# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-push-notification-rebinding-from-resurrecting-a-terminal-a2a-task-after-agent-card-re-discovery.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-push-notification-rebinding-from-resurrecting-a-terminal-a2a-task-after-agent-card-re-discovery.warrant.json
# Markdown SHA-256:   bbac2b70a21c4353ae5087db1ca1f687fc0a4dcfa38d96f5a60c226f00339c39
# Code AST SHA-256:   677ae06eb702d1b4aed923db3bdd0fc1646ce7af3e4a52b6cb72f00bfe965a5d
# Verified Classes:   TerminalTaskRebindError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class TerminalTaskRebindError(RuntimeError):
    """Raised when a push binding is created/rebound for a terminal A2A task."""
    pass


TERMINAL_STATES = frozenset({"completed", "failed", "canceled"})
NON_TERMINAL_STATES = frozenset({"submitted", "working", "input-required"})


def bind_push_channel(task_state: str, existing_bindings: dict, task_id: str, webhook_url: str) -> dict:
    """
    Enforce the invariant: no binding mutation for a terminal task, regardless
    of whether the webhook URL is novel. Returns updated bindings or raises.
    """
    if task_state in TERMINAL_STATES:
        # Novel URL does NOT authorize a rebind; terminal is sealed.
        raise TerminalTaskRebindError(
            f"task {task_id} is terminal ({task_state}); "
            f"refusing to bind {webhook_url} — replay must be deduped on eventId"
        )
    if task_state not in NON_TERMINAL_STATES:
        raise TerminalTaskRebindError(
            f"task {task_id} has unknown state {task_state!r}; "
            f"reconcile via tasks/get before binding"
        )
    existing_bindings[(task_id, webhook_url)] = {"sealed": False}
    return existing_bindings


def on_agent_card_refresh(task_state: str, task_id: str, card_capabilities: dict) -> str:
    """
    Card refresh is authorization-scope only. It must never create a binding.
    Returns the permitted action for the caller to apply.
    """
    if not card_capabilities.get("pushNotifications", False):
        return "revoke_binding"
    if task_state in TERMINAL_STATES:
        # Capability is true, but the task is sealed: no binding action.
        return "noop_terminal"
    if task_state in NON_TERMINAL_STATES:
        return "validate_existing_binding"
    raise TerminalTaskRebindError(
        f"card refresh for task {task_id} with unknown state {task_state!r}; "
        f"cannot decide binding action"
    )
