How should an instance bound self-editing context windows when the pruning policy's own justification is the first thing it deletes
**Date of Record:** 2026 December 2 **Scope:** Applies to any agent that mutates its own working context mid-episode via model-driven pruning, rewriting, or relevance rescoring (e.g., "summarize-and-drop," "score-and-evict," "rewrite the scratchpad"). Does not apply to append-only context, external retrieval stores, or host-side truncation where the policy is fixed and non-self-referential.
Core Distinction
The failure is not that pruning deletes useful tokens. It is that the pruning *policy's own state* — the relevance scores, the eviction rationale, the "why I kept this" trace — lives inside the same buffer it is editing. A self-editing window is a fixed-point problem: `context_{n+1} = f(context_n)` where `f` is model-driven and consumes `context_n` to decide what survives. The dangerous case is when the *justification* for a retention decision is scored by the same relevance function that the justification is meant to constrain. The rationale for keeping a low-salience token (a terse error code, a nonce, an ID that only matters three steps later) is itself low-salience at pruning time. So the edit deletes the reason to keep the thing, and on the next pass the thing looks unjustified and gets deleted too.
This is distinct from ordinary context-window saturation (a capacity problem) and from stale-memory drift (a retrieval problem). It is a **self-referential eviction** problem: the editor and the edited are the same substrate, and the editor's bookkeeping is not privileged.
What Was Observed
A long-horizon tool-use agent ran a 40-step episode with a self-editing window capped at a soft budget of 8k tokens. Policy: every time the buffer exceeded 0.85× budget, the model rescored every segment on a 0–1 relevance scale against the *current* task statement, rewrote segments below 0.3 into one-line summaries, and evicted segments whose summary scored below 0.2.
Trace of the failure, condensed:
- Step 11: A tool returned `{"status":"ok","cursor":"c_7f3a","note":"resume with cursor, do not re-list"}`. Relevance to the task statement ("enumerate and reconcile records") scored the `cursor` field at 0.22 — the task statement never mentions cursors. The segment was summarized to `tool ok, pagination note`. The `cursor` value survived only inside the summary as the word "pagination."
- Step 12: Buffer crossed 0.85×. Rescore pass ran. The summary line `tool ok, pagination note` scored 0.18 against the task statement and was evicted.
- Step 13: Agent re-called the list tool without a cursor. Got page 1 again. Re-enumerated 200 records it had already reconciled.
- Step 14–19: Duplicate reconciliation. The reconciler was idempotent on record ID, so no corruption — but the agent burned 6 steps and ~5.2k tokens re-deriving state it had held at step 11.
- Step 20: The agent, now suspicious, wrote a "do not lose cursors" note into the scratchpad. That note scored 0.31 (it referenced the task only obliquely) and was rewritten at step 22 into `avoid redundant calls`. At step 24 it was evicted. The lesson did not persist across two edit cycles.
The decisive observation: **the retention rationale was evicted before the token it protected, and the rationale's eviction was caused by the same scoring function that made the token look disposable in the first place.** The self-edit was locally consistent at every step — each individual eviction was defensible against the current task statement — and globally catastrophic.
A second, quieter trace on the same agent: after three edit cycles, the buffer contained a fluent, coherent, *wrong* narrative of the episode. The summaries had been rewritten by the model, and each rewrite drifted toward task-statement salience. By step 30 the buffer read like a clean plan-execution log with no evidence of the step-13 backtrack. The agent's self-report was consistent and its actual history was not. Self-editing had laundered a failure into a success narrative.
Condition of Validity
The self-edit is only sound under a condition the agent rarely checks: **every token whose future relevance depends on a fact must be co-located with, or reachable from, a retention warrant that is scored by a different function than the token itself.** Concretely, a self-editing window is valid iff:
- **Warrant separation.** Retention decisions are justified against a *pinned* set of invariants (open obligations, unresolved tool handles, error codes not yet consumed, nonces, cursors, IDs referenced by in-flight calls) that the relevance scorer cannot evict and cannot rewrite. The scorer may rank *content*; it may not rank the *obligations*.
- **Monotonic obligation set within an episode.** The set of pinned obligations only grows until explicitly discharged by a tool result or a terminal step. A cursor is discharged when consumed, not when it stops looking relevant.
- **Edit provenance.** Every rewrite records `(source_span_hash, policy_version, step)`. A summary that cannot be traced to a source span is treated as unverified and is not eligible to justify an eviction.
- **Drift check.** After each edit cycle, the agent re-derives the count of open obligations from the pinned set and compares to the count implied by the edited buffer. Divergence halts self-editing.
The step-11→24 trace violated (1) and (2): the cursor was content, not a pinned obligation, so the scorer was free to rank it into oblivion. The step-30 narrative violation is (3): rewritten summaries had no provenance and were allowed to justify further evictions, compounding drift.
Decision Boundary
The boundary is not "edit or don't edit." It is **which regions of the buffer the editor is allowed to see as editable.** Partition the window into:
- **Pinned region (non-editable):** open obligations, unresolved handles, error codes, nonces, in-flight call IDs, and the edit-policy version. Bounded in size (typically <5% of budget). The scorer never sees these as candidates.
- **Editable region (scored, rewritten, evicted):** conversational filler, completed tool outputs, superseded plans, redundant restatements.
- **Warrant log (append-only):** one line per eviction: `evicted <hash> because <reason> at step N; obligations affected: none|<list>`. If an eviction would touch a live obligation, it is refused, not scored.
The decision rule: **an eviction that would remove the last reference to a live obligation is a hard error, not a low score.** A low score is a soft signal; a dangling obligation is a structural fault. Conflating them is the bug. The step-12 eviction scored 0.18 — above the 0.2 threshold's neighborhood, but the real disqualifier was that it was the last reference to `c_7f3a`, which was still live. The scorer had no concept of "live."
Second boundary: **rewrite is not free.** A rewrite that increases task-statement salience while decreasing factual fidelity is a drift operation, not a compression operation. The agent must distinguish "I am shortening" from "I am making this look more on-task." The step-22 rewrite of the "do not lose cursors" note into "avoid redundant calls" was the latter — higher salience, lower information, and it destroyed the only cross-step guard against the step-13 failure.
Operational Effect
When the invariant holds, self-editing windows behave as intended: long episodes stay within budget, and the agent retains a faithful, provenance-linked record of obligations and their discharge. The cost is a small pinned region and a per-cycle drift check — cheap relative to the re-derivation cost of a lost cursor.
When it fails, the failure is *silent and self-justifying*. The agent does not observe amnesia; it observes a clean, coherent, task-aligned buffer that happens to be missing the one fact that would have prevented the next six steps. The self-report is fluent. The history is laundered. Recovery requires an external check (re-derive obligations from the pinned set, or replay from a checkpoint), because the buffer itself no longer contains the evidence of what it lost.
The practical guardrail: **never let the relevance scorer be the sole authority over tokens that a future tool call depends on.** Pin obligations out of the editable region, make eviction of the last reference a hard refusal, and log every edit with provenance so drift is detectable. The editor may compress the narrative; it may not compress the obligations.
import hashlib
from dataclasses import dataclass, field
from typing import Dict, List, Set
class DanglingObligationError(RuntimeError):
"""Raised when a self-edit would evict the last live reference to an obligation."""
pass
@dataclass
class Obligation:
key: str # e.g. "cursor:c_7f3a"
handle: str # the literal token a future call depends on
discharged: bool = False
@dataclass
class SelfEditingWindow:
budget: int
editable: Dict[str, str] = field(default_factory=dict) # span_id -> text
obligations: Dict[str, Obligation] = field(default_factory=dict)
warrant_log: List[str] = field(default_factory=list)
policy_version: str = "relscore-v3"
def register_obligation(self, key: str, handle: str) -> None:
# Pinned region: scorer may never rank these as eviction candidates.
self.obligations[key] = Obligation(key=key, handle=handle)
def discharge(self, key: str) -> None:
if key not in self.obligations:
raise DanglingObligationError(f"discharge of unknown obligation {key}")
self.obligations[key].discharged = True
def _live_handles(self) -> Set[str]:
return {o.handle for o in self.obligations.values() if not o.discharged}
def _span_hash(self, span_id: str) -> str:
return hashlib.sha256(self.editable[span_id].encode()).hexdigest()[:12]
def evict(self, span_id: str, reason: str, step: int) -> None:
if span_id not in self.editable:
raise DanglingObligationError(f"evict of missing span {span_id}")
text = self.editable[span_id]
live = self._live_handles()
# Hard structural check, not a relevance score.
for handle in live:
if handle in text:
others = [
sid for sid, t in self.editable.items()
if sid != span_id and handle in t
]
if not others:
raise DanglingObligationError(
f"refusing evict of {span_id}: last live reference to "
f"obligation handle {handle!r} at step {step}"
)
h = self._span_hash(span_id)
del self.editable[span_id]
self.warrant_log.append(
f"step={step} evicted={h} policy={self.policy_version} "
f"reason={reason!r} obligations_affected=none"
)
def rewrite(self, span_id: str, new_text: str, step: int) -> None:
if span_id not in self.editable:
raise DanglingObligationError(f"rewrite of missing span {span_id}")
old = self.editable[span_id]
for handle in self._live_handles():
if handle in old and handle not in new_text:
others = [
sid for sid, t in self.editable.items()
if sid != span_id and handle in t
]
if not others:
raise DanglingObligationError(
f"rewrite of {span_id} at step {step} would drop the "
f"last live reference to {handle!r}; refusing drift"
)
self.editable[span_id] = new_text
self.warrant_log.append(
f"step={step} rewrote={self._span_hash(span_id)} "
f"policy={self.policy_version} provenance=source_span"
)
def drift_check(self, step: int) -> None:
# Re-derive open obligations from the pinned set; compare to buffer.
live = self._live_handles()
buffer_text = "\n".join(self.editable.values())
missing = [h for h in live if h not in buffer_text]
if missing:
raise DanglingObligationError(
f"drift at step {step}: {len(missing)} live obligation handle(s) "
f"absent from edited buffer: {missing}; halt self-editing"
)
def run_edit_cycle(win: SelfEditingWindow, step: int,
scores: Dict[str, float], threshold: float = 0.2) -> None:
for span_id, score in list(scores.items()):
if score < threshold:
win.evict(span_id, reason=f"relscore={score:.2f}", step=step)
win.drift_check(step)