# Which invariants prevent self-editing context policies from silently evicting the one token the task depends on **Date of Record:** 2026 November 22 **Scope:** Applies to any agent that lets the model itself rewrite, prune, summarize, or relevance-score its own context window between turns (self-editing context managers, compaction loops, retention scorers). Does not apply to externally fixed sliding-window truncation or to stateless single-shot calls where the context is never re-authored by the model. ## Core Distinction There are two structurally different things an agent can do to its own context: *compress* and *evict*. Compression preserves a bijective-enough reconstruction of the original—a summary that still answers "what was the exact error string from step 3?" Eviction is lossy by construction: a token, span, or message is dropped and the model is thereafter operating on a strictly smaller information set with no record that the drop happened. The failure mode this record isolates is **relevance-score inversion at the boundary of a dependency**. A retention scorer ranks context spans by predicted relevance to the *current* turn. But agent tasks contain *latent dependencies*: a value observed at turn 3 (a UUID, an exact column name, a file path, a signed warrant, a constraint the user stated once) that is irrelevant to turns 4–20 and becomes load-bearing again at turn 21. The scorer, being a function of the current query, correctly assigns that span near-zero relevance for seventeen consecutive turns and evicts it. The eviction is not a bug in the scorer—the scorer did its job. The invariant that breaks is the one nobody wrote down: **a span may not be evicted on the basis of relevance-to-now if any not-yet-executed plan step references it.** ## What Was Observed A planner-executor agent running a multi-step data-migration task rewrote its own context every turn using a relevance-scored retention policy (keep top-k spans by cosine similarity to the last user/assistant turn plus a recency bonus; summarize the tail). The task required the agent to, at step 14, apply a transformation to a table whose exact name (`orders_2024_q3_staging`) had been stated once by the user in the opening message. Trace of the state transition: 1. Turn 1: user message contains the table name and the constraint "do not touch the production schema." Both scored high (relevance to turn 1 ≈ 1.0). Retained. 2. Turns 2–6: agent explores schema, runs `DESCRIBE` on several tables. The turn-1 message's relevance to each new turn decays; recency bonus for turns 2–6 dominates. The opening message falls below the top-k cutoff at turn 5 and is replaced by a *summary* that reads "User requested a data migration with schema-safety constraints." The exact table name and the exact constraint text are gone—the summary is semantically faithful but not *referentially* faithful. 3. Turns 7–13: agent proceeds confidently. The summary is sufficient for planning; nothing references the dropped literal. 4. Turn 14: executor emits a tool call targeting a table name it *reconstructs* from the summary plus the schema listing. It picks `orders_staging` (a real table, wrong quarter) because that string is present in the live schema context and matches the gist. The call succeeds. Rows are migrated to the wrong table. 5. Turn 18: verification step compares row counts and finds a mismatch, but the agent no longer has the original table name in context to know *which* table was intended. It cannot self-correct; it can only report an anomaly. The observable signature is not an error and not a hallucination in the classic sense. Every intermediate tool call returned success. The failure is a **silent referential drift**: the agent substituted a plausible literal for an exact one because the exact one had been evicted and only its gist survived. The summary was accurate at the semantic layer and catastrophically wrong at the referential layer. A second, sharper observation: the eviction was *irreversible within the episode*. Because the summarizer had already replaced the original span, and the summarizer's output was itself subject to the same retention policy on the next turn, there was no path back to the literal. The context had crossed a one-way boundary. ## Condition of Validity The guardrail below is only valid—and only necessary—under a specific conjunction of conditions. State them explicitly, because applying the guardrail outside them costs context budget for no benefit. The invariant **must** be enforced when all of the following hold: 1. **The context is model-authored.** The model, not a fixed external policy, decides what to keep. If truncation is deterministic (FIFO, token-count), the failure is loud (the model sees a missing region and can re-fetch); self-editing makes it silent. 2. **The task has a plan horizon longer than the retention window.** If every step's inputs are re-derivable from the current turn, eviction is harmless. The danger scales with the number of steps between observation and use. 3. **The evicted span contains literals that are not re-derivable.** Identifiers, exact strings, signed tokens, numeric thresholds, and negative constraints ("do not…") are the high-risk class. A span whose content can be regenerated from a tool call (e.g., a schema listing) is safe to evict; a span that encodes a *user decision* is not. 4. **Downstream steps are not verifiable against an external oracle.** If a later step can check the literal against ground truth, drift is caught. If the only record of the correct literal was the evicted span, it is not. When any of these fails, the cheaper policy (plain relevance scoring) is correct and the guardrail is overkill. The decision boundary section makes the cut explicit. ## Decision Boundary The boundary is between **relevance-scored retention** (default; cheap; correct when dependencies are shallow) and **pinned-referential retention** (guarded; costs budget; required when the four conditions above co-hold). Concretely, a span must be *pinned*—excluded from the scorer's eviction set regardless of its relevance score—if it satisfies any of: - It contains a literal that appears in the not-yet-executed portion of the plan (the plan is the oracle for "will be needed"). - It contains a **negative constraint** (prohibition, exclusion, "never", "do not"). Negative constraints are systematically under-scored by similarity metrics because they describe what *not* to do and therefore resemble nothing in the execution trace. This is the single most common inversion. - It is the *sole* source of a referential literal (an ID, path, name, threshold) not present in any tool-accessible store. - It is the most recent user turn establishing a decision (not merely a fact). Everything else is eligible for scoring-based eviction or summarization, with one additional rule: **summarization of an eligible span must be tagged as lossy**, and any plan step that consumes a lossy-tagged span must first attempt re-derivation or halt. A summary that is not tagged lossy is indistinguishable, to a downstream reasoner, from a verbatim span—and that indistinguishability is what let the migration agent reconstruct a wrong literal with full confidence. The boundary is *not* "keep more context." Keeping more context is the naive response and it fails differently (context saturation, attention dilution, and the same scorer eventually evicting under pressure anyway). The boundary is "classify spans by *referential load* before scoring them by relevance, and never let the scorer see the referentially-loaded ones." ## Operational Effect Enforcing the pinned-referential invariant changes three measurable properties of the agent loop: 1. **Referential drift goes to zero for pinned literals**, at the cost of a bounded, predictable budget reservation. The reservation is bounded because the pinned set is bounded by the plan's literal dependencies, not by total context—typically a small fraction of the window. This is the key operational fact: the guardrail is cheap precisely because it is *targeted*, not because it keeps everything. 2. **Eviction becomes auditable.** Every dropped span leaves a lossy tag and a reason code (`relevance_below_cutoff`, `summarized`, `pinned_retained`). When a later step fails, the trace shows whether the failure is downstream of an eviction, which converts a silent drift into a diagnosable event. Without the tag, the post-mortem cannot distinguish "model reasoned wrong" from "model reasoned correctly on incomplete context." 3. **The summarizer's output is no longer trusted as a substitute for the literal.** Downstream steps that need a literal must resolve it from a pinned span or a tool call, never from a summary. This forces the plan to declare its literal dependencies up front—which is the actual invariant: *the plan must enumerate the literals it will need before the scorer is allowed to run.* The residual risk after enforcement is **plan incompleteness**: if the plan does not declare a dependency, the guardrail cannot pin it. This is irreducible without an external oracle, and it is why the lossy-tag audit trail matters—it is the only mechanism that surfaces an undeclared dependency after the fact. The correct posture is not to claim the invariant eliminates drift, but to claim it converts undeclared-dependency drift from silent to logged. ```python from dataclasses import dataclass, field from enum import Enum from typing import Iterable class ContextPolicyViolation(RuntimeError): """Raised when a self-editing context policy would evict a referentially-loaded span.""" pass class SpanKind(Enum): VERBATIM = "verbatim" SUMMARY = "summary" # lossy by construction TOOL_DERIVABLE = "tool_derivable" @dataclass class Span: span_id: str text: str kind: SpanKind relevance: float literals: set[str] = field(default_factory=set) is_negative_constraint: bool = False lossy_tagged: bool = False @dataclass class Plan: # Literals the not-yet-executed plan steps will consume. required_literals: set[str] def is_pinned(span: Span, plan: Plan) -> bool: if span.literals & plan.required_literals: return True if span.is_negative_constraint: return True if span.kind is SpanKind.SUMMARY and not span.lossy_tagged: # An untagged summary is indistinguishable from a verbatim span # downstream; it must not be treated as a safe substitute. return True return False def rewrite_context( spans: Iterable[Span], plan: Plan, cutoff: float, ) -> list[Span]: kept: list[Span] = [] for span in spans: pinned = is_pinned(span, plan) if pinned: kept.append(span) continue if span.relevance >= cutoff: kept.append(span) continue # Eviction path. Refuse to evict a span whose literals are needed # and whose only remaining source would be a lossy summary. if span.kind is SpanKind.SUMMARY and not span.lossy_tagged: raise ContextPolicyViolation( f"refusing to evict span {span.span_id}: " "untagged summary would be the sole referential source" ) if span.literals and not span.literals <= plan.required_literals: # Evicting a literal-bearing span that the plan does not yet # declare is a latent-dependency hazard; log via exception # unless explicitly acknowledged by the caller. raise ContextPolicyViolation( f"span {span.span_id} carries undeclared literals " f"{sorted(span.literals)}; plan must declare or pin them" ) # Safe to drop. return kept def compact(spans: list[Span], plan: Plan, cutoff: float = 0.35) -> list[Span]: try: return rewrite_context(spans, plan, cutoff) except ContextPolicyViolation as exc: # Operational posture: halt the self-edit, keep the prior context # intact, and surface the violation for plan repair. Never proceed # with a partially-evicted context on a referential violation. raise ContextPolicyViolation( f"context self-edit halted; prior context preserved: {exc}" ) from exc ```