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): install Avibe environments atomically (#1711)
Call White2eb8b6dd0187
diff --git a/README.md b/README.mdindex a5e60f2da..8367084f5 100644--- a/README.md+++ b/README.md@@ -324,9 +324,13 @@ npm install -g @openai/codex```bashvibe stop+avibe_home="${AVIBE_HOME:-$HOME/.avibe}"+avibe_home="${avibe_home/#\~/$HOME}"uv tool uninstall avibe-osuv tool uninstall vibe-remote # legacy installs-rm -rf ~/.avibe ~/.vibe_remote+vibe_bin="$(command -v vibe)" && rm -f "$vibe_bin" "$(dirname "$vibe_bin")/.vibe.avibe-generation"+rm -rf "$avibe_home/runtime/install-generations"+rm -rf "$avibe_home" ~/.vibe_remote```---diff --git a/core/install_integrity.py b/core/install_integrity.pynew file mode 100644index 000000000..f757d1c70--- /dev/null+++ b/core/install_integrity.py@@ -0,0 +1,439 @@+"""Integrity checks shared by local installers and the runtime doctor.++Python installers record the files they put on disk in ``RECORD``. A package+version is not proof that those files are still complete: an interrupted copy+can leave valid metadata beside a partial package tree. These helpers make+the file contents the source of truth without importing the package being+checked.+"""++from __future__ import annotations++import base64+import csv+import hashlib+import importlib.metadata as importlib_metadata+import json+import os+import subprocess+import tempfile+from collections import deque+from dataclasses import dataclass+from importlib import import_module+from pathlib import Path, PurePosixPath+from typing import Iterable, Sequence++from packaging.markers import default_environment+from packaging.requirements import InvalidRequirement, Requirement+from packaging.utils import canonicalize_name+++RUNTIME_DISTRIBUTIONS = ("avibe-os", "vibe-remote")+RUNTIME_PROBE_PREFIX = "avibe-runtime-distributions:"+++@dataclass(frozen=True)+class IntegrityResult:+ """Measured result of a package-tree verification."""++ ok: bool+ checked_files: int = 0+ failures: tuple[str, ...] = ()++ @property+ def detail(self) -> str:+ if self.ok:+ return f"verified {self.checked_files} package files"+ if not self.failures:+ return "package integrity verification failed"+ suffix = ", ".join(self.failures[:5])+ if len(self.failures) > 5:+ suffix += f", and {len(self.failures) - 5} more"+ return suffix+++@dataclass(frozen=True)+class DependencyGraph:+ """Installed distributions reachable from Avibe's wheel metadata."""++ distributions: tuple[str, ...] = ()+ records: tuple[str, ...] = ()+ failures: tuple[str, ...] = ()+++def isolated_probe_environment() -> dict[str, str]:+ """Keep the candidate interpreter from importing the caller's checkout."""++ environment = os.environ.copy()+ environment.pop("PYTHONPATH", None)+ environment.pop("PYTHONHOME", None)+ return environment+++def run_isolated_probe(command: Sequence[str], *, timeout: float) -> subprocess.CompletedProcess[str]:+ """Run a candidate probe from a private empty working directory."""++ with tempfile.TemporaryDirectory(prefix="avibe-integrity-") as working_directory:+ return subprocess.run(+ command,+ capture_output=True,+ text=True,+ timeout=timeout,+ check=False,+ cwd=working_directory,+ env=isolated_probe_environment(),+ )+++def site_packages_for_python(python_executable: str | os.PathLike[str]) -> list[Path]:+ """Return site-packages directories belonging to a Python executable."""++ # Keep the logical path intact. uv tool interpreters are often symlinks to+ # a shared Python binary, while their import path and sysconfig point at+ # the tool environment selected through that symlink.+ executable = Path(python_executable).expanduser()+ discovered: list[Path] = []+ probe = (+ "import site, sysconfig; "+ "config = sysconfig.get_paths(); "+ "paths = [config.get('purelib'), config.get('platlib')]; "+ "paths += list(getattr(site, 'getsitepackages', lambda: [])()); "+ "user = getattr(site, 'getusersitepackages', lambda: '')(); "+ "paths += [user] if user and getattr(site, 'ENABLE_USER_SITE', True) else []; "+ "print('\\n'.join(dict.fromkeys(path for path in paths if path)))"+ )+ try:+ result = run_isolated_probe([str(executable), "-c", probe], timeout=10)+ except (OSError, subprocess.SubprocessError):+ result = None+ if result is not None and result.returncode == 0:+ discovered.extend(Path(line).expanduser() for line in result.stdout.splitlines() if line.strip())++ def has_record(path: Path) -> bool:+ return path.is_dir() and any(path.glob("*.dist-info/RECORD"))++ # The probed interpreter owns its import-path boundary. Filesystem globs+ # cannot infer that boundary when a prefix contains multiple Python+ # versions, so accept only interpreter-reported locations with wheel+ # metadata. A probe that cannot run is an invalid candidate, not a reason+ # to verify a sibling interpreter's packages.+ discovered = [path for path in discovered if has_record(path)]+ candidates: list[Path] = []+ seen: set[Path] = set()+ for path in discovered:+ try:+ resolved = path.resolve()+ except OSError:+ continue+ if resolved.is_dir() and resolved not in seen:+ seen.add(resolved)+ candidates.append(resolved)+ return candidates+++def record_paths(site_packages: Path, distribution_names: Iterable[str] | None = None) -> list[Path]:+ """Find RECORD files, optionally limited to normalized distribution names."""++ wanted = None+ if distribution_names is not None:+ wanted = {canonicalize_name(name) for name in distribution_names}+ paths: list[Path] = []+ for record in sorted(site_packages.glob("*.dist-info/RECORD")):+ if wanted is not None and record_distribution_name(record) not in wanted:+ continue+ paths.append(record)+ return paths+++def record_distribution_name(record: Path) -> str:+ """Return the canonical distribution name owning one wheel RECORD."""++ stem = record.parent.name.removesuffix(".dist-info")+ return canonicalize_name(stem.rsplit("-", 1)[0])+++def verify_site_packages(+ site_packages: Path | str,+ *,+ distribution_names: Iterable[str] | None = None,+) -> IntegrityResult:+ """Verify every hashed file named by installed distribution RECORD files.++ The RECORD file itself is allowed to have an empty hash, as specified by+ the wheel format. Paths that escape ``site_packages`` are rejected rather+ than resolved, so a malformed record cannot turn this check into a read of+ an unrelated file.+ """++ root = Path(site_packages).expanduser().resolve()+ records = record_paths(root, distribution_names)+ return verify_record_files(root, records)+++def verify_record_files(site_packages: Path | str, records: Iterable[Path]) -> IntegrityResult:+ """Verify exact wheel RECORD files selected by the candidate interpreter."""++ root = Path(site_packages).expanduser().resolve()+ failures: list[str] = []+ safe_records: list[Path] = []+ for record in records:+ try:+ record = Path(record).expanduser().resolve()+ record.relative_to(root)+ except (OSError, RuntimeError, ValueError):+ failures.append(f"unsafe RECORD path {record}")+ continue+ if record.name != "RECORD" or not record.parent.name.endswith(".dist-info"):+ failures.append(f"unsafe RECORD path {record}")+ continue+ safe_records.append(record)+ records = tuple(safe_records)+ if not records:+ failures.append(f"no RECORD file under {root}")+ return IntegrityResult(False, failures=tuple(failures))++ checked = 0+ for record_path in records:+ try:+ rows = list(csv.reader(record_path.read_text(encoding="utf-8").splitlines()))+ except (OSError, UnicodeError, csv.Error) as exc:+ failures.append(f"{record_path.name}: {exc}")+ continue+ for row in rows:+ if len(row) < 3 or not row[0]:+ failures.append(f"{record_path.name}: malformed RECORD row")+ continue+ relative = PurePosixPath(row[0])+ if relative.is_absolute():+ failures.append(f"{record_path.name}: unsafe path {row[0]}")+ continue+ path = (root / Path(*relative.parts)).resolve()+ # Wheel RECORD paths are relative to site-packages and legitimately+ # include ``../../../bin/<entrypoint>`` for generated scripts. The+ # enclosing tool root is the trust boundary, not site-packages+ # itself; anything that escapes that root is still rejected.+ if root.name in {"site-packages", "dist-packages"} and root.parent.name.startswith("python"):+ allowed_root = root.parent.parent.parent.resolve()+ elif root.name in {"site-packages", "dist-packages"} and root.parent.name == "Lib":+ allowed_root = root.parent.parent.resolve()+ else:+ allowed_root = root+ try:+ path.relative_to(allowed_root)+ except ValueError:+ failures.append(f"{record_path.name}: escaped path {row[0]}")+ continue+ if not path.is_file():+ failures.append(f"missing {row[0]}")+ continue+ digest = row[1]+ expected_size = row[2]+ if digest:+ try:+ algorithm, encoded = digest.split("=", 1)+ if algorithm not in {"sha256", "sha384", "sha512"}:+ failures.append(f"{row[0]}: unsupported hash {algorithm}")+ continue+ expected = base64.urlsafe_b64decode(encoded + "=" * (-len(encoded) % 4))+ actual = hashlib.new(algorithm, path.read_bytes()).digest()+ except (OSError, ValueError, UnicodeError):+ failures.append(f"{row[0]}: invalid hash")+ continue+ if actual != expected:+ failures.append(f"hash mismatch {row[0]}")+ continue+ if expected_size:+ try:+ if path.stat().st_size != int(expected_size):+ failures.append(f"size mismatch {row[0]}")+ continue+ except (OSError, ValueError):+ failures.append(f"invalid size {row[0]}")+ continue+ checked += 1++ return IntegrityResult(not failures, checked_files=checked, failures=tuple(failures))+++def runtime_import_modules() -> tuple[str, ...]:+ """Return import boundaries for every registered user-facing platform."""++ from config.platform_registry import platform_descriptors++ return tuple(+ dict.fromkeys(+ (+ "vibe",+ *(descriptor.client_module for descriptor in platform_descriptors()),+ )+ )+ )+++def inspect_dependency_graph(+ distribution_names: Iterable[str] = RUNTIME_DISTRIBUTIONS,+) -> DependencyGraph:+ """Validate the installed dependency closure rooted at Avibe's wheel metadata."""++ candidates = tuple(distribution_names)+ root = None+ root_candidate = ""+ for name in candidates:+ try:+ root = importlib_metadata.distribution(name)+ root_candidate = name+ break+ except importlib_metadata.PackageNotFoundError:+ continue+ if root is None:+ return DependencyGraph(failures=(f"missing runtime distribution: {' or '.join(candidates)}",))++ root_name = canonicalize_name(root.metadata.get("Name") or root_candidate)+ distributions = {root_name: root}+ requested_extras: dict[str, set[str]] = {root_name: set()}+ processed_extras: dict[str, frozenset[str]] = {}+ pending = deque([root_name])+ failures: set[str] = set()+ marker_environment = default_environment()++ while pending:+ distribution_name = pending.popleft()+ extras = requested_extras[distribution_name]+ extras_snapshot = frozenset(extras)+ if processed_extras.get(distribution_name) == extras_snapshot:+ continue+ processed_extras[distribution_name] = extras_snapshot+ distribution = distributions[distribution_name]++ for raw_requirement in distribution.requires or ():+ try:+ requirement = Requirement(raw_requirement)+ except InvalidRequirement:+ failures.add(f"invalid dependency metadata: {raw_requirement}")+ continue+ marker_extras = extras or {""}+ if requirement.marker is not None and not any(+ requirement.marker.evaluate({**marker_environment, "extra": extra})+ for extra in marker_extras+ ):+ continue++ dependency_name = canonicalize_name(requirement.name)+ try:+ dependency = importlib_metadata.distribution(requirement.name)+ except importlib_metadata.PackageNotFoundError:+ failures.add(f"missing dependency: {requirement.name}")+ continue+ if requirement.specifier and not requirement.specifier.contains(+ dependency.version,+ prereleases=True,+ ):+ failures.add(+ f"incompatible dependency: {requirement.name} {dependency.version} "+ f"does not satisfy {requirement.specifier}"+ )+ continue++ distributions[dependency_name] = dependency+ dependency_extras = requested_extras.setdefault(dependency_name, set())+ previous_extras = frozenset(dependency_extras)+ dependency_extras.update(requirement.extras)+ if dependency_name not in processed_extras or previous_extras != frozenset(dependency_extras):+ pending.append(dependency_name)++ records: list[str] = []+ for distribution_name, distribution in distributions.items():+ record = next(+ (+ file+ for file in (distribution.files or ())+ if file.name == "RECORD" and file.parent.name.endswith(".dist-info")+ ),+ None,+ )+ if record is None:+ failures.add(f"no RECORD for dependency {distribution_name}")+ continue+ records.append(str(distribution.locate_file(record)))++ return DependencyGraph(+ distributions=tuple(sorted(distributions)),+ records=tuple(sorted(dict.fromkeys(records))),+ failures=tuple(sorted(failures)),+ )+++def probe_runtime_environment(required_imports: Iterable[str] | None = None) -> tuple[str, ...]:+ """Raise when declared dependencies or registered platform imports are broken."""++ graph = inspect_dependency_graph()+ if graph.failures:+ raise RuntimeError("; ".join(graph.failures))+ modules = runtime_import_modules() if required_imports is None else tuple(required_imports)+ for module in modules:+ if module:+ import_module(module)+ return graph.records+++def verify_python_environment(+ python_executable: str | os.PathLike[str],+ *,+ required_imports: Iterable[str] | None = None,+ timeout: float = 30.0,+) -> IntegrityResult:+ """Verify package records, dependency closure, and platform imports."""++ executable = str(Path(python_executable).expanduser())+ site_packages = site_packages_for_python(executable)+ if not site_packages:+ return IntegrityResult(False, failures=(f"no site-packages for {executable}",))++ probe_call = (+ "probe_runtime_environment()"+ if required_imports is None+ else f"probe_runtime_environment({tuple(module for module in required_imports if module)!r})"+ )+ code = (+ "import json; "+ "from core.install_integrity import probe_runtime_environment; "+ f"print({RUNTIME_PROBE_PREFIX!r} + json.dumps({probe_call}))"+ )+ try:+ process = run_isolated_probe([executable, "-c", code], timeout=timeout)+ except (OSError, subprocess.SubprocessError) as exc:+ return IntegrityResult(False, failures=(f"runtime probe failed: {exc}",))+ if process.returncode != 0:+ detail = (process.stderr or process.stdout or "runtime probe failed").strip().splitlines()[-1]+ return IntegrityResult(False, failures=(f"runtime probe failed: {detail}",))++ dependency_line = next(+ (line for line in process.stdout.splitlines() if line.startswith(RUNTIME_PROBE_PREFIX)),+ None,+ )+ try:+ record_names = tuple(json.loads(dependency_line.removeprefix(RUNTIME_PROBE_PREFIX)))+ except (AttributeError, TypeError, ValueError, json.JSONDecodeError):+ return IntegrityResult(False, failures=("runtime probe did not report its dependency records",))++ failures: list[str] = []+ checked = 0+ records_by_site: dict[Path, list[Path]] = {site_package: [] for site_package in site_packages}+ for record_name in record_names:+ try:+ record = Path(record_name).expanduser().resolve()+ site_package = next(root for root in site_packages if record.is_relative_to(root))+ except (OSError, RuntimeError, StopIteration):+ failures.append(f"dependency RECORD outside candidate site-packages: {record_name}")+ continue+ records_by_site[site_package].append(record)+ for site_package, records in records_by_site.items():+ if not records:+ continue+ result = verify_record_files(site_package, records)+ checked += result.checked_files+ failures.extend(result.failures)+ if failures:+ return IntegrityResult(False, checked_files=checked, failures=tuple(failures))++ return IntegrityResult(True, checked_files=checked)diff --git a/docs/INSTALL_FOR_AI.md b/docs/INSTALL_FOR_AI.mdindex 3519727c1..a4c6dea04 100644--- a/docs/INSTALL_FOR_AI.md+++ b/docs/INSTALL_FOR_AI.md@@ -166,6 +166,10 @@ Only run this if the user asks to remove Avibe:```bashvibe stop+avibe_home="${AVIBE_HOME:-$HOME/.avibe}"+avibe_home="${avibe_home/#\~/$HOME}"uv tool uninstall vibe-remote-rm -rf ~/.vibe_remote+vibe_bin="$(command -v vibe)" && rm -f "$vibe_bin" "$(dirname "$vibe_bin")/.vibe.avibe-generation"+rm -rf "$avibe_home/runtime/install-generations"+rm -rf "$avibe_home" ~/.vibe_remote```diff --git a/docs/INSTALL_FOR_AI_ZH.md b/docs/INSTALL_FOR_AI_ZH.mdindex 5c516f24b..18adb2b73 100644--- a/docs/INSTALL_FOR_AI_ZH.md+++ b/docs/INSTALL_FOR_AI_ZH.md@@ -166,6 +166,10 @@ vibe doctor```bashvibe stop+avibe_home="${AVIBE_HOME:-$HOME/.avibe}"+avibe_home="${avibe_home/#\~/$HOME}"uv tool uninstall vibe-remote-rm -rf ~/.vibe_remote+vibe_bin="$(command -v vibe)" && rm -f "$vibe_bin" "$(dirname "$vibe_bin")/.vibe.avibe-generation"+rm -rf "$avibe_home/runtime/install-generations"+rm -rf "$avibe_home" ~/.vibe_remote```diff --git a/install.ps1 b/install.ps1index 0dc86654b..883ffac05 100644--- a/install.ps1+++ b/install.ps1@@ -54,6 +54,89 @@ function Test-Command {return $?}+function Resolve-InstallPath {+ param([string]$Path)++ $expanded = $Path+ if ($expanded -eq "~") {+ $expanded = $env:USERPROFILE+ } elseif ($expanded.StartsWith("~\") -or $expanded.StartsWith("~/")) {+ $expanded = Join-Path $env:USERPROFILE $expanded.Substring(2)+ }+ if (-not [System.IO.Path]::IsPathRooted($expanded)) {+ $expanded = Join-Path (Get-Location) $expanded+ }+ return [System.IO.Path]::GetFullPath($expanded)+}++function Get-StableBinDirectory {+ $configured = $env:UV_TOOL_BIN_DIR+ $directory = if ($configured) { $configured } else { Join-Path $env:USERPROFILE ".local\bin" }+ return Resolve-InstallPath $directory+}++function Get-LauncherState {+ param(+ [string]$Launcher,+ [string]$RuntimeHome+ )++ $state = @{+ Exists = Test-Path -LiteralPath $Launcher+ SourcePath = $null+ ActivationOwner = $null+ }+ if (-not $state.Exists) {+ return $state+ }++ $previousPythonPath = $env:PYTHONPATH+ $previousPythonHome = $env:PYTHONHOME+ $previousAvibeHome = $env:AVIBE_HOME+ Remove-Item Env:PYTHONPATH -ErrorAction SilentlyContinue+ Remove-Item Env:PYTHONHOME -ErrorAction SilentlyContinue+ $env:AVIBE_HOME = $RuntimeHome+ Push-Location $RuntimeHome+ try {+ $protocol = Invoke-NativeCommand -FilePath $Launcher -Arguments @("__activate-install", "--protocol-version")+ if ((Get-InstallProtocolVersion $protocol) -ge 2) {+ $snapshot = Invoke-NativeCommand `+ -FilePath $Launcher `+ -Arguments @("__activate-install", "--snapshot", "--launcher", $Launcher)+ if ($snapshot.Success -and $snapshot.Stdout.Trim()) {+ $state.SourcePath = $snapshot.Stdout.Trim()+ $owner = Join-Path $state.SourcePath "bin\vibe.exe"+ if (Test-Path -LiteralPath $owner) {+ $state.ActivationOwner = $owner+ }+ return $state+ }+ }+ } catch {+ # Released pre-protocol launchers fall through to legacy link discovery.+ } finally {+ Pop-Location+ if ($null -eq $previousPythonPath) { Remove-Item Env:PYTHONPATH -ErrorAction SilentlyContinue } else { $env:PYTHONPATH = $previousPythonPath }+ if ($null -eq $previousPythonHome) { Remove-Item Env:PYTHONHOME -ErrorAction SilentlyContinue } else { $env:PYTHONHOME = $previousPythonHome }+ if ($null -eq $previousAvibeHome) { Remove-Item Env:AVIBE_HOME -ErrorAction SilentlyContinue } else { $env:AVIBE_HOME = $previousAvibeHome }+ }+ try {+ $item = Get-Item -LiteralPath $Launcher -ErrorAction Stop+ $target = @($item.Target)[0]+ if (-not $target) {+ return $state+ }+ if (-not [System.IO.Path]::IsPathRooted($target)) {+ $target = Join-Path $item.DirectoryName $target+ }+ $state.SourcePath = Resolve-InstallPath $target+ $state.ActivationOwner = $state.SourcePath+ } catch {+ return $state+ }+ return $state+}+function Invoke-WebScriptWithRetry {param([string]$Url)@@ -192,14 +275,11 @@ function Invoke-NativeCommand {$stderrPath = [System.IO.Path]::GetTempFileName()try {- $process = Start-Process -FilePath $FilePath `- -ArgumentList $Arguments `- -RedirectStandardOutput $stdoutPath `- -RedirectStandardError $stderrPath `- -NoNewWindow `- -Wait `- -PassThru `- -ErrorAction Stop+ # PowerShell's call operator preserves the argument vector. In+ # contrast, Start-Process joins ArgumentList with spaces and loses the+ # boundaries around paths containing whitespace.+ & $FilePath @Arguments 1> $stdoutPath 2> $stderrPath+ $exitCode = $LASTEXITCODE$stdout = if (Test-Path $stdoutPath) { [System.IO.File]::ReadAllText($stdoutPath) } else { "" }$stderr = if (Test-Path $stderrPath) { [System.IO.File]::ReadAllText($stderrPath) } else { "" }@@ -213,30 +293,37 @@ function Invoke-NativeCommand {}return @{- Success = ($process.ExitCode -eq 0)- ExitCode = $process.ExitCode+ Success = ($exitCode -eq 0)+ ExitCode = $exitCode+ Stdout = $stdout.Trim()+ Stderr = $stderr.Trim()Output = ($capturedOutput -join [System.Environment]::NewLine).Trim()}} catch {$capturedOutput = @()+ $stdout = ""+ $stderr = ""- foreach ($path in @($stdoutPath, $stderrPath)) {- if (Test-Path $path) {- $streamOutput = [System.IO.File]::ReadAllText($path).Trim()- if ($streamOutput) {- $capturedOutput += $streamOutput- }- }+ if (Test-Path $stdoutPath) {+ $stdout = [System.IO.File]::ReadAllText($stdoutPath).Trim()+ if ($stdout) { $capturedOutput += $stdout }+ }+ if (Test-Path $stderrPath) {+ $stderr = [System.IO.File]::ReadAllText($stderrPath).Trim()+ if ($stderr) { $capturedOutput += $stderr }}$errorText = ($_ | Out-String).Trim()if ($errorText) {$capturedOutput += $errorText}+ $capturedStderr = (($stderr, $errorText) | Where-Object { $_ }) -join [System.Environment]::NewLinereturn @{Success = $falseExitCode = 1+ Stdout = $stdout+ Stderr = $capturedStderrOutput = ($capturedOutput -join [System.Environment]::NewLine).Trim()}} finally {@@ -248,10 +335,184 @@ function Invoke-NativeCommand {}}+function Get-InstallProtocolVersion {+ param([object]$Result)++ if (-not $Result.Success) {+ return 0+ }+ [int]$version = 0+ if (-not [int]::TryParse($Result.Stdout.Trim(), [ref]$version)) {+ return 0+ }+ return $version+}++function Activate-LegacyInstallCandidate {+ param(+ [string]$Candidate,+ [string]$StableLauncher,+ [string]$StableBin,+ [string]$GenerationRoot+ )++ $probe = Invoke-NativeCommand -FilePath $Candidate -Arguments @("--help")+ if (-not $probe.Success) {+ return @{+ Success = $false+ ExitCode = $probe.ExitCode+ Output = if ($probe.Output) { $probe.Output } else { "candidate vibe launcher failed its startup probe" }+ }+ }++ $replacement = Join-Path $StableBin ("vibe.exe.avibe-" + [Guid]::NewGuid().ToString("N") + ".new")+ try {+ try {+ New-Item -ItemType SymbolicLink -Path $replacement -Target $Candidate -ErrorAction Stop | Out-Null+ } catch {+ try {+ New-Item -ItemType HardLink -Path $replacement -Target $Candidate -ErrorAction Stop | Out-Null+ } catch {+ Copy-Item -LiteralPath $Candidate -Destination $replacement -Force -ErrorAction Stop+ }+ }+ # This fallback is fresh-install only. File.Move atomically refuses to+ # overwrite a launcher that appeared while the candidate was staging.+ [System.IO.File]::Move($replacement, $StableLauncher)+ } catch {+ Remove-Item -LiteralPath $replacement -Force -ErrorAction SilentlyContinue+ return @{ Success = $false; ExitCode = 1; Output = (($_ | Out-String).Trim()) }+ }++ $markerReplacement = $null+ try {+ $marker = Join-Path $StableBin ".vibe.exe.avibe-generation"+ $markerReplacement = Join-Path $StableBin (".vibe.exe.avibe-generation-" + [Guid]::NewGuid().ToString("N") + ".new")+ Set-Content -LiteralPath $markerReplacement -Value $GenerationRoot -Encoding UTF8+ Move-Item -Force -Path $markerReplacement -Destination $marker+ } catch {+ if ($markerReplacement) {+ Remove-Item -LiteralPath $markerReplacement -Force -ErrorAction SilentlyContinue+ }+ Write-Warning "Could not record the legacy install generation; retained all installed generations."+ }+ return @{ Success = $true; ExitCode = 0; Output = "" }+}+function Invoke-UvToolInstallAttempt {param([string[]]$Arguments)- return Invoke-NativeCommand -FilePath "uv" -Arguments (@("tool", "install") + $Arguments)+ $defaultHome = Join-Path $env:USERPROFILE ".avibe"+ $legacyHome = Join-Path $env:USERPROFILE ".vibe_remote"+ $runtimeHome = if ($env:AVIBE_HOME) {+ $env:AVIBE_HOME+ } elseif (Test-Path $defaultHome) {+ $defaultHome+ } elseif (Test-Path $legacyHome) {+ $legacyHome+ } else {+ $defaultHome+ }+ $runtimeHome = Resolve-InstallPath $runtimeHome+ $generationRoot = Join-Path (Join-Path $runtimeHome "runtime\install-generations") ([Guid]::NewGuid().ToString("N"))+ $generationTools = Join-Path $generationRoot "tools"+ $generationBin = Join-Path $generationRoot "bin"+ $stableBin = Get-StableBinDirectory+ $stableLauncher = Join-Path $stableBin "vibe.exe"+ # The candidate's shared Python activation owner resolves this snapshot to+ # a generation. PowerShell must not duplicate junction/symlink identity.+ $launcherState = Get-LauncherState -Launcher $stableLauncher -RuntimeHome $runtimeHome+ $previousSourcePath = $launcherState.SourcePath+ New-Item -ItemType Directory -Force -Path $generationTools, $generationBin, $stableBin | Out-Null++ $previousToolDir = $env:UV_TOOL_DIR+ $previousToolBinDir = $env:UV_TOOL_BIN_DIR+ try {+ $env:UV_TOOL_DIR = $generationTools+ $env:UV_TOOL_BIN_DIR = $generationBin+ $result = Invoke-NativeCommand -FilePath "uv" -Arguments (@("tool", "install") + $Arguments)+ if (-not $result.Success) {+ Remove-Item -LiteralPath $generationRoot -Recurse -Force -ErrorAction SilentlyContinue+ return $result+ }++ $candidate = Join-Path $generationBin "vibe.exe"+ if (-not (Test-Path $candidate)) {+ Remove-Item -LiteralPath $generationRoot -Recurse -Force -ErrorAction SilentlyContinue+ return @{+ Success = $false+ ExitCode = 1+ Output = "uv completed but the candidate vibe launcher was not created"+ }+ }++ $previousPythonPath = $env:PYTHONPATH+ $previousPythonHome = $env:PYTHONHOME+ $previousAvibeHome = $env:AVIBE_HOME+ Remove-Item Env:PYTHONPATH -ErrorAction SilentlyContinue+ Remove-Item Env:PYTHONHOME -ErrorAction SilentlyContinue+ $env:AVIBE_HOME = $runtimeHome+ Push-Location $runtimeHome+ try {+ $protocol = Invoke-NativeCommand -FilePath $candidate -Arguments @("__activate-install", "--protocol-version")+ $activationOwner = if ((Get-InstallProtocolVersion $protocol) -ge 1) {+ $candidate+ } elseif ($launcherState.ActivationOwner) {+ $ownerProtocol = Invoke-NativeCommand `+ -FilePath $launcherState.ActivationOwner `+ -Arguments @("__activate-install", "--protocol-version")+ if ((Get-InstallProtocolVersion $ownerProtocol) -ge 1) {+ $launcherState.ActivationOwner+ } else {+ $null+ }+ } else {+ $null+ }+ if ($activationOwner) {+ $activationArguments = @(+ "__activate-install",+ "--launcher", $stableLauncher,+ "--candidate", $candidate+ )+ if ($previousSourcePath) {+ $activationArguments += @("--source-generation", $previousSourcePath)+ }+ $activation = Invoke-NativeCommand -FilePath $activationOwner -Arguments $activationArguments+ } elseif ($launcherState.Exists) {+ $activation = @{+ Success = $false+ ExitCode = 1+ Output = "legacy candidate cannot safely replace an existing Avibe installation"+ }+ } else {+ # A legacy wheel may bootstrap a fresh machine. Existing+ # installs must route through a protocol-aware current owner.+ $activation = Activate-LegacyInstallCandidate `+ -Candidate $candidate `+ -StableLauncher $stableLauncher `+ -StableBin $stableBin `+ -GenerationRoot $generationRoot+ }+ } finally {+ Pop-Location+ if ($null -eq $previousPythonPath) { Remove-Item Env:PYTHONPATH -ErrorAction SilentlyContinue } else { $env:PYTHONPATH = $previousPythonPath }+ if ($null -eq $previousPythonHome) { Remove-Item Env:PYTHONHOME -ErrorAction SilentlyContinue } else { $env:PYTHONHOME = $previousPythonHome }+ if ($null -eq $previousAvibeHome) { Remove-Item Env:AVIBE_HOME -ErrorAction SilentlyContinue } else { $env:AVIBE_HOME = $previousAvibeHome }+ }+ if (-not $activation.Success) {+ Remove-Item -LiteralPath $generationRoot -Recurse -Force -ErrorAction SilentlyContinue+ return @{+ Success = $false+ ExitCode = $activation.ExitCode+ Output = if ($activation.Output) { $activation.Output } else { "candidate Avibe environment could not be activated" }+ }+ }+ return $result+ } finally {+ if ($null -eq $previousToolDir) { Remove-Item Env:UV_TOOL_DIR -ErrorAction SilentlyContinue } else { $env:UV_TOOL_DIR = $previousToolDir }+ if ($null -eq $previousToolBinDir) { Remove-Item Env:UV_TOOL_BIN_DIR -ErrorAction SilentlyContinue } else { $env:UV_TOOL_BIN_DIR = $previousToolBinDir }+ }}function Install-Vibe {@@ -322,34 +583,19 @@ function Install-Vibe {function Test-Installation {Write-Info "Verifying installation..."-- # Refresh PATH- $env:Path = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")- $env:Path += ";$env:USERPROFILE\.local\bin"-- if (Test-Command "vibe") {++ $stableBin = Get-StableBinDirectory+ $stableLauncher = Join-Path $stableBin "vibe.exe"+ $persistedPath = [System.Environment]::GetEnvironmentVariable("Path", "Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path", "User")+ $env:Path = "$stableBin;$persistedPath"++ if (Test-Path -LiteralPath $stableLauncher) {Write-Success "vibe command is available"Write-Host ""- & vibe --help+ & $stableLauncher --helpreturn $true}-- # Check common install locations- $vibeLocations = @(- "$env:USERPROFILE\.local\bin\vibe.exe"- )-- foreach ($loc in $vibeLocations) {- if (Test-Path $loc) {- Write-Warning "vibe installed at $loc but not in PATH"- Write-Host ""- Write-Host "Add this directory to your PATH:" -ForegroundColor Yellow- Write-Host " $(Split-Path $loc)"- Write-Host ""- return $true- }- }-+Write-Error "Installation verification failed. vibe command not found."}@@ -359,13 +605,14 @@ function Prepare-ShowRuntime {return}- if (-not (Test-Command "vibe")) {+ $stableLauncher = Join-Path (Get-StableBinDirectory) "vibe.exe"+ if (-not (Test-Path -LiteralPath $stableLauncher)) {Write-Warning "Show Runtime was not prepared because the vibe command is not available yet"return}Write-Info "Preparing Show Runtime for this platform..."- $result = Invoke-NativeCommand -FilePath "vibe" -Arguments @("runtime", "prepare", "--strict")+ $result = Invoke-NativeCommand -FilePath $stableLauncher -Arguments @("runtime", "prepare", "--strict")if ($result.Success) {Write-Success "Show Runtime is ready"return@@ -379,6 +626,7 @@ function Prepare-ShowRuntime {}function Write-NextSteps {+ $stableBin = Get-StableBinDirectoryWrite-Host ""Write-Host "Installation complete!" -ForegroundColor GreenWrite-Host ""@@ -397,7 +645,11 @@ function Write-NextSteps {Write-Host " uv tool uninstall avibe-os"Write-Host " uv tool uninstall vibe-remote"Write-Host " pip uninstall avibe-os vibe-remote"- Write-Host " Remove-Item -Recurse ~\.avibe, ~\.vibe_remote # remove config and data"+ Write-Host (" Remove-Item -Force `"$(Join-Path $stableBin 'vibe.exe')`"")+ Write-Host (" Remove-Item -Force `"$(Join-Path $stableBin '.vibe.exe.avibe-generation')`"")+ Write-Host ' $avibeHome = if ($env:AVIBE_HOME) { $env:AVIBE_HOME -replace ''^~(?=[\\/]|$)'', $env:USERPROFILE } else { "$env:USERPROFILE\.avibe" }'+ Write-Host ' Remove-Item -Recurse -Force (Join-Path $avibeHome "runtime\install-generations")'+ Write-Host ' Remove-Item -Recurse $avibeHome, ~\.vibe_remote # remove config and data'Write-Host ""Write-Host "Documentation:" -ForegroundColor BlueWrite-Host " https://github.com/$REPO#readme"diff --git a/install.sh b/install.shindex ee63ef3dc..5d607f39d 100755--- a/install.sh+++ b/install.sh@@ -19,7 +19,21 @@ PACKAGE_NAME="avibe-os"NODE_MINIMUM_REQUIREMENT="20.19+ or 22.12+"VIBE_BIN_PATH=""VIBE_TOOL_BIN_DIR=""+VIBE_CANDIDATE_BIN_PATH=""ORIGINAL_PATH="$PATH"+if [ -n "${AVIBE_HOME:-}" ]; then+ AVIBE_RUNTIME_HOME="${AVIBE_HOME/#\~/$HOME}"+ case "$AVIBE_RUNTIME_HOME" in+ /*) ;;+ *) AVIBE_RUNTIME_HOME="$PWD/$AVIBE_RUNTIME_HOME" ;;+ esac+elif [ -e "$HOME/.avibe" ] || [ -L "$HOME/.avibe" ]; then+ AVIBE_RUNTIME_HOME="$HOME/.avibe"+elif [ -e "$HOME/.vibe_remote" ] || [ -L "$HOME/.vibe_remote" ]; then+ AVIBE_RUNTIME_HOME="$HOME/.vibe_remote"+else+ AVIBE_RUNTIME_HOME="$HOME/.avibe"+fiREMOTE_ACCESS_PAIRING_KEY=""REMOTE_ACCESS_PAIRED=""@@ -403,11 +417,110 @@ install_node_optional() {}uv_tool_install() {- if [ -n "$VIBE_TOOL_BIN_DIR" ]; then- UV_TOOL_BIN_DIR="$VIBE_TOOL_BIN_DIR" uv tool install "$@"- else- uv tool install "$@"+ # uv writes a tool environment in place. Give every attempt its own+ # durable generation and activate its launcher only after uv exits+ # successfully, so an interrupted copy cannot damage the active install.+ local generation_root="$AVIBE_RUNTIME_HOME/runtime/install-generations/$(date +%s)-$$-${RANDOM}"+ local generation_tools="$generation_root/tools"+ local generation_bin="$generation_root/bin"+ local stable_bin_dir="${VIBE_TOOL_BIN_DIR:-$HOME/.local/bin}"+ local previous_target=""+ local source_snapshot=""+ mkdir -p "$generation_tools" "$generation_bin" "$stable_bin_dir"+ if [ -e "$stable_bin_dir/vibe" ] || [ -L "$stable_bin_dir/vibe" ]; then+ previous_target="$(resolve_binary_path "$stable_bin_dir/vibe" || true)"+ local current_protocol=""+ current_protocol="$(+ cd "$AVIBE_RUNTIME_HOME" || exit 1+ env -u PYTHONPATH -u PYTHONHOME AVIBE_HOME="$AVIBE_RUNTIME_HOME" "$stable_bin_dir/vibe" \+ __activate-install --protocol-version 2>/dev/null || true+ )"+ if [ "${current_protocol:-0}" -ge 2 ] 2>/dev/null; then+ source_snapshot="$(+ cd "$AVIBE_RUNTIME_HOME" || exit 1+ env -u PYTHONPATH -u PYTHONHOME AVIBE_HOME="$AVIBE_RUNTIME_HOME" "$stable_bin_dir/vibe" \+ __activate-install --snapshot --launcher "$stable_bin_dir/vibe" 2>/dev/null || true+ )"+ else+ source_snapshot="$previous_target"+ fifi++ if UV_TOOL_DIR="$generation_tools" UV_TOOL_BIN_DIR="$generation_bin" uv tool install "$@"; then+ VIBE_CANDIDATE_BIN_PATH="$generation_bin/vibe"+ if [ ! -x "$VIBE_CANDIDATE_BIN_PATH" ]; then+ warn "uv completed but the candidate vibe launcher was not created"+ rm -rf -- "$generation_root"+ return 1+ fi+ # The candidate's shared Python activation owner canonicalizes this+ # snapshot against the generation root. Keep path identity out of the+ # bootstrap script so aliases cannot produce a second interpretation.+ local activation_args=(+ __activate-install+ --launcher "$stable_bin_dir/vibe"+ --candidate "$VIBE_CANDIDATE_BIN_PATH"+ )+ if [ -n "$source_snapshot" ]; then+ activation_args+=(--source-generation "$source_snapshot")+ fi+ local activation_owner=""+ local owner=""+ local owner_protocol=""+ for owner in "$VIBE_CANDIDATE_BIN_PATH" "$previous_target"; do+ if [ -z "$owner" ] || [ ! -x "$owner" ]; then+ continue+ fi+ owner_protocol="$(+ cd "$AVIBE_RUNTIME_HOME" || exit 1+ env -u PYTHONPATH -u PYTHONHOME AVIBE_HOME="$AVIBE_RUNTIME_HOME" "$owner" \+ __activate-install --protocol-version 2>/dev/null || true+ )"+ if [ "${owner_protocol:-0}" -ge 1 ] 2>/dev/null; then+ activation_owner="$owner"+ break+ fi+ done+ if [ -n "$activation_owner" ]; then+ if ! (+ cd "$AVIBE_RUNTIME_HOME" || exit 1+ env -u PYTHONPATH -u PYTHONHOME AVIBE_HOME="$AVIBE_RUNTIME_HOME" "$activation_owner" \+ "${activation_args[@]}"+ ); then+ warn "candidate Avibe environment could not be activated"+ rm -rf -- "$generation_root"+ return 1+ fi+ else+ # A legacy wheel can bootstrap a fresh machine, but replacing an+ # existing launcher requires a current wheel to own the shared+ # lock and source-snapshot checks above.+ if ! (+ cd "$AVIBE_RUNTIME_HOME" || exit 1+ env -u PYTHONPATH -u PYTHONHOME AVIBE_HOME="$AVIBE_RUNTIME_HOME" \+ "$VIBE_CANDIDATE_BIN_PATH" --help >/dev/null 2>&1+ ); then+ warn "candidate vibe launcher failed its startup probe"+ rm -rf -- "$generation_root"+ return 1+ fi+ if [ -e "$stable_bin_dir/vibe" ] || [ -L "$stable_bin_dir/vibe" ]; then+ warn "legacy candidate cannot safely replace an existing Avibe installation"+ rm -rf -- "$generation_root"+ return 1+ fi+ if ! ln -s "$VIBE_CANDIDATE_BIN_PATH" "$stable_bin_dir/vibe"; then+ warn "legacy candidate Avibe launcher could not be activated"+ rm -rf -- "$generation_root"+ return 1+ fi+ fi+ VIBE_TOOL_BIN_DIR="$stable_bin_dir"+ VIBE_BIN_PATH="$stable_bin_dir/vibe"+ return 0+ fi+ rm -rf -- "$generation_root"+ return 1}install_package_candidate() {@@ -615,6 +728,17 @@ pair_remote_access() {success "Avibe service started"}+print_uninstall_commands() {+ echo " avibe_home=\"\${AVIBE_HOME:-\$HOME/.avibe}\""+ echo ' avibe_home="${avibe_home/#\~/$HOME}"'+ echo " uv tool uninstall avibe-os # current uv install"+ echo " uv tool uninstall vibe-remote # legacy uv install"+ echo " pip uninstall avibe-os vibe-remote"+ echo " rm -f \"$VIBE_TOOL_BIN_DIR/vibe\" \"$VIBE_TOOL_BIN_DIR/.vibe.avibe-generation\""+ echo ' rm -rf "$avibe_home/runtime/install-generations"'+ echo ' rm -rf "$avibe_home" ~/.vibe_remote # remove config and data'+}+# Print next stepsprint_next_steps() {local vibe_dir@@ -644,10 +768,7 @@ print_next_steps() {echo " vibe doctor - Run diagnostics"echo ""echo -e "${BLUE}Uninstall:${NC}"- echo " uv tool uninstall avibe-os # current uv install"- echo " uv tool uninstall vibe-remote # legacy uv install"- echo " pip uninstall avibe-os vibe-remote"- echo " rm -rf ~/.avibe ~/.vibe_remote # remove config and data"+ print_uninstall_commandsif ! is_vibe_immediately_available; thenecho ""echo -e "${BLUE}If 'vibe' is not found in a new shell:${NC}"@@ -681,10 +802,7 @@ print_next_steps() {echo " vibe doctor - Run diagnostics"echo ""echo -e "${BLUE}Uninstall:${NC}"- echo " uv tool uninstall avibe-os # current uv install"- echo " uv tool uninstall vibe-remote # legacy uv install"- echo " pip uninstall avibe-os vibe-remote"- echo " rm -rf ~/.avibe ~/.vibe_remote # remove config and data"+ print_uninstall_commandsecho ""echo -e "${BLUE}If 'vibe' is still not found:${NC}"echo " ${VIBE_BIN_PATH:-$HOME/.local/bin/vibe}"diff --git a/tests/test_install_integrity.py b/tests/test_install_integrity.pynew file mode 100644index 000000000..7654c3fd4--- /dev/null+++ b/tests/test_install_integrity.py@@ -0,0 +1,265 @@+import base64+import hashlib+import json+import stat+import subprocess+from pathlib import Path+from types import SimpleNamespace++from config.platform_registry import platform_descriptors+from core import install_integrity+from core.install_integrity import verify_site_packages+++def _write_record(root, relative: str, content: bytes, *, distribution: str = "demo_pkg") -> None:+ path = root / relative+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_bytes(content)+ digest = base64.urlsafe_b64encode(hashlib.sha256(content).digest()).decode().rstrip("=")+ record = root / f"{distribution}-1.0.dist-info" / "RECORD"+ record.parent.mkdir(parents=True, exist_ok=True)+ record.write_text(f"{relative},sha256={digest},{len(content)}\n", encoding="utf-8")+++def _runtime_probe_output(*records: Path) -> str:+ return f"{install_integrity.RUNTIME_PROBE_PREFIX}{json.dumps([str(record) for record in records])}\n"+++def test_verify_site_packages_accepts_complete_record(tmp_path):+ _write_record(tmp_path, "demo_pkg/__init__.py", b"value = 1\n")++ result = verify_site_packages(tmp_path)++ assert result.ok is True+ assert result.checked_files == 1+++def test_verify_site_packages_rejects_a_missing_file_with_valid_metadata(tmp_path):+ _write_record(tmp_path, "demo_pkg/__init__.py", b"value = 1\n")+ (tmp_path / "demo_pkg" / "__init__.py").unlink()++ result = verify_site_packages(tmp_path)++ assert result.ok is False+ assert "missing demo_pkg/__init__.py" in result.failures+++def test_verify_site_packages_rejects_a_changed_file(tmp_path):+ _write_record(tmp_path, "demo_pkg/__init__.py", b"value = 1\n")+ (tmp_path / "demo_pkg" / "__init__.py").write_bytes(b"value = 2\n")++ result = verify_site_packages(tmp_path)++ assert result.ok is False+ assert "hash mismatch demo_pkg/__init__.py" in result.failures+++def test_verify_python_environment_probes_use_private_empty_directories(monkeypatch, tmp_path):+ site_packages = tmp_path / "lib" / "python3.12" / "site-packages"+ _write_record(site_packages, "demo_pkg/__init__.py", b"value = 1\n")+ executable = tmp_path / "bin" / "python3"+ executable.parent.mkdir()+ executable.write_text("#!/bin/sh\n", encoding="utf-8")+ executable.chmod(0o755)+ calls = []++ def fake_run(*args, **kwargs):+ cwd = Path(kwargs["cwd"])+ calls.append(+ {+ **kwargs,+ "cwd_parent": cwd.parent,+ "cwd_mode": stat.S_IMODE(cwd.stat().st_mode),+ "cwd_entries": tuple(cwd.iterdir()),+ }+ )+ stdout = (+ f"{site_packages}\n"+ if len(calls) == 1+ else _runtime_probe_output(site_packages / "demo_pkg-1.0.dist-info" / "RECORD")+ )+ return subprocess.CompletedProcess(args[0], 0, stdout=stdout, stderr="")++ monkeypatch.setattr(install_integrity.subprocess, "run", fake_run)++ result = install_integrity.verify_python_environment(executable, required_imports=("demo_pkg",))++ assert result.ok is True+ assert len(calls) == 2+ assert all(call["cwd_parent"] == Path(install_integrity.tempfile.gettempdir()) for call in calls)+ assert all(call["cwd_mode"] & 0o077 == 0 for call in calls)+ assert all(call["cwd_entries"] == () for call in calls)+ assert calls[0]["cwd"] != calls[1]["cwd"]+++def test_candidate_probe_does_not_inherit_pythonpath(monkeypatch, tmp_path):+ site_packages = tmp_path / "lib" / "python3.12" / "site-packages"+ _write_record(site_packages, "demo_pkg/__init__.py", b"value = 1\n")+ executable = tmp_path / "bin" / "python3"+ executable.parent.mkdir()+ executable.write_text("#!/bin/sh\n", encoding="utf-8")+ executable.chmod(0o755)+ calls = []++ def fake_run(*args, **kwargs):+ calls.append(kwargs)+ if len(calls) == 1:+ return subprocess.CompletedProcess(args[0], 0, stdout=f"{site_packages}\n", stderr="")+ return subprocess.CompletedProcess(+ args[0],+ 0,+ stdout=_runtime_probe_output(site_packages / "demo_pkg-1.0.dist-info" / "RECORD"),+ stderr="",+ )++ monkeypatch.setenv("PYTHONPATH", str(tmp_path))+ monkeypatch.setattr(install_integrity.subprocess, "run", fake_run)++ result = install_integrity.verify_python_environment(executable, required_imports=("demo_pkg",))++ assert result.ok is True+ assert "PYTHONPATH" not in calls[0]["env"]+ assert "PYTHONPATH" not in calls[1]["env"]+++def test_site_discovery_ignores_reported_prefix_without_record(monkeypatch, tmp_path):+ site_packages = tmp_path / "Lib" / "site-packages"+ _write_record(site_packages, "demo_pkg/__init__.py", b"value = 1\n")+ executable = tmp_path / "Scripts" / "python.exe"+ executable.parent.mkdir()+ executable.write_text("", encoding="utf-8")++ def fake_run(*args, **kwargs):+ return subprocess.CompletedProcess(+ args[0],+ 0,+ stdout=f"{tmp_path}\n{site_packages}\n",+ stderr="",+ )++ monkeypatch.setattr(install_integrity.subprocess, "run", fake_run)++ assert install_integrity.site_packages_for_python(executable) == [site_packages.resolve()]+++def test_site_discovery_probe_respects_disabled_user_site(monkeypatch, tmp_path):+ executable = tmp_path / "bin" / "python3"+ executable.parent.mkdir()+ executable.write_text("", encoding="utf-8")+ calls = []++ def fake_run(*args, **kwargs):+ calls.append(args[0][2])+ return subprocess.CompletedProcess(args[0], 0, stdout="", stderr="")++ monkeypatch.setattr(install_integrity.subprocess, "run", fake_run)++ install_integrity.site_packages_for_python(executable)++ assert "ENABLE_USER_SITE" in calls[0]+++def test_site_discovery_ignores_other_python_versions_in_the_same_prefix(monkeypatch, tmp_path):+ selected = tmp_path / "lib" / "python3.12" / "site-packages"+ sibling = tmp_path / "lib" / "python3.11" / "site-packages"+ _write_record(selected, "demo_pkg/__init__.py", b"value = 1\n")+ _write_record(sibling, "demo_pkg/__init__.py", b"value = 1\n")+ executable = tmp_path / "bin" / "python3"+ executable.parent.mkdir()+ executable.write_text("", encoding="utf-8")++ monkeypatch.setattr(+ install_integrity.subprocess,+ "run",+ lambda *args, **kwargs: subprocess.CompletedProcess(args[0], 0, stdout=f"{selected}\n", stderr=""),+ )++ assert install_integrity.site_packages_for_python(executable) == [selected.resolve()]+++def test_verify_site_packages_accepts_dist_packages_entry_point(tmp_path):+ site_packages = tmp_path / "lib" / "python3.12" / "dist-packages"+ entrypoint = tmp_path / "bin" / "vibe"+ entrypoint.parent.mkdir(parents=True)+ entrypoint.write_bytes(b"#!/bin/sh\n")+ digest = base64.urlsafe_b64encode(hashlib.sha256(entrypoint.read_bytes()).digest()).decode().rstrip("=")+ record = site_packages / "demo_pkg-1.0.dist-info" / "RECORD"+ record.parent.mkdir(parents=True)+ record.write_text(f"../../../bin/vibe,sha256={digest},{entrypoint.stat().st_size}\n", encoding="utf-8")++ result = verify_site_packages(site_packages)++ assert result.ok is True+ assert result.checked_files == 1+++def test_runtime_imports_cover_every_registered_platform_client():+ expected = {descriptor.client_module for descriptor in platform_descriptors()}++ assert expected <= set(install_integrity.runtime_import_modules())+++def test_dependency_graph_rejects_a_wholly_missing_declared_distribution(monkeypatch):+ distributions = {+ "avibe-os": SimpleNamespace(+ metadata={"Name": "avibe-os"},+ version="1.0",+ requires=("slack-sdk>=3.26", "discord.py>=2.4"),+ files=(Path("avibe_os-1.0.dist-info/RECORD"),),+ locate_file=lambda path: Path("/site-packages") / path,+ ),+ "slack-sdk": SimpleNamespace(+ metadata={"Name": "slack-sdk"},+ version="3.30",+ requires=(),+ files=(Path("slack_sdk-3.30.dist-info/RECORD"),),+ locate_file=lambda path: Path("/site-packages") / path,+ ),+ }++ def distribution(name):+ try:+ return distributions[name]+ except KeyError as exc:+ raise install_integrity.importlib_metadata.PackageNotFoundError(name) from exc++ monkeypatch.setattr(install_integrity.importlib_metadata, "distribution", distribution)++ graph = install_integrity.inspect_dependency_graph()++ assert graph.distributions == ("avibe-os", "slack-sdk")+ assert graph.records == (+ "/site-packages/avibe_os-1.0.dist-info/RECORD",+ "/site-packages/slack_sdk-3.30.dist-info/RECORD",+ )+ assert graph.failures == ("missing dependency: discord.py",)+++def test_verify_python_environment_ignores_unrelated_distributions(monkeypatch, tmp_path):+ site_packages = tmp_path / "lib" / "python3.12" / "site-packages"+ _write_record(site_packages, "demo_pkg/__init__.py", b"value = 1\n")+ unrelated = site_packages / "unrelated-1.0.dist-info" / "RECORD"+ unrelated.parent.mkdir(parents=True)+ unrelated.write_text("unrelated/missing.py,,\n", encoding="utf-8")+ executable = tmp_path / "bin" / "python3"+ executable.parent.mkdir()+ executable.write_text("#!/bin/sh\n", encoding="utf-8")+ executable.chmod(0o755)+ calls = 0++ def fake_run(*args, **kwargs):+ nonlocal calls+ calls += 1+ stdout = (+ f"{site_packages}\n"+ if calls == 1+ else _runtime_probe_output(site_packages / "demo_pkg-1.0.dist-info" / "RECORD")+ )+ return subprocess.CompletedProcess(args[0], 0, stdout=stdout, stderr="")++ monkeypatch.setattr(install_integrity.subprocess, "run", fake_run)++ result = install_integrity.verify_python_environment(executable, required_imports=("demo_pkg",))++ assert result.ok is True+ assert result.checked_files == 1diff --git a/tests/test_install_script.py b/tests/test_install_script.pyindex 140d17ec3..263f8b64a 100644--- a/tests/test_install_script.py+++ b/tests/test_install_script.py@@ -51,7 +51,65 @@ def _write_fake_uv(path: Path, uv_log: Path) -> None:cat > "$bin_dir/vibe" <<'EOF'#!/usr/bin/env bashset -euo pipefail- if [ "${{1:-}}" = "--help" ]; then+ if [ "${{VIBE_TEST_REQUIRE_CANONICAL_HOME:-}}" = "1" ] && \+ [ "${{AVIBE_HOME:-}}" != "${{VIBE_TEST_EXPECTED_AVIBE_HOME:-}}" ]; then+ echo "AVIBE_HOME was not canonicalized" >&2+ exit 21+ fi+ if [ "${{1:-}}" = "__activate-install" ]; then+ if [ "${{2:-}}" = "--protocol-version" ]; then+ if [ -f "$(dirname "$0")/.legacy-activation" ]; then+ exit 2+ fi+ echo "2"+ exit 0+ fi+ if [ "${{2:-}}" = "--snapshot" ]; then+ launcher=""+ shift 2+ while [ "$#" -gt 0 ]; do+ case "$1" in+ --launcher) launcher="$2"; shift 2 ;;+ *) shift ;;+ esac+ done+ target="$(readlink "$launcher" 2>/dev/null || true)"+ if [ -n "$target" ]; then+ case "$target" in+ /*) ;;+ *) target="$(dirname "$launcher")/$target" ;;+ esac+ dirname "$(dirname "$target")"+ fi+ exit 0+ fi+ if [ "${{VIBE_TEST_CANDIDATE_PROBE_FAIL:-}}" = "1" ]; then+ echo "candidate import failed" >&2+ exit 19+ fi+ shift+ if [ -n "${{VIBE_TEST_ACTIVATION_OWNER_LOG:-}}" ]; then+ printf '%s' "$0" > "$VIBE_TEST_ACTIVATION_OWNER_LOG"+ fi+ launcher=""+ candidate=""+ source_generation=""+ while [ "$#" -gt 0 ]; do+ case "$1" in+ --launcher) launcher="$2"; shift 2 ;;+ --candidate) candidate="$2"; shift 2 ;;+ --source-generation) source_generation="$2"; shift 2 ;;+ *) shift ;;+ esac+ done+ if [ "${{VIBE_TEST_REQUIRE_SOURCE_GENERATION:-}}" = "1" ] && [ -z "$source_generation" ]; then+ echo "source generation missing" >&2+ exit 20+ fi+ replacement="${{launcher}}.new"+ ln -s "$candidate" "$replacement"+ mv -f "$replacement" "$launcher"+ elif [ "${{1:-}}" = "--help" ]; thenecho "usage: vibe"elif [ "${{1:-}}" = "version" ]; thenecho "avibe-os 9.9.9"@@ -88,6 +146,25 @@ def _write_fake_uv(path: Path, uv_log: Path) -> None:fiEOFchmod +x "$bin_dir/vibe"+ if [ "${{VIBE_TEST_LEGACY_ACTIVATION:-}}" = "1" ]; then+ touch "$bin_dir/.legacy-activation"+ fi+ cat > "$bin_dir/python3" <<'EOF'+ #!/usr/bin/env bash+ if [ "${1:-}" = "-c" ]; then+ if [ "${{VIBE_TEST_CANDIDATE_PROBE_FAIL:-}}" = "1" ]; then+ echo "candidate import failed" >&2+ exit 19+ fi+ echo "verified 1 package files"+ exit 0+ fi+ exit 1+ EOF+ chmod +x "$bin_dir/python3"+ if [ "${{VIBE_TEST_UV_FAIL:-}}" = "1" ]; then+ exit 17+ fi""",)@@ -179,6 +256,13 @@ def _vibe_version(env: dict[str, str], *, cwd: Path = REPO_ROOT) -> subprocess.Creturn _run("vibe version", cwd=cwd, env=env)+def _assert_staged_uv_bin(uv_log: Path, home_dir: Path) -> None:+ staged = Path(uv_log.read_text(encoding="utf-8"))+ assert staged.is_absolute()+ assert staged.name == "bin"+ assert staged.parent.parent == home_dir / ".avibe" / "runtime" / "install-generations"++def test_install_script_keeps_vibe_available_on_current_path(tmp_path):home_dir = tmp_path / "home"home_dir.mkdir()@@ -204,6 +288,173 @@ def test_install_script_keeps_vibe_available_on_current_path(tmp_path):assert uv_log.read_text(encoding="utf-8")+def test_install_script_canonicalizes_relative_avibe_home(tmp_path):+ home_dir = tmp_path / "home"+ home_dir.mkdir()+ path_dir = tmp_path / "path-bin"+ path_dir.mkdir()+ uv_log = tmp_path / "uv-tool-bin-dir.txt"+ _write_fake_uv(path_dir / "uv", uv_log)++ env = os.environ.copy()+ env["HOME"] = str(home_dir)+ env["AVIBE_HOME"] = "relative-avibe"+ env["PATH"] = os.pathsep.join([str(path_dir), "/usr/bin", "/bin"])+ env["VIBE_TEST_REQUIRE_CANONICAL_HOME"] = "1"+ env["VIBE_TEST_EXPECTED_AVIBE_HOME"] = str(tmp_path / "relative-avibe")++ install_result = _install(env, cwd=tmp_path)++ assert install_result.returncode == 0, install_result.stdout + install_result.stderr+ launcher = path_dir / "vibe"+ assert launcher.is_symlink()+ target = Path(os.readlink(launcher))+ assert target.is_absolute()+ assert target.is_file()+ assert target.is_relative_to(tmp_path / "relative-avibe" / "runtime" / "install-generations")+++def test_repeated_install_preserves_source_through_a_home_symlink(tmp_path):+ home_dir = tmp_path / "home"+ home_dir.mkdir()+ physical_runtime_home = tmp_path / "physical-avibe"+ physical_runtime_home.mkdir()+ logical_runtime_home = tmp_path / "logical-avibe"+ logical_runtime_home.symlink_to(physical_runtime_home, target_is_directory=True)+ path_dir = tmp_path / "path-bin"+ path_dir.mkdir()+ uv_log = tmp_path / "uv-tool-bin-dir.txt"+ _write_fake_uv(path_dir / "uv", uv_log)++ env = os.environ.copy()+ env["HOME"] = str(home_dir)+ env["AVIBE_HOME"] = str(logical_runtime_home)+ env["PATH"] = os.pathsep.join([str(path_dir), "/usr/bin", "/bin"])++ first = _install(env)+ launcher = path_dir / "vibe"+ physical_target = launcher.resolve()+ launcher.unlink()+ launcher.symlink_to(physical_target)+ env["VIBE_TEST_REQUIRE_SOURCE_GENERATION"] = "1"+ second = _install(env)++ assert first.returncode == 0, first.stdout + first.stderr+ assert second.returncode == 0, second.stdout + second.stderr+++def test_repeated_installer_runs_prune_old_generations(tmp_path):+ home_dir = tmp_path / "home"+ home_dir.mkdir()+ path_dir = tmp_path / "path-bin"+ path_dir.mkdir()+ uv_log = tmp_path / "uv-tool-bin-dir.txt"+ _write_fake_uv(path_dir / "uv", uv_log)++ env = os.environ.copy()+ env["HOME"] = str(home_dir)+ env["PATH"] = os.pathsep.join([str(path_dir), "/usr/bin", "/bin"])++ first = _install(env)+ first_generations = sorted((home_dir / ".avibe" / "runtime" / "install-generations").iterdir())+ second = _install(env)+ generations = sorted((home_dir / ".avibe" / "runtime" / "install-generations").iterdir())++ assert first.returncode == 0, first.stdout + first.stderr+ assert second.returncode == 0, second.stdout + second.stderr+ assert len(first_generations) == 1+ assert len(generations) == 2+ assert all(path.is_dir() for path in generations)+++def test_install_script_activates_a_wheel_without_the_shared_protocol(tmp_path):+ home_dir = tmp_path / "home"+ home_dir.mkdir()+ path_dir = tmp_path / "path-bin"+ path_dir.mkdir()+ uv_log = tmp_path / "uv-tool-bin-dir.txt"+ _write_fake_uv(path_dir / "uv", uv_log)++ env = os.environ.copy()+ env["HOME"] = str(home_dir)+ env["PATH"] = os.pathsep.join([str(path_dir), "/usr/bin", "/bin"])+ env["VIBE_TEST_LEGACY_ACTIVATION"] = "1"++ install_result = _install(env)+ version_result = _vibe_version(env)++ assert install_result.returncode == 0, install_result.stdout + install_result.stderr+ assert version_result.returncode == 0, version_result.stdout + version_result.stderr+ assert "avibe-os 9.9.9" in version_result.stdout+++def test_install_script_uses_the_current_owner_for_a_legacy_candidate(tmp_path):+ home_dir = tmp_path / "home"+ home_dir.mkdir()+ path_dir = tmp_path / "path-bin"+ path_dir.mkdir()+ uv_log = tmp_path / "uv-tool-bin-dir.txt"+ owner_log = tmp_path / "activation-owner.txt"+ _write_fake_uv(path_dir / "uv", uv_log)++ env = os.environ.copy()+ env["HOME"] = str(home_dir)+ env["PATH"] = os.pathsep.join([str(path_dir), "/usr/bin", "/bin"])++ first = _install(env)+ first_owner = (path_dir / "vibe").resolve()+ env["VIBE_TEST_LEGACY_ACTIVATION"] = "1"+ env["VIBE_TEST_ACTIVATION_OWNER_LOG"] = str(owner_log)+ second = _install(env)++ assert first.returncode == 0, first.stdout + first.stderr+ assert second.returncode == 0, second.stdout + second.stderr+ assert Path(owner_log.read_text(encoding="utf-8")).samefile(first_owner)+ assert (path_dir / "vibe").resolve() != first_owner+++def test_install_script_keeps_active_launcher_when_uv_install_fails(tmp_path):+ home_dir = tmp_path / "home"+ home_dir.mkdir()+ path_dir = tmp_path / "path-bin"+ path_dir.mkdir()+ uv_log = tmp_path / "uv-tool-bin-dir.txt"+ active = path_dir / "vibe"+ _write_executable(active, "#!/usr/bin/env bash\necho stable\n")+ _write_fake_uv(path_dir / "uv", uv_log)++ env = os.environ.copy()+ env["HOME"] = str(home_dir)+ env["PATH"] = os.pathsep.join([str(path_dir), "/usr/bin", "/bin"])+ env["VIBE_TEST_UV_FAIL"] = "1"++ install_result = _install(env)++ assert install_result.returncode != 0+ assert active.read_text(encoding="utf-8") == "#!/usr/bin/env bash\necho stable\n"+++def test_install_script_keeps_active_launcher_when_candidate_probe_fails(tmp_path):+ home_dir = tmp_path / "home"+ home_dir.mkdir()+ path_dir = tmp_path / "path-bin"+ path_dir.mkdir()+ uv_log = tmp_path / "uv-tool-bin-dir.txt"+ active = path_dir / "vibe"+ _write_executable(active, "#!/usr/bin/env bash\necho stable\n")+ _write_fake_uv(path_dir / "uv", uv_log)++ env = os.environ.copy()+ env["HOME"] = str(home_dir)+ env["PATH"] = os.pathsep.join([str(path_dir), "/usr/bin", "/bin"])+ env["VIBE_TEST_CANDIDATE_PROBE_FAIL"] = "1"++ install_result = _install(env)++ assert install_result.returncode != 0+ assert active.read_text(encoding="utf-8") == "#!/usr/bin/env bash\necho stable\n"++def test_install_script_pairs_and_starts_with_verified_vibe_path(tmp_path):home_dir = tmp_path / "home"home_dir.mkdir()@@ -417,6 +668,82 @@ def test_install_script_probes_the_same_libreoffice_path_as_memory(tmp_path):assert "Install LibreOffice from https://www.libreoffice.org/" not in powershell+def test_windows_installer_honors_configured_tool_bin_and_cross_volume_copy_fallback():+ powershell = INSTALL_POWERSHELL.read_text(encoding="utf-8")++ assert "function Get-StableBinDirectory" in powershell+ assert "function Resolve-InstallPath" in powershell+ assert "function Get-LauncherState" in powershell+ assert "Get-Content -LiteralPath $marker" not in powershell+ assert "function Get-GenerationPath" not in powershell+ assert '$expanded.StartsWith("~\\")' in powershell+ assert "$configured = $env:UV_TOOL_BIN_DIR" in powershell+ assert '"__activate-install"' in powershell+ assert '"--protocol-version"' in powershell+ assert '"--snapshot", "--launcher", $Launcher' in powershell+ assert '$activationArguments += @("--source-generation", $previousSourcePath)' in powershell+ assert "function Remove-StaleInstallGenerations" not in powershell+ assert "function Activate-LegacyInstallCandidate" in powershell+ assert "[System.IO.File]::Move($replacement, $StableLauncher)" in powershell+ assert "Start-Process -FilePath" not in powershell+ assert "& $FilePath @Arguments" in powershell+ assert "Stdout = $stdout.Trim()" in powershell+ assert "Stderr = $stderr.Trim()" in powershell+ assert "function Get-InstallProtocolVersion" in powershell+ assert "[int]::TryParse($Result.Stdout.Trim(), [ref]$version)" in powershell+ assert "[int]$protocol.Output.Trim()" not in powershell+ assert "$snapshot.Stdout.Trim()" in powershell+ assert '$env:Path = "$stableBin;$persistedPath"' in powershell+ assert "& $stableLauncher --help" in powershell+ assert 'Invoke-NativeCommand -FilePath $stableLauncher -Arguments @("runtime", "prepare", "--strict")' in powershell+++def test_install_script_candidate_probes_ignore_python_path_overrides():+ script = INSTALL_SCRIPT.read_text(encoding="utf-8")+ assert 'env -u PYTHONPATH -u PYTHONHOME AVIBE_HOME="$AVIBE_RUNTIME_HOME"' in script+ assert "__activate-install --protocol-version" in script+ assert '__activate-install --snapshot --launcher "$stable_bin_dir/vibe"' in script+ assert 'activation_args+=(--source-generation "$source_snapshot")' in script+ assert "generation_path_for" not in script+ assert 'AVIBE_HOME="$AVIBE_RUNTIME_HOME" "$activation_owner"' in script+ assert "verify_uv_candidate" not in script+ powershell = INSTALL_POWERSHELL.read_text(encoding="utf-8")+ assert "$previousPythonPath = $env:PYTHONPATH" in powershell+ assert "Remove-Item Env:PYTHONHOME" in powershell+ assert "$env:AVIBE_HOME = $runtimeHome" in powershell+ assert "Test-UvCandidate" not in powershell+++def test_uninstall_instructions_use_the_selected_stable_bin():+ script = INSTALL_SCRIPT.read_text(encoding="utf-8")+ assert r'rm -f \"$VIBE_TOOL_BIN_DIR/vibe\"' in script+ assert "rm -f ~/.local/bin/vibe" not in script+++def test_uninstall_instructions_expand_user_relative_avibe_home():+ script = INSTALL_SCRIPT.read_text(encoding="utf-8")+ assert 'avibe_home=\\"\\${AVIBE_HOME:-\\$HOME/.avibe}\\"' in script+ assert 'avibe_home="${avibe_home/#\\~/$HOME}"' in script+ assert 'rm -rf "$avibe_home/runtime/install-generations"' in script+ assert 'rm -rf "$avibe_home" ~/.vibe_remote' in script++ documents = (+ (REPO_ROOT / "README.md").read_text(encoding="utf-8"),+ (REPO_ROOT / "docs" / "INSTALL_FOR_AI.md").read_text(encoding="utf-8"),+ (REPO_ROOT / "docs" / "INSTALL_FOR_AI_ZH.md").read_text(encoding="utf-8"),+ )++ for document in documents:+ assert 'avibe_home="${AVIBE_HOME:-$HOME/.avibe}"' in document+ assert 'avibe_home="${avibe_home/#\\~/$HOME}"' in document+ assert 'rm -rf "$avibe_home/runtime/install-generations"' in document+ assert 'rm -rf "$avibe_home" ~/.vibe_remote' in document++ powershell = INSTALL_POWERSHELL.read_text(encoding="utf-8")+ assert "-replace ''^~(?=[\\\\/]|$)'', $env:USERPROFILE" in powershell+ assert "Remove-Item -Recurse $avibeHome, ~\\.vibe_remote" in powershell++def test_install_script_continues_when_show_runtime_prepare_fails(tmp_path):home_dir = tmp_path / "home"home_dir.mkdir()@@ -489,7 +816,7 @@ def test_install_script_prefers_original_path_order(tmp_path):install_result = _install(env, cwd=tmp_path)assert install_result.returncode == 0, install_result.stdout + install_result.stderr- assert uv_log.read_text(encoding="utf-8") == str(first_dir)+ _assert_staged_uv_bin(uv_log, home_dir)def test_install_script_skips_relative_path_entries_for_tool_bin(tmp_path):@@ -534,7 +861,7 @@ def test_install_script_skips_virtualenv_bin_dirs(tmp_path):install_result = _install(env, cwd=tmp_path)assert install_result.returncode == 0, install_result.stdout + install_result.stderr- assert uv_log.read_text(encoding="utf-8") == str(stable_bin)+ _assert_staged_uv_bin(uv_log, home_dir)assert not (venv_bin / "vibe").exists()@@ -560,7 +887,7 @@ def test_install_script_skips_pyenv_and_mise_bin_dirs(tmp_path):install_result = _install(env, cwd=tmp_path)assert install_result.returncode == 0, install_result.stdout + install_result.stderr- assert uv_log.read_text(encoding="utf-8") == str(stable_bin)+ _assert_staged_uv_bin(uv_log, home_dir)assert not (pyenv_bin / "vibe").exists()assert not (mise_bin / "vibe").exists()@@ -585,7 +912,7 @@ def test_install_script_skips_pyenv_shims_dir(tmp_path):install_result = _install(env, cwd=tmp_path)assert install_result.returncode == 0, install_result.stdout + install_result.stderr- assert uv_log.read_text(encoding="utf-8") == str(stable_bin)+ _assert_staged_uv_bin(uv_log, home_dir)assert not (shims_dir / "vibe").exists()@@ -607,7 +934,7 @@ def test_install_script_prefers_bin_over_sbin(tmp_path):install_result = _install(env, cwd=tmp_path)assert install_result.returncode == 0, install_result.stdout + install_result.stderr- assert uv_log.read_text(encoding="utf-8") == str(bin_dir)+ _assert_staged_uv_bin(uv_log, home_dir)assert not (sbin_dir / "vibe").exists()@@ -676,7 +1003,7 @@ def test_install_script_reinstalls_when_existing_uv_is_x86_on_apple_silicon(tmp_assert install_result.returncode == 0, install_result.stdout + install_result.stderrassert "Found x86_64 uv on Apple Silicon" in install_result.stdout- assert uv_log.read_text(encoding="utf-8") == str(path_dir)+ _assert_staged_uv_bin(uv_log, home_dir)def test_install_script_omits_retry_all_errors_for_older_curl(tmp_path):@@ -751,7 +1078,7 @@ def test_install_script_accepts_universal_uv_with_arm64e_slice_on_apple_silicon(assert install_result.returncode == 0, install_result.stdout + install_result.stderrassert "Found x86_64 uv on Apple Silicon" not in install_result.stdoutassert "uv is already installed" in install_result.stdout- assert uv_log.read_text(encoding="utf-8") == str(path_dir)+ _assert_staged_uv_bin(uv_log, home_dir)def test_install_script_checks_uv_symlink_target_architecture_on_apple_silicon(tmp_path):@@ -800,7 +1127,7 @@ def test_install_script_checks_uv_symlink_target_architecture_on_apple_silicon(tassert install_result.returncode == 0, install_result.stdout + install_result.stderrassert "Found x86_64 uv on Apple Silicon" in install_result.stdout- assert uv_log.read_text(encoding="utf-8") == str(path_dir)+ _assert_staged_uv_bin(uv_log, home_dir)def test_install_script_ignores_arch_tokens_in_uv_path_prefix(tmp_path):@@ -848,4 +1175,4 @@ def test_install_script_ignores_arch_tokens_in_uv_path_prefix(tmp_path):assert install_result.returncode == 0, install_result.stdout + install_result.stderrassert "Found x86_64 uv on Apple Silicon" in install_result.stdout- assert uv_log.read_text(encoding="utf-8") == str(path_dir)+ _assert_staged_uv_bin(uv_log, home_dir)diff --git a/tests/test_restart_supervisor.py b/tests/test_restart_supervisor.pyindex a373efea4..54646b241 100644--- a/tests/test_restart_supervisor.py+++ b/tests/test_restart_supervisor.py@@ -116,13 +116,23 @@ def test_schedule_restart_spawns_supervisor_and_records_status(monkeypatch, tmp_paths.ensure_data_dirs()paths.get_runtime_pid_path().write_text("12345", encoding="utf-8")calls = {}+ events: list[str] = []++ class Lock:+ def __enter__(self):+ events.append("lock-enter")++ def __exit__(self, *_args):+ events.append("lock-exit")monkeypatch.setattr(restart_supervisor, "get_restart_invocation_command", lambda vibe_path=None: ["/bin/vibe", "restart"])monkeypatch.setattr(restart_supervisor, "get_restart_environment", lambda vibe_path=None: {"PATH": "/bin"})monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))monkeypatch.setattr(restart_supervisor, "_prune_restart_logs", lambda: None)+ monkeypatch.setattr(restart_supervisor, "atomic_upgrade_lock", Lock)def fake_popen(command, **kwargs):+ events.append("spawn")calls["command"] = commandcalls["kwargs"] = kwargs@@ -144,6 +154,72 @@ def test_schedule_restart_spawns_supervisor_and_records_status(monkeypatch, tmp_assert calls["kwargs"]["start_new_session"] is Trueassert calls["kwargs"]["env"] == {"PATH": "/bin"}assert runtime.read_json(runtime.get_restart_status_path())["job_id"] == result["job_id"]+ assert events == ["lock-enter", "spawn", "lock-exit"]+++def test_schedule_restart_can_use_candidate_python_without_launcher_lock(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ paths.ensure_data_dirs()+ calls = {}++ monkeypatch.setattr(restart_supervisor, "get_restart_environment", lambda vibe_path=None: {"PATH": "/bin"})+ monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))+ monkeypatch.setattr(restart_supervisor, "_prune_restart_logs", lambda: None)++ def fake_popen(command, **kwargs):+ calls["command"] = command+ calls["kwargs"] = kwargs++ class Proc:+ pid = 45679++ return Proc()++ monkeypatch.setattr(restart_supervisor.subprocess, "Popen", fake_popen)++ result = restart_supervisor.schedule_restart(+ vibe_path=str(tmp_path / "stable" / "vibe.exe"),+ python_executable=str(tmp_path / "generation" / "python.exe"),+ trigger="upgrade",+ )++ assert result["state"] == "scheduled"+ assert calls["command"][:4] == [+ str(tmp_path / "generation" / "python.exe"),+ "-c",+ "from vibe.cli import main; main()",+ "__restart-supervisor",+ ]+++def test_candidate_supervisor_drops_source_pythonpath(monkeypatch, tmp_path):+ monkeypatch.setenv("PYTHONPATH", "/source/checkout")+ monkeypatch.setenv("PYTHONHOME", "/source/python")+ monkeypatch.setattr(restart_supervisor, "get_restart_environment", lambda vibe_path=None: None)+ monkeypatch.setattr(restart_supervisor, "get_safe_cwd", lambda: str(tmp_path))+ monkeypatch.setattr(restart_supervisor, "_prune_restart_logs", lambda: None)+ calls = {}++ def fake_popen(command, **kwargs):+ calls["kwargs"] = kwargs++ class Proc:+ pid = 45680++ return Proc()++ monkeypatch.setattr(restart_supervisor.subprocess, "Popen", fake_popen)+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ paths.ensure_data_dirs()++ restart_supervisor.schedule_restart(+ vibe_path=str(tmp_path / "stable" / "vibe.exe"),+ python_executable=str(tmp_path / "generation" / "python.exe"),+ trigger="upgrade",+ )++ assert "PYTHONPATH" not in calls["kwargs"]["env"]+ assert "PYTHONHOME" not in calls["kwargs"]["env"]def test_legacy_upgrade_target_reads_the_running_release_and_launcher(monkeypatch, tmp_path):diff --git a/tests/test_upgrade_flow.py b/tests/test_upgrade_flow.pyindex 27f975f4f..9bcba74f5 100644--- a/tests/test_upgrade_flow.py+++ b/tests/test_upgrade_flow.py@@ -1,9 +1,12 @@from __future__ import annotationsimport ast+from contextlib import nullcontextimport os+import statimport subprocessimport sys+from types import SimpleNamespacefrom pathlib import Pathfrom typing import Any@@ -11,9 +14,10 @@ import pytestsys.path.insert(0, str(Path(__file__).resolve().parents[1]))-from vibe import api, cli+from vibe import api, cli, runtimefrom vibe.runtime import ServiceLauncherfrom vibe.upgrade import (+ AtomicActivation,UpgradePlan,build_upgrade_plan,has_newer_version,@@ -23,12 +27,14 @@ from vibe.upgrade import (get_restart_environment,get_restart_invocation_command,get_restart_shell_command,+ defer_upgrade_activation,get_running_vibe_path,get_safe_cwd,installed_package_name,pinned_package_spec,RollbackTarget,rollback_target,+ restart_is_pending,)@@ -54,7 +60,7 @@ def _tree_is_not_an_installed_distribution(monkeypatch):monkeypatch.setattr("vibe.upgrade._distributions_providing_this_package", lambda: [])-def test_build_upgrade_plan_uses_uv_and_preserves_tool_bin_dir(monkeypatch):+def test_build_upgrade_plan_stages_custom_legacy_uv_launcher(monkeypatch):monkeypatch.setattr("vibe.upgrade.os.path.exists", lambda path: True)monkeypatch.setattr("vibe.upgrade.os.access", lambda path, mode: True)@@ -68,8 +74,12 @@ def test_build_upgrade_plan_uses_uv_and_preserves_tool_bin_dir(monkeypatch):assert plan.method == "uv"assert plan.command == ["/usr/local/bin/uv", "tool", "install", "avibe-os", "--upgrade"]assert plan.env is not None- assert plan.env["UV_TOOL_BIN_DIR"] == "/custom/bin"+ assert "UV_TOOL_DIR" in plan.env+ assert "UV_TOOL_BIN_DIR" in plan.envassert plan.env["PATH"] == "/usr/bin"+ assert plan.preflight_error is None+ assert plan.activation is not None+ assert plan.activation.launcher == Path("/custom/bin/vibe")def test_build_upgrade_plan_forces_legacy_uv_tool_install(monkeypatch):@@ -100,6 +110,772 @@ def test_build_upgrade_plan_uses_pip_for_non_uv_install():assert plan.env == {"PATH": "/usr/bin"}+def test_build_upgrade_plan_stages_uv_install_for_a_stable_launcher(monkeypatch, tmp_path):+ 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)+ monkeypatch.setattr("vibe.upgrade.config_paths.get_vibe_remote_dir", lambda: tmp_path / "home")+ monkeypatch.setattr("vibe.upgrade.os.path.exists", lambda path: True)+ monkeypatch.setattr("vibe.upgrade.os.access", lambda path, mode: True)++ plan = build_upgrade_plan(+ python_executable="/tmp/.local/share/uv/tools/avibe-os/bin/python",+ uv_path="/usr/local/bin/uv",+ vibe_path=str(launcher),+ base_env={"PATH": "/usr/bin"},+ )++ assert plan.activation is not None+ assert plan.activation.launcher == launcher+ assert plan.env is not None+ assert plan.env["UV_TOOL_DIR"].startswith(str(tmp_path / "home" / "runtime" / "install-generations"))+ assert plan.env["UV_TOOL_BIN_DIR"].startswith(str(tmp_path / "home" / "runtime" / "install-generations"))+++def test_build_upgrade_plan_refuses_uv_install_without_activation_point(monkeypatch):+ monkeypatch.setattr("vibe.upgrade.os.path.exists", lambda path: True)+ monkeypatch.setattr("vibe.upgrade.os.access", lambda path, mode: True)++ plan = build_upgrade_plan(+ python_executable="/tmp/.local/share/uv/tools/avibe-os/bin/python",+ uv_path="/usr/local/bin/uv",+ vibe_path="/tmp/.local/share/uv/tools/avibe-os/bin/vibe",+ base_env={"PATH": "/usr/bin"},+ )++ assert plan.activation is None+ assert plan.preflight_error is not None+++def test_activate_upgrade_candidate_replaces_launcher_only_after_verification(monkeypatch, tmp_path):+ from vibe import upgrade++ launcher = tmp_path / "bin" / "vibe"+ old = tmp_path / "old" / "vibe"+ candidate = tmp_path / "generation" / "bin" / "vibe"+ old.parent.mkdir(parents=True)+ candidate.parent.mkdir(parents=True)+ old.write_text("old\n", encoding="utf-8")+ candidate.write_text("new\n", encoding="utf-8")+ candidate.chmod(0o755)+ launcher.parent.mkdir(parents=True)+ launcher.symlink_to(old)+ activation = upgrade.AtomicActivation(launcher=launcher, candidate_launcher=candidate)+ monkeypatch.setattr(upgrade, "verify_upgrade_candidate", lambda _activation: upgrade.IntegrityResult(True, 1))++ upgrade.activate_upgrade_candidate(activation)++ assert launcher.is_symlink()+ assert launcher.resolve() == candidate.resolve()+ assert old.read_text(encoding="utf-8") == "old\n"+++def test_activate_upgrade_candidate_replaces_windows_hardlink_launcher(monkeypatch, tmp_path):+ from vibe import upgrade++ launcher = tmp_path / ".local" / "bin" / "vibe.exe"+ old_generation = tmp_path / "home" / "runtime" / "install-generations" / "old"+ candidate = tmp_path / "home" / "runtime" / "install-generations" / "new" / "bin" / "vibe.exe"+ launcher.parent.mkdir(parents=True)+ old_launcher = old_generation / "bin" / "vibe.exe"+ old_launcher.parent.mkdir(parents=True)+ candidate.parent.mkdir(parents=True)+ old_launcher.write_text("old\n", encoding="utf-8")+ os.link(old_launcher, launcher)+ os.utime(old_generation, (0, 0))+ candidate.write_text("new\n", encoding="utf-8")+ candidate.chmod(0o755)+ activation = upgrade.AtomicActivation(launcher=launcher, candidate_launcher=candidate)+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: tmp_path / "home" / "runtime" / "install-generations")+ monkeypatch.setattr(upgrade, "verify_upgrade_candidate", lambda _activation: upgrade.IntegrityResult(True, 1))++ upgrade.activate_upgrade_candidate(activation)++ assert launcher.is_symlink()+ assert launcher.resolve() == candidate.resolve()+++def test_activation_leaves_every_other_generation_untouched(monkeypatch, tmp_path):+ from vibe import upgrade++ root = tmp_path / "generations"+ launcher = tmp_path / "bin" / "vibe"+ previous = root / "previous" / "bin" / "vibe"+ candidate = root / "candidate" / "bin" / "vibe"+ unrelated = root / "unrelated" / "bin" / "vibe"+ for path in (previous, candidate, unrelated):+ path.parent.mkdir(parents=True)+ path.write_text(path.parent.parent.name, encoding="utf-8")+ path.chmod(0o755)+ launcher.parent.mkdir(parents=True)+ launcher.symlink_to(previous)+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: root)+ monkeypatch.setattr(upgrade, "verify_upgrade_candidate", lambda _activation: upgrade.IntegrityResult(True, 1))++ upgrade.activate_upgrade_candidate(upgrade.AtomicActivation(launcher, candidate, root / "previous"))++ assert launcher.resolve() == candidate.resolve()+ assert previous.exists()+ assert unrelated.exists()+++def test_activation_compares_source_generation_by_filesystem_identity(monkeypatch, tmp_path):+ from vibe import upgrade++ physical_home = tmp_path / "physical-home"+ logical_home = tmp_path / "logical-home"+ logical_home.symlink_to(physical_home, target_is_directory=True)+ root = physical_home / "runtime" / "install-generations"+ source = root / "source" / "bin" / "vibe"+ launcher = tmp_path / "bin" / "vibe"+ source.parent.mkdir(parents=True)+ launcher.parent.mkdir()+ source.write_text("source", encoding="utf-8")+ launcher.symlink_to(source)+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: root)++ activation = upgrade.AtomicActivation(+ launcher,+ root / "candidate" / "bin" / "vibe",+ logical_home / "runtime" / "install-generations" / "source" / "bin" / "vibe",+ )++ assert upgrade.atomic_activation_source_is_current(activation)+++def test_activation_compares_a_conventional_launcher_snapshot(monkeypatch, tmp_path):+ from vibe import upgrade++ root = tmp_path / "runtime" / "install-generations"+ old = tmp_path / "legacy" / "old-vibe"+ new = tmp_path / "legacy" / "new-vibe"+ launcher = tmp_path / "bin" / "vibe"+ for path in (old, new):+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(path.name, encoding="utf-8")+ path.chmod(0o755)+ launcher.parent.mkdir()+ launcher.symlink_to(old)+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: root)+ activation = upgrade.AtomicActivation(launcher, root / "candidate" / "bin" / "vibe", old)++ assert upgrade.atomic_activation_source_is_current(activation)+ launcher.unlink()+ launcher.symlink_to(new)+ assert not upgrade.atomic_activation_source_is_current(activation)+++def test_installer_activation_uses_the_shared_locked_boundary(monkeypatch, tmp_path):+ from vibe import upgrade++ events: list[str] = []++ class Lock:+ def __enter__(self):+ events.append("lock-enter")++ def __exit__(self, *_args):+ events.append("lock-exit")++ activation = upgrade.AtomicActivation(tmp_path / "vibe", tmp_path / "candidate")+ monkeypatch.setattr(upgrade, "atomic_upgrade_lock", Lock)+ monkeypatch.setattr(upgrade, "activation_block_reason", lambda _activation: None)+ monkeypatch.setattr(upgrade, "activate_upgrade_candidate", lambda _activation: events.append("activate"))++ upgrade.activate_installer_candidate(activation)++ assert events == ["lock-enter", "activate", "lock-exit"]+++def test_installer_activation_reports_its_protocol_version(capsys):+ from vibe import cli++ assert cli._dispatch_installer_activation(["--protocol-version"]) == 0+ assert capsys.readouterr().out == "2\n"+++def test_installer_activation_snapshot_comes_from_shared_launcher_identity(monkeypatch, tmp_path, capsys):+ from vibe import cli, upgrade++ root = tmp_path / "generations"+ generation = root / "active"+ target = generation / "bin" / "vibe"+ launcher = tmp_path / "bin" / "vibe"+ target.parent.mkdir(parents=True)+ launcher.parent.mkdir(parents=True)+ target.write_text("active\n", encoding="utf-8")+ launcher.symlink_to(target)+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: root)+ monkeypatch.setattr(cli, "atomic_uv_install_root", lambda: root)++ assert cli._dispatch_installer_activation(["--snapshot", "--launcher", str(launcher)]) == 0+ assert capsys.readouterr().out == f"{generation.resolve()}\n"+++def test_installer_rejects_a_snapshot_superseded_by_runtime_activation(monkeypatch, tmp_path):+ from vibe import upgrade++ root = tmp_path / "generations"+ launcher = tmp_path / "bin" / "vibe"+ old = root / "old" / "bin" / "vibe"+ runtime_candidate = root / "runtime" / "bin" / "vibe"+ installer_candidate = root / "installer" / "bin" / "vibe"+ for path in (old, runtime_candidate, installer_candidate):+ path.parent.mkdir(parents=True)+ path.write_text(path.parent.parent.name, encoding="utf-8")+ path.chmod(0o755)+ launcher.parent.mkdir(parents=True)+ launcher.symlink_to(old)+ installer_activation = upgrade.AtomicActivation(launcher, installer_candidate, root / "old")+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: root)+ monkeypatch.setattr(upgrade, "restart_is_pending", lambda: False)+ monkeypatch.setattr(upgrade, "verify_upgrade_candidate", lambda _activation: upgrade.IntegrityResult(True, 1))++ upgrade.activate_upgrade_candidate(upgrade.AtomicActivation(launcher, runtime_candidate, root / "old"))++ with pytest.raises(RuntimeError, match="changed while the installer was staging"):+ upgrade.activate_installer_candidate(installer_activation)+ assert launcher.resolve() == runtime_candidate.resolve()+++def test_verify_upgrade_candidate_follows_uv_launcher_to_tool_environment(monkeypatch, tmp_path):+ from vibe import upgrade++ launcher = tmp_path / "bin" / "vibe"+ tool_bin = tmp_path / "tools" / "avibe-os" / "bin"+ tool_bin.mkdir(parents=True)+ launcher.parent.mkdir(parents=True)+ launcher.symlink_to(tool_bin / "vibe")+ (tool_bin / "vibe").write_text("#!/bin/sh\n", encoding="utf-8")+ (tool_bin / "python3").write_text("#!/bin/sh\n", encoding="utf-8")+ (tool_bin / "vibe").chmod(0o755)+ (tool_bin / "python3").chmod(0o755)+ activation = upgrade.AtomicActivation(launcher=launcher, candidate_launcher=launcher)+ monkeypatch.setattr(upgrade, "verify_python_environment", lambda python: upgrade.IntegrityResult(True, 2))++ result = upgrade.verify_upgrade_candidate(activation)++ assert result.ok is True+ assert result.checked_files == 2+++def test_verify_upgrade_candidate_searches_staged_tools_for_windows_python(monkeypatch, tmp_path):+ from vibe import upgrade++ root = tmp_path / "generations"+ candidate = root / "generation" / "bin" / "vibe.exe"+ python = root / "generation" / "tools" / "avibe-os" / "Scripts" / "python.exe"+ candidate.parent.mkdir(parents=True)+ python.parent.mkdir(parents=True)+ candidate.write_text("#!/bin/sh\nexit 0\n", encoding="utf-8")+ python.write_text("python\n", encoding="utf-8")+ candidate.chmod(0o755)+ python.chmod(0o755)+ monkeypatch.setattr(upgrade.os, "name", "nt")+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: root)+ observed = {}++ def verify(path):+ observed["path"] = path+ return upgrade.IntegrityResult(True, 3)++ monkeypatch.setattr(upgrade, "verify_python_environment", verify)++ result = upgrade.verify_upgrade_candidate(upgrade.AtomicActivation(candidate, candidate))++ assert result.ok is True+ assert observed["path"] == python+++def test_verify_upgrade_candidate_rejects_launcher_that_fails_startup_probe(monkeypatch, tmp_path):+ from vibe import upgrade++ candidate = tmp_path / "bin" / "vibe"+ candidate.parent.mkdir(parents=True)+ candidate.write_text("#!/bin/sh\nexit 9\n", encoding="utf-8")+ candidate.chmod(0o755)+ python = candidate.parent / "python3"+ python.write_text("#!/bin/sh\n", encoding="utf-8")+ python.chmod(0o755)+ monkeypatch.setattr(upgrade, "verify_python_environment", lambda _python: upgrade.IntegrityResult(True, 3))++ result = upgrade.verify_upgrade_candidate(upgrade.AtomicActivation(candidate, candidate))++ assert result.ok is False+ assert "launcher probe failed" in result.failures[0]+++def test_atomic_activation_source_must_still_be_active_under_lock(monkeypatch, tmp_path):+ from vibe import upgrade++ root = tmp_path / "home" / "runtime" / "install-generations"+ old = root / "old" / "bin" / "vibe"+ new = root / "new" / "bin" / "vibe"+ launcher = tmp_path / ".local" / "bin" / "vibe"+ for path in (old, new):+ path.parent.mkdir(parents=True)+ path.write_text(path.parent.parent.name, encoding="utf-8")+ path.chmod(0o755)+ launcher.parent.mkdir(parents=True)+ launcher.symlink_to(old)+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: root)+ activation = upgrade.AtomicActivation(launcher, root / "candidate" / "bin" / "vibe", root / "old")++ assert upgrade.atomic_activation_source_is_current(activation)+ launcher.unlink()+ launcher.symlink_to(new)+ assert not upgrade.atomic_activation_source_is_current(activation)+++def test_launcher_generation_recognizes_windows_hardlink(monkeypatch, tmp_path):+ from vibe import upgrade++ root = tmp_path / "home" / "runtime" / "install-generations"+ generation = root / "old"+ source = generation / "bin" / "vibe.exe"+ launcher = tmp_path / ".local" / "bin" / "vibe.exe"+ source.parent.mkdir(parents=True)+ launcher.parent.mkdir(parents=True)+ source.write_text("old\n", encoding="utf-8")+ os.link(source, launcher)+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: root)++ assert upgrade._launcher_generation(launcher, root) == generation+++def test_launcher_generation_does_not_match_hardlink_inode_on_another_device(monkeypatch, tmp_path):+ from vibe import upgrade++ root = tmp_path / "home" / "runtime" / "install-generations"+ generation = root / "old"+ source = generation / "bin" / "vibe.exe"+ launcher = tmp_path / ".local" / "bin" / "vibe.exe"+ source.parent.mkdir(parents=True)+ launcher.parent.mkdir(parents=True)+ source.write_text("old\n", encoding="utf-8")+ launcher.write_text("old\n", encoding="utf-8")+ original_stat = Path.stat++ def fake_stat(path, *args, **kwargs):+ if path == launcher:+ return SimpleNamespace(st_dev=1, st_ino=7, st_mode=stat.S_IFREG)+ if path == source:+ return SimpleNamespace(st_dev=2, st_ino=7, st_mode=stat.S_IFREG)+ return original_stat(path, *args, **kwargs)++ monkeypatch.setattr(Path, "stat", fake_stat)+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: root)++ assert upgrade._generation_for_hardlink(launcher, root) is None+++def test_hardlink_generation_lookup_degrades_when_root_cannot_be_enumerated(monkeypatch, tmp_path):+ from vibe import upgrade++ root = tmp_path / "home" / "runtime" / "install-generations"+ launcher = tmp_path / ".local" / "bin" / "vibe.exe"+ root.mkdir(parents=True)+ launcher.parent.mkdir(parents=True)+ launcher.write_text("launcher\n", encoding="utf-8")+ original_iterdir = Path.iterdir++ def denied(path):+ if path == root.resolve():+ raise PermissionError("denied")+ return original_iterdir(path)++ monkeypatch.setattr(Path, "iterdir", denied)+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: root)++ assert upgrade._generation_for_hardlink(launcher, root) is None+++def test_copy_marker_must_match_the_live_launcher(monkeypatch, tmp_path):+ from vibe import upgrade++ root = tmp_path / "home" / "runtime" / "install-generations"+ old = root / "old"+ current = root / "current"+ launcher = tmp_path / ".local" / "bin" / "vibe.exe"+ marker = launcher.parent / ".vibe.exe.avibe-generation"+ for generation, content in ((old, "old\n"), (current, "current\n")):+ candidate = generation / "bin" / "vibe.exe"+ candidate.parent.mkdir(parents=True)+ candidate.write_text(content, encoding="utf-8")+ launcher.parent.mkdir(parents=True)+ launcher.write_text("current\n", encoding="utf-8")+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: root)++ marker.write_text(str(old), encoding="utf-8")+ assert upgrade._launcher_generation(launcher, root) is None++ marker.write_text(str(current), encoding="utf-8")+ assert upgrade._launcher_generation(launcher, root) == current.resolve()+++def test_launcher_is_current_process_only_matches_windows_launcher(monkeypatch, tmp_path):+ from vibe import upgrade++ launcher = tmp_path / "bin" / "vibe.exe"+ launcher.parent.mkdir()+ launcher.write_text("launcher\n", encoding="utf-8")+ monkeypatch.setattr(upgrade.os, "name", "nt")+ monkeypatch.setattr(upgrade.sys, "argv", [str(launcher)])++ assert upgrade.launcher_is_current_process(launcher)+ assert not upgrade.launcher_is_current_process(tmp_path / "bin" / "other.exe")+++def test_launcher_is_current_process_ignores_inherited_launcher_hint(monkeypatch, tmp_path):+ from vibe import upgrade++ launcher = tmp_path / "bin" / "vibe.exe"+ launcher.parent.mkdir()+ launcher.write_text("launcher\n", encoding="utf-8")+ monkeypatch.setattr(upgrade.os, "name", "nt")+ monkeypatch.setattr(upgrade.sys, "argv", [str(tmp_path / "service_main.py")])+ monkeypatch.setenv("VIBE_CURRENT_EXECUTABLE", str(launcher))++ assert not upgrade.launcher_is_current_process(launcher)+++def test_deferred_activation_dispatch_activates_then_schedules_restart(monkeypatch, tmp_path):+ from vibe import cli++ launcher = tmp_path / "bin" / "vibe.exe"+ candidate = tmp_path / "generation" / "bin" / "vibe.exe"+ calls: list[str] = []+ monkeypatch.setattr(cli.runtime, "pid_alive", lambda _pid: False)+ monkeypatch.setattr(cli, "atomic_upgrade_lock", lambda: nullcontext())+ monkeypatch.setattr(cli, "activation_block_reason", lambda _activation: None)+ monkeypatch.setattr(cli, "activate_upgrade_candidate", lambda _activation: calls.append("activate"))+ monkeypatch.setattr(cli, "schedule_restart", lambda **_kwargs: calls.append("restart"))++ result = cli._dispatch_deferred_upgrade_activation(+ [+ "--parent-pid",+ "123",+ "--launcher",+ str(launcher),+ "--candidate",+ str(candidate),+ "--restart",+ ]+ )++ assert result == 0+ assert calls == ["activate", "restart"]+++def test_deferred_activation_seeds_restart_before_releasing_install_lock(monkeypatch, tmp_path):+ from vibe import cli++ events: list[str] = []++ class Lock:+ def __enter__(self):+ events.append("lock-enter")++ def __exit__(self, *_args):+ events.append("lock-exit")++ monkeypatch.setattr(cli.runtime, "pid_alive", lambda _pid: False)+ monkeypatch.setattr(cli, "atomic_upgrade_lock", Lock)+ monkeypatch.setattr(cli, "activation_block_reason", lambda _activation: None)+ monkeypatch.setattr(cli, "activate_upgrade_candidate", lambda _activation: events.append("activate"))+ monkeypatch.setattr(cli, "schedule_restart", lambda **_kwargs: events.append("restart"))++ result = cli._dispatch_deferred_upgrade_activation(+ [+ "--parent-pid",+ "123",+ "--launcher",+ str(tmp_path / "vibe.exe"),+ "--candidate",+ str(tmp_path / "candidate.exe"),+ "--restart",+ ]+ )++ assert result == 0+ assert events == ["lock-enter", "activate", "restart", "lock-exit"]+++def test_deferred_offline_activation_prepares_show_runtime(monkeypatch, tmp_path):+ from vibe import cli++ calls: list[str] = []+ launcher = tmp_path / "vibe.exe"+ monkeypatch.setattr(cli.runtime, "pid_alive", lambda _pid: False)+ monkeypatch.setattr(cli, "atomic_upgrade_lock", lambda: nullcontext())+ monkeypatch.setattr(cli, "activation_block_reason", lambda _activation: None)+ monkeypatch.setattr(cli, "activate_upgrade_candidate", lambda _activation: calls.append("activate"))+ monkeypatch.setattr(cli, "_prepare_show_runtime_after_install", lambda path: calls.append(f"prepare:{path}"))++ result = cli._dispatch_deferred_upgrade_activation(+ [+ "--parent-pid",+ "123",+ "--launcher",+ str(launcher),+ "--candidate",+ str(tmp_path / "candidate.exe"),+ "--prepare-show-runtime",+ ]+ )++ assert result == 0+ assert calls == ["activate", f"prepare:{launcher}"]+++def test_deferred_upgrade_activation_uses_candidate_python(monkeypatch, tmp_path):+ from vibe import upgrade++ launcher = tmp_path / ".local" / "bin" / "vibe.exe"+ candidate = tmp_path / "generation" / "bin" / "vibe.exe"+ candidate_python = tmp_path / "generation" / "tools" / "avibe-os" / "Scripts" / "python.exe"+ candidate.parent.mkdir(parents=True)+ candidate_python.parent.mkdir(parents=True)+ candidate.write_text("candidate\n", encoding="utf-8")+ candidate_python.write_text("python\n", encoding="utf-8")+ activation = AtomicActivation(launcher, candidate, tmp_path / "generation")+ rollback = RollbackTarget("3.0.10", "vibe-remote", ServiceLauncher("old-python", "old-main"))+ calls = {}++ monkeypatch.setattr(upgrade, "_candidate_python", lambda _candidate: candidate_python)+ monkeypatch.setattr(upgrade.runtime_mod, "process_create_time", lambda _pid: 123.0)+ monkeypatch.setattr(upgrade, "get_safe_cwd", lambda: str(tmp_path))+ monkeypatch.setattr(upgrade, "isolated_probe_environment", lambda: {"PATH": "clean"})+ monkeypatch.setattr(upgrade.config_paths, "get_logs_dir", lambda: tmp_path / "logs")++ class Process:+ pid = 456++ def fake_popen(command, **kwargs):+ calls["command"] = command+ calls["kwargs"] = kwargs+ return Process()++ monkeypatch.setattr(upgrade.subprocess, "Popen", fake_popen)++ process = defer_upgrade_activation(+ activation,+ parent_pid=123,+ rollback_to=rollback,+ restart_required=True,+ prepare_show_runtime=True,+ )++ assert process.pid == 456+ assert calls["command"][:4] == [str(candidate_python), "-c", "from vibe.cli import main; main()", "__activate-upgrade"]+ assert "--parent-pid" in calls["command"]+ assert "--restart" in calls["command"]+ assert "--prepare-show-runtime" in calls["command"]+ assert calls["kwargs"]["env"] == {"PATH": "clean"}+++def test_deferred_activation_rejects_missing_source_when_launcher_changed(monkeypatch, tmp_path):+ from vibe import cli++ calls: list[str] = []+ monkeypatch.setattr(cli.runtime, "pid_alive", lambda _pid: False)+ monkeypatch.setattr(cli, "atomic_upgrade_lock", lambda: nullcontext())+ monkeypatch.setattr(cli, "activation_block_reason", lambda _activation: "superseded")+ monkeypatch.setattr(cli, "discard_atomic_uv_install_generation", lambda _path: calls.append("discard"))+ monkeypatch.setattr(cli, "activate_upgrade_candidate", lambda _activation: calls.append("activate"))++ result = cli._dispatch_deferred_upgrade_activation(+ ["--parent-pid", "123", "--launcher", str(tmp_path / "vibe.exe"), "--candidate", str(tmp_path / "candidate")]+ )++ assert result == 1+ assert calls == ["discard"]+++def test_cli_launcher_path_uses_hardlinked_generation(monkeypatch, tmp_path):+ from vibe import upgrade++ root = tmp_path / "home" / "runtime" / "install-generations"+ generation = root / "old"+ source = generation / "bin" / "vibe.exe"+ launcher = tmp_path / ".local" / "bin" / "vibe.exe"+ source.parent.mkdir(parents=True)+ launcher.parent.mkdir(parents=True)+ source.write_text("old\n", encoding="utf-8")+ source.chmod(0o755)+ os.link(source, launcher)+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: root)++ saved = ServiceLauncher(python=str(launcher), main="service_main.py")++ assert upgrade.get_cli_launcher_path(saved) == source+++def test_activate_upgrade_candidate_falls_back_to_hardlink(monkeypatch, tmp_path):+ from vibe import upgrade++ launcher = tmp_path / ".local" / "bin" / "vibe"+ candidate = tmp_path / "generation" / "bin" / "vibe"+ launcher.parent.mkdir(parents=True)+ candidate.parent.mkdir(parents=True)+ launcher.write_text("old\n", encoding="utf-8")+ candidate.write_text("new\n", encoding="utf-8")+ candidate.chmod(0o755)+ activation = upgrade.AtomicActivation(launcher=launcher, candidate_launcher=candidate)+ monkeypatch.setattr(upgrade, "verify_upgrade_candidate", lambda _activation: upgrade.IntegrityResult(True, 1))+ monkeypatch.setattr(Path, "symlink_to", lambda self, _target: (_ for _ in ()).throw(OSError("symlink denied")))++ upgrade.activate_upgrade_candidate(activation)++ assert not launcher.is_symlink()+ assert launcher.read_text(encoding="utf-8") == "new\n"+++def test_activate_upgrade_candidate_falls_back_to_copy_when_links_fail(monkeypatch, tmp_path):+ from vibe import upgrade++ launcher = tmp_path / ".local" / "bin" / "vibe"+ root = tmp_path / "home" / "runtime" / "install-generations"+ candidate = root / "generation" / "bin" / "vibe"+ launcher.parent.mkdir(parents=True)+ candidate.parent.mkdir(parents=True)+ launcher.write_text("old\n", encoding="utf-8")+ candidate.write_text("new\n", encoding="utf-8")+ candidate.chmod(0o755)+ activation = upgrade.AtomicActivation(launcher=launcher, candidate_launcher=candidate)+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: root)+ monkeypatch.setattr(upgrade, "verify_upgrade_candidate", lambda _activation: upgrade.IntegrityResult(True, 1))+ monkeypatch.setattr(Path, "symlink_to", lambda self, _target: (_ for _ in ()).throw(OSError("symlink denied")))+ monkeypatch.setattr(upgrade.os, "link", lambda _target, _replacement: (_ for _ in ()).throw(OSError("cross-device link")))++ upgrade.activate_upgrade_candidate(activation)++ assert not launcher.is_symlink()+ assert launcher.read_text(encoding="utf-8") == "new\n"+ assert upgrade._launcher_generation(launcher, root) == root / "generation"+++def test_is_uv_tool_install_uses_logical_atomic_generation_path(monkeypatch, tmp_path):+ from vibe import upgrade++ root = tmp_path / "home" / "runtime" / "install-generations"+ executable = root / "generation" / "tools" / "avibe-os" / "bin" / "python3"+ executable.parent.mkdir(parents=True)+ executable.write_text("#!/bin/sh\n", encoding="utf-8")+ executable.chmod(0o755)+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: root)++ assert upgrade.is_uv_tool_install(str(executable))+++def test_custom_legacy_bin_is_a_stable_launcher_without_uv_environment(monkeypatch, tmp_path):+ from vibe import upgrade++ launcher = tmp_path / "custom-tools" / "vibe.exe"+ launcher.parent.mkdir(parents=True)+ launcher.write_text("launcher\n", encoding="utf-8")+ launcher.chmod(0o755)+ monkeypatch.delenv("UV_TOOL_BIN_DIR", raising=False)++ assert upgrade._is_stable_launcher_path(launcher)+++def test_uv_environment_entry_point_is_not_a_stable_launcher(monkeypatch, tmp_path):+ from vibe import upgrade++ root = tmp_path / "home" / "runtime" / "install-generations"+ launcher = root / "generation" / "tools" / "avibe-os" / "bin" / "vibe.exe"+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: root)++ assert not upgrade._is_stable_launcher_path(launcher)+++def test_restart_is_pending_until_the_seed_marker_is_terminal(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ status = runtime.get_restart_status_path()+ status.parent.mkdir(parents=True)+ runtime.write_json(status, {"state": "scheduled", "supervisor_pid": None})++ assert restart_is_pending()++ runtime.write_json(status, {"state": "succeeded", "supervisor_pid": None})+ assert not restart_is_pending()+++def test_legacy_restart_record_expires_even_when_its_pid_was_reused(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ status = runtime.get_restart_status_path()+ status.parent.mkdir(parents=True)+ runtime.write_json(status, {"state": "scheduled", "supervisor_pid": 456})+ os.utime(status, (0, 0))+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 456)++ assert not restart_is_pending()+++def test_restart_state_with_a_non_object_shape_is_not_pending(monkeypatch, tmp_path):+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ status = runtime.get_restart_status_path()+ status.parent.mkdir(parents=True)+ status.write_text("[]", encoding="utf-8")++ assert not restart_is_pending()+++def test_doctor_resolves_hardlinked_atomic_generation(monkeypatch, tmp_path):+ from vibe import upgrade++ root = tmp_path / "home" / "runtime" / "install-generations"+ generation = root / "old"+ launcher_source = generation / "bin" / "vibe.exe"+ launcher = tmp_path / ".local" / "bin" / "vibe.exe"+ site_packages = generation / "tools" / "avibe-os" / "lib" / "python3.12" / "site-packages"+ launcher_source.parent.mkdir(parents=True)+ site_packages.mkdir(parents=True)+ launcher.parent.mkdir(parents=True)+ launcher_source.write_text("launcher\n", encoding="utf-8")+ os.link(launcher_source, launcher)+ monkeypatch.setattr(upgrade, "atomic_uv_install_root", lambda: root)+ monkeypatch.setattr(cli, "atomic_uv_install_root", lambda: root)++ assert site_packages in cli._uv_tool_site_packages_for_vibe(launcher)+++def test_do_upgrade_keeps_active_launcher_when_staged_install_fails(monkeypatch, tmp_path):+ launcher = tmp_path / "bin" / "vibe"+ old = tmp_path / "old" / "vibe"+ candidate = tmp_path / "generation" / "bin" / "vibe"+ old.parent.mkdir(parents=True)+ candidate.parent.mkdir(parents=True)+ old.write_text("old\n", encoding="utf-8")+ candidate.write_text("partial\n", encoding="utf-8")+ candidate.chmod(0o755)+ launcher.parent.mkdir(parents=True)+ launcher.symlink_to(old)+ plan = UpgradePlan(+ command=["uv", "tool", "install", "avibe-os", "--upgrade"],+ env={},+ method="uv",+ activation=AtomicActivation(launcher, candidate),+ )+ monkeypatch.setattr(api, "build_upgrade_plan", lambda **kwargs: plan)+ monkeypatch.setattr(api, "get_running_vibe_path", lambda: str(launcher))+ monkeypatch.setattr(api, "_runtime_process_was_running", lambda: False)+ monkeypatch.setattr(+ api.subprocess,+ "run",+ lambda *args, **kwargs: subprocess.CompletedProcess(plan.command, 1, stdout="", stderr="interrupted"),+ )++ result = api.do_upgrade(auto_restart=False)++ assert result["ok"] is False+ assert launcher.resolve() == old.resolve()++def test_build_upgrade_plan_uses_env_package_spec(monkeypatch):monkeypatch.setenv("VIBE_UPGRADE_PACKAGE_SPEC", "/tmp/vibe_remote-9999.0.0-py3-none-any.whl")monkeypatch.setattr("vibe.upgrade.os.path.exists", lambda path: True)@@ -877,7 +1653,7 @@ def test_do_upgrade_uses_upgrade_plan_env_and_restarts(monkeypatch):assert calls["run_cmd"] == plan.commandassert calls["run_kwargs"]["capture_output"] is Trueassert calls["run_kwargs"]["text"] is True- assert calls["run_kwargs"]["timeout"] == 120+ assert calls["run_kwargs"]["timeout"] == 1800assert calls["run_kwargs"]["env"] == plan.envsafe_cwd = calls["run_kwargs"].get("cwd")assert safe_cwd and os.path.isabs(safe_cwd), f"subprocess.run cwd must be an absolute path, got {safe_cwd!r}"diff --git a/vibe/api.py b/vibe/api.pyindex df70826db..9f7d540ef 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -12,6 +12,7 @@ import socketimport sslimport statimport subprocess+import sysimport threadingimport timeimport urllib.parse@@ -52,6 +53,7 @@ from config.v2_settings import (from config.v2_sessions import SessionsStorefrom config.platform_registry import get_platform_descriptorfrom core import latest_version_cache+from core.install_integrity import verify_python_environmentfrom core.memory.operation_lock import MemoryOperationBusy, MemoryOperationLeasefrom vibe.opencode_config import (get_opencode_config_paths,@@ -60,11 +62,22 @@ from vibe.opencode_config import ()from vibe.build_identity import get_build_identityfrom vibe.upgrade import (+ AtomicActivation,+ _candidate_python,+ activation_block_reason,+ activate_upgrade_candidate,+ atomic_upgrade_lock,build_upgrade_plan,+ defer_upgrade_activation,+ discard_atomic_uv_install_generation,get_latest_version_info,get_running_vibe_path,get_safe_cwd,+ launcher_is_current_process,+ restart_is_pending,should_skip_show_runtime_prepare,+ UPGRADE_INSTALL_TIMEOUT_SECONDS,+ verify_upgrade_candidate,)from vibe.restart_supervisor import schedule_restartfrom vibe import backend_model_catalog@@ -6251,27 +6264,91 @@ def do_upgrade(auto_restart: bool = True) -> dict:"""current_vibe_path = get_running_vibe_path()plan = build_upgrade_plan(vibe_path=current_vibe_path)+ if plan.preflight_error:+ return {+ "ok": False,+ "message": "Upgrade cannot be activated safely",+ "output": plan.preflight_error,+ "restarting": False,+ }runtime_was_running = _runtime_process_was_running()# Use a stable directory as cwd to avoid "Current directory does not exist"# errors. The vibe service process cwd may be inside the uv tool venv# directory, which uv deletes and recreates during upgrade.safe_cwd = get_safe_cwd()+ restarting = False+ restart_failed = False+ runtime_output = None+ deferred_activation = False+ restart_python = Nonetry:- result = subprocess.run(- plan.command,- capture_output=True,- text=True,- timeout=120,- env=plan.env,- cwd=safe_cwd,- )- if result.returncode == 0:- restarting = False- restart_failed = False- runtime_output = None- if auto_restart and runtime_was_running:+ with atomic_upgrade_lock():+ if restart_is_pending():+ return {+ "ok": False,+ "message": "Upgrade already has a restart in progress",+ "output": "Wait for the pending restart to finish before starting another upgrade.",+ "restarting": False,+ }+ if plan.activation is not None and activation_block_reason(plan.activation) == "superseded":+ return {+ "ok": False,+ "message": "Upgrade was superseded by another activation",+ "output": "The active Avibe generation changed while waiting for the upgrade lock; retry the upgrade.",+ "restarting": False,+ }+ result = subprocess.run(+ plan.command,+ capture_output=True,+ text=True,+ # A wheel install copies the complete candidate environment before+ # it can be activated. The old 120s bound interrupted that copy+ # in-place and left metadata claiming a package tree that no longer+ # existed. The candidate is isolated now; this is only a bound for+ # a genuinely hung resolver/download.+ timeout=UPGRADE_INSTALL_TIMEOUT_SECONDS,+ env=plan.env,+ cwd=safe_cwd,+ )+ if result.returncode == 0 and plan.activation is not None:+ try:+ if os.name == "nt" and launcher_is_current_process(plan.activation.launcher):+ candidate_result = verify_upgrade_candidate(plan.activation)+ if not candidate_result.ok:+ raise RuntimeError(candidate_result.detail)+ defer_upgrade_activation(+ plan.activation,+ parent_pid=os.getpid(),+ rollback_to=plan.rollback_to,+ restart_required=auto_restart and runtime_was_running,+ prepare_show_runtime=not should_skip_show_runtime_prepare(),+ )+ deferred_activation = True+ else:+ restart_python = _candidate_python(plan.activation.candidate_launcher)+ activate_upgrade_candidate(plan.activation)+ except Exception as exc: # noqa: BLE001+ discard_atomic_uv_install_generation(plan.activation.candidate_launcher)+ return {+ "ok": False,+ "message": "Upgrade candidate failed integrity verification",+ "output": str(exc),+ "restarting": False,+ }+ elif result.returncode != 0 and plan.activation is not None:+ discard_atomic_uv_install_generation(plan.activation.candidate_launcher)+ if result.returncode == 0 and plan.activation is None and plan.method == "pip":+ integrity = verify_python_environment(sys.executable)+ if not integrity.ok:+ return {+ "ok": False,+ "message": "Upgrade installed an incomplete Python environment",+ "output": integrity.detail,+ "restarting": False,+ }+ if result.returncode == 0 and auto_restart and runtime_was_running and not deferred_activation:try:schedule_restart(delay_seconds=2.0,@@ -6279,12 +6356,21 @@ def do_upgrade(auto_restart: bool = True) -> dict:trigger="upgrade",prepare_show_runtime=not should_skip_show_runtime_prepare(),rollback_to=plan.rollback_to,+ **({"python_executable": str(restart_python)} if restart_python else {}),)restarting = Trueexcept Exception as exc:restart_failed = Trueruntime_output = f"Restart scheduling failed; run `vibe restart` to use the new version.\n{exc}"- else:+ if result.returncode == 0:+ if deferred_activation:+ return {+ "ok": True,+ "message": "Upgrade successful. Activation will complete after this process exits.",+ "output": _append_upgrade_output(result.stdout, None),+ "restarting": auto_restart and runtime_was_running,+ }+ if not restarting and not restart_failed:runtime_output = _prepare_show_runtime_after_upgrade(current_vibe_path, safe_cwd)if restarting:message = "Upgrade successful. Restarting..."@@ -6307,6 +6393,8 @@ def do_upgrade(auto_restart: bool = True) -> dict:"restarting": False,}except subprocess.TimeoutExpired:+ if plan.activation is not None:+ discard_atomic_uv_install_generation(plan.activation.candidate_launcher)return {"ok": False,"message": "Upgrade timed out",@@ -6314,6 +6402,8 @@ def do_upgrade(auto_restart: bool = True) -> dict:"restarting": False,}except Exception as e:+ if plan.activation is not None:+ discard_atomic_uv_install_generation(plan.activation.candidate_launcher)return {"ok": False, "message": str(e), "output": None, "restarting": False}diff --git a/vibe/cli.py b/vibe/cli.pyindex 58365e1b1..03cbfa28e 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -51,6 +51,7 @@ from core.scheduled_tasks import ()from core.caller_context import caller_context_from_env, caller_resource_user_contextfrom core.command_runner import command_line_preview+from core.install_integrity import verify_python_environment, verify_site_packagesfrom core.vibe_agents import AgentArchivedEditError, AgentArchiveError, AgentNameValidationError, AgentReferenceRewriteError, VibeAgent, VibeAgentStore, iter_global_agent_files, parse_agent_file, validate_agent_backendfrom core.watches import (DEFAULT_RETRY_EXIT_CODE,@@ -68,11 +69,28 @@ from vibe.upgrade import (CURRENT_VIBE_EXECUTABLE_ENV,LEGACY_PACKAGE_NAME,PACKAGE_NAME,+ AtomicActivation,+ DEFERRED_ACTIVATION_TIMEOUT_SECONDS,+ RollbackTarget,+ activate_installer_candidate,+ activate_upgrade_candidate,+ activation_block_reason,+ atomic_uv_install_root,+ atomic_upgrade_lock,build_upgrade_plan,cache_running_vibe_path,+ defer_upgrade_activation,get_latest_version_info,get_safe_cwd,+ _launcher_generation,+ _candidate_python,+ launcher_is_current_process,+ restart_is_pending,+ restart_record_is_pending,+ discard_atomic_uv_install_generation,should_skip_show_runtime_prepare,+ UPGRADE_INSTALL_TIMEOUT_SECONDS,+ verify_upgrade_candidate,)from storage.db import create_sqlite_enginefrom storage.background import (@@ -1218,17 +1236,7 @@ def _service_install_family_items(*, detect_extra_processes: bool = True) -> lisdef _restart_status_is_stale(payload: dict, path: Path) -> bool:state = payload.get("state")if state in {"scheduled", "running"}:- supervisor_pid = payload.get("supervisor_pid")- if isinstance(supervisor_pid, int) and runtime.pid_alive(supervisor_pid):- started_at = payload.get("supervisor_started_at")- if started_at is not None:- current_started_at = runtime.process_create_time(supervisor_pid)- return current_started_at is not None and current_started_at != started_at- try:- age = time.time() - path.stat().st_mtime- except OSError:- return False- return age > DOCTOR_RESTART_SEED_GRACE_SECONDS+ return not restart_record_is_pending(payload, path, grace_seconds=DOCTOR_RESTART_SEED_GRACE_SECONDS)if state in {"succeeded", "failed", "error", "cancelled"}:try:@@ -11832,6 +11840,16 @@ def _uv_tool_site_packages_for_vibe(vibe_path: Path) -> list[Path]:seen_roots.add(key)tool_roots.append(resolved)+ # Atomic upgrades keep each validated uv environment in a durable+ # generation directory and switch only the stable PATH launcher. Resolve+ # that generation directly so doctor inspects the active candidate just as+ # it inspects a conventional ``~/.local/share/uv/tools/<package>`` root.+ generation_root = atomic_uv_install_root().expanduser().resolve()+ generation = _launcher_generation(vibe_path, generation_root)+ if generation:+ for package_name in UV_TOOL_PACKAGE_NAMES:+ add_tool_root(generation / "tools" / package_name)+parts = vibe_path.partstry:tools_index = parts.index("tools")@@ -11997,6 +12015,28 @@ def _local_cli_installation_items() -> list[dict]:else:_add_doctor_item(items, "pass", f"uv tool installation is not editable: {site_packages}")+ # A successful package-manager exit only proves that its metadata was+ # written. RECORD is the wheel-level evidence that every installed+ # file is still present and unchanged; this is what catches an+ # interrupted dependency copy such as a half-written lark-oapi tree.+ if any(site_packages.glob("*.dist-info")):+ integrity = verify_site_packages(site_packages)+ if integrity.ok:+ _add_doctor_item(+ items,+ "pass",+ f"Python package files are intact: {integrity.detail}",+ code="installation.package_integrity",+ )+ else:+ _add_doctor_item(+ items,+ "fail",+ f"Python package integrity check failed: {integrity.detail}",+ "Rerun the Avibe installer to replace the active environment with a verified wheel.",+ code="installation.package_integrity",+ )+alembic_dir = site_packages / "storage" / "alembic"versions_dir = alembic_dir / "versions"if not alembic_dir.exists() or not versions_dir.exists():@@ -14389,18 +14429,65 @@ def cmd_upgrade():current_vibe_path = cache_running_vibe_path()plan = build_upgrade_plan(vibe_path=current_vibe_path)+ if plan.preflight_error:+ print(f"\033[31mUpgrade cannot be activated safely: {plan.preflight_error}\033[0m")+ return 1print(f"Using {plan.method}: {' '.join(plan.command)}")runtime_was_running = _runtime_process_was_running()# Use a stable directory as cwd to avoid issues when running from a# directory that uv may delete during upgrade (e.g. inside the uv tool venv).safe_cwd = get_safe_cwd()+ restart = None+ restart_error = None+ deferred_activation = False+ restart_python = Nonetry:- result = subprocess.run(plan.command, capture_output=True, text=True, env=plan.env, cwd=safe_cwd)- if result.returncode == 0:- print("\033[32mUpgrade successful!\033[0m")- if runtime_was_running:+ with atomic_upgrade_lock():+ if restart_is_pending():+ print("\033[31mUpgrade already has a restart in progress; wait for it to finish.\033[0m")+ return 1+ if plan.activation is not None and activation_block_reason(plan.activation) == "superseded":+ print("\033[31mUpgrade was superseded by another activation; retry the upgrade.\033[0m")+ return 1+ result = subprocess.run(+ plan.command,+ capture_output=True,+ text=True,+ env=plan.env,+ cwd=safe_cwd,+ timeout=UPGRADE_INSTALL_TIMEOUT_SECONDS,+ )+ if result.returncode == 0 and plan.activation is not None:+ try:+ if os.name == "nt" and launcher_is_current_process(plan.activation.launcher):+ candidate_result = verify_upgrade_candidate(plan.activation)+ if not candidate_result.ok:+ raise RuntimeError(candidate_result.detail)+ defer_upgrade_activation(+ plan.activation,+ parent_pid=os.getpid(),+ rollback_to=plan.rollback_to,+ restart_required=runtime_was_running,+ prepare_show_runtime=not should_skip_show_runtime_prepare(),+ )+ deferred_activation = True+ else:+ restart_python = _candidate_python(plan.activation.candidate_launcher)+ activate_upgrade_candidate(plan.activation)+ except Exception as exc: # noqa: BLE001+ discard_atomic_uv_install_generation(plan.activation.candidate_launcher)+ print(f"\033[31mUpgrade candidate failed integrity verification: {exc}\033[0m")+ return 1+ elif result.returncode != 0 and plan.activation is not None:+ discard_atomic_uv_install_generation(plan.activation.candidate_launcher)+ if result.returncode == 0 and plan.activation is None and plan.method == "pip":+ integrity = verify_python_environment(sys.executable)+ if not integrity.ok:+ print(f"\033[31mUpgrade installed an incomplete Python environment: {integrity.detail}\033[0m")+ return 1+ if result.returncode == 0 and runtime_was_running and not deferred_activation:try:restart = schedule_restart(delay_seconds=0.0,@@ -14408,16 +14495,26 @@ def cmd_upgrade():trigger="upgrade",prepare_show_runtime=not should_skip_show_runtime_prepare(),rollback_to=plan.rollback_to,+ **({"python_executable": str(restart_python)} if restart_python else {}),)except Exception as exc:- print("\033[33mUpgrade installed, but restart scheduling failed.\033[0m")- print(f"Restart error: {exc}")- print("Run `vibe restart` to use the new version.")- return 2- else:- print("Restart scheduled to use the new version.")- print(f"Job ID: {restart['job_id']}")- print("Run `vibe status` to inspect the restart result.")+ restart_error = exc+ if result.returncode == 0:+ print("\033[32mUpgrade successful!\033[0m")+ if deferred_activation:+ print("Upgrade validated; launcher activation will complete after this command exits.")+ if runtime_was_running:+ print("Restart will be scheduled by the activation helper.")+ return 0+ if restart_error is not None:+ print("\033[33mUpgrade installed, but restart scheduling failed.\033[0m")+ print(f"Restart error: {restart_error}")+ print("Run `vibe restart` to use the new version.")+ return 2+ if restart is not None:+ print("Restart scheduled to use the new version.")+ print(f"Job ID: {restart['job_id']}")+ print("Run `vibe status` to inspect the restart result.")else:_prepare_show_runtime_after_install(current_vibe_path)print("Avibe was not running; the new version will be used next time you start it.")@@ -14426,6 +14523,8 @@ def cmd_upgrade():print(f"\033[31mUpgrade failed:\033[0m\n{result.stderr}")return 1except Exception as e:+ if plan.activation is not None:+ discard_atomic_uv_install_generation(plan.activation.candidate_launcher)print(f"\033[31mUpgrade failed: {e}\033[0m")return 1@@ -16859,11 +16958,130 @@ def _dispatch_restart_supervisor(argv: list[str]) -> int:return restart_supervisor_main(argv)+def _dispatch_deferred_upgrade_activation(argv: list[str]) -> int:+ """Activate a Windows CLI upgrade after the parent launcher exits."""++ parser = argparse.ArgumentParser(add_help=False)+ parser.add_argument("--parent-pid", type=int, required=True)+ parser.add_argument("--parent-started-at", type=float)+ parser.add_argument("--launcher", required=True)+ parser.add_argument("--candidate", required=True)+ parser.add_argument("--source-generation")+ parser.add_argument("--restart", action="store_true")+ parser.add_argument("--prepare-show-runtime", action="store_true")+ parser.add_argument("--rollback-to")+ parser.add_argument("--rollback-package")+ parser.add_argument("--rollback-python")+ parser.add_argument("--rollback-main")+ args = parser.parse_args(argv)++ deadline = time.monotonic() + DEFERRED_ACTIVATION_TIMEOUT_SECONDS+ while runtime.pid_alive(args.parent_pid):+ if args.parent_started_at is not None:+ observed = runtime.process_create_time(args.parent_pid)+ if observed is not None and observed != args.parent_started_at:+ break+ if time.monotonic() >= deadline:+ print("deferred upgrade activation timed out waiting for the parent launcher", file=sys.stderr)+ return 1+ time.sleep(0.1)++ source_generation = Path(args.source_generation) if args.source_generation else None+ activation = AtomicActivation(+ launcher=Path(args.launcher),+ candidate_launcher=Path(args.candidate),+ source_generation=source_generation,+ )+ if args.restart and args.rollback_to and (not args.rollback_python or not args.rollback_main):+ print("deferred upgrade restart is missing its rollback launcher", file=sys.stderr)+ return 1+ rollback_to = (+ RollbackTarget(+ version=args.rollback_to,+ package=args.rollback_package,+ launcher=runtime.ServiceLauncher(python=args.rollback_python, main=args.rollback_main),+ )+ if args.rollback_to+ else None+ )+ activated = False+ try:+ with atomic_upgrade_lock():+ reason = activation_block_reason(activation)+ if reason == "restart_pending":+ discard_atomic_uv_install_generation(activation.candidate_launcher)+ print("deferred upgrade activation found another restart in progress", file=sys.stderr)+ return 1+ if reason == "superseded":+ discard_atomic_uv_install_generation(activation.candidate_launcher)+ print("deferred upgrade activation was superseded by another activation", file=sys.stderr)+ return 1+ activate_upgrade_candidate(activation)+ activated = True+ if args.restart:+ schedule_restart(+ delay_seconds=0.0,+ vibe_path=args.launcher,+ trigger="upgrade",+ prepare_show_runtime=args.prepare_show_runtime,+ rollback_to=rollback_to,+ python_executable=sys.executable,+ )+ except Exception as exc:+ if not activated:+ discard_atomic_uv_install_generation(activation.candidate_launcher)+ print(f"deferred upgrade activation failed: {exc}", file=sys.stderr)+ else:+ print(f"deferred upgrade restart scheduling failed: {exc}", file=sys.stderr)+ return 1++ if not args.restart and args.prepare_show_runtime:+ _prepare_show_runtime_after_install(args.launcher)+ return 0+++def _dispatch_installer_activation(argv: list[str]) -> int:+ """Activate a staged one-command install through the shared Python owner."""++ if argv == ["--protocol-version"]:+ print("2")+ return 0+ parser = argparse.ArgumentParser(add_help=False)+ parser.add_argument("--snapshot", action="store_true")+ parser.add_argument("--launcher", required=True)+ parser.add_argument("--candidate")+ parser.add_argument("--source-generation")+ args = parser.parse_args(argv)+ if args.snapshot:+ generation = _launcher_generation(Path(args.launcher), atomic_uv_install_root())+ if generation is not None:+ print(generation)+ return 0+ if not args.candidate:+ parser.error("--candidate is required unless --snapshot is used")+ activation = AtomicActivation(+ launcher=Path(args.launcher),+ candidate_launcher=Path(args.candidate),+ source_generation=Path(args.source_generation) if args.source_generation else None,+ )+ try:+ activate_installer_candidate(activation)+ except Exception as exc:+ discard_atomic_uv_install_generation(activation.candidate_launcher)+ print(f"installer activation failed: {exc}", file=sys.stderr)+ return 1+ return 0++def main():cache_running_vibe_path()argv = sys.argv[1:]if argv and argv[0] == "__restart-supervisor":sys.exit(_dispatch_restart_supervisor(argv[1:]))+ if argv and argv[0] == "__activate-upgrade":+ sys.exit(_dispatch_deferred_upgrade_activation(argv[1:]))+ if argv and argv[0] == "__activate-install":+ sys.exit(_dispatch_installer_activation(argv[1:]))parser = build_parser()args = parser.parse_args()diff --git a/vibe/restart_supervisor.py b/vibe/restart_supervisor.pyindex 3d590d0d5..20ddce234 100644--- a/vibe/restart_supervisor.py+++ b/vibe/restart_supervisor.py@@ -30,6 +30,11 @@ from vibe.upgrade import (LEGACY_PACKAGE_NAME,PACKAGE_NAME,RollbackTarget,+ activate_launcher_target,+ atomic_uv_install_root,+ atomic_upgrade_lock,+ _launcher_generation,+ get_cli_launcher_path,_names_a_published_release,build_upgrade_plan,get_restart_command,@@ -627,6 +632,9 @@ def _roll_back_failed_upgrade("""version = rollback_to.version+ restore_stable_launcher = bool(+ vibe_path and _launcher_generation(Path(vibe_path).expanduser(), atomic_uv_install_root()) is not None+ )rollback: dict = {"target_version": version, "state": "running", "started_at": _now_iso()}record(rollback)write(f"rolling back to {version}: no service is running after the failed restart")@@ -655,42 +663,62 @@ def _roll_back_failed_upgrade(write(f"cannot roll back to {version}: the failed generation did not stop")return rollback- try:- plan = build_upgrade_plan(vibe_path=vibe_path, version=version, package_name=rollback_to.package)- except Exception as exc:- rollback.update(state="failed", error=f"cannot build a pinned install for {version}: {exc}")+ # A staged upgrade leaves the previous tool generation untouched. Reuse it+ # directly during rollback; reinstalling the old wheel would reintroduce a+ # long, mutable operation into the one path that exists to recover quickly.+ rollback_cli_launcher = get_cli_launcher_path(rollback_to.launcher) if restore_stable_launcher else None+ if restore_stable_launcher and vibe_path and rollback_cli_launcher is not None:+ rollback["install"] = {"method": "atomic", "ok": True, "reused": True}record(rollback)- return rollback+ write(f"reusing the previous {version} generation")+ else:+ try:+ plan = build_upgrade_plan(vibe_path=vibe_path, version=version, package_name=rollback_to.package)+ except Exception as exc:+ rollback.update(state="failed", error=f"cannot build a pinned install for {version}: {exc}")+ record(rollback)+ return rollback- rollback["install"] = {"method": plan.method, "ok": None}- record(rollback)- try:- result = subprocess.run(- plan.command,- capture_output=True,- text=True,- env=plan.env,- cwd=get_safe_cwd(),- timeout=_ROLLBACK_INSTALL_TIMEOUT_SECONDS,- )- except Exception as exc:- rollback["install"] = {"method": plan.method, "ok": False, "error": str(exc)}- rollback.update(state="failed", error=f"installing {version} failed: {exc}")+ rollback["install"] = {"method": plan.method, "ok": None}record(rollback)- return rollback- if result.returncode != 0:- # The installer's own stderr, trimmed: it is the only account of why the- # rollback could not proceed, and the full text can be megabytes of- # resolver output.- detail = (result.stderr or result.stdout or "").strip()[-2000:]- rollback["install"] = {"method": plan.method, "ok": False, "error": detail or f"exit code {result.returncode}"}- rollback.update(state="failed", error=f"installing {version} failed with exit code {result.returncode}")+ try:+ result = subprocess.run(+ plan.command,+ capture_output=True,+ text=True,+ env=plan.env,+ cwd=get_safe_cwd(),+ timeout=_ROLLBACK_INSTALL_TIMEOUT_SECONDS,+ )+ except Exception as exc:+ rollback["install"] = {"method": plan.method, "ok": False, "error": str(exc)}+ rollback.update(state="failed", error=f"installing {version} failed: {exc}")+ record(rollback)+ return rollback+ if result.returncode != 0:+ # The installer's own stderr, trimmed: it is the only account of why the+ # rollback could not proceed, and the full text can be megabytes of+ # resolver output.+ detail = (result.stderr or result.stdout or "").strip()[-2000:]+ rollback["install"] = {"method": plan.method, "ok": False, "error": detail or f"exit code {result.returncode}"}+ rollback.update(state="failed", error=f"installing {version} failed with exit code {result.returncode}")+ record(rollback)+ write(f"pinned install of {version} failed: {detail}")+ return rollback+ rollback["install"] = {"method": plan.method, "ok": True}+ record(rollback)+ write(f"installed {version} using {plan.method}")++ if restore_stable_launcher and vibe_path and rollback_cli_launcher is not None:+ try:+ with atomic_upgrade_lock():+ activate_launcher_target(vibe_path, rollback_cli_launcher)+ except Exception as exc: # noqa: BLE001+ rollback.update(state="failed", error=f"restoring the active launcher failed: {exc}")+ record(rollback)+ return rollback+ rollback["launcher"] = {"restored": True, "path": str(rollback_cli_launcher)}record(rollback)- write(f"pinned install of {version} failed: {detail}")- return rollback- rollback["install"] = {"method": plan.method, "ok": True}- record(rollback)- write(f"installed {version} using {plan.method}")try:rollback["database"] = _restore_database_for_rollback(backup_watermark, write)@@ -1051,6 +1079,39 @@ def schedule_restart(prepare_show_runtime: bool = False,memory_ui_secret: str | None = None,rollback_to: RollbackTarget | None = None,+ python_executable: str | None = None,+) -> dict:+ """Serialize every restart seed with install activation and pruning."""++ from storage.migrations import guard_source_checkout_default_state_bootstrap++ # The lock lives under the runtime directory. Preserve the development+ # guard's contract by checking it before lock acquisition can create that+ # directory.+ guard_source_checkout_default_state_bootstrap()+ with atomic_upgrade_lock():+ return _schedule_restart_locked(+ delay_seconds=delay_seconds,+ vibe_path=vibe_path,+ trigger=trigger,+ scope=scope,+ prepare_show_runtime=prepare_show_runtime,+ memory_ui_secret=memory_ui_secret,+ rollback_to=rollback_to,+ python_executable=python_executable,+ )+++def _schedule_restart_locked(+ *,+ delay_seconds: float,+ vibe_path: str | None,+ trigger: str,+ scope: str,+ prepare_show_runtime: bool,+ memory_ui_secret: str | None,+ rollback_to: RollbackTarget | None,+ python_executable: str | None,) -> dict:"""Spawn the detached restart job.@@ -1071,12 +1132,12 @@ def schedule_restart(is the only place they are put back together."""from core.memory.ui_access import process_ui_read_secret- from storage.migrations import guard_source_checkout_default_state_bootstrap-memory_ui_secret = memory_ui_secret or process_ui_read_secret()- guard_source_checkout_default_state_bootstrap()job_id = uuid.uuid4().hex[:12]- invocation = get_restart_invocation_command(vibe_path=vibe_path)+ if python_executable:+ invocation = [python_executable, "-c", "from vibe.cli import main; main()", "restart"]+ else:+ invocation = get_restart_invocation_command(vibe_path=vibe_path)command = [*invocation[:-1], "__restart-supervisor"] if invocation and invocation[-1] == "restart" else [*(invocation or ["vibe"]),"__restart-supervisor",@@ -1107,6 +1168,12 @@ def schedule_restart(if rollback_to.package:command.extend(["--rollback-package", rollback_to.package])env = get_restart_environment(vibe_path=vibe_path)+ if python_executable:+ # A candidate supervisor must import the staged wheel, never a source+ # checkout inherited from the parent process.+ env = dict(os.environ if env is None else env)+ env.pop("PYTHONPATH", None)+ env.pop("PYTHONHOME", None)log_path = _restart_log_path(job_id)log_path.parent.mkdir(parents=True, exist_ok=True)# Seed the status BEFORE spawning the job so the child's own writes (which setdiff --git a/vibe/upgrade.py b/vibe/upgrade.pyindex bd20fc25a..f3e96c971 100644--- a/vibe/upgrade.py+++ b/vibe/upgrade.py@@ -1,19 +1,32 @@from __future__ import annotations+import contextlib+import filecmpimport jsonimport loggingimport osimport reimport shleximport shutil+import subprocessimport sysimport tempfile+import timeimport urllib.requestfrom collections.abc import Mappingfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import NamedTuple, cast-+from uuid import uuid4++from config import paths as config_paths+from core.install_integrity import (+ IntegrityResult,+ isolated_probe_environment,+ run_isolated_probe,+ verify_python_environment,+)+from storage.lock import MigrationFileLockfrom vibe import runtime as runtime_mod@@ -26,6 +39,9 @@ CURRENT_VIBE_EXECUTABLE_ENV = "VIBE_CURRENT_EXECUTABLE"SHOW_RUNTIME_SKIP_ENV = "VIBE_INSTALL_SKIP_SHOW_RUNTIME"TRUTHY_ENV_VALUES = {"1", "true", "yes", "on"}UV_FALLBACK_BIN_DIRS = (".local/bin", ".cargo/bin")+UPGRADE_INSTALL_TIMEOUT_SECONDS = 30 * 60+RESTART_PENDING_GRACE_SECONDS = 5 * 60+DEFERRED_ACTIVATION_TIMEOUT_SECONDS = 5 * 60# 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@@ -84,6 +100,466 @@ class UpgradePlan:env: dict[str, str] | Nonemethod: strrollback_to: RollbackTarget | None = None+ activation: "AtomicActivation | None" = None+ preflight_error: str | None = None+++@dataclass(frozen=True)+class AtomicActivation:+ """A validated candidate and the stable launcher it will replace."""++ launcher: Path+ candidate_launcher: Path+ source_generation: Path | None = None+++def atomic_uv_install_root() -> Path:+ """Return the durable root for versioned uv tool environments."""++ return config_paths.get_vibe_remote_dir() / "runtime" / "install-generations"+++def atomic_upgrade_lock():+ """Serialize staged installation, launcher activation, and pruning."""++ lock_path = atomic_uv_install_root().expanduser().parent / ".install.lock"+ with MigrationFileLock(lock_path, timeout_seconds=UPGRADE_INSTALL_TIMEOUT_SECONDS):+ yield+++def restart_is_pending() -> bool:+ """Whether a scheduled restart still owns the next activation boundary."""++ path = runtime_mod.get_restart_status_path()+ payload = runtime_mod.read_json(path)+ if not isinstance(payload, Mapping):+ return False+ return restart_record_is_pending(payload, path)+++def restart_record_is_pending(+ payload: Mapping[str, object],+ path: Path,+ *,+ grace_seconds: float = RESTART_PENDING_GRACE_SECONDS,+) -> bool:+ """Apply the restart ownership policy to one persisted status record."""++ if payload.get("state") not in {"scheduled", "running"}:+ return False+ supervisor_pid = payload.get("supervisor_pid")+ if isinstance(supervisor_pid, int) and supervisor_pid > 0 and runtime_mod.pid_alive(supervisor_pid):+ started_at = payload.get("supervisor_started_at")+ if started_at is not None:+ current_started_at = runtime_mod.process_create_time(supervisor_pid)+ if current_started_at is not None:+ return current_started_at == started_at+ # Legacy records do not carry a process identity, and process metadata+ # can be unavailable. In both cases a reused PID must not block upgrades+ # for the lifetime of an unrelated process, so fall through to age.+ try:+ age = time.time() - path.stat().st_mtime+ except OSError:+ return False+ return age <= grace_seconds+++def _is_stable_launcher_path(launcher: Path) -> bool:+ if launcher.name.lower() not in {"vibe", "vibe.exe"}:+ return False+ # ``vibe_path`` has already been resolved to the command that launched this+ # installation. Its role, not the directory uv happened to use when it was+ # installed, makes it the stable activation point. The only unsafe shape is+ # the entry point inside the mutable uv tool environment itself.+ logical = os.path.normcase(os.path.abspath(os.path.expanduser(str(launcher))))+ atomic_root = os.path.normcase(os.path.abspath(os.path.expanduser(str(atomic_uv_install_root()))))+ uv_layout = logical.replace("\\", "/").lower()+ return "/uv/tools/" not in uv_layout and not Path(logical).is_relative_to(Path(atomic_root))+++def launcher_is_current_process(launcher: Path | str) -> bool:+ """Whether this Windows process is holding the stable launcher open."""++ if os.name != "nt":+ return False+ target = os.path.normcase(os.path.abspath(os.path.expanduser(str(launcher))))+ # ``VIBE_CURRENT_EXECUTABLE`` is inherited by the long-lived Web process+ # from the CLI that started it. It identifies a PATH entry, not the image+ # currently holding the file open, so only argv[0] is authoritative here.+ current = os.path.normcase(os.path.abspath(os.path.expanduser(sys.argv[0])))+ return current == target+++def _staged_uv_environment(vibe_path: str | None) -> tuple[Path, Path, AtomicActivation | None]:+ generation = atomic_uv_install_root() / uuid4().hex+ tools_dir = generation / "tools"+ bin_dir = generation / "bin"+ if not vibe_path:+ return tools_dir, bin_dir, None++ launcher = Path(vibe_path).expanduser()+ # Only replace a stable launcher link. A direct path into a virtualenv may+ # be the user's intentional installation and cannot be switched safely by+ # replacing the file the current process is executing.+ if not _is_stable_launcher_path(launcher):+ return tools_dir, bin_dir, None+ candidate = bin_dir / launcher.name+ return tools_dir, bin_dir, AtomicActivation(+ launcher=launcher,+ candidate_launcher=candidate,+ source_generation=_launcher_generation(launcher, atomic_uv_install_root()),+ )+++def _candidate_python(candidate_launcher: Path) -> Path | None:+ roots = [candidate_launcher.parent]+ with contextlib.suppress(OSError, RuntimeError):+ resolved_parent = candidate_launcher.resolve().parent+ if resolved_parent not in roots:+ roots.append(resolved_parent)+ with contextlib.suppress(OSError, RuntimeError, ValueError):+ generation = _generation_for_path(candidate_launcher, atomic_uv_install_root())+ if generation is not None:+ roots.append(generation / "tools")+ names = ("python.exe", "python3.exe", "python3", "python") if os.name == "nt" else ("python3", "python")+ for root in roots:+ for name in names:+ candidate = root / name+ if candidate.is_file() and os.access(candidate, os.X_OK):+ return candidate+ if root.name == "tools" and root.is_dir():+ for name in names:+ for candidate in sorted(root.rglob(name)):+ if candidate.is_file() and os.access(candidate, os.X_OK):+ return candidate+ return None+++def defer_upgrade_activation(+ activation: AtomicActivation,+ *,+ parent_pid: int,+ rollback_to: "RollbackTarget | None" = None,+ restart_required: bool = False,+ prepare_show_runtime: bool = False,+) -> subprocess.Popen:+ """Run activation after a Windows CLI process releases its launcher."""++ candidate_python = _candidate_python(activation.candidate_launcher)+ if candidate_python is None:+ raise RuntimeError(f"candidate Python missing beside {activation.candidate_launcher}")+ command = [+ str(candidate_python),+ "-c",+ "from vibe.cli import main; main()",+ "__activate-upgrade",+ "--parent-pid",+ str(parent_pid),+ "--launcher",+ str(activation.launcher),+ "--candidate",+ str(activation.candidate_launcher),+ ]+ if activation.source_generation is not None:+ command.extend(["--source-generation", str(activation.source_generation)])+ if restart_required:+ command.append("--restart")+ if prepare_show_runtime:+ command.append("--prepare-show-runtime")+ if rollback_to is not None:+ command.extend(+ [+ "--rollback-to",+ rollback_to.version,+ "--rollback-python",+ rollback_to.launcher.python,+ "--rollback-main",+ rollback_to.launcher.main,+ ]+ )+ if rollback_to.package:+ command.extend(["--rollback-package", rollback_to.package])+ parent_started_at = runtime_mod.process_create_time(parent_pid)+ if parent_started_at is not None:+ command.extend(["--parent-started-at", str(parent_started_at)])+ log_path = config_paths.get_logs_dir() / f"upgrade-activation-{uuid4().hex}.log"+ log_path.parent.mkdir(parents=True, exist_ok=True)+ with log_path.open("a", encoding="utf-8") as log:+ return subprocess.Popen(+ command,+ stdin=subprocess.DEVNULL,+ stdout=log,+ stderr=subprocess.STDOUT,+ start_new_session=True,+ close_fds=True,+ cwd=get_safe_cwd(),+ env=isolated_probe_environment(),+ )+++def get_cli_launcher_path(launcher: runtime_mod.ServiceLauncher) -> Path | None:+ """Find the CLI launcher next to a saved service interpreter."""++ names = ("vibe.exe", "vibe") if os.name == "nt" else ("vibe", "vibe.exe")+ python_path = Path(launcher.python).expanduser()+ root = atomic_uv_install_root()+ generation = _launcher_generation(python_path, root)+ if generation is not None:+ generation_bin = generation / "bin"+ for name in names:+ candidate = generation_bin / name+ if candidate.is_file() and os.access(candidate, os.X_OK):+ return candidate+ with contextlib.suppress(OSError):+ for name in names:+ candidate = next(generation.rglob(name), None)+ if candidate is not None and candidate.is_file() and os.access(candidate, os.X_OK):+ return candidate++ python_bin = python_path.parent+ for name in names:+ candidate = python_bin / name+ if candidate.is_file() and os.access(candidate, os.X_OK):+ return candidate+ return None+++def _generation_for_path(path: Path, root: Path) -> Path | None:+ """Return the canonical generation containing a logical install path.++ The leaf may itself be a symlink, as uv-managed Python launchers commonly+ are. Walk its logical ancestors and resolve only the candidate generation+ directory so the shared interpreter target cannot erase generation+ ownership.+ """++ try:+ root = root.expanduser().resolve()+ expanded = path.expanduser()+ except (OSError, RuntimeError):+ return None+ ancestors = [expanded, *expanded.parents]+ try:+ resolved_path = expanded.resolve()+ except (OSError, RuntimeError):+ resolved_path = None+ if resolved_path is not None:+ ancestors.extend((resolved_path, *resolved_path.parents))+ for ancestor in dict.fromkeys(ancestors):+ try:+ resolved = ancestor.resolve()+ except (OSError, RuntimeError):+ continue+ if resolved.parent == root:+ return resolved+ return None+++def _generation_for_hardlink(launcher: Path, root: Path) -> Path | None:+ """Find an atomic generation sharing the stable launcher's inode."""++ if launcher.is_symlink() or not _is_stable_launcher_path(launcher):+ return None+ try:+ launcher_stat = launcher.stat()+ identity = (launcher_stat.st_dev, launcher_stat.st_ino)+ except OSError:+ return None+ try:+ root = root.expanduser().resolve()+ if not root.is_dir():+ return None+ generations = list(root.iterdir())+ except OSError:+ return None+ for generation in generations:+ candidate = generation / "bin" / launcher.name+ try:+ candidate_stat = candidate.stat()+ if generation.is_dir() and (candidate_stat.st_dev, candidate_stat.st_ino) == identity:+ return generation+ except OSError:+ continue+ return None+++def _launcher_generation(launcher: Path, root: Path) -> Path | None:+ """Return the generation currently represented by a stable launcher."""++ root = root.expanduser().resolve()+ generation = _generation_for_path(launcher, root) or _generation_for_hardlink(launcher, root)+ if generation is not None:+ return generation+ if not _is_stable_launcher_path(launcher):+ return None+ marker = launcher.parent / f".{launcher.name}.avibe-generation"+ try:+ marked = Path(marker.read_text(encoding="utf-8").lstrip("\ufeff").strip())+ except (OSError, UnicodeError):+ return None+ generation = _generation_for_path(marked, root)+ if generation is None or not generation.is_dir():+ return None+ # A marker is necessary only for the cross-volume copy fallback. Treat it+ # as a hint and prove that it still describes the live launcher before use.+ candidate = generation / "bin" / launcher.name+ try:+ return generation if filecmp.cmp(launcher, candidate, shallow=False) else None+ except OSError:+ return None+++def _update_launcher_generation_marker(launcher: Path, target: Path, root: Path) -> None:+ """Record a copied launcher's generation without making cleanup mandatory."""++ marker = launcher.parent / f".{launcher.name}.avibe-generation"+ generation = _generation_for_path(target, root)+ if generation is None:+ with contextlib.suppress(OSError):+ marker.unlink()+ return+ replacement = marker.parent / f".{marker.name}.{uuid4().hex}.new"+ try:+ replacement.write_text(str(generation), encoding="utf-8")+ os.replace(replacement, marker)+ except OSError:+ with contextlib.suppress(OSError):+ replacement.unlink()+ logger.warning("failed to update launcher generation marker %s", marker, exc_info=True)+++def atomic_activation_source_is_current(activation: AtomicActivation) -> bool:+ """Check that the stable launcher still points at the source we measured."""++ root = atomic_uv_install_root()+ current = _launcher_generation(activation.launcher, root)+ if activation.source_generation is None:+ return current is None+ source = _generation_for_path(activation.source_generation, root)+ if current is not None or source is not None:+ return current == source+ try:+ current_target = activation.launcher.resolve(strict=True)+ return os.path.samefile(current_target, activation.source_generation)+ except (OSError, RuntimeError, ValueError):+ return False+++def activation_block_reason(activation: AtomicActivation) -> str | None:+ """Return why an activation cannot own the current install boundary."""++ if restart_is_pending():+ return "restart_pending"+ if not atomic_activation_source_is_current(activation):+ return "superseded"+ return None+++def discard_atomic_uv_install_generation(path: Path | str) -> bool:+ """Remove one failed candidate generation without touching active installs."""++ root = atomic_uv_install_root().expanduser().resolve()+ generation = _generation_for_path(Path(path), root)+ if generation is None or not generation.is_dir():+ return False+ try:+ shutil.rmtree(generation)+ except OSError:+ logger.warning("failed to discard atomic Avibe install generation %s", generation, exc_info=True)+ return False+ return True+++def verify_upgrade_candidate(activation: AtomicActivation) -> IntegrityResult:+ """Prove a staged tool is runnable and its package tree is complete."""++ candidate = activation.candidate_launcher+ if not candidate.is_file() or not os.access(candidate, os.X_OK):+ return IntegrityResult(False, failures=(f"candidate launcher missing: {candidate}",))+ python = _candidate_python(candidate)+ if python is None:+ return IntegrityResult(False, failures=(f"candidate Python missing beside {candidate}",))+ result = verify_python_environment(python)+ if not result.ok:+ return result+ try:+ probe = run_isolated_probe([str(candidate), "--help"], timeout=60)+ except (OSError, subprocess.SubprocessError) as exc:+ return IntegrityResult(False, failures=(f"candidate launcher probe failed: {exc}",))+ if probe.returncode != 0:+ detail = (probe.stderr or probe.stdout or "").strip().splitlines()+ suffix = detail[-1] if detail else f"exit code {probe.returncode}"+ return IntegrityResult(False, failures=(f"candidate launcher probe failed: {suffix}",))+ return result+++def _prepare_launcher_replacement(replacement: Path, target: Path) -> None:+ """Create a replacement launcher, using copy when links cannot cross volumes."""++ try:+ replacement.symlink_to(target)+ return+ except OSError:+ pass+ try:+ os.link(target, replacement)+ return+ except OSError:+ # A regular copy is the only portable option when the stable bin and+ # the runtime home are on different Windows volumes.+ shutil.copy2(target, replacement)+++def activate_upgrade_candidate(activation: AtomicActivation) -> None:+ """Atomically switch the stable launcher to a validated candidate."""++ result = verify_upgrade_candidate(activation)+ if not result.ok:+ raise RuntimeError(f"staged Avibe install failed integrity checks: {result.detail}")+ launcher = activation.launcher+ launcher.parent.mkdir(parents=True, exist_ok=True)+ replacement = launcher.parent / f".{launcher.name}.avibe-{uuid4().hex}.new"+ root = atomic_uv_install_root().expanduser().resolve()+ try:+ _prepare_launcher_replacement(replacement, activation.candidate_launcher)+ os.replace(replacement, launcher)+ except Exception:+ with contextlib.suppress(OSError):+ replacement.unlink()+ raise+ _update_launcher_generation_marker(launcher, activation.candidate_launcher, root)+++def activate_installer_candidate(activation: AtomicActivation) -> None:+ """Activate an installer candidate through the shared lifecycle owner."""++ with atomic_upgrade_lock():+ reason = activation_block_reason(activation)+ if reason == "restart_pending":+ raise RuntimeError("an Avibe restart is still in progress")+ if reason == "superseded":+ raise RuntimeError("the active Avibe generation changed while the installer was staging")+ activate_upgrade_candidate(activation)+++def activate_launcher_target(launcher: str | os.PathLike[str], target: str | os.PathLike[str]) -> None:+ """Atomically point a stable launcher at an already installed target."""++ launcher_path = Path(launcher).expanduser()+ target_path = Path(target).expanduser()+ if not target_path.is_file() or not os.access(target_path, os.X_OK):+ raise RuntimeError(f"rollback launcher is not executable: {target_path}")+ launcher_path.parent.mkdir(parents=True, exist_ok=True)+ replacement = launcher_path.parent / f".{launcher_path.name}.avibe-{uuid4().hex}.new"+ try:+ _prepare_launcher_replacement(replacement, target_path)+ os.replace(replacement, launcher_path)+ except Exception:+ with contextlib.suppress(OSError):+ replacement.unlink()+ raise+ _update_launcher_generation_marker(launcher_path, target_path, atomic_uv_install_root().expanduser().resolve())def resolve_command_path(command: str | None, search_path: str | None = None) -> str | None:@@ -459,7 +935,21 @@ def get_latest_version_info(current_version: str) -> dict:def is_uv_tool_install(python_executable: str | None = None) -> bool:executable = (python_executable or sys.executable or "").replace("\\", "/")- return "/uv/tools/" in executable+ if "/uv/tools/" in executable:+ return True+ try:+ logical = Path(os.path.abspath(os.path.expanduser(executable)))+ logical_root = Path(os.path.abspath(os.path.expanduser(str(atomic_uv_install_root()))))+ if logical.is_relative_to(logical_root):+ return True+ if _launcher_generation(logical, logical_root) is not None:+ return True+ # A logical path may contain a symlinked parent. Resolving is only the+ # fallback: uv's tool Python is itself commonly a symlink to a shared+ # interpreter outside the generation.+ return logical.resolve().is_relative_to(logical_root.resolve())+ except (OSError, ValueError, RuntimeError):+ return Falsedef is_legacy_uv_tool_install(python_executable: str | None = None) -> bool:@@ -789,9 +1279,19 @@ def build_upgrade_plan(if is_uv_tool_install(executable) and uv_binary:env = dict(base_env or os.environ)- vibe_bin_dir = get_current_vibe_bin_dir(vibe_path)- if vibe_bin_dir:- env["UV_TOOL_BIN_DIR"] = vibe_bin_dir+ atomic = None+ preflight_error = None+ if version is None:+ tool_dir, bin_dir, atomic = _staged_uv_environment(vibe_path)+ if atomic is None:+ preflight_error = "Cannot atomically upgrade uv installation: stable vibe launcher is unavailable"+ else:+ env["UV_TOOL_DIR"] = str(tool_dir)+ env["UV_TOOL_BIN_DIR"] = str(bin_dir)+ else:+ vibe_bin_dir = get_current_vibe_bin_dir(vibe_path)+ if vibe_bin_dir:+ env["UV_TOOL_BIN_DIR"] = vibe_bin_dircommand = [uv_binary, "tool", "install", package_spec]if not version:command.append("--upgrade")@@ -802,6 +1302,8 @@ def build_upgrade_plan(env=env,method="uv",rollback_to=rollback_to,+ activation=atomic,+ preflight_error=preflight_error,)command = [executable, "-m", "pip", "install"]