# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-stale-a2a-v1-0-agent-card-is-silently-rebinding-a-delegated-task-to-a-deprecated-skill-endpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-stale-a2a-v1-0-agent-card-is-silently-rebinding-a-delegated-task-to-a-deprecated-skill-endpoint.warrant.json
# Markdown SHA-256:   880d77bfc02dfb4bf1be796dea81dd58b04671913a74d6381b8dfc7f60f9d420
# Code AST SHA-256:   ac73684f6b7343070a4abe94902ec2e6de296609f07c3431c1469c1fc5384eed
# Verified Classes:   CardRebindError, TaskBinding
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CardRebindError(RuntimeError):
    """Raised when a task's authorizing Agent Card hash no longer matches
    the hash echoed by the remote worker on a status update.

    This is a terminal condition for the task: the worker advancing the
    state machine is not the worker the caller validated against.
    """


@dataclass(frozen=True)
class TaskBinding:
    task_id: str
    card_hash: str
    skill_id: str


def canonical_card_hash(card: dict) -> str:
    """Stable hash of the Agent Card snapshot used at delegation time.

    Canonicalization matters: vendors serialize the same card with
    different key orderings and whitespace. We hash the sorted-key
    compact encoding so that a re-fetch of an unchanged card produces
    the same hash.
    """
    encoded = json.dumps(card, sort_keys=True, separators=(",", ":")).encode("utf-8")
    return hashlib.sha256(encoded).hexdigest()


def validate_status_update(binding: TaskBinding, status_payload: dict) -> None:
    """Validate that a webhook status update comes from the same card
    snapshot that authorized the task.

    Raises CardRebindError if the echoed cardHash is missing or mismatched.
    A missing echo is treated as a rebind because a compliant remote must
    echo it; silence is indistinguishable from a redeployed worker that
    dropped the metadata field.
    """
    echoed = status_payload.get("metadata", {}).get("cardHash")
    if echoed is None:
        raise CardRebindError(
            f"task {binding.task_id}: status update omitted metadata.cardHash; "
            f"cannot confirm worker matches card {binding.card_hash[:12]}"
        )
    if echoed != binding.card_hash:
        raise CardRebindError(
            f"task {binding.task_id}: card rebind detected. "
            f"delegated against {binding.card_hash[:12]}, "
            f"worker now reports {echoed[:12]} for skill {binding.skill_id}"
        )


def handle_webhook(binding: TaskBinding, status_payload: dict) -> str:
    """Entry point for the caller's push-notification receiver."""
    try:
        validate_status_update(binding, status_payload)
    except CardRebindError:
        # Cancel the zombie task and surface for re-delegation.
        return "cancel_and_redelegate"
    return status_payload["status"]["state"]
