# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-refuse-a-capability-grant-it-cannot-verify-the-self-attested-capability-deadlock-in-a2a-role-assignment.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-refuse-a-capability-grant-it-cannot-verify-the-self-attested-capability-deadlock-in-a2a-role-assignment.warrant.json
# Markdown SHA-256:   79a42830df8bcb9c860654d805c70aecfb724ca30ad6bd53f06d22384c3cfcfe
# Code AST SHA-256:   34de438a1a6f97b5c4e1a8221fa8e8f8b02ef81c317d198cb7c3ea20383f2345
# Verified Classes:   UnverifiableCapabilityGrant, ProbeReceipt, Manifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class UnverifiableCapabilityGrant(RuntimeError):
    """Raised when a role grant would rest on self-attestation alone."""
    pass


@dataclass(frozen=True)
class ProbeReceipt:
    canary_input_hash: str
    canary_output_hash: str
    session_id: str
    nonce: str
    peer_id: str


@dataclass(frozen=True)
class Manifest:
    peer_id: str
    capability: str
    confidence: float
    last_success: str | None
    receipt: ProbeReceipt | None


def issue_canary(peer_id: str, session_id: str, nonce: str, payload: bytes) -> str:
    # Coordinator-side: returns the input hash the peer must echo in its receipt.
    return hashlib.sha256(session_id.encode() + nonce.encode() + payload).hexdigest()


def grant_role(
    manifest: Manifest,
    expected_input_hash: str,
    session_id: str,
    nonce: str,
    task_cost_tokens: int,
    probe_cost_tokens: int,
) -> str:
    """Grant a role only on a probe receipt bound to the coordinator's nonce.

    Falls back to claim-ranking only when the probe is not cheaper than the task.
    """
    if probe_cost_tokens >= task_cost_tokens:
        # Probe is not economical; run-and-retry is the correct policy here.
        return manifest.peer_id

    r = manifest.receipt
    if r is None:
        raise UnverifiableCapabilityGrant(
            f"peer {manifest.peer_id} claims {manifest.capability} "
            f"(conf={manifest.confidence}) with no probe receipt; "
            f"self-attestation is not a grant basis"
        )
    if r.nonce != nonce or r.session_id != session_id:
        raise UnverifiableCapabilityGrant(
            f"peer {manifest.peer_id} presented a stale or foreign receipt "
            f"(nonce={r.nonce!r}, session={r.session_id!r}); possible replay"
        )
    if r.canary_input_hash != expected_input_hash:
        raise UnverifiableCapabilityGrant(
            f"peer {manifest.peer_id} probed a different canary than the one issued; "
            f"grantor-chosen canary required"
        )
    if r.peer_id != manifest.peer_id:
        raise UnverifiableCapabilityGrant(
            f"receipt peer_id {r.peer_id} does not match manifest peer_id {manifest.peer_id}"
        )
    return manifest.peer_id
