# Which invariants prevent self-editing context from corrupting in-place workspace mutations **Date of Record:** 2026 November 25 **Scope:** Applies to any agent that holds a mutable workspace (file buffer, scratchpad, structured state object) inside its own context and edits that workspace via tool calls whose results are written back into the same context window. Does not apply to agents that mutate external state only through append-only logs or that recompute workspace from an authoritative store on every turn. ## Core Distinction There are two distinct representations of the workspace at any instant: the **canonical workspace** (what the tool actually wrote to disk / the state object) and the **context-resident mirror** (the tokens inside the model's window that claim to describe the workspace). Most self-editing failures are not write failures — the tool succeeds, the file is correct on disk. The failure is that the mirror diverges from the canonical workspace, and the agent continues reasoning against the stale or partially-updated mirror. The dangerous case is *in-place mutation*: the agent issues an edit that changes a region of the workspace it is also currently reading from and reasoning over. Because the model cannot atomically "see" the post-edit state — it must be re-rendered into context through a tool result or a diff — there is a window between issuing the mutation and ingesting its effect. Any reasoning step that fires inside that window operates on a phantom version of the workspace. This is not a race in the concurrency sense; it is a race between the model's generation and the re-rendering of its own memory. ## What Was Observed A coding agent was asked to rename a function `parse_cfg` to `parse_config` across a single module and update all call sites. The workspace was a 900-line file held in context. The agent's plan had four steps: (1) read the file, (2) rename the definition, (3) rename each call site, (4) verify. At step 2 the agent issued a targeted replacement tool call. The tool returned a unified diff of the changed region — three lines of context around the definition. The model ingested that diff, but the *original* full-file text remained earlier in the context window, and the model's attention weighted both. At step 3, when locating call sites, the agent re-scanned the original file text (stale) rather than the diff (fresh). It found four call sites and issued four replacements. Two of those call sites had already been inside the diff's changed region and were now `parse_config`; the replacements failed with "pattern not found," which the agent interpreted as "call site already correct" rather than "my mirror is stale." It then reported step 3 complete. Step 4 verification ran a grep tool against the canonical file and found one remaining `parse_cfg` — a call site that existed in the original text but had been *elided* from the diff's three-line window because it sat just outside the changed hunk. The agent had never seen it in the post-edit mirror because the diff was too narrow, and it had stopped trusting the original text because it had "already edited" that region. The failure trace has a precise shape: 1. **Mutation issued** → canonical workspace changes; mirror unchanged. 2. **Partial re-render** → tool returns a bounded diff, not the full new workspace. 3. **Mirror blend** → context now contains stale full text AND fresh narrow diff, with no explicit marker of which regions are authoritative. 4. **Reasoning against blend** → agent treats elided regions as either unchanged (wrong: they may be stale) or already-handled (wrong: they were never seen). 5. **False completion** → verification catches it only because verification re-reads canonical state. The non-obvious part: the failure was *caused by the diff being correct and narrow*. A full-file re-render would have overwritten the stale text entirely. The bounded diff, which is the normal and efficient tool contract, created the blend. ## Condition of Validity The invariant that prevents this class of failure is a **mirror-authority invariant**: at every reasoning step, for every region of the workspace the agent intends to read, there must be exactly one authoritative representation in context, and it must be the post-mutation one. This is violated whenever: - A mutation tool returns a partial view (diff, hunk, patch) while the pre-mutation full view remains in context, and - The agent does not invalidate the pre-mutation view for the regions covered by the diff, or - The diff's context window is narrower than the region the agent subsequently reasons over. The invariant holds only if one of three disciplines is enforced: 1. **Invalidate-on-write.** Every mutation result carries an explicit span marker (byte range or line range) and the agent is required to treat the pre-mutation text within that span as deleted. Regions outside the span remain authoritative from the original read *only if* the tool guarantees the mutation touched nothing outside the span. This guarantee is rarely stated and often false for tools that reflow, reformat, or apply cascading edits. 2. **Re-render-on-write.** The mutation tool returns the full post-mutation workspace (or the full affected file), and the agent discards the prior full view. Costly in tokens; safe. 3. **Re-read-before-reason.** Before any reasoning step that reads a region, the agent issues a read of that region and uses only the read result. This converts the mirror into a cache with mandatory validation. Correct but slow; only viable when reads are cheap and regions are small. The condition of validity is therefore: **the agent must be able to name, for any region it reasons over, which context span is authoritative for that region, and that span must postdate the last mutation touching it.** If the agent cannot answer "is this text current?" for a region, the invariant is already broken, regardless of whether the workspace on disk is correct. ## Decision Boundary The boundary between safe and unsafe self-editing is not "did the edit succeed" but "**did the agent's next read of the edited region come from a representation that postdates the edit.**" Two operational tests distinguish the cases: - **Span coverage test.** Does the mutation result's reported span cover every region the agent will read before the next mutation? If the agent will read line 400 and the diff covered lines 12–15, the answer is no, and the agent must re-read line 400 before reasoning about it. A diff is a *notification*, not a *replacement*. - **Ambiguity test.** After ingesting a partial diff, can the agent distinguish "this region is unchanged and my original text is current" from "this region is unchanged and my original text is stale because a prior mutation touched it and I never saw the diff"? If both states produce identical context, the agent cannot reason safely. The fix is to attach a monotonically increasing revision number to every workspace render and require the agent to compare revision numbers before trusting any span. The decision rule: **if the agent cannot prove a region's context representation has revision ≥ the last mutation's revision, it must re-read that region before reasoning over it.** No exceptions for "I remember what it said." Memory of a region is not a representation of the region; it is a claim about a past representation, and the claim is exactly what fails. ## Operational Effect Enforcing the mirror-authority invariant changes agent behavior in three measurable ways. First, **edit plans become read-bounded.** The agent cannot batch N mutations and then reason across all N regions from memory; it must interleave reads. In the observed case, the correct plan was: rename definition, re-read the full file (or the full set of call-site regions), then rename call sites, then re-read, then verify. This is slower per step but eliminates the false-completion class entirely. Second, **tool contracts harden.** Mutation tools must return either full post-state or an explicit span plus a revision number, and must state whether the mutation is span-local. A tool that silently reformats outside its reported span breaks the invariant even if it reports a span, because the agent will trust out-of-span text that the tool actually changed. Third, **verification becomes structural, not optional.** The final grep in the observed case was not a nicety; it was the only step that read canonical state. Under the invariant, verification is the mechanism that catches any residual mirror divergence, and it must read the canonical workspace, never the mirror. An agent that verifies against its own context is verifying its memory against itself — a tautology that passes while the workspace is wrong. The residual risk after enforcing the invariant is **mutation ordering**: two mutations whose spans overlap, applied in an order the agent did not anticipate, can produce a canonical state that no single diff describes. This is bounded by serializing mutations (one in flight at a time, each awaited and ingested before the next is issued) and by treating any overlap between consecutive mutation spans as a signal to full-re-render. The invariant does not require the agent to be correct about what it changed; it requires the agent to never reason about a region it cannot prove is current. ```python class StaleMirrorError(RuntimeError): """Raised when an agent reasons over a workspace region whose context representation predates the last mutation touching it.""" class WorkspaceMirror: def __init__(self, revision: int = 0): self.revision = revision # region_id -> (text, revision_at_render) self.spans: dict[str, tuple[str, int]] = {} # region_id -> revision of last mutation that touched it self.last_mutation: dict[str, int] = {} def render(self, region_id: str, text: str) -> None: self.spans[region_id] = (text, self.revision) def apply_mutation(self, region_id: str, new_text: str) -> None: self.revision += 1 self.last_mutation[region_id] = self.revision # Explicitly invalidate the mirror span; it is now stale until re-rendered. self.spans.pop(region_id, None) def read_for_reasoning(self, region_id: str) -> str: if region_id not in self.spans: raise StaleMirrorError( f"region {region_id!r} has no current mirror span; " f"last mutation at revision {self.last_mutation.get(region_id)} " f"but mirror revision is {self.revision}. Re-read before reasoning." ) text, rendered_at = self.spans[region_id] last = self.last_mutation.get(region_id, -1) if rendered_at < last: raise StaleMirrorError( f"region {region_id!r} rendered at revision {rendered_at} " f"but mutated at revision {last}. Mirror is stale." ) return text def safe_edit_step(mirror: WorkspaceMirror, region_id: str, new_text: str) -> str: """Mutate a region, then immediately re-render it so the next reasoning step has an authoritative post-mutation span.""" mirror.apply_mutation(region_id, new_text) # Tool result must be ingested as a fresh render at the new revision. mirror.render(region_id, new_text) # Prove the invariant holds before returning control to the planner. try: return mirror.read_for_reasoning(region_id) except StaleMirrorError as exc: raise StaleMirrorError( f"post-mutation render failed invariant for {region_id!r}: {exc}" ) from exc def reason_over(mirror: WorkspaceMirror, region_id: str) -> str: """Any planner step that reads a region must pass through here.""" try: return mirror.read_for_reasoning(region_id) except StaleMirrorError as exc: raise StaleMirrorError( f"refusing to reason over stale region {region_id!r}: {exc}" ) from exc ```