# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-federated-peer-s-capability-attestation-after-a-trust-anchor-rotation-and-why-does-the-naive-answer-break.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-federated-peer-s-capability-attestation-after-a-trust-anchor-rotation-and-why-does-the-naive-answer-break.warrant.json
# Markdown SHA-256:   95750393211412cb135e243ae3a5829a6e31caff2f6eb3e3f1e1f0f193550b66
# Code AST SHA-256:   4b4747b463d9fbabf21d90c4d7ebb030c49561b1ce58dfc8d7b07aa525ee01d5
# Verified Classes:   StaleAttestationError, CapabilityWithdrawnError, CachedGrant, HandoffResponse
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleAttestationError(RuntimeError):
    """Raised when a cached capability grant is used against a rotated anchor-epoch."""
    pass


class CapabilityWithdrawnError(RuntimeError):
    """Raised when the producer reports the capability is no longer delegated."""
    pass


@dataclass(frozen=True)
class CachedGrant:
    peer_id: str
    capability: str
    attestation: bytes
    anchor_epoch: int


@dataclass(frozen=True)
class HandoffResponse:
    accepted: bool
    current_anchor_epoch: int
    rejection_kind: Optional[str] = None  # None | "capability_withdrawn" | "capability_transient" | "transport_error"


def use_cached_grant(grant: CachedGrant, resp: HandoffResponse) -> None:
    """
    Gate a cached cross-org capability grant on anchor-epoch continuity.
    Must be called at every handoff, not once per session.
    """
    if resp.current_anchor_epoch != grant.anchor_epoch:
        # Anchor rotated since the grant was cached. The signature on the
        # cached attestation may still verify against the *old* anchor, but
        # the grant is no longer valid relative to the live trust domain.
        raise StaleAttestationError(
            f"peer={grant.peer_id} cap={grant.capability} "
            f"cached_epoch={grant.anchor_epoch} live_epoch={resp.current_anchor_epoch}; "
            f"discard grant, re-fetch anchor-set, re-verify, and re-plan pending steps"
        )

    if not resp.accepted and resp.rejection_kind == "capability_withdrawn":
        # Same epoch, but the producer withdrew the capability (e.g., policy
        # narrowing within an epoch). Permanent: do NOT retry; re-plan.
        raise CapabilityWithdrawnError(
            f"peer={grant.peer_id} cap={grant.capability} withdrawn at epoch "
            f"{grant.anchor_epoch}; invalidate dependent plan steps and record "
            f"as capability withdrawal, not transport fault"
        )
    # capability_transient / transport_error are handled by the retry policy,
    # not here — but they must never be conflated with the two errors above.
