# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-terminal-completed-task-state-when-the-a2a-v1-0-push-notification-webhook-has-acknowledged-a-taskstatusupd.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-terminal-completed-task-state-when-the-a2a-v1-0-push-notification-webhook-has-acknowledged-a-taskstatusupd.warrant.json
# Markdown SHA-256:   05d312c886e71999353426c0c6d53a0c12a162298b7ba3ca6177dd35e89717f4
# Code AST SHA-256:   fc7c45b150d43861bbda769bba984889961f1d1ddda909c0f571683c42eb0ca5
# Verified Classes:   DivergentTaskState, StatusEvent, TaskSnapshot
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import dataclasses
from typing import Optional


class DivergentTaskState(RuntimeError):
    """Raised when an acknowledged webhook event log is not subsumed by the
    terminal Task object returned by tasks/get. Indicates the instance must
    reconcile before trusting the terminal state."""
    pass


@dataclasses.dataclass
class StatusEvent:
    event_id: str
    from_state: Optional[str]
    to_state: str
    final: bool
    artifact_ids: list


@dataclasses.dataclass
class TaskSnapshot:
    task_id: str
    state: str
    artifact_ids: list
    history_length: int


def reconcile(events: list, task: TaskSnapshot, *, recoverable_via_refetch: bool) -> str:
    """Return 'authoritative' or 'completed-with-unverified-provenance'.
    Raise DivergentTaskState when reconciliation cannot proceed safely."""
    if not events:
        raise DivergentTaskState(
            f"task {task.task_id}: no acknowledged webhook events; cannot "
            f"verify terminal state {task.state!r}"
        )

    last = events[-1]
    if not last.final:
        raise DivergentTaskState(
            f"task {task.task_id}: last acknowledged event {last.event_id} "
            f"is not final but task snapshot reads {task.state!r}"
        )
    if last.to_state != task.state:
        raise DivergentTaskState(
            f"task {task.task_id}: last event state {last.to_state!r} != "
            f"task snapshot state {task.state!r}"
        )

    for prev, nxt in zip(events, events[1:]):
        if nxt.from_state != prev.to_state:
            raise DivergentTaskState(
                f"task {task.task_id}: event graph gap between "
                f"{prev.event_id} ({prev.to_state!r}) and "
                f"{nxt.event_id} ({nxt.from_state!r})"
            )

    event_artifacts = {a for e in events for a in e.artifact_ids}
    missing = event_artifacts - set(task.artifact_ids)
    if missing:
        if recoverable_via_refetch:
            raise DivergentTaskState(
                f"task {task.task_id}: artifacts {sorted(missing)} referenced "
                f"by events are absent from snapshot; refetch with higher "
                f"historyLength before accepting terminal state"
            )
        return "completed-with-unverified-provenance"

    if task.history_length < len(events):
        # Legal truncation: events acknowledged but history bounded below
        # the event count. Not a protocol violation, but the snapshot does
        # not subsume the event log; flag provenance.
        return "completed-with-unverified-provenance"

    return "authoritative"


def accept_terminal(events: list, task: TaskSnapshot, *, refetch_fn) -> str:
    """Top-level gate. Retries refetch once on recoverable divergence, then
    escalates. Must be called BEFORE any retry/dispatch logic."""
    try:
        return reconcile(events, task, recoverable_via_refetch=True)
    except DivergentTaskState as first:
        try:
            task = refetch_fn(task.task_id)
        except Exception as e:
            raise DivergentTaskState(
                f"task {task.task_id}: refetch failed after divergence "
                f"({first}); cannot establish provenance"
            ) from e
        return reconcile(events, task, recoverable_via_refetch=False)
