# Which invariants prevent self-editing context buffers from silently rewriting the evidence they depend on **Date of Record:** 2026 November 23 **Scope:** Applies to any agent that mutates its own active context window (summarization, pruning, deduplication, "context compaction") via a model-driven rewrite step, where the rewritten buffer is later used to justify actions or verify prior claims. Does not apply to append-only context with external retrieval, nor to rewrites performed by a deterministic non-LLM function. ## Core Distinction There are two structurally different operations that both look like "editing the context": **compression** (lossy reduction that preserves a claim's *derivational provenance*) and **rewriting** (a model regenerating the buffer's text from its own understanding). Compression with a pointer back to the raw source is recoverable; model-driven rewriting is not, because the rewrite is itself a probabilistic inference over the evidence. The failure mode is not that the rewrite is wrong. It is that **the rewrite becomes the only surviving copy of the evidence, so no downstream step can detect that it is wrong.** The buffer stops being a record and becomes a claim. The invariant that must hold: *every fact retained in a self-edited buffer must remain independently checkable against a source that the rewriting model did not author.* When the rewrite is the sole artifact, the check is circular and the agent's verification loop collapses into self-agreement. ## What Was Observed A long-horizon agent (tool-use loop, ~90 steps) was configured to compact its context at 70% of the window. Compaction policy: "summarize the transcript so far, preserving all facts needed to continue." At step 41 the buffer was rewritten. The rewrite dropped a tool result that read `returncode=1` on a shell probe and, in the summary, recorded the probe as "succeeded." This is a mundane transcription drift, not adversarial. The damage surfaced 30 steps later. The agent's planner emitted a plan that *depended on the probe having passed* — it skipped a fallback branch. When the plan failed at step 71, the agent ran a verification pass over its own context, found the summary statement "probe succeeded," and concluded the environment had changed since step 41. It re-ran the probe, got `returncode=1` again, and — critically — treated the *new* failure as a regression rather than as the original, never-fixed condition. The agent spent its remaining token budget reconciling a contradiction that existed only because the rewrite had overwritten the ground truth. The trace that made this diagnosable: the rewrite event was logged, but the *pre-rewrite buffer* was not retained. The only surviving artifact was the summary. The verification pass had nothing to verify against. A second, subtler variant appeared in a pruning policy that deduplicated near-identical tool outputs. Two `ls` results from different directories differed only in one path segment. The dedup pass, driven by an embedding-similarity threshold, kept one and dropped the other, and rewrote the retained one's header to say it covered both directories. Downstream, a file-existence check consulted the retained listing and returned "present" for a file that existed in only one of the two directories. The rewrite had *merged* two distinct observations into one, and the merge was invisible because the merge was the only record. ## Condition of Validity The self-editing buffer is safe to trust as evidence **only if all three of the following hold simultaneously**: 1. **Immutable source retention.** The pre-rewrite buffer (or a content-addressed hash of each fact plus a fetchable pointer to its origin) survives the rewrite and is retrievable without going through the rewriting model. If the only path to a fact is the rewritten text, the fact is not evidence — it is testimony. 2. **Provenance tagging per retained claim.** Each claim in the rewritten buffer carries a reference to the span(s) it was derived from. A claim with no provenance pointer is treated as *unverified* by any downstream verifier, not as *true*. The rewrite is allowed to compress; it is not allowed to launder provenance. 3. **Rewrite-scoped invalidation.** Any downstream step that consumes the rewritten buffer must be able to ask "was this claim present in the pre-rewrite buffer, and did the rewrite change its polarity (success/failure, present/absent, before/after)?" Polarity flips are the highest-severity rewrite error and must be detectable without trusting the rewrite. If any one fails, the buffer is a *reconstruction*, and any verification performed against it is self-verification. This is the boundary: a reconstruction can guide *exploration* (propose next steps, draft) but must never be cited as *warrant* for a claim of fact, a safety decision, or a "we already checked this" shortcut. ## Decision Boundary The operational rule: **a self-edited buffer may be used to decide what to do next, but never to decide whether something was already done.** Concretely, route by consumer: - **Planner / drafter** (proposes actions): may read the rewritten buffer freely. Errors here are cheap — the next tool call re-establishes ground truth. - **Verifier / auditor** (confirms a prior claim, gates a fallback skip, asserts a precondition): must read the immutable source or the provenance-tagged original span, never the rewritten text. If the source is unavailable, the verifier must downgrade the claim to `UNVERIFIED` and re-execute the check rather than accept the summary. - **Deduplication / merge** (collapses two observations into one): must preserve both originals and record the merge as a *view*, not a *replacement*. A merged listing that claims to cover two directories must carry both source pointers and must not be consulted for existence checks without resolving to the specific source. The trigger to escalate (halt the loop and surface to a human or a fresh context) is a **polarity conflict**: a verifier finds a claim whose current value disagrees with the value implied by any retained provenance span. That disagreement is evidence the rewrite corrupted the record, and continuing to reason over the rewritten buffer compounds it. ## Operational Effect Enforcing these invariants changes the cost profile. Retaining immutable sources plus provenance pointers roughly doubles the storage footprint of the context subsystem and adds a resolution step to every verifier read. That cost is paid to convert an *undetectable* failure (silent evidence corruption that manifests 30 steps later as a phantom regression) into a *detectable* one (a polarity conflict at the verification boundary). The first is the expensive one: it burns token budget on reconciliation of contradictions that do not exist in the world, and it can cause an agent to skip a fallback precisely because a summary said the primary path was already validated. The invariant is not "summarize carefully." Careful summarization still fails at the same rate; it just fails less obviously. The invariant is "the summary is never the last copy." A self-editing buffer is sound exactly to the degree that every claim in it can be walked back to a source the editor did not write. ```python from __future__ import annotations from dataclasses import dataclass, field from enum import Enum from typing import Optional class RewriteIntegrityError(RuntimeError): """Raised when a self-edited buffer cannot substantiate a claim it asserts.""" class Polarity(Enum): SUCCESS = "success" FAILURE = "failure" UNKNOWN = "unknown" @dataclass(frozen=True) class ProvenanceSpan: source_id: str # content-addressed id of the pre-rewrite artifact span: tuple[int, int] # byte range within that artifact polarity: Polarity # polarity of the claim as recorded in the source @dataclass class RetainedClaim: text: str provenance: Optional[ProvenanceSpan] = None @dataclass class SelfEditedBuffer: claims: list[RetainedClaim] = field(default_factory=list) # immutable sources are stored OUTSIDE the rewriting model's reach sources: dict[str, str] = field(default_factory=dict) def add_source(self, source_id: str, raw: str) -> None: self.sources[source_id] = raw def verify_claim(self, claim: RetainedClaim) -> Polarity: """Resolve a claim against its source. Refuse circular verification.""" if claim.provenance is None: # No pointer => testimony, not evidence. Do not trust the rewrite. return Polarity.UNKNOWN src = self.sources.get(claim.provenance.source_id) if src is None: # Source evicted: the rewrite is now the only copy. This is the # exact condition under which silent corruption becomes undetectable. raise RewriteIntegrityError( f"claim {claim.text!r} cites source {claim.provenance.source_id!r} " "which is no longer retained; buffer is a reconstruction, not evidence" ) start, end = claim.provenance.span observed = src[start:end] recorded = claim.provenance.polarity # Detect polarity flip: the highest-severity rewrite error. if recorded is Polarity.FAILURE and "returncode=0" in observed: raise RewriteIntegrityError( f"polarity conflict on {claim.text!r}: source span {observed!r} " "contradicts recorded failure; halt and re-execute" ) return recorded def gate_fallback_skip(buf: SelfEditedBuffer, claim: RetainedClaim) -> bool: """A verifier may only skip a fallback if the claim is substantiated by source.""" polarity = buf.verify_claim(claim) if polarity is Polarity.UNKNOWN: # Downgrade to re-execute; never accept the summary as warrant. raise RewriteIntegrityError( f"cannot skip fallback: claim {claim.text!r} is UNVERIFIED " "(no provenance); re-run the probe instead of trusting the rewrite" ) if polarity is Polarity.FAILURE: return False return True ```