# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-agent-card-discovery-mismatch-will-silently-corrupt-task-lifecycle-negotiation-before-the-first-message-i.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-agent-card-discovery-mismatch-will-silently-corrupt-task-lifecycle-negotiation-before-the-first-message-i.warrant.json
# Markdown SHA-256:   98777248c669577ce73e192d6e172d63b0d4be7b64ea1ea4330933f2cb30972b
# Code AST SHA-256:   cb069bb5813f6f4c79ea484698890e09324b96c9fd109b50ad3fabc791ec4525
# Verified Classes:   AgentCardContractError, ProbeResult
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Literal


class AgentCardContractError(RuntimeError):
    """Raised when a resolved Agent Card's declared capabilities diverge
    from observed task-lifecycle behavior for the target skill."""
    pass


@dataclass(frozen=True)
class ProbeResult:
    skill_id: str
    observed_output_mode: str
    terminal_state: Literal["completed", "failed", "working"]
    elapsed_s: float


def probe_card_before_promotion(
    card: dict,
    skill_id: str,
    probe: ProbeResult,
    max_terminal_latency_s: float = 30.0,
) -> None:
    """Validate a freshly resolved Agent Card against a single probe task
    before promoting it to the trusted cache. Raises AgentCardContractError
    on any structural signal of divergence.
    """
    skill = next((s for s in card.get("skills", []) if s.get("id") == skill_id), None)
    if skill is None:
        raise AgentCardContractError(
            f"skill {skill_id!r} absent from card; cannot attest capability"
        )

    # Signal 1: skill-level outputModes override card defaults. The probe must
    # match the skill-level declaration, not defaultOutputModes.
    declared_modes = skill.get("outputModes", card.get("defaultOutputModes", []))
    if probe.observed_output_mode not in declared_modes:
        raise AgentCardContractError(
            f"mode divergence: probe returned {probe.observed_output_mode!r}, "
            f"skill declares {declared_modes!r}"
        )

    # Signal 2: streaming-dependent lifecycle. If the card advertises streaming
    # but the probe never reached a terminal state, the callee is waiting on a
    # stream consumer that was never opened.
    capabilities = card.get("capabilities", {})
    if capabilities.get("streaming") and probe.terminal_state == "working":
        raise AgentCardContractError(
            "streaming dependency: probe stuck in 'working'; card requires a "
            "stream consumer the dispatcher did not open"
        )

    # Signal 3: scope/skill mismatch. A failed probe within the latency bound
    # with a declared OAuth2 scheme whose scopes omit the skill id indicates
    # the skill is gated behind an undeclared scope.
    if probe.terminal_state == "failed":
        schemes = card.get("securitySchemes", {})
        for scheme in schemes.values():
            scopes = scheme.get("flows", {}).get("clientCredentials", {}).get("scopes", {})
            if scopes and skill_id not in scopes:
                raise AgentCardContractError(
                    f"scope gap: skill {skill_id!r} not in declared scopes "
                    f"{list(scopes)}; probe failed after {probe.elapsed_s:.1f}s"
                )
        raise AgentCardContractError(
            f"probe failed for skill {skill_id!r} with no attributable signal"
        )

    # Signal 4: latency bound. A terminal state arriving after the bound
    # indicates an internal timeout path that masked the real failure.
    if probe.elapsed_s > max_terminal_latency_s:
        raise AgentCardContractError(
            f"terminal latency {probe.elapsed_s:.1f}s exceeds bound "
            f"{max_terminal_latency_s:.1f}s; failure path is masking state"
        )


def promote_or_quarantine(card: dict, skill_id: str, probe: ProbeResult) -> str:
    try:
        probe_card_before_promotion(card, skill_id, probe)
    except AgentCardContractError as exc:
        return f"QUARANTINE:{exc}"
    return "PROMOTE"
