Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
fix(mcp): repair the orphan bookkeeping, lock ownership and Windows quoting (#401)
Joseph Mikhail8b117da26c39
diff --git a/README.md b/README.mdindex d2be9121..cf292a19 100644--- a/README.md+++ b/README.md@@ -71,18 +71,24 @@ ix mcp doctor # check each client's registration`install` knows Claude Code, Codex, Cursor, VS Code, Gemini CLI, OpenClaw andopencode. It writes through each client's own MCP command where one exists-(`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.+(`claude mcp add`, `codex mcp add`, `gemini mcp add`, and `openclaw mcp set`+everywhere but Windows), so the client owns its config format. Cursor, VS Code+and opencode are edited directly instead, as is OpenClaw on Windows — its+registration is passed as a JSON argument, which cmd cannot carry intact. Every+direct write is merged in place with a `.bak` kept alongside. Cursor, VS Code+and opencode 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 differentserver — an earlier Ix plugin, say — that client is reported and left exactly asit 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`.+unrecognised id is an error rather than a silent no-op. Where a client's own+config can be read back — Cursor, VS Code, opencode, and OpenClaw off Windows —+`doctor` also reports a registration of ours whose recorded launcher path has+since disappeared, and `install` repairs it. The clients that answer with a+rendered table instead expose no stored command, so a launcher that has moved+there is not detected: clear the name with that client's own command+(`claude mcp remove ix-memory`) and re-run `ix mcp install`.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.tsindex 55788a30..9bd71ab5 100644--- a/ix-cli/src/cli/__tests__/mcp-install.test.ts+++ b/ix-cli/src/cli/__tests__/mcp-install.test.ts@@ -1,4 +1,4 @@-import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -339,28 +339,71 @@ 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({+ it.each([+ String.raw`C:\Users\gone\AppData\Roaming\npm\ix.cmd`,+ // A Windows username with a space is the common case, not the edge one; a+ // first attempt that recovered the path by regex stopped at the space and+ // read this as healthy — for most of the users the check was written for.+ String.raw`C:\Users\Jane Doe\AppData\Roaming\npm\ix.cmd`,+ String.raw`C:\Program Files\nodejs\ix.cmd`,+ "/opt/my tools/bin/ix",+ ])("reports %s as stale once it no longer resolves", (command) => {+ // What a registration looks like after an nvm switch or a reinstall to a+ // different prefix. Read as healthy, install skipped the one host it should+ // have repaired while doctor agreed it was fine.+ expect(classifyListing(`ix-memory ${JSON.stringify({ command, args: ["mcp"] })}`, command)).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");+ // Written under a directory with a space in it, so this cannot pass merely+ // by failing to recognise the path as a path.+ const dir = join(tempDir(), "my tools");+ mkdirSync(dir, { recursive: true });+ const launcher = join(dir, "ix.cmd");writeFileSync(launcher, "@echo off");- expect(classifyListing(`ix-memory ${JSON.stringify({ command: launcher, args: ["mcp"] })}`).registration).toBe(+ expect(+ classifyListing(`ix-memory ${JSON.stringify({ command: launcher, args: ["mcp"] })}`, launcher).registration,+ ).toBe("ours");+ });++ // Windows-only by nature: a UNC path is a network location there, and stat+ // fails on it with something other than ENOENT. Everywhere else those+ // backslashes are ordinary filename characters, so the path really is absent+ // and `stale` is the right answer.+ it.skipIf(process.platform !== "win32")("leaves a launcher it cannot conclusively stat alone", () => {+ // A file server being offline is not evidence the launcher is gone, and+ // `stale` triggers a rewrite with no --force, so only ENOENT counts.+ const unc = String.raw`\\server-that-does-not-exist\share\npm\ix.cmd`;++ expect(classifyListing(`ix-memory ${JSON.stringify({ command: unc, args: ["mcp"] })}`, unc).registration).toBe("ours",);});+ it("does not invent a stale launcher out of a suffix of a live path", () => {+ // A launcher that genuinely exists, sitting under a `.../npm/ix.cmd` tail.+ // A regex allowed to start at an interior `/` matched only that tail,+ // stat'd `/npm/ix.cmd` from the filesystem root, found nothing, and called+ // a working registration stale — so `install` rewrote it with no --force+ // and `doctor` exited 1 on a healthy machine. The fixture has to use a path+ // that exists, or it cannot tell the two behaviours apart.+ const dir = join(tempDir(), "Program Files", "npm");+ mkdirSync(dir, { recursive: true });+ const launcher = join(dir, "ix.cmd");+ writeFileSync(launcher, "@echo off");+ // Both properties are needed to reproduce it: the space stops an+ // unanchored match from spanning the path from its start, and the forward+ // slashes then give it an interior `/npm/ix.cmd` to latch onto instead.+ // A temp path without either cannot tell the two behaviours apart.+ const rendered = launcher.replaceAll("\\", "/");++ expect(classifyListing(`ix-memory ${rendered} mcp - enabled`).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.@@ -399,6 +442,21 @@ describe("quoteForCmd", () => {);});+ it.each([+ String.raw`C:\Users\R&D\npm\ix.cmd`,+ String.raw`C:\a^b\ix.cmd`,+ String.raw`C:\a|b\ix.cmd`,+ ])("quotes %s, which carries a metacharacter but no space", (path) => {+ // The case the test above cannot reach, because its fixture has a space and+ // so takes the quoting branch either way. A "does this need quoting?" check+ // that asks only about whitespace lets these through bare: verified by+ // round-trip that `C:\Users\R&D\npm\ix.cmd` then arrives as `C:\Users\R`+ // with cmd running `D\npm\ix.cmd` as a second command, and that+ // `C:\a^b\ix.cmd` arrives silently as `C:\ab\ix.cmd` — a wrong launcher+ // path written into every host config and reported as a success.+ expect(quoteForCmd(path)).toBe(`"${path}"`);+ });+it("leaves an ordinary argument alone", () => {expect(quoteForCmd("--scope")).toBe("--scope");});@@ -418,6 +476,13 @@ describe("classifyShown", () => {expect(classifyShown("No MCP server named ix-memory\n", false).registration).toBe("none");});+ it("does not read an unrelated 'not found' as free", () => {+ // A missing plugin, or the host's own loader failing. Neither says anything+ // about our name, and reading one as an empty slot writes over whatever the+ // user had — the very thing this function exists to prevent.+ expect(classifyShown("Error: plugin 'foo' not found\n", false).registration).toBe("unknown");+ });+it("reads a definition body as ours", () => {const shown = 'MCP server "ix-memory":\n{\n "command": "ix",\n "args": ["mcp"]\n}';diff --git a/ix-cli/src/cli/__tests__/mcp-runner.test.ts b/ix-cli/src/cli/__tests__/mcp-runner.test.tsindex 9e5b334f..b8e25519 100644--- a/ix-cli/src/cli/__tests__/mcp-runner.test.ts+++ b/ix-cli/src/cli/__tests__/mcp-runner.test.ts@@ -1,11 +1,11 @@-import { mkdtempSync, rmSync } from "node:fs";+import { existsSync, mkdtempSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { Command } from "commander";import { afterEach, describe, expect, it, vi } from "vitest";-import { acquireMapLock } from "../single-flight.js";+import { acquireMapLock, lockPathForTest } from "../single-flight.js";import { createInProcessRunner, resolveDefaultRunner, runCurrentIx } from "../../mcp/runner.js";const resetReadScope = vi.hoisted(() => vi.fn());@@ -76,13 +76,30 @@ function createTestProgram(): Command {// 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");+ .option("--hold <ms>", "keep working after taking the lock", "0")+ .option("--hang", "take the lock and never finish")+ .action(async (opts: { hold: string; hang?: boolean }) => {+ const workspace = process.env.IX_TEST_WORKSPACE ?? "workspace";+ const lock = acquireMapLock(workspace, "ix map test");+ if (!lock) {+ console.log("coalesced");+ return;+ }+ if (opts.hang) await new Promise(() => {});+ await new Promise((resolve) => setTimeout(resolve, Number(opts.hold)));+ // Whether the lock this command took is still its own by the time it+ // finishes — anything releasing it mid-run reopens the window.+ console.log(existsSync(lockPathForTest(workspace)) ? "mapped" : "lock-taken-mid-run");});program.command("ingest").action(() => console.log("ingested"));+ // Never settles: a hung backend call, or a rejection that used to end the+ // process and is now only logged by the server's error handlers.+ program.command("hang").action(async () => {+ await new Promise(() => {});+ });+return program;}@@ -90,11 +107,51 @@ function testRunner() {return createInProcessRunner({ version: "test-version", createProgram: createTestProgram });}+/**+ * Run a body against a throwaway lock directory.+ *+ * Any test whose commands reach `acquireMapLock` needs this: without it the+ * lock lands in the developer's real `~/.ix/locks` and can block their own+ * `ix map` for twenty minutes.+ */+async function withLockDir(body: () => Promise<void>): Promise<void> {+ const dir = mkdtempSync(join(tmpdir(), "ix-mcp-lock-"));+ const previous = { lockDir: process.env.IX_LOCK_DIR, workspace: process.env.IX_TEST_WORKSPACE };+ process.env.IX_LOCK_DIR = dir;+ process.env.IX_TEST_WORKSPACE = join(dir, "workspace");+ try {+ await body();+ } finally {+ if (previous.lockDir === undefined) delete process.env.IX_LOCK_DIR;+ else process.env.IX_LOCK_DIR = previous.lockDir;+ if (previous.workspace === undefined) delete process.env.IX_TEST_WORKSPACE;+ else process.env.IX_TEST_WORKSPACE = previous.workspace;+ rmSync(dir, { recursive: true, force: true });+ }+}+const originalSubprocessFlag = process.env.IX_MCP_SUBPROCESS;-afterEach(() => {+/**+ * Longer than the slowest command any test here abandons and then waits for.+ *+ * Every test pays it, so it is kept close to what the slowest one needs rather+ * than padded: at 500 it added ~11s to this file alone. The two commands that+ * never settle are unaffected either way — their grace is what bounds them.+ */+const DRAIN_MS = 250;++afterEach(async () => {if (originalSubprocessFlag === undefined) delete process.env.IX_MCP_SUBPROCESS;else process.env.IX_MCP_SUBPROCESS = originalSubprocessFlag;++ // Several tests deliberately abandon a command at its timeout, and an+ // abandoned command outlives the test that started it. The runner's state is+ // module-level, so while one is in flight every later test sees exit codes+ // distrusted and a lock held — which is correct behaviour, and silently+ // changes what an unrelated assertion observes. Draining here rather than at+ // the end of each body means a failing assertion cannot skip it.+ await new Promise((resolve) => setTimeout(resolve, DRAIN_MS));});describe("in-process ix runner", () => {@@ -219,13 +276,7 @@ describe("in-process ix runner", () => {});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 {+ await withLockDir(async () => {const run = testRunner();const first = await run(["map"]);@@ -236,27 +287,120 @@ describe("in-process ix runner", () => {// 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("does not release a running command's lock when an orphan settles", async () => {+ await withLockDir(async () => {+ const run = testRunner();++ // Abandoned at 40ms, settles at ~150ms — part-way through the map below.+ const orphan = run(["slow", "--delay", "150", "--tag", "orphan"], 40);+ const mapped = run(["map", "--hold", "400"]);++ expect((await orphan).ok).toBe(false);+ // Releasing every lock the process holds drops more than the+ // finishing command's, so an orphan settling mid-map deleted the lock of+ // the map that was still running — reopening the exact window+ // single-flight exists to close.+ expect((await mapped).stdout).toBe("mapped\n");+ });+ });++ it("does not release a still-running command's lock when its own grace fires", async () => {+ await withLockDir(async () => {+ const run = createInProcessRunner({+ version: "test-version",+ createProgram: createTestProgram,+ orphanGraceMs: 60,+ });++ // Abandoned at 40ms, grace fires at ~100ms, still working until ~400ms.+ // The grace drops the exit-code distrust; the lock is a separate lifetime+ // and stays with the command that is still using it.+ expect((await run(["map", "--hold", "400"], 40)).ok).toBe(false);+ await new Promise((resolve) => setTimeout(resolve, 200));++ // An unrelated command completing must not take the running map's lock+ // with it — releasing everything held is what did, one call later than+ // the grace itself.+ expect((await run(["say", "unrelated"], 5_000)).stdout).toBe("out:unrelated\n");+ expect((await run(["map"], 5_000)).stdout).toBe("coalesced\n");+ });+ });++ it("releases the lock of a command that overran its grace once it finishes", async () => {+ await withLockDir(async () => {+ const run = createInProcessRunner({+ version: "test-version",+ createProgram: createTestProgram,+ orphanGraceMs: 40,+ });++ // The other direction: holding every lock back to protect a running+ // command stranded the ones whose command had genuinely finished, and the+ // next ix_map coalesced forever. Ownership is what lets both hold.+ await run(["map", "--hold", "250"], 30);+ await new Promise((resolve) => setTimeout(resolve, 400));++ expect((await run(["map"], 5_000)).stdout).toBe("mapped\n");+ });+ });++ it("invalidates the read scope for a command that never settles at all", async () => {+ await withLockDir(async () => {+ const run = createInProcessRunner({+ version: "test-version",+ createProgram: createTestProgram,+ orphanGraceMs: 40,+ });+ resetReadScope.mockClear();++ // A hung `ix map` has no settle to hang the invalidation off, so the+ // grace has to carry it — otherwise the pre-map scope stays pinned for+ // the life of the server with nothing left to clear it.+ await run(["map", "--hang"], 30);+ await new Promise((resolve) => setTimeout(resolve, 150));++ expect(resetReadScope).toHaveBeenCalled();+ });+ });++ it("stops distrusting the exit code once an abandoned command overruns its grace", async () => {+ await withLockDir(async () => {+ const run = createInProcessRunner({+ version: "test-version",+ createProgram: createTestProgram,+ orphanGraceMs: 60,+ });+ process.exitCode = undefined;++ // Never settles, so nothing will ever remove it from the orphan set.+ // Left unbounded, every later failure reports ok and no lock is ever+ // released again — both for the life of the server.+ await run(["hang"], 30);+ await new Promise((resolve) => setTimeout(resolve, 120));++ expect(await run(["soft-fail"], 30)).toMatchObject({ ok: false });+ expect((await run(["map"], 30)).stdout).toBe("mapped\n");+ expect((await run(["map"], 30)).stdout).toBe("mapped\n");+ });});it("invalidates the read-scope cache after a command that can change it", async () => {- const run = testRunner();- resetReadScope.mockClear();+ await withLockDir(async () => {+ const run = testRunner();+ resetReadScope.mockClear();- await run(["say", "read"]);- expect(resetReadScope).not.toHaveBeenCalled();+ 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);+ // `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 () => {diff --git a/ix-cli/src/cli/single-flight.ts b/ix-cli/src/cli/single-flight.tsindex 686de88a..69c24427 100644--- a/ix-cli/src/cli/single-flight.ts+++ b/ix-cli/src/cli/single-flight.ts@@ -127,8 +127,32 @@ export function acquireMapLock(workspaceRoot: string, label: string): LockHandle}// 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>();+// process exits" is no longer the end of a command — see releaseLocksOwnedBy.+/**+ * Whatever the caller uses to identify the command taking a lock.+ *+ * Opaque here: single-flight only ever compares it by identity.+ */+export type LockOwner = unknown;++let resolveOwner: () => LockOwner = () => null;++/**+ * Teach single-flight how to tell which command is acquiring a lock.+ *+ * "The process holds this lock" stopped meaning "this command holds it" when+ * `ix mcp` began running many commands in one process. Without an owner the+ * only available release is "drop everything", which either takes a still-+ * running command's lock away or, if held back to avoid that, never releases+ * the finished command's at all. The MCP runner installs a resolver backed by+ * its async-context store; the plain CLI leaves this unset and keeps releasing+ * on process exit, exactly as before.+ */+export function setLockOwnerResolver(resolve: () => LockOwner): void {+ resolveOwner = resolve;+}++const held = new Map<() => void, LockOwner>();function makeHandle(path: string): LockHandle {let released = false;@@ -147,7 +171,7 @@ function makeHandle(path: string): LockHandle {const onSigint = (): void => { release(); process.exit(130); };const onSigterm = (): void => { release(); process.exit(143); };- held.add(release);+ held.set(release, resolveOwner());// 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.@@ -158,7 +182,7 @@ function makeHandle(path: string): LockHandle {}/**- * Release every lock this process still holds.+ * Release the locks one command took, and only those.** `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@@ -166,9 +190,13 @@ function makeHandle(path: string): LockHandle {* 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.+ *+ * Scoped by owner rather than releasing everything, so a command that outlived+ * its timeout keeps the lock it is still using while a *different* command that+ * has genuinely finished still gives its own up.*/-export function releaseHeldLocks(): void {- for (const release of [...held]) release();+export function releaseLocksOwnedBy(owner: LockOwner): void {+ for (const [release, heldBy] of [...held]) if (heldBy === owner) release();}// ── Test-only surface ──────────────────────────────────────────────────────diff --git a/ix-cli/src/mcp/hosts.ts b/ix-cli/src/mcp/hosts.tsindex c3b38f81..ef1026a1 100644--- a/ix-cli/src/mcp/hosts.ts+++ b/ix-cli/src/mcp/hosts.ts@@ -69,6 +69,20 @@ export interface Launcher {args: string[];}+/**+ * Characters an argument may contain and still be passed to cmd bare.+ *+ * A whitelist rather than a blacklist of whitespace and quotes: `&`, `^`, `|`,+ * `<` and `>` are all argument-splitting or escaping characters to cmd, and a+ * launcher path under `C:\Users\R&D\` contains no space, so a+ * "does it need quoting?" test that asks only about whitespace let it through+ * bare. Verified against a round-trip echo: `C:\Users\R&D\npm\ix.cmd` arrived+ * as `C:\Users\R`, with cmd then trying to run `D\npm\ix.cmd` as a second+ * command, and `C:\a^b\ix.cmd` arrived silently as `C:\ab\ix.cmd` — a wrong+ * launcher written into every host config and reported as a success.+ */+const SAFE_BARE_ARG = /^[A-Za-z0-9_@:.,=+\-\\/]+$/;+/*** Quote one argument for a Windows command line.*@@ -81,7 +95,7 @@ export interface Launcher {* round-trip echo: every cmd encoding mangles such a value.*/export function quoteForCmd(arg: string): string {- if (arg !== "" && !/[\s"]/.test(arg)) return arg;+ if (SAFE_BARE_ARG.test(arg)) return arg;let out = '"';let slashes = 0;for (const ch of arg) {@@ -119,11 +133,13 @@ async function run(bin: string, args: string[]): Promise<RunResult> {const options = { encoding: "utf8" as const, timeout: HOST_CLI_TIMEOUT_MS, windowsHide: true };try {if (platform() === "win32") {- const unencodable = [bin, ...args].find((arg) => arg.includes('"'));+ // Refused rather than mangled: a half-parsed argument reaches the host as+ // several arguments and writes a corrupt entry. A double quote flips+ // cmd's quote tracking mid-argument, and `%` is expanded by cmd before+ // the quoting has any say — neither survives quoting, so neither is sent.+ const unencodable = [bin, ...args].find((arg) => arg.includes('"') || 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}` };+ return { ok: false, stdout: "", stderr: `cannot pass this argument through cmd.exe: ${unencodable}` };}const line = [bin, ...args].map(quoteForCmd).join(" ");const { stdout, stderr } = await execFileAsync(line, { ...options, shell: true });@@ -153,7 +169,14 @@ export async function isOnPath(bin: string): Promise<boolean> {* that fix instead of handing the same problem to seven hosts. Falls back to* the bare name, which is no worse than not trying.*/-async function resolveLauncher(): Promise<{ command: string; args: string[] }> {+let launcherProbe: Promise<Launcher> | undefined;++/** Memoised: `install` resolves this once per host it registers. */+function resolveLauncher(): Promise<Launcher> {+ return (launcherProbe ??= probeLauncher());+}++async function probeLauncher(): Promise<Launcher> {if (platform() !== "win32") return { command: "ix", args: ["mcp"] };const found = await run("where", ["ix"]);@@ -201,15 +224,29 @@ function pathExists(path: string): boolean {}/**- * The absolute launcher path inside a registration, if it records one.+ * The launcher a registration records, read from the parsed entry.*- * 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.+ * Deliberately structural. Recovering the path by regex from the rendered text+ * cannot work: a Windows launcher normally sits under a username, and a path+ * containing a space is indistinguishable from two columns of a listing table.+ * The first attempt stopped at the space, so `C:\Users\Jane Doe\...\ix.cmd`+ * matched nothing and a dead launcher went on reading as healthy — the common+ * case, not the edge one. Worse, allowing a match to start at an interior `/`+ * made it latch onto a suffix like `/npm/ix.cmd` of a path that was perfectly+ * fine, report it stale, and silently rewrite a working registration.*/-function absoluteLauncherIn(text: string): string | null {- const match = /(?:[A-Za-z]:[\\/]|\/)[^"'\s,\]]*[\\/]ix(?:\.\w+)?(?=["'\s,\]]|$)/.exec(text);- return match ? match[0].replace(/\\\\/g, "\\") : null;+function launcherOf(entry: unknown): string | null {+ if (typeof entry !== "object" || entry === null) return null;+ const command = (entry as { command?: unknown }).command;+ if (typeof command === "string") return command;+ // opencode records `command: ["ix", "mcp"]`.+ if (Array.isArray(command) && typeof command[0] === "string") return command[0];+ return null;+}++/** Absolute paths are the only ones whose disappearance we can check for. */+function isAbsolutePath(value: string): boolean {+ return /^(?:[A-Za-z]:[\\/]|\\\\|\/)/.test(value);}/**@@ -238,7 +275,10 @@ const MISSING_ENTRY = /\b(no (mcp )?server|not found|unknown server|does not exi* `python3 .../server.py` or `node dist/server.js`, and those must read as* `other` so they are reported rather than replaced.*/-export function classifyListing(listing: string): Pick<HostStatus, "registration" | "detail"> {+export function classifyListing(+ listing: string,+ recorded: string | null = null,+): Pick<HostStatus, "registration" | "detail"> {const matches = listing.split("\n").map((entry) => entry.trim())@@ -251,7 +291,7 @@ export function classifyListing(listing: string): Pick<HostStatus, "registrationconst candidates = matches.filter((entry) => !LOG_LINE.test(entry));const line = candidates.at(-1) ?? matches[0]!;- return judge(line);+ return judge(line, recorded);}/**@@ -262,7 +302,19 @@ export function classifyListing(listing: string): Pick<HostStatus, "registration* registration as a stranger's and reports a false conflict on every re-run.*/export function classifyDefinition(blob: string): Pick<HostStatus, "registration" | "detail"> {- return judge(blob.replace(/\s+/g, " ").trim());+ return judge(blob.replace(/\s+/g, " ").trim(), launcherOf(parseEmbeddedObject(blob)));+}++/** The first JSON object in a blob, for hosts that pretty-print one. */+function parseEmbeddedObject(blob: string): unknown {+ const start = blob.indexOf("{");+ const end = blob.lastIndexOf("}");+ if (start === -1 || end <= start) return null;+ try {+ return JSON.parse(blob.slice(start, end + 1));+ } catch {+ return null;+ }}/**@@ -282,14 +334,18 @@ export function classifyShown(blob: string, ok: boolean): Pick<HostStatus, "regi// 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)) {+ // Tied to our own name: "not found" and "no such" turn up in plenty of+ // unrelated failures (a missing plugin, the host's own loader), and reading+ // one of those as "the name is free" overwrites the user's server — the very+ // thing this function exists to prevent.+ if (!ok && !(MISSING_ENTRY.test(blob) && blob.includes(SERVER_NAME))) {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"> {+function judge(text: string, recorded: string | null): Pick<HostStatus, "registration" | "detail"> {if (!(/(^|[\s"'/\\])ix(\.\w+)?([\s"',\]]|$)/.test(text) && /\bmcp\b/.test(text))) {return { registration: "other", detail: truncate(text) };}@@ -299,10 +355,29 @@ function judge(text: string): Pick<HostStatus, "registration" | "detail"> {// 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` };++ // A parsed entry gives the recorded command exactly, so it can be checked for+ // what it is: a path that has since disappeared.+ if (recorded !== null && isAbsolutePath(recorded) && !pathExists(recorded)) {+ return { registration: "stale", detail: `${recorded} no longer exists` };}++ // Hosts that answer with a rendered table give us no recorded command, and+ // staleness is not attempted for them. Five attempts at establishing it from+ // the row alone each produced the same class of failure — a *working*+ // registration reported stale, which re-registers with no `--force`. Parsing+ // the path back out broke on a different shape every time; comparing the row+ // against the launcher we would write today instead broke when `where`'s+ // console output was decoded as UTF-8 and a non-ASCII npm prefix came back+ // mangled, so a hand-repaired config was overwritten with an unstartable+ // path. The repair could not land on Claude Code anyway (see `register`).+ //+ // So this reports `ours`. A moved npm prefix on those hosts is not detected+ // and not repairable through `ix mcp install` at all — `--force` does not+ // apply to a registration already judged ours — so the user has to clear the+ // name with the host's own command (`claude mcp remove ix-memory`) and run+ // install again. That is a real gap, and a smaller one than silently+ // rewriting configs that were fine.return { registration: "ours", detail: truncate(text) };}@@ -422,17 +497,21 @@ export function stripJsonComments(raw: string): string {}/** Inspect a host by reading the JSON file its servers live in. */-function inspectJsonFile(path: string, key: string): Pick<HostStatus, "registration" | "detail"> {+function inspectJsonFile(path: string, ...keys: string[]): Pick<HostStatus, "registration" | "detail"> {const { value, missing } = readJsonFile(path);if (missing) return { registration: "none" };if (value === null) return { registration: "unknown", detail: `${path} is not valid JSON` };- const servers = value[key];+ let servers: unknown = value;+ for (const key of keys) {+ if (typeof servers !== "object" || servers === null) return { registration: "none" };+ servers = (servers as Record<string, unknown>)[key];+ }if (typeof servers !== "object" || servers === null) return { registration: "none" };const entry = (servers as Record<string, unknown>)[SERVER_NAME];if (entry === undefined) return { registration: "none" };- return classifyListing(`${SERVER_NAME} ${JSON.stringify(entry)}`);+ return classifyListing(`${SERVER_NAME} ${JSON.stringify(entry)}`, launcherOf(entry));}function vsCodeUserConfig(): string {@@ -534,6 +613,13 @@ export function createHosts(writeJson: (path: string, mutate: (config: Record<st// 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.+ //+ // The *read* stays on `openclaw mcp show` on every platform, deliberately.+ // Its argv carries no quote and no `%`, so cmd handles it, and asking+ // openclaw whether it can see the entry is the only check that the shape+ // written here is one openclaw actually reads. Pairing the read with the+ // write would make a wrong key report `already registered` forever+ // instead of `not registered` — trading a loud failure for a silent one.windowsFallback: (ix) =>writeJson(openclawConfigPath(), (config) => {const mcp = (config.mcp ??= {}) as Record<string, unknown>;diff --git a/ix-cli/src/mcp/runner.ts b/ix-cli/src/mcp/runner.tsindex 0bd445ac..12929426 100644--- a/ix-cli/src/mcp/runner.ts+++ b/ix-cli/src/mcp/runner.ts@@ -11,7 +11,7 @@ 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";+import { releaseLocksOwnedBy, setLockOwnerResolver } from "../cli/single-flight.js";const execFileAsync = promisify(execFile);const CLI_ENTRYPOINT = fileURLToPath(new URL("../cli/main.js", import.meta.url));@@ -99,6 +99,11 @@ const runContext = new AsyncLocalStorage<ActiveRun>();* *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.+ *+ * Membership is bounded by a grace timer as well as by the command settling,+ * because distrust is not free: while it holds, a genuinely failing command+ * reports success. An entry that could never be removed would make that+ * permanent.*/const liveOrphans = new Set<Promise<void>>();@@ -220,6 +225,15 @@ function installCapture(options: { redirectIdleStdout?: boolean } = {}): void {if (!resolveRun()) return pristineExit(code);throw new ProcessExitSignal(code ?? 0);}) as typeof process.exit;++ // Single-flight locks are taken deep inside a command, so the command has to+ // be identifiable from there. Deliberately the async context alone, without+ // resolveRun's fallback to activeRun: for output that fallback only ever+ // narrows the damage, but an owner guessed wrong here means a *different*+ // command's settle deletes a lock that is still in use. Unattributed is the+ // safe direction — the lock outlives its command and ages out — so a lock+ // taken outside any run context simply gets no owner.+ setLockOwnerResolver(() => runContext.getStore() ?? null);}/**@@ -289,6 +303,12 @@ export interface InProcessRunnerOptions {createProgram?: (version: string) => Command | Promise<Command>;/** Output cap for a single run. Defaults to {@link MAX_OUTPUT_BYTES}. */maxOutputBytes?: number;+ /**+ * How long an abandoned command keeps {@link liveOrphans} membership before+ * it is dropped regardless. Defaults to as long again as the command was+ * given. Tests shorten it; nothing else should need to.+ */+ orphanGraceMs?: number;}/**@@ -298,16 +318,27 @@ export interface InProcessRunnerOptions {* 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 {+function invalidateAfter(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();+/**+ * Give up the single-flight locks this command took.+ *+ * `ix map` takes its lock and never releases it, relying on process exit. Held+ * by a long-lived server the lock names the server's own live PID, so it never+ * reads as stale: every later ix_map coalesces into an empty success while the+ * graph goes unrefreshed, and the user's own editor-hook `ix map` is blocked+ * for the same 20 minutes.+ *+ * Scoped to this run, which is the whole point. Releasing everything held was+ * wrong in both directions — it took the lock of a map still running, and+ * holding it back to avoid that then stranded the lock of a map that had+ * finished. Ownership makes the question local: this command is over, so its+ * own locks go, and nobody else's are touched.+ */+function releaseLocksOf(run: ActiveRun): void {+ releaseLocksOwnedBy(run);}/**@@ -339,6 +370,7 @@ async function executeInProcess(version: string,createProgram: (version: string) => Command | Promise<Command>,maxBytes: number,+ orphanGraceMs?: number,): Promise<IxRunResult> {const program = throwOnUsageError(await createProgram(version));const run: ActiveRun = {@@ -394,12 +426,44 @@ async function executeInProcess(activeRun = null;if (commandSettled) {- afterCommand(args);+ invalidateAfter(args);+ releaseLocksOf(run);} else {liveOrphans.add(finished);++ // A command that never settles at all — a hung fetch, or a rejection that+ // used to end the process and is now only logged — would otherwise hold+ // this entry forever, and exit codes would stay distrusted, so *every*+ // later failure would report ok. The wait is bounded to as long again as+ // the command was allowed to run. Locks are not keyed off this set at all+ // any more, so the bound says nothing about them: a command that never+ // settles keeps the lock it is still using until it ages out.+ //+ // The cost of that bound is real and lands on someone else: past the+ // grace this command's late `process.exitCode` is charged to whichever+ // call is running by then, which is #400's original symptom in delayed+ // form. Bounded-open beats permanently-open, so the trade stands — but it+ // is a trade, not a free win.+ //+ // The grace drops the distrust and invalidates, and nothing else. It must+ // not release the lock: the command is by definition *still running*+ // there, and its lock is still doing its job. Scope invalidation is+ // idempotent, so running it here as well as on settle costs nothing and+ // covers the command that never settles at all — which would otherwise+ // leave the pre-map scope pinned with nothing left to invalidate it.+ const grace = setTimeout(() => {+ liveOrphans.delete(finished);+ invalidateAfter(args);+ }, orphanGraceMs ?? Math.max(timeoutMs, DEFAULT_TIMEOUT_MS));+ grace.unref?.();+void finished.then(() => {liveOrphans.delete(finished);- afterCommand(args);+ clearTimeout(grace);+ // On settle the command really is over, however long it overran, so its+ // locks go now.+ invalidateAfter(args);+ releaseLocksOf(run);});}}@@ -419,7 +483,7 @@ async function executeInProcess(* 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 — but only between *reads*: see- * {@link afterCommand} for the state whose sole invalidation used to be the+ * {@link invalidateAfter} 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@@ -434,12 +498,13 @@ export function createInProcessRunner(options: InProcessRunnerOptions = {}): IxRconst version = options.version ?? "0.0.0";const createProgram = options.createProgram ?? buildProgram;const maxBytes = options.maxOutputBytes ?? MAX_OUTPUT_BYTES;+ const orphanGraceMs = options.orphanGraceMs;let queue: Promise<unknown> = Promise.resolve();return (args, timeoutMs = DEFAULT_TIMEOUT_MS) => {const result = queue.then(() =>- executeInProcess(args, timeoutMs, version, createProgram, maxBytes),+ executeInProcess(args, timeoutMs, version, createProgram, maxBytes, orphanGraceMs),);// The chain must survive a rejection, or one failed run would strand every// later call behind it. executeInProcess resolves rather than throws for