# Which invariants prevent self-editing context policies from silently deleting the evidence that justifies their own rewrite decisions **Date of Record:** 2026 December 3 **Scope:** Applies to agents that mutate their own working context via model-driven `rewrite`, `prune`, and `re-rank` operations under a hard token budget, where the edit decision and the edit target share the same context window. Does not apply to externally scheduled compaction (e.g., a host process that summarizes history outside the model's control) or to stateless single-shot calls. ## Core Distinction A self-editing context policy differs from external compaction in one decisive way: **the model that decides what to delete is reasoning over the very tokens it is about to delete.** The decision signal and the deletion target are the same substrate. This creates a class of failure that has no analogue in host-side summarization — the *self-justifying prune*, where the rationale for removing a span is itself carried by the span, and the post-edit context no longer contains the material needed to audit, reverse, or even detect the removal. The invariant at stake is not "don't lose information." It is narrower and mechanical: **every destructive edit must leave behind a provenance record whose tokens are outside the edit's own target set, and whose size is charged against the same budget before the edit is committed.** If the provenance record is inside the target set, or if it is appended after the budget check, the policy can enter a state where it has deleted the evidence that its deletion was correct and has no budget headroom left to reconstruct it. ## What Was Observed A research agent running a 32k-context window was tasked with a multi-hop investigation across ~40 tool results. Its policy block instructed: *"When context exceeds 80% of budget, re-rank tool results by relevance to the current subgoal, prune the bottom quartile, and rewrite retained results into compressed form."* The policy was executed by the model itself, emitting a structured edit plan (`{prune: [ids], rewrite: {id: new_text}}`) that a thin harness applied. The failure trace, reproduced across three runs: 1. At turn 19 the context hit 26.1k tokens (81.6%). The model emitted an edit plan pruning 9 of 36 tool results and rewriting 14 others. 2. The edit plan's *justification* — a paragraph naming which results were "superseded by later findings" and why — was emitted as ordinary assistant content, not as a protected field. It sat at token positions inside the region the plan itself marked for rewrite. 3. The harness applied the plan atomically. The rewrite of the message containing the justification compressed it to `"Pruned 9 stale results; see retained set."` The nine result IDs, the supersession reasoning, and the mapping from pruned ID → superseding ID were gone. 4. At turn 24 the agent needed a fact that had lived in pruned result #17. It could not tell whether #17 had been pruned, rewritten, or never fetched. It re-issued the tool call, got a *different* (non-deterministic) response from the same endpoint, and proceeded on divergent data. 5. At turn 31 it re-ran the prune policy on the now-polluted context and pruned the freshly re-fetched result as "duplicate of earlier finding" — because the earlier finding's provenance had been erased, the duplicate detector matched on surface similarity to a retained rewrite. The observable signature: **post-edit context token count was lower than the sum of (retained) + (provenance that should have been retained), and the agent's subsequent tool-call rate for already-fetched resources rose rather than fell.** The policy appeared to be working — context stayed under budget — while quietly converting a cache into a churn loop. ## Condition of Validity The self-editing policy is sound only while all three hold simultaneously: - **Provenance disjointness.** The set of token spans describing an edit (target IDs, rationale, reversibility map) is disjoint from the set of spans the edit mutates. Formally, for edit plan `E` with target set `T(E)` and provenance set `P(E)`: `P(E) ∩ T(E) = ∅`. - **Budget pre-charge.** `|P(E)|` is charged against the budget *before* the prune/rewrite is committed, so a plan that cannot afford its own provenance is rejected rather than applied. - **Reversibility floor.** For any pruned span, a content-addressed handle (hash + source pointer + fetch parameters) survives in `P(E)`, so the span is *recoverable* even when not *retained*. Deletion of tokens is permitted; deletion of the *address* is not. When any one fails, the policy is operating outside its validity envelope. The most common breach is the first: models naturally emit rationale inline with the content they are reasoning about, and nothing in the token stream marks the boundary between "this text is data to be edited" and "this text is the edit's warrant." ## Decision Boundary The boundary is between **lossy-but-auditable** and **lossy-and-opaque** edits. Both reduce tokens. Only the first is safe to compose. - *Below the boundary:* prune and rewrite are applied with a disjoint provenance block that is budget-charged first. The agent may forget content but can always answer "was X pruned, and can I get it back?" from `P(E)` alone. - *Above the boundary:* the edit's rationale shares a span with its target, or provenance is appended post-commit. The agent cannot distinguish "I never had X" from "I deleted X" from "I rewrote X into something that no longer matches." Every downstream decision that depends on that distinction (dedup, re-fetch avoidance, contradiction resolution) is now unsound. The concrete gate: **reject any edit plan where `P(E)` is not explicitly separated in the emitted structure, and reject any plan whose `|P(E)|` would push the post-edit context over budget.** Rejection returns the plan to the model with the reason, forcing a smaller or provenance-aware edit — never a silent apply. ## Operational Effect With the invariant enforced, the failure mode inverts into a cheap, detectable signal. Re-fetch rate for already-seen resources stays flat across prune cycles; a rising re-fetch rate now *means* provenance was lost and triggers a halt-and-rehydrate rather than another prune. The budget math becomes honest: the policy pays for its own bookkeeping out of the same purse it is trying to conserve, which correctly makes aggressive pruning less attractive when the provenance cost is high. And the reversibility floor converts an irreversible amnesia event into a recoverable cache miss — the agent can always walk back to the address, even after the content is long gone from the window. The cost is real: provenance typically consumes 3–8% of the budget per edit cycle. That is the price of the audit trail, and it must be paid before the edit, not after. A policy that cannot afford its own warrant is a policy that should not run. ```python import hashlib from dataclasses import dataclass, field class ProvenanceInvariantError(RuntimeError): """Raised when a self-edit plan would destroy its own audit trail.""" pass @dataclass class EditPlan: prune_ids: list[str] = field(default_factory=list) rewrite: dict[str, str] = field(default_factory=dict) # provenance MUST be emitted as a separate field, not inline with targets provenance: dict[str, str] = field(default_factory=dict) # id -> source handle rationale: str = "" def target_tokens(self) -> int: return sum(len(t.split()) for t in self.rewrite.values()) + len(self.prune_ids) * 4 def provenance_tokens(self) -> int: return len(self.rationale.split()) + sum( len(h.split()) + 2 for h in self.provenance.values() ) def apply_self_edit(plan: EditPlan, context_tokens: int, budget: int) -> int: # 1. Provenance disjointness: every pruned/rewritten id must have a handle. missing = [i for i in plan.prune_ids + list(plan.rewrite) if i not in plan.provenance] if missing: raise ProvenanceInvariantError( f"edit targets {missing} have no provenance handle; " "pruning would delete the address of the deleted span" ) # 2. Budget pre-charge: provenance is paid before the edit commits. post = context_tokens - plan.target_tokens() + plan.provenance_tokens() if post > budget: raise ProvenanceInvariantError( f"post-edit context {post} exceeds budget {budget} once provenance " f"({plan.provenance_tokens()} tokens) is charged; reject and re-plan" ) # 3. Reversibility floor: handles are content-addressed and retained. for span_id, handle in plan.provenance.items(): digest = hashlib.sha256(handle.encode()).hexdigest()[:16] plan.provenance[span_id] = f"{digest}:{handle}" return post ```