Skip to content

armgit / Ix

Public Imported from GitHub
0

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

feat(cli): let IX_FORMAT and config.format choose the default format (#682)

Ian Hock847b25999d4f
diff --git a/docs/llm-format.md b/docs/llm-format.md
index 04dc54c0..6ad50863 100644
--- a/docs/llm-format.md
+++ b/docs/llm-format.md
@@ -11,6 +11,29 @@ hand-written renderer emit compact records (see below); the rest route
`--format llm` to whichever existing format is most compact (usually `text`),
so consumers can pass the flag unconditionally without a per-command lookup.
+## Choosing it once
+
+`--format` on the command line always wins. When it is absent, the default is
+resolved in this order:
+
+1. `IX_FORMAT` — `text`, `json` or `llm`.
+2. `format` in `~/.ix/config.yaml`, i.e. `ix config set format llm`.
+3. `text`.
+
+A plugin or a shell profile can therefore set `IX_FORMAT=llm` once instead of
+appending the flag to every command it wraps. `ix config show` prints the
+stored value and says when `IX_FORMAT` is overriding it.
+
+Two things this deliberately does not do. It does not switch on whether stdout
+is a terminal: a script that has always parsed `text` would start receiving
+records on its next run, with nothing it could have done about it. And it does
+not apply to a command that has no `llm` renderer to switch to — `ix query`
+offers `text` and `json`, so it stays on `text` and says so in `--help`.
+
+An unrecognised value is ignored rather than fatal — it is read by every later
+command, so a typo would otherwise break all of them at once. The CLI says
+which value it ignored, on stderr, when a person is there to read it.
+
## Wire format
- **One record per line.** Newline-delimited, no nesting.
diff --git a/ix-cli/src/cli/__tests__/default-format.test.ts b/ix-cli/src/cli/__tests__/default-format.test.ts
new file mode 100644
index 00000000..ae5f684d
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/default-format.test.ts
@@ -0,0 +1,117 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { mkdtempSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { Command } from "commander";
+import { describe, expect, it, vi } from "vitest";
+
+import { resolveDefaultFormat } from "../default-format.js";
+import { registerOssCommands } from "../register/oss.js";
+
+const noConfig = () => undefined;
+
+describe("resolveDefaultFormat", () => {
+ it("falls back to text when nothing is configured", () => {
+ expect(resolveDefaultFormat({}, noConfig)).toEqual({ format: "text" });
+ });
+
+ it("reads IX_FORMAT", () => {
+ expect(resolveDefaultFormat({ IX_FORMAT: "llm" }, noConfig)).toEqual({ format: "llm" });
+ });
+
+ it("reads config.format when IX_FORMAT is unset", () => {
+ expect(resolveDefaultFormat({}, () => "json")).toEqual({ format: "json" });
+ });
+
+ it("lets IX_FORMAT outrank config.format", () => {
+ expect(resolveDefaultFormat({ IX_FORMAT: "llm" }, () => "json")).toEqual({ format: "llm" });
+ });
+
+ it("does not read config when IX_FORMAT already answered", () => {
+ const readConfig = vi.fn(() => "json");
+ resolveDefaultFormat({ IX_FORMAT: "llm" }, readConfig);
+ expect(readConfig).not.toHaveBeenCalled();
+ });
+
+ it("accepts a padded or capitalised value", () => {
+ expect(resolveDefaultFormat({ IX_FORMAT: " LLM " }, noConfig).format).toBe("llm");
+ });
+
+ it("ignores an empty value rather than reporting it", () => {
+ expect(resolveDefaultFormat({ IX_FORMAT: "" }, () => "llm")).toEqual({ format: "llm" });
+ });
+
+ it("reports an unrecognised value and falls through to the next source", () => {
+ expect(resolveDefaultFormat({ IX_FORMAT: "yaml" }, () => "llm")).toEqual({
+ format: "llm",
+ ignored: { source: "IX_FORMAT", value: "yaml" },
+ });
+ });
+
+ it("reports an unrecognised config value", () => {
+ expect(resolveDefaultFormat({}, () => "pretty")).toEqual({
+ format: "text",
+ ignored: { source: "config.format", value: "pretty" },
+ });
+ });
+
+ it("keeps the more specific of two unrecognised values", () => {
+ expect(resolveDefaultFormat({ IX_FORMAT: "yaml" }, () => "pretty")).toEqual({
+ format: "text",
+ ignored: { source: "IX_FORMAT", value: "yaml" },
+ });
+ });
+});
+
+/**
+ * The registrar is exercised through a real program because what matters is
+ * commander's resolution order: an explicit flag has to keep winning, and a
+ * command that does not offer the configured format has to keep its own.
+ */
+describe("the default a command ends up with", () => {
+ // An empty IX_HOME of its own, so the developer's real ~/.ix/config.yaml
+ // cannot decide what these assert. The env is read when the commands are
+ // registered, which is why each case re-registers rather than sharing one
+ // program.
+ const withEnv = async (env: Record<string, string>, argv: string[]) => {
+ const home = mkdtempSync(join(tmpdir(), "ix-format-"));
+ writeFileSync(join(home, "config.yaml"), "endpoint: http://localhost:8090\n");
+ const previous = { ...process.env };
+ Object.assign(process.env, { IX_HOME: home, ...env });
+ try {
+ const program = new Command();
+ let seen: string | undefined;
+ registerOssCommands(program);
+ const command = program.commands.find((c) => c.name() === argv[0])!;
+ command.action(function (this: Command) { seen = this.opts().format; });
+ await program.parseAsync(argv, { from: "user" });
+ return seen;
+ } finally {
+ for (const key of Object.keys({ IX_HOME: home, ...env })) delete process.env[key];
+ Object.assign(process.env, previous);
+ }
+ };
+
+ it("is text when nothing is set", async () => {
+ expect(await withEnv({}, ["search", "Widget"])).toBe("text");
+ });
+
+ it("is IX_FORMAT when it is set", async () => {
+ expect(await withEnv({ IX_FORMAT: "llm" }, ["search", "Widget"])).toBe("llm");
+ });
+
+ it("is still the flag when one is given", async () => {
+ expect(await withEnv({ IX_FORMAT: "llm" }, ["search", "Widget", "--format", "json"])).toBe("json");
+ });
+
+ it("stays text for a command that does not render llm", async () => {
+ // `query` offers text and json only.
+ expect(await withEnv({ IX_FORMAT: "llm" }, ["query", "who calls Widget"])).toBe("text");
+ });
+
+ it("ignores a value that is not a format", async () => {
+ expect(await withEnv({ IX_FORMAT: "yaml" }, ["search", "Widget"])).toBe("text");
+ });
+});
diff --git a/ix-cli/src/cli/commands/config.ts b/ix-cli/src/cli/commands/config.ts
index 04817506..4534a0b0 100644
--- a/ix-cli/src/cli/commands/config.ts
+++ b/ix-cli/src/cli/commands/config.ts
@@ -3,6 +3,12 @@
import type { Command } from "commander";
import chalk from "chalk";
import { loadConfig, saveConfig } from "../config.js";
+import {
+ BUILT_IN_DEFAULT_FORMAT,
+ DEFAULT_FORMAT_CHOICES,
+ isFormat,
+ resolveDefaultFormat,
+} from "../default-format.js";
/** Resolve a dotted key path into a config object and return [obj, lastKey]. */
function resolvePath(obj: any, key: string): [any, string] {
@@ -27,7 +33,7 @@ export function registerConfigCommand(program: Command): void {
const cfg = loadConfig();
console.log(chalk.bold("Ix Configuration\n"));
console.log(` endpoint ${chalk.cyan(cfg.endpoint)}`);
- console.log(` format ${chalk.cyan(cfg.format)}`);
+ console.log(` format ${chalk.cyan(cfg.format)}${formatOverrideNote(cfg.format)}`);
if (cfg.workspaces?.length) {
console.log(` workspaces`);
for (const ws of cfg.workspaces) {
@@ -68,6 +74,15 @@ export function registerConfigCommand(program: Command): void {
.command("set <key> <value>")
.description("Set a config value (e.g. ix config set user.name 'Alice')")
.action((key: string, value: string) => {
+ // `format` is the one key here that changes what every other command
+ // prints. A typo used to save silently and then do nothing at all, since
+ // an unrecognised value falls back to text.
+ if (key === "format" && !isFormat(value)) {
+ console.error(chalk.red(`Not a format: ${value}`));
+ console.error(`Choose one of: ${DEFAULT_FORMAT_CHOICES.join(", ")}`);
+ process.exitCode = 1;
+ return;
+ }
const cfg = loadConfig() as any;
const [obj, lastKey] = resolvePath(cfg, key);
obj[lastKey] = value;
@@ -75,3 +90,18 @@ export function registerConfigCommand(program: Command): void {
console.log(chalk.green("✓") + ` ${key} = ${chalk.cyan(value)}`);
});
}
+
+/**
+ * What `ix config show` adds beside a stored format that is not the one
+ * commands will actually use, because IX_FORMAT outranks it.
+ */
+function formatOverrideNote(stored: string): string {
+ const { format, ignored } = resolveDefaultFormat(process.env, () => stored);
+ if (ignored?.source === "IX_FORMAT") {
+ return chalk.dim(` (IX_FORMAT=${ignored.value} ignored: not a format)`);
+ }
+ if (format !== (stored || BUILT_IN_DEFAULT_FORMAT)) {
+ return chalk.dim(` (overridden by IX_FORMAT=${format})`);
+ }
+ return "";
+}
diff --git a/ix-cli/src/cli/default-format.ts b/ix-cli/src/cli/default-format.ts
new file mode 100644
index 00000000..90c6fff9
--- /dev/null
+++ b/ix-cli/src/cli/default-format.ts
@@ -0,0 +1,75 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+/**
+ * Where the default `--format` comes from when a command is not given one.
+ *
+ * Every renderer costs a different number of tokens for the same answer —
+ * `context` measured at roughly 7.6 : 0.8 : 1 for json : llm : text — so the
+ * format an agent gets by default is one of the larger levers on what Ix costs
+ * it. Until now the only way to move it was to append `--format llm` to every
+ * call, which every plugin has to remember on every command it wraps.
+ *
+ * Resolution order: the flag on the command line, then `IX_FORMAT`, then
+ * `format` in `~/.ix/config.yaml`, then `text`. The flag is commander's job;
+ * this module supplies the rest as the option's default value, so `--format`
+ * still wins wherever it appears and nothing here can override an explicit
+ * choice.
+ *
+ * Deliberately *not* here: switching on whether stdout is a terminal. A script
+ * that has always parsed text output would start receiving json on its next
+ * run, which is a break with no opt-out.
+ */
+
+/** The formats every `--format` option accepts. */
+export const DEFAULT_FORMAT_CHOICES = ["text", "json", "llm"] as const;
+
+/** What a `--format` option falls back to when nothing is configured. */
+export const BUILT_IN_DEFAULT_FORMAT = "text";
+
+export interface ResolvedDefaultFormat {
+ /** The format to use when no `--format` flag is given. */
+ format: string;
+ /**
+ * A configured value that was not a format, and was therefore ignored.
+ * Reported so a typo does not silently leave the caller on `text`.
+ */
+ ignored?: { source: "IX_FORMAT" | "config.format"; value: string };
+}
+
+/**
+ * Resolve the default format from the environment and the stored config.
+ *
+ * An unrecognised value is ignored rather than fatal: `IX_FORMAT` is set once
+ * in a shell profile or a plugin's launcher and read by every later command, so
+ * a typo there would otherwise break every invocation of the CLI at once.
+ */
+export function resolveDefaultFormat(
+ env: NodeJS.ProcessEnv,
+ readConfigFormat: () => string | undefined,
+): ResolvedDefaultFormat {
+ let ignored: ResolvedDefaultFormat["ignored"];
+
+ // `readConfigFormat` is a thunk so that a valid IX_FORMAT answers without
+ // reading config.yaml off disk — this runs during registration, on every
+ // invocation of the CLI, including `ix --help`.
+ const sources: { source: "IX_FORMAT" | "config.format"; read: () => string | undefined }[] = [
+ { source: "IX_FORMAT", read: () => env.IX_FORMAT },
+ { source: "config.format", read: readConfigFormat },
+ ];
+
+ for (const { source, read } of sources) {
+ const raw = read();
+ const normalized = raw?.trim().toLowerCase();
+ if (!normalized) continue;
+ if (isFormat(normalized)) return { format: normalized, ...(ignored ? { ignored } : {}) };
+ // Keep the first bad value: it is the more specific of the two, and one
+ // line of warning is all this is worth.
+ ignored ??= { source, value: raw as string };
+ }
+
+ return { format: BUILT_IN_DEFAULT_FORMAT, ...(ignored ? { ignored } : {}) };
+}
+
+export function isFormat(value: string): boolean {
+ return (DEFAULT_FORMAT_CHOICES as readonly string[]).includes(value);
+}
diff --git a/ix-cli/src/cli/register/oss.ts b/ix-cli/src/cli/register/oss.ts
index 4dc249ef..98521c11 100644
--- a/ix-cli/src/cli/register/oss.ts
+++ b/ix-cli/src/cli/register/oss.ts
@@ -40,6 +40,13 @@ import { registerPatchesCommand } from "../commands/patches.js";
import { registerMcpCommand } from "../commands/mcp.js";
import { registerContextCommand } from "../commands/context.js";
import { validateCliOptions } from "../options.js";
+import {
+ BUILT_IN_DEFAULT_FORMAT,
+ DEFAULT_FORMAT_CHOICES,
+ resolveDefaultFormat,
+} from "../default-format.js";
+import { loadConfig } from "../config.js";
+import { stderrDim } from "../stderr.js";
const PRO_COMMANDS: { name: string; desc: string }[] = [
{ name: "briefing", desc: "Session-resume briefing" },
@@ -68,7 +75,6 @@ const ADVANCED_COMMANDS = [
"init", "ingest",
];
-const DEFAULT_FORMAT_CHOICES = ["text", "json", "llm"];
const OPTION_CHOICES: Record<string, Record<string, string[]>> = {
query: { depth: ["shallow", "standard", "deep"], format: ["text", "json"] },
map: { format: [...DEFAULT_FORMAT_CHOICES, "silent"], sort: ["importance", "confidence", "size", "alpha"] },
@@ -86,19 +92,68 @@ const OPTION_CHOICES: Record<string, Record<string, string[]>> = {
const ossCommands = new WeakSet<Command>();
function configureOssOptionChoices(root: Command): void {
+ const { format: defaultFormat, ignored } = resolveDefaultFormat(
+ process.env,
+ // Never let an unreadable or half-written config.yaml stop the CLI from
+ // registering its commands; loadConfig already falls back to defaults on a
+ // parse error, and this covers the rest (an unresolvable IX_HOME).
+ () => { try { return loadConfig().format; } catch { return undefined; } },
+ );
+
+ // Only where a person will read it: an agent captures stderr, and one more
+ // line at the top of its tool result is exactly what this change is for.
+ if (ignored && process.stderr.isTTY) {
+ stderrDim(
+ `Ignoring ${ignored.source}=${ignored.value}: not one of ` +
+ `${DEFAULT_FORMAT_CHOICES.join(", ")}. Using ${defaultFormat}.`
+ );
+ }
+
const visit = (command: Command): void => {
ossCommands.add(command);
const commandChoices = OPTION_CHOICES[command.name()] ?? {};
for (const option of command.options) {
const choices = commandChoices[option.attributeName()]
- ?? (option.long === "--format" ? DEFAULT_FORMAT_CHOICES : undefined);
+ ?? (option.long === "--format" ? [...DEFAULT_FORMAT_CHOICES] : undefined);
if (choices) option.choices(choices);
+ applyDefaultFormat(command, option, choices, defaultFormat);
}
for (const child of command.commands) visit(child);
};
visit(root);
}
+/**
+ * Point a `--format` option at the configured default.
+ *
+ * Only an option still sitting on the built-in `text` is moved: a command that
+ * declares a different default has a reason for it, and `ix config set format`
+ * is not an instruction to override it. The default must also be a format that
+ * command accepts — `query` renders text and json only, so `IX_FORMAT=llm`
+ * leaves it where it is rather than handing the renderer a format it has no
+ * branch for.
+ */
+function applyDefaultFormat(
+ command: Command,
+ option: Command["options"][number],
+ choices: string[] | undefined,
+ defaultFormat: string,
+): void {
+ if (option.long !== "--format") return;
+ if (defaultFormat === BUILT_IN_DEFAULT_FORMAT) return;
+ if (option.defaultValue !== BUILT_IN_DEFAULT_FORMAT) return;
+ if (!choices?.includes(defaultFormat)) return;
+
+ option.default(defaultFormat);
+ // `.option()` copies the default into the command's option values as it
+ // registers, so moving the Option's default afterwards changes the help text
+ // and nothing else. The stored value has to be moved with it -- and only
+ // while it is still the default, which at registration time it always is.
+ if (command.getOptionValueSource(option.attributeName()) === "default") {
+ command.setOptionValueWithSource(option.attributeName(), defaultFormat, "default");
+ }
+}
+
export function registerOssCommands(program: Command): void {
registerQueryCommand(program);
registerIngestCommand(program);