# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-agent-card-discovery-mismatch-that-silently-renegotiates-task-lifecycle-semantics-across-vendors.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-an-a2a-v1-0-agent-card-discovery-mismatch-that-silently-renegotiates-task-lifecycle-semantics-across-vendors.warrant.json
# Markdown SHA-256:   a88c38308491fec8c888332579345678626eaa30e904bbfcce0677bdf462c1b3
# Code AST SHA-256:   877cb1e568b46151424c8d9ee5dd9c595f737352dd4e281600af86cde4b617ba
# Verified Classes:   LifecycleRenegotiationError, TaskRef
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class LifecycleRenegotiationError(RuntimeError):
    """Raised when a remote agent silently substitutes a new Task.id/contextId
    during what the client believes is a resumption of an existing task."""


@dataclass(frozen=True)
class TaskRef:
    task_id: str
    context_id: str


def reconcile_task_response(
    request_ref: TaskRef | None,
    response_task: dict,
    remote_supports_history: bool,
) -> TaskRef:
    """Enforce the cross-vendor A2A lifecycle continuity invariant.

    Called on every response to a task-mutating call (message/send with taskId).
    Returns the TaskRef the client should continue tracking.
    """
    response_ref = TaskRef(
        task_id=response_task["id"],
        context_id=response_task.get("contextId", ""),
    )
    state = response_task.get("status", {}).get("state")

    # First turn: no prior task, adopt the response's identity.
    if request_ref is None:
        return response_ref

    # Resumption attempt: identity MUST be preserved unless the remote
    # explicitly signals a terminal state or an error.
    if response_ref.task_id != request_ref.task_id:
        if state in ("completed", "failed", "canceled"):
            # Honest terminal transition on a different id is still suspicious;
            # require explicit history support to accept it.
            if not remote_supports_history:
                raise LifecycleRenegotiationError(
                    f"remote closed task {request_ref.task_id} and returned "
                    f"terminal task {response_ref.task_id} without state history; "
                    "cannot verify the transition was intentional"
                )
            return response_ref
        # Non-terminal state on a substituted id == silent renegotiation.
        raise LifecycleRenegotiationError(
            f"silent task substitution: sent taskId={request_ref.task_id}, "
            f"received id={response_ref.task_id} in state={state!r}; "
            "remote likely treats input-required as terminal handoff"
        )

    if response_ref.context_id and response_ref.context_id != request_ref.context_id:
        raise LifecycleRenegotiationError(
            f"contextId drift on task {request_ref.task_id}: "
            f"expected {request_ref.context_id}, got {response_ref.context_id}"
        )

    return response_ref
