Skip to content

armgit / Ix

Public Imported from GitHub
0

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

feat(trace): report when a traversal stopped early, not just that nothing was found

Alot1z9558f4e0e601
diff --git a/ix-cli/src/cli/__tests__/trace-completeness.test.ts b/ix-cli/src/cli/__tests__/trace-completeness.test.ts
new file mode 100644
index 00000000..bda7fdf6
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/trace-completeness.test.ts
@@ -0,0 +1,157 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { describe, expect, it } from 'vitest';
+
+import { renderTracePathLlm, renderTraceSingleLlm, renderTraceBothLlm, searchPath } from '../commands/trace.js';
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+const node = (): any => ({ id: 'n1aaaaaa', name: 'bar', kind: 'method', resolved: true, children: [] });
+
+const n = (id: string) => ({ id, name: id.toUpperCase(), kind: 'file' });
+
+/** Mock IxClient.expand that returns neighbours keyed by (id, direction). */
+function makeClient(edges: Record<string, Record<string, Array<{ id: string; name: string; kind: string }>>>) {
+ return {
+ async expand(id: string, opts?: { direction?: string }) {
+ const direction = opts?.direction ?? 'out';
+ return { nodes: edges[id]?.[direction] ?? [], edges: [] };
+ },
+ };
+}
+
+const CAP_HINT = 'Node cap of 8 reached; nodes were dropped. Raise --cap, or start from a narrower target.';
+
+// ---------------------------------------------------------------------------
+// renderTraceSingleLlm — completeness flags surface instead of being discarded
+// ---------------------------------------------------------------------------
+
+describe('renderTraceSingleLlm completeness', () => {
+ it('reports depth_limited with a raise-the-bound hint instead of hardcoding false', () => {
+ const lines = renderTraceSingleLlm(
+ { id: 'root1234', name: 'foo', kind: 'function' }, 'mixed', 'downstream', 3,
+ [node()], false, 1, 1, Infinity, true,
+ );
+ expect(lines[0]).toContain('depth_limited=true');
+ expect(lines[0]).not.toContain('truncated=true');
+ expect(lines[1]).toBe(
+ 'diagnostic code=depth_limited message="Stopped descending at depth 3; there may be more below. Raise --depth to look further."',
+ );
+ });
+
+ it('prefers the truncated code when both bounds were hit', () => {
+ const lines = renderTraceSingleLlm(
+ { id: 'root1234', name: 'foo', kind: 'function' }, 'mixed', 'downstream', 3,
+ [node()], true, 9, 3, 8, true,
+ );
+ expect(lines[0]).toContain('truncated=true');
+ expect(lines[0]).toContain('depth_limited=true');
+ expect(lines[1]).toBe(`diagnostic code=truncated message="${CAP_HINT}"`);
+ });
+
+ it('emits neither flag nor diagnostic for an unbounded clean traversal', () => {
+ const lines = renderTraceSingleLlm(
+ { id: 'root1234', name: 'foo', kind: 'function' }, 'mixed', 'upstream', Infinity,
+ [node()], false, 1, 1, Infinity,
+ );
+ expect(lines[0]).not.toContain('truncated');
+ expect(lines[0]).not.toContain('depth_limited');
+ expect(lines[1]).toContain('node ');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// renderTraceBothLlm — per-direction truncation must not vanish
+// ---------------------------------------------------------------------------
+
+describe('renderTraceBothLlm completeness', () => {
+ it('surfaces truncated=true plus a hint when one direction hit the node cap', () => {
+ const lines = renderTraceBothLlm(
+ { id: 'root1234', name: 'foo', kind: 'function' }, 'mixed', Infinity,
+ { tree: [node()], nodesVisited: 9, maxDepthReached: 2, truncated: true },
+ { tree: [], nodesVisited: 0, maxDepthReached: 0 },
+ 8,
+ );
+ expect(lines[0]).toContain('truncated=true');
+ expect(lines[1]).toBe(`diagnostic code=truncated message="${CAP_HINT}"`);
+ });
+
+ it('emits no completeness fields for clean traversals', () => {
+ const lines = renderTraceBothLlm(
+ { id: 'root1234', name: 'foo', kind: 'function' }, 'mixed', Infinity,
+ { tree: [node()], nodesVisited: 1, maxDepthReached: 1 },
+ { tree: [], nodesVisited: 0, maxDepthReached: 0 },
+ );
+ expect(lines[0]).not.toContain('truncated');
+ expect(lines[1]).toBe('up name=bar kind=method id=n1aaaaaa parent=root1234');
+ });
+});
+
+// ---------------------------------------------------------------------------
+// renderTracePathLlm — cut traversal distinguishable from genuine absence
+// ---------------------------------------------------------------------------
+
+describe('renderTracePathLlm cut visibility', () => {
+ it('adds a search_cut diagnostic after no_path when the search was budget-cut', () => {
+ const lines = renderTracePathLlm(
+ { name: 'A', kind: 'function' }, { name: 'B', kind: 'function' }, 'mixed', [],
+ 'No route found from A to B within the requested search limits.',
+ CAP_HINT,
+ );
+ expect(lines[1]).toBe('diagnostic code=no_path message="No route found from A to B within the requested search limits."');
+ expect(lines[2]).toBe(`diagnostic code=search_cut message="${CAP_HINT}"`);
+ });
+
+ it('adds nothing when no cut hint is given', () => {
+ const lines = renderTracePathLlm(
+ { name: 'A', kind: 'function' }, { name: 'B', kind: 'function' }, 'mixed', [],
+ 'No route found from A to B.',
+ );
+ expect(lines).toHaveLength(2);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// searchPath — "no route exists" vs "budget stopped the search"
+// ---------------------------------------------------------------------------
+
+describe('searchPath cut semantics', () => {
+ it('reports cut with reason node-cap when the node budget stops the search before exhausting the graph', async () => {
+ // Two neighbours exist but the cap of 1 admits none of their expansions.
+ const client = makeClient({ A: { out: [n('x'), n('y')] } });
+ const cut = await searchPath(client as any, 'A', 'B', ['REL'], 10, 1);
+ expect(cut).toEqual({ path: null, cut: true, cutReason: 'node-cap' });
+ });
+
+ it('reports cut with reason depth when nodes beyond maxDepth remain unexplored', async () => {
+ const client = makeClient({ A: { out: [n('x')] }, x: { out: [n('y')] } });
+ const cut = await searchPath(client as any, 'A', 'B', ['REL'], 1, 10);
+ expect(cut).toEqual({ path: null, cut: true, cutReason: 'depth' });
+ });
+
+ it('reports cut=false after exhausting the graph without finding a route', async () => {
+ const client = makeClient({ A: { out: [n('x'), n('y')] }, x: {}, y: {} });
+ const none = await searchPath(client as any, 'A', 'B', ['REL'], 10, 10);
+ expect(none).toEqual({ path: null, cut: false });
+ });
+
+ it('still finds routes that complete within the budget, and flags a cut when the same route is just out of reach', async () => {
+ const client = makeClient({ A: { out: [n('x')] }, x: { out: [n('b')] } });
+ const found = await searchPath(client as any, 'A', 'b', ['REL'], 10, 3);
+ expect(found.cut).toBe(false);
+ expect(found.path?.map((p) => p.id)).toEqual(['A', 'x', 'b']);
+
+ // The route exists, but the budget stops one hop short — the caller must
+ // be able to tell this apart from "no route exists".
+ const tight = await searchPath(client as any, 'A', 'b', ['REL'], 10, 2);
+ expect(tight).toEqual({ path: null, cut: true, cutReason: 'node-cap' });
+ });
+
+ it('handles cyclic graphs without false cut claims', async () => {
+ const client = makeClient({ A: { out: [n('x')] }, x: { out: [n('A')] } });
+ const cycle = await searchPath(client as any, 'A', 'B', ['REL'], 10, 10);
+ expect(cycle).toEqual({ path: null, cut: false });
+ });
+});
diff --git a/ix-cli/src/cli/commands/trace.ts b/ix-cli/src/cli/commands/trace.ts
index cd367b3f..0588bdf4 100644
--- a/ix-cli/src/cli/commands/trace.ts
+++ b/ix-cli/src/cli/commands/trace.ts
@@ -250,17 +250,39 @@ export async function findPath(
maxDepth: number = 10,
maxNodes: number = Infinity,
): Promise<PathNode[] | null> {
- if (maxNodes < 1) return null;
- if (fromId === toId) return [{ id: fromId, name: "", kind: "" }];
+ const found = await searchPath(client, fromId, toId, predicates, maxDepth, maxNodes);
+ return found.path;
+}
+
+/**
+ * Budgeted route search that distinguishes "no route exists" from "a budget
+ * stopped the search before one was found": cut is true when the search ended
+ * early (node cap hit mid-flight, or nodes beyond maxDepth left unexplored)
+ * without reaching toId, with cutReason naming the bound to raise.
+ */
+export async function searchPath(
+ client: IxClient,
+ fromId: string,
+ toId: string,
+ predicates: string[],
+ maxDepth: number,
+ maxNodes: number,
+): Promise<{ path: PathNode[] | null; cut: boolean; cutReason?: "node-cap" | "depth" }> {
+ if (maxNodes < 1) return { path: null, cut: false };
+ if (fromId === toId) return { path: [{ id: fromId, name: "", kind: "" }], cut: false };
const nodeMap = new Map<string, { name: string; kind: string }>();
const queue: Array<{ id: string; path: string[] }> = [{ id: fromId, path: [fromId] }];
const visited = new Set<string>([fromId]);
+ let depthCut = false;
while (queue.length > 0) {
const entry = queue.shift()!;
const { id, path } = entry;
- if (path.length - 1 >= maxDepth) continue;
+ if (path.length - 1 >= maxDepth) {
+ depthCut = true;
+ continue;
+ }
const [outResult, inResult] = await Promise.all([
client.expand(id, { direction: "out", predicates, hops: 1 }),
@@ -269,7 +291,7 @@ export async function findPath(
for (const n of [...outResult.nodes, ...inResult.nodes]) {
if (visited.has(n.id)) continue;
- if (visited.size >= maxNodes) return null;
+ if (visited.size >= maxNodes) return { path: null, cut: true, cutReason: "node-cap" };
visited.add(n.id);
const name = n.name || n.attrs?.name || n.id.slice(0, 8);
if (!nodeMap.has(n.id)) {
@@ -278,18 +300,21 @@ export async function findPath(
if (n.id === toId) {
const fullPath = [...path, n.id];
- return fullPath.map((nodeId) => {
- if (nodeId === fromId) return { id: nodeId, name: "", kind: "" }; // filled below
- const meta = nodeMap.get(nodeId) ?? { name: nodeId.slice(0, 8), kind: "unknown" };
- return { id: nodeId, ...meta };
- });
+ return {
+ path: fullPath.map((nodeId) => {
+ if (nodeId === fromId) return { id: nodeId, name: "", kind: "" }; // filled below
+ const meta = nodeMap.get(nodeId) ?? { name: nodeId.slice(0, 8), kind: "unknown" };
+ return { id: nodeId, ...meta };
+ }),
+ cut: false,
+ };
}
queue.push({ id: n.id, path: [...path, n.id] });
}
}
- return null;
+ return { path: null, cut: depthCut, cutReason: depthCut ? "depth" : undefined };
}
// ── Text rendering ───────────────────────────────────────────────────
@@ -379,6 +404,7 @@ export function renderTracePathLlm(
from: { name: string; kind: string }, to: { name: string; kind: string },
relKind: string, pathNodes: PathNode[],
noPathMessage?: string,
+ cutHint?: string,
): string[] {
const lines = [llmLine("trace", [
["mode", "path"], ["from", from.name], ["to", to.name], ["kind", relKind],
@@ -386,6 +412,7 @@ export function renderTracePathLlm(
])];
if (pathNodes.length === 0) {
lines.push(llmLine("diagnostic", [["code", "no_path"], ["message", noPathMessage ?? `No route found from ${from.name} to ${to.name}.`]]));
+ if (cutHint) lines.push(llmLine("diagnostic", [["code", "search_cut"], ["message", cutHint]]));
return lines;
}
for (const n of pathNodes) lines.push(llmLine("step", [["name", n.name], ["kind", n.kind]]));
@@ -394,15 +421,26 @@ export function renderTracePathLlm(
export function renderTraceBothLlm(
target: { id: string; name: string; kind: string }, relKind: string, maxDepth: number,
- up: { tree: TraceNode[]; nodesVisited: number; maxDepthReached: number },
- down: { tree: TraceNode[]; nodesVisited: number; maxDepthReached: number },
+ up: { tree: TraceNode[]; nodesVisited: number; maxDepthReached: number; truncated?: boolean; depthLimited?: boolean },
+ down: { tree: TraceNode[]; nodesVisited: number; maxDepthReached: number; truncated?: boolean; depthLimited?: boolean },
+ maxNodes: number = Infinity,
): string[] {
+ const truncated = !!(up.truncated || down.truncated);
+ const depthLimited = !!(up.depthLimited || down.depthLimited);
const lines = [llmLine("trace", [
["mode", "directional"], ["target", target.name], ["kind", relKind],
["direction", "both"], ["depth", finiteDepth(maxDepth)], ["target_id", target.id?.slice(0, 8)],
+ ["truncated", truncated ? true : undefined],
+ ["depth_limited", depthLimited ? true : undefined],
["up_nodes", up.nodesVisited], ["up_depth", up.maxDepthReached],
["down_nodes", down.nodesVisited], ["down_depth", down.maxDepthReached],
])];
+ if (truncated || depthLimited) {
+ lines.push(llmLine("diagnostic", [
+ ["code", truncated ? "truncated" : "depth_limited"],
+ ["message", traversalHint(maxDepth, maxNodes, { truncated, depthLimited })],
+ ]));
+ }
lines.push(...traceNodesLlm("up", up.tree, target.id));
lines.push(...traceNodesLlm("down", down.tree, target.id));
return lines;
@@ -411,17 +449,22 @@ export function renderTraceBothLlm(
export function renderTraceSingleLlm(
target: { id: string; name: string; kind: string }, relKind: string, direction: string, maxDepth: number,
tree: TraceNode[], truncated: boolean, nodesVisited: number, maxDepthReached: number, maxNodes: number,
+ depthLimited: boolean = false,
): string[] {
const lines = [llmLine("trace", [
["mode", "directional"], ["target", target.name], ["kind", relKind],
["direction", direction], ["depth", finiteDepth(maxDepth)], ["target_id", target.id?.slice(0, 8)],
["nodes", nodesVisited], ["max_depth", maxDepthReached], ["truncated", truncated ? true : undefined],
+ ["depth_limited", depthLimited ? true : undefined],
])];
if (tree.length === 0) {
lines.push(llmLine("diagnostic", [["code", "no_edges"], ["message", `No ${direction} ${relKind} found for ${target.name}.`]]));
}
- if (truncated) {
- lines.push(llmLine("diagnostic", [["code", "truncated"], ["message", traversalHint(maxDepth, maxNodes, { truncated: true, depthLimited: false })]]));
+ if (truncated || depthLimited) {
+ lines.push(llmLine("diagnostic", [
+ ["code", truncated ? "truncated" : "depth_limited"],
+ ["message", traversalHint(maxDepth, maxNodes, { truncated, depthLimited })],
+ ]));
}
lines.push(...traceNodesLlm("node", tree, target.id));
return lines;
@@ -509,9 +552,12 @@ 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, maxNodes);
+ const { path: rawPath, cut: pathCut, cutReason } = await searchPath(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" : ""}.`;
+ const pathHint = bounded && pathCut
+ ? traversalHint(maxDepth, maxNodes, { truncated: cutReason === "node-cap", depthLimited: cutReason === "depth" })
+ : undefined;
// Fill in the from-node name (was left blank above)
const pathNodes: PathNode[] = rawPath
@@ -534,12 +580,22 @@ export function registerTraceCommand(program: Command): void {
output.summary = { path_length: pathNodes.length };
} else {
output.path = null;
- output.diagnostics = [
- {
- code: "no_path",
- message: noPathMessage,
- },
- ];
+ // Both states print no_path, but a budget cut adds a recovery
+ // hint so the caller can tell "none exists" from "search stopped".
+ output.diagnostics = pathCut
+ ? [
+ {
+ code: "no_path",
+ message: noPathMessage,
+ },
+ { code: "search_cut", message: pathHint },
+ ]
+ : [
+ {
+ code: "no_path",
+ message: noPathMessage,
+ },
+ ];
}
printJson(output);
return;
@@ -547,7 +603,7 @@ export function registerTraceCommand(program: Command): void {
// ── llm output ─────────────────────────────────────────
if (opts.format === "llm") {
- for (const line of renderTracePathLlm(fromTarget, toTarget, relKind, pathNodes, noPathMessage)) console.log(line);
+ for (const line of renderTracePathLlm(fromTarget, toTarget, relKind, pathNodes, noPathMessage, pathHint)) console.log(line);
return;
}
@@ -560,6 +616,7 @@ export function registerTraceCommand(program: Command): void {
if (pathNodes.length === 0) {
console.log(`\n${noPathMessage}`);
+ if (pathCut) console.log(chalk.dim(` ${pathHint}`));
return;
}
@@ -611,29 +668,43 @@ export function registerTraceCommand(program: Command): void {
// ── JSON ──────────────────────────────────────────────
if (opts.format === "json") {
- printJson(
- {
- mode: "directional",
- target: { name: target.name, kind: target.kind, path: relativePath(target.path) },
- direction: "both",
- kind: relKind,
- depth: maxDepth,
- upstream: {
- tree: upResult.tree.map(compactTreeNode),
- summary: { nodes_visited: upResult.nodesVisited, max_depth: upResult.maxDepthReached },
- },
- downstream: {
- tree: downResult.tree.map(compactTreeNode),
- summary: { nodes_visited: downResult.nodesVisited, max_depth: downResult.maxDepthReached },
- },
+ const output: Record<string, unknown> = {
+ mode: "directional",
+ target: { name: target.name, kind: target.kind, path: relativePath(target.path) },
+ direction: "both",
+ kind: relKind,
+ depth: maxDepth,
+ traversal: {
+ truncated: upResult.truncated || downResult.truncated,
+ depth_limited: upResult.depthLimited || downResult.depthLimited ? true : undefined,
+ node_cap: Number.isFinite(maxNodes) ? maxNodes : undefined,
+ },
+ upstream: {
+ tree: upResult.tree.map(compactTreeNode),
+ summary: { nodes_visited: upResult.nodesVisited, max_depth: upResult.maxDepthReached, depth_limited: upResult.depthLimited ? true : undefined },
},
- );
+ downstream: {
+ tree: downResult.tree.map(compactTreeNode),
+ summary: { nodes_visited: downResult.nodesVisited, max_depth: downResult.maxDepthReached, depth_limited: downResult.depthLimited ? true : undefined },
+ },
+ };
+ const bothTruncated = upResult.truncated || downResult.truncated;
+ const bothDepthLimited = upResult.depthLimited || downResult.depthLimited;
+ if (bothTruncated || bothDepthLimited) {
+ output.diagnostics = [
+ {
+ code: bothTruncated ? "truncated" : "depth_limited",
+ message: traversalHint(maxDepth, maxNodes, { truncated: bothTruncated, depthLimited: bothDepthLimited }),
+ },
+ ];
+ }
+ printJson(output);
return;
}
// ── llm ───────────────────────────────────────────────
if (opts.format === "llm") {
- for (const line of renderTraceBothLlm(target, relKind, maxDepth, upResult, downResult)) console.log(line);
+ for (const line of renderTraceBothLlm(target, relKind, maxDepth, upResult, downResult, maxNodes)) console.log(line);
return;
}
@@ -676,11 +747,17 @@ export function registerTraceCommand(program: Command): void {
renderSection("Summary");
renderKeyValue("Nodes visited", String(totalNodes));
renderKeyValue("Max depth", String(maxD));
+ if (upResult.truncated || downResult.truncated) {
+ renderKeyValue("Truncated", "true (node cap reached)");
+ }
+ if (upResult.depthLimited || downResult.depthLimited) {
+ renderKeyValue("Depth-limited", `true (stopped descending at depth ${maxD})`);
+ }
return;
}
// ── Single direction ────────────────────────────────────────
- const { tree, truncated, nodesVisited, maxDepthReached } = doUpstream
+ const { tree, truncated, depthLimited, nodesVisited, maxDepthReached } = doUpstream
? await buildTraceTree(client, target.id, { direction: "in", predicates, maxDepth, maxNodes })
: await buildTraceTree(client, target.id, { direction: "out", predicates, maxDepth, maxNodes });
@@ -693,7 +770,7 @@ export function registerTraceCommand(program: Command): void {
kind: relKind,
depth: maxDepth,
tree: tree.map(compactTreeNode),
- summary: { nodes_visited: nodesVisited, max_depth: maxDepthReached },
+ summary: { nodes_visited: nodesVisited, max_depth: maxDepthReached, depth_limited: depthLimited ? true : undefined },
};
if (tree.length === 0) {
@@ -701,9 +778,12 @@ export function registerTraceCommand(program: Command): void {
{ code: "no_edges", message: `No ${direction} ${relKind} found for ${target.name}.` },
];
}
- if (truncated) {
+ if (truncated || depthLimited) {
const diags = (output.diagnostics as unknown[]) ?? [];
- (diags as unknown[]).push({ code: "truncated", message: traversalHint(maxDepth, maxNodes, { truncated: true, depthLimited: false }) });
+ (diags as unknown[]).push({
+ code: truncated ? "truncated" : "depth_limited",
+ message: traversalHint(maxDepth, maxNodes, { truncated, depthLimited }),
+ });
output.diagnostics = diags;
}
@@ -713,7 +793,7 @@ export function registerTraceCommand(program: Command): void {
// ── llm ──────────────────────────────────────────────────────
if (opts.format === "llm") {
- for (const line of renderTraceSingleLlm(target, relKind, direction, maxDepth, tree, truncated, nodesVisited, maxDepthReached, maxNodes)) console.log(line);
+ for (const line of renderTraceSingleLlm(target, relKind, direction, maxDepth, tree, truncated, nodesVisited, maxDepthReached, maxNodes, depthLimited)) console.log(line);
return;
}
@@ -742,6 +822,8 @@ export function registerTraceCommand(program: Command): void {
renderSection("Summary");
renderKeyValue("Nodes visited", String(nodesVisited));
renderKeyValue("Max depth", String(maxDepthReached));
+ if (truncated) renderKeyValue("Truncated", "true (node cap reached)");
+ if (depthLimited) renderKeyValue("Depth-limited", `true (stopped descending at depth ${maxDepth})`);
},
);
}