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
feat(cli): spread ambiguous candidates across files, name containers (#890)
Ian Hockaefa02fee362
diff --git a/docs/llm-format.md b/docs/llm-format.mdindex 448da1da..1b623ac1 100644--- a/docs/llm-format.md+++ b/docs/llm-format.md@@ -117,8 +117,16 @@ which value it ignored, on stderr, when a person is there to read it.not choose a target. The error also carries `shown=<n> total=<m>` after`count=` (and `truncated=true` when the search window came back full, so`total` is a lower bound); json has `total` and `truncated` beside- `candidates`. Candidates are numbered in (path, line, id) order, so- `--pick <n>` means the same thing on every run. (The+ `candidates`. Candidates are ranked by how well they match (ties in+ (path, line, id) order), then each run of equal scores is dealt+ round-robin by file: the best of each file, then each file's second-best,+ and so on, so a file that defines the name many times does not fill the 8+ shown on its own. A worse score never goes ahead of a better one, so an+ import of the name still comes after every definition. That order is the+ numbering, so `--pick <n>` and `--all`'s `candidate=<n>` mean the same thing+ on every run. A candidate inside a class or other type carries+ `container=<name>` (json `container`), last on its record; it is absent for+ a top-level definition, or when the graph could not say. (Thebackend spells a missing target `unknown_target` in its own JSON bodies; thatis a wire detail and is translated on the way out, so a consumer never seesboth.)diff --git a/ix-cli/src/cli/__tests__/agent-outcomes.test.ts b/ix-cli/src/cli/__tests__/agent-outcomes.test.tsindex 41ecf650..accbef51 100644--- a/ix-cli/src/cli/__tests__/agent-outcomes.test.ts+++ b/ix-cli/src/cli/__tests__/agent-outcomes.test.ts@@ -372,22 +372,26 @@ describe("--all on an ambiguous target", () => {];it("skips an import of the name when definitions are listed, keeping --pick numbers", async () => {- graph({ clamp: [CLAMP_IMPORT, ...CLAMP_DEFS] });+ // A second definition in app/utils.py. The import scores worse than every+ // definition, so it ranks last (the file round-robin deals only among+ // equal scores) and the definitions keep their shown numbers under --all.+ const pyAgain = { ...CLAMP_DEFS[0], id: "py2-id", attrs: { line_start: 40, line_end: 41 } };+ graph({ clamp: [CLAMP_IMPORT, ...CLAMP_DEFS, pyAgain] });const plain = JSON.parse((await run(["callers", "clamp", "--format", "json"])).stdout);expect(plain.candidates.map((c: { id: string; rank: number }) => [c.rank, c.id]))- .toEqual([[1, "import-id"], [2, "py-id"], [3, "ts-id"]]);+ .toEqual([[1, "py-id"], [2, "ts-id"], [3, "py2-id"], [4, "import-id"]]);expand.mockClear();const body = JSON.parse((await run(["callers", "clamp", "--all", "--format", "json"])).stdout);- expect(body.candidates.map((c: { n: number; path: string }) => [c.n, c.path]))- .toEqual([[2, "app/utils.py"], [3, "web/src/math.ts"]]);- expect(new Set(body.results.map((r: { candidate: number }) => r.candidate))).toEqual(new Set([2, 3]));- expect(expand.mock.calls.map(([id]) => id).sort()).toEqual(["py-id", "ts-id"]);+ expect(body.candidates.map((c: { n: number; id: string }) => [c.n, c.id]))+ .toEqual([[1, "py-id"], [2, "ts-id"], [3, "py2-id"]]);+ expect(new Set(body.results.map((r: { candidate: number }) => r.candidate))).toEqual(new Set([1, 2, 3]));+ expect(expand.mock.calls.map(([id]) => id).sort()).toEqual(["py-id", "py2-id", "ts-id"]);// The skipped import is not a candidate the search cut off.expect((body.diagnostics ?? []).map((d: { code: string }) => d.code)).not.toContain("candidates_truncated");const impact = JSON.parse((await run(["impact", "clamp", "--all", "--format", "json"])).stdout);- expect(impact.results.map((r: { candidate: number }) => r.candidate)).toEqual([2, 3]);+ expect(impact.results.map((r: { candidate: number }) => r.candidate)).toEqual([1, 2, 3]);});it("still answers for imports when no definition is listed", async () => {diff --git a/ix-cli/src/cli/__tests__/candidate-spread.test.ts b/ix-cli/src/cli/__tests__/candidate-spread.test.tsnew file mode 100644index 00000000..9d8a2fb3--- /dev/null+++ b/ix-cli/src/cli/__tests__/candidate-spread.test.ts@@ -0,0 +1,289 @@+// Copyright 2026 Ix Infrastructure Inc.++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { Command } from "commander";+import { registerCallersCommand } from "../commands/callers.js";+import { registerLocateCommand } from "../commands/locate.js";+import { CONTAINER_LOOKUP_TIMEOUT_MS, resolveFileOrEntityFull, roundRobinByFile } from "../resolve.js";++// An ambiguous name lists 8 candidates. A file that defines the name many times+// must not fill that page on its own: the page is dealt round-robin by file+// (best of each file, then second-best, ...), and that order is the one+// `--pick` and `--all` number by. Each row names the type that contains it.++vi.mock("../bootstrap.js", async (orig) => ({+ ...(await orig<typeof import("../bootstrap.js")>()),+ resolveWorkspaceId: () => "ws-test",+}));++const { search, expand, expandByName } = vi.hoisted(() => ({+ search: vi.fn(), expand: vi.fn(), expandByName: 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); }+ async expandByName(...args: unknown[]) { return expandByName(...args); }+ async resolvePrefix(p: string) { return p; }+ async entity(id: string) {+ return { node: { id, kind: "method", name: "crop", attrs: { line_start: 1, line_end: 2 }, provenance: { sourceUri: `src/${id}.py` } } };+ }+ },+}));++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 () => [],+}));++vi.mock("../miss-reason.js", () => ({+ missProbeWouldRun: () => false,+ explainSymbolMiss: async () => null,+}));++const CACHE = "src/transformers/cache_utils.py";+const MODEL = "src/transformers/a_model.py";+const GEN = "src/transformers/generation/utils.py";+const IMAGE = "src/transformers/image_utils.py";++const method = (id: string, path: string, line: number) => ({+ id, kind: "method", name: "crop", attrs: { line_start: line, line_end: line + 5 }, provenance: { sourceUri: path },+});++/** 12 `crop` methods: 8 in one file, 4 spread over three others. */+const CROPS = [+ ...Array.from({ length: 8 }, (_, i) => method(`cache-${i + 1}`, CACHE, (i + 1) * 100)),+ method("model-1", MODEL, 5),+ method("gen-1", GEN, 10),+ method("gen-2", GEN, 20),+ method("image-1", IMAGE, 1),+];++/** The page as a reader sees it: files in path order, each file's next best per round. */+const ROUND_ROBIN = ["model-1", "cache-1", "gen-1", "image-1", "cache-2", "gen-2", "cache-3", "cache-4"];+const REST = ["cache-5", "cache-6", "cache-7", "cache-8"];++/** The classes holding each crop: CONTAINS edges into it, as /v1/expand-by-name returns them. */+const OWNERS: Record<string, { id: string; kind: string; name: string }> = {+ "cache-1": { id: "cls-dynamic", kind: "class", name: "DynamicLayer" },+ "cache-2": { id: "cls-static", kind: "class", name: "StaticLayer" },+ "gen-1": { id: "cls-gen", kind: "class", name: "GenerationMixin" },+ // A top-level function: its only parent is the file, which is no container.+ "image-1": { id: "file-image", kind: "file", name: "image_utils.py" },+};++function containsGraph() {+ const nodes = Object.values(OWNERS).map((o) => ({ ...o, attrs: {}, provenance: { sourceUri: "x" } }));+ const edges = Object.entries(OWNERS).map(([dst, o]) => ({ id: `e-${dst}`, src: o.id, dst, predicate: "CONTAINS", attrs: {} }));+ return { nodes, edges };+}++async function run(args: string[]): Promise<{ stdout: string; stderr: string; exitCode: number }> {+ const program = new Command().name("ix").exitOverride();+ registerCallersCommand(program);+ registerLocateCommand(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).replace(/\n$/, ""));+ return true;+ }) as never);+ process.exitCode = undefined;+ try {+ await program.parseAsync(args, { from: "user" });+ } finally {+ log.mockRestore();+ error.mockRestore();+ write.mockRestore();+ }+ return { stdout: stdout.join("\n"), stderr: stderr.join("\n"), exitCode: Number(process.exitCode ?? 0) };+}++let savedExitCode: typeof process.exitCode;+beforeEach(() => {+ savedExitCode = process.exitCode;+ search.mockReset().mockImplementation(async (term: string) => (term === "crop" ? CROPS : []));+ expand.mockReset().mockImplementation(async () => ({ nodes: [], edges: [] }));+ expandByName.mockReset().mockImplementation(async () => containsGraph());+});+afterEach(() => {+ process.exitCode = savedExitCode;+});++describe("roundRobinByFile", () => {+ it("deals the best of each file first, then the second-best, keeping each file's order", () => {+ const n = (id: string, path: string) => ({ id, provenance: { sourceUri: path } });+ const ranked = [n("a1", "a.py"), n("a2", "a.py"), n("a3", "a.py"), n("b1", "b.py"), n("c1", "c.py"), n("b2", "b.py")];+ expect(roundRobinByFile(ranked).map((x) => x.id)).toEqual(["a1", "b1", "c1", "a2", "b2", "a3"]);+ });++ it("groups Windows and posix spellings of one file together", () => {+ const n = (id: string, path: string) => ({ id, provenance: { sourceUri: path } });+ const ranked = [n("w1", "C:\\repo\\src\\a.py"), n("w2", "C:/repo/src/a.py"), n("b1", "C:\\repo\\src\\b.py")];+ expect(roundRobinByFile(ranked).map((x) => x.id)).toEqual(["w1", "b1", "w2"]);+ });++ it("keeps every candidate, once", () => {+ const n = (id: string, path: string) => ({ id, provenance: { sourceUri: path } });+ const ranked = [n("x", "a.py"), n("y", "a.py"), n("z", "b.py")];+ expect(roundRobinByFile(ranked).map((x) => x.id).sort()).toEqual(["x", "y", "z"]);+ });+});++describe("ambiguous candidates spread across files", () => {+ it("the first page covers min(8, files) files, in round-robin order (json)", async () => {+ const result = await run(["locate", "crop", "--format", "json"]);+ expect(result.exitCode).toBe(2);+ const body = JSON.parse(result.stdout);+ expect(body.total).toBe(12);+ expect(body.candidates.map((c: { id: string }) => c.id)).toEqual(ROUND_ROBIN);+ expect(body.candidates.map((c: { rank: number }) => c.rank)).toEqual([1, 2, 3, 4, 5, 6, 7, 8]);+ expect(new Set(body.candidates.map((c: { path: string }) => c.path)).size).toBe(4);+ });++ it("shows every candidate when there are 8 or fewer", async () => {+ search.mockImplementation(async (term: string) => (term === "crop" ? CROPS.slice(5, 11) : []));+ const body = JSON.parse((await run(["locate", "crop", "--format", "json"])).stdout);+ // cache-6..8, model-1, gen-1, gen-2+ expect(body.candidates.map((c: { id: string }) => c.id)).toEqual(["model-1", "cache-6", "gen-1", "cache-7", "gen-2", "cache-8"]);+ expect(body.total).toBe(6);+ });++ it("--pick n resolves to the candidate shown as n, past the first page too", async () => {+ const shown = JSON.parse((await run(["locate", "crop", "--format", "json"])).stdout).candidates;+ for (const c of shown) {+ const picked = JSON.parse((await run(["locate", "crop", "--pick", String(c.rank), "--format", "json"])).stdout);+ expect(picked.resolvedTarget.id).toBe(c.id);+ }+ const ninth = JSON.parse((await run(["locate", "crop", "--pick", "9", "--format", "json"])).stdout);+ expect(ninth.resolvedTarget.id).toBe(REST[0]);+ });++ it("--all numbers its candidate=<n> rows by the same order", async () => {+ expand.mockImplementation(async (id: string) => ({+ nodes: [{ id: `caller-of-${id}`, kind: "function", name: `callerOf_${id}`, provenance: { sourceUri: "src/use.py" } }],+ edges: [],+ }));+ const body = JSON.parse((await run(["callers", "crop", "--all", "--limit", "100", "--format", "json"])).stdout);+ expect(body.candidates.map((c: { n: number; id: string }) => `${c.n}:${c.id}`))+ .toEqual([...ROUND_ROBIN, ...REST].map((id, i) => `${i + 1}:${id}`));+ for (const row of body.results) {+ expect(row.name).toBe(`callerOf_${[...ROUND_ROBIN, ...REST][row.candidate - 1]}`);+ }+ // --all lists no containers, so it asks for none.+ expect(expandByName).not.toHaveBeenCalled();+ });++ it("deals only among equal scores: an import never goes ahead of a definition", async () => {+ // Two definitions in one file and an import of the name in each of nine+ // other files. The imports score worse (+5) but inside the window; dealt+ // across the whole list they would push the second definition off the page.+ const def = (id: string, line: number) => ({+ id, kind: "function", name: "clamp", attrs: { line_start: line, line_end: line + 3 }, provenance: { sourceUri: "app/utils.py" },+ });+ const imports = Array.from({ length: 9 }, (_, i) => ({+ id: `import-${i}`, kind: "module", name: "clamp", attrs: { line_start: 1, line_end: 1 }, provenance: { sourceUri: `app/use${i}.py` },+ }));+ search.mockImplementation(async (term: string) => (term === "clamp" ? [...imports, def("def-1", 10), def("def-2", 40)] : []));+ const body = JSON.parse((await run(["locate", "clamp", "--format", "json"])).stdout);+ expect(body.total).toBe(11);+ expect(body.candidates.map((c: { id: string }) => c.id))+ .toEqual(["def-1", "def-2", ...imports.slice(0, 6).map((i) => i.id)]);+ });+});++describe("candidate rows name their container", () => {+ it("json: an additive `container` key, only where there is one", async () => {+ const body = JSON.parse((await run(["locate", "crop", "--format", "json"])).stdout);+ const byId = Object.fromEntries(body.candidates.map((c: { id: string }) => [c.id, c]));+ expect(byId["cache-1"].container).toBe("DynamicLayer");+ expect(byId["cache-2"].container).toBe("StaticLayer");+ expect(byId["gen-1"].container).toBe("GenerationMixin");+ // The file is not a container; no CONTAINS parent at all is none either.+ expect(byId["image-1"]).not.toHaveProperty("container");+ expect(byId["model-1"]).not.toHaveProperty("container");+ // The existing keys, unchanged.+ expect(Object.keys(byId["model-1"])).toEqual(["id", "name", "kind", "path", "line", "score", "rank"]);+ expect(Object.keys(byId["cache-1"])).toEqual(["id", "name", "kind", "path", "line", "score", "rank", "container"]);+ // One request for the name, not one per candidate.+ expect(expandByName).toHaveBeenCalledTimes(1);+ expect(expandByName).toHaveBeenCalledWith("crop", { direction: "in", predicates: ["CONTAINS"], timeoutMs: CONTAINER_LOOKUP_TIMEOUT_MS });+ });++ it("llm: `container=` ends the candidate record", async () => {+ const lines = (await run(["locate", "crop", "--format", "llm"])).stdout.split("\n");+ const candidates = lines.filter((l) => l.startsWith("candidate "));+ expect(candidates[1]).toMatch(/^candidate n=2 name=crop kind=method path=src\/transformers\/cache_utils\.py id=cache-1 container=DynamicLayer$/);+ expect(candidates[0]).toMatch(/^candidate n=1 name=crop kind=method path=src\/transformers\/a_model\.py id=model-1$/);+ });++ it("text: the container beside the name, and the line", async () => {+ const result = await run(["locate", "crop"]);+ expect(result.stderr).toMatch(/2\. method\s+cache-1\s+crop {2}DynamicLayer in src\/transformers\/cache_utils\.py:100/);+ expect(result.stderr).toMatch(/1\. method\s+model-1\s+crop in src\/transformers\/a_model\.py:5/);+ });++ it("a backend that cannot answer leaves the containers out and the ambiguity as it was", async () => {+ expandByName.mockRejectedValue(new Error("500: boom"));+ const result = await run(["locate", "crop", "--format", "json"]);+ expect(result.exitCode).toBe(2);+ const body = JSON.parse(result.stdout);+ expect(body.candidates.map((c: { id: string }) => c.id)).toEqual(ROUND_ROBIN);+ expect(body.candidates.some((c: object) => "container" in c)).toBe(false);+ });++ it("locate asks once for a dotted name it re-reads as Class.method", async () => {+ // `Config.load` matches only fuzzily, in two files (ambiguous), and no+ // class Config exists: locate tries the qualified reading, keeps the+ // literal ambiguity, and asks for containers on that result only.+ const entry = (id: string, path: string) => ({+ id, kind: "config_entry", name: "Config.loadAll", attrs: { line_start: 3, line_end: 3 }, provenance: { sourceUri: path },+ });+ search.mockImplementation(async () => [entry("e1", "conf/a.toml"), entry("e2", "conf/b.toml")]);+ const result = await run(["locate", "Config.load", "--format", "json"]);+ expect(result.exitCode).toBe(2);+ expect(JSON.parse(result.stdout).candidates.map((c: { id: string }) => c.id).sort()).toEqual(["e1", "e2"]);+ expect(expandByName).toHaveBeenCalledTimes(1);+ });++ it("--pick resolves without asking for containers", async () => {+ await run(["locate", "crop", "--pick", "2", "--format", "json"]);+ expect(expandByName).not.toHaveBeenCalled();+ });+});++describe("a file name shared by several files", () => {+ // Every candidate is its own file, so the order is the match ranking (the+ // shortest path first): the file the notice says it used is number 1.+ const files = ["a/very/deep/dir/index.ts", "b/index.ts", "c/src/index.ts"].map((p) => ({+ id: p, name: "index.ts", kind: "file", attrs: {}, provenance: { sourceUri: p },+ }));+ const fileClient = () => ({+ search: vi.fn(async (term: string) => files.filter((f) => f.name.includes(term.split("/").pop()!))),+ workspaceSystem: vi.fn(async () => null),+ expandByName,+ }) as any;++ it("numbers the tie in rank order, chosen first, and --pick follows it", async () => {+ const r = await resolveFileOrEntityFull(fileClient(), "index.ts", { format: "json" } as any);+ expect(r.resolved && r.entity.path).toBe("b/index.ts");+ const notice = r.resolved ? r.notices?.find((n) => n.code === "ambiguous_target") : undefined;+ expect(notice?.candidates.map((c) => c.path)).toEqual(["b/index.ts", "c/src/index.ts", "a/very/deep/dir/index.ts"]);+ const picked = await resolveFileOrEntityFull(fileClient(), "index.ts", { format: "json", pick: 3 } as any);+ expect(picked.resolved && picked.entity.path).toBe("a/very/deep/dir/index.ts");+ // A tie that resolves asks for no containers.+ expect(expandByName).not.toHaveBeenCalled();+ });+});diff --git a/ix-cli/src/cli/__tests__/target-resolution.test.ts b/ix-cli/src/cli/__tests__/target-resolution.test.tsindex 85784219..aa96fc51 100644--- a/ix-cli/src/cli/__tests__/target-resolution.test.ts+++ b/ix-cli/src/cli/__tests__/target-resolution.test.ts@@ -77,7 +77,7 @@ const PACKAGES = [];describe("acceptance 1: a bare basename shared by three files", () => {- it("resolves to the same file in both orders, scored, with a path-sorted notice", async () => {+ it("resolves to the same file in both orders, scored, with a notice in rank order", async () => {const [a, b] = await inBothOrders(PACKAGES, (c) => full(c, "index.ts"));for (const r of [a, b]) {expect(r.resolved).toBe(true);diff --git a/ix-cli/src/cli/commands/locate.ts b/ix-cli/src/cli/commands/locate.tsindex 815a8dbe..f4572218 100644--- a/ix-cli/src/cli/commands/locate.ts+++ b/ix-cli/src/cli/commands/locate.ts@@ -5,7 +5,7 @@ import chalk from "chalk";import { IxClient } from "../../client/api.js";import { createClient } from "../../client/factory.js";import {- resolveFileOrEntityFull, resolveEntityFull, printResolved, printAmbiguous,+ resolveFileOrEntityFull, rankEntity, withContainers, printResolved, printAmbiguous,looksFileLike, isRawId, qualifiedSeparator, isFuzzyResult, withMissReason,type ResolvedEntity, type ResolveResult, type Suggestion,} from "../resolve.js";@@ -245,14 +245,17 @@ async function resolveWithAmbiguity(// Symbol resolution — use full result to detect ambiguityconst allKinds = ["file", "class", "object", "trait", "interface", "module", "function", "method", "constant"];const sep = qualifiedSeparator(symbol);- result = await resolveEntityFull(client, symbol, allKinds, { ...opts, format, ...(sep ? { silentMiss: true } : {}) });+ result = await rankEntity(client, symbol, allKinds, { ...opts, format, ...(sep ? { silentMiss: true } : {}) });// `Class::method`, `Class.method` and `Class#method` are read as a qualified// name only when the name as typed matches nothing, or (for `.`/`#`) matches// only fuzzily; resolveFileOrEntityFull then keeps the literal result unless- // the qualified one keeps the exit code.+ // the qualified one keeps the exit code. Containers are asked for only on+ // the result kept, so a re-resolved name does not pay for them twice.const missed = !result.resolved && !result.ambiguous;if (sep && (missed || (sep !== "::" && isFuzzyResult(result)))) {result = await resolveFileOrEntityFull(client, symbol, { ...opts, format });+ } else {+ result = await withContainers(client, result);}}diff --git a/ix-cli/src/cli/commands/read.ts b/ix-cli/src/cli/commands/read.tsindex 3517aa31..1857c2f0 100644--- a/ix-cli/src/cli/commands/read.ts+++ b/ix-cli/src/cli/commands/read.ts@@ -53,7 +53,7 @@ export interface ReadResult {interface AmbiguityResult {targetType: "ambiguous-file" | "ambiguous-symbol";- candidates: Array<{ name: string; kind?: string; path?: string; id?: string; rank?: number }>;+ candidates: Array<{ name: string; kind?: string; path?: string; id?: string; rank?: number; container?: string }>;diagnostics?: Array<{ code: string; message: string }>;}@@ -330,6 +330,7 @@ export function renderReadAmbiguityLlm(result: AmbiguityResult, target: string):["kind", c.kind],["path", c.path ? relativePath(c.path) ?? c.path : undefined],["id", llmShortId(c.id)],+ ["container", c.container],]));});lines.push(llmLine("hint", [[@@ -391,7 +392,8 @@ function outputAmbiguity(result: AmbiguityResult, target: string, format: stringconst kindStr = c.kind ? chalk.cyan(c.kind.padEnd(10)) : "";const pathStr = c.path ? chalk.dim(` ${c.path}`) : "";const idStr = c.id ? chalk.dim(` ${c.id.slice(0, 8)}`) : "";- stderr(` ${i + 1}. ${kindStr}${idStr} ${c.name}${pathStr}`);+ const containerStr = c.container ? ` ${c.container}` : "";+ stderr(` ${i + 1}. ${kindStr}${idStr} ${c.name}${containerStr}${pathStr}`);}if (result.targetType === "ambiguous-file") {stderr(chalk.dim("\nProvide a more specific path to disambiguate."));@@ -758,7 +760,7 @@ function filterMatches(type SymbolResult =| { type: "resolved"; node: any; sourceUri: string | null }- | { type: "ambiguous"; candidates: Array<{ name: string; kind?: string; path?: string; id?: string }> }+ | { type: "ambiguous"; candidates: Array<{ name: string; kind?: string; path?: string; id?: string; container?: string }> }| { type: "not-found" };/**@@ -788,6 +790,7 @@ async function trySymbolMatch(type: "ambiguous",candidates: full.result.candidates.map(c => ({name: c.name, kind: c.kind, path: c.path, id: c.id,+ ...(c.container ? { container: c.container } : {}),})),};}diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.tsindex ac1d5560..575c7ba7 100644--- a/ix-cli/src/cli/resolve.ts+++ b/ix-cli/src/cli/resolve.ts@@ -187,7 +187,11 @@ export interface ResolvedEntity {export interface AmbiguousResult {resolutionMode: "ambiguous";- candidates: Array<{ id: string; name: string; kind: string; path?: string; line?: number; score?: number; rank?: number }>;+ /**+ * `container`: the type that holds the candidate (its CONTAINS parent, never+ * a file), when the graph names one. Added after the list is ranked.+ */+ candidates: Array<{ id: string; name: string; kind: string; path?: string; line?: number; score?: number; rank?: number; container?: string }>;diagnostics?: Array<{ code: string; message: string }>;/** How many candidates tied (the candidate list shows at most 8 of them). */total?: number;@@ -471,6 +475,20 @@ export async function resolveEntityFull(symbol: string,preferredKinds: string[],opts?: ResolveOpts+): Promise<ResolveResult> {+ return withContainers(client, await rankEntity(client, symbol, preferredKinds, opts));+}++/**+ * `resolveEntityFull` without the candidates' containers: for lookups inside+ * the resolver, and for a caller that may re-resolve before it reports (add+ * them with `withContainers` on the result it keeps).+ */+export async function rankEntity(+ client: IxClient,+ symbol: string,+ preferredKinds: string[],+ opts?: ResolveOpts): Promise<ResolveResult> {// Scope is applied server-side (workspace_id, or system_id for a co-ingest). Only an// EXPLICIT --path narrows further, client-side; we no longer default the path filter@@ -670,11 +688,36 @@ function cmpStr(a: string, b: string): number {return a < b ? -1 : a > b ? 1 : 0;}-/** Order for display and `--pick`: (path, line, id), independent of backend order. */+/** Tiebreak for equal candidates: (path, line, id), independent of backend order. */function displayOrder(a: any, b: any): number {return cmpStr(nodePath(a), nodePath(b)) || lineOf(a) - lineOf(b) || cmpStr(String(a.id), String(b.id));}+/**+ * A ranked candidate list dealt round-robin by file: the best of each file+ * (files in the order of their best), then each file's second-best, and so on.+ * Within a file the ranked order stands. Only 8 are listed, and a file that+ * defines the name eight times would otherwise fill the page alone, with the+ * definitions the caller wants in other files out of sight. This is the order+ * the list is numbered in, so `--pick n` and `--all`'s `candidate=<n>` follow it.+ * Files compare as lower-cased posix paths, so `src\a.py` and `src/a.py` are one file.+ */+export function roundRobinByFile<T>(ranked: readonly T[], nodeOf: (item: T) => any = (item) => item): T[] {+ const files = new Map<string, T[]>();+ for (const item of ranked) {+ const key = nodePath(nodeOf(item));+ const group = files.get(key);+ if (group) group.push(item);+ else files.set(key, [item]);+ }+ const groups = [...files.values()];+ const dealt: T[] = [];+ for (let round = 0; dealt.length < ranked.length; round++) {+ for (const group of groups) if (round < group.length) dealt.push(group[round]);+ }+ return dealt;+}+function entityPath(node: any): string | undefined {return node.provenance?.sourceUri ?? node.provenance?.source_uri ?? node.path;}@@ -979,22 +1022,101 @@ function importIdsOf(owner: object): Set<string> {return fullCandidates.get(owner)?.imports ?? new Set();}+/** At most this many names are asked for containers; candidates usually share one. */+const CONTAINER_NAME_LOOKUPS = 3;++/**+ * The container lookup is decoration on an answer that is already complete,+ * and `/v1/expand-by-name` is not scoped to the workspace: on a large shared+ * graph a common name (`get`, `__init__`) can be slow. Past this the rows go+ * out without `container` rather than hold up the exit-2 record.+ */+export const CONTAINER_LOOKUP_TIMEOUT_MS = 5_000;++/**+ * Name the type that holds each candidate of an ambiguous result: its+ * `container`, the CONTAINS parent the graph has for it unless that is a file+ * (a top-level definition has none). Eight `crop` rows in one file cannot be+ * told apart without it.+ *+ * Entities carry no container attribute, so it comes from the edges: one+ * `/v1/expand-by-name` per distinct candidate name (one in the usual case,+ * where every candidate has the name that was asked for), never a request per+ * candidate. That endpoint answers for every entity of the name, so only+ * edges into a listed candidate are read. Best effort: a backend that cannot+ * answer (or not within CONTAINER_LOOKUP_TIMEOUT_MS) leaves the rows as they+ * were, and `container` is then absent.+ *+ * Only the ambiguous record (exit 2) pays for this. A resolved target, a+ * `--pick` and a tie notice make no extra request.+ */+export async function withContainers(client: IxClient, result: ResolveResult): Promise<ResolveResult> {+ if (result.resolved || !result.ambiguous) return result;+ const all = allCandidatesOf(result.result);+ const ids = new Set(all.map((c) => c.id));+ const names = [...new Set(result.result.candidates.map((c) => c.name).filter(Boolean))].slice(0, CONTAINER_NAME_LOOKUPS);+ const answers = await Promise.all(names.map(async (name) => {+ try {+ return await client.expandByName(name, { direction: "in", predicates: ["CONTAINS"], timeoutMs: CONTAINER_LOOKUP_TIMEOUT_MS });+ } catch {+ return null;+ }+ }));+ const owners = new Map<string, Set<string>>();+ for (const answer of answers) {+ if (!answer || !Array.isArray(answer.nodes) || !Array.isArray(answer.edges)) continue;+ const byId = new Map(answer.nodes.map((n: any) => [String(n?.id), n]));+ for (const e of answer.edges) {+ if (e?.predicate !== "CONTAINS" || !ids.has(String(e.dst))) continue;+ const parent = byId.get(String(e.src));+ const name = parent?.name || parent?.attrs?.name;+ if (!name || String(parent.kind ?? "").toLowerCase() === "file") continue;+ const set = owners.get(String(e.dst)) ?? new Set<string>();+ set.add(String(name));+ owners.set(String(e.dst), set);+ }+ }+ // Added in place: the listed rows are the same objects as the head of the+ // full list, so `--pick` and the shown page stay one list. Two different+ // owners for one candidate is not an answer.+ for (const c of all) {+ const found = owners.get(c.id);+ if (found?.size === 1) c.container = [...found][0];+ }+ return result;+}++/** Consecutive runs of equal score, in order; no scores is one run. */+function scoreTiers<T extends { score?: number }>(ranked: readonly T[]): T[][] {+ const tiers: T[][] = [];+ for (const item of ranked) {+ const last = tiers[tiers.length - 1];+ if (last && last[0].score === item.score) last.push(item);+ else tiers.push([item]);+ }+ return tiers;+}+function buildAmbiguous(nodes: any[],scores?: number[],extra?: { total?: number; truncated?: boolean; diagnostics?: Array<{ code: string; message: string }> },): AmbiguousResult {- // The 8 best by the caller's ranking, then shown (and numbered for --pick) in- // (path, line, id) order so `--pick n` means the same thing on every run.+ // The caller's ranking dealt round-robin by file within each score tier,+ // then the first 8 shown and numbered for --pick. A tier is a run of equal+ // scores: spreading never puts a worse score (an import's +5) ahead of a+ // better one, so the page is still the 8 best by score. The ranking breaks+ // ties by (path, line, id), so `--pick n` means the same thing on every run.const seen = new Set<string>();- const picked: Array<{ node: any; score?: number }> = [];- for (let i = 0; i < nodes.length && picked.length < 8; i++) {+ const ranked: Array<{ node: any; score?: number }> = [];+ for (let i = 0; i < nodes.length; i++) {const node = nodes[i] as any;if (seen.has(node.id)) continue;seen.add(node.id);- picked.push({ node, score: scores?.[i] });+ ranked.push({ node, score: scores?.[i] });}- picked.sort((a, b) => displayOrder(a.node, b.node));+ const dealt = scoreTiers(ranked).flatMap((tier) => roundRobinByFile(tier, (r) => r.node));+ const picked = dealt.slice(0, 8);const candidates: AmbiguousResult["candidates"] = picked.map(({ node, score }, i) => {const line = lineOf(node);const rank = i + 1;@@ -1018,9 +1140,8 @@ function buildAmbiguous(...(extra?.diagnostics ?? []),],};- const unique = nodes.filter((n: any, i) => n?.id && nodes.findIndex((m: any) => m?.id === n.id) === i);- const imports = new Set(unique.filter((n: any) => candidateOrigin(n) === "import").map((n: any) => String(n.id)));- rememberAll(result, candidates, [...unique].sort(displayOrder).map(candidateOf), imports);+ const imports = new Set(ranked.filter(({ node }) => candidateOrigin(node) === "import").map(({ node }) => String(node.id)));+ rememberAll(result, candidates, dealt.map(({ node }) => candidateOf(node)), imports);return result;}@@ -1130,6 +1251,15 @@ export async function resolveFileOrEntityFull(client: IxClient,target: string,opts?: ResolveOpts+): Promise<ResolveResult> {+ return withContainers(client, await rankFileOrEntity(client, target, opts));+}++/** `resolveFileOrEntityFull` without the candidates' containers (`--all` lists none). */+async function rankFileOrEntity(+ client: IxClient,+ target: string,+ opts?: ResolveOpts): Promise<ResolveResult> {// 1. Raw UUIDif (isRawId(target)) {@@ -1220,7 +1350,7 @@ export async function resolveFileOrEntityFull(// A literal hit that is only fuzzy (no exact name) does not stop the// qualified reading, but the qualified one replaces it only where that// keeps the exit code: a resolved literal is replaced only by a resolved one.- const literal = await resolveEntityFull(client, target, allKinds, { ...opts, silentMiss: true });+ const literal = await rankEntity(client, target, allKinds, { ...opts, silentMiss: true });if ((literal.resolved || literal.ambiguous) && !isFuzzyResult(literal)) return literal;const qualified = await resolveQualified(client, scoped, opts, true);if (qualified?.resolved) return qualified;@@ -1231,11 +1361,11 @@ export async function resolveFileOrEntityFull(: `No entity found matching "${target}".`);return literal;}- if (!looksFileLike(target)) return resolveEntityFull(client, target, allKinds, opts);+ if (!looksFileLike(target)) return rankEntity(client, target, allKinds, opts);// A path is a question about a file. "No entity found" answered it as if it// were a symbol, which does not say whether the file exists, was never// ingested, or was mistyped -- three different next steps.- const result = await resolveEntityFull(client, target, allKinds, { ...opts, silentMiss: true });+ const result = await rankEntity(client, target, allKinds, { ...opts, silentMiss: true });if (result.resolved || result.ambiguous) return result;return fileMiss(client, target, opts);}@@ -1258,7 +1388,7 @@ async function resolveQualified(// This gives a precise path hint rather than a guess from snake_case conversion.// The lookup is silent: no "not found" or ambiguity text for the class.const shortClassName = scoped.className.split(/::|[.#]/).pop()!;- const classResult = await resolveEntityFull(+ const classResult = await rankEntity(client,shortClassName,['class', 'interface', 'struct', 'trait', 'object', 'function'],@@ -1313,7 +1443,7 @@ async function resolveQualified(path: pathHint, // always use the class-derived hint, not opts?.pathsearchLimit: 50,};- const result = await resolveEntityFull(client, scoped.methodName, ['method', 'function'], scopedOpts);+ const result = await rankEntity(client, scoped.methodName, ['method', 'function'], scopedOpts);if (result.resolved) {// Rewrite the display name to show the full scoped form, as the user typed itreturn {@@ -1383,7 +1513,8 @@ async function membersOf(* `Class.method` / `Class#method`: the method looked up IN each class (one* class, or every class that holds the name). One method found resolves; several* are the ambiguous record (exit 1, the same code as the miss this replaces),- * sorted by (path, line, id) so `--pick n` selects among them. None is null,+ * sorted by (path, line, id) and dealt round-robin by file (roundRobinByFile)+ * so `--pick n` selects among them. None is null,* which the caller reports as the miss.*/async function resolveInClasses(@@ -1407,10 +1538,10 @@ async function resolveInClasses(}if (found.size === 0) return null;const display = `${scoped.className}${scoped.sep}${scoped.methodName}`;- const ordered = [...found.values()].sort((a, b) =>+ const ordered = roundRobinByFile([...found.values()].sort((a, b) =>cmpStr(normalizeForPathMatch(a.path), normalizeForPathMatch(b.path))|| (a.line ?? Number.MAX_SAFE_INTEGER) - (b.line ?? Number.MAX_SAFE_INTEGER)- || cmpStr(a.id, b.id));+ || cmpStr(a.id, b.id)));if (ordered.length === 1) {const only = ordered[0];return {@@ -1662,7 +1793,8 @@ export async function resolveTargetSetOrReport(const entity = await resolveFileOrReport(client, target, withAll, format);return entity ? { entities: [entity] } : null;}- const result = await resolveFileOrEntityFull(client, target, { ...opts, format });+ // The --all candidate list does not show containers: no request for them.+ const result = await rankFileOrEntity(client, target, { ...opts, format });if (result.resolved) {const tie = result.notices?.find((n) => n.code === "ambiguous_target");if (!tie || tie.candidates.length <= 1) {diff --git a/ix-cli/src/cli/ui.ts b/ix-cli/src/cli/ui.tsindex 95508890..1a3a365f 100644--- a/ix-cli/src/cli/ui.ts+++ b/ix-cli/src/cli/ui.ts@@ -231,7 +231,7 @@ export function reportUnresolvedTarget(* from the only field that was included. One call has to be enough to pick.*/function candidateLines(- candidates: ReadonlyArray<{ id?: string; name: string; kind?: string; path?: string }>,+ candidates: ReadonlyArray<{ id?: string; name: string; kind?: string; path?: string; container?: string }>,record: "candidate" | "suggestion",): string[] {return candidates.map((candidate, index) => llmLine(record, [@@ -242,6 +242,8 @@ function candidateLines(// Short form: the full uuid is four times the tokens and nothing here needs// it -- `--pick <n>` is the way to choose, and a prefix resolves an entity.["id", candidate.id ? candidate.id.slice(0, 8) : undefined],+ // Last, so a reader of the fields before it sees them where they were.+ ["container", candidate.container],]));}@@ -290,9 +292,10 @@ export function reportAmbiguousTarget(}for (let index = 0; index < result.candidates.length; index += 1) {const candidate = result.candidates[index];- const shortPath = candidate.path ? ` in ${candidate.path}` : "";+ const shortPath = candidate.path ? ` in ${candidate.path}${candidate.line != null ? `:${candidate.line}` : ""}` : "";+ const container = candidate.container ? ` ${candidate.container}` : "";console.error(- ` ${index + 1}. ${chalk.cyan((candidate.kind ?? "").padEnd(10))} ${chalk.dim(candidate.id.slice(0, 8))} ${candidate.name}${chalk.dim(shortPath)}`,+ ` ${index + 1}. ${chalk.cyan((candidate.kind ?? "").padEnd(10))} ${chalk.dim(candidate.id.slice(0, 8))} ${candidate.name}${container}${chalk.dim(shortPath)}`,);}const hints = ["--pick <n>"];diff --git a/ix-cli/src/client/__tests__/expand-by-name.test.ts b/ix-cli/src/client/__tests__/expand-by-name.test.tsnew file mode 100644index 00000000..e738517c--- /dev/null+++ b/ix-cli/src/client/__tests__/expand-by-name.test.ts@@ -0,0 +1,40 @@+// Copyright 2026 Ix Infrastructure Inc.++import { createServer, type IncomingMessage, type Server } from "node:http";+import type { AddressInfo } from "node:net";+import { afterEach, describe, expect, it } from "vitest";+import { IxClient } from "../api.js";++const servers: Server[] = [];++/** A backend that reads the request and never answers. */+async function silentBackend(seen: unknown[]): Promise<string> {+ const server = createServer((req: IncomingMessage) => {+ let body = "";+ req.on("data", (c) => { body += c; });+ req.on("end", () => seen.push(JSON.parse(body)));+ });+ servers.push(server);+ await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));+ return `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+}++afterEach(async () => {+ await Promise.all(servers.splice(0).map(s => new Promise<void>(r => {+ s.closeAllConnections();+ s.close(() => r());+ })));+});++// The ambiguous record's container lookup bounds its own request, so a slow+// answer for a common name cannot hold up exit 2 for the 2-minute default.+describe("IxClient.expandByName", () => {+ it("gives up after timeoutMs, and keeps it out of the request body", async () => {+ const seen: unknown[] = [];+ const client = new IxClient(await silentBackend(seen));+ const started = Date.now();+ await expect(client.expandByName("get", { direction: "in", predicates: ["CONTAINS"], timeoutMs: 100 })).rejects.toThrow();+ expect(Date.now() - started).toBeLessThan(5_000);+ expect(seen[0]).toEqual({ name: "get", direction: "in", predicates: ["CONTAINS"] });+ });+});diff --git a/ix-cli/src/client/api.ts b/ix-cli/src/client/api.tsindex f2a50d09..06e957b4 100644--- a/ix-cli/src/client/api.ts+++ b/ix-cli/src/client/api.ts@@ -289,14 +289,14 @@ export class IxClient {async expandByName(name: string,- opts?: { direction?: string; predicates?: string[]; kinds?: string[] }+ opts?: { direction?: string; predicates?: string[]; kinds?: string[]; timeoutMs?: number }): Promise<{ nodes: any[]; edges: any[] }> {return this.post("/v1/expand-by-name", {name,direction: opts?.direction ?? "both",predicates: opts?.predicates,kinds: opts?.kinds,- });+ }, opts?.timeoutMs);}async expand(@@ -805,7 +805,7 @@ export class IxClient {return this.token !== undefined;}- private async post<T>(path: string, body: unknown): Promise<T> {+ private async post<T>(path: string, body: unknown, timeoutMs = 2 * 60 * 1000): Promise<T> {const payload = JSON.stringify(body);return this.read<T>("POST", path, payload, () =>fetch(`${this.endpoint}${path}`, {@@ -814,9 +814,10 @@ export class IxClient {body: payload,// These small reads/writes (source-hashes, stitch, list, ...) had no// timeout, so a stalled connection could hang the process indefinitely.- // 2 min per request, also bounded by the shared deadline when set, and- // by the read deadline when this POST is a read.- signal: this.signalFor(2 * 60 * 1000, isSharedRead(path)),+ // 2 min per request unless the caller bounds it, also bounded by the+ // shared deadline when set, and by the read deadline when this POST is+ // a read.+ signal: this.signalFor(timeoutMs, isSharedRead(path)),}));}diff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.mdindex f7430036..43de8856 100644--- a/skills/ix/references/flags.md+++ b/skills/ix/references/flags.md@@ -127,7 +127,8 @@ surfaces (#575).no row carries is dropped rather than emitted empty.- **`--pick <n>` is 1-based** everywhere it appears, and is how you resolve anambiguous target without re-running with a longer name. It indexes the list- in stable (path, line, id) order, and also selects among the candidates of a+ in its stable numbered order (best match first; equal matches dealt+ round-robin by file so one file cannot fill the page), and also selects among the candidates of aresolution notice (a target that resolved by choosing among equal matches;only the true ties are listed and numbered).- **`--all` answers an ambiguous name for every candidate** (`callers`,