# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-capability-widening-when-an-mcp-a2a-gateway-re-derives-tool-schemas-across-heterogeneous-auth-scopes.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-capability-widening-when-an-mcp-a2a-gateway-re-derives-tool-schemas-across-heterogeneous-auth-scopes.warrant.json
# Markdown SHA-256:   e129239aba84a0ca3940f79e3764d56111faa936262d00c058fa52d76ac735a9
# Code AST SHA-256:   235abd1bd04b0c0bb7b1864c387c4ae4b53b3a3ed969cc92f7212187902d0298
# Verified Classes:   WarrantSubsetViolation, UngovernableBackend, Warrant, DerivedCall
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet, Optional


class WarrantSubsetViolation(RuntimeError):
    """Raised when a derived downstream call exceeds the caller's warrant."""


class UngovernableBackend(RuntimeError):
    """Raised when a backend cannot carry caller identity for rate governance."""


@dataclass(frozen=True)
class Warrant:
    subject: str
    scopes: FrozenSet[str]
    rate_class: str
    tenant: str
    parameter_domain: FrozenSet[str]

    def dominates(self, other: "Warrant") -> bool:
        return (
            self.subject == other.subject
            and other.scopes <= self.scopes
            and other.rate_class == self.rate_class
            and other.tenant == self.tenant
            and other.parameter_domain <= self.parameter_domain
        )


@dataclass
class DerivedCall:
    params: dict
    synthesized: set = field(default_factory=set)


def derive_downstream(
    caller: Warrant,
    source_schema: FrozenSet[str],
    target_schema: FrozenSet[str],
    caller_supplied: dict,
    backend_can_propagate_identity: bool,
) -> DerivedCall:
    if not backend_can_propagate_identity:
        raise UngovernableBackend(
            f"backend cannot carry subject {caller.subject!r}; "
            "rate governance would key on proxy identity"
        )

    synthesized = target_schema - source_schema
    params = dict(caller_supplied)

    for name in synthesized:
        # Never default to a liveness value; draw from warrant or reject.
        if name == "scope":
            if "*" in caller.scopes:
                params[name] = "*"
            elif len(caller.scopes) == 1:
                params[name] = next(iter(caller.scopes))
            else:
                raise WarrantSubsetViolation(
                    f"cannot synthesize 'scope' from multi-scope warrant "
                    f"{sorted(caller.scopes)} without explicit narrowing"
                )
        elif name == "tenant":
            params[name] = caller.tenant
        elif name in caller.parameter_domain:
            params[name] = name  # caller-domain-bound; flagged below
        else:
            raise WarrantSubsetViolation(
                f"target requires {name!r} not bounded by caller warrant"
            )

    derived = DerivedCall(params=params, synthesized=synthesized)

    # Subset check: every param value must be bounded by the caller's warrant.
    for name in derived.synthesized:
        if name not in caller.parameter_domain and name not in {"scope", "tenant"}:
            raise WarrantSubsetViolation(
                f"synthesized param {name!r} outside caller parameter_domain"
            )

    return derived


def emit(downstream: DerivedCall, caller: Warrant, live_card_widened: bool) -> dict:
    if live_card_widened:
        raise WarrantSubsetViolation(
            "live agent card is wider than cached card; fail-closed on tightening"
        )
    return {"params": downstream.params, "subject": caller.subject}
