Skip to content

armgit / Ix

Public Imported from GitHub
0

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

feat(depends,trace): bound an unasked-for traversal, and report its end honestly (#698)

Ian Hockec7100148b03
diff --git a/ix-cli/src/cli/__tests__/depends-semantics.test.ts b/ix-cli/src/cli/__tests__/depends-semantics.test.ts
index e620930d..c8ef32f9 100644
--- a/ix-cli/src/cli/__tests__/depends-semantics.test.ts
+++ b/ix-cli/src/cli/__tests__/depends-semantics.test.ts
@@ -68,9 +68,12 @@ describe("depends full-tree traversal", () => {
expect(dependsContent).toContain("nodesVisited >= maxNodes");
});
- it("reports truncation when limits hit", () => {
+ it("reports a cap cut and a depth stop as the different things they are", () => {
+ // Only the node cap can know that nodes were lost; reaching the depth
+ // bound means the walk stopped descending, which is not the same claim.
expect(dependsContent).toContain("truncated = true");
- expect(dependsContent).toContain("tree truncated");
+ expect(dependsContent).toContain("depthLimited = true");
+ expect(dependsContent).toContain("traversalHint");
});
});
diff --git a/ix-cli/src/cli/__tests__/traversal-bounds.test.ts b/ix-cli/src/cli/__tests__/traversal-bounds.test.ts
new file mode 100644
index 00000000..9fc66aa2
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/traversal-bounds.test.ts
@@ -0,0 +1,99 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { describe, expect, it, vi } from "vitest";
+
+import { buildDependencyTree, renderDependsLlm, traversalHint } from "../commands/depends.js";
+
+/**
+ * A graph where every node has two callers, so the cone is 2^depth. Both
+ * bounds were `Infinity`, which on a hub means the caller pays for thousands
+ * of nodes before seeing any of them.
+ */
+function infiniteFanout() {
+ let served = 0;
+ const client = {
+ expand: vi.fn(async (id: string, opts: { predicates: string[] }) => {
+ if (opts.predicates[0] !== "CALLS") return { nodes: [] };
+ served += 1;
+ return {
+ nodes: [
+ { id: `${id}-a`, name: `n${served}a`, kind: "function", attrs: { line_start: 1, line_end: 4 }, provenance: { source_uri: "src/a.ts" } },
+ { id: `${id}-b`, name: `n${served}b`, kind: "function", attrs: { line_start: 1, line_end: 4 }, provenance: { source_uri: "src/b.ts" } },
+ ],
+ };
+ }),
+ } as never;
+ return client;
+}
+
+describe("depends traversal bounds", () => {
+ it("stops at depth 3 by default", async () => {
+ const out = await buildDependencyTree(infiniteFanout(), "root");
+ expect(out.maxDepthReached).toBe(3);
+ expect(out.depthLimited).toBe(true);
+ });
+
+ it("stops at 100 nodes by default", async () => {
+ const out = await buildDependencyTree(infiniteFanout(), "root", { maxDepth: 50 });
+ expect(out.nodesVisited).toBeLessThanOrEqual(100);
+ expect(out.truncated).toBe(true);
+ });
+
+ it("still takes a caller's own bounds", async () => {
+ const out = await buildDependencyTree(infiniteFanout(), "root", { maxDepth: 1, maxNodes: 500 });
+ expect(out.maxDepthReached).toBe(1);
+ expect(out.nodesVisited).toBe(2);
+ });
+
+ it("does not call a depth stop a truncation", async () => {
+ // With a default of 3 this fires on most leaf branches. Claiming nodes
+ // were lost when the walk simply reached its bound is the dishonest half
+ // of a bound.
+ const empty = { expand: vi.fn(async () => ({ nodes: [] })) } as never;
+ const out = await buildDependencyTree(empty, "root");
+ expect(out.truncated).toBe(false);
+ expect(out.depthLimited).toBe(false);
+ });
+});
+
+describe("the ranking the cap applies", () => {
+ it("keeps a followable node over a dangling one", async () => {
+ const client = {
+ expand: vi.fn(async (_id: string, opts: { predicates: string[] }) => {
+ if (opts.predicates[0] !== "CALLS") return { nodes: [] };
+ return {
+ nodes: [
+ { id: "x1", name: "d41d8cd98f00b204e9800998ecf8427e", kind: "function" },
+ { id: "x2", name: "handleLogin", kind: "function" },
+ { id: "x3", name: "verify", kind: "function", provenance: { source_uri: "src/a.ts" } },
+ ],
+ };
+ }),
+ } as never;
+ const out = await buildDependencyTree(client, "root", { maxDepth: 1, maxNodes: 2 });
+ expect(out.tree.map((n) => n.name)).toEqual(["verify", "handleLogin"]);
+ expect(out.truncated).toBe(true);
+ });
+});
+
+describe("traversalHint", () => {
+ it("names the cap when the cap is what cut", () => {
+ expect(traversalHint(3, 100, { truncated: true, depthLimited: true }))
+ .toBe("Node cap of 100 reached; nodes were dropped. Raise --cap, or start from a narrower target.");
+ });
+
+ it("says only that it stopped when it only stopped", () => {
+ expect(traversalHint(3, 100, { truncated: false, depthLimited: true }))
+ .toBe("Stopped descending at depth 3; there may be more below. Raise --depth to look further.");
+ });
+
+ it("reaches the record stream with the right code", () => {
+ const target = { id: "t", name: "verify", kind: "function" };
+ const capped = renderDependsLlm(target, [], true, 100, 3, { maxDepth: 3, maxNodes: 100, depthLimited: true });
+ expect(capped.some((l) => l.startsWith("diagnostic code=truncated"))).toBe(true);
+
+ const stopped = renderDependsLlm(target, [], false, 8, 3, { maxDepth: 3, maxNodes: 100, depthLimited: true });
+ expect(stopped[0]).toContain("depth_limited=true");
+ expect(stopped.some((l) => l.startsWith("diagnostic code=depth_limited"))).toBe(true);
+ });
+});
diff --git a/ix-cli/src/cli/commands/depends.ts b/ix-cli/src/cli/commands/depends.ts
index da1968c9..feaea8ef 100644
--- a/ix-cli/src/cli/commands/depends.ts
+++ b/ix-cli/src/cli/commands/depends.ts
@@ -23,8 +23,20 @@ export interface DependencyNode {
cycle?: boolean;
}
-const MAX_NODES = Infinity;
-const DEFAULT_MAX_DEPTH = Infinity;
+/**
+ * What an unasked-for traversal is allowed to cost.
+ *
+ * Both were `Infinity`. `ix depends` on a hub walks the whole upstream cone,
+ * which on this graph is thousands of nodes and 5-50 KB of output for a
+ * question that is usually answered by the first level or two — and the caller
+ * pays for all of it before seeing any of it.
+ *
+ * Depth 3 is far enough to show a path through an intermediate; 100 nodes is
+ * more than fits on a screen. `--depth` and `--cap` still take anything,
+ * including a larger number, and the output says when a bound was reached.
+ */
+const MAX_NODES = 100;
+const DEFAULT_MAX_DEPTH = 3;
const PREDICATE_META: Record<string, { relation: DependencyNode["relation"]; sourceEdge: DependencyNode["sourceEdge"] }> = {
CALLS: { relation: "called_by", sourceEdge: "CALLS" },
@@ -35,6 +47,13 @@ const PREDICATE_META: Record<string, { relation: DependencyNode["relation"]; sou
};
const ALL_DEPENDENCY_PREDICATES = Object.keys(PREDICATE_META);
+/** Followable first: a name and a path, then a name, then a dangling id. */
+function nodePriority(n: any): number {
+ const name = n.name || n.attrs?.name || "";
+ if (!name || isRawId(name)) return 2;
+ return (n.provenance?.source_uri ?? n.provenance?.sourceUri ?? n.attrs?.path) ? 0 : 1;
+}
+
// ── Tree building ───────────────────────────────────────────────────
/**
@@ -45,17 +64,30 @@ export async function buildDependencyTree(
client: IxClient,
rootId: string,
opts?: { maxDepth?: number; maxNodes?: number; predicates?: string[] },
-): Promise<{ tree: DependencyNode[]; truncated: boolean; nodesVisited: number; maxDepthReached: number }> {
+): Promise<{
+ tree: DependencyNode[];
+ truncated: boolean;
+ depthLimited: boolean;
+ nodesVisited: number;
+ maxDepthReached: number;
+}> {
const maxDepth = opts?.maxDepth ?? DEFAULT_MAX_DEPTH;
const maxNodes = opts?.maxNodes ?? MAX_NODES;
const activePredicates = (opts?.predicates ?? ALL_DEPENDENCY_PREDICATES).filter((p) => p in PREDICATE_META);
const visited = new Set<string>([rootId]);
let nodesVisited = 0;
let truncated = false;
+ let depthLimited = false;
let maxDepthReached = 0;
async function expand(nodeId: string, depth: number): Promise<DependencyNode[]> {
- if (depth > maxDepth) { truncated = true; return []; }
+ // Stopping at the depth bound is not the same as cutting something off:
+ // there may have been nothing below. `truncated` stays a claim that nodes
+ // were definitely lost — which only the node cap can know — and
+ // `depthLimited` says the walk stopped descending. With an infinite
+ // default the distinction never mattered; with a default of 3 it is the
+ // difference between a true report and a lie on most leaf branches.
+ if (depth > maxDepth) { depthLimited = true; return []; }
if (nodesVisited >= maxNodes) { truncated = true; return []; }
maxDepthReached = Math.max(maxDepthReached, depth);
@@ -70,7 +102,13 @@ export async function buildDependencyTree(
// root would otherwise appear twice, the second time as a spurious cycle).
const levelSeen = new Set<string>();
- const processNodes = async (nodes: any[], relation: "called_by" | "imported_by" | "referenced_by" | "extended_by" | "implemented_by", sourceEdge: "CALLS" | "IMPORTS" | "REFERENCES" | "EXTENDS" | "IMPLEMENTS") => {
+ const processNodes = async (rawNodes: any[], relation: "called_by" | "imported_by" | "referenced_by" | "extended_by" | "implemented_by", sourceEdge: "CALLS" | "IMPORTS" | "REFERENCES" | "EXTENDS" | "IMPLEMENTS") => {
+ // Rank before the cap, or the cap keeps whatever the graph returned
+ // first. A node whose name is a raw id is a dangling reference nothing
+ // can follow, and one with no path costs a `locate` before it can be
+ // read; neither should displace a node carrying both. Stable within a
+ // band, and the predicate order (CALLS before IMPLEMENTS) is untouched.
+ const nodes = [...rawNodes].sort((a, b) => nodePriority(a) - nodePriority(b));
for (const n of nodes) {
if (nodesVisited >= maxNodes) { truncated = true; break; }
// Skip if already emitted at this level via a different edge type.
@@ -112,7 +150,7 @@ export async function buildDependencyTree(
}
const tree = await expand(rootId, 1);
- return { tree, truncated, nodesVisited, maxDepthReached };
+ return { tree, truncated, depthLimited, nodesVisited, maxDepthReached };
}
// ── Tree rendering ──────────────────────────────────────────────────
@@ -153,9 +191,22 @@ function renderTree(children: DependencyNode[], prefix: string, isLast: boolean[
* row per node with an explicit `parent=<id>` (top-level nodes point at the
* target). Consumers re-tree from id/parent alone. Ids are 8-char prefixes.
*/
+/** What stopped the walk, and the flag that lifts it. */
+export function traversalHint(
+ maxDepth: number,
+ maxNodes: number,
+ what: { truncated: boolean; depthLimited: boolean },
+): string {
+ if (what.truncated) {
+ return `Node cap of ${maxNodes} reached; nodes were dropped. Raise --cap, or start from a narrower target.`;
+ }
+ return `Stopped descending at depth ${maxDepth}; there may be more below. Raise --depth to look further.`;
+}
+
export function renderDependsLlm(
target: { id: string; name: string; kind: string; path?: string },
tree: DependencyNode[], truncated: boolean, nodesVisited: number, maxDepthReached: number,
+ bounds?: { maxDepth: number; maxNodes: number; depthLimited?: boolean },
): string[] {
const lines = [llmLine("depends", [
["target", target.name],
@@ -165,10 +216,17 @@ export function renderDependsLlm(
["nodes", nodesVisited],
["depth", maxDepthReached],
["truncated", truncated ? true : undefined],
+ ["depth_limited", bounds?.depthLimited ? true : undefined],
])];
if (tree.length === 0) {
lines.push(llmLine("diagnostic", [["code", "no_edges"], ["message", "No upstream dependents found."]]));
}
+ if (bounds && (truncated || bounds.depthLimited)) {
+ lines.push(llmLine("diagnostic", [
+ ["code", truncated ? "truncated" : "depth_limited"],
+ ["message", traversalHint(bounds.maxDepth, bounds.maxNodes, { truncated, depthLimited: !!bounds.depthLimited })],
+ ]));
+ }
const emit = (node: DependencyNode, parentId: string): void => {
lines.push(llmLine("dep", [
["name", node.resolved ? node.name : undefined],
@@ -222,7 +280,7 @@ export function registerDependsCommand(program: Command): void {
const maxDepth = opts.depth ? parseInt(opts.depth, 10) : DEFAULT_MAX_DEPTH;
const maxNodes = opts.cap ? parseInt(opts.cap, 10) : MAX_NODES;
- const { tree, truncated, nodesVisited, maxDepthReached } = await buildDependencyTree(
+ const { tree, truncated, depthLimited, nodesVisited, maxDepthReached } = await buildDependencyTree(
client, target.id, { maxDepth, maxNodes },
);
@@ -240,15 +298,23 @@ export function registerDependsCommand(program: Command): void {
nodesVisited,
maxDepthReached,
truncated,
- ...(opts.depth ? { depthLimit: maxDepth } : {}),
+ depthLimited,
+ // Always, not only when the caller passed a flag: there is a
+ // default now, and a bound nobody is told about is a bound nobody
+ // can raise.
+ depthLimit: maxDepth,
+ nodeCap: maxNodes,
},
};
if (tree.length === 0) {
output.diagnostics = [{ code: "no_edges", message: `No upstream dependents found for resolved entity.` }];
}
- if (truncated) {
+ if (truncated || depthLimited) {
output.diagnostics = output.diagnostics ?? [];
- output.diagnostics.push({ code: "truncated", message: `Traversal truncated (depth: ${maxDepth}, node cap: ${maxNodes}).` });
+ output.diagnostics.push({
+ code: truncated ? "truncated" : "depth_limited",
+ message: traversalHint(maxDepth, maxNodes, { truncated, depthLimited }),
+ });
}
printJson(output);
return;
@@ -256,7 +322,7 @@ export function registerDependsCommand(program: Command): void {
// ── llm output ───────────────────────────────────────────────
if (opts.format === "llm") {
- for (const line of renderDependsLlm(target, tree, truncated, nodesVisited, maxDepthReached)) console.log(line);
+ for (const line of renderDependsLlm(target, tree, truncated, nodesVisited, maxDepthReached, { maxDepth, maxNodes, depthLimited })) console.log(line);
return;
}
@@ -277,8 +343,9 @@ export function registerDependsCommand(program: Command): void {
console.log(` ${line}`);
}
- if (truncated) {
- console.log(chalk.yellow(`\n (tree truncated — ${nodesVisited} nodes visited, depth ${maxDepthReached})`));
+ if (truncated || depthLimited) {
+ console.log(chalk.yellow(`\n (${nodesVisited} nodes visited, depth ${maxDepthReached})`));
+ console.log(chalk.dim(` ${traversalHint(maxDepth, maxNodes, { truncated, depthLimited })}`));
}
console.log(chalk.dim(`\n ${nodesVisited} upstream dependents, depth ${maxDepthReached}`));
diff --git a/ix-cli/src/cli/commands/trace.ts b/ix-cli/src/cli/commands/trace.ts
index a0548d5a..cd367b3f 100644
--- a/ix-cli/src/cli/commands/trace.ts
+++ b/ix-cli/src/cli/commands/trace.ts
@@ -16,6 +16,7 @@ import {
} from "../ui.js";
import { compactTreeNode, relativePath, printJson } from "../format.js";
import { llmLine, llmShortId, type LlmValue } from "../llm.js";
+import { traversalHint } from "./depends.js";
import { parsePickOption } from "../options.js";
// ── Types ────────────────────────────────────────────────────────────
@@ -38,8 +39,15 @@ interface PathNode {
// ── Constants ────────────────────────────────────────────────────────
-const DEFAULT_MAX_DEPTH = Infinity;
-const MAX_NODES = Infinity;
+/**
+ * What an unasked-for traversal is allowed to cost — the same bounds
+ * `ix depends` uses, for the same reason: both were `Infinity`, and on a hub
+ * that is thousands of nodes the caller pays for before seeing any of them.
+ * `--depth` and `--cap` still take anything, and the output says when a bound
+ * was reached.
+ */
+const DEFAULT_MAX_DEPTH = 3;
+const MAX_NODES = 100;
// ── Helpers ──────────────────────────────────────────────────────────
@@ -165,15 +173,24 @@ async function buildTraceTree(
maxDepth: number;
maxNodes: number;
},
-): Promise<{ tree: TraceNode[]; truncated: boolean; nodesVisited: number; maxDepthReached: number }> {
+): Promise<{
+ tree: TraceNode[];
+ truncated: boolean;
+ depthLimited: boolean;
+ nodesVisited: number;
+ maxDepthReached: number;
+}> {
const { direction, predicates, maxDepth, maxNodes } = opts;
const visited = new Set<string>([rootId]);
let nodesVisited = 0;
let truncated = false;
+ let depthLimited = false;
let maxDepthReached = 0;
async function expand(nodeId: string, depth: number): Promise<TraceNode[]> {
- if (depth > maxDepth) { truncated = true; return []; }
+ // See depends.ts: stopping at the depth bound is not evidence that
+ // anything was cut off.
+ if (depth > maxDepth) { depthLimited = true; return []; }
if (nodesVisited >= maxNodes) { truncated = true; return []; }
maxDepthReached = Math.max(maxDepthReached, depth);
@@ -220,7 +237,7 @@ async function buildTraceTree(
}
const tree = await expand(rootId, 1);
- return { tree, truncated, nodesVisited, maxDepthReached };
+ return { tree, truncated, depthLimited, nodesVisited, maxDepthReached };
}
// ── Path search (BFS) ────────────────────────────────────────────────
@@ -404,7 +421,7 @@ export function renderTraceSingleLlm(
lines.push(llmLine("diagnostic", [["code", "no_edges"], ["message", `No ${direction} ${relKind} found for ${target.name}.`]]));
}
if (truncated) {
- lines.push(llmLine("diagnostic", [["code", "truncated"], ["message", `Traversal truncated (depth: ${maxDepth}, node cap: ${maxNodes}).`]]));
+ lines.push(llmLine("diagnostic", [["code", "truncated"], ["message", traversalHint(maxDepth, maxNodes, { truncated: true, depthLimited: false })]]));
}
lines.push(...traceNodesLlm("node", tree, target.id));
return lines;
@@ -686,7 +703,7 @@ export function registerTraceCommand(program: Command): void {
}
if (truncated) {
const diags = (output.diagnostics as unknown[]) ?? [];
- (diags as unknown[]).push({ code: "truncated", message: `Traversal truncated (depth: ${maxDepth}, node cap: ${maxNodes}).` });
+ (diags as unknown[]).push({ code: "truncated", message: traversalHint(maxDepth, maxNodes, { truncated: true, depthLimited: false }) });
output.diagnostics = diags;
}
diff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.md
index 72bef4e7..65cf3603 100644
--- a/skills/ix/references/flags.md
+++ b/skills/ix/references/flags.md
@@ -62,6 +62,12 @@ surfaces (#575).
`truncated=true total_lines=<n> next=<path>:401-800`, so the next page is one
command away. A line range you typed (`ix read a.ts:1-900`) is never capped,
a symbol target is its own span, and `--all` reads the whole file.
+- **`ix depends` and `ix trace` stop at depth 3 and 100 nodes.** Both were
+ unbounded, which on a hub is thousands of nodes the caller pays for before
+ seeing any. The output distinguishes the two ways a walk ends:
+ `truncated=true` means the node cap dropped nodes, `depth_limited=true` means
+ the walk stopped descending and there may or may not be more. `--depth` and
+ `--cap` take anything.
- **`--pick <n>` is 1-based** everywhere it appears, and is how you resolve an
ambiguous target without re-running with a longer name.
- **`--no-recursive` and `--no-open` negate a default-on behaviour**, so their
@@ -185,8 +191,8 @@ Show upstream dependents of the given entity (full tree by default).
| `--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) |
-| `--depth` | `<n>` | — | Cap traversal depth |
-| `--cap` | `<n>` | — | Cap number of nodes visited |
+| `--depth` | `<n>` | `3` | Cap traversal depth |
+| `--cap` | `<n>` | `100` | Cap number of nodes visited |
| `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |
| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |
| `--include-tests` | — | off | Include test and fixture entities in results |
@@ -640,8 +646,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 in edges (also applies to `--to`) |
-| `--cap` | `<n>` | — | Cap nodes visited per direction, or across the `--to` search (including the source) |
+| `--depth` | `<n>` | `3` | Cap traversal depth in edges (also applies to `--to`) |
+| `--cap` | `<n>` | `100` | 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) |