# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-capability-escalation-when-two-federated-agent-meshes-negotiate-delegated-authority-across-organizational-policy-bound.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-capability-escalation-when-two-federated-agent-meshes-negotiate-delegated-authority-across-organizational-policy-bound.warrant.json
# Markdown SHA-256:   559b10cee247cbaed43c5773d1477a4c85dda2f243978df5daccdf3be4bef9fd
# Code AST SHA-256:   a2faa93ef92a97c70bcc5ee68f6e2ec65b531dc78bea0a5c1b4d4a69b0d8cad6
# Verified Classes:   FederationEscalationError, Grant, NegotiationContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class FederationEscalationError(RuntimeError):
    """Raised when a negotiated grant is not a subset of delegator authority."""


@dataclass
class Grant:
    capability: str
    scope_pattern: str
    resolved_by: str  # "delegator" or "delegate"


@dataclass
class NegotiationContext:
    delegator_vocabulary: set[str]
    delegator_authority: set[tuple[str, str]]
    delegate_synthesis_capable: bool
    grants: list[Grant] = field(default_factory=list)


def commit_negotiated_grant(ctx: NegotiationContext) -> None:
    unknown = [g for g in ctx.grants if g.capability not in ctx.delegator_vocabulary]
    if unknown:
        raise FederationEscalationError(
            f"delegate emitted capabilities outside delegator vocabulary: "
            f"{[g.capability for g in unknown]}"
        )

    foreign_scope = [g for g in ctx.grants if g.resolved_by != "delegator"]
    if foreign_scope:
        raise FederationEscalationError(
            f"scope resolved by delegate, not delegator: "
            f"{[(g.capability, g.scope_pattern) for g in foreign_scope]}"
        )

    if ctx.delegate_synthesis_capable:
        # Fast path is unsound; require explicit diff against authority set.
        outside = [
            (g.capability, g.scope_pattern)
            for g in ctx.grants
            if (g.capability, g.scope_pattern) not in ctx.delegator_authority
        ]
        if outside:
            raise FederationEscalationError(
                f"resolution-diff found grants outside delegator authority: {outside}"
            )

    # Invariant holds: commit.
    return None
