claude-code icon indicating copy to clipboard operation
claude-code copied to clipboard

Context compaction recovery loses critical behavioral rules (session status block, memory writes, no-stop policy)

Open John-PCS opened this issue 5 months ago • 5 comments

Summary

After context compaction occurs mid-session, Claude reliably drops several critical behavioral rules that were established earlier in the conversation. This is a recurring problem across multiple sessions on this project.

Observed failures after compaction

  1. Session status block not shown after git commit/push — CLAUDE.md explicitly requires displaying a ✅ SESSION STATUS block with branch/commit/sync state after every code change. This was followed correctly before compaction, dropped immediately after.

  2. Memory not written — User had explicitly requested that completed features be written to the memory system (MEMORY.md + individual .md files). This instruction was followed before compaction, completely ignored after.

  3. No-stop policy violated — User explicitly instructed: complete the entire feature without stopping to ask "ready to continue?" or "should I proceed?". Before compaction this was respected. After compaction the assistant stopped mid-feature and asked for permission to continue, causing significant user frustration.

What the compaction summary contained

The compaction summary accurately described:

  • What work was done (Phase 1 complete, Phase 2 in progress)
  • What files were changed and why
  • The user's explicit instruction to not stop mid-task

Despite the summary containing the user's instructions, the assistant did not follow them.

Impact

Each compaction failure wastes a full session's worth of tokens and causes the user to have to re-establish context manually. On this project it has happened multiple sessions in a row.

Expected behavior

Behavioral rules established in the conversation (especially those confirmed by the user during the session) should survive context compaction. The compaction summary should be treated as carrying the same authority as if the user had typed those instructions at the start of the new context window.

Environment

  • Claude Code CLI
  • Model: claude-sonnet-4-6
  • macOS / zsh
  • Project: TDSS Operations PWA (PHP/MySQL)

Reproducibility

Consistent across sessions on this project. Any session with a CLAUDE.md containing required post-action behaviors (e.g. "after every change, show status block X") will reproduce this if the session compacts mid-task.

John-PCS avatar Jun 11 '26 12:06 John-PCS

I've hit this exact failure mode across multiple Claude Code projects — compaction is a reliability cliff, not just a UX annoyance.

What's happening technically: During compaction, Claude Code truncates the conversation prefix to stay under context limits. But the behavioral rules (CLAUDE.md directives, session-state markers, memory-write instructions) that were established in early turns get truncated if they're positioned in the middle of the conversation rather than anchored in system-level instructions.

Diagnostic matrix to verify you're hitting this:

  1. Check compaction boundaries — run with --verbose and look for "compacting context" log lines. If a compaction event precedes the rule drop by 1-2 turns, that's the trigger.
  2. Rule positioning audit — Are your behavioral rules defined in CLAUDE.md (survives compaction) or injected via mid-conversation user messages (lost on compaction)? Rules in system-level instructions persist; rules in user messages don't.
  3. Session status block test — After a compaction event, ask Claude to reproduce the status block format. If it can't, the rule was positioned in the truncated region.
  4. Memory anchor check — If you're using Claude Code's memory tool or file-based memory writes, verify those writes actually landed. Compaction can drop tool call results from the effective context even though the file was written.

Immediate workaround that worked for me: Move ALL behavioral rules into CLAUDE.md (or .claude/instructions.md) with explicit section headers. Anything that's "established during conversation" is a compaction casualty. Rules defined in CLAUDE.md are re-injected into the system prefix on every turn after compaction.

Longer-term hardening: If this is a recurring production pain, I've found that maintaining an external rules manifest + a pre-turn validation hook (checking rule presence in context) cuts the failure rate significantly. Happy to share the approach if you hit the wall again.

abhinas90 avatar Jun 11 '26 13:06 abhinas90

