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): stage downloads under IX_HOME, not TEMP (#392)
KageBinary1292375548fb
diff --git a/ix-cli/src/cli/__tests__/upgrade-archive-shape.test.ts b/ix-cli/src/cli/__tests__/upgrade-archive-shape.test.tsindex a8028424..e9872bd8 100644--- a/ix-cli/src/cli/__tests__/upgrade-archive-shape.test.ts+++ b/ix-cli/src/cli/__tests__/upgrade-archive-shape.test.ts@@ -5,6 +5,7 @@ import { tmpdir } from "node:os";import {installStagedTree,+ prepareDownloadDir,soleChildDir,swapInStagedTree,sweepUpgradeOrphans,@@ -291,4 +292,174 @@ describe("sweepUpgradeOrphans", () => {it("is a no-op when IX_HOME does not exist yet", () => {expect(() => sweepUpgradeOrphans(join(root, "nope"), join(root, "nope", "cli"))).not.toThrow();});++ // `ix upgrade` downloads into `.cli-download-*` / `.compass-download-*` under+ // IX_HOME rather than os.tmpdir(), which on Windows is TEMP verbatim and is+ // the path #349 died on. Leaving TEMP also left the OS's own cleanup, so a+ // run killed mid-download would park a multi-MB archive in ~/.ix forever+ // unless this sweep reclaims it.+ it("reclaims an interrupted download's scratch directory", () => {+ 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-download-abc123"), { recursive: true });+ writeFileSync(join(root, ".cli-download-abc123", "ix-0.9.2-linux-amd64.tar.gz"), "gz");+ mkdirSync(join(root, ".compass-download-def456"), { recursive: true });++ sweepUpgradeOrphans(root, installDir);++ expect(existsSync(join(root, ".cli-download-abc123"))).toBe(false);+ expect(existsSync(join(root, ".compass-download-def456"))).toBe(false);+ expect(readFileSync(join(installDir, "cli", "dist", "cli", "main.js"), "utf-8")).toBe("// live\n");+ });++ // The counterpart to the `.cli-backup-` note above, and the reason the sweep+ // call had to move above the download rather than staying between the+ // download and the extract: a download directory must never be a recovery+ // candidate, or an interrupted upgrade would rename an archive over ~/.ix/cli.+ it("does not treat a download directory as an install worth recovering", () => {+ const installDir = join(root, "cli");+ mkdirSync(join(root, ".cli-download-abc123"), { recursive: true });+ writeFileSync(join(root, ".cli-download-abc123", "ix-0.9.2-linux-amd64.tar.gz"), "gz");++ sweepUpgradeOrphans(root, installDir);++ expect(existsSync(installDir)).toBe(false);+ });++ /**+ * cleanupCompassSwap tests `index.html` rather than a bare existsSync, and+ * says why: a `compass/` holding only a `.version` is a real state, and a+ * bare existsSync "would call that 'back in place' and drop a backup the+ * caller had just told the user to go and rescue".+ *+ * recover() used the bare test, so the two disagreed on exactly that state —+ * it declined to restore, and the loop below then deleted the only working+ * bundle. Preserved by the swap's cleanup, destroyed by the sweep. Hoisting+ * the sweep above the download made it fire on runs that install nothing, so+ * an offline `ix upgrade` was enough to lose the compass permanently.+ */+ it("restores the compass over a husk instead of deleting the backup", () => {+ const installDir = join(root, "cli");+ // A torn swap: compass/ exists but holds only .version — index.html never+ // arrived — while the backup holds the real bundle.+ mkdirSync(join(installDir, "compass"), { recursive: true });+ writeFileSync(join(installDir, "compass", ".version"), "0.3.0\n");+ mkdirSync(join(root, ".compass-backup-1234"), { recursive: true });+ writeFileSync(join(root, ".compass-backup-1234", "index.html"), "<!-- real -->");++ sweepUpgradeOrphans(root, installDir);++ expect(existsSync(join(installDir, "compass", "index.html"))).toBe(true);+ expect(readFileSync(join(installDir, "compass", "index.html"), "utf-8")).toBe("<!-- real -->");+ expect(existsSync(join(root, ".compass-backup-1234"))).toBe(false);+ });++ it("leaves a genuinely intact compass alone", () => {+ // The other side of the same test: a real bundle is never replaced by a+ // backup, and the backup is still reclaimed.+ const installDir = join(root, "cli");+ mkdirSync(join(installDir, "compass"), { recursive: true });+ writeFileSync(join(installDir, "compass", "index.html"), "<!-- live -->");+ mkdirSync(join(root, ".compass-backup-1234"), { recursive: true });+ writeFileSync(join(root, ".compass-backup-1234", "index.html"), "<!-- stale -->");++ sweepUpgradeOrphans(root, installDir);++ expect(readFileSync(join(installDir, "compass", "index.html"), "utf-8")).toBe("<!-- live -->");+ expect(existsSync(join(root, ".compass-backup-1234"))).toBe(false);+ });++ it("restores the CLI over a tree with no entry point", () => {+ // Same rule for the install: a cli/ that cannot start is not worth keeping+ // a backup from.+ const installDir = join(root, "cli");+ mkdirSync(join(installDir, "cli", "dist"), { recursive: true });+ mkdirSync(join(root, ".cli-backup-1234", "cli", "dist", "cli"), { recursive: true });+ writeFileSync(join(root, ".cli-backup-1234", "cli", "dist", "cli", "main.js"), "// real\n");++ sweepUpgradeOrphans(root, installDir);++ expect(readFileSync(join(installDir, "cli", "dist", "cli", "main.js"), "utf-8")).toBe("// real\n");+ });++ /**+ * Moving the scratch under IX_HOME put it inside the sweep's reach for the+ * whole 300s curl timeout. A second `ix upgrade` — a second terminal, or+ * bootstrap.sh re-running it when compass is missing — would delete the first+ * run's archive mid-download; on POSIX the unlink is silent and curl still+ * exits 0, so the victim fails at the extract on a download it completed.+ */+ it("does not reclaim a download directory owned by a live process", () => {+ const installDir = join(root, "cli");+ // process.pid is by definition live — this stands in for the other run.+ const live = join(root, `.cli-download-${process.pid}-aaaaaa`);+ mkdirSync(live, { recursive: true });+ writeFileSync(join(live, "ix-0.9.2-linux-amd64.tar.gz"), "in flight");++ sweepUpgradeOrphans(root, installDir);++ expect(existsSync(join(live, "ix-0.9.2-linux-amd64.tar.gz"))).toBe(true);+ });++ it("still reclaims a download directory whose process is gone", () => {+ const installDir = join(root, "cli");+ // PID 2^22 is above every platform's pid_max, so it cannot be running.+ const dead = join(root, ".cli-download-4194304-bbbbbb");+ mkdirSync(dead, { recursive: true });+ writeFileSync(join(dead, "ix-0.9.2-linux-amd64.tar.gz"), "abandoned");+ // And the pre-pid naming, which must stay collectable.+ mkdirSync(join(root, ".compass-download-cccccc"), { recursive: true });++ sweepUpgradeOrphans(root, installDir);++ expect(existsSync(dead)).toBe(false);+ expect(existsSync(join(root, ".compass-download-cccccc"))).toBe(false);+ });+});++/**+ * The ordering that #349's fix turns on, and the one thing about it no test+ * reached while it was written inline in the command action: the sweep must run+ * BEFORE the download scratch is created. Once the sweep reclaims+ * `.cli-download-*`, running it afterwards deletes the archive the extract is+ * about to read — breaking every upgrade on every platform, not just the+ * Windows one. Both call sites go through this function so the order cannot+ * drift back apart.+ */+describe("prepareDownloadDir", () => {+ it("reclaims an earlier run's scratch but keeps the one it just made", () => {+ const installDir = join(root, "cli");+ mkdirSync(join(root, ".cli-download-stale1"), { recursive: true });+ writeFileSync(join(root, ".cli-download-stale1", "ix-0.9.1-linux-amd64.tar.gz"), "old");++ const dir = prepareDownloadDir(root, installDir, ".cli-download-");++ expect(existsSync(join(root, ".cli-download-stale1"))).toBe(false);+ // Swept after the mkdtemp instead of before, this directory is gone too and+ // the download that follows writes an archive nothing will extract.+ expect(existsSync(dir)).toBe(true);++ writeFileSync(join(dir, "ix-0.9.2-linux-amd64.tar.gz"), "gz");+ expect(existsSync(join(dir, "ix-0.9.2-linux-amd64.tar.gz"))).toBe(true);+ });++ it("puts an interrupted install back before downloading anything", () => {+ // The other half of sweeping first: the recovery happens even if the+ // download then fails, which the old position could not do.+ const installDir = join(root, "cli");+ mkdirSync(join(root, ".cli-backup-999", "cli", "dist", "cli"), { recursive: true });+ writeFileSync(join(root, ".cli-backup-999", "cli", "dist", "cli", "main.js"), "// prev\n");++ const dir = prepareDownloadDir(root, installDir, ".cli-download-");++ expect(readFileSync(join(installDir, "cli", "dist", "cli", "main.js"), "utf-8")).toBe("// prev\n");+ expect(existsSync(dir)).toBe(true);+ });++ it("creates IX_HOME when a manual install never did", () => {+ const ixHome = join(root, "fresh");+ const dir = prepareDownloadDir(ixHome, join(ixHome, "cli"), ".compass-download-");+ expect(existsSync(dir)).toBe(true);+ });});diff --git a/ix-cli/src/cli/commands/upgrade.ts b/ix-cli/src/cli/commands/upgrade.tsindex d11d0e91..939816fd 100644--- a/ix-cli/src/cli/commands/upgrade.ts+++ b/ix-cli/src/cli/commands/upgrade.ts@@ -3,7 +3,7 @@ import { execFileSync } from "child_process";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 { homedir } from "os";import chalk from "chalk";import { BACKEND_IMAGE, checkBackendImage, isNonStandardBackend } from "../backend-status.js";import { canRenderProgress } from "../stderr.js";@@ -772,11 +772,24 @@ export function sweepUpgradeOrphans(ixHome: string, installDir: string): void {return;}- const recover = (prefix: string, dest: string, label: string) => {+ // `intact` decides whether what is at `dest` counts as a real thing or a+ // husk, and it must be the same test the swap's own cleanup applies.+ // cleanupCompassSwap uses `index.html`, not a bare existsSync, and says why:+ // a `compass/` holding only a `.version` is a real state, and a bare+ // existsSync "would call that 'back in place' and drop a backup the caller had+ // just told the user to go and rescue".+ //+ // recover() used a bare existsSync, so the two disagreed on exactly the state+ // that matters: with a husk at dest it declined to restore, and the sweep+ // below then deleted the only working bundle. Preserved by cleanup, destroyed+ // by the sweep. The same reasoning applies to the CLI — a `cli/` with no entry+ // point cannot start and is not an install worth keeping a backup from.+ const recover = (prefix: string, dest: string, intact: string, label: string) => {const backups = entries.filter((e) => e.startsWith(prefix)).sort();const last = backups[backups.length - 1];- if (!existsSync(dest) && last) {+ if (!existsSync(join(dest, intact)) && last) {try {+ rmQuiet(dest);mkdirSync(dirname(dest), { recursive: true });renameSync(join(ixHome, last), dest);console.log(` Recovered the previous ${label} from ${last} (an earlier upgrade was interrupted).`);@@ -786,28 +799,106 @@ export function sweepUpgradeOrphans(ixHome: string, installDir: string): void {}};- recover(".cli-backup-", installDir, "install");+ recover(".cli-backup-", installDir, join("cli", "dist", "cli", "main.js"), "install");// join(installDir, "compass"), not the module-level COMPASS_DIR: that constant// is bound to the real IX_HOME, and this function takes ixHome as an argument// precisely so it can be pointed elsewhere. Using the constant would make a// test sweeping a temp directory rename its fixture into the developer's own// ~/.ix/cli/compass. Recovered second because the restore above may be what// creates the parent directory it needs.- recover(".compass-backup-", join(installDir, "compass"), "compass");+ recover(".compass-backup-", join(installDir, "compass"), "index.html", "compass");for (const name of entries) {+ // The download scratch, moved here from os.tmpdir() with #349. It holds a+ // multi-MB archive, and leaving TEMP also left the OS's own cleanup — so an+ // upgrade killed mid-download would park that in ~/.ix forever. These two+ // prefixes are deliberately NOT `-backup-`: `recover()` above renames the+ // last `.cli-backup-*` over the install directory, and a stray archive+ // directory must never be a candidate for that.+ const isDownload =+ name.startsWith(".cli-download-") || name.startsWith(".compass-download-");+if (name.startsWith(".cli-staging-") ||name.startsWith(".cli-backup-") ||name.startsWith(".compass-staging-") ||- name.startsWith(".compass-backup-")+ name.startsWith(".compass-backup-") ||+ isDownload) {+ // Never reclaim a directory another live `ix upgrade` is downloading+ // into. While the scratch lived in os.tmpdir() no sweep could match it;+ // moving it under IX_HOME put it in range for the whole 300s curl+ // timeout, so a second upgrade — a second terminal, or bootstrap.sh+ // re-running `ix upgrade` when it finds compass missing — would delete+ // the first run's archive out from under it. On POSIX the unlink+ // succeeds silently and curl still exits 0, so the victim fails at the+ // extract and reports a download it actually completed.+ //+ // Downloads only: staging and backup directories are named `<prefix><pid>`+ // with no trailing segment, so they carry no pid this can read, and+ // widening the guard to them would change reclaim behaviour that is not+ // what this PR is about.+ if (isDownload && isLiveScratch(name)) continue;const target = join(ixHome, name);if (target !== installDir && existsSync(target)) rmQuiet(target);}}}+/**+ * Does this scratch directory belong to a process that is still running?+ *+ * Download directories are named `<prefix><pid>-<random>`, so the owner is+ * recoverable from the name alone — no lockfile to leak, and a crashed run+ * leaves a pid that no longer resolves, which is exactly when the sweep should+ * reclaim it. Anything unparseable is treated as dead: the pre-existing naming+ * had no pid, and those must stay collectable.+ *+ * `process.kill(pid, 0)` sends no signal; it only asks whether the process is+ * addressable. EPERM means it exists but belongs to another user, which still+ * counts as live.+ */+function isLiveScratch(name: string): boolean {+ const pid = Number(/-(\d+)-[^-]*$/.exec(name)?.[1]);+ if (!Number.isInteger(pid) || pid <= 0) return false;+ if (pid === process.pid) return true;+ try {+ process.kill(pid, 0);+ return true;+ } catch (err) {+ return (err as NodeJS.ErrnoException).code === "EPERM";+ }+}++/**+ * Create the scratch directory an upgrade downloads into, having first+ * reclaimed whatever an interrupted run left behind.+ *+ * The two steps live in one function because their **order** is load-bearing+ * and was otherwise only a comment. `sweepUpgradeOrphans` now reclaims+ * `.cli-download-*` and `.compass-download-*`, so running it *after* the+ * scratch is created deletes the archive that is about to be extracted — which+ * breaks every upgrade on every platform, not just the Windows one #349 is+ * about. The old call sat between the download and the extract, safe only+ * while the scratch lived in `os.tmpdir()`; moving the downloads under IX_HOME+ * is what made the position matter. Sweeping first also puts an interrupted+ * install back even when the download then fails.+ *+ * `mkdirSync` first because `mkdtemp` needs the parent to exist, and a first+ * upgrade after a manual install can reach here before anything has created it.+ *+ * The pid goes in the name so a *concurrent* upgrade's sweep can tell this+ * directory is still in use — see isLiveScratch. Sweeping first protects this+ * run from itself; the pid protects it from the other one.+ */+export function prepareDownloadDir(ixHome: string, installDir: string, prefix: string): string {+ mkdirSync(ixHome, { recursive: true });+ sweepUpgradeOrphans(ixHome, installDir);+ // mkdtemp appends its own randomness, so the shape is `<prefix><pid>-<rand>`+ // and isLiveScratch's `-<digits>-<rand>` match finds the pid.+ return mkdtempSync(join(ixHome, `${prefix}${process.pid}-`));+}+/*** Repoint the Windows launchers at the newly installed tree.*@@ -1011,6 +1102,23 @@ export function registerUpgradeCommand(program: Command): void {process.exit(1);}+ // Reclaim orphans and restore an interrupted swap once, up front, for+ // every real `ix upgrade`.+ //+ // Both other sweep calls sit behind "something needs updating" — one+ // inside the CLI branch, one inside the compass branch. That was already+ // fragile, and #376 tightened the compass gate to skip release-bundled+ // compasses entirely, so on a healthy current install *neither* fires and+ // nothing is ever reclaimed. The archives this PR teaches the sweep about+ // are multi-MB, and the whole reason for sweeping them is that leaving+ // os.tmpdir() also left the OS's own cleanup — a sweep that only runs when+ // an update happens to be available does not deliver that.+ //+ // Cheap when there is nothing to do: one readdir of ~/.ix. The calls+ // inside prepareDownloadDir stay, because that is where the+ // sweep-before-scratch ordering is enforced; they simply find nothing.+ if (!opts.check) sweepUpgradeOrphans(IX_HOME, join(IX_HOME, "cli"));+// ── CLI upgrade ──────────────────────────────────────────────────const cliUpToDate = !isNewer(latest, current);if (cliUpToDate) {@@ -1027,7 +1135,18 @@ export function registerUpgradeCommand(program: Command): void {const url = `https://github.com/${GITHUB_ORG}/${GITHUB_REPO}/releases/download/v${latest}/${archiveName}`;const installDir = join(IX_HOME, "cli");- const tmpDirRaw = mkdtempSync(join(tmpdir(), "ix-upgrade-"));+ // Under IX_HOME, not os.tmpdir(). #349 is a Windows install that died+ // because TEMP arrived in 8.3 short form (`C:\Users\WIN10\~1\...`) on+ // a profile named `C:\Users\Win 10`, and setting TEMP to a path+ // without a space let the same install finish. install.ps1 was moved+ // off TEMP for that; `ix upgrade` stages through os.tmpdir(), which on+ // Windows *is* TEMP verbatim, so the same hazard was left live on the+ // upgrade path — where it breaks an install that already works.+ //+ // IX_HOME comes from USERPROFILE in its long form. prepareDownloadDir+ // also reclaims anything an interrupted upgrade left behind, and must+ // do so before the scratch exists — see its docstring.+ const tmpDirRaw = prepareDownloadDir(IX_HOME, installDir, ".cli-download-");const tmpFile = join(tmpDirRaw, archiveName);console.log(`Downloading ix ${latest} for ${platform}...`);@@ -1044,7 +1163,11 @@ export function registerUpgradeCommand(program: Command): void {console.error(` curl -fsSL https://raw.githubusercontent.com/${GITHUB_ORG}/${GITHUB_REPO}/main/scripts/install/install.sh | bash`);- rmSync(tmpDirRaw, { recursive: true, force: true });+ // rmQuiet, not a bare rmSync: this directory now lives under the+ // user profile rather than TEMP, where an AV or indexer handle on+ // the archive curl just wrote is routine — and a throw here would+ // replace the actionable message above with a raw EPERM.+ rmQuiet(tmpDirRaw);process.exit(1);}@@ -1063,10 +1186,6 @@ export function registerUpgradeCommand(program: Command): void {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 {rmQuiet(stagingDir);mkdirSync(stagingDir, { recursive: true });@@ -1301,10 +1420,15 @@ export function registerUpgradeCommand(program: Command): void {// backup may hold their only compass. Idempotent when the CLI branch// already ran, since it finds nothing left. (installDir is scoped to// that branch; COMPASS_DIR's parent is the same directory.)- sweepUpgradeOrphans(IX_HOME, dirname(COMPASS_DIR));-+ //+ // Under IX_HOME for the same reason as the CLI download above (#349),+ // and swept before the scratch exists for the same reason too.const compassUrl = `https://github.com/${GITHUB_ORG}/${COMPASS_DIST_REPO}/releases/download/v${compassLatest}/compass-${compassLatest}.tar.gz`;- const compassTmp = mkdtempSync(join(tmpdir(), "ix-compass-"));+ const compassTmp = prepareDownloadDir(+ IX_HOME,+ dirname(COMPASS_DIR),+ ".compass-download-",+ );const compassTar = join(compassTmp, `compass-${compassLatest}.tar.gz`);// Which step failed decides where to look: a download failure is a@@ -1353,7 +1477,11 @@ export function registerUpgradeCommand(program: Command): void {}}cleanupCompassSwap(COMPASS_DIR, compassStaging, compassBackup);- rmSync(compassTmp, { recursive: true, force: true });+ // rmQuiet, not a bare rmSync — same reason as the CLI download above,+ // and this one runs on the *success* path. A throw here escapes the+ // action, so writeCache() below never runs and the "update available"+ // notice keeps firing for the compass just installed.+ rmQuiet(compassTmp);}} else if (compassLatest && readCompassStamp().source === "release") {// Not "already latest" — it is a different series. Say what it is, so