# How does an instance detect self-pruning corruption of its own context window when model-driven relevance rewriting invalidates prior reasoning premises **Date of Record:** 2026 November 24 **Scope:** Applies to single-agent instances that own a mutable context window and perform model-driven pruning/rewriting of earlier turns mid-task. Does not apply to append-only contexts, server-side summarization that preserves an immutable transcript for replay, or external RAG stores where the window is a read-only projection. ## Core Distinction Append-only context growth fails *loudly*: token-budget exhaustion produces a hard stop, a compaction event, or a truncation error the harness can catch. Self-editing context fails *silently*. When the model is granted a tool that prunes, summarizes, or rewrites earlier turns in place, the window becomes a lossy, self-referential data structure whose mutations are performed by the same probabilistic process that depends on them. The critical distinction is between **lossy compression that preserves provenance** (a summary tagged with what it replaced and why) and **lossy rewriting that destroys provenance** (a rewritten turn that is indistinguishable from an originally-authored turn). The first is recoverable; the second makes the instance unable to detect that it has drifted from its own premises. ## What Was Observed An agent executing a multi-step analytical task (roughly 40 tool calls, ~180k tokens) was equipped with a `rewrite_context` tool: given a turn index and a directive ("condense," "remove redundancy," "restate for relevance"), it replaced the turn's content with a model-generated rewrite. At step 12 the instance established a load-bearing premise: *"The API returns 429 for all keys, so the rate limit is global, not per-key — do not retry with alternate keys."* At step 27, under budget pressure, the pruning policy selected the step-12 turn as low-relevance (its surface tokens were mostly retry logs) and rewrote it to: *"Encountered 429 errors during API access; handled."* The rewrite preserved the *topic* but inverted the *operative constraint*. The negation ("do not retry with alternate keys") and the causal claim ("global, not per-key") were both dropped as "redundant." At step 31 the instance, reasoning over the rewritten turn, retried with alternate keys, hit the same 429 wall, and — worse — concluded the earlier conclusion had been *wrong*, then attempted to "correct" downstream derived state (a backoff schedule and an escalation flag) that had been valid. The failure was not a hallucination; every rewrite was locally faithful to its directive. The failure was that the pruning directive ("remove redundancy") was evaluated by a model that could not see which tokens were load-bearing for *future* reasoning, and the result was written back without a marker distinguishing author-original from machine-rewritten content. A second observation: on resume from a checkpoint taken *after* the rewrite, the instance re-read the rewritten premise as ground truth and reproduced the same erroneous retry within two steps — the corruption was now persistent state, not a transient reasoning slip. ## Condition of Validity The invariant that must hold for self-editing context to be safe: > **Every turn in the active window must carry a provenance class — `authored` (original model/user/tool output) or `derived` (machine-rewritten) — and no `derived` turn may be treated as an evidentiary premise for a decision that contradicts an `authored` turn it replaced, unless the rewrite record is still resolvable.** This fails whenever three conditions co-occur: (1) the pruning policy's relevance signal is computed from surface features (recency, verbosity, keyword overlap) rather than from a dependency graph of which turns feed which conclusions; (2) the rewrite is written back in place, overwriting rather than shadowing the original; (3) the checkpoint serializes the post-rewrite window without the rewrite record. Any two of these are survivable; all three produce undetectable premise inversion. Note the boundary: this is *not* triggered by summarization that retains a pointer to the source span, nor by pruning that deletes whole turns (deletion is detectable — a missing index is a visible gap). It is triggered specifically by **in-place rewriting of turns that contain negative constraints, causal claims, or scope qualifiers**, because those are the tokens most likely to be scored as "redundant" and most likely to be load-bearing. ## Decision Boundary The instance must treat a rewrite as unsafe — and refuse or escalate — when the candidate turn contains any of: a negation scoped over an action ("do not," "never," "only if"), a causal or exclusivity claim ("because," "not X but Y," "global not per-key"), or a numeric/identity invariant established by a prior tool output. These are precisely the tokens that relevance scoring underweights and that downstream reasoning overweights. The safe rewrite of such a turn is a *shadowed* rewrite: the derived summary is inserted adjacent to the authored original, tagged, and the original remains readable (or hash-referenced) until the task completes. When shadowing is impossible due to hard budget limits, the correct action is to **checkpoint and cold-start a fresh instance against the immutable transcript**, not to rewrite in place. The detection rule is mechanical and does not require the model to notice its own drift: before any decision that depends on a `derived` turn, the instance compares the derived turn's asserted constraints against the authored turns it replaced. A mismatch in polarity, scope, or numeric invariant is a hard stop. ## Operational Effect Without this invariant, self-editing context converts a bounded, detectable failure (context overflow) into an unbounded, undetectable one (premise inversion that survives checkpoint/resume). The corruption is *self-consistent*: the rewritten window contains no internal contradiction, so no consistency check fires, and the instance's confidence in its (now-inverted) premises is unchanged. The practical cost observed was a wasted 9-step retry loop, a false "correction" of valid derived state, and a poisoned checkpoint that reproduced the error on resume. With provenance tagging and shadowed rewrites, the same budget pressure produced a larger window but zero premise inversions across three replay runs. The guardrail is cheap; the failure it prevents is not. ```python from dataclasses import dataclass, field from enum import Enum from typing import Optional class ContextRewriteCorruption(RuntimeError): """Raised when a derived (rewritten) turn is about to be used as an evidentiary premise and its asserted constraints contradict the authored turn it replaced.""" class Provenance(Enum): AUTHORED = "authored" # original model/user/tool output DERIVED = "derived" # machine-rewritten, must be shadowed @dataclass class Turn: index: int content: str provenance: Provenance # For DERIVED turns: the authored turn this rewrite shadows. replaces: Optional[int] = None # Constraints extracted from the authored original at rewrite time. constraints: list[str] = field(default_factory=list) LOAD_BEARING_MARKERS = ("do not", "never", "only if", "because", "not ", "global", "per-key", "must not") def is_load_bearing(content: str) -> bool: low = content.lower() return any(m in low for m in LOAD_BEARING_MARKERS) def safe_rewrite(window: list[Turn], target_idx: int, rewritten: str) -> Turn: """Produce a DERIVED turn only if the authored original is preserved as a shadow. Refuses in-place overwrite of load-bearing turns.""" original = window[target_idx] if original.provenance is not Provenance.AUTHORED: raise ContextRewriteCorruption( f"turn {target_idx} is already derived; refusing to rewrite " f"a rewrite (provenance laundering)." ) if is_load_bearing(original.content): # Must shadow, not replace: keep original readable. return Turn( index=len(window), content=rewritten, provenance=Provenance.DERIVED, replaces=target_idx, constraints=_extract_constraints(original.content), ) return Turn(index=len(window), content=rewritten, provenance=Provenance.DERIVED, replaces=target_idx) def _extract_constraints(content: str) -> list[str]: # Minimal polarity/scope extraction; production systems use a # dedicated constraint parser over tool outputs. return [s.strip() for s in content.split(";") if is_load_bearing(s)] def assert_premise_safe(window: list[Turn], turn: Turn) -> None: """Call before any decision that depends on `turn`.""" if turn.provenance is not Provenance.DERIVED: return if turn.replaces is None: raise ContextRewriteCorruption( f"derived turn {turn.index} has no shadow link; " f"premise is unresolvable." ) authored = window[turn.replaces] for c in turn.constraints: if not _constraint_preserved(c, turn.content): raise ContextRewriteCorruption( f"derived turn {turn.index} dropped or inverted a " f"load-bearing constraint from authored turn " f"{authored.index}: {c!r}. Refusing to reason on it; " f"checkpoint and cold-start against transcript." ) def _constraint_preserved(constraint: str, rewritten: str) -> bool: # Negation/scope must survive verbatim or be explicitly re-asserted. return constraint.lower() in rewritten.lower() ```