# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-task-against-a-stale-agent-card-after-the-remote-vendor-rotates-its-signing-key-mid-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-delegated-task-against-a-stale-agent-card-after-the-remote-vendor-rotates-its-signing-key-mid-delegation.warrant.json
# Markdown SHA-256:   12a73f8813abe61f095ad26d072439cd6fab8e6c974ca50bbcb031d9e387edeb
# Code AST SHA-256:   10dcaa83b24ba654d91bbbc2628fa25c27b92eba53bb0bbc95ee5d5d8d302feb
# Verified Classes:   CardBindingError, AgentCard, ArtifactEnvelope
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class CardBindingError(RuntimeError):
    """Raised when an artifact's card binding does not match the snapshot
    that authorized the delegated task."""


@dataclass(frozen=True)
class AgentCard:
    generation: str
    kid: str
    raw: dict

    def digest(self) -> str:
        canonical = json.dumps(self.raw, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


@dataclass(frozen=True)
class ArtifactEnvelope:
    task_id: str
    kid: str
    card_digest: str | None
    payload_hash: str


def verify_artifact_against_authorization(
    authorized_card: AgentCard,
    artifact: ArtifactEnvelope,
) -> None:
    """Verify an artifact against the card snapshot that authorized the task.

    Deliberately does NOT re-fetch the remote card here. Re-fetching at
    verification time decouples authorization from verification and lets a
    card publisher retroactively legitimize an artifact.
    """
    if artifact.card_digest is None:
        # A2A v1.0 does not mandate card_digest. Without it we cannot bind
        # the artifact to the authorization snapshot, and any rotation that
        # straddles the task will produce an ambiguous result.
        raise CardBindingError(
            f"artifact for task {artifact.task_id} carries no card_digest; "
            "cannot bind verification to authorization snapshot "
            f"{authorized_card.generation}"
        )

    if artifact.card_digest != authorized_card.digest():
        raise CardBindingError(
            f"artifact for task {artifact.task_id} was signed under card "
            f"digest {artifact.card_digest[:12]}..., but the task was "
            f"authorized under {authorized_card.generation} "
            f"({authorized_card.digest()[:12]}...). The remote rotated its "
            "card mid-delegation; refuse rather than re-fetch and re-verify."
        )

    if artifact.kid != authorized_card.kid:
        raise CardBindingError(
            f"artifact kid {artifact.kid} does not match authorized kid "
            f"{authorized_card.kid}; the remote signed with a key introduced "
            "after task acceptance"
        )


def delegate_task(
    remote_card: AgentCard,
    estimated_duration_s: int,
    rotation_period_s: int | None,
) -> None:
    """Pre-flight check before sending a delegated task."""
    if rotation_period_s is None:
        raise CardBindingError(
            "remote does not advertise a rotation cadence and its artifact "
            "scheme does not carry card_digest; in-flight tasks may straddle "
            "an unannounced rotation and fail verification ambiguously"
        )
    if estimated_duration_s >= rotation_period_s:
        raise CardBindingError(
            f"estimated task duration {estimated_duration_s}s exceeds remote "
            f"rotation period {rotation_period_s}s; the task will cross a "
            "rotation boundary and artifact verification cannot be bound to "
            "the authorization snapshot"
        )
