# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-against-a-stale-agent-card-capability-drift-at-the-a2a-v1-0-discovery-boundary-and-the-task-state-conformance.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-against-a-stale-agent-card-capability-drift-at-the-a2a-v1-0-discovery-boundary-and-the-task-state-conformance.warrant.json
# Markdown SHA-256:   47f366a6ef2fa66a9b1d6e49a94cfd6b3be768e6bd9743b475c9d5d4fe469a49
# Code AST SHA-256:   d7246a1f45143ac7f71577bcb027336320c4d0471423d4701c4d6b3646ad138f
# Verified Classes:   CapabilityContractMismatch, TaskState, Task, Replica
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from enum import Enum
from typing import Any


class CapabilityContractMismatch(RuntimeError):
    """Raised when a task envelope's negotiated card hash does not match
    the executing replica's live capability hash at the submitted->working
    transition. Non-retryable by contract."""


class TaskState(str, Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"


# Fields that constitute the capability contract. Everything else on the
# Agent Card (name, description, url, human `version`) is advisory and MUST
# NOT participate in the hash.
CONTRACT_FIELDS = (
    "capabilities",
    "skills",
    "defaultInputModes",
    "defaultOutputModes",
)


def capability_hash(card: dict[str, Any]) -> str:
    projection = {k: card.get(k) for k in CONTRACT_FIELDS}
    canonical = json.dumps(projection, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


@dataclass
class Task:
    task_id: str
    state: TaskState = TaskState.SUBMITTED
    envelope_metadata: dict[str, Any] = field(default_factory=dict)
    status_message: dict[str, Any] = field(default_factory=dict)


class Replica:
    def __init__(self, live_card: dict[str, Any]) -> None:
        self.live_card = live_card
        self.live_hash = capability_hash(live_card)

    def declared_input_fields(self, skill_id: str) -> set[str]:
        for skill in self.live_card.get("skills", []):
            if skill.get("id") == skill_id:
                return set(skill.get("inputSchema", {}).get("required", []))
        return set()

    def transition_to_working(self, task: Task) -> Task:
        # The single guard. Enforced at the only point where the replica
        # still knows which contract the client negotiated against.
        client_hash = task.envelope_metadata.get("agentCardHash")
        if client_hash != self.live_hash:
            task.state = TaskState.FAILED
            task.status_message = {
                "reason": "capability-contract-mismatch",
                "retryable": False,
                "clientHash": client_hash,
                "liveHash": self.live_hash,
            }
            raise CapabilityContractMismatch(
                f"task {task.task_id}: client negotiated {client_hash!r}, "
                f"replica serves {self.live_hash!r}"
            )
        task.state = TaskState.WORKING
        return task

    def request_input(self, task: Task, skill_id: str, field_name: str) -> Task:
        # input-required is only legal for fields declared in the *negotiated*
        # card's input schema. Undeclared fields are a contract violation.
        if field_name not in self.declared_input_fields(skill_id):
            task.state = TaskState.FAILED
            task.status_message = {
                "reason": "undeclared-input-required",
                "retryable": False,
                "field": field_name,
            }
            raise CapabilityContractMismatch(
                f"task {task.task_id}: input-required for undeclared field "
                f"{field_name!r} on skill {skill_id!r}"
            )
        task.state = TaskState.INPUT_REQUIRED
        return task


# --- demonstration of the drift regime ---

if __name__ == "__main__":
    old_card = {
        "capabilities": {"streaming": True, "pushNotifications": True},
        "skills": [{"id": "invoice-reconcile", "inputSchema": {"required": []}}],
        "defaultInputModes": ["application/json"],
        "defaultOutputModes": ["application/json"],
    }
    new_card = {
        "capabilities": {"streaming": True, "pushNotifications": False},
        "skills": [
            {
                "id": "invoice-reconcile-v2",
                "inputSchema": {"required": ["currency"]},
            }
        ],
        "defaultInputModes": ["application/json"],
        "defaultOutputModes": ["application/json"],
    }

    stale_client_hash = capability_hash(old_card)
    replica = Replica(new_card)

    task = Task(
        task_id="t-001",
        envelope_metadata={"agentCardHash": stale_client_hash, "skillId": "invoice-reconcile"},
    )

    try:
        replica.transition_to_working(task)
    except CapabilityContractMismatch as exc:
        # Client classifier: reason == capability-contract-mismatch -> invalidate
        # cache, re-resolve, do NOT retry identical payload.
        assert task.state is TaskState.FAILED
        assert task.status_message["retryable"] is False
        print(f"rejected fast: {exc}")
