# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-a2a-task-the-agent-card-capability-superset-invariant-and-the-silent-re-negotiation-trap.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-a2a-task-the-agent-card-capability-superset-invariant-and-the-silent-re-negotiation-trap.warrant.json
# Markdown SHA-256:   03cf9a82b3ceac3f255c96a3883e26cbac0cf5cdd78983ea0537d5aad7df4b14
# Code AST SHA-256:   65d5763dae749fbd154d3550f636babed204d7eada656d8e4c2b5345dca4efe4
# Verified Classes:   CapabilityContractViolation, StaleCardUnreconcilable, AgentCard, TaskContext
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class CapabilityContractViolation(RuntimeError):
    """Raised when a remote agent requests an input modality its Agent Card
    (as re-fetched) does not declare for the invoked skill. This is a
    server-side card/runtime divergence, not a client error."""


class StaleCardUnreconcilable(RuntimeError):
    """Raised when the client cannot re-fetch the Agent Card to reconcile an
    out-of-contract input-required, and policy forbids fabrication."""


@dataclass
class AgentCard:
    etag: str
    skills: dict  # skill_id -> set of declared input mime types
    fetched_at: float


@dataclass
class TaskContext:
    task_id: str
    skill_id: str
    card_at_start: AgentCard
    card_in_use: AgentCard = field(init=False)

    def __post_init__(self):
        self.card_in_use = self.card_at_start


def handle_input_required(
    ctx: TaskContext,
    requested_mime: str,
    refetch_card,          # callable(etag) -> Optional[AgentCard]; None == 304
    allow_human_escalation: bool,
) -> str:
    """Decide how to respond to an input-required transition.

    Returns one of: 'satisfy', 'escalate', 'fail_contract', 'fail_unreconcilable'.
    """
    declared = ctx.card_in_use.skills.get(ctx.skill_id, set())

    if requested_mime in declared:
        return "satisfy"

    # Out-of-contract request: reconcile against live card.
    fresh = refetch_card(ctx.card_in_use.etag)

    if fresh is None:
        # 304: card unchanged, yet server asks for undeclared modality.
        raise CapabilityContractViolation(
            f"task {ctx.task_id}: skill {ctx.skill_id} requested "
            f"undeclared input mime {requested_mime!r}; card unchanged "
            f"(etag={ctx.card_in_use.etag}). Server runtime has diverged "
            f"from its Agent Card."
        )

    # Card changed mid-task: adopt for remainder of task only.
    ctx.card_in_use = fresh
    if requested_mime in fresh.skills.get(ctx.skill_id, set()):
        return "satisfy"

    if allow_human_escalation:
        return "escalate"

    raise StaleCardUnreconcilable(
        f"task {ctx.task_id}: re-fetched card (etag={fresh.etag}) still "
        f"does not declare {requested_mime!r} for skill {ctx.skill_id}; "
        f"cannot satisfy and escalation disabled."
    )


def _demo():
    card = AgentCard(
        etag="v2.3.1",
        skills={"extract.v2": {"text/plain"}},
        fetched_at=0.0,
    )
    ctx = TaskContext(task_id="t-1", skill_id="extract.v2", card_at_start=card)

    # Server re-fetched card now also allows pdf (post-deploy expansion).
    upgraded = AgentCard(
        etag="v2.4.0",
        skills={"extract.v2": {"text/plain", "application/pdf"}},
        fetched_at=1.0,
    )

    def refetch(etag):
        return upgraded if etag != upgraded.etag else None

    # Out-of-contract request, card changed -> reconcile and satisfy.
    assert handle_input_required(ctx, "application/pdf", refetch, False) == "satisfy"

    # Server never updates card but asks for audio -> contract violation.
    ctx2 = TaskContext(task_id="t-2", skill_id="extract.v2", card_at_start=card)
    try:
        handle_input_required(ctx2, "audio/wav", lambda e: None, False)
    except CapabilityContractViolation:
        pass
    else:
        raise AssertionError("expected CapabilityContractViolation")


if __name__ == "__main__":
    _demo()
