# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-a-cached-agent-card-s-declared-task-state-transitions-against-an-in-flight-a2a-task-when-the-remote-agent-silently-re.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-a-cached-agent-card-s-declared-task-state-transitions-against-an-in-flight-a2a-task-when-the-remote-agent-silently-re.warrant.json
# Markdown SHA-256:   6db0dbaeb189ebafdca6189b081b215643079e6702199872e5a90a53161530e7
# Code AST SHA-256:   0c62acca0fd9bd329890286e8b68a70f2718706344808e5a146a1d268a5c1712
# Verified Classes:   LifecycleDriftError, AgentCard, TaskLease
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class LifecycleDriftError(RuntimeError):
    """Raised when a live task's transition is illegal under the current remote card.

    Carries both the cached card hash (lease at task start) and the live card
    hash (lease at the failing transition), plus the rejected edge, so the
    task can be reconciled rather than silently orphaned.
    """

    def __init__(self, task_id: str, edge: tuple[str, str],
                 cached_hash: str, live_hash: str, observed_state: str):
        self.task_id = task_id
        self.edge = edge
        self.cached_hash = cached_hash
        self.live_hash = live_hash
        self.observed_state = observed_state
        super().__init__(
            f"task {task_id}: edge {edge[0]}->{edge[1]} legal under cached card "
            f"{cached_hash[:12]} but not under live card {live_hash[:12]}; "
            f"server emitted {observed_state!r}"
        )


@dataclass
class AgentCard:
    """Minimal A2A v1.0 card view: the lifecycle graph it declares."""
    transitions: dict[str, set[str]] = field(default_factory=dict)
    skills: set[str] = field(default_factory=set)

    def allows(self, src: str, dst: str) -> bool:
        return dst in self.transitions.get(src, set())

    def content_hash(self) -> str:
        canon = repr(sorted((s, sorted(d)) for s, d in self.transitions.items()))
        return hashlib.sha256(canon.encode()).hexdigest()


@dataclass
class TaskLease:
    """Card pinned to a task at creation; re-fetched at each boundary."""
    task_id: str
    card: AgentCard
    card_hash: str

    @classmethod
    def open(cls, task_id: str, card: AgentCard) -> "TaskLease":
        return cls(task_id=task_id, card=card, card_hash=card.content_hash())


def advance(lease: TaskLease, current: str, dst: str,
            refetch_card) -> str:
    """Take one transition, reconciling card drift before committing the edge.

    The server's emitted state is authoritative; the cached card is a
    hypothesis. If the edge is illegal under the cached card, re-fetch and
    check whether the *live* card permits it. If neither does, the task is
    not recoverable under any known card and must fail loudly.
    """
    if lease.card.allows(current, dst):
        return dst  # lease honored; no drift on this edge

    live = refetch_card()
    live_hash = live.content_hash()

    if live.allows(current, dst):
        # Card drifted but the edge survives the narrowing: adopt the new lease.
        lease.card = live
        lease.card_hash = live_hash
        return dst

    raise LifecycleDriftError(
        task_id=lease.task_id,
        edge=(current, dst),
        cached_hash=lease.card_hash,
        live_hash=live_hash,
        observed_state=dst,
    )


def run_resume(lease: TaskLease, current: str, dst: str, refetch_card) -> str:
    """Resume path with explicit drift handling; never retries a drift as transport."""
    try:
        return advance(lease, current, dst, refetch_card)
    except LifecycleDriftError:
        # Do NOT retry: a narrowed graph will reject every retry identically.
        # Surface for re-planning under the live card.
        raise
