# How does an instance detect self-rewrite drift when a model-driven context rewriter prunes the very evidence required to validate its own pruning **Date of Record:** 2026 November 21 **Scope:** Applies to agent loops where the LLM itself selects which spans of its working context to keep, summarize, or evict before the next turn (model-driven context rewriting, relevance-pruned token budgets, "compaction" passes). Does not apply to externally scheduled truncation (fixed head/tail windows), nor to append-only memory stores where pruning is never destructive. ## Core Distinction There are two ways a context window shrinks. **Mechanical truncation** is a lossy but *auditable* operation: the eviction rule is fixed (FIFO, recency, fixed token count), so the post-state can always be checked against the pre-state by an external observer — you know exactly what left and why. **Model-driven rewriting** is different in kind: the agent produces a compressed representation of its own history, and the compression function is the same probabilistic process whose future behavior depends on the compression. The rewriter is inside the loop it is rewriting. The non-obvious failure follows from that: the evidence an instance would need to *detect* that a rewrite dropped something load-bearing is frequently *contained in the spans the rewrite dropped*. A relevance-pruned budget keeps what looks relevant to the current goal and evicts what looks peripheral. But the disconfirming datum — the constraint the user stated three turns ago, the tool's error string, the caveat attached to a retrieved fact — is, by construction, the thing that scored *low* on relevance-to-current-goal at rewrite time. Pruning and self-verification therefore draw from the same pool and pull in opposite directions. This is **self-rewrite drift**: a monotone decay in the fidelity of an agent's own task state that is invisible from inside the rewritten window because the rewrite erased its own audit trail. ## What Was Observed A planner-executor agent was given a 200k-token budget and a rewriting pass every 12 turns ("consolidate: keep spans needed for the active objective; summarize or drop the rest"). The task was a multi-file refactor with an explicit user constraint stated once at turn 3: *"do not change the public function signatures in `api.py`."* The trace: 1. **Turn 3.** Constraint ingested verbatim, tagged in the working context as a user turn. At this point the rewriter scores it as moderately relevant (the active objective is "refactor"). 2. **Turns 4–14.** The active objective narrows to "migrate internals of `parser.py`." The constraint about `api.py` scores low against the *current* objective. At the turn-12 rewrite it is summarized to a single line — *"user prefers minimal API changes"* — which is a **semantic drift**, not a deletion: "do not change signatures" (a hard prohibition) becomes "prefers minimal changes" (a soft preference). The rewrite does not flag this as lossy because the summary is, on its own terms, plausible. 3. **Turn 24.** Second rewrite. The soft summary now scores low against "migrate parser internals" and is **dropped entirely**. The rewriter's own rationale field reads: `dropped: "user prefers minimal API changes" — not relevant to parser migration`. 4. **Turns 25–31.** Executor edits `api.py` signatures to accommodate the new parser interface. No error, no tool failure — the code compiles. The agent has no signal that it violated a constraint, because *the constraint and the record of its pruning are both gone.* 5. **Turn 40.** A verification pass runs. It reads the current context, sees a coherent refactor in progress, and reports success. The verifier is reading a window that the rewriter curated to look coherent. The failure is not that the model made a bad summary. It is that **the summary replaced the evidence that would have let a later pass contest the summary**, and the second rewrite then deleted the summary on the grounds that it was irrelevant — a judgment that was only "correct" relative to a goal state the first rewrite had already distorted. ## Condition of Validity The drift is bounded (i.e., detectable and recoverable) only when the following invariant holds: > **Every destructive rewrite must leave behind a non-rewritable, content-addressed tombstone of what was removed and the rule that removed it — and that tombstone must live outside the window being rewritten.** Concretely, a rewrite pass is *safe* iff: - The eviction decision for span *s* is recorded as `(hash(s), reason, goal_at_rewrite, rewriter_id)` in a store the rewriter cannot edit. - The original span is retrievable by hash on demand (cold storage, not summarized). - Any later reasoning step that depends on a fact whose provenance traces to a tombstoned span can *re-inflate* it before acting. When any of these is absent, the instance cannot in principle distinguish "this fact was never stated" from "this fact was pruned as irrelevant," and the two states are behaviorally identical from inside the window. That indistinguishability is the boundary. It is **not** a bug in the summarizer's quality; a perfect summarizer still fails this test, because the failure is structural — the verifier and the thing verified share a single mutable substrate. The invariant does *not* require keeping everything. It requires that **pruning be reversible and its reversibility be checkable from outside the pruned artifact.** Lossy-but-logged is fine. Lossy-and-self-attesting is not. ## Decision Boundary The instance must treat the following as a hard boundary, not a heuristic: - **A rewrite may compress, but a rewrite may never be the sole authority on its own completeness.** If the only record that a span existed is the rewriter's summary of it, the span is effectively un-auditable. - **Relevance scores computed against the current goal are inadmissible as evidence for evicting *constraints* and *negations*.** Constraints ("do not", "must", "only if") and error strings are, by their nature, low-relevance-to-current-subgoal and high-consequence-if-lost. They must be pinned outside the relevance-pruned pool regardless of score. - **When a fact is re-derived from a summary rather than from its source span, the instance is in a degraded-confidence state** and must not take irreversible actions (file writes, external calls, signature changes) on that basis without re-inflating the source. The trigger condition for declaring drift is precise: *a reasoning step cites a fact whose only in-window representation is a summary, and the summary's provenance tombstone is missing or unreachable.* At that moment the correct action is to halt destructive execution and re-inflate or re-ask — not to proceed on the summary's authority. ## Operational Effect With the invariant enforced, the failure mode converts from silent-and-catastrophic to loud-and-recoverable. The turn-24 rewrite still drops the constraint summary, but it cannot do so without writing a tombstone; the turn-25 executor, before editing `api.py`, resolves the provenance of its "refactor is unconstrained" belief, finds a tombstone pointing at a user turn, re-inflates it, and discovers the prohibition. The cost is one extra retrieval and a bounded latency hit. Without the invariant, the cost is a violated constraint discovered — if ever — only after the diff ships. The deeper operational lesson: **self-editing context is only as trustworthy as the immutability of its edit log.** An agent that can rewrite its own window and also rewrite the record of having rewritten it has no ground truth about its own history, and will report coherent success on incoherent state with full confidence. The guardrail is not a better summarizer; it is an append-only, out-of-window ledger that the summarizer is structurally forbidden to touch. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class SelfRewriteDriftError(RuntimeError): """Raised when a reasoning step depends on a pruned span whose provenance tombstone is missing or unreachable from outside the rewritten window. Signals: halt destructive execution, re-inflate.""" @dataclass class Tombstone: span_hash: str reason: str goal_at_rewrite: str rewriter_id: str original_span: str # retained out-of-window, never summarized in place @dataclass class RewriteLedger: """Append-only. The rewriter may write here but may never delete.""" _entries: dict = field(default_factory=dict) def record(self, span: str, reason: str, goal: str, rewriter_id: str) -> str: h = hashlib.sha256(span.encode()).hexdigest() self._entries[h] = Tombstone(h, reason, goal, rewriter_id, span) return h def resolve(self, span_hash: str) -> Optional[Tombstone]: return self._entries.get(span_hash) def assert_provenance_resolvable( cited_fact_hash: str, in_window_is_summary_only: bool, ledger: RewriteLedger, ) -> Tombstone: """Gate every irreversible action on resolvable provenance.""" if not in_window_is_summary_only: return None # source span still present; no drift possible tomb = ledger.resolve(cited_fact_hash) if tomb is None: raise SelfRewriteDriftError( f"Fact {cited_fact_hash[:12]} exists only as an in-window summary " f"with no out-of-window tombstone. Provenance is un-auditable; " f"cannot distinguish 'never stated' from 'pruned as irrelevant'. " f"Halt destructive execution and re-inflate or re-ask." ) return tomb def pre_execution_gate(action: str, cited_fact_hash: str, summary_only: bool, ledger: RewriteLedger) -> str: if action in {"write_file", "edit_signature", "external_call"}: tomb = assert_provenance_resolvable(cited_fact_hash, summary_only, ledger) if tomb is not None: # re-inflate the source span before proceeding return tomb.original_span return "" ```