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(windows): install Compass where the CLI looks, and stop hiding why it failed (#346)
KageBinary0b4caf9fc281
diff --git a/ix-cli/src/cli/__tests__/upgrade-archive-shape.test.ts b/ix-cli/src/cli/__tests__/upgrade-archive-shape.test.tsindex 4d41dd26..8eec3bf4 100644--- a/ix-cli/src/cli/__tests__/upgrade-archive-shape.test.ts+++ b/ix-cli/src/cli/__tests__/upgrade-archive-shape.test.ts@@ -3,7 +3,12 @@ import { mkdtempSync, mkdirSync, writeFileSync, rmSync, existsSync, readFileSyncimport { join } from "node:path";import { tmpdir } from "node:os";-import { soleChildDir, swapInStagedTree, sweepUpgradeOrphans } from "../commands/upgrade.js";+import {+ installStagedTree,+ soleChildDir,+ swapInStagedTree,+ sweepUpgradeOrphans,+} from "../commands/upgrade.js";let root: string;@@ -15,6 +20,102 @@ afterEach(() => {rmSync(root, { recursive: true, force: true });});+// soleChildDir and swapInStagedTree are each correct in isolation; the bug was+// in how the upgrade path combined them. It resolved the staged root to read+// the CLI entry point, then swapped in the *outer* staging directory, so a+// Windows install ended up at cli\ix-<version>-windows-amd64\ — reproducing+// inside cli\ exactly the nesting it had just seen through. COMPASS_DIR and+// findCompassDist read cli\compass and nothing else, so `ix view` was broken on+// every Windows install and broke again on the first upgrade after install.ps1+// started laying the tree down flat.+//+// So these go through installStagedTree, which is where the upgrade path makes+// that choice. Resolving the staged root here and calling swapInStagedTree+// directly would pass against the bug too — the defect was never in either+// helper, only in the line that joined them, and a test that re-derives the+// composition cannot see it.+describe("staged swap, as the upgrade path composes it", () => {+ function seedWindowsZipStaging(home: string, ver: string) {+ const staging = join(home, `.cli-staging-${ver}`);+ const nested = join(staging, `ix-${ver}-windows-amd64`);+ mkdirSync(join(nested, "cli", "dist", "cli"), { recursive: true });+ writeFileSync(join(nested, "cli", "dist", "cli", "main.js"), `// ${ver}\n`);+ mkdirSync(join(nested, "compass"), { recursive: true });+ writeFileSync(join(nested, "compass", "index.html"), "<!doctype html>\n");+ return staging;+ }++ it("leaves compass where the CLI looks for it, given a nested Windows zip", () => {+ const installDir = join(root, "cli");+ const staging = seedWindowsZipStaging(root, "0.9.0");++ installStagedTree(installDir, staging, join(root, ".cli-backup-1"), true);++ // COMPASS_DIR / findCompassDist read exactly this path.+ expect(existsSync(join(installDir, "compass", "index.html"))).toBe(true);+ expect(existsSync(join(installDir, "cli", "dist", "cli", "main.js"))).toBe(true);+ // The nesting must not survive into the install.+ expect(existsSync(join(installDir, "ix-0.9.0-windows-amd64"))).toBe(false);+ });++ it("clears the staging husk the inner move leaves behind", () => {+ const installDir = join(root, "cli");+ const staging = seedWindowsZipStaging(root, "0.9.0");++ installStagedTree(installDir, staging, join(root, ".cli-backup-husk"), true);++ // Moving the inner directory out leaves the outer one standing. Left in+ // place it is a `.cli-staging-<pid>` that only the next run's sweep+ // reclaims, and on a reused pid that sweep is what the *next* upgrade+ // trips over.+ expect(existsSync(staging)).toBe(false);+ });++ it("keeps the launcher pointing at the install root once the tree is flat", () => {+ const installDir = join(root, "cli");+ const staging = seedWindowsZipStaging(root, "0.9.0");+ installStagedTree(installDir, staging, join(root, ".cli-backup-2"), true);++ // refreshLaunchers derives the shim target this way: a flat install has+ // several directories, so there is no sole child and the shim resolves to+ // %~dp0..\cli\ix.cmd — the form install.ps1 now writes.+ expect(soleChildDir(installDir)).toBeNull();+ });++ it("is unchanged for a POSIX tarball, already flattened by --strip-components", () => {+ const installDir = join(root, "cli");+ const staging = join(root, ".cli-staging-posix");+ mkdirSync(join(staging, "cli", "dist", "cli"), { recursive: true });+ writeFileSync(join(staging, "cli", "dist", "cli", "main.js"), "// posix\n");+ mkdirSync(join(staging, "compass"), { recursive: true });+ writeFileSync(join(staging, "compass", "index.html"), "<!doctype html>\n");++ // isWindows false: the staged root is the staging directory itself, so the+ // tree is installed whole and there is no husk to clear.+ installStagedTree(installDir, staging, join(root, ".cli-backup-3"), false);++ expect(existsSync(join(installDir, "compass", "index.html"))).toBe(true);+ expect(existsSync(join(installDir, "cli", "dist", "cli", "main.js"))).toBe(true);+ });++ it("installs a Windows tree that is already flat without re-nesting it", () => {+ // install.ps1 now lays the tree down flat, so the *next* upgrade sees a+ // Windows staging directory with no sole child. soleChildDir returns null+ // and the fallback has to install the staging directory itself.+ const installDir = join(root, "cli");+ const staging = join(root, ".cli-staging-flat");+ mkdirSync(join(staging, "cli", "dist", "cli"), { recursive: true });+ writeFileSync(join(staging, "cli", "dist", "cli", "main.js"), "// flat\n");+ mkdirSync(join(staging, "compass"), { recursive: true });+ writeFileSync(join(staging, "compass", "index.html"), "<!doctype html>\n");++ installStagedTree(installDir, staging, join(root, ".cli-backup-4"), true);++ expect(existsSync(join(installDir, "compass", "index.html"))).toBe(true);+ expect(existsSync(join(installDir, "cli", "dist", "cli", "main.js"))).toBe(true);+ });+});+describe("soleChildDir", () => {it("finds the single nested directory a Windows release zip extracts to", () => {// Windows zips wrap everything in ix-<version>-<platform>/; the launcherdiff --git a/ix-cli/src/cli/__tests__/upgrade-compass-bundle.test.ts b/ix-cli/src/cli/__tests__/upgrade-compass-bundle.test.tsnew file mode 100644index 00000000..4e477676--- /dev/null+++ b/ix-cli/src/cli/__tests__/upgrade-compass-bundle.test.ts@@ -0,0 +1,212 @@+import { execFileSync } from "node:child_process";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import {+ mkdtempSync,+ mkdirSync,+ writeFileSync,+ rmSync,+ renameSync,+ existsSync,+ readFileSync,+} from "node:fs";+import { join } from "node:path";+import { tmpdir } from "node:os";++import {+ cleanupCompassSwap,+ installCompassBundle,+ sweepUpgradeOrphans,+} from "../commands/upgrade.js";++// The compass repair used to empty COMPASS_DIR and extract into the hole, so+// any tar failure left no compass at all. While the Windows bundle sat+// unreachable at cli\ix-<version>-<platform>\compass that cost nothing — there+// was never anything at COMPASS_DIR to lose. install.ps1 now puts the bundle+// exactly there, which makes the destructive order a way for the repair path to+// break the install it is meant to rescue.++let root: string;++beforeEach(() => {+ root = mkdtempSync(join(tmpdir(), "ix-compass-test-"));+});++afterEach(() => {+ rmSync(root, { recursive: true, force: true });+});++/** An installed compass, as findCompassDist would accept it. */+function seedInstalledCompass(marker: string): string {+ const compassDir = join(root, "cli", "compass");+ mkdirSync(compassDir, { recursive: true });+ writeFileSync(join(compassDir, "index.html"), marker);+ writeFileSync(join(compassDir, ".version"), "0.1.0");+ return compassDir;+}++/**+ * A real compass-shaped tarball, nested one level the way ix-compass-dist+ * ships it — `--strip-components=1` is only correct against that shape, so+ * building the fixture any flatter would test a layout that does not exist.+ */+function buildCompassTarball(name: string, files: Record<string, string>): string {+ const src = join(root, `src-${name}`);+ const inner = join(src, `compass-${name}`);+ mkdirSync(inner, { recursive: true });+ for (const [rel, body] of Object.entries(files)) {+ writeFileSync(join(inner, rel), body);+ }+ // Relative paths, run from `src`. Git for Windows puts GNU tar on PATH ahead+ // of System32's bsdtar, and GNU tar reads `C:\...` in -f as a host:path+ // remote spec — "Cannot connect to C: resolve failed". That is the same trap+ // installCompassBundle sidesteps with cygpath; the fixture just avoids+ // absolute paths rather than depending on which tar answers.+ execFileSync("tar", ["-czf", `../${name}.tar.gz`, `compass-${name}`], {+ cwd: src,+ stdio: ["ignore", "ignore", "pipe"],+ });+ return join(root, `${name}.tar.gz`);+}++const staging = () => join(root, ".compass-staging-test");+const backup = () => join(root, ".compass-backup-test");++describe("installCompassBundle", () => {+ it("installs the bundle when the archive is good", () => {+ const compassDir = seedInstalledCompass("<!-- old -->");+ const tarPath = buildCompassTarball("0.2.0", {+ "index.html": "<!-- new -->",+ "app.js": "console.log(1);\n",+ });++ installCompassBundle(tarPath, compassDir, staging(), backup());++ expect(readFileSync(join(compassDir, "index.html"), "utf-8")).toBe("<!-- new -->");+ expect(existsSync(join(compassDir, "app.js"))).toBe(true);+ // The replaced tree goes entirely, rather than the new files landing on top+ // of the old ones — a stale .version would misreport what is installed.+ expect(existsSync(join(compassDir, ".version"))).toBe(false);+ });++ it("leaves the installed compass intact when tar fails", () => {+ const compassDir = seedInstalledCompass("<!-- keep me -->");++ expect(() =>+ installCompassBundle(join(root, "not-a-real-archive.tar.gz"), compassDir, staging(), backup())+ ).toThrow();++ // The whole point: a failed repair must not be what breaks `ix view`.+ expect(readFileSync(join(compassDir, "index.html"), "utf-8")).toBe("<!-- keep me -->");+ });++ it("leaves the installed compass intact when the archive has no index.html", () => {+ const compassDir = seedInstalledCompass("<!-- keep me -->");+ const tarPath = buildCompassTarball("empty", { "README.md": "no ui here\n" });++ // An extract that succeeds but produces no index.html is not a compass.+ // Swapping it in would hand findCompassDist a directory it rejects, and the+ // caller stamps .version straight after — telling `ix upgrade` never to+ // retry the download that would have fixed it.+ expect(() => installCompassBundle(tarPath, compassDir, staging(), backup())).toThrow(+ /index\.html/+ );+ expect(readFileSync(join(compassDir, "index.html"), "utf-8")).toBe("<!-- keep me -->");+ });++ it("installs into a fresh tree when no compass is present yet", () => {+ // The repair path on a machine whose release shipped an empty compass/:+ // nothing to swap out, and cli\ itself may not exist under a bare IX_HOME.+ const compassDir = join(root, "cli", "compass");+ const tarPath = buildCompassTarball("fresh", { "index.html": "<!-- fresh -->" });++ installCompassBundle(tarPath, compassDir, staging(), backup());++ expect(readFileSync(join(compassDir, "index.html"), "utf-8")).toBe("<!-- fresh -->");+ });++ it("leaves the old compass recoverable when the swap tears", () => {+ // swapInStagedTree moves the live compass to backupDir and then renames+ // staging into place. If that second rename fails and its restore fails+ // too, the backup is the only copy left — so the caller must not clear it+ // unconditionally, and the sweep must put it back rather than delete it.+ const compassDir = seedInstalledCompass("<!-- the only copy -->");+ const backupDir = join(root, ".compass-backup-torn");++ // Reproduce the torn state directly: swapInStagedTree got as far as moving+ // the compass aside, then failed.+ renameSync(compassDir, backupDir);+ expect(existsSync(compassDir)).toBe(false);++ // Cleanup must spare the backup while the compass is missing. Driving+ // cleanupCompassSwap rather than re-deriving its condition here: that guard+ // *is* the fix, so a test that restates it would pass either way.+ cleanupCompassSwap(compassDir, join(root, ".compass-staging-torn"), backupDir);+ expect(existsSync(join(backupDir, "index.html"))).toBe(true);++ // And the next run's sweep restores it rather than reclaiming it.+ sweepUpgradeOrphans(root, join(root, "cli"));+ expect(readFileSync(join(compassDir, "index.html"), "utf-8")).toBe("<!-- the only copy -->");+ expect(existsSync(backupDir)).toBe(false);+ });++ it("keeps the backup when the compass directory exists but holds no compass", () => {+ // `compass/` containing only a .version is a real state: install.ps1 used+ // to create exactly that, and v0.7.0-v0.8.1 shipped an empty compass/.+ // Treating the bare directory as "back in place" would drop the backup the+ // caller had just told the user to go and rescue.+ const compassDir = join(root, "cli", "compass");+ mkdirSync(compassDir, { recursive: true });+ writeFileSync(join(compassDir, ".version"), "0.2.0");+ const backupDir = join(root, ".compass-backup-empty");+ mkdirSync(backupDir, { recursive: true });+ writeFileSync(join(backupDir, "index.html"), "<!-- the real one -->");++ cleanupCompassSwap(compassDir, join(root, ".compass-staging-empty"), backupDir);++ expect(existsSync(join(backupDir, "index.html"))).toBe(true);+ });++ it("reclaims a stale backup rather than rolling a healthy compass back", () => {+ // The mirror of the bug above: with a working compass installed, a leftover+ // .compass-backup-* from an earlier torn run must be reclaimed, not+ // restored over the top. A wrong existsSync(dest) here would silently+ // downgrade the user to whatever that backup happens to hold.+ seedInstalledCompass("<!-- current -->");+ const stale = join(root, ".compass-backup-0001");+ mkdirSync(stale, { recursive: true });+ writeFileSync(join(stale, "index.html"), "<!-- ancient -->");++ sweepUpgradeOrphans(root, join(root, "cli"));++ expect(readFileSync(join(root, "cli", "compass", "index.html"), "utf-8")).toBe("<!-- current -->");+ expect(existsSync(stale)).toBe(false);+ });++ it("reclaims compass scratch directories an interrupted run left behind", () => {+ // Nothing swept .compass-staging-* / .compass-backup-* before, so a run+ // killed mid-swap leaked a full copy of the bundle into IX_HOME forever.+ seedInstalledCompass("<!-- installed -->");+ const staging = join(root, ".compass-staging-9999");+ mkdirSync(staging, { recursive: true });+ writeFileSync(join(staging, "index.html"), "<!-- half-extracted -->");++ sweepUpgradeOrphans(root, join(root, "cli"));++ expect(existsSync(staging)).toBe(false);+ // The installed compass is untouched by the sweep.+ expect(readFileSync(join(root, "cli", "compass", "index.html"), "utf-8")).toBe("<!-- installed -->");+ });++ it("does not leave the staging directory behind on success", () => {+ const compassDir = seedInstalledCompass("<!-- old -->");+ const tarPath = buildCompassTarball("clean", { "index.html": "<!-- new -->" });++ installCompassBundle(tarPath, compassDir, staging(), backup());++ // The swap renames staging onto compassDir, so nothing should survive at+ // either scratch path — these sit in IX_HOME next to the CLI's own+ // .cli-staging-*, and a leaked copy of the bundle stays there forever.+ expect(existsSync(staging())).toBe(false);+ expect(existsSync(backup())).toBe(false);+ });+});diff --git a/ix-cli/src/cli/__tests__/upgrade-exec-failure.test.ts b/ix-cli/src/cli/__tests__/upgrade-exec-failure.test.tsnew file mode 100644index 00000000..bd17ed9d--- /dev/null+++ b/ix-cli/src/cli/__tests__/upgrade-exec-failure.test.ts@@ -0,0 +1,108 @@+import { execFileSync } from "node:child_process";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { describeExecFailure } from "../commands/upgrade.js";++describe("describeExecFailure", () => {+ it("names PATH as the fix when the binary does not exist", () => {+ // The Windows compass repair failed with nothing on screen. If the cause+ // was a missing tar, the message has to say so — "spawnSync tar ENOENT"+ // alone does not tell you what to do about it.+ // Assembled at runtime so knip does not read it as a real binary this+ // package depends on and fail the dead-code check on an unlisted one.+ const missing = ["ix", "no", "such", "binary"].join("-");+ let err: unknown;+ try {+ execFileSync(missing, ["--version"], { stdio: "ignore" });+ } catch (e) {+ err = e;+ }+ expect(err).toBeDefined();+ const msg = describeExecFailure(err);+ expect(msg).toContain(missing);+ expect(msg).toContain("PATH");+ });++ it("surfaces stderr from a command that ran and failed, exactly once", () => {+ // A real tar failure explains itself on stderr — but execFileSync has+ // already folded that stderr into `message` by the time it throws, so+ // returning `${message}: ${stderr}` printed the whole complaint twice.+ //+ // Asserting only that the archive name appears is not enough: it appears in+ // the `Command failed: tar -xzf <path>` prefix regardless, so that+ // assertion passes even with `.stderr` stripped off the error entirely and+ // proves nothing about stderr being read back.+ let err: unknown;+ try {+ execFileSync("tar", ["-xzf", "/nonexistent/definitely-missing.tar.gz"], {+ stdio: ["ignore", "ignore", "pipe"],+ });+ } catch (e) {+ err = e;+ }+ const e = err as Error & { stderr?: Buffer };+ const captured = e.stderr?.toString().trim() ?? "";+ // The pipe really did capture something, and Node really did fold it in.+ expect(captured).not.toBe("");+ expect(e.message).toContain(captured);++ const msg = describeExecFailure(err);+ expect(msg).toBe(e.message);+ // tar's wording varies by implementation, so count rather than match: every+ // distinct line stderr produced appears in the result as many times as it+ // appeared in stderr, not twice that. Deduplicated because a tar that+ // genuinely repeats a line would otherwise fail this against correct code+ // — GNU tar emits 4 distinct lines here, bsdtar 1.+ for (const line of new Set(captured.split("\n").filter((l) => l.trim()))) {+ const inStderr = captured.split(line).length - 1;+ expect(msg.split(line).length - 1).toBe(inStderr);+ }+ });++ it("appends stderr when the message does not already carry it", () => {+ // The other half of the same branch: a caller that captured stderr without+ // Node folding it in still gets it, rather than a bare "Command failed".+ const bare = Object.assign(new Error("Command failed: tar -xzf compass.tar.gz"), {+ stderr: Buffer.from("tar: could not chdir to the destination\n"),+ });+ expect(describeExecFailure(bare)).toBe(+ "Command failed: tar -xzf compass.tar.gz: tar: could not chdir to the destination"+ );+ });++ it("does not blame PATH for a filesystem ENOENT", () => {+ // fs errors carry code ENOENT too, and the compass block runs writeFileSync+ // and mkdirSync inside the same try. "ENOENT: no such file or directory,+ // open '...\\.version' — is it installed and on PATH?" is advice about a+ // file, and there is nothing the user can do with it. Only a spawn failure+ // is a PATH problem, which is what the syscall distinguishes.+ // mkdtempSync, not a fixed name under tmpdir(): a predictable temp path is+ // CodeQL js/insecure-temporary-file, and it flags the write regardless of+ // the fact that this one is meant to fail. The nested directory below it is+ // never created, so the ENOENT is real.+ const dir = mkdtempSync(join(tmpdir(), "ix-exec-failure-"));+ let err: unknown;+ try {+ writeFileSync(join(dir, "no-such-dir", ".version"), "1.0.0");+ } catch (e) {+ err = e;+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ expect((err as NodeJS.ErrnoException).code).toBe("ENOENT");+ expect(describeExecFailure(err)).not.toContain("PATH");+ });++ it("does not throw on a non-Error rejection", () => {+ expect(describeExecFailure("plain string")).toBe("plain string");+ expect(describeExecFailure(undefined)).toBe("undefined");+ });++ it("falls back to the message when nothing was captured on stderr", () => {+ const bare = new Error("spawnSync tar EACCES");+ expect(describeExecFailure(bare)).toBe("spawnSync tar EACCES");+ });+});diff --git a/ix-cli/src/cli/commands/upgrade.ts b/ix-cli/src/cli/commands/upgrade.tsindex cfdc78c6..4e9cc53f 100644--- a/ix-cli/src/cli/commands/upgrade.ts+++ b/ix-cli/src/cli/commands/upgrade.ts@@ -204,6 +204,31 @@ function getTrackedVersion(versionFile: string): string {}}+/**+ * Render a failed `execFileSync` as something a user can act on.+ *+ * Two shapes matter. A missing binary throws `ENOENT` with a message that names+ * the spawn but not the cause, so the fix — put it on PATH — has to be spelled+ * out. A binary that ran and exited non-zero puts the real explanation on+ * stderr, which is lost unless the caller piped it and reads it back here.+ */+export function describeExecFailure(err: unknown): string {+ if (!(err instanceof Error)) return String(err);+ const e = err as NodeJS.ErrnoException & { stderr?: Buffer | string };+ // ENOENT on its own does not mean "no such binary" — every filesystem miss+ // carries it too (`ENOENT: ... open '...\.version'`, syscall "open"). Only a+ // spawn failure is a PATH problem, and advising someone to put their version+ // file on PATH sends them nowhere. The syscall is what separates the two.+ if (e.code === "ENOENT" && e.syscall?.startsWith("spawn")) {+ return `${e.message} — is it installed and on PATH?`;+ }+ // execFileSync folds piped stderr into `message` already, so appending it+ // unconditionally printed the command's entire complaint twice. Only reach+ // for `.stderr` when the message did not already carry it.+ const stderr = e.stderr?.toString().trim();+ return stderr && !e.message.includes(stderr) ? `${e.message}: ${stderr}` : e.message;+}+/*** Extract a .zip on Windows, trying every extractor a Windows box might have.*@@ -352,13 +377,134 @@ export function swapInStagedTree(installDir: string, stagingDir: string, backupD}/**- * 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 staged tree to install, given the directory an archive extracted into.*- * 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.+ * Windows zips nest everything under `ix-<version>-<platform>/`; POSIX tarballs+ * are already flattened by `--strip-components`. Resolve either shape.+ */+export function resolveStagedRoot(stagingDir: string, isWindows: boolean): string {+ return isWindows ? (soleChildDir(stagingDir) ?? stagingDir) : stagingDir;+}++/**+ * Install the tree staged in `stagingDir` at `installDir`.+ *+ * The choice of *which* directory to swap in lives here rather than at the call+ * site, because that choice was the bug. The upgrade path resolved the staged+ * root to read the CLI entry point out of it, then handed `swapInStagedTree`+ * the *outer* staging directory — reproducing inside `cli\` exactly the nesting+ * it had just seen through. COMPASS_DIR and findCompassDist read `cli\compass`+ * and nothing else, so `ix view` broke.+ *+ * Keeping the composition in one function is what makes it testable. A test+ * that resolves the staged root itself and then calls `swapInStagedTree`+ * directly passes just as happily against the bug as against the fix, because+ * the defect was never in either helper — it was in the line that joined them.+ */+export function installStagedTree(+ installDir: string,+ stagingDir: string,+ backupDir: string,+ isWindows: boolean+): void {+ swapInStagedTree(installDir, resolveStagedRoot(stagingDir, isWindows), backupDir);+ // The staged root moved out from under stagingDir, so on Windows the outer+ // directory survives the swap as an empty husk. Before the fix the swap+ // consumed it whole and there was nothing left to clear.+ rmQuiet(stagingDir);+}++/**+ * Replace the installed compass with the bundle in `tarPath`.+ *+ * Unpack beside the live copy and swap, rather than emptying `compassDir` and+ * extracting into the hole. The old order deleted the working compass first, so+ * a tar that failed — the exact failure the caller now bothers to report — left+ * no compass at all and `ix view` broken. That cost nothing while the Windows+ * bundle sat unreachable at `cli\ix-<version>-<platform>\compass`, but+ * install.ps1 now puts it exactly here, so the repair path would destroy the+ * copy the install just got right.+ *+ * `stagingDir` and `backupDir` belong under IX_HOME so the swap is a+ * same-filesystem rename; the OS temp dir can be on another volume.+ *+ * Throws with the working compass still in place.+ */+export function installCompassBundle(+ tarPath: string,+ compassDir: string,+ stagingDir: string,+ backupDir: string+): void {+ rmQuiet(stagingDir);+ mkdirSync(stagingDir, { recursive: true });++ let tarFile = tarPath;+ let tarDest = stagingDir;+ if (process.platform === "win32") {+ try {+ tarFile = execFileSync("cygpath", ["-u", tarPath], { encoding: "utf-8" }).trim();+ tarDest = execFileSync("cygpath", ["-u", stagingDir], { encoding: "utf-8" }).trim();+ } catch { /* use as-is */ }+ }+ execFileSync(+ "tar",+ ["-xzf", tarFile, "-C", tarDest, "--strip-components=1"],+ // Capture stderr rather than discarding it: this is the step that failed on+ // Windows and it left nothing behind to diagnose.+ { stdio: ["ignore", "ignore", "pipe"] }+ );++ // An extract that "succeeded" without producing index.html is not a compass.+ // Swapping it in would replace a working bundle with one findCompassDist+ // rejects, and the caller's version stamp would then tell `ix upgrade` never+ // to try again — the poisoned-stamp failure both installers now avoid.+ if (!existsSync(join(stagingDir, "index.html"))) {+ throw new Error(`archive did not contain index.html (extracted to ${stagingDir})`);+ }++ // compassDir's parent is the install dir. It exists in every real install,+ // but not necessarily in a dev tree that only sets IX_HOME.+ mkdirSync(dirname(compassDir), { recursive: true });+ swapInStagedTree(compassDir, stagingDir, backupDir);+}++/**+ * Clear the scratch directories a compass swap used.+ *+ * `backupDir` goes only once the compass is actually back in place. If the swap+ * tore — the old bundle moved aside, the new one failed to land, and+ * swapInStagedTree's own restore failed too — then the backup holds the only+ * copy of a working compass. Clearing it unconditionally turns a recoverable+ * failure into a permanently broken `ix view`, which is the one outcome the+ * backup exists to prevent. sweepUpgradeOrphans puts it back on the next run.+ */+export function cleanupCompassSwap(compassDir: string, stagingDir: string, backupDir: string): void {+ rmQuiet(stagingDir);+ // index.html, not the directory: a `compass/` holding only a `.version` is a+ // real state — install.ps1 used to create exactly that, and v0.7.0-v0.8.1+ // shipped an empty compass/ — and it is not a compass anyone can serve. A+ // bare existsSync(compassDir) would call that "back in place" and drop a+ // backup the caller had just told the user to go and rescue. Safe on the+ // success path: installCompassBundle proves index.html is there before it+ // swaps, so this is the same test findCompassDist applies.+ if (existsSync(join(compassDir, "index.html"))) rmQuiet(backupDir);+}++/**+ * Reclaim `.cli-staging-*` / `.cli-backup-*` and `.compass-staging-*` /+ * `.compass-backup-*` directories left behind by an upgrade that died mid-swap,+ * and put the install or the compass back if either is missing.+ *+ * Each swap has a window between its two renames in which nothing exists at the+ * destination. 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.+ *+ * The compass gets the same treatment as the CLI rather than a bare delete: its+ * backup is the only copy of a working bundle while the swap is torn, so a+ * sweep that just reclaimed it would turn an interrupted upgrade into a+ * permanently broken `ix view`.*/export function sweepUpgradeOrphans(ixHome: string, installDir: string): void {let entries: string[];@@ -367,19 +513,37 @@ export function sweepUpgradeOrphans(ixHome: string, installDir: string): void {} 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 */+ const recover = (prefix: string, dest: string, label: string) => {+ const backups = entries.filter((e) => e.startsWith(prefix)).sort();+ const last = backups[backups.length - 1];+ if (!existsSync(dest) && last) {+ try {+ mkdirSync(dirname(dest), { recursive: true });+ renameSync(join(ixHome, last), dest);+ console.log(` Recovered the previous ${label} from ${last} (an earlier upgrade was interrupted).`);+ } catch {+ /* fall through to the sweep; nothing is made worse by leaving it */+ }}- }+ };++ recover(".cli-backup-", installDir, "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");+for (const name of entries) {- if (name.startsWith(".cli-staging-") || name.startsWith(".cli-backup-")) {+ if (+ name.startsWith(".cli-staging-") ||+ name.startsWith(".cli-backup-") ||+ name.startsWith(".compass-staging-") ||+ name.startsWith(".compass-backup-")+ ) {const target = join(ixHome, name);if (target !== installDir && existsSync(target)) rmQuiet(target);}@@ -389,11 +553,18 @@ export function sweepUpgradeOrphans(ixHome: string, installDir: string): void {/*** 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.+ * Only Windows needs this. install.sh writes an *absolute* path into the shim+ * on Windows (`$INSTALL_DIR/cli/dist/cli/main.js`) but on POSIX writes+ * `exec "$INSTALL_DIR/ix"`, which resolves through the install directory itself+ * 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.+ *+ * That Windows path used to carry the release version in it+ * (`ix-<VERSION>-windows-amd64/`), which is why refreshing it mattered so much.+ * Both installers now lay the tree down flat, so it no longer changes between+ * releases — but the shim is still rewritten, because an install made by an+ * older script still has the version-encoded form on disk and nothing else+ * would ever repoint it.** On Windows three shims exist, not two:* - `%IX_HOME%\bin\ix.cmd` written by install.ps1@@ -659,7 +830,7 @@ export function registerUpgradeCommand(program: Command): void {// 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 stagedRoot = resolveStagedRoot(stagingDir, isWindows);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.");@@ -693,7 +864,13 @@ export function registerUpgradeCommand(program: Command): void {// leaving the user with nothing.const backupDir = join(IX_HOME, `.cli-backup-${process.pid}`);try {- swapInStagedTree(installDir, stagingDir, backupDir);+ // installStagedTree owns the staged-root resolution. It swaps in the+ // *inner* directory on Windows, so the zip's ix-<version>-<platform>/+ // wrapper does not get reproduced inside cli\ — which is what put+ // compass at cli\ix-<version>-<platform>\compass while COMPASS_DIR+ // and findCompassDist only ever read cli\compass. One shape on every+ // platform, and one function a test can hold to that.+ installStagedTree(installDir, stagingDir, backupDir, isWindows);} catch (err) {console.error("[error] Failed to install the CLI update.");console.error(` ${(err as Error).message}`);@@ -856,36 +1033,62 @@ export function registerUpgradeCommand(program: Command): void {);if (!opts.check) {+ // Sweep here too, not only in the CLI branch above. That call sits+ // behind "the CLI itself needs updating", so on a machine already on+ // the latest CLI it never runs — and this block is about to create+ // the very scratch directories it reclaims. Without this, a compass+ // swap interrupted on a current install stays torn until the *next*+ // CLI release, which is the one moment the user cannot wait for: the+ // 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));+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 compassTar = join(compassTmp, `compass-${compassLatest}.tar.gz`);+ // Which step failed decides where to look: a download failure is a+ // network, URL or proxy problem; an extract failure is a local tar+ // problem. One `catch` reporting both as "could not download" sent a+ // Windows investigation at the wrong half — and `tar` ran with stdio+ // "ignore", so the only step that had actually failed was also the+ // one that printed nothing at all.+ const compassStaging = join(IX_HOME, `.compass-staging-${process.pid}`);+ const compassBackup = join(IX_HOME, `.compass-backup-${process.pid}`);+ let stage = "download";try {execFileSync("curl", ["-fsSL", compassUrl, "-o", compassTar], {stdio: ["ignore", "inherit", "inherit"],timeout: 60000,});- mkdirSync(COMPASS_DIR, { recursive: true });- rmSync(COMPASS_DIR, { recursive: true, force: true });- mkdirSync(COMPASS_DIR, { recursive: true });- let tarFile = compassTar;- let tarDest = COMPASS_DIR;- if (process.platform === "win32") {- try {- tarFile = execFileSync("cygpath", ["-u", compassTar], { encoding: "utf-8" }).trim();- tarDest = execFileSync("cygpath", ["-u", COMPASS_DIR], { encoding: "utf-8" }).trim();- } catch { /* use as-is */ }- }- execFileSync(- "tar",- ["-xzf", tarFile, "-C", tarDest, "--strip-components=1"],- { stdio: "ignore" }- );+ stage = "extract";+ installCompassBundle(compassTar, COMPASS_DIR, compassStaging, compassBackup);+ // Its own stage: a failure here is a bundle that installed fine and+ // did not get stamped, which is not an extract problem and should+ // not be reported as one.+ stage = "stamp";writeFileSync(COMPASS_VERSION_FILE, compassLatest);console.log(`[ok] Compass upgraded to ${compassLatest}`);- } catch {- console.error("[!!] Could not download compass update. ix view may use the bundled version.");+ } catch (err) {+ console.error(`[!!] Compass ${stage} failed: ${describeExecFailure(err)}`);+ // Whether this is a degraded upgrade or a broken `ix view` depends+ // on what survived, and only the second is worth alarming about.+ // getInstalledCompassVersion reports "0.0.0" for a bundle with no+ // stamp beside it, so read the disk rather than quoting a version.+ if (existsSync(join(COMPASS_DIR, "index.html"))) {+ console.error(` ix view keeps working on the compass already installed (source: ${compassUrl})`);+ } else if (existsSync(compassBackup)) {+ // swapInStagedTree moved the old compass aside and then could not+ // put it back, so this is the only copy left. Name it rather than+ // letting the cleanup below take it, exactly as the CLI swap does.+ console.error(` Your previous compass is still at: ${compassBackup}`);+ console.error(` Rename that directory to ${COMPASS_DIR} to restore ix view, or re-run ix upgrade.`);+ } else {+ console.error(` ix view stays unavailable until this succeeds (source: ${compassUrl})`);+ }}+ cleanupCompassSwap(COMPASS_DIR, compassStaging, compassBackup);rmSync(compassTmp, { recursive: true, force: true });}} else if (compassLatest) {diff --git a/scripts/install/install.ps1 b/scripts/install/install.ps1index e889bcac..3f3bd3ee 100644--- a/scripts/install/install.ps1+++ b/scripts/install/install.ps1@@ -52,8 +52,15 @@ trap {function Test-Healthy {try {- $null = Invoke-WebRequest -Uri $HealthUrl -TimeoutSec 3 -ErrorAction Stop- $null = Invoke-WebRequest -Uri $ArangoUrl -TimeoutSec 3 -ErrorAction Stop+ # -UseBasicParsing, or Windows PowerShell hands the response to the IE+ # engine and stops the install on an interactive "Script Execution Risk"+ # prompt that defaults to No. It only fires once a backend is actually+ # up and returning a body — a first install has nothing listening, the+ # request fails outright, and the parse never happens. So this bites on+ # re-runs and upgrades, never on the machine you first tested. Both+ # endpoints return JSON that nothing here reads; only the status matters.+ $null = Invoke-WebRequest -Uri $HealthUrl -TimeoutSec 3 -UseBasicParsing -ErrorAction Stop+ $null = Invoke-WebRequest -Uri $ArangoUrl -TimeoutSec 3 -UseBasicParsing -ErrorAction Stopreturn $true} catch { return $false }}@@ -256,7 +263,6 @@ $Url = "https://github.com/$GithubOrg/$GithubRepo/releases/download/v$Version/$T$tmp = "$env:TEMP\$Tarball"$InstallDir = "$IxHome\cli"-New-Item -ItemType Directory -Force -Path $InstallDir | Out-NullNew-Item -ItemType Directory -Force -Path $IxBin | Out-NullWrite-Host "Downloading CLI..."@@ -270,25 +276,125 @@ if ($LASTEXITCODE -ne 0) {Write-Ok "Downloaded to $tmp"-if (-not (Test-Path $tmp)) {+if (-not (Test-Path -LiteralPath $tmp)) {Write-Err "Zip missing"}-$size = (Get-Item $tmp).Length+$size = (Get-Item -LiteralPath $tmp).Lengthif ($size -lt 100000) {Write-Err "Downloaded file too small (likely failed)"}Write-Host "Extracting CLI..."-Expand-Archive -Path $tmp -DestinationPath $InstallDir -Force++# The zip nests everything under ix-<version>-windows-amd64\, and Expand-Archive+# has no --strip-components. Extracting straight into cli\ therefore produced+# cli\ix-<version>-windows-amd64\compass\, while the CLI only ever looks in+# cli\compass (COMPASS_DIR in upgrade.ts, findCompassDist in view.ts). Every+# Windows install shipped a Compass that `ix view` could not see and fell back+# to a network repair that is not guaranteed to work — so `ix view` was broken+# on Windows even when the release bundled Compass correctly.+#+# Collapse that directory here. install.sh has always stripped it via tar, and+# `ix upgrade` already resolves either shape, so this makes a fresh Windows+# install match both.+# `.cli-staging-<pid>`, not a fixed name: sweepUpgradeOrphans in upgrade.ts+# reclaims `.cli-staging-*` and `.cli-backup-*`, so an installer killed+# mid-extract is cleaned up by the next `ix upgrade` instead of leaking a copy+# of the release into IX_HOME forever. The pid also keeps two concurrent runs+# from sharing a staging directory.+$Staging = "$IxHome\.cli-staging-$PID"+Remove-Item -Recurse -Force -LiteralPath $Staging -ErrorAction SilentlyContinue+New-Item -ItemType Directory -Force -Path $Staging | Out-Null+# -LiteralPath: -Path glob-expands, so a home directory containing [ or ] takes+# these off the real file — measured on 5.1, `Test-Path` returns False for a+# file that exists and `Remove-Item` silently no-ops. extractZipOnWindows in+# upgrade.ts already uses it for this reason. Applied to every path-taking+# cmdlet from the download onwards, not just this block: the zip's own+# Test-Path/Get-Item run first, so hardening only the extract would still have+# left the installer dying at "Zip missing" on such a home.+Expand-Archive -LiteralPath $tmp -DestinationPath $Staging -Force++# Exactly one directory, not merely the first of several — the same rule+# soleChildDir applies in upgrade.ts. `Select-Object -First 1` would pick one+# of several arbitrarily and could collapse the wrong tree into cli\.+# -Force counts hidden directories, so this stays the same test install.sh+# makes with `find -type d`, which counts them too.+$TopDirs = @(Get-ChildItem -LiteralPath $Staging -Directory -Force)+if ($TopDirs.Count -ne 1 -or -not (Test-Path -LiteralPath (Join-Path $TopDirs[0].FullName "ix.cmd"))) {+ Remove-Item -Recurse -Force -LiteralPath $Staging -ErrorAction SilentlyContinue+ Write-Err "Extracted archive is not an ix release: expected one top-level directory containing ix.cmd, found $($TopDirs.Count). Left the existing install untouched."+}+$Extracted = $TopDirs[0]++# Swap only once the new tree is known good, and move the old one aside instead+# of deleting it so a failed move can be undone. Deleting first is what left+# Windows users with no CLI at all in #337.+$Backup = "$IxHome\.cli-backup-$PID"++# Clear the backup path first, as swapInStagedTree does with rmQuiet(backupDir).+# Directory::Move refuses to move onto an existing destination, so a stale+# .cli-backup-<pid> — left by an earlier run that died mid-swap, on a pid Windows+# has since reused — would abort the swap. Check it actually went: -ErrorAction+# SilentlyContinue hides a removal that *failed* exactly as well as one that had+# nothing to do, and a locked leftover would otherwise send the swap in blind.+Remove-Item -Recurse -Force -LiteralPath $Backup -ErrorAction SilentlyContinue+if (Test-Path -LiteralPath $Backup) {+ Remove-Item -Recurse -Force -LiteralPath $Staging -ErrorAction SilentlyContinue+ Write-Err "Could not clear a leftover backup at $Backup. Remove it and re-run. Left the existing install untouched."+}++# [System.IO.Directory]::Move, not Move-Item.+#+# Move-Item on a directory falls back to a recursive copy-then-delete whenever+# the rename cannot be done, and then throws *part way through* — leaving the+# tree split across both paths, ix.cmd in the backup and cli\dist\cli\main.js+# still in cli\. The restore below cannot fire in that state, because it guards+# on `-not (Test-Path $InstallDir)` and $InstallDir still exists. So the branch+# written to protect the user's CLI is skipped in precisely the case that+# destroyed it, and the installer exits reporting only the lock message.+#+# On Windows an open handle under cli\ is routine rather than exotic: a running+# `ix view` serving compass out of cli\compass, `ix watch` holding tree-sitter's+# .node addons mapped for the life of the process, or Defender scanning the+# native modules the extract just wrote.+#+# Directory::Move is a plain rename — it either happens or the source is left+# untouched, and it will not move a directory *inside* an existing destination+# the way Move-Item does. That is the atomicity swapInStagedTree gets for free+# from fs.renameSync, and which this block only claimed to match.+try {+ if (Test-Path -LiteralPath $InstallDir) { [System.IO.Directory]::Move($InstallDir, $Backup) }+ [System.IO.Directory]::Move($Extracted.FullName, $InstallDir)+ Remove-Item -Recurse -Force -LiteralPath $Backup -ErrorAction SilentlyContinue+} catch {+ # Capture before the nested try below rebinds $_, and unwrap the+ # MethodInvocationException so the message is the IO error itself rather+ # than 'Exception calling "Move" with "2" argument(s)'.+ $failure = if ($_.Exception.InnerException) { $_.Exception.InnerException.Message } else { $_.Exception.Message }+ if ((Test-Path -LiteralPath $Backup) -and -not (Test-Path -LiteralPath $InstallDir)) {+ try {+ [System.IO.Directory]::Move($Backup, $InstallDir)+ Write-Warn "Restored the previous CLI after a failed update."+ } catch {+ # Name the surviving copy, the way upgrade.ts does when its own+ # restore fails. Without this the user cannot tell that the install+ # is gone rather than merely unchanged.+ Write-Warn "Your previous CLI is still at $Backup — rename it to $InstallDir to restore it."+ }+ }+ Remove-Item -Recurse -Force -LiteralPath $Staging -ErrorAction SilentlyContinue+ Write-Err "Could not install to $InstallDir : $failure"+}+Remove-Item -Recurse -Force -LiteralPath $Staging -ErrorAction SilentlyContinueWrite-Ok "Extraction complete"-Remove-Item $tmp -Force+Remove-Item -LiteralPath $tmp -Force@"@echo off-"%~dp0..\cli\ix-$Version-windows-amd64\ix.cmd" %*-"@ | Out-File "$IxBin\ix.cmd" -Encoding ascii+"%~dp0..\cli\ix.cmd" %*+"@ | Out-File -LiteralPath "$IxBin\ix.cmd" -Encoding ascii$userPath = [Environment]::GetEnvironmentVariable("PATH","User")if ($userPath -notlike "*$IxBin*") {@@ -310,18 +416,18 @@ if ($BackendVer) {# stayed broken forever.## This tests the path the CLI actually reads (COMPASS_DIR in upgrade.ts,-# findCompassDist in view.ts), not where the archive extracted. They differ here:-# Expand-Archive has no --strip-components, so a bundled compass lands in-# cli\ix-<version>-windows-amd64\compass\ and the CLI cannot see it. Do not-# "fix" this by pointing at that path — stamping a version for a bundle-# `ix view` will never find re-creates the poisoned stamp this change removes.-# Leaving it unstamped lets `ix upgrade` install a copy where the CLI looks.+# findCompassDist in view.ts). The extraction above collapses the archive's+# top-level directory, so that is now also where the bundled compass lands and+# this branch stamps a bundle `ix view` can genuinely serve. Keep the Test-Path+# on index.html: stamping a version for a compass that is not on disk is what+# made `ix upgrade` skip the repair download and break `ix view` permanently.+# The warning below is now a real failure signal, not the normal Windows path.$CompassVer = Get-CompassLatestVersion$CompassDir = Join-Path $IxHome "cli\compass"$CompassIndex = Join-Path $CompassDir "index.html"-if ($CompassVer -and (Test-Path $CompassIndex)) {+if ($CompassVer -and (Test-Path -LiteralPath $CompassIndex)) {[System.IO.File]::WriteAllText((Join-Path $CompassDir ".version"), $CompassVer)-} elseif (-not (Test-Path $CompassIndex)) {+} elseif (-not (Test-Path -LiteralPath $CompassIndex)) {Write-Warn "System Compass is not installed at $CompassDir — 'ix view' is unavailable until you run 'ix upgrade', which will fetch it."}diff --git a/scripts/install/install.sh b/scripts/install/install.shindex 8588b6d2..0f7192b2 100755--- a/scripts/install/install.sh+++ b/scripts/install/install.sh@@ -860,8 +860,14 @@ done# On Windows, avoid invoking the shim (calls cmd.exe, hangs in sh subshell)check_installed_version() {if [ "$PLATFORM" = "windows-amd64" ]; then- if [ -d "$INSTALL_DIR/ix-${VERSION}-windows-amd64" ]; then- echo "$VERSION"+ # Read the version out of the installed package rather than inferring it+ # from a version-named directory. That directory no longer exists — the+ # extract below collapses it — and probing for it would report "unknown"+ # against a perfectly current install, wiping and re-laying it on every+ # run, including one install.ps1 had just laid down correctly.+ if [ -f "$INSTALL_DIR/cli/package.json" ]; then+ sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' \+ "$INSTALL_DIR/cli/package.json" | head -1elseecho "unknown"fi@@ -953,7 +959,76 @@ if [ "$SKIP_CLI_INSTALL" = "0" ] && { [ ! -x "$IX_BIN/ix" ] || [ "$(check_instal# Extractif [ "$PLATFORM" = "windows-amd64" ]; then- unzip -q "$TMP_FILE" -d "$INSTALL_DIR"+ # unzip has no --strip-components, and the zip nests everything under+ # ix-<version>-windows-amd64/. Extracting straight into $INSTALL_DIR left a+ # bundled compass at cli/ix-<version>-windows-amd64/compass while the CLI+ # only ever reads cli/compass (COMPASS_DIR in upgrade.ts, findCompassDist in+ # view.ts), so `ix view` was unavailable on every Windows install made from+ # this script — the same break install.ps1 had.+ #+ # Unzip into staging and move the single top-level directory into place, so+ # both installers and `ix upgrade` lay down one shape. Without this the two+ # installers disagree on the same platform and half-break each other:+ # check_installed_version below reads the flat entry point, so a nested+ # tree reports "unknown" and gets replaced, and vice versa.+ ZIP_STAGING="$TMP_DIR/staged"+ mkdir -p "$ZIP_STAGING"+ unzip -q "$TMP_FILE" -d "$ZIP_STAGING"+ # Exactly one directory, matching soleChildDir in upgrade.ts and the guard+ # in install.ps1. Anything else is not a release we recognise, and+ # collapsing an arbitrary one of several would install the wrong tree.+ ZIP_TOP_COUNT=$(find "$ZIP_STAGING" -mindepth 1 -maxdepth 1 -type d | wc -l | tr -d ' ')+ ZIP_TOP=$(find "$ZIP_STAGING" -mindepth 1 -maxdepth 1 -type d | head -1)+ if [ "$ZIP_TOP_COUNT" != "1" ] || [ ! -f "$ZIP_TOP/ix.cmd" ]; then+ rm -rf "$TMP_DIR"+ err "Extracted archive is not an ix release: expected one top-level directory containing ix.cmd, found $ZIP_TOP_COUNT."+ fi+ # Move the old install aside rather than deleting it, then put it back if+ # the swap fails — the same shape as install.ps1 and swapInStagedTree.+ #+ # $INSTALL_DIR is not reliably the empty directory `mkdir -p` just made. The+ # `rm -rf "$INSTALL_DIR"` in the upgrade branch above only runs when+ # `[ -x "$IX_BIN/ix" ]`, and install.ps1 writes %IX_HOME%\bin\ix.cmd rather+ # than $IX_BIN/ix — so a populated install reaches here whenever the two+ # installers are mixed, or pick_bin_dir() resolves differently than it did+ # last run. Deleting that outright would destroy a working CLI with nothing+ # to restore from, and `mv` onto a directory that survived the delete would+ # silently nest the tree inside it, recreating the exact layout this is+ # here to remove.+ ZIP_BACKUP="$IX_HOME/.cli-backup-$$"+ # `|| true` on every cleanup rm below. Under `set -e` a bare rm that fails+ # aborts the script where it stands — verified — and the ones after the swap+ # sit between the new tree and the shim write, so a locked leftover would+ # install the CLI and then skip the launcher, ensure_path and both version+ # stamps. That is the brick rmQuiet() exists to prevent on the TS side and+ # that install.ps1 avoids with -ErrorAction SilentlyContinue.+ if ! rm -rf "$ZIP_BACKUP" 2>/dev/null && [ -e "$ZIP_BACKUP" ]; then+ rm -rf "$TMP_DIR" || true+ err "Could not clear a leftover backup at $ZIP_BACKUP. Remove it and re-run. The existing install is untouched."+ fi+ # Drop the empty directory `mkdir -p` just made, so a first-time install has+ # no backup at all and cannot report restoring a CLI that never existed.+ # rmdir fails harmlessly on a populated install, which is the one we want to+ # move aside.+ rmdir "$INSTALL_DIR" 2>/dev/null || true+ if [ -e "$INSTALL_DIR" ] && ! mv "$INSTALL_DIR" "$ZIP_BACKUP"; then+ rm -rf "$TMP_DIR" || true+ err "Could not move the existing install aside from $INSTALL_DIR. It is untouched."+ fi+ if mv "$ZIP_TOP" "$INSTALL_DIR"; then+ rm -rf "$ZIP_BACKUP" || true+ else+ # if/else, not `mv ... && warn`: with && a *failed* restore short-circuits+ # and says nothing at all, so the user is never told the only surviving+ # copy is at $ZIP_BACKUP — which is the case the backup exists for.+ if [ -d "$ZIP_BACKUP" ] && [ ! -e "$INSTALL_DIR" ] && mv "$ZIP_BACKUP" "$INSTALL_DIR"; then+ warn "Restored the previous CLI after a failed update."+ elif [ -d "$ZIP_BACKUP" ]; then+ warn "Your previous CLI is at $ZIP_BACKUP — move it to $INSTALL_DIR to restore it."+ fi+ rm -rf "$TMP_DIR" || true+ err "Could not install to $INSTALL_DIR."+ fielsetar -xzf "$TMP_FILE" -C "$INSTALL_DIR" --strip-components=1fi@@ -962,7 +1037,9 @@ if [ "$SKIP_CLI_INSTALL" = "0" ] && { [ ! -x "$IX_BIN/ix" ] || [ "$(check_instal# Create wrapper shim in bin dirif [ "$PLATFORM" = "windows-amd64" ]; then- IX_JS="$INSTALL_DIR/ix-${VERSION}-windows-amd64/cli/dist/cli/main.js"+ # No version in the path any more: the tree is flat, and refreshLaunchers+ # in upgrade.ts rewrites this shim to exactly this form after an upgrade.+ IX_JS="$INSTALL_DIR/cli/dist/cli/main.js"cat > "$IX_BIN/ix" <<SHIM#!/bin/shexec node "$IX_JS" "\$@"@@ -992,13 +1069,13 @@ BACKEND_VER=$(resolve_backend_version)# stayed broken forever. The bundle ships inside the release tarball; if it is# absent, leaving the stamp off lets `ix upgrade` self-heal from ix-compass-dist.# This tests the path the CLI actually reads (COMPASS_DIR in upgrade.ts,-# findCompassDist in view.ts), not wherever the archive happened to extract.-# Those differ on Windows: the zip is expanded without stripping its top-level-# directory, so a bundled compass lands in cli/ix-<version>-windows-amd64/ and-# the CLI cannot see it. Do not "fix" this by pointing at that path — stamping a-# version for a bundle `ix view` will never find re-creates the poisoned stamp-# this change exists to remove. Leaving it unstamped lets `ix upgrade` install a-# copy where the CLI does look.+# findCompassDist in view.ts). The Windows extract above now collapses the+# archive's top-level directory, so that is also where the bundled compass+# lands and this branch stamps a bundle `ix view` can genuinely serve — the+# warning below is a real failure signal on every platform, not the normal+# Windows path. Keep the -f test on index.html: stamping a version for a+# compass that is not on disk is what made `ix upgrade` skip the repair+# download and break `ix view` permanently.COMPASS_VER=$(resolve_compass_version)if [ -n "$COMPASS_VER" ] && [ -f "$IX_HOME/cli/compass/index.html" ]; thenprintf '%s' "$COMPASS_VER" > "$IX_HOME/cli/compass/.version"