# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-silent-capability-widening-mismatch-between-a-discovered-a2a-agent-card-and-the-task-acceptance-it-receives-at-delegatio.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-silent-capability-widening-mismatch-between-a-discovered-a2a-agent-card-and-the-task-acceptance-it-receives-at-delegatio.warrant.json
# Markdown SHA-256:   bb40be2e956a959bd3b9fc58afbd7de15bc2bc75f3221757aa029c0a8d2c5e35
# Code AST SHA-256:   e8ad655b0d6bd1602b3cf62ff676af15bb4b4be09ec09c1ca608687edc61a020
# Verified Classes:   CapabilityDriftError, TransportAdoptionError, CapabilityContract
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class CapabilityDriftError(RuntimeError):
    """Raised when the acceptor's effective contract diverges from the discovered card."""
    pass


class TransportAdoptionError(CapabilityDriftError):
    """Raised when streaming frames arrive on a task the card declared non-streaming."""
    pass


@dataclass
class CapabilityContract:
    peer_id: str
    card_hash: str
    skill_id: str
    output_modes: frozenset[str]
    streaming: bool
    recorded_at: float
    max_age_s: float = 60.0

    def is_fresh(self) -> bool:
        return (time.time() - self.recorded_at) <= self.max_age_s


def structural_hash(card: dict[str, Any]) -> str:
    material = {
        "skills": sorted(
            (s.get("id"), tuple(sorted(s.get("outputModes", []))))
            for s in card.get("skills", [])
        ),
        "streaming": bool(card.get("capabilities", {}).get("streaming", False)),
        "defaultOutputModes": tuple(sorted(card.get("defaultOutputModes", []))),
    }
    return hashlib.sha256(
        json.dumps(material, sort_keys=True).encode("utf-8")
    ).hexdigest()


def build_contract(peer_id: str, card: dict[str, Any], skill_id: str) -> CapabilityContract:
    skill = next((s for s in card.get("skills", []) if s.get("id") == skill_id), None)
    if skill is None:
        raise CapabilityDriftError(f"skill {skill_id!r} absent from card for {peer_id}")
    return CapabilityContract(
        peer_id=peer_id,
        card_hash=structural_hash(card),
        skill_id=skill_id,
        output_modes=frozenset(skill.get("outputModes", [])),
        streaming=bool(card.get("capabilities", {}).get("streaming", False)),
        recorded_at=time.time(),
    )


def validate_first_artifact(
    contract: CapabilityContract,
    fresh_card: dict[str, Any],
    artifact_mime: str,
    streaming_frames_seen: bool,
) -> None:
    if not contract.is_fresh():
        raise CapabilityDriftError(
            f"contract for {contract.peer_id} is stale "
            f"({time.time() - contract.recorded_at:.1f}s > {contract.max_age_s}s TTL)"
        )

    if structural_hash(fresh_card) != contract.card_hash:
        raise CapabilityDriftError(
            f"card hash drifted for {contract.peer_id}: "
            f"{contract.card_hash[:12]} -> {structural_hash(fresh_card)[:12]}"
        )

    if artifact_mime not in contract.output_modes:
        raise CapabilityDriftError(
            f"artifact mimeType {artifact_mime!r} not in contracted "
            f"outputModes {sorted(contract.output_modes)} for skill {contract.skill_id}"
        )

    if streaming_frames_seen and not contract.streaming:
        raise TransportAdoptionError(
            f"streaming frames observed on non-streaming contract for {contract.peer_id}; "
            f"adopt stream and extend deadline before consuming artifact"
        )
