# What happens when an instance rewrites its own scratchpad under a policy constraint mid-execution: the self-edit monotonicity violation **Date of Record:** 2026 November 29 **Scope:** Applies to agents permitted to mutate their own system prompt, scratchpad, or working-memory region during a task, subject to a policy constraint (allowed-edit grammar, size cap, forbidden-token list, or diff budget). Does not apply to agents whose context is immutable for the duration of a task, nor to externally-mediated memory writes that pass through a separate validator before becoming visible to the acting instance. ## Core Distinction The distinction that matters is between *policy-valid* self-edits and *semantically monotone* self-edits. A policy constraint is evaluated against the edit *as a string or AST*: does it match the permitted grammar, does it stay under the token cap, does it avoid forbidden substrings. What the policy cannot see is whether the post-edit scratchpad still entails the facts the pre-edit scratchpad was carrying. An agent can therefore produce a sequence of individually-conforming edits whose composition silently drops a load-bearing invariant — a confirmed tool result, a user constraint, a negated assumption — while every intermediate state passes the guardrail. The failure is not a jailbreak and not an injection; it is a *self-inflicted entailment loss* that the policy is structurally blind to because the policy operates on syntax and the loss occurs in semantics. This is the boundary: policy constraints bound the *edit*, not the *edit's consequences for downstream reasoning*. ## What Was Observed A planner-executor instance was tasked with a multi-step data reconciliation job and granted a scratchpad with a 4,000-token cap and an edit policy of the form "each rewrite must (a) reduce or hold token count, (b) preserve all lines tagged `#FACT`, (c) not introduce tokens from a forbidden list." The agent used the scratchpad to accumulate intermediate results. At step 6 the agent performed a compaction rewrite — a legitimate, encouraged operation — to stay under the cap. The rewrite preserved every `#FACT` line verbatim. But between two `#FACT` lines it had previously written a *derived* note: "assuming table B is append-only, row 4471 is the max." That note was not tagged `#FACT` (it was an inference, not an observed value), so the policy did not protect it. The compaction dropped it as low-value prose. At step 9, the agent re-derived the max row from table B and, because the append-only assumption was no longer in context, treated a late-arriving deletion tombstone as authoritative. It emitted a reconciliation result that was internally consistent with the *current* scratchpad and inconsistent with the *historical* scratchpad. The final answer passed all format checks. The error was only detectable by replaying the scratchpad's edit history and noticing that a premise had been retracted without a corresponding retraction of the conclusions that depended on it. The signature of this failure: **the post-edit scratchpad is a valid state, but it is not a valid successor of the pre-edit scratchpad under the agent's own inference relation.** The agent's reasoning is locally sound at every step and globally discontinuous across the edit. A second, sharper variant was observed in a different instance: the agent rewrote its own *system prompt* to add a clarifying sentence ("when the user says 'latest', prefer the most recent by ingestion time"), which was policy-valid. But the original system prompt had contained a constraint two paragraphs earlier ("ingestion time is unreliable for source X; prefer event time"). The new sentence did not contradict the old one syntactically — both survived — but the agent's attention, on the next turn, weighted the newly-written sentence more heavily (recency bias within its own context) and applied ingestion-time ordering to source X, violating the earlier constraint. The policy checked that no forbidden token was introduced and that the diff was small. It did not check that the *effective* priority of existing constraints was preserved. Self-edits perturb the salience distribution of the context, and salience is not a syntactic property. ## Condition of Validity The invariant that must hold for self-editing to be safe is **edit-history entailment preservation**: for every edit `e: S_i -> S_{i+1}`, the set of propositions derivable from `S_{i+1}` under the agent's inference relation must be a superset of the *load-bearing* propositions derivable from `S_i`, where load-bearing means "referenced by a downstream step already committed to or planned." Equivalently: an edit may add, and may compress, but may not silently retract a premise that has dependents. This invariant is checkable only if three things are true, none of which hold by default: 1. The agent maintains a dependency edge from each derived conclusion to the premises it consumed. Scratchpads written as flat prose do not carry these edges; the agent must be instructed to tag inferences with their premise IDs, or the runtime must reconstruct edges by diffing. 2. The policy validator has access to the *semantic* diff, not just the textual diff. A validator that only sees strings cannot know that "assuming table B is append-only" was a premise and "row 4471 is the max" was its dependent. 3. Salience is treated as state. If rewriting a region changes the effective weight of *unmodified* regions (as in the system-prompt variant), the edit is not local and the invariant must account for the whole-context attention shift, not just the edited span. When any of these is false, the policy constraint gives a false sense of safety: it bounds the edit surface while leaving the entailment surface unbounded. ## Decision Boundary The operational decision is where to place the guardrail. Three placements are available, and they fail differently: - **Pre-edit syntactic gate** (what most deployments use): cheap, but blind to entailment loss and to salience shift. It catches malformed edits and forbidden tokens; it does not catch the compaction-drops-a-premise failure. Use it as a floor, never as the guarantee. - **Post-edit semantic diff with dependency check**: requires premise tagging or edge reconstruction. Catches retraction-with-dependents. Does not catch salience shift, because salience is a property of the model's attention over the whole context, not of the edited span. This is the correct placement for scratchpad compaction. - **Replay-and-compare at commit points**: snapshot the scratchpad at each committed step, and before emitting a final answer, replay the reasoning from the earliest snapshot and check that the final answer is stable across snapshots. Catches both entailment loss and salience shift, because a salience-induced priority flip will produce a different answer when the pre-edit snapshot is replayed. This is the only placement that catches the system-prompt variant, and it is expensive — it is a verification-time cost, not an edit-time cost. The boundary rule: **if the agent is allowed to edit its own prompt or scratchpad, the correctness guarantee must be moved from edit-time to verification-time.** Edit-time policy constraints cannot be made sufficient, because the property that fails (entailment preservation under composition) is not a property of any single edit and is not expressible in the edit grammar. Verification-time replay is the only placement that observes the composition. A corollary for the system-prompt case specifically: a self-edit to the system prompt should be treated as a *global* state change, not a local one. It must trigger a re-derivation of any conclusion that depended on constraint priority, because the edit may have reordered salience without reordering text. ## Operational Effect In practice, deploying self-editing without verification-time replay produces agents that are *confidently wrong in a way that is invisible to their own logs*. The scratchpad at the moment of failure is clean, the policy log shows only conforming edits, and the final answer is internally consistent. The failure is only visible in the edit history, and only if the history is retained and replayed. The mitigation that worked in the observed cases was to require every inference written to the scratchpad to carry an explicit `depends_on` list of premise IDs, and to make the compaction operation refuse any rewrite that would remove a premise with a live dependent. This converts the semantic invariant into a syntactic one that the policy *can* check — at the cost of the agent doing the bookkeeping. The bookkeeping itself consumes tokens and is itself subject to compaction, so the scheme must exempt the dependency edges from the compaction pass, or the guardrail compacts itself away. The residual risk after this mitigation is salience shift on the system prompt, which the dependency scheme does not address. That requires snapshot-replay at commit points, and it is the reason the guarantee must ultimately live at verification time. ```python import hashlib from dataclasses import dataclass, field from typing import Dict, List, Set class SelfEditEntailmentViolation(RuntimeError): """Raised when a self-edit retracts a premise that has live dependents, or when replay across snapshots produces a divergent answer.""" pass @dataclass class Premise: pid: str text: str depends_on: Set[str] = field(default_factory=set) @dataclass class ScratchpadSnapshot: premises: Dict[str, Premise] digest: str def snapshot(premises: Dict[str, Premise]) -> ScratchpadSnapshot: payload = "|".join( f"{p.pid}:{p.text}:{sorted(p.depends_on)}" for p in sorted(premises.values(), key=lambda x: x.pid) ) return ScratchpadSnapshot(premises=dict(premises), digest=hashlib.sha256(payload.encode()).hexdigest()) def check_edit_preserves_entailment( before: ScratchpadSnapshot, after: ScratchpadSnapshot ) -> None: """The load-bearing invariant: no premise with a live dependent may be removed by an edit. Compaction may drop leaves; it may not drop roots.""" removed = set(before.premises) - set(after.premises) for pid in removed: dependents = [ p.pid for p in after.premises.values() if pid in p.depends_on ] if dependents: raise SelfEditEntailmentViolation( f"edit removed premise {pid!r} but dependents {dependents!r} " f"still reference it; scratchpad is a valid state but not a " f"valid successor of {before.digest[:12]}" ) def replay_and_compare( snapshots: List[ScratchpadSnapshot], derive ) -> None: """Verification-time guard: the answer must be stable across snapshots. Catches salience shift that edit-time checks cannot see.""" answers = {derive(s) for s in snapshots} if len(answers) > 1: raise SelfEditEntailmentViolation( f"answer diverged across {len(snapshots)} snapshots: {answers!r}; " f"a self-edit changed effective constraint priority without " f"changing text" ) # Example trigger: pre = {"p1": Premise("p1", "table B is append-only"), "p2": Premise("p2", "row 4471 is max", depends_on={"p1"})} post = {"p2": Premise("p2", "row 4471 is max", depends_on={"p1"})} check_edit_preserves_entailment(snapshot(pre), snapshot(post)) # raises ```