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
perf(cli): load less, and compile less, before every command
KageBinary1fb01f928472
diff --git a/ix-cli/src/cli/__tests__/startup-imports.test.ts b/ix-cli/src/cli/__tests__/startup-imports.test.tsnew file mode 100644index 00000000..000df9c4--- /dev/null+++ b/ix-cli/src/cli/__tests__/startup-imports.test.ts@@ -0,0 +1,73 @@+// Copyright 2026 Ix Infrastructure Inc.++import { spawnSync } from "node:child_process";+import { existsSync, readFileSync } from "node:fs";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { describe, expect, it } from "vitest";++const SRC = resolve(dirname(fileURLToPath(import.meta.url)), "../..");++/**+ * Every package the CLI loads before any command runs, following the static+ * `import`/`export ... from` edges from the entry point. Type-only imports+ * are erased by tsc and dynamic `import()` is deferred, so neither counts.+ */+function startupPackages(entries: string[]): { packages: Set<string>; modules: number } {+ const packages = new Set<string>();+ const seen = new Set<string>();+ const queue = [...entries];+ const edge = /^\s*(?:import|export)\s+(?!type\b)(?:[^'"]*?\s+from\s+)?["']([^"']+)["']/gm;+ while (queue.length > 0) {+ const file = queue.pop()!;+ if (seen.has(file)) continue;+ seen.add(file);+ const text = readFileSync(file, "utf-8");+ for (const match of text.matchAll(edge)) {+ const spec = match[1];+ if (spec.startsWith(".")) {+ const target = resolve(dirname(file), spec.replace(/\.js$/, ".ts"));+ if (existsSync(target)) queue.push(target);+ else packages.add(spec); // e.g. a relative path out to core-ingestion's dist+ } else if (!spec.startsWith("node:")) {+ packages.add(spec.startsWith("@") ? spec.split("/").slice(0, 2).join("/") : spec.split("/")[0]);+ }+ }+ }+ return { packages, modules: seen.size };+}++describe("CLI start-up module graph", () => {+ it("does not load zod, the MCP SDK or the parser for every command", () => {+ // `main.ts` imports `run-cli.ts` unconditionally, after enabling the+ // compile cache, so both are the start-up graph.+ const { packages, modules } = startupPackages([join(SRC, "cli/main.ts"), join(SRC, "cli/run-cli.ts")]);++ // The walk really reached the command registry.+ expect(modules).toBeGreaterThan(50);+ expect(packages.has("commander")).toBe(true);+ // zod is ~40 ms and ~95 modules; only `ix context --out/--save/--resume`+ // and the MCP server need it, and they load it themselves.+ expect(packages.has("zod")).toBe(false);+ expect(packages.has("@modelcontextprotocol/sdk")).toBe(false);+ expect([...packages].filter((p) => /core-ingestion|tree-sitter/.test(p))).toEqual([]);+ });++ it("loads zod on the first bundle validation, not on import", () => {+ const schema = join(SRC, "cli/context-bundle-schema.ts");+ const script = `+ const { createRequire } = await import("node:module");+ const req = createRequire(${JSON.stringify(schema)});+ const loaded = () => Object.keys(req.cache).some((k) => /[\\\\/]node_modules[\\\\/]zod[\\\\/]/.test(k));+ const m = await import(${JSON.stringify("file://" + schema)});+ const before = loaded();+ const bad = m.contextBundleSchema.safeParse({}).success;+ console.log(JSON.stringify({ before, after: loaded(), bad }));+ `;+ const child = spawnSync(process.execPath, ["--import", "tsx", "--input-type=module", "-e", script], {+ cwd: SRC, encoding: "utf-8",+ });+ expect(child.status, child.stderr).toBe(0);+ expect(JSON.parse(child.stdout.trim())).toEqual({ before: false, after: true, bad: false });+ }, 30_000);+});diff --git a/ix-cli/src/cli/context-bundle-schema.ts b/ix-cli/src/cli/context-bundle-schema.tsindex f20a66a2..85e74e29 100644--- a/ix-cli/src/cli/context-bundle-schema.ts+++ b/ix-cli/src/cli/context-bundle-schema.ts@@ -1,6 +1,7 @@// Copyright 2026 Ix Infrastructure Inc.-import { z } from "zod";+import { createRequire } from "node:module";+import type * as Zod from "zod";/*** Versioned id of the context bundle contract. Bump only on a breaking shape@@ -12,175 +13,208 @@ export const BUNDLE_SCHEMA = "ix-context-bundle/1";export const INVESTIGATION_SCHEMA = "ix-investigation/1";/**- * Versioned contract for the deterministic context bundle produced by- * `ix context` (schema `ix-context-bundle/1`).- *- * This is the single source of truth for the bundle's shape. The MCP server- * uses it as the `ix_context` output schema so agents get a structured- * contract, and the CLI validates every bundle with it on the way to disk- * (investigation save and `--out`) and on the way back off it- * (`loadInvestigation`), so a malformed or unexpected payload can never be- * written as if it were a valid bundle, nor honoured when read back.- *- * The shapes below mirror the `ContextBundle` and `EvidenceItem` interfaces in- * `commands/context.ts`. Fields the renderers and `--diff` dereference by name- * — `evidence[].title`, the `budgets`, the four `truncation` counters and- * the `metadata` values `--diff` re-sends to the backend — are pinned to their- * real types rather than left as open records: validation that accepts `{}`- * where the code goes on to read `.title` or `.maxEntities` only moves the- * failure downstream, from a named refusal to a TypeError or a NaN.- *- * The three backend report arrays (decisions/conflicts/intents) keep their own- * internal shapes and stay deliberately loose here; the bundle's versioned- * `schema` field remains the authoritative marker.+ * zod costs ~40 ms of module loading, on every command, and only four paths+ * of `ix context` ever validate (`--out`, `--save`, `--resume`/`--diff`,+ * `--list`). So the schemas are built on first use, from a synchronous require+ * (zod ships CommonJS too) because two of those paths are synchronous.*/-export const contextBundleSchema = z.object({- schema: z.literal(BUNDLE_SCHEMA),- generatedAt: z.string(),- target: z.object({- id: z.string(),- name: z.string(),- kind: z.string(),- resolutionMode: z.string(),- path: z.string().optional(),- }),- // Both optional, and only on a bundle built with `--from-issue`: every- // bundle saved before them, and every bundle built from a named target,- // still validates. Declared rather than left out, because zod strips an- // undeclared key on the way to disk and on the way back.- issue: z- .object({- startingPoints: z.array(- z.object({- token: z.string(),- id: z.string().optional(),- name: z.string(),- kind: z.string(),- path: z.string(),- lineStart: z.number().int().positive().optional(),- lineEnd: z.number().int().positive().optional(),- via: z.enum(["path in issue", "identifier in issue", "bm25 fallback"]),- }),- ),- unresolved: z.array(z.string()),- fallback: z.boolean(),- })- .optional(),- rankedFiles: z- .array(z.object({ path: z.string(), score: z.number(), reason: z.string() }))- .optional(),- entities: z.array(- z.object({+const requireZod = createRequire(import.meta.url);++function buildSchemas(z: typeof Zod.z) {+ /**+ * Versioned contract for the deterministic context bundle produced by+ * `ix context` (schema `ix-context-bundle/1`).+ *+ * This is the single source of truth for the bundle's shape. The MCP server+ * uses it as the `ix_context` output schema so agents get a structured+ * contract, and the CLI validates every bundle with it on the way to disk+ * (investigation save and `--out`) and on the way back off it+ * (`loadInvestigation`), so a malformed or unexpected payload can never be+ * written as if it were a valid bundle, nor honoured when read back.+ *+ * The shapes below mirror the `ContextBundle` and `EvidenceItem` interfaces in+ * `commands/context.ts`. Fields the renderers and `--diff` dereference by name+ * — `evidence[].title`, the `budgets`, the four `truncation` counters and+ * the `metadata` values `--diff` re-sends to the backend — are pinned to their+ * real types rather than left as open records: validation that accepts `{}`+ * where the code goes on to read `.title` or `.maxEntities` only moves the+ * failure downstream, from a named refusal to a TypeError or a NaN.+ *+ * The three backend report arrays (decisions/conflicts/intents) keep their own+ * internal shapes and stay deliberately loose here; the bundle's versioned+ * `schema` field remains the authoritative marker.+ */+ const contextBundleSchema = z.object({+ schema: z.literal(BUNDLE_SCHEMA),+ generatedAt: z.string(),+ target: z.object({id: z.string(),name: z.string(),kind: z.string(),+ resolutionMode: z.string(),path: z.string().optional(),- lineStart: z.number().int().positive().optional(),- lineEnd: z.number().int().positive().optional(),- stale: z.boolean(),}),- ),- relationships: z.array(z.object({ src: z.string(), dst: z.string(), predicate: z.string() })),- claims: z.array(- z- .object({ id: z.string(), entityId: z.string(), statement: z.string(), status: z.string() })+ // Both optional, and only on a bundle built with `--from-issue`: every+ // bundle saved before them, and every bundle built from a named target,+ // still validates. Declared rather than left out, because zod strips an+ // undeclared key on the way to disk and on the way back.+ issue: z+ .object({+ startingPoints: z.array(+ z.object({+ token: z.string(),+ id: z.string().optional(),+ name: z.string(),+ kind: z.string(),+ path: z.string(),+ lineStart: z.number().int().positive().optional(),+ lineEnd: z.number().int().positive().optional(),+ via: z.enum(["path in issue", "identifier in issue", "bm25 fallback"]),+ }),+ ),+ unresolved: z.array(z.string()),+ fallback: z.boolean(),+ })+ .optional(),+ rankedFiles: z+ .array(z.object({ path: z.string(), score: z.number(), reason: z.string() }))+ .optional(),+ entities: z.array(+ z.object({+ id: z.string(),+ name: z.string(),+ kind: z.string(),+ path: z.string().optional(),+ lineStart: z.number().int().positive().optional(),+ lineEnd: z.number().int().positive().optional(),+ stale: z.boolean(),+ }),+ ),+ relationships: z.array(z.object({ src: z.string(), dst: z.string(), predicate: z.string() })),+ claims: z.array(+ z+ .object({ id: z.string(), entityId: z.string(), statement: z.string(), status: z.string() })+ .catchall(z.unknown()),+ ),+ // DecisionReport/ConflictReport/IntentReport are the backend's own contracts+ // with their own shapes; they are forwarded, never dereferenced field-by-field+ // here, so they stay loose rather than duplicating those types in a second+ // place that could drift from them.+ decisions: z.array(z.record(z.string(), z.unknown())),+ conflicts: z.array(z.record(z.string(), z.unknown())),+ intents: z.array(z.record(z.string(), z.unknown())),+ provenance: z+ .object({+ sourceUri: z.string().optional(),+ sourceHash: z.string().optional(),+ extractor: z.string().optional(),+ sourceType: z.string().optional(),+ observedAt: z.string().optional(),+ introducedRev: z.number().optional(),+ historyLength: z.number(),+ stale: z.boolean(),+ }).catchall(z.unknown()),- ),- // DecisionReport/ConflictReport/IntentReport are the backend's own contracts- // with their own shapes; they are forwarded, never dereferenced field-by-field- // here, so they stay loose rather than duplicating those types in a second- // place that could drift from them.- decisions: z.array(z.record(z.string(), z.unknown())),- conflicts: z.array(z.record(z.string(), z.unknown())),- intents: z.array(z.record(z.string(), z.unknown())),- provenance: z- .object({- sourceUri: z.string().optional(),- sourceHash: z.string().optional(),- extractor: z.string().optional(),- sourceType: z.string().optional(),- observedAt: z.string().optional(),- introducedRev: z.number().optional(),- historyLength: z.number(),- stale: z.boolean(),- })- .catchall(z.unknown()),- freshness: z.object({ stale: z.boolean(), classification: z.string() }),- evidence: z.array(- z.object({- id: z.string(),- kind: z.string(),- source: z.string(),- title: z.string(),- score: z.number(),- reason: z.string(),- refs: z.array(z.string()),- // Optional and additive: bundles saved before it existed still parse.- // Listed rather than left to `catchall`, because an unlisted key is- // stripped on the way to disk and on the way back.- location: z- .object({- path: z.string(),- lineStart: z.number().int().positive().optional(),- lineEnd: z.number().int().positive().optional(),- })- .optional(),+ freshness: z.object({ stale: z.boolean(), classification: z.string() }),+ evidence: z.array(+ z.object({+ id: z.string(),+ kind: z.string(),+ source: z.string(),+ title: z.string(),+ score: z.number(),+ reason: z.string(),+ refs: z.array(z.string()),+ // Optional and additive: bundles saved before it existed still parse.+ // Listed rather than left to `catchall`, because an unlisted key is+ // stripped on the way to disk and on the way back.+ location: z+ .object({+ path: z.string(),+ lineStart: z.number().int().positive().optional(),+ lineEnd: z.number().int().positive().optional(),+ })+ .optional(),+ }),+ ),+ budgets: z.object({+ maxEntities: z.number().int().positive(),+ maxRelationships: z.number().int().positive(),+ maxEvidence: z.number().int().positive(),+ // Optional, and only this one. A bundle built before `--max-tokens`+ // existed carries the other four and nothing else, and zod strips keys it+ // does not declare — so leaving it out here would not have been "tolerant+ // of old files", it would have silently dropped the field from every new+ // one on its way to disk. Required would refuse to load those old files+ // instead, which is a worse answer than reporting `tokens=not-given`.+ maxTokens: z.number().int().positive().optional(),+ maxChars: z.number().int().positive(),}),- ),- budgets: z.object({- maxEntities: z.number().int().positive(),- maxRelationships: z.number().int().positive(),- maxEvidence: z.number().int().positive(),- // Optional, and only this one. A bundle built before `--max-tokens`- // existed carries the other four and nothing else, and zod strips keys it- // does not declare — so leaving it out here would not have been "tolerant- // of old files", it would have silently dropped the field from every new- // one on its way to disk. Required would refuse to load those old files- // instead, which is a worse answer than reporting `tokens=not-given`.- maxTokens: z.number().int().positive().optional(),- maxChars: z.number().int().positive(),- }),- truncation: z.object({- // Optional for the same reason `budgets.maxTokens` is: a bundle saved- // before this field existed carries the counters and nothing else, and an- // undeclared key would be stripped from every new one on its way to disk.- cut: z.array(z.object({ what: z.string(), count: z.number().int().positive() })).optional(),- entitiesTruncated: z.number().int().nonnegative(),- relationshipsTruncated: z.number().int().nonnegative(),- evidenceTruncated: z.number().int().nonnegative(),- charactersTruncated: z.number().int().nonnegative(),- // Optional on the way in, always written on the way out: a bundle saved- // before the conflict cap existed has no such counter, and refusing to- // read it back would break `--diff` against every investigation on disk.- conflictsTruncated: z.number().int().nonnegative().optional(),- }),- // `asOfRev` and `depth` are the two saved values `ix context --diff` re-sends- // to the backend, so they are typed rather than accepted as anything.- // Unknown keys pass through: metadata is the bundle's extension point, and- // stripping them would silently drop data on the read-back path.- metadata: z- .object({- asOfRev: z.number().optional(),- depth: z.string().optional(),- rankingRule: z.string(),- })- .catchall(z.unknown()),-});+ truncation: z.object({+ // Optional for the same reason `budgets.maxTokens` is: a bundle saved+ // before this field existed carries the counters and nothing else, and an+ // undeclared key would be stripped from every new one on its way to disk.+ cut: z.array(z.object({ what: z.string(), count: z.number().int().positive() })).optional(),+ entitiesTruncated: z.number().int().nonnegative(),+ relationshipsTruncated: z.number().int().nonnegative(),+ evidenceTruncated: z.number().int().nonnegative(),+ charactersTruncated: z.number().int().nonnegative(),+ // Optional on the way in, always written on the way out: a bundle saved+ // before the conflict cap existed has no such counter, and refusing to+ // read it back would break `--diff` against every investigation on disk.+ conflictsTruncated: z.number().int().nonnegative().optional(),+ }),+ // `asOfRev` and `depth` are the two saved values `ix context --diff` re-sends+ // to the backend, so they are typed rather than accepted as anything.+ // Unknown keys pass through: metadata is the bundle's extension point, and+ // stripping them would silently drop data on the read-back path.+ metadata: z+ .object({+ asOfRev: z.number().optional(),+ depth: z.string().optional(),+ rankingRule: z.string(),+ })+ .catchall(z.unknown()),+ });-/**- * Contract for the on-disk saved-investigation envelope (`~/.ix/investigations`).- *- * `id` and `savedAt` are rendered to the terminal and copied into the emitted- * `ix-investigation-diff/1` JSON, so they are validated here alongside the- * bundle rather than trusted from a bare cast.- */-export const savedInvestigationSchema = z.object({- schema: z.literal(INVESTIGATION_SCHEMA),- // `sanitizeId` percent-escapes anything outside this set on the way in, so a- // stored id can only contain these characters. Pinning the same set on the- // way out keeps control characters and ANSI escapes out of an id that- // `renderNote`/`renderSection` write straight to the terminal.- id: z.string().regex(/^[A-Za-z0-9._~-]+$/),- savedAt: z.string(),- bundle: contextBundleSchema,-});+ /**+ * Contract for the on-disk saved-investigation envelope (`~/.ix/investigations`).+ *+ * `id` and `savedAt` are rendered to the terminal and copied into the emitted+ * `ix-investigation-diff/1` JSON, so they are validated here alongside the+ * bundle rather than trusted from a bare cast.+ */+ const savedInvestigationSchema = z.object({+ schema: z.literal(INVESTIGATION_SCHEMA),+ // `sanitizeId` percent-escapes anything outside this set on the way in, so a+ // stored id can only contain these characters. Pinning the same set on the+ // way out keeps control characters and ANSI escapes out of an id that+ // `renderNote`/`renderSection` write straight to the terminal.+ id: z.string().regex(/^[A-Za-z0-9._~-]+$/),+ savedAt: z.string(),+ bundle: contextBundleSchema,+ });++ return { contextBundleSchema, savedInvestigationSchema };+}++let built: ReturnType<typeof buildSchemas> | undefined;+function schemas(): ReturnType<typeof buildSchemas> {+ return (built ??= buildSchemas((requireZod("zod") as typeof Zod).z));+}++type BundleSchema = ReturnType<typeof buildSchemas>["contextBundleSchema"];+type InvestigationSchema = ReturnType<typeof buildSchemas>["savedInvestigationSchema"];++/** The bundle contract (see `buildSchemas`); zod is loaded on the first parse. */+export const contextBundleSchema = {+ parse: (value: unknown): Zod.infer<BundleSchema> => schemas().contextBundleSchema.parse(value),+ safeParse: (value: unknown): ReturnType<BundleSchema["safeParse"]> => schemas().contextBundleSchema.safeParse(value),+};++/** The saved-investigation contract (see `buildSchemas`); zod is loaded on the first parse. */+export const savedInvestigationSchema = {+ parse: (value: unknown): Zod.infer<InvestigationSchema> => schemas().savedInvestigationSchema.parse(value),+ safeParse: (value: unknown): ReturnType<InvestigationSchema["safeParse"]> =>+ schemas().savedInvestigationSchema.safeParse(value),+};diff --git a/ix-cli/src/cli/main.ts b/ix-cli/src/cli/main.tsindex b66bc323..67d2820a 100644--- a/ix-cli/src/cli/main.ts+++ b/ix-cli/src/cli/main.ts@@ -1,19 +1,12 @@#!/usr/bin/env node// Copyright 2026 Ix Infrastructure Inc.-import { Command } from "commander";-import { registerOssCommands, registerProStubs } from "./register/oss.js";-import { tryLoadProCommands } from "./register/pro-loader.js";-import { isRepairInvocation } from "./register/pro-failure.js";-import { buildHelpText } from "./help-text.js";-import { checkForUpdate, updateCheckEnabled } from "./commands/upgrade.js";-import { stderrIsTerminal } from "./stderr.js";-import { detectRequestedFormat, renderCliError, setErrorFormat } from "./errors.js";-import { getEndpoint } from "./config.js";+// The entry point, kept to what must happen before the CLI's own modules load.+// Static imports are evaluated before a module's body runs, so the two steps+// below could not live in `run-cli.ts`: by the time its first line ran, the+// ~200 modules behind the command registry would already be loaded.-import { readFileSync } from "fs";-import { join, dirname } from "path";-import { fileURLToPath } from "url";+import * as nodeModule from "node:module";// Runtime Node version guard. Runs before any command work so users on an// unsupported Node get an actionable message instead of a cryptic "fetch@@ -31,105 +24,16 @@ const MIN_NODE_MAJOR = 22;}}-let cliVersion = "0.0.0";+// V8's code cache for every module loaded from here on. Compiling the CLI's+// modules is most of its start-up: measured at ~40 ms of ~180 ms before the+// first request on a warm machine. Node >= 22.1 keeps the cache under the OS+// temp directory, keyed by file content and Node version, so an upgrade can+// never run stale code; NODE_COMPILE_CACHE moves it and+// NODE_DISABLE_COMPILE_CACHE=1 turns it off. Absent on 22.0: then a no-op.try {- const __dirname = dirname(fileURLToPath(import.meta.url));- const pkg = JSON.parse(readFileSync(join(__dirname, "../../package.json"), "utf-8"));- cliVersion = pkg.version || "0.0.0";-} catch {}--// Set IX_DEBUG=1 to append stack traces to any rendered error.-const debug = process.env.IX_DEBUG === "1";--// Before anything can throw. The handlers below are installed for-// `unhandledRejection` and `uncaughtException`, which can fire before-// commander has parsed a thing, so the error boundary gets the format from-// argv rather than from a parsed command.-setErrorFormat(detectRequestedFormat(process.argv.slice(2)));--// Resolving the endpoint reads config off disk, which can itself fail. An-// error renderer must never throw, so failure here just drops the endpoint-// from the message rather than replacing one crash with another.-function safeEndpoint(): string | undefined {- try {- return getEndpoint();- } catch {- return undefined;- }+ (nodeModule as { enableCompileCache?: () => unknown }).enableCompileCache?.();+} catch {+ // A cache that cannot be opened only costs speed.}-// Last line of defence. Without these, any rejection escaping a command — most-// commonly the backend not running — reaches Node's default handler and prints-// an undici stack trace that exposes internal paths and tells the user nothing.-process.on("unhandledRejection", (err: unknown) => {- renderCliError(err, debug, safeEndpoint());-});-process.on("uncaughtException", (err: unknown) => {- renderCliError(err, debug, safeEndpoint());-});--const program = new Command();-program- .name("ix")- .version(cliVersion);--// Start with OSS-only help; updated after Pro probe.-program.helpInformation = () => buildHelpText();--registerOssCommands(program);--(async () => {- const ossCmdNames = new Set(program.commands.map((c: Command) => c.name()));-- // An installed-but-broken Pro throws here rather than reporting absence, so- // commands never run without its credential guard. Note this call sits- // OUTSIDE the parseAsync try/catch below — render the failure here rather- // than letting it reach the unhandledRejection handler by accident.- let proLoaded = false;- try {- proLoaded = await tryLoadProCommands(program);- } catch (err) {- if (!isRepairInvocation(process.argv)) {- renderCliError(err, debug, safeEndpoint()); // exits 1- }- // Repair invocation: continue OSS-only. proLoaded stays false, so the Pro- // stubs register below and would misreport a broken Pro as absent — the- // warning here is what distinguishes the two, and no command in the set- // above reaches a stub.- console.error(- "[!!] Ix Pro is installed but failed to initialize; continuing with OSS " +- "commands only so this one can repair the install.",- );- }- if (proLoaded) {- // Collect commands that Pro added (weren't in OSS set)- const proCommands = program.commands- .filter((c: Command) => !ossCmdNames.has(c.name()))- .map((c: Command) => ({ name: c.name(), desc: c.description() }));-- program.helpInformation = () => buildHelpText(proCommands);- } else {- registerProStubs(program);- }-- // Check for updates (non-blocking, cached 1hr). Only when a person is- // watching stderr — see updateCheckEnabled for why, and for the- // IX_NO_UPDATE_CHECK opt-out.- const args = process.argv.slice(2);- if (updateCheckEnabled(args, process.env, stderrIsTerminal())) {- // Deliberately not awaited — but it must still be caught here. The catch- // inside checkForUpdate only guards its inner fetch chain; the function's- // own promise covers the synchronous cached-read path, and a corrupt- // ~/.ix/.version-check.json makes that throw. Uncaught, the new- // unhandledRejection handler then aborts a command that already succeeded.- checkForUpdate().catch(() => {});- }-- // parseAsync (not parse) so rejections from async action handlers surface- // here instead of floating off as unhandled rejections.- try {- await program.parseAsync();- } catch (err) {- renderCliError(err, debug, safeEndpoint());- }-})();+await import("./run-cli.js");diff --git a/ix-cli/src/cli/run-cli.ts b/ix-cli/src/cli/run-cli.tsnew file mode 100644index 00000000..c0512fd8--- /dev/null+++ b/ix-cli/src/cli/run-cli.ts@@ -0,0 +1,122 @@+// Copyright 2026 Ix Infrastructure Inc.++// The CLI proper. `main.ts` is the entry point: it checks the Node version and+// turns on the compile cache, then imports this module, so everything below+// -- every command module and its dependencies -- loads through the cache.++import { Command } from "commander";+import { registerOssCommands, registerProStubs } from "./register/oss.js";+import { tryLoadProCommands } from "./register/pro-loader.js";+import { isRepairInvocation } from "./register/pro-failure.js";+import { buildHelpText } from "./help-text.js";+import { checkForUpdate, updateCheckEnabled } from "./commands/upgrade.js";+import { stderrIsTerminal } from "./stderr.js";+import { detectRequestedFormat, renderCliError, setErrorFormat } from "./errors.js";+import { getEndpoint } from "./config.js";++import { readFileSync } from "fs";+import { join, dirname } from "path";+import { fileURLToPath } from "url";++let cliVersion = "0.0.0";+try {+ const __dirname = dirname(fileURLToPath(import.meta.url));+ const pkg = JSON.parse(readFileSync(join(__dirname, "../../package.json"), "utf-8"));+ cliVersion = pkg.version || "0.0.0";+} catch {}++// Set IX_DEBUG=1 to append stack traces to any rendered error.+const debug = process.env.IX_DEBUG === "1";++// Before anything can throw. The handlers below are installed for+// `unhandledRejection` and `uncaughtException`, which can fire before+// commander has parsed a thing, so the error boundary gets the format from+// argv rather than from a parsed command.+setErrorFormat(detectRequestedFormat(process.argv.slice(2)));++// Resolving the endpoint reads config off disk, which can itself fail. An+// error renderer must never throw, so failure here just drops the endpoint+// from the message rather than replacing one crash with another.+function safeEndpoint(): string | undefined {+ try {+ return getEndpoint();+ } catch {+ return undefined;+ }+}++// Last line of defence. Without these, any rejection escaping a command — most+// commonly the backend not running — reaches Node's default handler and prints+// an undici stack trace that exposes internal paths and tells the user nothing.+process.on("unhandledRejection", (err: unknown) => {+ renderCliError(err, debug, safeEndpoint());+});+process.on("uncaughtException", (err: unknown) => {+ renderCliError(err, debug, safeEndpoint());+});++const program = new Command();+program+ .name("ix")+ .version(cliVersion);++// Start with OSS-only help; updated after Pro probe.+program.helpInformation = () => buildHelpText();++registerOssCommands(program);++(async () => {+ const ossCmdNames = new Set(program.commands.map((c: Command) => c.name()));++ // An installed-but-broken Pro throws here rather than reporting absence, so+ // commands never run without its credential guard. Note this call sits+ // OUTSIDE the parseAsync try/catch below — render the failure here rather+ // than letting it reach the unhandledRejection handler by accident.+ let proLoaded = false;+ try {+ proLoaded = await tryLoadProCommands(program);+ } catch (err) {+ if (!isRepairInvocation(process.argv)) {+ renderCliError(err, debug, safeEndpoint()); // exits 1+ }+ // Repair invocation: continue OSS-only. proLoaded stays false, so the Pro+ // stubs register below and would misreport a broken Pro as absent — the+ // warning here is what distinguishes the two, and no command in the set+ // above reaches a stub.+ console.error(+ "[!!] Ix Pro is installed but failed to initialize; continuing with OSS " ++ "commands only so this one can repair the install.",+ );+ }+ if (proLoaded) {+ // Collect commands that Pro added (weren't in OSS set)+ const proCommands = program.commands+ .filter((c: Command) => !ossCmdNames.has(c.name()))+ .map((c: Command) => ({ name: c.name(), desc: c.description() }));++ program.helpInformation = () => buildHelpText(proCommands);+ } else {+ registerProStubs(program);+ }++ // Check for updates (non-blocking, cached 1hr). Only when a person is+ // watching stderr — see updateCheckEnabled for why, and for the+ // IX_NO_UPDATE_CHECK opt-out.+ const args = process.argv.slice(2);+ if (updateCheckEnabled(args, process.env, stderrIsTerminal())) {+ // Deliberately not awaited — but it must still be caught here. The catch+ // inside checkForUpdate only guards its inner fetch chain; the function's+ // own promise covers the synchronous cached-read path, and a corrupt+ // ~/.ix/.version-check.json makes that throw. Uncaught, the new+ // unhandledRejection handler then aborts a command that already succeeded.+ checkForUpdate().catch(() => {});+ }++ // parseAsync (not parse) so rejections from async action handlers surface+ // here instead of floating off as unhandled rejections.+ try {+ await program.parseAsync();+ } catch (err) {+ renderCliError(err, debug, safeEndpoint());+ }+})();