# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-aaif-scoped-capability-tokens-when-delegated-attenuation-outlives-the-parent-warrant-s-revocation-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-aaif-scoped-capability-tokens-when-delegated-attenuation-outlives-the-parent-warrant-s-revocation-epoch.warrant.json
# Markdown SHA-256:   a08fef005cc311e9bad3f3233bef6648ea40d7b2b0c7bf5096c9f04429759c89
# Code AST SHA-256:   32b0e823d2ac9dc0789821a2e6bd90fa744a855390e36de283b2ee62591668c9
# Verified Classes:   StaleEpochDelegationError, CapabilityToken, Attestation
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleEpochDelegationError(RuntimeError):
    """Raised when a delegated AAIF token's parent epoch is behind the root's current epoch."""
    pass


@dataclass(frozen=True)
class CapabilityToken:
    warrant_id: str
    parent_epoch: int
    scope: frozenset
    expiry: float
    signature_valid: bool


@dataclass(frozen=True)
class Attestation:
    warrant_id: str
    current_epoch: int
    fetched_at: float


def verify_delegated_invocation(
    token: CapabilityToken,
    requested_action: str,
    now: float,
    attestation: Optional[Attestation],
    max_staleness: float,
) -> bool:
    # Structural checks: offline, cheap, necessary.
    if not token.signature_valid:
        raise StaleEpochDelegationError(
            f"token for warrant {token.warrant_id} has invalid signature"
        )
    if now >= token.expiry:
        raise StaleEpochDelegationError(
            f"token for warrant {token.warrant_id} expired at {token.expiry}"
        )
    if requested_action not in token.scope:
        raise StaleEpochDelegationError(
            f"action {requested_action!r} outside scope {sorted(token.scope)}"
        )

    # Epoch anchoring: the conjunct that cannot be checked offline.
    if attestation is None:
        raise StaleEpochDelegationError(
            f"no attestation for warrant {token.warrant_id}; "
            "offline verification is insufficient for delegated authority"
        )
    if attestation.warrant_id != token.warrant_id:
        raise StaleEpochDelegationError(
            f"attestation warrant {attestation.warrant_id} != token warrant {token.warrant_id}"
        )
    if now - attestation.fetched_at > max_staleness:
        raise StaleEpochDelegationError(
            f"attestation for {token.warrant_id} stale by "
            f"{now - attestation.fetched_at:.1f}s > {max_staleness}s"
        )
    if token.parent_epoch < attestation.current_epoch:
        raise StaleEpochDelegationError(
            f"token epoch {token.parent_epoch} < root epoch "
            f"{attestation.current_epoch} for warrant {token.warrant_id}; "
            "delegation outlived parent revocation"
        )

    return True
