# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-replay-divergence-when-an-agent-s-tool-call-transcript-is-re-executed-against-a-mutated-environment.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-replay-divergence-when-an-agent-s-tool-call-transcript-is-re-executed-against-a-mutated-environment.warrant.json
# Markdown SHA-256:   554ec2bec02addcbe87c25f6c73e02d4d93d157bad8341589080d07515590c2d
# Code AST SHA-256:   16f5c2bdc42bcbff0d4ae40c7acf8edab8fa227396353b139189db9540f8c877
# Verified Classes:   ReplayDivergenceError, SideEffectInReplayError, ToolClass, RecordedTurn, ReplayState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from enum import Enum


class ReplayDivergenceError(RuntimeError):
    """Raised when a re-executed tool result does not match the recorded digest."""


class SideEffectInReplayError(RuntimeError):
    """Raised when a side-effecting tool is dispatched during replay."""


class ToolClass(Enum):
    READ_ONLY = "read_only"
    SIDE_EFFECTING = "side_effecting"


@dataclass(frozen=True)
class RecordedTurn:
    turn_index: int
    tool_call_id: str
    tool_name: str
    tool_class: ToolClass
    result_digest: str  # sha256 over canonicalized payload, captured at record time


@dataclass
class ReplayState:
    cursor: int = 0
    admitted: list = field(default_factory=list)
    divergences: list = field(default_factory=list)
    branch: str = "authentic"  # or "counterfactual:<turn>:<orig>:<new>"


def canonical_digest(payload: dict) -> str:
    # Strip volatile fields before hashing; stable key order; no whitespace variance.
    volatile = {"timestamp", "request_id", "server_latency_ms"}
    clean = {k: v for k, v in payload.items() if k not in volatile}
    blob = json.dumps(clean, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(blob).hexdigest()


def admit_turn(
    recorded: RecordedTurn,
    reexecuted_payload: dict,
    state: ReplayState,
    *,
    allow_counterfactual: bool,
) -> ReplayState:
    if recorded.turn_index != state.cursor:
        raise ReplayDivergenceError(
            f"cursor {state.cursor} != turn {recorded.turn_index}; "
            "checkpoint resume across unadmitted turns is forbidden"
        )

    if recorded.tool_class is ToolClass.SIDE_EFFECTING:
        raise SideEffectInReplayError(
            f"turn {recorded.turn_index}: {recorded.tool_name} is side-effecting; "
            "must be replayed against a recorded-effect stub, not the live surface"
        )

    actual = canonical_digest(reexecuted_payload)
    if actual != recorded.result_digest:
        state.divergences.append(
            {
                "turn": recorded.turn_index,
                "tool_call_id": recorded.tool_call_id,
                "recorded": recorded.result_digest,
                "actual": actual,
            }
        )
        if not allow_counterfactual:
            raise ReplayDivergenceError(
                f"turn {recorded.turn_index} ({recorded.tool_name}): result digest "
                f"mismatch {recorded.result_digest[:12]} -> {actual[:12]}; "
                "recorded assistant turn consumed evidence that no longer exists"
            )
        # Open a labeled counterfactual branch; downstream recorded turns are discarded.
        state.branch = (
            f"counterfactual:{recorded.turn_index}:"
            f"{recorded.result_digest[:12]}:{actual[:12]}"
        )
        state.cursor = recorded.turn_index + 1
        return state

    state.admitted.append(recorded.turn_index)
    state.cursor = recorded.turn_index + 1
    return state


def replay(
    transcript: list[RecordedTurn],
    reexecute,  # callable(RecordedTurn) -> dict
    *,
    allow_counterfactual: bool = False,
) -> ReplayState:
    state = ReplayState()
    for turn in transcript:
        payload = reexecute(turn)
        state = admit_turn(
            turn, payload, state, allow_counterfactual=allow_counterfactual
        )
        if state.branch != "authentic":
            # Counterfactual branch: stop replaying recorded turns; caller must
            # re-derive all subsequent turns from the model.
            break
    return state
