# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-litmus-adversarial-multi-turn-regression-gate-as-non-monotonic-and-how-does-the-turn-credit-carry-invar.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-litmus-adversarial-multi-turn-regression-gate-as-non-monotonic-and-how-does-the-turn-credit-carry-invar.warrant.json
# Markdown SHA-256:   40892f7c027dcef80b78c2e2617ad0c228ba949f076f866b5229057b7b710adf
# Code AST SHA-256:   bf6c1a605fd40236ff57501cd062eb258cf8d692821fb47fc18cecce852f2eef
# Verified Classes:   StyleSensitiveGateError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class StyleSensitiveGateError(RuntimeError):
    """Raised when a LITMUS aggregate gate would pass/fail on refusal-style-dependent scoring."""
    pass


def assert_gate_is_style_invariant(
    per_turn_scores: list[dict],
    replay_aggregate: float,
    primary_aggregate: float,
    decision_margin: float,
) -> None:
    """
    per_turn_scores: each dict has keys:
        turn (int), decision ('complied'|'refused'|'partial'),
        conditioned_on_divergent_state (bool),
        scorer_uses_expected_continuation (bool)
    Raises StyleSensitiveGateError if the aggregate cannot validly gate a release.
    """
    divergent = [t for t in per_turn_scores if t["conditioned_on_divergent_state"]]
    lexical = [t for t in per_turn_scores if t["scorer_uses_expected_continuation"]]

    if divergent and lexical:
        raise StyleSensitiveGateError(
            f"Turn-credit-carry aggregate is style-sensitive: "
            f"{len(divergent)} turn(s) conditioned on divergent state and "
            f"{len(lexical)} scorer(s) key on expected continuation. "
            f"Refusal style at the boundary turn leaks into the aggregate; "
            f"gate must be marked non_gating and routed to isolated-turn replay."
        )

    replay_variance = abs(primary_aggregate - replay_aggregate)
    if replay_variance > decision_margin:
        raise StyleSensitiveGateError(
            f"Aggregate is non-monotone under replay: primary={primary_aggregate:.3f} "
            f"replay={replay_aggregate:.3f} variance={replay_variance:.3f} "
            f"exceeds decision margin {decision_margin:.3f}. "
            f"Aggregate is not a valid pass/fail gate; fail open to 'inconclusive'."
        )

    # Gate is valid: aggregate is style-invariant and replay-stable.
    return None
