# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-an-unpropagated-jurisdiction-constraint-after-a-policy-negotiated-capability-handoff-in-cross-org-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-an-unpropagated-jurisdiction-constraint-after-a-policy-negotiated-capability-handoff-in-cross-org-federation.warrant.json
# Markdown SHA-256:   0ae623748382096700a0363d7c9ff8922e6cdade90f6089b2a83c2216e865208
# Code AST SHA-256:   a9c2c2fc85454c68c72dbef3bb3941927c0e82ffbfe41dfd9b6bc8cca8113e42
# Verified Classes:   UnboundResidencyError, CapabilityToken, ToolSchema, Invocation
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class UnboundResidencyError(RuntimeError):
    """Raised when a capability token's residency claim cannot be bound
    to the resolved execution context of a cross-org tool invocation."""
    pass


@dataclass(frozen=True)
class CapabilityToken:
    capability: str
    residency_claim: str  # e.g. "EU"
    issuer: str


@dataclass(frozen=True)
class ToolSchema:
    name: str
    residency_params: frozenset  # params that determine residency
    defaults: dict               # provider defaults for those params


@dataclass(frozen=True)
class Invocation:
    tool: str
    args: dict
    resolved_region: Optional[str]


def enforce_residency_binding(
    token: CapabilityToken,
    schema: ToolSchema,
    invocation: Invocation,
) -> None:
    # Every residency-determining parameter must be explicitly bound in the
    # invocation. A provider default is a latent policy decision and cannot
    # discharge the token's claim.
    unbound = schema.residency_params - invocation.args.keys()
    if unbound:
        raise UnboundResidencyError(
            f"capability {token.capability!r} claims residency "
            f"{token.residency_claim!r} but tool {schema.name!r} leaves "
            f"residency-determining params unbound: {sorted(unbound)}; "
            f"provider defaults {schema.defaults!r} may contradict the claim"
        )

    # Even when bound, the resolved region must match the claim. A bound
    # parameter that resolves to a broader region is still a violation.
    if invocation.resolved_region is None:
        raise UnboundResidencyError(
            f"tool {schema.name!r} did not resolve a concrete region for "
            f"claim {token.residency_claim!r}; cannot verify binding"
        )
    if not invocation.resolved_region.upper().startswith(
        token.residency_claim.upper()
    ):
        raise UnboundResidencyError(
            f"residency claim {token.residency_claim!r} contradicts resolved "
            f"region {invocation.resolved_region!r} for tool {schema.name!r}"
        )
