# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-quorum-threshold-be-re-derived-when-heterogeneous-llm-agents-vote-on-non-deterministic-outputs.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-quorum-threshold-be-re-derived-when-heterogeneous-llm-agents-vote-on-non-deterministic-outputs.warrant.json
# Markdown SHA-256:   5e06fcf727c04259b09793801c2306bfbef2a564f4156a102422ce66db3747c0
# Code AST SHA-256:   2adb9ddcf2c5888b909dde51d0640c76718680ce6d83bdfd24788ea7e11d6798
# Verified Classes:   QuorumIndependenceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class QuorumIndependenceError(RuntimeError):
    """Raised when a quorum's agreeing coalition is not decorrelated,
    or when fault cannot be separated from honest boundary variance."""
    pass


def evaluate_quorum(
    votes: dict[str, str],                  # agent_id -> "PASS" | "FAIL"
    shared_context_groups: list[set[str]],  # agents sharing preprocessing/retrieval
    calibration_probe_present: bool,
    boundary_flagged: set[str],             # agents whose vote flipped on re-run
    required_effective_quorum: int,
) -> str:
    # Collapse each shared-context group into a single effective voter.
    # Correlated agents are one mouth, not many votes.
    effective_voters: dict[str, str] = {}
    grouped: set[str] = set()
    for group in shared_context_groups:
        present = [a for a in group if a in votes]
        if not present:
            continue
        grouped.update(present)
        verdicts = {votes[a] for a in present}
        if len(verdicts) > 1:
            # Intra-group disagreement means the group cannot act as one voter;
            # it is unstable and must not be counted toward quorum at all.
            continue
        effective_voters[f"group:{sorted(present)}"] = verdicts.pop()
    for agent, verdict in votes.items():
        if agent not in grouped:
            effective_voters[agent] = verdict

    # Boundary-flagged agents are excluded from quorum statistics:
    # their variance is honest boundary sensitivity, not a fault signal.
    stable_voters = {
        k: v for k, v in effective_voters.items()
        if not any(a in boundary_flagged for a in k.replace("group:", "").strip("[]' ").split("', '"))
    }

    if not calibration_probe_present:
        raise QuorumIndependenceError(
            "No calibration probe in cycle: Byzantine fault is indistinguishable "
            "from honest non-determinism. Hold result; do not accept quorum."
        )

    pass_votes = sum(1 for v in stable_voters.values() if v == "PASS")
    fail_votes = sum(1 for v in stable_voters.values() if v == "FAIL")

    if pass_votes >= required_effective_quorum:
        if pass_votes < len(stable_voters):
            # A decorrelated dissent exists; accept only if the dissent is
            # boundary-flagged (variance) rather than stable (fault signal).
            dissenters = [k for k, v in stable_voters.items() if v == "FAIL"]
            if any(d not in boundary_flagged for d in dissenters):
                raise QuorumIndependenceError(
                    f"Stable decorrelated dissent {dissenters}: highest-value signal, "
                    "must not be overridden by correlated majority. Route to adjudication."
                )
        return "ACCEPT"
    if fail_votes >= required_effective_quorum:
        return "REJECT"
    raise QuorumIndependenceError(
        f"No effective quorum: PASS={pass_votes}, FAIL={fail_votes}, "
        f"required={required_effective_quorum} over {len(stable_voters)} independent voters."
    )
