# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-capability-against-a-federated-agent-card-registry-that-has-silently-drifted-from-its-home-domain-s-authorita.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-capability-against-a-federated-agent-card-registry-that-has-silently-drifted-from-its-home-domain-s-authorita.warrant.json
# Markdown SHA-256:   870931a8a7fa96cc437b3940cb5d09b0d5872c18cba3c7001b314dae66ff3d8c
# Code AST SHA-256:   60f7dc5096a118e8249636e34adfe4d15e3e4a9ad5f05ff0649c37340c0d6092
# Verified Classes:   StaleCapabilityEpochError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class StaleCapabilityEpochError(RuntimeError):
    """Raised when a negotiated capability is exercised under an epoch the peer no longer honors."""
    pass


def dispatch_under_negotiated_epoch(peer, negotiated_epoch, payload, broker):
    # Resolve the peer's current capability epoch through the broker.
    current = broker.resolve_card(peer.id)

    # Invariant: a negotiated capability is valid only for the epoch it was negotiated under.
    if current.capability_epoch != negotiated_epoch:
        raise StaleCapabilityEpochError(
            f"peer {peer.id} advanced capability_epoch "
            f"{negotiated_epoch} -> {current.capability_epoch}; "
            f"renegotiation required before dispatch"
        )

    response = peer.invoke(payload)

    # Capability-shaped errors are permanent retractions, not transport failures.
    if response.kind in {"method_not_found", "unsupported_schema", "capability_retracted"}:
        broker.invalidate(peer.id)
        raise StaleCapabilityEpochError(
            f"peer {peer.id} rejected capability under epoch {negotiated_epoch}: "
            f"{response.kind} — renegotiate, do not retry"
        )

    return response
