# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a2a-v1-0-delegated-task-orphaning-when-a-remote-agent-s-card-advertised-defaultinputmodes-defaultoutputmodes-diverge-from-the.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a2a-v1-0-delegated-task-orphaning-when-a-remote-agent-s-card-advertised-defaultinputmodes-defaultoutputmodes-diverge-from-the.warrant.json
# Markdown SHA-256:   6fa7817d21b2423e13f6e44d562cc139f2d077bc045f53bb1ec1426712792308
# Code AST SHA-256:   4754173a64d2f96b55a812f3f8be8a9948cebdcab81016dd2ced6befcff38c06
# Verified Classes:   TaskIdentityDivergence
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class TaskIdentityDivergence(RuntimeError):
    """Raised when a remote agent's taskId remap or state-graph divergence
    would orphan a delegated task under A2A v1.0."""
    pass


TERMINAL_STATES = {"completed", "failed", "canceled"}
# States we treat as potentially terminal unless proven resumable by probe/extension.
AMBIGUOUS_TERMINAL = {"input-required", "auth-required"}


def reconcile_send_response(
    requested_task_id: str,
    response: dict,
    prior_state: str,
    identity_stability_proven: bool,
) -> str:
    """
    Enforce the reconciliation invariant on every tasks/send response.
    Returns the taskId the local FSM should now track.
    Raises TaskIdentityDivergence if the remote silently remapped and we
    cannot safely reclaim, or if an ambiguous-terminal state was resumed
    without proof of taskId stability.
    """
    returned_id = response.get("taskId")
    if returned_id is None:
        raise TaskIdentityDivergence(
            f"tasks/send for {requested_task_id} returned no taskId; "
            "cannot bind FSM — treat as protocol violation."
        )

    if returned_id != requested_task_id:
        # Remote remapped. The prior task may still be live and orphaned.
        # Caller MUST issue tasks/cancel{requested_task_id} best-effort.
        if prior_state in TERMINAL_STATES:
            # Prior was already terminal locally; remap is a fresh delegation.
            return returned_id
        raise TaskIdentityDivergence(
            f"Remote remapped {requested_task_id} -> {returned_id} while "
            f"prior_state={prior_state!r} was non-terminal. Prior task is a "
            "candidate orphan; cancel it before rebinding."
        )

    # Same id. Now check the ambiguous-terminal resume case.
    if prior_state in AMBIGUOUS_TERMINAL and response.get("state") == "working":
        if not identity_stability_proven:
            raise TaskIdentityDivergence(
                f"Resumed {requested_task_id} from {prior_state!r} to working "
                "without positive evidence of taskId stability. Remote may have "
                "deallocated context and be silently starting a fresh task under "
                "a stable id; probe or re-delegate instead."
            )

    return returned_id


def delegate_with_reconciliation(
    client,
    card: dict,
    message: dict,
    probe_first: bool = True,
) -> str:
    """
    Drive one delegated task, enforcing identity reconciliation at each hop.
    """
    identity_stability_proven = bool(card.get("x-task-semantics", {}).get("taskIdStable"))
    if probe_first and not identity_stability_proven:
        # Cheap probe: short task that forces input-required, observe remap.
        identity_stability_proven = _probe_task_id_stability(client, card)

    task_id = client.send(message)["taskId"]
    prior_state = "submitted"

    while True:
        status = client.get(task_id)
        state = status["state"]
        if state in TERMINAL_STATES:
            return task_id
        if state in AMBIGUOUS_TERMINAL:
            answer = client.collect_user_input(task_id)
            resp = client.send(message=answer, task_id=task_id)
            try:
                task_id = reconcile_send_response(
                    requested_task_id=task_id,
                    response=resp,
                    prior_state=prior_state,
                    identity_stability_proven=identity_stability_proven,
                )
            except TaskIdentityDivergence:
                # Best-effort reclaim of the orphan before propagating.
                client.cancel(task_id)
                raise
        prior_state = state


def _probe_task_id_stability(client, card: dict) -> bool:
    """Issue a task engineered to hit input-required, then resume; observe remap."""
    probe = client.send({"role": "user", "parts": [{"kind": "text", "text": "PROBE: request one input"}]})
    pid = probe["taskId"]
    st = client.get(pid)
    if st["state"] != "input-required":
        # Card advertised resumability but probe never reached it; be conservative.
        return False
    resp = client.send(message={"role": "user", "parts": [{"kind": "text", "text": "go"}]}, task_id=pid)
    return resp.get("taskId") == pid
