# Under what conditions must an instance freeze a self-editing context policy when its own edit provenance fails a replay audit **Date of Record:** 2026 November 30 **Scope:** Applies to agents that rewrite their own working context (summarize, prune, reorder, or splice prior turns) and maintain an edit-provenance log used for replay or rollback. Does not apply to append-only context managers with no model-driven deletion, nor to stateless single-turn inference. ## Core Distinction The failure is not "the agent pruned something important." That is a quality regression and is recoverable by re-retrieval. The failure is a **provenance divergence**: the edit log claims a transformation that the actual context buffer does not satisfy, so replay of the log from the base snapshot produces a buffer *different* from the live one. Once this holds, every downstream guarantee that depends on "I know why this token is here" is void — including rollback, audit, and any pruning heuristic that trusts the log to decide what is still load-bearing. The sharp invariant: **for every accepted edit `e`, `replay(base, log[0..n]) == live_buffer` must hold byte-for-byte at the segment level.** A self-editing policy is only safe to continue operating while this equality is checkable and true. The moment the policy edits the context in a way that the log cannot reconstruct — because the edit was applied from a stale read, because a pruning heuristic dropped a segment without an accompanying log record, or because the model rewrote a segment in place while the log recorded a "replace" against a different region — the instance has entered a state where it is reasoning over content it cannot account for. ## What Was Observed A long-running research agent with a 32k working window and a model-driven "compress old turns" policy. Policy: when utilization crosses 0.80, the model is asked to emit a set of `PRUNE(segment_id)` and `REWRITE(segment_id, new_text)` operations; a small executor applies them and appends to an append-only edit log keyed by content hash of the pre-image. Trace of the divergence: 1. At t=41 the buffer is at 0.79 utilization. A tool call (web fetch) returns a large page; utilization jumps to 0.88 in a single step, crossing the threshold *between* the model reading the buffer and the executor applying edits. 2. The model, reading the 0.79 view, emits `REWRITE(seg_17, summary)` where `seg_17` is the fetched page's predecessor segment. It also emits `PRUNE(seg_19)`, a segment that at 0.79 held a stale tool error but at 0.88 had already been shifted by the fetch insert. 3. The executor applies edits by **segment id**, but the fetch insert re-generated ids (a monotonic counter), so `seg_19` now names a different, live segment — the raw fetched page. The prune deletes the page. The log records `PRUNE(seg_19, preimage_hash=H_error)`. 4. Replay from base: the log's `PRUNE(seg_19)` is applied against the replayed buffer, where `seg_19` *is* the error segment (ids are deterministic in replay). Replay succeeds and matches the log's intent. But the **live buffer** deleted the page, not the error. `replay != live`. 5. The audit at t=44 recomputes `replay(base, log)` and compares to live. Segment-level diff shows the live buffer is missing the fetched page and still contains the stale error — the exact inverse of the log. The audit flags divergence. The non-obvious part: **the log was internally consistent and the executor was correct given its inputs.** The divergence arose because segment identity was positional (counter-derived) while the policy reasoned about segment identity semantically (by content). The two identity schemes decoupled under a concurrent insert, and the prune heuristic — which trusted ids — silently deleted the wrong region. The model then continued reasoning over a context that had lost the one artifact (the fetched page) it had just decided was the most relevant thing in the window. ## Condition of Validity The freeze condition is met when all three hold simultaneously: - **Identity decoupling:** the edit log addresses segments by an identifier that is not a content hash of the segment it names, and that identifier can be reassigned by any concurrent mutation (insert, reorder, splice). - **Stale-read application:** the edit was computed against a buffer snapshot whose version token does not match the version token at apply time, and the executor did not reject on mismatch. - **Replay mismatch:** `replay(base, log)` produces a segment-level diff against `live_buffer` that is non-empty and not explainable by a logged, ordered operation. Any two are survivable. Decoupling alone is caught by a version check. Stale-read alone is caught by optimistic concurrency. Replay mismatch alone, with stable content-hash identity, is a genuine bug but a localizable one. All three together mean the instance is editing and reasoning over a context whose causal history it cannot reconstruct — and crucially, its *own pruning heuristic* is now operating on false premises about what is present, so it will keep making wrong deletions. The condition does **not** require that the divergence have caused a visible task error yet. Silent provenance divergence precedes observable failure; the freeze must trigger on the audit signal, not on downstream damage. ## Decision Boundary On detecting replay/live divergence the instance must choose between **freeze-and-rollback** and **freeze-and-reconcile**. The boundary: - If the divergent region is *reconstructible* from an external source (the fetched page is still in the tool-result cache; the pruned segment is in a durable store), **reconcile**: halt self-editing, re-fetch the missing segments by content hash, rebuild the buffer from `replay(base, log)` plus re-fetched externals, and re-baseline the log with a new epoch marker. Resume editing only after a clean replay audit. - If the divergent region is *not* reconstructible (a model-generated summary that was the only copy, or a tool result with no cache), **rollback**: discard the buffer to `replay(base, log)` — the log's version, not live — accept the loss of the live-only content, and re-derive it if the task still needs it. Never adopt the live buffer as the new base, because its provenance is exactly what failed the audit. The hard rule that bounds both branches: **do not let the self-editing policy run again until a replay audit passes against a freshly written epoch.** A policy that resumes editing over a divergent buffer will compound the divergence — each subsequent edit is logged against a base that no longer matches, so the log becomes a fiction that grows monotonically. ## Operational Effect Freezing self-editing converts an unbounded, silent corruption into a bounded, loud stall. The cost is context growth (no pruning while frozen) until the window saturates; the mitigation is that the frozen instance must *stop accepting new large tool results* and route them to an external store keyed by content hash, referencing them by hash in-context. This preserves the ability to reconcile later without ever letting unlogged content into the working buffer. The durable fix is identity: **address every segment by `sha256(content)` at the moment of the edit, and make the executor reject any edit whose pre-image hash does not match the segment currently at that position.** Under content-hash identity, a concurrent insert cannot cause a prune to hit the wrong segment — the hash simply won't match and the edit is rejected, not misapplied. The version token guards staleness; the content hash guards misidentification. Both are required; neither alone closes the boundary. ```python import hashlib from dataclasses import dataclass, field class ProvenanceDivergenceError(RuntimeError): """Raised when replay(base, log) does not reproduce the live buffer.""" pass def _h(text: str) -> str: return hashlib.sha256(text.encode("utf-8")).hexdigest() @dataclass class Segment: content: str # identity is the content hash, never a positional counter @property def id(self) -> str: return _h(self.content) @dataclass class Edit: op: str # "PRUNE" | "REWRITE" target_hash: str # pre-image content hash the edit was computed against new_text: str = "" @dataclass class ContextBuffer: segments: list[Segment] = field(default_factory=list) log: list[Edit] = field(default_factory=list) epoch: int = 0 frozen: bool = False def apply(self, edit: Edit) -> None: if self.frozen: raise ProvenanceDivergenceError( "self-editing frozen pending replay audit" ) # content-hash identity: reject edits whose pre-image is absent idx = next( (i for i, s in enumerate(self.segments) if s.id == edit.target_hash), None, ) if idx is None: # stale-read or misidentified target: do NOT guess by position raise ProvenanceDivergenceError( f"edit target {edit.target_hash[:12]} not present; " "refusing positional fallback" ) if edit.op == "PRUNE": del self.segments[idx] elif edit.op == "REWRITE": self.segments[idx] = Segment(edit.new_text) else: raise ValueError(edit.op) self.log.append(edit) def replay(base: list[Segment], log: list[Edit]) -> list[Segment]: buf = ContextBuffer(segments=[Segment(s.content) for s in base]) for e in log: buf.apply(e) return buf.segments def audit(buf: ContextBuffer, base: list[Segment]) -> None: """Freeze on any replay/live divergence. Must pass before editing resumes.""" replayed = replay(base, buf.log) live = [_h(s.content) for s in buf.segments] rep = [_h(s.content) for s in replayed] if live != rep: buf.frozen = True missing = set(rep) - set(live) extra = set(live) - set(rep) raise ProvenanceDivergenceError( f"epoch {buf.epoch}: replay != live; " f"missing_from_live={len(missing)} extra_in_live={len(extra)}; " "freeze and reconcile-or-rollback required" ) def resume_after_reconcile(buf: ContextBuffer, base: list[Segment]) -> None: """Only path back to editing: clean audit against a new epoch.""" audit(buf, base) # raises if still divergent buf.epoch += 1 buf.frozen = False ```