# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-delegated-scope-authority-mid-tool-chain-when-aaif-attestation-tokens-outlive-their-minting-context.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-delegated-scope-authority-mid-tool-chain-when-aaif-attestation-tokens-outlive-their-minting-context.warrant.json
# Markdown SHA-256:   4f1ae5f436a926ae5d587c2811407bb146f958f1a7e4075024b99e153fdc518e
# Code AST SHA-256:   b5dc4f2fedee83a25c3b25dc9c7f4922a6d10e599feb13842f99f6747ccdd103
# Verified Classes:   ScopeChainViolation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ScopeChainViolation(RuntimeError):
    """Raised when a tool call's required scope is not covered by a token
    whose delegation chain terminates at the calling agent identity."""
    pass


def authorize_tool_call(
    caller_id: str,
    required_scope: set[str],
    token_cache: list[dict],
    current_plan_hash: str,
) -> dict:
    # Select only tokens whose terminal delegate is the caller (chain binding)
    bound = [t for t in token_cache if t["delegate"] == caller_id]
    if not bound:
        raise ScopeChainViolation(
            f"no AAIF token bound to caller {caller_id!r}; "
            f"cannot authorize {sorted(required_scope)}"
        )

    # Effective scope is the narrowest grant across the caller's bound tokens
    # at the caller's depth; never the union with ancestor tokens.
    caller_depth = max(t["depth"] for t in bound)
    at_depth = [t for t in bound if t["depth"] == caller_depth]
    effective = set().union(*(t["scope"] for t in at_depth))

    # Plan divergence invalidates reuse even if scope happens to match
    diverged = any(t["plan_hash"] != current_plan_hash for t in at_depth)
    if diverged and not required_scope.issubset(effective):
        raise ScopeChainViolation(
            f"plan diverged and required scope {sorted(required_scope)} "
            f"exceeds attested {sorted(effective)}; re-attestation required"
        )

    if not required_scope.issubset(effective):
        missing = required_scope - effective
        raise ScopeChainViolation(
            f"scope escalation blocked: caller {caller_id!r} at depth "
            f"{caller_depth} lacks {sorted(missing)}; delegator must re-grant"
        )

    return next(t for t in at_depth if required_scope.issubset(t["scope"]))
