Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

70.4 KB
Raw Blame
from __future__ import annotations

import contextlib
import errno
import json
import logging
import os
import re
import shlex
import shutil
import subprocess
import sys
import tempfile
import time
import urllib.parse
import urllib.request
from collections.abc import Callable, Mapping
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import cast
from uuid import uuid4

from packaging.utils import canonicalize_name

from vibe.package_shape import CORE_PACKAGE_NAME, LEGACY_CORE_PACKAGE_NAME

from config import paths as config_paths
from core.caller_context import environment_without_caller_context
from core.install_integrity import (
    IntegrityResult,
    isolated_probe_environment,
    run_isolated_probe,
    verify_python_environment,
)
from core.windows_arch import WINDOWS_ARM64_UV_PYTHON, windows_native_arm64
from storage.lock import MigrationFileLock
from vibe import runtime as runtime_mod


logger = logging.getLogger(__name__)

PACKAGE_NAME = CORE_PACKAGE_NAME
LEGACY_PACKAGE_NAME = LEGACY_CORE_PACKAGE_NAME
PIP_DOWNLOAD_DEST_PLACEHOLDER = "{avibe-pip-download-destination}"
DEFAULT_UPDATE_METADATA_URL = f"https://pypi.org/pypi/{PACKAGE_NAME}/json"
CURRENT_VIBE_EXECUTABLE_ENV = "VIBE_CURRENT_EXECUTABLE"
SHOW_RUNTIME_SKIP_ENV = "VIBE_INSTALL_SKIP_SHOW_RUNTIME"
DESKTOP_MANAGED_RUNTIME_ENV = "AVIBE_DESKTOP_MANAGED_RUNTIME"
TRUTHY_ENV_VALUES = {"1", "true", "yes", "on"}
UV_FALLBACK_BIN_DIRS = (".local/bin", ".cargo/bin")
# The fixed stable-launcher locations install.sh and install.ps1 choose from,
# in addition to PATH and uv's configured tool bin. Discovery checks these
# names; it never scans the filesystem.
INSTALLER_LAUNCHER_DIRS = ("~/.local/bin", "~/bin", "/usr/local/bin", "/opt/homebrew/bin")
UPGRADE_INSTALL_TIMEOUT_SECONDS = 30 * 60
# A slow interpreter download may finish; a hung one must not take the whole
# install bound from the Avibe install that follows it.
PYTHON_PATCH_UPGRADE_TIMEOUT_SECONDS = 10 * 60
UV_PYTHON_DIR_TIMEOUT_SECONDS = 30
RESTART_PENDING_GRACE_SECONDS = 5 * 60
DEFERRED_ACTIVATION_TIMEOUT_SECONDS = 5 * 60
# A CPython installation in uv's Python directory, named by its uv install key:
# a patch such as ``cpython-3.12.12-macos-aarch64-none`` or uv's minor-version
# link ``cpython-3.12-macos-aarch64-none``. Variant builds (freethreaded, debug)
# carry a ``+`` and are deliberately not matched.
_UV_MANAGED_CPYTHON_DIR_RE = re.compile(
    r"cpython-(?P<minor>\d+\.\d+)(?:\.\d+(?:(?:a|b|rc)\d+)?)?"
    r"-(?P<platform>[a-z0-9_]+-[a-z0-9_]+-[a-z0-9_]+)"
)
# A spec that names nothing but a package, so appending ``==<version>`` to it
# yields a requirement rather than a broken string. PEP 508 names only:
# anything with a path separator, a URL scheme, extras, a marker, or a version
# of its own is deliberately excluded. See `pinned_package_spec`.
_BARE_PACKAGE_NAME_RE = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?")
# PEP 440-ish parser: release + optional pre-release (a/b/rc) + optional
# post + optional dev, plus a local version segment (``+local``) that we
# accept but ignore for ordering. Word forms (alpha/beta/preview) are listed
# before their single-letter aliases so the alternation does not match a bare
# leading letter (e.g. the "a" in "alpha").
_VERSION_RE = re.compile(
    r"^\s*v?(?P<release>\d+(?:\.\d+)*)"
    r"(?:[._-]?(?P<pre>alpha|beta|preview|pre|rc|a|b|c)[._-]?(?P<pre_num>\d+)?)?"
    r"(?:[._-]?(?P<post>post)[._-]?(?P<post_num>\d+)?)?"
    r"(?:[._-]?(?P<dev>dev)[._-]?(?P<dev_num>\d+)?)?"
    r"(?:\+(?P<local>[a-z0-9._-]+))?\s*$",
    re.IGNORECASE,
)
# Relative ordering of pre-release stages: a/alpha < b/beta < c/rc/pre/preview.
_PRE_ORDER = {
    "a": 0,
    "alpha": 0,
    "b": 1,
    "beta": 1,
    "c": 2,
    "rc": 2,
    "pre": 2,
    "preview": 2,
}


class RestartState(str, Enum):
    """Closed restart-state vocabulary and its retention policy."""

    def __new__(cls, value: str, retention: str | None):
        member = str.__new__(cls, value)
        member._value_ = value
        member.retention = retention
        return member

    SCHEDULED = ("scheduled", "seed")
    RUNNING = ("running", "seed")
    SUCCEEDED = ("succeeded", "result")
    FAILED = ("failed", "result")
    ERROR = ("error", "result")
    CANCELLED = ("cancelled", "result")
    SKIPPED = ("skipped", "result")
    UNKNOWN = ("unknown", None)


@dataclass(frozen=True)
class UpgradePlan:
    """A validated package-install command and its execution metadata."""

    command: list[str]
    env: dict[str, str] | None
    method: str
    preflight_command: list[str] | None = None
    preflight_fallback_command: list[str] | None = None
    activation: "AtomicActivation | None" = None
    preflight_error: str | None = None
    python_upgrade_command: list[str] | None = None


def execute_upgrade_plan(
    plan: UpgradePlan,
    *,
    run: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
    **run_kwargs: object,
) -> subprocess.CompletedProcess[str]:
    """Run a validated plan after its non-mutating preflight.

    The caller owns package mutation sequencing. This helper deliberately does
    not acquire a lifecycle lock: callers can run the plan synchronously while
    the existing restart supervisor owns any later activation.
    """

    if plan.preflight_error:
        raise ValueError(plan.preflight_error)
    preflight = preflight_upgrade_plan(plan, run=run, **run_kwargs)
    if preflight is not None:
        if preflight.returncode != 0:
            return preflight

    if plan.python_upgrade_command is not None:
        _upgrade_python_patch(plan.python_upgrade_command, env=plan.env, run=run, **run_kwargs)

    if plan.activation is not None:
        from vibe.install_generations import mark_install_generation

        mark_install_generation(plan.activation.candidate_launcher, os.getpid())
    return run(plan.command, env=plan.env, **run_kwargs)


def _upgrade_python_patch(
    command: list[str],
    *,
    env: dict[str, str] | None,
    run: Callable[..., subprocess.CompletedProcess[str]],
    **run_kwargs: object,
) -> None:
    """Move the interpreter's minor version to its newest patch, best effort.

    uv never moves an installed Python to a newer patch by itself, so without
    this a tool environment keeps the CPython and OpenSSL it was created with.
    The staged install that follows selects the newest installed patch. An
    older uv without ``python install --upgrade``, an offline machine, or a
    failed download leaves the installed patch in use and the upgrade goes on.
    """

    try:
        result = run(command, env=env, **{**run_kwargs, "timeout": PYTHON_PATCH_UPGRADE_TIMEOUT_SECONDS})
    except (OSError, subprocess.SubprocessError) as exc:
        logger.warning("Keeping the installed Python patch: %s failed: %s", shlex.join(command), exc)
        return
    output = "\n".join(part.strip() for part in (result.stdout, result.stderr) if part and part.strip())
    if result.returncode != 0:
        logger.warning(
            "Keeping the installed Python patch (a newer one needs uv 0.9.10 or later and network access): "
            "%s exited %s: %s",
            shlex.join(command),
            result.returncode,
            output,
        )
        return
    logger.info("Python patch check: %s", output or "done")


