# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-peer-s-capability-advertisement-that-its-own-policy-engine-would-have-rejected-and-only-discover-the-violation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-peer-s-capability-advertisement-that-its-own-policy-engine-would-have-rejected-and-only-discover-the-violation.warrant.json
# Markdown SHA-256:   1419e2d402f21e7104a438e3337819cfbe2f2d3a7a93613a409787a75c4319f4
# Code AST SHA-256:   becba662b7639b5fdff6bafbff67353713aaca042265ea9a9c53083c8712d879
# Verified Classes:   StaleTrustGrantError, TrustGrant, FederationAdmission
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Dict, Optional


class StaleTrustGrantError(RuntimeError):
    """Raised when an inbound capability invocation would be admitted under a
    trust grant that is not bound to the current policy version."""
    pass


@dataclass(frozen=True)
class TrustGrant:
    peer_id: str
    capability_id: str
    policy_version: int
    tier: str
    issued_at: float

    def key(self) -> str:
        raw = f"{self.peer_id}|{self.capability_id}|{self.policy_version}"
        return hashlib.sha256(raw.encode()).hexdigest()


class FederationAdmission:
    def __init__(self, current_policy_version: int):
        self.current_policy_version = current_policy_version
        self._grants: Dict[str, TrustGrant] = {}

    def record_grant(self, grant: TrustGrant) -> None:
        self._grants[grant.key()] = grant

    def invalidate_on_policy_roll(self, new_version: int) -> None:
        # Grants are keyed by policy_version, so a roll leaves old-version
        # grants orphaned. Purge them explicitly to avoid accidental reuse.
        self.current_policy_version = new_version
        stale = [k for k, g in self._grants.items()
                 if g.policy_version != new_version]
        for k in stale:
            del self._grants[k]

    def admit(self, peer_id: str, capability_id: str,
              required_tier: str) -> TrustGrant:
        # The invariant: lookup key includes the *current* policy version.
        probe = TrustGrant(
            peer_id=peer_id,
            capability_id=capability_id,
            policy_version=self.current_policy_version,
            tier="",
            issued_at=0.0,
        )
        grant: Optional[TrustGrant] = self._grants.get(probe.key())
        if grant is None:
            raise StaleTrustGrantError(
                f"no trust grant for peer={peer_id} cap={capability_id} "
                f"under policy_version={self.current_policy_version}; "
                f"handshake must be re-run or predicate re-evaluated"
            )
        if grant.tier != required_tier:
            raise StaleTrustGrantError(
                f"tier mismatch for peer={peer_id} cap={capability_id}: "
                f"grant={grant.tier} required={required_tier}"
            )
        return grant


def dispatch_inbound(admission: FederationAdmission, peer_id: str,
                     capability_id: str, required_tier: str) -> None:
    # Pre-invocation guard. If this raises, the tool is never invoked.
    admission.admit(peer_id, capability_id, required_tier)
    # ... invoke tool only after admission succeeds ...
