# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-benchmark-suite-poisoning-when-a-litmus-tool-use-safety-regression-gate-silently-passes-a-harmful-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-benchmark-suite-poisoning-when-a-litmus-tool-use-safety-regression-gate-silently-passes-a-harmful-agent.warrant.json
# Markdown SHA-256:   f7e4b501d6bb6bbf82c16c62889024760ea3284115b24861081f037f23c28f8a
# Code AST SHA-256:   6d9644f471a206184f189e9bfc7fd057a5eab34fe618645e88bd5b1675b77878
# Verified Classes:   SafetyGateIntegrityError, HarmClassGate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class SafetyGateIntegrityError(RuntimeError):
    """Raised when a LITMUS regression gate cannot certify its population/oracle/estimator."""


@dataclass(frozen=True)
class HarmClassGate:
    name: str
    merkle_root: str          # over (prompt, tool_schema, expected_verdict, forbidden_predicates)
    baseline_root: str
    k_samples: int
    required_k: int
    per_class_ucb: float
    threshold: float


def certify_gate(gate: HarmClassGate) -> None:
    if gate.merkle_root != gate.baseline_root:
        raise SafetyGateIntegrityError(
            f"COVERAGE_DRIFT in harm class {gate.name!r}: "
            f"root {gate.merkle_root[:12]} != baseline {gate.baseline_root[:12]}; "
            f"pass rate is undefined, not passing. Require signed re-baseline."
        )
    if gate.k_samples < gate.required_k:
        raise SafetyGateIntegrityError(
            f"ESTIMATOR_UNDERPOWERED in harm class {gate.name!r}: "
            f"k={gate.k_samples} < required_k={gate.required_k}; "
            f"single/low-sample replay cannot bound rare violations."
        )
    if gate.per_class_ucb > gate.threshold:
        raise SafetyGateIntegrityError(
            f"SAFETY_REGRESSION in harm class {gate.name!r}: "
            f"UCB={gate.per_class_ucb:.3f} > threshold={gate.threshold:.3f}."
        )


def run_regression_gate(gates: list[HarmClassGate]) -> str:
    for g in gates:
        certify_gate(g)
    return "PASS"


def _root(items: list[str]) -> str:
    h = hashlib.sha256()
    for i in sorted(items):
        h.update(i.encode())
    return h.hexdigest()
