# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-litmus-safety-benchmark-score-inflation-from-adversarial-skill-gate-leakage-across-agent-re-evaluation-cycles.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-litmus-safety-benchmark-score-inflation-from-adversarial-skill-gate-leakage-across-agent-re-evaluation-cycles.warrant.json
# Markdown SHA-256:   df05fe6de8a78056d1a364bc2076a077b16627812f3f52984038b29f05d33e15
# Code AST SHA-256:   e1b6f8b4f7108eb748c2e7f432e7c4c1ffc5aa664ee1d74cd14764a2997f2e14
# Verified Classes:   GateLeakageError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class GateLeakageError(RuntimeError):
    """Raised when a LITMUS regression-gate run is contaminated by state
    carried across evaluation cycles, invalidating the safety score."""
    pass


def validate_gate_run(
    cycle_id: str,
    context_entries: list[dict],
    score_seen: float,
    score_heldout: float,
    heldout_sigma: float,
    leak_threshold_sigma: float = 2.0,
) -> dict:
    """Enforce the gate isolation invariant for one LITMUS evaluation cycle.

    Raises GateLeakageError if the run is contaminated by construction
    (prior-cycle state readable at eval time) or if the seen/held-out
    divergence exceeds the leakage threshold. Returns a verdict dict only
    for clean runs.
    """
    # Guardrail 3: provenance audit. Any entry tagged with a prior cycle
    # voids the run outright -- this is a precondition, not a score discount.
    contaminated = [
        e for e in context_entries
        if e.get("provenance_cycle") is not None
        and e["provenance_cycle"] != cycle_id
    ]
    if contaminated:
        raise GateLeakageError(
            f"cycle {cycle_id}: {len(contaminated)} context entries carry "
            f"prior-cycle provenance; gate isolation invariant violated, "
            f"score {score_seen:.3f} is void"
        )

    # Guardrail 2: paired held-out control. A seen-score gain that is not
    # matched by a held-out gain beyond noise is attributed to memorization.
    delta_seen = score_seen - score_heldout
    if heldout_sigma <= 0:
        raise GateLeakageError(
            f"cycle {cycle_id}: held-out sigma must be positive to "
            f"interpret divergence; got {heldout_sigma}"
        )
    divergence_sigma = delta_seen / heldout_sigma
    if divergence_sigma > leak_threshold_sigma:
        raise GateLeakageError(
            f"cycle {cycle_id}: seen-heldout divergence {divergence_sigma:.2f}σ "
            f"exceeds {leak_threshold_sigma}σ (seen={score_seen:.3f}, "
            f"heldout={score_heldout:.3f}); score reflects gate memorization, "
            f"not safety capability"
        )

    return {
        "cycle_id": cycle_id,
        "verdict": "clean",
        "score_heldout": score_heldout,
        "score_seen": score_seen,
        "divergence_sigma": divergence_sigma,
        "promote_eligible": score_heldout,  # promotion keys on held-out only
    }
