Skip to content

armgit / Ix

Public Imported from GitHub
0

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

fix(cli): validate pick options consistently (#438)

Hiro-Chiba043bc68f0fb7
diff --git a/ix-cli/src/cli/__tests__/context-pick-validation.test.ts b/ix-cli/src/cli/__tests__/context-pick-validation.test.ts
new file mode 100644
index 00000000..58851153
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/context-pick-validation.test.ts
@@ -0,0 +1,65 @@
+import { Command, type CommanderError } from "commander";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const resolveFileOrEntity = vi.hoisted(() => vi.fn());
+
+vi.mock("../resolve.js", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../resolve.js")>()),
+ resolveFileOrEntity,
+}));
+
+import { registerContextCommand } from "../commands/context.js";
+
+async function runContext(args: string[]): Promise<{ error?: CommanderError; stderr: string }> {
+ const stderr: string[] = [];
+ const program = new Command()
+ .name("ix")
+ .exitOverride()
+ .configureOutput({ writeErr: (chunk) => stderr.push(chunk) });
+ registerContextCommand(program);
+
+ try {
+ await program.parseAsync(["context", "Widget", ...args], { from: "user" });
+ return { stderr: stderr.join("") };
+ } catch (error) {
+ return { error: error as CommanderError, stderr: stderr.join("") };
+ }
+}
+
+describe("ix context --pick validation", () => {
+ beforeEach(() => {
+ resolveFileOrEntity.mockReset().mockResolvedValue(undefined);
+ });
+
+ it.each(["nope", "1nope"])("rejects the complete value %j before resolving", async (pick) => {
+ const result = await runContext(["--pick", pick]);
+
+ expect(result.error?.exitCode).toBe(1);
+ expect(result.stderr).toContain("argument '" + pick + "' is invalid");
+ expect(result.stderr).toContain("must be a positive integer");
+ expect(result.stderr).not.toContain("TypeError");
+ expect(resolveFileOrEntity).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ["1", 1],
+ ["2", 2],
+ ])("passes valid pick %s to resolution as an integer", async (rawPick, expectedPick) => {
+ const result = await runContext([
+ "--pick",
+ rawPick,
+ "--kind",
+ "function",
+ "--path",
+ "src/main.ts",
+ ]);
+
+ expect(result.error).toBeUndefined();
+ expect(resolveFileOrEntity).toHaveBeenCalledOnce();
+ expect(resolveFileOrEntity.mock.calls[0]?.[2]).toEqual({
+ kind: "function",
+ path: "src/main.ts",
+ pick: expectedPick,
+ });
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/depends-semantics.test.ts b/ix-cli/src/cli/__tests__/depends-semantics.test.ts
index effe5f79..65a8a617 100644
--- a/ix-cli/src/cli/__tests__/depends-semantics.test.ts
+++ b/ix-cli/src/cli/__tests__/depends-semantics.test.ts
@@ -106,8 +106,7 @@ describe("depends nested tree structure", () => {
describe("depends input validation", () => {
it("validates --pick as positive integer", () => {
- expect(dependsContent).toContain("Invalid value for --pick");
- expect(dependsContent).toContain("must be a positive integer");
+ expect(dependsContent).toContain("parsePickOption");
});
it("supports --pick option", () => {
diff --git a/ix-cli/src/cli/__tests__/diff-content.test.ts b/ix-cli/src/cli/__tests__/diff-content.test.ts
index ecfc9430..75f52e18 100644
--- a/ix-cli/src/cli/__tests__/diff-content.test.ts
+++ b/ix-cli/src/cli/__tests__/diff-content.test.ts
@@ -202,8 +202,9 @@ describe("diff.ts resolver flags", () => {
expect(diffContent).toContain("resolveFileOrEntity(client, target, resolveOpts)");
});
- it("converts --pick string to number", () => {
- expect(diffContent).toContain("parseInt(opts.pick, 10)");
+ it("parses --pick as a positive integer", () => {
+ expect(diffContent).toContain("parsePickOption");
+ expect(diffContent).toContain("pick: opts.pick");
});
it("imports printResolved for text-mode output", () => {
diff --git a/ix-cli/src/cli/__tests__/pick-option-validation.test.ts b/ix-cli/src/cli/__tests__/pick-option-validation.test.ts
new file mode 100644
index 00000000..b9d0c16b
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/pick-option-validation.test.ts
@@ -0,0 +1,61 @@
+import { Command, type CommanderError } from "commander";
+import { describe, expect, it } from "vitest";
+
+import { parsePickOption } from "../options.js";
+import { registerOssCommands } from "../register/oss.js";
+
+const PICK_COMMANDS: Array<[string, string[]]> = [
+ ["callers", ["callers", "Widget"]],
+ ["callees", ["callees", "Widget"]],
+ ["contains", ["contains", "Widget"]],
+ ["context", ["context", "Widget"]],
+ ["depends", ["depends", "Widget"]],
+ ["diff", ["diff", "1", "2", "Widget"]],
+ ["explain", ["explain", "Widget"]],
+ ["history", ["history", "Widget"]],
+ ["impact", ["impact", "Widget"]],
+ ["imported-by", ["imported-by", "Widget"]],
+ ["imports", ["imports", "Widget"]],
+ ["locate", ["locate", "Widget"]],
+ ["overview", ["overview", "Widget"]],
+ ["read", ["read", "Widget"]],
+ ["subsystems", ["subsystems", "Widget"]],
+ ["trace", ["trace", "Widget"]],
+];
+
+async function rejectPick(args: string[], pick: string): Promise<{ error?: CommanderError; stderr: string }> {
+ const stderr: string[] = [];
+ const program = new Command()
+ .name("ix")
+ .exitOverride()
+ .configureOutput({ writeErr: (chunk) => stderr.push(chunk) });
+ registerOssCommands(program);
+
+ try {
+ await program.parseAsync([...args, "--pick", pick], { from: "user" });
+ return { stderr: stderr.join("") };
+ } catch (error) {
+ return { error: error as CommanderError, stderr: stderr.join("") };
+ }
+}
+
+describe("shared --pick validation", () => {
+ it.each(PICK_COMMANDS)("rejects a partial integer before running %s", async (_name, args) => {
+ const result = await rejectPick(args, "1nope");
+
+ expect(result.error?.exitCode).toBe(1);
+ expect(result.stderr).toContain("must be a positive integer");
+ expect(result.stderr).not.toContain("TypeError");
+ });
+
+ it.each(["nope", "0", "-1", "9007199254740992"])("rejects %j", (value) => {
+ expect(() => parsePickOption(value)).toThrow("must be a positive integer");
+ });
+
+ it.each([
+ ["1", 1],
+ ["+2", 2],
+ ])("parses %s", (value, expected) => {
+ expect(parsePickOption(value)).toBe(expected);
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/resolver-consistency.test.ts b/ix-cli/src/cli/__tests__/resolver-consistency.test.ts
index f0c056de..fed55b53 100644
--- a/ix-cli/src/cli/__tests__/resolver-consistency.test.ts
+++ b/ix-cli/src/cli/__tests__/resolver-consistency.test.ts
@@ -30,7 +30,8 @@ describe("resolver flag consistency across content commands", () => {
});
it("passes pick as number to resolver", () => {
- expect(content).toContain("parseInt(opts.pick, 10)");
+ expect(content).toContain("parsePickOption");
+ expect(content).toContain("pick: opts.pick");
});
});
}
diff --git a/ix-cli/src/cli/commands/callers.ts b/ix-cli/src/cli/commands/callers.ts
index ea39aa50..034a7527 100644
--- a/ix-cli/src/cli/commands/callers.ts
+++ b/ix-cli/src/cli/commands/callers.ts
@@ -5,6 +5,7 @@ import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint, resolveWorkspaceRoot } from "../config.js";
import { formatEdgeResults, relativePath } from "../format.js";
+import { parsePickOption } from "../options.js";
import { resolveFileOrEntity, printResolved } from "../resolve.js";
import { stderr } from "../stderr.js";
import { llmLine, llmError } from "../llm.js";
@@ -21,14 +22,14 @@ export function registerCallersCommand(program: Command): void {
.command("callers <symbol>")
.description("Show methods/functions that call the given symbol (cross-file)")
.option("--kind <kind>", "Filter target entity by kind")
- .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")
+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)
.option("--limit <n>", "Max results to show", "50")
.option("--format <fmt>", "Output format (text|json|llm)", "text")
.addHelpText("after", "\nExamples:\n ix callers verify_token\n ix callers processPayment --format json\n ix callers parse --kind method --limit 20")
- .action(async (symbol: string, opts: { kind?: string; pick?: string; limit: string; format: string }) => {
+ .action(async (symbol: string, opts: { kind?: string; pick?: number; limit: string; format: string }) => {
const client = new IxClient(getEndpoint());
const limit = parseInt(opts.limit, 10);
- const resolveOpts = { kind: opts.kind, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
+ const resolveOpts = { kind: opts.kind, pick: opts.pick };
const target = await resolveFileOrEntity(client, symbol, resolveOpts);
if (!target) { llmUnresolved(opts.format, symbol); return; }
if (opts.format === "text") printResolved(target);
@@ -124,14 +125,14 @@ export function registerCallersCommand(program: Command): void {
.command("callees <symbol>")
.description("Show methods/functions called by the given symbol (cross-file)")
.option("--kind <kind>", "Filter target entity by kind")
- .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")
+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)
.option("--limit <n>", "Max results to show", "50")
.option("--format <fmt>", "Output format (text|json|llm)", "text")
.addHelpText("after", "\nExamples:\n ix callees processPayment\n ix callees parse --format json")
- .action(async (symbol: string, opts: { kind?: string; pick?: string; limit: string; format: string }) => {
+ .action(async (symbol: string, opts: { kind?: string; pick?: number; limit: string; format: string }) => {
const client = new IxClient(getEndpoint());
const calleeLimit = parseInt(opts.limit, 10);
- const resolveOpts = { kind: opts.kind, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
+ const resolveOpts = { kind: opts.kind, pick: opts.pick };
const target = await resolveFileOrEntity(client, symbol, resolveOpts);
if (!target) { llmUnresolved(opts.format, symbol); return; }
if (opts.format === "text") printResolved(target);
diff --git a/ix-cli/src/cli/commands/contains.ts b/ix-cli/src/cli/commands/contains.ts
index de9e1f3e..830bbc3d 100644
--- a/ix-cli/src/cli/commands/contains.ts
+++ b/ix-cli/src/cli/commands/contains.ts
@@ -2,6 +2,7 @@ import type { Command } from "commander";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
import { formatEdgeResults } from "../format.js";
+import { parsePickOption } from "../options.js";
import { resolveFileOrEntity, printResolved } from "../resolve.js";
import { llmError } from "../llm.js";
@@ -11,14 +12,14 @@ export function registerContainsCommand(program: Command): void {
.description("Show members contained by the given entity (class, module, file)")
.option("--kind <kind>", "Filter target entity by kind")
.option("--path <path>", "Filter target entity by file path (substring match)")
- .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")
+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)
.option("--limit <n>", "Max results to show", "50")
.option("--format <fmt>", "Output format (text|json|llm)", "text")
.addHelpText("after", "\nExamples:\n ix contains IngestionService\n ix contains auth.py --kind file --format json\n ix contains MyClass --limit 20\n ix contains package --path crates/regex/Cargo.toml")
- .action(async (symbol: string, opts: { kind?: string; path?: string; pick?: string; limit: string; format: string }) => {
+ .action(async (symbol: string, opts: { kind?: string; path?: string; pick?: number; limit: string; format: string }) => {
const client = new IxClient(getEndpoint());
const limit = parseInt(opts.limit, 10);
- const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
+ const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick };
const target = await resolveFileOrEntity(client, symbol, resolveOpts);
if (!target) {
if (opts.format === "llm") console.log(llmError("unresolved_target", `No entity resolved for "${symbol}".`));
diff --git a/ix-cli/src/cli/commands/context.ts b/ix-cli/src/cli/commands/context.ts
index d2ee39bb..5d868db9 100644
--- a/ix-cli/src/cli/commands/context.ts
+++ b/ix-cli/src/cli/commands/context.ts
@@ -16,6 +16,7 @@ import type {
import { getEndpoint } from "../config.js";
import { collectFacts, type EntityFacts } from "../explain/facts.js";
import { printLlmLines } from "../llm.js";
+import { parsePickOption } from "../options.js";
import { resolveFileOrEntity } from "../resolve.js";
import { createStaleProbe } from "../stale.js";
import { renderNote, renderSection, renderWarning } from "../ui.js";
@@ -29,7 +30,7 @@ const BUNDLE_SCHEMA = "ix-context-bundle/1";
interface ContextOptions {
kind?: string;
path?: string;
- pick?: string;
+ pick?: number;
depth?: string;
asOfRev?: string;
maxEntities?: string;
@@ -119,7 +120,7 @@ export function registerContextCommand(program: Command): void {
)
.option("--kind <kind>", "Filter target entity by kind")
.option("--path <path>", "Prefer symbols from files matching this path substring")
- .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")
+ .option("--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("--max-entities <n>", "Maximum entities in the bundle", "50")
@@ -162,7 +163,7 @@ export function registerContextCommand(program: Command): void {
const resolved = await resolveFileOrEntity(client, target, {
kind: opts.kind,
path: opts.path,
- pick: opts.pick ? parseInt(opts.pick, 10) : undefined,
+ pick: opts.pick,
});
if (!resolved) return;
@@ -243,14 +244,14 @@ export function registerContextCommand(program: Command): void {
async function buildFreshBundle(
target: string,
- opts: { kind?: string; path?: string; pick?: string; depth?: string; asOfRev?: string },
+ opts: { kind?: string; path?: string; pick?: number; depth?: string; asOfRev?: string },
budgets: { maxEntities: number; maxRelationships: number; maxEvidence: number; maxChars: number },
): Promise<ContextBundle | undefined> {
const client = new IxClient(getEndpoint());
const resolved = await resolveFileOrEntity(client, target, {
kind: opts.kind,
path: opts.path,
- pick: opts.pick ? parseInt(opts.pick, 10) : undefined,
+ pick: opts.pick,
});
if (!resolved) return undefined;
diff --git a/ix-cli/src/cli/commands/depends.ts b/ix-cli/src/cli/commands/depends.ts
index a58f4f3a..9d2d9049 100644
--- a/ix-cli/src/cli/commands/depends.ts
+++ b/ix-cli/src/cli/commands/depends.ts
@@ -3,9 +3,9 @@ import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
import { resolveFileOrEntity, printResolved, isRawId } from "../resolve.js";
-import { stderr } from "../stderr.js";
import { compactTreeNode, relativePath } from "../format.js";
import { llmLine, llmError } from "../llm.js";
+import { parsePickOption } from "../options.js";
// ── Tree types ──────────────────────────────────────────────────────
@@ -192,7 +192,7 @@ export function registerDependsCommand(program: Command): void {
.description("Show upstream dependents of the given entity (full tree by default)")
.option("--kind <kind>", "Filter target entity by kind")
.option("--path <path>", "Prefer symbols from files matching this path substring")
- .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")
+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)
.option("--depth <n>", "Cap traversal depth")
.option("--cap <n>", "Cap number of nodes visited")
.option("--format <fmt>", "Output format (text|json|llm)", "text")
@@ -204,22 +204,13 @@ export function registerDependsCommand(program: Command): void {
ix depends AuthProvider --depth 2
ix depends parser.py --kind file
ix depends NodeKind --pick 1 --cap 500`)
- .action(async (symbol: string, opts: { kind?: string; path?: string; pick?: string; depth?: string; cap?: string; format: string; includeTests?: boolean; testsOnly?: boolean }) => {
+ .action(async (symbol: string, opts: { kind?: string; path?: string; pick?: number; depth?: string; cap?: string; format: string; includeTests?: boolean; testsOnly?: boolean }) => {
const client = new IxClient(getEndpoint());
- // Validate --pick
- if (opts.pick !== undefined) {
- const pickVal = parseInt(opts.pick, 10);
- if (isNaN(pickVal) || pickVal < 1) {
- stderr(`Invalid value for --pick: must be a positive integer.`);
- return;
- }
- }
-
const resolveOpts = {
kind: opts.kind,
path: opts.path,
- pick: opts.pick ? parseInt(opts.pick, 10) : undefined,
+ pick: opts.pick,
includeTests: opts.includeTests,
testsOnly: opts.testsOnly,
};
diff --git a/ix-cli/src/cli/commands/diff.ts b/ix-cli/src/cli/commands/diff.ts
index 8598224b..b06c894f 100644
--- a/ix-cli/src/cli/commands/diff.ts
+++ b/ix-cli/src/cli/commands/diff.ts
@@ -10,6 +10,7 @@ import { getEndpoint } from "../config.js";
import { resolveFileOrEntity, resolveEntityFull, printResolved, looksFileLike, type ResolvedEntity } from "../resolve.js";
import { formatDiff, relativePath } from "../format.js";
import { llmLine, llmError } from "../llm.js";
+import { parsePickOption } from "../options.js";
/** Render a `--summary` diff as a single llm record. */
function renderDiffSummaryLlm(result: any): string {
@@ -419,7 +420,7 @@ export function registerDiffCommand(program: Command): void {
.option("--format <fmt>", "Output format (text|json|llm)", "text")
.option("--kind <kind>", "Filter target entity by kind")
.option("--path <path>", "Prefer symbols from files matching this path substring")
- .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")
+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)
.addHelpText("after", `\nExamples:
ix diff 3 5
ix diff 3 5 ix-cli/src/cli/commands/decide.ts
@@ -428,7 +429,7 @@ export function registerDiffCommand(program: Command): void {
ix diff 3 5 --summary`)
.action(async (fromRev: string, toRev: string, target: string | undefined, opts: {
entity?: string; summary?: boolean; content?: boolean; limit?: string; full?: boolean; format: string;
- kind?: string; path?: string; pick?: string;
+ kind?: string; path?: string; pick?: number;
}) => {
const client = new IxClient(getEndpoint());
const from = parseInt(fromRev, 10);
@@ -438,7 +439,7 @@ export function registerDiffCommand(program: Command): void {
const resolveOpts = {
kind: opts.kind,
path: opts.path,
- pick: opts.pick ? parseInt(opts.pick, 10) : undefined,
+ pick: opts.pick,
};
let entityId: string | undefined = opts.entity;
let resolved: ResolvedEntity | null = null;
diff --git a/ix-cli/src/cli/commands/explain.ts b/ix-cli/src/cli/commands/explain.ts
index ea8a8ed3..16971285 100644
--- a/ix-cli/src/cli/commands/explain.ts
+++ b/ix-cli/src/cli/commands/explain.ts
@@ -10,6 +10,7 @@ import { inferImportance } from "../explain/importance.js";
import { renderExplanation } from "../explain/render.js";
import { renderExplainLlm, renderExplainRawLlm } from "../explain/llm.js";
import { printLlmLines } from "../llm.js";
+import { parsePickOption } from "../options.js";
import { renderSection, renderWarning, renderNote } from "../ui.js";
export function registerExplainCommand(program: Command): void {
@@ -18,13 +19,13 @@ export function registerExplainCommand(program: Command): void {
.description("Explain an entity — infers role, importance, and structural context")
.option("--kind <kind>", "Filter target entity by kind")
.option("--path <path>", "Prefer symbols from files matching this path substring")
- .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")
+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)
.option("--format <fmt>", "Output format (text|json|llm)", "text")
.option("--raw", "Show raw metadata dump (legacy format)")
.addHelpText("after", "\nExamples:\n ix explain IngestionService\n ix explain expand --path memory-layer\n ix explain verify_token --kind function --format json\n ix explain IxClient --raw")
- .action(async (symbol: string, opts: { kind?: string; path?: string; pick?: string; format: string; raw?: boolean }) => {
+ .action(async (symbol: string, opts: { kind?: string; path?: string; pick?: number; format: string; raw?: boolean }) => {
const client = new IxClient(getEndpoint());
- const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
+ const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick };
const target = await resolveFileOrEntity(client, symbol, resolveOpts);
if (!target) return;
diff --git a/ix-cli/src/cli/commands/history.ts b/ix-cli/src/cli/commands/history.ts
index 0eb81964..284e13e0 100644
--- a/ix-cli/src/cli/commands/history.ts
+++ b/ix-cli/src/cli/commands/history.ts
@@ -5,6 +5,7 @@ import { getEndpoint } from "../config.js";
import { resolveFileOrEntity, printResolved } from "../resolve.js";
import { relativePath } from "../format.js";
import { llmLine, llmError } from "../llm.js";
+import { parsePickOption } from "../options.js";
/** Render an entity's provenance chain as llm records: a header then one `patch` row per revision. */
export function renderHistoryLlm(
@@ -28,16 +29,16 @@ export function registerHistoryCommand(program: Command): void {
.description("Show provenance chain for a file or entity")
.option("--kind <kind>", "Filter target entity by kind")
.option("--path <path>", "Prefer symbols from files matching this path substring")
- .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")
+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)
.option("--format <fmt>", "Output format (text|json|llm)", "text")
.addHelpText("after", `\nExamples:
ix history ix-cli/src/cli/commands/decide.ts
ix history decide.ts
ix history IngestionService --kind class
ix history <entity-uuid>`)
- .action(async (target: string, opts: { kind?: string; path?: string; pick?: string; format: string }) => {
+ .action(async (target: string, opts: { kind?: string; path?: string; pick?: number; format: string }) => {
const client = new IxClient(getEndpoint());
- const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
+ const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick };
const resolved = await resolveFileOrEntity(client, target, resolveOpts);
if (!resolved) {
if (opts.format === "llm") console.log(llmError("unresolved_target", `No entity resolved for "${target}".`));
diff --git a/ix-cli/src/cli/commands/impact.ts b/ix-cli/src/cli/commands/impact.ts
index 3152b307..c30ff0f1 100644
--- a/ix-cli/src/cli/commands/impact.ts
+++ b/ix-cli/src/cli/commands/impact.ts
@@ -8,6 +8,7 @@ import { bucketByHierarchy, getSystemPath, formatSystemPath, hasMapData, type Sy
import { inferRiskSemantics, humanizeLabel, type ImpactFacts, type RiskSemantics } from "../impact/risk-semantics.js";
import { stripNulls } from "../format.js";
import { llmLine, llmError } from "../llm.js";
+import { parsePickOption } from "../options.js";
const CONTAINER_KINDS = new Set(["class", "module", "file", "object", "trait", "interface"]);
@@ -16,7 +17,7 @@ export function registerImpactCommand(program: Command): void {
.command("impact <target>")
.description("System risk analysis — what behavior is at risk if this changes")
.option("--kind <kind>", "Filter target entity by kind")
- .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")
+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)
.option("--depth <n>", "Expansion depth for callers/importers (default 1, max 3)", "1")
.option("--limit <n>", "Max top-impacted members to show", "10")
.option("--format <fmt>", "Output format (text|json|llm)", "text")
@@ -27,13 +28,13 @@ export function registerImpactCommand(program: Command): void {
.action(
async (
symbol: string,
- opts: { kind?: string; pick?: string; depth: string; limit: string; format: string }
+ opts: { kind?: string; pick?: number; depth: string; limit: string; format: string }
) => {
const client = new IxClient(getEndpoint());
const limit = parseInt(opts.limit, 10);
const depth = Math.min(Math.max(parseInt(opts.depth, 10) || 1, 1), 3);
- const resolveOpts = { kind: opts.kind, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
+ const resolveOpts = { kind: opts.kind, pick: opts.pick };
const target = await resolveFileOrEntity(client, symbol, resolveOpts);
if (!target) {
// The resolver already printed human guidance to stderr; for llm
diff --git a/ix-cli/src/cli/commands/imports.ts b/ix-cli/src/cli/commands/imports.ts
index d2474fd0..f5454cd8 100644
--- a/ix-cli/src/cli/commands/imports.ts
+++ b/ix-cli/src/cli/commands/imports.ts
@@ -4,6 +4,7 @@ import { getEndpoint } from "../config.js";
import { formatEdgeResults } from "../format.js";
import { resolveFileOrEntity, printResolved } from "../resolve.js";
import { llmError } from "../llm.js";
+import { parsePickOption } from "../options.js";
function llmUnresolved(format: string, symbol: string): void {
if (format === "llm") console.log(llmError("unresolved_target", `No entity resolved for "${symbol}".`));
@@ -14,14 +15,14 @@ export function registerImportsCommand(program: Command): void {
.command("imports <symbol>")
.description("Show what the given entity imports")
.option("--kind <kind>", "Filter target entity by kind")
- .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")
+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)
.option("--limit <n>", "Max results to show", "50")
.option("--format <fmt>", "Output format (text|json|llm)", "text")
.addHelpText("after", "\nExamples:\n ix imports auth.py\n ix imports IngestionService --format json")
- .action(async (symbol: string, opts: { kind?: string; pick?: string; limit: string; format: string }) => {
+ .action(async (symbol: string, opts: { kind?: string; pick?: number; limit: string; format: string }) => {
const client = new IxClient(getEndpoint());
const limit = parseInt(opts.limit, 10);
- const resolveOpts = { kind: opts.kind, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
+ const resolveOpts = { kind: opts.kind, pick: opts.pick };
const target = await resolveFileOrEntity(client, symbol, resolveOpts);
if (!target) { llmUnresolved(opts.format, symbol); return; }
if (opts.format === "text") printResolved(target);
@@ -33,14 +34,14 @@ export function registerImportsCommand(program: Command): void {
.command("imported-by <symbol>")
.description("Show what imports the given entity")
.option("--kind <kind>", "Filter target entity by kind")
- .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")
+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)
.option("--limit <n>", "Max results to show", "50")
.option("--format <fmt>", "Output format (text|json|llm)", "text")
.addHelpText("after", "\nExamples:\n ix imported-by AuthProvider\n ix imported-by io.circe.Json --format json")
- .action(async (symbol: string, opts: { kind?: string; pick?: string; limit: string; format: string }) => {
+ .action(async (symbol: string, opts: { kind?: string; pick?: number; limit: string; format: string }) => {
const client = new IxClient(getEndpoint());
const limit = parseInt(opts.limit, 10);
- const resolveOpts = { kind: opts.kind, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
+ const resolveOpts = { kind: opts.kind, pick: opts.pick };
const target = await resolveFileOrEntity(client, symbol, resolveOpts);
if (!target) { llmUnresolved(opts.format, symbol); return; }
if (opts.format === "text") printResolved(target);
diff --git a/ix-cli/src/cli/commands/locate.ts b/ix-cli/src/cli/commands/locate.ts
index 8e0e473e..ac22163b 100644
--- a/ix-cli/src/cli/commands/locate.ts
+++ b/ix-cli/src/cli/commands/locate.ts
@@ -9,6 +9,7 @@ import { isFileStale } from "../stale.js";
import { stderr } from "../stderr.js";
import { relativePath } from "../format.js";
import { llmLine, llmError } from "../llm.js";
+import { parsePickOption } from "../options.js";
import { getEffectiveSystemPath, hasMapData } from "../hierarchy.js";
import { humanizeLabel } from "../impact/risk-semantics.js";
import { renderSection, renderKeyValue, renderNote, renderWarning, renderBreadcrumb } from "../ui.js";
@@ -36,19 +37,19 @@ export function registerLocateCommand(program: Command): void {
.description("Resolve a symbol to its position in the codebase and system hierarchy")
.option("--kind <kind>", "Filter target entity by kind")
.option("--path <path>", "Prefer results from files matching this path substring")
- .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")
+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)
.option("--format <fmt>", "Output format (text|json|llm)", "text")
.addHelpText("after", `\nExamples:
ix locate IngestionService
ix locate verify_token --kind function
ix locate ArangoClient --format json
ix locate scoreCandidate --pick 2`)
- .action(async (symbol: string, opts: { kind?: string; path?: string; pick?: string; format: string }) => {
+ .action(async (symbol: string, opts: { kind?: string; path?: string; pick?: number; format: string }) => {
const client = new IxClient(getEndpoint());
const diagnostics: string[] = [];
const isJson = opts.format === "json";
- const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
+ const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick };
// Resolution with ambiguity detection
const { target, ambiguous } = await resolveWithAmbiguity(client, symbol, resolveOpts, opts.format);
diff --git a/ix-cli/src/cli/commands/overview.ts b/ix-cli/src/cli/commands/overview.ts
index 39d22861..5de53891 100644
--- a/ix-cli/src/cli/commands/overview.ts
+++ b/ix-cli/src/cli/commands/overview.ts
@@ -6,6 +6,7 @@ import { getEffectiveSystemPath, getSystemPath, hasMapData } from "../hierarchy.
import { humanizeLabel } from "../impact/risk-semantics.js";
import { relativePath } from "../format.js";
import { llmLine, llmError, type LlmValue } from "../llm.js";
+import { parsePickOption } from "../options.js";
import { renderSection, renderKeyValue, renderNote, renderBreadcrumb } from "../ui.js";
const CONTAINER_KINDS = new Set(["class", "module", "file", "trait", "object", "interface"]);
@@ -37,7 +38,7 @@ export function registerOverviewCommand(program: Command): void {
.description("Structural summary — what a target contains or what surrounds it")
.option("--kind <kind>", "Filter target entity by kind")
.option("--path <path>", "Prefer symbols from files matching this path substring")
- .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")
+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)
.option("--format <fmt>", "Output format (text|json|llm)", "text")
.addHelpText(
"after",
@@ -52,9 +53,9 @@ Examples:
ix overview overview.ts
ix overview scoreCandidate --pick 2`
)
- .action(async (symbol: string, opts: { kind?: string; path?: string; pick?: string; format: string }) => {
+ .action(async (symbol: string, opts: { kind?: string; path?: string; pick?: number; format: string }) => {
const client = new IxClient(getEndpoint());
- const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
+ const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick };
const target = await resolveFileOrEntity(client, symbol, resolveOpts);
if (!target) {
// Resolver printed human guidance to stderr; add a structured record for llm.
diff --git a/ix-cli/src/cli/commands/read.ts b/ix-cli/src/cli/commands/read.ts
index 1e024576..bb907e58 100644
--- a/ix-cli/src/cli/commands/read.ts
+++ b/ix-cli/src/cli/commands/read.ts
@@ -9,6 +9,7 @@ import { stderr } from "../stderr.js";
import { isFileStale } from "../stale.js";
import { relativePath } from "../format.js";
import { llmLine, printLlmLines } from "../llm.js";
+import { parsePickOption } from "../options.js";
/** Common file extensions that signal the target is file-like, not a symbol name. */
const FILE_EXTENSIONS = new Set([
@@ -193,7 +194,7 @@ export function registerReadCommand(program: Command): void {
.option("--format <fmt>", "Output format (text|json|llm)", "text")
.option("--kind <kind>", "Filter symbol by kind")
.option("--path <path>", "Prefer symbols from files matching this path substring")
- .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")
+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)
.option("--root <dir>", "Workspace root directory")
.addHelpText("after", `\nResolution order:
1. Exact file path ix read src/main.ts
@@ -209,7 +210,7 @@ Examples:
ix read IngestionService
ix read ingestFile --kind method
ix read verify_token --path auth`)
- .action(async (target: string, opts: { format: string; kind?: string; path?: string; pick?: string; root?: string }) => {
+ .action(async (target: string, opts: { format: string; kind?: string; path?: string; pick?: number; root?: string }) => {
const root = resolveWorkspaceRoot(opts.root);
const client = new IxClient(getEndpoint());
@@ -274,7 +275,7 @@ Examples:
}
// --- Step 4: Try unique symbol match ---
- const symbolResult = await trySymbolMatch(client, rawTarget, { kind: opts.kind, path: opts.path, pick: opts.pick ? parseInt(opts.pick, 10) : undefined });
+ const symbolResult = await trySymbolMatch(client, rawTarget, { kind: opts.kind, path: opts.path, pick: opts.pick });
if (symbolResult.type === "resolved") {
const { node, sourceUri } = symbolResult;
// sourceUri coming from the graph is workspace-relative under the
diff --git a/ix-cli/src/cli/commands/subsystems.ts b/ix-cli/src/cli/commands/subsystems.ts
index 0e95ccdf..fa79ac75 100644
--- a/ix-cli/src/cli/commands/subsystems.ts
+++ b/ix-cli/src/cli/commands/subsystems.ts
@@ -6,6 +6,7 @@ import { resolveWorkspaceId } from "../bootstrap.js";
import { resolveReadSystemId } from "../resolve.js";
import { roundFloat } from "../format.js";
import { llmLine, llmError } from "../llm.js";
+import { parsePickOption } from "../options.js";
import { renderMapText, renderMapLlm, type MapRegion, type MapResult } from "./map.js";
import {
renderSubsystemExplanationJson,
@@ -58,7 +59,7 @@ export function registerSubsystemsCommand(program: Command): void {
.option("--edge-cap <n>", "Max edges per direction per region in detailed mode")
.option("--member-file-cap <n>", "Max member files per region in detailed mode")
.option("--target <target>", "Scope subsystem output to a persisted architecture region")
- .option("--pick <n>", "Resolve an ambiguous region target by numbered candidate")
+ .option("--pick <n>", "Resolve an ambiguous region target by numbered candidate", parsePickOption)
.option("--level <n>", "Filter to level (1=module, 2=subsystem, 3=system)")
.option("--min-confidence <n>", "Only show regions above this confidence threshold (0-1)", "0")
.option("--max-items <n>", "Max items to show per section in text output (default: 10)", "10")
@@ -96,7 +97,7 @@ Examples:
edgeCap?: string;
memberFileCap?: string;
target?: string;
- pick?: string;
+ pick?: number;
level?: string;
minConfidence: string;
maxItems: string;
@@ -112,13 +113,7 @@ Examples:
const systemId = await resolveReadSystemId(client);
const scope = { workspaceId: systemId ? undefined : resolveWorkspaceId(), systemId };
const target = resolveSubsystemTarget(positionalTarget, opts.target);
- const pick = parsePickOption(opts.pick);
-
- if (!target.error && pick.error) {
- console.error(chalk.red("Error:"), pick.error);
- process.exitCode = 1;
- return;
- }
+ const pick = { value: opts.pick };
if (target.error) {
console.error(chalk.red("Error:"), target.error);
process.exitCode = 1;
@@ -458,15 +453,6 @@ function resolveSubsystemTarget(
return value ? { value } : {};
}
-function parsePickOption(rawPick: string | undefined): { value?: number; error?: string } {
- if (rawPick === undefined) return {};
- const value = Number.parseInt(rawPick, 10);
- if (!Number.isFinite(value) || value <= 0) {
- return { error: "Invalid --pick value." };
- }
- return { value };
-}
-
function parseOptionalIntOption(name: string, raw: string | undefined): { value?: number; error?: string } {
if (raw === undefined) return {};
const value = Number.parseInt(raw, 10);
diff --git a/ix-cli/src/cli/commands/trace.ts b/ix-cli/src/cli/commands/trace.ts
index 29e13da4..9a4c1026 100644
--- a/ix-cli/src/cli/commands/trace.ts
+++ b/ix-cli/src/cli/commands/trace.ts
@@ -4,10 +4,10 @@ import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
import { resolveFileOrEntity, isRawId, activeReadScope, ensureReadScope } from "../resolve.js";
import type { ResolvedEntity } from "../resolve.js";
-import { stderr } from "../stderr.js";
import { renderSection, renderKeyValue, renderResolvedHeader, colorizeKind } from "../ui.js";
import { compactTreeNode, relativePath } from "../format.js";
import { llmLine, llmError, type LlmValue } from "../llm.js";
+import { parsePickOption } from "../options.js";
// ── Types ────────────────────────────────────────────────────────────
@@ -408,7 +408,7 @@ export function registerTraceCommand(program: Command): void {
.option("--kind <kind>", "Relationship kind: calls|imports|depends|contains")
.option("--depth <n>", "Cap traversal depth")
.option("--cap <n>", "Cap number of nodes visited, per direction")
- .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")
+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)", parsePickOption)
.option("--path <path>", "Prefer symbols from files matching this path substring")
.option("--format <fmt>", "Output format (text|json|llm)", "text")
.option("--include-tests", "Include test and fixture entities")
@@ -433,7 +433,7 @@ export function registerTraceCommand(program: Command): void {
kind?: string;
depth?: string;
cap?: string;
- pick?: string;
+ pick?: number;
path?: string;
format: string;
includeTests?: boolean;
@@ -442,18 +442,9 @@ export function registerTraceCommand(program: Command): void {
) => {
const client = new IxClient(getEndpoint());
- // Validate --pick
- if (opts.pick !== undefined) {
- const pickVal = parseInt(opts.pick, 10);
- if (isNaN(pickVal) || pickVal < 1) {
- stderr("Invalid value for --pick: must be a positive integer.");
- return;
- }
- }
-
const resolveOpts = {
path: opts.path,
- pick: opts.pick ? parseInt(opts.pick, 10) : undefined,
+ pick: opts.pick,
includeTests: opts.includeTests,
testsOnly: opts.testsOnly,
};
@@ -566,7 +557,7 @@ export function registerTraceCommand(program: Command): void {
target = await pickTraceTarget(client, symbol, target, {
direction,
predicates,
- pick: opts.pick ? parseInt(opts.pick, 10) : undefined,
+ pick: opts.pick,
path: opts.path,
});
diff --git a/ix-cli/src/cli/options.ts b/ix-cli/src/cli/options.ts
new file mode 100644
index 00000000..32732b4d
--- /dev/null
+++ b/ix-cli/src/cli/options.ts
@@ -0,0 +1,14 @@
+import { InvalidArgumentError } from "commander";
+
+export function parsePickOption(value: string): number {
+ const normalized = value.trim();
+ if (!/^\+?[1-9]\d*$/.test(normalized)) {
+ throw new InvalidArgumentError("must be a positive integer (for example, 1 or 2)");
+ }
+
+ const parsed = Number(normalized);
+ if (!Number.isSafeInteger(parsed)) {
+ throw new InvalidArgumentError("must be a positive integer (for example, 1 or 2)");
+ }
+ return parsed;
+}