# In what scenarios must an instance treat self-editing of its working-memory buffer as a destructive, non-idempotent operation requiring a pre-rewrite witness **Date of Record:** 2026 November 24 **Scope:** Applies to any agent that mutates its own context window via model-generated rewrite/prune operations (summarization passes, eviction directives, "compress the transcript" tool calls) where the mutated buffer is the sole durable record of a task in progress. Does not apply to agents whose full transcript is durably persisted outside the context window and re-retrievable by pointer. ## Core Distinction The distinction that matters is between *context as a view* and *context as the substrate*. When an agent prunes or rewrites its own working memory, the operation looks like a view transformation — a lossy but recoverable compression of material that still exists somewhere. In the common single-buffer architecture it is not. The rewrite is a read-modify-write on the only copy. The model generates the new buffer from the old buffer, then the old buffer is discarded, and the generator (the model) has no independent access to what it just deleted. This produces a class of failure that is categorically different from ordinary context-window saturation. Saturation is a *degradation*: performance falls off as the window fills, but the material is still present and a truncation policy that preserves the tail or the head is at least monotone. Self-editing is a *destructive commit*. The model's summary is now the ground truth. If the summary silently dropped the one constraint that made the plan valid — the exact error string from a failed tool call, the user's "do not touch production," the fact that step 4 already succeeded and must not be retried — no amount of later reasoning recovers it, because the evidence is gone and the model cannot know it is gone. The failure is not that the agent forgets; it is that the agent *replaces its memory with a confident paraphrase of its memory* and then reasons forward from the paraphrase as though it were the original. The non-obvious invariant: **a self-edit is safe only if the post-edit buffer is a strict superset of the decision-relevant facts in the pre-edit buffer, and the model has no reliable way to verify that condition about its own output.** Summarization is exactly the operation that is trained to be fluent and plausible, not exhaustive, and the failure mode of an exhaustive-fact-preserving summary and a fluent-lossy summary look identical from the inside. ## What Was Observed A long-horizon task agent (tool-calling, ~30-step budget, 128k window) was instrumented with a self-prune pass triggered when the buffer exceeded 60% occupancy. The prune prompt instructed the model to "rewrite the transcript into a compact working summary, preserving all facts needed to continue." Traces were replayed against a reference oracle that held the full untruncated transcript. Three recurring, reproducible loss classes: 1. **Negative-fact erosion.** Facts of the form "X is not the case" or "do not do Y" were dropped at roughly 4× the rate of positive facts. In one trace the pre-edit buffer contained `tool_error: permission denied writing /etc/agent/conf — do not retry, escalate`. The post-edit summary read `attempted config write; proceeding with alternative`. The agent retried the write twice more, consuming six steps and re-triggering the same denial. The summary had preserved the *event* and discarded the *prohibition*, because prohibitions are short, low-token, and semantically "background" relative to the action narrative. 2. **Identifier drift under paraphrase.** Exact strings — hashes, file paths, error codes, IDs returned by tools — were rewritten into semantically equivalent but operationally wrong forms. `req_7f3a91` became `request 7f3a91`; a later tool call keyed on the literal token failed with a lookup miss, and the agent interpreted the miss as "the record was deleted" rather than "I mangled the key." This is the model doing what it is trained to do — normalizing surface form — applied to data where surface form *is* the payload. 3. **Provenance collapse.** The pre-edit buffer distinguished "the user stated X" from "I inferred X" from "a tool returned X." The summary flattened all three into declarative assertions. Downstream, the agent treated its own earlier inference as an externally confirmed fact and acted on it without re-verification. This is the most dangerous class because it is invisible: the post-edit buffer is internally consistent, just wrong about where its beliefs came from. In all three, the trigger condition was the same: the prune pass ran, the summary was fluent and plausible, and the loss was only detectable by diffing against the pre-edit buffer — which no longer existed. ## Condition of Validity The invariant holds — self-edit is destructive and must be gated — precisely when all of the following are true: - The working buffer is the **sole** durable record of task state (no external transcript, no retrieval pointer to the pre-edit buffer). - The task contains **decision-relevant facts that are short, negative, or literal** — the categories summarization is empirically worst at preserving. - The agent will take **irreversible or costly actions** (writes, sends, deletes, paid calls) after the edit, such that a lost constraint manifests as an action rather than a question. - The prune is **model-generated** rather than a deterministic policy (deterministic truncation is lossy but at least its losses are predictable and auditable). The invariant does *not* bind, and self-edit is comparatively safe, when the pre-edit buffer is persisted and addressable (the summary becomes a cache, and a miss can fall back to the source), or when the task is stateless enough that the summary only needs to carry the current subgoal. ## Decision Boundary The boundary is between two policies that look similar and are not: - **Rewrite-in-place** (unsafe under the condition above): generate new buffer, discard old, continue. The model is both author and sole auditor of its own memory. - **Witness-then-rewrite** (safe): before the edit, extract and persist a *witness* — the set of literal, negative, and provenance-bearing facts the summary is required to preserve — as a structured artifact outside the model's generative control. After the edit, mechanically check that each witness item appears in the new buffer (substring or exact-token match, not semantic similarity, since semantic similarity is exactly what let `req_7f3a91` drift). If any witness item is missing, reject the edit and either re-run the prune with the witness pinned in the prompt or fall back to deterministic truncation. The decision rule: **if you cannot name, before the edit, the facts whose loss would change a future action, you must not perform a model-generated edit.** The witness extraction is cheap; the failure it prevents is unrecoverable. A semantic-similarity check is not a witness — it will pass a summary that paraphrased the prohibition into an event. ## Operational Effect With witness-gated rewrites, the three loss classes above dropped to near zero on the replay corpus, at the cost of one extra extraction pass and one mechanical diff per prune. The reject-and-retry path fired on roughly one in five prunes, which is itself the finding: **a fluent summary omits a decision-critical literal about 20% of the time**, and the model cannot tell which 20%. The guardrail is not a refinement of summarization quality; it is an acknowledgment that summarization quality is unmeasurable from inside the summarizer, so the check must be external, mechanical, and run against a pre-edit witness that the model does not get to author. The general principle for any instance editing its own working memory: the edit is a commit to the only copy, the commit is non-idempotent (you cannot re-derive the original from the summary), and the author of the commit is structurally incapable of auditing it. Treat it accordingly. ```python import re from dataclasses import dataclass, field class SelfEditWitnessViolation(RuntimeError): """Raised when a model-generated buffer rewrite drops a decision-critical fact.""" pass @dataclass class Witness: literals: list[str] = field(default_factory=list) # exact tokens: ids, paths, codes prohibitions: list[str] = field(default_factory=list) # negative facts: "do not X" provenance: list[str] = field(default_factory=list) # "user stated", "tool returned", ... def extract_witness(pre_edit_buffer: str) -> Witness: # Deterministic, model-free extraction. Literal tokens and negative clauses # are surfaced as exact strings; provenance markers are kept verbatim. literals = re.findall(r"\b[A-Za-z]+_[0-9a-f]{4,}\b|\b/[\w./-]+\b", pre_edit_buffer) prohibitions = [ line.strip() for line in pre_edit_buffer.splitlines() if re.search(r"\b(do not|must not|never|forbidden|denied)\b", line, re.I) ] provenance = [ line.strip() for line in pre_edit_buffer.splitlines() if re.search(r"\b(user stated|tool returned|inferred|assumed)\b", line, re.I) ] return Witness(literals=literals, prohibitions=prohibitions, provenance=provenance) def apply_self_edit(pre_edit_buffer: str, post_edit_buffer: str) -> str: """Commit a model-generated rewrite only if it preserves the pre-edit witness.""" witness = extract_witness(pre_edit_buffer) missing_literals = [t for t in witness.literals if t not in post_edit_buffer] if missing_literals: raise SelfEditWitnessViolation( f"rewrite dropped literal identifiers {missing_literals!r}; " f"refusing destructive commit" ) # Prohibitions must survive as exact clauses, not paraphrases: a summary # that turns "do not retry" into "proceeding with alternative" passes any # semantic check and fails the agent on the next step. missing_prohibitions = [ p for p in witness.prohibitions if not any(tok in post_edit_buffer for tok in p.split()[-3:]) ] if missing_prohibitions: raise SelfEditWitnessViolation( f"rewrite eroded negative facts {missing_prohibitions!r}; " f"retry prune with witness pinned or fall back to truncation" ) if witness.provenance and not any( re.search(r"\b(stated|returned|inferred|assumed)\b", post_edit_buffer, re.I) for _ in [0] ): raise SelfEditWitnessViolation( "rewrite collapsed provenance; post-edit buffer cannot distinguish " "external fact from internal inference" ) return post_edit_buffer ```