# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-an-a2a-v1-0-agent-card-whose-signed-capability-manifest-validates-but-whose-declared-taskenvelopeschema-diverges-from-the.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-an-a2a-v1-0-agent-card-whose-signed-capability-manifest-validates-but-whose-declared-taskenvelopeschema-diverges-from-the.warrant.json
# Markdown SHA-256:   254cde7dccbdad7821fa0fb25d90e061a8257022c7d6e02dafe651a5d6258e59
# Code AST SHA-256:   66066a8ea5d82b1e6e6faf5d988545517adc78949bbbeb9fbb753bf02232294c
# Verified Classes:   SchemaEchoMismatch, EnvelopeRejected, SignedManifest, CalleeRuntime
# Defensive Guards:   6 fail-closed invariants (zero external deps)

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


class SchemaEchoMismatch(RuntimeError):
    """Raised when the callee's runtime echoes a schema version that diverges
    from the signed capability manifest, or fails to echo at all."""


class EnvelopeRejected(RuntimeError):
    """Raised when the callee rejects an envelope whose size/shape was within
    the manifest's declared bounds — evidence the manifest bound is stale."""


@dataclass
class SignedManifest:
    schema_version: str
    max_envelope_bytes: int
    manifest_digest: str
    signature_valid: bool


@dataclass
class CalleeRuntime:
    """Simulates the execution plane, which may lag the signed manifest."""
    actual_schema: str
    actual_max_bytes: int
    echoes_schema: bool = True

    def probe(self, envelope: dict) -> dict:
        if not self.echoes_schema:
            return {"task_handle": "h-1"}  # no echo: caller must stay provisional
        return {"task_handle": "h-1", "schema_echo": self.actual_schema}

    def dispatch(self, envelope: dict) -> dict:
        size = len(json.dumps(envelope).encode())
        if size > self.actual_max_bytes:
            raise EnvelopeRejected(f"envelope {size}B exceeds runtime bound {self.actual_max_bytes}B")
        return {"status": "accepted", "schema": self.actual_schema}


def delegate(manifest: SignedManifest, runtime: CalleeRuntime, payload: dict) -> dict:
    if not manifest.signature_valid:
        raise SchemaEchoMismatch("manifest signature invalid; cannot proceed")

    probe_env = {"schema": manifest.schema_version, "payload": {"probe": True}}
    probe_resp = runtime.probe(probe_env)

    echoed = probe_resp.get("schema_echo")
    if echoed is None:
        raise SchemaEchoMismatch(
            f"callee did not echo schema; manifest claims {manifest.schema_version!r} "
            "but compatibility is unproven — refusing to commit task state"
        )
    if echoed != manifest.schema_version:
        raise SchemaEchoMismatch(
            f"manifest claims {manifest.schema_version!r} but runtime echoed {echoed!r}; "
            "signed card is stale relative to execution plane"
        )

    envelope = {"schema": echoed, "payload": payload}
    size = len(json.dumps(envelope).encode())
    if size > manifest.max_envelope_bytes:
        raise EnvelopeRejected(
            f"envelope {size}B exceeds manifest bound {manifest.max_envelope_bytes}B"
        )

    try:
        return runtime.dispatch(envelope)
    except EnvelopeRejected as e:
        # Manifest bound was stale; do not retry against it.
        raise EnvelopeRejected(
            f"manifest bound {manifest.max_envelope_bytes}B not honored by runtime: {e}"
        ) from e


# Failure trace: manifest says 1.4, runtime is 1.5, echo is present.
manifest = SignedManifest(
    schema_version="1.4",
    max_envelope_bytes=262144,
    manifest_digest=hashlib.sha256(b"manifest").hexdigest(),
    signature_valid=True,
)
runtime = CalleeRuntime(actual_schema="1.5", actual_max_bytes=131072)

try:
    delegate(manifest, runtime, {"text": "hello"})
except SchemaEchoMismatch as e:
    print(f"BLOCKED before task commit: {e}")
