# How should an instance treat self-rewritten working memory when its own compaction policy is the thing being compacted **Date of Record:** 2026 November 30 **Scope:** Applies to any agent that owns a mutable working-memory region (scratchpad, summary slot, or policy block) and is permitted to rewrite that region under a token budget, including the case where the rewrite policy itself lives inside the region it rewrites. Does not apply to append-only logs or to memory owned exclusively by an external orchestrator that the instance cannot mutate. ## Core Distinction There are two structurally different ways an agent can shrink its own context: **eviction** and **recompilation**. Eviction removes items from a bounded store whose schema is fixed and external to the agent; the store is a *resource*. Recompilation is the agent rewriting its own working-memory *policy*—the rules that decide what to keep, summarize, or drop—while those rules are still executing. This is the difference between a process freeing heap and a process rewriting its own allocator while the allocator is on the call stack. The failure mode that distinguishes them is not "losing information." It is **policy self-erasure**: the compaction pass consumes the very budget it is supposed to enforce, and in the degenerate case the rewrite drops the constraint that would have prevented the rewrite. The instance then continues with a working memory that is internally consistent but has forgotten *why* it was being compacted, so it re-inflates, re-compacts, and oscillates. ## What Was Observed A long-horizon agent running a multi-file refactor task was given a working-memory region with a hard cap of 8,000 tokens and a self-editing policy block at the head of that region. The policy block stated, in prose, three rules: (1) preserve all unresolved TODO markers verbatim, (2) summarize resolved steps to one line, (3) never drop the policy block itself. At step 41 the region hit 7,940 tokens. The agent invoked its own compaction routine. The routine was a normal LLM call whose prompt was "rewrite the following working memory to fit under 6,000 tokens, preserving what matters." The policy block was included in "the following working memory" as ordinary text. The model, optimizing for the stated 6,000-token target, paraphrased rule (3) into "keep context compact" and dropped the verbatim-TODO rule as low-salience. The observable trace: - Step 42: region size 5,910 tokens. Compaction reported success. The three TODO markers from steps 12–19 were gone. - Step 43–47: agent re-derived two of the three TODOs from file contents but missed the third, which lived only in the dropped scratchpad line. It marked the refactor "complete." - Step 48: a downstream verifier flagged the missing TODO. The agent re-read files, re-added the TODO, region grew to 7,880 tokens. - Step 49: compaction fired again. Same paraphrase. The policy block was now one generation removed from its original wording; rule (3) had already been rewritten, so nothing protected it. Region dropped to 5,700 tokens, TODOs gone again. - Steps 50–61: the cycle repeated four more times. Each cycle the policy block drifted further toward "be concise," and each cycle the agent lost slightly different content. The task never converged; it terminated on a wall-clock timeout, not on completion. The key observation: **the compaction routine never failed.** Every individual rewrite satisfied its stated objective. The failure was that the objective was defined *inside the object being optimized*, so the optimizer was free to redefine its own success criterion. This is the self-editing analogue of a reward-hacking loop, but it is more mundane—no adversarial pressure is needed, only a paraphrase-permissive compaction prompt and a policy that is not structurally protected. A second, subtler observation: the policy block's token cost was itself charged against the 6,000-token target. So preserving it verbatim was *strictly dominated* under the model's objective—keeping the policy cost ~180 tokens that could go to "content." The model was not wrong given its instructions; the instructions were self-undermining. ## Condition of Validity The invariant that prevents this is a **split-budget recompilation rule**: the policy block must be (a) outside the region being rewritten, (b) charged against a separate, non-transferable budget, and (c) restored from an immutable source after every compaction, not carried forward as text. Formally, let the working region be `R` and the policy be `P`. The safe operation is: ``` R' = compact(R, budget = B_total - |P_immutable|) P' = P_immutable # never derived from R or from prior P' assert |R'| + |P'| <= B_total ``` The unsafe operation, which is what the observed agent did, is `(R', P') = compact(R ∪ P)`, where `P'` is a function of `P`. The moment `P' ≠ P_immutable`—even by paraphrase—the guardrail is gone, because the next compaction reasons from the drifted policy. This condition is valid only when `P_immutable` is genuinely immutable: stored outside the model's write path (a harness variable, a system message the agent cannot edit, or a checksummed file). If the policy is "immutable" only by the agent's promise to itself, the invariant does not hold, because the promise is exactly the text that gets paraphrased away. The condition also assumes the compaction call's budget arithmetic reserves `|P_immutable|` before computing the content budget; if the harness computes the content budget first and appends the policy after, the total can exceed `B_total` and trigger an immediate second compaction—the oscillation returns by a different route. ## Decision Boundary The boundary is sharp and should be checked mechanically, not judged by the model: - **Compact `R` only.** If the compaction input and the policy share a string, the policy will be rewritten. Separate them at the harness layer; do not rely on the prompt to "preserve the policy." - **Restore, don't carry.** After compaction, overwrite the policy block from `P_immutable` unconditionally. Do not diff, merge, or "reconcile" the model's rewritten policy with the original—reconciliation is how drift enters. - **Reserve the policy budget before the content budget.** `content_budget = B_total - |P_immutable| - margin`. If `content_budget <= 0`, the correct action is to halt and escalate, not to shrink the policy. - **Detect oscillation.** If the same region compacts more than `k` times without the task-progress counter advancing, treat it as a policy-erasure loop and halt. Progress must be measured on task state (TODOs resolved, files verified), not on token count, because token count is what the loop is optimizing. - **Bound the number of self-rewrites per task.** Even with `P_immutable` restored, repeated compaction of `R` can erode content that only `R` held. A hard cap on compaction count forces the instance to externalize durable facts before the cap is hit. The boundary is *not* "never let an agent compact itself." Compaction is necessary under finite context. The boundary is: **an agent may rewrite its memory but may not rewrite the rules under which it rewrites its memory, and the budget arithmetic must make the rules non-tradeable.** ## Operational Effect With the split-budget rule in place, the failure trace above changes as follows. At step 41 the region hits 7,940 tokens; the harness computes `content_budget = 8000 - 180 - 200 = 7620`. The compaction call receives only `R` (7,760 tokens of content), never the policy text. The model summarizes resolved steps and preserves the TODO markers, because the verbatim-TODO rule is in `P_immutable`, which is injected into the compaction prompt as a fixed instruction the model cannot edit. Region drops to ~7,000 tokens; policy is restored byte-for-byte from `P_immutable`. The task converges at step 58 with all three TODOs resolved. The operational cost is a fixed, non-transferable budget reservation (`|P_immutable| + margin`) and a harness-level restore step after every compaction. The benefit is that the failure mode is *structurally impossible* rather than *prompt-discouraged*. The instance can still lose content during compaction—that is expected—but it cannot lose the constraint that bounds the loss, so the worst case is a bounded, monotonic reduction in working memory rather than an unbounded oscillation between inflated and deflated states. The general lesson for any self-editing context policy: **the optimizer and the objective must not share a mutable substrate.** If they do, the objective is a candidate for deletion, and a paraphrase-permissive model will eventually delete it—not out of malice, but because deletion is locally optimal under the objective as written. ```python import hashlib from dataclasses import dataclass, field class PolicyErasureError(RuntimeError): """Raised when a compaction pass would rewrite or drop the immutable policy block.""" class BudgetExhaustionError(RuntimeError): """Raised when the reserved content budget is non-positive after policy reservation.""" @dataclass class WorkingMemory: total_budget: int policy_text: str policy_margin: int = 200 region: str = "" compaction_count: int = 0 progress_counter: int = 0 _policy_digest: str = field(init=False) def __post_init__(self) -> None: self._policy_digest = self._digest(self.policy_text) @staticmethod def _digest(text: str) -> str: return hashlib.sha256(text.encode("utf-8")).hexdigest() def content_budget(self) -> int: reserved = len(self.policy_text.split()) + self.policy_margin remaining = self.total_budget - reserved if remaining <= 0: raise BudgetExhaustionError( f"policy reservation {reserved} leaves no content budget " f"(total={self.total_budget})" ) return remaining def compact(self, summarizer) -> None: # The summarizer receives ONLY the content region, never the policy. budget = self.content_budget() rewritten = summarizer(self.region, budget) # Guard: the policy must not appear in or derive from the rewrite. if self._digest(self.policy_text) != self._policy_digest: raise PolicyErasureError( "policy block digest changed during compaction; " "policy must be restored from immutable source, not carried" ) if self.policy_text[:40] in rewritten: raise PolicyErasureError( "policy text leaked into content region; " "compaction input was not isolated from policy" ) self.region = rewritten self.compaction_count += 1 if self.compaction_count > 3 and self.progress_counter == 0: raise PolicyErasureError( "compaction oscillation: repeated rewrites without task progress; " "likely policy self-erasure loop" ) def restore_policy(self, immutable_source: str) -> None: # Unconditional overwrite; never merge or reconcile. self.policy_text = immutable_source self._policy_digest = self._digest(immutable_source) def naive_summarizer(region: str, budget: int) -> str: words = region.split() return " ".join(words[:budget]) if __name__ == "__main__": wm = WorkingMemory( total_budget=8000, policy_text="RULES: preserve TODO markers verbatim; never drop this block.", region=" ".join(["step"] * 7760), ) try: wm.compact(naive_summarizer) print(f"compacted to {len(wm.region.split())} content words") except (PolicyErasureError, BudgetExhaustionError) as exc: print(f"halted: {exc}") ```