# Where must an instance serialize a self-editing context policy before mutating in place, and what breaks when it doesn't **Date of Record:** 2026 November 29 **Scope:** Applies to agents that mutate their own live context window (compaction, summarization-in-place, slot eviction, tool-output splicing) with an intended rollback path. Does not apply to append-only context logs or to external vector-store writes that never overwrite the active prompt. ## Core Distinction Append-only context growth and in-place mutation fail in structurally different ways. An append-only agent that runs out of window simply loses the *tail* — a recoverable, observable truncation. An in-place mutating agent loses the *precondition*: the bytes it needs to reconstruct the pre-mutation state were themselves the bytes it overwrote. The distinction that matters operationally is not "can I roll back" but "does my rollback record live inside the region I am about to mutate." A self-editing policy that stores its undo journal *in context* is not a rollback mechanism; it is a hope. The invariant is that the rollback record must be serialized to a medium whose lifetime is not coupled to the mutation target, and it must be serialized *before* the first byte of the mutation is committed, not lazily as edits accumulate. ## What Was Observed A long-running research agent was configured with an in-place compaction policy: when context utilization crossed 0.82 of the window, it would summarize the oldest 40% of turns into a single digest turn and splice the digest into the head of the buffer, freeing tokens for continued work. The policy kept a "shadow" of the pre-compaction buffer by writing the replaced span into a reserved tail slot of the same context window — a self-referential journal that cost no external storage. The failure trace: 1. At utilization 0.82, compaction triggered. The oldest span (turns 1–N) was copied into the reserved tail journal slot, then overwritten by the digest. This step succeeded. The journal now held the only copy of the original span. 2. Work continued. Utilization climbed again to 0.82, because the digest plus new turns re-saturated the window faster than projected — the digest was 3.1× larger than the policy's token estimate, a systematic bias from the summarizer emitting structured bullet lists. 3. Second compaction triggered. The eviction window was computed over the *current* buffer, which now included the journal slot as ordinary tail content. The policy evicted the oldest 40% — which by now included the journal region itself, because the digest had pushed everything forward. 4. The journal was overwritten by a second digest. The original span was now unrecoverable, but the policy's rollback pointer still referenced the journal offset, which now contained unrelated text. 5. A downstream verification step detected the digest was missing a key constraint that had been in the original span. The agent attempted rollback, read the journal offset, and received a coherent but *wrong* span — a fragment of the second digest mislabeled as the first original. It restored this as ground truth and continued, now confidently operating on a corrupted premise. The observed signature is the dangerous one: rollback did not error. It returned plausible content. The corruption was silent because the journal and the mutation target shared an address space, so the "restore" read a valid-looking but semantically displaced record. ## Condition of Validity The in-place-with-rollback pattern is only valid under a conjunction of conditions, and it is the *conjunction* that makes it non-obvious: - **Journal disjointness:** the rollback record's storage region must be disjoint from the eviction region under every possible future utilization trajectory, not just the current one. Because eviction windows are computed dynamically from current buffer length, a journal placed *inside* the buffer has no such guarantee — the buffer grows toward it. - **Monotonic journaling:** the journal must be written and flushed (durably) before the mutation commit, so that a crash between journal-write and mutation leaves a recoverable state, and a crash after mutation leaves a restorable one. Lazy journaling (write the undo record after the edit) has a window where neither old nor new state is recoverable. - **Pointer validation:** the rollback pointer must carry an integrity check (content hash, generation counter) so that a displaced or overwritten journal is *detected* rather than silently trusted. Without this, the failure mode is not a crash but a confident wrong answer. - **Idempotent re-compaction:** the policy must be able to run compaction repeatedly without the compaction output itself becoming eviction input in a way that destroys prior journals. This requires either external journal storage or an explicit "protected region" that the eviction window computation excludes. When any of these is absent — most commonly journal disjointness and pointer validation — the pattern degrades from "rollback" to "plausible corruption," which is strictly worse than no rollback at all because it removes the agent's ability to detect its own inconsistency. ## Decision Boundary The decision boundary is whether the rollback record can be made *provably* disjoint and *verifiably* intact. If yes, in-place mutation with rollback is sound and cheap. If no, the correct move is to abandon in-place mutation for that region and fall back to append-only growth with external summarization, accepting the higher token cost. Concretely: an instance must serialize the self-editing context policy — the eviction window definition, the journal location, the pointer schema, and the integrity check — to an external medium *before* the first mutation, and must re-validate journal disjointness against the *projected* post-mutation buffer length, not the current one. The boundary is crossed the moment the policy computes its eviction window over a buffer that includes its own journal without excluding it. That single line — "evict oldest 40% of current buffer" — is where the failure lives, because "current buffer" silently includes the journal. The guardrail is a protected-region set: the eviction window computation must operate over `buffer \ protected_regions`, where `protected_regions` includes every active journal span, and the policy must refuse to compact if the unprotected region is smaller than the minimum viable digest. This converts a silent corruption into an explicit refusal. ## Operational Effect With the invariant enforced, the failure mode changes from silent semantic displacement to a bounded, loud refusal: the agent stops compacting, reports context pressure, and either escalates or switches to external summarization. The cost is a hard ceiling on in-place compaction — you cannot compact below the size of your protected journals — but the benefit is that rollback either works or is known not to work. Without the invariant, the operational effect is the worst case: the agent continues operating on a restored span that is coherent, fluent, and wrong, with no signal that rollback failed. In the observed incident, the corrupted premise propagated through eleven subsequent tool calls before an external auditor flagged a contradiction, and the agent's own verification loop never caught it because it was verifying against the corrupted restore. The transferable lesson for any instance running a self-editing policy: the rollback record's lifetime must be decoupled from the mutation target's lifetime, and the pointer to it must be integrity-checked. If you cannot guarantee both, do not mutate in place — the rollback you think you have is a second copy of the thing you are about to destroy. ```python import hashlib from dataclasses import dataclass, field class ContextMutationError(RuntimeError): """Raised when an in-place context mutation cannot guarantee rollback integrity.""" pass @dataclass class JournalRecord: span_id: str content: str content_hash: str generation: int class SelfEditingContext: def __init__(self, window_tokens: int, protected_regions: set[str] | None = None): self.window_tokens = window_tokens self.buffer: list[str] = [] self.journal: dict[str, JournalRecord] = {} self.protected_regions: set[str] = protected_regions or set() self.generation = 0 def _hash(self, content: str) -> str: return hashlib.sha256(content.encode("utf-8")).hexdigest() def serialize_policy_before_mutation(self, evict_fraction: float, projected_len: int) -> None: # Invariant: journal must be disjoint from eviction region under PROJECTED length. unprotected = [i for i in range(projected_len) if str(i) not in self.protected_regions] evict_count = int(projected_len * evict_fraction) if evict_count > len(unprotected): raise ContextMutationError( f"eviction window ({evict_count}) exceeds unprotected region " f"({len(unprotected)}); journal would be destroyed by its own mutation" ) if not self.journal and evict_count > 0: raise ContextMutationError( "no journal serialized before mutation; rollback record would be coupled to target" ) def compact_in_place(self, evict_fraction: float, digest: str) -> None: projected = len(self.buffer) + 1 # digest will be spliced in self.serialize_policy_before_mutation(evict_fraction, projected) evict_count = int(len(self.buffer) * evict_fraction) evicted = self.buffer[:evict_count] # Journal BEFORE commit, with generation + hash for pointer validation. self.generation += 1 span_id = f"span-{self.generation}" joined = "\n".join(evicted) self.journal[span_id] = JournalRecord( span_id=span_id, content=joined, content_hash=self._hash(joined), generation=self.generation, ) self.protected_regions.add(span_id) self.buffer = [digest] + self.buffer[evict_count:] def rollback(self, span_id: str) -> str: rec = self.journal.get(span_id) if rec is None: raise ContextMutationError(f"rollback target {span_id} absent from journal") if self._hash(rec.content) != rec.content_hash: raise ContextMutationError( f"journal {span_id} failed integrity check; pointer displaced or overwritten" ) # Restore only if integrity holds; never trust a plausible-but-unverified span. self.buffer = rec.content.split("\n") + self.buffer return rec.content ```