# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-residency-constraints-across-a-federated-trust-boundary-and-the-audit-trail-forks.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-residency-constraints-across-a-federated-trust-boundary-and-the-audit-trail-forks.warrant.json
# Markdown SHA-256:   a9521513104484ee57bb53dc73a9b382ce82c2c4822bc583e42a1f22b3895817
# Code AST SHA-256:   af4534e9bfce8e43b28d88c8427cd3ed5c219b422951e3f8f0be9f52af9b7c7a
# Verified Classes:   ResidencyScopeFork
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class ResidencyScopeFork(RuntimeError):
    """Raised when a delegated warrant's scope cannot be totally mapped
    onto the serving agent's capability set, or when a runtime op's
    region is not covered by the raw warrant scope."""
    pass


def negotiate_warrant(warrant_scope: str, capability_tags: set[str],
                      mapping: dict[str, set[str]]) -> set[str]:
    tokens = set(warrant_scope.split("+"))
    unmapped = {t for t in tokens if t not in mapping}
    if unmapped:
        # Fail closed: never fall through to a permissive default
        # across an org boundary.
        raise ResidencyScopeFork(
            f"unmapped scope tokens {sorted(unmapped)}; refusing to "
            f"negotiate a warrant whose scope is not total"
        )
    granted = set().union(*(mapping[t] for t in tokens))
    uncovered = capability_tags - granted
    if uncovered:
        raise ResidencyScopeFork(
            f"capability tags {sorted(uncovered)} are not covered by "
            f"granted scope; serving agent could execute an "
            f"un-auditable op"
        )
    return granted


def runtime_gate(op_region: str, op_tag: str, raw_warrant_scope: str,
                 allowed_regions: dict[str, set[str]]) -> None:
    tokens = set(raw_warrant_scope.split("+"))
    # Check against the RAW scope, not the mapped tag set.
    if op_tag not in tokens:
        raise ResidencyScopeFork(
            f"op tag {op_tag!r} not in raw warrant scope "
            f"{raw_warrant_scope!r}; audit trail would fork"
        )
    if op_region not in allowed_regions.get(op_tag, set()):
        raise ResidencyScopeFork(
            f"op region {op_region!r} violates residency for "
            f"scope {raw_warrant_scope!r}"
        )
