# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-an-aaif-signed-capability-attestation-whose-delegation-chain-anchors-to-a-revoked-root.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-an-aaif-signed-capability-attestation-whose-delegation-chain-anchors-to-a-revoked-root.warrant.json
# Markdown SHA-256:   9f9cd051173a2dbd5e609e9e8be6b11ea79a3803da3fba1517d39cd7e884d9ba
# Code AST SHA-256:   767c33d2b3830fcfe63fc6a548f91046bcfab0dbf2c1bb6893720f3ae0201369
# Verified Classes:   AnchorState, AnchorResolutionError, CapabilityGrantDenied, AnchorObservation, DelegationChain
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timedelta
from enum import Enum


class AnchorState(Enum):
    LIVE = "live"
    REVOKED = "revoked"
    UNKNOWN = "unknown"


class AnchorResolutionError(RuntimeError):
    """Raised when the anchor's revocation state cannot be confirmed fresh."""
    pass


class CapabilityGrantDenied(RuntimeError):
    """Raised when a delegation chain fails full-closure authorization."""
    pass


@dataclass
class AnchorObservation:
    state: AnchorState
    observed_at: datetime


@dataclass
class DelegationChain:
    root_anchor: str
    leaf_agent: str
    expires_at: datetime
    signatures_valid: bool


STALENESS_BUDGET = timedelta(minutes=5)


def authorize_capability(
    chain: DelegationChain,
    anchor_obs: AnchorObservation,
    now: datetime,
) -> bool:
    if not chain.signatures_valid:
        raise CapabilityGrantDenied(f"signature invalid on chain {chain.leaf_agent}")

    # Anchor liveness is part of the predicate, not a hygiene check.
    if anchor_obs.state is AnchorState.REVOKED:
        raise CapabilityGrantDenied(
            f"anchor {chain.root_anchor} revoked; downstream grants invalid"
        )

    if anchor_obs.state is AnchorState.UNKNOWN:
        raise AnchorResolutionError(
            f"anchor {chain.root_anchor} state unresolved; fail closed"
        )

    age = now - anchor_obs.observed_at
    if age > STALENESS_BUDGET:
        raise AnchorResolutionError(
            f"anchor {chain.root_anchor} observation stale by {age}; re-resolve"
        )

    # Staleness budget must be shorter than remaining delegation validity.
    if anchor_obs.observed_at + STALENESS_BUDGET > chain.expires_at:
        raise CapabilityGrantDenied(
            f"chain {chain.leaf_agent} expires before anchor can be re-confirmed"
        )

    return True