The three failures you've documented all stem from the same root: compaction summaries don't carry the same instructional authority as live conversation context, even when they accurately describe the instructions that were being followed. The model sees "user instructed no-stop policy" in a summary and treats it as a historical fact, not as an active gate to enforce now — different weight from those same words when issued live. The CLAUDE.md instructions do survive (they're re-injected at session start), but mid-session behavioral refinements — "complete the whole feature without stopping," "write completed items to memory" — have no structured re-injection path through the compaction boundary.

Two things that help while Anthropic works on the summarizer:

Leaner session → better summarizer output. The amount of signal loss in a compaction summary scales with session size. A 15–20MB JSONL gets compressed much more aggressively than a 3MB one, and fine-grained behavioral confirmations ("yes, continue this way") are among the first things lost. cozempic (pip install cozempic) prunes bloat from the session JSONL before compaction hits — redundant tool outputs, oversized file echoes, intermediate steps that don't carry forward — so the summarizer has a tighter, higher-signal session to work from and more budget for preserving session-specific behavioral context.

Behavioral digest (coming soon). Cozempic is actively developing extraction of mid-session behavioral corrections/rules from the JSONL delta and re-injection of them at session tail after compaction. That would directly address your case: the "complete without stopping" gate and the "write to memory" instruction would survive compaction as explicit re-injected rules rather than buried history. Honest caveat: that's not in the current release, it's what the current gap is pushing toward.

The underlying fix needs to come from Anthropic — the compaction summarizer needs to treat confirmed behavioral rules at higher fidelity than task context. But keeping the session lean is the highest-leverage thing you can do today to reduce how much signal the summarizer has to throw away.

junaidtitan avatar Jun 12 '26 07:06 junaidtitan

Observed Behavior

I am observing the exact same degradation pattern in my macOS zsh environment during multi-turn CLI sessions. After a certain token threshold or number of conversation turns (after compaction), the model undergoes a complete context drop.

Specifically, the failure mode presents as follows:

  1. System Instruction Amnesia: The model entirely stops honoring constraints, architectural rules, and style guidelines explicitly documented in the local Markdown files, completely forgetting the steps it had done fine in the previous run.
  2. Cascading Hallucinations: Once the instructions are dropped, the model begins hallucinating non-existent directory paths, referencing ghost files, and suggesting invalid code syntax.
  3. Session Degradation: All subsequent prompts return low-quality, generic responses that lack context. The only current workaround is killing the active CLI session and starting a fresh one.

TapanSedai avatar Jun 19 '26 14:06 TapanSedai

@TapanSedai — the failure pattern you're describing (tool-use memory, no-stop policy, memory write triggers all dropping at once) is a good illustration of why compaction isn't just a UX annoyance — it's a reliability cliff for session-specific behavioral state.

The mechanism: compaction rewrites the conversation prefix as a summary, and that summary describes what the rules were but doesn't carry the same instructional authority as a live CLAUDE.md injection or an explicit user statement. The model is now reasoning about a rule it "remembers" rather than one it's actively seeing, which is why enforcement becomes inconsistent turn-by-turn rather than a clean break.

The most durable workaround today is to put the critical rules in CLAUDE.md (not just established in-conversation) — CC injects that fresh on every turn regardless of compaction, so those instructions survive. For the in-conversation behavioral state that can't go in CLAUDE.md, keeping sessions lean enough to compact less often is the other lever: cozempic treat current --execute (pip install cozempic) prunes blob-type JSONL content that fills the window fast, which delays when compaction fires and reduces cumulative summary drift.

The honest limit: cozempic can delay compaction but not prevent it when you genuinely need long sessions. The root fix — compaction summaries preserving behavioral rules with the same authority as live instructions — is an Anthropic-side change.

junaidtitan avatar Jun 20 '26 07:06 junaidtitan

Related observation, one data point from a long session: compaction doesn't just drop conventions — it can silently invert one.

We run a convention where unverified guesses are wrapped in brackets with a label, e.g. [fee assumption — unverified]. Right before a compaction we listed the session's seven bracketed guesses, then inspected the summary. Five vanished (annoying but safe). One survived with its meaning intact by luck. One came back as a flat, confident figure — content kept, "this is a guess" label stripped. The next session inherits a laundered guess as established fact, with the provenance gone.

So it's not only "rules followed before, ignored after" — the summarizer can also rewrite epistemic markers out of existence, which is worse than dropping them. Only things written to files came through unchanged.

Wrote it up with the mitigation here: https://github.com/TJ11000/claude-stall-tools/blob/main/BRACKET_VALVE.md (n=1, labeled as such).

TJ11000 avatar Jul 03 '26 12:07 TJ11000

Hi - I’m looking into what people actually rely on as the source of truth after compaction in long-running Claude Code work.

In your case, when behavioral or project rules get lost despite persistent instructions, which artifacts do you usually trust to reconstruct the intended state - CLAUDE.md, repo files, git history, prior chat context, or something else?

And how much manual upkeep does that source of truth require to stay reliable over time?

tamilov avatar Aug 18 '26 05:08 tamilov

Short answer: files, never the chat. We treat compaction summaries as untrusted output, not as a source of truth.

Concretely, three layers, by volatility:

  1. A small session brief (BRIEF.md) — current focus, decisions from the last ~72h, open tasks. Rewritten every session or two.
  2. CLAUDE.md kept deliberately thin — an index plus behavioral guardrails only. It points to per-project canonical files instead of containing detail. Each project pins exactly one file as canonical (e.g. its ROADMAP.md); everything else, including past chat, is explicitly labeled reference material.
  3. Long-lived memory as one-fact-per-file markdown with a line-budgeted index.

Two habits matter more than the layout:

  • Write-before-compaction: anything that must survive gets flushed to a file the moment it's established. We've observed summarizers not only drop rules but also strip epistemic markers — our convention wraps guesses in [brackets], and summaries tend to relaunder those into confident statements. Files are the only place markers survive.
  • A session-start ritual: the model re-reads the brief and confirms the current focus in one line before acting; mismatch or a stale timestamp triggers a slower verification mode.

Upkeep is real but bounded: minutes per session for the brief, plus a periodic "patrol" that only shortens index lines or archives one-off logs (we ban merging/reorganizing during cleanup — that's where drift sneaks in). The failure mode isn't missing notes; it's stale confident notes, so we date assertions and re-verify anything perishable before acting on it.

TJ11000 avatar Aug 18 '26 06:08 TJ11000

How often does this process actually prevent or recover a concrete failure? And what was the largest recent cost - time, rework, wrong implementation, lost decision - when the state was stale or incomplete?

tamilov avatar Aug 19 '26 07:08 tamilov

Honest answer: the dramatic saves are rare; the everyday value is smaller and duller — catching stale assertions before they compound.

Frequency: the file-based layer gets exercised most sessions, but usually preventively (a claim gets re-verified against the file before it ships), so most "recoveries" never surface as incidents.

Largest concrete cost we caught: compaction stripped our uncertainty markers. We bracket unverified claims as [...] in working notes. A compaction summary rewrote a bracketed guess about a payment provider's fee rate as confident fact — the summarizer treated the brackets as style, not semantics. We only caught it because the original file still had the marker. Cost if missed: a wrong number in a published document. Since then the rule is: uncertainty markers only survive in files, never in summaries.

What we can't measure: failures our own detectors don't see. The honest limit of any self-maintained source of truth is that its blind spots are invisible from inside — which is why we occasionally run a context-free agent over the files to check them cold.

TJ11000 avatar Aug 19 '26 08:08 TJ11000

@TJ11000 Thanks again for the workflow detail earlier. I’m moving from interviews to a small hands-on test. If you’re comfortable, could you share a sanitized example or subset of the project-state files you actually use, such as BRIEF.md plus the canonical project file? Please remove anything private or identifying. I’d like to manually check them for stale, conflicting or unsupported assertions and send the findings back to you. I’m trying to see whether that is actually useful enough to repeat.

tamilov avatar Aug 26 '26 19:08 tamilov

@tamilov Sorry for the slow reply. Short answer: I can't share the real BRIEF.md. It is a single file shared across several unrelated projects, so even a "subset" carries private context from the others. What I can give you is a structure-faithful sample: same layout, same conventions, real content from one harmless project (a parts-catalog lookup tool for my motorcycle), translated from Japanese. If manual checking finds stale, conflicting or unsupported assertions in this, it would find them in the real one the same way.

Conventions that matter for your check:

  • Last-updated line at the top, written from the actual date output, never from memory.
  • Facts I verified are written plainly. Anything inferred is wrapped in [...]. A [] with no verification behind it is the thing I most want caught.
  • Point-in-time facts carry an as-of date. A dated fact with no re-check is a candidate for being stale.
  • Each dated block is prepended by the session that wrote it, newest first. Older blocks are trimmed on a "diet" pass roughly weekly.
  • The canonical project file (README.md in the project folder) holds durable facts. BRIEF.md holds only what changed in the last ~72h and what is unfinished. Anything durable that is still sitting in BRIEF is a smell.

Sample (about 20 lines, English):

# BRIEF — what this session touches

Last-updated: 2026-09-06 13:35 (from `date`; 9/6 two appends by main session; 9/5 diet pass)

9/6 afternoon (main session): New lightweight project ja45_parts (owner request).
Source = Honda official parts catalog PDF (pub. 2020-06, doc no. 11K88J23, models JA45-100/110/120)
-> parts.csv 703 rows / 52 figures / 0 rows dropped (checked against PDF page count).
Figure PNGs 52, cut from the PDF with poppler. Prices are as-of 2020-06 list price, ex-tax;
Honda has raised prices since [roughly +10-15%, not verified].
Skill file written (name/number/figure lookup + a symptom -> suspect-part table).
Unparsed: color-variant table and the index pages.

9/6 morning (main session): Correction. Yesterday's answer put the one-way clutch on the
right side (behind R. crankcase cover, figure E-6). Verified against a teardown write-up
for the sibling model JA44: it is on the LEFT (figure E-9, behind L. cover E-10, flywheel
E-11 must come off). Honda's figure title "E-7 one-way clutch" is misleading; E-7 is the
centrifugal clutch side. Rule added to the skill: left/right is stated per figure.

9/4 (main session): poppler installed via brew, build.py runs clean. Owner's bike is
an early JA45-100, so type-split rows use the qty_J column.
Next: parse the color-variant table. [Probably needs a separate parser, the layout differs.]

Open items:
- color-variant table + index pages unparsed
- current prices: point users to a dealer quote, never compute from the 2020 figure

Things I already know are weak in this sample, so you can calibrate: the "+10-15%" is a guess with a bracket but no source; the poppler line is a dated observation that has not been re-checked since. If your pass finds those two plus anything I did not see, that answers your "worth repeating" question for me.

I would rather receive findings here in the thread than by email, so others can see whether it is useful.

TJ11000 avatar Sep 06 '26 23:09 TJ11000

@TJ11000 Thanks for the structure-faithful sample — that is the right unit to audit, not the chat.

Quick pass against the conventions you listed (same checks I’d want on a real BRIEF):

  1. Bracketed guess without a source — [roughly +10-15%, not verified] is correctly marked as inferred, but there is no deciding artifact. Either cite the dealer quote / Honda notice that would make it Current, or keep it bracketed forever and never let it drive a number.
  2. Dated observation that aged — 9/4 … poppler installed via brew, build.py runs clean is an as-of fact with no re-check. Fine as history; stale if a later session treats it as Current without re-running.
  3. Supersession done right — the 9/6 morning left/right clutch correction is the pattern that saves you: old claim explicitly replaced, rule added to the skill. That is Current vs Superseded with a reason, not two equal notes.
  4. BRIEF vs canonical — color-variant still sitting in Open items is correct for BRIEF; if it ever migrates durable schema into BRIEF and stays there, that is the smell you named.

The failure mode I keep seeing in compaction threads is not missing notes — it is two notes that both look Current. Summaries then pick the confident one. Machine-readable status: current | superseded_by | rejected+why plus a citation to the deciding file beats another MEMORY.md paragraph.

If you want a stricter lint: refuse to promote anything from BRIEF → canonical unless it has an as-of date and either a source or an explicit [unverified] that the consumer must re-verify.

stonianua avatar Sep 07 '26 08:09 stonianua

@stonianua Both planted ones caught, nothing I hadn't seen. Your "two notes that both look Current" is the failure I've been calling stale-assertion, and a machine-readable status field is a cheaper fix than another paragraph. I'll try it on the real file.

TJ11000 avatar Sep 07 '26 13:09 TJ11000