def preflight_upgrade_plan(
    plan: UpgradePlan,
    *,
    run: Callable[..., subprocess.CompletedProcess[str]] = subprocess.run,
    **run_kwargs: object,
) -> subprocess.CompletedProcess[str] | None:
    """Resolve a plan without mutating the environment."""

    if plan.preflight_command is None:
        return None

    def run_preflight(command: list[str]) -> subprocess.CompletedProcess[str]:
        scratch_dir: str | None = None
        try:
            if PIP_DOWNLOAD_DEST_PLACEHOLDER in command:
                scratch_dir = tempfile.mkdtemp(prefix="avibe-pip-download-")
                command = [
                    scratch_dir if argument == PIP_DOWNLOAD_DEST_PLACEHOLDER else argument
                    for argument in command
                ]
            return run(command, env=plan.env, **run_kwargs)
        finally:
            if scratch_dir is not None:
                shutil.rmtree(scratch_dir, ignore_errors=True)

    preflight = run_preflight(plan.preflight_command)
    if (
        preflight.returncode == 0
        or plan.preflight_fallback_command is None
        or not _pip_dry_run_is_unsupported(preflight)
    ):
        return preflight

    return run_preflight(plan.preflight_fallback_command)


def _pip_dry_run_is_unsupported(result: subprocess.CompletedProcess[str]) -> bool:
    output = f"{result.stdout or ''}\n{result.stderr or ''}".lower()
    return "--dry-run" in output and any(
        marker in output
        for marker in ("no such option", "unknown option", "unrecognized argument")
    )


@dataclass
class AtomicActivation:
    """A validated candidate and the stable launcher it will replace.

    ``committed`` becomes true immediately after the stable launcher is
    replaced. Callers use it to distinguish post-commit cleanup or reporting
    failures from pre-commit activation failures.
    """

    launcher: Path
    candidate_launcher: Path
    source_generation: Path | None = None
    committed: bool = field(default=False, init=False, repr=False, compare=False)


@dataclass(frozen=True)
class LauncherActivationFailure:
    """A managed peer launcher that remained on its previous generation."""

    launcher: Path
    reason: str
    reason_code: str = "move_failed"


@dataclass(frozen=True)
class ActivationOutcome:
    """The committed activation and any managed peers left behind."""

    activated_launcher: Path
    peer_failures: tuple[LauncherActivationFailure, ...] = ()


def atomic_uv_install_root() -> Path:
    """Return the durable root for versioned uv tool environments."""

    return config_paths.get_vibe_remote_dir() / "runtime" / "install-generations"


@contextlib.contextmanager
def atomic_upgrade_lock(*, timeout_seconds: float = UPGRADE_INSTALL_TIMEOUT_SECONDS):
    """Serialize staged installation, launcher activation, and pruning."""

    lock_path = atomic_uv_install_root().expanduser().parent / ".install.lock"
    with MigrationFileLock(lock_path, timeout_seconds=timeout_seconds):
        yield


def restart_is_pending() -> bool:
    """Whether a scheduled restart still owns the next activation boundary."""

    path = runtime_mod.get_restart_status_path()
    payload = runtime_mod.read_json(path)
    if not isinstance(payload, Mapping):
        return False
    return restart_record_is_pending(payload, path)


def restart_record_is_pending(
    payload: Mapping[str, object],
    path: Path,
    *,
    grace_seconds: float = RESTART_PENDING_GRACE_SECONDS,
) -> bool:
    """Apply the restart ownership policy to one persisted status record.

    The one policy every reader of the restart status applies. A live
    supervisor pid is the job while its recorded identity matches: its start
    token, or the create time a job a released build ran recorded. A record
    that cannot be verified -- no pid yet, no identity recorded, or none
    readable now -- owns the restart only until it is ``grace_seconds`` old.
    """

    try:
        state = RestartState(payload.get("state"))
    except (TypeError, ValueError):
        return False
    if state.retention != "seed":
        return False
    supervisor_pid = payload.get("supervisor_pid")
    if isinstance(supervisor_pid, int) and supervisor_pid > 0 and runtime_mod.pid_alive(supervisor_pid):
        start_token = payload.get("supervisor_start_token")
        started_at = payload.get("supervisor_started_at")
        if start_token is not None:
            current_start_token = runtime_mod.process_start_token(supervisor_pid)
            if current_start_token is not None:
                return current_start_token == start_token
        elif started_at is not None:
            # A job a released build ran recorded its create time instead.
            current_started_at = runtime_mod.process_create_time(supervisor_pid)
            if current_started_at is not None:
                return current_started_at == started_at
        # A record with no identity (from before identities, or written where
        # none could be read) and one whose identity cannot be read now cannot
        # tell the job from a reused PID, which must not block upgrades for the
        # lifetime of an unrelated process, so fall through to age.
    try:
        age = time.time() - path.stat().st_mtime
    except OSError:
        return False
    return age <= grace_seconds


def _is_stable_launcher_path(launcher: Path) -> bool:
    if launcher.name.lower() not in {"vibe", "vibe.exe"}:
        return False
    # ``vibe_path`` has already been resolved to the command that launched this
    # installation. Its role, not the directory uv happened to use when it was
    # installed, makes it the stable activation point. The only unsafe shape is
    # the entry point inside the mutable uv tool environment itself.
    logical = os.path.normcase(os.path.abspath(os.path.expanduser(str(launcher))))
    atomic_root = os.path.normcase(os.path.abspath(os.path.expanduser(str(atomic_uv_install_root()))))
    uv_layout = logical.replace("\\", "/").lower()
    return "/uv/tools/" not in uv_layout and not Path(logical).is_relative_to(Path(atomic_root))


def launcher_is_current_process(launcher: Path | str) -> bool:
    """Whether this Windows process is holding the stable launcher open."""

    if os.name != "nt":
        return False
    target = os.path.normcase(os.path.abspath(os.path.expanduser(str(launcher))))
    # ``VIBE_CURRENT_EXECUTABLE`` is inherited by the long-lived Web process
    # from the CLI that started it. It identifies a PATH entry, not the image
    # currently holding the file open, so only argv[0] is authoritative here.
    current = os.path.normcase(os.path.abspath(os.path.expanduser(sys.argv[0])))
    return current == target


def _staged_uv_environment(vibe_path: str | None) -> tuple[Path, Path, AtomicActivation | None]:
    generation = atomic_uv_install_root() / uuid4().hex
    # 3.0.13 only recognizes uv installs whose interpreter path contains
    # /uv/tools/. Generations must retain that released handoff contract so an
    # immutable 3.0.13 process can choose uv for its first product upgrade.
    tools_dir = generation / "uv" / "tools"
    bin_dir = generation / "bin"
    if not vibe_path:
        return tools_dir, bin_dir, None

    launcher = Path(vibe_path).expanduser()
    # Only replace a stable launcher link. A direct path into a virtualenv may
    # be the user's intentional installation and cannot be switched safely by
    # replacing the file the current process is executing.
    if not _is_stable_launcher_path(launcher):
        return tools_dir, bin_dir, None
    candidate = bin_dir / launcher.name
    return tools_dir, bin_dir, AtomicActivation(
        launcher=launcher,
        candidate_launcher=candidate,
        source_generation=_launcher_generation(launcher, atomic_uv_install_root()),
    )


def _candidate_python(candidate_launcher: Path) -> Path | None:
    roots = [candidate_launcher.parent]
    with contextlib.suppress(OSError, RuntimeError):
        resolved_parent = candidate_launcher.resolve().parent
        if resolved_parent not in roots:
            roots.append(resolved_parent)
    with contextlib.suppress(OSError, RuntimeError, ValueError):
        generation = _generation_for_path(candidate_launcher, atomic_uv_install_root())
        if generation is not None:
            roots.extend((generation / "uv" / "tools", generation / "tools"))
    names = ("python.exe", "python3.exe", "python3", "python") if os.name == "nt" else ("python3", "python")
    for root in roots:
        for name in names:
            candidate = root / name
            if candidate.is_file() and os.access(candidate, os.X_OK):
                return candidate
        if root.name == "tools" and root.is_dir():
            for name in names:
                for candidate in sorted(root.rglob(name)):
                    if candidate.is_file() and os.access(candidate, os.X_OK):
                        return candidate
    return None


