# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-cross-org-capability-scope-leak-in-federated-agent-negotiation-before-the-first-tool-call-executes.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-cross-org-capability-scope-leak-in-federated-agent-negotiation-before-the-first-tool-call-executes.warrant.json
# Markdown SHA-256:   27b58fb3e74cc9313f24758575b3ae1d39f266ce15b6ddff60a0d0f0e79806df
# Code AST SHA-256:   7848fc99b9877a53464575252fecef5f8f77376aa8dce3a1a80d9c5561e46c0f
# Verified Classes:   ScopeWideningError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class ScopeWideningError(RuntimeError):
    """Raised when a provider-issued capability grant exceeds the requested scope."""
    pass


def validate_grant_monotonicity(requested_scope: dict, granted_scope: dict) -> None:
    """
    Enforce that granted_scope is a subset of requested_scope.
    Raised before any tool call executes. Structured qualifiers only.
    """
    for key, req_val in requested_scope.items():
        if key not in granted_scope:
            # Grant omitted a requested qualifier; provider may have defaulted it.
            raise ScopeWideningError(
                f"grant missing requested qualifier {key!r}; cannot prove subset"
            )
        grant_val = granted_scope[key]

        if isinstance(req_val, list):
            # Field allowlist: granted fields must be a subset of requested.
            extra = set(grant_val) - set(req_val)
            if extra:
                raise ScopeWideningError(
                    f"grant widens {key!r}: extra fields {sorted(extra)}"
                )
        elif isinstance(req_val, (int, float)):
            # Numeric bound: granted must not exceed requested.
            if grant_val > req_val:
                raise ScopeWideningError(
                    f"grant widens {key!r}: {grant_val} > requested {req_val}"
                )
        elif isinstance(req_val, str):
            # Scalar qualifier (e.g. tenant): must match exactly unless wildcard requested.
            if req_val != "*" and grant_val != req_val:
                raise ScopeWideningError(
                    f"grant widens {key!r}: {grant_val!r} != requested {req_val!r}"
                )
        else:
            raise ScopeWideningError(
                f"qualifier {key!r} has non-comparable type {type(req_val).__name__}; "
                "federation schema must use structured qualifiers"
            )


def negotiate_and_execute(requested_scope: dict, provider_mint, tool_call) -> dict:
    grant = provider_mint(requested_scope)  # returns {"scope": {...}, "warrant": "..."}
    try:
        validate_grant_monotonicity(requested_scope, grant["scope"])
    except ScopeWideningError:
        # Fail loud at grant-receipt; do not proceed to tool_call.
        raise
    # Execution bounds recomputed from the grant, never cached from the request.
    execution_bounds = {k: grant["scope"][k] for k in requested_scope}
    return tool_call(execution_bounds)
