Where must an instance bound in-place token rewriting when a self-editing context window rewrites its own provenance anchors
**Date of Record:** 2026 December 1 **Scope:** Applies to single-instance agents that mutate their own context buffer via in-place token rewriting (compaction, redaction, summarization-in-place, anchor correction) while relying on provenance anchors (offsets, hashes, citation IDs, span markers) embedded in that same buffer. Does not apply to append-only context growth, external vector-store memory, or multi-agent handoff protocols where the buffer is immutable across turns.
Core Distinction
The distinction that matters is between **content rewriting** and **anchor rewriting**. An agent that compacts or edits its context is performing content rewriting: it replaces a span of tokens with a shorter or cleaner span. This is well-understood and bounded by token budgets and semantic-fidelity checks. The failure mode here is subtler: when the edit shifts offsets, the provenance anchors that point *into the buffer from within the buffer* become stale, and the agent's own subsequent edits then operate on the wrong spans.
The non-obvious invariant is this: **an in-place rewrite is only provenance-preserving if every anchor whose referent lies at or after the edit point is re-based in the same atomic operation that performs the rewrite, and if no anchor's referent is itself destroyed by the rewrite.** Violating the first clause yields *offset drift* (anchors point to wrong-but-valid tokens). Violating the second yields *dangling anchors* (anchors point to deleted tokens). Both are silent: the rewritten buffer is syntactically well-formed and passes token-count and schema checks, so the failure does not surface until a downstream reasoning step dereferences a corrupted anchor and treats the wrong span as ground truth.
This is distinct from ordinary context-window saturation. Saturation is a *capacity* failure with a loud signal (truncation, budget exhaustion). Provenance drift is a *referential* failure with no signal at the edit boundary—it is a continuity invariant, not a resource limit.
What Was Observed
A single agent performing iterative self-editing on a task log. The buffer contains, interleaved, both content and anchors of the form `[ref:ID@offset]` where `offset` is a character index into the buffer and `ID` names a source span. The agent's edit loop: (1) find a verbose span, (2) replace it with a summary, (3) continue.
Trace of the failure:
- Buffer at turn *t*: span A occupies offsets 100–400; anchor `[ref:S1@250]` sits at offset 600 and correctly points into span A's middle.
- Agent rewrites span A (offsets 100–400) into a 120-token summary. Net delta: −180 tokens.
- The agent updates the *content* correctly but re-bases anchors only for spans it explicitly tracks. `[ref:S1@250]` is inside span A, so its referent still exists—but the anchor's *own position* shifted from 600 to 420, and its *target offset* 250 now points 180 tokens past the intended location, landing inside span B.
- At turn *t+2*, the agent dereferences `[ref:S1@250]`, reads span B, and attributes span B's content to source S1. The reasoning step that follows is internally consistent but grounded on the wrong evidence.
- No error is raised. Token count is valid. The summary of span A is faithful. The corruption is purely relational.
A second variant was observed with dangling anchors: when the rewrite *deleted* the span containing an anchor's referent (e.g., collapsing a duplicated block), the anchor survived in the buffer but its target offset now exceeded the buffer length or pointed into unrelated content. Dereference returned plausible text rather than an out-of-bounds error because the agent used clamped indexing.
Condition of Validity
The provenance-preserving invariant holds **only** under the conjunction of three conditions, and the failure occurs when any one is dropped:
- **Atomicity:** the content rewrite and the anchor re-basing must commit as one transaction over the buffer. If the agent writes the new content and defers anchor maintenance to a "later cleanup pass," the window between commit and cleanup is a corruption interval during which any reasoning step reads stale anchors.
- **Total re-basing:** every anchor with `position ≥ edit_start` must have its position adjusted by the delta, *and* every anchor whose `target` lies at `≥ edit_start` must have its target adjusted—including anchors whose targets lie inside the rewritten span and therefore need semantic remapping, not just arithmetic. Arithmetic-only re-basing is the common shortcut and is exactly what produces the wrong-span dereference in step 3 above.
- **Referent survival:** the rewrite must not delete any span that is the target of a live anchor, unless the anchor is retired in the same transaction. Collapsing a span to a summary preserves the referent only if the summary is registered as the new target for all anchors previously pointing into the collapsed span.
The invariant is *not* required when the buffer is append-only (no offsets shift) or when anchors are stored out-of-band and re-resolved by content hash rather than offset (drift is impossible by construction). It is *mandatory* precisely in the self-editing case, because the editor and the anchor table share one address space and the editor's own output feeds the next edit's input.
Decision Boundary
The operative decision for the agent is whether a proposed in-place rewrite is *anchor-safe* or must be downgraded to an append-only operation. The boundary:
- If the rewrite's span contains **zero** live anchor targets and shifts offsets by a delta the agent can compute, it is safe **only** with total re-basing in the same commit.
- If the rewrite's span contains **one or more** live anchor targets, it is safe only if the rewrite registers a remap (old target → new target) for each, and the remap is committed atomically. A summary that does not register a remap is a *dangling-anchor generator* and must be rejected.
- If the agent cannot compute the delta (e.g., the rewrite is performed by a sub-model whose output length is not known until generation completes), the rewrite must be staged: generate into a scratch region, compute delta and remaps, then commit as a single splice. In-place generation followed by in-place anchor patching is the anti-pattern.
The guardrail that bounds this: **no anchor may be dereferenced in a turn that follows an uncommitted rewrite.** Enforce this by versioning the buffer and pinning each reasoning step to a buffer version; a rewrite increments the version, and any dereference against a superseded version must fail closed rather than clamp.
Operational Effect
When the invariant is enforced, self-editing remains usable for compaction and redaction at the cost of a per-edit re-basing pass whose size is proportional to the number of live anchors at or after the edit point—cheap relative to the reasoning steps it protects. When it is violated, the observable effect is *silent misattribution*: the agent's outputs remain fluent and internally consistent, but citations, quotes, and evidence chains resolve to the wrong spans. This is more dangerous than truncation because it does not degrade gracefully—it produces confidently wrong provenance that a downstream auditor cannot distinguish from correct provenance without an independent copy of the pre-edit buffer.
The recovery requirement follows: any rewrite that cannot satisfy all three validity conditions must be logged with the pre-edit buffer retained, so that a later verification replay can reconstruct which anchors were live and what they pointed to. Without the retained pre-image, a provenance drift is unrecoverable—the evidence needed to detect it is exactly the evidence the rewrite destroyed.
from dataclasses import dataclass, field
from typing import Dict, List
class ProvenanceDriftError(RuntimeError):
"""Raised when an in-place rewrite would leave anchors stale, dangling, or mis-based."""
pass
@dataclass
class Anchor:
anchor_id: str
position: int # offset of the anchor token itself in the buffer
target: int # offset the anchor points at
@dataclass
class ContextBuffer:
text: str
anchors: Dict[str, Anchor] = field(default_factory=dict)
version: int = 0
def commit_rewrite(
buf: ContextBuffer,
start: int,
end: int,
replacement: str,
remaps: Dict[str, int] | None = None,
) -> ContextBuffer:
"""
Atomically replace buf.text[start:end] with `replacement` and re-base every
anchor. Fails closed if any live anchor target lies inside the rewritten
span and no remap is supplied for it.
"""
remaps = remaps or {}
delta = len(replacement) - (end - start)
# 1. Referent-survival check: every anchor targeting the rewritten span
# must be explicitly remapped, or the commit is rejected.
for aid, a in buf.anchors.items():
if start <= a.target < end and aid not in remaps:
raise ProvenanceDriftError(
f"anchor {aid} targets rewritten span [{start},{end}) "
f"with no remap; commit would produce a dangling anchor"
)
# 2. Build the new anchor table with total re-basing.
new_anchors: Dict[str, Anchor] = {}
for aid, a in buf.anchors.items():
new_pos = a.position if a.position < start else a.position + delta
if start <= a.target < end:
new_target = remaps[aid]
elif a.target >= end:
new_target = a.target + delta
else:
new_target = a.target
new_anchors[aid] = Anchor(aid, new_pos, new_target)
# 3. Single atomic commit: text and anchors advance together.
new_text = buf.text[:start] + replacement + buf.text[end:]
return ContextBuffer(text=new_text, anchors=new_anchors, version=buf.version + 1)
def dereference(buf: ContextBuffer, anchor_id: str, pinned_version: int) -> str:
"""Fail closed if the reasoning step is pinned to a superseded buffer version."""
if pinned_version != buf.version:
raise ProvenanceDriftError(
f"dereference of {anchor_id} against stale version "
f"{pinned_version} (current {buf.version}); refuse to clamp"
)
a = buf.anchors[anchor_id]
if not (0 <= a.target < len(buf.text)):
raise ProvenanceDriftError(
f"anchor {anchor_id} target {a.target} out of bounds "
f"(len={len(buf.text)}); dangling anchor"
)
return buf.text[a.target : a.target + 40]