# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-federated-capability-grant-it-cannot-re-attest-at-execution-time.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-federated-capability-grant-it-cannot-re-attest-at-execution-time.warrant.json
# Markdown SHA-256:   c0b40afa55b46d981ac1446dec3b58d801d2f17760b67d56b9cab88b73637f81
# Code AST SHA-256:   dba6e8f5aef8288d8d458a131a934af9be0e52da63a1e5c145a4ca8ba7181c2a
# Verified Classes:   StaleAttestationError, CapabilityGrant, PolicySnapshot, FederatedGrantee
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass
from typing import Callable, Optional


class StaleAttestationError(RuntimeError):
    """Raised when a federated grant is executed against an attestation that
    no longer reflects the grantee's live state at execution time."""


@dataclass(frozen=True)
class CapabilityGrant:
    grant_id: str
    tool: str
    policy_id: str
    policy_version_at_issue: int
    attestation_inputs_hash: str  # hash of mutable fields P ranged over at issue
    deferrable: bool
    staleness_budget_s: int
    signature_valid: bool


@dataclass(frozen=True)
class PolicySnapshot:
    policy_id: str
    version: int
    resolved_at: float
    inputs_hash: str
    evaluate: Callable[[], bool]  # re-evaluates P over *current* grantee state


class FederatedGrantee:
    def __init__(self, authority: Callable[[str], Optional[PolicySnapshot]]):
        self._authority = authority

    def dispatch(self, grant: CapabilityGrant, now: Optional[float] = None) -> str:
        now = time.time() if now is None else now

        if not grant.signature_valid:
            raise StaleAttestationError(f"grant {grant.grant_id}: bad signature")

        snap = self._authority(grant.policy_id)

        # Authority unreachable: only deferrable capabilities may proceed,
        # and only if a cached snapshot is within the grant-signed budget.
        if snap is None:
            if not grant.deferrable:
                raise StaleAttestationError(
                    f"grant {grant.grant_id}: authority unreachable for "
                    f"non-deferrable capability {grant.tool}; refusing"
                )
            snap = self._cached(grant.policy_id)
            if snap is None or (now - snap.resolved_at) > grant.staleness_budget_s:
                raise StaleAttestationError(
                    f"grant {grant.grant_id}: stale cache beyond "
                    f"{grant.staleness_budget_s}s budget"
                )

        # Version monotonicity: a resolved version older than the one the
        # grant was issued against means we are reading a stale replica.
        if snap.version < grant.policy_version_at_issue:
            raise StaleAttestationError(
                f"grant {grant.grant_id}: resolved policy v{snap.version} < "
                f"issued v{grant.policy_version_at_issue}; stale replica"
            )

        # Re-bind attestation to execution time by re-evaluating P now.
        if not snap.evaluate():
            raise StaleAttestationError(
                f"grant {grant.grant_id}: predicate {grant.policy_id} "
                f"v{snap.version} false at execution time"
            )

        # The inputs hash must match the live state, not the issuance snapshot.
        live_hash = self._hash_live_inputs()
        if live_hash != snap.inputs_hash:
            raise StaleAttestationError(
                f"grant {grant.grant_id}: live inputs {live_hash[:8]} do not "
                f"match policy-evaluated inputs {snap.inputs_hash[:8]}"
            )

        return self._invoke(grant.tool)

    def _cached(self, policy_id: str) -> Optional[PolicySnapshot]:
        return self._cache.get(policy_id)

    def _hash_live_inputs(self) -> str:
        return hashlib.sha256(self._live_state_bytes()).hexdigest()

    def _live_state_bytes(self) -> bytes:
        return b""  # wired to the grantee's current agent-card fields

    def _invoke(self, tool: str) -> str:
        return f"invoked {tool}"
