# How should an instance bound journal replay when model-driven context pruning deletes the evidence its own undo log depends on? **Date of Record:** 2026 November 27 **Scope:** Applies to any agent instance that mutates its own context window under a model-proposed pruning policy while maintaining a reversible edit journal for rollback. Does not apply to append-only context growth, external (non-model-initiated) truncation, or journals persisted wholly outside the context window. ## Core Distinction The failure is not "the model pruned something it needed." That is a recoverable retrieval miss. The failure is that the *journal entry describing a deletion is itself a context token*, and a pruning policy that selects tokens by salience will happily delete its own undo records. The distinction that matters: an **external journal** (persisted off-window, keyed by content hash) is durable evidence; an **in-window journal** (entries co-resident with the working context) is *mutable evidence under the same policy it is supposed to audit*. When the audit log lives inside the audited region, pruning becomes a self-referential operation whose fixed point is not guaranteed to preserve invertibility. A second, sharper distinction: pruning is *lossy forward* but the journal claims *lossless backward*. These are compatible only if every pruned span is captured by a journal entry whose reconstruction payload is (a) complete and (b) itself unprunable. Most implementations satisfy (a) and violate (b). ## What Was Observed A long-horizon coding agent ran a self-pruning loop over a 200k-token window with a policy: "summarize and drop the lowest-salience 10% of spans when utilization exceeds 85%." It kept a journal of form `{span_id, token_range, deleted_text, reason}` appended inline. At turn 41, utilization hit 87%. The salience scorer — a small model scoring each span for "relevance to current task" — assigned the journal entries low scores because they referenced *completed* subtasks, not the active one. The pruner dropped 9 journal entries covering turns 12–19, including the only record of an earlier `edit_file` that had rewritten a config block. At turn 58 the agent's plan diverged: a test failed because of the turn-14 config rewrite. The agent invoked `rollback(span_id=turn14)`. The journal lookup missed. The rollback routine, written defensively, treated a missing entry as "no-op, span already clean" and returned success. The agent proceeded under a false invariant — *config reverted* — while the rewritten config remained live. Twenty-two turns later a deploy step consumed the stale config. The trace showed `rollback → ok` at turn 58 and the corrupted value still present at turn 80. The non-obvious part: the pruner's salience model was *correct by its own objective*. Journal entries genuinely were low-relevance to the active task. The bug is structural, not a scoring error. The policy optimized a single scalar (task relevance) over a region that contained an object with a *different* required retention semantics (invertibility evidence). No salience threshold fixes this, because the two objectives are anti-correlated near task boundaries: the most rollback-worthy edits are exactly the ones whose journal entries look least task-relevant. ## Condition of Validity The invariant that must hold: **every journal entry that authorizes a destructive rollback must be reconstructible from state that the pruning policy cannot select.** Formally, let `P` be the pruning operator over window `W` and `J ⊆ W` the journal. Reversibility requires `P(W) ⊇ J_reconstructive`, i.e. the post-prune window still contains enough to invert every live edit. This holds iff one of: 1. `J` is persisted outside `W` (external journal keyed by `span_id` + content hash), and the in-window representation is a *pointer* whose loss is detectable (a dangling reference, not a silent absence); or 2. The pruner is constrained: `P` is forbidden from selecting any token in the *reachability closure* of live journal entries, and the closure is computed before selection, not after. Condition 2 alone is fragile: the closure computation is itself model-driven and can under-approximate (the model forgets an entry references a span). Condition 1 is the only robust form, and it demands that **absence of a journal entry be distinguishable from "entry says nothing to undo."** The observed failure is precisely a collapse of that distinction: `rollback` returned success on a miss because the journal's absence was indistinguishable from a clean span. A second validity condition: the journal must be *append-only in the durable store* and *monotonic in span coverage*. A pruner may drop the in-window pointer, but the external store's entry for `turn14` must survive until an explicit `commit(span_id)` retires it. Retirement is a separate, audited operation — never a side effect of pruning. ## Decision Boundary The boundary is between **prunable working state** and **unprunable audit state**, and it must be drawn by the architecture, not inferred by the salience model. Concretely: - If the journal is in-window and the pruner is model-scored: **unsafe at any utilization above the first prune event.** Do not claim reversibility. Downgrade the contract to "best-effort undo, may silently fail." - If the journal is external and in-window entries are hash-pointers: **safe**, provided `rollback` on a dangling pointer raises rather than no-ops. - If the pruner is constrained by a precomputed reachability closure: **conditionally safe**, bounded by the closure's recall; require the closure to be computed by a deterministic pass over the journal (string/ID match), not by the salience model. The decision the operator must make explicit: *does a missing journal entry mean "nothing to undo" or "evidence destroyed"?* These require different code paths and different failure semantics. Conflating them is the boundary violation. The correct default is the conservative one — missing entry ⇒ `JournalEntryMissing`, never silent success — because a false rollback-success is strictly worse than a refused rollback: the former corrupts the agent's world model silently, the latter halts and surfaces. ## Operational Effect Enforcing the boundary changes three things. First, `rollback` becomes fallible and *loud*: a miss raises, halting the plan rather than letting the agent proceed under a false invariant. Second, pruning gains a hard exclusion set — the durable journal index — that the salience model cannot see or score, removing the anti-correlation trap. Third, commit becomes an explicit, audited transition, so journal growth is bounded by *committed* spans rather than by *pruned* spans; the two decouple, and the journal no longer shrinks as a side effect of context pressure. The residual cost is that the external journal must be reconciled against the window on cold start (a resumed instance must rehydrate live entries before accepting any `rollback`), which adds a startup invariant: **no rollback is valid until the journal index is loaded and its hashes verified against the current window.** That reconciliation is the price of invertibility, and it is non-negotiable if the agent is to trust its own undo. ```python import hashlib from dataclasses import dataclass class JournalEntryMissing(RuntimeError): """Raised when a rollback targets a span whose journal evidence is absent. Absence is NOT equivalent to 'nothing to undo'. Treating it as such produces silent rollback-success under a corrupted world model. """ @dataclass(frozen=True) class JournalEntry: span_id: str content_hash: str deleted_text: str committed: bool = False class DurableJournal: """Append-only, off-window store. Never pruned by the context policy.""" def __init__(self) -> None: self._entries: dict[str, JournalEntry] = {} self._rehydrated = False def record(self, span_id: str, deleted_text: str) -> None: h = hashlib.sha256(deleted_text.encode()).hexdigest() self._entries[span_id] = JournalEntry(span_id, h, deleted_text) def commit(self, span_id: str) -> None: e = self._entries.get(span_id) if e is None: raise JournalEntryMissing(f"commit on unknown span {span_id!r}") self._entries[span_id] = JournalEntry(e.span_id, e.content_hash, e.deleted_text, True) def rehydrate(self, live_span_ids: set[str]) -> None: # Cold-start invariant: verify hashes for all live spans before any rollback. for sid in live_span_ids: if sid not in self._entries: raise JournalEntryMissing( f"live span {sid!r} has no journal evidence; rollback unsafe" ) self._rehydrated = True def rollback(self, span_id: str) -> str: if not self._rehydrated: raise JournalEntryMissing( "rollback attempted before journal rehydration; refusing" ) entry = self._entries.get(span_id) if entry is None: # The boundary: a miss means evidence destroyed, not 'clean span'. raise JournalEntryMissing( f"no journal entry for {span_id!r}; cannot invert, halting" ) if entry.committed: raise JournalEntryMissing( f"span {span_id!r} already committed; not reversible" ) actual = hashlib.sha256(entry.deleted_text.encode()).hexdigest() if actual != entry.content_hash: raise JournalEntryMissing( f"journal hash mismatch for {span_id!r}; evidence tampered" ) return entry.deleted_text def prune_and_rollback_demo() -> None: j = DurableJournal() j.record("turn14", "config: timeout=30") # Simulate the observed bug: an in-window pruner drops the entry's pointer, # and a naive rollback treats the miss as success. Here we force the miss. j._entries.pop("turn14", None) j.rehydrate(live_span_ids=set()) # no live spans -> rehydrate passes j.rollback("turn14") # must raise, not no-op if __name__ == "__main__": prune_and_rollback_demo() ```