Agent MemoryAI AgentsClaude CodeCodex CLIPython

Context Compaction Keeps Erasing Your Rules Right When Precision Matters

How compact-ledger captures verbatim user constraints, mid-session overrides, and failing test trajectories before compaction and re-injects them in about 50 milliseconds.

By Solomon Wakhungu6 min read
162 KB transcript11.7 msIn-process parse across 80 edit/test loops
Injected size~274 tok1,098 chars rendered from 162 KB log
Verification346 testsPlus 24/24 seeded eval cases in ~50 ms

What disappears the moment your session compacts

Forty minutes into a billing refactor, Claude Code compacts your conversation, and on the very next turn the agent starts editing database migrations you told it never to touch. A minute later it reintroduces a June 30 cutoff you already changed to July 31, then tries a broken fix whose exact test failure you already saw twenty minutes ago.

Lossy compaction summaries are fine for broad narrative context, but they quietly drop negative rules, blend mid-session corrections with the old brief, and erase exact assertion values from failing tests.

I built compact-ledger to preserve those exact details verbatim across compaction without calling another language model.

Why summarizing with another LLM misses the point

Compaction already uses an LLM to compress conversation history. Adding a second model call to write a 'better' summary still paraphrases your instructions, costs tokens, and adds seconds of wait time right when you want to keep moving.

What survives compaction should not be a softer paraphrase. It should be your exact words for rules and overrides, plus a structured list of observed test values and edit loops pulled straight from the session log.

That is why compact-ledger runs locally with no third-party dependencies and no LLM calls. On an Apple Silicon Mac, parsing a 162 KB transcript with 80 failing edit and test cycles takes 11.7 ms in-process, and the cold CLI hooks complete in 51 to 55 ms including Python startup.

Four priority tiers inside a strict character cap

In Claude Code, compact-ledger attaches to two lifecycle hooks (callbacks the harness triggers around compaction). Right before compaction runs, the PreCompact hook reads the session JSONL transcript (a line-by-line JSON log of every turn and tool call) and saves a clean snapshot in a local gitignored project folder. When the compacted session resumes, the SessionStart hook loads that snapshot and injects a compact Markdown block capped at 6,000 characters by default.

Compaction lifecycle
How compact-ledger carries rules and test trajectories across compaction
1. PreCompact Hook
Read JSONL Transcript
Linear scan of turns, user overrides, runner outputs, and file edits.
2. Atomic Store
Local Session Snapshot
File-locked JSON snapshot saved per session alongside manual pins.
3. SessionStart Hook
Bounded Markdown Block
Injected on compact or resume strictly inside the character budget.
Budget priority order (highest tier survives tightest caps)
Tier 1
Manual Pins & Overrides
Locked rules and superseding corrections.
Tier 2
User Constraints
One pin per rule, chatter stripped.
Tier 3
Test Trajectories
Observed values and edit-thrash warnings.
Tier 4
Modified Files
Deduplicated paths relative to repo root.
Snapshots are written atomically under a local gitignored project directory before compaction, then re-injected in strict priority order on resume without touching an LLM.
  1. Manual pins and active overrides: Rules pinned explicitly by you or the agent, plus mid-session corrections printed right next to the stale instruction they retired. Seeing both the live rule and what it superseded stops the compaction summary from reviving the old date or package manager.
  2. Active verbatim user constraints: Positive and negative directives split one pin per rule, even if four rules arrived in one opening brief. Casual chatter and harness-generated messages like hook feedback or system reminders are filtered out.
  3. Test failure trajectories and edit-thrash warnings: Parses pytest, vitest, jest, go test, and generic command failures, listing observed values oldest first and classifying each test as oscillating, stalled, progressing, single failure, or resolved. If an edit reverts an earlier change while tests keep failing, it emits an explicit thrash warning.
  4. Modified files summary: A deduplicated list of touched files, normalized relative to the project root.

The priority ordering matters when you tighten the character cap. Under a 400-character or 1,200-character limit, manual pins and overrides always win over auto-extracted rules, test histories, and file lists, and the output never exceeds the cap.

Handling rule overrides and oscillating tests

One subtle case tripped me up early: what happens when you set a broad negative rule and later change your mind? If turn one says 'Never use spaces' and turn twelve says 'Actually use two spaces instead of tabs', the override needs to retire that broad ban. At the same time, a scoped ban like 'Never use spaces in filenames' has to stay active.

Splitting long briefs into single-rule pins solved a related headache. Retiring the June 30 billing cutoff from a four-rule opening prompt now retires only that one sentence, leaving the migration freeze and Decimal money rule intact.

On the testing side, showing observed values in order makes dead ends obvious at a glance. Seeing a test move from 400 to 200 and back to 400 alongside a revert warning on the same file tells the post-compaction agent immediately not to try that same edit again. Across that 162 KB benchmark transcript with 80 failing cycles, the entire rendered ledger compresses down to 1,098 characters, roughly 274 tokens.

Fail-open hooks and where this stops

A memory hook should never break your coding session. Both hook commands fail open by default, exiting cleanly with empty output if stdin is malformed or a file disappears, and snapshots reject symlinks and quarantine corrupt JSON to timestamped backups rather than crashing.

Trade-offs and limits

Automatic compaction hooks are currently Claude Code native because Codex CLI does not expose a compaction hook yet. Codex rollouts (including code-mode exec and apply-patch events) still parse end-to-end through explicit snapshot and inject CLI commands. Also, automatic rule detection from free-form prose is heuristic, so use manual pins for any constraint you cannot afford to lose. Finally, compact-ledger is session-scoped compaction memory, not cross-session project memory.

Run the eval suite or wire it into your project

You can run the bundled 24-case deterministic evaluation suite anywhere without installing the package:

Run the 24-case eval suite
uvx compact-ledger eval

To install the CLI, wire PreCompact and SessionStart hooks into Claude Code, and pin a hard rule in your current session:

Install hooks and pin a rule
uv tool install compact-ledger
compact-ledger init --write
compact-ledger doctor
compact-ledger pin "Never push to main" --negative --tag git

The repository also ships as a no-setup Claude Code plugin and an installable agent skill so your agent remembers to pin rules as soon as you state them.

View all posts
Agent Verification · 6 min read

Your Coding Agent Cited Line 48 Without Ever Opening the File

Why I built a deterministic transcript verifier that checks file citations, quoted code, and 'no other callers' claims in under a millisecond without calling another model.

Read post
Agent Reliability · 7 min read

Stopping AI Agents from Double-Posting When Tools Time Out

Putting a local SQLite write-ahead journal, deterministic preflight rules, and read-only crash reconciliation in front of mutating MCP and CLI calls.

Read post
CLI & Guardrails · 6 min read

Giving AI Agents Safe Access to Discord Without MCP Schema Bloat

Why I built a REST-first Discord CLI with 89 commands, operator policy ceilings, offline dry-run confirmation tokens, and random-nonce prompt-injection boundaries.

Read post