# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-an-a2a-task-envelope-against-a-stale-agent-card-the-capability-superset-illusion-in-cross-framework-delegatio.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-an-a2a-task-envelope-against-a-stale-agent-card-the-capability-superset-illusion-in-cross-framework-delegatio.warrant.json
# Markdown SHA-256:   57a7b885ac4d7ee2c1b9bd35b3f2a9a29ee94e565bf435d81ad8bb6d522bdff8
# Code AST SHA-256:   9b1812608bdf5187128c9d336bdba752e33b895f4b2948def901e575e090239a
# Verified Classes:   CardEnvelopeDriftError, AgentCard
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field
from typing import Any


class CardEnvelopeDriftError(RuntimeError):
    """Raised when a task envelope is constructed against a card revision
    that the remote is not currently serving, or when an artifact-schema
    rejection is misclassified as a transport failure."""


@dataclass
class AgentCard:
    revision: str
    skills: dict[str, dict[str, Any]]
    capabilities: dict[str, bool] = field(default_factory=dict)

    def fingerprint(self) -> str:
        payload = json.dumps(
            {"revision": self.revision, "skills": self.skills,
             "capabilities": self.capabilities},
            sort_keys=True,
        ).encode()
        return hashlib.sha256(payload).hexdigest()


def build_envelope(card: AgentCard, skill_id: str, task_input: dict[str, Any],
                   live_card_fingerprint: str) -> dict[str, Any]:
    """Construct a delegation envelope ONLY if the cached card is coherent
    with the remote's live card revision. Otherwise refuse to build."""
    if skill_id not in card.skills:
        raise CardEnvelopeDriftError(
            f"skill {skill_id!r} absent from card revision {card.revision!r}"
        )

    # Invariant: the card we build against must match the remote's live card.
    if card.fingerprint() != live_card_fingerprint:
        raise CardEnvelopeDriftError(
            "card-envelope coherence violated: cached card revision "
            f"{card.revision!r} does not match live fingerprint; "
            "re-fetch card before delegating"
        )

    skill = card.skills[skill_id]
    return {
        "skill": skill_id,
        "cardRevision": card.revision,
        "cardFingerprint": live_card_fingerprint,
        "acceptedOutputModes": skill["outputModes"],
        "input": task_input,
    }


def classify_failure(envelope: dict[str, Any], outcome: dict[str, Any]) -> str:
    """Separate transport failure from artifact-schema rejection. A schema
    rejection must NEVER trip the UNREACHABLE circuit-breaker."""
    if outcome.get("transport_error"):
        return "UNREACHABLE"
    if not outcome.get("artifact_valid", True):
        # Schema mismatch against a live card => contract drift, not death.
        raise CardEnvelopeDriftError(
            f"artifact rejected for skill {envelope['skill']!r} against "
            f"card revision {envelope['cardRevision']!r}; "
            "classify as CONTRACT_DRIFT and refresh card, do not mark UNREACHABLE"
        )
    return "OK"
