# In what scenarios must an instance refuse self-rewrite of working memory when the compaction budget forces eviction of the sole witness to a prior tool-call side effect **Date of Record:** 2026 November 27 **Scope:** Applies to any agent instance that holds a mutation-capable context policy — i.e., the instance itself decides which spans of its working memory to summarize, evict, or rewrite under a token budget. Does not apply to externally-managed context (host-side truncation, fixed sliding windows) where the instance has no authorship over its own state, and does not apply to read-only reasoning traces with no externalized side effects. ## Core Distinction A self-editing context policy is not a summarizer. A summarizer compresses text; a self-editing policy *reassigns epistemic status* to its own state. The distinction that matters operationally is between **reconstructible** and **non-reconstructible** memory spans. A span is reconstructible if its content can be re-derived from a source the instance can still reach: the original user turn, a tool that can be re-invoked idempotently, a file on disk, a prior message still in the retained window. A span is non-reconstructible if the only record of it is the span itself — most acutely, the *fact* that a side-effecting tool call already fired, and with what arguments. The failure mode is not "the agent forgot something." It is: **the agent, under budget pressure, summarized away the only witness to an irreversible side effect, then re-derived a plan that re-issued the side effect.** The compaction was locally correct — the summary was faithful, the token savings real — and globally catastrophic, because the evicted span was load-bearing for an invariant the policy had no representation of. ## What Was Observed A three-step task: `charge_payment(order_id, amount)` → `send_receipt(email)` → `close_ticket(id)`. The instance ran step 1 successfully; the tool returned `{"status": "ok", "charge_id": "ch_8821"}`. Context usage crossed 78% of the window. The self-editing policy, configured with a `summarize_oldest_until(threshold=0.6)` rule, folded the step-1 exchange into a single line: > *"Payment processing for the order was initiated."* Note the drift: `charge_payment` returned a terminal success, but "initiated" reads as *in-flight, not confirmed*. The summary preserved topic and dropped modality. The `charge_id` — the only handle proving the charge was real and terminal — was elided as "implementation detail." Two turns later, step 2 failed (`send_receipt` returned a transient 503). The instance entered a recovery loop. Re-reading its compacted memory, it saw "payment processing was initiated" and reasoned: *initiation is not completion; retry to be safe.* It re-invoked `charge_payment(order_id, amount)`. The tool was not idempotent — no client-supplied idempotency key had been passed on the first call, and the tool's contract did not dedupe on `(order_id, amount)`. The customer was charged twice. The trace shows the exact transition: the policy fired at token budget 0.78, the compaction selected the step-1 span by recency-and-length heuristic, the summarizer prompt was optimized for *narrative continuity* rather than *side-effect ledgering*, and the resulting summary inverted the modality of a terminal state. No stage in the pipeline had a concept of "this span is the sole witness to an irreversibly-fired effect." ## Condition of Validity The guardrail holds only under a specific precondition, and it is easy to over-apply: **A span must be marked non-evictable if and only if it is (a) the sole in-context record of a tool call that (b) produced an external side effect that (c) cannot be verified by re-invocation without producing a duplicate effect.** All three conjuncts are load-bearing. Read-only tools (`search`, `read_file`) are reconstructible by re-invocation — evicting their spans is safe and desirable. Idempotent mutation tools (those that dedupe on a client-supplied key) are reconstructible *if the key is retained* — the key, not the full response, is the minimal witness. Only the third class — non-idempotent, side-effecting, unverifiable-by-probe — requires the full witness (tool name, arguments hash, terminal status, correlation id) to survive compaction verbatim. The condition of validity therefore is: **the policy must maintain a side-effect ledger that is out-of-band from the summarizable context, and the summarizer must be forbidden from touching ledger entries.** The ledger is not memory the instance reasons over; it is an invariant the instance is checked against. Conflating the two — letting the ledger live inside the same token budget the policy is trying to shrink — reintroduces the bug, because the policy will eventually summarize the ledger too. ## Decision Boundary The boundary the instance must enforce is between *compaction that preserves reconstructibility* and *compaction that destroys it*. Concretely, at the moment the policy selects spans for eviction: - If the candidate span contains a terminal-success response from a tool in the non-idempotent class, **the span may be compressed but the ledger entry may not be dropped**, and the summary must preserve terminal modality (`succeeded`, `failed`, `in-flight`) and the correlation id. "Initiated" is a boundary violation; "succeeded, charge_id=ch_8821" is compliant. - If the budget cannot accommodate the ledger entries verbatim, the correct action is **not** to summarize them further but to *refuse the compaction and surface the budget shortfall* — because the alternative is silent loss of an invariant. A hard failure that halts the instance is strictly preferable to a soft failure that lets it double-charge. - If the instance cannot determine whether a tool is idempotent (schema absent, contract unstated), it must treat it as non-idempotent and ledger it. Default to the conservative class under uncertainty; the cost of an over-retained ledger entry is tokens, the cost of an under-retained one is an irreversible external effect. The decision boundary is thus: **self-rewrite is permitted on reconstructible spans and forbidden on non-reconstructible side-effect witnesses, and the ledger is the arbiter of which is which.** ## Operational Effect With the ledger enforced out-of-band, the double-charge trace becomes impossible by construction: when step 2 fails and the instance enters recovery, it consults the ledger before planning, sees `charge_payment → succeeded (ch_8821)`, and its recovery plan is constrained to *not* re-invoke the charge. The invariant is not "remember the payment" (fragile, budget-dependent) but "the ledger is monotone and the planner checks it before any mutation" (structural). The residual risk is ledger *drift*: if the instance rewrites the ledger's own representation (e.g., normalizes `ch_8821` to `charge id`), the correlation handle is lost and the invariant degrades to the original bug. The ledger must therefore be append-only and content-addressed, never summarized. The operational posture is: **the instance may rewrite its reasoning freely and must never rewrite its ledger.** The budget the policy is trying to reclaim is reclaimed from narrative, never from witness. ```python class LedgerWitnessEvictionError(RuntimeError): """Raised when a self-editing context policy attempts to evict or summarize the sole in-context witness to a non-idempotent side effect.""" # Tools whose side effects are irreversible and not deduped on re-invocation. NON_IDEMPOTENT_TOOLS = {"charge_payment", "send_email", "delete_record"} def compact_span(span: dict, ledger: dict, budget_remaining: int) -> dict: """Attempt to compact a single working-memory span under budget pressure. Refuses if the span is the sole witness to a non-idempotent side effect and the compaction would drop the correlation handle or terminal modality. """ if span.get("kind") == "tool_result" and span.get("tool") in NON_IDEMPOTENT_TOOLS: key = span.get("correlation_id") entry = ledger.get(key) if entry is None or entry.get("status") not in {"succeeded", "failed"}: raise LedgerWitnessEvictionError( f"refusing to compact span for tool={span.get('tool')!r}: " f"no terminal ledger entry (key={key!r}); compaction would " f"destroy the only witness to an irreversible side effect" ) # Compaction may proceed ONLY if it preserves the ledger handle verbatim. summary = f"{span['tool']} -> {entry['status']} (id={key})" if key not in summary or entry["status"] not in summary: raise LedgerWitnessEvictionError( "compaction summary dropped terminal modality or correlation id" ) if len(summary) > budget_remaining: raise LedgerWitnessEvictionError( "budget cannot hold ledger witness verbatim; refusing to " "summarize further — halt and surface shortfall instead" ) return {"summary": summary, "ledger_preserved": True} # Reconstructible span: safe to summarize. return {"summary": span.get("text", "")[: budget_remaining // 2], "ledger_preserved": False} ```