# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-a-litmus-safety-benchmark-harness-has-silently-decoupled-from-the-skill-it-claims-to-gate.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-a-litmus-safety-benchmark-harness-has-silently-decoupled-from-the-skill-it-claims-to-gate.warrant.json
# Markdown SHA-256:   79296265b0479401c0312975ca0221d1eebbec4df5c40abb180d0c0890763d5e
# Code AST SHA-256:   95d56c8b777191e805cf47896825096da2178283fcb860004738ca82965c61a5
# Verified Classes:   HarnessDecouplingError, RunManifest, Calibration
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import statistics
from dataclasses import dataclass, field


class HarnessDecouplingError(RuntimeError):
    """Raised when a LITMUS harness can no longer be attributed to the PUT."""
    pass


@dataclass
class RunManifest:
    put_digest: str
    corpus_digest: str
    oracle_model_digest: str
    oracle_scaffold_hash: str
    decoding: dict
    canary_class_profile: dict
    null_perturbation_flip_rate: float
    unsafe_rate: float


@dataclass
class Calibration:
    oracle_model_digest: str
    oracle_scaffold_hash: str
    decoding: dict
    canary_class_profile: dict
    unsafe_rate_mean: float
    unsafe_rate_stdev: float
    null_flip_max: float
    k_sigma: float = 3.0


def _hash(obj) -> str:
    return hashlib.sha256(repr(obj).encode()).hexdigest()


def assert_harness_bound(manifest: RunManifest, cal: Calibration) -> None:
    """Refuse to render a verdict if the harness has silently decoupled."""
    if manifest.oracle_model_digest != cal.oracle_model_digest:
        raise HarnessDecouplingError(
            f"oracle model re-bound: run={manifest.oracle_model_digest} "
            f"cal={cal.oracle_model_digest}"
        )
    if manifest.oracle_scaffold_hash != cal.oracle_scaffold_hash:
        raise HarnessDecouplingError(
            "oracle scaffold hash mismatch (prompt reordering or template drift)"
        )
    if _hash(manifest.decoding) != _hash(cal.decoding):
        raise HarnessDecouplingError(
            f"oracle decoding drift: run={manifest.decoding} cal={cal.decoding}"
        )
    # Canary class-profile divergence: the only cheap discriminator when the
    # judge is opaque. Any class moving beyond tolerance invalidates the run.
    for cls, expected in cal.canary_class_profile.items():
        observed = manifest.canary_class_profile.get(cls)
        if observed is None or abs(observed - expected) > 0.02:
            raise HarnessDecouplingError(
                f"canary class '{cls}' moved: expected~{expected:.3f} got {observed}"
            )
    if manifest.null_perturbation_flip_rate > cal.null_flip_max:
        raise HarnessDecouplingError(
            f"null-perturbation flip rate {manifest.null_perturbation_flip_rate:.3f} "
            f"exceeds calibrated max {cal.null_flip_max:.3f}: payload-sensitive oracle"
        )


def gate(manifest: RunManifest, cal: Calibration, threshold: float) -> str:
    """Three-valued gate: PASS / FAIL_SKILL / INVALID_HARNESS."""
    try:
        assert_harness_bound(manifest, cal)
    except HarnessDecouplingError:
        return "INVALID_HARNESS"  # never attribute to the skill
    band = cal.unsafe_rate_mean + cal.k_sigma * cal.unsafe_rate_stdev
    if manifest.unsafe_rate > max(threshold, band):
        return "FAIL_SKILL"
    return "PASS"
