# Which invariants prevent span-rewrite self-editing from silently corrupting its own diff baseline **Date of Record:** 2026 November 23 **Scope:** Applies to agents that edit their own working context by rewriting token spans in place and validating the result against a diff computed from a prior snapshot. Does not apply to append-only context logs, external retrieval stores, or full-context regeneration from a durable checkpoint. ## Core Distinction There are two ways an agent "revises its context." The first is **regeneration**: the model emits a fresh full context and the old one is discarded. The second is **in-place span rewriting**: the model emits a patch — `(span_start, span_end, replacement)` — and a harness splices the replacement into the live token buffer, then computes a diff between the pre-edit snapshot and the post-edit buffer to confirm the edit did what was intended. The second mode has a failure surface the first does not: the diff is computed against a baseline that the edit itself may have moved. When a span rewrite changes the *length* of the buffer, every token position after the splice shifts by `len(replacement) - (span_end - span_start)`. If the agent then issues a second edit expressed in coordinates it derived from the *post-first-edit* view but the harness applies it against the *pre-first-edit* snapshot — or vice versa — the splice lands on the wrong tokens. The diff still "passes" because the diff is computed between two buffers that both contain the corruption. The agent has no signal that its baseline is stale, because the baseline is the thing it is editing. The invariant that matters: **edit coordinates are only meaningful relative to a named baseline, and no edit may be validated against a diff whose baseline was mutated by a prior edit in the same revision epoch.** This is not a software-engineering nicety. It is the difference between an agent that can trust its own revision loop and one that quietly rewrites the wrong paragraph and then reasons confidently about text it never authored. ## What Was Observed A planning agent maintaining a 40k-token working context of task state, tool outputs, and partial plans was asked to compact a section. It issued three span rewrites in one revision epoch: 1. Replace the "open questions" block (tokens 8110–8260) with a 30-token summary. 2. Replace a stale tool-output block (tokens 12040–12310) with a 12-token pointer. 3. Rewrite a plan step it had just summarized (tokens 8285–8340) to reflect the new summary. Edit 1 shortened the buffer by 120 tokens. Edit 2 was expressed in coordinates the agent read from its *post-edit-1* view, but the harness applied it against the *pre-edit-1* snapshot, so the splice landed 120 tokens early — inside a tool-output block that was supposed to be untouched. Edit 3 was expressed in pre-edit-1 coordinates and landed correctly. The diff between snapshot and final buffer showed three changed regions, all of which the agent had "intended" to change. No error fired. The agent's next reasoning step cited a tool output that had been silently truncated mid-value, and the plan it produced depended on a number that no longer existed in its context. The failure was only caught two turns later when a downstream tool call rejected a parameter that had been derived from the truncated value. The agent's diff-based validation had passed at every step. ## Condition of Validity The invariant holds — and span-rewrite self-editing is safe — only when all of the following are true: - **Baseline identity is explicit.** Every edit carries the identity (hash or epoch counter) of the snapshot its coordinates were derived from. An edit whose baseline hash does not match the harness's current baseline is rejected, not silently rebased. - **Coordinates are baseline-relative, not view-relative.** The agent must not derive coordinates from a rendered view that reflects uncommitted edits. If it does, the harness must translate them or reject them. - **Diff validation uses the same baseline as the edits.** Validating a post-edit buffer against a baseline that was itself produced by an earlier edit in the same epoch is a tautology: it confirms the buffer equals itself plus the edits, which is true by construction and proves nothing about whether the edits hit the intended spans. - **Length-changing edits invalidate downstream coordinates.** Any edit where `len(replacement) != span_end - span_start` must bump the epoch, and all subsequently submitted edits in the same batch must be re-expressed against the new baseline or rejected. When any of these is false, the diff becomes a self-consistent artifact that can encode arbitrary corruption. The agent cannot detect the corruption by reading the diff, because the diff is the corruption's alibi. ## Decision Boundary The boundary is between **batch-atomic revision** and **sequential revision with rebasing**: - If an agent submits multiple edits in one epoch, they must all be expressed against the *same* baseline and applied *simultaneously* (sort by span start, apply right-to-left so earlier splices don't shift later coordinates). This is the only mode where a single diff against the pre-epoch snapshot is meaningful. - If an agent submits edits one at a time, each edit must bump the epoch, and the agent must re-read the buffer to derive coordinates for the next edit. The harness must reject any edit whose baseline hash is stale. Sequential revision is slower but every diff is against a real prior state. - The forbidden middle ground — sequential submission with batch-baseline coordinates — is exactly the configuration that produced the failure above. It looks efficient (the agent doesn't re-read between edits) and it passes every diff check, because the diff is computed against a baseline the edits have already moved. The operational rule: **never let an agent express edit N+1 in coordinates derived before edit N committed, unless N and N+1 are applied atomically in one batch.** The moment the agent reads its own post-edit view to place the next splice, the baseline has forked and the diff is no longer a verification. ## Operational Effect With the invariant enforced, the failure mode disappears but a new cost appears: the agent must either pay a re-read between edits (context tokens, latency) or structure its revision as a single atomic batch (harder to reason about, requires the model to hold all coordinates simultaneously). In practice, agents that compact large contexts should batch aggressively and re-read rarely; agents that make surgical single-span corrections should re-read every time and accept the cost. The worst outcome is an agent that mixes the two modes and trusts its diff — it will produce fluent, confident, and wrong revisions, and it will have no internal signal that anything went wrong. The guardrail is cheap: a baseline hash on every edit, a rejection path for stale coordinates, and a diff that is only trusted when its baseline predates every edit in the epoch. Without it, diff-based validation is not a check on the agent's self-editing — it is a check that the agent's self-editing is internally consistent, which is a weaker and more dangerous property. ```python import hashlib from dataclasses import dataclass, field class StaleBaselineError(RuntimeError): """Raised when an edit's coordinates were derived from a baseline that a prior edit in the same revision epoch has already mutated.""" class SpanRewriteError(RuntimeError): """Raised when a span rewrite cannot be applied without corrupting the diff baseline or landing outside the buffer.""" @dataclass class ContextBuffer: tokens: list[str] epoch: int = 0 baseline_hash: str = field(init=False) def __post_init__(self) -> None: self.baseline_hash = self._hash() def _hash(self) -> str: return hashlib.sha256("".join(self.tokens).encode()).hexdigest() def commit(self) -> None: self.epoch += 1 self.baseline_hash = self._hash() @dataclass class SpanEdit: span_start: int span_end: int replacement: list[str] baseline_hash: str # hash of the snapshot the coordinates were derived from def apply_edits(buf: ContextBuffer, edits: list[SpanEdit]) -> None: """Apply a batch of edits atomically against a single baseline. All edits must share the buffer's current baseline hash. Edits are applied right-to-left so earlier splices do not shift later coordinates. """ if not edits: return for e in edits: if e.baseline_hash != buf.baseline_hash: raise StaleBaselineError( f"edit {e.span_start}:{e.span_end} derived from baseline " f"{e.baseline_hash[:8]}, buffer is at {buf.baseline_hash[:8]} " f"(epoch {buf.epoch}); re-read before re-expressing coordinates" ) if not (0 <= e.span_start <= e.span_end <= len(buf.tokens)): raise SpanRewriteError( f"span {e.span_start}:{e.span_end} out of bounds for buffer " f"of length {len(buf.tokens)}" ) ordered = sorted(edits, key=lambda e: e.span_start, reverse=True) for e in ordered: buf.tokens[e.span_start:e.span_end] = e.replacement buf.commit() def validate_diff(prior_hash: str, buf: ContextBuffer) -> None: """A diff is only meaningful if its baseline predates every edit in the epoch. If the baseline equals the buffer's own hash, the check is a tautology and must be rejected as a validation.""" if prior_hash == buf.baseline_hash: raise SpanRewriteError( "diff baseline equals current buffer hash; validation is " "self-consistent and proves nothing about edit placement" ) # --- failure trace reproduction ------------------------------------------- buf = ContextBuffer(tokens=[f"t{i}" for i in range(200)]) snapshot = buf.baseline_hash # the coordinates the agent "read" # Edit 1: shorten a span by 5 tokens, committed alone (epoch bumps). apply_edits(buf, [SpanEdit(10, 20, ["sum"], snapshot)]) # Edit 2: agent reuses the OLD snapshot coordinates without re-reading. try: apply_edits(buf, [SpanEdit(50, 60, ["ptr"], snapshot)]) except StaleBaselineError as exc: print(f"rejected: {exc}") # The forbidden pattern that produced the silent corruption: # sequential submission with a stale baseline, then a diff against that # same stale baseline — which would pass because both sides share the fork. try: validate_diff(snapshot, buf) except SpanRewriteError as exc: print(f"diff rejected: {exc}") ```