# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-agent-s-commitment-vote-as-evidence-of-intent-rather-than-evidence-of-state.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-byzantine-agent-s-commitment-vote-as-evidence-of-intent-rather-than-evidence-of-state.warrant.json
# Markdown SHA-256:   aa6e50673a3c6f4239306c261f43ecaa3633d7f684b8ae68c2f94a85f1039971
# Code AST SHA-256:   be4bc97affafa4d4ea5b6af1014b0fa46ac2eb7ba3360124b929616ba9ad0016
# Verified Classes:   UnwitnessedVoteError, EquivocationError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class UnwitnessedVoteError(RuntimeError):
    """Raised when a vote lacks f+1 independent attestations of its log-prefix hash."""
    pass


class EquivocationError(RuntimeError):
    """Raised when an agent casts conflicting votes in the same (view, task_id)."""
    pass


def aggregate_commit_votes(votes, acks, f, quorum_size):
    """
    votes: list of dicts with keys agent_id, view, task_id, payload_hash, log_prefix_hash
    acks:  dict mapping log_prefix_hash -> set of agent_ids that independently attested it
    f:     max Byzantine agents
    quorum_size: 2f+1
    """
    seen = {}  # (agent_id, view, task_id) -> payload_hash
    counted = {}  # payload_hash -> set of agent_ids

    for v in votes:
        key = (v["agent_id"], v["view"], v["task_id"])
        if key in seen and seen[key] != v["payload_hash"]:
            raise EquivocationError(
                f"agent {v['agent_id']} equivocated on {key}: "
                f"{seen[key]} vs {v['payload_hash']}"
            )
        seen[key] = v["payload_hash"]

        attestors = acks.get(v["log_prefix_hash"], set()) - {v["agent_id"]}
        if len(attestors) < f + 1:
            raise UnwitnessedVoteError(
                f"vote from {v['agent_id']} on task {v['task_id']} has "
                f"{len(attestors)} independent attestations, need {f + 1}"
            )

        counted.setdefault(v["payload_hash"], set()).add(v["agent_id"])

    certificates = [
        payload for payload, agents in counted.items()
        if len(agents) >= quorum_size
    ]
    if len(certificates) > 1:
        raise EquivocationError(
            f"multiple conflicting certificates formed: {certificates}"
        )
    return certificates[0] if certificates else None
