# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-non-replayable-divergence-when-reconstructing-a-multi-agent-session-from-partial-telemetry.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-non-replayable-divergence-when-reconstructing-a-multi-agent-session-from-partial-telemetry.warrant.json
# Markdown SHA-256:   0c077255985309af089b426befda07fbb97392f98db12d35805f2af77cf0e5cb
# Code AST SHA-256:   467af6c15a42030c8d02d73f5e97aa4cca825edb60643b0ef9a84b7f917b455b
# Verified Classes:   ReplayDivergenceError, ReplayMode, TurnTelemetry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from enum import Enum


class ReplayDivergenceError(RuntimeError):
    """Raised when a replayer attempts to validate a decision against an
    output it re-sampled rather than the output that was actually recorded."""


class ReplayMode(Enum):
    EXACT = "exact"
    RECONSTRUCTIVE = "reconstructive"
    INVALID = "invalid"


@dataclass
class TurnTelemetry:
    turn_id: int
    agent: str
    temperature: float
    seed: int | None
    recorded_model_version: str
    pinned_model_version: str
    tool_response_refetched: bool


def classify_replay_mode(t: TurnTelemetry) -> ReplayMode:
    if t.tool_response_refetched:
        return ReplayMode.INVALID
    weight_match = t.recorded_model_version == t.pinned_model_version
    if t.temperature == 0.0 and weight_match:
        return ReplayMode.EXACT
    if t.seed is not None and weight_match:
        return ReplayMode.EXACT
    return ReplayMode.RECONSTRUCTIVE


def validate_downstream_verdict(
    upstream: TurnTelemetry,
    replayed_output: str,
    recorded_output: str,
    verdict_references: str,
) -> None:
    mode = classify_replay_mode(upstream)
    if mode is ReplayMode.INVALID:
        raise ReplayDivergenceError(
            f"turn {upstream.turn_id}: tool response re-fetched; "
            "replay is not forensically valid"
        )
    if mode is ReplayMode.RECONSTRUCTIVE:
        if verdict_references == replayed_output and replayed_output != recorded_output:
            raise ReplayDivergenceError(
                f"turn {upstream.turn_id}: downstream verdict validated against "
                f"re-sampled output (temp={upstream.temperature}, seed={upstream.seed}); "
                "must validate against recorded output"
            )
        # Reconstructive turns are permitted only against recorded output.
        return
    if replayed_output != recorded_output:
        raise ReplayDivergenceError(
            f"turn {upstream.turn_id}: EXACT-mode replay diverged from recorded "
            f"output (weights {upstream.pinned_model_version}); investigate "
            "endpoint nondeterminism or genuine tampering"
        )


def replay_coverage(turns: list[TurnTelemetry]) -> float:
    if not turns:
        return 0.0
    exact = sum(1 for t in turns if classify_replay_mode(t) is ReplayMode.EXACT)
    return exact / len(turns)
