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(map): canonicalize and validate workspace roots (#545)
Hiro-Chiba3ca56a6b9dab
diff --git a/ix-cli/node_modules b/ix-cli/node_modulesnew file mode 120000index 00000000..ce7a785d--- /dev/null+++ b/ix-cli/node_modules@@ -0,0 +1 @@+/home/ianhock/ix-work/oss/Ix/ix-cli/node_modules\ No newline at end of filediff --git a/ix-cli/src/cli/__tests__/bootstrap-migration.test.ts b/ix-cli/src/cli/__tests__/bootstrap-migration.test.tsindex 13973da7..6d0c9615 100644--- a/ix-cli/src/cli/__tests__/bootstrap-migration.test.ts+++ b/ix-cli/src/cli/__tests__/bootstrap-migration.test.ts@@ -86,25 +86,45 @@ function readWorkspaceId(rootPath: string): string | undefined {}describe("workspace_id migration (Ix#225 gap 2)", () => {+ it.skipIf(process.platform === "win32")("normalizes an equivalent registered root instead of duplicating it", () => {+ const root = nodePath.join(home, "repoLinked");+ const linked = nodePath.join(home, "repoAlias");+ fs.mkdirSync(root, { recursive: true });+ fs.symlinkSync(root, linked, "dir");+ const canonicalRoot = fs.realpathSync.native(root);+ const pathId = workspaceIdForPath(canonicalRoot);+ writeConfig([{ workspace_id: pathId, workspace_name: "repoLinked", root_path: linked, default: true }]);++ const state = ensureWorkspaceIdState(root);+ const config = parse(fs.readFileSync(nodePath.join(home, ".ix", "config.yaml"), "utf8")) as {+ workspaces: { root_path: string }[];+ };++ expect(state.migrated).toBe(false);+ expect(config.workspaces).toHaveLength(1);+ expect(config.workspaces[0].root_path).toBe(canonicalRoot);+ });+it("re-keys a legacy random workspace_id to the path-based id and reports migrated", () => {const root = nodePath.join(home, "repoOne");fs.mkdirSync(root, { recursive: true });writeConfig([{ workspace_id: "rand0001", workspace_name: "repoOne", root_path: root, default: true }]);- const pathId = workspaceIdForPath(root);+ const canonicalRoot = fs.realpathSync.native(root);+ const pathId = workspaceIdForPath(canonicalRoot);expect(pathId).not.toBe("rand0001");const state = ensureWorkspaceIdState(root);expect(state.workspaceId).toBe(pathId);expect(state.migrated).toBe(true);expect(state.previousWorkspaceId).toBe("rand0001"); // captured for orphan cleanup- expect(readWorkspaceId(root)).toBe(pathId); // persisted+ expect(readWorkspaceId(canonicalRoot)).toBe(pathId); // persisted});it("does NOT migrate (or churn) a workspace already on the path-based id", () => {const root = nodePath.join(home, "repoTwo");fs.mkdirSync(root, { recursive: true });- const pathId = workspaceIdForPath(root);+ const pathId = workspaceIdForPath(fs.realpathSync.native(root));writeConfig([{ workspace_id: pathId, workspace_name: "repoTwo", root_path: root, default: true }]);const state = ensureWorkspaceIdState(root);@@ -118,7 +138,7 @@ describe("workspace_id migration (Ix#225 gap 2)", () => {writeConfig([]); // no workspaces yetconst state = ensureWorkspaceIdState(root);- expect(state.workspaceId).toBe(workspaceIdForPath(root));+ expect(state.workspaceId).toBe(workspaceIdForPath(fs.realpathSync.native(root)));expect(state.migrated).toBe(false);});});diff --git a/ix-cli/src/cli/__tests__/map-root.test.ts b/ix-cli/src/cli/__tests__/map-root.test.tsnew file mode 100644index 00000000..dc86ea35--- /dev/null+++ b/ix-cli/src/cli/__tests__/map-root.test.ts@@ -0,0 +1,171 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { execFileSync } from "node:child_process";+import { mkdtempSync, mkdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { Command } from "commander";+import { registerMapCommand } from "../commands/map.js";+import { canonicalMapRoot, resolveMapRoot } from "../map-root.js";+import { lockPathForTest } from "../single-flight.js";++const fixtures: string[] = [];+let savedHome: string | undefined;+let savedProfile: string | undefined;+let home: string;+let savedExitCode: number | string | undefined;++beforeEach(() => {+ savedHome = process.env.HOME;+ savedProfile = process.env.USERPROFILE;+ savedExitCode = process.exitCode;+ process.exitCode = undefined;+ home = fixture();+ process.env.HOME = home;+ process.env.USERPROFILE = home;+ mkdirSync(join(home, ".ix"), { recursive: true });+});++afterEach(() => {+ process.env.HOME = savedHome;+ process.env.USERPROFILE = savedProfile;+ process.exitCode = savedExitCode;+ vi.restoreAllMocks();+ for (const fixture of fixtures.splice(0)) rmSync(fixture, { recursive: true, force: true });+});++function fixture(): string {+ const dir = mkdtempSync(join(tmpdir(), "ix-map-root-"));+ fixtures.push(dir);+ return dir;+}++describe("map root resolution", () => {+ it("resolves an unregistered nested cwd to its git root", () => {+ const root = fixture();+ const nested = join(root, "src", "commands");+ mkdirSync(nested, { recursive: true });+ execFileSync("git", ["init", "-q"], { cwd: root });++ expect(resolveMapRoot(undefined, nested)).toBe(realpathSync.native(root));+ });++ // `ix map` writes. A configured workspace outranking the repository the user+ // is standing in means a bare `ix map` re-ingests a tree nothing on screen+ // names -- and rewrites that workspace's map baseline on the way through.+ it("maps the current repository, not the configured named workspace", () => {+ const selected = fixture();+ const repo = fixture();+ const nested = join(repo, "src");+ mkdirSync(nested, { recursive: true });+ execFileSync("git", ["init", "-q"], { cwd: repo });+ writeFileSync(join(home, ".ix", "config.yaml"), [+ "endpoint: http://localhost:8090",+ "workspace: selected",+ "workspaces:",+ " - workspace_id: selected-id",+ " workspace_name: selected",+ ` root_path: ${selected}`,+ " default: false",+ "",+ ].join("\n"));++ expect(resolveMapRoot(undefined, nested)).toBe(realpathSync.native(repo));+ });++ it("maps the current repository, not the default workspace", () => {+ const selected = fixture();+ const repo = fixture();+ const nested = join(repo, "src");+ mkdirSync(nested, { recursive: true });+ execFileSync("git", ["init", "-q"], { cwd: repo });+ writeFileSync(join(home, ".ix", "config.yaml"), [+ "endpoint: http://localhost:8090",+ "workspaces:",+ " - workspace_id: selected-id",+ " workspace_name: selected",+ ` root_path: ${selected}`,+ " default: true",+ "",+ ].join("\n"));++ expect(resolveMapRoot(undefined, nested)).toBe(realpathSync.native(repo));+ });++ it("prefers the registered workspace containing cwd over its git root", () => {+ const repo = fixture();+ const registered = join(repo, "packages", "inner");+ const nested = join(registered, "src");+ mkdirSync(nested, { recursive: true });+ execFileSync("git", ["init", "-q"], { cwd: repo });+ writeFileSync(join(home, ".ix", "config.yaml"), [+ "endpoint: http://localhost:8090",+ "workspaces:",+ " - workspace_id: inner-id",+ " workspace_name: inner",+ ` root_path: ${registered}`,+ " default: true",+ "",+ ].join("\n"));++ expect(resolveMapRoot(undefined, nested)).toBe(realpathSync.native(registered));+ });++ it("falls back to the default workspace when cwd has no local context", () => {+ const selected = fixture();+ const bare = fixture();+ writeFileSync(join(home, ".ix", "config.yaml"), [+ "endpoint: http://localhost:8090",+ "workspaces:",+ " - workspace_id: selected-id",+ " workspace_name: selected",+ ` root_path: ${selected}`,+ " default: true",+ "",+ ].join("\n"));++ expect(resolveMapRoot(undefined, bare)).toBe(realpathSync.native(selected));+ });++ it.skipIf(process.platform === "win32")("canonicalizes a symlink before deriving workspace identity", () => {+ const root = fixture();+ const real = join(root, "real");+ const linked = join(root, "linked");+ mkdirSync(real);+ symlinkSync(real, linked, "dir");++ expect(canonicalMapRoot(linked)).toBe(realpathSync.native(real));+ expect(lockPathForTest(linked)).toBe(lockPathForTest(real));+ });++ it("rejects a missing path before bootstrap can register it", () => {+ const root = fixture();+ const missing = join(root, "missing");++ expect(() => resolveMapRoot(missing, root)).toThrow(`Map path does not exist: ${missing}`);+ });++ it("reports a missing map path as structured json", async () => {+ const root = fixture();+ const missing = join(root, "missing");+ const output: string[] = [];+ vi.spyOn(console, "log").mockImplementation((...args: unknown[]) => output.push(args.join(" ")));+ const program = new Command();+ registerMapCommand(program);++ await program.parseAsync(["node", "ix", "map", missing, "--format", "json"]);++ expect(JSON.parse(output.join("\n"))).toEqual({+ error: "invalid_map_path",+ message: `Map path does not exist: ${missing}`,+ });+ expect(process.exitCode).toBe(1);+ });++ it("rejects a file path before bootstrap can register it", () => {+ const root = fixture();+ const file = join(root, "file.ts");+ writeFileSync(file, "export {};\n");++ expect(() => canonicalMapRoot(file)).toThrow(`Map path is not a directory: ${file}`);+ });+});diff --git a/ix-cli/src/cli/bootstrap.ts b/ix-cli/src/cli/bootstrap.tsindex b2c0bfbd..4727380e 100644--- a/ix-cli/src/cli/bootstrap.ts+++ b/ix-cli/src/cli/bootstrap.ts@@ -4,7 +4,7 @@ import { homedir } from "node:os";import { execFileSync } from "node:child_process";import chalk from "chalk";import { IxClient } from "../client/api.js";-import { getEndpoint, loadConfig, saveConfig, findWorkspaceForCwd, getDefaultWorkspace, type WorkspaceConfig } from "./config.js";+import { canonicalWorkspacePath, getEndpoint, loadConfig, saveConfig, findWorkspaceForCwd, getDefaultWorkspace, type WorkspaceConfig } from "./config.js";import { workspaceIdForPath } from "./system.js";import { readBackendHealth } from "./commands/upgrade.js";@@ -48,11 +48,13 @@ interface WorkspaceState { ws: WorkspaceConfig; created: boolean; migrated: bool* Returns the workspace name. Does nothing if already registered.*/function getOrCreateWorkspace(cwd: string): WorkspaceState {- const rootPath = resolve(cwd);+ const rootPath = canonicalWorkspacePath(resolve(cwd));const config = loadConfig();const pathId = workspaceIdForPath(rootPath);- const existing = (config.workspaces ?? []).find(w => w.root_path === rootPath);+ const existing = (config.workspaces ?? []).find(w => canonicalWorkspacePath(w.root_path) === rootPath);if (existing) {+ const pathChanged = existing.root_path !== rootPath;+ existing.root_path = rootPath;// Migrate a legacy random workspace_id to the path-based id (Ix#225 gap 2) so// an already-registered repo converges with co-ingest. This changes the// workspace_id that node identity folds, so the next map must re-ingest under@@ -64,6 +66,7 @@ function getOrCreateWorkspace(cwd: string): WorkspaceState {migratedRootsThisRun.set(rootPath, previousWorkspaceId);return { ws: existing, created: false, migrated: true, previousWorkspaceId };}+ if (pathChanged) saveConfig(config);const previousWorkspaceId = migratedRootsThisRun.get(rootPath);return { ws: existing, created: false, migrated: previousWorkspaceId !== undefined, previousWorkspaceId };}diff --git a/ix-cli/src/cli/commands/map.ts b/ix-cli/src/cli/commands/map.tsindex 64a3dc53..1b045643 100644--- a/ix-cli/src/cli/commands/map.ts+++ b/ix-cli/src/cli/commands/map.ts@@ -1,4 +1,3 @@-import { resolve } from "node:path";import { type Command } from "commander";import chalk from "chalk";import { IxClient } from "../../client/api.js";@@ -14,6 +13,7 @@ import { acquireMapLock } from "../single-flight.js";import { canRenderProgress } from "../stderr.js";import { loadIngestBaseline } from "../ingest-baseline.js";import { saveMapBaseline } from "../map-baseline.js";+import { resolveMapRoot } from "../map-root.js";// Hard wall-clock budget for a single `ix map`. Past this, the shared deadline// signal aborts every in-flight request and the command exits, so a single@@ -346,7 +346,21 @@ Examples:ix map . --full --verbose`).action(async (pathArg: string | undefined, opts: { format: string; level?: string; minConfidence: string; maxItems: string; allItems?: boolean; sort: string; graph?: boolean; list?: boolean; full?: boolean; verbose?: boolean; silent?: boolean }) => {- const cwd = pathArg ? resolve(pathArg) : process.cwd();+ let cwd: string;+ try {+ cwd = resolveMapRoot(pathArg);+ } catch (err: any) {+ const message = err?.message ?? "Invalid map path";+ if (opts.format === "json") {+ console.log(JSON.stringify({ error: "invalid_map_path", message }, null, 2));+ } else if (opts.format === "llm") {+ console.log(llmError("invalid_map_path", message));+ } else {+ console.error(chalk.red("Error:"), message);+ }+ process.exitCode = 1;+ return;+ }const silent = opts.silent === true || opts.format === "silent";diff --git a/ix-cli/src/cli/config.ts b/ix-cli/src/cli/config.tsindex 9cf73747..2a6ca750 100644--- a/ix-cli/src/cli/config.ts+++ b/ix-cli/src/cli/config.ts@@ -2,7 +2,7 @@ import { readFileSync, writeFileSync, existsSync, rmSync, chmodSync, renameSync,import { isAbsolute, join, relative, resolve as resolvePath, sep } from "node:path";import { homedir } from "node:os";import { createHash } from "node:crypto";-import { execSync } from "node:child_process";+import { execFileSync } from "node:child_process";import { parse, stringify } from "yaml";import { IxClient } from "../client/api.js";@@ -223,6 +223,12 @@ export function isPathInside(root: string, candidate: string): boolean {return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));}+export function canonicalWorkspacePath(input: string): string {+ const resolved = resolvePath(input);+ try { return realpathSync.native(resolved); }+ catch { return resolved; }+}+/*** Is a path contained by one specific root after resolving symlinks on both* sides? This is stricter than `isReadablePath`, which deliberately allows all@@ -267,9 +273,11 @@ export function selectWorkspaceForCwd(workspaces: WorkspaceConfig[],cwd: string,): WorkspaceConfig | undefined {+ const canonicalCwd = canonicalWorkspacePath(cwd);return workspaces- .filter(workspace => isPathInside(workspace.root_path, cwd))- .sort((a, b) => b.root_path.length - a.root_path.length)[0];+ .map(workspace => ({ workspace, root: canonicalWorkspacePath(workspace.root_path) }))+ .filter(({ root }) => isPathInside(root, canonicalCwd))+ .sort((a, b) => b.root.length - a.root.length)[0]?.workspace;}export function findWorkspaceForCwd(cwd: string): WorkspaceConfig | undefined {@@ -309,11 +317,10 @@ export function absoluteFromSourceUri(sourceUri: string, explicitRoot?: string):return resolvePath(root, normalized);}-export function resolveWorkspaceRoot(explicitRoot?: string): string {+export function resolveWorkspaceRoot(explicitRoot?: string, cwd = process.cwd()): string {// 1. Explicit --rootif (explicitRoot) return explicitRoot;// 2. Nearest initialized workspace containing cwd- const cwd = process.cwd();const nearest = findWorkspaceForCwd(cwd);if (nearest) return nearest.root_path;// 3. Named workspace from `ix config set workspace <name>`@@ -326,9 +333,25 @@ export function resolveWorkspaceRoot(explicitRoot?: string): string {const defaultWs = getDefaultWorkspace();if (defaultWs) return defaultWs.root_path;// 5. Git root- try {- return execSync("git rev-parse --show-toplevel", { encoding: "utf-8" }).trim();- } catch {}+ const gitRoot = gitRootFor(cwd);+ if (gitRoot) return gitRoot;// 6. cwd fallbackreturn cwd;}++/**+ * The git top-level containing `cwd`, or undefined outside a repository.+ *+ * stderr is discarded: outside a repo git writes "fatal: not a git repository"+ * to it, and this is a probe, not a failure the user needs to see.+ */+export function gitRootFor(cwd: string): string | undefined {+ try {+ const out = execFileSync("git", ["rev-parse", "--show-toplevel"], {+ cwd,+ encoding: "utf-8",+ stdio: ["ignore", "pipe", "ignore"],+ }).trim();+ return out || undefined;+ } catch { return undefined; }+}diff --git a/ix-cli/src/cli/map-root.ts b/ix-cli/src/cli/map-root.tsnew file mode 100644index 00000000..79ce9be0--- /dev/null+++ b/ix-cli/src/cli/map-root.ts@@ -0,0 +1,46 @@+import { realpathSync, statSync } from "node:fs";+import { resolve } from "node:path";+import { findWorkspaceForCwd, gitRootFor, resolveWorkspaceRoot } from "./config.js";++export function canonicalMapRoot(candidate: string): string {+ const resolved = resolve(candidate);+ let stat;+ try {+ stat = statSync(resolved);+ } catch {+ throw new Error(`Map path does not exist: ${resolved}`);+ }+ if (!stat.isDirectory()) {+ throw new Error(`Map path is not a directory: ${resolved}`);+ }+ return realpathSync.native(resolved);+}++/**+ * Which root does a bare `ix map` ingest?+ *+ * Deliberately NOT `resolveWorkspaceRoot`'s cascade. That one answers "which+ * graph am I querying?", where a configured workspace outranking the current+ * directory is the point. `ix map` writes: it re-ingests a tree and rewrites+ * that workspace's baseline. Letting a configured default outrank the+ * repository the user is standing in means `ix map` inside repo A silently+ * re-ingests repo B, with nothing on screen naming B.+ *+ * So the local answer wins whenever there is one:+ * 1. an explicit path argument+ * 2. the registered workspace containing cwd+ * 3. cwd's own git root <- ahead of the named/default workspace+ * 4. the named/default workspace, for a cwd with no local context at all+ * 5. cwd+ */+export function resolveMapRoot(pathArg?: string, cwd = process.cwd()): string {+ if (pathArg) return canonicalMapRoot(resolve(cwd, pathArg));++ const nearest = findWorkspaceForCwd(cwd);+ if (nearest) return canonicalMapRoot(nearest.root_path);++ const gitRoot = gitRootFor(cwd);+ if (gitRoot) return canonicalMapRoot(gitRoot);++ return canonicalMapRoot(resolveWorkspaceRoot(undefined, cwd));+}diff --git a/ix-cli/src/cli/single-flight.ts b/ix-cli/src/cli/single-flight.tsindex 69c24427..d78c3378 100644--- a/ix-cli/src/cli/single-flight.ts+++ b/ix-cli/src/cli/single-flight.ts@@ -1,5 +1,5 @@-import { mkdirSync, writeFileSync, readFileSync, rmSync, openSync, closeSync } from "node:fs";-import { join } from "node:path";+import { mkdirSync, writeFileSync, readFileSync, rmSync, openSync, closeSync, realpathSync } from "node:fs";+import { join, resolve } from "node:path";import { homedir, hostname } from "node:os";import { createHash } from "node:crypto";@@ -54,7 +54,10 @@ function lockMaxMs(): number {}function lockPathFor(key: string): string {- const h = createHash("sha256").update(key).digest("hex").slice(0, 16);+ let canonicalKey: string;+ try { canonicalKey = realpathSync.native(key); }+ catch { canonicalKey = resolve(key); }+ const h = createHash("sha256").update(canonicalKey).digest("hex").slice(0, 16);return join(lockDir(), `map-${h}.lock`);}