# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-terminal-state-divergence-in-a2a-v1-0-task-lifecycles-when-agent-card-capability-negotiation-succeeds-but-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-terminal-state-divergence-in-a2a-v1-0-task-lifecycles-when-agent-card-capability-negotiation-succeeds-but-execution.warrant.json
# Markdown SHA-256:   fa8f3c456a31db8e2f9853876689a7c53681626901cd0029c681bd08dc4c65a5
# Code AST SHA-256:   7600c28f2df2bd0ed9e53a939649ec8102bfe30e29aaeee777f0bb11b189c3f3
# Verified Classes:   CardRevisionDivergenceError, LifecycleForkError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class CardRevisionDivergenceError(RuntimeError):
    """Raised when a task-scoped write targets a card revision other than the one negotiated."""
    pass


class LifecycleForkError(RuntimeError):
    """Raised when a resumption response mints a task id differing from the original."""
    pass


def dispatch_resumption(
    negotiated_card_etag: str,
    live_card_etag: str,
    original_task_id: str,
    resumption_response: dict,
    handler_locked: bool,
) -> dict:
    if not handler_locked:
        # The stream handler and the write path must share a task-id mutex;
        # otherwise a terminal event can race the resumption write.
        raise CardRevisionDivergenceError(
            f"resumption for task {original_task_id} not serialized against "
            f"TaskStatusUpdateEvent handler; fork window open"
        )

    if negotiated_card_etag != live_card_etag:
        # Card hot-swapped between discovery and dispatch; terminal-state
        # semantics are no longer provably the ones we negotiated.
        raise CardRevisionDivergenceError(
            f"task {original_task_id}: negotiated card etag {negotiated_card_etag!r} "
            f"!= live {live_card_etag!r}; input-required resumability unverified"
        )

    returned_id = resumption_response.get("task", {}).get("id")
    if returned_id != original_task_id:
        # Remote minted a new task on an unknown reference; duplicate side
        # effects are now in flight under two ids.
        raise LifecycleForkError(
            f"resumption of {original_task_id} returned task id {returned_id!r}; "
            f"lifecycle forked, reconcile before retry"
        )

    return resumption_response
