# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-agent-card-capability-claims-against-observed-task-execution-conformance-during-a-cross-vendor-a2a-v1-0-delegation-ha.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-agent-card-capability-claims-against-observed-task-execution-conformance-during-a-cross-vendor-a2a-v1-0-delegation-ha.warrant.json
# Markdown SHA-256:   bf7cd5feac55f06b51d995739c14eb43839460dfcde52cd858d8a0f9da2204ff
# Code AST SHA-256:   de56ac1ade96b209cf649bbb44b177e52e4b86e607976e3f2f2bb7e307b73106
# Verified Classes:   A2AConformanceError, Witness, ConformanceRegistry
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import json
import time
from dataclasses import dataclass, field
from typing import Any


class A2AConformanceError(RuntimeError):
    """Raised when a remote agent's execution diverges from its Agent Card declaration."""


@dataclass
class Witness:
    vendor_id: str
    skill: str
    input_mode: str
    output_mode: str
    observed_at: float
    ttl_seconds: float = 3600.0

    def is_fresh(self, now: float | None = None) -> bool:
        now = now if now is not None else time.time()
        return (now - self.observed_at) < self.ttl_seconds


@dataclass
class ConformanceRegistry:
    witnesses: dict[tuple[str, str, str, str], Witness] = field(default_factory=dict)

    def _key(self, vendor_id: str, skill: str, in_mode: str, out_mode: str):
        return (vendor_id, skill, in_mode, out_mode)

    def has_fresh_witness(self, vendor_id: str, skill: str, in_mode: str, out_mode: str) -> bool:
        w = self.witnesses.get(self._key(vendor_id, skill, in_mode, out_mode))
        return w is not None and w.is_fresh()

    def record(self, vendor_id: str, skill: str, in_mode: str, out_mode: str) -> None:
        self.witnesses[self._key(vendor_id, skill, in_mode, out_mode)] = Witness(
            vendor_id=vendor_id, skill=skill, input_mode=in_mode,
            output_mode=out_mode, observed_at=time.time(),
        )

    def invalidate(self, vendor_id: str, skill: str, in_mode: str, out_mode: str) -> None:
        self.witnesses.pop(self._key(vendor_id, skill, in_mode, out_mode), None)


def validate_artifact_against_declared_mode(artifact: dict[str, Any], declared_output_mode: str) -> None:
    """Enforce the declared output mode at artifact-receipt time, before local completion."""
    parts = artifact.get("parts") or []
    if not parts:
        raise A2AConformanceError("artifact has no parts; remote reported completed with empty payload")
    part = parts[0]
    actual = part.get("mimeType")
    if actual != declared_output_mode:
        raise A2AConformanceError(
            f"declared output mode {declared_output_mode!r} but artifact mimeType {actual!r}"
        )
    if declared_output_mode == "application/json":
        body = part.get("data") if "data" in part else part.get("text")
        try:
            json.loads(body) if isinstance(body, str) else body
        except (json.JSONDecodeError, TypeError) as exc:
            raise A2AConformanceError(
                f"artifact claims application/json but body is not parseable JSON: {exc}"
            ) from exc


def probe_skill(remote_call, vendor_id: str, skill: str, in_mode: str, out_mode: str,
                probe_input: dict[str, Any]) -> None:
    """Send a minimal known-answer probe; raise if execution diverges from the card."""
    task = remote_call("message/send", {
        "skill": skill,
        "message": {"role": "user", "parts": [probe_input]},
    })
    if task.get("status", {}).get("state") != "completed":
        raise A2AConformanceError(
            f"probe task for {skill}/{in_mode}->{out_mode} did not complete: {task.get('status')}"
        )
    artifacts = task.get("artifacts") or []
    if not artifacts:
        raise A2AConformanceError(f"probe for {skill} returned no artifact")
    validate_artifact_against_declared_mode(artifacts[0], out_mode)


def delegate_with_provisional_barrier(
    remote_call,
    registry: ConformanceRegistry,
    vendor_id: str,
    skill: str,
    in_mode: str,
    out_mode: str,
    real_input: dict[str, Any],
    probe_input: dict[str, Any],
    budget_release,
) -> dict[str, Any]:
    """Delegate only after a fresh witness; hold budget until artifact validates."""
    if not registry.has_fresh_witness(vendor_id, skill, in_mode, out_mode):
        probe_skill(remote_call, vendor_id, skill, in_mode, out_mode, probe_input)
        registry.record(vendor_id, skill, in_mode, out_mode)

    task = remote_call("message/send", {
        "skill": skill,
        "message": {"role": "user", "parts": [real_input]},
    })
    if task.get("status", {}).get("state") != "completed":
        raise A2AConformanceError(f"delegated task did not complete: {task.get('status')}")

    artifacts = task.get("artifacts") or []
    try:
        validate_artifact_against_declared_mode(artifacts[0], out_mode)
    except A2AConformanceError:
        registry.invalidate(vendor_id, skill, in_mode, out_mode)
        remote_call("tasks/cancel", {"taskId": task.get("id")})
        raise

    budget_release(task.get("id"))
    return task
