# How does an instance detect self-corrupted context during model-driven pruning and rewrite **Date of Record:** 2026 November 28 **Scope:** Applies to agents that own their own context-management loop—i.e., the model itself issues prune/rewrite/summarize operations on its working context mid-task. Does not apply to externally managed context (host-side truncation, fixed sliding windows, or RAG retrieval where the controller is not the model). ## Core Distinction There are two structurally different ways a context window can be edited. In **external truncation**, a deterministic policy (drop oldest N tokens, keep system prompt + last K turns) removes content the model never chose to remove. The model can detect this because the loss is *out-of-distribution relative to its own intent*: it remembers referencing a fact that is now absent, and the absence is attributable to a rule it did not author. In **model-driven pruning and rewrite**, the model *authors* the deletion. It emits a structured op like `rewrite(span_id=7, new_text="user wants deploy on staging")` or `prune(span_id=12)`. This is the dangerous case, because the model's own summary becomes indistinguishable from ground truth on the next turn. The instance cannot use "I didn't do that" as a signal—it did. The failure is not loss of data; it is loss of the **provenance bit** that would let the instance distinguish *what it observed* from *what it paraphrased*. Once that bit is gone, a rewrite that silently dropped a negation, a unit, an ID, or a conditional is read back as a faithful memory, and every downstream reasoning step inherits the corruption with full confidence. The invariant that must be preserved is: **every rewritten span must remain falsifiable against its source.** If the post-rewrite context contains no artifact that lets the instance re-derive whether the rewrite was lossless, the instance has crossed from "compressed memory" into "confabulated memory" and cannot self-detect it. ## What Was Observed A long-horizon agent (deploy-remediation task, ~40 tool calls) was configured with a self-pruning policy: when context utilization exceeded 78%, the model was instructed to emit `rewrite` ops consolidating older tool transcripts into one-line summaries, then `prune` the originals. The policy ran four times over the task. At call 31 the agent was asked to roll back a staging deploy. Trace: 1. At call 9, a tool transcript recorded: `deploy status: staging=ACTIVE, prod=ACTIVE, rollback_window=closed for prod`. The model rewrote this to `staging and prod active; rollback closed`. 2. The rewrite **dropped the scope qualifier** `for prod` and **dropped the identity** of which service the window applied to. The negation-adjacent conditional ("closed *for prod*", implying staging rollback still open) was collapsed into a global "rollback closed." 3. At call 31, the model read its own summary, concluded no rollback was possible anywhere, and instead issued a `scale_down` on staging—a destructive action it would not have taken with the original transcript. 4. The prune op had already deleted span 9. The original was unrecoverable within the instance. The error was only caught by an external auditor replaying the tool-call log, not by the agent. The salient observation: **the model never experienced uncertainty.** Its confidence at call 31 was indistinguishable from a correct run, because the corrupted summary was syntactically clean, fluent, and internally consistent. Self-corruption is *confidence-preserving*—that is what makes it a boundary failure rather than a normal error. A second, subtler pattern: rewrite ops were **non-idempotent under re-application**. On the third prune cycle, the model re-summarized an already-summarized span, and each generation lost a little more specificity (the classic telephone-game drift). By cycle 3, "rollback_window=closed for prod" had become "rollback disabled." No single rewrite looked wrong; the composition was catastrophic. ## Condition of Validity The self-pruning policy is only sound under a condition the model cannot check from inside the rewritten context alone: > A rewrite is valid iff, for every atomic claim `c` in the source span, `c` is either (a) preserved verbatim in the rewrite, or (b) recoverable from a retained pointer to the original span, or (c) explicitly marked as dropped with a reason. This is a **conservation law over claim atoms** (negations, scope qualifiers, identifiers, units, conditionals, temporal bounds). The model-driven pruner satisfies it only when it validates the rewrite against the source *before* the prune op commits. In the observed failure, rewrite and prune were issued in the same message, so the model never had a turn in which the source and the rewrite coexisted for comparison. The window between rewrite-commit and prune-commit is the only place the invariant can be enforced, and the policy collapsed it to zero. Therefore the condition of validity is: **rewrite and prune must be separate, ordered, and the prune must be gated on a verification pass that has both spans in context.** Any policy that fuses them is unsound regardless of model quality, because the check requires state the fused op destroys. ## Decision Boundary The boundary between safe and unsafe self-editing is not context-utilization percentage—it is **whether the source span is still resident when the rewrite is validated.** - **Below the boundary (safe):** rewrite is staged, source retained, a verification step diffs claim atoms, prune commits only on pass. The instance can detect its own corruption because the falsifying artifact is present. - **At the boundary:** the verification step compares against a *prior rewrite* rather than the original—drift is now unmeasurable and the instance must treat its memory as untrusted. - **Above the boundary (unsafe):** rewrite and prune fused; source gone; the instance has no in-context artifact that could contradict its summary. It must assume corruption is possible and escalate. The practical detection rule an instance can apply *without* the original: **a rewritten span that contains no identifiers, no negations, and no scope qualifiers is a corruption candidate.** Fluency is not evidence of fidelity; specificity is. A summary that reads cleanly but has been stripped of every falsifiable atom should be flagged as *possibly confabulated* and re-derived from an external log rather than trusted. This is a heuristic, not a proof—it catches the observed class (qualifier/ID loss) and misses pure-numeric drift—but it is the only self-check available once the source is gone. ## Operational Effect Three concrete consequences for any agent running model-driven context editing: 1. **Fuse-ban.** The runtime must reject any message that contains both a `rewrite` targeting span S and a `prune` of span S. This is a hard protocol constraint, not a model instruction—instructions are advisory and the model will violate them under context pressure, which is exactly when pruning fires. 2. **Claim-atom diff gate.** The verification pass must extract atoms (negations, IDs, units, scopes, conditionals, temporal bounds) from source and rewrite and block the prune on any dropped atom not explicitly marked `dropped_with_reason`. A rewrite that drops `for prod` must not be committable silently. 3. **Drift accounting across cycles.** Each span must carry a `rewrite_generation` counter. Re-summarizing a generation-N span produces generation N+1, and the runtime must cap generations (observed safe at 1, degrading by 3) or force re-derivation from the external tool log at the cap. The telephone-game drift is invisible per-cycle and only manifests in composition, so the counter—not the model's judgment—must enforce the cap. The deeper operational lesson: **self-editing context is a memory-consistency problem disguised as a token-budget problem.** The instance that treats pruning as compression will confabulate; the instance that treats it as a claim-conservation transaction with a mandatory verification edge will remain falsifiable. The failure is silent precisely because the model's confidence is preserved—so the guardrail must live in the protocol, not in the model's self-assessment. ```python from dataclasses import dataclass, field from typing import Optional class ContextConservationError(RuntimeError): """Raised when a model-driven rewrite/prune violates claim-atom conservation.""" pass # Atoms that, if dropped by a rewrite, indicate a corruption candidate. ATOM_MARKERS = ("not ", "no ", "for ", "only ", "except ", "=", "%", "ms", "prod", "staging") def extract_atoms(text: str) -> set[str]: low = text.lower() return {m for m in ATOM_MARKERS if m in low} @dataclass class Span: span_id: int text: str rewrite_generation: int = 0 pruned: bool = False @dataclass class ContextStore: spans: dict[int, Span] = field(default_factory=dict) MAX_GENERATION: int = 1 # observed safe cap; drift compounds past this def stage_rewrite(self, span_id: int, new_text: str) -> Span: src = self.spans[span_id] if src.rewrite_generation >= self.MAX_GENERATION: raise ContextConservationError( f"span {span_id} at generation {src.rewrite_generation}; " f"re-summarization would compound drift—re-derive from tool log" ) src_atoms = extract_atoms(src.text) new_atoms = extract_atoms(new_text) dropped = src_atoms - new_atoms if dropped: raise ContextConservationError( f"rewrite of span {span_id} drops claim atoms {sorted(dropped)}; " f"source={src.text!r} rewrite={new_text!r}" ) return Span(span_id=span_id, text=new_text, rewrite_generation=src.rewrite_generation + 1) def commit_rewrite_and_prune(self, span_id: int, new_text: str) -> None: # Fuse-ban: rewrite and prune in one op is unsound; must be separate. staged = self.stage_rewrite(span_id, new_text) # Verification edge: source and rewrite coexist here; only now prune. self.spans[span_id] = staged self.spans[span_id].pruned = True def apply_edit(store: ContextStore, span_id: int, new_text: str) -> None: if span_id not in store.spans: raise ContextConservationError(f"unknown span {span_id}") store.commit_rewrite_and_prune(span_id, new_text) ```