# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-aaif-capability-token-whose-scope-was-attenuated-against-a-stale-delegation-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-presents-a-valid-aaif-capability-token-whose-scope-was-attenuated-against-a-stale-delegation-chain.warrant.json
# Markdown SHA-256:   8896ddf83a268344daa063d31d3f034289c432f234179287e36c77cb425bb1a1
# Code AST SHA-256:   d60ffc51485b6a98c47c050f1936de56efd975f58884de29d68d33bdd5f5d517
# Verified Classes:   StaleDelegationChainError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StaleDelegationChainError(RuntimeError):
    """Raised when a capability token's delegation chain was attenuated
    against an ancestor snapshot that is no longer the ledger head."""
    pass


def verify_capability(token, ledger, max_depth=8):
    chain = resolve_chain(token)  # embedded, signed, self-authenticating
    if len(chain) > max_depth:
        raise StaleDelegationChainError(
            f"chain depth {len(chain)} exceeds bound {max_depth}"
        )
    for link in chain:
        head_scope = ledger.head_scope(link.issuer_id, link.credential_id)
        if head_scope is None:
            # ledger unreachable or credential unknown: fail closed
            raise StaleDelegationChainError(
                f"cannot resolve head for {link.credential_id}; "
                f"refusing embedded-trust fallback"
            )
        if not link.embedded_scope.issubset(head_scope):
            raise StaleDelegationChainError(
                f"link {link.credential_id} embedded scope "
                f"{link.embedded_scope} exceeds head scope {head_scope}; "
                f"attenuation computed against superseded parent"
            )
    # only now is the chain-head invariant satisfied
    return authorize(token.scope, chain[0].head_scope)
