Skip to content

armgit / Ix

Public Imported from GitHub
0

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

fix(cli): doctor reports an unparseable config as a failing check

KageBinaryf4e886055125
diff --git a/ix-cli/src/cli/__tests__/doctor-config-broken.test.ts b/ix-cli/src/cli/__tests__/doctor-config-broken.test.ts
new file mode 100644
index 00000000..e33c7bff
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/doctor-config-broken.test.ts
@@ -0,0 +1,172 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Command } from "commander";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+// `ix doctor` with a $IX_HOME/config.yaml that does not parse. `loadConfig()`
+// throws ConfigParseError for that file (every other command stops on it), and
+// doctor used to stop on it too, before its own "Config file parses" check ran.
+// Nothing about the config layer is mocked here: the point is what the real
+// loadConfig does to doctor.
+
+const endpointsSeen: string[] = [];
+
+vi.mock("../../client/api.js", () => ({
+ IxClient: class {
+ constructor(readonly endpoint: string = "http://localhost:8090") {
+ endpointsSeen.push(endpoint);
+ }
+ async stats() { return { nodes: { total: 10 }, edges: { total: 20 } }; }
+ async conflicts() { return []; }
+ async fetchCapabilities() { return {}; }
+ async currentRevision() { return { rev: 1 }; }
+ },
+}));
+
+vi.mock("../resolve.js", async (orig) => ({
+ ...(await orig<typeof import("../resolve.js")>()),
+ resolveReadSystemId: async () => undefined,
+}));
+
+vi.mock("../remote.js", async (orig) => ({
+ ...(await orig<typeof import("../remote.js")>()),
+ isCloudReady: async () => false,
+}));
+
+// No docker inspect or socket connects: see doctor-stats-once.test.ts.
+vi.mock("../backend-status.js", async (orig) => ({
+ ...(await orig<typeof import("../backend-status.js")>()),
+ checkBackendImage: () => ({ kind: "docker-unavailable" as const }),
+ checkBackendSchema: async () => ({ ok: true as const }),
+ isNonStandardBackend: () => false,
+}));
+
+vi.mock("../commands/upgrade.js", async (orig) => ({
+ ...(await orig<typeof import("../commands/upgrade.js")>()),
+ readBackendHealth: async () => ({ status: "ok", schema_version: 3, database: "reachable" }),
+}));
+
+const BROKEN = "endpoint: [unclosed\nworkspaces:\n - workspace_id: abc\n";
+
+let savedEndpoint: string | undefined;
+let savedHome: string | undefined;
+let savedToken: string | undefined;
+let savedExitCode: number | string | undefined;
+let configPath: string;
+
+beforeEach(() => {
+ vi.resetModules();
+ endpointsSeen.length = 0;
+ savedEndpoint = process.env.IX_ENDPOINT;
+ process.env.IX_ENDPOINT = "http://127.0.0.1:9";
+ savedToken = process.env.IX_TOKEN;
+ delete process.env.IX_TOKEN;
+ savedHome = process.env.IX_HOME;
+ process.env.IX_HOME = mkdtempSync(join(tmpdir(), "ix-doctor-broken-"));
+ configPath = join(process.env.IX_HOME, "config.yaml");
+ writeFileSync(configPath, BROKEN);
+ savedExitCode = process.exitCode;
+ process.exitCode = undefined;
+});
+
+afterEach(() => {
+ if (savedEndpoint === undefined) delete process.env.IX_ENDPOINT;
+ else process.env.IX_ENDPOINT = savedEndpoint;
+ if (savedToken === undefined) delete process.env.IX_TOKEN;
+ else process.env.IX_TOKEN = savedToken;
+ rmSync(process.env.IX_HOME!, { recursive: true, force: true });
+ if (savedHome === undefined) delete process.env.IX_HOME;
+ else process.env.IX_HOME = savedHome;
+ process.exitCode = savedExitCode;
+});
+
+async function runDoctor(format: string): Promise<{ out: string[]; err: string[] }> {
+ const { registerDoctorCommand } = await import("../commands/doctor.js");
+ const program = new Command();
+ program.name("ix").exitOverride();
+ registerDoctorCommand(program);
+ const out: string[] = [];
+ const err: string[] = [];
+ const log = vi.spyOn(console, "log").mockImplementation((...args) => out.push(args.join(" ")));
+ const error = vi.spyOn(console, "error").mockImplementation((...args) => err.push(args.join(" ")));
+ const write = vi.spyOn(process.stdout, "write").mockImplementation((chunk: any) => { out.push(String(chunk)); return true; });
+ try {
+ await program.parseAsync(["doctor", "--format", format], { from: "user" });
+ } catch (e) {
+ // Doctor itself throwing is the bug: record it so the assertions see it.
+ err.push(`THREW: ${(e as Error)?.stack ?? String(e)}`);
+ } finally {
+ log.mockRestore();
+ error.mockRestore();
+ write.mockRestore();
+ }
+ return { out, err };
+}
+
+const escapedPath = () => configPath.replace(/\\/g, "\\\\");
+
+describe("ix doctor with a config.yaml that does not parse", () => {
+ it("still runs the other checks, fails 'Config file parses' naming the file, and exits 1", async () => {
+ const { out, err } = await runDoctor("llm");
+ const all = [...out, ...err].join("\n");
+
+ expect(err.join("\n")).not.toContain("THREW");
+ expect(out[0]).toContain("healthy=false");
+ expect(process.exitCode).toBe(1);
+
+ const configLine = out.find((l) => l.includes('name="Config file parses"'));
+ expect(configLine).toMatch(/status=fail/);
+ expect(configLine).toContain(escapedPath());
+ // What is true: other commands stop on this file. Not "runs on defaults".
+ expect(configLine).toMatch(/refuse to run until it is fixed/);
+ expect(all).not.toMatch(/runs on defaults/);
+ // The parser's message, first line only, and no stack trace anywhere.
+ expect(configLine).toMatch(/does not parse, so .*until it is fixed: \S/);
+ expect(all).not.toMatch(/\n\s+at\s/);
+ expect(all).not.toMatch(/ConfigParseError/);
+
+ // The checks that do not need the config ran and answered.
+ expect(out).toContain('check name="Server reachable" status=ok detail="http://127.0.0.1:9 → ok"');
+ expect(out.find((l) => l.includes('name="Database reachable"'))).toMatch(/status=ok/);
+ expect(out.find((l) => l.includes('name="No unresolved conflicts"'))).toMatch(/status=ok detail=clean/);
+
+ // The ones that do say they were not checked, rather than guessing.
+ for (const name of [
+ "Workspace for this directory",
+ "No stray nested workspaces",
+ "Completed map for this workspace",
+ "Graph has nodes",
+ "Graph has edges",
+ ]) {
+ expect(out).toContain(`check name="${name}" status=ok detail="not checked: config.yaml does not parse"`);
+ }
+ });
+
+ it("falls back to the default endpoint when IX_ENDPOINT is unset", async () => {
+ delete process.env.IX_ENDPOINT;
+
+ const { out, err } = await runDoctor("llm");
+
+ expect(err.join("\n")).not.toContain("THREW");
+ expect(endpointsSeen).toContain("http://localhost:8090");
+ expect(out).toContain('check name="Server reachable" status=ok detail="http://localhost:8090 → ok"');
+ expect(process.exitCode).toBe(1);
+ });
+
+ it("keeps the JSON shape and adds the failing check to it", async () => {
+ const { out, err } = await runDoctor("json");
+
+ expect(err.join("\n")).not.toContain("THREW");
+ const body = JSON.parse(out.join(""));
+ expect(body).toMatchObject({ healthy: false, hasWarnings: expect.any(Boolean) });
+ expect(Array.isArray(body.checks)).toBe(true);
+ const check = body.checks.find((c: { name: string }) => c.name === "Config file parses");
+ expect(check).toMatchObject({ ok: false });
+ expect(check.detail).toContain(configPath);
+ expect(check.detail).not.toMatch(/\n\s+at\s/);
+ expect(process.exitCode).toBe(1);
+ });
+});
diff --git a/ix-cli/src/cli/commands/doctor.ts b/ix-cli/src/cli/commands/doctor.ts
index ea455b1d..011fdc80 100644
--- a/ix-cli/src/cli/commands/doctor.ts
+++ b/ix-cli/src/cli/commands/doctor.ts
@@ -4,12 +4,16 @@ import type { Command } from "commander";
import chalk from "chalk";
import { renderSection, renderSuccess, renderError } from "../ui.js";
import { createClient } from "../../client/factory.js";
+import { IxClient } from "../../client/api.js";
import {
canonicalWorkspacePath,
+ ConfigParseError,
+ DEFAULT_ENDPOINT,
findWorkspaceForCwd,
getDefaultWorkspace,
getEndpoint,
gitRootFor,
+ loadConfig,
loadWorkspaces,
selectWorkspaceForCwd,
type WorkspaceConfig,
@@ -285,19 +289,68 @@ export async function assessDatabase(
}
}
-/** "Config file parses": a config.yaml Ix cannot read is otherwise silently replaced by defaults. */
+/** What every other command does with a config.yaml that does not parse (#807). */
+const CONFIG_REFUSAL = "other ix commands refuse to run until it is fixed";
+
+/**
+ * "Config file parses". A config.yaml that does not parse stops every other
+ * command (`loadConfig` throws ConfigParseError), so this is a failure, and the
+ * one doctor is still able to report: it catches that error itself.
+ */
export function assessConfigFile(configPath: string, read: (p: string) => string | null): CheckResult {
const raw = read(configPath);
if (raw === null) return { ok: true, detail: "no config file (defaults)" };
try {
const parsed = parseYaml(raw);
if (parsed !== null && parsed !== undefined && (typeof parsed !== "object" || Array.isArray(parsed))) {
- return { ok: false, detail: `${configPath} is not a mapping of settings` };
+ return { ok: false, detail: `${configPath} is not a mapping of settings, so ${CONFIG_REFUSAL}` };
}
return { ok: true, detail: configPath };
} catch (e) {
const first = ((e as Error)?.message ?? String(e)).split("\n")[0];
- return { ok: false, detail: `${configPath} does not parse, so Ix runs on defaults: ${first}` };
+ return { ok: false, detail: `${configPath} does not parse, so ${CONFIG_REFUSAL}: ${first}` };
+ }
+}
+
+/** The answer of a check that needs config.yaml when config.yaml does not parse. */
+const CONFIG_NOT_CHECKED: CheckResult = { ok: true, detail: "not checked: config.yaml does not parse" };
+
+function isConfigParseError(e: unknown): e is ConfigParseError {
+ return (e as Error | undefined)?.name === "ConfigParseError";
+}
+
+/**
+ * The endpoint and client doctor checks with. A config.yaml that does not parse
+ * is the one failure doctor must survive, since reporting it is its job: the
+ * endpoint falls back to IX_ENDPOINT or the default, and the client is built
+ * without the stored token, which lives in the file that does not parse.
+ */
+function doctorClient(): { endpoint: string; client: IxClient } {
+ let endpoint: string;
+ try {
+ endpoint = getEndpoint();
+ } catch (e) {
+ if (!isConfigParseError(e)) throw e;
+ endpoint = process.env.IX_ENDPOINT || DEFAULT_ENDPOINT;
+ }
+ try {
+ return { endpoint, client: createClient({ endpoint }) };
+ } catch (e) {
+ if (!isConfigParseError(e)) throw e;
+ // createClient read the stored token from the file that does not parse.
+ const token = process.env.IX_TOKEN?.trim();
+ // eslint-disable-next-line no-restricted-syntax -- the factory cannot build a client without config.yaml
+ return { endpoint, client: new IxClient(endpoint, undefined, token ? { token } : {}) };
+ }
+}
+
+/** A workspace lookup, or none when config.yaml (where workspaces live) does not parse. */
+function workspaceOrNone(lookup: () => WorkspaceConfig | undefined): WorkspaceConfig | undefined {
+ try {
+ return lookup();
+ } catch (e) {
+ if (isConfigParseError(e)) return undefined;
+ throw e;
}
}
@@ -317,8 +370,14 @@ export function registerDoctorCommand(program: Command): void {
.description("Check Ix system health — server, database, graph integrity")
.option("--format <fmt>", "Output format (text|json|llm)", "text")
.action(async (opts: { format: string }) => {
- const endpoint = getEndpoint();
- const client = createClient({ endpoint });
+ const { endpoint, client } = doctorClient();
+ // Asked of the file directly: with IX_ENDPOINT and IX_TOKEN set,
+ // building the client never reads it.
+ let configBroken = false;
+ try { loadConfig(); } catch (e) {
+ if (!isConfigParseError(e)) throw e;
+ configBroken = true;
+ }
// "Graph has nodes" and "Graph has edges" are two questions about one
// response. They were two `client.stats()` calls, run back to back by the
@@ -338,11 +397,14 @@ export function registerDoctorCommand(program: Command): void {
// never-ingested directory passed every check while quoting another repo's
// graph (#518). Local, so it still answers when the backend is unreachable.
const cwd = process.cwd();
- const matchedWorkspace = findWorkspaceForCwd(cwd);
- const substitutedWorkspace = matchedWorkspace ? undefined : getDefaultWorkspace();
+ const matchedWorkspace = workspaceOrNone(() => findWorkspaceForCwd(cwd));
+ const substitutedWorkspace = matchedWorkspace ? undefined : workspaceOrNone(getDefaultWorkspace);
let statsOnce: Promise<{ stats: any; scope: string; systemId?: string }> | undefined;
const sharedStats = (): Promise<{ stats: any; scope: string; systemId?: string }> => (statsOnce ??= (async () => {
+ // Without the workspaces there is no scope to count in, and an
+ // unscoped count would be reported as if it were this directory's.
+ if (configBroken) throw new ConfigParseError(pathJoin(ixHome(), "config.yaml"), "see Config file parses");
// Scoped the same way `ix stats` scopes, because doctor disagreeing with
// stats about the size of the graph is the whole of #510. Not a
// tombstone fix: /v1/stats filters `deleted_rev == null` in every one of
@@ -440,6 +502,7 @@ export function registerDoctorCommand(program: Command): void {
} catch { /* fall through to the local answer */ }
if (systemScoped) return { ok: true, detail: "scoped to the active system" };
+ if (configBroken) return CONFIG_NOT_CHECKED;
if (matchedWorkspace) return { ok: true, detail: `workspace '${matchedWorkspace.workspace_name}'` };
if (substitutedWorkspace) {
return {
@@ -476,6 +539,7 @@ export function registerDoctorCommand(program: Command): void {
// doctor`.
name: "Completed map for this workspace",
run: async () => {
+ if (configBroken) return CONFIG_NOT_CHECKED;
if (!matchedWorkspace) {
return { ok: false, warn: true, detail: "no local workspace to check" };
}
@@ -515,6 +579,7 @@ export function registerDoctorCommand(program: Command): void {
const total = stats.nodes?.total ?? 0;
return { ok: total > 0, detail: `${total} nodes in ${scope}` };
} catch (e: any) {
+ if (isConfigParseError(e)) return CONFIG_NOT_CHECKED;
return { ok: false, detail: e.message ?? "stats failed" };
}
},
@@ -527,6 +592,7 @@ export function registerDoctorCommand(program: Command): void {
const total = stats.edges?.total ?? 0;
return { ok: total > 0, detail: `${total} edges in ${scope}` };
} catch (e: any) {
+ if (isConfigParseError(e)) return CONFIG_NOT_CHECKED;
return { ok: false, detail: e.message ?? "stats failed" };
}
},
@@ -555,6 +621,7 @@ export function registerDoctorCommand(program: Command): void {
// not a second failure for one problem.
return { ok: true, detail: `not judged: no ${health.status === "empty" ? "nodes" : "edge breakdown"} in ${scope}` };
} catch (e: any) {
+ if (isConfigParseError(e)) return CONFIG_NOT_CHECKED;
return { ok: false, detail: e.message ?? "stats failed" };
}
},
@@ -567,6 +634,7 @@ export function registerDoctorCommand(program: Command): void {
const count = Array.isArray(c) ? c.length : 0;
return { ok: count === 0, detail: count === 0 ? "clean" : `${count} conflict(s)` };
} catch (e: any) {
+ if (isConfigParseError(e)) return CONFIG_NOT_CHECKED;
return { ok: false, detail: e.message ?? "conflicts check failed" };
}
},
@@ -652,7 +720,15 @@ export function registerDoctorCommand(program: Command): void {
const results: Array<{ name: string } & CheckResult> = [];
for (const check of checks) {
- const result = await check.run();
+ let result: CheckResult;
+ try {
+ result = await check.run();
+ } catch (e) {
+ // A check that reached for config.yaml and found it unparseable. Any
+ // other throw is a bug in the check and still surfaces.
+ if (!isConfigParseError(e)) throw e;
+ result = CONFIG_NOT_CHECKED;
+ }
results.push({ name: check.name, ...result });
}
diff --git a/ix-cli/src/cli/config.ts b/ix-cli/src/cli/config.ts
index d2c9c53a..1782aacf 100644
--- a/ix-cli/src/cli/config.ts
+++ b/ix-cli/src/cli/config.ts
@@ -152,8 +152,11 @@ export interface IxConfig {
auth?: { local_token?: string };
}
+/** The backend a config with no `endpoint` (or no config at all) points at. */
+export const DEFAULT_ENDPOINT = "http://localhost:8090";
+
const defaultConfig: IxConfig = {
- endpoint: "http://localhost:8090",
+ endpoint: DEFAULT_ENDPOINT,
format: "text",
};