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
perf: cut ix read from 60-80s to 3.9s, plus two per-command round trips (#494)
KageBinary958d679cd8f1
diff --git a/ix-cli/src/cli/__tests__/doctor-stats-once.test.ts b/ix-cli/src/cli/__tests__/doctor-stats-once.test.tsnew file mode 100644index 00000000..e0f40fe0--- /dev/null+++ b/ix-cli/src/cli/__tests__/doctor-stats-once.test.ts@@ -0,0 +1,75 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { Command } from "commander";++const statsCalls = { n: 0 };++vi.mock("../../client/api.js", () => ({+ IxClient: class {+ async stats() {+ statsCalls.n += 1;+ return { nodes: { total: 10 }, edges: { total: 20 } };+ }+ async conflicts() { return []; }+ async health() { return { status: "ok" }; }+ },+}));++// Doctor also inspects the live container and probes the schema. Both are+// mocked, not merely pointed somewhere harmless: an unmocked `docker inspect`+// or socket connect is slow-and-variable rather than fast-and-failing, which is+// how this test timed out at 5s on the Windows runner while passing on Linux.+vi.mock("../backend-status.js", async (orig) => ({+ ...(await orig<typeof import("../backend-status.js")>()),+ checkBackendImage: () => ({ kind: "docker-unavailable" as const }),+ checkBackendSchema: async () => ({ ok: true as const }),+ isNonStandardBackend: () => false,+}));++vi.mock("../commands/upgrade.js", async (orig) => ({+ ...(await orig<typeof import("../commands/upgrade.js")>()),+ readBackendHealth: async () => ({ status: "ok", schema_version: 3 }),+}));++let savedEndpoint: string | undefined;++beforeEach(() => {+ vi.resetModules();+ statsCalls.n = 0;+ // Belt and braces with the mocks above: nothing in this test may depend on a+ // backend being reachable, or on how quickly a given OS refuses a connection.+ savedEndpoint = process.env.IX_ENDPOINT;+ process.env.IX_ENDPOINT = "http://127.0.0.1:9";+});++afterEach(() => {+ if (savedEndpoint === undefined) delete process.env.IX_ENDPOINT;+ else process.env.IX_ENDPOINT = savedEndpoint;+});++async function runDoctor(): Promise<void> {+ const { registerDoctorCommand } = await import("../commands/doctor.js");+ const program = new Command();+ program.name("ix").exitOverride();+ registerDoctorCommand(program);+ const log = vi.spyOn(console, "log").mockImplementation(() => {});+ const err = vi.spyOn(console, "error").mockImplementation(() => {});+ try {+ await program.parseAsync(["doctor", "--format", "llm"], { from: "user" });+ } catch { /* exitOverride / process.exit path */ } finally {+ log.mockRestore();+ err.mockRestore();+ }+}++describe("ix doctor", () => {+ /**+ * "Graph has nodes" and "Graph has edges" are two questions about one+ * response, and they were two `client.stats()` calls run back to back by the+ * sequential check loop. `/v1/stats` is 3-4s on a large graph, so the second+ * one was roughly half of what `ix doctor` spent.+ */+ it("asks the backend for stats once, not once per check that reads it", async () => {+ await runDoctor();+ expect(statsCalls.n).toBe(1);+ });+});diff --git a/ix-cli/src/cli/__tests__/read-local-first.test.ts b/ix-cli/src/cli/__tests__/read-local-first.test.tsnew file mode 100644index 00000000..c96ee659--- /dev/null+++ b/ix-cli/src/cli/__tests__/read-local-first.test.ts@@ -0,0 +1,104 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Command } from "commander";++const searchCalls: Array<Record<string, unknown>> = [];++vi.mock("../../client/api.js", () => ({+ IxClient: class {+ async search(term: string, opts: Record<string, unknown>) {+ searchCalls.push({ term, ...opts });+ return [];+ }+ async entity() { return { node: {}, claims: [], edges: [] }; }+ async workspaceSystem() { return { systemId: null }; }+ },+}));++let root: string;++beforeEach(() => {+ vi.resetModules();+ searchCalls.length = 0;+ root = mkdtempSync(join(tmpdir(), "ix-read-local-"));+ mkdirSync(join(root, "src", "cli"), { recursive: true });+ mkdirSync(join(root, "node_modules", "junk"), { recursive: true });+ writeFileSync(join(root, "src", "cli", "upgrade.ts"), "export const x = 1;\n");+ writeFileSync(join(root, "node_modules", "junk", "upgrade.ts"), "module.exports = {};\n");+});++afterEach(() => {+ rmSync(root, { recursive: true, force: true });+ vi.restoreAllMocks();+});++async function runRead(target: string): Promise<string> {+ const { registerReadCommand } = await import("../commands/read.js");+ const program = new Command();+ program.name("ix").exitOverride();+ registerReadCommand(program);+ const out: string[] = [];+ const log = vi.spyOn(console, "log").mockImplementation((...v: unknown[]) => { out.push(v.join(" ")); });+ const err = vi.spyOn(console, "error").mockImplementation((...v: unknown[]) => { out.push(v.join(" ")); });+ try {+ await program.parseAsync(["read", target, "--root", root], { from: "user" });+ } catch { /* commander exitOverride */ } finally {+ log.mockRestore();+ err.mockRestore();+ }+ return out.join("\n");+}++describe("ix read resolves filenames from disk before the graph", () => {+ it("finds a nested file by bare basename without asking the backend at all", async () => {+ const out = await runRead("upgrade");++ expect(out).toContain("export const x = 1;");+ // The whole point: zero round trips. This used to be a `kind: file` search+ // plus a nine-way fan-out over guessed extensions.+ expect(searchCalls).toEqual([]);+ });++ it("does not descend into node_modules, so the workspace copy wins", async () => {+ const out = await runRead("upgrade");+ // Assert the content that WAS rendered, not merely the absence of the other+ // file's — a run that resolves nothing would satisfy the absence alone, and+ // that is exactly what the pre-fix code does here.+ expect(out).toContain("export const x = 1;");+ expect(out).not.toContain("module.exports");+ });++ /**+ * The regression this file exists for.+ *+ * `ix read <symbol>` used to issue 12 backend calls: a `kind: file` search,+ * then NINE concurrent searches appending .scala/.ts/.tsx/.py/.rs/.go/.java/+ * .js/.md, then the symbol lookup that actually answers. All nine returned+ * empty for a symbol, and being concurrent they contended for the same+ * collection — measured at ~54s EACH instead of ~10s, so the command took+ * 60-80s before reaching the call that works.+ *+ * `ix map` ignores a strict superset of the directories this walk ignores, so+ * an exhaustive walk that finds nothing proves the graph has nothing to find+ * either.+ */+ it("asks the graph nothing about filenames for an extension-less symbol", async () => {+ await runRead("registerUpgradeCommand");++ const fileSearches = searchCalls.filter((c) => c.kind === "file");+ expect(fileSearches).toEqual([]);+ // Every guessed-extension term is gone too.+ expect(searchCalls.some((c) => String(c.term).endsWith(".scala"))).toBe(false);+ expect(searchCalls.some((c) => String(c.term).endsWith(".tsx"))).toBe(false);+ });++ it("still asks the graph when the target carries an extension", async () => {+ // A file that is ingested but not checked out locally is exactly the case+ // the graph lookup exists for, so an extension must not take the shortcut.+ await runRead("NotOnDisk.scala");++ expect(searchCalls.some((c) => c.kind === "file" && c.term === "NotOnDisk.scala")).toBe(true);+ });+});diff --git a/ix-cli/src/cli/__tests__/stitch-scope-cache.test.ts b/ix-cli/src/cli/__tests__/stitch-scope-cache.test.tsnew file mode 100644index 00000000..03a7dff8--- /dev/null+++ b/ix-cli/src/cli/__tests__/stitch-scope-cache.test.ts@@ -0,0 +1,112 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++let home: string;+let savedHome: string | undefined;++beforeEach(() => {+ vi.resetModules();+ home = mkdtempSync(join(tmpdir(), "ix-stitch-scope-"));+ savedHome = process.env.HOME;+ process.env.HOME = home;+ mkdirSync(join(home, ".ix"), { recursive: true });+});++afterEach(() => {+ if (savedHome === undefined) delete process.env.HOME;+ else process.env.HOME = savedHome;+ rmSync(home, { recursive: true, force: true });+ vi.restoreAllMocks();+});++describe("stitch scope cache", () => {+ it("round-trips a system id", async () => {+ const c = await import("../config.js");+ c.writeStitchScope("ws-1", "sys-9");+ expect(c.readStitchScope("ws-1")).toEqual({ systemId: "sys-9" });+ });++ /**+ * "Not stitched" is the common answer and the one worth not re-asking: the+ * backend query behind it is an unindexed scan that is SLOWEST when it finds+ * nothing, because there is no match to stop early on.+ */+ it("caches a null answer rather than treating it as a miss", async () => {+ const c = await import("../config.js");+ c.writeStitchScope("ws-2", null);+ expect(c.readStitchScope("ws-2")).toEqual({ systemId: null });+ });++ it("reports a miss for a workspace it has never seen", async () => {+ const c = await import("../config.js");+ expect(c.readStitchScope("never-seen")).toBeUndefined();+ });++ it("treats a corrupt or truncated file as a miss, never as an answer", async () => {+ const c = await import("../config.js");+ writeFileSync(c.stitchScopeCachePath("ws-3"), "{not json");+ expect(c.readStitchScope("ws-3")).toBeUndefined();+ });++ it("rejects a file whose recorded workspace is not the one asked for", async () => {+ // Guards a hash collision or a hand-edited file from answering for the+ // wrong workspace, which would scope every later read to someone else.+ const c = await import("../config.js");+ writeFileSync(c.stitchScopeCachePath("ws-4"), JSON.stringify({ workspaceId: "other", systemId: "sys-x" }));+ expect(c.readStitchScope("ws-4")).toBeUndefined();+ });++ it("rejects a non-string, non-null systemId", async () => {+ const c = await import("../config.js");+ writeFileSync(c.stitchScopeCachePath("ws-5"), JSON.stringify({ workspaceId: "ws-5", systemId: 42 }));+ expect(c.readStitchScope("ws-5")).toBeUndefined();+ });++ it("clears an entry so the next read asks the backend again", async () => {+ const c = await import("../config.js");+ c.writeStitchScope("ws-6", "sys-6");+ expect(existsSync(c.stitchScopeCachePath("ws-6"))).toBe(true);+ c.clearStitchScopeCache("ws-6");+ expect(c.readStitchScope("ws-6")).toBeUndefined();+ });++ it("clearing an entry that was never written is not an error", async () => {+ const c = await import("../config.js");+ expect(() => c.clearStitchScopeCache("ws-7")).not.toThrow();+ });+});++describe("ensureReadScope uses the cache", () => {+ it("does not call the backend when a cached answer exists", async () => {+ const c = await import("../config.js");+ const bootstrap = await import("../bootstrap.js");+ vi.spyOn(bootstrap, "resolveWorkspaceId").mockReturnValue("ws-cached");+ c.writeStitchScope("ws-cached", "sys-cached");++ const { ensureReadScope, activeReadScope, resetReadScope } = await import("../resolve.js");+ resetReadScope();+ const workspaceSystem = vi.fn(async () => ({ systemId: "sys-from-backend" }));++ await ensureReadScope({ workspaceSystem } as never);++ expect(workspaceSystem).not.toHaveBeenCalled();+ expect(activeReadScope().systemId).toBe("sys-cached");+ });++ it("asks the backend on a miss and records the answer for next time", async () => {+ const c = await import("../config.js");+ const bootstrap = await import("../bootstrap.js");+ vi.spyOn(bootstrap, "resolveWorkspaceId").mockReturnValue("ws-fresh");++ const { ensureReadScope, resetReadScope } = await import("../resolve.js");+ resetReadScope();+ const workspaceSystem = vi.fn(async () => ({ systemId: "sys-fresh" }));++ await ensureReadScope({ workspaceSystem } as never);++ expect(workspaceSystem).toHaveBeenCalledOnce();+ expect(c.readStitchScope("ws-fresh")).toEqual({ systemId: "sys-fresh" });+ });+});diff --git a/ix-cli/src/cli/commands/doctor.ts b/ix-cli/src/cli/commands/doctor.tsindex 59b93e74..c2cf61a7 100644--- a/ix-cli/src/cli/commands/doctor.ts+++ b/ix-cli/src/cli/commands/doctor.ts@@ -120,6 +120,15 @@ export function registerDoctorCommand(program: Command): void {const endpoint = getEndpoint();const client = new IxClient(endpoint);+ // "Graph has nodes" and "Graph has edges" are two questions about one+ // response. They were two `client.stats()` calls, run back to back by the+ // sequential loop below — and `/v1/stats` is 3-4 s on a large graph, so+ // the second one was most of what `ix doctor` spent. Memoized rather than+ // hoisted so a run that never reaches those checks still never asks, and+ // so a failure is still reported per check rather than aborting both.+ let statsOnce: Promise<any> | undefined;+ const sharedStats = (): Promise<any> => (statsOnce ??= client.stats());+const checks: Check[] = [{name: "Server reachable",@@ -138,7 +147,7 @@ export function registerDoctorCommand(program: Command): void {name: "Graph has nodes",run: async () => {try {- const s = await client.stats();+ const s = await sharedStats();const total = s.nodes?.total ?? 0;return { ok: total > 0, detail: `${total} nodes` };} catch (e: any) {@@ -150,7 +159,7 @@ export function registerDoctorCommand(program: Command): void {name: "Graph has edges",run: async () => {try {- const s = await client.stats();+ const s = await sharedStats();const total = s.edges?.total ?? 0;return { ok: total > 0, detail: `${total} edges` };} catch (e: any) {diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.tsindex 29fbbaf0..8214d286 100644--- a/ix-cli/src/cli/commands/ingest.ts+++ b/ix-cli/src/cli/commands/ingest.ts@@ -10,7 +10,7 @@ import { ParsePool } from './parse-pool.js';import chalk from 'chalk';import { IxClient } from '../../client/api.js';import type { GraphPatchPayload } from '../../client/types.js';-import { getEndpoint, resolveWorkspaceRoot } from '../config.js';+import { getEndpoint, resolveWorkspaceRoot, clearStitchScopeCache } from '../config.js';import { isRev, loadIngestBaseline, saveIngestBaseline } from '../ingest-baseline.js';import { resolveGitHubToken } from '../github/auth.js';import { parseGitHubRepo, fetchGitHubData } from '../github/fetch.js';@@ -2009,6 +2009,11 @@ export async function ingestFiles(if (provides.length > 0 || stitchConsumes.length > 0 || stitchExports.length > 0 || symbolConsumes.length > 0) {const res = await client.stitch({ workspaceId, provides, consumes: stitchConsumes, exports: stitchExports, symbolConsumes });if (debug) process.stderr.write(` [stitch] provides=${provides.length} consumes=${stitchConsumes.length} exports=${stitchExports.length} symConsumes=${symbolConsumes.length} -> ${res.stitched} edges\n`);+ // This call is the one thing that can change whether the workspace+ // belongs to a system, and reads cache that answer on disk. Drop it+ // here so the next read asks again rather than scoping to the+ // pre-stitch workspace for as long as the file survives.+ clearStitchScopeCache(workspaceId);}} catch (err) {if (debug) process.stderr.write(` [stitch skipped] ${err}\n`);diff --git a/ix-cli/src/cli/commands/read.ts b/ix-cli/src/cli/commands/read.tsindex bb907e58..bb1d4f0c 100644--- a/ix-cli/src/cli/commands/read.ts+++ b/ix-cli/src/cli/commands/read.ts@@ -11,23 +11,6 @@ import { relativePath } from "../format.js";import { llmLine, printLlmLines } from "../llm.js";import { parsePickOption } from "../options.js";-/** Common file extensions that signal the target is file-like, not a symbol name. */-const FILE_EXTENSIONS = new Set([- ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",- ".scala", ".sc", ".java", ".py", ".rb", ".go", ".rs",- ".md", ".mdx", ".rst", ".txt",- ".json", ".yaml", ".yml", ".toml", ".ini", ".conf",- ".sql", ".graphql", ".gql", ".sh", ".bash",- ".html", ".css", ".scss", ".less",-]);--function looksFileLike(target: string): boolean {- if (target.includes("/") || target.includes("\\")) return true;- const ext = path.extname(target).toLowerCase();- if (ext && FILE_EXTENSIONS.has(ext)) return true;- return false;-}-export interface ReadResult {targetType: "file" | "file-range" | "filename-match" | "symbol";path: string;@@ -242,7 +225,7 @@ Examples:// read should prefer resolving to a real file before trying symbol match.// e.g. "ix read Node" should find Node.scala before trying symbol resolution.{- const filenameMatches = await tryFilenameMatch(client, rawTarget);+ const filenameMatches = await tryFilenameMatch(client, rawTarget, root);if (filenameMatches.length === 1) {const matchPath = filenameMatches[0].path;if (matchPath && fs.existsSync(matchPath)) {@@ -351,10 +334,32 @@ Examples:*/async function tryFilenameMatch(client: IxClient,- target: string+ target: string,+ root: string): Promise<Array<{ name: string; path: string }>> {const basename = path.basename(target);const hasExtension = path.extname(basename) !== "";++ // Strategy 0: the workspace itself. `read` can only display a file that+ // exists locally — every graph result below is re-checked with `existsSync`+ // and dropped when it is missing — so disk is the authority here, not a cache+ // of the backend. It answers in milliseconds against seconds, and reaching it+ // before `ensureReadScope` also skips that call's scope lookup, which is its+ // own ~1.5 s on a large graph.+ const local = findLocalBasenameMatches(root, basename);+ if (local.paths.length > 0) {+ return local.paths.map(p => ({ name: path.basename(p), path: p }));+ }++ // An extension-less target with no local file of that basename is not a+ // filename in this workspace, and the graph cannot say otherwise: `ix map`'s+ // IGNORE_DIRS is a strict superset of the walk's, so every file the graph+ // holds for this workspace is a file the walk visited. Asking the backend+ // anyway costs ~8 s of `kind: file` search that returns empty every time.+ // Targets that DO carry an extension still go to the graph, which is what+ // answers `ix read Node.scala` for a file that is ingested but not checked out.+ if (!hasExtension && local.exhaustive) return [];+// Scope to the active workspace / co-ingest system / Path-2 stitched system.await ensureReadScope(client);const scope = activeReadScope();@@ -363,10 +368,20 @@ async function tryFilenameMatch(let nodes = await client.search(basename, { limit: 20, kind: "file", ...scope });// Strategy 2: If bare name (no extension), also search with common extensions- // to avoid being crowded out by unrelated results. Fire the per-extension searches- // CONCURRENTLY — sequentially they were ~9 round trips that hung `ix read <symbol>`- // on large backends. Results are merged in extension-priority order (a .scala hit- // still ranks before a .ts hit), and the downstream filter/sort picks the winner.+ // to avoid being crowded out by unrelated results — a bare `upgrade` search+ // is a substring match, and on a large graph the file actually called+ // `upgrade.ts` does not survive the backend's LIMIT.+ //+ // Gated on `local.exhaustive`, and that gate is the whole point. These nine+ // searches are fired concurrently, and nine concurrent unindexed scans do not+ // cost what one costs: measured on a 1.16M-node graph they take ~54 s EACH+ // rather than ~10 s, because they contend for the same collection. For a+ // symbol like `registerUpgradeCommand` all nine return empty, and `ix read`+ // spent 60-80 s before reaching the symbol lookup that answers it.+ //+ // When the walk above completed, "no local file has this basename" is proven,+ // and a graph hit could not be displayed anyway. Only when the walk ran out+ // of budget is the question still open, and then the fallback still runs.if (!hasExtension && !filterMatches(nodes, basename).length) {const extensions = [".scala", ".ts", ".tsx", ".py", ".rs", ".go", ".java", ".js", ".md"];const perExt = await Promise.all(@@ -390,6 +405,67 @@ async function tryFilenameMatch(});}+/** Directories a workspace walk must not descend into. Mirrors stale.ts. */+const WALK_IGNORE_DIRS = new Set([+ "node_modules", ".git", "dist", "build", "target", ".next",+ ".cache", "__pycache__", ".ix", ".claude",+]);++/** How many directory entries a single basename lookup will look at. */+const WALK_ENTRY_BUDGET = 40_000;++interface LocalMatches {+ paths: string[];+ /** False when the budget ran out, i.e. "no match" is not a proven answer. */+ exhaustive: boolean;+}++/**+ * Find files in the workspace whose basename matches `target`, on disk.+ *+ * `read` can only ever *display* a file that exists locally — the graph branch+ * below re-checks `existsSync` on whatever path the backend hands back and+ * falls through when it is missing. So the filesystem is not a shortcut here,+ * it is the authority, and it answers in milliseconds where the graph takes+ * seconds.+ *+ * Returns `exhaustive: false` if the entry budget ran out. A negative answer is+ * only trustworthy when the whole workspace was walked, and the caller uses+ * that distinction to decide whether it may skip the backend fallback.+ */+function findLocalBasenameMatches(root: string, target: string, limit = 25): LocalMatches {+ const wanted = path.basename(target);+ const wantedNoExt = wanted.replace(/\.[^.]+$/, "");+ const paths: string[] = [];+ const stack = [root];+ let budget = WALK_ENTRY_BUDGET;++ while (stack.length > 0 && paths.length < limit) {+ const current = stack.pop()!;+ let entries: fs.Dirent[];+ try {+ entries = fs.readdirSync(current, { withFileTypes: true });+ } catch {+ continue; // unreadable directory is not an error for a lookup+ }+ for (const entry of entries) {+ if (--budget <= 0) return { paths, exhaustive: false };+ if (entry.isDirectory()) {+ if (entry.name.startsWith(".") || WALK_IGNORE_DIRS.has(entry.name)) continue;+ stack.push(path.join(current, entry.name));+ continue;+ }+ if (!entry.isFile()) continue; // symlinks are not followed+ const nameNoExt = entry.name.replace(/\.[^.]+$/, "");+ if (entry.name === wanted || nameNoExt === wanted || nameNoExt === wantedNoExt) {+ paths.push(path.join(current, entry.name));+ if (paths.length >= limit) return { paths, exhaustive: true };+ }+ }+ }+ return { paths, exhaustive: stack.length === 0 };+}+/** Filter nodes to those whose filename actually matches the target basename. */function filterMatches(nodes: any[],diff --git a/ix-cli/src/cli/commands/reset.ts b/ix-cli/src/cli/commands/reset.tsindex f9c6f285..ac11969e 100644--- a/ix-cli/src/cli/commands/reset.ts+++ b/ix-cli/src/cli/commands/reset.ts@@ -2,8 +2,21 @@ import type { Command } from "commander";import chalk from "chalk";import { spawnSync } from "child_process";import { IxClient } from "../../client/api.js";-import { getEndpoint, clearIngestMtimeCache } from "../config.js";+import { getEndpoint, clearIngestMtimeCache, clearStitchScopeCache } from "../config.js";import { canRenderProgress } from "../stderr.js";+import { resolveWorkspaceId } from "../bootstrap.js";++/**+ * Drop this workspace's cached "am I stitched into a system?" answer.+ *+ * A reset wipes the graph, so the stitch records go with it and any cached+ * system id is now a lie. Best-effort and silent: an unresolvable workspace+ * simply has nothing cached to clear.+ */+function clearStitchScopeCacheForCwd(): void {+ const ws = resolveWorkspaceId(process.cwd());+ if (ws) clearStitchScopeCache(ws);+}export function registerResetCommand(program: Command): void {program@@ -56,12 +69,14 @@ export function registerResetCommand(program: Command): void {stopSpinner();// Clear the mtime cache so the next ix map re-ingests all filesclearIngestMtimeCache(process.cwd());+ clearStitchScopeCacheForCwd();console.log(chalk.green("✓") + " Code graph wiped. Planning artifacts preserved.");console.log(chalk.dim(" Run `ix map` to rebuild the code graph."));} else {await client.reset();stopSpinner();clearIngestMtimeCache(process.cwd());+ clearStitchScopeCacheForCwd();console.log(chalk.green("✓") + " Graph wiped.");}} catch (err: any) {diff --git a/ix-cli/src/cli/config.ts b/ix-cli/src/cli/config.tsindex cf47064d..ac547f8a 100644--- a/ix-cli/src/cli/config.ts+++ b/ix-cli/src/cli/config.ts@@ -16,6 +16,58 @@ export function ingestMtimeCachePath(projectRoot: string): string {return join(homedir(), ".ix", `ingest_mtimes_${key}.json`);}+/**+ * Path to the cached answer to "is this workspace stitched into a System?".+ *+ * Kept beside the ingest mtime cache and keyed the same way. See+ * `readStitchScope` for why this is on disk rather than in memory.+ */+export function stitchScopeCachePath(workspaceId: string): string {+ const key = createHash("sha256").update(workspaceId).digest("hex").slice(0, 12);+ return join(homedir(), ".ix", `stitch_scope_${key}.json`);+}++/**+ * The stitched system for a workspace, as last answered by the backend.+ *+ * `ensureReadScope` memoized this per process, which is no cache at all for a+ * CLI: every `ix` invocation is a fresh process, so every aggregate read paid+ * the lookup again. On a large graph that lookup is ~1.5 s — for `ix smells`,+ * three times the cost of the work it precedes.+ *+ * Returns `undefined` when there is nothing usable on disk, which is also what+ * a malformed or unreadable file returns: this is a cache, so every failure+ * means "ask the backend", never "fail the command".+ *+ * There is deliberately no TTL. A workspace's system changes when it is mapped+ * or ingested, and both of those clear this file (`clearStitchScopeCache`), so+ * a timer would only add a window in which the answer is wrong for no reason.+ */+export function readStitchScope(workspaceId: string): { systemId: string | null } | undefined {+ try {+ const raw = JSON.parse(readFileSync(stitchScopeCachePath(workspaceId), "utf-8"));+ if (raw?.workspaceId !== workspaceId) return undefined; // hash collision or hand-edit+ if (raw.systemId !== null && typeof raw.systemId !== "string") return undefined;+ return { systemId: raw.systemId };+ } catch {+ return undefined;+ }+}++/** Record the backend's answer. Best-effort: a cache that cannot be written is not an error. */+export function writeStitchScope(workspaceId: string, systemId: string | null): void {+ try {+ const path = stitchScopeCachePath(workspaceId);+ mkdirSync(join(homedir(), ".ix"), { recursive: true });+ writeFileSync(path, JSON.stringify({ workspaceId, systemId }) + "\n", "utf8");+ } catch { /* non-critical */ }+}++/** Drop the cached stitch answer. Called wherever the mtime cache is cleared. */+export function clearStitchScopeCache(workspaceId: string): void {+ try { rmSync(stitchScopeCachePath(workspaceId), { force: true }); } catch { /* non-critical */ }+}+/** Remove the ingest mtime cache so the next map re-ingests every file. Best-effort. */export function clearIngestMtimeCache(projectRoot: string): void {try { rmSync(ingestMtimeCachePath(projectRoot), { force: true }); } catch { /* non-critical */ }diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.tsindex 573354ef..0893f43a 100644--- a/ix-cli/src/cli/resolve.ts+++ b/ix-cli/src/cli/resolve.ts@@ -5,6 +5,7 @@ import { stderr } from "./stderr.js";import { applyRoleFilter } from "./role-filter.js";import { detectSystem } from "./system.js";import { resolveWorkspaceId } from "./bootstrap.js";+import { readStitchScope, writeStitchScope } from "./config.js";/*** The read scope for the current working directory: a co-ingested multi-repo system@@ -59,7 +60,21 @@ export async function ensureReadScope(client: Pick<IxClient, "workspaceSystem">)const ws = resolveWorkspaceId(cwd);let systemId: string | undefined;if (ws) {- try { systemId = (await client.workspaceSystem(ws)).systemId ?? undefined; } catch { /* best-effort */ }+ // Disk first. This lookup is ~1.5 s on a large graph and its answer changes+ // only when the workspace is mapped or ingested — both of which clear the+ // file — so asking the backend once per process was paying it on every+ // single `ix` invocation. `null` is a cached answer too: "not stitched" is+ // the common case and the one worth not re-asking.+ const cached = readStitchScope(ws);+ if (cached) {+ systemId = cached.systemId ?? undefined;+ } else {+ try {+ const answer = (await client.workspaceSystem(ws)).systemId ?? null;+ writeStitchScope(ws, answer);+ systemId = answer ?? undefined;+ } catch { /* best-effort: leave the scope at workspace level, cache nothing */ }+ }}_scopeCache = { cwd, workspaceId: systemId ? undefined : ws, systemId, stitchChecked: true };}