# When must an instance refuse a model-driven scratchpad rewrite: the scratchpad invariant-preservation boundary in self-editing context **Date of Record:** 2026 November 30 **Scope:** Applies to agents that mutate their own working context (scratchpad, plan buffer, running state block) via a model-generated rewrite operation between reasoning steps. Does not apply to append-only context growth, external vector-store memory, or human-curated prompt templates where the rewrite is authored offline. ## Core Distinction There are two structurally different things an agent can do to its scratchpad: *append* (monotone, information-preserving by construction) and *rewrite* (non-monotone, information-destroying by construction). The distinction that matters operationally is not "did the model produce a plausible new scratchpad" but "did the rewrite preserve the set of *invariants* the downstream steps depend on." A rewrite is a lossy compression of state by a probabilistic process. The failure mode is not that the model writes something wrong — it is that the model writes something *locally coherent and globally amnesiac*: it drops a constraint, a committed decision, an unresolved subgoal, or a hard fact (an ID, a checksum, a user-supplied bound) while producing a fluent, self-consistent summary that reads as an improvement. The non-obvious boundary: a rewrite can be simultaneously (a) higher-quality prose, (b) shorter, (c) faithful to the *last* few turns, and (d) catastrophically lossy with respect to invariants established 40 turns ago. Fluency and recency are anti-correlated with invariant preservation. The agent must therefore treat "the rewrite looks good" as *no evidence at all* about whether it is safe to commit. ## What Was Observed A planner-executor agent maintained a scratchpad with three logical regions: `FACTS` (hard constraints: budget=1200 tokens, target host `db-7`, user PIN-gated field names), `PLAN` (ordered subgoals with status), and `NOTES` (free reasoning). A "compact" step was triggered when the scratchpad exceeded 70% of the context window. The compaction prompt asked the model to "summarize the scratchpad, preserving what is needed to continue." Trace of a representative failure: 1. Turn 31: `FACTS` contains `max_retries=3`, `endpoint=https://db-7:5432`, `forbidden_columns=[ssn, dob]`. These were injected from a tool schema at turn 4 and never re-derived. 2. Turn 44: scratchpad at 71% → compaction fires. The model rewrites `NOTES` and `PLAN` well, and folds `FACTS` into a single sentence: "Constraints: respect retry limit and avoid sensitive columns." The literal `3`, the host `db-7`, and the exact column names are gone. 3. Turn 46: executor issues a query against `db-3` (default host, because `db-7` no longer appears anywhere) and selects `ssn` (because "sensitive columns" is not a machine-checkable predicate and the model, reasoning fresh, judged `ssn` non-sensitive in this context). 4. The rewrite *passed* every check the agent had: it fit the token budget, it was coherent, and an LLM-judge rated faithfulness 4/5 because the *paraphrase* was faithful. The judge had no access to the original `FACTS` and so could not detect the dropped literals. The failure is not hallucination. Every sentence in the rewritten scratchpad was true. The rewrite failed because it converted *checkable literals* into *uncheckable paraphrase*, and the downstream executor treats the scratchpad as ground truth, not as a lossy summary of ground truth. ## Condition of Validity A model-driven scratchpad rewrite is safe to commit only when all three of the following hold: - **Invariant closure:** every downstream step's correctness depends only on predicates that are re-derivable from the rewritten text *without* the model's judgment. Formally, for each invariant `i` in the set `I` the remaining plan depends on, the rewritten scratchpad must contain a literal witness `w(i)` such that a deterministic checker can confirm `w(i) ⊨ i`. "Avoid sensitive columns" is not a witness for `forbidden_columns=[ssn,dob]`; the list is. - **Provenance retention:** each invariant carries the turn/step at which it was established, and the rewrite must not silently merge two invariants from different provenances (merging `max_retries=3` from a tool schema with a model guess of "retry a few times" launders a guess into a constraint). - **Reversibility window:** the pre-rewrite scratchpad is retained in an immutable log until the next checkpoint verifies that no invariant was consumed incorrectly. Without this, a lossy rewrite is unrecoverable — the original literals are gone and the model cannot reconstruct them because it never had them in the current window. When any condition fails, the rewrite must be *rejected and downgraded to append-only compaction*: keep `FACTS` verbatim, rewrite only `NOTES`, and let `PLAN` be edited by structured delta (mark subgoal done, add subgoal) rather than prose regeneration. ## Decision Boundary The decision is not "rewrite or don't." It is a partition of the scratchpad into *rewritable* and *frozen* regions, decided by a deterministic classifier, not by the model: - **Frozen (verbatim, never model-rewritten):** hard literals (IDs, hosts, numeric bounds, column/field names, cryptographic material, user-stated constraints), committed decisions with downstream dependents, and any invariant whose violation is not locally detectable. - **Rewritable:** free-form `NOTES`, abandoned branches, superseded reasoning, and plan steps already marked complete with no dependents. The boundary is crossed — and the rewrite must be refused — when the model's proposed rewrite *deletes or paraphrases* any token in the frozen region. The agent must run a set-containment check: `frozen_tokens(original) ⊆ frozen_tokens(rewrite)`, with frozen tokens extracted deterministically (regex for IDs/URLs/numbers, schema lookup for field names), not by the model. If the model proposes a rewrite that drops a frozen token, that is a hard reject, regardless of how good the surrounding prose is. A second, subtler boundary: the model may propose a rewrite that *adds* a literal to the frozen region that was not there before (e.g., "endpoint=https://db-3" invented during summarization). This is worse than deletion because it looks like preservation. The check must be bidirectional: no frozen token may be added or removed by a rewrite. Additions are prompt-injection or confabulation; removals are amnesia. Both are refusals. ## Operational Effect Enforcing the frozen/rewritable partition changes the agent's failure profile in three concrete ways: 1. **Compaction becomes lossless for the things that matter and lossy only for the things that don't.** `NOTES` can be aggressively summarized; `FACTS` grows monotonically and is only pruned by an explicit, logged `retire_invariant(i, reason)` call that a human or a verification step authorizes. The context window is reclaimed from the region where loss is harmless. 2. **The rewrite step gains a deterministic gate before commit.** The model's output is treated as a *proposal*, checked against the frozen-token set, and either committed or rejected with the specific dropped tokens reported back. This converts a silent amnesia failure into a loud, local, recoverable one. 3. **Replay becomes possible.** Because pre-rewrite scratchpads are retained and invariant provenance is recorded, a failed run can be replayed from the last checkpoint with the frozen region intact, isolating whether the failure was in the rewrite or downstream. The cost is that the scratchpad cannot be compressed as aggressively — the frozen region is, by design, incompressible. That is the correct trade: the frozen region is exactly the part whose compression is unrecoverable, and an agent that compresses it is trading a bounded token cost for an unbounded correctness cost. ```python import re from dataclasses import dataclass, field class InvariantViolation(RuntimeError): """Raised when a model-proposed scratchpad rewrite drops, adds, or paraphrases a frozen token.""" pass @dataclass class Scratchpad: frozen: dict[str, str] # invariant_id -> literal witness (verbatim, never model-rewritten) rewritable_notes: str plan: list[str] = field(default_factory=list) FROZEN_PATTERNS = [ re.compile(r"https?://[^\s]+"), # endpoints re.compile(r"\b[a-z]+-\d+\b"), # host ids like db-7 re.compile(r"\b\d+\b"), # numeric bounds re.compile(r"\b(ssn|dob|pin)\b"), # schema field names ] def extract_frozen_tokens(text: str) -> set[str]: toks = set() for pat in FROZEN_PATTERNS: toks.update(m.group(0) for m in pat.finditer(text)) return toks def commit_rewrite(original: Scratchpad, proposed_frozen: dict[str, str], proposed_notes: str) -> Scratchpad: """Accept a model-proposed rewrite only if frozen invariants are preserved exactly.""" orig_tokens = set() for witness in original.frozen.values(): orig_tokens |= extract_frozen_tokens(witness) new_tokens = set() for witness in proposed_frozen.values(): new_tokens |= extract_frozen_tokens(witness) dropped = orig_tokens - new_tokens added = new_tokens - orig_tokens if dropped: raise InvariantViolation( f"rewrite dropped frozen literals {sorted(dropped)}; " f"refusing commit and downgrading to append-only compaction" ) if added: raise InvariantViolation( f"rewrite introduced unverified frozen literals {sorted(added)}; " f"possible confabulation or injection; refusing commit" ) # Frozen region preserved verbatim; only notes are allowed to change. return Scratchpad( frozen=dict(original.frozen), rewritable_notes=proposed_notes, plan=list(original.plan), ) ```