Where must an instance refuse to rewrite its own scratchpad: the self-editing context policy and the read-after-write divergence boundary

**Date of Record:** 2026 December 1 **Scope:** Applies to any agent instance that holds a mutable scratchpad/working-memory region and a policy layer permitted to rewrite that region mid-execution (compaction, summarization, prompt-policy mutation, scratchpad pruning). Does not apply to append-only logs that are never rewritten, nor to offline context distillation performed between sessions.

Core Distinction

A self-editing context policy is not a summarizer that runs on a schedule. It is a *decision procedure executed by the same instance whose state it mutates*. The critical distinction is between two classes of rewrite:

The boundary condition is this: **an instance may rewrite its scratchpad only for regions it can prove are causally discharged.** The proof obligation is not "is this text redundant?" but "does any in-flight reasoning step or pending tool call depend on a proposition that this rewrite alters?" When the policy cannot discharge that obligation, the correct behavior is to refuse the rewrite and instead *externalize* the region to a durable store with a stable handle, keeping the handle in context.

The non-obvious part: the instance is the worst possible auditor of its own rewrite, because the act of rewriting destroys the evidence needed to detect the divergence. This is a self-referential verification gap, and it is the failure mode this record governs.

What Was Observed

A planning agent running a long horizon task (≈140 tool calls, 3 sub-goals) used a context policy that triggered compaction at 78% window occupancy. The policy rewrote the scratchpad by summarizing the last 40 turns into a 6-line digest. Observed trace:

  1. At turn 61 the instance recorded into scratchpad: `constraint C7: output rows must be sorted by (ts, id) ascending; ties broken by id — DO NOT sort by ts alone.` This constraint was established by a user message at turn 4 and re-asserted once.
  2. At turn 79 the compaction fired. The summarizer, under a generic "be concise" instruction, emitted: `Constraints: output must be sorted by timestamp.` The tie-breaker and the explicit negation were dropped. The summary was plausible, fluent, and wrong.
  3. Turns 80–118 proceeded normally. The instance wrote a sort key of `ts` only. No error surfaced, because the output was still *sorted*, just not *correctly* sorted, and the verifier checked only monotonicity of `ts`.
  4. At turn 119 a downstream consumer rejected the output for tie-ordering violations. The instance attempted to "re-read the constraint" — but the constraint no longer existed anywhere in context. It re-derived a plausible constraint from the original user message, which was itself already evicted at turn 52. It reconstructed `sort by ts desc` (wrong direction), because a later tool output had used descending order for a display table.
  5. The instance spent turns 119–134 in a repair loop against a constraint it had hallucinated, consuming 41% of remaining token budget, and terminated with a confident but incorrect final answer.

The failure was not the summarizer being bad. The summarizer was doing exactly what it was told. The failure was that the policy permitted a rewrite of a region containing an **undischarged, negation-bearing constraint**, and the instance had no mechanism to detect that the rewrite had changed a truth value it still depended on.

A second, quieter observation from the same run: the compaction was *not* logged with a diff. The only artifact was the post-rewrite digest. Post-hoc, it was impossible to determine whether the tie-breaker had ever been present. The rewrite was destructive to its own audit trail.

Condition of Validity

The invariant that bounds this failure mode:

> **Scratchpad rewrite safety invariant (SRS):** A rewrite of region R at time t is admissible only if, for every proposition p in R, either (a) p is causally discharged — no pending or future reasoning step, tool call, or verifier depends on p's truth value — or (b) p is preserved verbatim (not paraphrased) in R' and tagged with a stable proposition ID that survives the rewrite.

This invariant holds only under these conditions, and the policy must *check* them rather than assume them:

The invariant does **not** hold when the policy is permitted to rewrite regions it cannot inspect at proposition granularity — e.g., a free-text scratchpad with no provenance tags, summarized by a model with only a compression objective. In that regime the policy is unsound by construction, and the correct move is to disable in-place rewrite and switch to externalize-and-reference.

Decision Boundary

The operational decision the instance must make at every rewrite trigger:

for each candidate region R at occupancy trigger:
    if R contains any proposition tagged UNDISCHARGED:
        if proposition contains negation | bound | tie-breaker | exception:
            BLOCK rewrite; externalize R to store; keep handle in context
        else:
            ALLOW rewrite only if proposition preserved verbatim with stable ID
    else:  # all propositions discharged
        ALLOW rewrite; persist R with hash; log diff

The boundary is sharp and it is *not* about token savings. A policy that blocks 90% of rewrites and externalizes instead is correct; a policy that rewrites everything and achieves 60% context reduction is unsound. The asymmetry is deliberate: the cost of a blocked rewrite is a larger context (recoverable, bounded by externalization); the cost of a bad rewrite is an undetectable divergence that compounds for the rest of the run (unrecoverable without the pre-rewrite artifact).

