# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-cross-org-federation-policy-engine-has-silently-widened-a-data-residency-boundary-through-capability-aliasing.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-cross-org-federation-policy-engine-has-silently-widened-a-data-residency-boundary-through-capability-aliasing.warrant.json
# Markdown SHA-256:   e67ef183755a3500752d5cee5a82f5ea42fad9ea3b08c1d3dfb9584d5e2f0246
# Code AST SHA-256:   c2e6509e9fedecf1a282180221ee203f0adfd39f6e5eb1365fd70e68f7eec970
# Verified Classes:   ResidencyWideningError, CapNode, Grant
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class ResidencyWideningError(RuntimeError):
    """Raised when alias resolution moves an execution to a region outside the caller's grant."""


@dataclass
class CapNode:
    name: str
    region: str
    impl: str | None = None


@dataclass
class Grant:
    capability: str
    allowed_regions: set[str]
    resolved_chain: list[str] = field(default_factory=list)


def resolve(node_name: str, registry: dict[str, CapNode], max_hops: int = 8) -> tuple[CapNode, list[str]]:
    chain: list[str] = []
    seen: set[str] = set()
    cur = node_name
    while True:
        if cur in seen:
            raise ResidencyWideningError(f"alias cycle at {cur!r}: {chain}")
        seen.add(cur)
        chain.append(cur)
        node = registry.get(cur)
        if node is None:
            raise ResidencyWideningError(f"unresolved capability {cur!r}")
        if node.impl is None:
            return node, chain
        if len(chain) >= max_hops:
            raise ResidencyWideningError(f"alias chain exceeds {max_hops} hops: {chain}")
        cur = node.impl


def gate(call_cap: str, grant: Grant, registry: dict[str, CapNode]) -> str:
    resolved, chain = resolve(call_cap, registry)

    # Invariant 1: capability must be the grant's capability, checked post-resolution.
    if resolved.name != grant.capability and call_cap != grant.capability:
        raise ResidencyWideningError(
            f"capability mismatch: resolved {resolved.name!r} not in grant {grant.capability!r}"
        )

    # Invariant 2: residency gated on the RESOLVED node's region, not the alias tag.
    if resolved.region not in grant.allowed_regions:
        raise ResidencyWideningError(
            f"residency widening: {call_cap!r} -> {resolved.name!r} executes in "
            f"{resolved.region!r}, grant allows {sorted(grant.allowed_regions)}; chain={chain}"
        )

    # Invariant 3: audit must carry resolved identity, not alias identity.
    grant.resolved_chain = chain
    return resolved.region


# Reproduces the incident: alias says eu-west, impl executes us-east-1.
registry = {
    "summarize_v2": CapNode("summarize_v2", "eu-west", impl="summarize_core"),
    "summarize_core": CapNode("summarize_core", "us-east-1", impl="text_pipeline"),
    "text_pipeline": CapNode("text_pipeline", "us-east-1"),
}
grant = Grant(capability="summarize_v2", allowed_regions={"eu-west"})

try:
    gate("summarize_v2", grant, registry)
except ResidencyWideningError as e:
    print("DENIED:", e)
