# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-advertises-a-skill-in-its-agent-card-that-its-task-lifecycle-cannot-actually-negotiate.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-advertises-a-skill-in-its-agent-card-that-its-task-lifecycle-cannot-actually-negotiate.warrant.json
# Markdown SHA-256:   b0cdd3d4aa9ebc6c9a1e2cb50b0c7b5f7d61ad295ada7f874cf9da4e4b6aed8f
# Code AST SHA-256:   bdd2aab6ddc79b1c4ac93946675e372bc691cca7b519c32022935c95ffde4794
# Verified Classes:   LifecycleNegotiationError, TaskState, AgentCard, DelegationProbe
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import enum
from dataclasses import dataclass, field
from typing import Optional


class LifecycleNegotiationError(RuntimeError):
    """Raised when an advertised skill cannot be negotiated to a terminal state."""
    pass


class TaskState(enum.Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    COMPLETED = "completed"
    FAILED = "failed"


@dataclass
class AgentCard:
    name: str
    skills: list[str]
    push_notifications: bool
    state_transition_history: bool


@dataclass
class DelegationProbe:
    card: AgentCard
    orchestrator_supports_push: bool = False
    observed_states: list[TaskState] = field(default_factory=list)

    def can_observe_input_required(self) -> bool:
        if TaskState.INPUT_REQUIRED not in self.observed_states:
            return False
        if self.card.push_notifications and not self.orchestrator_supports_push:
            return False
        return True


def preflight_delegation(probe: DelegationProbe, skill: str) -> None:
    if skill not in probe.card.skills:
        raise LifecycleNegotiationError(
            f"skill {skill!r} not advertised by {probe.card.name!r}"
        )
    if not probe.can_observe_input_required():
        raise LifecycleNegotiationError(
            f"cannot observe input-required lifecycle on {probe.card.name!r}: "
            f"push_notifications={probe.card.push_notifications}, "
            f"orchestrator_supports_push={probe.orchestrator_supports_push}, "
            f"observed={[s.value for s in probe.observed_states]}"
        )


def delegate(card: AgentCard, skill: str, probe: Optional[DelegationProbe]) -> str:
    if probe is None:
        raise LifecycleNegotiationError(
            "refusing delegation without lifecycle preflight; "
            "card discovery is necessary but not sufficient"
        )
    preflight_delegation(probe, skill)
    return f"delegated:{skill}->{card.name}"
