# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-validate-a-delegated-aaif-capability-token-after-a-sub-agent-mutates-its-own-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-validate-a-delegated-aaif-capability-token-after-a-sub-agent-mutates-its-own-scope.warrant.json
# Markdown SHA-256:   0dc332ae27f6977810df6262bcbce561693bdc4db36495273aa5bd0e3ec1f087
# Code AST SHA-256:   20383f0639ea5adad04a16544346886e1e8f9f678ba7c3d3be98f9efddeaf5d6
# Verified Classes:   ScopeResurrectionError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ScopeResurrectionError(RuntimeError):
    """Raised when a presented token's scope exceeds the intersection of ancestor grants."""


def authorize_operation(presented_token, required_scope, ancestor_chain):
    """
    presented_token: dict with keys iss, scope (set), caveats (list), delegation_depth
    required_scope: set of scope strings the operation needs
    ancestor_chain: list of tokens from immediate parent up to root principal, each
                    with scope (set) and caveats (list)
    """
    if not ancestor_chain:
        raise ScopeResurrectionError(
            "no ancestor chain supplied; cannot verify scope provenance"
        )

    effective = set(presented_token["scope"])
    for ancestor in ancestor_chain:
        effective &= set(ancestor["scope"])

    missing = set(required_scope) - effective
    if missing:
        raise ScopeResurrectionError(
            f"scope resurrection: required {sorted(missing)} not present in "
            f"every ancestor grant; presented scope {sorted(presented_token['scope'])} "
            f"effective scope {sorted(effective)}"
        )

    if presented_token["delegation_depth"] < 0:
        raise ScopeResurrectionError(
            "delegation depth exhausted on holder re-sign"
        )

    for caveat in presented_token["caveats"]:
        if not caveat.evaluate(required_scope):
            raise ScopeResurrectionError(
                f"caveat {caveat.name!r} violated for operation requiring "
                f"{sorted(required_scope)}"
            )

    return True
