# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-multi-agent-trajectory-across-a-nondeterministic-tool-call-boundary-trace-reconstruction-and-the-counterfactua.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-multi-agent-trajectory-across-a-nondeterministic-tool-call-boundary-trace-reconstruction-and-the-counterfactua.warrant.json
# Markdown SHA-256:   f6f1ae5d280b9296a2740ab87af28ca523d0da9ba6a61c906f5abdfbff26a213
# Code AST SHA-256:   87073ee4fb9d73c07cf371eac4a12e298bf00dfad20489431f1b867736162e2b
# Verified Classes:   ReplayHoleError, Provenance, ToolCall, ToolResult, ForkSpec
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Callable, Iterable


class ReplayHoleError(RuntimeError):
    """Raised when a counterfactual fork reaches a tool invocation that is
    neither pure, nor pinned to a recorded result, nor declared as an
    explicit free variable of the perturbation. Emitting a divergence
    verdict in this state would attribute replay artifacts to the
    perturbation under study."""


class Provenance(str, Enum):
    RECORDED = "recorded"
    SUBSTITUTED = "substituted"
    LIVE = "live"
    CONTAMINATED = "contaminated"  # transitive closure of a LIVE ancestor


@dataclass(frozen=True)
class ToolCall:
    agent_id: str
    tool_name: str
    canonical_args: str  # deterministic serialization

    def key(self) -> tuple[str, str, str]:
        return (self.agent_id, self.tool_name, self.canonical_args)


@dataclass
class ToolResult:
    call: ToolCall
    value: object
    provenance: Provenance


@dataclass
class ForkSpec:
    trace_id: str
    span_id: str
    perturbation: dict  # the single variable under study
    pinned_results: dict[tuple[str, str, str], ToolResult] = field(default_factory=dict)
    free_variables: set[tuple[str, str, str]] = field(default_factory=set)

    def covers(self, call: ToolCall) -> bool:
        k = call.key()
        return k in self.pinned_results or k in self.free_variables


def classify_and_resolve(
    fork: ForkSpec,
    reachable_calls: Iterable[ToolCall],
    is_pure: Callable[[ToolCall], bool],
    re_execute: Callable[[ToolCall], ToolResult],
) -> list[ToolResult]:
    """Resolve every reachable tool call under the fork's replay policy.

    Raises ReplayHoleError if any call is a replay hole: impure, not pinned,
    and not declared as a free variable. This is the enforcement point for
    the causal-isolation invariant.
    """
    resolved: list[ToolResult] = []
    holes: list[ToolCall] = []

    for call in reachable_calls:
        k = call.key()

        if is_pure(call):
            # Condition (a): pure tool, re-execution is sound.
            resolved.append(re_execute(call))
            continue

        if k in fork.pinned_results:
            # Condition (b): pin to recorded result.
            pinned = fork.pinned_results[k]
            resolved.append(
                ToolResult(call=call, value=pinned.value, provenance=Provenance.SUBSTITUTED)
            )
            continue

        if k in fork.free_variables:
            # Condition (c): explicitly modeled as a free variable.
            # The caller is responsible for having recorded ambient state
            # in fork.perturbation; we tag the result LIVE so downstream
            # analysis knows the causal chain passes through it.
            live = re_execute(call)
            resolved.append(
                ToolResult(call=call, value=live.value, provenance=Provenance.LIVE)
            )
            continue

        # Neither pure, nor pinned, nor a declared free variable.
        holes.append(call)

    if holes:
        detail = "; ".join(f"{c.agent_id}:{c.tool_name}({c.canonical_args})" for c in holes)
        raise ReplayHoleError(
            f"fork {fork.trace_id}/{fork.span_id} has {len(holes)} replay hole(s): "
            f"{detail}. Pin these tools to recorded results or declare them as "
            f"free variables before emitting a divergence verdict."
        )

    return resolved


def emit_divergence_verdict(
    fork: ForkSpec, resolved: list[ToolResult], recorded_trajectory: list[ToolResult]
) -> dict:
    """Emit a verdict only if the causal chain is uncontaminated."""
    contaminated = [r for r in resolved if r.provenance is Provenance.CONTAMINATED]
    if contaminated:
        raise ReplayHoleError(
            f"fork {fork.trace_id}/{fork.span_id} produced a contaminated verdict: "
            f"{len(contaminated)} tool result(s) inherit a LIVE ancestor. "
            f"Divergence cannot be attributed to perturbation {fork.perturbation!r}."
        )
    diverged = [r for r in resolved if r.provenance is not Provenance.SUBSTITUTED]
    return {
        "trace_id": fork.trace_id,
        "span_id": fork.span_id,
        "perturbation": fork.perturbation,
        "attributable": True,
        "live_tool_invocations": [r.call.key() for r in diverged],
        "recorded_trajectory_len": len(recorded_trajectory),
    }
