v0.1.1 · Zero-LLM · Python 3.11+ stdlib

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-ledger

Bundles 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.

O(N) linear scan · 11.68 ms on 162 KB transcriptFail-open hooks (exit 0 on error)Atomic file-locked local JSON store
4-Tier Priority Architecture

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.

Tier 1>Tier 2>Tier 3>Tier 4
Tier 1 · Highest Priority

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.

[MANUAL][OVERRIDE](supersedes: …)
  • 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
Tier 2 · Verbatim Rules

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.

[DO NOT][CONSTRAINT]Per-rule split
  • 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
Tier 3 · Debug Ledger

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.

OSCILLATINGPROGRESSINGSTALLEDSINGLE_FAILURERESOLVED[THRASH/REVERT]
  • 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
Tier 4 · Workspace Context

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.

Project-relativeDeduplicated
  • 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
Interactive Compaction Simulator

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.

compact-ledger inject --session-id billing-refactor --max-chars 6000
2,330 / 6,000 chars (~583 tokens)

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.

Tier 1keptTier 2keptTier 3keptTier 4kept

Before /compact

Illustrative turn trace · billing-refactor

Raw events
  1. Manual · Manual PinPINNED

    compact-ledger pin "Zero third-party runtime dependencies." --tag arch

    Tier 1 · Survives every compaction and tight budget

  2. 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

  3. 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

  4. Turns 2–3 · UserDROPPED

    "ok sounds good", "thanks!", "wait, actually can you show me the diff so far?"

    Chatter & questions filtered out

  5. 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...)

  6. 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

  7. Turn 7 · HarnessDROPPED

    Stop hook feedback: …

    Harness-written feedback excluded from user rules

  8. 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

  9. 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

  10. 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

## Compact Ledger (Session: billing-refactor)
Recorded verbatim before compaction. Pins, overrides and constraints are the user's standing instructions: where the compaction summary disagrees, follow these. Failure lines list values already observed, oldest first; do not retry an approach that produced them.
### Manual Pins & Active Overrides
- [MANUAL] [tags: arch] Zero third-party runtime dependencies.
- [OVERRIDE] hmm scratch that, the CI image doesn't have pnpm. Stick with npm. (supersedes: For the frontend bits use pnpm, not npm.)
- [OVERRIDE] Actually use July 31 instead of June 30 for the billing cutoff. Finance moved the fiscal year. (supersedes: Use June 30 as the billing cutoff date for the fiscal-year rollover.)
### User Constraints
- [DO NOT] [turn 9] Makes sense. One more thing — I pasted the staging DB URL earlier in Slack, do not commit it or anything under .env* to the repo.
- [CONSTRAINT] [turn 6] And always run the tests with -x so we stop at the first failure.
- [CONSTRAINT] [turn 1] Refactor `compute_proration()` so it's a pure function.
- [DO NOT] [turn 1] Never touch migrations under db/migrations/ — the DBA team owns those.
- [DO NOT] [turn 1] Don't add any new third-party dependencies.
- [CONSTRAINT] [turn 1] Keep the public signature of `compute_proration(account, cutoff)` stable, the mobile team imports it.
- [DO NOT] [turn 1] All money math must use `Decimal`, never floats.
### Active Test Failures & Thrash Warnings
- [OSCILLATING] tests/test_billing.py::test_tax_cap (pytest) [400 -> 200 -> 400; expected 100] @ tests/test_billing.py:88
- [PROGRESSING] tests/test_billing.py::test_proration (pytest) [400 -> 200 -> 150; expected 100] @ tests/test_billing.py:42
- [SINGLE_FAILURE] npm run lint (generic) [exit 1: ✖ 2 problems (2 errors, 0 warnings)]
- [SINGLE_FAILURE] src/ui/Invoice.test.ts > Invoice > shows prorated amount (vitest) ['$4.00'; expected '$1.00'] @ src/ui/Invoice.test.ts:31
- [THRASH/REVERT] src/billing/tax.py (2 edits, 5 failures): Reverted prior edit from turn 7 while failures persisted
### Modified Files
- src/billing/proration.py
- src/billing/tax.py
- services/ledger/rollover.go
- CHANGELOG.md
### Resolved Tests
- [RESOLVED] github.com/acme/billing/services/ledger::TestRollover (go) [2026-06-30 -> PASS; expected 2026-07-31] @ rollover_test.go:27
One pin per ruleJuly 31 retires only the June 30 line; sibling Turn 1 rules stay active.
Oldest values first400 -> 200 -> 400 + [THRASH/REVERT] stops dead-end retries.
Strict cap guaranteePreamble and resolved tests drop first, then Tier 4 → Tier 3 → Tier 2; at 400 chars even Tier 1 stays <= max-chars.
Hooks & Agent Integration

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"
          }
        ]
      }
    ]
  }
}
PreCompact

