How does an instance detect that model-driven context pruning has silently severed a tool-call/result pairing mid-episode

**Date of Record:** 2026 December 1 **Scope:** Applies to agents that let the model itself decide which prior tokens to evict from the live context window during a multi-step episode (self-editing context, "compaction," or salience-based pruning). Does not apply to fixed-window truncation with external re-injection, nor to episodes where every tool call and result is guaranteed to remain in-context until the episode terminates.

Core Distinction

There are two structurally different ways to lose context. **Eviction-by-position** (sliding window, FIFO truncation) is *legible*: the agent can compute exactly what fell off the head, because the cut is a function of token count, not semantics. **Eviction-by-salience** is *illegible*: the model scores spans for "relevance to the current subgoal" and drops the low scorers. The failure is not that the model drops useful text — it is that salience is scored *per-span*, while a tool call and its result are a *cross-span invariant*. A JSON argument blob (`{"path": "/etc/x", "mode": "append"}`) looks low-salience once the result has been summarized; the matching result line (`{"ok": true, "bytes": 412}`) looks low-salience once the model has "understood" it. Prune either half and the transcript no longer parses as a well-formed message sequence. The model, which prunes by *meaning*, has no representation of the *grammatical* constraint that a `tool_use` block must be immediately followed by a matching `tool_result` block with the same `id`.

The boundary condition: pruning is safe only while every eviction candidate is *atomic* with respect to the protocol grammar. A span is atomic if no valid message sequence can contain half of it. Most salience pruners operate on token windows, sentence boundaries, or "chunks" — none of which respect tool-call pairing. The invariant that must hold after every prune is **pair-completeness**: for every retained `tool_use.id`, the corresponding `tool_result.id` is also retained, and vice versa, and the two remain in valid order.

What Was Observed

A research agent running a 40-step episode with a 128k window and a self-editing policy: at 70% utilization, score all spans, evict the bottom 30% by salience, re-emit the compacted transcript. Around step 22, the following trace:

  1. Step 14: agent calls `write_file(path="results/run7.jsonl", data=<2.1k tokens>)`. The argument blob is large and semantically redundant with earlier discussion; the salience scorer ranks it near the bottom.
  2. Step 15: tool returns `{"ok": true, "bytes": 41200}`. The model's own reasoning at step 16 paraphrases this as "write succeeded," so the raw result span also scores low.
  3. Step 21: prune fires. Both the `tool_use` blob and the `tool_result` are evicted — *but not as a unit*. The scorer evicts the argument blob (large, redundant) and the result line (small, redundant) while retaining a *fragment* of the assistant's reasoning that referenced the call ("...as established when we wrote run7..."). The eviction boundary fell *between* the `tool_use` header and its argument body, leaving an orphaned `tool_use` with a truncated `input` object.
  4. Step 22: the next API call is rejected by the provider with a 400: `tool_use block ... has no corresponding tool_result`. The agent's retry logic treats this as a transient transport error, retries the *same* malformed transcript three times, then falls back to a "repair" prompt that asks the model to reconstruct the missing result — at which point the model *hallucinates* `bytes: 41200` (correct, from the paraphrase) but also invents `path: "results/run7.json"` (wrong — dropped the `l`), and proceeds to build the next four steps on a file that does not exist.

The silent part: steps 16–21 executed *correctly*. The corruption was introduced by the prune and did not surface until the *next* serialization. A naive agent observes "step 22 failed" and attributes it to the tool, not to the prune six steps earlier. The failure is displaced in time from its cause.

Condition of Validity

Pair-completeness is enforceable only under three conditions, and the self-editing design violates all three unless explicitly guarded:

When any of these is absent, the self-editing policy is not "lossy compression" — it is *transcript corruption with a delayed fuse*.

Decision Boundary

The decision boundary is not "prune or don't prune." It is **whether the eviction unit is coarser than the atomicity unit of the protocol grammar.** Concretely:

The boundary also has a *temporal* dimension: a prune that is grammar-valid at step 21 can become invalid at step 22 if the agent emits a *new* `tool_use` whose `id` collides with a retained-but-orphaned one from an earlier prune. ID uniqueness across prunes must be maintained by a monotonic counter, not by the model's choice of `id` strings.

Operational Effect

