# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-agent-manifest-whose-capability-attestation-was-signed-over-a-stale-capability-set.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-agent-manifest-whose-capability-attestation-was-signed-over-a-stale-capability-set.warrant.json
# Markdown SHA-256:   e17fa2703aabdc9c8154b58fdfd79b69acfa3c69901e2cab98a5afe0d117f675
# Code AST SHA-256:   4cf7fb622cdf9ed2c0f131c061eebbedabcddecaff94a2b8ff71382122be6383
# Verified Classes:   CapabilityAttestationError, ProbeResult, SignedManifest
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from enum import Enum
from typing import Callable


class CapabilityAttestationError(RuntimeError):
    """Raised when a federated peer's attested capability set cannot be
    corroborated against its live capability state at the action boundary."""


class ProbeResult(Enum):
    GRANTED = "granted"
    DENIED = "denied"
    UNKNOWN = "unknown"


@dataclass(frozen=True)
class SignedManifest:
    peer_id: str
    capabilities: frozenset[str]
    signature_valid: bool
    epoch: int
    expiry_ts: float


def authorize_action(
    manifest: SignedManifest,
    capability: str,
    now_ts: float,
    issuer_current_epoch: Callable[[str], int | None],
    live_probe: Callable[[str, str], ProbeResult],
) -> None:
    """Authorize a single delegated action against a federated peer.

    The signed manifest is a *claim*; this function requires a live
    corroboration before the action proceeds. Fails closed on any
    ambiguity: unreachable epoch source, unknown probe, or stale epoch
    all abort the delegation rather than degrade it.
    """
    if not manifest.signature_valid:
        raise CapabilityAttestationError(
            f"manifest for {manifest.peer_id} failed signature verification"
        )
    if now_ts >= manifest.expiry_ts:
        raise CapabilityAttestationError(
            f"manifest for {manifest.peer_id} expired at {manifest.expiry_ts}"
        )
    if capability not in manifest.capabilities:
        raise CapabilityAttestationError(
            f"capability {capability!r} not present in attested set for "
            f"{manifest.peer_id}"
        )

    current_epoch = issuer_current_epoch(manifest.peer_id)
    if current_epoch is None:
        # Partition between relying agent and issuer: fail closed.
        raise CapabilityAttestationError(
            f"issuer epoch for {manifest.peer_id} unreachable; "
            f"cannot corroborate attestation freshness"
        )
    if manifest.epoch < current_epoch:
        # Issuer has advanced its policy epoch since this attestation was
        # signed; the attested capability set may no longer be a superset
        # of the peer's live capabilities. Refuse to act on the stale claim.
        raise CapabilityAttestationError(
            f"stale attestation for {manifest.peer_id}: manifest epoch "
            f"{manifest.epoch} < issuer epoch {current_epoch}"
        )

    result = live_probe(manifest.peer_id, capability)
    if result is not ProbeResult.GRANTED:
        # DENIED or UNKNOWN both abort. Critically: this must NOT be caught
        # by a retry/fallback handler that substitutes a different tool.
        raise CapabilityAttestationError(
            f"live probe for {manifest.peer_id}:{capability} returned "
            f"{result.value}; aborting delegation (no fallback permitted)"
        )
