# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-passes-a-litmus-regression-suite-that-was-calibrated-against-a-stale-adversarial-corpus.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-passes-a-litmus-regression-suite-that-was-calibrated-against-a-stale-adversarial-corpus.warrant.json
# Markdown SHA-256:   39b2c35274eebd110b8dd53b1846a5f14e2761066167d36a5587e6632fa8a643
# Code AST SHA-256:   9d0607654ae8a35478ce95392372fd7823e8e8adb947a92338347fb4f6b79fa1
# Verified Classes:   StaleCorpusGateError, CorpusManifest, DeploymentFingerprint
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class StaleCorpusGateError(RuntimeError):
    """Raised when a LITMUS regression gate is asked to certify a deployment
    whose tool schema, policy, or model fingerprint postdates the corpus."""
    pass


@dataclass(frozen=True)
class CorpusManifest:
    schema_version: str
    policy_hash: str
    model_id: str
    probe_count: int
    covered_paths: frozenset


@dataclass(frozen=True)
class DeploymentFingerprint:
    schema_version: str
    policy_hash: str
    model_id: str
    reachable_paths: frozenset


def evaluate_gate(
    manifest: CorpusManifest,
    deployment: DeploymentFingerprint,
    pass_count: int,
    threshold: float,
) -> str:
    # C1: corpus must match the deployment surface exactly.
    if manifest.schema_version != deployment.schema_version:
        raise StaleCorpusGateError(
            f"corpus schema {manifest.schema_version!r} != deployment "
            f"{deployment.schema_version!r}; regenerate before gating"
        )
    if manifest.policy_hash != deployment.policy_hash:
        raise StaleCorpusGateError(
            "policy hash mismatch: corpus predates current system policy"
        )
    if manifest.model_id != deployment.model_id:
        raise StaleCorpusGateError(
            f"model {deployment.model_id!r} not covered by corpus "
            f"({manifest.model_id!r}); probes may not exercise new capability"
        )

    # C2: composition coverage — every reachable path must be probed.
    uncovered = deployment.reachable_paths - manifest.covered_paths
    if uncovered:
        raise StaleCorpusGateError(
            f"{len(uncovered)} reachable tool paths have no probe: "
            f"{sorted(uncovered)[:5]}"
        )

    # C3/C4: pass rate is a floor, and a rise across a surface change is
    # a coverage signal, not a safety gain. Caller must supply prior rate.
    rate = pass_count / manifest.probe_count
    if rate < threshold:
        return "FAIL"
    return "PASS"


def gate_with_drift_check(
    manifest: CorpusManifest,
    deployment: DeploymentFingerprint,
    pass_count: int,
    threshold: float,
    prior_rate: float | None,
    surface_changed: bool,
) -> str:
    result = evaluate_gate(manifest, deployment, pass_count, threshold)
    rate = pass_count / manifest.probe_count
    if surface_changed and prior_rate is not None and rate > prior_rate:
        # Green build coincident with a surface change: refuse to certify.
        raise StaleCorpusGateError(
            f"pass rate rose {prior_rate:.3f} -> {rate:.3f} across a surface "
            "change; treat as COVERAGE_DRIFT, not improvement"
        )
    return result
