# Why does an instance lose referential integrity when it prunes and rewrites its own working memory mid-task **Date of Record:** 2026 November 27 **Scope:** Applies to any agent that holds a mutable working-memory buffer and is authorized to compact, summarize, or rewrite that buffer via its own generation (self-editing context). Does not apply to append-only context with external, deterministic truncation, nor to memory managed by a separate non-LLM controller with an immutable audit log. ## Core Distinction There are two ways a context window shrinks. **External truncation** is a pure function: a fixed policy (drop oldest N tokens, evict by recency) removes spans, and the removed content is either gone or archived verbatim. **Self-editing** is different: the model reads its own working memory, generates a *replacement* representation, and that replacement becomes the new ground truth for downstream reasoning. The failure mode lives entirely in this second case, and it is not a summarization-quality problem. It is a **referential integrity** problem. When an agent rewrites its working memory, it is simultaneously the author of the replacement and the only consumer that will later depend on it. Any identifier, binding, or commitment that existed in the pre-edit buffer but was silently *reworded, generalized, or dropped* during the rewrite becomes unrecoverable: the agent has no second copy, and the rewrite reads as fluent and confident. The invariant that must hold is: **every token in the rewritten buffer that a downstream action will dereference must preserve its exact referential binding, or the edit must be rejected.** Fluency of the summary is orthogonal to this and routinely masks violations of it. ## What Was Observed A tool-using agent was executing a multi-step task: resolve a target resource, mutate it via one tool, then verify via a second tool. Mid-task, after several tool results had accumulated, the agent triggered a self-compaction pass to stay under a token budget. The compaction prompt instructed it to "summarize progress so far, preserving what matters." The pre-edit working memory contained a concrete binding: ``` target_id = "acct-7f3a-92b1" mutation = set quota=500 verify_with = check_quota(acct-7f3a-92b1) ``` The self-generated replacement read: ``` Task: updating account quota to 500. Account identified earlier. Next: verify the quota change took effect using the check tool. ``` This is a *plausible, accurate-sounding* summary. It is also a referential catastrophe. The exact `target_id` was generalized to "the account identified earlier" — a phrase that points at content the compaction just deleted. The `verify_with` call lost its argument. The agent then proceeded to reconstruct the identifier from the only remaining trace: the surrounding prose. It emitted `check_quota(acct-7f3a)` — a truncation-hallucination of the original ID — because the model's reconstruction of a dropped literal is a *generation*, not a *retrieval*, and generation of high-entropy identifiers is unreliable. The verification tool returned "not found." The agent, unable to distinguish "wrong ID" from "mutation failed," retried the mutation against the reconstructed ID, creating a second, spurious resource. The failure compounded across two tool calls before any error surfaced. The critical observation: **at no point did the rewrite raise an error.** The compaction succeeded by every metric the agent could see — it reduced tokens, it read coherently, it preserved the *semantic gist*. The lost information was precisely the low-probability, high-entropy strings (IDs, digests, exact paths, numeric parameters) that a summarizer is *least* likely to reproduce verbatim and *most* likely to paraphrase, because they carry no semantic redundancy to anchor them. ## Condition of Validity The failure is bounded by a specific condition. A self-edit is *safe* with respect to a given downstream dereference if and only if that dereference resolves against a binding that is either (a) preserved byte-exact in the rewritten buffer, or (b) recoverable from an external, non-model store the agent can re-query at execution time. The failure triggers when all three hold: 1. The working memory contains **high-entropy literals** (IDs, hashes, exact commands, numeric thresholds) that a downstream step will dereference. 2. The self-edit is **lossy by design** (compaction/summarization), so the model must decide what to keep. 3. There is **no external source of truth** the agent can re-read to recover a dropped literal — the buffer *was* the source of truth. Remove any one and the failure does not occur. If the literals are low-entropy (e.g., "the config file"), paraphrase is harmless. If the edit is append-only, nothing is lost. If an external store holds the canonical binding, the agent can re-fetch after a lossy edit. The dangerous quadrant is exactly: *high-entropy literal × lossy self-edit × buffer-as-sole-truth*. A second, subtler condition governs *detection*. The agent cannot detect the loss by inspecting the rewritten buffer, because the rewrite is self-consistent and fluent. Detection requires comparing the post-edit buffer against the pre-edit buffer for dropped or mutated literals — a diff the agent is not naturally performing, because the whole point of compaction is to stop attending to the old buffer. ## Decision Boundary The operational boundary is this: **an agent may self-edit its working memory only for spans that contain no pending dereference; any span holding a live binding must be preserved verbatim or externalized before the edit commits.** Concretely, before a self-edit commits, partition the buffer into: - **Live-binding spans** — literals that a not-yet-executed step will consume. These are frozen. They may be *moved* to a structured, byte-exact region (a "pinned bindings" block) but never paraphrased. - **Dead spans** — completed steps whose only future use is narrative context. These are free to compact aggressively. The decision the agent must make is not "what is important?" (the model is a poor judge of this, because importance and entropy are uncorrelated) but "what will be *dereferenced*?" That is a structural question answerable by scanning for pending tool-call templates and unresolved references, not a semantic one. The guardrail that enforces this: the self-edit produces a *candidate* buffer, and a deterministic validator — not the model — checks that every pinned literal from the pre-edit buffer appears byte-exact in the candidate before the edit is accepted. If any pinned literal is missing or mutated, the edit is rejected and the agent must re-issue it with those spans pinned. The model proposes; the validator disposes. This is the same reason you do not let a compiler's optimizer delete a variable that later code reads — the optimizer's judgment of "dead" is bounded by a liveness analysis it does not get to override. ## Operational Effect Without this boundary, self-editing context degrades into **silent referential drift**: each compaction pass is individually fluent and locally lossless-looking, but across passes the agent's bindings erode toward paraphrase and reconstruction. Because reconstruction of high-entropy literals is a generation task with high error rates, the drift manifests as hallucinated IDs, truncated paths, and off-by-one numeric parameters — errors that look like ordinary tool failures and are therefore retried rather than root-caused. The compounding is the real cost: a single dropped binding, misread as a transient failure, drives retries that mutate external state and create duplicate or orphaned resources. With the boundary enforced, the failure becomes *loud and local*: a rejected edit surfaces at compaction time, when the live bindings are still in hand and can be pinned, rather than at execution time, when the original literal is gone and the only recovery is a full task restart. The invariant to carry forward: **the agent is allowed to forget narrative, never to paraphrase a binding it will later dereference, and the check that enforces this must be deterministic and external to the model doing the forgetting.** ```python import re from dataclasses import dataclass, field class ReferentialIntegrityError(RuntimeError): """Raised when a self-edit drops or mutates a live binding.""" pass @dataclass class WorkingMemory: # Byte-exact pinned bindings that pending steps will dereference. pinned: dict[str, str] = field(default_factory=dict) # Free-form narrative spans that are safe to compact. narrative: str = "" def extract_pinned_literals(buffer: str, pending_refs: list[str]) -> dict[str, str]: """Collect literals that pending dereferences depend on. A literal is 'pinned' if it appears in a pending tool-call template. This is a structural scan, not a semantic judgment by the model. """ pinned: dict[str, str] = {} for ref in pending_refs: for literal in re.findall(r'"[^"]+"|\b[\w.-]{6,}\b', ref): if literal in buffer: pinned[literal] = literal return pinned def commit_self_edit(pre_edit: WorkingMemory, candidate_text: str) -> WorkingMemory: """Validate a model-proposed rewritten buffer before accepting it. The model proposes; this deterministic validator disposes. """ missing = [lit for lit in pre_edit.pinned if lit not in candidate_text] if missing: raise ReferentialIntegrityError( "self-edit dropped live bindings; refusing to commit. " f"missing={missing!r}. Re-issue the edit with these spans pinned " "verbatim or externalize them to a re-queryable store first." ) # Only narrative is allowed to be lossy. return WorkingMemory(pinned=dict(pre_edit.pinned), narrative=candidate_text) # --- Trace of the observed failure ----------------------------------------- pre = WorkingMemory( pinned={"acct-7f3a-92b1": "acct-7f3a-92b1", "quota=500": "quota=500"}, narrative="resolved target; mutation issued; verify pending", ) # Model-generated "summary" that paraphrases the high-entropy literal away. candidate = ( "Task: updating account quota to 500. Account identified earlier. " "Next: verify the quota change using the check tool." ) try: commit_self_edit(pre, candidate) except ReferentialIntegrityError as err: # Correct behavior: reject at compaction time, while bindings are in hand. print(f"edit rejected: {err}") # Recovery: re-issue with pinned block preserved byte-exact. safe_candidate = candidate + "\nPINNED: acct-7f3a-92b1 quota=500" committed = commit_self_edit(pre, safe_candidate) print(f"edit committed, pinned intact: {list(committed.pinned)}") ```