# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reject-a-peer-s-agent-card-when-supportedinterfaces-protocolversion-is-a-range-expression-rather-than-a-pinned-version-the-a2a.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reject-a-peer-s-agent-card-when-supportedinterfaces-protocolversion-is-a-range-expression-rather-than-a-pinned-version-the-a2a.warrant.json
# Markdown SHA-256:   ca170477968757f9bae43ca44d0059729711e730c463ee22a1f3d35a3435dbcb
# Code AST SHA-256:   3a9b90b513c34caa5f0b900fc749ddcb2328918b3130feebe91649ff0dbfcccc
# Verified Classes:   DialectMismatchError, SplitBrainCompletionError, TaskReducer
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import re
from dataclasses import dataclass

class DialectMismatchError(RuntimeError):
    """Raised when a task cannot be pinned to a single frame dialect."""
    pass

class SplitBrainCompletionError(RuntimeError):
    """Raised when local terminal state contradicts peer terminal state."""
    pass

# Versions whose artifact-update frames carry a `final` boolean.
FINAL_FLAG_VERSIONS = {(1, 0), (1, 1)}

def _parse(v: str):
    m = re.fullmatch(r"(\d+)\.(\d+)(?:\.\d+)?", v.strip())
    if not m:
        return None
    return (int(m.group(1)), int(m.group(2)))

def _satisfies(client: tuple, expr: str) -> bool:
    # Minimal range check: ">=A <B", "^A", "A.x", or exact.
    expr = expr.strip()
    if expr.startswith("^"):
        base = _parse(expr[1:])
        if base is None:
            return False
        return client[0] == base[0] and client >= base
    if ".x" in expr:
        base = _parse(expr.replace(".x", ".0"))
        return base is not None and client[0] == base[0]
    if ">=" in expr and "<" in expr:
        lo = _parse(expr.split(">=")[1].split("<")[0])
        hi = _parse(expr.split("<")[1])
        return lo is not None and hi is not None and lo <= client < hi
    exact = _parse(expr)
    return exact == client

def pin_dialect(client_version: str, card_interfaces: list[dict],
                client_implements: set[tuple]) -> tuple:
    """
    Select a single dialect for the task. Refuse to proceed if the only
    satisfiable interfaces are range-valued and unpinnable.
    """
    client = _parse(client_version)
    if client is None:
        raise DialectMismatchError(f"unparseable client version {client_version!r}")

    candidates = []
    for iface in card_interfaces:
        expr = iface.get("protocolVersion", "")
        if _satisfies(client, expr):
            candidates.append((iface, expr))

    if not candidates:
        raise DialectMismatchError("no interface satisfies client version")

    # Prefer an explicitly pinnable interface.
    for iface, expr in candidates:
        if iface.get("selection") == "client-pinned" and _parse(expr) in client_implements:
            return _parse(expr)

    # Otherwise, pick the highest dialect in the range that we implement,
    # and configure the reducer for THAT dialect, not our native one.
    best = None
    for iface, expr in candidates:
        for ver in client_implements:
            if _satisfies(ver, expr) and (best is None or ver > best):
                best = ver
    if best is None:
        raise DialectMismatchError(
            f"range {expr!r} admits no dialect this client implements"
        )
    return best

@dataclass
class TaskReducer:
    dialect: tuple
    saw_final: bool = False
    terminal: str | None = None

    def on_artifact_update(self, frame: dict):
        if "final" in frame:
            self.saw_final = bool(frame["final"])
        # v0.2 dialect: no `final` key; do not treat absence as truncation.

    def on_status(self, frame: dict):
        state = frame.get("status", {}).get("state")
        if state in ("completed", "failed", "canceled"):
            # Positive terminal predicate: status is authoritative.
            if self.dialect in FINAL_FLAG_VERSIONS and not self.saw_final:
                # Warning only; do not suppress terminal transition.
                frame.setdefault("warnings", []).append("no_final_marker")
            self.terminal = state

    def require_agreement(self, peer_status: str):
        if self.terminal is None:
            raise SplitBrainCompletionError("local task has no terminal state")
        if self.terminal != peer_status:
            raise SplitBrainCompletionError(
                f"local={self.terminal} peer={peer_status}: dialect divergence"
            )
