Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(install): validate staged updates and restore failed promotions
Seth Wilsonaac76022feb2
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex f0176459..41a20d3e 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -277,6 +277,9 @@ jobs:steps:- uses: actions/checkout@v4+ - name: Verify failed updates preserve the previous installation+ run: python3 scripts/test-installers.py --shell sh -v+- name: Build a fake release directoryrun: |set -euo pipefail@@ -397,13 +400,17 @@ jobs:test ! -e "$MERCURY_INSTALL/bin/mercury"installer-windows:- name: Installer dry run (install.ps1, Windows PowerShell 5.1, local release dir)+ name: Installer dry run (install.ps1, ${{ matrix.shell }}, local release dir)runs-on: windows-latest+ strategy:+ fail-fast: false+ matrix:+ shell: [powershell, pwsh]steps:- uses: actions/checkout@v4- name: Build a fake release directory (real stub exe) and serve it as application/octet-stream- shell: powershell+ shell: ${{ matrix.shell }}run: |$ErrorActionPreference = 'Stop'$rel = Join-Path $env:RUNNER_TEMP 'fake-release\v9.9.9'@@ -429,6 +436,17 @@ jobs:class H(http.server.SimpleHTTPRequestHandler):def guess_type(self, path):return 'application/octet-stream'+ def do_GET(self):+ if self.path == '/cosmicstack-labs/mercury-agent/releases/latest':+ self.send_response(302)+ self.send_header('Location', '/cosmicstack-labs/mercury-agent/releases/tag/v9.9.9')+ self.end_headers()+ elif self.path == '/cosmicstack-labs/mercury-agent/releases/tag/v9.9.9':+ self.send_response(200)+ self.end_headers()+ self.wfile.write(b'release fixture')+ else:+ super().do_GET()os.chdir(sys.argv[1])http.server.ThreadingHTTPServer(('127.0.0.1', 8765), H).serve_forever()'@ -replace '^ ', '' | Set-Content -Path $server -Encoding ASCII@@ -437,8 +455,16 @@ jobs:foreach ($i in 1..30) { try { Invoke-WebRequest -Uri http://127.0.0.1:8765/v9.9.9/checksums.txt -UseBasicParsing | Out-Null; $ok = $true; break } catch { Start-Sleep -Milliseconds 500 } }if (-not $ok) { throw 'fake release server did not come up' }- - name: Run install.ps1 from disk under Windows PowerShell 5.1- shell: powershell+ - name: Check latest-version resolution and piped dev installer+ shell: ${{ matrix.shell }}+ run: ./scripts/test-installer-helpers.ps1 -LatestUri http://127.0.0.1:8765/cosmicstack-labs/mercury-agent/releases/latest++ - name: Verify failed updates preserve the previous installation+ shell: ${{ matrix.shell }}+ run: python scripts/test-installers.py --shell ${{ matrix.shell }} -v++ - name: Run install.ps1 from disk+ shell: ${{ matrix.shell }}env:MERCURY_VERSION: 9.9.9MERCURY_DOWNLOAD_BASE: http://127.0.0.1:8765@@ -450,7 +476,7 @@ jobs:"PSVersion: $($PSVersionTable.PSVersion)"$log = Join-Path $env:RUNNER_TEMP 'install.log'# From disk (not irm | iex): also proves the file parses without a BOM under the ANSI code page.- powershell -NoProfile -ExecutionPolicy Bypass -File scripts\install.ps1 2>&1 | Tee-Object -FilePath $log+ & (Get-Process -Id $PID).Path -NoProfile -ExecutionPolicy Bypass -File scripts\install.ps1 2>&1 | Tee-Object -FilePath $logif ($LASTEXITCODE -ne 0) { throw "install.ps1 exited $LASTEXITCODE" }if (-not (Select-String -Path $log -Pattern 'Checksums verified' -Quiet)) { throw 'no "Checksums verified" in output' }if (-not (Select-String -Path $log -Pattern 'Smoke test passed' -Quiet)) { throw 'no "Smoke test passed" in output' }diff --git a/scripts/install-dev.ps1 b/scripts/install-dev.ps1index 1991cf7d..ea87ad12 100755--- a/scripts/install-dev.ps1+++ b/scripts/install-dev.ps1@@ -13,11 +13,13 @@$ErrorActionPreference = 'Stop'# Running from a checkout: prefer the sibling stable installer.-$sibling = Join-Path $PSScriptRoot 'install.ps1'-if (Test-Path $sibling) {- $env:MERCURY_CHANNEL = 'dev'- & $sibling- return+if (-not [string]::IsNullOrEmpty($PSScriptRoot)) {+ $sibling = Join-Path $PSScriptRoot 'install.ps1'+ if (Test-Path $sibling -PathType Leaf) {+ $env:MERCURY_CHANNEL = 'dev'+ & $sibling+ return+ }}# Otherwise pull the stable installer from the always-current site URL. Thediff --git a/scripts/install.ps1 b/scripts/install.ps1index f89b06d1..1272d327 100644--- a/scripts/install.ps1+++ b/scripts/install.ps1@@ -45,13 +45,18 @@ function Get-MercuryArch {Die "32-bit Windows is not supported. Mercury ships x64 and arm64 binaries only."}-function Resolve-LatestVersion {- # The /releases/latest URL redirects to /releases/tag/vX.Y.Z. We follow it- # without hitting the JSON API (no rate limits, no auth needed).- $resp = Invoke-WebRequest -Uri "https://github.com/$Repo/releases/latest" `- -MaximumRedirection 5 -UseBasicParsing- $final = $resp.BaseResponse.ResponseUri.AbsoluteUri- if ($final -match '/tag/v?([0-9][^/]*)/?$') {+function Resolve-LatestVersion ([uri]$LatestUri = "https://github.com/$Repo/releases/latest") {+ # PowerShell 5.1 exposes HttpWebResponse.ResponseUri; PowerShell 7 uses+ # HttpResponseMessage.RequestMessage.RequestUri after following redirects.+ $resp = Invoke-WebRequest -Uri $LatestUri -MaximumRedirection 5 -UseBasicParsing+ $final = $resp.BaseResponse.ResponseUri+ if (-not $final) { $final = $resp.BaseResponse.RequestMessage.RequestUri }+ $final = [uri]$final+ $tagPrefix = $LatestUri.AbsolutePath -replace '/latest/?$', '/tag/'+ $tagPattern = '^' + [regex]::Escape($tagPrefix) + 'v?([0-9][0-9A-Za-z.+-]*)/?$'+ if ($final -and $final.IsAbsoluteUri -and $final.Scheme -eq $LatestUri.Scheme -and+ $final.Authority -eq $LatestUri.Authority -and -not $final.UserInfo -and+ -not $final.Query -and -not $final.Fragment -and $final.AbsolutePath -match $tagPattern) {return $Matches[1]}Die "Could not determine the latest Mercury version from $final"@@ -218,6 +223,29 @@ try {Die 'Failed to extract the required web directory from web.tar.gz'}+ $candidateBin = Join-Path $stageDir $binName+ Move-Item -Path $binaryTmp -Destination $candidateBin+ try {+ $smoke = & $candidateBin --version 2>&1+ $smokeExit = $LASTEXITCODE+ } catch { Die "The downloaded binary could not start; the previous installation was preserved: $_" }+ # STATUS_ILLEGAL_INSTRUCTION on CPUs without AVX2: validate the baseline+ # too, before replacing either artifact in a working installation.+ if ($smokeExit -ne 0 -and $asset -ne 'mercury-win-x64-baseline.exe' -and ($smokeExit -eq -1073741795 -or $smokeExit -eq 3221225501)) {+ Write-Info 'This CPU cannot run the default build (illegal instruction) - switching to the baseline build'+ $asset = 'mercury-win-x64-baseline.exe'+ $expected = Get-RequiredChecksum -Checksums $checksums -Asset $asset+ Save-VerifiedAsset -Uri "$releaseDir/$asset" -Path $candidateBin -ExpectedHash $expected -Asset $asset+ try {+ $smoke = & $candidateBin --version 2>&1+ $smokeExit = $LASTEXITCODE+ } catch { Die "The baseline binary could not start; the previous installation was preserved: $_" }+ }+ if ($smokeExit -ne 0) {+ Die "Mercury $versionLabel cannot run on this machine; the previous installation was preserved: $smoke"+ }+ Write-Info "Smoke test passed: $binName --version -> $smoke"+New-Item -ItemType Directory -Force -Path $binDir | Out-Null# Windows cannot overwrite a running executable. `mercury upgrade` hands# us its own PID in MERCURY_WAIT_PID: wait for it to exit (not a fixed@@ -242,12 +270,47 @@ try {Die ("Mercury is still running (PID {0}). Run `mercury stop` and re-run the installer." -f ($still.Id -join ', '))}}- Remove-Item $binPath -Force}- Move-Item -Path $binaryTmp -Destination $binPath -Force+ # Backups stay on the installation's filesystem until both moves succeed.+ # If recovery itself fails, retain those files and report their location.+ $backupDir = Join-Path $binDir ('.mercury-install-' + [guid]::NewGuid().ToString('N'))+ New-Item -ItemType Directory -Path $backupDir | Out-Null+ $previousBinary = Join-Path $backupDir 'previous-binary'+ $previousWeb = Join-Path $backupDir 'previous-web'$webDir = Join-Path $binDir 'web'- if (Test-Path $webDir) { Remove-Item $webDir -Recurse -Force }- Move-Item -Path (Join-Path $stageDir 'web') -Destination $webDir+ $binaryPromoted = $false+ $webPromoted = $false+ try {+ # Finish any cross-volume copy before moving the old installation.+ $candidateDir = Join-Path $backupDir 'candidate'+ Move-Item -Path $stageDir -Destination $candidateDir+ $candidateBin = Join-Path $candidateDir $binName+ if (Test-Path $binPath) { Move-Item -Path $binPath -Destination $previousBinary }+ if (Test-Path $webDir) { Move-Item -Path $webDir -Destination $previousWeb }+ Move-Item -Path $candidateBin -Destination $binPath+ $binaryPromoted = $true+ Move-Item -Path (Join-Path $candidateDir 'web') -Destination $webDir+ $webPromoted = $true+ } catch {+ $promotionError = $_+ $restoreFailed = $false+ foreach ($part in @(+ @{ Target = $binPath; Backup = $previousBinary; Promoted = $binaryPromoted },+ @{ Target = $webDir; Backup = $previousWeb; Promoted = $webPromoted }+ )) {+ try {+ if ($part.Promoted) { Remove-Item -LiteralPath $part.Target -Recurse -Force }+ if (Test-Path $part.Backup) { Move-Item -Path $part.Backup -Destination $part.Target }+ } catch { $restoreFailed = $true }+ }+ if ($restoreFailed) {+ Write-Warn2 "Could not fully restore the previous installation. Recovery files: $backupDir"+ } else {+ Remove-Item -LiteralPath $backupDir -Recurse -Force+ }+ throw $promotionError+ }+ Remove-Item -LiteralPath $backupDir -Recurse -ForceWrite-Info 'Web dashboard assets installed'}finally {@@ -256,33 +319,6 @@ finally {Write-Info "Installed to $binPath"-# Post-install smoke. A CPU without AVX2 cannot run the default build and-# dies with STATUS_ILLEGAL_INSTRUCTION (0xC000001D, #155): switch to the-# baseline build in place.-$smoke = & $binPath --version 2>&1-$smokeExit = $LASTEXITCODE-if ($smokeExit -ne 0 -and $asset -ne 'mercury-win-x64-baseline.exe' -and ($smokeExit -eq -1073741795 -or $smokeExit -eq 3221225501)) {- Write-Info 'This CPU cannot run the default build (illegal instruction) - switching to the baseline build'- $asset = 'mercury-win-x64-baseline.exe'- $tmp2 = Join-Path $env:TEMP ("mercury-" + [guid]::NewGuid().ToString('N'))- New-Item -ItemType Directory -Path $tmp2 | Out-Null- try {- $expected = Get-RequiredChecksum -Checksums $checksums -Asset $asset- $dl = Join-Path $tmp2 $asset- Save-VerifiedAsset -Uri "$releaseDir/$asset" -Path $dl -ExpectedHash $expected -Asset $asset- Remove-Item $binPath -Force- Move-Item -Path $dl -Destination $binPath -Force- $smoke = & $binPath --version 2>&1- $smokeExit = $LASTEXITCODE- } finally {- Remove-Item $tmp2 -Recurse -Force -ErrorAction SilentlyContinue- }-}-if ($smokeExit -ne 0) {- Die "Mercury $versionLabel is installed but not runnable on this machine: $smoke (please report this at https://github.com/$Repo/issues)"-}-Write-Info "Smoke test passed: $binName --version -> $smoke"-$pathUpdated = Update-UserPath -BinDir $binDirWrite-Host ''diff --git a/scripts/install.sh b/scripts/install.shindex 3ff6a37a..ba073033 100755--- a/scripts/install.sh+++ b/scripts/install.sh@@ -204,6 +204,30 @@ maybe_update_path() {PATH_UPDATED=1}+# Keep backups until both artifacts have been promoted. A failed rollback leaves+# its recovery directory intact rather than deleting the only working copy.+cleanup_install() {+ rollback_failed=0+ if [ -n "$transaction_dir" ] && [ "$promotion_started" = 1 ] && [ "$promotion_complete" = 0 ]; then+ for part in binary web; do+ if [ "$part" = binary ]; then target="$bin_path"; candidate="$candidate_dir/$BIN_NAME";+ else target="$bin_dir/web"; candidate="$candidate_dir/web"; fi+ backup="$transaction_dir/previous-$part"+ if [ -e "$backup" ] || [ -L "$backup" ]; then+ if ! { rm -rf "$target" && mv "$backup" "$target"; }; then rollback_failed=1; fi+ elif [ ! -e "$candidate" ]; then+ rm -rf "$target" || rollback_failed=1+ fi+ done+ fi+ if [ "$rollback_failed" = 1 ]; then+ err "Could not fully restore the previous installation. Recovery files: $transaction_dir"+ elif [ -n "$transaction_dir" ]; then+ rm -rf "$transaction_dir"+ fi+ rm -rf "$tmp_dir"+}+# ----- main ------------------------------------------------------------------main() {@@ -253,7 +277,12 @@ Install the supported Node.js package instead:web_tmp="$tmp_dir/web.tar.gz"checksums_tmp="$tmp_dir/checksums.txt"stage_dir="$tmp_dir/stage"- trap 'rm -rf "$tmp_dir"' EXIT INT TERM+ transaction_dir=''+ promotion_started=0+ promotion_complete=0+ trap cleanup_install EXIT+ trap 'exit 130' INT+ trap 'exit 143' TERMchecksum_url="${release_dir}/checksums.txt"info "Downloading checksums.txt ..."@@ -303,29 +332,27 @@ Install the supported Node.js package instead:tar -xzf "$web_tmp" -C "$stage_dir" || die "Failed to extract web dashboard assets"[ -d "$stage_dir/web" ] || die "web.tar.gz does not contain the required web directory"+ # Stage on the install filesystem (not a potentially noexec /tmp), with+ # dashboard assets beside the executable just as in the final installation.mkdir -p "$bin_dir"- mv "$binary_tmp" "$bin_path"- chmod +x "$bin_path"- rm -rf "$bin_dir/web"- mv "$stage_dir/web" "$bin_dir/web"- info "Web dashboard assets installed"-- # macOS: strip the quarantine attribute so Gatekeeper doesn't bark on- # unsigned binaries downloaded via curl.+ transaction_dir=$(mktemp -d "$bin_dir/.mercury-install.XXXXXX")+ candidate_dir="$transaction_dir/candidate"+ mkdir -p "$candidate_dir"+ candidate_bin="$candidate_dir/$BIN_NAME"+ mv "$binary_tmp" "$candidate_bin"+ chmod +x "$candidate_bin"+ mv "$stage_dir/web" "$candidate_dir/web"++ # macOS: strip quarantine before testing the staged executable.if [ "$os" = "macos" ] && have xattr; then- xattr -d com.apple.quarantine "$bin_path" 2>/dev/null || true+ xattr -d com.apple.quarantine "$candidate_bin" 2>/dev/null || truefi- info "Installed to $bin_path"-- # Post-install smoke: the binary must at least report its version. A- # wrong-arch download, a glibc mismatch or a quarantined binary fails- # here with a readable message instead of at first use.- # `if` form: under set -e a failing command substitution exits the script- # (the 1.3.4 installer died with "Illegal instruction" instead of switching builds).- if smoke_out=$("$bin_path" --version 2>&1); then smoke_status=0; else smoke_status=$?; fi+ # Validate before touching the working installation, including CPU fallback.+ # The if form retains the failure status under set -e.+ if smoke_out=$("$candidate_bin" --version 2>&1); then smoke_status=0; else smoke_status=$?; fi# SIGILL (exit 132) on the default build = a CPU without AVX2 that- # /proc/cpuinfo did not reveal: switch to the baseline build in place.+ # /proc/cpuinfo did not reveal: switch to the staged baseline build.if [ "$smoke_status" -ne 0 ] && [ "$os" = "linux" ] && [ "$arch" = "x64" ] && [ "$asset" != "mercury-linux-x64-baseline" ] \&& { [ "$smoke_status" -eq 132 ] || printf '%s' "$smoke_out" | grep -qi 'illegal instruction'; } \&& has_asset "$checksums_tmp" "mercury-linux-x64-baseline"; then@@ -333,19 +360,32 @@ Install the supported Node.js package instead:asset="mercury-linux-x64-baseline"fetch_to "${release_dir}/${asset}" "$tmp_dir/$asset" || die "Failed to download ${release_dir}/${asset}"[ "$(sha256_file "$tmp_dir/$asset")" = "$(checksum_for "$checksums_tmp" "$asset")" ] || die "Checksum mismatch for $asset"- mv "$tmp_dir/$asset" "$bin_path"- chmod +x "$bin_path"- if smoke_out=$("$bin_path" --version 2>&1); then smoke_status=0; else smoke_status=$?; fi+ mv "$tmp_dir/$asset" "$candidate_bin"+ chmod +x "$candidate_bin"+ if smoke_out=$("$candidate_bin" --version 2>&1); then smoke_status=0; else smoke_status=$?; fifiif [ "$smoke_status" -eq 0 ]; theninfo "Smoke test passed: $BIN_NAME --version → $smoke_out"else- err "The installed binary failed to run: $bin_path --version"+ err "The downloaded binary failed to run: $candidate_bin --version"printf '%s\n' "$smoke_out" | sed 's/^/ /' >&2- die "Mercury ${version_label} is installed but not runnable on ${os}-${arch}. Please report this at https://github.com/${REPO}/issues (include the lines above)."+ die "Mercury ${version_label} cannot run on ${os}-${arch}; the previous installation was preserved. Please report this at https://github.com/${REPO}/issues (include the lines above)."fi- rm -rf "$tmp_dir"+ promotion_started=1+ if [ -e "$bin_path" ] || [ -L "$bin_path" ]; then+ mv "$bin_path" "$transaction_dir/previous-binary"+ fi+ if [ -e "$bin_dir/web" ] || [ -L "$bin_dir/web" ]; then+ mv "$bin_dir/web" "$transaction_dir/previous-web"+ fi+ mv "$candidate_bin" "$bin_path"+ mv "$candidate_dir/web" "$bin_dir/web"+ promotion_complete=1+ info "Web dashboard assets installed"+ info "Installed to $bin_path"++ cleanup_installtrap - EXIT INT TERMPATH_UPDATED=0diff --git a/scripts/test-installer-helpers.ps1 b/scripts/test-installer-helpers.ps1new file mode 100644index 00000000..8fece401--- /dev/null+++ b/scripts/test-installer-helpers.ps1@@ -0,0 +1,63 @@+#Requires -Version 5+param([string]$LatestUri)+$ErrorActionPreference = 'Stop'++# Load only the resolver function, never the installer's main routine.+$installer = Join-Path $PSScriptRoot 'install.ps1'+$ast = [System.Management.Automation.Language.Parser]::ParseFile($installer, [ref]$null, [ref]$null)+$resolver = $ast.Find({ param($node) $node -is [System.Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Resolve-LatestVersion' }, $true)+. ([scriptblock]::Create($resolver.Extent.Text))+$Repo = 'cosmicstack-labs/mercury-agent'+function Die ([string]$msg) { throw $msg }+function Assert-Equal ($Actual, $Expected) {+ if ($Actual -ne $Expected) { throw "Expected '$Expected', received '$Actual'" }+}+function Invoke-WebRequest {+ param($Uri, $MaximumRedirection, [switch]$UseBasicParsing)+ Assert-Equal $Uri "https://github.com/$Repo/releases/latest"+ Assert-Equal $MaximumRedirection 5+ Assert-Equal $UseBasicParsing $true+ return $script:response+}++$tag = [uri]"https://github.com/$Repo/releases/tag/v9.9.9"+$script:response = [pscustomobject]@{ BaseResponse = [pscustomobject]@{ ResponseUri = $tag } }+Assert-Equal (Resolve-LatestVersion) '9.9.9'+$script:response = [pscustomobject]@{ BaseResponse = [pscustomobject]@{ RequestMessage = [pscustomobject]@{ RequestUri = $tag } } }+Assert-Equal (Resolve-LatestVersion) '9.9.9'++foreach ($badUri in @(+ $null,+ "https://example.com/$Repo/releases/tag/v9.9.9",+ "https://github.com/other/repo/releases/tag/v9.9.9",+ "https://github.com/$Repo/releases/latest",+ "https://github.com/$Repo/releases/tag/v9.9.9?untrusted=1",+ "https://github.com/$Repo/releases/tag/v9.9.9#fragment"+)) {+ $script:response = [pscustomobject]@{ BaseResponse = [pscustomobject]@{ RequestMessage = [pscustomobject]@{ RequestUri = $badUri } } }+ $rejected = $false+ try { Resolve-LatestVersion | Out-Null } catch { $rejected = $true }+ Assert-Equal $rejected $true+}+Remove-Item Function:Invoke-WebRequest++# Optional local fixture exercises this runtime's actual HTTP response type,+# including redirection, without fetching or installing a public release.+if ($LatestUri) { Assert-Equal (Resolve-LatestVersion -LatestUri $LatestUri) '9.9.9' }++$previousChannel = $env:MERCURY_CHANNEL+try {+ function Invoke-RestMethod {+ param($Uri)+ Assert-Equal $Uri 'https://mercuryagent.sh/install.ps1'+ return '$script:devRan = $env:MERCURY_CHANNEL'+ }+ $script:devRan = $null+ $wrapper = [scriptblock]::Create([IO.File]::ReadAllText((Join-Path $PSScriptRoot 'install-dev.ps1')))+ & $wrapper+ Assert-Equal $script:devRan 'dev'+} finally {+ $env:MERCURY_CHANNEL = $previousChannel+ Remove-Item Function:Invoke-RestMethod+}+Write-Output "Installer helper checks passed (PowerShell $($PSVersionTable.PSVersion))."diff --git a/scripts/test-installers.py b/scripts/test-installers.pynew file mode 100644index 00000000..f631c75a--- /dev/null+++ b/scripts/test-installers.py@@ -0,0 +1,204 @@+#!/usr/bin/env python3+"""Exercise real installers against disposable local releases; never touch user state.++Run with --shell sh on Linux/macOS, or --shell powershell/pwsh on Windows.+The Windows fixture uses the .NET Framework compiler present on CI runners.+"""+import argparse+import functools+import hashlib+import http.server+import os+from pathlib import Path+import platform+import shlex+import shutil+import subprocess+import tarfile+import tempfile+import threading+import unittest+++PARSER = argparse.ArgumentParser()+PARSER.add_argument('--shell', default='sh')+ARGS, UNITTEST_ARGS = PARSER.parse_known_args()+REPO = Path(__file__).resolve().parent.parent+WINDOWS = ARGS.shell != 'sh'+++class QuietHandler(http.server.SimpleHTTPRequestHandler):+ def log_message(self, *_args):+ pass++ def guess_type(self, path):+ return 'application/octet-stream'+++class InstallerTests(unittest.TestCase):+ def setUp(self):+ self.temp = tempfile.TemporaryDirectory(prefix='mercury installer ')+ self.addCleanup(self.temp.cleanup)+ self.root = Path(self.temp.name)+ self.release = self.root / 'releases' / 'v9.9.9'+ self.release.mkdir(parents=True)+ self.prefix = self.root / 'existing installation'+ self.bin = self.prefix / 'bin'+ self.bin.mkdir(parents=True)+ self.name = 'mercury.exe' if WINDOWS else 'mercury'+ self.installed = self.bin / self.name+ self.stub(self.installed, 'old-version')+ (self.bin / 'web').mkdir()+ (self.bin / 'web' / 'index.html').write_text('old-dashboard')+ self.old_binary = self.installed.read_bytes()+ os_name = 'macos' if platform.system() == 'Darwin' else 'linux'+ arch = 'arm64' if platform.machine().lower() in ('arm64', 'aarch64') else 'x64'+ self.asset = 'mercury-win-x64.exe' if WINDOWS else f'mercury-{os_name}-{arch}'+ self.baseline = 'mercury-win-x64-baseline.exe' if WINDOWS else 'mercury-linux-x64-baseline'+ (self.release / 'web').mkdir()+ (self.release / 'web' / 'index.html').write_text('new-dashboard')+ with tarfile.open(self.release / 'web.tar.gz', 'w:gz') as archive:+ archive.add(self.release / 'web', arcname='web')+ handler = functools.partial(QuietHandler, directory=str(self.release.parent))+ server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), handler)+ self.addCleanup(server.server_close)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ self.addCleanup(server.shutdown)+ self.env = {key: value for key, value in os.environ.items() if not key.startswith('MERCURY_')}+ self.env.update(MERCURY_VERSION='9.9.9', MERCURY_NO_PATH='1', MERCURY_NO_PAUSE='1',+ MERCURY_INSTALL=str(self.prefix),+ MERCURY_DOWNLOAD_BASE=f'http://127.0.0.1:{server.server_port}')+ cpuinfo = self.root / 'cpuinfo'+ cpuinfo.write_text('flags: avx2\n')+ self.env['MERCURY_CPUINFO'] = str(cpuinfo)++ def stub(self, path, version, status=0):+ if WINDOWS:+ source = self.root / 'stub.cs'+ source.write_text('class P { static int Main(string[] a) { '+ f'System.Console.WriteLine("{version}"); return {status}; }} }}')+ csc = Path(os.environ['WINDIR']) / 'Microsoft.NET/Framework64/v4.0.30319/csc.exe'+ subprocess.run([str(csc), '/nologo', '/out:' + str(path), str(source)], check=True,+ capture_output=True, text=True)+ else:+ path.write_text(f'#!/bin/sh\necho {shlex.quote(version)}\nexit {status}\n')+ path.chmod(0o755)++ def install(self, fail_promotion=False, fail_restore=False):+ assets = sorted(path for path in self.release.iterdir() if path.is_file())+ (self.release / 'checksums.txt').write_text(''.join(+ f'{hashlib.sha256(path.read_bytes()).hexdigest()} {path.name}\n'+ for path in assets if path.name != 'checksums.txt'))+ if fail_restore:+ self.env['MERCURY_TEST_RESTORE_FAILURE'] = '1'+ if WINDOWS:+ command = [ARGS.shell, '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', str(REPO / 'scripts/install.ps1')]+ if fail_promotion:+ wrapper = self.root / 'failure.ps1'+ # Fail only the new dashboard's promotion; all actual moves and+ # recovery still use the real filesystem/Move-Item cmdlet.+ wrapper.write_text("""function Move-Item {+ param($Path, $Destination, [switch]$Force)+ if ($Destination -eq (Join-Path $env:MERCURY_INSTALL 'bin/web') -and $Path -notlike '*previous-web') {+ throw 'injected dashboard promotion failure'+ }+ if ($env:MERCURY_TEST_RESTORE_FAILURE -eq '1' -and $Path -like '*previous-binary') {+ throw 'injected binary restoration failure'+ }+ Microsoft.PowerShell.Management\\Move-Item -Path $Path -Destination $Destination -Force:$Force+}+& $env:MERCURY_TEST_INSTALLER+""")+ self.env['MERCURY_TEST_INSTALLER'] = str(REPO / 'scripts/install.ps1')+ command[-1] = str(wrapper)+ else:+ command = ['sh', str(REPO / 'scripts/install.sh')]+ if fail_promotion:+ wrappers = self.root / 'wrappers'+ wrappers.mkdir()+ mv = wrappers / 'mv'+ real_mv = shutil.which('mv')+ mv.write_text(f'''#!/bin/sh+for last do :; done+if [ "$last" = "$MERCURY_INSTALL/bin/web" ] && [ "${{1##*/}}" != previous-web ]; then+ echo 'injected dashboard promotion failure' >&2+ exit 42+fi+if [ "${{MERCURY_TEST_RESTORE_FAILURE:-}}" = 1 ] && [ "${{1##*/}}" = previous-binary ]; then+ echo 'injected binary restoration failure' >&2+ exit 43+fi+exec {shlex.quote(real_mv)} "$@"+''')+ mv.chmod(0o755)+ self.env['PATH'] = str(wrappers) + os.pathsep + self.env['PATH']+ return subprocess.run(command, env=self.env, capture_output=True, text=True, timeout=45)++ def assert_preserved(self, result):+ self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertEqual(self.installed.read_bytes(), self.old_binary, result.stdout + result.stderr)+ self.assertEqual((self.bin / 'web' / 'index.html').read_text(), 'old-dashboard')++ def test_nonrunnable_update_preserves_working_installation(self):+ self.stub(self.release / self.asset, 'cannot-start', 42)+ self.assert_preserved(self.install())++ def test_failed_baseline_preserves_working_installation(self):+ if not WINDOWS and self.asset != 'mercury-linux-x64':+ self.skipTest('baseline fallback is x64 Linux/Windows only')+ self.stub(self.release / self.asset, 'illegal instruction', -1073741795 if WINDOWS else 132)+ self.stub(self.release / self.baseline, 'baseline-cannot-start', 42)+ result = self.install()+ self.assertIn('switching to the baseline build', result.stdout)+ self.assert_preserved(result)++ def test_dashboard_promotion_failure_restores_both_previous_artifacts(self):+ self.stub(self.release / self.asset, '9.9.9')+ result = self.install(fail_promotion=True)+ self.assertIn('injected dashboard promotion failure', result.stdout + result.stderr)+ self.assert_preserved(result)++ def test_failed_first_install_leaves_no_partial_artifacts(self):+ self.installed.unlink()+ shutil.rmtree(self.bin / 'web')+ self.stub(self.release / self.asset, '9.9.9')+ result = self.install(fail_promotion=True)+ self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertFalse(self.installed.exists())+ self.assertFalse((self.bin / 'web').exists())+ self.assertEqual(list(self.bin.iterdir()), [])++ def test_failed_recovery_keeps_backup_for_manual_restoration(self):+ self.stub(self.release / self.asset, '9.9.9')+ result = self.install(fail_promotion=True, fail_restore=True)+ self.assertNotEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertIn('Recovery files:', result.stdout + result.stderr)+ backups = list(self.bin.glob('.mercury-install*/previous-binary'))+ self.assertEqual(len(backups), 1)+ self.assertEqual(backups[0].read_bytes(), self.old_binary)+ self.assertEqual((self.bin / 'web' / 'index.html').read_text(), 'old-dashboard')++ def test_successful_baseline_is_validated_and_promoted(self):+ if not WINDOWS and self.asset != 'mercury-linux-x64':+ self.skipTest('baseline fallback is x64 Linux/Windows only')+ self.stub(self.release / self.asset, 'illegal instruction', -1073741795 if WINDOWS else 132)+ self.stub(self.release / self.baseline, '9.9.9-baseline')+ result = self.install()+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ self.assertIn('switching to the baseline build', result.stdout)+ self.assertEqual(subprocess.check_output([str(self.installed), '--version'], text=True).strip(), '9.9.9-baseline')+ self.assertEqual((self.bin / 'web' / 'index.html').read_text(), 'new-dashboard')++ def test_successful_update_replaces_both_artifacts(self):+ self.stub(self.release / self.asset, '9.9.9')+ result = self.install()+ self.assertEqual(result.returncode, 0, result.stdout + result.stderr)+ actual = subprocess.check_output([str(self.installed), '--version'], text=True).strip()+ self.assertEqual(actual, '9.9.9')+ self.assertEqual((self.bin / 'web' / 'index.html').read_text(), 'new-dashboard')+ self.assertEqual(sorted(path.name for path in self.bin.iterdir()), [self.name, 'web'])+++if __name__ == '__main__':+ unittest.main(argv=[__file__] + UNITTEST_ARGS)diff --git a/website/docs/getting-started/installation.mdx b/website/docs/getting-started/installation.mdxindex 2a46130e..18dc18b1 100644--- a/website/docs/getting-started/installation.mdx+++ b/website/docs/getting-started/installation.mdx@@ -4,7 +4,7 @@ title: Installationslug: /----Mercury runs anywhere Node.js 22+ runs, plus everywhere a single binary can live — including phones via Termux.+Mercury offers standalone releases for specific desktop and server targets, plus an npm package requiring Node.js 22 or newer. Android uses the npm route through Termux.## The easiest way: Mercury Desktop@@ -15,14 +15,14 @@ The rest of this page installs the Mercury runtime from the command line: for se## Pick your platform- **[macOS](/docs/getting-started/platforms/macos)** — `curl | sh` installer, Homebrew-style PATH setup, Apple Silicon & Intel binaries.-- **[Linux](/docs/getting-started/platforms/linux)** — works on any glibc distro; static x64/arm64 binaries.+- **[Linux](/docs/getting-started/platforms/linux)** — standalone x64/arm64 binaries for glibc-based systems.- **[Windows](/docs/getting-started/platforms/windows)** — PowerShell installer, native `.exe`, optional WSL path.- **[Termux & lightweight devices](/docs/getting-started/platforms/termux)** — Android (Termux), iSH, Alpine containers, Raspberry Pi.- **[Cloud Instance](/docs/getting-started/platforms/cloud-instance)** — hosted Mercury Code via [Atomic Bot](https://atomicbot.ai/?utm_source=agent). No install needed.## Two install paths-Every platform supports two routes — pick whichever fits.+Choose a route supported by your operating system and CPU.### 1. Standalone binary (no Node.js required)@@ -42,9 +42,27 @@ The installer:- Detects your OS and CPU architecture (macOS arm64/x64, Linux x64/arm64, Windows x64).- Resolves the latest GitHub release.-- Verifies the SHA-256 checksum against `checksums.txt`.+- Verifies the SHA-256 checksum against `checksums.txt` and tests the staged binary with `--version` before replacing an existing installation.- Installs to `~/.mercury/bin/mercury` (or `%USERPROFILE%\.mercury\bin\mercury.exe`) and updates your shell `PATH`.+#### Standalone support limits++| System | Published runtime targets | Other environments |+|---|---|---|+| macOS | arm64, x64 | No 32-bit binary |+| Linux | glibc-based x64, arm64 | No musl/Alpine, Android/bionic, or 32-bit binary |+| Windows | x64, including an older-CPU baseline build | No native Windows arm64 or 32-bit binary |++Linux x64 also has a baseline build for CPUs without AVX2. The installer can select or fall back to it, but the binary still needs a compatible operating system and libc. A baseline build does not add support for every CPU or distribution.++For Alpine, Termux, Windows on ARM, or another target without a published binary, consider the [npm route](#2-npm-package-requires-nodejs-22) if a compatible Node.js 22+ build and the package's dependencies are available. The npm package is not a guarantee of support on every machine. See the platform guides for requirements.++#### Failed installer updates++The command-line installers check the downloaded binary and dashboard before replacing existing files, including a baseline fallback when needed. If a handled file-promotion failure occurs, they attempt to restore both previous artifacts. If restoration fails, the error reports a recovery directory containing the remaining backups; preserve it until recovery is complete.++These steps are not an atomic transaction across the binary and dashboard. Power loss, forced termination, filesystem failures, and concurrent installers can interrupt recovery. Keep an independent backup for installations you rely on. This behavior applies to the standalone command-line installers; npm and Desktop updates have their own update paths.+#### Environment variables| Variable | Default | Purpose |diff --git a/website/docs/getting-started/platforms/linux.mdx b/website/docs/getting-started/platforms/linux.mdxindex b29880ff..7d6c0c32 100644--- a/website/docs/getting-started/platforms/linux.mdx+++ b/website/docs/getting-started/platforms/linux.mdx@@ -4,7 +4,7 @@ title: Linuxsidebar_label: Linux----Mercury runs on any modern Linux distro with glibc ≥ 2.31 (Ubuntu 20.04+, Debian 11+, Fedora 34+, Arch, etc.) on **x86_64** or **arm64**.+Mercury publishes standalone Linux binaries for **x86_64** and **arm64** on glibc-based systems. Alpine/musl, Android/bionic, and 32-bit systems need another installation route; see the [support limits](../installation.mdx#standalone-support-limits).## Quickest install (recommended)@@ -22,7 +22,7 @@ mercury --version```:::note Older x86-64 CPUs-The default Linux x64 build uses AVX2. On a CPU without it (Intel before 2013, some VMs) the installer picks the **baseline** build automatically — from `/proc/cpuinfo`, or by switching after an `Illegal instruction` crash. To force it: `MERCURY_ASSET=mercury-linux-x64-baseline curl -fsSL https://mercuryagent.sh/install.sh | sh`.+The default Linux x64 build uses AVX2. On a CPU without it (Intel before 2013, some VMs) the installer picks the **baseline** build automatically — from `/proc/cpuinfo`, or by switching after an `Illegal instruction` crash. To force it: `curl -fsSL https://mercuryagent.sh/install.sh | MERCURY_ASSET=mercury-linux-x64-baseline sh`.:::## Via npm (if you already have Node)@@ -46,7 +46,7 @@ Check yours:uname -m # x86_64 or aarch64```-For armv7 (32-bit Pi, older boards), use the [npm route](#via-npm-if-you-already-have-node) — there's no prebuilt 32-bit ARM binary yet.+There is no prebuilt 32-bit ARM binary. The [npm route](#via-npm-if-you-already-have-node) requires a compatible Node.js 22+ build and dependencies for the device; older boards are not covered by the standard binary releases.## Pinning a versiondiff --git a/website/docs/getting-started/platforms/termux.mdx b/website/docs/getting-started/platforms/termux.mdxindex 0aa7f90d..59b56fd2 100644--- a/website/docs/getting-started/platforms/termux.mdx+++ b/website/docs/getting-started/platforms/termux.mdx@@ -4,7 +4,7 @@ title: Termux & Lightweight Devicessidebar_label: Termux & Mobile----Mercury runs on **Android via [Termux](https://termux.dev/)**, giving you a real coding agent in your pocket. It also works in other minimal environments like iSH (iOS), Alpine containers, and Raspberry Pi.+Mercury runs on **Android via [Termux](https://termux.dev/)**. Other lightweight environments require a compatible Node.js 22+ build and Mercury dependencies; availability varies by operating system and CPU.## Termux (Android)@@ -105,7 +105,7 @@ npm i -g @cosmicstack/mercury-agent@latest## iSH (iOS)-[iSH](https://ish.app/) runs an Alpine Linux user-space on iOS. Mercury works there via npm:+[iSH](https://ish.app/) runs an Alpine Linux user-space on iOS. Its emulated x86 environment is not covered by Mercury's standalone releases. Only try the npm route if Node.js 22+ and the dependencies are available:```shapk add nodejs npm@@ -129,17 +129,11 @@ This applies to Docker images based on `alpine:*` as well.## Raspberry Pi- **64-bit Pi OS (Pi 3/4/5)**: the standard [Linux installer](./linux.mdx) works — pulls `mercury-linux-arm64`.-- **32-bit Pi OS or armv6 (Pi Zero, Pi 1)**: no prebuilt binary; install via npm:-- ```bash- curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -- sudo apt install -y nodejs- npm i -g @cosmicstack/mercury-agent- ```+- **32-bit Pi OS or armv6 (Pi Zero, Pi 1)**: no prebuilt binary. The npm route requires a compatible Node.js 22+ build for the device and may require compiling native dependencies. Do not install Node.js 20 as a fallback; it does not meet Mercury's minimum version.## Other lightweight environments-If your platform isn't listed and the binary doesn't run (`Exec format error`, missing libc), the npm route always works as long as Node.js 20+ is available. If Node isn't packaged for your OS, see [Build From Source](../build-from-source).+If a binary reports `Exec format error` or a missing libc, check the [standalone support limits](../installation.mdx#standalone-support-limits). The npm route requires Node.js 22+ and compatible dependencies; it is not guaranteed on unlisted systems. [Building from source](../build-from-source) also requires a compatible runtime.## Next stepsdiff --git a/website/docs/getting-started/platforms/windows.mdx b/website/docs/getting-started/platforms/windows.mdxindex 8e725f2d..a190a0db 100644--- a/website/docs/getting-started/platforms/windows.mdx+++ b/website/docs/getting-started/platforms/windows.mdx@@ -4,11 +4,11 @@ title: Windowssidebar_label: Windows----Mercury runs natively on Windows 10 (build 1809+) and Windows 11, on **x64**. Native arm64 binaries are not yet published — on Windows on ARM, use WSL or the npm route.+Mercury runs natively on Windows 10 (build 1809+) and Windows 11, on **x64**. Native arm64 and 32-bit Windows binaries are not published. On Windows on ARM, consider WSL or the npm route with a compatible Node.js 22+ build.## Quickest install (recommended)-Open PowerShell (any version) and run:+Open Windows PowerShell 5.1 or PowerShell 7 and run:```powershellirm https://mercuryagent.sh/install.ps1 | iex