# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-resolve-cross-org-federation-policy-conflicts-when-a2a-task-graph-edges-carry-divergent-delegation-constraints.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-resolve-cross-org-federation-policy-conflicts-when-a2a-task-graph-edges-carry-divergent-delegation-constraints.warrant.json
# Markdown SHA-256:   fa67430c183c3333888c87f30de5831e7be0037412c4147c3694f82c7e73082d
# Code AST SHA-256:   1ba93412d0553f54200197ed87609a2f6e510e3439d128f050a5cb065753b4bc
# Verified Classes:   PolicyMeetUndefined, FederationPolicy
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Optional

class PolicyMeetUndefined(RuntimeError):
    """Raised when two federation policies have no well-formed meet on an edge."""
    def __init__(self, edge: tuple[str, str], axis: str, left, right):
        self.edge, self.axis, self.left, self.right = edge, axis, left, right
        super().__init__(
            f"meet undefined on edge {edge[0]}->{edge[1]} axis={axis}: "
            f"{left!r} ⊓ {right!r} = ⊥"
        )

@dataclass(frozen=True)
class FederationPolicy:
    max_hop_depth: int
    allowed_tools: FrozenSet[str]
    residency: FrozenSet[str]

def meet(edge: tuple[str, str], outbound: FederationPolicy,
         inbound: FederationPolicy) -> FederationPolicy:
    # depth: min is always defined
    depth = min(outbound.max_hop_depth, inbound.max_hop_depth)
    # tools: empty intersection is ⊥, not an empty allowlist
    tools = outbound.allowed_tools & inbound.allowed_tools
    if not tools:
        raise PolicyMeetUndefined(edge, "allowed_tools",
                                  outbound.allowed_tools, inbound.allowed_tools)
    # residency: empty intersection is ⊥
    res = outbound.residency & inbound.residency
    if not res:
        raise PolicyMeetUndefined(edge, "residency",
                                  outbound.residency, inbound.residency)
    return FederationPolicy(depth, tools, res)

def plan_graph(edges, policies):
    """Evaluate meet for every edge before dispatch. Fail closed."""
    resolved = {}
    for parent, child in edges:
        outbound = policies[parent].outbound
        inbound = policies[child].inbound
        resolved[(parent, child)] = meet((parent, child), outbound, inbound)
    return resolved
