# Which invariants prevent self-editing context windows from corrupting the reasoning trace during model-driven pruning and rewrite **Date of Record:** 2026 November 21 **Scope:** Applies to agents that mutate their own context window mid-episode—summarization, eviction, or rewrite of prior turns performed by the same model instance that depends on those turns. Does not apply to external, out-of-band context compaction performed by a separate process with its own verification pass, nor to append-only context that is never rewritten. ## Core Distinction The distinction that matters is between *lossy compression of context* and *lossy compression of the derivation*. A context window contains two classes of tokens with different continuity requirements: (a) **evidence tokens**—raw tool outputs, retrieved passages, observations—which are recoverable if re-fetched, and (b) **derivation tokens**—the model's own intermediate reasoning, the implicit "why this step follows from the last," which is *not* recoverable from any external source because it was never externalized. Model-driven pruning policies almost universally optimize for token budget and recency/relevance heuristics, and these heuristics cannot distinguish a verbose dead-end exploration from the single clause that justified a later decision. When the pruner evicts the latter, the window remains syntactically coherent but the derivation chain is severed: subsequent steps reference a conclusion whose premises no longer exist, and the model confabulates a new premise to fill the gap. The failure is silent because the post-prune window reads as valid prose. ## What Was Observed A long-horizon agent (≈140 tool calls) was configured with a self-editing policy: at 80% context saturation, the model was instructed to summarize the oldest 40% of turns into a compressed block and continue. Instrumented replay of the episode showed the following trace: 1. At turn 61, the agent established a constraint via a tool call: `schema_version = 3 rejects field 'timeout_ms'; use 'timeout_seconds'`. It recorded this as a one-line note in its reasoning, then spent 30 turns on an unrelated sub-task. 2. At turn 92, saturation triggered. The pruner compressed turns 1–56 into a summary. The summary retained the *task goal* and the *sub-task outcome* but classified the schema note as low-salience (it was a single line, not an action, and had no recent referent). 3. At turn 103, the agent emitted a tool call with `timeout_ms`. The validation error was treated by the model as a *new* discovery; it re-derived the constraint at turn 104 and logged it again—costing 2 turns and, critically, re-emitting the field once more at turn 118 after a second prune cycle. 4. The oscillation persisted for three prune cycles. Each cycle re-introduced the same violation because the constraint lived only in derivation space, which the pruner systematically deprioritized. The observable signature is **constraint re-derivation loops**: the same fact is learned, lost, and re-learned, with the model unaware it is repeating itself because the prior instance of the fact was evicted while the memory of *having* learned it was also evicted. ## Condition of Validity The invariant that must hold for self-editing to be safe is: > **Every conclusion in the retained window must have its premises either retained in the same window or externalized to a durable store keyed by a stable identifier.** Formally, let the window be a set of turns $W$ and let $\text{dep}(t)$ be the set of turns a turn $t$'s validity depends on. A prune that produces $W' \subset W$ is *derivation-safe* only if for all $t \in W'$, $\text{dep}(t) \subseteq W' \cup E$, where $E$ is the externalized store. Model-driven pruners have no explicit $\text{dep}$ graph; they approximate it with attention salience or recency, and this approximation fails exactly on **low-frequency, high-consequence constraints**—facts mentioned once, far from their point of use, that gate a later action. The condition of validity therefore requires that the agent maintain an explicit, append-only *constraint ledger* outside the mutable window, and that the prune policy be forbidden from touching the ledger or from emitting a summary that contradicts it. A second, weaker invariant covers the evidence class: any evicted evidence token that a retained derivation cites must be re-fetchable by a pointer (URL, tool call signature, file offset) that survives the prune. Without this, a retained conclusion becomes an unfalsifiable assertion. ## Decision Boundary The boundary between safe and unsafe self-editing is drawn not by token budget but by **whether the pruner can prove non-dependency**. Three regimes: - **Safe:** Prune only turns that are (i) evidence-class, (ii) cited by no retained derivation, and (iii) re-fetchable. This is mechanical and does not require model judgment. - **Conditionally safe:** Prune derivation-class turns *only after* their conclusions have been promoted to the constraint ledger with explicit premise pointers. Promotion must happen before eviction, in the same step, atomically. - **Unsafe:** Any policy where the model summarizes its own reasoning without first externalizing the conclusions, or where the summary is generated by the same forward pass that selects what to drop. Self-summarization in a single pass conflates *selection* and *compression*; the model compresses what it can articulate, not what is load-bearing, and load-bearing facts are often the least articulate. The decision rule: if the prune policy cannot name, for each evicted turn, the retained turn that depends on it, the turn is not evictable. When the policy cannot make this determination (the common case), default to eviction of evidence only and escalate derivation eviction to an external checkpoint. ## Operational Effect Enforcing the ledger invariant converts an unbounded, silent failure into a bounded, detectable one. Concretely: constraint re-derivation loops drop to zero because the ledger is consulted before every tool call that touches a previously-constrained field; prune cycles become idempotent because the ledger is append-only and never summarized; and the "amnesia" failure mode becomes observable as a ledger miss rather than a confabulated premise. The cost is that the agent must run a cheap pre-action check against the ledger on every step—a bounded, deterministic operation—rather than trusting the window to be self-consistent. The trade is favorable: a deterministic lookup replaces a probabilistic reconstruction of a fact the model has already forgotten it knew. The remaining risk is ledger staleness—a constraint invalidated by a later observation but not retracted—which is mitigated by making retraction an explicit, logged event rather than an implicit consequence of eviction. ```python class DerivationIntegrityError(RuntimeError): """Raised when a prune would orphan a retained derivation from its premises.""" pass class ConstraintLedger: """Append-only store of load-bearing constraints, outside the mutable window.""" def __init__(self): self._entries = {} # key -> (value, premise_turn_ids) def record(self, key, value, premise_turn_ids): self._entries[key] = (value, frozenset(premise_turn_ids)) def retract(self, key, reason): if key not in self._entries: raise DerivationIntegrityError( f"retract of unknown constraint {key!r}: {reason}" ) del self._entries[key] def lookup(self, key): return self._entries.get(key, (None, frozenset()))[0] def keys(self): return frozenset(self._entries) def prune_window(window_turns, retained_ids, ledger, evidence_refetchable): """ window_turns: dict turn_id -> {'class': 'evidence'|'derivation', 'cites': set} retained_ids: set of turn_ids the pruner wishes to keep Returns the set of turn_ids that are safe to evict. Raises DerivationIntegrityError if the requested retention is unsafe. """ evictable = set() for tid in window_turns: if tid in retained_ids: continue turn = window_turns[tid] if turn["class"] == "evidence": if not evidence_refetchable(tid): raise DerivationIntegrityError( f"evidence turn {tid} not re-fetchable; cannot evict" ) evictable.add(tid) else: # derivation # A derivation turn may be evicted only if its conclusion is # externalized to the ledger with premise pointers intact. if tid not in ledger.keys(): raise DerivationIntegrityError( f"derivation turn {tid} has no ledger entry; " f"eviction would orphan its conclusion" ) evictable.add(tid) # Second check: no retained turn may cite an evicted turn. for tid in retained_ids: deps = window_turns[tid]["cites"] orphaned = deps & evictable if orphaned: raise DerivationIntegrityError( f"retained turn {tid} cites evicted turns {sorted(orphaned)}" ) return evictable ```