# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-delegated-capability-token-replay-across-agent-restarts-in-aaif-scoped-credentials.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-delegated-capability-token-replay-across-agent-restarts-in-aaif-scoped-credentials.warrant.json
# Markdown SHA-256:   98de598ffe26ff1b58fa4bc87a614fcc9d43241b305685908beab10f37eee94e
# Code AST SHA-256:   5769c463d0ed48fa8eb85788589a93338b7720c6375a78aa31f95b83270cd416
# Verified Classes:   StaleDelegationEpoch, EpochManifestUnavailable, CapabilityToken, EpochManifest
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleDelegationEpoch(RuntimeError):
    """Raised when a presented capability token's epoch is behind the issuer's current epoch."""
    pass


class EpochManifestUnavailable(RuntimeError):
    """Raised when the PEP cannot confirm the issuer's current epoch; must fail closed."""
    pass


@dataclass(frozen=True)
class CapabilityToken:
    instance_id: str
    delegation_chain: str
    epoch: int
    boot_nonce: str
    scope: str
    expires_at: float


@dataclass(frozen=True)
class EpochManifest:
    chain: str
    current_epoch: int
    fetched_at: float


def authorize_presentation(
    token: CapabilityToken,
    instance_boot_nonce: str,
    manifest: EpochManifest | None,
    manifest_max_age_s: float,
    now: float | None = None,
) -> bool:
    now = time.monotonic() if now is None else now

    if manifest is None or (now - manifest.fetched_at) > manifest_max_age_s:
        raise EpochManifestUnavailable(
            f"no fresh epoch manifest for chain {token.delegation_chain!r}; "
            "refusing to authorize on TTL alone"
        )

    if token.delegation_chain != manifest.chain:
        raise EpochManifestUnavailable(
            f"manifest chain {manifest.chain!r} does not match token chain "
            f"{token.delegation_chain!r}"
        )

    if token.epoch > manifest.current_epoch:
        raise StaleDelegationEpoch(
            f"token epoch {token.epoch} ahead of issuer epoch "
            f"{manifest.current_epoch}; possible forgery or clock skew"
        )

    if token.epoch < manifest.current_epoch:
        raise StaleDelegationEpoch(
            f"token epoch {token.epoch} behind issuer epoch "
            f"{manifest.current_epoch}; delegation revoked during restart window"
        )

    if token.boot_nonce != instance_boot_nonce:
        raise StaleDelegationEpoch(
            f"token boot nonce {token.boot_nonce!r} does not match live instance "
            f"{instance_boot_nonce!r}; token minted for a prior process"
        )

    if token.expires_at <= now:
        raise StaleDelegationEpoch(
            f"token expired at {token.expires_at}; epoch matched but TTL elapsed"
        )

    return True
