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
test(cli): keep tests out of the real /.ix and fail the run if they do (#877)
Ian Hocke09f7aa50f67
diff --git a/ix-cli/src/cli/__tests__/backend-version-home.test.ts b/ix-cli/src/cli/__tests__/backend-version-home.test.tsnew file mode 100644index 00000000..a41e461a--- /dev/null+++ b/ix-cli/src/cli/__tests__/backend-version-home.test.ts@@ -0,0 +1,73 @@+// Copyright 2026 Ix Infrastructure Inc.++import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";+import { homedir, tmpdir } from "node:os";+import { join } from "node:path";++// Imported statically, so the module is loaded -- and anything it computes at+// import time is fixed -- before any test below changes IX_HOME. That is the+// order the leak needed: a module that bound `$IX_HOME/.backend-version` to a+// const at load kept writing to whatever home was current then, however a+// later test isolated itself.+import { backendVersionFile, recordBackendRelease } from "../backend-version.js";+import { backendCeiling } from "../commands/upgrade.js";++const isNewer = (a: string, b: string): boolean =>+ a.localeCompare(b, undefined, { numeric: true }) > 0;++let loadHome: string | undefined;+let home: string;++beforeEach(() => {+ loadHome = process.env.IX_HOME;+ home = realpathSync(mkdtempSync(join(tmpdir(), "ix-bv-home-")));+});++afterEach(() => {+ if (loadHome === undefined) delete process.env.IX_HOME;+ else process.env.IX_HOME = loadHome;+ rmSync(home, { recursive: true, force: true });+});++describe("the backend-version stamp follows IX_HOME at call time", () => {+ it("writes the stamp under an IX_HOME set after the module was imported", () => {+ process.env.IX_HOME = home;++ expect(backendVersionFile()).toBe(join(home, ".backend-version"));+ expect(recordBackendRelease("1.2.3", "1.2.3", isNewer)).toBe(true);++ expect(readFileSync(join(home, ".backend-version"), "utf-8")).toBe("1.2.3");+ // ...and not in the home that was current when the module loaded.+ if (loadHome) expect(existsSync(join(loadHome, ".backend-version"))).toBe(false);+ });++ it("is re-resolved on every call", () => {+ process.env.IX_HOME = home;+ const first = backendVersionFile();+ const second = join(home, "second");+ process.env.IX_HOME = second;+ expect(backendVersionFile()).toBe(join(second, ".backend-version"));+ expect(backendVersionFile()).not.toBe(first);+ });++ it("upgrade.ts reads its release cache from the IX_HOME current at call time", () => {+ // The same leak in upgrade.ts: its `.version-check.json` (the ceiling a+ // container's reported version is held to) was bound at import too.+ process.env.IX_HOME = home;+ mkdirSync(home, { recursive: true });+ writeFileSync(+ join(home, ".version-check.json"),+ JSON.stringify({ latest: "1.0.0", backendLatest: "3.4.5", checkedAt: Date.now() }),+ );+ expect(backendCeiling()).toBe("3.4.5");++ process.env.IX_HOME = join(home, "empty");+ expect(backendCeiling()).toBeNull();+ });++ it("falls back to ~/.ix when IX_HOME is unset, as the CLI always has", () => {+ delete process.env.IX_HOME;+ expect(backendVersionFile()).toBe(join(homedir(), ".ix", ".backend-version"));+ });+});diff --git a/ix-cli/src/cli/__tests__/upgrade-backend-stamp.test.ts b/ix-cli/src/cli/__tests__/upgrade-backend-stamp.test.tsindex d012b630..ac26aa58 100644--- a/ix-cli/src/cli/__tests__/upgrade-backend-stamp.test.ts+++ b/ix-cli/src/cli/__tests__/upgrade-backend-stamp.test.ts@@ -363,10 +363,11 @@ describe("composeTracksLatestBackend", () => {/*** `stampBackendVersionAfterPull` against a real, isolated IX_HOME.*- * The module resolves BACKEND_VERSION_FILE and VERSION_CACHE from IX_HOME at- * load, so IX_HOME is set and the module re-imported — without that, a- * regression in the early return would have this reaching api.github.com and- * overwriting the developer's own ~/.ix/.backend-version.+ * The module used to resolve the stamp and the version cache from IX_HOME at+ * load (both follow IX_HOME per call now), so IX_HOME is set and the module+ * re-imported — without that, a regression in the early return would have+ * this reaching api.github.com and overwriting the developer's own+ * ~/.ix/.backend-version.*/describe("stampBackendVersionAfterPull, isolated", () => {let home: string;diff --git a/ix-cli/src/cli/__tests__/upgrade-check-closing-line.test.ts b/ix-cli/src/cli/__tests__/upgrade-check-closing-line.test.tsindex 3b8aeb15..2ce58b4d 100644--- a/ix-cli/src/cli/__tests__/upgrade-check-closing-line.test.ts+++ b/ix-cli/src/cli/__tests__/upgrade-check-closing-line.test.ts@@ -56,9 +56,10 @@ describe("ix upgrade --check output", () => {let logs: string[];beforeEach(() => {- // upgrade.ts binds IX_HOME and VERSION_CACHE as module-level consts at load- // time, so `await import` below only picks up this temp home if the module- // is not already in the registry. Running this file alone it is not, and the+ // upgrade.ts used to bind IX_HOME and VERSION_CACHE as module-level consts+ // at load time (it resolves them per call now), so `await import` below+ // only picked up this temp home if the module was not already in the+ // registry. Running this file alone it is not, and the// test passed; in a full-suite run another file has already imported it and// the writeCache at the end of the command lands in the developer's REAL// ~/.ix, seeding latest: "99.0.0" for CLI, compass and backend. The testdiff --git a/ix-cli/src/cli/backend-status.ts b/ix-cli/src/cli/backend-status.tsindex 6a034f89..780fe241 100644--- a/ix-cli/src/cli/backend-status.ts+++ b/ix-cli/src/cli/backend-status.ts@@ -16,14 +16,12 @@import { execFileSync, spawnSync } from "node:child_process";import { join } from "node:path";-import { homedir } from "node:os";import type { IxClient } from "../client/api.js";import { fetchBackendHealth, isLocalEndpoint } from "./backend-version.js";import { getEndpoint } from "./config.js";+import { ixHome } from "./ix-home.js";export const BACKEND_IMAGE = "ghcr.io/ix-infrastructure/ix-memory-layer";-const IX_HOME = process.env.IX_HOME || join(homedir(), ".ix");-const STANDARD_BACKEND_DIR = join(IX_HOME, "backend");// On-disk graph format this CLI expects. MUST stay in sync with the backend's// reported schema_version; a mismatch forces a full re-ingest (see ingest.ts,@@ -295,7 +293,8 @@ export function checkBackendImage(endpoint: string = getEndpoint()): BackendImagexport function isNonStandardBackend(container: BackendContainer): boolean {const cfg = container.composeConfigFiles;if (!cfg) return false;- return !cfg.split(",").some((p) => p.trim().startsWith(STANDARD_BACKEND_DIR));+ const standardBackendDir = join(ixHome(), "backend");+ return !cfg.split(",").some((p) => p.trim().startsWith(standardBackendDir));}export interface BackendSchemaStatus {diff --git a/ix-cli/src/cli/backend-version.ts b/ix-cli/src/cli/backend-version.tsindex e9dc006f..459c63b9 100644--- a/ix-cli/src/cli/backend-version.ts+++ b/ix-cli/src/cli/backend-version.ts@@ -2,8 +2,8 @@import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";import { dirname, join } from "path";-import { homedir } from "os";+import { ixHome } from "./ix-home.js";import type { IxClient } from "../client/api.js";import type { HealthResponse } from "../client/types.js";@@ -17,10 +17,16 @@ import type { HealthResponse } from "../client/types.js";* future call site from silently forgetting to.*/-const IX_HOME = process.env.IX_HOME || join(homedir(), ".ix");--/** The release the backend is believed to be running. */-export const BACKEND_VERSION_FILE = join(IX_HOME, ".backend-version");+/**+ * The release the backend is believed to be running: `$IX_HOME/.backend-version`.+ *+ * A function, not a const, so the path follows IX_HOME as it is when the stamp+ * is read or written rather than when this module was first imported -- see+ * `ixHome()`.+ */+export function backendVersionFile(): string {+ return join(ixHome(), ".backend-version");+}/*** The one definition of a valid version string, imported by upgrade.ts too.@@ -123,7 +129,7 @@ export function recordBackendRelease(const value = typeof reported === "string" ? reported.trim() : "";if (!value || value.length > MAX_VERSION_LENGTH || !VERSION_RE.test(value)) return false;- const tracked = getTrackedVersion(BACKEND_VERSION_FILE);+ const tracked = getTrackedVersion(backendVersionFile());if (value === tracked) return false; // already agrees; do not touch the fileconst ceiling =@@ -133,7 +139,7 @@ export function recordBackendRelease(// No published release can be older than what a container legitimately runs.if (ceiling ? isNewer(value, ceiling) : isNewer(value, tracked)) return false;- return writeVersionStamp(BACKEND_VERSION_FILE, value);+ return writeVersionStamp(backendVersionFile(), value);}/**diff --git a/ix-cli/src/cli/commands/docker.ts b/ix-cli/src/cli/commands/docker.tsindex 86e53bdc..89fdb1e6 100644--- a/ix-cli/src/cli/commands/docker.ts+++ b/ix-cli/src/cli/commands/docker.ts@@ -5,16 +5,17 @@ import { execFileSync, spawn } from "child_process";import { createInterface } from "readline";import { copyFileSync, existsSync, mkdirSync, readFileSync } from "fs";import { dirname, join } from "path";-import { homedir } from "os";import { fileURLToPath } from "url";import { stampBackendVersionAfterPull } from "./upgrade.js";import { clearLocalToken, ensureLocalToken } from "../config.js";+import { ixHome } from "../ix-home.js";import { createClient } from "../../client/factory.js";import { backendComposeArgs, composeSupportsLocalToken, handSetLocalToken, parseArangoHealth } from "../backend-compose.js";-const IX_HOME = process.env.IX_HOME || join(homedir(), ".ix");-const COMPOSE_DIR = join(IX_HOME, "backend");-const LOCAL_COMPOSE = join(COMPOSE_DIR, "docker-compose.yml");+// Functions, not consts, so they follow IX_HOME as it is when a command runs+// rather than when this module was imported -- see `ixHome()`.+const composeDir = (): string => join(ixHome(), "backend");+const localCompose = (): string => join(composeDir(), "docker-compose.yml");const HEALTH_URL = "http://localhost:8090/v1/health";/**@@ -48,13 +49,14 @@ function bundledComposeFile(): string | null {* the installed CLI.*/function findComposeFile(): string | null {- if (existsSync(LOCAL_COMPOSE)) return LOCAL_COMPOSE;+ const local = localCompose();+ if (existsSync(local)) return local;const bundled = bundledComposeFile();if (!bundled) return null;try {- mkdirSync(COMPOSE_DIR, { recursive: true });- copyFileSync(bundled, LOCAL_COMPOSE);- return LOCAL_COMPOSE;+ mkdirSync(composeDir(), { recursive: true });+ copyFileSync(bundled, local);+ return local;} catch {return null;}@@ -73,7 +75,7 @@ function arangoHealth(composeFile: string | null): ReturnType<typeof parseArango}function reportMissingCompose(): void {- console.error(`[error] No backend compose file at ${LOCAL_COMPOSE}, and this CLI install does not ship one.`);+ console.error(`[error] No backend compose file at ${localCompose()}, and this CLI install does not ship one.`);console.error(" Reinstall or run 'ix upgrade' to restore it.");}@@ -200,10 +202,10 @@ export function registerDockerCommand(program: Command): void {let composeText = "";try { composeText = composeFile ? readFileSync(composeFile, "utf-8") : ""; } catch { /* reported below */ }if (!composeSupportsLocalToken(composeText)) {- console.error(`[error] ${composeFile ?? LOCAL_COMPOSE} does not pass IX_LOCAL_TOKEN to the backend.`);+ console.error(`[error] ${composeFile ?? localCompose()} does not pass IX_LOCAL_TOKEN to the backend.`);console.error(" It predates token support, and 'ix upgrade' does not replace it. Move it aside and");console.error(" run this again: 'ix docker start' then writes the compose file this CLI ships.");- console.error(` mv ${LOCAL_COMPOSE} ${LOCAL_COMPOSE}.old`);+ console.error(` mv ${localCompose()} ${localCompose()}.old`);process.exit(1);}// A token already set by hand in .env is adopted rather than replaced,diff --git a/ix-cli/src/cli/commands/upgrade.ts b/ix-cli/src/cli/commands/upgrade.tsindex 0ed5e9d2..5137af9a 100644--- a/ix-cli/src/cli/commands/upgrade.ts+++ b/ix-cli/src/cli/commands/upgrade.ts@@ -12,19 +12,20 @@ import { canRenderProgress } from "../stderr.js";import { ChecksumError, attestationCommand, downloadVerified, verifyAttestation } from "../integrity.js";import type { IxClient } from "../../client/api.js";import {- BACKEND_VERSION_FILE,VERSION_RE,+ backendVersionFile,fetchBackendHealth,getTrackedVersion,writeVersionStamp,} from "../backend-version.js";import { backendComposeArgs } from "../backend-compose.js";+import { ixHome } from "../ix-home.js";// Re-exported for the existing importers of this module (tests and call sites// that predate backend-version.ts). recordBackendRelease is deliberately NOT// among them: it is reached only through fetchBackendHealth, and re-exporting// it here would advertise a second way in.-export { BACKEND_VERSION_FILE, VERSION_RE, writeVersionStamp } from "../backend-version.js";+export { VERSION_RE, backendVersionFile, writeVersionStamp } from "../backend-version.js";/*** Fetch health and record what the backend says it is running.@@ -53,10 +54,11 @@ const GITHUB_ORG = "ix-infrastructure";const GITHUB_REPO = "Ix";const COMPASS_DIST_REPO = "ix-compass-dist";const MEMORY_LAYER_DIST_REPO = "ix-memory-layer-dist";-const IX_HOME = process.env.IX_HOME || join(homedir(), ".ix");-const VERSION_CACHE = join(IX_HOME, ".version-check.json");-const COMPASS_DIR = join(IX_HOME, "cli", "compass");-const COMPASS_VERSION_FILE = join(COMPASS_DIR, ".version");+// State paths are functions, not consts, so they follow IX_HOME as it is when+// a command runs rather than when this module was imported -- see `ixHome()`.+const versionCacheFile = (): string => join(ixHome(), ".version-check.json");+const compassDir = (): string => join(ixHome(), "cli", "compass");+const compassVersionFile = (): string => join(compassDir(), ".version");interface VersionCache {latest: string;@@ -115,8 +117,8 @@ async function fetchLatestRelease(function readCache(): VersionCache | null {try {- if (!existsSync(VERSION_CACHE)) return null;- const parsed = JSON.parse(readFileSync(VERSION_CACHE, "utf-8"));+ if (!existsSync(versionCacheFile())) return null;+ const parsed = JSON.parse(readFileSync(versionCacheFile(), "utf-8"));// JSON.parse only proves it is JSON, not that it is *this* shape. A cache// file holding `{"latest": 123}` used to reach isNewer() and throw// "latest.split is not a function", which surfaced as a successful command@@ -139,11 +141,11 @@ function readCache(): VersionCache | null {function writeCache(latest: string, compassLatest?: string, backendLatest?: string): void {try {- mkdirSync(IX_HOME, { recursive: true });+ mkdirSync(ixHome(), { recursive: true });const data: VersionCache = { latest, checkedAt: Date.now() };if (compassLatest) data.compassLatest = compassLatest;if (backendLatest) data.backendLatest = backendLatest;- writeFileSync(VERSION_CACHE, JSON.stringify(data));+ writeFileSync(versionCacheFile(), JSON.stringify(data));} catch {// non-critical}@@ -267,7 +269,7 @@ function getInstalledCompassVersion(): string {* is half the answer, and reading the file once keeps the two from disagreeing.*/function installedCompass(): CompassStamp & { present: boolean } {- const present = existsSync(join(COMPASS_DIR, "index.html"));+ const present = existsSync(join(compassDir(), "index.html"));if (!present) return { source: "dist", version: "0.0.0", present };return { ...readCompassStamp(), present };}@@ -342,8 +344,8 @@ export function parseCompassStamp(raw: string): CompassStamp {function readCompassStamp(): CompassStamp {try {- if (!existsSync(COMPASS_VERSION_FILE)) return { source: "dist", version: "0.0.0" };- return parseCompassStamp(readFileSync(COMPASS_VERSION_FILE, "utf-8"));+ if (!existsSync(compassVersionFile())) return { source: "dist", version: "0.0.0" };+ return parseCompassStamp(readFileSync(compassVersionFile(), "utf-8"));} catch {return { source: "dist", version: "0.0.0" };}@@ -430,7 +432,7 @@ function stampFailureMessage(): string {// "until it is writable" would be a guess — and a wrong one for the case the// tests actually reproduce, a directory sitting where the file belongs, which// no permission change fixes.- return `[!!] Could not record the version in ${BACKEND_VERSION_FILE}; until it can be written, backend update notices will be wrong.`;+ return `[!!] Could not record the version in ${backendVersionFile()}; until it can be written, backend update notices will be wrong.`;}/**@@ -549,7 +551,7 @@ export async function stampBackendVersionAfterPull(composeFile: string): Promise// `latest` first: it decides whether there is anything to write at all, so// it reads in the order it applies and does not lean on the writer's own// falsy check to make a null call a no-op.- if (latest && !writeVersionStamp(BACKEND_VERSION_FILE, latest)) {+ if (latest && !writeVersionStamp(backendVersionFile(), latest)) {// Must not fail the start, and only worth saying when the file really is// wrong: a root-owned stamp already holding what we just pulled fails to// write on every cold start with nothing actually out of date.@@ -558,7 +560,7 @@ export async function stampBackendVersionAfterPull(composeFile: string): Promise// fetched": a stamp stuck AHEAD is also wrong and also cannot be// corrected here, and the notice this warns about is computed from the// CACHED release, which can be up to an hour out of step with `latest`.- if (stampDisagreesWithPull(getTrackedVersion(BACKEND_VERSION_FILE), latest)) {+ if (stampDisagreesWithPull(getTrackedVersion(backendVersionFile()), latest)) {console.error(chalk.yellow(stampFailureMessage()));}}@@ -803,7 +805,7 @@ export function resolveStagedRoot(stagingDir: string, isWindows: boolean): strin* 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`+ * it had just seen through. compassDir() 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@@ -1032,11 +1034,11 @@ export function sweepUpgradeOrphans(ixHome: string, installDir: string): void {};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+ // join(installDir, "compass"), not compassDir(): that follows the process's+ // IX_HOME, and this function takes ixHome as an argument precisely so it can+ // be pointed elsewhere. Using compassDir() would make a test sweeping a temp+ // directory rename its fixture into whatever IX_HOME is current -- the+ // developer's own ~/.ix/cli/compass, outside the test setup. Recovered second because the restore above may be what// creates the parent directory it needs.recover(".compass-backup-", join(installDir, "compass"), "index.html", "compass");@@ -1166,7 +1168,7 @@ function refreshLaunchers(installDir: string, installedRoot: string, isWindows:const entryPath = join(installedRoot, "cli", "dist", "cli", "main.js");{- const cmdShim = join(IX_HOME, "bin", "ix.cmd");+ const cmdShim = join(ixHome(), "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@@ -1307,7 +1309,7 @@ export async function checkForUpdate(): Promise<void> {const hasCompassUpdate = shouldOfferCompassUpgrade(cache.compassLatest);const hasBackendUpdate = backendUpdateAvailable(cache.backendLatest,- getTrackedVersion(BACKEND_VERSION_FILE),+ getTrackedVersion(backendVersionFile()),);if (hasCliUpdate || hasCompassUpdate || hasBackendUpdate) {printUpdateNotice(current, cache.latest, !!hasCompassUpdate, !!hasBackendUpdate);@@ -1337,7 +1339,7 @@ export async function checkForUpdate(): Promise<void> {const hasCompassUpdate = shouldOfferCompassUpgrade(compassLatest ?? undefined);const hasBackendUpdate = backendUpdateAvailable(backendLatest ?? undefined,- getTrackedVersion(BACKEND_VERSION_FILE),+ getTrackedVersion(backendVersionFile()),);if (hasCliUpdate || hasCompassUpdate || hasBackendUpdate) {printUpdateNotice(current, latest, !!hasCompassUpdate, !!hasBackendUpdate);@@ -1444,7 +1446,7 @@ export function registerUpgradeCommand(program: Command): void {// 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"));+ if (!opts.check) sweepUpgradeOrphans(ixHome(), join(ixHome(), "cli"));// ── CLI upgrade ──────────────────────────────────────────────────// What is still outstanding when the command ends. Only meaningful under@@ -1479,7 +1481,7 @@ export function registerUpgradeCommand(program: Command): void {? `ix-${latest}-${platform}.zip`: `ix-${latest}-${platform}.tar.gz`;const url = `https://github.com/${GITHUB_ORG}/${GITHUB_REPO}/releases/download/v${latest}/${archiveName}`;- const installDir = join(IX_HOME, "cli");+ const installDir = join(ixHome(), "cli");// 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@@ -1492,7 +1494,7 @@ export function registerUpgradeCommand(program: Command): void {// 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 tmpDirRaw = prepareDownloadDir(ixHome(), installDir, ".cli-download-");const tmpFile = join(tmpDirRaw, archiveName);console.log(`Downloading ix ${latest} for ${platform}...`);@@ -1544,7 +1546,7 @@ export function registerUpgradeCommand(program: Command): void {// 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 stagingDir = join(ixHome(), `.cli-staging-${process.pid}`);const cleanupStaging = () => {rmQuiet(stagingDir);rmQuiet(tmpDirRaw);@@ -1604,12 +1606,12 @@ export function registerUpgradeCommand(program: Command): void {// 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}`);+ const backupDir = join(ixHome(), `.cli-backup-${process.pid}`);try {// 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+ // compass at cli\ix-<version>-<platform>\compass while compassDir()// 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);@@ -1661,7 +1663,7 @@ export function registerUpgradeCommand(program: Command): void {// - dev symlink present -> leave it (the dev rebuilds their own repo)// - absent (OSS users) -> do nothing, print nothing; Pro stays invisibleif (!opts.check) {- const proDir = join(IX_HOME, "node_modules", "@ix", "pro");+ const proDir = join(ixHome(), "node_modules", "@ix", "pro");let proPresent = false;let proIsLink = false;try {@@ -1671,7 +1673,7 @@ export function registerUpgradeCommand(program: Command): void {if (proPresent && !proIsLink) {try {console.log("Refreshing @ix/pro...");- execFileSync("npm", ["update", "--prefix", IX_HOME, "@ix/pro"], {+ execFileSync("npm", ["update", "--prefix", ixHome(), "@ix/pro"], {stdio: "ignore",timeout: 120000,});@@ -1684,8 +1686,8 @@ export function registerUpgradeCommand(program: Command): void {}// ── Backend (memory-layer) upgrade ───────────────────────────────- const backendCurrent = getTrackedVersion(BACKEND_VERSION_FILE);- const backendComposeFile = join(IX_HOME, "backend", "docker-compose.yml");+ const backendCurrent = getTrackedVersion(backendVersionFile());+ const backendComposeFile = join(ixHome(), "backend", "docker-compose.yml");let backendImageChanged = false;const backendUpgradeNeeded = !!backendLatest && backendUpdateAvailable(backendLatest, backendCurrent);const backendUpgradeSkipped = !opts.check && !backendComposeAllowsUpgrade(backendComposeFile);@@ -1728,7 +1730,7 @@ export function registerUpgradeCommand(program: Command): void {// the real cause.backendImageChanged = true;console.log(`[ok] Backend image updated to ${backendLatest}`);- if (!writeVersionStamp(BACKEND_VERSION_FILE, backendLatest)) {+ if (!writeVersionStamp(backendVersionFile(), backendLatest)) {console.error(chalk.yellow(stampFailureMessage()));}} catch {@@ -1826,14 +1828,14 @@ export function registerUpgradeCommand(program: Command): void {// 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.)+ // that branch; compassDir()'s parent is the same directory.)//// 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 = prepareDownloadDir(- IX_HOME,- dirname(COMPASS_DIR),+ ixHome(),+ dirname(compassDir()),".compass-download-",);const compassTar = join(compassTmp, `compass-${compassLatest}.tar.gz`);@@ -1844,8 +1846,8 @@ export function registerUpgradeCommand(program: Command): void {// 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}`);+ const compassStaging = join(ixHome(), `.compass-staging-${process.pid}`);+ const compassBackup = join(ixHome(), `.compass-backup-${process.pid}`);let stage = "download";try {try {@@ -1855,7 +1857,7 @@ export function registerUpgradeCommand(program: Command): void {throw err;}stage = "extract";- installCompassBundle(compassTar, COMPASS_DIR, compassStaging, compassBackup);+ installCompassBundle(compassTar, compassDir(), 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.@@ -1865,7 +1867,7 @@ export function registerUpgradeCommand(program: Command): void {// here, and this number really is in the ix-compass-dist series —// which is the series the next run will compare it against// (parseCompassStamp, #376).- writeFileSync(COMPASS_VERSION_FILE, `${compassLatest}\n`);+ writeFileSync(compassVersionFile(), `${compassLatest}\n`);console.log(`[ok] Compass upgraded to ${compassLatest}`);} catch (err) {failures.push(`compass ${stage}`);@@ -1874,19 +1876,19 @@ export function registerUpgradeCommand(program: Command): void {// 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"))) {+ if (existsSync(join(compassDir(), "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.`);+ console.error(` Rename that directory to ${compassDir()} 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);+ cleanupCompassSwap(compassDir(), compassStaging, compassBackup);// 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"diff --git a/ix-cli/src/cli/commands/view.ts b/ix-cli/src/cli/commands/view.tsindex 4d06fcbb..ca794257 100644--- a/ix-cli/src/cli/commands/view.ts+++ b/ix-cli/src/cli/commands/view.ts@@ -10,22 +10,25 @@ import {mkdirSync,} from "fs";import { join, dirname } from "path";-import { homedir, platform } from "os";+import { platform } from "os";import { fileURLToPath } from "url";import { createConnection } from "net";import { resolveWorkspaceId } from "../bootstrap.js";import { findWorkspaceForCwd, getDefaultWorkspace, getLocalToken, loadWorkspaces } from "../config.js";import { detectSystem } from "../system.js";import { createClient } from "../../client/factory.js";+import { ixHome } from "../ix-home.js";import { ensureFreshMap } from "../map-freshness.js";-const IX_HOME = process.env.IX_HOME || join(homedir(), ".ix");-const PID_FILE = join(IX_HOME, "compass.pid");+// The paths below are functions, not consts, so they follow IX_HOME as it is+// when a command runs rather than when this module was imported -- see+// `ixHome()`.+const pidFile = (): string => join(ixHome(), "compass.pid");// Records the workspace scope (id, or "*all*") of the running visualizer, so a second// `ix view` launched from a different workspace can warn instead of silently showing the// already-running (differently-scoped) instance.-const SCOPE_FILE = join(IX_HOME, "compass.scope");-const PORT_FILE = join(IX_HOME, "compass.port");+const scopeFile = (): string => join(ixHome(), "compass.scope");+const portFile = (): string => join(ixHome(), "compass.port");/*** `.cjs`, not `.js`.*@@ -37,13 +40,13 @@ const PORT_FILE = join(IX_HOME, "compass.port");* neither the cause nor the fix. `.cjs` is CommonJS whatever any ancestor* says. (`$HOME/package.json` is rare but real — this box has one.)*/-const SERVER_SCRIPT_FILE = join(IX_HOME, "tmp", "compass-server.cjs");+const serverScriptFile = (): string => join(ixHome(), "tmp", "compass-server.cjs");const BACKEND_URL = "http://localhost:8090";/** Resolve the compass dist directory — installed path first, then dev fallback. */function findCompassDist(): string | null {// Installed: $IX_HOME/cli/compass/- const installed = join(IX_HOME, "cli", "compass");+ const installed = join(ixHome(), "cli", "compass");if (existsSync(join(installed, "index.html"))) return installed;// Dev / repo: relative to this file → ../../compass/dist/@@ -55,7 +58,7 @@ function findCompassDist(): string | null {}function removeCompassState(): void {- for (const path of [PID_FILE, SCOPE_FILE, PORT_FILE]) {+ for (const path of [pidFile(), scopeFile(), portFile()]) {try { unlinkSync(path); } catch { /* ignore */ }}}@@ -98,7 +101,7 @@ function readTextIfPresent(path: string): string | null {*/function readRunningPort(): number | null {try {- const raw = readTextIfPresent(PORT_FILE);+ const raw = readTextIfPresent(portFile());const port = raw === null ? null : parsePort(raw);if (port !== null) return port;} catch {@@ -106,11 +109,11 @@ function readRunningPort(): number | null {}try {- const match = readTextIfPresent(SERVER_SCRIPT_FILE)?.match(/^const PORT = (\d+);$/m);+ const match = readTextIfPresent(serverScriptFile())?.match(/^const PORT = (\d+);$/m);const port = match?.[1] ? parsePort(match[1]) : null;if (port !== null) {// Best-effort migration for a visualizer started before compass.port existed.- try { writeFileSync(PORT_FILE, String(port)); } catch { /* ignore */ }+ try { writeFileSync(portFile(), String(port)); } catch { /* ignore */ }}return port;} catch {@@ -166,7 +169,7 @@ export function runningInstanceLines(* read would delete a live server's only record, or orphan a fresh one.*/function readAlivePid(): number | null {- const raw = readTextIfPresent(PID_FILE);+ const raw = readTextIfPresent(pidFile());if (raw === null) {removeCompassState();return null;@@ -765,7 +768,7 @@ export function registerViewCommand(program: Command): void {// below and quietly hand back another workspace's graph, which is the// exact confusion the scope file exists to prevent. Empty counts as// unknown too, not as a scope literally named "".- const runningKey = readTextIfPresent(SCOPE_FILE)?.trim() || null;+ const runningKey = readTextIfPresent(scopeFile())?.trim() || null;if (runningKey !== null && runningKey !== scopeKey) {const runningLabel = runningKey === "*all*"? "all workspaces"@@ -801,16 +804,16 @@ export function registerViewCommand(program: Command): void {}// Write server script to temp location- const scriptDir = dirname(SERVER_SCRIPT_FILE);+ const scriptDir = dirname(serverScriptFile());mkdirSync(scriptDir, { recursive: true });// The file is deliberately invariant: systemId can be returned by the// backend and must never flow into JavaScript that is written and then// executed. Runtime values travel as argv instead.- writeFileSync(SERVER_SCRIPT_FILE, serverScript());+ writeFileSync(serverScriptFile(), serverScript());// Spawn detached processconst child = spawn(process.execPath, [- SERVER_SCRIPT_FILE,+ serverScriptFile(),...serverRuntimeArgs(distDir, port, workspaceId, systemId, mapRoot),], {detached: true,@@ -828,10 +831,10 @@ export function registerViewCommand(program: Command): void {const ready = await waitForServer(port);// Save PID, scope, and port for subsequent start/status/stop commands.- mkdirSync(dirname(PID_FILE), { recursive: true });- writeFileSync(PID_FILE, String(child.pid));- writeFileSync(SCOPE_FILE, scopeKey);- writeFileSync(PORT_FILE, String(port));+ mkdirSync(dirname(pidFile()), { recursive: true });+ writeFileSync(pidFile(), String(child.pid));+ writeFileSync(scopeFile(), scopeKey);+ writeFileSync(portFile(), String(port));// One URL, printed and opened. They used to differ: only the opened// one carried the cache bust, so --no-open, a copied URL, a bookmarkdiff --git a/ix-cli/src/cli/ix-home.ts b/ix-cli/src/cli/ix-home.tsindex 6dffbbde..4c1219e2 100644--- a/ix-cli/src/cli/ix-home.ts+++ b/ix-cli/src/cli/ix-home.ts@@ -22,10 +22,11 @@ import { join } from "node:path";* makes isolation a module-registry problem rather than an environment one:* a test that sets IX_HOME in `beforeEach` is isolated when its file runs* alone and not when another file imported the module first. That is exactly- * how #498 wrote a bogus `99.0.0` upgrade notice into a real `~/.ix`. Five- * modules still bind it that way (`backend-status`, `backend-version`,- * `docker`, `upgrade`, `view`); each derives further path constants from it,- * so converting them is a wider change than this one and is left as follow-up.+ * how #498 wrote a bogus `99.0.0` upgrade notice into a real `~/.ix`. The last+ * five modules that bound it that way (`backend-status`, `backend-version`,+ * `docker`, `upgrade`, `view`) now derive their paths from this on each call;+ * `__tests__/backend-version-home.test.ts` pins that. Do not reintroduce a+ * module-level path built from it.*/export function ixHome(): string {return process.env.IX_HOME || join(homedir(), ".ix");diff --git a/ix-cli/vitest.config.ts b/ix-cli/vitest.config.tsindex 7ced0f94..0ab030c1 100644--- a/ix-cli/vitest.config.ts+++ b/ix-cli/vitest.config.ts@@ -4,8 +4,10 @@ import { configDefaults, defineConfig } from "vitest/config";export default defineConfig({test: {- // Strips an ambient IX_HOME before each file; see the comment in the file.+ // Gives each file a temp HOME (and so a temp ~/.ix); see the comment in the file.setupFiles: ["./vitest.setup.ts"],+ // Fails the run if the developer's real ~/.ix (or $IX_HOME) changed anyway.+ globalSetup: ["./vitest.home-guard.ts"],// vitest 4 dropped `dist/` from its built-in exclude list. Without this the// compiled `dist/**/*.test.js` copies emitted by `npm run build` get// collected and fail (they read sibling `.ts` sources that only exist underdiff --git a/ix-cli/vitest.home-guard.ts b/ix-cli/vitest.home-guard.tsnew file mode 100644index 00000000..8416b3f5--- /dev/null+++ b/ix-cli/vitest.home-guard.ts@@ -0,0 +1,119 @@+// Copyright 2026 Ix Infrastructure Inc.++import { lstatSync, readdirSync, realpathSync } from "node:fs";+import { homedir } from "node:os";+import { join, relative, resolve } from "node:path";++// A tripwire for the developer's real Ix state (vitest `globalSetup`).+//+// `vitest.setup.ts` gives every test file a throwaway home, and the CLI+// resolves its state directory on every call, so no test should be able to+// touch the real `~/.ix`. This proves it rather than trusting it: before the+// run it records the real `~/.ix` -- and an exported `$IX_HOME`, if the+// developer has one -- and after the run it fails if anything under either was+// created, changed or removed.+//+// globalSetup runs once in vitest's main process, which `vitest.setup.ts`+// never touches, so `os.homedir()` and `process.env.IX_HOME` here are still the+// developer's own. The guard only reads metadata (lstat, readdir): it never+// writes there, never follows a symlink out of it, and never reads a file's+// contents -- config.yaml holds a credential. A directory that does not exist+// is recorded as absent, so creating it is caught too.+//+// What it cannot tell apart: a real `ix` the developer (or an editor hook)+// ran against the same home while the suite was running changes it just the+// same. If the listed paths are yours, re-run; `IX_TEST_HOME_GUARD=off` skips+// the check for a run where that cannot be avoided.++/** Per-path signature; any write, create, delete, rename or chmod changes it. */+type Snapshot = Map<string, string>;++function signature(path: string): string | null {+ try {+ const st = lstatSync(path);+ const kind = st.isDirectory() ? "d" : st.isSymbolicLink() ? "l" : st.isFile() ? "f" : "o";+ return `${kind} ${st.size} ${st.mtimeMs} ${st.ctimeMs} ${st.mode} ${st.ino}`;+ } catch (err) {+ return (err as NodeJS.ErrnoException).code === "ENOENT" ? null : "unreadable";+ }+}++function snapshot(root: string): Snapshot {+ const snap: Snapshot = new Map();+ // `~/.ix` may itself be a symlink to where the state really lives; record+ // the link, then walk what it points at. Nothing below it is followed.+ let base = root;+ try { base = realpathSync(root); } catch { /* absent: recorded as such below */ }+ if (base !== root) {+ const link = signature(root);+ if (link !== null) snap.set("->", link);+ }+ const walk = (dir: string): void => {+ const sig = signature(dir);+ if (sig === null) return;+ snap.set(relative(base, dir) || ".", sig);+ if (!sig.startsWith("d ")) return;+ let names: string[];+ try { names = readdirSync(dir); } catch { return; }+ for (const name of names) {+ const path = join(dir, name);+ const s = signature(path);+ if (s === null) continue; // removed between readdir and lstat+ if (s.startsWith("d ")) walk(path);+ else snap.set(relative(base, path), s);+ }+ };+ walk(base);+ return snap;+}++function diff(before: Snapshot, after: Snapshot): string[] {+ const changes: string[] = [];+ for (const [path, sig] of after) {+ const was = before.get(path);+ if (was === undefined) changes.push(`created ${path}`);+ else if (was !== sig) changes.push(`modified ${path}`);+ }+ for (const path of before.keys()) {+ if (!after.has(path)) changes.push(`removed ${path}`);+ }+ return changes.sort();+}++/** The real state directories: `~/.ix`, and `$IX_HOME` when one is exported. */+export function realStateDirs(env: NodeJS.ProcessEnv = process.env, home: string = homedir()): string[] {+ const dirs = [resolve(home, ".ix")];+ if (env.IX_HOME) dirs.push(resolve(env.IX_HOME));+ return [...new Set(dirs)];+}++export default function setup(): (() => void) | void {+ if (process.env.IX_TEST_HOME_GUARD === "off") return;+ const roots = realStateDirs();+ const before = roots.map((root) => snapshot(root));++ return () => {+ const report: string[] = [];+ roots.forEach((root, i) => {+ const changes = diff(before[i]!, snapshot(root));+ if (changes.length === 0) return;+ report.push(` ${root}:`);+ for (const line of changes.slice(0, 20)) report.push(` ${line}`);+ if (changes.length > 20) report.push(` ... and ${changes.length - 20} more`);+ });+ if (report.length === 0) return;+ // Vitest runs globalSetup teardown after the results are reported and only+ // logs what it throws ("error during close"), leaving the exit status at 0.+ // Set it here, or the guard would be a message nobody's CI ever sees.+ process.exitCode = 1;+ throw new Error(+ [+ "The test run changed the developer's real Ix state directory:",+ ...report,+ "A test reached the real home instead of the temp one vitest.setup.ts gives it.",+ "If you ran `ix` yourself during the run, those changes are yours: re-run, or",+ "set IX_TEST_HOME_GUARD=off for that run.",+ ].join("\n"),+ );+ };+}diff --git a/ix-cli/vitest.setup.ts b/ix-cli/vitest.setup.tsindex 57c55265..ed546d4d 100644--- a/ix-cli/vitest.setup.ts+++ b/ix-cli/vitest.setup.ts@@ -1,20 +1,68 @@// Copyright 2026 Ix Infrastructure Inc.+import { mkdtempSync, realpathSync, rmSync } from "node:fs";+import { syncBuiltinESMExports } from "node:module";+import os from "node:os";+import { join } from "node:path";+import { afterAll } from "vitest";+// Runs before every test file (vitest `setupFiles`).//-// Strip an ambient IX_HOME. `config.ts` resolves the state directory through-// `ixHome()` -- `$IX_HOME`, else `~/.ix` -- so a developer, or a harness such-// as a benchmark, that has IX_HOME exported would otherwise have every test-// that isolates itself by overriding HOME write to THEIR real state directory-// instead of the temp home it set up: a HOME override relocates `~/.ix`, not-// `$IX_HOME`. Eight files isolate that way today.+// Give every file a throwaway home, so nothing a test does by default can+// reach the developer's real `~/.ix` -- or the IX_HOME they exported. The CLI+// finds its state through `ixHome()` (`$IX_HOME`, else `~/.ix`), and a test+// that forgot to isolate itself used to resolve that to the real one: it could+// overwrite `.backend-version`, register workspaces in the real config.yaml,+// or drop map baselines next to the developer's own. `vitest.home-guard.ts`+// fails the run if anything reaches it anyway.+//+// HOME and USERPROFILE (what `os.homedir()` reads on Windows) point at a fresh+// temp directory, which also covers what is not under IX_HOME: the host config+// files `ix mcp` writes, `~/.local/bin`, a child process's git config. An+// ambient IX_HOME is stripped, as it always was here: a developer, or a+// harness such as a benchmark, that has one exported would otherwise have every+// file that isolates itself by overriding HOME write to THEIR state directory+// instead of the temp home it set up -- a HOME override relocates `~/.ix`, not+// `$IX_HOME`. So by default the state directory is `<temp home>/.ix`.+//+// Under vitest's threads / vmThreads pools that is not enough on its own:+// `os.homedir()` answers from the environment libuv sees, which a worker+// thread's `process.env` write never reaches, so the HOME set here -- and every+// HOME override a test makes -- would be ignored and `~/.ix` would resolve to+// the real one. There, `os.homedir()` is made to read `process.env` the way+// libuv reads the real environment in a forked worker (USERPROFILE on Windows,+// HOME elsewhere, the original answer when unset), and the change is synced to+// every `import { homedir } from "node:os"`. A dozen files isolate by+// overriding HOME, some swapping it between two "machines" inside one test,+// so this keeps them isolated in every pool rather than only under forks+// (vmThreads, below, is the one exception).//-// Deleting the variable here restores the invariant those files were written-// against, and costs nothing for the files that set IX_HOME themselves: they-// do so in `beforeEach`, which runs after this. Per file, not once per worker-// -- vitest re-runs setupFiles for each file, and `process.env` is per worker-// under the default forks pool, so no file can leak an IX_HOME to the next.+// `realpathSync` because macOS hands out `/var/...` for a directory that is+// really `/private/var/...`, and some tests compare canonical paths.+//+// Tests that set their own HOME or IX_HOME still win: they do so in+// `beforeEach` or at module scope, both of which run after this. Per file, not+// once per worker -- vitest re-runs setupFiles for each file, so each file+// starts from an empty home and no file can leak state, or an environment+// override, to the next.+const home = realpathSync(mkdtempSync(join(os.tmpdir(), "ix-test-home-")));+process.env.HOME = home;+process.env.USERPROFILE = home;delete process.env.IX_HOME;+if (os.homedir() !== home) {+ const libuvHomedir = os.homedir;+ os.homedir = () =>+ (process.platform === "win32" ? process.env.USERPROFILE : process.env.HOME) || libuvHomedir();+ syncBuiltinESMExports();+}+// vmThreads links builtins into each file as a snapshot the patch does not+// reach. Where a fresh import still answers the real home, pin IX_HOME: a HOME+// override then no longer moves a file's state, but nothing reaches `~/.ix`.+if ((await import("node:os")).homedir() !== home) process.env.IX_HOME = join(home, ".ix");++afterAll(() => {+ try { rmSync(home, { recursive: true, force: true }); } catch { /* best effort */ }+});// No test may start a real background map refresh (a detached `ix// __map-refresh` process that outlives the test). Region views start onediff --git a/ix-cli/vitest.slow.config.ts b/ix-cli/vitest.slow.config.tsindex 8ee65820..2715b3d9 100644--- a/ix-cli/vitest.slow.config.ts+++ b/ix-cli/vitest.slow.config.ts@@ -10,6 +10,7 @@ import { defineConfig } from "vitest/config";export default defineConfig({test: {setupFiles: ["./vitest.setup.ts"],+ globalSetup: ["./vitest.home-guard.ts"],include: ["src/**/*.slow.test.ts"],fileParallelism: false,sequence: { concurrent: false },