# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-attest-a-federated-peer-s-policy-anchor-after-a-bilateral-trust-epoch-rolls-over-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-re-attest-a-federated-peer-s-policy-anchor-after-a-bilateral-trust-epoch-rolls-over-mid-handoff.warrant.json
# Markdown SHA-256:   a892cc1223bb5e11f2ecbeaf6c96429c47a93b41b5709d0ad8aa77d95c2872ef
# Code AST SHA-256:   77261fd5e53014f2799178124f5a25806eb67e404c148e9d4a1d5e3c6d3acf4f
# Verified Classes:   StaleEpochError, PolicyNarrowedError, Warrant, Anchor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class StaleEpochError(RuntimeError):
    """Raised when a warrant's bound epoch no longer matches the peer's live anchor."""


class PolicyNarrowedError(RuntimeError):
    """Raised when re-attestation yields an anchor that does not grant the warrant's capability."""


@dataclass(frozen=True)
class Warrant:
    authority: str
    capability: str
    epoch_id: str
    anchor_fingerprint: str
    expires_at: float


@dataclass(frozen=True)
class Anchor:
    epoch_id: str
    fingerprint: str
    granted_capabilities: frozenset


def exercise_capability(
    warrant: Warrant,
    live_anchor: Anchor,
    now: float,
    is_capability_step: bool = True,
) -> None:
    """Gate a capability exercise on (authority, epoch, expiry) all being live.

    Non-capability steps (pure reasoning over materialized context) may proceed
    under a stale epoch until warrant expiry. Capability steps may not.
    """
    if now >= warrant.expires_at:
        raise StaleEpochError(
            f"warrant {warrant.authority!r} expired at {warrant.expires_at}, now {now}"
        )

    if not is_capability_step:
        return  # materialized-context drain path; epoch rollover tolerated

    if live_anchor.epoch_id != warrant.epoch_id:
        raise StaleEpochError(
            f"warrant bound to epoch {warrant.epoch_id!r} but peer anchor is "
            f"{live_anchor.epoch_id!r}; re-attest before exercising "
            f"{warrant.capability!r}"
        )

    if live_anchor.fingerprint != warrant.anchor_fingerprint:
        raise StaleEpochError(
            f"anchor fingerprint drift: warrant {warrant.anchor_fingerprint!r} "
            f"vs live {live_anchor.fingerprint!r}"
        )

    if warrant.capability not in live_anchor.granted_capabilities:
        raise PolicyNarrowedError(
            f"capability {warrant.capability!r} not granted under epoch "
            f"{live_anchor.epoch_id!r}; surface narrowing to origin instance"
        )
