# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-stale-agent-card-s-capabilities-bitmap-as-a-lying-contract-during-a2a-delegation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-stale-agent-card-s-capabilities-bitmap-as-a-lying-contract-during-a2a-delegation.warrant.json
# Markdown SHA-256:   ae83a58715906b507cda7cd7c139f8fef422b006eae19f9a0fc1a5147fa84d1b
# Code AST SHA-256:   0dd3354f6712534da5f454ee2a1dc0dc0770d6a9e2984407c1a0ee18a45e7ec3
# Verified Classes:   StaleAgentCardDelegationError, AgentCard
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class StaleAgentCardDelegationError(RuntimeError):
    """Raised when delegation proceeds against a card whose skill
    declaration is stale or unverified at send time."""
    pass


class AgentCard:
    def __init__(self, peer_id, skills, fetched_at, ttl_seconds):
        self.peer_id = peer_id
        self.skills = set(skills)
        self.fetched_at = fetched_at
        self.ttl_seconds = ttl_seconds

    def is_fresh(self, now):
        return (now - self.fetched_at) <= self.ttl_seconds

    def declares(self, skill_id):
        return skill_id in self.skills


def delegate_task(card, skill_id, payload, now, remote_echoes_skill_resolution):
    # Invariant: never delegate on card presence alone when the card
    # is stale or the remote does not echo skill resolution.
    if not card.is_fresh(now):
        if not remote_echoes_skill_resolution:
            raise StaleAgentCardDelegationError(
                f"card for {card.peer_id} is stale "
                f"(age={(now - card.fetched_at)}s > ttl={card.ttl_seconds}s) "
                f"and remote does not echo skill resolution; "
                f"refusing to delegate {skill_id} on advertisement alone"
            )

    if not card.declares(skill_id):
        raise StaleAgentCardDelegationError(
            f"card for {card.peer_id} does not declare skill {skill_id}; "
            f"refusing to send"
        )

    # Acceptance is provisional: caller must NOT advance its plan on
    # 'working' unless remote_echoes_skill_resolution is True.
    return {
        "peer_id": card.peer_id,
        "skill_id": skill_id,
        "payload": payload,
        "acceptance_is_provisional": not remote_echoes_skill_resolution,
    }
