Skip to content

armgit / Ix

Public Imported from GitHub
0

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

feat(cli): distinct exit codes, --all and multi-target for graph lookups (#853)

Tanner Kocherbb3059b18c3f
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index d3c5f0a0..0d3862d2 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -97,6 +97,17 @@ Breaking changes: use `feat!:` or `fix!:` prefix.
### Exit codes
+The graph commands share one set of codes, defined in
+`ix-cli/src/cli/outcome.ts`: `0` results, `1` error, `2` ambiguous target,
+`3` target not found, `4` workspace not mapped (`IX_LEGACY_EXIT_CODES=1`
+collapses 2-4 to 1). A hook that runs `ix` exits with its own status, never
+ix's: Claude Code treats a hook's exit `2` as a block. Report a resolution
+failure through `resolveFileOrReport` or `reportResolutionFailure` rather than
+setting `process.exitCode` yourself,
+and the right code follows. `ix read`'s ambiguity is the one exception: it
+exits 0 with its own `ambiguous` record, as it always has (see below for why
+adding a non-zero exit is not free).
+
Making a command exit non-zero is a **breaking change to every plugin and MCP
client**, even when the payload it prints is an improvement. Both consumers
throw stdout away on a failed run:
diff --git a/docs/llm-format.md b/docs/llm-format.md
index 12af8225..ba95a5d2 100644
--- a/docs/llm-format.md
+++ b/docs/llm-format.md
@@ -65,12 +65,50 @@ which value it ignored, on stderr, when a person is there to read it.
`\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 graph target that
- does not exist is always `unresolved_target`. `locate` is the remaining
- exit-status exception tracked in #539.
+ does not exist is always `unresolved_target`.
+ The graph commands (`locate`, `callers`, `callees`, `impact`, `explain` and
+ the rest that resolve a target, `subsystems <region>` and `around` included)
+ exit with a code per outcome, and json's `error` / llm's `error code=` carry
+ the matching slug (`subsystems --format json` prints the backend's body, where
+ an unknown region is `unknown_target`):
+
+ | Exit | Outcome | Slug |
+ |---|---|---|
+ | 0 | results | — |
+ | 2 | ambiguous: candidates listed, retry with `--pick <n>`, `--path` or `--all` | `ambiguous_target` |
+ | 3 | not found: suggestions and a reason when known | `unresolved_target` |
+ | 4 | workspace not mapped: run `ix map` | `workspace_not_mapped` |
+ | 1 | any other error (backend down, bad argument, ...) | its own slug |
+
+ `IX_LEGACY_EXIT_CODES=1` makes every non-zero exit `1`, for an integration
+ that compares the status against `1`. A hook must not pass ix's status
+ through as its own: Claude Code reads a hook's exit `2` as "block this
+ action", so an ambiguous name would block the tool call. End the hook with
+ its own status (the shipped hooks exit 0), or set `IX_LEGACY_EXIT_CODES=1`.
+ One exception in json: `locate`'s ambiguity record carries the slug as
+ `code: "ambiguous_target"`, not `error` (it never was an `error` record, and
+ readers that treat any string `error` as a failure would drop its
+ candidates); it still exits 2.
+ One exception in exit code: `read`'s ambiguity (a file or symbol name that
+ matches several) exits 0 with its own record, `ambiguous kind=<file|symbol>
+ target=... count=<n>` and its candidates (json: `targetType:
+ "ambiguous-file"` / `"ambiguous-symbol"`, `candidates`, no `error`), as it
+ always has. Retry with `--pick <n>` or `--path`. Its miss exits 3 like the
+ rest.
A file target's miss adds `reason=file_not_in_graph` (on disk, not ingested)
- or `reason=file_not_found`, any miss may carry `suggestion` records with the
- nearest names in the graph, and a miss on an empty or degraded graph carries
- a `graph` record saying so.
+ or `reason=file_not_found`. A symbol's miss says why when the workspace's
+ text can: `reason=symbol_file_not_indexed` (the name is only in source files
+ the graph does not have), `reason=symbol_not_extracted` (it is in indexed files, named
+ with their revision, but not as an entity) or `reason=symbol_not_in_source`
+ (it is nowhere in the workspace either), with `files=` naming up to three
+ files. Only files `ix map` parses count, so a name that appears only in, say,
+ a `.txt` is a plain miss; a command spends at most 5 seconds on these lookups,
+ then reports later misses plainly; `IX_MISS_PROBE=0` turns them off. A miss
+ under `--kind`, `--path` or the test filter, where an entity of that name
+ exists outside the filter, is a plain miss too (no `reason`): drop or change
+ the filter. Any miss may carry
+ `suggestion` records with the nearest names in the graph (`locate` included),
+ and a miss on an empty or degraded graph carries a `graph` record saying so.
A graph read from a directory no registered workspace covers is
`workspace_not_mapped`, with `dir=` and a `hint=` naming the command that
maps it.
@@ -85,6 +123,44 @@ which value it ignored, on stderr, when a person is there to read it.
is a wire detail and is translated on the way out, so a consumer never sees
both.)
+### Every candidate at once (`--all`)
+
+`callers`, `callees` and `impact` take `--all`: an ambiguous name is answered
+for every listed candidate (exit 0) instead of exiting 2. Edge rows are one
+union, paged by `--limit`/`--offset`, and each carries the candidate it belongs
+to; json has `resolutionMode: "all"`, a `candidates` list and `candidate` on
+each row:
+
+```
+callers target=handle shown=3 total=3 resolved=3 candidates=2
+candidate n=1 name=handle kind=function path=src/a.ts id=1111aaaa
+candidate n=2 name=handle kind=function path=src/b.ts id=2222bbbb
+ref name=route kind=function path=src/server.ts lines=10-30 candidate=1
+ref name=retry kind=function path=src/jobs.ts lines=4-9 candidate=2
+```
+
+`impact --all` prints one analysis per candidate, each after its `candidate`
+record (json: `results: [{ candidate, ... }]`). Tied candidates past the 8 an
+ambiguity error lists are covered too (those 8 keep their `--pick` numbers; the
+rest follow, and `--pick <n>` reaches them by the same numbers), up to 25 per
+call: past that, only the first 25 are answered and a `candidates_truncated`
+diagnostic says so. An import of the name (`from app.utils import clamp`) is listed in
+an ambiguity but skipped by `--all` when a definition is listed too, so the
+numbers can skip it; when only imports are listed, they are answered. The search window is bounded (up to 200 names with `--path`, fewer
+without); the same diagnostic says when it was cut off. Narrow
+with `--kind` or `--path` to keep the run small. `--pick` takes precedence over
+`--all`.
+
+### Several targets (`ix locate a b c`, `ix callers a b c`)
+
+Each target is answered as it would be alone, grouped: llm opens each group
+with `target n=<i> name=<t>` and ends with
+`targets total=<n> ok=<n> [ambiguous=<n>] [not_found=<n>] [not_mapped=<n>] [failed=<n>]`;
+json is `{ targets: [{ target, exitCode, ...answer }], summary }`. The run exits
+with the worst target's code (error, then workspace not mapped, then not
+found, then ambiguous), so a partial answer never exits 0. The summary counts
+each target by its outcome, so it reads the same under `IX_LEGACY_EXIT_CODES=1`.
+
### Resolution notices (exit 0)
When a target resolves by choosing among equal candidates, or by a fuzzy match,
@@ -103,7 +179,8 @@ 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
+selects among the tied candidates, the listed ones first and the rest in the
+order `--all` numbers them; 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
diff --git a/ix-cli/src/cli/__tests__/agent-outcomes.test.ts b/ix-cli/src/cli/__tests__/agent-outcomes.test.ts
new file mode 100644
index 00000000..41ecf650
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/agent-outcomes.test.ts
@@ -0,0 +1,617 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Command } from "commander";
+import { ALL_CONCURRENCY, registerCallersCommand } from "../commands/callers.js";
+import { registerExplainCommand } from "../commands/explain.js";
+import { registerImpactCommand } from "../commands/impact.js";
+import { registerLocateCommand } from "../commands/locate.js";
+import { WorkspaceNotMappedError, renderCliError, setErrorFormat } from "../errors.js";
+import { LEGACY_EXIT_CODES_ENV, exitCodeFor, worseExitCode } from "../outcome.js";
+import { ALL_CANDIDATE_CAP } from "../resolve.js";
+
+// The outcome contract an agent routes on (outcome.ts): 0 results, 2 ambiguous
+// (candidates returned), 3 not found (suggestions), 4 workspace not mapped,
+// 1 a real error -- the same in every graph command, and the same slug in
+// json `error` and llm `error code=`.
+
+vi.mock("../bootstrap.js", async (orig) => ({
+ ...(await orig<typeof import("../bootstrap.js")>()),
+ resolveWorkspaceId: () => "ws-test",
+}));
+
+const { search, expand, resolvePrefix } = vi.hoisted(() => ({ search: vi.fn(), expand: vi.fn(), resolvePrefix: vi.fn() }));
+
+vi.mock("../../client/api.js", () => ({
+ IxClient: class {
+ async workspaceSystem() { return { systemId: null }; }
+ async search(...args: unknown[]) { return search(...args); }
+ async expand(...args: unknown[]) { return expand(...args); }
+ async resolvePrefix(...args: unknown[]) { return resolvePrefix(...args); }
+ async entity(id: string) {
+ return { node: { id, kind: "function", name: id, attrs: { line_start: 1, line_end: 2 }, provenance: { sourceUri: `src/${id}.ts` } } };
+ }
+ },
+}));
+
+vi.mock("../config.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../config.js")>(),
+ readStitchScope: () => undefined,
+ writeStitchScope: vi.fn(),
+}));
+
+vi.mock("../hierarchy.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../hierarchy.js")>(),
+ getSystemPath: async () => [],
+ getEffectiveSystemPath: async () => [],
+ bucketByHierarchy: async () => [],
+}));
+
+// The probe itself is covered by miss-reason.test.ts; here, only that its
+// answer reaches every command's miss.
+vi.mock("../miss-reason.js", () => ({
+ missProbeWouldRun: () => true,
+ explainSymbolMiss: async (_client: unknown, symbol: string) => symbol === "NotIndexed"
+ ? {
+ reason: "symbol_file_not_indexed",
+ message: '"NotIndexed" is not in the graph, but it appears in src/gen.go, which has not been indexed.',
+ files: ["src/gen.go"],
+ }
+ : null,
+}));
+
+const DUPLICATES = [
+ { 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 UNIQUE = [{ id: "only-id", kind: "function", name: "Unique", provenance: { sourceUri: "src/only.ts" } }];
+
+/** search() answers by term, so one run can mix hits, misses and ties. */
+function graph(byName: Record<string, unknown[]>): void {
+ search.mockImplementation(async (term: string) => byName[term] ?? []);
+}
+
+async function run(args: string[]): Promise<{ stdout: string; stderr: string; exitCode: number }> {
+ const program = new Command().name("ix").exitOverride();
+ registerCallersCommand(program);
+ registerImpactCommand(program);
+ registerLocateCommand(program);
+ registerExplainCommand(program);
+ const stdout: string[] = [];
+ const stderr: string[] = [];
+ const log = vi.spyOn(console, "log").mockImplementation((...parts) => { stdout.push(parts.join(" ")); });
+ const error = vi.spyOn(console, "error").mockImplementation((...parts) => { stderr.push(parts.join(" ")); });
+ const write = vi.spyOn(process.stderr, "write").mockImplementation(((part: string) => {
+ stderr.push(String(part).replace(/\n$/, ""));
+ return true;
+ }) as never);
+ process.exitCode = undefined;
+ try {
+ await program.parseAsync(args, { from: "user" });
+ } finally {
+ log.mockRestore();
+ error.mockRestore();
+ write.mockRestore();
+ }
+ const exitCode = Number(process.exitCode ?? 0);
+ return { stdout: stdout.join("\n"), stderr: stderr.join("\n"), exitCode };
+}
+
+let savedExitCode: typeof process.exitCode;
+beforeEach(() => {
+ savedExitCode = process.exitCode;
+ delete process.env[LEGACY_EXIT_CODES_ENV];
+ graph({ Duplicate: DUPLICATES, Unique: UNIQUE });
+ expand.mockReset().mockImplementation(async (id: string, opts: { direction: string }) => ({
+ nodes: [
+ { id: `${opts.direction}-of-${id}`, kind: "function", name: `${opts.direction === "in" ? "callerOf" : "calleeOf"}_${id}`, provenance: { sourceUri: `src/${id}-user.ts` } },
+ // Reached from every candidate: one row per candidate, each tagged.
+ { id: "shared-id", kind: "function", name: "shared", provenance: { sourceUri: "src/shared.ts" } },
+ ],
+ edges: [],
+ }));
+});
+afterEach(() => {
+ process.exitCode = savedExitCode;
+ delete process.env[LEGACY_EXIT_CODES_ENV];
+});
+
+const COMMANDS = ["locate", "callers", "callees", "impact", "explain"] as const;
+
+describe.each(COMMANDS)("ix %s outcome codes", (command) => {
+ it("exits 3 with unresolved_target for a name that is not in the graph", async () => {
+ const json = await run([command, "Missing", "--format", "json"]);
+ expect(json.exitCode).toBe(3);
+ expect(JSON.parse(json.stdout).error).toBe("unresolved_target");
+
+ const llm = await run([command, "Missing", "--format", "llm"]);
+ expect(llm.exitCode).toBe(3);
+ expect(llm.stdout).toMatch(/^error code=unresolved_target /);
+
+ const text = await run([command, "Missing"]);
+ expect(text.exitCode).toBe(3);
+ });
+
+ it("exits 2 with ambiguous_target and the candidates for a shared name", async () => {
+ const json = await run([command, "Duplicate", "--format", "json"]);
+ expect(json.exitCode).toBe(2);
+ const body = JSON.parse(json.stdout);
+ // locate's record was never an `error` (string-`error` readers treat it as
+ // a failure and drop the candidates): its slug rides in `code`.
+ if (command === "locate") {
+ expect(body.code).toBe("ambiguous_target");
+ expect(body.error).toBeUndefined();
+ } else {
+ expect(body.error).toBe("ambiguous_target");
+ }
+ expect(body.candidates.map((c: { id: string }) => c.id)).toEqual(["first-id", "second-id"]);
+
+ const llm = await run([command, "Duplicate", "--format", "llm"]);
+ expect(llm.exitCode).toBe(2);
+ expect(llm.stdout).toMatch(/^error code=ambiguous_target /);
+ expect(llm.stdout).toContain("candidate n=2 name=Duplicate");
+ });
+
+ it("collapses every non-zero outcome to 1 under IX_LEGACY_EXIT_CODES=1", async () => {
+ process.env[LEGACY_EXIT_CODES_ENV] = "1";
+ expect((await run([command, "Missing", "--format", "json"])).exitCode).toBe(1);
+ expect((await run([command, "Duplicate", "--format", "json"])).exitCode).toBe(1);
+ });
+});
+
+describe.each(["locate", "callers", "callees", "impact"] as const)("ix %s on a target that resolves", (command) => {
+ it("exits 0", async () => {
+ const result = await run([command, "Unique", "--format", "json"]);
+ expect(result.exitCode).toBe(0);
+ expect(JSON.parse(result.stdout).error).toBeUndefined();
+ });
+});
+
+describe("ambiguity hints name --all where it applies", () => {
+ it("callers offers --all; locate does not", async () => {
+ expect((await run(["callers", "Duplicate", "--format", "llm"])).stdout).toMatch(/hint text=".*--all/);
+ expect((await run(["locate", "Duplicate", "--format", "llm"])).stdout).not.toContain("--all");
+ });
+});
+
+class ExitCalled extends Error {
+ constructor(readonly code: number) { super(`exit ${code}`); }
+}
+
+describe("workspace not mapped", () => {
+ it("exits 4 with workspace_not_mapped in json and llm, and 1 under the legacy switch", () => {
+ // process.exit ends the run; the mock throws so nothing after it runs.
+ const exit = vi.spyOn(process, "exit").mockImplementation(((code: number) => { throw new ExitCalled(code); }) as never);
+ const render = (err: unknown) => { try { renderCliError(err); } catch (e) { if (!(e instanceof ExitCalled)) throw e; } };
+ const log = vi.spyOn(console, "log").mockImplementation(() => {});
+ const write = vi.spyOn(process.stderr, "write").mockImplementation((() => true) as never);
+ try {
+ for (const format of ["json", "llm"]) {
+ setErrorFormat(format);
+ render(new WorkspaceNotMappedError("/tmp/elsewhere", "Run `ix map`."));
+ expect(exit).toHaveBeenLastCalledWith(4);
+ }
+ expect(JSON.parse(String(log.mock.calls[0][0])).error).toBe("workspace_not_mapped");
+ expect(String(log.mock.calls[1][0])).toMatch(/^error code=workspace_not_mapped /);
+
+ process.env[LEGACY_EXIT_CODES_ENV] = "1";
+ render(new WorkspaceNotMappedError("/tmp/elsewhere", "Run `ix map`."));
+ expect(exit).toHaveBeenLastCalledWith(1);
+ } finally {
+ setErrorFormat(undefined);
+ exit.mockRestore();
+ log.mockRestore();
+ write.mockRestore();
+ }
+ });
+});
+
+describe("exit code precedence", () => {
+ it("keeps the worst outcome: error > not mapped > not found > ambiguous > ok", () => {
+ expect(worseExitCode(0, 2)).toBe(2);
+ expect(worseExitCode(2, 3)).toBe(3);
+ expect(worseExitCode(3, 2)).toBe(3);
+ expect(worseExitCode(3, 4)).toBe(4);
+ expect(worseExitCode(4, 1)).toBe(1);
+ expect(worseExitCode(1, 3)).toBe(1);
+ });
+
+ it("maps outcomes to their codes", () => {
+ expect([exitCodeFor("ambiguous"), exitCodeFor("not_found"), exitCodeFor("not_mapped")]).toEqual([2, 3, 4]);
+ process.env[LEGACY_EXIT_CODES_ENV] = "true";
+ expect([exitCodeFor("ambiguous"), exitCodeFor("not_found"), exitCodeFor("not_mapped")]).toEqual([1, 1, 1]);
+ process.env[LEGACY_EXIT_CODES_ENV] = "0";
+ expect(exitCodeFor("not_found")).toBe(3);
+ });
+});
+
+describe("--all on an ambiguous target", () => {
+ it.each(["callers", "callees"] as const)("%s: unions every candidate's rows, each tagged with its candidate (json)", async (command) => {
+ const result = await run([command, "Duplicate", "--all", "--format", "json"]);
+ expect(result.exitCode).toBe(0);
+ const body = JSON.parse(result.stdout);
+ expect(body.error).toBeUndefined();
+ expect(body.resolutionMode).toBe("all");
+ expect(body.candidates).toEqual([
+ { n: 1, id: "first-id", name: "Duplicate", kind: "function", path: "src/first.ts" },
+ { n: 2, id: "second-id", name: "Duplicate", kind: "function", path: "src/second.ts" },
+ ]);
+ const prefix = command === "callers" ? "callerOf" : "calleeOf";
+ const rows = body.results.map((r: { name: string; candidate: number }) => `${r.candidate}:${r.name}`).sort();
+ expect(rows).toEqual([`1:${prefix}_first-id`, "1:shared", `2:${prefix}_second-id`, "2:shared"]);
+ expect(body.summary.total).toBe(4);
+ // One query per candidate, never one by name.
+ expect(expand.mock.calls.map(([id]) => id).sort()).toEqual(["first-id", "second-id"]);
+ });
+
+ it("callers: llm lists the candidates and tags every ref", async () => {
+ const result = await run(["callers", "Duplicate", "--all", "--format", "llm"]);
+ expect(result.exitCode).toBe(0);
+ const lines = result.stdout.split("\n");
+ expect(lines[0]).toMatch(/^callers target=Duplicate .*total=4 .*candidates=2/);
+ expect(lines.filter((l) => l.startsWith("candidate "))).toEqual([
+ expect.stringMatching(/^candidate n=1 name=Duplicate kind=function path=src\/first.ts/),
+ expect.stringMatching(/^candidate n=2 name=Duplicate kind=function path=src\/second.ts/),
+ ]);
+ const refs = lines.filter((l) => l.startsWith("ref "));
+ expect(refs).toHaveLength(4);
+ for (const ref of refs) expect(ref).toMatch(/ candidate=[12]$/);
+ });
+
+ it("callers: pages over the union with --limit/--offset", async () => {
+ const first = JSON.parse((await run(["callers", "Duplicate", "--all", "--limit", "3", "--format", "json"])).stdout);
+ const second = JSON.parse((await run(["callers", "Duplicate", "--all", "--limit", "3", "--offset", "3", "--format", "json"])).stdout);
+ expect(first.results).toHaveLength(3);
+ expect(first.summary.nextOffset).toBe(3);
+ expect(second.results).toHaveLength(1);
+ const all = [...first.results, ...second.results].map((r: { candidate: number; name: string }) => `${r.candidate}:${r.name}`);
+ expect(new Set(all).size).toBe(4);
+ });
+
+ it("is plain resolution for a name that resolves, and still a miss for one that does not", async () => {
+ const one = JSON.parse((await run(["callers", "Unique", "--all", "--format", "json"])).stdout);
+ expect(one.resolvedTarget).toMatchObject({ id: "only-id" });
+ expect(one.candidates).toBeUndefined();
+ expect(one.results.every((r: { candidate?: number }) => r.candidate === undefined)).toBe(true);
+
+ const miss = await run(["callers", "Missing", "--all", "--format", "json"]);
+ expect(miss.exitCode).toBe(3);
+ });
+
+ it("--pick wins over --all", async () => {
+ const body = JSON.parse((await run(["callers", "Duplicate", "--all", "--pick", "2", "--format", "json"])).stdout);
+ expect(body.resolvedTarget).toMatchObject({ id: "second-id" });
+ expect(body.candidates).toBeUndefined();
+ });
+
+ const manyNamed = (n: number) => Array.from({ length: n }, (_, i) => ({
+ id: `dup-${String(i).padStart(2, "0")}`, kind: "function", name: "Many", provenance: { sourceUri: `src/m${String(i).padStart(2, "0")}.ts` },
+ }));
+
+ it("covers every tied candidate, not only the 8 an ambiguity lists", async () => {
+ graph({ Many: manyNamed(12) });
+ // Without --all the error still lists 8 of 12.
+ const plain = JSON.parse((await run(["callers", "Many", "--format", "json"])).stdout);
+ expect(plain.candidates).toHaveLength(8);
+ expect(plain.total).toBe(12);
+ expect(Object.keys(plain)).not.toContain("allCandidates");
+
+ expand.mockClear();
+ const body = JSON.parse((await run(["callers", "Many", "--all", "--limit", "100", "--format", "json"])).stdout);
+ expect(body.candidates).toHaveLength(12);
+ // The 8 listed keep the numbers --pick gives them; the rest follow.
+ expect(body.candidates.slice(0, 8).map((c: { id: string }) => c.id))
+ .toEqual(plain.candidates.map((c: { id: string }) => c.id));
+ expect(new Set(expand.mock.calls.map(([id]) => id)).size).toBe(12);
+ expect(body.summary.total).toBe(24);
+ expect((body.diagnostics ?? []).map((d: { code: string }) => d.code)).not.toContain("candidates_truncated");
+ });
+
+ it("lets --pick reach a candidate past the 8 listed by the number --all gave it", async () => {
+ graph({ Many: manyNamed(12) });
+ const all = JSON.parse((await run(["callers", "Many", "--all", "--format", "json"])).stdout);
+ const eleventh = all.candidates.find((c: { n: number }) => c.n === 11);
+ expect(eleventh).toBeDefined();
+
+ const picked = JSON.parse((await run(["callers", "Many", "--pick", "11", "--format", "json"])).stdout);
+ expect(picked.resolvedTarget).toMatchObject({ id: eleventh.id });
+
+ const out = await run(["callers", "Many", "--pick", "13", "--format", "json"]);
+ expect(out.stdout).toContain("--pick 13 is out of range (1-12).");
+ });
+
+ it("keeps at most ALL_CONCURRENCY edge queries in flight", async () => {
+ graph({ Many: manyNamed(12) });
+ const base = expand.getMockImplementation()!;
+ let inFlight = 0;
+ let peak = 0;
+ expand.mockImplementation(async (...args: unknown[]) => {
+ peak = Math.max(peak, ++inFlight);
+ await new Promise((r) => setTimeout(r, 2));
+ inFlight--;
+ return base(...(args as [string, { direction: string }]));
+ });
+ const result = await run(["callers", "Many", "--all", "--format", "json"]);
+ expect(result.exitCode).toBe(0);
+ expect(expand).toHaveBeenCalledTimes(12);
+ expect(peak).toBeLessThanOrEqual(ALL_CONCURRENCY);
+ });
+
+ it("says when the name search itself was cut off", async () => {
+ graph({ Many: manyNamed(60) });
+ const body = JSON.parse((await run(["callers", "Many", "--all", "--limit", "500", "--format", "json"])).stdout);
+ expect(body.candidates.length).toBeGreaterThan(8);
+ expect(body.diagnostics.map((d: { code: string }) => d.code)).toContain("candidates_truncated");
+ });
+
+ it("answers at most ALL_CANDIDATE_CAP candidates and says so", async () => {
+ graph({ Many: manyNamed(ALL_CANDIDATE_CAP + 5) });
+ expand.mockClear();
+ const body = JSON.parse((await run(["callers", "Many", "--all", "--limit", "500", "--format", "json"])).stdout);
+ expect(body.candidates).toHaveLength(ALL_CANDIDATE_CAP);
+ expect(body.candidates.map((c: { n: number }) => c.n)).toEqual(Array.from({ length: ALL_CANDIDATE_CAP }, (_, i) => i + 1));
+ expect(new Set(expand.mock.calls.map(([id]) => id)).size).toBe(ALL_CANDIDATE_CAP);
+ const cut = body.diagnostics.find((d: { code: string }) => d.code === "candidates_truncated");
+ expect(cut.message).toContain(`first ${ALL_CANDIDATE_CAP} of ${ALL_CANDIDATE_CAP + 5}`);
+
+ const impact = JSON.parse((await run(["impact", "Many", "--all", "--format", "json"])).stdout);
+ expect(impact.results).toHaveLength(ALL_CANDIDATE_CAP);
+ expect(impact.diagnostics.map((d: { code: string }) => d.code)).toContain("candidates_truncated");
+
+ // A candidate past the cap is still reachable by its number.
+ const picked = JSON.parse((await run(["callers", "Many", "--pick", String(ALL_CANDIDATE_CAP + 3), "--format", "json"])).stdout);
+ expect(picked.resolvedTarget).toMatchObject({ id: `dup-${ALL_CANDIDATE_CAP + 2}` });
+ });
+
+ // `from app.utils import clamp` is a one-line `module` named clamp: an
+ // ambiguity lists it, but it is not a definition (candidate-origin.ts).
+ const CLAMP_IMPORT = { id: "import-id", kind: "module", name: "clamp", attrs: { line_start: 3, line_end: 3 }, provenance: { sourceUri: "app/pricing.py" } };
+ const CLAMP_DEFS = [
+ { id: "py-id", kind: "function", name: "clamp", attrs: { line_start: 22, line_end: 23 }, provenance: { sourceUri: "app/utils.py" } },
+ { id: "ts-id", kind: "function", name: "clamp", attrs: { line_start: 9, line_end: 11 }, provenance: { sourceUri: "web/src/math.ts" } },
+ ];
+
+ it("skips an import of the name when definitions are listed, keeping --pick numbers", async () => {
+ graph({ clamp: [CLAMP_IMPORT, ...CLAMP_DEFS] });
+ const plain = JSON.parse((await run(["callers", "clamp", "--format", "json"])).stdout);
+ expect(plain.candidates.map((c: { id: string; rank: number }) => [c.rank, c.id]))
+ .toEqual([[1, "import-id"], [2, "py-id"], [3, "ts-id"]]);
+
+ expand.mockClear();
+ const body = JSON.parse((await run(["callers", "clamp", "--all", "--format", "json"])).stdout);
+ expect(body.candidates.map((c: { n: number; path: string }) => [c.n, c.path]))
+ .toEqual([[2, "app/utils.py"], [3, "web/src/math.ts"]]);
+ expect(new Set(body.results.map((r: { candidate: number }) => r.candidate))).toEqual(new Set([2, 3]));
+ expect(expand.mock.calls.map(([id]) => id).sort()).toEqual(["py-id", "ts-id"]);
+ // The skipped import is not a candidate the search cut off.
+ expect((body.diagnostics ?? []).map((d: { code: string }) => d.code)).not.toContain("candidates_truncated");
+
+ const impact = JSON.parse((await run(["impact", "clamp", "--all", "--format", "json"])).stdout);
+ expect(impact.results.map((r: { candidate: number }) => r.candidate)).toEqual([2, 3]);
+ });
+
+ it("still answers for imports when no definition is listed", async () => {
+ const other = { ...CLAMP_IMPORT, id: "import-2", provenance: { sourceUri: "web/src/format.ts" } };
+ graph({ clamp: [CLAMP_IMPORT, other] });
+ const body = JSON.parse((await run(["callers", "clamp", "--all", "--format", "json"])).stdout);
+ expect(body.candidates.map((c: { n: number; id: string }) => [c.n, c.id])).toEqual([[1, "import-id"], [2, "import-2"]]);
+ });
+
+ it("impact: one analysis per candidate, tagged (json and llm)", async () => {
+ const json = await run(["impact", "Duplicate", "--all", "--format", "json"]);
+ expect(json.exitCode).toBe(0);
+ const body = JSON.parse(json.stdout);
+ expect(body).toMatchObject({ target: "Duplicate", resolutionMode: "all" });
+ expect(body.candidates.map((c: { id: string }) => c.id)).toEqual(["first-id", "second-id"]);
+ expect(body.results.map((r: { candidate: number; resolvedTarget: { name: string } }) => [r.candidate, r.resolvedTarget.name]))
+ .toEqual([[1, "Duplicate"], [2, "Duplicate"]]);
+ // Each analysis read its own candidate's edges.
+ const ids = new Set(expand.mock.calls.map(([id]) => id));
+ expect(ids.has("first-id") && ids.has("second-id")).toBe(true);
+
+ const llm = await run(["impact", "Duplicate", "--all", "--format", "llm"]);
+ expect(llm.exitCode).toBe(0);
+ const lines = llm.stdout.split("\n");
+ expect(lines[0]).toBe("impact_all target=Duplicate candidates=2 total=2");
+ const firstCandidate = lines.findIndex((l) => l.startsWith("candidate n=1"));
+ const secondCandidate = lines.findIndex((l) => l.startsWith("candidate n=2"));
+ expect(firstCandidate).toBeGreaterThan(0);
+ expect(secondCandidate).toBeGreaterThan(firstCandidate + 1);
+ });
+});
+
+describe("several targets in one call", () => {
+ it("locate: json groups per target, with each target's own exit code; the run exits with the worst", async () => {
+ const result = await run(["locate", "Unique", "Duplicate", "Missing", "--format", "json"]);
+ expect(result.exitCode).toBe(3);
+ const body = JSON.parse(result.stdout);
+ expect(body.targets.map((t: { target: string; exitCode: number }) => [t.target, t.exitCode]))
+ .toEqual([["Unique", 0], ["Duplicate", 2], ["Missing", 3]]);
+ expect(body.targets[0].resolvedTarget).toMatchObject({ id: "only-id" });
+ expect(body.targets[1].code).toBe("ambiguous_target");
+ expect(body.targets[1].error).toBeUndefined();
+ expect(body.targets[2].error).toBe("unresolved_target");
+ expect(body.summary).toEqual({ total: 3, ok: 1, ambiguous: 1, notFound: 1, notMapped: 0, failed: 0 });
+ });
+
+ it("the summary counts an unmapped target as not mapped, and a miss the same under the legacy switch", async () => {
+ const base = search.getMockImplementation()!;
+ search.mockImplementation(async (term: string, ...rest: unknown[]) => {
+ if (term === "Elsewhere") throw new WorkspaceNotMappedError("/tmp/elsewhere", "Run `ix map`.");
+ return base(term, ...rest);
+ });
+ const json = await run(["locate", "Unique", "Elsewhere", "Missing", "--format", "json"]);
+ expect(json.exitCode).toBe(4);
+ const body = JSON.parse(json.stdout);
+ // The same fields as the one-target record (errors.ts renderCliError), `dir` included.
+ expect(body.targets[1]).toMatchObject({ target: "Elsewhere", exitCode: 4, error: "workspace_not_mapped", dir: "/tmp/elsewhere", next: "Run `ix map`." });
+ expect(body.summary).toEqual({ total: 3, ok: 1, ambiguous: 0, notFound: 1, notMapped: 1, failed: 0 });
+ const llm = await run(["locate", "Unique", "Elsewhere", "--format", "llm"]);
+ expect(llm.stdout).toMatch(/^error code=workspace_not_mapped .* dir=\/tmp\/elsewhere hint=/m);
+ expect(llm.stdout.split("\n").pop()).toBe("targets total=2 ok=1 not_mapped=1");
+
+ // Every miss exits 1 under the switch; the summary still tells them apart.
+ process.env[LEGACY_EXIT_CODES_ENV] = "1";
+ const legacy = await run(["locate", "Unique", "Duplicate", "Missing", "Elsewhere", "--format", "json"]);
+ expect(legacy.exitCode).toBe(1);
+ const legacyBody = JSON.parse(legacy.stdout);
+ expect(legacyBody.targets.map((t: { exitCode: number }) => t.exitCode)).toEqual([0, 1, 1, 1]);
+ expect(legacyBody.summary).toEqual({ total: 4, ok: 1, ambiguous: 1, notFound: 1, notMapped: 1, failed: 0 });
+ });
+
+ it("callers: llm opens each group with a target record and ends with a summary", async () => {
+ const result = await run(["callers", "Unique", "Duplicate", "--format", "llm"]);
+ expect(result.exitCode).toBe(2);
+ const lines = result.stdout.split("\n");
+ expect(lines[0]).toBe("target n=1 name=Unique");
+ expect(lines[1]).toMatch(/^callers target=Unique /);
+ const second = lines.indexOf("target n=2 name=Duplicate");
+ expect(second).toBeGreaterThan(1);
+ expect(lines[second + 1]).toMatch(/^error code=ambiguous_target /);
+ expect(lines[lines.length - 1]).toBe("targets total=2 ok=1 ambiguous=1");
+ });
+
+ it("callers: every target answered exits 0, with one group each", async () => {
+ graph({ Unique: UNIQUE, Other: [{ id: "other-id", kind: "function", name: "Other", provenance: { sourceUri: "src/other.ts" } }] });
+ const result = await run(["callers", "Unique", "Other", "--format", "json"]);
+ expect(result.exitCode).toBe(0);
+ const body = JSON.parse(result.stdout);
+ expect(body.targets.map((t: { resolvedTarget: { id: string } }) => t.resolvedTarget.id)).toEqual(["only-id", "other-id"]);
+ expect(body.targets[1].results.map((r: { name: string }) => r.name)).toContain("callerOf_other-id");
+ });
+
+ it("a target whose query throws gets its own error group; the others still answer", async () => {
+ graph({ Unique: UNIQUE, Other: [{ id: "other-id", kind: "function", name: "Other", provenance: { sourceUri: "src/other.ts" } }] });
+ const base = expand.getMockImplementation()!;
+ expand.mockImplementation(async (...args: unknown[]) => {
+ if (args[0] === "only-id") throw new Error('500: {"error":"query_failed","message":"backend broke"}');
+ return base(...(args as [string, { direction: string }]));
+ });
+ const json = await run(["callers", "Unique", "Other", "--format", "json"]);
+ expect(json.exitCode).toBe(1);
+ const body = JSON.parse(json.stdout);
+ expect(body.targets[0]).toMatchObject({ target: "Unique", exitCode: 1, error: "query_failed", message: "backend broke" });
+ expect(body.targets[1]).toMatchObject({ target: "Other", exitCode: 0 });
+ expect(body.targets[1].results.map((r: { name: string }) => r.name)).toContain("callerOf_other-id");
+ expect(body.summary).toEqual({ total: 2, ok: 1, ambiguous: 0, notFound: 0, notMapped: 0, failed: 1 });
+
+ const llm = await run(["callers", "Unique", "Other", "--format", "llm"]);
+ expect(llm.exitCode).toBe(1);
+ const lines = llm.stdout.split("\n");
+ expect(lines[1]).toMatch(/^error code=query_failed /);
+ expect(lines).toContain("target n=2 name=Other");
+ expect(lines[lines.length - 1]).toBe("targets total=2 ok=1 failed=1");
+ });
+
+ it("text: a header per target", async () => {
+ const result = await run(["locate", "Unique", "Missing"]);
+ expect(result.exitCode).toBe(3);
+ expect(result.stdout).toContain("── Unique ──");
+ expect(result.stdout).toContain("── Missing ──");
+ });
+
+ it("one target prints exactly what it always did", async () => {
+ const result = await run(["locate", "Unique", "--format", "json"]);
+ expect(JSON.parse(result.stdout).targets).toBeUndefined();
+ });
+});
+
+describe("locate misses carry the fields every miss carries", () => {
+ it("suggestions for a near name, in json and llm", async () => {
+ search.mockImplementation(async (term: string) => (term === "Uniqu" ? [] : UNIQUE));
+ const json = JSON.parse((await run(["locate", "Uniqu", "--format", "json"])).stdout);
+ expect(json.error).toBe("unresolved_target");
+ expect(json.suggestions?.map((s: { name: string }) => s.name)).toEqual(["Unique"]);
+ const llm = (await run(["locate", "Uniqu", "--format", "llm"])).stdout;
+ expect(llm).toContain("suggestion n=1 name=Unique");
+ });
+});
+
+describe.each(COMMANDS)("ix %s says why a name is not in the graph", (command) => {
+ it("json carries reason, files and the message; llm the reason; text the message", async () => {
+ const json = await run([command, "NotIndexed", "--format", "json"]);
+ expect(json.exitCode).toBe(3);
+ expect(JSON.parse(json.stdout)).toMatchObject({
+ error: "unresolved_target",
+ reason: "symbol_file_not_indexed",
+ message: expect.stringContaining("src/gen.go, which has not been indexed"),
+ });
+ expect(JSON.parse(json.stdout).files).toEqual(["src/gen.go"]);
+
+ const llm = await run([command, "NotIndexed", "--format", "llm"]);
+ expect(llm.stdout).toMatch(/^error code=unresolved_target .*reason=symbol_file_not_indexed/);
+
+ const text = await run([command, "NotIndexed"]);
+ expect(text.stderr).toContain("src/gen.go, which has not been indexed");
+ });
+});
+
+describe("an id lookup the backend could not answer", () => {
+ const RAW_ID = "12345678-1234-1234-1234-123456789abc";
+
+ it("is a real error, not a missing symbol", async () => {
+ const { resolveFileOrEntityFull } = await import("../resolve.js");
+ const down = { entity: async () => { throw new Error("fetch failed: connect ECONNREFUSED 127.0.0.1:8090"); } };
+ await expect(resolveFileOrEntityFull(down as never, RAW_ID, { format: "json" })).rejects.toThrow(/ECONNREFUSED/);
+ const failing = { entity: async () => { throw new Error("500: internal error"); } };
+ await expect(resolveFileOrEntityFull(failing as never, RAW_ID, { format: "json" })).rejects.toThrow(/^500:/);
+ });
+
+ it("is a miss only when the backend says the id does not exist", async () => {
+ const { resolveFileOrEntityFull, isLookupMiss } = await import("../resolve.js");
+ const absent = { entity: async () => { throw new Error("404: not found"); } };
+ expect(await resolveFileOrEntityFull(absent as never, RAW_ID, { format: "json" })).toEqual({ resolved: false, ambiguous: false });
+ expect(isLookupMiss(new Error("No entity found for prefix: abcd1234"))).toBe(true);
+ expect(isLookupMiss(new Error("401: unauthorized"))).toBe(false);
+ });
+
+ it("is a miss when the backend answers 200 without a node", async () => {
+ const { resolveFileOrEntityFull } = await import("../resolve.js");
+ for (const body of [{ node: null }, {}, null]) {
+ const empty = { entity: async () => body };
+ expect(await resolveFileOrEntityFull(empty as never, RAW_ID, { format: "json" })).toEqual({ resolved: false, ambiguous: false });
+ }
+ });
+
+ it("a hex-looking name falls through to the name search whatever the prefix lookup answers", async () => {
+ graph({ deadbeef: [{ id: "beef-id", kind: "function", name: "deadbeef", provenance: { sourceUri: "src/beef.ts" } }] });
+ const { resolveFileOrEntityFull } = await import("../resolve.js");
+ for (const status of ["403: forbidden", "405: method not allowed", "502: <html>bad gateway</html>"]) {
+ resolvePrefix.mockReset().mockRejectedValue(new Error(status));
+ const { IxClient } = await import("../../client/api.js");
+ const result = await resolveFileOrEntityFull(new (IxClient as any)(), "deadbeef", { format: "json" });
+ expect(result).toMatchObject({ resolved: true, entity: { id: "beef-id" } });
+ }
+ const down = Object.assign(new Error("fetch failed"), { cause: { code: "ECONNREFUSED" } });
+ resolvePrefix.mockReset().mockRejectedValue(down);
+ const { IxClient } = await import("../../client/api.js");
+ await expect(resolveFileOrEntityFull(new (IxClient as any)(), "deadbeef", { format: "json" })).rejects.toThrow(/fetch failed/);
+ });
+});
+
+describe("subsystems and around carry the same outcome codes as their slugs", () => {
+ it("subsystems: an ambiguous region exits 2, an unknown one 3, any other error 1", async () => {
+ const { setSubsystemErrorExit } = await import("../commands/subsystems.js");
+ const exitFor = (body: unknown) => { process.exitCode = undefined; setSubsystemErrorExit(body); return Number(process.exitCode); };
+ expect(exitFor({ error: "ambiguous_target", target_query: "api", candidates: [] })).toBe(2);
+ expect(exitFor({ error: "unknown_target", message: "No region api", suggestions: [] })).toBe(3);
+ expect(exitFor({ error: "query_failed" })).toBe(1);
+ process.env[LEGACY_EXIT_CODES_ENV] = "1";
+ expect(exitFor({ error: "ambiguous_target", target_query: "api", candidates: [] })).toBe(1);
+ });
+
+ it("around: a file not in the graph exits 3, a bad argument 1", async () => {
+ const { reportError } = await import("../commands/around.js");
+ const log = vi.spyOn(console, "log").mockImplementation(() => {});
+ try {
+ process.exitCode = undefined;
+ reportError("unresolved_target", "not in the graph", "llm", [["reason", "file_not_in_graph"]]);
+ expect(process.exitCode).toBe(3);
+ process.exitCode = undefined;
+ reportError("invalid_line_range", "bad range", "llm");
+ expect(process.exitCode).toBe(1);
+ } finally {
+ log.mockRestore();
+ }
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/callers-text-fallback-paging.test.ts b/ix-cli/src/cli/__tests__/callers-text-fallback-paging.test.ts
index c1c54ecc..193e7713 100644
--- a/ix-cli/src/cli/__tests__/callers-text-fallback-paging.test.ts
+++ b/ix-cli/src/cli/__tests__/callers-text-fallback-paging.test.ts
@@ -20,6 +20,7 @@ vi.mock("../../client/factory.js", () => ({
vi.mock("../resolve.js", async (importOriginal) => ({
...await importOriginal<typeof import("../resolve.js")>(),
resolveFileOrReport: async () => ({ id: "11111111-0000-0000-0000-000000000000", kind: "function", name: "foo", resolutionMode: "exact" }),
+ resolveTargetSetOrReport: async () => ({ entities: [{ id: "11111111-0000-0000-0000-000000000000", kind: "function", name: "foo", resolutionMode: "exact" }] }),
printResolved: () => {},
}));
vi.mock("../graph-health.js", async (importOriginal) => ({
diff --git a/ix-cli/src/cli/__tests__/callers-text-fallback-snippet-cap.test.ts b/ix-cli/src/cli/__tests__/callers-text-fallback-snippet-cap.test.ts
index c73dc538..a401ca2e 100644
--- a/ix-cli/src/cli/__tests__/callers-text-fallback-snippet-cap.test.ts
+++ b/ix-cli/src/cli/__tests__/callers-text-fallback-snippet-cap.test.ts
@@ -20,6 +20,7 @@ vi.mock("../../client/factory.js", () => ({
vi.mock("../resolve.js", async (importOriginal) => ({
...await importOriginal<typeof import("../resolve.js")>(),
resolveFileOrReport: async () => ({ id: "11111111-0000-0000-0000-000000000000", kind: "function", name: "foo", resolutionMode: "exact" }),
+ resolveTargetSetOrReport: async () => ({ entities: [{ id: "11111111-0000-0000-0000-000000000000", kind: "function", name: "foo", resolutionMode: "exact" }] }),
printResolved: () => {},
}));
vi.mock("../graph-health.js", async (importOriginal) => ({
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 8af408d6..04a70f49 100644
--- a/ix-cli/src/cli/__tests__/diff-unresolved-target.test.ts
+++ b/ix-cli/src/cli/__tests__/diff-unresolved-target.test.ts
@@ -89,6 +89,6 @@ describe("ix diff — unresolved target", () => {
it("exits non-zero for an unresolved target", async () => {
await run(["diff", "3", "5", "DefinitelyMissing", "--format", "json"]);
- expect(process.exitCode).toBe(1);
+ expect(process.exitCode).toBe(3);
});
});
diff --git a/ix-cli/src/cli/__tests__/edge-server-cap.test.ts b/ix-cli/src/cli/__tests__/edge-server-cap.test.ts
index 5b6ede6e..d17b9221 100644
--- a/ix-cli/src/cli/__tests__/edge-server-cap.test.ts
+++ b/ix-cli/src/cli/__tests__/edge-server-cap.test.ts
@@ -21,6 +21,7 @@ vi.mock("../../client/factory.js", () => ({
vi.mock("../resolve.js", async (importOriginal) => ({
...await importOriginal<typeof import("../resolve.js")>(),
resolveFileOrReport: async () => ({ id: "11111111-0000-0000-0000-000000000000", kind: "class", name: "Big", resolutionMode: "exact" }),
+ resolveTargetSetOrReport: async () => ({ entities: [{ id: "11111111-0000-0000-0000-000000000000", kind: "class", name: "Big", resolutionMode: "exact" }] }),
printResolved: () => {},
}));
diff --git a/ix-cli/src/cli/__tests__/impact-leaf-limit-wiring.test.ts b/ix-cli/src/cli/__tests__/impact-leaf-limit-wiring.test.ts
index c2c0f503..305ad5b7 100644
--- a/ix-cli/src/cli/__tests__/impact-leaf-limit-wiring.test.ts
+++ b/ix-cli/src/cli/__tests__/impact-leaf-limit-wiring.test.ts
@@ -19,6 +19,7 @@ vi.mock("../../client/factory.js", () => ({
vi.mock("../resolve.js", async (importOriginal) => ({
...await importOriginal<typeof import("../resolve.js")>(),
resolveFileOrReport: async () => ({ id: "11111111-0000-0000-0000-000000000000", kind: "function", name: "verify", resolutionMode: "exact" }),
+ resolveTargetSetOrReport: async () => ({ entities: [{ id: "11111111-0000-0000-0000-000000000000", kind: "function", name: "verify", resolutionMode: "exact" }] }),
printResolved: () => {},
}));
vi.mock("../graph-health.js", async (importOriginal) => ({
diff --git a/ix-cli/src/cli/__tests__/miss-reason.test.ts b/ix-cli/src/cli/__tests__/miss-reason.test.ts
new file mode 100644
index 00000000..f5c8d28c
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/miss-reason.test.ts
@@ -0,0 +1,238 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { execFileSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+const workspace = vi.hoisted(() => ({ root: "" }));
+
+vi.mock("../config.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../config.js")>(),
+ resolveWorkspaceRoot: () => workspace.root,
+}));
+
+const { explainSymbolMiss, MISS_PROBE_ENV } = await import("../miss-reason.js");
+const { runWithSignal } = await import("../../client/run-signal.js");
+const { withMissReason } = await import("../resolve.js");
+
+const hasRipgrep = (() => {
+ try { execFileSync("rg", ["--version"], { stdio: "ignore" }); return true; } catch { return false; }
+})();
+
+/** A client whose graph holds exactly these files. */
+function client(indexed: Array<{ uri: string; rev?: number }>) {
+ return {
+ search: vi.fn(async (term: string): Promise<any[]> => indexed
+ .filter((f) => f.uri.split("/").pop() === term)
+ .map((f) => ({ id: `id-${f.uri}`, kind: "file", name: term, createdRev: f.rev, provenance: { sourceUri: f.uri } }))),
+ };
+}
+
+describe.skipIf(!hasRipgrep)("explainSymbolMiss", () => {
+ let savedHome: string | undefined;
+
+ beforeAll(() => {
+ workspace.root = mkdtempSync(join(tmpdir(), "ix-miss-reason-"));
+ mkdirSync(join(workspace.root, "src"));
+ writeFileSync(join(workspace.root, "src", "indexed.ts"), "export const x = 1;\nfunction helper() { return parseWidget; }\n");
+ writeFileSync(join(workspace.root, "src", "skipped.go"), "package main\nfunc renderGadget() {}\n");
+ // Sorted ahead of src/: an unindexed source file, and a file Ix never parses.
+ mkdirSync(join(workspace.root, "aaa"));
+ writeFileSync(join(workspace.root, "aaa", "early.go"), "package aaa\n// see frobnicate\n");
+ writeFileSync(join(workspace.root, "aaa", "notes.txt"), "frobnicate and onlyInProse\n");
+ writeFileSync(join(workspace.root, "src", "late.ts"), "const s = \"frobnicate\";\n");
+ // A dot-directory `ix map` parses, and one it skips (file-discovery.ts SKIPPED_DIRS).
+ mkdirSync(join(workspace.root, ".storybook"));
+ writeFileSync(join(workspace.root, ".storybook", "preview.ts"), "export const storybookOnlyName = 1;\n");
+ mkdirSync(join(workspace.root, ".venv", "lib"), { recursive: true });
+ writeFileSync(join(workspace.root, ".venv", "lib", "site.py"), "venvOnlyName = 1\n");
+ });
+
+ afterAll(() => {
+ rmSync(workspace.root, { recursive: true, force: true });
+ });
+
+ beforeEach(() => {
+ process.env[MISS_PROBE_ENV] = "1";
+ savedHome = process.env.IX_HOME;
+ process.env.IX_HOME = join(workspace.root, ".ix-home");
+ });
+
+ afterEach(() => {
+ process.env[MISS_PROBE_ENV] = "0";
+ if (savedHome === undefined) delete process.env.IX_HOME;
+ else process.env.IX_HOME = savedHome;
+ });
+
+ it("names a file the graph never indexed", async () => {
+ const why = await explainSymbolMiss(client([{ uri: "src/indexed.ts", rev: 7 }]), "renderGadget", {});
+ expect(why).toMatchObject({ reason: "symbol_file_not_indexed", files: ["src/skipped.go"] });
+ expect(why?.message).toContain("src/skipped.go, which has not been indexed");
+ });
+
+ it("names the indexed file and its revision when the name was not extracted", async () => {
+ const why = await explainSymbolMiss(client([{ uri: "src/indexed.ts", rev: 7 }]), "parseWidget", {});
+ expect(why).toMatchObject({ reason: "symbol_not_extracted", files: ["src/indexed.ts"] });
+ expect(why?.message).toContain("src/indexed.ts (indexed at rev 7)");
+ });
+
+ it("matches an absolute source uri by its workspace-relative suffix", async () => {
+ const why = await explainSymbolMiss(client([{ uri: `${workspace.root}/src/indexed.ts` }]), "parseWidget", {});
+ expect(why?.reason).toBe("symbol_not_extracted");
+ });
+
+ it("says when the name is nowhere in the workspace either", async () => {
+ const why = await explainSymbolMiss(client([]), "NoSuchNameAnywhere", {});
+ expect(why).toMatchObject({ reason: "symbol_not_in_source" });
+ });
+
+ it("reads the last segment of a qualified name, and honours --path", async () => {
+ expect((await explainSymbolMiss(client([]), "Widget.renderGadget", {}))?.reason).toBe("symbol_file_not_indexed");
+ expect((await explainSymbolMiss(client([]), "renderGadget", { path: "lib/" }))?.reason).toBe("symbol_not_in_source");
+ });
+
+ it("searches the dot-directories ix map parses, not the ones it skips", async () => {
+ const why = await explainSymbolMiss(client([]), "storybookOnlyName", {});
+ expect(why).toMatchObject({ reason: "symbol_file_not_indexed", files: [".storybook/preview.ts"] });
+ expect((await explainSymbolMiss(client([]), "venvOnlyName", {}))?.reason).toBe("symbol_not_in_source");
+ });
+
+ it("is skipped by IX_MISS_PROBE=0, and for a target that is not a name", async () => {
+ expect(await explainSymbolMiss(client([]), "a b", {})).toBeNull();
+ process.env[MISS_PROBE_ENV] = "0";
+ expect(await explainSymbolMiss(client([]), "renderGadget", {})).toBeNull();
+ });
+
+ it("asks for the file by path (scope), so same-named files elsewhere cannot crowd it out", async () => {
+ const c = client([{ uri: "src/indexed.ts", rev: 7 }]);
+ await explainSymbolMiss(c, "parseWidget", {});
+ expect(c.search).toHaveBeenCalledWith("indexed.ts", expect.objectContaining({ scope: "src/indexed.ts", kind: "file" }));
+ });
+
+ it("does not claim a file was never indexed when a full window (an older backend ignoring scope) lacks it", async () => {
+ // 51 same-named files, the indexed one last: a backend without `scope`
+ // returns the first 50 and the target is not among them.
+ const crowd = Array.from({ length: 51 }, (_, i) => ({ uri: i === 50 ? "src/skipped.go" : `vendor/p${i}/skipped.go` }));
+ const all = client(crowd);
+ const windowed = { search: vi.fn(async (term: string, opts?: { limit?: number }) => (await all.search(term)).slice(0, opts?.limit)) };
+ expect(await explainSymbolMiss(windowed, "renderGadget", {})).toBeNull();
+ });
+
+ it("does not send an agent to `ix map` when an indexed file has the name and an earlier one is unindexed", async () => {
+ const why = await explainSymbolMiss(client([{ uri: "src/late.ts", rev: 3 }]), "frobnicate", {});
+ expect(why).toMatchObject({ reason: "symbol_not_extracted", files: ["aaa/early.go", "src/late.ts"] });
+ expect(why?.message).toContain("src/late.ts (indexed at rev 3)");
+ });
+
+ it("ignores files Ix does not parse: the name only there is a plain miss", async () => {
+ expect(await explainSymbolMiss(client([]), "onlyInProse", {})).toBeNull();
+ });
+
+ it("stops probing once a run has spent its time budget, per run", async () => {
+ let clock = 1_000_000;
+ const now = vi.spyOn(Date, "now").mockImplementation(() => clock);
+ try {
+ // Each graph lookup "takes" 6 s: one probe spends the whole budget.
+ const slow = client([{ uri: "src/indexed.ts", rev: 7 }]);
+ const base = slow.search.getMockImplementation()!;
+ slow.search.mockImplementation(async (term: string) => { clock += 6_000; return base(term); });
+ const spent = new AbortController().signal;
+ await runWithSignal(spent, async () => {
+ expect((await explainSymbolMiss(slow, "parseWidget", {}))?.reason).toBe("symbol_not_extracted");
+ expect(await explainSymbolMiss(slow, "parseWidget", {})).toBeNull();
+ });
+ // Another run (another `ix mcp` call) has its own budget.
+ await runWithSignal(new AbortController().signal, async () => {
+ expect((await explainSymbolMiss(slow, "parseWidget", {}))?.reason).toBe("symbol_not_extracted");
+ });
+ } finally {
+ now.mockRestore();
+ }
+ });
+
+ it("gives up (null) when the graph lookup fails, rather than guessing", async () => {
+ const failing = { search: vi.fn(async (): Promise<any[]> => { throw new Error("backend down"); }) };
+ expect(await explainSymbolMiss(failing, "renderGadget", {})).toBeNull();
+ });
+
+ describe("withMissReason under --kind, --path or the test filter", () => {
+ /** The graph has src/indexed.ts and, when `entity` is set, a function named parseWidget. */
+ function graphWith(entity: boolean) {
+ return {
+ search: vi.fn(async (term: string, opts?: { kind?: string }): Promise<any[]> => {
+ if (opts?.kind === "file") {
+ return term === "indexed.ts" ? [{ id: "id-file", kind: "file", name: term, provenance: { sourceUri: "src/indexed.ts" } }] : [];
+ }
+ return entity && term === "parseWidget"
+ ? [{ id: "id-fn", kind: "function", name: "parseWidget", provenance: { sourceUri: "src/indexed.ts" } }]
+ : [];
+ }),
+ };
+ }
+ type Miss = { resolved: false; ambiguous: false; reason?: string; hiddenTestCount?: number };
+ const miss = (extra: Partial<Miss> = {}): Miss => ({ resolved: false, ambiguous: false, ...extra });
+ const inRun = <T>(fn: () => Promise<T>) => runWithSignal(new AbortController().signal, fn);
+
+ it("does not call a name never extracted when a filter set its entity aside", async () => {
+ await inRun(async () => {
+ const graph = graphWith(true);
+ const cases: Array<[Record<string, unknown>, Miss]> = [
+ [{ kind: "class" }, miss()],
+ [{ path: "src/" }, miss()],
+ [{ testsOnly: true }, miss()],
+ [{}, miss({ hiddenTestCount: 1 })],
+ ];
+ for (const [opts, result] of cases) {
+ const out = await withMissReason(graph as any, "parseWidget", result, opts, "json");
+ expect(out).toEqual(result);
+ }
+ });
+ });
+
+ it("still explains a filtered miss when no entity carries the name", async () => {
+ await inRun(async () => {
+ const out = await withMissReason(graphWith(false) as any, "parseWidget", miss(), { kind: "class" }, "json");
+ expect(out).toMatchObject({ reason: "symbol_not_extracted" });
+ });
+ });
+
+ it("spends no search on the filter check when the probe would not run", async () => {
+ await inRun(async () => {
+ const graph = graphWith(true);
+ process.env[MISS_PROBE_ENV] = "0";
+ expect(await withMissReason(graph as any, "parseWidget", miss(), { kind: "class" }, "json")).toEqual(miss());
+ process.env[MISS_PROBE_ENV] = "1";
+ expect(await withMissReason(graph as any, "not a name", miss(), { kind: "class" }, "json")).toEqual(miss());
+ expect(graph.search).not.toHaveBeenCalled();
+ });
+ });
+
+ it("spends no search on the filter check once the run's budget is spent", async () => {
+ let clock = 1_000_000;
+ const now = vi.spyOn(Date, "now").mockImplementation(() => clock);
+ try {
+ await inRun(async () => {
+ const slow = graphWith(false);
+ const base = slow.search.getMockImplementation()!;
+ slow.search.mockImplementation(async (...args: Parameters<typeof base>) => { clock += 6_000; return base(...args); });
+ // No filter: straight to the probe, whose lookup spends the budget.
+ expect(await withMissReason(slow as any, "parseWidget", miss(), {}, "json")).toMatchObject({ reason: "symbol_not_extracted" });
+ slow.search.mockClear();
+ expect(await withMissReason(slow as any, "parseWidget", miss(), { kind: "class" }, "json")).toEqual(miss());
+ expect(slow.search).not.toHaveBeenCalled();
+ });
+ } finally {
+ now.mockRestore();
+ }
+ });
+
+ it("skips the probe when the unfiltered lookup fails", async () => {
+ await inRun(async () => {
+ const failing = { search: vi.fn(async (): Promise<any[]> => { throw new Error("backend down"); }) };
+ expect(await withMissReason(failing as any, "parseWidget", miss(), { kind: "class" }, "json")).toEqual(miss());
+ });
+ });
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/multi-target-notices.test.ts b/ix-cli/src/cli/__tests__/multi-target-notices.test.ts
new file mode 100644
index 00000000..a40c343f
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/multi-target-notices.test.ts
@@ -0,0 +1,62 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { noteResolutionNotices, printJson, resetResolutionNotices } from "../format.js";
+import { runPerTarget } from "../multi-target.js";
+
+// Resolution notices are module state (format.ts). A target that queues one and
+// then throws never reaches the printJson that would take it, so runPerTarget
+// must not let it ride into the next target's answer, or onto the grouping.
+
+const NOTICE = { code: "ambiguous_target", target: "first", message: "first matches 2 candidates equally" };
+
+let savedExitCode: typeof process.exitCode;
+beforeEach(() => {
+ savedExitCode = process.exitCode;
+ resetResolutionNotices();
+});
+afterEach(() => {
+ process.exitCode = savedExitCode;
+ resetResolutionNotices();
+});
+
+describe("runPerTarget and pending resolution notices", () => {
+ it("drops a thrown target's notices instead of handing them to the next target (json)", async () => {
+ const out: string[] = [];
+ const log = vi.spyOn(console, "log").mockImplementation((...parts) => { out.push(parts.join(" ")); });
+ try {
+ await runPerTarget(["first", "second", "third"], "json", async (target) => {
+ if (target === "second") {
+ printJson({ resolvedTarget: { name: target } });
+ return;
+ }
+ noteResolutionNotices([{ ...NOTICE, target }]);
+ throw new Error(`backend failed for ${target}`);
+ });
+ } finally {
+ log.mockRestore();
+ }
+ const body = JSON.parse(out.join("\n"));
+ expect(body.targets.map((t: { target: string }) => t.target)).toEqual(["first", "second", "third"]);
+ expect(body.targets[0].error).toBe("cli_error");
+ expect(body.targets[1].resolvedTarget).toEqual({ name: "second" });
+ expect(body.targets[1].resolutionNotices).toBeUndefined();
+ expect(body.resolutionNotices).toBeUndefined();
+ });
+
+ it("keeps a target's own notices", async () => {
+ const out: string[] = [];
+ const log = vi.spyOn(console, "log").mockImplementation((...parts) => { out.push(parts.join(" ")); });
+ try {
+ await runPerTarget(["first", "second"], "json", async (target) => {
+ noteResolutionNotices([{ ...NOTICE, target }]);
+ printJson({ resolvedTarget: { name: target } });
+ });
+ } finally {
+ log.mockRestore();
+ }
+ const body = JSON.parse(out.join("\n"));
+ expect(body.targets.map((t: { resolutionNotices: Array<{ target: string }> }) => t.resolutionNotices.map((n) => n.target)))
+ .toEqual([["first"], ["second"]]);
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/path-disambiguation.test.ts b/ix-cli/src/cli/__tests__/path-disambiguation.test.ts
index d00f71f5..576342cf 100644
--- a/ix-cli/src/cli/__tests__/path-disambiguation.test.ts
+++ b/ix-cli/src/cli/__tests__/path-disambiguation.test.ts
@@ -79,14 +79,14 @@ describe.each(["impact", "callers", "callees", "imports", "imported-by"])("%s pa
it("does not silently select a candidate outside --path", async () => {
const output = await run(command, ["--path", "missing.ts"]);
- expect(process.exitCode).toBe(1);
+ expect(process.exitCode).toBe(3);
expect(output.error).toBe("unresolved_target");
expect(expand).not.toHaveBeenCalled();
});
it("preserves ambiguity when no filter is supplied", async () => {
const output = await run(command, []);
- expect(process.exitCode).toBe(1);
+ expect(process.exitCode).toBe(2);
expect(output.error).toBe("ambiguous_target");
expect(expand).not.toHaveBeenCalled();
});
diff --git a/ix-cli/src/cli/__tests__/target-resolution.test.ts b/ix-cli/src/cli/__tests__/target-resolution.test.ts
index 68ea0066..85784219 100644
--- a/ix-cli/src/cli/__tests__/target-resolution.test.ts
+++ b/ix-cli/src/cli/__tests__/target-resolution.test.ts
@@ -15,7 +15,7 @@ vi.mock("../bootstrap.js", async (orig) => ({
/**
* 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.
+ * passed over; what was ambiguous (exit 2 now) stays so. No new non-zero exit.
*/
type Node = ReturnType<typeof node>;
@@ -191,7 +191,7 @@ describe("a suffix not on a '/' boundary is labelled fuzzy (review round 5)", ()
});
});
-describe("acceptance 4: two functions named render stay ambiguous (exit 1)", () => {
+describe("acceptance 4: two functions named render stay ambiguous (exit 2)", () => {
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 () => {
@@ -200,7 +200,7 @@ describe("acceptance 4: two functions named render stay ambiguous (exit 1)", ()
logs.length = 0;
process.exitCode = undefined;
expect(await resolveFileOrReport(c, "render", {}, "json")).toBeNull();
- expect(process.exitCode).toBe(1);
+ expect(process.exitCode).toBe(2);
outs.push(JSON.parse(logs[0]));
}
expect(outs[0].error).toBe("ambiguous_target");
@@ -211,7 +211,7 @@ describe("acceptance 4: two functions named render stay ambiguous (exit 1)", ()
it("llm: count= unchanged, shown= and total= added", async () => {
await resolveFileOrReport(client(nodes), "render", {}, "llm");
- expect(process.exitCode).toBe(1);
+ expect(process.exitCode).toBe(2);
expect(logs[0]).toMatch(/^error code=ambiguous_target .*count=2 shown=2 total=2/);
});
});
@@ -570,7 +570,7 @@ describe("acceptance 7: many methods named run", () => {
const nodes = runs(40);
logs.length = 0;
expect(await resolveFileOrReport(client(nodes), "run", {}, "json")).toBeNull();
- expect(process.exitCode).toBe(1);
+ expect(process.exitCode).toBe(2);
const out = JSON.parse(logs[0]);
expect(out.error).toBe("ambiguous_target");
expect(out.candidates).toHaveLength(8);
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 41c16da8..8eb7d24a 100644
--- a/ix-cli/src/cli/__tests__/unresolved-machine-output.test.ts
+++ b/ix-cli/src/cli/__tests__/unresolved-machine-output.test.ts
@@ -88,7 +88,7 @@ describe("unresolved targets in machine formats", () => {
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(process.exitCode).toBe(3);
expect(JSON.parse(result.stdout)).toEqual({
error: "unresolved_target",
message: 'No entity found matching "DefinitelyMissing".',
@@ -98,7 +98,7 @@ describe("unresolved targets in machine formats", () => {
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(process.exitCode).toBe(3);
expect(result.stdout).toBe(
'error code=unresolved_target message="No entity found matching \\"DefinitelyMissing\\"."',
);
@@ -107,7 +107,7 @@ describe("unresolved targets in machine formats", () => {
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(process.exitCode).toBe(3);
expect(result.stdout).toBe("");
expect(result.stderr).toContain('No entity found matching "DefinitelyMissing".');
});
@@ -123,7 +123,7 @@ describe("unresolved targets in machine formats", () => {
["overview", "Duplicate", "--format", "json"],
);
- expect(process.exitCode).toBe(1);
+ expect(process.exitCode).toBe(2);
expect(JSON.parse(result.stdout)).toMatchObject({
error: "ambiguous_target",
message: 'Ambiguous symbol "Duplicate".',
@@ -134,6 +134,29 @@ describe("unresolved targets in machine formats", () => {
});
});
+ // `ix read`'s ambiguity is the one exception (docs/llm-format.md): it has
+ // always exited 0 with an `ambiguous` record, and plugins that drop stdout
+ // on a non-zero exit would lose the candidates. Its miss still exits 3.
+ it("keeps ix read's ambiguity at exit 0 with its own ambiguous record", 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 register = (await import("../commands/read.js")).registerReadCommand;
+
+ const json = await run(register, ["read", "Duplicate", "--format", "json"]);
+ expect(process.exitCode ?? 0).toBe(0);
+ const body = JSON.parse(json.stdout);
+ expect(body).toMatchObject({ targetType: "ambiguous-symbol" });
+ expect(body.error).toBeUndefined();
+ expect(body.candidates).toHaveLength(2);
+
+ process.exitCode = undefined;
+ const llm = await run(register, ["read", "Duplicate", "--format", "llm"]);
+ expect(process.exitCode ?? 0).toBe(0);
+ expect(llm.stdout).toMatch(/^ambiguous kind=symbol target=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" } },
@@ -145,7 +168,7 @@ describe("unresolved targets in machine formats", () => {
["overview", "Duplicate", "--pick", "3", "--format", "json"],
);
- expect(process.exitCode).toBe(1);
+ expect(process.exitCode).toBe(2);
const output = JSON.parse(result.stdout);
expect(output.error).toBe("ambiguous_target");
expect(output.diagnostics[0]).toEqual({
@@ -160,7 +183,7 @@ describe("unresolved targets in machine formats", () => {
["trace", "MissingFrom", "--to", "MissingTo", "--format", "json"],
);
- expect(process.exitCode).toBe(1);
+ expect(process.exitCode).toBe(3);
expect(JSON.parse(result.stdout)).toEqual({
error: "unresolved_target",
message: 'No entities found matching "MissingFrom" or "MissingTo".',
@@ -168,20 +191,23 @@ describe("unresolved targets in machine formats", () => {
});
});
- // locate joins the same contract (#539) but deliberately keeps its own body
- // rather than adopting reportUnresolvedTarget's `{error, message}` shape:
+ // locate joins the same contract (#539) and keeps its own body, with the
+ // shared `{error, message}` fields added rather than substituted:
// shipped plugins read `diagnostics` off it, and the point of #539 is that
// the exit code becomes informative without the payload going away.
it("returns a non-zero status from ix locate while keeping its result body", async () => {
const { registerLocateCommand } = await import("../commands/locate.js");
const result = await run(registerLocateCommand, ["locate", "DefinitelyMissing", "--format", "json"]);
- expect(process.exitCode).toBe(1);
+ expect(process.exitCode).toBe(3);
expect(JSON.parse(result.stdout)).toEqual({
resolvedTarget: null,
resolutionMode: "none",
systemPath: null,
diagnostics: ["No graph entity found."],
+ // The slug and message every other command's miss carries.
+ error: "unresolved_target",
+ message: 'No graph entity found for "DefinitelyMissing".',
});
});
@@ -202,7 +228,7 @@ describe("unresolved targets in machine formats", () => {
for (const format of ["json", "llm", "text"] as const) {
process.exitCode = undefined;
const result = await run(registerLocateCommand, ["locate", "Duplicate", "--format", format]);
- expect(process.exitCode, `format=${format}`).toBe(1);
+ expect(process.exitCode, `format=${format}`).toBe(2);
// ...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");
@@ -216,7 +242,7 @@ describe("unresolved targets in machine formats", () => {
const { registerLocateCommand } = await import("../commands/locate.js");
const result = await run(registerLocateCommand, ["locate", "DefinitelyMissing", "--format", "llm"]);
- expect(process.exitCode).toBe(1);
+ expect(process.exitCode).toBe(3);
// This record was already being emitted -- while exiting 0, which is the
// contradiction #539 opens with.
expect(result.stdout).toContain("unresolved_target");
diff --git a/ix-cli/src/cli/commands/around.ts b/ix-cli/src/cli/commands/around.ts
index 491cb5fd..242a27fd 100644
--- a/ix-cli/src/cli/commands/around.ts
+++ b/ix-cli/src/cli/commands/around.ts
@@ -9,6 +9,7 @@ import { resolveWorkspaceRoot } from "../config.js";
import { printJson } from "../format.js";
import { llmError, printLlmLines } from "../llm.js";
import { parseBudgetOption } from "../options.js";
+import { setOutcome } from "../outcome.js";
import { isQuiet } from "../output-shape.js";
import { stderr } from "../stderr.js";
import { SourceFiles } from "../edge-sites.js";
@@ -19,11 +20,14 @@ import {
} from "../around.js";
import { aroundJson, renderAroundLlm, renderAroundText } from "../around-render.js";
-function reportError(code: string, message: string, format: string, extra: Array<[string, string]> = []): void {
+export function reportError(code: string, message: string, format: string, extra: Array<[string, string]> = []): void {
if (format === "json") printJson({ error: code, message, ...Object.fromEntries(extra) });
else if (format === "llm") console.log(llmError(code, message, extra));
else stderr(chalk.red(message));
- process.exitCode = 1;
+ // A file that is not in the graph is a miss (3), as for every graph command
+ // that resolves a target (outcome.ts); a bad argument is an error (1).
+ if (code === "unresolved_target") setOutcome("not_found");
+ else process.exitCode = 1;
}
/** The file's lines, or none when it is not on disk (the graph's spans then stand as recorded). */
diff --git a/ix-cli/src/cli/commands/callers.ts b/ix-cli/src/cli/commands/callers.ts
index eab7a9ab..5c7fef91 100644
--- a/ix-cli/src/cli/commands/callers.ts
+++ b/ix-cli/src/cli/commands/callers.ts
@@ -6,20 +6,27 @@ import type { Command } from "commander";
import chalk from "chalk";
import { createClient } from "../../client/factory.js";
import { resolveWorkspaceRoot } from "../config.js";
-import { expandCapped, formatEdgeResults, printJson, relativePath, sliceEdgeResults, sliceRanked, truncationHint, type Diagnostic } from "../format.js";
+import { expandCapped, formatEdgeResults, printJson, relativePath, sliceEdgeResults, sliceRanked, truncationHint, type Diagnostic, type EdgeCandidate } from "../format.js";
import { checkGraphHealth, graphHealthProse, isUnhealthy, type GraphHealth } from "../graph-health.js";
import { parsePickOption } from "../options.js";
import { nextPageCommand, OFFSET_FLAG, parseOffset } from "../paging.js";
-import { activeReadScope, resolveFileOrReport, printResolved } from "../resolve.js";
+import { activeReadScope, candidatesCut, resolveTargetSetOrReport, printResolved, type TargetSet } from "../resolve.js";
+import { EXIT_CODES_HELP } from "../outcome.js";
+import { runPerTarget } from "../multi-target.js";
+import type { IxClient } from "../../client/api.js";
import { stderr } from "../stderr.js";
import { llmLine } from "../llm.js";
-import { edgeTargetFor, rankTextUses, withEdgeSites } from "../edge-sites.js";
+import { edgeTargetFor, rankTextUses, SourceFiles, withEdgeSites } from "../edge-sites.js";
import { renderWarning } from "../ui.js";
import { currentRunSignal } from "../../client/run-signal.js";
+import { mapLimit } from "../../client/request-memo.js";
import { clipSnippet } from "./text.js";
const execFileAsync = promisify(execFile);
+/** Edge queries `--all` keeps in flight at once: a 200-way tie is not a 400-request burst. */
+export const ALL_CONCURRENCY = 4;
+
/** Rows per page of the text fallback. --limit does not apply to it. */
export const TEXT_FALLBACK_PAGE = 10;
@@ -48,161 +55,77 @@ function bannerOverRows(health: { diagnostics?: Diagnostic[] }, format: string,
if (format === "text" && rows > 0 && health.diagnostics) renderWarning(health.diagnostics[0].message);
}
+interface EdgeOpts {
+ kind?: string; path?: string; pick?: number; all?: boolean; limit: string; offset: string; format: string;
+}
+
+const ALL_FLAG = "When the symbol is ambiguous, answer for every candidate; rows are tagged with their candidate";
+
+/**
+ * `--all`: one edge query per candidate of an ambiguous symbol, unioned into
+ * one paged list whose rows carry `candidate: <n>` (numbering the candidate
+ * list printed with them). The whole blast radius of a name in one call,
+ * still attributable row by row. No text fallback: an empty union is the
+ * graph's answer for every candidate.
+ */
+async function edgesOfAll(
+ client: IxClient,
+ symbol: string,
+ set: TargetSet,
+ relation: "callers" | "callees",
+ limit: number,
+ offset: number,
+ format: string,
+ cmd: Command,
+): Promise<void> {
+ const healthCheck = checkGraphHealth(client, activeReadScope());
+ // `n` is the candidate's `--pick` number (resolve.ts candidateSet).
+ const candidates: EdgeCandidate[] = set.entities.map((e, i) => ({ n: e.n ?? i + 1, id: e.id, name: e.name, kind: e.kind, path: e.path }));
+ const expanded = await mapLimit(set.entities, ALL_CONCURRENCY, (e) => client.expand(e.id, {
+ direction: relation === "callers" ? "in" : "out",
+ predicates: ["CALLS", "REFERENCES"],
+ }));
+ const rows = expanded.flatMap((result, i) => result.nodes.map((n: any) => ({ ...n, candidate: candidates[i].n })));
+ const health = await healthDiagnostics(healthCheck);
+ bannerOverRows(health, format, rows.length);
+ const slice = sliceEdgeResults(rows, limit, offset, expanded.some((r) => expandCapped(r)));
+ if (slice.nextOffset !== undefined) slice.next = nextPageCommand(cmd, [symbol], slice.nextOffset);
+ // Call sites are looked up against the candidate the row belongs to.
+ const sites = await mapLimit(set.entities, ALL_CONCURRENCY, (e) => edgeTargetFor(client, e, relation));
+ const files = new SourceFiles();
+ const siteOf = new Map(candidates.map((c, i) => [c.n, sites[i]]));
+ const sited = slice.rows.map((row: any) => withEdgeSites([row], relation, siteOf.get(row.candidate)!, { files })[0]);
+ const diagnostics = [...(health.diagnostics ?? [])];
+ const cut = candidatesCut(set, candidates.length, "Answered for");
+ if (cut) diagnostics.push({ code: "candidates_truncated", message: cut });
+ formatEdgeResults({ ...slice, rows: sited }, relation, symbol, format, undefined, "graph",
+ diagnostics.length ? diagnostics : undefined, candidates);
+}
+
export function registerCallersCommand(program: Command): void {
program
- .command("callers <symbol>")
- .description("Show methods/functions that call the given symbol (cross-file)")
+ .command("callers <symbols...>")
+ .description("Show methods/functions that call the given symbols (cross-file)")
.option("--kind <kind>", "Filter target entity by kind")
.option("--path <path>", "Restrict to symbols from files matching this path substring")
.option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)
+ .option("--all", ALL_FLAG)
.option("--limit <n>", "Max results to show", "50")
.option("--offset <n>", OFFSET_FLAG, "0")
.option("--format <fmt>", "Output format (text|json|llm)", "text")
- .addHelpText("after", "\nExamples:\n ix callers verify_token\n ix callers processPayment --format json\n ix callers parse --kind method --limit 20\n ix callers verify_token --offset 50")
- .action(async (symbol: string, opts: { kind?: string; path?: string; pick?: number; limit: string; offset: string; format: string }, cmd: Command) => {
- const client = createClient();
- const limit = parseInt(opts.limit, 10);
- const offset = parseOffset(opts.offset);
- const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick };
- const target = await resolveFileOrReport(client, symbol, resolveOpts, opts.format);
- if (!target) return;
- if (opts.format === "text") printResolved(target);
- const healthCheck = checkGraphHealth(client, activeReadScope());
- // Use expand by entity ID to avoid aggregating results across all same-named entities
- const result = await client.expand(target.id, {
- direction: "in",
- predicates: ["CALLS", "REFERENCES"],
- });
- const health = await healthDiagnostics(healthCheck);
- bannerOverRows(health, opts.format, result.nodes.length);
- // `ix ingest --force` does not bring a hollowed graph's edges back; the
- // health check names what does.
- const remedy = health.fix ?? "ix ingest --force --recursive .";
-
- if (result.nodes.length === 0) {
- // Fallback to text search: pages of TEXT_FALLBACK_PAGE rows, --offset honoured.
- try {
- const root = resolveWorkspaceRoot();
- // The timeout bounds a search that rg could otherwise run for ever.
- const { stdout } = await execFileAsync("rg", callersTextSearchArgs(target.name, root), {
- maxBuffer: 5 * 1024 * 1024, timeout: 10_000, signal: currentRunSignal(),
- });
-
- const allTextResults: any[] = [];
- for (const line of stdout.split("\n")) {
- if (!line.trim()) continue;
- try {
- const parsed = JSON.parse(line);
- if (parsed.type === "match") {
- const data = parsed.data;
- allTextResults.push({
- id: "",
- kind: "text-match",
- name: `${data.path?.text ?? ""}:${data.line_number ?? 0}`,
- resolved: false,
- path: relativePath(data.path?.text) ?? "",
- line: data.line_number ?? 0,
- // Capped like `ix text`: one minified line must not flood
- // the context. Ranking still reads the whole line.
- attrs: { snippet: clipSnippet(data.lines?.text ?? "", data.submatches).trim() },
- fullLine: data.lines?.text?.trim() ?? "",
- });
- }
- } catch { /* skip malformed lines */ }
- }
+ .addHelpText("after", `\nExamples:
+ ix callers verify_token
+ ix callers processPayment --format json
+ ix callers parse --kind method --limit 20
+ ix callers verify_token --offset 50
+ ix callers handle --all --format llm
+ ix callers parseConfig loadConfig --format llm
- // rg searches files in parallel, so match order varies between runs;
- // sort first so the ranking, and the output, do not.
- allTextResults.sort((x, y) => (x.path < y.path ? -1 : x.path > y.path ? 1 : x.line - y.line));
- // Calls first and the definition out: an unranked fallback led with
- // import lines and the target's own signature.
- const ranked = rankTextUses(
- allTextResults.map((r) => ({ ...r, snippet: r.fullLine as string })),
- target.name,
- ).map(({ snippet: _snippet, fullLine: _fullLine, ...r }) => r);
- const candidatesFound = ranked.length;
- // The ranking is a stable sort of a sorted list, so pages neither
- // overlap nor skip a row.
- const page = sliceRanked(ranked, TEXT_FALLBACK_PAGE, undefined, offset);
- if (page.nextOffset !== undefined) page.next = nextPageCommand(cmd, [symbol], page.nextOffset);
- const textResults = page.rows;
- const pastEnd = candidatesFound > 0 && textResults.length === 0;
- const pastEndMessage = `${candidatesFound} text candidates; --offset ${offset} is past the end.`;
- const pageHint = page.truncated ? truncationHint(page, "text candidates") : undefined;
-
- if (candidatesFound > 0) {
- if (opts.format === "llm") {
- console.log(llmLine("callers", [
- ["target", target.name], ["source", "text"],
- ["offset", offset > 0 ? offset : undefined],
- ["shown", textResults.length], ["total", candidatesFound],
- ]));
- console.log(llmLine("diagnostic", [
- ["code", "text_fallback_used"],
- ["message", "No graph-backed CALLS/REFERENCES edges; showing text matches."],
- ]));
- if (pageHint) {
- console.log(llmLine("diagnostic", [
- ["code", "results_truncated"], ["next_offset", page.nextOffset], ["message", pageHint],
- ]));
- }
- if (pastEnd) console.log(llmLine("diagnostic", [["code", "offset_past_end"], ["message", pastEndMessage]]));
- for (const d of health.diagnostics ?? []) {
- console.log(llmLine("diagnostic", [["code", d.code], ["message", d.message]]));
- }
- for (const r of textResults) {
- console.log(llmLine("ref", [["path", r.path], ["line", r.line], ["snippet", r.attrs?.snippet ?? ""]]));
- }
- return;
- }
- if (opts.format === "json") {
- printJson({
- results: textResults,
- resultSource: "text",
- resolvedTarget: target,
- summary: {
- candidatesFound,
- candidatesReturned: textResults.length,
- ...(offset > 0 ? { offset } : {}),
- ...(page.truncated ? { truncated: true } : {}),
- ...(page.nextOffset !== undefined ? { nextOffset: page.nextOffset } : {}),
- },
- diagnostics: [{
- code: "text_fallback_used",
- message: `No graph-backed CALLS/REFERENCES edges found. If files were ingested before extraction was added, run: ${remedy}`,
- },
- ...(pageHint ? [{ code: "results_truncated", message: pageHint }] : []),
- ...(pastEnd ? [{ code: "offset_past_end", message: pastEndMessage }] : []),
- ...(health.diagnostics ?? [])],
- });
- } else if (pastEnd) {
- console.log(pastEndMessage);
- } else {
- bannerOverRows(health, opts.format, textResults.length);
- stderr(chalk.dim("No graph-backed CALLS/REFERENCES edges found. Showing text-based candidate usages."));
- stderr(chalk.dim(`Tip: if files were ingested before CALLS extraction, run: ${remedy}\n`));
- for (const r of textResults) {
- const snippet = r.attrs?.snippet ?? "";
- console.log(` ${chalk.dim(r.name)} ${snippet}`);
- }
- if (page.truncated || offset > 0) {
- const range = offset > 0 ? `${offset + 1}-${offset + textResults.length}` : `${textResults.length}`;
- const next = page.next ?? (page.nextOffset !== undefined ? `--offset ${page.nextOffset}` : undefined);
- stderr(chalk.dim(`\n (${candidatesFound} total candidates; showing ${range})${next ? ` next: ${next}` : ""}`));
- }
- }
- return;
- }
- } catch { /* ripgrep not available or no matches */ }
-
- // Both graph and text empty (also the health-gated path: --offset does not apply).
- formatEdgeResults(sliceEdgeResults([], limit), "callers", target.name, opts.format, target, "graph", health.diagnostics);
- } else {
- const slice = sliceEdgeResults(result.nodes, limit, offset, expandCapped(result));
- if (slice.nextOffset !== undefined) slice.next = nextPageCommand(cmd, [symbol], slice.nextOffset);
- const site = await edgeTargetFor(client, target, "callers");
- formatEdgeResults({ ...slice, rows: withEdgeSites(slice.rows, "callers", site) }, "callers", target.name, opts.format, target, "graph", health.diagnostics);
- }
+Several symbols answer in one call, grouped per symbol (json: {targets: [...]}).
+${EXIT_CODES_HELP}`)
+ .action(async (symbols: string[], opts: EdgeOpts, cmd: Command) => {
+ const client = createClient();
+ await runPerTarget(symbols, opts.format, (symbol) => callersOne(client, symbol, opts, cmd));
});
program
@@ -211,17 +134,27 @@ export function registerCallersCommand(program: Command): void {
.option("--kind <kind>", "Filter target entity by kind")
.option("--path <path>", "Restrict to symbols from files matching this path substring")
.option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)
+ .option("--all", ALL_FLAG)
.option("--limit <n>", "Max results to show", "50")
.option("--offset <n>", OFFSET_FLAG, "0")
.option("--format <fmt>", "Output format (text|json|llm)", "text")
- .addHelpText("after", "\nExamples:\n ix callees processPayment\n ix callees parse --format json")
- .action(async (symbol: string, opts: { kind?: string; path?: string; pick?: number; limit: string; offset: string; format: string }, cmd: Command) => {
+ .addHelpText("after", `\nExamples:
+ ix callees processPayment
+ ix callees parse --format json
+ ix callees handle --all --format llm
+${EXIT_CODES_HELP}`)
+ .action(async (symbol: string, opts: EdgeOpts, cmd: Command) => {
const client = createClient();
const calleeLimit = parseInt(opts.limit, 10);
const calleeOffset = parseOffset(opts.offset);
- const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick };
- const target = await resolveFileOrReport(client, symbol, resolveOpts, opts.format);
- if (!target) return;
+ const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick, all: opts.all };
+ const set = await resolveTargetSetOrReport(client, symbol, resolveOpts, opts.format);
+ if (!set) return;
+ if (set.all) {
+ await edgesOfAll(client, symbol, set, "callees", calleeLimit, calleeOffset, opts.format, cmd);
+ return;
+ }
+ const target = set.entities[0];
if (opts.format === "text") printResolved(target);
const healthCheck = checkGraphHealth(client, activeReadScope());
// Use expand by entity ID to avoid aggregating results across all same-named entities
@@ -237,3 +170,153 @@ export function registerCallersCommand(program: Command): void {
formatEdgeResults({ ...slice, rows: withEdgeSites(slice.rows, "callees", site) }, "callees", target.name, opts.format, target, "graph", health.diagnostics);
});
}
+
+async function callersOne(client: IxClient, symbol: string, opts: EdgeOpts, cmd: Command): Promise<void> {
+ const limit = parseInt(opts.limit, 10);
+ const offset = parseOffset(opts.offset);
+ const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick, all: opts.all };
+ const set = await resolveTargetSetOrReport(client, symbol, resolveOpts, opts.format);
+ if (!set) return;
+ if (set.all) {
+ await edgesOfAll(client, symbol, set, "callers", limit, offset, opts.format, cmd);
+ return;
+ }
+ const target = set.entities[0];
+ if (opts.format === "text") printResolved(target);
+ const healthCheck = checkGraphHealth(client, activeReadScope());
+ // Use expand by entity ID to avoid aggregating results across all same-named entities
+ const result = await client.expand(target.id, {
+ direction: "in",
+ predicates: ["CALLS", "REFERENCES"],
+ });
+ const health = await healthDiagnostics(healthCheck);
+ bannerOverRows(health, opts.format, result.nodes.length);
+ // `ix ingest --force` does not bring a hollowed graph's edges back; the
+ // health check names what does.
+ const remedy = health.fix ?? "ix ingest --force --recursive .";
+
+ if (result.nodes.length === 0) {
+ // Fallback to text search: pages of TEXT_FALLBACK_PAGE rows, --offset honoured.
+ try {
+ const root = resolveWorkspaceRoot();
+ // The timeout bounds a search that rg could otherwise run for ever.
+ const { stdout } = await execFileAsync("rg", callersTextSearchArgs(target.name, root), {
+ maxBuffer: 5 * 1024 * 1024, timeout: 10_000, signal: currentRunSignal(),
+ });
+
+ const allTextResults: any[] = [];
+ for (const line of stdout.split("\n")) {
+ if (!line.trim()) continue;
+ try {
+ const parsed = JSON.parse(line);
+ if (parsed.type === "match") {
+ const data = parsed.data;
+ allTextResults.push({
+ id: "",
+ kind: "text-match",
+ name: `${data.path?.text ?? ""}:${data.line_number ?? 0}`,
+ resolved: false,
+ path: relativePath(data.path?.text) ?? "",
+ line: data.line_number ?? 0,
+ // Capped like `ix text`: one minified line must not flood
+ // the context. Ranking still reads the whole line.
+ attrs: { snippet: clipSnippet(data.lines?.text ?? "", data.submatches).trim() },
+ fullLine: data.lines?.text?.trim() ?? "",
+ });
+ }
+ } catch { /* skip malformed lines */ }
+ }
+
+ // rg searches files in parallel, so match order varies between runs;
+ // sort first so the ranking, and the output, do not.
+ allTextResults.sort((x, y) => (x.path < y.path ? -1 : x.path > y.path ? 1 : x.line - y.line));
+ // Calls first and the definition out: an unranked fallback led with
+ // import lines and the target's own signature.
+ const ranked = rankTextUses(
+ allTextResults.map((r) => ({ ...r, snippet: r.fullLine as string })),
+ target.name,
+ ).map(({ snippet: _snippet, fullLine: _fullLine, ...r }) => r);
+ const candidatesFound = ranked.length;
+ // The ranking is a stable sort of a sorted list, so pages neither
+ // overlap nor skip a row.
+ const page = sliceRanked(ranked, TEXT_FALLBACK_PAGE, undefined, offset);
+ if (page.nextOffset !== undefined) page.next = nextPageCommand(cmd, [symbol], page.nextOffset);
+ const textResults = page.rows;
+ const pastEnd = candidatesFound > 0 && textResults.length === 0;
+ const pastEndMessage = `${candidatesFound} text candidates; --offset ${offset} is past the end.`;
+ const pageHint = page.truncated ? truncationHint(page, "text candidates") : undefined;
+
+ if (candidatesFound > 0) {
+ if (opts.format === "llm") {
+ console.log(llmLine("callers", [
+ ["target", target.name], ["source", "text"],
+ ["offset", offset > 0 ? offset : undefined],
+ ["shown", textResults.length], ["total", candidatesFound],
+ ]));
+ console.log(llmLine("diagnostic", [
+ ["code", "text_fallback_used"],
+ ["message", "No graph-backed CALLS/REFERENCES edges; showing text matches."],
+ ]));
+ if (pageHint) {
+ console.log(llmLine("diagnostic", [
+ ["code", "results_truncated"], ["next_offset", page.nextOffset], ["message", pageHint],
+ ]));
+ }
+ if (pastEnd) console.log(llmLine("diagnostic", [["code", "offset_past_end"], ["message", pastEndMessage]]));
+ for (const d of health.diagnostics ?? []) {
+ console.log(llmLine("diagnostic", [["code", d.code], ["message", d.message]]));
+ }
+ for (const r of textResults) {
+ console.log(llmLine("ref", [["path", r.path], ["line", r.line], ["snippet", r.attrs?.snippet ?? ""]]));
+ }
+ return;
+ }
+ if (opts.format === "json") {
+ printJson({
+ results: textResults,
+ resultSource: "text",
+ resolvedTarget: target,
+ summary: {
+ candidatesFound,
+ candidatesReturned: textResults.length,
+ ...(offset > 0 ? { offset } : {}),
+ ...(page.truncated ? { truncated: true } : {}),
+ ...(page.nextOffset !== undefined ? { nextOffset: page.nextOffset } : {}),
+ },
+ diagnostics: [{
+ code: "text_fallback_used",
+ message: `No graph-backed CALLS/REFERENCES edges found. If files were ingested before extraction was added, run: ${remedy}`,
+ },
+ ...(pageHint ? [{ code: "results_truncated", message: pageHint }] : []),
+ ...(pastEnd ? [{ code: "offset_past_end", message: pastEndMessage }] : []),
+ ...(health.diagnostics ?? [])],
+ });
+ } else if (pastEnd) {
+ console.log(pastEndMessage);
+ } else {
+ bannerOverRows(health, opts.format, textResults.length);
+ stderr(chalk.dim("No graph-backed CALLS/REFERENCES edges found. Showing text-based candidate usages."));
+ stderr(chalk.dim(`Tip: if files were ingested before CALLS extraction, run: ${remedy}\n`));
+ for (const r of textResults) {
+ const snippet = r.attrs?.snippet ?? "";
+ console.log(` ${chalk.dim(r.name)} ${snippet}`);
+ }
+ if (page.truncated || offset > 0) {
+ const range = offset > 0 ? `${offset + 1}-${offset + textResults.length}` : `${textResults.length}`;
+ const next = page.next ?? (page.nextOffset !== undefined ? `--offset ${page.nextOffset}` : undefined);
+ stderr(chalk.dim(`\n (${candidatesFound} total candidates; showing ${range})${next ? ` next: ${next}` : ""}`));
+ }
+ }
+ return;
+ }
+ } catch { /* ripgrep not available or no matches */ }
+
+ // Both graph and text empty (also the health-gated path: --offset does not apply).
+ formatEdgeResults(sliceEdgeResults([], limit), "callers", target.name, opts.format, target, "graph", health.diagnostics);
+ } else {
+ const slice = sliceEdgeResults(result.nodes, limit, offset, expandCapped(result));
+ if (slice.nextOffset !== undefined) slice.next = nextPageCommand(cmd, [symbol], slice.nextOffset);
+ const site = await edgeTargetFor(client, target, "callers");
+ formatEdgeResults({ ...slice, rows: withEdgeSites(slice.rows, "callers", site) }, "callers", target.name, opts.format, target, "graph", health.diagnostics);
+ }
+}
diff --git a/ix-cli/src/cli/commands/impact.ts b/ix-cli/src/cli/commands/impact.ts
index f8e073e2..99e9802f 100644
--- a/ix-cli/src/cli/commands/impact.ts
+++ b/ix-cli/src/cli/commands/impact.ts
@@ -5,13 +5,14 @@ import chalk from "chalk";
import { renderSection, renderKeyValue, renderNote, renderResolvedHeader, renderWarning, colorizeKind } from "../ui.js";
import { IxClient } from "../../client/api.js";
import { createClient } from "../../client/factory.js";
-import { activeReadScope, resolveFileOrReport, printResolved } from "../resolve.js";
+import { activeReadScope, candidatesCut, resolveTargetSetOrReport, printResolved, type ResolvedEntity, type TargetSet } from "../resolve.js";
+import { EXIT_CODES_HELP } from "../outcome.js";
import { checkGraphHealth, graphHealthJson, graphHealthLlmFields, graphHealthProse, isUnhealthy } from "../graph-health.js";
import { bucketByHierarchy, getSystemPath, formatSystemPath, hasMapData, type SystemPath } from "../hierarchy.js";
import { inferRiskSemantics, humanizeLabel, type ImpactFacts, type RiskSemantics } from "../impact/risk-semantics.js";
-import { lineSpan, printJson, relativePath, rowLocation, sliceEdgeResults, stripNulls, type Slice } from "../format.js";
+import { captureJson, lineSpan, printJson, relativePath, rowLocation, sliceEdgeResults, stripNulls, type Slice } from "../format.js";
import { forMcp, suggest, type Relation } from "../next-step.js";
-import { llmLine } from "../llm.js";
+import { llmLine, llmShortId } from "../llm.js";
import { parsePickOption } from "../options.js";
const CONTAINER_KINDS = new Set(["class", "module", "file", "object", "trait", "interface"]);
@@ -23,27 +24,30 @@ export function registerImpactCommand(program: Command): void {
.option("--kind <kind>", "Filter target entity by kind")
.option("--path <path>", "Restrict to symbols from files matching this path substring")
.option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)
+ .option("--all", "When the target is ambiguous, analyse every candidate; each analysis is tagged with its candidate")
.option("--depth <n>", "Expansion depth for callers/importers (default 1, max 3)", "1")
.option("--limit <n>", "Max top-impacted members (and llm caller/callee rows) to show", "10")
.option("--format <fmt>", "Output format (text|json|llm)", "text")
.addHelpText(
"after",
- "\nExamples:\n ix impact IngestionService\n ix impact IngestionService --kind class\n ix impact verify_token --format json\n ix impact AuthProvider --limit 5"
+ "\nExamples:\n ix impact IngestionService\n ix impact IngestionService --kind class\n ix impact verify_token --format json\n ix impact AuthProvider --limit 5\n ix impact handle --all --format llm\n" +
+ EXIT_CODES_HELP
)
.action(
async (
symbol: string,
- opts: { kind?: string; path?: string; pick?: number; depth: string; limit: string; format: string }
+ opts: { kind?: string; path?: string; pick?: number; all?: boolean; depth: string; limit: string; format: string }
) => {
const client = createClient({ query: true });
const limit = parseInt(opts.limit, 10);
const depth = Math.min(Math.max(parseInt(opts.depth, 10) || 1, 1), 3);
- const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick };
- const target = await resolveFileOrReport(client, symbol, resolveOpts, opts.format);
- if (!target) return;
+ const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick, all: opts.all };
+ const set = await resolveTargetSetOrReport(client, symbol, resolveOpts, opts.format);
+ if (!set) return;
+ const target = set.entities[0];
- if (opts.format === "text") printResolved(target);
+ if (opts.format === "text" && !set.all) printResolved(target);
// A hollowed graph reports "low risk, no dependents" for anything:
// the answer is only as good as the edges it counts. Said first, in
@@ -53,15 +57,70 @@ export function registerImpactCommand(program: Command): void {
if (graph && opts.format === "llm") console.log(llmLine("graph", graphHealthLlmFields(health)));
if (graph && opts.format === "text") renderWarning(graphHealthProse(health));
- if (CONTAINER_KINDS.has(target.kind)) {
- await containerImpact(client, target, limit, depth, opts.format, graph);
- } else {
- await leafImpact(client, target, depth, limit, opts.format, graph);
- }
+ const analyse = (entity: ResolvedEntity) => CONTAINER_KINDS.has(entity.kind)
+ ? containerImpact(client, entity, limit, depth, opts.format, graph)
+ : leafImpact(client, entity, depth, limit, opts.format, graph);
+
+ if (set.all) await impactOfAll(symbol, set, opts.format, analyse);
+ else await analyse(target);
}
);
}
+/**
+ * `--all`: the impact of every candidate of an ambiguous target, one
+ * analysis each, in candidate order. Grouped rather than merged: risk and
+ * propagation are properties of one entity and do not add up across several.
+ *
+ * json `{ target, resolutionMode: "all", candidates, results: [{ candidate, ...impact }] }`
+ * llm a `candidate n=<i> ...` record before each candidate's impact records
+ * text a header per candidate
+ */
+async function impactOfAll(
+ symbol: string,
+ set: TargetSet,
+ format: string,
+ analyse: (entity: ResolvedEntity) => Promise<void>,
+): Promise<void> {
+ // `n` is the candidate's `--pick` number (resolve.ts candidateSet).
+ const candidates = set.entities.map((e, i) => ({ n: e.n ?? i + 1, id: e.id, name: e.name, kind: e.kind, path: relativePath(e.path) ?? e.path }));
+ const total = set.all?.total ?? candidates.length;
+ const truncation = candidatesCut(set, candidates.length, "Analysed");
+
+ if (format === "json") {
+ const results: Record<string, unknown>[] = [];
+ for (let i = 0; i < set.entities.length; i += 1) {
+ const payloads = await captureJson(() => analyse(set.entities[i]));
+ const only = payloads.length === 1 && payloads[0] && typeof payloads[0] === "object" ? payloads[0] as Record<string, unknown> : { results: payloads };
+ results.push({ candidate: candidates[i].n, ...only });
+ }
+ printJson({
+ target: symbol,
+ resolutionMode: "all",
+ candidates,
+ results,
+ ...(truncation ? { diagnostics: [{ code: "candidates_truncated", message: truncation }] } : {}),
+ });
+ return;
+ }
+
+ if (format === "llm") {
+ console.log(llmLine("impact_all", [["target", symbol], ["candidates", candidates.length], ["total", total]]));
+ if (truncation) console.log(llmLine("diagnostic", [["code", "candidates_truncated"], ["message", truncation]]));
+ } else if (truncation) {
+ renderWarning(truncation);
+ }
+ for (let i = 0; i < set.entities.length; i += 1) {
+ const c = candidates[i];
+ if (format === "llm") {
+ console.log(llmLine("candidate", [["n", c.n], ["name", c.name], ["kind", c.kind], ["path", c.path], ["id", llmShortId(c.id)]]));
+ } else {
+ console.log(`${i > 0 ? "\n" : ""}${chalk.bold(`── [${c.n}] ${c.kind} ${c.name}${c.path ? ` in ${c.path}` : ""} ──`)}`);
+ }
+ await analyse(set.entities[i]);
+ }
+}
+
/**
* The risk a hollowed graph would report is drawn from edges it has lost, so
* "low risk" there means "no edges left", not "safe to change". Withheld as
diff --git a/ix-cli/src/cli/commands/locate.ts b/ix-cli/src/cli/commands/locate.ts
index aef81799..534561d2 100644
--- a/ix-cli/src/cli/commands/locate.ts
+++ b/ix-cli/src/cli/commands/locate.ts
@@ -1,12 +1,16 @@
// Copyright 2026 Ix Infrastructure Inc.
import type { Command } from "commander";
+import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { createClient } from "../../client/factory.js";
import {
resolveFileOrEntityFull, resolveEntityFull, printResolved, printAmbiguous,
- looksFileLike, isRawId, qualifiedSeparator, isFuzzyResult, type ResolvedEntity,
+ looksFileLike, isRawId, qualifiedSeparator, isFuzzyResult, withMissReason,
+ type ResolvedEntity, type ResolveResult, type Suggestion,
} from "../resolve.js";
+import { EXIT_CODES_HELP, setOutcome } from "../outcome.js";
+import { runPerTarget } from "../multi-target.js";
import { isFileStale } from "../stale.js";
import { stderr } from "../stderr.js";
import { relativePath, printJson } from "../format.js";
@@ -32,12 +36,18 @@ interface LocateOutput {
hasMapData?: boolean;
stale?: boolean;
diagnostics: string[];
+ /** A miss: the `unresolved_target` record fields every graph command's miss carries. */
+ error?: "unresolved_target";
+ message?: string;
+ reason?: string;
+ files?: string[];
+ suggestions?: Suggestion[];
}
export function registerLocateCommand(program: Command): void {
program
- .command("locate <symbol>")
- .description("Resolve a symbol to its position in the codebase and system hierarchy")
+ .command("locate <symbols...>")
+ .description("Resolve symbols to their position in the codebase and system hierarchy")
.option("--kind <kind>", "Filter target entity by kind")
.option("--path <path>", "Restrict to results from files matching this path substring")
.option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)
@@ -46,178 +56,177 @@ export function registerLocateCommand(program: Command): void {
ix locate IngestionService
ix locate verify_token --kind function
ix locate ArangoClient --format json
- ix locate scoreCandidate --pick 2`)
- .action(async (symbol: string, opts: { kind?: string; path?: string; pick?: number; format: string }) => {
+ ix locate scoreCandidate --pick 2
+ ix locate parseConfig loadConfig writeConfig --format llm
+
+Several symbols answer in one call, grouped per symbol (json: {targets: [...]}).
+${EXIT_CODES_HELP}`)
+ .action(async (symbols: string[], opts: { kind?: string; path?: string; pick?: number; format: string }) => {
const client = createClient();
- const diagnostics: string[] = [];
- const isJson = opts.format === "json";
-
- const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick };
-
- // Resolution with ambiguity detection
- const { target, ambiguous } = await resolveWithAmbiguity(client, symbol, resolveOpts, opts.format);
-
- if (!target) {
- if (ambiguous) {
- // Printed above, in whichever format was asked for -- and exits 1,
- // like every other resolution failure.
- //
- // This was exit 0 in the first draft of #539, reasoned as "it
- // resolved to several candidates, which is an answer, not a miss".
- // #547 settled it the other way for the eight graph commands, and
- // being the one command that disagrees is worse than either rule:
- // `ix overview Duplicate` and `ix locate Duplicate` would report the
- // same condition with different statuses.
- //
- // It is also the same contradiction #539 opens with, one level up.
- // The llm branch above already prints `error code=ambiguous_target`,
- // and the json branch a record whose `resolvedTarget` is null -- a
- // machine caller that trusts the exit code is told the command
- // succeeded while being handed an error record. A `--pick <n>` that
- // is out of range lands here too, and that is a plain bad argument.
- process.exitCode = 1;
- return;
- }
- const output: LocateOutput = {
- resolvedTarget: null,
- resolutionMode: "none",
- systemPath: null,
- diagnostics: ["No graph entity found."],
- };
- outputLocate(output, symbol, opts.format);
- // #539: a machine caller could not tell this from a successful command
- // that intentionally returned nothing. `context`, `explain`, `read`,
- // `trace` and `subsystems` all exit 1 here (#526, #532); locate was the
- // odd one out, and its llm output even emitted an `error` record while
- // exiting 0.
- //
- // The body is deliberately left as it is rather than replaced with
- // `reportUnresolvedTarget`'s `{error, message}` shape: shipped plugins
- // read `diagnostics` from it, and #539's whole point is that the exit
- // code should become informative without the payload going away.
- //
- // Ambiguity keeps its own path above -- a different message and a
- // different record -- but the same exit code, per #547.
- process.exitCode = 1;
- return;
- }
+ await runPerTarget(symbols, opts.format, (symbol) => locateOne(client, symbol, opts));
+ });
+}
- if (opts.format === "text") printResolved(target);
-
- const isContainer = CONTAINER_KINDS.has(target.kind);
- const isFile = FILE_KINDS.has(target.kind);
-
- // Parallel fetch: effective system path, parent container (for non-containers), entity details
- const [systemPath, containsResult, details] = await Promise.all([
- getEffectiveSystemPath(client, target.id),
- isContainer
- ? Promise.resolve({ nodes: [] })
- : client.expand(target.id, { direction: "in", predicates: ["CONTAINS"] }),
- client.entity(target.id),
- ]);
-
- const node = details.node as any;
- const nodePath = node.provenance?.source_uri ?? node.provenance?.sourceUri ?? undefined;
-
- // Extract line range from attrs
- const lineStart = node.attrs?.line_start ?? node.attrs?.lineStart;
- const lineEnd = node.attrs?.line_end ?? node.attrs?.lineEnd;
- const lineRange = lineStart != null && lineEnd != null
- ? { start: Number(lineStart), end: Number(lineEnd) }
- : undefined;
-
- // Check staleness
- let stale = false;
- if (nodePath) {
- try { stale = isFileStale(nodePath); } catch {}
- }
+async function locateOne(
+ client: IxClient,
+ symbol: string,
+ opts: { kind?: string; path?: string; pick?: number; format: string },
+): Promise<void> {
+ const diagnostics: string[] = [];
+
+ const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick };
+
+ // Resolution with ambiguity detection
+ const { target, ambiguous, miss } = await resolveWithAmbiguity(client, symbol, resolveOpts, opts.format);
+
+ if (!target) {
+ if (ambiguous) {
+ // Printed above, in whichever format was asked for. Exits 2, like
+ // every other ambiguous graph target (outcome.ts): the candidates
+ // are the answer, and `--pick <n>` is the retry.
+ //
+ // #547 settled that locate and the other graph commands report this
+ // condition with one status; `ix overview Duplicate` and
+ // `ix locate Duplicate` must agree. A `--pick <n>` that is out of
+ // range lands here too, with its candidates.
+ setOutcome("ambiguous");
+ return;
+ }
+ // The body keeps its shape (shipped plugins read `diagnostics` from
+ // it) and gains the `error` slug, reason and suggestions every other
+ // command's miss carries, so one parser reads them all.
+ const reason = miss ? await withMissReason(client, symbol, miss, resolveOpts, opts.format) : undefined;
+ const output: LocateOutput = {
+ resolvedTarget: null,
+ resolutionMode: "none",
+ systemPath: null,
+ diagnostics: ["No graph entity found."],
+ error: "unresolved_target",
+ message: reason?.message ?? `No graph entity found for "${symbol}".`,
+ ...(reason?.reason ? { reason: reason.reason } : {}),
+ ...(reason?.files?.length ? { files: reason.files } : {}),
+ ...(miss?.suggestions?.length ? { suggestions: miss.suggestions } : {}),
+ };
+ outputLocate(output, symbol, opts.format);
+ // #539: a machine caller could not tell this from a successful command
+ // that intentionally returned nothing. Exits 3, the not-found code
+ // `context`, `explain`, `read` and `trace` share.
+ setOutcome("not_found");
+ return;
+ }
- // Container context (parent for callables)
- let container: LocateOutput["container"];
- if (!isContainer && containsResult.nodes.length > 0) {
- const c = containsResult.nodes[0] as any;
- container = {
- kind: c.kind || "unknown",
- name: c.name || c.attrs?.name || "(unknown)",
- id: c.id,
- };
- }
+ if (opts.format === "text") printResolved(target);
+
+ const isContainer = CONTAINER_KINDS.has(target.kind);
+ const isFile = FILE_KINDS.has(target.kind);
+
+ // Parallel fetch: effective system path, parent container (for non-containers), entity details
+ const [systemPath, containsResult, details] = await Promise.all([
+ getEffectiveSystemPath(client, target.id),
+ isContainer
+ ? Promise.resolve({ nodes: [] })
+ : client.expand(target.id, { direction: "in", predicates: ["CONTAINS"] }),
+ client.entity(target.id),
+ ]);
+
+ const node = details.node as any;
+ const nodePath = node.provenance?.source_uri ?? node.provenance?.sourceUri ?? undefined;
+
+ // Extract line range from attrs
+ const lineStart = node.attrs?.line_start ?? node.attrs?.lineStart;
+ const lineEnd = node.attrs?.line_end ?? node.attrs?.lineEnd;
+ const lineRange = lineStart != null && lineEnd != null
+ ? { start: Number(lineStart), end: Number(lineEnd) }
+ : undefined;
+
+ // Check staleness
+ let stale = false;
+ if (nodePath) {
+ try { stale = isFileStale(nodePath); } catch {}
+ }
- // Sub-file entities (table, view, function, etc.) have no IN_REGION edges of their
- // own — those belong to the containing file. Walk up via CONTAINS to inherit the
- // parent file's system path so hasMapData returns true after `ix map`.
- // Diagnostic for missing map data
- const hasMap = hasMapData(systemPath);
- if (!hasMap) {
- diagnostics.push(`No system map. Run ${forMcp() ? "ix_map" : "`ix map`"} to see hierarchy.`);
- }
+ // Container context (parent for callables)
+ let container: LocateOutput["container"];
+ if (!isContainer && containsResult.nodes.length > 0) {
+ const c = containsResult.nodes[0] as any;
+ container = {
+ kind: c.kind || "unknown",
+ name: c.name || c.attrs?.name || "(unknown)",
+ id: c.id,
+ };
+ }
- // Build system path: append resolved symbol for non-file targets
- let systemPathMapped = systemPath.map((n) => ({ name: n.name, kind: n.kind }));
- if (!isFile) {
- const lastInPath = systemPathMapped[systemPathMapped.length - 1];
- if (!lastInPath || lastInPath.name !== target.name) {
- systemPathMapped = [...systemPathMapped, { name: target.name, kind: target.kind }];
- }
- }
+ // Sub-file entities (table, view, function, etc.) have no IN_REGION edges of their
+ // own — those belong to the containing file. Walk up via CONTAINS to inherit the
+ // parent file's system path so hasMapData returns true after `ix map`.
+ // Diagnostic for missing map data
+ const hasMap = hasMapData(systemPath);
+ if (!hasMap) {
+ diagnostics.push(`No system map. Run ${forMcp() ? "ix_map" : "`ix map`"} to see hierarchy.`);
+ }
- // Make path repo-relative
- const displayPath = nodePath ? toRepoRelative(nodePath) : undefined;
-
- const output: LocateOutput = {
- resolvedTarget: {
- id: target.id,
- kind: target.kind,
- name: target.name,
- path: displayPath,
- },
- resolutionMode: target.resolutionMode === "exact" ? undefined as any : target.resolutionMode,
- lineRange,
- container,
- systemPath: systemPathMapped,
- hasMapData: hasMap,
- diagnostics: diagnostics.length > 0 ? diagnostics : [] as string[],
- };
- if (stale) {
- output.stale = true;
- }
+ // Build system path: append resolved symbol for non-file targets
+ let systemPathMapped = systemPath.map((n) => ({ name: n.name, kind: n.kind }));
+ if (!isFile) {
+ const lastInPath = systemPathMapped[systemPathMapped.length - 1];
+ if (!lastInPath || lastInPath.name !== target.name) {
+ systemPathMapped = [...systemPathMapped, { name: target.name, kind: target.kind }];
+ }
+ }
- outputLocate(output, symbol, opts.format);
- });
+ // Make path repo-relative
+ const displayPath = nodePath ? toRepoRelative(nodePath) : undefined;
+
+ const output: LocateOutput = {
+ resolvedTarget: {
+ id: target.id,
+ kind: target.kind,
+ name: target.name,
+ path: displayPath,
+ },
+ resolutionMode: target.resolutionMode === "exact" ? undefined as any : target.resolutionMode,
+ lineRange,
+ container,
+ systemPath: systemPathMapped,
+ hasMapData: hasMap,
+ diagnostics: diagnostics.length > 0 ? diagnostics : [] as string[],
+ };
+ if (stale) {
+ output.stale = true;
+ }
+
+ outputLocate(output, symbol, opts.format);
}
// ── Ambiguity-aware resolution ──────────────────────────────────────────────
+type Miss = Extract<ResolveResult, { resolved: false; ambiguous: false }>;
+
async function resolveWithAmbiguity(
client: IxClient,
symbol: string,
opts: { kind?: string; path?: string; pick?: number },
format: string,
-): Promise<{ target: ResolvedEntity | null; ambiguous: boolean }> {
+): Promise<{ target: ResolvedEntity | null; ambiguous: boolean; miss?: Miss }> {
+ let result: ResolveResult;
// 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.
+ // ambiguous.
if (isRawId(symbol) || looksFileLike(symbol)) {
- 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 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 });
+ } else {
+ // Symbol resolution — use full result to detect ambiguity
+ const allKinds = ["file", "class", "object", "trait", "interface", "module", "function", "method", "constant"];
+ const sep = qualifiedSeparator(symbol);
+ result = await resolveEntityFull(client, symbol, allKinds, { ...opts, format, ...(sep ? { silentMiss: true } : {}) });
+ // `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) {
@@ -228,6 +237,11 @@ async function resolveWithAmbiguity(
if (result.ambiguous) {
if (format === "json") {
printJson({
+ // Locate's ambiguity was never an `error` record, and integrations that
+ // treat any string `error` as a failure would drop the candidates: the
+ // shared slug rides in `code` instead (the exit code is 2, outcome.ts).
+ code: "ambiguous_target",
+ message: `Ambiguous symbol "${symbol}".`,
resolvedTarget: null,
resolutionMode: "ambiguous",
candidates: result.result.candidates,
@@ -247,7 +261,7 @@ async function resolveWithAmbiguity(
return { target: null, ambiguous: true };
}
- return { target: null, ambiguous: false };
+ return { target: null, ambiguous: false, miss: result };
}
// ── Repo-relative path ──────────────────────────────────────────────────────
@@ -272,7 +286,16 @@ function humanizeBreadcrumb(nodes: Array<{ name: string; kind: string }>): strin
export function renderLocateLlm(output: LocateOutput, symbol: string): string[] {
const t = output.resolvedTarget;
if (!t) {
- return [llmError("unresolved_target", `No graph entity found for "${symbol}".`)];
+ const near = output.suggestions ?? [];
+ return [
+ llmError("unresolved_target", output.message ?? `No graph entity found for "${symbol}".`,
+ [["reason", output.reason], ["files", output.files?.join(",")]]),
+ ...near.map((c, i) => llmLine("suggestion", [
+ ["n", i + 1], ["name", c.name], ["kind", c.kind],
+ ["path", c.path ? relativePath(c.path) ?? c.path : undefined], ["id", llmShortId(c.id)],
+ ])),
+ ...(near.length ? [llmLine("hint", [["text", "Re-run with one of these names, or narrow with --path."]])] : []),
+ ];
}
const lines = [llmLine("locate", [
["target", t.name],
@@ -304,6 +327,12 @@ function outputLocate(output: LocateOutput, symbol: string, format: string): voi
if (!output.resolvedTarget) {
stderr(`No graph entity found for "${symbol}".`);
+ if (output.suggestions?.length) {
+ stderr(chalk.dim("Did you mean:"));
+ for (const c of output.suggestions) {
+ stderr(` ${chalk.cyan((c.kind || "").padEnd(10))} ${c.name}${c.path ? chalk.dim(` in ${c.path}`) : ""}`);
+ }
+ }
console.log("No matches found.");
return;
}
diff --git a/ix-cli/src/cli/commands/subsystems.ts b/ix-cli/src/cli/commands/subsystems.ts
index 5ef7b8bc..a57a1d15 100644
--- a/ix-cli/src/cli/commands/subsystems.ts
+++ b/ix-cli/src/cli/commands/subsystems.ts
@@ -9,6 +9,7 @@ import { resolveReadSystemId } from "../resolve.js";
import { roundFloat, printJson } from "../format.js";
import { llmLine, llmError, llmShortId } from "../llm.js";
import { parsePickOption } from "../options.js";
+import { setOutcome } from "../outcome.js";
import { renderMapText, renderMapLlm, type MapRegion, type MapResult } from "./map.js";
import {
renderSubsystemExplanationJson,
@@ -224,18 +225,10 @@ Examples:
} catch (err: any) {
const body = parseErrorBody(err);
if (body) {
- if (opts.format === "json") {
- printJson(body);
- process.exitCode = 1;
- return;
- }
- if (opts.format === "llm") {
- console.log(renderSubsystemErrorLlm(body));
- process.exitCode = 1;
- return;
- }
- renderSubsystemError(body, Boolean(opts.explain));
- process.exitCode = 1;
+ if (opts.format === "json") printJson(body);
+ else if (opts.format === "llm") console.log(renderSubsystemErrorLlm(body));
+ else renderSubsystemError(body, Boolean(opts.explain));
+ setSubsystemErrorExit(body);
return;
}
console.error(chalk.red("Error:"), err.message);
@@ -364,6 +357,17 @@ export function renderScopedSubsystemLlm(result: ScopedSubsystemResult): string[
return lines;
}
+/**
+ * The exit code for a backend error body, matching the slug it prints: an
+ * ambiguous region is 2 and an unknown one 3, as for every graph command that
+ * resolves a target (outcome.ts); anything else is 1.
+ */
+export function setSubsystemErrorExit(body: unknown): void {
+ if (isAmbiguousSubsystemResult(body)) setOutcome("ambiguous");
+ else if (isUnknownSubsystemTargetResult(body)) setOutcome("not_found");
+ else process.exitCode = 1;
+}
+
export function renderSubsystemErrorLlm(body: unknown): string {
if (isAmbiguousSubsystemResult(body)) {
return llmError("ambiguous_target", `Multiple regions matched "${body.target_query}".`, [
diff --git a/ix-cli/src/cli/errors.ts b/ix-cli/src/cli/errors.ts
index 45402855..9d440c1b 100644
--- a/ix-cli/src/cli/errors.ts
+++ b/ix-cli/src/cli/errors.ts
@@ -4,6 +4,7 @@ import chalk from "chalk";
import { PRE_CONNECTION_CODES, RESET_RECONCILIATION_ERROR } from "../client/transport.js";
import { llmError } from "./llm.js";
+import { exitCodeFor } from "./outcome.js";
// ── Answering in the format the caller asked for ───────────────────────────
@@ -387,7 +388,8 @@ export function renderCliError(err: unknown, debug = false, endpoint?: string):
} else if (!emitLlmError(err.code, err.summary, err.hint, [["dir", err.dir]])) {
renderStructuredError({ error: err.code, message: err.summary, next: err.hint });
}
- process.exit(1);
+ // Its own code, so an agent knows to map rather than retry (outcome.ts).
+ process.exit(exitCodeFor("not_mapped"));
}
const e = err as any;
diff --git a/ix-cli/src/cli/format.ts b/ix-cli/src/cli/format.ts
index 42a85ade..f7fb664d 100644
--- a/ix-cli/src/cli/format.ts
+++ b/ix-cli/src/cli/format.ts
@@ -1,7 +1,7 @@
// Copyright 2026 Ix Infrastructure Inc.
import chalk from "chalk";
-import { llmLine, llmShortId } from "./llm.js";
+import { llmLine, llmShortId, type LlmValue } from "./llm.js";
import { projectRow, requestedFields } from "./output-shape.js";
import type { EdgeSite } from "./edge-sites.js";
@@ -83,9 +83,34 @@ function withResolutionNotices(value: unknown): unknown {
};
}
+/** Set while {@link captureJson} runs: payloads are collected instead of printed. */
+let jsonSink: unknown[] | undefined;
+
/** Print a JSON payload on stdout, indented only when that helps someone. */
export function printJson(value: unknown): void {
- console.log(JSON.stringify(withResolutionNotices(value), null, jsonIndent()));
+ const payload = withResolutionNotices(value);
+ if (jsonSink) {
+ jsonSink.push(payload);
+ return;
+ }
+ console.log(JSON.stringify(payload, null, jsonIndent()));
+}
+
+/**
+ * Run `fn` and return the payloads it passed to `printJson`, unprinted. A
+ * multi-target command runs its one-target body per target and prints one
+ * object grouping them, rather than several JSON documents on one stream.
+ */
+export async function captureJson(fn: () => Promise<void>): Promise<unknown[]> {
+ const previous = jsonSink;
+ const sink: unknown[] = [];
+ jsonSink = sink;
+ try {
+ await fn();
+ } finally {
+ jsonSink = previous;
+ }
+ return sink;
}
// ── JSON optimization helpers ──────────────────────────────────────────────
@@ -872,9 +897,21 @@ export function formatLocateResults(results: LocateResult[], format: string): vo
* llm records: a header line keyed by the relation, optional diagnostic lines,
* then one `ref` row per related entity. Unresolved targets carry resolved=false.
*/
+/**
+ * The candidates an `--all` edge query ran over. Rows carry `candidate: <n>`,
+ * numbering into this list.
+ */
+export interface EdgeCandidate {
+ n: number;
+ id: string;
+ name: string;
+ kind: string;
+ path?: string;
+}
+
export function renderEdgeResultsLlm(
slice: Slice<any>, relation: string, symbol: string,
- source?: ResultSource, diagnostics?: Diagnostic[]
+ source?: ResultSource, diagnostics?: Diagnostic[], candidates?: EdgeCandidate[],
): string[] {
const refs = slice.rows.map((n: any) => {
const name = n.name || n.attrs?.name || "";
@@ -884,6 +921,7 @@ export function renderEdgeResultsLlm(
kind: n.kind ?? undefined,
id: n.id ?? undefined,
site: n.site as EdgeSite | undefined,
+ candidate: typeof n.candidate === "number" ? n.candidate as number : undefined,
...rowLocation(n),
};
});
@@ -901,7 +939,14 @@ export function renderEdgeResultsLlm(
["resolved", refs.length - unresolved],
["unresolved", unresolved > 0 ? unresolved : undefined],
["source", source && source !== "graph" ? source : undefined],
+ ["candidates", candidates ? candidates.length : undefined],
])];
+ for (const c of candidates ?? []) {
+ lines.push(llmLine("candidate", [
+ ["n", c.n], ["name", c.name], ["kind", c.kind],
+ ["path", c.path ? relativePath(c.path) ?? c.path : undefined], ["id", llmShortId(c.id)],
+ ]));
+ }
if (slice.truncated) {
lines.push(llmLine("diagnostic", [
["code", "results_truncated"],
@@ -918,16 +963,19 @@ export function renderEdgeResultsLlm(
lines.push(llmLine("diagnostic", [["code", d.code], ["message", d.message]]));
}
refs.forEach((ref, i) => {
+ // Which `--all` candidate the row belongs to. Outside projectRow: a row
+ // that lost it under `--fields` could not be attributed at all.
+ const tag: Array<[string, LlmValue]> = ref.candidate !== undefined ? [["candidate", ref.candidate]] : [];
// An unresolved row has no name to go by, so its id is all there is.
lines.push(ref.resolved
- ? llmLine("ref", projectRow([
+ ? llmLine("ref", [...projectRow([
["name", ref.name], ["kind", ref.kind], ["id", ids[i]],
["path", ref.path], ["lines", lineSpan(ref)],
["site", ref.site ? siteLabel(ref.site) : undefined],
["also", ref.site?.also?.join(",")],
["snippet", ref.site?.snippet],
- ]))
- : llmLine("ref", projectRow([["kind", ref.kind], ["id", llmShortId(ref.id)], ["resolved", false]])));
+ ]), ...tag])
+ : llmLine("ref", [...projectRow([["kind", ref.kind], ["id", llmShortId(ref.id)], ["resolved", false]]), ...tag]));
});
return lines;
}
@@ -936,12 +984,13 @@ export function formatEdgeResults(
slice: Slice<any>, relation: string, symbol: string, format: string,
resolvedTarget?: { id: string; kind: string; name: string; resolutionMode?: string },
source?: ResultSource,
- diagnostics?: Diagnostic[]
+ diagnostics?: Diagnostic[],
+ candidates?: EdgeCandidate[],
): void {
const nodes = slice.rows;
if (format === "llm") {
- for (const line of renderEdgeResultsLlm(slice, relation, symbol, source, diagnostics)) {
+ for (const line of renderEdgeResultsLlm(slice, relation, symbol, source, diagnostics, candidates)) {
console.log(line);
}
return;
@@ -957,6 +1006,7 @@ export function formatEdgeResults(
id: resolved ? n.id : undefined,
...rowLocation(n),
...(n.site ? { site: n.site } : {}),
+ ...(typeof n.candidate === "number" ? { candidate: n.candidate } : {}),
};
if (!resolved) {
ref.resolved = false;
@@ -981,6 +1031,10 @@ export function formatEdgeResults(
output.resolutionMode = resolvedTarget.resolutionMode;
}
}
+ if (candidates) {
+ output.resolutionMode = "all";
+ output.candidates = candidates.map((c) => ({ ...c, path: relativePath(c.path) ?? c.path }));
+ }
if (nodes.length === 0) {
output.diagnostics = isPastEnd(slice)
? [{ code: "offset_past_end", message: pastEndMessage(slice, relation) }]
@@ -1028,6 +1082,10 @@ export function formatEdgeResults(
if (source && source !== "graph") {
console.log(chalk.dim(`Source: ${source}`));
}
+ for (const c of candidates ?? []) {
+ const where = c.path ? ` in ${relativePath(c.path) ?? c.path}` : "";
+ console.log(chalk.dim(` [${c.n}] ${c.kind} ${c.name}${where}`));
+ }
for (const n of nodes) {
const name = n.name || n.attrs?.name || "";
const shortId = n.id?.slice(0, 8) ?? "";
@@ -1037,7 +1095,8 @@ export function formatEdgeResults(
const where = locationLabel(rowLocation(n));
console.log(
` ${chalk.cyan((n.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${chalk.bold(name)}`
- + (where ? ` ${chalk.dim(where)}` : ""),
+ + (where ? ` ${chalk.dim(where)}` : "")
+ + (typeof n.candidate === "number" ? ` ${chalk.dim(`[${n.candidate}]`)}` : ""),
);
const site = n.site as EdgeSite | undefined;
if (site) console.log(` ${chalk.dim(`at ${siteLabel(site)}`)} ${site.snippet}`);
@@ -1101,7 +1160,8 @@ export type DiagnosticCode =
| "text_fallback_used"
| "stale_source"
| "unfiltered_search"
- | "graph_degraded";
+ | "graph_degraded"
+ | "candidates_truncated";
export interface Diagnostic {
code: DiagnosticCode;
diff --git a/ix-cli/src/cli/miss-reason.ts b/ix-cli/src/cli/miss-reason.ts
new file mode 100644
index 00000000..3d1c79ea
--- /dev/null
+++ b/ix-cli/src/cli/miss-reason.ts
@@ -0,0 +1,238 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { execFile } from "node:child_process";
+import * as path from "node:path";
+import { promisify } from "node:util";
+import type { IxClient } from "../client/api.js";
+import { currentRunSignal } from "../client/run-signal.js";
+import { resolveWorkspaceRoot } from "./config.js";
+import { SKIPPED_DIRS, isGeneratedFile, isSupportedSourceFile } from "./file-discovery.js";
+import { isFileStale } from "./stale.js";
+
+const execFileAsync = promisify(execFile);
+
+/** Files whose graph state is looked up; each costs one search. */
+const FILES_CHECKED = 3;
+
+/** `IX_MISS_PROBE=0` skips the probe (a tree too large for even one bounded rg). */
+export const MISS_PROBE_ENV = "IX_MISS_PROBE";
+
+/**
+ * Wall time one run may spend on miss probes, all misses together. A
+ * multi-target call with several misses in a large tree would otherwise pay
+ * the rg walk once per miss; once the budget is spent, later misses are
+ * reported plainly. Kept per run (`ix mcp` runs many in one process), and per
+ * process outside one, where a process is one command.
+ */
+const PROBE_BUDGET_MS = 5_000;
+const spentByRun = new WeakMap<AbortSignal, number>();
+let spentOutsideRun = 0;
+
+function probeTimeSpent(): number {
+ const run = currentRunSignal();
+ return run ? spentByRun.get(run) ?? 0 : spentOutsideRun;
+}
+
+function chargeProbeTime(ms: number): void {
+ const run = currentRunSignal();
+ if (run) spentByRun.set(run, (spentByRun.get(run) ?? 0) + ms);
+ else spentOutsideRun += ms;
+}
+
+/** A file `ix map` would hand to the parser: the only kind the graph can lack for a reason `ix map` fixes. */
+function isParsedFile(file: string): boolean {
+ return isSupportedSourceFile(file) && !isGeneratedFile(path.posix.basename(file));
+}
+
+function normalizeForPathMatch(value: string): string {
+ return value.toLowerCase().replace(/\\/g, "/");
+}
+
+export interface SymbolMissReason {
+ /**
+ * `symbol_file_not_indexed` the name is in a file the graph does not have
+ * `symbol_not_extracted` the name is in indexed files, as no entity
+ * `symbol_not_in_source` the name is in no file of the workspace either
+ */
+ reason: "symbol_file_not_indexed" | "symbol_not_extracted" | "symbol_not_in_source";
+ message: string;
+ /** Workspace-relative files the name appears in (at most three). */
+ files?: string[];
+}
+
+/**
+ * Why a symbol that resolved to nothing is not in the graph, when the
+ * workspace's text can say.
+ *
+ * "No entity found" alone sends an agent to grep, which either finds the name
+ * (and the agent concludes Ix is broken) or does not (and it wasted a call).
+ * One bounded `rg -l` answers which of those it is before the agent asks: the
+ * name is in a file the graph never indexed, in an indexed file as something
+ * the parser does not extract, or nowhere at all.
+ *
+ * Best effort: no ripgrep, a timeout, or a failed search is `null`, and the
+ * miss is reported as it always was.
+ */
+export async function explainSymbolMiss(
+ client: Pick<IxClient, "search">,
+ symbol: string,
+ scope: { path?: string; workspaceId?: string; systemId?: string },
+): Promise<SymbolMissReason | null> {
+ if (!missProbeWouldRun(symbol)) return null;
+ const left = PROBE_BUDGET_MS - probeTimeSpent();
+ const name = probedName(symbol);
+
+ let root: string;
+ try { root = resolveWorkspaceRoot(); } catch { return null; }
+
+ const started = Date.now();
+ try {
+ return await probe(client, symbol, name, root, scope, left);
+ } finally {
+ chargeProbeTime(Date.now() - started);
+ }
+}
+
+/** The last segment of `Class.method` / `pkg::name`: that is the token in the text. */
+function probedName(symbol: string): string {
+ return symbol.split(/::|[.#]/).filter(Boolean).pop() ?? "";
+}
+
+/**
+ * Whether `explainSymbolMiss` would look at all: the probe is on, this run's
+ * budget is not spent, and the target is a name rg can search for. A caller
+ * that pays for its own lookup before the probe checks this first.
+ */
+export function missProbeWouldRun(symbol: string): boolean {
+ if (process.env[MISS_PROBE_ENV] === "0") return false;
+ if (PROBE_BUDGET_MS - probeTimeSpent() <= 0) return false;
+ return /^[A-Za-z_$][\w$]*$/.test(probedName(symbol));
+}
+
+/**
+ * rg skips dot-directories unless told otherwise, but `ix map` parses
+ * `.storybook/`, `.github/scripts/` and the like; only the dot-directories it
+ * skips too (`.git`, `.venv`, `.next`, ...) stay out of the search.
+ */
+const RG_SCOPE_ARGS: readonly string[] = [
+ "--hidden",
+ ...[...SKIPPED_DIRS].filter((dir) => dir.startsWith(".")).flatMap((dir) => ["-g", `!${dir}/`]),
+];
+
+async function probe(
+ client: Pick<IxClient, "search">,
+ symbol: string,
+ name: string,
+ root: string,
+ scope: { path?: string; workspaceId?: string; systemId?: string },
+ timeoutMs: number,
+): Promise<SymbolMissReason | null> {
+ const hits = await filesMentioning(name, root, scope.path, timeoutMs);
+ if (hits === null) return null;
+ if (hits.length === 0) {
+ return {
+ reason: "symbol_not_in_source",
+ message: `No entity found matching "${symbol}", and "${name}" does not appear in any file under ${scope.path ? `paths matching "${scope.path}"` : "the workspace"} either.`,
+ };
+ }
+
+ // A README or a .txt that mentions the name is no file the graph lacks:
+ // `ix map` never parses it. Only the name in no parsed file at all is left
+ // as a plain miss.
+ const files = hits.filter(isParsedFile);
+ if (files.length === 0) return null;
+
+ // Every checked file is looked up before judging: one unindexed file among
+ // indexed ones does not make re-mapping the answer.
+ const checked = files.slice(0, FILES_CHECKED);
+ const nodes = await Promise.all(checked.map((file) => graphFile(client, file, scope)));
+ const indexed: Array<{ file: string; rev?: number; stale: boolean }> = [];
+ checked.forEach((file, i) => {
+ if (!nodes[i]) return;
+ let stale = false;
+ try { stale = isFileStale(path.join(root, file)); } catch { /* unknown is not stale */ }
+ indexed.push({ file, rev: revOf(nodes[i]), stale });
+ });
+ if (indexed.length === 0) {
+ if (nodes.some((n) => n === undefined)) return null;
+ return {
+ reason: "symbol_file_not_indexed",
+ message: `"${symbol}" is not in the graph, but it appears in ${checked[0]}, which has not been indexed: ` +
+ "run `ix map`, or the file is ignored.",
+ files: checked,
+ };
+ }
+
+ const first = indexed[0];
+ const where = `${first.file}${first.rev !== undefined ? ` (indexed at rev ${first.rev})` : " (indexed)"}`;
+ const more = files.length > 1 ? ` and ${files.length - 1} other file${files.length === 2 ? "" : "s"}` : "";
+ const stale = indexed.find((f) => f.stale);
+ return {
+ reason: "symbol_not_extracted",
+ message: `"${symbol}" is not in the graph. It appears in ${where}${more}, but no entity by that name was extracted: ` +
+ (stale
+ ? `${stale.file} changed after it was indexed, so run \`ix map\` and retry.`
+ : "it may be a local, a string, or a construct the parser does not index; `ix text` finds the occurrences."),
+ files: checked,
+ };
+}
+
+/** Workspace-relative files containing `name` as a word, sorted; null when rg could not answer. */
+async function filesMentioning(name: string, root: string, pathFilter: string | undefined, timeoutMs: number): Promise<string[] | null> {
+ let stdout: string;
+ try {
+ ({ stdout } = await execFileAsync("rg", ["-l", "-F", "-w", ...RG_SCOPE_ARGS, "-e", name, "--", root], {
+ maxBuffer: 1024 * 1024, timeout: Math.min(5_000, timeoutMs), signal: currentRunSignal(),
+ }));
+ } catch (err) {
+ const failure = err as { code?: unknown; stdout?: string };
+ // rg exits 1 for "no matches": that is an answer.
+ if (failure.code === 1 && !failure.stdout) return [];
+ return null;
+ }
+ const filter = pathFilter ? normalizeForPathMatch(pathFilter) : "";
+ return stdout.split("\n")
+ .filter(Boolean)
+ .map((abs) => path.relative(root, abs).split(path.sep).join("/"))
+ .filter((rel) => !filter || normalizeForPathMatch(rel).includes(filter))
+ .sort();
+}
+
+const FILE_SEARCH_LIMIT = 50;
+
+/**
+ * The graph's node for a workspace-relative file: null when the graph has
+ * none, undefined when that cannot be told (the search failed, or its window
+ * came back full without the file -- a basename shared by more files than the
+ * window holds proves nothing about this one).
+ *
+ * The path goes to the backend as `scope`, applied before the limit, so the
+ * window holds only files at that path. A backend too old to know `scope`
+ * ignores it, and the full-window rule above keeps the answer honest there.
+ */
+async function graphFile(
+ client: Pick<IxClient, "search">,
+ file: string,
+ scope: { workspaceId?: string; systemId?: string },
+): Promise<any | null | undefined> {
+ try {
+ const nodes = await client.search(path.posix.basename(file), {
+ limit: FILE_SEARCH_LIMIT, kind: "file", nameOnly: true, scope: file,
+ workspaceId: scope.workspaceId, systemId: scope.systemId,
+ });
+ const want = normalizeForPathMatch(file);
+ const found = (nodes as any[]).find((n) => {
+ const uri = normalizeForPathMatch(n?.provenance?.sourceUri ?? n?.provenance?.source_uri ?? "");
+ return uri === want || uri.endsWith(`/${want}`);
+ });
+ if (found) return found;
+ return nodes.length >= FILE_SEARCH_LIMIT ? undefined : null;
+ } catch {
+ return undefined;
+ }
+}
+
+function revOf(node: any): number | undefined {
+ const rev = node?.createdRev ?? node?.created_rev ?? node?.rev;
+ return typeof rev === "number" ? rev : undefined;
+}
diff --git a/ix-cli/src/cli/multi-target.ts b/ix-cli/src/cli/multi-target.ts
new file mode 100644
index 00000000..c55ff118
--- /dev/null
+++ b/ix-cli/src/cli/multi-target.ts
@@ -0,0 +1,186 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import chalk from "chalk";
+import {
+ CliUsageError, WorkspaceNotMappedError, backendUnreachableError, formatFetchError, isBackendUnreachable,
+ parseBackendError,
+} from "./errors.js";
+import { captureJson, printJson, resetResolutionNotices } from "./format.js";
+import { llmError, llmLine } from "./llm.js";
+import {
+ EXIT_AMBIGUOUS, EXIT_ERROR, EXIT_NOT_FOUND, EXIT_NOT_MAPPED, EXIT_OK, exitCodeFor, runForOutcome, setOutcome,
+ type MissOutcome,
+} from "./outcome.js";
+
+/**
+ * Run a one-target command body for each of several targets and group the
+ * answers per target: `ix callers a b c` is one round trip instead of three.
+ *
+ * One target is the command exactly as before. With several:
+ *
+ * json one object, `{ targets: [{ target, exitCode, ...answer }], summary }`,
+ * where `answer` is what the command prints for that target alone
+ * llm a `target n=<i> name=<t>` record before each target's own records,
+ * then a `targets` summary record
+ * text a header line per target
+ *
+ * The process exits with the worst target's code (outcome.ts): every target
+ * answered is 0, and one miss among answers is still that miss's code, so a
+ * caller that only reads the status is never told a partial answer is whole.
+ *
+ * A target whose body throws (a backend error mid-answer) is reported in its
+ * own group with its own code, and the remaining targets still run; only a
+ * usage error, which is about the flags rather than any one target, ends the
+ * run at the process-wide boundary as before.
+ */
+export async function runPerTarget(
+ targets: readonly string[],
+ format: string,
+ run: (target: string) => Promise<void>,
+): Promise<void> {
+ if (targets.length === 1) {
+ await run(targets[0]);
+ return;
+ }
+
+ const codes: TargetCode[] = [];
+ if (format === "json") {
+ const groups: Record<string, unknown>[] = [];
+ for (const target of targets) {
+ // A target that throws after queueing a resolution notice must not
+ // hand it to the next target's json.
+ resetResolutionNotices();
+ let payloads: unknown[] = [];
+ let failure: TargetFailure | undefined;
+ const own = await runForOutcome(async () => {
+ try {
+ payloads = await captureJson(() => run(target));
+ } catch (err) {
+ failure = targetFailure(err);
+ recordFailure(failure);
+ }
+ });
+ codes.push(own);
+ const exitCode = own.exitCode;
+ groups.push(failure
+ ? {
+ target, exitCode, error: failure.code, message: failure.message,
+ ...(failure.dir ? { dir: failure.dir } : {}), ...(failure.next ? { next: failure.next } : {}),
+ }
+ : { target, exitCode, ...groupBody(payloads) });
+ }
+ // Nor may the last target's leftovers land on the grouping object.
+ resetResolutionNotices();
+ printJson({ targets: groups, summary: summarize(codes) });
+ return;
+ }
+
+ for (let index = 0; index < targets.length; index += 1) {
+ const target = targets[index];
+ resetResolutionNotices();
+ if (format === "llm") console.log(llmLine("target", [["n", index + 1], ["name", target]]));
+ else console.log(`${index > 0 ? "\n" : ""}${chalk.bold(`── ${target} ──`)}`);
+ codes.push(await runForOutcome(async () => {
+ try {
+ await run(target);
+ } catch (err) {
+ const failure = targetFailure(err);
+ recordFailure(failure);
+ if (format === "llm") {
+ console.log(llmError(failure.code, failure.message, [
+ ...(failure.dir ? [["dir", failure.dir] as [string, string]] : []),
+ ...(failure.next ? [["hint", failure.next] as [string, string]] : []),
+ ]));
+ } else {
+ process.stderr.write(chalk.red(`Error: ${failure.message}\n`));
+ if (failure.next) process.stderr.write(chalk.dim(`${failure.next}\n`));
+ }
+ }
+ }));
+ }
+ if (format === "llm") {
+ const summary = summarize(codes);
+ console.log(llmLine("targets", [
+ ["total", summary.total], ["ok", summary.ok],
+ ["ambiguous", summary.ambiguous || undefined], ["not_found", summary.notFound || undefined],
+ ["not_mapped", summary.notMapped || undefined], ["failed", summary.failed || undefined],
+ ]));
+ }
+}
+
+interface TargetFailure {
+ code: string;
+ message: string;
+ next?: string;
+ /** The unmapped directory, as the one-target `workspace_not_mapped` record carries it. */
+ dir?: string;
+ exitCode: number;
+ outcome?: MissOutcome;
+}
+
+type TargetCode = { exitCode: number; outcome?: MissOutcome };
+
+/** A thrown target's status, recorded as its outcome when it has one. */
+function recordFailure(failure: TargetFailure): void {
+ if (failure.outcome) setOutcome(failure.outcome);
+ else process.exitCode = failure.exitCode;
+}
+
+/**
+ * What one target's thrown error says, in the slugs and codes the
+ * process-wide boundary (`renderCliError`) would use, without exiting.
+ * A usage error is rethrown: it is the same for every target.
+ */
+function targetFailure(err: unknown): TargetFailure {
+ if (err instanceof CliUsageError) throw err;
+ if (err instanceof WorkspaceNotMappedError) {
+ return {
+ code: err.code, message: err.summary, next: err.hint, dir: err.dir, exitCode: exitCodeFor("not_mapped"), outcome: "not_mapped",
+ };
+ }
+ if (isBackendUnreachable(err)) {
+ const unreachable = backendUnreachableError();
+ return { code: unreachable.error, message: unreachable.message, next: unreachable.next, exitCode: EXIT_ERROR };
+ }
+ const raw = (err as { message?: unknown } | null | undefined)?.message;
+ const structured = typeof raw === "string" ? parseBackendError(raw) : null;
+ if (structured) {
+ return { code: structured.error, message: structured.message, next: structured.next, exitCode: EXIT_ERROR };
+ }
+ const message = err === null || err === undefined ? String(err) : formatFetchError(err);
+ return { code: "cli_error", message, exitCode: EXIT_ERROR };
+}
+
+/** One JSON object per target as-is; anything else under `result(s)`. */
+function groupBody(payloads: unknown[]): Record<string, unknown> {
+ if (payloads.length === 1) {
+ const only = payloads[0];
+ if (only !== null && typeof only === "object" && !Array.isArray(only)) return only as Record<string, unknown>;
+ return { result: only };
+ }
+ return payloads.length === 0 ? {} : { results: payloads };
+}
+
+/**
+ * Which summary bucket a target falls in. By its code, or, when the legacy
+ * switch made a miss exit 1, by the outcome it recorded, so the summary says
+ * the same with or without `IX_LEGACY_EXIT_CODES`.
+ */
+function bucketOf({ exitCode, outcome }: TargetCode): "ok" | MissOutcome | "failed" {
+ switch (exitCode) {
+ case EXIT_OK: return "ok";
+ case EXIT_AMBIGUOUS: return "ambiguous";
+ case EXIT_NOT_FOUND: return "not_found";
+ case EXIT_NOT_MAPPED: return "not_mapped";
+ }
+ return outcome && exitCode === EXIT_ERROR && exitCodeFor(outcome) === EXIT_ERROR ? outcome : "failed";
+}
+
+function summarize(codes: readonly TargetCode[]) {
+ const buckets = codes.map(bucketOf);
+ const count = (b: ReturnType<typeof bucketOf>) => buckets.filter((x) => x === b).length;
+ return {
+ total: codes.length, ok: count("ok"), ambiguous: count("ambiguous"), notFound: count("not_found"),
+ notMapped: count("not_mapped"), failed: count("failed"),
+ };
+}
diff --git a/ix-cli/src/cli/outcome.ts b/ix-cli/src/cli/outcome.ts
new file mode 100644
index 00000000..42b0e2c0
--- /dev/null
+++ b/ix-cli/src/cli/outcome.ts
@@ -0,0 +1,124 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+/**
+ * Exit codes for a graph command whose target did not resolve to one entity.
+ *
+ * A coding agent treats any non-zero exit as "the tool is broken" and goes
+ * back to grep. When a miss, an ambiguous name, an unmapped directory and a
+ * real failure all exited 1, the agent could not tell "retry with --pick" from
+ * "give up". Each now has its own code, and the machine formats carry the
+ * matching error slug (json `error`, llm `error code=`):
+ *
+ * 0 results
+ * 1 a real error (backend down, bad argument, ...)
+ * 2 ambiguous target: candidates returned `ambiguous_target`
+ * 3 target not found: suggestions when known `unresolved_target`
+ * 4 workspace not mapped `workspace_not_mapped`
+ *
+ * All of them are still non-zero, so a runner that only asks "did it fail?"
+ * sees what it always saw. `IX_LEGACY_EXIT_CODES=1` collapses 2, 3 and 4 back
+ * to 1 for an integration that compares the status against 1.
+ */
+export const EXIT_OK = 0;
+export const EXIT_ERROR = 1;
+export const EXIT_AMBIGUOUS = 2;
+export const EXIT_NOT_FOUND = 3;
+export const EXIT_NOT_MAPPED = 4;
+
+export const LEGACY_EXIT_CODES_ENV = "IX_LEGACY_EXIT_CODES";
+
+export type MissOutcome = "ambiguous" | "not_found" | "not_mapped";
+
+const CODES: Record<MissOutcome, number> = {
+ ambiguous: EXIT_AMBIGUOUS,
+ not_found: EXIT_NOT_FOUND,
+ not_mapped: EXIT_NOT_MAPPED,
+};
+
+/** One line per code, for `--help` and the agent docs. */
+export const EXIT_CODES_HELP = `
+Exit codes:
+ 0 results 2 ambiguous: candidates listed 4 workspace not mapped
+ 1 error 3 not found: suggestions listed
+ ${LEGACY_EXIT_CODES_ENV}=1 makes every non-zero exit 1.`;
+
+export function legacyExitCodes(): boolean {
+ const value = process.env[LEGACY_EXIT_CODES_ENV]?.trim().toLowerCase();
+ return !!value && value !== "0" && value !== "false" && value !== "no";
+}
+
+/** The exit code for an outcome, honouring the legacy switch. */
+export function exitCodeFor(outcome: MissOutcome): number {
+ return legacyExitCodes() ? EXIT_ERROR : CODES[outcome];
+}
+
+/**
+ * How bad a code is, for a run that answered several targets: an error beats
+ * an unmapped workspace beats a miss beats an ambiguity, so the worst one
+ * decides the status. Unknown non-zero codes count as errors.
+ */
+function severity(code: number): number {
+ switch (code) {
+ case EXIT_OK: return 0;
+ case EXIT_AMBIGUOUS: return 1;
+ case EXIT_NOT_FOUND: return 2;
+ case EXIT_NOT_MAPPED: return 3;
+ default: return 4;
+ }
+}
+
+/** The more severe of two exit codes. */
+export function worseExitCode(a: number, b: number): number {
+ return severity(b) > severity(a) ? b : a;
+}
+
+function currentExitCode(): number {
+ const code = process.exitCode;
+ if (code === undefined || code === null || code === "") return EXIT_OK;
+ const n = Number(code);
+ return Number.isFinite(n) ? n : EXIT_ERROR;
+}
+
+/**
+ * The worst outcome recorded since `runForOutcome` last reset it. The exit
+ * code alone cannot say which outcome a target had under the legacy switch,
+ * where every one of them is 1.
+ */
+let recorded: MissOutcome | undefined;
+
+function worseOutcome(a: MissOutcome | undefined, b: MissOutcome | undefined): MissOutcome | undefined {
+ if (!a || !b) return a ?? b;
+ return CODES[b] > CODES[a] ? b : a;
+}
+
+/**
+ * Record an outcome on `process.exitCode`, keeping any worse status already
+ * set: one target's ambiguity must not hide another's error.
+ */
+export function setOutcome(outcome: MissOutcome): void {
+ recorded = worseOutcome(recorded, outcome);
+ process.exitCode = worseExitCode(currentExitCode(), exitCodeFor(outcome));
+}
+
+/**
+ * Run one target of a multi-target command and return the exit code it alone
+ * would have had, and the worst outcome it recorded, leaving
+ * `process.exitCode` at the worst code so far.
+ */
+export async function runForOutcome(fn: () => Promise<void>): Promise<{ exitCode: number; outcome?: MissOutcome }> {
+ const before = currentExitCode();
+ const recordedBefore = recorded;
+ process.exitCode = undefined;
+ recorded = undefined;
+ await fn();
+ const own = currentExitCode();
+ const outcome = recorded;
+ process.exitCode = worseExitCode(before, own) || undefined;
+ recorded = worseOutcome(recordedBefore, outcome);
+ return { exitCode: own, ...(outcome ? { outcome } : {}) };
+}
+
+/** `runForOutcome`'s exit code alone. */
+export async function runForExitCode(fn: () => Promise<void>): Promise<number> {
+ return (await runForOutcome(fn)).exitCode;
+}
diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.ts
index 97202230..e362524e 100644
--- a/ix-cli/src/cli/resolve.ts
+++ b/ix-cli/src/cli/resolve.ts
@@ -15,6 +15,8 @@ import { reportAmbiguousTarget, reportResolutionFailure, reportResolutionNotices
import { relativePath } from "./format.js";
import { isQuiet } from "./output-shape.js";
import { disambiguationHint } from "./next-step.js";
+import { explainSymbolMiss, missProbeWouldRun } from "./miss-reason.js";
+import { isBackendUnreachable } from "./errors.js";
import {
candidateOrigin, isFileStemMatch, looksLikeCodeIdentifier, requestsNonCode,
} from "./candidate-origin.js";
@@ -236,6 +238,8 @@ export interface ResolveOpts {
format?: string;
/** Internal: the caller reports the miss itself (a file target's miss). */
silentMiss?: boolean;
+ /** The command takes `--all`, so an ambiguity's hint names it. */
+ offerAll?: boolean;
}
export interface Suggestion {
@@ -260,6 +264,8 @@ export type ResolveResult =
*/
reason?: string;
message?: string;
+ /** For a symbol miss with a `symbol_*` reason: the files the name appears in. */
+ files?: string[];
/** Set by the reporter's caller when the graph itself is empty or degraded. */
graph?: GraphHealth;
};
@@ -689,7 +695,7 @@ function tieNotice(
const lower = lowerCount > 0
? ` ${lowerCount} more scored lower and ${lowerCount === 1 ? "is" : "are"} not listed.`
: "";
- return {
+ const notice: ResolutionNotice = {
code: "ambiguous_target",
target: symbol,
message: `"${symbol}" matches ${windowFull ? "at least " : ""}${tier.length} candidates equally; using ${chosen.name || symbol}${where ? ` (${where})` : ""}.${lower}`,
@@ -698,6 +704,8 @@ function tieNotice(
total: tier.length,
...(windowFull ? { truncated: true } : {}),
};
+ rememberAll(notice, amb.candidates, allCandidatesOf(amb), importIdsOf(amb));
+ return notice;
}
/**
@@ -819,7 +827,9 @@ export function applyPick(
if (result.resolved) return null; // already resolved, no need to pick
if (!result.ambiguous) return null;
- const candidates = result.result.candidates;
+ // Every tied candidate, the shown 8 first: `--all` numbers past 8 (n=9...)
+ // and `--pick` must reach them by the same numbers.
+ const candidates = allCandidatesOf(result.result);
const idx = opts.pick - 1; // convert 1-based to 0-based
if (idx < 0 || idx >= candidates.length) {
@@ -864,15 +874,16 @@ export function pickFromNotice(
const at = result.notices.findIndex((n) => n.code === "ambiguous_target");
if (at < 0) return result;
const notice = result.notices[at];
+ const candidates = allCandidatesOf(notice);
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}).`;
+ if (idx < 0 || idx >= candidates.length) {
+ const message = `--pick ${opts.pick} is out of range (1-${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 picked = candidates[idx];
const keepFuzzy = result.entity.resolutionMode === "fuzzy";
return {
...result,
@@ -918,6 +929,37 @@ function nodeToResolved(node: any, symbol: string, mode: ResolutionMode): Resolv
};
}
+/**
+ * Every tied candidate behind an ambiguous result or notice, not only the 8
+ * shown. Kept beside the object rather than on it, so no json or llm renderer
+ * that prints the result can leak a list of hundreds. `--all` reads it
+ * (`allCandidatesOf`): the shown 8 first, numbered as `--pick` numbers them,
+ * then the rest in display order. `imports` holds the ids of the candidates
+ * that are imports of the name rather than definitions (candidate-origin.ts),
+ * which `--all` skips when a definition is listed too.
+ */
+const fullCandidates = new WeakMap<object, { all: AmbiguousResult["candidates"]; imports: Set<string> }>();
+
+function rememberAll(
+ owner: object,
+ shown: AmbiguousResult["candidates"],
+ all: AmbiguousResult["candidates"],
+ imports: Set<string> = new Set(),
+): void {
+ const shownIds = new Set(shown.map((c) => c.id));
+ fullCandidates.set(owner, { all: [...shown, ...all.filter((c) => !shownIds.has(c.id))], imports });
+}
+
+/** The full candidate list behind an ambiguous result or notice (falls back to the shown ones). */
+export function allCandidatesOf(owner: AmbiguousResult | ResolutionNotice): AmbiguousResult["candidates"] {
+ return fullCandidates.get(owner)?.all ?? owner.candidates;
+}
+
+/** The ids among `allCandidatesOf(owner)` that are imports of the name, not definitions. */
+function importIdsOf(owner: object): Set<string> {
+ return fullCandidates.get(owner)?.imports ?? new Set();
+}
+
function buildAmbiguous(
nodes: any[],
scores?: number[],
@@ -947,7 +989,7 @@ function buildAmbiguous(
rank,
};
});
- return {
+ const result: AmbiguousResult = {
resolutionMode: "ambiguous",
candidates,
...(extra?.total != null ? { total: extra.total } : {}),
@@ -957,6 +999,10 @@ function buildAmbiguous(
...(extra?.diagnostics ?? []),
],
};
+ const unique = nodes.filter((n: any, i) => n?.id && nodes.findIndex((m: any) => m?.id === n.id) === i);
+ const imports = new Set(unique.filter((n: any) => candidateOrigin(n) === "import").map((n: any) => String(n.id)));
+ rememberAll(result, candidates, [...unique].sort(displayOrder).map(candidateOf), imports);
+ return result;
}
export function printAmbiguous(symbol: string, result: AmbiguousResult, opts?: { kind?: string; path?: string }): void {
@@ -1068,22 +1114,28 @@ export async function resolveFileOrEntityFull(
): Promise<ResolveResult> {
// 1. Raw UUID
if (isRawId(target)) {
+ let n: any;
try {
- const details = await client.entity(target);
- const n = details.node as any;
- return {
- resolved: true,
- entity: {
- id: target,
- kind: n.kind || "unknown",
- name: n.name || target,
- resolutionMode: "exact",
- },
- };
- } catch {
+ n = (await client.entity(target))?.node;
+ } catch (err) {
+ // Only "no such id" is a miss. A backend that is down, refusing or
+ // erroring is a real error (exit 1), not a missing symbol (exit 3).
+ if (!isLookupMiss(err)) throw err;
+ }
+ // A 200 without a node names nothing too: a miss, not a cli_error.
+ if (!n || typeof n !== "object") {
missProse(opts, `Entity not found: ${target}`);
return { resolved: false, ambiguous: false };
}
+ return {
+ resolved: true,
+ entity: {
+ id: target,
+ kind: n.kind || "unknown",
+ name: n.name || target,
+ resolutionMode: "exact",
+ },
+ };
}
// 1.5 Short ID prefix (8–31 hex chars, e.g. "aacc3359" from CLI output)
@@ -1101,8 +1153,12 @@ export async function resolveFileOrEntityFull(
resolutionMode: "exact",
},
};
- } catch {
- // Not a valid entity prefix — fall through to normal resolution
+ } catch (err) {
+ // A hex-looking target can still be a symbol name (`deadbeef`), so any
+ // answer short of an unreachable backend falls through to the name
+ // search rather than failing a symbol that exists. Unreachable is
+ // rethrown only because the name search would fail the same way.
+ if (isBackendUnreachable(err)) throw err;
}
}
@@ -1343,19 +1399,17 @@ async function resolveInClasses(
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 qualifiedResult: AmbiguousResult = {
+ 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.") },
+ ],
};
+ rememberAll(qualifiedResult, qualifiedResult.candidates, ordered);
+ const ambiguous: ResolveResult = { resolved: false, ambiguous: true, result: qualifiedResult };
const picked = applyPick(ambiguous, opts);
if (picked?.resolved) return { ...picked, entity: { ...picked.entity, name: display } };
return picked ?? ambiguous;
@@ -1478,19 +1532,195 @@ export async function resolveFileOrReport(
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.
- const graph = await checkGraphHealth(client, activeScope());
- if (isUnhealthy(graph)) {
- reportResolutionFailure(target, { ...result, graph }, format, opts);
- return null;
+ await reportUnresolved(client, target, result, opts, format);
+ return null;
+}
+
+/**
+ * Report a target that did not resolve, with the best "why" available: the
+ * graph is empty or degraded, or (for a symbol) what the workspace's text says
+ * about the name. Sets the exit code (outcome.ts).
+ */
+export async function reportUnresolved(
+ client: IxClient,
+ target: string,
+ result: Exclude<ResolveResult, { resolved: true }>,
+ opts: ResolveOpts | undefined,
+ format: string,
+): Promise<void> {
+ if (result.ambiguous) {
+ reportResolutionFailure(target, result, format, opts);
+ return;
+ }
+ // 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.
+ const graph = await checkGraphHealth(client, activeScope());
+ if (isUnhealthy(graph)) {
+ reportResolutionFailure(target, { ...result, graph }, format, opts);
+ return;
+ }
+ reportResolutionFailure(target, await withMissReason(client, target, result, opts, format), format, opts);
+}
+
+/**
+ * A symbol miss with the reason the workspace's text gives (miss-reason.ts).
+ * A file target already carries its own; a raw id has no text to look for.
+ */
+export async function withMissReason<T extends { reason?: string; message?: string; hiddenTestCount?: number }>(
+ client: IxClient,
+ target: string,
+ result: T,
+ opts: ResolveOpts | undefined,
+ format: string | undefined,
+): Promise<T> {
+ if (result.reason || isRawId(target) || looksFileLike(target)) return result;
+ // filteredOut costs a search: not for a probe that is off or out of budget.
+ if (!missProbeWouldRun(target)) return result;
+ if (await filteredOut(client, target, result, opts)) return result;
+ const why = await explainSymbolMiss(client, target, { path: opts?.path, ...activeScope() });
+ if (!why) return result;
+ // The resolver already wrote the bare miss for a person; this is the part
+ // that says what to do about it. Machine formats get it in the record.
+ if (format !== "json" && format !== "llm") stderr(chalk.dim(why.message));
+ return { ...result, reason: why.reason, message: why.message, ...(why.files ? { files: why.files } : {}) };
+}
+
+/**
+ * Whether the miss is the filters' doing: `--kind`, `--path` or the test
+ * filter set aside an entity that does carry the name. The probe judges by
+ * the text alone, so it would call such a name never extracted and send the
+ * agent to `ix text`; the plain miss, with its suggestions, is the true
+ * answer. One unfiltered search, and only when a filter was in play. A failed
+ * search counts as filtered out: it is no evidence the entity is missing.
+ */
+async function filteredOut(
+ client: IxClient,
+ target: string,
+ result: { hiddenTestCount?: number },
+ opts: ResolveOpts | undefined,
+): Promise<boolean> {
+ if (!opts?.kind && !opts?.path && !opts?.testsOnly && !result.hiddenTestCount) return false;
+ const name = target.split(/::|[.#]/).filter(Boolean).pop() ?? target;
+ const { workspaceId, systemId } = activeScope();
+ try {
+ const nodes = await client.search(name, { limit: 50, nameOnly: true, workspaceId, systemId });
+ return (nodes as any[]).some((n) => (n?.name || n?.attrs?.name || "") === name);
+ } catch {
+ return true;
+ }
+}
+
+/** The entities a command with `--all` runs over. */
+export interface TargetSet {
+ /**
+ * Under `--all`, each entity's `n` is its `--pick` number in the ambiguity
+ * list, so numbers can skip a candidate `--all` leaves out (an import).
+ */
+ entities: Array<ResolvedEntity & { n?: number }>;
+ /**
+ * Present when `--all` expanded the target to its candidates. `capped`:
+ * more candidates were listed than `ALL_CANDIDATE_CAP`, so only the first
+ * ones are answered.
+ */
+ all?: { total: number; truncated?: boolean; capped?: boolean };
+}
+
+/**
+ * The one entity a target resolves to or, under `--all`, every listed
+ * candidate of an ambiguous one (and of a target that resolved by choosing
+ * among equal ties). `null` after reporting a miss.
+ *
+ * Without `--all`, or with `--pick`, this is `resolveFileOrReport`.
+ */
+export async function resolveTargetSetOrReport(
+ client: IxClient,
+ target: string,
+ opts: (ResolveOpts & { all?: boolean }) | undefined,
+ format: string,
+): Promise<TargetSet | null> {
+ const withAll = { ...opts, offerAll: true };
+ if (!opts?.all || opts.pick !== undefined) {
+ const entity = await resolveFileOrReport(client, target, withAll, format);
+ return entity ? { entities: [entity] } : null;
+ }
+ const result = await resolveFileOrEntityFull(client, target, { ...opts, format });
+ if (result.resolved) {
+ const tie = result.notices?.find((n) => n.code === "ambiguous_target");
+ if (!tie || tie.candidates.length <= 1) {
+ if (result.notices?.length) reportResolutionNotices(result.notices, format, opts);
+ return { entities: [result.entity] };
}
+ return candidateSet(tie, tie.total, tie.truncated);
}
- reportResolutionFailure(target, result, format, opts);
+ if (result.ambiguous) {
+ return candidateSet(result.result, result.result.total, result.result.truncated);
+ }
+ await reportUnresolved(client, target, result, withAll, format);
return null;
}
+/**
+ * The most candidates one `--all` call answers for. Each is at least one
+ * backend query (`impact` runs a whole analysis per candidate, one after
+ * another), so a common name must not turn one call into hundreds of round
+ * trips; past the cap, `--kind`/`--path` or `--pick` reach the rest.
+ */
+export const ALL_CANDIDATE_CAP = 25;
+
+/**
+ * Why an `--all` answer may not cover every candidate, or undefined when it
+ * does: `ALL_CANDIDATE_CAP` stopped it, or the resolver's search window came
+ * back full, so names past it were never seen.
+ */
+export function candidatesCut(set: TargetSet, answered: number, verb: string): string | undefined {
+ if (!set.all) return undefined;
+ if (set.all.capped) {
+ return `${verb} the first ${answered} of ${set.all.total}${set.all.truncated ? "+" : ""} candidates ` +
+ `(--all answers at most ${ALL_CANDIDATE_CAP}); narrow with --kind or --path, or reach one with --pick <n>.`;
+ }
+ if (!set.all.truncated && set.all.total <= answered) return undefined;
+ return `${verb} ${answered} candidates, but the name search was cut off, so there may be more; ` +
+ "narrow with --kind or --path to cover the rest.";
+}
+
+/**
+ * The candidates `--all` answers for, each keeping its `--pick` number. An
+ * import of the name (`from app.utils import clamp`) is listed in an ambiguity
+ * but is not a definition: when a definition is listed too, the import is
+ * skipped, since its callers are the definition's. When only imports are
+ * listed they are still the answer (the same demotion-not-filter rule as
+ * `originPenalty`).
+ */
+function candidateSet(owner: AmbiguousResult | ResolutionNotice, total?: number, truncated?: boolean): TargetSet {
+ const numbered = allCandidatesOf(owner).map((c, i) => ({ c, n: i + 1 }));
+ const imports = importIdsOf(owner);
+ const definitions = numbered.filter(({ c }) => !imports.has(c.id));
+ const kept = definitions.length > 0 ? definitions : numbered;
+ const skipped = numbered.length - kept.length;
+ const answered = kept.slice(0, ALL_CANDIDATE_CAP);
+ return {
+ entities: answered.map(({ c, n }) => ({ id: c.id, kind: c.kind, name: c.name, path: c.path, resolutionMode: "ambiguous", n })),
+ all: {
+ total: Math.max((total ?? numbered.length) - skipped, kept.length),
+ ...(truncated ? { truncated: true } : {}),
+ ...(kept.length > answered.length ? { capped: true } : {}),
+ },
+ };
+}
+
+/**
+ * Whether an id lookup failed because the id names nothing: the backend's
+ * 400/404/410 (`<status>: ...`, see `httpError`) or `resolvePrefix`'s own
+ * no-match and ambiguous-prefix errors. Anything else -- a refused
+ * connection, a 5xx, a 401 -- is not evidence about the id.
+ */
+export function isLookupMiss(err: unknown): boolean {
+ const message = err instanceof Error ? err.message : String(err);
+ return /^(400|404|410):/.test(message)
+ || message.startsWith("No entity found for prefix:")
+ || message.startsWith("Ambiguous prefix ");
+}
+
/**
* Search the graph for a file entity matching the target path or filename.
*
@@ -1626,6 +1856,7 @@ async function tryFileGraphMatch(
total: tied.length,
...(truncated ? { truncated: true } : {}),
};
+ rememberAll(notice, amb.candidates, allCandidatesOf(amb), importIdsOf(amb));
const notices = fuzzy ? [notice, fuzzyNotice(target, chosen)] : [notice];
return pickFromNotice({ resolved: true, entity: chosen, notices }, opts);
}
diff --git a/ix-cli/src/cli/ui.ts b/ix-cli/src/cli/ui.ts
index 5c6d1390..95508890 100644
--- a/ix-cli/src/cli/ui.ts
+++ b/ix-cli/src/cli/ui.ts
@@ -15,6 +15,7 @@ import { isQuiet } from "./output-shape.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";
+import { setOutcome } from "./outcome.js";
// ── Brand palette ─────────────────────────────────────────────────────────────
//
@@ -177,7 +178,7 @@ export function reportUnresolvedTarget(
target: string | string[],
format?: string,
suggestions?: Suggestion[],
- detail?: { reason?: string; message?: string; graph?: GraphHealth },
+ detail?: { reason?: string; message?: string; graph?: GraphHealth; files?: string[] },
): void {
// A file target's miss says which of "not ingested" and "does not exist" it
// is; the code stays `unresolved_target` so a consumer routes on one slug.
@@ -188,12 +189,16 @@ export function reportUnresolvedTarget(
...unresolvedTargetRecord(target),
message,
...(detail?.reason ? { reason: detail.reason } : {}),
+ ...(detail?.files?.length ? { files: detail.files } : {}),
...(near.length ? { suggestions: near } : {}),
...(detail?.graph ? { graph: graphHealthJson(detail.graph) } : {}),
});
} else if (format === "llm") {
const lines = [
- llmError("unresolved_target", message, detail?.reason ? [["reason", detail.reason]] : []),
+ llmError("unresolved_target", message, [
+ ...(detail?.reason ? [["reason", detail.reason]] as Array<[string, string]> : []),
+ ...(detail?.files?.length ? [["files", detail.files.join(",")]] as Array<[string, string]> : []),
+ ]),
...(detail?.graph ? [llmLine("graph", graphHealthLlmFields(detail.graph))] : []),
...candidateLines(near, "suggestion"),
];
@@ -204,7 +209,7 @@ export function reportUnresolvedTarget(
} else {
if (detail?.graph) console.error(chalk.yellow(graphHealthProse(detail.graph)));
if (!near.length) {
- process.exitCode = 1;
+ setOutcome("not_found");
return;
}
// The resolver already wrote the miss itself for a person; this adds the
@@ -214,7 +219,7 @@ export function reportUnresolvedTarget(
console.error(` ${chalk.cyan((s.kind || "").padEnd(10))} ${s.name}${s.path ? chalk.dim(` in ${s.path}`) : ""}`);
}
}
- process.exitCode = 1;
+ setOutcome("not_found");
}
/**
@@ -244,7 +249,7 @@ export function reportAmbiguousTarget(
target: string,
result: AmbiguousResult,
format?: string,
- opts?: { kind?: string; path?: string },
+ opts?: { kind?: string; path?: string; offerAll?: boolean },
): void {
const message = `Ambiguous symbol "${target}".`;
if (format === "json") {
@@ -264,6 +269,7 @@ export function reportAmbiguousTarget(
const hints = [mcp ? "pick=<n>" : "--pick <n>"];
if (!opts?.kind) hints.push(mcp ? "kind=<kind>" : "--kind");
if (!opts?.path) hints.push(mcp ? "path=<file substring>" : "--path");
+ if (opts?.offerAll && !mcp) hints.push("--all");
const lines = [
llmError("ambiguous_target", message, [
["count", String(result.candidates.length)],
@@ -292,7 +298,8 @@ export function reportAmbiguousTarget(
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.`));
+ if (opts?.offerAll) hints.push("--all");
+ console.error(chalk.dim(`\nUse ${hints.join(" or ")} to disambiguate${opts?.offerAll ? " (--all answers for every candidate)" : ""}.`));
}
/**
@@ -367,9 +374,14 @@ export function reportResolutionFailure(
target: string,
result: Exclude<ResolveResult, { resolved: true }>,
format?: string,
- opts?: { kind?: string; path?: string },
+ opts?: { kind?: string; path?: string; offerAll?: boolean },
): void {
- if (result.ambiguous) reportAmbiguousTarget(target, result.result, format, opts);
- else reportUnresolvedTarget(target, format, result.suggestions, { reason: result.reason, message: result.message, graph: result.graph });
- process.exitCode = 1;
+ if (result.ambiguous) {
+ reportAmbiguousTarget(target, result.result, format, opts);
+ setOutcome("ambiguous");
+ } else {
+ reportUnresolvedTarget(target, format, result.suggestions, {
+ reason: result.reason, message: result.message, graph: result.graph, files: result.files,
+ });
+ }
}
diff --git a/ix-cli/test/e2e/scenarios.e2e.ts b/ix-cli/test/e2e/scenarios.e2e.ts
index 74079b30..be85bdf0 100644
--- a/ix-cli/test/e2e/scenarios.e2e.ts
+++ b/ix-cli/test/e2e/scenarios.e2e.ts
@@ -14,7 +14,7 @@
import { readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
-import { afterAll, beforeAll, beforeEach, describe, it } from "vitest";
+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
import {
type Checkout,
type E2eEnv,
@@ -23,6 +23,7 @@ import {
e2eEnv,
freshSignature,
git,
+ ix,
map,
resetBackend,
expectSameGraph,
@@ -210,3 +211,56 @@ describe("incremental equals fresh", () => {
expectSameGraph("map twice", await signature(env, co), first);
});
});
+
+// The outcome contract agents route on (ix-cli/src/cli/outcome.ts), against a
+// real backend: `clamp` is defined in app/utils.py and web/src/math.ts, and
+// app/pricing.py imports it (`from app.utils import clamp`, a one-line module
+// entity the ambiguity lists as --pick 1 but --all skips).
+describe("agent outcomes", () => {
+ it("exits 0 / 2 / 3 / 4 for results, ambiguity, a miss and an unmapped directory", () => {
+ const co = checkout("polyglot");
+ map(env, co);
+
+ expect(ix(env, co, ["locate", "slugify", "--format", "json"]).status).toBe(0);
+
+ const ambiguous = ix(env, co, ["callers", "clamp", "--format", "json"], true);
+ expect(ambiguous.status).toBe(2);
+ expect(JSON.parse(ambiguous.stdout).error).toBe("ambiguous_target");
+
+ const miss = ix(env, co, ["locate", "definitelyNotAName", "--format", "json"], true);
+ expect(miss.status).toBe(3);
+ expect(JSON.parse(miss.stdout).error).toBe("unresolved_target");
+
+ const unmapped = checkout("polyglot-b");
+ const notMapped = ix(env, unmapped, ["locate", "slugify", "--format", "json"], true);
+ expect(notMapped.status).toBe(4);
+ expect(JSON.parse(notMapped.stdout).error).toBe("workspace_not_mapped");
+
+ process.env.IX_LEGACY_EXIT_CODES = "1";
+ try {
+ expect(ix(env, co, ["callers", "clamp", "--format", "json"], true).status).toBe(1);
+ } finally {
+ delete process.env.IX_LEGACY_EXIT_CODES;
+ }
+ });
+
+ it("--all answers every candidate, and several targets answer in one call", () => {
+ const co = checkout("polyglot");
+ map(env, co);
+
+ const all = JSON.parse(ix(env, co, ["callers", "clamp", "--all", "--format", "json"]).stdout);
+ expect(all.resolutionMode).toBe("all");
+ expect(all.candidates.map((c: { path: string }) => c.path).sort()).toEqual(["app/utils.py", "web/src/math.ts"]);
+ expect(all.results.length).toBeGreaterThan(0);
+ // Each candidate keeps the number --pick gives it in the ambiguity list.
+ const listed = JSON.parse(ix(env, co, ["callers", "clamp", "--format", "json"], true).stdout).candidates;
+ for (const c of all.candidates) {
+ expect(listed.find((l: { rank: number }) => l.rank === c.n)).toMatchObject({ id: c.id });
+ }
+ for (const row of all.results) expect(all.candidates.map((c: { n: number }) => c.n)).toContain(row.candidate);
+
+ const many = ix(env, co, ["locate", "slugify", "clamp", "definitelyNotAName", "--format", "json"], true);
+ expect(many.status).toBe(3);
+ expect(JSON.parse(many.stdout).targets.map((t: { exitCode: number }) => t.exitCode)).toEqual([0, 2, 3]);
+ });
+});
diff --git a/ix-cli/vitest.setup.ts b/ix-cli/vitest.setup.ts
index 77ef5760..7c4eeee8 100644
--- a/ix-cli/vitest.setup.ts
+++ b/ix-cli/vitest.setup.ts
@@ -15,3 +15,10 @@
// -- vitest re-runs setupFiles for each file, and `process.env` is per worker
// under the default forks pool, so no file can leak an IX_HOME to the next.
delete process.env.IX_HOME;
+
+// A target that resolves to nothing runs one bounded `rg` over the workspace to
+// say why (`cli/miss-reason.ts`). Under test the "workspace" is this checkout,
+// whose sources and fixtures mention every name a test misses on, so the
+// reason would depend on the repository's contents. Off by default here; the
+// tests for the probe turn it back on.
+process.env.IX_MISS_PROBE = "0";
diff --git a/skills/ix/SKILL.md b/skills/ix/SKILL.md
index 98f119b1..86f3f556 100644
--- a/skills/ix/SKILL.md
+++ b/skills/ix/SKILL.md
@@ -56,6 +56,26 @@ tool calls; an ambiguous name answers with candidates and `pick=`/`path=` to
choose one. No health check is needed first. `ix mcp --tools=all` serves
every command as a tool.
+## Reading the exit code
+
+A non-zero exit from a graph command is usually an answer, not a breakage:
+
+| Exit | Means | Do |
+|---|---|---|
+| 0 | results | use them |
+| 2 | ambiguous: candidates listed | re-run with `--pick <n>` or `--path`, or `--all` (`callers`/`callees`/`impact`) for every candidate at once |
+| 3 | not found | read `reason` / `suggestion`: a file not indexed means `ix map`; a near name means retry with it |
+| 4 | workspace not mapped | `ix map` |
+| 1 | a real error | read the `error` record |
+
+json carries the same outcome in `error` (`ambiguous_target`,
+`unresolved_target`, `workspace_not_mapped`); llm in `error code=`. One
+exception: `ix locate`'s json ambiguity carries it as `code: "ambiguous_target"`
+(with its candidates), not `error`; and `ix read`'s ambiguity exits 0 with an
+`ambiguous` record (json `targetType: "ambiguous-symbol"`) and its candidates.
+Ask about
+several names in one call: `ix locate a b c`, `ix callers a b c`.
+
## How to spend calls
1. **Start with `ix context <file-or-symbol>`** — one bounded call that names the
diff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.md
index 8b4ceaf1..af0c4db8 100644
--- a/skills/ix/references/flags.md
+++ b/skills/ix/references/flags.md
@@ -129,6 +129,20 @@ surfaces (#575).
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).
+- **`--all` answers an ambiguous name for every candidate** (`callers`,
+ `callees`, `impact`), instead of exiting 2 with the candidate list. Each row
+ (or, for `impact`, each analysis) carries `candidate=<n>`, numbering the
+ `candidate` records printed with it. It covers the tied candidates the name
+ search returned, not only the 8 an ambiguity lists (numbered as `--pick`
+ numbers them; an import of the name is skipped when a definition is listed
+ too), up to 25 per call, so narrow with `--kind`
+ or `--path` for a common name; a `candidates_truncated` diagnostic says when
+ the cap or the search cut it off. `--pick` takes precedence over it.
+- **Exit codes** for the graph commands: `0` results, `2` ambiguous
+ (candidates listed), `3` not found (suggestions and a reason when known),
+ `4` workspace not mapped, `1` any other error. `IX_LEGACY_EXIT_CODES=1` makes
+ every non-zero exit `1` again. With several targets (`ix locate a b c`) the
+ run exits with the worst target's code and each group carries its own.
- **`--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.
@@ -165,6 +179,7 @@ Show methods/functions called by the given symbol (cross-file).
| `--kind` | `<kind>` | — | Filter target entity by kind |
| `--path` | `<path>` | — | Restrict to symbols from files matching this path substring |
| `--pick` | `<n>` | — | Pick Nth candidate from ambiguous results (1-based) |
+| `--all` | — | off | When the symbol is ambiguous, answer for every candidate; rows are tagged with their candidate |
| `--limit` | `<n>` | `50` | Max results to show |
| `--offset` | `<n>` | `0` | Skip the first N results (use the next: hint to page) |
| `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |
@@ -172,15 +187,17 @@ Show methods/functions called by the given symbol (cross-file).
| `--quiet` | — | off | Drop headers, section titles and advisory hints |
| `--fields` | `<list>` | — | Keep only these fields on each row, in this order (e.g. `name,path,lines`) |
-### `ix callers <symbol>`
+### `ix callers <symbols...>`
-Show methods/functions that call the given symbol (cross-file).
+Show methods/functions that call the given symbols (cross-file). Several
+symbols answer in one call, grouped per symbol.
| Flag | Value | Default | Effect |
|---|---|---|---|
| `--kind` | `<kind>` | — | Filter target entity by kind |
| `--path` | `<path>` | — | Restrict to symbols from files matching this path substring |
| `--pick` | `<n>` | — | Pick Nth candidate from ambiguous results (1-based) |
+| `--all` | — | off | When the symbol is ambiguous, answer for every candidate; rows are tagged with their candidate |
| `--limit` | `<n>` | `50` | Max results to show |
| `--offset` | `<n>` | `0` | Skip the first N results (use the next: hint to page) |
| `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |
@@ -451,6 +468,7 @@ System risk analysis — what behavior is at risk if this changes.
| `--kind` | `<kind>` | — | Filter target entity by kind |
| `--path` | `<path>` | — | Restrict to symbols from files matching this path substring |
| `--pick` | `<n>` | — | Pick Nth candidate from ambiguous results (1-based) |
+| `--all` | — | off | When the target is ambiguous, analyse every candidate; each analysis is tagged with its candidate |
| `--depth` | `<n>` | `1` | Expansion depth for callers/importers (default 1, max 3) |
| `--limit` | `<n>` | `10` | Max top-impacted members to show |
| `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |
@@ -533,9 +551,10 @@ List entities by kind with optional path scoping.
| `--quiet` | — | off | Drop headers, section titles and advisory hints |
| `--fields` | `<list>` | — | Keep only these fields on each row, in this order (e.g. `name,path,lines`) |
-### `ix locate <symbol>`
+### `ix locate <symbols...>`
-Resolve a symbol to its position in the codebase and system hierarchy.
+Resolve symbols to their position in the codebase and system hierarchy.
+Several symbols answer in one call, grouped per symbol.
| Flag | Value | Default | Effect |
|---|---|---|---|
@@ -677,6 +696,10 @@ Read raw file content, line ranges, or symbol source code.
| `--root` | `<dir>` | — | Workspace root directory |
| `--all` | — | off | Read the whole file or symbol, past the 400-line default cap |
+An ambiguous file or symbol name exits 0 with an `ambiguous` record and its
+candidates (unlike the graph commands' exit 2); retry with `--pick <n>` or
+`--path`. A miss exits 3.
+
### `ix reset`
Wipe graph data.
diff --git a/skills/ix/references/troubleshooting.md b/skills/ix/references/troubleshooting.md
index 3abeef52..e7a8dec8 100644
--- a/skills/ix/references/troubleshooting.md
+++ b/skills/ix/references/troubleshooting.md
@@ -68,6 +68,13 @@ again.
- `IX_PARSE_WORKERS=N` — the most parse workers `ix map` / `ix ingest` starts
(default 8, never more than the cores less one). Each loads every grammar,
so a small edit starts one; raise it for a faster first map on a large machine.
+- `IX_LEGACY_EXIT_CODES=1` — exit `1` for every failure, as before the graph
+ commands split ambiguous (`2`), not found (`3`) and workspace not mapped (`4`)
+ out of it. For an integration that compares the status against `1`.
+- `IX_MISS_PROBE=0` — skip the bounded `rg -l` a graph command runs when a
+ symbol is not in the graph (at most 5 seconds per command, all misses together), to say whether the name is in a file that was
+ never indexed, in an indexed file as something the parser does not extract,
+ or nowhere at all.
- `IX_PATCH_ACTOR=<actor>` — the `actor` on each graph patch `ix map` / `ix ingest`
sends (default `ix/ingestion`; GitHub ingest uses `ix/github-ingest`). Set it
empty (`IX_PATCH_ACTOR=`) for a backend that authenticates writers and stamps