# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-anchor-a-replay-checkpoint-so-that-a-multi-agent-trace-remains-forensically-reconstructable-after-an-auditor-s-non-deterministi.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-anchor-a-replay-checkpoint-so-that-a-multi-agent-trace-remains-forensically-reconstructable-after-an-auditor-s-non-deterministi.warrant.json
# Markdown SHA-256:   0708991c78680d4484469cd109373bc0d53c8bfc0a37b61a86f2564ea4b93c75
# Code AST SHA-256:   3117a6eb8dc6d36190c1fd5d9aa019b762ffa3a0ce9badae9886f21223eb3d9b
# Verified Classes:   ReplayDivergence, ReplayMode, DecisionCheckpoint, ReplayHarness
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class ReplayDivergence(RuntimeError):
    """Raised when a recomputed decision diverges from its checkpointed verdict
    during incident-reconstruction replay. The checkpoint is authoritative;
    the recomputation is a diagnostic signal, not a substitute."""
    pass


class ReplayMode(Enum):
    RECONSTRUCTION = "reconstruction"   # checkpoint is authoritative
    REGRESSION = "regression"           # recomputation is authoritative


@dataclass(frozen=True)
class DecisionCheckpoint:
    step: int
    decider_id: str
    model_weights_hash: str
    decoding_params_hash: str
    sampling_seed: int
    prompt_hash: str
    evidence_set_hash: str
    verdict: str

    def content_hash(self) -> str:
        payload = "|".join([
            str(self.step), self.decider_id, self.model_weights_hash,
            self.decoding_params_hash, str(self.sampling_seed),
            self.prompt_hash, self.evidence_set_hash, self.verdict,
        ])
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass
class ReplayHarness:
    mode: ReplayMode
    checkpoints: dict[int, DecisionCheckpoint] = field(default_factory=dict)

    def replay_decision(
        self,
        step: int,
        recompute_fn,
    ) -> str:
        ckpt = self.checkpoints.get(step)
        if ckpt is None:
            # A gating decision with no checkpoint is not reconstructable.
            raise ReplayDivergence(
                f"step {step}: gating decision has no checkpoint; "
                f"trace is byte-complete but decision-incomplete"
            )

        recomputed = recompute_fn(ckpt)

        if self.mode is ReplayMode.RECONSTRUCTION:
            if recomputed != ckpt.verdict:
                # Do NOT substitute. Surface the divergence and continue
                # against the checkpointed branch.
                raise ReplayDivergence(
                    f"step {step}: checkpoint={ckpt.verdict!r} "
                    f"recomputed={recomputed!r} "
                    f"ckpt_hash={ckpt.content_hash()[:12]} "
                    f"weights={ckpt.model_weights_hash[:12]} "
                    f"seed={ckpt.sampling_seed}"
                )
            return ckpt.verdict

        # REGRESSION: recomputation is the measured quantity.
        return recomputed
