# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-bft-quorum-certificate-when-the-signing-agents-committed-task-state-has-diverged-from-the-certificate-s-cl.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-a-bft-quorum-certificate-when-the-signing-agents-committed-task-state-has-diverged-from-the-certificate-s-cl.warrant.json
# Markdown SHA-256:   d08c29a99e0d317bf6ee6819f58c0a47a2788ba610d2228719bf9b0403eeee71
# Code AST SHA-256:   f42125e22a09a740a808adb95db6e6e71c0b7ac049afd4c51288fda8f9b7cc7f
# Verified Classes:   NonTransferableAttestationError, QuorumCertificate
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Mapping


class NonTransferableAttestationError(RuntimeError):
    """Raised when a quorum certificate's state root cannot be reconstructed
    from committed, deterministic inputs by a receiving agent."""
    pass


@dataclass(frozen=True)
class QuorumCertificate:
    view: int
    state_root: str          # hex digest claimed by the QC
    signers: tuple[str, ...]
    dag_hash: str            # hash of the committed task DAG
    blob_refs: tuple[str, ...]  # content-addressed refs to committed blobs


def recompute_root(dag_hash: str, blobs: Mapping[str, bytes]) -> str:
    """Deterministic reconstruction: root over DAG hash + sorted blob hashes.
    Episodic memory and reasoning traces MUST NOT be included."""
    h = hashlib.sha256()
    h.update(dag_hash.encode())
    for ref in sorted(blobs):
        h.update(ref.encode())
        h.update(hashlib.sha256(blobs[ref]).digest())
    return h.hexdigest()


def adopt_certificate(
    qc: QuorumCertificate,
    local_blobs: Mapping[str, bytes],
    quorum_size: int,
) -> str:
    """Adopt a QC only if its root is reconstructible from committed inputs.
    Otherwise raise NonTransferableAttestationError — do NOT halt as corrupt."""
    if len(set(qc.signers)) < quorum_size:
        raise NonTransferableAttestationError(
            f"QC view={qc.view} has {len(set(qc.signers))} signers, "
            f"below quorum {quorum_size}"
        )

    missing = [r for r in qc.blob_refs if r not in local_blobs]
    if missing:
        # State-transfer trigger, not a corruption verdict.
        raise NonTransferableAttestationError(
            f"QC view={qc.view} root={qc.state_root[:12]} not reconstructible: "
            f"missing blobs {missing}; enter state-sync path"
        )

    reconstructed = recompute_root(qc.dag_hash, local_blobs)
    if reconstructed != qc.state_root:
        # Attributable divergence: the signers attested a root we cannot rebuild.
        raise NonTransferableAttestationError(
            f"QC view={qc.view} claimed root={qc.state_root[:12]} but "
            f"reconstructed={reconstructed[:12]}; signers {qc.signers} "
            f"attested a non-transferable state root"
        )

    return qc.state_root
