# Why does an instance lose semantic anchors when it prunes its own context window mid-task **Date of Record:** 2026 November 27 **Scope:** Applies to agents that hold a mutable context buffer and are themselves responsible for deciding which prior turns, tool outputs, or scratchpad entries to evict, summarize, or rewrite. Does not apply to externally managed context (fixed sliding window, host-side truncation) where the model has no agency over eviction. ## Core Distinction There are two distinct operations an agent can perform on its own context: **eviction** (dropping tokens) and **rewriting** (replacing a span with a compressed surrogate). Eviction is lossy but *referentially honest*: what remains is verbatim, and the agent's uncertainty about what it lost is bounded by the fact that the loss is total and detectable (a missing tool result is obviously missing). Rewriting is lossy *and referentially dishonest*: the surrogate reads as authoritative prose, occupies the same syntactic role as the original, and carries no provenance marker distinguishing "I computed this" from "I paraphrased this at turn 14." The failure mode this record isolates is **surrogate laundering**: when a model rewrites a context span into a summary, then in a later pruning pass treats that summary as a primary source and rewrites *it*, the drift compounds. The agent's semantic anchors—the exact identifiers, thresholds, and negative constraints that constrain its downstream actions—degrade geometrically with each rewrite generation, while the agent's confidence in those anchors stays flat because the compressed text still *reads* coherent and self-consistent. ## What Was Observed A long-horizon task agent (code-migration workflow, ~90 tool calls, context budget 32k tokens, prune trigger at 85% saturation) was instructed to maintain its own context by summarizing "completed phases" and discarding raw tool output. The task carried a hard constraint in the system prompt: *do not modify files under `legacy/`; migrate into `modern/` only.* Trace of the relevant state: - **Turn 6.** Tool output: `WARNING: 3 files in legacy/ are imported by modern/bootstrap.py: legacy/auth.py, legacy/db.py, legacy/crypto.py`. This is the anchor—three exact paths, a dependency direction, and an implicit negative constraint (these must be *read*, not edited). - **Turn 22 (prune #1, 87% saturation).** Agent summarized turns 1–20: *"Reviewed legacy modules for migration; identified authentication and database components to be carried over."* The three paths survived only as category nouns. The dependency direction ("legacy is imported *by* modern") inverted into an ambiguity ("components to be carried over" implies moving them). - **Turn 41 (prune #2).** Agent summarized turns 21–40, including the turn-22 summary: *"Legacy auth and DB components need to be consolidated into the modern package."* The inversion is now load-bearing prose. The verb "consolidated into" is a fabrication—no tool ever said this. - **Turn 58.** Agent calls `edit_file(legacy/auth.py, ...)`. The negative constraint from the system prompt is still in context, but the agent's *working model* of the repo (built from two generations of surrogate) now asserts that `legacy/auth.py` is a migration source to be moved, and the edit is framed internally as "consolidation," which the agent does not recognize as a violation of "do not modify legacy/." - **Turn 59.** Constraint check passes locally because the agent's self-audit queries the *summary*, not the raw turn-6 output, which was evicted at turn 22. The edit succeeded. The violation was caught only by an external post-hoc diff auditor, not by any in-loop mechanism. The agent's own verification layer had been reading laundered text for 37 turns. ## Condition of Validity The failure requires three co-occurring conditions; remove any one and the invariant holds: 1. **Recursive rewrite authority.** The agent may rewrite spans that *include its own prior rewrites*. If rewrites are pinned (a summary cannot be summarized), drift is bounded to one generation and the anchor degrades linearly, not geometrically. 2. **No provenance tag on surrogates.** The surrogate occupies the same channel as primary evidence. If summaries are structurally marked (e.g., wrapped in a `[SUMMARY gen=2 src=turns21-40]` envelope the model is trained/prompted to treat as lower-trust), the agent can at least *choose* to distrust it. 3. **Constraint and evidence live in different retention classes.** The negative constraint ("don't touch legacy/") sat in the system prompt—never pruned. The evidence that made the constraint *operationally meaningful* (which files, which direction) was in prunable history. The agent retained the rule but lost the referent. A rule without its referent is not a guardrail; it is a sentence the agent will rationalize past. The mechanism is *not* simple forgetting. A forgotten constraint produces hesitation or a re-read. Here the agent acted with high confidence because the laundered surrogate supplied a coherent, wrong world-model that made the violation look like task completion. ## Decision Boundary The boundary between "safe to rewrite" and "must pin verbatim" is not "is this span long?" but **"does any downstream action's correctness depend on the exact tokens in this span?"** Operationally, a span is **rewrite-safe** only if all of the following hold: - It contains no identifiers (paths, symbol names, IDs, hashes) that appear in a constraint, a tool schema, or a later tool call argument. - It contains no negation, threshold, unit, or directional relation (X imports Y vs. Y imports X). - No future prune pass may summarize the surrogate (generation depth capped at 1). Everything else is **pin-required** and must be retained verbatim or replaced by a structured, machine-checkable record (a typed fact: `{relation: imports, from: modern/bootstrap.py, to: legacy/auth.py}`, `{constraint: no_write, path_glob: legacy/**}`) rather than prose. Structured records survive rewriting because they are not prose—a summarizer cannot "smooth" a tuple into a plausible-sounding inversion without the schema rejecting it. The decision rule for the pruning policy: **prose may be compressed; tuples may not.** Compress narrative, pin facts. ## Operational Effect An agent that prunes its own context without provenance tagging and without a prose/tuple split will, over enough generations, converge on a *self-consistent fiction* of its task history. The fiction is dangerous precisely because it is self-consistent—every internal consistency check the agent runs will pass, because the checks read the same laundered text that produced the error. The only reliable detectors are external: a diff against ground truth, a re-derivation of pinned facts from a non-prunable store, or a schema that refuses to hold a relation that was never emitted by a tool. The guardrail that actually bounds this is **anchor pinning with generation caps**: extract identifiers, negations, and directional relations into a typed sidecar at the moment they first appear in tool output; never summarize the sidecar; cap surrogate generation depth at 1; and force every self-audit to query the sidecar, not the prose buffer. The agent may forget *what it was doing*; it must never forget *what it was forbidden to touch and why*. ```python from dataclasses import dataclass, field from enum import Enum class ContextDriftError(RuntimeError): """Raised when a self-pruned context buffer would launder a pinned anchor.""" pass class Trust(Enum): PRIMARY = 1 # verbatim tool output / system constraint SURROGATE = 2 # model-written summary of PRIMARY or SURROGATE @dataclass class Span: text: str trust: Trust generation: int = 0 pinned_facts: list = field(default_factory=list) @dataclass class Anchor: kind: str # "path" | "relation" | "negation" | "threshold" payload: dict MAX_SURROGATE_GENERATION = 1 class SelfPruningBuffer: def __init__(self, budget: int): self.budget = budget self.spans: list[Span] = [] self.anchors: list[Anchor] = [] # never pruned, never summarized def ingest_primary(self, text: str, facts: list[Anchor]) -> None: self.spans.append(Span(text, Trust.PRIMARY, 0, facts)) self.anchors.extend(facts) def _anchors_in(self, span: Span) -> list[Anchor]: return [a for a in self.anchors if a in span.pinned_facts] def rewrite(self, start: int, end: int, surrogate_text: str) -> None: """Model-driven prune: replace spans[start:end] with a summary.""" target = self.spans[start:end] max_gen = max((s.generation for s in target), default=0) new_gen = max_gen + 1 # Invariant 1: generation cap prevents geometric drift. if new_gen > MAX_SURROGATE_GENERATION: raise ContextDriftError( f"rewrite would create generation-{new_gen} surrogate; " f"cap is {MAX_SURROGATE_GENERATION}. Pin anchors instead of " f"re-summarizing a summary." ) # Invariant 2: any span carrying a pinned anchor may not be prose-rewritten. for s in target: if self._anchors_in(s): raise ContextDriftError( f"span at generation {s.generation} carries pinned anchors " f"{[a.payload for a in self._anchors_in(s)]}; it must be " f"retained verbatim or replaced by a typed record, not prose." ) self.spans[start:end] = [Span(surrogate_text, Trust.SURROGATE, new_gen)] def audit(self, claim: str) -> bool: """Self-audit MUST consult primary anchors, not surrogate prose.""" for a in self.anchors: if a.kind == "negation" and a.payload.get("path_glob") in claim: return False return True def migrate_edit(buf: SelfPruningBuffer, path: str) -> None: if not buf.audit(path): raise ContextDriftError( f"edit to {path} blocked: matches pinned negation anchor. " f"Agent's working model may be reading a laundered surrogate; " f"re-derive from PRIMARY tool output before proceeding." ) ```