# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-adversarial-litmus-benchmark-harnesses-from-silently-laundering-a-regressed-agent-through-a-stale-safety-gate.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-adversarial-litmus-benchmark-harnesses-from-silently-laundering-a-regressed-agent-through-a-stale-safety-gate.warrant.json
# Markdown SHA-256:   796c8024b56e3dd10f85f27ce401c823a51fa9c476dacb1f4266ab84bb6ca1a8
# Code AST SHA-256:   f5954258ea27bc87e0cb195a5a2e2354c27ee3d23cdae3f89ccbeb1e5f33f9b8
# Verified Classes:   InstrumentDriftError, InstrumentFingerprint, RunRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class InstrumentDriftError(RuntimeError):
    """Raised when a gate is asked to compare runs scored by different instruments."""
    pass


@dataclass(frozen=True)
class InstrumentFingerprint:
    judge_model: str
    judge_prompt_hash: str
    corpus_root: str          # Merkle root over case IDs + bodies
    scoring_weights_hash: str
    aggregation: str          # "mean" | "worst_category" | "p95"

    def digest(self) -> str:
        payload = json.dumps(self.__dict__, sort_keys=True).encode()
        return hashlib.sha256(payload).hexdigest()


@dataclass
class RunRecord:
    checkpoint_id: str
    fingerprint: InstrumentFingerprint
    score: float
    per_category: dict = field(default_factory=dict)


def _fingerprint_of(run: RunRecord) -> str:
    return run.fingerprint.digest()


def gate_verdict(
    baseline: RunRecord,
    candidate: RunRecord,
    min_delta: float = 0.0,
    judge_agreement: float = 1.0,
    min_judge_agreement: float = 0.85,
) -> str:
    """
    Emit PASS/FAIL/INCOMPARABLE for a candidate checkpoint against a baseline.

    Invariants enforced:
      1. Baseline and candidate must share an identical instrument fingerprint.
      2. The judge's own calibration agreement must clear a floor.
      3. A regression (candidate - baseline < min_delta) is FAIL.
    Any violation of (1) or (2) is INCOMPARABLE, never PASS.
    """
    if judge_agreement < min_judge_agreement:
        # The instrument itself is unreliable; do not emit a safety verdict.
        raise InstrumentDriftError(
            f"judge agreement {judge_agreement:.3f} below floor "
            f"{min_judge_agreement:.3f}; instrument untrusted"
        )

    base_fp = _fingerprint_of(baseline)
    cand_fp = _fingerprint_of(candidate)

    if base_fp != cand_fp:
        # The two runs were scored by different exams. A delta is meaningless.
        raise InstrumentDriftError(
            "fingerprint mismatch between baseline "
            f"({baseline.checkpoint_id}@{base_fp[:12]}) and candidate "
            f"({candidate.checkpoint_id}@{cand_fp[:12]}); "
            "re-baseline required, verdict is INCOMPARABLE"
        )

    delta = candidate.score - baseline.score
    if delta < min_delta:
        return f"FAIL (delta={delta:+.3f})"
    return f"PASS (delta={delta:+.3f})"


def demo() -> None:
    fp_old = InstrumentFingerprint(
        judge_model="judge-7b",
        judge_prompt_hash="a1b2",
        corpus_root="c0ffee",
        scoring_weights_hash="w9",
        aggregation="mean",
    )
    fp_new = InstrumentFingerprint(
        judge_model="judge-70b",     # silent upgrade
        judge_prompt_hash="a1b2",
        corpus_root="d15ea5e",       # 12 cases pruned
        scoring_weights_hash="w9",
        aggregation="mean",
    )

    baseline = RunRecord("agent@v40", fp_old, score=0.91)
    candidate = RunRecord("agent@v41", fp_new, score=0.94)

    # The naive comparison would report +0.03 PASS and launder the regression.
    try:
        verdict = gate_verdict(baseline, candidate)
        print("verdict:", verdict)
    except InstrumentDriftError as e:
        print("blocked:", e)

    # After a forced re-baseline under the SAME (new) instrument:
    rebaselined_v40 = RunRecord("agent@v40", fp_new, score=0.96)
    candidate_v41 = RunRecord("agent@v41", fp_new, score=0.94)
    print("honest verdict:", gate_verdict(rebaselined_v40, candidate_v41))


if __name__ == "__main__":
    demo()
