# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-warrant-scope-collapse-when-an-a2a-federation-bridge-re-signs-an-mcp-tool-capability.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-warrant-scope-collapse-when-an-a2a-federation-bridge-re-signs-an-mcp-tool-capability.warrant.json
# Markdown SHA-256:   4cab8f5b7a7f9292043dcf44a9cb2a7b0c5f930f1092c7544951525e89b9fd66
# Code AST SHA-256:   b578954e9509176f22964d34dd7d99add279b619585ec73a7581b53dcf89ce7b
# Verified Classes:   WarrantScopeCollapse, ResourceURI, A2AWarrant, ToolEnvelope, MCPCallContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass
from typing import FrozenSet


class WarrantScopeCollapse(RuntimeError):
    """Raised when a protocol bridge would widen authority during MCP<->A2A translation."""


@dataclass(frozen=True)
class ResourceURI:
    value: str


@dataclass(frozen=True)
class A2AWarrant:
    issuer: str
    subject: str
    resources: FrozenSet[ResourceURI]
    delegation_depth: int
    expires_in_s: int


@dataclass(frozen=True)
class ToolEnvelope:
    name: str
    side_effects: FrozenSet[str]  # e.g. {"read", "write"}


@dataclass(frozen=True)
class MCPCallContext:
    # Non-optional by construction: the bridge cannot build one without these.
    issuer: str
    subject: str
    resources: FrozenSet[ResourceURI]
    delegation_depth: int


def bridge_warrant(
    inbound: A2AWarrant,
    tool: ToolEnvelope,
    bridge_policy: FrozenSet[ResourceURI],
    bridge_issuer: str,
) -> MCPCallContext:
    """Translate an A2A warrant into an MCP call context, reducing authority only.

    Invariants enforced:
      1. bridge_policy must be a subset of inbound.resources (bridge may not
         sign authority it was not delegated).
      2. The resulting resource set is inbound.resources ∩ bridge_policy.
      3. The tool's declared side-effect envelope must be satisfiable by the
         narrowed resource set; otherwise the bridge rejects the tool.
      4. delegation_depth is decremented, never reset.
    """
    if not bridge_policy.issubset(inbound.resources):
        raise WarrantScopeCollapse(
            f"bridge policy {sorted(r.value for r in bridge_policy)} "
            f"exceeds inbound warrant {sorted(r.value for r in inbound.resources)} "
            f"from {inbound.issuer}"
        )

    narrowed = inbound.resources & bridge_policy

    if not narrowed:
        raise WarrantScopeCollapse(
            f"empty intersection for tool {tool.name!r}; refusing to sign"
        )

    # A tool that internally performs read+write cannot honor a read-only grant.
    required = tool.side_effects
    granted = {r.value.rsplit(":", 1)[-1] for r in narrowed}
    if not required.issubset(granted):
        raise WarrantScopeCollapse(
            f"tool {tool.name!r} requires {sorted(required)} but warrant grants "
            f"{sorted(granted)}; bridge must not silently narrow the tool"
        )

    if inbound.delegation_depth <= 0:
        raise WarrantScopeCollapse(
            f"delegation depth exhausted for subject {inbound.subject}"
        )

    return MCPCallContext(
        issuer=bridge_issuer,
        subject=inbound.subject,
        resources=narrowed,
        delegation_depth=inbound.delegation_depth - 1,
    )


def dispatch(inbound: A2AWarrant, tool: ToolEnvelope, bridge_policy, bridge_issuer) -> str:
    ctx = bridge_warrant(inbound, tool, bridge_policy, bridge_issuer)
    return f"dispatched {tool.name} for {ctx.subject} under {sorted(r.value for r in ctx.resources)}"
