# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-an-agent-card-s-declared-capabilities-against-an-observed-schema-mismatch-during-a2a-v1-0-cross-framework-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-an-agent-card-s-declared-capabilities-against-an-observed-schema-mismatch-during-a2a-v1-0-cross-framework-delegation.warrant.json
# Markdown SHA-256:   5d6232153f70bec3d51045be5b5da8218195ef7b347282d5e8425b15cb7f92e5
# Code AST SHA-256:   fc838e9e42297e2c193941c51c26633f1d53f9cd4d380ce1e62a3f90d1fdebb4
# Verified Classes:   AgentCardConformanceError, CardGeneration, CanaryResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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


class AgentCardConformanceError(RuntimeError):
    """Raised when a remote agent's runtime behavior contradicts its Agent Card
    declaration in a way that would cause silent-wrong delegation."""
    pass


@dataclass
class CardGeneration:
    agent_url: str
    etag: str
    fetched_at: float
    declared_streaming: bool
    declared_history: bool
    declared_input_modes: list[str]


@dataclass
class CanaryResult:
    generation: CardGeneration
    content_ok: bool
    frames_observed: int
    history_length: int
    ran_at: float = field(default_factory=time.time)


def probe_agent(
    card: CardGeneration,
    send_task: Callable[[dict], dict],
    canary_payload: dict,
    expected_canary_answer: str,
) -> CanaryResult:
    """Send a minimal self-verifying task and validate BOTH content and transport
    against the card's declarations. Does not trust the card; the card is the
    hypothesis under test."""
    resp = send_task(canary_payload)

    # Content check: the canary's answer is known to the client.
    content_ok = expected_canary_answer in (resp.get("output") or "")

    # Transport checks: capability overclaims surface here, not in content.
    frames = resp.get("stream_frame_count", 0)
    history = len(resp.get("history") or [])

    if card.declared_streaming and frames == 0:
        raise AgentCardConformanceError(
            f"{card.agent_url} declared streaming=true but canary observed 0 frames; "
            f"delegation would block until timeout with truncated payload."
        )
    if card.declared_history and history == 0:
        raise AgentCardConformanceError(
            f"{card.agent_url} declared stateTransitionHistory=true but canary "
            f"returned empty history; audit trail would be lost."
        )
    if resp.get("state") == "completed" and not content_ok:
        raise AgentCardConformanceError(
            f"{card.agent_url} returned state=completed with output that fails the "
            f"canary's known-answer check; silent-wrong delegation risk."
        )
    return CanaryResult(card, content_ok, frames, history)


def delegate_with_canary_gate(
    card: CardGeneration,
    canary_cache: dict[str, CanaryResult],
    send_task: Callable[[dict], dict],
    canary_payload: dict,
    expected_canary_answer: str,
    real_task: dict,
    capability_criticality: bool,
    failure_visibility_low: bool,
) -> dict:
    """Gate a real delegation on a fresh, passing canary when the risk triangle
    (stale card, critical capability, silent-wrong failure) is fully lit."""
    key = (card.agent_url, card.etag)
    risk_triangle = capability_criticality and failure_visibility_low

    cached = canary_cache.get(key)
    if risk_triangle and cached is None:
        cached = probe_agent(card, send_task, canary_payload, expected_canary_answer)
        canary_cache[key] = cached

    if risk_triangle and cached is not None and not cached.content_ok:
        raise AgentCardConformanceError(
            f"Canary for {card.agent_url}@{card.etag} failed known-answer check; "
            f"refusing real delegation to avoid silent-wrong result."
        )

    return send_task(real_task)
