Skip to content

armgit / Ix

Public Imported from GitHub
0

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

fix(config): loud parse errors, no lost registrations, one parse per process (CL-18)

KageBinary8de7236f1c13
diff --git a/docs-site/src/content/docs/reference/commands.md b/docs-site/src/content/docs/reference/commands.md
index 23ccc152..adfdacf6 100644
--- a/docs-site/src/content/docs/reference/commands.md
+++ b/docs-site/src/content/docs/reference/commands.md
@@ -91,6 +91,7 @@ before it exits: `ix map` re-ingests the workspace, and so does `ix ingest` when
| `ix view` | Opens the [Compass](/guides/compass/) visualizer |
| `ix mcp` | Runs the [MCP server](/integrations/mcp/). `ix mcp install` registers it with your clients |
| `ix config show` / `get` / `set` | Reads and writes [configuration](/reference/configuration/) |
+| `ix config prune` | Removes registered workspaces whose directory no longer exists (`--dry-run` lists them) |
| `ix savings` | Reports tokens saved against reading files directly. `--detail` breaks it down by command |
| `ix savings reset` | Clears the saved totals. Can't be undone |
| `ix help [topic]` | Help on a command, or the `workflows` and `advanced` topics |
diff --git a/ix-cli/src/cli/__tests__/config-integrity.test.ts b/ix-cli/src/cli/__tests__/config-integrity.test.ts
new file mode 100644
index 00000000..a6ce3cda
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/config-integrity.test.ts
@@ -0,0 +1,207 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { execFile } from "node:child_process";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { promisify } from "node:util";
+
+import { Command } from "commander";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { parse } from "yaml";
+
+/**
+ * CL-18: a config.yaml that did not parse was silently replaced by defaults;
+ * parallel registrations each renamed their own copy over the others' and kept
+ * one or two of eight; `ix config show` printed nested credentials; and every
+ * load re-parsed the file.
+ */
+
+const execFileAsync = promisify(execFile);
+const CLI_ROOT = resolve(fileURLToPath(new URL("../../..", import.meta.url)));
+const TSX = join(CLI_ROOT, "node_modules", ".bin", "tsx");
+const BOOTSTRAP = join(CLI_ROOT, "src", "cli", "bootstrap.ts");
+
+let home: string;
+let saved: string | undefined;
+
+beforeEach(() => {
+ vi.resetModules();
+ home = mkdtempSync(join(tmpdir(), "ix-cfg-"));
+ saved = process.env.IX_HOME;
+ process.env.IX_HOME = home;
+});
+
+afterEach(() => {
+ if (saved === undefined) delete process.env.IX_HOME;
+ else process.env.IX_HOME = saved;
+ vi.restoreAllMocks();
+ rmSync(home, { recursive: true, force: true });
+});
+
+const configPath = () => join(home, "config.yaml");
+
+describe("parallel registrations", () => {
+ it.skipIf(process.platform === "win32")("8 processes registering 8 repositories at once keep all 8", async () => {
+ const script = join(home, "register.mts");
+ writeFileSync(script, `import { ensureWorkspaceRegistered } from ${JSON.stringify(BOOTSTRAP)};\nensureWorkspaceRegistered(process.argv[2]);\n`);
+ for (let trial = 0; trial < 2; trial++) {
+ rmSync(configPath(), { force: true });
+ const dirs = Array.from({ length: 8 }, (_, i) => {
+ const d = join(home, `t${trial}-repo${i}`);
+ mkdirSync(d, { recursive: true });
+ return d;
+ });
+ await Promise.all(dirs.map((d) =>
+ execFileAsync(TSX, [script, d], { env: { ...process.env, IX_HOME: home, IX_LOCK_DIR: join(home, "locks") } })));
+ const registered = (parse(readFileSync(configPath(), "utf8")).workspaces ?? []).map((w: { root_path: string }) => w.root_path);
+ expect(registered.sort()).toEqual(dirs.sort());
+ }
+ }, 60_000);
+});
+
+describe("a config that does not parse", () => {
+ it("throws ConfigParseError naming the file, rather than answering defaults", async () => {
+ writeFileSync(configPath(), "endpoint: [unclosed\nworkspaces:\n - x\n");
+ const { loadConfig, ConfigParseError } = await import("../config.js");
+ expect(() => loadConfig()).toThrow(ConfigParseError);
+ expect(() => loadConfig()).toThrow(configPath());
+ });
+
+ it("a top level that is not a mapping is refused too; an empty file is defaults", async () => {
+ const { loadConfig, ConfigParseError, resetConfigMemo } = await import("../config.js");
+ writeFileSync(configPath(), "- a\n- b\n");
+ expect(() => loadConfig()).toThrow(ConfigParseError);
+ resetConfigMemo();
+ writeFileSync(configPath(), "");
+ expect(loadConfig().endpoint).toBe("http://localhost:8090");
+ });
+
+ it("the error boundary prints the path and the code, and exits 1", async () => {
+ writeFileSync(configPath(), "endpoint: [unclosed\n");
+ const { loadConfig } = await import("../config.js");
+ const { renderCliError } = await import("../errors.js");
+ const lines: string[] = [];
+ vi.spyOn(console, "error").mockImplementation((...a: unknown[]) => { lines.push(a.join(" ")); });
+ vi.spyOn(process.stdout, "write").mockImplementation((s: string | Uint8Array) => { lines.push(String(s)); return true; });
+ vi.spyOn(process, "exit").mockImplementation(((code?: number) => { throw new Error(`exit ${code}`); }) as never);
+ let err: unknown;
+ try { loadConfig(); } catch (e) { err = e; }
+ expect(() => renderCliError(err)).toThrow("exit 1");
+ expect(lines.join("\n")).toContain(configPath());
+ expect(lines.join("\n")).toMatch(/not valid YAML/);
+ });
+
+ it("saveConfig still refuses to overwrite it", async () => {
+ writeFileSync(configPath(), "endpoint: [unclosed\n");
+ const { saveConfig } = await import("../config.js");
+ expect(() => saveConfig({ endpoint: "http://localhost:8090", format: "text" })).toThrow(/not valid YAML/);
+ expect(readFileSync(configPath(), "utf8")).toBe("endpoint: [unclosed\n");
+ });
+});
+
+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");
+ const first = loadConfig();
+ 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
+ const parsesBefore = parseSpy.mock.calls.length;
+ loadConfig();
+ loadConfig();
+ expect(parseSpy.mock.calls.length).toBe(parsesBefore);
+
+ saveConfig({ ...second, format: "json" });
+ expect(loadConfig().format).toBe("json");
+
+ // 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");
+ });
+});
+
+describe("readConfiguredFormat, for command registration", () => {
+ it("reads the top-level format line without parsing the file", async () => {
+ const { readConfiguredFormat, resetConfigMemo } = await import("../config.js");
+ const cases: Array<[string, string | undefined]> = [
+ ["format: llm\n", "llm"],
+ ["endpoint: x\nformat: \"json\" # chosen\n", "json"],
+ ["format: 'text'\n", "text"],
+ ["endpoint: x\n", undefined],
+ ["nested:\n format: llm\n", undefined],
+ // Broken elsewhere: registration still gets its answer; the command reports the file.
+ ["format: json\nendpoint: [unclosed\n", "json"],
+ ];
+ for (const [text, want] of cases) {
+ resetConfigMemo();
+ writeFileSync(configPath(), text);
+ expect(readConfiguredFormat(), text).toBe(want);
+ }
+ rmSync(configPath());
+ expect(readConfiguredFormat()).toBeUndefined();
+ });
+});
+
+describe("ix config", () => {
+ async function run(...args: string[]): Promise<{ out: string; code: number | string | undefined }> {
+ const out: string[] = [];
+ vi.spyOn(console, "log").mockImplementation((...a: unknown[]) => { out.push(a.join(" ")); });
+ vi.spyOn(console, "error").mockImplementation((...a: unknown[]) => { out.push(a.join(" ")); });
+ const savedCode = process.exitCode;
+ process.exitCode = undefined;
+ const { registerConfigCommand } = await import("../commands/config.js");
+ const program = new Command().exitOverride();
+ registerConfigCommand(program);
+ await program.parseAsync(["config", ...args], { from: "user" });
+ const code = process.exitCode;
+ process.exitCode = savedCode;
+ return { out: out.join("\n"), code };
+ }
+
+ it("show redacts tokens and does not dump nested credentials", async () => {
+ writeFileSync(configPath(),
+ "endpoint: http://localhost:8090\nformat: text\nauth:\n local_token: abc123secretvalue\n" +
+ "instances:\n prod:\n jwt: eyJhbGciOi\n refresh_token: rt-123\n");
+ const { out } = await run("show");
+ expect(out).toContain("auth.local_token");
+ expect(out).toContain("(redacted)");
+ expect(out).not.toContain("abc123secretvalue");
+ expect(out).not.toContain("eyJhbGciOi");
+ expect(out).not.toContain("rt-123");
+ });
+
+ it("set refuses workspaces and a non-URL endpoint, and accepts a URL", async () => {
+ writeFileSync(configPath(), "endpoint: http://localhost:8090\nformat: text\nworkspaces:\n - workspace_id: \"a\"\n workspace_name: a\n root_path: /a\n default: true\n");
+ expect((await run("set", "workspaces", "oops")).code).toBe(1);
+ expect((await run("set", "endpoint", "localhost:8090")).code).toBe(1);
+ expect((await run("set", "endpoint", "ftp://x")).code).toBe(1);
+ expect(parse(readFileSync(configPath(), "utf8")).workspaces).toHaveLength(1);
+ expect((await run("set", "endpoint", "http://127.0.0.1:8190")).code).toBeUndefined();
+ expect(parse(readFileSync(configPath(), "utf8")).endpoint).toBe("http://127.0.0.1:8190");
+ });
+
+ it("prune drops roots that no longer exist, keeps a default, and --dry-run changes nothing", async () => {
+ const live = join(home, "live");
+ mkdirSync(live);
+ writeFileSync(configPath(),
+ "endpoint: http://localhost:8090\nformat: text\nworkspaces:\n" +
+ ` - workspace_id: "gone"\n workspace_name: gone\n root_path: ${join(home, "gone")}\n default: true\n` +
+ ` - workspace_id: "live"\n workspace_name: live\n root_path: ${live}\n default: false\n`);
+ const before = readFileSync(configPath(), "utf8");
+ expect((await run("prune", "--dry-run")).out).toMatch(/would remove gone/);
+ expect(readFileSync(configPath(), "utf8")).toBe(before);
+
+ expect((await run("prune")).out).toMatch(/removed gone/);
+ const after = parse(readFileSync(configPath(), "utf8")).workspaces;
+ expect(after).toEqual([{ workspace_id: "live", workspace_name: "live", root_path: live, default: true }]);
+ });
+});
diff --git a/ix-cli/src/cli/bootstrap.ts b/ix-cli/src/cli/bootstrap.ts
index 25906af4..68df0b96 100644
--- a/ix-cli/src/cli/bootstrap.ts
+++ b/ix-cli/src/cli/bootstrap.ts
@@ -7,7 +7,7 @@ import { execFileSync } from "node:child_process";
import chalk from "chalk";
import { createClient } from "../client/factory.js";
import { renderBanner } from "./banner.js";
-import { canonicalWorkspacePath, getEndpoint, gitRootFor, loadConfig, loadWorkspaces, saveConfig, findWorkspaceForCwd, type WorkspaceConfig } from "./config.js";
+import { canonicalWorkspacePath, getEndpoint, gitRootFor, loadConfig, loadWorkspaces, findWorkspaceForCwd, updateConfig, type IxConfig, type WorkspaceConfig } from "./config.js";
import { WorkspaceNotMappedError, workspaceNotMappedHint } from "./errors.js";
import { ixHome } from "./ix-home.js";
import { stderr } from "./stderr.js";
@@ -79,7 +79,24 @@ interface WorkspaceState { ws: WorkspaceConfig; created: boolean; migrated: bool
*/
function getOrCreateWorkspace(cwd: string): WorkspaceState {
const rootPath = canonicalWorkspacePath(resolve(cwd));
- const config = loadConfig();
+ // The common case, already registered under its path id, needs no write and
+ // so no lock.
+ const known = (loadConfig().workspaces ?? []).find(w => w.root_path === rootPath && w.workspace_id === workspaceIdForPath(rootPath));
+ if (known) {
+ const previousWorkspaceId = migratedRootsThisRun.get(rootPath);
+ return { ws: known, created: false, migrated: previousWorkspaceId !== undefined, previousWorkspaceId };
+ }
+ // Read, change and write under the config lock, so parallel registrations
+ // each see the one before (see updateConfig).
+ return updateConfig((config) => {
+ let save: typeof config | undefined;
+ const state = registerIn(config, rootPath, () => { save = config; });
+ return { save, result: state };
+ });
+}
+
+/** The registration itself, on a config read under the lock; `changed` marks it for saving. */
+function registerIn(config: IxConfig, rootPath: string, changed: () => void): WorkspaceState {
const pathId = workspaceIdForPath(rootPath);
const existing = (config.workspaces ?? []).find(w => canonicalWorkspacePath(w.root_path) === rootPath);
if (existing) {
@@ -92,11 +109,11 @@ function getOrCreateWorkspace(cwd: string): WorkspaceState {
if (existing.workspace_id !== pathId) {
const previousWorkspaceId = existing.workspace_id;
existing.workspace_id = pathId;
- saveConfig(config);
+ changed();
migratedRootsThisRun.set(rootPath, previousWorkspaceId);
return { ws: existing, created: false, migrated: true, previousWorkspaceId };
}
- if (pathChanged) saveConfig(config);
+ if (pathChanged) changed();
const previousWorkspaceId = migratedRootsThisRun.get(rootPath);
return { ws: existing, created: false, migrated: previousWorkspaceId !== undefined, previousWorkspaceId };
}
@@ -113,7 +130,7 @@ function getOrCreateWorkspace(cwd: string): WorkspaceState {
default: !hasDefault,
};
config.workspaces = [...workspaces, ws];
- saveConfig(config);
+ changed();
return { ws, created: true, migrated: false };
}
diff --git a/ix-cli/src/cli/commands/config.ts b/ix-cli/src/cli/commands/config.ts
index 4534a0b0..425714b9 100644
--- a/ix-cli/src/cli/commands/config.ts
+++ b/ix-cli/src/cli/commands/config.ts
@@ -2,7 +2,8 @@
import type { Command } from "commander";
import chalk from "chalk";
-import { loadConfig, saveConfig } from "../config.js";
+import { existsSync } from "node:fs";
+import { loadConfig, updateConfig, type WorkspaceConfig } from "../config.js";
import {
BUILT_IN_DEFAULT_FORMAT,
DEFAULT_FORMAT_CHOICES,
@@ -21,6 +22,35 @@ function resolvePath(obj: any, key: string): [any, string] {
return [cur, parts[parts.length - 1]];
}
+/** Keys whose values `ix config show` never prints: the config holds credentials. */
+const SECRET_KEY = /token|secret|jwt|password/i;
+
+/** A value as `show` prints it: secrets as a marker, never their text. */
+export function displayValue(key: string, value: unknown): string {
+ return SECRET_KEY.test(key) ? "(redacted)" : String(value);
+}
+
+/**
+ * Why `ix config set <key> <value>` must refuse, or undefined to allow it.
+ * `workspaces` is a list `ix map` maintains; a string written over it lost
+ * every registration. `endpoint` must be a URL the client can call.
+ */
+export function rejectSet(key: string, value: string): string | undefined {
+ const top = key.split(".")[0];
+ if (top === "workspaces") return "workspaces is managed by `ix map` and `ix config prune`; it cannot be set by hand.";
+ if (key === "endpoint") {
+ let url: URL;
+ try { url = new URL(value); } catch { return `Not a URL: ${value}`; }
+ if (url.protocol !== "http:" && url.protocol !== "https:") return `The endpoint must be http:// or https://, not ${url.protocol}`;
+ }
+ return undefined;
+}
+
+/** Registered workspaces whose root no longer exists on disk. */
+export function staleWorkspaces(workspaces: readonly WorkspaceConfig[], exists: (p: string) => boolean = existsSync): WorkspaceConfig[] {
+ return workspaces.filter((w) => !exists(w.root_path));
+}
+
export function registerConfigCommand(program: Command): void {
const config = program
.command("config")
@@ -47,10 +77,13 @@ export function registerConfigCommand(program: Command): void {
if (known.has(k)) continue;
if (typeof v === "object" && v !== null) {
for (const [k2, v2] of Object.entries(v as object)) {
- console.log(` ${k}.${k2} ${chalk.cyan(String(v2))}`);
+ // Nested objects (Pro's instances) are summarised, not dumped: they
+ // carry tunnel JWTs and refresh tokens.
+ const shown = typeof v2 === "object" && v2 !== null ? "(…)" : displayValue(`${k}.${k2}`, v2);
+ console.log(` ${k}.${k2} ${chalk.cyan(shown)}`);
}
} else {
- console.log(` ${k} ${chalk.cyan(String(v))}`);
+ console.log(` ${k} ${chalk.cyan(displayValue(k, v))}`);
}
}
});
@@ -83,11 +116,45 @@ export function registerConfigCommand(program: Command): void {
process.exitCode = 1;
return;
}
- const cfg = loadConfig() as any;
- const [obj, lastKey] = resolvePath(cfg, key);
- obj[lastKey] = value;
- saveConfig(cfg);
- console.log(chalk.green("✓") + ` ${key} = ${chalk.cyan(value)}`);
+ const refused = rejectSet(key, value);
+ if (refused) {
+ console.error(chalk.red(refused));
+ process.exitCode = 1;
+ return;
+ }
+ updateConfig((cfg) => {
+ const [obj, lastKey] = resolvePath(cfg, key);
+ obj[lastKey] = value;
+ return { save: cfg, result: undefined };
+ });
+ console.log(chalk.green("✓") + ` ${key} = ${chalk.cyan(displayValue(key, value))}`);
+ });
+
+ config
+ .command("prune")
+ .description("Remove registered workspaces whose directory no longer exists")
+ .option("--dry-run", "List what would be removed without changing anything")
+ .action((opts: { dryRun?: boolean }) => {
+ if (opts.dryRun) {
+ const stale = staleWorkspaces(loadConfig().workspaces ?? []);
+ if (stale.length === 0) console.log("No registered workspace is missing.");
+ for (const w of stale) console.log(`would remove ${w.workspace_name} ${chalk.dim(w.root_path)}`);
+ return;
+ }
+ const removed = updateConfig((cfg) => {
+ const stale = staleWorkspaces(cfg.workspaces ?? []);
+ if (stale.length === 0) return { result: stale };
+ const gone = new Set(stale);
+ const kept = (cfg.workspaces ?? []).filter((w) => !gone.has(w));
+ // Keep exactly one default when the default was among the removed.
+ if (kept.length > 0 && !kept.some((w) => w.default)) kept[0] = { ...kept[0]!, default: true };
+ return { save: { ...cfg, workspaces: kept }, result: stale };
+ });
+ if (removed.length === 0) console.log("No registered workspace is missing.");
+ for (const w of removed) console.log(`${chalk.green("✓")} removed ${w.workspace_name} ${chalk.dim(w.root_path)}`);
+ // Unregistering does not touch the backend: say so rather than imply the
+ // graphs went with the entries.
+ if (removed.length > 0) console.log(chalk.dim(" Their graphs stay in the backend."));
});
}
diff --git a/ix-cli/src/cli/config.ts b/ix-cli/src/cli/config.ts
index 05ad1604..d2c9c53a 100644
--- a/ix-cli/src/cli/config.ts
+++ b/ix-cli/src/cli/config.ts
@@ -1,6 +1,6 @@
// Copyright 2026 Ix Infrastructure Inc.
-import { readFileSync, writeFileSync, existsSync, rmSync, chmodSync, renameSync, realpathSync, mkdirSync } from "node:fs";
+import { readFileSync, writeFileSync, existsSync, rmSync, chmodSync, renameSync, realpathSync, mkdirSync, statSync } from "node:fs";
import { dirname, isAbsolute, join, relative, resolve as resolvePath, sep } from "node:path";
import { createHash, randomBytes } from "node:crypto";
import { execFileSync } from "node:child_process";
@@ -8,6 +8,7 @@ import { parse, stringify } from "yaml";
import { IxClient } from "../client/api.js";
import { ixHome } from "./ix-home.js";
import { isLocalEndpoint } from "./backend-version.js";
+import { acquireLockAt, namedLockPath } from "./single-flight.js";
/**
* The key of a project root's per-root state files. Canonical first: `ix
@@ -156,6 +157,27 @@ const defaultConfig: IxConfig = {
format: "text",
};
+/**
+ * config.yaml exists and does not parse. Thrown rather than answered with the
+ * defaults: falling back silently ran every command against the default
+ * endpoint with no workspaces, and the first registration then saved over the
+ * file. The error boundary prints the path and the parser's message.
+ */
+export class ConfigParseError extends Error {
+ constructor(readonly path: string, readonly detail: string) {
+ super(`${path} is not valid YAML: ${detail}`);
+ this.name = "ConfigParseError";
+ }
+}
+
+/**
+ * The last parse of config.yaml, keyed by the file's mtime and size. A command
+ * loads the config a dozen times or more, and with many workspaces each YAML
+ * parse costs milliseconds; the key catches a write by another process, and
+ * `saveConfig` drops it for this one.
+ */
+let configMemo: { path: string; mtimeMs: number; size: number; config: IxConfig } | undefined;
+
export function loadConfig(): IxConfig {
const configPath = join(ixHome(), "config.yaml");
// A copy, here and below: callers edit what they get back and save it.
@@ -163,21 +185,111 @@ export function loadConfig(): IxConfig {
// workspace into it, so every later load in the process that found no
// config file -- a fresh IX_HOME, a deleted file -- inherited workspaces
// that were never in either.
- if (!existsSync(configPath)) return { ...defaultConfig };
+ let stat: { mtimeMs: number; size: number };
try {
- const raw = readFileSync(configPath, "utf-8");
- const parsed = parse(raw) as Partial<IxConfig>;
- // Normalize workspace_id to a string. saveConfig quotes an all-digit path-hash
- // id, but a hand-edited or legacy unquoted value parses from YAML as a number,
- // which then silently breaks string id comparisons (e.g. migration detection
- // would re-key a workspace that is already on the correct id).
- if (Array.isArray(parsed.workspaces)) {
- parsed.workspaces = parsed.workspaces.map((w) => ({ ...w, workspace_id: String(w.workspace_id) }));
- }
- return { ...defaultConfig, ...parsed };
+ stat = statSync(configPath);
+ } catch {
+ return { ...defaultConfig };
+ }
+ if (configMemo && configMemo.path === configPath && configMemo.mtimeMs === stat.mtimeMs && configMemo.size === stat.size) {
+ return structuredClone(configMemo.config);
+ }
+ let raw: string;
+ try {
+ raw = readFileSync(configPath, "utf-8");
} catch {
return { ...defaultConfig };
}
+ let parsed: Partial<IxConfig> | null;
+ try {
+ parsed = parse(raw) as Partial<IxConfig> | null;
+ } catch (err) {
+ throw new ConfigParseError(configPath, (err instanceof Error ? err.message : String(err)).split("\n")[0]!);
+ }
+ if (parsed === null || parsed === undefined) parsed = {}; // an empty file
+ if (typeof parsed !== "object" || Array.isArray(parsed)) {
+ throw new ConfigParseError(configPath, "the top level is not a mapping of settings");
+ }
+ // Normalize workspace_id to a string. saveConfig quotes an all-digit path-hash
+ // id, but a hand-edited or legacy unquoted value parses from YAML as a number,
+ // which then silently breaks string id comparisons (e.g. migration detection
+ // would re-key a workspace that is already on the correct id).
+ if (Array.isArray(parsed.workspaces)) {
+ parsed.workspaces = parsed.workspaces.map((w) => ({ ...w, workspace_id: String(w.workspace_id) }));
+ }
+ const config = { ...defaultConfig, ...parsed };
+ configMemo = { path: configPath, mtimeMs: stat.mtimeMs, size: stat.size, config: structuredClone(config) };
+ return config;
+}
+
+/**
+ * The `format` setting alone, for command registration, which runs before
+ * anything else on every invocation -- `ix --version` included. A full parse
+ * of a config with a thousand workspaces is ~60 ms, all of it for one scalar
+ * that sits on its own top-level line, so this reads that line. A memoised
+ * parse is used when there is one. Undefined when the file or the key is
+ * missing or unreadable: registration never fails on the config.
+ */
+export function readConfiguredFormat(): string | undefined {
+ const configPath = join(ixHome(), "config.yaml");
+ if (configMemo?.path === configPath) {
+ try {
+ const st = statSync(configPath);
+ if (st.mtimeMs === configMemo.mtimeMs && st.size === configMemo.size) return configMemo.config.format;
+ } catch { return undefined; }
+ }
+ let raw: string;
+ try { raw = readFileSync(configPath, "utf-8"); } catch { return undefined; }
+ const m = /^format:[ \t]*(?:"([^"\n]*)"|'([^'\n]*)'|([^\s#]+))[ \t]*(?:#.*)?$/m.exec(raw);
+ return m ? (m[1] ?? m[2] ?? m[3]) : undefined;
+}
+
+/** Test hook: forget the memoised parse. */
+export function resetConfigMemo(): void {
+ configMemo = undefined;
+}
+
+/** How long a config write waits for another process's before going ahead anyway. */
+const CONFIG_LOCK_WAIT_MS = 5_000;
+
+/**
+ * Read config.yaml, apply `mutate`, and write it back, with no other Ix
+ * process writing it in between.
+ *
+ * `saveConfig` alone is atomic per write but last-writer-wins: eight `ix map`
+ * runs registering eight new repositories each read the file, each appended
+ * its own workspace, and each renamed its copy over the others' -- leaving one
+ * or two of the eight. Under the lock each one reads what the previous one
+ * wrote. The lock is the single-flight link lock, so a crashed holder is
+ * detected by its dead pid; past {@link CONFIG_LOCK_WAIT_MS} the write goes
+ * ahead unlocked rather than hang a command.
+ *
+ * `mutate` gets a fresh read, never the memoised one, and returns the config
+ * to save, or undefined to leave the file as it is.
+ */
+export function updateConfig<T>(mutate: (config: IxConfig) => { save?: IxConfig; result: T }): T {
+ const configPath = join(ixHome(), "config.yaml");
+ const lock = waitForLock(namedLockPath("config", configPath), `config write ${configPath}`);
+ try {
+ configMemo = undefined;
+ const { save, result } = mutate(loadConfig());
+ if (save) saveConfig(save);
+ return result;
+ } finally {
+ lock?.release();
+ }
+}
+
+function waitForLock(path: string, label: string): { release(): void } | null {
+ const deadline = Date.now() + CONFIG_LOCK_WAIT_MS;
+ const pause = new Int32Array(new SharedArrayBuffer(4));
+ for (;;) {
+ const handle = acquireLockAt(path, label);
+ if (handle) return handle;
+ if (Date.now() >= deadline) return null;
+ // A synchronous wait: registration runs inside synchronous callers.
+ Atomics.wait(pause, 0, 0, 5 + Math.floor(Math.random() * 20));
+ }
}
// Keys the OSS schema owns. For these, the in-memory `config` argument is
@@ -252,6 +364,7 @@ export function saveConfig(config: IxConfig): void {
} catch {
// chmod can fail on exotic filesystems; the temp's create-mode is the primary guard.
}
+ configMemo = undefined;
}
export function getEndpoint(): string {
@@ -287,21 +400,24 @@ export function storedLocalToken(): string | undefined {
export function ensureLocalToken(): string {
const existing = storedLocalToken();
if (existing) return existing;
- const config = loadConfig();
- const token = randomBytes(32).toString("hex");
- saveConfig({ ...config, auth: { ...config.auth, local_token: token } });
- return token;
+ return updateConfig((config) => {
+ const stored = config.auth?.local_token;
+ if (typeof stored === "string" && stored.trim()) return { result: stored.trim() };
+ const token = randomBytes(32).toString("hex");
+ return { save: { ...config, auth: { ...config.auth, local_token: token } }, result: token };
+ });
}
/** Forget the stored local token. */
export function clearLocalToken(): void {
- const config = loadConfig();
- if (!config.auth?.local_token) return;
- const { local_token: _dropped, ...rest } = config.auth;
- const next: IxConfig = { ...config };
- if (Object.keys(rest).length > 0) next.auth = rest;
- else delete next.auth;
- saveConfig(next);
+ updateConfig((config) => {
+ if (!config.auth?.local_token) return { result: undefined };
+ const { local_token: _dropped, ...rest } = config.auth;
+ const next: IxConfig = { ...config };
+ if (Object.keys(rest).length > 0) next.auth = rest;
+ else delete next.auth;
+ return { save: next, result: undefined };
+ });
}
// Kept for @ix/pro, which imports it. The factory itself is the synchronous
diff --git a/ix-cli/src/cli/errors.ts b/ix-cli/src/cli/errors.ts
index c7885179..894d61c7 100644
--- a/ix-cli/src/cli/errors.ts
+++ b/ix-cli/src/cli/errors.ts
@@ -325,6 +325,18 @@ export function backendUnreachableError(endpoint?: string): StructuredError {
};
}
+/**
+ * config.yaml does not parse. Every command reads it, so every command stops
+ * here, naming the file rather than quietly running on defaults.
+ */
+export function configParseError(path: string, detail: string): StructuredError {
+ return {
+ error: "config_parse_error",
+ message: `${path} is not valid YAML, so Ix will not run on a guess: ${detail}`,
+ next: `Fix the file, or move it aside to start from defaults (your workspace registrations are in it): mv ${path} ${path}.broken`,
+ };
+}
+
/**
* The backend answered 401 `local_token_required`: it was started with
* IX_LOCAL_TOKEN and this CLI sent no token, or a different one.
@@ -374,6 +386,13 @@ export function renderCliError(err: unknown, debug = false, endpoint?: string):
process.exit(1);
}
+ if (e?.name === "ConfigParseError") {
+ const broken = configParseError(e.path, e.detail);
+ if (!emitLlmError(broken.error, broken.message, broken.next)) renderStructuredError(broken);
+ if (debug) writeDebugDetail(err);
+ process.exit(1);
+ }
+
if (e?.name === "LocalTokenRequiredError") {
const refused = localTokenRequiredError(endpoint);
if (!emitLlmError(refused.error, refused.message, refused.next)) {
diff --git a/ix-cli/src/cli/register/oss.ts b/ix-cli/src/cli/register/oss.ts
index e8090f94..8588a31b 100644
--- a/ix-cli/src/cli/register/oss.ts
+++ b/ix-cli/src/cli/register/oss.ts
@@ -49,7 +49,7 @@ import {
DEFAULT_FORMAT_CHOICES,
resolveDefaultFormat,
} from "../default-format.js";
-import { loadConfig } from "../config.js";
+import { readConfiguredFormat } from "../config.js";
import { stderrDim } from "../stderr.js";
const PRO_COMMANDS: { name: string; desc: string }[] = [
@@ -92,9 +92,10 @@ 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; loadConfig already falls back to defaults on a
- // parse error, and this covers the rest (an unresolvable IX_HOME).
- () => { try { return loadConfig().format; } catch { return undefined; } },
+ // 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
diff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.md
index 1bd4f0a1..207e9db0 100644
--- a/skills/ix/references/flags.md
+++ b/skills/ix/references/flags.md
@@ -173,13 +173,13 @@ Show methods/functions that call the given symbol (cross-file).
Show or update Ix configuration.
-Subcommands: `show`, `get`, `set`.
+Subcommands: `show`, `get`, `set`, `prune`.
No flags.
#### `ix config show`
-Show current configuration.
+Show current configuration. Values of keys that look like credentials (`token`, `secret`, `jwt`, `password`) print as `(redacted)`.
No flags.
@@ -191,10 +191,18 @@ No flags.
#### `ix config set <key> <value>`
-Set a config value (e.g. ix config set user.name 'Alice').
+Set a config value (e.g. ix config set user.name 'Alice'). `endpoint` must be an `http://` or `https://` URL; `workspaces` cannot be set by hand.
No flags.
+#### `ix config prune`
+
+Remove registered workspaces whose directory no longer exists. Their graphs stay in the backend.
+
+| Flag | Value | Default | Effect |
+|---|---|---|---|
+| `--dry-run` | — | off | List what would be removed without changing anything |
+
### `ix conflicts`
List detected conflicts.