# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-negotiate-a-capability-it-cannot-durably-honor-the-a2a-v1-0-agent-card-task-state-divergence-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-negotiate-a-capability-it-cannot-durably-honor-the-a2a-v1-0-agent-card-task-state-divergence-boundary.warrant.json
# Markdown SHA-256:   3f1b60a8f926cf854032aeaf3e4b28d71fbb113f489fa758bbb9893c2d792bd3
# Code AST SHA-256:   353917958bbb6cc2a3ee0617f95ef1cc27d9d75f2ba3d42a06cd00ebf7c2181a
# Verified Classes:   CardCapabilityDivergence, AgentCard, TaskRecord, DurableTaskStore
# Defensive Guards:   6 fail-closed invariants (zero external deps)

"""
Card/executor divergence probe for A2A v1.0.
Run on every deploy. Fails closed if any advertised capability
cannot be durably honored across replica reassignment.
"""

from dataclasses import dataclass, field
from typing import Optional


class CardCapabilityDivergence(RuntimeError):
    """Raised when an Agent Card advertises a capability the
    durable task state machine cannot honor."""
    pass


@dataclass
class AgentCard:
    streaming: bool = False
    push_notifications: bool = False
    state_transition_history: bool = False
    input_modes: list = field(default_factory=list)
    output_modes: list = field(default_factory=list)


@dataclass
class TaskRecord:
    task_id: str
    context_id: str
    state: str
    history: list = field(default_factory=list)


class DurableTaskStore:
    """The authority. Must be shared across all replicas that can
    serve tasks/get, tasks/resubscribe, tasks/cancel."""

    def __init__(self):
        self._tasks: dict[str, TaskRecord] = {}
        self._message_id_index: dict[str, str] = {}

    def create(self, task_id: str, context_id: str, message_id: str) -> TaskRecord:
        if message_id in self._message_id_index:
            return self._tasks[self._message_id_index[message_id]]
        rec = TaskRecord(task_id=task_id, context_id=context_id, state="submitted")
        rec.history.append(("submitted", None))
        self._tasks[task_id] = rec
        self._message_id_index[message_id] = task_id
        return rec

    def get(self, task_id: str) -> Optional[TaskRecord]:
        return self._tasks.get(task_id)

    def transition(self, task_id: str, new_state: str, note: Optional[str] = None):
        rec = self._tasks.get(task_id)
        if rec is None:
            raise CardCapabilityDivergence(
                f"transition on unknown task {task_id!r}: store is not authoritative"
            )
        rec.state = new_state
        rec.history.append((new_state, note))


def probe_capability_durability(card: AgentCard, store: DurableTaskStore,
                                executor_input_modes: set,
                                executor_output_modes: set,
                                survives_replica_hop: bool) -> None:
    """
    Asserts the invariant:
    every advertised capability bit and every advertised mode must be
    backed by the durable store and the executor's real validators.
    """
    # 1. stateTransitionHistory must be durably appended, not stream-only.
    if card.state_transition_history:
        rec = store.create("probe-1", "ctx-1", "msg-1")
        store.transition("probe-1", "working")
        store.transition("probe-1", "completed")
        if len(rec.history) < 3:
            raise CardCapabilityDivergence(
                "stateTransitionHistory=true but history not appended to store"
            )

    # 2. streaming / pushNotifications require a store the next replica can read.
    if (card.streaming or card.push_notifications) and not survives_replica_hop:
        raise CardCapabilityDivergence(
            "streaming/pushNotifications advertised but task store is replica-local; "
            "tasks/get on a different replica will return TaskNotFoundError"
        )

    # 3. inputModes/outputModes must be a subset of what the executor validates.
    advertised_in = set(card.input_modes)
    advertised_out = set(card.output_modes)
    if not advertised_in.issubset(executor_input_modes):
        raise CardCapabilityDivergence(
            f"card advertises inputModes {advertised_in - executor_input_modes} "
            f"that the executor cannot validate"
        )
    if not advertised_out.issubset(executor_output_modes):
        raise CardCapabilityDivergence(
            f"card advertises outputModes {advertised_out - executor_output_modes} "
            f"that the executor cannot emit"
        )

    # 4. messageId idempotency must resolve retries to the same taskId.
    a = store.create("probe-2", "ctx-2", "msg-dup")
    b = store.create("probe-3", "ctx-2", "msg-dup")
    if a.task_id != b.task_id:
        raise CardCapabilityDivergence(
            "messageId idempotency broken: retry minted a new taskId"
        )


if __name__ == "__main__":
    card = AgentCard(
        streaming=True,
        push_notifications=True,
        state_transition_history=True,
        input_modes=["text/plain", "application/json"],
        output_modes=["text/plain"],
    )
    store = DurableTaskStore()
    # Simulate a gateway whose store is replica-local:
    probe_capability_durability(
        card=card,
        store=store,
        executor_input_modes={"text/plain"},  # executor only handles text
        executor_output_modes={"text/plain"},
        survives_replica_hop=False,           # replica-local store
    )
