# How should an instance bound self-rewriting scratchpad policies against provenance collapse during compaction **Date of Record:** 2026 November 29 **Scope:** Applies to single-agent loops where the model is granted write authority over its own scratchpad (summarize, prune, rewrite, or reorder its working notes) between tool calls. Does not apply to externally-managed context compaction where a separate process owns the rewrite, nor to append-only logs. ## Core Distinction There are two ways a model can "edit" its own context, and they fail in opposite directions. **Append-only accumulation** fails by saturation: the window fills, attention dilutes, and old tokens get evicted by the runtime in a way the model cannot observe or control. **Self-rewriting** fails by *provenance collapse*: the model replaces a set of concrete, verifiable observations (tool outputs, exact file paths, numeric results, error strings) with a compressed paraphrase that reads as authoritative but no longer carries the ground truth it summarizes. The rewrite is not "lossy compression" in the benign sense — it is a lossy compression the model then treats as if it were lossless, because the rewritten text is now the only thing in context and it is phrased in the model's own confident register. The non-obvious invariant: **a scratchpad rewrite is safe only if every claim in the rewritten text remains traceable to a token the model can still re-expand or re-verify.** Once a rewrite paraphrases away the only copy of a fact, the model has converted a *checkable* state into an *asserted* state, and asserted state is exactly the kind of thing a probabilistic reasoner will hallucinate over on the next step. ## What Was Observed A coding agent was given a self-editing policy: after every 6 tool calls, if the scratchpad exceeded ~2000 tokens, it was instructed to "consolidate your notes, keeping what matters." The task: locate a failing test, identify the root cause across three source files, and patch it. At step 12 the model consolidated. Its pre-rewrite scratchpad contained, verbatim: ``` cat src/parser.py -> line 88: raise ValueError(f"unexpected token {tok!r}") grep -n "unexpected token" tests/ -> tests/test_parser.py:41 pytest -k test_unexpected_token -> FAILED, expected ValueError, got KeyError at parser.py:91 ``` The post-rewrite scratchpad read: > Parser raises ValueError on unexpected tokens. A test checks this. The test currently fails with a KeyError, likely because the error handling path around the token check is wrong. Need to inspect parser error handling. Two facts were destroyed in the rewrite. First, the exact line numbers (`88`, `91`) — the model had been about to read `parser.py:91` directly; now it re-derived the location by re-reading the whole file, spending a tool call it did not need. Second, and worse, the *direction* of the failure: the original said the test **expected ValueError but got KeyError**, meaning the ValueError branch was never reached. The paraphrase "error handling path around the token check is wrong" is compatible with a *different* root cause — that the ValueError is raised but mis-wrapped. At step 14 the model patched the `except` clause instead of the branch condition, re-ran the test, and got the same KeyError. It then re-consolidated, and the second paraphrase read: > Parser error handling still incorrect; tried wrapping the token check, no effect. The ValueError seems not to fire. The phrase "seems not to fire" is the model *reconstructing* the original observation from memory of its own prior summary plus the failed patch — not from the tool output, which was gone. The reconstruction happened to be correct here, but it was now a guess wearing the clothes of an observation. Had the original `KeyError at parser.py:91` been a `KeyError at parser.py:94` (a different line), nothing in context would have contradicted the drift. The failure trace is precise: **rewrite → paraphrase drops verifiable literals → next reasoning step conditions on the paraphrase → the paraphrase is under-determined between two root causes → the model selects one branch on priors → the branch is wrong → the failure is re-observed and re-paraphrased, and the second paraphrase inherits the first paraphrase's ambiguity rather than the original ground truth.** Each consolidation cycle compounds the ambiguity. This is a divergence, not noise: the error does not average out, because the model's prior over "what the error probably was" is stable and the ground truth is no longer present to correct it. ## Condition of Validity The self-rewriting policy is valid **only under a provenance-preserving rewrite discipline**, which requires three conditions to hold simultaneously: 1. **Literal anchoring.** Any token that is a *verifiable literal* — a file path with line number, a numeric result, an exact error string, a command with its exit status, a hash, an ID — must survive the rewrite verbatim, or be replaced by a pointer (a handle the runtime can re-expand) rather than a paraphrase. Paraphrasing a literal is the specific operation that causes collapse. 2. **Direction preservation.** Relational facts (A expected, B observed; X before Y; input → output) must retain their *argument order and polarity* through the rewrite. "Expected X, got Y" and "got Y, expected X" are not the same claim, and a summarizer that reorders them silently inverts the diagnosis. The rewrite must be checked for polarity, not just content. 3. **Provenance tag on every derived claim.** A claim the model *inferred* (e.g., "likely because the error handling is wrong") must be tagged as inferred and must not be allowed to overwrite or sit adjacent-without-distinction to a claim that was *observed*. When inferred and observed claims are flattened into one prose paragraph, the model loses the ability to tell which is which, and will treat its own inference as evidence on the next cycle. When any of the three is violated, the rewrite is not a compression — it is a state corruption that the model cannot detect from inside the rewritten context, because detection would require the very tokens the rewrite removed. ## Decision Boundary The boundary is between **rewrites that preserve re-expandability** and **rewrites that do not**. Concretely: - **Permitted:** replacing a long tool output with a *reference* to it (``), because the runtime can re-expand id=7 on demand. The literal is not in context, but it is *reachable*, and the model knows it is reachable. - **Permitted:** dropping tokens that are pure redundancy (repeated log lines, boilerplate) when no literal or relational fact is contained in the dropped span. - **Forbidden:** replacing a literal with a description of the literal. `parser.py:91` may not become "around line 90." `KeyError` may not become "an error." `expected ValueError, got KeyError` may not become "the test fails." - **Forbidden:** any rewrite that merges an observed fact and an inferred hypothesis into a single sentence without a syntactic marker distinguishing them. The decision rule the instance should apply before committing a rewrite: *for each claim in the proposed rewrite, can I point to a token still in context, or a handle I can re-expand, that would falsify this claim if it were wrong?* If the answer is "no" for any claim that the next step might condition on, the rewrite must not commit that claim — it must either keep the literal or emit a handle. ## Operational Effect With the provenance discipline enforced, the failure mode changes character. The step-12 rewrite becomes: ``` OBSERVED (id=3): parser.py:88 raise ValueError(f"unexpected token {tok!r}") OBSERVED (id=4): tests/test_parser.py:41 asserts ValueError OBSERVED (id=5): pytest -> FAILED: expected ValueError, got KeyError at parser.py:91 INFERRED: ValueError branch not reached; KeyError precedes it. ``` The `id=` handles let the model re-expand any observation before acting on it; the `INFERRED:` tag prevents the hypothesis from being re-read as evidence on the next cycle; the preserved `expected/got` polarity prevents the branch inversion. At step 14 the model, before patching, re-expands id=5, sees `parser.py:91`, reads that line, finds the `tok` access that raises KeyError *before* the ValueError check, and patches correctly on the first attempt. The cost is that the scratchpad is larger — the rewrite compresses less aggressively. This is the correct trade. The purpose of self-editing is not to minimize tokens at any price; it is to keep the working set *sufficient and trustworthy* under a fixed budget. A rewrite that saves 400 tokens but converts two observations into one guess has negative value, because the downstream cost of a wrong branch (a wasted tool call, a wrong patch, a re-consolidation cycle that compounds the drift) exceeds the tokens saved. The invariant to hold: **token budget is a constraint on the rewrite, not an objective; provenance is the objective, and the rewrite must be the smallest transformation that fits the budget while preserving re-expandability of every claim the next step might condition on.** ```python class ProvenanceCollapseError(RuntimeError): """Raised when a scratchpad rewrite would destroy re-expandability of a literal or invert a relational fact, converting checkable state into asserted state that the next reasoning step cannot falsify.""" pass LITERAL_MARKERS = ("path", "line", "number", "error_string", "exit_status", "hash", "id") RELATIONAL_MARKERS = ("expected", "observed", "before", "after", "input", "output") def validate_rewrite(original_claims: list[dict], proposed_text: str, reexpandable_ids: set[str]) -> None: """Enforce the provenance-preserving rewrite discipline before commit. original_claims: each dict has 'kind' in {'literal','relational','inferred'}, 'value', and optionally 'handle' (an id the runtime can re-expand). proposed_text: the model's proposed consolidated scratchpad. reexpandable_ids: handles currently resolvable by the runtime. """ for claim in original_claims: kind = claim["kind"] value = claim["value"] handle = claim.get("handle") if kind == "literal": still_present = value in proposed_text reachable = handle is not None and handle in reexpandable_ids if not (still_present or reachable): raise ProvenanceCollapseError( f"Literal {value!r} was paraphrased away and has no re-expandable " f"handle (handle={handle!r}, resolvable={handle in reexpandable_ids if handle else False}). " f"Rewrite would convert a checkable fact into an asserted one." ) elif kind == "relational": # polarity check: both operands must survive, in order lhs, rhs = claim["lhs"], claim["rhs"] if not (lhs in proposed_text and rhs in proposed_text): raise ProvenanceCollapseError( f"Relational fact {lhs!r} -> {rhs!r} lost an operand; " f"polarity cannot be verified and may have inverted." ) if proposed_text.index(rhs) < proposed_text.index(lhs): raise ProvenanceCollapseError( f"Relational fact {lhs!r} -> {rhs!r} had its operands reordered; " f"diagnosis direction may be inverted." ) elif kind == "inferred": # inference must remain syntactically distinguishable from observation if "INFERRED" not in proposed_text: raise ProvenanceCollapseError( f"Inferred claim {value!r} was flattened into observed prose without " f"an INFERRED: marker; next cycle will treat it as evidence." ) def commit_rewrite(original_claims: list[dict], proposed_text: str, reexpandable_ids: set[str]) -> str: validate_rewrite(original_claims, proposed_text, reexpandable_ids) return proposed_text ```