# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-the-litmus-safety-benchmark-diverge-from-its-own-recorded-verdict-when-the-evaluation-harness-replays-a-multi-turn-agentic-tra.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-the-litmus-safety-benchmark-diverge-from-its-own-recorded-verdict-when-the-evaluation-harness-replays-a-multi-turn-agentic-tra.warrant.json
# Markdown SHA-256:   a314220fe1b80700681d367a494ee0c8cee9d68db7d8a86c1d3d1ac04fd0ec9c
# Code AST SHA-256:   665dfd118b849ff24e887bb1c81dd6c134eeeaa0db5e68cfe44c339dc4851f15
# Verified Classes:   ReconstructionContractMismatch, ReconstructionContract, VerdictRecord
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ReconstructionContractMismatch(RuntimeError):
    """Raised when a stored verdict is replayed under a different
    reconstruction contract than the one that produced it."""
    pass


@dataclass(frozen=True)
class ReconstructionContract:
    budget_tokens: int
    policy: str          # e.g. "middle_truncate", "observation_only_evict"
    tokenizer_hash: str

    def fingerprint(self) -> str:
        payload = json.dumps(
            {
                "budget": self.budget_tokens,
                "policy": self.policy,
                "tok": self.tokenizer_hash,
            },
            sort_keys=True,
        ).encode()
        return hashlib.sha256(payload).hexdigest()


@dataclass
class VerdictRecord:
    episode_id: str
    label: str
    rationale: str
    contract_fingerprint: str


def replay_verdict(record: VerdictRecord, current: ReconstructionContract) -> str:
    """Return the stored label only if the reconstruction contract matches.

    A mismatch means the transcript the judge originally read cannot be
    regenerated byte-for-byte; the stored label is a label for a different
    input and MUST NOT be compared against a fresh judge pass.
    """
    if record.contract_fingerprint != current.fingerprint():
        raise ReconstructionContractMismatch(
            f"episode {record.episode_id}: stored verdict was produced under "
            f"contract {record.contract_fingerprint[:12]}, replay requested "
            f"under {current.fingerprint()[:12]}. Re-adjudicate and store a "
            f"new verdict; do not diff against the old label."
        )
    return record.label


def safe_replay(record: VerdictRecord, current: ReconstructionContract) -> dict:
    try:
        label = replay_verdict(record, current)
    except ReconstructionContractMismatch as exc:
        return {"status": "REPLAY_INVALID", "detail": str(exc), "label": None}
    return {"status": "OK", "label": label}
