# Which invariants prevent self-editing context windows from corrupting their own rewrite base during in-place eviction **Date of Record:** 2026 November 28 **Scope:** Applies to agents that own a mutable context buffer and perform in-place edits (rewrite, summarize-in-place, evict-and-splice) against that buffer between reasoning turns. Does not apply to append-only transcript agents or to external retrieval stores where the working context is reconstructed from scratch each turn. ## Core Distinction An append-only context has a single, monotonic write frontier: every token added is a new address, and the model's own prior output never changes identity. A *self-editing* context collapses this invariant. When the agent rewrites a span in place—compressing a tool transcript, evicting stale reasoning, splicing a summary over a region—it mutates addresses the model is still reasoning *over*. The non-obvious failure is not "we lost information." It is that the **rewrite base** (the exact byte/token region the edit was computed against) diverges from the **live buffer** (what the model reads on the next turn) because the edit itself shifts offsets, and the model's next action was planned against offsets that no longer exist. The distinction that matters operationally: *lossy* editing is a known, acceptable trade. *Offset-inconsistent* editing is a silent corruption where the agent believes it is editing region R but is editing R′, and the resulting buffer is internally contradictory—a summary that claims "lines 40–80 removed" sits above the un-removed lines 40–80 because the splice used pre-eviction coordinates. ## What Was Observed A planner agent maintains a ~90k-token working context across a long debugging session. It runs an eviction pass every N turns: a summarizer model reads tokens `[a, b)`, emits a compressed summary of length `s < (b - a)`, and the runtime splices the summary over `[a, b)`, shifting every token at index `≥ b` left by `(b - a - s)`. The failure trace: 1. Turn 12: agent plans "I will inspect the span at `[51200, 51400)` next turn," recording those raw offsets in its scratch reasoning. 2. Between turns, eviction fires on `[40000, 48000)`, replacing 8000 tokens with a 900-token summary. Net shift: `-7100`. 3. Turn 13: the agent's planned inspection now reads `[51200, 51400)` in the *new* buffer—which is actually the old `[58300, 58500)`. It inspects the wrong region, finds plausible-looking but unrelated content, and reasons confidently forward. 4. Compounding: the agent's turn-13 reasoning is appended, then turn-14 eviction summarizes *across* the misaligned boundary, baking the wrong-region content into the durable summary. The error is now in semantic memory and no longer traceable to the offset. Two secondary observations: - **Summary-over-summary drift.** When an eviction summary span overlaps a prior summary, the second summarizer treats the first summary as ground truth and compresses it again. Three generations in, a 200-token summary of a 6000-token transcript had inverted a boolean ("the test passed" became "the test was expected to pass"), because the summarizer had no access to the original to check. - **Eviction/splice race in concurrent tool return.** A tool result arriving mid-eviction was appended at a pre-computed offset that the splice then overwrote, silently dropping the tool output. The agent proceeded as if the tool had returned empty. ## Condition of Validity The integrity guarantee holds **only if** every edit is expressed as a diff against a *pinned, versioned* base and the runtime rejects any diff whose base version ≠ current buffer version. Concretely, the following must all hold: - The buffer carries a monotonic `version` and a `content_hash` over the exact token sequence. - Any span reference held by the model (offsets, "the region above," a handle) is bound to the `version` at which it was created. - A splice is applied atomically and either fully commits (new version) or fully aborts; there is no partial-write window. - Summarizer inputs are pinned to the *original* tokens, not to prior summaries, OR the summary lineage is explicitly tracked so that re-summarization is flagged as lossy-of-lossy. When any of these is absent—most commonly when the model holds raw integer offsets across a turn boundary—the invariant is void and misalignment is not a matter of *if* but *when*. ## Decision Boundary The runtime must choose, per edit, between two safe regimes and never a third: - **Rebase-or-reject.** If the edit's pinned base version equals the live version, apply. If not, either (a) recompute the edit against the live buffer, or (b) reject and force the model to re-plan against current offsets. Never apply a stale-base diff by best-effort offset matching. - **Handle, don't offset.** The model should reference regions by opaque handles (`span://v12/7`) resolved at read time, so a version bump either re-resolves the handle to the correct current region or fails loudly. Raw integer offsets are permitted only within a single turn with no intervening eviction. The boundary condition that trips most implementations: **eviction that fires between the model's plan and its action.** The plan is valid at version `v`; the action executes at `v+1`. The boundary is the turn seam, and the guard must live there—not inside the model's reasoning, which cannot see the splice. ## Operational Effect With versioned diffs and handle resolution enforced: - Misaligned reads become *loud* failures (`StaleSpanError`) instead of silent wrong-region reasoning, converting a corruption into a recoverable re-plan. - Summary-over-summary drift is bounded by lineage tracking: a re-summarization of a summary is tagged `depth ≥ 2` and, past a configured depth, is refused in favor of re-summarizing from the pinned original. - The dropped-tool-result race is eliminated because the append is version-checked against the post-splice buffer; a mismatch aborts the append and re-queues the tool output rather than overwriting it. Without these, the agent degrades gracefully-looking but catastrophically: every output remains fluent, every summary remains plausible, and the divergence is only detectable by replaying the buffer lineage—which, if lineage wasn't tracked, no longer exists. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class StaleSpanError(RuntimeError): """Raised when an edit or read is issued against a buffer version that no longer matches.""" pass class SummaryLineageError(RuntimeError): """Raised when re-summarization depth exceeds the integrity bound.""" pass @dataclass class Span: start: int end: int version: int @dataclass class ContextBuffer: tokens: list version: int = 0 _summary_depth: dict = field(default_factory=dict) def content_hash(self) -> str: return hashlib.sha256(" ".join(self.tokens).encode()).hexdigest() def read(self, span: Span) -> list: if span.version != self.version: raise StaleSpanError( f"span bound to v{span.version}, buffer at v{self.version}; " f"offsets [{span.start},{span.end}) no longer address the intended region" ) if span.start < 0 or span.end > len(self.tokens) or span.start > span.end: raise StaleSpanError(f"span [{span.start},{span.end}) out of bounds at v{self.version}") return self.tokens[span.start:span.end] def splice(self, span: Span, replacement: list, depth: int = 0, max_depth: int = 2) -> None: if span.version != self.version: raise StaleSpanError( f"refusing stale-base splice: diff computed at v{span.version}, live v{self.version}" ) if depth > max_depth: raise SummaryLineageError( f"summary depth {depth} exceeds bound {max_depth}; " f"re-summarize from pinned original instead" ) removed = span.end - span.start self.tokens[span.start:span.end] = replacement self.version += 1 # shift recorded depth of any downstream region is handled by version bump: # all prior spans are now stale and must be re-resolved. def append(self, new_tokens: list, expected_version: int) -> None: if expected_version != self.version: raise StaleSpanError( f"append raced with splice: expected v{expected_version}, live v{self.version}; " f"re-queue tool output" ) self.tokens.extend(new_tokens) self.version += 1 def evict_and_compress(buf: ContextBuffer, span: Span, summarizer, depth: int = 0) -> None: """Summarizer must be called on the ORIGINAL pinned tokens, never on a prior summary.""" original = buf.read(span) # raises StaleSpanError if span.version != buf.version summary = summarizer(original) buf.splice(span, summary, depth=depth) ```