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
fix(context): report what governed, decode ids once, refuse the ignored flags
Joseph Mikhail824e598bb0ae
diff --git a/docs/llm-format.md b/docs/llm-format.mdindex 5b7c1d38..00c3fd75 100644--- a/docs/llm-format.md+++ b/docs/llm-format.md@@ -135,16 +135,37 @@ is not enough: the id is the backend's, and the statement is what changed.```investigations total=2 skipped=1-investigation id=widget saved_at=2026-01-03T09:12:44.108Z target=Widget target_kind=class classification=current entities=12 relationships=20 evidence=8-investigation id=auth-path saved_at=2026-01-02T17:03:11.882Z target=verify_token target_kind=function classification=stale stale=true entities=31 relationships=64 evidence=25 truncated_evidence=4+investigation id=widget saved_at=2026-01-03T09:12:44.108Z target=Widget target_kind=class classification=current stale=false entities=12 relationships=20 evidence=8 truncated_entities=0 truncated_relationships=0 truncated_evidence=0 truncated_chars=0+investigation id=auth-path saved_at=2026-01-02T17:03:11.882Z target=verify_token target_kind=function classification=stale stale=true entities=31 relationships=64 evidence=25 truncated_entities=0 truncated_relationships=0 truncated_evidence=4 truncated_chars=0````skipped` counts saved files that did not match the contract and is presentonly when it is non-zero — it is the one thing about a listing that cannot be-seen from the records themselves. `id` is the id `--resume` and `--diff` take,-not the file name on disk; the two differ whenever an id contains a character-outside `[A-Za-z0-9._-]`. The counts describe each bundle; the bundles-themselves are not in the listing, and `ix context --resume <id>` fetches one.+seen from the records themselves. Note that `stale=` and the four `truncated_*`+fields are *not* dropped when zero or false: `llmField` omits only nullish and+empty-string values, and these say "measured, and it was none", which a missing+field does not.++`id` is the id `--resume` and `--diff` take, not necessarily the file name on+disk; the two differ whenever an id contains a character outside+`[A-Za-z0-9._-]`. Both forms load, because the encoding is not always+reversible — above U+00FF the escape width is ambiguous, and the listing shows+the stored name rather than guess.++The counts describe each bundle; the bundles themselves are not in the listing,+and `ix context --resume <id>` fetches one:++```+resumed id=widget saved_at=2026-01-03T09:12:44.108Z+context target=Widget target_kind=class stale=false classification=current entities=2 relationships=1 claims=1 decisions=0 conflicts=0 intents=0 evidence=7 truncated_entities=0 truncated_relationships=0 truncated_evidence=0 truncated_chars=0+evidence score=0 kind=target title="Widget (class)"+```++`resumed`, not `investigation`: the record kinds are distinct because the+shapes are, and a consumer routing on the kind should not have to guess which+of two field sets it is holding. `saved_at` is on it because the `context`+record that follows says whether the snapshot was fresh when it was taken, not+when that was.Error line:diff --git a/ix-cli/src/cli/__tests__/context-investigation.test.ts b/ix-cli/src/cli/__tests__/context-investigation.test.tsindex 479a5cdb..b4eb9003 100644--- a/ix-cli/src/cli/__tests__/context-investigation.test.ts+++ b/ix-cli/src/cli/__tests__/context-investigation.test.ts@@ -22,6 +22,7 @@ import {parseRequestedBudgets,renderBundle,renderInvestigationDiff,+ renderSavedInvestigation,saveInvestigation,} from "../commands/context.js";@@ -93,6 +94,41 @@ function captureWarnings(fn: () => void): string {return lines.join("\n").replace(/\u001b\[[0-9;]*m/g, "");}+/**+ * Run `fn` with stdout and stderr captured separately.+ *+ * One helper for the file. There were three, and they disagreed: two joined a+ * multi-argument `console.log` with a space, the third pushed each argument as+ * its own line, so identical output produced different arrays depending on+ * which block a test happened to sit in.+ */+function captureStreams(fn: () => void): { out: string[]; err: string[] } {+ const out: string[] = [];+ const err: string[] = [];+ const origLog = console.log;+ const origErr = console.error;+ console.log = (...a: unknown[]) => void out.push(a.map(String).join(" "));+ console.error = (...a: unknown[]) => void err.push(a.map(String).join(" "));+ try {+ fn();+ } finally {+ console.log = origLog;+ console.error = origErr;+ }+ return { out, err };+}++/** The same, joined the way a terminal shows it. */+function captureText(fn: () => void): { out: string; err: string } {+ const { out, err } = captureStreams(fn);+ return { out: out.join("\n"), err: err.join("\n") };+}++/** Just the stdout half, for the renderers that write nothing else. */+function captureLog(fn: () => void): string[] {+ return captureStreams(fn).out;+}+function makeFacts(overrides: Partial<EntityFacts> = {}): EntityFacts {return {id: "entity-1",@@ -401,10 +437,13 @@ describe("ix context investigation state", () => {saveInvestigation("widget-check", bundle);const stored = loadInvestigation("widget-check")!;- expect(mergeDiffOptions(stored, {})).toEqual({ asOfRev: "7", depth: "2" });- expect(mergeDiffOptions(stored, { asOfRev: "3" })).toEqual({ asOfRev: "3", depth: "2" });- expect(mergeDiffOptions(stored, { depth: "4" })).toEqual({ asOfRev: "7", depth: "4" });- expect(mergeDiffOptions(stored, { asOfRev: "3", depth: "4" })).toEqual({ asOfRev: "3", depth: "4" });+ // Numbers, not strings: `--as-of-rev` is validated by its Commander+ // argParser now, so the round trip out to a string and back through+ // `parseInt` is gone.+ expect(mergeDiffOptions(stored, {})).toEqual({ asOfRev: 7, depth: "2" });+ expect(mergeDiffOptions(stored, { asOfRev: 3 })).toEqual({ asOfRev: 3, depth: "2" });+ expect(mergeDiffOptions(stored, { depth: "4" })).toEqual({ asOfRev: 7, depth: "4" });+ expect(mergeDiffOptions(stored, { asOfRev: 3, depth: "4" })).toEqual({ asOfRev: 3, depth: "4" });});it("never collides or escapes for hostile investigation ids", () => {@@ -472,9 +511,17 @@ describe("ix context investigation state", () => {expect(overrideDiff.budgets.requestedApplied).toBe(false);expect(overrideDiff.budgets.note).toMatch(/were not applied to the fresh side/i);- // …and it reads true when they do match what the bundle was built with.+ // Still false when the numbers happen to agree, which is the case that+ // makes "requested equals effective" the wrong derivation: `--max-evidence+ // 25` against a fresh side already built with 25 changes nothing, and+ // reporting true there told an agent its override had taken.const matching = parseRequestedBudgets({ maxEntities: 50, maxEvidence: 25 });- expect(diffInvestigations(stored, fresh, matching).budgets.requestedApplied).toBe(true);+ const agreeing = diffInvestigations(stored, fresh, matching);+ expect(agreeing.budgets.requested).toEqual({ maxEntities: 50, maxEvidence: 25 });+ expect(agreeing.budgets.effective).toEqual(fresh.budgets);+ expect(agreeing.budgets.requestedApplied).toBe(false);+ // …and the note beside it says the same thing, in every format.+ expect(agreeing.budgets.note).toMatch(/were not applied to the fresh side/i);});it("records exactly the --max-* flags that were passed", () => {@@ -535,7 +582,7 @@ describe("ix context investigation state", () => {// carries `applied=` so the precedence rule — saved budgets govern// --diff — is a field an agent can test rather than a sentence to read.expect(llm.lines).toContain("budgets scope=saved entities=5 relationships=1 evidence=2 chars=12000");- expect(llm.lines).toContain("budgets scope=requested evidence=25 applied=true");+ expect(llm.lines).toContain("budgets scope=requested evidence=25 applied=false");expect(llm.lines).toContain("budgets scope=effective entities=50 relationships=100 evidence=25 chars=12000");// And none of the prose survives into the record stream.expect(llm.lines.some((l) => l.includes(":") && l.startsWith(" "))).toBe(false);@@ -554,8 +601,11 @@ describe("ix context investigation state", () => {expect(parsed.budgets.requested).toEqual(requested);expect(parsed.budgets.effective).toEqual(fresh.budgets);// The same fact the llm record carries as `applied=`, so a JSON consumer- // does not have to string-match an English sentence for it.- expect(parsed.budgets.requestedApplied).toBe(true);+ // does not have to string-match an English sentence for it — and it agrees+ // with the note and with the text renderer's "not applied" label, which a+ // value comparison did not.+ expect(parsed.budgets.requestedApplied).toBe(false);+ expect(parsed.budgets.note).toMatch(/were not applied to the fresh side/i);});// `--diff --format llm` used to fall through to the prose renderer, because@@ -563,19 +613,6 @@ describe("ix context investigation state", () => {// by `llmLine`, so a value carrying a space is quoted rather than splitting// the record. These tests pin that.describe("--format llm rendering", () => {- function captureLog(fn: () => void): string[] {- const lines: string[] = [];- const orig = console.log;- console.log = (...args: unknown[]) => {- for (const arg of args) lines.push(String(arg));- };- try {- fn();- } finally {- console.log = orig;- }- return lines;- }it("emits a header and counts for an empty diff without falling back to prose", () => {const saved = bundleWith([makeClaim("renders to DOM", 0.9)]);@@ -748,6 +785,24 @@ describe("ix context investigation state", () => {expect(lines[0]).toMatch(/^context target=Widget target_kind=class /);});+ it("gives --resume its own record kind, not --list's", () => {+ // Both emitted `investigation`, with two fields here and thirteen there,+ // so a consumer routing on the record kind could not tell which shape to+ // expect and reading `target` off this one yielded undefined.+ const saved = bundleWith([makeClaim("renders to DOM", 0.9)]);+ saveInvestigation("widget-resume", saved);+ const lines = captureLog(() => renderSavedInvestigation("widget-resume", "llm"));++ expect(lines[0]).toMatch(/^resumed id=widget-resume saved_at=/);+ // …and it carries the one fact the bundle records do not: when the+ // snapshot was taken. `classification=current` says it was fresh then,+ // not when then was.+ expect(lines[0]).toMatch(/saved_at=\d{4}-\d{2}-\d{2}T/);+ // The prose note it replaces is gone from the record stream.+ expect(lines.some((l) => l.includes("Resumed investigation"))).toBe(false);+ expect(lines[1]).toMatch(/^context target=Widget/);+ });+it("does not regress the prose (text) renderer", () => {const saved = bundleWith([makeClaim("renders to DOM", 0.9)]);saveInvestigation("widget-llm-text", saved);@@ -767,31 +822,6 @@ describe("ix context investigation state", () => {// Without it, neither humans nor agents can see what they have stored —// the only path was reading the JSON files directly.describe("listInvestigations", () => {- /**- * Run `fn` with stdout and stderr captured separately.- *- * One helper for the whole block, and multi-arg calls joined with a space- * the way a terminal shows them: the two ad-hoc capturers this replaces- * disagreed on that (one joined, one pushed each argument as its own line),- * so identical output produced different arrays depending on which test you- * happened to be reading.- */- const captureStreams = (fn: () => void) => {- const out: string[] = [];- const err: string[] = [];- const origLog = console.log;- const origErr = console.error;- console.log = (...a: unknown[]) => void out.push(a.join(" "));- console.error = (...a: unknown[]) => void err.push(a.join(" "));- try {- fn();- } finally {- console.log = origLog;- console.error = origErr;- }- return { out: out.join("\n"), err: err.join("\n") };- };-/** Restamp a saved investigation's `savedAt`, leaving everything else alone. */const stampSavedAt = (id: string, savedAt: string) => {const path = join(investigationsDir(), `${id}.json`);@@ -840,14 +870,47 @@ describe("ix context investigation state", () => {// `widget/auth` was saved as `widget~2Fauth` and listed as that, and// resuming it looked for `widget~7E2Fauth`, which does not exist.saveInvestigation("widget/auth", bundleWith([makeClaim("renders to DOM", 0.9)]));- const [only] = listInvestigations().saved;- expect(only.id).toBe("widget~2Fauth"); // on disk, as stored+ // Stored encoded, one file, no separator in the name.+ expect(readdirSync(investigationsDir())).toEqual(["widget~2Fauth.json"]);- const { out } = captureStreams(() => renderInvestigationList([only], 0, "json"));- const listed = JSON.parse(out).investigations[0].id;- expect(listed).toBe("widget/auth");+ // Decoded once, at the read boundary, so every format agrees. Decoding at+ // each print site is how `--format llm` came to say `widget/auth` while+ // `--format json` and the text header said `widget~2Fauth`.+ const [only] = listInvestigations().saved;+ expect(only.id).toBe("widget/auth");+ const { out } = captureText(() => renderInvestigationList([only], 0, "json"));+ expect(JSON.parse(out).investigations[0].id).toBe("widget/auth");// The whole point: the id the listing offers has to load.- expect(loadInvestigation(listed)?.bundle.target.name).toBe("Widget");+ expect(loadInvestigation(only.id)?.bundle.target.name).toBe("Widget");+ });++ it("lists an id that --resume can take back even when it cannot be decoded", () => {+ // `sanitizeId` writes two hex digits below U+0100 and three or four above+ // it, so `~7528` is either one CJK code unit or `~752` followed by a+ // literal `8` and nothing in the string says which. Guessing produced a+ // mangled id that loaded nothing; the round-trip check refuses to guess+ // and shows the stored name, and `loadInvestigation` accepts that form.+ saveInvestigation("用户", bundleWith([makeClaim("renders to DOM", 0.9)]));+ const [only] = listInvestigations().saved;+ expect(only.id).toBe("~7528~6237");+ expect(loadInvestigation(only.id)?.bundle.target.name).toBe("Widget");+ // …and the id the user actually typed still reaches the same file.+ expect(loadInvestigation("用户")?.bundle.target.name).toBe("Widget");+ });++ it("keeps an id that is literally spelled like an encoding on its own file", () => {+ // The on-disk fallback is second, not first, so `widget~2Fauth` typed as+ // an id finds the file it was saved to rather than the one `widget/auth`+ // was.+ saveInvestigation("widget/auth", bundleWith([makeClaim("renders to DOM", 0.9)]));+ saveInvestigation("widget~2Fauth", bundleWith([makeClaim("mounts to DOM", 0.9)]));+ expect(readdirSync(investigationsDir()).sort()).toEqual(+ ["widget~2Fauth.json", "widget~7E2Fauth.json"],+ );+ const claims = (id: string) =>+ loadInvestigation(id)!.bundle.claims.map((c) => c.statement);+ expect(claims("widget/auth")).toContain("renders to DOM");+ expect(claims("widget~2Fauth")).toContain("mounts to DOM");});it("skips files whose envelope or bundle does not match the contract", () => {@@ -884,7 +947,7 @@ describe("ix context investigation state", () => {saveInvestigation("good", bundleWith([makeClaim("renders to DOM", 0.9)]));const { saved } = listInvestigations();- const json = captureStreams(() => renderInvestigationList(saved, 3, "json"));+ const json = captureText(() => renderInvestigationList(saved, 3, "json"));expect(() => JSON.parse(json.out)).not.toThrow();const parsed = JSON.parse(json.out);expect(parsed.investigations).toHaveLength(1);@@ -893,18 +956,18 @@ describe("ix context investigation state", () => {expect(parsed.skipped).toBe(3);expect(json.err).toContain("3 saved investigation file(s)");- const llm = captureStreams(() => renderInvestigationList(saved, 3, "llm"));+ const llm = captureText(() => renderInvestigationList(saved, 3, "llm"));expect(llm.out.split("\n")[0]).toBe("investigations total=1 skipped=3");// The count is the record's business; nothing is written beside it.expect(llm.err).toBe("");// And with nothing skipped the field is simply absent.- const clean = captureStreams(() => renderInvestigationList(saved, 0, "llm"));+ const clean = captureText(() => renderInvestigationList(saved, 0, "llm"));expect(clean.out.split("\n")[0]).toBe("investigations total=1");expect(clean.err).toBe("");// `skipped` is still there in json, as a zero rather than as nothing:// "none were rejected" is an answer, and its absence is not.- const cleanJson = captureStreams(() => renderInvestigationList(saved, 0, "json"));+ const cleanJson = captureText(() => renderInvestigationList(saved, 0, "json"));expect(JSON.parse(cleanJson.out).skipped).toBe(0);});@@ -917,7 +980,7 @@ describe("ix context investigation state", () => {const { saved } = listInvestigations();expect(saved[0].bundle.evidence.length).toBeGreaterThan(0);- const { out } = captureStreams(() => renderInvestigationList(saved, 0, "json"));+ const { out } = captureText(() => renderInvestigationList(saved, 0, "json"));const [item] = JSON.parse(out).investigations;expect(Object.keys(item).sort()).toEqual(["counts", "freshness", "id", "savedAt", "target", "truncation"].sort(),diff --git a/ix-cli/src/cli/__tests__/context-mode-conflict.test.ts b/ix-cli/src/cli/__tests__/context-mode-conflict.test.tsindex 89e2be9f..052763d2 100644--- a/ix-cli/src/cli/__tests__/context-mode-conflict.test.ts+++ b/ix-cli/src/cli/__tests__/context-mode-conflict.test.ts@@ -82,10 +82,13 @@ describe("detectContextModeConflict", () => {const msg = detectContextModeConflict({ resume: "x", out: "/tmp/x.json", format })!;expect(msg).toMatch(/--resume cannot be combined with --out/);expect(msg).not.toMatch(/--format json with --out/);- // And the way out it does name has to work.- expect(msg).toMatch(/>/);- expect(detectContextModeConflict({ resume: "x", format: "json" })).toBeUndefined();+ // And the way out it names has to be a way out. `toMatch(/>/)` was+ // satisfied by the `<id>` placeholder already in the message, so it+ // passed for any wording at all, including one naming nothing.+ expect(msg).toContain("ix context --resume <id> --format json > <path>");}+ // The redirect it recommends is not itself refused here.+ expect(detectContextModeConflict({ resume: "x", format: "json" })).toBeUndefined();});it("flags --diff + --save (C-1)", () => {@@ -129,6 +132,17 @@ describe("detectContextModeConflict", () => {);});+ it("flags a positional target alongside --resume, the sibling nobody guarded", () => {+ // `--resume` reads the id from its own flag and never looks at the+ // positional, so `ix context Widget --resume widget-investigation` rendered+ // the saved investigation and dropped `Widget` with exit 0 -- the same+ // defect as the --list one, one line below the guard added for it. --diff+ // does use the positional, so it stays legal there.+ expect(detectContextModeConflict({ resume: "x" }, "Widget")).toMatch(/--resume takes no target/);+ expect(detectContextModeConflict({ diff: "x" }, "Widget")).toBeUndefined();+ expect(detectContextModeConflict({ resume: "x" })).toBeUndefined();+ });+it("flags a positional target alongside --list", () => {// A positional is as ignorable as a flag: `ix context Widget --list`// dropped the target with nothing said.@@ -202,11 +216,18 @@ describe("detectDiffModeConflict", () => {describe("mode-flag coverage does not drift from the command", () => {/** Flags that select what the command does, or where its output goes. */const CONTEXT_MODE_FLAGS = ["out", "save", "resume", "diff", "list"] as const;- /** Flags that shape the bundle a mode produces; any pair of these is legal. */+ /**+ * Flags that shape a bundle. Legal with each other and with the modes that+ * build one; refused by `--list` and `--resume`, which build none — that gap+ * was five typed flags accepted and dropped with exit 0, and this list saying+ * "legal everywhere" is what certified it.+ */const CONTEXT_BUILD_FLAGS = ["kind", "path", "pick", "depth", "asOfRev",- "maxEntities", "maxRelationships", "maxEvidence", "maxChars", "format",+ "maxEntities", "maxRelationships", "maxEvidence", "maxChars",];+ /** Meaningful to every mode, so in neither group. */+ const CONTEXT_UNIVERSAL_FLAGS = ["format"];function registeredAttributes(register: (p: Command) => void, name: string): string[] {const program = new Command();@@ -218,10 +239,34 @@ describe("mode-flag coverage does not drift from the command", () => {it("classifies every option ix context registers", () => {expect(registeredAttributes(registerContextCommand, "context")).toEqual(- [...CONTEXT_MODE_FLAGS, ...CONTEXT_BUILD_FLAGS].sort(),+ [...CONTEXT_MODE_FLAGS, ...CONTEXT_BUILD_FLAGS, ...CONTEXT_UNIVERSAL_FLAGS].sort(),);});+ it("refuses every build flag given to a mode that builds nothing", () => {+ for (const mode of ["list", "resume"] as const) {+ for (const flag of CONTEXT_BUILD_FLAGS) {+ const opts = { [mode]: mode === "list" ? true : "x", [flag]: 1 } as Record<string, unknown>;+ expect(+ detectContextModeConflict(opts),+ `--${flag} is silently ignored by --${mode}`,+ ).toBeTruthy();+ }+ // …and the mode alone, or with --format, is the ordinary path.+ expect(detectContextModeConflict({ [mode]: mode === "list" ? true : "x", format: "llm" })).toBeUndefined();+ }+ // --diff consumes all of them, so none of this applies to it.+ for (const flag of CONTEXT_BUILD_FLAGS) {+ expect(detectContextModeConflict({ diff: "x", [flag]: 1 })).toBeUndefined();+ }+ });++ it("names every ignored flag at once, not one per re-run", () => {+ const msg = detectContextModeConflict({ list: true, maxEntities: 10, kind: "class" })!;+ expect(msg).toContain("--kind");+ expect(msg).toContain("--max-entities");+ });+it("refuses every pair of mode flags", () => {for (const a of CONTEXT_MODE_FLAGS) {for (const b of CONTEXT_MODE_FLAGS) {@@ -309,6 +354,9 @@ describe("ix context action surfaces mode conflicts on stderr and exits 1", () ={ args: ["context", "--list", "--save", "y"], expect: /--list cannot be combined with --save/ },{ args: ["context", "--list", "--out", "/tmp/x.json"], expect: /--list cannot be combined with --out/ },{ args: ["context", "Widget", "--list"], expect: /--list takes no target/ },+ { args: ["context", "Widget", "--resume", "x"], expect: /--resume takes no target/ },+ { args: ["context", "--list", "--max-entities", "10"], expect: /--max-entities cannot be combined with --list/ },+ { args: ["context", "--resume", "x", "--kind", "class"], expect: /--kind cannot be combined with --resume/ },])("ix $args → stderr matches $expect and exit code is 1", ({ args, expect: re }) => {const r = runProgram(registerContextCommand, args);expect(r.exitCode).toBe(1);diff --git a/ix-cli/src/cli/__tests__/context-pick-validation.test.ts b/ix-cli/src/cli/__tests__/context-pick-validation.test.tsindex 70c988f6..9601982f 100644--- a/ix-cli/src/cli/__tests__/context-pick-validation.test.ts+++ b/ix-cli/src/cli/__tests__/context-pick-validation.test.ts@@ -125,3 +125,53 @@ describe("ix context --max-* validation", () => {}});});++/**+ * `--as-of-rev` sat two lines from the budget flags with a bare+ * `parseInt(opts.asOfRev, 10)` behind it, and its value goes to the backend:+ * `--as-of-rev abc` sent NaN, `3.9` silently became 3, `10abc` became 10.+ */+describe("ix context --as-of-rev validation", () => {+ beforeEach(() => {+ resolveFileOrEntity.mockReset().mockResolvedValue(undefined);+ });++ it.each(["abc", "3.9", "10abc", "-1", "0"])("rejects %j rather than sending it", async (value) => {+ const result = await runContext(["--as-of-rev", value]);+ expect(result.error?.exitCode).toBe(1);+ expect(result.stderr).toContain("must be a positive integer");+ expect(resolveFileOrEntity).not.toHaveBeenCalled();+ });++ it("accepts a revision", async () => {+ expect((await runContext(["--as-of-rev", "12"])).error).toBeUndefined();+ });+});++describe("ix context refusals reach the caller that asked for records", () => {+ beforeEach(() => {+ resolveFileOrEntity.mockReset().mockResolvedValue(undefined);+ });++ it("answers a missing target with a record and a non-zero status", async () => {+ // It was a `renderWarning` — console.log — with the exit code left at 0, so+ // an `llm` consumer got a prose line in its record stream and a script+ // could not tell "no target given" from a successful empty bundle.+ const out: string[] = [];+ const origLog = console.log;+ const priorExit = process.exitCode;+ console.log = (...a: unknown[]) => void out.push(a.map(String).join(" "));+ try {+ process.exitCode = undefined;+ const program = new Command().name("ix").exitOverride();+ registerContextCommand(program);+ await program.parseAsync(["context", "--format", "llm"], { from: "user" });+ expect(out).toHaveLength(1);+ expect(out[0]).toMatch(/^error code=missing_target message="/);+ expect(process.exitCode).toBe(1);+ } finally {+ console.log = origLog;+ process.exitCode = priorExit;+ }+ });+});diff --git a/ix-cli/src/cli/commands/context.ts b/ix-cli/src/cli/commands/context.tsindex 6684996a..5eac2752 100644--- a/ix-cli/src/cli/commands/context.ts+++ b/ix-cli/src/cli/commands/context.ts@@ -19,11 +19,11 @@ import type {} from "../../client/types.js";import { getEndpoint } from "../config.js";import { collectFacts, type EntityFacts } from "../explain/facts.js";-import { llmError, llmLine, printLlmLines, reportModeConflict } from "../llm.js";-import { parseBudgetOption, parsePickOption } from "../options.js";+import { llmLine, printLlmLines } from "../llm.js";+import { parseBudgetOption, parsePickOption, parseRevisionOption } from "../options.js";import { resolveFileOrEntity } from "../resolve.js";import { createStaleProbe } from "../stale.js";-import { renderNote, renderSection, renderWarning } from "../ui.js";+import { renderNote, renderSection, renderWarning, renderWarningErr, reportFailure } from "../ui.js";/** The four `--max-*` knobs that bound a bundle. */interface BudgetSnapshot {@@ -48,12 +48,13 @@ interface BudgetSnapshot {* the number that is applied.*/const BUDGETS = [- { key: "maxEntities", label: "entities", help: "Maximum entities in the bundle", min: 1, max: 500, fallback: 50 },- { key: "maxRelationships", label: "relationships", help: "Maximum relationships in the bundle", min: 1, max: 1000, fallback: 100 },- { key: "maxEvidence", label: "evidence", help: "Maximum evidence items in the bundle", min: 1, max: 200, fallback: 25 },- { key: "maxChars", label: "chars", help: "Maximum characters of evidence output", min: 1000, max: 1_000_000, fallback: 12_000 },+ { key: "maxEntities", flag: "--max-entities", label: "entities", help: "Maximum entities in the bundle", min: 1, max: 500, fallback: 50 },+ { key: "maxRelationships", flag: "--max-relationships", label: "relationships", help: "Maximum relationships in the bundle", min: 1, max: 1000, fallback: 100 },+ { key: "maxEvidence", flag: "--max-evidence", label: "evidence", help: "Maximum evidence items in the bundle", min: 1, max: 200, fallback: 25 },+ { key: "maxChars", flag: "--max-chars", label: "chars", help: "Maximum characters of evidence output", min: 1000, max: 1_000_000, fallback: 12_000 },] as const satisfies ReadonlyArray<{key: keyof BudgetSnapshot;+ flag: string;label: string;help: string;min: number;@@ -72,10 +73,29 @@ const BUDGETS = [* that enforces them.*/function budgetHelp(key: keyof BudgetSnapshot): string {- const b = BUDGETS.find((entry) => entry.key === key)!;+ const b = budgetField(key);return `${b.help} (default: ${b.fallback}, clamped to ${b.min}-${b.max})`;}+/** The table row for one budget. */+function budgetField(key: keyof BudgetSnapshot): (typeof BUDGETS)[number] {+ return BUDGETS.find((entry) => entry.key === key)!;+}++/**+ * The Commander `argParser` for one budget flag.+ *+ * The example in the rejection message comes from the flag's own default, not+ * from a constant: a single hardcoded "50" told someone who mistyped+ * `--max-chars` to try 50, which parses and is then silently clamped up to 1000+ * by `clampBudgets` -- while the help text one line away says the range is+ * 1000-1000000.+ */+function budgetParser(key: keyof BudgetSnapshot): (value: string) => number {+ const example = String(budgetField(key).fallback);+ return (value: string) => parseBudgetOption(value, example);+}+/** Apply the table's range and default to whatever the caller supplied. */function clampBudgets(opts: Partial<BudgetSnapshot>): BudgetSnapshot {const out = {} as BudgetSnapshot;@@ -91,7 +111,7 @@ interface ContextOptions extends Partial<BudgetSnapshot> {path?: string;pick?: number;depth?: string;- asOfRev?: string;+ asOfRev?: number;out?: string;save?: string;resume?: string;@@ -178,16 +198,16 @@ export function registerContextCommand(program: Command): void {.option("--path <path>", "Prefer symbols from files matching this path substring").option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption).option("--depth <depth>", "Context-graph expansion depth")- .option("--as-of-rev <n>", "Historical context as of a graph revision")+ .option("--as-of-rev <n>", "Historical context as of a graph revision", parseRevisionOption)// No Commander default on the --max-* flags, so `parseRequestedBudgets`// can tell an absent flag from one set to the default value. The defaults// and ranges are the BUDGETS table's, applied by `clampBudgets` and shown// in the help text by `budgetHelp` -- they differ per flag, so there is no// single pair to name here.- .option("--max-entities <n>", budgetHelp("maxEntities"), parseBudgetOption)- .option("--max-relationships <n>", budgetHelp("maxRelationships"), parseBudgetOption)- .option("--max-evidence <n>", budgetHelp("maxEvidence"), parseBudgetOption)- .option("--max-chars <n>", budgetHelp("maxChars"), parseBudgetOption)+ .option("--max-entities <n>", budgetHelp("maxEntities"), budgetParser("maxEntities"))+ .option("--max-relationships <n>", budgetHelp("maxRelationships"), budgetParser("maxRelationships"))+ .option("--max-evidence <n>", budgetHelp("maxEvidence"), budgetParser("maxEvidence"))+ .option("--max-chars <n>", budgetHelp("maxChars"), budgetParser("maxChars")).option("--format <fmt>", "Output format (text|json|llm)", "text").option("--out <path>", "Write the JSON bundle to this file instead of stdout").option("--save <id>", "Persist the bundle as a resumable investigation state")@@ -201,7 +221,7 @@ export function registerContextCommand(program: Command): void {.action(async (target: string | undefined, opts: ContextOptions) => {const conflict = detectContextModeConflict(opts, target);if (conflict) {- reportModeConflict(conflict, opts.format);+ reportFailure("mode_conflict", conflict, opts.format);return;}if (opts.resume) {@@ -235,7 +255,14 @@ export function registerContextCommand(program: Command): void {return;}if (!target) {- renderWarning("ix context requires a target unless --resume <id> or --diff <id> is given.");+ // An error with a non-zero status, not a stdout warning with a zero one:+ // a script asked for a bundle and got none, and a `--format llm` caller+ // got a prose line in the middle of a record stream saying so.+ reportFailure(+ "missing_target",+ "ix context requires a target unless --resume <id>, --diff <id> or --list is given.",+ opts.format,+ );return;}@@ -248,8 +275,8 @@ export function registerContextCommand(program: Command): void {});if (!resolved) return;- const asOfRev = opts.asOfRev ? parseInt(opts.asOfRev, 10) : undefined;const budgets = clampBudgets(opts);+ const asOfRev = opts.asOfRev;const [facts, context, provenance] = await Promise.all([collectFacts(client, resolved.id, resolved.name, resolved.kind),@@ -277,7 +304,9 @@ export function registerContextCommand(program: Command): void {}if (opts.out && opts.format !== "json") {- renderWarning("--out writes JSON; ignoring --format and forcing json.");+ // stderr: --out still writes the file and still prints a note, so this+ // advisory would otherwise sit in the stdout an `llm` caller is reading.+ renderWarningErr("--out writes JSON; ignoring --format and forcing json.");}const out = opts.out;if (out) {@@ -288,7 +317,11 @@ export function registerContextCommand(program: Command): void {// in a caller-owned file (CodeQL js/network-data-written-to-file).const parsed = contextBundleSchema.safeParse(bundle);if (!parsed.success) {- renderWarning(`--out "${out}" refused: the bundle does not match the ${BUNDLE_SCHEMA} schema (${parsed.error.issues.length} issue(s)).`);+ reportFailure(+ "out_refused",+ `--out "${out}" refused: the bundle does not match the ${BUNDLE_SCHEMA} schema (${parsed.error.issues.length} issue(s)).`,+ opts.format,+ );return;}// Atomic write: serialize to a private temp file in the SAME directory,@@ -307,7 +340,11 @@ export function registerContextCommand(program: Command): void {if (err.code === "EISDIR" || err.code === "EPERM") {try {if (fs.statSync(targetPath).isDirectory()) {- renderWarning(`--out "${out}" is a directory; refusing to write the bundle there.`);+ reportFailure(+ "out_refused",+ `--out "${out}" is a directory; refusing to write the bundle there.`,+ opts.format,+ );return;}} catch { /* target may not exist; fall through to rethrow */ }@@ -322,7 +359,7 @@ export function registerContextCommand(program: Command): void {async function buildFreshBundle(target: string,- opts: { kind?: string; path?: string; pick?: number; depth?: string; asOfRev?: string },+ opts: { kind?: string; path?: string; pick?: number; depth?: string; asOfRev?: number },budgets: BudgetSnapshot,): Promise<ContextBundle | undefined> {const client = new IxClient(getEndpoint());@@ -333,7 +370,7 @@ async function buildFreshBundle(});if (!resolved) return undefined;- const asOfRev = opts.asOfRev ? parseInt(opts.asOfRev, 10) : undefined;+ const asOfRev = opts.asOfRev;const [facts, context, provenance] = await Promise.all([collectFacts(client, resolved.id, resolved.name, resolved.kind),client.query(resolved.name, { asOfRev, depth: opts.depth }),@@ -346,19 +383,41 @@ async function buildFreshBundle(/**- * The `ContextOptions` fields `detectContextModeConflict` consumes.+ * What `detectContextModeConflict` reads: all of `ContextOptions`.+ *+ * Derived from the action handler's own declaration, never hand-copied. The+ * detector exists to stop a typed flag being a no-op, so a shape it maintains+ * separately is the one thing it cannot afford: written out field-by-field it+ * drifted immediately, when `--list` was added to `ContextOptions` on a sibling+ * branch and the detector could not see it with nothing from the typechecker to+ * say so. `Partial` so the pure function can be called with one flag at a time+ * in a test, without inventing a `format`.+ */+export type ContextModeOptions = Partial<ContextOptions>;++/**+ * Flags that shape a bundle this run builds, and are therefore meaningless to a+ * mode that builds none.*- * `Pick`, not a hand-copied shape: the detector exists to stop a typed flag- * being a no-op, so its idea of the flags must come from the same declaration- * the action handler uses. Written out field-by-field it drifted immediately --- * `--list` was added to `ContextOptions` on a sibling branch and the detector- * could not see it, with nothing from the typechecker to say so. `Partial` so- * the pure function can still be called with one flag at a time in a test,- * without inventing a `format`.+ * `--list` enumerates saved state and `--resume` renders it verbatim; neither+ * resolves a target or applies a budget, so every one of these was accepted and+ * dropped in silence — `ix context --list --max-entities 10 --kind class` took+ * five typed flags and exited 0. `--diff` is not here: it re-resolves the target+ * with `--kind`/`--path`/`--pick`, forwards `--depth`/`--as-of-rev` through+ * `mergeDiffOptions`, and reports the `--max-*` values rather than dropping+ * them.+ *+ * Listed as `[field, flag]` because the message has to name what the user+ * typed, and Commander's camelCase attribute is not that.*/-export type ContextModeOptions = Partial<- Pick<ContextOptions, "resume" | "diff" | "save" | "out" | "list" | "format">->;+const BUILD_FLAGS: ReadonlyArray<[keyof ContextOptions, string]> = [+ ["kind", "--kind"],+ ["path", "--path"],+ ["pick", "--pick"],+ ["depth", "--depth"],+ ["asOfRev", "--as-of-rev"],+ ...BUDGETS.map((b) => [b.key, b.flag] as [keyof ContextOptions, string]),+];/*** Detect mutually-incompatible mode/output flags on `ix context` and return a@@ -380,7 +439,8 @@ export type ContextModeOptions = Partial<* lose that race.** `target` is a parameter because a positional is as ignorable as a flag:- * `ix context Widget --list` dropped the target with nothing said.+ * `ix context Widget --list` and `ix context Widget --resume x` both dropped it+ * with nothing said.*/export function detectContextModeConflict(opts: ContextModeOptions,@@ -389,6 +449,23 @@ export function detectContextModeConflict(if (opts.list && target) {return `--list takes no target; it enumerates every saved investigation. Drop "${target}", or drop --list to build a fresh bundle for it.`;}+ if (opts.resume && target) {+ return `--resume takes no target; it renders the investigation you name, whatever that was built for. Drop "${target}", or use --diff <id> to compare a saved investigation against a fresh build of it.`;+ }+ // Flags that shape a bundle, given to a mode that builds none. Reported as+ // one message naming every offender, because dropping one at a time and+ // re-running to find the next is the experience this detector exists to+ // avoid, and the flags are all wrong for the same reason.+ for (const [mode, why] of [+ ["list", "--list enumerates saved investigations and builds no bundle"],+ ["resume", "--resume renders a saved investigation exactly as it was built"],+ ] as const) {+ if (!opts[mode]) continue;+ const ignored = BUILD_FLAGS.filter(([field]) => opts[field] !== undefined).map(([, flag]) => flag);+ if (ignored.length > 0) {+ return `${ignored.join(", ")} cannot be combined with --${mode}; ${why}, so ${ignored.length > 1 ? "those flags change" : "that flag changes"} nothing. Drop ${ignored.length > 1 ? "them" : "it"}, or run ix context <target> to build a bundle with ${ignored.length > 1 ? "them" : "it"}.`;+ }+ }if (opts.list && opts.resume) {return "--list and --resume cannot be combined; --list enumerates saved investigations, --resume renders one. Run --list first, then --resume the id you want.";}@@ -469,28 +546,41 @@ export function sanitizeId(id: string): string {}/**- * Recover the id the user typed from the id stored on disk.+ * The id to show the user, given the id stored on disk.*- * `sanitizeId` is injective and deliberately *not* idempotent — it encodes `~`- * as `~7E` precisely so a raw `~` cannot be confused with an escape — so the- * stored form is the wrong thing to hand back to the user. `ix context --list`- * printed it anyway, next to "Resume with: ix context --resume <id>", and- * `--resume` sanitizes what it is given: an id saved as `widget/auth` was- * listed as `widget~2Fauth`, and resuming that looked for `widget~7E2Fauth`,- * which does not exist. `saveInvestigation`'s own note echoes the id the user- * typed, so the two affordances contradicted each other.+ * `sanitizeId` is deliberately *not* idempotent — it encodes `~` as `~7E` so a+ * raw `~` cannot be mistaken for an escape — so the stored form is the wrong+ * thing to hand back. `ix context --list` printed it next to "Resume with:+ * ix context --resume <id>", and `--resume` sanitizes what it is given: an id+ * saved as `widget/auth` was listed as `widget~2Fauth`, and resuming that+ * looked for `widget~7E2Fauth`, which does not exist.*- * `sanitizeId(unsanitizeId(stored)) === stored` for every id this CLI wrote,- * which is what makes the listed id usable. A hand-written file whose id is- * outside `sanitizeId`'s range has no input that reaches it and is not a case- * this recovers.+ * The escape is not fixed-width, and that is why this decodes and then+ * re-encodes rather than trusting the decode. `toString(16)` gives two hex+ * digits below U+0100 and three or four above it, so `~7528` is either one CJK+ * code unit or `~752` followed by a literal `8`, and nothing in the string says+ * which. Two hex digits is the case every Latin-1 id takes; anything else fails+ * the re-encode and the stored id is returned untouched, which is honest rather+ * than a guess. `loadInvestigation` accepts that form too, so a listed id loads+ * either way — the display is the nicety, the load is the contract.*/-export function unsanitizeId(stored: string): string {- return stored.replace(/~([0-9A-Fa-f]{2})/g, (_m, hex: string) =>+export function displayId(stored: string): string {+ const decoded = stored.replace(/~([0-9A-Fa-f]{2})/g, (_m, hex: string) =>String.fromCharCode(parseInt(hex, 16)),);+ return sanitizeId(decoded) === stored ? decoded : stored;}+/**+ * The shape `sanitizeId` produces: what a file in the investigations directory+ * can be named, and therefore what `loadInvestigation` may accept verbatim.+ *+ * The leading character excludes `.` so no input names a dotfile, and the set+ * excludes every path separator, so nothing here can address a second directory+ * segment or a parent.+ */+const STORED_ID = /^[A-Za-z0-9_~-][A-Za-z0-9._~-]*$/;+export function saveInvestigation(id: string, bundle: ContextBundle): void {const dir = investigationDir();mkdirSync(dir, { recursive: true });@@ -537,11 +627,13 @@ interface SavedInvestigation {*/export function mergeDiffOptions(saved: SavedInvestigation,- opts: { asOfRev?: string; depth?: string },-): { asOfRev?: string; depth?: string } {- const savedRev = saved.bundle.metadata.asOfRev;+ opts: { asOfRev?: number; depth?: string },+): { asOfRev?: number; depth?: string } {+ // Numbers on both sides now: `--as-of-rev` is validated by its Commander+ // argParser, so the round trip through a string that this used to do -- and+ // the `parseInt` on the far side of it -- is gone.return {- asOfRev: opts.asOfRev ?? (savedRev === undefined ? undefined : String(savedRev)),+ asOfRev: opts.asOfRev ?? saved.bundle.metadata.asOfRev,depth: opts.depth ?? saved.bundle.metadata.depth,};}@@ -582,8 +674,11 @@ export function listInvestigations(): { saved: SavedInvestigation[]; skipped: nu// The validated value, not the raw parse — the same assertion// `loadInvestigation` makes, and for the same reason: it re-narrows the// open report arrays the schema leaves as records, and every field the- // renderer dereferences has been checked by this point.- out.push(parsed.data as unknown as SavedInvestigation);+ // renderer dereferences has been checked by this point. The id is decoded+ // here too, so every reader of an enumerated investigation sees the id it+ // can type back — see `displayId`.+ const state = parsed.data as unknown as SavedInvestigation;+ out.push({ ...state, id: displayId(state.id) });}out.sort((a, b) => {if (a.savedAt !== b.savedAt) return a.savedAt < b.savedAt ? 1 : -1;@@ -594,7 +689,7 @@ export function listInvestigations(): { saved: SavedInvestigation[]; skipped: nu/** One saved investigation as `--list` describes it: what it is, not what is in it. */interface InvestigationSummary {- /** The id to type back, not the id on disk — see `unsanitizeId`. */+ /** The id to type back, not the id on disk — decoded by `displayId` on read. */id: string;savedAt: string;target: { name: string; kind: string };@@ -607,7 +702,7 @@ interface InvestigationSummary {function summariseInvestigation(s: SavedInvestigation): InvestigationSummary {const b = s.bundle;return {- id: unsanitizeId(s.id),+ id: s.id,savedAt: s.savedAt,target: { name: b.target.name, kind: b.target.kind },freshness: b.freshness,@@ -650,9 +745,8 @@ export function renderInvestigationList(// caller was piping. Plain text rather than chalk — nothing else in this// file writes to stderr, and a colour code is not worth an import that// only this line needs.- console.error(- ` Warning ${skipped} saved investigation file(s) did not match the contract; skipped.` +- " Run `ix context --resume <id>` for a per-file report.",+ renderWarningErr(+ `${skipped} saved investigation file(s) in ${investigationDir()} did not match the contract; skipped.`,);}if (format === "json") {@@ -728,14 +822,24 @@ function refuseInvestigation(code: string, message: string, format?: string): un// of the record stream — and with a prose line inside the JSON payload for a// `--format json` caller piping to `jq`. The human keeps the same wording, on// stderr, where prose belongs whatever the format.- if (format === "llm") console.log(llmError(code, message));- else console.error(` Warning ${message}`);- process.exitCode = 1;+ reportFailure(code, message, format);return undefined;}export function loadInvestigation(id: string, format?: string): SavedInvestigation | undefined {- const path = investigationPath(id);+ let path = investigationPath(id);+ if (!existsSync(path) && STORED_ID.test(id)) {+ // Also accept the on-disk form. `sanitizeId` is not idempotent, so an id+ // that is already encoded gets encoded again and misses its own file:+ // `widget/auth` is stored as `widget~2Fauth`, and asking for+ // `widget~2Fauth` looked for `widget~7E2Fauth`. `displayId` recovers the+ // typed form for every Latin-1 id, but the escape width is ambiguous above+ // that, so for the rest the encoded name is the only thing a listing can+ // print — and it has to work. Second, not first, so an id that is genuinely+ // spelled `widget~2Fauth` still finds its own file before this.+ const encoded = join(investigationDir(), `${id}.json`);+ if (existsSync(encoded)) path = encoded;+ }if (!existsSync(path)) {return refuseInvestigation("no_saved_investigation", `No saved investigation "${id}" at ${path}`, format);}@@ -788,10 +892,17 @@ export function loadInvestigation(id: string, format?: string): SavedInvestigati// the backend) plus the literals zod widens to `string`. Every field this file// dereferences has been checked by this point — unlike the `as` cast on raw// JSON.parse output that this replaces, which checked nothing.- return parsed.data as unknown as SavedInvestigation;+ //+ // The id is decoded here, at the one boundary every reader comes through,+ // rather than at each place one is printed. Decoding per call site is how+ // `--format llm` came to report `widget/auth` while `--format json` and the+ // text header reported `widget~2Fauth` for the same investigation, and a+ // JSON-chaining caller fed the second back to `--resume` and was refused.+ const state = parsed.data as unknown as SavedInvestigation;+ return { ...state, id: displayId(state.id) };}-function renderSavedInvestigation(id: string, format: string): void {+export function renderSavedInvestigation(id: string, format: string): void {const saved = loadInvestigation(id, format);if (!saved) return;if (format === "json") {@@ -804,11 +915,11 @@ function renderSavedInvestigation(id: string, format: string): void {// it carries the one fact the bundle records do not: when this snapshot// was taken. `classification=current` says it was fresh when it was// saved, not when that was.- printLlmLines([llmLine("investigation", { id: unsanitizeId(saved.id), saved_at: saved.savedAt })]);+ printLlmLines([llmLine("resumed", { id: saved.id, saved_at: saved.savedAt })]);renderBundle(saved.bundle, format);return;}- renderNote(`Resumed investigation "${unsanitizeId(saved.id)}" saved ${saved.savedAt}`);+ renderNote(`Resumed investigation "${saved.id}" saved ${saved.savedAt}`);renderBundle(saved.bundle, format);}@@ -885,10 +996,20 @@ export function diffInvestigations(// while the fresh side used another one -- the silent misreport this record// exists to prevent. `ContextBundle.budgets` records the truth on both sides.const effective: BudgetSnapshot = { ...fresh.budgets };- // Whether the caller's --max-* flags governed the fresh side. Derived by- // comparison rather than hardcoded false, for the same reason.- const requestedApplied = requestedBudgets !== undefined- && BUDGETS.every((f) => requestedBudgets[f.key] === undefined || requestedBudgets[f.key] === effective[f.key]);+ // Whether the caller's --max-* flags governed the fresh side.+ //+ // Not `requested equals effective`. Equal numbers are not evidence of+ // causation: `--max-evidence 25` against a saved budget of 25 produces+ // identical values while the flag changed nothing, and reporting `true` there+ // told an agent its override had taken -- so it raised the number, got the+ // saved budget again and now `false`. Three formats of one command disagreed,+ // because the note printed beside it said the opposite.+ //+ // What decides this is which budget the action handler hands+ // `buildFreshBundle`, and that is `saved.bundle.budgets` unconditionally, one+ // call site named in the comment there. So this is false, and the day that+ // call changes it is the day this needs to change with it.+ const requestedApplied = false;return {schema: "ix-investigation-diff/1",@@ -1024,7 +1145,7 @@ export function renderInvestigationDiff(// record per line invariant.printLlmLines([llmLine("diff", {- investigation: unsanitizeId(saved.id),+ investigation: saved.id,target: fresh.target.name,// How old the saved side is. `freshness_previous=current` says the// snapshot was fresh when it was taken, not when that was — and adiff --git a/ix-cli/src/cli/commands/diff.ts b/ix-cli/src/cli/commands/diff.tsindex 8f749e37..0611f512 100644--- a/ix-cli/src/cli/commands/diff.ts+++ b/ix-cli/src/cli/commands/diff.ts@@ -10,7 +10,8 @@ import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";import { resolveFileOrEntity, resolveEntityFull, printResolved, looksFileLike, type ResolvedEntity } from "../resolve.js";import { formatDiff, relativePath } from "../format.js";-import { llmLine, llmError, reportModeConflict } from "../llm.js";+import { llmLine, llmError } from "../llm.js";+import { reportFailure } from "../ui.js";import { parsePickOption } from "../options.js";/**@@ -482,7 +483,7 @@ export function registerDiffCommand(program: Command): void {}) => {const conflict = detectDiffModeConflict(opts);if (conflict) {- reportModeConflict(conflict, opts.format);+ reportFailure("mode_conflict", conflict, opts.format);return;}const client = new IxClient(getEndpoint());diff --git a/ix-cli/src/cli/llm.ts b/ix-cli/src/cli/llm.tsindex 8a30b9ad..5339010e 100644--- a/ix-cli/src/cli/llm.ts+++ b/ix-cli/src/cli/llm.ts@@ -18,8 +18,6 @@* newlines/tabs are encoded as `\n`/`\r`/`\t` so a record never spans lines.*/-import chalk from "chalk";-/** A field value before rendering. Nullish/empty values are omitted. */export type LlmValue = string | number | boolean | null | undefined;@@ -100,26 +98,3 @@ export function printLlmLines(lines: Array<string | null | undefined>): void {if (line != null) console.log(line);}}--/**- * Report a mutually-exclusive flag combination in the format the caller asked- * for, and mark the run failed.- *- * Both halves matter. `--format llm` gets the `error code=... message="..."`- * record on stdout that imports.ts, trace.ts, locate.ts and callers.ts already- * emit and that docs/llm-format.md specifies: an agent is told to pass the flag- * unconditionally, so an error it cannot parse is an error it cannot act on.- * Every other format gets the human line on stderr, so a `--format json` caller- * piping to `jq` never finds prose in the payload.- *- * One function because it was otherwise written twice, byte for byte including- * its docblock, in `context.ts` and `diff.ts`. What it encodes -- which stream,- * which record kind, which exit code -- is a convention that has to change- * everywhere at once or not at all, and `subsystems.ts` already carries six- * copies of the stderr half for the same reason.- */-export function reportModeConflict(message: string, format?: string): void {- if (format === "llm") console.log(llmError("mode_conflict", message));- else console.error(chalk.red("Error:"), message);- process.exitCode = 1;-}diff --git a/ix-cli/src/cli/options.ts b/ix-cli/src/cli/options.tsindex e76bd150..921580e1 100644--- a/ix-cli/src/cli/options.ts+++ b/ix-cli/src/cli/options.ts@@ -36,7 +36,25 @@ export function parsePickOption(value: string): number {* requested budget back to the caller, and a silently repaired number* (`--max-entities 1e3` becoming 1) is a misreport of the one thing that record* exists to carry.+ *+ * `example` is the flag's own default, supplied by the caller. A shared literal+ * would be wrong for at least one flag: `--max-chars` starts at 12000 and+ * clamps up from anything below 1000, so suggesting 50 there names a value the+ * command silently replaces.+ */+export function parseBudgetOption(value: string, example: string): number {+ return parsePositiveInt(value, example);+}++/**+ * Parse a revision flag: a positive integer graph revision.+ *+ * `parseInt(opts.asOfRev, 10)` reached `client.query({ asOfRev })` and+ * `buildBundle` unchecked, so `--as-of-rev abc` sent NaN to the backend,+ * `--as-of-rev 3.9` silently became 3, and `--as-of-rev 10abc` became 10 — the+ * same not-a-validator failure the budget flags had, on the flag two lines+ * above them.*/-export function parseBudgetOption(value: string): number {- return parsePositiveInt(value, "50");+export function parseRevisionOption(value: string): number {+ return parsePositiveInt(value, "12");}diff --git a/ix-cli/src/cli/ui.ts b/ix-cli/src/cli/ui.tsindex 582cff87..b29aaa0e 100644--- a/ix-cli/src/cli/ui.ts+++ b/ix-cli/src/cli/ui.ts@@ -7,6 +7,8 @@import chalk from "chalk";+import { llmError } from "./llm.js";+// ── Brand palette ─────────────────────────────────────────────────────────────//// Primary / kind accent chalk.cyan@@ -70,6 +72,22 @@ export function renderWarning(text: string): void {console.log(` ${chalk.yellow("Warning")} ${chalk.yellow(text)}`);}+/**+ * The same warning, on stderr.+ *+ * Every renderer here writes to stdout, which is where a command's payload+ * goes: a warning printed alongside a `--format json` bundle lands inside what+ * the caller pipes to `jq`, and inside the record stream for `--format llm`.+ * When a command has a machine format, its prose belongs on the other stream.+ *+ * Same padding and same colour as `renderWarning`, deliberately — this had been+ * hand-rolled twice as `console.error(" Warning " + text)`, which put the+ * convention in three places and dropped the colour humans were getting.+ */+export function renderWarningErr(text: string): void {+ console.error(` ${chalk.yellow("Warning")} ${chalk.yellow(text)}`);+}+/** Success confirmation. */export function renderSuccess(text: string): void {console.log(` ${chalk.green(text)}`);@@ -86,3 +104,30 @@ export function renderError(text: string): void {export function renderResolvedHeader(kind: string, name: string): void {console.log(`${chalk.bold("Resolved:")} ${chalk.cyan(kind)} ${chalk.bold(name)}`);}++/**+ * Report a command failure in the format the caller asked for, and mark the run+ * failed.+ *+ * Both halves matter. `--format llm` gets the `error code=... message="..."`+ * record on stdout that `callers.ts`, `contains.ts`, `depends.ts`, `diff.ts` and+ * `history.ts` already emit and that docs/llm-format.md specifies: an agent is+ * told to pass the flag unconditionally, so an error it cannot parse is an+ * error it cannot act on. Every other format gets the human line on stderr, so+ * a `--format json` caller piping to `jq` never finds prose in the payload.+ *+ * One function because it was otherwise written twice, byte for byte including+ * its docblock, in `context.ts` and `diff.ts`, while five more refusals in the+ * same handler wrote `renderWarning` — which is `console.log` — and left the+ * exit code at 0, so a script could not tell a refusal from an empty success.+ * `subsystems.ts` carries six more copies of the stderr half.+ *+ * Here rather than in `llm.ts`: this is an output-routing decision, and putting+ * it there forced `chalk` into the module documented as the token-minimal wire+ * format renderer, for the sake of one human-facing line.+ */+export function reportFailure(code: string, message: string, format?: string): void {+ if (format === "llm") console.log(llmError(code, message));+ else console.error(chalk.red("Error:"), message);+ process.exitCode = 1;+}