# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-signature-after-an-a2a-v1-0-capability-renegotiation-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-signature-after-an-a2a-v1-0-capability-renegotiation-mid-task.warrant.json
# Markdown SHA-256:   ac340f3046640ec68a61bfef5cbadc2b47e0409be55faa2f2ebfecce8dfd2616
# Code AST SHA-256:   db813d12d58ab43cd82439d4f3e1e4a27e78044005bdbde289beb7f93efb8316
# Verified Classes:   StaleAgentCardError, CapabilityWithdrawnError, AgentCard, SignedResponse
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class StaleAgentCardError(RuntimeError):
    """Raised when a verified response proves the cached Agent Card is stale."""


class CapabilityWithdrawnError(RuntimeError):
    """Raised when a renegotiated card no longer offers a load-bearing capability."""


@dataclass(frozen=True)
class AgentCard:
    version: int
    kid: str
    capabilities: frozenset
    card_hash: str


@dataclass(frozen=True)
class SignedResponse:
    kid: str
    card_version: int
    method: str
    error_code: int | None
    payload: dict


def _verify(response: SignedResponse, jwks: dict) -> bool:
    # Stand-in for real JWS verification against the peer's JWKS.
    return response.kid in jwks


def _fetch_card(peer: str) -> AgentCard:
    # Stand-in for agent/getAuthenticatedExtendedCard.
    raw = {"version": 2, "kid": "key-2025",
           "capabilities": ["messaging"], "skills": []}
    h = hashlib.sha256(json.dumps(raw, sort_keys=True).encode()).hexdigest()
    return AgentCard(version=raw["version"], kid=raw["kid"],
                     capabilities=frozenset(raw["capabilities"]), card_hash=h)


def handle_response(peer: str, cached: AgentCard, jwks: dict,
                    response: SignedResponse, required_caps: frozenset) -> AgentCard:
    if not _verify(response, jwks):
        # Only here is it a genuine security fault.
        raise StaleAgentCardError(
            f"signature verification failed for kid={response.kid}; "
            f"treat as untrusted, do not retry"
        )

    capability_asserted = response.method in cached.capabilities
    version_advanced = response.card_version > cached.version
    method_missing = response.error_code == -32601

    if version_advanced or (method_missing and capability_asserted):
        # Signed response proves the cached card is stale: renegotiate.
        fresh = _fetch_card(peer)
        if fresh.version <= cached.version:
            raise StaleAgentCardError(
                f"peer {peer} advertised version {fresh.version} but response "
                f"claims {response.card_version}; version binding is broken"
            )
        lost = required_caps - fresh.capabilities
        if lost:
            raise CapabilityWithdrawnError(
                f"peer {peer} withdrew {sorted(lost)} under card v{fresh.version}; "
                f"re-plan task, do not retry against stale card"
            )
        return fresh

    return cached
