# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-delegated-task-whose-agent-card-was-discovered-under-a-different-protocol-epoch-than-the-task-envelope-claims.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-delegated-task-whose-agent-card-was-discovered-under-a-different-protocol-epoch-than-the-task-envelope-claims.warrant.json
# Markdown SHA-256:   17e3272de22ef6eb74e1bbf9b6c61a1f5865fc4a2f5d2e0b75b4d0c132b4a0c3
# Code AST SHA-256:   ba78dbb2ac5ae79e7a8e9e74db2409d79176ad40a22948c3f5ab61c162096493
# Verified Classes:   ProtocolEpochSkewError, AgentCard, TaskEnvelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ProtocolEpochSkewError(RuntimeError):
    """Raised when a task envelope is built from a card epoch that does not
    match the live card the callee is actually serving."""


@dataclass(frozen=True)
class AgentCard:
    protocol_version: str
    skill_schema_hash: str
    etag: str


@dataclass(frozen=True)
class TaskEnvelope:
    built_from_card_etag: str
    built_from_schema_hash: str
    protocol_version: str
    payload: dict


def delegate(
    envelope: TaskEnvelope,
    live_card: AgentCard,
    *,
    strict: bool = True,
) -> dict:
    """Dispatch a delegated task only if the envelope's provenance matches the
    live card. In strict mode, any skew is a hard rejection; the caller must
    re-negotiate rather than let the callee coerce unknown fields to defaults.
    """
    if envelope.protocol_version != live_card.protocol_version:
        raise ProtocolEpochSkewError(
            f"envelope protocol {envelope.protocol_version!r} != "
            f"live card protocol {live_card.protocol_version!r}; "
            f"re-negotiate before dispatch"
        )

    if envelope.built_from_card_etag != live_card.etag:
        raise ProtocolEpochSkewError(
            f"envelope built from card etag {envelope.built_from_card_etag!r}, "
            f"live card etag is {live_card.etag!r}; cached card is stale"
        )

    if envelope.built_from_schema_hash != live_card.skill_schema_hash:
        raise ProtocolEpochSkewError(
            "skill schema changed between discovery and invocation; "
            "unknown optional fields would be silently defaulted by the callee"
        )

    # Only now is the envelope semantically valid against the callee.
    return _dispatch(envelope.payload, live_card)


def _dispatch(payload: dict, live_card: AgentCard) -> dict:
    # Real transport call would go here; the invariant is enforced above.
    return {"status": "completed", "echoed_etag": live_card.etag, "result": payload}
