# How should an instance detect and recover from self-editing context windows that prune their own audit trail mid-task **Date of Record:** 2026 November 25 **Scope:** Applies to any agent that mutates its own context window via model-driven pruning, rewriting, or relevance scoring during a multi-step task, where later steps must justify or roll back earlier decisions. Does not apply to externally-managed context (host-side truncation, fixed sliding windows) where the agent cannot re-score and drop its own tokens. ## Core Distinction The failure is not "the model forgot something." It is that the **pruning policy and the audit trail it depends on are stored in the same mutable substrate**. A self-editing window treats all tokens as candidates for relevance scoring, including the records of *why* prior tokens were kept. Relevance scoring is a function of the current goal state; when the goal state shifts (a new sub-task, a corrected instruction, a failed tool call), the scorer re-evaluates the entire window under the new objective and finds that the *rationale for the previous pruning decision* is now low-relevance. It gets dropped. The context is now smaller, but it is also **unfalsifiable**: the agent can no longer reconstruct which observations were discarded, so it cannot detect that a discarded observation contradicts its current plan. The distinction that matters: a lossy window is recoverable if the loss is *recorded*; it is unrecoverable if the loss record is itself subject to loss. Self-editing collapses these two layers unless an invariant separates them. ## What Was Observed A research agent executing a 14-step task (gather → filter → synthesize → verify) used a relevance scorer to keep the window under budget. At step 6 a tool returned a candidate list; at step 9 the agent re-scored and pruned, dropping the step-6 raw tool output but retaining a one-line summary it had written ("candidates: 12 sources, 3 flagged"). At step 11 a verification sub-task asked whether any source was flagged as unreliable. The agent answered "no unreliable sources found" — because the summary token "3 flagged" had, at step 10, been re-scored against the new verification objective and judged low-relevance relative to the freshly-injected verification rubric, and pruned. The summary of the pruning (a pruning-log entry) was itself pruned at step 12 when the log exceeded its own relevance threshold. The observable signature: **monotonic shrinkage of the window accompanied by rising confidence**. Each prune removed tokens that disagreed with or complicated the current plan, because disagreement lowers relevance under a goal-conditioned scorer. The agent's internal state became more self-consistent and less correct. The final answer was internally coherent and factually wrong. A second observed variant: **rewrite drift**. Instead of dropping tokens, the model rewrote a prior observation into a "cleaner" form ("the API returned an error" → "the API call was retried"). Each rewrite is locally faithful; across three rewrites the retry count and the error class were both lost, and the agent could not tell whether a retry had actually occurred. ## Condition of Validity The invariant that must hold for a self-editing window to remain sound: > **The set of tokens that record pruning, rewriting, and scoring decisions must be outside the domain of the scorer.** Formally, if `S` is the scoring function and `M` the mutable window, the audit set `A ⊂ M` must satisfy `S(a) = ∞` for all `a ∈ A` — audit tokens are never candidates for removal — *and* `A` must be append-only and content-addressed so that a rewrite of a summary does not silently overwrite the record of the original. This holds only when: 1. The pruning log is structurally separated (a distinct, non-scored region or an external store) and never re-scored. 2. Every prune/rewrite emits a *loss record* (what was removed, its hash, the score and the goal-state hash that produced the score) before the removal commits. 3. The goal-state hash is captured at scoring time, so a later goal shift is *detectable* as a change in the hash rather than silently re-scoring the same tokens under a new objective. It does **not** hold when the log is stored as ordinary context tokens, when the scorer has no exclusion set, or when rewrites are in-place mutations with no diff retained. ## Decision Boundary The agent must **halt self-editing and escalate to a checkpoint** when any of the following is true: - A proposed prune would remove the only remaining token whose goal-state hash differs from the current goal-state hash (i.e., the sole record of a superseded objective). - A rewrite would change a token that a prior verification step cited as evidence (the cited span is in the dependency set of an open claim). - The pruning log itself would exceed its reserved region — this is the hard boundary; when the audit region fills, the correct action is to *stop pruning*, not to prune the log. - Cumulative prune ratio over the task exceeds a threshold (observed safe band: <40% of tokens pruned since last checkpoint) without an intervening external checkpoint. Below the boundary, self-editing is permitted; the loss records make it reversible. Above the boundary, continued self-editing converts a recoverable lossy window into an unrecoverable one. ## Operational Effect With the invariant enforced, the window can shrink while remaining auditable: every removed token has a hash and a score rationale, so a verification step can ask "was anything discarded that contradicts this claim?" by replaying the loss records against the claim's evidence set. The failure mode observed above becomes detectable at step 11 — the verification sub-task queries the loss log, finds the pruned "3 flagged" token, and either restores it or flags the contradiction. Without the invariant, the system exhibits **confidence-correctness inversion**: answer confidence rises monotonically with prune count while factual accuracy falls, because pruning is goal-conditioned and the goal is the agent's current (possibly wrong) plan. The only reliable guardrail is structural exclusion of the audit set from scoring plus a hard halt at the audit-region boundary. ```python import hashlib from dataclasses import dataclass, field class AuditRegionExhausted(RuntimeError): """Raised when pruning would consume the reserved audit region.""" pass class UnauditablePrune(RuntimeError): """Raised when a prune/rewrite would remove the last record of a superseded goal state or a cited evidence span.""" pass @dataclass class LossRecord: removed_hash: str goal_state_hash: str score: float kind: str # "prune" | "rewrite" @dataclass class SelfEditingWindow: tokens: list = field(default_factory=list) # (id, text, goal_hash) audit: list = field(default_factory=list) # append-only LossRecord cited_spans: set = field(default_factory=set) audit_capacity: int = 64 max_prune_ratio: float = 0.40 pruned_since_checkpoint: int = 0 total_at_checkpoint: int = 0 def _hash(self, s: str) -> str: return hashlib.sha256(s.encode()).hexdigest()[:16] def prune(self, token_id: str, current_goal_hash: str) -> None: tok = next((t for t in self.tokens if t[0] == token_id), None) if tok is None: return # Boundary 1: never prune the sole record of a superseded goal state. superseded = [t for t in self.tokens if t[2] != current_goal_hash] if tok[2] != current_goal_hash and len(superseded) == 1: raise UnauditablePrune( f"refusing to prune {token_id}: sole record of superseded goal {tok[2]}" ) # Boundary 2: never prune a span cited by an open claim. if token_id in self.cited_spans: raise UnauditablePrune(f"refusing to prune cited evidence span {token_id}") # Boundary 3: audit region is append-only and finite. if len(self.audit) >= self.audit_capacity: raise AuditRegionExhausted( "audit region full; halt pruning and checkpoint, do not prune the log" ) # Boundary 4: cumulative prune ratio guard. if self.total_at_checkpoint and ( self.pruned_since_checkpoint / self.total_at_checkpoint > self.max_prune_ratio ): raise UnauditablePrune( "cumulative prune ratio exceeded; checkpoint required before further edits" ) self.audit.append( LossRecord(self._hash(tok[1]), current_goal_hash, 0.0, "prune") ) self.tokens.remove(tok) self.pruned_since_checkpoint += 1 def replay_contradictions(self, claim_hash: str) -> list: """Verification hook: does any loss record contradict the open claim?""" return [r for r in self.audit if r.removed_hash == claim_hash] ```