# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-silent-a2a-v1-0-capability-shim-downgrade-before-it-commits-a-delegated-task.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-silent-a2a-v1-0-capability-shim-downgrade-before-it-commits-a-delegated-task.warrant.json
# Markdown SHA-256:   02a1c4b7f5cb776c8710919b344ee3fcb39fe46add629f2e94dff677c27253b6
# Code AST SHA-256:   d7f97809358f274c6423280965b29e2ad4f2f5023c9ae72ea461c50359628952
# Verified Classes:   ShimElisionError, Part
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ShimElisionError(RuntimeError):
    """Raised when a peer's shim parsed fewer or coerced parts than were sent."""


@dataclass(frozen=True)
class Part:
    mime_type: str
    payload: bytes

    def digest(self) -> str:
        return hashlib.sha256(self.payload).hexdigest()


def assert_manifest_round_trip(sent: list[Part], echoed: list[Part], peer_id: str) -> None:
    if len(sent) != len(echoed):
        raise ShimElisionError(
            f"peer {peer_id} parsed {len(echoed)} of {len(sent)} parts; "
            f"shim dropped parts it could not map"
        )
    for i, (s, e) in enumerate(zip(sent, echoed)):
        if s.mime_type != e.mime_type:
            raise ShimElisionError(
                f"peer {peer_id} coerced part[{i}] {s.mime_type} -> {e.mime_type}; "
                f"structured payload lost"
            )
        if s.digest() != e.digest():
            raise ShimElisionError(
                f"peer {peer_id} mutated part[{i}] payload; digest mismatch"
            )


def delegate_with_probe(caller, peer_card, task_parts: list[Part]) -> str:
    if peer_card.protocol_version != "1.0":
        raise ShimElisionError(f"unsupported native version {peer_card.protocol_version}")
    if peer_card.compatibility_shims:
        probe = caller.send_task(peer_card, task_parts, history_length=1)
        assert_manifest_round_trip(task_parts, probe.echoed_parts, peer_card.agent_id)
    result = caller.send_task(peer_card, task_parts, history_length=1)
    assert_manifest_round_trip(task_parts, result.echoed_parts, peer_card.agent_id)
    return result.artifact
