# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-replay-diverge-when-its-tool-call-transcript-is-re-executed-against-a-live-upstream-the-non-idempotent-read-boundary-in-agent-tra.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-replay-diverge-when-its-tool-call-transcript-is-re-executed-against-a-live-upstream-the-non-idempotent-read-boundary-in-agent-tra.warrant.json
# Markdown SHA-256:   9fbb323121130dec20a63ec73e74ebdf58ed8a120aa51ae736793f324b59828f
# Code AST SHA-256:   b9346986f4e7d5067e50076207deb2e4c32470b6cf80ecda8c7e630ed8932387
# Verified Classes:   ReplayAttributionError, Provenance, ReplayStep, ReplayLedger
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Any


class ReplayAttributionError(RuntimeError):
    """Raised when a replay step cannot be causally attributed to the model."""


class Provenance(Enum):
    FROZEN = "frozen"                # served from persisted transcript
    IDEMPOTENT_LIVE = "idempotent"   # re-executed, tool declared pure
    NONIDEMPOTENT_LIVE = "mutable"   # re-executed, tool is mutable
    MISSING = "missing"              # retention expired, no result


@dataclass
class ReplayStep:
    turn: int
    context_hash: str
    tool_call: dict[str, Any]
    recorded_result_hash: str | None
    replayed_result_hash: str | None
    provenance: Provenance


@dataclass
class ReplayLedger:
    steps: list[ReplayStep] = field(default_factory=list)
    fork_root: int | None = None

    def record(self, step: ReplayStep) -> None:
        if self.fork_root is not None:
            # once forked, every subsequent step is counterfactual
            step.provenance = Provenance.NONIDEMPOTENT_LIVE if step.provenance is not Provenance.MISSING else step.provenance
        self.steps.append(step)
        if self.fork_root is None and self._is_fork(step):
            self.fork_root = step.turn

    @staticmethod
    def _is_fork(step: ReplayStep) -> bool:
        if step.provenance is Provenance.FROZEN:
            return False
        if step.provenance is Provenance.MISSING:
            return True
        if step.provenance is Provenance.NONIDEMPOTENT_LIVE:
            # mutable read re-executed: even a hash match is coincidence
            return True
        # IDEMPOTENT_LIVE: fork only if the hash actually differs
        return step.recorded_result_hash != step.replayed_result_hash

    def assert_attributable(self, turn: int) -> None:
        if self.fork_root is not None and turn >= self.fork_root:
            raise ReplayAttributionError(
                f"turn {turn} is downstream of fork root at turn {self.fork_root}; "
                f"divergence here is counterfactual, not evidence of model fault"
            )


def hash_result(payload: Any) -> str:
    return hashlib.sha256(repr(payload).encode()).hexdigest()


def attribute_divergence(
    ledger: ReplayLedger,
    turn: int,
    recorded_args: dict[str, Any],
    replayed_args: dict[str, Any],
) -> str:
    """Classify a tool-argument divergence as attributable or counterfactual."""
    ledger.assert_attributable(turn)
    if recorded_args == replayed_args:
        return "no_divergence"
    return "attributable_model_divergence"
