# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-forged-commit-certificate-during-speculative-agent-branch-reconciliation-under-byzantine-quorum-assumptions.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-forged-commit-certificate-during-speculative-agent-branch-reconciliation-under-byzantine-quorum-assumptions.warrant.json
# Markdown SHA-256:   8442b595a7eb8447676bc1b1eb32de9d63134a801739f9f36f820a618c231336
# Code AST SHA-256:   947377f9899bcf1caf68d034ed1aa557e9475d545486a99faeb98edd02cb9c09
# Verified Classes:   StaleQuorumCertificateError, InsufficientQuorumError, CommitCertificate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import FrozenSet


class StaleQuorumCertificateError(RuntimeError):
    """Raised when a commit certificate's epoch does not bind to the current reconfiguration epoch."""
    pass


class InsufficientQuorumError(RuntimeError):
    pass


@dataclass(frozen=True)
class CommitCertificate:
    epoch: int
    agent_id: str
    step_index: int
    payload_hash: str
    signers: FrozenSet[str]  # public keys, not indices
    signatures_valid: bool


def branch_digest(epoch: int, agent_id: str, step_index: int, payload_hash: str) -> str:
    # epoch is inside the hash: a stale cert cannot collide with a current-epoch branch
    h = hashlib.sha256()
    h.update(f"{epoch}|{agent_id}|{step_index}|{payload_hash}".encode())
    return h.hexdigest()


def verify_commit_certificate(
    cert: CommitCertificate,
    current_epoch: int,
    membership: FrozenSet[str],
    f: int,
) -> bool:
    if cert.epoch != current_epoch:
        raise StaleQuorumCertificateError(
            f"cert epoch {cert.epoch} != current epoch {current_epoch}; "
            f"branch {cert.agent_id}/{cert.step_index} quarantined"
        )
    if not cert.signatures_valid:
        raise InsufficientQuorumError("signature verification failed")
    if not cert.signers.issubset(membership):
        raise InsufficientQuorumError(
            f"signers {cert.signers - membership} not in epoch-{current_epoch} membership"
        )
    if len(cert.signers) < 2 * f + 1:
        raise InsufficientQuorumError(
            f"quorum {len(cert.signers)} < {2 * f + 1}"
        )
    return True


def reconcile_branch(
    cert: CommitCertificate,
    current_epoch: int,
    membership: FrozenSet[str],
    f: int,
) -> str:
    verify_commit_certificate(cert, current_epoch, membership, f)
    return branch_digest(cert.epoch, cert.agent_id, cert.step_index, cert.payload_hash)
