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): fail unresolved graph commands (#547)

Hiro-Chibadf30296eb6a8
diff --git a/docs/llm-format.md b/docs/llm-format.md
index 99bf1bb5..37c2453b 100644
--- a/docs/llm-format.md
+++ b/docs/llm-format.md
@@ -25,11 +25,15 @@ so consumers can pass the flag unconditionally without a per-command lookup.
backslash-escaped and newline / carriage-return / tab are encoded as `\n` /
`\r` / `\t`, so a record never spans more than one line.
- **Errors:** a uniform `error code=<slug> message="..."` line in the same
- format as data lines; the process still exits non-zero. A target that does
- not exist is always `unresolved_target`, whichever command was asked —
- `context`, `explain`, `read`, `locate`, `subsystems`, `trace`. (The backend
- spells the same condition `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.)
+ format as data lines; the process still exits non-zero. A graph target that
+ does not exist is always `unresolved_target`. `locate` is the remaining
+ exit-status exception tracked in #539.
+ 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
+ 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.)
## Hierarchies
diff --git a/ix-cli/src/cli/__tests__/context-pick-validation.test.ts b/ix-cli/src/cli/__tests__/context-pick-validation.test.ts
index a748a463..c2411d7e 100644
--- a/ix-cli/src/cli/__tests__/context-pick-validation.test.ts
+++ b/ix-cli/src/cli/__tests__/context-pick-validation.test.ts
@@ -1,11 +1,11 @@
import { Command, type CommanderError } from "commander";
import { beforeEach, describe, expect, it, vi } from "vitest";
-const resolveFileOrEntity = vi.hoisted(() => vi.fn());
+const resolveFileOrReport = vi.hoisted(() => vi.fn());
vi.mock("../resolve.js", async (importOriginal) => ({
...(await importOriginal<typeof import("../resolve.js")>()),
- resolveFileOrEntity,
+ resolveFileOrReport,
}));
import { parseContextDepthOption, registerContextCommand } from "../commands/context.js";
@@ -28,7 +28,7 @@ async function runContext(args: string[]): Promise<{ error?: CommanderError; std
describe("ix context --pick validation", () => {
beforeEach(() => {
- resolveFileOrEntity.mockReset().mockResolvedValue(undefined);
+ resolveFileOrReport.mockReset().mockResolvedValue(undefined);
});
it.each(["nope", "1nope"])("rejects the complete value %j before resolving", async (pick) => {
@@ -38,7 +38,7 @@ describe("ix context --pick validation", () => {
expect(result.stderr).toContain("argument '" + pick + "' is invalid");
expect(result.stderr).toContain("must be a positive integer");
expect(result.stderr).not.toContain("TypeError");
- expect(resolveFileOrEntity).not.toHaveBeenCalled();
+ expect(resolveFileOrReport).not.toHaveBeenCalled();
});
it.each([
@@ -55,8 +55,8 @@ describe("ix context --pick validation", () => {
]);
expect(result.error).toBeUndefined();
- expect(resolveFileOrEntity).toHaveBeenCalledOnce();
- expect(resolveFileOrEntity.mock.calls[0]?.[2]).toEqual({
+ expect(resolveFileOrReport).toHaveBeenCalledOnce();
+ expect(resolveFileOrReport.mock.calls[0]?.[2]).toEqual({
kind: "function",
path: "src/main.ts",
pick: expectedPick,
@@ -75,7 +75,7 @@ describe("ix context --pick validation", () => {
*/
describe("ix context --max-* validation", () => {
beforeEach(() => {
- resolveFileOrEntity.mockReset().mockResolvedValue(undefined);
+ resolveFileOrReport.mockReset().mockResolvedValue(undefined);
});
it.each(["10abc", "0x10", "1e3", "-5", "0", "3.5", "", " "])(
@@ -85,7 +85,7 @@ describe("ix context --max-* validation", () => {
expect(result.error?.exitCode).toBe(1);
expect(result.stderr).toContain("must be a positive integer");
- expect(resolveFileOrEntity).not.toHaveBeenCalled();
+ expect(resolveFileOrReport).not.toHaveBeenCalled();
},
);
@@ -133,14 +133,14 @@ describe("ix context --max-* validation", () => {
*/
describe("ix context --as-of-rev validation", () => {
beforeEach(() => {
- resolveFileOrEntity.mockReset().mockResolvedValue(undefined);
+ resolveFileOrReport.mockReset().mockResolvedValue(undefined);
});
it.each(["abc", "3.9", "10abc", "-1", "0"])("rejects %j rather than sending it", async (value) => {
const result = await runContext(["--as-of-rev", value]);
expect(result.error?.exitCode).toBe(1);
expect(result.stderr).toContain("must be a positive integer");
- expect(resolveFileOrEntity).not.toHaveBeenCalled();
+ expect(resolveFileOrReport).not.toHaveBeenCalled();
});
it("accepts a revision", async () => {
@@ -150,14 +150,14 @@ describe("ix context --as-of-rev validation", () => {
describe("ix context --depth validation", () => {
beforeEach(() => {
- resolveFileOrEntity.mockReset().mockResolvedValue(undefined);
+ resolveFileOrReport.mockReset().mockResolvedValue(undefined);
});
it.each(["compact", "standard", "full", "shallow", "deep", "FULL"])("accepts depth %j", async (depth) => {
const result = await runContext(["--depth", depth]);
expect(result.error).toBeUndefined();
- expect(resolveFileOrEntity).toHaveBeenCalledOnce();
+ expect(resolveFileOrReport).toHaveBeenCalledOnce();
});
it.each([
@@ -195,7 +195,7 @@ describe("ix context --depth validation", () => {
const result = await runContext(["--depth", depth]);
expect(result.error).toBeUndefined();
- expect(resolveFileOrEntity).toHaveBeenCalledOnce();
+ expect(resolveFileOrReport).toHaveBeenCalledOnce();
} finally {
warn.mockRestore();
}
@@ -217,7 +217,7 @@ describe("ix context --depth validation", () => {
describe("ix context refusals reach the caller that asked for records", () => {
beforeEach(() => {
- resolveFileOrEntity.mockReset().mockResolvedValue(undefined);
+ resolveFileOrReport.mockReset().mockResolvedValue(undefined);
});
it("answers a missing target with a record and a non-zero status", async () => {
diff --git a/ix-cli/src/cli/__tests__/depends-semantics.test.ts b/ix-cli/src/cli/__tests__/depends-semantics.test.ts
index 65a8a617..ac764e88 100644
--- a/ix-cli/src/cli/__tests__/depends-semantics.test.ts
+++ b/ix-cli/src/cli/__tests__/depends-semantics.test.ts
@@ -125,8 +125,8 @@ describe("depends input validation", () => {
expect(dependsContent).toContain('"--format <fmt>"');
});
- it("uses resolveFileOrEntity with resolveOpts", () => {
- expect(dependsContent).toContain("resolveFileOrEntity(client, symbol, resolveOpts)");
+ it("uses resolveFileOrReport with resolveOpts", () => {
+ expect(dependsContent).toContain("resolveFileOrReport(client, symbol, resolveOpts, opts.format)");
});
it("traverses edges in reverse via predicate map", () => {
diff --git a/ix-cli/src/cli/__tests__/diff-content.test.ts b/ix-cli/src/cli/__tests__/diff-content.test.ts
index 75f52e18..db0a786f 100644
--- a/ix-cli/src/cli/__tests__/diff-content.test.ts
+++ b/ix-cli/src/cli/__tests__/diff-content.test.ts
@@ -198,8 +198,8 @@ describe("diff.ts resolver flags", () => {
expect(diffContent).toContain('"--path <path>"');
});
- it("passes resolver opts to resolveFileOrEntity", () => {
- expect(diffContent).toContain("resolveFileOrEntity(client, target, resolveOpts)");
+ it("passes resolver opts to resolveFileOrReport", () => {
+ expect(diffContent).toContain("resolveFileOrReport(client, target, resolveOpts, opts.format)");
});
it("parses --pick as a positive integer", () => {
@@ -212,8 +212,7 @@ describe("diff.ts resolver flags", () => {
});
it("outputs structured JSON for ambiguous targets", () => {
- expect(diffContent).toContain("resolveEntityFull");
- expect(diffContent).toContain("fullResult.ambiguous");
+ expect(diffContent).toContain("resolveFileOrReport");
});
});
diff --git a/ix-cli/src/cli/__tests__/diff-unresolved-target.test.ts b/ix-cli/src/cli/__tests__/diff-unresolved-target.test.ts
index 950ae62f..0942115d 100644
--- a/ix-cli/src/cli/__tests__/diff-unresolved-target.test.ts
+++ b/ix-cli/src/cli/__tests__/diff-unresolved-target.test.ts
@@ -47,7 +47,6 @@ describe("ix diff — unresolved target", () => {
process.exitCode = savedExitCode;
});
- // The symbol path: resolveEntityFull finds nothing.
it("emits the shared slug and message as json for a symbol target", async () => {
const result = await run(["diff", "3", "5", "DefinitelyMissing", "--format", "json"]);
@@ -57,9 +56,6 @@ describe("ix diff — unresolved target", () => {
});
});
- // The file-like path: a target with an extension skips resolveEntityFull and
- // goes through resolveFileOrEntity, which is a separate branch with its own
- // copy of the record. Both were wrong; both must be right.
it("emits the shared slug and message as json for a file-like target", async () => {
const result = await run(["diff", "3", "5", "DefinitelyMissing.ts", "--format", "json"]);
@@ -77,14 +73,9 @@ describe("ix diff — unresolved target", () => {
);
});
- // Deliberate scope boundary, not an oversight. Making `ix diff` exit non-zero
- // is a breaking change for the plugins that call it (CONTRIBUTING -> CLI
- // Standards -> Exit codes); ix-cursor-plugin's ix_diff tool routes on the
- // exit status. That half is queued behind Ix #547. This test fails the moment
- // someone adds the exit code without doing that work.
- it("does not yet exit non-zero — that half is queued behind the plugin fixes", async () => {
+ it("exits non-zero for an unresolved target", async () => {
await run(["diff", "3", "5", "DefinitelyMissing", "--format", "json"]);
- expect(process.exitCode).toBeUndefined();
+ expect(process.exitCode).toBe(1);
});
});
diff --git a/ix-cli/src/cli/__tests__/file-resolution.test.ts b/ix-cli/src/cli/__tests__/file-resolution.test.ts
index 1e2f2516..5eef8f1b 100644
--- a/ix-cli/src/cli/__tests__/file-resolution.test.ts
+++ b/ix-cli/src/cli/__tests__/file-resolution.test.ts
@@ -37,10 +37,10 @@ describe("file-first resolution helper", () => {
});
it("resolveFileOrEntity tries file graph match before symbol resolution", () => {
- // The function should check looksFileLike first, then fall through to resolveEntity
+ // The function should check looksFileLike first, then fall through to structured symbol resolution
expect(resolveContent).toContain("looksFileLike(target)");
expect(resolveContent).toContain("tryFileGraphMatch(client, target,");
- expect(resolveContent).toContain("resolveEntity(client, target,");
+ expect(resolveContent).toContain("resolveEntityFull(client, target,");
});
it("tryFileGraphMatch scores exact path matches higher than basename matches", () => {
@@ -51,8 +51,8 @@ describe("file-first resolution helper", () => {
});
describe("history command uses file-first resolution", () => {
- it("imports resolveFileOrEntity", () => {
- expect(historyContent).toContain("resolveFileOrEntity");
+ it("imports resolveFileOrReport", () => {
+ expect(historyContent).toContain("resolveFileOrReport");
});
it("accepts a target argument, not entityId", () => {
@@ -69,8 +69,8 @@ describe("diff command supports scoped target", () => {
expect(diffContent).toContain('command("diff <fromRev> <toRev> [target]")');
});
- it("uses resolveFileOrEntity for target resolution", () => {
- expect(diffContent).toContain("resolveFileOrEntity");
+ it("uses resolveFileOrReport for target resolution", () => {
+ expect(diffContent).toContain("resolveFileOrReport");
});
it("passes resolved entity ID to diff API", () => {
@@ -96,8 +96,9 @@ describe("diff command supports scoped target", () => {
describe("all graph commands use resolveFileOrEntity consistently", () => {
for (const cmd of COMMANDS_USING_FILE_RESOLUTION) {
- it(`${cmd} imports resolveFileOrEntity`, () => {
- expect(commandContents[cmd]).toContain("resolveFileOrEntity");
+ it(`${cmd} uses file-first resolution`, () => {
+ const helper = cmd === "locate" ? "resolveFileOrEntity" : "resolveFileOrReport";
+ expect(commandContents[cmd]).toContain(helper);
});
}
});
@@ -107,8 +108,8 @@ describe("--pick support", () => {
expect(resolveContent).toContain("export function applyPick");
});
- it("resolve.ts printAmbiguous outputs numbered candidates", () => {
- expect(resolveContent).toContain("${i + 1}.");
+ it("resolve.ts delegates ambiguity output to the shared reporter", () => {
+ expect(resolveContent).toContain("reportAmbiguousTarget(symbol, result, \"text\", opts)");
});
it("overview.ts declares --path option", () => {
diff --git a/ix-cli/src/cli/__tests__/mcp.test.ts b/ix-cli/src/cli/__tests__/mcp.test.ts
index daf853c2..ed199f89 100644
--- a/ix-cli/src/cli/__tests__/mcp.test.ts
+++ b/ix-cli/src/cli/__tests__/mcp.test.ts
@@ -129,6 +129,59 @@ describe("ix mcp", () => {
expect(result.content).toEqual([{ type: "text", text: error }]);
});
+ it("preserves a structured LLM error when the CLI exits non-zero", async () => {
+ const error = 'error code=unresolved_target message="No graph entity found for \\"Missing\\"."';
+ const client = await connect(async () => ({
+ ok: false,
+ stdout: error,
+ stderr: 'No entity found matching "Missing".',
+ }));
+
+ const result = await client.callTool({
+ name: "ix_impact",
+ arguments: { target: "Missing" },
+ });
+
+ expect(result.isError).toBe(true);
+ expect(result.content).toEqual([{ type: "text", text: error }]);
+ });
+
+ it("does not mistake arbitrary stdout from a failed command for a machine error", async () => {
+ const client = await connect(async () => ({
+ ok: false,
+ stdout: "partial output",
+ stderr: "backend unavailable",
+ }));
+
+ const result = await client.callTool({
+ name: "ix_impact",
+ arguments: { target: "Missing" },
+ });
+
+ expect(result.isError).toBe(true);
+ expect(result.content).toEqual([{
+ type: "text",
+ text: JSON.stringify({ error: "backend unavailable", tool: "ix_impact" }),
+ }]);
+ });
+
+ it("preserves a structured JSON error when the CLI exits non-zero", async () => {
+ const error = JSON.stringify({ error: "invalid_map_path", message: "Path is outside the workspace." });
+ const client = await connect(async () => ({
+ ok: false,
+ stdout: error,
+ stderr: "Path is outside the workspace.",
+ }));
+
+ const result = await client.callTool({
+ name: "ix_map",
+ arguments: { file: "../outside.ts" },
+ });
+
+ expect(result.isError).toBe(true);
+ expect(result.content).toEqual([{ type: "text", text: error }]);
+ });
+
it("keeps error-like source lines after a successful LLM record as data", async () => {
const output = [
"content target=fixture.ts lines=1",
@@ -255,15 +308,10 @@ describe("ix mcp", () => {
const result = await client.callTool({ name: "ix_health", arguments: {} });
expect(result.isError).toBe(true);
- expect(result.content).toEqual([
- {
- type: "text",
- text: JSON.stringify({
- error: "error code=backend_unreachable message=offline",
- tool: "ix_health",
- }),
- },
- ]);
+ expect(result.content).toEqual([{
+ type: "text",
+ text: "error code=backend_unreachable message=offline",
+ }]);
});
it("keeps the existing ix_map file argument contract", async () => {
diff --git a/ix-cli/src/cli/__tests__/pick-resolution.test.ts b/ix-cli/src/cli/__tests__/pick-resolution.test.ts
index 9aaaeee4..2ac7d4a4 100644
--- a/ix-cli/src/cli/__tests__/pick-resolution.test.ts
+++ b/ix-cli/src/cli/__tests__/pick-resolution.test.ts
@@ -70,23 +70,35 @@ describe("applyPick", () => {
}
});
- it("returns not-found for pick=0 (out of range)", () => {
+ it("keeps ambiguity and adds a diagnostic for pick=0", () => {
const result = makeAmbiguousResult(3);
const picked = applyPick(result, { pick: 0 });
expect(picked).not.toBeNull();
expect(picked!.resolved).toBe(false);
if (!picked!.resolved) {
- expect(picked!.ambiguous).toBe(false);
+ expect(picked!.ambiguous).toBe(true);
+ if (picked!.ambiguous) {
+ expect(picked!.result.diagnostics?.[0]).toEqual({
+ code: "pick_out_of_range",
+ message: "--pick 0 is out of range (1-3).",
+ });
+ }
}
});
- it("returns not-found for pick > candidates.length", () => {
+ it("keeps ambiguity and adds a diagnostic for pick > candidates.length", () => {
const result = makeAmbiguousResult(3);
const picked = applyPick(result, { pick: 10 });
expect(picked).not.toBeNull();
expect(picked!.resolved).toBe(false);
if (!picked!.resolved) {
- expect(picked!.ambiguous).toBe(false);
+ expect(picked!.ambiguous).toBe(true);
+ if (picked!.ambiguous) {
+ expect(picked!.result.diagnostics?.[0]).toEqual({
+ code: "pick_out_of_range",
+ message: "--pick 10 is out of range (1-3).",
+ });
+ }
}
});
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 f2f62357..f4564b11 100644
--- a/ix-cli/src/cli/__tests__/unresolved-machine-output.test.ts
+++ b/ix-cli/src/cli/__tests__/unresolved-machine-output.test.ts
@@ -1,14 +1,43 @@
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() { return []; }
+ 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(),
+ };
+});
+
type Register = (program: Command) => void;
+type LoadRegister = () => Promise<Register>;
+
+const UNRESOLVED_COMMANDS: ReadonlyArray<readonly [string, readonly string[], LoadRegister]> = [
+ ["context", ["context", "DefinitelyMissing"], async () => (await import("../commands/context.js")).registerContextCommand],
+ ["explain", ["explain", "DefinitelyMissing"], async () => (await import("../commands/explain.js")).registerExplainCommand],
+ ["read", ["read", "DefinitelyMissing"], async () => (await import("../commands/read.js")).registerReadCommand],
+ ["overview", ["overview", "DefinitelyMissing"], async () => (await import("../commands/overview.js")).registerOverviewCommand],
+ ["impact", ["impact", "DefinitelyMissing"], async () => (await import("../commands/impact.js")).registerImpactCommand],
+ ["contains", ["contains", "DefinitelyMissing"], async () => (await import("../commands/contains.js")).registerContainsCommand],
+ ["callers", ["callers", "DefinitelyMissing"], async () => (await import("../commands/callers.js")).registerCallersCommand],
+ ["callees", ["callees", "DefinitelyMissing"], async () => (await import("../commands/callers.js")).registerCallersCommand],
+ ["imports", ["imports", "DefinitelyMissing"], async () => (await import("../commands/imports.js")).registerImportsCommand],
+ ["imported-by", ["imported-by", "DefinitelyMissing"], async () => (await import("../commands/imports.js")).registerImportsCommand],
+ ["depends", ["depends", "DefinitelyMissing"], async () => (await import("../commands/depends.js")).registerDependsCommand],
+ ["trace", ["trace", "DefinitelyMissing"], async () => (await import("../commands/trace.js")).registerTraceCommand],
+ ["history", ["history", "DefinitelyMissing"], async () => (await import("../commands/history.js")).registerHistoryCommand],
+ ["diff", ["diff", "3", "5", "DefinitelyMissing"], async () => (await import("../commands/diff.js")).registerDiffCommand],
+];
async function run(register: Register, args: string[]): Promise<{ stdout: string; stderr: string }> {
const program = new Command();
@@ -18,11 +47,16 @@ async function run(register: Register, args: string[]): Promise<{ 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") };
}
@@ -33,18 +67,15 @@ describe("unresolved targets in machine formats", () => {
beforeEach(() => {
savedExitCode = process.exitCode;
process.exitCode = undefined;
+ search.mockReset().mockResolvedValue([]);
});
afterEach(() => {
process.exitCode = savedExitCode;
});
- it.each([
- ["context", async () => (await import("../commands/context.js")).registerContextCommand],
- ["explain", async () => (await import("../commands/explain.js")).registerExplainCommand],
- ["read", async () => (await import("../commands/read.js")).registerReadCommand],
- ] as const)("returns JSON and a non-zero status from ix %s", async (command, loadRegister) => {
- const result = await run(await loadRegister(), [command, "DefinitelyMissing", "--format", "json"]);
+ it.each(UNRESOLVED_COMMANDS)("returns JSON and a non-zero status from ix %s", async (_command, args, loadRegister) => {
+ const result = await run(await loadRegister(), [...args, "--format", "json"]);
expect(process.exitCode).toBe(1);
expect(JSON.parse(result.stdout)).toEqual({
@@ -52,4 +83,77 @@ describe("unresolved targets in machine formats", () => {
message: 'No entity found matching "DefinitelyMissing".',
});
});
+
+ it.each(UNRESOLVED_COMMANDS)("returns LLM output and a non-zero status from ix %s", async (_command, args, loadRegister) => {
+ const result = await run(await loadRegister(), [...args, "--format", "llm"]);
+
+ expect(process.exitCode).toBe(1);
+ expect(result.stdout).toBe(
+ 'error code=unresolved_target message="No entity found matching \\"DefinitelyMissing\\"."',
+ );
+ });
+
+ it.each(UNRESOLVED_COMMANDS)("keeps text stdout clean and exits non-zero from ix %s", async (_command, args, loadRegister) => {
+ const result = await run(await loadRegister(), [...args, "--format", "text"]);
+
+ expect(process.exitCode).toBe(1);
+ expect(result.stdout).toBe("");
+ expect(result.stderr).toContain('No entity found matching "DefinitelyMissing".');
+ });
+
+ it("reports ambiguous targets with candidates without claiming they are missing", async () => {
+ search.mockResolvedValue([
+ { id: "first-id", kind: "function", name: "Duplicate", provenance: { sourceUri: "src/first.ts" } },
+ { id: "second-id", kind: "function", name: "Duplicate", provenance: { sourceUri: "src/second.ts" } },
+ ]);
+
+ const result = await run(
+ (await import("../commands/overview.js")).registerOverviewCommand,
+ ["overview", "Duplicate", "--format", "json"],
+ );
+
+ expect(process.exitCode).toBe(1);
+ expect(JSON.parse(result.stdout)).toMatchObject({
+ error: "ambiguous_target",
+ message: 'Ambiguous symbol "Duplicate".',
+ candidates: [
+ { id: "first-id", name: "Duplicate" },
+ { id: "second-id", name: "Duplicate" },
+ ],
+ });
+ });
+
+ it("keeps an out-of-range pick classified as ambiguity and exits non-zero", async () => {
+ search.mockResolvedValue([
+ { id: "first-id", kind: "function", name: "Duplicate", provenance: { sourceUri: "src/first.ts" } },
+ { id: "second-id", kind: "function", name: "Duplicate", provenance: { sourceUri: "src/second.ts" } },
+ ]);
+
+ const result = await run(
+ (await import("../commands/overview.js")).registerOverviewCommand,
+ ["overview", "Duplicate", "--pick", "3", "--format", "json"],
+ );
+
+ expect(process.exitCode).toBe(1);
+ const output = JSON.parse(result.stdout);
+ expect(output.error).toBe("ambiguous_target");
+ expect(output.diagnostics[0]).toEqual({
+ code: "pick_out_of_range",
+ message: "--pick 3 is out of range (1-2).",
+ });
+ });
+
+ it("reports both missing trace endpoints in one result", async () => {
+ const result = await run(
+ (await import("../commands/trace.js")).registerTraceCommand,
+ ["trace", "MissingFrom", "--to", "MissingTo", "--format", "json"],
+ );
+
+ expect(process.exitCode).toBe(1);
+ expect(JSON.parse(result.stdout)).toEqual({
+ error: "unresolved_target",
+ message: 'No entities found matching "MissingFrom" or "MissingTo".',
+ targets: ["MissingFrom", "MissingTo"],
+ });
+ });
});
diff --git a/ix-cli/src/cli/commands/callers.ts b/ix-cli/src/cli/commands/callers.ts
index 034a7527..92e4a79d 100644
--- a/ix-cli/src/cli/commands/callers.ts
+++ b/ix-cli/src/cli/commands/callers.ts
@@ -6,14 +6,9 @@ import { IxClient } from "../../client/api.js";
import { getEndpoint, resolveWorkspaceRoot } from "../config.js";
import { formatEdgeResults, relativePath } from "../format.js";
import { parsePickOption } from "../options.js";
-import { resolveFileOrEntity, printResolved } from "../resolve.js";
+import { resolveFileOrReport, printResolved } from "../resolve.js";
import { stderr } from "../stderr.js";
-import { llmLine, llmError } from "../llm.js";
-
-/** Emit a structured llm error for a failed resolution, or nothing for other formats. */
-function llmUnresolved(format: string, symbol: string): void {
- if (format === "llm") console.log(llmError("unresolved_target", `No entity resolved for "${symbol}".`));
-}
+import { llmLine } from "../llm.js";
const execFileAsync = promisify(execFile);
@@ -30,8 +25,8 @@ export function registerCallersCommand(program: Command): void {
const client = new IxClient(getEndpoint());
const limit = parseInt(opts.limit, 10);
const resolveOpts = { kind: opts.kind, pick: opts.pick };
- const target = await resolveFileOrEntity(client, symbol, resolveOpts);
- if (!target) { llmUnresolved(opts.format, symbol); return; }
+ const target = await resolveFileOrReport(client, symbol, resolveOpts, opts.format);
+ if (!target) return;
if (opts.format === "text") printResolved(target);
// Use expand by entity ID to avoid aggregating results across all same-named entities
const result = await client.expand(target.id, {
@@ -133,8 +128,8 @@ export function registerCallersCommand(program: Command): void {
const client = new IxClient(getEndpoint());
const calleeLimit = parseInt(opts.limit, 10);
const resolveOpts = { kind: opts.kind, pick: opts.pick };
- const target = await resolveFileOrEntity(client, symbol, resolveOpts);
- if (!target) { llmUnresolved(opts.format, symbol); return; }
+ const target = await resolveFileOrReport(client, symbol, resolveOpts, opts.format);
+ if (!target) return;
if (opts.format === "text") printResolved(target);
// Use expand by entity ID to avoid aggregating results across all same-named entities
const result = await client.expand(target.id, {
diff --git a/ix-cli/src/cli/commands/contains.ts b/ix-cli/src/cli/commands/contains.ts
index 830bbc3d..fa05fa5c 100644
--- a/ix-cli/src/cli/commands/contains.ts
+++ b/ix-cli/src/cli/commands/contains.ts
@@ -3,8 +3,7 @@ import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
import { formatEdgeResults } from "../format.js";
import { parsePickOption } from "../options.js";
-import { resolveFileOrEntity, printResolved } from "../resolve.js";
-import { llmError } from "../llm.js";
+import { resolveFileOrReport, printResolved } from "../resolve.js";
export function registerContainsCommand(program: Command): void {
program
@@ -20,11 +19,8 @@ export function registerContainsCommand(program: Command): void {
const client = new IxClient(getEndpoint());
const limit = parseInt(opts.limit, 10);
const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick };
- const target = await resolveFileOrEntity(client, symbol, resolveOpts);
- if (!target) {
- if (opts.format === "llm") console.log(llmError("unresolved_target", `No entity resolved for "${symbol}".`));
- return;
- }
+ const target = await resolveFileOrReport(client, symbol, resolveOpts, opts.format);
+ if (!target) return;
if (opts.format === "text") printResolved(target);
const result = await client.expand(target.id, { direction: "out", predicates: ["CONTAINS"] });
const limited = result.nodes.slice(0, limit);
diff --git a/ix-cli/src/cli/commands/context.ts b/ix-cli/src/cli/commands/context.ts
index b694f01b..0677de2a 100644
--- a/ix-cli/src/cli/commands/context.ts
+++ b/ix-cli/src/cli/commands/context.ts
@@ -20,9 +20,9 @@ import { getEndpoint } from "../config.js";
import { collectFacts, type EntityFacts } from "../explain/facts.js";
import { llmLine, printLlmLines } from "../llm.js";
import { parseBudgetOption, parsePickOption, parseRevisionOption } from "../options.js";
-import { resolveFileOrEntity } from "../resolve.js";
+import { resolveFileOrReport } from "../resolve.js";
import { createStaleProbe, hasCompletedSourceGraphBaseline } from "../stale.js";
-import { renderNote, renderSection, renderWarning, renderWarningErr, reportFailure, reportUnresolvedTarget } from "../ui.js";
+import { renderNote, renderSection, renderWarning, renderWarningErr, reportFailure } from "../ui.js";
/** The four `--max-*` knobs that bound a bundle. */
interface BudgetSnapshot {
@@ -283,6 +283,7 @@ export function registerContextCommand(program: Command): void {
target ?? saved.bundle.target.name,
{ ...opts, ...mergeDiffOptions(saved, opts) },
saved.bundle.budgets,
+ opts.format,
);
if (!fresh) return;
renderInvestigationDiff(saved, fresh, opts.format, requestedBudgets);
@@ -302,15 +303,12 @@ export function registerContextCommand(program: Command): void {
const client = new IxClient(getEndpoint());
- const resolved = await resolveFileOrEntity(client, target, {
+ const resolved = await resolveFileOrReport(client, target, {
kind: opts.kind,
path: opts.path,
pick: opts.pick,
- });
- if (!resolved) {
- reportUnresolvedTarget(target, opts.format);
- return;
- }
+ }, opts.format);
+ if (!resolved) return;
const budgets = clampBudgets(opts);
const asOfRev = opts.asOfRev;
@@ -404,13 +402,14 @@ async function buildFreshBundle(
target: string,
opts: { kind?: string; path?: string; pick?: number; depth?: string; asOfRev?: number },
budgets: BudgetSnapshot,
+ format: string,
): Promise<ContextBundle | undefined> {
const client = new IxClient(getEndpoint());
- const resolved = await resolveFileOrEntity(client, target, {
+ const resolved = await resolveFileOrReport(client, target, {
kind: opts.kind,
path: opts.path,
pick: opts.pick,
- });
+ }, format);
if (!resolved) return undefined;
const asOfRev = opts.asOfRev;
diff --git a/ix-cli/src/cli/commands/depends.ts b/ix-cli/src/cli/commands/depends.ts
index 9d2d9049..5721438e 100644
--- a/ix-cli/src/cli/commands/depends.ts
+++ b/ix-cli/src/cli/commands/depends.ts
@@ -2,9 +2,9 @@ import type { Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
-import { resolveFileOrEntity, printResolved, isRawId } from "../resolve.js";
+import { resolveFileOrReport, printResolved, isRawId } from "../resolve.js";
import { compactTreeNode, relativePath } from "../format.js";
-import { llmLine, llmError } from "../llm.js";
+import { llmLine } from "../llm.js";
import { parsePickOption } from "../options.js";
// ── Tree types ──────────────────────────────────────────────────────
@@ -214,11 +214,8 @@ export function registerDependsCommand(program: Command): void {
includeTests: opts.includeTests,
testsOnly: opts.testsOnly,
};
- const target = await resolveFileOrEntity(client, symbol, resolveOpts);
- if (!target) {
- if (opts.format === "llm") console.log(llmError("unresolved_target", `No entity resolved for "${symbol}".`));
- return;
- }
+ const target = await resolveFileOrReport(client, symbol, resolveOpts, opts.format);
+ if (!target) return;
const maxDepth = opts.depth ? parseInt(opts.depth, 10) : DEFAULT_MAX_DEPTH;
const maxNodes = opts.cap ? parseInt(opts.cap, 10) : MAX_NODES;
diff --git a/ix-cli/src/cli/commands/diff.ts b/ix-cli/src/cli/commands/diff.ts
index 073ad1c9..571a688c 100644
--- a/ix-cli/src/cli/commands/diff.ts
+++ b/ix-cli/src/cli/commands/diff.ts
@@ -8,10 +8,10 @@ import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
-import { resolveFileOrEntity, resolveEntityFull, printResolved, looksFileLike, type ResolvedEntity } from "../resolve.js";
+import { resolveFileOrReport, printResolved, type ResolvedEntity } from "../resolve.js";
import { formatDiff, relativePath } from "../format.js";
-import { llmLine, llmError } from "../llm.js";
-import { reportFailure, unresolvedTargetMessage, unresolvedTargetRecord } from "../ui.js";
+import { llmLine } from "../llm.js";
+import { reportFailure } from "../ui.js";
import { parsePickOption } from "../options.js";
/**
@@ -499,36 +499,9 @@ export function registerDiffCommand(program: Command): void {
let entityId: string | undefined = opts.entity;
let resolved: ResolvedEntity | null = null;
if (target && !entityId) {
- if (opts.format === "json") {
- // Use full resolver for structured JSON ambiguity output
- const allKinds = ["file", "class", "object", "trait", "interface", "module", "function", "method"];
- const isFile = looksFileLike(target);
- if (!isFile) {
- const fullResult = await resolveEntityFull(client, target, allKinds, resolveOpts);
- if (fullResult.resolved) {
- resolved = fullResult.entity;
- } else if (fullResult.ambiguous) {
- console.log(JSON.stringify(fullResult.result, null, 2));
- return;
- } else {
- console.log(JSON.stringify(unresolvedTargetRecord(target), null, 2));
- return;
- }
- } else {
- resolved = await resolveFileOrEntity(client, target, resolveOpts);
- if (!resolved) {
- console.log(JSON.stringify(unresolvedTargetRecord(target), null, 2));
- return;
- }
- }
- } else {
- resolved = await resolveFileOrEntity(client, target, resolveOpts);
- if (!resolved) {
- if (opts.format === "llm") console.log(llmError("unresolved_target", unresolvedTargetMessage(target)));
- return;
- }
- if (opts.format === "text") printResolved(resolved);
- }
+ resolved = await resolveFileOrReport(client, target, resolveOpts, opts.format);
+ if (!resolved) return;
+ if (opts.format === "text") printResolved(resolved);
entityId = resolved.id;
}
diff --git a/ix-cli/src/cli/commands/explain.ts b/ix-cli/src/cli/commands/explain.ts
index a0ed4872..c84b83c1 100644
--- a/ix-cli/src/cli/commands/explain.ts
+++ b/ix-cli/src/cli/commands/explain.ts
@@ -2,7 +2,7 @@ import type { Command } from "commander";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
import { formatExplain, relativePath, type ExplainResult, type EntityRef, type Diagnostic } from "../format.js";
-import { resolveFileOrEntity, isRawId } from "../resolve.js";
+import { resolveFileOrReport, isRawId } from "../resolve.js";
import { isFileStale } from "../stale.js";
import { collectFacts } from "../explain/facts.js";
import { inferRole } from "../explain/role-inference.js";
@@ -11,7 +11,7 @@ import { renderExplanation } from "../explain/render.js";
import { renderExplainLlm, renderExplainRawLlm } from "../explain/llm.js";
import { printLlmLines } from "../llm.js";
import { parsePickOption } from "../options.js";
-import { renderSection, renderWarning, renderNote, reportUnresolvedTarget } from "../ui.js";
+import { renderSection, renderWarning, renderNote } from "../ui.js";
export function registerExplainCommand(program: Command): void {
program
@@ -26,11 +26,8 @@ export function registerExplainCommand(program: Command): void {
.action(async (symbol: string, opts: { kind?: string; path?: string; pick?: number; format: string; raw?: boolean }) => {
const client = new IxClient(getEndpoint());
const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick };
- const target = await resolveFileOrEntity(client, symbol, resolveOpts);
- if (!target) {
- reportUnresolvedTarget(symbol, opts.format);
- return;
- }
+ const target = await resolveFileOrReport(client, symbol, resolveOpts, opts.format);
+ if (!target) return;
if (opts.raw) {
await rawExplain(client, target, opts.format);
diff --git a/ix-cli/src/cli/commands/history.ts b/ix-cli/src/cli/commands/history.ts
index 284e13e0..3e78c638 100644
--- a/ix-cli/src/cli/commands/history.ts
+++ b/ix-cli/src/cli/commands/history.ts
@@ -2,9 +2,9 @@ import type { Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
-import { resolveFileOrEntity, printResolved } from "../resolve.js";
+import { resolveFileOrReport, printResolved } from "../resolve.js";
import { relativePath } from "../format.js";
-import { llmLine, llmError } from "../llm.js";
+import { llmLine } from "../llm.js";
import { parsePickOption } from "../options.js";
/** Render an entity's provenance chain as llm records: a header then one `patch` row per revision. */
@@ -39,11 +39,8 @@ export function registerHistoryCommand(program: Command): void {
.action(async (target: string, opts: { kind?: string; path?: string; pick?: number; format: string }) => {
const client = new IxClient(getEndpoint());
const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick };
- const resolved = await resolveFileOrEntity(client, target, resolveOpts);
- if (!resolved) {
- if (opts.format === "llm") console.log(llmError("unresolved_target", `No entity resolved for "${target}".`));
- return;
- }
+ const resolved = await resolveFileOrReport(client, target, resolveOpts, opts.format);
+ if (!resolved) return;
if (opts.format === "text") printResolved(resolved);
diff --git a/ix-cli/src/cli/commands/impact.ts b/ix-cli/src/cli/commands/impact.ts
index c30ff0f1..d1fa6495 100644
--- a/ix-cli/src/cli/commands/impact.ts
+++ b/ix-cli/src/cli/commands/impact.ts
@@ -3,11 +3,11 @@ import chalk from "chalk";
import { renderSection, renderKeyValue, renderNote, renderResolvedHeader, colorizeKind } from "../ui.js";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
-import { resolveFileOrEntity, printResolved } from "../resolve.js";
+import { resolveFileOrReport, printResolved } from "../resolve.js";
import { bucketByHierarchy, getSystemPath, formatSystemPath, hasMapData, type SystemPath } from "../hierarchy.js";
import { inferRiskSemantics, humanizeLabel, type ImpactFacts, type RiskSemantics } from "../impact/risk-semantics.js";
import { stripNulls } from "../format.js";
-import { llmLine, llmError } from "../llm.js";
+import { llmLine } from "../llm.js";
import { parsePickOption } from "../options.js";
const CONTAINER_KINDS = new Set(["class", "module", "file", "object", "trait", "interface"]);
@@ -35,13 +35,8 @@ export function registerImpactCommand(program: Command): void {
const depth = Math.min(Math.max(parseInt(opts.depth, 10) || 1, 1), 3);
const resolveOpts = { kind: opts.kind, pick: opts.pick };
- const target = await resolveFileOrEntity(client, symbol, resolveOpts);
- if (!target) {
- // The resolver already printed human guidance to stderr; for llm
- // consumers emit a structured error record on stdout as well.
- if (opts.format === "llm") console.log(llmError("unresolved_target", `No entity resolved for "${symbol}".`));
- return;
- }
+ const target = await resolveFileOrReport(client, symbol, resolveOpts, opts.format);
+ if (!target) return;
if (opts.format === "text") printResolved(target);
diff --git a/ix-cli/src/cli/commands/imports.ts b/ix-cli/src/cli/commands/imports.ts
index f5454cd8..a2b20c8a 100644
--- a/ix-cli/src/cli/commands/imports.ts
+++ b/ix-cli/src/cli/commands/imports.ts
@@ -2,14 +2,9 @@ import type { Command } from "commander";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
import { formatEdgeResults } from "../format.js";
-import { resolveFileOrEntity, printResolved } from "../resolve.js";
-import { llmError } from "../llm.js";
+import { resolveFileOrReport, printResolved } from "../resolve.js";
import { parsePickOption } from "../options.js";
-function llmUnresolved(format: string, symbol: string): void {
- if (format === "llm") console.log(llmError("unresolved_target", `No entity resolved for "${symbol}".`));
-}
-
export function registerImportsCommand(program: Command): void {
program
.command("imports <symbol>")
@@ -23,8 +18,8 @@ export function registerImportsCommand(program: Command): void {
const client = new IxClient(getEndpoint());
const limit = parseInt(opts.limit, 10);
const resolveOpts = { kind: opts.kind, pick: opts.pick };
- const target = await resolveFileOrEntity(client, symbol, resolveOpts);
- if (!target) { llmUnresolved(opts.format, symbol); return; }
+ const target = await resolveFileOrReport(client, symbol, resolveOpts, opts.format);
+ if (!target) return;
if (opts.format === "text") printResolved(target);
const result = await client.expand(target.id, { direction: "out", predicates: ["IMPORTS"] });
formatEdgeResults(result.nodes.slice(0, limit), "imports", target.name, opts.format, target, "graph");
@@ -42,8 +37,8 @@ export function registerImportsCommand(program: Command): void {
const client = new IxClient(getEndpoint());
const limit = parseInt(opts.limit, 10);
const resolveOpts = { kind: opts.kind, pick: opts.pick };
- const target = await resolveFileOrEntity(client, symbol, resolveOpts);
- if (!target) { llmUnresolved(opts.format, symbol); return; }
+ const target = await resolveFileOrReport(client, symbol, resolveOpts, opts.format);
+ if (!target) return;
if (opts.format === "text") printResolved(target);
const result = await client.expand(target.id, { direction: "in", predicates: ["IMPORTS"] });
formatEdgeResults(result.nodes.slice(0, limit), "imported-by", target.name, opts.format, target, "graph");
diff --git a/ix-cli/src/cli/commands/overview.ts b/ix-cli/src/cli/commands/overview.ts
index 5de53891..468591d6 100644
--- a/ix-cli/src/cli/commands/overview.ts
+++ b/ix-cli/src/cli/commands/overview.ts
@@ -1,11 +1,11 @@
import type { Command } from "commander";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
-import { resolveFileOrEntity, printResolved } from "../resolve.js";
+import { resolveFileOrReport, printResolved } from "../resolve.js";
import { getEffectiveSystemPath, getSystemPath, hasMapData } from "../hierarchy.js";
import { humanizeLabel } from "../impact/risk-semantics.js";
import { relativePath } from "../format.js";
-import { llmLine, llmError, type LlmValue } from "../llm.js";
+import { llmLine, type LlmValue } from "../llm.js";
import { parsePickOption } from "../options.js";
import { renderSection, renderKeyValue, renderNote, renderBreadcrumb } from "../ui.js";
@@ -56,12 +56,8 @@ Examples:
.action(async (symbol: string, opts: { kind?: string; path?: string; pick?: number; format: string }) => {
const client = new IxClient(getEndpoint());
const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick };
- const target = await resolveFileOrEntity(client, symbol, resolveOpts);
- if (!target) {
- // Resolver printed human guidance to stderr; add a structured record for llm.
- if (opts.format === "llm") console.log(llmError("unresolved_target", `No entity resolved for "${symbol}".`));
- return;
- }
+ const target = await resolveFileOrReport(client, symbol, resolveOpts, opts.format);
+ if (!target) return;
if (opts.format === "text") printResolved(target);
diff --git a/ix-cli/src/cli/commands/trace.ts b/ix-cli/src/cli/commands/trace.ts
index 9a4c1026..69c75309 100644
--- a/ix-cli/src/cli/commands/trace.ts
+++ b/ix-cli/src/cli/commands/trace.ts
@@ -2,11 +2,18 @@ import type { Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
-import { resolveFileOrEntity, isRawId, activeReadScope, ensureReadScope } from "../resolve.js";
+import { resolveFileOrEntityFull, resolveFileOrReport, isRawId, activeReadScope, ensureReadScope } from "../resolve.js";
import type { ResolvedEntity } from "../resolve.js";
-import { renderSection, renderKeyValue, renderResolvedHeader, colorizeKind } from "../ui.js";
+import {
+ renderSection,
+ renderKeyValue,
+ renderResolvedHeader,
+ colorizeKind,
+ reportResolutionFailure,
+ reportUnresolvedTarget,
+} from "../ui.js";
import { compactTreeNode, relativePath } from "../format.js";
-import { llmLine, llmError, type LlmValue } from "../llm.js";
+import { llmLine, type LlmValue } from "../llm.js";
import { parsePickOption } from "../options.js";
// ── Types ────────────────────────────────────────────────────────────
@@ -458,14 +465,22 @@ export function registerTraceCommand(program: Command): void {
...resolveOpts,
path: undefined,
};
- const [fromTarget, toTarget] = await Promise.all([
- resolveFileOrEntity(client, symbol, resolveOpts),
- resolveFileOrEntity(client, opts.to, toResolveOpts),
+ const [fromResult, toResult] = await Promise.all([
+ resolveFileOrEntityFull(client, symbol, resolveOpts),
+ resolveFileOrEntityFull(client, opts.to, toResolveOpts),
]);
- if (!fromTarget || !toTarget) {
- if (opts.format === "llm") console.log(llmError("unresolved_target", `Could not resolve ${!fromTarget ? symbol : opts.to}.`));
+ if (!fromResult.resolved || !toResult.resolved) {
+ if (!fromResult.resolved && !toResult.resolved && !fromResult.ambiguous && !toResult.ambiguous) {
+ reportUnresolvedTarget([symbol, opts.to], opts.format);
+ } else if (!fromResult.resolved) {
+ reportResolutionFailure(symbol, fromResult, opts.format, resolveOpts);
+ } else if (!toResult.resolved) {
+ reportResolutionFailure(opts.to, toResult, opts.format, toResolveOpts);
+ }
return;
}
+ const fromTarget = fromResult.entity;
+ const toTarget = toResult.entity;
const relKind = opts.kind ?? "mixed";
const predicates = kindToPredicates(opts.kind);
@@ -539,11 +554,8 @@ export function registerTraceCommand(program: Command): void {
}
// ── Directional mode ────────────────────────────────────────
- const resolvedTarget = await resolveFileOrEntity(client, symbol, resolveOpts);
- if (!resolvedTarget) {
- if (opts.format === "llm") console.log(llmError("unresolved_target", `No entity resolved for "${symbol}".`));
- return;
- }
+ const resolvedTarget = await resolveFileOrReport(client, symbol, resolveOpts, opts.format);
+ if (!resolvedTarget) return;
let target: ResolvedEntity = resolvedTarget;
const predicates = kindToPredicates(opts.kind);
diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.ts
index 0893f43a..84fa4efa 100644
--- a/ix-cli/src/cli/resolve.ts
+++ b/ix-cli/src/cli/resolve.ts
@@ -6,6 +6,7 @@ import { applyRoleFilter } from "./role-filter.js";
import { detectSystem } from "./system.js";
import { resolveWorkspaceId } from "./bootstrap.js";
import { readStitchScope, writeStitchScope } from "./config.js";
+import { reportAmbiguousTarget, reportResolutionFailure } from "./ui.js";
/**
* The read scope for the current working directory: a co-ingested multi-repo system
@@ -214,7 +215,7 @@ export async function resolveEntity(
const result = await resolveEntityFull(client, symbol, preferredKinds, opts);
if (result.resolved) return result.entity;
if (result.ambiguous) {
- printAmbiguous(symbol, result.result, opts);
+ reportAmbiguousTarget(symbol, result.result, "text", opts);
}
return null;
}
@@ -423,8 +424,18 @@ export function applyPick(
const idx = opts.pick - 1; // convert 1-based to 0-based
if (idx < 0 || idx >= candidates.length) {
- stderr(`--pick ${opts.pick} is out of range (1-${candidates.length}).`);
- return { resolved: false, ambiguous: false };
+ const message = `--pick ${opts.pick} is out of range (1-${candidates.length}).`;
+ stderr(message);
+ return {
+ ...result,
+ result: {
+ ...result.result,
+ diagnostics: [
+ { code: "pick_out_of_range", message },
+ ...(result.result.diagnostics ?? []),
+ ],
+ },
+ };
}
const picked = candidates[idx];
@@ -485,16 +496,7 @@ function buildAmbiguous(nodes: any[], scores?: number[]): AmbiguousResult {
}
export function printAmbiguous(symbol: string, result: AmbiguousResult, opts?: { kind?: string; path?: string }): void {
- stderr(`Ambiguous symbol "${symbol}":`);
- for (let i = 0; i < result.candidates.length; i++) {
- const c = result.candidates[i];
- const shortPath = c.path ? ` in ${c.path}` : "";
- stderr(` ${i + 1}. ${chalk.cyan((c.kind ?? "").padEnd(10))} ${chalk.dim(c.id.slice(0, 8))} ${c.name}${chalk.dim(shortPath)}`);
- }
- const hints: string[] = ["--pick <n>"];
- if (!opts?.kind) hints.push("--kind");
- if (!opts?.path) hints.push("--path");
- stderr(chalk.dim(`\nUse ${hints.join(" or ")} to disambiguate.`));
+ reportAmbiguousTarget(symbol, result, "text", opts);
}
/**
@@ -570,27 +572,30 @@ export function looksFileLike(target: string): boolean {
* 2. File-like input → search graph for matching file entity
* 3. Symbol name → use scored resolver
*
- * Returns { id, name, kind } or null if not found.
+ * Keeps ambiguity distinct from a genuine miss so machine callers can act on it.
*/
-export async function resolveFileOrEntity(
+export async function resolveFileOrEntityFull(
client: IxClient,
target: string,
opts?: { kind?: string; path?: string; pick?: number; includeTests?: boolean; testsOnly?: boolean }
-): Promise<ResolvedEntity | null> {
+): Promise<ResolveResult> {
// 1. Raw UUID
if (isRawId(target)) {
try {
const details = await client.entity(target);
const n = details.node as any;
return {
- id: target,
- kind: n.kind || "unknown",
- name: n.name || target,
- resolutionMode: "exact",
+ resolved: true,
+ entity: {
+ id: target,
+ kind: n.kind || "unknown",
+ name: n.name || target,
+ resolutionMode: "exact",
+ },
};
} catch {
stderr(`Entity not found: ${target}`);
- return null;
+ return { resolved: false, ambiguous: false };
}
}
@@ -601,10 +606,13 @@ export async function resolveFileOrEntity(
const details = await client.entity(fullId);
const n = details.node as any;
return {
- id: fullId,
- kind: n.kind || "unknown",
- name: n.name || target,
- resolutionMode: "exact",
+ resolved: true,
+ entity: {
+ id: fullId,
+ kind: n.kind || "unknown",
+ name: n.name || target,
+ resolutionMode: "exact",
+ },
};
} catch {
// Not a valid entity prefix — fall through to normal resolution
@@ -614,7 +622,7 @@ export async function resolveFileOrEntity(
// 2. File-like input → try graph file search
if (looksFileLike(target)) {
const fileEntity = await tryFileGraphMatch(client, target, opts);
- if (fileEntity) return fileEntity;
+ if (fileEntity) return { resolved: true, entity: fileEntity };
// Fall through to symbol resolution
}
@@ -657,18 +665,44 @@ export async function resolveFileOrEntity(
path: pathHint, // always use the class-derived hint, not opts?.path
searchLimit: 50,
};
- const entity = await resolveEntity(client, scoped.methodName, ['method', 'function'], scopedOpts);
- if (entity) {
+ const result = await resolveEntityFull(client, scoped.methodName, ['method', 'function'], scopedOpts);
+ if (result.resolved) {
// Rewrite the display name to show the full scoped form
- return { ...entity, name: `${scoped.className}::${scoped.methodName}` };
+ 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 null;
+ return result;
}
// 3. Symbol resolution (handles all entity kinds)
const allKinds = ["file", "class", "object", "trait", "interface", "module", "method", "function"];
- return resolveEntity(client, target, allKinds, opts);
+ return resolveEntityFull(client, target, allKinds, opts);
+}
+
+export async function resolveFileOrEntity(
+ client: IxClient,
+ target: string,
+ opts?: { kind?: string; path?: string; pick?: number; includeTests?: boolean; testsOnly?: boolean },
+): Promise<ResolvedEntity | null> {
+ const result = await resolveFileOrEntityFull(client, target, opts);
+ if (result.resolved) return result.entity;
+ if (result.ambiguous) reportAmbiguousTarget(target, result.result, "text", opts);
+ return null;
+}
+
+export async function resolveFileOrReport(
+ client: IxClient,
+ target: string,
+ opts: { kind?: string; path?: string; pick?: number; includeTests?: boolean; testsOnly?: boolean } | undefined,
+ format: string,
+): Promise<ResolvedEntity | null> {
+ const result = await resolveFileOrEntityFull(client, target, opts);
+ 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.ts
index 6f6d35a5..8b4951bb 100644
--- a/ix-cli/src/cli/ui.ts
+++ b/ix-cli/src/cli/ui.ts
@@ -8,6 +8,7 @@
import chalk from "chalk";
import { llmError } from "./llm.js";
+import type { AmbiguousResult, ResolveResult } from "./resolve.js";
// ── Brand palette ─────────────────────────────────────────────────────────────
//
@@ -141,16 +142,23 @@ export function reportFailure(code: string, message: string, format?: string): v
* wrong today and can be fixed now, while the exit-code half is queued behind
* the plugin work (CONTRIBUTING -> CLI Standards -> Exit codes).
*/
-export function unresolvedTargetMessage(target: string): string {
+export function unresolvedTargetMessage(target: string | string[]): string {
+ if (Array.isArray(target)) {
+ return `No entities found matching ${target.map((value) => `"${value}"`).join(" or ")}.`;
+ }
return `No entity found matching "${target}".`;
}
/** The `--format json` record for a target that does not exist. */
-export function unresolvedTargetRecord(target: string): { error: string; message: string } {
- return { error: "unresolved_target", message: unresolvedTargetMessage(target) };
+export function unresolvedTargetRecord(target: string | string[]): { error: string; message: string; targets?: string[] } {
+ return {
+ error: "unresolved_target",
+ message: unresolvedTargetMessage(target),
+ ...(Array.isArray(target) ? { targets: target } : {}),
+ };
}
-export function reportUnresolvedTarget(target: string, format?: string): void {
+export function reportUnresolvedTarget(target: string | string[], format?: string): void {
const message = unresolvedTargetMessage(target);
if (format === "json") {
console.log(JSON.stringify(unresolvedTargetRecord(target), null, 2));
@@ -159,3 +167,51 @@ export function reportUnresolvedTarget(target: string, format?: string): void {
}
process.exitCode = 1;
}
+
+export function reportAmbiguousTarget(
+ target: string,
+ result: AmbiguousResult,
+ format?: string,
+ opts?: { kind?: string; path?: string },
+): void {
+ const message = `Ambiguous symbol "${target}".`;
+ if (format === "json") {
+ console.log(JSON.stringify({
+ error: "ambiguous_target",
+ message,
+ candidates: result.candidates,
+ diagnostics: result.diagnostics ?? [],
+ }, null, 2));
+ return;
+ }
+ if (format === "llm") {
+ console.log(llmError("ambiguous_target", message, [
+ ["candidates", result.candidates.map((candidate, index) => `${index + 1}:${candidate.name}`).join(",")],
+ ]));
+ return;
+ }
+
+ console.error(`Ambiguous symbol "${target}":`);
+ for (let index = 0; index < result.candidates.length; index += 1) {
+ const candidate = result.candidates[index];
+ const shortPath = candidate.path ? ` in ${candidate.path}` : "";
+ console.error(
+ ` ${index + 1}. ${chalk.cyan((candidate.kind ?? "").padEnd(10))} ${chalk.dim(candidate.id.slice(0, 8))} ${candidate.name}${chalk.dim(shortPath)}`,
+ );
+ }
+ const hints = ["--pick <n>"];
+ if (!opts?.kind) hints.push("--kind");
+ if (!opts?.path) hints.push("--path");
+ console.error(chalk.dim(`\nUse ${hints.join(" or ")} to disambiguate.`));
+}
+
+export function reportResolutionFailure(
+ target: string,
+ result: Exclude<ResolveResult, { resolved: true }>,
+ format?: string,
+ opts?: { kind?: string; path?: string },
+): void {
+ if (result.ambiguous) reportAmbiguousTarget(target, result.result, format, opts);
+ else reportUnresolvedTarget(target, format);
+ process.exitCode = 1;
+}
diff --git a/ix-cli/src/mcp/server.ts b/ix-cli/src/mcp/server.ts
index 65ca0b3a..c86db8e6 100644
--- a/ix-cli/src/mcp/server.ts
+++ b/ix-cli/src/mcp/server.ts
@@ -623,6 +623,9 @@ async function runCommand(
): Promise<CallToolResult> {
const result = await runIx(args, timeoutMs);
if (!result.ok) {
+ const machineError = machineErrorOutput(result.stdout);
+ if (machineError) return textResult(machineError, true);
+
const detail =
result.stderr.trim() ||
result.stdout.trim() ||
@@ -719,6 +722,15 @@ function parseJsonOutput(output: string): unknown {
return null;
}
+function machineErrorOutput(output: string): string | null {
+ const text = output.trim();
+ if (text.startsWith("error code=")) return text;
+
+ const parsed = parseJsonOutput(text);
+ if (isRecord(parsed) && typeof parsed.error === "string") return text;
+ return null;
+}
+
function isRecord(value: unknown): value is Record<string, unknown> {
return value !== null && typeof value === "object" && !Array.isArray(value);
}