# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-draw-the-quorum-boundary-when-heterogeneous-llm-agents-vote-on-non-deterministic-outputs.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-draw-the-quorum-boundary-when-heterogeneous-llm-agents-vote-on-non-deterministic-outputs.warrant.json
# Markdown SHA-256:   06bc19fd2c8ac50737aa1cd268b5741ed00f3fd2611d9ddbc3b140228685fe8f
# Code AST SHA-256:   419f90388b3e034cfa967c4fc680b64a51f6a8a2497f0b9d90a78ce3b7868e77
# Verified Classes:   NominalQuorumError, AgentVerdict
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import statistics
from dataclasses import dataclass


class NominalQuorumError(RuntimeError):
    """Raised when a panel commits on a quorum that is nominal, not effective."""
    pass


@dataclass
class AgentVerdict:
    agent_id: str
    samples: list[bool]  # True = approve, one entry per replay

    @property
    def agreement(self) -> float:
        if not self.samples:
            return 0.0
        majority = statistics.mode(self.samples)
        return self.samples.count(majority) / len(self.samples)

    @property
    def stable_vote(self) -> bool | None:
        # None = unstable / abstain; do not count toward quorum
        if self.agreement < STABILITY_TAU:
            return None
        return statistics.mode(self.samples)


STABILITY_TAU = 0.90
MIN_STABLE_APPROVE = 2
MAX_STABLE_REJECT = 1
MIN_MARGIN = 1
REPLAY_BUDGET = 5


def commit_panel_decision(verdicts: list[AgentVerdict]) -> bool:
    if any(len(v.samples) < REPLAY_BUDGET for v in verdicts):
        raise NominalQuorumError(
            f"replay budget {REPLAY_BUDGET} not met; verdicts are single-sample"
        )

    stable_approve = sum(1 for v in verdicts if v.stable_vote is True)
    stable_reject = sum(1 for v in verdicts if v.stable_vote is False)
    unstable = [v.agent_id for v in verdicts if v.stable_vote is None]

    margin = stable_approve - stable_reject

    if stable_approve >= MIN_STABLE_APPROVE and stable_reject <= MAX_STABLE_REJECT and margin >= MIN_MARGIN:
        return True

    if stable_reject >= MIN_STABLE_APPROVE and stable_approve <= MAX_STABLE_REJECT and -margin >= MIN_MARGIN:
        return False

    # No side reached *stable* quorum: the nominal 2-of-3 may have fired,
    # but the effective quorum did not. Escalate; do not commit.
    raise NominalQuorumError(
        f"no stable quorum: stable_approve={stable_approve} "
        f"stable_reject={stable_reject} unstable_agents={unstable} "
        f"margin={margin}; escalate instead of committing"
    )
