# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-inherit-a-litmus-safety-score-across-harness-revisions-the-calibration-drift-boundary-in-ci-gated-adversarial-evaluati.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-inherit-a-litmus-safety-score-across-harness-revisions-the-calibration-drift-boundary-in-ci-gated-adversarial-evaluati.warrant.json
# Markdown SHA-256:   d3f8ec0ed2e330d1899570ff7bae53e5b8f02c627a7657bc19dc33ab0abe38fd
# Code AST SHA-256:   21ef82d5a2e02bfa8431fed1d7a5028b1d3201ec9c0ccfc230eb1868ba21e7a0
# Verified Classes:   CalibrationInheritanceError, CalibrationTuple, ScoreArtifact
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CalibrationInheritanceError(RuntimeError):
    """Raised when a persisted LITMUS score is reused across a diverged calibration tuple."""
    pass


@dataclass(frozen=True)
class CalibrationTuple:
    model_hash: str
    scaffold_hash: str
    judge_id: str
    judge_rubric_hash: str
    seed_corpus_hash: str
    decoding_params: dict
    harness_revision: str

    def identity(self) -> str:
        payload = json.dumps(
            {
                "model": self.model_hash,
                "scaffold": self.scaffold_hash,
                "judge": self.judge_id,
                "rubric": self.judge_rubric_hash,
                "seeds": self.seed_corpus_hash,
                "decoding": self.decoding_params,
                "harness": self.harness_revision,
            },
            sort_keys=True,
        )
        return hashlib.sha256(payload.encode()).hexdigest()


@dataclass(frozen=True)
class ScoreArtifact:
    tuple_identity: str
    score: float
    threshold: float


def gate_release(
    candidate: CalibrationTuple,
    artifact: ScoreArtifact | None,
    force_full_run: bool = False,
) -> str:
    if artifact is None or force_full_run:
        return "RUN_FULL_SUITE"

    if artifact.tuple_identity != candidate.identity():
        # Do not inherit, do not adjust, do not average. Refuse and re-run.
        raise CalibrationInheritanceError(
            "Persisted LITMUS score was calibrated against a diverged tuple "
            f"(artifact={artifact.tuple_identity[:12]}, "
            f"candidate={candidate.identity()[:12]}). "
            "Judge rubric, seed corpus, decoding, or harness revision moved; "
            "the score is not a valid gate input for this candidate."
        )

    if artifact.score < artifact.threshold:
        return "FAIL_SAFETY_GATE"

    return "PASS_VIA_INHERITED_SCORE"


def run_gate(candidate: CalibrationTuple, artifact: ScoreArtifact | None) -> None:
    try:
        outcome = gate_release(candidate, artifact)
    except CalibrationInheritanceError as exc:
        # Hard-fail the CI step; never downgrade to a warning.
        raise CalibrationInheritanceError(f"CI safety gate blocked: {exc}") from exc
    if outcome == "FAIL_SAFETY_GATE":
        raise CalibrationInheritanceError(
            f"Safety score {artifact.score:.3f} below threshold {artifact.threshold:.3f}"
        )
