# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-stale-a2a-agent-card-as-a-capability-revocation-rather-than-a-transient-fetch-failure.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-stale-a2a-agent-card-as-a-capability-revocation-rather-than-a-transient-fetch-failure.warrant.json
# Markdown SHA-256:   98b2b79eb15883b80e5bcf8282deb772629eeb5c6ec570138f881b7f9b588a64
# Code AST SHA-256:   2901245a53a0071e0d4cbe2bf7a108985d18b31a3c292b7dc357954d295ce8e0
# Verified Classes:   CapabilityRevocationError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CapabilityRevocationError(RuntimeError):
    """Raised when a remote A2A agent's card no longer advertises a skill
    or securityScheme that the client negotiated against."""
    def __init__(self, skill_id: str, negotiated_version: str, current_version: str):
        self.skill_id = skill_id
        self.negotiated_version = negotiated_version
        self.current_version = current_version
        super().__init__(
            f"skill {skill_id!r} revoked: negotiated card {negotiated_version}, "
            f"server now serves {current_version}"
        )


def classify_a2a_error(status: int, body: dict, negotiated_card: dict) -> str:
    """Return one of: RETRY, REVOKE, REFETCH_THEN_DECIDE."""
    if status >= 500 or status in (408, 429):
        return "RETRY"
    if status == 404 and "skillId" in body:
        # Semantic fault: skill route gone. Must re-fetch before deciding.
        return "REFETCH_THEN_DECIDE"
    if status == 401 or status == 403:
        # Could be rotated scheme OR wrong key. Ambiguous until card diff.
        return "REFETCH_THEN_DECIDE"
    if status == 422:
        return "REFETCH_THEN_DECIDE"
    return "REFETCH_THEN_DECIDE"


def dispatch_with_revocation_check(
    skill_id: str,
    payload: dict,
    negotiated_card: dict,
    fetch_card,
    call_remote,
) -> dict:
    try:
        return call_remote(skill_id, payload)
    except RemoteHTTPError as e:
        decision = classify_a2a_error(e.status, e.body, negotiated_card)
        if decision == "RETRY":
            return call_remote(skill_id, payload)  # caller's retry policy applies
        # REFETCH_THEN_DECIDE: compare fresh card against negotiated witness
        fresh = fetch_card()
        negotiated_skills = {s["id"] for s in negotiated_card.get("skills", [])}
        fresh_skills = {s["id"] for s in fresh.get("skills", [])}
        if skill_id in negotiated_skills and skill_id not in fresh_skills:
            raise CapabilityRevocationError(
                skill_id=skill_id,
                negotiated_version=negotiated_card.get("version", "unknown"),
                current_version=fresh.get("version", "unknown"),
            )
        if negotiated_card.get("securitySchemes") != fresh.get("securitySchemes"):
            raise CapabilityRevocationError(
                skill_id=skill_id,
                negotiated_version=negotiated_card.get("version", "unknown"),
                current_version=fresh.get("version", "unknown"),
            )
        # Card unchanged on the relevant axes: the fault was genuinely transient.
        return call_remote(skill_id, payload)
