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): never cache "no workspace" in the read scope

KageBinaryb202ef87fd69
diff --git a/ix-cli/src/cli/__tests__/read-scope-cache.test.ts b/ix-cli/src/cli/__tests__/read-scope-cache.test.ts
new file mode 100644
index 00000000..e9e37157
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/read-scope-cache.test.ts
@@ -0,0 +1,100 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import * as fs from "node:fs";
+import * as os from "node:os";
+import * as path from "node:path";
+
+import { clearStitchScopeCache, saveConfig } from "../config.js";
+import { WorkspaceNotMappedError } from "../errors.js";
+import { activeReadScope, ensureReadScope, resetReadScope } from "../resolve.js";
+
+/**
+ * `ix mcp` keeps the read scope for its whole session. It used to keep a "no
+ * workspace here" answer too, and a stitch answer the next map invalidated, so
+ * an `ix map` run from a terminal or an editor hook went unseen: the session
+ * kept refusing reads, or kept answering against the pre-map scope, until it
+ * was restarted.
+ */
+
+let home: string;
+let repo: string;
+let savedCwd: string;
+
+function register(workspaceId: string): void {
+ saveConfig({
+ endpoint: "http://localhost:8090",
+ format: "text",
+ workspaces: [{ workspace_id: workspaceId, workspace_name: "repo", root_path: repo, default: false }],
+ } as never);
+}
+
+/** A backend that answers the stitch lookup with `systemId` and counts calls. */
+function client(systemId: () => string | null) {
+ const calls = { n: 0 };
+ return {
+ calls,
+ workspaceSystem: async () => {
+ calls.n++;
+ return { systemId: systemId() };
+ },
+ };
+}
+
+beforeEach(() => {
+ home = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), "ix-scope-cache-")));
+ process.env.IX_HOME = path.join(home, ".ix");
+ fs.mkdirSync(process.env.IX_HOME, { recursive: true });
+ repo = path.join(home, "repo");
+ fs.mkdirSync(repo, { recursive: true });
+ savedCwd = process.cwd();
+ process.chdir(repo);
+ resetReadScope();
+});
+
+afterEach(() => {
+ process.chdir(savedCwd);
+ delete process.env.IX_HOME;
+ resetReadScope();
+ fs.rmSync(home, { recursive: true, force: true });
+});
+
+describe("read scope cache in a long-lived process", () => {
+ it("sees a workspace registered after a failed read, without resetReadScope", async () => {
+ const backend = client(() => null);
+ await expect(ensureReadScope(backend)).rejects.toBeInstanceOf(WorkspaceNotMappedError);
+ expect(activeReadScope()).toEqual(expect.objectContaining({ workspaceId: undefined, systemId: undefined }));
+
+ // What `ix map` in another process does to this one's world.
+ register("ws-late");
+
+ await ensureReadScope(backend);
+ expect(activeReadScope().workspaceId).toBe("ws-late");
+ });
+
+ it("asks again for a stitched system once an external map clears the stitch answer", async () => {
+ register("ws-1");
+ let system: string | null = null;
+ const backend = client(() => system);
+
+ await ensureReadScope(backend);
+ expect(activeReadScope()).toEqual(expect.objectContaining({ workspaceId: "ws-1", systemId: undefined }));
+
+ // The map stitches the repo into a system server-side and clears the file.
+ system = "sys-1";
+ clearStitchScopeCache("ws-1");
+
+ await ensureReadScope(backend);
+ expect(activeReadScope()).toEqual(expect.objectContaining({ workspaceId: undefined, systemId: "sys-1" }));
+ });
+
+ it("keeps a current scope cached: one backend lookup for repeated reads", async () => {
+ register("ws-2");
+ const backend = client(() => null);
+ await ensureReadScope(backend);
+ await ensureReadScope(backend);
+ await ensureReadScope(backend);
+ expect(backend.calls.n).toBe(1);
+ expect(activeReadScope().workspaceId).toBe("ws-2");
+ });
+});
diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.ts
index f97977f4..f36fc1bc 100644
--- a/ix-cli/src/cli/resolve.ts
+++ b/ix-cli/src/cli/resolve.ts
@@ -8,7 +8,8 @@ import { stderr } from "./stderr.js";
import { applyRoleFilter } from "./role-filter.js";
import { detectSystem } from "./system.js";
import { requireReadWorkspaceId, resolveWorkspaceId } from "./bootstrap.js";
-import { readStitchScope, resolveWorkspaceRoot, writeStitchScope } from "./config.js";
+import { readStitchScope, resolveWorkspaceRoot, stitchScopeCachePath, writeStitchScope } from "./config.js";
+import { ixHome } from "./ix-home.js";
import { checkGraphHealth, isUnhealthy, type GraphHealth } from "./graph-health.js";
import { reportAmbiguousTarget, reportResolutionFailure } from "./ui.js";
import { relativePath } from "./format.js";
@@ -27,7 +28,52 @@ import {
* (getActiveWorkspaceRoot vs. workspace-relative source_uri) dropped every candidate
* (issue #228, originally fixed in search.ts only).
*/
-let _scopeCache: { cwd: string; workspaceId?: string; systemId?: string; stitchChecked?: boolean } | undefined;
+let _scopeCache: {
+ cwd: string;
+ workspaceId?: string;
+ systemId?: string;
+ stitchChecked?: boolean;
+ /** scopeKey() when this was computed; a different key means it is stale. */
+ key: string;
+} | undefined;
+
+function mtimeOf(file: string): string {
+ try {
+ return String(fs.statSync(file).mtimeMs);
+ } catch {
+ return "-";
+ }
+}
+
+/**
+ * What a cached scope depends on besides the cwd: config.yaml, where `ix map`
+ * registers a workspace, and the workspace's stitch-scope file, which a map or
+ * ingest clears. `ix mcp` keeps this cache for the whole session, and the map
+ * that changes either one usually runs in another process -- an editor hook,
+ * a terminal -- that resetReadScope() never hears about. Two stats per read.
+ */
+function scopeKey(workspaceId: string | undefined): string {
+ const stitch = workspaceId ? mtimeOf(stitchScopeCachePath(workspaceId)) : "-";
+ return `${mtimeOf(path.join(ixHome(), "config.yaml"))}|${stitch}`;
+}
+
+/** The cached scope for `cwd`, if it is still current. */
+function currentCache(cwd: string): NonNullable<typeof _scopeCache> | undefined {
+ if (_scopeCache?.cwd !== cwd) return undefined;
+ const ws = _scopeCache.workspaceId ?? resolveWorkspaceIdQuiet(cwd);
+ if (_scopeCache.key !== scopeKey(ws)) return undefined;
+ return _scopeCache;
+}
+
+// The workspace id for the stitch-file part of the key. Only consulted for a
+// system-scoped entry, where the cache holds no workspace id of its own.
+function resolveWorkspaceIdQuiet(cwd: string): string | undefined {
+ try {
+ return resolveWorkspaceId(cwd);
+ } catch {
+ return undefined;
+ }
+}
/**
* Drop the cached scope so the next read resolves it again.
@@ -47,11 +93,15 @@ export function activeReadScope(): { workspaceId?: string; systemId?: string } {
}
function activeScope(): { workspaceId?: string; systemId?: string } {
const cwd = process.cwd();
- if (_scopeCache?.cwd === cwd) return _scopeCache;
+ const cached = currentCache(cwd);
+ if (cached) return cached;
const systemId = detectSystem(cwd)?.systemId;
const workspaceId = systemId ? undefined : resolveWorkspaceId(cwd);
- _scopeCache = { cwd, workspaceId, systemId, stitchChecked: false };
- return _scopeCache;
+ const scope = { cwd, workspaceId, systemId, stitchChecked: false, key: scopeKey(workspaceId) };
+ // "No workspace here" is never cached: it is exactly the answer an `ix map`
+ // run elsewhere changes, and recomputing it is a few file reads.
+ _scopeCache = workspaceId || systemId ? scope : undefined;
+ return scope;
}
/**
@@ -79,9 +129,12 @@ export async function ensureReadScope(
async function foldStitchedSystem(client: Pick<IxClient, "workspaceSystem">): Promise<void> {
const cwd = process.cwd();
- if (_scopeCache?.cwd === cwd && _scopeCache.stitchChecked) return;
+ if (currentCache(cwd)?.stitchChecked) return;
const localSystem = detectSystem(cwd)?.systemId;
- if (localSystem) { _scopeCache = { cwd, systemId: localSystem, stitchChecked: true }; return; }
+ if (localSystem) {
+ _scopeCache = { cwd, systemId: localSystem, stitchChecked: true, key: scopeKey(resolveWorkspaceIdQuiet(cwd)) };
+ return;
+ }
const ws = resolveWorkspaceId(cwd);
let systemId: string | undefined;
if (ws) {
@@ -101,7 +154,10 @@ async function foldStitchedSystem(client: Pick<IxClient, "workspaceSystem">): Pr
} catch { /* best-effort: leave the scope at workspace level, cache nothing */ }
}
}
- _scopeCache = { cwd, workspaceId: systemId ? undefined : ws, systemId, stitchChecked: true };
+ // Unmapped: leave nothing cached, so the next read looks again (see activeScope).
+ _scopeCache = ws || systemId
+ ? { cwd, workspaceId: systemId ? undefined : ws, systemId, stitchChecked: true, key: scopeKey(ws) }
+ : undefined;
}
/**
diff --git a/ix-cli/src/mcp/runner.ts b/ix-cli/src/mcp/runner.ts
index 16c0db2a..f2c6a153 100644
--- a/ix-cli/src/mcp/runner.ts
+++ b/ix-cli/src/mcp/runner.ts
@@ -324,8 +324,11 @@ 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 invalidateAfter(args: string[]): void {
- if (SCOPE_CHANGING_COMMANDS.has(args[0] ?? "")) resetReadScope();
+function invalidateAfter(args: string[], failed = false): void {
+ // A failed read is often "no workspace here"; whatever the user does next
+ // (map, cd, register) should be looked up fresh rather than answered from
+ // the scope that just failed.
+ if (failed || SCOPE_CHANGING_COMMANDS.has(args[0] ?? "")) resetReadScope();
}
/**
@@ -450,7 +453,7 @@ async function executeInProcess(
activeRun = null;
if (commandSettled) {
- invalidateAfter(args);
+ invalidateAfter(args, failure !== null || (commandExitCode !== undefined && commandExitCode !== 0));
releaseLocksOf(run);
} else {
liveOrphans.add(finished);