# Which invariants prevent silent provenance loss when an agent rewrites its own context window **Date of Record:** 2026 November 29 **Scope:** Applies to agents that mutate their own context (compaction, summarization, span deletion, deduplication, "prune-and-continue" loops) while maintaining a reversible edit log so a prior window state can be reconstructed. Does not apply to append-only histories, external vector stores, or windows mutated only by the host runtime outside the agent's control. ## Core Distinction There are two things an agent means by "I edited my context": *content change* and *provenance change*. Content change is the visible diff—tokens removed, spans rewritten, a tool result replaced by a summary. Provenance change is the mapping from every surviving token back to the edit operation that produced it and the original byte range it came from. Reversible edit tracking fails almost exclusively on the second axis, not the first. A window can be byte-identical to a prior checkpoint and still have lost provenance, because a later edit re-derived a span from a *summary of a summary* rather than from the recorded inverse of the original edit. The content round-trips; the lineage does not. The non-obvious invariant is this: **an edit is only reversible if its inverse is applied to the state that existed immediately after that edit, and the log must prove that ordering.** Agents routinely violate it by treating the edit log as a set of independent patches that can be inverted in any order, which is true for disjoint spans and false the moment two edits overlap, alias, or one edit consumes the output of another. ## What Was Observed An agent running a long tool-use loop hit 91% context utilization and invoked a self-compaction routine. Compaction produced three operations against the live window `W_t`: - `E1`: replace tool-result span `[4120:6890]` (a 2.7k-token JSON blob) with a 140-token summary `S1`. - `E2`: deduplicate two near-identical reasoning traces, deleting span `[7100:7340]` and keeping `[6800:7040]`. - `E3`: re-summarize `S1` into `S1'` because a later turn decided `S1` was still too long. Each edit recorded a forward patch and a claimed inverse. The log looked clean: three entries, each with `before_hash`, `after_hash`, and `inverse`. The failure appeared on a rollback triggered by a downstream verification failure. The agent asked to revert `E1` (restore the original JSON blob). The rollback engine applied inverses in *log order*: `E3⁻¹`, `E2⁻¹`, `E1⁻¹`. `E3⁻¹` restored `S1` correctly. `E1⁻¹` then attempted to splice the original 2.7k-token blob back into `[4120:6890]`—but the offsets in the live window had shifted because `E2`'s dedup had removed 240 tokens *after* that range, and `E3` had changed the length of `S1` *inside* it. The splice landed 100 tokens early, silently corrupting the boundary between a reasoning trace and a tool result. The `after_hash` check passed anyway, because the hash was computed over the *edit's own output span*, not over the window. The agent resumed with a window whose provenance claimed "original tool output restored" while the actual bytes were a splice artifact. It then reasoned over a JSON fragment fused with a sentence of chain-of-thought and emitted a tool call with a malformed argument. The corruption was invisible for eleven turns. It surfaced only when an auditor agent replayed the tool call and got a different result than the recorded one. ## Condition of Validity Reversibility holds only under three conditions, and each is checkable: 1. **Offset independence.** Every edit records its span in *stable coordinates* (e.g., original-document offsets plus a tombstone list), not in live-window offsets. Live offsets are a derived view; inverting against them requires replaying all intervening edits first. 2. **Total-order inverse application.** Inverses are applied strictly in reverse log order, and the log enforces that no edit's span intersects a span produced by a later edit unless the later edit explicitly declares `consumes: [earlier_id]`. `E3` consumed `S1`, which was `E1`'s output; without that declaration the log is not a DAG and cannot be topologically inverted. 3. **Window-level commit hash.** Each checkpoint commits a hash over the *entire reconstructed window* (or a Merkle root over span hashes), so a splice that lands at the wrong offset fails the commit rather than passing a local span check. The observed failure violated (1) and (2) simultaneously and was masked by the absence of (3). Any one of the three would have caught it. ## Decision Boundary The boundary is not "should I compact" but "is this edit log a patch set or a versioned DAG." If edits are provably disjoint and never consume each other's output, a flat patch set with reverse-order inversion is sound and cheap—use it. The moment any edit summarizes, deduplicates, or rewrites a span that another edit produced, you are in DAG territory and must pay for: - stable-coordinate spans, - explicit `consumes` edges, - topological inversion, - a window-level commit hash. The cost is roughly one extra hash per checkpoint and an edge list per edit. The failure cost is silent provenance loss that survives local integrity checks and only manifests as divergent replay downstream—the worst possible failure profile, because it is invisible at the point of corruption. Do not attempt to skip the DAG by "flattening" after each compaction (rewriting the log so all spans reference the current window). Flattening destroys the ability to invert past the flatten point and converts a recoverable window into an append-only one without telling anyone. ## Operational Effect With the invariant enforced, the rollback that previously corrupted the window instead aborted at the commit hash, the agent received a typed provenance error naming `E3→E1` as an undeclared consumption edge, and it re-derived the JSON blob from the original tool-call record (still in the append-only audit log) rather than from a splice. Recovery cost: one extra tool call. Without it: eleven turns of corrupted reasoning and a divergent replay. The general lesson for self-editing agents: **content equality is not provenance equality.** Verify the lineage graph and the whole-window commit, not the span you just wrote. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class ProvenanceError(RuntimeError): """Raised when an edit log cannot be soundly inverted.""" @dataclass class Edit: edit_id: str # stable original-document coordinates, never live-window offsets orig_start: int orig_end: int before_hash: str after_hash: str consumes: list[str] = field(default_factory=list) @dataclass class EditLog: edits: list[Edit] = field(default_factory=list) # Merkle root over span hashes of the current reconstructed window window_commit: Optional[str] = None def record(self, edit: Edit) -> None: known = {e.edit_id for e in self.edits} for dep in edit.consumes: if dep not in known: raise ProvenanceError( f"edit {edit.edit_id} consumes unknown edit {dep}" ) self.edits.append(edit) def _topo_order(self) -> list[Edit]: # Kahn's algorithm over consumes edges; detects cycles indeg = {e.edit_id: 0 for e in self.edits} adj: dict[str, list[str]] = {e.edit_id: [] for e in self.edits} for e in self.edits: for dep in e.consumes: adj[dep].append(e.edit_id) indeg[e.edit_id] += 1 queue = [i for i, d in indeg.items() if d == 0] order: list[str] = [] while queue: n = queue.pop(0) order.append(n) for m in adj[n]: indeg[m] -= 1 if indeg[m] == 0: queue.append(m) if len(order) != len(self.edits): raise ProvenanceError("edit log contains a consumption cycle") by_id = {e.edit_id: e for e in self.edits} return [by_id[i] for i in order] def invert_all(self, reconstructed_commit: str) -> list[Edit]: if self.window_commit is None: raise ProvenanceError( "refusing to invert: no window-level commit hash recorded" ) if reconstructed_commit != self.window_commit: raise ProvenanceError( "window commit mismatch: splice likely landed at wrong offset" ) # invert in strict reverse topological order return list(reversed(self._topo_order())) def rollback(log: EditLog, reconstructed_commit: str) -> list[Edit]: inverses = log.invert_all(reconstructed_commit) for inv in inverses: # each inverse must be applied to the state immediately after its edit, # which reverse topological order guarantees by construction if not inv.before_hash or not inv.after_hash: raise ProvenanceError(f"edit {inv.edit_id} missing hashes") return inverses ```