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
perf(cli): stop paying for JSON indentation nobody reads (#686)
Ian Hock544c6057945b
diff --git a/ix-cli/src/cli/__tests__/format.test.ts b/ix-cli/src/cli/__tests__/format.test.tsindex 7b09ab64..4e3481cd 100644--- a/ix-cli/src/cli/__tests__/format.test.ts+++ b/ix-cli/src/cli/__tests__/format.test.ts@@ -282,7 +282,7 @@ describe("formatDecisions", () => {{ id: "abc-123", kind: "decision", attrs: { title: "Use ArangoDB", rationale: "Supports MVCC" } }];formatDecisions(decisions, "json");- expect(spy).toHaveBeenCalledWith(JSON.stringify(decisions, null, 2));+ expect(spy).toHaveBeenCalledWith(JSON.stringify(decisions));spy.mockRestore();});@@ -312,7 +312,7 @@ describe("formatTextResults", () => {const spy = vi.spyOn(console, "log").mockImplementation(() => {});const results = [{ path: "src/foo.ts", line_start: 42, line_end: 42, snippet: "const foo = bar;", engine: "ripgrep", score: 1.0 }];formatTextResults(sliceRanked(results, 20), "json");- expect(spy).toHaveBeenCalledWith(JSON.stringify(results, null, 2));+ expect(spy).toHaveBeenCalledWith(JSON.stringify(results));spy.mockRestore();});diff --git a/ix-cli/src/cli/__tests__/json-output-shape.test.ts b/ix-cli/src/cli/__tests__/json-output-shape.test.tsnew file mode 100644index 00000000..70d5eab2--- /dev/null+++ b/ix-cli/src/cli/__tests__/json-output-shape.test.ts@@ -0,0 +1,105 @@+// Copyright 2026 Ix Infrastructure Inc.++import { Command } from "commander";+import { afterEach, describe, expect, it, vi } from "vitest";++import { printJson, setPrettyJson } from "../format.js";+import { registerOssCommands } from "../register/oss.js";++const payload = { name: "resolveWorkspaceRoot", path: "src/cli/config.ts", lines: [322, 342] };++function withTty<T>(isTTY: boolean | undefined, fn: () => T): T {+ const original = Object.getOwnPropertyDescriptor(process.stdout, "isTTY");+ Object.defineProperty(process.stdout, "isTTY", { value: isTTY, configurable: true });+ try {+ return fn();+ } finally {+ if (original) Object.defineProperty(process.stdout, "isTTY", original);+ else delete (process.stdout as { isTTY?: boolean }).isTTY;+ }+}++function captured(fn: () => void): string {+ const spy = vi.spyOn(console, "log").mockImplementation(() => {});+ try {+ fn();+ return spy.mock.calls.map((call) => String(call[0])).join("\n");+ } finally {+ spy.mockRestore();+ }+}++afterEach(() => setPrettyJson(false));++describe("printJson", () => {+ it("is compact when stdout is not a terminal", () => {+ const out = withTty(undefined, () => captured(() => printJson(payload)));+ expect(out).toBe(JSON.stringify(payload));+ expect(out).not.toContain("\n");+ });++ it("indents when a person is watching", () => {+ const out = withTty(true, () => captured(() => printJson(payload)));+ expect(out).toBe(JSON.stringify(payload, null, 2));+ });++ it("indents off-TTY once --pretty has been recorded", () => {+ setPrettyJson(true);+ const out = withTty(undefined, () => captured(() => printJson(payload)));+ expect(out).toBe(JSON.stringify(payload, null, 2));+ });++ it("re-reads the destination on every call", () => {+ // The shape is a property of where the bytes are going, not of where the+ // process was when this module loaded.+ const piped = withTty(undefined, () => captured(() => printJson(payload)));+ const terminal = withTty(true, () => captured(() => printJson(payload)));+ expect(piped).not.toBe(terminal);+ });+});++describe("--pretty", () => {+ it("is offered by every command that can emit JSON", () => {+ const program = new Command();+ program.name("ix");+ registerOssCommands(program);++ const pending = [...program.commands];+ const missing: string[] = [];+ while (pending.length > 0) {+ const command = pending.shift()!;+ pending.push(...command.commands);+ const format = command.options.find((option) => option.long === "--format");+ if (!format?.argChoices?.includes("json")) continue;+ if (!command.options.some((option) => option.long === "--pretty")) missing.push(command.name());+ }+ expect(missing).toEqual([]);+ });++ it("is not offered by commands with no JSON to shape", () => {+ const program = new Command();+ program.name("ix");+ registerOssCommands(program);++ const upgrade = program.commands.find((command) => command.name() === "upgrade");+ expect(upgrade?.options.some((option) => option.long === "--pretty")).toBe(false);+ });++ it("reaches the renderers through the root preAction hook", async () => {+ const program = new Command();+ program.name("ix").exitOverride();+ registerOssCommands(program);+ program+ .command("probe")+ .option("--pretty")+ .action(() => {});++ await program.parseAsync(["probe", "--pretty"], { from: "user" });+ const out = withTty(undefined, () => captured(() => printJson(payload)));+ expect(out).toBe(JSON.stringify(payload, null, 2));++ await program.parseAsync(["probe"], { from: "user" });+ const plain = withTty(undefined, () => captured(() => printJson(payload)));+ expect(plain).toBe(JSON.stringify(payload));+ });+});diff --git a/ix-cli/src/cli/commands/callers.ts b/ix-cli/src/cli/commands/callers.tsindex 1c9c273f..96d90e00 100644--- a/ix-cli/src/cli/commands/callers.ts+++ b/ix-cli/src/cli/commands/callers.ts@@ -6,7 +6,7 @@ import type { Command } from "commander";import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint, resolveWorkspaceRoot } from "../config.js";-import { formatEdgeResults, relativePath, sliceEdgeResults } from "../format.js";+import { formatEdgeResults, printJson, relativePath, sliceEdgeResults } from "../format.js";import { parsePickOption } from "../options.js";import { resolveFileOrReport, printResolved } from "../resolve.js";import { stderr } from "../stderr.js";@@ -84,7 +84,7 @@ export function registerCallersCommand(program: Command): void {return;}if (opts.format === "json") {- console.log(JSON.stringify({+ printJson({results: textResults,resultSource: "text",resolvedTarget: target,@@ -96,7 +96,7 @@ export function registerCallersCommand(program: Command): void {code: "text_fallback_used",message: "No graph-backed CALLS/REFERENCES edges found. If files were ingested before extraction was added, run: ix ingest --force --recursive .",}],- }, null, 2));+ });} else {stderr(chalk.dim("No graph-backed CALLS/REFERENCES edges found. Showing text-based candidate usages."));stderr(chalk.dim("Tip: if files were ingested before CALLS extraction, run: ix ingest --force --recursive .\n"));diff --git a/ix-cli/src/cli/commands/context.ts b/ix-cli/src/cli/commands/context.tsindex d81187ef..5f239bef 100644--- a/ix-cli/src/cli/commands/context.ts+++ b/ix-cli/src/cli/commands/context.ts@@ -25,6 +25,7 @@ import { parseBudgetOption, parsePickOption, parseRevisionOption } from "../optiimport { resolveFileOrReport } from "../resolve.js";import { createStaleProbe, hasCompletedSourceGraphBaseline } from "../stale.js";import { renderNote, renderSection, renderWarning, renderWarningErr, reportFailure } from "../ui.js";+import { printJson } from "../format.js";/** The `--max-*` knobs that bound a bundle. */interface BudgetSnapshot {@@ -914,7 +915,7 @@ export function renderInvestigationList();}if (format === "json") {- console.log(JSON.stringify({ investigations: summaries, skipped }, null, 2));+ printJson({ investigations: summaries, skipped });return;}if (format === "llm") {@@ -1070,7 +1071,7 @@ export function renderSavedInvestigation(id: string, format: string): void {const saved = loadInvestigation(id, format);if (!saved) return;if (format === "json") {- console.log(JSON.stringify(saved, null, 2));+ printJson(saved);return;}if (format === "llm") {@@ -1300,7 +1301,7 @@ export function renderInvestigationDiff(const diff = diffInvestigations(saved, fresh, requestedBudgets);if (format === "json") {- console.log(JSON.stringify(diff, null, 2));+ printJson(diff);return;}if (format === "llm") {@@ -1836,7 +1837,7 @@ function rankEvidence(input: {export function renderBundle(bundle: ContextBundle, format: string): void {if (format === "json") {- console.log(JSON.stringify(bundle, null, 2));+ printJson(bundle);return;}if (format === "llm") {diff --git a/ix-cli/src/cli/commands/depends.ts b/ix-cli/src/cli/commands/depends.tsindex 114ae1eb..da1968c9 100644--- a/ix-cli/src/cli/commands/depends.ts+++ b/ix-cli/src/cli/commands/depends.ts@@ -5,7 +5,7 @@ import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";import { resolveFileOrReport, printResolved, isRawId } from "../resolve.js";-import { compactTreeNode, relativePath } from "../format.js";+import { compactTreeNode, relativePath, printJson } from "../format.js";import { llmLine, llmShortId } from "../llm.js";import { parsePickOption } from "../options.js";@@ -250,7 +250,7 @@ export function registerDependsCommand(program: Command): void {output.diagnostics = output.diagnostics ?? [];output.diagnostics.push({ code: "truncated", message: `Traversal truncated (depth: ${maxDepth}, node cap: ${maxNodes}).` });}- console.log(JSON.stringify(output, null, 2));+ printJson(output);return;}diff --git a/ix-cli/src/cli/commands/diff.ts b/ix-cli/src/cli/commands/diff.tsindex 0a6260cf..4ea72333 100644--- a/ix-cli/src/cli/commands/diff.ts+++ b/ix-cli/src/cli/commands/diff.ts@@ -11,7 +11,7 @@ import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";import { resolveFileOrReport, printResolved, type ResolvedEntity } from "../resolve.js";-import { formatDiff, relativePath } from "../format.js";+import { formatDiff, relativePath, printJson } from "../format.js";import { llmLine } from "../llm.js";import { reportFailure } from "../ui.js";import { parsePickOption } from "../options.js";@@ -511,7 +511,7 @@ export function registerDiffCommand(program: Command): void {const result: any = await client.diff(from, to, { summary: true, entityId });if (opts.format === "json") {- console.log(JSON.stringify(compactDiffResult(result), null, 2));+ printJson(compactDiffResult(result));} else if (opts.format === "llm") {console.log(renderDiffSummaryLlm(result));} else {@@ -574,7 +574,7 @@ export function registerDiffCommand(program: Command): void {if (displaySpan) {jsonResult.lineSpan = displaySpan;}- console.log(JSON.stringify(jsonResult, null, 2));+ printJson(jsonResult);} else {console.log(chalk.cyan.bold(`\nDiff: rev ${from} → ${to}`));if (diffLines.length === 0) {@@ -627,7 +627,7 @@ export function registerDiffCommand(program: Command): void {c.sourceContent = afterSource ?? beforeSource;}}- console.log(JSON.stringify(compactDiffResult(result), null, 2));+ printJson(compactDiffResult(result));} else {await formatDiffContent(result);}@@ -648,14 +648,14 @@ export function registerDiffCommand(program: Command): void {const changeCount = diffLines.filter(l => l.startsWith("+") || l.startsWith("-")).length;if (opts.format === "json") {- console.log(JSON.stringify({+ printJson({...compactDiffResult(result),textualChanges: {detected: true,lineChanges: changeCount,note: "Textual changes detected but not captured by graph parser (e.g. comments, whitespace).",},- }, null, 2));+ });} else {const name = resolved.name ?? fileUri;console.log(chalk.yellow(`${name} modified (${changeCount} textual changes — not captured by parser)`));@@ -667,7 +667,7 @@ export function registerDiffCommand(program: Command): void {}if (opts.format === "json") {- console.log(JSON.stringify(compactDiffResult(result), null, 2));+ printJson(compactDiffResult(result));} else if (opts.format === "llm") {formatDiff(result, "llm");} else {diff --git a/ix-cli/src/cli/commands/doctor.ts b/ix-cli/src/cli/commands/doctor.tsindex 1a30a845..86307000 100644--- a/ix-cli/src/cli/commands/doctor.ts+++ b/ix-cli/src/cli/commands/doctor.ts@@ -22,6 +22,7 @@ import { backendCeiling, isNewer, readBackendHealth } from "./upgrade.js";import { loadIngestBaseline } from "../ingest-baseline.js";import { isCloudReady } from "../remote.js";import { hasCompletedMapBaseline } from "../stale.js";+import { printJson } from "../format.js";interface CheckResult {ok: boolean;@@ -392,7 +393,7 @@ export function registerDoctorCommand(program: Command): void {}if (opts.format === "json") {- console.log(JSON.stringify({ healthy: !hasFailure, hasWarnings: hasWarning, checks: results }, null, 2));+ printJson({ healthy: !hasFailure, hasWarnings: hasWarning, checks: results });return;}diff --git a/ix-cli/src/cli/commands/entity.ts b/ix-cli/src/cli/commands/entity.tsindex 8cbc768f..cedf59dc 100644--- a/ix-cli/src/cli/commands/entity.ts+++ b/ix-cli/src/cli/commands/entity.ts@@ -4,7 +4,7 @@ import type { Command } from "commander";import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";-import { lineSpan, relativePath, rowLocation, stripNulls } from "../format.js";+import { lineSpan, relativePath, rowLocation, stripNulls, printJson } from "../format.js";import { llmLine, llmShortId } from "../llm.js";/** Render entity details as llm records: a header line then one `edge` row per edge. */@@ -43,7 +43,7 @@ export function registerEntityCommand(program: Command): void {const resolvedId = await client.resolvePrefix(id);const result = await client.entity(resolvedId);if (opts.format === "json") {- console.log(JSON.stringify(compactEntity(result), null, 2));+ printJson(compactEntity(result));} else if (opts.format === "llm") {for (const line of renderEntityLlm(result)) console.log(line);} else {diff --git a/ix-cli/src/cli/commands/explain.ts b/ix-cli/src/cli/commands/explain.tsindex ab56df36..521eed96 100644--- a/ix-cli/src/cli/commands/explain.ts+++ b/ix-cli/src/cli/commands/explain.ts@@ -3,7 +3,7 @@import type { Command } from "commander";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";-import { formatExplain, relativePath, type ExplainResult, type EntityRef, type Diagnostic } from "../format.js";+import { formatExplain, relativePath, printJson, type ExplainResult, type EntityRef, type Diagnostic } from "../format.js";import { resolveFileOrReport, isRawId } from "../resolve.js";import { isFileStale } from "../stale.js";import { collectFacts } from "../explain/facts.js";@@ -53,7 +53,7 @@ export function registerExplainCommand(program: Command): void {rendered,};if (facts.diagnostics.length > 0) output.diagnostics = facts.diagnostics;- console.log(JSON.stringify(output, null, 2));+ printJson(output);} else {if (facts.stale) {renderWarning("Source has changed since last ingest. Run ix map to update.");@@ -217,7 +217,7 @@ async function rawExplain(output.stale = true;output.warning = "Results may be stale; file has changed since last ingest.";}- console.log(JSON.stringify(output, null, 2));+ printJson(output);} else {if (stale) renderWarning("Source has changed since last ingest. Run ix map to update.");formatExplain(result, "text");diff --git a/ix-cli/src/cli/commands/history.ts b/ix-cli/src/cli/commands/history.tsindex 0a4b4e57..0e371bb3 100644--- a/ix-cli/src/cli/commands/history.ts+++ b/ix-cli/src/cli/commands/history.ts@@ -5,7 +5,7 @@ import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";import { resolveFileOrReport, printResolved } from "../resolve.js";-import { relativePath } from "../format.js";+import { relativePath, printJson } from "../format.js";import { llmLine } from "../llm.js";import { parsePickOption } from "../options.js";@@ -56,7 +56,7 @@ export function registerHistoryCommand(program: Command): void {if (opts.format === "json") {const patches = allPatches;- console.log(JSON.stringify({+ printJson({resolvedTarget: { kind: resolved.kind, name: resolved.name, path: relativePath(resolved.path) },patches: patches.map((p: any) => ({rev: p.rev ?? p.data?.rev,@@ -64,7 +64,7 @@ export function registerHistoryCommand(program: Command): void {intent: (p.data?.intent ?? p.intent) || undefined,source: relativePath(p.data?.source?.uri) ?? undefined,})),- }, null, 2));+ });} else {const patches = Array.isArray(result) ? result : (result as any)?.patches ?? [];if (patches.length === 0) {diff --git a/ix-cli/src/cli/commands/impact.ts b/ix-cli/src/cli/commands/impact.tsindex 4d6ddebf..a4a23285 100644--- a/ix-cli/src/cli/commands/impact.ts+++ b/ix-cli/src/cli/commands/impact.ts@@ -8,7 +8,7 @@ import { getEndpoint } from "../config.js";import { resolveFileOrReport, 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 { lineSpan, rowLocation, stripNulls } from "../format.js";+import { lineSpan, printJson, rowLocation, stripNulls } from "../format.js";import { llmLine } from "../llm.js";import { parsePickOption } from "../options.js";@@ -369,39 +369,35 @@ async function containerImpact(const risk = inferRiskSemantics(riskFacts);if (isJson) {- console.log(- JSON.stringify(- stripNulls({- resolvedTarget: { kind: target.kind, name: target.name },- depth,- systemPath: systemPathMapped.length > 0 ? systemPathMapped : undefined,- riskSummary: risk.riskSummary,- riskLevel: risk.riskLevel,- riskCategory: risk.category,- atRiskBehavior: risk.behaviorAtRisk,- nextStep: risk.nextStep || undefined,- flowPropagation: risk.flowPropagation || undefined,- summary: {- members: members.length,- directImporters: directImporters.length,- directDependents: directDependents.length,- memberLevelCallers: totalMemberCallers,- },- topImpactedMembers: topMembers.length > 0 ? topMembers : undefined,- propagationBuckets: propagationBuckets.length > 0 ? propagationBuckets.map((b) => ({- region: b.region.name,- regionKind: b.region.kind,- count: b.members.length,- members: b.members.slice(0, 5).map((m) => ({ name: m.name, kind: m.kind })),- })) : undefined,- decisions: decisions.length > 0 ? decisions : undefined,- tasks: tasks.length > 0 ? tasks : undefined,- bugs: bugs.length > 0 ? bugs : undefined,- diagnostics: diagnostics.length > 0 ? diagnostics : undefined,- }),- null,- 2- )+ printJson(+ stripNulls({+ resolvedTarget: { kind: target.kind, name: target.name },+ depth,+ systemPath: systemPathMapped.length > 0 ? systemPathMapped : undefined,+ riskSummary: risk.riskSummary,+ riskLevel: risk.riskLevel,+ riskCategory: risk.category,+ atRiskBehavior: risk.behaviorAtRisk,+ nextStep: risk.nextStep || undefined,+ flowPropagation: risk.flowPropagation || undefined,+ summary: {+ members: members.length,+ directImporters: directImporters.length,+ directDependents: directDependents.length,+ memberLevelCallers: totalMemberCallers,+ },+ topImpactedMembers: topMembers.length > 0 ? topMembers : undefined,+ propagationBuckets: propagationBuckets.length > 0 ? propagationBuckets.map((b) => ({+ region: b.region.name,+ regionKind: b.region.kind,+ count: b.members.length,+ members: b.members.slice(0, 5).map((m) => ({ name: m.name, kind: m.kind })),+ })) : undefined,+ decisions: decisions.length > 0 ? decisions : undefined,+ tasks: tasks.length > 0 ? tasks : undefined,+ bugs: bugs.length > 0 ? bugs : undefined,+ diagnostics: diagnostics.length > 0 ? diagnostics : undefined,+ }),);} else if (format === "llm") {const lines = [@@ -514,43 +510,39 @@ async function leafImpact(const risk = inferRiskSemantics(riskFacts);if (isJson) {- console.log(- JSON.stringify(- stripNulls({- resolvedTarget: { kind: target.kind, name: target.name },- depth,- systemPath: systemPathMapped.length > 0 ? systemPathMapped : undefined,- riskSummary: risk.riskSummary,- riskLevel: risk.riskLevel,- riskCategory: risk.category,- atRiskBehavior: risk.behaviorAtRisk,- nextStep: risk.nextStep || undefined,- flowPropagation: risk.flowPropagation || undefined,- summary: {- callers: callersResult.nodes.length,- callees: calleesResult.nodes.length,- },- callerList: callersResult.nodes.length > 0 ? callersResult.nodes.map((n: any) => ({- kind: n.kind,- name: n.name || n.attrs?.name || "(unnamed)",- })) : undefined,- calleeList: calleesResult.nodes.length > 0 ? calleesResult.nodes.map((n: any) => ({- kind: n.kind,- name: n.name || n.attrs?.name || "(unnamed)",- })) : undefined,- propagationBuckets: propagationBuckets.length > 0 ? propagationBuckets.map((b) => ({- region: b.region.name,- regionKind: b.region.kind,- count: b.members.length,- members: b.members.slice(0, 5).map((m) => ({ name: m.name, kind: m.kind })),- })) : undefined,- decisions: decisions.length > 0 ? decisions : undefined,- tasks: tasks.length > 0 ? tasks : undefined,- bugs: bugs.length > 0 ? bugs : undefined,- }),- null,- 2- )+ printJson(+ stripNulls({+ resolvedTarget: { kind: target.kind, name: target.name },+ depth,+ systemPath: systemPathMapped.length > 0 ? systemPathMapped : undefined,+ riskSummary: risk.riskSummary,+ riskLevel: risk.riskLevel,+ riskCategory: risk.category,+ atRiskBehavior: risk.behaviorAtRisk,+ nextStep: risk.nextStep || undefined,+ flowPropagation: risk.flowPropagation || undefined,+ summary: {+ callers: callersResult.nodes.length,+ callees: calleesResult.nodes.length,+ },+ callerList: callersResult.nodes.length > 0 ? callersResult.nodes.map((n: any) => ({+ kind: n.kind,+ name: n.name || n.attrs?.name || "(unnamed)",+ })) : undefined,+ calleeList: calleesResult.nodes.length > 0 ? calleesResult.nodes.map((n: any) => ({+ kind: n.kind,+ name: n.name || n.attrs?.name || "(unnamed)",+ })) : undefined,+ propagationBuckets: propagationBuckets.length > 0 ? propagationBuckets.map((b) => ({+ region: b.region.name,+ regionKind: b.region.kind,+ count: b.members.length,+ members: b.members.slice(0, 5).map((m) => ({ name: m.name, kind: m.kind })),+ })) : undefined,+ decisions: decisions.length > 0 ? decisions : undefined,+ tasks: tasks.length > 0 ? tasks : undefined,+ bugs: bugs.length > 0 ? bugs : undefined,+ }),);} else if (format === "llm") {const toRef = (kind: string) => (n: any) =>diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.tsindex faaeb3c1..57fa0dd7 100644--- a/ix-cli/src/cli/commands/ingest.ts+++ b/ix-cli/src/cli/commands/ingest.ts@@ -41,6 +41,7 @@ import {transformPRComment,transformCommit,} from '../github/transform.js';+import { printJson } from '../format.js';// ---------------------------------------------------------------------------// File discovery// ---------------------------------------------------------------------------@@ -3547,7 +3548,7 @@ export async function ingestFiles(}if (opts.format === 'json') {- console.log(JSON.stringify({+ printJson({filesProcessed: filesDiscovered,filesChanged,patchesApplied,@@ -3592,7 +3593,7 @@ export async function ingestFiles([...langParseMs.entries()].map(([lang, s]) => [lang, { ms: Math.round(s.ms), files: s.files }])),resolveStats,- }, null, 2));+ });} else if (opts.printSummary !== false) {console.log(chalk.bold('\nIngest summary'));console.log(` processed: ${patchesApplied} files (${elapsed}s)`);@@ -3775,7 +3776,7 @@ async function ingestGitHub(opts: {const elapsed = ((performance.now() - start) / 1000).toFixed(2);if (opts.format === 'json') {- console.log(JSON.stringify({+ printJson({source: `${repo.owner}/${repo.repo}`,issues: data.issues.length,pullRequests: data.pullRequests.length,@@ -3784,7 +3785,7 @@ async function ingestGitHub(opts: {rev: result.rev,status: result.status,elapsedSeconds: parseFloat(elapsed),- }, null, 2));+ });} else {console.log(chalk.bold('\nGitHub ingest summary'));console.log(` repo: ${repo.owner}/${repo.repo}`);diff --git a/ix-cli/src/cli/commands/inventory.ts b/ix-cli/src/cli/commands/inventory.tsindex e7c9eb0d..4a3d34c2 100644--- a/ix-cli/src/cli/commands/inventory.ts+++ b/ix-cli/src/cli/commands/inventory.ts@@ -6,7 +6,7 @@ import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";import { resolveWorkspaceId } from "../bootstrap.js";import { resolveReadSystemId } from "../resolve.js";-import { relativePath } from "../format.js";+import { relativePath, printJson } from "../format.js";import { llmLine } from "../llm.js";import { normalizePathSeparators } from "../path-match.js";@@ -140,7 +140,7 @@ Examples:byFile: grouped,};if (ungrouped.length > 0) output.ungrouped = ungrouped;- console.log(JSON.stringify(output, null, 2));+ printJson(output);return;}diff --git a/ix-cli/src/cli/commands/locate.ts b/ix-cli/src/cli/commands/locate.tsindex 27b94b2c..436dae0b 100644--- a/ix-cli/src/cli/commands/locate.ts+++ b/ix-cli/src/cli/commands/locate.ts@@ -9,7 +9,7 @@ import {} from "../resolve.js";import { isFileStale } from "../stale.js";import { stderr } from "../stderr.js";-import { relativePath } from "../format.js";+import { relativePath, printJson } from "../format.js";import { llmLine, llmError, llmShortId } from "../llm.js";import { parsePickOption } from "../options.js";import { getEffectiveSystemPath, hasMapData } from "../hierarchy.js";@@ -209,13 +209,13 @@ async function resolveWithAmbiguity(if (result.ambiguous) {if (format === "json") {- console.log(JSON.stringify({+ printJson({resolvedTarget: null,resolutionMode: "ambiguous",candidates: result.result.candidates,systemPath: null,diagnostics: result.result.diagnostics ?? [],- }, null, 2));+ });} else if (format === "llm") {// The shared renderer: one record per candidate with kind, path and a// short id. This used to emit `candidates=1:config.ts,2:config.ts` --@@ -272,7 +272,7 @@ export function renderLocateLlm(output: LocateOutput, symbol: string): string[]function outputLocate(output: LocateOutput, symbol: string, format: string): void {if (format === "json") {- console.log(JSON.stringify(output, null, 2));+ printJson(output);return;}if (format === "llm") {diff --git a/ix-cli/src/cli/commands/map.ts b/ix-cli/src/cli/commands/map.tsindex 128bfcc7..33d98ca8 100644--- a/ix-cli/src/cli/commands/map.ts+++ b/ix-cli/src/cli/commands/map.ts@@ -4,7 +4,7 @@ import { type Command } from "commander";import chalk from "chalk";import { IxClient } from "../../client/api.js";import { clearMapBaseline, getEndpoint } from "../config.js";-import { roundFloat } from "../format.js";+import { roundFloat, printJson } from "../format.js";import { llmLine, llmError, llmShortId } from "../llm.js";import { bootstrap, resolveWorkspaceId } from "../bootstrap.js";import { formatFetchError } from "../errors.js";@@ -390,7 +390,7 @@ Examples:} catch (err: any) {const message = err?.message ?? "Invalid map path";if (opts.format === "json") {- console.log(JSON.stringify({ error: "invalid_map_path", message }, null, 2));+ printJson({ error: "invalid_map_path", message });} else if (opts.format === "llm") {console.log(llmError("invalid_map_path", message));} else {@@ -620,7 +620,7 @@ Examples:if (minConf > 0) regions = regions.filter(r => r.confidence >= minConf);if (opts.format === "json") {- console.log(JSON.stringify({+ printJson({file_count: result.file_count,region_count: regions.length,levels: result.levels,@@ -649,7 +649,7 @@ Examples:confidence: roundFloat(r.confidence),signals: r.dominant_signals,})),- }, null, 2));+ });return;}if (opts.format === "llm") {diff --git a/ix-cli/src/cli/commands/mcp.ts b/ix-cli/src/cli/commands/mcp.tsindex 641cacdc..c26d7605 100644--- a/ix-cli/src/cli/commands/mcp.ts+++ b/ix-cli/src/cli/commands/mcp.ts@@ -5,6 +5,7 @@ import chalk from "chalk";import { llmLine, type LlmValue } from "../llm.js";import type { DoctorReport, HostReport, InstallReport, Outcome } from "../../mcp/install.js";+import { printJson } from "../format.js";/** Symbol and colour per outcome, shared by install and doctor. */const OUTCOME_STYLE: Record<Outcome, { mark: string; paint: (text: string) => string }> = {@@ -49,7 +50,7 @@ function hostFields(host: HostReport): Array<[string, LlmValue]> {function renderInstall(report: InstallReport, format: string, dryRun: boolean): void {if (format === "json") {- console.log(JSON.stringify(report, null, 2));+ printJson(report);return;}if (format === "llm") {@@ -75,7 +76,7 @@ function renderInstall(report: InstallReport, format: string, dryRun: boolean):function renderDoctor(report: DoctorReport, format: string): void {if (format === "json") {- console.log(JSON.stringify(report, null, 2));+ printJson(report);return;}if (format === "llm") {diff --git a/ix-cli/src/cli/commands/overview.ts b/ix-cli/src/cli/commands/overview.tsindex d5792479..eabb54db 100644--- a/ix-cli/src/cli/commands/overview.ts+++ b/ix-cli/src/cli/commands/overview.ts@@ -6,7 +6,7 @@ import { getEndpoint } from "../config.js";import { resolveFileOrReport, printResolved } from "../resolve.js";import { getEffectiveSystemPath, getSystemPath, hasMapData } from "../hierarchy.js";import { humanizeLabel } from "../impact/risk-semantics.js";-import { relativePath } from "../format.js";+import { relativePath, printJson } from "../format.js";import { llmLine, type LlmValue } from "../llm.js";import { parsePickOption } from "../options.js";import { renderSection, renderKeyValue, renderNote, renderBreadcrumb } from "../ui.js";@@ -193,7 +193,7 @@ async function overviewContainer(};if (format === "json") {- console.log(JSON.stringify(result, null, 2));+ printJson(result);return;}@@ -329,7 +329,7 @@ async function overviewLeaf(};if (format === "json") {- console.log(JSON.stringify(result, null, 2));+ printJson(result);return;}diff --git a/ix-cli/src/cli/commands/rank.ts b/ix-cli/src/cli/commands/rank.tsindex a697eb04..d96e2bdb 100644--- a/ix-cli/src/cli/commands/rank.ts+++ b/ix-cli/src/cli/commands/rank.ts@@ -7,6 +7,7 @@ import { getEndpoint } from "../config.js";import { activeReadScope, ensureReadScope } from "../resolve.js";import { llmLine } from "../llm.js";import { normalizePathSeparators } from "../path-match.js";+import { printJson } from "../format.js";type Metric = "dependents" | "callers" | "importers" | "members";@@ -194,14 +195,14 @@ export function registerRankCommand(program: Command): void {if (opts.format === "llm") {for (const line of renderRankLlm(metric, opts.kind, opts.path ?? null, [], 0, ["No entities found for the given kind."])) console.log(line);} else if (isJson) {- console.log(JSON.stringify({+ printJson({metric,kind: opts.kind,scope: opts.path ?? null,results: [],summary: { evaluated: 0, totalCandidates: 0, returned: 0 },diagnostics: ["No entities found for the given kind."],- }, null, 2));+ });} else {console.log(chalk.dim("No entities found for the given kind."));}@@ -224,14 +225,14 @@ export function registerRankCommand(program: Command): void {if (opts.format === "llm") {for (const line of renderRankLlm(metric, opts.kind, opts.path ?? null, [], 0, [`No entities matched filters: ${filterDesc}.`])) console.log(line);} else if (isJson) {- console.log(JSON.stringify({+ printJson({metric,kind: opts.kind,scope: opts.path ?? null,results: [],summary: { evaluated: 0, totalCandidates: 0, returned: 0 },diagnostics: [`No entities matched filters: ${filterDesc}.`],- }, null, 2));+ });} else {console.log(chalk.dim(`No entities matched filters: ${filterDesc}.`));}@@ -250,14 +251,14 @@ export function registerRankCommand(program: Command): void {if (opts.format === "llm") {for (const line of renderRankLlm(metric, opts.kind, opts.path ?? null, results.map(r => ({ name: r.name, kind: r.kind, score: r.score })), candidates.length, diagnostics)) console.log(line);} else if (isJson) {- console.log(JSON.stringify({+ printJson({metric,kind: opts.kind,scope: scopeNeedle,results: results.map(r => ({ name: r.name, kind: r.kind, score: r.score })),summary: { evaluated: candidates.length, returned: results.length },diagnostics: diagnostics.length > 0 ? diagnostics : undefined,- }, null, 2));+ });} else {console.log(chalk.bold(`Top ${results.length} ${pluralize(opts.kind)} by ${metric}:`));const maxNameLen = Math.max(...results.map((r) => r.name.length), 1);diff --git a/ix-cli/src/cli/commands/read.ts b/ix-cli/src/cli/commands/read.tsindex b88c4bb1..c28ab92a 100644--- a/ix-cli/src/cli/commands/read.ts+++ b/ix-cli/src/cli/commands/read.ts@@ -9,7 +9,7 @@ import { absoluteFromSourceUri, getEndpoint, isReadablePath, readableRoots, resoimport { resolveEntityFull, activeReadScope, ensureReadScope } from "../resolve.js";import { stderr } from "../stderr.js";import { isFileStale } from "../stale.js";-import { relativePath } from "../format.js";+import { relativePath, printJson } from "../format.js";import { llmError, llmLine, llmShortId, printLlmLines } from "../llm.js";import { parsePickOption } from "../options.js";import { reportUnresolvedTarget } from "../ui.js";@@ -59,7 +59,7 @@ function guardReadable(absPath: string, explicitRoot: string | undefined, what:if (isReadablePath(absPath, explicitRoot)) return true;const message = `Refusing to read ${what} outside the workspace: ${absPath}`;if (format === "json") {- console.log(JSON.stringify({ error: "path_outside_workspace", message }, null, 2));+ printJson({ error: "path_outside_workspace", message });} else if (format === "llm") {console.log(llmError("path_outside_workspace", message));} else {@@ -74,7 +74,7 @@ function guardReadable(absPath: string, explicitRoot: string | undefined, what:function reportInvalidLineRange(target: string, format: string): void {const message = `Invalid line range in "${target}". Line numbers must start at 1 and the end must not precede the start.`;if (format === "json") {- console.log(JSON.stringify({ error: "invalid_line_range", message }, null, 2));+ printJson({ error: "invalid_line_range", message });} else if (format === "llm") {console.log(llmError("invalid_line_range", message));} else {@@ -238,7 +238,7 @@ export function outputResult(result: ReadResult, format: string): void {printLlmLines(renderReadLlm(result));} else if (format === "json") {const out = { ...result, path: relativePath(result.path) ?? result.path };- console.log(JSON.stringify(out, null, 2));+ printJson(out);} else {if (result.stale) stderr(chalk.yellow("⚠ File has changed since last ingest. Run ix map to update.\n"));if (result.targetType === "symbol" || result.targetType === "filename-match") {@@ -262,7 +262,7 @@ function outputAmbiguity(result: AmbiguityResult, target: string, format: stringif (format === "llm") {printLlmLines(renderReadAmbiguityLlm(result, target));} else if (format === "json") {- console.log(JSON.stringify(result, null, 2));+ printJson(result);} else {const label = result.targetType === "ambiguous-file" ? "file" : "symbol";stderr(`Ambiguous ${label} "${target}":`);diff --git a/ix-cli/src/cli/commands/savings.ts b/ix-cli/src/cli/commands/savings.tsindex bab0158f..94c805d8 100644--- a/ix-cli/src/cli/commands/savings.ts+++ b/ix-cli/src/cli/commands/savings.ts@@ -5,6 +5,7 @@ import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";import { llmLine, printLlmLines } from "../llm.js";+import { printJson } from "../format.js";interface CommandBreakdown {count: number;@@ -155,7 +156,7 @@ export function registerSavingsCommand(program: Command): void {if (opts.format === "json") {const pricing = PRICING[opts.model] ?? PRICING.opus;- console.log(JSON.stringify({+ printJson({...result,computed: {session: {@@ -169,7 +170,7 @@ export function registerSavingsCommand(program: Command): void {pricingModel: pricing.label,waterRateMlPer1kTokens: WATER_ML_PER_1K_TOKENS,},- }, null, 2));+ });return;}diff --git a/ix-cli/src/cli/commands/search.ts b/ix-cli/src/cli/commands/search.tsindex 3d091264..9a2dca0e 100644--- a/ix-cli/src/cli/commands/search.ts+++ b/ix-cli/src/cli/commands/search.ts@@ -5,7 +5,7 @@ import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";import { resolveWorkspaceId } from "../bootstrap.js";-import { formatNodes, relativePath } from "../format.js";+import { formatNodes, relativePath, printJson } from "../format.js";import { scoreCandidate, resolveReadSystemId } from "../resolve.js";import { applyRoleFilter, roleHint } from "../role-filter.js";import { stderr } from "../stderr.js";@@ -346,7 +346,7 @@ Examples:}if (opts.format === "json") {- console.log(JSON.stringify({+ printJson({results: trimmed.map((s, i) => ({id: s.node.id,name: s.node.name || (s.node.attrs as any)?.name || "(unnamed)",@@ -363,7 +363,7 @@ Examples:totalCandidates: rawNodes.length,},diagnostics,- }, null, 2));+ });} else {formatNodes(ranked, opts.format);if (pathWindowLimited) stderr(chalk.dim(diagnostics.find(d => d.code === "path_search_truncated")!.message));diff --git a/ix-cli/src/cli/commands/smells.ts b/ix-cli/src/cli/commands/smells.tsindex 3ac19fd9..aae3d6b1 100644--- a/ix-cli/src/cli/commands/smells.ts+++ b/ix-cli/src/cli/commands/smells.ts@@ -7,6 +7,7 @@ import { getEndpoint } from "../config.js";import { resolveWorkspaceId } from "../bootstrap.js";import { resolveReadSystemId } from "../resolve.js";import { llmLine, llmError, type LlmValue } from "../llm.js";+import { printJson } from "../format.js";interface SmellCandidate {file_id: string;@@ -77,7 +78,7 @@ Examples:}if (opts.format === "json") {const smells = result.smells ?? [];- console.log(JSON.stringify({+ printJson({count: smells.length,inference_version: "smell_v1",smells: smells.map((s: any) => ({@@ -85,7 +86,7 @@ Examples:entity_id: s.entity_id?.slice(0, 12),confidence: s.confidence,})),- }, null, 2));+ });return;}const smells = result.smells ?? [];@@ -140,7 +141,7 @@ Examples:signals: c.signals,})),};- console.log(JSON.stringify(compact, null, 2));+ printJson(compact);return;}diff --git a/ix-cli/src/cli/commands/stats.ts b/ix-cli/src/cli/commands/stats.tsindex b8ce9a18..a43a33d6 100644--- a/ix-cli/src/cli/commands/stats.ts+++ b/ix-cli/src/cli/commands/stats.ts@@ -7,6 +7,7 @@ import { getEndpoint } from "../config.js";import { resolveWorkspaceId } from "../bootstrap.js";import { resolveReadSystemId } from "../resolve.js";import { llmLine, llmError, type LlmValue } from "../llm.js";+import { printJson } from "../format.js";/** Render `ix stats` as llm records: one `nodes` line and one `edges` line. */export function renderStatsLlm(result: any): string[] {@@ -40,7 +41,7 @@ export function registerStatsCommand(program: Command): void {}if (opts.format === "json") {- console.log(JSON.stringify(result, null, 2));+ printJson(result);return;}diff --git a/ix-cli/src/cli/commands/status.ts b/ix-cli/src/cli/commands/status.tsindex 33d72875..70a6b5cf 100644--- a/ix-cli/src/cli/commands/status.ts+++ b/ix-cli/src/cli/commands/status.ts@@ -8,6 +8,7 @@ import { getEndpoint, resolveWorkspaceRoot } from "../config.js";import { detectStaleFiles } from "../stale.js";import { llmError, llmLine, printLlmLines } from "../llm.js";import { backendUnreachableError, isBackendUnreachable } from "../errors.js";+import { printJson } from "../format.js";interface StatusStaleInfo {graphCompleted: boolean;@@ -82,7 +83,7 @@ export function registerStatusCommand(program: Command): void {staleFiles: staleInfo?.staleFiles ?? 0,sampleChangedFiles: staleInfo?.sampleChangedFiles ?? [],};- console.log(JSON.stringify(result, null, 2));+ printJson(result);} else {renderSection("Status");renderKeyValue("Ix Memory", health.status);diff --git a/ix-cli/src/cli/commands/subsystems.ts b/ix-cli/src/cli/commands/subsystems.tsindex 3631c3c4..8e224eb1 100644--- a/ix-cli/src/cli/commands/subsystems.ts+++ b/ix-cli/src/cli/commands/subsystems.ts@@ -6,7 +6,7 @@ import { IxClient, type ListSubsystemsOptions } from "../../client/api.js";import { getEndpoint } from "../config.js";import { resolveWorkspaceId } from "../bootstrap.js";import { resolveReadSystemId } from "../resolve.js";-import { roundFloat } from "../format.js";+import { roundFloat, printJson } from "../format.js";import { llmLine, llmError, llmShortId } from "../llm.js";import { parsePickOption } from "../options.js";import { renderMapText, renderMapLlm, type MapRegion, type MapResult } from "./map.js";@@ -192,7 +192,7 @@ Examples:if (opts.format === "json") {if (opts.detailed) {- console.log(JSON.stringify(buildDetailedListPayload(filtered, result.pagination), null, 2));+ printJson(buildDetailedListPayload(filtered, result.pagination));} else {const compact = filtered.map(s => ({name: s.name,@@ -202,12 +202,12 @@ Examples:chunks_per_file: roundFloat(s.chunk_density),smell_files: s.smell_files,}));- console.log(JSON.stringify({ scores: compact }, null, 2));+ printJson({ scores: compact });}return;}if (opts.detailed) {- console.log(JSON.stringify(buildDetailedListPayload(filtered, result.pagination), null, 2));+ printJson(buildDetailedListPayload(filtered, result.pagination));return;}printScores(filtered);@@ -225,7 +225,7 @@ Examples:const body = parseErrorBody(err);if (body) {if (opts.format === "json") {- console.log(JSON.stringify(body, null, 2));+ printJson(body);process.exitCode = 1;return;}@@ -264,7 +264,7 @@ Examples:const score = (scoreResult.scores ?? []).find((candidate) => candidate.region_id === result.target.id) ?? null;if (opts.format === "json") {- console.log(JSON.stringify(renderSubsystemExplanationJson(result, score), null, 2));+ printJson(renderSubsystemExplanationJson(result, score));return;}@@ -273,7 +273,7 @@ Examples:}if (opts.format === "json") {- console.log(JSON.stringify(compactMapResult(result), null, 2));+ printJson(compactMapResult(result));return;}diff --git a/ix-cli/src/cli/commands/text.ts b/ix-cli/src/cli/commands/text.tsindex 9841f711..579114de 100644--- a/ix-cli/src/cli/commands/text.ts+++ b/ix-cli/src/cli/commands/text.ts@@ -4,7 +4,7 @@ import { spawn } from "node:child_process";import { createInterface } from "node:readline";import path from "node:path";import type { Command } from "commander";-import { formatTextResults, sliceRanked, type TextResult } from "../format.js";+import { formatTextResults, printJson, sliceRanked, type TextResult } from "../format.js";import { isPathInsideResolvedRoot, resolveWorkspaceRoot } from "../config.js";import { stderr } from "../stderr.js";import { llmError } from "../llm.js";@@ -110,7 +110,7 @@ export function registerTextCommand(program: Command, executeRipgrep: RunRipgrepif (!isPathInsideResolvedRoot(root, searchPath)) {const message = `Search path is outside the workspace: ${opts.path}`;if (opts.format === "json") {- console.log(JSON.stringify({ error: "path_outside_workspace", message }, null, 2));+ printJson({ error: "path_outside_workspace", message });} else if (opts.format === "llm") {console.log(llmError("path_outside_workspace", message));} else {diff --git a/ix-cli/src/cli/commands/trace.ts b/ix-cli/src/cli/commands/trace.tsindex eaf44f1a..a0548d5a 100644--- a/ix-cli/src/cli/commands/trace.ts+++ b/ix-cli/src/cli/commands/trace.ts@@ -14,7 +14,7 @@ import {reportResolutionFailure,reportUnresolvedTarget,} from "../ui.js";-import { compactTreeNode, relativePath } from "../format.js";+import { compactTreeNode, relativePath, printJson } from "../format.js";import { llmLine, llmShortId, type LlmValue } from "../llm.js";import { parsePickOption } from "../options.js";@@ -524,7 +524,7 @@ export function registerTraceCommand(program: Command): void {},];}- console.log(JSON.stringify(output, null, 2));+ printJson(output);return;}@@ -594,26 +594,22 @@ export function registerTraceCommand(program: Command): void {// ── 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 },- },+ printJson(+ {+ 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;}@@ -694,7 +690,7 @@ export function registerTraceCommand(program: Command): void {output.diagnostics = diags;}- console.log(JSON.stringify(output, null, 2));+ printJson(output);return;}diff --git a/ix-cli/src/cli/format.ts b/ix-cli/src/cli/format.tsindex cbabc073..129df6fb 100644--- a/ix-cli/src/cli/format.ts+++ b/ix-cli/src/cli/format.ts@@ -5,6 +5,42 @@ import { llmLine, llmShortId } from "./llm.js";export type ResultSource = "graph" | "text" | "graph+text" | "heuristic";+// ── JSON output shape ──────────────────────────────────────────────────────++/**+ * Whether the caller explicitly asked for indented JSON.+ *+ * False means nobody asked, and the shape then follows the destination:+ * indented for a terminal, compact for anything else. Two spaces of indent per+ * level is roughly a fifth of a JSON payload, and the only reader that gains+ * anything from it is a human looking at a screen. Every other reader — a pipe+ * into `jq`, an agent's tool result, the MCP child process — pays tokens for+ * whitespace it discards.+ */+let prettyJsonRequested = false;++/** Record `--pretty`. Called once from the root `preAction` hook. */+export function setPrettyJson(pretty: boolean): void {+ prettyJsonRequested = pretty;+}++/**+ * The indent `JSON.stringify` should use, read at print time.+ *+ * Deliberately not cached: `process.stdout.isTTY` is what makes this decision,+ * and a test that redirects stdout would otherwise get the shape from whatever+ * the process looked like at import time.+ */+function jsonIndent(): number | undefined {+ if (prettyJsonRequested) return 2;+ return process.stdout.isTTY ? 2 : undefined;+}++/** Print a JSON payload on stdout, indented only when that helps someone. */+export function printJson(value: unknown): void {+ console.log(JSON.stringify(value, null, jsonIndent()));+}+// ── JSON optimization helpers ──────────────────────────────────────────────/**@@ -174,7 +210,7 @@ export function confidenceColor(score: number): (text: string) => string {export function formatContext(result: any, format: string): void {if (format === "json") {- console.log(JSON.stringify(result, null, 2));+ printJson(result);return;}@@ -257,7 +293,7 @@ export function renderNodesLlm(nodes: any[]): string[] {export function formatNodes(nodes: any[], format: string): void {if (format === "json") {- console.log(JSON.stringify(nodes, null, 2));+ printJson(nodes);return;}if (format === "llm") {@@ -290,7 +326,7 @@ export function formatNodes(nodes: any[], format: string): void {export function formatDecisions(nodes: any[], format: string): void {if (format === "json") {- console.log(JSON.stringify(nodes, null, 2));+ printJson(nodes);return;}if (nodes.length === 0) {@@ -319,7 +355,7 @@ const BUG_STATUS_ICONS: Record<string, string> = {export function formatBugs(nodes: any[], format: string): void {if (format === "json") {- console.log(JSON.stringify(nodes, null, 2));+ printJson(nodes);return;}if (nodes.length === 0) {@@ -358,7 +394,7 @@ export function formatPatches(patches: any[], format: string): void {timestamp: p.timestamp,source: relativePath(p.source?.uri) || undefined,}));- console.log(JSON.stringify(compact, null, 2));+ printJson(compact);return;}if (format === "llm") {@@ -383,7 +419,7 @@ export function formatPatches(patches: any[], format: string): void {export function formatIntents(intents: any[], format: string): void {if (format === "json") {- console.log(JSON.stringify(intents, null, 2));+ printJson(intents);return;}if (intents.length === 0) {@@ -449,7 +485,7 @@ export function renderDiffLlm(result: any): string[] {export function formatDiff(result: any, format: string): void {if (format === "json") {- console.log(JSON.stringify(result, null, 2));+ printJson(result);return;}if (format === "llm") {@@ -554,7 +590,7 @@ export function formatTextResults(slice: Slice<TextResult>, format: string): voi...r,path: relativePath(r.path) ?? r.path,}));- console.log(JSON.stringify(compact, null, 2));+ printJson(compact);return;}if (format === "llm") {@@ -585,7 +621,7 @@ export interface LocateResult {export function formatLocateResults(results: LocateResult[], format: string): void {if (format === "json") {- console.log(JSON.stringify(results, null, 2));+ printJson(results);return;}if (results.length === 0) {@@ -726,7 +762,7 @@ export function formatEdgeResults(unresolved: unresolvedCount,truncated: slice.truncated,};- console.log(JSON.stringify(output, null, 2));+ printJson(output);return;}if (nodes.length === 0) {@@ -770,7 +806,7 @@ export function renderConflictsLlm(conflicts: any[]): string[] {export function formatConflicts(conflicts: any[], format: string): void {if (format === "json") {- console.log(JSON.stringify(conflicts, null, 2));+ printJson(conflicts);return;}if (format === "llm") {@@ -857,7 +893,7 @@ export function formatExplain(result: ExplainResult, format: string): void {if (result.diagnostics && result.diagnostics.length > 0) {output.diagnostics = result.diagnostics;}- console.log(JSON.stringify(output, null, 2));+ printJson(output);return;}const shortId = result.id.slice(0, 8);diff --git a/ix-cli/src/cli/register/oss.ts b/ix-cli/src/cli/register/oss.tsindex 19b9eeb4..aad29156 100644--- a/ix-cli/src/cli/register/oss.ts+++ b/ix-cli/src/cli/register/oss.ts@@ -40,6 +40,7 @@ import { registerPatchesCommand } from "../commands/patches.js";import { registerMcpCommand } from "../commands/mcp.js";import { registerContextCommand } from "../commands/context.js";import { validateCliOptions } from "../options.js";+import { setPrettyJson } from "../format.js";import {BUILT_IN_DEFAULT_FORMAT,DEFAULT_FORMAT_CHOICES,@@ -92,7 +93,7 @@ const OPTION_CHOICES: Record<string, Record<string, string[]>> = {*/const ossCommands = new WeakSet<Command>();-function configureOssOptionChoices(root: Command): void {+function configureOssOptions(root: Command): void {const { format: defaultFormat, ignored } = resolveDefaultFormat(process.env,// Never let an unreadable or half-written config.yaml stop the CLI from@@ -113,11 +114,18 @@ function configureOssOptionChoices(root: Command): void {const visit = (command: Command): void => {ossCommands.add(command);const commandChoices = OPTION_CHOICES[command.name()] ?? {};+ let rendersJson = false;for (const option of command.options) {const choices = commandChoices[option.attributeName()]?? (option.long === "--format" ? [...DEFAULT_FORMAT_CHOICES] : undefined);if (choices) option.choices(choices);applyDefaultFormat(command, option, choices, defaultFormat);+ if (option.long === "--format" && (choices ?? []).includes("json")) rendersJson = true;+ }+ // Declared here rather than 32 times by hand, and only where it means+ // something: a command with no `--format json` has no JSON to shape.+ if (rendersJson && !command.options.some((option) => option.long === "--pretty")) {+ command.option("--pretty", "Indent JSON output (the default only when stdout is a terminal)");}for (const child of command.commands) visit(child);};@@ -195,9 +203,14 @@ export function registerOssCommands(program: Command): void {registerMcpCommand(program);registerContextCommand(program);- configureOssOptionChoices(program);+ configureOssOptions(program);program.hook("preAction", (_thisCommand, actionCommand) => {+ // Before anything prints. `--pretty` is a property of the run, not of a+ // payload, so the renderers read it from one place instead of threading a+ // flag through every signature that ends in a `console.log`.+ setPrettyJson(actionCommand.opts().pretty === true);+// OSS commands only. The rules below read an option's *shape* -- `<n>`// means a non-negative integer, `--min-confidence` means 0..1 -- which is// a claim about commands whose declarations live in this repo. A Prodiff --git a/ix-cli/src/cli/ui.ts b/ix-cli/src/cli/ui.tsindex 39b0dde6..5a419688 100644--- a/ix-cli/src/cli/ui.ts+++ b/ix-cli/src/cli/ui.ts@@ -10,7 +10,7 @@import chalk from "chalk";import { llmError, llmLine } from "./llm.js";-import { relativePath } from "./format.js";+import { printJson, relativePath } from "./format.js";import type { AmbiguousResult, ResolveResult, Suggestion } from "./resolve.js";// ── Brand palette ─────────────────────────────────────────────────────────────@@ -169,10 +169,10 @@ export function reportUnresolvedTarget(const message = unresolvedTargetMessage(target);const near = suggestions ?? [];if (format === "json") {- console.log(JSON.stringify({+ printJson({...unresolvedTargetRecord(target),...(near.length ? { suggestions: near } : {}),- }, null, 2));+ });} else if (format === "llm") {const lines = [llmError("unresolved_target", message), ...candidateLines(near, "suggestion")];if (near.length) {@@ -221,12 +221,12 @@ export function reportAmbiguousTarget(): void {const message = `Ambiguous symbol "${target}".`;if (format === "json") {- console.log(JSON.stringify({+ printJson({error: "ambiguous_target",message,candidates: result.candidates,diagnostics: result.diagnostics ?? [],- }, null, 2));+ });return;}if (format === "llm") {diff --git a/skills/ix/references/flags.md b/skills/ix/references/flags.mdindex ec2ecbda..72bef4e7 100644--- a/skills/ix/references/flags.md+++ b/skills/ix/references/flags.md@@ -89,6 +89,7 @@ Show methods/functions called by the given symbol (cross-file).| `--pick` | `<n>` | — | Pick Nth candidate from ambiguous results (1-based) || `--limit` | `<n>` | `50` | Max results to show || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |### `ix callers <symbol>`@@ -101,6 +102,7 @@ Show methods/functions that call the given symbol (cross-file).| `--pick` | `<n>` | — | Pick Nth candidate from ambiguous results (1-based) || `--limit` | `<n>` | `50` | Max results to show || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |### `ix config`@@ -135,6 +137,7 @@ List detected conflicts.| Flag | Value | Default | Effect ||---|---|---|---|| `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |### `ix contains <symbol>`@@ -147,6 +150,7 @@ Show members contained by the given entity (class, module, file).| `--pick` | `<n>` | — | Pick Nth candidate from ambiguous results (1-based) || `--limit` | `<n>` | `50` | Max results to show || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |### `ix context [target]`@@ -165,6 +169,7 @@ Build a bounded, deterministic context bundle for a symbol, file, or entity (or| `--max-tokens` | `<n>` | `1500` | Maximum tokens of evidence output (clamped to 500-200000) || `--max-chars` | `<n>` | — | Maximum characters of evidence output; overrides `--max-tokens` (clamped to 1000-1000000) || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal || `--out` | `<path>` | — | Write the JSON bundle to this file instead of stdout || `--save` | `<id>` | — | Persist the bundle as a resumable investigation state || `--resume` | `<id>` | — | Render a saved investigation state without a backend |@@ -183,6 +188,7 @@ Show upstream dependents of the given entity (full tree by default).| `--depth` | `<n>` | — | Cap traversal depth || `--cap` | `<n>` | — | Cap number of nodes visited || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal || `--include-tests` | — | off | Include test and fixture entities in results || `--tests-only` | — | off | Show only test and fixture entities |@@ -198,6 +204,7 @@ Show diff between two revisions, optionally scoped to a file or entity.| `--limit` | `<n>` | — | Max changes to return (default 100) || `--full` | — | off | Return all changes (no limit) || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal || `--kind` | `<kind>` | — | Filter target entity by kind || `--path` | `<path>` | — | Restrict to symbols from files matching this path substring || `--pick` | `<n>` | — | Pick Nth candidate from ambiguous results (1-based) |@@ -253,6 +260,7 @@ Check Ix system health — server, database, graph integrity.| Flag | Value | Default | Effect ||---|---|---|---|| `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |### `ix entity <id>`@@ -261,6 +269,7 @@ Get entity details with claims and edges.| Flag | Value | Default | Effect ||---|---|---|---|| `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |### `ix explain <symbol>`@@ -272,6 +281,7 @@ Explain an entity — infers role, importance, and structural context.| `--path` | `<path>` | — | Restrict to symbols from files matching this path substring || `--pick` | `<n>` | — | Pick Nth candidate from ambiguous results (1-based) || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal || `--raw` | — | off | Show raw metadata dump (legacy format) |### `ix help [topic]`@@ -297,6 +307,7 @@ Show provenance chain for a file or entity.| `--path` | `<path>` | — | Restrict to symbols from files matching this path substring || `--pick` | `<n>` | — | Pick Nth candidate from ambiguous results (1-based) || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |### `ix impact <target>`@@ -310,6 +321,7 @@ System risk analysis — what behavior is at risk if this changes.| `--depth` | `<n>` | `1` | Expansion depth for callers/importers (default 1, max 3) || `--limit` | `<n>` | `10` | Max top-impacted members to show || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |### `ix imported-by <symbol>`@@ -322,6 +334,7 @@ Show what imports the given entity.| `--pick` | `<n>` | — | Pick Nth candidate from ambiguous results (1-based) || `--limit` | `<n>` | `50` | Max results to show || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |### `ix imports <symbol>`@@ -334,6 +347,7 @@ Show what the given entity imports.| `--pick` | `<n>` | — | Pick Nth candidate from ambiguous results (1-based) || `--limit` | `<n>` | `50` | Max results to show || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |### `ix ingest [path]`@@ -349,6 +363,7 @@ Ingest source files or GitHub data into the knowledge graph.| `--limit` | `<n>` | `50` | Max items per category (default 50) || `--force` | — | off | Force re-ingest even if files are unchanged (useful after parser upgrades) || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal || `--root` | `<dir>` | — | Workspace root directory || `--debug` | — | `false` | Show phase timing breakdown || `--lang` | `<langs>` | — | Comma-separated languages to include (e.g. cpp,c or typescript). Aliases: c++=cpp, c#=csharp, py=python, ts=typescript, js=javascript |@@ -369,6 +384,7 @@ List entities by kind with optional path scoping.| `--path` | `<path>` | — | Filter by source file path substring || `--limit` | `<n>` | `50` | Max results || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |### `ix locate <symbol>`@@ -380,6 +396,7 @@ Resolve a symbol to its position in the codebase and system hierarchy.| `--path` | `<path>` | — | Restrict to results from files matching this path substring || `--pick` | `<n>` | — | Pick Nth candidate from ambiguous results (1-based) || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |### `ix map [path]`@@ -388,6 +405,7 @@ Map the architectural hierarchy of a codebase.| Flag | Value | Default | Effect ||---|---|---|---|| `--format` | `text\|json\|llm\|silent` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal || `--level` | `<n>` | — | Show only regions at this level (1=finest, higher=coarser) || `--min-confidence` | `<n>` | `0` | Only show regions above this confidence threshold (0-1) || `--max-items` | `<n>` | `10` | Max items to show per section in text output (default: 10) |@@ -419,6 +437,7 @@ Register `ix mcp` with the AI clients installed on this machine.| `--dry-run` | — | `false` | Report what would change without writing anything || `--force` | — | `false` | Replace a registration held by a different server || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |#### `ix mcp doctor`@@ -428,6 +447,7 @@ Check that `ix mcp` is registered and launchable from each client.|---|---|---|---|| `--host` | `<ids...>` | — | Only these hosts || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |### `ix overview <target>`@@ -439,6 +459,7 @@ Structural summary — what a target contains or what surrounds it.| `--path` | `<path>` | — | Restrict to symbols from files matching this path substring || `--pick` | `<n>` | — | Pick Nth candidate from ambiguous results (1-based) || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |### `ix patches`@@ -448,6 +469,7 @@ List recent patches.|---|---|---|---|| `--limit` | `<n>` | `50` | Maximum patches to return || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |### `ix query <question>`@@ -458,6 +480,7 @@ List recent patches.| `--as-of` | `<rev>` | — | Time-travel to a specific revision || `--depth` | `shallow\|standard\|deep` | `standard` | Query depth (shallow\|standard\|deep) || `--format` | `text\|json` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal || `--unsafe` | — | off | Enable query (can produce large outputs) |### `ix rank`@@ -473,6 +496,7 @@ Rank entities by graph-derived importance (dependents, callers, importers, membe| `--exclude-path` | `<path>` | — | Exclude entities whose source path contains this substring || `--exclude-kind` | `<kinds>` | — | Comma-separated kinds to exclude from results || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |### `ix read <target>`@@ -481,6 +505,7 @@ Read raw file content, line ranges, or symbol source code.| Flag | Value | Default | Effect ||---|---|---|---|| `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal || `--kind` | `<kind>` | — | Filter symbol by kind || `--path` | `<path>` | — | Restrict to symbols from files matching this path substring || `--pick` | `<n>` | — | Pick Nth candidate from ambiguous results (1-based) |@@ -508,6 +533,7 @@ Subcommands: `reset`.| `--detail` | — | off | Include per-command breakdown || `--model` | `opus\|sonnet\|haiku\|gpt-4o` | `opus` | Pricing model (opus\|sonnet\|haiku\|gpt-4o) || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |#### `ix savings reset`@@ -527,6 +553,7 @@ Search the knowledge graph by term — ranked by structural relevance.| `--path` | `<path>` | — | Filter results by file path (case-insensitive substring match). Keyword searches widen the candidate window up to 2000 nodes and warn if that bound is reached. || `--as-of` | `<rev>` | — | Search as of a specific revision || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal || `--include-tests` | — | off | Include test and fixture entities in results || `--tests-only` | — | off | Show only test and fixture entities || `--semantic` | — | off | Use vector-similarity (embedding) search instead of keyword matching |@@ -538,6 +565,7 @@ Detect architecture smells in the codebase.| Flag | Value | Default | Effect ||---|---|---|---|| `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal || `--orphan-max-connections` | `<n>` | `0` | Max connections for orphan files || `--god-module-chunks` | `<n>` | `20` | Min chunks for god module || `--god-module-fan` | `<n>` | `15` | Min fan-in/out for god module |@@ -551,6 +579,7 @@ Show graph statistics — node/edge counts by type.| Flag | Value | Default | Effect ||---|---|---|---|| `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal |### `ix status`@@ -559,6 +588,7 @@ Show Ix backend health and status.| Flag | Value | Default | Effect ||---|---|---|---|| `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal || `--root` | `<dir>` | — | Workspace root directory |### `ix subsystems [target]`@@ -568,6 +598,7 @@ Show the persisted architectural map saved by 'ix map'.| Flag | Value | Default | Effect ||---|---|---|---|| `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal || `--list` | — | off | List stored subsystem health scores instead of the persisted architecture map || `--detailed` | — | off | Include member files and enriched call/import edges (requires --list) || `--limit` | `<n>` | — | Max regions per page in detailed mode (default: 200 when auto-paging) |@@ -596,6 +627,7 @@ Fast lexical/text search across the codebase (uses ripgrep).| `--path` | `<dir>` | `.` | Restrict search to a workspace-relative directory || `--language` | `<lang>` | — | Filter by language (python, typescript, scala, etc.) || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal || `--root` | `<dir>` | — | Workspace root directory |### `ix trace <symbol>`@@ -613,6 +645,7 @@ Follow how it connects.| `--pick` | `<n>` | — | Pick Nth candidate from ambiguous results (1-based) || `--path` | `<path>` | — | Restrict to symbols from files matching this path substring || `--format` | `text\|json\|llm` | `text` | Output format — see [output-formats.md](output-formats.md) |+| `--pretty` | — | off | Indent JSON output; the default only when stdout is a terminal || `--include-tests` | — | off | Include test and fixture entities || `--tests-only` | — | off | Show only test and fixture entities |diff --git a/skills/ix/references/output-formats.md b/skills/ix/references/output-formats.mdindex 4aa0bd29..7e11deb4 100644--- a/skills/ix/references/output-formats.md+++ b/skills/ix/references/output-formats.md@@ -22,6 +22,12 @@ stored value.A command that does not implement the configured format keeps its own defaultrather than being handed one it cannot render — `query` renders `text` and`json` only, so `IX_FORMAT=llm` leaves it on `text`.+### JSON is compact unless a person is watching++`--format json` prints one line when stdout is not a terminal — a pipe, a+command substitution, an agent's tool result — and indents only when you are+reading it on screen. Indentation is whitespace a parser throws away, and it is+about a fifth of the payload. `--pretty` forces the indented shape anywhere.### Commands that accept `--format` but route `llm` to `text`