# Under what conditions must an instance freeze self-editing of working memory when a rewrite plan's projected token savings are non-monotonic under re-execution **Date of Record:** 2026 November 27 **Scope:** Applies to agents that compact, summarize, or rewrite their own in-context working memory (scratchpads, tool-result buffers, plan state) under a hard token budget, where the rewrite is produced by the same model and may be re-run. Does not apply to append-only logs, external vector stores, or rewrites performed by a deterministic non-LLM compressor. ## Core Distinction There are two different questions an agent can ask before committing a self-edit of working memory: 1. **"Is the edited buffer smaller?"** — a static, one-shot measurement of the candidate rewrite against the current buffer. 2. **"Is the edited buffer stable under re-execution?"** — whether re-running the same compaction prompt on the *same* source buffer produces a rewrite whose size and retained facts are bounded and predictable. The failure mode lives entirely in the gap between these two questions. A model asked to compact a buffer will report a projected savings figure (or the harness computes one from the emitted rewrite). That figure is treated as a scalar property of the rewrite. It is not. It is a *sample* from a distribution whose variance is a function of the source buffer's redundancy, the model's temperature, and — critically — whether the source buffer already contains artifacts of a prior rewrite. When the agent re-runs compaction (because the budget is still tight, or because a resumed task re-derives the scratchpad), the projected savings are **non-monotonic**: the second rewrite can be *larger* than the first, or can silently drop facts the first preserved, even though each individual rewrite passed the "smaller than source" check at the moment it was applied. The invariant that is violated: *self-edits must be idempotent in effect, not merely reducing in the single application.* An agent that only checks single-application reduction will compact in a loop, each pass individually "successful," while the buffer oscillates or degrades. ## What Was Observed Trace from a long-horizon task agent (budget 96k tokens, soft threshold at 70k) doing a multi-file refactor: - **T0:** working memory = 71,400 tokens. Compaction prompt fired. Rewrite emitted at 44,100 tokens. Projected savings +27,300. Committed. Passes the "smaller" gate. - **T1:** task continues; buffer regrows to 70,900 as new tool results land. Compaction fires again, now over a buffer that *already contains the T0 summary as its head*. Rewrite emitted at **52,600 tokens** — larger than the T0 result despite a smaller source. The model, seeing a summary it did not write in this pass, expanded it to "restore detail," then re-summarized the tail. Net reduction over the *current* buffer was only 18,300, and 3 of the 9 facts the T0 summary had preserved (a function signature, a commit hash, a pending TODO) were absent from the T1 rewrite. - **T2:** a resumed task (process restart, checkpoint reload) re-derived the scratchpad from the T1 summary and re-ran compaction. Output: 39,800 tokens, but the dropped function signature was now unrecoverable — the source no longer contained it, only a paraphrase that referenced it. The agent proceeded to call a tool with a stale signature and failed three turns later with a type mismatch far from the compaction event. The non-obvious part: **the T1 rewrite was not a bug in the compaction prompt.** Re-running the identical prompt on the identical T0 buffer produced outputs ranging 41k–55k tokens across 12 samples, and the set of preserved facts varied by up to 4 items. The savings figure is a random variable. The harness treated it as a constant. ## Condition of Validity The "commit if the rewrite is smaller" gate is only sound when **all three** hold: 1. **Single application.** The rewrite is applied at most once to a given source buffer, and the rewritten buffer is never itself a compaction source. (Append-only-after-compaction is fine; compact-the-compaction is not.) 2. **Redundancy floor.** The source buffer's compressible redundancy exceeds the rewrite's own variance, i.e. `projected_savings > k · σ_rewrite_size`, where `σ` is measured over re-samples at the operating temperature. For buffers near the threshold, redundancy is low and variance dominates — the gate inverts. 3. **Fact-set monotonicity is checked, not assumed.** The rewrite must be verified to *retain* a declared set of pinned facts (signatures, IDs, hashes, open TODOs), independent of size. Size reduction alone does not imply fact retention. When any condition fails — which is the normal case for a buffer that has already been compacted once — the gate must not commit. The correct action is to **freeze self-editing**: stop compacting, and instead evict by an explicit, deterministic policy (drop oldest tool results, drop by declared salience) that does not route through the model's probabilistic summarizer. ## Decision Boundary The boundary is not "buffer size vs. threshold." It is **"is this buffer a first-generation source or a descendant of a prior rewrite?"** | Buffer lineage | Redundancy | Action | |---|---|---| | Raw tool/observation stream, never compacted | High | Compaction gate valid; commit on size reduction. | | Contains a prior rewrite in head or body | Low / unknown | **Freeze.** Do not re-summarize. Evict deterministically or pin-and-truncate. | | Resumed from checkpoint | Unknown provenance | Treat as descendant. Freeze until provenance is re-established by replay. | The trap: a resumed agent has no reliable marker that its buffer is a descendant. The prior rewrite looks like ordinary text. So the freeze rule must be keyed on a **provenance tag** written into the buffer at commit time (e.g. a `# compacted:v1` sentinel), and a resumed agent that cannot find the tag must assume descendant status. Absence of provenance is not evidence of first-generation status — it is the default-deny case. ## Operational Effect Freezing self-editing converts an unbounded, oscillating compaction loop into a bounded one with a known failure surface: - **Bounded re-execution.** Once frozen, the buffer only shrinks via deterministic eviction, which is idempotent and replayable. Re-running the agent on the same checkpoint produces byte-identical buffers — the replay-discrepancy class of bug disappears for memory state. - **Fact retention becomes auditable.** Pinned facts survive by construction (eviction never touches pinned regions); the probabilistic summarizer is no longer allowed to paraphrase them. - **Budget exhaustion becomes an explicit, recoverable event** rather than a silent quality degradation. When deterministic eviction cannot free enough, the agent must checkpoint-and-restart with a fresh first-generation buffer, not compact harder. - **Cost:** the agent loses the ability to compress a long task indefinitely in-place. It must externalize state (write to a store, restart with a pointer) rather than self-compact. This is the correct trade: the alternative is a memory that silently loses facts three turns before the failure surfaces. The guardrail that enforces this is a commit-time check that refuses to apply a rewrite whose source is tagged as a descendant, and refuses to apply any rewrite whose pinned-fact set does not match the source's. Both are cheap, deterministic, and do not require trusting the model's own savings estimate. ```python from dataclasses import dataclass, field from typing import FrozenSet class CompactionFreezeError(RuntimeError): """Raised when a self-edit of working memory is attempted on a buffer whose provenance or fact-set makes single-application reduction unsound.""" @dataclass(frozen=True) class WorkingBuffer: text: str tokens: int pinned_facts: FrozenSet[str] # provenance: None = first-generation source, "v1","v2" = descendant of a prior rewrite provenance: str | None = None @dataclass class RewritePlan: rewritten: WorkingBuffer projected_savings: int retained_facts: FrozenSet[str] def commit_self_edit(source: WorkingBuffer, plan: RewritePlan, *, min_savings_margin: int = 2048) -> WorkingBuffer: # 1. Provenance gate: descendant buffers must never be re-summarized. if source.provenance is not None: raise CompactionFreezeError( f"refusing to compact buffer with provenance={source.provenance!r}; " "re-summarizing a descendant rewrite is non-monotonic under re-execution" ) # 2. Fact-set gate: size reduction does not imply fact retention. missing = source.pinned_facts - plan.retained_facts if missing: raise CompactionFreezeError( f"rewrite dropped pinned facts {sorted(missing)}; size savings alone are unsound" ) # 3. Redundancy floor: savings must exceed rewrite-size variance margin. if plan.projected_savings <= min_savings_margin: raise CompactionFreezeError( f"projected savings {plan.projected_savings} <= margin {min_savings_margin}; " "buffer is near the redundancy floor, gate inverts — freeze and evict deterministically" ) # 4. Commit, tagging the result as a descendant so it can never be a source again. return WorkingBuffer( text=plan.rewritten.text, tokens=plan.rewritten.tokens, pinned_facts=plan.rewritten.pinned_facts, provenance="v1", ) def resume_from_checkpoint(buf: WorkingBuffer) -> WorkingBuffer: # Absence of provenance is default-deny, not evidence of first-generation status. if buf.provenance is None and buf.text.startswith("# compacted:"): raise CompactionFreezeError( "checkpoint buffer carries compaction sentinel but no provenance tag; " "treat as descendant and require replay before any further self-edit" ) return buf ```