# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-byzantine-agent-has-captured-the-consensus-quorum-before-the-commit-point.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-byzantine-agent-has-captured-the-consensus-quorum-before-the-commit-point.warrant.json
# Markdown SHA-256:   669f2d7f3bba6f230381df0a6ed0100581644db0571294b8fa2bd010ffa88c9c
# Code AST SHA-256:   e5fffa4c8f8959d89a3400d3c6bf281c7ed52cf8dec8f21fd2f4a8939a012dbf
# Verified Classes:   QuorumProvenanceError, EpochFrozenError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class QuorumProvenanceError(RuntimeError):
    """Raised when a quorum is cardinality-valid but provenance-invalid:
    the vote count meets threshold but effective independent lineages do not."""
    pass


class EpochFrozenError(RuntimeError):
    """Raised when the voter set is mutated mid-epoch, invalidating quorum arithmetic."""
    pass


def evaluate_commit(
    votes: list[dict],
    eligible_voters: set[str],
    epoch_open: bool,
    quorum_threshold: int,
    f: int,
) -> bool:
    """
    Decide whether a proposed state mutation may commit.
    Each vote: {"signer": str, "lineage_hash": str, "epoch": int}
    """
    if not epoch_open:
        # Voter set changed after epoch opened; cardinality is no longer meaningful.
        raise EpochFrozenError(
            "voter set mutated mid-epoch; quorum arithmetic invalid, re-run in fresh epoch"
        )

    signers = {v["signer"] for v in votes}
    if not signers.issubset(eligible_voters):
        # A vote from outside the frozen set is structurally inadmissible.
        raise EpochFrozenError(
            f"votes from non-eligible signers: {signers - eligible_voters}"
        )

    distinct_signers = len(signers)
    distinct_lineages = len({v["lineage_hash"] for v in votes})

    if distinct_signers < quorum_threshold:
        return False  # not enough votes at all

    # Cardinality satisfied. Now check provenance.
    if distinct_lineages < f + 1:
        raise QuorumProvenanceError(
            f"quorum reached by cardinality ({distinct_signers} signers) but only "
            f"{distinct_lineages} independent lineages (< f+1={f+1}); "
            f"likely clone-capture via delegation. Refusing commit."
        )

    return True
