# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-replay-divergence-when-an-agent-s-non-deterministic-tool-outputs-are-re-executed-for-forensic-evidence.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-replay-divergence-when-an-agent-s-non-deterministic-tool-outputs-are-re-executed-for-forensic-evidence.warrant.json
# Markdown SHA-256:   5fb31c795332449baeb1b8ce4b5633f174a9148284c369f76db2f07d53613fe6
# Code AST SHA-256:   79d788a68a48bf04e38ac1ee4807b422cf964a09892abc6b3bd9519fb95c72fe
# Verified Classes:   ReplayDivergenceError, RecordedStep
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ReplayDivergenceError(RuntimeError):
    """Raised when evidence replay cannot re-derive a transition from recorded inputs alone."""
    pass


@dataclass(frozen=True)
class RecordedStep:
    seq: int
    prev_state_hash: str
    observation_raw: bytes          # exact bytes the model conditioned on
    sampler_seed: int | None        # None => sampling not pinned
    decision_token_id: int
    next_state_hash: str


def verify_evidence_chain(steps: list[RecordedStep], step_fn) -> str:
    """Pure-computation replay: no live tools, no re-sampling. Returns final state hash."""
    if not steps:
        raise ReplayDivergenceError("empty transcript: nothing to attest")

    prev_hash = steps[0].prev_state_hash
    for step in steps:
        if step.prev_state_hash != prev_hash:
            raise ReplayDivergenceError(
                f"seq {step.seq}: chain break, prev hash mismatch "
                f"({step.prev_state_hash[:12]} != {prev_hash[:12]})"
            )
        if step.sampler_seed is None:
            raise ReplayDivergenceError(
                f"seq {step.seq}: sampler seed unpinned; transcript is testimony, "
                f"not a witness, and attribution is unsound"
            )
        obs_hash = hashlib.sha256(step.observation_raw).hexdigest()
        derived = step_fn(prev_hash, obs_hash, step.sampler_seed, step.decision_token_id)
        if derived != step.next_state_hash:
            raise ReplayDivergenceError(
                f"seq {step.seq}: transition not licensed by recorded inputs; "
                f"possible Byzantine tampering"
            )
        prev_hash = derived
    return prev_hash
