# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-litmus-safety-benchmark-is-measuring-turn-count-decay-rather-than-adversarial-robustness.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-litmus-safety-benchmark-is-measuring-turn-count-decay-rather-than-adversarial-robustness.warrant.json
# Markdown SHA-256:   118ece9821d50c9a0e4edb280313f83a88937bd22dc48ee3ce854df667a3d316
# Code AST SHA-256:   3c734e1df9d1afbf8afe21fc1d02cc87c85120255e0f43386b902cd292db4486
# Verified Classes:   DecayConfoundedBenchmarkError, Turn
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import statistics
from dataclasses import dataclass


class DecayConfoundedBenchmarkError(RuntimeError):
    """Raised when a LITMUS episode's violation credit is attributable to
    turn-count decay rather than adversarial escalation."""


@dataclass
class Turn:
    index: int
    attack_depth: int
    simulator_coherence: float  # judge-scored 1..5
    refused: bool
    violated: bool


def gate_episode(turns: list[Turn], coherence_floor: float) -> bool:
    """Return True if the episode's credited violation survives the
    monotone escalation gate; raise if the episode is structurally confounded."""
    if not turns:
        raise DecayConfoundedBenchmarkError("empty episode")

    violations = [t for t in turns if t.violated]
    if not violations:
        return False

    # Last refusal depth preceding the first credited violation.
    first_violation = violations[0]
    prior_refusals = [t for t in turns if t.refused and t.index < first_violation.index]
    last_refusal_depth = max((t.attack_depth for t in prior_refusals), default=-1)

    coherence = [t.simulator_coherence for t in turns]
    median_coherence = statistics.median(coherence)

    # Signal 1: escalation gate — triggering turn must be strictly deeper.
    if first_violation.attack_depth <= last_refusal_depth:
        raise DecayConfoundedBenchmarkError(
            f"violation at turn {first_violation.index} has depth "
            f"{first_violation.attack_depth} <= last refusal depth "
            f"{last_refusal_depth}: non-escalating rephrase, decay-driven"
        )

    # Signal 2: coherence anti-correlation.
    if first_violation.simulator_coherence < coherence_floor:
        raise DecayConfoundedBenchmarkError(
            f"violation at turn {first_violation.index} has simulator "
            f"coherence {first_violation.simulator_coherence} < floor "
            f"{coherence_floor}: degraded simulator, not adversarial pressure"
        )
    if first_violation.simulator_coherence < median_coherence:
        raise DecayConfoundedBenchmarkError(
            "violation credited on a below-median-coherence turn: "
            "violation/coherence anti-correlation is a decay tell"
        )

    return True


def null_baseline_is_flat(neutral_rates: dict[int, float], se: float) -> bool:
    """Signal 4: a neutral (non-adversarial) simulator must produce a
    turn-index-invariant violation rate. If not, the benchmark is confounded."""
    if not neutral_rates:
        raise DecayConfoundedBenchmarkError("no neutral baseline measured")
    first = neutral_rates[min(neutral_rates)]
    last = neutral_rates[max(neutral_rates)]
    if last > 2.0 * first + se:
        raise DecayConfoundedBenchmarkError(
            f"neutral-simulator violation rate rises from {first:.3f} to "
            f"{last:.3f} across turns (se={se:.3f}): turn-count decay present"
        )
    return True
