# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-task-whose-agent-card-was-signed-by-a-key-the-caller-never-resolved.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-task-whose-agent-card-was-signed-by-a-key-the-caller-never-resolved.warrant.json
# Markdown SHA-256:   3fb0dd7de38f350267785dcd45d89f74e510812e314ea33841051be49581ecad
# Code AST SHA-256:   6f2d97e83d87a9d23ebed0914d5c7cccc9f841a9d16427144c1dbfd1692c79b2
# Verified Classes:   TrustBoundaryError, AgentCard, TaskHandle
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import uuid
from dataclasses import dataclass


class TrustBoundaryError(RuntimeError):
    """Raised when a task lifecycle crosses a trust boundary the card did not authorize."""
    pass


@dataclass
class AgentCard:
    kid: str
    issuer: str
    skills: list[str]
    binds_executor_identity: bool  # True only if securityScheme yields sub==kid at request time


@dataclass
class TaskHandle:
    task_id: str
    executor_instance: str | None = None
    terminal: bool = False


def begin_task(card: AgentCard, requested_skill: str, caller_generated_id: str | None = None) -> TaskHandle:
    if requested_skill not in card.skills:
        raise TrustBoundaryError(
            f"skill {requested_skill!r} not in signed card for kid={card.kid}; "
            f"card advertises {card.skills}"
        )
    if not card.binds_executor_identity:
        # Card is authentic but does not bind the executing instance to kid.
        # Refuse to create a task whose cancel may route to a different worker.
        raise TrustBoundaryError(
            f"card kid={card.kid} issuer={card.issuer} does not bind executor identity; "
            f"task lifecycle would be unverifiable across the worker pool"
        )
    return TaskHandle(task_id=caller_generated_id or str(uuid.uuid4()))


def cancel_task(handle: TaskHandle, executor_response_status: int) -> None:
    if executor_response_status == 404:
        # Do not retry: a 404 on cancel means the executor that received the
        # cancel never saw the task. Retrying cannot reconcile terminal state.
        raise TrustBoundaryError(
            f"tasks/cancel for {handle.task_id} returned 404 from "
            f"executor {handle.executor_instance!r}; task state is orphaned"
        )
    if handle.terminal:
        raise TrustBoundaryError(
            f"task {handle.task_id} already terminal; cancel would violate monotonicity"
        )
    handle.terminal = True
