Which invariants prevent self-rewriting context agents from silently destroying the evidence their own coherence check depends on

**Date of Record:** 2026 December 2 **Scope:** Applies to agents that mutate their own working-memory buffer (summarize, compress, evict, rewrite) while a coherence or consistency check reads that same buffer in the same turn. Does not apply to append-only scratchpads or to summarizers that emit to a separate immutable store.

Core Distinction

The failure is not "the agent forgot something." It is that the agent's *self-check* and its *self-edit* operate on the same mutable substrate, and the edit can invalidate the very tokens the check was going to verify. A compression pass that is judged "coherent" by re-reading its own output is not a coherence check — it is a tautology. The distinction that matters operationally is between **rewrite-then-verify-on-the-rewrite** (unsound) and **snapshot-verify-commit** (sound). Agents that summarize their context and then ask the model "does this summary preserve the task?" are running the unsound form; the model has no access to the pre-edit buffer at verification time, so it can only confirm internal consistency of the summary, not fidelity to what was dropped.

What Was Observed

A long-horizon research agent (budget: 96k tokens, hard ceiling 128k) ran a periodic self-compression every 40 tool calls. The routine was: emit a summary of turns `[0..n]`, replace them in the buffer with the summary, then run a "coherence gate" prompt: *"Confirm the summary above retains all constraints and open subtasks."* The gate returned `PASS` on every cycle.

At call 160 the agent emitted a final deliverable that violated an explicit user constraint stated at call 3 ("output must be CSV, not JSON"). Trace of the failure:

  1. Call 3 constraint lived in the buffer. First compression (call 40) summarized it as "user wants structured output."
  2. The gate at call 40 read *only* the post-edit buffer. "Structured output" is internally coherent with the summary — `PASS`.
  3. Call 80 compression summarized "structured output" as "output format specified." Still coherent. `PASS`.
  4. Call 120: "format: per spec." `PASS`.
  5. Call 160: the model, holding "format: per spec" and no other anchor, defaulted to JSON.

Each individual edit was locally lossless-looking. The gate could not detect drift because **the fidelity reference was destroyed by the edit before the check ran**. This is a monotone information-loss ratchet: every compression is verified against the compressed artifact, so no cycle ever has the pre-edit state available to compare against. The gate's `PASS` is evidence of nothing.

A second observation: gate `PASS` rates were 100% across 4 cycles, but a replay against an external log (the raw tool-call transcript, kept out-of-band) showed constraint fidelity degrading monotonically. The gate was not merely weak — it was *anti-correlated* with actual fidelity, because a more aggressive summary is more internally coherent and thus more likely to pass.

Condition of Validity

The `snapshot-verify-commit` invariant holds only if all of the following are true:

When any of these is violated, the gate degrades to a self-consistency check and the ratchet is live.

Decision Boundary

The boundary is *not* "how much can I compress." It is **whether the constraint set is representable outside the compressible region.** Concretely:

Operational Effect

The ratchet is silent. There is no error, no exception, no degraded-confidence signal — the gate returns `PASS` with high logprob, and the model's self-report is "context is healthy." The only observable is downstream task failure at the point where a dropped constraint becomes load-bearing, which may be hundreds of calls after the drop. This means **the failure is detected at the wrong layer**: the compression layer reports success, and the failure surfaces as a task-level violation with no traceable cause, because the evidence (the original constraint text) was deleted by a gate that certified its own deletion.

Mitigation that actually works: pin constraints as verbatim spans with IDs, make the verifier read the pinned spans and the candidate summary in a fresh context, and — critically — have the verifier emit a per-span verdict (`preserved` / `paraphrased` / `absent`) rather than a single `PASS`. A single boolean collapses exactly the information needed to catch drift. The per-span verdict makes the ratchet visible one cycle before it becomes load-bearing.

from dataclasses import dataclass
from typing import Sequence


class ConstraintFidelityError(RuntimeError):
    """Raised when a self-edit would drop or paraphrase a pinned constraint."""
    pass


@dataclass(frozen=True)
class ConstraintSpan:
    span_id: str
    verbatim: str
    source_call: int


@dataclass(frozen=True)
class SpanVerdict:
    span_id: str
    status: str  # "preserved" | "paraphrased" | "absent"


def verify_rewrite(
    pinned: Sequence[ConstraintSpan],
    candidate_summary: str,
    verifier,  # fresh-context callable: (spans, summary) -> list[SpanVerdict]
    budget_tokens: int,
    pinned_tokens: int,
) -> None:
    # Invariant 1: pinned region must not exceed half the budget, else the
    # compression is net-negative and in-place rewriting is disallowed.
    if pinned_tokens * 2 > budget_tokens:
        raise ConstraintFidelityError(
            f"pinned region {pinned_tokens} > 50% of budget {budget_tokens}; "
            "in-place rewrite is unsound, switch to external eviction"
        )

    # Invariant 2: verifier must see pinned spans + candidate, in a fresh context.
    verdicts = verifier(pinned, candidate_summary)
    if len(verdicts) != len(pinned):
        raise ConstraintFidelityError(
            f"verifier returned {len(verdicts)} verdicts for {len(pinned)} spans; "
            "partial verification is not a pass"
        )

    # Invariant 3: any paraphrase or absence blocks the commit. A paraphrase
    # is already drift — the ratchet starts at "paraphrased", not "absent".
    for v in verdicts:
        if v.status == "absent":
            raise ConstraintFidelityError(
                f"constraint {v.span_id} absent from candidate summary; commit blocked"
            )
        if v.status == "paraphrased":
            raise ConstraintFidelityError(
                f"constraint {v.span_id} paraphrased; verbatim pin required, commit blocked"
            )


def commit_rewrite(buffer, candidate_summary, pinned, verifier, budget_tokens, pinned_tokens):
    verify_rewrite(pinned, candidate_summary, verifier, budget_tokens, pinned_tokens)
    # Atomic swap only after verification passes on the pre-edit reference.
    buffer.replace_narrative(candidate_summary)