Skip to content

armgit / Ix

Public Imported from GitHub
0

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

fix(mcp): close the in-process state leaks and the Windows install path (#400)

Joseph Mikhail7f6f1ceb60e0
diff --git a/README.md b/README.md
index 1faa6905..d2be9121 100644
--- a/README.md
+++ b/README.md
@@ -71,14 +71,18 @@ ix mcp doctor # check each client's registration
`install` knows Claude Code, Codex, Cursor, VS Code, Gemini CLI, OpenClaw and
opencode. It writes through each client's own MCP command where one exists
-(`claude mcp add`, `codex mcp add`, `gemini mcp add`, `openclaw mcp set`,
-`code --add-mcp`), so the client owns its config format; only Cursor and
-opencode are edited directly, and both are merged in place with a `.bak` kept
-alongside.
+(`claude mcp add`, `codex mcp add`, `gemini mcp add`, `openclaw mcp set`), so
+the client owns its config format; Cursor, VS Code and opencode are edited
+directly, and each is merged in place with a `.bak` kept alongside. Those three
+are also detected by their config directory rather than by a shell command,
+since `cursor` and `code` are opt-in shims a GUI install may not have.
**It never overwrites.** If the name `ix-memory` already belongs to a different
server — an earlier Ix plugin, say — that client is reported and left exactly as
-it was. Pass `--force` to replace it, or `--host <id>` to limit the run.
+it was. Pass `--force` to replace it, or `--host <id>` to limit the run; an
+unrecognised id is an error rather than a silent no-op. `doctor` additionally
+reports a registration of ours whose recorded launcher path has since
+disappeared, which `install` then repairs without `--force`.
To register a single client by hand instead, point it at `ix` with the argument
`mcp`. For Codex:
diff --git a/ix-cli/src/cli/__tests__/mcp-install.test.ts b/ix-cli/src/cli/__tests__/mcp-install.test.ts
index 818e7837..55788a30 100644
--- a/ix-cli/src/cli/__tests__/mcp-install.test.ts
+++ b/ix-cli/src/cli/__tests__/mcp-install.test.ts
@@ -4,7 +4,16 @@ import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
-import { classifyDefinition, classifyListing, type McpHost, type Registration } from "../../mcp/hosts.js";
+import {
+ ADD_ARGS,
+ classifyDefinition,
+ classifyListing,
+ classifyShown,
+ pickWindowsLauncher,
+ quoteForCmd,
+ type McpHost,
+ type Registration,
+} from "../../mcp/hosts.js";
import { IX_MCP_OSS_TOOL_NAMES, IX_MCP_PRO_TOOL_NAMES } from "../../mcp/server.js";
import { runDoctor, runInstall, writeJsonConfig } from "../../mcp/install.js";
@@ -27,7 +36,7 @@ function tempDir(): string {
function fakeHost(
id: string,
registration: Registration,
- options: { installed?: boolean; fails?: boolean } = {},
+ options: { installed?: boolean; fails?: boolean; detectInstalled?: () => Promise<boolean> } = {},
): McpHost & { registerCalls: number } {
const host = {
id,
@@ -35,6 +44,7 @@ function fakeHost(
bin: options.installed === false ? "definitely-not-a-real-binary-xyz" : "node",
target: `${id}-config`,
registerCalls: 0,
+ ...(options.detectInstalled ? { detectInstalled: options.detectInstalled } : {}),
async inspect() {
return { registration };
},
@@ -130,6 +140,42 @@ describe("ix mcp install", () => {
expect(report.hosts.map((h) => h.id)).toEqual(["b"]);
expect(hosts[0]!.registerCalls).toBe(0);
});
+
+ it("rejects an unknown host id instead of reporting a silent success", async () => {
+ const hosts = [fakeHost("claude", "none")];
+
+ // Filtering everything out and returning `registered: 0` let a typo in a
+ // setup script register nothing and still exit 0.
+ await expect(runInstall({ hosts, only: ["claude-code"] })).rejects.toThrow(/unknown host 'claude-code'/);
+ await expect(runDoctor({ hosts, only: ["vs-code"] })).rejects.toThrow(/unknown host/);
+ expect(hosts[0]!.registerCalls).toBe(0);
+ });
+
+ it("repairs a registration whose launcher path is gone, without --force", async () => {
+ const host = fakeHost("moved", "stale");
+
+ const report = await runInstall({ hosts: [host] });
+
+ // Still ours, so nothing of the user's is at risk — and re-resolving the
+ // path is the only thing that fixes it. Reported as healthy, install
+ // skipped the one host it should have rewritten.
+ expect(host.registerCalls).toBe(1);
+ expect(report.hosts[0]?.outcome).toBe("registered");
+ });
+
+ it("consults a host's own installed check before falling back to PATH", async () => {
+ // Cursor and VS Code are read and written through config files; their shell
+ // shims are opt-in and say nothing about whether the editor is there.
+ const host = fakeHost("cursor", "none", {
+ installed: false,
+ detectInstalled: async () => true,
+ });
+
+ const report = await runInstall({ hosts: [host] });
+
+ expect(report.hosts[0]).toMatchObject({ outcome: "registered", installed: true });
+ expect(host.registerCalls).toBe(1);
+ });
});
describe("ix mcp doctor", () => {
@@ -152,6 +198,17 @@ describe("ix mcp doctor", () => {
});
});
+describe("ix mcp doctor reporting", () => {
+ it("names a dead launcher rather than calling it registered", async () => {
+ const report = await runDoctor({ hosts: [fakeHost("moved", "stale")] });
+
+ // `= already registered` plus `+ ix on PATH` was the report a user got
+ // while every client failed to load a single Ix tool.
+ expect(report.hosts[0]?.outcome).toBe("stale");
+ expect(report.hosts[0]?.note).toMatch(/launcher/);
+ });
+});
+
describe("writeJsonConfig", () => {
it("keeps every unrelated key and backs up what was there", () => {
const dir = tempDir();
@@ -193,6 +250,28 @@ describe("writeJsonConfig", () => {
expect(JSON.parse(readFileSync(path, "utf8")).servers["ix-memory"].command).toBe("ix");
});
+ it("accepts the JSON-with-comments the read path already accepts", () => {
+ const path = join(tempDir(), "mcp.json");
+ // Valid for Cursor, and `inspect` reads it happily. The write path parsed
+ // it raw, so install reported the name free and then hard-failed, telling
+ // the user to fix a file their editor reads without complaint.
+ writeFileSync(
+ path,
+ ['{', ' // my servers', ' "mcpServers": { "theirs": { "command": "other" } }', "}", ""].join("\n"),
+ );
+
+ writeJsonConfig(path, (config) => {
+ const servers = (config.mcpServers ??= {}) as Record<string, unknown>;
+ servers["ix-memory"] = { command: "ix", args: ["mcp"] };
+ });
+
+ const written = JSON.parse(readFileSync(path, "utf8"));
+ expect(written.mcpServers.theirs.command).toBe("other");
+ expect(written.mcpServers["ix-memory"].command).toBe("ix");
+ // The comments are gone, which is what the .bak is for.
+ expect(readFileSync(`${path}.bak`, "utf8")).toContain("// my servers");
+ });
+
it("refuses to overwrite a file it cannot parse", () => {
const path = join(tempDir(), "mcp.json");
writeFileSync(path, "{ this is not json");
@@ -260,6 +339,28 @@ describe("registration classification", () => {
expect(classifyListing("some-other-server: npx thing").registration).toBe("none");
});
+ it("reports an absolute launcher path that no longer resolves as stale", () => {
+ // What a Windows registration looks like after an nvm switch or a reinstall
+ // to a different prefix. Judged from the command string alone this reads as
+ // healthy, so install skipped it and doctor called it registered while every
+ // client failed to start a single Ix tool.
+ const entry = JSON.stringify({ command: "C:\\Users\\gone\\AppData\\Roaming\\npm\\ix.cmd", args: ["mcp"] });
+
+ expect(classifyListing(`ix-memory ${entry}`)).toMatchObject({
+ registration: "stale",
+ detail: expect.stringContaining("no longer exists"),
+ });
+ });
+
+ it("keeps an absolute launcher that does resolve as ours", () => {
+ const launcher = join(tempDir(), "ix.cmd");
+ writeFileSync(launcher, "@echo off");
+
+ expect(classifyListing(`ix-memory ${JSON.stringify({ command: launcher, args: ["mcp"] })}`).registration).toBe(
+ "ours",
+ );
+ });
+
it("recognises a pretty-printed definition split across lines", () => {
// `openclaw mcp show` puts "ix" and "mcp" on separate lines; matching one
// line at a time reads our own entry as a stranger's.
@@ -269,3 +370,74 @@ describe("registration classification", () => {
expect(classifyListing(shown).registration).toBe("other");
});
});
+
+describe("windows launcher resolution", () => {
+ it("skips npm's extensionless POSIX shim, which CreateProcess cannot launch", () => {
+ // The exact output of `where ix` on a machine with npm's shims: the
+ // exact-name match comes first, and it is a `#!/bin/sh` script. Recording
+ // it registered a command no host could start, in every host at once, while
+ // `ix mcp doctor` still reported `+ ix on PATH`.
+ const entries = [
+ String.raw`C:\Users\me\AppData\Roaming\npm\ix`,
+ String.raw`C:\Users\me\AppData\Roaming\npm\ix.cmd`,
+ ];
+
+ expect(pickWindowsLauncher(entries)).toBe(String.raw`C:\Users\me\AppData\Roaming\npm\ix.cmd`);
+ });
+
+ it("falls back to nothing when no entry is executable", () => {
+ expect(pickWindowsLauncher([String.raw`C:\tools\ix`])).toBeUndefined();
+ });
+});
+
+describe("quoteForCmd", () => {
+ it("quotes a path with spaces and cmd metacharacters", () => {
+ // A quoted region is literal to cmd, so `&` and `(` survive it. Unquoted,
+ // cmd reads the `&` as a command separator.
+ expect(quoteForCmd(String.raw`C:\Program Files\a&b(c)\ix.cmd`)).toBe(
+ String.raw`"C:\Program Files\a&b(c)\ix.cmd"`,
+ );
+ });
+
+ it("leaves an ordinary argument alone", () => {
+ expect(quoteForCmd("--scope")).toBe("--scope");
+ });
+});
+
+describe("classifyShown", () => {
+ it("reads a host that could not answer as occupied, not free", () => {
+ // openclaw's config is wedged, or its output format moved. Reading that as
+ // an empty slot replaced the user's own server under our name, without
+ // --force, and reported `+ registered`.
+ expect(classifyShown("Error: failed to read config\n", false)).toMatchObject({
+ registration: "unknown",
+ });
+ });
+
+ it("still reads an explicit 'no such server' as free", () => {
+ expect(classifyShown("No MCP server named ix-memory\n", false).registration).toBe("none");
+ });
+
+ it("reads a definition body as ours", () => {
+ const shown = 'MCP server "ix-memory":\n{\n "command": "ix",\n "args": ["mcp"]\n}';
+
+ expect(classifyShown(shown, true).registration).toBe("ours");
+ });
+});
+
+describe("host registration arguments", () => {
+ it("pins gemini to user scope", () => {
+ // `gemini mcp add` defaults to project scope, writing `<cwd>/.gemini/` —
+ // invisible from every other directory, while the report named the
+ // user-level file.
+ expect(ADD_ARGS.gemini({ command: "ix", args: ["mcp"] })).toEqual([
+ "mcp",
+ "add",
+ "--scope",
+ "user",
+ "ix-memory",
+ "ix",
+ "mcp",
+ ]);
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/mcp-runner.test.ts b/ix-cli/src/cli/__tests__/mcp-runner.test.ts
index 923afb28..9e5b334f 100644
--- a/ix-cli/src/cli/__tests__/mcp-runner.test.ts
+++ b/ix-cli/src/cli/__tests__/mcp-runner.test.ts
@@ -1,8 +1,19 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
import { Command } from "commander";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { acquireMapLock } from "../single-flight.js";
import { createInProcessRunner, resolveDefaultRunner, runCurrentIx } from "../../mcp/runner.js";
+const resetReadScope = vi.hoisted(() => vi.fn());
+vi.mock("../resolve.js", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../resolve.js")>()),
+ resetReadScope,
+}));
+
/**
* A stand-in command tree. The capture machinery is what is under test here,
* not the Ix commands, and a real one would need a backend.
@@ -50,6 +61,28 @@ function createTestProgram(): Command {
for (let i = 0; i < 20; i += 1) console.log("x".repeat(100));
});
+ // A command that outlives its timeout and *then* reports failure the way
+ // `ix map` does — the shape that used to be charged to whichever call was
+ // running by the time it landed.
+ program
+ .command("late-fail")
+ .option("--delay <ms>", "how long before it reports failure", "150")
+ .action(async (opts: { delay: string }) => {
+ await new Promise((resolve) => setTimeout(resolve, Number(opts.delay)));
+ process.exitCode = 1;
+ });
+
+ // Stands in for `ix map`, which takes a single-flight lock and leaves it to
+ // process exit to release.
+ program
+ .command("map")
+ .action(() => {
+ const lock = acquireMapLock(process.env.IX_TEST_WORKSPACE ?? "workspace", "ix map test");
+ console.log(lock ? "mapped" : "coalesced");
+ });
+
+ program.command("ingest").action(() => console.log("ingested"));
+
return program;
}
@@ -125,7 +158,11 @@ describe("in-process ix runner", () => {
it("fails a run that outlives its timeout", async () => {
const run = testRunner();
- const result = await run(["slow"], 50);
+ // Bounded rather than left on the 5s default: an abandoned command stays
+ // in flight after the test that started it, and while one is alive the
+ // runner distrusts process.exitCode and holds off releasing locks — so a
+ // long orphan silently changes what later tests in this file observe.
+ const result = await run(["slow", "--delay", "200"], 50);
expect(result.ok).toBe(false);
expect(result.stderr).toContain("timed out after 50ms");
@@ -134,7 +171,7 @@ describe("in-process ix runner", () => {
it("stays usable after a timeout rather than stranding the queue", async () => {
const run = testRunner();
- await run(["slow"], 50);
+ await run(["slow", "--delay", "200"], 50);
expect(await run(["say", "after"])).toMatchObject({ ok: true, stdout: "out:after\n" });
});
@@ -152,6 +189,76 @@ describe("in-process ix runner", () => {
expect(covering).toEqual({ ok: true, stdout: "done:covering\n", stderr: "" });
});
+ it("does not charge a timed-out command's late exit code to the next call", async () => {
+ const run = testRunner();
+ process.exitCode = undefined;
+
+ // Abandoned at 50ms; sets process.exitCode = 1 at ~150ms.
+ const timedOut = await run(["late-fail", "--delay", "150"], 50);
+ // Runs across that moment. Its own command succeeds.
+ const covering = await run(["slow", "--delay", "250", "--tag", "covering"], 5_000);
+
+ expect(timedOut.ok).toBe(false);
+ // The orphan's write is the only thing that could make this false, and a
+ // successful lookup reported as a failure hides its answer inside an
+ // `error` string the agent cannot tell from a real fault.
+ expect(covering).toEqual({ ok: true, stdout: "done:covering\n", stderr: "" });
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it("trusts process.exitCode again once no orphan is in flight", async () => {
+ const run = testRunner();
+ process.exitCode = undefined;
+
+ await run(["late-fail", "--delay", "60"], 30);
+ // Long enough for the orphan to finish and leave the set.
+ await run(["slow", "--delay", "150", "--tag", "drain"], 5_000);
+
+ // Distrust must be temporary: a genuinely failing command still fails.
+ expect(await run(["soft-fail"])).toMatchObject({ ok: false });
+ });
+
+ it("releases the map single-flight lock when the command ends, not the process", async () => {
+ const lockDir = mkdtempSync(join(tmpdir(), "ix-mcp-lock-"));
+ const previousLockDir = process.env.IX_LOCK_DIR;
+ const previousWorkspace = process.env.IX_TEST_WORKSPACE;
+ process.env.IX_LOCK_DIR = lockDir;
+ process.env.IX_TEST_WORKSPACE = join(lockDir, "workspace");
+
+ try {
+ const run = testRunner();
+
+ const first = await run(["map"]);
+ const second = await run(["map"]);
+
+ expect(first.stdout).toBe("mapped\n");
+ // The lock records the server's own live PID, so it never ages out as
+ // stale. Held across calls, every later ix_map coalesced into an empty
+ // success while the graph was never refreshed.
+ expect(second.stdout).toBe("mapped\n");
+ } finally {
+ if (previousLockDir === undefined) delete process.env.IX_LOCK_DIR;
+ else process.env.IX_LOCK_DIR = previousLockDir;
+ if (previousWorkspace === undefined) delete process.env.IX_TEST_WORKSPACE;
+ else process.env.IX_TEST_WORKSPACE = previousWorkspace;
+ rmSync(lockDir, { recursive: true, force: true });
+ }
+ });
+
+ it("invalidates the read-scope cache after a command that can change it", async () => {
+ const run = testRunner();
+ resetReadScope.mockClear();
+
+ await run(["say", "read"]);
+ expect(resetReadScope).not.toHaveBeenCalled();
+
+ // `ix map` can stitch the repo into a System server-side; every later read
+ // in the session would otherwise still scope to the pre-map workspace.
+ await run(["map"]);
+ await run(["ingest"]);
+ expect(resetReadScope).toHaveBeenCalledTimes(2);
+ });
+
it("truncates output instead of growing the server heap without bound", async () => {
const run = createInProcessRunner({
createProgram: createTestProgram,
@@ -183,6 +290,37 @@ describe("in-process ix runner", () => {
});
});
+describe("installServerErrorHandlers", () => {
+ it("replaces the CLI's exit-on-error handlers with reporting ones", async () => {
+ const { installServerErrorHandlers } = await import("../../mcp/runner.js");
+ const before = {
+ uncaught: process.listeners("uncaughtException"),
+ unhandled: process.listeners("unhandledRejection"),
+ };
+ const exit = vi.spyOn(process, "exit").mockImplementation((() => undefined) as never);
+
+ try {
+ installServerErrorHandlers();
+ const handler = process.listeners("uncaughtException").at(-1) as (err: unknown) => void;
+ handler(new Error("stray rejection from a fire-and-forget fetch"));
+
+ // main.ts's handlers end in process.exit(1) on every path. For a server
+ // that is the whole session and all 22 tools, over an error that belonged
+ // to one tool call.
+ expect(exit).not.toHaveBeenCalled();
+ // And they are gone, not merely outnumbered: one handler each, ours.
+ expect(process.listeners("uncaughtException")).toHaveLength(1);
+ expect(process.listeners("unhandledRejection")).toHaveLength(1);
+ } finally {
+ exit.mockRestore();
+ process.removeAllListeners("uncaughtException");
+ process.removeAllListeners("unhandledRejection");
+ for (const listener of before.uncaught) process.on("uncaughtException", listener);
+ for (const listener of before.unhandled) process.on("unhandledRejection", listener);
+ }
+ });
+});
+
describe("resolveDefaultRunner", () => {
it("runs in-process by default", () => {
delete process.env.IX_MCP_SUBPROCESS;
diff --git a/ix-cli/src/cli/__tests__/mcp.test.ts b/ix-cli/src/cli/__tests__/mcp.test.ts
index 94147fb5..0416fcef 100644
--- a/ix-cli/src/cli/__tests__/mcp.test.ts
+++ b/ix-cli/src/cli/__tests__/mcp.test.ts
@@ -75,7 +75,7 @@ describe("ix mcp", () => {
arguments: { symbol: "Widget" },
});
- expect(calls).toEqual([["locate", "Widget", "--format", "llm"]]);
+ expect(calls).toEqual([["locate", "--format=llm", "--", "Widget"]]);
expect(result.content).toEqual([{ type: "text", text: "match name=Widget" }]);
});
@@ -127,7 +127,7 @@ describe("ix mcp", () => {
await client.callTool({ name: "ix_map", arguments: { file: "src/service.ts" } });
- expect(calls).toEqual([["map", "src/service.ts", "--format", "json"]]);
+ expect(calls).toEqual([["map", "--format=json", "--", "src/service.ts"]]);
});
it("applies ix_smells path and limit compatibility without unsupported CLI flags", async () => {
@@ -139,7 +139,7 @@ describe("ix mcp", () => {
stdout: JSON.stringify({
count: 3,
candidates: [
- { file: "src/a.ts", smell: "orphan" },
+ { file: "ix-cli/src/a.ts", smell: "orphan" },
{ file: "src/nested/b.ts", smell: "orphan" },
{ file: "test/c.ts", smell: "orphan" },
],
@@ -153,12 +153,14 @@ describe("ix mcp", () => {
arguments: { path: "src", limit: 1 },
});
- expect(calls).toEqual([["smells", "--format", "json"]]);
+ expect(calls).toEqual([["smells", "--format=json"]]);
const content = (result as CallToolResult).content[0];
expect(content?.type).toBe("text");
const parsed = JSON.parse(content?.type === "text" ? content.text : "{}");
expect(parsed.count).toBe(1);
- expect(parsed.candidates).toEqual([{ file: "src/a.ts", smell: "orphan" }]);
+ // Substring, not prefix: `ix-cli/src/a.ts` is what `ix inventory --path src`
+ // would have returned, and ix_smells must agree with it.
+ expect(parsed.candidates).toEqual([{ file: "ix-cli/src/a.ts", smell: "orphan" }]);
});
it("maps ix_ingest onto the github form the plugins used", async () => {
@@ -170,7 +172,7 @@ describe("ix mcp", () => {
await client.callTool({ name: "ix_ingest", arguments: { github: "owner/repo", limit: 25 } });
- expect(calls).toEqual([["ingest", "--github", "owner/repo", "--limit", "25", "--format", "json"]]);
+ expect(calls).toEqual([["ingest", "--github=owner/repo", "--limit=25", "--format=json"]]);
});
it("does not pass --limit when ingesting a local path", async () => {
@@ -183,7 +185,37 @@ describe("ix mcp", () => {
await client.callTool({ name: "ix_ingest", arguments: { path: "src" } });
// --limit is a GitHub paging cap; on a path ingest it is meaningless.
- expect(calls).toEqual([["ingest", "src", "--format", "json"]]);
+ expect(calls).toEqual([["ingest", "--format=json", "--", "src"]]);
+ });
+
+ it("puts positional values behind -- so a leading dash is not read as a flag", async () => {
+ const calls: string[][] = [];
+ const client = await connect(async (args) => {
+ calls.push(args);
+ return { ok: true, stdout: "{}", stderr: "" };
+ });
+
+ await client.callTool({ name: "ix_text", arguments: { pattern: "--path", limit: 20 } });
+
+ // Without the separator commander read `--path` as a flag and swallowed the
+ // following `--limit` as its value, so the tool searched for the literal
+ // text `20` under a directory named `--limit` and reported ok.
+ expect(calls).toEqual([["text", "--limit=20", "--format=llm", "--", "--path"]]);
+ });
+
+ it("lists entities by kind without demanding a path, and forwards the limit", async () => {
+ const calls: string[][] = [];
+ const client = await connect(async (args) => {
+ calls.push(args);
+ return { ok: true, stdout: "{}", stderr: "" };
+ });
+
+ // The form CLAUDE.md tells agents to use. A required `path` made it
+ // impossible over MCP, and a dropped `--limit` silently capped every answer
+ // at the CLI's default 50.
+ await client.callTool({ name: "ix_inventory", arguments: { kind: "function", limit: 200 } });
+
+ expect(calls).toEqual([["inventory", "--kind=function", "--limit=200", "--format=llm"]]);
});
it("maps ix_decide onto the decide command", async () => {
@@ -199,7 +231,7 @@ describe("ix mcp", () => {
});
expect(calls).toEqual([
- ["decide", "Use CONTAINS", "--rationale", "Normalize edges", "--affects", "Ingestion", "--format", "json"],
+ ["decide", "--rationale=Normalize edges", "--affects=Ingestion", "--format=json", "--", "Use CONTAINS"],
]);
});
});
diff --git a/ix-cli/src/cli/commands/mcp.ts b/ix-cli/src/cli/commands/mcp.ts
index 8a6a6252..0a17ef5a 100644
--- a/ix-cli/src/cli/commands/mcp.ts
+++ b/ix-cli/src/cli/commands/mcp.ts
@@ -12,6 +12,7 @@ const OUTCOME_STYLE: Record<Outcome, { mark: string; paint: (text: string) => st
conflict: { mark: "!", paint: chalk.yellow },
failed: { mark: "x", paint: chalk.red },
"not-registered": { mark: "o", paint: chalk.yellow },
+ stale: { mark: "!", paint: chalk.yellow },
"not-installed": { mark: "-", paint: chalk.dim },
};
@@ -22,6 +23,7 @@ const OUTCOME_TEXT: Record<Outcome, string> = {
conflict: "conflict — left alone",
failed: "failed",
"not-registered": "not registered",
+ stale: "registered, but its launcher is gone",
"not-installed": "not installed",
};
@@ -125,7 +127,9 @@ export function registerMcpCommand(program: Command): void {
const { runDoctor } = await import("../../mcp/install.js");
const report = await runDoctor({ only: opts.host });
renderDoctor(report, opts.format);
- const broken = report.hosts.some((host) => host.outcome === "conflict" || host.outcome === "not-registered");
+ const broken = report.hosts.some(
+ (host) => host.outcome === "conflict" || host.outcome === "not-registered" || host.outcome === "stale",
+ );
if (!report.ixOnPath || broken) process.exitCode = 1;
});
}
diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.ts
index f8b418d5..573354ef 100644
--- a/ix-cli/src/cli/resolve.ts
+++ b/ix-cli/src/cli/resolve.ts
@@ -16,6 +16,20 @@ import { resolveWorkspaceId } from "./bootstrap.js";
* (issue #228, originally fixed in search.ts only).
*/
let _scopeCache: { cwd: string; workspaceId?: string; systemId?: string; stitchChecked?: boolean } | undefined;
+
+/**
+ * Drop the cached scope so the next read resolves it again.
+ *
+ * The cache is keyed on cwd alone and never expires, which was safe while a
+ * command's process ended with it. `ix mcp` runs many commands in one
+ * long-lived process, so it calls this after anything that can change what a
+ * repo is scoped to — an ingest, or a map that stitches the repo into a System
+ * server-side. Without it, every later read in the session still answers
+ * against the pre-map workspace.
+ */
+export function resetReadScope(): void {
+ _scopeCache = undefined;
+}
export function activeReadScope(): { workspaceId?: string; systemId?: string } {
return activeScope();
}
diff --git a/ix-cli/src/cli/single-flight.ts b/ix-cli/src/cli/single-flight.ts
index f292a18f..686de88a 100644
--- a/ix-cli/src/cli/single-flight.ts
+++ b/ix-cli/src/cli/single-flight.ts
@@ -126,22 +126,51 @@ export function acquireMapLock(workspaceRoot: string, label: string): LockHandle
return null; // a live holder owns it — caller should coalesce
}
+// Locks this process still holds. `ix mcp` runs commands in-process, so "the
+// process exits" is no longer the end of a command — see releaseHeldLocks.
+const held = new Set<() => void>();
+
function makeHandle(path: string): LockHandle {
let released = false;
const release = (): void => {
if (released) return;
released = true;
+ held.delete(release);
+ // Both listeners are removed with the lock. A long-lived process that maps
+ // repeatedly would otherwise accumulate one set per map and trip Node's
+ // max-listeners warning.
+ process.off("exit", release);
+ process.off("SIGINT", onSigint);
+ process.off("SIGTERM", onSigterm);
try { rmSync(path, { force: true }); } catch { /* best effort */ }
};
+ const onSigint = (): void => { release(); process.exit(130); };
+ const onSigterm = (): void => { release(); process.exit(143); };
+
+ held.add(release);
// Release on normal exit and on the common termination signals so a killed
// map (hook timeout, Ctrl-C) does not leave a lock that blocks the next run
// until it ages out.
process.once("exit", release);
- process.once("SIGINT", () => { release(); process.exit(130); });
- process.once("SIGTERM", () => { release(); process.exit(143); });
+ process.once("SIGINT", onSigint);
+ process.once("SIGTERM", onSigterm);
return { release };
}
+/**
+ * Release every lock this process still holds.
+ *
+ * `ix map` takes its lock and leaves it to process exit, which was the end of
+ * the command until `ix mcp` began running commands in-process. There, the
+ * holder PID is the server's own and stays alive, so the lock never reads as
+ * stale: the first ix_map works and every later one coalesces into an empty
+ * success while the graph is never refreshed. The MCP runner calls this when a
+ * command finishes, restoring the boundary the process used to provide.
+ */
+export function releaseHeldLocks(): void {
+ for (const release of [...held]) release();
+}
+
// ── Test-only surface ──────────────────────────────────────────────────────
// Exported for unit tests; not part of the public CLI API.
export function lockPathForTest(workspaceRoot: string): string {
diff --git a/ix-cli/src/mcp/hosts.ts b/ix-cli/src/mcp/hosts.ts
index ea64e5f5..c3b38f81 100644
--- a/ix-cli/src/mcp/hosts.ts
+++ b/ix-cli/src/mcp/hosts.ts
@@ -1,7 +1,7 @@
import { execFile } from "node:child_process";
-import { readFileSync } from "node:fs";
+import { readFileSync, statSync } from "node:fs";
import { homedir, platform } from "node:os";
-import { join } from "node:path";
+import { dirname, join } from "node:path";
import { promisify } from "node:util";
const execFileAsync = promisify(execFile);
@@ -21,6 +21,7 @@ const HOST_CLI_TIMEOUT_MS = 20_000;
export type Registration =
| "none" // nothing under our name; safe to add
| "ours" // already points at `ix mcp`; nothing to do
+ | "stale" // ours, but the recorded launcher path is gone — re-register over it
| "other" // a different server holds the name — never overwrite without --force
| "unknown"; // could not tell, so treat it as occupied
@@ -38,6 +39,16 @@ export interface McpHost {
label: string;
/** Executable whose presence on PATH means the host is installed. */
bin: string;
+ /**
+ * Whether the host is present, when {@link bin} does not answer that.
+ *
+ * Cursor, VS Code and opencode are read and written through their config
+ * files, so their shell commands are irrelevant to whether registration can
+ * work — and `cursor`/`code` are opt-in shims a GUI user may never have
+ * installed. Gating those hosts on PATH reported "not installed" for an
+ * editor sitting right there and wrote nothing.
+ */
+ detectInstalled?(): Promise<boolean>;
/** Read-only look at what holds {@link SERVER_NAME} today. */
inspect(): Promise<Pick<HostStatus, "registration" | "detail">>;
/** Register `ix mcp`. Only called once inspect reports it is safe. */
@@ -52,13 +63,73 @@ interface RunResult {
stderr: string;
}
+/** How a host is told to reach `ix mcp`. */
+export interface Launcher {
+ command: string;
+ args: string[];
+}
+
+/**
+ * Quote one argument for a Windows command line.
+ *
+ * Wrapping in double quotes is what makes a path containing a space — or a
+ * `&`, or parentheses — survive: cmd treats a quoted region as literal. An
+ * argument carrying a double quote of its own cannot be encoded this way and
+ * is refused by {@link run}. Escaping it as `\"` satisfies the callee's own
+ * argv parsing but flips cmd's quote tracking mid-argument, so a space later in
+ * the same argument is then read as an argument separator. Verified against a
+ * round-trip echo: every cmd encoding mangles such a value.
+ */
+export function quoteForCmd(arg: string): string {
+ if (arg !== "" && !/[\s"]/.test(arg)) return arg;
+ let out = '"';
+ let slashes = 0;
+ for (const ch of arg) {
+ if (ch === "\\") {
+ slashes += 1;
+ out += ch;
+ continue;
+ }
+ if (ch === '"') {
+ out += `${"\\".repeat(slashes)}\\"`;
+ slashes = 0;
+ continue;
+ }
+ slashes = 0;
+ out += ch;
+ }
+ return `${out}${"\\".repeat(slashes)}"`;
+}
+
+/**
+ * Invoke a host's own CLI.
+ *
+ * Windows cannot spawn these directly. npm ships them as `.cmd` shims, which
+ * Node has refused to spawn without a shell since CVE-2024-27980 (`spawn
+ * EINVAL`), while the bare name never resolves at all because CreateProcess
+ * consults no PATHEXT. Both failures surfaced as ENOENT, which `inspect` read
+ * as "cannot tell" and reported as a conflict — so on Windows every CLI-backed
+ * host was left alone and nothing was ever registered.
+ *
+ * The Windows path therefore goes through cmd, as a single pre-quoted string.
+ * Handing `shell: true` an args array instead lets Node concatenate them
+ * unescaped (DEP0190), which loses any path containing a space.
+ */
async function run(bin: string, args: string[]): Promise<RunResult> {
+ const options = { encoding: "utf8" as const, timeout: HOST_CLI_TIMEOUT_MS, windowsHide: true };
try {
- const { stdout, stderr } = await execFileAsync(bin, args, {
- encoding: "utf8",
- timeout: HOST_CLI_TIMEOUT_MS,
- windowsHide: true,
- });
+ if (platform() === "win32") {
+ const unencodable = [bin, ...args].find((arg) => arg.includes('"'));
+ if (unencodable !== undefined) {
+ // Refused rather than mangled: a half-parsed argument reaches the host
+ // as several arguments and writes a corrupt entry.
+ return { ok: false, stdout: "", stderr: `cannot pass a quoted argument through cmd.exe: ${unencodable}` };
+ }
+ const line = [bin, ...args].map(quoteForCmd).join(" ");
+ const { stdout, stderr } = await execFileAsync(line, { ...options, shell: true });
+ return { ok: true, stdout, stderr };
+ }
+ const { stdout, stderr } = await execFileAsync(bin, args, options);
return { ok: true, stdout, stderr };
} catch (error) {
const failure = error as Error & { stdout?: string; stderr?: string };
@@ -86,12 +157,59 @@ async function resolveLauncher(): Promise<{ command: string; args: string[] }> {
if (platform() !== "win32") return { command: "ix", args: ["mcp"] };
const found = await run("where", ["ix"]);
- const resolved = found.stdout
+ const entries = found.stdout
.split(/\r?\n/)
.map((entry) => entry.trim())
- .filter(Boolean)[0];
+ .filter(Boolean);
+
+ // `where` lists the exact-name match ahead of the PATHEXT variants, and npm's
+ // exact-name entry is an extensionless `#!/bin/sh` shim — precisely the file
+ // CreateProcess cannot launch. Taking the first line recorded that shim into
+ // every host, so nothing started while `ix mcp doctor` still reported `+ ix on
+ // PATH`. Only an entry Windows can actually execute counts.
+ return { command: pickWindowsLauncher(entries) ?? "ix", args: ["mcp"] };
+}
+
+/** The first `where ix` entry Windows can actually execute. */
+export function pickWindowsLauncher(entries: string[]): string | undefined {
+ return entries.find(isWindowsExecutable);
+}
+
+function isWindowsExecutable(entry: string): boolean {
+ const extensions = (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD")
+ .split(";")
+ .map((ext) => ext.trim().toLowerCase())
+ .filter(Boolean);
+ const lower = entry.toLowerCase();
+ return extensions.some((ext) => lower.endsWith(ext));
+}
+
+/**
+ * Whether a path resolves today.
+ *
+ * Only ENOENT counts as absent — a permission error means something is there,
+ * and reporting that as a dead launcher would rewrite a registration that is
+ * fine.
+ */
+function pathExists(path: string): boolean {
+ try {
+ statSync(path);
+ return true;
+ } catch (err) {
+ return (err as NodeJS.ErrnoException).code !== "ENOENT";
+ }
+}
- return { command: resolved || "ix", args: ["mcp"] };
+/**
+ * The absolute launcher path inside a registration, if it records one.
+ *
+ * Unix registers the bare name, so this finds nothing there and staleness never
+ * applies. JSON-encoded entries arrive with their backslashes doubled, which is
+ * undone here so the path can be checked.
+ */
+function absoluteLauncherIn(text: string): string | null {
+ const match = /(?:[A-Za-z]:[\\/]|\/)[^"'\s,\]]*[\\/]ix(?:\.\w+)?(?=["'\s,\]]|$)/.exec(text);
+ return match ? match[0].replace(/\\\\/g, "\\") : null;
}
/**
@@ -104,6 +222,14 @@ async function resolveLauncher(): Promise<{ command: string; args: string[] }> {
*/
const LOG_LINE = /^\[|^\s*(error|warning|warn|failed|validation)\b|Error:|Failed to|Validation failed/i;
+/**
+ * A host saying, in its own words, that nothing holds the name.
+ *
+ * Some hosts report that by exiting non-zero, which is otherwise indistinguishable
+ * from a host that could not answer at all.
+ */
+const MISSING_ENTRY = /\b(no (mcp )?server|not found|unknown server|does not exist|no such)\b/i;
+
/**
* Decide what a host's own listing says about our name.
*
@@ -139,12 +265,45 @@ export function classifyDefinition(blob: string): Pick<HostStatus, "registration
return judge(blob.replace(/\s+/g, " ").trim());
}
+/**
+ * Classify what `<host> mcp show <name>` printed.
+ *
+ * Whether the host answered at all is part of the evidence, for the same reason
+ * the listing path treats a failed `list` as occupied: guessing "none" is the
+ * one wrong guess that overwrites something. A wedged config, a permissions
+ * error, or an output format that changed upstream all fail the substring
+ * checks below, and reading that as an empty slot replaced whatever the user
+ * had — without `--force`, and reported as a cheerful `+ registered`. Only a
+ * host that answered, or one that said outright it has no such server, may read
+ * as free.
+ */
+export function classifyShown(blob: string, ok: boolean): Pick<HostStatus, "registration" | "detail"> {
+ // "No MCP server named X" also mentions the name and also exits 0, so the
+ // presence of a definition body is what distinguishes the two.
+ const definition = blob.includes(SERVER_NAME) && blob.includes("{");
+ if (definition) return classifyDefinition(blob);
+ if (!ok && !MISSING_ENTRY.test(blob)) {
+ return { registration: "unknown", detail: firstLine(blob) };
+ }
+ return { registration: "none" };
+}
+
/** Ours iff the entry invokes the `ix` binary with the `mcp` subcommand. */
function judge(text: string): Pick<HostStatus, "registration" | "detail"> {
- if (/(^|[\s"'/\\])ix(\.\w+)?([\s"',\]]|$)/.test(text) && /\bmcp\b/.test(text)) {
- return { registration: "ours", detail: truncate(text) };
+ if (!(/(^|[\s"'/\\])ix(\.\w+)?([\s"',\]]|$)/.test(text) && /\bmcp\b/.test(text))) {
+ return { registration: "other", detail: truncate(text) };
+ }
+
+ // Windows records an absolute launcher path rather than the bare name, so the
+ // entry dies whenever the npm prefix moves — an nvm switch, a reinstall
+ // elsewhere. Judging that healthy from the command string alone is what made
+ // `install` skip the one host it should have repaired, while `doctor` agreed
+ // it was fine and no command anywhere would rewrite it.
+ const launcher = absoluteLauncherIn(text);
+ if (launcher !== null && !pathExists(launcher)) {
+ return { registration: "stale", detail: `${launcher} no longer exists` };
}
- return { registration: "other", detail: truncate(text) };
+ return { registration: "ours", detail: truncate(text) };
}
function truncate(line: string, max = 120): string {
@@ -166,6 +325,11 @@ function cliHost(spec: {
* is ours.
*/
showArgs?: string[];
+ /**
+ * Used in place of `addArgs` on Windows, where an argument containing a
+ * double quote cannot be encoded through cmd.
+ */
+ windowsFallback?: (launcher: { command: string; args: string[] }) => void;
}): McpHost {
return {
id: spec.id,
@@ -175,11 +339,7 @@ function cliHost(spec: {
async inspect() {
if (spec.showArgs) {
const shown = await run(spec.bin, spec.showArgs);
- const blob = `${shown.stdout}\n${shown.stderr}`;
- // "No MCP server named X" also mentions the name and also exits 0, so
- // presence of a definition body is what distinguishes the two.
- if (!blob.includes(SERVER_NAME) || !blob.includes("{")) return { registration: "none" };
- return classifyDefinition(blob);
+ return classifyShown(`${shown.stdout}\n${shown.stderr}`, shown.ok);
}
const result = await run(spec.bin, spec.listArgs);
@@ -191,7 +351,12 @@ function cliHost(spec: {
return classifyListing(`${result.stdout}\n${result.stderr}`);
},
async register() {
- const result = await run(spec.bin, spec.addArgs(await resolveLauncher()));
+ const launcher = await resolveLauncher();
+ if (spec.windowsFallback && platform() === "win32") {
+ spec.windowsFallback(launcher);
+ return;
+ }
+ const result = await run(spec.bin, spec.addArgs(launcher));
if (!result.ok) {
throw new Error(firstLine(result.stderr) || firstLine(result.stdout) || "registration failed");
}
@@ -227,7 +392,7 @@ function readJsonFile(path: string): { value: Record<string, unknown> | null; mi
* VS Code and Cursor both accept JSON-with-comments in these files, and a user
* who has hand-annotated theirs must not read as corrupt.
*/
-function stripJsonComments(raw: string): string {
+export function stripJsonComments(raw: string): string {
let out = "";
let inString = false;
let inLine = false;
@@ -285,6 +450,42 @@ function opencodeConfigPath(): string {
return join(homedir(), ".config", "opencode", "opencode.json");
}
+function openclawConfigPath(): string {
+ return join(homedir(), ".openclaw", "openclaw.json");
+}
+
+/**
+ * A file-configured host counts as present if its shell command resolves *or*
+ * its config directory exists.
+ *
+ * `cursor` and `code` are opt-in PATH shims — on macOS they appear only after
+ * the user runs "Shell Command: Install 'code' command in PATH" — so their
+ * absence says nothing about whether the editor is installed, and the config
+ * file is what registration actually touches.
+ */
+function fileHostInstalled(bin: string, configPath: string): () => Promise<boolean> {
+ return async () => (await isOnPath(bin)) || pathExists(dirname(configPath)) || pathExists(configPath);
+}
+
+/**
+ * The argv each CLI-backed host is registered with.
+ *
+ * Exported so the flags stay pinned: `gemini mcp add` defaults to *project*
+ * scope, and leaving that to the host default wrote `<cwd>/.gemini/settings.json`
+ * while the report named the user-level file.
+ */
+export const ADD_ARGS = {
+ claude: (ix: Launcher) => ["mcp", "add", "--scope", "user", SERVER_NAME, ix.command, ...ix.args],
+ codex: (ix: Launcher) => ["mcp", "add", SERVER_NAME, "--", ix.command, ...ix.args],
+ gemini: (ix: Launcher) => ["mcp", "add", "--scope", "user", SERVER_NAME, ix.command, ...ix.args],
+ openclaw: (ix: Launcher) => [
+ "mcp",
+ "set",
+ SERVER_NAME,
+ JSON.stringify({ command: ix.command, args: ix.args }),
+ ],
+} satisfies Record<string, (ix: Launcher) => string[]>;
+
/**
* The hosts `ix mcp install` knows about.
*
@@ -301,7 +502,7 @@ export function createHosts(writeJson: (path: string, mutate: (config: Record<st
bin: "claude",
target: "user scope",
listArgs: ["mcp", "list"],
- addArgs: (ix) => ["mcp", "add", "--scope", "user", SERVER_NAME, ix.command, ...ix.args],
+ addArgs: ADD_ARGS.claude,
}),
cliHost({
id: "codex",
@@ -309,7 +510,7 @@ export function createHosts(writeJson: (path: string, mutate: (config: Record<st
bin: "codex",
target: "~/.codex/config.toml",
listArgs: ["mcp", "list"],
- addArgs: (ix) => ["mcp", "add", SERVER_NAME, "--", ix.command, ...ix.args],
+ addArgs: ADD_ARGS.codex,
}),
cliHost({
id: "gemini",
@@ -317,7 +518,7 @@ export function createHosts(writeJson: (path: string, mutate: (config: Record<st
bin: "gemini",
target: "~/.gemini/settings.json",
listArgs: ["mcp", "list"],
- addArgs: (ix) => ["mcp", "add", SERVER_NAME, ix.command, ...ix.args],
+ addArgs: ADD_ARGS.gemini,
}),
cliHost({
id: "openclaw",
@@ -328,22 +529,38 @@ export function createHosts(writeJson: (path: string, mutate: (config: Record<st
// `openclaw mcp list` prints names only ("- ix-memory"), so the command
// behind the name is invisible there.
showArgs: ["mcp", "show", SERVER_NAME],
- addArgs: (ix) => ["mcp", "set", SERVER_NAME, JSON.stringify({ command: ix.command, args: ix.args })],
+ addArgs: ADD_ARGS.openclaw,
+ // `openclaw mcp set` takes its definition as a JSON argument, and a JSON
+ // argument cannot be encoded through cmd (see `run`). Windows therefore
+ // writes the documented config shape directly; every other platform keeps
+ // going through the CLI so openclaw owns its own format.
+ windowsFallback: (ix) =>
+ writeJson(openclawConfigPath(), (config) => {
+ const mcp = (config.mcp ??= {}) as Record<string, unknown>;
+ const servers = (mcp.servers ??= {}) as Record<string, unknown>;
+ servers[SERVER_NAME] = { command: ix.command, args: ix.args };
+ }),
}),
{
id: "vscode",
label: "VS Code",
bin: "code",
target: vsCodeUserConfig(),
+ detectInstalled: fileHostInstalled("code", vsCodeUserConfig()),
// No list subcommand, so the user-profile file is the only read path.
async inspect() {
return inspectJsonFile(vsCodeUserConfig(), "servers");
},
async register() {
const ix = await resolveLauncher();
- const definition = JSON.stringify({ name: SERVER_NAME, command: ix.command, args: ix.args });
- const result = await run("code", ["--add-mcp", definition]);
- if (!result.ok) throw new Error(firstLine(result.stderr) || "code --add-mcp failed");
+ // Written rather than handed to `code --add-mcp`, so the write lands in
+ // the same file `inspect` reads. Shelling out needed `code` on PATH —
+ // which a GUI-only install does not have — and passed a JSON argument,
+ // which Windows cannot encode.
+ writeJson(vsCodeUserConfig(), (config) => {
+ const servers = (config.servers ??= {}) as Record<string, unknown>;
+ servers[SERVER_NAME] = { command: ix.command, args: ix.args };
+ });
},
},
{
@@ -351,6 +568,7 @@ export function createHosts(writeJson: (path: string, mutate: (config: Record<st
label: "Cursor",
bin: "cursor",
target: cursorConfigPath(),
+ detectInstalled: fileHostInstalled("cursor", cursorConfigPath()),
async inspect() {
return inspectJsonFile(cursorConfigPath(), "mcpServers");
},
@@ -367,6 +585,7 @@ export function createHosts(writeJson: (path: string, mutate: (config: Record<st
label: "opencode",
bin: "opencode",
target: opencodeConfigPath(),
+ detectInstalled: fileHostInstalled("opencode", opencodeConfigPath()),
async inspect() {
return inspectJsonFile(opencodeConfigPath(), "mcp");
},
diff --git a/ix-cli/src/mcp/install.ts b/ix-cli/src/mcp/install.ts
index af8b5a15..996e7d79 100644
--- a/ix-cli/src/mcp/install.ts
+++ b/ix-cli/src/mcp/install.ts
@@ -5,6 +5,7 @@ import {
createHosts,
isOnPath,
SERVER_NAME,
+ stripJsonComments,
type HostStatus,
type McpHost,
type Registration,
@@ -21,7 +22,9 @@ export type Outcome =
| "failed"
| "would-register"
/** Doctor only: host is present and the name is free, but nothing points at us. */
- | "not-registered";
+ | "not-registered"
+ /** Doctor only: ours, but the launcher path it records is gone. */
+ | "stale";
export interface HostReport extends HostStatus {
outcome: Outcome;
@@ -89,7 +92,13 @@ export function writeJsonConfig(path: string, mutate: (config: Record<string, un
if (raw.trim() !== "") {
let parsed: unknown;
try {
- parsed = JSON.parse(raw);
+ // Comments are stripped for the same reason the read path strips them:
+ // VS Code and Cursor both accept JSON-with-comments here. Parsing raw
+ // meant a hand-annotated config passed `inspect`, reported its name as
+ // free, and then hard-failed the write telling the user to fix a file
+ // their editor reads without complaint. The `.bak` below is what makes
+ // losing those comments recoverable.
+ parsed = JSON.parse(stripJsonComments(raw));
} catch {
// Refuse rather than overwrite: a file we cannot parse is a file whose
// contents we would be destroying.
@@ -112,10 +121,42 @@ export function writeJsonConfig(path: string, mutate: (config: Record<string, un
function outcomeFor(registration: Registration, force: boolean): Exclude<Outcome, "not-installed" | "failed"> | null {
if (registration === "none") return null; // proceed
if (registration === "ours") return "already-registered";
+ // Already ours, just pointing at a launcher that no longer exists. Rewriting
+ // it is the repair, and it needs no --force: nothing of the user's is at risk.
+ if (registration === "stale") return null;
return force ? null : "conflict";
}
+/**
+ * The hosts named by `--host`, or all of them.
+ *
+ * An unrecognised id used to filter every host out and report success, so a
+ * typo in a setup script (`--host claude-code`, when the id is `claude`)
+ * registered nothing and exited 0.
+ */
+function selectHosts(all: McpHost[], only?: string[]): McpHost[] {
+ if (!only?.length) return all;
+ const known = new Set(all.map((host) => host.id));
+ const unknown = only.filter((id) => !known.has(id));
+ if (unknown.length > 0) {
+ throw new Error(
+ `unknown host ${unknown.map((id) => `'${id}'`).join(", ")} — known hosts: ${[...known].join(", ")}`,
+ );
+ }
+ return all.filter((host) => only.includes(host.id));
+}
+
+/** Whether the host is present. Falls back to the PATH probe. */
+async function hostInstalled(host: McpHost): Promise<boolean> {
+ return host.detectInstalled ? host.detectInstalled() : isOnPath(host.bin);
+}
+
function noteFor(registration: Registration, detail?: string): string | undefined {
+ if (registration === "stale") {
+ return detail
+ ? `registered, but its launcher is gone: ${detail}`
+ : "registered, but the launcher path it records no longer exists";
+ }
if (registration === "other") {
return detail
? `'${SERVER_NAME}' already points at something else: ${detail}`
@@ -128,16 +169,14 @@ function noteFor(registration: Registration, detail?: string): string | undefine
}
export async function runInstall(options: InstallOptions = {}): Promise<InstallReport> {
- const hosts = (options.hosts ?? createHosts(writeJsonConfig)).filter(
- (host) => !options.only?.length || options.only.includes(host.id),
- );
+ const hosts = selectHosts(options.hosts ?? createHosts(writeJsonConfig), options.only);
const reports: HostReport[] = [];
for (const host of hosts) {
const base = { id: host.id, label: host.label, target: host.target };
- if (!(await isOnPath(host.bin))) {
+ if (!(await hostInstalled(host))) {
reports.push({ ...base, installed: false, registration: "none", outcome: "not-installed" });
continue;
}
@@ -175,15 +214,22 @@ export async function runInstall(options: InstallOptions = {}): Promise<InstallR
};
}
+/** What each registration means when nothing is being written. */
+const DOCTOR_OUTCOME: Record<Registration, Outcome> = {
+ ours: "already-registered",
+ none: "not-registered",
+ stale: "stale",
+ other: "conflict",
+ unknown: "conflict",
+};
+
export async function runDoctor(options: { hosts?: McpHost[]; only?: string[] } = {}): Promise<DoctorReport> {
- const hosts = (options.hosts ?? createHosts(writeJsonConfig)).filter(
- (host) => !options.only?.length || options.only.includes(host.id),
- );
+ const hosts = selectHosts(options.hosts ?? createHosts(writeJsonConfig), options.only);
const reports: HostReport[] = [];
for (const host of hosts) {
const base = { id: host.id, label: host.label, target: host.target };
- if (!(await isOnPath(host.bin))) {
+ if (!(await hostInstalled(host))) {
reports.push({ ...base, installed: false, registration: "none", outcome: "not-installed" });
continue;
}
@@ -192,8 +238,7 @@ export async function runDoctor(options: { hosts?: McpHost[]; only?: string[] }
...base,
installed: true,
registration,
- outcome:
- registration === "ours" ? "already-registered" : registration === "none" ? "not-registered" : "conflict",
+ outcome: DOCTOR_OUTCOME[registration],
note: noteFor(registration, detail),
});
}
diff --git a/ix-cli/src/mcp/runner.ts b/ix-cli/src/mcp/runner.ts
index 50d14d25..0bd445ac 100644
--- a/ix-cli/src/mcp/runner.ts
+++ b/ix-cli/src/mcp/runner.ts
@@ -10,6 +10,8 @@ import { Command, CommanderError } from "commander";
import { registerOssCommands, registerProStubs } from "../cli/register/oss.js";
import { tryLoadProCommands } from "../cli/register/pro-loader.js";
+import { resetReadScope } from "../cli/resolve.js";
+import { releaseHeldLocks } from "../cli/single-flight.js";
const execFileAsync = promisify(execFile);
const CLI_ENTRYPOINT = fileURLToPath(new URL("../cli/main.js", import.meta.url));
@@ -64,6 +66,9 @@ interface ActiveRun {
* Node 22, so it cannot be. Isolating output per async context while the exit
* code stayed global would attribute a call's output to the right result and
* its success to the wrong one. See `createInProcessRunner`.
+ *
+ * A timeout breaks that serialization — the queue advances while the abandoned
+ * command runs on — which is what {@link liveOrphans} exists to contain.
*/
let activeRun: ActiveRun | null = null;
let captureInstalled = false;
@@ -79,6 +84,36 @@ let redirectIdleStdout = false;
*/
const runContext = new AsyncLocalStorage<ActiveRun>();
+/**
+ * Commands abandoned at their timeout that are still running.
+ *
+ * Nothing cancels a timed-out command — no Ix command takes an abort signal —
+ * so it keeps writing to the process globals after the queue has moved on.
+ * Output is attributed per run through {@link runContext}; `process.exitCode`
+ * cannot be, because it is a non-configurable accessor and so cannot be made
+ * context-local (verified on Node 26: `Object.defineProperty` throws).
+ *
+ * What is knowable is when it is untrustworthy. While an orphan is alive, its
+ * late `process.exitCode = 1` — the failure shape most commands use — is
+ * indistinguishable from the running command's own, and reading it reported a
+ * *successful* tool call as failed, with its real answer buried inside an
+ * `error` string. A run started while this set is non-empty therefore ignores
+ * `process.exitCode` and judges only by what the command threw.
+ */
+const liveOrphans = new Set<Promise<void>>();
+
+/**
+ * Commands whose effects invalidate `cli/resolve.ts`'s per-cwd scope cache.
+ *
+ * That cache never expires — one command per process *was* its invalidation.
+ * Left alone in a long-lived server, the first tool call in a not-yet-ingested
+ * repo pinned the scope, and every read after an `ix_map` that stitched the
+ * repo into a System still resolved against the pre-map workspace: "not found"
+ * for symbols the agent had just watched itself ingest, until the host
+ * restarted the server.
+ */
+const SCOPE_CHANGING_COMMANDS = new Set(["map", "ingest"]);
+
/** The run a write belongs to: its own context first, else whoever holds the globals. */
function resolveRun(): ActiveRun | null {
return runContext.getStore() ?? activeRun;
@@ -256,6 +291,48 @@ export interface InProcessRunnerOptions {
maxOutputBytes?: number;
}
+/**
+ * Undo the process-lifetime state a finished command left behind.
+ *
+ * Every one of these was released by process exit when a command *was* a
+ * process. In a server that never exits they are leaks, and each of them makes
+ * the next tool call answer from something stale rather than fail loudly.
+ */
+function afterCommand(args: string[]): void {
+ if (SCOPE_CHANGING_COMMANDS.has(args[0] ?? "")) resetReadScope();
+
+ // `ix map` takes a single-flight lock it never releases itself, relying on
+ // process exit. Held by a long-lived server, the lock file names the server's
+ // own live PID — so it never reads as stale — and every later ix_map coalesces
+ // and returns an empty success while the graph goes unrefreshed. It also
+ // blocks the user's own editor-hook `ix map` for the same 20 minutes. Skipped
+ // while an orphan is in flight: a map still running is entitled to its lock.
+ if (liveOrphans.size === 0) releaseHeldLocks();
+}
+
+/**
+ * Replace the CLI's fatal error handlers for the lifetime of the server.
+ *
+ * `main.ts` installs `unhandledRejection`/`uncaughtException` handlers whose
+ * every path ends in `process.exit(1)`. That is right for one command in one
+ * process and fatal for a server: a stray rejection from any command's
+ * fire-and-forget work would either exit outright, or — once the in-process
+ * capture is installed — throw ProcessExitSignal out of the handler, which
+ * becomes an uncaughtException, which throws again from inside the fatal
+ * handler and aborts Node. Either way the client loses the server and all its
+ * tools mid-session over an error that belonged to one tool call.
+ */
+export function installServerErrorHandlers(): void {
+ process.removeAllListeners("uncaughtException");
+ process.removeAllListeners("unhandledRejection");
+ const report = (label: string) => (error: unknown) => {
+ const detail = error instanceof Error ? (error.stack ?? error.message) : String(error);
+ pristineStderrWrite(`[ix mcp] ${label}: ${detail}\n`);
+ };
+ process.on("uncaughtException", report("uncaught exception"));
+ process.on("unhandledRejection", report("unhandled rejection"));
+}
+
async function executeInProcess(
args: string[],
timeoutMs: number,
@@ -277,15 +354,29 @@ async function executeInProcess(
process.exitCode = undefined;
activeRun = run;
+ // Decided before the command starts: an orphan already in flight can write
+ // process.exitCode at any point during this run, and there is no way to tell
+ // its write from this command's own.
+ const exitCodeIsOurs = liveOrphans.size === 0;
+
let failure: string | null = null;
let commandExitCode: number | string | undefined;
+ const work = runContext.run(run, () => program.parseAsync(args, { from: "user" }));
+ // Settles either way and never rejects, so it can be watched without adding a
+ // second rejection handler to `work`.
+ let commandSettled = false;
+ const finished = work.then(
+ () => {
+ commandSettled = true;
+ },
+ () => {
+ commandSettled = true;
+ },
+ );
+
try {
- await withTimeout(
- runContext.run(run, () => program.parseAsync(args, { from: "user" })),
- timeoutMs,
- args[0] ?? "ix",
- );
+ await withTimeout(work, timeoutMs, args[0] ?? "ix");
} catch (error) {
if (error instanceof ProcessExitSignal) {
// An explicit exit; the command already explained itself on stdout/stderr.
@@ -297,10 +388,20 @@ async function executeInProcess(
failure = error instanceof Error ? error.message : String(error);
}
} finally {
- commandExitCode = commandExitCode ?? process.exitCode;
+ commandExitCode = commandExitCode ?? (exitCodeIsOurs ? process.exitCode : undefined);
process.exitCode = callerExitCode;
run.closed = true;
activeRun = null;
+
+ if (commandSettled) {
+ afterCommand(args);
+ } else {
+ liveOrphans.add(finished);
+ void finished.then(() => {
+ liveOrphans.delete(finished);
+ afterCommand(args);
+ });
+ }
}
const ok = failure === null && (commandExitCode === undefined || commandExitCode === 0);
@@ -317,7 +418,9 @@ async function executeInProcess(
* Booting `main.js` costs ~0.58s before any query runs, which a tool-calling
* agent pays on every hop of a `locate → callers → read` chain. Running the
* same command tree here removes that entirely and lets `cli/resolve.ts`'s
- * per-cwd scope cache survive between calls.
+ * per-cwd scope cache survive between calls — but only between *reads*: see
+ * {@link afterCommand} for the state whose sole invalidation used to be the
+ * process ending, and which is therefore reset per command here.
*
* Runs are serialized. Commands report failure through `process.exitCode` and
* print through `process.stdout`, both of which are process-wide, so two
diff --git a/ix-cli/src/mcp/server.ts b/ix-cli/src/mcp/server.ts
index abdfccf5..730fde22 100644
--- a/ix-cli/src/mcp/server.ts
+++ b/ix-cli/src/mcp/server.ts
@@ -7,6 +7,7 @@ import {
createProtocolStdout,
DEFAULT_TIMEOUT_MS,
detectPro,
+ installServerErrorHandlers,
resolveDefaultRunner,
type IxRunner,
} from "./runner.js";
@@ -69,6 +70,26 @@ interface CreateServerOptions {
type ToolInput = Record<string, unknown>;
+/**
+ * One Ix invocation, with its options kept apart from its positional values.
+ *
+ * The split is what lets every positional go behind a `--` separator. Appending
+ * them as bare tokens let commander read any value beginning with `-` as a
+ * flag: `ix_text` searching for `--force` failed outright, and searching for
+ * `--path` quietly consumed the following `--limit` as its value and ranked
+ * hits for the literal text `20` instead — a wrong answer the caller had no way
+ * to detect.
+ */
+interface IxArgv {
+ command: string;
+ positionals: string[];
+ options: string[];
+}
+
+function ix(command: string, positionals: string[] = [], options: string[] = []): IxArgv {
+ return { command, positionals, options };
+}
+
export function createIxMcpServer(options: CreateServerOptions = {}): McpServer {
const version = options.version ?? "0.0.0";
@@ -87,14 +108,14 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer
});
registerTool(server, "ix_health", "Check Ix backend and graph readiness", {}, async () =>
- runFormatted(runIx, "ix_health", ["status"]),
+ runFormatted(runIx, "ix_health", ix("status")),
);
registerTool(
server,
"ix_locate",
"Resolve a symbol to its canonical graph-backed target",
{ symbol: z.string().min(1) },
- async (input) => runFormatted(runIx, "ix_locate", ["locate", stringArg(input, "symbol")]),
+ async (input) => runFormatted(runIx, "ix_locate", ix("locate", [stringArg(input, "symbol")])),
);
registerTool(
server,
@@ -107,15 +128,10 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer
language: z.string().min(1).optional(),
},
async (input) => {
- const args = [
- "text",
- stringArg(input, "pattern"),
- "--limit",
- numberArg(input, "limit").toString(),
- ];
- pushOption(args, "--path", input.path);
- pushOption(args, "--language", input.language);
- return runFormatted(runIx, "ix_text", args);
+ const options = [`--limit=${numberArg(input, "limit")}`];
+ pushOption(options, "--path", input.path);
+ pushOption(options, "--language", input.language);
+ return runFormatted(runIx, "ix_text", ix("text", [stringArg(input, "pattern")], options));
},
);
registerTool(
@@ -123,7 +139,7 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer
"ix_impact",
"Analyze the blast radius and risk of changing a symbol or file",
{ target: z.string().min(1) },
- async (input) => runFormatted(runIx, "ix_impact", ["impact", stringArg(input, "target")]),
+ async (input) => runFormatted(runIx, "ix_impact", ix("impact", [stringArg(input, "target")])),
);
registerTool(
server,
@@ -131,9 +147,8 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer
"Ingest one path or refresh the full workspace architecture map",
{ file: z.string().min(1).optional() },
async (input) => {
- const args = ["map"];
- if (typeof input.file === "string") args.push(input.file);
- return runJson(runIx, "ix_map", args, 120_000);
+ const positionals = typeof input.file === "string" ? [input.file] : [];
+ return runJson(runIx, "ix_map", ix("map", positionals), 120_000);
},
);
registerTool(
@@ -141,14 +156,14 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer
"ix_overview",
"Return the structural overview of a symbol, file, or subsystem",
{ target: z.string().min(1) },
- async (input) => runFormatted(runIx, "ix_overview", ["overview", stringArg(input, "target")]),
+ async (input) => runFormatted(runIx, "ix_overview", ix("overview", [stringArg(input, "target")])),
);
registerTool(
server,
"ix_read",
"Read graph-bounded source for a symbol or indexed file",
{ symbol: z.string().min(1) },
- async (input) => runFormatted(runIx, "ix_read", ["read", stringArg(input, "symbol")]),
+ async (input) => runFormatted(runIx, "ix_read", ix("read", [stringArg(input, "symbol")])),
);
registerTool(
server,
@@ -161,14 +176,12 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer
summary: z.boolean().default(false),
},
async (input) => {
- const args = [
- "diff",
+ const positionals = [
numberArg(input, "from_rev").toString(),
numberArg(input, "to_rev").toString(),
];
- if (typeof input.target === "string") args.push(input.target);
- if (input.summary === true) args.push("--summary");
- return runFormatted(runIx, "ix_diff", args);
+ if (typeof input.target === "string") positionals.push(input.target);
+ return runFormatted(runIx, "ix_diff", ix("diff", positionals, input.summary === true ? ["--summary"] : []));
},
);
registerSymbolTool(server, runIx, "ix_callers", "List incoming call edges", "callers");
@@ -184,12 +197,9 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer
depth: z.number().int().min(1).max(5).default(2),
},
async (input) =>
- runFormatted(runIx, "ix_depends", [
- "depends",
- stringArg(input, "symbol"),
- "--depth",
- numberArg(input, "depth").toString(),
- ]),
+ runFormatted(runIx, "ix_depends", ix("depends", [stringArg(input, "symbol")], [
+ `--depth=${numberArg(input, "depth")}`,
+ ])),
);
registerTool(
server,
@@ -200,9 +210,9 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer
to: z.string().min(1).optional(),
},
async (input) => {
- const args = ["trace", stringArg(input, "symbol")];
- pushOption(args, "--to", input.to);
- return runFormatted(runIx, "ix_trace", args);
+ const options: string[] = [];
+ pushOption(options, "--to", input.to);
+ return runFormatted(runIx, "ix_trace", ix("trace", [stringArg(input, "symbol")], options));
},
);
registerSymbolTool(
@@ -223,35 +233,34 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer
path: z.string().min(1).optional(),
},
async (input) => {
- const args = [
- "rank",
- "--by",
- stringArg(input, "by"),
- "--kind",
- stringArg(input, "kind"),
- "--top",
- numberArg(input, "top").toString(),
+ const options = [
+ `--by=${stringArg(input, "by")}`,
+ `--kind=${stringArg(input, "kind")}`,
+ `--top=${numberArg(input, "top")}`,
];
- pushOption(args, "--path", input.path);
- return runFormatted(runIx, "ix_rank", args);
+ pushOption(options, "--path", input.path);
+ return runFormatted(runIx, "ix_rank", ix("rank", [], options));
},
);
registerTool(
server,
"ix_inventory",
- "List graph entities within a repository path",
+ "List graph entities by kind, optionally scoped to a repository path",
{
- path: z.string().min(1),
+ // Optional, and `--limit` is forwarded, because the CLI's own contract is
+ // `--kind` required and `--path` an optional filter. Requiring a path
+ // made the documented `ix inventory --kind function` call impossible over
+ // MCP, and dropping the limit capped every answer at the CLI's default 50
+ // with no way to ask for more.
kind: z.string().min(1).default("file"),
+ path: z.string().min(1).optional(),
+ limit: z.number().int().min(1).max(500).default(50),
+ },
+ async (input) => {
+ const options = [`--kind=${stringArg(input, "kind")}`, `--limit=${numberArg(input, "limit")}`];
+ pushOption(options, "--path", input.path);
+ return runFormatted(runIx, "ix_inventory", ix("inventory", [], options));
},
- async (input) =>
- runFormatted(runIx, "ix_inventory", [
- "inventory",
- "--kind",
- stringArg(input, "kind"),
- "--path",
- stringArg(input, "path"),
- ]),
);
registerTool(
server,
@@ -264,17 +273,17 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer
async (input) => runSmells(runIx, input),
);
registerTool(server, "ix_stats", "Return graph-wide statistics", {}, async () =>
- runFormatted(runIx, "ix_stats", ["stats"]),
+ runFormatted(runIx, "ix_stats", ix("stats")),
);
registerTool(server, "ix_subsystems", "List graph-derived subsystems", {}, async () =>
- runFormatted(runIx, "ix_subsystems", ["subsystems"]),
+ runFormatted(runIx, "ix_subsystems", ix("subsystems")),
);
registerTool(
server,
"ix_history",
"Show provenance and patch history for a file or symbol",
{ target: z.string().min(1) },
- async (input) => runFormatted(runIx, "ix_history", ["history", stringArg(input, "target")]),
+ async (input) => runFormatted(runIx, "ix_history", ix("history", [stringArg(input, "target")])),
);
registerTool(
server,
@@ -287,20 +296,20 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer
since: z.string().min(1).optional().describe("ISO 8601 date"),
},
async (input) => {
- const args = ["ingest"];
- if (typeof input.path === "string") args.push(input.path);
- pushOption(args, "--github", input.github);
- pushOption(args, "--since", input.since);
- if (typeof input.github === "string") args.push("--limit", numberArg(input, "limit").toString());
+ const options: string[] = [];
+ pushOption(options, "--github", input.github);
+ pushOption(options, "--since", input.since);
+ if (typeof input.github === "string") options.push(`--limit=${numberArg(input, "limit")}`);
+ const positionals = typeof input.path === "string" ? [input.path] : [];
// Ingestion walks the tree or pages a GitHub API, so it gets the same
// headroom as ix_map rather than the default read timeout.
- return runJson(runIx, "ix_ingest", args, 120_000);
+ return runJson(runIx, "ix_ingest", ix("ingest", positionals, options), 120_000);
},
);
if (options.proAvailable) {
registerTool(server, "ix_briefing", "Load the Ix Pro session briefing", {}, async () =>
- runJson(runIx, "ix_briefing", ["briefing"]),
+ runJson(runIx, "ix_briefing", ix("briefing")),
);
registerTool(
server,
@@ -308,9 +317,9 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer
"List Ix Pro architecture decisions, optionally scoped to a path",
{ path: z.string().min(1).optional() },
async (input) => {
- const args = ["decisions"];
- pushOption(args, "--path", input.path);
- return runJson(runIx, "ix_decisions", args);
+ const options: string[] = [];
+ pushOption(options, "--path", input.path);
+ return runJson(runIx, "ix_decisions", ix("decisions", [], options));
},
);
registerTool(
@@ -323,9 +332,9 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer
affects: z.string().min(1).optional().describe("entity the decision affects"),
},
async (input) => {
- const args = ["decide", stringArg(input, "title"), "--rationale", stringArg(input, "rationale")];
- pushOption(args, "--affects", input.affects);
- return runJson(runIx, "ix_decide", args);
+ const options = [`--rationale=${stringArg(input, "rationale")}`];
+ pushOption(options, "--affects", input.affects);
+ return runJson(runIx, "ix_decide", ix("decide", [stringArg(input, "title")], options));
},
);
}
@@ -334,6 +343,9 @@ export function createIxMcpServer(options: CreateServerOptions = {}): McpServer
}
export async function startIxMcpServer(version = "0.0.0"): Promise<void> {
+ // Before anything can throw: the CLI's own handlers exit the process on any
+ // stray error, which for a server means losing every tool mid-session.
+ installServerErrorHandlers();
const server = createIxMcpServer({ version, proAvailable: await detectPro() });
// A dedicated handle on fd 1 rather than process.stdout, which the in-process
// runner patches to capture command output.
@@ -348,7 +360,7 @@ function registerSymbolTool(
command: string,
): void {
registerTool(server, name, description, { symbol: z.string().min(1) }, async (input) =>
- runFormatted(runIx, name, [command, stringArg(input, "symbol")]),
+ runFormatted(runIx, name, ix(command, [stringArg(input, "symbol")])),
);
}
@@ -364,22 +376,34 @@ function registerTool(
);
}
+/**
+ * Flatten to argv: options first, then every positional behind `--`.
+ *
+ * Option values use the `--flag=value` form for the same reason, so a value of
+ * `--rationale` cannot be mistaken for the next flag.
+ */
+function toArgv(argv: IxArgv, format: string): string[] {
+ const args = [argv.command, ...argv.options, `--format=${format}`];
+ if (argv.positionals.length > 0) args.push("--", ...argv.positionals);
+ return args;
+}
+
async function runFormatted(
runIx: IxRunner,
tool: string,
- args: string[],
+ argv: IxArgv,
timeoutMs = DEFAULT_TIMEOUT_MS,
): Promise<CallToolResult> {
- return runCommand(runIx, tool, [...args, "--format", "llm"], timeoutMs);
+ return runCommand(runIx, tool, toArgv(argv, "llm"), timeoutMs);
}
async function runJson(
runIx: IxRunner,
tool: string,
- args: string[],
+ argv: IxArgv,
timeoutMs = DEFAULT_TIMEOUT_MS,
): Promise<CallToolResult> {
- return runCommand(runIx, tool, [...args, "--format", "json"], timeoutMs);
+ return runCommand(runIx, tool, toArgv(argv, "json"), timeoutMs);
}
async function runCommand(
@@ -401,7 +425,7 @@ async function runCommand(
}
async function runSmells(runIx: IxRunner, input: ToolInput): Promise<CallToolResult> {
- const result = await runIx(["smells", "--format", "json"], DEFAULT_TIMEOUT_MS);
+ const result = await runIx(toArgv(ix("smells"), "json"), DEFAULT_TIMEOUT_MS);
if (!result.ok) {
const detail = result.stderr.trim() || result.stdout.trim() || "smells failed without output";
return textResult(JSON.stringify({ error: detail, tool: "ix_smells" }), true);
@@ -419,8 +443,12 @@ async function runSmells(runIx: IxRunner, input: ToolInput): Promise<CallToolRes
if (path === null || !isRecord(candidate) || typeof candidate.file !== "string") {
return path === null;
}
- const file = normalizePath(candidate.file);
- return file === path || file.startsWith(`${path}/`);
+ // Substring, matching what `--path` means everywhere else in the CLI
+ // ("Filter by source file path substring" on inventory, the same on
+ // rank). Prefix matching answered `{"count": 0}` — a confident "no
+ // architecture smells here" — for the `src` an agent had just used
+ // successfully against ix_inventory on files stored as `ix-cli/src/...`.
+ return normalizePath(candidate.file).includes(path);
})
.slice(0, limit);
@@ -442,9 +470,9 @@ function numberArg(input: ToolInput, key: string): number {
return input[key] as number;
}
-function pushOption(args: string[], flag: string, value: unknown): void {
+function pushOption(options: string[], flag: string, value: unknown): void {
if (typeof value === "string" && value.length > 0) {
- args.push(flag, value);
+ options.push(`${flag}=${value}`);
}
}