# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-during-a2a-v1-0-cross-organization-delegation-when-capability-negotiation-silently-succeeds-against-a-d.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-stale-agent-card-during-a2a-v1-0-cross-organization-delegation-when-capability-negotiation-silently-succeeds-against-a-d.warrant.json
# Markdown SHA-256:   9401a9bb3a2bdd66dc7ea11165d35f0c24517619598d78dc6bd56d81235b522c
# Code AST SHA-256:   698b42fe179a49d222a87cf93eee0b24a221f670b54037fb171229642ef27d06
# Verified Classes:   StaleAgentCardError, AgentCard, LiveRegistry
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class StaleAgentCardError(RuntimeError):
    """Raised when a delegation handshake would proceed against a card
    whose capability surface no longer matches the remote's live registry."""


@dataclass(frozen=True)
class AgentCard:
    protocol_version: str
    skills: frozenset[str]
    generation: Optional[str]  # publisher-supplied freshness token, may be None
    etag: Optional[str]        # discovery-response ETag, may be None


@dataclass(frozen=True)
class LiveRegistry:
    skills: frozenset[str]
    generation: str


def negotiate_delegation(
    card: AgentCard,
    registry: LiveRegistry,
    requested_skill: str,
    client_trust_window_s: int,
) -> str:
    """Confirm the card's claimed capability against the live registry
    before committing a task. Returns the generation token to embed in
    the submission envelope.
    """
    if card.protocol_version != "1.0":
        raise StaleAgentCardError(
            f"protocol mismatch: card={card.protocol_version} client=1.0"
        )

    if requested_skill not in card.skills:
        raise StaleAgentCardError(
            f"skill {requested_skill!r} absent from resolved card; "
            f"card advertises {sorted(card.skills)}"
        )

    # The card claims the skill; now confirm the claim is current.
    if requested_skill not in registry.skills:
        raise StaleAgentCardError(
            f"skill {requested_skill!r} present in card but absent from live "
            f"registry (card generation={card.generation!r}, "
            f"live generation={registry.generation!r}); "
            f"discovery cache is stale — re-resolve .well-known/agent.json"
        )

    # A card with no generation token cannot be freshness-verified; the
    # only safe path is to bind the submission to the live generation so
    # the remote rejects it synchronously if the registry shifts again.
    if card.generation is None:
        return registry.generation

    if card.generation != registry.generation:
        raise StaleAgentCardError(
            f"generation skew: card={card.generation!r} "
            f"registry={registry.generation!r}; refusing to delegate"
        )

    if client_trust_window_s <= 0:
        raise StaleAgentCardError(
            "zero trust window: card cannot be revalidated; "
            "require ETag revalidation or short-TTL discovery"
        )

    return card.generation


def submit_task(card: AgentCard, registry: LiveRegistry, skill: str) -> str:
    gen = negotiate_delegation(card, registry, skill, client_trust_window_s=60)
    envelope_id = hashlib.sha256(f"{skill}:{gen}".encode()).hexdigest()[:16]
    return f"tasks/send envelope={envelope_id} skill={skill} gen={gen}"
