Skip to content

armgit / Ix

Public Imported from GitHub
0

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

fix(cli): CL-19B target resolution reports its guesses without new exit codes

KageBinarye25cfe3cf9be
diff --git a/docs/llm-format.md b/docs/llm-format.md
index 3c75d5c5..a2b5d9d8 100644
--- a/docs/llm-format.md
+++ b/docs/llm-format.md
@@ -76,11 +76,46 @@ which value it ignored, on stderr, when a person is there to read it.
maps it.
An ambiguous graph target is instead `ambiguous_target`, includes numbered
candidates, and exits non-zero because the requested graph operation could
- not choose a target. (The
+ 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
backend spells a missing target `unknown_target` in its own JSON bodies; that
is a wire detail and is translated on the way out, so a consumer never sees
both.)
+### Resolution notices (exit 0)
+
+When a target resolves by choosing among equal candidates, or by a fuzzy match,
+the command still succeeds. It says so with `diagnostic` records, never an
+`error` record, printed before the command's own first record (so before a
+`context` header):
+
+```
+diagnostic code=ambiguous_target target=index.ts chosen=index.ts shown=3 total=3 message="..."
+candidate n=1 name=index.ts kind=file path=packages/a/src/index.ts id=1111aaaa
+candidate n=2 name=index.ts kind=file path=packages/b/src/index.ts id=2222bbbb
+hint text="Use --pick <n> or --path to choose another."
+```
+
+The candidates are only the true ties: the ones that scored the same as the
+chosen target. `shown=`, `total=` and `--pick <n>` all count that same list.
+Candidates that scored close but lower are not listed as equal; the message
+only counts them ("2 more scored lower and are not listed"). `--pick <n>`
+selects among the listed candidates; an out-of-range pick keeps the
+default and adds a `pick_out_of_range` diagnostic, still exiting 0.
+
+`Class.method` and `Class#method` resolve only to a member of that class: one
+of the class's `CONTAINS` children in the graph or, when the graph has none
+for it, a symbol in the class's own source file (the same path, not a
+substring of it). A same-named method elsewhere is not returned; the target is
+a miss instead. A match on
+a name that is not an exact one is `diagnostic code=fuzzy_match
+resolution=fuzzy ...`, and json carries `resolutionMode: "fuzzy"`. In json the
+notices are a top-level `resolutionNotices` array merged into the command's
+object; an `{error}` record never carries one.
+
## Graph health
`explain` and `context` check that the graph they answer from still has its
diff --git a/ix-cli/src/cli/__tests__/ambiguity-and-suggestions.test.ts b/ix-cli/src/cli/__tests__/ambiguity-and-suggestions.test.ts
index 8574bdc8..f90f2a9c 100644
--- a/ix-cli/src/cli/__tests__/ambiguity-and-suggestions.test.ts
+++ b/ix-cli/src/cli/__tests__/ambiguity-and-suggestions.test.ts
@@ -90,6 +90,33 @@ describe("an ambiguous target in llm format", () => {
expect(JSON.parse(stdout).candidates[0].id).toBe("1111aaaa-0000-0000-0000-000000000000");
});
+ it("says how many tied, in llm, after the unchanged count=", async () => {
+ const { stdout } = await run(["overview", "Duplicate", "--format", "llm"]);
+ expect(stdout.split("\n")[0]).toMatch(/error code=ambiguous_target .*count=2 shown=2 total=2$/);
+ });
+
+ it("says how many tied in json, and whether the list was cut off", async () => {
+ const payload = JSON.parse((await run(["overview", "Duplicate", "--format", "json"])).stdout);
+ expect(payload.total).toBe(2);
+ expect(payload.truncated).toBeUndefined();
+ expect(payload.error).toBe("ambiguous_target");
+ });
+
+ it("shows N of M in text when only some candidates are listed", async () => {
+ const { reportAmbiguousTarget } = await import("../ui.js");
+ const candidates = Array.from({ length: 8 }, (_, i) => ({ id: `id-${i}000000`, name: "run", kind: "method", path: `src/m${i}.ts` }));
+ const lines: string[] = [];
+ const error = vi.spyOn(console, "error").mockImplementation((...parts) => lines.push(parts.join(" ")));
+ try {
+ reportAmbiguousTarget("run", { resolutionMode: "ambiguous", candidates, total: 30, truncated: true }, "text");
+ reportAmbiguousTarget("run", { resolutionMode: "ambiguous", candidates, total: 12 }, "text");
+ } finally {
+ error.mockRestore();
+ }
+ expect(lines.join("\n")).toContain("Showing 8 of >=30");
+ expect(lines.join("\n")).toContain("Showing 8 of 12");
+ });
+
it("drops the flags it was already given from the hint", async () => {
// Called directly: which flags are worth suggesting is the reporter's
// decision, and reaching it through a command means first arranging for
diff --git a/ix-cli/src/cli/__tests__/pick-resolution.test.ts b/ix-cli/src/cli/__tests__/pick-resolution.test.ts
index 51e1f2a0..95ebf512 100644
--- a/ix-cli/src/cli/__tests__/pick-resolution.test.ts
+++ b/ix-cli/src/cli/__tests__/pick-resolution.test.ts
@@ -1,7 +1,7 @@
// Copyright 2026 Ix Infrastructure Inc.
import { describe, it, expect } from "vitest";
-import { applyPick, type ResolveResult, type AmbiguousResult } from "../resolve.js";
+import { applyPick, pickFromNotice, type ResolutionNotice, type ResolveResult, type AmbiguousResult } from "../resolve.js";
function makeAmbiguousResult(count: number): ResolveResult & { resolved: false; ambiguous: true } {
const candidates: AmbiguousResult["candidates"] = [];
@@ -109,3 +109,47 @@ describe("applyPick", () => {
expect(applyPick(result, { pick: 1 })).toBeNull();
});
});
+
+describe("pickFromNotice", () => {
+ const candidates: AmbiguousResult["candidates"] = [
+ { id: "id-0", name: "index.ts", kind: "file", path: "packages/a/src/index.ts", rank: 1 },
+ { id: "id-1", name: "index.ts", kind: "file", path: "packages/b/src/index.ts", rank: 2 },
+ ];
+ const notice: ResolutionNotice = {
+ code: "ambiguous_target",
+ target: "index.ts",
+ message: "tied",
+ chosen: candidates[0],
+ candidates,
+ total: 2,
+ };
+ const resolved: ResolveResult = {
+ resolved: true,
+ entity: { id: "id-0", kind: "file", name: "index.ts", path: "packages/a/src/index.ts", resolutionMode: "scored" },
+ notices: [notice],
+ };
+
+ it("leaves the result alone without --pick, a notice or a resolved result", () => {
+ expect(pickFromNotice(resolved, {})).toBe(resolved);
+ const plain: ResolveResult = { resolved: true, entity: { id: "x", kind: "file", name: "x", resolutionMode: "exact" } };
+ expect(pickFromNotice(plain, { pick: 2 })).toBe(plain);
+ const miss: ResolveResult = { resolved: false, ambiguous: false };
+ expect(pickFromNotice(miss, { pick: 2 })).toBe(miss);
+ });
+
+ it("resolves to the picked candidate, as scored, and drops the notice", () => {
+ const picked = pickFromNotice(resolved, { pick: 2 });
+ expect(picked.resolved && picked.entity.id).toBe("id-1");
+ expect(picked.resolved && picked.entity.resolutionMode).toBe("scored");
+ expect(picked.resolved && picked.notices).toEqual([]);
+ });
+
+ it("keeps the default and stays resolved when the pick is out of range", () => {
+ const picked = pickFromNotice(resolved, { pick: 7 });
+ expect(picked.resolved).toBe(true);
+ if (picked.resolved) {
+ expect(picked.entity.id).toBe("id-0");
+ expect(picked.notices?.[0].diagnostics?.[0].code).toBe("pick_out_of_range");
+ }
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/target-resolution.test.ts b/ix-cli/src/cli/__tests__/target-resolution.test.ts
new file mode 100644
index 00000000..4ec9c0d6
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/target-resolution.test.ts
@@ -0,0 +1,552 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { printJson, resetResolutionNotices } from "../format.js";
+import { resolveFileOrEntityFull, resolveFileOrReport } from "../resolve.js";
+
+// Same stand-in as resolver-definitions-first: the checkout is not a registered
+// workspace, and this suite is about resolution, not scoping.
+vi.mock("../bootstrap.js", async (orig) => ({
+ ...(await orig<typeof import("../bootstrap.js")>()),
+ resolveWorkspaceId: () => "ws-test",
+}));
+
+/**
+ * CL-19B: a target that matches several things no longer picks one silently.
+ * It still resolves where it resolved before (exit 0) and reports what it
+ * passed over; what was ambiguous (exit 1) stays so. No new non-zero exit.
+ */
+
+type Node = ReturnType<typeof node>;
+
+function node(id: string, name: string, kind: string, path: string, line = 1) {
+ return { id, name, kind, provenance: { sourceUri: path }, attrs: { line_start: line, line_end: line + 10 } };
+}
+
+const file = (path: string, id = path) => node(id, path.slice(path.lastIndexOf("/") + 1), "file", path);
+
+/** A fake backend: name substring match, `kind` and `limit` honoured. */
+function client(nodes: Node[]) {
+ return {
+ search: vi.fn(async (term: string, opts: { limit?: number; kind?: string }) => {
+ const t = term.toLowerCase();
+ const hits = nodes.filter((x) => (!opts.kind || x.kind === opts.kind) && x.name.toLowerCase().includes(t));
+ return hits.slice(0, opts.limit);
+ }),
+ workspaceSystem: vi.fn(async () => null),
+ } as any;
+}
+
+/** Run `fn` against the backend in both of its orders. */
+async function inBothOrders<T>(nodes: Node[], fn: (c: any) => Promise<T>): Promise<[T, T]> {
+ return [await fn(client(nodes)), await fn(client([...nodes].reverse()))];
+}
+
+let logs: string[];
+let errs: string[];
+
+beforeEach(() => {
+ process.exitCode = undefined;
+ resetResolutionNotices();
+ logs = [];
+ errs = [];
+ vi.spyOn(console, "log").mockImplementation((...a: unknown[]) => { logs.push(a.join(" ")); });
+ vi.spyOn(console, "error").mockImplementation((...a: unknown[]) => { errs.push(a.join(" ")); });
+ vi.spyOn(process.stderr, "write").mockImplementation(((chunk: unknown) => { errs.push(String(chunk)); return true; }) as any);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ process.exitCode = undefined;
+ resetResolutionNotices();
+});
+
+async function full(c: any, target: string, opts: Record<string, unknown> = {}) {
+ return resolveFileOrEntityFull(c, target, { format: "json", ...opts } as any);
+}
+
+function paths(notices: any[] | undefined): string[] {
+ return (notices?.[0]?.candidates ?? []).map((c: any) => c.path);
+}
+
+const PACKAGES = [
+ file("packages/ab/src/index.ts"),
+ file("packages/beta/src/index.ts"),
+ file("packages/gamma/src/index.ts"),
+];
+
+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 () => {
+ const [a, b] = await inBothOrders(PACKAGES, (c) => full(c, "index.ts"));
+ for (const r of [a, b]) {
+ expect(r.resolved).toBe(true);
+ if (!r.resolved) continue;
+ expect(r.entity.resolutionMode).toBe("scored");
+ expect(r.notices?.[0].code).toBe("ambiguous_target");
+ expect(r.notices?.[0].total).toBe(3);
+ expect(paths(r.notices)).toEqual(PACKAGES.map((p) => p.provenance.sourceUri));
+ }
+ expect(a.resolved && b.resolved && a.entity.id === b.entity.id).toBe(true);
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it("--pick 2 selects packages/beta", async () => {
+ const [a, b] = await inBothOrders(PACKAGES, (c) => full(c, "index.ts", { pick: 2 }));
+ for (const r of [a, b]) {
+ expect(r.resolved && r.entity.path).toBe("packages/beta/src/index.ts");
+ }
+ });
+});
+
+describe("acceptance 2: a suffix shared by three packages", () => {
+ it("resolves, never as exact, with a notice", async () => {
+ const [a, b] = await inBothOrders(PACKAGES, (c) => full(c, "src/index.ts"));
+ for (const r of [a, b]) {
+ expect(r.resolved).toBe(true);
+ if (!r.resolved) continue;
+ expect(r.entity.resolutionMode).not.toBe("exact");
+ expect(r.notices?.[0].total).toBe(3);
+ }
+ expect(a.resolved && b.resolved && a.entity.id === b.entity.id).toBe(true);
+ });
+
+ it("a root src/index.ts wins at the full-path tier: exact, no notice", async () => {
+ const nodes = [file("src/index.ts"), ...PACKAGES];
+ const [a, b] = await inBothOrders(nodes, (c) => full(c, "src/index.ts"));
+ for (const r of [a, b]) {
+ expect(r.resolved && r.entity.path).toBe("src/index.ts");
+ expect(r.resolved && r.entity.resolutionMode).toBe("exact");
+ expect(r.resolved && r.notices).toBeUndefined();
+ }
+ });
+
+ it("an absolute path picks the deeper file", async () => {
+ const nodes = [file("src/index.ts"), ...PACKAGES];
+ const [a, b] = await inBothOrders(nodes, (c) => full(c, "/work/repo/packages/beta/src/index.ts"));
+ for (const r of [a, b]) {
+ expect(r.resolved && r.entity.path).toBe("packages/beta/src/index.ts");
+ expect(r.resolved && r.notices).toBeUndefined();
+ }
+ });
+});
+
+describe("acceptance 3: a suffix stops at a path segment", () => {
+ const nodes = [file("ix-cli/config.ts"), file("src/cli/config.ts")];
+
+ it("cli/config.ts is src/cli/config.ts, not ix-cli/config.ts, and says nothing", async () => {
+ const [a, b] = await inBothOrders(nodes, (c) => full(c, "cli/config.ts"));
+ for (const r of [a, b]) {
+ expect(r.resolved && r.entity.path).toBe("src/cli/config.ts");
+ expect(r.resolved && r.notices).toBeUndefined();
+ }
+ });
+
+ it("li/config.ts (not on a boundary) still resolves, so no new exit 1", async () => {
+ const [a, b] = await inBothOrders(nodes, (c) => full(c, "li/config.ts"));
+ expect(a.resolved).toBe(true);
+ expect(b.resolved).toBe(true);
+ expect(a.resolved && b.resolved && a.entity.id === b.entity.id).toBe(true);
+ });
+});
+
+describe("acceptance 4: two functions named render stay ambiguous (exit 1)", () => {
+ const nodes = [node("r2", "render", "function", "src/z.ts", 5), node("r1", "render", "function", "src/a.ts", 9)];
+
+ it("json: path-sorted candidates with total, the same in both orders", async () => {
+ const outs: any[] = [];
+ for (const c of [client(nodes), client([...nodes].reverse())]) {
+ logs.length = 0;
+ process.exitCode = undefined;
+ expect(await resolveFileOrReport(c, "render", {}, "json")).toBeNull();
+ expect(process.exitCode).toBe(1);
+ outs.push(JSON.parse(logs[0]));
+ }
+ expect(outs[0].error).toBe("ambiguous_target");
+ expect(outs[0].total).toBe(2);
+ expect(outs[0].candidates.map((c: any) => c.path)).toEqual(["src/a.ts", "src/z.ts"]);
+ expect(outs[0].candidates).toEqual(outs[1].candidates);
+ });
+
+ it("llm: count= unchanged, shown= and total= added", async () => {
+ await resolveFileOrReport(client(nodes), "render", {}, "llm");
+ expect(process.exitCode).toBe(1);
+ expect(logs[0]).toMatch(/^error code=ambiguous_target .*count=2 shown=2 total=2/);
+ });
+});
+
+describe("acceptance 5: Class.method, Class#method and Class::method", () => {
+ const nodes = [
+ node("cls", "IxClient", "class", "src/client/api.ts", 10),
+ node("m-api", "expand", "method", "src/client/api.ts", 200),
+ node("m-other", "expand", "method", "src/other/graph.ts", 30),
+ node("os", "os.path", "module", "lib/os.py"),
+ ];
+
+ for (const sep of [".", "#", "::"]) {
+ it(`IxClient${sep}expand is the method in src/client/api.ts`, async () => {
+ const [a, b] = await inBothOrders(nodes, (c) => full(c, `IxClient${sep}expand`));
+ for (const r of [a, b]) {
+ expect(r.resolved && r.entity.id).toBe("m-api");
+ expect(r.resolved && r.entity.name).toBe(`IxClient${sep}expand`);
+ }
+ expect(process.exitCode).toBeUndefined();
+ });
+ }
+
+ it("a name stored with a dot still resolves literally", async () => {
+ const r = await full(client(nodes), "os.path");
+ expect(r.resolved && r.entity.id).toBe("os");
+ });
+
+ for (const sep of [".", "#", "::"]) {
+ it(`Worker${sep}run with two tied methods is ambiguous, not a miss`, async () => {
+ const tied = [
+ node("w", "Worker", "class", "src/worker.ts", 1),
+ node("r1", "run", "method", "src/worker.ts", 10),
+ node("r2", "run", "method", "src/worker.ts", 20),
+ ];
+ const r = await full(client(tied), `Worker${sep}run`);
+ expect(r.resolved).toBe(false);
+ expect(r.resolved === false && "ambiguous" in r && r.ambiguous).toBe(true);
+ });
+ }
+
+ it("--pick on a fuzzy match keeps the fuzzy notice on the picked entity", async () => {
+ const fz = [
+ node("a", "WorkerAlpha", "class", "src/a.ts"),
+ node("b", "WorkerBeta", "interface", "src/b.ts"),
+ ];
+ const r = await full(client(fz), "Worker", { pick: 2 });
+ if (!r.resolved) throw new Error("expected resolved");
+ expect(r.entity.id).toBe("b");
+ for (const n of r.notices ?? []) expect(n.chosen.id).toBe("b");
+ });
+
+ for (const sep of [".", "#"]) {
+ it(`Config${sep}load with Config in two files is ambiguous between the methods, not a miss`, async () => {
+ const twoClasses = [
+ node("ca", "Config", "class", "a/config.ts", 1),
+ node("cb", "Config", "class", "b/config.ts", 1),
+ node("la", "load", "method", "a/config.ts", 10),
+ node("lb", "load", "method", "b/config.ts", 10),
+ ];
+ const [a, b] = await inBothOrders(twoClasses, (c) => full(c, `Config${sep}load`));
+ for (const r of [a, b]) {
+ if (r.resolved || !r.ambiguous) throw new Error("expected ambiguous");
+ expect(r.result.candidates.map((c) => c.id)).toEqual(["la", "lb"]);
+ expect(r.result.total).toBe(2);
+ }
+ const picked = await full(client(twoClasses), `Config${sep}load`, { pick: 2 });
+ expect(picked.resolved && picked.entity.id).toBe("lb");
+ expect(picked.resolved && picked.entity.name).toBe(`Config${sep}load`);
+ });
+
+ it(`Config${sep}load resolves when only one of the Config classes has it`, async () => {
+ const oneHas = [
+ node("ca", "Config", "class", "a/config.ts", 1),
+ node("cb", "Config", "class", "b/config.ts", 1),
+ node("lb", "load", "method", "b/config.ts", 10),
+ ];
+ const [a, b] = await inBothOrders(oneHas, (c) => full(c, `Config${sep}load`));
+ for (const r of [a, b]) {
+ expect(r.resolved && r.entity.id).toBe("lb");
+ expect(r.resolved && r.entity.name).toBe(`Config${sep}load`);
+ }
+ });
+ }
+
+ for (const sep of [".", "#"]) {
+ it(`User${sep}save stays a miss when only UserService exists (no fuzzy class)`, async () => {
+ const nodes2 = [
+ node("us", "UserService", "class", "app/user_service.py", 1),
+ node("save", "save", "method", "app/user_service.py", 10),
+ ];
+ const [a, b] = await inBothOrders(nodes2, (c) => full(c, `User${sep}save`));
+ for (const r of [a, b]) expect(r.resolved || ("ambiguous" in r && r.ambiguous)).toBe(false);
+ });
+
+ it(`Config${sep}load ignores a fuzzy near-name method (loader)`, async () => {
+ const onlyNear = [
+ node("ca", "Config", "class", "a/config.py", 1),
+ node("cb", "Config", "class", "b/config.py", 1),
+ node("ldr", "loader", "method", "a/config.py", 10),
+ ];
+ const [a, b] = await inBothOrders(onlyNear, (c) => full(c, `Config${sep}load`));
+ for (const r of [a, b]) expect(r.resolved || ("ambiguous" in r && r.ambiguous)).toBe(false);
+
+ const withExact = [...onlyNear, node("lb", "load", "method", "b/config.py", 10)];
+ const [c1, c2] = await inBothOrders(withExact, (c) => full(c, `Config${sep}load`));
+ for (const r of [c1, c2]) {
+ expect(r.resolved && r.entity.id).toBe("lb");
+ expect(r.resolved && r.entity.name).toBe(`Config${sep}load`);
+ }
+ });
+
+ it(`Single${sep}load ignores a fuzzy method in the one class's file`, async () => {
+ const single = [
+ node("s", "Single", "class", "src/single.py", 1),
+ node("ldr", "loader", "method", "src/single.py", 10),
+ ];
+ const r = await full(client(single), `Single${sep}load`);
+ expect(r.resolved || ("ambiguous" in r && r.ambiguous)).toBe(false);
+ });
+ }
+
+ it("a qualified name whose class is not found stays a miss", async () => {
+ const r = await full(client(nodes), "Nope.expand");
+ expect(r.resolved).toBe(false);
+ });
+});
+
+/** The fake backend plus the graph's CONTAINS edges (class id -> member ids). */
+function clientWithContains(nodes: Node[], contains: Record<string, string[]>) {
+ const c = client(nodes);
+ c.expand = vi.fn(async (id: string) => ({
+ nodes: (contains[id] ?? []).map((m) => nodes.find((n) => n.id === m)).filter(Boolean),
+ edges: [],
+ }));
+ return c;
+}
+
+describe("Class.method must be a member of the class (round 4)", () => {
+ for (const sep of [".", "#"]) {
+ it(`Config${sep}load: a load in a file whose path contains the class's file is not returned`, async () => {
+ // `xa/config.ts` contains the substring `a/config.ts` and the old basename
+ // hint `config`; neither makes its `load` a member of a/config.ts's Config.
+ const nodes = [
+ node("ca", "Config", "class", "a/config.ts", 1),
+ node("other", "load", "method", "xa/config.ts", 10),
+ ];
+ for (const c of [client(nodes), clientWithContains(nodes, { ca: [] })]) {
+ const r = await full(c, `Config${sep}load`);
+ expect(r.resolved).toBe(false);
+ expect(!r.resolved && r.ambiguous).toBe(false);
+ }
+ });
+
+ it(`Config${sep}load resolves to the class's own load, from CONTAINS or the same file`, async () => {
+ const nodes = [
+ node("ca", "Config", "class", "a/config.ts", 1),
+ node("own", "load", "method", "a/config.ts", 10),
+ node("other", "load", "method", "xa/config.ts", 10),
+ ];
+ const viaFile = await inBothOrders(nodes, (c) => full(c, `Config${sep}load`));
+ const viaGraph = await inBothOrders(nodes, (c) =>
+ full(Object.assign(c, { expand: clientWithContains(nodes, { ca: ["own"] }).expand }), `Config${sep}load`));
+ for (const r of [...viaFile, ...viaGraph]) {
+ expect(r.resolved && r.entity.id).toBe("own");
+ expect(r.resolved && r.entity.name).toBe(`Config${sep}load`);
+ }
+ });
+
+ it(`Config${sep}load: CONTAINS rules out a same-file load that belongs to another class`, async () => {
+ const nodes = [
+ node("ca", "Config", "class", "a/config.ts", 1),
+ node("cx", "Loader", "class", "a/config.ts", 50),
+ node("theirs", "load", "method", "a/config.ts", 60),
+ node("save", "save", "method", "a/config.ts", 10),
+ ];
+ const c = clientWithContains(nodes, { ca: ["save"], cx: ["theirs"] });
+ const r = await full(c, `Config${sep}load`);
+ expect(r.resolved || (!r.resolved && r.ambiguous)).toBe(false);
+ expect(c.expand).toHaveBeenCalledWith("ca", expect.objectContaining({ predicates: ["CONTAINS"] }));
+ });
+
+ it(`Config${sep}load prints exactly one miss line in text mode`, async () => {
+ const nodes = [
+ node("ca", "Config", "class", "a/config.ts", 1),
+ node("other", "load", "method", "xa/config.ts", 10),
+ ];
+ const r = await full(client(nodes), `Config${sep}load`, { format: "text" });
+ expect(r.resolved).toBe(false);
+ const misses = errs.join("").split("\n").filter((l) => /No entity/.test(l));
+ expect(misses).toEqual([`No entity found matching "Config${sep}load".`]);
+ });
+ }
+});
+
+describe("a tie notice lists only the true ties (round 4)", () => {
+ // class and interface tie at the top score; the module scores lower but
+ // within the old +5 window, so it used to be counted as "equal".
+ const nodes = [
+ node("cls", "Parser", "class", "src/a.ts"),
+ node("ifc", "Parser", "interface", "src/b.ts"),
+ node("mod", "Parser", "module", "src/c.ts"),
+ ];
+
+ it("total, candidates and --pick cover the top tier; the near-miss is only counted", async () => {
+ const [a, b] = await inBothOrders(nodes, (c) => full(c, "Parser"));
+ for (const r of [a, b]) {
+ if (!r.resolved) throw new Error("expected resolved");
+ expect(r.entity.id).toBe("cls");
+ const n = r.notices?.[0];
+ expect(n?.code).toBe("ambiguous_target");
+ expect(n?.total).toBe(2);
+ expect(n?.candidates.map((c) => c.id)).toEqual(["cls", "ifc"]);
+ expect(n?.message).toContain("matches 2 candidates equally");
+ expect(n?.message).toContain("1 more scored lower and is not listed.");
+ }
+ const picked = await full(client(nodes), "Parser", { pick: 2 });
+ expect(picked.resolved && picked.entity.id).toBe("ifc");
+ const outOfRange = await full(client(nodes), "Parser", { pick: 3 });
+ expect(outOfRange.resolved && outOfRange.entity.id).toBe("cls");
+ expect(errs.join("")).toContain("--pick 3 is out of range (1-2).");
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it("llm: shown= and total= match the listed candidates", async () => {
+ expect(await resolveFileOrReport(client(nodes), "Parser", {}, "llm")).not.toBeNull();
+ const lines = logs.join("\n").split("\n");
+ expect(lines[0]).toMatch(/^diagnostic code=ambiguous_target target=Parser .*shown=2 total=2/);
+ expect(lines.filter((l) => l.startsWith("candidate "))).toHaveLength(2);
+ });
+});
+
+describe("--pick among fuzzy candidates stays fuzzy", () => {
+ it("an ambiguous fuzzy set picked with --pick is labelled fuzzy with a notice", async () => {
+ const nodes = [
+ node("r1", "runAlpha", "function", "src/a.ts"),
+ node("r2", "runBeta", "function", "src/b.ts"),
+ ];
+ const base = await full(client(nodes), "run");
+ expect(base.resolved).toBe(false);
+ const r = await full(client(nodes), "run", { pick: 2 });
+ if (!r.resolved) throw new Error("expected resolved");
+ expect(r.entity.id).toBe("r2");
+ expect(r.entity.resolutionMode).toBe("fuzzy");
+ expect(r.notices?.[0].code).toBe("fuzzy_match");
+ expect(r.notices?.[0].chosen.id).toBe("r2");
+ });
+});
+
+describe("a fuzzy literal hit does not hide the qualified reading", () => {
+ it("Config.load prefers the class member over a fuzzy literal Config.loadAll", async () => {
+ const nodes = [
+ node("entry", "Config.loadAll", "config_entry", "conf/app.toml", 3),
+ node("ca", "Config", "class", "a/config.ts", 1),
+ node("own", "load", "method", "a/config.ts", 10),
+ ];
+ const [a, b] = await inBothOrders(nodes, (c) => full(c, "Config.load"));
+ for (const r of [a, b]) expect(r.resolved && r.entity.id).toBe("own");
+ });
+
+ it("keeps the fuzzy literal (exit 0) when the qualified reading misses", async () => {
+ const nodes = [
+ node("entry", "Config.loadAll", "config_entry", "conf/app.toml", 3),
+ node("ca", "Config", "class", "a/config.ts", 1),
+ ];
+ const r = await full(client(nodes), "Config.load");
+ expect(r.resolved && r.entity.id).toBe("entry");
+ expect(r.resolved && r.entity.resolutionMode).toBe("fuzzy");
+ });
+});
+
+describe("acceptance 6: fuzzy matches are labelled", () => {
+ const nodes = [
+ node("fn", "reparseConfig", "function", "src/parse-pool.ts", 3),
+ node("m", "expand", "method", "src/client/api.ts", 20),
+ ];
+
+ it("`parse` resolves to reparseConfig as fuzzy, with a fuzzy_match notice, exit 0", async () => {
+ const [a, b] = await inBothOrders(nodes, (c) => full(c, "parse"));
+ for (const r of [a, b]) {
+ expect(r.resolved && r.entity.id).toBe("fn");
+ expect(r.resolved && r.entity.resolutionMode).toBe("fuzzy");
+ expect(r.resolved && r.notices?.map((n) => n.code)).toEqual(["fuzzy_match"]);
+ }
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it("llm: resolution=fuzzy, and the output never starts with `error code=`", async () => {
+ expect(await resolveFileOrReport(client(nodes), "parse", {}, "llm")).not.toBeNull();
+ expect(process.exitCode).toBeUndefined();
+ expect(logs[0]).toMatch(/^diagnostic code=fuzzy_match resolution=fuzzy/);
+ expect(logs.join("\n")).not.toMatch(/^error code=/);
+ });
+
+ it("json: resolutionMode fuzzy and resolutionNotices merge into the command's object", async () => {
+ expect(await resolveFileOrReport(client(nodes), "parse", {}, "json")).not.toBeNull();
+ printJson({ results: [] });
+ const out = JSON.parse(logs[0]);
+ expect(out.results).toEqual([]);
+ expect(out.resolutionMode).toBe("fuzzy");
+ expect(out.resolutionNotices[0].code).toBe("fuzzy_match");
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it("`expan` keeps resolving and is labelled fuzzy", async () => {
+ const r = await full(client(nodes), "expan");
+ expect(r.resolved && r.entity.resolutionMode).toBe("fuzzy");
+ });
+});
+
+describe("acceptance 7: many methods named run", () => {
+ const runs = (n: number) => Array.from({ length: n }, (_, i) =>
+ node(`run-${String(i).padStart(2, "0")}`, "run", "method", `src/m${String(i).padStart(2, "0")}.ts`, 4));
+
+ it("40 of them (window 30): exit 1 as before, 8 shown, total=30, truncated", async () => {
+ const nodes = runs(40);
+ logs.length = 0;
+ expect(await resolveFileOrReport(client(nodes), "run", {}, "json")).toBeNull();
+ expect(process.exitCode).toBe(1);
+ const out = JSON.parse(logs[0]);
+ expect(out.error).toBe("ambiguous_target");
+ expect(out.candidates).toHaveLength(8);
+ expect(out.total).toBe(30);
+ expect(out.truncated).toBe(true);
+ });
+
+ it("20 of them: --pick 3 gives the same id in both orders", async () => {
+ const [a, b] = await inBothOrders(runs(20), (c) => full(c, "run", { pick: 3 }));
+ expect(a.resolved && b.resolved).toBe(true);
+ expect(a.resolved && b.resolved && a.entity.id === b.entity.id).toBe(true);
+ });
+});
+
+describe("modes and notices", () => {
+ it("ResolutionMode vs resolutionMode is not reported exact", async () => {
+ const r = await full(client([node("p", "resolutionMode", "field", "src/a.ts")]), "ResolutionMode");
+ expect(r.resolved && r.entity.resolutionMode).not.toBe("exact");
+ });
+
+ it("--kind no longer forces exact", async () => {
+ const r = await full(client([node("p", "Parse", "function", "src/a.ts")]), "parse", { kind: "function" });
+ expect(r.resolved && r.entity.resolutionMode).not.toBe("exact");
+ });
+
+ it("a case-sensitive exact name stays exact", async () => {
+ const r = await full(client([node("p", "parse", "function", "src/a.ts")]), "parse");
+ expect(r.resolved && r.entity.resolutionMode).toBe("exact");
+ });
+
+ it("the json notice merges into an object but never into an {error} record", () => {
+ resetResolutionNotices();
+ const notice = { code: "ambiguous_target", total: 2 };
+ // (reportResolutionNotices queues through the same store)
+ return import("../format.js").then(({ noteResolutionNotices }) => {
+ noteResolutionNotices([notice]);
+ printJson({ error: "boom", message: "x" });
+ expect(JSON.parse(logs[0])).toEqual({ error: "boom", message: "x" });
+ printJson({ ok: true });
+ expect(JSON.parse(logs[1])).toEqual({ ok: true });
+ });
+ });
+
+ it("an out-of-range --pick on a notice keeps the default and exit 0", async () => {
+ const r = await full(client(PACKAGES), "index.ts", { pick: 9 });
+ expect(r.resolved).toBe(true);
+ if (r.resolved) expect(r.notices?.[0].diagnostics?.[0].code).toBe("pick_out_of_range");
+ expect(process.exitCode).toBeUndefined();
+ expect(errs.join("\n")).toContain("--pick 9 is out of range");
+ });
+
+ it("an ambiguity notice in llm is diagnostic, candidate and hint records, exit 0", async () => {
+ expect(await resolveFileOrReport(client(PACKAGES), "index.ts", {}, "llm")).not.toBeNull();
+ expect(process.exitCode).toBeUndefined();
+ const lines = logs.join("\n").split("\n");
+ expect(lines[0]).toMatch(/^diagnostic code=ambiguous_target target=index.ts .*shown=3 total=3/);
+ expect(lines.filter((l) => l.startsWith("candidate "))).toHaveLength(3);
+ expect(lines.some((l) => l.startsWith("hint ") && l.includes("--pick"))).toBe(true);
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/unresolved-machine-output.test.ts b/ix-cli/src/cli/__tests__/unresolved-machine-output.test.ts
index 39ebad18..41c16da8 100644
--- a/ix-cli/src/cli/__tests__/unresolved-machine-output.test.ts
+++ b/ix-cli/src/cli/__tests__/unresolved-machine-output.test.ts
@@ -206,6 +206,8 @@ describe("unresolved targets in machine formats", () => {
// ...and the body still says what it always said. The exit code becomes
// informative without the payload going away, which is #539's whole point.
if (format === "json") expect(JSON.parse(result.stdout).resolutionMode).toBe("ambiguous");
+ // N-of-M (CL-19B): locate's own json body carries the same total.
+ if (format === "json") expect(JSON.parse(result.stdout).total).toBe(2);
if (format === "llm") expect(result.stdout).toContain("ambiguous_target");
}
});
diff --git a/ix-cli/src/cli/commands/locate.ts b/ix-cli/src/cli/commands/locate.ts
index 044ec607..aef81799 100644
--- a/ix-cli/src/cli/commands/locate.ts
+++ b/ix-cli/src/cli/commands/locate.ts
@@ -4,8 +4,8 @@ import type { Command } from "commander";
import { IxClient } from "../../client/api.js";
import { createClient } from "../../client/factory.js";
import {
- resolveFileOrEntity, resolveEntityFull, printResolved, printAmbiguous,
- looksFileLike, isRawId, type ResolvedEntity,
+ resolveFileOrEntityFull, resolveEntityFull, printResolved, printAmbiguous,
+ looksFileLike, isRawId, qualifiedSeparator, isFuzzyResult, type ResolvedEntity,
} from "../resolve.js";
import { isFileStale } from "../stale.js";
import { stderr } from "../stderr.js";
@@ -14,7 +14,7 @@ import { llmLine, llmError, llmShortId } from "../llm.js";
import { parsePickOption } from "../options.js";
import { getEffectiveSystemPath, hasMapData } from "../hierarchy.js";
import { humanizeLabel } from "../impact/risk-semantics.js";
-import { renderSection, renderKeyValue, renderNote, renderWarning, renderBreadcrumb, reportAmbiguousTarget } from "../ui.js";
+import { renderSection, renderKeyValue, renderNote, renderWarning, renderBreadcrumb, reportAmbiguousTarget, reportResolutionNotices } from "../ui.js";
import { forMcp } from "../next-step.js";
const CONTAINER_KINDS = new Set(["class", "module", "file", "trait", "object", "interface"]);
@@ -194,17 +194,34 @@ async function resolveWithAmbiguity(
opts: { kind?: string; path?: string; pick?: number },
format: string,
): Promise<{ target: ResolvedEntity | null; ambiguous: boolean }> {
- // For raw IDs and file-like targets, delegate to resolveFileOrEntity (no ambiguity)
+ // For raw IDs and file-like targets, delegate to resolveFileOrEntityFull. A
+ // file target can tie, but it resolves (with a notice) rather than turn
+ // ambiguous; one that falls through to a symbol keeps the text report.
if (isRawId(symbol) || looksFileLike(symbol)) {
- const target = await resolveFileOrEntity(client, symbol, opts);
- return { target, ambiguous: false };
+ const fileResult = await resolveFileOrEntityFull(client, symbol, opts);
+ if (fileResult.resolved) {
+ if (fileResult.notices?.length) reportResolutionNotices(fileResult.notices, format, opts);
+ return { target: fileResult.entity, ambiguous: false };
+ }
+ if (fileResult.ambiguous) printAmbiguous(symbol, fileResult.result, opts);
+ return { target: null, ambiguous: false };
}
// Symbol resolution — use full result to detect ambiguity
const allKinds = ["file", "class", "object", "trait", "interface", "module", "function", "method", "constant"];
- const result = await resolveEntityFull(client, symbol, allKinds, { ...opts, format });
+ const sep = qualifiedSeparator(symbol);
+ let result = await resolveEntityFull(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.
+ const missed = !result.resolved && !result.ambiguous;
+ if (sep && (missed || (sep !== "::" && isFuzzyResult(result)))) {
+ result = await resolveFileOrEntityFull(client, symbol, { ...opts, format });
+ }
if (result.resolved) {
+ if (result.notices?.length) reportResolutionNotices(result.notices, format, opts);
return { target: result.entity, ambiguous: false };
}
@@ -214,6 +231,8 @@ async function resolveWithAmbiguity(
resolvedTarget: null,
resolutionMode: "ambiguous",
candidates: result.result.candidates,
+ ...(result.result.total != null ? { total: result.result.total } : {}),
+ ...(result.result.truncated ? { truncated: true } : {}),
systemPath: null,
diagnostics: result.result.diagnostics ?? [],
});
diff --git a/ix-cli/src/cli/commands/read.ts b/ix-cli/src/cli/commands/read.ts
index 9e0d7765..a908eb76 100644
--- a/ix-cli/src/cli/commands/read.ts
+++ b/ix-cli/src/cli/commands/read.ts
@@ -15,7 +15,7 @@ import { relativePath, printJson } from "../format.js";
import { llmError, llmLine, llmShortId, printLlmLines } from "../llm.js";
import { parsePickOption } from "../options.js";
import { disambiguationHint } from "../next-step.js";
-import { reportUnresolvedTarget } from "../ui.js";
+import { reportResolutionNotices, reportUnresolvedTarget } from "../ui.js";
export interface ReadResult {
targetType: "file" | "file-range" | "filename-match" | "symbol";
@@ -679,6 +679,7 @@ async function trySymbolMatch(
const full = await resolveEntityFull(client, symbol, preferredKinds, opts);
if (full.resolved) {
+ if (full.notices?.length) reportResolutionNotices(full.notices, opts.format, opts);
const details = await client.entity(full.entity.id);
const fullNode = details.node as any;
const sourceUri = fullNode.provenance?.source_uri ?? fullNode.provenance?.sourceUri ?? null;
diff --git a/ix-cli/src/cli/commands/trace.ts b/ix-cli/src/cli/commands/trace.ts
index baa2a52f..d2d395ed 100644
--- a/ix-cli/src/cli/commands/trace.ts
+++ b/ix-cli/src/cli/commands/trace.ts
@@ -13,6 +13,7 @@ import {
colorizeKind,
reportResolutionFailure,
reportUnresolvedTarget,
+ reportResolutionNotices,
} from "../ui.js";
import { compactTreeNode, relativePath, printJson } from "../format.js";
import { llmLine, llmShortId, type LlmValue } from "../llm.js";
@@ -542,6 +543,9 @@ export function registerTraceCommand(program: Command): void {
}
const fromTarget = fromResult.entity;
const toTarget = toResult.entity;
+ for (const r of [fromResult, toResult]) {
+ if (r.notices?.length) reportResolutionNotices(r.notices, opts.format, resolveOpts);
+ }
const relKind = opts.kind ?? "mixed";
const predicates = kindToPredicates(opts.kind);
diff --git a/ix-cli/src/cli/format.ts b/ix-cli/src/cli/format.ts
index 8c6d7b7a..57c78324 100644
--- a/ix-cli/src/cli/format.ts
+++ b/ix-cli/src/cli/format.ts
@@ -38,9 +38,53 @@ function jsonIndent(): number | undefined {
return process.stdout.isTTY ? 2 : undefined;
}
+// ── Resolution notices ─────────────────────────────────────────────────────
+
+/**
+ * Notices about a guessed target (`ambiguous_target`, `fuzzy_match`) waiting for
+ * the command's own json object. Per process: `ix mcp` runs every command as a
+ * subprocess, so nothing outlives one command. Tests that call a command
+ * in-process should call `resetResolutionNotices` between cases.
+ */
+let pendingResolutionNotices: unknown[] = [];
+
+/** Queue notices for the next `printJson`. */
+export function noteResolutionNotices(list: readonly unknown[]): void {
+ pendingResolutionNotices.push(...list);
+}
+
+export function takeResolutionNotices(): unknown[] {
+ const taken = pendingResolutionNotices;
+ pendingResolutionNotices = [];
+ return taken;
+}
+
+export function resetResolutionNotices(): void {
+ pendingResolutionNotices = [];
+}
+
+/**
+ * Merge pending notices into a plain object that is not an error record.
+ * Anything else (an array, a scalar, an `{error}`) is printed untouched and the
+ * notices are dropped: an error is its own answer, and the exit code is the same.
+ */
+function withResolutionNotices(value: unknown): unknown {
+ const notices = takeResolutionNotices();
+ if (notices.length === 0) return value;
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return value;
+ const obj = value as Record<string, unknown>;
+ if (typeof obj.error === "string") return value;
+ const fuzzy = notices.some((n) => (n as { code?: string })?.code === "fuzzy_match");
+ return {
+ ...obj,
+ ...(fuzzy && obj.resolutionMode === undefined ? { resolutionMode: "fuzzy" } : {}),
+ resolutionNotices: notices,
+ };
+}
+
/** Print a JSON payload on stdout, indented only when that helps someone. */
export function printJson(value: unknown): void {
- console.log(JSON.stringify(value, null, jsonIndent()));
+ console.log(JSON.stringify(withResolutionNotices(value), null, jsonIndent()));
}
// ── JSON optimization helpers ──────────────────────────────────────────────
diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.ts
index 8055f6e4..9efc02e8 100644
--- a/ix-cli/src/cli/resolve.ts
+++ b/ix-cli/src/cli/resolve.ts
@@ -11,7 +11,7 @@ import { requireReadWorkspaceId, resolveWorkspaceId } from "./bootstrap.js";
import { readStitchScope, resolveWorkspaceRoot, stitchScopeCachePath, writeStitchScope } from "./config.js";
import { ixHome } from "./ix-home.js";
import { checkGraphHealth, isUnhealthy, type GraphHealth } from "./graph-health.js";
-import { reportAmbiguousTarget, reportResolutionFailure } from "./ui.js";
+import { reportAmbiguousTarget, reportResolutionFailure, reportResolutionNotices } from "./ui.js";
import { relativePath } from "./format.js";
import { isQuiet } from "./output-shape.js";
import { disambiguationHint } from "./next-step.js";
@@ -173,7 +173,7 @@ export async function resolveReadSystemId(
return activeReadScope().systemId;
}
-export type ResolutionMode = "exact" | "preferred-kind" | "scored" | "ambiguous" | "heuristic";
+export type ResolutionMode = "exact" | "preferred-kind" | "scored" | "ambiguous" | "heuristic" | "fuzzy";
export interface ResolvedEntity {
id: string;
@@ -185,7 +185,28 @@ export interface ResolvedEntity {
export interface AmbiguousResult {
resolutionMode: "ambiguous";
- candidates: Array<{ id: string; name: string; kind: string; path?: string; score?: number; rank?: number }>;
+ candidates: Array<{ id: string; name: string; kind: string; path?: string; line?: number; score?: number; rank?: number }>;
+ diagnostics?: Array<{ code: string; message: string }>;
+ /** How many candidates tied (the candidate list shows at most 8 of them). */
+ total?: number;
+ /** True when the search window came back full, so `total` is a lower bound. */
+ truncated?: boolean;
+}
+
+/**
+ * A resolved target that was a guess worth reporting. The result still resolves
+ * (exit 0); the notice says which candidates were passed over, or that the
+ * match was fuzzy. It is never an `error`, so plugin runners see no failure.
+ */
+export interface ResolutionNotice {
+ code: "ambiguous_target" | "fuzzy_match";
+ target: string;
+ message: string;
+ chosen: { id: string; name: string; kind: string; path?: string };
+ candidates: AmbiguousResult["candidates"];
+ total: number;
+ truncated?: boolean;
+ /** Extra diagnostics, e.g. `pick_out_of_range`. */
diagnostics?: Array<{ code: string; message: string }>;
}
@@ -225,7 +246,7 @@ export interface Suggestion {
}
export type ResolveResult =
- | { resolved: true; entity: ResolvedEntity; hiddenTestCount?: number }
+ | { resolved: true; entity: ResolvedEntity; hiddenTestCount?: number; notices?: ResolutionNotice[] }
| { resolved: false; ambiguous: true; result: AmbiguousResult; hiddenTestCount?: number }
| {
resolved: false;
@@ -422,7 +443,10 @@ export async function resolveEntity(
opts?: ResolveOpts
): Promise<ResolvedEntity | null> {
const result = await resolveEntityFull(client, symbol, preferredKinds, opts);
- if (result.resolved) return result.entity;
+ if (result.resolved) {
+ if (result.notices?.length) reportResolutionNotices(result.notices, "text", opts);
+ return result.entity;
+ }
if (result.ambiguous) {
reportAmbiguousTarget(symbol, result.result, "text", opts);
}
@@ -457,6 +481,7 @@ export async function resolveEntityFull(
workspaceId,
systemId,
});
+ const windowFull = nodes.length >= searchLimit;
// The backend orders its window by weight — every exact name before every
// partial one — so when a name is imported in dozens of files, the window is
@@ -527,22 +552,52 @@ export async function resolveEntityFull(
return name === symbolLower || isFileStemMatch(n, symbol);
});
+ // Finish a pick: --pick selects among an ambiguous result's candidates, or
+ // among the candidates a resolved result's notice passed over.
+ const finish = (winner: ResolveResult): ResolveResult => {
+ const picked = applyPick(winner, opts);
+ if (picked) return { ...picked, hiddenTestCount } as ResolveResult;
+ return { ...pickFromNotice(winner, opts), hiddenTestCount } as ResolveResult;
+ };
+ const pickOpts = { ...opts, path: effectivePath, windowFull };
+
// Score exact-name candidates
if (exactName.length > 0) {
- const winner = pickBest(exactName, symbol, preferredKinds, { ...opts, path: effectivePath });
- if (winner) {
- const picked = applyPick(winner, opts);
- if (picked) return { ...picked, hiddenTestCount } as ResolveResult;
- return { ...winner, hiddenTestCount } as ResolveResult;
- }
+ const winner = pickBest(exactName, symbol, preferredKinds, pickOpts);
+ if (winner) return finish(winner);
}
// ── Phase 2: Fall back to all candidates ────────────────────────────
- const winner = pickBest(filteredNodes, symbol, preferredKinds, { ...opts, path: effectivePath });
+ // No candidate carries the name, so whatever wins is a fuzzy match: it
+ // resolves (exit 0 as before) but is labelled, and the notice says so.
+ const winner = pickBest(filteredNodes, symbol, preferredKinds, pickOpts);
if (winner) {
- const picked = applyPick(winner, opts);
- if (picked) return { ...picked, hiddenTestCount } as ResolveResult;
- return { ...winner, hiddenTestCount } as ResolveResult;
+ if (winner.resolved) {
+ const e = winner.entity;
+ return finish({
+ ...winner,
+ entity: { ...e, resolutionMode: "fuzzy" },
+ notices: [fuzzyNotice(symbol, e), ...(winner.notices ?? [])],
+ });
+ }
+ if (winner.ambiguous) {
+ winner.result.diagnostics = [
+ ...(winner.result.diagnostics ?? []),
+ { code: "fuzzy_match", message: `No exact match for ${symbol}; these are fuzzy matches.` },
+ ];
+ // --pick among fuzzy candidates is still a fuzzy match: keep the label.
+ const picked = applyPick(winner, opts);
+ if (picked?.resolved) {
+ const e = picked.entity;
+ return {
+ ...picked,
+ entity: { ...e, resolutionMode: "fuzzy" },
+ notices: [fuzzyNotice(symbol, e)],
+ hiddenTestCount,
+ };
+ }
+ }
+ return finish(winner);
}
// Nothing resolved at all
@@ -576,6 +631,75 @@ export function mergeById<T extends { id?: unknown }>(base: T[], extra: T[]): T[
return [...base, ...extra.filter((n) => !seen.has(n.id))];
}
+/** Start line of a node, for a stable candidate order. Missing sorts last. */
+function lineOf(node: any): number {
+ const v = Number(node?.attrs?.line_start ?? node?.attrs?.lineStart ?? node?.line_start);
+ return Number.isFinite(v) ? v : Number.MAX_SAFE_INTEGER;
+}
+
+function nodePath(node: any): string {
+ return normalizeForPathMatch(node?.provenance?.sourceUri ?? node?.provenance?.source_uri ?? node?.path ?? "");
+}
+
+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. */
+function displayOrder(a: any, b: any): number {
+ return cmpStr(nodePath(a), nodePath(b)) || lineOf(a) - lineOf(b) || cmpStr(String(a.id), String(b.id));
+}
+
+function entityPath(node: any): string | undefined {
+ return node.provenance?.sourceUri ?? node.provenance?.source_uri ?? node.path;
+}
+
+/** The one-line notice for a target resolved by a fuzzy (non-exact) name. */
+function fuzzyNotice(symbol: string, e: ResolvedEntity): ResolutionNotice {
+ const where = e.path ? ` (${e.path})` : "";
+ return {
+ code: "fuzzy_match",
+ target: symbol,
+ message: `No exact match for ${symbol}; using fuzzy match ${e.name}${where}`,
+ chosen: { id: e.id, name: e.name, kind: e.kind, path: e.path },
+ candidates: [{ id: e.id, name: e.name, kind: e.kind, path: e.path, rank: 1 }],
+ total: 1,
+ };
+}
+
+/**
+ * The notice for a pick among equal candidates: resolved, but say what else
+ * tied. `tier` is only the candidates at the chosen one's score (the true
+ * ties); `lowerCount` is how many more scored close but worse. Those are only
+ * counted in the message, so `total`, the listed candidates and `--pick n` all
+ * describe the same set.
+ */
+function tieNotice(
+ symbol: string,
+ chosen: any,
+ tier: Array<{ node: any; score: number }>,
+ windowFull: boolean | undefined,
+ lowerCount = 0,
+): ResolutionNotice {
+ const amb = buildAmbiguous(tier.map((s) => s.node), tier.map((s) => s.score), {
+ total: tier.length,
+ truncated: windowFull,
+ });
+ const where = entityPath(chosen);
+ const lower = lowerCount > 0
+ ? ` ${lowerCount} more scored lower and ${lowerCount === 1 ? "is" : "are"} not listed.`
+ : "";
+ return {
+ code: "ambiguous_target",
+ target: symbol,
+ message: `"${symbol}" matches ${windowFull ? "at least " : ""}${tier.length} candidates equally; using ${chosen.name || symbol}${where ? ` (${where})` : ""}.${lower}`,
+ chosen: { id: chosen.id, name: chosen.name || chosen.attrs?.name || symbol, kind: chosen.kind ?? "", path: where },
+ candidates: amb.candidates,
+ total: tier.length,
+ ...(windowFull ? { truncated: true } : {}),
+ };
+}
+
/**
* Given a candidate set, score them, dedup, and either pick a winner or declare ambiguity.
*/
@@ -583,7 +707,7 @@ function pickBest(
candidates: any[],
symbol: string,
preferredKinds: string[],
- opts?: { kind?: string; path?: string }
+ opts?: { kind?: string; path?: string; windowFull?: boolean }
): ResolveResult | null {
// Score all candidates
const scored = candidates.map(n => ({
@@ -591,15 +715,15 @@ function pickBest(
score: scoreCandidate(n, symbol, opts),
}));
- // Sort by score ascending (lower = better)
+ const kindRank = (n: any) => {
+ const idx = preferredKinds.indexOf(n.kind);
+ return idx >= 0 ? idx : preferredKinds.length;
+ };
+ // Sort by score ascending (lower = better); ties by preferred kind, then by
+ // (path, line, id) so the pick never depends on the order the backend sent.
scored.sort((a, b) => {
if (a.score !== b.score) return a.score - b.score;
- // Tie-break: prefer preferred kinds in order
- const aIdx = preferredKinds.indexOf(a.node.kind);
- const bIdx = preferredKinds.indexOf(b.node.kind);
- const aRank = aIdx >= 0 ? aIdx : preferredKinds.length;
- const bRank = bIdx >= 0 ? bIdx : preferredKinds.length;
- return aRank - bRank;
+ return kindRank(a.node) - kindRank(b.node) || displayOrder(a.node, b.node);
});
// Dedup by id
@@ -618,12 +742,12 @@ function pickBest(
// Single candidate — clear winner
if (unique.length === 1) {
- return { resolved: true, entity: nodeToResolved(best.node, symbol, resolutionMode(best, opts)) };
+ return { resolved: true, entity: nodeToResolved(best.node, symbol, resolutionMode(best, symbol)) };
}
// Best is significantly better than second (score gap >= 3) — winner
if (second && best.score + 3 <= second.score) {
- return { resolved: true, entity: nodeToResolved(best.node, symbol, resolutionMode(best, opts)) };
+ return { resolved: true, entity: nodeToResolved(best.node, symbol, resolutionMode(best, symbol)) };
}
// Check if all top candidates at the same score tier are the same entity
@@ -631,9 +755,19 @@ function pickBest(
const topTier = unique.filter(s => s.score === topScore);
const topIds = new Set(topTier.map(s => s.node.id));
if (topIds.size === 1) {
- return { resolved: true, entity: nodeToResolved(best.node, symbol, resolutionMode(best, opts)) };
+ return { resolved: true, entity: nodeToResolved(best.node, symbol, resolutionMode(best, symbol)) };
}
+ // Candidates within range of the top score: the ambiguous record's list.
+ const eligible = unique.filter(s => s.score <= topScore + 5);
+ // A tie rule's notice lists only the true ties (the top score tier); the
+ // near-misses below it are counted, not presented as equal.
+ const tied = (mode: ResolutionMode): ResolveResult => ({
+ resolved: true,
+ entity: nodeToResolved(best.node, symbol, mode),
+ notices: [tieNotice(symbol, best.node, topTier, opts?.windowFull, eligible.length - topTier.length)],
+ });
+
// If the best candidate ranks strictly higher in the kind preference list than all
// other top-tier candidates, auto-pick it — the preference list is the tiebreaker.
const topTierKindRanks = topTier.map(s => {
@@ -642,14 +776,14 @@ function pickBest(
});
const bestKindRank = topTierKindRanks[0];
if (topTier.length > 1 && topTierKindRanks.every((r, i) => i === 0 || r > bestKindRank)) {
- return { resolved: true, entity: nodeToResolved(best.node, symbol, "preferred-kind") };
+ return tied("preferred-kind");
}
// If best is a container kind and second is a method/function, prefer the container
const bestKind = (best.node.kind || "").toLowerCase();
const secondKind = (second.node.kind || "").toLowerCase();
if (CONTAINER_KINDS.has(bestKind) && !CONTAINER_KINDS.has(secondKind)) {
- return { resolved: true, entity: nodeToResolved(best.node, symbol, "scored") };
+ return tied("scored");
}
// If path was provided and best matches path but second doesn't, best wins
@@ -663,14 +797,13 @@ function pickBest(
}
// Genuinely ambiguous — return only structurally relevant candidates
- const ambiguousCandidates = unique
- .filter(s => s.score <= topScore + 5) // only candidates within range
- .slice(0, 8);
-
return {
resolved: false,
ambiguous: true,
- result: buildAmbiguous(ambiguousCandidates.map(s => s.node), ambiguousCandidates.map(s => s.score)),
+ result: buildAmbiguous(eligible.map(s => s.node), eligible.map(s => s.score), {
+ total: eligible.length,
+ truncated: opts?.windowFull,
+ }),
};
}
@@ -717,9 +850,58 @@ export function applyPick(
};
}
-function resolutionMode(scored: { score: number }, opts?: { kind?: string }): ResolutionMode {
- if (opts?.kind) return "exact";
- if (scored.score <= 0) return "exact";
+/**
+ * `--pick n` on a resolved result that carries an ambiguous_target notice picks
+ * among the notice's candidates. Unlike applyPick on an ambiguous result, an
+ * out-of-range pick keeps the default choice and the exit code stays 0: --pick
+ * must not create a new non-zero exit.
+ */
+export function pickFromNotice(
+ result: ResolveResult,
+ opts?: { pick?: number },
+): ResolveResult {
+ if (opts?.pick == null || !result.resolved || !result.notices) return result;
+ const at = result.notices.findIndex((n) => n.code === "ambiguous_target");
+ if (at < 0) return result;
+ const notice = result.notices[at];
+ const idx = opts.pick - 1;
+ if (idx < 0 || idx >= notice.candidates.length) {
+ const message = `--pick ${opts.pick} is out of range (1-${notice.candidates.length}).`;
+ stderr(message);
+ const notices = result.notices.slice();
+ notices[at] = { ...notice, diagnostics: [{ code: "pick_out_of_range", message }, ...(notice.diagnostics ?? [])] };
+ return { ...result, notices };
+ }
+ const picked = notice.candidates[idx];
+ const keepFuzzy = result.entity.resolutionMode === "fuzzy";
+ return {
+ ...result,
+ entity: {
+ id: picked.id,
+ kind: picked.kind,
+ name: picked.name,
+ path: picked.path,
+ resolutionMode: keepFuzzy ? "fuzzy" : "scored",
+ },
+ notices: result.notices
+ .filter((_, i) => i !== at)
+ .map((n) => {
+ if (n.code !== "fuzzy_match") return n;
+ const where = picked.path ? ` (${picked.path})` : "";
+ return {
+ ...n,
+ message: `No exact match for ${n.target}; using fuzzy match ${picked.name}${where}`,
+ chosen: { id: picked.id, name: picked.name, kind: picked.kind, path: picked.path },
+ candidates: [{ ...picked, rank: 1 }],
+ };
+ }),
+ };
+}
+
+/** "exact" only for a case-sensitive exact name; otherwise the score bands. */
+function resolutionMode(scored: { node: any; score: number }, symbol: string): ResolutionMode {
+ const name = scored.node?.name || scored.node?.attrs?.name || "";
+ if (scored.score <= 0 && name === symbol) return "exact";
if (scored.score <= 5) return "preferred-kind";
return "scored";
}
@@ -736,28 +918,44 @@ function nodeToResolved(node: any, symbol: string, mode: ResolutionMode): Resolv
};
}
-function buildAmbiguous(nodes: any[], scores?: number[]): AmbiguousResult {
+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.
const seen = new Set<string>();
- const candidates: AmbiguousResult["candidates"] = [];
- let rank = 0;
- for (let i = 0; i < nodes.length && i < 8; i++) {
+ const picked: Array<{ node: any; score?: number }> = [];
+ for (let i = 0; i < nodes.length && picked.length < 8; i++) {
const node = nodes[i] as any;
if (seen.has(node.id)) continue;
seen.add(node.id);
- rank++;
- candidates.push({
+ picked.push({ node, score: scores?.[i] });
+ }
+ picked.sort((a, b) => displayOrder(a.node, b.node));
+ const candidates: AmbiguousResult["candidates"] = picked.map(({ node, score }, i) => {
+ const line = lineOf(node);
+ const rank = i + 1;
+ return {
id: node.id,
name: node.name || node.attrs?.name || "(unnamed)",
kind: node.kind ?? "",
- path: node.provenance?.sourceUri ?? node.provenance?.source_uri ?? node.path,
- score: scores?.[i],
+ path: entityPath(node),
+ ...(line !== Number.MAX_SAFE_INTEGER ? { line } : {}),
+ score,
rank,
- });
- }
+ };
+ });
return {
resolutionMode: "ambiguous",
candidates,
- diagnostics: [{ code: "ambiguous_resolution", message: disambiguationHint("Use --pick <n> or --path to disambiguate.") }],
+ ...(extra?.total != null ? { total: extra.total } : {}),
+ ...(extra?.truncated ? { truncated: true } : {}),
+ diagnostics: [
+ { code: "ambiguous_resolution", message: disambiguationHint("Use --pick <n> or --path to disambiguate.") },
+ ...(extra?.diagnostics ?? []),
+ ],
};
}
@@ -801,18 +999,33 @@ function camelToSnake(s: string): string {
}
/**
- * Parse a scoped symbol like "ClassName::methodName" (C++/Rust/PHP style).
- * Returns the class and method parts, or null if no `::` is present.
- * Uses the *last* `::` so that nested scopes like `ns::Class::method` resolve
- * to `{ className: "ns::Class", methodName: "method" }`.
+ * Parse a scoped symbol like "ClassName::methodName" (C++/Rust/PHP style), or
+ * the `Class.method` / `Class#method` spellings (JS, Java, Python docs).
+ * Splits on the *last* separator so nested scopes like `ns::Class::method`
+ * resolve to `{ className: "ns::Class", methodName: "method" }`. `.` and `#`
+ * need identifier parts on both sides and a target that is not a file name.
*/
-function parseScopedSymbol(symbol: string): { className: string; methodName: string } | null {
+function parseScopedSymbol(symbol: string): { className: string; methodName: string; sep: "::" | "." | "#" } | null {
const idx = symbol.lastIndexOf('::');
- if (idx < 1) return null;
- const className = symbol.slice(0, idx);
- const methodName = symbol.slice(idx + 2);
- if (!className || !methodName) return null;
- return { className, methodName };
+ if (idx >= 1) {
+ const className = symbol.slice(0, idx);
+ const methodName = symbol.slice(idx + 2);
+ if (className && methodName) return { className, methodName, sep: "::" };
+ return null;
+ }
+ if (looksFileLike(symbol)) return null;
+ const at = Math.max(symbol.lastIndexOf('#'), symbol.lastIndexOf('.'));
+ if (at < 1) return null;
+ const className = symbol.slice(0, at);
+ const methodName = symbol.slice(at + 1);
+ if (!/^[A-Za-z_$][\w$]*$/.test(methodName)) return null;
+ if (!/^[A-Za-z_$][\w$]*([.#][A-Za-z_$][\w$]*)*$/.test(className)) return null;
+ return { className, methodName, sep: symbol[at] as "." | "#" };
+}
+
+/** The separator when `target` is `Class::method`, `Class.method` or `Class#method`, else null. */
+export function qualifiedSeparator(target: string): "::" | "." | "#" | null {
+ return parseScopedSymbol(target)?.sep ?? null;
}
// ── File-first resolution ─────────────────────────────────────────────────
@@ -890,60 +1103,16 @@ export async function resolveFileOrEntityFull(
// 2. File-like input → try graph file search
if (looksFileLike(target)) {
- const fileEntity = await tryFileGraphMatch(client, target, opts);
- if (fileEntity) return { resolved: true, entity: fileEntity };
+ const fileResult = await tryFileGraphMatch(client, target, opts);
+ if (fileResult) return fileResult;
// Fall through to symbol resolution
}
// 2.5 Scoped symbol (e.g. "CompactionJob::Run", "ns::Class::method")
const scoped = parseScopedSymbol(target);
- if (scoped) {
- // Phase A: resolve the class entity to obtain its actual source file path.
- // This gives a precise path hint rather than a guess from snake_case conversion.
- // We suppress stderr during this lookup to avoid confusing "not found" noise.
- const shortClassName = scoped.className.split('::').pop()!;
- const classEntity = await resolveEntity(
- client,
- shortClassName,
- ['class', 'interface', 'struct', 'trait', 'object', 'function'],
- { ...opts, kind: opts?.kind ? undefined : undefined }, // no kind constraint for class lookup
- );
-
- // Determine the best path hint: prefer the actual file path from phase A,
- // fall back to snake_case conversion of the class name.
- let pathHint: string;
- if (classEntity?.path) {
- // Extract basename without extension (e.g. "/db/flush_job.h" → "flush_job")
- const basename = classEntity.path.replace(/\\/g, '/').split('/').pop() ?? '';
- pathHint = basename.replace(/\.[^.]+$/, '').toLowerCase();
- } else {
- // Fallback: CamelCase → snake_case (e.g. "CompactionJob" → "compaction_job")
- pathHint = camelToSnake(shortClassName);
- }
-
- // Phase B: find the method, boosting candidates in the class's source file.
- // Use pathHint (derived from the class entity's actual source file) as the
- // path constraint — it is always more specific than the user's broad --path
- // workspace filter (e.g. "rocksdb"), so it takes priority.
- // Use a higher search limit so that methods in the correct file are not
- // pushed out by unrelated Run/Execute methods in other classes.
- // We deliberately do NOT force kind=method because some parsers classify
- // class methods as kind "function".
- const scopedOpts = {
- ...opts,
- path: pathHint, // always use the class-derived hint, not opts?.path
- searchLimit: 50,
- };
- const result = await resolveEntityFull(client, scoped.methodName, ['method', 'function'], scopedOpts);
- if (result.resolved) {
- // Rewrite the display name to show the full scoped form
- return {
- ...result,
- entity: { ...result.entity, name: `${scoped.className}::${scoped.methodName}` },
- };
- }
- // Not found — return null (don't fall through to a literal "Foo::Bar" search)
- return result;
+ if (scoped?.sep === "::") {
+ // Not found is returned as is (no fall-through to a literal "Foo::Bar" search).
+ return (await resolveQualified(client, scoped, opts, false))!;
}
// 3. Symbol resolution (handles all entity kinds)
@@ -953,6 +1122,24 @@ export async function resolveFileOrEntityFull(
// module-level constant is not ranked behind every config entry and heading
// that happens to share its name (Ix#679).
const allKinds = ["file", "class", "object", "trait", "interface", "module", "method", "function", "constant"];
+ if (scoped) {
+ // `Class.method` / `Class#method`: a name stored with a dot (`os.path`)
+ // resolves literally, so the qualified reading is tried only when the
+ // literal lookup finds nothing, and only if the class itself is found.
+ // 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 });
+ if ((literal.resolved || literal.ambiguous) && !isFuzzyResult(literal)) return literal;
+ const qualified = await resolveQualified(client, scoped, opts, true);
+ if (qualified?.resolved) return qualified;
+ if (literal.resolved || literal.ambiguous) return literal;
+ if (qualified?.ambiguous) return qualified;
+ missProse(opts, opts?.path
+ ? `No entity named "${target}" found in paths matching "${opts.path}".`
+ : `No entity found matching "${target}".`);
+ return literal;
+ }
if (!looksFileLike(target)) return resolveEntityFull(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
@@ -962,6 +1149,202 @@ export async function resolveFileOrEntityFull(
return fileMiss(client, target, opts);
}
+/**
+ * Resolve `Class<sep>method`. For `::` (requireClass false): find the class for
+ * its source file, then the method boosted toward that file, as before. With
+ * `requireClass` (the `.`/`#` spellings) the method must be contained by the
+ * class (its CONTAINS children, else the class's exact source file); a class
+ * that is not found, found only by a fuzzy match, or holding no such member
+ * gives null, so a miss never becomes an unlabelled guess.
+ */
+async function resolveQualified(
+ client: IxClient,
+ scoped: { className: string; methodName: string; sep: "::" | "." | "#" },
+ opts: ResolveOpts | undefined,
+ requireClass: boolean,
+): Promise<ResolveResult | null> {
+ // Phase A: resolve the class entity to obtain its actual source file path.
+ // 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(
+ client,
+ shortClassName,
+ ['class', 'interface', 'struct', 'trait', 'object', 'function'],
+ // No kind constraint for the class lookup. For `.`/`#`, --pick selects the
+ // method, not the class, so it is not spent on the class lookup.
+ { ...opts, kind: undefined, silentMiss: true, ...(requireClass ? { pick: undefined } : {}) },
+ );
+ // For `.`/`#` the class must exist by name: a fuzzy class (`User` matching
+ // `UserService`) would turn a miss into a confident wrong answer.
+ if (requireClass) {
+ if (isFuzzyResult(classResult)) return null;
+ // The method must live IN the class. A class name held by several classes
+ // (ambiguous, or resolved by a tie rule) is still a class that exists: the
+ // method is looked for in each of them rather than reported as a miss.
+ if (classResult.resolved) {
+ const tie = classResult.notices?.find((n) => n.code === "ambiguous_target");
+ const e = classResult.entity;
+ const classes = tie ? tie.candidates : [{ id: e.id, name: e.name, kind: e.kind, path: e.path }];
+ return resolveInClasses(client, scoped, classes, !!tie?.truncated || (tie ? tie.total > tie.candidates.length : false), opts);
+ }
+ if (classResult.ambiguous) {
+ const classes = classResult.result;
+ return resolveInClasses(client, scoped, classes.candidates,
+ !!classes.truncated || (classes.total ?? 0) > classes.candidates.length, opts);
+ }
+ return null;
+ }
+ const classEntity = classResult.resolved ? classResult.entity : null;
+
+ // Determine the best path hint: prefer the actual file path from phase A,
+ // fall back to snake_case conversion of the class name.
+ let pathHint: string;
+ if (classEntity?.path) {
+ // Extract basename without extension (e.g. "/db/flush_job.h" → "flush_job")
+ const basename = classEntity.path.replace(/\\/g, '/').split('/').pop() ?? '';
+ pathHint = basename.replace(/\.[^.]+$/, '').toLowerCase();
+ } else {
+ // Fallback: CamelCase → snake_case (e.g. "CompactionJob" → "compaction_job")
+ pathHint = camelToSnake(shortClassName);
+ }
+
+ // Phase B: find the method, boosting candidates in the class's source file.
+ // Use pathHint (derived from the class entity's actual source file) as the
+ // path constraint — it is always more specific than the user's broad --path
+ // workspace filter (e.g. "rocksdb"), so it takes priority.
+ // Use a higher search limit so that methods in the correct file are not
+ // pushed out by unrelated Run/Execute methods in other classes.
+ // We deliberately do NOT force kind=method because some parsers classify
+ // class methods as kind "function".
+ const scopedOpts = {
+ ...opts,
+ path: pathHint, // always use the class-derived hint, not opts?.path
+ searchLimit: 50,
+ };
+ const result = await resolveEntityFull(client, scoped.methodName, ['method', 'function'], scopedOpts);
+ if (result.resolved) {
+ // Rewrite the display name to show the full scoped form, as the user typed it
+ return {
+ ...result,
+ entity: { ...result.entity, name: `${scoped.className}${scoped.sep}${scoped.methodName}` },
+ };
+ }
+ return result;
+}
+
+/** A result that came from resolveEntityFull's fuzzy phase (no exact name). */
+export function isFuzzyResult(r: ResolveResult): boolean {
+ if (r.resolved) {
+ return r.entity.resolutionMode === "fuzzy" || !!r.notices?.some((n) => n.code === "fuzzy_match");
+ }
+ return r.ambiguous && !!r.result.diagnostics?.some((d) => d.code === "fuzzy_match");
+}
+
+type Candidate = AmbiguousResult["candidates"][number];
+
+function candidateOf(n: any): Candidate {
+ const line = lineOf(n);
+ return {
+ id: String(n.id),
+ name: n.name || n.attrs?.name || "",
+ kind: n.kind ?? "",
+ path: entityPath(n),
+ ...(line !== Number.MAX_SAFE_INTEGER ? { line } : {}),
+ };
+}
+
+/**
+ * The members of `cls` named exactly `memberName`. Containment comes from the
+ * graph: the class's CONTAINS children. Only when the graph has no CONTAINS
+ * children for the class (or cannot be asked) does it fall back to the same
+ * source file, compared exactly, never as a substring: `a/config.ts` is not
+ * `xa/config.ts`.
+ */
+async function membersOf(
+ client: IxClient,
+ cls: { id: string; path?: string },
+ memberName: string,
+): Promise<{ found: Candidate[]; truncated: boolean }> {
+ const named = (n: any) => n && String(n.id) !== cls.id && (n.name || n.attrs?.name) === memberName;
+ let children: any[] | null;
+ try {
+ const expanded = await client.expand(cls.id, { direction: "out", predicates: ["CONTAINS"] });
+ children = Array.isArray(expanded?.nodes) ? expanded.nodes.filter((n: any) => String(n?.id) !== cls.id) : null;
+ } catch {
+ children = null;
+ }
+ if (children && children.length > 0) {
+ return { found: children.filter(named).map(candidateOf), truncated: false };
+ }
+ if (!cls.path) return { found: [], truncated: false };
+ const classFile = normalizeForPathMatch(cls.path);
+ const { workspaceId, systemId } = activeScope();
+ const limit = 50;
+ const nodes = await client.search(memberName, { limit, nameOnly: true, workspaceId, systemId, scope: cls.path });
+ const found = nodes
+ .filter((n: any) => named(n) && nodePath(n) === classFile)
+ .map(candidateOf);
+ return { found, truncated: nodes.length >= limit };
+}
+
+/**
+ * `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,
+ * which the caller reports as the miss.
+ */
+async function resolveInClasses(
+ client: IxClient,
+ scoped: { className: string; methodName: string; sep: "::" | "." | "#" },
+ classes: Candidate[],
+ classesTruncated: boolean,
+ opts: ResolveOpts | undefined,
+): Promise<ResolveResult | null> {
+ // Only the listed classes are searched; when more classes tied, the method
+ // list is a lower bound and is marked truncated.
+ let truncated = classesTruncated;
+ const found = new Map<string, Candidate>();
+ const seenClasses = new Set<string>();
+ for (const cls of classes) {
+ if (seenClasses.has(cls.id)) continue;
+ seenClasses.add(cls.id);
+ const r = await membersOf(client, cls, scoped.methodName);
+ if (r.truncated) truncated = true;
+ for (const c of r.found) if (!found.has(c.id)) found.set(c.id, c);
+ }
+ if (found.size === 0) return null;
+ const display = `${scoped.className}${scoped.sep}${scoped.methodName}`;
+ const ordered = [...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));
+ if (ordered.length === 1) {
+ const only = ordered[0];
+ return {
+ resolved: true,
+ entity: { id: only.id, kind: only.kind, name: display, path: only.path, resolutionMode: "scored" },
+ };
+ }
+ const ambiguous: ResolveResult = {
+ resolved: false,
+ ambiguous: true,
+ result: {
+ resolutionMode: "ambiguous",
+ candidates: ordered.slice(0, 8).map((c, i) => ({ ...c, rank: i + 1 })),
+ total: ordered.length,
+ ...(truncated ? { truncated: true } : {}),
+ diagnostics: [
+ { code: "ambiguous_resolution", message: disambiguationHint("Use --pick <n> or --path to disambiguate.") },
+ ],
+ },
+ };
+ const picked = applyPick(ambiguous, opts);
+ if (picked?.resolved) return { ...picked, entity: { ...picked.entity, name: display } };
+ return picked ?? ambiguous;
+}
+
/**
* The miss for a file target: on disk but not in the graph, or on neither,
* with the graph's nearest file names as suggestions.
@@ -1032,7 +1415,11 @@ export async function nearestNames(
.filter((n: any) => n?.id && n.kind !== "chunk")
.map((n: any) => ({ n, d: editDistance(nameOf(n), symbol) }))
.filter(({ d }) => d <= maxDistance)
- .sort((a, b) => a.d - b.d || Number(!STRUCTURAL_KINDS.has(a.n.kind)) - Number(!STRUCTURAL_KINDS.has(b.n.kind)));
+ .sort((a, b) => a.d - b.d
+ || Number(!STRUCTURAL_KINDS.has(a.n.kind)) - Number(!STRUCTURAL_KINDS.has(b.n.kind))
+ || cmpStr(String(nameOf(a.n)), String(nameOf(b.n)))
+ || cmpStr(nodePath(a.n), nodePath(b.n))
+ || cmpStr(String(a.n.id), String(b.n.id)));
// One row per name and file: an import of the name in the same file adds nothing.
const seen = new Set<string>();
const unique = ranked.map(({ n }) => n).filter((n: any) => {
@@ -1053,7 +1440,10 @@ export async function resolveFileOrEntity(
opts?: ResolveOpts,
): Promise<ResolvedEntity | null> {
const result = await resolveFileOrEntityFull(client, target, opts);
- if (result.resolved) return result.entity;
+ if (result.resolved) {
+ if (result.notices?.length) reportResolutionNotices(result.notices, "text", opts);
+ return result.entity;
+ }
if (result.ambiguous) reportAmbiguousTarget(target, result.result, "text", opts);
return null;
}
@@ -1068,7 +1458,10 @@ export async function resolveFileOrReport(
// prose, or whether the structured record below is the only copy that should
// reach stdout.
const result = await resolveFileOrEntityFull(client, target, { ...opts, format });
- if (result.resolved) return result.entity;
+ if (result.resolved) {
+ if (result.notices?.length) reportResolutionNotices(result.notices, format, opts);
+ return result.entity;
+ }
if (!result.ambiguous) {
// A miss on an empty or hollowed graph is not evidence the name does not
// exist. Only on this path, and cached per backend revision.
@@ -1084,13 +1477,25 @@ export async function resolveFileOrReport(
/**
* Search the graph for a file entity matching the target path or filename.
- * Tries exact path match first, then basename match.
+ *
+ * Tiers, best first:
+ * quality: 0 the full path: equal to the uri, relative to the cwd, or an
+ * absolute path ending in it (the longest uri wins); or a
+ * filename inside --path
+ * quality: 1 a path suffix on a '/' boundary (`src/index.ts` in `pkg/src/index.ts`)
+ * quality: 2 a suffix not on a boundary (`li/config.ts`): kept so a path
+ * that names one file is not sent to the file miss
+ * quality: 3 the exact filename
+ * quality: 4 the filename without its extension
+ * Within a tier, the shortest uri, then uri, then id. It never returns
+ * ambiguous (a file target never newly exits 1): equal candidates resolve to
+ * the first and carry an ambiguous_target notice listing the rest.
*/
async function tryFileGraphMatch(
client: IxClient,
target: string,
- opts?: { path?: string },
-): Promise<ResolvedEntity | null> {
+ opts?: { path?: string; pick?: number },
+): Promise<ResolveResult | null> {
const basename = path.basename(target);
const targetHasPath = target.includes("/") || target.includes("\\");
// Explicit --path only (not the absolute workspace root); scope server-side instead.
@@ -1099,8 +1504,9 @@ async function tryFileGraphMatch(
const { workspaceId, systemId } = activeScope();
// Search for file entities matching the basename
+ const limit = effectivePath ? 200 : 50;
const nodes = await client.search(basename, {
- limit: effectivePath ? 200 : 50,
+ limit,
kind: "file",
nameOnly: true,
workspaceId,
@@ -1113,29 +1519,43 @@ async function tryFileGraphMatch(
const basenameLower = basename.toLowerCase();
const basenameNoExt = basename.replace(/\.[^.]+$/, "").toLowerCase();
const normalizedPathHint = normalizeForPathMatch(effectivePath);
+ const isAbsolute = path.isAbsolute(target) || /^[a-z]:\//.test(targetLower);
+ let fromCwd = "";
+ if (targetHasPath && !isAbsolute) {
+ try { fromCwd = normalizeForPathMatch(path.relative(resolveWorkspaceRoot(), path.resolve(process.cwd(), target))); }
+ catch { fromCwd = ""; }
+ }
- const matches: Array<{ node: any; quality: number }> = [];
+ const matches: Array<{ node: any; quality: number; uri: string }> = [];
for (const n of nodes as any[]) {
const name = (n.name || "").toLowerCase();
const uri = normalizeForPathMatch(n.provenance?.sourceUri ?? n.provenance?.source_uri ?? "");
+ const add = (quality: number) => { matches.push({ node: n, quality, uri }); };
- // Exact path match (best): covers both absolute URIs matching absolute target,
- // and relative URIs that are a suffix of an absolute target path.
- if (targetHasPath && (uri.endsWith(targetLower) || uri === targetLower
- || (uri.includes("/") && targetLower.endsWith(uri)))) {
- matches.push({ node: n, quality: 0 });
+ if (targetHasPath && (uri === targetLower || (fromCwd && uri === fromCwd))) {
+ add(0);
+ } else if (targetHasPath && isAbsolute && uri.includes("/") && targetLower.endsWith("/" + uri)) {
+ add(0);
}
// Filename match in user-requested path
else if (normalizedPathHint && uri.includes(normalizedPathHint) && name === basenameLower) {
- matches.push({ node: n, quality: 0 });
+ add(0);
+ }
+ // Suffix on a '/' boundary
+ else if (targetHasPath && uri.endsWith("/" + targetLower)) {
+ add(1);
+ }
+ // Suffix that is not on a boundary
+ else if (targetHasPath && (uri.endsWith(targetLower) || (uri.includes("/") && targetLower.endsWith(uri)))) {
+ add(2);
}
// Exact filename match
else if (name === basenameLower) {
- matches.push({ node: n, quality: 1 });
+ add(3);
}
// Bare name match (no extension)
else if (name.replace(/\.[^.]+$/, "") === basenameNoExt) {
- matches.push({ node: n, quality: 2 });
+ add(4);
}
}
@@ -1144,30 +1564,43 @@ async function tryFileGraphMatch(
// elsewhere is a different file: `docs-site/package.json` resolved to the
// repo-root `package.json` and was answered about with full confidence. The
// miss is reported instead, with that file among its suggestions.
- if (targetHasPath && !effectivePath && !matches.some((m) => m.quality === 0)) return null;
+ if (targetHasPath && !effectivePath && !matches.some((m) => m.quality <= 2)) return null;
- // Sort by quality then by URI length ascending (shorter = closer to root = more prominent)
+ // Quality, then the shortest uri (closer to the root = more prominent; for an
+ // absolute path the longest, the deepest file it ends in), then uri, then id.
matches.sort((a, b) => {
if (a.quality !== b.quality) return a.quality - b.quality;
- const uriA = normalizeForPathMatch(a.node.provenance?.sourceUri ?? a.node.provenance?.source_uri ?? "");
- const uriB = normalizeForPathMatch(b.node.provenance?.sourceUri ?? b.node.provenance?.source_uri ?? "");
- return uriA.length - uriB.length;
+ const byLength = isAbsolute && a.quality === 0 ? b.uri.length - a.uri.length : a.uri.length - b.uri.length;
+ return byLength || cmpStr(a.uri, b.uri) || cmpStr(String(a.node.id), String(b.node.id));
});
- // If multiple matches at same quality, prefer path-matching target
const best = matches[0];
- if (matches.length > 1 && matches[0].quality === matches[1].quality && (target.includes("/") || target.includes("\\") || !!normalizedPathHint)) {
- // Disambiguate by path when user provided a path
- const pathMatch = matches.find(m => {
- const uri = normalizeForPathMatch(m.node.provenance?.sourceUri ?? m.node.provenance?.source_uri ?? "");
- return uri.endsWith(targetLower) || uri === targetLower
- || (uri.includes("/") && targetLower.endsWith(uri))
- || (!!normalizedPathHint && uri.includes(normalizedPathHint));
- });
- if (pathMatch) {
- return nodeToResolved(pathMatch.node, pathMatch.node.name, "exact");
- }
+ // The candidates that tie with the best: same tier (and, for an absolute
+ // path, the same file).
+ const tied: typeof matches = [];
+ const seenIds = new Set<string>();
+ for (const m of matches) {
+ if (m.quality !== best.quality) break;
+ if (isAbsolute && best.quality === 0 && m.uri !== best.uri) continue;
+ if (seenIds.has(m.node.id)) continue;
+ seenIds.add(m.node.id);
+ tied.push(m);
}
-
- return nodeToResolved(best.node, best.node.name || basename, best.quality === 0 ? "exact" : "scored");
+ const entityOf = (m: typeof best, mode: ResolutionMode) => nodeToResolved(m.node, m.node.name || basename, mode);
+ if (tied.length <= 1) {
+ return { resolved: true, entity: entityOf(best, best.quality === 0 ? "exact" : "scored") };
+ }
+ const truncated = nodes.length >= limit;
+ const amb = buildAmbiguous(tied.map((m) => m.node), undefined, { total: tied.length, truncated });
+ const chosen = entityOf(best, "scored");
+ const notice: ResolutionNotice = {
+ code: "ambiguous_target",
+ target,
+ message: `"${target}" matches ${truncated ? "at least " : ""}${tied.length} files equally; using ${chosen.path ?? chosen.name}.`,
+ chosen: { id: chosen.id, name: chosen.name, kind: chosen.kind, path: chosen.path },
+ candidates: amb.candidates,
+ total: tied.length,
+ ...(truncated ? { truncated: true } : {}),
+ };
+ return pickFromNotice({ resolved: true, entity: chosen, notices: [notice] }, opts);
}
diff --git a/ix-cli/src/cli/ui.ts b/ix-cli/src/cli/ui.ts
index 7a248501..5c6d1390 100644
--- a/ix-cli/src/cli/ui.ts
+++ b/ix-cli/src/cli/ui.ts
@@ -10,9 +10,9 @@
import chalk from "chalk";
import { llmError, llmLine } from "./llm.js";
-import { printJson, relativePath } from "./format.js";
+import { noteResolutionNotices, printJson, relativePath } from "./format.js";
import { isQuiet } from "./output-shape.js";
-import type { AmbiguousResult, ResolveResult, Suggestion } from "./resolve.js";
+import type { AmbiguousResult, ResolutionNotice, ResolveResult, Suggestion } from "./resolve.js";
import { forMcp } from "./next-step.js";
import { graphHealthJson, graphHealthLlmFields, graphHealthProse, type GraphHealth } from "./graph-health.js";
@@ -252,6 +252,8 @@ export function reportAmbiguousTarget(
error: "ambiguous_target",
message,
candidates: result.candidates,
+ ...(result.total != null ? { total: result.total } : {}),
+ ...(result.truncated ? { truncated: true } : {}),
diagnostics: result.diagnostics ?? [],
});
return;
@@ -263,7 +265,11 @@ export function reportAmbiguousTarget(
if (!opts?.kind) hints.push(mcp ? "kind=<kind>" : "--kind");
if (!opts?.path) hints.push(mcp ? "path=<file substring>" : "--path");
const lines = [
- llmError("ambiguous_target", message, [["count", String(result.candidates.length)]]),
+ llmError("ambiguous_target", message, [
+ ["count", String(result.candidates.length)],
+ ...(result.total != null ? [["shown", String(result.candidates.length)], ["total", String(result.total)]] as Array<[string, string]> : []),
+ ...(result.truncated ? [["truncated", "true"]] as Array<[string, string]> : []),
+ ]),
...candidateLines(result.candidates, "candidate"),
llmLine("hint", [["text", `${mcp ? "Pass" : "Use"} ${hints.join(" or ")} to disambiguate.`]]),
...(result.diagnostics ?? []).map((d) => llmLine("diagnostic", [["code", d.code], ["message", d.message]])),
@@ -273,6 +279,9 @@ export function reportAmbiguousTarget(
}
console.error(`Ambiguous symbol "${target}":`);
+ if (result.total != null && (result.truncated || result.total > result.candidates.length)) {
+ console.error(chalk.dim(` Showing ${result.candidates.length} of ${result.truncated ? ">=" : ""}${result.total}`));
+ }
for (let index = 0; index < result.candidates.length; index += 1) {
const candidate = result.candidates[index];
const shortPath = candidate.path ? ` in ${candidate.path}` : "";
@@ -286,6 +295,74 @@ export function reportAmbiguousTarget(
console.error(chalk.dim(`\nUse ${hints.join(" or ")} to disambiguate.`));
}
+/**
+ * Report what a resolver guessed, for a target that DID resolve (exit 0).
+ *
+ * llm: `diagnostic` records on stdout before the command's own output, never
+ * `error code=` (plugin runners treat that as a failure). json: queued for
+ * `printJson`, which merges them into the command's object as
+ * `resolutionNotices`. text: a line on stderr.
+ */
+export function reportResolutionNotices(
+ notices: readonly ResolutionNotice[],
+ format?: string,
+ opts?: { kind?: string; path?: string },
+): void {
+ if (notices.length === 0) return;
+ if (format === "json") {
+ noteResolutionNotices(notices);
+ return;
+ }
+ if (format === "llm") {
+ const mcp = forMcp();
+ const lines: string[] = [];
+ for (const notice of notices) {
+ if (notice.code === "fuzzy_match") {
+ lines.push(llmLine("diagnostic", [
+ ["code", "fuzzy_match"],
+ ["resolution", "fuzzy"],
+ ["target", notice.target],
+ ["chosen", notice.chosen.name],
+ ["message", notice.message],
+ ]));
+ continue;
+ }
+ lines.push(llmLine("diagnostic", [
+ ["code", "ambiguous_target"],
+ ["target", notice.target],
+ ["chosen", notice.chosen.name],
+ ["shown", String(notice.candidates.length)],
+ ["total", String(notice.total)],
+ ...(notice.truncated ? [["truncated", "true"]] as Array<[string, string]> : []),
+ ["message", notice.message],
+ ]));
+ lines.push(...candidateLines(notice.candidates, "candidate"));
+ for (const d of notice.diagnostics ?? []) {
+ lines.push(llmLine("diagnostic", [["code", d.code], ["message", d.message]]));
+ }
+ const hints = [mcp ? "pick=<n>" : "--pick <n>"];
+ if (!opts?.path) hints.push(mcp ? "path=<file substring>" : "--path");
+ lines.push(llmLine("hint", [["text", `${mcp ? "Pass" : "Use"} ${hints.join(" or ")} to choose another.`]]));
+ }
+ console.log(lines.join("\n"));
+ return;
+ }
+ if (isQuiet()) return;
+ for (const notice of notices) {
+ console.error(chalk.dim(notice.message));
+ if (notice.code !== "ambiguous_target") continue;
+ for (let index = 0; index < notice.candidates.length; index += 1) {
+ const candidate = notice.candidates[index];
+ const where = candidate.path ? ` in ${candidate.path}` : "";
+ console.error(chalk.dim(` ${index + 1}. ${(candidate.kind ?? "").padEnd(10)} ${candidate.id.slice(0, 8)} ${candidate.name}${where}`));
+ }
+ if (notice.total > notice.candidates.length || notice.truncated) {
+ console.error(chalk.dim(` Showing ${notice.candidates.length} of ${notice.truncated ? ">=" : ""}${notice.total}`));
+ }
+ console.error(chalk.dim(` Use --pick <n>${opts?.path ? "" : " or --path"} to choose another.`));
+ }
+}
+
export function reportResolutionFailure(
target: string,
result: Exclude<ResolveResult, { resolved: true }>,
diff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.md
index e2f27d31..433c604d 100644
--- a/skills/ix/references/flags.md
+++ b/skills/ix/references/flags.md
@@ -111,7 +111,10 @@ surfaces (#575).
the caller's order, not the renderer's. It never touches a header, and a field
no row carries is dropped rather than emitted empty.
- **`--pick <n>` is 1-based** everywhere it appears, and is how you resolve an
- ambiguous target without re-running with a longer name.
+ ambiguous 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
+ resolution notice (a target that resolved by choosing among equal matches;
+ only the true ties are listed and numbered).
- **`--no-recursive` and `--no-open` negate a default-on behaviour**, so their
Default of `on` is the positive behaviour, and passing the flag turns it off.