# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-delegated-a2a-task-under-a-stale-agent-card-whose-declared-skill-contract-no-longer-matches-the-responder-s-li.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-delegated-a2a-task-under-a-stale-agent-card-whose-declared-skill-contract-no-longer-matches-the-responder-s-li.warrant.json
# Markdown SHA-256:   ece7830dabb4c5667a276ab5e066fd12dc877a9f24f7b6417bb8e018e93352f5
# Code AST SHA-256:   ac3c61644307caa30f59d609a1c9668fa79e6dae7086d5862c6dd55494b59b38
# Verified Classes:   StaleAgentCardError, NonIdempotentResponderError, CardSnapshot, TaskRecord
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Optional


class StaleAgentCardError(RuntimeError):
    """Raised when a delegated task's failure cannot be attributed to a stable card."""


class NonIdempotentResponderError(RuntimeError):
    """Raised when a retry would duplicate side effects on a non-idempotent responder."""


@dataclass
class CardSnapshot:
    card_bytes: bytes
    card_hash: str
    skill_id: str
    advertised_states: frozenset
    idempotent_on_duplicate_id: bool


@dataclass
class TaskRecord:
    task_id: str
    session_id: str
    card_hash: str
    skill_id: str
    terminal_state: Optional[str] = None
    failure_reason: Optional[str] = None


def resolve_card(raw_card: bytes, skill_id: str) -> CardSnapshot:
    card = json.loads(raw_card)
    skill = next((s for s in card.get("skills", []) if s.get("id") == skill_id), None)
    if skill is None:
        raise StaleAgentCardError(f"skill {skill_id!r} not present in card")
    ext = next(
        (e for e in skill.get("extensions", []) if e.get("uri") == "urn:a2a:lifecycle:v1"),
        None,
    )
    states = frozenset(ext["states"]) if ext else frozenset({"working", "completed", "failed"})
    idem = bool(ext.get("idempotentOnDuplicateId", False)) if ext else False
    return CardSnapshot(
        card_bytes=raw_card,
        card_hash=hashlib.sha256(raw_card).hexdigest(),
        skill_id=skill_id,
        advertised_states=states,
        idempotent_on_duplicate_id=idem,
    )


def classify_failure(
    record: TaskRecord,
    snapshot: CardSnapshot,
    live_card_bytes: bytes,
    tasks_get_result: Optional[dict],
) -> str:
    """Return 'negotiation_drift', 'responder_fault', or 'safe_retry'."""
    live_hash = hashlib.sha256(live_card_bytes).hexdigest()
    if live_hash != record.card_hash:
        return "negotiation_drift"
    if record.failure_reason is None:
        raise StaleAgentCardError(
            f"task {record.task_id} reached failure with no reason; cannot attribute"
        )
    if not snapshot.idempotent_on_duplicate_id:
        raise NonIdempotentResponderError(
            f"responder for skill {snapshot.skill_id} does not declare idempotency; "
            f"retry of {record.task_id} would duplicate side effects"
        )
    if tasks_get_result is None or tasks_get_result.get("id") != record.task_id:
        raise NonIdempotentResponderError(
            f"tasks/get for {record.task_id} did not return the same terminal task; "
            f"responder is not idempotent on duplicate id"
        )
    if tasks_get_result.get("status", {}).get("state") not in snapshot.advertised_states:
        raise StaleAgentCardError(
            f"responder emitted state {tasks_get_result['status']['state']!r} "
            f"not in advertised set {sorted(snapshot.advertised_states)}"
        )
    return "safe_retry"


def delegate_with_guard(
    raw_card: bytes,
    skill_id: str,
    task_id: str,
    session_id: str,
    send_fn,
    get_fn,
) -> TaskRecord:
    snapshot = resolve_card(raw_card, skill_id)
    record = TaskRecord(
        task_id=task_id,
        session_id=session_id,
        card_hash=snapshot.card_hash,
        skill_id=skill_id,
    )
    result = send_fn(task_id=task_id, session_id=session_id, history_length=10)
    if result.get("status", {}).get("state") == "failed":
        record.terminal_state = "failed"
        record.failure_reason = result["status"].get("message", {}).get("reason")
        verdict = classify_failure(
            record=record,
            snapshot=snapshot,
            live_card_bytes=raw_card,
            tasks_get_result=get_fn(task_id=task_id),
        )
        if verdict == "negotiation_drift":
            raise StaleAgentCardError(
                f"card drifted between resolve and failure for {task_id}; "
                f"re-delegate under freshly resolved card"
            )
        if verdict == "safe_retry":
            result = send_fn(task_id=task_id, session_id=session_id, history_length=10)
    record.terminal_state = result.get("status", {}).get("state")
    return record
