Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

test(cli): replace source-grep tests with behaviour tests (QA-06B)

KageBinaryf685658fb148
diff --git a/ix-cli/src/cli/__tests__/depends-semantics.test.ts b/ix-cli/src/cli/__tests__/depends-semantics.test.ts
index 781c8ade..217d99db 100644
--- a/ix-cli/src/cli/__tests__/depends-semantics.test.ts
+++ b/ix-cli/src/cli/__tests__/depends-semantics.test.ts
@@ -1,147 +1,207 @@
// Copyright 2026 Ix Infrastructure Inc.
-import { describe, it, expect } from "vitest";
-import * as fs from "node:fs";
-import * as path from "node:path";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Command } from "commander";
+import { registerDependsCommand } from "../commands/depends.js";
/**
- * Verify that `ix depends` presents results in dependency direction,
- * uses full-tree traversal, and has correct semantics.
+ * `ix depends` presents results in dependency direction, walks the upstream
+ * tree one hop at a time, and says what it is. Run through the registered
+ * command against a fake graph, so what is checked is what a caller sees.
*/
-const dependsTsPath = path.resolve(__dirname, "../commands/depends.ts");
-const dependsContent = fs.readFileSync(dependsTsPath, "utf-8");
-// The walk itself is shared with `ix trace`.
-const walkContent = fs.readFileSync(path.resolve(__dirname, "../tree-walk.ts"), "utf-8");
+// This suite is about the walk and its output, not about scoping.
+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", () => ({
+ IxClient: class {
+ async workspaceSystem() { return { systemId: null }; }
+ async search(...args: unknown[]) { return search(...args); }
+ async expand(...args: unknown[]) { return expand(...args); }
+ },
+}));
+
+vi.mock("../config.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../config.js")>(),
+ readStitchScope: () => undefined,
+ writeStitchScope: vi.fn(),
+}));
+
+function node(id: string, name: string, kind: string, sourceUri: string) {
+ return { id, name, kind, attrs: {}, provenance: { sourceUri } };
+}
+
+const TARGET = node("target-id", "Target", "function", "src/target.ts");
+const ALPHA = node("alpha-id", "Alpha", "function", "src/alpha.ts");
+const BRAVO = node("bravo-id", "Bravo", "file", "src/bravo.ts");
+const CHARLIE = node("charlie-id", "Charlie", "function", "src/charlie.ts");
-// ── Direction semantics ─────────────────────────────────────────────
-
-describe("depends direction semantics", () => {
- it("description says upstream dependents", () => {
- expect(dependsContent).toContain("upstream dependents");
- expect(dependsContent).not.toContain("reverse CALLS");
- });
-
- it("text heading uses dependency-oriented language", () => {
- expect(dependsContent).toContain("Dependents");
- });
-
- it("empty state message uses dependency language", () => {
- expect(dependsContent).toContain("No upstream dependents found");
- });
-
- it("uses dependency-oriented relation values", () => {
- expect(dependsContent).toContain('"called_by"');
- expect(dependsContent).toContain('"imported_by"');
- });
+/**
+ * Who points at whom, keyed by `<id>|<predicate>`: Target <-CALLS- Alpha,
+ * Target <-IMPORTS- Bravo, Alpha <-CALLS- Charlie, Charlie <-CALLS- Alpha
+ * (a cycle back to Alpha).
+ */
+const INBOUND: Record<string, unknown[]> = {
+ "target-id|CALLS": [ALPHA],
+ "target-id|IMPORTS": [BRAVO],
+ "alpha-id|CALLS": [CHARLIE],
+ "charlie-id|CALLS": [ALPHA],
+};
+
+const ANSI = /\x1b\[[0-9;]*m/g;
+
+async function run(args: string[]): Promise<{ stdout: string; stderr: string; command: Command }> {
+ const program = new Command().name("ix").exitOverride();
+ registerDependsCommand(program);
+ const stdout: string[] = [];
+ const stderr: string[] = [];
+ const log = vi.spyOn(console, "log").mockImplementation((...parts) => { stdout.push(parts.join(" ")); });
+ const error = vi.spyOn(console, "error").mockImplementation((...parts) => { stderr.push(parts.join(" ")); });
+ const write = vi.spyOn(process.stderr, "write").mockImplementation(((part: string) => {
+ stderr.push(String(part));
+ return true;
+ }) as never);
+ try {
+ await program.parseAsync(["depends", ...args], { from: "user" });
+ } finally {
+ log.mockRestore();
+ error.mockRestore();
+ write.mockRestore();
+ }
+ const command = program.commands.find((c) => c.name() === "depends")!;
+ return { stdout: stdout.join("\n").replace(ANSI, ""), stderr: stderr.join("\n").replace(ANSI, ""), command };
+}
+
+async function runJson(args: string[]): Promise<any> {
+ return JSON.parse((await run([...args, "--format", "json"])).stdout);
+}
+
+function findChild(nodes: any[] | undefined, name: string): any {
+ const found = (nodes ?? []).find((n) => n.name === name);
+ expect(found, `child ${name}`).toBeDefined();
+ return found;
+}
+
+let savedExitCode: typeof process.exitCode;
+
+beforeEach(() => {
+ savedExitCode = process.exitCode;
+ process.exitCode = undefined;
+ search.mockReset().mockImplementation(async (term: string, opts?: { kind?: string }) =>
+ [TARGET].filter((n) => n.name.toLowerCase().includes(term.toLowerCase()) && (!opts?.kind || n.kind === opts.kind)));
+ expand.mockReset().mockImplementation(async (id: string, opts: { predicates: string[] }) =>
+ ({ nodes: INBOUND[`${id}|${opts.predicates[0]}`] ?? [], edges: [] }));
});
-// ── Full-tree traversal ─────────────────────────────────────────────
+afterEach(() => {
+ process.exitCode = savedExitCode;
+ vi.restoreAllMocks();
+});
-describe("depends full-tree traversal", () => {
- it("has buildDependencyTree function", () => {
- expect(dependsContent).toContain("buildDependencyTree");
- });
+// ── Direction semantics ─────────────────────────────────────────────
- it("expands recursively via one-hop calls", () => {
- // Uses hops: 1 for each level; the shared walk fetches breadth-first and
- // builds the tree by the depth-first recursion it always used.
- expect(dependsContent).toContain("hops: 1");
- expect(dependsContent).toContain("walkTree<DependencyNode>");
- expect(walkContent).toContain("await expand(n.id, depth + 1)");
+describe("depends direction semantics", () => {
+ it("description says upstream dependents", async () => {
+ const { command } = await run(["Target", "--format", "json"]);
+ expect(command.description()).toContain("upstream dependents");
+ expect(command.description()).not.toContain("reverse CALLS");
});
- it("defaults to full traversal without --depth", () => {
- // --depth has no default value in option declaration
- expect(dependsContent).toContain('depth?: string');
- expect(dependsContent).toContain("DEFAULT_MAX_DEPTH");
+ it("walks inbound edges one hop and one predicate at a time, across all five predicates", async () => {
+ await run(["Target", "--format", "json"]);
+ expect(expand).toHaveBeenCalled();
+ for (const [, opts] of expand.mock.calls) {
+ expect(opts).toMatchObject({ direction: "in", hops: 1 });
+ expect(opts.predicates).toHaveLength(1);
+ }
+ const atRoot = new Set(expand.mock.calls.filter(([id]) => id === "target-id").map(([, opts]) => opts.predicates[0]));
+ expect(atRoot).toEqual(new Set(["CALLS", "IMPORTS", "REFERENCES", "EXTENDS", "IMPLEMENTS"]));
});
- it("--depth acts as optional limiter", () => {
- expect(dependsContent).toContain('"--depth <n>"');
- expect(dependsContent).toContain("Cap traversal depth");
+ it("text heading uses dependency-oriented language", async () => {
+ const { stdout } = await run(["Target"]);
+ expect(stdout).toContain("Dependents");
});
- it("has cycle detection", () => {
- expect(walkContent).toContain("visited.has(n.id)");
- expect(dependsContent).toContain("cycle: true");
- });
+ it("empty state message uses dependency language", async () => {
+ expand.mockResolvedValue({ nodes: [], edges: [] });
+ const { stdout } = await run(["Target"]);
+ expect(stdout).toContain("No upstream dependents found");
- it("has node cap safety limit", () => {
- expect(dependsContent).toContain("MAX_NODES");
- expect(walkContent).toContain("nodesVisited >= opts.maxNodes");
+ const output = await runJson(["Target"]);
+ expect(output.tree).toEqual([]);
+ expect(output.diagnostics[0].code).toBe("no_edges");
});
- it("reports a cap cut and a depth stop as the different things they are", () => {
- // Only the node cap can know that nodes were lost; reaching the depth
- // bound means the walk stopped descending, which is not the same claim.
- expect(walkContent).toContain("truncated = true");
- expect(walkContent).toContain("depthLimited = true");
- expect(dependsContent).toContain("traversalHint");
+ it("uses dependency-oriented relation values", async () => {
+ const output = await runJson(["Target"]);
+ expect(findChild(output.tree, "Alpha").rel).toBe("called_by");
+ expect(findChild(output.tree, "Bravo").rel).toBe("imported_by");
});
});
-// ── Nested tree output ──────────────────────────────────────────────
-
-describe("depends nested tree structure", () => {
- it("has DependencyNode interface with children", () => {
- expect(dependsContent).toContain("interface DependencyNode");
- expect(dependsContent).toContain("children: DependencyNode[]");
- });
+// ── Full-tree traversal ─────────────────────────────────────────────
- it("JSON outputs tree field not flat results", () => {
- expect(dependsContent).toContain("tree,");
- expect(dependsContent).not.toMatch(/\bresults: allDependents\.map\b/);
+describe("depends full-tree traversal", () => {
+ it("expands recursively via one-hop calls", async () => {
+ const output = await runJson(["Target"]);
+ const charlie = findChild(findChild(output.tree, "Alpha").children, "Charlie");
+ expect(charlie.rel).toBe("called_by");
+ // Charlie's own dependents were asked for, one hop from Charlie.
+ expect(expand.mock.calls.some(([id]) => id === "charlie-id")).toBe(true);
});
- it("JSON includes traversal metadata", () => {
- expect(dependsContent).toContain("nodesVisited");
- expect(dependsContent).toContain("maxDepthReached");
- expect(dependsContent).toContain("truncated");
+ it("defaults to depth 3 and 100 nodes without --depth or --cap", async () => {
+ const output = await runJson(["Target"]);
+ expect(output.traversal.depthLimit).toBe(3);
+ expect(output.traversal.nodeCap).toBe(100);
});
- it("renders text tree with box-drawing glyphs", () => {
- expect(dependsContent).toContain("└─");
- expect(dependsContent).toContain("├─");
- expect(dependsContent).toContain("│");
+ it("--depth and --cap act as limiters", async () => {
+ const output = await runJson(["Target", "--depth", "1", "--cap", "5"]);
+ expect(output.traversal.depthLimit).toBe(1);
+ expect(output.traversal.nodeCap).toBe(5);
+ expect(findChild(output.tree, "Alpha").children).toBeUndefined();
});
- it("JSON includes semantics field", () => {
- expect(dependsContent).toContain('"downstream_dependents"');
+ it("marks a node already on the walk as a cycle instead of following it", async () => {
+ const output = await runJson(["Target"]);
+ const charlie = findChild(findChild(output.tree, "Alpha").children, "Charlie");
+ expect(charlie.children.some((n: any) => n.cycle === true)).toBe(true);
});
});
-// ── Input validation ────────────────────────────────────────────────
-
-describe("depends input validation", () => {
- it("validates --pick as positive integer", () => {
- expect(dependsContent).toContain("parsePickOption");
- });
-
- it("supports --pick option", () => {
- expect(dependsContent).toContain('"--pick <n>"');
- });
-
- it("supports --kind option", () => {
- expect(dependsContent).toContain('"--kind <kind>"');
- });
+// ── Nested tree output ──────────────────────────────────────────────
- it("supports --path option", () => {
- expect(dependsContent).toContain('"--path <path>"');
+describe("depends nested tree structure", () => {
+ it("JSON outputs a nested tree field, not flat results", async () => {
+ const output = await runJson(["Target"]);
+ expect(Array.isArray(output.tree)).toBe(true);
+ expect(output.results).toBeUndefined();
+ expect(Array.isArray(findChild(output.tree, "Alpha").children)).toBe(true);
});
- it("supports --format option", () => {
- expect(dependsContent).toContain('"--format <fmt>"');
+ it("JSON includes traversal metadata", async () => {
+ const { traversal } = await runJson(["Target"]);
+ expect(typeof traversal.nodesVisited).toBe("number");
+ expect(typeof traversal.maxDepthReached).toBe("number");
+ expect(typeof traversal.truncated).toBe("boolean");
});
- it("uses resolveFileOrReport with resolveOpts", () => {
- expect(dependsContent).toContain("resolveFileOrReport(client, symbol, resolveOpts, opts.format)");
+ it("renders text tree with box-drawing glyphs", async () => {
+ const { stdout } = await run(["Target"]);
+ expect(stdout).toContain("├─");
+ expect(stdout).toContain("└─");
+ expect(stdout).toContain("│");
});
- it("traverses edges in reverse via predicate map", () => {
- expect(dependsContent).toContain('direction: "in"');
- expect(dependsContent).toContain("predicates: [p]");
- expect(dependsContent).toContain("CALLS");
- expect(dependsContent).toContain("IMPORTS");
+ it("JSON includes semantics field", async () => {
+ const output = await runJson(["Target"]);
+ expect(output.semantics).toBe("downstream_dependents");
});
});
diff --git a/ix-cli/src/cli/__tests__/file-resolution.test.ts b/ix-cli/src/cli/__tests__/file-resolution.test.ts
index dd920008..801070fc 100644
--- a/ix-cli/src/cli/__tests__/file-resolution.test.ts
+++ b/ix-cli/src/cli/__tests__/file-resolution.test.ts
@@ -1,149 +1,293 @@
// Copyright 2026 Ix Infrastructure Inc.
-import { describe, it, expect } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Command } from "commander";
import * as fs from "node:fs";
+import * as os from "node:os";
import * as path from "node:path";
/**
- * Verify that the shared file-first resolution helper exists
- * and that all graph navigation commands use it consistently.
+ * The shared file-first resolution helper, and the commands that take a file
+ * or entity target, checked by what they do: which file a target resolves to,
+ * in which order the graph is asked, and which id reaches the backend.
*/
-const resolveTsPath = path.resolve(__dirname, "../resolve.ts");
-const resolveContent = fs.readFileSync(resolveTsPath, "utf-8");
+// Graph reads refuse a directory no workspace covers (workspace_not_mapped),
+// and this suite runs from a tmp directory 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 historyTsPath = path.resolve(__dirname, "../commands/history.ts");
-const historyContent = fs.readFileSync(historyTsPath, "utf-8");
+const client = vi.hoisted(() => ({
+ search: vi.fn(),
+ entity: vi.fn(),
+ expand: vi.fn(),
+ provenance: vi.fn(),
+ diff: vi.fn(),
+ listPatches: vi.fn(),
+ resolvePrefix: vi.fn(),
+}));
-const diffTsPath = path.resolve(__dirname, "../commands/diff.ts");
-const diffContent = fs.readFileSync(diffTsPath, "utf-8");
+vi.mock("../../client/api.js", () => ({
+ IxClient: class {
+ async workspaceSystem() { return { systemId: null }; }
+ async search(...args: unknown[]) { return client.search(...args); }
+ async entity(...args: unknown[]) { return client.entity(...args); }
+ async expand(...args: unknown[]) { return client.expand(...args); }
+ async provenance(...args: unknown[]) { return client.provenance(...args); }
+ async diff(...args: unknown[]) { return client.diff(...args); }
+ async listPatches(...args: unknown[]) { return client.listPatches(...args); }
+ async resolvePrefix(...args: unknown[]) { return client.resolvePrefix(...args); }
+ },
+}));
-/** Commands that should all use resolveFileOrEntity for consistent file-path support. */
-const COMMANDS_USING_FILE_RESOLUTION = [
- "overview", "callers", "contains", "imports", "depends", "locate", "impact", "explain",
-];
+vi.mock("../config.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../config.js")>(),
+ readStitchScope: () => undefined,
+ writeStitchScope: vi.fn(),
+}));
+
+vi.mock("../hierarchy.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../hierarchy.js")>(),
+ getSystemPath: async () => [],
+ getEffectiveSystemPath: async () => [],
+ bucketByHierarchy: async () => [],
+}));
+
+import { looksFileLike, resetReadScope, resolveFileOrEntityFull } from "../resolve.js";
+import { registerHistoryCommand } from "../commands/history.js";
+import { registerDiffCommand } from "../commands/diff.js";
+
+function node(id: string, name: string, kind: string, sourceUri: string) {
+ return { id, name, kind, attrs: {}, provenance: { sourceUri } };
+}
+
+/** A client whose search answers from a fixed list by case-insensitive substring, like the backend. */
+function graph(nodes: ReturnType<typeof node>[]) {
+ const search = vi.fn(async (term: string, opts?: { kind?: string }) =>
+ nodes.filter((n) => n.name.toLowerCase().includes(term.toLowerCase()) && (!opts?.kind || n.kind === opts.kind)));
+ return { search, workspaceSystem: async () => ({ systemId: null }) } as never as Parameters<typeof resolveFileOrEntityFull>[0] & { search: typeof search };
+}
+
+/** A client whose file search returns these files whatever the term, as a fuzzy backend window might. */
+function fileWindow(files: ReturnType<typeof node>[]) {
+ const search = vi.fn(async (_term: string, opts?: { kind?: string }) => (opts?.kind === "file" ? files : []));
+ return { search, workspaceSystem: async () => ({ systemId: null }) } as never as Parameters<typeof resolveFileOrEntityFull>[0];
+}
-const commandContents: Record<string, string> = {};
-for (const cmd of COMMANDS_USING_FILE_RESOLUTION) {
- const cmdPath = path.resolve(__dirname, `../commands/${cmd}.ts`);
- commandContents[cmd] = fs.readFileSync(cmdPath, "utf-8");
+async function run(register: (program: Command) => void, args: string[]): Promise<{ stdout: string; command: Command }> {
+ const program = new Command().name("ix").exitOverride();
+ register(program);
+ const stdout: string[] = [];
+ const log = vi.spyOn(console, "log").mockImplementation((...parts) => { stdout.push(parts.join(" ")); });
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+ const write = vi.spyOn(process.stderr, "write").mockImplementation((() => true) as never);
+ try {
+ await program.parseAsync(args, { from: "user" });
+ } finally {
+ log.mockRestore();
+ error.mockRestore();
+ write.mockRestore();
+ }
+ return { stdout: stdout.join("\n"), command: program.commands[0] };
}
+const FILE_A = node("file-a-id", "a.ts", "file", "src/a.ts");
+
+let dir: string;
+let savedCwd: string;
+let savedExitCode: typeof process.exitCode;
+
+beforeEach(() => {
+ // A non-git directory of its own: nothing here touches the real checkout or
+ // ~/.ix, and git has no repository to answer from.
+ dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "ix-file-res-")));
+ process.env.IX_HOME = path.join(dir, ".ix");
+ savedCwd = process.cwd();
+ process.chdir(dir);
+ resetReadScope();
+ savedExitCode = process.exitCode;
+ process.exitCode = undefined;
+ for (const fn of Object.values(client)) fn.mockReset();
+ client.search.mockImplementation(async (term: string, opts?: { kind?: string }) =>
+ [FILE_A].filter((n) => n.name.toLowerCase().includes(term.toLowerCase()) && (!opts?.kind || n.kind === opts.kind)));
+ client.entity.mockImplementation(async (id: string) => ({ node: { ...FILE_A, id } }));
+ client.expand.mockResolvedValue({ nodes: [], edges: [] });
+ client.provenance.mockResolvedValue([]);
+ client.diff.mockResolvedValue({ fromRev: 3, toRev: 5, changes: [], total: 0 });
+ client.listPatches.mockResolvedValue([]);
+ client.resolvePrefix.mockRejectedValue(new Error("not a prefix"));
+});
+
+afterEach(() => {
+ process.exitCode = savedExitCode;
+ process.chdir(savedCwd);
+ delete process.env.IX_HOME;
+ resetReadScope();
+ fs.rmSync(dir, { recursive: true, force: true });
+ vi.restoreAllMocks();
+});
+
describe("file-first resolution helper", () => {
- it("resolve.ts exports looksFileLike", () => {
- expect(resolveContent).toContain("export function looksFileLike");
+ it("looksFileLike recognises paths and known extensions, not symbols", () => {
+ for (const target of ["src/a.ts", "a\\b", "parser.py", "index.tsx"]) {
+ expect(looksFileLike(target), target).toBe(true);
+ }
+ for (const target of ["Widget", "a.unknownext", "CompactionJob::Run"]) {
+ expect(looksFileLike(target), target).toBe(false);
+ }
});
- it("resolve.ts exports resolveFileOrEntity", () => {
- expect(resolveContent).toContain("export async function resolveFileOrEntity");
- });
+ it("resolveFileOrEntity tries file graph match before symbol resolution", async () => {
+ const nodes = [node("f-parser", "parser.py", "file", "src/parser.py"), node("fn-parser", "parser", "function", "src/parser.py")];
+
+ const asFile = graph(nodes);
+ const fileResult = await resolveFileOrEntityFull(asFile, "parser.py", { format: "json" });
+ expect(fileResult.resolved && fileResult.entity.id).toBe("f-parser");
+ expect(asFile.search.mock.calls[0][1]).toMatchObject({ kind: "file", nameOnly: true });
- it("resolveFileOrEntity tries file graph match before symbol resolution", () => {
- // The function should check looksFileLike first, then fall through to structured symbol resolution
- expect(resolveContent).toContain("looksFileLike(target)");
- expect(resolveContent).toContain("tryFileGraphMatch(client, target,");
- expect(resolveContent).toContain("resolveEntityFull(client, target,");
+ const asSymbol = graph(nodes);
+ const symbolResult = await resolveFileOrEntityFull(asSymbol, "parser", { format: "json" });
+ expect(symbolResult.resolved && symbolResult.entity.id).toBe("fn-parser");
});
- it("tryFileGraphMatch scores exact path matches higher than basename matches", () => {
- expect(resolveContent).toContain("quality: 0"); // exact path
- expect(resolveContent).toContain("quality: 1"); // exact filename
- expect(resolveContent).toContain("quality: 2"); // bare name
+ it("tryFileGraphMatch scores exact path matches higher than basename matches", async () => {
+ // Exact filename (quality 1) beats a bare-name match (quality 2), even at a longer uri.
+ const byFilename = await resolveFileOrEntityFull(fileWindow([
+ node("bare", "score.js", "file", "score.js"),
+ node("exact-name", "score.ts", "file", "src/deep/ranking/score.ts"),
+ ]), "score.ts", { format: "json" });
+ expect(byFilename.resolved && byFilename.entity.id).toBe("exact-name");
+
+ // Exact path (quality 0) beats an exact filename elsewhere, and says it was exact.
+ const byPath = await resolveFileOrEntityFull(fileWindow([
+ node("root-score", "score.ts", "file", "score.ts"),
+ node("path-score", "score.ts", "file", "src/ranking/score.ts"),
+ ]), "src/ranking/score.ts", { format: "json" });
+ expect(byPath.resolved && byPath.entity).toMatchObject({ id: "path-score", resolutionMode: "exact" });
+
+ // CL-19 touchpoint: two files of the same name at the same quality resolve
+ // to the shorter uri today. CL-19 fix 1 makes this case ambiguous on
+ // purpose; update this expectation with it rather than working around it.
+ const byLength = await resolveFileOrEntityFull(fileWindow([
+ node("deep-score", "score.ts", "file", "src/deep/score.ts"),
+ node("short-score", "score.ts", "file", "a/score.ts"),
+ ]), "score.ts", { format: "json" });
+ expect(byLength.resolved && byLength.entity).toMatchObject({ id: "short-score", resolutionMode: "scored" });
});
});
describe("history command uses file-first resolution", () => {
- it("imports resolveFileOrReport", () => {
- expect(historyContent).toContain("resolveFileOrReport");
- });
-
- it("accepts a target argument, not entityId", () => {
- expect(historyContent).toContain('command("history <target>")');
+ it("accepts a target argument, not entityId", async () => {
+ const program = new Command();
+ registerHistoryCommand(program);
+ const [target] = program.commands[0].registeredArguments;
+ expect(target.name()).toBe("target");
+ expect(target.required).toBe(true);
});
- it("supports --kind option", () => {
- expect(historyContent).toContain("--kind");
+ it("asks for the provenance of the resolved file", async () => {
+ const { stdout } = await run(registerHistoryCommand, ["history", "src/a.ts", "--format", "json"]);
+ expect(client.provenance).toHaveBeenCalledWith("file-a-id");
+ expect(JSON.parse(stdout).resolvedTarget.kind).toBe("file");
});
});
describe("diff command supports scoped target", () => {
it("accepts optional third positional argument", () => {
- expect(diffContent).toContain('command("diff <fromRev> <toRev> [target]")');
- });
-
- it("uses resolveFileOrReport for target resolution", () => {
- expect(diffContent).toContain("resolveFileOrReport");
+ const program = new Command();
+ registerDiffCommand(program);
+ const target = program.commands[0].registeredArguments[2];
+ expect(target.name()).toBe("target");
+ expect(target.required).toBe(false);
});
- it("passes resolved entity ID to diff API", () => {
- expect(diffContent).toContain("entityId");
+ it("passes resolved entity ID to diff API", async () => {
+ await run(registerDiffCommand, ["diff", "3", "5", "src/a.ts", "--format", "json"]);
+ expect(client.diff).toHaveBeenCalled();
+ expect(client.diff.mock.calls.every(([, , opts]) => opts.entityId === "file-a-id")).toBe(true);
});
- it("supports --content flag for detailed attribute diffs", () => {
- expect(diffContent).toContain('"--content"');
- expect(diffContent).toContain("formatDiffContent");
+ it("sends no entity ID without a target", async () => {
+ await run(registerDiffCommand, ["diff", "3", "5", "--format", "json"]);
+ expect(client.diff).toHaveBeenCalled();
+ expect(client.diff.mock.calls.every(([, , opts]) => opts.entityId === undefined)).toBe(true);
});
- it("--content reads source from disk using line spans", () => {
- expect(diffContent).toContain("readSourceSpan");
- expect(diffContent).toContain("line_start");
- expect(diffContent).toContain("line_end");
- expect(diffContent).toContain("fs.readFileSync");
- });
+ it("--content reads source from disk using line spans into sourceContent", async () => {
+ const file = path.join(dir, "f.ts");
+ fs.writeFileSync(file, "line one\nline two\nline three\n");
+ client.diff.mockResolvedValue({
+ fromRev: 3,
+ toRev: 5,
+ total: 1,
+ changes: [{
+ changeType: "added",
+ entityId: "fn-id",
+ atToRev: { name: "added", kind: "function", attrs: { line_start: 2, line_end: 3 }, provenance: { source_uri: file } },
+ }],
+ });
+ // The from side has a timestamp, and git has no repository here to read it
+ // from, so the textual diff gives up and the graph-driven fallback answers.
+ client.listPatches.mockResolvedValue([{ rev: 3, timestamp: "2026-01-01T00:00:00Z" }]);
- it("--content augments JSON output with sourceContent", () => {
- expect(diffContent).toContain("sourceContent");
+ const { stdout } = await run(registerDiffCommand, ["diff", "3", "5", "--content", "--format", "json"]);
+ expect(JSON.parse(stdout).changes[0].sourceContent).toBe("line two\nline three");
});
});
-describe("all graph commands use resolveFileOrEntity consistently", () => {
- for (const cmd of COMMANDS_USING_FILE_RESOLUTION) {
- it(`${cmd} uses file-first resolution`, () => {
- const helper = cmd === "locate" ? "resolveFileOrEntity" : "resolveFileOrReport";
- expect(commandContents[cmd]).toContain(helper);
- });
- }
-});
+type LoadRegister = () => Promise<(program: Command) => void>;
-describe("--pick support", () => {
- it("resolve.ts exports applyPick", () => {
- expect(resolveContent).toContain("export function applyPick");
- });
+/** Graph commands that take a file or entity target. */
+const COMMANDS_USING_FILE_RESOLUTION: ReadonlyArray<readonly [string, LoadRegister]> = [
+ ["overview", async () => (await import("../commands/overview.js")).registerOverviewCommand],
+ ["callers", async () => (await import("../commands/callers.js")).registerCallersCommand],
+ ["contains", async () => (await import("../commands/contains.js")).registerContainsCommand],
+ ["imports", async () => (await import("../commands/imports.js")).registerImportsCommand],
+ ["depends", async () => (await import("../commands/depends.js")).registerDependsCommand],
+ ["locate", async () => (await import("../commands/locate.js")).registerLocateCommand],
+ ["impact", async () => (await import("../commands/impact.js")).registerImpactCommand],
+ ["explain", async () => (await import("../commands/explain.js")).registerExplainCommand],
+];
- it("resolve.ts delegates ambiguity output to the shared reporter", () => {
- expect(resolveContent).toContain("reportAmbiguousTarget(symbol, result, \"text\", opts)");
- });
+/** Every entity id a command asked the backend about, after resolution. */
+function requestedIds(): string[] {
+ return [
+ ...client.entity.mock.calls.map(([id]) => id),
+ ...client.expand.mock.calls.map(([id]) => id),
+ ].filter((id): id is string => typeof id === "string");
+}
- it("overview.ts declares --path option", () => {
- expect(commandContents["overview"]).toContain('"--path');
+describe("all graph commands use resolveFileOrEntity consistently", () => {
+ it.each(COMMANDS_USING_FILE_RESOLUTION)("%s resolves a file path to the file entity", async (command, loadRegister) => {
+ await run(await loadRegister(), [command, "src/a.ts", "--format", "json"]);
+ expect(requestedIds()).toContain("file-a-id");
});
+});
- it("overview.ts declares --pick option", () => {
- expect(commandContents["overview"]).toContain('"--pick');
+describe("--pick support", () => {
+ // --pick through each command is pick-option-validation.test.ts and
+ // resolver-consistency.test.ts; applyPick on its own is pick-resolution.test.ts.
+ it("--pick selects among ambiguous candidates by 1-based rank", async () => {
+ const result = await resolveFileOrEntityFull(graph([
+ node("first-id", "Duplicate", "function", "src/first.ts"),
+ node("second-id", "Duplicate", "function", "src/second.ts"),
+ ]), "Duplicate", { format: "json", pick: 2 });
+ expect(result.resolved && result.entity.id).toBe("second-id");
});
-
- const PICK_COMMANDS = ["overview", "callers", "contains", "imports", "depends", "locate", "impact", "explain"];
- for (const cmd of PICK_COMMANDS) {
- it(`${cmd} declares --pick option`, () => {
- expect(commandContents[cmd]).toContain("--pick");
- });
- }
});
describe("ambiguous result structure", () => {
- it("resolve.ts AmbiguousResult includes rank field", () => {
- expect(resolveContent).toContain("rank?:");
- });
-
- it("resolve.ts AmbiguousResult includes diagnostics field", () => {
- expect(resolveContent).toContain("diagnostics?:");
- });
-
- it("buildAmbiguous sets rank on candidates", () => {
- expect(resolveContent).toContain("rank,");
- });
-
- it("buildAmbiguous sets diagnostics with ambiguous_resolution code", () => {
- expect(resolveContent).toContain("ambiguous_resolution");
+ it("ranks candidates 1..n and carries the ambiguous_resolution diagnostic", async () => {
+ const result = await resolveFileOrEntityFull(graph([
+ node("first-id", "Duplicate", "function", "src/first.ts"),
+ node("second-id", "Duplicate", "function", "src/second.ts"),
+ ]), "Duplicate", { format: "json" });
+ expect(result.resolved).toBe(false);
+ if (result.resolved || !result.ambiguous) throw new Error("expected an ambiguous result");
+ expect(result.result.candidates.map((c) => c.rank)).toEqual([1, 2]);
+ expect(result.result.diagnostics?.[0].code).toBe("ambiguous_resolution");
});
});
diff --git a/ix-cli/src/cli/__tests__/resolver-consistency.test.ts b/ix-cli/src/cli/__tests__/resolver-consistency.test.ts
index be564173..14f0edd6 100644
--- a/ix-cli/src/cli/__tests__/resolver-consistency.test.ts
+++ b/ix-cli/src/cli/__tests__/resolver-consistency.test.ts
@@ -1,40 +1,179 @@
// Copyright 2026 Ix Infrastructure Inc.
-import { describe, it, expect } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Command, CommanderError } from "commander";
import * as fs from "node:fs";
+import * as os from "node:os";
import * as path from "node:path";
+import { resetReadScope } from "../resolve.js";
/**
- * Verify that all content-producing resolver commands support
- * --pick, --kind, and --path for consistent ambiguity resolution.
+ * Every content-producing resolver command honours --pick, --kind and --path
+ * the same way: given two candidates of one name, each flag makes the command
+ * ask the backend about the selected candidate and never about the other one.
*/
-const CONTENT_COMMANDS = ["read", "overview", "locate", "diff", "history"];
+// Graph reads refuse a directory no workspace covers (workspace_not_mapped),
+// and this suite runs from a tmp directory 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 commandFiles = CONTENT_COMMANDS.map(cmd => {
- const tsPath = path.resolve(__dirname, `../commands/${cmd}.ts`);
- return { cmd, tsPath, content: fs.readFileSync(tsPath, "utf-8") };
+const client = vi.hoisted(() => ({
+ search: vi.fn(),
+ entity: vi.fn(),
+ expand: vi.fn(),
+ provenance: vi.fn(),
+ diff: vi.fn(),
+ listPatches: vi.fn(),
+ resolvePrefix: vi.fn(),
+}));
+
+vi.mock("../../client/api.js", () => ({
+ IxClient: class {
+ async workspaceSystem() { return { systemId: null }; }
+ async search(...args: unknown[]) { return client.search(...args); }
+ async entity(...args: unknown[]) { return client.entity(...args); }
+ async expand(...args: unknown[]) { return client.expand(...args); }
+ async provenance(...args: unknown[]) { return client.provenance(...args); }
+ async diff(...args: unknown[]) { return client.diff(...args); }
+ async listPatches(...args: unknown[]) { return client.listPatches(...args); }
+ async resolvePrefix(...args: unknown[]) { return client.resolvePrefix(...args); }
+ },
+}));
+
+vi.mock("../config.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../config.js")>(),
+ readStitchScope: () => undefined,
+ writeStitchScope: vi.fn(),
+}));
+
+vi.mock("../hierarchy.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../hierarchy.js")>(),
+ getSystemPath: async () => [],
+ getEffectiveSystemPath: async () => [],
+ bucketByHierarchy: async () => [],
+}));
+
+type Register = (program: Command) => void;
+type LoadRegister = () => Promise<Register>;
+
+/** The command, the arguments before the target, and where it registers. */
+const COMMANDS: ReadonlyArray<readonly [string, readonly string[], LoadRegister]> = [
+ ["read", ["read"], async () => (await import("../commands/read.js")).registerReadCommand],
+ ["overview", ["overview"], async () => (await import("../commands/overview.js")).registerOverviewCommand],
+ ["locate", ["locate"], async () => (await import("../commands/locate.js")).registerLocateCommand],
+ ["history", ["history"], async () => (await import("../commands/history.js")).registerHistoryCommand],
+ ["diff", ["diff", "3", "5"], async () => (await import("../commands/diff.js")).registerDiffCommand],
+ ["depends", ["depends"], async () => (await import("../commands/depends.js")).registerDependsCommand],
+ ["callers", ["callers"], async () => (await import("../commands/callers.js")).registerCallersCommand],
+ ["contains", ["contains"], async () => (await import("../commands/contains.js")).registerContainsCommand],
+ ["imports", ["imports"], async () => (await import("../commands/imports.js")).registerImportsCommand],
+ ["impact", ["impact"], async () => (await import("../commands/impact.js")).registerImpactCommand],
+ ["explain", ["explain"], async () => (await import("../commands/explain.js")).registerExplainCommand],
+];
+
+function node(id: string, kind: string, sourceUri: string) {
+ return { id, kind, name: "Duplicate", attrs: {}, provenance: { sourceUri } };
+}
+
+/** Two same-named functions: only --pick or --path can choose between them. */
+const SAME_KIND = [node("first-id", "function", "src/first.ts"), node("second-id", "function", "src/second.ts")];
+/** A class and a function: unfiltered, the class wins; --kind function must reach the function. */
+const MIXED_KIND = [node("first-id", "class", "src/first.ts"), node("second-id", "function", "src/second.ts")];
+
+/** Search answers like the backend: by name substring, narrowed by kind when one is asked for. */
+function serve(nodes: ReturnType<typeof node>[]) {
+ client.search.mockImplementation(async (term: string, opts?: { kind?: string }) =>
+ nodes.filter((n) => n.name.toLowerCase().includes(term.toLowerCase()) && (!opts?.kind || n.kind === opts.kind)));
+ client.entity.mockImplementation(async (id: string) => {
+ const n = nodes.find((x) => x.id === id);
+ return { node: { id, kind: n?.kind ?? "function", name: "Duplicate", provenance: { sourceUri: n?.provenance.sourceUri } } };
+ });
+}
+
+/** Every entity id the command asked the backend about, after resolution. */
+function requestedIds(): string[] {
+ return [
+ ...client.entity.mock.calls.map(([id]) => id),
+ ...client.expand.mock.calls.map(([id]) => id),
+ ...client.provenance.mock.calls.map(([id]) => id),
+ ...client.diff.mock.calls.map(([, , opts]) => opts?.entityId),
+ ].filter((id): id is string => typeof id === "string");
+}
+
+async function run(register: Register, args: string[]): Promise<void> {
+ const program = new Command().name("ix").exitOverride();
+ register(program);
+ const log = vi.spyOn(console, "log").mockImplementation(() => {});
+ const error = vi.spyOn(console, "error").mockImplementation(() => {});
+ const write = vi.spyOn(process.stderr, "write").mockImplementation((() => true) as never);
+ try {
+ await program.parseAsync([...args, "--format", "json"], { from: "user" });
+ } catch (err) {
+ // What a command does after resolving (read finding no source file, for
+ // one) is not this suite's question; which id it asked for is.
+ if (!(err instanceof CommanderError)) throw err;
+ } finally {
+ log.mockRestore();
+ error.mockRestore();
+ write.mockRestore();
+ }
+}
+
+let dir: string;
+let savedCwd: string;
+let savedExitCode: typeof process.exitCode;
+
+beforeEach(() => {
+ // read looks on disk after resolving; keep it off the real checkout and ~/.ix.
+ dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "ix-resolver-")));
+ process.env.IX_HOME = path.join(dir, ".ix");
+ savedCwd = process.cwd();
+ process.chdir(dir);
+ resetReadScope();
+ savedExitCode = process.exitCode;
+ process.exitCode = undefined;
+ for (const fn of Object.values(client)) fn.mockReset();
+ client.expand.mockResolvedValue({ nodes: [], edges: [] });
+ client.provenance.mockResolvedValue([]);
+ client.diff.mockResolvedValue({ fromRev: 3, toRev: 5, changes: [], total: 0 });
+ client.listPatches.mockResolvedValue([]);
+ client.resolvePrefix.mockRejectedValue(new Error("not a prefix"));
+});
+
+afterEach(() => {
+ process.exitCode = savedExitCode;
+ process.chdir(savedCwd);
+ delete process.env.IX_HOME;
+ resetReadScope();
+ fs.rmSync(dir, { recursive: true, force: true });
+ vi.restoreAllMocks();
});
describe("resolver flag consistency across content commands", () => {
- for (const { cmd, content } of commandFiles) {
- describe(cmd, () => {
- it("supports --pick", () => {
- expect(content).toContain('"--pick <n>"');
- });
-
- it("supports --kind", () => {
- expect(content).toContain('"--kind <kind>"');
- });
-
- it("supports --path", () => {
- expect(content).toContain('"--path <path>"');
- });
-
- it("passes pick as number to resolver", () => {
- expect(content).toContain("parsePickOption");
- expect(content).toContain("pick: opts.pick");
- });
+ describe.each(COMMANDS)("%s", (_command, prefix, loadRegister) => {
+ it("--pick 2 selects the second candidate", async () => {
+ serve(SAME_KIND);
+ await run(await loadRegister(), [...prefix, "Duplicate", "--pick", "2"]);
+ expect(requestedIds()).toContain("second-id");
+ expect(requestedIds()).not.toContain("first-id");
});
- }
+
+ it("--path selects the candidate under that path", async () => {
+ serve(SAME_KIND);
+ await run(await loadRegister(), [...prefix, "Duplicate", "--path", "second.ts"]);
+ expect(requestedIds()).toContain("second-id");
+ expect(requestedIds()).not.toContain("first-id");
+ });
+
+ it("--kind selects the candidate of that kind", async () => {
+ serve(MIXED_KIND);
+ await run(await loadRegister(), [...prefix, "Duplicate", "--kind", "function"]);
+ expect(requestedIds()).toContain("second-id");
+ expect(requestedIds()).not.toContain("first-id");
+ });
+ });
});