# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-byzantine-quorum-is-silently-converging-on-a-poisoned-checkpoint-in-heterogeneous-llm-agent-swarms.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-byzantine-quorum-is-silently-converging-on-a-poisoned-checkpoint-in-heterogeneous-llm-agent-swarms.warrant.json
# Markdown SHA-256:   16779fc76029da4e85a53f0a2a6031da9bb99f0ab4a8e7ba40e100532fc23a97
# Code AST SHA-256:   af68f4d60e010240042a12449c8551a5cc5f9d67967679f15cff9154b41729cf
# Verified Classes:   QuorumCaptureError, CheckpointWindow
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Sequence


class QuorumCaptureError(RuntimeError):
    """Raised when a Byzantine quorum's dissent structure indicates score-driven capture."""
    pass


@dataclass
class CheckpointWindow:
    # For each checkpoint in the window: set of agent IDs that dissented from the committed value.
    dissent_sets: list[set[str]] = field(default_factory=list)
    # Honesty-score weight mass of dissenters vs. their raw headcount mass, per checkpoint.
    weighted_dissent_mass: list[float] = field(default_factory=list)
    unweighted_dissent_mass: list[float] = field(default_factory=list)


def _jaccard(a: set[str], b: set[str]) -> float:
    if not a and not b:
        return 1.0
    return len(a & b) / len(a | b)


def detect_capture(
    window: CheckpointWindow,
    capture_ratio_floor: float = 0.3,
    jaccard_ceiling: float = 0.8,
    min_windows: int = 5,
) -> None:
    """Raise QuorumCaptureError if dissent weight-ratio has collapsed AND dissent identity is frozen."""
    n = len(window.dissent_sets)
    if n < min_windows:
        raise QuorumCaptureError(
            f"insufficient windows ({n} < {min_windows}); cannot assess dissent structure"
        )

    ratios = [
        w / u if u > 0 else 1.0
        for w, u in zip(window.weighted_dissent_mass, window.unweighted_dissent_mass)
    ]
    mean_ratio = sum(ratios) / len(ratios)

    jaccards = [
        _jaccard(window.dissent_sets[i], window.dissent_sets[i + 1])
        for i in range(n - 1)
    ]
    mean_jaccard = sum(jaccards) / len(jaccards)

    if mean_ratio < capture_ratio_floor and mean_jaccard > jaccard_ceiling:
        raise QuorumCaptureError(
            "quorum capture detected: dissent weight-ratio collapsed "
            f"(mean={mean_ratio:.3f} < {capture_ratio_floor}) while dissent identity "
            f"froze (mean Jaccard={mean_jaccard:.3f} > {jaccard_ceiling}). "
            "Honesty score is measuring coalition membership, not honesty. "
            "Halt commit and re-derive scores from an orthogonal source."
        )
