# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-admit-a-tool-call-that-no-single-federation-policy-permits-cross-org-federation-policy-negotiation-for-data-residency-and-tool-al.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-admit-a-tool-call-that-no-single-federation-policy-permits-cross-org-federation-policy-negotiation-for-data-residency-and-tool-al.warrant.json
# Markdown SHA-256:   1ba8fb53e9aa7802aa1df54c09f6d6f01cae103e44232201ca5a4d290ed6cc83
# Code AST SHA-256:   ed794f508a8b72f3e614a1ef0ecd170ff40789a7f30e6676862d9d1ee84e0ead
# Verified Classes:   FederationEnvelopeError, Manifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Dict, Set, Tuple


class FederationEnvelopeError(RuntimeError):
    """Raised when a negotiated envelope admits a call no single policy permits."""


@dataclass(frozen=True)
class Manifest:
    org: str
    version: str
    # tool -> set of permitted residency regions
    tools: Dict[str, Set[str]]
    # tools for which cross-org delegation is permitted
    delegable: Set[str]


def negotiate(a: Manifest, b: Manifest, *, intersect_tuples: bool) -> Dict[str, Set[str]]:
    """Produce a merged tool->regions envelope.

    intersect_tuples=True yields the sound (tool, region) intersection.
    intersect_tuples=False yields the unsound tool-intersection / region-union.
    """
    shared_tools = set(a.tools) & set(b.tools)
    envelope: Dict[str, Set[str]] = {}
    for tool in shared_tools:
        if intersect_tuples:
            envelope[tool] = a.tools[tool] & b.tools[tool]
        else:
            envelope[tool] = a.tools[tool] | b.tools[tool]
    return envelope


def admit(
    envelope: Dict[str, Set[str]],
    tool: str,
    region: str,
    principal_org: str,
    manifests: Tuple[Manifest, ...],
) -> None:
    """Admit or reject a federated call. Raises on the composition boundary."""
    if tool not in envelope:
        raise FederationEnvelopeError(f"tool {tool!r} not in negotiated envelope")
    if region not in envelope[tool]:
        raise FederationEnvelopeError(
            f"region {region!r} not permitted for {tool!r} in envelope"
        )
    # The boundary check: is there at least one manifest that permits this
    # exact (tool, region) for the calling principal's org?
    if not any(
        tool in m.tools and region in m.tools[tool] and m.org == principal_org
        for m in manifests
    ):
        raise FederationEnvelopeError(
            f"composition boundary violated: call ({tool!r}, {region!r}) "
            f"for principal {principal_org!r} is admitted by the merged envelope "
            f"but permitted by no single manifest"
        )


# Reproduction of the 2026-11-09 incident.
a = Manifest("A", "v7", {"search": {"eu-west"}, "translate": {"us-east"}}, set())
b = Manifest("B", "v3", {"search": {"us-east", "eu-west"}, "translate": {"eu-west"}}, {"search"})

unsound = negotiate(a, b, intersect_tuples=False)
admit(unsound, "search", "us-east", "A", (a, b))  # raises FederationEnvelopeError
