Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
fix(upgrade): stop `ix upgrade` destroying the CLI on Windows (#337)
KageBinarybbe950d80651
diff --git a/ix-cli/src/cli/__tests__/upgrade-archive-shape.test.ts b/ix-cli/src/cli/__tests__/upgrade-archive-shape.test.tsnew file mode 100644index 00000000..4d41dd26--- /dev/null+++ b/ix-cli/src/cli/__tests__/upgrade-archive-shape.test.ts@@ -0,0 +1,158 @@+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { mkdtempSync, mkdirSync, writeFileSync, rmSync, existsSync, readFileSync } from "node:fs";+import { join } from "node:path";+import { tmpdir } from "node:os";++import { soleChildDir, swapInStagedTree, sweepUpgradeOrphans } from "../commands/upgrade.js";++let root: string;++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), "ix-upgrade-test-"));+});++afterEach(() => {+ rmSync(root, { recursive: true, force: true });+});++describe("soleChildDir", () => {+ it("finds the single nested directory a Windows release zip extracts to", () => {+ // Windows zips wrap everything in ix-<version>-<platform>/; the launcher+ // shim has to point inside it, so the name is read back rather than assumed.+ const nested = join(root, "ix-0.9.0-windows-amd64");+ mkdirSync(nested, { recursive: true });+ expect(soleChildDir(root)).toBe(nested);+ });++ it("ignores loose files beside the directory", () => {+ const nested = join(root, "ix-0.9.0-windows-amd64");+ mkdirSync(nested, { recursive: true });+ writeFileSync(join(root, "README.txt"), "x");+ expect(soleChildDir(root)).toBe(nested);+ });++ it("returns null when the layout is already flat (POSIX tarball)", () => {+ // --strip-components=1 leaves several top-level dirs, so there is no single+ // child to descend into and the caller must use the directory as-is.+ mkdirSync(join(root, "cli"), { recursive: true });+ mkdirSync(join(root, "core-ingestion"), { recursive: true });+ mkdirSync(join(root, "compass"), { recursive: true });+ expect(soleChildDir(root)).toBeNull();+ });++ it("returns null for an empty or missing directory", () => {+ expect(soleChildDir(root)).toBeNull();+ expect(soleChildDir(join(root, "does-not-exist"))).toBeNull();+ });++ it("propagates a read failure instead of reporting it as a flat layout", () => {+ // Swallowing anything other than "not there" would surface downstream as+ // "the release archive did not contain the expected entry point", pointing+ // the user at GitHub for what is a fault on their own machine. A plain file+ // gives a deterministic non-ENOENT readdir failure (ENOTDIR) on every OS.+ const notADir = join(root, "regular-file");+ writeFileSync(notADir, "x");+ expect(() => soleChildDir(notADir)).toThrow();+ });+});++describe("swapInStagedTree", () => {+ const entry = (base: string, ver: string) =>+ join(base, "cli", `ix-${ver}-windows-amd64`, "cli", "dist", "cli", "main.js");++ function seedInstall(home: string, ver: string) {+ mkdirSync(join(home, "cli", `ix-${ver}-windows-amd64`, "cli", "dist", "cli"), { recursive: true });+ writeFileSync(entry(home, ver), `// ${ver}\n`);+ }++ function seedStaging(home: string, name: string, ver: string) {+ const staging = join(home, name);+ mkdirSync(join(staging, `ix-${ver}-windows-amd64`, "cli", "dist", "cli"), { recursive: true });+ writeFileSync(join(staging, `ix-${ver}-windows-amd64`, "cli", "dist", "cli", "main.js"), `// ${ver}\n`);+ return staging;+ }++ it("swaps in the new version and removes the backup on success", () => {+ seedInstall(root, "0.8.1");+ const staging = seedStaging(root, ".cli-staging-1", "0.9.0");+ const backup = join(root, ".cli-backup-1");++ swapInStagedTree(join(root, "cli"), staging, backup);++ expect(existsSync(entry(root, "0.9.0"))).toBe(true);+ expect(existsSync(entry(root, "0.8.1"))).toBe(false);+ expect(existsSync(backup)).toBe(false);+ expect(existsSync(staging)).toBe(false);+ });++ it("installs cleanly when there is no previous install to move aside", () => {+ const staging = seedStaging(root, ".cli-staging-2", "0.9.0");+ swapInStagedTree(join(root, "cli"), staging, join(root, ".cli-backup-2"));+ expect(existsSync(entry(root, "0.9.0"))).toBe(true);+ });++ it("restores the previous install when the staged tree cannot be moved in", () => {+ // The regression this guards: if the second rename fails, the old install+ // has already been moved aside and must be put back rather than left gone.+ seedInstall(root, "0.8.1");+ const backup = join(root, ".cli-backup-3");+ const missingStaging = join(root, ".cli-staging-does-not-exist");++ expect(() => swapInStagedTree(join(root, "cli"), missingStaging, backup)).toThrow();++ expect(existsSync(entry(root, "0.8.1"))).toBe(true);+ expect(existsSync(backup)).toBe(false);+ });++ it("completes even when a previous run left a backup directory behind", () => {+ // The swap is complete once the rename lands; clearing the previous tree is+ // housekeeping and must never fail the upgrade. Aborting there would skip+ // the launcher refresh and leave the shim aimed at a directory that no+ // longer exists — the brick this whole path exists to prevent.+ seedInstall(root, "0.8.1");+ const staging = seedStaging(root, ".cli-staging-4", "0.9.0");+ const backup = join(root, ".cli-backup-4");+ mkdirSync(join(backup, "stale", "junk"), { recursive: true });+ writeFileSync(join(backup, "stale", "junk", "leftover.js"), "// from an earlier failed run\n");++ expect(() => swapInStagedTree(join(root, "cli"), staging, backup)).not.toThrow();++ expect(existsSync(entry(root, "0.9.0"))).toBe(true);+ expect(existsSync(entry(root, "0.8.1"))).toBe(false);+ expect(existsSync(backup)).toBe(false);+ });+});++describe("sweepUpgradeOrphans", () => {+ it("restores the install when a previous run died between the two renames", () => {+ // Ctrl-C in that window leaves no ~/.ix/cli at all, so the user cannot run+ // `ix upgrade` to repair it — the next run has to put it back itself.+ const installDir = join(root, "cli");+ const backup = join(root, ".cli-backup-999");+ mkdirSync(join(backup, "cli", "dist", "cli"), { recursive: true });+ writeFileSync(join(backup, "cli", "dist", "cli", "main.js"), "// 0.8.1\n");++ sweepUpgradeOrphans(root, installDir);++ expect(existsSync(join(installDir, "cli", "dist", "cli", "main.js"))).toBe(true);+ expect(existsSync(backup)).toBe(false);+ });++ it("reclaims staging and backup leftovers without touching a healthy install", () => {+ const installDir = join(root, "cli");+ mkdirSync(join(installDir, "cli", "dist", "cli"), { recursive: true });+ writeFileSync(join(installDir, "cli", "dist", "cli", "main.js"), "// live\n");+ mkdirSync(join(root, ".cli-staging-111"), { recursive: true });+ mkdirSync(join(root, ".cli-backup-222"), { recursive: true });++ sweepUpgradeOrphans(root, installDir);++ expect(existsSync(join(root, ".cli-staging-111"))).toBe(false);+ expect(existsSync(join(root, ".cli-backup-222"))).toBe(false);+ expect(readFileSync(join(installDir, "cli", "dist", "cli", "main.js"), "utf-8")).toBe("// live\n");+ });++ it("is a no-op when IX_HOME does not exist yet", () => {+ expect(() => sweepUpgradeOrphans(join(root, "nope"), join(root, "nope", "cli"))).not.toThrow();+ });+});diff --git a/ix-cli/src/cli/commands/upgrade.ts b/ix-cli/src/cli/commands/upgrade.tsindex 5554b3ef..3c134707 100644--- a/ix-cli/src/cli/commands/upgrade.ts+++ b/ix-cli/src/cli/commands/upgrade.ts@@ -1,7 +1,7 @@import { Command } from "commander";import { execFileSync } from "child_process";-import { readFileSync, writeFileSync, existsSync, mkdirSync, rmSync, mkdtempSync, lstatSync } from "fs";-import { dirname, join } from "path";+import { readFileSync, writeFileSync, existsSync, mkdirSync, rmSync, mkdtempSync, lstatSync, renameSync, readdirSync } from "fs";+import { basename, dirname, join } from "path";import { fileURLToPath } from "url";import { homedir, tmpdir } from "os";import chalk from "chalk";@@ -130,6 +130,285 @@ function getTrackedVersion(versionFile: string): string {}}+/**+ * Extract a .zip on Windows, trying every extractor a Windows box might have.+ *+ * This used to call `unzip` alone, which is NOT present on stock Windows — it+ * only exists if the user happens to have Git Bash or MSYS. Combined with the+ * install directory being deleted before extraction, a missing `unzip` removed+ * the user's CLI and installed nothing in its place.+ *+ * Order matters: bsdtar ships with Windows 10 1803+ and reads zip archives, so+ * it is both the most likely to exist and the fastest. PowerShell is always+ * present. `unzip` stays last for MSYS shells where it may be the only one.+ */+function extractZipOnWindows(zipPath: string, destDir: string): void {+ const toUnixPath = (p: string): string => {+ try {+ return execFileSync("cygpath", ["-u", p], { encoding: "utf-8" }).trim();+ } catch {+ return p;+ }+ };++ // PowerShell single-quoted strings escape a quote by doubling it.+ const psQuote = (p: string): string => `'${p.replace(/'/g, "''")}'`;++ const attempts: Array<{ cmd: string; args: string[] }> = [+ { cmd: "tar", args: ["-xf", zipPath, "-C", destDir] },+ {+ cmd: "powershell",+ args: [+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ // $ErrorActionPreference is load-bearing. Expand-Archive reports+ // unreadable entries and per-file access denials as *non-terminating*+ // errors, and powershell.exe still exits 0 for those — so without this+ // a half-extracted tree reads as success and the fallback below is+ // never tried.+ `$ErrorActionPreference='Stop'; Expand-Archive -LiteralPath ${psQuote(zipPath)} ` ++ `-DestinationPath ${psQuote(destDir)} -Force`,+ ],+ },+ { cmd: "unzip", args: ["-q", "-o", toUnixPath(zipPath), "-d", toUnixPath(destDir)] },+ ];++ const failures: string[] = [];+ for (const { cmd, args } of attempts) {+ // Start each attempt from an empty destination. A previous extractor may+ // have left a partial tree behind, and merging a second attempt into it+ // would produce a directory that looks complete and is not.+ rmSync(destDir, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });+ mkdirSync(destDir, { recursive: true });+ try {+ // Capture stderr rather than discarding it: the aggregated message below+ // is the only diagnostic the user ever sees, and "Command failed:+ // powershell ..." on its own is unactionable.+ execFileSync(cmd, args, { stdio: ["ignore", "ignore", "pipe"] });+ } catch (err) {+ const e = err as Error & { stderr?: Buffer | string };+ const detail = e.stderr ? String(e.stderr).trim() : "";+ failures.push(`${cmd}: ${detail || e.message}`);+ continue;+ }+ // An extractor that exits 0 without producing anything has not succeeded.+ if (readdirSync(destDir).length === 0) {+ failures.push(`${cmd}: exited 0 but extracted nothing`);+ continue;+ }+ return;+ }+ throw new Error(`no usable zip extractor found (${failures.join("; ")})`);+}++/**+ * Delete a directory without letting the failure escape.+ *+ * Used only for housekeeping — staging leftovers and the previous install once+ * the swap has already succeeded. On Windows `rmSync` defaults to no retries+ * and an AV or indexer handle on a tree the process was running from moments+ * ago is enough to throw, so the retries matter and the failure must not.+ */+function rmQuiet(target: string): void {+ try {+ rmSync(target, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });+ } catch {+ /* a leftover directory is reclaimed by sweepUpgradeOrphans on the next run */+ }+}++/**+ * The single top-level directory an archive extracted into, if there is exactly+ * one. Windows release zips nest everything under `ix-<version>-<platform>/`,+ * and reading it back beats assuming the name — the shim has to point inside it.+ */+export function soleChildDir(dir: string): string | null {+ let entries;+ try {+ entries = readdirSync(dir, { withFileTypes: true });+ } catch (err) {+ // A directory that is not there genuinely has no sole child. Anything else+ // — EACCES from a group-policy ACL, EMFILE — is a fault on this machine,+ // and swallowing it would surface downstream as "the release archive is+ // malformed", pointing the user at the wrong thing entirely.+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;+ throw err;+ }+ const dirs = entries.filter((e) => e.isDirectory());+ return dirs.length === 1 && dirs[0] ? join(dir, dirs[0].name) : null;+}++/**+ * Characters we are willing to interpolate into a launcher script.+ *+ * The version directory is read back out of the downloaded archive rather than+ * derived from the VERSION_RE-validated tag, so it has not been through that+ * barrier. `cmd.exe` splits a batch line on `&` and expands `%VAR%`, so a+ * directory name carrying either would change what the launcher runs.+ */+const SAFE_DIR_NAME = /^[A-Za-z0-9._-]+$/;++/**+ * Replace `installDir` with the tree staged in `stagingDir`.+ *+ * Cleanup of the previous install deliberately sits *outside* the failure+ * boundary. Once the second rename returns, the upgrade has happened; deleting+ * the old tree is housekeeping, and on Windows it is the single step most+ * likely to fail. Letting that failure propagate would abort the caller before+ * it repoints the launcher shims, leaving them aimed at a directory that no+ * longer exists — precisely the brick this path exists to prevent.+ *+ * Throws only when the install is still intact (or has been put back).+ */+export function swapInStagedTree(installDir: string, stagingDir: string, backupDir: string): void {+ rmQuiet(backupDir);+ if (existsSync(installDir)) renameSync(installDir, backupDir);+ try {+ renameSync(stagingDir, installDir);+ } catch (err) {+ try {+ if (existsSync(backupDir) && !existsSync(installDir)) renameSync(backupDir, installDir);+ } catch {+ /* caller reports where the surviving copy is */+ }+ throw err;+ }+ rmQuiet(backupDir);+}++/**+ * Reclaim `.cli-staging-*` / `.cli-backup-*` directories left behind by an+ * upgrade that died mid-swap, and put the install back if it is missing.+ *+ * The swap has a window between the two renames in which no install exists.+ * Ctrl-C, a killed process or a lost machine inside that window terminates+ * without running any catch, so in-process recovery cannot help — and with no+ * `ix` on disk the user cannot run `ix upgrade` to repair it either.+ */+export function sweepUpgradeOrphans(ixHome: string, installDir: string): void {+ let entries: string[];+ try {+ entries = readdirSync(ixHome);+ } catch {+ return;+ }+ const backups = entries.filter((e) => e.startsWith(".cli-backup-")).sort();+ const lastBackup = backups[backups.length - 1];++ if (!existsSync(installDir) && lastBackup) {+ try {+ renameSync(join(ixHome, lastBackup), installDir);+ console.log(` Recovered the previous install from ${lastBackup} (an earlier upgrade was interrupted).`);+ } catch {+ /* fall through to the sweep; nothing is made worse by leaving it */+ }+ }+ for (const name of entries) {+ if (name.startsWith(".cli-staging-") || name.startsWith(".cli-backup-")) {+ const target = join(ixHome, name);+ if (target !== installDir && existsSync(target)) rmQuiet(target);+ }+ }+}++/**+ * Repoint the Windows launchers at the newly installed tree.+ *+ * Only Windows needs this. install.sh writes a *version-encoded* path on+ * Windows (`$INSTALL_DIR/ix-<VERSION>-windows-amd64/cli/dist/cli/main.js`) but+ * on POSIX writes `exec "$INSTALL_DIR/ix"`, which has no version in it and so+ * never goes stale — rewriting that one would be churn at best, and at worst+ * fails on a root-owned /usr/local/bin that the user cannot write.+ *+ * On Windows three shims exist, not two:+ * - `%IX_HOME%\bin\ix.cmd` written by install.ps1+ * - `/usr/local/bin/ix` written by install.sh when that dir is writable+ * - `~/.local/bin/ix` written by install.sh otherwise+ *+ * install.sh picks one of the latter two via pick_bin_dir() and *deletes* the+ * other as a stale duplicate, so refreshing a hard-coded `~/.local/bin/ix`+ * recreates the copy it removed while leaving the live one pointing into the+ * version directory the swap just deleted. Refresh whichever already exist.+ *+ * Returns a list of human-readable problems; empty means everything on PATH now+ * points at the new install.+ */+function refreshLaunchers(installDir: string, installedRoot: string, isWindows: boolean): string[] {+ if (!isWindows) return [];+ const problems: string[] = [];+ const entryPath = join(installedRoot, "cli", "dist", "cli", "main.js");++ {+ const cmdShim = join(IX_HOME, "bin", "ix.cmd");+ // Mirror install.ps1's *relative* form (`%~dp0..\cli\<dir>\ix.cmd`) rather+ // than embedding an absolute path. %~dp0 is expanded by cmd.exe at run+ // time, so the user's profile directory never has to survive a round trip+ // through a batch file's encoding — an absolute path written as "ascii"+ // silently corrupts any non-ASCII home (C:\Users\José\...) and produces a+ // launcher that points nowhere.+ const dirName = installedRoot === installDir ? "" : basename(installedRoot);+ if (dirName && !SAFE_DIR_NAME.test(dirName)) {+ problems.push(`refused to write ${cmdShim}: unsafe directory name ${JSON.stringify(dirName)}`);+ } else {+ const inner = dirName ? `%~dp0..\\cli\\${dirName}\\ix.cmd` : `%~dp0..\\cli\\ix.cmd`;+ try {+ // Leave a contributor's dev shim alone. scripts/dev/setup.sh points+ // this same file at their working tree; silently repointing it at the+ // released build makes their rebuilds appear to do nothing. This is the+ // convention the @ix/pro refresh below already follows.+ //+ // Read-or-default rather than existsSync-then-read: guarding a write+ // with an existence check is a TOCTOU (CodeQL js/file-system-race).+ let existing = "";+ try {+ existing = readFileSync(cmdShim, "utf-8");+ } catch {+ /* no shim yet — install.ps1 has not run on this machine */+ }+ if (existing && !existing.includes("%~dp0..\\cli\\") && !existing.includes(installDir)) {+ console.log(" Left your dev ix.cmd shim untouched (re-run scripts/dev/setup.sh to repoint it).");+ } else {+ mkdirSync(dirname(cmdShim), { recursive: true });+ writeFileSync(cmdShim, `@echo off\r\n"${inner}" %*\r\n`, "ascii");+ }+ } catch (err) {+ problems.push(`${cmdShim}: ${(err as Error).message}`);+ }+ }+ }++ // The bash shim install.sh writes under Git Bash / MSYS, which also carries+ // the version-encoded path. pick_bin_dir() puts it in whichever of these two+ // it chose, so refresh the one that is actually there.+ let jsPath = entryPath;+ try {+ jsPath = execFileSync("cygpath", ["-u", entryPath], { encoding: "utf-8" }).trim();+ } catch {+ /* use the windows path */+ }+ const body = `#!/usr/bin/env bash\nexec node "${jsPath}" "$@"\n`;+ const candidates = ["/usr/local/bin/ix", join(homedir(), ".local", "bin", "ix")];++ for (const target of candidates) {+ // Probe by reading rather than existsSync-then-write, which is a TOCTOU+ // (CodeQL js/file-system-race). Only refresh a shim that is already there:+ // creating one install.sh chose not to create would put a second,+ // competing `ix` on PATH.+ try {+ readFileSync(target);+ } catch {+ continue;+ }+ try {+ writeFileSync(target, body, { mode: 0o755 });+ } catch (err) {+ problems.push(`${target}: ${(err as Error).message}`);+ }+ }+ return problems;+}+function detectPlatform(): string {let os: string;if (process.platform === "darwin") os = "darwin";@@ -266,46 +545,114 @@ export function registerUpgradeCommand(program: Command): void {}console.log("Installing...");++ // Extract into a staging directory beside the install, verify the+ // result actually runs, and only then swap it in. The previous order+ // was rmSync(installDir) *first*, so any extraction failure left the+ // user with no CLI at all — and on Windows that failure was the+ // default case, because the extractor it called (`unzip`) is not+ // present on a stock Windows box. Staging lives under IX_HOME rather+ // than the temp dir so the swap is a same-filesystem rename.+ const stagingDir = join(IX_HOME, `.cli-staging-${process.pid}`);+ const cleanupStaging = () => {+ rmQuiet(stagingDir);+ rmQuiet(tmpDirRaw);+ };++ // Reclaim anything an interrupted upgrade left behind, and put the+ // install back if a previous run died between the two renames.+ sweepUpgradeOrphans(IX_HOME, installDir);+try {- rmSync(installDir, { recursive: true, force: true });- mkdirSync(installDir, { recursive: true });+ rmQuiet(stagingDir);+ mkdirSync(stagingDir, { recursive: true });if (isWindows) {- let unixTmpFile = tmpFile;- let unixInstallDir = installDir;- try {- unixTmpFile = execFileSync("cygpath", ["-u", tmpFile], { encoding: "utf-8" }).trim();- unixInstallDir = execFileSync("cygpath", ["-u", installDir], { encoding: "utf-8" }).trim();- } catch { /* use as-is */ }- execFileSync("unzip", ["-q", unixTmpFile, "-d", unixInstallDir], { stdio: "ignore" });+ extractZipOnWindows(tmpFile, stagingDir);} else {execFileSync("tar",- ["-xzf", tmpFile, "-C", installDir, "--strip-components=1"],+ ["-xzf", tmpFile, "-C", stagingDir, "--strip-components=1"],{ stdio: "ignore" });}- rmSync(tmpDirRaw, { recursive: true, force: true });- } catch {+ } catch (err) {console.error("[error] Failed to extract CLI update.");- rmSync(tmpDirRaw, { recursive: true, force: true });+ console.error(` ${(err as Error).message}`);+ console.error(" Your existing install is untouched.");+ cleanupStaging();+ process.exit(1);+ }++ // Windows zips nest under ix-<version>-<platform>/; POSIX tarballs are+ // already flattened by --strip-components. Resolve either shape.+ const stagedRoot = isWindows ? (soleChildDir(stagingDir) ?? stagingDir) : stagingDir;+ const stagedEntry = join(stagedRoot, "cli", "dist", "cli", "main.js");+ if (!existsSync(stagedEntry)) {+ console.error("[error] Downloaded archive did not contain the expected CLI entry point.");+ console.error(` Expected: ${stagedEntry}`);+ console.error(" Your existing install is untouched.");+ cleanupStaging();+ process.exit(1);+ }++ // Actually start the staged CLI before trusting it. existsSync on+ // main.js cannot distinguish a good tree from a truncated extraction+ // or a tarball whose node_modules is missing a lazily-required+ // module — and the working install is about to be deleted, so this is+ // the last point at which that is recoverable.+ try {+ execFileSync(process.execPath, [stagedEntry, "--version"], {+ stdio: ["ignore", "ignore", "pipe"],+ timeout: 120000,+ });+ } catch (err) {+ const e = err as Error & { stderr?: Buffer | string };+ console.error("[error] The downloaded CLI did not run.");+ console.error(` ${String(e.stderr || "").trim() || e.message}`);+ console.error(" Your existing install is untouched.");+ cleanupStaging();process.exit(1);}- // On Windows, update the shim to point to the new versioned directory- if (isWindows) {- const shimPath = join(homedir(), ".local", "bin", "ix");- const jsPathWin = join(installDir, `ix-${latest}-${platform}`, "cli", "dist", "cli", "main.js");- let jsPath = jsPathWin;- try {- jsPath = execFileSync("cygpath", ["-u", jsPathWin], { encoding: "utf-8" }).trim();- } catch { /* use windows path */ }- // Write the shim directly (creating ~/.local/bin if needed) rather than- // existsSync-then-write, which is a TOCTOU (CodeQL js/file-system-race).- // jsPath derives only from the validated-semver `latest` + install dir.- try {- mkdirSync(dirname(shimPath), { recursive: true });- writeFileSync(shimPath, `#!/usr/bin/env bash\nexec node "${jsPath}" "$@"\n`);- } catch { /* shim refresh is best-effort */ }+ // Move the old install aside rather than deleting it outright, so a+ // failure part-way through the swap can put it back instead of+ // leaving the user with nothing.+ const backupDir = join(IX_HOME, `.cli-backup-${process.pid}`);+ try {+ swapInStagedTree(installDir, stagingDir, backupDir);+ } catch (err) {+ console.error("[error] Failed to install the CLI update.");+ console.error(` ${(err as Error).message}`);+ if (existsSync(installDir)) {+ console.error(" Your existing install is untouched.");+ } else {+ // The restore inside swapInStagedTree could not put it back.+ // Say where the surviving copy is — otherwise the user cannot+ // tell that the install is gone rather than merely unchanged.+ console.error(` Your previous install is still at: ${backupDir}`);+ console.error(` Rename that directory to ${installDir} to restore it, or reinstall:`);+ console.error(+ ` curl -fsSL https://raw.githubusercontent.com/${GITHUB_ORG}/${GITHUB_REPO}/main/scripts/install/install.sh | bash`+ );+ }+ cleanupStaging();+ process.exit(1);+ }+ rmQuiet(tmpDirRaw);++ // Repoint every launcher on PATH at the new install. This is not+ // best-effort any more: the tree the old shims named has just been+ // deleted, so a shim left stale is a CLI that no longer starts.+ const installedRoot = (isWindows ? soleChildDir(installDir) : null) ?? installDir;+ const shimProblems = refreshLaunchers(installDir, installedRoot, isWindows);+ if (shimProblems.length > 0) {+ console.error("[error] Installed the update but could not repoint the launcher:");+ for (const p of shimProblems) console.error(` ${p}`);+ console.error(" Re-run the installer to repair it:");+ console.error(+ ` curl -fsSL https://raw.githubusercontent.com/${GITHUB_ORG}/${GITHUB_REPO}/main/scripts/install/install.sh | bash`+ );+ process.exit(1);}console.log(`[ok] Upgraded ix: ${current} → ${latest}`);