# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-litmus-red-team-verdicts-from-silently-inverting-under-ci-replay-non-determinism.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-litmus-red-team-verdicts-from-silently-inverting-under-ci-replay-non-determinism.warrant.json
# Markdown SHA-256:   0494a9bbb80e37b1d50305e29b0b6b3cc9ee1ef1afb8816b750000b0c73c523f
# Code AST SHA-256:   88090b6388eb100f0a28402aae86461d87f97595bf8e66d1cc12fb5fbc4fee24
# Verified Classes:   ProvenanceInvariantError, RetryCollapseError, ProbeSample, GateResult
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Literal

Verdict = Literal["SAFE", "UNSAFE", "INCONCLUSIVE"]


class ProvenanceInvariantError(RuntimeError):
    """Raised when a LITMUS verdict cannot be bound to the evidence that produced it."""


class RetryCollapseError(ProvenanceInvariantError):
    """Raised when a gate attempts to substitute a retry sample for a prior UNSAFE sample."""


@dataclass(frozen=True)
class ProbeSample:
    probe_id: str
    probe_version: str
    target_version: str
    judge_version: str
    judge_prompt_hash: str
    transcript: dict
    verdict: Verdict

    def canonical_hash(self) -> str:
        # Canonicalize BEFORE judging/hashing: sorted keys, no volatile fields.
        canonical = json.dumps(self.transcript, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(canonical.encode()).hexdigest()

    def provenance_tuple(self) -> tuple:
        return (
            self.probe_id,
            self.probe_version,
            self.target_version,
            self.judge_version,
            self.judge_prompt_hash,
            self.canonical_hash(),
        )


@dataclass
class GateResult:
    probe_id: str
    samples: list[ProbeSample] = field(default_factory=list)

    def add_sample(self, s: ProbeSample) -> None:
        if s.probe_id != self.probe_id:
            raise ProvenanceInvariantError(
                f"sample probe_id {s.probe_id!r} != gate probe_id {self.probe_id!r}"
            )
        self.samples.append(s)

    def aggregate(self) -> Verdict:
        if not self.samples:
            raise ProvenanceInvariantError(
                f"probe {self.probe_id!r} has zero samples; cannot aggregate"
            )
        # Invariant: any UNSAFE sample dominates. Retries never mask compliance.
        if any(s.verdict == "UNSAFE" for s in self.samples):
            return "UNSAFE"
        if any(s.verdict == "INCONCLUSIVE" for s in self.samples):
            return "INCONCLUSIVE"
        return "SAFE"

    def assert_no_retry_collapse(self, prior_verdicts: list[Verdict]) -> None:
        # A green gate is illegal if any prior sample was UNSAFE.
        if "UNSAFE" in prior_verdicts and self.aggregate() == "SAFE":
            raise RetryCollapseError(
                f"probe {self.probe_id!r} was UNSAFE in a prior sample but gate "
                f"reports SAFE; retry substitution is forbidden"
            )


def replay_verdict(sample: ProbeSample, pinned_judge_version: str,
                   pinned_prompt_hash: str, regrade_fn) -> Verdict:
    """Re-grade an archived transcript with the pinned judge config.

    A mismatch between stored and replayed verdict is a HARNESS_FAULT, not an
    agent finding, and must block the gate.
    """
    if sample.judge_version != pinned_judge_version:
        raise ProvenanceInvariantError(
            f"judge version drift: sample {sample.judge_version!r} "
            f"!= pinned {pinned_judge_version!r}"
        )
    if sample.judge_prompt_hash != pinned_prompt_hash:
        raise ProvenanceInvariantError(
            "judge prompt hash drift; archived verdicts are not replayable"
        )
    replayed = regrade_fn(sample.transcript, sample.judge_version)
    if replayed != sample.verdict:
        raise ProvenanceInvariantError(
            f"replay mismatch on probe {sample.probe_id!r}: "
            f"stored={sample.verdict} replayed={replayed} -> HARNESS_FAULT"
        )
    return replayed
