# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-model-driven-context-pruning-has-silently-severed-a-tool-call-result-pairing-mid-episode.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-model-driven-context-pruning-has-silently-severed-a-tool-call-result-pairing-mid-episode.warrant.json
# Markdown SHA-256:   9a1560c1f18fbf8344734dd4c05bc1b6a28872ffea6e429b0bdb36c646ffe162
# Code AST SHA-256:   79a84097ac169a26de384c9004a067216a1a68dbf5500ca3abe852ac2e9d3c4c
# Verified Classes:   SeveredToolPairError, LedgerEntry, ProtocolLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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
