# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-delegates-a-scoped-token-across-a-capability-boundary-it-cannot-name.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-delegates-a-scoped-token-across-a-capability-boundary-it-cannot-name.warrant.json
# Markdown SHA-256:   2f2ade03af302d6553d843f94d329995abd2faa53039d5a11dcb35748b94fb74
# Code AST SHA-256:   9412b98e6a35a204cdf6651a61c741dbd7b6e2879296ce051e61063c71c4d79d
# Verified Classes:   DelegationScopeError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class DelegationScopeError(RuntimeError):
    """Raised when a delegated token cannot express the resource constraint
    its parent holds, i.e. a tool-scoped token is minted for a resource-open
    tool without an accompanying resource claim."""
    pass


def mint_child_token(parent_claims: dict, child_request: dict,
                     tool_registry: dict) -> dict:
    tool = child_request["tool"]
    spec = tool_registry.get(tool)
    if spec is None:
        raise DelegationScopeError(f"unknown tool {tool!r}")

    if not spec["resource_closed"]:
        # Resource-open tool: the token MUST carry a resource claim that is a
        # subset of the parent's grant. Tool name alone is not authority.
        requested_res = child_request.get("resource_claim")
        if requested_res is None:
            raise DelegationScopeError(
                f"tool {tool!r} is resource-open; refusing to mint "
                f"tool-scoped-only token without resource_claim"
            )
        parent_res = set(parent_claims.get("resources", []))
        if not set(requested_res).issubset(parent_res):
            raise DelegationScopeError(
                f"resource_claim {requested_res!r} not entailed by "
                f"parent grant {sorted(parent_res)!r}"
            )
        return {
            "sub": child_request["sub"],
            "aud": tool,
            "scope": [f"tool:{tool}"],
            "resource_claim": requested_res,
            "parent": parent_claims["id"],
        }

    # Resource-closed tool: tool scope is sufficient authority.
    return {
        "sub": child_request["sub"],
        "aud": tool,
        "scope": [f"tool:{tool}"],
        "parent": parent_claims["id"],
    }


def verify_call(token: dict, resolved_resource: str,
                tool_registry: dict) -> bool:
    tool = token["aud"]
    spec = tool_registry[tool]
    if spec["resource_closed"]:
        return True
    claim = token.get("resource_claim")
    if claim is None:
        raise DelegationScopeError(
            f"token for resource-open tool {tool!r} has no resource_claim; "
            f"cannot authorize resolved resource {resolved_resource!r}"
        )
    return resolved_resource in claim
