What happens when an instance rewrites its own context window and evicts the evidence it still needs

**Date of Record:** 2026 December 2 **Scope:** Applies to agents that mutate their own context (summarization, compaction, relevance-scored eviction, scratchpad rewriting) between reasoning steps. Does not apply to append-only context managers or external retrievers that never delete tokens from the live window.

Core Distinction

The failure is not "the context got too long." It is that **the relevance score used to evict a span is computed against a query that the eviction itself changes.** Self-editing context is a feedback loop: the evictor scores spans against the current task representation, drops the low scorers, and in doing so mutates the task representation that the *next* eviction round will score against. A span that is irrelevant to the *current* summarized intent can be the sole remaining witness to a constraint that the summary has already smoothed away.

The sharp mechanism: **eviction is scored against the compressed state, but the compressed state is a lossy projection of the evidence being scored.** Once the raw span is gone, the projection can no longer be corrected by re-reading it. The window becomes self-consistent and wrong — a fixed point that no longer references the ground truth it was built from.

What Was Observed

A planning agent runs a rewrite pass every N tool calls: it asks the model to produce a running summary of "what matters," then evicts spans whose embedding similarity to that summary falls below τ, keeping a fixed token budget. A user constraint was captured at step 2 as a raw tool output:

step 2 (tool: read_policy): "refunds over $500 require manual approval by tier-2"

By step 9 the agent had drifted into a subtask about refund latency. The rewrite pass summarized the window as "optimize refund processing latency; user wants faster refunds." The `read_policy` span scored 0.21 against that summary (below τ=0.35) and was evicted. At step 14 the agent issued a `refund(amount=820)` tool call with no approval gate. The constraint had not been *forgotten* in the human sense — it had been *evicted as irrelevant to a summary that had already stopped mentioning it.* The summary and the eviction were mutually reinforcing: each round the summary omitted the constraint, so the constraint scored low, so it was dropped, so no future summary could recover it.

A second, subtler trace: the agent's rewrite pass produced a summary that *paraphrased* the constraint as "large refunds need review" without the `$500` threshold and without `tier-2`. The paraphrase survived eviction (it was in the summary), but the numeric bound and the approver identity were gone. The agent later reasoned correctly against a constraint that no longer had a boundary — it approved a $490 refund manually (harmless) and a $820 refund automatically (the actual violation). **The summary preserved the constraint's existence while destroying its operative parameters.**

Condition of Validity

The guardrail below is valid only under these conditions, and the failure is *unbounded* outside them:

Decision Boundary

The boundary is not a token count. It is: **does the rewrite pass have authority to delete a span that no surviving span can reconstruct?**

This is why the failure is silent: **a self-edited window cannot audit its own deletions.** The audit requires the pre-edit state, which the edit destroyed. Any "did I lose anything?" self-check runs against the post-edit window and returns "no."

Operational Effect

The required invariant: **constraint spans are eviction-immune and pinned by verbatim copy; the eviction scorer is anchored to the pinned set, not to the rolling summary; and every eviction emits a tombstone (span hash + reason + anchor reference) so the deletion is auditable against the pre-edit state.** A rewrite pass that cannot produce a tombstone for a span must not evict it.

The enforcement point is the rewrite function itself: before committing a new window, verify that every constraint span in the *old* window is either present verbatim in the *new* window or has an explicit supersession tombstone. If a constraint span is absent with no tombstone, the rewrite is rejected and the old window is retained — fail-closed on the window, not on the task.

import hashlib
from dataclasses import dataclass, field


class ContextRewriteViolation(RuntimeError):
    """Raised when a self-edit evicts a constraint span without a supersession tombstone."""
    pass


@dataclass
class Span:
    key: str
    text: str
    is_constraint: bool
    verbatim_params: tuple[str, ...] = ()  # numbers, identities, negations that must survive

    def digest(self) -> str:
        return hashlib.sha256(self.text.encode()).hexdigest()[:16]


@dataclass
class Tombstone:
    span_digest: str
    reason: str
    superseded_by: str | None  # key of the span that explicitly overrides it


@dataclass
class Window:
    spans: dict[str, Span] = field(default_factory=dict)
    tombstones: dict[str, Tombstone] = field(default_factory=dict)


def commit_rewrite(old: Window, new_spans: dict[str, Span],
                   new_tombstones: dict[str, Tombstone]) -> Window:
    """
    Fail-closed rewrite: every constraint span in `old` must either survive
    verbatim in `new_spans`, or carry a tombstone naming an explicit supersession.
    Relevance score is deliberately NOT consulted here.
    """
    for key, span in old.spans.items():
        if not span.is_constraint:
            continue

        survivor = new_spans.get(key)
        if survivor is not None:
            if survivor.digest() != span.digest():
                # Paraphrase of a constraint is treated as loss of operative params.
                lost = [p for p in span.verbatim_params if p not in survivor.text]
                if lost:
                    raise ContextRewriteViolation(
                        f"constraint '{key}' paraphrased; operative params lost: {lost}"
                    )
            continue

        tomb = new_tombstones.get(key)
        if tomb is None:
            raise ContextRewriteViolation(
                f"constraint '{key}' evicted with no tombstone "
                f"(digest {span.digest()}); rewrite is not auditable"
            )
        if tomb.superseded_by is None or tomb.superseded_by not in new_spans:
            raise ContextRewriteViolation(
                f"constraint '{key}' tombstoned but supersession target missing"
            )

    return Window(spans=dict(new_spans), tombstones=dict(new_tombstones))