# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-task-has-silently-forked-terminal-state-divergence-between-the-caller-s-task-object-and-the-remote-agent.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-task-has-silently-forked-terminal-state-divergence-between-the-caller-s-task-object-and-the-remote-agent.warrant.json
# Markdown SHA-256:   341d619f4cf7897f4149bbb8d659868c41fd2cbd2400785b0e11aa84a4515108
# Code AST SHA-256:   c40b4eac4bb1fa10ad8d1b69887c473956cb9610180021aa70a7a2b21dd45bbc
# Verified Classes:   TaskState, SilentForkError, WriteProvenance, LocalTask, RemoteTask
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Literal


TERMINAL_STATES = frozenset({"completed", "failed", "canceled", "rejected"})


class TaskState(str, Enum):
    SUBMITTED = "submitted"
    WORKING = "working"
    INPUT_REQUIRED = "input-required"
    COMPLETED = "completed"
    FAILED = "failed"
    CANCELED = "canceled"
    REJECTED = "rejected"


class SilentForkError(RuntimeError):
    """Raised when caller-local and remote task state have forked undetected."""


@dataclass
class WriteProvenance:
    source: Literal["sse", "sync_response", "tasks_get", "caller_initiated"]
    timestamp_ms: int
    message_id: str | None = None


@dataclass
class LocalTask:
    task_id: str
    state: TaskState
    last_write: WriteProvenance
    pending_ack: bool = False
    artifacts_seen: set[str] = field(default_factory=set)


@dataclass
class RemoteTask:
    task_id: str
    state: TaskState
    dedup_window_s: int
    executed_message_ids: dict[str, list[int]]  # messageId -> [start_ms, ...]
    artifact_ids: list[str]


def assert_resend_safe(
    local: LocalTask,
    remote: RemoteTask,
    resend_horizon_s: int,
    now_ms: int,
) -> None:
    """
    Gate a tasks/resend. Raises SilentForkError if issuing the resend
    would risk re-executing an already-processed envelope against an
    advanced remote state.
    """
    # Invariant 1: terminal states are locally absorbing.
    if local.state in TERMINAL_STATES:
        if remote.state != local.state:
            raise SilentForkError(
                f"terminal divergence on {local.task_id}: "
                f"local={local.state.value} remote={remote.state.value}"
            )
        raise SilentForkError(
            f"refusing resend on terminal task {local.task_id}; "
            f"issue tasks/get to confirm instead"
        )

    # Invariant 2: do not resend over a stale synchronous write.
    if (
        local.last_write.source == "sync_response"
        and not local.pending_ack
    ):
        raise SilentForkError(
            f"resend on {local.task_id} would apply intent against "
            f"unknown-advanced state; last write was stale sync_response"
        )

    # Invariant 3: dedup horizon must strictly exceed resend horizon.
    if remote.dedup_window_s < resend_horizon_s:
        raise SilentForkError(
            f"dedup window {remote.dedup_window_s}s < resend horizon "
            f"{resend_horizon_s}s on {local.task_id}; replay becomes re-execution"
        )

    # Invariant 4: the envelope's messageId must not already be executing.
    mid = local.last_write.message_id
    if mid and mid in remote.executed_message_ids:
        starts = remote.executed_message_ids[mid]
        if len(starts) >= 1 and (now_ms - starts[-1]) > remote.dedup_window_s * 1000:
            raise SilentForkError(
                f"messageId {mid} already executed at {starts}; "
                f"dedup expired, resend would re-execute"
            )

    # Invariant 5: artifact cardinality must not have drifted.
    if len(remote.artifact_ids) > len(local.artifacts_seen):
        raise SilentForkError(
            f"artifact cardinality drift on {local.task_id}: "
            f"remote={len(remote.artifact_ids)} local={len(local.artifacts_seen)}"
        )
