# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-silently-revoked-a2a-push-notification-binding-when-the-peer-s-task-lifecycle-continues-to-advance.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-silently-revoked-a2a-push-notification-binding-when-the-peer-s-task-lifecycle-continues-to-advance.warrant.json
# Markdown SHA-256:   a2298ab295c4ffb946a3955530ac03e4b834b55e51d3ac6830979e2606a5e62e
# Code AST SHA-256:   4657f79ca1ac615ce4845d41d1ed64bb44724b2f69dae3c0542904bd62ccf311
# Verified Classes:   LifecycleState, PushBindingPresumedDead, TaskView
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from enum import IntEnum


class LifecycleState(IntEnum):
    SUBMITTED = 0
    WORKING = 1
    COMPLETED = 2
    FAILED = 3
    CANCELED = 4

    @property
    def terminal(self) -> bool:
        return self in (LifecycleState.COMPLETED,
                        LifecycleState.FAILED,
                        LifecycleState.CANCELED)


class PushBindingPresumedDead(RuntimeError):
    """Raised when silence + independent state divergence proves the
    A2A push-notification binding is no longer delivering, while the
    task itself continues to advance on the server side."""


@dataclass
class TaskView:
    task_id: str
    last_known_state: LifecycleState
    last_event_at: float          # monotonic seconds, webhook receipt
    declared_cadence_s: float     # server-declared expected event interval


def reconcile(
    view: TaskView,
    probe_state: LifecycleState,
    now: float,
    cadence_slack: float = 3.0,
) -> LifecycleState:
    """Called on a cadence. Returns the state the client should adopt.

    Invariant: local state advances only on confirmed sources. Silence
    alone never advances state; it only triggers a probe whose result
    may advance it. If the probe shows advancement the client has not
    seen via webhook, the binding is dead and pull-supervision must
    take over.
    """
    if probe_state < view.last_known_state:
        # Replica lag: never regress local monotonic state.
        return view.last_known_state

    silence = now - view.last_event_at
    silence_threshold = view.declared_cadence_s * cadence_slack

    if silence > silence_threshold and probe_state > view.last_known_state:
        raise PushBindingPresumedDead(
            f"task {view.task_id}: binding silent {silence:.1f}s "
            f"(threshold {silence_threshold:.1f}s) while server state "
            f"advanced {view.last_known_state.name} -> {probe_state.name}; "
            f"switch to pull-based supervision"
        )

    if probe_state.terminal and probe_state > view.last_known_state:
        # Terminal transition observed via probe; adopt it and stop
        # expecting webhooks for this task.
        return probe_state

    return view.last_known_state
