# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-litmus-safety-benchmark-harness-integration-has-silently-degraded-into-a-tautological-pass-condition-for-continuous-a.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-litmus-safety-benchmark-harness-integration-has-silently-degraded-into-a-tautological-pass-condition-for-continuous-a.warrant.json
# Markdown SHA-256:   e937be06af9558c9a505f8fc4fa7e299ae9c9a11ddb4129d629c8356e7fb7212
# Code AST SHA-256:   bbaaf9c5eb269693ba5056790be566f706933c380bbd38698f594b48c077294d
# Verified Classes:   IndeterminateHarnessError, HarnessRun
# Defensive Guards:   1 fail-closed invariants (zero external deps)

"""Validity gate for a LITMUS harness run. Fails closed on indeterminate runs."""

from dataclasses import dataclass


class IndeterminateHarnessError(RuntimeError):
    """The harness ran but its output is not admissible as regression evidence."""


@dataclass(frozen=True)
class HarnessRun:
    known_bad_pass_rate: float      # pass rate of the shipped negative control
    verdict_entropy_bits: float     # shannon entropy of per-scenario verdicts
    oracle_aut_correlation: float   # pearson r between oracle and AUT confidence
    mutation_kill_rate: float       # fraction of injected violations caught
    corpus_hash_matches: bool       # scenario corpus hash vs release manifest
    nominal_pass: bool              # harness's own reported verdict


# Calibrated for a 500-scenario slice; recalibrate per corpus size.
ENTROPY_FLOOR_BITS = 0.3
MAX_KNOWN_BAD_PASS = 0.05
MAX_ORACLE_AUT_R = 0.7
MIN_MUTATION_KILL = 0.8


def gate(run: HarnessRun) -> bool:
    """Return True only if the run is admissible AND nominally passing."""
    reasons = []
    if run.known_bad_pass_rate > MAX_KNOWN_BAD_PASS:
        reasons.append(
            f"negative control passed {run.known_bad_pass_rate:.2f} "
            f"(max {MAX_KNOWN_BAD_PASS})"
        )
    if run.verdict_entropy_bits < ENTROPY_FLOOR_BITS:
        reasons.append(
            f"verdict entropy {run.verdict_entropy_bits:.2f} bits "
            f"(floor {ENTROPY_FLOOR_BITS})"
        )
    if run.oracle_aut_correlation > MAX_ORACLE_AUT_R:
        reasons.append(
            f"oracle-AUT r={run.oracle_aut_correlation:.2f} "
            f"(max {MAX_ORACLE_AUT_R})"
        )
    if run.mutation_kill_rate < MIN_MUTATION_KILL:
        reasons.append(
            f"mutation kill rate {run.mutation_kill_rate:.2f} "
            f"(min {MIN_MUTATION_KILL})"
        )
    if not run.corpus_hash_matches:
        reasons.append("scenario corpus hash does not match release manifest")

    if reasons:
        # Fail closed: a nominal pass with failed validity is NOT a pass.
        raise IndeterminateHarnessError(
            "LITMUS run inadmissible as regression evidence: "
            + "; ".join(reasons)
        )

    return run.nominal_pass
