# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-silent-capability-widening-failure-in-a2a-v1-0-agent-card-discovery-when-delegated-task-lifecycle-states-are-negoti.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-silent-capability-widening-failure-in-a2a-v1-0-agent-card-discovery-when-delegated-task-lifecycle-states-are-negoti.warrant.json
# Markdown SHA-256:   398911eb0ab3e2ecae2523a9b20586ced516107000ed346772fd9b1b40a336e4
# Code AST SHA-256:   b92f63012d88c86413b6a04e77392e2b54144a5438a5421b19d1b907553a9d11
# Verified Classes:   CardDriftError, TaskStalledError, CachedCard, DelegatedTask
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class CardDriftError(RuntimeError):
    """Raised when a remote agent card diverges from the one a task was negotiated against."""
    pass


class TaskStalledError(RuntimeError):
    """Raised when a task remains non-terminal past its liveness bound with no state change."""
    pass


@dataclass
class CachedCard:
    fingerprint: str
    skills: frozenset
    streaming: bool
    push_notifications: bool


@dataclass
class DelegatedTask:
    task_id: str
    skill: str
    card_at_creation: CachedCard
    last_state: str = "submitted"
    last_change_ts: float = field(default_factory=time.monotonic)


def fingerprint_card(card_json: dict) -> str:
    # Canonicalize the fields that actually gate lifecycle behavior.
    basis = repr(sorted(card_json.get("skills", []))) + repr(
        card_json.get("capabilities", {})
    )
    return hashlib.sha256(basis.encode()).hexdigest()


def guard_poll(
    task: DelegatedTask,
    current_card_json: dict,
    current_state: str,
    now: Optional[float] = None,
    liveness_bound_s: float = 90.0,
) -> None:
    """
    Called on every tasks/get poll. Raises if the task is being driven against
    a card that no longer matches, or if the task has stalled.
    """
    now = now if now is not None else time.monotonic()

    if current_state != task.last_state:
        task.last_state = current_state
        task.last_change_ts = now
        return

    # State unchanged: check card drift before declaring a stall.
    current_fp = fingerprint_card(current_card_json)
    if current_fp != task.card_at_creation.fingerprint:
        if task.skill not in current_card_json.get("skills", []):
            raise CardDriftError(
                f"Task {task.task_id}: skill '{task.skill}' removed from remote card "
                f"mid-task (was {task.card_at_creation.fingerprint[:12]}, "
                f"now {current_fp[:12]}). Lifecycle contract void; renegotiate or fail."
            )
        raise CardDriftError(
            f"Task {task.task_id}: remote card drifted "
            f"({task.card_at_creation.fingerprint[:12]} -> {current_fp[:12]}) "
            f"while state='{current_state}'. Re-validate inputModes before next send."
        )

    if now - task.last_change_ts > liveness_bound_s:
        raise TaskStalledError(
            f"Task {task.task_id}: state='{current_state}' unchanged for "
            f"{now - task.last_change_ts:.1f}s against a stable card. "
            f"Remote handler likely swallowed a transition; abort and record."
        )
