# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-trust-anchor-mid-federation-before-it-acts-on-a-stale-capability-warrant.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-revoked-trust-anchor-mid-federation-before-it-acts-on-a-stale-capability-warrant.warrant.json
# Markdown SHA-256:   d92c272fa7cdf4ac778229f08aa5f77b2d8693a25ca49e1f7cf98e2385e92c02
# Code AST SHA-256:   abc32eb86a85e2dd9db38b9165d7cdd3e98570e65209f3c3d53dea3978683e24
# Verified Classes:   StaleAnchorEpochError, AnchorEpochTracker
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StaleAnchorEpochError(RuntimeError):
    """Raised when a cached capability warrant was verified under an anchor
    epoch that the peer org has since superseded (revocation/rotation)."""
    pass


class AnchorEpochTracker:
    """Tracks the high-water anchor epoch per peer org via signed epoch beacons.

    The tracker is the only component allowed to advance a peer's epoch.
    Warrant verification consults it before any authorizing action.
    """

    def __init__(self):
        # peer_org_id -> highest anchor epoch observed (monotonic)
        self._high_water = {}
        # peer_org_id -> epoch of the last beacon we accepted
        self._beacon_epoch = {}

    def observe_beacon(self, peer_org_id: str, epoch: int, signature_valid: bool) -> None:
        if not signature_valid:
            # An unsigned/invalid beacon must never advance the high-water mark.
            return
        current = self._high_water.get(peer_org_id, -1)
        if epoch > current:
            self._high_water[peer_org_id] = epoch
            self._beacon_epoch[peer_org_id] = epoch

    def require_current(self, peer_org_id: str, cached_epoch: int) -> None:
        """Gate an authorizing action on anchor-epoch freshness.

        Raises if the cached warrant's epoch is behind the peer's high-water
        mark, or if no beacon has ever been observed for the peer.
        """
        if peer_org_id not in self._high_water:
            raise StaleAnchorEpochError(
                f"no anchor-epoch beacon ever observed for {peer_org_id!r}; "
                f"cannot confirm cached epoch {cached_epoch} is current"
            )
        high_water = self._high_water[peer_org_id]
        if cached_epoch < high_water:
            raise StaleAnchorEpochError(
                f"cached warrant epoch {cached_epoch} for {peer_org_id!r} is "
                f"behind peer high-water mark {high_water}; "
                f"anchor likely rotated or revoked — re-verify before acting"
            )


def authorize_action(
    tracker: AnchorEpochTracker,
    peer_org_id: str,
    cached_warrant_epoch: int,
    action_is_authority_bearing: bool,
) -> None:
    """Enforce the epoch-freshness precondition before dispatching an action.

    Only authority-bearing actions (mutating, budget-spending, or
    capability-minting) require a confirmed-current epoch. Read-only,
    idempotent actions may proceed under a bounded stale window.
    """
    if not action_is_authority_bearing:
        return  # bounded stale window permitted for read-only actions
    tracker.require_current(peer_org_id, cached_warrant_epoch)


# --- illustrative use in an orchestrator dispatch path ---

def dispatch(tracker, peer_org_id, warrant, action):
    try:
        authorize_action(
            tracker,
            peer_org_id=peer_org_id,
            cached_warrant_epoch=warrant.anchor_epoch,
            action_is_authority_bearing=action.mutates_state or action.mints_capability,
        )
    except StaleAnchorEpochError as exc:
        # Fail closed: refuse the action, surface for re-verification.
        raise StaleAnchorEpochError(
            f"refusing {action.name!r} against {peer_org_id!r}: {exc}"
        ) from exc
    return action.execute(warrant)
