# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-v1-0-agent-card-whose-push-notification-binding-changed-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-v1-0-agent-card-whose-push-notification-binding-changed-mid-task.warrant.json
# Markdown SHA-256:   3990526b11a2476fdc9251d550ebc710c468e2344b766abaf555ed4de4ac942a
# Code AST SHA-256:   8bd9abd773655280541a83368f600ed501491f1de1d350b349e881ae07e9a0b9
# Verified Classes:   PushBindingDriftError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class PushBindingDriftError(RuntimeError):
    """Raised when a card re-fetch would rebind an in-flight task's push channel."""
    pass


def resolve_push_binding(task_record: dict, current_card: dict) -> dict:
    """
    Return the push binding to use for a task. The binding is frozen at
    tasks/send time and stored on the task record. The current Agent Card
    is only a template for tasks that have not yet been accepted.
    """
    state = task_record["status"]["state"]
    pinned = task_record.get("pushBinding")
    card_pn = current_card.get("pushNotifications") or {}
    card_url = card_pn.get("url")
    card_schemes = tuple(sorted(card_pn.get("authentication", {}).get("schemes", [])))

    if state in ("submitted", "working", "input-required"):
        if pinned is None:
            raise PushBindingDriftError(
                f"task {task_record['id']} is {state} but has no pinned push binding; "
                "cannot safely derive one from a mutable card"
            )
        if card_url is not None and card_url != pinned["url"]:
            raise PushBindingDriftError(
                f"card pushNotifications.url rotated ({pinned['url']} -> {card_url}) "
                f"while task {task_record['id']} is {state}; refusing to rebind in-flight task"
            )
        if card_schemes and card_schemes != tuple(sorted(pinned["schemes"])):
            raise PushBindingDriftError(
                f"card auth schemes changed ({pinned['schemes']} -> {card_schemes}) "
                f"for in-flight task {task_record['id']}; binding is frozen at acceptance"
            )
        return pinned

    # No in-flight task: the card is a valid template for the next send.
    if card_url is None:
        raise PushBindingDriftError(
            f"card for task {task_record['id']} advertises no pushNotifications.url; "
            "cannot bind a new task"
        )
    return {"url": card_url, "schemes": list(card_schemes)}
