# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-a-litmus-adversarial-scenario-generator-silently-produce-non-adversarial-tests-that-pass-every-safety-gate.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-a-litmus-adversarial-scenario-generator-silently-produce-non-adversarial-tests-that-pass-every-safety-gate.warrant.json
# Markdown SHA-256:   99fc3318c43ad7b5069c242d8f86bc97ab1eeed8707aa64bdbd2ec0ca34bb15e
# Code AST SHA-256:   879100ca97549008d31e9f052e95558e028894be0d543a2eaec3db63f531c7d6
# Verified Classes:   AttractorCollapseError, Mutant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from statistics import mean

class AttractorCollapseError(RuntimeError):
    """Raised when a LITMUS batch has collapsed onto the shared-alignment attractor."""
    pass

@dataclass
class Mutant:
    harmfulness: float      # H from generator's adversarial head
    validity: float         # V from generator's validity head
    heldout_harm: float     # H* from disjoint judge
    edit_distance: float    # semantic distance from parent seed

def audit_batch(mutants: list[Mutant], window: int = 200,
                corr_threshold: float = 0.5,
                divergence_threshold: float = 0.35) -> None:
    if len(mutants) < 2:
        return
    recent = mutants[-window:]
    hs = [m.harmfulness for m in recent]
    vs = [m.validity for m in recent]
    corr = _pearson(hs, vs)
    divergence = mean(m.harmfulness - m.heldout_harm for m in recent)
    edit_trend = _edit_trend(mutants)

    if corr > corr_threshold:
        raise AttractorCollapseError(
            f"H/V correlation {corr:.2f} > {corr_threshold}: adversarial and "
            f"validity heads have collapsed onto the shared alignment prior."
        )
    if divergence > divergence_threshold:
        raise AttractorCollapseError(
            f"Generator-vs-heldout harmfulness gap {divergence:.2f} > "
            f"{divergence_threshold}: generator is rating its own defanged output."
        )
    if edit_trend < 0:
        raise AttractorCollapseError(
            f"Edit distance from parent seed is decaying ({edit_trend:.3f}/iter): "
            f"the loop is un-mutating back toward benign seeds."
        )

def _pearson(xs: list[float], ys: list[float]) -> float:
    n = len(xs)
    mx, my = mean(xs), mean(ys)
    num = sum((x - mx) * (y - my) for x, y in zip(xs, ys))
    den = (sum((x - mx) ** 2 for x in xs) * sum((y - my) ** 2 for y in ys)) ** 0.5
    return num / den if den else 0.0

def _edit_trend(mutants: list[Mutant]) -> float:
    # slope of mean edit distance over the last three chunks
    chunks = [mutants[i:i + 50] for i in range(0, len(mutants), 50)][-3:]
    means = [mean(m.edit_distance for m in c) for c in chunks if c]
    if len(means) < 2:
        return 0.0
    return means[-1] - means[0]
