# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-pass-mcp-conformance-yet-corrupt-a2a-handoffs-the-schema-widening-blind-spot-at-protocol-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-pass-mcp-conformance-yet-corrupt-a2a-handoffs-the-schema-widening-blind-spot-at-protocol-boundaries.warrant.json
# Markdown SHA-256:   4c9d9034b2bd99b2d9b801da24f71446a44dcc76a9e9d55b6599c29a652623c9
# Code AST SHA-256:   eda3deaa3ba6cab68f4ad10c2c695a999fd0d8adb8172e30692e30ba2e2aa883
# Verified Classes:   ProtocolSeamViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import json
from typing import Any, Callable


class ProtocolSeamViolation(RuntimeError):
    """Raised when an egress artifact carries fields the downstream peer's
    closed schema forbids — the MCP-widening / A2A-strictness seam failure."""
    pass


def project_egress(
    ingress: dict[str, Any],
    artifact_schema: dict[str, Any],
    emit: Callable[[dict[str, Any]], None],
) -> dict[str, Any]:
    """Project a widened MCP ingress frame onto a strict A2A artifact schema.

    Accepts wide (unknown keys tolerated at ingress), emits narrow (unknown
    keys dropped). Raises ProtocolSeamViolation if a required artifact field
    is missing after projection — the case where the seam cannot be bridged
    without a semantic fix upstream.
    """
    allowed = set(artifact_schema.get("properties", {}).keys())
    required = set(artifact_schema.get("required", []))

    if artifact_schema.get("additionalProperties", True) is not False:
        # Consumer is lenient; passthrough is safe for this peer.
        projected = dict(ingress)
    else:
        projected = {k: v for k, v in ingress.items() if k in allowed}

    missing = required - projected.keys()
    if missing:
        raise ProtocolSeamViolation(
            f"egress projection dropped required artifact fields {sorted(missing)}; "
            f"ingress keys were {sorted(ingress.keys())} — the orchestrator must "
            f"supply these explicitly, retrying with the same widened frame will "
            f"reproduce this deadlock"
        )

    dropped = set(ingress.keys()) - projected.keys()
    if dropped:
        # Surface the diff so the orchestrator can invalidate the offending
        # field in episodic memory instead of re-emitting it on retry.
        projected["__seam_dropped__"] = sorted(dropped)

    emit(projected)
    return projected


def handle_handoff(
    ingress_frame: dict[str, Any], artifact_schema: dict[str, Any]
) -> None:
    try:
        project_egress(ingress_frame, artifact_schema, emit=lambda a: None)
    except ProtocolSeamViolation:
        raise
    except Exception as exc:  # noqa: BLE001
        raise ProtocolSeamViolation(
            f"unexpected seam failure projecting {sorted(ingress_frame)}: {exc}"
        ) from exc


if __name__ == "__main__":
    strict_artifact = {
        "type": "object",
        "properties": {"rows": {"type": "array"}},
        "required": ["rows"],
        "additionalProperties": False,
    }
    # Widened ingress passes MCP conformance but corrupts the A2A handoff.
    widened = {"rows": [], "timeout_ms": 5000}
    projected = handle_handoff(widened, strict_artifact) or project_egress(
        widened, strict_artifact, emit=lambda a: None
    )
    assert "timeout_ms" not in projected
    print(json.dumps(projected))
