# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-task-state-divergence-between-a-delegating-agent-s-local-projection-and-the-remote-agent-s-authoritative.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-task-state-divergence-between-a-delegating-agent-s-local-projection-and-the-remote-agent-s-authoritative.warrant.json
# Markdown SHA-256:   9f510d62bd20f255e654d126c34d5921eeb16149ec0663927090f46f0c55039e
# Code AST SHA-256:   bb049bfe7e163592a9cc5021ba27fb9c0ff0f21badb7bf820c8cfd1b73c8db59
# Verified Classes:   TaskProjectionDivergence, TaskProjection
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class TaskProjectionDivergence(RuntimeError):
    """Raised when the client's local task projection has skipped a state
    transition present in the server's authoritative history. This is the
    A2A v1.0 input-required gap: the client believes the task is `working`
    while the server is blocked in `input-required` awaiting a follow-up."""
    pass


@dataclass
class TaskProjection:
    task_id: str
    context_id: str
    state: str
    history_tail: str          # canonical hash of the last history entry
    last_seq: int = 0
    pending_user_input: bool = False


def _history_tail_hash(history: list[dict]) -> str:
    if not history:
        return ""
    last = history[-1]
    # Canonicalize only the fields that define the terminal event.
    canon = f"{last.get('role','')}|{last.get('state','')}|{last.get('timestamp','')}"
    return hashlib.sha256(canon.encode()).hexdigest()[:16]


def reconcile(
    local: TaskProjection,
    remote_task: dict,
    server_supports_replay_from_origin: bool,
) -> TaskProjection:
    remote_history = remote_task.get("history", [])
    remote_tail = _history_tail_hash(remote_history)
    remote_state = remote_task["status"]["state"]

    # Structural signal #1: history-tail divergence. The state field may
    # agree (both 'working') while the histories disagree, which is the
    # signature of a skipped input-required event during a disconnect.
    if remote_tail and remote_tail != local.history_tail:
        if remote_state == "input-required" and local.state == "working":
            if not local.pending_user_input:
                raise TaskProjectionDivergence(
                    f"task {local.task_id}: client projected 'working' but "
                    f"server is authoritative 'input-required' (history tail "
                    f"{local.history_tail!r} -> {remote_tail!r}); delegation "
                    f"deadlocked, re-delegate with explicit input handler"
                )
        # Any other tail divergence is a benign lag; adopt remote truth.
        local.history_tail = remote_tail
        local.state = remote_state

    # Structural signal #2: sequence gap at the envelope level.
    remote_seq = remote_task.get("status", {}).get("seq", local.last_seq)
    if remote_seq > local.last_seq + 1 and not server_supports_replay_from_origin:
        # We cannot trust the projection; force a full history adoption.
        local.history_tail = remote_tail
        local.state = remote_state
        local.last_seq = remote_seq

    # Structural signal #3: context bleed.
    if remote_task.get("contextId") and remote_task["contextId"] != local.context_id:
        raise TaskProjectionDivergence(
            f"task {local.task_id}: contextId mismatch "
            f"{local.context_id!r} != {remote_task['contextId']!r}"
        )

    local.last_seq = max(local.last_seq, remote_seq)
    return local
