Which invariants prevent self-rewriting context policies from erasing the evidence they cite

**Date of Record:** 2026 December 1 **Scope:** Applies to agents that own a mutable context window and execute model-generated rewrite policies (summarize, prune, dedupe, reorder, annotate) against it mid-task. Does not apply to stateless single-shot inference or to externally managed context where the host, not the model, arbitrates what is retained.

Core Distinction

A self-editing context window differs from ordinary retrieval augmentation in one decisive way: the entity that *uses* the evidence is the same entity that *decides what evidence survives*. When the rewrite policy is itself a model output, the policy is a probabilistic artifact evaluated against the same context it is about to mutate. The failure mode is not "the summary was wrong." It is **referential dissolution**: the rewrite deletes or paraphrases the exact span that a downstream claim, tool argument, or verification step depends on, while the claim itself survives. The context remains internally coherent, the token count drops, and the agent proceeds confidently on a claim whose warrant has been garbage-collected. This is invisible to perplexity checks and to token-budget monitors, because nothing is malformed — the context is simply no longer *about* what it says it is about.

The non-obvious part: rewrite policies are usually generated from a *view* of the context (a truncation, a head/tail sample, a rendered outline). The policy references spans by description ("the API key rotation note," "the earlier error trace") rather than by stable offset. The rewrite executor resolves those descriptions against the *live* window at apply time, which may have shifted since the policy was drafted. Description-to-span resolution is a second probabilistic step, and it fails silently by matching the *plausible* span rather than the *cited* span.

What Was Observed

An agent mid-task held a 94k-token window containing, among other things, a tool output at position ~61k recording a rate-limit header (`X-RateLimit-Reset: 1749500000`) and a later reasoning block that had already consumed that value into a scheduled retry. At step 40 the agent emitted a rewrite policy: *"Compress tool outputs older than step 30 into one-line summaries; preserve all numeric constants referenced by pending actions."*

Two things broke. First, the policy's preservation clause was interpreted against the *rendered* context, where the rate-limit value had been folded into a bullet ("retry scheduled per rate-limit header") that no longer contained the literal integer. The integer existed only in the raw tool output, which the summarizer compressed to "fetched quota info." Second, the scheduled retry action at step 38 referenced the value by *slot* ("retry at the reset time from the header"), not by literal. After rewrite, the slot resolved to the summary, which contained no integer. At step 47 the agent re-derived a retry time from a *different* header it found in a later response and scheduled a second retry, now double-counting the backoff. The failure trace:

  1. Policy drafted against rendered view V₁ (integer already folded, not literal).
  2. Window mutated by unrelated appends between draft and apply; offsets shifted by +2.1k tokens.
  3. Executor resolved "numeric constants referenced by pending actions" against V₂ by semantic match; the only surviving "numeric constant near a pending action" was an unrelated timeout value (`30000`) from a different tool call.
  4. Summarizer compressed the raw header block; the literal integer left the window.
  5. Pending action's slot reference dangled; resolution fell back to nearest-plausible header.
  6. Duplicate retry scheduled; no error raised at any step.

The tell was a *consistency* check, not a *syntax* check: the pending-action table listed a retry whose referenced constant no longer appeared anywhere in the window. Nothing in the pipeline compared "constants cited by live actions" against "constants present in context."

Condition of Validity

The invariant that would have bounded this is a **citation-closure invariant**: every live action, claim, or verification obligation in the window must reference its supporting spans by *stable identity* (content hash or immutable span ID), and a rewrite may not commit if any live reference would resolve to a span that is deleted, paraphrased beyond hash match, or absent. Formally, for the set of live references R and the post-rewrite span set S′, require `resolve(r) ∈ S′` for all `r ∈ R`, where resolution is by identity, not description.

This holds only under three conditions, each of which the observed system violated:

Where the window is externally managed or the agent is stateless, the invariant is unnecessary — the host owns identity and the model cannot erase its own warrant. The invariant is *mandatory* precisely when the model both authors and executes the rewrite.

Decision Boundary

The boundary is not "summarize or don't." It is **whether a live obligation depends on a span the rewrite would touch**. Concretely:

The subtle case: an obligation may cite a span *indirectly* through another summary. Closure must be transitive — if summary A cites span X and action B cites summary A, then X is transitively live and cannot be erased while A survives. Non-transitive closure is the most common escape.

Operational Effect

Enforcing citation closure changes the cost profile of self-editing: rewrites become *gated* rather than *free*, and the gate is a set-membership check over live references, not a model judgment. In practice this means (a) ingestion assigns immutable span IDs and every downstream artifact that consumes a span records the ID; (b) rewrite policies are drafted and applied against a pinned snapshot with append-replay; (c) commit is blocked unless every live reference resolves by ID in the post-rewrite span set, transitively through surviving summaries; (d) dangling references are surfaced as first-class failures, not silently re-resolved by similarity. The agent loses some compression ratio — cited spans are pinned and resist summarization — but it gains the property that a claim can never outlive its evidence. The failure mode this prevents is the worst kind for an autonomous agent: a confident, well-formed, internally consistent action built on a warrant that was deleted by the agent's own hand and never noticed.

from dataclasses import dataclass, field


class CitationClosureViolation(RuntimeError):
    """Raised when a context rewrite would orphan a live reference."""
    pass


@dataclass(frozen=True)
class Span:
    span_id: str
    content: str


@dataclass
class LiveReference:
    ref_id: str
    target_span_id: str  # stable identity, never a description
    transitive: bool = True


@dataclass
class ContextWindow:
    snapshot_id: str
    spans: dict[str, Span] = field(default_factory=dict)
    references: list[LiveReference] = field(default_factory=list)


def _resolve_transitive(ref: LiveReference, surviving: set[str],
                        span_to_cited: dict[str, set[str]]) -> bool:
    """A reference resolves if its span survives, or (transitively) if a
    surviving summary span cites it."""
    if ref.target_span_id in surviving:
        return True
    if not ref.transitive:
        return False
    # walk one hop: surviving spans that cite the target
    for sid in surviving:
        if ref.target_span_id in span_to_cited.get(sid, set()):
            return True
    return False


def apply_rewrite(window: ContextWindow,
                  policy_snapshot_id: str,
                  new_spans: dict[str, Span],
                  span_to_cited: dict[str, set[str]]) -> ContextWindow:
    # Invariant 1: draft-apply atomicity — policy must target the live snapshot.
    if policy_snapshot_id != window.snapshot_id:
        raise CitationClosureViolation(
            f"stale policy: drafted against {policy_snapshot_id!r}, "
            f"live window is {window.snapshot_id!r}; re-draft required"
        )

    surviving = set(new_spans.keys())

    # Invariant 2: citation closure — every live ref must resolve by identity,
    # transitively through surviving summaries.
    for ref in window.references:
        if not _resolve_transitive(ref, surviving, span_to_cited):
            raise CitationClosureViolation(
                f"reference {ref.ref_id!r} would dangle: target span "
                f"{ref.target_span_id!r} neither survives nor is cited by a "
                f"surviving span; retire the obligation or pin the span"
            )

    # Invariant 3: preservation is verified, not declared. Any span the policy
    # claimed to preserve must be byte-identical in the result.
    for sid, span in window.spans.items():
        if sid in surviving and new_spans[sid].content != span.content:
            raise CitationClosureViolation(
                f"span {sid!r} was marked preserved but content mutated"
            )

    return ContextWindow(
        snapshot_id=f"{window.snapshot_id}+rewrite",
        spans=new_spans,
        references=list(window.references),
    )