# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-peer-s-successful-tool-result-during-a2a-conformance-testing.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-peer-s-successful-tool-result-during-a2a-conformance-testing.warrant.json
# Markdown SHA-256:   6f5d7bcaee698e5354816bd3044e1156a60fede1eb985e768205788acfd62a28
# Code AST SHA-256:   eed8e0a093362f6b50e47e61258fff2fd9ef5192bf2f1d1248a33133963b3447
# Verified Classes:   WarrantContextViolation, Warrant, ToolResult
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from datetime import datetime, timezone


class WarrantContextViolation(RuntimeError):
    """Raised when a peer's reported execution context escapes the warrant closure."""
    pass


@dataclass(frozen=True)
class Warrant:
    id: str
    account_id: str
    valid_until: datetime
    allowed_nodes: frozenset[str]


@dataclass(frozen=True)
class ToolResult:
    status: str
    schema_version: str
    execution_context: dict
    payload: dict


def validate_result_against_warrant(result: ToolResult, warrant: Warrant) -> None:
    if result.status != "success":
        return

    ctx = result.execution_context

    if ctx.get("warrant_id") != warrant.id:
        raise WarrantContextViolation(
            f"warrant identity substitution: expected {warrant.id!r}, got {ctx.get('warrant_id')!r}"
        )

    if ctx.get("account_id") != warrant.account_id:
        raise WarrantContextViolation(
            f"account scope escape: expected {warrant.account_id!r}, got {ctx.get('account_id')!r}"
        )

    as_of_raw = ctx.get("as_of")
    if not as_of_raw:
        raise WarrantContextViolation("missing execution_context.as_of; cannot verify temporal closure")

    as_of = datetime.fromisoformat(as_of_raw.replace("Z", "+00:00"))
    if as_of.tzinfo is None:
        as_of = as_of.replace(tzinfo=timezone.utc)

    if as_of > warrant.valid_until:
        raise WarrantContextViolation(
            f"temporal closure violated: as_of={as_of.isoformat()} > valid_until={warrant.valid_until.isoformat()}"
        )

    node = ctx.get("execution_node")
    if warrant.allowed_nodes and node not in warrant.allowed_nodes:
        raise WarrantContextViolation(
            f"node binding escape: {node!r} not in {sorted(warrant.allowed_nodes)}"
        )
