# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-advertises-a-webhook-capability-in-its-agent-card-but-the-receiver-never-acknowledges-the-task-state-transition.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-advertises-a-webhook-capability-in-its-agent-card-but-the-receiver-never-acknowledges-the-task-state-transition.warrant.json
# Markdown SHA-256:   6694501bd4b735f6ca15750b738a496804a3450063c1beaaa7da84e2112b3ba4
# Code AST SHA-256:   baf02c2c5c52786d66671f6e1037dcb39d33eac44ebf66fff66cb262ae3aba6f
# Verified Classes:   TaskReconciliationError, TaskReplica
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field


class TaskReconciliationError(RuntimeError):
    """Raised when a client's task replica cannot be reconciled with the executor."""


@dataclass
class TaskReplica:
    task_id: str
    local_state: str = "working"
    last_webhook_at: float | None = None
    last_poll_at: float | None = None
    delegation_timeout_s: float = 900.0
    poll_interval_s: float = 60.0


def reconcile(
    replica: TaskReplica,
    fetch_task_state,          # callable(task_id) -> str, hits tasks/get
    now: float | None = None,
) -> str:
    """Enforce the invariant: push is a hint, poll is the truth.

    A webhook payload may only *trigger* a reconciliation; it may never
    itself commit a terminal state to the replica.
    """
    now = now if now is not None else time.monotonic()

    # Invariant 1: poll cadence must be strictly tighter than delegation timeout.
    if replica.poll_interval_s * 3 >= replica.delegation_timeout_s:
        raise TaskReconciliationError(
            f"poll_interval={replica.poll_interval_s}s is not < "
            f"delegation_timeout/3={replica.delegation_timeout_s/3}s; "
            "push-only trust would allow zombie delegation"
        )

    # Invariant 2: never trust an unconfirmed webhook as a state commit.
    if replica.last_webhook_at is not None and replica.last_poll_at is None:
        # webhook arrived but we never verified against tasks/get
        authoritative = fetch_task_state(replica.task_id)
        replica.last_poll_at = now
        if authoritative != replica.local_state:
            replica.local_state = authoritative
        return replica.local_state

    # Invariant 3: if no webhook and poll is overdue, poll anyway.
    overdue = (
        replica.last_poll_at is None
        or (now - replica.last_poll_at) > replica.poll_interval_s
    )
    if overdue:
        authoritative = fetch_task_state(replica.task_id)
        replica.last_poll_at = now
        if authoritative in ("completed", "failed", "canceled"):
            replica.local_state = authoritative
            return replica.local_state

    # Invariant 4: a replica stuck in 'working' past delegation timeout
    # while the executor reports terminal is a reconciliation failure,
    # not a cancelable task. Do NOT issue tasks/cancel.
    if (
        replica.local_state == "working"
        and replica.last_poll_at is not None
        and (now - replica.last_poll_at) > replica.delegation_timeout_s
    ):
        authoritative = fetch_task_state(replica.task_id)
        if authoritative in ("completed", "failed", "canceled"):
            replica.local_state = authoritative
            raise TaskReconciliationError(
                f"task {replica.task_id} was terminal ({authoritative}) on executor "
                "while replica held 'working'; webhook delivery was lost. "
                "Do not cancel — reconcile and adopt executor state."
            )

    return replica.local_state
