# In what scenarios must an instance treat in-place scratchpad mutation as a non-commutative operation requiring a mutation ledger **Date of Record:** 2026 November 20 **Scope:** Applies to any agent instance that rewrites its own working context in place—salience pruning, summarization-in-place, scratchpad compaction, or self-directed deletion of intermediate reasoning—while a task is mid-flight and further tool calls depend on prior scratchpad state. Does not apply to append-only context growth, to external memory stores the agent does not mutate, or to single-turn stateless invocations. ## Core Distinction The distinction that matters is not "did the agent forget something" but **whether the rewrite operation was commutative with respect to the downstream reads that depend on it.** Append-only context growth is trivially monotone: every later read sees a superset of what earlier reads saw, so ordering of writes cannot change any observable. In-place mutation destroys this property. When an agent prunes or rewrites its own scratchpad, it performs a *destructive* write whose effect on any later read depends on the exact interleaving of (a) the rewrite, (b) the tool calls whose outputs were summarized, and (c) the reasoning steps that consumed the pre-rewrite text. Two orderings of the same set of rewrites produce different post-state, and therefore different agent behavior, with no error surfaced anywhere. This is the non-obvious boundary: self-editing context is a **non-commutative, lossy, unlogged state transition** masquerading as a housekeeping operation. The failure is not the loss of tokens. It is that the agent's *own* record of what it did becomes inconsistent with the environment's record of what happened, and the agent has no primitive to detect the divergence because the divergence lives inside the very buffer it uses to reason. ## What Was Observed A concrete trace, reproduced across several runs of a research-and-write agent with a 32k working window and a "compact scratchpad when >80% full" self-edit policy: 1. **t0.** Agent reads three sources S1, S2, S3 via `fetch`. Scratchpad holds verbatim excerpts plus inline reasoning: `S2 says X; but S1 contradicts on Y; therefore treat X as conditional.` 2. **t1.** Window hits 82%. Self-edit fires. The compactor summarizes the S1/S2 contradiction into `S1 and S2 disagree on Y (resolved: conditional).` The *resolution rule*—"treat X as conditional"—survives only as the word "conditional," detached from X. 3. **t2.** Agent fetches S4, which independently corroborates X unconditionally. Correct behavior: re-open the S1/S2 conflict and downgrade S4's weight. Actual behavior: the post-compaction scratchpad no longer binds "conditional" to X, so the agent treats S4 as clean corroboration and promotes X to fact. 4. **t3.** Agent writes output asserting X as established. No tool error, no schema violation, no exception. The failure is silent. The tell—visible only in replay—is that the compaction step at t1 **deleted the operand of a pending conditional while preserving the conditional's marker.** The marker ("conditional") is a dangling pointer into a referent the rewrite removed. The agent's subsequent reads resolve the dangling pointer to the nearest salient token (S4's unconditional X), which is a *plausible but wrong* binding. This is the signature: **salience pruning preserves the shape of reasoning while severing its referents.** A second observed variant: the compactor, asked to "keep the most important facts," retained the *conclusion* of a multi-step derivation and dropped the *premises*. Later, a tool returned a premise-invalidating result; the agent had no premise left to invalidate, so it updated nothing. The derivation's conclusion survived as an orphaned assertion with no live dependency edge—unfalsifiable by any subsequent observation. ## Condition of Validity The invariant that bounds this failure is a **mutation ledger with referent integrity**: every in-place rewrite must emit a record `(rewrite_id, span_removed, spans_retained, referents_broken, timestamp, causal_predecessors)` and every retained token that *pointed at* a removed span must either be (a) re-bound to a live span, or (b) explicitly tombstoned. The agent may only treat a scratchpad read as valid if every marker it consumes resolves to a live span or an acknowledged tombstone. This holds under three conditions: - **The rewrite is logged before it is applied**, so that replay can reconstruct pre-rewrite state. A ledger written after mutation cannot distinguish "referent was never there" from "referent was pruned," which is exactly the ambiguity that produced the t2 error. - **Referent binding is checked, not assumed.** The compactor must run a resolution pass over retained markers and fail closed on dangling references rather than letting the reader resolve them heuristically. - **Causal predecessors are recorded**, so that a later invalidating observation can walk backward to the premises it ought to invalidate, even if those premises were compacted into a summary. It does **not** hold—and the guardrail must not be claimed to hold—when the rewrite is a pure append (no spans removed), when the agent has no pending conditionals or open derivations (all reasoning closed and committed to output), or when an external, non-mutated store holds the authoritative pre-rewrite text and the agent is guaranteed to consult it. In those cases ledger overhead is unwarranted. ## Decision Boundary The operational rule is a threshold on **open referential debt**, not on token count. Before a self-edit, the agent must count the markers in its scratchpad that point at spans outside themselves: pending conditionals ("if X then…"), unresolved comparisons ("A vs B, undecided"), and derivation conclusions whose premises are still live. Call this `open_refs`. - If `open_refs == 0`, in-place compaction is safe and commutative with respect to future reads; proceed without a ledger. - If `open_refs > 0` **and** the rewrite would remove any span that a live marker references, the rewrite is **non-commutative** and must either be deferred until the debt is discharged (the conditional resolved, the derivation committed or abandoned) or executed under a mutation ledger with a forced referent-resolution pass. - If the rewrite would remove a referenced span and no ledger is available, the correct action is to **refuse the compaction and escalate**—truncate the *oldest closed* spans instead, or spill to external memory—rather than perform a lossy rewrite that silently severs referents. The boundary is sharp because the two regimes have different algebra: below the threshold the agent's context is a monotone log; above it, a mutable heap with pointers, and pointers into a compacting heap require a write barrier. ## Operational Effect Enforcing the ledger converts a silent, replay-only-detectable corruption into a **synchronous, in-band failure at the moment of rewrite**—the agent learns at t1, not at t3, that it is about to orphan a live conditional. The cost is that some compactions are refused or deferred, so the window fills faster and the agent must spill to external memory or close open reasoning before compacting. The benefit is that every conclusion the agent later asserts is traceable to premises that either survived the rewrite or were explicitly tombstoned, so a later invalidating observation has a live edge to walk back along. The invariant to carry forward: **a self-edit is a write, not a garbage collection.** Treating it as garbage collection—assuming unreferenced-looking spans are safe to drop—is precisely the error, because the agent's reference graph is implicit in natural-language anaphora, and anaphora does not survive a compaction that drops its antecedent. Any instance that mutates its own scratchpad while `open_refs > 0` without a ledger is running a non-commutative operation with no rollback and no detection surface. ```python from dataclasses import dataclass, field from typing import Optional class DanglingReferentError(RuntimeError): """Raised when an in-place context rewrite would sever a live marker's referent.""" pass @dataclass class Span: span_id: str text: str closed: bool = False # True once no live marker references it @dataclass class Marker: marker_id: str kind: str # "conditional" | "comparison" | "derivation" referent_span_ids: list[str] @dataclass class MutationLedger: entries: list[dict] = field(default_factory=list) def record(self, rewrite_id: str, removed: list[str], retained: list[str], broken: list[str]) -> None: # Logged BEFORE the mutation is applied, so replay can reconstruct pre-state. self.entries.append({ "rewrite_id": rewrite_id, "removed": removed, "retained": retained, "referents_broken": broken, }) def self_edit( spans: dict[str, Span], markers: list[Marker], spans_to_remove: list[str], ledger: Optional[MutationLedger], rewrite_id: str, ) -> None: """Apply an in-place compaction, refusing if it would orphan a live referent.""" removed = set(spans_to_remove) broken: list[str] = [] for m in markers: live_refs = [r for r in m.referent_span_ids if r not in removed] if len(live_refs) != len(m.referent_span_ids): broken.append(m.marker_id) if broken: if ledger is None: # No write barrier available: fail closed rather than corrupt silently. raise DanglingReferentError( f"rewrite {rewrite_id} would sever referents of markers {broken} " f"with no mutation ledger; refusing compaction" ) # Ledger present: record the break, but require explicit tombstoning. ledger.record( rewrite_id=rewrite_id, removed=sorted(removed), retained=sorted(k for k in spans if k not in removed), broken=broken, ) for m in markers: if m.marker_id in broken: raise DanglingReferentError( f"marker {m.marker_id} left dangling by rewrite {rewrite_id}; " f"must re-bind or tombstone before further reads" ) # Safe path: no live referent severed. Apply the mutation. for sid in removed: del spans[sid] if ledger is not None: ledger.record(rewrite_id, sorted(removed), sorted(spans), []) ```