Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
fix(cli): make an ambiguous target pickable from one call (#685)
Ian Hock7c476abc89f6
diff --git a/ix-cli/src/cli/__tests__/ambiguity-and-suggestions.test.ts b/ix-cli/src/cli/__tests__/ambiguity-and-suggestions.test.tsnew file mode 100644index 00000000..4b0e168d--- /dev/null+++ b/ix-cli/src/cli/__tests__/ambiguity-and-suggestions.test.ts@@ -0,0 +1,176 @@+// Copyright 2026 Ix Infrastructure Inc.++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { Command } from "commander";++const search = vi.hoisted(() => vi.fn());++vi.mock("../../client/api.js", () => ({+ IxClient: class {+ async workspaceSystem() { return { systemId: null }; }+ async search(...args: unknown[]) { return search(...args); }+ },+}));++vi.mock("../config.js", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../config.js")>();+ return {+ ...actual,+ readStitchScope: () => undefined,+ writeStitchScope: vi.fn(),+ };+});++const node = (id: string, name: string, kind: string, uri: string) => ({+ id, name, kind, provenance: { sourceUri: uri },+});++async function run(args: string[]): Promise<{ stdout: string; stderr: string }> {+ const { registerOverviewCommand } = await import("../commands/overview.js");+ const program = new Command();+ program.name("ix").exitOverride();+ registerOverviewCommand(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);+ try {+ await program.parseAsync(args, { from: "user" });+ } finally {+ log.mockRestore();+ error.mockRestore();+ write.mockRestore();+ }+ return { stdout: stdout.join("\n"), stderr: stderr.join("\n") };+}++describe("an ambiguous target in llm format", () => {+ let savedExitCode: number | string | undefined;++ beforeEach(() => {+ savedExitCode = process.exitCode;+ process.exitCode = undefined;+ search.mockReset().mockResolvedValue([+ node("1111aaaa-0000-0000-0000-000000000000", "Duplicate", "function", "src/first.ts"),+ node("2222bbbb-0000-0000-0000-000000000000", "Duplicate", "function", "src/second.ts"),+ ]);+ });++ afterEach(() => { process.exitCode = savedExitCode; });++ it("names each candidate well enough to pick one", async () => {+ const { stdout } = await run(["overview", "Duplicate", "--format", "llm"]);+ const lines = stdout.split("\n");++ // Previously the whole answer was+ // `candidates=1:Duplicate,2:Duplicate` — three entries differing in nothing.+ expect(lines[0]).toContain("error code=ambiguous_target");+ expect(lines[0]).toContain("count=2");+ expect(lines[1]).toBe("candidate n=1 name=Duplicate kind=function path=src/first.ts id=1111aaaa");+ expect(lines[2]).toBe("candidate n=2 name=Duplicate kind=function path=src/second.ts id=2222bbbb");+ expect(lines[3]).toContain("hint");+ expect(lines[3]).toContain("--pick <n>");+ });++ it("carries the full id in json, where size is not the constraint", async () => {+ const { stdout } = await run(["overview", "Duplicate", "--format", "json"]);+ expect(JSON.parse(stdout).candidates[0].id).toBe("1111aaaa-0000-0000-0000-000000000000");+ });++ 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+ // the resolver not to break the tie.+ const { reportAmbiguousTarget } = await import("../ui.js");+ const candidates = [+ { id: "1111aaaa-0000-0000-0000-000000000000", name: "Duplicate", kind: "function", path: "src/first.ts" },+ { id: "2222bbbb-0000-0000-0000-000000000000", name: "Duplicate", kind: "function", path: "src/second.ts" },+ ];+ const lines: string[] = [];+ const log = vi.spyOn(console, "log").mockImplementation((...parts) => lines.push(parts.join(" ")));+ try {+ reportAmbiguousTarget("Duplicate", { resolutionMode: "ambiguous", candidates }, "llm", { kind: "function", path: "src" });+ } finally {+ log.mockRestore();+ }+ const hint = lines.join("\n").split("\n").find((line) => line.startsWith("hint"))!;+ expect(hint).toContain("--pick <n>");+ expect(hint).not.toContain("--kind");+ expect(hint).not.toContain("--path");+ });+});++describe("a target that resolves to nothing", () => {+ let savedExitCode: number | string | undefined;++ beforeEach(() => {+ savedExitCode = process.exitCode;+ process.exitCode = undefined;+ search.mockReset();+ });++ afterEach(() => { process.exitCode = savedExitCode; });++ /** The name exists — `--path` is what excluded it. */+ const elsewhere = () => {+ search.mockResolvedValue([+ node("5555eeee-0000-0000-0000-000000000000", "Widget", "class", "src/ui/widget.ts"),+ node("6666ffff-0000-0000-0000-000000000000", "Widget", "function", "src/ui/factory.ts"),+ ]);+ };++ it("says where the symbol does live, in llm", async () => {+ elsewhere();+ const { stdout } = await run(["overview", "Widget", "--path", "server", "--format", "llm"]);+ const lines = stdout.split("\n");++ expect(lines[0]).toContain("error code=unresolved_target");+ expect(lines[1]).toBe("suggestion n=1 name=Widget kind=class path=src/ui/widget.ts id=5555eeee");+ expect(lines[2]).toBe("suggestion n=2 name=Widget kind=function path=src/ui/factory.ts id=6666ffff");+ expect(lines[3]).toContain("hint");+ });++ it("says it in json too", async () => {+ elsewhere();+ const { stdout } = await run(["overview", "Widget", "--path", "server", "--format", "json"]);+ const payload = JSON.parse(stdout);+ expect(payload.error).toBe("unresolved_target");+ expect(payload.suggestions).toHaveLength(2);+ expect(payload.suggestions[0]).toMatchObject({ name: "Widget", kind: "class", path: "src/ui/widget.ts" });+ });++ it("says the miss once, not once per stream", async () => {+ elsewhere();+ // An agent runs `ix ... 2>&1`. The record on stdout is the answer; the+ // prose on stderr was a second copy of it.+ const { stdout, stderr } = await run(["overview", "Widget", "--path", "server", "--format", "llm"]);+ expect(stdout).toContain("unresolved_target");+ expect(stderr).not.toContain("No entity named");+ });++ it("still tells a person, in text", async () => {+ elsewhere();+ const { stdout, stderr } = await run(["overview", "Widget", "--path", "server"]);+ expect(stdout).toBe("");+ expect(stderr).toContain('No entity named "Widget" found in paths matching "server".');+ expect(stderr).toContain("Did you mean:");+ expect(stderr).toContain("src/ui/widget.ts");+ });++ it("adds nothing when the name matched nothing at all", async () => {+ // A miss here means the search came back empty, so there is nothing to+ // suggest — and re-running it without `nameOnly` returns the same empty+ // set, which is why nothing tries.+ search.mockResolvedValue([]);+ const { stdout } = await run(["overview", "NothingLikeThis", "--format", "json"]);+ expect(JSON.parse(stdout)).toEqual({+ error: "unresolved_target",+ message: 'No entity found matching "NothingLikeThis".',+ });+ expect(search).toHaveBeenCalledTimes(1);+ });+});diff --git a/ix-cli/src/cli/commands/locate.ts b/ix-cli/src/cli/commands/locate.tsindex ebc1c27c..4af448c1 100644--- a/ix-cli/src/cli/commands/locate.ts+++ b/ix-cli/src/cli/commands/locate.ts@@ -14,7 +14,7 @@ import { llmLine, llmError } 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 } from "../ui.js";+import { renderSection, renderKeyValue, renderNote, renderWarning, renderBreadcrumb, reportAmbiguousTarget } from "../ui.js";const CONTAINER_KINDS = new Set(["class", "module", "file", "trait", "object", "interface"]);const FILE_KINDS = new Set(["file"]);@@ -201,7 +201,7 @@ async function resolveWithAmbiguity(// Symbol resolution — use full result to detect ambiguityconst allKinds = ["file", "class", "object", "trait", "interface", "module", "function", "method"];- const result = await resolveEntityFull(client, symbol, allKinds, opts);+ const result = await resolveEntityFull(client, symbol, allKinds, { ...opts, format });if (result.resolved) {return { target: result.entity, ambiguous: false };@@ -217,9 +217,10 @@ async function resolveWithAmbiguity(diagnostics: result.result.diagnostics ?? [],}, null, 2));} else if (format === "llm") {- console.log(llmError("ambiguous_target", `Ambiguous symbol "${symbol}".`, [- ["candidates", result.result.candidates.map((c, i) => `${i + 1}:${c.name}`).join(",")],- ]));+ // The shared renderer: one record per candidate with kind, path and a+ // short id. This used to emit `candidates=1:config.ts,2:config.ts` --+ // nothing to choose between.+ reportAmbiguousTarget(symbol, result.result, "llm", opts);} else {printAmbiguous(symbol, result.result, opts);}diff --git a/ix-cli/src/cli/commands/read.ts b/ix-cli/src/cli/commands/read.tsindex 9097fe65..66df9571 100644--- a/ix-cli/src/cli/commands/read.ts+++ b/ix-cli/src/cli/commands/read.ts@@ -284,7 +284,7 @@ Examples:}// --- Step 4: Try unique symbol match ---- const symbolResult = await trySymbolMatch(client, rawTarget, { kind: opts.kind, path: opts.path, pick: opts.pick });+ const symbolResult = await trySymbolMatch(client, rawTarget, { kind: opts.kind, path: opts.path, pick: opts.pick, format: opts.format });if (symbolResult.type === "resolved") {const { node, sourceUri } = symbolResult;// sourceUri coming from the graph is workspace-relative under the@@ -533,7 +533,7 @@ type SymbolResult =async function trySymbolMatch(client: IxClient,symbol: string,- opts: { kind?: string; path?: string; pick?: number }+ opts: { kind?: string; path?: string; pick?: number; format?: string }): Promise<SymbolResult> {const preferredKinds = ["file", "class", "object", "trait", "interface", "module", "function", "method"];const full = await resolveEntityFull(client, symbol, preferredKinds, opts);diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.tsindex ed6a4592..694d7323 100644--- a/ix-cli/src/cli/resolve.ts+++ b/ix-cli/src/cli/resolve.ts@@ -9,6 +9,7 @@ import { detectSystem } from "./system.js";import { resolveWorkspaceId } from "./bootstrap.js";import { readStitchScope, writeStitchScope } from "./config.js";import { reportAmbiguousTarget, reportResolutionFailure } from "./ui.js";+import { relativePath } from "./format.js";/*** The read scope for the current working directory: a co-ingested multi-repo system@@ -108,10 +109,43 @@ export interface AmbiguousResult {diagnostics?: Array<{ code: string; message: string }>;}+/**+ * A near-miss worth naming when a target does not resolve.+ *+ * A miss is a dead end for the caller: an agent that gets "no entity found"+ * spends its next turn running `ix search` by hand, and a person retypes the+ * name. The candidates are already in hand (or one search away), so they are+ * cheaper to hand over than to make the caller ask for.+ */+/**+ * What a resolver needs from its caller.+ *+ * `format` is here so a miss is reported once. The prose ("No entity found+ * matching …") goes to stderr for a person; a json or llm caller gets the same+ * fact as a record on stdout from `reportUnresolvedTarget`, and printing both+ * means an agent running `ix … 2>&1` reads the miss twice.+ */+export interface ResolveOpts {+ kind?: string;+ path?: string;+ pick?: number;+ includeTests?: boolean;+ testsOnly?: boolean;+ searchLimit?: number;+ format?: string;+}++export interface Suggestion {+ id: string;+ name: string;+ kind: string;+ path?: string;+}+export type ResolveResult =| { resolved: true; entity: ResolvedEntity; hiddenTestCount?: number }| { resolved: false; ambiguous: true; result: AmbiguousResult; hiddenTestCount?: number }- | { resolved: false; ambiguous: false; hiddenTestCount?: number };+ | { resolved: false; ambiguous: false; hiddenTestCount?: number; suggestions?: Suggestion[] };// ── Structural kind sets ──────────────────────────────────────────────────@@ -123,6 +157,39 @@ const STRUCTURAL_KINDS = new Set([...CONTAINER_KINDS, "function", "method",]);+/**+ * Report a miss to a person, once.+ *+ * Under `--format json|llm` the reporter writes a machine-readable record for+ * the same miss on stdout, and an agent almost always runs with `2>&1`, so this+ * prose would be a second copy of an answer it already has.+ */+function missProse(opts: ResolveOpts | undefined, message: string): void {+ const format = opts?.format;+ if (format === "json" || format === "llm") return;+ stderr(message);+}++/** The best few near-misses to offer, newest scoring first, deduped by id. */+function toSuggestions(nodes: any[], limit = 3): Suggestion[] {+ const seen = new Set<string>();+ const out: Suggestion[] = [];+ for (const n of nodes) {+ const id = String(n.id ?? "");+ if (!id || seen.has(id)) continue;+ seen.add(id);+ const uri = n.provenance?.sourceUri ?? n.provenance?.source_uri;+ out.push({+ id,+ name: String(n.name ?? n.attrs?.name ?? ""),+ kind: String(n.kind ?? ""),+ path: uri ? (relativePath(uri) ?? uri) : undefined,+ });+ if (out.length >= limit) break;+ }+ return out;+}+function looksTypeLikeSymbol(symbol: string): boolean {return /^[A-Z][A-Za-z0-9_]*$/.test(symbol);}@@ -212,7 +279,7 @@ export async function resolveEntity(client: IxClient,symbol: string,preferredKinds: string[],- opts?: { kind?: string; path?: string; pick?: number; includeTests?: boolean; testsOnly?: boolean; searchLimit?: number }+ opts?: ResolveOpts): Promise<ResolvedEntity | null> {const result = await resolveEntityFull(client, symbol, preferredKinds, opts);if (result.resolved) return result.entity;@@ -233,7 +300,7 @@ export async function resolveEntityFull(client: IxClient,symbol: string,preferredKinds: string[],- opts?: { kind?: string; path?: string; pick?: number; includeTests?: boolean; testsOnly?: boolean; searchLimit?: number }+ 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@@ -251,7 +318,10 @@ export async function resolveEntityFull(});if (nodes.length === 0) {- stderr(`No entity found matching "${symbol}".`);+ // Nothing to suggest: the search matched no name, and re-running it without+ // `nameOnly` returns the same empty set (measured against a 1.4M-node graph+ // on three terms), so a second call would only cost a round trip.+ missProse(opts, `No entity found matching "${symbol}".`);return { resolved: false, ambiguous: false };}@@ -269,8 +339,11 @@ export async function resolveEntityFull(: roleFiltered;if (effectivePath && filteredNodes.length === 0) {- stderr(`No entity named "${symbol}" found in paths matching "${effectivePath}".`);- return { resolved: false, ambiguous: false, hiddenTestCount };+ missProse(opts, `No entity named "${symbol}" found in paths matching "${effectivePath}".`);+ // The name exists — just not under --path. Saying where it does live is the+ // whole answer to the question the filter was asking.+ const suggestions = toSuggestions(roleFiltered);+ return { resolved: false, ambiguous: false, hiddenTestCount, ...(suggestions.length ? { suggestions } : {}) };}// ── Phase 1: Exact-name candidates ──────────────────────────────────@@ -308,8 +381,9 @@ export async function resolveEntityFull(}// Nothing resolved at all- stderr(`No entity found matching "${symbol}".`);- return { resolved: false, ambiguous: false, hiddenTestCount };+ missProse(opts, `No entity found matching "${symbol}".`);+ const suggestions = toSuggestions(filteredNodes);+ return { resolved: false, ambiguous: false, hiddenTestCount, ...(suggestions.length ? { suggestions } : {}) };}/**@@ -579,7 +653,7 @@ export function looksFileLike(target: string): boolean {export async function resolveFileOrEntityFull(client: IxClient,target: string,- opts?: { kind?: string; path?: string; pick?: number; includeTests?: boolean; testsOnly?: boolean }+ opts?: ResolveOpts): Promise<ResolveResult> {// 1. Raw UUIDif (isRawId(target)) {@@ -596,7 +670,7 @@ export async function resolveFileOrEntityFull(},};} catch {- stderr(`Entity not found: ${target}`);+ missProse(opts, `Entity not found: ${target}`);return { resolved: false, ambiguous: false };}}@@ -687,7 +761,7 @@ export async function resolveFileOrEntityFull(export async function resolveFileOrEntity(client: IxClient,target: string,- opts?: { kind?: string; path?: string; pick?: number; includeTests?: boolean; testsOnly?: boolean },+ opts?: ResolveOpts,): Promise<ResolvedEntity | null> {const result = await resolveFileOrEntityFull(client, target, opts);if (result.resolved) return result.entity;@@ -698,10 +772,13 @@ export async function resolveFileOrEntity(export async function resolveFileOrReport(client: IxClient,target: string,- opts: { kind?: string; path?: string; pick?: number; includeTests?: boolean; testsOnly?: boolean } | undefined,+ opts: ResolveOpts | undefined,format: string,): Promise<ResolvedEntity | null> {- const result = await resolveFileOrEntityFull(client, target, opts);+ // The format goes in so the resolver knows whether a person will read its+ // 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;reportResolutionFailure(target, result, format, opts);return null;diff --git a/ix-cli/src/cli/ui.ts b/ix-cli/src/cli/ui.tsindex eb59d7c7..39b0dde6 100644--- a/ix-cli/src/cli/ui.ts+++ b/ix-cli/src/cli/ui.ts@@ -9,8 +9,9 @@import chalk from "chalk";-import { llmError } from "./llm.js";-import type { AmbiguousResult, ResolveResult } from "./resolve.js";+import { llmError, llmLine } from "./llm.js";+import { relativePath } from "./format.js";+import type { AmbiguousResult, ResolveResult, Suggestion } from "./resolve.js";// ── Brand palette ─────────────────────────────────────────────────────────────//@@ -160,16 +161,58 @@ export function unresolvedTargetRecord(target: string | string[]): { error: stri};}-export function reportUnresolvedTarget(target: string | string[], format?: string): void {+export function reportUnresolvedTarget(+ target: string | string[],+ format?: string,+ suggestions?: Suggestion[],+): void {const message = unresolvedTargetMessage(target);+ const near = suggestions ?? [];if (format === "json") {- console.log(JSON.stringify(unresolvedTargetRecord(target), null, 2));+ console.log(JSON.stringify({+ ...unresolvedTargetRecord(target),+ ...(near.length ? { suggestions: near } : {}),+ }, null, 2));} else if (format === "llm") {- console.log(llmError("unresolved_target", message));+ const lines = [llmError("unresolved_target", message), ...candidateLines(near, "suggestion")];+ if (near.length) {+ lines.push(llmLine("hint", [["text", "Re-run with one of these names, or narrow with --path."]]));+ }+ console.log(lines.join("\n"));+ } else if (near.length) {+ // The resolver already wrote the miss itself for a person; this adds the+ // part that makes it actionable.+ console.error(chalk.dim("Did you mean:"));+ for (const s of near) {+ console.error(` ${chalk.cyan((s.kind || "").padEnd(10))} ${s.name}${s.path ? chalk.dim(` in ${s.path}`) : ""}`);+ }}process.exitCode = 1;}+/**+ * Candidate records for the llm format.+ *+ * `read` has emitted name, kind, path and id per candidate since its own+ * renderer landed; everything else emitted `candidates=1:config.ts,2:config.ts,+ * 3:config.ts` -- three entries that differ in nothing an agent can choose by,+ * 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 }>,+ record: "candidate" | "suggestion",+): string[] {+ return candidates.map((candidate, index) => llmLine(record, [+ ["n", String(index + 1)],+ ["name", candidate.name],+ ["kind", candidate.kind],+ ["path", candidate.path ? relativePath(candidate.path) ?? candidate.path : undefined],+ // 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],+ ]));+}+export function reportAmbiguousTarget(target: string,result: AmbiguousResult,@@ -187,9 +230,16 @@ export function reportAmbiguousTarget(return;}if (format === "llm") {- console.log(llmError("ambiguous_target", message, [- ["candidates", result.candidates.map((candidate, index) => `${index + 1}:${candidate.name}`).join(",")],- ]));+ const hints = ["--pick <n>"];+ if (!opts?.kind) hints.push("--kind");+ if (!opts?.path) hints.push("--path");+ const lines = [+ llmError("ambiguous_target", message, [["count", String(result.candidates.length)]]),+ ...candidateLines(result.candidates, "candidate"),+ llmLine("hint", [["text", `Use ${hints.join(" or ")} to disambiguate.`]]),+ ...(result.diagnostics ?? []).map((d) => llmLine("diagnostic", [["code", d.code], ["message", d.message]])),+ ];+ console.log(lines.join("\n"));return;}@@ -214,6 +264,6 @@ export function reportResolutionFailure(opts?: { kind?: string; path?: string },): void {if (result.ambiguous) reportAmbiguousTarget(target, result.result, format, opts);- else reportUnresolvedTarget(target, format);+ else reportUnresolvedTarget(target, format, result.suggestions);process.exitCode = 1;}