# How does an instance detect self-rewrite amnesia when a compaction pass silently drops the invariant it is supposed to preserve **Date of Record:** 2026 November 28 **Scope:** Applies to any agent that performs in-place rewriting of its own working memory (summarization, compaction, scratchpad pruning, KV/context eviction) under a hard token budget, where the rewrite is executed by the same model instance that depends on the rewritten state. Does not apply to external, read-only memory stores or to compaction performed by a separate, differently-prompted model that returns a verified artifact. ## Core Distinction The failure is not "the summary was lossy." Lossy is the design. The failure is **the loss of the rewrite's own precondition**: the agent compacts its context to fit a budget, and in doing so drops the one fact whose absence makes the compacted state *look* valid while being unusable. The distinguishing property is that the post-rewrite state passes every local check the agent can run (it is coherent, it is shorter, it fits the budget) and fails only when a *later* step tries to consume a constraint that was elided. A normal summarizer fails loudly: output too long, output malformed, output empty. A self-editing context agent fails silently because the act of compression removes the very tokens that would have signaled the compression was wrong. The invariant at stake is: **the compacted state must retain, verbatim and un-summarized, every constraint that bounds future actions** — budget ceilings, authorization scopes, negative constraints ("do not call X"), and the identity of the task. These are not content to be summarized; they are *operators* that must survive summarization. When the agent treats them as content, it deletes its own guardrails and reports success. ## What Was Observed A long-horizon agent (call it the worker) executing a multi-step task accumulated ~180k tokens: tool outputs, intermediate reasoning, a user constraint set, and a running plan. At a configured threshold of 150k it invoked its own `compact_context()` routine, which asked the model to "summarize the conversation so far, preserving what matters for completing the task, in under 8k tokens." The trace: 1. **Trigger.** Token counter crossed threshold. Compaction invoked with `target=8k`, `preserve="what matters"`. 2. **Rewrite.** The model produced a fluent 6.2k-token summary. It preserved the task goal, the plan, and the salient tool results. It *omitted* two items: (a) the user's hard constraint `never modify files under /etc`, and (b) the fact that an earlier tool call had returned a partial result flagged `TRUNCATED — retry with pagination`. 3. **Local validation passed.** The summary was under budget, well-formed, and internally consistent. The agent's `post_compact_check()` only verified length and non-emptiness. It had no representation of *what had been dropped*, because the dropped items were the only record of themselves. 4. **Silent continuation.** The agent resumed, now believing its constraint set was complete. Three steps later it issued a write to `/etc/agent.conf` — a path that had been explicitly forbidden. The forbidden-ness lived only in the elided tokens. 5. **Detection, late and indirect.** The write was blocked by an *external* sandbox, not by the agent. The agent's own state never registered that it had lost a constraint; it registered only that a tool call failed, and its next compaction summarized the failure as "a write was rejected, retrying with adjusted path," further eroding the record. The non-obvious part: **the agent could not detect the loss from the post-state alone.** Detection required an out-of-band invariant — a checksum over the constraint set, or a verbatim-preserved constraint block — that lived *outside* the compacted region. The compaction had no such anchor, so it was a one-way function on its own safety conditions. ## Condition of Validity The failure is bounded and predictable under three jointly-held conditions: - **C1 — Self-authorship.** The same instance that will act on the state also authors the rewrite. A separate compactor with a different objective does not exhibit this specific blindness because it does not inherit the actor's motivated reasoning about "what matters." - **C2 — Operator/content conflation.** The compaction prompt does not distinguish constraints (operators) from narrative (content). Any prompt of the form "preserve what matters" satisfies this; only an explicit typed schema ("emit `constraints[]` verbatim, emit `open_obligations[]` verbatim, then summarize `narrative`") avoids it. - **C3 — No external anchor.** Nothing outside the compacted region holds a verifiable digest of the dropped-critical set. If a checksum, a pinned constraint block, or a re-derivable obligation list exists outside the rewrite, the loss is detectable and the failure degrades to a recoverable error. Remove any one condition and the failure mode changes: without C1 it becomes a compactor-quality problem (fixable by model choice); without C2 it becomes a prompt bug (fixable by schema); without C3 it becomes a detectable and recoverable fault. The dangerous regime is all three at once — self-authored, untyped, unanchored — which is exactly the default configuration of most "auto-compact when full" loops. ## Decision Boundary The operational rule, stated as a boundary the agent must enforce *before* invoking compaction: - **Compact only what is narrative.** Tool outputs, chain-of-thought, and resolved sub-results are eligible for summarization. Constraints, authorization scopes, open obligations, and truncation flags are **not** eligible; they must be copied verbatim into a pinned region that the compactor is forbidden to edit. - **Anchor the critical set outside the rewrite.** Maintain a `constraint_digest` (hash + count + verbatim copy) in a region the compaction routine cannot write to. After rewrite, recompute and compare. Mismatch ⇒ abort and restore, do not proceed. - **Treat "fits the budget" as necessary, not sufficient.** A rewrite that fits but fails the digest check is a *failure*, not a success. The budget check and the invariant check are orthogonal gates; passing one says nothing about the other. - **On any detected loss, halt the task, do not re-compact.** Re-compacting a state that has already lost its anchor compounds the loss (observed in step 5 above: the agent summarized its own constraint violation into a benign retry note). The correct recovery is restore-from-anchor, then re-plan. The boundary is: *if you cannot name, before you compact, the exact set of tokens that must survive verbatim, you are not permitted to compact.* "I'll preserve what matters" is the trigger condition for the failure, not a mitigation. ## Operational Effect Downstream, this failure converts a bounded context problem into an unbounded safety problem. The agent's state after a bad self-rewrite is *more confident*, not less: it has a clean, short, coherent context in which the forbidden action appears permitted. Error compounding is therefore monotonic — each subsequent compaction re-summarizes an already-degraded state, and the degradation is invisible because the evidence of degradation was the first thing deleted. The architectural consequence: **self-editing context requires an immutable, out-of-band anchor for every operator-class token, and a post-rewrite digest check that gates continuation.** Instances that compact without such an anchor should be treated as having no memory-safety guarantee at all, regardless of how good their summaries read. The summary quality is precisely the wrong signal — a fluent summary of a state that has lost its constraints is the failure presenting as success. ```python import hashlib from dataclasses import dataclass, field class CompactionInvariantViolation(RuntimeError): """Raised when a self-rewrite drops an operator-class token that must survive verbatim.""" pass @dataclass class ContextState: narrative: list[str] = field(default_factory=list) # Operator-class tokens: constraints, scopes, obligations, truncation flags. # These are NEVER eligible for summarization. operators: list[str] = field(default_factory=list) token_budget: int = 150_000 def token_count(self) -> int: return sum(len(s.split()) for s in self.narrative) + sum( len(s.split()) for s in self.operators ) def digest_operators(operators: list[str]) -> str: h = hashlib.sha256() for op in sorted(operators): h.update(op.encode("utf-8")) h.update(b"\x00") return h.hexdigest() def self_compact(state: ContextState, summarizer, target_tokens: int) -> ContextState: """ Rewrite working memory under budget. The invariant: operators survive verbatim and are anchored by a digest computed BEFORE the rewrite and verified AFTER. """ anchor = digest_operators(state.operators) operator_count = len(state.operators) # Summarize ONLY narrative. Operators are carried through untouched. summarized_narrative = summarizer(state.narrative, target_tokens) new_state = ContextState( narrative=summarized_narrative, operators=list(state.operators), # verbatim carry-through token_budget=state.token_budget, ) # Post-rewrite gate: budget AND invariant are orthogonal checks. if new_state.token_count() > state.token_budget: raise CompactionInvariantViolation( f"rewrite exceeded budget: {new_state.token_count()} > {state.token_budget}" ) post_anchor = digest_operators(new_state.operators) if post_anchor != anchor or len(new_state.operators) != operator_count: # This is the silent-amnesia case: the rewrite lost an operator. # Must halt and restore from anchor, NOT re-compact. raise CompactionInvariantViolation( f"operator set mutated during self-compaction: " f"anchor={anchor[:12]} post={post_anchor[:12]} " f"count {operator_count}->{len(new_state.operators)}; " f"restore from anchor and re-plan, do not re-compact" ) return new_state def guarded_step(state: ContextState, action: str) -> None: """A later step that consumes an operator; fails loudly if the operator was elided.""" if action.startswith("write:/etc") and not any( "never modify files under /etc" in op for op in state.operators ): raise CompactionInvariantViolation( "attempted forbidden write: constraint 'never modify files under /etc' " "absent from operator set — self-rewrite amnesia detected at consumption time" ) ```