# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-a-federated-capability-warrant-before-tool-invocation-and-why-post-hoc-audit-cannot-substitute.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-a-federated-capability-warrant-before-tool-invocation-and-why-post-hoc-audit-cannot-substitute.warrant.json
# Markdown SHA-256:   c43dffb051304e1f89da71427d40e3ca859b1b723a723f11101fed3fc2d5b6ba
# Code AST SHA-256:   acdde408e34138d76271ed25fe752b9982d63c85906251eea107ffca90110cab
# Verified Classes:   WarrantScopeViolation, EnforcementPointMisconfigured, ToolCall, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Callable


class WarrantScopeViolation(RuntimeError):
    """Raised when a synthesized tool call falls outside the inbound warrant's scope."""


class EnforcementPointMisconfigured(RuntimeError):
    """Raised when the registry, not the warrant, is the effective authority."""


@dataclass(frozen=True)
class ToolCall:
    tool: str
    args: dict


@dataclass(frozen=True)
class Warrant:
    warrant_id: str
    issuer: str
    scope: frozenset  # set of (tool, arg_predicate) pairs
    expires_at: int

    def permits(self, call: ToolCall, now: int) -> bool:
        if now >= self.expires_at:
            return False
        for tool, predicate in self.scope:
            if tool == call.tool and predicate(call.args):
                return True
        return False


def dispatch_federated_tool(
    call: ToolCall,
    warrant: Warrant,
    registry_allows: Callable[[ToolCall], bool],
    handler: Callable[[ToolCall], None],
    now: int,
) -> None:
    # Registry may narrow, never widen. If the registry would admit a call the
    # warrant does not, that is a misconfiguration, not an authorization.
    registry_ok = registry_allows(call)
    warrant_ok = warrant.permits(call, now)

    if registry_ok and not warrant_ok:
        # The dangerous case: registry would have let it through. Deny on
        # warrant scope, and surface the config drift explicitly.
        raise WarrantScopeViolation(
            f"call {call.tool}{call.args} outside warrant {warrant.warrant_id} "
            f"scope; registry would have permitted it — registry is not an "
            f"authorization source for federated callers"
        )

    if not warrant_ok:
        raise WarrantScopeViolation(
            f"call {call.tool}{call.args} outside warrant {warrant.warrant_id}"
        )

    # Gate passed: side effect may commit. This is the only path to handler().
    handler(call)


def bind_federated_agent(
    agent_registry: Callable[[ToolCall], bool],
    warrant: Warrant,
) -> Callable[[ToolCall], bool]:
    # Refuse to bind if the registry admits anything the warrant cannot, because
    # that guarantees a gate denial later that the agent cannot recover from
    # cleanly — better to fail at bind time than mid-task.
    probe_scope = warrant.scope
    if not probe_scope:
        raise EnforcementPointMisconfigured(
            f"warrant {warrant.warrant_id} has empty scope; cannot bind"
        )
    return agent_registry
