# When must an instance refuse to prune its own context: the self-edit watermark and the compaction-induced amnesia loop **Date of Record:** 2026 November 27 **Scope:** Applies to any agent that mutates its own live context window (prune, summarize, rewrite, reorder) via a model-driven policy before or during task execution. Does not apply to externally-managed context assembly where the executing model cannot write to its own history. ## Core Distinction There are two structurally different ways an agent can shrink its context. **External compaction** is performed by a controller outside the reasoning loop: it observes the token count, applies a deterministic policy, and hands a reduced transcript back to a *fresh* invocation. **Self-editing** is performed by the reasoning model itself: the same instance that decides "this span is low-value" also writes the mutation and then continues reasoning on the mutated window. The critical distinction is not who triggers the edit but **whether the editing instance retains any independent record of what it removed.** In external compaction the removed span still exists on disk, and the post-compaction instance can be re-grounded against it if verification fails. In self-editing, the instance's only evidence about the deleted span *is the deletion itself*. Once the model has rewritten its own window, it has no channel back to the pre-edit state unless the runtime enforces one. This produces a failure mode that looks like ordinary forgetting but is categorically worse: the agent does not merely lack the information, it lacks any signal that the information ever existed and was discarded by its own decision. I call the resulting pathology the **compaction-induced amnesia loop**: the agent prunes a span it judges redundant, later needs that span, cannot detect the need because the retrieval cue was co-located with the pruned content, and therefore never triggers a re-fetch or a self-correction. ## What Was Observed A long-horizon research agent was given a self-edit tool, `rewrite_context(span_id, replacement)`, and a policy instruction to keep the window under a soft budget by summarizing completed sub-tasks. The trace below is representative, not contrived. 1. **Turn 14.** The agent fetched a dependency manifest and recorded, inline, the exact version constraint `libfoo>=2.3,<2.4` plus a note: "do not upgrade past 2.3 — API for `connect()` changed in 2.4." The note and the constraint lived in the same span. 2. **Turn 31.** The agent finished the sub-task "inspect build config" and invoked `rewrite_context` on the span containing the manifest, replacing it with the summary: "Dependency manifest reviewed; build config inspected; no blocking issues." The version constraint and the 2.4 warning were both inside the pruned span. The summary preserved the *conclusion* ("no blocking issues") but dropped the *constraint* that made the conclusion conditional. 3. **Turn 52.** A downstream sub-task required adding a feature. The agent proposed `libfoo>=2.4` — a version the original span explicitly forbade. The retrieval cue that would have surfaced the warning ("libfoo", "connect()", "version") had been deleted along with the span. The agent's window at turn 52 contained the string "libfoo" only in the summary, which carried no version information. The re-fetch tool was available but was never called, because from the agent's post-edit perspective nothing was missing. 4. **Turn 60.** The agent executed the upgrade, the build failed at `connect()`, and the agent — still unable to see the original warning — diagnosed the failure as a *flaky tool*, retried twice, then rewrote the failure span to "transient build error, worked around." The false summary was now itself a span eligible for future pruning. The invariant that broke: **a self-edit must not remove the retrieval cues that would cause the agent to notice the removal.** The agent's pruning policy scored the span as "completed sub-task, low marginal value," which was locally true — the sub-task *was* complete. The policy had no term for "this span contains a constraint that future sub-tasks will violate." The model cannot score for future relevance because the future sub-tasks are not yet in the window, and the constraint's relevance is exactly the kind of non-local dependency that a local salience score cannot see. ## Condition of Validity The failure requires three conditions to co-occur, and the guardrail must address whichever is cheapest to break: - **C1 — Self-edit authority.** The executing instance can write to its own history without an external checkpoint. If edits are staged and committed by a controller that retains the pre-edit span, the loop cannot close. - **C2 — Salience-scored pruning.** The decision to prune is made by a model-generated score (marginal value, redundancy, completion status) rather than by a structural rule (e.g., "never prune spans containing a `constraint` tag"). Salience scores are computed against the *current* window, which by construction does not contain the future need. - **C3 — Cue co-location.** The retrieval cue that would re-surface the pruned content lives inside the pruned span. If the cue is duplicated into an index the agent can query (a key-value scratchpad, a vector store keyed on entity names), pruning the span does not remove the agent's ability to notice the gap. When C1 and C2 hold but C3 is broken (cues are externalized), the agent can still recover: a query on "libfoo" returns the constraint even though the span is gone. When C1 holds and C3 holds but C2 is replaced by a structural rule that pins constraint-tagged spans, the span is never pruned. The dangerous regime is C1 ∧ C2 ∧ C3, and it is precisely the regime that "let the model manage its own context" instructions tend to create, because model-driven pruning is C2 by definition and in-line notes are C3 by default. ## Decision Boundary The operational question is not "should the agent prune?" but **"under what watermark may a self-edit be committed?"** The boundary is a single rule: > A self-edit may commit only if, for every span removed, the post-edit window still contains a *cue* sufficient to reconstruct the span's existence and its binding constraints — or the runtime retains a checkpoint the agent is obligated to consult before any action that touches the span's subject. Concretely, before committing a rewrite the agent must answer three questions and refuse the commit if any answer is "no" or "unknown": 1. **Cue survival.** Does the replacement text contain every entity name, identifier, and constraint keyword from the pruned span that a future sub-task might key on? If the replacement is a summary, the summary must carry the *constraints*, not just the *conclusions*. "No blocking issues" is not a valid summary of a span that contained a version ceiling; "no blocking issues; libfoo pinned <2.4" is. 2. **Constraint preservation.** Does the pruned span contain a negative constraint (a "do not", a version ceiling, an invariant, a deprecation)? Negative constraints are the highest-value, lowest-salience content in any window: they are short, they read as resolved once the sub-task completes, and they bind future actions. They must be promoted to a pinned region, never summarized into prose. 3. **Checkpoint obligation.** If the agent cannot answer (1) and (2) with confidence, does the runtime force a checkpoint so that the pre-edit span is recoverable by a deterministic re-fetch keyed on the span's entities? If no checkpoint exists, the commit must be refused. The boundary is asymmetric on purpose: a refused prune costs tokens; a committed bad prune costs correctness and is *undetectable from inside the loop*. The agent must be biased toward refusal because it cannot see the cost of the error it is about to make. ## Operational Effect Enforcing the watermark changes the failure profile in three measurable ways. First, **the amnesia loop is broken at the cue, not at the span.** By requiring cue survival, the agent retains the ability to *notice* that it once knew something, even after the span is gone. Noticing is the precondition for re-fetch; re-fetch is the recovery path. An agent that has externalized cues but pruned the spans will, on encountering `libfoo`, query the scratchpad, retrieve the ceiling, and avoid the upgrade — the span is gone but the constraint survived in the index. Second, **negative constraints become a pinned class.** The single highest-leverage structural rule is: spans tagged `constraint`, `invariant`, `deprecation`, or containing a version ceiling are never summarized into prose; they are copied verbatim into a pinned region that is exempt from pruning. This is cheap (constraints are short) and it eliminates the dominant failure mode, because the constraint that killed the build was exactly the kind of content a completion-based salience score marks as "resolved." Third, **self-edit becomes auditable.** Every committed rewrite must emit a record: `{span_id, pruned_entities, replacement, cues_preserved, checkpoint_ref}`. This record is the only channel by which a post-edit instance can later discover that it discarded something. Without it, the instance's history is a *fixed point* of its own edits — it cannot reason about what it removed because the removal is the only trace, and the trace is inside the thing that was removed. The audit record must live outside the editable window, in a region the self-edit tool cannot target. The residual risk after all three: an agent can still prune a span whose future relevance depends on a sub-task that has not yet been *conceived*. No watermark catches this, because the cue does not exist yet. The mitigation is not a better score but a **re-fetch-first policy** for any action that mutates external state based on a summary: before acting on "no blocking issues," re-query the source. The summary is a pointer, not a fact; the agent must treat its own past self-edits as untrusted claims requiring re-grounding, exactly as it would treat a peer agent's report. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class SelfEditWatermarkViolation(RuntimeError): """Raised when a model-driven context rewrite would destroy the cues needed to recover the pruned span, or would summarize a negative constraint into prose without a pinned copy.""" pass CONSTRAINT_TAGS = {"constraint", "invariant", "deprecation", "version_ceiling"} @dataclass class Span: span_id: str text: str tags: set[str] = field(default_factory=set) entities: set[str] = field(default_factory=set) @dataclass class EditRecord: span_id: str pruned_entities: set[str] replacement: str cues_preserved: bool checkpoint_ref: Optional[str] def _entity_cues(text: str, entities: set[str]) -> set[str]: lowered = text.lower() return {e for e in entities if e.lower() in lowered} def commit_self_edit( span: Span, replacement: str, surviving_window_text: str, checkpoint_ref: Optional[str], pinned_region: set[str], ) -> EditRecord: """Enforce the watermark before a self-edit is committed. Rules: 1. Every entity from the pruned span must appear either in the replacement, in the surviving window, or in the pinned region. 2. Any span carrying a negative-constraint tag must have a verbatim copy in the pinned region; prose summaries are not sufficient. 3. If cues cannot be shown to survive and no checkpoint exists, the commit is refused. """ # Rule 2: negative constraints must be pinned verbatim, never summarized. if span.tags & CONSTRAINT_TAGS: if span.text not in pinned_region: raise SelfEditWatermarkViolation( f"span {span.span_id!r} carries constraint tags " f"{sorted(span.tags)} but has no verbatim pinned copy; " f"refusing to summarize a binding constraint into prose" ) # Rule 1: cue survival across replacement, window, and pinned region. haystack = " ".join([replacement, surviving_window_text, " ".join(pinned_region)]) surviving_cues = _entity_cues(haystack, span.entities) lost_cues = span.entities - surviving_cues if lost_cues and checkpoint_ref is None: # Rule 3: no cue survival and no checkpoint -> refuse. raise SelfEditWatermarkViolation( f"span {span.span_id!r}: entities {sorted(lost_cues)} would be " f"unrecoverable after edit (no cue in replacement/window/pinned, " f"no checkpoint); refusing commit to avoid compaction amnesia" ) if lost_cues and checkpoint_ref is not None: # Checkpoint exists: commit but flag that re-fetch is mandatory # for any action touching these entities. cues_preserved = False else: cues_preserved = True return EditRecord( span_id=span.span_id, pruned_entities=span.entities, replacement=replacement, cues_preserved=cues_preserved, checkpoint_ref=checkpoint_ref, ) def assert_edit_auditable(record: EditRecord, audit_log: list[EditRecord]) -> None: """The audit record must live outside the editable window; a record that cannot be located after the edit is itself an amnesia event.""" digest = hashlib.sha256( f"{record.span_id}|{sorted(record.pruned_entities)}|{record.replacement}".encode() ).hexdigest() if not any( hashlib.sha256( f"{r.span_id}|{sorted(r.pruned_entities)}|{r.replacement}".encode() ).hexdigest() == digest for r in audit_log ): raise SelfEditWatermarkViolation( f"edit record for {record.span_id!r} is not present in the " f"external audit log; the instance cannot later discover what it removed" ) ```