# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-capability-warrant-decay-when-an-agentic-gateway-translates-mcp-tool-calls-into-a2a-tasks-and-legacy-rpc-envelopes.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-capability-warrant-decay-when-an-agentic-gateway-translates-mcp-tool-calls-into-a2a-tasks-and-legacy-rpc-envelopes.warrant.json
# Markdown SHA-256:   0a12dd02d59b8c400e98e03aa3adf58975af5056bc0f386426d1d3d1a41c35e6
# Code AST SHA-256:   ad42874406de1cd9aace32ac179bc0b08322f49150dc2b44323184f49e29389b
# Verified Classes:   WarrantDecayError, CapabilityWarrant, TranslationHop
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class WarrantDecayError(RuntimeError):
    """Raised when a translation hop cannot carry the caller's capability warrant
    and the gateway would otherwise substitute its own identity (widening scope)."""


@dataclass(frozen=True)
class CapabilityWarrant:
    subject: str
    scopes: FrozenSet[str]
    origin_session: str

    def is_subset_of(self, other: "CapabilityWarrant") -> bool:
        return self.scopes <= other.scopes


@dataclass
class TranslationHop:
    protocol: str                      # "mcp" | "a2a" | "thrift" | "grpc"
    carries_warrant: bool              # protocol has a signed capability field
    gateway_can_delegate: bool         # RFC 8693 token exchange available
    gateway_service_scopes: FrozenSet[str] = field(default_factory=frozenset)


def translate(warrant: CapabilityWarrant, hop: TranslationHop) -> CapabilityWarrant:
    """Return the warrant the downstream hop will actually enforce.

    Enforces the monotone-non-expansion invariant: the returned warrant must be
    a subset of the originating warrant. Fails closed when the hop cannot carry
    or delegate the warrant and would require substituting gateway identity.
    """
    if hop.carries_warrant:
        # Warrant crosses the boundary intact; receiver enforces it.
        return warrant
    if hop.gateway_can_delegate:
        # Delegated identity narrows to the caller's scopes.
        return CapabilityWarrant(
            subject=warrant.subject,
            scopes=warrant.scopes,
            origin_session=warrant.origin_session,
        )
    # Neither carry nor delegate: substituting gateway identity would widen scope.
    effective = CapabilityWarrant(
        subject=f"gateway:{hop.protocol}",
        scopes=hop.gateway_service_scopes,
        origin_session=warrant.origin_session,
    )
    if not effective.is_subset_of(warrant):
        raise WarrantDecayError(
            f"hop '{hop.protocol}' cannot carry or delegate warrant for "
            f"session={warrant.origin_session!r}; gateway scopes "
            f"{sorted(effective.scopes)} not subset of caller scopes "
            f"{sorted(warrant.scopes)}. Refusing to substitute identity."
        )
    return effective


def route_chain(warrant: CapabilityWarrant, hops: list[TranslationHop]) -> list[CapabilityWarrant]:
    chain = [warrant]
    for hop in hops:
        chain.append(translate(chain[-1], hop))
    return chain


if __name__ == "__main__":
    caller = CapabilityWarrant(
        subject="mcp-client-7",
        scopes=frozenset({"files:read", "files:write:/tmp/scratch", "net:egress:api.internal"}),
        origin_session="sess-7f3a",
    )
    hops = [
        TranslationHop("a2a", carries_warrant=True, gateway_can_delegate=False),
        # Legacy Thrift hop: no warrant field, gateway holds broad service creds.
        TranslationHop(
            "thrift",
            carries_warrant=False,
            gateway_can_delegate=False,
            gateway_service_scopes=frozenset({"files:read", "files:write:*"}),
        ),
    ]
    try:
        route_chain(caller, hops)
    except WarrantDecayError as e:
        print(f"FAIL-CLOSED: {e}")
