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.

fix(upgrade): move a uv-managed Python to its newest patch on upgrade (#2919)

Call Whitea65c87a05d67
diff --git a/docs/CLI.md b/docs/CLI.md
index 33b3db964..3257bb96e 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -622,6 +622,16 @@ 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).
+When Avibe runs on a uv-managed CPython, the upgrade first moves that Python
+minor version to its newest patch release with
+`uv python install --upgrade --no-bin`, so CPython and OpenSSL security fixes
+arrive with Avibe releases. It never changes the minor version and adds no
+`python3.x` command to your `PATH`. As with `uv python upgrade`, other uv
+environments that follow this minor version's managed Python move to the new
+patch too. uv only knows patches released before its own version; with uv older
+than 0.9.10, offline, or when the download fails, the upgrade continues on the
+installed patch and logs why. Run `uv self update` to reach newer patches.
+
## Service Lifecycle
### Understanding "Restart" vs "Stop"
diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.md
index 4315bf6f0..b08ae591b 100644
--- a/docs/CLI_ZH.md
+++ b/docs/CLI_ZH.md
@@ -506,6 +506,14 @@ vibe upgrade
因此任何 `PATH` 查找都不会留在旧版本上。指向其他位置的启动器永远不会被修改。
参见 [Upgrading](UPGRADING.md#stable-launchers)。
+当 Avibe 运行在 uv 管理的 CPython 上时,升级会先用
+`uv python install --upgrade --no-bin` 把这个 Python 小版本更新到最新补丁版本,
+让 CPython 和 OpenSSL 的安全修复随 Avibe 版本一起到达。它不会改变小版本,也不会在
+`PATH` 中添加 `python3.x` 命令。与 `uv python upgrade` 相同,其他跟随该小版本托管
+Python 的 uv 环境也会一起使用新补丁。uv 只知道在它自身版本发布之前的补丁;uv 低于
+0.9.10、离线或下载失败时,升级会继续使用已安装的补丁,并在日志中说明原因。运行
+`uv self update` 即可获得更新的补丁。
+
## 服务生命周期
### 理解「重启」与「停止」的区别
diff --git a/tests/test_upgrade_flow.py b/tests/test_upgrade_flow.py
index 91da3c96a..9f4c47072 100644
--- a/tests/test_upgrade_flow.py
+++ b/tests/test_upgrade_flow.py
@@ -172,6 +172,118 @@ def test_build_upgrade_plan_keeps_windows_on_arm_on_x64_python(monkeypatch, tmp_
pinned = ["--python", "cpython-3.12-windows-x86_64-none"]
assert (plan.command[4:6] == pinned) is on_arm, plan.command
+ # The patch upgrade targets the interpreter the staged install will use.
+ upgraded = (plan.python_upgrade_command or [])[-1:]
+ assert upgraded == (["cpython-3.12-windows-x86_64-none"] if on_arm else [])
+
+
+ ("home", "expected"),
+ [
+ # Created before uv's minor-version links, as on a long-lived install.
+ ("{uv}/cpython-3.12.12-macos-aarch64-none/bin", "cpython-3.12-macos-aarch64-none"),
+ ("{uv}/cpython-3.12-linux-x86_64-gnu/bin", "cpython-3.12-linux-x86_64-gnu"),
+ ("{uv}/cpython-3.14.0rc2-linux-aarch64-musl/bin", "cpython-3.14-linux-aarch64-musl"),
+ # Windows records the install directory itself, not its bin.
+ ("{uv}/cpython-3.13.5-windows-x86_64-none", "cpython-3.13-windows-x86_64-none"),
+ # Interpreters uv does not own, even one named like uv's, or builds a
+ # plain minor request would replace.
+ ("/usr/bin", None),
+ ("/opt/homebrew/opt/[email protected]/Frameworks/Python.framework/Versions/3.12/bin", None),
+ ("{other}/cpython-3.12-linux-x86_64-gnu/bin", None),
+ ("{uv}/cpython-3.13.5+freethreaded-linux-x86_64-gnu/bin", None),
+ # uv cannot say where its Pythons are.
+ ("{uv}/cpython-3.12.12-macos-aarch64-none/bin", "uv-fails"),
+ ],
+)
+def test_uv_upgrade_moves_only_a_uv_managed_interpreter_to_its_newest_patch(
+ monkeypatch, tmp_path, home, expected,
+):
+ launcher = tmp_path / "bin" / "vibe"
+ target = tmp_path / "old" / "vibe"
+ target.parent.mkdir(parents=True)
+ target.write_text("#!/bin/sh\n", encoding="utf-8")
+ launcher.parent.mkdir(parents=True)
+ launcher.symlink_to(target)
+ uv_python_dir = tmp_path / "uv" / "python"
+ uv = tmp_path / "uv-bin" / "uv"
+ uv.parent.mkdir()
+ uv.write_text(
+ "#!/bin/sh\nexit 2\n" if expected == "uv-fails"
+ else f'#!/bin/sh\n[ "$1 $2" = "python dir" ] && echo {shlex.quote(str(uv_python_dir))}\n',
+ encoding="utf-8",
+ )
+ uv.chmod(0o755)
+ tool_python = tmp_path / "uv" / "tools" / "avibe-os" / "bin" / "python"
+ tool_python.parent.mkdir(parents=True)
+ (tool_python.parent.parent / "pyvenv.cfg").write_text(
+ f"home = {home.format(uv=uv_python_dir, other=tmp_path / 'opt')}\nversion_info = 3.12.12\n",
+ encoding="utf-8",
+ )
+ monkeypatch.setattr("vibe.upgrade.config_paths.get_vibe_remote_dir", lambda: tmp_path / "home")
+ monkeypatch.setattr("vibe.upgrade.windows_native_arm64", lambda: False)
+
+ plan = build_upgrade_plan(
+ python_executable=str(tool_python),
+ uv_path=str(uv),
+ vibe_path=str(launcher),
+ base_env={"PATH": "/usr/bin"},
+ )
+
+ assert plan.method == "uv"
+ assert plan.python_upgrade_command == (
+ None
+ if expected in (None, "uv-fails")
+ else [str(uv), "python", "install", "--upgrade", "--no-bin", "--no-registry", expected]
+ )
+ # uv keeps choosing the staged interpreter, so a release that drops this
+ # minor version can still move the install to a supported one.
+ assert "--python" not in plan.command
+
+
[email protected]("outcome", ["upgraded", "old-uv", "offline", "timeout", "uv-missing"])
+def test_python_patch_upgrade_runs_first_and_never_blocks_the_staged_install(caplog, outcome):
+ python_upgrade = [
+ "/usr/local/bin/uv", "python", "install", "--upgrade", "--no-bin", "--no-registry",
+ "cpython-3.12-macos-aarch64-none",
+ ]
+ plan = UpgradePlan(
+ command=["/usr/local/bin/uv", "tool", "install", "avibe-os", "--upgrade"],
+ env={"PATH": "/usr/bin", "UV_TOOL_DIR": "/staged/uv/tools"},
+ method="uv",
+ python_upgrade_command=python_upgrade,
+ )
+ calls = []
+
+ def run(command, **kwargs):
+ calls.append((command, kwargs))
+ if command != python_upgrade:
+ return subprocess.CompletedProcess(command, 0, "", "")
+ if outcome == "timeout":
+ raise subprocess.TimeoutExpired(command, kwargs["timeout"])
+ if outcome == "uv-missing":
+ raise FileNotFoundError(command[0])
+ returncode, stderr = {
+ "upgraded": (0, "Installed Python 3.12.15"),
+ "old-uv": (2, "error: unexpected argument '--upgrade' found"),
+ "offline": (1, "error: Failed to install cpython-3.12.15-macos-aarch64-none"),
+ }[outcome]
+ return subprocess.CompletedProcess(command, returncode, "", stderr)
+
+ with caplog.at_level("INFO", logger="vibe.upgrade"):
+ result = execute_upgrade_plan(
+ plan, run=run, capture_output=True, text=True,
+ timeout=vibe_upgrade.UPGRADE_INSTALL_TIMEOUT_SECONDS,
+ )
+
+ assert result.returncode == 0
+ # The staged install runs after the patch upgrade so it can select it.
+ assert [command for command, _ in calls] == [python_upgrade, plan.command]
+ patch_kwargs, install_kwargs = calls[0][1], calls[1][1]
+ assert patch_kwargs["env"] == plan.env
+ assert patch_kwargs["timeout"] == vibe_upgrade.PYTHON_PATCH_UPGRADE_TIMEOUT_SECONDS
+ assert install_kwargs["timeout"] == vibe_upgrade.UPGRADE_INSTALL_TIMEOUT_SECONDS
+ assert ("Keeping the installed Python patch" in caplog.text) is (outcome != "upgraded")
def test_build_upgrade_plan_refuses_uv_install_without_activation_point(monkeypatch):
diff --git a/vibe/upgrade.py b/vibe/upgrade.py
index 00049b3aa..60a4e2ed1 100644
--- a/vibe/upgrade.py
+++ b/vibe/upgrade.py
@@ -54,8 +54,20 @@ UV_FALLBACK_BIN_DIRS = (".local/bin", ".cargo/bin")
# 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
@@ -117,6 +129,7 @@ class UpgradePlan:
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(
@@ -139,6 +152,9 @@ def execute_upgrade_plan(
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
@@ -146,6 +162,40 @@ def execute_upgrade_plan(
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,
*,
@@ -1617,6 +1667,57 @@ def pinned_package_spec(version: str | None, *, package_name: str) -> str:
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,
@@ -1661,6 +1762,18 @@ def build_upgrade_plan(
# 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):
@@ -1673,6 +1786,7 @@ def build_upgrade_plan(
preflight_command=preflight_command,
activation=atomic,
preflight_error=preflight_error,
+ python_upgrade_command=python_upgrade_command,
)
command = [executable, "-m", "pip", "install"]