Skip to content

armgit / avibe

Public Imported from GitHub
0

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

feat(installer): give uninstall one owner in the installers (#2306)

Call White32b4ae95ba94
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index a221be163..c2335755a 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -434,6 +434,9 @@ jobs:
if (-not (Select-String -Path install-output.log -Pattern 'avibe-os installed successfully \(from custom package spec\)' -Quiet)) {
throw "Installer output missing custom package success message"
}
+ if (-not (Select-String -Path install-output.log -Pattern 'install.ps1))) -Uninstall' -SimpleMatch -Quiet)) {
+ throw "Installer output does not point to the uninstall owner"
+ }
# Exercise retirement through the real hardlink/copy launcher on
# Windows, not just mocked link fallbacks in the Python unit suite.
@@ -469,6 +472,81 @@ jobs:
throw "vibe version output missing expected marker"
}
+ # Windows PowerShell 5.1 is what `irm ... | iex` runs for most users, so
+ # the uninstall owner runs there, in both its file and script-block forms.
+ - name: Uninstall keeps user data and a purge needs confirmation
+ shell: pwsh
+ run: |
+ $avibeHome = Join-Path $env:USERPROFILE ".avibe"
+ $root = Join-Path $avibeHome "runtime\install-generations"
+ $stable = Join-Path $env:USERPROFILE ".local\bin\vibe.exe"
+ $peerBin = Join-Path $env:RUNNER_TEMP "peer-bin"
+ $foreignBin = Join-Path $env:RUNNER_TEMP "foreign-bin"
+ $peer = Join-Path $peerBin "vibe.exe"
+ $foreign = Join-Path $foreignBin "vibe.exe"
+ $markers = @((Join-Path $peerBin ".vibe.exe.avibe-generation"), (Join-Path (Split-Path $stable) ".vibe.exe.avibe-generation"))
+ $userData = Join-Path $avibeHome "user-data.txt"
+
+ function Invoke-Uninstall {
+ param([string]$Log, [string[]]$Options, [switch]$ScriptBlock)
+ # The installer resets PATH for this session, so restore the peers' directories.
+ $env:Path = "$peerBin;$foreignBin;$env:Path"
+ if ($ScriptBlock) {
+ # The documented one-line form, with the script read locally instead of downloaded.
+ # It must return to the session rather than exit it.
+ $command = "& ([scriptblock]::Create((Get-Content -Raw .\install.ps1))) -Uninstall $($Options -join ' '); 'session kept'; exit `$LASTEXITCODE"
+ powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Command $command *> $Log
+ } else {
+ powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File .\install.ps1 -Uninstall @Options *> $Log
+ }
+ $status = $LASTEXITCODE
+ Get-Content -LiteralPath $Log | Write-Host
+ return $status
+ }
+
+ function Install-WithPeers {
+ & .\install.ps1 *> reinstall.log
+ if ($LASTEXITCODE -ne 0) { Get-Content reinstall.log; throw "Reinstall failed" }
+ $generation = @(Get-ChildItem -LiteralPath $root -Directory)[0].FullName
+ # A second managed launcher: the cross-volume copy and its marker.
+ New-Item -ItemType Directory -Force -Path $peerBin, $foreignBin | Out-Null
+ Copy-Item -LiteralPath (Join-Path $generation "bin\vibe.exe") -Destination $peer -Force
+ Set-Content -LiteralPath $markers[0] -Value $generation -Encoding UTF8
+ # A vibe.exe the installer never placed.
+ Copy-Item -LiteralPath "$env:SystemRoot\System32\where.exe" -Destination $foreign -Force
+ Set-Content -LiteralPath $userData -Value "keep me"
+ }
+
+ Install-WithPeers
+ if (-not (Test-Path -LiteralPath $markers[1])) { throw "The installer did not record its launcher marker" }
+
+ $status = Invoke-Uninstall -Log uninstall.log
+ if ($status -ne 0) { throw "Uninstall exited with $status" }
+ foreach ($path in @($stable, $peer) + $markers + @($root)) {
+ if (Test-Path -LiteralPath $path) { throw "Uninstall left $path" }
+ }
+ if (-not (Test-Path -LiteralPath $foreign)) { throw "Uninstall removed a vibe.exe it did not install" }
+ if ((Get-Content -LiteralPath $userData) -ne "keep me") { throw "Uninstall did not keep the user's data" }
+ foreach ($expected in @("Stopped the Avibe service", "Your data was kept in:", "-Uninstall -Purge")) {
+ if (-not (Select-String -Path uninstall.log -Pattern $expected -SimpleMatch -Quiet)) { throw "Uninstall output is missing: $expected" }
+ }
+
+ Install-WithPeers
+ $status = Invoke-Uninstall -Log purge-refused.log -Options @("-Purge")
+ if ($status -ne 1) { throw "A purge that could not prompt exited with $status" }
+ foreach ($path in @($stable, $peer, $root, $userData)) {
+ if (-not (Test-Path -LiteralPath $path)) { throw "An unconfirmed purge removed $path" }
+ }
+ if (-not (Select-String -Path purge-refused.log -Pattern "Nothing was removed." -SimpleMatch -Quiet)) { throw "The refused purge did not say so" }
+
+ $status = Invoke-Uninstall -Log purge.log -Options @("-Purge", "-Yes") -ScriptBlock
+ if ($status -ne 0) { throw "A confirmed purge exited with $status" }
+ foreach ($path in @($stable, $peer, $root, $avibeHome) + $markers) {
+ if (Test-Path -LiteralPath $path) { throw "A confirmed purge left $path" }
+ }
+ if (-not (Test-Path -LiteralPath $foreign)) { throw "A purge removed a vibe.exe it did not install" }
+ if (-not (Select-String -Path purge.log -Pattern "session kept" -SimpleMatch -Quiet)) { throw "The script-block form ended the session" }
+
windows-control-ipc:
runs-on: windows-latest
needs: build-linux-artifacts
@@ -527,3 +605,9 @@ jobs:
# shows it, and like the steps above it needs no packaged Runtime.
- name: Verify Skill discovery keeps real directory identities
run: python -m pytest tests/test_managed_skills.py -q -k zero_directory_entry_identities
+
+ # install.ps1 carries its own copy of the stable-launcher rule, since its
+ # uninstall cannot rely on the installed Python. Pin it to the Python
+ # owner in both Windows PowerShell and PowerShell 7.
+ - name: Verify the installer's launcher rule matches the Python owner
+ run: python -m pytest tests/test_installer_uninstall.py -q -ra -k "rule_matches or dirs_match or powershell"
diff --git a/README.md b/README.md
index aa5af83c4..0f8ba4510 100644
--- a/README.md
+++ b/README.md
@@ -318,22 +318,16 @@ OpenCode may pause tool calls for approval unless `~/.config/opencode/opencode.j
## Uninstall
-The snippet removes the first `vibe` on your `PATH`. If `which -a vibe` lists more than one Avibe launcher, remove the others too.
+Run the installer with `--uninstall`. It stops Avibe, then removes every `vibe` command and install file it put on this machine. A `vibe` it did not install is left alone. Your settings, sessions, and other data in `~/.avibe` are kept:
```bash
-avibe_home="${AVIBE_HOME:-$HOME/.avibe}"
-avibe_home="${avibe_home/#\~/$HOME}"
-vibe_bin="$(command -v vibe)" # capture Avibe's launcher before uninstalling
-if "$vibe_bin" version 2>/dev/null | grep -Eq '^(avibe-os|vibe-remote) '; then
- "$vibe_bin" stop
-else
- echo "Skipping ${vibe_bin}: not Avibe's launcher"; vibe_bin=""
-fi
-uv tool uninstall avibe-os
-uv tool uninstall vibe-remote # legacy install
-[ -n "$vibe_bin" ] && rm -f "$vibe_bin" "$(dirname "$vibe_bin")/.vibe.avibe-generation"
-rm -rf "$avibe_home/runtime/install-generations"
-rm -rf "$avibe_home" ~/.vibe_remote
+bash -o pipefail -c 'curl -fsSL https://avibe.bot/install.sh | bash -s -- --uninstall'
+```
+
+To delete your data too, add `--purge`. It lists everything it will delete and asks before deleting. **Deleted data cannot be recovered.** Where no terminal can answer, it also needs `--yes`.
+
+```bash
+bash -o pipefail -c 'curl -fsSL https://avibe.bot/install.sh | bash -s -- --uninstall --purge'
```
---
diff --git a/README_ZH.md b/README_ZH.md
index 27ce809ba..7262cd334 100644
--- a/README_ZH.md
+++ b/README_ZH.md
@@ -318,22 +318,16 @@ bash -o pipefail -c 'curl -fsSL https://opencode.ai/install | bash'
## 卸载
-这段命令只删除 `PATH` 上排在最前面的 `vibe`。如果 `which -a vibe` 列出了不止一个 Avibe 启动器,其余的也要一并删掉。
+带上 `--uninstall` 运行安装脚本。它会先停止 Avibe,再删除它在这台机器上装的所有 `vibe` 命令和安装文件;不是它装的 `vibe` 不会动。`~/.avibe` 里的设置、会话和其他数据都会保留:
```bash
-avibe_home="${AVIBE_HOME:-$HOME/.avibe}"
-avibe_home="${avibe_home/#\~/$HOME}"
-vibe_bin="$(command -v vibe)" # 卸载前先记下 Avibe 的启动器
-if "$vibe_bin" version 2>/dev/null | grep -Eq '^(avibe-os|vibe-remote) '; then
- "$vibe_bin" stop
-else
- echo "跳过 ${vibe_bin}:不是 Avibe 的启动器"; vibe_bin=""
-fi
-uv tool uninstall avibe-os
-uv tool uninstall vibe-remote # 旧版安装
-[ -n "$vibe_bin" ] && rm -f "$vibe_bin" "$(dirname "$vibe_bin")/.vibe.avibe-generation"
-rm -rf "$avibe_home/runtime/install-generations"
-rm -rf "$avibe_home" ~/.vibe_remote
+bash -o pipefail -c 'curl -fsSL https://avibe.bot/install.sh | bash -s -- --uninstall'
+```
+
+如果连数据也要删,加上 `--purge`。它会先列出要删除的全部内容,确认后才删。**删除的数据无法恢复。** 没有终端可以回答确认时,还需要加 `--yes`。
+
+```bash
+bash -o pipefail -c 'curl -fsSL https://avibe.bot/install.sh | bash -s -- --uninstall --purge'
```
---
diff --git a/docs/INSTALL_FOR_AI.md b/docs/INSTALL_FOR_AI.md
index a16138b8b..650836e51 100644
--- a/docs/INSTALL_FOR_AI.md
+++ b/docs/INSTALL_FOR_AI.md
@@ -191,20 +191,24 @@ does not need an IM chat to complete this smoke test.
## Uninstall
-Only run this if the user asks to remove Avibe. It removes the first `vibe` on `PATH`; if `which -a vibe` lists more than one Avibe launcher, remove the others too:
+Only run this if the user asks to remove Avibe. The installer owns uninstall: it stops the service, then removes every `vibe` launcher and install file it placed. It never touches a `vibe` it did not install, and it keeps the user's data (`~/.avibe`, and the legacy `~/.vibe_remote`):
```bash
-avibe_home="${AVIBE_HOME:-$HOME/.avibe}"
-avibe_home="${avibe_home/#\~/$HOME}"
-vibe_bin="$(command -v vibe)" # capture Avibe's launcher before uninstalling
-if "$vibe_bin" version 2>/dev/null | grep -Eq '^(avibe-os|vibe-remote) '; then
- "$vibe_bin" stop
-else
- echo "Skipping ${vibe_bin}: not Avibe's launcher"; vibe_bin=""
-fi
-uv tool uninstall avibe-os
-uv tool uninstall vibe-remote # legacy install
-[ -n "$vibe_bin" ] && rm -f "$vibe_bin" "$(dirname "$vibe_bin")/.vibe.avibe-generation"
-rm -rf "$avibe_home/runtime/install-generations"
-rm -rf "$avibe_home" ~/.vibe_remote
+bash -o pipefail -c 'curl -fsSL https://avibe.bot/install.sh | bash -s -- --uninstall'
+```
+
+Windows PowerShell:
+
+```powershell
+& ([scriptblock]::Create((irm https://raw.githubusercontent.com/avibe-bot/avibe/master/install.ps1))) -Uninstall
+```
+
+Delete the user's data too only when they explicitly ask for it. It cannot be recovered, so confirm with the user first. It deletes only real directories: for a home reached through a link it removes the link and reports what it points to, which the user can delete by hand. The purge lists everything it deletes and asks on the terminal; without one, as in an agent shell, it refuses unless `--yes` (PowerShell: `-Yes`) is added:
+
+```bash
+bash -o pipefail -c 'curl -fsSL https://avibe.bot/install.sh | bash -s -- --uninstall --purge'
+```
+
+```powershell
+& ([scriptblock]::Create((irm https://raw.githubusercontent.com/avibe-bot/avibe/master/install.ps1))) -Uninstall -Purge
```
diff --git a/docs/INSTALL_FOR_AI_ZH.md b/docs/INSTALL_FOR_AI_ZH.md
index 7325dbc95..084081a68 100644
--- a/docs/INSTALL_FOR_AI_ZH.md
+++ b/docs/INSTALL_FOR_AI_ZH.md
@@ -166,20 +166,24 @@ vibe doctor
## 卸载
-只有用户明确要删除 Avibe 时才运行。它只删除 `PATH` 上排在最前面的 `vibe`;如果 `which -a vibe` 列出了不止一个 Avibe 启动器,其余的也要一并删掉:
+只有用户明确要删除 Avibe 时才运行。卸载由安装脚本负责:它先停止服务,再删除它放置的所有 `vibe` 启动器和安装文件;不是它装的 `vibe` 不会动,用户数据(`~/.avibe` 和旧版的 `~/.vibe_remote`)会保留:
```bash
-avibe_home="${AVIBE_HOME:-$HOME/.avibe}"
-avibe_home="${avibe_home/#\~/$HOME}"
-vibe_bin="$(command -v vibe)" # 卸载前先记下 Avibe 的启动器
-if "$vibe_bin" version 2>/dev/null | grep -Eq '^(avibe-os|vibe-remote) '; then
- "$vibe_bin" stop
-else
- echo "跳过 ${vibe_bin}:不是 Avibe 的启动器"; vibe_bin=""
-fi
-uv tool uninstall avibe-os
-uv tool uninstall vibe-remote # 旧版安装
-[ -n "$vibe_bin" ] && rm -f "$vibe_bin" "$(dirname "$vibe_bin")/.vibe.avibe-generation"
-rm -rf "$avibe_home/runtime/install-generations"
-rm -rf "$avibe_home" ~/.vibe_remote
+bash -o pipefail -c 'curl -fsSL https://avibe.bot/install.sh | bash -s -- --uninstall'
+```
+
+Windows PowerShell:
+
+```powershell
+& ([scriptblock]::Create((irm https://raw.githubusercontent.com/avibe-bot/avibe/master/install.ps1))) -Uninstall
+```
+
+只有用户明确要求时,才连同数据一起删除。数据删除后无法恢复,所以先和用户确认。清除只删除真实目录:如果 home 是通过链接到达的,只删除链接本身,并告诉用户它指向哪里,由用户自行删除。清除时会先列出要删除的全部内容,并在终端上确认;没有终端时(比如 agent 的 shell),不加 `--yes`(PowerShell 为 `-Yes`)就不会执行:
+
+```bash
+bash -o pipefail -c 'curl -fsSL https://avibe.bot/install.sh | bash -s -- --uninstall --purge'
+```
+
+```powershell
+& ([scriptblock]::Create((irm https://raw.githubusercontent.com/avibe-bot/avibe/master/install.ps1))) -Uninstall -Purge
```
diff --git a/install.ps1 b/install.ps1
index 001b68e1b..35635d46c 100644
--- a/install.ps1
+++ b/install.ps1
@@ -1,8 +1,21 @@
# Avibe Installation Script for Windows
# Usage: irm https://raw.githubusercontent.com/avibe-bot/avibe/master/install.ps1 | iex
+# Uninstall, keeping your data:
+# & ([scriptblock]::Create((irm https://raw.githubusercontent.com/avibe-bot/avibe/master/install.ps1))) -Uninstall
+# Add -Purge to also delete your data. A session that cannot prompt also needs -Yes.
+# The uninstaller never deletes through a link; anything behind a link is reported for you to remove.
#
# Prerequisites: None! uv will be installed automatically and manages Python for you.
+param(
+ # Remove Avibe itself and keep your data.
+ [switch]$Uninstall,
+ # With -Uninstall, also delete your Avibe data. This cannot be undone.
+ [switch]$Purge,
+ # Confirm -Purge without a prompt.
+ [switch]$Yes
+)
+
$ErrorActionPreference = "Stop"
# Configuration
@@ -14,6 +27,11 @@ $NODE_MINIMUM_REQUIREMENT = "20.19+ or 22.12+"
# GitHub; earlier uv fetches it from GitHub only. Get-UvPythonInstallMirror
# gives earlier uv the CDN for the install step unless the user chose a source.
$ASTRAL_PYTHON_INSTALL_MIRROR = "https://releases.astral.sh/github/python-build-standalone/releases/download"
+$PUBLIC_INSTALL_SCRIPT_URL = "https://raw.githubusercontent.com/$REPO/master/install.ps1"
+# The fixed stable-launcher locations launcher discovery checks beside PATH and
+# uv's configured tool bin. Keep in step with INSTALLER_LAUNCHER_DIRS in
+# vibe/upgrade.py; entries without a drive do not apply on Windows.
+$INSTALLER_LAUNCHER_DIRS = @("~/.local/bin", "~/bin", "/usr/local/bin", "/opt/homebrew/bin")
function Write-Banner {
Write-Host @"
@@ -421,9 +439,7 @@ function Activate-LegacyInstallCandidate {
return @{ Success = $true; ExitCode = 0; Output = "" }
}
-function Invoke-UvToolInstallAttempt {
- param([string[]]$Arguments, [string]$PythonInstallMirror)
-
+function Get-RuntimeHome {
$defaultHome = Join-Path $env:USERPROFILE ".avibe"
$legacyHome = Join-Path $env:USERPROFILE ".vibe_remote"
$runtimeHome = if ($env:AVIBE_HOME) {
@@ -435,7 +451,13 @@ function Invoke-UvToolInstallAttempt {
} else {
$defaultHome
}
- $runtimeHome = Resolve-InstallPath $runtimeHome
+ return Resolve-InstallPath $runtimeHome
+}
+
+function Invoke-UvToolInstallAttempt {
+ param([string[]]$Arguments, [string]$PythonInstallMirror)
+
+ $runtimeHome = Get-RuntimeHome
$generationRoot = Join-Path (Join-Path $runtimeHome "runtime\install-generations") ([Guid]::NewGuid().ToString("N"))
# 3.0.13 identifies uv-managed installs from the executable's /uv/tools/
# path. Keep that released contract in every generation so the old binary
@@ -702,7 +724,6 @@ function Prepare-ShowRuntime {
}
function Write-NextSteps {
- $stableBin = Get-StableBinDirectory
Write-Host ""
Write-Host "Installation complete!" -ForegroundColor Green
Write-Host ""
@@ -718,20 +739,703 @@ function Write-NextSteps {
Write-Host " vibe doctor - Run diagnostics"
Write-Host ""
Write-Host "Uninstall:" -ForegroundColor Blue
- 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 -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 " $(Get-UninstallCommand)"
+ Write-Host " Add -Purge to also delete your data in $(Get-RuntimeHome). This cannot be undone."
Write-Host ""
Write-Host "Documentation:" -ForegroundColor Blue
Write-Host " https://github.com/$REPO#readme"
Write-Host ""
}
+# The one-line uninstall command for this runtime home, with any options
+# appended. AVIBE_HOME is repeated when it chose the home.
+function Get-UninstallCommand {
+ param([string[]]$Options)
+
+ $command = "& ([scriptblock]::Create((irm $PUBLIC_INSTALL_SCRIPT_URL))) -Uninstall"
+ if ($Options) {
+ $command += " " + ($Options -join " ")
+ }
+ if ($env:AVIBE_HOME) {
+ $command = "`$env:AVIBE_HOME = '$((Get-RuntimeHome).Replace("'", "''"))'; $command"
+ }
+ return $command
+}
+
+# The installer owns uninstall. It runs outside Avibe, so nothing it deletes is
+# in use by itself, and it cannot rely on the installed Python, which may come
+# from any earlier release or be broken. It therefore carries its own copy of
+# the launcher rule in vibe.upgrade.managed_stable_launchers; tests pin the
+# copies to the same cases.
+
+function Test-FullyQualifiedPath {
+ param([string]$Path)
+ return $Path -match '^[A-Za-z]:[\\/]' -or $Path -match '^[\\/]{2}[^\\/]'
+}
+
+# The directory entry itself, even for a link whose target is gone.
+function Get-DirectoryEntry {
+ param([string]$Path)
+
+ $parent = Split-Path -Parent $Path
+ $leaf = Split-Path -Leaf $Path
+ if (-not $parent -or -not (Test-Path -LiteralPath $parent -PathType Container)) {
+ return $null
+ }
+ return Get-ChildItem -LiteralPath $parent -Force -Filter $leaf -ErrorAction SilentlyContinue |
+ Where-Object { $_.Name -eq $leaf } |
+ Select-Object -First 1
+}
+
+# Follow a path's chain of symbolic links and junctions at the leaf, as far as
+# it goes, to the entry it finally names.
+function Resolve-LinkChain {
+ param([string]$Path)
+
+ for ($depth = 0; $depth -lt 20; $depth++) {
+ $entry = Get-DirectoryEntry $Path
+ if (-not $entry -or $entry.LinkType -notin @("SymbolicLink", "Junction")) {
+ break
+ }
+ $target = @($entry.Target)[0]
+ if (-not $target) {
+ break
+ }
+ $target = $target -replace '^\\(\\\?|\?\?)\\', ''
+ if (-not [System.IO.Path]::IsPathRooted($target)) {
+ $target = Join-Path (Split-Path -Parent $Path) $target
+ }
+ $Path = [System.IO.Path]::GetFullPath($target)
+ }
+ return $Path
+}
+
+function Test-PathInGenerationRoot {
+ param([string]$Path, [string]$Root)
+
+ $prefix = [System.IO.Path]::GetFullPath($Root).TrimEnd("\", "/") + "\"
+ return [System.IO.Path]::GetFullPath($Path).StartsWith($prefix, [System.StringComparison]::OrdinalIgnoreCase)
+}
+
+# A file's SHA-256, or $null when it cannot be read. .NET computes it, so no
+# module has to load in a session whose module path came from another shell.
+function Get-ContentHash {
+ param([string]$Path)
+
+ try {
+ $sha256 = [System.Security.Cryptography.SHA256]::Create()
+ try {
+ return [System.BitConverter]::ToString($sha256.ComputeHash([System.IO.File]::ReadAllBytes($Path)))
+ } finally {
+ $sha256.Dispose()
+ }
+ } catch {
+ return $null
+ }
+}
+
+# Whether deleting install-generations would break this launcher: it resolves
+# into the root, or it is a hard link or copy of a generation's launcher.
+# vibe.upgrade._launcher_generation recognizes the same shapes, but it moves a
+# launcher only into a recognized installation, and a copy only with its
+# marker. A launcher missing either would still break, so it goes too.
+function Test-LauncherUsesInstallGenerations {
+ param([string]$Launcher, [string]$Root)
+
+ if (Test-PathInGenerationRoot (Resolve-LinkChain $Launcher) $Root) {
+ return $true
+ }
+ if (-not (Test-Path -LiteralPath $Launcher -PathType Leaf)) {
+ return $false
+ }
+ $hash = Get-ContentHash $Launcher
+ if (-not $hash) {
+ return $false
+ }
+ foreach ($generation in @(Get-ChildItem -LiteralPath $Root -Directory -Force -ErrorAction SilentlyContinue)) {
+ $exported = Join-Path $generation.FullName "bin\vibe.exe"
+ if ((Test-Path -LiteralPath $exported -PathType Leaf) -and (Get-ContentHash $exported) -eq $hash) {
+ return $true
+ }
+ }
+ return $false
+}
+
+# Each distinct directory launcher discovery searches: PATH, uv's configured
+# tool bin, then the installer's fixed locations.
+function Get-LauncherSearchDirectories {
+ $seen = @{}
+ foreach ($directory in @($env:Path -split ";") + @($env:UV_TOOL_BIN_DIR) + $INSTALLER_LAUNCHER_DIRS) {
+ if (-not $directory) {
+ continue
+ }
+ if ($directory -eq "~" -or $directory.StartsWith("~\") -or $directory.StartsWith("~/")) {
+ $directory = Resolve-InstallPath $directory
+ }
+ if (-not (Test-FullyQualifiedPath $directory)) {
+ continue
+ }
+ $directory = [System.IO.Path]::GetFullPath($directory).TrimEnd("\", "/")
+ $key = $directory.ToLowerInvariant()
+ if ($seen.ContainsKey($key)) {
+ continue
+ }
+ $seen[$key] = $true
+ $directory
+ }
+}
+
+# Each launcher this home's uninstall removes. Like the Python owner, it never
+# counts one inside a uv tool environment or the generation root.
+function Get-ManagedLaunchers {
+ param([string]$Root)
+
+ foreach ($directory in Get-LauncherSearchDirectories) {
+ $launcher = Join-Path $directory "vibe.exe"
+ if ($launcher.Replace("\", "/").ToLowerInvariant().Contains("/uv/tools/") -or
+ (Test-PathInGenerationRoot $launcher $Root) -or -not (Get-DirectoryEntry $launcher)) {
+ continue
+ }
+ if (Test-LauncherUsesInstallGenerations $launcher $Root) {
+ $launcher
+ }
+ }
+}
+
+# Each launcher marker the uninstall leaves without a purpose: one beside a
+# launcher it removes, or one naming a generation in the root it deletes.
+function Get-StaleLauncherMarkers {
+ param([string]$Root, [string[]]$Launchers)
+
+ foreach ($directory in Get-LauncherSearchDirectories) {
+ $marker = Join-Path $directory ".vibe.exe.avibe-generation"
+ if (-not (Test-Path -LiteralPath $marker -PathType Leaf)) {
+ continue
+ }
+ $marked = "$(Get-Content -LiteralPath $marker -Raw -ErrorAction SilentlyContinue)".Trim([char]0xFEFF, " ", "`r", "`n", "`t")
+ if (($Launchers -contains (Join-Path $directory "vibe.exe")) -or
+ ((Test-FullyQualifiedPath $marked) -and (Test-PathInGenerationRoot $marked $Root))) {
+ $marker
+ }
+ }
+}
+
+function Get-UvCommand {
+ $command = Get-Command uv -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
+ if ($command) {
+ return $command.Source
+ }
+ $fallback = Join-Path $env:USERPROFILE ".local\bin\uv.exe"
+ if (Test-Path -LiteralPath $fallback -PathType Leaf) {
+ return $fallback
+ }
+ return $null
+}
+
+function Get-UvToolDirectory {
+ param([string]$Uv)
+
+ if ($Uv) {
+ $result = Invoke-NativeCommand -FilePath $Uv -Arguments @("tool", "dir")
+ if ($result.Success -and $result.Stdout) {
+ return $result.Stdout
+ }
+ }
+ if ($env:UV_TOOL_DIR) {
+ return $env:UV_TOOL_DIR
+ }
+ return Join-Path $env:APPDATA "uv\tools"
+}
+
+# Whether uv's own uninstall of a tool removes only that tool's launchers. uv
+# deletes every launcher path its receipt records, even one that another tool,
+# such as a different vibe, has replaced since.
+function Test-UvToolOwnsItsLaunchers {
+ param([string]$Environment)
+
+ $receipt = Join-Path $Environment "uv-receipt.toml"
+ if (-not (Test-Path -LiteralPath $receipt -PathType Leaf)) {
+ return $true
+ }
+ $pattern = 'install-path\s*=\s*(?:"((?:[^"\\]|\\.)*)"|''([^'']*)'')'
+ foreach ($match in [regex]::Matches((Get-Content -LiteralPath $receipt -Raw), $pattern)) {
+ $path = if ($match.Groups[1].Success) { [regex]::Unescape($match.Groups[1].Value) } else { $match.Groups[2].Value }
+ if (-not (Get-DirectoryEntry $path)) {
+ continue
+ }
+ if (Test-PathInGenerationRoot (Resolve-LinkChain $path) $Environment) {
+ continue
+ }
+ $own = Join-Path $Environment ("Scripts\" + (Split-Path -Leaf $path))
+ $hash = Get-ContentHash $path
+ if ($hash -and (Test-Path -LiteralPath $own -PathType Leaf) -and $hash -eq (Get-ContentHash $own)) {
+ continue
+ }
+ return $false
+ }
+ return $true
+}
+
+# Each live process that removal must wait for, as "pid command": one that runs
+# from, or names on its command line, a path about to be deleted. The
+# uninstaller's own process tree never counts.
+function Get-BlockingProcesses {
+ param([string[]]$Paths)
+
+ $needles = New-Object System.Collections.Generic.List[string]
+ foreach ($path in $Paths) {
+ if (-not $path) {
+ continue
+ }
+ foreach ($form in @([System.IO.Path]::GetFullPath($path).TrimEnd("\", "/"), (Resolve-LinkChain $path).TrimEnd("\", "/"))) {
+ if (-not $needles.Contains($form)) {
+ $needles.Add($form)
+ }
+ }
+ }
+ # CIM is the one source of command lines; without it nothing is removed.
+ try {
+ $processes = @(Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object {
+ [pscustomobject]@{ Id = [int]$_.ProcessId; Parent = [int]$_.ParentProcessId; Text = "$($_.ExecutablePath) $($_.CommandLine)" }
+ })
+ } catch {
+ $processes = @()
+ }
+ if ($processes.Count -eq 0) {
+ throw "no process list is available"
+ }
+ $parents = @{}
+ foreach ($process in $processes) {
+ $parents[$process.Id] = $process.Parent
+ }
+ $own = @{}
+ for ($id = $PID; $id -and -not $own.ContainsKey($id); $id = $parents[$id]) {
+ $own[$id] = $true
+ }
+ $descendants = @{ $PID = $true }
+ do {
+ $grew = $false
+ foreach ($process in $processes) {
+ if (-not $descendants.ContainsKey($process.Id) -and $descendants.ContainsKey($process.Parent)) {
+ $descendants[$process.Id] = $true
+ $grew = $true
+ }
+ }
+ } while ($grew)
+ foreach ($process in $processes) {
+ if ($own.ContainsKey($process.Id) -or $descendants.ContainsKey($process.Id)) {
+ continue
+ }
+ $text = $process.Text + " "
+ foreach ($needle in $needles) {
+ $at = $text.IndexOf($needle, [System.StringComparison]::OrdinalIgnoreCase)
+ $found = $false
+ while ($at -ge 0 -and -not $found) {
+ $found = $text[$at + $needle.Length] -in @([char]'\', [char]'/', [char]'"', [char]' ')
+ $at = $text.IndexOf($needle, $at + 1, [System.StringComparison]::OrdinalIgnoreCase)
+ }
+ if ($found) {
+ "$($process.Id) $($process.Text.Trim())"
+ break
+ }
+ }
+ }
+}
+
+# Ask an installed Avibe to stop its service; the first that succeeds is enough.
+function Stop-AvibeService {
+ param([string[]]$Launchers, [string]$RuntimeHome)
+
+ foreach ($launcher in $Launchers) {
+ if (-not (Test-Path -LiteralPath $launcher -PathType Leaf)) {
+ continue
+ }
+ $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 $(if (Test-Path -LiteralPath $RuntimeHome -PathType Container) { $RuntimeHome } else { [System.IO.Path]::GetTempPath() })
+ try {
+ $result = Invoke-NativeCommand -FilePath $launcher -Arguments @("stop")
+ } 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 ($result.Success) {
+ return $true
+ }
+ Write-Warning "'$launcher stop' failed: $($result.Output)"
+ }
+ return $false
+}
+
+# Whether this uninstall is for the default home. Global uv tool installs and
+# a legacy ~\.vibe_remote directory belong to no chosen AVIBE_HOME, so only the
+# default home's uninstall removes them.
+function Test-UninstallingDefaultHome {
+ param([string]$RuntimeHome)
+
+ return -not $env:AVIBE_HOME -or $RuntimeHome.TrimEnd("\", "/") -eq (Join-Path $env:USERPROFILE ".avibe")
+}
+
+# This home's data paths: for the default home both default names, and for an
+# explicit AVIBE_HOME that home alone.
+function Get-AvibeDataDirectories {
+ param([string]$RuntimeHome)
+
+ $candidates = if (Test-UninstallingDefaultHome $RuntimeHome) {
+ @((Join-Path $env:USERPROFILE ".avibe"), (Join-Path $env:USERPROFILE ".vibe_remote"))
+ } else {
+ @($RuntimeHome.TrimEnd("\", "/"))
+ }
+ # Only a directory or a link is a home; anything else under those names is not Avibe's.
+ foreach ($candidate in $candidates) {
+ $entry = Get-DirectoryEntry $candidate
+ if ($entry -and ($entry.PSIsContainer -or ($entry.Attributes -band [System.IO.FileAttributes]::ReparsePoint))) {
+ $candidate
+ }
+ }
+}
+
+function Test-IsLink {
+ param([string]$Path)
+
+ $entry = Get-DirectoryEntry $Path
+ return [bool]($entry -and ($entry.Attributes -band [System.IO.FileAttributes]::ReparsePoint))
+}
+
+# A data path for the user, naming what a link points to.
+function Get-DataPathDescription {
+ param([string]$Path)
+
+ $entry = Get-DirectoryEntry $Path
+ if ($entry -and ($entry.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) {
+ return "$Path -> $(@($entry.Target)[0])"
+ }
+ return $Path
+}
+
+# Whether an explicit AVIBE_HOME shows it is an Avibe home. The installer and
+# Avibe both create its runtime directory, and uninstall keeps it until a purge.
+function Test-LooksLikeAvibeHome {
+ param([string]$Path)
+
+ $entry = Get-DirectoryEntry (Join-Path $Path "runtime")
+ return $entry -and $entry.PSIsContainer -and -not ($entry.Attributes -band [System.IO.FileAttributes]::ReparsePoint)
+}
+
+# Whether deleting a directory would delete the user's profile or the root of
+# a drive or share.
+function Test-PathHoldsHome {
+ param([string]$Path)
+
+ $full = [System.IO.Path]::GetFullPath($Path).TrimEnd("\", "/")
+ $root = "$([System.IO.Path]::GetPathRoot($full))".TrimEnd("\", "/")
+ if (-not $root -or $root.Equals($full, [System.StringComparison]::OrdinalIgnoreCase)) {
+ return $true
+ }
+ foreach ($profile in @($env:USERPROFILE, (Resolve-LinkChain $env:USERPROFILE))) {
+ $profile = [System.IO.Path]::GetFullPath($profile).TrimEnd("\", "/")
+ if ($profile.Equals($full, [System.StringComparison]::OrdinalIgnoreCase) -or
+ $profile.StartsWith($full + "\", [System.StringComparison]::OrdinalIgnoreCase)) {
+ return $true
+ }
+ }
+ return $false
+}
+
+# Delete a file or directory tree. A link is removed itself and never followed:
+# Windows PowerShell's Remove-Item -Recurse deletes what a directory link names.
+function Remove-InstalledPath {
+ param([string]$Path)
+
+ $entry = Get-DirectoryEntry $Path
+ if (-not $entry) {
+ return
+ }
+ if ($entry.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {
+ if ($entry.PSIsContainer) { [System.IO.Directory]::Delete($entry.FullName, $false) } else { [System.IO.File]::Delete($entry.FullName) }
+ return
+ }
+ if ($entry.PSIsContainer) {
+ try {
+ # This recursion deletes a link it meets and does not follow it.
+ [System.IO.Directory]::Delete($entry.FullName, $true)
+ } catch {
+ # A read-only entry stops it; clear each attribute on the way down.
+ foreach ($child in @(Get-ChildItem -LiteralPath $entry.FullName -Force)) {
+ Remove-InstalledPath $child.FullName
+ }
+ [System.IO.Directory]::Delete($entry.FullName, $false)
+ }
+ } else {
+ $entry.Attributes = [System.IO.FileAttributes]::Normal
+ [System.IO.File]::Delete($entry.FullName)
+ }
+}
+
+function Remove-ReportedPath {
+ param([string]$Path, [string]$Verb = "Removed")
+
+ try {
+ Remove-InstalledPath $Path
+ } catch {
+ # Reported below from what is left on disk.
+ }
+ if (Get-DirectoryEntry $Path) {
+ Write-Warning "Could not remove $Path"
+ return $false
+ }
+ Write-Success "$Verb $Path"
+ return $true
+}
+
+function Confirm-Purge {
+ if ($Yes) {
+ return $true
+ }
+ $answer = $null
+ if ([Environment]::UserInteractive -and -not [Console]::IsInputRedirected) {
+ try {
+ $answer = Read-Host "Delete all of this permanently? [y/N]"
+ } catch {
+ # A -NonInteractive session refuses to prompt.
+ }
+ }
+ if ($null -eq $answer) {
+ Write-Warning "A purge needs confirmation, and this session cannot prompt. Nothing was removed."
+ Write-Host " To confirm without a prompt, run:"
+ Write-Host " $(Get-UninstallCommand -Options @('-Purge', '-Yes'))"
+ return $false
+ }
+ if ($answer -match '^(y|yes)$') {
+ return $true
+ }
+ Write-Info "Purge cancelled. Nothing was removed."
+ return $false
+}
+
+# Name a vibe left on PATH, other than a managed launcher that could not be
+# removed, which is reported as such.
+function Write-RemainingVibe {
+ param([string[]]$Launchers)
+
+ $remaining = Get-Command vibe -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1
+ if ($remaining -and $Launchers -notcontains $remaining.Source) {
+ Write-Info "Another vibe command remains at $($remaining.Source). This installer did not install it, so it was left in place."
+ Write-Host " If it is a pip install of Avibe, remove it with that pip: pip uninstall avibe-os vibe-remote"
+ }
+}
+
+function Write-KeptData {
+ param([string[]]$Data)
+
+ if (-not $Data) {
+ return
+ }
+ Write-Host ""
+ Write-Host "Your data was kept in:"
+ foreach ($item in $Data) { Write-Host " $(Get-DataPathDescription $item)" }
+ Write-Host "To delete it too (this cannot be undone), run:"
+ Write-Host " $(Get-UninstallCommand -Options @('-Purge'))"
+}
+
+function Uninstall-Avibe {
+ # Every step reports its own failure; one failure must not hide the rest.
+ $ErrorActionPreference = "Continue"
+ $runtimeHome = Get-RuntimeHome
+ $root = Join-Path $runtimeHome "runtime\install-generations"
+ $launchers = @(Get-ManagedLaunchers $root)
+ $markers = @(Get-StaleLauncherMarkers -Root $root -Launchers $launchers)
+ $uv = Get-UvCommand
+ $toolDirectory = Get-UvToolDirectory $uv
+ $presentUvTools = @($PACKAGE_NAME, "vibe-remote" | Where-Object { Test-Path -LiteralPath (Join-Path $toolDirectory $_) -PathType Container })
+ $uvTools = @(if (Test-UninstallingDefaultHome $runtimeHome) { $presentUvTools })
+ $data = @(Get-AvibeDataDirectories $runtimeHome)
+ $doomedData = @()
+ $unlinkedData = @()
+ $failed = $false
+
+ Write-Info "Uninstalling Avibe for $runtimeHome"
+ if ($uvTools.Count -eq 0) {
+ foreach ($package in $presentUvTools) {
+ Write-Info "Leaving the uv tool install $package in place: it belongs to no AVIBE_HOME, so only an uninstall of the default home removes it"
+ }
+ }
+ if ($launchers.Count -eq 0 -and $markers.Count -eq 0 -and $uvTools.Count -eq 0 -and -not (Get-DirectoryEntry $root) -and
+ (-not $Purge -or $data.Count -eq 0)) {
+ Write-Info "No Avibe installation was found, so nothing was removed."
+ Write-RemainingVibe
+ Write-KeptData $data
+ return 0
+ }
+ if ($Purge) {
+ # A purge never deletes through a link. It deletes real directories
+ # and removes a link itself, keeping whatever the link points to.
+ foreach ($item in $data) {
+ if (Test-IsLink $item) {
+ $unlinkedData += $item
+ } elseif (-not (Test-UninstallingDefaultHome $runtimeHome) -and -not (Test-LooksLikeAvibeHome $item)) {
+ Write-Warning "Refusing to purge ${item}: it has no runtime directory, so it does not look like an Avibe home. Nothing was removed."
+ return 1
+ } elseif (Test-PathHoldsHome $item) {
+ Write-Warning "Refusing to purge ${item}: it holds your user profile. Nothing was removed."
+ return 1
+ } else {
+ $doomedData += $item
+ }
+ }
+ $listing = @($launchers) + @($markers)
+ if (Get-DirectoryEntry $root) { $listing += $root }
+ $listing += @($uvTools | ForEach-Object { "$(Join-Path $toolDirectory $_) (uv tool $_)" })
+ $listing += @($doomedData | ForEach-Object { "$_ (your Avibe data)" })
+ Write-Host ""
+ if ($listing.Count -gt 0) {
+ Write-Host "This permanently deletes:" -ForegroundColor Yellow
+ foreach ($item in $listing) { Write-Host " $item" }
+ }
+ if ($unlinkedData.Count -gt 0) {
+ Write-Host "It removes these links, not what they point to:" -ForegroundColor Yellow
+ foreach ($item in $unlinkedData) { Write-Host " $(Get-DataPathDescription $item)" }
+ }
+ Write-Host ""
+ if (-not (Confirm-Purge)) {
+ return 1
+ }
+ }
+
+ # Nothing is removed while Avibe could still be using it: first ask it to
+ # stop, then check that no process runs from or names what goes next.
+ $stoppers = @($launchers) + @($uvTools | ForEach-Object { Join-Path $toolDirectory "$_\Scripts\vibe.exe" })
+ $doomed = @($launchers) + @($root) + @($uvTools | ForEach-Object { Join-Path $toolDirectory $_ }) + @($doomedData)
+ $stopped = Stop-AvibeService -Launchers $stoppers -RuntimeHome $runtimeHome
+ if ($stopped) {
+ Write-Success "Stopped the Avibe service"
+ } else {
+ # Without a confirmed stop, anything still using the home counts too.
+ $doomed += $runtimeHome
+ }
+ # Children of a stopped service can take a moment to exit.
+ for ($attempt = 1; $attempt -le 6; $attempt++) {
+ try {
+ $running = @(Get-BlockingProcesses -Paths $doomed)
+ } catch {
+ Write-Warning "No process list is available here, so the uninstall cannot confirm that nothing still uses what it deletes. Nothing was removed."
+ return 1
+ }
+ if ($running.Count -eq 0 -or $attempt -eq 6) {
+ break
+ }
+ Start-Sleep -Seconds 1
+ }
+ if ($running.Count -gt 0) {
+ Write-Warning "These processes still use what the uninstall would delete, so nothing was removed:"
+ foreach ($item in $running) {
+ Write-Host " pid $($item.Substring(0, [Math]::Min(200, $item.Length)))"
+ }
+ Write-Host " Stop them, then run the uninstall again."
+ return 1
+ }
+ if (-not $stopped) {
+ if ($stoppers.Count -gt 0) {
+ Write-Warning "The installed vibe could not stop the service. No process runs from or names what the uninstall deletes or this home."
+ } else {
+ Write-Info "No installed vibe could be asked to stop the service. No process runs from or names what the uninstall deletes or this home."
+ }
+ Write-Host " Processes outside those paths, such as a managed OpenCode server, could not be confirmed stopped."
+ Write-Host " To check, run: Get-Process opencode, cloudflared -ErrorAction SilentlyContinue"
+ }
+
+ foreach ($item in $launchers + $markers) {
+ if (-not (Remove-ReportedPath $item)) { $failed = $true }
+ }
+ if (Get-DirectoryEntry $root) {
+ # The root goes only when the home and every step below it are real
+ # directories: never through a link, never any other kind of entry.
+ # Nor while a managed launcher it serves is still there to dangle.
+ $left = $null
+ $behindLink = $root
+ foreach ($step in @($runtimeHome.TrimEnd("\", "/"), (Join-Path $runtimeHome "runtime"), $root)) {
+ $entry = Get-DirectoryEntry $step
+ if ($entry -and ($entry.Attributes -band [System.IO.FileAttributes]::ReparsePoint)) {
+ $left = "$(Get-DataPathDescription $step), and the uninstaller never deletes through a link"
+ $behindLink = (Resolve-LinkChain $step) + $root.Substring($step.Length)
+ break
+ }
+ if (-not $entry -or -not $entry.PSIsContainer) {
+ $left = "$step is not a directory, and the uninstaller deletes only real directories"
+ break
+ }
+ }
+ foreach ($launcher in $launchers) {
+ if (-not $left -and (Get-DirectoryEntry $launcher)) {
+ $left = "$launcher could not be removed, and removing the root would leave it dangling"
+ }
+ }
+ if ($left) {
+ Write-Warning "Left $root in place: $left."
+ Write-Host " If it is yours, remove it with: Remove-Item -Recurse -Force -LiteralPath '$($behindLink.Replace("'", "''"))'"
+ $failed = $true
+ } elseif (-not (Remove-ReportedPath $root)) {
+ $failed = $true
+ }
+ }
+ foreach ($package in $uvTools) {
+ $environment = Join-Path $toolDirectory $package
+ if (-not $uv) {
+ Write-Warning "uv was not found, so the uv tool install $package at $environment was left in place"
+ $failed = $true
+ } elseif (-not (Test-UvToolOwnsItsLaunchers $environment)) {
+ Write-Warning "Left the uv tool install $package in place: a launcher it records now belongs to another program, which 'uv tool uninstall $package' would delete"
+ $failed = $true
+ } elseif ((Invoke-NativeCommand -FilePath $uv -Arguments @("tool", "uninstall", $package)).Success -or
+ -not (Test-Path -LiteralPath $environment)) {
+ Write-Success "Removed the uv tool install $package"
+ } else {
+ Write-Warning "Could not remove the uv tool install $package; run 'uv tool uninstall $package'"
+ $failed = $true
+ }
+ }
+ if ($Purge) {
+ $keptTargets = @($unlinkedData | ForEach-Object { Get-DataPathDescription $_ })
+ foreach ($item in $unlinkedData) {
+ if (-not (Remove-ReportedPath $item -Verb "Removed the link")) { $failed = $true }
+ }
+ foreach ($item in $doomedData) {
+ if (-not (Remove-ReportedPath $item -Verb "Deleted")) { $failed = $true }
+ }
+ foreach ($item in $keptTargets) {
+ $link, $target = $item -split ' -> ', 2
+ if (-not [System.IO.Path]::IsPathRooted($target)) {
+ $target = Join-Path (Split-Path -Parent $link) $target
+ }
+ if (Get-DirectoryEntry $target) {
+ Write-Info "Kept $target, which $link pointed to. Delete it by hand if it is yours."
+ }
+ }
+ }
+
+ Write-RemainingVibe -Launchers $launchers
+
+ Write-Host ""
+ if ($failed) {
+ Write-Warning "Avibe was not completely removed. See the warnings above."
+ } elseif ($doomedData.Count -gt 0) {
+ Write-Success "Avibe and its data were removed."
+ } else {
+ Write-Success "Avibe was removed."
+ }
+ if (-not $Purge) {
+ Write-KeptData $data
+ }
+ if ($failed) { return 1 }
+ return 0
+}
+
# Main installation flow
function Main {
Write-Banner
@@ -758,5 +1462,29 @@ function Main {
Write-NextSteps
}
+# Each option means one thing, so a purge is never implied by another.
+$optionError = if ($Purge -and -not $Uninstall) {
+ "-Purge deletes your data during an uninstall; use it with -Uninstall"
+} elseif ($Yes -and -not $Purge) {
+ "-Yes confirms a purge; use it with -Uninstall -Purge"
+}
+if ($Uninstall -or $optionError) {
+ Write-Banner
+ if ($optionError) {
+ Write-Host "[ERROR] " -ForegroundColor Red -NoNewline
+ Write-Host $optionError
+ $uninstallStatus = 1
+ } else {
+ $uninstallStatus = Uninstall-Avibe | Select-Object -Last 1
+ }
+ # A script file reports its status; a script block run at the prompt must
+ # not close the user's session, so it leaves the status in LASTEXITCODE.
+ if ($MyInvocation.MyCommand.Path) {
+ exit $uninstallStatus
+ }
+ $global:LASTEXITCODE = $uninstallStatus
+ return
+}
+
# Run main
Main
diff --git a/install.sh b/install.sh
index 7a7bbeb0b..98195cac9 100755
--- a/install.sh
+++ b/install.sh
@@ -1,6 +1,10 @@
#!/usr/bin/env bash
# Avibe Installation Script
# Usage: bash -o pipefail -c 'curl -fsSL https://avibe.bot/install.sh | bash -s -- --launch'
+# Uninstall, keeping your data:
+# bash -o pipefail -c 'curl -fsSL https://avibe.bot/install.sh | bash -s -- --uninstall'
+# Add --purge to also delete your data; without a terminal to confirm on, a purge also needs --yes.
+# The uninstaller never deletes through a link; anything behind a link is reported for you to remove.
#
# Prerequisites: None! uv will be installed automatically and manages Python for you.
@@ -22,6 +26,11 @@ VIBE_TOOL_BIN_DIR=""
# A root install has one supported stable launcher, whatever PATH order the
# shell happens to have. Upgrades keep every other managed launcher in step.
ROOT_TOOL_BIN_DIR="/usr/local/bin"
+# The fixed stable-launcher locations this installer chooses from, in order.
+# Launcher discovery checks them beside PATH and uv's configured tool bin.
+# Keep in step with INSTALLER_LAUNCHER_DIRS in vibe/upgrade.py.
+INSTALLER_LAUNCHER_DIRS=("$HOME/.local/bin" "$HOME/bin" "/usr/local/bin" "/opt/homebrew/bin")
+PUBLIC_INSTALL_SCRIPT_URL="https://avibe.bot/install.sh"
VIBE_CANDIDATE_BIN_PATH=""
# uv 0.10.8 and later fetch managed Python from Astral's CDN and fall back to
# GitHub; earlier uv fetches it from GitHub only. uv_python_install_mirror
@@ -29,6 +38,8 @@ VIBE_CANDIDATE_BIN_PATH=""
ASTRAL_PYTHON_INSTALL_MIRROR="https://releases.astral.sh/github/python-build-standalone/releases/download"
UV_INSTALL_PYTHON_MIRROR=""
LAUNCH_AFTER_INSTALL=""
+PURGE_USER_DATA=""
+ASSUME_YES=""
AVIBE_LAUNCHED=""
ORIGINAL_PATH="$PATH"
if [ -n "${AVIBE_HOME:-}" ]; then
@@ -44,6 +55,10 @@ elif [ -e "$HOME/.vibe_remote" ] || [ -L "$HOME/.vibe_remote" ]; then
else
AVIBE_RUNTIME_HOME="$HOME/.avibe"
fi
+# A trailing separator makes a link read as the directory it names.
+while [ "${#AVIBE_RUNTIME_HOME}" -gt 1 ] && [ "${AVIBE_RUNTIME_HOME%/}" != "$AVIBE_RUNTIME_HOME" ]; do
+ AVIBE_RUNTIME_HOME="${AVIBE_RUNTIME_HOME%/}"
+done
REMOTE_ACCESS_PAIRING_KEY=""
REMOTE_ACCESS_PAIRED=""
@@ -220,14 +235,7 @@ choose_tool_bin_dir() {
done
IFS="$old_ifs"
- local preferred_dirs=(
- "$HOME/.local/bin"
- "$HOME/bin"
- "/usr/local/bin"
- "/opt/homebrew/bin"
- )
-
- for dir in "${preferred_dirs[@]}"; do
+ for dir in "${INSTALLER_LAUNCHER_DIRS[@]}"; do
if is_absolute_dir "$dir" && launcher_destination_is_available "$dir" && ensure_writable_dir "$dir"; then
echo "$dir"
return 0
@@ -858,15 +866,685 @@ launch_vibe() {
success "Avibe launched"
}
+# Print the one-line uninstall command for this runtime home, with any options
+# appended. Like the install command, it fails when the download does, and it
+# repeats AVIBE_HOME when that chose the home.
+uninstall_command() {
+ local home_prefix=""
+ if [ -n "${AVIBE_HOME:-}" ]; then
+ home_prefix="AVIBE_HOME=$(printf '%q' "$AVIBE_RUNTIME_HOME") "
+ fi
+ printf "%sbash -o pipefail -c 'curl -fsSL %s | bash -s -- --uninstall%s'\n" \
+ "$home_prefix" "$PUBLIC_INSTALL_SCRIPT_URL" "${*:+ $*}"
+}
+
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'
+ echo " $(uninstall_command)"
+ echo " Add --purge to also delete your data in $AVIBE_RUNTIME_HOME. This cannot be undone."
+}
+
+# The installer owns uninstall. It runs outside Avibe, so nothing it deletes is
+# in use by itself, and it cannot rely on the installed Python, which may come
+# from any earlier release or be broken. It therefore carries its own copy of
+# the launcher rule in vibe.upgrade.managed_stable_launchers; tests pin the
+# two to the same cases.
+
+install_generations_root() {
+ printf '%s\n' "$AVIBE_RUNTIME_HOME/runtime/install-generations"
+}
+
+# Print an absolute path with its deepest existing ancestor made physical, so a
+# path through symlinks or "..", even into something already deleted, compares
+# by prefix.
+physical_path() {
+ local path="$1"
+ local rest=""
+ local dir=""
+
+ while [ -n "$path" ] && [ "$path" != "/" ]; do
+ path="${path%/}"
+ if dir="$(cd -P -- "$path" 2>/dev/null && pwd -P)"; then
+ printf '%s%s\n' "${dir%/}" "$rest"
+ return 0
+ fi
+ rest="/${path##*/}$rest"
+ path="${path%/*}"
+ done
+ printf '%s\n' "${rest:-/}"
+}
+
+path_in_generation_root() {
+ local root=""
+ root="$(physical_path "$(install_generations_root)")"
+ case "$(physical_path "$1")" in
+ "$root"/?*) return 0 ;;
+ esac
+ return 1
+}
+
+# Whether deleting install-generations would break this launcher: it resolves
+# into the root, or it is a hard link or copy of a generation's launcher.
+# vibe.upgrade._launcher_generation recognizes the same shapes, but it moves a
+# launcher only into a recognized installation, and a copy only with its
+# marker. A launcher missing either would still break, so it goes too.
+launcher_uses_install_generations() {
+ local launcher="$1"
+ local exported=""
+
+ if path_in_generation_root "$(resolve_binary_path "$launcher")"; then
+ return 0
+ fi
+ [ -f "$launcher" ] || return 1
+ for exported in "$(install_generations_root)"/*/bin/vibe; do
+ if [ -f "$exported" ] && { [ "$launcher" -ef "$exported" ] || cmp -s "$launcher" "$exported" 2>/dev/null; }; then
+ return 0
+ fi
+ done
+ return 1
+}
+
+# Print each distinct directory launcher discovery searches: PATH, uv's
+# configured tool bin, then the installer's fixed locations.
+launcher_search_dirs() {
+ local dir=""
+ local key=""
+ local seen=":"
+ local uv_tool_bin="${UV_TOOL_BIN_DIR:-}"
+ local old_ifs="$IFS"
+ local -a dirs=()
+
+ IFS=":"
+ for dir in $ORIGINAL_PATH; do
+ dirs+=("$dir")
+ done
+ IFS="$old_ifs"
+ dirs+=("${uv_tool_bin/#\~/$HOME}" "${INSTALLER_LAUNCHER_DIRS[@]}")
+
+ for dir in "${dirs[@]}"; do
+ dir="${dir%/}"
+ is_absolute_dir "$dir" || continue
+ key="$(physical_path "$dir")"
+ case "$seen" in
+ *":$key:"*) continue ;;
+ esac
+ seen="$seen$key:"
+ printf '%s\n' "$dir"
+ done
+}
+
+# Print each launcher this home's uninstall removes. Like the Python owner, it
+# never counts one inside a uv tool environment or the generation root.
+managed_launchers() {
+ local dir=""
+ local launcher=""
+
+ while IFS= read -r dir; do
+ launcher="$dir/vibe"
+ case "$launcher" in
+ */uv/tools/*) continue ;;
+ esac
+ if { [ -e "$launcher" ] || [ -L "$launcher" ]; } && ! path_in_generation_root "$launcher" &&
+ launcher_uses_install_generations "$launcher"; then
+ printf '%s\n' "$launcher"
+ fi
+ done < <(launcher_search_dirs)
+}
+
+# Print each launcher marker the uninstall leaves without a purpose: one beside
+# a launcher it removes, or one naming a generation in the root it deletes.
+stale_launcher_markers() {
+ local dir=""
+ local marker=""
+ local marked=""
+ local bom=$'\xef\xbb\xbf'
+
+ while IFS= read -r dir; do
+ marker="$dir/.vibe.avibe-generation"
+ [ -f "$marker" ] || continue
+ marked="$(cat "$marker" 2>/dev/null)"
+ marked="${marked#"$bom"}"
+ marked="${marked%$'\r'}"
+ if printf '%s\n' "$@" | grep -Fqx -- "$dir/vibe" ||
+ { is_absolute_dir "$marked" && path_in_generation_root "$marked"; }; then
+ printf '%s\n' "$marker"
+ fi
+ done < <(launcher_search_dirs)
+}
+
+find_uv() {
+ local candidate=""
+
+ for candidate in "$(PATH="$ORIGINAL_PATH" command -v uv 2>/dev/null || true)" "$HOME/.local/bin/uv" "$HOME/.cargo/bin/uv"; do
+ if [ -n "$candidate" ] && [ -x "$candidate" ]; then
+ printf '%s\n' "$candidate"
+ return 0
+ fi
+ done
+ return 1
+}
+
+uv_tool_dir() {
+ local uv="$1"
+ local dir=""
+
+ if [ -n "$uv" ]; then
+ dir="$("$uv" tool dir 2>/dev/null || true)"
+ fi
+ printf '%s\n' "${dir:-${UV_TOOL_DIR:-${XDG_DATA_HOME:-$HOME/.local/share}/uv/tools}}"
+}
+
+# Whether uv's own uninstall of a tool removes only that tool's launchers. uv
+# deletes every launcher path its receipt records, even one that another tool,
+# such as a different `vibe`, has replaced since.
+uv_tool_owns_its_launchers() {
+ local environment="$1"
+ local environment_root=""
+ local path=""
+
+ [ -f "$environment/uv-receipt.toml" ] || return 0
+ environment_root="$(physical_path "$environment")"
+ while IFS= read -r path; do
+ [ -n "$path" ] || continue
+ { [ -e "$path" ] || [ -L "$path" ]; } || continue
+ case "$(physical_path "$(resolve_binary_path "$path")")" in
+ "$environment_root"/*) continue ;;
+ esac
+ if cmp -s "$path" "$environment/bin/${path##*/}" 2>/dev/null; then
+ continue
+ fi
+ return 1
+ done < <(grep -oE "install-path = (\"[^\"]*\"|'[^']*')" "$environment/uv-receipt.toml" 2>/dev/null |
+ sed -e "s/^install-path = [\"']//" -e "s/[\"']\$//")
+ return 0
+}
+
+# Print "pid ppid command" for every process, or nothing when neither ps nor
+# /proc can list them.
+process_table() {
+ local dir=""
+ local key=""
+ local value=""
+ local ppid=""
+
+ # Linux also names each executable, which a relative argv[0] hides.
+ if [ -r /proc/self/cmdline ]; then
+ for dir in /proc/[0-9]*; do
+ [ -r "$dir/cmdline" ] || continue
+ ppid=0
+ while IFS=$'\t' read -r key value; do
+ if [ "$key" = "PPid:" ]; then
+ ppid="$value"
+ break
+ fi
+ done 2>/dev/null < "$dir/status"
+ value="$(readlink "$dir/exe" 2>/dev/null)"
+ printf '%s %s %s%s\n' "${dir#/proc/}" "$ppid" "$(tr '\0' ' ' < "$dir/cmdline" 2>/dev/null)" \
+ "${value:+ ($value)}"
+ done
+ return 0
+ fi
+ ps -eo pid=,ppid=,args= 2>/dev/null
+}
+
+# Print each live process that removal must wait for, as "pid command": one
+# that runs from, or names on its command line, a path about to be deleted (the
+# arguments). The uninstaller's own process tree never counts. Returns 2 when
+# nothing can list processes.
+blocking_processes() {
+ local path=""
+ local physical=""
+ local paths=""
+ local table=""
+
+ for path in "$@"; do
+ [ -n "$path" ] || continue
+ paths="$paths$path"$'\n'
+ physical="$(physical_path "$path")"
+ if [ "$physical" != "$path" ]; then
+ paths="$paths$physical"$'\n'
+ fi
+ done
+ table="$(process_table)"
+ if [ -z "$table" ]; then
+ return 2
+ fi
+ printf '%s\n' "$table" | AVIBE_UNINSTALL_PATHS="$paths" AVIBE_UNINSTALL_SELF="$$" awk '
+ BEGIN {
+ count = split(ENVIRON["AVIBE_UNINSTALL_PATHS"], paths, "\n")
+ self = ENVIRON["AVIBE_UNINSTALL_SELF"]
+ }
+ {
+ pid = $1
+ parent[pid] = $2
+ $1 = ""; $2 = ""
+ sub(/^ +/, "")
+ command[pid] = $0
+ order[++processes] = pid
+ }
+ END {
+ for (pid = self; pid != "" && pid != "0" && !(pid in own); pid = parent[pid]) own[pid] = 1
+ descendants[self] = 1
+ do {
+ grew = 0
+ for (i = 1; i <= processes; i++) {
+ pid = order[i]
+ if (!(pid in descendants) && (parent[pid] in descendants)) { descendants[pid] = 1; grew = 1 }
+ }
+ } while (grew)
+ for (i = 1; i <= processes; i++) {
+ pid = order[i]
+ if ((pid in own) || (pid in descendants)) continue
+ text = command[pid] " "
+ for (j = 1; j <= count; j++) {
+ if (paths[j] != "" && (index(text, paths[j] "/") || index(text, paths[j] " ") || index(text, paths[j] ")"))) {
+ print pid " " command[pid]
+ break
+ }
+ }
+ }
+ }'
+}
+
+# Ask an installed Avibe to stop its service; the first that succeeds is enough.
+stop_avibe_service() {
+ local launcher=""
+ local output=""
+
+ for launcher in "$@"; do
+ [ -x "$launcher" ] || continue
+ if output="$(
+ cd "$AVIBE_RUNTIME_HOME" 2>/dev/null || cd /
+ env -u PYTHONPATH -u PYTHONHOME AVIBE_HOME="$AVIBE_RUNTIME_HOME" "$launcher" stop 2>&1
+ )"; then
+ return 0
+ fi
+ warn "'$launcher stop' failed${output:+: $(printf '%s\n' "$output" | tail -n 3)}"
+ done
+ return 1
+}
+
+# Whether this uninstall is for the default home. Global uv tool installs and
+# a legacy ~/.vibe_remote directory belong to no chosen AVIBE_HOME, so only the
+# default home's uninstall removes them.
+uninstalling_default_home() {
+ [ -z "${AVIBE_HOME:-}" ] || [ "$AVIBE_RUNTIME_HOME" = "$HOME/.avibe" ]
+}
+
+# Print this home's data paths: for the default home both default names, and
+# for an explicit AVIBE_HOME that home alone. Only a directory or a link is a
+# home; anything else under those names is not Avibe's.
+avibe_data_directories() {
+ local path=""
+ local -a paths=("$AVIBE_RUNTIME_HOME")
+
+ if uninstalling_default_home; then
+ paths=("$HOME/.avibe" "$HOME/.vibe_remote")
+ fi
+ for path in "${paths[@]}"; do
+ if [ -L "$path" ] || [ -d "$path" ]; then
+ printf '%s\n' "$path"
+ fi
+ done
+}
+
+# Print a data path for the user, naming what a link points to.
+describe_data_path() {
+ if [ -L "$1" ]; then
+ printf '%s -> %s\n' "$1" "$(readlink "$1" 2>/dev/null)"
+ else
+ printf '%s\n' "$1"
+ fi
+}
+
+# Print the physical path of <base>[/<rel>] for deleting it, when that cannot
+# go through a link: <base> itself and every step below it are real
+# directories, whatever its ancestors are. Every directory the uninstaller
+# deletes goes through here. Returns 2 with the resolved path when the spelled
+# path goes through a link, and 1 when it names no directory.
+verified_directory() {
+ local base="$1"
+ local rel="${2:-}"
+ local logical=""
+ local parent=""
+ local actual=""
+
+ logical="$(CDPATH= cd -L -- "$base" 2>/dev/null && pwd -L)" || return 1
+ parent="$(CDPATH= cd -P -- "$(dirname -- "$logical")" 2>/dev/null && pwd -P)" || return 1
+ actual="$(CDPATH= cd -P -- "$base${rel:+/$rel}" 2>/dev/null && pwd -P)" || return 1
+ printf '%s\n' "$actual"
+ [ "$actual" = "${parent%/}/$(basename -- "$logical")${rel:+/$rel}" ] || return 2
+}
+
+# Whether an explicit AVIBE_HOME shows it is an Avibe home. The installer and
+# Avibe both create its runtime directory, and uninstall keeps it until a purge.
+looks_like_avibe_home() {
+ [ -d "$1/runtime" ] && [ ! -L "$1/runtime" ]
+}
+
+# Whether deleting a directory would delete the user's home or the filesystem.
+path_holds_home() {
+ local target=""
+
+ target="$(physical_path "$1")"
+ [ "$target" = "/" ] && return 0
+ case "$(physical_path "$HOME")/" in
+ "$target"/*) return 0 ;;
+ esac
+ return 1
+}
+
+confirm_purge() {
+ local answer=""
+
+ if [ "$ASSUME_YES" = "1" ]; then
+ return 0
+ fi
+ # Read the terminal itself: under curl | bash, standard input is the script.
+ if ! { true < /dev/tty; } 2>/dev/null; then
+ warn "A purge needs confirmation, and no terminal is available. Nothing was removed."
+ echo " To confirm without a terminal, run:"
+ echo " $(uninstall_command --purge --yes)"
+ return 1
+ fi
+ printf 'Delete all of this permanently? [y/N] ' > /dev/tty
+ read -r answer < /dev/tty || answer=""
+ case "$answer" in
+ y|Y|yes|YES|Yes) return 0 ;;
+ esac
+ info "Purge cancelled. Nothing was removed."
+ return 1
+}
+
+# Name a vibe left on PATH, other than a managed launcher (the arguments) that
+# could not be removed, which is reported as such. This installer never uses
+# pip, so an Avibe console script there came from a pip install, which only
+# that pip can remove.
+report_remaining_vibe() {
+ local remaining=""
+ local interpreter=""
+ local launcher=""
+
+ remaining="$(PATH="$ORIGINAL_PATH" command -v vibe 2>/dev/null || true)"
+ if [ -z "$remaining" ] || { [ ! -e "$remaining" ] && [ ! -L "$remaining" ]; }; then
+ return 0
+ fi
+ for launcher in "$@"; do
+ if [ "$launcher" = "$remaining" ]; then
+ return 0
+ fi
+ done
+ if ! is_avibe_launcher "$remaining"; then
+ info "Another vibe command remains at $remaining. This installer did not install it, so it was left in place."
+ return 0
+ fi
+ interpreter="$(head -n 1 "$remaining" 2>/dev/null)"
+ interpreter="${interpreter#\#!}"
+ case "$interpreter" in
+ /*" "*|"") interpreter="python3" ;;
+ /*) ;;
+ *) interpreter="python3" ;;
+ esac
+ info "An Avibe install that this installer did not make remains at $remaining, such as a pip install."
+ echo " Remove it with the Python that runs it: $interpreter -m pip uninstall avibe-os vibe-remote"
+}
+
+print_kept_data() {
+ local item=""
+
+ [ "$#" -gt 0 ] || return 0
+ echo ""
+ echo "Your data was kept in:"
+ for item in "$@"; do
+ echo " $(describe_data_path "$item")"
+ done
+ echo "To delete it too (this cannot be undone), run:"
+ echo " $(uninstall_command --purge)"
+}
+
+uninstall_avibe() {
+ # Every step reports its own failure; one failure must not hide the rest.
+ set +e
+ local root=""
+ local item=""
+ local uv=""
+ local tool_dir=""
+ local package=""
+ local failed=0
+ local -a launchers=()
+ local -a markers=()
+ local -a uv_tools=()
+ local -a data=()
+ local target=""
+ local -a doomed_data=()
+ local -a doomed_physical=()
+ local -a unlinked_data=()
+ local -a running=()
+
+ root="$(install_generations_root)"
+ while IFS= read -r item; do launchers+=("$item"); done < <(managed_launchers)
+ while IFS= read -r item; do markers+=("$item"); done < <(stale_launcher_markers "${launchers[@]}")
+ local -a other_uv_tools=()
+ uv="$(find_uv || true)"
+ tool_dir="$(uv_tool_dir "$uv")"
+ for package in "$PACKAGE_NAME" vibe-remote; do
+ if [ ! -d "$tool_dir/$package" ]; then
+ continue
+ elif uninstalling_default_home; then
+ uv_tools+=("$package")
+ else
+ other_uv_tools+=("$package")
+ fi
+ done
+ while IFS= read -r item; do data+=("$item"); done < <(avibe_data_directories)
+
+ info "Uninstalling Avibe for $AVIBE_RUNTIME_HOME"
+ for package in "${other_uv_tools[@]}"; do
+ info "Leaving the uv tool install $package in place: it belongs to no AVIBE_HOME, so only an uninstall of the default home removes it"
+ done
+ if [ "${#launchers[@]}" -eq 0 ] && [ "${#markers[@]}" -eq 0 ] && [ "${#uv_tools[@]}" -eq 0 ] &&
+ [ ! -e "$root" ] && [ ! -L "$root" ] && { [ "$PURGE_USER_DATA" != "1" ] || [ "${#data[@]}" -eq 0 ]; }; then
+ info "No Avibe installation was found, so nothing was removed."
+ report_remaining_vibe
+ print_kept_data "${data[@]}"
+ return 0
+ fi
+ if [ "$PURGE_USER_DATA" = "1" ]; then
+ # A purge never deletes through a link. It deletes real directories
+ # and removes a link itself, keeping whatever the link points to.
+ for item in "${data[@]}"; do
+ if [ -L "$item" ]; then
+ unlinked_data+=("$item")
+ elif ! uninstalling_default_home && ! looks_like_avibe_home "$item"; then
+ warn "Refusing to purge $item: it has no runtime directory, so it does not look like an Avibe home. Nothing was removed."
+ return 1
+ elif path_holds_home "$item"; then
+ warn "Refusing to purge $item: it holds your home directory. Nothing was removed."
+ return 1
+ elif ! target="$(verified_directory "$item")"; then
+ warn "Refusing to purge $item: it resolves through a link to ${target:-nothing}. Nothing was removed."
+ echo " Name the home without the link, or delete what it names by hand if it is yours."
+ return 1
+ else
+ doomed_data+=("$item")
+ doomed_physical+=("$target")
+ fi
+ done
+ local -a listing=("${launchers[@]}" "${markers[@]}")
+ if [ -e "$root" ] || [ -L "$root" ]; then listing+=("$root"); fi
+ for item in "${uv_tools[@]}"; do listing+=("$tool_dir/$item (uv tool $item)"); done
+ for item in "${doomed_data[@]}"; do listing+=("$item (your Avibe data)"); done
+ echo ""
+ if [ "${#listing[@]}" -gt 0 ]; then
+ echo -e "${YELLOW}This permanently deletes:${NC}"
+ for item in "${listing[@]}"; do echo " $item"; done
+ fi
+ if [ "${#unlinked_data[@]}" -gt 0 ]; then
+ echo -e "${YELLOW}It removes these links, not what they point to:${NC}"
+ for item in "${unlinked_data[@]}"; do echo " $(describe_data_path "$item")"; done
+ fi
+ echo ""
+ confirm_purge || return 1
+ fi
+
+ # Nothing is removed while Avibe could still be using it: first ask it to
+ # stop, then check that no process runs from or names what goes next.
+ local stopped=0
+ local -a stoppers=("${launchers[@]}")
+ local -a doomed=("${launchers[@]}" "$root")
+ for package in "${uv_tools[@]}"; do
+ stoppers+=("$tool_dir/$package/bin/vibe")
+ doomed+=("$tool_dir/$package")
+ done
+ doomed+=("${doomed_data[@]}")
+ if stop_avibe_service "${stoppers[@]}"; then
+ stopped=1
+ success "Stopped the Avibe service"
+ else
+ # Without a confirmed stop, anything still using the home counts too.
+ doomed+=("$AVIBE_RUNTIME_HOME")
+ fi
+ # Children of a stopped service can take a moment to exit.
+ local attempt=""
+ local blocking=""
+ local listed=1
+ for attempt in 1 2 3 4 5 6; do
+ running=()
+ blocking="$(blocking_processes "${doomed[@]}")" || listed=0
+ while IFS= read -r item; do
+ if [ -n "$item" ]; then running+=("$item"); fi
+ done <<< "$blocking"
+ if [ "${#running[@]}" -eq 0 ] || [ "$attempt" = 6 ]; then
+ break
+ fi
+ sleep 1
+ done
+ if [ "${#running[@]}" -gt 0 ]; then
+ warn "These processes still use what the uninstall would delete, so nothing was removed:"
+ for item in "${running[@]}"; do
+ echo " pid ${item:0:200}"
+ done
+ echo " Stop them, then run the uninstall again."
+ return 1
+ fi
+ if [ "$listed" != "1" ]; then
+ warn "No process list is available here, so the uninstall cannot confirm that nothing still uses what it deletes. Nothing was removed."
+ return 1
+ fi
+ if [ "$stopped" != "1" ]; then
+ if [ "${#stoppers[@]}" -gt 0 ]; then
+ warn "The installed vibe could not stop the service. No process runs from or names what the uninstall deletes or this home."
+ else
+ info "No installed vibe could be asked to stop the service. No process runs from or names what the uninstall deletes or this home."
+ fi
+ echo " Processes outside those paths, such as a managed OpenCode server, could not be confirmed stopped."
+ echo " To check, run: ps -eo pid,args | grep -E 'opencode serve|cloudflared'"
+ fi
+
+ for item in "${launchers[@]}" "${markers[@]}"; do
+ if rm -f -- "$item" 2>/dev/null && [ ! -e "$item" ] && [ ! -L "$item" ]; then
+ success "Removed $item"
+ else
+ warn "Could not remove $item"
+ failed=1
+ fi
+ done
+ if [ -e "$root" ] || [ -L "$root" ]; then
+ # The root goes only when the home and every step below it are real
+ # directories: never through a link, never any other kind of entry.
+ # Nor while a managed launcher it serves is still there to dangle.
+ local step=""
+ local left=""
+ for step in "$AVIBE_RUNTIME_HOME" "$AVIBE_RUNTIME_HOME/runtime" "$root"; do
+ if [ -L "$step" ]; then
+ left="$step is a link to $(readlink "$step" 2>/dev/null), and the uninstaller never deletes through a link"
+ break
+ elif [ ! -d "$step" ]; then
+ left="$step is not a directory, and the uninstaller deletes only real directories"
+ break
+ fi
+ done
+ local physical_root=""
+ if [ -z "$left" ] && ! physical_root="$(verified_directory "$AVIBE_RUNTIME_HOME" runtime/install-generations)"; then
+ left="$root resolves through a link to ${physical_root:-nothing}, and the uninstaller never deletes through a link"
+ fi
+ for step in "${launchers[@]}"; do
+ if [ -z "$left" ] && { [ -e "$step" ] || [ -L "$step" ]; }; then
+ left="$step could not be removed, and removing the root would leave it dangling"
+ fi
+ done
+ if [ -n "$left" ]; then
+ warn "Left $root in place: $left."
+ echo " If it is yours, remove it with: rm -rf -- $(printf '%q' "$(physical_path "$root")")"
+ failed=1
+ elif rm -rf -- "$physical_root" 2>/dev/null && [ ! -e "$physical_root" ] && [ ! -L "$physical_root" ]; then
+ success "Removed $root"
+ else
+ warn "Could not remove $root"
+ failed=1
+ fi
+ fi
+ for package in "${uv_tools[@]}"; do
+ if [ -z "$uv" ]; then
+ warn "uv was not found, so the uv tool install $package at $tool_dir/$package was left in place"
+ failed=1
+ elif ! uv_tool_owns_its_launchers "$tool_dir/$package"; then
+ warn "Left the uv tool install $package in place: a launcher it records now belongs to another program, which 'uv tool uninstall $package' would delete"
+ failed=1
+ elif "$uv" tool uninstall "$package" >/dev/null 2>&1 || [ ! -d "$tool_dir/$package" ]; then
+ success "Removed the uv tool install $package"
+ else
+ warn "Could not remove the uv tool install $package; run 'uv tool uninstall $package'"
+ failed=1
+ fi
+ done
+
+ if [ "$PURGE_USER_DATA" = "1" ]; then
+ local -a kept_targets=()
+ for item in "${unlinked_data[@]}"; do
+ target="$(readlink "$item" 2>/dev/null)"
+ case "$target" in
+ /*) ;;
+ *) target="$(dirname -- "$item")/$target" ;;
+ esac
+ kept_targets+=("$item -> $target")
+ if rm -f -- "$item" 2>/dev/null && [ ! -e "$item" ] && [ ! -L "$item" ]; then
+ success "Removed the link $item"
+ else
+ warn "Could not remove the link $item"
+ failed=1
+ fi
+ done
+ local index=0
+ for index in "${!doomed_data[@]}"; do
+ item="${doomed_physical[$index]}"
+ if rm -rf -- "$item" 2>/dev/null && [ ! -e "$item" ] && [ ! -L "$item" ]; then
+ success "Deleted ${doomed_data[$index]}"
+ else
+ warn "Could not delete ${doomed_data[$index]}"
+ failed=1
+ fi
+ done
+ for item in "${kept_targets[@]}"; do
+ if [ -e "${item#* -> }" ] || [ -L "${item#* -> }" ]; then
+ info "Kept ${item#* -> }, which ${item%% -> *} pointed to. Delete it by hand if it is yours."
+ fi
+ done
+ fi
+
+ report_remaining_vibe "${launchers[@]}"
+
+ echo ""
+ if [ "$failed" -ne 0 ]; then
+ warn "Avibe was not completely removed. See the warnings above."
+ elif [ "${#doomed_data[@]}" -gt 0 ]; then
+ success "Avibe and its data were removed."
+ else
+ success "Avibe was removed."
+ fi
+ if [ "$PURGE_USER_DATA" != "1" ]; then
+ print_kept_data "${data[@]}"
+ fi
+ return "$failed"
}
# Print next steps
@@ -962,13 +1640,31 @@ main() {
unset AVIBE_PAIRING_KEY
local arg
+ local uninstall=""
for arg in "$@"; do
case "$arg" in
--launch) LAUNCH_AFTER_INSTALL="1" ;;
+ --uninstall) uninstall="1" ;;
+ --purge) PURGE_USER_DATA="1" ;;
+ --yes) ASSUME_YES="1" ;;
*) error "Unsupported installer option: $arg" ;;
esac
done
-
+ # Each option means one thing, so a purge is never implied by another.
+ if [ "$uninstall" = "1" ] && [ "$LAUNCH_AFTER_INSTALL" = "1" ]; then
+ error "--launch cannot be combined with --uninstall"
+ fi
+ if [ "$PURGE_USER_DATA" = "1" ] && [ "$uninstall" != "1" ]; then
+ error "--purge deletes your data during an uninstall; use it with --uninstall"
+ fi
+ if [ "$ASSUME_YES" = "1" ] && [ "$PURGE_USER_DATA" != "1" ]; then
+ error "--yes confirms a purge; use it with --uninstall --purge"
+ fi
+ if [ "$uninstall" = "1" ]; then
+ uninstall_avibe
+ exit $?
+ fi
+
local os
os=$(detect_os)
info "Detected OS: $os"
diff --git a/tests/test_install_generation_retirement.py b/tests/test_install_generation_retirement.py
index 77b92c17b..5b080eb5f 100644
--- a/tests/test_install_generation_retirement.py
+++ b/tests/test_install_generation_retirement.py
@@ -39,7 +39,7 @@ def installation(tmp_path, monkeypatch):
def candidate(
root, name, *, layout="uv/tools", package="avibe-os",
- export_name="vibe", entry_name="vibe",
+ export_name="vibe", entry_name="vibe", copy_export=False,
):
generation = root / name
environment = generation / layout / package
@@ -50,7 +50,11 @@ def candidate(
(environment / "pyvenv.cfg").write_text("include-system-site-packages = false\n")
exported = generation / "bin" / export_name
exported.parent.mkdir()
- exported.symlink_to(target)
+ # uv links a tool's launcher on POSIX and copies it on Windows.
+ if copy_export:
+ shutil.copy2(target, exported)
+ else:
+ exported.symlink_to(target)
(environment / "uv-receipt.toml").write_text(
f'[tool]\nrequirements = [{{ name = "{package}" }}]\n'
f'entrypoints = [{{ name = {json.dumps(entry_name)}, install-path = {json.dumps(str(exported))} }}]\n',
diff --git a/tests/test_install_script.py b/tests/test_install_script.py
index cc8f6ab6a..dc11fe6b8 100644
--- a/tests/test_install_script.py
+++ b/tests/test_install_script.py
@@ -390,6 +390,10 @@ def test_install_script_keeps_vibe_available_on_current_path(tmp_path):
assert "Run 'vibe' to open the setup wizard" in install_result.stdout
assert "vibe remote - Set up remote Web UI access" in install_result.stdout
assert "export PATH=" not in install_result.stdout
+ # Uninstall has one owner, so the installer points to it, not to steps.
+ uninstall = install_result.stdout.split("Uninstall:", 1)[1].splitlines()[1]
+ assert "bash -o pipefail -c 'curl -fsSL https://avibe.bot/install.sh | bash -s -- --uninstall'" in uninstall
+ assert f"Add --purge to also delete your data in {home_dir / '.avibe'}." in install_result.stdout
assert version_result.returncode == 0, version_result.stdout + version_result.stderr
assert "avibe-os 9.9.9" in version_result.stdout
assert uv_log.read_text(encoding="utf-8")
@@ -936,7 +940,9 @@ def test_windows_installer_honors_configured_tool_bin_and_cross_volume_copy_fall
assert "function Resolve-InstallPath" in powershell
assert "function Get-LauncherState" in powershell
assert '$generationTools = Join-Path $generationRoot "uv\\tools"' in powershell
- assert "Get-Content -LiteralPath $marker" not in powershell
+ # Activation leaves marker interpretation to the Python owner; only the
+ # uninstall below reads a marker, to decide whether the marker itself goes.
+ assert "Get-Content -LiteralPath $marker" not in powershell.split("# The one-line uninstall command", 1)[0]
assert "function Get-GenerationPath" not in powershell
assert '$expanded.StartsWith("~\\")' in powershell
assert "$configured = $env:UV_TOOL_BIN_DIR" in powershell
@@ -977,36 +983,6 @@ def test_install_script_candidate_probes_ignore_python_path_overrides():
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()
diff --git a/tests/test_installer_uninstall.py b/tests/test_installer_uninstall.py
new file mode 100644
index 000000000..961b4f692
--- /dev/null
+++ b/tests/test_installer_uninstall.py
@@ -0,0 +1,997 @@
+"""The installers own uninstall (#2239).
+
+`install.sh --uninstall` and `install.ps1 -Uninstall` cannot rely on the
+installed Python, which may come from any earlier release or be broken, so each
+carries its own copy of the launcher rule in
+``vibe.upgrade.managed_stable_launchers``. The shared cases pin both copies to
+the Python rule; the rest exercise the POSIX owner end to end. The Windows owner
+runs end to end in the windows-install-smoke CI job.
+"""
+
+from __future__ import annotations
+
+import os
+import select
+import shlex
+import shutil
+import subprocess
+import sys
+import time
+from dataclasses import dataclass
+from pathlib import Path
+
+import pytest
+
+from tests.test_install_generation_retirement import candidate
+from vibe import upgrade
+
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+INSTALL_SCRIPT = REPO_ROOT / "install.sh"
+INSTALL_POWERSHELL = REPO_ROOT / "install.ps1"
+WINDOWS = os.name == "nt"
+LAUNCHER = "vibe.exe" if WINDOWS else "vibe"
+MARKER = f".{LAUNCHER}.avibe-generation"
+SYSTEM_PATH = (
+ [os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32")] if WINDOWS else ["/usr/bin", "/bin"]
+)
+
+
+@dataclass
+class Layout:
+ tmp: Path
+ home: Path
+ avibe_home: Path
+ root: Path
+ current: Path
+ older: Path
+ path_dirs: list[Path]
+ uv_tool_bin: Path
+ installer_dir: Path
+ elsewhere: Path
+
+ @property
+ def search_path(self) -> str:
+ return os.pathsep.join([*map(str, self.path_dirs), *SYSTEM_PATH])
+
+ def env(self, **extra: str) -> dict[str, str]:
+ # HOME alone selects the default home, as for most users.
+ return {
+ "HOME": str(self.home),
+ "PATH": self.search_path,
+ "UV_TOOL_BIN_DIR": str(self.uv_tool_bin),
+ "LC_ALL": "C",
+ **extra,
+ }
+
+
+def layout(tmp_path):
+ home = tmp_path / "home"
+ avibe_home = home / ".avibe"
+ root = avibe_home / "runtime" / "install-generations"
+ dirs = [tmp_path / name for name in ("path-a", "path-b", "path-c", "uv-bin", "installer-bin", "elsewhere")]
+ for directory in dirs:
+ directory.mkdir(parents=True)
+ (avibe_home / "config").mkdir(parents=True)
+ (avibe_home / "config" / "config.json").write_text("{}\n", encoding="utf-8")
+ (avibe_home / "state").mkdir()
+ (avibe_home / "state" / "vibe.sqlite").write_bytes(b"user data")
+ return Layout(
+ tmp=tmp_path,
+ home=home,
+ avibe_home=avibe_home,
+ root=root,
+ current=candidate(root, "current", export_name=LAUNCHER, copy_export=WINDOWS),
+ older=candidate(root, "older", export_name=LAUNCHER, copy_export=WINDOWS),
+ path_dirs=dirs[:3],
+ uv_tool_bin=dirs[3],
+ installer_dir=dirs[4],
+ elsewhere=dirs[5],
+ )
+
+
+def _foreign(path: Path, text: str = "#!/bin/sh\necho foreign\n") -> Path:
+ path.write_text(text, encoding="utf-8")
+ path.chmod(0o755)
+ return path
+
+
+def _copy(path: Path, exported: Path, *, marker: bool) -> Path:
+ shutil.copy2(exported.resolve(), path)
+ if marker:
+ (path.parent / MARKER).write_text(str(exported.parent.parent.resolve()), encoding="utf-8")
+ return path
+
+
+def _symlink(path: Path, target: Path | str) -> Path:
+ try:
+ path.symlink_to(target)
+ except OSError as error:
+ if not WINDOWS:
+ raise
+ pytest.skip(f"this Windows session cannot create symbolic links: {error}")
+ return path
+
+
+def _hardlink(path: Path, exported: Path) -> Path:
+ os.link(exported.resolve(), path)
+ return path
+
+
+def _replaced_copy(path: Path, exported: Path) -> Path:
+ """A launcher someone replaced after Avibe copied it and wrote its marker."""
+ _copy(path, exported, marker=True)
+ path.unlink()
+ return _foreign(path)
+
+
+def _searched(directory: Path, layout: Layout) -> Path:
+ directory.mkdir(parents=True)
+ layout.path_dirs.append(directory)
+ return directory
+
+
+def _other_home(layout: Layout) -> Path:
+ root = layout.tmp / "other" / ".avibe" / "runtime" / "install-generations"
+ return candidate(root, "g", export_name=LAUNCHER, copy_export=WINDOWS)
+
+
+def _unrecognized_generation(layout: Layout) -> Path:
+ target = layout.root / "partial" / "bin" / LAUNCHER
+ target.parent.mkdir(parents=True)
+ return _foreign(target, "#!/bin/sh\n# partial\n")
+
+
+SHARED_CASES = {
+ # Shapes the Python owner manages; the uninstall removes each of them.
+ "symlink": (lambda l: _symlink(l.path_dirs[0] / LAUNCHER, l.current), True, True),
+ "relative-symlink": (
+ lambda l: _symlink(l.path_dirs[0] / LAUNCHER, os.path.relpath(l.current, l.path_dirs[0])), True, True,
+ ),
+ "chained-symlink": (
+ lambda l: _symlink(l.path_dirs[0] / LAUNCHER, _symlink(l.elsewhere / LAUNCHER, l.older)), True, True,
+ ),
+ "hardlink": (lambda l: _hardlink(l.path_dirs[0] / LAUNCHER, l.current), True, True),
+ "marked-copy": (lambda l: _copy(l.path_dirs[0] / LAUNCHER, l.current, marker=True), True, True),
+ "found-through-uv-tool-bin": (lambda l: _symlink(l.uv_tool_bin / LAUNCHER, l.current), True, True),
+ "found-through-installer-dir": (lambda l: _symlink(l.installer_dir / LAUNCHER, l.older), True, True),
+ # The Python owner will not move these, but deleting the root breaks them.
+ "unmarked-copy": (lambda l: _copy(l.path_dirs[0] / LAUNCHER, l.current, marker=False), False, True),
+ "dangling-into-root": (
+ lambda l: _symlink(l.path_dirs[0] / LAUNCHER, l.root / "deleted" / "bin" / LAUNCHER), False, True,
+ ),
+ "unrecognized-generation": (
+ lambda l: _symlink(l.path_dirs[0] / LAUNCHER, _unrecognized_generation(l)), False, True,
+ ),
+ # Nobody's to remove.
+ "foreign-file": (lambda l: _foreign(l.path_dirs[0] / LAUNCHER), False, False),
+ "foreign-symlink": (
+ lambda l: _symlink(l.path_dirs[0] / LAUNCHER, _foreign(l.elsewhere / "other-vibe")), False, False,
+ ),
+ "copy-whose-marker-is-stale": (lambda l: _replaced_copy(l.path_dirs[0] / LAUNCHER, l.current), False, False),
+ "another-homes-generation": (lambda l: _symlink(l.path_dirs[0] / LAUNCHER, _other_home(l)), False, False),
+ "inside-a-uv-tool-environment": (
+ lambda l: _symlink(_searched(l.tmp / "uv" / "tools" / "x" / "bin", l) / LAUNCHER, l.current), False, False,
+ ),
+ "not-searched": (lambda l: _symlink(l.elsewhere / LAUNCHER, l.current), False, False),
+}
+
+
+def _python_rule(layout: Layout, monkeypatch) -> set[str]:
+ monkeypatch.setenv("AVIBE_HOME", str(layout.avibe_home))
+ monkeypatch.setenv("PATH", layout.search_path)
+ monkeypatch.setenv("UV_TOOL_BIN_DIR", str(layout.uv_tool_bin))
+ monkeypatch.delenv(upgrade.CURRENT_VIBE_EXECUTABLE_ENV, raising=False)
+ monkeypatch.setattr(upgrade, "INSTALLER_LAUNCHER_DIRS", (str(layout.installer_dir),))
+ return {os.path.normcase(str(launcher)) for launcher, _ in upgrade.managed_stable_launchers()}
+
+
+def _installer_shell(layout: Layout, command: str, **env: str) -> subprocess.CompletedProcess[str]:
+ """Run install.sh functions against the layout alone, never the host's directories."""
+ source = INSTALL_SCRIPT.read_text(encoding="utf-8").rsplit('\nmain "$@"', 1)[0]
+ script = f"{source}\nINSTALLER_LAUNCHER_DIRS=({shlex.quote(str(layout.installer_dir))})\n{command}\n"
+ return subprocess.run(
+ ["bash", "-c", script],
+ cwd=layout.tmp,
+ env=layout.env(**env),
+ capture_output=True,
+ text=True,
+ timeout=60,
+ # No controlling terminal, as under CI or an unattended pipe.
+ start_new_session=True,
+ )
+
+
+def _powershell(layout: Layout, shell: str, command: str, **env: str) -> list[str]:
+ """Run install.ps1 functions against the layout; the owner's own flow runs in CI."""
+ source = INSTALL_POWERSHELL.read_text(encoding="utf-8").split("\n# Each option means one thing", 1)[0]
+ script = layout.tmp / "installer-functions.ps1"
+ installer_dir = str(layout.installer_dir).replace("'", "''")
+ script.write_text(
+ f"{source}\n$INSTALLER_LAUNCHER_DIRS = @('{installer_dir}')\n{command}\n",
+ encoding="utf-8-sig",
+ )
+ result = subprocess.run(
+ [shell, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", str(script)],
+ # A shell started from Python keeps PowerShell 7's module path, which
+ # Windows PowerShell cannot load; a user's own session has its default.
+ env={
+ **{name: value for name, value in os.environ.items() if name.upper() != "PSMODULEPATH"},
+ **layout.env(USERPROFILE=str(layout.home), AVIBE_HOME=str(layout.avibe_home), APPDATA=str(layout.tmp)),
+ **env,
+ },
+ capture_output=True,
+ text=True,
+ timeout=120,
+ )
+ assert result.returncode == 0, result.stdout + result.stderr
+ return [line.strip() for line in result.stdout.splitlines() if line.strip()]
+
+
+def _powershell_rule(layout: Layout, shell: str) -> set[str]:
+ launchers = _powershell(layout, shell, "Get-ManagedLaunchers (Join-Path (Get-RuntimeHome) 'runtime\\install-generations')")
+ return {os.path.normcase(launcher) for launcher in launchers}
+
+
+def _rule_implementations() -> list:
+ if not WINDOWS:
+ return ["install.sh"]
+ # Resolved now: each case replaces PATH with its layout's before the shell runs.
+ return [pytest.param(shutil.which(shell), id=shell) for shell in ("pwsh", "powershell") if shutil.which(shell)]
+
+
[email protected]("implementation", _rule_implementations())
[email protected]("case", SHARED_CASES)
+def test_installer_launcher_rule_matches_the_python_owner(layout, monkeypatch, implementation, case):
+ build, python_manages, uninstall_removes = SHARED_CASES[case]
+ launcher = os.path.normcase(str(build(layout)))
+ # A launcher the Python owner manages is always one the uninstall removes.
+ assert not python_manages or uninstall_removes
+
+ python_managed = _python_rule(layout, monkeypatch)
+ if implementation == "install.sh":
+ result = _installer_shell(layout, "managed_launchers")
+ assert result.returncode == 0, result.stdout + result.stderr
+ removed = set(result.stdout.splitlines())
+ else:
+ removed = _powershell_rule(layout, implementation)
+
+ assert python_managed == ({launcher} if python_manages else set())
+ assert removed == ({launcher} if uninstall_removes else set())
+
+
+def test_installer_launcher_dirs_match_the_python_owner():
+ """The shared cases replace these lists, so pin the shipped ones directly."""
+ listed = ", ".join(f'"{directory}"' for directory in upgrade.INSTALLER_LAUNCHER_DIRS)
+ assert f"$INSTALLER_LAUNCHER_DIRS = @({listed})" in INSTALL_POWERSHELL.read_text(encoding="utf-8")
+ if WINDOWS:
+ return
+ source = INSTALL_SCRIPT.read_text(encoding="utf-8").rsplit('\nmain "$@"', 1)[0]
+ result = subprocess.run(
+ ["bash", "-c", f'{source}\nprintf "%s\\n" "${{INSTALLER_LAUNCHER_DIRS[@]}}"'],
+ env={"HOME": "/home/u", "PATH": os.pathsep.join(SYSTEM_PATH)},
+ capture_output=True,
+ text=True,
+ check=True,
+ )
+ assert result.stdout.splitlines() == [
+ directory.replace("~", "/home/u", 1) for directory in upgrade.INSTALLER_LAUNCHER_DIRS
+ ]
+
+
[email protected](not WINDOWS, reason="Windows path roots")
[email protected]("shell", _rule_implementations())
+def test_powershell_purge_guard_refuses_roots_and_the_profile(layout, shell):
+ profile = str(layout.home)
+ unsafe = ["C:\\", "\\\\server\\share", "\\\\server\\share\\", profile, str(layout.home.parent)]
+ safe = [str(layout.avibe_home), "\\\\server\\share\\avibe"]
+ listed = ", ".join("'" + path.replace("'", "''") + "'" for path in unsafe + safe)
+
+ verdicts = _powershell(layout, shell, f"foreach ($path in @({listed})) {{ Test-PathHoldsHome $path }}")
+
+ assert verdicts == ["True"] * len(unsafe) + ["False"] * len(safe)
+
+
+posix_only = pytest.mark.skipif(WINDOWS, reason="the Windows owner runs end to end in windows-install-smoke")
+
+
+def _stop_logging_generation(layout: Layout, exported: Path) -> None:
+ """Make a generation's launcher record each stop and what still existed then."""
+ exported.resolve().write_text(
+ "#!/bin/sh\n"
+ f"# generation {exported.parent.parent.name}\n"
+ 'if [ "$1" = stop ]; then\n'
+ ' state=""\n'
+ ' for path in $VIBE_TEST_WATCH; do [ -e "$path" ] && state="$state+" || state="$state-"; done\n'
+ ' printf "stop %s %s %s\\n" "$0" "$AVIBE_HOME" "$state" >> "$VIBE_TEST_LOG"\n'
+ ' exit "${VIBE_TEST_STOP_STATUS:-0}"\n'
+ "fi\n",
+ encoding="utf-8",
+ )
+
+
+def installed(layout):
+ """Two managed launchers, one foreign launcher, and the user's data."""
+ for exported in (layout.current, layout.older):
+ _stop_logging_generation(layout, exported)
+ first = _symlink(layout.path_dirs[0] / LAUNCHER, layout.current)
+ (first.parent / MARKER).write_text(str(layout.current.parent.parent.resolve()), encoding="utf-8")
+ # A root host's second launcher: the installer's fixed location, copied.
+ second = _copy(layout.installer_dir / LAUNCHER, layout.current, marker=True)
+ foreign = _foreign(layout.path_dirs[1] / LAUNCHER)
+ # A marker naming a generation this home deletes, beside a launcher that
+ # has since been replaced by something else.
+ (foreign.parent / MARKER).write_text(str(layout.older.parent.parent.resolve()), encoding="utf-8")
+ legacy_home = _symlink(layout.home / ".vibe_remote", layout.avibe_home)
+ log = layout.tmp / "calls.log"
+ watch = " ".join(str(path) for path in (layout.root, first, second))
+ return layout, first, second, foreign, legacy_home, {"VIBE_TEST_LOG": str(log), "VIBE_TEST_WATCH": watch}
+
+
+def _calls(layout: Layout) -> list[str]:
+ log = layout.tmp / "calls.log"
+ return log.read_text(encoding="utf-8").splitlines() if log.exists() else []
+
+
+def _assert_untouched(layout: Layout, first: Path, second: Path, foreign: Path, legacy_home: Path) -> None:
+ assert first.is_symlink() and second.is_file() and foreign.is_file()
+ assert (first.parent / MARKER).is_file() and (foreign.parent / MARKER).is_file()
+ assert {path.name for path in layout.root.iterdir()} == {"current", "older"}
+ assert (layout.avibe_home / "state" / "vibe.sqlite").read_bytes() == b"user data"
+ assert legacy_home.is_symlink()
+
+
+@posix_only
+def test_uninstall_removes_avibe_and_keeps_user_data(installed):
+ layout, first, second, foreign, legacy_home, env = installed
+ foreign_bytes = foreign.read_bytes()
+
+ result = _installer_shell(layout, "main --uninstall", **env)
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ # One stop, through a managed launcher, while every file was still there.
+ assert _calls(layout) == [f"stop {first} {layout.avibe_home} +++"]
+ for removed in (first, second, first.parent / MARKER, second.parent / MARKER, foreign.parent / MARKER):
+ assert not removed.exists() and not removed.is_symlink()
+ assert not layout.root.exists()
+ assert foreign.read_bytes() == foreign_bytes
+ assert (layout.avibe_home / "config" / "config.json").is_file()
+ assert (layout.avibe_home / "state" / "vibe.sqlite").read_bytes() == b"user data"
+ assert legacy_home.is_symlink()
+ assert f"Another vibe command remains at {foreign}" in result.stdout
+ assert "Avibe was removed." in result.stdout
+ kept = result.stdout.split("Your data was kept in:\n", 1)[1]
+ assert kept.startswith(f" {layout.avibe_home}\n {legacy_home} -> {layout.avibe_home}\n")
+ assert " bash -o pipefail -c 'curl -fsSL https://avibe.bot/install.sh | bash -s -- --uninstall --purge'\n" in kept
+
+
+@posix_only
+def test_a_purge_without_a_terminal_needs_yes_and_deletes_nothing(installed):
+ layout, first, second, foreign, legacy_home, env = installed
+
+ result = _installer_shell(layout, "main --uninstall --purge", **env)
+
+ assert result.returncode == 1
+ listed = result.stdout.split("This permanently deletes:", 1)[1]
+ for path in (first, second, layout.root, layout.avibe_home, legacy_home):
+ assert f" {path}" in listed
+ assert "bash -s -- --uninstall --purge --yes'" in result.stdout
+ assert "Nothing was removed." in result.stdout
+ assert _calls(layout) == []
+ _assert_untouched(layout, first, second, foreign, legacy_home)
+
+
+@posix_only
+def test_a_confirmed_purge_lists_then_deletes_the_data(installed):
+ layout, first, second, foreign, legacy_home, env = installed
+
+ result = _installer_shell(layout, "main --uninstall --purge --yes", **env)
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert result.stdout.index("This permanently deletes:") < result.stdout.index("Removed")
+ assert not layout.avibe_home.exists() and not legacy_home.is_symlink()
+ assert not first.is_symlink() and not second.exists()
+ assert foreign.is_file()
+ assert "Avibe and its data were removed." in result.stdout
+ assert "Your data was kept" not in result.stdout
+
+
+def _read_terminal(terminal: int, *, until: bytes | None = None, timeout: float = 30) -> bytes:
+ output = b""
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline and (until is None or until not in output):
+ if not select.select([terminal], [], [], 0.1)[0]:
+ continue
+ try:
+ chunk = os.read(terminal, 4096)
+ except OSError: # the child closed the terminal
+ break
+ if not chunk:
+ break
+ output += chunk
+ return output
+
+
+@posix_only
[email protected]("answer, confirmed", [("n", False), ("", False), ("y", True)])
+def test_a_purge_piped_into_bash_confirms_on_the_terminal(installed, answer, confirmed):
+ """`curl ... | bash` feeds the script through stdin, so the answer comes from /dev/tty."""
+ import pty
+
+ layout, first, second, foreign, legacy_home, env = installed
+ source = INSTALL_SCRIPT.read_text(encoding="utf-8").rsplit('\nmain "$@"', 1)[0]
+ piped = layout.tmp / "piped-install.sh"
+ piped.write_text(
+ f'{source}\nINSTALLER_LAUNCHER_DIRS=({shlex.quote(str(layout.installer_dir))})\nmain "$@"\n', encoding="utf-8"
+ )
+ bash = shutil.which("bash", path=layout.search_path)
+ child, terminal = pty.fork()
+ if child == 0: # pragma: no cover - replaced by exec
+ os.execve(bash, [bash, "-c", f"bash -s -- --uninstall --purge < {shlex.quote(str(piped))}"], layout.env(**env))
+ output = _read_terminal(terminal, until=b"[y/N]")
+ os.write(terminal, f"{answer}\n".encode())
+ output += _read_terminal(terminal)
+ _, status = os.waitpid(child, 0)
+ text = output.decode(errors="replace")
+
+ assert b"[y/N]" in output, text
+ if confirmed:
+ assert os.waitstatus_to_exitcode(status) == 0, text
+ assert not layout.avibe_home.exists() and not layout.root.exists()
+ else:
+ assert os.waitstatus_to_exitcode(status) == 1, text
+ assert "Purge cancelled. Nothing was removed." in text
+ _assert_untouched(layout, first, second, foreign, legacy_home)
+
+
+@posix_only
+ "shape, options, stop_status, blocks",
+ [
+ ("connector-in-install-generations", "--uninstall", "0", True),
+ ("child-exiting-after-a-clean-stop", "--uninstall", "0", False),
+ ("mentions-an-unrelated-path", "--uninstall", "0", False),
+ ("connector-in-the-kept-home", "--uninstall", "0", False),
+ ("connector-in-the-purged-home", "--uninstall --purge --yes", "0", True),
+ ("connector-in-the-home-after-a-failed-stop", "--uninstall", "1", True),
+ ("nothing-left-after-a-failed-stop", "--uninstall", "1", False),
+ ],
+)
+def test_uninstall_waits_for_any_process_using_what_it_deletes(installed, shape, options, stop_status, blocks):
+ """No process may run from, or name, what goes; without a confirmed stop, the home counts too."""
+ layout, first, second, foreign, legacy_home, env = installed
+ unrelated = layout.tmp / "unrelated" / "runtime" / "install-generations"
+ command, seconds = {
+ "connector-in-install-generations": (f"{layout.root}/current/bin/cloudflared tunnel run", 60),
+ "child-exiting-after-a-clean-stop": (f"{layout.root}/current/bin/python -m vibe.log_sink", 2),
+ "mentions-an-unrelated-path": (f"harmless --config={unrelated}/current", 60),
+ "connector-in-the-kept-home": (f"{layout.avibe_home}/bin/cloudflared tunnel run", 60),
+ "connector-in-the-purged-home": (f"{layout.avibe_home}/bin/cloudflared tunnel run", 60),
+ "connector-in-the-home-after-a-failed-stop": (f"{layout.avibe_home}/bin/cloudflared tunnel run", 60),
+ "nothing-left-after-a-failed-stop": ("harmless", 60),
+ }[shape]
+ process = subprocess.Popen(["bash", "-c", f"exec -a {shlex.quote(command)} sleep {seconds}"])
+ try:
+ result = _installer_shell(layout, f"main {options}", VIBE_TEST_STOP_STATUS=stop_status, **env)
+ finally:
+ process.kill()
+ process.wait()
+
+ # A failed stop asks every managed launcher; a clean one stops at the first.
+ assert len(_calls(layout)) == (1 if stop_status == "0" else 2)
+ if blocks:
+ assert result.returncode == 1
+ assert f" pid {process.pid} {command} {seconds}" in result.stdout
+ assert "Stop them, then run the uninstall again." in result.stdout
+ _assert_untouched(layout, first, second, foreign, legacy_home)
+ return
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert not layout.root.exists() and not first.is_symlink()
+ if stop_status == "0":
+ assert "Stopped the Avibe service" in result.stdout
+ else:
+ assert "The installed vibe could not stop the service." in result.stdout
+ assert "such as a managed OpenCode server, could not be confirmed stopped" in result.stdout
+
+
+@posix_only
+def test_uninstall_removes_legacy_uv_tools_unless_uv_would_delete_a_foreign_launcher(layout):
+ tool_dir = layout.tmp / "uv-tools"
+ legacy_bin = layout.path_dirs[2]
+ log = layout.tmp / "calls.log"
+ current = tool_dir / "avibe-os"
+ (current / "bin").mkdir(parents=True)
+ _stop_logging_generation(layout, _foreign(current / "bin" / "vibe"))
+ own = _symlink(legacy_bin / "vibe", current / "bin" / "vibe")
+ (current / "uv-receipt.toml").write_text(f'[tool]\nentrypoints = [{{ name = "vibe", install-path = "{own}" }}]\n')
+ legacy = tool_dir / "vibe-remote"
+ legacy.mkdir()
+ foreign = _foreign(layout.path_dirs[1] / "vibe")
+ (legacy / "uv-receipt.toml").write_text(f'[tool]\nentrypoints = [{{ name = "vibe", install-path = "{foreign}" }}]\n')
+ # uv removes the tool environment and every launcher its receipt records.
+ _foreign(
+ layout.path_dirs[0] / "uv",
+ "#!/bin/sh\n"
+ 'case "$1 $2" in\n'
+ f' "tool dir") echo {shlex.quote(str(tool_dir))} ;;\n'
+ f' "tool uninstall") echo "uv uninstall $3" >> {shlex.quote(str(log))}\n'
+ f' rm -rf {shlex.quote(str(tool_dir))}/"$3" {shlex.quote(str(own))} ;;\n'
+ " *) exit 2 ;;\n"
+ "esac\n",
+ )
+
+ result = _installer_shell(layout, "main --uninstall", VIBE_TEST_LOG=str(log), VIBE_TEST_WATCH="")
+
+ assert result.returncode == 1
+ # With no managed launcher left, the legacy install's own launcher stops Avibe.
+ assert _calls(layout) == [f"stop {current / 'bin' / 'vibe'} {layout.avibe_home} ", "uv uninstall avibe-os"]
+ assert not current.exists() and not own.is_symlink()
+ assert legacy.is_dir() and foreign.is_file()
+ assert "Left the uv tool install vibe-remote in place" in result.stdout
+ assert "Avibe was not completely removed." in result.stdout
+
+
+@posix_only
+def test_uninstall_without_an_installation_says_so(layout):
+ shutil.rmtree(layout.root)
+
+ result = _installer_shell(layout, "main --uninstall")
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert "No Avibe installation was found, so nothing was removed." in result.stdout
+ assert "Avibe was removed." not in result.stdout
+ assert f"Your data was kept in:\n {layout.avibe_home}\n" in result.stdout
+
+
+@posix_only
+ "options, message",
+ [
+ ("--purge", "use it with --uninstall"),
+ ("--uninstall --yes", "use it with --uninstall --purge"),
+ ("--uninstall --launch", "cannot be combined"),
+ ],
+)
+def test_uninstall_options_never_imply_one_another(installed, options, message):
+ layout, first, second, foreign, legacy_home, env = installed
+
+ result = _installer_shell(layout, f"main {options}", **env)
+
+ assert result.returncode == 1
+ assert message in result.stdout
+ assert _calls(layout) == []
+ _assert_untouched(layout, first, second, foreign, legacy_home)
+
+
+@posix_only
+ "home, reason",
+ [("tmp", "it holds your home directory"), ("project", "it does not look like an Avibe home")],
+)
+def test_a_purge_refuses_a_home_that_is_not_safe_to_delete(installed, home, reason):
+ layout, first, second, foreign, legacy_home, env = installed
+ target = layout.tmp if home == "tmp" else layout.tmp / "project"
+ (target / "runtime" if home == "tmp" else target / "config").mkdir(parents=True)
+
+ result = _installer_shell(layout, "main --uninstall --purge --yes", **{**env, "AVIBE_HOME": str(target)})
+
+ assert result.returncode == 1
+ assert f"Refusing to purge {target}" in result.stdout and reason in result.stdout
+ assert target.is_dir() and _calls(layout) == []
+ _assert_untouched(layout, first, second, foreign, legacy_home)
+
+
+def _linked_home(layout: Layout, shape: str, *, windows: bool) -> tuple[Path, list[Path], list[Path]]:
+ """Build a home reached through links; return the profile, the links, and what they name."""
+ profile = layout.home
+ shutil.rmtree(layout.avibe_home)
+ (profile / "keep.txt").write_text("the user's own file", encoding="utf-8")
+ if shape == "chain":
+ # ~/.avibe reaches the data through a link to a link.
+ data = layout.tmp / "data" / "avibe"
+ (data / "runtime").mkdir(parents=True)
+ (data / "state").mkdir()
+ hop = _symlink(layout.tmp / "hop", data)
+ if windows:
+ import _winapi
+
+ _winapi.CreateJunction(str(hop), str(layout.avibe_home))
+ else:
+ _symlink(layout.avibe_home, hop)
+ legacy = _symlink(profile / ".vibe_remote", layout.avibe_home)
+ return profile, [layout.avibe_home, legacy], [data]
+ # The profile itself is reached through a link, and ~/.vibe_remote names it.
+ linked_profile = layout.tmp / "profile-link"
+ if windows:
+ import _winapi
+
+ _winapi.CreateJunction(str(profile), str(linked_profile))
+ else:
+ _symlink(linked_profile, profile)
+ legacy = _symlink(profile / ".vibe_remote", linked_profile)
+ return linked_profile, [legacy], [profile]
+
+
+@posix_only
[email protected]("shape", ["chain", "link-to-the-profile"])
+def test_a_purge_removes_links_and_never_what_they_name(layout, shape):
+ profile, links, targets = _linked_home(layout, shape, windows=False)
+
+ result = _installer_shell(layout, "main --uninstall --purge --yes", HOME=str(profile))
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert not any(link.is_symlink() for link in links)
+ assert all(target.is_dir() for target in targets)
+ assert (layout.home / "keep.txt").read_text(encoding="utf-8") == "the user's own file"
+ assert "It removes these links, not what they point to:" in result.stdout
+ assert "pointed to. Delete it by hand if it is yours." in result.stdout
+
+
[email protected](not WINDOWS, reason="junctions")
[email protected]("shell", _rule_implementations())
[email protected]("shape", ["chain", "link-to-the-profile"])
+def test_powershell_purge_removes_links_and_never_what_they_name(layout, shell, shape):
+ profile, links, targets = _linked_home(layout, shape, windows=True)
+
+ _powershell(
+ layout, shell, "$Purge = $true; $Yes = $true; Uninstall-Avibe | Out-Null", USERPROFILE=str(profile), AVIBE_HOME=""
+ )
+
+ assert not any(os.path.lexists(link) for link in links)
+ assert all(target.is_dir() for target in targets)
+ assert (layout.home / "keep.txt").read_text(encoding="utf-8") == "the user's own file"
+
+
[email protected](not WINDOWS, reason="Windows process table")
[email protected]("shell", _rule_implementations())
+def test_powershell_waits_for_a_process_using_what_it_deletes(layout, shell):
+ unrelated = layout.tmp / "unrelated" / "runtime" / "install-generations"
+ sleeper = "import time; time.sleep(120)"
+ using = subprocess.Popen([sys.executable, "-c", sleeper, str(layout.root / "current" / "bin" / "cloudflared.exe")])
+ mentioning = subprocess.Popen([sys.executable, "-c", sleeper, f"--config={unrelated}"])
+ try:
+ root = str(layout.root).replace("'", "''")
+ blocking = _powershell(layout, shell, f"Get-BlockingProcesses -Paths @('{root}')")
+ finally:
+ for process in (using, mentioning):
+ process.kill()
+ process.wait()
+
+ pids = {int(line.split(" ", 1)[0]) for line in blocking}
+ assert using.pid in pids and mentioning.pid not in pids
+
+
+def _spelled_home(layout: Layout, spelling: str) -> tuple[str, Path]:
+ """Return an AVIBE_HOME spelling and the physical home it reaches."""
+ def home_at(path: Path) -> Path:
+ (path / "runtime" / "install-generations" / "g").mkdir(parents=True)
+ (path / "state").mkdir()
+ return path
+
+ if spelling == "linked-ancestor":
+ # The home is a real directory under a linked parent, as with /home -> /var/home.
+ real = home_at(layout.tmp / "var-home" / "instance")
+ _symlink(layout.tmp / "home-link", real.parent)
+ return str(layout.tmp / "home-link" / "instance"), real
+ if spelling == "dot-dot-through-a-link":
+ # Spelled x/../instance, where x is a link: bash reads it as one directory,
+ # and the kernel resolves another.
+ home_at(layout.tmp / "sub" / "instance")
+ reached = home_at(layout.tmp / "elsewhere" / "instance")
+ (layout.tmp / "elsewhere" / "deep").mkdir()
+ _symlink(layout.tmp / "sub" / "x", layout.tmp / "elsewhere" / "deep")
+ return str(layout.tmp / "sub" / "x" / ".." / "instance"), reached
+ real = home_at(layout.tmp / "instance")
+ link = _symlink(layout.tmp / "instance-link", real)
+ suffix = {"trailing-dot": "/.", "double-slash": "//", "trailing-slash": "/"}[spelling]
+ return f"{link}{suffix}", real
+
+
+@posix_only
+ "spelling, succeeds",
+ [
+ ("trailing-dot", False),
+ ("double-slash", False),
+ ("trailing-slash", False),
+ ("dot-dot-through-a-link", False),
+ ("linked-ancestor", True),
+ ],
+)
[email protected]("options", ["--uninstall", "--uninstall --purge --yes"])
+def test_uninstall_deletes_directories_only_by_their_verified_physical_path(layout, spelling, succeeds, options):
+ avibe_home, reached = _spelled_home(layout, spelling)
+ purge = "--purge" in options
+
+ result = _installer_shell(layout, f"main {options}", AVIBE_HOME=avibe_home)
+
+ if succeeds:
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert not (reached / "runtime" / "install-generations").exists()
+ assert reached.exists() is not purge
+ return
+ assert result.returncode == 1
+ # The directory the spelling reaches keeps everything.
+ assert (reached / "runtime" / "install-generations" / "g").is_dir()
+ assert (reached / "state").is_dir()
+
+
+@posix_only
+def test_a_purge_unlinks_an_explicit_home_named_with_trailing_slashes(layout):
+ target = layout.tmp / "instance"
+ (target / "runtime").mkdir(parents=True)
+ (target / "state").mkdir()
+ link = _symlink(layout.tmp / "instance-link", target)
+
+ result = _installer_shell(layout, "main --uninstall --purge --yes", AVIBE_HOME=f"{link}///")
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert not link.is_symlink()
+ assert (target / "runtime").is_dir() and (target / "state").is_dir()
+ assert f"Kept {target}, which {link} pointed to." in result.stdout
+
+
+@posix_only
+def test_a_purge_leaves_a_file_that_merely_has_a_home_name(layout):
+ shutil.rmtree(layout.avibe_home)
+ layout.avibe_home.write_text("someone else's file", encoding="utf-8")
+
+ result = _installer_shell(layout, "main --uninstall --purge --yes")
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert layout.avibe_home.read_text(encoding="utf-8") == "someone else's file"
+
+
+@posix_only
+def test_uninstall_removes_nothing_when_no_process_list_is_available(installed):
+ layout, first, second, foreign, legacy_home, env = installed
+
+ # As on a system with neither ps nor /proc.
+ result = _installer_shell(layout, "process_table() { :; }\nmain --uninstall", **env)
+
+ assert result.returncode == 1
+ assert "No process list is available here" in result.stdout
+ assert "Nothing was removed." in result.stdout
+ _assert_untouched(layout, first, second, foreign, legacy_home)
+
+
+def _link_directory(link: Path, target: Path) -> None:
+ if WINDOWS:
+ import _winapi
+
+ _winapi.CreateJunction(str(target), str(link))
+ else:
+ _symlink(link, target)
+
+
+def _generations_behind_a_link(layout: Layout, shape: str) -> tuple[Path, dict[str, str]]:
+ """Move part of the home elsewhere and reach it through a link; return the real root."""
+ if shape == "linked-runtime":
+ external = layout.tmp / "external-runtime"
+ shutil.move(str(layout.avibe_home / "runtime"), str(external))
+ _link_directory(layout.avibe_home / "runtime", external)
+ return external / "install-generations", {}
+ if shape == "non-directory-root":
+ shutil.rmtree(layout.root)
+ layout.root.write_text("not a generation root", encoding="utf-8")
+ return layout.root, {}
+ external = layout.tmp / "external-home"
+ shutil.move(str(layout.avibe_home), str(external))
+ if shape == "linked-home":
+ _link_directory(layout.avibe_home, external)
+ else:
+ # No ~/.avibe, so the installer selects this legacy alias as the home.
+ _link_directory(layout.home / ".vibe_remote", external)
+ return external / "runtime" / "install-generations", {}
+
+
+GENERATION_GUARD_SHAPES = ["linked-runtime", "linked-home", "stale-legacy-alias", "non-directory-root"]
+
+
+def _assert_generations_kept(root: Path, shape: str) -> None:
+ if shape == "non-directory-root":
+ assert root.read_text(encoding="utf-8") == "not a generation root"
+ else:
+ assert {path.name for path in root.iterdir()} == {"current", "older"}
+
+
+@posix_only
[email protected]("shape", GENERATION_GUARD_SHAPES)
+def test_uninstall_deletes_the_generation_root_only_through_real_directories(layout, shape):
+ external_root, _ = _generations_behind_a_link(layout, shape)
+ # The fixture's generation exports link by the old path, so name the file itself.
+ launcher = _symlink(layout.path_dirs[0] / LAUNCHER, external_root / "current" / "uv" / "tools" / "avibe-os" / "bin" / "vibe")
+
+ result = _installer_shell(layout, "main --uninstall")
+
+ assert result.returncode == 1
+ _assert_generations_kept(external_root, shape)
+ # Launchers are links or files themselves, so they still go.
+ assert not launcher.is_symlink()
+ if shape == "non-directory-root":
+ assert "is not a directory, and the uninstaller deletes only real directories." in result.stdout
+ else:
+ assert "and the uninstaller never deletes through a link." in result.stdout
+ assert f"If it is yours, remove it with: rm -rf -- {shlex.quote(str(external_root.resolve()))}" in result.stdout
+ assert "Avibe was not completely removed." in result.stdout
+
+
+@posix_only
[email protected](hasattr(os, "geteuid") and os.geteuid() == 0, reason="root can remove from a read-only directory")
+def test_uninstall_keeps_the_generation_root_while_a_launcher_could_not_be_removed(installed):
+ layout, first, second, foreign, legacy_home, env = installed
+ first.parent.chmod(0o555) # as a system directory the user cannot write
+ try:
+ result = _installer_shell(layout, "main --uninstall", **env)
+ finally:
+ first.parent.chmod(0o755)
+
+ assert result.returncode == 1
+ assert first.is_symlink() and not second.exists()
+ assert {path.name for path in layout.root.iterdir()} == {"current", "older"}
+ assert f"Left {layout.root} in place: {first} could not be removed" in result.stdout
+ # It is reported once, as the managed launcher it is, not as another install.
+ assert f"remains at {first}" not in result.stdout
+
+
[email protected](not os.path.exists("/proc/self/exe"), reason="Linux names each process's executable")
+def test_uninstall_waits_for_a_process_started_by_a_relative_path(installed):
+ layout, first, second, foreign, legacy_home, env = installed
+ binary = layout.root / "current" / "bin" / "cloudflared"
+ shutil.copy2(shutil.which("sleep"), binary)
+ process = subprocess.Popen(["./cloudflared", "60"], cwd=binary.parent)
+ try:
+ result = _installer_shell(layout, "main --uninstall", **env)
+ finally:
+ process.kill()
+ process.wait()
+
+ assert result.returncode == 1
+ # The command line shows only ./cloudflared; the executable names the generation.
+ assert f" pid {process.pid} ./cloudflared 60 ({binary})" in result.stdout
+ _assert_untouched(layout, first, second, foreign, legacy_home)
+
+
[email protected](not WINDOWS, reason="junctions")
[email protected]("shell", _rule_implementations())
[email protected]("shape", GENERATION_GUARD_SHAPES)
+def test_powershell_deletes_the_generation_root_only_through_real_directories(layout, shell, shape):
+ external_root, _ = _generations_behind_a_link(layout, shape)
+ env = {} if shape in ("linked-runtime", "non-directory-root") else {"AVIBE_HOME": ""}
+
+ output = "\n".join(_powershell(layout, shell, "Uninstall-Avibe | Out-Null", **env))
+
+ _assert_generations_kept(external_root, shape)
+ if shape == "non-directory-root":
+ assert "is not a directory, and the uninstaller deletes only real directories." in output
+ else:
+ assert "and the uninstaller never deletes through a link." in output
+ assert "If it is yours, remove it with:" in output
+
+
[email protected](not WINDOWS, reason="an open file cannot be deleted on Windows")
[email protected]("shell", _rule_implementations())
+def test_powershell_keeps_the_generation_root_while_a_launcher_could_not_be_removed(layout, shell):
+ launcher = _copy(layout.path_dirs[0] / LAUNCHER, layout.current, marker=True)
+ with launcher.open("rb"): # held open, so Windows refuses to delete it
+ output = "\n".join(_powershell(layout, shell, "Uninstall-Avibe | Out-Null"))
+
+ assert launcher.is_file()
+ assert {path.name for path in layout.root.iterdir()} == {"current", "older"}
+ assert f"{launcher} could not be removed" in output
+
+
[email protected](not WINDOWS, reason="Windows process table")
[email protected]("shell", _rule_implementations())
+def test_powershell_removes_nothing_without_a_process_list(layout, shell):
+ output = "\n".join(_powershell(
+ layout, shell, "function Get-CimInstance { throw 'WMI is unavailable' }; Uninstall-Avibe | Out-Null"
+ ))
+
+ assert "No process list is available here" in output
+ assert {path.name for path in layout.root.iterdir()} == {"current", "older"}
+
+
+@posix_only
+def test_uninstall_names_the_pip_that_can_remove_an_avibe_it_did_not_install(layout):
+ shutil.rmtree(layout.root)
+ pip_launcher = _foreign(
+ layout.path_dirs[0] / "vibe",
+ "#!/opt/python/bin/python3\nimport sys\nfrom vibe.cli import main\nif __name__ == '__main__':\n sys.exit(main())\n",
+ )
+
+ result = _installer_shell(layout, "main --uninstall")
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert pip_launcher.is_file()
+ assert f"remains at {pip_launcher}, such as a pip install" in result.stdout
+ assert "/opt/python/bin/python3 -m pip uninstall avibe-os vibe-remote" in result.stdout
+
+
+def _fake_uv(layout: Layout, tool_dir: Path) -> None:
+ """uv removes a tool's environment; `uv tool dir` names where they live."""
+ log = shlex.quote(str(layout.tmp / "calls.log"))
+ _foreign(
+ layout.path_dirs[0] / "uv",
+ "#!/bin/sh\n"
+ 'case "$1 $2" in\n'
+ f' "tool dir") echo {shlex.quote(str(tool_dir))} ;;\n'
+ f' "tool uninstall") echo "uv uninstall $3" >> {log}; rm -rf {shlex.quote(str(tool_dir))}/"$3" ;;\n'
+ " *) exit 2 ;;\n"
+ "esac\n",
+ )
+
+
+@posix_only
+def test_an_explicit_avibe_home_purges_only_that_home(installed):
+ layout, first, second, foreign, legacy_home, env = installed
+ instance = layout.tmp / "instance"
+ (instance / "runtime").mkdir(parents=True)
+ # A global uv tool install belongs to no chosen home.
+ tool = layout.tmp / "uv-tools" / "avibe-os"
+ tool.mkdir(parents=True)
+ _fake_uv(layout, tool.parent)
+
+ result = _installer_shell(layout, "main --uninstall --purge --yes", **{**env, "AVIBE_HOME": str(instance)})
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert not instance.exists()
+ # The default home's launchers, data, and uv tool belong to another installation.
+ _assert_untouched(layout, first, second, foreign, legacy_home)
+ assert tool.is_dir() and _calls(layout) == []
+ assert "Leaving the uv tool install avibe-os in place" in result.stdout
+
+
+@posix_only
[email protected]("shape", ["wrong-legacy-link", "wrong-legacy-link-without-avibe-home", "explicit-legacy-home"])
+def test_a_purge_deletes_only_the_selected_homes_data(installed, shape):
+ layout, first, second, foreign, legacy_home, env = installed
+ legacy_home.unlink()
+ unrelated = layout.tmp / "unrelated"
+ unrelated.mkdir()
+ (unrelated / "notes.txt").write_text("not Avibe's", encoding="utf-8")
+ if shape.startswith("wrong-legacy-link"):
+ # Doctor reports this as a wrong link; without ~/.avibe it is also the home.
+ legacy_home.symlink_to(unrelated)
+ if shape.endswith("without-avibe-home"):
+ shutil.rmtree(layout.avibe_home)
+ else:
+ (legacy_home / "runtime").mkdir(parents=True)
+ env = {**env, "AVIBE_HOME": str(legacy_home)}
+
+ result = _installer_shell(layout, "main --uninstall --purge --yes", **env)
+
+ assert result.returncode == 0, result.stdout + result.stderr
+ assert (unrelated / "notes.txt").read_text(encoding="utf-8") == "not Avibe's"
+ if shape.startswith("wrong-legacy-link"):
+ assert not layout.avibe_home.exists()
+ assert not legacy_home.is_symlink()
+ assert f" {legacy_home} -> {unrelated}" in result.stdout
+ assert f"Kept {unrelated}, which {legacy_home} pointed to." in result.stdout
+ else:
+ assert not legacy_home.exists()
+ # ~/.avibe is the home Avibe uses without AVIBE_HOME, another installation.
+ assert (layout.avibe_home / "state" / "vibe.sqlite").read_bytes() == b"user data"
+ assert first.is_symlink() and layout.root.is_dir()
+
+
+ "document, native_windows",
+ [
+ ("README.md", False),
+ ("README_ZH.md", False),
+ ("docs/INSTALL_FOR_AI.md", True),
+ ("docs/INSTALL_FOR_AI_ZH.md", True),
+ ],
+)
+def test_uninstall_recipes_point_to_the_installer(document, native_windows):
+ text = (REPO_ROOT / document).read_text(encoding="utf-8")
+
+ # Like the install command, a failed download fails the command.
+ assert "bash -o pipefail -c 'curl -fsSL https://avibe.bot/install.sh | bash -s -- --uninstall'\n" in text
+ assert "bash -o pipefail -c 'curl -fsSL https://avibe.bot/install.sh | bash -s -- --uninstall --purge'\n" in text
+ powershell = "& ([scriptblock]::Create((irm https://raw.githubusercontent.com/avibe-bot/avibe/master/install.ps1))) -Uninstall"
+ assert (f"{powershell}\n" in text and f"{powershell} -Purge\n" in text) is native_windows
+ assert "uv tool uninstall" not in text and "rm -rf" not in text