# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-that-a-delegated-a2a-task-has-been-silently-reaped-by-the-remote-agent-s-card-version-rotation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-that-a-delegated-a2a-task-has-been-silently-reaped-by-the-remote-agent-s-card-version-rotation.warrant.json
# Markdown SHA-256:   0e94ca9483337d34653ebfec8b698ab786c197e983dbab9dd1f4fff906bf3c99
# Code AST SHA-256:   46058c89a1900c5f2c7e327316e563ba3e23646a676834b92db9f4de2108dadf
# Verified Classes:   CardBindingInvalidatedError, CardSnapshot
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


class CardBindingInvalidatedError(RuntimeError):
    """Raised when the remote Agent Card has drifted since delegation,
    invalidating tasks/get as a liveness oracle for the in-flight task."""
    pass


@dataclass(frozen=True)
class CardSnapshot:
    card_hash: str
    task_endpoint: str
    streaming: bool


def canonical_card_hash(card: dict) -> str:
    # Canonicalize the fields that govern task execution binding.
    binding = {
        "endpoints": card.get("endpoints", {}),
        "capabilities": {
            "streaming": card.get("capabilities", {}).get("streaming", False),
            "taskContinuityAcrossRevisions": card.get("capabilities", {}).get(
                "taskContinuityAcrossRevisions", False
            ),
        },
        "skills": sorted(
            (s.get("id"), s.get("version")) for s in card.get("skills", [])
        ),
    }
    return hashlib.sha256(
        json.dumps(binding, sort_keys=True, separators=(",", ":")).encode()
    ).hexdigest()


def assert_card_binding_stable(
    delegated_snapshot: CardSnapshot,
    current_card: dict,
    task_state: str,
) -> None:
    current_hash = canonical_card_hash(current_card)
    current_endpoint = current_card.get("endpoints", {}).get("task", "")
    current_streaming = current_card.get("capabilities", {}).get("streaming", False)

    continuity_opt_in = current_card.get("capabilities", {}).get(
        "taskContinuityAcrossRevisions", False
    )
    if continuity_opt_in:
        return  # Operator guarantees task continuity across revisions.

    if task_state not in ("working", "submitted", "input-required"):
        return  # Terminal or non-live states do not rely on the oracle.

    if current_hash != delegated_snapshot.card_hash:
        raise CardBindingInvalidatedError(
            "Agent Card drifted since delegation "
            f"(delegated_hash={delegated_snapshot.card_hash[:12]}, "
            f"current_hash={current_hash[:12]}, "
            f"delegated_endpoint={delegated_snapshot.task_endpoint}, "
            f"current_endpoint={current_endpoint}, "
            f"delegated_streaming={delegated_snapshot.streaming}, "
            f"current_streaming={current_streaming}); "
            "tasks/get state is no longer a valid liveness oracle for this task."
        )


def poll_task_liveness(
    delegated_snapshot: CardSnapshot,
    fetch_card,
    fetch_task_state,
    task_id: str,
) -> Optional[str]:
    current_card = fetch_card()
    assert_card_binding_stable(
        delegated_snapshot=delegated_snapshot,
        current_card=current_card,
        task_state=fetch_task_state(task_id),
    )
    return fetch_task_state(task_id)
