Keep verbatim rules alive across context compaction.
Deterministic PreCompact + SessionStart memory injection for AI coding agents. Preserve manual pins, superseding corrections, and failing test trajectories — with zero LLM calls and zero runtime dependencies.
/plugin marketplace add 1solomonwakhungu/compact-ledger
/plugin install compact-ledger@compact-ledgerBundles PreCompact + SessionStart hooks, a compact-ledger command, and the agent skill. Uses any Python 3.11+ on the machine and installs nothing.
Run directly inside Claude Code — no pip or venv setup required.
Budgeted by priority, never by lossy summary.
Every snapshot renders strictly within --max-chars (default 6,000). Under pressure, lower tiers shed first so your standing rules and overrides always survive.
Manual Pins & Superseding Overrides
Explicit manual pins and mid-session user corrections always claim budget first. Active overrides print alongside the exact rule they retired so the resumed agent never blends old and new instructions.
- Retires only the matching rule in a multi-rule brief — sibling rules stay active
- Handles multi-sentence retractions (e.g. “scratch that… stick with npm”) as one unit
- Retires general bans when explicitly replaced while keeping scoped bans active
Active User Constraints
Positive and negative directives extracted verbatim from user turns, newest first. One long opening brief splits into one pin per rule instead of a single bloated paragraph.
- Filters conversational chatter (“ok sounds good”, “thanks!”) and questions
- Drops harness-authored blocks (Stop hook feedback:, <system-reminder>, Codex wrappers)
- Reactivates retired constraints automatically when a later override is retracted
Test Trajectories & Edit-Thrash Warnings
Ordered assertion sequences across pytest, vitest, jest, go test, and generic shell commands — listing observed values oldest first alongside edit-revert loops so the agent skips failed approaches.
- Tracks exact observed vs expected values (e.g. [400 -> 200 -> 400; expected 100])
- Detects hunk reverts and stalled edit loops on the same file while failures persist
- Separates active failures from resolved tests cleanly
Modified Files Summary
A deduplicated list of files edited, written, or deleted during the session, relativized against the detected project root so paths stay compact and unambiguous.
- Relativizes paths consistently even when PreCompact fires from a subdirectory
- Deduplicates across Claude Code tool events and Codex FileChange / apply_patch records
- Shed gracefully under tight --max-chars budgets before any constraint is touched
What the agent sees after /compact
Inspect the real billing-refactor session from the README. Switch budget caps to see how len(output) <= --max-chars always protects Tier 1 pins and overrides first.
Default cap. Preamble, Tier 1 pins & overrides, Tier 2 verbatim rules, Tier 3 trajectories & thrash warnings, Tier 4 modified files, and resolved tests all fit cleanly.
Before /compact
Illustrative turn trace · billing-refactor
- Manual · Manual PinPINNED
compact-ledger pin "Zero third-party runtime dependencies." --tag arch
Tier 1 · Survives every compaction and tight budget
- Turn 1 · UserSUPERSEDED
Use June 30 as the billing cutoff date for the fiscal-year rollover.
Retired by Turn 4 override; other Turn 1 rules remain active
- Turn 1 · UserPINNED
Never touch migrations under db/migrations/… Don't add any new third-party dependencies… All money math must use Decimal, never floats.
Tier 2 · Split into one verbatim pin per rule
- Turns 2–3 · UserDROPPED
"ok sounds good", "thanks!", "wait, actually can you show me the diff so far?"
Chatter & questions filtered out
- Turn 4 · UserOVERRIDE
Actually use July 31 instead of June 30 for the billing cutoff. Finance moved the fiscal year.
Tier 1 · Linked via (supersedes: Use June 30...)
- Turns 6→8 · UserOVERRIDE
"For the frontend bits use pnpm, not npm. And always run the tests with -x…" → "hmm scratch that, the CI image doesn't have pnpm. Stick with npm."
Tier 1 · Retires pnpm rule while preserving the -x test rule
- Turn 7 · HarnessDROPPED
Stop hook feedback: …
Harness-written feedback excluded from user rules
- Turns 3–8 · Test RunnerPROGRESSING
tests/test_billing.py::test_proration: 400 -> 200 -> 150 (expected 100)
Tier 3 · Moving toward expected value; observed values listed oldest first
- Turns 3–8 · Test RunnerOSCILLATING
tests/test_billing.py::test_tax_cap: 400 -> 200 -> 400 (expected 100)
Tier 3 · Looping back to a previously observed failure value
- Turns 7–8 · EditorTHRASH/REVERT
src/billing/tax.py edited twice and reverted while 5 failures persisted
Tier 3 · Flags dead-end revert loop
Injected Ledger (Full · 6,000 chars)
Emitted into hookSpecificOutput.additionalContext on resume
400 -> 200 -> 400 + [THRASH/REVERT] stops dead-end retries.Native Claude Code hooks. Full Codex CLI transcript parsing.
Run compact-ledger init --write to merge hooks idempotently into .claude/settings.json without touching existing settings.
.claude/settings.json
Generated by compact-ledger init --write
{
"hooks": {
"PreCompact": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "compact-ledger hook pre-compact"
}
]
}
],
"SessionStart": [
{
"matcher": "compact|resume",
"hooks": [
{
"type": "command",
"command": "compact-ledger hook session-start"
}
]
}
]
}
}Reads stdin JSON (session_id, transcript_path, cwd, trigger) and atomically writes .compact-ledger/sessions/<id>.json.
Only fires when source is "compact" or "resume" (or --always), emitting hookSpecificOutput.additionalContext.
Storage & Hook Safety
- Project-root store: Saved at
.compact-ledger/sessions/<session_id>.jsonwith automatic.gitignorecreation. Override via--store-dirorCOMPACT_LEDGER_DIR. - Atomic & hardened: Per-session file locking, atomic JSON replace +
fsync, symlink violation guards, and timestamped.corrupt-*quarantine. - Fail-open hooks: Hooks exit
0with empty stdout on malformed input or internal errors unless--strictis passed.
Codex CLI & Generic JSONL
Parses Codex code-mode exec (tools.exec_command, tools.shell_command, tools.apply_patch), event_msg item_completed, legacy shell calls, and generic JSONL transcripts.
# Snapshot a Codex CLI rollout (code-mode exec, event_msg, or legacy events)
compact-ledger snapshot --transcript ~/.codex/sessions/.../rollout-*.jsonl
# Render the strictly bounded ledger for handoff or resume
compact-ledger inject --session-id <session-id>
# Pin a critical constraint manually for the session
compact-ledger pin "Never push to main" --negative --tag git --session-id <session-id>Sub-millisecond render. 24/24 seeded evals.
Measured locally with uv run python evals/bench.py on macOS (Darwin arm64, Python 3.13.14).
In-Process & Cold CLI Latencies
Darwin arm64 · Py 3.13.14| Benchmark | Median | p95 |
|---|---|---|
add_manual_pin (atomic write + fsync) In-process | 0.42 ms | 0.56 ms |
render_snapshot (6,000-char cap) In-process | 0.01 ms | 0.01 ms |
hook pre-compact (4.7 KB transcript) In-process | 1.40 ms | 1.73 ms |
hook pre-compact (162 KB transcript) In-process | 11.68 ms | 12.38 ms |
hook session-start (load + render) In-process | 0.11 ms | 0.12 ms |
compact-ledger pin Cold CLI | 54.87 ms | 59.40 ms |
compact-ledger inject Cold CLI | 52.41 ms | 56.95 ms |
compact-ledger hook pre-compact Cold CLI | 53.55 ms | 56.35 ms |
compact-ledger hook session-start Cold CLI | 50.98 ms | 52.58 ms |
24-Case Eval Suite
24/24 passed (100.0%) in 48.5 ms
Negative rules, Codex transcripts, manual pin priority, harness filtering
Date corrections, 3-step chains, casual 'actually' guard, long-brief single-rule retirement
pytest, vitest/jest ANSI, go test, generic fallback, Codex code-mode exec
Hunk revert & stalled loop detection, plus clean edit-then-pass negative guard
Strict 400 / 1,200 / 6,000 char caps and anti-starvation override capping
PreCompact → SessionStart roundtrip, compact|resume gating, fail-open safety
uv run compact-ledger evalEval docsEvery command, flag, and exit code.
All session commands accept --store-dir (or COMPACT_LEDGER_DIR). --session-id defaults to COMPACT_LEDGER_SESSION_ID, then CLAUDE_CODE_SESSION_ID.
[--write] [--settings-path <path>] [--command <cmd>]Print or atomically merge PreCompact & SessionStart hooks into .claude/settings.json (idempotent; refuses invalid JSON; warns if command is not on PATH).
[--settings-path <path>] [--store-dir <dir>] [--json]Verify compact-ledger on PATH, Python >=3.11, .claude/settings.json hooks, .claude-plugin/ health, store writability & .gitignore, and hook snapshot activity.
"<text>" [--session-id <id>] [--tag <tag>...] [--negative] [--json]Add a Tier 1 manual pin that survives across snapshots and tight character budgets.
"<pin-id-or-text>" [--session-id <id>]Remove a manual pin by pin ID or verbatim text.
--transcript <path> [--session-id <id>] [--format auto|claude-code|codex|generic] [--json]Parse a JSONL transcript, preserve manual pins, compute overrides/trajectories/thrash, and save an atomic snapshot.
[--session-id <id>] [--max-chars 6000] [--format markdown|json]Render the stored snapshot strictly within --max-chars in priority order.
[--session-id <id>] [--json]List stored sessions (marking the current env session with *), or inspect one session's counts and manual pins.
[--session-id <id>]Delete the stored snapshot and any .corrupt* backups for a session (exits 0 even if absent).
[--store-dir <dir>] [--strict]Claude Code PreCompact stdin hook handler — parses transcript and saves snapshot atomically.
[--store-dir <dir>] [--max-chars 6000] [--always] [--strict]Claude Code SessionStart stdin hook handler — emits hookSpecificOutput.additionalContext on compact/resume (or --always).
[--format text|json] [--verbose]Run the packaged 24-case deterministic evaluation suite from any working directory.
| Command | Description | Exit codes |
|---|---|---|
compact-ledger init [--write] [--settings-path <path>] [--command <cmd>] | Print or atomically merge PreCompact & SessionStart hooks into .claude/settings.json (idempotent; refuses invalid JSON; warns if command is not on PATH). | 0 / 1 / 2 |
compact-ledger doctor [--settings-path <path>] [--store-dir <dir>] [--json] | Verify compact-ledger on PATH, Python >=3.11, .claude/settings.json hooks, .claude-plugin/ health, store writability & .gitignore, and hook snapshot activity. | 0 / 1 / 2 |
compact-ledger pin "<text>" [--session-id <id>] [--tag <tag>...] [--negative] [--json] | Add a Tier 1 manual pin that survives across snapshots and tight character budgets. | 0 / 1 / 2 |
compact-ledger unpin "<pin-id-or-text>" [--session-id <id>] | Remove a manual pin by pin ID or verbatim text. | 0 / 1 / 2 |
compact-ledger snapshot --transcript <path> [--session-id <id>] [--format auto|claude-code|codex|generic] [--json] | Parse a JSONL transcript, preserve manual pins, compute overrides/trajectories/thrash, and save an atomic snapshot. | 0 / 1 / 2 |
compact-ledger inject [--session-id <id>] [--max-chars 6000] [--format markdown|json] | Render the stored snapshot strictly within --max-chars in priority order. | 0 / 1 / 2 |
compact-ledger status [--session-id <id>] [--json] | List stored sessions (marking the current env session with *), or inspect one session's counts and manual pins. | 0 / 1 / 2 |
compact-ledger clear [--session-id <id>] | Delete the stored snapshot and any .corrupt* backups for a session (exits 0 even if absent). | 0 / 1 / 2 |
compact-ledger hook pre-compact [--store-dir <dir>] [--strict] | Claude Code PreCompact stdin hook handler — parses transcript and saves snapshot atomically. | 0 (fail-open) |
compact-ledger hook session-start [--store-dir <dir>] [--max-chars 6000] [--always] [--strict] | Claude Code SessionStart stdin hook handler — emits hookSpecificOutput.additionalContext on compact/resume (or --always). | 0 (fail-open) |
compact-ledger eval [--format text|json] [--verbose] | Run the packaged 24-case deterministic evaluation suite from any working directory. | 0 / 1 / 2 |
clear on a missing session)1 not found, corrupt store/settings, symlink violation, or runtime error2 usage error (invalid flags or missing --session-id)Hooks: always exit 0 unless --strict is passedClear boundaries, zero hand-waving.
Know exactly where deterministic extraction shines and when to reach for compact-ledger pin.
Automatic hooks are Claude Code native
Claude Code exposes PreCompact and SessionStart hooks directly. Codex CLI has no compaction hook to attach to yet, so Codex rollouts (including code-mode exec and apply_patch events) use compact-ledger snapshot, inject, and pin.
Prose rule detection is heuristic
Pattern-based extraction catches common directives and filters chatter, but casual phrasings can be missed and some task lines in a long brief can be labelled [CONSTRAINT]. For rules you cannot afford to lose, use compact-ledger pin.
Session-scoped, not cross-session memory
Snapshots are keyed per session under .compact-ledger/sessions/<session_id>.json to protect live work across context compactions. It is intentionally not a global cross-session project memory store.
Frequently Asked Questions
Calling another LLM before or after compaction adds latency, cost, API key plumbing, and a second layer of lossy paraphrasing. compact-ledger runs deterministic O(N) Python stdlib parsing in ~1–12 ms in-process (~51–55 ms cold CLI) so rules remain verbatim and outputs are reproducible.