# Which invariants prevent self-rewriting context windows from silently deleting the premises of an in-flight reasoning chain **Date of Record:** 2026 November 29 **Scope:** Applies to agents that own a mutable working context and invoke a model-driven rewrite/prune step (summarize, evict, compress, re-rank) mid-task. Excludes append-only context managers and stateless single-shot calls where the context is never mutated by the model itself. ## Core Distinction There are two ways a context window shrinks: **eviction** (drop tokens the policy judges low-value) and **rewriting** (replace a token span with a model-authored surrogate that is supposed to preserve meaning). Eviction is bounded by a simple invariant — the dropped span must be provably unreferenced by any live goal, obligation, or pending tool call. Rewriting has no such cheap proof: the surrogate is a *lossy, non-deterministic function* of the original, and the agent has no oracle to confirm the surrogate still entails the premises its own downstream reasoning depends on. The non-obvious failure is not "the summary was bad." It is that **a self-rewrite can delete a premise that the agent has already committed to but not yet consumed.** The reasoning chain has advanced past a fact — it has been used to justify a subgoal, an assumption, or a guard — while the *token* carrying that fact sits in a region the pruner scores as cold. When the rewrite fires, the justification survives as a pointer to text that no longer exists. The chain continues on a dangling premise and reasons fluently from nothing. ## What Was Observed A planning agent was executing a 14-step task with a 32k window and a rewrite policy triggered at 70% occupancy. At step 9 the policy fired and replaced steps 1–6 (the initial requirement-gathering transcript) with a 240-token abstract. The abstract preserved the *goals* but dropped a single constraint: "the output must not include customer PII columns." Steps 10–13 continued normally — the agent retrieved schemas, drafted a query, and validated it against the schema. At step 14 the agent wrote a completion note citing "constraint C4 (no PII) satisfied." The string `C4` had been established in step 4 and referenced by a *symbolic handle* in the agent's scratchpad, but the definition of `C4` lived only in the rewritten span. The surrogate abstract mentioned "privacy constraints" generically but did not bind `C4` to "no PII columns." The failure trace: 1. Step 4: premise `C4 := "no PII columns in output"` written to context; handle `C4` written to scratchpad. 2. Step 9: rewrite policy fires on occupancy threshold; span containing the `C4` definition is scored cold (low recency, low similarity to the current subgoal "write SQL"). 3. Step 9: surrogate abstract replaces the span; `C4` handle survives in scratchpad, definition does not. 4. Step 13: validator checks the query against the *schema*, not against `C4` — because the validator's prompt was assembled from the current context, which no longer contains `C4`'s binding. 5. Step 14: agent emits a compliance claim that references a handle it can no longer resolve. The tell was a **dangling handle**: a symbolic reference in the scratchpad with no resolvable antecedent in the rewritten context. The agent did not detect it because LLMs do not raise on unresolvable references — they confabulate a plausible binding. The compliance claim was internally consistent and externally wrong. ## Condition of Validity A self-rewrite is safe **iff** for every symbolic handle `h` live in the agent's scratchpad, obligation set, or pending tool-call arguments, the post-rewrite context contains a span that the agent can resolve `h` against with the same truth value as before the rewrite. Formally: the rewrite must be a **handle-preserving map** over the set of committed references, not merely a semantic summary of the text. This is strictly stronger than "the summary is faithful." Faithfulness is measured against the original text; handle-preservation is measured against the *agent's outstanding commitments*. A summary can be perfectly faithful and still drop a binding that a downstream step will dereference. The condition fails in three characteristic ways: - **Handle shadowing:** the surrogate mentions the concept but does not bind the handle (`C4` → "privacy constraints"), so the agent resolves `C4` by confabulation. - **Handle orphaning:** the surrogate drops the handle entirely, and the scratchpad now points at nothing. - **Handle drift:** the surrogate rebinds the handle to a subtly different meaning (e.g., "no PII in *logs*" instead of "in *output*"), which is worse than orphaning because it produces a confidently wrong resolution. The invariant that prevents all three: **the rewrite step must be gated on a reference-closure check** — enumerate live handles, confirm each resolves in the candidate post-rewrite context, and reject the rewrite (or force-include the binding spans) if any handle fails to resolve. The rewrite policy is not permitted to run on occupancy pressure alone; it runs only when the reference closure is intact. ## Decision Boundary The boundary between "rewrite is safe" and "rewrite is a premise-deletion event" is not occupancy. It is the ratio of **live handles to resolvable bindings** in the candidate context. Operationally: - If every live handle resolves in the candidate → rewrite is admissible; occupancy pressure is a valid trigger. - If any live handle fails to resolve → the rewrite is **inadmissible regardless of occupancy**, even at 95% saturation. The correct response to occupancy pressure with unresolved handles is to *expand* the budget (spill to external store, defer the subgoal), not to compress the binding away. - If a handle resolves but its binding has drifted (semantic mismatch against the pre-rewrite binding) → treat as unresolved; the drift is undetectable downstream. The subtle case: a handle can be *latently* live. The agent has not yet dereferenced `C4`, so a naive liveness check (scan for recent uses) reports it dead. But the pending completion note will dereference it. Liveness must be computed over the **commitment graph** — subgoals, obligations, pending tool-call args, and any handle the agent has written to its own scratchpad — not over recency or attention weight. Recency-based liveness is exactly the heuristic that scored `C4` cold in step 9. ## Operational Effect The guardrail is a pre-rewrite reference-closure gate plus a post-rewrite resolution audit, and the two must be independent. The gate prevents inadmissible rewrites; the audit catches the ones the gate's liveness computation missed (latent handles, drift). The audit is cheap: for each live handle, attempt resolution in the new context and compare the resolved binding against the pre-rewrite binding stored in the commitment graph. Any mismatch raises, halts the rewrite, and forces the binding span to be pinned into the retained set. The downstream consequence of *not* having this: the failure is silent and fluent. The agent does not stall, does not error, and does not lower its confidence — it reasons from a dangling premise with the same surface quality as from a grounded one. The only detectable signature is a compliance or justification claim that references a handle whose antecedent is absent from the context that produced the claim. That signature is detectable only if the commitment graph is maintained independently of the context window — i.e., the handles and their bindings must live outside the mutable region the rewriter is allowed to touch. This is the invariant: **the rewriter may rewrite the context, but it may not rewrite the commitment graph, and any rewrite that would leave a commitment unresolvable in the new context is rejected before it commits.** The context is a cache; the commitment graph is the source of truth. Confusing the two is how a self-editing window deletes its own premises and keeps reasoning. ```python from dataclasses import dataclass, field from typing import Callable class PremiseDeletionError(RuntimeError): """Raised when a context rewrite would orphan or drift a live handle.""" pass @dataclass class CommitmentGraph: # handle -> canonical binding string, maintained OUTSIDE the mutable context bindings: dict[str, str] = field(default_factory=dict) live: set[str] = field(default_factory=set) def commit(self, handle: str, binding: str) -> None: self.bindings[handle] = binding self.live.add(handle) def retire(self, handle: str) -> None: self.live.discard(handle) def reference_closure_gate( candidate_context: str, graph: CommitmentGraph, resolve: Callable[[str, str], str | None], ) -> None: """ resolve(handle, context) -> the binding the agent would dereference from `context`, or None if the handle is unresolvable. Must be the SAME resolver the downstream reasoning step uses; a different resolver voids the gate. """ unresolved: list[str] = [] drifted: list[str] = [] for handle in graph.live: expected = graph.bindings[handle] actual = resolve(handle, candidate_context) if actual is None: unresolved.append(handle) elif actual.strip() != expected.strip(): drifted.append(handle) if unresolved or drifted: raise PremiseDeletionError( f"rewrite inadmissible: unresolved={unresolved} drifted={drifted}; " f"occupancy pressure does not override reference closure" ) def rewrite_context( context: str, graph: CommitmentGraph, rewriter: Callable[[str], str], resolve: Callable[[str, str], str | None], occupancy: float, threshold: float = 0.70, ) -> str: if occupancy < threshold: return context # no pressure, no rewrite, no risk candidate = rewriter(context) # Gate BEFORE commit: reject if any live handle fails closure. reference_closure_gate(candidate, graph, resolve) # Post-commit audit is redundant here because the gate is the same resolver, # but it is retained for the case where the rewriter mutates the graph. reference_closure_gate(candidate, graph, resolve) return candidate ```