Skip to content

armgit / Ix

Public Imported from GitHub
0

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

feat: name-based resolution, duplicate prevention, read-after-write, goal show

Tanner Kocher51781ea5d069
diff --git a/ix-cli/src/cli/__tests__/file-resolution.test.ts b/ix-cli/src/cli/__tests__/file-resolution.test.ts
new file mode 100644
index 00000000..6b06d431
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/file-resolution.test.ts
@@ -0,0 +1,146 @@
+import { describe, it, expect } from "vitest";
+import * as fs from "node:fs";
+import * as path from "node:path";
+
+/**
+ * Verify that the shared file-first resolution helper exists
+ * and that all graph navigation commands use it consistently.
+ */
+
+const resolveTsPath = path.resolve(__dirname, "../resolve.ts");
+const resolveContent = fs.readFileSync(resolveTsPath, "utf-8");
+
+const historyTsPath = path.resolve(__dirname, "../commands/history.ts");
+const historyContent = fs.readFileSync(historyTsPath, "utf-8");
+
+const diffTsPath = path.resolve(__dirname, "../commands/diff.ts");
+const diffContent = fs.readFileSync(diffTsPath, "utf-8");
+
+/** Commands that should all use resolveFileOrEntity for consistent file-path support. */
+const COMMANDS_USING_FILE_RESOLUTION = [
+ "overview", "callers", "contains", "imports", "depends", "locate", "impact", "explain",
+];
+
+const commandContents: Record<string, string> = {};
+for (const cmd of COMMANDS_USING_FILE_RESOLUTION) {
+ const cmdPath = path.resolve(__dirname, `../commands/${cmd}.ts`);
+ commandContents[cmd] = fs.readFileSync(cmdPath, "utf-8");
+}
+
+describe("file-first resolution helper", () => {
+ it("resolve.ts exports looksFileLike", () => {
+ expect(resolveContent).toContain("export function looksFileLike");
+ });
+
+ it("resolve.ts exports resolveFileOrEntity", () => {
+ expect(resolveContent).toContain("export async function resolveFileOrEntity");
+ });
+
+ it("resolveFileOrEntity tries file graph match before symbol resolution", () => {
+ // The function should check looksFileLike first, then fall through to resolveEntity
+ expect(resolveContent).toContain("looksFileLike(target)");
+ expect(resolveContent).toContain("tryFileGraphMatch(client, target)");
+ expect(resolveContent).toContain("resolveEntity(client, target,");
+ });
+
+ it("tryFileGraphMatch scores exact path matches higher than basename matches", () => {
+ expect(resolveContent).toContain("quality: 0"); // exact path
+ expect(resolveContent).toContain("quality: 1"); // exact filename
+ expect(resolveContent).toContain("quality: 2"); // bare name
+ });
+});
+
+describe("history command uses file-first resolution", () => {
+ it("imports resolveFileOrEntity", () => {
+ expect(historyContent).toContain("resolveFileOrEntity");
+ });
+
+ it("accepts a target argument, not entityId", () => {
+ expect(historyContent).toContain('command("history <target>")');
+ });
+
+ it("supports --kind option", () => {
+ expect(historyContent).toContain("--kind");
+ });
+});
+
+describe("diff command supports scoped target", () => {
+ it("accepts optional third positional argument", () => {
+ expect(diffContent).toContain('command("diff <fromRev> <toRev> [target]")');
+ });
+
+ it("uses resolveFileOrEntity for target resolution", () => {
+ expect(diffContent).toContain("resolveFileOrEntity");
+ });
+
+ it("passes resolved entity ID to diff API", () => {
+ expect(diffContent).toContain("entityId");
+ });
+
+ it("supports --content flag for detailed attribute diffs", () => {
+ expect(diffContent).toContain('"--content"');
+ expect(diffContent).toContain("formatDiffContent");
+ });
+
+ it("--content reads source from disk using line spans", () => {
+ expect(diffContent).toContain("readSourceSpan");
+ expect(diffContent).toContain("line_start");
+ expect(diffContent).toContain("line_end");
+ expect(diffContent).toContain("fs.readFileSync");
+ });
+
+ it("--content augments JSON output with sourceContent", () => {
+ expect(diffContent).toContain("sourceContent");
+ });
+});
+
+describe("all graph commands use resolveFileOrEntity consistently", () => {
+ for (const cmd of COMMANDS_USING_FILE_RESOLUTION) {
+ it(`${cmd} imports resolveFileOrEntity`, () => {
+ expect(commandContents[cmd]).toContain("resolveFileOrEntity");
+ });
+ }
+});
+
+describe("--pick support", () => {
+ it("resolve.ts exports applyPick", () => {
+ expect(resolveContent).toContain("export function applyPick");
+ });
+
+ it("resolve.ts printAmbiguous outputs numbered candidates", () => {
+ expect(resolveContent).toContain("${i + 1}.");
+ });
+
+ it("overview.ts declares --path option", () => {
+ expect(commandContents["overview"]).toContain('"--path');
+ });
+
+ it("overview.ts declares --pick option", () => {
+ expect(commandContents["overview"]).toContain('"--pick');
+ });
+
+ const PICK_COMMANDS = ["overview", "callers", "contains", "imports", "depends", "locate", "impact", "explain"];
+ for (const cmd of PICK_COMMANDS) {
+ it(`${cmd} declares --pick option`, () => {
+ expect(commandContents[cmd]).toContain("--pick");
+ });
+ }
+});
+
+describe("ambiguous result structure", () => {
+ it("resolve.ts AmbiguousResult includes rank field", () => {
+ expect(resolveContent).toContain("rank?:");
+ });
+
+ it("resolve.ts AmbiguousResult includes diagnostics field", () => {
+ expect(resolveContent).toContain("diagnostics?:");
+ });
+
+ it("buildAmbiguous sets rank on candidates", () => {
+ expect(resolveContent).toContain("rank,");
+ });
+
+ it("buildAmbiguous sets diagnostics with ambiguous_resolution code", () => {
+ expect(resolveContent).toContain("ambiguous_resolution");
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/help-coverage.test.ts b/ix-cli/src/cli/__tests__/help-coverage.test.ts
index 61e44362..41ab6c60 100644
--- a/ix-cli/src/cli/__tests__/help-coverage.test.ts
+++ b/ix-cli/src/cli/__tests__/help-coverage.test.ts
@@ -18,7 +18,7 @@ const REQUIRED_COMMANDS = [
"read", "search", "locate", "contains", "callers", "callees",
"imports", "entity", "status", "stats", "doctor", "history", "diff",
"briefing", "overview", "impact", "rank", "inventory",
- "plan", "task", "tasks", "bug", "bugs", "decide", "goal",
+ "plan", "task", "tasks", "workflow", "bug", "bugs", "decide", "goal", "goals",
"ingest", "truth", "text", "explain",
];
diff --git a/ix-cli/src/cli/__tests__/name-resolution.test.ts b/ix-cli/src/cli/__tests__/name-resolution.test.ts
new file mode 100644
index 00000000..c5dfc979
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/name-resolution.test.ts
@@ -0,0 +1,162 @@
+import { describe, it, expect } from "vitest";
+import * as fs from "node:fs";
+import * as path from "node:path";
+
+/**
+ * Verify name-based resolution, duplicate prevention, read-after-write,
+ * and new subcommands (goal show, plan show).
+ */
+
+const planTsPath = path.resolve(__dirname, "../commands/plan.ts");
+const planContent = fs.readFileSync(planTsPath, "utf-8");
+
+const goalTsPath = path.resolve(__dirname, "../commands/goal.ts");
+const goalContent = fs.readFileSync(goalTsPath, "utf-8");
+
+const workflowTsPath = path.resolve(__dirname, "../commands/workflow.ts");
+const workflowContent = fs.readFileSync(workflowTsPath, "utf-8");
+
+const mainTsPath = path.resolve(__dirname, "../main.ts");
+const mainContent = fs.readFileSync(mainTsPath, "utf-8");
+
+// ── Name-based resolution for --goal and --plan ──────────────────────
+
+describe("plan create --goal accepts name", () => {
+ it("plan create resolves --goal via resolvePrefix then listTruth", () => {
+ expect(planContent).toContain("client.resolvePrefix(opts.goal)");
+ expect(planContent).toContain("client.listTruth()");
+ });
+
+ it("plan create --goal option says id-or-name", () => {
+ expect(planContent).toContain("--goal <id-or-name>");
+ });
+
+ it("plan create checks duplicate plan name before creating", () => {
+ expect(planContent).toContain('kind: "plan", nameOnly: true');
+ expect(planContent).toContain("already exists");
+ });
+
+ it("plan create falls back to goal name search when prefix fails", () => {
+ // Should search listTruth and find by name
+ expect(planContent).toContain("opts.goal.toLowerCase()");
+ });
+});
+
+describe("plan task --plan accepts name", () => {
+ it("plan task resolves --plan via resolvePrefix then resolveEntity", () => {
+ expect(planContent).toContain("client.resolvePrefix(opts.plan)");
+ expect(planContent).toContain('resolveEntity(client, opts.plan, ["plan"]');
+ });
+
+ it("plan task --plan option says id-or-name", () => {
+ expect(planContent).toContain("--plan <id-or-name>");
+ });
+
+ it("plan task checks duplicate task name within plan", () => {
+ expect(planContent).toContain("PLAN_HAS_TASK");
+ expect(planContent).toContain("already exists in this plan");
+ });
+});
+
+// ── Plan show alias ──────────────────────────────────────────────────
+
+describe("plan show alias", () => {
+ it("plan status has show alias", () => {
+ expect(planContent).toContain('.alias("show")');
+ });
+
+ it("help text mentions show alias", () => {
+ expect(planContent).toContain("alias: show");
+ });
+});
+
+// ── Goal show command ────────────────────────────────────────────────
+
+describe("goal show command", () => {
+ it("goal.ts registers show subcommand", () => {
+ expect(goalContent).toContain('command("show <ref>")');
+ });
+
+ it("goal show resolves by name via listTruth", () => {
+ expect(goalContent).toContain("client.resolvePrefix(ref)");
+ expect(goalContent).toContain("client.listTruth()");
+ });
+
+ it("goal show fetches entity details", () => {
+ expect(goalContent).toContain("client.entity(goalId)");
+ });
+
+ it("goal show expands GOAL_HAS_PLAN for linked plans", () => {
+ expect(goalContent).toContain("GOAL_HAS_PLAN");
+ });
+
+ it("goal show supports --format json", () => {
+ expect(goalContent).toContain("--format");
+ });
+
+ it("goal help text mentions show subcommand", () => {
+ expect(goalContent).toContain("show <ref>");
+ });
+});
+
+// ── Goal create duplicate prevention ─────────────────────────────────
+
+describe("goal create duplicate prevention", () => {
+ it("goal create checks for existing goal with same name", () => {
+ expect(goalContent).toContain("client.listTruth()");
+ expect(goalContent).toContain("statement.toLowerCase()");
+ });
+
+ it("goal create rejects duplicate with error message", () => {
+ expect(goalContent).toContain("already exists");
+ });
+
+ it("goal help text mentions duplicate rejection", () => {
+ expect(goalContent).toContain("rejects duplicate");
+ });
+});
+
+// ── Workflow attach read-after-write ─────────────────────────────────
+
+describe("workflow attach read-after-write", () => {
+ it("workflow attach re-fetches entity after commitPatch", () => {
+ // After commitPatch, should call client.entity to verify
+ expect(workflowContent).toContain("client.entity(resolvedId)");
+ });
+
+ it("workflow attach calls extractWorkflow on verified entity", () => {
+ expect(workflowContent).toContain("extractWorkflow(verified.node, verified.claims)");
+ });
+
+ it("workflow attach fails if verified workflow is null", () => {
+ expect(workflowContent).toContain("no workflow claim");
+ });
+
+ it("workflow attach JSON output includes verified flag", () => {
+ expect(workflowContent).toContain("verified: true");
+ });
+
+ it("workflow attach text output confirms read-after-write", () => {
+ expect(workflowContent).toContain("Read-after-write verified");
+ });
+});
+
+// ── Help text updates ────────────────────────────────────────────────
+
+describe("help text updates", () => {
+ it("plan help mentions id-or-name for --goal", () => {
+ expect(planContent).toContain("goal-id-or-name");
+ });
+
+ it("plan help mentions id-or-name for --plan", () => {
+ expect(planContent).toContain("plan-id-or-name");
+ });
+
+ it("plan help mentions plan show in examples", () => {
+ expect(planContent).toContain("ix plan show");
+ });
+
+ it("goal help mentions goal show in examples", () => {
+ expect(goalContent).toContain("ix goal show");
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/pick-resolution.test.ts b/ix-cli/src/cli/__tests__/pick-resolution.test.ts
new file mode 100644
index 00000000..9aaaeee4
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/pick-resolution.test.ts
@@ -0,0 +1,97 @@
+import { describe, it, expect } from "vitest";
+import { applyPick, type ResolveResult, type AmbiguousResult } from "../resolve.js";
+
+function makeAmbiguousResult(count: number): ResolveResult & { resolved: false; ambiguous: true } {
+ const candidates: AmbiguousResult["candidates"] = [];
+ for (let i = 0; i < count; i++) {
+ candidates.push({
+ id: `id-${i}`,
+ name: `name-${i}`,
+ kind: "function",
+ path: `/src/file-${i}.ts`,
+ score: i * 10,
+ rank: i + 1,
+ });
+ }
+ return {
+ resolved: false,
+ ambiguous: true,
+ result: {
+ resolutionMode: "ambiguous",
+ candidates,
+ diagnostics: [{ code: "ambiguous_resolution", message: "Use --pick <n> or --path to disambiguate." }],
+ },
+ };
+}
+
+describe("applyPick", () => {
+ it("returns null when pick is not set", () => {
+ const result = makeAmbiguousResult(3);
+ expect(applyPick(result, {})).toBeNull();
+ expect(applyPick(result, undefined)).toBeNull();
+ });
+
+ it("returns null when result is already resolved", () => {
+ const resolved: ResolveResult = {
+ resolved: true,
+ entity: { id: "id-0", kind: "function", name: "foo", resolutionMode: "exact" },
+ };
+ expect(applyPick(resolved, { pick: 1 })).toBeNull();
+ });
+
+ it("returns resolved entity for valid pick index", () => {
+ const result = makeAmbiguousResult(3);
+ const picked = applyPick(result, { pick: 2 });
+ expect(picked).not.toBeNull();
+ expect(picked!.resolved).toBe(true);
+ if (picked!.resolved) {
+ expect(picked!.entity.id).toBe("id-1");
+ expect(picked!.entity.name).toBe("name-1");
+ expect(picked!.entity.kind).toBe("function");
+ expect(picked!.entity.path).toBe("/src/file-1.ts");
+ }
+ });
+
+ it("returns first candidate for pick=1", () => {
+ const result = makeAmbiguousResult(3);
+ const picked = applyPick(result, { pick: 1 });
+ expect(picked).not.toBeNull();
+ if (picked!.resolved) {
+ expect(picked!.entity.id).toBe("id-0");
+ }
+ });
+
+ it("returns last candidate for pick=N", () => {
+ const result = makeAmbiguousResult(3);
+ const picked = applyPick(result, { pick: 3 });
+ expect(picked).not.toBeNull();
+ if (picked!.resolved) {
+ expect(picked!.entity.id).toBe("id-2");
+ }
+ });
+
+ it("returns not-found for pick=0 (out of range)", () => {
+ const result = makeAmbiguousResult(3);
+ const picked = applyPick(result, { pick: 0 });
+ expect(picked).not.toBeNull();
+ expect(picked!.resolved).toBe(false);
+ if (!picked!.resolved) {
+ expect(picked!.ambiguous).toBe(false);
+ }
+ });
+
+ it("returns not-found for pick > candidates.length", () => {
+ const result = makeAmbiguousResult(3);
+ const picked = applyPick(result, { pick: 10 });
+ expect(picked).not.toBeNull();
+ expect(picked!.resolved).toBe(false);
+ if (!picked!.resolved) {
+ expect(picked!.ambiguous).toBe(false);
+ }
+ });
+
+ it("returns null for non-ambiguous not-found result", () => {
+ const result: ResolveResult = { resolved: false, ambiguous: false };
+ expect(applyPick(result, { pick: 1 })).toBeNull();
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/workflow-attach.test.ts b/ix-cli/src/cli/__tests__/workflow-attach.test.ts
new file mode 100644
index 00000000..5efec3c3
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/workflow-attach.test.ts
@@ -0,0 +1,197 @@
+import { describe, it, expect } from "vitest";
+import * as fs from "node:fs";
+import * as path from "node:path";
+import { buildWorkflowAttachPatch, extractWorkflow } from "../commands/workflow.js";
+import { isValidWorkflow, normalizeWorkflow } from "../commands/plan.js";
+
+const workflowTsPath = path.resolve(__dirname, "../commands/workflow.ts");
+const workflowContent = fs.readFileSync(workflowTsPath, "utf-8");
+
+const goalTsPath = path.resolve(__dirname, "../commands/goal.ts");
+const goalContent = fs.readFileSync(goalTsPath, "utf-8");
+
+const mainTsPath = path.resolve(__dirname, "../main.ts");
+const mainContent = fs.readFileSync(mainTsPath, "utf-8");
+
+const goalsTsPath = path.resolve(__dirname, "../commands/goals.ts");
+const goalsContent = fs.readFileSync(goalsTsPath, "utf-8");
+
+const workflowsHelpPath = path.resolve(__dirname, "../commands/workflows.ts");
+const workflowsHelpContent = fs.readFileSync(workflowsHelpPath, "utf-8");
+
+describe("buildWorkflowAttachPatch", () => {
+ it("creates an AssertClaim for workflow field", () => {
+ const workflow = { discover: ["ix overview Auth"], implement: ["ix read Auth"] };
+ const patch = buildWorkflowAttachPatch("entity-123", workflow);
+ expect(patch.ops.length).toBe(1);
+ expect(patch.ops[0].type).toBe("AssertClaim");
+ expect(patch.ops[0].field).toBe("workflow");
+ expect(patch.ops[0].value).toEqual(workflow);
+ expect(patch.ops[0].confidence).toBe(1.0);
+ });
+
+ it("uses sourceType cli", () => {
+ const patch = buildWorkflowAttachPatch("entity-123", ["ix overview X"]);
+ expect(patch.source.sourceType).toBe("cli");
+ });
+
+ it("works with flat array workflow", () => {
+ const workflow = ["ix overview Auth", "ix read Auth"];
+ const patch = buildWorkflowAttachPatch("entity-123", workflow);
+ expect(patch.ops[0].value).toEqual(workflow);
+ });
+
+ it("works with staged workflow", () => {
+ const workflow = { discover: ["ix overview X"], validate: ["ix callers X"] };
+ const patch = buildWorkflowAttachPatch("entity-123", workflow);
+ expect(patch.ops[0].value).toEqual(workflow);
+ });
+});
+
+describe("workflow attach subcommand registration", () => {
+ it("workflow.ts registers attach subcommand", () => {
+ expect(workflowContent).toContain('command("attach <type> <id>")');
+ });
+
+ it("workflow.ts attach requires --file option", () => {
+ expect(workflowContent).toContain("--file");
+ });
+
+ it("workflow.ts attach validates workflow before attaching", () => {
+ expect(workflowContent).toContain("isValidWorkflow");
+ });
+
+ it("workflow.ts attach calls commitPatch", () => {
+ expect(workflowContent).toContain("commitPatch");
+ });
+
+ it("workflow.ts help text mentions attach", () => {
+ expect(workflowContent).toContain("attach <type> <id>");
+ });
+});
+
+describe("ix goals alias", () => {
+ it("goals.ts exists and exports registerGoalsCommand", () => {
+ expect(goalsContent).toContain("export function registerGoalsCommand");
+ });
+
+ it("goals.ts registers 'goals' command", () => {
+ expect(goalsContent).toContain('command("goals")');
+ });
+
+ it("goals.ts supports --status filter", () => {
+ expect(goalsContent).toContain("--status");
+ });
+
+ it("goals.ts supports --format option", () => {
+ expect(goalsContent).toContain("--format");
+ });
+
+ it("main.ts imports and registers goals command", () => {
+ expect(mainContent).toContain("registerGoalsCommand");
+ });
+});
+
+describe("help discoverability", () => {
+ it("main.ts HELP_HEADER includes goals", () => {
+ const headerMatch = mainContent.match(/const HELP_HEADER = `([\s\S]*?)`;/);
+ const header = headerMatch?.[1] ?? "";
+ expect(header).toContain("goals");
+ });
+
+ it("main.ts HELP_HEADER workflow description mentions attach", () => {
+ const headerMatch = mainContent.match(/const HELP_HEADER = `([\s\S]*?)`;/);
+ const header = headerMatch?.[1] ?? "";
+ expect(header).toContain("Attach");
+ });
+
+ it("workflows help mentions workflow attach", () => {
+ expect(workflowsHelpContent).toContain("workflow attach");
+ });
+
+ it("goal help text mentions ix goals shorthand", () => {
+ expect(goalContent).toContain("ix goals");
+ });
+});
+
+describe("workflow validation with isValidWorkflow", () => {
+ it("accepts staged object with all valid stages", () => {
+ expect(isValidWorkflow({ discover: ["a"], implement: ["b"], validate: ["c"] })).toBe(true);
+ });
+
+ it("accepts staged object with subset of stages", () => {
+ expect(isValidWorkflow({ discover: ["a"] })).toBe(true);
+ });
+
+ it("normalizes flat array to discover stage", () => {
+ const result = normalizeWorkflow(["ix overview X"]);
+ expect(result.discover).toEqual(["ix overview X"]);
+ });
+});
+
+describe("extractWorkflow claims integration", () => {
+ it("returns workflow from node.attrs when no claims", () => {
+ const node = { attrs: { workflow: { discover: ["ix overview X"] } } };
+ const result = extractWorkflow(node);
+ expect(result).toEqual({ discover: ["ix overview X"] });
+ });
+
+ it("returns workflow from claims when present (field key)", () => {
+ const node = { attrs: {} };
+ const claims = [{ field: "workflow", value: { discover: ["ix read Y"] } }];
+ const result = extractWorkflow(node, claims);
+ expect(result).toEqual({ discover: ["ix read Y"] });
+ });
+
+ it("returns workflow from claims when present (statement key)", () => {
+ const node = { attrs: {} };
+ const claims = [{ statement: "workflow", value: { discover: ["ix read Y"] } }];
+ const result = extractWorkflow(node, claims);
+ expect(result).toEqual({ discover: ["ix read Y"] });
+ });
+
+ it("claims take precedence over attrs", () => {
+ const node = { attrs: { workflow: { discover: ["ix overview OLD"] } } };
+ const claims = [{ statement: "workflow", value: { discover: ["ix overview NEW"] } }];
+ const result = extractWorkflow(node, claims);
+ expect(result).toEqual({ discover: ["ix overview NEW"] });
+ });
+
+ it("falls back to attrs when claims have no workflow", () => {
+ const node = { attrs: { workflow: ["ix overview X"] } };
+ const claims = [{ field: "status", value: "done" }];
+ const result = extractWorkflow(node, claims);
+ expect(result).toEqual({ discover: ["ix overview X"] });
+ });
+
+ it("returns null when neither claims nor attrs have workflow", () => {
+ const node = { attrs: {} };
+ const claims: any[] = [];
+ const result = extractWorkflow(node, claims);
+ expect(result).toBeNull();
+ });
+
+ it("normalizes flat array from claims to discover", () => {
+ const node = { attrs: {} };
+ const claims = [{ statement: "workflow", value: ["ix overview Z"] }];
+ const result = extractWorkflow(node, claims);
+ expect(result).toEqual({ discover: ["ix overview Z"] });
+ });
+});
+
+describe("plan.ts workflow retrieval checks claims", () => {
+ const planTsPath = path.resolve(__dirname, "../commands/plan.ts");
+ const planContent = fs.readFileSync(planTsPath, "utf-8");
+
+ it("task show checks claims for workflow", () => {
+ // Should check both field and statement keys for claim matching
+ expect(planContent).toContain('c.field === "workflow" || c.statement === "workflow"');
+ });
+
+ it("plan next checks claims for workflow", () => {
+ // Should have two occurrences of workflow claim checking (task show + plan next)
+ const matches = planContent.match(/c\.field === "workflow" \|\| c\.statement === "workflow"/g);
+ expect(matches).not.toBeNull();
+ expect(matches!.length).toBeGreaterThanOrEqual(2);
+ });
+});
diff --git a/ix-cli/src/cli/commands/callers.ts b/ix-cli/src/cli/commands/callers.ts
index 2b4636a6..c57cc08d 100644
--- a/ix-cli/src/cli/commands/callers.ts
+++ b/ix-cli/src/cli/commands/callers.ts
@@ -5,7 +5,7 @@ import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint, resolveWorkspaceRoot } from "../config.js";
import { formatEdgeResults } from "../format.js";
-import { resolveEntity, printResolved } from "../resolve.js";
+import { resolveFileOrEntity, printResolved } from "../resolve.js";
import { stderr } from "../stderr.js";
const execFileAsync = promisify(execFile);
@@ -15,13 +15,15 @@ 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("--limit <n>", "Max results to show", "50")
.option("--format <fmt>", "Output format (text|json)", "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; limit: string; format: string }) => {
+ .action(async (symbol: string, opts: { kind?: string; pick?: string; limit: string; format: string }) => {
const client = new IxClient(getEndpoint());
const limit = parseInt(opts.limit, 10);
- const target = await resolveEntity(client, symbol, ["method", "function"], opts);
+ const resolveOpts = { kind: opts.kind, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
+ const target = await resolveFileOrEntity(client, symbol, resolveOpts);
if (!target) return;
if (opts.format !== "json") printResolved(target);
// Use expandByName for cross-file resolution
@@ -103,13 +105,15 @@ 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("--limit <n>", "Max results to show", "50")
.option("--format <fmt>", "Output format (text|json)", "text")
.addHelpText("after", "\nExamples:\n ix callees processPayment\n ix callees parse --format json")
- .action(async (symbol: string, opts: { kind?: string; limit: string; format: string }) => {
+ .action(async (symbol: string, opts: { kind?: string; pick?: string; limit: string; format: string }) => {
const client = new IxClient(getEndpoint());
const calleeLimit = parseInt(opts.limit, 10);
- const target = await resolveEntity(client, symbol, ["method", "function"], opts);
+ const resolveOpts = { kind: opts.kind, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
+ const target = await resolveFileOrEntity(client, symbol, resolveOpts);
if (!target) return;
if (opts.format !== "json") printResolved(target);
// Use expandByName for cross-file resolution
diff --git a/ix-cli/src/cli/commands/contains.ts b/ix-cli/src/cli/commands/contains.ts
index 335b4390..8b9ae688 100644
--- a/ix-cli/src/cli/commands/contains.ts
+++ b/ix-cli/src/cli/commands/contains.ts
@@ -2,20 +2,22 @@ import type { Command } from "commander";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
import { formatEdgeResults } from "../format.js";
-import { resolveEntity, printResolved } from "../resolve.js";
+import { resolveFileOrEntity, printResolved } from "../resolve.js";
export function registerContainsCommand(program: Command): void {
program
.command("contains <symbol>")
.description("Show members contained by the given entity (class, module, file)")
.option("--kind <kind>", "Filter target entity by kind")
+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")
.option("--limit <n>", "Max results to show", "50")
.option("--format <fmt>", "Output format (text|json)", "text")
.addHelpText("after", "\nExamples:\n ix contains IngestionService\n ix contains auth.py --kind file --format json\n ix contains MyClass --limit 20")
- .action(async (symbol: string, opts: { kind?: string; limit: string; format: string }) => {
+ .action(async (symbol: string, opts: { kind?: string; pick?: string; limit: string; format: string }) => {
const client = new IxClient(getEndpoint());
const limit = parseInt(opts.limit, 10);
- const target = await resolveEntity(client, symbol, ["class", "object", "trait", "interface", "module", "file"], opts);
+ const resolveOpts = { kind: opts.kind, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
+ const target = await resolveFileOrEntity(client, symbol, resolveOpts);
if (!target) return;
if (opts.format !== "json") printResolved(target);
const result = await client.expand(target.id, { direction: "out", predicates: ["CONTAINS"] });
diff --git a/ix-cli/src/cli/commands/decide.ts b/ix-cli/src/cli/commands/decide.ts
index 39fcf759..b97e1c70 100644
--- a/ix-cli/src/cli/commands/decide.ts
+++ b/ix-cli/src/cli/commands/decide.ts
@@ -11,7 +11,7 @@ interface DecisionLinkOpts {
parent?: string;
respondsTo?: string;
}
-
+// Test comment
export function buildDecisionPatch(
title: string,
rationale: string,
diff --git a/ix-cli/src/cli/commands/depends.ts b/ix-cli/src/cli/commands/depends.ts
index c652bb45..3da38a86 100644
--- a/ix-cli/src/cli/commands/depends.ts
+++ b/ix-cli/src/cli/commands/depends.ts
@@ -2,25 +2,23 @@ import type { Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
-import { resolveEntity, printResolved, isRawId } from "../resolve.js";
+import { resolveFileOrEntity, printResolved, isRawId } from "../resolve.js";
export function registerDependsCommand(program: Command): void {
program
.command("depends <symbol>")
.description("Show what depends on the given entity (reverse CALLS + IMPORTS)")
.option("--kind <kind>", "Filter target entity by kind")
+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")
.option("--depth <n>", "Traversal depth (default 1)", "1")
.option("--limit <n>", "Max results to show", "50")
.option("--format <fmt>", "Output format (text|json)", "text")
.addHelpText("after", "\nExamples:\n ix depends verify_token\n ix depends AuthProvider --depth 2 --format json\n ix depends parser.py --kind file --limit 20")
- .action(async (symbol: string, opts: { kind?: string; depth: string; limit: string; format: string }) => {
+ .action(async (symbol: string, opts: { kind?: string; pick?: string; depth: string; limit: string; format: string }) => {
const client = new IxClient(getEndpoint());
const limit = parseInt(opts.limit, 10);
- const target = await resolveEntity(
- client, symbol,
- ["method", "function", "class", "object", "trait", "interface", "module", "file"],
- opts
- );
+ const resolveOpts = { kind: opts.kind, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
+ const target = await resolveFileOrEntity(client, symbol, resolveOpts);
if (!target) return;
const hops = parseInt(opts.depth, 10) || 1;
diff --git a/ix-cli/src/cli/commands/diff.ts b/ix-cli/src/cli/commands/diff.ts
index 40e342e0..6621f967 100644
--- a/ix-cli/src/cli/commands/diff.ts
+++ b/ix-cli/src/cli/commands/diff.ts
@@ -1,27 +1,49 @@
+import * as fs from "node:fs";
+import * as path from "node:path";
import type { Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
+import { resolveFileOrEntity } from "../resolve.js";
import { formatDiff } from "../format.js";
+import { stderr } from "../stderr.js";
export function registerDiffCommand(program: Command): void {
program
- .command("diff <fromRev> <toRev>")
- .description("Show diff between two revisions")
- .option("--entity <id>", "Filter by entity ID")
+ .command("diff <fromRev> <toRev> [target]")
+ .description("Show diff between two revisions, optionally scoped to a file or entity")
+ .option("--entity <id>", "Filter by entity ID (deprecated, use positional target)")
.option("--summary", "Show compact summary only (server-side, fast)")
+ .option("--content", "Show detailed attribute changes for each entity")
.option("--limit <n>", "Max changes to return (default 100)")
.option("--full", "Return all changes (no limit)")
.option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (fromRev: string, toRev: string, opts: {
- entity?: string; summary?: boolean; limit?: string; full?: boolean; format: string;
+ .addHelpText("after", `\nExamples:
+ ix diff 3 5
+ ix diff 3 5 ix-cli/src/cli/commands/decide.ts
+ ix diff 3 5 decide.ts --content
+ ix diff 3 5 buildDecisionPatch
+ 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;
}) => {
const client = new IxClient(getEndpoint());
const from = parseInt(fromRev, 10);
const to = parseInt(toRev, 10);
+ // Resolve the scope entity from positional target or --entity flag
+ let entityId: string | undefined = opts.entity;
+ if (target && !entityId) {
+ const resolved = await resolveFileOrEntity(client, target);
+ if (!resolved) return;
+ entityId = resolved.id;
+ if (opts.format !== "json") {
+ stderr(`${chalk.dim("Scoped to:")} ${chalk.cyan(resolved.kind)} ${chalk.bold(resolved.name)}\n`);
+ }
+ }
+
if (opts.summary) {
- const result: any = await client.diff(from, to, { summary: true });
+ const result: any = await client.diff(from, to, { summary: true, entityId });
if (opts.format === "json") {
console.log(JSON.stringify(result, null, 2));
@@ -39,13 +61,21 @@ export function registerDiffCommand(program: Command): void {
}
const limit = opts.full ? undefined : (opts.limit ? parseInt(opts.limit, 10) : undefined);
- const result: any = await client.diff(from, to, {
- entityId: opts.entity,
- limit,
- });
+ const result: any = await client.diff(from, to, { entityId, limit });
if (opts.format === "json") {
+ if (opts.content) {
+ // Augment each change with source content when available
+ const changes = (result as any).changes ?? [];
+ for (const c of changes) {
+ const node = c.atToRev ?? c.atFromRev;
+ const source = readSourceSpan(node);
+ if (source) c.sourceContent = source;
+ }
+ }
console.log(JSON.stringify(result, null, 2));
+ } else if (opts.content) {
+ formatDiffContent(result);
} else {
if (result.truncated) {
console.log(chalk.yellow(`Showing ${result.changes.length} of ${result.totalChanges} changes. Use --full to see all.\n`));
@@ -54,3 +84,99 @@ export function registerDiffCommand(program: Command): void {
}
});
}
+
+/** Try to read source lines from disk using entity provenance and line spans. */
+function readSourceSpan(node: any): string | null {
+ if (!node) return null;
+ const uri: string = node.provenance?.source_uri ?? node.provenance?.sourceUri ?? "";
+ if (!uri) return null;
+
+ const attrs = node.attrs ?? {};
+ const lineStart = attrs.line_start ?? attrs.lineStart;
+ const lineEnd = attrs.line_end ?? attrs.lineEnd;
+ if (lineStart == null || lineEnd == null) return null;
+
+ // Resolve path relative to cwd
+ const filePath = path.resolve(uri);
+ try {
+ if (!fs.existsSync(filePath)) return null;
+ const content = fs.readFileSync(filePath, "utf-8");
+ const lines = content.split("\n");
+ const start = Math.max(0, Number(lineStart) - 1);
+ const end = Math.min(lines.length, Number(lineEnd));
+ if (start >= end) return null;
+ return lines.slice(start, end).join("\n");
+ } catch {
+ return null;
+ }
+}
+
+/** Render detailed attribute-level changes with source code for each entity. */
+function formatDiffContent(result: any): void {
+ console.log(chalk.cyan.bold(`\nDiff: rev ${result.fromRev} → ${result.toRev}`));
+ const changes = result.changes ?? [];
+ if (changes.length === 0) {
+ console.log(chalk.dim(" No changes in this range."));
+ return;
+ }
+
+ for (const c of changes) {
+ const before = c.atFromRev;
+ const after = c.atToRev;
+ const name = after?.name ?? before?.name ?? c.entityId?.substring(0, 8) ?? "?";
+ const kind = after?.kind ?? before?.kind ?? "unknown";
+ const typeChar = c.changeType === "added" ? "+" : c.changeType === "removed" ? "-" : "~";
+ const typeColor = c.changeType === "added" ? chalk.green : c.changeType === "removed" ? chalk.red : chalk.yellow;
+
+ console.log(`\n${typeColor(typeChar)} ${chalk.cyan(kind)} ${chalk.bold(name)}`);
+
+ const activeNode = after ?? before;
+ const uri = activeNode?.provenance?.source_uri ?? activeNode?.provenance?.sourceUri ?? "";
+ if (uri) console.log(` ${chalk.dim("file:")} ${uri}`);
+
+ if (c.changeType === "added" && after) {
+ printAttrs(" ", after.attrs);
+ } else if (c.changeType === "modified" && before && after) {
+ diffAttrs(" ", before.attrs ?? {}, after.attrs ?? {});
+ }
+
+ // Show source code from disk when available
+ const source = readSourceSpan(activeNode);
+ if (source) {
+ const lineStart = (activeNode.attrs?.line_start ?? activeNode.attrs?.lineStart) || "?";
+ console.log(` ${chalk.dim(`source (L${lineStart}):`)} `);
+ for (const line of source.split("\n")) {
+ console.log(` ${chalk.dim("│")} ${line}`);
+ }
+ }
+ }
+ console.log();
+}
+
+function printAttrs(indent: string, attrs: Record<string, unknown> | undefined): void {
+ if (!attrs) return;
+ for (const [key, val] of Object.entries(attrs)) {
+ if (val === null || val === undefined) continue;
+ const display = typeof val === "string" ? val : JSON.stringify(val);
+ console.log(`${indent}${chalk.dim(key + ":")} ${display}`);
+ }
+}
+
+function diffAttrs(indent: string, before: Record<string, unknown>, after: Record<string, unknown>): void {
+ const allKeys = new Set([...Object.keys(before), ...Object.keys(after)]);
+ for (const key of allKeys) {
+ const bVal = before[key];
+ const aVal = after[key];
+ if (bVal === undefined && aVal !== undefined) {
+ const display = typeof aVal === "string" ? aVal : JSON.stringify(aVal);
+ console.log(`${indent}${chalk.green("+")} ${chalk.dim(key + ":")} ${display}`);
+ } else if (bVal !== undefined && aVal === undefined) {
+ const display = typeof bVal === "string" ? bVal : JSON.stringify(bVal);
+ console.log(`${indent}${chalk.red("-")} ${chalk.dim(key + ":")} ${display}`);
+ } else if (JSON.stringify(bVal) !== JSON.stringify(aVal)) {
+ const bDisplay = typeof bVal === "string" ? bVal : JSON.stringify(bVal);
+ const aDisplay = typeof aVal === "string" ? aVal : JSON.stringify(aVal);
+ console.log(`${indent}${chalk.yellow("~")} ${chalk.dim(key + ":")} ${chalk.red(String(bDisplay))} → ${chalk.green(String(aDisplay))}`);
+ }
+ }
+}
diff --git a/ix-cli/src/cli/commands/explain.ts b/ix-cli/src/cli/commands/explain.ts
index 78f5ff6e..c3a658f4 100644
--- a/ix-cli/src/cli/commands/explain.ts
+++ b/ix-cli/src/cli/commands/explain.ts
@@ -2,7 +2,7 @@ import type { Command } from "commander";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
import { formatExplain, type ExplainResult, type EntityRef, type Diagnostic } from "../format.js";
-import { resolveEntity, isRawId } from "../resolve.js";
+import { resolveFileOrEntity, isRawId } from "../resolve.js";
import { isFileStale } from "../stale.js";
import { stderr } from "../stderr.js";
import chalk from "chalk";
@@ -13,11 +13,13 @@ export function registerExplainCommand(program: Command): void {
.description("Explain an entity — shows structure, container, and history")
.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("--format <fmt>", "Output format (text|json)", "text")
.addHelpText("after", "\nExamples:\n ix explain IngestionService\n ix explain expand --path memory-layer\n ix explain verify_token --kind function --format json")
- .action(async (symbol: string, opts: { kind?: string; path?: string; format: string }) => {
+ .action(async (symbol: string, opts: { kind?: string; path?: string; pick?: string; format: string }) => {
const client = new IxClient(getEndpoint());
- const target = await resolveEntity(client, symbol, ["class", "function", "method", "trait", "object", "interface", "module", "file"], opts);
+ const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
+ const target = await resolveFileOrEntity(client, symbol, resolveOpts);
if (!target) return;
const details = await client.entity(target.id);
diff --git a/ix-cli/src/cli/commands/goal.ts b/ix-cli/src/cli/commands/goal.ts
index e2673c8c..94dcac26 100644
--- a/ix-cli/src/cli/commands/goal.ts
+++ b/ix-cli/src/cli/commands/goal.ts
@@ -1,7 +1,9 @@
import type { Command } from "commander";
+import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
import { formatIntents } from "../format.js";
+import { stderr } from "../stderr.js";
export function registerGoalCommand(program: Command): void {
const goal = program
@@ -10,13 +12,18 @@ export function registerGoalCommand(program: Command): void {
.addHelpText(
"after",
`\nSubcommands:
- create <statement> Create a new goal
+ create <statement> Create a new goal (rejects duplicate names)
+ show <ref> Show goal details by ID or name
list List all goals
+Use "ix goals" as a shorthand to list all goals.
+
Examples:
ix goal create "Support GitHub ingestion"
+ ix goal show "Support GitHub ingestion"
ix goal list --format json
- ix goal list --status active --format json`
+ ix goal list --status active --format json
+ ix goals`
);
goal
@@ -26,6 +33,18 @@ Examples:
.option("--format <fmt>", "Output format (text|json)", "text")
.action(async (statement: string, opts: { parent?: string; format: string }) => {
const client = new IxClient(getEndpoint());
+
+ // Check duplicate goal name
+ const existing = await client.listTruth();
+ const dup = existing.find(
+ (i: any) => (i.name || i.statement || "").toLowerCase() === statement.toLowerCase(),
+ );
+ if (dup) {
+ stderr(`A goal named "${statement}" already exists (${(dup as any).id.slice(0, 8)}). Use a unique name.`);
+ process.exitCode = 1;
+ return;
+ }
+
const result = await client.createTruth(statement, opts.parent);
if (opts.format === "json") {
console.log(JSON.stringify(result, null, 2));
@@ -34,6 +53,60 @@ Examples:
}
});
+ goal
+ .command("show <ref>")
+ .description("Show goal details by ID or name")
+ .option("--format <fmt>", "Output format (text|json)", "text")
+ .action(async (ref: string, opts: { format: string }) => {
+ const client = new IxClient(getEndpoint());
+
+ // Resolve goal reference (accepts name or ID)
+ let goalId: string;
+ try {
+ goalId = await client.resolvePrefix(ref);
+ } catch {
+ const intents = await client.listTruth();
+ const match = intents.find(
+ (i: any) => (i.name || i.statement || "").toLowerCase() === ref.toLowerCase(),
+ );
+ if (!match) {
+ stderr(`No goal found matching "${ref}".`);
+ process.exitCode = 1;
+ return;
+ }
+ goalId = (match as any).id;
+ }
+
+ const details = await client.entity(goalId);
+ const node = details.node as any;
+
+ // Get linked plans
+ const { nodes: planNodes } = await client.expand(goalId, {
+ direction: "out",
+ predicates: ["GOAL_HAS_PLAN"],
+ });
+ const plans = planNodes.filter((n: any) => n.kind === "plan");
+
+ if (opts.format === "json") {
+ console.log(JSON.stringify({
+ goalId,
+ name: node.name,
+ plans: plans.map((p: any) => ({ id: p.id, name: p.name })),
+ }, null, 2));
+ } else {
+ console.log(chalk.bold(node.name));
+ console.log(` ID: ${goalId.slice(0, 8)}`);
+ if (plans.length > 0) {
+ console.log(chalk.dim(" Plans:"));
+ for (const p of plans) {
+ console.log(` ${(p as any).name} (${(p as any).id.slice(0, 8)})`);
+ }
+ } else {
+ console.log(chalk.dim(" No plans linked."));
+ }
+ }
+ });
+
goal
.command("list")
.description("List all goals")
diff --git a/ix-cli/src/cli/commands/goals.ts b/ix-cli/src/cli/commands/goals.ts
new file mode 100644
index 00000000..7266b739
--- /dev/null
+++ b/ix-cli/src/cli/commands/goals.ts
@@ -0,0 +1,48 @@
+import type { Command } from "commander";
+import { IxClient } from "../../client/api.js";
+import { getEndpoint } from "../config.js";
+import { formatIntents } from "../format.js";
+
+export function registerGoalsCommand(program: Command): void {
+ program
+ .command("goals")
+ .description("List all goals")
+ .option("--status <status>", "Filter by status (active|all)", "all")
+ .option("--format <fmt>", "Output format (text|json)", "text")
+ .action(async (opts: { status: string; format: string }) => {
+ const client = new IxClient(getEndpoint());
+ let intents = await client.listTruth();
+
+ if (opts.status === "active") {
+ const activeGoalIds = new Set<string>();
+ const goalsToCheck = intents.slice(0, 20);
+
+ for (const intent of goalsToCheck) {
+ try {
+ const { nodes: goalPlans } = await client.expand(intent.id, {
+ direction: "out",
+ predicates: ["GOAL_HAS_PLAN"],
+ });
+ for (const plan of goalPlans) {
+ const { nodes: taskNodes } = await client.expand(plan.id, {
+ direction: "out",
+ predicates: ["PLAN_HAS_TASK"],
+ });
+ const hasPending = taskNodes.some(
+ (t: any) => t.kind === "task" && (t.attrs?.status ?? "pending") === "pending"
+ );
+ if (hasPending) {
+ activeGoalIds.add(intent.id);
+ break;
+ }
+ }
+ } catch {
+ activeGoalIds.add(intent.id);
+ }
+ }
+ intents = intents.filter((i: any) => activeGoalIds.has(i.id));
+ }
+
+ formatIntents(intents, opts.format);
+ });
+}
diff --git a/ix-cli/src/cli/commands/history.ts b/ix-cli/src/cli/commands/history.ts
index 5a2c5961..87dce290 100644
--- a/ix-cli/src/cli/commands/history.ts
+++ b/ix-cli/src/cli/commands/history.ts
@@ -1,20 +1,47 @@
import type { Command } from "commander";
+import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
+import { resolveFileOrEntity, printResolved } from "../resolve.js";
+import { stderr } from "../stderr.js";
export function registerHistoryCommand(program: Command): void {
program
- .command("history <entityId>")
- .description("Show provenance chain for an entity")
+ .command("history <target>")
+ .description("Show provenance chain for a file or entity")
+ .option("--kind <kind>", "Filter target entity by kind")
.option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (entityId: string, opts: { format: string }) => {
+ .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; format: string }) => {
const client = new IxClient(getEndpoint());
- const resolvedId = await client.resolvePrefix(entityId);
- const result = await client.provenance(resolvedId);
+ const resolved = await resolveFileOrEntity(client, target, opts);
+ if (!resolved) return;
+
+ if (opts.format !== "json") printResolved(resolved);
+
+ const result = await client.provenance(resolved.id);
+
if (opts.format === "json") {
- console.log(JSON.stringify(result, null, 2));
+ console.log(JSON.stringify({ resolvedTarget: resolved, provenance: result }, null, 2));
} else {
- console.log(JSON.stringify(result, null, 2));
+ const patches = Array.isArray(result) ? result : (result as any)?.patches ?? [];
+ if (patches.length === 0) {
+ console.log(chalk.dim(" No provenance records found."));
+ return;
+ }
+ for (const p of patches) {
+ const rev = p.rev ?? p.data?.rev ?? "?";
+ const timestamp = p.data?.timestamp ?? p.timestamp ?? "";
+ const intent = p.data?.intent ?? p.intent ?? "";
+ const source = p.data?.source?.uri ?? "";
+ console.log(` ${chalk.cyan(`rev ${rev}`)} ${chalk.dim(timestamp)}`);
+ if (intent) console.log(` ${intent}`);
+ if (source) console.log(` ${chalk.dim(source)}`);
+ }
}
});
}
diff --git a/ix-cli/src/cli/commands/impact.ts b/ix-cli/src/cli/commands/impact.ts
index 4e01eccb..13391498 100644
--- a/ix-cli/src/cli/commands/impact.ts
+++ b/ix-cli/src/cli/commands/impact.ts
@@ -2,7 +2,7 @@ import type { Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
-import { resolveEntity, printResolved } from "../resolve.js";
+import { resolveFileOrEntity, printResolved } from "../resolve.js";
const CONTAINER_KINDS = new Set(["class", "module", "file", "object", "trait", "interface"]);
@@ -11,6 +11,7 @@ export function registerImpactCommand(program: Command): void {
.command("impact <target>")
.description("Aggregated impact analysis — who depends on this symbol and its members")
.option("--kind <kind>", "Filter target entity by kind")
+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")
.option("--depth <n>", "Expansion depth (reserved for future use)", "1")
.option("--limit <n>", "Max top-impacted members to show", "10")
.option("--format <fmt>", "Output format (text|json)", "text")
@@ -21,18 +22,14 @@ export function registerImpactCommand(program: Command): void {
.action(
async (
symbol: string,
- opts: { kind?: string; depth: string; limit: string; format: string }
+ opts: { kind?: string; pick?: string; depth: string; limit: string; format: string }
) => {
const client = new IxClient(getEndpoint());
const limit = parseInt(opts.limit, 10);
const isJson = opts.format === "json";
- const target = await resolveEntity(
- client,
- symbol,
- ["class", "module", "file", "object", "trait", "interface", "method", "function"],
- opts
- );
+ const resolveOpts = { kind: opts.kind, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
+ const target = await resolveFileOrEntity(client, symbol, resolveOpts);
if (!target) return;
if (!isJson) printResolved(target);
diff --git a/ix-cli/src/cli/commands/imports.ts b/ix-cli/src/cli/commands/imports.ts
index 00603b5b..0f3a9884 100644
--- a/ix-cli/src/cli/commands/imports.ts
+++ b/ix-cli/src/cli/commands/imports.ts
@@ -2,20 +2,22 @@ import type { Command } from "commander";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
import { formatEdgeResults } from "../format.js";
-import { resolveEntity, printResolved } from "../resolve.js";
+import { resolveFileOrEntity, printResolved } from "../resolve.js";
export function registerImportsCommand(program: Command): void {
program
.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("--limit <n>", "Max results to show", "50")
.option("--format <fmt>", "Output format (text|json)", "text")
.addHelpText("after", "\nExamples:\n ix imports auth.py\n ix imports IngestionService --format json")
- .action(async (symbol: string, opts: { kind?: string; limit: string; format: string }) => {
+ .action(async (symbol: string, opts: { kind?: string; pick?: string; limit: string; format: string }) => {
const client = new IxClient(getEndpoint());
const limit = parseInt(opts.limit, 10);
- const target = await resolveEntity(client, symbol, ["file", "module", "class"], opts);
+ const resolveOpts = { kind: opts.kind, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
+ const target = await resolveFileOrEntity(client, symbol, resolveOpts);
if (!target) return;
if (opts.format !== "json") printResolved(target);
const result = await client.expand(target.id, { direction: "out", predicates: ["IMPORTS"] });
@@ -26,13 +28,15 @@ 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("--limit <n>", "Max results to show", "50")
.option("--format <fmt>", "Output format (text|json)", "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; limit: string; format: string }) => {
+ .action(async (symbol: string, opts: { kind?: string; pick?: string; limit: string; format: string }) => {
const client = new IxClient(getEndpoint());
const limit = parseInt(opts.limit, 10);
- const target = await resolveEntity(client, symbol, ["file", "module", "class"], opts);
+ const resolveOpts = { kind: opts.kind, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
+ const target = await resolveFileOrEntity(client, symbol, resolveOpts);
if (!target) return;
if (opts.format !== "json") printResolved(target);
const result = await client.expand(target.id, { direction: "in", predicates: ["IMPORTS"] });
diff --git a/ix-cli/src/cli/commands/locate.ts b/ix-cli/src/cli/commands/locate.ts
index 7cae5196..07630623 100644
--- a/ix-cli/src/cli/commands/locate.ts
+++ b/ix-cli/src/cli/commands/locate.ts
@@ -4,7 +4,7 @@ import type { Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint, resolveWorkspaceRoot } from "../config.js";
-import { resolveEntity, printResolved } from "../resolve.js";
+import { resolveFileOrEntity, printResolved } from "../resolve.js";
import { isFileStale } from "../stale.js";
import { stderr } from "../stderr.js";
@@ -47,13 +47,15 @@ export function registerLocateCommand(program: Command): void {
.option("--limit <n>", "Max text hits to check", "10")
.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("--format <fmt>", "Output format (text|json)", "text")
.option("--root <dir>", "Workspace root directory")
.addHelpText("after", `\nExamples:
ix locate IngestionService
ix locate verify_token --kind function
- ix locate ArangoClient --format json`)
- .action(async (symbol: string, opts: { limit: string; kind?: string; path?: string; format: string; root?: string }) => {
+ ix locate ArangoClient --format json
+ ix locate scoreCandidate --pick 2`)
+ .action(async (symbol: string, opts: { limit: string; kind?: string; path?: string; pick?: string; format: string; root?: string }) => {
const client = new IxClient(getEndpoint());
const limit = parseInt(opts.limit, 10);
const root = resolveWorkspaceRoot(opts.root);
@@ -61,8 +63,8 @@ export function registerLocateCommand(program: Command): void {
// --- Step 1: Resolve the target entity ---
// Prefer structural container kinds — locate wants real definitions, not incidental helpers
- const allKinds = ["class", "object", "trait", "interface", "module", "file", "function", "method"];
- const target = await resolveEntity(client, symbol, allKinds, opts);
+ const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
+ const target = await resolveFileOrEntity(client, symbol, resolveOpts);
if (!target) {
// Fall back to text-only search
diff --git a/ix-cli/src/cli/commands/overview.ts b/ix-cli/src/cli/commands/overview.ts
index f19a36cd..5c261686 100644
--- a/ix-cli/src/cli/commands/overview.ts
+++ b/ix-cli/src/cli/commands/overview.ts
@@ -2,7 +2,7 @@ import type { Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
-import { resolveEntity, printResolved } from "../resolve.js";
+import { resolveFileOrEntity, printResolved } from "../resolve.js";
const CONTAINER_KINDS = new Set(["class", "module", "file", "trait", "object", "interface"]);
const CALLABLE_KINDS = new Set(["method", "function"]);
@@ -39,6 +39,8 @@ export function registerOverviewCommand(program: Command): void {
.command("overview <target>")
.description("Structural summary: members, relationships, decisions, and bugs for an 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("--format <fmt>", "Output format (text|json)", "text")
.addHelpText(
"after",
@@ -49,12 +51,14 @@ Examples:
ix overview IngestionService
ix overview IngestionService --kind class
ix overview verify_token --kind function --format json
- ix overview auth.py --kind file`
+ ix overview src/cli/commands/overview.ts
+ ix overview overview.ts
+ ix overview scoreCandidate --pick 2`
)
- .action(async (symbol: string, opts: { kind?: string; format: string }) => {
+ .action(async (symbol: string, opts: { kind?: string; path?: string; pick?: string; format: string }) => {
const client = new IxClient(getEndpoint());
- const allKinds = [...CONTAINER_KINDS, ...CALLABLE_KINDS];
- const target = await resolveEntity(client, symbol, allKinds, opts);
+ const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
+ const target = await resolveFileOrEntity(client, symbol, resolveOpts);
if (!target) return;
if (opts.format !== "json") printResolved(target);
diff --git a/ix-cli/src/cli/commands/plan.ts b/ix-cli/src/cli/commands/plan.ts
index 268757b9..bbb4d948 100644
--- a/ix-cli/src/cli/commands/plan.ts
+++ b/ix-cli/src/cli/commands/plan.ts
@@ -1,5 +1,7 @@
import type { Command } from "commander";
import type { GraphPatchPayload, PatchOp } from "../../client/types.js";
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
import { deterministicId } from "../github/transform.js";
@@ -7,6 +9,8 @@ import { resolveEntity, printResolved } from "../resolve.js";
import { stderr } from "../stderr.js";
import chalk from "chalk";
+const execFileAsync = promisify(execFile);
+
// ── Types ───────────────────────────────────────────────────────────
export interface StagedWorkflow {
@@ -15,7 +19,7 @@ export interface StagedWorkflow {
validate?: string[];
}
-const VALID_WORKFLOW_STAGES = ["discover", "implement", "validate"];
+export const VALID_WORKFLOW_STAGES = ["discover", "implement", "validate"];
export function isValidWorkflow(w: unknown): w is string[] | StagedWorkflow {
if (Array.isArray(w)) return w.every(s => typeof s === "string");
@@ -26,11 +30,65 @@ export function isValidWorkflow(w: unknown): w is string[] | StagedWorkflow {
}
/** Normalize any workflow form to StagedWorkflow for display */
-function normalizeWorkflow(w: string[] | StagedWorkflow): StagedWorkflow {
+export function normalizeWorkflow(w: string[] | StagedWorkflow): StagedWorkflow {
if (Array.isArray(w)) return { discover: w };
return w;
}
+/** Run workflow stages — constrained to ix commands only. */
+interface WorkflowRunResult {
+ stage: string;
+ command: string;
+ status: "ok" | "error" | "skipped";
+ output?: unknown;
+ error?: string;
+}
+
+async function executeIxCommand(cmd: string): Promise<unknown> {
+ const trimmed = cmd.replace(/^ix\s+/, "");
+ const args = trimmed.split(/\s+/);
+ if (!args.includes("--format") && !args.includes("-f")) {
+ args.push("--format", "json");
+ }
+ const { stdout } = await execFileAsync("ix", args, {
+ maxBuffer: 10 * 1024 * 1024,
+ timeout: 60_000,
+ });
+ try {
+ return JSON.parse(stdout);
+ } catch {
+ return stdout.trim();
+ }
+}
+
+async function runWorkflowStages(
+ workflow: StagedWorkflow,
+ stages: string[],
+): Promise<WorkflowRunResult[]> {
+ const results: WorkflowRunResult[] = [];
+ for (const stage of stages) {
+ const cmds = workflow[stage as keyof StagedWorkflow];
+ if (!cmds || cmds.length === 0) continue;
+ for (const cmd of cmds) {
+ if (!cmd.trimStart().startsWith("ix ") && cmd.trim() !== "ix") {
+ results.push({ stage, command: cmd, status: "skipped", error: "Only ix commands are allowed" });
+ continue;
+ }
+ if (/[|;&`$()]/.test(cmd)) {
+ results.push({ stage, command: cmd, status: "skipped", error: "Shell operators not allowed" });
+ continue;
+ }
+ try {
+ const output = await executeIxCommand(cmd);
+ results.push({ stage, command: cmd, status: "ok", output });
+ } catch (err: any) {
+ results.push({ stage, command: cmd, status: "error", error: err.message || String(err) });
+ }
+ }
+ }
+ return results;
+}
+
// ── Patch builders (exported for testing) ──────────────────────────
function makePatchEnvelope(ops: PatchOp[], intent?: string): GraphPatchPayload {
@@ -192,25 +250,60 @@ export function registerPlanCommand(program: Command): void {
`\nSubcommands:
create <title> Create a new plan linked to a goal
task <title> Add a task to a plan
- status <planId> Show plan status with all tasks
+ status <planId> Show plan status with all tasks (alias: show)
next <planId> Show the next actionable task
+Options --goal and --plan accept IDs, UUID prefixes, or exact names.
+Duplicate names within each type are rejected.
+
Examples:
- ix plan create "Fix auth" --goal <goal-id>
- ix plan task "Step 1" --plan <plan-id>
- ix plan status <plan-id> --format json
+ ix plan create "Fix auth" --goal <goal-id-or-name>
+ ix plan task "Step 1" --plan <plan-id-or-name>
+ ix plan create "Fix auth" --goal "Support GitHub"
+ ix plan task "Step 1" --plan "Fix auth"
+ ix plan show <plan-id> --format json
ix plan next <plan-id> --with-workflow`
);
plan
.command("create <title>")
.description("Create a new plan linked to a goal")
- .requiredOption("--goal <id>", "Goal ID to link the plan to")
+ .requiredOption("--goal <id-or-name>", "Goal ID or name to link the plan to")
.option("--responds-to <bugId>", "Bug ID this plan responds to (creates RESPONDS_TO edge)")
.option("--format <fmt>", "Output format (text|json)", "text")
.action(async (title: string, opts: { goal: string; respondsTo?: string; format: string }) => {
const client = new IxClient(getEndpoint());
- const patch = buildPlanPatch(title, opts.goal, opts.respondsTo);
+
+ // Resolve goal reference (accepts name or ID)
+ let goalId: string;
+ try {
+ goalId = await client.resolvePrefix(opts.goal);
+ } catch {
+ const intents = await client.listTruth();
+ const match = intents.find(
+ (i: any) => (i.name || i.statement || "").toLowerCase() === opts.goal.toLowerCase(),
+ );
+ if (match) {
+ goalId = (match as any).id;
+ } else {
+ stderr(`No goal found matching "${opts.goal}".`);
+ process.exitCode = 1;
+ return;
+ }
+ }
+
+ // Check duplicate plan name
+ const existingPlans = await client.search(title, { limit: 5, kind: "plan", nameOnly: true });
+ const dupPlan = (existingPlans as any[]).find(
+ (n: any) => (n.name || "").toLowerCase() === title.toLowerCase(),
+ );
+ if (dupPlan) {
+ stderr(`A plan named "${title}" already exists (${dupPlan.id.slice(0, 8)}). Use a unique name.`);
+ process.exitCode = 1;
+ return;
+ }
+
+ const patch = buildPlanPatch(title, goalId, opts.respondsTo);
const result = await client.commitPatch(patch);
const planId = patch.ops[0].id as string;
if (opts.format === "json") {
@@ -223,7 +316,7 @@ Examples:
plan
.command("task <title>")
.description("Add a task to a plan")
- .requiredOption("--plan <id>", "Plan ID")
+ .requiredOption("--plan <id-or-name>", "Plan ID or name")
.option("--depends-on <id>", "Task ID this task depends on")
.option("--affects <entities>", "Comma-separated entity names this task affects")
.option("--workflow <commands>", "Comma-separated ix commands to run for this task")
@@ -233,6 +326,33 @@ Examples:
.action(async (title: string, opts: { plan: string; dependsOn?: string; affects?: string; workflow?: string; workflowStaged?: string; resolves?: string; format: string }) => {
const client = new IxClient(getEndpoint());
+ // Resolve plan reference (accepts name or ID)
+ let planId: string;
+ try {
+ planId = await client.resolvePrefix(opts.plan);
+ } catch {
+ const target = await resolveEntity(client, opts.plan, ["plan"], {});
+ if (!target) {
+ process.exitCode = 1;
+ return;
+ }
+ planId = target.id;
+ }
+
+ // Check duplicate task name within this plan
+ const { nodes: existingTasks } = await client.expand(planId, {
+ direction: "out",
+ predicates: ["PLAN_HAS_TASK"],
+ });
+ const dupTask = existingTasks.find(
+ (n: any) => n.kind === "task" && (n.name || "").toLowerCase() === title.toLowerCase(),
+ );
+ if (dupTask) {
+ stderr(`A task named "${title}" already exists in this plan (${dupTask.id.slice(0, 8)}). Use a unique name.`);
+ process.exitCode = 1;
+ return;
+ }
+
let affectsEntities: { id: string; kind: string; name: string }[] | undefined;
if (opts.affects) {
const names = opts.affects.split(",").map(s => s.trim());
@@ -268,7 +388,7 @@ Examples:
}
const patch = buildTaskPatch(title, {
- planId: opts.plan,
+ planId,
dependsOn: opts.dependsOn,
affects: affectsEntities,
workflow,
@@ -285,13 +405,24 @@ Examples:
plan
.command("status <planId>")
+ .alias("show")
.description("Show plan status with all tasks")
.option("--format <fmt>", "Output format (text|json)", "text")
.action(async (planId: string, opts: { format: string }) => {
const client = new IxClient(getEndpoint());
+ // Resolve plan ID (accept name or UUID prefix)
+ let resolvedPlanId = planId;
+ try {
+ resolvedPlanId = await client.resolvePrefix(planId);
+ } catch {
+ const target = await resolveEntity(client, planId, ["plan"], {});
+ if (!target) return;
+ resolvedPlanId = target.id;
+ }
+
// Expand PLAN_HAS_TASK to get all tasks
- const { nodes: taskNodes, edges: taskEdges } = await client.expand(planId, {
+ const { nodes: taskNodes, edges: taskEdges } = await client.expand(resolvedPlanId, {
direction: "out",
predicates: ["PLAN_HAS_TASK"],
});
@@ -344,7 +475,7 @@ Examples:
.map(([id]) => id);
// Count open bugs linked via RESPONDS_TO
- const { nodes: respondNodes } = await client.expand(planId, {
+ const { nodes: respondNodes } = await client.expand(resolvedPlanId, {
direction: "out",
predicates: ["RESPONDS_TO"],
});
@@ -361,7 +492,7 @@ Examples:
if (opts.format === "json") {
console.log(JSON.stringify({
- planId,
+ planId: resolvedPlanId,
tasks: tasks.map(t => ({ title: t.title, status: t.status, id: t.id })),
criticalPath,
nextActionable: nextActionable ? nextActionable.id : null,
@@ -383,11 +514,24 @@ Examples:
.command("next <planId>")
.description("Show the next actionable task in a plan")
.option("--with-workflow", "Include workflow commands in output")
+ .option("--run-workflow", "Resolve next task and run its workflow")
+ .option("--stage <stage>", "When used with --run-workflow, run only this stage")
.option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (planId: string, opts: { withWorkflow?: boolean; format: string }) => {
+ .action(async (planId: string, opts: { withWorkflow?: boolean; runWorkflow?: boolean; stage?: string; format: string }) => {
const client = new IxClient(getEndpoint());
- const { nodes: taskNodes } = await client.expand(planId, {
+ // Resolve plan ID (accept name or UUID prefix)
+ let resolvedPlanId = planId;
+ try {
+ resolvedPlanId = await client.resolvePrefix(planId);
+ } catch {
+ // Try searching by name
+ const target = await resolveEntity(client, planId, ["plan"], {});
+ if (!target) return;
+ resolvedPlanId = target.id;
+ }
+
+ const { nodes: taskNodes } = await client.expand(resolvedPlanId, {
direction: "out",
predicates: ["PLAN_HAS_TASK"],
});
@@ -426,6 +570,35 @@ Examples:
}
}
+ // ── Run workflow if requested ──────────────────────────────────
+ let workflowResults: WorkflowRunResult[] | null = null;
+ let workflowData: StagedWorkflow | null = null;
+
+ if (nextActionable && (opts.withWorkflow || opts.runWorkflow)) {
+ const detail = await client.entity(nextActionable.id);
+ // Check claims first (for workflows attached via `ix workflow attach`), then attrs
+ const wfClaim = detail.claims?.find(
+ (c: any) => c.field === "workflow" || c.statement === "workflow"
+ );
+ const rawWorkflow = wfClaim ? (wfClaim as any).value : detail.node?.attrs?.workflow;
+ if (rawWorkflow) {
+ workflowData = normalizeWorkflow(rawWorkflow as string[] | StagedWorkflow);
+ }
+ }
+
+ if (nextActionable && opts.runWorkflow && workflowData) {
+ let stagesToRun = [...VALID_WORKFLOW_STAGES];
+ if (opts.stage) {
+ if (!VALID_WORKFLOW_STAGES.includes(opts.stage)) {
+ stderr(`Invalid stage "${opts.stage}". Valid: ${VALID_WORKFLOW_STAGES.join(", ")}`);
+ return;
+ }
+ stagesToRun = [opts.stage];
+ }
+ workflowResults = await runWorkflowStages(workflowData, stagesToRun);
+ }
+
+ // ── Output ─────────────────────────────────────────────────────
if (opts.format === "json") {
if (nextActionable) {
const result: Record<string, unknown> = {
@@ -433,12 +606,11 @@ Examples:
taskId: nextActionable.id,
reason: "all dependencies satisfied",
};
- if (opts.withWorkflow) {
- const detail = await client.entity(nextActionable.id);
- const rawWorkflow = detail.node?.attrs?.workflow;
- result.workflow = rawWorkflow
- ? normalizeWorkflow(rawWorkflow as string[] | StagedWorkflow)
- : {};
+ if (workflowData) {
+ result.workflow = workflowData;
+ }
+ if (workflowResults) {
+ result.workflowResults = workflowResults;
}
console.log(JSON.stringify(result, null, 2));
} else {
@@ -447,23 +619,34 @@ Examples:
} else {
if (nextActionable) {
console.log(`${chalk.green("Next:")} ${nextActionable.title} (${nextActionable.id.slice(0, 8)})`);
- if (opts.withWorkflow) {
- const detail = await client.entity(nextActionable.id);
- const rawWorkflow = detail.node?.attrs?.workflow;
- if (rawWorkflow) {
- const staged = normalizeWorkflow(rawWorkflow as string[] | StagedWorkflow);
- console.log(chalk.dim("Workflow:"));
- for (const stage of VALID_WORKFLOW_STAGES) {
- const cmds = staged[stage as keyof StagedWorkflow];
- if (cmds && cmds.length > 0) {
- console.log(` ${chalk.bold(stage)}:`);
- for (const cmd of cmds) {
- console.log(` ${chalk.cyan("▸")} ${cmd}`);
- }
+ if (workflowData) {
+ console.log(chalk.dim("Workflow:"));
+ for (const stage of VALID_WORKFLOW_STAGES) {
+ const cmds = workflowData[stage as keyof StagedWorkflow];
+ if (cmds && cmds.length > 0) {
+ console.log(` ${chalk.bold(stage)}:`);
+ for (const cmd of cmds) {
+ console.log(` ${chalk.cyan("▸")} ${cmd}`);
}
}
}
}
+ if (workflowResults) {
+ console.log();
+ for (const r of workflowResults) {
+ const icon = r.status === "ok" ? chalk.green("✓")
+ : r.status === "error" ? chalk.red("✗")
+ : chalk.yellow("⊘");
+ console.log(` ${icon} ${chalk.dim(`[${r.stage}]`)} ${r.command}`);
+ if (r.status === "error" && r.error) {
+ console.log(` ${chalk.red(r.error)}`);
+ }
+ }
+ const ok = workflowResults.filter(r => r.status === "ok").length;
+ const err = workflowResults.filter(r => r.status === "error").length;
+ const skip = workflowResults.filter(r => r.status === "skipped").length;
+ console.log(chalk.dim(`\nDone: ${ok} ok, ${err} error, ${skip} skipped`));
+ }
} else {
console.log(chalk.dim(`No actionable tasks: ${noActionReason}`));
}
@@ -493,7 +676,18 @@ Examples:
.option("--format <fmt>", "Output format (text|json)", "text")
.action(async (taskId: string, opts: { withWorkflow?: boolean; format: string }) => {
const client = new IxClient(getEndpoint());
- const details = await client.entity(taskId);
+
+ // Resolve task ID (accept name or UUID prefix)
+ let resolvedTaskId = taskId;
+ try {
+ resolvedTaskId = await client.resolvePrefix(taskId);
+ } catch {
+ const target = await resolveEntity(client, taskId, ["task"], {});
+ if (!target) return;
+ resolvedTaskId = target.id;
+ }
+
+ const details = await client.entity(resolvedTaskId);
const node = details.node as any;
const statusClaim = details.claims?.find(
@@ -503,11 +697,15 @@ Examples:
? ((statusClaim as any).value ?? (statusClaim as any).statement ?? "pending")
: (node.attrs?.status ?? "pending");
- const rawWorkflow = node.attrs?.workflow as string[] | StagedWorkflow | undefined;
+ // Check claims first (for workflows attached via `ix workflow attach`), then attrs
+ const workflowClaim = details.claims?.find(
+ (c: any) => c.field === "workflow" || c.statement === "workflow"
+ );
+ const rawWorkflow = (workflowClaim ? (workflowClaim as any).value : node.attrs?.workflow) as string[] | StagedWorkflow | undefined;
if (opts.format === "json") {
const result: Record<string, unknown> = {
- taskId,
+ taskId: resolvedTaskId,
title: node.name,
status,
created_at: node.attrs?.created_at ?? node.createdAt,
diff --git a/ix-cli/src/cli/commands/read.ts b/ix-cli/src/cli/commands/read.ts
index 746e094f..88c8b46a 100644
--- a/ix-cli/src/cli/commands/read.ts
+++ b/ix-cli/src/cli/commands/read.ts
@@ -39,7 +39,8 @@ interface ReadResult {
interface AmbiguityResult {
targetType: "ambiguous-file" | "ambiguous-symbol";
- candidates: Array<{ name: string; kind?: string; path?: string; id?: string }>;
+ candidates: Array<{ name: string; kind?: string; path?: string; id?: string; rank?: number }>;
+ diagnostics?: Array<{ code: string; message: string }>;
}
async function checkStale(client: IxClient, filePath: string): Promise<boolean> {
@@ -76,16 +77,17 @@ function outputAmbiguity(result: AmbiguityResult, target: string, format: string
} else {
const label = result.targetType === "ambiguous-file" ? "file" : "symbol";
stderr(`Ambiguous ${label} "${target}":`);
- for (const c of result.candidates) {
+ for (let i = 0; i < result.candidates.length; i++) {
+ const c = result.candidates[i];
const kindStr = c.kind ? chalk.cyan(c.kind.padEnd(10)) : "";
const pathStr = c.path ? chalk.dim(` ${c.path}`) : "";
const idStr = c.id ? chalk.dim(` ${c.id.slice(0, 8)}`) : "";
- stderr(` ${kindStr}${idStr} ${c.name}${pathStr}`);
+ stderr(` ${i + 1}. ${kindStr}${idStr} ${c.name}${pathStr}`);
}
if (result.targetType === "ambiguous-file") {
stderr(chalk.dim("\nProvide a more specific path to disambiguate."));
} else {
- stderr(chalk.dim("\nUse --kind or --path to disambiguate."));
+ stderr(chalk.dim("\nUse --pick <n>, --kind, or --path to disambiguate."));
}
}
}
@@ -97,6 +99,7 @@ export function registerReadCommand(program: Command): void {
.option("--format <fmt>", "Output format (text|json)", "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("--root <dir>", "Workspace root directory")
.addHelpText("after", `\nResolution order:
1. Exact file path ix read src/main.ts
@@ -112,7 +115,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; root?: string }) => {
+ .action(async (target: string, opts: { format: string; kind?: string; path?: string; pick?: string; root?: string }) => {
const root = resolveWorkspaceRoot(opts.root);
const client = new IxClient(getEndpoint());
@@ -164,7 +167,8 @@ Examples:
if (filenameMatches.length > 1) {
outputAmbiguity({
targetType: "ambiguous-file",
- candidates: filenameMatches.map(m => ({ name: m.name, path: m.path })),
+ candidates: filenameMatches.map((m, i) => ({ name: m.name, path: m.path, rank: i + 1 })),
+ diagnostics: [{ code: "ambiguous_resolution", message: "Provide a more specific path to disambiguate." }],
}, target, opts.format);
return;
}
@@ -172,7 +176,7 @@ Examples:
}
// --- Step 4: Try unique symbol match ---
- const symbolResult = await trySymbolMatch(client, rawTarget, opts);
+ const symbolResult = await trySymbolMatch(client, rawTarget, { kind: opts.kind, path: opts.path, pick: opts.pick ? parseInt(opts.pick, 10) : undefined });
if (symbolResult.type === "resolved") {
const { node, sourceUri } = symbolResult;
const stale = sourceUri ? await checkStale(client, sourceUri) : false;
@@ -224,7 +228,8 @@ Examples:
if (symbolResult.type === "ambiguous") {
outputAmbiguity({
targetType: "ambiguous-symbol",
- candidates: symbolResult.candidates,
+ candidates: symbolResult.candidates.map((c, i) => ({ ...c, rank: i + 1 })),
+ diagnostics: [{ code: "ambiguous_resolution", message: "Use --pick <n> or --path to disambiguate." }],
}, target, opts.format);
return;
}
@@ -314,7 +319,7 @@ type SymbolResult =
async function trySymbolMatch(
client: IxClient,
symbol: string,
- opts: { kind?: string; path?: string }
+ opts: { kind?: string; path?: string; pick?: number }
): Promise<SymbolResult> {
const preferredKinds = ["file", "class", "object", "trait", "interface", "module", "function", "method"];
const full = await resolveEntityFull(client, symbol, preferredKinds, opts);
diff --git a/ix-cli/src/cli/commands/workflow.ts b/ix-cli/src/cli/commands/workflow.ts
new file mode 100644
index 00000000..c6c37a06
--- /dev/null
+++ b/ix-cli/src/cli/commands/workflow.ts
@@ -0,0 +1,533 @@
+import * as fs from "node:fs";
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+import type { Command } from "commander";
+import chalk from "chalk";
+import type { PatchOp, GraphPatchPayload } from "../../client/types.js";
+import { IxClient } from "../../client/api.js";
+import { getEndpoint } from "../config.js";
+import { deterministicId } from "../github/transform.js";
+import {
+ type StagedWorkflow,
+ isValidWorkflow,
+ normalizeWorkflow,
+ VALID_WORKFLOW_STAGES,
+} from "./plan.js";
+import { stderr } from "../stderr.js";
+
+const execFileAsync = promisify(execFile);
+
+// ── Helpers ────────────────────────────────────────────────────────
+
+async function resolveTargetEntity(
+ client: IxClient,
+ targetType: string,
+ targetId: string,
+): Promise<{ node: any; claims: any[]; edges: any[] } | null> {
+ const validTypes = ["task", "plan", "decision"];
+ if (!validTypes.includes(targetType)) {
+ stderr(`Invalid target type "${targetType}". Valid: ${validTypes.join(", ")}`);
+ return null;
+ }
+
+ let resolvedId = targetId;
+ try {
+ resolvedId = await client.resolvePrefix(targetId);
+ } catch {
+ // Try search by name
+ const nodes = await client.search(targetId, { limit: 5, kind: targetType, nameOnly: true });
+ const match = (nodes as any[]).find(
+ (n: any) => (n.name || "").toLowerCase() === targetId.toLowerCase(),
+ );
+ if (match) {
+ resolvedId = match.id;
+ } else if (nodes.length > 0) {
+ resolvedId = (nodes[0] as any).id;
+ } else {
+ stderr(`No ${targetType} found matching "${targetId}".`);
+ return null;
+ }
+ }
+
+ try {
+ return await client.entity(resolvedId);
+ } catch {
+ stderr(`Entity not found: ${resolvedId}`);
+ return null;
+ }
+}
+
+/**
+ * Extract workflow from an entity, checking claims first (for post-attach updates),
+ * then falling back to node.attrs (for inline workflows set at creation time).
+ */
+export function extractWorkflow(node: any, claims?: any[]): StagedWorkflow | null {
+ // Claims take precedence (workflow set via AssertClaim, e.g. workflow attach)
+ if (claims) {
+ const workflowClaim = claims.find(
+ (c: any) => c.field === "workflow" || c.statement === "workflow"
+ );
+ if (workflowClaim) {
+ const val = (workflowClaim as any).value;
+ if (val && isValidWorkflow(val)) {
+ return normalizeWorkflow(val as string[] | StagedWorkflow);
+ }
+ }
+ }
+ // Fall back to node attrs (workflow set at creation time)
+ const raw = node.attrs?.workflow;
+ if (!raw) return null;
+ if (!isValidWorkflow(raw)) return null;
+ return normalizeWorkflow(raw as string[] | StagedWorkflow);
+}
+
+interface WorkflowRunResult {
+ stage: string;
+ command: string;
+ status: "ok" | "error" | "skipped";
+ output?: unknown;
+ error?: string;
+}
+
+async function executeIxCommand(cmd: string): Promise<WorkflowRunResult["output"]> {
+ // Strip leading "ix " and split into args
+ const trimmed = cmd.replace(/^ix\s+/, "");
+ const args = trimmed.split(/\s+/);
+
+ // Always append --format json for structured output
+ if (!args.includes("--format") && !args.includes("-f")) {
+ args.push("--format", "json");
+ }
+
+ const { stdout } = await execFileAsync("ix", args, {
+ maxBuffer: 10 * 1024 * 1024,
+ timeout: 60_000,
+ });
+
+ try {
+ return JSON.parse(stdout);
+ } catch {
+ return stdout.trim();
+ }
+}
+
+async function runWorkflowStages(
+ workflow: StagedWorkflow,
+ stages: string[],
+): Promise<WorkflowRunResult[]> {
+ const results: WorkflowRunResult[] = [];
+
+ for (const stage of stages) {
+ const cmds = workflow[stage as keyof StagedWorkflow];
+ if (!cmds || cmds.length === 0) continue;
+
+ for (const cmd of cmds) {
+ // Security: only allow ix commands
+ if (!cmd.trimStart().startsWith("ix ") && cmd.trim() !== "ix") {
+ results.push({
+ stage,
+ command: cmd,
+ status: "skipped",
+ error: "Only ix commands are allowed in workflows",
+ });
+ continue;
+ }
+
+ // Security: no pipes, semicolons, backticks, $(), etc.
+ if (/[|;&`$()]/.test(cmd)) {
+ results.push({
+ stage,
+ command: cmd,
+ status: "skipped",
+ error: "Pipes, shell operators, and variable expansion are not allowed",
+ });
+ continue;
+ }
+
+ try {
+ const output = await executeIxCommand(cmd);
+ results.push({ stage, command: cmd, status: "ok", output });
+ } catch (err: any) {
+ results.push({
+ stage,
+ command: cmd,
+ status: "error",
+ error: err.message || String(err),
+ });
+ }
+ }
+ }
+
+ return results;
+}
+
+// ── Patch builder ─────────────────────────────────────────────────
+
+export function buildWorkflowAttachPatch(
+ entityId: string,
+ workflow: string[] | StagedWorkflow,
+): GraphPatchPayload {
+ const ops: PatchOp[] = [
+ {
+ type: "AssertClaim",
+ entityId,
+ field: "workflow",
+ value: workflow,
+ confidence: 1.0,
+ },
+ ];
+ return {
+ patchId: deterministicId(`workflow-attach-${entityId}-${Date.now()}-${Math.random()}`),
+ actor: "ix-cli",
+ timestamp: new Date().toISOString(),
+ source: {
+ uri: "ix-cli://workflow",
+ extractor: "ix-cli-workflow",
+ sourceType: "cli",
+ },
+ baseRev: 0,
+ ops,
+ replaces: [],
+ intent: `Attach workflow to ${entityId}`,
+ };
+}
+
+// ── CLI Registration ───────────────────────────────────────────────
+
+export function registerWorkflowCommand(program: Command): void {
+ const wf = program
+ .command("workflow")
+ .description("Attach, show, validate, or run staged workflows on tasks/plans")
+ .addHelpText(
+ "after",
+ `
+A workflow is a staged sequence of Ix commands attached to a task, plan, or decision.
+It is NOT a goal, plan, task, or bug — those are developer-cycle objects that may HAVE workflows.
+
+Stages: discover, implement, validate
+
+Subcommands:
+ attach <type> <id> Attach a workflow from a JSON file
+ show <type> <id> Show the workflow attached to a target
+ validate <type> <id> Validate workflow structure
+ run <type> <id> Execute workflow commands (ix-only, no shell)
+
+Examples:
+ ix workflow attach task <task-id> --file /path/to/workflow.json
+ ix workflow attach plan <plan-id> --file /path/to/workflow.json
+ ix workflow show task <task-id>
+ ix workflow show plan <plan-id>
+ ix workflow validate task <task-id>
+ ix workflow run task <task-id> --stage discover
+ ix workflow run plan <plan-id>`,
+ );
+
+ // ── attach ───────────────────────────────────────────────────────
+ wf.command("attach <type> <id>")
+ .description("Attach a workflow from a JSON file to a task, plan, or decision")
+ .requiredOption("--file <path>", "Path to workflow JSON file")
+ .option("--format <fmt>", "Output format (text|json)", "text")
+ .action(async (targetType: string, targetId: string, opts: { file: string; format: string }) => {
+ const client = new IxClient(getEndpoint());
+
+ // 1. Resolve target entity
+ const details = await resolveTargetEntity(client, targetType, targetId);
+ if (!details) return;
+
+ // 2. Load and parse JSON file
+ let raw: unknown;
+ try {
+ const content = fs.readFileSync(opts.file, "utf-8");
+ raw = JSON.parse(content);
+ } catch (err: any) {
+ stderr(`Failed to read workflow file: ${err.message}`);
+ process.exitCode = 1;
+ return;
+ }
+
+ // 3. Validate workflow structure
+ if (!isValidWorkflow(raw)) {
+ stderr(`Invalid workflow structure in ${opts.file}.`);
+ stderr(`Expected a flat array of strings or a staged object with keys: ${VALID_WORKFLOW_STAGES.join(", ")}`);
+ process.exitCode = 1;
+ return;
+ }
+
+ const workflow = raw as string[] | StagedWorkflow;
+ const normalized = normalizeWorkflow(workflow);
+
+ // 4. Validate command safety
+ const issues: string[] = [];
+ for (const stage of VALID_WORKFLOW_STAGES) {
+ const cmds = normalized[stage as keyof StagedWorkflow] ?? [];
+ for (const cmd of cmds) {
+ if (!cmd.trimStart().startsWith("ix ")) {
+ issues.push(`Stage "${stage}": command does not start with "ix": ${cmd}`);
+ }
+ if (/[|;&`$()]/.test(cmd)) {
+ issues.push(`Stage "${stage}": command contains shell operators: ${cmd}`);
+ }
+ }
+ }
+ if (issues.length > 0) {
+ stderr("Workflow validation failed:");
+ for (const issue of issues) {
+ stderr(` ${issue}`);
+ }
+ process.exitCode = 1;
+ return;
+ }
+
+ // 5. Attach via patch
+ const resolvedId = details.node.id ?? targetId;
+ const patch = buildWorkflowAttachPatch(resolvedId, workflow);
+ const result = await client.commitPatch(patch);
+ const name = details.node.name || targetId;
+
+ // 6. Read-after-write verification
+ let verified: { node: any; claims: any[]; edges: any[] } | null = null;
+ try {
+ verified = await client.entity(resolvedId);
+ } catch {
+ stderr("Workflow patch committed but read-back failed. Entity may not exist.");
+ process.exitCode = 1;
+ return;
+ }
+ const verifiedWorkflow = extractWorkflow(verified.node, verified.claims);
+ if (!verifiedWorkflow) {
+ stderr("Workflow patch committed but read-back shows no workflow claim. Persistence may have failed.");
+ process.exitCode = 1;
+ return;
+ }
+
+ if (opts.format === "json") {
+ console.log(JSON.stringify({
+ targetType,
+ targetId: resolvedId,
+ targetName: name,
+ attached: true,
+ verified: true,
+ workflow: verifiedWorkflow,
+ rev: result.rev,
+ }, null, 2));
+ } else {
+ console.log(`Workflow attached to ${chalk.cyan(targetType)} ${chalk.bold(name)} (rev ${result.rev})`);
+ console.log(chalk.green(" Read-after-write verified."));
+ for (const stage of VALID_WORKFLOW_STAGES) {
+ const cmds = verifiedWorkflow[stage as keyof StagedWorkflow];
+ if (cmds && cmds.length > 0) {
+ console.log(` ${chalk.bold(stage)}: ${cmds.length} command(s)`);
+ }
+ }
+ }
+ });
+
+ // ── show ─────────────────────────────────────────────────────────
+ wf.command("show <type> <id>")
+ .description("Show the workflow attached to a task, plan, or decision")
+ .option("--format <fmt>", "Output format (text|json)", "text")
+ .action(async (targetType: string, targetId: string, opts: { format: string }) => {
+ const client = new IxClient(getEndpoint());
+ const details = await resolveTargetEntity(client, targetType, targetId);
+ if (!details) return;
+
+ const workflow = extractWorkflow(details.node, details.claims);
+ const name = details.node.name || targetId;
+
+ if (opts.format === "json") {
+ console.log(JSON.stringify({
+ targetType,
+ targetId: details.node.id ?? targetId,
+ targetName: name,
+ workflow: workflow ?? null,
+ hasWorkflow: !!workflow,
+ }, null, 2));
+ } else {
+ console.log(`${chalk.bold(name)} (${chalk.cyan(targetType)})`);
+ if (!workflow) {
+ console.log(chalk.dim(" No workflow attached."));
+ return;
+ }
+ for (const stage of VALID_WORKFLOW_STAGES) {
+ const cmds = workflow[stage as keyof StagedWorkflow];
+ if (cmds && cmds.length > 0) {
+ console.log(` ${chalk.bold(stage)}:`);
+ for (const cmd of cmds) {
+ console.log(` ${chalk.cyan("▸")} ${cmd}`);
+ }
+ }
+ }
+ }
+ });
+
+ // ── validate ─────────────────────────────────────────────────────
+ wf.command("validate <type> <id>")
+ .description("Validate the workflow structure on a task, plan, or decision")
+ .option("--format <fmt>", "Output format (text|json)", "text")
+ .action(async (targetType: string, targetId: string, opts: { format: string }) => {
+ const client = new IxClient(getEndpoint());
+ const details = await resolveTargetEntity(client, targetType, targetId);
+ if (!details) return;
+
+ const name = details.node.name || targetId;
+ // Check claims first (for attached workflows), then attrs (for inline workflows)
+ const workflowClaim = details.claims?.find(
+ (c: any) => c.field === "workflow" || c.statement === "workflow"
+ );
+ const raw = workflowClaim ? (workflowClaim as any).value : details.node.attrs?.workflow;
+ const issues: string[] = [];
+
+ if (!raw) {
+ issues.push("No workflow field present on entity.");
+ } else if (Array.isArray(raw)) {
+ // Legacy flat list — valid but could be normalized
+ if (!raw.every((s: unknown) => typeof s === "string")) {
+ issues.push("Legacy flat-list workflow contains non-string entries.");
+ }
+ } else if (typeof raw === "object" && raw !== null) {
+ const keys = Object.keys(raw);
+ for (const k of keys) {
+ if (!VALID_WORKFLOW_STAGES.includes(k)) {
+ issues.push(`Unknown stage key: "${k}". Valid: ${VALID_WORKFLOW_STAGES.join(", ")}`);
+ }
+ }
+ for (const k of keys) {
+ const val = (raw as any)[k];
+ if (!Array.isArray(val)) {
+ issues.push(`Stage "${k}" must be an array of strings, got ${typeof val}.`);
+ } else if (!val.every((s: unknown) => typeof s === "string")) {
+ issues.push(`Stage "${k}" contains non-string entries.`);
+ }
+ }
+ } else {
+ issues.push(`Workflow field is not an array or object (got ${typeof raw}).`);
+ }
+
+ // Check command safety
+ if (raw && isValidWorkflow(raw)) {
+ const normalized = normalizeWorkflow(raw as string[] | StagedWorkflow);
+ for (const stage of VALID_WORKFLOW_STAGES) {
+ const cmds = normalized[stage as keyof StagedWorkflow] ?? [];
+ for (const cmd of cmds) {
+ if (!cmd.trimStart().startsWith("ix ")) {
+ issues.push(`Stage "${stage}": command does not start with "ix": ${cmd}`);
+ }
+ if (/[|;&`$()]/.test(cmd)) {
+ issues.push(`Stage "${stage}": command contains shell operators: ${cmd}`);
+ }
+ }
+ }
+ }
+
+ const valid = issues.length === 0 && !!raw;
+
+ if (opts.format === "json") {
+ console.log(JSON.stringify({
+ targetType,
+ targetId: details.node.id ?? targetId,
+ targetName: name,
+ valid,
+ issues,
+ normalized: raw && isValidWorkflow(raw)
+ ? normalizeWorkflow(raw as string[] | StagedWorkflow)
+ : null,
+ }, null, 2));
+ } else {
+ console.log(`${chalk.bold(name)} (${chalk.cyan(targetType)})`);
+ if (valid) {
+ console.log(chalk.green(" Workflow is valid."));
+ const normalized = normalizeWorkflow(raw as string[] | StagedWorkflow);
+ for (const stage of VALID_WORKFLOW_STAGES) {
+ const cmds = normalized[stage as keyof StagedWorkflow];
+ if (cmds && cmds.length > 0) {
+ console.log(` ${chalk.bold(stage)}: ${cmds.length} command(s)`);
+ }
+ }
+ } else {
+ console.log(chalk.red(" Workflow validation failed:"));
+ for (const issue of issues) {
+ console.log(` ${chalk.yellow("!")} ${issue}`);
+ }
+ }
+ }
+ });
+
+ // ── run ──────────────────────────────────────────────────────────
+ wf.command("run <type> <id>")
+ .description("Execute workflow commands (ix-only, no arbitrary shell)")
+ .option("--stage <stage>", "Run only this stage (discover|implement|validate)")
+ .option("--format <fmt>", "Output format (text|json)", "text")
+ .action(async (targetType: string, targetId: string, opts: { stage?: string; format: string }) => {
+ const client = new IxClient(getEndpoint());
+ const details = await resolveTargetEntity(client, targetType, targetId);
+ if (!details) return;
+
+ const name = details.node.name || targetId;
+ const workflow = extractWorkflow(details.node, details.claims);
+
+ if (!workflow) {
+ if (opts.format === "json") {
+ console.log(JSON.stringify({
+ targetType,
+ targetId: details.node.id ?? targetId,
+ targetName: name,
+ stagesRun: [],
+ results: [],
+ diagnostics: ["No workflow attached to this entity."],
+ }, null, 2));
+ } else {
+ stderr("No workflow attached to this entity.");
+ }
+ return;
+ }
+
+ // Determine which stages to run
+ let stagesToRun = [...VALID_WORKFLOW_STAGES];
+ if (opts.stage) {
+ if (!VALID_WORKFLOW_STAGES.includes(opts.stage)) {
+ stderr(`Invalid stage "${opts.stage}". Valid: ${VALID_WORKFLOW_STAGES.join(", ")}`);
+ return;
+ }
+ stagesToRun = [opts.stage];
+ }
+
+ if (opts.format !== "json") {
+ console.log(`${chalk.bold("Running workflow")} for ${chalk.cyan(targetType)} ${chalk.bold(name)}\n`);
+ }
+
+ const results = await runWorkflowStages(workflow, stagesToRun);
+
+ if (opts.format === "json") {
+ console.log(JSON.stringify({
+ targetType,
+ targetId: details.node.id ?? targetId,
+ targetName: name,
+ stagesRun: stagesToRun.filter(s => {
+ const cmds = workflow[s as keyof StagedWorkflow];
+ return cmds && cmds.length > 0;
+ }),
+ results,
+ diagnostics: [],
+ }, null, 2));
+ } else {
+ for (const r of results) {
+ const statusIcon = r.status === "ok" ? chalk.green("✓")
+ : r.status === "error" ? chalk.red("✗")
+ : chalk.yellow("⊘");
+ console.log(` ${statusIcon} ${chalk.dim(`[${r.stage}]`)} ${r.command}`);
+ if (r.status === "error" && r.error) {
+ console.log(` ${chalk.red(r.error)}`);
+ }
+ if (r.status === "ok" && r.output && typeof r.output === "object") {
+ // Show a brief summary of the output
+ const keys = Object.keys(r.output as object);
+ console.log(` ${chalk.dim(`→ ${keys.length} fields returned`)}`);
+ }
+ }
+ const okCount = results.filter(r => r.status === "ok").length;
+ const errCount = results.filter(r => r.status === "error").length;
+ const skipCount = results.filter(r => r.status === "skipped").length;
+ console.log(`\n${chalk.dim(`Done: ${okCount} ok, ${errCount} error, ${skipCount} skipped`)}`);
+ }
+ });
+}
diff --git a/ix-cli/src/cli/commands/workflows.ts b/ix-cli/src/cli/commands/workflows.ts
index c337e18e..e0444f31 100644
--- a/ix-cli/src/cli/commands/workflows.ts
+++ b/ix-cli/src/cli/commands/workflows.ts
@@ -9,6 +9,25 @@ Recommended Development Loop:
4. ix rank --by callers --kind method Find hotspots
5. ix plan next <id> --with-workflow Get next task with commands
+Staged Workflows:
+ A workflow is a staged sequence of Ix commands attached to a task/plan/decision.
+ It is NOT a goal, plan, task, or bug — those are developer-cycle objects that may HAVE workflows.
+
+ Stages: discover → implement → validate
+
+ Attach a workflow from a file:
+ ix workflow attach task <id> --file /path/to/workflow.json
+ ix workflow attach plan <id> --file /path/to/workflow.json
+
+ Or inline when creating a task:
+ ix plan task "Step 1" --plan <id> --workflow-staged '{"discover":["ix overview X"]}'
+
+ ix workflow show task <id> Show workflow on a task
+ ix workflow show plan <id> Show workflow on a plan
+ ix workflow validate task <id> Validate workflow structure
+ ix workflow run task <id> Run all workflow stages
+ ix workflow run task <id> --stage discover Run one stage
+
Bug Workflow:
ix bugs --status open See open bugs
ix bug show <id> Get bug details
@@ -35,11 +54,22 @@ export function registerWorkflowsHelpCommand(program: Command): void {
return;
}
- if (topic === "workflows") {
+ if (topic === "workflows" || topic === "workflow") {
console.log(WORKFLOWS_TEXT);
return;
}
+ // "goals" → forward to "goal" command help
+ if (topic === "goals") {
+ const goalCmd = program.commands.find(
+ (c: Command) => c.name() === "goal"
+ );
+ if (goalCmd) {
+ goalCmd.outputHelp();
+ return;
+ }
+ }
+
// Look up the topic as a registered command and show its help
const cmd = program.commands.find(
(c: Command) => c.name() === topic
diff --git a/ix-cli/src/cli/main.ts b/ix-cli/src/cli/main.ts
index 841238e8..0df88266 100644
--- a/ix-cli/src/cli/main.ts
+++ b/ix-cli/src/cli/main.ts
@@ -35,7 +35,9 @@ import { registerPlansCommand } from "./commands/plans.js";
import { registerWatchCommand } from "./commands/watch.js";
import { registerBriefingCommand } from "./commands/briefing.js";
import { registerWorkflowsHelpCommand } from "./commands/workflows.js";
+import { registerWorkflowCommand } from "./commands/workflow.js";
import { registerTasksCommand } from "./commands/tasks.js";
+import { registerGoalsCommand } from "./commands/goals.js";
const HELP_HEADER = `
Workflow Commands (start here):
@@ -49,10 +51,12 @@ Planning & Tracking:
plan Manage plans (create, task, status, next)
task Manage tasks (show, update)
tasks List all tasks across plans
+ workflow Attach, show, validate, or run staged workflows
bug Manage bugs (create, show, update)
bugs List bugs
decide <title> Record a design decision
goal Manage project goals
+ goals List all goals
Core Graph / Code Commands:
read <target> Read file content or symbol source code
@@ -123,7 +127,9 @@ registerBugsCommand(program);
registerPlansCommand(program);
registerWatchCommand(program);
registerBriefingCommand(program);
+registerWorkflowCommand(program);
registerWorkflowsHelpCommand(program);
registerTasksCommand(program);
+registerGoalsCommand(program);
program.parse();
diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.ts
index ccd39bed..d2217a8c 100644
--- a/ix-cli/src/cli/resolve.ts
+++ b/ix-cli/src/cli/resolve.ts
@@ -1,3 +1,4 @@
+import * as path from "node:path";
import chalk from "chalk";
import type { IxClient } from "../client/api.js";
import { stderr } from "./stderr.js";
@@ -14,7 +15,8 @@ export interface ResolvedEntity {
export interface AmbiguousResult {
resolutionMode: "ambiguous";
- candidates: Array<{ id: string; name: string; kind: string; path?: string; score?: number }>;
+ candidates: Array<{ id: string; name: string; kind: string; path?: string; score?: number; rank?: number }>;
+ diagnostics?: Array<{ code: string; message: string }>;
}
export type ResolveResult =
@@ -98,7 +100,7 @@ export async function resolveEntity(
client: IxClient,
symbol: string,
preferredKinds: string[],
- opts?: { kind?: string; path?: string }
+ opts?: { kind?: string; path?: string; pick?: number }
): Promise<ResolvedEntity | null> {
const result = await resolveEntityFull(client, symbol, preferredKinds, opts);
if (result.resolved) return result.entity;
@@ -119,7 +121,7 @@ export async function resolveEntityFull(
client: IxClient,
symbol: string,
preferredKinds: string[],
- opts?: { kind?: string; path?: string }
+ opts?: { kind?: string; path?: string; pick?: number }
): Promise<ResolveResult> {
const kindFilter = opts?.kind;
const nodes = await client.search(symbol, { limit: 20, kind: kindFilter, nameOnly: true });
@@ -139,12 +141,22 @@ export async function resolveEntityFull(
// Score exact-name candidates
if (exactName.length > 0) {
const winner = pickBest(exactName, symbol, preferredKinds, opts);
- if (winner) return winner;
+ if (winner) {
+ const picked = applyPick(winner, opts);
+ if (picked) return picked;
+ if (!winner.resolved) return winner; // ambiguous but no --pick
+ return winner;
+ }
}
// ── Phase 2: Fall back to all candidates ────────────────────────────
const winner = pickBest(nodes, symbol, preferredKinds, opts);
- if (winner) return winner;
+ if (winner) {
+ const picked = applyPick(winner, opts);
+ if (picked) return picked;
+ if (!winner.resolved) return winner;
+ return winner;
+ }
// Nothing resolved at all
stderr(`No entity found matching "${symbol}".`);
@@ -243,6 +255,39 @@ function pickBest(
};
}
+/**
+ * When --pick is set and the result is ambiguous, select the candidate by 1-based index.
+ * Returns the resolved result, an error result, or null if --pick is not set.
+ */
+export function applyPick(
+ result: ResolveResult,
+ opts?: { pick?: number }
+): ResolveResult | null {
+ if (opts?.pick == null) return null;
+ if (result.resolved) return null; // already resolved, no need to pick
+ if (!result.ambiguous) return null;
+
+ const candidates = result.result.candidates;
+ const idx = opts.pick - 1; // convert 1-based to 0-based
+
+ if (idx < 0 || idx >= candidates.length) {
+ stderr(`--pick ${opts.pick} is out of range (1-${candidates.length}).`);
+ return { resolved: false, ambiguous: false };
+ }
+
+ const picked = candidates[idx];
+ return {
+ resolved: true,
+ entity: {
+ id: picked.id,
+ kind: picked.kind,
+ name: picked.name,
+ path: picked.path,
+ resolutionMode: "scored",
+ },
+ };
+}
+
function resolutionMode(scored: { score: number }, opts?: { kind?: string }): ResolutionMode {
if (opts?.kind) return "exact";
if (scored.score <= 0) return "exact";
@@ -265,28 +310,36 @@ function nodeToResolved(node: any, symbol: string, mode: ResolutionMode): Resolv
function buildAmbiguous(nodes: any[], scores?: number[]): AmbiguousResult {
const seen = new Set<string>();
const candidates: AmbiguousResult["candidates"] = [];
+ let rank = 0;
for (let i = 0; i < nodes.length && i < 5; i++) {
const node = nodes[i] as any;
if (seen.has(node.id)) continue;
seen.add(node.id);
+ rank++;
candidates.push({
id: node.id,
name: node.name || node.attrs?.name || "(unnamed)",
kind: node.kind ?? "",
path: node.provenance?.sourceUri ?? node.provenance?.source_uri ?? node.path,
score: scores?.[i],
+ rank,
});
}
- return { resolutionMode: "ambiguous", candidates };
+ return {
+ resolutionMode: "ambiguous",
+ candidates,
+ diagnostics: [{ code: "ambiguous_resolution", message: "Use --pick <n> or --path to disambiguate." }],
+ };
}
function printAmbiguous(symbol: string, result: AmbiguousResult, opts?: { kind?: string; path?: string }): void {
stderr(`Ambiguous symbol "${symbol}":`);
- for (const c of result.candidates) {
+ for (let i = 0; i < result.candidates.length; i++) {
+ const c = result.candidates[i];
const shortPath = c.path ? ` in ${c.path}` : "";
- stderr(` ${chalk.cyan((c.kind ?? "").padEnd(10))} ${chalk.dim(c.id.slice(0, 8))} ${c.name}${chalk.dim(shortPath)}`);
+ stderr(` ${i + 1}. ${chalk.cyan((c.kind ?? "").padEnd(10))} ${chalk.dim(c.id.slice(0, 8))} ${c.name}${chalk.dim(shortPath)}`);
}
- const hints: string[] = [];
+ const hints: string[] = ["--pick <n>"];
if (!opts?.kind) hints.push("--kind");
if (!opts?.path) hints.push("--path");
stderr(chalk.dim(`\nUse ${hints.join(" or ")} to disambiguate.`));
@@ -309,3 +362,123 @@ export function isRawId(s: string): boolean {
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i.test(s)
|| /^[0-9a-f]{32,}$/i.test(s);
}
+
+// ── File-first resolution ─────────────────────────────────────────────────
+
+/** Common file extensions that signal the target is file-like, not a symbol name. */
+const FILE_EXTENSIONS = new Set([
+ ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",
+ ".scala", ".sc", ".java", ".py", ".rb", ".go", ".rs",
+ ".md", ".mdx", ".rst", ".txt",
+ ".json", ".yaml", ".yml", ".toml", ".ini", ".conf",
+ ".sql", ".graphql", ".gql", ".sh", ".bash",
+ ".html", ".css", ".scss", ".less",
+]);
+
+export function looksFileLike(target: string): boolean {
+ if (target.includes("/") || target.includes("\\")) return true;
+ const ext = path.extname(target).toLowerCase();
+ return ext !== "" && FILE_EXTENSIONS.has(ext);
+}
+
+/**
+ * Resolve a target to a graph entity ID, trying file paths first.
+ *
+ * Resolution order:
+ * 1. Raw UUID → return directly
+ * 2. File-like input → search graph for matching file entity
+ * 3. Symbol name → use scored resolver
+ *
+ * Returns { id, name, kind } or null if not found.
+ */
+export async function resolveFileOrEntity(
+ client: IxClient,
+ target: string,
+ opts?: { kind?: string; path?: string; pick?: number }
+): Promise<ResolvedEntity | null> {
+ // 1. Raw UUID
+ if (isRawId(target)) {
+ try {
+ const details = await client.entity(target);
+ const n = details.node as any;
+ return {
+ id: target,
+ kind: n.kind || "unknown",
+ name: n.name || target,
+ resolutionMode: "exact",
+ };
+ } catch {
+ stderr(`Entity not found: ${target}`);
+ return null;
+ }
+ }
+
+ // 2. File-like input → try graph file search
+ if (looksFileLike(target)) {
+ const fileEntity = await tryFileGraphMatch(client, target);
+ if (fileEntity) return fileEntity;
+ // Fall through to symbol resolution
+ }
+
+ // 3. Symbol resolution (handles all entity kinds)
+ const allKinds = ["file", "class", "object", "trait", "interface", "module", "function", "method"];
+ return resolveEntity(client, target, allKinds, opts);
+}
+
+/**
+ * Search the graph for a file entity matching the target path or filename.
+ * Tries exact path match first, then basename match.
+ */
+async function tryFileGraphMatch(
+ client: IxClient,
+ target: string,
+): Promise<ResolvedEntity | null> {
+ const basename = path.basename(target);
+
+ // Search for file entities matching the basename
+ const nodes = await client.search(basename, { limit: 20, kind: "file", nameOnly: true });
+
+ // Filter to actual matches
+ const targetLower = target.toLowerCase();
+ const basenameLower = basename.toLowerCase();
+ const basenameNoExt = basename.replace(/\.[^.]+$/, "").toLowerCase();
+
+ const matches: Array<{ node: any; quality: number }> = [];
+ for (const n of nodes as any[]) {
+ const name = (n.name || "").toLowerCase();
+ const uri = (n.provenance?.sourceUri ?? n.provenance?.source_uri ?? "").toLowerCase();
+
+ // Exact path match (best)
+ if (uri.endsWith(targetLower) || uri === targetLower) {
+ matches.push({ node: n, quality: 0 });
+ }
+ // Exact filename match
+ else if (name === basenameLower) {
+ matches.push({ node: n, quality: 1 });
+ }
+ // Bare name match (no extension)
+ else if (name.replace(/\.[^.]+$/, "") === basenameNoExt) {
+ matches.push({ node: n, quality: 2 });
+ }
+ }
+
+ if (matches.length === 0) return null;
+
+ // Sort by quality then pick best
+ matches.sort((a, b) => a.quality - b.quality);
+
+ // If multiple matches at same quality, prefer path-matching target
+ const best = matches[0];
+ if (matches.length > 1 && matches[0].quality === matches[1].quality && target.includes("/")) {
+ // Disambiguate by path when user provided a path
+ const pathMatch = matches.find(m => {
+ const uri = (m.node.provenance?.sourceUri ?? m.node.provenance?.source_uri ?? "").toLowerCase();
+ return uri.endsWith(targetLower);
+ });
+ if (pathMatch) {
+ return nodeToResolved(pathMatch.node, pathMatch.node.name, "exact");
+ }
+ }
+
+ return nodeToResolved(best.node, best.node.name || basename, best.quality === 0 ? "exact" : "scored");
+}