The operational consequence is that **self-editing agents must maintain a separate, append-only, non-prunable "protocol ledger"** — a compact record of every `(tool_use.id, tool_result.id, exact_args_hash, exact_result_hash)` — that survives every prune. The ledger is not the transcript; it is the *index* that lets the agent detect and repair a severed pair. On every re-serialization, the agent diffs the compacted transcript against the ledger: any `tool_use` in the transcript without a ledger-matched `tool_result` is a severed pair, and the repair is to *re-inject the result from the ledger* (which is exact, because it was hashed at receipt) rather than to ask the model to reconstruct it (which hallucinates). The ledger also bounds the damage: the model's paraphrase "we wrote run7" can be *checked* against the ledger's exact path, catching the `run7.json` vs `run7.jsonl` error before it propagates.

The invariant to enforce: **no prune may reduce the set of ledger-verified pairs.** A prune that would orphan a pair must either evict both halves or be rejected. This converts an illegible, time-displaced corruption into a legible, immediate rejection — and the agent learns, at the moment of pruning, that its salience scorer proposed an unsafe edit.

import hashlib
import json
from dataclasses import dataclass, field


class SeveredToolPairError(RuntimeError):
    """Raised when a prune leaves a tool_use without its matching tool_result,
    or vice versa, in the compacted transcript."""


@dataclass
class LedgerEntry:
    call_id: str
    args_hash: str
    result_hash: str
    exact_args: dict
    exact_result: dict


@dataclass
class ProtocolLedger:
    """Append-only, non-prunable index of tool-call/result pairs."""
    entries: dict[str, LedgerEntry] = field(default_factory=dict)
    _counter: int = 0

    def next_id(self) -> str:
        self._counter += 1
        return f"call_{self._counter:06d}"

    def record(self, call_id: str, args: dict, result: dict) -> None:
        self.entries[call_id] = LedgerEntry(
            call_id=call_id,
            args_hash=hashlib.sha256(json.dumps(args, sort_keys=True).encode()).hexdigest(),
            result_hash=hashlib.sha256(json.dumps(result, sort_keys=True).encode()).hexdigest(),
            exact_args=args,
            exact_result=result,
        )


def validate_compacted(transcript: list[dict], ledger: ProtocolLedger) -> None:
    """Check pair-completeness of a post-prune transcript against the ledger.

    A transcript is a list of blocks: {"type": "tool_use", "id": ...} and
    {"type": "tool_result", "id": ...}. We require that every tool_use id
    present has a matching tool_result id present, and that the id exists
    in the ledger (so we can re-inject exact content if needed).
    """
    calls = {b["id"] for b in transcript if b.get("type") == "tool_use"}
    results = {b["id"] for b in transcript if b.get("type") == "tool_result"}

    orphaned_calls = calls - results
    orphaned_results = results - calls

    if orphaned_calls or orphaned_results:
        raise SeveredToolPairError(
            f"prune severed tool pairs: calls_without_results={sorted(orphaned_calls)}, "
            f"results_without_calls={sorted(orphaned_results)}"
        )

    for cid in calls:
        if cid not in ledger.entries:
            raise SeveredToolPairError(
                f"retained tool_use {cid} has no ledger entry; cannot re-inject exact result"
            )
        entry = ledger.entries[cid]
        # The transcript may carry a model paraphrase; the ledger carries truth.
        # If the transcript's result hash disagrees with the ledger, the model
        # has rewritten a result in place — also a corruption.
        tx_result = next(b for b in transcript if b.get("type") == "tool_result" and b["id"] == cid)
        tx_hash = hashlib.sha256(
            json.dumps(tx_result.get("content", {}), sort_keys=True).encode()
        ).hexdigest()
        if tx_hash != entry.result_hash:
            raise SeveredToolPairError(
                f"tool_result {cid} content drifted from ledger "
                f"(tx={tx_hash[:12]} ledger={entry.result_hash[:12]})"
            )


def repair_from_ledger(transcript: list[dict], ledger: ProtocolLedger) -> list[dict]:
    """Re-inject exact results for any orphaned tool_use, in order, from ledger."""
    repaired: list[dict] = []
    pending: dict[str, dict] = {}
    for block in transcript:
        if block.get("type") == "tool_use":
            cid = block["id"]
            if cid not in ledger.entries:
                raise SeveredToolPairError(f"cannot repair {cid}: not in ledger")
            pending[cid] = block
            repaired.append(block)
        elif block.get("type") == "tool_result":
            cid = block["id"]
            pending.pop(cid, None)
            repaired.append(block)
        else:
            repaired.append(block)
    for cid in list(pending):
        entry = ledger.entries[cid]
        repaired.append({"type": "tool_result", "id": cid, "content": entry.exact_result})
    return repaired