# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-a2a-v1-0-agent-card-as-a-cache-coherence-hazard-rather-than-a-discovery-artifact.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-an-a2a-v1-0-agent-card-as-a-cache-coherence-hazard-rather-than-a-discovery-artifact.warrant.json
# Markdown SHA-256:   7ad0024228594ebddc014def314566b0ac7f3ad6460df25b7a6df0a9eac361e7
# Code AST SHA-256:   acc454a17261b4c838ebd7fa44c292dfa84807163e384b4329b620099befa86a
# Verified Classes:   CardExecutorDivergence, DivergenceAwareDispatcher
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class CardExecutorDivergence(RuntimeError):
    """Raised when a peer's advertised Agent Card schema disagrees with its executor's accepted schema."""
    pass


class DivergenceAwareDispatcher:
    def __init__(self, card_cache, transport, max_renegotiations: int = 1):
        self.card_cache = card_cache
        self.transport = transport
        self.max_renegotiations = max_renegotiations

    def dispatch(self, peer_id: str, skill: str, payload: dict) -> dict:
        renegotiations = 0
        while True:
            card = self.card_cache.get(peer_id)
            if card is None:
                raise CardExecutorDivergence(
                    f"no card cached for peer {peer_id!r}; refusing blind dispatch"
                )
            if skill not in card.get("skills", {}):
                raise CardExecutorDivergence(
                    f"peer {peer_id!r} card does not advertise skill {skill!r}"
                )
            self._validate_against_card(card, skill, payload)

            response = self.transport.send(peer_id, skill, payload)
            if not self._is_schema_rejection(response):
                return response

            # Schema-shaped rejection: the card lied. Invalidate unconditionally.
            if renegotiations >= self.max_renegotiations:
                self.card_cache.quarantine(peer_id)
                raise CardExecutorDivergence(
                    f"peer {peer_id!r} card/executor persistently divergent after "
                    f"{renegotiations} renegotiation(s); quarantined"
                )
            self.card_cache.invalidate_unconditional(peer_id)  # no If-None-Match
            new_card = self.card_cache.fetch(peer_id)
            if new_card is None:
                raise CardExecutorDivergence(
                    f"peer {peer_id!r} card refetch failed during renegotiation"
                )
            payload = self._renegotiate_payload(card, new_card, skill, payload)
            renegotiations += 1

    def _validate_against_card(self, card, skill, payload):
        # Local JSON-Schema check against cached card. Advisory only.
        ...

    def _is_schema_rejection(self, response) -> bool:
        # A2A v1.0 does not standardize this; infer from JSON-RPC code + message shape.
        err = response.get("error") or {}
        return err.get("code") == -32602 and "param" in str(err.get("message", "")).lower()

    def _renegotiate_payload(self, old_card, new_card, skill, payload):
        # Map old-schema payload onto new-schema requirements; refuse if unmappable.
        ...
