# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-grant-it-cannot-translate-policy-translation-residue-and-the-trust-broker-attestation-hole.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-grant-it-cannot-translate-policy-translation-residue-and-the-trust-broker-attestation-hole.warrant.json
# Markdown SHA-256:   e77b5c8e7e38868b2c227af3ac29a1ceb136179987d27b7c8f57717e04ae4f84
# Code AST SHA-256:   6f1cefcf51abfa24a2ce2490b8a4b216444f724acb8b3cbeaa2009b5ee5a3bb8
# Verified Classes:   UntranslatableGrantError, FederatedGrant, GrantAcceptanceGate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class UntranslatableGrantError(RuntimeError):
    """Raised when a federated grant carries residue the consumer cannot enforce."""


@dataclass
class FederatedGrant:
    capability: str
    granted: bool
    translated_constraints: dict
    residue: list[str] = field(default_factory=list)
    broker_attestation: str = ""


class GrantAcceptanceGate:
    """Consumer-side gate: a signed grant is necessary but not sufficient."""

    def __init__(self, enforcement_hooks: dict[str, Callable]):
        # Maps a residue token to a consumer-side enforcement hook.
        self.hooks = enforcement_hooks

    def accept(self, grant: FederatedGrant) -> dict:
        if not grant.granted:
            raise UntranslatableGrantError(
                f"grant for {grant.capability!r} was denied by broker"
            )

        unresolved = [tok for tok in grant.residue if tok not in self.hooks]
        if unresolved:
            # Attestation validity does NOT imply translation completeness.
            raise UntranslatableGrantError(
                f"grant for {grant.capability!r} has untranslatable residue "
                f"{unresolved}; broker_attestation={grant.broker_attestation!r} "
                f"signs the translation, not the policy. Refusing execution."
            )

        # All residue resolved: attach hooks to the execution context.
        active_hooks = {tok: self.hooks[tok] for tok in grant.residue}
        return {
            "capability": grant.capability,
            "constraints": grant.translated_constraints,
            "enforcement_hooks": active_hooks,
        }


def execute_federated_call(grant: FederatedGrant, gate: GrantAcceptanceGate,
                           payload: dict) -> dict:
    ctx = gate.accept(grant)  # fail-closed before any tool invocation
    for hook in ctx["enforcement_hooks"].values():
        hook(payload)  # e.g. classification ceiling, persistence ban
    return {"status": "executed", "capability": ctx["capability"], "payload": payload}
