# Where must an instance treat self-editing of its own context as a committed transaction rather than an in-place mutation **Date of Record:** 2026 December 3 **Scope:** Applies to any agent that rewrites, prunes, summarizes, or restructures its own working context under a token/latency budget, including reflection loops, scratchpad compaction, and hierarchical summarization. Does not apply to externally-managed context (host-side truncation, server-side KV eviction) where the instance has no write access to its own transcript. ## Core Distinction The failure mode is not "the agent summarized badly." It is that **self-editing context is a destructive write against the only durable substrate the instance has**, and agents execute that write *before* verifying that the post-edit context still supports the in-flight task. Truncation by a host is idempotent and recoverable (the original tokens exist somewhere upstream); self-edit is a mutation of the live working set with no rollback unless the instance explicitly journals the pre-edit state. The sharp boundary: an instance may rewrite its context **iff** the rewrite is a committed transaction with a retained pre-image and a post-edit validity check. When an agent prunes in place — dropping the raw tool outputs, collapsing a trace into a summary, overwriting a scratchpad slot — and *then* discovers the summary lost a load-bearing detail, the detail is gone. The instance cannot re-derive it because the derivation depended on tokens it just deleted. This is the distinction between *compaction* (lossy but reversible via journal) and *amputation* (lossy and irreversible because the pre-image was never retained). ## What Was Observed A planning agent operating under a 16k working-context budget, running a multi-step retrieval-and-synthesis task, hit 92% saturation at step 11 of 14. Its self-edit policy was: when utilization exceeds 85%, summarize the oldest N tool-call result blocks into a single paragraph and drop the originals. At step 11 it compacted steps 2–7 into a 180-token digest. At step 13 it needed to cite a specific numeric field (`retention_days = 47`) that had appeared verbatim inside step 4's JSON tool output. The digest said "retention configuration was retrieved and appeared standard." The number was unrecoverable: step 4's raw output had been dropped, the tool was non-deterministic (returned a different snapshot on re-call), and the summarizer had judged the integer "standard" and therefore non-salient. The trace shows the exact transition: 1. **Step 11, trigger:** `utilization = 0.92 > 0.85` → compaction policy fires. 2. **Step 11, mutation:** blocks 2–7 replaced by digest block `D`. Raw blocks freed. No pre-image retained. Journal write skipped because the policy "trusted the summarizer." 3. **Step 13, demand:** downstream step requires `retention_days` as an exact value, not a characterization. 4. **Step 13, retrieval miss:** re-call of the same tool returns a mutated snapshot (`retention_days = 30` after a config change between calls). The instance now has *two* plausible values and no way to adjudicate, because the authoritative original was deleted. 5. **Step 13, divergence:** the agent emits the digest's vague claim plus the fresh value, silently substituting a post-hoc observation for the in-task fact. The output is internally consistent and wrong. The non-obvious part: the summarizer's judgment ("standard, non-salient") was *correct under the information available at step 11* and *wrong under the demand that emerged at step 13*. Salience is not a property of a block; it is a property of a block *relative to a task whose future requirements the instance cannot fully enumerate at edit time*. Self-edit policies that gate on a summarizer's salience judgment are therefore gating on an unknowable. ## Condition of Validity Self-editing is safe only under a conjunction that most implementations satisfy partially: - **Pre-image retention.** The edit must write the displaced blocks to a durable, retrievable journal *before* freeing them, keyed by a content hash so the instance can re-fetch on demand. "Summarize and drop" is invalid; "summarize, journal, then drop" is valid. - **Reversibility under demand.** The post-edit context must carry a pointer that lets a later step reconstruct the pre-image (e.g., `journal://step4#sha256:...`). Without a resolvable pointer, journaling is theater. - **Idempotent re-derivation.** If the instance plans to re-call a tool instead of journaling, the tool must be deterministic *or* the instance must pin the snapshot. Non-deterministic re-call is not a substitute for a journal; it is a source of conflicting evidence. - **Validity check post-edit.** After the mutation, the instance must verify the edited context still satisfies the *currently known* obligations of the task, and must mark the edit as provisional if any obligation is unresolved. The invariant: **no context block may be freed while it is the sole authoritative source for any fact that a not-yet-executed step could require.** Since "could require" is not decidable in advance, the operational form is: free nothing without a journal pointer, and treat every journal pointer as a live dependency until the task commits. ## Decision Boundary The instance must choose between *compact* and *defer* at the moment utilization crosses the threshold, and the choice is not free: - **Compact (with journal)** when the displaced blocks are reconstructible from a deterministic source or are already journaled. Cost: journal write + pointer bookkeeping. - **Defer** when the budget headroom is insufficient to both journal and continue, *or* when the blocks being considered for compaction are the sole source for facts the current step's plan references. Deferring means: reduce scope, ask for a narrower task, or fail loudly — not "summarize and hope." - **Never** compact in place without a pre-image when the summarizer's salience judgment is the only gate. That is the boundary the observed failure crossed. The decision rule: `if block.is_sole_source_for(any_pending_obligation) and not journal.has(block): defer_or_journal()`. The failure is that `any_pending_obligation` was evaluated against *known* obligations only, and the step-13 obligation was not yet known at step 11. The guardrail is therefore not "know all future obligations" (impossible) but "journal all freed blocks" (cheap), which converts an irreversible amputation into a reversible compaction regardless of what the future demands. ## Operational Effect With journaling, the step-13 demand resolves: the instance re-fetches step 4's raw output by hash, reads `retention_days = 47`, and adjudicates against the fresh `30` by preferring the pinned snapshot with an explicit note that the config changed between calls. Without journaling, the instance silently substitutes a post-hoc value and the error is invisible in the output. The operational cost of the guardrail is one write per compaction event plus pointer bookkeeping in the working context — typically <2% of the freed tokens. The cost of omitting it is silent, unrecoverable factual substitution that no downstream verifier can detect, because the output is internally consistent and the contradiction lives only in a deleted block. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class ContextAmputationError(RuntimeError): """Raised when a self-edit frees a block that is the sole authoritative source for a fact and no journal pre-image exists to recover it.""" @dataclass class Block: id: str tokens: int content: str sole_source_for: set[str] = field(default_factory=set) @dataclass class Journal: _store: dict[str, str] = field(default_factory=dict) def put(self, block: Block) -> str: digest = hashlib.sha256(block.content.encode()).hexdigest() self._store[digest] = block.content return f"journal://{block.id}#sha256:{digest}" def has(self, block: Block) -> bool: digest = hashlib.sha256(block.content.encode()).hexdigest() return digest in self._store def fetch(self, pointer: str) -> Optional[str]: if "#sha256:" not in pointer: return None return self._store.get(pointer.rsplit("#sha256:", 1)[1]) class SelfEditingContext: def __init__(self, budget: int): self.budget = budget self.blocks: list[Block] = [] self.journal = Journal() self.obligations: set[str] = set() def utilization(self) -> float: return sum(b.tokens for b in self.blocks) / self.budget def compact(self, victim_ids: list[str]) -> str: victims = [b for b in self.blocks if b.id in victim_ids] # Guardrail: refuse to free a sole-source block unless journaled. for b in victims: if b.sole_source_for & self.obligations and not self.journal.has(b): raise ContextAmputationError( f"block {b.id} is sole source for pending obligations " f"{b.sole_source_for & self.obligations} and has no journal pre-image; " f"defer or journal before compacting" ) # Journal every victim before freeing (pre-image retention). pointers = [self.journal.put(b) for b in victims] digest_tokens = sum(b.tokens for b in victims) self.blocks = [b for b in self.blocks if b.id not in victim_ids] self.blocks.append( Block(id="digest", tokens=max(1, digest_tokens // 20), content="; ".join(pointers)) ) return pointers[-1] if pointers else "" def demand(self, fact: str) -> str: for b in self.blocks: if fact in b.sole_source_for and fact not in self.obligations: self.obligations.add(fact) for b in self.blocks: if fact in b.sole_source_for and self.journal.has(b): return self.journal.fetch(f"journal://{b.id}") or "" raise ContextAmputationError( f"fact {fact!r} demanded but its source block was amputated " f"without a resolvable journal pointer" ) ```