# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-recorded-agentic-session-and-the-tool-layer-is-not-hermetic-counterfactual-drift-in-forensic-reconstruction.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-recorded-agentic-session-and-the-tool-layer-is-not-hermetic-counterfactual-drift-in-forensic-reconstruction.warrant.json
# Markdown SHA-256:   b609ce85596f68d021421966d786a1dc143cfc20922a4a0a30903e9f366d7ea0
# Code AST SHA-256:   a350f87cac0d3a49cab7a15695ceeb45fcd2b1c145818a8199d4fc40db581791
# Verified Classes:   ReplayContamination, TapeMiss, ToolCall, RecordedResult, ContaminationLedger, HermeticReplayHarness
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any, Callable, Optional


class ReplayContamination(RuntimeError):
    """Raised when a counterfactual replay diverges outside the declared intervention set."""
    pass


class TapeMiss(ReplayContamination):
    """Raised when a non-intervention tool call has no recorded result to serve."""
    pass


@dataclass
class ToolCall:
    name: str
    args: dict


@dataclass
class RecordedResult:
    call: ToolCall
    value: Any


@dataclass
class ContaminationLedger:
    entries: list = field(default_factory=list)

    def record(self, call: ToolCall, recorded: Any, replayed: Any, intervened: bool) -> None:
        self.entries.append({
            "tool": call.name,
            "args": call.args,
            "recorded": recorded,
            "replayed": replayed,
            "intervened": intervened,
        })

    def non_intervention_divergences(self) -> list:
        return [e for e in self.entries
                if not e["intervened"] and e["recorded"] != e["replayed"]]


class HermeticReplayHarness:
    """
    Serves every tool call from the recorded tape unless the call is in the
    declared intervention set. Live execution is permitted ONLY for declared
    interventions; a tape miss on a non-intervention call is a hard failure.
    """

    def __init__(
        self,
        tape: dict,                       # tape_key(call) -> RecordedResult
        live_tools: dict,                 # tool_name -> Callable[[dict], Any]
        interventions: set,               # set of tape_keys declared as counterfactual
        ledger: Optional[ContaminationLedger] = None,
    ):
        self.tape = tape
        self.live_tools = live_tools
        self.interventions = interventions
        self.ledger = ledger or ContaminationLedger()

    @staticmethod
    def _key(call: ToolCall) -> tuple:
        return (call.name, tuple(sorted(call.args.items())))

    def invoke(self, call: ToolCall) -> Any:
        key = self._key(call)
        intervened = key in self.interventions

        if intervened:
            tool = self.live_tools.get(call.name)
            if tool is None:
                raise ReplayContamination(
                    f"intervention declared for {call.name} but no live tool registered"
                )
            replayed = tool(call.args)
            recorded = self.tape[key].value if key in self.tape else None
            self.ledger.record(call, recorded, replayed, intervened=True)
            return replayed

        if key not in self.tape:
            raise TapeMiss(
                f"non-intervention call {call.name}{call.args} has no recorded result; "
                f"refusing live execution (would contaminate the counterfactual)"
            )

        recorded = self.tape[key].value
        self.ledger.record(call, recorded, recorded, intervened=False)
        return recorded

    def certify(self) -> None:
        """Call after replay: reject the audit if any non-intervention call diverged."""
        bad = self.ledger.non_intervention_divergences()
        if bad:
            raise ReplayContamination(
                f"counterfactual replay contaminated: {len(bad)} non-intervention "
                f"divergence(s), first={bad[0]['tool']}{bad[0]['args']}"
            )