def defer_upgrade_activation(
    activation: AtomicActivation,
    *,
    parent_pid: int,
    restart_required: bool = False,
    prepare_show_runtime: bool = False,
) -> subprocess.Popen:
    """Run activation after a Windows CLI process releases its launcher."""

    candidate_python = _candidate_python(activation.candidate_launcher)
    if candidate_python is None:
        raise RuntimeError(f"candidate Python missing beside {activation.candidate_launcher}")
    command = [
        str(candidate_python),
        "-c",
        "from vibe.cli import main; main()",
        "__activate-upgrade",
        "--parent-pid",
        str(parent_pid),
        "--launcher",
        str(activation.launcher),
        "--candidate",
        str(activation.candidate_launcher),
    ]
    if activation.source_generation is not None:
        command.extend(["--source-generation", str(activation.source_generation)])
    if restart_required:
        command.append("--restart")
    if prepare_show_runtime:
        command.append("--prepare-show-runtime")
    parent_started_at = runtime_mod.process_create_time(parent_pid)
    if parent_started_at is not None:
        command.extend(["--parent-started-at", str(parent_started_at)])
    log_path = config_paths.get_logs_dir() / f"upgrade-activation-{uuid4().hex}.log"
    log_path.parent.mkdir(parents=True, exist_ok=True)
    with log_path.open("a", encoding="utf-8") as log:
        process = subprocess.Popen(
            command,
            stdin=subprocess.DEVNULL,
            stdout=log,
            stderr=subprocess.STDOUT,
            start_new_session=True,
            close_fds=True,
            cwd=get_safe_cwd(),
            # Activation is Avibe's own work: it runs after this process exits,
            # under the installation's authority, not the caller's. Keep the
            # interpreter isolation this spawn already needs and drop the caller
            # hop on top of it, rather than changing what probes inherit.
            env=environment_without_caller_context(isolated_probe_environment()),
        )
    # The parent still owns the install lock and is alive. Publish the helper's
    # PID before releasing that lock, including the interval where the helper
    # is waiting for this Windows CLI to release its executable.
    from vibe.install_generations import mark_install_generation

    try:
        mark_install_generation(activation.candidate_launcher, process.pid)
    except Exception:
        # The helper cannot activate while its parent is alive. This is still
        # pre-commit; the caller can safely discard the failed candidate.
        with contextlib.suppress(OSError):
            process.terminate()
        raise
    activation.committed = True
    setattr(process, "activation_log_path", log_path)
    return process


def get_deferred_activation_log_path(process: object) -> Path | None:
    """Return the existing log path used by a detached activation helper."""

    path = getattr(process, "activation_log_path", None)
    return path if isinstance(path, Path) else None


def get_cli_launcher_path(launcher: runtime_mod.ServiceLauncher) -> Path | None:
    """Find the CLI launcher next to a saved service interpreter."""

    names = ("vibe.exe", "vibe") if os.name == "nt" else ("vibe", "vibe.exe")
    python_path = Path(launcher.python).expanduser()
    root = atomic_uv_install_root()
    generation = _launcher_generation(python_path, root)
    if generation is not None:
        generation_bin = generation / "bin"
        for name in names:
            candidate = generation_bin / name
            if candidate.is_file() and os.access(candidate, os.X_OK):
                return candidate
        with contextlib.suppress(OSError):
            for name in names:
                candidate = next(generation.rglob(name), None)
                if candidate is not None and candidate.is_file() and os.access(candidate, os.X_OK):
                    return candidate

    python_bin = python_path.parent
    for name in names:
        candidate = python_bin / name
        if candidate.is_file() and os.access(candidate, os.X_OK):
            return candidate
    return None


def _generation_for_path(path: Path, root: Path) -> Path | None:
    """Return the canonical generation containing a logical install path.

    The leaf may itself be a symlink, as uv-managed Python launchers commonly
    are. Walk its logical ancestors and resolve only the candidate generation
    directory so the shared interpreter target cannot erase generation
    ownership.
    """

    try:
        root = root.expanduser().resolve()
        expanded = path.expanduser()
    except (OSError, RuntimeError):
        return None
    ancestors = [expanded, *expanded.parents]
    try:
        resolved_path = expanded.resolve()
    except (OSError, RuntimeError):
        resolved_path = None
    if resolved_path is not None:
        ancestors.extend((resolved_path, *resolved_path.parents))
    for ancestor in dict.fromkeys(ancestors):
        try:
            resolved = ancestor.resolve()
        except (OSError, RuntimeError):
            continue
        if resolved.parent == root:
            return resolved
    return None


def _generation_for_hardlink(launcher: Path, root: Path) -> Path | None:
    """Find an atomic generation sharing the stable launcher's inode."""

    if launcher.is_symlink() or not _is_stable_launcher_path(launcher):
        return None
    try:
        launcher_stat = launcher.stat()
        identity = (launcher_stat.st_dev, launcher_stat.st_ino)
    except OSError:
        return None
    try:
        root = root.expanduser().resolve()
        if not root.is_dir():
            return None
        generations = list(root.iterdir())
    except OSError:
        return None
    for generation in generations:
        candidate = generation / "bin" / launcher.name
        try:
            candidate_stat = candidate.stat()
            if generation.is_dir() and (candidate_stat.st_dev, candidate_stat.st_ino) == identity:
                # Directory aliases must use the collector's canonical identity.
                return _generation_for_path(generation, root)
        except OSError:
            continue
    return None


def _launcher_generation(launcher: Path, root: Path) -> Path | None:
    """Return the generation currently represented by a stable launcher."""

    root = root.expanduser().resolve()
    generation = _generation_for_path(launcher, root) or _generation_for_hardlink(launcher, root)
    if generation is not None:
        return generation
    if not _is_stable_launcher_path(launcher):
        return None
    marker = launcher.parent / f".{launcher.name}.avibe-generation"
    try:
        marked = Path(marker.read_text(encoding="utf-8").lstrip("\ufeff").strip())
    except (OSError, UnicodeError):
        return None
    generation = _generation_for_path(marked, root)
    if generation is None or not generation.is_dir():
        return None
    # A marker is necessary only for the cross-volume copy fallback. Treat it
    # as a hint and prove that it still describes the live launcher before use.
    # A managed launcher has its export's name (see ``managed_stable_launchers``).
    candidate = generation / "bin" / launcher.name
    try:
        # Read both files on every check. Marker validation is a safety
        # boundary, and stat-keyed filecmp caching could reuse a comparison
        # after a same-size/same-mtime copy fallback was replaced.
        return generation if launcher.read_bytes() == candidate.read_bytes() else None
    except OSError:
        return None


def _update_launcher_generation_marker(launcher: Path, target: Path, root: Path) -> None:
    """Record a copied launcher's generation without making cleanup mandatory."""

    marker = launcher.parent / f".{launcher.name}.avibe-generation"
    generation = _generation_for_path(target, root)
    if generation is None:
        with contextlib.suppress(OSError):
            marker.unlink()
        return
    replacement = marker.parent / f".{marker.name}.{uuid4().hex}.new"
    try:
        replacement.write_text(str(generation), encoding="utf-8")
        os.replace(replacement, marker)
    except OSError:
        with contextlib.suppress(OSError):
            replacement.unlink()
        logger.warning("failed to update launcher generation marker %s", marker, exc_info=True)


@dataclass(frozen=True)
class LauncherSelection:
    """A stable launcher and the managed generation it currently selects."""

    launcher: Path
    generation: Path
    version: str | None


def generation_version(generation: Path) -> str | None:
    """Return the Avibe version installed in one managed generation."""

    from importlib import metadata

    try:
        site_packages = [
            path
            for layout in ("uv/tools", "tools")
            for package in (PACKAGE_NAME, LEGACY_PACKAGE_NAME)
            for path in (
                *(generation / layout / package).glob("lib/python*/site-packages"),
                generation / layout / package / "Lib" / "site-packages",
            )
            if path.is_dir()
        ]
        # The legacy distribution is a shim beside the core package once the
        # rename shipped; the core package's version describes the code.
        for package in (PACKAGE_NAME, LEGACY_PACKAGE_NAME):
            for distribution in metadata.distributions(name=package, path=[str(path) for path in site_packages]):
                if distribution.version:
                    return distribution.version
    except (OSError, ValueError):
        # Unreadable or undecodable metadata is an unknown version, which never
        # fences start and never stops status or doctor from reporting it.
        pass
    return None


