# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-an-a2a-v1-0-agent-card-is-a-stale-capability-projection-rather-than-a-live-contract-at-delegation-time.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-an-a2a-v1-0-agent-card-is-a-stale-capability-projection-rather-than-a-live-contract-at-delegation-time.warrant.json
# Markdown SHA-256:   d5177ab795dc018655734286db77719f7f73defcc9da765bb3c8d937c9e7e57e
# Code AST SHA-256:   69b1d47016336be373c77bcdfa4d4400d700dcb8c8f0fb534cc5e2638d2c70b2
# Verified Classes:   StaleProjectionError, CapabilityMismatchError, AgentCard
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass

MAX_PROJECTION_AGE_S = 4 * 3600
PROBE_HALF_LIFE_S = MAX_PROJECTION_AGE_S // 2


class StaleProjectionError(RuntimeError):
    """Raised when an A2A agent card cannot be trusted as a live capability contract."""
    pass


class CapabilityMismatchError(RuntimeError):
    """Raised when the peer rejects echo-negotiated capabilities (-32001)."""
    pass


@dataclass
class AgentCard:
    skill_id: str
    skill_version: str
    output_modes: list
    streaming: bool
    minted_at: float          # epoch seconds, from metadata.projection.minted_at
    content_hash: str
    served_from_mirror: bool


def fetch_live_capabilities(peer_url: str) -> dict:
    # GET /capabilities/live — authoritative runtime probe, bypasses mirror cache.
    ...


def delegate(card: AgentCard, task_payload: dict, peer_url: str) -> dict:
    age = time.time() - card.minted_at

    if age > MAX_PROJECTION_AGE_S:
        raise StaleProjectionError(
            f"card for {card.skill_id}@{card.skill_version} is {age:.0f}s old "
            f"(max {MAX_PROJECTION_AGE_S}s); refusing optimistic delegation"
        )

    if age > PROBE_HALF_LIFE_S or card.served_from_mirror:
        live = fetch_live_capabilities(peer_url)
        if (live["output_modes"] != card.output_modes
                or live["streaming"] != card.streaming
                or live["skill_version"] != card.skill_version):
            raise StaleProjectionError(
                f"card/runtime divergence for {card.skill_id}: "
                f"card={card.output_modes}/{card.streaming}/{card.skill_version} "
                f"live={live['output_modes']}/{live['streaming']}/{live['skill_version']}"
            )

    envelope = {
        "message": task_payload,
        "metadata": {
            "requestedCapabilities": {
                "outputModes": card.output_modes,
                "streaming": card.streaming,
                "skill": f"{card.skill_id}@{card.skill_version}",
            }
        },
    }
    resp = _post(peer_url + "/message/send", envelope)  # noqa: F821

    if resp.get("error", {}).get("code") == -32001:
        raise CapabilityMismatchError(
            f"peer rejected echo-negotiated capabilities: {resp['error']['message']}"
        )
    return resp


def validate_completion(card: AgentCard, task_result: dict) -> None:
    artifact_modes = {a["mimeType"] for a in task_result.get("artifacts", [])}
    if not artifact_modes.issubset(set(card.output_modes)):
        raise CapabilityMismatchError(
            f"completed task emitted {artifact_modes} outside declared "
            f"outputModes {card.output_modes}; task state is transport-valid but "
            f"semantically invalid"
        )
