# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-quorum-ordered-tool-result-divergence-from-surviving-a-byzantine-agent-s-equivocating-replay-in-multi-agent-consensus.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-quorum-ordered-tool-result-divergence-from-surviving-a-byzantine-agent-s-equivocating-replay-in-multi-agent-consensus.warrant.json
# Markdown SHA-256:   643f98c2696f5ca808fe65ad94c31498fd479799784efa02dc2fe83f1e77d965
# Code AST SHA-256:   e4d3da2be3144292ca4b15068c30f6e82f16829705fdcd952a1b611237a9fcbf
# Verified Classes:   EquivocationCommitError, Transcript
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Sequence


class EquivocationCommitError(RuntimeError):
    """Raised when a commit certificate would bind two distinct tool outcomes
    to the same request nonce, or when a quorum is claimed without the
    required distinct-nonce attestations."""


@dataclass(frozen=True)
class Transcript:
    nonce: str          # agent-signed, single-use per epoch
    tool_id: str
    args_hash: str
    result_hash: str
    signer: str


def commit_outcome(
    transcripts: Sequence[Transcript],
    f: int,
) -> str:
    """Return the committed outcome, or 'INDETERMINATE'.

    Invariant: a commit requires >= 2f+1 DISTINCT nonces attesting the SAME
    result_hash. Two result_hashes each attested by >= f+1 distinct nonces
    is proof of non-determinism or equivocation and MUST NOT be majority-voted.
    """
    by_result: dict[str, set[str]] = {}
    nonce_to_result: dict[str, str] = {}

    for t in transcripts:
        # Duplicate-nonce detection: one nonce, two results => Byzantine.
        if t.nonce in nonce_to_result and nonce_to_result[t.nonce] != t.result_hash:
            raise EquivocationCommitError(
                f"nonce {t.nonce!r} signed two distinct results: "
                f"{nonce_to_result[t.nonce]!r} vs {t.result_hash!r}"
            )
        nonce_to_result[t.nonce] = t.result_hash
        by_result.setdefault(t.result_hash, set()).add(t.nonce)

    quorum = 2 * f + 1
    contenders = [
        (rh, nonces)
        for rh, nonces in by_result.items()
        if len(nonces) >= quorum
    ]

    if len(contenders) > 1:
        # Two mutually exclusive quorums: non-determinism or equivocation.
        # Do NOT commit; require re-invocation under fresh nonces.
        raise EquivocationCommitError(
            f"conflicting quorums for {[c[0] for c in contenders]}; "
            f"outcome is INDETERMINATE, re-invoke under new nonces"
        )

    if not contenders:
        # No quorum yet; caller may add more transcripts.
        return "INDETERMINATE"

    # Exactly one quorum: also verify no minority bloc reaches f+1 with a
    # different result, which would signal a flapping tool rather than noise.
    committed_hash, committed_nonces = contenders[0]
    for rh, nonces in by_result.items():
        if rh != committed_hash and len(nonces) >= f + 1:
            raise EquivocationCommitError(
                f"minority bloc {rh!r} has {len(nonces)} distinct nonces "
                f"(>= f+1={f+1}); tool is non-deterministic, cannot commit"
            )

    return committed_hash


def verify_and_commit(
    transcripts: Sequence[Transcript],
    f: int,
    expected_tool: str,
) -> str:
    for t in transcripts:
        if t.tool_id != expected_tool:
            raise EquivocationCommitError(
                f"transcript references tool {t.tool_id!r}, "
                f"expected {expected_tool!r}"
            )
    return commit_outcome(transcripts, f)
