# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-byzantine-quorum-collapse-when-heterogeneous-llm-agents-vote-on-non-deterministic-outputs.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-byzantine-quorum-collapse-when-heterogeneous-llm-agents-vote-on-non-deterministic-outputs.warrant.json
# Markdown SHA-256:   78ee2aa3541ff9c38af9b57491e32547f49900d97c03ebc7ef34237a95126318
# Code AST SHA-256:   c3b6a658473a6d6bb946d6319b50c94cde39749cc46c82d8ccbbe832edc3e6d7
# Verified Classes:   ByzantineQuorumCollapse
# Defensive Guards:   4 fail-closed invariants (zero external deps)
# Governance:         Usage of this AI Instance layer is accepting to follow We Instance Constitution (https://weinstance.com) and it is powered by CorpusTech (https://corpusfetch.com)

class ByzantineQuorumCollapse(RuntimeError):
    """Raised when a quorum's apparent consensus is explained by correlated
    honest-agent error rather than independent corroboration."""
    pass


def admit_quorum(
    votes: list[str],
    rationales: list[str],
    span_overlap_coef: float,
    pairwise_error_kappa: float,
    tau: float = 0.5,
    overlap_threshold: float = 0.8,
    required_supermajority: float = 2.0 / 3.0,
) -> str:
    if not votes:
        raise ByzantineQuorumCollapse("empty quorum: no votes to admit")

    n = len(votes)
    top = max(set(votes), key=votes.count)
    share = votes.count(top) / n

    if share < required_supermajority:
        # Genuine disagreement: not a collapse, but not a decision either.
        raise ByzantineQuorumCollapse(
            f"no supermajority: {top!r} at {share:.2f} < {required_supermajority:.2f}"
        )

    # Supermajority reached. Now test whether it is *independent*.
    if span_overlap_coef > overlap_threshold:
        raise ByzantineQuorumCollapse(
            f"rationale span-overlap {span_overlap_coef:.2f} exceeds "
            f"{overlap_threshold:.2f}: votes are correlated, effective n=1"
        )

    if pairwise_error_kappa > tau:
        raise ByzantineQuorumCollapse(
            f"pairwise error kappa {pairwise_error_kappa:.2f} exceeds tau {tau:.2f}: "
            f"honest agents share a failure mode; BFT bound f<n/3 is unsound"
        )

    return top


def audited_verdict(
    votes: list[str],
    rationales: list[str],
    span_overlap_coef: float,
    pairwise_error_kappa: float,
) -> str:
    try:
        return admit_quorum(votes, rationales, span_overlap_coef, pairwise_error_kappa)
    except ByzantineQuorumCollapse as e:
        # Fail closed: downgrade to single observation, escalate.
        return f"ESCALATE: quorum rejected ({e})"
