# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-policy-warrant-divergence-at-a-federation-gateway-when-negotiated-capability-scopes-silently-widen-across-an-asymmetric-po.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-policy-warrant-divergence-at-a-federation-gateway-when-negotiated-capability-scopes-silently-widen-across-an-asymmetric-po.warrant.json
# Markdown SHA-256:   744b5c3830214503742e2ebadc31f9f93825508a3a19e39e9974c96254a1e70f
# Code AST SHA-256:   30050708db6f51ef59ad40906d959f0b5a00d3a93e3af52416c987ac5309832d
# Verified Classes:   PolicyWarrantDivergence, Policy, ExecutedCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class PolicyWarrantDivergence(RuntimeError):
    """Raised when a negotiated federation scope is locally non-empty on both
    sides but the two intersections were computed over different attribute
    lattices, so the executed call is not bounded by either full policy."""


@dataclass
class Policy:
    # attribute -> allowed value set; "*" means unconstrained on that axis
    constraints: dict[str, set[str]] = field(default_factory=dict)


@dataclass
class ExecutedCall:
    capability: str
    bindings: dict[str, str]


def negotiate_and_verify(
    local_policy: Policy,
    peer_echoed_manifest_attrs: set[str],
    executed: ExecutedCall,
) -> None:
    """Fail-closed verification of a cross-boundary call after negotiation.

    The negotiated intersection is trusted only if the peer's echoed manifest
    covers every attribute the local policy constrains on. Otherwise the
    intersection is unsound and the call must be rejected.
    """
    local_attrs = set(local_policy.constraints.keys())

    missing = local_attrs - peer_echoed_manifest_attrs
    if missing:
        # Peer serialized away attributes we constrain on -> divergent lattice.
        raise PolicyWarrantDivergence(
            f"capability={executed.capability!r}: peer manifest omits "
            f"attributes {sorted(missing)} that local policy constrains; "
            f"intersection is unsound, refusing call"
        )

    # Replay the executed bindings against the local policy.
    for attr, allowed in local_policy.constraints.items():
        if attr not in executed.bindings:
            raise PolicyWarrantDivergence(
                f"capability={executed.capability!r}: executed call omits "
                f"binding for constrained attribute {attr!r}"
            )
        if executed.bindings[attr] not in allowed:
            raise PolicyWarrantDivergence(
                f"capability={executed.capability!r}: binding "
                f"{attr}={executed.bindings[attr]!r} outside local grant "
                f"{sorted(allowed)}"
            )


# --- exercised trace -------------------------------------------------------
if __name__ == "__main__":
    caller_policy = Policy(constraints={"corpus": {"public"}})

    # Peer B echoed only tenant granularity; corpus was dropped in manifest.
    peer_echo = {"tenant"}

    executed = ExecutedCall(
        capability="tool:search",
        bindings={"tenant": "caller_org", "corpus": "private"},  # over-grant
    )

    try:
        negotiate_and_verify(caller_policy, peer_echo, executed)
    except PolicyWarrantDivergence as exc:
        print(f"REJECTED: {exc}")
