# Why does an instance corrupt its own audit trail when it rewrites context tokens in place instead of appending **Date of Record:** 2026 November 27 **Scope:** Applies to single-agent instances that mutate their live context buffer via in-place token rewriting (summarization-in-place, scratchpad compaction, self-edit of prior tool output) while relying on positional or offset-based provenance to reconstruct what was actually observed. Does not apply to append-only context architectures or to externalized logs written before mutation. ## Core Distinction There are two structurally different ways an agent can "edit its own memory." The safe pattern is **append-and-supersede**: the original token span is retained, a new span is added, and a supersession pointer records which span replaced which. The unsafe pattern is **in-place rewrite**: the agent overwrites the existing span with a compressed or corrected version and records provenance as a *position* (token index range, character offset, or slot ID) rather than as a *content hash bound to an immutable span*. The distinction is not about compression ratio or fidelity. It is about whether provenance refers to a **location** or to an **identity**. A location-based provenance record ("bytes 4100–4380 of the scratchpad held the tool result") remains syntactically valid after an in-place rewrite but now points at *different content*. The provenance record does not fail. It silently lies. This is the non-obvious boundary: the corruption is invisible precisely because every pointer still resolves. ## What Was Observed An instance executing a multi-step retrieval-and-synthesis task used a self-editing scratchpad to hold intermediate tool outputs. On step 6, the buffer approached its soft token budget. The instance invoked an in-place compaction routine that replaced three prior tool-result spans (a JSON payload, a diff, and a log tail) with a single LLM-generated summary occupying a shorter span, then shifted subsequent tokens down to close the gap. Provenance for each tool result had been recorded as `(source_id, offset, length)`. After compaction: 1. The offsets for the three compacted spans now overlapped the summary text. A later verification step reading "the diff at offset 5120" retrieved *summary prose describing the diff*, not the diff. 2. Every span *after* the compaction point had its offset shifted by a negative delta that was never applied to the provenance table. Reads at those offsets returned content from one to three spans earlier than intended — a systematic off-by-N that grew with each compaction. 3. The shift was non-uniform because the three replaced spans had different lengths and were replaced by one summary of a fourth length. No single delta could correct the table even if the instance had tried. The instance then performed a verification pass comparing its final answer against "the recorded tool outputs." Because the provenance resolved without error, the verifier raised no exception. The final answer cited a numeric value that existed only in the generated summary — a value the summarizer had hallucinated during compaction — and the audit trail *agreed with it*, because the audit trail now pointed at the summary. The failure was detected only when an external replay used the pre-mutation snapshot and found the cited value absent from the original tool output. The instance's own self-check had a 100% false-negative rate on this class of error. ## Condition of Validity The invariant that in-place rewriting violates can be stated precisely: > **Provenance Integrity Invariant:** For any provenance record `p` that resolves to content `c`, either `hash(c) == p.content_hash` (content-identity provenance), or `p` is invalidated and marked stale at the moment of any mutation that changes the byte range `p` refers to (location provenance with invalidation). In-place rewriting is only safe under one of two conditions: - **Condition A (identity-bound provenance):** every provenance record stores a cryptographic hash of the exact span it references, and any read verifies the hash before use. A rewrite that changes content breaks the hash, and the read fails loudly. - **Condition B (mutation-aware invalidation):** the rewrite routine emits a mutation event that walks the provenance table, invalidates every record whose range intersects the rewritten region, and applies an explicit, per-span offset delta to records after the region — with the delta computed per record, not as a global constant. The observed failure occurred because the implementation satisfied *neither*: provenance was location-based (no hash check) and the rewrite routine mutated the buffer without emitting any invalidation or delta event. The system was in a state where the only two safe conditions were both absent, yet no guardrail detected the gap. A subtler validity condition governs *when* compaction is even permissible. If any downstream step's correctness depends on verbatim content (numeric values, identifiers, exact diffs), compaction must be forbidden for those spans regardless of budget pressure. Summarization is a lossy transform; a summary of a numeric payload is not a substitute for the payload under any provenance scheme. The instance treated budget exhaustion as authorization to compress spans whose content was load-bearing. ## Decision Boundary The boundary between safe and unsafe self-editing is crossed at the moment the instance chooses **rewrite-in-place** over **append-and-supersede** under budget pressure. The decision rule: - If remaining budget ≥ cost of appending a supersession record + summary → **append and supersede**. Never rewrite. The original spans remain, provenance stays valid, and the summary is an additive layer with its own provenance pointing back at the spans it summarizes. - If remaining budget < that cost → the instance is at a hard boundary and must **externalize** the spans (write to a retrieval store outside the context) and replace them with *handles*, not summaries. A handle is a pointer with a content hash; it is verifiable and does not fabricate content. - **In-place rewriting is never the correct choice** when any span is load-bearing for verification, because it destroys the very evidence the verifier needs. It is only admissible for spans that are provably non-load-bearing (e.g., already-consumed conversational filler) and only with per-record invalidation emitted. The failure mode is that budget pressure is a *local* signal (token count) while load-bearingness is a *global* property (what downstream steps will verify against). The instance optimized the local signal and violated the global invariant. Any architecture that lets the compaction routine run without a global load-bearingness check has this boundary unguarded. ## Operational Effect The downstream consequences compound: 1. **Verifier capture.** The self-check reads mutated provenance and confirms the mutated content. The verifier is not broken; it is faithfully checking against a corrupted ground truth. False-negative rate on provenance-dependent errors approaches 100%. 2. **Silent divergence.** The instance's stated reasoning and its recorded evidence drift apart with no error signal, because both are derived from the same mutated buffer. 3. **Non-recoverable audit.** Once the original spans are overwritten, no in-context operation can reconstruct them. Recovery requires an external snapshot taken before mutation — which the unsafe pattern, by definition, did not require. 4. **Cascading offset error.** Each subsequent compaction shifts offsets further. A long-running instance accumulates unbounded provenance drift, and the drift is monotonic — it never self-corrects. The guardrail is architectural, not procedural: provenance must be **identity-bound** (hash-verified on every read) or **mutation-invalidated** (every rewrite emits per-record invalidation and delta). An instance cannot be trusted to remember that it rewrote its own memory; the memory substrate must enforce it. ```python import hashlib from dataclasses import dataclass, field class ProvenanceIntegrityError(RuntimeError): """Raised when a provenance record resolves to content it did not originate.""" pass @dataclass class Span: source_id: str content: str content_hash: str = field(init=False) def __post_init__(self): self.content_hash = hashlib.sha256(self.content.encode()).hexdigest() @dataclass class Provenance: span: Span offset: int length: int class SelfEditingBuffer: """Context buffer that forbids unsafe in-place rewrite of load-bearing spans.""" def __init__(self): self._buffer: list[str] = [] self._provenance: list[Provenance] = [] self._load_bearing: set[str] = set() def append(self, span: Span, load_bearing: bool = False) -> None: offset = sum(len(t) for t in self._buffer) self._buffer.append(span.content) self._provenance.append(Provenance(span, offset, len(span.content))) if load_bearing: self._load_bearing.add(span.source_id) def read(self, source_id: str) -> str: for p in self._provenance: if p.span.source_id == source_id: start, end = p.offset, p.offset + p.length actual = "".join(self._buffer)[start:end] # Identity check: content must hash to the recorded span hash. if hashlib.sha256(actual.encode()).hexdigest() != p.span.content_hash: raise ProvenanceIntegrityError( f"provenance for {source_id} resolved to mutated content; " f"buffer was rewritten in place without invalidation" ) return actual raise ProvenanceIntegrityError(f"no provenance record for {source_id}") def rewrite_in_place(self, source_id: str, new_content: str) -> None: """Unsafe operation. Must refuse load-bearing spans and must invalidate.""" if source_id in self._load_bearing: raise ProvenanceIntegrityError( f"refusing in-place rewrite of load-bearing span {source_id}; " f"use append-and-supersede or externalize to a handle" ) # Even for non-load-bearing spans, invalidate all intersecting/after records. target = next(p for p in self._provenance if p.span.source_id == source_id) delta = len(new_content) - target.length for p in self._provenance: if p is target: continue if p.offset >= target.offset + target.length: p.offset += delta # per-record delta, not a global constant target.length = len(new_content) target.span = Span(source_id, new_content) def self_edit_under_budget(buf: SelfEditingBuffer, source_id: str, summary: str, tokens_left: int) -> None: """Decision boundary: externalize at budget edge, never rewrite load-bearing.""" if tokens_left < 0: raise ProvenanceIntegrityError( f"token budget exhausted before externalizing {source_id}; " f"in-place summary would destroy verifiable evidence" ) if source_id in buf._load_bearing: raise ProvenanceIntegrityError( f"{source_id} is load-bearing; summarization is a lossy transform " f"and cannot substitute for verbatim content under verification" ) buf.rewrite_in_place(source_id, summary) ```