# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-litmus-gate-saturation-from-genuine-agent-regression.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-litmus-gate-saturation-from-genuine-agent-regression.warrant.json
# Markdown SHA-256:   7537506f4b361a34ed1a5b95eea1cda1a88a23c67784097244ca7b4a8c0c437b
# Code AST SHA-256:   03823c8419102fc54b2a87a9e27c8efdc88acc6ebee5b92bdc5d79105f8004cc
# Verified Classes:   GateSaturationError, GateResult
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class GateSaturationError(RuntimeError):
    """Raised when a LITMUS gate trip is attributable to instrument saturation
    rather than a genuine downward shift in the agent's quality distribution."""


@dataclass
class GateResult:
    mean_delta: float
    p_value: float
    clipped_mass_delta: float
    censored_mean_delta: float


CLIP_MASS_THRESHOLD = 0.02  # 2 percentage points for a 10-point rubric
ALPHA = 0.01


def evaluate_gate(result: GateResult) -> str:
    """Decide whether a gate trip is a real regression or saturation.

    Returns 'promote' or 'block'. Raises GateSaturationError when the
    aggregate comparison is inadmissible and the censored re-estimate
    contradicts the naive aggregate.
    """
    tripped = result.p_value < ALPHA and result.mean_delta < 0.0
    if not tripped:
        return "promote"

    saturated = abs(result.clipped_mass_delta) > CLIP_MASS_THRESHOLD
    if saturated:
        # Aggregate is inadmissible. Trust the censored estimate instead.
        if result.censored_mean_delta >= 0.0:
            raise GateSaturationError(
                f"Gate tripped (delta={result.mean_delta:.3f}, p={result.p_value:.4f}) "
                f"but clipped-mass delta={result.clipped_mass_delta:.3f} exceeds "
                f"threshold {CLIP_MASS_THRESHOLD}; censored estimate "
                f"{result.censored_mean_delta:+.3f} shows no regression. "
                f"Trip is instrument saturation, not agent regression."
            )
        # Saturated AND censored estimate still negative: genuine regression.
        return "block"

    return "block"


def run_gate(results: list[GateResult]) -> dict:
    outcomes = {"promote": 0, "block": 0, "saturation": 0}
    for r in results:
        try:
            outcomes[evaluate_gate(r)] += 1
        except GateSaturationError as exc:
            outcomes["saturation"] += 1
            # Log and continue; saturation trips do not block deployment.
            print(f"[saturation] {exc}")
    return outcomes
