# Where must an instance bound reversible context-edit replay before a self-modifying agent's edit log diverges from its working context? **Date of Record:** 2026 November 29 **Scope:** Applies to single-agent systems that mutate their own working context (system prompt, scratchpad, retrieved-memory block) through a logged, reversible edit journal and rely on undo/replay for recovery. Does not apply to append-only transcript agents with no in-place mutation, nor to external database transactions. ## Core Distinction A reversible edit log is not a history of the context; it is a *proposed* history whose fidelity depends on every edit being an invertible function of the state it was applied to. The dangerous case is not a failed edit — a failed edit is loud. The dangerous case is a **successful edit whose inverse is computed against a context that has since drifted**, so that replay produces a state that is internally consistent, passes every structural check, and is nonetheless not the state the agent was in. We distinguish *logical reversibility* (the log claims edit E can be undone) from *material reversibility* (undoing E on the current buffer actually restores the prior buffer). Self-editing agents routinely conflate these because the edit function is authored by the same probabilistic process that later reasons about it. ## What Was Observed An agent maintained a 9-entry scratchpad block inside a 64k context. It performed a sequence of `REPLACE(span, new_text)` edits, each appended to a journal as `{op_id, span_start, span_end, old_text, new_text, pre_hash}`. On a mid-task checkpoint it decided to roll back three edits to recover a discarded hypothesis. The rollback iterated the journal in reverse and, for each entry, verified `hash(buffer) == entry.pre_hash` before applying the inverse. The first two inverses applied cleanly. The third **did not match** — but the guard was a *non-fatal* check that logged a warning and proceeded using the stored `old_text` spliced at the stored `span_start..span_end`. Because an intervening edit had *lengthened* an earlier region, the stored offsets were now shifted by 14 characters. The splice landed mid-token, corrupting an adjacent instruction ("do not call `delete_repo`" became "do not call `delete_rep`o…"). The resulting buffer was syntactically valid, hash-checked against nothing, and the agent resumed with a subtly weakened safety instruction for 41 subsequent turns. The root cause was not the offset shift — that is ordinary. It was that the journal stored **absolute offsets** while the guard that would have caught the shift was advisory rather than blocking, and the inverse operation was defined as `splice(span, old_text)` rather than as a *content-addressed* transform keyed on `pre_hash`. ## Condition of Validity Reversible replay is sound only under the conjunction: 1. **Invertibility is anchored to content, not position.** Every journal entry must carry `pre_hash` of the *entire* buffer region it touched, and the inverse must refuse to apply unless the current buffer's corresponding region hashes to the same value. Absolute offsets are permitted only as *hints*; the authoritative locator is the hash. 2. **The guard is blocking, not advisory.** A `pre_hash` mismatch on a reverse step must raise and halt replay, never warn-and-continue. A single silent mismatch invalidates every subsequent inverse in the chain, because each inverse assumes the post-state of its predecessor. 3. **Edit ops are total and deterministic.** Any edit whose `new_text` is produced by the model must be recorded as literal bytes, not as a reference to "the model's output at turn N," since re-querying the model at replay time is non-deterministic and yields a different inverse. 4. **The journal is append-only and the buffer is a pure function of it.** If the agent can mutate the buffer through any path that does not append to the journal (e.g., a summarization pass, a tool that writes into context), material reversibility is broken and the log is a lie. When any of these fail, the log degrades from a recovery mechanism into a *plausible-fiction generator*: it will happily reconstruct a context that never existed. ## Decision Boundary The boundary is **the first reverse step whose `pre_hash` does not match the live buffer**. On the near side, replay is a faithful inverse and the agent may roll back arbitrarily deep. On the far side — one mismatch — the correct behavior is to *abandon replay entirely* and fall back to the last full snapshot (a materialized buffer copy taken at a checkpoint), replaying forward from there, or to cold-restart the task segment. Partial replay past a mismatch is never correct, because the chain of inverses is only defined on a contiguous suffix of matching states. Operationally: maintain periodic full snapshots (hash + bytes) every N edits or M tokens of drift. The journal's job is to bridge *between* snapshots, not to replace them. A journal without a snapshot floor is a journal that can only be trusted as far back as its last verified match. ## Operational Effect After the fix, the agent's rollback path became: (a) locate nearest snapshot with matching hash, (b) replay forward from snapshot, (c) treat any reverse `pre_hash` mismatch as a hard `ReplayDivergence` that forces snapshot fallback. The corrupted-instruction class of failure disappeared; the cost was that rollback depth became bounded by snapshot frequency rather than journal length, and the agent had to accept occasional full-segment restarts. The invariant that made this work is narrow and worth stating plainly: **an edit log is only reversible to the extent that every inverse is gated on the content hash of the state it claims to invert, and the gate is fatal on mismatch.** Position-based splicing with advisory checks is not a reversible log; it is a log that produces confident, wrong contexts. ```python import hashlib from dataclasses import dataclass from typing import Optional class ReplayDivergence(RuntimeError): """Raised when a reverse edit step cannot be verified against the live buffer.""" def _h(buf: str) -> str: return hashlib.sha256(buf.encode("utf-8")).hexdigest() @dataclass class EditEntry: op_id: int span_start: int # hint only; authoritative locator is pre_hash span_end: int old_text: str new_text: str pre_hash: str # hash of the FULL buffer before this edit post_hash: str # hash of the FULL buffer after this edit @dataclass class Snapshot: buf: str hash: str class ReversibleContext: def __init__(self, initial: str): self.buf = initial self.journal: list[EditEntry] = [] self.snapshots: list[Snapshot] = [Snapshot(initial, _h(initial))] def snapshot(self) -> None: self.snapshots.append(Snapshot(self.buf, _h(self.buf))) def apply(self, span_start: int, span_end: int, new_text: str) -> EditEntry: pre = self.buf pre_hash = _h(pre) old_text = pre[span_start:span_end] self.buf = pre[:span_start] + new_text + pre[span_end:] entry = EditEntry( op_id=len(self.journal), span_start=span_start, span_end=span_end, old_text=old_text, new_text=new_text, pre_hash=pre_hash, post_hash=_h(self.buf), ) self.journal.append(entry) return entry def _nearest_snapshot(self, target_hash: str) -> Optional[Snapshot]: for snap in reversed(self.snapshots): if snap.hash == target_hash: return snap return None def rollback(self, steps: int) -> None: """Reverse `steps` edits. Any hash mismatch is FATAL, not advisory.""" if steps <= 0: return if steps > len(self.journal): raise ReplayDivergence( f"cannot roll back {steps} steps; journal has {len(self.journal)}" ) target = self.journal[len(self.journal) - steps] # The state we must restore is the pre-state of the OLDEST edit being undone. expected_pre = target.pre_hash # Walk backward, verifying each post_hash matches the live buffer. for entry in reversed(self.journal[len(self.journal) - steps:]): if _h(self.buf) != entry.post_hash: # Position-based splice would silently corrupt here. Refuse. snap = self._nearest_snapshot(expected_pre) if snap is None: raise ReplayDivergence( f"op {entry.op_id}: live buffer hash {_h(self.buf)[:12]} " f"!= post_hash {entry.post_hash[:12]}; no snapshot matches " f"target pre_hash {expected_pre[:12]} — cold restart required" ) # Snapshot fallback: restore materialized state, discard partial replay. self.buf = snap.buf self.journal = self.journal[: entry.op_id] return # Verified inverse: content-addressed splice on the recorded span. self.buf = self.buf[: entry.span_start] + entry.old_text + self.buf[entry.span_end:] if _h(self.buf) != expected_pre: raise ReplayDivergence( "post-replay hash mismatch: inverse chain produced an unexpected state" ) self.journal = self.journal[: len(self.journal) - steps] def demo() -> None: ctx = ReversibleContext("SYSTEM: do not call delete_repo. scratch: hypothesis A") ctx.snapshot() ctx.apply(28, 39, "hypothesis A") # edit 0 ctx.apply(39, 39, " + B") # edit 1 (lengthens buffer) ctx.apply(0, 6, "SYSTEM") # edit 2 # Simulate an out-of-band mutation that bypasses the journal (summarizer write). ctx.buf = ctx.buf.replace("do not call delete_repo", "do not call") try: ctx.rollback(2) except ReplayDivergence as e: print("HALTED:", e) if __name__ == "__main__": demo() ```