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): make the ix.cmd launcher diagnose its own broken target (#386)
KageBinary83a534f6a8d1
diff --git a/ix-cli/src/cli/__tests__/windows-launcher.test.ts b/ix-cli/src/cli/__tests__/windows-launcher.test.tsnew file mode 100644index 00000000..33ee3e41--- /dev/null+++ b/ix-cli/src/cli/__tests__/windows-launcher.test.ts@@ -0,0 +1,149 @@+import { describe, expect, it } from "vitest";+import { win32 as winPath } from "node:path";+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";++import { windowsShimBody } from "../commands/upgrade.js";+import { checkWindowsLauncher } from "../commands/doctor.js";++/**+ * Ix#385: `ix upgrade` before 0.9.0 refreshed only the bash shim and left+ * `%IX_HOME%\bin\ix.cmd` pointing at a `cli\ix.cmd` the upgrade had just+ * replaced with a version-nested directory. cmd.exe's error names the wrapper+ * rather than the cause:+ *+ * '"C:\Users\Win 10\.ix\bin\..\cli\ix.cmd"' is not recognized as an internal+ * or external command, operable program or batch file.+ *+ * The fix cannot be delivered by new CLI code — the *old* version performs the+ * upgrade — so the launcher has to diagnose itself, and the CLI that would+ * explain it is exactly as unreachable as the launcher.+ */+describe("windowsShimBody", () => {+ const FLAT = String.raw`%~dp0..\cli\ix.cmd`;+ const NESTED = String.raw`%~dp0..\cli\ix-0.9.1-windows-amd64\ix.cmd`;++ it("guards the target before invoking it", () => {+ const body = windowsShimBody(FLAT);+ const guard = body.indexOf(`if not exist "${FLAT}" goto :ix_missing`);+ const invoke = body.indexOf(`"${FLAT}" %*`);+ expect(guard).toBeGreaterThanOrEqual(0);+ expect(invoke).toBeGreaterThan(guard);+ });++ it("propagates the CLI's exit code on the success path", () => {+ // Without this the launcher always exits 0 and every non-zero ix exit —+ // a failed map, a Pro stub — reads as success to any caller.+ expect(windowsShimBody(FLAT)).toContain("exit /b %errorlevel%");+ });++ it("names the cause and the recovery, not just the missing path", () => {+ const body = windowsShimBody(FLAT);+ expect(body).toContain("ix upgrade");+ expect(body).toContain("irm https://ix-infra.com/install.ps1 ^| iex");+ expect(body).toContain("exit /b 1");+ });++ it("escapes the pipe so cmd.exe prints it instead of building a pipeline", () => {+ // A bare | in `echo irm ... | iex` pipes echo's output into `iex`, which+ // does not exist as a program on Windows, so the recovery line would be+ // replaced by an error about `iex`.+ const body = windowsShimBody(FLAT);+ expect(body).toContain("^| iex");+ expect(body).not.toMatch(/[^^]\| iex/);+ });++ it("uses CRLF, which batch files require", () => {+ const body = windowsShimBody(FLAT);+ expect(body).toContain("\r\n");+ expect(body.split("\r\n").length).toBeGreaterThan(5);+ expect(body).not.toMatch(/[^\r]\n/);+ });++ it("carries the nested target through verbatim", () => {+ const body = windowsShimBody(NESTED);+ expect(body).toContain(`if not exist "${NESTED}" goto :ix_missing`);+ expect(body).toContain(`"${NESTED}" %*`);+ expect(body).not.toContain(FLAT);+ });+});++describe("install.ps1 and refreshLaunchers emit the same launcher", () => {+ it("does not let the two writers drift apart", () => {+ // Two places write this file: install.ps1 on a fresh install, and+ // refreshLaunchers() on every upgrade. They have drifted before — the flat+ // vs version-nested shim bugs (#346, #385) were both one writer learning+ // something the other did not. A fresh install and an upgraded install must+ // end up with byte-identical launchers.+ const ps1 = readFileSync(+ fileURLToPath(new URL("../../../../scripts/install/install.ps1", import.meta.url)),+ "utf-8",+ );+ const heredoc = ps1.match(/@"\r?\n(@echo off\r?\n[\s\S]*?)\r?\n"@ \| Out-File/);+ expect(heredoc, "install.ps1 no longer contains the ix.cmd here-string").not.toBeNull();++ const fromInstaller = heredoc![1].replace(/\r?\n/g, "\n").trim();+ const fromUpgrade = windowsShimBody(String.raw`%~dp0..\cli\ix.cmd`)+ .replace(/\r?\n/g, "\n")+ .trim();++ expect(fromInstaller).toBe(fromUpgrade);+ });+});++describe("checkWindowsLauncher", () => {+ const IX_HOME = String.raw`C:\Users\Win 10\.ix`;+ const shim = (target: string) => windowsShimBody(target);++ it("passes when the launcher target exists", () => {+ const result = checkWindowsLauncher(+ IX_HOME,+ () => shim(String.raw`%~dp0..\cli\ix.cmd`),+ () => true,+ );+ expect(result.ok).toBe(true);+ });++ it("fails with the repair command when the target is gone", () => {+ const result = checkWindowsLauncher(+ IX_HOME,+ () => shim(String.raw`%~dp0..\cli\ix.cmd`),+ () => false,+ );+ expect(result.ok).toBe(false);+ expect(result.warn).toBeFalsy();+ expect(result.detail).toContain("does not exist");+ expect(result.detail).toContain("install.ps1");+ });++ it("resolves the target relative to bin/, matching %~dp0", () => {+ // %~dp0 is the directory of ix.cmd itself — IX_HOME\bin — so the check has+ // to resolve from there, not from IX_HOME, or it probes the wrong path and+ // reports a healthy install as broken.+ const probed: string[] = [];+ checkWindowsLauncher(+ IX_HOME,+ () => shim(String.raw`%~dp0..\cli\ix.cmd`),+ (p) => { probed.push(p); return true; },+ );+ expect(probed).toEqual([winPath.join(IX_HOME, "cli", "ix.cmd")]);+ });++ it("is silent when no launcher exists (POSIX install, or never installed)", () => {+ const result = checkWindowsLauncher(IX_HOME, () => null, () => false);+ expect(result.ok).toBe(true);+ });++ it("leaves an unrecognized launcher alone rather than calling it broken", () => {+ // A contributor's dev shim from scripts/dev/setup.sh points straight at a+ // working tree with an absolute path. Reporting that as a failure would+ // send them reinstalling over their own build.+ const result = checkWindowsLauncher(+ IX_HOME,+ () => '@echo off\r\nnode "C:\\src\\Ix\\ix-cli\\dist\\cli\\main.js" %*\r\n',+ () => false,+ );+ expect(result.ok).toBe(true);+ expect(result.warn).toBe(true);+ });+});diff --git a/ix-cli/src/cli/commands/doctor.ts b/ix-cli/src/cli/commands/doctor.tsindex 9be4da37..8ba94d01 100644--- a/ix-cli/src/cli/commands/doctor.ts+++ b/ix-cli/src/cli/commands/doctor.ts@@ -4,6 +4,9 @@ import { renderSection, renderSuccess, renderError } from "../ui.js";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";import { llmLine, printLlmLines } from "../llm.js";+import { existsSync, readFileSync } from "node:fs";+import { join as pathJoin, win32 as winPath } from "node:path";+import { homedir } from "node:os";import {BACKEND_IMAGE,checkBackendImage,@@ -59,6 +62,54 @@ interface Check {run: () => Promise<CheckResult>;}+/**+ * Does `%IX_HOME%\bin\ix.cmd` still point at a CLI that exists?+ *+ * `ix upgrade` before 0.9.0 refreshed only the bash shim and left this launcher+ * aimed at a `cli\ix.cmd` the upgrade had just replaced with a version-nested+ * directory (Ix#385).+ *+ * The obvious objection is that a user whose launcher is broken cannot run+ * `ix doctor` to be told so. True from PowerShell — which is why the launcher+ * now diagnoses itself. This check covers the case that shim cannot: the *bash*+ * shim under Git Bash / MSYS is refreshed by every version, so `ix` keeps+ * working there while the native launcher is quietly dead. Someone who lives in+ * Git Bash can be broken in PowerShell for weeks without knowing.+ */+export function checkWindowsLauncher(+ ixHome: string,+ readShim: (path: string) => string | null,+ exists: (path: string) => boolean,+): CheckResult {+ const shimPath = pathJoin(ixHome, "bin", "ix.cmd");+ const body = readShim(shimPath);+ if (body === null) {+ return { ok: true, detail: "no ix.cmd launcher (not installed by install.ps1)" };+ }++ // The launcher invokes its target as the first quoted %~dp0-relative path.+ const target = body.match(/"(%~dp0[^"]+)"/)?.[1];+ if (!target) {+ return { ok: true, warn: true, detail: `${shimPath}: unrecognized launcher, left alone` };+ }++ // %~dp0 is the directory of ix.cmd itself — IX_HOME\bin — and the target is+ // written with backslashes. Resolve with win32 semantics explicitly rather+ // than the ambient `path`, so the separator handling does not depend on which+ // OS happens to be evaluating it. (Production only reaches here on Windows,+ // but a resolver that silently misreads its input off-Windows is untestable.)+ const resolved = winPath.join(ixHome, "bin", target.replace(/^%~dp0/, ""));+ if (exists(resolved)) return { ok: true, detail: `ix.cmd → ${target}` };++ return {+ ok: false,+ detail:+ `${shimPath} points at ${target}, which does not exist — ` ++ "an upgrade from before 0.9.0 moved the CLI. Reinstall to repair: " ++ "irm https://ix-infra.com/install.ps1 | iex",+ };+}+export function registerDoctorCommand(program: Command): void {program.command("doctor")@@ -169,6 +220,19 @@ export function registerDoctorCommand(program: Command): void {},];+ // Windows-only: a launcher pointing at a CLI the upgrade moved (Ix#385).+ if (process.platform === "win32") {+ checks.push({+ name: "Windows launcher",+ run: async () =>+ checkWindowsLauncher(+ process.env.IX_HOME || pathJoin(homedir(), ".ix"),+ (p) => { try { return readFileSync(p, "utf-8"); } catch { return null; } },+ existsSync,+ ),+ });+ }+const results: Array<{ name: string } & CheckResult> = [];for (const check of checks) {const result = await check.run();diff --git a/ix-cli/src/cli/commands/upgrade.ts b/ix-cli/src/cli/commands/upgrade.tsindex dc04e8e9..cc281a49 100644--- a/ix-cli/src/cli/commands/upgrade.ts+++ b/ix-cli/src/cli/commands/upgrade.ts@@ -323,6 +323,49 @@ function rmQuiet(target: string): void {* 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.*/+/**+ * The body of `%IX_HOME%\bin\ix.cmd`, which is the launcher every native+ * Windows shell actually runs.+ *+ * It checks its own target before invoking it, because the failure it is+ * guarding against is unrecoverable from inside the CLI. `ix upgrade` on any+ * version before 0.9.0 refreshed only the *bash* shim under Git Bash and left+ * this file pointing at a `cli\ix.cmd` that the upgrade had just replaced with+ * a version-nested directory (Ix#385). The user is then holding a launcher that+ * cannot start the program that would have told them what to do — cmd.exe says+ * only:+ *+ * '"C:\Users\...\.ix\bin\..\cli\ix.cmd"' is not recognized as an internal or+ * external command, operable program or batch file.+ *+ * which names the wrapper rather than the cause and reads like a broken install+ * rather than a broken upgrade. So the recovery instruction has to live in the+ * batch file itself. Nothing else in the system can reach them at that point:+ * `ix doctor` is exactly as unreachable as `ix`.+ *+ * `^|` is an escaped pipe — cmd.exe would otherwise treat it as a pipeline.+ */+export function windowsShimBody(inner: string): string {+ return [+ "@echo off",+ `if not exist "${inner}" goto :ix_missing`,+ `"${inner}" %*`,+ "exit /b %errorlevel%",+ "",+ ":ix_missing",+ "echo(",+ `echo The Ix CLI is not at "${inner}".`,+ "echo(",+ "echo An 'ix upgrade' from a version before 0.9.0 moved the CLI and left",+ "echo this launcher pointing at the old path. Reinstalling repairs it:",+ "echo(",+ "echo irm https://ix-infra.com/install.ps1 ^| iex",+ "echo(",+ "exit /b 1",+ "",+ ].join("\r\n");+}+export function soleChildDir(dir: string): string | null {let entries;try {@@ -696,7 +739,7 @@ function refreshLaunchers(installDir: string, installedRoot: string, isWindows: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");+ writeFileSync(cmdShim, windowsShimBody(inner), "ascii");}} catch (err) {problems.push(`${cmdShim}: ${(err as Error).message}`);diff --git a/scripts/install/install.ps1 b/scripts/install/install.ps1index bcc26516..7a876b17 100644--- a/scripts/install/install.ps1+++ b/scripts/install/install.ps1@@ -486,9 +486,28 @@ Write-Ok "Extraction complete"Remove-Item -LiteralPath $tmp -Force+# Checks its own target before invoking it. `ix upgrade` on any version before+# 0.9.0 refreshed only the bash shim and left this file pointing at a+# `cli\ix.cmd` the upgrade had just replaced with a version-nested directory+# (Ix#385). cmd.exe's own error names this wrapper rather than the cause, and+# the CLI that would explain it is exactly as unreachable as the launcher — so+# the recovery instruction has to live here. `^|` is an escaped pipe.@"@echo off+if not exist "%~dp0..\cli\ix.cmd" goto :ix_missing"%~dp0..\cli\ix.cmd" %*+exit /b %errorlevel%++:ix_missing+echo(+echo The Ix CLI is not at "%~dp0..\cli\ix.cmd".+echo(+echo An 'ix upgrade' from a version before 0.9.0 moved the CLI and left+echo this launcher pointing at the old path. Reinstalling repairs it:+echo(+echo irm https://ix-infra.com/install.ps1 ^| iex+echo(+exit /b 1"@ | Out-File -LiteralPath "$IxBin\ix.cmd" -Encoding ascii$userPath = [Environment]::GetEnvironmentVariable("PATH","User")