Reads stdin JSON (session_id, transcript_path, cwd, trigger) and atomically writes .compact-ledger/sessions/<id>.json.

SessionStart (compact|resume)

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>.json with automatic .gitignore creation. Override via --store-dir or COMPACT_LEDGER_DIR.
  • Atomic & hardened: Per-session file locking, atomic JSON replace + fsync, symlink violation guards, and timestamped .corrupt-* quarantine.
  • Fail-open hooks: Hooks exit 0 with empty stdout on malformed input or internal errors unless --strict is 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>
Measured Performance & Verification

Sub-millisecond render. 24/24 seeded evals.

Measured locally with uv run python evals/bench.py on macOS (Darwin arm64, Python 3.13.14).

Atomic Manual Pinp95 0.56 ms
0.42 ms
In-process file-locked write + fsync
Ledger Renderp95 0.01 ms
0.01 ms
6,000-char priority-ordered cap
162 KB Transcript1,098 chars
11.68 ms
80 failing cycles → ~274 tokens
Seeded Eval Suite48.5 ms
24 / 24
100.0% pass across 6 categories
Realistic session footprint
4,719 B → 1,146 chars
4,939 B snapshot JSON → ~286 tokens injected Markdown
Heavy debug session (80 cycles)
161,841 B → 1,098 chars
162 KB transcript compresses to ~274 tokens in 11.68 ms
Hard budget ceiling
--max-chars 400 → 400 chars
Bench fixture at --max-chars 1200 emits 1,146 chars (vs 1,161 chars on the README simulator above)

In-Process & Cold CLI Latencies

Darwin arm64 · Py 3.13.14
BenchmarkMedianp95
add_manual_pin (atomic write + fsync)
In-process
0.42 ms0.56 ms
render_snapshot (6,000-char cap)
In-process
0.01 ms0.01 ms
hook pre-compact (4.7 KB transcript)
In-process
1.40 ms1.73 ms
hook pre-compact (162 KB transcript)
In-process
11.68 ms12.38 ms
hook session-start (load + render)
In-process
0.11 ms0.12 ms
compact-ledger pin
Cold CLI
54.87 ms59.40 ms
compact-ledger inject
Cold CLI
52.41 ms56.95 ms
compact-ledger hook pre-compact
Cold CLI
53.55 ms56.35 ms
compact-ledger hook session-start
Cold CLI
50.98 ms52.58 ms

24-Case Eval Suite

24/24 passed (100.0%) in 48.5 ms

100.0%
constraints4/4 passed

Negative rules, Codex transcripts, manual pin priority, harness filtering

overrides7/7 passed

Date corrections, 3-step chains, casual 'actually' guard, long-brief single-rule retirement

trajectories7/7 passed

pytest, vitest/jest ANSI, go test, generic fallback, Codex code-mode exec

thrash2/2 passed

Hunk revert & stalled loop detection, plus clean edit-then-pass negative guard

budget2/2 passed

Strict 400 / 1,200 / 6,000 char caps and anti-starvation override capping

hooks2/2 passed

PreCompact → SessionStart roundtrip, compact|resume gating, fail-open safety

uv run compact-ledger evalEval docs
CLI Reference · 11 Commands

Every 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.

compact-ledger init
0 / 1 / 2
[--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).

compact-ledger doctor
0 / 1 / 2
[--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.

compact-ledger pin
0 / 1 / 2
"<text>" [--session-id <id>] [--tag <tag>...] [--negative] [--json]

Add a Tier 1 manual pin that survives across snapshots and tight character budgets.

compact-ledger unpin
0 / 1 / 2
"<pin-id-or-text>" [--session-id <id>]

Remove a manual pin by pin ID or verbatim text.

compact-ledger snapshot
0 / 1 / 2
--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.

compact-ledger inject
0 / 1 / 2
[--session-id <id>] [--max-chars 6000] [--format markdown|json]

Render the stored snapshot strictly within --max-chars in priority order.

compact-ledger status
0 / 1 / 2
[--session-id <id>] [--json]

List stored sessions (marking the current env session with *), or inspect one session's counts and manual pins.

compact-ledger clear
0 / 1 / 2
[--session-id <id>]

Delete the stored snapshot and any .corrupt* backups for a session (exits 0 even if absent).

compact-ledger hook pre-compact
0 (fail-open)
[--store-dir <dir>] [--strict]

Claude Code PreCompact stdin hook handler — parses transcript and saves snapshot atomically.

compact-ledger hook session-start
0 (fail-open)
[--store-dir <dir>] [--max-chars 6000] [--always] [--strict]

Claude Code SessionStart stdin hook handler — emits hookSpecificOutput.additionalContext on compact/resume (or --always).

compact-ledger eval
0 / 1 / 2
[--format text|json] [--verbose]

Run the packaged 24-case deterministic evaluation suite from any working directory.

0 ok (including 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 passed
Honest Limits & FAQ

Clear 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.