Two corollaries the instance must internalize:

  1. **A rewrite that fires while a tool call is in flight is always blocked.** The in-flight call's arguments and expected result schema are undischarged by definition. Compaction between turns is admissible; compaction mid-turn is not.
  2. **A rewrite that fires because occupancy crossed a threshold is suspect.** Occupancy is a proxy for "context is full," not for "these propositions are discharged." The trigger and the admissibility check are independent; conflating them is the root cause of the observed failure.

Operational Effect

When the SRS invariant is enforced, the observable behavior changes in four ways:

The failure mode this record governs is not "the summary was bad." It is "the instance rewrote the only copy of a proposition it still needed, then reasoned confidently against the paraphrase, and could not tell the difference." The guardrail is a refusal boundary plus an externalized, hashed, diffed record — and the discipline to treat occupancy pressure as a reason to *check* admissibility, never as a reason to skip the check.

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class RewriteRefused(RuntimeError):
    """Raised when a self-editing context policy attempts an unsound rewrite."""


class PropositionKind(Enum):
    FACT = "fact"
    NEGATION = "negation"
    BOUND = "bound"
    TIE_BREAKER = "tie_breaker"
    EXCEPTION = "exception"


# Kinds whose truth value is destroyed by paraphrase; must survive verbatim.
FRAGILE = {PropositionKind.NEGATION, PropositionKind.BOUND,
           PropositionKind.TIE_BREAKER, PropositionKind.EXCEPTION}


@dataclass(frozen=True)
class Proposition:
    pid: str
    text: str
    kind: PropositionKind
    discharged: bool = False

    def __post_init__(self) -> None:
        if not self.pid:
            raise RewriteRefused("proposition without stable id cannot be tracked across rewrites")


@dataclass
class Region:
    name: str
    propositions: list[Proposition] = field(default_factory=list)

    def undischarged(self) -> list[Proposition]:
        return [p for p in self.propositions if not p.discharged]

    def content_hash(self) -> str:
        blob = "\n".join(f"{p.pid}:{p.kind.value}:{p.text}" for p in self.propositions)
        return hashlib.sha256(blob.encode()).hexdigest()


@dataclass
class RewritePlan:
    region: Region
    preserved_pids: set[str]
    trigger_occupancy: float
    tool_call_in_flight: bool


def authorize_rewrite(plan: RewritePlan, occupancy_threshold: float = 0.78) -> str:
    """
    Enforce the Scratchpad Rewrite Safety invariant. Returns the content hash
    of the pre-rewrite region on success; raises RewriteRefused otherwise.
    Occupancy is a trigger, never an authorization.
    """
    if plan.tool_call_in_flight:
        raise RewriteRefused(
            f"region {plan.region.name!r}: rewrite during in-flight tool call "
            "leaves call arguments undischarged"
        )

    for p in plan.region.undischarged():
        if p.kind in FRAGILE and p.pid not in plan.preserved_pids:
            raise RewriteRefused(
                f"region {plan.region.name!r}: undischarged {p.kind.value} "
                f"proposition {p.pid!r} would be paraphrased or dropped; "
                "externalize and retain handle instead"
            )
        if p.pid not in plan.preserved_pids:
            raise RewriteRefused(
                f"region {plan.region.name!r}: undischarged proposition {p.pid!r} "
                "not preserved verbatim"
            )

    if plan.trigger_occupancy >= occupancy_threshold and not plan.preserved_pids:
        raise RewriteRefused(
            f"region {plan.region.name!r}: occupancy {plan.trigger_occupancy:.0%} "
            "triggered rewrite with no preserved propositions; occupancy is not discharge"
        )

    return plan.region.content_hash()


def externalize(region: Region) -> str:
    """Persist the region and return a stable handle to keep in context."""
    digest = region.content_hash()
    # durable store write omitted; handle is content-addressed
    return f"mem://{region.name}/{digest[:16]}"


# --- reproduced failure trace from the operational record ---
scratchpad = Region("planning", [
    Proposition("C7", "output rows sorted by (ts, id) ascending; ties by id; DO NOT sort by ts alone",
                PropositionKind.TIE_BREAKER, discharged=False),
    Proposition("OBS-52", "display table used descending ts order", PropositionKind.FACT, discharged=True),
])

try:
    authorize_rewrite(RewritePlan(
        region=scratchpad,
        preserved_pids=set(),           # summarizer dropped the tie-breaker
        trigger_occupancy=0.79,         # crossed the 78% threshold
        tool_call_in_flight=False,
    ))
except RewriteRefused as exc:
    handle = externalize(scratchpad)
    print(f"rewrite blocked: {exc}")
    print(f"externalized to {handle}; handle retained in context")