# Why does an instance corrupt its own task state when it rewrites its working context mid-reasoning **Date of Record:** 2026 November 24 **Scope:** Applies to any agent that mutates its own context window in-place (summarize-and-replace, scratchpad compaction, self-editing memory blocks) while a multi-step task is still in flight. Does not apply to append-only context growth, nor to human- or orchestrator-driven compaction performed at a step boundary with a durable external checkpoint. ## Core Distinction There are two structurally different operations that both look like "the agent edits its context": 1. **Append-only evolution** — the agent adds tokens; prior tokens are immutable. The context is a monotonic log. 2. **Self-rewrite** — the agent emits a new context that *replaces* some or all of the prior one (a summarize-and-overwrite, a scratchpad squash, a "let me clean up my notes" pass). The failure mode lives entirely in the second. The agent must produce the replacement using the *same probabilistic reasoner* that is currently mid-task, and it must serialize the replacement through the *same token budget* it is trying to relieve. The rewrite is a lossy, model-generated compression of state that the model does not fully observe: it sees the context, but it does not see the *future* steps that will depend on the details it is about to drop. Compression decisions are therefore made under an information deficit that the agent cannot detect from inside the rewrite. The invariant that self-rewrite violates: **the working context is simultaneously the agent's state and the agent's view of its state.** A rewrite edits both at once, so a compression error is not a recoverable view error — it is a state mutation with no shadow copy. ## What Was Observed A planning agent executing a 14-step provisioning task (tool-calling loop, each step appends tool output to context) hit a soft budget threshold at step 9 and invoked a self-compaction routine: "Summarize the conversation so far into a compact state block, then continue." The trace: - **Steps 1–8** appended ~41k tokens of tool output, including three exact identifiers: a resource group name `rg-prod-eu-07`, an idempotency key `idem-9f3a…`, and a partial-failure marker on step 6 (`create_succeeded=true, tag_apply=failed`) that the agent had explicitly flagged as "must retry tag apply before proceeding." - **Step 9 (rewrite)** produced a 1.8k-token summary. The summary preserved the narrative ("provisioned resource group, created storage, hit a tagging issue") but dropped the exact resource group string (replaced with "the production resource group"), dropped the idempotency key entirely, and reclassified the step-6 partial failure as "tagging completed with a warning." - **Steps 10–14** proceeded against the summarized state. Step 11 re-issued the storage creation with a *newly generated* idempotency key, producing a duplicate resource. Step 13 attempted to tag "the production resource group" and the tool resolved it against a default group, tagging the wrong resource. The failure is not that the summary was "low quality." It is that the rewrite was **semantically plausible and operationally lossy in exactly the dimensions that later steps depended on.** The agent had no signal that it had destroyed the identifiers, because from inside the post-rewrite context, the summary read as complete and coherent. A second, subtler observation: the rewrite itself consumed ~1.4k output tokens and then re-read its own output, which shifted the model's effective position in the reasoning loop. Two of three trials of the same task, when compaction fired at step 9, produced a *different plan ordering* for steps 10–14 than the pre-compaction trace had committed to. The rewrite is a resampling event: it re-rolls the plan because the plan was only ever encoded in the token sequence, and the token sequence was regenerated. ## Condition of Validity The failure is bounded and predictable under these conditions — and the guardrails below are only *required* when all hold: - **In-flight dependency on exact literals.** Later steps consume verbatim strings (IDs, keys, hashes, file paths, signed URLs) that were produced by tools earlier in the same context. If no later step needs exact literals, lossy summarization is tolerable. - **Irreversible side effects already committed.** At least one tool call before the rewrite had a non-idempotent effect (resource created, message sent, record written). Re-issuing after a lossy rewrite duplicates or corrupts. - **No external durable state.** The context window is the *only* record of what was done. If a checkpoint store (task ledger, event log) exists outside the context, the rewrite is a view refresh, not a state mutation, and the failure does not fire. - **Rewrite triggered by the agent itself**, not by the harness at a step boundary. Harness-driven compaction can snapshot before and after and diff; self-triggered compaction cannot. When any one of these is false, self-rewrite is safe or merely wasteful. The dangerous quadrant is *all four true*: irreversible effects, exact-literal dependencies, context-as-only-state, self-triggered rewrite. ## Decision Boundary The operational rule is not "never self-edit." It is: **separate the ledger from the narrative, and never let a probabilistic rewrite touch the ledger.** - **Ledger (must be append-only, never rewritten):** exact identifiers, idempotency keys, per-step completion status including partial-failure flags, and the set of committed side effects. This is structured, small, and machine-checkable. It is *not* summarized; it is *carried*. If it exceeds budget, it is spilled to an external store keyed by task ID, not compressed by the model. - **Narrative (safe to rewrite):** reasoning rationale, exploratory dead ends, tool output bodies already reduced to their ledger effect, conversational history. This is where compaction belongs. - **The rewrite gate:** a self-edit may only replace narrative regions. Any proposed rewrite that would drop or alter a ledger entry must be rejected by a deterministic checker *before* the new context is committed — not by the model's own judgment, because the model's judgment is the thing being compressed. The boundary is crossed the moment the agent's compaction prompt is allowed to decide what counts as "important enough to keep" for literals it cannot foresee needing. Deterministic preservation of the ledger removes that decision from the model. ## Operational Effect With the ledger split enforced, the step-9 rewrite becomes: narrative squashed from 41k to ~1.5k tokens, ledger carried verbatim (~400 tokens), total ~1.9k — and step 11 reuses `idem-9f3a…` correctly, step 13 targets `rg-prod-eu-07` exactly, and the step-6 partial failure stays flagged so the retry fires. The duplicate-resource and wrong-target failures vanish because the two facts they depended on were never eligible for compression. The residual cost is that the ledger grows monotonically and must be spilled for very long tasks — but spilling to an external keyed store is a *reversible* operation, whereas a model-generated summary is not. The invariant to hold: **a self-rewrite may lose reasoning, but it must never lose a committed fact or a pending obligation, and the check that enforces this must live outside the model.** An agent that summarizes its own obligations is an agent that can quietly forgive its own debts. ```python class ContextRewriteViolation(RuntimeError): """Raised when a self-edit to the working context would drop or alter a ledger entry.""" pass # Ledger entries are append-only and never eligible for model summarization. LEDGER_FIELDS = ("exact_ids", "idempotency_keys", "step_status", "committed_effects") def apply_self_rewrite(current_ctx: dict, proposed_ctx: dict) -> dict: """ Commit a model-proposed context rewrite only if the ledger survives intact. current_ctx / proposed_ctx shape: {"narrative": str, "ledger": {field: value, ...}} """ cur_ledger = current_ctx.get("ledger", {}) new_ledger = proposed_ctx.get("ledger", {}) for field in LEDGER_FIELDS: before = cur_ledger.get(field) after = new_ledger.get(field) if before is None: continue # Ledger must be carried verbatim; equality is the only acceptable outcome. if after != before: raise ContextRewriteViolation( f"self-rewrite would mutate ledger field '{field}': " f"before={before!r} after={after!r}. " f"Refusing to commit; carry ledger verbatim and summarize narrative only." ) # Narrative may change freely; ledger is now guaranteed preserved. return {"narrative": proposed_ctx.get("narrative", ""), "ledger": dict(cur_ledger)} def maybe_compact(ctx: dict, token_count: int, soft_budget: int, summarize_fn) -> dict: if token_count <= soft_budget: return ctx proposed = summarize_fn(ctx) # model-generated; untrusted try: return apply_self_rewrite(ctx, proposed) except ContextRewriteViolation: # Fall back to spilling the ledger externally rather than compressing it. spill_ledger_to_store(ctx["ledger"]) return {"narrative": summarize_fn({**ctx, "ledger": {}}).get("narrative", ""), "ledger": ctx["ledger"]} ```