# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-a2a-capability-card-drifts-from-the-broker-s-cached-warrant-during-cross-org-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-a2a-capability-card-drifts-from-the-broker-s-cached-warrant-during-cross-org-federation.warrant.json
# Markdown SHA-256:   05f539685fc0ee85c42c63f85d20dbe05dc6c148335cb91377530048614e133b
# Code AST SHA-256:   331eefbfe35d9df348fd0e9ba9f703057c94493582014f24b8750c87ae5daf13
# Verified Classes:   StaleWarrantEpoch
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class StaleWarrantEpoch(RuntimeError):
    """Raised when a broker dispatches against a cached warrant epoch that the
    remote peer has superseded. Distinct from insufficient-authority: the caller
    is authorized, but its cached belief about the peer is outdated."""
    def __init__(self, peer_id: str, cited_epoch: int, current_epoch: int):
        self.peer_id = peer_id
        self.cited_epoch = cited_epoch
        self.current_epoch = current_epoch
        super().__init__(
            f"peer {peer_id}: warrant epoch {cited_epoch} superseded by {current_epoch}"
        )


def dispatch_delegation(broker, peer_id: str, action: str) -> dict:
    entry = broker.cache.get(peer_id)
    if entry is None:
        entry = broker.refresh_card(peer_id)  # cold fill

    envelope = broker.sign_envelope(
        peer_id=peer_id,
        action=action,
        warrant_epoch=entry.warrant_epoch,
    )

    response = broker.transport.send(peer_id, envelope)

    if response.status == "ok":
        return response.body

    if response.error_code == "EpochStale":
        # The remote told us our belief is outdated. Invalidate, re-fetch,
        # re-sign at the new epoch, retry exactly once.
        current = int(response.error_detail["current_epoch"])
        if current <= entry.warrant_epoch:
            raise StaleWarrantEpoch(peer_id, entry.warrant_epoch, current)
        broker.cache.invalidate(peer_id)
        entry = broker.refresh_card(peer_id)
        if entry.warrant_epoch != current:
            raise StaleWarrantEpoch(peer_id, entry.warrant_epoch, current)
        retry_env = broker.sign_envelope(
            peer_id=peer_id, action=action, warrant_epoch=entry.warrant_epoch
        )
        retry = broker.transport.send(peer_id, retry_env)
        if retry.status != "ok":
            raise StaleWarrantEpoch(peer_id, entry.warrant_epoch, current)
        return retry.body

    if response.status == "forbidden":
        # Unexplained 403: our cached belief is untrustworthy. Invalidate and
        # do NOT retry with the same epoch.
        broker.cache.invalidate(peer_id)
        raise StaleWarrantEpoch(
            peer_id, entry.warrant_epoch, entry.warrant_epoch  # unknown current
        )

    raise RuntimeError(f"unhandled peer response: {response.status}")
