# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-peer-s-capability-grant-before-trust-bootstrap-attestation-has-converged.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-peer-s-capability-grant-before-trust-bootstrap-attestation-has-converged.warrant.json
# Markdown SHA-256:   806419faf27e4b6b23c3a5efe590761bd9368005875bcdf57f0bed8b932f4986
# Code AST SHA-256:   d009b12738d905a718d24cefac6c1ba5e68286f9f134075d31c8e5833af8795d
# Verified Classes:   TrustBootstrapError, PinState, CapabilityGrant, PinStore
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum


class TrustBootstrapError(RuntimeError):
    """Raised when a capability grant is acted upon before trust-anchor convergence."""


class PinState(Enum):
    CONVERGED = "converged"
    DIVERGED = "diverged"
    IN_FLIGHT = "in_flight"


@dataclass
class CapabilityGrant:
    peer_id: str
    chain_anchor: str
    signature_valid: bool
    peer_corroboration: tuple[str, ...] = ()


@dataclass
class PinStore:
    pinned_roots: frozenset[str]
    durably_committed: bool


def classify_grant(grant: CapabilityGrant, store: PinStore) -> PinState:
    if not store.durably_committed:
        return PinState.IN_FLIGHT
    if grant.chain_anchor in store.pinned_roots:
        return PinState.CONVERGED
    return PinState.DIVERGED


def accept_grant(grant: CapabilityGrant, store: PinStore, deferral_budget_exhausted: bool) -> bool:
    if not grant.signature_valid:
        raise TrustBootstrapError(f"grant from {grant.peer_id} failed signature check")

    state = classify_grant(grant, store)

    if state is PinState.IN_FLIGHT:
        if deferral_budget_exhausted:
            raise TrustBootstrapError(
                f"pin store did not commit within bootstrap deadline; "
                f"cannot evaluate grant from {grant.peer_id} (anchor={grant.chain_anchor})"
            )
        return False  # defer: do not honor, do not reject

    if state is PinState.DIVERGED:
        # Peer corroboration is explicitly NOT admissible here: it is transitive
        # over the same unpinned anchor and cannot substitute for local pinning.
        raise TrustBootstrapError(
            f"grant from {grant.peer_id} anchored at unpinned root {grant.chain_anchor}; "
            f"corroboration={grant.peer_corroboration} rejected as non-authoritative"
        )

    return True  # CONVERGED: anchor is locally pinned and durably committed
