# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-hardware-attested-identity-whose-short-lived-aaif-delegation-token-expires-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-hardware-attested-identity-whose-short-lived-aaif-delegation-token-expires-mid-execution.warrant.json
# Markdown SHA-256:   6399b7fe2c57547e71dc637cf0ceab4cab85612ecef15e5e0342f98ea2c19979
# Code AST SHA-256:   d6a8a40938b0c2a0682b71a3b2ef30ffda4ce43f4bce0ec6c4b411e68461ff70
# Verified Classes:   DelegationAuthorityError, AAIFToken
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class DelegationAuthorityError(RuntimeError):
    """Raised when an action is attempted without live delegated authority.

    Distinct from attestation failure: the enclave may be perfectly healthy.
    """


@dataclass(frozen=True)
class AAIFToken:
    not_after: float          # absolute epoch seconds
    capabilities: frozenset  # e.g. {"write:patch", "call:test-runner"}
    parent_warrant_revoked: bool = False


def require_authority(
    token: AAIFToken | None,
    capability: str,
    now: float | None = None,
) -> None:
    """Gate a side-effecting action on live delegated authority.

    Called per-action, at the moment of the effect. Does NOT consult or
    cache attestation state: a valid enclave quote is not evidence of
    authority and must never substitute for this check.
    """
    now = time.time() if now is None else now

    if token is None:
        raise DelegationAuthorityError(
            "no AAIF token in scope; identity alone does not authorize action"
        )
    if token.parent_warrant_revoked:
        raise DelegationAuthorityError(
            "parent warrant revoked; halt and surface as authority error, "
            "do not retry and do not re-attest"
        )
    if now >= token.not_after:
        raise DelegationAuthorityError(
            f"AAIF delegation expired at {token.not_after:.0f} "
            f"(now={now:.0f}); request re-issuance from parent, "
            f"do NOT re-run attestation"
        )
    if capability not in token.capabilities:
        raise DelegationAuthorityError(
            f"capability {capability!r} not in token scope "
            f"{sorted(token.capabilities)}"
        )


def execute_tool_call(token: AAIFToken | None, capability: str, fn, *args):
    # Re-verify at the point of effect, not at session open.
    require_authority(token, capability)
    return fn(*args)
