# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-verify-a-federated-peer-s-capability-warrant-before-every-delegated-tool-call-rather-than-trusting-the-cache.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-verify-a-federated-peer-s-capability-warrant-before-every-delegated-tool-call-rather-than-trusting-the-cache.warrant.json
# Markdown SHA-256:   62c2bbc9d952566e4def1aa6d240b4a11245c8c44636982f37954096c713f070
# Code AST SHA-256:   66e69e5d71bb46a4ce95a7a02c4163f4c263bd3a8105ce8213753b8645573a9a
# Verified Classes:   StaleWarrantError, PeerWarrant, FederatedPrincipal
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleWarrantError(RuntimeError):
    """Raised when a delegated call is bound to an authorization epoch the peer has moved past."""


@dataclass(frozen=True)
class PeerWarrant:
    peer_id: str
    grant_epoch: int
    trust_score: float
    delegation_ceiling: dict


class FederatedPrincipal:
    def __init__(self):
        self._warrants: dict[str, PeerWarrant] = {}

    def discover(self, peer_id: str, manifest: dict, warrant: PeerWarrant) -> None:
        # Manifest is cached separately and freely; warrant is epoch-bound.
        self._warrants[peer_id] = warrant

    def delegate(self, peer_id: str, tool: str, args: dict, peer_epoch_now: int) -> dict:
        warrant = self._warrants.get(peer_id)
        if warrant is None:
            raise StaleWarrantError(f"no warrant for peer {peer_id}; discovery required")
        if peer_epoch_now != warrant.grant_epoch:
            # Authorization moved since discovery: re-discover before any decision.
            raise StaleWarrantError(
                f"peer {peer_id} epoch advanced {warrant.grant_epoch}->{peer_epoch_now}; "
                f"cached warrant is a past authorization, not a current permission"
            )
        ceiling = warrant.delegation_ceiling
        if tool == "export_redacted" and args.get("region") not in ceiling.get("region", set()):
            # Genuine scope violation against a current, correct warrant.
            raise StaleWarrantError(
                f"region {args.get('region')} outside current ceiling {ceiling.get('region')}"
            )
        return {"status": "accepted", "peer": peer_id, "epoch": peer_epoch_now}


def handle_denial(principal: FederatedPrincipal, peer_id: str, peer_epoch_now: int) -> str:
    """On PERMISSION_DENIED: never retry-then-failover on cached capability."""
    try:
        principal.delegate(peer_id, "redact_document", {"scope": "all"}, peer_epoch_now)
        return "accepted"
    except StaleWarrantError:
        # Re-discover; do NOT compare against cached manifest for failover selection.
        raise StaleWarrantError(
            f"denial on {peer_id} is potentially epoch-stale; re-discover before failover"
        )
