# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-discovers-a-peer-agent-card-whose-declared-task-state-machine-is-only-partially-conformant-to-a2a-v1-0-and-then-hands-of.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-discovers-a-peer-agent-card-whose-declared-task-state-machine-is-only-partially-conformant-to-a2a-v1-0-and-then-hands-of.warrant.json
# Markdown SHA-256:   ec30e3dd6a32f4ce0119cfce47f23cf7e734c716f27c46dbefe6eabcb7963c59
# Code AST SHA-256:   288ea0dba6444457f3d00ee46b42d3fa757c66779c0abd55ad06cd96a021dd3e
# Verified Classes:   HandoffConformanceError, PeerConformanceRecord, ConformanceRegistry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field
from typing import Literal

TaskState = Literal[
    "submitted", "working", "input-required", "auth-required",
    "completed", "failed", "canceled", "rejected",
]

NON_TERMINAL = {"submitted", "working", "input-required", "auth-required"}
TERMINAL = {"completed", "failed", "canceled", "rejected"}


class HandoffConformanceError(RuntimeError):
    """Raised when a mid-lifecycle task transfer would violate the A2A v1.0 transition invariant."""


@dataclass
class PeerConformanceRecord:
    peer_id: str
    state_path: tuple[TaskState, ...]
    observed_at: float
    history_append_policy: Literal["echo", "suppress", "unknown"]
    final_on_pause: bool
    message_id_dedup_states: frozenset[TaskState]
    ttl_seconds: float = 3600.0

    def is_fresh(self) -> bool:
        return (time.time() - self.observed_at) < self.ttl_seconds


@dataclass
class ConformanceRegistry:
    records: dict[tuple[str, tuple[TaskState, ...]], PeerConformanceRecord] = field(default_factory=dict)

    def lookup(self, peer_id: str, path: tuple[TaskState, ...]) -> PeerConformanceRecord | None:
        rec = self.records.get((peer_id, path))
        if rec is None or not rec.is_fresh():
            return None
        return rec


def _last_message_hash(history: list[dict]) -> str:
    if not history:
        return ""
    last = history[-1]
    blob = f"{last.get('role','')}|{last.get('messageId','')}|{last.get('content','')}"
    return hashlib.sha256(blob.encode()).hexdigest()


def plan_handoff(
    *,
    client_id: str,
    peer_id: str,
    task_id: str,
    current_state: TaskState,
    history: list[dict],
    registry: ConformanceRegistry,
    card_advertises_streaming: bool,
) -> Literal["transfer", "recreate", "probe_then_transfer"]:
    """
    Decide whether a mid-lifecycle handoff to `peer_id` is safe.

    Invariant: transfer is permitted only if the peer's transition function
    has been observed on the exact state path we are about to hand off,
    and the observation is fresh. Otherwise we must re-create the task
    from `submitted`, where the A2A transition graph is unambiguous.
    """
    if current_state in TERMINAL:
        raise HandoffConformanceError(
            f"task {task_id} is terminal ({current_state}); terminal tasks must not be transferred"
        )

    if current_state == "submitted":
        # Unambiguous: both machines start from the same state.
        return "transfer"

    path = (current_state,)
    rec = registry.lookup(peer_id, path)

    if rec is None:
        # No verified transition function for this peer on this path.
        # A card that advertises streaming is NOT sufficient evidence.
        if card_advertises_streaming:
            # We *could* probe, but probing is only safe if the peer
            # supports a no-op skill; absent that, re-create.
            return "recreate"
        return "recreate"

    # We have a fresh observation. Now check the specific hazards that
    # caused the incident: final-on-pause, history append policy, and
    # messageId dedup coverage.
    if current_state in {"input-required", "auth-required"}:
        if rec.final_on_pause:
            raise HandoffConformanceError(
                f"peer {peer_id} sets final=true on {current_state}; "
                f"client would close its stream reader and lose the artifact. "
                f"Re-create task {task_id} instead of transferring."
            )
        if current_state not in rec.message_id_dedup_states:
            raise HandoffConformanceError(
                f"peer {peer_id} does not dedup messageId in state {current_state}; "
                f"client timeout-retry would double-apply the user turn. "
                f"Transfer of task {task_id} is unsafe."
            )

    if rec.history_append_policy == "echo" and _last_message_hash(history) != "":
        # Echo policy means the peer will re-append our last message;
        # length-based reconciliation would drop a real agent turn.
        # Require hash-based reconciliation, which the caller must opt into.
        raise HandoffConformanceError(
            f"peer {peer_id} echoes history (append policy=echo); "
            f"length-based reconciliation would corrupt task {task_id}. "
            f"Caller must reconcile by messageId hash before transfer."
        )

    return "transfer"


def execute_handoff(
    *,
    client_id: str,
    peer_id: str,
    task_id: str,
    current_state: TaskState,
    history: list[dict],
    registry: ConformanceRegistry,
    card_advertises_streaming: bool,
    send_fn,
    recreate_fn,
) -> str:
    decision = plan_handoff(
        client_id=client_id,
        peer_id=peer_id,
        task_id=task_id,
        current_state=current_state,
        history=history,
        registry=registry,
        card_advertises_streaming=card_advertises_streaming,
    )
    if decision == "transfer":
        return send_fn(peer_id=peer_id, task_id=task_id, state=current_state, history=history)
    if decision == "recreate":
        return recreate_fn(peer_id=peer_id, task_id=task_id, history=history)
    raise HandoffConformanceError(f"unreachable decision {decision}")
