# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-peer-s-terminal-task-state-when-a2a-v1-0-tasks-get-returns-completed-but-the-artifact-lineage-does-not-close-over-the.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-peer-s-terminal-task-state-when-a2a-v1-0-tasks-get-returns-completed-but-the-artifact-lineage-does-not-close-over-the.warrant.json
# Markdown SHA-256:   2f9b2979e8b05e2b83b78e265d4b6fcb57cd1ac58ab93f11589ce80762f8d58c
# Code AST SHA-256:   74ad7aa007fc522d6e3f93988cc2320cb73228faf4eaca351da867fd906ccc67
# Verified Classes:   LineageOpenCompletion, Warrant, PinnedCard
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class LineageOpenCompletion(RuntimeError):
    """Raised when a peer reports a terminal 'completed' state whose artifacts
    do not lineage-close over the warrant this instance issued at tasks/send."""


@dataclass(frozen=True)
class Warrant:
    issuer: str
    scope: str
    hash: str
    nonce: str
    delegation_depth: int


@dataclass(frozen=True)
class PinnedCard:
    agent_id: str
    card_hash: str
    output_schema: dict[str, Any]


def _schema_ok(parts: list[dict[str, Any]], schema: dict[str, Any]) -> bool:
    # Minimal structural check; a real impl would use jsonschema.validate.
    for part in parts:
        if part.get("type") != "data":
            continue
        data = part.get("data", {})
        for field, rule in schema.get("properties", {}).items():
            if field not in data:
                return False
            if rule.get("type") == "array" and len(data[field]) < rule.get("minItems", 0):
                return False
    return True


def reconcile_terminal_state(
    issued: Warrant,
    pinned_card: PinnedCard,
    task_get_response: dict[str, Any],
) -> dict[str, Any]:
    status = task_get_response.get("status", {})
    if status.get("state") != "completed":
        return {"accept": False, "reason": "non_terminal"}

    artifacts = task_get_response.get("artifacts", [])
    if not artifacts:
        raise LineageOpenCompletion(
            f"peer {pinned_card.agent_id} returned completed with zero artifacts "
            f"for warrant {issued.hash[:12]}"
        )

    for art in artifacts:
        wm = art.get("metadata", {}).get("warrant", {})
        if wm.get("hash") != issued.hash:
            raise LineageOpenCompletion(
                f"warrant hash mismatch: expected {issued.hash[:12]}, "
                f"got {str(wm.get('hash'))[:12]}"
            )
        if wm.get("nonce") != issued.nonce:
            raise LineageOpenCompletion(
                "warrant nonce mismatch — artifact may be replayed from a prior task"
            )
        if wm.get("delegation_depth") != issued.delegation_depth:
            raise LineageOpenCompletion(
                f"delegation depth laundering: issued {issued.delegation_depth}, "
                f"artifact claims {wm.get('delegation_depth')} — intermediate hop "
                f"collapsed a multi-hop chain"
            )
        if not _schema_ok(art.get("parts", []), pinned_card.output_schema):
            raise LineageOpenCompletion(
                f"artifact parts violate pinned outputSchema of "
                f"card {pinned_card.card_hash[:12]}"
            )

    return {"accept": True, "reason": "lineage_closed"}
