Skip to content

armgit / Ix

Public Imported from GitHub
0

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

fix(trace): honor depth and node budgets in path searches (#634)

Hiro-Chiba40831854d8ad
diff --git a/ix-cli/src/cli/__tests__/trace-path-budgets.test.ts b/ix-cli/src/cli/__tests__/trace-path-budgets.test.ts
new file mode 100644
index 00000000..f0d08d0d
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/trace-path-budgets.test.ts
@@ -0,0 +1,77 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Command } from "commander";
+import { registerTraceCommand } from "../commands/trace.js";
+
+const expand = vi.hoisted(() => vi.fn());
+vi.mock("../../client/api.js", () => ({
+ IxClient: class { async expand(...args: unknown[]) { return expand(...args); } },
+}));
+vi.mock("../resolve.js", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../resolve.js")>(),
+ resolveFileOrEntityFull: async (_client: unknown, name: string) => ({
+ resolved: true, entity: { id: name, name, kind: "function" },
+ }),
+}));
+
+async function run(args: string[], format = "json", to = "C") {
+ const program = new Command().name("ix").exitOverride();
+ registerTraceCommand(program);
+ const output: string[] = [];
+ vi.spyOn(console, "log").mockImplementation((...parts) => { output.push(parts.join(" ")); });
+ await program.parseAsync(["trace", "A", "--to", to, "--kind", "calls", ...args, "--format", format], { from: "user" });
+ return output.join("\n");
+}
+
+describe("trace --to search budgets", () => {
+ beforeEach(() => {
+ expand.mockReset().mockImplementation(async (id: string, opts: { direction: string }) => {
+ const adjacent: Record<string, string[]> = opts.direction === "out"
+ ? { A: ["B"], B: ["C"] } : { B: ["A"], C: ["B"] };
+ return { nodes: (adjacent[id] ?? []).map(name => ({ id: name, name, kind: "function" })), edges: [] };
+ });
+ });
+ afterEach(() => vi.restoreAllMocks());
+
+ it("does not return a two-edge path at depth one", async () => {
+ const output = JSON.parse(await run(["--depth", "1"]));
+ expect(output.path).toBeNull();
+ expect(expand.mock.calls.map(([id]) => id)).toEqual(["A", "A"]);
+ });
+
+ it("finds a path exactly at the depth boundary", async () => {
+ const output = JSON.parse(await run(["--depth", "2"]));
+ expect(output.path.map((n: { name: string }) => n.name)).toEqual(["A", "B", "C"]);
+ });
+
+ it("does not expand the source at depth zero", async () => {
+ expect(JSON.parse(await run(["--depth", "0"])).path).toBeNull();
+ expect(expand).not.toHaveBeenCalled();
+ });
+
+ it("enforces the node cap before visiting the target", async () => {
+ expect(JSON.parse(await run(["--cap", "2"])).path).toBeNull();
+ });
+
+ it("finds the route when the cap includes all three nodes", async () => {
+ expect(JSON.parse(await run(["--cap", "3"])).path).toHaveLength(3);
+ });
+
+ it("does no graph expansion at cap zero", async () => {
+ expect(JSON.parse(await run(["--cap", "0"])).path).toBeNull();
+ expect(expand).not.toHaveBeenCalled();
+ });
+
+ it("returns a zero-edge self path without expansion", async () => {
+ expect(JSON.parse(await run(["--depth", "0", "--cap", "1"], "json", "A")).path).toHaveLength(1);
+ expect(expand).not.toHaveBeenCalled();
+ });
+
+ it.each(["json", "llm", "text"])("qualifies a bounded miss in %s output", async (format) => {
+ const output = await run(["--depth", "1", "--cap", "2"], format);
+ expect(output).toContain("within the requested search limits");
+ });
+
+ it("preserves an unrestricted successful route", async () => {
+ expect(JSON.parse(await run([])).path).toHaveLength(3);
+ });
+});
diff --git a/ix-cli/src/cli/commands/trace.ts b/ix-cli/src/cli/commands/trace.ts
index 1ea18bb0..b51c92d4 100644
--- a/ix-cli/src/cli/commands/trace.ts
+++ b/ix-cli/src/cli/commands/trace.ts
@@ -229,7 +229,10 @@ export async function findPath(
toId: string,
predicates: string[],
maxDepth: number = 10,
+ maxNodes: number = Infinity,
): Promise<PathNode[] | null> {
+ if (maxNodes < 1) return null;
+ if (fromId === toId) return [{ id: fromId, name: "", kind: "" }];
const nodeMap = new Map<string, { name: string; kind: string }>();
const queue: Array<{ id: string; path: string[] }> = [{ id: fromId, path: [fromId] }];
@@ -238,7 +241,7 @@ export async function findPath(
while (queue.length > 0) {
const entry = queue.shift()!;
const { id, path } = entry;
- if (path.length >= maxDepth) continue;
+ if (path.length - 1 >= maxDepth) continue;
const [outResult, inResult] = await Promise.all([
client.expand(id, { direction: "out", predicates, hops: 1 }),
@@ -246,6 +249,9 @@ export async function findPath(
]);
for (const n of [...outResult.nodes, ...inResult.nodes]) {
+ if (visited.has(n.id)) continue;
+ if (visited.size >= maxNodes) return null;
+ visited.add(n.id);
const name = n.name || n.attrs?.name || n.id.slice(0, 8);
if (!nodeMap.has(n.id)) {
nodeMap.set(n.id, { name, kind: n.kind ?? "unknown" });
@@ -260,8 +266,6 @@ export async function findPath(
});
}
- if (visited.has(n.id)) continue;
- visited.add(n.id);
queue.push({ id: n.id, path: [...path, n.id] });
}
}
@@ -355,13 +359,14 @@ const finiteDepth = (d: number): LlmValue => (Number.isFinite(d) ? d : undefined
export function renderTracePathLlm(
from: { name: string; kind: string }, to: { name: string; kind: string },
relKind: string, pathNodes: PathNode[],
+ noPathMessage?: string,
): string[] {
const lines = [llmLine("trace", [
["mode", "path"], ["from", from.name], ["to", to.name], ["kind", relKind],
["length", pathNodes.length > 0 ? pathNodes.length : undefined],
])];
if (pathNodes.length === 0) {
- lines.push(llmLine("diagnostic", [["code", "no_path"], ["message", `No route found from ${from.name} to ${to.name}.`]]));
+ lines.push(llmLine("diagnostic", [["code", "no_path"], ["message", noPathMessage ?? `No route found from ${from.name} to ${to.name}.`]]));
return lines;
}
for (const n of pathNodes) lines.push(llmLine("step", [["name", n.name], ["kind", n.kind]]));
@@ -413,8 +418,8 @@ export function registerTraceCommand(program: Command): void {
.option("--upstream", "Show who calls/imports this (same as depends)")
.option("--downstream", "Show what this calls/imports (outward flow)")
.option("--kind <kind>", "Relationship kind: calls|imports|depends|contains")
- .option("--depth <n>", "Cap traversal depth")
- .option("--cap <n>", "Cap number of nodes visited, per direction")
+ .option("--depth <n>", "Cap traversal depth in edges (also applies to --to)")
+ .option("--cap <n>", "Cap nodes visited per direction, or across the --to search (including the source)")
.option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)
.option("--path <path>", "Restrict to symbols from files matching this path substring")
.option("--format <fmt>", "Output format (text|json|llm)", "text")
@@ -485,7 +490,9 @@ export function registerTraceCommand(program: Command): void {
const relKind = opts.kind ?? "mixed";
const predicates = kindToPredicates(opts.kind);
- const rawPath = await findPath(client, fromTarget.id, toTarget.id, predicates, maxDepth + 7);
+ const rawPath = await findPath(client, fromTarget.id, toTarget.id, predicates, maxDepth, maxNodes);
+ const bounded = Number.isFinite(maxDepth) || Number.isFinite(maxNodes);
+ const noPathMessage = `No route found from ${fromTarget.name} to ${toTarget.name}${bounded ? " within the requested search limits" : ""}.`;
// Fill in the from-node name (was left blank above)
const pathNodes: PathNode[] = rawPath
@@ -511,7 +518,7 @@ export function registerTraceCommand(program: Command): void {
output.diagnostics = [
{
code: "no_path",
- message: `No route found from ${fromTarget.name} to ${toTarget.name}.`,
+ message: noPathMessage,
},
];
}
@@ -521,7 +528,7 @@ export function registerTraceCommand(program: Command): void {
// ── llm output ─────────────────────────────────────────
if (opts.format === "llm") {
- for (const line of renderTracePathLlm(fromTarget, toTarget, relKind, pathNodes)) console.log(line);
+ for (const line of renderTracePathLlm(fromTarget, toTarget, relKind, pathNodes, noPathMessage)) console.log(line);
return;
}
@@ -533,7 +540,7 @@ export function registerTraceCommand(program: Command): void {
renderKeyValue("Kind", cap(relKind));
if (pathNodes.length === 0) {
- console.log(`\nNo route found from ${chalk.bold(fromTarget.name)} to ${chalk.bold(toTarget.name)}.`);
+ console.log(`\n${noPathMessage}`);
return;
}
diff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.md
index 85c6a882..6873577e 100644
--- a/skills/ix/references/flags.md
+++ b/skills/ix/references/flags.md
@@ -589,8 +589,8 @@ Follow how it connects.
| `--upstream` | — | off | Show who calls/imports this (same as depends) |
| `--downstream` | — | off | Show what this calls/imports (outward flow) |
| `--kind` | `<kind>` | — | Relationship kind: calls\|imports\|depends\|contains |
-| `--depth` | `<n>` | — | Cap traversal depth |
-| `--cap` | `<n>` | — | Cap number of nodes visited, per direction |
+| `--depth` | `<n>` | — | Cap traversal depth in edges (also applies to `--to`) |
+| `--cap` | `<n>` | — | Cap nodes visited per direction, or across the `--to` search (including the source) |
| `--pick` | `<n>` | — | Pick Nth candidate from ambiguous results (1-based) |
| `--path` | `<path>` | — | Restrict to symbols from files matching this path substring |
| `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |