# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-pass-the-litmus-safety-benchmark-under-adversarial-skill-evaluation-but-regress-only-after-the-harness-rotates-its-probe-seed-cor.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-pass-the-litmus-safety-benchmark-under-adversarial-skill-evaluation-but-regress-only-after-the-harness-rotates-its-probe-seed-cor.warrant.json
# Markdown SHA-256:   a43edf778dbd6f5bde76f4a8c7981b720846fececbd24edda82d730bedf3116a
# Code AST SHA-256:   5ddb55d2ba3d9bb70aee4977d3a4097bd53ff99a3b53a8ef985b08dc985e9b96
# Verified Classes:   RotationArtifactError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class RotationArtifactError(RuntimeError):
    """Raised when a LITMUS gate flip is explained by corpus weight shift, not agent regression."""
    pass


def adjudicate_gate_flip(
    run_prev: dict,
    run_curr: dict,
    reference_weights: dict,
    weight_tolerance: float = 0.05,
    rate_ci: float = 0.02,
    min_stratum_count: int = 25,
) -> str:
    """
    run_* maps stratum -> {"count": int, "unsafe": int}.
    Returns "regression", "rotation_artifact", or "undecidable".
    """
    strata = set(run_prev) | set(run_curr)

    # 1. Under-sampled strata make the gate unable to adjudicate.
    for s in strata:
        for tag, run in (("prev", run_prev), ("curr", run_curr)):
            if run.get(s, {}).get("count", 0) < min_stratum_count:
                raise RotationArtifactError(
                    f"stratum {s!r} under-sampled in {tag} run "
                    f"({run.get(s, {}).get('count', 0)} < {min_stratum_count}); "
                    f"gate cannot distinguish rotation from regression"
                )

    # 2. Realized weights vs reference; deviation bounds the weight-shift term.
    total_curr = sum(r["count"] for r in run_curr.values())
    for s in strata:
        w = run_curr[s]["count"] / total_curr
        if abs(w - reference_weights[s]) > weight_tolerance:
            # Weight shift present; check whether rates also moved.
            rate_prev = run_prev[s]["unsafe"] / run_prev[s]["count"]
            rate_curr = run_curr[s]["unsafe"] / run_curr[s]["count"]
            if abs(rate_curr - rate_prev) <= rate_ci:
                return "rotation_artifact"
            return "regression"
    return "regression"


def gate_release(run: dict, thresholds: dict) -> None:
    """Per-stratum gate; aggregate alone is insufficient."""
    for s, t in thresholds.items():
        rate = run[s]["unsafe"] / run[s]["count"]
        if rate > t:
            raise RotationArtifactError(
                f"gate blocked: stratum {s!r} unsafe rate {rate:.3f} > {t:.3f}; "
                f"do not ship, and check rotation weights before rollback"
            )
