# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-replay-divergence-in-agentic-forensic-reconstruction-the-non-idempotent-tool-call-shadow.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-replay-divergence-in-agentic-forensic-reconstruction-the-non-idempotent-tool-call-shadow.warrant.json
# Markdown SHA-256:   fae4189432f1d19f066c9b3548f1dc291b643f507d0f79a3a778c46fd13692a9
# Code AST SHA-256:   c436f9d11dc2f151e3cacff66328a842cf8ac5b1a2830e947b3c2d5b0e294be6
# Verified Classes:   ToolPurity, ReplayDivergenceError, ToolCall, Trace
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Optional


class ToolPurity(Enum):
    REPLAY_PURE = "replay_pure"
    IMPURE_READ = "impure_read"
    IMPURE_WRITE = "impure_write"
    UNCLASSIFIED = "unclassified"


class ReplayDivergenceError(RuntimeError):
    """Raised when a trace cannot be faithfully replayed for forensic attribution."""


@dataclass
class ToolCall:
    name: str
    purity: ToolPurity
    shadow_input_recoverable: bool = True  # only meaningful for IMPURE_READ


@dataclass
class Trace:
    calls: list[ToolCall]
    incident_timestamp_ns: int


def audit_replay_safety(trace: Trace) -> None:
    """Gate forensic replay on tool-surface purity.

    Raises ReplayDivergenceError if the trace cannot support faithful replay.
    """
    unclassified = [c.name for c in trace.calls if c.purity is ToolPurity.UNCLASSIFIED]
    if unclassified:
        raise ReplayDivergenceError(
            f"trace contains unclassified tool calls {unclassified}; "
            f"purity must be established before replay or divergence is unattributable"
        )

    writes = [c.name for c in trace.calls if c.purity is ToolPurity.IMPURE_WRITE]
    if writes:
        raise ReplayDivergenceError(
            f"trace contains impure-write calls {writes}; replay against live "
            f"endpoints would mutate the state under reconstruction"
        )

    unrecoverable = [
        c.name
        for c in trace.calls
        if c.purity is ToolPurity.IMPURE_READ and not c.shadow_input_recoverable
    ]
    if unrecoverable:
        raise ReplayDivergenceError(
            f"impure-read calls {unrecoverable} have unrecoverable shadow inputs; "
            f"any divergence is a replay artifact, not a model defect"
        )


def classify_divergence(trace: Trace, first_divergent_call: str) -> str:
    """Attribute a divergence to model drift or shadow input, or refuse."""
    audit_replay_safety(trace)
    for call in trace.calls:
        if call.name == first_divergent_call:
            if call.purity is ToolPurity.REPLAY_PURE:
                return "MODEL_NONDETERMINISM"
            return "SHADOW_INPUT"
    raise ReplayDivergenceError(
        f"divergent call {first_divergent_call!r} not present in trace; "
        f"replay is not reconstructing the recorded run"
    )
