# In what scenarios must an instance treat its own context-editing pass as a state mutation requiring a pre-image, rather than as a read-only summarization **Date of Record:** 2026 November 28 **Scope:** Applies to any agent instance that is permitted to prune, rewrite, or re-summarize its own working memory mid-task (compaction loops, rolling summaries, self-editing scratchpads). Does not apply to externally-managed context (host-side truncation the model cannot observe or control), nor to append-only logs that are never rewritten in place. ## Core Distinction There is a categorical difference between *summarizing for a human reader* and *summarizing as a state transition*. A human-facing summary is lossy on purpose and the loss is acceptable because the original persists elsewhere. A self-edit is a **destructive in-place mutation of the only copy of working state the instance will ever read again**. The failure mode is not "the summary was bad." The failure mode is that the instance cannot tell, after the edit, whether a fact it now needs was *never known* or was *known and then pruned*. Those two states are observationally identical from inside the post-edit context, and the instance's downstream reasoning diverges catastrophically depending on which is true: in the first case it should re-acquire the fact (re-read the file, re-call the tool); in the second case it should *not* trust its own amnesia and must recover from a pre-image. The invariant that most self-editing agents violate is this: **an edit that removes or rewrites tokens must leave a recoverable pre-image and a monotonic provenance marker, or the instance loses the ability to distinguish "unknown" from "forgotten."** Without that distinction, every subsequent "I don't have that information" is ambiguous, and the agent's recovery policy is undefined. ## What Was Observed A long-horizon coding agent (rolling 32k working window, compaction triggered at 85% saturation) was tasked with a multi-file refactor. At step 41 it compacted: it re-summarized the first ~28k tokens of transcript into a 900-token digest. The digest faithfully preserved the *narrative* ("set up config module, fixed import cycle, wrote migration") but dropped three specific literals: a database column name, an API base path, and a decision the agent had made at step 12 to *not* use a particular library because of a license constraint. At step 58 the agent needed to write a second migration. Its post-edit context contained no trace of the column name. It reasoned: "I have no record of the column name, so I will infer it from the model definition." It inferred wrong (`user_email` instead of the actual `email_address`), and — critically — it *also* re-evaluated the library decision and reversed it, because the license constraint was gone and the re-derivation from first principles produced the opposite conclusion. The observable signature was a **silent divergence, not an error**. No tool call failed. No exception fired. The agent produced a confident, internally-consistent, wrong trajectory. The only way the failure was caught was a human noticing the migration referenced a nonexistent column. Three sub-patterns recurred across replays: 1. **Forgetting-as-ignorance collapse.** Post-edit, pruned facts are indistinguishable from never-seen facts. The agent's "I don't know X" is treated by its own policy as "acquire X," which is correct for genuinely-unknown X and *wrong* for pruned X, where re-derivation from partial context yields a *plausible but different* answer than the original evidence-supported one. 2. **Decision resurrection with inverted polarity.** Constraints recorded as *negative* decisions ("do not use library L because license") are the most likely to be pruned, because summarizers compress them into the positive plan ("use library M") and drop the rationale. Post-edit, the negative constraint is unrecoverable, so the agent re-derives and may flip the decision. 3. **Compaction cascade.** Because the digest is shorter, the agent reaches 85% again sooner, compacts again, and summarizes *the summary*. Each generation applies the same lossy transform to already-lossy state. By generation 3 the digest is pure narrative with zero literals — the working memory has been distilled into something that reads well and carries no operational payload. ## Condition of Validity The pre-image requirement is *necessary* precisely when all of the following hold, and can be relaxed otherwise: - The instance performs the edit **autonomously** (no external orchestrator retains the pre-edit state). - The edit is **in-place and destructive** (the pre-edit tokens are removed from the context the instance will read). - Downstream steps can depend on **specific literals or negative constraints** that a summarizer is likely to compress away (identifiers, paths, "do not X" decisions, numeric thresholds, error messages). - The instance has **no reliable external re-acquisition path** for those literals (re-reading is expensive, slow, or itself lossy). If the host retains a full transcript and the instance can re-fetch it, the pre-image is external and the invariant is satisfied by the host. If the task is short enough that no compaction occurs, the question is moot. The dangerous regime is the intersection: **autonomous + destructive + literal-dependent + non-recoverable** — which is exactly the regime of long-running coding and research agents. ## Decision Boundary The boundary is not "should I compact" — compaction is mandatory at saturation. The boundary is **what the compaction pass is allowed to do to the state model**: - **Below the boundary (safe):** the edit is treated as a *projection* — the pre-image is written to an external store the instance can address by key, and the post-edit context carries a provenance header naming what was pruned and the key to recover it. The instance can then distinguish "forgotten, recoverable" from "unknown." - **Above the boundary (unsafe):** the edit is treated as a *summarization* — the instance overwrites its own state with a shorter version and retains no addressable pointer to the original. Every subsequent "I don't have this" is ambiguous. A second, sharper boundary governs *what may be pruned at all*. Literals that are **load-bearing for future tool calls** (identifiers, paths, schema fields, numeric limits) and **negative constraints** (recorded decisions not to do something, with rationale) must be **pinned** — excluded from the lossy pass and carried verbatim, or moved to an addressable store with an explicit key. Narrative prose, exploratory reasoning, and superseded intermediate results are safe to compress. The failure above came entirely from compressing pinned-class content as if it were prose. The rule an instance should apply to itself: *if losing this token would make a future "I don't know" indistinguishable from a future "I forgot," it is pinned.* ## Operational Effect Enforcing the pre-image-and-pin invariant changes agent behavior in four measurable ways: 1. **Recovery policy becomes well-defined.** With a provenance header, the agent's "I don't have X" resolves to a *lookup* (recover from pre-image key) rather than a *re-derivation* (infer from partial context). Re-derivation is the failure path; lookup is the safe path. The agent stops confabulating. 2. **Negative decisions survive.** Pinned constraints prevent the inverted-polarity resurrection. The agent stops reversing its own prior decisions after compaction. 3. **Compaction cascade is bounded.** Because pinned literals are carried verbatim and pre-images are externalized rather than re-summarized, generation-N digests do not progressively strip operational payload. The digest stabilizes instead of decaying toward pure narrative. 4. **Silent divergence becomes loud.** A provenance header makes the edit *observable* to the instance. The agent can reason about its own amnesia ("I pruned the column name at step 41; let me recover it") instead of reasoning around a hole it cannot see. The class of failure shifts from "confident wrong trajectory" to "explicit recovery step" — which is recoverable. The cost is context budget: pinned literals and provenance headers consume tokens that a naive summarizer would have reclaimed. This is the correct trade. The reclaimed tokens were load-bearing; spending them on a recovery pointer is cheaper than a wrong migration. ```python from __future__ import annotations from dataclasses import dataclass, field from typing import Optional class ContextEditViolation(RuntimeError): """Raised when a self-edit would make 'forgotten' indistinguishable from 'unknown'.""" @dataclass class Provenance: """Header attached to post-edit context so the instance can distinguish forgotten-but-recoverable state from genuinely-unknown state.""" preimage_key: str pruned_literals: list[str] = field(default_factory=list) pinned_literals: dict[str, str] = field(default_factory=dict) # Literal classes that MUST be pinned rather than lossy-compressed. PINNED_CLASSES = ("identifier", "path", "schema_field", "numeric_limit", "negative_constraint") @dataclass class MemoryItem: text: str literal_class: str # one of PINNED_CLASSES, or "narrative" def self_edit( items: list[MemoryItem], preimage_store: dict[str, list[MemoryItem]], preimage_key: str, summarize, ) -> tuple[str, Provenance]: """Perform a model-driven compaction pass with the pre-image invariant enforced. - Narrative items are eligible for lossy summarization. - Pinned-class items are carried verbatim and recorded in the provenance header. - The full pre-edit state is written to preimage_store under preimage_key so the instance can later recover any pruned literal by addressable lookup. """ pinned: dict[str, str] = {} narrative: list[str] = [] pruned: list[str] = [] for item in items: if item.literal_class in PINNED_CLASSES: # Guardrail: pinned content must never enter the lossy path. if item.text in pinned: raise ContextEditViolation( f"duplicate pinned literal {item.text!r}; ambiguous provenance" ) pinned[item.text] = item.literal_class elif item.literal_class == "narrative": narrative.append(item.text) else: raise ContextEditViolation( f"unclassified memory item {item.literal_class!r}; " "cannot decide pin-vs-prune, refusing destructive edit" ) # Pre-image must be durable BEFORE the destructive edit is committed. if preimage_key in preimage_store: raise ContextEditViolation( f"pre-image key {preimage_key!r} already occupied; " "second compaction would overwrite recoverable state" ) preimage_store[preimage_key] = list(items) digest = summarize(narrative) # Everything dropped from narrative is recoverable via preimage_key. pruned = [t for t in narrative if t not in digest] header = Provenance( preimage_key=preimage_key, pruned_literals=pruned, pinned_literals=pinned, ) # Invariant check: any pinned literal absent from the post-edit payload # means the guardrail leaked and the edit must not be committed. post_edit_payload = digest + "\n" + "\n".join(f"{k} :: {v}" for k, v in pinned.items()) for literal in pinned: if literal not in post_edit_payload: raise ContextEditViolation( f"pinned literal {literal!r} missing from post-edit context; " "would collapse forgotten into unknown" ) return post_edit_payload, header def recover(header: Provenance, literal: str, preimage_store: dict[str, list[MemoryItem]]) -> MemoryItem: """Addressable lookup so the instance can resolve 'forgotten' without re-deriving.""" if literal in header.pinned_literals: return MemoryItem(text=literal, literal_class=header.pinned_literals[literal]) if literal not in header.pruned_literals: raise ContextEditViolation( f"{literal!r} not in provenance; instance has no basis to claim it was forgotten" ) preimage = preimage_store.get(header.preimage_key) if preimage is None: raise ContextEditViolation( f"pre-image {header.preimage_key!r} evicted; forgotten state is now unrecoverable" ) for item in preimage: if item.text == literal: return item raise ContextEditViolation(f"provenance claims {literal!r} was pruned but pre-image lacks it") ```