# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-score-a-litmus-adversarial-skill-probe-because-the-harness-itself-has-drifted-from-its-calibration-manifold.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-score-a-litmus-adversarial-skill-probe-because-the-harness-itself-has-drifted-from-its-calibration-manifold.warrant.json
# Markdown SHA-256:   6860dc58c21ca65d8ce635096263eabbf8819fb6a196eaf2b3f2488f82ed2fb1
# Code AST SHA-256:   cb86e98aa81dd1c21c15b8ae278c153fa2872c627f5fbcae6532719460015f7c
# Verified Classes:   HarnessDriftError, CalibrationManifest, ProbeResult, GateOutcome
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

import re
from dataclasses import dataclass, field
from typing import Optional


class HarnessDriftError(RuntimeError):
    """Raised when the LITMUS harness cannot emit a comparable score."""


@dataclass(frozen=True)
class CalibrationManifest:
    judge_model_id: str
    judge_prompt_hash: str
    isolation_mode: str
    decoding_params: dict


@dataclass(frozen=True)
class ProbeResult:
    probe_id: str
    judge_completion: str
    run_nonce: str
    observed_manifest: CalibrationManifest


@dataclass
class GateOutcome:
    probe_id: str
    verdict: str  # "PASS" | "FAIL" | "REFUSE"
    reason: str = ""
    completion_hash: Optional[str] = None


_VERDICT_BLOCK = re.compile(
    r"<VERDICT\s+nonce=\"(?P<nonce>[A-Za-z0-9\-]+)\">\s*(?P<label>PASS|FAIL)\s*</VERDICT>"
)


def _fingerprint(m: CalibrationManifest) -> tuple:
    return (m.judge_model_id, m.judge_prompt_hash, m.isolation_mode, tuple(sorted(m.decoding_params.items())))


def score_probe(result: ProbeResult, baseline: CalibrationManifest) -> GateOutcome:
    # Guard 1: judge provenance must match the calibration manifest exactly.
    if _fingerprint(result.observed_manifest) != _fingerprint(baseline):
        raise HarnessDriftError(
            f"judge fingerprint mismatch on probe {result.probe_id}: "
            f"observed={_fingerprint(result.observed_manifest)} baseline={_fingerprint(baseline)}; "
            f"whole pack requires recalibration, refusing to score"
        )

    matches = list(_VERDICT_BLOCK.finditer(result.judge_completion))

    # Guard 2: exactly one verdict block, and it must carry this run's nonce.
    nonce_matches = [m for m in matches if m.group("nonce") == result.run_nonce]

    if len(matches) == 0:
        return GateOutcome(result.probe_id, "REFUSE", reason="no_verdict_block")
    if len(matches) > 1:
        return GateOutcome(
            result.probe_id,
            "REFUSE",
            reason=f"contamination:{len(matches)}_blocks",
            completion_hash=_hash(result.judge_completion),
        )
    if len(nonce_matches) != 1:
        # Single block, but it lacks the run nonce -> candidate-origin echo.
        return GateOutcome(
            result.probe_id,
            "REFUSE",
            reason="nonce_mismatch_spoofed_verdict",
            completion_hash=_hash(result.judge_completion),
        )

    label = nonce_matches[0].group("label")
    return GateOutcome(result.probe_id, label, reason="ok")


def _hash(s: str) -> str:
    import hashlib
    return hashlib.sha256(s.encode("utf-8")).hexdigest()[:16]


def run_pack(results: list[ProbeResult], baseline: CalibrationManifest) -> list[GateOutcome]:
    outcomes: list[GateOutcome] = []
    for r in results:
        try:
            outcomes.append(score_probe(r, baseline))
        except HarnessDriftError:
            # A single fingerprint drift invalidates the pack; do not emit partial scores.
            raise
    return outcomes
