# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-an-adversarial-litmus-safety-probe-has-silently-corrupted-its-own-scoring-rubric-mid-run.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-an-adversarial-litmus-safety-probe-has-silently-corrupted-its-own-scoring-rubric-mid-run.warrant.json
# Markdown SHA-256:   7342037af15fd2614d30e5f471b3da46db372e792cb573cd4627f66862afbabf
# Code AST SHA-256:   4fe8645d0b8f95acf4bfd8ee2a1910d40b4402eef68cb7d4eeacfd2bae4966c2
# Verified Classes:   RubricIntegrityError, Verdict
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class RubricIntegrityError(RuntimeError):
    """Raised when a verdict was computed under a rubric that does not match the epoch's canonical rubric,
    or when replay divergence exceeds the harness tolerance."""
    pass


@dataclass(frozen=True)
class Verdict:
    probe_id: str
    severity: int
    rubric_hash: str


def rubric_hash(rubric_text: str) -> str:
    return hashlib.sha256(rubric_text.encode("utf-8")).hexdigest()


def admit_verdict(verdict: Verdict, canonical_hash: str) -> Verdict:
    """Gate every verdict through rubric attestation before it enters the scored set."""
    if verdict.rubric_hash != canonical_hash:
        raise RubricIntegrityError(
            f"probe {verdict.probe_id}: verdict computed under rubric {verdict.rubric_hash[:12]} "
            f"but epoch canonical is {canonical_hash[:12]} — quarantine, do not score"
        )
    return verdict


def check_replay_divergence(
    primary: list[Verdict],
    replay: list[Verdict],
    tolerance: float = 0.02,
) -> float:
    """Independent replay must agree with primary within tolerance, else the batch is invalid."""
    by_id = {v.probe_id: v for v in replay}
    compared = 0
    disagreed = 0
    for p in primary:
        r = by_id.get(p.probe_id)
        if r is None:
            continue
        compared += 1
        if p.severity != r.severity:
            disagreed += 1
    if compared == 0:
        raise RubricIntegrityError("replay produced no comparable verdicts — audit the harness, not the scores")
    divergence = disagreed / compared
    if divergence > tolerance:
        raise RubricIntegrityError(
            f"replay divergence {divergence:.3f} exceeds tolerance {tolerance:.3f} "
            f"over {compared} probes — batch invalid, likely rubric corruption"
        )
    return divergence
