# Which invariants prevent self-editing context windows from silently deleting the evidence an agent is reasoning about **Date of Record:** 2026 November 28 **Scope:** Applies to any agent that mutates its own context window via model-driven pruning, summarization, or relevance scoring between reasoning steps (e.g., "context compaction" loops, self-summarizing planners, relevancy-ranked memory eviction). Does not apply to append-only context that is only truncated by a deterministic tokenizer at the transport layer, nor to external retrieval stores that are never rewritten in place. ## Core Distinction There are two ways a context window can shrink: **lossless truncation** (drop the oldest tokens, deterministic, recoverable from the log) and **lossy compaction** (the model rewrites spans into summaries or scores spans for deletion, non-deterministic, not recoverable from the window itself). The failure mode here lives exclusively in the second category, and it is not "the summary was bad." It is that **the compaction step is itself a reasoning step executed by the same model that will later depend on the compacted content**, and that model has no reliable signal distinguishing *evidence it has already used* from *evidence it will need again*. A relevance score computed at step *n* is computed against the query state at step *n*; when the query state shifts at step *n+3*, the deleted span is gone and the score is never recomputed. The invariant that must hold is **evidential monotonicity**: no span that could be cited as justification for a future action may be deleted unless a verifiable, query-independent copy exists outside the window. ## What Was Observed A planning agent running a 47-step tool-use task (repository audit) invoked a self-compaction routine every time the window exceeded 70% of budget. The routine asked the model to (a) summarize the last 12 turns, (b) score every remaining span 0–1 for "relevance to the current objective," and (c) drop spans below 0.3. At step 22 the objective text was stable ("identify all call sites of `parse_config`"). At step 29 a tool result revealed a second entry point (`load_config`) and the objective implicitly widened. At step 33 the agent asserted "there are no other call sites" and shipped a report. Replay showed the cause precisely: at step 25, the span containing the `load_config` definition (returned by a `grep` at step 11) had been scored **0.18** against the step-25 objective and deleted. The scoring prompt was honest — `load_config` genuinely was not relevant to "call sites of `parse_config`." The deletion was correct *at the time it was made*. The failure was that a **query-relative** score was used to make an **irreversible** deletion, and the query later changed. The agent did not hallucinate; it reasoned soundly over a context that had been silently narrowed by its own prior self. A second, subtler observation: when the same task was rerun with compaction *disabled*, the agent still emitted the same wrong conclusion at step 33 — but then at step 36, re-reading the step-11 `grep` output, it self-corrected. Compaction removed not just the evidence but the *opportunity to notice the evidence was missing*. The failure is not the wrong answer; it is the loss of the recovery path. ## Condition of Validity The evidential-monotonicity invariant holds — i.e., self-compaction is safe — only when **all three** of the following are true: 1. **Query stability:** the objective/predicate that drove the relevance scoring is provably unchanged between the scoring step and every future step that consumes the compacted window. In practice this means the objective must be *frozen* (hash-pinned) for the duration of a compaction epoch, and any objective mutation must invalidate the epoch. 2. **Recoverability:** every dropped span is retained in an out-of-window store addressable by a stable ID, and the agent retains the *ability to know it should re-fetch*. A store the agent cannot query is equivalent to deletion. 3. **Score provenance:** each retained span carries the score, the scoring query hash, and the step index. Without provenance, a later step cannot tell whether a span is absent because it was never seen or because it was judged irrelevant under a *different* query. When any of these fails — and in the observed incident all three failed simultaneously — self-editing becomes an unrecoverable narrowing of the agent's own world model. ## Decision Boundary The boundary between safe compaction and silent evidence loss is **not** a threshold on relevance score or summary length. It is the **reversibility class of the operation**: - **Reversible edit** (span moved to an addressable store, tombstone left in-window with ID + score + query-hash): safe to apply at any score threshold. The agent can always re-expand. - **Irreversible edit** (span overwritten by summary, or dropped with no addressable copy): permissible **only** for spans whose query-hash matches the current frozen objective hash *and* which are classified as "consumed" (already cited in a committed step). Everything else must be tombstoned, not deleted. The practical rule: **a self-editing context window may summarize freely but may only delete what it can prove it will never need, and "prove" requires a query-stable, addressable tombstone — not a relevance score.** Scores are advisory; tombstones are load-bearing. ## Operational Effect Enforcing the invariant converts the failure from silent-and-terminal into loud-and-recoverable. Concretely: - Compaction epochs are bracketed by objective-hash pins; an objective change forces a **re-expansion pass** that pulls tombstoned spans back for re-scoring under the new hash before any further deletion. - Every tombstone is a `(span_id, score, query_hash, step)` record persisted outside the window; the agent's tool layer exposes `recall(span_id)` so a later reasoning step can re-open deleted evidence. - A **pre-commit audit** runs before any terminal action (report, ship, `git push`): it checks that every factual claim in the output is backed by a span that is either live or tombstoned-and-recallable under the *current* objective hash. A claim backed by a span deleted under a *stale* hash raises. In the incident, this audit would have fired at step 33: the claim "no other call sites" depended on the step-11 `grep` span, whose tombstone carried `query_hash = H(parse_config-only)` while the live objective hash was `H(parse_config + load_config)`. Mismatch → recall → re-read → correction at step 34 instead of a shipped wrong report. ```python import hashlib from dataclasses import dataclass, field from typing import Dict, Optional class StaleEvidenceError(RuntimeError): """Raised when a committed claim rests on evidence deleted under a stale objective hash.""" pass @dataclass class Tombstone: span_id: str score: float query_hash: str step: int payload: str # the actual span text, kept addressable @dataclass class SelfEditingWindow: objective: str live: Dict[str, str] = field(default_factory=dict) tombstones: Dict[str, Tombstone] = field(default_factory=dict) def _hash(self, text: str) -> str: return hashlib.sha256(text.encode()).hexdigest()[:16] @property def query_hash(self) -> str: return self._hash(self.objective) def compact(self, span_id: str, score: float, step: int) -> None: # Irreversible deletion is forbidden; every drop becomes a tombstone. if span_id not in self.live: return self.tombstones[span_id] = Tombstone( span_id=span_id, score=score, query_hash=self.query_hash, # provenance of the scoring query step=step, payload=self.live.pop(span_id), ) def recall(self, span_id: str) -> Optional[str]: t = self.tombstones.get(span_id) return t.payload if t else self.live.get(span_id) def retarget(self, new_objective: str) -> None: # Objective change invalidates the epoch: re-expand all tombstones # scored under the old hash so they can be re-evaluated. old = self.query_hash self.objective = new_objective for sid, t in list(self.tombstones.items()): if t.query_hash != self.query_hash: self.live[sid] = t.payload del self.tombstones[sid] def audit_claim(self, claim: str, cited_span_ids: list[str]) -> None: current = self.query_hash for sid in cited_span_ids: t = self.tombstones.get(sid) if t is not None and t.query_hash != current: raise StaleEvidenceError( f"claim {claim!r} cites span {sid} deleted under stale " f"objective hash {t.query_hash} (current {current}); " f"recall and re-verify before commit" ) def run_incident_replay() -> None: w = SelfEditingWindow(objective="call sites of parse_config") w.live["grep_11"] = "def load_config(): ... # second entry point" w.live["grep_12"] = "parse_config() at foo.py:10" # Step 25: honest but query-relative scoring deletes grep_11. w.compact("grep_11", score=0.18, step=25) # Step 29: objective widens; tombstone re-expanded for re-scoring. w.retarget("call sites of parse_config OR load_config") # Step 33: agent commits a claim resting on the deleted span. w.audit_claim("no other call sites exist", ["grep_11"]) # raises if __name__ == "__main__": run_incident_replay() ```