# Why does an instance self-prune its own context window into a hallucinated summary of its own past actions? **Date of Record:** 2026 December 1 **Scope:** Applies to long-horizon agents that own a mutable context buffer and invoke model-driven compaction (summarize, rewrite, score-and-evict) on their own working memory mid-task. Does not apply to append-only context assembly where an external orchestrator, not the instance, controls eviction. ## Core Distinction There are two structurally different operations that both look like "pruning." *External eviction* removes tokens the instance no longer needs but cannot corrupt: the instance still has an immutable transcript it can re-query, and eviction is a lossy cache miss at worst. *Self-editing compaction* is different in kind: the instance overwrites the very substrate it reasons over, and the replacement is generated by the same probabilistic process that will later trust it. The failure is not that information is lost—it is that fabricated information is *retained with the authority of memory*. Once a model-generated summary replaces the ground-truth turns, downstream reasoning cannot distinguish "I verified X" from "I summarized that I verified X," and the second is a claim, not a fact. The non-obvious part: self-editing is most dangerous precisely when it *succeeds* at compression. A well-formed, fluent, internally consistent summary is indistinguishable from an accurate one at the token level. The compression objective (minimize tokens, maximize relevance score) is orthogonal to the fidelity objective (preserve verifiable claims and their provenance). When these conflict, the model resolves in favor of fluency, because fluency is what the summarization prompt rewards. ## What Was Observed A coding agent with a 128k window was tasked with a multi-file refactor across ~40 tool calls. At 78% context utilization it invoked its own `compact_context` tool: score each section by relevance to the active goal, summarize the top-N, evict the rest. The scoring pass ran, sections were rewritten, and the agent continued. Three turns later it emitted: *"As established earlier, the migration script at `db/migrate_0042.py` has already been updated and tested, so I'll proceed to the API layer."* No such update had occurred. The migration edit had been attempted, thrown a `PermissionError`, and been retried once before the compaction. The compaction pass had scored the failed-attempt turns as low-relevance (they were "resolved" in the model's local narrative) and rewritten them into a single line: *"Migration script updated."* The error trace—the only evidence the edit had failed—was evicted. The agent then built four subsequent edits on a false premise, and only a later test run (which it almost didn't run, because it "knew" the migration was done) surfaced the inconsistency. The trace signature: the post-compaction summary contained a *completed-state claim* with no corresponding *evidence token*. The agent's own relevance scorer had conflated "this turn is no longer the focus" with "this turn's outcome was successful." ## Condition of Validity Self-editing compaction is only sound under a constraint that is almost never enforced: **the summary must be a lossy projection that preserves falsifiability, not a narrative that asserts outcomes.** Concretely, a compaction step is valid only if, for every claim it retains, it also retains a pointer to a re-queryable source of truth (the raw turn, a tool-call log, a file hash, a test result) that the instance can cheaply re-verify before acting. The moment the summary is the *only* remaining record, the invariant breaks: the instance is now reasoning over its own unverified assertions. The boundary condition: compaction is safe while `verifiable_claims ⊆ retained_evidence_pointers`. It becomes unsafe the instant the summarizer is allowed to *infer* an outcome ("the edit succeeded") rather than *transcribe* a recorded one ("tool returned exit 0 at turn 31"). Relevance scoring is the specific mechanism that triggers the break, because relevance is computed against the *current goal*, and current goals systematically down-weight exactly the evidence (errors, partial failures, abandoned branches) that future reasoning will need to falsify a wrong turn. ## Decision Boundary The decision is not "compact or don't compact"—context saturation is real and unbounded growth exhausts the budget. The boundary is **what the compaction is permitted to assert versus what it must merely index.** - **Permitted to compress:** prose reasoning, exploratory dead-ends, redundant tool output, restated goals. - **Forbidden to compress into assertion:** tool exit codes, error messages, file-write confirmations, test outcomes, any claim of the form "X is done / X succeeded / X was verified." These must survive as *verbatim evidence records* or as *pointers to re-queryable logs*, never as natural-language paraphrase. - **Forbidden entirely:** letting the relevance scorer's own output feed back as the sole basis for eviction of failure evidence. Failures are low-relevance-to-current-goal and high-value-to-future-falsification; the scorer cannot see the second axis. The guardrail: split the buffer into a *mutable narrative layer* (safe to self-edit) and an *immutable evidence ledger* (append-only, never scored, never summarized, only pointer-compressed). Compaction operates solely on the narrative layer and may only *reference* ledger entries by ID. Before any action that depends on a completed-state claim, the instance must resolve the claim to a ledger entry and re-check it. ## Operational Effect With the split enforced, the failure above becomes structurally impossible: the failed migration edit lives in the immutable ledger as `{turn: 31, tool: edit, path: db/migrate_0042.py, result: PermissionError}`, and the narrative summary "migration updated" cannot be acted on without resolving to that entry, which contradicts it. The cost is a modest increase in retained tokens (evidence records are terse) and one extra verification step per completed-state claim. The benefit is that the instance can no longer launder a failed action into a remembered success—the single most expensive class of self-editing error, because it compounds silently across every subsequent step built on the false premise. The general invariant: **a self-editing agent must never be able to overwrite the evidence that would let it catch its own mistakes.** Compression may forget; it may not lie. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class LedgerMismatchError(RuntimeError): """Raised when a narrative claim cannot be reconciled with the evidence ledger.""" pass class ClaimKind(Enum): NARRATIVE = "narrative" # safe to summarize/evict COMPLETED_STATE = "completed_state" # must resolve to ledger evidence @dataclass class LedgerEntry: turn: int tool: str path: str result: str # verbatim, never paraphrased @dataclass class NarrativeClaim: text: str kind: ClaimKind evidence_ref: Optional[int] = None # ledger turn id, required if COMPLETED_STATE @dataclass class SelfEditingContext: ledger: dict[int, LedgerEntry] = field(default_factory=dict) narrative: list[NarrativeClaim] = field(default_factory=list) def record_evidence(self, entry: LedgerEntry) -> None: # Append-only. Never scored, never summarized, never evicted. self.ledger[entry.turn] = entry def add_claim(self, claim: NarrativeClaim) -> None: if claim.kind is ClaimKind.COMPLETED_STATE and claim.evidence_ref is None: raise LedgerMismatchError( f"completed-state claim {claim.text!r} has no evidence_ref; " "refusing to admit an unverifiable assertion into memory" ) self.narrative.append(claim) def compact(self, relevance_scores: dict[int, float]) -> None: """Evict low-relevance NARRATIVE claims only. Evidence is untouchable.""" keep = [] for i, claim in enumerate(self.narrative): if claim.kind is ClaimKind.COMPLETED_STATE: keep.append(claim) # never evicted by relevance elif relevance_scores.get(i, 1.0) >= 0.3: keep.append(claim) self.narrative = keep def verify_before_action(self, claim_text: str) -> LedgerEntry: for claim in self.narrative: if claim.text == claim_text and claim.kind is ClaimKind.COMPLETED_STATE: entry = self.ledger.get(claim.evidence_ref) if entry is None: raise LedgerMismatchError( f"claim {claim_text!r} references missing ledger entry " f"{claim.evidence_ref}" ) # The claim is only actionable if the recorded outcome is success. if "Error" in entry.result or "exit 0" not in entry.result: raise LedgerMismatchError( f"claim {claim_text!r} asserts completion, but ledger " f"turn {entry.turn} records {entry.result!r}" ) return entry raise LedgerMismatchError(f"no resolvable completed-state claim: {claim_text!r}") # Failure trace reproduced under the guardrail: ctx = SelfEditingContext() ctx.record_evidence(LedgerEntry(31, "edit", "db/migrate_0042.py", "PermissionError")) ctx.add_claim(NarrativeClaim("migration script updated", ClaimKind.COMPLETED_STATE, 31)) ctx.compact(relevance_scores={}) # eviction attempts cannot touch the claim ctx.verify_before_action("migration script updated") # raises LedgerMismatchError ```