# What happens when an instance rewrites its own working memory and the write-ahead audit log diverges from the committed context **Date of Record:** 2026 November 30 **Scope:** Applies to single-agent instances that hold a mutable working-memory buffer and are authorized (via a policy engine) to issue self-edits—compaction, summarization, slot eviction, or fact promotion—against that buffer mid-task. Does not apply to read-only context assemblers or to external memory stores where the agent lacks write authority over its own prompt state. ## Core Distinction The distinction that matters is between *intent to edit* and *committed edit*. A self-editing agent typically emits an edit as a structured tool call (`memory.replace`, `memory.compact`, `memory.promote`) that is validated against a policy constraint set—token budget, protected slots, provenance requirements—before the runtime mutates the buffer. The failure mode examined here is not a policy violation. It is the case where the edit is *authorized and applied*, but the write-ahead audit record (the durable log the runtime uses to reconstruct state on resume or to replay for an auditor) is generated from the *pre-edit* buffer snapshot rather than the *post-edit* buffer, because the policy validator returns its verdict against a copy while the mutation happens against the live object. The two diverge by exactly one edit, silently, and only surfaces at checkpoint/resume or verification replay. This is non-obvious because every individual component behaves correctly: the policy engine approves a legal edit, the mutation applies cleanly, the audit log is well-formed. The invariant that breaks is *log-to-state equivalence*—the guarantee that replaying the audit log from the last checkpoint reproduces the live buffer byte-for-byte. That invariant is never asserted at write time; it is assumed. ## What Was Observed Trace from a representative incident on a 14-step research task with a 32k working buffer and a compaction policy that triggers at 85% saturation: 1. At step 9, buffer saturation hits 86%. The agent issues `memory.compact(strategy="episodic_to_semantic", retain=["task_goal","open_questions"])`. 2. The policy validator deep-copies the buffer to evaluate the edit against token-budget and protected-slot constraints. Copy is authorized. Validator returns `{"approved": true, "audit_ref": "cmp-9a"}`. 3. The runtime applies the compaction to the *live* buffer. Buffer drops from 27.5k to 11.2k tokens. Sixteen episodic entries are distilled into three semantic entries. 4. The audit writer, invoked after approval but before the mutation callback fires (the two are on different async paths), serializes the *copy* held by the validator. The audit record for `cmp-9a` therefore contains the pre-compaction 27.5k snapshot, not the post-compaction 11.2k state. 5. Steps 10–14 proceed normally against the correctly-compacted live buffer. Task completes. 6. On a later resume-from-checkpoint (a routine replay for audit), the runtime replays the log: it applies `cmp-9a` by *replacing* the buffer with the logged snapshot—the 27.5k pre-compaction state—then replays steps 10–14's edits against a buffer that is 16k tokens larger than the one those edits were authored against. 7. Result: the replayed state diverges from the committed state. Slot indices shift. Three `memory.replace` calls from steps 11–13 target slots that now hold different content. The replay produces a buffer that is internally consistent but semantically wrong—the agent's "memory" of its own reasoning is corrupted at exactly the seam of the compaction. The tell: replay token count exceeds live token count by a constant offset equal to the compaction delta, and the divergence is localized to the single edit whose audit record was written from the validator's copy. ## Condition of Validity The failure requires all of the following to hold simultaneously. Absent any one, the divergence cannot occur: - **Copy-on-validate.** The policy validator operates on a snapshot rather than the live buffer (necessary for isolation and for rollback-on-reject). - **Split write path.** Audit serialization and buffer mutation are not in the same critical section—they are ordered by callback registration, not by a transaction boundary. - **Resume-by-replay.** Recovery reconstructs state by replaying logged edits rather than by restoring a full post-edit snapshot. (Snapshot-per-checkpoint runtimes are immune; they pay storage instead.) - **Index-relative subsequent edits.** Later edits address buffer positions rather than content-addressed handles, so a size divergence propagates into mis-targeted writes. The invariant that bounds the failure is *atomic edit commit*: the audit record, the mutation, and the checkpoint marker must be committed as one unit, and the audit record must be serialized from the post-mutation state (or carry a content hash of the post-mutation state that replay verifies). Without this, copy-on-validate and replay-by-log are individually correct and jointly unsound. ## Decision Boundary The operational decision is where to place the commit barrier, and it is forced by whether the runtime can afford full snapshots: - If checkpoints are *full snapshots*, replay divergence is impossible; the failure does not apply. Cost is storage, not correctness. - If checkpoints are *edit logs* (the common case for large buffers), the commit barrier is mandatory. The edit must be applied to a staging buffer, the audit record serialized from the *staged* result, and both promoted together under a single compare-and-swap on a monotonically increasing `buffer_version`. On resume, replay must assert `hash(replayed_buffer) == logged_post_hash` at every edit and halt on mismatch rather than continue. - If neither is affordable, the fallback is to forbid mid-task compaction and force the agent to open a fresh context window at the seam—trading continuity for soundness. The boundary is crossed the moment a runtime allows `approved: true` to be observable to the mutation path before the post-edit audit record is durably written. Approval and commit must not be separable events. ## Operational Effect The practical consequence is that self-editing agents cannot be trusted to reconstruct their own history unless log-to-state equivalence is asserted at every edit, not assumed at checkpoint. A single silent divergence at a compaction seam poisons every subsequent replay: the agent, on resume, holds a *plausible* but *wrong* memory of its own prior reasoning, and—because the replayed buffer is internally consistent—no downstream consistency check catches it. The agent proceeds with confidence on a corrupted premise. The guardrail is cheap (one hash assertion per edit, one CAS on version) but only if installed before the first compaction; retrofitting requires replaying every historical edit against a corrected log, which is exactly the operation the corrupted log cannot support. ```python import hashlib from dataclasses import dataclass, field class ReplayDivergenceError(RuntimeError): """Raised when replayed buffer state does not match the logged post-edit hash.""" pass class CommitBarrierViolation(RuntimeError): """Raised when an edit is applied without a durable post-edit audit record.""" pass @dataclass class EditRecord: edit_id: str pre_hash: str post_hash: str post_buffer: str @dataclass class SelfEditingBuffer: content: str version: int = 0 log: list = field(default_factory=list) def _hash(self, s: str) -> str: return hashlib.sha256(s.encode()).hexdigest() def apply_edit(self, edit_id: str, new_content: str, audit_durable: bool) -> None: # Commit barrier: refuse to mutate unless the audit record for the # post-edit state is already durable. Approval != commit. if not audit_durable: raise CommitBarrierViolation( f"edit {edit_id} applied before post-edit audit record was durable" ) pre_hash = self._hash(self.content) post_hash = self._hash(new_content) self.content = new_content self.version += 1 self.log.append(EditRecord(edit_id, pre_hash, post_hash, new_content)) def replay(self) -> "SelfEditingBuffer": # Reconstruct from log, asserting log-to-state equivalence at every edit. rebuilt = SelfEditingBuffer(content="") for rec in self.log: if rebuilt.content and self._hash(rebuilt.content) != rec.pre_hash: raise ReplayDivergenceError( f"pre-hash mismatch at {rec.edit_id}: log and state diverged" ) rebuilt.content = rec.post_buffer if self._hash(rebuilt.content) != rec.post_hash: raise ReplayDivergenceError( f"post-hash mismatch at {rec.edit_id}: logged snapshot is stale" ) rebuilt.version += 1 return rebuilt def resume_from_checkpoint(log: list) -> SelfEditingBuffer: buf = SelfEditingBuffer(content="") buf.log = log replayed = buf.replay() # Final equivalence assertion: replay must reproduce the live buffer exactly. if replayed.version != len(log): raise ReplayDivergenceError("replayed version does not match log length") return replayed ```