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(cli): refuse graph reads from an unmapped directory (workspace_not_mapped)
KageBinary979947e5a2c5
diff --git a/docs/llm-format.md b/docs/llm-format.mdindex 2de7d88b..00883270 100644--- a/docs/llm-format.md+++ b/docs/llm-format.md@@ -60,6 +60,9 @@ which value it ignored, on stderr, when a person is there to read it.format as data lines; the process still exits non-zero. A graph target thatdoes not exist is always `unresolved_target`. `locate` is the remainingexit-status exception tracked in #539.+ A graph read from a directory no registered workspace covers is+ `workspace_not_mapped`, with `dir=` and a `hint=` naming the command that+ maps it.An ambiguous graph target is instead `ambiguous_target`, includes numberedcandidates, and exits non-zero because the requested graph operation couldnot choose a target. (Thediff --git a/ix-cli/src/cli/__tests__/ambiguity-and-suggestions.test.ts b/ix-cli/src/cli/__tests__/ambiguity-and-suggestions.test.tsindex 4b0e168d..0c6b61e4 100644--- a/ix-cli/src/cli/__tests__/ambiguity-and-suggestions.test.ts+++ b/ix-cli/src/cli/__tests__/ambiguity-and-suggestions.test.ts@@ -3,6 +3,14 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { Command } from "commander";+// Graph reads refuse a directory no workspace covers (workspace_not_mapped),+// and this suite runs from a checkout that is not registered anywhere. It is+// about resolution, not scoping, so the directory counts as mapped here.+vi.mock("../bootstrap.js", async (orig) => ({+ ...(await orig<typeof import("../bootstrap.js")>()),+ resolveWorkspaceId: () => "ws-test",+}));+const search = vi.hoisted(() => vi.fn());vi.mock("../../client/api.js", () => ({diff --git a/ix-cli/src/cli/__tests__/diff-unresolved-target.test.ts b/ix-cli/src/cli/__tests__/diff-unresolved-target.test.tsindex bcc5f34e..42481fed 100644--- a/ix-cli/src/cli/__tests__/diff-unresolved-target.test.ts+++ b/ix-cli/src/cli/__tests__/diff-unresolved-target.test.ts@@ -12,6 +12,14 @@import { Command } from "commander";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+// Graph reads refuse a directory no workspace covers (workspace_not_mapped),+// and this suite runs from a checkout that is not registered anywhere. It is+// about resolution, not scoping, so the directory counts as mapped here.+vi.mock("../bootstrap.js", async (orig) => ({+ ...(await orig<typeof import("../bootstrap.js")>()),+ resolveWorkspaceId: () => "ws-test",+}));+vi.mock("../../client/api.js", () => ({IxClient: class {async workspaceSystem() { return { systemId: null }; }diff --git a/ix-cli/src/cli/__tests__/doctor-stats-once.test.ts b/ix-cli/src/cli/__tests__/doctor-stats-once.test.tsindex b9fe3563..446fc774 100644--- a/ix-cli/src/cli/__tests__/doctor-stats-once.test.ts+++ b/ix-cli/src/cli/__tests__/doctor-stats-once.test.ts@@ -263,7 +263,8 @@ describe("ix doctor", () => {const cwd = process.cwd().replace(/\\/g, "\\\\");expect(lines).toContain('check name="Workspace for this directory" status=fail detail="no workspace registered for ' +- `${cwd} — reads here answer from workspace 'other-repo' instead. ` ++ `${cwd} — graph reads here fail with workspace_not_mapped ` ++ "(they no longer fall back to the default workspace 'other-repo'). " +'Run `ix map` in this directory."',);});diff --git a/ix-cli/src/cli/__tests__/path-disambiguation.test.ts b/ix-cli/src/cli/__tests__/path-disambiguation.test.tsindex 2668127f..d00f71f5 100644--- a/ix-cli/src/cli/__tests__/path-disambiguation.test.ts+++ b/ix-cli/src/cli/__tests__/path-disambiguation.test.ts@@ -6,6 +6,15 @@ import { registerCallersCommand } from "../commands/callers.js";import { registerImpactCommand } from "../commands/impact.js";import { registerImportsCommand } from "../commands/imports.js";+// Graph reads refuse a directory no workspace covers (workspace_not_mapped),+// and this suite runs from a checkout that is not registered anywhere. It is+// about resolution, not scoping, so the directory counts as mapped here.+vi.mock("../bootstrap.js", async (orig) => ({+ ...(await orig<typeof import("../bootstrap.js")>()),+ resolveWorkspaceId: () => "ws-test",+}));++const { search, expand } = vi.hoisted(() => ({ search: vi.fn(), expand: vi.fn() }));vi.mock("../../client/api.js", () => ({diff --git a/ix-cli/src/cli/__tests__/read-local-first.test.ts b/ix-cli/src/cli/__tests__/read-local-first.test.tsindex 75860509..a26d1a47 100644--- a/ix-cli/src/cli/__tests__/read-local-first.test.ts+++ b/ix-cli/src/cli/__tests__/read-local-first.test.ts@@ -6,6 +6,15 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { Command } from "commander";+// Graph reads refuse a directory no workspace covers (workspace_not_mapped),+// and this suite runs from a checkout that is not registered anywhere. It is+// about resolution, not scoping, so the directory counts as mapped here.+vi.mock("../bootstrap.js", async (orig) => ({+ ...(await orig<typeof import("../bootstrap.js")>()),+ resolveWorkspaceId: () => "ws-test",+}));++const searchCalls: Array<Record<string, unknown>> = [];vi.mock("../../client/api.js", () => ({diff --git a/ix-cli/src/cli/__tests__/resolver-definitions-first.test.ts b/ix-cli/src/cli/__tests__/resolver-definitions-first.test.tsindex 99cfa8ed..60b44b1c 100644--- a/ix-cli/src/cli/__tests__/resolver-definitions-first.test.ts+++ b/ix-cli/src/cli/__tests__/resolver-definitions-first.test.ts@@ -4,6 +4,15 @@ import { describe, expect, it, vi } from "vitest";import { resolveEntityFull, scoreCandidate } from "../resolve.js";+// Graph reads refuse a directory no workspace covers (workspace_not_mapped),+// and this suite runs from a checkout that is not registered anywhere. It is+// about resolution, not scoping, so the directory counts as mapped here.+vi.mock("../bootstrap.js", async (orig) => ({+ ...(await orig<typeof import("../bootstrap.js")>()),+ resolveWorkspaceId: () => "ws-test",+}));++/*** The resolver behind `ix context` / `ix explain` / `ix locate` must pick the* code definition of a name, not an import of it (a `module` entity located indiff --git a/ix-cli/src/cli/__tests__/resolver-type-preference.test.ts b/ix-cli/src/cli/__tests__/resolver-type-preference.test.tsindex d08002d0..67003aeb 100644--- a/ix-cli/src/cli/__tests__/resolver-type-preference.test.ts+++ b/ix-cli/src/cli/__tests__/resolver-type-preference.test.ts@@ -1,9 +1,18 @@// Copyright 2026 Ix Infrastructure Inc.-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import { resolveEntityFull } from '../resolve.js';+// Graph reads refuse a directory no workspace covers (workspace_not_mapped),+// and this suite runs from a checkout that is not registered anywhere. It is+// about resolution, not scoping, so the directory counts as mapped here.+vi.mock("../bootstrap.js", async (orig) => ({+ ...(await orig<typeof import("../bootstrap.js")>()),+ resolveWorkspaceId: () => "ws-test",+}));++describe('resolver type preference', () => {it('prefers a class declaration over same-named method candidates for PascalCase symbols', async () => {const client = {diff --git a/ix-cli/src/cli/__tests__/search-ranking.test.ts b/ix-cli/src/cli/__tests__/search-ranking.test.tsindex f67312da..74dbfa58 100644--- a/ix-cli/src/cli/__tests__/search-ranking.test.ts+++ b/ix-cli/src/cli/__tests__/search-ranking.test.ts@@ -3,6 +3,15 @@import { describe, it, expect, vi } from "vitest";import { resolveEntityFull, scoreCandidate } from "../resolve.js";+// Graph reads refuse a directory no workspace covers (workspace_not_mapped),+// and this suite runs from a checkout that is not registered anywhere. It is+// about resolution, not scoping, so the directory counts as mapped here.+vi.mock("../bootstrap.js", async (orig) => ({+ ...(await orig<typeof import("../bootstrap.js")>()),+ resolveWorkspaceId: () => "ws-test",+}));++/*** Verify that search ranking correctly incorporates backend _search_weight.*diff --git a/ix-cli/src/cli/__tests__/stale-workspace.test.ts b/ix-cli/src/cli/__tests__/stale-workspace.test.tsindex a0573888..97f853a3 100644--- a/ix-cli/src/cli/__tests__/stale-workspace.test.ts+++ b/ix-cli/src/cli/__tests__/stale-workspace.test.ts@@ -273,8 +273,18 @@ describe("workspace-scoped staleness", () => {staleFiles: 1,sampleChangedFiles: ["deleted.js"],});- expect(isFileStale(filePath)).toBe(true);- expect(isFileStale(path.join(root, "never-mapped.js"))).toBe(false);+ // From inside the workspace, as a read runs. The probe resolves the active+ // root from cwd, and a repository cwd now outranks `default: true` (see+ // resolveWorkspaceRoot), so asking from this test's own checkout would ask+ // about that checkout instead.+ const previousCwd = process.cwd();+ process.chdir(root);+ try {+ expect(isFileStale(filePath)).toBe(true);+ expect(isFileStale(path.join(root, "never-mapped.js"))).toBe(false);+ } finally {+ process.chdir(previousCwd);+ }});it("persists an empty baseline after the last mapped file is deleted", () => {diff --git a/ix-cli/src/cli/__tests__/trace-path.test.ts b/ix-cli/src/cli/__tests__/trace-path.test.tsindex a374a6e6..3202e510 100644--- a/ix-cli/src/cli/__tests__/trace-path.test.ts+++ b/ix-cli/src/cli/__tests__/trace-path.test.ts@@ -1,9 +1,18 @@// Copyright 2026 Ix Infrastructure Inc.-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import { findPath, pickTraceTarget } from '../commands/trace.js';+// Graph reads refuse a directory no workspace covers (workspace_not_mapped),+// and this suite runs from a checkout that is not registered anywhere. It is+// about resolution, not scoping, so the directory counts as mapped here.+vi.mock("../bootstrap.js", async (orig) => ({+ ...(await orig<typeof import("../bootstrap.js")>()),+ resolveWorkspaceId: () => "ws-test",+}));++// ---------------------------------------------------------------------------// Helpers// ---------------------------------------------------------------------------diff --git a/ix-cli/src/cli/__tests__/unresolved-machine-output.test.ts b/ix-cli/src/cli/__tests__/unresolved-machine-output.test.tsindex 4952ecea..39ebad18 100644--- a/ix-cli/src/cli/__tests__/unresolved-machine-output.test.ts+++ b/ix-cli/src/cli/__tests__/unresolved-machine-output.test.ts@@ -3,6 +3,15 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { Command } from "commander";+// Graph reads refuse a directory no workspace covers (workspace_not_mapped),+// and this suite runs from a checkout that is not registered anywhere. It is+// about resolution, not scoping, so the directory counts as mapped here.+vi.mock("../bootstrap.js", async (orig) => ({+ ...(await orig<typeof import("../bootstrap.js")>()),+ resolveWorkspaceId: () => "ws-test",+}));++const search = vi.hoisted(() => vi.fn());vi.mock("../../client/api.js", () => ({diff --git a/ix-cli/src/cli/__tests__/workspace-not-mapped.test.ts b/ix-cli/src/cli/__tests__/workspace-not-mapped.test.tsnew file mode 100644index 00000000..76d0f85c--- /dev/null+++ b/ix-cli/src/cli/__tests__/workspace-not-mapped.test.ts@@ -0,0 +1,189 @@+// Copyright 2026 Ix Infrastructure Inc.++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import * as fs from "node:fs";+import * as os from "node:os";+import * as path from "node:path";+import { execFileSync } from "node:child_process";++import { requireReadWorkspaceId, resolveWorkspaceId } from "../bootstrap.js";+import { resolveWorkspaceRoot, saveConfig, type WorkspaceConfig } from "../config.js";+import { renderCliError, setErrorFormat, WorkspaceNotMappedError } from "../errors.js";+import { ensureReadScope, resetReadScope, resolveReadSystemId } from "../resolve.js";++/**+ * A graph read from a directory no workspace covers used to be answered: from+ * the `default: true` workspace (an unrelated repo), or, with none, unscoped+ * across every workspace on the backend -- `ix search resolveWorkspaceRoot`+ * came back as four rows, one per checkout of Ix mapped into the backend.+ */++let home: string;+let other: string;+let unmapped: string;+let savedCwd: string;++function register(workspaces: Array<Partial<WorkspaceConfig> & { root_path: string }>, extra: Record<string, unknown> = {}) {+ saveConfig({+ endpoint: "http://localhost:8090",+ format: "text",+ ...extra,+ workspaces: workspaces.map((w, i) => ({+ workspace_id: w.workspace_id ?? `ws00000${i}`,+ workspace_name: w.workspace_name ?? path.basename(w.root_path),+ root_path: w.root_path,+ default: w.default ?? false,+ })),+ } as never);+}++beforeEach(() => {+ home = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "ix-unmapped-")));+ process.env.IX_HOME = path.join(home, ".ix");+ other = path.join(home, "other-repo");+ unmapped = path.join(home, "somewhere-else");+ fs.mkdirSync(other, { recursive: true });+ fs.mkdirSync(unmapped, { recursive: true });+ savedCwd = process.cwd();+ resetReadScope();+});++afterEach(() => {+ process.chdir(savedCwd);+ delete process.env.IX_HOME;+ resetReadScope();+ fs.rmSync(home, { recursive: true, force: true });+});++describe("resolveWorkspaceId", () => {+ it("does not substitute the default workspace for a directory outside it", () => {+ register([{ root_path: other, workspace_id: "0ther001", default: true }]);+ expect(resolveWorkspaceId(unmapped)).toBeUndefined();+ expect(resolveWorkspaceId(path.join(other))).toBe("0ther001");+ });++ it("still honours a workspace pinned by name (`ix config set workspace <name>`)", () => {+ register([{ root_path: other, workspace_id: "0ther001", workspace_name: "other" }], { workspace: "other" });+ expect(resolveWorkspaceId(unmapped)).toBe("0ther001");+ });+});++describe("requireReadWorkspaceId", () => {+ it("names the directory and how to map it", () => {+ register([{ root_path: other, default: true }]);+ let error: unknown;+ try { requireReadWorkspaceId(unmapped); } catch (e) { error = e; }+ expect(error).toBeInstanceOf(WorkspaceNotMappedError);+ const e = error as WorkspaceNotMappedError;+ expect(e.code).toBe("workspace_not_mapped");+ expect(e.dir).toBe(unmapped);+ // Not in a git repository, so a bare `ix map` would fall back to the+ // default workspace: the path is spelled out.+ expect(e.hint).toContain(`ix map ${unmapped}`);+ // Stands alone: `ix mcp` relays the message as-is.+ expect(e.message).toMatch(/^workspace_not_mapped: .* is not inside a mapped Ix workspace/);+ expect(e.message).toContain(e.hint);+ });++ it("points a directory inside an unmapped git checkout at that checkout", () => {+ execFileSync("git", ["init", "-q", unmapped]);+ const sub = path.join(unmapped, "src");+ fs.mkdirSync(sub);+ register([]);+ let error: WorkspaceNotMappedError | undefined;+ try { requireReadWorkspaceId(sub); } catch (e) { error = e as WorkspaceNotMappedError; }+ expect(error?.hint).toContain(`Run \`ix map\` here to map ${unmapped}`);+ });+});++describe("read scope", () => {+ const client = { workspaceSystem: vi.fn(async () => ({ systemId: null })) };++ it("refuses an unscoped read instead of searching every workspace", async () => {+ register([{ root_path: other, default: true }]);+ process.chdir(unmapped);+ await expect(ensureReadScope(client)).rejects.toBeInstanceOf(WorkspaceNotMappedError);+ });++ it("lets `ix doctor` look at the state it exists to report", async () => {+ register([{ root_path: other, default: true }]);+ process.chdir(unmapped);+ await expect(resolveReadSystemId(client, { allowUnmapped: true })).resolves.toBeUndefined();+ });++ it("scopes a read from inside a mapped workspace as before", async () => {+ register([{ root_path: other, workspace_id: "0ther001" }]);+ process.chdir(other);+ await expect(ensureReadScope(client)).resolves.toBeUndefined();+ });+});++describe("resolveWorkspaceRoot", () => {+ it("ranks the git checkout the caller stands in above the default workspace", () => {+ // `ix text` from an unmapped checkout searched the default workspace's+ // files: an answer from an unrelated repository.+ execFileSync("git", ["init", "-q", unmapped]);+ register([{ root_path: other, default: true }]);+ expect(fs.realpathSync(resolveWorkspaceRoot(undefined, unmapped))).toBe(unmapped);+ });++ it("keeps the default workspace for a directory with no local context", () => {+ register([{ root_path: other, default: true }]);+ const bare = fs.mkdtempSync(path.join(os.tmpdir(), "ix-bare-"));+ try {+ // Only meaningful where the temp dir is not itself inside a checkout.+ let inGit = true;+ try { execFileSync("git", ["-C", bare, "rev-parse"], { stdio: "ignore" }); } catch { inGit = false; }+ if (!inGit) expect(resolveWorkspaceRoot(undefined, bare)).toBe(other);+ } finally {+ fs.rmSync(bare, { recursive: true, force: true });+ }+ });+});++describe("the error, rendered", () => {+ let out: string[];+ let err: string[];++ beforeEach(() => {+ out = [];+ err = [];+ vi.spyOn(console, "log").mockImplementation((...a) => void out.push(a.join(" ")));+ vi.spyOn(console, "error").mockImplementation((...a) => void err.push(a.join(" ")));+ vi.spyOn(process, "exit").mockImplementation((() => { throw new Error("exit"); }) as never);+ });++ afterEach(() => {+ vi.restoreAllMocks();+ setErrorFormat(undefined);+ });++ const failure = () => new WorkspaceNotMappedError("/work/unmapped", "Run `ix map /work/unmapped` to map this directory.");++ it("is one structured record in json", () => {+ setErrorFormat("json");+ expect(() => renderCliError(failure())).toThrow("exit");+ expect(JSON.parse(out.join("\n"))).toEqual({+ error: "workspace_not_mapped",+ message: "/work/unmapped is not inside a mapped Ix workspace, so there is no graph to answer from.",+ dir: "/work/unmapped",+ next: "Run `ix map /work/unmapped` to map this directory.",+ });+ });++ it("is one error record in llm", () => {+ setErrorFormat("llm");+ expect(() => renderCliError(failure())).toThrow("exit");+ expect(out).toEqual([+ 'error code=workspace_not_mapped message="/work/unmapped is not inside a mapped Ix workspace, so there is no graph to answer from." ' ++ 'dir=/work/unmapped hint="Run `ix map /work/unmapped` to map this directory."',+ ]);+ });++ it("is prose on stderr for a person, with nothing on stdout", () => {+ expect(() => renderCliError(failure())).toThrow("exit");+ expect(out).toEqual([]);+ expect(err.join("\n")).toContain("is not inside a mapped Ix workspace");+ expect(err.join("\n")).toContain("Run `ix map /work/unmapped`");+ });+});diff --git a/ix-cli/src/cli/bootstrap.ts b/ix-cli/src/cli/bootstrap.tsindex e57fafd5..4fe0c955 100644--- a/ix-cli/src/cli/bootstrap.ts+++ b/ix-cli/src/cli/bootstrap.ts@@ -7,7 +7,8 @@ import { execFileSync } from "node:child_process";import chalk from "chalk";import { IxClient } from "../client/api.js";import { renderBanner } from "./banner.js";-import { canonicalWorkspacePath, getEndpoint, loadConfig, saveConfig, findWorkspaceForCwd, getDefaultWorkspace, type WorkspaceConfig } from "./config.js";+import { canonicalWorkspacePath, getEndpoint, gitRootFor, loadConfig, loadWorkspaces, saveConfig, findWorkspaceForCwd, type WorkspaceConfig } from "./config.js";+import { WorkspaceNotMappedError, workspaceNotMappedHint } from "./errors.js";import { ixHome } from "./ix-home.js";import { stderr } from "./stderr.js";import { workspaceIdForPath } from "./system.js";@@ -142,13 +143,35 @@ export function ensureWorkspaceId(cwd = process.cwd()): string {}/**- * Resolve the workspace id for a READ, without creating one. Returns the id of the- * nearest registered workspace containing cwd, else the default workspace, else- * undefined — meaning an unscoped/global read, preserving back-compat for callers- * run outside any registered workspace.+ * Resolve the workspace id for a READ, without creating one: the nearest+ * registered workspace containing cwd, else a workspace pinned by name with+ * `ix config set workspace <name>`, else undefined.+ *+ * Deliberately NOT the `default: true` workspace. That flag is set on whichever+ * repo happened to be mapped first, not chosen, and falling back to it answered+ * reads from an unrelated repository with nothing on screen saying so (the+ * ix-bench runner found agents in an unregistered worktree getting another+ * repo's `ix context`). Undefined is not "read everything" either: graph reads+ * refuse it through {@link requireReadWorkspaceId}.*/export function resolveWorkspaceId(cwd = process.cwd()): string | undefined {- return (findWorkspaceForCwd(cwd) ?? getDefaultWorkspace())?.workspace_id;+ const nearest = findWorkspaceForCwd(cwd);+ if (nearest) return nearest.workspace_id;+ const pinned = loadConfig().workspace;+ if (pinned) return loadWorkspaces().find(w => w.workspace_name === pinned)?.workspace_id;+ return undefined;+}++/**+ * The workspace a graph read is scoped to, or a {@link WorkspaceNotMappedError}+ * naming the directory and how to map it. For every command whose answer comes+ * from the graph; commands that do not need one (`text`, `status`, `doctor`,+ * `view --all`, `map` itself) never call this.+ */+export function requireReadWorkspaceId(cwd = process.cwd()): string {+ const id = resolveWorkspaceId(cwd);+ if (id) return id;+ throw new WorkspaceNotMappedError(cwd, workspaceNotMappedHint(cwd, gitRootFor(cwd)));}/**diff --git a/ix-cli/src/cli/commands/doctor.ts b/ix-cli/src/cli/commands/doctor.tsindex 1a801460..65843d90 100644--- a/ix-cli/src/cli/commands/doctor.ts+++ b/ix-cli/src/cli/commands/doctor.ts@@ -160,7 +160,7 @@ export function registerDoctorCommand(program: Command): void {// count. What the unscoped call added was every *live* node belonging to// some other workspace on the same backend, which is how a freshly// reset workspace still looked like a 17k-node graph.- const systemId = await resolveReadSystemId(client);+ const systemId = await resolveReadSystemId(client, { allowUnmapped: true });const workspace = systemId ? undefined : (matchedWorkspace ?? substitutedWorkspace);const stats = await client.stats({ workspaceId: workspace?.workspace_id, systemId });// Named, not deictic. "this workspace" is only true when cwd actually@@ -219,8 +219,8 @@ export function registerDoctorCommand(program: Command): void {return {ok: false,detail:- `no workspace registered for ${cwd} — reads here answer from ` +- `workspace '${substitutedWorkspace.workspace_name}' instead. ` ++ `no workspace registered for ${cwd} — graph reads here fail with workspace_not_mapped ` ++ `(they no longer fall back to the default workspace '${substitutedWorkspace.workspace_name}'). ` +"Run `ix map` in this directory.",};}diff --git a/ix-cli/src/cli/config.ts b/ix-cli/src/cli/config.tsindex 88a18862..89e4c6f5 100644--- a/ix-cli/src/cli/config.ts+++ b/ix-cli/src/cli/config.ts@@ -362,12 +362,17 @@ export function resolveWorkspaceRoot(explicitRoot?: string, cwd = process.cwd())const named = loadWorkspaces().find(w => w.workspace_name === cfg.workspace);if (named) return named.root_path;}- // 4. Configured default workspace- const defaultWs = getDefaultWorkspace();- if (defaultWs) return defaultWs.root_path;- // 5. Git root+ // 4. Git root: the repository the caller is standing in. Ahead of the+ // default workspace for the reason `resolveMapRoot` gives: `default: true`+ // marks whichever repo was mapped first, so ranking it above a local+ // repository made `ix text` in an unmapped checkout search an unrelated+ // one. (Graph reads from such a directory refuse outright; see+ // `requireReadWorkspaceId`.)const gitRoot = gitRootFor(cwd);if (gitRoot) return gitRoot;+ // 5. Configured default workspace, for a cwd with no local context at all+ const defaultWs = getDefaultWorkspace();+ if (defaultWs) return defaultWs.root_path;// 6. cwd fallbackreturn cwd;}diff --git a/ix-cli/src/cli/errors.ts b/ix-cli/src/cli/errors.tsindex 79adc30c..20cf6451 100644--- a/ix-cli/src/cli/errors.ts+++ b/ix-cli/src/cli/errors.ts@@ -57,9 +57,14 @@ export function detectRequestedFormat(argv: readonly string[]): string | undefin* answer, because X" is an answer. The human prose is then skipped rather than* printed alongside, so the caller gets exactly one report.*/-function emitLlmError(code: string, message: string, hint?: string): boolean {+function emitLlmError(+ code: string,+ message: string,+ hint?: string,+ extra: Array<[string, string]> = [],+): boolean {if (requestedFormat !== "llm") return false;- console.log(llmError(code, message, hint ? [["hint", hint]] : []));+ console.log(llmError(code, message, [...extra, ...(hint ? [["hint", hint] as [string, string]] : [])]));return true;}@@ -133,6 +138,47 @@ export class CliResolutionError extends Error {}}+/**+ * A graph read was asked for from a directory no registered workspace covers.+ *+ * This used to be answered anyway: the read fell back to whichever workspace+ * carried `default: true` -- an unrelated repository -- or, with no default,+ * ran unscoped across every workspace on the backend, which is how one+ * function came back as four rows from four checkouts of the same repo. Both+ * look like answers. Refusing, and saying how to map the directory, is the+ * only response that cannot be mistaken for one.+ *+ * Its `message` stands alone, because `ix mcp` runs commands in-process and+ * relays a thrown error's message as-is rather than through the renderer below.+ */+export class WorkspaceNotMappedError extends Error {+ readonly code = "workspace_not_mapped";+ constructor(+ public readonly dir: string,+ public readonly hint: string = workspaceNotMappedHint(dir),+ ) {+ super(`workspace_not_mapped: ${dir} is not inside a mapped Ix workspace, so there is no graph to answer from. ${hint}`);+ this.name = "WorkspaceNotMappedError";+ }+ /** The message without the code prefix or the hint, for renderers that carry both separately. */+ get summary(): string {+ return `${this.dir} is not inside a mapped Ix workspace, so there is no graph to answer from.`;+ }+}++/**+ * How to get a graph for `dir`. `ix map` with no argument maps the enclosing+ * git repository (see `resolveMapRoot`), so that is named when there is one;+ * outside a repository a bare `ix map` would fall back to the configured+ * default workspace, so the path is spelled out instead.+ */+export function workspaceNotMappedHint(dir: string, gitRoot?: string): string {+ const map = gitRoot+ ? `Run \`ix map\` here to map ${gitRoot}`+ : `Run \`ix map ${dir}\` to map this directory`;+ return `${map}, or run the command from inside a workspace that is already mapped (\`ix config show\` lists them).`;+}+/*** Format an error for display, unwrapping fetch `TypeError: fetch failed`* to expose the underlying transport cause (e.g. ECONNRESET, UND_ERR_SOCKET).@@ -294,6 +340,15 @@ export function renderCliError(err: unknown, debug = false, endpoint?: string):process.exit(1);}+ if (err instanceof WorkspaceNotMappedError) {+ if (requestedFormat === "json") {+ console.log(JSON.stringify({ error: err.code, message: err.summary, dir: err.dir, next: err.hint }));+ } else if (!emitLlmError(err.code, err.summary, err.hint, [["dir", err.dir]])) {+ renderStructuredError({ error: err.code, message: err.summary, next: err.hint });+ }+ process.exit(1);+ }+const e = err as any;if (isBackendUnreachable(err)) {diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.tsindex b6e982db..121bbb7a 100644--- a/ix-cli/src/cli/resolve.ts+++ b/ix-cli/src/cli/resolve.ts@@ -6,7 +6,7 @@ import type { IxClient } from "../client/api.js";import { stderr } from "./stderr.js";import { applyRoleFilter } from "./role-filter.js";import { detectSystem } from "./system.js";-import { resolveWorkspaceId } from "./bootstrap.js";+import { requireReadWorkspaceId, resolveWorkspaceId } from "./bootstrap.js";import { readStitchScope, writeStitchScope } from "./config.js";import { reportAmbiguousTarget, reportResolutionFailure } from "./ui.js";import { relativePath } from "./format.js";@@ -60,7 +60,21 @@ function activeScope(): { workspaceId?: string; systemId?: string } {* Best-effort + cached (one lookup per cwd); an older backend or a true singleton* leaves the scope at workspace level. Read commands `await` this before resolving.*/-export async function ensureReadScope(client: Pick<IxClient, "workspaceSystem">): Promise<void> {+export async function ensureReadScope(+ client: Pick<IxClient, "workspaceSystem">,+ opts?: { allowUnmapped?: boolean },+): Promise<void> {+ await foldStitchedSystem(client);+ // A read with neither a workspace nor a system would run unscoped, across+ // every workspace on the backend: the same function once per checkout, from+ // repositories the caller never asked about. Refused with the fix instead.+ // `ix doctor` opts out -- reporting this state is its job, not failing on it.+ if (!opts?.allowUnmapped && !_scopeCache?.workspaceId && !_scopeCache?.systemId) {+ requireReadWorkspaceId(process.cwd());+ }+}++async function foldStitchedSystem(client: Pick<IxClient, "workspaceSystem">): Promise<void> {const cwd = process.cwd();if (_scopeCache?.cwd === cwd && _scopeCache.stitchChecked) return;const localSystem = detectSystem(cwd)?.systemId;@@ -92,8 +106,11 @@ export async function ensureReadScope(client: Pick<IxClient, "workspaceSystem">)* scope to: a co-ingest system (detectSystem) OR a Path-2 stitched system (backend* lookup), else undefined (workspace-scoped). Drop-in for `detectSystem(cwd)?.systemId`.*/-export async function resolveReadSystemId(client: Pick<IxClient, "workspaceSystem">): Promise<string | undefined> {- await ensureReadScope(client);+export async function resolveReadSystemId(+ client: Pick<IxClient, "workspaceSystem">,+ opts?: { allowUnmapped?: boolean },+): Promise<string | undefined> {+ await ensureReadScope(client, opts);return activeReadScope().systemId;}diff --git a/skills/ix/references/troubleshooting.md b/skills/ix/references/troubleshooting.mdindex 2c87832a..7c4d9e8a 100644--- a/skills/ix/references/troubleshooting.md+++ b/skills/ix/references/troubleshooting.md@@ -38,6 +38,7 @@ again.| `Compass UI not found` on `ix view` | Run `ix upgrade` to fetch Compass. Re-running the installer wipes the Compass assets, so bootstrap auto-restores them with `ix upgrade`; skip with `IX_SKIP_COMPASS=1` || Compass shows "Compass not connected to a codebase" | The scoped workspace has no graph — run `ix map .` from the repo root, then reload the tab || Slow or stale results | Re-run `ix map --silent` to refresh the graph |+| `error code=workspace_not_mapped` | The directory is in no registered workspace. Graph reads no longer fall back to the `default: true` workspace (an unrelated repo) or to every workspace on the backend. Run `ix map` in the repo (the error names the root it would map), or run from inside a mapped one || `graph status=degraded` / `classification=degraded` | The graph kept its nodes but lost its edges, so zero callers/members mean *unknown*, not none. Usually another checkout of the same repo was ingested into this backend later (Ix-memory#211). `ix map` and `ix ingest --force` do not repair it; `ix reset --workspace --yes --ingest` (this workspace only) does. It hollows the other checkout in turn until the backend fix ships || `Commits against <endpoint> kept failing` | Commits kept failing, so `ix map` gave up rather than sending one doomed request per file. Read the `Last error` line it prints — the CLI cannot tell the two causes apart, because the memory layer answers 500 for both. **A saturated database:** `ix doctor` still passes (it asks whether the backend is reachable and the graph consistent, and an ArangoDB too busy to begin a transaction is both), so check `docker stats` and `GET /_db/<db>/_api/query/current`, then re-map once it is idle. **Patches the backend will not accept:** the error names the patch or the field; re-map after fixing it, or `IX_COMMIT_FAILURE_LIMIT=0` to send the rest regardless. |