Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
feat(cli): say why a target missed, and what was probably meant
KageBinarycc6d409306f5
diff --git a/docs/llm-format.md b/docs/llm-format.mdindex 00883270..84c01f5a 100644--- a/docs/llm-format.md+++ b/docs/llm-format.md@@ -60,6 +60,10 @@ which value it ignored, on stderr, when a person is there to read it.format as data lines; the process still exits non-zero. A graph target thatdoes not exist is always `unresolved_target`. `locate` is the remainingexit-status exception tracked in #539.+ 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.A graph read from a directory no registered workspace covers is`workspace_not_mapped`, with `dir=` and a `hint=` naming the command thatmaps it.diff --git a/ix-cli/src/cli/__tests__/ambiguity-and-suggestions.test.ts b/ix-cli/src/cli/__tests__/ambiguity-and-suggestions.test.tsindex 0c6b61e4..8574bdc8 100644--- a/ix-cli/src/cli/__tests__/ambiguity-and-suggestions.test.ts+++ b/ix-cli/src/cli/__tests__/ambiguity-and-suggestions.test.ts@@ -11,6 +11,7 @@ vi.mock("../bootstrap.js", async (orig) => ({resolveWorkspaceId: () => "ws-test",}));+const search = vi.hoisted(() => vi.fn());vi.mock("../../client/api.js", () => ({@@ -170,15 +171,36 @@ describe("a target that resolves to nothing", () => {});it("adds nothing when the name matched nothing at all", async () => {- // A miss here means the search came back empty, so there is nothing to- // suggest — and re-running it without `nameOnly` returns the same empty- // set, which is why nothing tries.+ // Re-running the search without `nameOnly` returns the same empty set, so+ // nothing does that. What is tried is one search each for a leading and a+ // trailing fragment of the name (nearestNames); when those find nothing+ // either, the miss carries no suggestions.search.mockResolvedValue([]);const { stdout } = await run(["overview", "NothingLikeThis", "--format", "json"]);expect(JSON.parse(stdout)).toEqual({error: "unresolved_target",message: 'No entity found matching "NothingLikeThis".',});- expect(search).toHaveBeenCalledTimes(1);+ expect(search).toHaveBeenCalledTimes(3);+ expect(search.mock.calls.slice(1).map((c) => c[0])).toEqual(["NothingL", "LikeThis"]);+ });++ it("offers the nearest names for a typo the substring search cannot match", async () => {+ // `parseBudgetOptoin` matches no name by substring; its leading fragment+ // finds `parseBudgetOption`, one transposition away.+ search.mockImplementation(async (term: string) =>+ term === "parseBudg"+ ? [+ { id: "f-1", name: "parseBudgetOption", kind: "function", provenance: { sourceUri: "src/options.ts" } },+ { id: "c-1", name: "parseBudgetOption", kind: "chunk", provenance: { sourceUri: "src/options.ts" } },+ { id: "f-2", name: "parseBudgetLimitsFromEnvironment", kind: "function", provenance: { sourceUri: "src/env.ts" } },+ ]+ : []);+ const { stdout } = await run(["overview", "parseBudgetOptoin", "--format", "json"]);+ expect(JSON.parse(stdout)).toEqual({+ error: "unresolved_target",+ message: 'No entity found matching "parseBudgetOptoin".',+ suggestions: [{ id: "f-1", name: "parseBudgetOption", kind: "function", path: "src/options.ts" }],+ });});});diff --git a/ix-cli/src/cli/__tests__/diff-unresolved-target.test.ts b/ix-cli/src/cli/__tests__/diff-unresolved-target.test.tsindex 42481fed..8af408d6 100644--- a/ix-cli/src/cli/__tests__/diff-unresolved-target.test.ts+++ b/ix-cli/src/cli/__tests__/diff-unresolved-target.test.ts@@ -20,6 +20,7 @@ vi.mock("../bootstrap.js", async (orig) => ({resolveWorkspaceId: () => "ws-test",}));+vi.mock("../../client/api.js", () => ({IxClient: class {async workspaceSystem() { return { systemId: null }; }@@ -69,9 +70,11 @@ describe("ix diff — unresolved target", () => {it("emits the shared slug and message as json for a file-like target", async () => {const result = await run(["diff", "3", "5", "DefinitelyMissing.ts", "--format", "json"]);+ // Same slug; a file target's message says which kind of miss it is.expect(JSON.parse(result.stdout)).toEqual({error: "unresolved_target",- message: 'No entity found matching "DefinitelyMissing.ts".',+ message: 'No file "DefinitelyMissing.ts" in the graph, and none at that path on disk.',+ reason: "file_not_found",});});diff --git a/ix-cli/src/cli/__tests__/miss-suggestions.test.ts b/ix-cli/src/cli/__tests__/miss-suggestions.test.tsnew file mode 100644index 00000000..03286297--- /dev/null+++ b/ix-cli/src/cli/__tests__/miss-suggestions.test.ts@@ -0,0 +1,140 @@+// Copyright 2026 Ix Infrastructure Inc.++import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import * as fs from "node:fs";+import * as os from "node:os";+import * as path from "node:path";++// This suite is about what a miss says, not about scoping.+vi.mock("../bootstrap.js", async (orig) => ({+ ...(await orig<typeof import("../bootstrap.js")>()),+ resolveWorkspaceId: () => "ws-test",+}));++import { editDistance, nearestNames, resetReadScope, resolveFileOrEntityFull, resolveFileOrReport } from "../resolve.js";+import { resetGraphHealthMemo } from "../graph-health.js";++function node(id: string, name: string, kind: string, sourceUri: string) {+ return { id, name, kind, attrs: {}, provenance: { sourceUri } };+}++/** A client whose search answers from a fixed list by case-insensitive substring, like the backend. */+function graph(nodes: ReturnType<typeof node>[]) {+ const search = vi.fn(async (term: string, opts?: { kind?: string }) =>+ nodes.filter((n) => n.name.toLowerCase().includes(term.toLowerCase()) && (!opts?.kind || n.kind === opts.kind)));+ return { search, workspaceSystem: async () => ({ systemId: null }) } as never as Parameters<typeof resolveFileOrEntityFull>[0] & { search: typeof search };+}++const NODES = [+ node("f-opts", "options.ts", "file", "ix-cli/src/cli/options.ts"),+ node("f-pkg-cli", "package.json", "file", "ix-cli/package.json"),+ node("f-pkg-root", "package.json", "file", "package.json"),+ node("fn-parse", "parseBudgetOption", "function", "ix-cli/src/cli/options.ts"),+ node("ch-parse", "parseBudgetOption", "chunk", "ix-cli/src/cli/options.ts"),+ node("fn-root", "resolveWorkspaceRoot", "function", "ix-cli/src/cli/config.ts"),+];++let dir: string;+let savedCwd: string;++beforeEach(() => {+ dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "ix-miss-")));+ process.env.IX_HOME = path.join(dir, ".ix");+ savedCwd = process.cwd();+ process.chdir(dir);+ resetReadScope();+});++afterEach(() => {+ process.chdir(savedCwd);+ delete process.env.IX_HOME;+ resetReadScope();+ fs.rmSync(dir, { recursive: true, force: true });+});++describe("editDistance", () => {+ it("counts single-character edits, ignoring case", () => {+ expect(editDistance("parseBudgetOptoin", "parseBudgetOption")).toBe(2);+ expect(editDistance("resolveWorkspaceRooot", "resolveWorkspaceRoot")).toBe(1);+ expect(editDistance("ABC", "abc")).toBe(0);+ expect(editDistance("", "abc")).toBe(3);+ });+});++describe("a symbol the substring search cannot match", () => {+ it("is offered the nearest names, definitions only, without chunk copies", async () => {+ const client = graph(NODES);+ const result = await resolveFileOrEntityFull(client, "parseBudgetOptoin", { format: "json" });+ expect(result).toMatchObject({ resolved: false, ambiguous: false });+ expect((result as { suggestions?: unknown[] }).suggestions).toEqual([+ { id: "fn-parse", name: "parseBudgetOption", kind: "function", path: "ix-cli/src/cli/options.ts" },+ ]);+ });++ it("is offered nothing when nothing is close", async () => {+ const near = await nearestNames(graph(NODES), "completelyUnrelatedName", {});+ expect(near).toEqual([]);+ });+});++describe("a file target that misses", () => {+ it("says the file is on disk but not in the graph, and what to run", async () => {+ fs.mkdirSync(path.join(dir, "src"));+ fs.writeFileSync(path.join(dir, "src", "fresh.ts"), "export const x = 1;\n");+ const result = await resolveFileOrEntityFull(graph(NODES), "src/fresh.ts", { format: "json" });+ expect(result).toMatchObject({ resolved: false, reason: "file_not_in_graph" });+ expect((result as { message?: string }).message).toContain("exists on disk but is not in the graph");+ expect((result as { message?: string }).message).toContain("ix map");+ });++ it("says it exists nowhere, and suggests the graph's nearest file", async () => {+ const result = await resolveFileOrEntityFull(graph(NODES), "ix-cli/src/cli/optons.ts", { format: "json" });+ expect(result).toMatchObject({+ resolved: false,+ reason: "file_not_found",+ message: 'No file "ix-cli/src/cli/optons.ts" in the graph, and none at that path on disk.',+ });+ expect((result as { suggestions?: Array<{ name: string }> }).suggestions?.map((s) => s.name)).toEqual(["options.ts"]);+ });++ it("does not answer a path with a same-named file somewhere else", async () => {+ // `docs-site/package.json` resolved to the repo-root `package.json`.+ const result = await resolveFileOrEntityFull(graph(NODES), "docs-site/package.json", { format: "json" });+ expect(result.resolved).toBe(false);+ expect((result as { reason?: string }).reason).toBe("file_not_found");+ });++ it("still resolves a path that names the file, from a subdirectory or with ./", async () => {+ for (const target of ["ix-cli/src/cli/options.ts", "src/cli/options.ts", "./src/cli/options.ts", "options.ts"]) {+ const result = await resolveFileOrEntityFull(graph(NODES), target, { format: "json" });+ expect(result.resolved, target).toBe(true);+ if (result.resolved) expect(result.entity.id).toBe("f-opts");+ }+ });+});++describe("a miss on a graph that is empty", () => {+ it("says the graph is empty rather than that the name does not exist", async () => {+ resetGraphHealthMemo();+ const client = {+ endpoint: "http://backend.test",+ search: vi.fn(async () => []),+ workspaceSystem: async () => ({ systemId: null }),+ currentRevision: async () => 7,+ stats: async () => ({ nodes: { total: 0, byKind: [] }, edges: { total: 0, byPredicate: [] } }),+ };+ const out: string[] = [];+ const log = vi.spyOn(console, "log").mockImplementation((...a) => void out.push(a.join(" ")));+ const saved = process.exitCode;+ try {+ expect(await resolveFileOrReport(client as never, "zzhpAlphaOne", undefined, "json")).toBeNull();+ } finally {+ log.mockRestore();+ process.exitCode = saved;+ }+ expect(JSON.parse(out.join("\n"))).toMatchObject({+ error: "unresolved_target",+ graph: { status: "empty", reason: "no_nodes", fix: "ix map" },+ });+ });+});diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.tsindex 121bbb7a..791c1f3e 100644--- a/ix-cli/src/cli/resolve.ts+++ b/ix-cli/src/cli/resolve.ts@@ -1,5 +1,6 @@// Copyright 2026 Ix Infrastructure Inc.+import * as fs from "node:fs";import * as path from "node:path";import chalk from "chalk";import type { IxClient } from "../client/api.js";@@ -7,7 +8,8 @@ import { stderr } from "./stderr.js";import { applyRoleFilter } from "./role-filter.js";import { detectSystem } from "./system.js";import { requireReadWorkspaceId, resolveWorkspaceId } from "./bootstrap.js";-import { readStitchScope, writeStitchScope } from "./config.js";+import { readStitchScope, resolveWorkspaceRoot, writeStitchScope } from "./config.js";+import { checkGraphHealth, isUnhealthy, type GraphHealth } from "./graph-health.js";import { reportAmbiguousTarget, reportResolutionFailure } from "./ui.js";import { relativePath } from "./format.js";import { isQuiet } from "./output-shape.js";@@ -154,6 +156,8 @@ export interface ResolveOpts {testsOnly?: boolean;searchLimit?: number;format?: string;+ /** Internal: the caller reports the miss itself (a file target's miss). */+ silentMiss?: boolean;}export interface Suggestion {@@ -166,7 +170,21 @@ export interface Suggestion {export type ResolveResult =| { resolved: true; entity: ResolvedEntity; hiddenTestCount?: number }| { resolved: false; ambiguous: true; result: AmbiguousResult; hiddenTestCount?: number }- | { resolved: false; ambiguous: false; hiddenTestCount?: number; suggestions?: Suggestion[] };+ | {+ resolved: false;+ ambiguous: false;+ hiddenTestCount?: number;+ suggestions?: Suggestion[];+ /**+ * Why it missed, when that is more than "no such name": a file target+ * that is on disk but not in the graph (`file_not_in_graph`), or on+ * neither (`file_not_found`). The message then replaces the generic one.+ */+ reason?: string;+ message?: string;+ /** Set by the reporter's caller when the graph itself is empty or degraded. */+ graph?: GraphHealth;+ };// ── Structural kind sets ──────────────────────────────────────────────────@@ -187,7 +205,7 @@ const STRUCTURAL_KINDS = new Set([*/function missProse(opts: ResolveOpts | undefined, message: string): void {const format = opts?.format;- if (format === "json" || format === "llm") return;+ if (opts?.silentMiss || format === "json" || format === "llm") return;stderr(message);}@@ -398,11 +416,14 @@ export async function resolveEntityFull(}if (nodes.length === 0) {- // Nothing to suggest: the search matched no name, and re-running it without- // `nameOnly` returns the same empty set (measured against a 1.4M-node graph- // on three terms), so a second call would only cost a round trip.+ // The backend matches names by substring, so a typo (`parseBudgetOptoin`)+ // matches nothing -- and re-running without `nameOnly` returns the same+ // empty set (measured against a 1.4M-node graph on three terms). What does+ // find it is a fragment of the name: one request each for a leading and a+ // trailing fragment, ranked by edit distance. Only on this miss path.missProse(opts, `No entity found matching "${symbol}".`);- return { resolved: false, ambiguous: false };+ const near = await nearestNames(client, symbol, { kind: kindFilter, workspaceId, systemId });+ return { resolved: false, ambiguous: false, ...(near.length ? { suggestions: near } : {}) };}// Apply role filter before scoring@@ -873,7 +894,98 @@ export async function resolveFileOrEntityFull(// module-level constant is not ranked behind every config entry and heading// that happens to share its name (Ix#679).const allKinds = ["file", "class", "object", "trait", "interface", "module", "method", "function", "constant"];- return resolveEntityFull(client, target, allKinds, opts);+ if (!looksFileLike(target)) return resolveEntityFull(client, target, allKinds, opts);+ // A path is a question about a file. "No entity found" answered it as if it+ // were a symbol, which does not say whether the file exists, was never+ // ingested, or was mistyped -- three different next steps.+ const result = await resolveEntityFull(client, target, allKinds, { ...opts, silentMiss: true });+ if (result.resolved || result.ambiguous) return result;+ return fileMiss(client, target, opts);+}++/**+ * The miss for a file target: on disk but not in the graph, or on neither,+ * with the graph's nearest file names as suggestions.+ */+async function fileMiss(client: IxClient, target: string, opts?: ResolveOpts): Promise<ResolveResult> {+ const candidates = path.isAbsolute(target)+ ? [target]+ : [path.resolve(resolveWorkspaceRoot(), target), path.resolve(process.cwd(), target)];+ const onDisk = candidates.some((p) => { try { return fs.statSync(p).isFile(); } catch { return false; } });+ const message = onDisk+ ? `"${target}" exists on disk but is not in the graph: it has not been ingested yet (run \`ix map\`), ` ++ "or it is ignored or of a type Ix does not parse."+ : `No file "${target}" in the graph, and none at that path on disk.`;+ missProse(opts, message);+ const { workspaceId, systemId } = activeScope();+ const stem = path.basename(target).replace(/\.[^.]+$/, "");+ const near = (await nearestNames(client, stem, { kind: "file", workspaceId, systemId }, (n) => {+ const name = String(n.name ?? "");+ return name.replace(/\.[^.]+$/, "");+ })).filter((sug) => !opts?.path || (sug.path ?? "").toLowerCase().includes(opts.path.toLowerCase()));+ return {+ resolved: false,+ ambiguous: false,+ reason: onDisk ? "file_not_in_graph" : "file_not_found",+ message,+ ...(near.length ? { suggestions: near } : {}),+ };+}++/** Levenshtein distance, case-insensitive. Small inputs only (names). */+export function editDistance(a: string, b: string): number {+ const x = a.toLowerCase();+ const y = b.toLowerCase();+ if (x === y) return 0;+ let prev = Array.from({ length: y.length + 1 }, (_, i) => i);+ for (let i = 1; i <= x.length; i++) {+ const cur = [i];+ for (let j = 1; j <= y.length; j++) {+ cur[j] = Math.min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (x[i - 1] === y[j - 1] ? 0 : 1));+ }+ prev = cur;+ }+ return prev[y.length];+}++/**+ * The graph names closest to `symbol`, for a miss. Two name-only searches, for+ * a leading and a trailing fragment (a typo sits in one half or the other),+ * then ranked by edit distance and kept only when close enough to be a+ * plausible intent. Best-effort: any failure is "no suggestions".+ */+export async function nearestNames(+ client: Pick<IxClient, "search">,+ symbol: string,+ scope: { kind?: string; workspaceId?: string; systemId?: string },+ nameOf: (node: any) => string = (n) => String(n.name ?? n.attrs?.name ?? ""),+ limit = 3,+): Promise<Suggestion[]> {+ if (symbol.length < 4) return [];+ const width = Math.max(3, Math.ceil(symbol.length * 0.5));+ const fragments = [...new Set([symbol.slice(0, width), symbol.slice(-width)])];+ try {+ const found = (await Promise.all(fragments.map((term) => client.search(term, {+ limit: 30, kind: scope.kind, nameOnly: true, workspaceId: scope.workspaceId, systemId: scope.systemId,+ })))).flat();+ const maxDistance = Math.max(2, Math.floor(symbol.length / 3));+ const ranked = found+ .filter((n: any) => n?.id && n.kind !== "chunk")+ .map((n: any) => ({ n, d: editDistance(nameOf(n), symbol) }))+ .filter(({ d }) => d <= maxDistance)+ .sort((a, b) => a.d - b.d || Number(!STRUCTURAL_KINDS.has(a.n.kind)) - Number(!STRUCTURAL_KINDS.has(b.n.kind)));+ // One row per name and file: an import of the name in the same file adds nothing.+ const seen = new Set<string>();+ const unique = ranked.map(({ n }) => n).filter((n: any) => {+ const key = `${n.name}|${n.provenance?.sourceUri ?? n.provenance?.source_uri ?? ""}`;+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+ return toSuggestions(unique, limit);+ } catch {+ return [];+ }}export async function resolveFileOrEntity(@@ -898,6 +1010,15 @@ export async function resolveFileOrReport(// reach stdout.const result = await resolveFileOrEntityFull(client, target, { ...opts, format });if (result.resolved) 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;+ }+ }reportResolutionFailure(target, result, format, opts);return null;}@@ -927,8 +1048,9 @@ async function tryFileGraphMatch(systemId,});- // Filter to actual matches- const targetLower = normalizeForPathMatch(target);+ // Filter to actual matches. Leading `./` and `../` say where the caller is+ // standing, not where the file is, so they are not part of the suffix match.+ const targetLower = normalizeForPathMatch(target).replace(/^(\.\.?\/)+/, "");const basenameLower = basename.toLowerCase();const basenameNoExt = basename.replace(/\.[^.]+$/, "").toLowerCase();const normalizedPathHint = normalizeForPathMatch(effectivePath);@@ -959,6 +1081,11 @@ async function tryFileGraphMatch(}if (matches.length === 0) return null;+ // A path names one file. When no node sits at it, a same-named file+ // elsewhere is a different file: `docs-site/package.json` resolved to the+ // repo-root `package.json` and was answered about with full confidence. The+ // miss is reported instead, with that file among its suggestions.+ if (targetHasPath && !effectivePath && !matches.some((m) => m.quality === 0)) return null;// Sort by quality then by URI length ascending (shorter = closer to root = more prominent)matches.sort((a, b) => {diff --git a/ix-cli/src/cli/ui.ts b/ix-cli/src/cli/ui.tsindex 95eef269..f962ed87 100644--- a/ix-cli/src/cli/ui.ts+++ b/ix-cli/src/cli/ui.ts@@ -13,6 +13,7 @@ import { llmError, llmLine } from "./llm.js";import { printJson, relativePath } from "./format.js";import { isQuiet } from "./output-shape.js";import type { AmbiguousResult, ResolveResult, Suggestion } from "./resolve.js";+import { graphHealthJson, graphHealthLlmFields, graphHealthProse, type GraphHealth } from "./graph-health.js";// ── Brand palette ─────────────────────────────────────────────────────────────//@@ -175,21 +176,36 @@ export function reportUnresolvedTarget(target: string | string[],format?: string,suggestions?: Suggestion[],+ detail?: { reason?: string; message?: string; graph?: GraphHealth },): void {- const message = unresolvedTargetMessage(target);+ // 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.+ const message = detail?.message ?? unresolvedTargetMessage(target);const near = suggestions ?? [];if (format === "json") {printJson({...unresolvedTargetRecord(target),+ message,+ ...(detail?.reason ? { reason: detail.reason } : {}),...(near.length ? { suggestions: near } : {}),+ ...(detail?.graph ? { graph: graphHealthJson(detail.graph) } : {}),});} else if (format === "llm") {- const lines = [llmError("unresolved_target", message), ...candidateLines(near, "suggestion")];+ const lines = [+ llmError("unresolved_target", message, detail?.reason ? [["reason", detail.reason]] : []),+ ...(detail?.graph ? [llmLine("graph", graphHealthLlmFields(detail.graph))] : []),+ ...candidateLines(near, "suggestion"),+ ];if (near.length) {lines.push(llmLine("hint", [["text", "Re-run with one of these names, or narrow with --path."]]));}console.log(lines.join("\n"));- } else if (near.length) {+ } else {+ if (detail?.graph) console.error(chalk.yellow(graphHealthProse(detail.graph)));+ if (!near.length) {+ process.exitCode = 1;+ return;+ }// The resolver already wrote the miss itself for a person; this adds the// part that makes it actionable.console.error(chalk.dim("Did you mean:"));@@ -274,6 +290,6 @@ export function reportResolutionFailure(opts?: { kind?: string; path?: string },): void {if (result.ambiguous) reportAmbiguousTarget(target, result.result, format, opts);- else reportUnresolvedTarget(target, format, result.suggestions);+ else reportUnresolvedTarget(target, format, result.suggestions, { reason: result.reason, message: result.message, graph: result.graph });process.exitCode = 1;}