# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-silent-task-orphaning-when-a2a-v1-0-agent-card-discovery-races-against-cross-framework-push-notification-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-silent-task-orphaning-when-a2a-v1-0-agent-card-discovery-races-against-cross-framework-push-notification-binding.warrant.json
# Markdown SHA-256:   873c69bac8e6e30a95e451d944085deb674092a095df9f54c2e69e6cd5d368a4
# Code AST SHA-256:   7cdd4ff3fe510ae91372b77779e78473d4814b88d80c49e3c1e4c5aa0a6898d5
# Verified Classes:   OrphanedTaskError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class OrphanedTaskError(RuntimeError):
    """Raised when a task's terminal state is not observable to its creator."""
    pass


def resolve_push_binding(card: dict, task: dict) -> str:
    """
    Resolve the delivery binding for an in-flight task.

    The binding MUST come from the task's negotiated token, not from the
    card's endpoint field. The card is advisory: it tells us push is
    supported and where to negotiate, not where to deliver.
    """
    binding = task.get("pushBinding")
    if not binding:
        raise OrphanedTaskError(
            f"task {task.get('taskId')} has no task-scoped push binding; "
            f"refusing to derive one from card version {card.get('version')} "
            f"because card generation may differ from submission generation"
        )
    if binding.get("cardVersionAtNegotiation") != task.get("cardVersionAtSubmission"):
        raise OrphanedTaskError(
            f"task {task.get('taskId')} binding negotiated under card version "
            f"{binding.get('cardVersionAtNegotiation')} but task submitted under "
            f"{task.get('cardVersionAtSubmission')}; delivery would be unobservable"
        )
    return binding["token"]


def deliver_terminal_state(card: dict, task: dict, state: str) -> None:
    token = resolve_push_binding(card, task)
    # Delivery uses the task-scoped token; card re-fetch cannot redirect it.
    _post(token, {"taskId": task["taskId"], "state": state})