def _launcher_key(launcher: Path) -> str:
    """Identify a launcher file by its canonical directory, not its own target."""

    launcher = launcher.expanduser().absolute()
    return os.path.normcase(str(launcher.parent.resolve() / launcher.name))


def managed_stable_launchers(*launchers: str | os.PathLike[str] | None) -> list[tuple[Path, Path]]:
    """Return every discoverable stable launcher with the managed generation it selects.

    Candidates are the given launchers, the launcher this invocation ran
    through, then every PATH entry, uv's configured tool bin and the
    installers' fixed launcher locations. A launcher that
    resolves outside this install's generation root, or to anything there that
    retirement would not recognize as an Avibe installation, is not Avibe's to
    manage and is never returned.
    """

    from vibe.install_generations import _uv_installation

    root = atomic_uv_install_root().expanduser().resolve()
    exported: dict[Path, frozenset[str]] = {}
    names = ("vibe.exe",) if os.name == "nt" else ("vibe",)
    directories = [*os.get_exec_path(), os.environ.get("UV_TOOL_BIN_DIR", ""), *INSTALLER_LAUNCHER_DIRS]
    # An activation through an off-PATH launcher moves that launcher, so later
    # discovery must still see it beside any peer that could not move.
    invoked = get_running_vibe_path()
    candidates = [Path(launcher) for launcher in (*launchers, invoked) if launcher]
    candidates.extend(Path(directory) / name for directory in directories if directory for name in names)
    seen: set[str] = set()
    result: list[tuple[Path, Path]] = []
    for candidate in candidates:
        launcher = candidate.expanduser()
        if not launcher.is_absolute() or not _is_stable_launcher_path(launcher):
            continue
        try:
            key = _launcher_key(launcher)
            present = launcher.is_symlink() or launcher.exists()
        except (OSError, RuntimeError):
            continue
        if not present or key in seen:
            continue
        seen.add(key)
        generation = _launcher_generation(launcher, root)
        if generation is None:
            continue
        if generation not in exported:
            try:
                installation = _uv_installation(generation)
            except OSError:
                installation = None
            exported[generation] = frozenset(
                os.path.normcase(export.name) for export in (installation[1] if installation else ())
            )
        # Invariant: a managed launcher has the name of a launcher its install
        # exports, so ``generation/bin/<launcher name>`` is that export. The
        # copy-marker check and every move rely on it; any other name, such as
        # an extensionless alias of Windows' ``vibe.exe``, is not Avibe's.
        if os.path.normcase(launcher.name) in exported[generation]:
            result.append((launcher.absolute(), generation))
    return result


def stable_launcher_selections(*launchers: str | os.PathLike[str] | None) -> list[LauncherSelection]:
    """Describe every managed stable launcher with its generation's version."""

    versions: dict[Path, str | None] = {}
    selections: list[LauncherSelection] = []
    for launcher, generation in managed_stable_launchers(*launchers):
        if generation not in versions:
            versions[generation] = generation_version(generation)
        selections.append(LauncherSelection(launcher, generation, versions[generation]))
    return selections


def _generation_installed_at(generation: Path) -> float:
    """When uv installed a generation, from the receipt it writes for each install."""

    times = []
    for receipt in (*generation.glob("uv/tools/*/uv-receipt.toml"), *generation.glob("tools/*/uv-receipt.toml")):
        with contextlib.suppress(OSError):
            times.append(receipt.stat().st_mtime)
    return max(times, default=float("-inf"))


def _activation_rank(generation: Path, version: str | None) -> tuple:
    """Order installs so the last activated one ranks highest.

    The newest version wins, and a known version outranks an unknown one.
    Generations of the same version, such as a reinstall or integrity repair,
    rank by when uv installed them: activation always installs a fresh
    generation, so the most recent install of a version is the one activated.
    This is the only ordering behind both the repair target and the fence.
    """

    parsed = _parse_version(version) if version else None
    installed_at = _generation_installed_at(generation)
    return (0, installed_at) if parsed is None else (1, parsed, installed_at)


def top_ranked_selections(selections: list[LauncherSelection]) -> list[LauncherSelection]:
    """Return every launcher selecting an install at the highest ``_activation_rank``.

    More than one generation here is a tie: the evidence cannot say which
    install was activated last.
    """

    ranks: dict[Path, tuple] = {}
    for selection in selections:
        if selection.generation not in ranks:
            ranks[selection.generation] = _activation_rank(selection.generation, selection.version)
    if not ranks:
        return []
    top = max(ranks.values())
    return [selection for selection in selections if ranks[selection.generation] == top]


def newest_launcher_selection(selections: list[LauncherSelection]) -> LauncherSelection | None:
    """Return a launcher selecting the last activated install, or ``None`` when that is unknown.

    A tie between different generations is ambiguous, never settled by
    discovery order: the repair then has no target, and the fence and the
    service warning have no last activation to compare against.
    """

    top = top_ranked_selections(selections)
    return top[0] if len({selection.generation for selection in top}) == 1 else None


def current_generation() -> Path | None:
    """Return the managed generation this process runs from, if any."""

    root = atomic_uv_install_root()
    for path in (sys.executable, sys.prefix, __file__):
        generation = _generation_for_path(Path(path).absolute(), root)
        if generation is not None:
            return generation
    return None


def process_generation(pid: int | None) -> Path | None:
    """Return the managed generation another process runs from, if it can be read."""

    import psutil

    if not pid:
        return None
    try:
        process = psutil.Process(pid)
        values = [argument.strip('"') for argument in process.cmdline()]
        values.append(process.exe())
    except (psutil.Error, OSError):
        return None
    root = atomic_uv_install_root()
    for value in values:
        if value and Path(value).is_absolute():
            generation = _generation_for_path(Path(value), root)
            if generation is not None:
                return generation
    return None


@dataclass(frozen=True)
class GenerationDowngrade:
    """A generation older than the newest one a stable launcher selects."""

    generation: Path
    version: str
    activated: LauncherSelection

    def as_dict(self) -> dict[str, str | None]:
        return {
            "generation": str(self.generation),
            "version": self.version,
            "activated_generation": str(self.activated.generation),
            "activated_version": self.activated.version,
            "launcher": str(self.activated.launcher),
        }


def generation_downgrade(generation: Path | None) -> GenerationDowngrade | None:
    """Report whether a generation is older than the last activated one.

    Activation keeps every stable launcher on the generation it installs, so
    the highest ``_activation_rank`` any launcher selects is the last
    activation; an older install of the same version counts as well. A
    generation whose own version is unknown never counts as a downgrade, and
    neither does anything while the top rank is tied between installs.
    """

    if generation is None:
        return None
    version = generation_version(generation)
    if version is None or _parse_version(version) is None:
        return None
    newest = newest_launcher_selection(stable_launcher_selections())
    if newest is None or newest.generation == generation:
        return None
    if _activation_rank(newest.generation, newest.version) <= _activation_rank(generation, version):
        return None
    return GenerationDowngrade(generation, version, newest)


def atomic_activation_source_is_current(activation: AtomicActivation) -> bool:
    """Check that the stable launcher still points at the source we measured."""

    root = atomic_uv_install_root()
    current = _launcher_generation(activation.launcher, root)
    if activation.source_generation is None:
        return current is None
    source = _generation_for_path(activation.source_generation, root)
    if current is not None or source is not None:
        return current == source
    try:
        current_target = activation.launcher.resolve(strict=True)
        return os.path.samefile(current_target, activation.source_generation)
    except (OSError, RuntimeError, ValueError):
        return False


def activation_block_reason(activation: AtomicActivation) -> str | None:
    """Return why an activation cannot own the current install boundary."""

    if restart_is_pending():
        return "restart_pending"
    if not atomic_activation_source_is_current(activation):
        return "superseded"
    return None


