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
// Copyright 2026 Ix Infrastructure Inc.
import type { Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { createClient } from "../../client/factory.js";
import { resolveFileOrEntityFull, resolveFileOrReport, activeReadScope, ensureReadScope } from "../resolve.js";
import type { ResolvedEntity } from "../resolve.js";
import {
renderSection,
renderKeyValue,
renderResolvedHeader,
colorizeKind,
reportResolutionFailure,
reportUnresolvedTarget,
reportResolutionNotices,
} from "../ui.js";
import { compactTreeNode, relativePath, printJson } from "../format.js";
import { llmLine, llmShortId, type LlmValue } from "../llm.js";
import { traversalHint } from "./depends.js";
import { parseCountOption, parsePickOption } from "../options.js";
import { createLimiter, EXPAND_CONCURRENCY, walkTree, type Limiter, type TreeWalkResult } from "../tree-walk.js";
// ── Types ────────────────────────────────────────────────────────────
interface TraceNode {
id: string;
name: string;
kind: string;
resolved: boolean;
path?: string;
children: TraceNode[];
cycle?: boolean;
}
interface PathNode {
id: string;
name: string;
kind: string;
/** Predicate of the edge that reached this step from the previous one; set only when the edge was found. */
via?: string;
/** True when that edge runs from this step back to the previous one (found walking "in"). */
reversed?: boolean;
}
// ── Constants ────────────────────────────────────────────────────────
/**
* 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` must be non-negative integers, and the output says
* when a bound was reached.
*/
const DEFAULT_MAX_DEPTH = 3;
const MAX_NODES = 100;
// ── Helpers ──────────────────────────────────────────────────────────
const ALL_PREDICATES = ["CALLS", "IMPORTS", "REFERENCES", "EXTENDS", "IMPLEMENTS", "CONTAINS"];
/** Map --kind flag to API predicates. If no kind specified, use all predicates (same as depends). */
function kindToPredicates(kind?: string): string[] {
if (!kind) return ALL_PREDICATES;
switch (kind.toLowerCase()) {
case "calls": return ["CALLS", "REFERENCES"];
case "imports": return ["IMPORTS"];
case "depends": return ["IMPORTS"];
case "contains": return ["CONTAINS"];
default: return ALL_PREDICATES;
}
}
function isExactSymbolMatch(node: any, symbol: string): boolean {
const name = node?.name || node?.attrs?.name || "";
return name === symbol || String(name).toLowerCase() === symbol.toLowerCase();
}
async function traceEdgeScore(
client: IxClient,
nodeId: string,
direction: "upstream" | "downstream" | "both",
predicates: string[],
): Promise<number> {
if (direction === "both") {
const [upstream, downstream] = await Promise.all([
client.expand(nodeId, { direction: "in", predicates, hops: 1 }),
client.expand(nodeId, { direction: "out", predicates, hops: 1 }),
]);
return upstream.nodes.length + downstream.nodes.length;
}
const result = await client.expand(nodeId, {
direction: direction === "upstream" ? "in" : "out",
predicates,
hops: 1,
});
return result.nodes.length;
}
export async function pickTraceTarget(
client: IxClient,
symbol: string,
target: ResolvedEntity,
opts: {
direction: "upstream" | "downstream" | "both";
predicates: string[];
pick?: number;
path?: string;
},
): Promise<ResolvedEntity> {
if (target.kind !== "config_entry") return target;
if (opts.path) return target;
await ensureReadScope(client);
const candidates = (await client.search(symbol, {
limit: 50,
kind: "config_entry",
nameOnly: true,
...activeReadScope(),
}))
.filter((node: any) => isExactSymbolMatch(node, symbol))
.filter((node: any, index: number, all: any[]) =>
all.findIndex((other: any) => other.id === node.id) === index,
);
if (candidates.length <= 1) return target;
const scored = await Promise.all(
candidates.map(async (node: any, index: number) => ({
node,
index,
score: await traceEdgeScore(client, node.id, opts.direction, opts.predicates),
})),
);
scored.sort((a, b) => {
if (a.score !== b.score) return b.score - a.score;
if (a.node.id === target.id) return -1;
if (b.node.id === target.id) return 1;
return a.index - b.index;
});
if (opts.pick !== undefined) {
const picked = scored[opts.pick - 1];
if (!picked) return target;
return {
id: picked.node.id,
kind: picked.node.kind,
name: picked.node.name || picked.node.attrs?.name || symbol,
path: picked.node.provenance?.sourceUri ?? picked.node.provenance?.source_uri ?? picked.node.path,
resolutionMode: "scored",
};
}
const current = scored.find((entry) => entry.node.id === target.id);
const best = scored[0];
if (!best) return target;
if ((current?.score ?? -1) >= best.score) return target;
if (best.score <= 0) return target;
return {
id: best.node.id,
kind: best.node.kind,
name: best.node.name || best.node.attrs?.name || symbol,
path: best.node.provenance?.sourceUri ?? best.node.provenance?.source_uri ?? best.node.path,
resolutionMode: "scored",
};
}
// ── Tree traversal ───────────────────────────────────────────────────
async function buildTraceTree(
client: IxClient,
rootId: string,
opts: {
direction: "in" | "out";
predicates: string[];
maxDepth: number;
maxNodes: number;
limiter?: Limiter;
},
): Promise<TreeWalkResult<TraceNode>> {
const { direction, predicates, maxDepth, maxNodes, limiter } = opts;
return walkTree<TraceNode>({
rootId,
maxDepth,
maxNodes,
// One call per predicate (matches depends.ts behaviour — order and dedup are stable)
predicates,
expand: (nodeId, p) => client.expand(nodeId, { direction, predicates: [p], hops: 1 }),
makeNode: (n, _p, { name, resolved, cycle }) => ({
id: n.id,
name: resolved ? name : n.id.slice(0, 8),
kind: n.kind ?? "unknown",
resolved,
path: n.provenance?.sourceUri ?? n.provenance?.source_uri ?? undefined,
children: [],
...(cycle ? { cycle: true } : {}),
}),
limiter,
});
}
// ── Path search (BFS) ────────────────────────────────────────────────
export async function findPath(
client: IxClient,
fromId: string,
toId: string,
predicates: string[],
maxDepth: number = 10,
maxNodes: number = Infinity,
): Promise<PathNode[] | null> {
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" }> {
// A cap below one admits not even the source, so nothing was searched:
// that is the budget talking, not evidence that no route exists.
if (maxNodes < 1) return { path: null, cut: true, cutReason: "node-cap" };
if (fromId === toId) return { path: [{ id: fromId, name: "", kind: "" }], cut: false };
const nodeMap = new Map<string, { name: string; kind: string }>();
// How each visited node was first reached from its BFS parent.
const linkMap = new Map<string, { via: string; reversed: boolean }>();
const predicateRank = (p: string) => {
const i = predicates.indexOf(p);
return i < 0 ? predicates.length : i;
};
// The predicate joining parent and child in the given orientation, first in
// request order when several do. Edges between two neighbours are ignored.
const linkPredicate = (edges: any[] | undefined, src: string, dst: string): string | undefined => {
let best: string | undefined;
for (const e of edges ?? []) {
if (e?.src !== src || e?.dst !== dst || typeof e.predicate !== "string") continue;
if (best === undefined || predicateRank(e.predicate) < predicateRank(best)) best = e.predicate;
}
return best;
};
// Breadth-first as before, and still read one entry at a time in queue
// order, so the route returned — the shortest, first-queued on a tie — does
// not change. What changes is that an entry's neighbours are requested as
// soon as it is queued, a bounded number at a time, instead of when the
// loop reaches it.
const limit = createLimiter(EXPAND_CONCURRENCY);
let done = false;
const noNodes = { nodes: [] as any[], edges: [] as any[] };
const neighbours = (id: string) => {
const both = Promise.all([
limit(() => (done ? Promise.resolve(noNodes) : client.expand(id, { direction: "out", predicates, hops: 1 }))),
limit(() => (done ? Promise.resolve(noNodes) : client.expand(id, { direction: "in", predicates, hops: 1 }))),
]);
both.catch(() => {}); // read later, or never once a route is found
return both;
};
type Entry = { id: string; path: string[]; next?: ReturnType<typeof neighbours> };
const enqueue = (id: string, path: string[]): Entry =>
// An entry at the depth bound is never expanded, so nothing is fetched for it.
({ id, path, next: path.length - 1 >= maxDepth ? undefined : neighbours(id) });
const queue: Entry[] = [enqueue(fromId, [fromId])];
const visited = new Set<string>([fromId]);
let depthCut = false;
try {
for (let head = 0; head < queue.length; head++) {
const { id, path, next } = queue[head];
if (!next) {
depthCut = true;
continue;
}
const [outResult, inResult] = await next;
const outCount = outResult.nodes.length;
const found = [...outResult.nodes, ...inResult.nodes];
for (let k = 0; k < found.length; k++) {
const n = found[k];
if (visited.has(n.id)) continue;
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)) {
nodeMap.set(n.id, { name, kind: n.kind ?? "unknown" });
}
if (!linkMap.has(n.id)) {
const reversed = k >= outCount;
const via = reversed
? linkPredicate(inResult.edges, n.id, id)
: linkPredicate(outResult.edges, id, n.id);
if (via) linkMap.set(n.id, { via, reversed });
}
if (n.id === toId) {
const fullPath = [...path, n.id];
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" };
const link = linkMap.get(nodeId);
return {
id: nodeId,
...meta,
...(link ? { via: link.via } : {}),
...(link?.reversed ? { reversed: true } : {}),
};
}),
cut: false,
};
}
queue.push(enqueue(n.id, [...path, n.id]));
}
}
} finally {
// Whatever is still queued behind the limiter is not sent.
done = true;
}
return { path: null, cut: depthCut, cutReason: depthCut ? "depth" : undefined };
}
/**
* A directional walk's JSON summary. `truncated` and `depth_limited` appear
* only when true, matching the llm header fields of the same names.
*/
function traceSummary(r: { nodesVisited: number; maxDepthReached: number; truncated?: boolean; depthLimited?: boolean }) {
return {
nodes_visited: r.nodesVisited,
max_depth: r.maxDepthReached,
truncated: r.truncated ? true : undefined,
depth_limited: r.depthLimited ? true : undefined,
};
}
// ── Text rendering ───────────────────────────────────────────────────
/** Return last 3 path components from a file URI, for compact display. */
function shortPath(uri: string | undefined): string {
if (!uri) return "";
const p = uri.replace(/^file:\/\//, "").replace(/\\/g, "/");
const parts = p.split("/").filter(Boolean);
return parts.slice(-3).join("/");
}
/** Walk a tree and count how many times each node name appears. */
function collectAllNames(children: Array<{ name: string; children: any[] }>, out: Map<string, number>): void {
for (const c of children) {
out.set(c.name, (out.get(c.name) ?? 0) + 1);
collectAllNames(c.children, out);
}
}
function renderTraceTree(
children: Array<{ name: string; kind?: string; path?: string; children: any[]; cycle?: boolean }>,
isLast: boolean[],
disambiguate?: Set<string>,
): string[] {
const lines: string[] = [];
for (let i = 0; i < children.length; i++) {
const child = children[i];
const last = i === children.length - 1;
const connector = last ? "└─ " : "├─ ";
let indent = "";
for (const il of isLast) {
indent += il ? " " : "│ ";
}
const kindStr = child.cycle
? chalk.dim((child.kind ?? "").padEnd(10))
: colorizeKind(child.kind ?? "");
let nameStr = child.cycle
? chalk.dim(child.name) + chalk.yellow(" ↺")
: child.name;
if (!child.cycle && disambiguate?.has(child.name) && child.path) {
nameStr += chalk.dim(` (${shortPath(child.path)})`);
}
lines.push(`${indent}${connector}${kindStr} ${nameStr}`);
if (child.children.length > 0) {
lines.push(...renderTraceTree(child.children, [...isLast, last], disambiguate));
}
}
return lines;
}
const cap = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);
// ── llm rendering ─────────────────────────────────────────────────────
/** Flatten a trace tree into llm records with explicit parent=<id> (8-char ids). */
function traceNodesLlm(record: string, tree: TraceNode[], rootId: string): string[] {
const lines: string[] = [];
const emit = (node: TraceNode, parentId: string): void => {
lines.push(llmLine(record, [
["name", node.resolved ? node.name : undefined],
["kind", node.kind],
["id", llmShortId(node.id)],
["parent", parentId?.slice(0, 8)],
["path", relativePath(node.path)],
["cycle", node.cycle ? true : undefined],
["resolved", node.resolved ? undefined : false],
]));
for (const c of node.children) emit(c, node.id);
};
for (const n of tree) emit(n, rootId);
return lines;
}
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,
cutHint?: { code: "truncated" | "depth_limited"; message: 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", noPathMessage ?? `No route found from ${from.name} to ${to.name}.`]]));
if (cutHint) lines.push(llmLine("diagnostic", [["code", cutHint.code], ["message", cutHint.message]]));
return lines;
}
for (const n of pathNodes) {
lines.push(llmLine("step", [
["name", n.name], ["kind", n.kind],
["via", n.via],
["reversed", n.reversed ? true : undefined],
]));
}
return lines;
}
export function renderTraceBothLlm(
target: { id: string; name: string; kind: string }, relKind: string, maxDepth: 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;
}
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 || 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;
}
// ── Command ──────────────────────────────────────────────────────────
export function registerTraceCommand(program: Command): void {
program
.command("trace <symbol>")
.description("Follow how it connects")
.option("--to <target>", "Find path to target symbol")
.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 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")
.option("--include-tests", "Include test and fixture entities")
.option("--tests-only", "Show only test and fixture entities")
.addHelpText(
"after",
`\nExamples:
ix trace IxClient
ix trace IxClient --downstream
ix trace resolve --upstream
ix trace registerImpactCommand --to IxClient
ix trace api.ts --kind imports
ix trace IxClient --depth 3 --format json`,
)
.action(
async (
symbol: string,
opts: {
to?: string;
upstream?: boolean;
downstream?: boolean;
kind?: string;
depth?: string;
cap?: string;
pick?: number;
path?: string;
format: string;
includeTests?: boolean;
testsOnly?: boolean;
},
) => {
const client = createClient();
const resolveOpts = {
path: opts.path,
pick: opts.pick,
includeTests: opts.includeTests,
testsOnly: opts.testsOnly,
};
const maxDepth = opts.depth !== undefined ? parseCountOption(opts.depth, "3") : DEFAULT_MAX_DEPTH;
const maxNodes = opts.cap !== undefined ? parseCountOption(opts.cap, "100") : MAX_NODES;
// ── Path mode (--to) ────────────────────────────────────────
if (opts.to) {
const toResolveOpts = {
...resolveOpts,
path: undefined,
};
const [fromResult, toResult] = await Promise.all([
resolveFileOrEntityFull(client, symbol, resolveOpts),
resolveFileOrEntityFull(client, opts.to, toResolveOpts),
]);
if (!fromResult.resolved || !toResult.resolved) {
if (!fromResult.resolved && !toResult.resolved && !fromResult.ambiguous && !toResult.ambiguous) {
reportUnresolvedTarget([symbol, opts.to], opts.format);
} else if (!fromResult.resolved) {
reportResolutionFailure(symbol, fromResult, opts.format, resolveOpts);
} else if (!toResult.resolved) {
reportResolutionFailure(opts.to, toResult, opts.format, toResolveOpts);
}
return;
}
const fromTarget = fromResult.entity;
const toTarget = toResult.entity;
for (const r of [fromResult, toResult]) {
if (r.notices?.length) reportResolutionNotices(r.notices, opts.format, resolveOpts);
}
const relKind = opts.kind ?? "mixed";
const predicates = kindToPredicates(opts.kind);
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" : ""}.`;
// Coded like the directional modes' cuts, so a caller knows whether to
// raise --cap or --depth without parsing the message.
const pathHint = bounded && pathCut
? {
code: cutReason === "node-cap" ? "truncated" as const : "depth_limited" as const,
message: 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
? rawPath.map((n, i) =>
i === 0 ? { id: n.id, name: fromTarget.name, kind: fromTarget.kind } : n,
)
: [];
// ── JSON output ────────────────────────────────────────
if (opts.format === "json") {
const output: Record<string, unknown> = {
mode: "path",
from: { name: fromTarget.name, kind: fromTarget.kind, path: relativePath(fromTarget.path) },
to: { name: toTarget.name, kind: toTarget.kind, path: relativePath(toTarget.path) },
kind: relKind,
};
if (pathNodes.length > 0) {
const mapped = pathNodes.map((n) => ({
name: n.name,
kind: n.kind,
...(n.via ? { via: n.via } : {}),
...(n.reversed ? { reversed: true } : {}),
}));
output.path = mapped;
output.summary = { path_length: pathNodes.length };
} else {
output.path = null;
// Both states print no_path, but a budget cut adds the bound that
// stopped it, so the caller can tell "none exists" from "search stopped".
output.diagnostics = [
{
code: "no_path",
message: noPathMessage,
},
...(pathHint ? [pathHint] : []),
];
}
printJson(output);
return;
}
// ── llm output ─────────────────────────────────────────
if (opts.format === "llm") {
for (const line of renderTracePathLlm(fromTarget, toTarget, relKind, pathNodes, noPathMessage, pathHint)) console.log(line);
return;
}
// ── Text output ────────────────────────────────────────
renderResolvedHeader(fromTarget.kind, fromTarget.name);
renderSection("Trace");
renderKeyValue("From", fromTarget.name);
renderKeyValue("To", toTarget.name);
renderKeyValue("Kind", cap(relKind));
if (pathNodes.length === 0) {
console.log(`\n${noPathMessage}`);
if (pathHint) console.log(chalk.dim(` ${pathHint.message}`));
return;
}
renderSection("Route");
for (let i = 0; i < pathNodes.length; i++) {
const n = pathNodes[i];
const kindStr = colorizeKind(n.kind ?? "");
if (i === 0) {
console.log(` ${kindStr} ${n.name}`);
} else if (n.via) {
const arrow = n.reversed ? `<--${n.via}--` : `--${n.via}-->`;
console.log(` ${chalk.dim(arrow)} ${kindStr} ${n.name}`);
} else {
console.log(` ${chalk.dim("→")} ${kindStr} ${n.name}`);
}
}
renderSection("Summary");
renderKeyValue("Path length", String(pathNodes.length));
return;
}
// ── Directional mode ────────────────────────────────────────
const resolvedTarget = await resolveFileOrReport(client, symbol, resolveOpts, opts.format);
if (!resolvedTarget) return;
let target: ResolvedEntity = resolvedTarget;
const predicates = kindToPredicates(opts.kind);
const relKind = opts.kind ?? "mixed";
// Determine direction(s)
const doUpstream = opts.upstream === true;
const doDownstream = opts.downstream === true;
const doBoth = !doUpstream && !doDownstream;
const direction = doBoth ? "both" : doUpstream ? "upstream" : "downstream";
target = await pickTraceTarget(client, symbol, target, {
direction,
predicates,
pick: opts.pick,
path: opts.path,
});
// upstream = "in" (who depends on this — same as depends)
// downstream = "out" (what this depends on — inverse of depends)
// ── Both: run up + down in parallel ────────────────────────
if (doBoth) {
// One limiter for both walks, so the in-flight bound is per command.
const limiter = createLimiter(EXPAND_CONCURRENCY);
const [upResult, downResult] = await Promise.all([
buildTraceTree(client, target.id, { direction: "in", predicates, maxDepth, maxNodes, limiter }),
buildTraceTree(client, target.id, { direction: "out", predicates, maxDepth, maxNodes, limiter }),
]);
// ── JSON ──────────────────────────────────────────────
if (opts.format === "json") {
const output: Record<string, unknown> = {
mode: "directional",
target: { name: target.name, kind: target.kind, path: relativePath(target.path) },
direction: "both",
kind: relKind,
depth: maxDepth,
// Per direction, in the same summary fields single-direction
// output uses, so a caller can see which side hit which bound.
upstream: {
tree: upResult.tree.map(compactTreeNode),
summary: traceSummary(upResult),
},
downstream: {
tree: downResult.tree.map(compactTreeNode),
summary: traceSummary(downResult),
},
};
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, maxNodes)) console.log(line);
return;
}
// ── Text ──────────────────────────────────────────────
renderResolvedHeader(target.kind, target.name);
renderSection("Trace");
renderKeyValue("Direction", "Both");
renderKeyValue("Kind", cap(relKind));
// Upstream section (in edges — who depends on this)
renderSection("Upstream");
console.log(` ${target.name}`);
const upNameCounts = new Map<string, number>();
collectAllNames(upResult.tree, upNameCounts);
const upDisambiguate = new Set([...upNameCounts.entries()].filter(([, n]) => n > 1).map(([k]) => k));
if (upResult.tree.length === 0) {
console.log(chalk.dim(" (none)"));
} else {
for (const line of renderTraceTree(upResult.tree, [], upDisambiguate)) {
console.log(` ${line}`);
}
}
// Downstream section (out edges — what this depends on)
renderSection("Downstream");
console.log(` ${target.name}`);
const downNameCounts = new Map<string, number>();
collectAllNames(downResult.tree, downNameCounts);
const downDisambiguate = new Set([...downNameCounts.entries()].filter(([, n]) => n > 1).map(([k]) => k));
if (downResult.tree.length === 0) {
console.log(chalk.dim(" (none)"));
} else {
for (const line of renderTraceTree(downResult.tree, [], downDisambiguate)) {
console.log(` ${line}`);
}
}
const totalNodes = upResult.nodesVisited + downResult.nodesVisited;
const maxD = Math.max(upResult.maxDepthReached, downResult.maxDepthReached);
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, depthLimited, nodesVisited, maxDepthReached } = doUpstream
? await buildTraceTree(client, target.id, { direction: "in", predicates, maxDepth, maxNodes })
: await buildTraceTree(client, target.id, { direction: "out", predicates, maxDepth, maxNodes });
// ── JSON ────────────────────────────────────────────────────
if (opts.format === "json") {
const output: Record<string, unknown> = {
mode: "directional",
target: { name: target.name, kind: target.kind, path: relativePath(target.path) },
direction,
kind: relKind,
depth: maxDepth,
tree: tree.map(compactTreeNode),
summary: traceSummary({ nodesVisited, maxDepthReached, truncated, depthLimited }),
};
if (tree.length === 0) {
output.diagnostics = [
{ code: "no_edges", message: `No ${direction} ${relKind} found for ${target.name}.` },
];
}
if (truncated || depthLimited) {
const diags = (output.diagnostics as unknown[]) ?? [];
(diags as unknown[]).push({
code: truncated ? "truncated" : "depth_limited",
message: traversalHint(maxDepth, maxNodes, { truncated, depthLimited }),
});
output.diagnostics = diags;
}
printJson(output);
return;
}
// ── llm ──────────────────────────────────────────────────────
if (opts.format === "llm") {
for (const line of renderTraceSingleLlm(target, relKind, direction, maxDepth, tree, truncated, nodesVisited, maxDepthReached, maxNodes, depthLimited)) console.log(line);
return;
}
// ── Text ────────────────────────────────────────────────────
renderResolvedHeader(target.kind, target.name);
renderSection("Trace");
renderKeyValue("Direction", cap(direction));
renderKeyValue("Kind", cap(relKind));
if (tree.length === 0) {
const relDir = doUpstream ? "upstream" : "downstream";
console.log(`\nNo ${relDir} ${relKind} found for ${chalk.bold(target.name)}.`);
return;
}
renderSection("Path");
console.log(` ${target.name}`);
const singleNameCounts = new Map<string, number>();
collectAllNames(tree, singleNameCounts);
const singleDisambiguate = new Set([...singleNameCounts.entries()].filter(([, n]) => n > 1).map(([k]) => k));
for (const line of renderTraceTree(tree, [], singleDisambiguate)) {
console.log(` ${line}`);
}
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})`);
},
);
}