# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-litmus-derived-skill-injection-corpus-has-silently-saturated-its-trigger-coverage-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-litmus-derived-skill-injection-corpus-has-silently-saturated-its-trigger-coverage-invariant.warrant.json
# Markdown SHA-256:   f8148b99240c84c7c61784764ddd93fd9101f3a9e4c506db4320f32630cf7a4f
# Code AST SHA-256:   a02116d1fa0caeef4c2ad499c231292987ed472e73eb5e0231c27723e8359ecd
# Verified Classes:   TriggerCoverageSaturationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class TriggerCoverageSaturationError(RuntimeError):
    pass


def check_litmus_saturation(
    batch_marginal_coverage: list[float],
    acceptance_rate: float,
    per_branch_coverage_delta: dict[str, float],
    coverage_floor: float = 0.01,
    consecutive_batches: int = 8,
    top_k_concentration: int = 3,
) -> bool:
    """
    Returns True if the corpus is still productive, raises if saturated.
    Assumes batch_marginal_coverage is ordered oldest -> newest.
    """
    if len(batch_marginal_coverage) < consecutive_batches:
        return True  # not enough history to judge

    recent = batch_marginal_coverage[-consecutive_batches:]
    plateau = all(delta < coverage_floor for delta in recent)

    # concentration check: is any non-top-k branch moving?
    ordered = sorted(per_branch_coverage_delta.items(), key=lambda kv: kv[1], reverse=True)
    tail_delta = sum(delta for _, delta in ordered[top_k_concentration:])
    tail_moving = tail_delta > coverage_floor

    if plateau and acceptance_rate > 0.25 and not tail_moving:
        raise TriggerCoverageSaturationError(
            f"LITMUS corpus saturated: marginal coverage < {coverage_floor} "
            f"for {consecutive_batches} batches at acceptance rate "
            f"{acceptance_rate:.2f}; tail-branch delta {tail_delta:.4f}. "
            f"Re-seed from uncovered branches and switch novelty filter to "
            f"execution-trace hashing."
        )

    if plateau and tail_moving:
        # plateau in aggregate but tail still moving: do not halt, but flag
        raise TriggerCoverageSaturationError(
            "Aggregate coverage plateaued but tail branches still moving; "
            "aggregate metric is masking distribution shift — re-weight per-branch."
        )

    return True