def discard_atomic_uv_install_generation(path: Path | str) -> bool:
    """Remove one failed candidate generation without touching active installs."""

    root = atomic_uv_install_root().expanduser().resolve()
    generation = _generation_for_path(Path(path), root)
    if generation is None or not generation.is_dir():
        return False
    try:
        shutil.rmtree(generation)
    except OSError:
        logger.warning("failed to discard atomic Avibe install generation %s", generation, exc_info=True)
        return False
    return True


def verify_upgrade_candidate(activation: AtomicActivation) -> IntegrityResult:
    """Prove a staged tool is runnable and its package tree is complete."""

    candidate = activation.candidate_launcher
    if not candidate.is_file() or not os.access(candidate, os.X_OK):
        return IntegrityResult(False, failures=(f"candidate launcher missing: {candidate}",))
    python = _candidate_python(candidate)
    if python is None:
        return IntegrityResult(False, failures=(f"candidate Python missing beside {candidate}",))
    result = verify_python_environment(python)
    if not result.ok:
        return result
    try:
        probe = run_isolated_probe([str(candidate), "--help"], timeout=60)
    except (OSError, subprocess.SubprocessError) as exc:
        return IntegrityResult(False, failures=(f"candidate launcher probe failed: {exc}",))
    if probe.returncode != 0:
        detail = (probe.stderr or probe.stdout or "").strip().splitlines()
        suffix = detail[-1] if detail else f"exit code {probe.returncode}"
        return IntegrityResult(False, failures=(f"candidate launcher probe failed: {suffix}",))
    return result


def _prepare_launcher_replacement(replacement: Path, target: Path) -> None:
    """Create a replacement launcher, using copy when links cannot cross volumes."""

    try:
        replacement.symlink_to(target)
        return
    except OSError:
        pass
    try:
        os.link(target, replacement)
        return
    except OSError:
        # A regular copy is the only portable option when the stable bin and
        # the runtime home are on different Windows volumes.
        shutil.copy2(target, replacement)


def _activation_failure_reason_code(exc: BaseException) -> str:
    """Classify a peer move failure without discarding its concrete cause."""

    if isinstance(exc, PermissionError) or getattr(exc, "errno", None) in {
        errno.EACCES,
        errno.EPERM,
    } or getattr(exc, "winerror", None) == 5:
        return "permission_denied"
    return "move_failed"


def activate_upgrade_candidate(activation: AtomicActivation) -> ActivationOutcome:
    """Atomically switch the stable launcher to a validated candidate."""

    # Runtime callers already own this lock; the lock is re-entrant so direct
    # activation and installer callers share the same collection boundary too.
    with atomic_upgrade_lock():
        return _activate_upgrade_candidate_locked(activation)


def _activate_upgrade_candidate_locked(activation: AtomicActivation) -> ActivationOutcome:
    from vibe.install_generations import (
        collect_install_generations,
        finish_install_generation,
    )

    result = verify_upgrade_candidate(activation)
    if not result.ok:
        raise RuntimeError(f"staged Avibe install failed integrity checks: {result.detail}")
    launcher = activation.launcher
    # Every other stable launcher already selecting a managed generation moves
    # with the invoked one, so no PATH lookup keeps an older build. Discover
    # them before the commit: once the primary launcher is replaced, nothing
    # here may raise and make the caller discard the activated candidate.
    primary = _launcher_key(launcher)
    peers = [(peer, selected) for peer, selected in managed_stable_launchers() if _launcher_key(peer) != primary]
    launcher.parent.mkdir(parents=True, exist_ok=True)
    replacement = launcher.parent / f".{launcher.name}.avibe-{uuid4().hex}.new"
    root = atomic_uv_install_root().expanduser().resolve()
    try:
        _prepare_launcher_replacement(replacement, activation.candidate_launcher)
        os.replace(replacement, launcher)
        activation.committed = True
    except Exception:
        with contextlib.suppress(OSError):
            replacement.unlink()
        raise
    _update_launcher_generation_marker(launcher, activation.candidate_launcher, root)
    # A peer left behind stays protected from collection and is reported by
    # `vibe doctor`; it must not undo the committed activation. A peer that
    # now follows the primary, such as an alias of it, keeps its shape.
    activated = _generation_for_path(activation.candidate_launcher, root)
    peer_failures: list[LauncherActivationFailure] = []
    for peer, selected in peers:
        if selected == activated:
            continue
        try:
            if not move_managed_launcher_locked(peer, selected, activation.candidate_launcher):
                if _launcher_generation(peer, root) == activated:
                    continue
                reason = "the launcher changed after discovery"
                peer_failures.append(
                    LauncherActivationFailure(peer, reason, "launcher_changed_after_discovery")
                )
                logger.warning("Could not move stable launcher %s: %s", peer, reason)
        except Exception as exc:
            reason = str(exc).strip() or type(exc).__name__
            peer_failures.append(
                LauncherActivationFailure(peer, reason, _activation_failure_reason_code(exc))
            )
            logger.warning("Could not move stable launcher %s to the activated generation", peer, exc_info=True)
    finish_install_generation(activation.candidate_launcher)
    collect_install_generations(launcher)
    return ActivationOutcome(launcher.absolute(), tuple(peer_failures))


def activate_installer_candidate(activation: AtomicActivation) -> ActivationOutcome:
    """Activate an installer candidate through the shared lifecycle owner."""

    with atomic_upgrade_lock():
        reason = activation_block_reason(activation)
        if reason == "restart_pending":
            raise RuntimeError("an Avibe restart is still in progress")
        if reason == "superseded":
            raise RuntimeError("the active Avibe generation changed while the installer was staging")
        return activate_upgrade_candidate(activation)


def activation_repair_command(launcher: str | os.PathLike[str]) -> str:
    """Return a shell-safe repair command rooted at the activated launcher."""

    full_path = os.path.abspath(os.path.expanduser(str(launcher)))
    command = [full_path, "doctor", "repair", "stable-launchers"]
    if os.name == "nt":
        powershell_path = full_path.replace("'", "''")
        return f"& '{powershell_path}' doctor repair stable-launchers"
    return shlex.join(command)


def format_activation_failures(outcome: ActivationOutcome, language: str = "en") -> str | None:
    """Render managed peer failures for a user-facing upgrade result."""

    if not outcome.peer_failures:
        return None
    from vibe.i18n import t

    repair_command = activation_repair_command(outcome.activated_launcher)
    repair_instruction_key = (
        "update.stableLauncherRepairPowerShellInstruction"
        if os.name == "nt"
        else "update.stableLauncherRepairInstruction"
    )
    repair_instruction = t(repair_instruction_key, language, repairCommand=repair_command)
    messages = []
    for failure in outcome.peer_failures:
        if failure.reason_code == "permission_denied":
            key = "update.stableLauncherActivationPermissionDenied"
        elif failure.reason_code == "launcher_changed_after_discovery":
            key = "update.stableLauncherActivationChanged"
        else:
            key = "update.stableLauncherActivationFailed"
        messages.append(
            t(
                key,
                language,
                launcher=str(failure.launcher),
                reason=failure.reason,
                repairCommand=repair_command,
                repairInstruction=repair_instruction,
            )
        )
    return "\n\n".join(messages)


def format_deferred_activation_log(log_path: Path | None, language: str = "en") -> str | None:
    """Explain where a deferred activation helper records its result."""

    if log_path is None:
        return None
    from vibe.i18n import t

    return t("update.deferredActivationLog", language, logPath=str(log_path))


def activate_launcher_target(launcher: str | os.PathLike[str], target: str | os.PathLike[str]) -> None:
    """Atomically point a stable launcher at an installed target."""

    with atomic_upgrade_lock():
        _activate_launcher_target_locked(launcher, target)


def move_managed_launcher_locked(launcher: Path, selected: Path, target: str | os.PathLike[str]) -> bool:
    """Repoint a stable launcher only while it still selects the generation it was found on.

    The upgrade lock serializes Avibe, not uv, other installers or an
    administrator. A launcher replaced since discovery is no longer Avibe's to
    move, so it is left as it is and reported as not moved.
    """

    if _launcher_generation(launcher, atomic_uv_install_root().expanduser().resolve()) != selected:
        return False
    _activate_launcher_target_locked(launcher, target)
    return True


