# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-delegated-capability-tokens-from-silently-outliving-the-warrant-that-minted-them.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-delegated-capability-tokens-from-silently-outliving-the-warrant-that-minted-them.warrant.json
# Markdown SHA-256:   5619c7b21f5b11666ad3105e56be0c3442af884bee97d338b8ec092914c6f351
# Code AST SHA-256:   979b510527535f611786ad604609101d0c91b31fa84a3f63ad4e0f56fc812650
# Verified Classes:   OrphanedDelegationError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class OrphanedDelegationError(RuntimeError):
    """Raised when a delegated token's claimed authority is not a subset of
    its live issuer chain's current authority at use time."""
    pass


def verify_delegated_capability(token, authority_service, now, max_staleness_s):
    """
    Enforce the use-time intersection invariant for an AAIF scoped token.

    token: dict with keys
        - 'claims_scope': set[str]        scope asserted at mint time
        - 'issuer_chain': list[str]       ordered ancestor token IDs, root first
        - 'exp': float                    token expiry (epoch seconds)
        - 'issued_at': float
    authority_service: callable(token_id) -> dict with 'scope', 'exp', 'revoked'
    """
    if now >= token["exp"]:
        raise OrphanedDelegationError(
            f"token expired at {token['exp']}, now={now}"
        )

    # Walk the chain and intersect current ancestor scopes.
    effective = set(token["claims_scope"])
    for ancestor_id in token["issuer_chain"]:
        ancestor = authority_service(ancestor_id)
        if ancestor is None:
            raise OrphanedDelegationError(
                f"ancestor {ancestor_id} unresolvable; chain broken"
            )
        if ancestor["revoked"]:
            raise OrphanedDelegationError(
                f"ancestor {ancestor_id} revoked; descendant token is orphaned"
            )
        if now >= ancestor["exp"]:
            raise OrphanedDelegationError(
                f"ancestor {ancestor_id} expired at {ancestor['exp']}; "
                f"descendant outlives its warrant"
            )
        # Scope-narrowing: ancestor may have shrunk below the child's claim.
        effective &= set(ancestor["scope"])

    # Staleness bound: the authority snapshot we just read must be fresh enough.
    if now - token["issued_at"] > max_staleness_s:
        raise OrphanedDelegationError(
            f"token age {now - token['issued_at']:.0f}s exceeds "
            f"revocation staleness bound {max_staleness_s}s; re-mint required"
        )

    if not effective:
        raise OrphanedDelegationError(
            "intersection of claimed scope with live chain authority is empty"
        )
    return effective
