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
feat(cli): add `--format llm` token-optimized output (PR 1, #206) (#232)
Joseph Mikhailfe27c9d2432d
diff --git a/docs/llm-format.md b/docs/llm-format.mdnew file mode 100644index 00000000..4ecee668--- /dev/null+++ b/docs/llm-format.md@@ -0,0 +1,98 @@+# `--format llm` output convention++`--format llm` is a token-minimal, newline-delimited output mode for AI coding+agents (ix-claude-plugin, Cursor, Codex, ...) that call `ix` many times per+session. It strips the decorative whitespace of `--format text` and the+structural overhead of `--format json`, typically cutting response bytes 2-4x+versus `json` on tree- and table-shaped output.++It is accepted on every command that accepts `--format`. Commands with a+hand-written renderer emit compact records (see below); the rest route+`--format llm` to whichever existing format is most compact (usually `text`),+so consumers can pass the flag unconditionally without a per-command lookup.++## Wire format++- **One record per line.** Newline-delimited, no nesting.+- **Scalars:** `key=value` pairs separated by a single space.+- **Tabular rows:** a leading `record-kind` token, then `key=value` pairs:+ `region id=cli kind=subsystem label="Cli / Client" level=2 files=87`.+- **No decorative whitespace, separators, or headers.**+- **Omitted fields:** null, undefined, and empty values are dropped. Zeros and+ other defaults are dropped where they carry no signal.+- **Quoting:** a value containing a space, `=`, `"`, `\`, or a control+ character is wrapped in double quotes. Inside quotes, `"` and `\` are+ backslash-escaped and newline / carriage-return / tab are encoded as `\n` /+ `\r` / `\t`, so a record never spans more than one line.+- **Errors:** a uniform `error code=<slug> message="..."` line in the same+ format as data lines; the process still exits non-zero.++## Hierarchies++Hierarchical data (e.g. `ix map` regions) is emitted flat, one record per line,+with an explicit `parent=<id>` field. Trees are re-treeable on the consumer+side from `id` / `parent=` alone. This keeps the "no significant whitespace"+invariant and survives pipe truncation.++```+region id=root kind=system label="Cli"+region id=cli kind=subsystem label="Client" parent=root+region id=srv kind=subsystem label="Server" parent=root+```++## Examples++`ix stats`:++```+nodes total=98979 method=49180 module=38199 class=6833 file=3285+edges total=354283 CALLS=177418 CONTAINS=57163 IMPORTS=38199+```++`ix subsystems --list`:++```+subsystems count=2+region id=cli-client label="Cli / Client" kind=subsystem level=2 files=87 health=0.62 chunks_per_file=4.1 smells=3 confidence=0.88+region id=ingestion-parsers label="Ingestion / Parsers" kind=subsystem level=2 files=212 health=0.71 confidence=0.74+```++`ix smells`:++```+smells rev=42 count=2 version=smell_v1+smell kind=has_smell.god_module file=Region.scala confidence=0.91 chunks=42 fan_in=18 fan_out=9+smell kind=has_smell.orphan_file file=tmp.py confidence=0.8 connections=0+```++`ix impact <leaf>`:++```+impact target=verify_token kind=function risk=high category=boundary summary="Auth check; 14 call sites at risk"+behavior text="Token validation across the request pipeline"+counts callers=14 callees=3+bucket region="Auth Layer" kind=subsystem count=9+caller name=handleLogin kind=method+```++`ix overview <container>`:++```+overview target=IngestionService kind=class file=src/ingest.ts system_path=Ingestion,Parsers+contains method=12 field=4+item name=parseFile kind=method+```++Error line:++```+error code=unknown_target message="No entity named 'IngestionService' found" suggestions=Ingestion,Service+```++## 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+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__/bootstrap-notice.test.ts b/ix-cli/src/cli/__tests__/bootstrap-notice.test.tsnew file mode 100644index 00000000..55e22d85--- /dev/null+++ b/ix-cli/src/cli/__tests__/bootstrap-notice.test.ts@@ -0,0 +1,30 @@+import { describe, it, expect, vi, afterEach } from "vitest";+import { emitSetupNotice } from "../bootstrap.js";++afterEach(() => vi.restoreAllMocks());++describe("emitSetupNotice", () => {+ it("writes setup notices to stderr, never stdout (keeps machine output clean)", () => {+ const out = vi.spyOn(console, "log").mockImplementation(() => {});+ const err = vi.spyOn(console, "error").mockImplementation(() => {});++ emitSetupNotice(true, true, "my-workspace");++ // The bug this guards: the banner leaked to stdout and corrupted --format json|llm.+ expect(out).not.toHaveBeenCalled();+ expect(err).toHaveBeenCalled();+ const stderrText = err.mock.calls.map((c) => String(c[0])).join("\n");+ expect(stderrText).toContain("Registered workspace");+ expect(stderrText).toContain("my-workspace");+ });++ it("emits nothing when neither config nor workspace was newly created", () => {+ const out = vi.spyOn(console, "log").mockImplementation(() => {});+ const err = vi.spyOn(console, "error").mockImplementation(() => {});++ emitSetupNotice(false, false, "x");++ expect(out).not.toHaveBeenCalled();+ expect(err).not.toHaveBeenCalled();+ });+});diff --git a/ix-cli/src/cli/__tests__/llm-renderers.test.ts b/ix-cli/src/cli/__tests__/llm-renderers.test.tsnew file mode 100644index 00000000..ce538b9e--- /dev/null+++ b/ix-cli/src/cli/__tests__/llm-renderers.test.ts@@ -0,0 +1,200 @@+import { describe, it, expect } from "vitest";+import { renderMapLlm, type MapRegion, type MapResult } from "../commands/map.js";+import { renderSubsystemScoreLlm, renderScopedSubsystemLlm, renderSubsystemErrorLlm } from "../commands/subsystems.js";+import type { SubsystemScore, ScopedSubsystemRegion, ScopedSubsystemResult } from "../explain/subsystem.js";+import { renderStatsLlm } from "../commands/stats.js";+import { renderSmellsRunLlm, renderSmellsListLlm } from "../commands/smells.js";+import { impactHeaderLlm, impactPropagationLlm, impactTailLlm } from "../commands/impact.js";+import { overviewContainerLlm, overviewLeafLlm } from "../commands/overview.js";++function captureLog(fn: () => void): string[] {+ const lines: string[] = [];+ const orig = console.log;+ console.log = (...args: unknown[]) => { lines.push(args.map(String).join(" ")); };+ try { fn(); } finally { console.log = orig; }+ return lines;+}++function region(over: Partial<MapRegion>): MapRegion {+ return {+ id: "r", label: "R", label_kind: "module", level: 1, file_count: 1,+ child_region_count: 0, parent_id: null, cohesion: 0, external_coupling: 0,+ boundary_ratio: 0, confidence: 0, crosscut_score: 0, dominant_signals: [],+ interface_node_count: 0, ...over,+ };+}++describe("renderMapLlm", () => {+ it("emits a summary line then flat region records with parent=", () => {+ const result: MapResult = {+ file_count: 100, region_count: 2, levels: 2, map_rev: 7,+ outcome: "ok", regions: [], hierarchy: [],+ };+ const regions = [+ region({ id: "root", label: "Cli", label_kind: "system", level: 2, file_count: 100, child_region_count: 2, confidence: 0.9 }),+ region({ id: "cli", label: "Cli / Client", label_kind: "subsystem", level: 1, file_count: 87, parent_id: "root", confidence: 0.62, dominant_signals: ["naming", "imports"] }),+ ];+ const lines = captureLog(() => renderMapLlm(result, regions));++ expect(lines[0]).toBe("map files=100 regions=2 levels=2 rev=7 outcome=ok");+ // root: parent_id null is dropped; child_region_count surfaces as children;+ // float metrics (cohesion/coupling) are emitted even at 0 since the value carries signal+ expect(lines[1]).toBe("region id=root kind=system label=Cli level=2 files=100 children=2 cohesion=0 coupling=0 confidence=0.9");+ // child: parent= present, label with spaces is quoted, signals joined by comma+ expect(lines[2]).toBe('region id=cli kind=subsystem label="Cli / Client" level=1 files=87 parent=root cohesion=0 coupling=0 confidence=0.62 signals=naming,imports');+ });++ it("drops zero children and empty signals", () => {+ const result: MapResult = {+ file_count: 1, region_count: 1, levels: 1, map_rev: 1,+ regions: [], hierarchy: [],+ };+ const lines = captureLog(() => renderMapLlm(result, [region({ id: "x", label: "X" })]));+ expect(lines[1]).toBe("region id=x kind=module label=X level=1 files=1 cohesion=0 coupling=0 confidence=0");+ expect(lines[1]).not.toContain("children=");+ expect(lines[1]).not.toContain("signals=");+ expect(lines[1]).not.toContain("parent=");+ });+});++describe("renderSubsystemScoreLlm", () => {+ const base: SubsystemScore = {+ region_id: "cli-client", name: "Cli / Client", level: 2, label_kind: "subsystem",+ file_count: 87, health_score: 0.623, chunk_density: 4.07, smell_rate: 0.1,+ smell_files: 3, total_chunks: 354, confidence: 0.88, inference_version: "v1",+ };++ it("renders a region record with rounded floats and quoted label", () => {+ expect(renderSubsystemScoreLlm(base)).toBe(+ 'region id=cli-client label="Cli / Client" kind=subsystem level=2 files=87 health=0.62 chunks_per_file=4.07 smells=3 confidence=0.88'+ );+ });++ it("drops smells and chunks_per_file when zero (no-signal noise)", () => {+ const line = renderSubsystemScoreLlm({ ...base, smell_files: 0, chunk_density: 0 });+ expect(line).not.toContain("smells=");+ expect(line).not.toContain("chunks_per_file=");+ expect(line).toContain("health=0.62");+ });+});++describe("renderScopedSubsystemLlm", () => {+ function scopedRegion(over: Partial<ScopedSubsystemRegion>): ScopedSubsystemRegion {+ return {+ id: "x", label: "X", level: 1, label_kind: "module", parent_id: null,+ file_count: 1, confidence: 0, is_cross_cutting: false, dominant_signals: [], ...over,+ };+ }+ it("emits target, health, then flat region records with parent=", () => {+ const result: ScopedSubsystemResult = {+ target: scopedRegion({ id: "auth", label: "Auth", label_kind: "subsystem", level: 2, file_count: 42, confidence: 0.8, dominant_signals: ["imports"] }),+ parent: { id: "root", label: "Sys", level: 3, label_kind: "system" },+ summary: { well_defined: 1, moderate: 2, fuzzy: 0, cross_cutting: 1 },+ children: [scopedRegion({ id: "c1", label: "Login", parent_id: "auth", confidence: 0.5, is_cross_cutting: true })],+ hierarchy: scopedRegion({ id: "auth" }),+ };+ const lines = renderScopedSubsystemLlm(result);+ expect(lines[0]).toBe('target id=auth label=Auth kind=subsystem level=2 files=42 confidence=0.8 parent=root signals=imports');+ expect(lines[1]).toBe("health well_defined=1 moderate=2 fuzzy=0 cross_cutting=1");+ expect(lines[2]).toBe("region id=c1 label=Login kind=module level=1 files=1 parent=auth confidence=0.5 cross_cutting=true");+ });+});++describe("renderSubsystemErrorLlm", () => {+ it("renders ambiguous_target with candidate list", () => {+ const line = renderSubsystemErrorLlm({ error: "ambiguous_target", target_query: "Auth", candidates: [{ pick: 1, label: "Auth", level: 2, label_kind: "subsystem", file_count: 4 }, { pick: 2, label: "AuthZ", level: 2, label_kind: "subsystem", file_count: 2 }] });+ expect(line).toBe('error code=ambiguous_target message="Multiple regions matched \\"Auth\\"." candidates=1:Auth,2:AuthZ');+ });+ it("renders unknown_target with suggestions", () => {+ const line = renderSubsystemErrorLlm({ error: "unknown_target", target_query: "Foo", message: "No region named Foo.", suggestions: ["Bar", "Baz"] });+ expect(line).toBe('error code=unknown_target message="No region named Foo." suggestions=Bar,Baz');+ });+});++describe("renderStatsLlm", () => {+ it("emits nodes/edges lines, dropping zero-count kinds", () => {+ const lines = renderStatsLlm({+ nodes: { total: 100, byKind: [{ kind: "method", count: 60 }, { kind: "class", count: 0 }] },+ edges: { total: 50, byPredicate: [{ predicate: "CALLS", count: 50 }, { predicate: "EXTENDS", count: 0 }] },+ });+ expect(lines).toEqual(["nodes total=100 method=60", "edges total=50 CALLS=50"]);+ });+});++describe("renderSmellsLlm", () => {+ it("renders a detection run, highest confidence first, dropping chunks=0", () => {+ const lines = renderSmellsRunLlm({+ rev: 9, run_at: "", count: 2,+ candidates: [+ { file_id: "a", file: "low.py", smell: "has_smell.orphan_file", confidence: 0.5, signals: { connectivity: 0 }, inference_version: "smell_v1" },+ { file_id: "b", file: "big.ts", smell: "has_smell.god_module", confidence: 0.9, signals: { chunks: 0, fan_in: 23, fan_out: 2 }, inference_version: "smell_v1" },+ ],+ });+ expect(lines[0]).toBe("smells rev=9 count=2 version=smell_v1");+ expect(lines[1]).toBe("smell kind=has_smell.god_module file=big.ts confidence=0.9 fan_in=23 fan_out=2");+ expect(lines[1]).not.toContain("chunks=");+ expect(lines[2]).toBe("smell kind=has_smell.orphan_file file=low.py confidence=0.5 connections=0");+ });+ it("renders --list claims", () => {+ const lines = renderSmellsListLlm([{ smell: "has_smell.god_module", entity_id: "abcdef0123456789", confidence: 0.7, inference_version: "smell_v1" }]);+ expect(lines[0]).toBe("smells count=1 version=smell_v1");+ expect(lines[1]).toBe("smell kind=has_smell.god_module entity=abcdef012345 confidence=0.7 version=smell_v1");+ });+});++describe("impact llm helpers", () => {+ const risk = {+ riskLevel: "high", category: "boundary", riskSummary: "Auth check; 14 sites",+ behaviorAtRisk: ["Token validation"], nextStep: "Run callers", flowPropagation: undefined,+ } as any;+ it("impactHeaderLlm emits impact + behavior lines with quoted summary and comma system_path", () => {+ const lines = impactHeaderLlm({ kind: "function", name: "verify_token" }, risk, [{ name: "Auth", kind: "subsystem" }, { name: "Core", kind: "system" }]);+ expect(lines[0]).toBe('impact target=verify_token kind=function risk=high category=boundary system_path=Auth,Core summary="Auth check; 14 sites"');+ expect(lines[1]).toBe('behavior text="Token validation"');+ });+ it("impactPropagationLlm sorts buckets by member count and emits flow first", () => {+ const lines = impactPropagationLlm(+ [{ region: { name: "small", kind: "module" }, members: [1] }, { region: { name: "big", kind: "subsystem" }, members: [1, 2, 3] }],+ { flowName: "request", count: 9 },+ );+ expect(lines[0]).toBe("flow name=request count=9");+ // humanizeLabel turns "big" into "big layer" (then quoted for the space)+ expect(lines[1]).toBe('bucket region="big layer" kind=subsystem count=3');+ expect(lines[2]).toBe('bucket region="small layer" kind=module count=1');+ });+ it("impactTailLlm emits next/decision/task/bug records", () => {+ const lines = impactTailLlm(risk, [{ name: "Use JWT" }], [{ name: "Migrate", status: "open" }], [{ name: "Leak", status: "open", severity: "high" }]);+ expect(lines).toEqual([+ 'next text="Run callers"',+ 'decision name="Use JWT"',+ "task name=Migrate status=open",+ "bug name=Leak status=open severity=high",+ ]);+ });+});++describe("overview llm helpers", () => {+ it("overviewContainerLlm emits overview + contains + item + note", () => {+ const lines = overviewContainerLlm({+ target: { name: "IngestionService", kind: "class" }, displayPath: "src/ingest.ts",+ systemPath: [{ name: "Ingestion", kind: "system" }, { name: "Core", kind: "subsystem" }], hasMap: true,+ childrenByKind: { method: 12, field: 4 }, keyItems: [{ name: "parseFile", kind: "method" }],+ diagnostics: ["No system map."],+ });+ expect(lines[0]).toBe("overview target=IngestionService kind=class file=src/ingest.ts system_path=Ingestion,Core");+ expect(lines[1]).toBe("contains method=12 field=4");+ expect(lines[2]).toBe("item name=parseFile kind=method");+ expect(lines[3]).toBe('note text="No system map."');+ });+ it("overviewLeafLlm emits contained_in and nearby/sibling, dropping absent system_path", () => {+ const lines = overviewLeafLlm({+ target: { name: "verify", kind: "function" }, displayPath: "auth.ts",+ containedIn: { kind: "class", name: "Auth" }, systemPath: [], hasMap: false,+ siblingsByKind: { method: 3 }, keySiblings: [{ name: "login", kind: "method" }], diagnostics: [],+ });+ expect(lines[0]).toBe('overview target=verify kind=function file=auth.ts contained_in="class Auth"');+ expect(lines[0]).not.toContain("system_path=");+ expect(lines[1]).toBe("nearby method=3");+ expect(lines[2]).toBe("sibling name=login kind=method");+ });+});diff --git a/ix-cli/src/cli/__tests__/llm.test.ts b/ix-cli/src/cli/__tests__/llm.test.tsnew file mode 100644index 00000000..24e6e5f7--- /dev/null+++ b/ix-cli/src/cli/__tests__/llm.test.ts@@ -0,0 +1,88 @@+import { describe, it, expect } from "vitest";+import { llmQuote, llmField, llmLine, llmError } from "../llm.js";++describe("llmQuote", () => {+ it("leaves bare values untouched", () => {+ expect(llmQuote("auth.py")).toBe("auth.py");+ expect(llmQuote("god_module")).toBe("god_module");+ expect(llmQuote("0.62")).toBe("0.62");+ expect(llmQuote("a,b,c")).toBe("a,b,c");+ });++ it("quotes values containing spaces", () => {+ expect(llmQuote("Cli / Client")).toBe('"Cli / Client"');+ });++ it("quotes values containing = or \"", () => {+ expect(llmQuote("a=b")).toBe('"a=b"');+ expect(llmQuote('say "hi"')).toBe('"say \\"hi\\""');+ });++ it("escapes backslashes", () => {+ expect(llmQuote("a\\b")).toBe('"a\\\\b"');+ });++ it("encodes newlines/tabs so the record stays on one line", () => {+ expect(llmQuote("line1\nline2")).toBe('"line1\\nline2"');+ expect(llmQuote("a\tb")).toBe('"a\\tb"');+ expect(llmQuote("line1\nline2")).not.toContain("\n");+ });++ it("renders the empty string as explicit empty quotes", () => {+ expect(llmQuote("")).toBe('""');+ });+});++describe("llmField", () => {+ it("drops null/undefined/empty", () => {+ expect(llmField("k", null)).toBeNull();+ expect(llmField("k", undefined)).toBeNull();+ expect(llmField("k", "")).toBeNull();+ });++ it("renders numbers and booleans", () => {+ expect(llmField("files", 87)).toBe("files=87");+ expect(llmField("cross", true)).toBe("cross=true");+ expect(llmField("n", 0)).toBe("n=0");+ });++ it("quotes string values that need it", () => {+ expect(llmField("label", "Cli / Client")).toBe('label="Cli / Client"');+ });+});++describe("llmLine", () => {+ it("emits a record-kind token then key=value pairs", () => {+ const line = llmLine("region", [+ ["id", "cli-client"],+ ["label", "Cli / Client"],+ ["level", 2],+ ["files", 87],+ ]);+ expect(line).toBe('region id=cli-client label="Cli / Client" level=2 files=87');+ });++ it("skips omitted fields", () => {+ const line = llmLine("region", [+ ["id", "root"],+ ["parent", null],+ ["files", 0],+ ]);+ expect(line).toBe("region id=root files=0");+ });++ it("accepts a plain object and supports no record kind", () => {+ expect(llmLine(null, { a: 1, b: "x" })).toBe("a=1 b=x");+ });+});++describe("llmError", () => {+ it("renders a uniform error record", () => {+ const line = llmError("unknown_target", "No entity named 'Foo' found", [+ ["suggestions", "Bar,Baz"],+ ]);+ expect(line).toBe(+ 'error code=unknown_target message="No entity named \'Foo\' found" suggestions=Bar,Baz'+ );+ });+});diff --git a/ix-cli/src/cli/bootstrap.ts b/ix-cli/src/cli/bootstrap.tsindex 081f86a4..213e80c7 100644--- a/ix-cli/src/cli/bootstrap.ts+++ b/ix-cli/src/cli/bootstrap.ts@@ -91,6 +91,21 @@ export async function ensureBackendAvailable(): Promise<void> {}}+/**+ * Emit the one-time "Ix / Created config / Registered workspace" setup notice.+ *+ * These are side-effect messages, not program output, so they go to stderr —+ * keeping stdout clean for `--format json|llm` consumers (a banner on stdout+ * corrupts the first machine-readable response after a workspace is registered).+ */+export function emitSetupNotice(createdConfig: boolean, registered: boolean, name: string): void {+ if (!createdConfig && !registered) return;+ console.error(chalk.bold("Ix\n"));+ if (createdConfig) console.error(chalk.dim(`Created default config.`));+ if (registered) console.error(chalk.dim(`Registered workspace "${name}".`));+ console.error();+}+/*** Full lazy bootstrap. Call at the top of map/watch actions.* Prints user-friendly output only on first run (when something was created).@@ -99,12 +114,7 @@ export async function bootstrap(cwd = process.cwd()): Promise<void> {const createdConfig = ensureLocalConfig();const { registered, name } = ensureWorkspaceRegistered(cwd);- if (createdConfig || registered) {- console.log(chalk.bold("Ix\n"));- if (createdConfig) console.log(chalk.dim(`Created default config.`));- if (registered) console.log(chalk.dim(`Registered workspace "${name}".`));- console.log();- }+ emitSetupNotice(createdConfig, registered, name);await ensureBackendAvailable();}diff --git a/ix-cli/src/cli/commands/callers.ts b/ix-cli/src/cli/commands/callers.tsindex 9320a6f7..5832be80 100644--- a/ix-cli/src/cli/commands/callers.ts+++ b/ix-cli/src/cli/commands/callers.ts@@ -17,7 +17,7 @@ export function registerCallersCommand(program: Command): void {.option("--kind <kind>", "Filter target entity by kind").option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)").option("--limit <n>", "Max results to show", "50")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").addHelpText("after", "\nExamples:\n ix callers verify_token\n ix callers processPayment --format json\n ix callers parse --kind method --limit 20").action(async (symbol: string, opts: { kind?: string; pick?: string; limit: string; format: string }) => {const client = new IxClient(getEndpoint());@@ -106,7 +106,7 @@ export function registerCallersCommand(program: Command): void {.option("--kind <kind>", "Filter target entity by kind").option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)").option("--limit <n>", "Max results to show", "50")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").addHelpText("after", "\nExamples:\n ix callees processPayment\n ix callees parse --format json").action(async (symbol: string, opts: { kind?: string; pick?: string; limit: string; format: string }) => {const client = new IxClient(getEndpoint());diff --git a/ix-cli/src/cli/commands/conflicts.ts b/ix-cli/src/cli/commands/conflicts.tsindex 99a322eb..5a636611 100644--- a/ix-cli/src/cli/commands/conflicts.ts+++ b/ix-cli/src/cli/commands/conflicts.ts@@ -7,7 +7,7 @@ export function registerConflictsCommand(program: Command): void {program.command("conflicts").description("List detected conflicts")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").action(async (opts: { format: string }) => {const client = new IxClient(getEndpoint());const conflicts = await client.conflicts();diff --git a/ix-cli/src/cli/commands/contains.ts b/ix-cli/src/cli/commands/contains.tsindex fb130f95..18a6a99f 100644--- a/ix-cli/src/cli/commands/contains.ts+++ b/ix-cli/src/cli/commands/contains.ts@@ -12,7 +12,7 @@ export function registerContainsCommand(program: Command): void {.option("--path <path>", "Filter target entity by file path (substring match)").option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)").option("--limit <n>", "Max results to show", "50")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").addHelpText("after", "\nExamples:\n ix contains IngestionService\n ix contains auth.py --kind file --format json\n ix contains MyClass --limit 20\n ix contains package --path crates/regex/Cargo.toml").action(async (symbol: string, opts: { kind?: string; path?: string; pick?: string; limit: string; format: string }) => {const client = new IxClient(getEndpoint());diff --git a/ix-cli/src/cli/commands/depends.ts b/ix-cli/src/cli/commands/depends.tsindex bef225f0..97c956a4 100644--- a/ix-cli/src/cli/commands/depends.ts+++ b/ix-cli/src/cli/commands/depends.ts@@ -156,7 +156,7 @@ export function registerDependsCommand(program: Command): void {.option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)").option("--depth <n>", "Cap traversal depth").option("--cap <n>", "Cap number of nodes visited")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").option("--include-tests", "Include test and fixture entities in results").option("--tests-only", "Show only test and fixture entities").addHelpText("after", `\nExamples:diff --git a/ix-cli/src/cli/commands/diff.ts b/ix-cli/src/cli/commands/diff.tsindex 02bef651..76ceb353 100644--- a/ix-cli/src/cli/commands/diff.ts+++ b/ix-cli/src/cli/commands/diff.ts@@ -405,7 +405,7 @@ export function registerDiffCommand(program: Command): void {.option("--content", "Show detailed attribute changes for each entity").option("--limit <n>", "Max changes to return (default 100)").option("--full", "Return all changes (no limit)")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").option("--kind <kind>", "Filter target entity by kind").option("--path <path>", "Prefer symbols from files matching this path substring").option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")diff --git a/ix-cli/src/cli/commands/doctor.ts b/ix-cli/src/cli/commands/doctor.tsindex f5ec148a..2932a1d5 100644--- a/ix-cli/src/cli/commands/doctor.ts+++ b/ix-cli/src/cli/commands/doctor.ts@@ -13,7 +13,7 @@ export function registerDoctorCommand(program: Command): void {program.command("doctor").description("Check Ix system health — server, database, graph integrity")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").action(async (opts: { format: string }) => {const endpoint = getEndpoint();const client = new IxClient(endpoint);diff --git a/ix-cli/src/cli/commands/entity.ts b/ix-cli/src/cli/commands/entity.tsindex a23fa9f2..9b5db928 100644--- a/ix-cli/src/cli/commands/entity.ts+++ b/ix-cli/src/cli/commands/entity.ts@@ -8,7 +8,7 @@ export function registerEntityCommand(program: Command): void {program.command("entity <id>").description("Get entity details with claims and edges")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").action(async (id: string, opts: { format: string }) => {const client = new IxClient(getEndpoint());const resolvedId = await client.resolvePrefix(id);diff --git a/ix-cli/src/cli/commands/explain.ts b/ix-cli/src/cli/commands/explain.tsindex 3a79cf88..e11a1381 100644--- a/ix-cli/src/cli/commands/explain.ts+++ b/ix-cli/src/cli/commands/explain.ts@@ -18,7 +18,7 @@ export function registerExplainCommand(program: Command): void {.option("--kind <kind>", "Filter target entity by kind").option("--path <path>", "Prefer symbols from files matching this path substring").option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").option("--raw", "Show raw metadata dump (legacy format)").addHelpText("after", "\nExamples:\n ix explain IngestionService\n ix explain expand --path memory-layer\n ix explain verify_token --kind function --format json\n ix explain IxClient --raw").action(async (symbol: string, opts: { kind?: string; path?: string; pick?: string; format: string; raw?: boolean }) => {diff --git a/ix-cli/src/cli/commands/history.ts b/ix-cli/src/cli/commands/history.tsindex ba055a67..6eca3deb 100644--- a/ix-cli/src/cli/commands/history.ts+++ b/ix-cli/src/cli/commands/history.ts@@ -13,7 +13,7 @@ export function registerHistoryCommand(program: Command): void {.option("--kind <kind>", "Filter target entity by kind").option("--path <path>", "Prefer symbols from files matching this path substring").option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").addHelpText("after", `\nExamples:ix history ix-cli/src/cli/commands/decide.tsix history decide.tsdiff --git a/ix-cli/src/cli/commands/impact.ts b/ix-cli/src/cli/commands/impact.tsindex 1d0b9ee9..3152b307 100644--- a/ix-cli/src/cli/commands/impact.ts+++ b/ix-cli/src/cli/commands/impact.ts@@ -7,6 +7,7 @@ import { resolveFileOrEntity, printResolved } from "../resolve.js";import { bucketByHierarchy, getSystemPath, formatSystemPath, hasMapData, type SystemPath } from "../hierarchy.js";import { inferRiskSemantics, humanizeLabel, type ImpactFacts, type RiskSemantics } from "../impact/risk-semantics.js";import { stripNulls } from "../format.js";+import { llmLine, llmError } from "../llm.js";const CONTAINER_KINDS = new Set(["class", "module", "file", "object", "trait", "interface"]);@@ -18,7 +19,7 @@ export function registerImpactCommand(program: Command): void {.option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)").option("--depth <n>", "Expansion depth for callers/importers (default 1, max 3)", "1").option("--limit <n>", "Max top-impacted members to show", "10")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").addHelpText("after","\nExamples:\n ix impact IngestionService\n ix impact IngestionService --kind class\n ix impact verify_token --format json\n ix impact AuthProvider --limit 5"@@ -31,18 +32,22 @@ export function registerImpactCommand(program: Command): void {const client = new IxClient(getEndpoint());const limit = parseInt(opts.limit, 10);const depth = Math.min(Math.max(parseInt(opts.depth, 10) || 1, 1), 3);- const isJson = opts.format === "json";const resolveOpts = { kind: opts.kind, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };const target = await resolveFileOrEntity(client, symbol, resolveOpts);- if (!target) return;+ if (!target) {+ // The resolver already printed human guidance to stderr; for llm+ // consumers emit a structured error record on stdout as well.+ if (opts.format === "llm") console.log(llmError("unresolved_target", `No entity resolved for "${symbol}".`));+ return;+ }- if (!isJson) printResolved(target);+ if (opts.format === "text") printResolved(target);if (CONTAINER_KINDS.has(target.kind)) {- await containerImpact(client, target, limit, depth, isJson);+ await containerImpact(client, target, limit, depth, opts.format);} else {- await leafImpact(client, target, depth, isJson);+ await leafImpact(client, target, depth, opts.format);}});@@ -192,6 +197,68 @@ function capitalize(s: string): string {return s.charAt(0).toUpperCase() + s.slice(1);}+// ── llm rendering ────────────────────────────────────────────────────────────++export function impactHeaderLlm(+ target: { kind: string; name: string },+ risk: RiskSemantics,+ systemPath: Array<{ name: string; kind: string }>,+): string[] {+ const lines = [llmLine("impact", [+ ["target", target.name],+ ["kind", target.kind],+ ["risk", risk.riskLevel],+ ["category", risk.category],+ ["system_path", systemPath.length > 0 ? systemPath.map((n) => n.name).join(",") : undefined],+ ["summary", risk.riskSummary],+ ])];+ for (const b of risk.behaviorAtRisk) {+ lines.push(llmLine("behavior", [["text", b]]));+ }+ return lines;+}++export function impactPropagationLlm(+ buckets: Array<{ region: { name: string; kind: string }; members: unknown[] }>,+ flow?: { flowName: string; count: number },+): string[] {+ const lines: string[] = [];+ if (flow) {+ lines.push(llmLine("flow", [["name", flow.flowName], ["count", flow.count]]));+ }+ const sorted = [...buckets].sort((a, b) => b.members.length - a.members.length);+ for (const bucket of sorted) {+ lines.push(llmLine("bucket", [+ ["region", humanizeLabel(bucket.region.name)],+ ["kind", bucket.region.kind],+ ["count", bucket.members.length],+ ]));+ }+ return lines;+}++export function impactTailLlm(+ risk: RiskSemantics,+ decisions: Array<{ name: string }>,+ tasks: Array<{ name: string; status: string }>,+ bugs: Array<{ name: string; status: string; severity: string }>,+): string[] {+ const lines: string[] = [];+ if (risk.nextStep) {+ lines.push(llmLine("next", [["text", risk.nextStep]]));+ }+ for (const d of decisions) {+ lines.push(llmLine("decision", [["name", d.name]]));+ }+ for (const t of tasks) {+ lines.push(llmLine("task", [["name", t.name], ["status", t.status]]));+ }+ for (const b of bugs) {+ lines.push(llmLine("bug", [["name", b.name], ["status", b.status], ["severity", b.severity]]));+ }+ return lines;+}+// ── Container impact ─────────────────────────────────────────────────────────async function containerImpact(@@ -199,8 +266,9 @@ async function containerImpact(target: { id: string; kind: string; name: string; resolutionMode: string },limit: number,depth: number,- isJson: boolean+ format: string): Promise<void> {+ const isJson = format === "json";const diagnostics: string[] = [];const [containsResult, importersResult, dependentsResult, systemPath, decisionsResult, tasksResult, bugsResult] = await Promise.all([@@ -331,6 +399,20 @@ async function containerImpact(2));+ } else if (format === "llm") {+ const lines = [+ ...impactHeaderLlm(target, risk, systemPathMapped),+ llmLine("counts", [+ ["members", members.length],+ ["importers", directImporters.length],+ ["dependents", directDependents.length],+ ["member_callers", totalMemberCallers],+ ]),+ ...impactPropagationLlm(propagationBuckets, risk.flowPropagation),+ ...topMembers.map((m) => llmLine("member", [["name", m.name], ["kind", m.kind], ["callers", m.callerCount]])),+ ...impactTailLlm(risk, decisions, tasks, bugs),+ ];+ for (const line of lines) console.log(line);} else {// 1. Risk summary + At-risk behaviorrenderRiskHeader(target, risk, systemPath);@@ -367,8 +449,9 @@ async function leafImpact(client: IxClient,target: { id: string; kind: string; name: string; resolutionMode: string },depth: number,- isJson: boolean+ format: string): Promise<void> {+ const isJson = format === "json";const [callersResult, calleesResult, systemPath, decisionsResult, tasksResult, bugsResult] = await Promise.all([client.expand(target.id, { direction: "in", predicates: ["CALLS", "REFERENCES"], hops: depth }),client.expand(target.id, { direction: "out", predicates: ["CALLS", "REFERENCES"] }),@@ -460,6 +543,21 @@ async function leafImpact(2));+ } else if (format === "llm") {+ const toRef = (kind: string) => (n: any) =>+ llmLine(kind, [["name", n.name || n.attrs?.name || "(unnamed)"], ["kind", n.kind]]);+ const lines = [+ ...impactHeaderLlm(target, risk, systemPathMapped),+ llmLine("counts", [+ ["callers", callersResult.nodes.length],+ ["callees", calleesResult.nodes.length],+ ]),+ ...impactPropagationLlm(propagationBuckets, risk.flowPropagation),+ ...callersResult.nodes.map(toRef("caller")),+ ...calleesResult.nodes.map(toRef("callee")),+ ...impactTailLlm(risk, decisions, tasks, bugs),+ ];+ for (const line of lines) console.log(line);} else {// 1. Risk summary + At-risk behaviorrenderRiskHeader(target, risk, systemPath);diff --git a/ix-cli/src/cli/commands/imports.ts b/ix-cli/src/cli/commands/imports.tsindex 0f3a9884..8acff18c 100644--- a/ix-cli/src/cli/commands/imports.ts+++ b/ix-cli/src/cli/commands/imports.ts@@ -11,7 +11,7 @@ export function registerImportsCommand(program: Command): void {.option("--kind <kind>", "Filter target entity by kind").option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)").option("--limit <n>", "Max results to show", "50")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").addHelpText("after", "\nExamples:\n ix imports auth.py\n ix imports IngestionService --format json").action(async (symbol: string, opts: { kind?: string; pick?: string; limit: string; format: string }) => {const client = new IxClient(getEndpoint());@@ -30,7 +30,7 @@ export function registerImportsCommand(program: Command): void {.option("--kind <kind>", "Filter target entity by kind").option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)").option("--limit <n>", "Max results to show", "50")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").addHelpText("after", "\nExamples:\n ix imported-by AuthProvider\n ix imported-by io.circe.Json --format json").action(async (symbol: string, opts: { kind?: string; pick?: string; limit: string; format: string }) => {const client = new IxClient(getEndpoint());diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.tsindex c03a9954..eeec9be5 100644--- a/ix-cli/src/cli/commands/ingest.ts+++ b/ix-cli/src/cli/commands/ingest.ts@@ -375,7 +375,7 @@ export function registerIngestCommand(program: Command): void {.option('--since <date>', 'Only fetch items updated after this date (ISO 8601)').option('--limit <n>', 'Max items per category (default 50)', '50').option('--force', 'Force re-ingest even if files are unchanged (useful after parser upgrades)')- .option('--format <fmt>', 'Output format (text|json)', 'text')+ .option('--format <fmt>', 'Output format (text|json|llm)', 'text').option('--root <dir>', 'Workspace root directory').option('--debug', 'Show phase timing breakdown', false).option('--lang <langs>', 'Comma-separated languages to include (e.g. cpp,c or typescript). Aliases: c++=cpp, c#=csharp, py=python, ts=typescript, js=javascript')diff --git a/ix-cli/src/cli/commands/inventory.ts b/ix-cli/src/cli/commands/inventory.tsindex c8cc16cd..72bfc7e0 100644--- a/ix-cli/src/cli/commands/inventory.ts+++ b/ix-cli/src/cli/commands/inventory.ts@@ -12,7 +12,7 @@ export function registerInventoryCommand(program: Command): void {.requiredOption("--kind <kind>", "Entity kind to list (class, method, function, file, module, etc.)").option("--path <path>", "Filter by source file path substring").option("--limit <n>", "Max results", "50")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").addHelpText("after", `Examples:ix inventory --kind classdiff --git a/ix-cli/src/cli/commands/locate.ts b/ix-cli/src/cli/commands/locate.tsindex d791056f..1e178414 100644--- a/ix-cli/src/cli/commands/locate.ts+++ b/ix-cli/src/cli/commands/locate.ts@@ -37,7 +37,7 @@ export function registerLocateCommand(program: Command): void {.option("--kind <kind>", "Filter target entity by kind").option("--path <path>", "Prefer results from files matching this path substring").option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").addHelpText("after", `\nExamples:ix locate IngestionServiceix locate verify_token --kind functiondiff --git a/ix-cli/src/cli/commands/map.ts b/ix-cli/src/cli/commands/map.tsindex 5df3e50a..97476d1a 100644--- a/ix-cli/src/cli/commands/map.ts+++ b/ix-cli/src/cli/commands/map.ts@@ -4,6 +4,7 @@ import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";import { roundFloat } from "../format.js";+import { llmLine, llmError } from "../llm.js";import { bootstrap, resolveWorkspaceId } from "../bootstrap.js";import { formatFetchError } from "../errors.js";import { ingestFiles } from "./ingest.js";@@ -84,7 +85,7 @@ export function registerMapCommand(program: Command): void {program.command("map [path]").description("Map the architectural hierarchy of a codebase")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").option("--level <n>", "Show only regions at this level (1=finest, higher=coarser)").option("--min-confidence <n>", "Only show regions above this confidence threshold (0-1)", "0").option("--max-items <n>", "Max items to show per section in text output (default: 10)", "10")@@ -133,9 +134,17 @@ Examples:const cwd = pathArg ? resolve(pathArg) : process.cwd();const silent = opts.silent === true || opts.format === "silent";+ // json and llm are machine formats: suppress progress chatter and route+ // ingestion through the quiet path so stdout carries only the result.+ const machineFormat = opts.format === "json" || opts.format === "llm";+ // Report an error on the right channel: structured record for llm, prose for the rest.+ const emitError = (msg: string) => {+ if (opts.format === "llm") console.log(llmError("backend_error", msg));+ else console.error(chalk.red("Error:"), msg);+ };// Print warning when --full override is active- if (opts.full && opts.format !== "json" && !silent) {+ if (opts.full && !machineFormat && !silent) {console.log(chalk.yellow("\nWarning"));console.log(chalk.yellow(" Full local map override enabled.\n"));console.log(" Ix will ignore automatic local safety limits and attempt full local mapping.");@@ -160,10 +169,10 @@ Examples:await runner.runIngestion({cwd,silent,- format: (opts.format === "json" || silent) ? "json" : "text",+ format: (machineFormat || silent) ? "json" : "text",});} catch (err: any) {- console.error(chalk.red("Error:"), formatFetchError(err));+ emitError(formatFetchError(err));process.exitCode = 1;return;}@@ -171,20 +180,20 @@ Examples:try {await bootstrap(cwd);} catch (err: any) {- console.error(chalk.red("Error:"), err.message);+ emitError(err.message);process.exitCode = 1;return;}try {await ingestFiles(cwd, {recursive: true,- format: (opts.format === "json" || silent) ? "json" : "text",+ format: (machineFormat || silent) ? "json" : "text",printSummary: false,suppressOutput: true,mapMode: true,});} catch (err: any) {- console.error(chalk.red("Error:"), formatFetchError(err));+ emitError(formatFetchError(err));process.exitCode = 1;return;}@@ -195,7 +204,7 @@ Examples:const mapBarWidth = 25;const mapStart = performance.now();- const mapInterval = (opts.format !== "json" && !silent) ? setInterval(() => {+ const mapInterval = (!machineFormat && !silent) ? setInterval(() => {const elapsed = performance.now() - mapStart;const pct = 1 - Math.exp(-elapsed / 4000);const filled = Math.round(pct * mapBarWidth);@@ -209,7 +218,7 @@ Examples:result = await client.map({ full: opts.full, workspaceId: resolveWorkspaceId(cwd) }) as MapResult;} catch (err: any) {if (mapInterval) { clearInterval(mapInterval); process.stderr.write('\r' + ' '.repeat(60) + '\r'); }- console.error(chalk.red("Error:"), formatFetchError(err));+ emitError(formatFetchError(err));process.exitCode = 1;return;}@@ -226,7 +235,7 @@ Examples:return;}- if (opts.format !== "json") {+ if (!machineFormat) {const mapSec = (mapMs / 1000).toFixed(1);process.stderr.write(chalk.dim(` Mapped in ${mapSec}s\n`));}@@ -260,10 +269,40 @@ Examples:}, null, 2));return;}+ if (opts.format === "llm") {+ renderMapLlm(result, regions);+ return;+ }renderMapText(result, cwd, opts);});}+/** Flat one-record-per-line region listing with explicit parent= for the llm format. */+export function renderMapLlm(result: MapResult, regions: MapRegion[]): void {+ console.log(llmLine("map", [+ ["files", result.file_count],+ ["regions", regions.length],+ ["levels", result.levels],+ ["rev", result.map_rev],+ ["outcome", result.outcome],+ ]));+ for (const r of regions) {+ console.log(llmLine("region", [+ ["id", r.id],+ ["kind", r.label_kind],+ ["label", r.label],+ ["level", r.level],+ ["files", r.file_count],+ ["parent", r.parent_id],+ ["children", r.child_region_count > 0 ? r.child_region_count : undefined],+ ["cohesion", roundFloat(r.cohesion)],+ ["coupling", roundFloat(r.external_coupling)],+ ["confidence", roundFloat(r.confidence)],+ ["signals", r.dominant_signals.length > 0 ? r.dominant_signals.join(",") : undefined],+ ]));+ }+}+export function renderMapText(result: MapResult, cwd: string, opts: MapTextRenderOptions): void {const minConf = parseFloat(opts.minConfidence ?? "0");const levelFilter = opts.level ? parseInt(opts.level, 10) : null;diff --git a/ix-cli/src/cli/commands/overview.ts b/ix-cli/src/cli/commands/overview.tsindex f5199787..cbf12cc9 100644--- a/ix-cli/src/cli/commands/overview.ts+++ b/ix-cli/src/cli/commands/overview.ts@@ -6,6 +6,7 @@ import { resolveFileOrEntity, printResolved } from "../resolve.js";import { getEffectiveSystemPath, getSystemPath, hasMapData } from "../hierarchy.js";import { humanizeLabel } from "../impact/risk-semantics.js";import { relativePath } from "../format.js";+import { llmLine, llmError, type LlmValue } from "../llm.js";import { renderSection, renderKeyValue, renderNote, renderBreadcrumb } from "../ui.js";const CONTAINER_KINDS = new Set(["class", "module", "file", "trait", "object", "interface"]);@@ -38,7 +39,7 @@ export function registerOverviewCommand(program: Command): void {.option("--kind <kind>", "Filter target entity by kind").option("--path <path>", "Prefer symbols from files matching this path substring").option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").addHelpText("after",`\nUse overview for structural summaries. Use 'ix locate' for position.@@ -56,9 +57,13 @@ Examples:const client = new IxClient(getEndpoint());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 (!target) {+ // Resolver printed human guidance to stderr; add a structured record for llm.+ if (opts.format === "llm") console.log(llmError("unresolved_target", `No entity resolved for "${symbol}".`));+ return;+ }- if (opts.format !== "json") printResolved(target);+ if (opts.format === "text") printResolved(target);const isContainer = CONTAINER_KINDS.has(target.kind);const isRegion = REGION_KINDS.has(target.kind);@@ -194,6 +199,13 @@ async function overviewContainer(return;}+ if (format === "llm") {+ for (const line of overviewContainerLlm({ target, displayPath, systemPath: systemPathMapped, hasMap, childrenByKind, keyItems, diagnostics })) {+ console.log(line);+ }+ return;+ }+renderOverviewHeader(target, displayPath, null, systemPathMapped, hasMap);if (Object.keys(childrenByKind).length > 0) {@@ -323,6 +335,13 @@ async function overviewLeaf(return;}+ if (format === "llm") {+ for (const line of overviewLeafLlm({ target, displayPath, containedIn, systemPath: systemPathMapped, hasMap, siblingsByKind, keySiblings, diagnostics })) {+ console.log(line);+ }+ return;+ }+renderOverviewHeader(target, displayPath, containedIn, systemPathMapped, hasMap);// Nearby structure@@ -345,6 +364,66 @@ async function overviewLeaf(renderDiagnostics(diagnostics);}+// ── llm rendering ────────────────────────────────────────────────────────────++function systemPathField(systemPath: Array<{ name: string }>, hasMap: boolean): LlmValue {+ return systemPath.length > 1 && hasMap ? systemPath.map((n) => n.name).join(",") : undefined;+}++export function overviewContainerLlm(d: {+ target: { name: string; kind: string };+ displayPath: string | null;+ systemPath: Array<{ name: string; kind: string }>;+ hasMap: boolean;+ childrenByKind: Record<string, number>;+ keyItems: Array<{ name: string; kind: string }>;+ diagnostics: string[];+}): string[] {+ const lines = [llmLine("overview", [+ ["target", d.target.name],+ ["kind", d.target.kind],+ ["file", d.displayPath],+ ["system_path", systemPathField(d.systemPath, d.hasMap)],+ ])];+ const containsEntries = Object.entries(d.childrenByKind).sort((a, b) => b[1] - a[1]);+ if (containsEntries.length > 0) {+ lines.push(llmLine("contains", containsEntries as Array<[string, LlmValue]>));+ }+ for (const item of d.keyItems) {+ lines.push(llmLine("item", [["name", item.name], ["kind", item.kind]]));+ }+ for (const note of d.diagnostics) lines.push(llmLine("note", [["text", note]]));+ return lines;+}++export function overviewLeafLlm(d: {+ target: { name: string; kind: string };+ displayPath: string | null;+ containedIn: { kind: string; name: string } | null;+ systemPath: Array<{ name: string; kind: string }>;+ hasMap: boolean;+ siblingsByKind: Record<string, number> | null;+ keySiblings: Array<{ name: string; kind: string }> | null;+ diagnostics: string[];+}): string[] {+ const lines = [llmLine("overview", [+ ["target", d.target.name],+ ["kind", d.target.kind],+ ["file", d.displayPath],+ ["contained_in", d.containedIn ? `${d.containedIn.kind} ${d.containedIn.name}` : undefined],+ ["system_path", systemPathField(d.systemPath, d.hasMap)],+ ])];+ if (d.siblingsByKind && Object.keys(d.siblingsByKind).length > 0) {+ const entries = Object.entries(d.siblingsByKind).sort((a, b) => b[1] - a[1]);+ lines.push(llmLine("nearby", entries as Array<[string, LlmValue]>));+ }+ for (const s of d.keySiblings ?? []) {+ lines.push(llmLine("sibling", [["name", s.name], ["kind", s.kind]]));+ }+ for (const note of d.diagnostics) lines.push(llmLine("note", [["text", note]]));+ return lines;+}+// ── Shared rendering ────────────────────────────────────────────────────────function renderOverviewHeader(diff --git a/ix-cli/src/cli/commands/patches.ts b/ix-cli/src/cli/commands/patches.tsindex d8699546..1f5d8d2b 100644--- a/ix-cli/src/cli/commands/patches.ts+++ b/ix-cli/src/cli/commands/patches.ts@@ -8,7 +8,7 @@ export function registerPatchesCommand(program: Command): void {.command("patches").description("List recent patches").option("--limit <n>", "Maximum patches to return", "50")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").action(async (opts: { limit: string; format: string }) => {const client = new IxClient(getEndpoint());const patches = await client.listPatches({ limit: parseInt(opts.limit, 10) });diff --git a/ix-cli/src/cli/commands/rank.ts b/ix-cli/src/cli/commands/rank.tsindex 8306eb6e..9d47ed31 100644--- a/ix-cli/src/cli/commands/rank.ts+++ b/ix-cli/src/cli/commands/rank.ts@@ -117,7 +117,7 @@ export function registerRankCommand(program: Command): void {.option("--path <path>", "Filter entities by source path substring").option("--exclude-path <path>", "Exclude entities whose source path contains this substring").option("--exclude-kind <kinds>", "Comma-separated kinds to exclude from results")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").addHelpText("after",`\nExamples:diff --git a/ix-cli/src/cli/commands/read.ts b/ix-cli/src/cli/commands/read.tsindex e0ad77f3..0643c3d9 100644--- a/ix-cli/src/cli/commands/read.ts+++ b/ix-cli/src/cli/commands/read.ts@@ -98,7 +98,7 @@ export function registerReadCommand(program: Command): void {program.command("read <target>").description("Read raw file content, line ranges, or symbol source code")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").option("--kind <kind>", "Filter symbol by kind").option("--path <path>", "Prefer symbols from files matching this path substring").option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")diff --git a/ix-cli/src/cli/commands/savings.ts b/ix-cli/src/cli/commands/savings.tsindex 7cf6a88f..aa2237e2 100644--- a/ix-cli/src/cli/commands/savings.ts+++ b/ix-cli/src/cli/commands/savings.ts@@ -95,7 +95,7 @@ export function registerSavingsCommand(program: Command): void {.description("Show token savings from Ix usage").option("--detail", "Include per-command breakdown").option("--model <model>", "Pricing model (opus|sonnet|haiku|gpt-4o)", "opus")- .option("--format <fmt>", "Output format (text|json)", "text");+ .option("--format <fmt>", "Output format (text|json|llm)", "text");cmd.action(async (opts: { detail?: boolean; model: string; format: string }) => {const client = new IxClient(getEndpoint());diff --git a/ix-cli/src/cli/commands/search.ts b/ix-cli/src/cli/commands/search.tsindex efa39fbf..daaac8da 100644--- a/ix-cli/src/cli/commands/search.ts+++ b/ix-cli/src/cli/commands/search.ts@@ -94,7 +94,7 @@ export function registerSearchCommand(program: Command): void {.option("--language <lang>", "Filter by language/file extension (e.g. scala, ts)").option("--path <path>", "Boost results from files matching this path substring").option("--as-of <rev>", "Search as of a specific revision")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").option("--include-tests", "Include test and fixture entities in results").option("--tests-only", "Show only test and fixture entities").addHelpText("after", `\nRanking priority:diff --git a/ix-cli/src/cli/commands/smells.ts b/ix-cli/src/cli/commands/smells.tsindex e168936a..83166c03 100644--- a/ix-cli/src/cli/commands/smells.ts+++ b/ix-cli/src/cli/commands/smells.ts@@ -3,6 +3,7 @@ import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";import { resolveWorkspaceId } from "../bootstrap.js";+import { llmLine, llmError, type LlmValue } from "../llm.js";interface SmellCandidate {file_id: string;@@ -30,7 +31,7 @@ export function registerSmellsCommand(program: Command): void {program.command("smells").description("Detect architecture smells in the codebase")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").option("--orphan-max-connections <n>","Max connections for orphan files", "0").option("--god-module-chunks <n>", "Min chunks for god module", "20").option("--god-module-fan <n>", "Min fan-in/out for god module", "15")@@ -65,7 +66,8 @@ Examples:try {result = await client.listSmells({ workspaceId: resolveWorkspaceId() });} catch (err: any) {- console.error(chalk.red("Error:"), err.message);+ if (opts.format === "llm") console.log(llmError("backend_error", err.message ?? "smells request failed"));+ else console.error(chalk.red("Error:"), err.message);process.exitCode = 1;return;}@@ -83,6 +85,10 @@ Examples:return;}const smells = result.smells ?? [];+ if (opts.format === "llm") {+ for (const line of renderSmellsListLlm(smells)) console.log(line);+ return;+ }if (smells.length === 0) {console.log(chalk.dim("No smell claims found. Run `ix smells` to detect."));return;@@ -109,7 +115,8 @@ Examples:workspaceId: resolveWorkspaceId(),}) as SmellReport;} catch (err: any) {- console.error(chalk.red("Error:"), err.message);+ if (opts.format === "llm") console.log(llmError("backend_error", err.message ?? "smells request failed"));+ else console.error(chalk.red("Error:"), err.message);process.exitCode = 1;return;}@@ -132,6 +139,11 @@ Examples:return;}+ if (opts.format === "llm") {+ for (const line of renderSmellsRunLlm(report)) console.log(line);+ return;+ }+console.log(`\n${chalk.bold("Architecture Smells")} ` +chalk.dim(`rev ${report.rev} · ${report.count} candidates`)@@ -175,6 +187,61 @@ function confidenceBar(conf: number): string {return color(bar);}+/** Render `ix smells --list` claims as llm records. */+export function renderSmellsListLlm(smells: any[]): string[] {+ const lines = [llmLine("smells", [["count", smells.length], ["version", "smell_v1"]])];+ for (const s of smells) {+ lines.push(llmLine("smell", [+ ["kind", s.smell],+ ["entity", s.entity_id?.slice(0, 12)],+ ["confidence", s.confidence],+ ["version", s.inference_version],+ ]));+ }+ return lines;+}++/** Render a fresh `ix smells` detection run as llm records, highest-confidence first. */+export function renderSmellsRunLlm(report: SmellReport): string[] {+ const lines = [llmLine("smells", [["rev", report.rev], ["count", report.count], ["version", "smell_v1"]])];+ const sorted = [...report.candidates].sort((a, b) => b.confidence - a.confidence);+ for (const c of sorted) {+ lines.push(llmLine("smell", [+ ["kind", c.smell],+ ["file", c.file],+ ["confidence", c.confidence],+ ...signalFields(c.smell, c.signals),+ ]));+ }+ return lines;+}++/**+ * Structured signal fields per smell kind for the llm format. Mirrors the+ * fields shown in text mode. A god_module's chunk count is dropped when 0+ * (uncomputed / no signal); fan-in/out are the defining signals and kept.+ */+function signalFields(smellKind: string, signals: Record<string, unknown>): Array<[string, LlmValue]> {+ const num = (v: unknown): LlmValue =>+ typeof v === "number" || typeof v === "string" ? v : undefined;+ switch (smellKind) {+ case "has_smell.orphan_file":+ return [["connections", num(signals["connectivity"]) ?? 0]];+ case "has_smell.god_module": {+ const chunks = num(signals["chunks"]);+ return [+ ["chunks", chunks === 0 ? undefined : chunks],+ ["fan_in", num(signals["fan_in"])],+ ["fan_out", num(signals["fan_out"])],+ ];+ }+ case "has_smell.weak_component_member":+ return [["neighbors", num(signals["neighbor_count"]) ?? 0]];+ default:+ return [];+ }+}+function formatSignals(smellKind: string, signals: Record<string, unknown>): string {switch (smellKind) {case "has_smell.orphan_file":diff --git a/ix-cli/src/cli/commands/stats.ts b/ix-cli/src/cli/commands/stats.tsindex 5b8cd9ec..22ab78a7 100644--- a/ix-cli/src/cli/commands/stats.ts+++ b/ix-cli/src/cli/commands/stats.ts@@ -3,21 +3,48 @@ import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";import { resolveWorkspaceId } from "../bootstrap.js";+import { llmLine, llmError, type LlmValue } from "../llm.js";++/** Render `ix stats` as llm records: one `nodes` line and one `edges` line. */+export function renderStatsLlm(result: any): string[] {+ const nodeFields: Array<[string, LlmValue]> = [["total", result.nodes.total]];+ for (const entry of result.nodes.byKind) {+ if ((entry.count ?? 0) > 0) nodeFields.push([entry.kind ?? "unknown", entry.count]);+ }+ const edgeFields: Array<[string, LlmValue]> = [["total", result.edges.total]];+ for (const entry of result.edges.byPredicate) {+ if ((entry.count ?? 0) > 0) edgeFields.push([entry.predicate ?? "unknown", entry.count]);+ }+ return [llmLine("nodes", nodeFields), llmLine("edges", edgeFields)];+}export function registerStatsCommand(program: Command): void {program.command("stats").description("Show graph statistics — node/edge counts by type")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").action(async (opts: { format: string }) => {const client = new IxClient(getEndpoint());- const result = await client.stats({ workspaceId: resolveWorkspaceId() });+ let result;+ try {+ result = await client.stats({ workspaceId: resolveWorkspaceId() });+ } catch (err: any) {+ if (opts.format === "llm") console.log(llmError("backend_error", err.message ?? "stats request failed"));+ else console.error(chalk.red("Error:"), err.message);+ process.exitCode = 1;+ return;+ }if (opts.format === "json") {console.log(JSON.stringify(result, null, 2));return;}+ if (opts.format === "llm") {+ for (const line of renderStatsLlm(result)) console.log(line);+ return;+ }+console.log(chalk.bold("\nnodes") + chalk.dim(` (${result.nodes.total} total)`));for (const entry of result.nodes.byKind) {const kind = entry.kind ?? "unknown";diff --git a/ix-cli/src/cli/commands/status.ts b/ix-cli/src/cli/commands/status.tsindex 824419e2..e204e1e0 100644--- a/ix-cli/src/cli/commands/status.ts+++ b/ix-cli/src/cli/commands/status.ts@@ -8,7 +8,7 @@ export function registerStatusCommand(program: Command): void {program.command("status").description("Show Ix backend health and status")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").option("--root <dir>", "Workspace root directory").action(async (opts: { format: string; root?: string }) => {const client = new IxClient(getEndpoint());diff --git a/ix-cli/src/cli/commands/subsystems.ts b/ix-cli/src/cli/commands/subsystems.tsindex f59d1ce1..bbf0b702 100644--- a/ix-cli/src/cli/commands/subsystems.ts+++ b/ix-cli/src/cli/commands/subsystems.ts@@ -4,7 +4,8 @@ import { IxClient, type ListSubsystemsOptions } from "../../client/api.js";import { getEndpoint } from "../config.js";import { resolveWorkspaceId } from "../bootstrap.js";import { roundFloat } from "../format.js";-import { renderMapText, type MapResult } from "./map.js";+import { llmLine, llmError } from "../llm.js";+import { renderMapText, renderMapLlm, type MapRegion, type MapResult } from "./map.js";import {renderSubsystemExplanationJson,renderSubsystemExplanationText,@@ -47,7 +48,7 @@ export function registerSubsystemsCommand(program: Command): void {program.command("subsystems [target]").description("Show the persisted architectural map saved by 'ix map'")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").option("--list", "List stored subsystem health scores instead of the persisted architecture map").option("--detailed", "Include member files and enriched call/import edges (requires --list)").option("--limit <n>", "Max regions per page in detailed mode (default: 200 when auto-paging)")@@ -160,7 +161,8 @@ Examples:result = await loadSubsystemScores(client, detailedQuery.value ?? {});}} catch (err: any) {- console.error(chalk.red("Error:"), err.message);+ if (opts.format === "llm") console.log(llmError("backend_error", err.message ?? "subsystems request failed"));+ else console.error(chalk.red("Error:"), err.message);process.exitCode = 1;return;}@@ -172,6 +174,12 @@ Examples:? scores.filter(s => s.level === parseInt(opts.level!, 10)): scores;+ if (opts.format === "llm") {+ console.log(llmLine("subsystems", [["count", filtered.length]]));+ for (const s of filtered) console.log(renderSubsystemScoreLlm(s));+ return;+ }+if (opts.format === "json") {if (opts.detailed) {console.log(JSON.stringify(buildDetailedListPayload(filtered, result.pagination), null, 2));@@ -211,6 +219,11 @@ Examples:process.exitCode = 1;return;}+ if (opts.format === "llm") {+ console.log(renderSubsystemErrorLlm(body));+ process.exitCode = 1;+ return;+ }renderSubsystemError(body, Boolean(opts.explain));process.exitCode = 1;return;@@ -254,6 +267,20 @@ Examples:return;}+ if (opts.format === "llm") {+ if (isScopedSubsystemResult(result)) {+ for (const line of renderScopedSubsystemLlm(result)) console.log(line);+ } else {+ const mapResult = result as MapResult;+ let regions: MapRegion[] = mapResult.regions;+ if (opts.level) regions = regions.filter(r => r.level === parseInt(opts.level!, 10));+ const minConf = parseFloat(opts.minConfidence ?? "0");+ if (minConf > 0) regions = regions.filter(r => r.confidence >= minConf);+ renderMapLlm(mapResult, regions);+ }+ return;+ }+if (isScopedSubsystemResult(result)) {renderScopedSubsystemText(result, Boolean(opts.verbose));return;@@ -271,6 +298,79 @@ Examples:});}+// ── llm renderers ────────────────────────────────────────────────────────────++export function renderSubsystemScoreLlm(s: SubsystemScore): string {+ // chunk_density is dropped when 0 (uncomputed / no signal); see docs/llm-format.md.+ return llmLine("region", [+ ["id", s.region_id],+ ["label", s.name],+ ["kind", s.label_kind],+ ["level", s.level],+ ["files", s.file_count],+ ["health", roundFloat(s.health_score)],+ ["chunks_per_file", s.chunk_density > 0 ? roundFloat(s.chunk_density) : undefined],+ ["smells", s.smell_files > 0 ? s.smell_files : undefined],+ ["confidence", roundFloat(s.confidence)],+ ]);+}++export function renderScopedSubsystemLlm(result: ScopedSubsystemResult): string[] {+ const t = result.target;+ const lines = [+ llmLine("target", [+ ["id", t.id],+ ["label", t.label],+ ["kind", t.label_kind],+ ["level", t.level],+ ["files", t.file_count],+ ["confidence", roundFloat(t.confidence)],+ ["cross_cutting", t.is_cross_cutting ? true : undefined],+ ["parent", result.parent?.id],+ ["signals", t.dominant_signals.length > 0 ? t.dominant_signals.join(",") : undefined],+ ]),+ llmLine("health", [+ ["well_defined", result.summary.well_defined],+ ["moderate", result.summary.moderate],+ ["fuzzy", result.summary.fuzzy],+ ["cross_cutting", result.summary.cross_cutting],+ ]),+ ];+ const emit = (region: ScopedSubsystemRegion): void => {+ lines.push(llmLine("region", [+ ["id", region.id],+ ["label", region.label],+ ["kind", region.label_kind],+ ["level", region.level],+ ["files", region.file_count],+ ["parent", region.parent_id],+ ["confidence", roundFloat(region.confidence)],+ ["cross_cutting", region.is_cross_cutting ? true : undefined],+ ["signals", region.dominant_signals.length > 0 ? region.dominant_signals.join(",") : undefined],+ ]));+ for (const child of region.children ?? []) emit(child);+ };+ for (const child of result.children) emit(child);+ return lines;+}++export function renderSubsystemErrorLlm(body: unknown): string {+ if (isAmbiguousSubsystemResult(body)) {+ return llmError("ambiguous_target", `Multiple regions matched "${body.target_query}".`, [+ ["candidates", body.candidates.map(c => `${c.pick}:${c.label}`).join(",")],+ ]);+ }+ if (isUnknownSubsystemTargetResult(body)) {+ return llmError("unknown_target", body.message, [+ ["suggestions", (body.suggestions ?? []).join(",") || undefined],+ ]);+ }+ if (typeof body === "object" && body !== null && "error" in body) {+ return llmError("error", String((body as { error: unknown }).error));+ }+ return llmError("error", "Request failed.");+}+function printScores(scores: SubsystemScore[]): void {if (scores.length === 0) {console.log(chalk.dim("No subsystem scores found. Run 'ix map' then 'ix subsystems'."));diff --git a/ix-cli/src/cli/commands/text.ts b/ix-cli/src/cli/commands/text.tsindex 6a8c159f..8886b7e2 100644--- a/ix-cli/src/cli/commands/text.ts+++ b/ix-cli/src/cli/commands/text.ts@@ -14,7 +14,7 @@ export function registerTextCommand(program: Command): void {.option("--limit <n>", "Max results", "20").option("--path <dir>", "Restrict search to a directory", ".").option("--language <lang>", "Filter by language (python, typescript, scala, etc.)")- .option("--format <fmt>", "Output format (text|json)", "text")+ .option("--format <fmt>", "Output format (text|json|llm)", "text").option("--root <dir>", "Workspace root directory").addHelpText("after", "\nExamples:\n ix text verify_token --language python\n ix text \"class.*Service\" --limit 10 --format json\n ix text TODO --path src/").action(async (term: string, opts: { limit: string; path: string; format: string; language?: string; root?: string }) => {diff --git a/ix-cli/src/cli/commands/trace.ts b/ix-cli/src/cli/commands/trace.tsindex f47d98cd..b29ab4ee 100644--- a/ix-cli/src/cli/commands/trace.ts+++ b/ix-cli/src/cli/commands/trace.ts@@ -1,41 +1,41 @@-import type { Command } from "commander";-import chalk from "chalk";-import { IxClient } from "../../client/api.js";-import { getEndpoint } from "../config.js";+import type { Command } from "commander";+import chalk from "chalk";+import { IxClient } from "../../client/api.js";+import { getEndpoint } from "../config.js";import { resolveFileOrEntity, isRawId } from "../resolve.js";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";--// ── 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;-}--// ── Constants ────────────────────────────────────────────────────────--const DEFAULT_MAX_DEPTH = Infinity;-const MAX_NODES = Infinity;--// ── 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). */+import { stderr } from "../stderr.js";+import { renderSection, renderKeyValue, renderResolvedHeader, colorizeKind } from "../ui.js";+import { compactTreeNode, relativePath } from "../format.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;+}++// ── Constants ────────────────────────────────────────────────────────++const DEFAULT_MAX_DEPTH = Infinity;+const MAX_NODES = Infinity;++// ── 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()) {@@ -141,339 +141,339 @@ export async function pickTraceTarget(resolutionMode: "scored",};}--// ── Tree traversal ───────────────────────────────────────────────────--async function buildTraceTree(- client: IxClient,- rootId: string,- opts: {- direction: "in" | "out";- predicates: string[];- maxDepth: number;- maxNodes: number;- },-): Promise<{ tree: TraceNode[]; truncated: boolean; nodesVisited: number; maxDepthReached: number }> {- const { direction, predicates, maxDepth, maxNodes } = opts;- const visited = new Set<string>([rootId]);- let nodesVisited = 0;- let truncated = false;- let maxDepthReached = 0;-- async function expand(nodeId: string, depth: number): Promise<TraceNode[]> {- if (depth > maxDepth) { truncated = true; return []; }- if (nodesVisited >= maxNodes) { truncated = true; return []; }- maxDepthReached = Math.max(maxDepthReached, depth);-- // One call per predicate (matches depends.ts behaviour — order and dedup are stable)- const results = await Promise.all(- predicates.map((p) => client.expand(nodeId, { direction, predicates: [p], hops: 1 })),- );-- const children: TraceNode[] = [];- const levelSeen = new Set<string>();-- for (const result of results) {- for (const n of result.nodes) {- if (nodesVisited >= maxNodes) { truncated = true; break; }- if (levelSeen.has(n.id)) continue;-- const name = n.name || n.attrs?.name || "";- const resolved = !!name && !isRawId(name);- const isCycle = visited.has(n.id);-- nodesVisited++;- levelSeen.add(n.id);- visited.add(n.id);-- const child: TraceNode = {- 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: [],- ...(isCycle ? { cycle: true } : {}),- };-- if (!isCycle && resolved) {- child.children = await expand(n.id, depth + 1);- }-- children.push(child);- }- }-- return children;- }-- const tree = await expand(rootId, 1);- return { tree, truncated, nodesVisited, maxDepthReached };-}--// ── Path search (BFS) ────────────────────────────────────────────────--export async function findPath(- client: IxClient,- fromId: string,- toId: string,- predicates: string[],- maxDepth: number = 10,-): Promise<PathNode[] | null> {- 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]);-- while (queue.length > 0) {- const entry = queue.shift()!;- const { id, path } = entry;- if (path.length >= maxDepth) continue;-- const [outResult, inResult] = await Promise.all([- client.expand(id, { direction: "out", predicates, hops: 1 }),- client.expand(id, { direction: "in", predicates, hops: 1 }),- ]);-- for (const n of [...outResult.nodes, ...inResult.nodes]) {- 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 (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 };- });- }-- if (visited.has(n.id)) continue;- visited.add(n.id);- queue.push({ id: n.id, path: [...path, n.id] });- }- }-- return null;-}--// ── 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);---// ── 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")- .option("--cap <n>", "Cap number of nodes visited, per direction")- .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")- .option("--path <path>", "Prefer symbols from files matching this path substring")- .option("--format <fmt>", "Output format (text|json)", "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?: string;- path?: string;- format: string;- includeTests?: boolean;- testsOnly?: boolean;- },- ) => {- const client = new IxClient(getEndpoint());-- // Validate --pick- if (opts.pick !== undefined) {- const pickVal = parseInt(opts.pick, 10);- if (isNaN(pickVal) || pickVal < 1) {- stderr("Invalid value for --pick: must be a positive integer.");- return;- }- }-- const resolveOpts = {- path: opts.path,- pick: opts.pick ? parseInt(opts.pick, 10) : undefined,- includeTests: opts.includeTests,- testsOnly: opts.testsOnly,- };-- const maxDepth = opts.depth ? parseInt(opts.depth, 10) : DEFAULT_MAX_DEPTH;- const maxNodes = opts.cap ? parseInt(opts.cap, 10) : MAX_NODES;-- // ── Path mode (--to) ────────────────────────────────────────- if (opts.to) {- const toResolveOpts = {- ...resolveOpts,- path: undefined,- };- const [fromTarget, toTarget] = await Promise.all([- resolveFileOrEntity(client, symbol, resolveOpts),- resolveFileOrEntity(client, opts.to, toResolveOpts),- ]);- if (!fromTarget || !toTarget) return;-- const relKind = opts.kind ?? "mixed";- const predicates = kindToPredicates(opts.kind);-- const rawPath = await findPath(client, fromTarget.id, toTarget.id, predicates, maxDepth + 7);-- // 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 }));- output.path = mapped;- output.summary = { path_length: pathNodes.length };- } else {- output.path = null;- output.diagnostics = [- {- code: "no_path",- message: `No route found from ${fromTarget.name} to ${toTarget.name}.`,- },- ];- }- console.log(JSON.stringify(output, null, 2));- 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(`\nNo route found from ${chalk.bold(fromTarget.name)} to ${chalk.bold(toTarget.name)}.`);- 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 {- console.log(` ${chalk.dim("→")} ${kindStr} ${n.name}`);- }- }-- renderSection("Summary");- renderKeyValue("Path length", String(pathNodes.length));- return;- }-- // ── Directional mode ────────────────────────────────────────++// ── Tree traversal ───────────────────────────────────────────────────++async function buildTraceTree(+ client: IxClient,+ rootId: string,+ opts: {+ direction: "in" | "out";+ predicates: string[];+ maxDepth: number;+ maxNodes: number;+ },+): Promise<{ tree: TraceNode[]; truncated: boolean; nodesVisited: number; maxDepthReached: number }> {+ const { direction, predicates, maxDepth, maxNodes } = opts;+ const visited = new Set<string>([rootId]);+ let nodesVisited = 0;+ let truncated = false;+ let maxDepthReached = 0;++ async function expand(nodeId: string, depth: number): Promise<TraceNode[]> {+ if (depth > maxDepth) { truncated = true; return []; }+ if (nodesVisited >= maxNodes) { truncated = true; return []; }+ maxDepthReached = Math.max(maxDepthReached, depth);++ // One call per predicate (matches depends.ts behaviour — order and dedup are stable)+ const results = await Promise.all(+ predicates.map((p) => client.expand(nodeId, { direction, predicates: [p], hops: 1 })),+ );++ const children: TraceNode[] = [];+ const levelSeen = new Set<string>();++ for (const result of results) {+ for (const n of result.nodes) {+ if (nodesVisited >= maxNodes) { truncated = true; break; }+ if (levelSeen.has(n.id)) continue;++ const name = n.name || n.attrs?.name || "";+ const resolved = !!name && !isRawId(name);+ const isCycle = visited.has(n.id);++ nodesVisited++;+ levelSeen.add(n.id);+ visited.add(n.id);++ const child: TraceNode = {+ 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: [],+ ...(isCycle ? { cycle: true } : {}),+ };++ if (!isCycle && resolved) {+ child.children = await expand(n.id, depth + 1);+ }++ children.push(child);+ }+ }++ return children;+ }++ const tree = await expand(rootId, 1);+ return { tree, truncated, nodesVisited, maxDepthReached };+}++// ── Path search (BFS) ────────────────────────────────────────────────++export async function findPath(+ client: IxClient,+ fromId: string,+ toId: string,+ predicates: string[],+ maxDepth: number = 10,+): Promise<PathNode[] | null> {+ 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]);++ while (queue.length > 0) {+ const entry = queue.shift()!;+ const { id, path } = entry;+ if (path.length >= maxDepth) continue;++ const [outResult, inResult] = await Promise.all([+ client.expand(id, { direction: "out", predicates, hops: 1 }),+ client.expand(id, { direction: "in", predicates, hops: 1 }),+ ]);++ for (const n of [...outResult.nodes, ...inResult.nodes]) {+ 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 (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 };+ });+ }++ if (visited.has(n.id)) continue;+ visited.add(n.id);+ queue.push({ id: n.id, path: [...path, n.id] });+ }+ }++ return null;+}++// ── 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);+++// ── 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")+ .option("--cap <n>", "Cap number of nodes visited, per direction")+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")+ .option("--path <path>", "Prefer 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?: string;+ path?: string;+ format: string;+ includeTests?: boolean;+ testsOnly?: boolean;+ },+ ) => {+ const client = new IxClient(getEndpoint());++ // Validate --pick+ if (opts.pick !== undefined) {+ const pickVal = parseInt(opts.pick, 10);+ if (isNaN(pickVal) || pickVal < 1) {+ stderr("Invalid value for --pick: must be a positive integer.");+ return;+ }+ }++ const resolveOpts = {+ path: opts.path,+ pick: opts.pick ? parseInt(opts.pick, 10) : undefined,+ includeTests: opts.includeTests,+ testsOnly: opts.testsOnly,+ };++ const maxDepth = opts.depth ? parseInt(opts.depth, 10) : DEFAULT_MAX_DEPTH;+ const maxNodes = opts.cap ? parseInt(opts.cap, 10) : MAX_NODES;++ // ── Path mode (--to) ────────────────────────────────────────+ if (opts.to) {+ const toResolveOpts = {+ ...resolveOpts,+ path: undefined,+ };+ const [fromTarget, toTarget] = await Promise.all([+ resolveFileOrEntity(client, symbol, resolveOpts),+ resolveFileOrEntity(client, opts.to, toResolveOpts),+ ]);+ if (!fromTarget || !toTarget) return;++ const relKind = opts.kind ?? "mixed";+ const predicates = kindToPredicates(opts.kind);++ const rawPath = await findPath(client, fromTarget.id, toTarget.id, predicates, maxDepth + 7);++ // 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 }));+ output.path = mapped;+ output.summary = { path_length: pathNodes.length };+ } else {+ output.path = null;+ output.diagnostics = [+ {+ code: "no_path",+ message: `No route found from ${fromTarget.name} to ${toTarget.name}.`,+ },+ ];+ }+ console.log(JSON.stringify(output, null, 2));+ 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(`\nNo route found from ${chalk.bold(fromTarget.name)} to ${chalk.bold(toTarget.name)}.`);+ 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 {+ console.log(` ${chalk.dim("→")} ${kindStr} ${n.name}`);+ }+ }++ renderSection("Summary");+ renderKeyValue("Path length", String(pathNodes.length));+ return;+ }++ // ── Directional mode ────────────────────────────────────────const resolvedTarget = await resolveFileOrEntity(client, symbol, resolveOpts);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 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,@@ -482,141 +482,141 @@ export function registerTraceCommand(program: Command): void {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) {- const [upResult, downResult] = await Promise.all([- buildTraceTree(client, target.id, { direction: "in", predicates, maxDepth, maxNodes }),- buildTraceTree(client, target.id, { direction: "out", predicates, maxDepth, maxNodes }),- ]);-- // ── JSON ──────────────────────────────────────────────- if (opts.format === "json") {- console.log(- JSON.stringify(- {- 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 },- },- },- null,- 2,- ),- );- 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));- return;- }-- // ── Single direction ────────────────────────────────────────- const { tree, truncated, 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: { nodes_visited: nodesVisited, max_depth: maxDepthReached },- };-- if (tree.length === 0) {- output.diagnostics = [- { code: "no_edges", message: `No ${direction} ${relKind} found for ${target.name}.` },- ];- }- if (truncated) {- const diags = (output.diagnostics as unknown[]) ?? [];- (diags as unknown[]).push({ code: "truncated", message: `Traversal truncated (depth: ${maxDepth}, node cap: ${maxNodes}).` });- output.diagnostics = diags;- }-- console.log(JSON.stringify(output, null, 2));- 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));- },- );-}+ // 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) {+ const [upResult, downResult] = await Promise.all([+ buildTraceTree(client, target.id, { direction: "in", predicates, maxDepth, maxNodes }),+ buildTraceTree(client, target.id, { direction: "out", predicates, maxDepth, maxNodes }),+ ]);++ // ── JSON ──────────────────────────────────────────────+ if (opts.format === "json") {+ console.log(+ JSON.stringify(+ {+ 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 },+ },+ },+ null,+ 2,+ ),+ );+ 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));+ return;+ }++ // ── Single direction ────────────────────────────────────────+ const { tree, truncated, 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: { nodes_visited: nodesVisited, max_depth: maxDepthReached },+ };++ if (tree.length === 0) {+ output.diagnostics = [+ { code: "no_edges", message: `No ${direction} ${relKind} found for ${target.name}.` },+ ];+ }+ if (truncated) {+ const diags = (output.diagnostics as unknown[]) ?? [];+ (diags as unknown[]).push({ code: "truncated", message: `Traversal truncated (depth: ${maxDepth}, node cap: ${maxNodes}).` });+ output.diagnostics = diags;+ }++ console.log(JSON.stringify(output, null, 2));+ 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));+ },+ );+}diff --git a/ix-cli/src/cli/llm.ts b/ix-cli/src/cli/llm.tsnew file mode 100644index 00000000..c527fa9c--- /dev/null+++ b/ix-cli/src/cli/llm.ts@@ -0,0 +1,90 @@+/**+ * Renderer for the `--format llm` output convention.+ *+ * The goal is a newline-delimited, token-minimal wire format that AI coding+ * agents (ix-claude-plugin, Cursor, Codex, ...) can consume without the+ * decorative whitespace of `--format text` or the structural overhead of+ * `--format json`. See docs/llm-format.md for the full spec.+ *+ * Convention:+ * - One record per line. Newline-delimited, no nesting.+ * - Scalars: `key=value` pairs separated by a single space.+ * - Tabular rows: a leading record-kind token, then `key=value` pairs.+ * - No decorative whitespace, separators, or headers.+ * - Null/undefined/empty values are dropped. Zeros and other defaults are+ * dropped by the caller where they carry no signal.+ * - Quoting: a value containing a space, `=`, `"`, or a control character is+ * wrapped in double quotes; inner `"` and `\` are backslash-escaped and+ * newlines/tabs are encoded as `\n`/`\r`/`\t` so a record never spans lines.+ */++/** A field value before rendering. Nullish/empty values are omitted. */+export type LlmValue = string | number | boolean | null | undefined;++/** Ordered field pairs, or a plain object whose own enumerable keys are used. */+export type LlmFields = Array<[string, LlmValue]> | Record<string, LlmValue>;++// Quote when a value contains whitespace, `=`, `"`, `\`, or any C0 control char.+const NEEDS_QUOTING = /[\s="\\\x00-\x1f]/;++/**+ * Quote and escape a value for the llm wire format.+ *+ * Bare values pass through untouched. Anything containing whitespace, `=`, `"`,+ * or a control character is wrapped in double quotes with `\` and `"` escaped+ * and newline/CR/tab encoded so the value stays on a single line.+ */+export function llmQuote(raw: string): string {+ if (raw === "") return '""';+ if (!NEEDS_QUOTING.test(raw)) return raw;+ const escaped = raw+ .replace(/\\/g, "\\\\")+ .replace(/"/g, '\\"')+ .replace(/\n/g, "\\n")+ .replace(/\r/g, "\\r")+ .replace(/\t/g, "\\t");+ return `"${escaped}"`;+}++/** Render a single `key=value` token, or null if the value is omitted. */+export function llmField(key: string, value: LlmValue): string | null {+ if (value === null || value === undefined) return null;+ const str = typeof value === "string" ? value : String(value);+ if (str === "") return null;+ return `${key}=${llmQuote(str)}`;+}++function fieldEntries(fields: LlmFields): Array<[string, LlmValue]> {+ return Array.isArray(fields) ? fields : Object.entries(fields);+}++/**+ * Render one record line: an optional leading record-kind token followed by+ * `key=value` pairs. Omitted fields (nullish/empty) are skipped. Returns the+ * line without a trailing newline.+ */+export function llmLine(recordKind: string | null, fields: LlmFields = []): string {+ const parts: string[] = [];+ if (recordKind) parts.push(recordKind);+ for (const [key, value] of fieldEntries(fields)) {+ const field = llmField(key, value);+ if (field) parts.push(field);+ }+ return parts.join(" ");+}++/** Render an error record in the shared format. Caller still sets the exit code. */+export function llmError(+ code: string,+ message: string,+ extra: LlmFields = [],+): string {+ return llmLine("error", [["code", code], ["message", message], ...fieldEntries(extra)]);+}++/** Print rendered lines, skipping any that are empty. */+export function printLlmLines(lines: Array<string | null | undefined>): void {+ for (const line of lines) {+ if (line) console.log(line);+ }+}