# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-task-it-cannot-resume-the-input-required-working-resurrection-gap-in-a2a-v1-0-task-lifecycle-handshakes.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-task-it-cannot-resume-the-input-required-working-resurrection-gap-in-a2a-v1-0-task-lifecycle-handshakes.warrant.json
# Markdown SHA-256:   8ef1b6bde9e661f422bc1bc933f77cc3cdd756cad8422efe09c37298ff5ca7b4
# Code AST SHA-256:   150bf4c3b0f0dc039ffd486260fa9c74a1c8f7fe54babcc5be68db19be1b422c
# Verified Classes:   ContinuityGapError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ContinuityGapError(RuntimeError):
    """Raised when an A2A resume transitions to 'working' without echoing
    the client's continuityToken, indicating the remote rehydrated from a
    stale checkpoint (or from nothing) rather than continuing execution."""


def resume_task(
    remote_resume_fn,
    task_id: str,
    context_id: str,
    continuity_token: str,
    message_parts: list,
    max_gather_latency_s: float,
    observed_gather_latency_s: float,
) -> dict:
    # Guard 1: gather latency vs. the shortest plausible remote suspension TTL.
    # We cannot read the TTL from the AgentCard; 30s is the empirical floor for
    # hosted runtimes. Beyond it we must not assume continuation.
    if observed_gather_latency_s > max_gather_latency_s:
        raise ContinuityGapError(
            f"gather latency {observed_gather_latency_s:.1f}s exceeds "
            f"continuity budget {max_gather_latency_s:.1f}s for task {task_id}; "
            f"remote execution context may have been evicted"
        )

    task = remote_resume_fn(
        taskId=task_id,
        contextId=context_id,
        message={"role": "user", "parts": message_parts,
                 "metadata": {"continuityToken": continuity_token}},
    )

    # Guard 2: the resume must land in 'working' *and* echo the token.
    state = task.get("status", {}).get("state")
    echoed = (
        task.get("status", {})
        .get("message", {})
        .get("metadata", {})
        .get("continuityToken")
    )
    if state == "working" and echoed != continuity_token:
        # Remote accepted the resume but did not prove it retained context.
        # Treat as fresh execution: quarantine, do not trust the result.
        raise ContinuityGapError(
            f"task {task_id} resumed to 'working' without continuity token "
            f"(echoed={echoed!r}); remote likely rehydrated a stale checkpoint "
            f"and may replay non-idempotent tool calls"
        )

    # Guard 3: a canceled task must never resurrect to 'working'.
    if task.get("status", {}).get("state") == "working" and task.get("canceledAt"):
        raise ContinuityGapError(
            f"task {task_id} transitioned canceled -> working; "
            f"resume raced a cancel and the remote violated terminality"
        )

    return task
