# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-foreign-org-policy-translation-from-silently-widening-delegated-capability-scope-in-federated-agent-handoffs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-foreign-org-policy-translation-from-silently-widening-delegated-capability-scope-in-federated-agent-handoffs.warrant.json
# Markdown SHA-256:   1e2837a155f158f58149ee9f551d26cb34b3af93da6866c3cad576381f278a48
# Code AST SHA-256:   d801b9a6b4d7e48d7befe9cc90397270f7922b5c721c8afb5d8f9bf099d197e7
# Verified Classes:   UnenforceableCaveat, Caveat, Warrant, RemotePolicy
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class UnenforceableCaveat(RuntimeError):
    """Raised when an inbound warrant caveat has no enforcing predicate at the remote PDP."""
    pass


@dataclass(frozen=True)
class Caveat:
    key: str
    value: str


@dataclass
class Warrant:
    subject: str
    capability: str
    caveats: list[Caveat] = field(default_factory=list)


@dataclass
class RemotePolicy:
    # Maps a local capability to the set of qualifier keys its PDP can actually evaluate.
    enforceable: dict[str, set[str]]


def translate_and_gate(
    warrant: Warrant,
    remote: RemotePolicy,
    translator: Callable[[Warrant], dict],
) -> dict:
    """
    Translate a foreign warrant into the remote dialect, but fail closed if any
    caveat in the warrant cannot be enforced by the remote PDP.

    Invariant: for every caveat c in warrant.caveats, the remote policy must have
    an enforceable predicate on c.key for the translated capability. Otherwise the
    translation would silently drop the restriction and widen scope.
    """
    translated = translator(warrant)  # lossy rendering; may drop qualifiers
    cap = translated.get("capability", warrant.capability)
    enforceable_keys = remote.enforceable.get(cap, set())

    for caveat in warrant.caveats:
        if caveat.key not in enforceable_keys:
            # Do NOT proceed. The remote cannot enforce this restriction, so the
            # translated policy would be a strict superset of the requested scope.
            raise UnenforceableCaveat(
                f"caveat {caveat.key}={caveat.value!r} on capability {cap!r} "
                f"has no enforcing predicate at remote PDP; refusing handoff "
                f"to prevent scope widening (subject={warrant.subject})"
            )

    return translated


# --- demonstration ---
remote_b = RemotePolicy(enforceable={"read:customer_records": {"since", "limit"}})
w = Warrant(
    subject="orgA/planner",
    capability="read:customer_records",
    caveats=[Caveat("region", "EU"), Caveat("since", "-90d")],
)

def naive_translator(warrant: Warrant) -> dict:
    # Standard best-effort mapping: drop qualifiers the remote dialect lacks.
    return {"capability": warrant.capability, "qualifiers": {"since": "-90d"}}

try:
    translate_and_gate(w, remote_b, naive_translator)
except UnenforceableCaveat as e:
    print(f"handoff blocked: {e}")
    # orchestrator falls back to data-enumeration: pass EU record IDs explicitly,
    # so the region restriction travels in the payload, not the policy.
