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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(upgrade): keep every stable launcher in step and fence silent downgrades (#2238)
Call White7a61c19486fe
diff --git a/docs/CLI.md b/docs/CLI.mdindex 1c19fefb1..400e09f1a 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -50,6 +50,7 @@ vibe- Starts Avibe if needed- Reuses already-running processes- Opens the web UI in your browser+- Only warns when it runs an install older than the last activated one: bare `vibe` is also the systemd and launchd entry, so it never refuses to start### `vibe start`@@ -58,6 +59,7 @@ Start Avibe if needed. Opens the web UI in your browser unless you suppress it.```bashvibe startvibe start --no-open-browser+vibe start --allow-downgrade```**Behavior:**@@ -65,6 +67,7 @@ vibe start --no-open-browser- Opens the setup wizard at `http://127.0.0.1:5123`- With `--no-open-browser`, keeps the service/UI lifecycle the same but does not launch a system browser window- **Preserves running processes** — Use `vibe restart` when you need an explicit restart+- Refuses to run an install older than the last activated one, for example an old `vibe` earlier on `PATH`. The error names both versions and the launcher to run instead; `--allow-downgrade` runs the older build on purpose. The desktop app only warns.### `vibe stop`@@ -86,12 +89,14 @@ Restart Avibe (main service + Web UI). The OpenCode server is terminated as part```bashvibe restartvibe restart --delay-seconds 60+vibe restart --allow-downgrade```**Behavior:**- Stops the main service and Web UI, then re-starts them- Terminates the OpenCode server- With `--delay-seconds N`, schedules the restart `N` seconds in the future so an active conversation can receive its reply before the restart lands. Prefer this form when an agent is triggering the restart from inside Slack, Discord, Telegram, Lark/Feishu, or WeChat.+- Refuses, like `vibe start`, to restart onto an install older than the last activated one unless you pass `--allow-downgrade`### `vibe status`@@ -110,6 +115,12 @@ vibe status}```+When the running service is older than the last activated install, the output+also contains a `generation_downgrade` object with the running `version` and+`generation`, the `activated_version` and `activated_generation`, and the+`launcher` that selects the newer install. Restart through that launcher to run+the new version.+### `vibe skill`Avibe gives Claude, Codex, and OpenCode one managed Skill catalog and suppresses@@ -235,6 +246,7 @@ vibe doctor repair --dry-runvibe doctor repair home-migration --yesvibe doctor repair duplicate-service-processes --yesvibe doctor repair stale-install-runtime --yes+vibe doctor repair stable-launchers --yesvibe doctor repair stale-restart-state --yesvibe doctor repair askill --yesvibe doctor repair avault --yes@@ -250,6 +262,8 @@ vibe doctor repair tmux --yes- Agent CLI availability (Claude Code, OpenCode, Codex)- Runtime home migration state- Runtime process, install, and restart metadata state+- Stable `vibe` launchers that select different installed versions (fails with both paths and versions; `stable-launchers` points them all at the newest one, and changes nothing when two installs tie as the last activation)+- A running service older than the last activated install (warns)- askill, avault, Git Runtime, Model Hub engine (CPA), Show Runtime, tmux, and Node.js readiness through one dependency diagnostic group- `vibe doctor --deep` also probes missing dependencies without downloading their bodies- managed downloads retry transient HTTP, DNS, timeout, and connection failures with bounded backoff@@ -541,6 +555,11 @@ If Avibe is already running, the command schedules a managed restart so theservice and Web UI switch to the upgraded code. If Avibe is stopped, the commandkeeps it stopped and the new version is used on the next start.+Activation moves every stable `vibe` launcher that already selects an Avibe+install to the new version together, so no `PATH` lookup keeps an older build.+Launchers that point anywhere else are never changed. See+[Upgrading](UPGRADING.md#stable-launchers).+## Service Lifecycle### Understanding "Restart" vs "Stop"diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.mdindex 24d8bda83..0505679c3 100644--- a/docs/CLI_ZH.md+++ b/docs/CLI_ZH.md@@ -48,6 +48,7 @@ vibe- 按需启动 Avibe- 复用已运行的进程- 在浏览器中打开 Web UI+- 从比最近一次激活更旧的安装运行时只给出警告:裸 `vibe` 也是 systemd 和 launchd 的启动入口,因此它不会拒绝启动### `vibe start`@@ -56,6 +57,7 @@ vibe```bashvibe startvibe start --no-open-browser+vibe start --allow-downgrade```**行为:**@@ -63,6 +65,7 @@ vibe start --no-open-browser- 打开设置向导 `http://127.0.0.1:5123`- 使用 `--no-open-browser` 时,服务和 Web UI 的启动/复用逻辑不变,但不会额外拉起系统浏览器窗口- **保留已运行的进程** — 需要明确重启时请使用 `vibe restart`+- `vibe start` 和 `vibe restart` 会拒绝运行比最近一次激活更旧的安装,例如 `PATH` 中更靠前的旧 `vibe`。错误信息会写明两个版本以及应改用的启动器;如确实要运行旧版本,请加 `--allow-downgrade`。桌面应用只给出警告。### `vibe stop`@@ -94,6 +97,10 @@ vibe status}```+如果正在运行的服务比最近一次激活的安装更旧,输出还会包含 `generation_downgrade`+对象:其中有正在运行的 `version` 和 `generation`、`activated_version` 和+`activated_generation`,以及选中较新安装的 `launcher`。通过这个启动器重启即可运行新版本。+### `vibe skill`Avibe 为 Claude、Codex 和 OpenCode 提供统一的托管 Skill Catalog,并在由 Avibe@@ -201,6 +208,7 @@ vibe doctor repair --dry-runvibe doctor repair home-migration --yesvibe doctor repair duplicate-service-processes --yesvibe doctor repair stale-install-runtime --yes+vibe doctor repair stable-launchers --yesvibe doctor repair stale-restart-state --yesvibe doctor repair askill --yesvibe doctor repair avault --yes@@ -216,6 +224,8 @@ vibe doctor repair tmux --yes- Agent CLI 可用性(Claude Code、OpenCode、Codex)- runtime home 迁移状态- runtime 进程、安装来源和重启元数据状态+- 稳定 `vibe` 启动器是否选中了不同的已安装版本(失败时列出两边的路径和版本;`stable-launchers` 会把它们都指向最新版本;两个安装同为最后激活时不做任何改动)+- 正在运行的服务是否比最近一次激活的安装更旧(警告)- 通过统一依赖诊断组检查 askill、avault、Git Runtime、Model Hub 引擎(CPA)、Show Runtime、tmux 和 Node.js- `vibe doctor --deep` 还会在不下载正文的情况下探测缺失依赖的精确地址- 托管下载会对临时 HTTP、DNS、超时和连接故障执行有界退避重试@@ -479,6 +489,10 @@ vibe upgrade如果 Avibe 已在运行,该命令会安排一次受控重启,让服务和 Web UI 切换到升级后的代码。如果 Avibe 原本是停止状态,则保持停止,下次启动时使用新版本。+激活新版本时,所有已经选中 Avibe 安装的稳定 `vibe` 启动器会一起切换到新版本,+因此任何 `PATH` 查找都不会留在旧版本上。指向其他位置的启动器永远不会被修改。+参见 [Upgrading](UPGRADING.md#stable-launchers)。+## 服务生命周期### 理解「重启」与「停止」的区别diff --git a/docs/COMMANDS.md b/docs/COMMANDS.mdindex 5519bd8e6..6b7ac197e 100644--- a/docs/COMMANDS.md+++ b/docs/COMMANDS.md@@ -547,12 +547,14 @@ vibe- starts the main service if it is not already running- opens the Web UI- preserves already-running service, Web UI, and OpenCode processes; use `vibe restart` for an explicit restart+- only warns when it runs an install older than the last activated one, because it is also the systemd and launchd entry### `vibe start````bashvibe startvibe start --no-open-browser+vibe start --allow-downgrade```- `--no-open-browser` keeps the same start/reuse semantics but suppresses the browser launch. This is the supported contract for desktop shells that own their own WebView.@@ -560,6 +562,7 @@ vibe start --no-open-browser- starts the main service if it is not already running- opens the Web UI- preserves already-running service, Web UI, and OpenCode processes; use `vibe restart` for an explicit restart+- refuses to run an install older than the last activated one, naming both versions and the launcher to run instead; `--allow-downgrade` runs the older build on purpose, and the desktop app only warns### `vibe stop`@@ -596,6 +599,7 @@ Recommended usage:- prefer `vibe restart --delay-seconds 60` when an agent triggers the restart from an active conversation- use plain `vibe restart` when the user explicitly wants the restart to happen immediately+- like `vibe start`, refuses to restart onto an install older than the last activated one unless `--allow-downgrade` is passed### `vibe status`@@ -604,6 +608,7 @@ vibe status```- prints runtime status JSON+- includes `generation_downgrade` when the running service is older than the last activated install, naming both versions and the launcher that selects the newer one### `vibe doctor`@@ -616,6 +621,7 @@ vibe doctor- checks backend CLI availability- checks runtime home migration state- checks runtime process, install, and restart metadata state+- fails when stable `vibe` launchers select different installed versions, naming each path and version, and warns when the running service is older than the last activated install- checks askill, avault, Git Runtime, Model Hub engine (CPA), Show Runtime, tmux, and Node.js through one dependency diagnostic group- `vibe doctor --deep` probes missing dependency endpoints without downloading their bodies- managed downloads retry transient HTTP, DNS, timeout, and connection failures with bounded backoff@@ -627,6 +633,7 @@ vibe doctor repair --dry-runvibe doctor repair home-migration --yesvibe doctor repair duplicate-service-processes --yesvibe doctor repair stale-install-runtime --yes+vibe doctor repair stable-launchers --yesvibe doctor repair stale-restart-state --yesvibe doctor repair askill --yesvibe doctor repair avault --yes@@ -698,6 +705,7 @@ vibe upgrade```- upgrades Avibe using the selected upgrade plan+- moves every stable `vibe` launcher that already selects an Avibe install to the new version together; launchers pointing elsewhere are never changed- schedules a managed restart after success when Avibe is already running- keeps Avibe stopped when it was not running before the upgradediff --git a/docs/COMMANDS_ZH.md b/docs/COMMANDS_ZH.mdindex ee9115ea9..ab199d471 100644--- a/docs/COMMANDS_ZH.md+++ b/docs/COMMANDS_ZH.md@@ -525,12 +525,14 @@ vibe- 如果主服务尚未运行,则启动主服务- 打开 Web UI- 保留已运行的服务、Web UI 与 OpenCode server;需要明确重启时使用 `vibe restart`+- 从比最近一次激活更旧的安装运行时只给出警告,因为它也是 systemd 和 launchd 的启动入口### `vibe start````bashvibe startvibe start --no-open-browser+vibe start --allow-downgrade```- `--no-open-browser` 会保留相同的启动/复用语义,但不会自动打开浏览器;桌面壳这类自带 WebView 的调用方应使用这个契约。@@ -538,6 +540,7 @@ vibe start --no-open-browser- 如果主服务尚未运行,则启动主服务- 打开 Web UI- 保留已运行的服务、Web UI 与 OpenCode server;需要明确重启时使用 `vibe restart`+- 拒绝运行比最近一次激活更旧的安装,并写明两个版本以及应改用的启动器;`--allow-downgrade` 表示有意运行旧版本,桌面应用只给出警告### `vibe stop`@@ -574,6 +577,7 @@ vibe restart --delay-seconds 60- 如果是 Agent 在活跃会话里触发重启,优先使用 `vibe restart --delay-seconds 60`- 只有用户明确要求立刻重启时,再使用普通 `vibe restart`+- 与 `vibe start` 相同,除非传入 `--allow-downgrade`,否则拒绝重启到比最近一次激活更旧的安装### `vibe status`@@ -582,6 +586,7 @@ vibe status```- 输出运行状态 JSON+- 如果正在运行的服务比最近一次激活的安装更旧,会包含 `generation_downgrade`,写明两个版本以及选中较新安装的启动器### `vibe doctor`@@ -594,6 +599,7 @@ vibe doctor- 检查 backend CLI 是否可用- 检查 runtime home 迁移状态- 检查 runtime 进程、安装来源和重启元数据状态+- 稳定 `vibe` 启动器选中了不同的已安装版本时报失败并列出每个路径和版本;正在运行的服务比最近一次激活的安装更旧时给出警告- 通过统一依赖诊断组检查 askill、avault、Git Runtime、Model Hub 引擎(CPA)、Show Runtime、tmux 和 Node.js- `vibe doctor --deep` 会在不下载正文的情况下探测缺失依赖的地址- 托管下载会对临时 HTTP、DNS、超时和连接故障执行有界退避重试@@ -605,6 +611,7 @@ vibe doctor repair --dry-runvibe doctor repair home-migration --yesvibe doctor repair duplicate-service-processes --yesvibe doctor repair stale-install-runtime --yes+vibe doctor repair stable-launchers --yesvibe doctor repair stale-restart-state --yesvibe doctor repair askill --yesvibe doctor repair avault --yes@@ -676,6 +683,7 @@ vibe upgrade```- 按升级计划升级 Avibe+- 所有已经选中 Avibe 安装的稳定 `vibe` 启动器会一起切换到新版本;指向其他位置的启动器永远不会被修改- 如果 Avibe 已在运行,成功后安排一次受控重启- 如果 Avibe 原本未运行,则保持停止状态diff --git a/docs/INSTALL_FOR_AI.md b/docs/INSTALL_FOR_AI.mdindex 37feec399..7b3a59bf7 100644--- a/docs/INSTALL_FOR_AI.md+++ b/docs/INSTALL_FOR_AI.md@@ -54,6 +54,8 @@ vibe doctorIf the installer cannot use PyPI, it falls back to GitHub. If `vibe` is installed but not on `PATH`, inspect the installer's final output and help the user add the reported bin directory to their shell profile.+When the installer runs as root, it installs the launcher at `/usr/local/bin/vibe`, the one supported location for root installs. Later upgrades move every stable `vibe` launcher that selects this install together; see [Upgrading](UPGRADING.md#stable-launchers).+## Step 3: Install at Least One Coding AgentAsk the user which backend they want first. Recommended default: OpenCode for low-friction setup, Claude Code for deeper coding work, Codex for OpenAI workflows.@@ -171,6 +173,8 @@ does not need an IM chat to complete this smoke test.| Symptom | What to check || --- | --- || `vibe` command missing | Shell `PATH`, uv tool bin directory, installer output |+| `vibe doctor` reports launchers on different versions | Run `vibe doctor repair stable-launchers` |+| `vibe start` refuses an older install | Run the launcher named in the error; pass `--allow-downgrade` only to run the older build on purpose || Agent not found | Install the selected agent CLI and verify it is on `PATH` || Slack bot silent | App installed, Socket Mode token, bot token scopes, bot invited to channel || Telegram group silent | Bot privacy mode, mention requirements, discovered chat list |diff --git a/docs/INSTALL_FOR_AI_ZH.md b/docs/INSTALL_FOR_AI_ZH.mdindex 18adb2b73..becbc391f 100644--- a/docs/INSTALL_FOR_AI_ZH.md+++ b/docs/INSTALL_FOR_AI_ZH.md@@ -54,6 +54,8 @@ vibe doctor如果安装器无法使用 PyPI,会自动回退到 GitHub。如果已经安装但找不到 `vibe` 命令,查看安装器最后输出的 bin 目录,并帮用户把它加入 shell `PATH`。+以 root 身份运行安装器时,启动器会安装到 `/usr/local/bin/vibe`,这是 root 安装唯一支持的位置。之后的升级会让所有选中这份安装的稳定 `vibe` 启动器一起切换版本,参见 [Upgrading](UPGRADING.md#stable-launchers)。+## 第 3 步:至少安装一个编码 Agent先问用户想用哪个后端。默认建议:OpenCode 上手最轻,Claude Code 适合复杂编码任务,Codex 适合 OpenAI 工作流。@@ -154,6 +156,8 @@ vibe doctor| 现象 | 检查点 || --- | --- || 找不到 `vibe` 命令 | shell `PATH`、uv tool bin 目录、安装器输出 |+| `vibe doctor` 报告启动器版本不一致 | 运行 `vibe doctor repair stable-launchers` |+| `vibe start` 拒绝运行旧安装 | 改用错误信息中给出的启动器;只有确实要运行旧版本时才加 `--allow-downgrade` || 找不到 agent | 安装所选 agent CLI,并确认它在 `PATH` 里 || Slack 没反应 | App 是否安装、Socket Mode token、bot token scopes、bot 是否被邀请进频道 || Telegram 群里没反应 | Bot privacy mode、是否需要 @、聊天是否已被发现 |diff --git a/docs/UPGRADING.md b/docs/UPGRADING.mdindex 719b20624..17232480f 100644--- a/docs/UPGRADING.md+++ b/docs/UPGRADING.md@@ -1,5 +1,43 @@# Upgrading+## Stable launchers++`vibe upgrade` and the installers activate a new version by repointing every+stable `vibe` launcher that already selects an Avibe install on this machine:+the one you ran, every `vibe` on `PATH`, uv's tool bin directory, and the+installer locations `~/.local/bin`, `~/bin`, `/usr/local/bin` and+`/opt/homebrew/bin`. A launcher that points anywhere else, such as a separate uv+tool environment or a wrapper script, is never changed. A launcher is managed+only under the name its install exports, `vibe` or `vibe.exe` on Windows, so an+alias under any other name is left alone.++A root install has one supported launcher: `/usr/local/bin/vibe`. The installer+chooses it when run as root even if another directory on `PATH` already holds a+`vibe`, and later upgrades keep that other launcher on the same version.++If a launcher cannot be moved, for example because it is not writable,+`vibe doctor` fails and lists each launcher with its version. Run+`vibe doctor repair stable-launchers` to point all of them at the newest+installed version, or at the most recent install when two share a version. A+launcher that another installer replaced in the meantime is left as it is, and+the repair fails if the launchers still disagree afterwards. When two different+installs tie as the last activation, the repair cannot choose between them: it+changes nothing and asks you to run the installer again, whose new install moves+every launcher. `vibe doctor` still lists the split, and the downgrade check+below treats neither install as older. On Windows, the launcher you run the repair+from cannot be replaced while it runs, so the repair moves every other launcher+and names the launcher to run it from again.++`vibe start` and `vibe restart` refuse to run an install older than the last+activated one and name the launcher to run instead. An earlier install of the+same version, such as one a reinstall left behind, counts as older; an install+whose version cannot be read never does. Pass `--allow-downgrade` to+run the older build on purpose. Bare `vibe`, which systemd and launchd use, and+the desktop app only warn, so a supervised service still comes up. While the+running service is older than the last activation, `vibe status` includes a+`generation_downgrade` object and `vibe doctor` warns; restart through the named+launcher to run the new version.+## Memory removalAvibe no longer includes the optional Memory product. Upgrading does not deletediff --git a/install.sh b/install.shindex 54b3dbb36..fa1583bb7 100755--- a/install.sh+++ b/install.sh@@ -19,6 +19,9 @@ PACKAGE_NAME="avibe-os"NODE_MINIMUM_REQUIREMENT="20.19+ or 22.12+"VIBE_BIN_PATH=""VIBE_TOOL_BIN_DIR=""+# A root install has one supported stable launcher, whatever PATH order the+# shell happens to have. Upgrades keep every other managed launcher in step.+ROOT_TOOL_BIN_DIR="/usr/local/bin"VIBE_CANDIDATE_BIN_PATH=""LAUNCH_AFTER_INSTALL=""AVIBE_LAUNCHED=""@@ -174,6 +177,12 @@ choose_tool_bin_dir() {local dirlocal fallback_sbin_dir=""+ if [ "$(id -u 2>/dev/null || echo 1)" = "0" ] && is_absolute_dir "$ROOT_TOOL_BIN_DIR" &&+ launcher_destination_is_available "$ROOT_TOOL_BIN_DIR" && ensure_writable_dir "$ROOT_TOOL_BIN_DIR"; then+ echo "$ROOT_TOOL_BIN_DIR"+ return 0+ fi+local old_ifs="$IFS"IFS=":"# Reinstall through the established public entrypoint before choosing a newdiff --git a/tests/conftest.py b/tests/conftest.pyindex 9f734b09a..87bd32e18 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -215,6 +215,7 @@ def _isolate_vibe_remote_home(request, tmp_path, monkeypatch):"AVIBE_CALLER_REMOTE","AVIBE_CALLER_RESOURCE_CONTEXT","VIBE_INTERNAL_DISPATCH_SOCKET",+ "VIBE_CURRENT_EXECUTABLE","AVIBE_SKILL_WORKING_DIR","AVIBE_SKILL_PROJECT_BASE","AVIBE_SKILL_HOME",diff --git a/tests/test_install_generation_retirement.py b/tests/test_install_generation_retirement.pyindex 3f960cc95..77b92c17b 100644--- a/tests/test_install_generation_retirement.py+++ b/tests/test_install_generation_retirement.py@@ -727,6 +727,81 @@ def test_alias_invocation_cannot_retire_the_path_selected_command(assert subprocess.run([str(launcher)], check=False).returncode == 0[email protected]("invoked", ["installer", "uv"])+def test_root_launchers_move_together_through_either_activation(installation, monkeypatch, tmp_path, invoked):+ """#2081: a root host has the installer's PATH launcher and uv's ~/.local/bin one."""+ root, installer_launcher = installation+ uv_launcher = tmp_path / "root-home" / ".local" / "bin" / "vibe"+ foreign = tmp_path / "foreign-bin" / "vibe"+ foreign_target = tmp_path / "foreign-target"+ uv_launcher.parent.mkdir(parents=True)+ foreign.parent.mkdir()+ foreign_target.write_text("#!/bin/sh\nexit 0\n")+ foreign_target.chmod(0o755)+ foreign.symlink_to(foreign_target)+ # The root shell's PATH does not include ~/.local/bin; only its fixed+ # installer location makes it discoverable.+ monkeypatch.setattr(upgrade, "INSTALLER_LAUNCHER_DIRS", (str(uv_launcher.parent), str(foreign.parent)))+ old = activate(root, installer_launcher, "old")+ uv_launcher.symlink_to(old)++ current = activate(root, installer_launcher if invoked == "installer" else uv_launcher, "current")++ assert installer_launcher.resolve() == current.resolve()+ assert uv_launcher.resolve() == current.resolve()+ assert {path.name for path in root.iterdir()} == {"current"}+ assert os.readlink(foreign) == str(foreign_target)+++def test_a_launcher_that_cannot_move_keeps_its_generation(installation, monkeypatch, tmp_path):+ root, launcher = installation+ peer = tmp_path / "root-home" / ".local" / "bin" / "vibe"+ peer.parent.mkdir(parents=True)+ monkeypatch.setattr(upgrade, "INSTALLER_LAUNCHER_DIRS", (str(peer.parent),))+ old = activate(root, launcher, "old")+ peer.symlink_to(old)++ def read_only(path, target):+ raise PermissionError(f"{path} is read-only")++ monkeypatch.setattr(upgrade, "_activate_launcher_target_locked", read_only)+ current = activate(root, launcher, "current")++ assert launcher.resolve() == current.resolve()+ assert peer.resolve() == old.resolve()+ assert {path.name for path in root.iterdir()} == {"old", "current"}+ assert subprocess.run([str(peer)], check=False).returncode == 0+++def test_a_peer_replaced_after_discovery_is_left_alone(installation, monkeypatch, tmp_path):+ """The upgrade lock serializes Avibe, not uv, another installer or an administrator."""+ root, launcher = installation+ peer = tmp_path / "root-home" / ".local" / "bin" / "vibe"+ foreign_target = tmp_path / "foreign-target"+ peer.parent.mkdir(parents=True)+ foreign_target.write_text("#!/bin/sh\nexit 0\n")+ foreign_target.chmod(0o755)+ monkeypatch.setattr(upgrade, "INSTALLER_LAUNCHER_DIRS", (str(peer.parent),))+ old = activate(root, launcher, "old")+ peer.symlink_to(old)+ discover = upgrade.managed_stable_launchers+ replaced = []++ def replaced_after_discovery(*launchers):+ found = discover(*launchers)+ if not replaced:+ peer.unlink()+ peer.symlink_to(foreign_target)+ replaced.append(peer)+ return found++ monkeypatch.setattr(upgrade, "managed_stable_launchers", replaced_after_discovery)+ current = activate(root, launcher, "current")++ assert launcher.resolve() == current.resolve()+ assert os.readlink(peer) == str(foreign_target)++def test_partial_removal_retains_uv_evidence_and_next_pass_finishes(installation, monkeypatch):root, launcher = installationold = candidate(root, "old")diff --git a/tests/test_install_script.py b/tests/test_install_script.pyindex 4e7c83f4a..795805e9b 100644--- a/tests/test_install_script.py+++ b/tests/test_install_script.py@@ -1181,6 +1181,28 @@ def test_install_script_activation_fallback_refuses_an_unowned_destination(tmp_passert not (home_dir / ".avibe" / "runtime" / "install-generations").exists()[email protected]("uid, chosen", [("0", "root-bin"), ("1000", "existing-bin")])+def test_root_install_selects_one_stable_launcher_regardless_of_path(tmp_path, uid, chosen):+ """#2081: a root shell's PATH order must not pick a second stable launcher."""+ home_dir = tmp_path / "home"+ existing_bin = tmp_path / "existing-bin"+ root_bin = tmp_path / "root-bin"+ existing_bin.mkdir(parents=True)+ home_dir.mkdir()+ _write_console_launcher(existing_bin / "vibe", "#!/bin/sh\necho old\n")+ source = INSTALL_SCRIPT.read_text().rsplit('\nmain "$@"', 1)[0]+ result = _run(+ source + f"\nid() {{ echo {uid}; }}\nROOT_TOOL_BIN_DIR={str(root_bin)!r}\nchoose_tool_bin_dir\n",+ cwd=tmp_path,+ env={+ **os.environ, "HOME": str(home_dir), "AVIBE_HOME": str(home_dir / ".avibe"),+ "PATH": os.pathsep.join([str(existing_bin), "/usr/bin", "/bin"]),+ },+ )+ assert result.returncode == 0, result.stdout + result.stderr+ assert result.stdout.strip().splitlines()[-1] == str(tmp_path / chosen)++def test_powershell_publishes_complete_installer_marker_before_source_snapshot():source = INSTALL_POWERSHELL.read_text(encoding="utf-8")# PowerShell execution/convergence remains a native Windows CI gate.diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.pyindex e8af51435..3de4d88b8 100644--- a/tests/test_vibe_cli.py+++ b/tests/test_vibe_cli.py@@ -1,5 +1,6 @@import asyncioimport builtins+import contextlibimport hashlibimport jsonimport os@@ -8,6 +9,7 @@ import reimport signalimport shleximport sqlite3+import subprocessimport sysimport threadingimport time@@ -20,6 +22,8 @@ from vibe import runtimefrom vibe import clifrom vibe import internal_clientfrom vibe import remote_access+from vibe import upgrade+from storage.lock import MigrationLockTimeoutdef _make_fake_uv_tool(@@ -236,6 +240,364 @@ def test_local_cli_installation_items_fails_for_unknown_sqlite_revision(monkeypa)+def _managed_generation(name: str, version: str, export: str = "vibe") -> Path:+ """Build one uv-shaped install generation that reports ``version``."""++ generation = upgrade.atomic_uv_install_root() / name+ environment = generation / "uv" / "tools" / "avibe-os"+ target = environment / "bin" / "vibe"+ target.parent.mkdir(parents=True)+ target.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")+ target.chmod(0o755)+ (environment / "pyvenv.cfg").write_text("include-system-site-packages = false\n", encoding="utf-8")+ metadata = environment / "lib" / "python3.12" / "site-packages" / f"avibe_os-{version}.dist-info" / "METADATA"+ metadata.parent.mkdir(parents=True)+ metadata.write_text(f"Metadata-Version: 2.1\nName: avibe-os\nVersion: {version}\n", encoding="utf-8")+ exported = generation / "bin" / export+ exported.parent.mkdir()+ exported.symlink_to(target)+ (environment / "uv-receipt.toml").write_text(+ '[tool]\nrequirements = [{ name = "avibe-os" }]\n'+ f'entrypoints = [{{ name = "vibe", install-path = {json.dumps(str(exported))} }}]\n',+ encoding="utf-8",+ )+ return generation+++def split_launchers(monkeypatch, tmp_path):+ """A PATH launcher left on 1.4.0 beside an installer launcher on 1.5.0."""++ old = _managed_generation("old", "1.4.0")+ new = _managed_generation("new", "1.5.0")+ path_launcher = tmp_path / "usr-local-bin" / "vibe"+ installer_launcher = tmp_path / "home" / ".local" / "bin" / "vibe"+ for launcher, generation in ((path_launcher, old), (installer_launcher, new)):+ launcher.parent.mkdir(parents=True)+ launcher.symlink_to(generation / "bin" / "vibe")+ monkeypatch.setenv("PATH", str(path_launcher.parent))+ monkeypatch.delenv("UV_TOOL_BIN_DIR", raising=False)+ monkeypatch.delenv(upgrade.DESKTOP_MANAGED_RUNTIME_ENV, raising=False)+ monkeypatch.setattr(upgrade, "INSTALLER_LAUNCHER_DIRS", (str(installer_launcher.parent),))+ return SimpleNamespace(old=old, new=new, path_launcher=path_launcher, installer_launcher=installer_launcher)+++def _reinstall_same_version(split) -> str:+ """Make the stale install an earlier install of the activated version."""++ metadata = next(split.old.glob("uv/tools/avibe-os/lib/*/site-packages/*.dist-info/METADATA"))+ metadata.write_text("Metadata-Version: 2.1\nName: avibe-os\nVersion: 1.5.0\n", encoding="utf-8")+ for generation, installed_at in ((split.old, 1_000_000), (split.new, 2_000_000)):+ os.utime(generation / "uv" / "tools" / "avibe-os" / "uv-receipt.toml", (installed_at, installed_at))+ return "1.5.0"++[email protected]("newer", ["installer-location", "invoking-launcher", "same-version-reinstall"])+def test_doctor_names_split_stable_launchers_and_repair_moves_the_stale_one(split_launchers, monkeypatch, newer):+ split = split_launchers+ old_version = "1.4.0"+ if newer == "invoking-launcher":+ # Activated through a launcher outside PATH and every fixed location.+ monkeypatch.setattr(upgrade, "INSTALLER_LAUNCHER_DIRS", ())+ monkeypatch.setenv(upgrade.CURRENT_VIBE_EXECUTABLE_ENV, str(split.installer_launcher))+ if newer == "same-version-reinstall":+ # A reinstall of the same version whose PATH peer, found first, stayed behind.+ old_version = _reinstall_same_version(split)++ items = cli._stable_launcher_items()++ assert [item["status"] for item in items] == ["fail"]+ item = items[0]+ assert f"{split.path_launcher} -> {old_version} ({split.old})" in item["message"]+ assert f"{split.installer_launcher} -> 1.5.0 ({split.new})" in item["message"]+ assert f"{split.installer_launcher} doctor repair stable-launchers" in item["action"]+ assert item["repair"]["command"] == "vibe doctor repair stable-launchers"++ result = cli._repair_stable_launchers()++ assert result["status"] == "repaired"+ assert result["launchers"] == [str(split.path_launcher)]+ assert split.path_launcher.resolve() == (split.new / "bin" / "vibe").resolve()+ assert split.installer_launcher.resolve() == (split.new / "bin" / "vibe").resolve()+ assert [item["status"] for item in cli._stable_launcher_items()] == ["pass"]+++def test_a_launcher_is_managed_only_under_a_name_its_install_exports(split_launchers, monkeypatch):+ """Copy-marker validation and every move use ``generation/bin/<launcher name>``."""++ from vibe.install_generations import _uv_installation++ split = split_launchers+ exe = _managed_generation("exe", "1.6.0", export="vibe.exe")+ exe_launcher = split.installer_launcher.with_name("vibe.exe")+ exe_launcher.symlink_to(exe / "bin" / "vibe.exe")+ # An alias whose name the install it selects does not export.+ alias = split.path_launcher.parent.parent / "alias" / "vibe.exe"+ alias.parent.mkdir()+ alias.symlink_to(split.old / "bin" / "vibe")+ monkeypatch.setenv(upgrade.CURRENT_VIBE_EXECUTABLE_ENV, str(alias))++ managed = upgrade.managed_stable_launchers(exe_launcher)++ assert [launcher for launcher, _generation in managed] == [+ exe_launcher, split.path_launcher, split.installer_launcher,+ ]+ for launcher, generation in managed:+ assert launcher.name in {export.name for export in _uv_installation(generation)[1]}++ result = cli._repair_stable_launchers()++ assert result["status"] == "repaired"+ assert alias.resolve() == (split.old / "bin" / "vibe").resolve()+++def test_tied_installs_are_never_ranked_by_discovery_order(split_launchers, monkeypatch):+ """Two installs of one version with identical receipt times tie as the last activation."""++ split = split_launchers+ _reinstall_same_version(split)+ for generation in (split.old, split.new):+ os.utime(generation / "uv" / "tools" / "avibe-os" / "uv-receipt.toml", (1_500_000, 1_500_000))+ monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")++ item, = cli._stable_launcher_items()++ assert item["status"] == "fail"+ for launcher, generation in ((split.path_launcher, split.old), (split.installer_launcher, split.new)):+ assert f"{launcher} -> 1.5.0 ({generation})" in item["message"]+ assert f"{launcher} -> 1.5.0 ({generation})" in item["action"]+ assert "repair" not in item+ assert "Avibe 安装程序" in item["action"]++ result = cli._repair_stable_launchers()++ assert result["status"] == "failed"+ assert result["reason"] == "stable_launchers_tied"+ assert "没有改动任何启动器" in result["message"]+ assert split.path_launcher.resolve() == (split.old / "bin" / "vibe").resolve()+ assert split.installer_launcher.resolve() == (split.new / "bin" / "vibe").resolve()++ ran = []+ monkeypatch.setattr(cli, "cmd_start", lambda **_kwargs: ran.append("start") or 0)+ parser = cli.build_parser()+ for generation in (split.old, split.new):+ monkeypatch.setattr(cli, "current_generation", lambda generation=generation: generation)+ with pytest.raises(SystemExit) as exc_info:+ cli._dispatch_parsed_command(parser, parser.parse_args(["start"]))+ assert exc_info.value.code == 0+ assert ran == ["start", "start"]++[email protected]("failure", ["unwritable-launcher", "missing-export", "lock-busy"])+def test_stable_launcher_repair_failures_are_localized(split_launchers, monkeypatch, failure):+ """No exception text reaches the localized repair message."""++ split = split_launchers+ monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")+ reason, fragment = {+ "unwritable-launcher": ("stable_launcher_move_failed", "请确认你有权限写入它"),+ "missing-export": ("stable_launcher_move_failed", "请确认你有权限写入它"),+ "lock-busy": ("upgrade_lock_busy", "另一个 Avibe 安装、升级或修复正在进行"),+ }[failure]+ if failure == "unwritable-launcher":+ if os.name != "posix" or os.geteuid() == 0:+ pytest.skip("requires POSIX non-root permissions")+ split.path_launcher.parent.chmod(0o555)+ elif failure == "missing-export":+ (split.new / "bin" / "vibe").unlink()+ else:+ @contextlib.contextmanager+ def busy(**_kwargs):+ raise MigrationLockTimeout("Timed out waiting for migration lock")+ yield++ monkeypatch.setattr(cli, "atomic_upgrade_lock", busy)++ try:+ result = cli._repair_stable_launchers()+ finally:+ split.path_launcher.parent.chmod(0o755)++ assert result["status"] == "failed"+ assert result["reason"] == reason+ assert fragment in result["message"]+ assert not any(text in result["message"] for text in ("Permission", "not executable", "Timed out"))+ assert split.path_launcher.resolve() == (split.old / "bin" / "vibe").resolve()+++def test_windows_repair_leaves_the_launcher_it_runs_from_and_names_the_target(split_launchers, monkeypatch):+ """Windows cannot replace a running image, so the repair names a launcher that can."""++ split = split_launchers+ peer = split.path_launcher.parent.parent / "home-bin" / "vibe"+ peer.parent.mkdir()+ peer.symlink_to(split.old / "bin" / "vibe")+ monkeypatch.setattr(upgrade, "INSTALLER_LAUNCHER_DIRS", (str(split.installer_launcher.parent), str(peer.parent)))+ monkeypatch.setattr(cli, "_configured_cli_language", lambda: "zh")+ # Stand-in for Windows holding the stale PATH launcher's image open.+ monkeypatch.setattr(cli, "launcher_is_current_process", lambda launcher: Path(launcher) == split.path_launcher)++ result = cli._repair_stable_launchers()++ assert result["status"] == "failed"+ assert result["reason"] == "stable_launcher_running"+ assert result["launchers"] == [str(peer)]+ assert str(split.path_launcher) in result["message"] and "Windows 无法" in result["message"]+ commands = [shlex.split(command) for command in re.findall(r"`([^`]+)`", result["message"])]+ assert [str(split.installer_launcher), "doctor", "repair", "stable-launchers"] in commands+ assert peer.resolve() == (split.new / "bin" / "vibe").resolve()+ assert split.path_launcher.resolve() == (split.old / "bin" / "vibe").resolve()+++def test_recovery_commands_stay_pasteable_from_a_launcher_path_with_spaces(split_launchers, monkeypatch, capsys):+ split = split_launchers+ spaced = split.installer_launcher.parent.parent / "Program Files" / "vibe"+ spaced.parent.mkdir()+ split.installer_launcher.rename(spaced)+ monkeypatch.setattr(upgrade, "INSTALLER_LAUNCHER_DIRS", (str(spaced.parent),))+ monkeypatch.setattr(cli, "current_generation", lambda: split.old)+ monkeypatch.setattr(cli, "cmd_vibe", lambda: 0)+ monkeypatch.setattr(runtime, "resolve_service_owner_pid", lambda **_kwargs: 4242)+ monkeypatch.setattr(cli, "process_generation", lambda pid: split.old if pid == 4242 else None)+ parser = cli.build_parser()++ def commands(text: str) -> list[list[str]]:+ return [shlex.split(command) for command in re.findall(r"`([^`]+)`", text)]++ repair = [str(spaced), "doctor", "repair", "stable-launchers"]+ assert repair in commands(cli._stable_launcher_items()[0]["action"])+ assert [str(spaced), "restart"] in commands(cli._service_generation_items()[0]["action"])+ for argv, expected in ((["start"], [[str(spaced), "start"]]), ([], [[str(spaced)], repair])):+ with pytest.raises(SystemExit):+ cli._dispatch_parsed_command(parser, parser.parse_args(argv))+ error_commands = commands(capsys.readouterr().err)+ assert all(command in error_commands for command in expected), (argv, error_commands)+++def test_stable_launcher_repair_fails_unless_the_launchers_converge(split_launchers, monkeypatch):+ """The upgrade lock does not stop another installer moving a launcher mid-repair."""++ split = split_launchers+ other = _managed_generation("other", "1.3.0")+ move = cli.move_managed_launcher_locked++ def raced(launcher, selected, target):+ launcher.unlink()+ launcher.symlink_to(other / "bin" / "vibe")+ return move(launcher, selected, target)++ monkeypatch.setattr(cli, "move_managed_launcher_locked", raced)++ result = cli._repair_stable_launchers()++ assert result["status"] == "failed"+ assert f"{split.path_launcher} -> 1.3.0 ({other})" in result["message"]+ assert split.path_launcher.resolve() == (other / "bin" / "vibe").resolve()+++def test_unreadable_version_metadata_is_unknown_and_never_blocks_start(split_launchers, monkeypatch):+ split = split_launchers+ metadata = next(split.old.glob("uv/tools/avibe-os/lib/*/site-packages/*.dist-info/METADATA"))+ metadata.write_bytes(b"Metadata-Version: 2.1\nName: avibe-os\nVersion: 1.4.0\nSummary: \xff\xfe\n")+ ran = []+ monkeypatch.setattr(cli, "current_generation", lambda: split.old)+ monkeypatch.setattr(cli, "cmd_start", lambda **_kwargs: ran.append("start") or 0)+ parser = cli.build_parser()++ with pytest.raises(SystemExit) as exc_info:+ cli._dispatch_parsed_command(parser, parser.parse_args(["start"]))++ assert exc_info.value.code == 0+ assert ran == ["start"]+ assert f"{split.path_launcher} -> unknown ({split.old})" in cli._stable_launcher_items()[0]["message"]++[email protected]("same_version", [False, True], ids=["older-version", "same-version-reinstall"])[email protected]("command", ["start", "restart"])+def test_an_older_install_refuses_start_and_restart_unless_downgrade_is_explicit(+ split_launchers, monkeypatch, capsys, command, same_version,+):+ split = split_launchers+ old_version = _reinstall_same_version(split) if same_version else "1.4.0"+ ran = []+ monkeypatch.setattr(cli, "current_generation", lambda: split.old)+ monkeypatch.setattr(cli, "cmd_start", lambda **_kwargs: ran.append("start") or 0)+ monkeypatch.setattr(cli, "_cmd_restart_with_delay", lambda _delay: ran.append("restart") or 0)+ parser = cli.build_parser()++ with pytest.raises(SystemExit) as refused:+ cli._dispatch_parsed_command(parser, parser.parse_args([command]))++ assert refused.value.code == 1+ assert ran == []+ error = capsys.readouterr().err+ for fragment in (old_version, str(split.old), "1.5.0", str(split.new), f"{split.installer_launcher} {command}"):+ assert fragment in error+ assert "--allow-downgrade" in error++ with pytest.raises(SystemExit) as allowed:+ cli._dispatch_parsed_command(parser, parser.parse_args([command, "--allow-downgrade"]))++ assert allowed.value.code == 0+ assert ran == [command]+ assert "1.5.0" in capsys.readouterr().err++[email protected]("argv,desktop", [([], False), (["start"], True)])+def test_a_supervisor_launch_of_an_older_install_is_warned_not_refused(+ split_launchers, monkeypatch, capsys, argv, desktop,+):+ split = split_launchers+ ran = []+ monkeypatch.setattr(cli, "current_generation", lambda: split.old)+ monkeypatch.setattr(cli, "cmd_vibe", lambda: ran.append("vibe") or 0)+ monkeypatch.setattr(cli, "cmd_start", lambda **_kwargs: ran.append("start") or 0)+ if desktop:+ monkeypatch.setenv(upgrade.DESKTOP_MANAGED_RUNTIME_ENV, "1")+ parser = cli.build_parser()++ with pytest.raises(SystemExit) as exc_info:+ cli._dispatch_parsed_command(parser, parser.parse_args(argv))++ assert exc_info.value.code == 0+ assert ran == [argv[0] if argv else "vibe"]+ error = capsys.readouterr().err+ assert "1.4.0" in error and "1.5.0" in error+ assert f"{split.installer_launcher} doctor repair stable-launchers" in error+++def test_status_and_doctor_report_a_service_older_than_the_last_activation(split_launchers, monkeypatch):+ split = split_launchers+ # A real process whose argv names the old install, as a supervisor+ # started from the stale launcher would look.+ service = subprocess.Popen(+ [sys.executable, "-c", "import time; time.sleep(60)", str(split.old / "uv" / "tools" / "avibe-os" / "bin" / "vibe")]+ )+ try:+ monkeypatch.setattr(runtime, "service_instance_lock_available", lambda: (False, service.pid))+ expected = {+ "generation": str(split.old),+ "version": "1.4.0",+ "activated_generation": str(split.new),+ "activated_version": "1.5.0",+ "launcher": str(split.installer_launcher),+ }++ status = json.loads(runtime.render_status(detect_extra_processes=False))+ items = cli._service_generation_items()+ finally:+ service.kill()+ service.wait()++ assert status["service_owner_pid"] == service.pid+ assert status["generation_downgrade"] == expected+ assert [item["status"] for item in items] == ["warn"]+ assert "1.4.0" in items[0]["message"] and "1.5.0" in items[0]["message"]+ assert str(split.new) in items[0]["message"]+ assert f"{split.installer_launcher} restart" in items[0]["action"]+ assert items[0]["generation_downgrade"] == expected++def test_default_config_written(tmp_path, monkeypatch):monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")runtime.ensure_dirs()diff --git a/vibe/cli.py b/vibe/cli.pyindex 6376ecafc..73481c8a8 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -83,22 +83,30 @@ from vibe.upgrade import (atomic_upgrade_lock,build_upgrade_plan,cache_running_vibe_path,+ current_generation,execute_upgrade_plan,defer_upgrade_activation,+ generation_downgrade,get_latest_version_info,get_safe_cwd,is_desktop_managed_runtime,_launcher_generation,_candidate_python,launcher_is_current_process,+ move_managed_launcher_locked,+ newest_launcher_selection,+ process_generation,restart_is_pending,restart_record_is_pending,discard_atomic_uv_install_generation,should_skip_show_runtime_prepare,+ stable_launcher_selections,+ top_ranked_selections,UPGRADE_INSTALL_TIMEOUT_SECONDS,verify_upgrade_candidate,)from storage.db import create_sqlite_engine+from storage.lock import MigrationLockTimeoutfrom storage.background import (DefinitionWriteConflict,SQLiteBackgroundTaskStore,@@ -126,9 +134,12 @@ _TRUTHY_ENV_VALUES = {"1", "true", "yes", "on"}_FALSY_ENV_VALUES = {"0", "false", "no", "off"}DOCTOR_RESTART_RESULT_RETENTION_SECONDS = 10 * 60DOCTOR_RESTART_SEED_GRACE_SECONDS = 60.0+DOCTOR_LAUNCHER_REPAIR_LOCK_TIMEOUT_SECONDS = 10.0+STABLE_LAUNCHER_REPAIR_ARGS = ("doctor", "repair", "stable-launchers")DOCTOR_REPAIR_TARGETS = ("home-migration","stale-install-runtime",+ "stable-launchers","duplicate-service-processes","stale-restart-state","askill",@@ -138,8 +149,8 @@ DOCTOR_REPAIR_TARGETS = ("show-runtime","tmux",)-DOCTOR_DEFAULT_REPAIR_TARGETS = DOCTOR_REPAIR_TARGETS[:4]-DOCTOR_DEPENDENCY_REPAIR_TARGETS = frozenset(DOCTOR_REPAIR_TARGETS[4:])+DOCTOR_DEFAULT_REPAIR_TARGETS = DOCTOR_REPAIR_TARGETS[:5]+DOCTOR_DEPENDENCY_REPAIR_TARGETS = frozenset(DOCTOR_REPAIR_TARGETS[5:])def _doctor_repair_target(value: str) -> str:@@ -154,6 +165,7 @@ def _doctor_repair_target(value: str) -> str:DOCTOR_REPAIR_DRY_RUN_I18N_KEYS = {"home-migration": "doctor.repair.dryHomeMigration","stale-install-runtime": "doctor.repair.dryStaleInstall",+ "stable-launchers": "doctor.repair.dryStableLaunchers","duplicate-service-processes": "doctor.repair.dryDuplicateProcesses","stale-restart-state": "doctor.repair.dryStaleRestart","askill": "doctor.repair.dryAskill",@@ -1158,6 +1170,43 @@ def _current_cli_install_family() -> str | None:return None+def _launcher_command(launcher: Path | str, *args: str) -> str:+ """A pasteable command that runs ``launcher``, even from a path with spaces."""++ return shlex.join([str(launcher), *args])+++def _service_generation_items() -> list[dict]:+ """Warn when the running service is older than the last activated install."""++ items: list[dict] = []+ owner_pid = runtime.resolve_service_owner_pid(include_starting=False)+ downgrade = generation_downgrade(process_generation(owner_pid)) if owner_pid else None+ if downgrade is None:+ return items+ language = _configured_cli_language()+ _add_doctor_item(+ items,+ "warn",+ i18n_t(+ "doctor.item.serviceGenerationBehind",+ language,+ version=downgrade.version,+ generation=downgrade.generation,+ activatedVersion=downgrade.activated.version,+ activatedGeneration=downgrade.activated.generation,+ ),+ i18n_t(+ "doctor.action.serviceGenerationBehind",+ language,+ restartCommand=_launcher_command(downgrade.activated.launcher, "restart"),+ ),+ code="runtime.service_generation_behind",+ generation_downgrade=downgrade.as_dict(),+ )+ return items++def _service_install_family_items(*, detect_extra_processes: bool = True) -> list[dict]:items: list[dict] = []language = _configured_cli_language()@@ -12412,6 +12461,7 @@ def _doctor(*, deep: bool = False):for item in [*_service_lifecycle_items(detect_extra_processes=deep),*_service_install_family_items(detect_extra_processes=deep),+ *_service_generation_items(),*_restart_state_items(),*_runtime_architecture_items(),*_show_git_checkpoint_items(),@@ -12434,7 +12484,7 @@ def _doctor(*, deep: bool = False):summary[status] += 1groups.append({"name": i18n_t("doctor.group.dependencies", language), "items": dependency_items})- local_cli_items = _local_cli_installation_items()+ local_cli_items = [*_stable_launcher_items(), *_local_cli_installation_items()]for item in local_cli_items:status = item.get("status")if status in summary:@@ -12644,6 +12694,73 @@ def _current_sqlite_revision() -> str | None:return str(row[0])+def _describe_launcher_selections(selections: list, language: str) -> str:+ unknown = i18n_t("doctor.value.unknown", language)+ return "; ".join(+ f"{selection.launcher} -> {selection.version or unknown} ({selection.generation})"+ for selection in selections+ )+++def _stable_launcher_items() -> list[dict]:+ """Fail when two discoverable stable launchers select different installs."""++ items: list[dict] = []+ language = _configured_cli_language()+ selections = stable_launcher_selections()+ if len(selections) < 2:+ return items+ unknown = i18n_t("doctor.value.unknown", language)+ if len({selection.generation for selection in selections}) == 1:+ _add_doctor_item(+ items,+ "pass",+ i18n_t(+ "doctor.item.launchersInStep",+ language,+ count=len(selections),+ version=selections[0].version or unknown,+ ),+ code="installation.stable_launchers",+ )+ return items+ target = newest_launcher_selection(selections)+ _add_doctor_item(+ items,+ "fail",+ i18n_t(+ "doctor.item.splitLaunchers",+ language,+ launchers=_describe_launcher_selections(selections, language),+ ),+ i18n_t(+ "doctor.action.splitLaunchersTied",+ language,+ launchers=_describe_launcher_selections(top_ranked_selections(selections), language),+ )+ if target is None+ else i18n_t(+ "doctor.action.splitLaunchers",+ language,+ repairCommand=_launcher_command(target.launcher, *STABLE_LAUNCHER_REPAIR_ARGS),+ version=target.version or unknown,+ ),+ code="installation.split_launchers",+ # Tied installs leave the repair nothing to choose, so doctor does not offer it.+ repair_target=None if target is None else "stable-launchers",+ repair_risk="low",+ launchers=[+ {+ "path": str(selection.launcher),+ "version": selection.version,+ "generation": str(selection.generation),+ }+ for selection in selections+ ],+ )+ return items++def _local_cli_installation_items() -> list[dict]:items: list[dict] = []language = _configured_cli_language()@@ -13051,6 +13168,136 @@ def _repair_duplicate_service_processes(*, dry_run: bool = False) -> dict:)+def _repair_stable_launchers(*, dry_run: bool = False) -> dict:+ """Point every managed stable launcher at the newest installed generation."""++ target_name = "stable-launchers"+ language = _configured_cli_language()++ def in_step(selections: list) -> dict | None:+ if len({selection.generation for selection in selections}) < 2:+ return _doctor_repair_result(+ target_name, "skipped", i18n_t("doctor.repair.stableLaunchersInStep", language)+ )+ return None++ # Launchers already in step need no lock; taking it would create the+ # home of an install that has none.+ if (skipped := in_step(stable_launcher_selections())) is not None:+ return skipped+ if dry_run:+ return _doctor_repair_result(target_name, "planned", i18n_t("doctor.repair.dryStableLaunchers", language))+ try:+ with atomic_upgrade_lock(timeout_seconds=DOCTOR_LAUNCHER_REPAIR_LOCK_TIMEOUT_SECONDS):+ selections = stable_launcher_selections()+ if (skipped := in_step(selections)) is not None:+ return skipped+ target = newest_launcher_selection(selections)+ if target is None:+ # Discovery order must never pick between tied installs.+ return _doctor_repair_result(+ target_name,+ "failed",+ i18n_t(+ "doctor.repair.stableLaunchersTied",+ language,+ launchers=_describe_launcher_selections(top_ranked_selections(selections), language),+ ),+ reason="stable_launchers_tied",+ )+ unknown = i18n_t("doctor.value.unknown", language)+ moved: list[Path] = []+ running = None+ for selection in selections:+ if selection.generation == target.generation:+ continue+ # Windows cannot replace the image this repair runs from. The+ # target launcher is not running, so it can move this one.+ if launcher_is_current_process(selection.launcher):+ running = selection+ continue+ # A managed launcher has its export's name, so the target+ # install exports the same name (see managed_stable_launchers).+ exported = target.generation / "bin" / selection.launcher.name+ try:+ # A launcher another installer replaced since discovery is left alone.+ if move_managed_launcher_locked(selection.launcher, selection.generation, exported):+ moved.append(selection.launcher)+ except (OSError, RuntimeError) as exc:+ logger.warning("failed to repoint stable launcher %s", selection.launcher, exc_info=True)+ return _doctor_repair_result(+ target_name,+ "failed",+ i18n_t(+ "doctor.repair.stableLauncherMoveFailed",+ language,+ launcher=selection.launcher,+ version=target.version or unknown,+ generation=target.generation,+ ),+ reason="stable_launcher_move_failed",+ error=str(exc),+ launchers=[str(launcher) for launcher in moved],+ )+ if running is not None:+ return _doctor_repair_result(+ target_name,+ "failed",+ i18n_t(+ "doctor.repair.stableLauncherRunning",+ language,+ launcher=running.launcher,+ repairCommand=_launcher_command(target.launcher, *STABLE_LAUNCHER_REPAIR_ARGS),+ ),+ reason="stable_launcher_running",+ launchers=[str(launcher) for launcher in moved],+ )+ # Report what the launchers select now, not what was attempted: the+ # upgrade lock does not stop uv or another installer changing them.+ remaining = stable_launcher_selections()+ if len({selection.generation for selection in remaining}) > 1:+ return _doctor_repair_result(+ target_name,+ "failed",+ i18n_t(+ "doctor.repair.stableLaunchersStillSplit",+ language,+ launchers=_describe_launcher_selections(remaining, language),+ ),+ reason="stable_launchers_still_split",+ launchers=[str(launcher) for launcher in moved],+ )+ except MigrationLockTimeout:+ return _doctor_repair_result(+ target_name,+ "failed",+ i18n_t("doctor.repair.stableLaunchersBusy", language),+ reason="upgrade_lock_busy",+ )+ except Exception as exc: # noqa: BLE001+ logger.warning("stable launcher repair failed", exc_info=True)+ return _doctor_repair_result(+ target_name,+ "failed",+ i18n_t("doctor.repair.stableLaunchersFailed", language),+ reason="stable_launcher_repair_exception",+ error=str(exc),+ )+ return _doctor_repair_result(+ target_name,+ "repaired",+ i18n_t(+ "doctor.repair.stableLaunchersRepaired",+ language,+ launchers=", ".join(map(str, moved)),+ version=target.version or i18n_t("doctor.value.unknown", language),+ generation=target.generation,+ ),+ launchers=[str(launcher) for launcher in moved],+ generation=str(target.generation),+ )++def _repair_stale_install_runtime(*, dry_run: bool = False) -> dict:target = "stale-install-runtime"language = _configured_cli_language()@@ -13350,6 +13597,7 @@ def _repair_doctor_targets(targets: list[str], *, dry_run: bool = False, deep: bhandlers = {"home-migration": _repair_home_migration,"stale-install-runtime": _repair_stale_install_runtime,+ "stable-launchers": _repair_stable_launchers,"duplicate-service-processes": _repair_duplicate_service_processes,"stale-restart-state": _repair_stale_restart_state,"askill": _repair_askill,@@ -16221,6 +16469,40 @@ def _schedule_delayed_restart(delay_seconds: float) -> int:return 0+def _generation_downgrade_blocks(command: str | None, *, allow_downgrade: bool = False) -> bool:+ """Report running an install older than the last activated one.++ ``vibe start`` and ``vibe restart`` refuse unless the downgrade is explicit.+ A supervisor-owned launch (``command`` is None, or the desktop shell) is+ only warned: blocking it would leave the service down instead of old.+ """++ downgrade = generation_downgrade(current_generation())+ if downgrade is None:+ return False+ supervised = command is None or is_desktop_managed_runtime()+ if supervised:+ key = "update.downgradeWarning"+ else:+ key = "update.downgradeAllowed" if allow_downgrade else "update.downgradeRefused"+ print(+ i18n_t(+ key,+ _configured_cli_language(),+ command=command or "",+ version=downgrade.version,+ generation=downgrade.generation,+ activatedVersion=downgrade.activated.version,+ activatedGeneration=downgrade.activated.generation,+ launcher=_launcher_command(downgrade.activated.launcher),+ rerunCommand=_launcher_command(downgrade.activated.launcher, *([command] if command else [])),+ repairCommand=_launcher_command(downgrade.activated.launcher, *STABLE_LAUNCHER_REPAIR_ARGS),+ ),+ file=sys.stderr,+ )+ return not supervised and not allow_downgrade++def _cmd_restart_with_delay(delay_seconds: float) -> int:if delay_seconds > 0:return _schedule_delayed_restart(delay_seconds)@@ -16249,6 +16531,11 @@ def build_parser():default=None,help="Start services without opening the Web UI in the system browser.",)+ start_parser.add_argument(+ "--allow-downgrade",+ action="store_true",+ help="Start this install even though a newer one was activated since.",+ )desktop_parser = subparsers.add_parser("desktop", help=argparse.SUPPRESS)desktop_subparsers = desktop_parser.add_subparsers(dest="desktop_command", required=True)desktop_endpoint_parser = desktop_subparsers.add_parser("endpoint", help=argparse.SUPPRESS)@@ -16260,6 +16547,11 @@ def build_parser():default=0,help="Schedule the restart to run asynchronously after N seconds, then exit immediately.",)+ restart_parser.add_argument(+ "--allow-downgrade",+ action="store_true",+ help="Restart onto this install even though a newer one was activated since.",+ )# `__restart-supervisor` is deliberately absent here. It is never typed: this# program spawns it, and `vibe/restart_supervisor.py` owns both the argv it# builds and the parser that reads it back. Restating those flags here made@@ -18376,10 +18668,14 @@ def _dispatch_parsed_command(parser: argparse.ArgumentParser, args) -> None:if args.command == "stop":sys.exit(cmd_stop(receipt=args.receipt) if args.receipt is not None else cmd_stop())if args.command == "start":+ if _generation_downgrade_blocks("start", allow_downgrade=args.allow_downgrade):+ sys.exit(1)sys.exit(cmd_start(open_browser=args.open_browser))if args.command == "desktop" and args.desktop_command == "endpoint":sys.exit(cmd_desktop_endpoint())if args.command == "restart":+ if _generation_downgrade_blocks("restart", allow_downgrade=args.allow_downgrade):+ sys.exit(1)sys.exit(_cmd_restart_with_delay(args.delay_seconds))if args.command == "status":sys.exit(cmd_status())@@ -18575,4 +18871,7 @@ def _dispatch_parsed_command(parser: argparse.ArgumentParser, args) -> None:if args.watch_command in {"remove", "rm"}:sys.exit(cmd_watch_remove(args.watch_id))parser.error("watch command is required")+ # Bare `vibe` is also the supervisor entry (systemd, launchd); it is never+ # refused, only told which newer install it is behind.+ _generation_downgrade_blocks(None)sys.exit(cmd_vibe())diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex d82a1aaa3..0194ed62f 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -509,7 +509,10 @@"availableDiscord": "🚀 **Avibe Update Available**\n\nUpdate from `{current}` → {latestLink}","availableMarkdown": "🚀 Avibe Update Available\n\nUpdate from `{current}` → {latestLink}","availableText": "🚀 Avibe Update Available\n\nUpdate from {current} → {latestLink}",- "actionUpdateNow": "Update Now"+ "actionUpdateNow": "Update Now",+ "downgradeRefused": "Refusing to {command} from Avibe {version} ({generation}): the last activated install is {activatedVersion} ({activatedGeneration}). Run `{rerunCommand}` instead, or pass --allow-downgrade to run the older build on purpose.",+ "downgradeAllowed": "Warning: running Avibe {version} ({generation}), older than the last activated install {activatedVersion} ({activatedGeneration}), because --allow-downgrade was given.",+ "downgradeWarning": "Warning: this vibe runs Avibe {version} ({generation}), older than the last activated install {activatedVersion} ({activatedGeneration}). Use `{launcher}`, or run `{repairCommand}` to move every launcher to it."},"discord": {"settingsSubtitle": "Adjust message visibility, mention behavior, and language.",@@ -1234,6 +1237,9 @@"cliMissing": "No vibe executable found on PATH","cliPathPrecedence": "PATH resolves vibe to {active} before {preferred}","cliPath": "PATH resolves vibe to {path}",+ "splitLaunchers": "Stable vibe launchers select different installs: {launchers}",+ "launchersInStep": "{count} stable vibe launchers select Avibe {version}",+ "serviceGenerationBehind": "The running service is Avibe {version} ({generation}), older than the last activated install {activatedVersion} ({activatedGeneration})","cliNotUvTool": "Active vibe executable is not the uv tool installation","cliEditable": "uv tool installation is editable: {path}","cliNotEditable": "uv tool installation is not editable: {path}",@@ -1316,6 +1322,9 @@"cronNumericWeekday": "Confirm each intended day, then rewrite the weekday with names, for example vibe task update <id> --cron '0 9 * * mon-fri'","cliMissing": "Install Avibe with uv tool or add the intended vibe executable to PATH.","cliPathPrecedence": "Put ~/.local/bin before system Python bin directories when using the uv tool installation.",+ "splitLaunchers": "Run `{repairCommand}` to point every launcher at Avibe {version}.",+ "splitLaunchersTied": "These installs tie as the last activation, so the repair cannot choose one: {launchers}. Run the Avibe installer again; its new install moves every launcher.",+ "serviceGenerationBehind": "Run `{restartCommand}` to run the last activated install.","cliNotUvTool": "uv tool package-integrity checks are skipped for this executable.","cliEditable": "Reinstall Avibe from a normal wheel. Do not use 'uv tool install --editable .' for the live local CLI.","packageIntegrityFailed": "Rerun the Avibe installer to replace the active environment with a verified wheel.",@@ -1348,6 +1357,14 @@"extraProcessPartial": "Some extra service processes could not be stopped.","extraProcessStopped": "Stopped extra Avibe service process(es).","noLegacyProcess": "No legacy vibe-remote service process was detected.",+ "stableLaunchersInStep": "Every stable vibe launcher already selects the same install.",+ "stableLaunchersRepaired": "Pointed {launchers} at Avibe {version} ({generation}).",+ "stableLaunchersFailed": "Could not point every stable vibe launcher at the newest install. Run `vibe doctor` to see where each launcher points.",+ "stableLauncherMoveFailed": "Could not point {launcher} at Avibe {version} ({generation}). Make sure you can write to it, then run `vibe doctor repair stable-launchers` again.",+ "stableLauncherRunning": "Windows cannot replace {launcher} while this repair runs from it, so it still selects the older install. Run `{repairCommand}` to move it.",+ "stableLaunchersTied": "Stable vibe launchers select installs that tie as the last activation: {launchers}. No launcher was changed; run the Avibe installer again, and its new install moves every launcher.",+ "stableLaunchersBusy": "Another Avibe install, upgrade or repair is running. Run `vibe doctor repair stable-launchers` again when it finishes.",+ "stableLaunchersStillSplit": "Stable vibe launchers still select different installs after the repair: {launchers}. Another installer may have changed them; run `vibe doctor` again.","staleInstallDryRun": "Would stop legacy service process(es) and start current Avibe: {pids}.","staleInstallPartial": "Some legacy vibe-remote service processes could not be stopped.","staleInstallStopped": "Stopped legacy vibe-remote service process(es).",@@ -1417,6 +1434,7 @@"dryStaleInstall": "Would stop a running legacy vibe-remote service and start the current Avibe service.","dryDuplicateProcesses": "Would stop extra Avibe service processes outside the service lock.","dryStaleRestart": "Would remove stale restart metadata and refresh runtime status.",+ "dryStableLaunchers": "Would point every stable vibe launcher at the newest installed version.","dryAskill": "Would install or refresh askill with the official installer.","dryAvault": "Would install or refresh the manifest-pinned avault release.","dryModelHubEngine": "Would install or refresh the Avibe-pinned Model Hub engine (CPA).",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex a7c52bec6..21d1b9c0c 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -509,7 +509,10 @@"availableDiscord": "🚀 **Avibe 有可用更新**\n\n从 `{current}` 更新到 {latestLink}","availableMarkdown": "🚀 Avibe 有可用更新\n\n从 `{current}` 更新到 {latestLink}","availableText": "🚀 Avibe 有可用更新\n\n从 {current} 更新到 {latestLink}",- "actionUpdateNow": "立即更新"+ "actionUpdateNow": "立即更新",+ "downgradeRefused": "拒绝从 Avibe {version}({generation})执行 {command}:最近激活的安装是 {activatedVersion}({activatedGeneration})。请改为运行 `{rerunCommand}`;如确需运行旧版本,请加 --allow-downgrade。",+ "downgradeAllowed": "警告:由于指定了 --allow-downgrade,正在运行 Avibe {version}({generation}),它比最近激活的安装 {activatedVersion}({activatedGeneration})旧。",+ "downgradeWarning": "警告:这个 vibe 运行的是 Avibe {version}({generation}),比最近激活的安装 {activatedVersion}({activatedGeneration})旧。请使用 `{launcher}`,或运行 `{repairCommand}` 让所有启动器都指向它。"},"discord": {"settingsSubtitle": "调整消息可见性、@提及策略与语言。",@@ -1234,6 +1237,9 @@"cliMissing": "PATH 中找不到 vibe 可执行文件","cliPathPrecedence": "PATH 先解析到 {active},而不是 {preferred}","cliPath": "PATH 解析到 vibe:{path}",+ "splitLaunchers": "稳定 vibe 启动器指向了不同的安装:{launchers}",+ "launchersInStep": "{count} 个稳定 vibe 启动器都指向 Avibe {version}",+ "serviceGenerationBehind": "运行中的服务是 Avibe {version}({generation}),比最近激活的安装 {activatedVersion}({activatedGeneration})旧","cliNotUvTool": "当前 vibe 可执行文件不是 uv tool 安装","cliEditable": "uv tool 安装是 editable:{path}","cliNotEditable": "uv tool 安装不是 editable:{path}",@@ -1316,6 +1322,9 @@"cronNumericWeekday": "确认每个任务原本想要的日期后,改用星期英文名,例如 vibe task update <id> --cron '0 9 * * mon-fri'","cliMissing": "使用 uv tool 安装 Avibe,或将预期的 vibe 可执行文件加入 PATH。","cliPathPrecedence": "使用 uv tool 安装时,将 ~/.local/bin 放在系统 Python bin 目录之前。",+ "splitLaunchers": "运行 `{repairCommand}`,让所有启动器都指向 Avibe {version}。",+ "splitLaunchersTied": "这些安装同为最后激活,修复无法从中选择:{launchers}。请重新运行 Avibe 安装程序,它的新安装会让所有启动器一起切换过去。",+ "serviceGenerationBehind": "运行 `{restartCommand}`,改为运行最近激活的安装。","cliNotUvTool": "此可执行文件将跳过 uv tool 包完整性检查。","cliEditable": "从普通 wheel 重新安装 Avibe。运行中的本地 CLI 不要使用 'uv tool install --editable .'。","packageIntegrityFailed": "重新运行 Avibe 安装器,以经过验证的 wheel 替换当前环境。",@@ -1348,6 +1357,14 @@"extraProcessPartial": "部分额外服务进程无法停止。","extraProcessStopped": "已停止额外 Avibe 服务进程。","noLegacyProcess": "未发现旧版 vibe-remote 服务进程。",+ "stableLaunchersInStep": "所有稳定 vibe 启动器已指向同一个安装。",+ "stableLaunchersRepaired": "已让 {launchers} 指向 Avibe {version}({generation})。",+ "stableLaunchersFailed": "无法让所有稳定 vibe 启动器都指向最新的安装。运行 `vibe doctor` 查看每个启动器当前指向哪里。",+ "stableLauncherMoveFailed": "无法让 {launcher} 指向 Avibe {version}({generation})。请确认你有权限写入它,然后重新运行 `vibe doctor repair stable-launchers`。",+ "stableLauncherRunning": "Windows 无法在这次修复从 {launcher} 运行时替换它,所以它仍指向较旧的安装。请运行 `{repairCommand}` 来切换它。",+ "stableLaunchersTied": "稳定 vibe 启动器指向的安装同为最后激活,无法区分:{launchers}。没有改动任何启动器;请重新运行 Avibe 安装程序,它的新安装会让所有启动器一起切换过去。",+ "stableLaunchersBusy": "另一个 Avibe 安装、升级或修复正在进行。请在它完成后重新运行 `vibe doctor repair stable-launchers`。",+ "stableLaunchersStillSplit": "修复后稳定 vibe 启动器仍指向不同的安装:{launchers}。可能有其他安装程序改动了它们,请重新运行 `vibe doctor`。","staleInstallDryRun": "将停止旧版服务进程并启动当前 Avibe:{pids}。","staleInstallPartial": "部分旧版 vibe-remote 服务进程无法停止。","staleInstallStopped": "已停止旧版 vibe-remote 服务进程。",@@ -1417,6 +1434,7 @@"dryStaleInstall": "将停止运行中的旧版 vibe-remote 服务并启动当前 Avibe 服务。","dryDuplicateProcesses": "将停止服务锁外的额外 Avibe 服务进程。","dryStaleRestart": "将移除过期重启元数据并刷新运行时状态。",+ "dryStableLaunchers": "将让所有稳定 vibe 启动器都指向最新的已安装版本。","dryAskill": "将使用官方安装器安装或刷新 askill。","dryAvault": "将安装或刷新清单固定的 avault 版本。","dryModelHubEngine": "将安装或刷新 Avibe 固定的 Model Hub 引擎(CPA)版本。",diff --git a/vibe/install_generations.py b/vibe/install_generations.pyindex 41be8231c..26e3b535d 100644--- a/vibe/install_generations.py+++ b/vibe/install_generations.py@@ -371,12 +371,16 @@ def collect_install_generations(launcher: str | Path | None = None) -> list[Pathlogger.info("Install generation collection deferred: unknown launcher target")return []# Invoking an explicit alias is not permission to break the command- # selected by PATH. This is one ordinary command lookup, not an- # alias registry or filesystem scan. Only confirmed managed targets- # add protection; an unrelated command cannot veto retirement.+ # selected by PATH, or a stable launcher activation could not move.+ # These are the fixed launcher locations, not an alias registry or+ # filesystem scan. Only confirmed managed targets add protection;+ # an unrelated command or a dangling link cannot veto retirement.path_command = shutil.which("vibe")- if path_command and Path(path_command).absolute() != launcher_path:- kept.update(_launcher_targets(Path(path_command).absolute(), root, managed))+ others = {Path(path_command).absolute()} if path_command else set()+ others.update(peer for peer, _generation in upgrade.managed_stable_launchers())+ for other in others - {launcher_path}:+ if other.exists():+ kept.update(_launcher_targets(other, root, managed))references = _invocation_paths() | _runtime_paths()kept.update(generation for path in referencesdiff --git a/vibe/runtime.py b/vibe/runtime.pyindex 4dcabf004..0ec856b80 100644--- a/vibe/runtime.py+++ b/vibe/runtime.py@@ -1607,6 +1607,15 @@ def render_status(*, detect_extra_processes: bool = True):status["service_owner_pid"] = owner_pidstatus["running"] = runningstatus["pid"] = owner_pid or (extra_pids[0] if extra_pids else None)+ # A supervisor may bring the service up from an older install than the+ # last activation; it is not refused, so say so here.+ from vibe.upgrade import generation_downgrade, process_generation++ downgrade = generation_downgrade(process_generation(owner_pid)) if owner_pid else None+ if downgrade is not None:+ status["generation_downgrade"] = downgrade.as_dict()+ else:+ status.pop("generation_downgrade", None)restart_status = read_json(get_restart_status_path())if restart_status:status["restart"] = restart_statusdiff --git a/vibe/upgrade.py b/vibe/upgrade.pyindex fbfe48aae..8c1a752c0 100644--- a/vibe/upgrade.py+++ b/vibe/upgrade.py@@ -47,6 +47,10 @@ 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 * 60RESTART_PENDING_GRACE_SECONDS = 5 * 60DEFERRED_ACTIVATION_TIMEOUT_SECONDS = 5 * 60@@ -495,6 +499,7 @@ def _launcher_generation(launcher: Path, root: Path) -> Path | None: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.nametry:# Read both files on every check. Marker validation is a safety@@ -524,6 +529,247 @@ def _update_launcher_generation_marker(launcher: Path, target: Path, root: Path)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."""@@ -625,6 +871,12 @@ def _activate_upgrade_candidate_locked(activation: AtomicActivation) -> None: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()@@ -636,6 +888,16 @@ def _activate_upgrade_candidate_locked(activation: AtomicActivation) -> None: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)+ for peer, selected in peers:+ try:+ if selected != activated:+ move_managed_launcher_locked(peer, selected, activation.candidate_launcher)+ except Exception:+ 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)@@ -659,6 +921,20 @@ def activate_launcher_target(launcher: str | os.PathLike[str], target: str | os._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()