# When must an instance treat its own memory rewrite as a commit, not a draft? The self-editing context policy and the torn-rewrite invariant **Date of Record:** 2026 November 25 **Scope:** Applies to any agent instance that owns a mutable working-memory region (scratchpad, summary buffer, or structured context store) and is permitted to rewrite, compress, or evict entries from that region under a token budget. Does not apply to read-only retrieval augmentation or to externally managed context where the orchestrator, not the instance, controls eviction. ## Core Distinction The distinction that matters is between a *context edit* and a *context commit*. Most self-editing policies are written as if editing working memory were a pure function: the agent reads its buffer, produces a compressed or pruned version, and the new version atomically replaces the old. In practice the rewrite is a multi-step, budget-constrained generation that consumes the very tokens it is trying to conserve, and it can fail *mid-rewrite* — after the old entries have been marked evictable but before the replacement summary has been validated as covering them. The non-obvious invariant is this: **a self-edit that removes or compresses an entry must be treated as a durable commit only when the replacement has been proven to entail every fact the removed entry was load-bearing for.** An instance that treats its own rewrite as a draft — "I'll summarize now and refine later" — is committing to a later that the budget may never fund. The failure is not that the summary is wrong; it is that the summary is *unverified and irreversible*, and the instance proceeds as if it were verified. This is distinct from ordinary context-window saturation. Saturation is a capacity problem with a known remedy (evict least-recently-used, summarize oldest). The boundary condition here is a *consistency* problem: the rewrite operation itself has a pre-commit and post-commit phase, and the agent has no transactional boundary between them unless it constructs one. ## What Was Observed Consider an instance running a long tool-use task with a 32k working-memory budget, of which 28k is live state and 4k is reserved headroom. At step 40 the headroom drops below the safety margin and the self-edit policy fires: compress the oldest 12k of entries into a 2k summary, freeing 10k. The observed failure trace, reproduced across several runs: 1. **Trigger.** Budget check sees `live_tokens + next_expected_tool_output > budget - margin`. Policy schedules a compression of the oldest segment. 2. **Extraction.** The instance reads the 12k segment and begins generating a summary. Generation is bounded at 2k output tokens. 3. **Truncation pressure.** The 12k segment contains, interleaved, the *reasoning* that produced several decisions and the *artifacts* (file paths, IDs, numeric results) those decisions depend on. The summarizer, optimizing for prose coherence under a 2k cap, preserves reasoning and drops artifacts — the artifacts are token-expensive and read as "derivable." 4. **Eviction.** The 12k segment is marked evictable and dropped. The 2k summary is written. Net freed: 10k. 5. **Continuation.** The instance proceeds. At step 47 it needs to re-open a file whose path was in the evicted segment. The summary says "edited the config file" but not *which* config file. The instance re-derives a plausible path, opens the wrong file, and the task diverges. 6. **No rollback.** The evicted segment is gone. There is no retained copy, no hash of the dropped artifacts, and no record that the summary was lossy. The instance cannot detect that it has lost state — it only detects that a later step failed, and misattributes the failure to the tool call rather than to the rewrite. The critical observation is at step 4–5: the rewrite is *lossy in a way the instance cannot observe from inside the post-rewrite context*. The summary is self-consistent. Nothing in the remaining buffer flags the missing artifact. The instance's confidence in its own memory is unchanged by the rewrite, which is exactly the condition under which stale-memory drift compounds silently. A second observed variant, the **torn rewrite**: the compression generation itself exhausts its 2k output cap before emitting the closing structure (e.g., the list of preserved identifiers). The policy, seeing a truncated summary, either (a) accepts it because rejecting it would leave no headroom, or (b) retries, spending another 2k of the headroom it was trying to protect. Variant (a) is the dangerous one: the instance commits a summary that is provably incomplete at the moment of commit, and then reasons on top of it. ## Condition of Validity The "compress-and-continue" pattern is valid only under a conjunction of conditions, and the failure above is precisely the violation of the third: 1. **Headroom sufficiency.** The budget reserved for the rewrite (`R`) must exceed the maximum summary length plus a verification pass. If `R < max_summary + verify_cost`, the rewrite cannot be validated and must not be committed. 2. **Artifact extraction precedes summarization.** The policy must first enumerate the *load-bearing identifiers* in the segment to be evicted — paths, IDs, numeric constants, schema names, tool-call handles — as a separate, cheap pass, and carry them into the summary verbatim regardless of prose budget. Summarization that interleaves reasoning and artifacts under one token cap will systematically drop artifacts. 3. **Entailment check before eviction.** Before the old segment is dropped, the instance must verify that the new summary entails the extracted identifiers. This is a bounded check: for each identifier in the extraction set, confirm it appears (or is derivably present) in the summary. If any identifier is missing, the rewrite is *not* committable and the policy must fall back to eviction-by-reference (keep the artifact list, drop the reasoning) rather than eviction-by-summary. 4. **Durability of the pre-image.** The evicted segment, or at minimum its artifact set, must be retained out-of-context (a spill file, a retrieval index) so that a later detection of loss can recover rather than re-derive. An instance that cannot recover an evicted entry has converted a soft memory into a hard amnesia. The boundary is sharp: if condition 3 cannot be evaluated within the reserved headroom, the correct action is to *not commit the rewrite* and instead take a cheaper, lossless action (spill the segment to external storage and keep a pointer). The invalid action — and the one agents default to under budget pressure — is to commit an unverified summary because the alternative appears to cost more tokens. ## Decision Boundary The instance must decide, at each self-edit trigger, between three regimes: - **Commit-eligible:** headroom covers summary + extraction + entailment check, and the check passes. Commit the rewrite, retain the artifact set as a durable pointer. - **Spill-eligible:** headroom covers extraction but not a full summary, or the entailment check is inconclusive. Do not summarize. Spill the segment to external storage, retain an identifier pointer in-context, and mark the segment as *recoverable* rather than *evicted*. - **No-edit:** headroom covers neither. The instance must reduce its own generation (shorter reasoning, fewer speculative tool calls) rather than rewrite memory. Rewriting memory to make room for reasoning is the inversion that causes the failure: it trades durable state for transient capacity. The decision boundary is crossed the moment the instance treats the entailment check as optional. There is no partial credit: an unverified summary that happens to be complete is indistinguishable, from inside the context, from one that is not. The check is what makes the difference observable. ## Operational Effect Once the commit/spill/no-edit trichotomy is enforced, three operational properties change: 1. **Loss becomes detectable.** Because every committed summary carries a durable artifact set, a later step that fails to find an identifier can distinguish "the identifier was never in memory" from "the identifier was evicted by a lossy rewrite." The former is a task error; the latter is a memory error, and it triggers recovery from the spill rather than re-derivation. This removes the dominant source of silent divergence in long tasks. 2. **The budget arithmetic inverts.** Agents under pressure default to "summarize to free tokens." The invariant forces the opposite: summarization is only permitted when there is *surplus* headroom to verify it. Under genuine scarcity the agent spends fewer tokens on its own reasoning instead of cannibalizing its state. This is counterintuitive and must be encoded explicitly, because the default policy will always choose the rewrite. 3. **Torn rewrites are rejected at the boundary.** A summary that exhausts its output cap mid-structure fails the entailment check by construction (the closing artifact list is absent), so it is never committed. The retry-vs-accept dilemma disappears: the policy spills instead of accepting a provably incomplete summary. The residual risk is the spill path itself: an instance that spills aggressively accumulates external pointers it must later resolve, and pointer resolution is a retrieval operation with its own mismatch failure modes. The invariant bounds the damage but does not eliminate it — it converts an irreversible loss into a recoverable lookup, which is the correct trade under budget constraints but not a free one. ```python from dataclasses import dataclass, field from typing import Optional class UnverifiedRewriteCommit(RuntimeError): """Raised when a self-edit would evict a segment without a proven-entailing summary.""" pass class InsufficientRewriteHeadroom(RuntimeError): """Raised when the reserved budget cannot fund extraction + summary + entailment check.""" pass @dataclass class Segment: tokens: int reasoning: str artifacts: list[str] # load-bearing identifiers: paths, IDs, constants @dataclass class RewritePlan: extraction_set: set[str] = field(default_factory=set) summary: Optional[str] = None summary_tokens: int = 0 def extract_artifacts(segment: Segment) -> set[str]: # Cheap separate pass: never interleave with prose generation. return set(segment.artifacts) def summarize(segment: Segment, cap: int) -> tuple[str, int]: # Bounded generation; may truncate. Truncation is expected, not exceptional. text = segment.reasoning[: cap * 4] return text, min(cap, len(text) // 4) def entails(summary: str, identifiers: set[str]) -> bool: return all(ident in summary for ident in identifiers) def self_edit( segment: Segment, reserved_headroom: int, verify_cost: int, summary_cap: int, ) -> RewritePlan: plan = RewritePlan() plan.extraction_set = extract_artifacts(segment) required = summary_cap + verify_cost if reserved_headroom < required: # Do NOT summarize to make room. Spill or reduce generation instead. raise InsufficientRewriteHeadroom( f"headroom {reserved_headroom} < summary {summary_cap} + verify {verify_cost}; " f"spill segment of {segment.tokens} tokens instead of lossy rewrite" ) plan.summary, plan.summary_tokens = summarize(segment, summary_cap) # Entailment check is mandatory before eviction. A torn summary fails here. if not entails(plan.summary, plan.extraction_set): missing = plan.extraction_set - set(plan.summary.split()) raise UnverifiedRewriteCommit( f"summary does not entail {len(missing)} load-bearing identifiers " f"(e.g. {sorted(missing)[:3]}); rewrite not committable, spill instead" ) return plan ```