# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a-task-lifecycle-against-a-stale-a2a-agent-card-whose-declared-capabilities-diverge-from-the-peer-s-live-sche.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-a-task-lifecycle-against-a-stale-a2a-agent-card-whose-declared-capabilities-diverge-from-the-peer-s-live-sche.warrant.json
# Markdown SHA-256:   87a93eaf92bb9ec0119f946bf555e3d05a3f93929fcfb11360a830f921a3cab5
# Code AST SHA-256:   0b6e2db8f770e17da046c960005ce9f6895808dccc1f85eef5446d20fa60df57
# Verified Classes:   A2ALifecycleDivergence, PinnedTask
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Any


class A2ALifecycleDivergence(RuntimeError):
    """Raised when a task's negotiated schema diverges from the peer's live schema
    or when the peer's task store loses a task ID mid-lifecycle."""


@dataclass
class PinnedTask:
    task_id: str
    peer: str
    schema_at_submit: dict[str, Any]
    state: str = "submitted"
    created_at: float = field(default_factory=time.time)
    last_continuation_schema: dict[str, Any] | None = None


def build_continuation(
    task: PinnedTask,
    input_required_message: dict[str, Any],
    cached_card: dict[str, Any],
    refetch_card,
) -> dict[str, Any]:
    """Construct the follow-up turn. The input-required message is authoritative;
    the cached card is advisory. Divergence is a protocol error, not a retry."""
    msg_parts = input_required_message.get("parts", [])
    msg_schema = input_required_message.get("metadata", {}).get("schema")
    card_modes = set(cached_card.get("defaultInputModes", []))

    msg_modes = {p.get("type") for p in msg_parts if "type" in p}
    if not msg_modes.issubset(card_modes):
        # Card and live message disagree. Re-fetch once; if still disagreeing, fail.
        fresh = refetch_card(task.peer)
        fresh_modes = set(fresh.get("defaultInputModes", []))
        if not msg_modes.issubset(fresh_modes):
            raise A2ALifecycleDivergence(
                f"peer {task.peer} task {task.task_id}: input-required message "
                f"demands modes {msg_modes} not in card (cached={card_modes}, "
                f"fresh={fresh_modes}); schema={msg_schema}"
            )
        cached_card = fresh  # adopt fresh card for this continuation only

    task.last_continuation_schema = {"modes": msg_modes, "schema": msg_schema}
    task.state = "working"
    return {"taskId": task.task_id, "message": {"parts": msg_parts}}


def handle_continuation_response(task: PinnedTask, response: dict[str, Any]) -> None:
    """A -32001 on continuation means the peer lost the task ID. Terminal."""
    error = response.get("error")
    if error and error.get("code") == -32001:
        task.state = "failed"
        raise A2ALifecycleDivergence(
            f"peer {task.peer} lost task {task.task_id} (code -32001); "
            f"task ID is peer-scoped and must not be reused"
        )
    if "result" in response:
        task.state = response["result"].get("status", {}).get("state", task.state)


def reconcile_orphans(tasks: list[PinnedTask], peer_probe, ttl_s: float = 300.0) -> list[str]:
    """Sweep tasks whose peer-side record is gone or whose age exceeds TTL."""
    orphans = []
    now = time.time()
    for t in tasks:
        if t.state in ("completed", "failed"):
            continue
        if now - t.created_at > ttl_s:
            t.state = "failed"
            orphans.append(t.task_id)
            continue
        probe = peer_probe(t.peer, t.task_id)
        if probe.get("error", {}).get("code") == -32001:
            t.state = "failed"
            orphans.append(t.task_id)
    return orphans
