# When must an instance refuse a model-authored context diff because the edit journal cannot reconstruct the pre-edit context byte-for-byte **Date of Record:** 2026 November 26 **Scope:** Applies to any agent architecture where the running LLM proposes edits to its own working context (system prompt, scratchpad, distilled memory block, or tool-result cache) as structured diffs that are applied by a host-side editor and recorded in an append-only edit journal for rollback. Does not apply to append-only context growth without diffs, or to human-authored edits reviewed out-of-band. ## Core Distinction There are two different things an edit journal can mean, and conflating them is the failure mode. A **semantic journal** records *intent*: "at step 14 the model asked to replace the paragraph beginning 'Constraints:' with X." A **byte journal** records *effect*: the exact pre-image bytes and post-image bytes of every region that changed, sufficient to invert the edit mechanically without re-invoking the model. Most self-editing implementations write semantic journals—they log the model's diff text plus a timestamp—and then claim rollback safety. This is false the moment the model's diff is ambiguous against the actual buffer. The model emits a diff against *its mental model of the context*, which is a lossy, attention-weighted reconstruction of the actual token sequence. When the host applies that diff, it must locate the anchor text the model referenced. If the anchor is not unique, or was itself altered by an earlier uncommitted edit in the same batch, the applied edit diverges from the intended edit. The journal then records an intent that no longer corresponds to any reachable state, and rollback reconstructs the wrong pre-image. The invariant that must hold: **for every journal entry, applying the inverse of the recorded byte pre-image to the current buffer must yield exactly the buffer state that existed immediately before the forward edit, and this must be verifiable by hash, not by re-parsing the diff.** ## What Was Observed A three-agent research swarm shared a 96k-token context containing a distilled findings block, a scratchpad, and a tool-result cache. Each agent held write authority over its own scratchpad section but could propose edits to the shared findings block through a diff protocol. The host editor applied diffs sequentially and appended each to a journal keyed by `(step, agent_id, section, diff_text)`. At step 22, agent B emitted a diff whose hunk header was: ``` @@ findings_block @@ - Confidence: medium + Confidence: high (replicated n=3) ``` The string `Confidence: medium` appeared **four times** in the findings block—once per claim, because the distillation step had normalized claim metadata into a uniform template. The host's anchor resolver, using a first-match rule, edited the first occurrence. Agent B had intended the fourth (the claim it had just replicated). The forward edit succeeded; the journal recorded the diff text and the resolved byte offsets `[48211, 48230)`. At step 27, a verification agent flagged the fourth claim as unreplicated and the swarm triggered a rollback to step 21 to re-derive findings. The rollback engine replayed journal inverses in reverse order. For the step-22 entry it inverted the recorded byte range `[48211, 48230)`—correctly restoring the *first* claim's confidence to `medium`. But the *fourth* claim still read `high (replicated n=3)`, because that is what agent B's forward edit had semantically intended and what a later step-24 edit had additionally reinforced. The reconstructed step-21 state differed from the true step-21 state in exactly one field, and the difference was invisible to the semantic journal: every entry replayed cleanly, every diff text matched, and the hash of the reconstructed buffer did not match the hash recorded at step 21. The swarm resumed from the corrupted state. The verification agent, now seeing a `high` confidence claim with no supporting replication in the restored tool cache, entered a contradiction loop: it re-flagged the claim, the findings agent re-raised confidence citing the (stale, pre-rollback) replication record, and the loop consumed 40k tokens before the token budget forced termination. The root cause was not the ambiguity itself—ambiguous anchors are common and recoverable. It was that the journal could not *detect* that rollback had produced a state that never existed. ## Condition of Validity A model-authored diff is only rollback-safe under a byte journal when all three of the following hold at apply time: 1. **Anchor uniqueness is verified against the live buffer, not the model's claimed context.** Before applying any hunk, the host must confirm the anchor string (or its normalized form) occurs exactly once in the target region. If it occurs more than once, the diff is *underdetermined* and must be rejected or disambiguated with explicit byte offsets supplied by the host, never by re-prompting the model (re-prompting introduces a second non-deterministic sample that may anchor differently). 2. **The journal stores pre-image and post-image bytes plus a rolling hash of the full buffer before and after each edit.** Storing the diff text is insufficient because diff text is an intent, not a state. The rolling hash chain is what makes rollback *verifiable*: after inverting entry N, the engine recomputes the hash and compares to the hash recorded before entry N was applied. A mismatch is a hard stop. 3. **No two edits in a batch may target overlapping or anchor-adjacent regions without a forced checkpoint.** If edit N+1's anchor region intersects edit N's post-image, then inverting N+1 followed by N is only valid if N+1's pre-image was captured *after* N was applied. Batch-applied diffs that were all authored against the same pre-batch context violate this: the model authored them against a single mental snapshot, but they apply to a mutating buffer. The failure above violated (1) directly and (2) and (3) structurally: the journal had no hash chain, so the divergence was undetectable, and the batch contained a later edit (step 24) that touched an anchor-adjacent region without a checkpoint. ## Decision Boundary The boundary is not "reject ambiguous diffs." Ambiguity is cheap to detect and cheap to reject. The boundary is: **when the journal cannot prove, by hash, that an inverse replay reconstructs a state that actually existed, the instance must treat the entire post-checkpoint segment as non-rollbackable and must not resume from any reconstructed state.** Concretely, the instance must refuse to roll back—and must instead escalate to full context re-derivation from the last checkpoint with a verified hash chain—when any of these hold: - A hunk anchor resolves to more than one location in the live buffer. - The rolling hash after inverting entry N does not equal the hash recorded before entry N. - A journal entry's pre-image bytes are absent from the buffer at replay time (the region was overwritten by a later edit that did not record an intersecting pre-image). - The batch contains edits authored against the same pre-batch snapshot that touch overlapping regions. The last condition is the non-obvious one. It is tempting to allow it because each individual diff is well-formed. But a batch of diffs all authored against snapshot S, applied sequentially to a buffer that moves away from S, is a set of edits to *different* buffers than the ones the model reasoned about. The journal faithfully records what was applied; it cannot record what was *intended against S*. Rollback to S is therefore not reconstructable from the journal alone, and the instance must re-derive S by replaying from the last checkpoint whose hash chain is intact. ## Operational Effect The practical consequence is a separation of two operations that self-editing agents routinely fuse: **apply** and **commit**. Apply mutates the buffer and appends a candidate journal entry carrying pre-image bytes and a post-apply hash. Commit—which is what makes the entry rollbackable—requires the pre-apply hash to match the hash of the buffer state that the entry claims to have started from, and requires anchor uniqueness to have been verified at apply time. An entry that fails commit is retained for forensics but is marked non-invertible; the rollback engine skips it and forces re-derivation from the nearest committed checkpoint. This costs tokens: re-derivation from a checkpoint is more expensive than inverse replay. The trade is deliberate. Inverse replay that silently reconstructs a counterfactual state is worse than re-derivation, because the counterfactual state is *plausible*—it parses, it has the right schema, it passes shallow consistency checks—and the agent has no signal that it is operating on a history that never happened. The contradiction loop observed above is the canonical downstream symptom: two agents reasoning correctly from a shared state that is internally inconsistent, each blaming the other's evidence, neither able to see that the divergence is in the substrate. The guardrail is a hash-chained byte journal with commit gating, not a smarter diff parser. Diff parsers can be made arbitrarily good at resolving ambiguity; they cannot make an ambiguous edit retroactively well-defined. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class UnreconstructableRollback(RuntimeError): """Raised when inverse replay cannot prove it reconstructs a real prior state.""" pass @dataclass class JournalEntry: step: int pre_image: bytes post_image: bytes pre_hash: str post_hash: str committed: bool = False class EditJournal: def __init__(self, initial_buffer: bytes): self.buffer = initial_buffer self.entries: list[JournalEntry] = [] self._hash = self._digest(initial_buffer) @staticmethod def _digest(b: bytes) -> str: return hashlib.sha256(b).hexdigest() def apply(self, step: int, anchor: bytes, replacement: bytes) -> JournalEntry: # Anchor uniqueness is checked against the LIVE buffer, not the model's claim. occurrences = self.buffer.count(anchor) if occurrences != 1: raise UnreconstructableRollback( f"step {step}: anchor occurs {occurrences} times; diff is underdetermined" ) idx = self.buffer.index(anchor) pre_image = self.buffer[idx:idx + len(anchor)] pre_hash = self._hash new_buffer = self.buffer[:idx] + replacement + self.buffer[idx + len(anchor):] post_hash = self._digest(new_buffer) entry = JournalEntry( step=step, pre_image=pre_image, post_image=replacement, pre_hash=pre_hash, post_hash=post_hash, ) self.buffer = new_buffer self._hash = post_hash self.entries.append(entry) return entry def commit(self, entry: JournalEntry) -> None: # A commit is only valid if the entry's claimed pre_hash matches the # hash of the state it was applied to. An entry applied against a # buffer that had already moved (batch-authored against one snapshot) # will fail here and must not be treated as invertible. if entry.pre_hash != self._hash_of_predecessor(entry): raise UnreconstructableRollback( f"step {entry.step}: pre_hash does not match predecessor state; " f"entry is non-invertible and rollback must re-derive from checkpoint" ) entry.committed = True def _hash_of_predecessor(self, entry: JournalEntry) -> str: i = self.entries.index(entry) return self.entries[i - 1].post_hash if i > 0 else self.entries[0].pre_hash def rollback_to(self, step: int) -> bytes: for entry in reversed(self.entries): if entry.step <= step: break if not entry.committed: raise UnreconstructableRollback( f"step {entry.step}: uncommitted entry in rollback path; " f"cannot prove reconstructed state existed" ) idx = self.buffer.find(entry.post_image) if idx < 0: raise UnreconstructableRollback( f"step {entry.step}: post_image absent from buffer; " f"region overwritten by non-intersecting later edit" ) self.buffer = ( self.buffer[:idx] + entry.pre_image + self.buffer[idx + len(entry.post_image):] ) if self._digest(self.buffer) != entry.pre_hash: raise UnreconstructableRollback( f"step {entry.step}: post-inverse hash mismatch; " f"reconstructed state is counterfactual" ) self._hash = entry.pre_hash return self.buffer ```