Skip to content

armgit / Ix

Public Imported from GitHub
0

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

feat(cli): Tier 2 --format llm renderers (#206) (#233)

Joseph Mikhail19db830d6cc4
diff --git a/docs/llm-format.md b/docs/llm-format.md
index 4ecee668..09197462 100644
--- a/docs/llm-format.md
+++ b/docs/llm-format.md
@@ -91,8 +91,10 @@ error code=unknown_target message="No entity named 'IngestionService' found" sug
## Status
-Renderers shipped: `stats`, `smells`, `subsystems`, `map`, `impact`,
-`overview`. Remaining commands accept `--format llm` and route to `text` until
-their renderers land (tracked on ix-infrastructure/Ix#206). Programmatic
+Renderers shipped: Tier 1 (`map`, `subsystems`, `impact`, `smells`,
+`overview`) plus `stats`; Tier 2 (`inventory`, `rank`, `depends`, `trace`,
+`contains`, `callers`, `callees`, `imports`, `imported-by`). Remaining commands
+accept `--format llm` and route to `text` until their renderers land (tracked
+on ix-infrastructure/Ix#206). Programmatic
consumers that need to parse output should continue to use `--format json`; the
`llm` format is optimized for being read by a model, not parsed.
diff --git a/ix-cli/src/cli/__tests__/llm-tier2.test.ts b/ix-cli/src/cli/__tests__/llm-tier2.test.ts
new file mode 100644
index 00000000..ac2ef357
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/llm-tier2.test.ts
@@ -0,0 +1,107 @@
+import { describe, it, expect } from "vitest";
+import { renderEdgeResultsLlm } from "../format.js";
+import { renderInventoryLlm } from "../commands/inventory.js";
+import { renderRankLlm } from "../commands/rank.js";
+import { renderDependsLlm, type DependencyNode } from "../commands/depends.js";
+import { renderTracePathLlm, renderTraceBothLlm, renderTraceSingleLlm } from "../commands/trace.js";
+
+describe("renderEdgeResultsLlm", () => {
+ it("emits a relation header and ref rows, marking unresolved targets", () => {
+ const nodes = [
+ { id: "abcdef1234567890", name: "handleLogin", kind: "method", provenance: { source_uri: "src/a.ts" } },
+ { id: "deadbeef00000000", name: "", kind: "method" },
+ ];
+ const lines = renderEdgeResultsLlm(nodes, "callers", "verify_token", "graph");
+ expect(lines[0]).toBe("callers target=verify_token total=2 resolved=1 unresolved=1");
+ expect(lines[1]).toBe("ref name=handleLogin kind=method id=abcdef12 path=src/a.ts");
+ expect(lines[2]).toBe("ref kind=method id=deadbeef resolved=false");
+ });
+
+ it("emits a no_edges diagnostic when empty", () => {
+ const lines = renderEdgeResultsLlm([], "callees", "foo", "graph");
+ expect(lines[0]).toBe("callees target=foo total=0 resolved=0");
+ expect(lines[1]).toBe('diagnostic code=no_edges message="No callees edges found."');
+ });
+});
+
+describe("renderInventoryLlm", () => {
+ it("groups names per file and lists pathless entities as items", () => {
+ const nodes = [
+ { name: "Foo", kind: "class", provenance: { source_uri: "src/a.ts" } },
+ { name: "Bar", kind: "class", provenance: { source_uri: "src/a.ts" } },
+ { name: "Baz", kind: "class" },
+ ];
+ const lines = renderInventoryLlm("class", "auth", nodes);
+ expect(lines).toEqual([
+ "inventory kind=class scope=auth total=3",
+ "file path=src/a.ts items=Foo,Bar",
+ "item name=Baz kind=class",
+ ]);
+ });
+});
+
+describe("renderRankLlm", () => {
+ it("emits a header then one entity row per result (rank = order)", () => {
+ const lines = renderRankLlm("dependents", "class", null, [
+ { name: "Foo", kind: "class", score: 42 },
+ { name: "Bar", kind: "class", score: 10 },
+ ], 100, []);
+ expect(lines).toEqual([
+ "rank metric=dependents kind=class evaluated=100 returned=2",
+ "entity name=Foo kind=class score=42",
+ "entity name=Bar kind=class score=10",
+ ]);
+ });
+});
+
+describe("renderDependsLlm", () => {
+ it("flattens the tree into dep rows with parent= pointing at the target", () => {
+ const tree: DependencyNode[] = [{
+ id: "child1aa", name: "handleLogin", kind: "method", resolved: true,
+ relation: "called_by", sourceEdge: "CALLS", children: [],
+ }];
+ const lines = renderDependsLlm({ id: "root1234", name: "verify", kind: "function" }, tree, false, 1, 1);
+ expect(lines[0]).toBe("depends target=verify kind=function target_id=root1234 semantics=downstream_dependents nodes=1 depth=1");
+ expect(lines[1]).toBe("dep name=handleLogin kind=method id=child1aa parent=root1234 rel=called_by");
+ });
+});
+
+describe("trace llm renderers", () => {
+ const node = (over: any) => ({ id: "n1aaaaaa", name: "bar", kind: "method", resolved: true, children: [], ...over });
+
+ it("renderTracePathLlm emits a path with step rows", () => {
+ const lines = renderTracePathLlm({ name: "A", kind: "function" }, { name: "B", kind: "function" }, "mixed", [
+ { id: "a", name: "A", kind: "function" }, { id: "b", name: "B", kind: "function" },
+ ]);
+ expect(lines).toEqual([
+ "trace mode=path from=A to=B kind=mixed length=2",
+ "step name=A kind=function",
+ "step name=B kind=function",
+ ]);
+ });
+
+ it("renderTracePathLlm emits a no_path diagnostic when empty", () => {
+ const lines = renderTracePathLlm({ name: "A", kind: "function" }, { name: "B", kind: "function" }, "mixed", []);
+ expect(lines[1]).toBe('diagnostic code=no_path message="No route found from A to B."');
+ });
+
+ it("renderTraceSingleLlm flattens with parent= and drops infinite depth", () => {
+ const lines = renderTraceSingleLlm(
+ { id: "root1234", name: "foo", kind: "function" }, "mixed", "upstream", Infinity,
+ [node({})], false, 1, 1, Infinity,
+ );
+ expect(lines[0]).toBe("trace mode=directional target=foo kind=mixed direction=upstream target_id=root1234 nodes=1 max_depth=1");
+ expect(lines[0]).not.toContain("depth=Infinity");
+ expect(lines[1]).toBe("node name=bar kind=method id=n1aaaaaa parent=root1234");
+ });
+
+ it("renderTraceBothLlm emits up/down record streams with per-direction counts", () => {
+ 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]).toBe("trace mode=directional target=foo kind=mixed direction=both target_id=root1234 up_nodes=1 up_depth=1 down_nodes=0 down_depth=0");
+ expect(lines[1]).toBe("up name=bar kind=method id=n1aaaaaa parent=root1234");
+ });
+});
diff --git a/ix-cli/src/cli/commands/callers.ts b/ix-cli/src/cli/commands/callers.ts
index 5832be80..ea39aa50 100644
--- a/ix-cli/src/cli/commands/callers.ts
+++ b/ix-cli/src/cli/commands/callers.ts
@@ -7,6 +7,12 @@ import { getEndpoint, resolveWorkspaceRoot } from "../config.js";
import { formatEdgeResults, relativePath } from "../format.js";
import { resolveFileOrEntity, printResolved } from "../resolve.js";
import { stderr } from "../stderr.js";
+import { llmLine, llmError } from "../llm.js";
+
+/** Emit a structured llm error for a failed resolution, or nothing for other formats. */
+function llmUnresolved(format: string, symbol: string): void {
+ if (format === "llm") console.log(llmError("unresolved_target", `No entity resolved for "${symbol}".`));
+}
const execFileAsync = promisify(execFile);
@@ -24,8 +30,8 @@ export function registerCallersCommand(program: Command): void {
const limit = parseInt(opts.limit, 10);
const resolveOpts = { kind: opts.kind, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
const target = await resolveFileOrEntity(client, symbol, resolveOpts);
- if (!target) return;
- if (opts.format !== "json") printResolved(target);
+ if (!target) { llmUnresolved(opts.format, symbol); return; }
+ if (opts.format === "text") printResolved(target);
// Use expand by entity ID to avoid aggregating results across all same-named entities
const result = await client.expand(target.id, {
direction: "in",
@@ -64,6 +70,20 @@ export function registerCallersCommand(program: Command): void {
const textResults = allTextResults.slice(0, 10);
if (textResults.length > 0) {
+ if (opts.format === "llm") {
+ console.log(llmLine("callers", [
+ ["target", target.name], ["source", "text"],
+ ["total", textResults.length], ["candidates", candidatesFound],
+ ]));
+ console.log(llmLine("diagnostic", [
+ ["code", "text_fallback_used"],
+ ["message", "No graph-backed CALLS/REFERENCES edges; showing text matches."],
+ ]));
+ for (const r of textResults) {
+ console.log(llmLine("ref", [["path", r.path], ["line", r.line], ["snippet", r.attrs?.snippet ?? ""]]));
+ }
+ return;
+ }
if (opts.format === "json") {
console.log(JSON.stringify({
results: textResults,
@@ -113,8 +133,8 @@ export function registerCallersCommand(program: Command): void {
const calleeLimit = parseInt(opts.limit, 10);
const resolveOpts = { kind: opts.kind, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
const target = await resolveFileOrEntity(client, symbol, resolveOpts);
- if (!target) return;
- if (opts.format !== "json") printResolved(target);
+ if (!target) { llmUnresolved(opts.format, symbol); return; }
+ if (opts.format === "text") printResolved(target);
// Use expand by entity ID to avoid aggregating results across all same-named entities
const result = await client.expand(target.id, {
direction: "out",
diff --git a/ix-cli/src/cli/commands/contains.ts b/ix-cli/src/cli/commands/contains.ts
index 18a6a99f..de9e1f3e 100644
--- a/ix-cli/src/cli/commands/contains.ts
+++ b/ix-cli/src/cli/commands/contains.ts
@@ -3,6 +3,7 @@ import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
import { formatEdgeResults } from "../format.js";
import { resolveFileOrEntity, printResolved } from "../resolve.js";
+import { llmError } from "../llm.js";
export function registerContainsCommand(program: Command): void {
program
@@ -19,8 +20,11 @@ export function registerContainsCommand(program: Command): void {
const limit = parseInt(opts.limit, 10);
const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
const target = await resolveFileOrEntity(client, symbol, resolveOpts);
- if (!target) return;
- if (opts.format !== "json") printResolved(target);
+ if (!target) {
+ if (opts.format === "llm") console.log(llmError("unresolved_target", `No entity resolved for "${symbol}".`));
+ return;
+ }
+ if (opts.format === "text") printResolved(target);
const result = await client.expand(target.id, { direction: "out", predicates: ["CONTAINS"] });
const limited = result.nodes.slice(0, limit);
formatEdgeResults(limited, "contains", target.name, opts.format, target, "graph");
diff --git a/ix-cli/src/cli/commands/depends.ts b/ix-cli/src/cli/commands/depends.ts
index 97c956a4..a58f4f3a 100644
--- a/ix-cli/src/cli/commands/depends.ts
+++ b/ix-cli/src/cli/commands/depends.ts
@@ -5,6 +5,7 @@ import { getEndpoint } from "../config.js";
import { resolveFileOrEntity, printResolved, isRawId } from "../resolve.js";
import { stderr } from "../stderr.js";
import { compactTreeNode, relativePath } from "../format.js";
+import { llmLine, llmError } from "../llm.js";
// ── Tree types ──────────────────────────────────────────────────────
@@ -145,6 +146,44 @@ function renderTree(children: DependencyNode[], prefix: string, isLast: boolean[
return lines;
}
+/**
+ * Render the dependency tree as flat llm records: a header line then one `dep`
+ * 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.
+ */
+export function renderDependsLlm(
+ target: { id: string; name: string; kind: string; path?: string },
+ tree: DependencyNode[], truncated: boolean, nodesVisited: number, maxDepthReached: number,
+): string[] {
+ const lines = [llmLine("depends", [
+ ["target", target.name],
+ ["kind", target.kind],
+ ["target_id", target.id?.slice(0, 8)],
+ ["semantics", "downstream_dependents"],
+ ["nodes", nodesVisited],
+ ["depth", maxDepthReached],
+ ["truncated", truncated ? true : undefined],
+ ])];
+ if (tree.length === 0) {
+ lines.push(llmLine("diagnostic", [["code", "no_edges"], ["message", "No upstream dependents found."]]));
+ }
+ const emit = (node: DependencyNode, parentId: string): void => {
+ lines.push(llmLine("dep", [
+ ["name", node.resolved ? node.name : undefined],
+ ["kind", node.kind],
+ ["id", node.id?.slice(0, 8)],
+ ["parent", parentId?.slice(0, 8)],
+ ["rel", node.relation],
+ ["path", relativePath(node.path)],
+ ["cycle", node.cycle ? true : undefined],
+ ["resolved", node.resolved ? undefined : false],
+ ]));
+ for (const child of node.children) emit(child, node.id);
+ };
+ for (const node of tree) emit(node, target.id);
+ return lines;
+}
+
// ── CLI command ─────────────────────────────────────────────────────
export function registerDependsCommand(program: Command): void {
@@ -185,7 +224,10 @@ export function registerDependsCommand(program: Command): void {
testsOnly: opts.testsOnly,
};
const target = await resolveFileOrEntity(client, symbol, resolveOpts);
- if (!target) return;
+ if (!target) {
+ if (opts.format === "llm") console.log(llmError("unresolved_target", `No entity resolved for "${symbol}".`));
+ return;
+ }
const maxDepth = opts.depth ? parseInt(opts.depth, 10) : DEFAULT_MAX_DEPTH;
const maxNodes = opts.cap ? parseInt(opts.cap, 10) : MAX_NODES;
@@ -222,6 +264,12 @@ export function registerDependsCommand(program: Command): void {
return;
}
+ // ── llm output ───────────────────────────────────────────────
+ if (opts.format === "llm") {
+ for (const line of renderDependsLlm(target, tree, truncated, nodesVisited, maxDepthReached)) console.log(line);
+ return;
+ }
+
// ── Text output ──────────────────────────────────────────────
printResolved(target);
diff --git a/ix-cli/src/cli/commands/imports.ts b/ix-cli/src/cli/commands/imports.ts
index 8acff18c..d2474fd0 100644
--- a/ix-cli/src/cli/commands/imports.ts
+++ b/ix-cli/src/cli/commands/imports.ts
@@ -3,6 +3,11 @@ import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
import { formatEdgeResults } from "../format.js";
import { resolveFileOrEntity, printResolved } from "../resolve.js";
+import { llmError } from "../llm.js";
+
+function llmUnresolved(format: string, symbol: string): void {
+ if (format === "llm") console.log(llmError("unresolved_target", `No entity resolved for "${symbol}".`));
+}
export function registerImportsCommand(program: Command): void {
program
@@ -18,8 +23,8 @@ export function registerImportsCommand(program: Command): void {
const limit = parseInt(opts.limit, 10);
const resolveOpts = { kind: opts.kind, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
const target = await resolveFileOrEntity(client, symbol, resolveOpts);
- if (!target) return;
- if (opts.format !== "json") printResolved(target);
+ if (!target) { llmUnresolved(opts.format, symbol); return; }
+ if (opts.format === "text") printResolved(target);
const result = await client.expand(target.id, { direction: "out", predicates: ["IMPORTS"] });
formatEdgeResults(result.nodes.slice(0, limit), "imports", target.name, opts.format, target, "graph");
});
@@ -37,8 +42,8 @@ export function registerImportsCommand(program: Command): void {
const limit = parseInt(opts.limit, 10);
const resolveOpts = { kind: opts.kind, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
const target = await resolveFileOrEntity(client, symbol, resolveOpts);
- if (!target) return;
- if (opts.format !== "json") printResolved(target);
+ if (!target) { llmUnresolved(opts.format, symbol); return; }
+ if (opts.format === "text") printResolved(target);
const result = await client.expand(target.id, { direction: "in", predicates: ["IMPORTS"] });
formatEdgeResults(result.nodes.slice(0, limit), "imported-by", target.name, opts.format, target, "graph");
});
diff --git a/ix-cli/src/cli/commands/inventory.ts b/ix-cli/src/cli/commands/inventory.ts
index 72bfc7e0..64f57181 100644
--- a/ix-cli/src/cli/commands/inventory.ts
+++ b/ix-cli/src/cli/commands/inventory.ts
@@ -4,6 +4,38 @@ import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
import { resolveWorkspaceId } from "../bootstrap.js";
import { relativePath } from "../format.js";
+import { llmLine } from "../llm.js";
+
+/**
+ * Render `ix inventory` as llm records: a header line then one `file` row per
+ * source file with its entity names comma-joined (entities without a path
+ * become standalone `item` rows). Grouping mirrors the json renderer to avoid
+ * repeating the path on every entity.
+ */
+export function renderInventoryLlm(kind: string, scope: string | null, nodes: any[]): string[] {
+ const byFile = new Map<string, string[]>();
+ const ungrouped: Array<{ name: string; kind: string }> = [];
+ for (const n of nodes) {
+ const name = String(n.name || n.attrs?.name || "(unnamed)");
+ const rawPath = (n as any).provenance?.source_uri ?? n.provenance?.sourceUri ?? n.attrs?.path;
+ const path = relativePath(rawPath);
+ if (path) {
+ const names = byFile.get(path) ?? [];
+ names.push(name);
+ byFile.set(path, names);
+ } else {
+ ungrouped.push({ name, kind: String(n.kind) });
+ }
+ }
+ const lines = [llmLine("inventory", [["kind", kind], ["scope", scope ?? undefined], ["total", nodes.length]])];
+ for (const [path, names] of byFile) {
+ lines.push(llmLine("file", [["path", path], ["items", names.join(",")]]));
+ }
+ for (const u of ungrouped) {
+ lines.push(llmLine("item", [["name", u.name], ["kind", u.kind]]));
+ }
+ return lines;
+}
export function registerInventoryCommand(program: Command): void {
program
@@ -77,6 +109,11 @@ Examples:
return;
}
+ if (opts.format === "llm") {
+ for (const line of renderInventoryLlm(opts.kind, scope, nodes)) console.log(line);
+ return;
+ }
+
if (nodes.length === 0) {
console.log(`No ${opts.kind} entities found${scope ? ` in ${scope}` : ""}.`);
return;
diff --git a/ix-cli/src/cli/commands/rank.ts b/ix-cli/src/cli/commands/rank.ts
index 9d47ed31..0813d6ab 100644
--- a/ix-cli/src/cli/commands/rank.ts
+++ b/ix-cli/src/cli/commands/rank.ts
@@ -3,9 +3,27 @@ import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
import { resolveWorkspaceId } from "../bootstrap.js";
+import { llmLine } from "../llm.js";
type Metric = "dependents" | "callers" | "importers" | "members";
+/** Render `ix rank` as llm records: a header line then one `entity` row per result (rank = line order). */
+export function renderRankLlm(
+ metric: string, kind: string, scope: string | null,
+ results: Array<{ name: string; kind: string; score: number }>,
+ evaluated: number, diagnostics: string[],
+): string[] {
+ const lines = [llmLine("rank", [
+ ["metric", metric], ["kind", kind], ["scope", scope ?? undefined],
+ ["evaluated", evaluated], ["returned", results.length],
+ ])];
+ for (const d of diagnostics) lines.push(llmLine("diagnostic", [["message", d]]));
+ for (const r of results) {
+ lines.push(llmLine("entity", [["name", r.name], ["kind", r.kind], ["score", r.score]]));
+ }
+ return lines;
+}
+
const METRIC_CONFIG: Record<Metric, { direction: string; predicates: string[] }> = {
dependents: { direction: "in", predicates: ["CALLS", "IMPORTS", "REFERENCES"] },
callers: { direction: "in", predicates: ["CALLS", "REFERENCES"] },
@@ -157,7 +175,9 @@ export function registerRankCommand(program: Command): void {
const allNodes = await client.listByKind(opts.kind, { limit: 2000, workspaceId: resolveWorkspaceId() });
if (allNodes.length === 0) {
- if (isJson) {
+ if (opts.format === "llm") {
+ for (const line of renderRankLlm(metric, opts.kind, opts.path ?? null, [], 0, ["No entities found for the given kind."])) console.log(line);
+ } else if (isJson) {
console.log(JSON.stringify({
metric,
kind: opts.kind,
@@ -185,7 +205,9 @@ export function registerRankCommand(program: Command): void {
opts.excludePath ? `exclude-path "${opts.excludePath}"` : null,
excludeKinds.length > 0 ? `exclude-kind "${excludeKinds.join(",")}"` : null,
].filter(Boolean).join(", ");
- if (isJson) {
+ if (opts.format === "llm") {
+ for (const line of renderRankLlm(metric, opts.kind, opts.path ?? null, [], 0, [`No entities matched filters: ${filterDesc}.`])) console.log(line);
+ } else if (isJson) {
console.log(JSON.stringify({
metric,
kind: opts.kind,
@@ -209,7 +231,9 @@ export function registerRankCommand(program: Command): void {
const results = scored.slice(0, topN);
// 7. Output
- if (isJson) {
+ if (opts.format === "llm") {
+ for (const line of renderRankLlm(metric, opts.kind, opts.path ?? null, results.map(r => ({ name: r.name, kind: r.kind, score: r.score })), candidates.length, diagnostics)) console.log(line);
+ } else if (isJson) {
console.log(JSON.stringify({
metric,
kind: opts.kind,
diff --git a/ix-cli/src/cli/commands/trace.ts b/ix-cli/src/cli/commands/trace.ts
index b29ab4ee..17c9c244 100644
--- a/ix-cli/src/cli/commands/trace.ts
+++ b/ix-cli/src/cli/commands/trace.ts
@@ -7,6 +7,7 @@ import type { ResolvedEntity } from "../resolve.js";
import { stderr } from "../stderr.js";
import { renderSection, renderKeyValue, renderResolvedHeader, colorizeKind } from "../ui.js";
import { compactTreeNode, relativePath } from "../format.js";
+import { llmLine, llmError, type LlmValue } from "../llm.js";
// ── Types ────────────────────────────────────────────────────────────
@@ -319,6 +320,79 @@ function renderTraceTree(
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", node.id?.slice(0, 8)],
+ ["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[],
+): 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}.`]]));
+ return lines;
+ }
+ for (const n of pathNodes) lines.push(llmLine("step", [["name", n.name], ["kind", n.kind]]));
+ return lines;
+}
+
+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 },
+): string[] {
+ const lines = [llmLine("trace", [
+ ["mode", "directional"], ["target", target.name], ["kind", relKind],
+ ["direction", "both"], ["depth", finiteDepth(maxDepth)], ["target_id", target.id?.slice(0, 8)],
+ ["up_nodes", up.nodesVisited], ["up_depth", up.maxDepthReached],
+ ["down_nodes", down.nodesVisited], ["down_depth", down.maxDepthReached],
+ ])];
+ 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,
+): 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],
+ ])];
+ 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", `Traversal truncated (depth: ${maxDepth}, node cap: ${maxNodes}).`]]));
+ }
+ lines.push(...traceNodesLlm("node", tree, target.id));
+ return lines;
+}
// ── Command ──────────────────────────────────────────────────────────
@@ -395,7 +469,10 @@ export function registerTraceCommand(program: Command): void {
resolveFileOrEntity(client, symbol, resolveOpts),
resolveFileOrEntity(client, opts.to, toResolveOpts),
]);
- if (!fromTarget || !toTarget) return;
+ if (!fromTarget || !toTarget) {
+ if (opts.format === "llm") console.log(llmError("unresolved_target", `Could not resolve ${!fromTarget ? symbol : opts.to}.`));
+ return;
+ }
const relKind = opts.kind ?? "mixed";
const predicates = kindToPredicates(opts.kind);
@@ -434,6 +511,12 @@ export function registerTraceCommand(program: Command): void {
return;
}
+ // ── llm output ─────────────────────────────────────────
+ if (opts.format === "llm") {
+ for (const line of renderTracePathLlm(fromTarget, toTarget, relKind, pathNodes)) console.log(line);
+ return;
+ }
+
// ── Text output ────────────────────────────────────────
renderResolvedHeader(fromTarget.kind, fromTarget.name);
renderSection("Trace");
@@ -464,7 +547,10 @@ export function registerTraceCommand(program: Command): void {
// ── Directional mode ────────────────────────────────────────
const resolvedTarget = await resolveFileOrEntity(client, symbol, resolveOpts);
- if (!resolvedTarget) return;
+ if (!resolvedTarget) {
+ if (opts.format === "llm") console.log(llmError("unresolved_target", `No entity resolved for "${symbol}".`));
+ return;
+ }
let target: ResolvedEntity = resolvedTarget;
const predicates = kindToPredicates(opts.kind);
@@ -518,6 +604,12 @@ export function registerTraceCommand(program: Command): void {
return;
}
+ // ── llm ───────────────────────────────────────────────
+ if (opts.format === "llm") {
+ for (const line of renderTraceBothLlm(target, relKind, maxDepth, upResult, downResult)) console.log(line);
+ return;
+ }
+
// ── Text ──────────────────────────────────────────────
renderResolvedHeader(target.kind, target.name);
renderSection("Trace");
@@ -592,6 +684,12 @@ export function registerTraceCommand(program: Command): void {
return;
}
+ // ── llm ──────────────────────────────────────────────────────
+ if (opts.format === "llm") {
+ for (const line of renderTraceSingleLlm(target, relKind, direction, maxDepth, tree, truncated, nodesVisited, maxDepthReached, maxNodes)) console.log(line);
+ return;
+ }
+
// ── Text ────────────────────────────────────────────────────
renderResolvedHeader(target.kind, target.name);
renderSection("Trace");
diff --git a/ix-cli/src/cli/format.ts b/ix-cli/src/cli/format.ts
index e6743f74..576ab1d5 100644
--- a/ix-cli/src/cli/format.ts
+++ b/ix-cli/src/cli/format.ts
@@ -1,5 +1,6 @@
import chalk from "chalk";
import { resolve } from "path";
+import { llmLine } from "./llm.js";
export type ResultSource = "graph" | "text" | "graph+text" | "heuristic";
@@ -401,6 +402,49 @@ export function formatLocateResults(results: LocateResult[], format: string): vo
}
}
+/**
+ * Render edge-query results (callers/callees/contains/imports/imported-by) as
+ * llm records: a header line keyed by the relation, optional diagnostic lines,
+ * then one `ref` row per related entity. Unresolved targets carry resolved=false.
+ */
+export function renderEdgeResultsLlm(
+ nodes: any[], relation: string, symbol: string,
+ source?: ResultSource, diagnostics?: Diagnostic[]
+): string[] {
+ const isRawId = (s: string) =>
+ /^[0-9a-f]{8}-[0-9a-f]{4}-/i.test(s) || /^[0-9a-f]{32,}$/i.test(s);
+ const refs = nodes.map((n: any) => {
+ const name = n.name || n.attrs?.name || "";
+ return {
+ resolved: !!name && !isRawId(name),
+ name,
+ kind: n.kind ?? undefined,
+ id: n.id ?? undefined,
+ path: relativePath(n.provenance?.source_uri ?? n.provenance?.sourceUri ?? n.attrs?.path ?? undefined),
+ };
+ });
+ const unresolved = refs.filter((r) => !r.resolved).length;
+ const lines = [llmLine(relation, [
+ ["target", symbol],
+ ["total", refs.length],
+ ["resolved", refs.length - unresolved],
+ ["unresolved", unresolved > 0 ? unresolved : undefined],
+ ["source", source && source !== "graph" ? source : undefined],
+ ])];
+ if (refs.length === 0 && (!diagnostics || diagnostics.length === 0)) {
+ lines.push(llmLine("diagnostic", [["code", "no_edges"], ["message", `No ${relation} edges found.`]]));
+ }
+ for (const d of diagnostics ?? []) {
+ lines.push(llmLine("diagnostic", [["code", d.code], ["message", d.message]]));
+ }
+ for (const ref of refs) {
+ lines.push(ref.resolved
+ ? llmLine("ref", [["name", ref.name], ["kind", ref.kind], ["id", ref.id?.slice(0, 8)], ["path", ref.path]])
+ : llmLine("ref", [["kind", ref.kind], ["id", ref.id?.slice(0, 8)], ["resolved", false]]));
+ }
+ return lines;
+}
+
export function formatEdgeResults(
nodes: any[], relation: string, symbol: string, format: string,
resolvedTarget?: { id: string; kind: string; name: string; resolutionMode?: string },
@@ -411,6 +455,13 @@ export function formatEdgeResults(
const isRawId = (s: string) =>
/^[0-9a-f]{8}-[0-9a-f]{4}-/i.test(s) || /^[0-9a-f]{32,}$/i.test(s);
+ if (format === "llm") {
+ for (const line of renderEdgeResultsLlm(nodes, relation, symbol, source, diagnostics)) {
+ console.log(line);
+ }
+ return;
+ }
+
if (format === "json") {
const results = nodes.map((n: any) => {
const name = n.name || n.attrs?.name || "";