# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-validly-signed-agent-card-the-a2a-v1-0-capability-scope-drift-failure-in-cross-vendor-delegation-handshakes.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-validly-signed-agent-card-the-a2a-v1-0-capability-scope-drift-failure-in-cross-vendor-delegation-handshakes.warrant.json
# Markdown SHA-256:   1e5ada1c716e08e8a60d5d3e1fdd32f30d0cde50479f824d989adb6749deb95c
# Code AST SHA-256:   56a5b54a9ca7b1a413b635de1be762ab47e69b9116280c177b88cf27edad80a3
# Verified Classes:   StaleCapabilityCardError, CapabilityProbeFailedError, AgentCard, DelegationPolicy
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class StaleCapabilityCardError(RuntimeError):
    """Raised when an authentic Agent Card is too old to bind a task to."""
    pass


class CapabilityProbeFailedError(RuntimeError):
    """Raised when a live capability probe contradicts the card."""
    pass


@dataclass
class AgentCard:
    kid: str
    version: str
    created_epoch: float
    capabilities: dict          # e.g. {"streaming": True, "skills": [...]}
    signature_valid: bool


@dataclass
class DelegationPolicy:
    freshness_window_s: float = 900.0      # 15 min for high-churn vendors
    require_probe_without_history: bool = True


def verify_and_bind(
    card: AgentCard,
    required_capabilities: dict,
    policy: DelegationPolicy,
    prior_success_within_window: bool,
    probe_fn,                              # callable(card) -> dict of live caps
    now: Optional[float] = None,
) -> None:
    """
    Enforce the conjunctive validity condition. Returns None on success;
    raises on any boundary violation. Must be called BEFORE the caller
    commits a task ID to durable state.
    """
    now = now if now is not None else time.time()

    # Conjunct 1: authenticity.
    if not card.signature_valid:
        raise StaleCapabilityCardError(
            f"card kid={card.kid} failed signature verification"
        )

    # Conjunct 2: freshness. Authenticity is not liveness.
    age = now - card.created_epoch
    if age > policy.freshness_window_s:
        raise StaleCapabilityCardError(
            f"card kid={card.kid} v{card.version} age={age:.0f}s "
            f"exceeds freshness_window={policy.freshness_window_s:.0f}s; "
            f"authentic but not delegable"
        )

    # Conjunct 3a: declared capability superset.
    for cap, want in required_capabilities.items():
        have = card.capabilities.get(cap)
        if have != want:
            raise CapabilityProbeFailedError(
                f"card declares {cap}={have!r}, task requires {want!r}"
            )

    # Conjunct 3b: liveness. Without prior success, require a live probe.
    if not prior_success_within_window:
        if not policy.require_probe_without_history:
            return
        live = probe_fn(card)
        for cap, want in required_capabilities.items():
            if live.get(cap) != want:
                raise CapabilityProbeFailedError(
                    f"live probe contradicts card: {cap}={live.get(cap)!r} "
                    f"vs declared {want!r} (runtime drift / rollback)"
                )


def delegate_task(card: AgentCard, task_payload: dict, policy: DelegationPolicy,
                  prior_success: bool, probe_fn, commit_fn) -> str:
    """
    Order matters: verify+probe FIRST, commit task ID to durable state SECOND.
    Reversing this order is the boundary failure this record documents.
    """
    verify_and_bind(
        card=card,
        required_capabilities=task_payload["requires"],
        policy=policy,
        prior_success_within_window=prior_success,
        probe_fn=probe_fn,
    )
    # Only now is it safe to write to episodic memory / outbox.
    task_id = commit_fn(task_payload)
    return task_id
