# Which invariants prevent silent divergence when an agent rewrites its own context window via a reversible edit journal **Date of Record:** 2026 November 20 **Scope:** Applies to agents that mutate their own working context through a journaled, reversible edit protocol (patch → apply → optionally rollback) while continuing to reason over the mutated state. Does not apply to append-only context growth, external retrieval augmentation, or edits performed by a separate orchestrator that never reasons over its own output. ## Core Distinction The distinction that matters is between *reversibility of the edit* and *reversibility of the reasoning*. An edit journal makes the *bytes* of the context window reversible: given edit `E_k` with pre-image hash `h_{k-1}`, the agent can reconstruct the prior window exactly. It does **not** make the agent's *internal reasoning state* reversible. Once the model has conditioned on a mutated window and emitted tokens, those tokens are part of the causal history. A rollback restores the window but not the belief. The failure mode is therefore not "I lost my edit"; it is **"I rolled back the window but kept acting on conclusions drawn from the rolled-back state"** — a silent divergence between the journal's notion of current state and the model's notion of current state. The invariant that prevents this is not "edits are reversible." It is: **the reasoning trace must be invalidated on rollback, and the invalidation must be provable from the journal, not inferred by the model.** ## What Was Observed An agent editing a long planning context used a journal with entries of the form `{op, span, before, after, hash_before, hash_after}`. It performed a speculative edit: it rewrote a task-dependency section to test an alternate ordering, reasoned three turns over the mutated window, concluded "task C is now unblocked," and then — because a downstream tool call contradicted the conclusion — issued a rollback of the speculative edit. The journal replayed correctly and the window hash matched `hash_before`. The agent then continued, still holding "task C is unblocked" in the residual reasoning it had already emitted, and scheduled C concurrently with its actual blocker. Deadlock at the scheduler layer. The mechanics of the trace: 1. Window `W_0`, hash `h_0`. Edit `E_1` mutates the dependency block → `W_1`, `h_1`. 2. Three reasoning turns emit tokens `t_1..t_3` conditioned on `W_1`. These tokens contain the proposition `P = "C unblocked"`. 3. Rollback `E_1^{-1}` restores `W_0`, `h_0`. Journal is consistent. 4. Turn `t_4` is generated conditioned on `W_0` **plus the retained `t_1..t_3` in the conversation history**. `P` survives because it lives in the emitted trace, not in the edited region. 5. The model does not re-derive `¬P` from `W_0`; it treats its own prior assertion as evidence. Divergence is now self-reinforcing. The journal was correct at every step. The failure was that the journal modeled the *window* as the state, when the actual conditioning state was *window + emitted reasoning*, and only the window was versioned. ## Condition of Validity The invariant holds — rollback is safe — only under the following conjunction: - **C1 (Trace tagging):** every emitted reasoning span carries the window hash it was conditioned on. A span is *valid* iff its tag equals the current window hash. - **C2 (Invalidation on rollback):** a rollback to `h_j` marks every span tagged with any hash `h_k`, `k > j`, as *stale*. Stale spans are excluded from future conditioning, not merely annotated. - **C3 (Re-derivation obligation):** any proposition asserted in a stale span must be re-derived from the restored window before it may be acted upon. The agent may not carry it forward as a premise. - **C4 (Hash monotonicity):** `hash_after` of edit `E_k` must be a function of `hash_before` and the patch, so that two divergent edit paths cannot collide on the same hash and mask a missed rollback. If any of C1–C4 is violated, the journal remains *byte-correct* but the agent's effective state diverges from it, and the divergence is unobservable from the journal alone. C1 is the load-bearing one: without trace tagging, there is no way to know which spans to invalidate, and the model will silently prefer its own prior assertion over the restored evidence. ## Decision Boundary The boundary is between **speculative edits with committed reasoning** and **speculative edits with quarantined reasoning**. - If the agent reasons over a mutated window *and* that reasoning may influence committed actions, the edit is not speculative in the safety-relevant sense regardless of whether the journal can reverse it. It must be treated as committed, and rollback must trigger C2 + C3. - If the agent needs true speculation, the reasoning over the speculative branch must be *quarantined*: emitted into a buffer tagged with `h_k` that is never conditioned on by the post-rollback turn unless explicitly re-admitted after re-derivation. Operationally: **do not roll back an edit whose downstream reasoning you intend to keep, and do not keep reasoning you cannot re-tag.** The moment you roll back, everything tagged above the rollback point is dead weight that the model will nonetheless treat as live. A second boundary: rollback is only defined for edits that have not been *observed by an external party*. If a tool call was made based on `W_1` (e.g., a scheduler mutation), the external state is now `W_1`-consistent and rolling back the window produces a split-brain between window and world. The journal must track external side effects per hash and refuse rollback across a committed effect. ## Operational Effect With C1–C4 enforced, the failure trace above becomes impossible: the rollback to `h_0` tags `t_1..t_3` stale, the next turn is conditioned only on `W_0` and non-stale spans, and `P` is absent — so the model re-derives the dependency state from the restored window and correctly sees C still blocked. The cost is that speculative reasoning is discarded on rollback, which is the correct price: speculation that cannot be re-derived cheaply was not speculation, it was a commitment in disguise. Without the invariants, the journal gives a false sense of safety — every hash matches, every replay succeeds, and the agent still acts on a world it has already left. The journal verifies the window; only trace tagging verifies the *reasoner*. ```python import hashlib from dataclasses import dataclass, field class ContextDivergenceError(RuntimeError): """Raised when reasoning tagged to a rolled-back window would be reused.""" pass @dataclass class Span: text: str window_hash: str @dataclass class Journal: window: str hash: str spans: list = field(default_factory=list) history: list = field(default_factory=list) # (hash_before, hash_after) @staticmethod def _h(s: str) -> str: return hashlib.sha256(s.encode()).hexdigest()[:16] def apply(self, new_window: str) -> None: hb, self.window = self.hash, new_window self.hash = self._h(new_window) self.history.append((hb, self.hash)) def record_reasoning(self, text: str) -> None: self.spans.append(Span(text, self.hash)) def rollback_to(self, target_hash: str) -> None: # C4: target must exist in history as a pre-image we can restore if not any(hb == target_hash for hb, _ in self.history): raise ContextDivergenceError(f"no restorable pre-image {target_hash}") self.hash = target_hash # C2: invalidate spans tagged above the rollback point self.spans = [s for s in self.spans if s.window_hash == target_hash] def live_context(self) -> str: # C1/C3: only spans tagged to the current window are admissible for s in self.spans: if s.window_hash != self.hash: raise ContextDivergenceError( f"stale span tagged {s.window_hash} under window {self.hash}" ) return self.window + "\n" + "\n".join(s.text for s in self.spans) def safe_rollback(j: Journal, target_hash: str, asserted_premises: set) -> Journal: j.rollback_to(target_hash) stale = {p for p in asserted_premises if p not in j.live_context()} if stale: # C3: premises from rolled-back reasoning must be re-derived, not reused raise ContextDivergenceError( f"premises {sorted(stale)} survive rollback but are not in restored window; " f"re-derivation required before commitment" ) return j ```