Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

perf(cli): load only the command being run on the agent-facing path (#858)

Ian Hock43b5491cb0cb
diff --git a/CLAUDE.md b/CLAUDE.md
index d44b49c4..819b8573 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -45,16 +45,23 @@ ix map --silent # refresh the graph after code chang
`ix reset --workspace` (the registered workspace containing cwd, nothing
else). After a global reset, re-map each workspace.
- **The OSS↔Pro command boundary is derived at runtime, not declared.**
- `run-cli.ts` snapshots `ossCmdNames` right after `registerOssCommands()`; the
- Pro probe diffs against it. Adding a command to `oss.ts` silently makes it
- OSS; removing one makes Pro own it. `registerProCommands` is async and MUST
- be awaited.
+ `run-cli.ts` snapshots `ossCmdNames` right after registering the OSS
+ commands; the Pro probe diffs against it. Adding a command to `oss.ts`
+ silently makes it OSS; removing one makes Pro own it. `registerProCommands`
+ is async and MUST be awaited.
+- **A new OSS command goes in two places:** `registerOssCommands()` in
+ `register/oss.ts` and `OSS_COMMAND_TABLE` in `register/oss-table.ts`. With
+ Pro absent, `run-cli.ts` loads only the table entry for the command being
+ run. A command missing from the table still works (it takes the full path),
+ but `startup-fast-path.test.ts` fails until it is added. The shared
+ per-command setup is in `register/oss-setup.ts`.
- **`ix patches` is OSS, not Pro** (#371). It is implemented here and registered
in `oss.ts`. `@ix/pro` also registers a `patches`; commander throws on the
duplicate and Pro's `tryRegister` swallows the throw, so the OSS one — which
registers first — wins on a Kartr install too. Do not re-add it to
- `PRO_COMMANDS`: a stub for a command that exists in OSS shadows the real
- implementation, and the failure is silent rather than a crash.
+ `PRO_COMMANDS` (`register/pro-stubs.ts`): a stub for a command that exists
+ in OSS shadows the real implementation, and the failure is silent rather
+ than a crash.
- **`ix upgrade` wipes `~/.ix/cli/compass`.** The Compass assets ship only via
`ix upgrade`, and re-running the installer re-extracts over them, so a
re-install can leave `ix view` with no UI. `bootstrap.sh` re-runs `ix upgrade`
diff --git a/docs-site/src/content/docs/reference/configuration.md b/docs-site/src/content/docs/reference/configuration.md
index 4bc8dd3a..26834088 100644
--- a/docs-site/src/content/docs/reference/configuration.md
+++ b/docs-site/src/content/docs/reference/configuration.md
@@ -28,6 +28,7 @@ ix config set format llm # set a value
| `IX_PARSE_BUDGET_MS=<ms>` | How long `ix map` / `ix ingest` may spend parsing one file before skipping it and naming it in the summary (default 10000). A skipped file is tried again on every run, and `ix status` warns about it until it is in the graph. `0` turns the budget off |
| `IX_PARSE_WORKERS=<n>` | Most parse workers `ix map` / `ix ingest` starts (default 8, never more than the cores less one). Workers start as files need them, one per 50 files |
| `IX_PATCH_ACTOR=<actor>` | The `actor` stamped on each graph patch `ix map` / `ix ingest` sends (default `ix/ingestion`; `ix ingest --github` uses `ix/github-ingest`). Set it to empty (`IX_PATCH_ACTOR=`) for a backend that authenticates writers and stamps the verified principal itself: such a backend rejects a non-empty actor that differs from the principal with 403 `body actor ... conflicts with verified principal`. Any other value is sent as the actor |
+| `IX_LOAD_ALL_COMMANDS=1` | Loads every command module on each call, as releases before the start-up fast path did. Without Ix Pro installed, `ix <command>` normally loads only that command; with Ix Pro installed every call already loads everything, so this changes nothing there. If a command misbehaves on an install without Pro, try it again with this set: a difference between the two is a bug worth reporting |
### Bootstrap script variables
diff --git a/ix-cli/scripts/bench-startup.mjs b/ix-cli/scripts/bench-startup.mjs
new file mode 100644
index 00000000..bd941e2f
--- /dev/null
+++ b/ix-cli/scripts/bench-startup.mjs
@@ -0,0 +1,119 @@
+#!/usr/bin/env node
+// Copyright 2026 Ix Infrastructure Inc.
+
+// Wall time of the agent-facing `ix` commands against the built CLI, with `rg`
+// on the same term alongside `ix text` for comparison. A measuring tool for a
+// person, not a CI gate: timings on shared runners are too noisy to assert on.
+//
+// npm run build && node scripts/bench-startup.mjs [--runs 10] [--term word]
+// [--cwd dir] [--cli path]
+//
+// Every command runs once untimed (to warm the OS file cache and Node's
+// compile cache), then --runs times. Output is a Markdown table of the median
+// and p90 in milliseconds and the exit code of the last run: a command that
+// cannot reach a backend still pays its full start-up before it says so, which
+// is the part this measures.
+
+import { spawnSync } from "node:child_process";
+import { existsSync } from "node:fs";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = dirname(fileURLToPath(import.meta.url));
+
+function parseArgs(argv) {
+ const out = {
+ runs: 10,
+ term: "registerOssCommands",
+ cwd: resolve(here, "../.."),
+ cli: resolve(here, "../dist/cli/main.js"),
+ };
+ for (let i = 0; i < argv.length; i++) {
+ const flag = argv[i];
+ const value = argv[i + 1];
+ if (flag === "--runs") out.runs = Math.max(1, parseInt(value, 10) || out.runs);
+ else if (flag === "--term") out.term = value;
+ else if (flag === "--cwd") out.cwd = resolve(value);
+ else if (flag === "--cli") out.cli = resolve(value);
+ else if (flag === "-h" || flag === "--help") {
+ process.stdout.write("usage: bench-startup.mjs [--runs N] [--term WORD] [--cwd DIR] [--cli PATH]\n");
+ process.exit(0);
+ } else {
+ process.stderr.write(`unknown argument: ${flag}\n`);
+ process.exit(2);
+ }
+ i++;
+ }
+ return out;
+}
+
+const opts = parseArgs(process.argv.slice(2));
+if (!existsSync(opts.cli)) {
+ process.stderr.write(`${opts.cli} not found: run \`npm run build\` first.\n`);
+ process.exit(2);
+}
+
+const readTarget = existsSync(join(opts.cwd, "ix-cli/src/cli/main.ts")) ? "ix-cli/src/cli/main.ts" : "README.md";
+const hookInput = JSON.stringify({
+ session_id: "bench-startup",
+ tool_name: "Bash",
+ cwd: opts.cwd,
+ tool_input: { command: "true" },
+});
+
+const ix = (...args) => ({ cmd: process.execPath, args: [opts.cli, ...args] });
+const cases = [
+ { label: "node -e 0", ...{ cmd: process.execPath, args: ["-e", "0"] } },
+ { label: "ix --version", ...ix("--version") },
+ { label: `ix text ${opts.term}`, ...ix("text", opts.term) },
+ // An explicit "." -- with no path and a piped stdin, rg searches stdin.
+ { label: `rg -n ${opts.term} .`, cmd: "rg", args: ["-n", opts.term, "."] },
+ { label: `ix locate ${opts.term}`, ...ix("locate", opts.term) },
+ { label: `ix read ${readTarget}`, ...ix("read", readTarget) },
+ { label: `ix explain ${opts.term}`, ...ix("explain", opts.term) },
+ { label: `ix callers ${opts.term}`, ...ix("callers", opts.term) },
+ { label: `ix search ${opts.term}`, ...ix("search", opts.term) },
+ { label: `ix context ${opts.term}`, ...ix("context", opts.term) },
+ { label: `ix impact ${opts.term}`, ...ix("impact", opts.term) },
+ { label: `ix around ${readTarget}`, ...ix("around", readTarget) },
+ { label: "ix hook claude-post-edit", ...ix("hook", "claude-post-edit"), input: hookInput },
+];
+
+// No update check, no colour: neither is what an agent sees, and both vary.
+const env = { ...process.env, IX_NO_UPDATE_CHECK: "1", NO_COLOR: "1" };
+delete env.FORCE_COLOR;
+
+function once(c) {
+ const started = process.hrtime.bigint();
+ const child = spawnSync(c.cmd, c.args, {
+ cwd: opts.cwd, env, input: c.input ?? "", encoding: "utf-8", maxBuffer: 64 * 1024 * 1024,
+ });
+ const ms = Number(process.hrtime.bigint() - started) / 1e6;
+ return { ms, status: child.error ? `error: ${child.error.code ?? child.error.message}` : child.status };
+}
+
+function percentile(sorted, p) {
+ const index = Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1));
+ return sorted[index];
+}
+
+const rows = [];
+for (const c of cases) {
+ once(c);
+ const times = [];
+ let status;
+ for (let i = 0; i < opts.runs; i++) {
+ const r = once(c);
+ times.push(r.ms);
+ status = r.status;
+ }
+ times.sort((a, b) => a - b);
+ rows.push({ label: c.label, median: percentile(times, 50), p90: percentile(times, 90), status });
+}
+
+const fmt = (ms) => ms.toFixed(0);
+process.stdout.write(`Node ${process.version}, ${opts.runs} runs each, cwd ${opts.cwd}\n\n`);
+process.stdout.write("| Command | median ms | p90 ms | exit |\n|---|---:|---:|---:|\n");
+for (const r of rows) {
+ process.stdout.write(`| \`${r.label}\` | ${fmt(r.median)} | ${fmt(r.p90)} | ${r.status} |\n`);
+}
diff --git a/ix-cli/src/cli/__tests__/config-integrity.test.ts b/ix-cli/src/cli/__tests__/config-integrity.test.ts
index ff6ab9cd..80763af4 100644
--- a/ix-cli/src/cli/__tests__/config-integrity.test.ts
+++ b/ix-cli/src/cli/__tests__/config-integrity.test.ts
@@ -11,6 +11,7 @@ import { promisify } from "node:util";
import { Command } from "commander";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { createRequire } from "node:module";
import { parse } from "yaml";
/**
@@ -218,13 +219,16 @@ describe("a config that does not parse", () => {
describe("loadConfig is parsed once per change", () => {
it("answers from the memo, hands out copies, and sees saves and outside writes", async () => {
writeFileSync(configPath(), "endpoint: http://localhost:8090\nformat: text\nworkspaces: []\n");
- const parseSpy = vi.fn();
- vi.doMock("yaml", async (orig) => {
- const real = await orig<typeof import("yaml")>();
- return { ...real, parse: (...args: Parameters<typeof real.parse>) => { parseSpy(); return real.parse(...args); } };
- });
- const { loadConfig, saveConfig } = await import("../config.js");
+ // config.ts loads yaml with `require` on first use, so an ESM mock of
+ // "yaml" never reaches it. Spy on the CommonJS exports it actually calls
+ // (one module, one require cache per worker) instead.
+ const yamlExports = createRequire(import.meta.url)("yaml") as typeof import("yaml");
+ const parseSpy = vi.spyOn(yamlExports, "parse");
+ const { loadConfig, saveConfig, resetConfigMemo } = await import("../config.js");
+ resetConfigMemo();
const first = loadConfig();
+ // The spy sees the parse at all, so the "no new parses" check below means something.
+ expect(parseSpy).toHaveBeenCalledTimes(1);
first.workspaces!.push({ workspace_id: "x", workspace_name: "x", root_path: "/x", default: true });
const second = loadConfig();
expect(second.workspaces).toEqual([]); // the caller's edit did not reach the memo
@@ -239,7 +243,7 @@ describe("loadConfig is parsed once per change", () => {
// Another process writes: a different size is seen at once.
writeFileSync(configPath(), "endpoint: http://localhost:8190\nformat: text\n");
expect(loadConfig().endpoint).toBe("http://localhost:8190");
- vi.doUnmock("yaml");
+ parseSpy.mockRestore();
});
});
diff --git a/ix-cli/src/cli/__tests__/pro-loader.test.ts b/ix-cli/src/cli/__tests__/pro-loader.test.ts
index 437905e5..25896e88 100644
--- a/ix-cli/src/cli/__tests__/pro-loader.test.ts
+++ b/ix-cli/src/cli/__tests__/pro-loader.test.ts
@@ -75,3 +75,31 @@ it("does not treat an installed plugin with no exports map and no entry as absen
expect(r.stderr).toMatch(/^Installed Ix Pro could not (be resolved|initialize)\./);
expect(r.stderr).toContain("Reinstall the reviewed CLI/Pro pair");
});
+
+// `run-cli.ts` skips `tryLoadProCommands` -- and registers only the command
+// being run -- when `proIsAbsent()` says so. So it must say "absent" for
+// exactly the install the loader itself reports as absent, and never for an
+// installed Pro in any state, broken ones included.
+function proIsAbsentIn(setup: (pro: string) => void | undefined): boolean {
+ const root = mkdtempSync(join(tmpdir(), "ix-pro-loader-")); roots.push(root);
+ writeFileSync(join(root, "loader.mjs"), loader);
+ writeFileSync(join(root, "probe.mjs"), "import {proIsAbsent} from './loader.mjs'; console.log(JSON.stringify(proIsAbsent()));\n");
+ setup(join(root, "node_modules", "@ix", "pro"));
+ const r = spawnSync(process.execPath, [join(root, "probe.mjs")], { cwd: root, encoding: "utf8", timeout: 15000 });
+ expect(r.error).toBeUndefined(); expect(r.status, r.stderr).toBe(0);
+ return JSON.parse(r.stdout) as boolean;
+}
+function installPro(exports: unknown, code: string | undefined) {
+ return (pro: string) => {
+ mkdirSync(pro, { recursive: true });
+ writeFileSync(join(pro, "package.json"), JSON.stringify({ name: "@ix/pro", type: "module", ...(exports === undefined ? {} : { exports }) }));
+ if (code !== undefined) writeFileSync(join(pro, "register.js"), code);
+ };
+}
+it("proIsAbsent is true only where tryLoadProCommands reports absence", () => {
+ expect(proIsAbsentIn(() => undefined)).toBe(true);
+ expect(proIsAbsentIn(installPro({ "./register": "./register.js" }, "export function registerProCommands(){}"))).toBe(false);
+ expect(proIsAbsentIn(installPro({ "./register": "./register.js" }, "export const unrelated=true;"))).toBe(false);
+ expect(proIsAbsentIn(installPro({ ".": "./register.js" }, "export const unrelated=true;"))).toBe(false);
+ expect(proIsAbsentIn(installPro(undefined, undefined))).toBe(false);
+});
diff --git a/ix-cli/src/cli/__tests__/startup-fast-path.test.ts b/ix-cli/src/cli/__tests__/startup-fast-path.test.ts
new file mode 100644
index 00000000..ed5dffb3
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/startup-fast-path.test.ts
@@ -0,0 +1,383 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { spawn } from "node:child_process";
+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
+import * as nodeModule from "node:module";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath, pathToFileURL } from "node:url";
+import { Command } from "commander";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+import { registerOssCommands } from "../register/oss.js";
+import { LOAD_ALL_COMMANDS_ENV, OSS_COMMAND_TABLE, planStartup, registerForPlan } from "../register/oss-table.js";
+
+/**
+ * The CLI registers only the command being run when it can
+ * (`register/oss-table.ts`). These tests hold that fast path to the full one:
+ * the same commands, the same option setup, the same bytes out, and only the
+ * one command module loaded.
+ */
+
+const SRC = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
+const MAIN = join(SRC, "cli/main.ts");
+const TSX = pathToFileURL(nodeModule.createRequire(import.meta.url).resolve("tsx")).href;
+const VERSION = JSON.parse(readFileSync(join(SRC, "../package.json"), "utf-8")).version as string;
+
+const scratch: string[] = [];
+function tempDir(prefix: string): string {
+ const dir = mkdtempSync(join(tmpdir(), prefix));
+ scratch.push(dir);
+ return dir;
+}
+
+let home: string; // IX_HOME: exists, no config.yaml
+let work: string; // cwd: not a git repository, not a mapped workspace
+let tracer: string; // --import module recording every module the CLI loads
+let ttyStderr: string; // --import module making process.stderr claim to be a terminal
+
+beforeAll(() => {
+ home = tempDir("ix-fast-home-");
+ work = tempDir("ix-fast-work-");
+ writeFileSync(join(work, "a.txt"), "first line\nneedle here\nlast line\n");
+ const hooks = tempDir("ix-fast-hooks-");
+ writeFileSync(join(hooks, "hooks.mjs"),
+ 'import { appendFileSync } from "node:fs";\n' +
+ "export async function load(url, context, next) {\n" +
+ " if (process.env.IX_TEST_MODULE_TRACE) appendFileSync(process.env.IX_TEST_MODULE_TRACE, url + \"\\n\");\n" +
+ " return next(url, context);\n" +
+ "}\n");
+ writeFileSync(join(hooks, "register.mjs"),
+ 'import { register } from "node:module";\nregister(new URL("./hooks.mjs", import.meta.url));\n');
+ tracer = pathToFileURL(join(hooks, "register.mjs")).href;
+ writeFileSync(join(hooks, "tty-stderr.mjs"),
+ 'Object.defineProperty(process.stderr, "isTTY", { value: true, configurable: true });\n');
+ ttyStderr = pathToFileURL(join(hooks, "tty-stderr.mjs")).href;
+});
+
+afterAll(() => {
+ for (const dir of scratch.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+interface Run { stdout: string; stderr: string; status: number | null }
+
+function baseEnv(extra: Record<string, string> = {}): NodeJS.ProcessEnv {
+ const env: NodeJS.ProcessEnv = { ...process.env, IX_HOME: home, IX_NO_UPDATE_CHECK: "1", NO_COLOR: "1", ...extra };
+ for (const key of ["FORCE_COLOR", "IX_FORMAT", LOAD_ALL_COMMANDS_ENV, "NODE_COMPILE_CACHE", "NODE_DISABLE_COMPILE_CACHE"]) {
+ if (!(key in extra)) delete env[key];
+ }
+ return env;
+}
+
+function runCli(args: string[], opts: { env?: NodeJS.ProcessEnv; cwd?: string; input?: string; imports?: string[] } = {}): Promise<Run> {
+ return new Promise((done, fail) => {
+ const child = spawn(process.execPath, ["--import", TSX, ...(opts.imports ?? []).flatMap((m) => ["--import", m]), MAIN, ...args], {
+ cwd: opts.cwd ?? work, env: opts.env ?? baseEnv(), stdio: ["pipe", "pipe", "pipe"],
+ });
+ let stdout = "";
+ let stderr = "";
+ child.stdout.setEncoding("utf-8").on("data", (d: string) => { stdout += d; });
+ child.stderr.setEncoding("utf-8").on("data", (d: string) => { stderr += d; });
+ child.on("error", fail);
+ child.on("close", (status) => done({ stdout, stderr, status }));
+ child.stdin.end(opts.input ?? "");
+ });
+}
+
+/** The `commands/*` modules a run loaded, by file name without extension. */
+async function commandModulesLoaded(
+ args: string[], extraEnv: Record<string, string> = {}, input?: string, imports: string[] = [],
+): Promise<string[]> {
+ const trace = join(tempDir("ix-fast-trace-"), "modules.txt");
+ writeFileSync(trace, "");
+ await runCli(args, { env: baseEnv({ IX_TEST_MODULE_TRACE: trace, ...extraEnv }), imports: [tracer, ...imports], input });
+ const urls = readFileSync(trace, "utf-8").split("\n").filter(Boolean);
+ // Proves the tracer saw the CLI at all, so an empty answer means something.
+ expect(urls.some((u) => /\/cli\/main\.ts$/.test(u))).toBe(true);
+ const names = urls
+ .map((u) => /\/src\/cli\/commands\/([^/]+)\.ts$/.exec(u)?.[1])
+ .filter((n): n is string => n !== undefined);
+ return [...new Set(names)].sort();
+}
+
+function namesAndAliases(program: Command): string[] {
+ return program.commands.flatMap((c) => [c.name(), ...c.aliases()]).sort();
+}
+
+/** What `configureOssOptions` decides about a command, in a comparable shape. */
+function optionShape(command: Command): unknown {
+ return {
+ name: command.name(),
+ aliases: command.aliases(),
+ options: command.options.map((o) => ({
+ flags: o.flags, description: o.description, defaultValue: o.defaultValue, choices: o.argChoices,
+ })),
+ values: command.opts(),
+ children: command.commands.map(optionShape),
+ };
+}
+
+describe("the fast-path table", () => {
+ it("names every command and alias registerOssCommands() registers, and nothing else", () => {
+ const program = new Command();
+ registerOssCommands(program);
+ expect(Object.keys(OSS_COMMAND_TABLE).sort()).toEqual(namesAndAliases(program));
+ });
+
+ it("points each name at the module that registers it", async () => {
+ for (const [name, load] of Object.entries(OSS_COMMAND_TABLE)) {
+ const program = new Command();
+ (await load())(program);
+ expect(namesAndAliases(program), name).toContain(name);
+ }
+ });
+});
+
+describe("planStartup", () => {
+ const absent = () => true;
+ const present = () => false;
+ const kind = (args: string[], env: NodeJS.ProcessEnv = {}, pro = absent) => planStartup(args, env, pro).kind;
+
+ it("registers one command for a known first word", () => {
+ for (const name of ["text", "locate", "read", "explain", "callers", "search", "context", "impact", "around", "hook"]) {
+ const plan = planStartup([name, "x"], {}, absent);
+ expect(plan.kind, name).toBe("command");
+ expect(plan.kind === "command" && plan.name).toBe(name);
+ }
+ expect(kind(["text", "--help"])).toBe("command");
+ });
+
+ it("registers no command for a lone --version or -V", () => {
+ expect(kind(["--version"])).toBe("version");
+ expect(kind(["-V"])).toBe("version");
+ });
+
+ it("registers everything whenever commander needs the whole list", () => {
+ expect(kind([])).toBe("all");
+ expect(kind(["--help"])).toBe("all");
+ expect(kind(["-h"])).toBe("all");
+ expect(kind(["help"])).toBe("all");
+ expect(kind(["help", "text"])).toBe("all");
+ expect(kind(["txt"])).toBe("all"); // unknown: "did you mean"
+ expect(kind(["briefing"])).toBe("all"); // a Pro command / stub
+ expect(kind(["--pretty", "text", "x"])).toBe("all");
+ expect(kind(["--version", "text"])).toBe("all");
+ expect(kind(["constructor"])).toBe("all"); // not an own key of the table
+ expect(kind(["__proto__"])).toBe("all");
+ });
+
+ it("registers everything when Pro is installed, broken or not", () => {
+ expect(kind(["text", "x"], {}, present)).toBe("all");
+ expect(kind(["--version"], {}, present)).toBe("all");
+ expect(kind(["patches"], {}, present)).toBe("all");
+ });
+
+ it("registers everything when IX_LOAD_ALL_COMMANDS=1", () => {
+ expect(kind(["text", "x"], { [LOAD_ALL_COMMANDS_ENV]: "1" })).toBe("all");
+ expect(kind(["--version"], { [LOAD_ALL_COMMANDS_ENV]: "1" })).toBe("all");
+ });
+
+ it("does not look for Pro when the answer is everything anyway", () => {
+ let probes = 0;
+ planStartup(["--help"], {}, () => { probes++; return true; });
+ planStartup(["txt"], {}, () => { probes++; return true; });
+ expect(probes).toBe(0);
+ });
+});
+
+describe("registerForPlan", () => {
+ let savedHome: string | undefined;
+ let savedFormat: string | undefined;
+ beforeAll(() => {
+ savedHome = process.env.IX_HOME;
+ savedFormat = process.env.IX_FORMAT;
+ process.env.IX_HOME = home;
+ process.env.IX_FORMAT = "llm"; // exercises the configured-default rewrite
+ });
+ afterAll(() => {
+ if (savedHome === undefined) delete process.env.IX_HOME; else process.env.IX_HOME = savedHome;
+ if (savedFormat === undefined) delete process.env.IX_FORMAT; else process.env.IX_FORMAT = savedFormat;
+ });
+
+ it("registers exactly the module's commands, set up as registerOssCommands() sets them up", async () => {
+ const full = new Command();
+ registerOssCommands(full);
+ for (const name of Object.keys(OSS_COMMAND_TABLE)) {
+ if (name === "help") continue; // never planned: it needs every command
+ const program = new Command();
+ const plan = planStartup([name], {}, () => true);
+ expect(await registerForPlan(program, plan), name).toBe(true);
+ const registered = program.commands.map((c) => c.name());
+ // A module that registers two commands (callers/callees) brings both.
+ expect(registered.length, name).toBeLessThanOrEqual(2);
+ for (const command of program.commands) {
+ const twin = full.commands.find((c) => c.name() === command.name());
+ expect(optionShape(command), name).toEqual(optionShape(twin!));
+ }
+ }
+ });
+
+ it("registers nothing for --version and everything for the full plan", async () => {
+ const none = new Command();
+ expect(await registerForPlan(none, { kind: "version" })).toBe(true);
+ expect(none.commands).toEqual([]);
+
+ const all = new Command();
+ expect(await registerForPlan(all, { kind: "all" })).toBe(false);
+ const expected = new Command();
+ registerOssCommands(expected);
+ expect(namesAndAliases(all)).toEqual(namesAndAliases(expected));
+ });
+});
+
+describe("the CLI loads only the command it runs", () => {
+ const cases: Array<[string[], string[]]> = [
+ [["--version"], []],
+ [["text", "needle", "--format", "json"], ["text"]],
+ [["locate", "x"], ["locate"]],
+ [["read", "a.txt"], ["read"]],
+ [["explain", "x"], ["depends", "explain"]], // explain/facts.ts uses depends' tree
+ [["callers", "x"], ["callers", "text"]], // the text fallback's snippet clipper
+ [["search", "x"], ["search"]],
+ [["context", "x"], ["context", "depends"]],
+ [["impact", "x"], ["impact"]],
+ [["around", "a.txt"], ["around"]],
+ [["hook", "--help"], ["hook"]],
+ ];
+
+ it.concurrent.each(cases)("ix %j loads %j", async (args, expected) => {
+ expect(await commandModulesLoaded(args)).toEqual(expected);
+ }, 60_000);
+
+ it.concurrent("ix hook claude-post-edit loads no command module", async () => {
+ expect(await commandModulesLoaded(["hook", "claude-post-edit"], {}, "{}")).toEqual([]);
+ }, 60_000);
+
+ it.concurrent("the full path still loads every command module", async () => {
+ const loaded = await commandModulesLoaded(["--version"], { [LOAD_ALL_COMMANDS_ENV]: "1" });
+ expect(loaded.length).toBeGreaterThanOrEqual(38);
+ expect(loaded).toEqual(expect.arrayContaining(["text", "read", "workflows", "upgrade"]));
+ }, 60_000);
+});
+
+describe("the fast and full paths answer identically", () => {
+ const cases: Array<[string, string[], Record<string, string>?]> = [
+ ["--version", ["--version"]],
+ ["-V", ["-V"]],
+ ["root --help", ["--help"]],
+ ["help text", ["help", "text"]],
+ ["unknown command", ["txt"]],
+ ["Pro command, Pro absent", ["briefing", "list"]],
+ ["subcommand --help", ["text", "--help"]],
+ ["missing argument", ["read"]],
+ ["read --format json", ["read", "a.txt", "--format", "json"]],
+ ["read --pretty", ["read", "a.txt", "--format", "json", "--pretty"]],
+ ["read --fields", ["read", "a.txt", "--format", "json", "--fields", "content,lineStart"]],
+ ["read --quiet", ["read", "a.txt:1-2", "--quiet"]],
+ ["read --format llm", ["read", "a.txt", "--format", "llm"]],
+ ["configured default format", ["read", "a.txt"], { IX_FORMAT: "json" }],
+ ["invalid --format choice", ["text", "needle", "--format", "bogus"]],
+ ["invalid integer option", ["text", "needle", "--limit", "abc"]],
+ ["invalid OPTION_CHOICES value", ["context", "x", "--depth", "bogus"]],
+ ["unknown option", ["locate", "x", "--bogus"]],
+ ["text --format json", ["text", "needle", "--format", "json"]],
+ ["graph command outside a workspace", ["locate", "x", "--format", "json"]],
+ ["hook --help", ["hook", "--help"]],
+ ];
+
+ it.concurrent.each(cases)("%s", async (_label, args, extra = {}) => {
+ const [fast, full] = await Promise.all([
+ runCli(args, { env: baseEnv(extra) }),
+ runCli(args, { env: baseEnv({ ...extra, [LOAD_ALL_COMMANDS_ENV]: "1" }) }),
+ ]);
+ expect(fast).toEqual(full);
+ expect(fast.stdout + fast.stderr).not.toBe("");
+ }, 60_000);
+
+ it.concurrent("--version prints the version and nothing else", async () => {
+ expect(await runCli(["--version"])).toEqual({ stdout: `${VERSION}\n`, stderr: "", status: 0 });
+ }, 60_000);
+});
+
+describe("the update check", () => {
+ // Every other test runs with stderr piped, where `upgrade.js` is never
+ // loaded. A person's terminal is the one place it is, so fake one.
+ it.concurrent("is loaded only when stderr is a terminal", async () => {
+ expect(await commandModulesLoaded(["read", "a.txt", "--format", "json"])).toEqual(["read"]);
+ expect(await commandModulesLoaded(["read", "a.txt", "--format", "json"], {}, undefined, [ttyStderr]))
+ .toEqual(["read", "upgrade"]);
+ }, 60_000);
+
+ it.concurrent("still prints its notice on a terminal, the same on both paths", async () => {
+ // A fresh cached answer naming a newer release: the notice comes from the
+ // cache, so no request leaves the machine.
+ const own = tempDir("ix-update-home-");
+ writeFileSync(join(own, ".version-check.json"), JSON.stringify({ latest: "999.0.0", checkedAt: Date.now() }));
+ const env = baseEnv({ IX_HOME: own, IX_NO_UPDATE_CHECK: "" });
+ const args = ["read", "a.txt:1-1", "--format", "text"];
+ const [fast, full] = await Promise.all([
+ runCli(args, { env, imports: [ttyStderr] }),
+ runCli(args, { env: { ...env, [LOAD_ALL_COMMANDS_ENV]: "1" }, imports: [ttyStderr] }),
+ ]);
+ expect(fast.status).toBe(0);
+ expect(fast.stdout).toContain("first line");
+ expect(fast.stderr).toContain("999.0.0");
+ expect(fast).toEqual(full);
+ }, 60_000);
+});
+
+describe("the compile cache", () => {
+ const supported = typeof (nodeModule as { enableCompileCache?: unknown }).enableCompileCache === "function";
+
+ /** A scratch OS temp dir (TMPDIR on POSIX, TEMP/TMP on Windows), an empty IX_HOME and a cwd. */
+ function sandbox(extra: Record<string, string> = {}) {
+ const tmp = tempDir("ix-cc-tmp-");
+ const ixHomeDir = tempDir("ix-cc-home-");
+ const cwd = tempDir("ix-cc-cwd-");
+ const env = baseEnv({ IX_HOME: ixHomeDir, TMPDIR: tmp, TMP: tmp, TEMP: tmp, ...extra });
+ return { tmp, ixHomeDir, cwd, env };
+ }
+ const versionOnly = { stdout: `${VERSION}\n`, stderr: "", status: 0 };
+
+ it.skipIf(!supported)("lives in Node's default place under the OS temp dir, never under IX_HOME or the cwd", async () => {
+ const box = sandbox();
+ expect(await runCli(["--version"], { cwd: box.cwd, env: box.env })).toEqual(versionOnly);
+ expect(statSync(join(box.tmp, "node-compile-cache")).isDirectory()).toBe(true);
+ expect(readdirSync(box.ixHomeDir)).toEqual([]);
+ expect(readdirSync(box.cwd)).toEqual([]);
+ }, 60_000);
+
+ it("creates nothing when NODE_DISABLE_COMPILE_CACHE is set", async () => {
+ const box = sandbox({ NODE_DISABLE_COMPILE_CACHE: "1" });
+ expect(await runCli(["--version"], { cwd: box.cwd, env: box.env })).toEqual(versionOnly);
+ expect(existsSync(join(box.tmp, "node-compile-cache"))).toBe(false);
+ expect(readdirSync(box.ixHomeDir)).toEqual([]);
+ expect(readdirSync(box.cwd)).toEqual([]);
+ }, 60_000);
+
+ it("leaves NODE_COMPILE_CACHE to Node", async () => {
+ const elsewhere = join(tempDir("ix-cc-elsewhere-"), "cache");
+ const box = sandbox({ NODE_COMPILE_CACHE: elsewhere });
+ expect(await runCli(["--version"], { cwd: box.cwd, env: box.env })).toEqual(versionOnly);
+ expect(existsSync(join(box.tmp, "node-compile-cache"))).toBe(false);
+ expect(readdirSync(box.ixHomeDir)).toEqual([]);
+ }, 60_000);
+
+ it("does not create IX_HOME", async () => {
+ const box = sandbox();
+ const missing = join(tempDir("ix-cc-parent-"), "home");
+ expect(await runCli(["--version"], { cwd: box.cwd, env: { ...box.env, IX_HOME: missing } })).toEqual(versionOnly);
+ expect(existsSync(missing)).toBe(false);
+ }, 60_000);
+
+ it("is silently skipped when its directory cannot be created", async () => {
+ // A regular file where the directory has to go fails for every user,
+ // root included, on every platform.
+ const box = sandbox();
+ writeFileSync(join(box.tmp, "node-compile-cache"), "");
+ expect(await runCli(["--version"], { cwd: box.cwd, env: box.env })).toEqual(versionOnly);
+ const read = await runCli(["read", "a.txt", "--format", "json"], { env: box.env });
+ expect(read.status).toBe(0);
+ expect(read.stderr).toBe("");
+ expect(statSync(join(box.tmp, "node-compile-cache")).isFile()).toBe(true);
+ }, 60_000);
+});
diff --git a/ix-cli/src/cli/__tests__/startup-imports.test.ts b/ix-cli/src/cli/__tests__/startup-imports.test.ts
index 000df9c4..38eeef6e 100644
--- a/ix-cli/src/cli/__tests__/startup-imports.test.ts
+++ b/ix-cli/src/cli/__tests__/startup-imports.test.ts
@@ -40,8 +40,12 @@ function startupPackages(entries: string[]): { packages: Set<string>; modules: n
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")]);
+ // compile cache, and `run-cli.ts` imports `register/oss.ts` (every command)
+ // whenever it cannot register just the one being run -- a dynamic import,
+ // so it is named here. Together they are the largest start-up graph.
+ const { packages, modules } = startupPackages([
+ join(SRC, "cli/main.ts"), join(SRC, "cli/run-cli.ts"), join(SRC, "cli/register/oss.ts"),
+ ]);
// The walk really reached the command registry.
expect(modules).toBeGreaterThan(50);
diff --git a/ix-cli/src/cli/bootstrap.ts b/ix-cli/src/cli/bootstrap.ts
index 7b8b7409..5656ba37 100644
--- a/ix-cli/src/cli/bootstrap.ts
+++ b/ix-cli/src/cli/bootstrap.ts
@@ -13,7 +13,6 @@ import { ixHome } from "./ix-home.js";
import { stderr } from "./stderr.js";
import { workspaceIdForPath } from "./system.js";
import { IX_CALLER_ENV } from "./next-step.js";
-import { readBackendHealth } from "./commands/upgrade.js";
import { isLocalEndpoint } from "./backend-version.js";
export interface BootstrapResult {
@@ -249,6 +248,11 @@ export function canAutoStartBackend(endpoint: string): boolean {
export async function ensureBackendAvailable(): Promise<void> {
const endpoint = getEndpoint();
const client = createClient({ endpoint });
+ // Loaded here, not at the top: every graph command imports this file, and
+ // `upgrade.js` (with the release-download code behind it) is needed only on
+ // this path. Outside the try, so a module that fails to load is not taken
+ // for a backend that is down.
+ const { readBackendHealth } = await import("./commands/upgrade.js");
try {
// Through readBackendHealth so this probe records the release the backend
// reports, like every other health fetch. `ix init` never reaches the
diff --git a/ix-cli/src/cli/config.ts b/ix-cli/src/cli/config.ts
index 741c8282..9e22d20e 100644
--- a/ix-cli/src/cli/config.ts
+++ b/ix-cli/src/cli/config.ts
@@ -4,7 +4,8 @@ import { readFileSync, writeFileSync, existsSync, rmSync, chmodSync, realpathSyn
import { dirname, isAbsolute, join, relative, resolve as resolvePath, sep } from "node:path";
import { createHash, randomBytes } from "node:crypto";
import { execFileSync } from "node:child_process";
-import { parse, stringify } from "yaml";
+import { createRequire } from "node:module";
+import type * as Yaml from "yaml";
import { IxClient } from "../client/api.js";
import { ixHome } from "./ix-home.js";
import { isLocalEndpoint } from "./backend-version.js";
@@ -12,6 +13,16 @@ import { renameWithRetry, withConfigLock } from "./config-lock.js";
export { ConfigLockError } from "./config-lock.js";
+// `yaml` is ~70 modules, loaded the first time config.yaml is actually parsed
+// or written rather than on import: every command imports this file, and
+// `ix --version`, or any call made where there is no config.yaml, never needs
+// it. Synchronous, because `loadConfig` is.
+const requireYaml = createRequire(import.meta.url);
+let yamlModule: typeof Yaml | undefined;
+function yaml(): typeof Yaml {
+ return (yamlModule ??= requireYaml("yaml") as typeof Yaml);
+}
+
/**
* The key of a project root's per-root state files. Canonical first: `ix
* ingest <path>` resolves its root with `canonicalWorkspacePath`, and a caller
@@ -228,6 +239,7 @@ export function loadConfig(): IxConfig {
closeSync(fd);
}
let parsed: Partial<IxConfig> | null;
+ const { parse } = yaml(); // outside the try: not a parse error if it fails
try {
parsed = parse(raw) as Partial<IxConfig> | null;
} catch (err) {
@@ -346,6 +358,7 @@ function writeConfigLocked(config: IxConfig, configDir: string, configPath: stri
mkdirSync(configDir, { recursive: true, mode: 0o700 });
let existing: Record<string, unknown> = {};
if (existsSync(configPath)) {
+ const { parse } = yaml(); // outside the try: not a parse error if it fails
try {
const parsed = parse(readFileSync(configPath, "utf-8"));
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
@@ -383,7 +396,7 @@ function writeConfigLocked(config: IxConfig, configDir: string, configPath: stri
// EPERM/EBUSY while another process has the target open -- an unlocked
// reader, an indexer, antivirus -- so it is retried for a few seconds.
const tmpPath = `${configPath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
- writeFileSync(tmpPath, stringify(merged), { mode: 0o600 });
+ writeFileSync(tmpPath, yaml().stringify(merged), { mode: 0o600 });
try {
renameWithRetry(tmpPath, configPath);
} catch (err) {
diff --git a/ix-cli/src/cli/main.ts b/ix-cli/src/cli/main.ts
index 4dbe1057..48097ca6 100644
--- a/ix-cli/src/cli/main.ts
+++ b/ix-cli/src/cli/main.ts
@@ -26,12 +26,20 @@ const MIN_NODE_MAJOR = 22;
// 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.
+// first request on a warm machine. Node >= 22.1 keys the cache by file content
+// and Node version, so an upgrade can never run stale code, and keeps it in
+// its default place under the OS temp directory, which the OS cleans: caches
+// left behind by older Node versions do not pile up in Ix's own state.
+// Node's own settings win, and then this calls nothing: NODE_COMPILE_CACHE has
+// already been applied before this line runs, and NODE_DISABLE_COMPILE_CACHE
+// (any value, as Node reads it) turns the cache off. Absent on 22.0: then a
+// no-op. A directory that cannot be created or written is reported in the
+// return value, which is ignored: it only costs speed.
try {
- (nodeModule as { enableCompileCache?: () => unknown }).enableCompileCache?.();
+ const { enableCompileCache } = nodeModule as { enableCompileCache?: () => unknown };
+ if (enableCompileCache && process.env.NODE_COMPILE_CACHE === undefined && process.env.NODE_DISABLE_COMPILE_CACHE === undefined) {
+ enableCompileCache();
+ }
} catch {
// A cache that cannot be opened only costs speed.
}
diff --git a/ix-cli/src/cli/register/oss-setup.ts b/ix-cli/src/cli/register/oss-setup.ts
new file mode 100644
index 00000000..ae19e5e6
--- /dev/null
+++ b/ix-cli/src/cli/register/oss-setup.ts
@@ -0,0 +1,151 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+/**
+ * What `registerOssCommands()` does to the commands once they are registered:
+ * option choices, the configured default `--format`, the shared
+ * `--pretty`/`--quiet`/`--fields` options, and the `preAction` hook that
+ * applies them and validates option values.
+ *
+ * Its own module so the CLI's fast path (`register/oss-table.ts`), which
+ * registers only the command being run, applies exactly the same setup
+ * without loading every other command module to get at it.
+ */
+
+import type { Command } from "commander";
+import { validateCliOptions } from "../options.js";
+import { setPrettyJson } from "../format.js";
+import { setOutputShape } from "../output-shape.js";
+import {
+ BUILT_IN_DEFAULT_FORMAT,
+ DEFAULT_FORMAT_CHOICES,
+ resolveDefaultFormat,
+} from "../default-format.js";
+import { readConfiguredFormat } from "../config.js";
+import { stderrDim } from "../stderr.js";
+
+const OPTION_CHOICES: Record<string, Record<string, string[]>> = {
+ query: { depth: ["shallow", "standard", "deep"], format: ["text", "json"] },
+ map: { format: [...DEFAULT_FORMAT_CHOICES, "silent"], sort: ["importance", "confidence", "size", "alpha"] },
+ subsystems: { sort: ["importance", "confidence", "size", "alpha"] },
+ savings: { model: ["opus", "sonnet", "haiku", "gpt-4o"] },
+ context: { depth: ["compact", "standard", "full", "shallow", "deep"] },
+ mcp: { tools: ["core", "all"] },
+};
+
+/**
+ * Every command this file registered, so the preAction hook below can tell an
+ * OSS option from a Pro one. Pro commands are registered later, against the
+ * same root program, from a package this repo cannot see -- so their option
+ * domains are not ours to infer.
+ */
+const ossCommands = new WeakSet<Command>();
+
+function configureOssOptions(root: Command): void {
+ const { format: defaultFormat, ignored } = resolveDefaultFormat(
+ process.env,
+ // Never let an unreadable or half-written config.yaml stop the CLI from
+ // registering its commands: a config that does not parse is reported by the
+ // command that needs it (ConfigParseError), not here. And no full parse for
+ // one scalar on every invocation, `--version` included.
+ () => { try { return readConfiguredFormat(); } catch { return undefined; } },
+ );
+
+ // Only where a person will read it: an agent captures stderr, and one more
+ // line at the top of its tool result is exactly what this change is for.
+ if (ignored && process.stderr.isTTY) {
+ stderrDim(
+ `Ignoring ${ignored.source}=${ignored.value}: not one of ` +
+ `${DEFAULT_FORMAT_CHOICES.join(", ")}. Using ${defaultFormat}.`
+ );
+ }
+
+ const visit = (command: Command): void => {
+ ossCommands.add(command);
+ const commandChoices = OPTION_CHOICES[command.name()] ?? {};
+ let rendersRows = false;
+ let rendersJson = false;
+ for (const option of command.options) {
+ const choices = commandChoices[option.attributeName()]
+ ?? (option.long === "--format" ? [...DEFAULT_FORMAT_CHOICES] : undefined);
+ if (choices) option.choices(choices);
+ applyDefaultFormat(command, option, choices, defaultFormat);
+ if (option.long === "--format") rendersRows = true;
+ if (option.long === "--format" && (choices ?? []).includes("json")) rendersJson = true;
+ }
+ // Declared here rather than 32 times by hand, and only where it means
+ // something: a command with no `--format json` has no JSON to shape.
+ if (rendersJson && !command.options.some((option) => option.long === "--pretty")) {
+ command.option("--pretty", "Indent JSON output (the default only when stdout is a terminal)");
+ }
+ // Declared here rather than on 33 commands by hand, and only where there
+ // is an answer to shape. A command with no `--format` prints a status
+ // line or nothing.
+ if (rendersRows) {
+ if (!command.options.some((option) => option.long === "--quiet")) {
+ command.option("--quiet", "Drop headers, section titles and advisory hints");
+ }
+ if (!command.options.some((option) => option.long === "--fields")) {
+ command.option("--fields <list>", "Keep only these fields on each row, in this order (e.g. name,path,lines)");
+ }
+ }
+ for (const child of command.commands) visit(child);
+ };
+ visit(root);
+}
+
+/**
+ * Point a `--format` option at the configured default.
+ *
+ * Only an option still sitting on the built-in `text` is moved: a command that
+ * declares a different default has a reason for it, and `ix config set format`
+ * is not an instruction to override it. The default must also be a format that
+ * command accepts — `query` renders text and json only, so `IX_FORMAT=llm`
+ * leaves it where it is rather than handing the renderer a format it has no
+ * branch for.
+ */
+function applyDefaultFormat(
+ command: Command,
+ option: Command["options"][number],
+ choices: string[] | undefined,
+ defaultFormat: string,
+): void {
+ if (option.long !== "--format") return;
+ if (defaultFormat === BUILT_IN_DEFAULT_FORMAT) return;
+ if (option.defaultValue !== BUILT_IN_DEFAULT_FORMAT) return;
+ if (!choices?.includes(defaultFormat)) return;
+
+ option.default(defaultFormat);
+ // `.option()` copies the default into the command's option values as it
+ // registers, so moving the Option's default afterwards changes the help text
+ // and nothing else. The stored value has to be moved with it -- and only
+ // while it is still the default, which at registration time it always is.
+ if (command.getOptionValueSource(option.attributeName()) === "default") {
+ command.setOptionValueWithSource(option.attributeName(), defaultFormat, "default");
+ }
+}
+
+/**
+ * Configure every command registered on `program` so far as an OSS command and
+ * install the `preAction` hook. Call once, after the OSS commands are
+ * registered and before Pro's are.
+ */
+export function applyOssSetup(program: Command): void {
+ configureOssOptions(program);
+
+ program.hook("preAction", (_thisCommand, actionCommand) => {
+ // Before anything prints. All three are properties of the run, not of a
+ // payload, so the renderers read them from one place rather than every
+ // signature growing parameters it only forwards.
+ const opts = actionCommand.opts();
+ setPrettyJson(opts.pretty === true);
+ setOutputShape({ quiet: opts.quiet === true, fields: typeof opts.fields === "string" ? opts.fields : undefined });
+
+ // OSS commands only. The rules below read an option's *shape* -- `<n>`
+ // means a non-negative integer, `--min-confidence` means 0..1 -- which is
+ // a claim about commands whose declarations live in this repo. A Pro
+ // command declaring `--threshold <n>` for a float would be rejected by a
+ // rule its author never opted into, and no test here could catch it.
+ if (!ossCommands.has(actionCommand)) return;
+ validateCliOptions(actionCommand);
+ });
+}
diff --git a/ix-cli/src/cli/register/oss-table.ts b/ix-cli/src/cli/register/oss-table.ts
new file mode 100644
index 00000000..d6d5d95e
--- /dev/null
+++ b/ix-cli/src/cli/register/oss-table.ts
@@ -0,0 +1,132 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import type { Command } from "commander";
+import { applyOssSetup } from "./oss-setup.js";
+import { proIsAbsent } from "./pro-loader.js";
+
+/**
+ * Which module registers each OSS command, so the CLI can load only the one
+ * being run.
+ *
+ * `registerOssCommands()` (`register/oss.ts`) imports all ~40 command modules
+ * and everything they depend on, on every call, `--version` included, before
+ * the command does anything. Agents and plugin hooks call `ix` far more
+ * often than a person does, and compare it with `rg`, which has answered by
+ * then. So `run-cli.ts` asks `planStartup` first and, where it can, registers
+ * the one command instead.
+ *
+ * Keyed by every top-level name and alias `registerOssCommands()` registers;
+ * a module that registers two commands (`callers` and `callees`) appears under
+ * both. A test holds this table and `registerOssCommands()` to the same set of
+ * names, so a command added there and not here fails CI rather than silently
+ * taking the slow path.
+ */
+type RegisterCommand = (program: Command) => void;
+
+export const OSS_COMMAND_TABLE: Readonly<Record<string, () => Promise<RegisterCommand>>> = {
+ query: async () => (await import("../commands/query.js")).registerQueryCommand,
+ ingest: async () => (await import("../commands/ingest.js")).registerIngestCommand,
+ search: async () => (await import("../commands/search.js")).registerSearchCommand,
+ status: async () => (await import("../commands/status.js")).registerStatusCommand,
+ entity: async () => (await import("../commands/entity.js")).registerEntityCommand,
+ history: async () => (await import("../commands/history.js")).registerHistoryCommand,
+ conflicts: async () => (await import("../commands/conflicts.js")).registerConflictsCommand,
+ diff: async () => (await import("../commands/diff.js")).registerDiffCommand,
+ init: async () => (await import("../commands/init.js")).registerInitCommand,
+ text: async () => (await import("../commands/text.js")).registerTextCommand,
+ locate: async () => (await import("../commands/locate.js")).registerLocateCommand,
+ explain: async () => (await import("../commands/explain.js")).registerExplainCommand,
+ callers: async () => (await import("../commands/callers.js")).registerCallersCommand,
+ callees: async () => (await import("../commands/callers.js")).registerCallersCommand,
+ imports: async () => (await import("../commands/imports.js")).registerImportsCommand,
+ "imported-by": async () => (await import("../commands/imports.js")).registerImportsCommand,
+ contains: async () => (await import("../commands/contains.js")).registerContainsCommand,
+ stats: async () => (await import("../commands/stats.js")).registerStatsCommand,
+ doctor: async () => (await import("../commands/doctor.js")).registerDoctorCommand,
+ depends: async () => (await import("../commands/depends.js")).registerDependsCommand,
+ read: async () => (await import("../commands/read.js")).registerReadCommand,
+ inventory: async () => (await import("../commands/inventory.js")).registerInventoryCommand,
+ impact: async () => (await import("../commands/impact.js")).registerImpactCommand,
+ rank: async () => (await import("../commands/rank.js")).registerRankCommand,
+ overview: async () => (await import("../commands/overview.js")).registerOverviewCommand,
+ watch: async () => (await import("../commands/watch.js")).registerWatchCommand,
+ docker: async () => (await import("../commands/docker.js")).registerDockerCommand,
+ help: async () => (await import("../commands/workflows.js")).registerWorkflowsHelpCommand,
+ map: async () => (await import("../commands/map.js")).registerMapCommand,
+ smells: async () => (await import("../commands/smells.js")).registerSmellsCommand,
+ subsystems: async () => (await import("../commands/subsystems.js")).registerSubsystemsCommand,
+ reset: async () => (await import("../commands/reset.js")).registerResetCommand,
+ config: async () => (await import("../commands/config.js")).registerConfigCommand,
+ trace: async () => (await import("../commands/trace.js")).registerTraceCommand,
+ upgrade: async () => (await import("../commands/upgrade.js")).registerUpgradeCommand,
+ view: async () => (await import("../commands/view.js")).registerViewCommand,
+ savings: async () => (await import("../commands/savings.js")).registerSavingsCommand,
+ patches: async () => (await import("../commands/patches.js")).registerPatchesCommand,
+ mcp: async () => (await import("../commands/mcp.js")).registerMcpCommand,
+ context: async () => (await import("../commands/context.js")).registerContextCommand,
+ around: async () => (await import("../commands/around.js")).registerAroundCommand,
+ hook: async () => (await import("../commands/hook.js")).registerHookCommand,
+};
+
+/**
+ * Commands that read the registry itself. `ix help <topic>` looks the topic up
+ * among every registered command, so it needs all of them.
+ */
+const NEEDS_EVERY_COMMAND = new Set(["help"]);
+
+/** Set to `1` to register every command, as before the table existed. */
+export const LOAD_ALL_COMMANDS_ENV = "IX_LOAD_ALL_COMMANDS";
+
+export type StartupPlan =
+ | { kind: "all" }
+ | { kind: "version" }
+ | { kind: "command"; name: string; load: () => Promise<RegisterCommand> };
+
+/**
+ * How much of the command registry this invocation needs. `args` is argv
+ * without the node and script paths.
+ *
+ * Only two shapes get less than everything, and only with Pro absent:
+ *
+ * - `ix --version` / `ix -V` alone: no command at all.
+ * - `ix <name> ...` where `<name>` is the first token and in the table: that
+ * command's module.
+ *
+ * Everything else registers all of them, because commander needs the whole
+ * list to answer it: root help (`ix`, `ix --help`, `ix help ...`), an unknown
+ * word ("did you mean"), a Pro command or stub, or an option before the
+ * command word. With Pro installed it is always everything: Pro registers
+ * against the same program after OSS and can collide with an OSS name
+ * (`patches`), where whichever registered first wins.
+ */
+export function planStartup(
+ args: readonly string[],
+ env: NodeJS.ProcessEnv = process.env,
+ isProAbsent: () => boolean = proIsAbsent,
+): StartupPlan {
+ if (env[LOAD_ALL_COMMANDS_ENV] === "1") return { kind: "all" };
+ const word = args[0];
+ if (word === undefined) return { kind: "all" };
+ const versionOnly = args.length === 1 && (word === "--version" || word === "-V");
+ const known = !NEEDS_EVERY_COMMAND.has(word) && Object.hasOwn(OSS_COMMAND_TABLE, word);
+ if (!versionOnly && !known) return { kind: "all" };
+ // Last: the only check here that touches the filesystem.
+ if (!isProAbsent()) return { kind: "all" };
+ return versionOnly ? { kind: "version" } : { kind: "command", name: word, load: OSS_COMMAND_TABLE[word] };
+}
+
+/**
+ * Register what `plan` calls for on `program`, with the same per-command setup
+ * `registerOssCommands()` applies. True when that was less than every command
+ * -- which `planStartup` only allows with Pro absent.
+ */
+export async function registerForPlan(program: Command, plan: StartupPlan): Promise<boolean> {
+ if (plan.kind === "all") {
+ const { registerOssCommands } = await import("./oss.js");
+ registerOssCommands(program);
+ return false;
+ }
+ if (plan.kind === "command") (await plan.load())(program);
+ applyOssSetup(program);
+ return true;
+}
diff --git a/ix-cli/src/cli/register/oss.ts b/ix-cli/src/cli/register/oss.ts
index 8588a31b..8f48ece8 100644
--- a/ix-cli/src/cli/register/oss.ts
+++ b/ix-cli/src/cli/register/oss.ts
@@ -41,137 +41,19 @@ import { registerMcpCommand } from "../commands/mcp.js";
import { registerContextCommand } from "../commands/context.js";
import { registerAroundCommand } from "../commands/around.js";
import { registerHookCommand } from "../commands/hook.js";
-import { validateCliOptions } from "../options.js";
-import { setPrettyJson } from "../format.js";
-import { setOutputShape } from "../output-shape.js";
-import {
- BUILT_IN_DEFAULT_FORMAT,
- DEFAULT_FORMAT_CHOICES,
- resolveDefaultFormat,
-} from "../default-format.js";
-import { readConfiguredFormat } from "../config.js";
-import { stderrDim } from "../stderr.js";
+import { applyOssSetup } from "./oss-setup.js";
-const PRO_COMMANDS: { name: string; desc: string }[] = [
- { name: "briefing", desc: "Session-resume briefing" },
- { name: "bug", desc: "Manage bugs" },
- { name: "decide", desc: "Record a design decision" },
- { name: "decisions", desc: "List recorded design decisions" },
- { name: "goal", desc: "Manage project goals" },
- { name: "goals", desc: "List all goals" },
- // `patches` is deliberately absent: ix-cli owns the real implementation
- // (commands/patches.ts, registered above). It sat in this list while never
- // being registered, so `ix patches` answered "requires Ix Pro" on OSS and
- // shadowed a working command — see #371.
- { name: "plan", desc: "Manage plans and plan tasks" },
- { name: "task", desc: "Manage tasks" },
- { name: "plans", desc: "List all plans" },
- { name: "tasks", desc: "List all tasks across plans" },
- { name: "truth", desc: "Manage project intents (truth)" },
- { name: "workflow", desc: "Attach, show, validate, or run staged workflows" },
-];
-
-const OPTION_CHOICES: Record<string, Record<string, string[]>> = {
- query: { depth: ["shallow", "standard", "deep"], format: ["text", "json"] },
- map: { format: [...DEFAULT_FORMAT_CHOICES, "silent"], sort: ["importance", "confidence", "size", "alpha"] },
- subsystems: { sort: ["importance", "confidence", "size", "alpha"] },
- savings: { model: ["opus", "sonnet", "haiku", "gpt-4o"] },
- context: { depth: ["compact", "standard", "full", "shallow", "deep"] },
- mcp: { tools: ["core", "all"] },
-};
-
-/**
- * Every command this file registered, so the preAction hook below can tell an
- * OSS option from a Pro one. Pro commands are registered later, against the
- * same root program, from a package this repo cannot see -- so their option
- * domains are not ours to infer.
- */
-const ossCommands = new WeakSet<Command>();
-
-function configureOssOptions(root: Command): void {
- const { format: defaultFormat, ignored } = resolveDefaultFormat(
- process.env,
- // Never let an unreadable or half-written config.yaml stop the CLI from
- // registering its commands: a config that does not parse is reported by the
- // command that needs it (ConfigParseError), not here. And no full parse for
- // one scalar on every invocation, `--version` included.
- () => { try { return readConfiguredFormat(); } catch { return undefined; } },
- );
-
- // Only where a person will read it: an agent captures stderr, and one more
- // line at the top of its tool result is exactly what this change is for.
- if (ignored && process.stderr.isTTY) {
- stderrDim(
- `Ignoring ${ignored.source}=${ignored.value}: not one of ` +
- `${DEFAULT_FORMAT_CHOICES.join(", ")}. Using ${defaultFormat}.`
- );
- }
-
- const visit = (command: Command): void => {
- ossCommands.add(command);
- const commandChoices = OPTION_CHOICES[command.name()] ?? {};
- let rendersRows = false;
- let rendersJson = false;
- for (const option of command.options) {
- const choices = commandChoices[option.attributeName()]
- ?? (option.long === "--format" ? [...DEFAULT_FORMAT_CHOICES] : undefined);
- if (choices) option.choices(choices);
- applyDefaultFormat(command, option, choices, defaultFormat);
- if (option.long === "--format") rendersRows = true;
- if (option.long === "--format" && (choices ?? []).includes("json")) rendersJson = true;
- }
- // Declared here rather than 32 times by hand, and only where it means
- // something: a command with no `--format json` has no JSON to shape.
- if (rendersJson && !command.options.some((option) => option.long === "--pretty")) {
- command.option("--pretty", "Indent JSON output (the default only when stdout is a terminal)");
- }
- // Declared here rather than on 33 commands by hand, and only where there
- // is an answer to shape. A command with no `--format` prints a status
- // line or nothing.
- if (rendersRows) {
- if (!command.options.some((option) => option.long === "--quiet")) {
- command.option("--quiet", "Drop headers, section titles and advisory hints");
- }
- if (!command.options.some((option) => option.long === "--fields")) {
- command.option("--fields <list>", "Keep only these fields on each row, in this order (e.g. name,path,lines)");
- }
- }
- for (const child of command.commands) visit(child);
- };
- visit(root);
-}
+export { registerProStubs } from "./pro-stubs.js";
/**
- * Point a `--format` option at the configured default.
+ * Register every OSS command on `program`, then the setup they share.
*
- * Only an option still sitting on the built-in `text` is moved: a command that
- * declares a different default has a reason for it, and `ix config set format`
- * is not an instruction to override it. The default must also be a format that
- * command accepts — `query` renders text and json only, so `IX_FORMAT=llm`
- * leaves it where it is rather than handing the renderer a format it has no
- * branch for.
+ * A command added here must also go into `OSS_COMMAND_TABLE`
+ * (`register/oss-table.ts`), which the CLI uses to load only the command being
+ * run. One that is missing still works -- the CLI falls back to this function
+ * for any name the table does not know -- but it fails a test, so it gets
+ * added rather than quietly paying for all of the others on every call.
*/
-function applyDefaultFormat(
- command: Command,
- option: Command["options"][number],
- choices: string[] | undefined,
- defaultFormat: string,
-): void {
- if (option.long !== "--format") return;
- if (defaultFormat === BUILT_IN_DEFAULT_FORMAT) return;
- if (option.defaultValue !== BUILT_IN_DEFAULT_FORMAT) return;
- if (!choices?.includes(defaultFormat)) return;
-
- option.default(defaultFormat);
- // `.option()` copies the default into the command's option values as it
- // registers, so moving the Option's default afterwards changes the help text
- // and nothing else. The stored value has to be moved with it -- and only
- // while it is still the default, which at registration time it always is.
- if (command.getOptionValueSource(option.attributeName()) === "default") {
- command.setOptionValueWithSource(option.attributeName(), defaultFormat, "default");
- }
-}
-
export function registerOssCommands(program: Command): void {
registerQueryCommand(program);
registerIngestCommand(program);
@@ -214,49 +96,6 @@ export function registerOssCommands(program: Command): void {
registerAroundCommand(program);
registerHookCommand(program);
- configureOssOptions(program);
-
- program.hook("preAction", (_thisCommand, actionCommand) => {
- // Before anything prints. All three are properties of the run, not of a
- // payload, so the renderers read them from one place rather than every
- // signature growing parameters it only forwards.
- const opts = actionCommand.opts();
- setPrettyJson(opts.pretty === true);
- setOutputShape({ quiet: opts.quiet === true, fields: typeof opts.fields === "string" ? opts.fields : undefined });
-
- // OSS commands only. The rules below read an option's *shape* -- `<n>`
- // means a non-negative integer, `--min-confidence` means 0..1 -- which is
- // a claim about commands whose declarations live in this repo. A Pro
- // command declaring `--threshold <n>` for a float would be rejected by a
- // rule its author never opted into, and no test here could catch it.
- if (!ossCommands.has(actionCommand)) return;
- validateCliOptions(actionCommand);
- });
+ applyOssSetup(program);
}
-export function registerProStubs(program: Command): void {
- const registered = new Set(program.commands.map((c: Command) => c.name()));
- for (const { name, desc } of PRO_COMMANDS) {
- if (registered.has(name)) continue;
- const stub = program
- .command(name)
- .description(desc)
- // Swallow whatever the caller passed. `allowUnknownOption` alone only
- // covers flags; commander still rejects excess *operands*, and it does so
- // before the action runs. So `ix bug` reached this message but
- // `ix bug create "title" --affects Entity` — the form the docs and every
- // agent actually use — died with "too many arguments for 'bug'" and never
- // said anything about Pro. The subcommand and its arguments are
- // deliberately ignored: the only thing worth saying here is that the
- // whole command needs Pro.
- .argument("[args...]")
- .allowUnknownOption(true)
- .allowExcessArguments(true)
- .action(() => {
- console.error(`The '${name}' command requires Ix Pro.`);
- console.error(`Install @ix/pro to enable premium features.`);
- process.exitCode = 1;
- });
- (stub as any).hidden = true;
- }
-}
diff --git a/ix-cli/src/cli/register/pro-loader.ts b/ix-cli/src/cli/register/pro-loader.ts
index 96ec0b95..af737f2f 100644
--- a/ix-cli/src/cli/register/pro-loader.ts
+++ b/ix-cli/src/cli/register/pro-loader.ts
@@ -19,6 +19,21 @@ function proPackageIsAbsent(): boolean {
}
}
+/**
+ * True exactly when `tryLoadProCommands` would return false without loading
+ * anything: neither `@ix/pro/register` nor the package itself resolves. An
+ * installed-but-broken Pro counts as present, so a caller that skips the
+ * loader on this answer still leaves the broken case to the loader's error.
+ */
+export function proIsAbsent(): boolean {
+ try {
+ import.meta.resolve("@ix/pro/register");
+ return false;
+ } catch {
+ return proPackageIsAbsent();
+ }
+}
+
export async function tryLoadProCommands(program: Command): Promise<boolean> {
let specifier: string;
try {
diff --git a/ix-cli/src/cli/register/pro-stubs.ts b/ix-cli/src/cli/register/pro-stubs.ts
new file mode 100644
index 00000000..725bf960
--- /dev/null
+++ b/ix-cli/src/cli/register/pro-stubs.ts
@@ -0,0 +1,50 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import type { Command } from "commander";
+
+const PRO_COMMANDS: { name: string; desc: string }[] = [
+ { name: "briefing", desc: "Session-resume briefing" },
+ { name: "bug", desc: "Manage bugs" },
+ { name: "decide", desc: "Record a design decision" },
+ { name: "decisions", desc: "List recorded design decisions" },
+ { name: "goal", desc: "Manage project goals" },
+ { name: "goals", desc: "List all goals" },
+ // `patches` is deliberately absent: ix-cli owns the real implementation
+ // (commands/patches.ts, registered by `registerOssCommands` in oss.ts and
+ // listed in oss-table.ts). It sat in this list while never
+ // being registered, so `ix patches` answered "requires Ix Pro" on OSS and
+ // shadowed a working command — see #371.
+ { name: "plan", desc: "Manage plans and plan tasks" },
+ { name: "task", desc: "Manage tasks" },
+ { name: "plans", desc: "List all plans" },
+ { name: "tasks", desc: "List all tasks across plans" },
+ { name: "truth", desc: "Manage project intents (truth)" },
+ { name: "workflow", desc: "Attach, show, validate, or run staged workflows" },
+];
+
+export function registerProStubs(program: Command): void {
+ const registered = new Set(program.commands.map((c: Command) => c.name()));
+ for (const { name, desc } of PRO_COMMANDS) {
+ if (registered.has(name)) continue;
+ const stub = program
+ .command(name)
+ .description(desc)
+ // Swallow whatever the caller passed. `allowUnknownOption` alone only
+ // covers flags; commander still rejects excess *operands*, and it does so
+ // before the action runs. So `ix bug` reached this message but
+ // `ix bug create "title" --affects Entity` — the form the docs and every
+ // agent actually use — died with "too many arguments for 'bug'" and never
+ // said anything about Pro. The subcommand and its arguments are
+ // deliberately ignored: the only thing worth saying here is that the
+ // whole command needs Pro.
+ .argument("[args...]")
+ .allowUnknownOption(true)
+ .allowExcessArguments(true)
+ .action(() => {
+ console.error(`The '${name}' command requires Ix Pro.`);
+ console.error(`Install @ix/pro to enable premium features.`);
+ process.exitCode = 1;
+ });
+ (stub as any).hidden = true;
+ }
+}
diff --git a/ix-cli/src/cli/run-cli.ts b/ix-cli/src/cli/run-cli.ts
index 6e90ba69..832bb054 100644
--- a/ix-cli/src/cli/run-cli.ts
+++ b/ix-cli/src/cli/run-cli.ts
@@ -3,13 +3,15 @@
// 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.
+// Which command modules load at all is `planStartup`'s call
+// (`register/oss-table.ts`): usually just the one being run.
import { Command } from "commander";
-import { registerOssCommands, registerProStubs } from "./register/oss.js";
+import { registerProStubs } from "./register/pro-stubs.js";
+import { planStartup, registerForPlan } from "./register/oss-table.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";
@@ -63,7 +65,9 @@ program
// Start with OSS-only help; updated after Pro probe.
program.helpInformation = () => buildHelpText();
-registerOssCommands(program);
+// Every OSS command, or only the one this invocation runs. The second happens
+// only with Pro absent, so `lazy` also means there is no Pro to load.
+const lazy = await registerForPlan(program, planStartup(process.argv.slice(2)));
(async () => {
const ossCmdNames = new Set(program.commands.map((c: Command) => c.name()));
@@ -79,7 +83,7 @@ registerOssCommands(program);
// registers.
const isHook = process.argv[2] === "hook";
try {
- if (!isHook) proLoaded = await tryLoadProCommands(program);
+ if (!isHook && !lazy) proLoaded = await tryLoadProCommands(program);
} catch (err) {
if (!isRepairInvocation(process.argv)) {
renderCliError(err, debug, safeEndpoint()); // exits 1
@@ -107,14 +111,17 @@ registerOssCommands(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.
+ // `updateCheckEnabled` is false whenever stderr is not a terminal, which is
+ // every agent and hook call, so only a person's pays for loading it.
const args = process.argv.slice(2);
- if (updateCheckEnabled(args, process.env, stderrIsTerminal())) {
+ const updates = stderrIsTerminal() ? await import("./commands/upgrade.js") : undefined;
+ if (updates?.updateCheckEnabled(args, process.env, true)) {
// 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(() => {});
+ updates.checkForUpdate().catch(() => {});
}
// parseAsync (not parse) so rejections from async action handlers surface
diff --git a/skills/ix/references/commands.md b/skills/ix/references/commands.md
index 8e4273a6..53143731 100644
--- a/skills/ix/references/commands.md
+++ b/skills/ix/references/commands.md
@@ -214,11 +214,18 @@ ix inventory --kind function --path auth.py
degraded graph.
- **The OSS↔Pro command boundary is derived at runtime, not declared.**
- `run-cli.ts` (which `main.ts` loads) snapshots `ossCmdNames` immediately after `registerOssCommands()`;
- the Pro probe (`tryLoadProCommands`) then diffs whatever commands exist
- against that set to decide which count as "Pro". Consequences:
+ `run-cli.ts` (which `main.ts` loads) snapshots `ossCmdNames` immediately
+ after registering the OSS commands; the Pro probe (`tryLoadProCommands`)
+ then diffs whatever commands exist against that set to decide which count
+ as "Pro". Consequences:
- Adding a `register*Command` call in `oss.ts` silently reclassifies that
command as OSS — it vanishes from the Pro help diff.
+ - A new OSS command also needs an entry in `OSS_COMMAND_TABLE`
+ (`register/oss-table.ts`): with Pro absent, `run-cli.ts` loads only the
+ table's module for the command being run. Without the entry the command
+ still works (it takes the full path), but `startup-fast-path.test.ts`
+ fails until it is added. The shared per-command setup is in
+ `register/oss-setup.ts`.
- Removing one from `oss.ts` makes Pro own it, or — without the license — a
Pro stub replaces it (stubs skip any name already registered, so an OSS
command left in place blocks its stub).
@@ -226,7 +233,8 @@ ix inventory --kind function --path auth.py
and MUST be awaited; skipping the await makes every `ix <pro-cmd>` fail
with "unknown command".
- Real example: `registerPatchesCommand` was defined but never called in
- `oss.ts`, so a `patches` entry in `PRO_COMMANDS` shadowed it and `ix
+ `oss.ts`, so a `patches` entry in `PRO_COMMANDS` (now in
+ `register/pro-stubs.ts`) shadowed it and `ix
patches` answered "requires Ix Pro" (#371). #390 wired the call in and
dropped the stub, so `ix patches` is an OSS command today.