# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-an-a2a-task-against-a-stale-remote-agent-card-whose-skills-schema-has-silently-widened.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-an-a2a-task-against-a-stale-remote-agent-card-whose-skills-schema-has-silently-widened.warrant.json
# Markdown SHA-256:   a5a4cbf1f484f26d98cdeb563e6e50aee54af2755dc6435ac7f96d96ccb943d1
# Code AST SHA-256:   b7228b38a2157c10e115f37757119894772469a9e5d1871a40b7f72d6626293b
# Verified Classes:   CapabilityDesyncError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CapabilityDesyncError(RuntimeError):
    """Raised when a remote Agent Card advertises a capability the remote handler rejects."""
    pass


def dispatch_with_epoch_guard(client, remote_card, task, dispatched_kind):
    cached_modes = remote_card["skills"][0]["inputModes"]
    if dispatched_kind not in cached_modes:
        raise CapabilityDesyncError(
            f"client bug: dispatched kind {dispatched_kind!r} not in cached inputModes {cached_modes!r}"
        )

    response = client.send_task(task, card_version=remote_card["version"])

    if response.get("error", {}).get("code") == -32602:
        fresh = client.fetch_agent_card(remote_card["url"])
        if fresh["version"] == remote_card["version"]:
            raise CapabilityDesyncError(
                f"remote {remote_card['url']} rejects kind {dispatched_kind!r} "
                f"despite Card version {fresh['version']} advertising it; "
                f"Card/handler desync — halt retries, do not evict peer"
            )
        if dispatched_kind not in fresh["skills"][0]["inputModes"]:
            raise CapabilityDesyncError(
                f"capability withdrawn at Card version {fresh['version']}; "
                f"task {task['id']} cannot proceed, mark failed without retry"
            )
        return client.send_task(task, card_version=fresh["version"])

    return response
