# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-equivocation-in-bft-agent-task-commitments-before-quorum-finalization.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-equivocation-in-bft-agent-task-commitments-before-quorum-finalization.warrant.json
# Markdown SHA-256:   294fe948254a3c2cfccc3bb62e982e0c6ef8f308e78648065cb39d31092ef55d
# Code AST SHA-256:   adc30bb00843d1d83352092787b2c1d4f78e7183385185110dd0489d61bd0b96
# Verified Classes:   CommitmentEquivocationError, QuiescenceViolationError, Commitment
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class CommitmentEquivocationError(RuntimeError):
    """Raised when an agent emits conflicting commitments that cannot be
    classified as honest divergent re-derivation."""
    pass


class QuiescenceViolationError(RuntimeError):
    """Raised when context mutated during the vote window, invalidating the
    divergent-re-derivation signal."""
    pass


@dataclass(frozen=True)
class Commitment:
    round_id: int
    task_id: str
    agent_id: str
    context_prefix_digest: str   # hash of frozen context at round entry
    context_delta_digest: str    # hash of context mutated during vote window
    commitment_hash: str
    timestamp: float
    signature_valid: bool


def classify_second_vote(first: Commitment, second: Commitment) -> str:
    if not (first.signature_valid and second.signature_valid):
        raise CommitmentEquivocationError(
            f"invalid signature on vote for task {first.task_id} round {first.round_id}"
        )
    if (first.round_id, first.task_id, first.agent_id) != (
        second.round_id, second.task_id, second.agent_id
    ):
        raise CommitmentEquivocationError("votes do not share round/task/agent tuple")
    if first.commitment_hash == second.commitment_hash:
        return "DUPLICATE"

    prefix_match = first.context_prefix_digest == second.context_prefix_digest
    delta_present = bool(second.context_delta_digest) and bool(first.context_delta_digest)
    monotonic = second.timestamp > first.timestamp

    if prefix_match and delta_present and monotonic:
        return "DIVERGENT_REDERIVATION"

    if prefix_match and not delta_present:
        raise CommitmentEquivocationError(
            f"identical frozen prefix, empty delta, conflicting hash on "
            f"task {first.task_id} round {first.round_id} agent {first.agent_id}: "
            f"key compromise or hash collision"
        )

    raise CommitmentEquivocationError(
        f"frozen prefix mismatch on task {first.task_id} round {first.round_id} "
        f"agent {first.agent_id}: {first.context_prefix_digest[:8]} vs "
        f"{second.context_prefix_digest[:8]}"
    )


def quorum_count(
    votes: list[Commitment],
    frozen_prefix: str,
    quiescent: bool,
) -> int:
    if not quiescent:
        raise QuiescenceViolationError(
            "context mutated during vote window; divergent-re-derivation "
            "signal is unreliable, must treat all divergence as Byzantine"
        )
    by_agent: dict[str, list[Commitment]] = {}
    for v in votes:
        by_agent.setdefault(v.agent_id, []).append(v)

    counted = 0
    for agent_id, agent_votes in by_agent.items():
        if len(agent_votes) == 1:
            if agent_votes[0].context_prefix_digest == frozen_prefix:
                counted += 1
            continue
        classification = classify_second_vote(agent_votes[0], agent_votes[1])
        if classification == "DIVERGENT_REDERIVATION":
            # freeze: do not count either vote; require re-attestation
            continue
        if classification == "DUPLICATE":
            counted += 1
    return counted