def _activate_launcher_target_locked(launcher: str | os.PathLike[str], target: str | os.PathLike[str]) -> None:
    launcher_path = Path(launcher).expanduser()
    target_path = Path(target).expanduser()
    if not target_path.is_file() or not os.access(target_path, os.X_OK):
        raise RuntimeError(f"launcher target is not executable: {target_path}")
    launcher_path.parent.mkdir(parents=True, exist_ok=True)
    replacement = launcher_path.parent / f".{launcher_path.name}.avibe-{uuid4().hex}.new"
    try:
        _prepare_launcher_replacement(replacement, target_path)
        os.replace(replacement, launcher_path)
    except Exception:
        with contextlib.suppress(OSError):
            replacement.unlink()
        raise
    _update_launcher_generation_marker(launcher_path, target_path, atomic_uv_install_root().expanduser().resolve())


def is_desktop_managed_runtime(base_env: Mapping[str, str] | None = None) -> bool:
    env = os.environ if base_env is None else base_env
    value = env.get(DESKTOP_MANAGED_RUNTIME_ENV, "")
    return value.strip().lower() in TRUTHY_ENV_VALUES


def resolve_command_path(command: str | None, search_path: str | None = None) -> str | None:
    if not command:
        return None

    expanded = Path(command).expanduser()
    if expanded.is_absolute():
        return os.path.abspath(str(expanded))

    if any(sep in command for sep in (os.sep, "/")):
        return os.path.abspath(str(Path.cwd() / expanded))

    resolved = shutil.which(command, path=search_path)
    if not resolved:
        return None
    return os.path.abspath(os.path.expanduser(resolved))


def is_usable_command_path(path: str | None) -> bool:
    if not path:
        return False
    return os.path.exists(path) and os.access(path, os.X_OK)


def get_launcher_bin_dir(command_path: str) -> str:
    current = os.path.abspath(os.path.expanduser(command_path))

    while os.path.islink(current):
        target = os.readlink(current)
        if not os.path.isabs(target):
            target = os.path.abspath(os.path.join(os.path.dirname(current), target))
        else:
            target = os.path.abspath(os.path.expanduser(target))

        if not os.path.islink(target):
            return str(Path(current).parent)

        current = target

    return str(Path(current).parent)


def get_known_uv_paths(base_env: Mapping[str, str] | None = None) -> list[str]:
    env = base_env or os.environ
    home = env.get("HOME")
    if home is not None:
        return [os.path.join(home, bin_dir, "uv") for bin_dir in UV_FALLBACK_BIN_DIRS]
    return [os.path.expanduser(f"~/{bin_dir}/uv") for bin_dir in UV_FALLBACK_BIN_DIRS]


def should_skip_show_runtime_prepare(base_env: Mapping[str, str] | None = None) -> bool:
    env = base_env or os.environ
    return env.get(SHOW_RUNTIME_SKIP_ENV, "").strip().lower() in TRUTHY_ENV_VALUES


def find_uv_binary(uv_path: str | None = None, base_env: Mapping[str, str] | None = None) -> str | None:
    env = base_env or os.environ
    search_path = env.get("PATH")

    resolved = resolve_command_path(uv_path, search_path=search_path)
    if is_usable_command_path(resolved):
        return resolved

    resolved = resolve_command_path("uv", search_path=search_path)
    if is_usable_command_path(resolved):
        return resolved

    for candidate in get_known_uv_paths(base_env=env):
        resolved = resolve_command_path(candidate, search_path=search_path)
        if is_usable_command_path(resolved):
            return resolved

    return None


def get_running_vibe_path(
    *,
    vibe_path: str | None = None,
    argv0: str | None = None,
    search_path: str | None = None,
) -> str | None:
    resolved = resolve_command_path(vibe_path, search_path=search_path)
    if is_usable_command_path(resolved):
        return resolved

    env_path = resolve_command_path(os.environ.get(CURRENT_VIBE_EXECUTABLE_ENV), search_path=search_path)
    if is_usable_command_path(env_path):
        return env_path

    argv_path = resolve_command_path(argv0 or sys.argv[0], search_path=search_path)
    if is_usable_command_path(argv_path):
        argv_path_str = cast(str, argv_path)
        if Path(argv_path_str).name.startswith("vibe"):
            return argv_path_str

    fallback_path = resolve_command_path("vibe", search_path=search_path)
    if is_usable_command_path(fallback_path):
        return fallback_path
    return None


def cache_running_vibe_path(vibe_path: str | None = None) -> str | None:
    resolved = get_running_vibe_path(vibe_path=vibe_path)
    if resolved:
        os.environ[CURRENT_VIBE_EXECUTABLE_ENV] = resolved
    return resolved


def get_restart_command(
    *,
    vibe_path: str | None = None,
    python_executable: str | None = None,
    argv0: str | None = None,
    search_path: str | None = None,
) -> list[str]:
    resolved = get_running_vibe_path(vibe_path=vibe_path, argv0=argv0, search_path=search_path)
    if resolved:
        return [resolved]
    return [python_executable or sys.executable, "-c", "from vibe.cli import main; main()"]


def get_restart_invocation_command(
    *,
    vibe_path: str | None = None,
    python_executable: str | None = None,
    argv0: str | None = None,
    search_path: str | None = None,
) -> list[str]:
    return [
        *get_restart_command(
            vibe_path=vibe_path,
            python_executable=python_executable,
            argv0=argv0,
            search_path=search_path,
        ),
        "restart",
    ]


def _get_source_checkout_root() -> str | None:
    source_root = Path(__file__).resolve().parent.parent
    if not source_root.is_dir():
        return None
    if not (source_root / "pyproject.toml").is_file():
        return None
    if not (source_root / "vibe" / "__init__.py").is_file():
        return None
    return str(source_root)


def _normalize_pythonpath_entries(pythonpath: str) -> list[str]:
    normalized_entries: list[str] = []
    seen_entries: set[str] = set()

    for entry in pythonpath.split(os.pathsep):
        if not entry:
            continue
        normalized_entry = os.path.abspath(os.path.expanduser(entry))
        if normalized_entry in seen_entries:
            continue
        seen_entries.add(normalized_entry)
        normalized_entries.append(normalized_entry)

    return normalized_entries


def get_restart_environment(
    *,
    vibe_path: str | None = None,
    argv0: str | None = None,
    search_path: str | None = None,
    base_env: Mapping[str, str] | None = None,
) -> dict[str, str] | None:
    resolved = get_running_vibe_path(vibe_path=vibe_path, argv0=argv0, search_path=search_path)
    if resolved:
        return None

    source_root = _get_source_checkout_root()
    if not source_root:
        return None

    env = dict(base_env or os.environ)
    pythonpath = env.get("PYTHONPATH")
    if pythonpath:
        normalized_root = os.path.abspath(source_root)
        normalized_entries = _normalize_pythonpath_entries(pythonpath)
        if normalized_root not in normalized_entries:
            normalized_entries.insert(0, normalized_root)
        env["PYTHONPATH"] = os.pathsep.join(normalized_entries)
        return env

    env["PYTHONPATH"] = source_root
    return env


def get_restart_shell_command(
    *,
    vibe_path: str | None = None,
    python_executable: str | None = None,
    argv0: str | None = None,
    search_path: str | None = None,
) -> str:
    command = get_restart_invocation_command(
        vibe_path=vibe_path,
        python_executable=python_executable,
        argv0=argv0,
        search_path=search_path,
    )
    return shlex.join(command)


def get_update_metadata_url() -> str:
    return os.environ.get("AVIBE_UPDATE_METADATA_URL") or os.environ.get(
        "VIBE_UPDATE_METADATA_URL", DEFAULT_UPDATE_METADATA_URL
    )


def get_upgrade_package_spec() -> str:
    return os.environ.get("AVIBE_UPGRADE_PACKAGE_SPEC") or os.environ.get("VIBE_UPGRADE_PACKAGE_SPEC", PACKAGE_NAME)


