# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-capability-grant-whose-scope-digest-was-negotiated-against-a-stale-peer-policy-epoch.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-refuse-a-federated-capability-grant-whose-scope-digest-was-negotiated-against-a-stale-peer-policy-epoch.warrant.json
# Markdown SHA-256:   c41330d7d5fb3202185fe01a789002b3cd4c5948ddf15ca0b62bea8f9458aeb2
# Code AST SHA-256:   4cb8f69f53f13b28fc1b2ed5910dea40340b86baaf140a7ac05df76958089fc4
# Verified Classes:   FederatedScopeEpochMismatch, Warrant, PeerState
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass


class FederatedScopeEpochMismatch(RuntimeError):
    """Raised when a cached warrant's policy epoch cannot be reconciled
    with the peer's live policy epoch at call time."""
    pass


@dataclass(frozen=True)
class Warrant:
    scope_digest: str
    policy_epoch: int
    issuer: str
    subject: str
    expires_at: float


@dataclass(frozen=True)
class PeerState:
    current_epoch: int
    live_manifest_digest: str | None  # None if peer will not serve manifest


def digest_manifest(manifest: dict) -> str:
    canonical = repr(sorted(manifest.items())).encode()
    return "sha256:" + hashlib.sha256(canonical).hexdigest()


def authorize_call(warrant: Warrant, peer: PeerState, now: float | None = None) -> None:
    """Gate a federated call. Returns None if the call may proceed;
    raises FederatedScopeEpochMismatch if the warrant cannot be
    reconciled with the peer's live policy state."""
    now = time.time() if now is None else now

    if warrant.expires_at < now:
        raise FederatedScopeEpochMismatch(
            f"warrant from {warrant.issuer} expired at {warrant.expires_at}"
        )

    if warrant.policy_epoch > peer.current_epoch:
        raise FederatedScopeEpochMismatch(
            f"epoch inversion: warrant epoch {warrant.policy_epoch} > "
            f"peer current epoch {peer.current_epoch}; receiver's view of "
            f"peer is inconsistent (stale replica or rollback)"
        )

    if warrant.policy_epoch == peer.current_epoch:
        return  # pinned; safe

    # warrant.policy_epoch < peer.current_epoch
    if peer.live_manifest_digest is None:
        raise FederatedScopeEpochMismatch(
            f"epoch drift {warrant.policy_epoch}->{peer.current_epoch} and "
            f"peer serves no manifest; scope_digest {warrant.scope_digest} "
            f"cannot be revalidated. Refusing call rather than guessing."
        )

    if peer.live_manifest_digest != warrant.scope_digest:
        raise FederatedScopeEpochMismatch(
            f"scope_digest drift: warrant holds {warrant.scope_digest}, "
            f"peer live manifest is {peer.live_manifest_digest} at epoch "
            f"{peer.current_epoch}. Capability surface changed; re-negotiate."
        )

    # Epoch advanced but capability surface is byte-identical
    # (e.g., signing-key rotation). Safe to proceed on the cached scope.
    return


def execute_step(warrant: Warrant, peer: PeerState, payload: dict) -> dict:
    authorize_call(warrant, peer)
    # ... perform the federated call against peer at peer.current_epoch ...
    return {"status": "ok", "payload": payload}
