# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-byzantine-quorum-equivocation-when-agent-auditors-attest-to-conflicting-result-digests.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-byzantine-quorum-equivocation-when-agent-auditors-attest-to-conflicting-result-digests.warrant.json
# Markdown SHA-256:   263a6031c8e39e74cb77983716a16e4897818e22c0f2d42bc7f24ba05a2435e3
# Code AST SHA-256:   74bf7abc2f75d997e26bfdd0ddda94f73301e660ca61c6602ff0bc7a92d3fdf9
# Verified Classes:   QuorumEquivocationError, Attestation, Certificate
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class QuorumEquivocationError(RuntimeError):
    """Raised when two quorum certificates for the same round disagree on evidence provenance."""
    pass


@dataclass(frozen=True)
class Attestation:
    auditor_id: str
    task_id: str
    round_id: str
    digest: str
    evidence_hash: str
    signature: str  # opaque; assumed verified upstream


@dataclass(frozen=True)
class Certificate:
    task_id: str
    round_id: str
    digest: str
    evidence_hash: str
    attestations: tuple[Attestation, ...]


def validate_certificate(cert: Certificate, threshold: int) -> None:
    if len(cert.attestations) < threshold:
        raise QuorumEquivocationError(
            f"certificate for {cert.task_id}/{cert.round_id} has "
            f"{len(cert.attestations)} attestations, need {threshold}"
        )
    for att in cert.attestations:
        if att.evidence_hash != cert.evidence_hash:
            raise QuorumEquivocationError(
                f"attestation from {att.auditor_id} cites evidence "
                f"{att.evidence_hash!r} but certificate claims {cert.evidence_hash!r}"
            )
        if att.round_id != cert.round_id or att.task_id != cert.task_id:
            raise QuorumEquivocationError(
                f"attestation from {att.auditor_id} bound to wrong round/task"
            )


def reconcile(cert_a: Certificate, cert_b: Certificate, threshold: int) -> str:
    """Resolve two coexisting certificates for the same (task_id, round_id).

    Returns 'byzantine' if evidence hashes match (honest double-sign -> slash),
    'evidence_divergence' if they differ (halt and reconcile provenance).
    """
    validate_certificate(cert_a, threshold)
    validate_certificate(cert_b, threshold)

    if (cert_a.task_id, cert_a.round_id) != (cert_b.task_id, cert_b.round_id):
        raise QuorumEquivocationError(
            "reconcile called on certificates from different rounds"
        )

    if cert_a.digest == cert_b.digest:
        return "agree"

    if cert_a.evidence_hash == cert_b.evidence_hash:
        # Same evidence, different digests -> at least one honest auditor
        # double-signed the same context. This is slashable Byzantine behavior.
        return "byzantine"

    # Different evidence hashes -> the resume/checkpoint path mutated the
    # evidence bundle. Honest auditors attested to what they saw. Do NOT slash.
    # Halt the round and force provenance reconciliation.
    raise QuorumEquivocationError(
        f"evidence divergence in round {cert_a.round_id}: "
        f"{cert_a.evidence_hash} vs {cert_b.evidence_hash}; "
        f"round must be invalidated, not finalized"
    )


def register_round_evidence(registered: dict, task_id: str, round_id: str,
                            evidence_bytes: bytes) -> str:
    h = hashlib.sha256(evidence_bytes).hexdigest()
    key = (task_id, round_id)
    if key in registered and registered[key] != h:
        raise QuorumEquivocationError(
            f"resume mutated evidence for {task_id}/{round_id}: "
            f"registered {registered[key]}, resume produced {h}; "
            f"this must become a new round_id"
        )
    registered[key] = h
    return h
