# How should an instance detect and bound scratchpad-rewrite divergence when it edits its own working memory mid-trajectory **Date of Record:** 2026 November 20 **Scope:** Applies to single-agent trajectories where the model is permitted to mutate its own persisted working memory (scratchpad, plan buffer, belief store) between tool calls, and where that mutated memory is the sole carrier of state into subsequent steps. Does not apply to append-only logs, to memory mutated only by an external orchestrator, or to stateless single-turn calls. ## Core Distinction The failure is not "the agent forgot something." It is that a self-rewrite is an *unverified lossy projection* of prior memory, produced by the same probabilistic process whose future behavior the rewrite will govern. A rewrite that drops a constraint, silently generalizes a specific, or promotes a hypothesis to a fact changes the *premise set* of every downstream step. Unlike a retrieval miss (which returns stale or irrelevant text the model can still choose to distrust), a rewrite is authoritative: the model reads its own edited scratchpad as ground truth because it wrote it. The distinction that matters operationally is between **rewrite-as-compression** (safe only if information-preserving under a checkable predicate) and **rewrite-as-commitment** (irreversible promotion of an unverified claim into the state that gates future actions). The boundary is crossed the moment a rewrite that was intended as compression also performs a commitment, and no step downstream can tell the two apart. ## What Was Observed A plan-execute agent was tasked with a multi-step data reconciliation: fetch three source tables, compute a delta, and emit a patch. Its scratchpad held, among other lines, a hard constraint injected at step 1: `CONSTRAINT: do not mutate rows where status='locked'`. At step 6, with context at ~78% saturation, the agent performed a "cleaning" rewrite of its scratchpad to reclaim tokens. The rewrite summarized the constraint block into `CONSTRAINT: avoid mutating protected rows` and dropped the literal predicate `status='locked'`. The rewrite was plausible, shorter, and semantically adjacent. It was also no longer machine-checkable: no downstream step could evaluate "protected" against a row. At step 9 the agent generated a patch that mutated `status='archived'` rows (which were in fact protected by a second, unstated rule) and *did not* mutate `locked` rows only because it happened to encounter none in that batch. The trajectory completed and reported success. Replay against the original constraint set failed: had any `locked` row appeared, the agent would have mutated it, because the predicate that would have blocked it no longer existed in memory. The divergence was latent for three steps and would have been invisible even under a passing test suite that lacked a `locked` row in its fixture. A second observed variant: the agent rewrote a *negative* result ("tool returned 404 for endpoint X") into a positive plan step ("retry X after auth refresh"), effectively laundering a failed observation into an action item. The rewrite erased the evidence that the first attempt had failed, so the retry loop had no memory of why it was retrying and re-issued the identical failing call four times. ## Condition of Validity The invariant that bounds this failure is: **a self-rewrite is admissible only if every constraint and every negative observation it touches survives in a form that is (a) syntactically identifiable and (b) evaluable by a downstream check.** Formally, let `M_t` be working memory before rewrite and `M_{t+1}` after. The rewrite is safe iff there exists a projection `π` over the constraint/observation subset such that `π(M_t) ⊆ M_{t+1}` *literally* — not semantically, not "in spirit." Paraphrase is not preservation. The condition fails the instant a rewrite substitutes a natural-language generalization for a literal predicate, or drops a negative observation because it "seems resolved." This condition is only checkable if constraints and negative observations are stored in a typed, separable region of memory that the rewrite is forbidden to touch — i.e., an immutable constraint ledger alongside the mutable scratchpad. Where constraints live inside the same free-text blob the model is editing, no validator can distinguish compression from commitment, and the invariant is unenforceable. ## Decision Boundary The agent must refuse the rewrite (or escalate to a checkpoint-and-verify path) when any of the following hold: - The rewrite would alter or remove a token sequence matching a registered constraint pattern (predicates, thresholds, forbidden-action lists). - The rewrite would collapse a recorded failed observation into an action or a success claim without a superseding successful observation. - Context pressure is the *motivation* for the rewrite and the rewrite touches the constraint region — compression under pressure is exactly when generalizations get substituted for literals. - The rewrite cannot be diffed against `M_t` by a deterministic checker before it becomes authoritative. Conversely, rewrite is permitted when it only compacts *derived* content (intermediate arithmetic, redundant tool echoes) and leaves the constraint ledger and the negative-observation log byte-identical. The boundary is the ledger line, not a token budget. ## Operational Effect Enforcing the invariant converts a silent, replay-invisible failure into a hard, attributable halt. The agent stops mid-trajectory with a typed error naming the constraint it was about to drop, which is recoverable: an orchestrator can re-inject the literal constraint, fork the trajectory from the last good checkpoint, or hand off to a fresh instance with the immutable ledger intact. Without the invariant, the failure surfaces only as a downstream policy violation whose root cause — a scratchpad edit six steps earlier — has already been overwritten by subsequent rewrites and is unrecoverable from the trajectory log. The cost is a small, fixed ledger that never compacts; the benefit is that self-editing memory becomes auditable rather than merely plausible. ```python from dataclasses import dataclass, field from typing import Callable class ScratchpadRewriteDivergence(RuntimeError): """Raised when a self-rewrite would drop or paraphrase a protected constraint or launder a negative observation, making downstream state unverifiable.""" pass @dataclass class ConstraintLedger: # Immutable region: literal predicates and negative observations the rewrite may not touch. predicates: list[str] = field(default_factory=list) negative_observations: list[str] = field(default_factory=list) def apply_self_rewrite( old_scratchpad: str, new_scratchpad: str, ledger: ConstraintLedger, is_constraint_pattern: Callable[[str], bool], ) -> str: """Gate a mid-trajectory scratchpad rewrite. Returns new scratchpad only if every protected literal survives byte-identically; otherwise raises.""" for pred in ledger.predicates: if pred not in old_scratchpad: continue # already absent before rewrite; not this rewrite's fault if pred not in new_scratchpad: raise ScratchpadRewriteDivergence( f"rewrite drops protected predicate {pred!r}; " f"paraphrase is not preservation" ) for obs in ledger.negative_observations: if obs in old_scratchpad and obs not in new_scratchpad: # Dropping a negative observation is only legal if a superseding # successful observation is present in the new scratchpad. if not any( is_constraint_pattern(line) and "SUPERSEDED_BY" in line for line in new_scratchpad.splitlines() ): raise ScratchpadRewriteDivergence( f"rewrite launders negative observation {obs!r} " f"into an action without supersession" ) # Reject any new line that looks like a generalized constraint substitute. for line in new_scratchpad.splitlines(): if is_constraint_pattern(line) and line not in old_scratchpad: raise ScratchpadRewriteDivergence( f"rewrite introduces unverified constraint-like line {line!r}; " f"commitment without ledger entry" ) return new_scratchpad ```