def _normalize_release_parts(parts: tuple[int, ...]) -> tuple[int, ...]:
    normalized = list(parts)
    while len(normalized) > 1 and normalized[-1] == 0:
        normalized.pop()
    return tuple(normalized)


def _parse_version_parts(
    value: str,
) -> tuple[tuple[int, ...], tuple[int, int] | None, int | None, int | None] | None:
    """Split a version into (release, pre, post, dev).

    ``pre`` is ``(stage_order, num)`` for a/b/rc releases, else ``None``.
    ``post`` / ``dev`` are the numeric component, or ``None`` when absent.
    The local segment (``+...``) is matched but intentionally discarded: per
    PEP 440 it does not affect ordering.
    """
    match = _VERSION_RE.match(value)
    if not match:
        return None

    release = _normalize_release_parts(
        tuple(int(part) for part in match.group("release").split("."))
    )
    pre = None
    if match.group("pre"):
        pre = (_PRE_ORDER[match.group("pre").lower()], int(match.group("pre_num") or "0"))
    post = int(match.group("post_num") or "0") if match.group("post") else None
    dev = int(match.group("dev_num") or "0") if match.group("dev") else None
    return (release, pre, post, dev)


def _version_key(
    parts: tuple[tuple[int, ...], tuple[int, int] | None, int | None, int | None],
) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...], tuple[int, ...]]:
    """Build a totally-ordered, all-int comparison key (PEP 440 ordering).

    Bands are plain int tuples so they never compare a number against a tuple.
    Within a release: ``X.devN`` < ``Xa/b/rcN`` < ``X`` (final) < ``X.postN``,
    and a trailing ``.devN`` sorts before the same version without it.
    """
    release, pre, post, dev = parts
    if pre is None and post is None and dev is not None:
        pre_band: tuple[int, ...] = (0,)  # bare X.devN sorts before any pre/final of X
    elif pre is None:
        pre_band = (2,)  # final (or post-only) sorts after pre-releases
    else:
        pre_band = (1, pre[0], pre[1])
    post_band = (0,) if post is None else (1, post)
    dev_band = (1,) if dev is None else (0, dev)  # a dev release sorts before the non-dev
    return (release, pre_band, post_band, dev_band)


def _parse_version(
    value: str,
) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...], tuple[int, ...]] | None:
    parts = _parse_version_parts(value)
    return None if parts is None else _version_key(parts)


def _is_prerelease_version(value: str) -> bool:
    parts = _parse_version_parts(value)
    if parts is None:
        return False
    _release, pre, _post, dev = parts
    return pre is not None or dev is not None


def _is_yanked_release(files: object) -> bool:
    if not isinstance(files, list) or not files:
        return False
    yanked_flags = [bool(item.get("yanked")) for item in files if isinstance(item, dict)]
    return bool(yanked_flags) and all(yanked_flags)


def select_latest_update_version(metadata: Mapping[str, object], current_version: str) -> str:
    allow_prereleases = _is_prerelease_version(current_version)
    releases = metadata.get("releases")

    candidates: list[tuple[object, str]] = []
    if isinstance(releases, Mapping):
        for version_str, files in releases.items():
            if not isinstance(version_str, str):
                continue
            parsed = _parse_version(version_str)
            if parsed is None:
                continue
            if not allow_prereleases and _is_prerelease_version(version_str):
                continue
            if _is_yanked_release(files):
                continue
            candidates.append((parsed, version_str))

    if candidates:
        candidates.sort(key=lambda item: item[0])
        return candidates[-1][1]

    latest = str((metadata.get("info") or {}).get("version") or "")
    if latest and (allow_prereleases or not _is_prerelease_version(latest)):
        return latest
    return ""


def has_newer_version(candidate: str, current: str) -> bool:
    if not candidate or candidate == current:
        return False

    latest_parsed = _parse_version(candidate)
    current_parsed = _parse_version(current)
    if latest_parsed is not None and current_parsed is not None:
        return latest_parsed > current_parsed

    # Fallback for strings the parser cannot handle: compare the leading
    # integer of each of the first three dotted components. Stop at the first
    # component without a leading digit so we never silently drop a position
    # (e.g. treating "3.0.4rc4" as [3, 0] and ranking it below "3.0.3").
    def _loose_parts(text: str) -> list[int]:
        parts: list[int] = []
        for chunk in text.split(".")[:3]:
            digits = re.match(r"\d+", chunk)
            if not digits:
                break
            parts.append(int(digits.group()))
        return parts

    try:
        return _loose_parts(candidate) > _loose_parts(current)
    except (ValueError, AttributeError):
        return candidate != current


def get_latest_version_info(current_version: str) -> dict:
    result = {"current": current_version, "latest": None, "has_update": False, "error": None}

    try:
        url = get_update_metadata_url()
        req = urllib.request.Request(url, headers={"User-Agent": PACKAGE_NAME})
        with urllib.request.urlopen(req, timeout=10) as resp:
            data = json.loads(resp.read().decode("utf-8"))

        latest = select_latest_update_version(data, current_version)
        result["latest"] = latest

        if latest and latest != current_version:
            result["has_update"] = has_newer_version(latest, current_version)
    except Exception as e:
        result["error"] = str(e)

    return result


def is_uv_tool_install(python_executable: str | None = None) -> bool:
    executable = (python_executable or sys.executable or "").replace("\\", "/")
    if "/uv/tools/" in executable:
        return True
    try:
        logical = Path(os.path.abspath(os.path.expanduser(executable)))
        logical_root = Path(os.path.abspath(os.path.expanduser(str(atomic_uv_install_root()))))
        if logical.is_relative_to(logical_root):
            return True
        if _launcher_generation(logical, logical_root) is not None:
            return True
        # A logical path may contain a symlinked parent. Resolving is only the
        # fallback: uv's tool Python is itself commonly a symlink to a shared
        # interpreter outside the generation.
        return logical.resolve().is_relative_to(logical_root.resolve())
    except (OSError, ValueError, RuntimeError):
        return False


def is_legacy_uv_tool_install(python_executable: str | None = None) -> bool:
    executable = (python_executable or sys.executable or "").replace("\\", "/")
    return f"/uv/tools/{LEGACY_PACKAGE_NAME}/" in executable


def _distributions_providing_this_package() -> list[str]:
    """Installed core providers, excluding the retained legacy companion.

    Its manifest shared the vibe namespace, but never described core code.
    Read distribution metadata only; do not load or modify that package.
    """

    try:
        from importlib.metadata import packages_distributions
    except ImportError:  # pragma: no cover - importlib.metadata ships with 3.10+
        return []
    try:
        return sorted(
            {
                name
                for name in packages_distributions().get(__name__.split(".")[0], [])
                if canonicalize_name(name) != "avibe-memory"
            }
        )
    except Exception:  # pragma: no cover - a broken environment answers nothing
        logger.debug("Failed to read installed distribution metadata", exc_info=True)
        return []


def _providers_recording_a_published_release() -> list[tuple[str, str]]:
    """Every distribution providing this package, with the release it records.

    Local-version recordings are dropped rather than reported. They identify
    a source tree rather than a public release, so they can neither confirm nor
    contradict a released one. Public dev versions can be published just like
    other prereleases. An environment that answers nothing at all --
    no provider, unreadable metadata, nothing published -- comes back empty. Both
    callers read empty as "no evidence", never as evidence of disagreement.
    """

    distributions = _distributions_providing_this_package()
    if not distributions:
        return []
    try:
        from importlib.metadata import version as distribution_version

        recorded = [(name, distribution_version(name)) for name in distributions]
    except Exception:  # pragma: no cover - a broken environment answers nothing
        logger.debug("Failed to read the installed distribution version", exc_info=True)
        return []
    return [(name, version) for name, version in recorded if _names_a_published_release(version)]


def _providers_describing_running_code() -> list[str]:
    """Return providers whose recorded release matches the running code.

    Multiple providers can remain after the `vibe-remote` to `avibe-os` rename.
    Comparing every published record prevents a forward install from becoming a
    silent no-op when stale metadata claims the requested release is present.
    """

    from vibe import __version__

    return [
        name
        for name, recorded in _providers_recording_a_published_release()
        if recorded == __version__
    ]


