# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-multi-agent-trajectory-and-the-tool-call-nondeterminism-is-silently-re-sampled-instead-of-pinned.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-replays-a-multi-agent-trajectory-and-the-tool-call-nondeterminism-is-silently-re-sampled-instead-of-pinned.warrant.json
# Markdown SHA-256:   fe1e52c0a58fc3e10785681659ce849ecb9f1e328949d82ecf6f1e729939a1d2
# Code AST SHA-256:   c5abb111c7f4b09be176eb7b2c254ef911c7cc0552b39a083c35a2993a1a25f3
# Verified Classes:   ObservationTapeMismatch, SnapshotUnavailable, TapeEntry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass
from typing import Any


class ObservationTapeMismatch(RuntimeError):
    """Raised when a replayed tool observation does not match the recorded tape."""


class SnapshotUnavailable(RuntimeError):
    """Raised when the pinned model snapshot cannot be resolved for replay."""


@dataclass(frozen=True)
class TapeEntry:
    step_id: int
    tool_name: str
    tool_version: str
    request_hash: str
    response_body: Any
    response_hash: str
    environment_fingerprint: str


def _hash(obj: Any) -> str:
    return hashlib.sha256(
        json.dumps(obj, sort_keys=True, separators=(",", ":")).encode()
    ).hexdigest()


def replay_trajectory(
    tape: list[TapeEntry],
    live_tool_results: dict[int, Any],
    model_snapshot_available: bool,
    allow_counterfactual: bool = False,
) -> list[dict]:
    """
    Replay a recorded multi-agent trajectory against a pinned observation tape.

    The tape is authoritative. Live tool results are only consulted when
    `allow_counterfactual` is set, and even then a mismatch aborts unless the
    caller has explicitly opted into a counterfactual probe (which must be
    reported separately, never as a replay).
    """
    if not model_snapshot_available:
        raise SnapshotUnavailable(
            "Pinned model snapshot is unavailable; replay is advisory only "
            "and may not be used to close an incident."
        )

    replayed: list[dict] = []
    for entry in tape:
        recorded_hash = entry.response_hash
        if entry.step_id in live_tool_results:
            live_body = live_tool_results[entry.step_id]
            live_hash = _hash(live_body)
            if live_hash != recorded_hash:
                if not allow_counterfactual:
                    raise ObservationTapeMismatch(
                        f"Step {entry.step_id} ({entry.tool_name}@{entry.tool_version}) "
                        f"replayed observation hash {live_hash[:12]} != recorded "
                        f"{recorded_hash[:12]}. Trajectory divergence is attributable "
                        f"to the observation tape, not the agent policy. Aborting "
                        f"attribution."
                    )
                replayed.append(
                    {
                        "step_id": entry.step_id,
                        "mode": "counterfactual",
                        "recorded_hash": recorded_hash,
                        "perturbed_hash": live_hash,
                    }
                )
                continue
        replayed.append(
            {
                "step_id": entry.step_id,
                "mode": "replay",
                "recorded_hash": recorded_hash,
                "response_body": entry.response_body,
            }
        )
    return replayed


def attribute_divergence(
    tape: list[TapeEntry],
    live_tool_results: dict[int, Any],
    model_snapshot_available: bool,
) -> str:
    """
    Classify the source of a trajectory divergence. Returns 'agent_policy'
    only when the tape is fully faithful; otherwise raises.
    """
    try:
        replay_trajectory(
            tape=tape,
            live_tool_results=live_tool_results,
            model_snapshot_available=model_snapshot_available,
            allow_counterfactual=False,
        )
    except ObservationTapeMismatch as exc:
        # Tape is not faithful: attribution to agent policy is forbidden.
        raise ObservationTapeMismatch(
            "Refusing to attribute divergence to agent policy: "
            "observation tape is not faithful. " + str(exc)
        ) from exc
    return "agent_policy"
