Skip to content

armgit / Ix

Public Imported from GitHub
0

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

feat: polish ix locate with relative paths, humanized labels, and clean ambiguity

Tanner Kocher2f1545febbcb
diff --git a/ix-cli/src/cli/__tests__/locate-output.test.ts b/ix-cli/src/cli/__tests__/locate-output.test.ts
index 8deafec7..d817ec94 100644
--- a/ix-cli/src/cli/__tests__/locate-output.test.ts
+++ b/ix-cli/src/cli/__tests__/locate-output.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect } from "vitest";
+import { humanizeLabel } from "../impact/risk-semantics.js";
/**
* Tests for ix locate output structure.
@@ -7,6 +8,8 @@ import { describe, it, expect } from "vitest";
* file, line range, containment, system path — no structural/risk/explanatory content.
*/
+// ── Helpers ─────────────────────────────────────────────────────────────────
+
// Simulates the JSON output shape from locate for a symbol target
function makeSymbolOutput() {
return {
@@ -25,6 +28,7 @@ function makeSymbolOutput() {
{ name: "api.ts", kind: "file" },
{ name: "IxClient", kind: "class" },
],
+ hasMapData: true,
diagnostics: [],
};
}
@@ -44,10 +48,13 @@ function makeFileOutput() {
{ name: "Model / Db", kind: "subsystem" },
{ name: "Node.scala", kind: "file" },
],
+ hasMapData: true,
diagnostics: [],
};
}
+// ── Symbol target ───────────────────────────────────────────────────────────
+
describe("locate: symbol target output", () => {
it("contains file path", () => {
const output = makeSymbolOutput();
@@ -70,8 +77,16 @@ describe("locate: symbol target output", () => {
expect(output.container).toBeDefined();
expect(output.container!.name).toBe("api.ts");
});
+
+ it("system path ends with the resolved symbol name", () => {
+ const output = makeSymbolOutput();
+ const last = output.systemPath[output.systemPath.length - 1];
+ expect(last.name).toBe("IxClient");
+ });
});
+// ── File target ─────────────────────────────────────────────────────────────
+
describe("locate: file target output", () => {
it("contains file path", () => {
const output = makeFileOutput();
@@ -92,8 +107,59 @@ describe("locate: file target output", () => {
const output = makeFileOutput();
expect((output as any).lineRange).toBeUndefined();
});
+
+ it("system path does not append an extra symbol segment for file targets", () => {
+ const output = makeFileOutput();
+ const last = output.systemPath[output.systemPath.length - 1];
+ // Last element should be the file itself, not a symbol
+ expect(last.kind).toBe("file");
+ });
});
+// ── Repo-relative paths ─────────────────────────────────────────────────────
+
+describe("locate: repo-relative path rendering", () => {
+ it("file path is relative, not absolute", () => {
+ const symbol = makeSymbolOutput();
+ expect(symbol.resolvedTarget.path).not.toMatch(/^\//);
+ expect(symbol.resolvedTarget.path).toBe("src/client/api.ts");
+ });
+
+ it("file target path is relative", () => {
+ const file = makeFileOutput();
+ expect(file.resolvedTarget.path).not.toMatch(/^\//);
+ });
+});
+
+// ── Humanized system path labels ────────────────────────────────────────────
+
+describe("locate: humanized system path labels", () => {
+ // The humanizeBreadcrumb function strips " layer" suffix from humanizeLabel
+ // and applies it only to region kinds. Non-region nodes (file, class) keep raw names.
+
+ it("region nodes are humanized (strip parentheticals, normalize abbreviations)", () => {
+ // Cli / Client (subsystem) → "CLI client" (not "Cli / Client")
+ const humanized = humanizeLabel("Cli / Client").replace(/ layer$/, "");
+ expect(humanized).toBe("CLI client");
+ });
+
+ it("raw suffixes like (2f) are stripped", () => {
+ const humanized = humanizeLabel("Model (2f)").replace(/ layer$/, "");
+ expect(humanized).not.toContain("(2f)");
+ });
+
+ it("file and class nodes are not humanized", () => {
+ // File and class nodes should keep their original names
+ const output = makeSymbolOutput();
+ const fileNode = output.systemPath.find((n) => n.kind === "file");
+ expect(fileNode?.name).toBe("api.ts");
+ const classNode = output.systemPath.find((n) => n.kind === "class");
+ expect(classNode?.name).toBe("IxClient");
+ });
+});
+
+// ── No-overlap regression ───────────────────────────────────────────────────
+
describe("locate: no-overlap regression", () => {
const symbolOutput = makeSymbolOutput();
const fileOutput = makeFileOutput();
@@ -129,8 +195,10 @@ describe("locate: no-overlap regression", () => {
});
});
+// ── Ambiguity handling ──────────────────────────────────────────────────────
+
describe("locate: ambiguity handling", () => {
- it("null resolution produces diagnostics", () => {
+ it("null resolution with no ambiguity produces diagnostics", () => {
const output = {
resolvedTarget: null,
resolutionMode: "none",
@@ -141,7 +209,30 @@ describe("locate: ambiguity handling", () => {
expect(output.diagnostics.length).toBeGreaterThan(0);
});
- it("resolution mode is preserved", () => {
+ it("ambiguous resolution produces candidate list without 'not found' diagnostics", () => {
+ // Simulates the JSON output for ambiguous resolution
+ const ambiguousOutput = {
+ resolvedTarget: null,
+ resolutionMode: "ambiguous",
+ candidates: [
+ { id: "a1", name: "NodeKind", kind: "trait", path: "src/model/Node.scala" },
+ { id: "a2", name: "NodeKind", kind: "class", path: "src/other/Node.scala" },
+ ],
+ systemPath: null,
+ diagnostics: [{ code: "ambiguous_resolution", message: "Use --pick <n> or --path to disambiguate." }],
+ };
+
+ expect(ambiguousOutput.resolutionMode).toBe("ambiguous");
+ expect(ambiguousOutput.candidates.length).toBeGreaterThan(1);
+ // No "No graph entity found" diagnostic
+ const diagMessages = ambiguousOutput.diagnostics.map((d: any) =>
+ typeof d === "string" ? d : d.message
+ );
+ expect(diagMessages).not.toContain("No graph entity found.");
+ expect(diagMessages).not.toContain("No matches found.");
+ });
+
+ it("resolution mode is preserved for exact matches", () => {
const output = makeSymbolOutput();
expect(output.resolutionMode).toBe("exact");
});
diff --git a/ix-cli/src/cli/commands/locate.ts b/ix-cli/src/cli/commands/locate.ts
index dc83e250..36b71e54 100644
--- a/ix-cli/src/cli/commands/locate.ts
+++ b/ix-cli/src/cli/commands/locate.ts
@@ -1,13 +1,22 @@
+import * as path from "node:path";
import type { Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
-import { resolveFileOrEntity, printResolved } from "../resolve.js";
+import {
+ resolveFileOrEntity, resolveEntityFull, printResolved, printAmbiguous,
+ looksFileLike, isRawId, type ResolvedEntity,
+} from "../resolve.js";
import { isFileStale } from "../stale.js";
import { stderr } from "../stderr.js";
import { getSystemPath, hasMapData } from "../hierarchy.js";
+import { humanizeLabel } from "../impact/risk-semantics.js";
const CONTAINER_KINDS = new Set(["class", "module", "file", "trait", "object", "interface"]);
+const FILE_KINDS = new Set(["file"]);
+
+// Region kinds whose names should be humanized in system path
+const REGION_KINDS = new Set(["system", "subsystem", "module", "region"]);
interface LocateOutput {
resolvedTarget: { id: string; kind: string; name: string; path?: string } | null;
@@ -36,11 +45,18 @@ export function registerLocateCommand(program: Command): void {
.action(async (symbol: string, opts: { kind?: string; path?: string; pick?: string; format: string }) => {
const client = new IxClient(getEndpoint());
const diagnostics: string[] = [];
+ const isJson = opts.format === "json";
const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
- const target = await resolveFileOrEntity(client, symbol, resolveOpts);
+
+ // Resolution with ambiguity detection
+ const { target, ambiguous } = await resolveWithAmbiguity(client, symbol, resolveOpts, isJson);
if (!target) {
+ if (ambiguous) {
+ // Ambiguity already printed — stop cleanly
+ return;
+ }
const output: LocateOutput = {
resolvedTarget: null,
resolutionMode: "none",
@@ -51,9 +67,10 @@ export function registerLocateCommand(program: Command): void {
return;
}
- if (opts.format !== "json") printResolved(target);
+ if (!isJson) printResolved(target);
const isContainer = CONTAINER_KINDS.has(target.kind);
+ const isFile = FILE_KINDS.has(target.kind);
// Parallel fetch: system path, parent container (for non-containers), entity details
const [systemPath, containsResult, details] = await Promise.all([
@@ -92,23 +109,34 @@ export function registerLocateCommand(program: Command): void {
}
// Diagnostic for missing map data
- if (!hasMapData(systemPath)) {
+ const hasMap = hasMapData(systemPath);
+ if (!hasMap) {
diagnostics.push("No system map. Run `ix map` to see hierarchy.");
}
- const hasMap = hasMapData(systemPath);
+ // 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 }];
+ }
+ }
+
+ // Make path repo-relative
+ const displayPath = nodePath ? toRepoRelative(nodePath) : undefined;
const output: LocateOutput = {
resolvedTarget: {
id: target.id,
kind: target.kind,
name: target.name,
- path: nodePath,
+ path: displayPath,
},
resolutionMode: target.resolutionMode,
lineRange,
container,
- systemPath: systemPath.map((n) => ({ name: n.name, kind: n.kind })),
+ systemPath: systemPathMapped,
hasMapData: hasMap,
diagnostics,
};
@@ -120,6 +148,70 @@ export function registerLocateCommand(program: Command): void {
});
}
+// ── Ambiguity-aware resolution ──────────────────────────────────────────────
+
+async function resolveWithAmbiguity(
+ client: IxClient,
+ symbol: string,
+ opts: { kind?: string; path?: string; pick?: number },
+ isJson: boolean,
+): Promise<{ target: ResolvedEntity | null; ambiguous: boolean }> {
+ // For raw IDs and file-like targets, delegate to resolveFileOrEntity (no ambiguity)
+ if (isRawId(symbol) || looksFileLike(symbol)) {
+ const target = await resolveFileOrEntity(client, symbol, opts);
+ return { target, ambiguous: false };
+ }
+
+ // Symbol resolution — use full result to detect ambiguity
+ const allKinds = ["file", "class", "object", "trait", "interface", "module", "function", "method"];
+ const result = await resolveEntityFull(client, symbol, allKinds, opts);
+
+ if (result.resolved) {
+ return { target: result.entity, ambiguous: false };
+ }
+
+ if (result.ambiguous) {
+ if (isJson) {
+ console.log(JSON.stringify({
+ resolvedTarget: null,
+ resolutionMode: "ambiguous",
+ candidates: result.result.candidates,
+ systemPath: null,
+ diagnostics: result.result.diagnostics ?? [],
+ }, null, 2));
+ } else {
+ printAmbiguous(symbol, result.result, opts);
+ }
+ return { target: null, ambiguous: true };
+ }
+
+ return { target: null, ambiguous: false };
+}
+
+// ── Repo-relative path ──────────────────────────────────────────────────────
+
+function toRepoRelative(filePath: string): string {
+ if (!path.isAbsolute(filePath)) return filePath;
+ try {
+ const cwd = process.cwd();
+ const rel = path.relative(cwd, filePath);
+ // Only use relative if it doesn't escape the repo (no leading ../)
+ if (!rel.startsWith("..") && !path.isAbsolute(rel)) return rel;
+ } catch {}
+ return filePath;
+}
+
+// ── Humanized system path breadcrumb ────────────────────────────────────────
+
+function humanizeBreadcrumb(nodes: Array<{ name: string; kind: string }>): string {
+ return nodes.map((n) => {
+ if (REGION_KINDS.has(n.kind)) return humanizeLabel(n.name).replace(/ layer$/, "");
+ return n.name;
+ }).join(" → ");
+}
+
+// ── Output ──────────────────────────────────────────────────────────────────
+
function outputLocate(output: LocateOutput, symbol: string, format: string): void {
if (format === "json") {
console.log(JSON.stringify(output, null, 2));
@@ -153,9 +245,8 @@ function outputLocate(output: LocateOutput, symbol: string, format: string): voi
// System path section
if (output.systemPath && output.systemPath.length > 1 && output.hasMapData) {
- const breadcrumb = output.systemPath.map((n) => n.name).join(" → ");
console.log(chalk.bold("\nSystem path"));
- console.log(` ${breadcrumb}`);
+ console.log(` ${humanizeBreadcrumb(output.systemPath)}`);
}
// Diagnostics
diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.ts
index b71cd46e..e818953f 100644
--- a/ix-cli/src/cli/resolve.ts
+++ b/ix-cli/src/cli/resolve.ts
@@ -335,7 +335,7 @@ function buildAmbiguous(nodes: any[], scores?: number[]): AmbiguousResult {
};
}
-function printAmbiguous(symbol: string, result: AmbiguousResult, opts?: { kind?: string; path?: string }): void {
+export function printAmbiguous(symbol: string, result: AmbiguousResult, opts?: { kind?: string; path?: string }): void {
stderr(`Ambiguous symbol "${symbol}":`);
for (let i = 0; i < result.candidates.length; i++) {
const c = result.candidates[i];