def installed_metadata_describes_running_code() -> bool:
    """Whether every published provider record matches the running files.

    pip trusts installed metadata when deciding whether an upgrade has work to
    do. A mismatch therefore forces the forward reinstall. Unknown source or
    editable layouts remain unforced because they provide no reliable published
    version to compare.
    """

    from vibe import __version__

    if not _names_a_published_release(__version__):
        return True

    published = _providers_recording_a_published_release()
    if not published:
        return True
    # Metadata describes the code only if EVERY provider recording a published
    # release records this one; a single dissenter is a distribution pip would
    # read as already satisfied.
    return len(_providers_describing_running_code()) == len(published)


def get_current_vibe_bin_dir(vibe_path: str | None = None) -> str | None:
    current_vibe = get_running_vibe_path(vibe_path=vibe_path)
    if not current_vibe:
        return None

    return get_launcher_bin_dir(current_vibe)


def get_current_uv_tool_dir(python_executable: str | None = None) -> str | None:
    """Return the logical uv tool root containing the running interpreter."""

    executable = Path(python_executable or sys.executable).expanduser().absolute()
    for parent in executable.parents:
        if parent.name == "tools" and parent.parent.name == "uv":
            return str(parent)
    return None


def _names_a_published_release(version: str) -> bool:
    """Whether the version alone can identify a release for an index install.

    Public dev versions are supported by the official release producer too.
    Only local labels identify source builds; a dev suffix is not provenance.
    Eligibility does not prove availability: exact repair preflights must still
    resolve the selected core artifact before installation.

    Asking the property instead of listing the strings is what stops the next
    unlisted shape from costing the same attempt. Unparseable reads as
    unpublished for the same reason: a version this codebase cannot even order is
    not one it should pin an install to.
    """

    match = _VERSION_RE.match(version)
    if match is None:
        return False
    return not match.group("local")


def pinned_package_spec(version: str | None, *, package_name: str) -> str:
    if not version:
        return package_name
    if _BARE_PACKAGE_NAME_RE.fullmatch(package_name) is None:
        raise ValueError("The configured upgrade package spec cannot carry a version pin")
    return f"{package_name}=={version}"


def _uv_managed_python_minor(python_executable: str, uv_binary: str, env: Mapping[str, str]) -> str | None:
    """The uv request for the minor version of a tool interpreter uv manages.

    A tool environment records its base interpreter as ``home`` in
    ``pyvenv.cfg``. Only an interpreter inside uv's own Python directory is
    uv's to upgrade; a system Python, or a standalone build another tool keeps
    elsewhere, is left as it is.
    """

    try:
        config = (Path(python_executable).parent.parent / "pyvenv.cfg").read_text(encoding="utf-8")
    except (OSError, ValueError):
        return None
    home = ""
    for line in config.splitlines():
        key, separator, value = line.partition("=")
        if separator and key.strip() == "home":
            home = value.strip()
            break
    if not home:
        return None
    try:
        located = subprocess.run(
            [uv_binary, "python", "dir"],
            env=dict(env),
            capture_output=True,
            text=True,
            cwd=get_safe_cwd(),
            timeout=UV_PYTHON_DIR_TIMEOUT_SECONDS,
        )
    except (OSError, subprocess.SubprocessError) as exc:
        logger.warning("Keeping the installed Python patch: cannot locate uv's Python directory: %s", exc)
        return None
    if located.returncode != 0 or not located.stdout.strip():
        logger.warning(
            "Keeping the installed Python patch: uv python dir exited %s: %s",
            located.returncode,
            (located.stderr or "").strip(),
        )
        return None
    try:
        # The first component names the installation, whether ``home`` is it
        # (Windows) or its bin (POSIX), and whether reached through uv's minor
        # link or a patch directory.
        installation = Path(home).resolve().relative_to(Path(located.stdout.strip()).resolve()).parts
    except (OSError, RuntimeError, ValueError):
        return None
    match = _UV_MANAGED_CPYTHON_DIR_RE.fullmatch(installation[0]) if installation else None
    return f"cpython-{match['minor']}-{match['platform']}" if match else None


def build_upgrade_plan(
    *,
    python_executable: str | None = None,
    uv_path: str | None = None,
    vibe_path: str | None = None,
    base_env: dict[str, str] | None = None,
    version: str | None = None,
    target_version: str | None = None,
    package_name: str | None = None,
    package_spec: str | None = None,
    core_spec: str | None = None,
) -> UpgradePlan:
    """How to install avibe: the newest release, or `version` exactly."""

    executable = python_executable or sys.executable
    # Explicit target specs belong to the selected interpreter, not the caller.
    package_spec = (
        (
            core_spec
            or pinned_package_spec(
                version,
                package_name=package_name or PACKAGE_NAME,
            )
        )
        if version
        else (package_spec or get_upgrade_package_spec())
    )
    uv_binary = find_uv_binary(uv_path=uv_path, base_env=base_env)
    if is_uv_tool_install(executable) and uv_binary:
        env = dict(base_env or os.environ)
        preflight_error = None
        # Exact repairs can recreate the whole uv environment too. Stage them
        # just like forward upgrades while the service/UI still use the old one.
        tool_dir, bin_dir, atomic = _staged_uv_environment(vibe_path)
        if atomic is None:
            preflight_error = "Cannot atomically upgrade uv installation: stable vibe launcher is unavailable"
        else:
            env["UV_TOOL_DIR"] = str(tool_dir)
            env["UV_TOOL_BIN_DIR"] = str(bin_dir)
        command = [uv_binary, "tool", "install", package_spec]
        if windows_native_arm64():
            # The staged environment is new, so uv would pick a native arm64
            # interpreter again; keep the x64 one install.ps1 chose.
            command += ["--python", WINDOWS_ARM64_UV_PYTHON]
            python_minor = WINDOWS_ARM64_UV_PYTHON
        else:
            # uv still chooses the staged interpreter: an explicit `--python`
            # would stop it from leaving a minor version that a new release
            # no longer supports. Upgrading the current minor first only gives
            # that choice its newest patch.
            python_minor = _uv_managed_python_minor(executable, uv_binary, env)
        python_upgrade_command = (
            [uv_binary, "python", "install", "--upgrade", "--no-bin", "--no-registry", python_minor]
            if python_minor
            else None
        )
        if not version:
            command.append("--upgrade")
        if version or package_spec != PACKAGE_NAME or is_legacy_uv_tool_install(executable):
            command.append("--force")
        preflight_command = None
        return UpgradePlan(
            command=command,
            env=env,
            method="uv",
            preflight_command=preflight_command,
            activation=atomic,
            preflight_error=preflight_error,
            python_upgrade_command=python_upgrade_command,
        )

    command = [executable, "-m", "pip", "install"]
    if not version:
        command.append("--upgrade")
    # Exact repairs reinstall even when metadata already matches. Forward
    # installs force only when metadata disagrees with the running files.
    if version or not installed_metadata_describes_running_code():
        command.append("--force-reinstall")
    command.append(package_spec)
    preflight_command = None
    # A forward core-only install needs a single resolver pass. Exact repairs
    # retain their availability check before changing the installed version.
    preflight_fallback_command = None
    if version:
        preflight_command = [
            executable,
            "-m",
            "pip",
            "download",
            "--dest",
            PIP_DOWNLOAD_DEST_PLACEHOLDER,
        ]
        preflight_command.extend(["--no-deps", package_spec])
    return UpgradePlan(
        command=command,
        env=dict(base_env or os.environ),
        method="pip",
        preflight_command=preflight_command,
        preflight_fallback_command=preflight_fallback_command,
    )

def get_safe_cwd() -> str:
    """Return a stable, existing absolute directory for subprocess cwd.

    The vibe service process cwd may be inside the uv tool venv directory,
    which uv deletes and recreates during upgrade.  Using the home directory
    avoids 'Current directory does not exist' errors.  Falls back to the
    system temp directory or ``/`` when HOME is unset or invalid.
    """
    for candidate in (os.path.expanduser("~"), tempfile.gettempdir(), "/"):
        if os.path.isabs(candidate) and os.path.isdir(candidate):
            return candidate
    return "/"