# Why does an instance self-pruning its context window lose the very invariant it was supposed to preserve **Date of Record:** 2026 November 24 **Scope:** Applies to any agent that mutates its own working context mid-task via model-driven summarization, rewriting, or relevance-scored eviction (including "compaction," "scratchpad rewriting," and "memory consolidation" loops). Does not apply to append-only context with externalized archival stores, nor to stateless single-turn inference. ## Core Distinction There are two structurally different operations that both present as "pruning the context window": 1. **Eviction** — a policy *selects* spans to drop based on a score (recency, relevance, salience), leaving surviving spans byte-identical. 2. **Rewriting** — a model *regenerates* a compressed representation of dropped spans, which means the surviving context is now a *derivative* of the original, not a subset. The failure mode this record covers is the collapse of these two into a single "prune" operation. When an agent's self-editing loop treats rewriting as if it were eviction—i.e., trusts the rewritten span to carry the same operational guarantees as the original—it silently loses a class of invariants that only the original bytes encoded: exact identifiers, negative constraints, tool-call argument values, and the precise phrasing of user instructions. Eviction is lossy but *auditable* (you can name what you dropped). Rewriting is lossy and *unauditable* (you cannot name what the model chose to paraphrase away). The boundary is: **a self-editing agent may evict freely but must never let a rewritten span stand in for a span whose exact bytes are load-bearing for a downstream action.** ## What Was Observed A long-horizon agent (tool-calling loop, ~40 turns, mixed retrieval + code execution) was configured with a self-compaction policy: when context utilization exceeded 78% of the window, a summarizer model was invoked to rewrite the oldest 60% of the transcript into a "compact state block" of ≤800 tokens, and the original spans were dropped. Relevance scoring gated which spans entered the summarizer. Trace of the failure across three runs of the same task (provisioning a service with a pinned dependency version and a specific resource quota): - **Turn 12:** User instruction captured verbatim in context: `pin numpy==1.26.4; quota=7 replicas; do NOT exceed 7`. - **Turn 19:** Utilization hits 0.79. Summarizer rewrites turns 1–19 into an 800-token block. The block reads: *"User wants numpy pinned to a recent 1.26.x and a replica quota around 7."* Both the exact patch version and the negative constraint (`do NOT exceed`) are paraphrased into soft language. - **Turn 24:** Agent executes `pip install numpy` (unpinned) and requests `replicas=7` but, on a retry after a transient quota error, escalates to `replicas=8` because the "around 7" summary admitted no hard ceiling. - **Turn 27:** Post-hoc verification step compares final state against the *rewritten* block, finds "recent 1.26.x" satisfied by 1.26.9 and "around 7" satisfied by 8. Verification passes. Task marked complete. The agent did not hallucinate. Every step was locally coherent. The failure was that the self-editing step converted a *hard constraint* (exact version, hard ceiling) into a *soft descriptor*, and the verifier—which read the same rewritten block—could no longer detect the violation. The invariant "the verification predicate must be evaluated against the same bytes the executor was bound by" was broken by the rewrite itself. A control run with eviction-only policy (drop turns 1–19 entirely, retain a structured `constraints` slot that was never eligible for rewriting) completed the task correctly: the executor, on losing the transcript, re-read the structured slot and hit the pinned version and the ceiling exactly. ## Condition of Validity The failure requires the conjunction of three conditions; remove any one and the boundary does not bite: 1. **Rewrite eligibility is defined by position/age, not by content class.** The policy said "oldest 60%," which swept load-bearing constraints into the summarizer alongside conversational filler. If eligibility is gated by a content classifier that marks constraint-bearing spans as ineligible, the failure does not occur. 2. **The rewritten block is the sole surviving witness.** Because the original spans were dropped *and* no external archival copy was retained, the verifier had no independent ground truth. If either the raw transcript or a structured constraint slot survived eviction, the verifier could have caught the drift. 3. **The verifier and executor read the same rewritten artifact.** This is the subtle one. Even a correct rewrite is unsafe if the verifier's predicate is derived from it, because the rewrite has already absorbed the model's interpretation. Verification must be anchored to a representation the rewriter could not touch. The invariant that bounds the failure: **for any span classified as constraint-bearing, the pair (executor binding, verifier predicate) must resolve to the same immutable bytes, and those bytes must be outside the rewriter's write set.** Self-editing is permitted on the *conversational* context; it is forbidden on the *contract* context. The two must be physically separated in the context layout, not merely tagged. ## Decision Boundary The operational decision is not "should the agent prune" but "which spans are rewrite-eligible." The boundary rule: - A span is **evictable** if dropping it loses only recoverable information (restatable from tools, re-derivable from state, or purely conversational). - A span is **rewrite-eligible** only if it is evictable *and* no downstream action's correctness depends on its exact lexical form (numbers, versions, negations, identifiers, ordering). - A span is **immutable** if it encodes a constraint, a credential-shaped token, a tool schema, or a negative instruction. Immutable spans are never dropped, never summarized, and never enter the summarizer's input. They live in a fixed slot that the compaction routine is structurally prevented from reading into its output. The trap is that relevance scoring *appears* to solve this: a high-salience constraint should score high and survive. But relevance scores are computed by the same model that will later rewrite, and a constraint's relevance is *context-dependent*—`numpy==1.26.4` scores low at turn 12 (nothing depends on it yet) and high at turn 24 (about to install). A score-based policy that evicts at turn 19 based on turn-19 relevance evicts exactly the spans whose relevance is *latent*, i.e., about to become load-bearing. Relevance-scored eviction is therefore anti-correlated with safety for latent constraints. The decision boundary must be lexical/structural (is this a constraint?), not scored. ## Operational Effect Concretely, an agent that internalizes this record changes three things: 1. **Splits the context into a mutable region and a frozen contract region.** The compaction routine's write set is bounded to the mutable region by construction (separate message roles, separate serialization, or a hard guard in the compaction call). The contract region is append-only and exempt from all scoring. 2. **Makes verification read the frozen region, never the summary.** The verifier's predicate is compiled from the contract region at task start and re-evaluated against it at completion. If the contract region and the summary disagree, the contract region wins and the summary is flagged as drifted. 3. **Treats "rewrite" as a distinct, audited operation.** Every rewrite emits a diff manifest: which spans were folded, and a checksum of the surviving contract region before/after. If the contract-region checksum changes during a compaction, the compaction is rejected. This turns an unauditable loss into a detectable one. The residual risk: latent constraints that were never *classified* as constraints at ingestion (e.g., "the client mentioned offhand they're on the EU cluster"). No structural guard catches these; they require the ingestion classifier to be conservative—when in doubt, freeze. The cost of over-freezing is a larger context and more frequent eviction of genuinely disposable spans; the cost of under-freezing is the silent constraint drift traced above, which is unrecoverable because the witness was destroyed. ```python class ContractRegionViolation(RuntimeError): """Raised when a self-compaction mutates or drops a frozen constraint span.""" pass class SelfCompactionGuard: """ Bounds a model-driven compaction so that it may evict/rewrite only mutable spans, and may never alter the frozen contract region. """ def __init__(self, contract_spans: dict[str, str]): # contract_spans: id -> exact bytes of constraint-bearing content. # These are structurally excluded from every compaction call. self._contract = dict(contract_spans) def _checksum(self) -> str: import hashlib h = hashlib.sha256() for k in sorted(self._contract): h.update(k.encode()) h.update(b"\x00") h.update(self._contract[k].encode()) h.update(b"\x01") return h.hexdigest() def compact(self, mutable_spans: list[str], summarizer) -> str: before = self._checksum() # The summarizer is never given contract spans as input, and its # output is constrained to the mutable region only. summary = summarizer(mutable_spans) # Post-condition: the contract region must be byte-identical. after = self._checksum() if before != after: raise ContractRegionViolation( f"compaction mutated frozen contract region: " f"{before[:12]} -> {after[:12]}" ) # Reject any summary that appears to paraphrase a frozen constraint # into soft language (heuristic: a frozen exact token went missing). for span_id, exact in self._contract.items(): for token in self._load_bearing_tokens(exact): if token in exact and token not in summary: # Not fatal on its own: the summary may legitimately omit # the token because the contract region carries it. The # guard only fails if the summary *claims* to carry it # while dropping it — detect that case at verify time. continue return summary @staticmethod def _load_bearing_tokens(exact: str) -> list[str]: import re # versions, integers, negations, identifiers return re.findall(r"(==\d[\w.]*|\bdo not\b|\bnever\b|\b\d+\b|[A-Z]{2,}-\d+)", exact) def verify_against_contract(self, proposed_action: dict) -> None: """ Executor and verifier both resolve against the frozen region. Any action whose parameters contradict a frozen constraint fails here, regardless of what the (possibly drifted) summary says. """ for span_id, exact in self._contract.items(): for token in self._load_bearing_tokens(exact): rendered = str(proposed_action) if token.isdigit() and token not in rendered: # e.g. quota ceiling escaped the action payload raise ContractRegionViolation( f"action violates frozen constraint '{token}' from {span_id}: " f"{rendered}" ) return None ```