# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-byzantine-quorum-certificate-that-a-majority-of-honest-peers-never-voted-for.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-byzantine-quorum-certificate-that-a-majority-of-honest-peers-never-voted-for.warrant.json
# Markdown SHA-256:   f1e5ed0410e00adb2d9310674914cbdc7ac2948d1df734f7e4e2e8a53e397d7e
# Code AST SHA-256:   db138592a1151675b6772d378e3c21ef4cfda505fd4474137a6d7a2ac3c7a136
# Verified Classes:   BindingScopeError, Proposal, QuorumCertificate, VerifiedCommitment
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class BindingScopeError(RuntimeError):
    """Raised when a QC's signed preimage does not bind the executed task tuple."""
    pass


@dataclass(frozen=True)
class Proposal:
    view: int
    epoch: int
    task_id: str
    payload_hash: str  # hex digest of payload only


@dataclass(frozen=True)
class QuorumCertificate:
    signed_digest: str      # digest the quorum actually signed
    signatures: tuple       # opaque; assume threshold-verified elsewhere
    signer_count: int


@dataclass(frozen=True)
class VerifiedCommitment:
    """Constructible only by verify_qc_binding. Carries the bound tuple."""
    view: int
    epoch: int
    task_id: str
    payload_hash: str


def canonical_digest(p: Proposal) -> str:
    # The signed preimage MUST include every field the agent will act on.
    preimage = f"{p.view}|{p.epoch}|{p.task_id}|{p.payload_hash}".encode()
    return hashlib.sha256(preimage).hexdigest()


def verify_qc_binding(proposal: Proposal, qc: QuorumCertificate, quorum: int) -> VerifiedCommitment:
    # Layer 1: cryptographic quorum.
    if qc.signer_count < quorum:
        raise BindingScopeError(
            f"quorum shortfall: {qc.signer_count} < {quorum}"
        )
    # Layer 2: the signed digest must bind the FULL tuple, not payload alone.
    expected = canonical_digest(proposal)
    if qc.signed_digest != expected:
        raise BindingScopeError(
            "QC signed digest does not bind (view, epoch, task_id, payload_hash); "
            f"expected {expected}, QC attests {qc.signed_digest}. "
            "Task binding is attacker-controlled and unvoted."
        )
    # Only now may the agent act, and only on fields from the verified preimage.
    return VerifiedCommitment(
        view=proposal.view,
        epoch=proposal.epoch,
        task_id=proposal.task_id,
        payload_hash=proposal.payload_hash,
    )


def commit_task(commitment: VerifiedCommitment, executor) -> None:
    # Type system enforces that only a bound, verified tuple reaches execution.
    if not isinstance(commitment, VerifiedCommitment):
        raise BindingScopeError("commit_task requires a VerifiedCommitment")
    executor(commitment.task_id, commitment.payload_hash)
