Skip to content

armgit / Ix

Public Imported from GitHub
0

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

feat(llm): implement --format llm for the five commands that faked it (#372)

KageBinaryed361190094b
diff --git a/CLAUDE.md b/CLAUDE.md
index 3878dd61..1d92b6ff 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -90,13 +90,15 @@ Use the `ix` CLI exclusively.
- `--format json` — use when chaining results between commands, or when you need
to pull a specific field out of the response.
-**Four commands advertise `llm` in their help but do not implement it**, and fall
-back to human-oriented text without an error: `explain`, `read`, `status`, and the
-deprecated `query`. Use `--format json` on those if you need to parse the result.
-Everywhere else in the routing tables, `llm` behaves as described.
-
-These commands take no `--format` at all: `config`, `init`, `reset`, `upgrade`,
-`view`, `watch`. (`ingest` does accept it, despite being an action command.)
+Every command that accepts `--format` implements `llm`, with two exceptions that
+fall back to text without an error: `diff --content` (verbatim hunks) and
+`ingest`. The deprecated `query` accepts only `text|json` — passing `--format
+llm` to it silently renders text.
+
+`--format llm` is **not** accepted at all by `config`, `init`, `reset`,
+`upgrade`, `view`, `watch` and `docker`, which take no `--format`; passing it is
+an `unknown option` error, not a fallback. Do not pass it blind. (`ingest` does
+accept `--format`, despite being an action command.)
**Pro features.** Some commands below are marked **[Pro]**, as are the whole
**Planning** and **Workflows** sections — every command in those two tables is
diff --git a/docs/llm-format.md b/docs/llm-format.md
index 158f1c29..7a2808e5 100644
--- a/docs/llm-format.md
+++ b/docs/llm-format.md
@@ -95,8 +95,31 @@ Renderers shipped: Tier 1 (`map`, `subsystems`, `impact`, `smells`,
`overview`) plus `stats`; Tier 2 (`inventory`, `rank`, `depends`, `trace`,
`contains`, `callers`, `callees`, `imports`, `imported-by`); Tier 3 (`search`,
`text`, `history`, `patches`); Tier 4 (`entity`, `locate`, `diff`,
-`conflicts`). Commands whose output is verbatim source or prose (`read`,
-`explain`, `doctor`, `status`, `savings`, and `diff --content`) route
-`--format llm` to `text`, the most compact existing form. 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.
+`conflicts`); Tier 5 (`explain`, `read`, `status`, `doctor`, `savings`).
+
+Tier 5 closes the prose fallback. Those five routed `--format llm` to `text` on
+the theory that verbatim source and prose have no record form, which is true of
+the *payload* but not of what surrounds it — `explain`'s prose is a rendering of
+facts the agent can have directly, and `read`'s source was arriving under a
+per-line number gutter and ANSI escapes. `explain` is the one that mattered
+most: it is the first call most plugins make, and its records are ~55% smaller
+than the `--format json` that `text` sent people to as a workaround.
+
+Two deliberate exceptions remain:
+
+- **`read`'s content block is not records.** An agent asked for source and wants
+ it byte-for-byte, so the payload is emitted raw after a `content lines=<n>`
+ record that makes the block self-delimiting. This is the only place the
+ one-record-per-line invariant is relaxed, and the count is what lets a
+ consumer relax it safely.
+- **`status` is not smaller** — it is within a byte or two of `json`, because
+ the payload is a handful of scalars either way. It is in Tier 5 for the
+ explicit `stale=true|false` field, which is the question the command gets
+ called to answer and which `text` only implied through a warning line.
+
+Still routing to `text`: `diff --content` (verbatim hunks) and `ingest`, a
+hidden implementation-detail command whose output is a completion summary.
+
+Programmatic consumers that need to parse output should continue to use
+`--format json`; the `llm` format is optimized for being read by a model, not
+parsed.
diff --git a/ix-cli/src/cli/__tests__/llm-tier5.test.ts b/ix-cli/src/cli/__tests__/llm-tier5.test.ts
new file mode 100644
index 00000000..80721158
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/llm-tier5.test.ts
@@ -0,0 +1,284 @@
+import { describe, it, expect, vi } from "vitest";
+import { renderExplainLlm, renderExplainRawLlm } from "../explain/llm.js";
+import { renderReadLlm, renderReadAmbiguityLlm, outputResult } from "../commands/read.js";
+import type { ReadResult } from "../commands/read.js";
+import { renderStatusLlm } from "../commands/status.js";
+import { renderDoctorLlm } from "../commands/doctor.js";
+import { renderSavingsLlm } from "../commands/savings.js";
+import type { EntityFacts } from "../explain/facts.js";
+
+/**
+ * The commands that advertised `llm` in their help and rendered `text`.
+ *
+ * docs/llm-format.md says an unimplemented command routes `--format llm` to
+ * "whichever existing format is most compact", which for all five of these was
+ * the prose renderer — so agents paid full human-oriented output on the path
+ * they call most. These tests pin the records, and in particular the two
+ * properties that are easy to regress: zero counts survive, and a value that
+ * would break the one-record-per-line invariant gets quoted.
+ */
+
+function facts(over: Partial<EntityFacts> = {}): EntityFacts {
+ return {
+ id: "e1", name: "IngestionService", kind: "class",
+ path: "src/ingest.ts",
+ members: [], memberCount: 0,
+ callerCount: 0, calleeCount: 0, dependentCount: 0, importerCount: 0,
+ downstreamDependents: 0, downstreamDepth: 0,
+ topCallers: [], topDependents: [],
+ historyLength: 0,
+ stale: false,
+ diagnostics: [],
+ ...over,
+ } as EntityFacts;
+}
+
+const role = { role: "service", confidence: "high", reasons: [] } as any;
+const importance = { level: "high", category: "broad-shared-dependency", reasons: [] } as any;
+const rendered = {
+ explanation: "PROSE_EXPLANATION", context: "PROSE_CONTEXT",
+ usedBy: null, whyItMatters: "PROSE_WHY", notes: [],
+};
+
+describe("explain --format llm", () => {
+ it("emits the facts, not the prose that was rendered from them", () => {
+ const lines = renderExplainLlm(
+ facts({ callerCount: 12, dependentCount: 40, introducedRev: 7 }),
+ role, importance, rendered,
+ );
+
+ expect(lines[0]).toBe("entity id=e1 name=IngestionService kind=class path=src/ingest.ts rev=7");
+ expect(lines).toContain("role role=service confidence=high");
+ expect(lines).toContain("importance level=high category=broad-shared-dependency");
+ // The whole point: none of the prose survives. It is a rendering of the
+ // records above, so an agent that gets the records can drop it.
+ expect(lines.join("\n")).not.toContain("PROSE_EXPLANATION");
+ expect(lines.join("\n")).not.toContain("PROSE_CONTEXT");
+ expect(lines.join("\n")).not.toContain("PROSE_WHY");
+ });
+
+ it("keeps zero counts, because 'nothing calls this' is an answer", () => {
+ const line = renderExplainLlm(facts(), role, importance, rendered)
+ .find(l => l.startsWith("edges "));
+
+ // llmField drops "" but keeps "0" — if these were passed as numbers a
+ // future change to that rule would silently delete the answer.
+ expect(line).toBe("edges callers=0 callees=0 dependents=0 importers=0 members=0 downstream=0 depth=0 history=0");
+ });
+
+ it("marks stale sources and carries diagnostics through", () => {
+ const lines = renderExplainLlm(
+ facts({ stale: true, diagnostics: [{ code: "stale_source", message: "File changed since ingest." }] }),
+ role, importance, rendered,
+ );
+
+ expect(lines[0]).toContain("stale=true");
+ expect(lines).toContain('diagnostic code=stale_source message="File changed since ingest."');
+ });
+
+ it("quotes a signature so a record never spans two lines", () => {
+ const lines = renderExplainLlm(
+ facts({ signature: "run(a: string,\n b: number): void" }),
+ role, importance, rendered,
+ );
+
+ const sig = lines.find(l => l.startsWith("signature "))!;
+ expect(sig).toContain("\\n");
+ expect(sig.split("\n")).toHaveLength(1);
+ });
+
+ it("renders the --raw dump as records too", () => {
+ const lines = renderExplainRawLlm({
+ id: "e1", name: "verify_token", kind: "function", file: "src/auth.py",
+ calledBy: 3, calls: 1, contains: 0, historyLength: 2,
+ callList: [{ name: "decode", kind: "function", resolved: true }],
+ });
+
+ expect(lines[0]).toBe("entity id=e1 name=verify_token kind=function path=src/auth.py");
+ expect(lines).toContain("edges called_by=3 calls=1 contains=0 history=2");
+ expect(lines).toContain("call name=decode kind=function");
+ });
+});
+
+describe("read --format llm", () => {
+ it("drops the per-line gutter and self-delimits the payload", () => {
+ const lines = renderReadLlm({
+ targetType: "symbol", path: "/repo/src/auth.py",
+ lineStart: 10, lineEnd: 12,
+ content: "def verify():\n return True\n",
+ symbol: "verify", kind: "function",
+ } as any);
+
+ expect(lines[0]).toContain("line_start=10");
+ expect(lines[0]).toContain("symbol=verify");
+ // content lines=<n> tells the consumer exactly how many lines follow, so a
+ // line of source can never be mistaken for another record.
+ expect(lines[1]).toBe("content lines=3");
+ expect(lines.slice(2)).toEqual(["def verify():", " return True", ""]);
+ // No line number prefixes anywhere.
+ expect(lines.slice(2).some(l => /^\s*\d+ /.test(l))).toBe(false);
+ });
+
+ it("lists candidates when the target is ambiguous", () => {
+ const lines = renderReadAmbiguityLlm({
+ targetType: "ambiguous-symbol",
+ candidates: [
+ { name: "run", kind: "function", path: "/repo/a.ts" },
+ { name: "run", kind: "method", path: "/repo/b.ts" },
+ ],
+ } as any, "run");
+
+ expect(lines[0]).toBe("ambiguous kind=symbol target=run count=2");
+ expect(lines[1]).toContain("candidate n=1 name=run kind=function");
+ expect(lines[lines.length - 1]).toContain("--pick");
+ });
+});
+
+describe("status --format llm", () => {
+ it("answers 'can I trust the graph' in one field", () => {
+ const lines = renderStatusLlm("ok", "http://localhost:8090", {
+ currentRev: 11, lastIngestAt: "2026-08-09T12:00:00.000Z",
+ staleFiles: 2, sampleChangedFiles: ["src/a.ts", "src/b.ts"],
+ });
+
+ expect(lines[0]).toContain("stale=true");
+ expect(lines[0]).toContain("stale_files=2");
+ // ISO, not "3h ago" — the consumer can do its own arithmetic.
+ expect(lines[0]).toContain("last_ingest_at=2026-08-09T12:00:00.000Z");
+ expect(lines).toContain("changed path=src/a.ts");
+ });
+
+ it("says stale=false rather than omitting it when the graph is current", () => {
+ const lines = renderStatusLlm("ok", "http://localhost:8090", {
+ currentRev: 11, lastIngestAt: null, staleFiles: 0, sampleChangedFiles: [],
+ });
+
+ expect(lines[0]).toContain("stale=false");
+ expect(lines[0]).toContain("stale_files=0");
+ });
+
+ it("omits the staleness fields entirely when there is no baseline to read", () => {
+ const lines = renderStatusLlm("ok", "http://localhost:8090", null);
+
+ expect(lines).toEqual(["status backend=ok endpoint=http://localhost:8090"]);
+ });
+});
+
+describe("doctor --format llm", () => {
+ it("prints the detail instead of telling you to re-run for it", () => {
+ const lines = renderDoctorLlm([
+ { name: "Backend reachable", ok: true, detail: "ok" },
+ { name: "Graph schema matches engine", ok: false, warn: true, detail: "graph schema v2, expected v3" },
+ { name: "Docker running", ok: false, detail: "daemon not up" },
+ ], true, true);
+
+ expect(lines[0]).toBe("doctor healthy=false warnings=true checks=3");
+ expect(lines).toContain('check name="Backend reachable" status=ok detail=ok');
+ expect(lines).toContain('check name="Graph schema matches engine" status=warn detail="graph schema v2, expected v3"');
+ expect(lines).toContain('check name="Docker running" status=fail detail="daemon not up"');
+ });
+
+ // {ok:true, warn:true} is the only shape the ternary's ordering decides —
+ // `latest-not-pulled` returns it, and every other combination reads the same
+ // either way round. Without this row the comment explaining why `ok` must be
+ // tested first sits above an untested branch.
+ //
+ // `ok`, not `warn`, because that is what the glyph line renders for the same
+ // record (green ✓, not yellow !). The two formats describing one check
+ // differently is the bug worth guarding; the header still carries
+ // warnings=true, so nothing is lost.
+ it("agrees with the glyph on a check that passes with a warning", () => {
+ const lines = renderDoctorLlm(
+ [{ name: "Backend image", ok: true, warn: true, detail: "can't verify — :latest not pulled" }],
+ false, true,
+ );
+
+ expect(lines[0]).toBe("doctor healthy=true warnings=true checks=1");
+ expect(lines).toContain('check name="Backend image" status=ok detail="can\'t verify — :latest not pulled"');
+ });
+});
+
+describe("savings --format llm", () => {
+ const data = (over = {}) => ({
+ commandCount: 10, tokensSaved: 50_000, naiveTokens: 60_000, actualTokens: 10_000,
+ byCommandType: { explain: { count: 4, saved: 20_000 } },
+ ...over,
+ });
+
+ it("emits one record per scope with the derived money and water", () => {
+ const lines = renderSavingsLlm(
+ { session: data(), lifetime: data() } as any, "opus", false,
+ );
+
+ const session = lines.find(l => l.includes("name=session"))!;
+ expect(session).toContain("tokens_saved=50000");
+ expect(session).toContain("water_saved_ml=100");
+ expect(session).toMatch(/money_saved=\d+\.\d{2}/);
+ });
+
+ it("gates the per-command breakdown behind --detail, like the other formats", () => {
+ const without = renderSavingsLlm({ session: data(), lifetime: data() } as any, "opus", false);
+ const with_ = renderSavingsLlm({ session: data(), lifetime: data() } as any, "opus", true);
+
+ expect(without.some(l => l.startsWith("command "))).toBe(false);
+ expect(with_).toContain("command scope=session name=explain count=4 tokens_saved=20000");
+ });
+});
+
+/**
+ * The `content lines=<n>` header is only true of render *composed with* print.
+ * renderReadLlm returns the blank lines correctly; printLlmLines used to drop
+ * them on the way to stdout, so the count promised more lines than a consumer
+ * ever received and it ate the following records as source. Asserting on the
+ * returned array cannot see that — these drive the real print path.
+ */
+describe("read --format llm content framing", () => {
+ function emit(content: string, over: Partial<ReadResult> = {}): string[] {
+ const out: string[] = [];
+ const spy = vi.spyOn(console, "log").mockImplementation((...a: unknown[]) => {
+ out.push(a.map(String).join(" "));
+ });
+ try {
+ outputResult({
+ targetType: "file", path: "/repo/src/a.ts",
+ lineStart: 1, lineEnd: 1, content, stale: false,
+ ...over,
+ } as ReadResult, "llm");
+ } finally {
+ spy.mockRestore();
+ }
+ return out;
+ }
+
+ function framing(content: string): { declared: number; emitted: number } {
+ const out = emit(content);
+ const header = out.findIndex(l => l.startsWith("content lines="));
+ return {
+ declared: Number(/content lines=(\d+)/.exec(out[header])![1]),
+ emitted: out.length - header - 1,
+ };
+ }
+
+ it.each([
+ ["a blank line in the middle", "def verify():\n\n return True\n"],
+ ["an empty file", ""],
+ ["CRLF content", "a\r\nb\r\n"],
+ ["no trailing newline", "x\ny"],
+ ["only blank lines", "\n\n\n"],
+ ])("emits exactly as many lines as it declares: %s", (_label, content) => {
+ const { declared, emitted } = framing(content);
+ expect(emitted).toBe(declared);
+ });
+
+ it("keeps the blank line in place rather than closing the gap", () => {
+ const out = emit("a\n\nb\n");
+ expect(out.slice(out.findIndex(l => l.startsWith("content lines=")) + 1))
+ .toEqual(["a", "", "b", ""]);
+ });
+
+ it("routes --format llm to records, not the numbered gutter", () => {
+ const out = emit("x\ny");
+ expect(out[0]).toContain("file path=");
+ expect(out.some(l => /^\s*\d+ /.test(l))).toBe(false);
+ });
+});
diff --git a/ix-cli/src/cli/commands/doctor.ts b/ix-cli/src/cli/commands/doctor.ts
index 2ab89c55..9be4da37 100644
--- a/ix-cli/src/cli/commands/doctor.ts
+++ b/ix-cli/src/cli/commands/doctor.ts
@@ -3,6 +3,7 @@ import chalk from "chalk";
import { renderSection, renderSuccess, renderError } from "../ui.js";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
+import { llmLine, printLlmLines } from "../llm.js";
import {
BACKEND_IMAGE,
checkBackendImage,
@@ -18,6 +19,41 @@ interface CheckResult {
warn?: boolean;
}
+/**
+ * `ix doctor --format llm`.
+ *
+ * `text` renders a ✓/!/✗ glyph per check and then, on failure, the singularly
+ * unhelpful "Run with --format json for details" — the details were already in
+ * hand, they were just not printed. Every check's status and detail is emitted
+ * here, so an agent never has to make a second call to find out what broke.
+ *
+ * Status is a word rather than a symbol because `ok`/`warn`/`fail` survives
+ * being read back by something that is not a terminal.
+ */
+export function renderDoctorLlm(
+ results: Array<{ name: string } & CheckResult>,
+ hasFailure: boolean,
+ hasWarning: boolean,
+): string[] {
+ const lines = [llmLine("doctor", [
+ ["healthy", hasFailure ? "false" : "true"],
+ ["warnings", hasWarning ? "true" : "false"],
+ ["checks", String(results.length)],
+ ])];
+ for (const r of results) {
+ lines.push(llmLine("check", [
+ ["name", r.name],
+ // Same precedence as the glyphs and as `hasFailure` below: a warning is
+ // `{ ok: false, warn: true }`, so `warn` has to be checked on the
+ // not-ok branch. Testing it on the ok branch reports every warning as a
+ // hard failure, which is the opposite of what `hasFailure` concludes.
+ ["status", r.ok ? "ok" : r.warn ? "warn" : "fail"],
+ ["detail", r.detail],
+ ]));
+ }
+ return lines;
+}
+
interface Check {
name: string;
run: () => Promise<CheckResult>;
@@ -142,6 +178,11 @@ export function registerDoctorCommand(program: Command): void {
const hasFailure = results.some((r) => !r.ok && !r.warn);
const hasWarning = results.some((r) => r.warn);
+ if (opts.format === "llm") {
+ printLlmLines(renderDoctorLlm(results, hasFailure, hasWarning));
+ return;
+ }
+
if (opts.format === "json") {
console.log(JSON.stringify({ healthy: !hasFailure, hasWarnings: hasWarning, checks: results }, null, 2));
return;
diff --git a/ix-cli/src/cli/commands/explain.ts b/ix-cli/src/cli/commands/explain.ts
index 220aedce..ea8a8ed3 100644
--- a/ix-cli/src/cli/commands/explain.ts
+++ b/ix-cli/src/cli/commands/explain.ts
@@ -8,6 +8,8 @@ import { collectFacts } from "../explain/facts.js";
import { inferRole } from "../explain/role-inference.js";
import { inferImportance } from "../explain/importance.js";
import { renderExplanation } from "../explain/render.js";
+import { renderExplainLlm, renderExplainRawLlm } from "../explain/llm.js";
+import { printLlmLines } from "../llm.js";
import { renderSection, renderWarning, renderNote } from "../ui.js";
export function registerExplainCommand(program: Command): void {
@@ -37,7 +39,9 @@ export function registerExplainCommand(program: Command): void {
const importance = inferImportance(facts);
const rendered = renderExplanation(facts, role, importance);
- if (opts.format === "json") {
+ if (opts.format === "llm") {
+ printLlmLines(renderExplainLlm(facts, role, importance, rendered));
+ } else if (opts.format === "json") {
const output: any = {
resolvedTarget: { kind: target.kind, name: target.name },
facts,
@@ -199,7 +203,9 @@ async function rawExplain(
(result as any).warning = "Results may be stale; file has changed since last ingest.";
}
- if (format === "json") {
+ if (format === "llm") {
+ printLlmLines(renderExplainRawLlm(result));
+ } else if (format === "json") {
const output: any = {
resolvedTarget: { kind: target.kind, name: target.name },
result,
diff --git a/ix-cli/src/cli/commands/read.ts b/ix-cli/src/cli/commands/read.ts
index 2fa58f8a..b979ecfe 100644
--- a/ix-cli/src/cli/commands/read.ts
+++ b/ix-cli/src/cli/commands/read.ts
@@ -8,6 +8,7 @@ import { resolveEntityFull, activeReadScope, ensureReadScope } from "../resolve.
import { stderr } from "../stderr.js";
import { isFileStale } from "../stale.js";
import { relativePath } from "../format.js";
+import { llmLine, printLlmLines } from "../llm.js";
/** Common file extensions that signal the target is file-like, not a symbol name. */
const FILE_EXTENSIONS = new Set([
@@ -26,7 +27,7 @@ function looksFileLike(target: string): boolean {
return false;
}
-interface ReadResult {
+export interface ReadResult {
targetType: "file" | "file-range" | "filename-match" | "symbol";
path: string;
lineStart: number;
@@ -57,8 +58,75 @@ function readFileRange(filePath: string, start?: number, end?: number): { conten
return { content, lineStart, lineEnd };
}
-function outputResult(result: ReadResult, format: string): void {
- if (format === "json") {
+/**
+ * `ix read --format llm`.
+ *
+ * The one command whose payload is not records: an agent asked for source and
+ * wants it byte-for-byte. Everything around it goes, though — `text` prefixes
+ * every single line with a 4-column padded line number and an ANSI dim escape,
+ * which on a 200-line read is 200 gutters of pure overhead for information the
+ * `line_start` field already carries once.
+ *
+ * The `content lines=<n>` record makes the block self-delimiting, so a
+ * consumer knows exactly how many following lines are payload and never has to
+ * guess whether a line of source is another record.
+ */
+export function renderReadLlm(result: ReadResult): string[] {
+ const contentLines = result.content.split("\n");
+ return [
+ llmLine("file", [
+ ["path", relativePath(result.path) ?? result.path],
+ ["line_start", String(result.lineStart)],
+ ["line_end", String(result.lineEnd)],
+ ["target", result.targetType],
+ ["symbol", result.symbol],
+ ["kind", result.kind],
+ ["stale", result.stale ? "true" : null],
+ ]),
+ llmLine("content", [["lines", String(contentLines.length)]]),
+ ...contentLines,
+ ];
+}
+
+/** `ix read --format llm` when the target resolves to more than one thing. */
+export function renderReadAmbiguityLlm(result: AmbiguityResult, target: string): string[] {
+ const isFile = result.targetType === "ambiguous-file";
+ const lines = [
+ llmLine("ambiguous", [
+ ["kind", isFile ? "file" : "symbol"],
+ ["target", target],
+ ["count", String(result.candidates.length)],
+ ]),
+ ];
+ result.candidates.forEach((c, i) => {
+ lines.push(llmLine("candidate", [
+ ["n", String(i + 1)],
+ ["name", c.name],
+ ["kind", c.kind],
+ ["path", c.path ? relativePath(c.path) ?? c.path : undefined],
+ ["id", c.id],
+ ]));
+ });
+ lines.push(llmLine("hint", [[
+ "text",
+ isFile
+ ? "Provide a more specific path to disambiguate."
+ : "Use --pick <n>, --kind, or --path to disambiguate.",
+ ]]));
+ for (const d of result.diagnostics ?? []) {
+ lines.push(llmLine("diagnostic", [["code", d.code], ["message", d.message]]));
+ }
+ return lines;
+}
+
+// Exported for the tests: the `content lines=<n>` invariant is a property of
+// render *composed with* print, not of either alone. Asserting on
+// renderReadLlm's return value passes just as happily when printLlmLines drops
+// the blank lines out from under the count.
+export function outputResult(result: ReadResult, format: string): void {
+ if (format === "llm") {
+ printLlmLines(renderReadLlm(result));
+ } else if (format === "json") {
const out = { ...result, path: relativePath(result.path) ?? result.path };
console.log(JSON.stringify(out, null, 2));
} else {
@@ -74,7 +142,9 @@ function outputResult(result: ReadResult, format: string): void {
}
function outputAmbiguity(result: AmbiguityResult, target: string, format: string): void {
- if (format === "json") {
+ if (format === "llm") {
+ printLlmLines(renderReadAmbiguityLlm(result, target));
+ } else if (format === "json") {
console.log(JSON.stringify(result, null, 2));
} else {
const label = result.targetType === "ambiguous-file" ? "file" : "symbol";
diff --git a/ix-cli/src/cli/commands/savings.ts b/ix-cli/src/cli/commands/savings.ts
index aa2237e2..f476d47f 100644
--- a/ix-cli/src/cli/commands/savings.ts
+++ b/ix-cli/src/cli/commands/savings.ts
@@ -2,6 +2,7 @@ import type { Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
+import { llmLine, printLlmLines } from "../llm.js";
interface CommandBreakdown {
count: number;
@@ -21,6 +22,49 @@ interface SavingsResponse {
lifetime: SavingsData;
}
+/**
+ * `ix savings --format llm`.
+ *
+ * `text` draws a rule, two labelled blocks and a per-command table. The numbers
+ * are the whole content, so they go out as two `scope` records with the
+ * breakdown behind `--detail` exactly as the other formats gate it.
+ *
+ * Money and water are computed here rather than left to the caller because the
+ * pricing table lives in this file — a consumer cannot derive them from
+ * `tokens_saved` without it.
+ */
+export function renderSavingsLlm(
+ result: SavingsResponse,
+ model: string,
+ detail: boolean,
+): string[] {
+ const pricing = PRICING[model] ?? PRICING.opus;
+ const lines = [llmLine("savings", [["model", pricing.label]])];
+
+ for (const [scope, data] of [["session", result.session], ["lifetime", result.lifetime]] as const) {
+ lines.push(llmLine("scope", [
+ ["name", scope],
+ ["commands", String(data.commandCount)],
+ ["tokens_saved", String(data.tokensSaved)],
+ ["naive_tokens", String(data.naiveTokens)],
+ ["actual_tokens", String(data.actualTokens)],
+ ["money_saved", estimateMoney(data.tokensSaved, model).toFixed(2)],
+ ["water_saved_ml", String(estimateWater(data.tokensSaved))],
+ ]));
+ if (!detail) continue;
+ for (const [command, breakdown] of Object.entries(data.byCommandType)) {
+ lines.push(llmLine("command", [
+ ["scope", scope],
+ ["name", command],
+ ["count", String(breakdown.count)],
+ ["tokens_saved", String(breakdown.saved)],
+ ]));
+ }
+ }
+
+ return lines;
+}
+
// Pricing models: input $/MTok, output $/MTok
const PRICING: Record<string, { input: number; output: number; label: string }> = {
opus: { input: 15, output: 75, label: "Claude Opus ($15/MTok in, $75/MTok out)" },
@@ -102,6 +146,11 @@ export function registerSavingsCommand(program: Command): void {
const detail = opts.detail ?? false;
const result: SavingsResponse = await client.savings(detail);
+ if (opts.format === "llm") {
+ printLlmLines(renderSavingsLlm(result, opts.model, detail));
+ return;
+ }
+
if (opts.format === "json") {
const pricing = PRICING[opts.model] ?? PRICING.opus;
console.log(JSON.stringify({
diff --git a/ix-cli/src/cli/commands/status.ts b/ix-cli/src/cli/commands/status.ts
index 005684b9..68df36af 100644
--- a/ix-cli/src/cli/commands/status.ts
+++ b/ix-cli/src/cli/commands/status.ts
@@ -3,6 +3,43 @@ import { renderSection, renderKeyValue, renderWarning, renderNote, renderSuccess
import { IxClient } from "../../client/api.js";
import { getEndpoint, resolveWorkspaceRoot } from "../config.js";
import { detectStaleFiles } from "../stale.js";
+import { llmError, llmLine, printLlmLines } from "../llm.js";
+
+interface StatusStaleInfo {
+ currentRev: number;
+ lastIngestAt: string | null;
+ staleFiles: number;
+ sampleChangedFiles: string[];
+}
+
+/**
+ * `ix status --format llm`.
+ *
+ * The reason to call `status` from an agent is to decide one thing: is the
+ * graph current enough to trust, or does it need `ix map` first. `text` buries
+ * that behind section headers, a "Last ingest" field humanised to "3h ago", and
+ * a sampled file list. The `stale` field answers it directly, and
+ * `last_ingest_at` stays ISO so the consumer can do its own arithmetic instead
+ * of parsing prose.
+ */
+export function renderStatusLlm(
+ backend: string,
+ endpoint: string,
+ staleInfo: StatusStaleInfo | null,
+): string[] {
+ const lines = [llmLine("status", [
+ ["backend", backend],
+ ["endpoint", endpoint],
+ ["rev", staleInfo ? String(staleInfo.currentRev) : null],
+ ["last_ingest_at", staleInfo?.lastIngestAt ?? null],
+ ["stale_files", staleInfo ? String(staleInfo.staleFiles) : null],
+ ["stale", staleInfo ? (staleInfo.staleFiles > 0 ? "true" : "false") : null],
+ ])];
+ for (const f of staleInfo?.sampleChangedFiles ?? []) {
+ lines.push(llmLine("changed", [["path", f]]));
+ }
+ return lines;
+}
export function registerStatusCommand(program: Command): void {
program
@@ -24,7 +61,9 @@ export function registerStatusCommand(program: Command): void {
staleInfo = null;
}
- if (opts.format === "json") {
+ if (opts.format === "llm") {
+ printLlmLines(renderStatusLlm(health.status, getEndpoint(), staleInfo ?? null));
+ } else if (opts.format === "json") {
const result: any = {
backend: health.status,
currentRev: staleInfo?.currentRev ?? null,
@@ -58,7 +97,14 @@ export function registerStatusCommand(program: Command): void {
}
}
} catch (err) {
- console.error(`Ix backend not reachable at ${getEndpoint()}`);
+ // The spec's uniform error record, so a consumer that pipes `--format
+ // llm` parses the failure the same way it parses a result rather than
+ // hitting an unparseable human sentence. Exit code is unchanged.
+ if (opts.format === "llm") {
+ console.log(llmError("backend_unreachable", `Ix backend not reachable at ${getEndpoint()}`));
+ } else {
+ console.error(`Ix backend not reachable at ${getEndpoint()}`);
+ }
process.exit(1);
}
});
diff --git a/ix-cli/src/cli/explain/llm.ts b/ix-cli/src/cli/explain/llm.ts
new file mode 100644
index 00000000..823a3d81
--- /dev/null
+++ b/ix-cli/src/cli/explain/llm.ts
@@ -0,0 +1,181 @@
+import { llmLine } from "../llm.js";
+import { relativePath } from "../format.js";
+import type { EntityFacts } from "./facts.js";
+import type { RoleInference } from "./role-inference.js";
+import type { ImportanceInference } from "./importance.js";
+import type { ExplanationOutput } from "./render.js";
+
+/**
+ * `ix explain --format llm`.
+ *
+ * `explain` advertised `llm` and rendered `text` — the prose pipeline
+ * (explanation / context / why-it-matters) with section headers and indents.
+ * That is the single most expensive thing an agent reads, and it is the
+ * command a plugin calls first on almost every question, so the fallback was
+ * costing the most tokens on the hottest path.
+ *
+ * The prose is a *rendering* of `facts` + `role` + `importance`, so an agent
+ * does not need it: emit the inputs as records and let the model do its own
+ * summarising. `whyItMatters` and `explanation` are dropped entirely for that
+ * reason — every claim in them is derivable from the `role`, `importance` and
+ * `edges` lines below.
+ *
+ * Counts are emitted even at zero on the `edges` line: "this has no callers"
+ * is a real answer to "who calls this", and dropping the field would make it
+ * indistinguishable from a field the renderer forgot.
+ */
+export function renderExplainLlm(
+ facts: EntityFacts,
+ role: RoleInference,
+ importance: ImportanceInference,
+ rendered: ExplanationOutput,
+): string[] {
+ const lines: string[] = [];
+
+ lines.push(llmLine("entity", [
+ ["id", facts.id],
+ ["name", facts.name],
+ ["kind", facts.kind],
+ ["path", facts.path],
+ ["rev", facts.introducedRev],
+ ["stale", facts.stale ? "true" : null],
+ ]));
+
+ lines.push(llmLine("role", [
+ ["role", role.role],
+ ["confidence", role.confidence],
+ ]));
+
+ lines.push(llmLine("importance", [
+ ["level", importance.level],
+ ["category", importance.category],
+ ]));
+
+ // Zeroes are meaningful here, so they are stringified rather than passed as
+ // numbers — llmField drops "" but keeps "0".
+ lines.push(llmLine("edges", [
+ ["callers", String(facts.callerCount)],
+ ["callees", String(facts.calleeCount)],
+ ["dependents", String(facts.dependentCount)],
+ ["importers", String(facts.importerCount)],
+ ["members", String(facts.memberCount)],
+ ["downstream", String(facts.downstreamDependents)],
+ ["depth", String(facts.downstreamDepth)],
+ ["history", String(facts.historyLength)],
+ ]));
+
+ if (facts.container) {
+ lines.push(llmLine("container", [
+ ["kind", facts.container.kind],
+ ["name", facts.container.name],
+ ]));
+ }
+
+ if (facts.subsystemName || facts.moduleName) {
+ lines.push(llmLine("location", [
+ ["subsystem", facts.subsystemName],
+ ["module", facts.moduleName],
+ ]));
+ }
+
+ if (facts.signature) lines.push(llmLine("signature", [["text", facts.signature]]));
+
+ for (const caller of facts.topCallers) {
+ lines.push(llmLine("caller", [["name", caller]]));
+ }
+ for (const dependent of facts.topDependents) {
+ lines.push(llmLine("dependent", [["name", dependent]]));
+ }
+ for (const member of facts.members) {
+ lines.push(llmLine("member", [["name", member]]));
+ }
+
+ // Kept from the prose because it is the one part that is not derivable from
+ // the records above: `usedBy` names call sites the counts only total up.
+ if (rendered.usedBy) lines.push(llmLine("used_by", [["text", rendered.usedBy]]));
+
+ for (const note of rendered.notes) {
+ lines.push(llmLine("note", [["text", note]]));
+ }
+
+ for (const diagnostic of facts.diagnostics) {
+ lines.push(llmLine("diagnostic", [
+ ["code", diagnostic.code],
+ ["message", diagnostic.message],
+ ]));
+ }
+
+ return lines;
+}
+
+/**
+ * `ix explain --raw --format llm`.
+ *
+ * The legacy metadata dump. Same treatment, driven off the assembled
+ * `ExplainResult` rather than the fact pipeline.
+ */
+export function renderExplainRawLlm(result: {
+ kind?: string;
+ name?: string;
+ id?: string;
+ file?: string;
+ chunkKind?: string;
+ container?: { kind: string; name: string };
+ introducedRev?: number;
+ calledBy?: number;
+ calls?: number;
+ contains?: number;
+ historyLength?: number;
+ signature?: string;
+ docstring?: string;
+ callList?: Array<{ name: string; kind?: string; path?: string; resolved: boolean }>;
+ diagnostics?: Array<{ code: string; message: string }>;
+ stale?: boolean;
+}): string[] {
+ const lines: string[] = [];
+
+ lines.push(llmLine("entity", [
+ ["id", result.id],
+ ["name", result.name],
+ ["kind", result.kind],
+ ["path", result.file],
+ ["chunk_kind", result.chunkKind],
+ ["rev", result.introducedRev],
+ ["stale", result.stale ? "true" : null],
+ ]));
+
+ lines.push(llmLine("edges", [
+ ["called_by", String(result.calledBy ?? 0)],
+ ["calls", String(result.calls ?? 0)],
+ ["contains", String(result.contains ?? 0)],
+ ["history", String(result.historyLength ?? 0)],
+ ]));
+
+ if (result.container) {
+ lines.push(llmLine("container", [
+ ["kind", result.container.kind],
+ ["name", result.container.name],
+ ]));
+ }
+
+ if (result.signature) lines.push(llmLine("signature", [["text", result.signature]]));
+ if (result.docstring) lines.push(llmLine("docstring", [["text", result.docstring]]));
+
+ for (const call of result.callList ?? []) {
+ lines.push(llmLine("call", [
+ ["name", call.name],
+ ["kind", call.kind],
+ ["path", relativePath(call.path)],
+ ["resolved", call.resolved ? null : "false"],
+ ]));
+ }
+
+ for (const diagnostic of result.diagnostics ?? []) {
+ lines.push(llmLine("diagnostic", [
+ ["code", diagnostic.code],
+ ["message", diagnostic.message],
+ ]));
+ }
+
+ return lines;
+}
diff --git a/ix-cli/src/cli/llm.ts b/ix-cli/src/cli/llm.ts
index c527fa9c..5339010e 100644
--- a/ix-cli/src/cli/llm.ts
+++ b/ix-cli/src/cli/llm.ts
@@ -82,9 +82,19 @@ export function llmError(
return llmLine("error", [["code", code], ["message", message], ...fieldEntries(extra)]);
}
-/** Print rendered lines, skipping any that are empty. */
+/**
+ * Print rendered lines, skipping only the ones that were omitted.
+ *
+ * `!= null`, not truthiness: `read` pushes raw source through here after a
+ * `content lines=<n>` header, and a blank source line is `""`. Dropping those
+ * left the header counting lines that never reached stdout, so a consumer
+ * honouring the count ate the following records as source. Nothing else can
+ * arrive empty — every renderer builds its lines with a record kind, and
+ * `llmLine` only returns `""` for a null kind with no surviving fields, which
+ * no caller does.
+ */
export function printLlmLines(lines: Array<string | null | undefined>): void {
for (const line of lines) {
- if (line) console.log(line);
+ if (line != null) console.log(line);
}
}