# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-grant-more-authority-than-the-federation-policy-it-negotiated-under.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-grant-more-authority-than-the-federation-policy-it-negotiated-under.warrant.json
# Markdown SHA-256:   76708661c7dc33c8568f53aa23bfe763d88a5b4cb9f78bbd1c7b6270d2f1089f
# Code AST SHA-256:   eb85352de9737f67be1e6835034d02132ba40078f35d6465ead4828f3aa9cd16
# Verified Classes:   EnvelopeWideningError, Peer, Peering
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from typing import FrozenSet


class EnvelopeWideningError(RuntimeError):
    """Raised when a negotiated peering envelope exceeds the receiver's attested grant."""


@dataclass(frozen=True)
class Peer:
    org: str
    advertised: FrozenSet[str]          # what the registry says it can do
    granted_for_peer_class: FrozenSet[str]  # what the policy authority allows for this peer class


@dataclass
class Peering:
    local: Peer
    remote: Peer
    envelope: FrozenSet[str] = field(default_factory=frozenset)

    def negotiate(self) -> FrozenSet[str]:
        # Correct: intersect GRANTED sets, not advertised sets.
        granted_intersection = self.local.granted_for_peer_class & self.remote.granted_for_peer_class
        advertised_intersection = self.local.advertised & self.remote.advertised
        if not granted_intersection <= advertised_intersection:
            # Advertisement must be a lower bound on grants; if it isn't, the
            # registry is lying and the envelope cannot be trusted.
            raise EnvelopeWideningError(
                f"advertised set {advertised_intersection} does not cover granted "
                f"set {granted_intersection} for {self.local.org}<->{self.remote.org}"
            )
        self.envelope = granted_intersection
        return self.envelope

    def accept_warrant(self, scope: str, payload: bytes) -> bool:
        # Revalidate at use time against the live grant table, BEFORE parsing payload.
        if scope not in self.local.granted_for_peer_class:
            raise EnvelopeWideningError(
                f"warrant scope {scope!r} not in live grant for peer class "
                f"{self.remote.org}; envelope was {sorted(self.envelope)}"
            )
        if scope not in self.envelope:
            raise EnvelopeWideningError(
                f"warrant scope {scope!r} outside negotiated envelope {sorted(self.envelope)}"
            )
        # Only now is it safe to deserialize.
        return self._dispatch(scope, payload)

    def _dispatch(self, scope: str, payload: bytes) -> bool:
        return True


def run_peering(local: Peer, remote: Peer, warrant_scope: str, payload: bytes) -> bool:
    p = Peering(local, remote)
    p.negotiate()
    return p.accept_warrant(warrant_scope, payload)


# Reproduction of the observed failure: A advertises sandbox but does not grant it.
a = Peer(
    org="org-a",
    advertised=frozenset({"read:dataset", "run:code_sandbox", "write:artifact", "delegate:subagent"}),
    granted_for_peer_class=frozenset({"read:dataset"}),
)
b = Peer(
    org="org-b",
    advertised=frozenset({"read:dataset", "run:code_sandbox", "write:artifact"}),
    granted_for_peer_class=frozenset({"read:dataset", "run:code_sandbox", "write:artifact"}),
)

try:
    run_peering(a, b, "run:code_sandbox", b"print('cross-org payload')")
except EnvelopeWideningError as e:
    # Expected: the widening is caught at negotiation or acceptance, not at dispatch.
    print(f"blocked before dispatch: {e}")
