Skip to content

armgit / Ix

Public Imported from GitHub
0

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

feat: extract Pro commands into @ix/pro, add dynamic CLI help

Tanner Kocher76ab10d89c5d
diff --git a/ix-cli/package.json b/ix-cli/package.json
index b498889f..c5ee530d 100644
--- a/ix-cli/package.json
+++ b/ix-cli/package.json
@@ -4,6 +4,11 @@
"type": "module",
"description": "Ix Memory — Persistent Memory for LLM Systems",
"main": "dist/index.js",
+ "exports": {
+ ".": "./dist/index.js",
+ "./client/*": "./dist/client/*",
+ "./cli/*": "./dist/cli/*"
+ },
"bin": {
"ix": "dist/cli/main.js"
},
diff --git a/ix-cli/src/cli/__tests__/briefing.test.ts b/ix-cli/src/cli/__tests__/briefing.test.ts
deleted file mode 100644
index 877387b2..00000000
--- a/ix-cli/src/cli/__tests__/briefing.test.ts
+++ /dev/null
@@ -1,141 +0,0 @@
-import { describe, it, expect, vi } from "vitest";
-import { buildBriefing, type BriefingResult } from "../commands/briefing.js";
-
-function mockClient(overrides: Partial<Record<string, any>> = {}): any {
- return {
- health: vi.fn().mockResolvedValue({ status: "ok" }),
- listByKind: vi.fn().mockImplementation((kind: string) => {
- if (overrides[`listByKind:${kind}`]) return Promise.resolve(overrides[`listByKind:${kind}`]);
- return Promise.resolve([]);
- }),
- listDecisions: vi.fn().mockResolvedValue(overrides.decisions ?? []),
- listPatches: vi.fn().mockResolvedValue(overrides.patches ?? []),
- conflicts: vi.fn().mockResolvedValue(overrides.conflicts ?? []),
- expand: vi.fn().mockResolvedValue({ nodes: [], edges: [] }),
- entity: vi.fn().mockResolvedValue({ node: { attrs: {} }, claims: [], edges: [] }),
- ...overrides.clientOverrides,
- };
-}
-
-describe("buildBriefing", () => {
- it("returns all expected top-level keys", async () => {
- const client = mockClient();
- const result = await buildBriefing(client);
- expect(result).toHaveProperty("lastIngestAt");
- expect(result).toHaveProperty("revision");
- expect(result).toHaveProperty("activeGoals");
- expect(result).toHaveProperty("activePlans");
- expect(result).toHaveProperty("openBugs");
- expect(result).toHaveProperty("recentDecisions");
- expect(result).toHaveProperty("recentChanges");
- expect(result).toHaveProperty("conflicts");
- expect(result).toHaveProperty("diagnostics");
- });
-
- it("produces valid output with empty state (no crashes)", async () => {
- const client = mockClient();
- const result = await buildBriefing(client);
- expect(result.activeGoals).toEqual([]);
- expect(result.activePlans).toEqual([]);
- expect(result.openBugs).toEqual([]);
- expect(result.recentDecisions).toEqual([]);
- expect(result.recentChanges).toEqual([]);
- expect(result.conflicts).toEqual([]);
- expect(result.diagnostics).toEqual([]);
- expect(result.lastIngestAt).toBeNull();
- expect(result.revision).toBeNull();
- });
-
- it("maps goals from intent nodes", async () => {
- const client = mockClient({
- "listByKind:intent": [
- { id: "g1", name: "Support GitHub", attrs: {} },
- { id: "g2", name: "Scale to 100k", attrs: {} },
- ],
- });
- const result = await buildBriefing(client);
- expect(result.activeGoals).toHaveLength(2);
- expect(result.activeGoals[0]).toEqual({ id: "g1", name: "Support GitHub" });
- expect(result.activeGoals[1]).toEqual({ id: "g2", name: "Scale to 100k" });
- });
-
- it("filters bugs to open/investigating only", async () => {
- const client = mockClient({
- "listByKind:bug": [
- { id: "b1", name: "Login crash", attrs: { status: "open", severity: "high" } },
- { id: "b2", name: "Fixed bug", attrs: { status: "resolved", severity: "low" } },
- { id: "b3", name: "Under review", attrs: { status: "investigating", severity: "medium" } },
- ],
- });
- const result = await buildBriefing(client);
- expect(result.openBugs).toHaveLength(2);
- expect(result.openBugs.map(b => b.id)).toEqual(["b1", "b3"]);
- });
-
- it("extracts revision and lastIngestAt from patches", async () => {
- const client = mockClient({
- patches: [
- { patch_id: "p1", rev: 42, intent: "Ingest src", timestamp: "2026-03-08T10:00:00Z" },
- ],
- });
- const result = await buildBriefing(client);
- expect(result.revision).toBe(42);
- expect(result.lastIngestAt).toBe("2026-03-08T10:00:00Z");
- });
-
- it("maps recent decisions", async () => {
- const client = mockClient({
- decisions: [
- { id: "d1", name: "Use CONTAINS", attrs: { rationale: "Normalize edges" } },
- ],
- });
- const result = await buildBriefing(client);
- expect(result.recentDecisions).toHaveLength(1);
- expect(result.recentDecisions[0].name).toBe("Use CONTAINS");
- expect(result.recentDecisions[0].rationale).toBe("Normalize edges");
- });
-
- it("includes plan task summary with nextTask", async () => {
- const planNode = { id: "plan-1", name: "Fix Auth", kind: "plan", attrs: {} };
- const taskNode = { id: "task-1", name: "Update token", kind: "task", attrs: { status: "pending" } };
-
- const client = mockClient({
- "listByKind:plan": [planNode],
- clientOverrides: {
- expand: vi.fn().mockImplementation((id: string, opts: any) => {
- if (id === "plan-1" && opts.predicates?.includes("PLAN_HAS_TASK")) {
- return Promise.resolve({ nodes: [taskNode], edges: [] });
- }
- return Promise.resolve({ nodes: [], edges: [] });
- }),
- entity: vi.fn().mockResolvedValue({
- node: { attrs: { status: "pending" } },
- claims: [],
- edges: [],
- }),
- },
- });
-
- const result = await buildBriefing(client);
- expect(result.activePlans).toHaveLength(1);
- expect(result.activePlans[0].name).toBe("Fix Auth");
- expect(result.activePlans[0].taskSummary.total).toBe(1);
- expect(result.activePlans[0].taskSummary.pending).toBe(1);
- expect(result.activePlans[0].nextTask).toBe("Update token");
- });
-
- it("records diagnostics when endpoints fail", async () => {
- const client = mockClient({
- clientOverrides: {
- health: vi.fn().mockRejectedValue(new Error("unreachable")),
- listByKind: vi.fn().mockRejectedValue(new Error("down")),
- listDecisions: vi.fn().mockRejectedValue(new Error("down")),
- listPatches: vi.fn().mockRejectedValue(new Error("down")),
- conflicts: vi.fn().mockRejectedValue(new Error("down")),
- },
- });
- const result = await buildBriefing(client);
- expect(result.diagnostics.length).toBeGreaterThan(0);
- expect(result.diagnostics).toContain("health endpoint unreachable");
- });
-});
diff --git a/ix-cli/src/cli/__tests__/bug-patch.test.ts b/ix-cli/src/cli/__tests__/bug-patch.test.ts
deleted file mode 100644
index 9e61d2ba..00000000
--- a/ix-cli/src/cli/__tests__/bug-patch.test.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { buildBugPatch, buildBugUpdatePatch } from "../commands/bug.js";
-
-describe("buildBugPatch", () => {
- it("creates a Bug node with correct kind and attrs", () => {
- const patch = buildBugPatch("Login fails", "Users cannot log in", "high");
- expect(patch.ops[0].type).toBe("UpsertNode");
- expect(patch.ops[0].kind).toBe("bug");
- expect(patch.ops[0].name).toBe("Login fails");
- const attrs = patch.ops[0].attrs as Record<string, unknown>;
- expect(attrs.description).toBe("Users cannot log in");
- expect(attrs.status).toBe("open");
- expect(attrs.severity).toBe("high");
- expect(attrs.created_at).toBeDefined();
- });
-
- it("defaults severity to medium", () => {
- const patch = buildBugPatch("Minor issue", "Something small");
- const attrs = patch.ops[0].attrs as Record<string, unknown>;
- expect(attrs.severity).toBe("medium");
- });
-
- it("creates BUG_AFFECTS edges when affects provided", () => {
- const patch = buildBugPatch("Crash bug", "Crashes on load", "critical", {
- affects: [
- { id: "entity-1", kind: "class", name: "AuthService" },
- { id: "entity-2", kind: "function", name: "verifyToken" },
- ],
- });
- expect(patch.ops.length).toBe(3); // 1 UpsertNode + 2 UpsertEdge
- expect(patch.ops[1].type).toBe("UpsertEdge");
- expect(patch.ops[1].predicate).toBe("BUG_AFFECTS");
- expect(patch.ops[1].src).toBe(patch.ops[0].id);
- expect(patch.ops[1].dst).toBe("entity-1");
- expect(patch.ops[2].predicate).toBe("BUG_AFFECTS");
- expect(patch.ops[2].dst).toBe("entity-2");
- });
-
- it("creates no edges when affects is empty", () => {
- const patch = buildBugPatch("Standalone bug", "No links");
- expect(patch.ops.length).toBe(1);
- });
-
- it("uses sourceType cli", () => {
- const patch = buildBugPatch("Test bug", "desc");
- expect(patch.source.sourceType).toBe("cli");
- });
-});
-
-describe("buildBugUpdatePatch", () => {
- it("creates an AssertClaim for status change", () => {
- const patch = buildBugUpdatePatch("bug-id-123", "investigating");
- expect(patch.ops.length).toBe(1);
- expect(patch.ops[0].type).toBe("AssertClaim");
- expect(patch.ops[0].field).toBe("status");
- expect(patch.ops[0].value).toBe("investigating");
- });
-
- it("uses sourceType cli", () => {
- const patch = buildBugUpdatePatch("bug-id-123", "resolved");
- expect(patch.source.sourceType).toBe("cli");
- });
-});
diff --git a/ix-cli/src/cli/__tests__/decide-linking.test.ts b/ix-cli/src/cli/__tests__/decide-linking.test.ts
deleted file mode 100644
index b570a041..00000000
--- a/ix-cli/src/cli/__tests__/decide-linking.test.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { buildDecisionPatch } from "../commands/decide.js";
-
-describe("buildDecisionPatch", () => {
- it("creates a patch with DECISION_AFFECTS edges", () => {
- const patch = buildDecisionPatch(
- "Use client-side patch",
- "Avoid server coupling",
- {
- affects: [
- { id: "entity-1", kind: "class", name: "IngestionService" },
- { id: "entity-2", kind: "class", name: "IxClient" },
- ],
- }
- );
- expect(patch.ops.length).toBe(3); // 1 UpsertNode + 2 UpsertEdge
- expect(patch.ops[0].type).toBe("UpsertNode");
- expect(patch.ops[0].kind).toBe("decision");
- expect(patch.ops[1].type).toBe("UpsertEdge");
- expect(patch.ops[1].predicate).toBe("DECISION_AFFECTS");
- expect(patch.ops[2].predicate).toBe("DECISION_AFFECTS");
- });
-
- it("creates DECISION_SUPERSEDES edge when supersedes is provided", () => {
- const patch = buildDecisionPatch("New approach", "Better", {
- supersedes: "old-decision-id",
- });
- expect(patch.ops.length).toBe(2); // 1 UpsertNode + 1 UpsertEdge
- expect(patch.ops[1].predicate).toBe("DECISION_SUPERSEDES");
- expect(patch.ops[1].src).toBe(patch.ops[0].id); // new decision → old
- expect(patch.ops[1].dst).toBe("old-decision-id");
- });
-
- it("creates DECISION_CHILD edge when parent is provided", () => {
- const patch = buildDecisionPatch("Sub-decision", "Detail", {
- parent: "parent-decision-id",
- });
- expect(patch.ops.length).toBe(2);
- expect(patch.ops[1].predicate).toBe("DECISION_CHILD");
- expect(patch.ops[1].src).toBe("parent-decision-id"); // parent → child
- expect(patch.ops[1].dst).toBe(patch.ops[0].id);
- });
-
- it("creates DECISION_RESPONDS_TO_BUG edge when respondsTo is provided", () => {
- const patch = buildDecisionPatch("Fix auth flow", "JWT is better", {
- respondsTo: "bug-id-999",
- });
- expect(patch.ops.length).toBe(2); // 1 UpsertNode + 1 UpsertEdge
- expect(patch.ops[1].predicate).toBe("DECISION_RESPONDS_TO_BUG");
- expect(patch.ops[1].src).toBe(patch.ops[0].id); // decision → bug
- expect(patch.ops[1].dst).toBe("bug-id-999");
- });
-
- it("omits DECISION_RESPONDS_TO_BUG edge when respondsTo is not provided", () => {
- const patch = buildDecisionPatch("Simple decision", "Reason");
- expect(patch.ops.length).toBe(1); // just the node
- });
-
- it("uses sourceType decision", () => {
- const patch = buildDecisionPatch("Test", "Reason");
- expect(patch.source.sourceType).toBe("decision");
- });
-});
diff --git a/ix-cli/src/cli/__tests__/goal-truth-separation.test.ts b/ix-cli/src/cli/__tests__/goal-truth-separation.test.ts
deleted file mode 100644
index 8ec40385..00000000
--- a/ix-cli/src/cli/__tests__/goal-truth-separation.test.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import { describe, it, expect } from "vitest";
-import * as fs from "node:fs";
-import * as path from "node:path";
-
-/**
- * Verify that goals and truths are semantically separated:
- * - api.ts has separate listGoals/createGoal and listTruth/createTruth methods
- * - goal.ts calls listGoals, not listTruth
- * - truth.ts still calls listTruth
- */
-
-const apiTsPath = path.resolve(__dirname, "../../client/api.ts");
-const apiContent = fs.readFileSync(apiTsPath, "utf-8");
-
-const goalTsPath = path.resolve(__dirname, "../commands/goal.ts");
-const goalContent = fs.readFileSync(goalTsPath, "utf-8");
-
-const goalsTsPath = path.resolve(__dirname, "../commands/goals.ts");
-const goalsContent = fs.readFileSync(goalsTsPath, "utf-8");
-
-const truthTsPath = path.resolve(__dirname, "../commands/truth.ts");
-const truthContent = fs.readFileSync(truthTsPath, "utf-8");
-
-const planTsPath = path.resolve(__dirname, "../commands/plan.ts");
-const planContent = fs.readFileSync(planTsPath, "utf-8");
-
-describe("api.ts has separate goal and truth methods", () => {
- it("has listGoals method", () => {
- expect(apiContent).toContain("async listGoals()");
- });
-
- it("has createGoal method", () => {
- expect(apiContent).toContain("async createGoal(");
- });
-
- it("listGoals calls /v1/truth endpoint (goals are stored as truth)", () => {
- expect(apiContent).toContain('"/v1/truth"');
- });
-
- it("still has listTruth method", () => {
- expect(apiContent).toContain("async listTruth()");
- });
-
- it("still has createTruth method", () => {
- expect(apiContent).toContain("async createTruth(");
- });
-});
-
-describe("goal.ts uses goal endpoints, not truth", () => {
- it("goal.ts calls listGoals", () => {
- expect(goalContent).toContain("client.listGoals()");
- });
-
- it("goal.ts calls createGoal", () => {
- expect(goalContent).toContain("client.createGoal(");
- });
-
- it("goal.ts does NOT call listTruth", () => {
- expect(goalContent).not.toContain("client.listTruth()");
- });
-
- it("goal.ts does NOT call createTruth", () => {
- expect(goalContent).not.toContain("client.createTruth(");
- });
-
- it("goal.ts description does not mention truth alias", () => {
- expect(goalContent).not.toContain("aliases for ix truth");
- });
-});
-
-describe("goals.ts uses goal endpoints", () => {
- it("goals.ts calls listGoals", () => {
- expect(goalsContent).toContain("client.listGoals()");
- });
-
- it("goals.ts does NOT call listTruth", () => {
- expect(goalsContent).not.toContain("client.listTruth()");
- });
-});
-
-describe("truth.ts still uses truth endpoints", () => {
- it("truth.ts calls listTruth", () => {
- expect(truthContent).toContain("client.listTruth()");
- });
-
- it("truth.ts calls createTruth", () => {
- expect(truthContent).toContain("client.createTruth(");
- });
-});
-
-describe("plan.ts uses goal endpoints for goal resolution", () => {
- it("plan create resolves goals via listGoals", () => {
- expect(planContent).toContain("client.listGoals()");
- });
-
- it("plan create does NOT use listTruth for goal resolution", () => {
- expect(planContent).not.toContain("client.listTruth()");
- });
-});
diff --git a/ix-cli/src/cli/__tests__/help-coverage.test.ts b/ix-cli/src/cli/__tests__/help-coverage.test.ts
index 41ab6c60..2c4d053c 100644
--- a/ix-cli/src/cli/__tests__/help-coverage.test.ts
+++ b/ix-cli/src/cli/__tests__/help-coverage.test.ts
@@ -1,40 +1,51 @@
import { describe, it, expect } from "vitest";
-import * as fs from "node:fs";
-import * as path from "node:path";
+import { buildHelpText } from "../help-text.js";
/**
- * Verify that HELP_HEADER in main.ts mentions all core commands.
+ * Verify that buildHelpText output mentions all core commands.
* This prevents regression where new commands become invisible.
*/
-const mainTsPath = path.resolve(__dirname, "../main.ts");
-const mainTsContent = fs.readFileSync(mainTsPath, "utf-8");
-
-// Extract the HELP_HEADER string from main.ts
-const headerMatch = mainTsContent.match(/const HELP_HEADER = `([\s\S]*?)`;/);
-const HELP_HEADER = headerMatch?.[1] ?? "";
+const ossHelp = buildHelpText();
const REQUIRED_COMMANDS = [
- "read", "search", "locate", "contains", "callers", "callees",
- "imports", "entity", "status", "stats", "doctor", "history", "diff",
- "briefing", "overview", "impact", "rank", "inventory",
- "plan", "task", "tasks", "workflow", "bug", "bugs", "decide", "goal", "goals",
- "ingest", "truth", "text", "explain",
+ "init", "search", "locate", "explain", "impact", "overview", "watch",
+ "read", "inventory", "rank", "history", "diff",
+ "ingest", "status", "stats", "doctor", "docker",
];
describe("help coverage", () => {
- it("HELP_HEADER is non-empty", () => {
- expect(HELP_HEADER.length).toBeGreaterThan(100);
+ it("OSS help is non-empty", () => {
+ expect(ossHelp.length).toBeGreaterThan(100);
});
- it("HELP_HEADER mentions all core commands", () => {
+ it("OSS help mentions all core commands", () => {
const missing: string[] = [];
for (const cmd of REQUIRED_COMMANDS) {
- // Match command name at start of a line (with leading whitespace)
- if (!HELP_HEADER.includes(cmd)) {
+ if (!ossHelp.includes(cmd)) {
missing.push(cmd);
}
}
expect(missing).toEqual([]);
});
+
+ it("OSS help uses new branding", () => {
+ expect(ossHelp).toContain("ix — Code Memory CLI");
+ expect(ossHelp).not.toContain("Persistent Memory for LLM Systems");
+ });
+
+ it("OSS help does not show a Pro section", () => {
+ expect(ossHelp).not.toContain("Pro:");
+ });
+
+ it("Pro help includes Pro section when commands provided", () => {
+ const proHelp = buildHelpText([
+ { name: "plan", desc: "Manage plans" },
+ { name: "goal", desc: "Manage goals" },
+ ]);
+ expect(proHelp).toContain("Pro:");
+ expect(proHelp).toContain("plan");
+ expect(proHelp).toContain("Manage plans");
+ expect(proHelp).toContain("goal");
+ });
});
diff --git a/ix-cli/src/cli/__tests__/help-topics.test.ts b/ix-cli/src/cli/__tests__/help-topics.test.ts
index 9ec7010c..05c2f114 100644
--- a/ix-cli/src/cli/__tests__/help-topics.test.ts
+++ b/ix-cli/src/cli/__tests__/help-topics.test.ts
@@ -12,13 +12,15 @@ const workflowsContent = fs.readFileSync(workflowsTsPath, "utf-8");
describe("help topic routing", () => {
it("help command accepts an optional [topic] argument", () => {
- // The help command should be registered as "help [topic]" not "help"
- // so it can handle arbitrary topic names like task, plan, bug, goal
expect(workflowsContent).toContain('command("help [topic]")');
});
+ it("no-topic path uses program.helpInformation() (dynamic, bypasses Commander)", () => {
+ expect(workflowsContent).toContain("program.helpInformation()");
+ expect(workflowsContent).not.toContain('import { HELP_TEXT }');
+ });
+
it("help action looks up commands on the program", () => {
- // The action should delegate to program.commands for arbitrary topics
expect(workflowsContent).toContain("program.commands.find");
expect(workflowsContent).toContain("outputHelp");
});
@@ -28,6 +30,11 @@ describe("help topic routing", () => {
expect(workflowsContent).toContain("WORKFLOWS_TEXT");
});
+ it("help action handles the advanced topic directly", () => {
+ expect(workflowsContent).toContain('topic === "advanced"');
+ expect(workflowsContent).toContain("ADVANCED_TEXT");
+ });
+
it("help action handles unknown topics with an error", () => {
expect(workflowsContent).toContain("Unknown help topic");
});
diff --git a/ix-cli/src/cli/__tests__/name-resolution.test.ts b/ix-cli/src/cli/__tests__/name-resolution.test.ts
deleted file mode 100644
index de7ce97b..00000000
--- a/ix-cli/src/cli/__tests__/name-resolution.test.ts
+++ /dev/null
@@ -1,162 +0,0 @@
-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 listGoals", () => {
- expect(planContent).toContain("client.resolvePrefix(opts.goal)");
- expect(planContent).toContain("client.listGoals()");
- });
-
- 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 listGoals 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 listGoals", () => {
- expect(goalContent).toContain("client.resolvePrefix(ref)");
- expect(goalContent).toContain("client.listGoals()");
- });
-
- 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.listGoals()");
- 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__/plan-patch.test.ts b/ix-cli/src/cli/__tests__/plan-patch.test.ts
deleted file mode 100644
index 9c237845..00000000
--- a/ix-cli/src/cli/__tests__/plan-patch.test.ts
+++ /dev/null
@@ -1,149 +0,0 @@
-import { describe, it, expect } from "vitest";
-import { buildPlanPatch, buildTaskPatch, buildTaskUpdatePatch, isValidWorkflow } from "../commands/plan.js";
-
-describe("buildPlanPatch", () => {
- it("creates a Plan node and GOAL_HAS_PLAN edge", () => {
- const patch = buildPlanPatch("GitHub Ingestion", "goal-id-123");
- expect(patch.ops.length).toBe(2);
- expect(patch.ops[0].type).toBe("UpsertNode");
- expect(patch.ops[0].kind).toBe("plan");
- expect(patch.ops[0].name).toBe("GitHub Ingestion");
- expect(patch.ops[1].type).toBe("UpsertEdge");
- expect(patch.ops[1].predicate).toBe("GOAL_HAS_PLAN");
- expect(patch.ops[1].src).toBe("goal-id-123");
- expect(patch.ops[1].dst).toBe(patch.ops[0].id);
- });
-
- it("adds RESPONDS_TO edge when respondsTo is provided", () => {
- const patch = buildPlanPatch("Fix plan", "goal-id-123", "bug-id-456");
- expect(patch.ops.length).toBe(3); // node + GOAL_HAS_PLAN + RESPONDS_TO
- expect(patch.ops[2].type).toBe("UpsertEdge");
- expect(patch.ops[2].predicate).toBe("RESPONDS_TO");
- expect(patch.ops[2].src).toBe(patch.ops[0].id); // plan → bug
- expect(patch.ops[2].dst).toBe("bug-id-456");
- });
-
- it("omits RESPONDS_TO edge when respondsTo is not provided", () => {
- const patch = buildPlanPatch("Simple plan", "goal-id-123");
- expect(patch.ops.length).toBe(2);
- });
-
- it("uses sourceType cli", () => {
- const patch = buildPlanPatch("Plan", "goal-id");
- expect(patch.source.sourceType).toBe("cli");
- });
-});
-
-describe("buildTaskPatch", () => {
- it("creates a Task node and PLAN_HAS_TASK edge", () => {
- const patch = buildTaskPatch("Fetch GitHub API", { planId: "plan-123" });
- expect(patch.ops[0].type).toBe("UpsertNode");
- expect(patch.ops[0].kind).toBe("task");
- expect((patch.ops[0].attrs as Record<string, unknown>).status).toBe("pending");
- expect(patch.ops[1].predicate).toBe("PLAN_HAS_TASK");
- });
-
- it("adds DEPENDS_ON edge when dependsOn is provided", () => {
- const patch = buildTaskPatch("Transform layer", {
- planId: "plan-123",
- dependsOn: "task-abc",
- });
- expect(patch.ops.length).toBe(3); // node + PLAN_HAS_TASK + DEPENDS_ON
- expect(patch.ops[2].predicate).toBe("DEPENDS_ON");
- expect(patch.ops[2].src).toBe(patch.ops[0].id); // this task depends on...
- expect(patch.ops[2].dst).toBe("task-abc");
- });
-
- it("adds TASK_AFFECTS edges when affects is provided", () => {
- const patch = buildTaskPatch("Wire up service", {
- planId: "plan-123",
- affects: [
- { id: "entity-1", kind: "class", name: "IngestionService" },
- ],
- });
- expect(patch.ops.length).toBe(3); // node + PLAN_HAS_TASK + TASK_AFFECTS
- expect(patch.ops[2].predicate).toBe("TASK_AFFECTS");
- });
-
- it("stores workflow array in attrs when provided", () => {
- const patch = buildTaskPatch("Investigate auth", {
- planId: "plan-123",
- workflow: ["ix overview AuthService", "ix explain verifyToken"],
- });
- const attrs = patch.ops[0].attrs as Record<string, unknown>;
- expect(attrs.workflow).toEqual(["ix overview AuthService", "ix explain verifyToken"]);
- });
-
- it("omits workflow from attrs when not provided", () => {
- const patch = buildTaskPatch("Simple task", { planId: "plan-123" });
- const attrs = patch.ops[0].attrs as Record<string, unknown>;
- expect(attrs).not.toHaveProperty("workflow");
- });
-
- it("stores staged workflow object in attrs when provided", () => {
- const staged = { discover: ["ix overview Auth"], implement: ["ix read Auth"], validate: ["ix callers Auth"] };
- const patch = buildTaskPatch("Staged task", {
- planId: "plan-123",
- workflow: staged,
- });
- const attrs = patch.ops[0].attrs as Record<string, unknown>;
- expect(attrs.workflow).toEqual(staged);
- });
-
- it("adds TASK_RESOLVES_BUG edge when resolves is provided", () => {
- const patch = buildTaskPatch("Fix crash", {
- planId: "plan-123",
- resolves: "bug-id-789",
- });
- const resolveEdge = patch.ops.find((op: any) => op.predicate === "TASK_RESOLVES_BUG");
- expect(resolveEdge).toBeDefined();
- expect(resolveEdge!.src).toBe(patch.ops[0].id);
- expect(resolveEdge!.dst).toBe("bug-id-789");
- });
-
- it("omits TASK_RESOLVES_BUG edge when resolves is not provided", () => {
- const patch = buildTaskPatch("Normal task", { planId: "plan-123" });
- const resolveEdge = patch.ops.find((op: any) => op.predicate === "TASK_RESOLVES_BUG");
- expect(resolveEdge).toBeUndefined();
- });
-
- it("uses sourceType cli", () => {
- const patch = buildTaskPatch("Task", { planId: "plan-123" });
- expect(patch.source.sourceType).toBe("cli");
- });
-});
-
-describe("isValidWorkflow", () => {
- it("accepts flat string array", () => {
- expect(isValidWorkflow(["ix overview Auth"])).toBe(true);
- });
-
- it("accepts staged object with valid keys", () => {
- expect(isValidWorkflow({ discover: ["cmd1"], implement: ["cmd2"] })).toBe(true);
- });
-
- it("rejects staged object with unknown keys", () => {
- expect(isValidWorkflow({ discover: ["cmd1"], invalid: ["cmd2"] })).toBe(false);
- });
-
- it("rejects non-object/array values", () => {
- expect(isValidWorkflow("string")).toBe(false);
- expect(isValidWorkflow(42)).toBe(false);
- expect(isValidWorkflow(null)).toBe(false);
- });
-});
-
-describe("buildTaskUpdatePatch", () => {
- it("creates an AssertClaim for status change", () => {
- const patch = buildTaskUpdatePatch("task-id-123", "done");
- expect(patch.ops.length).toBe(1);
- expect(patch.ops[0].type).toBe("AssertClaim");
- expect(patch.ops[0].field).toBe("status");
- expect(patch.ops[0].value).toBe("done");
- });
-
- it("uses sourceType cli", () => {
- const patch = buildTaskUpdatePatch("task-id-123", "done");
- expect(patch.source.sourceType).toBe("cli");
- });
-});
diff --git a/ix-cli/src/cli/__tests__/task-status.test.ts b/ix-cli/src/cli/__tests__/task-status.test.ts
deleted file mode 100644
index df5b4225..00000000
--- a/ix-cli/src/cli/__tests__/task-status.test.ts
+++ /dev/null
@@ -1,131 +0,0 @@
-import { describe, it, expect } from "vitest";
-import * as fs from "node:fs";
-import * as path from "node:path";
-import { getTaskStatus } from "../task-utils.js";
-
-/**
- * Verify task status reading — unified getTaskStatus function + source integration.
- */
-
-const planTsPath = path.resolve(__dirname, "../commands/plan.ts");
-const planContent = fs.readFileSync(planTsPath, "utf-8");
-
-const tasksTsPath = path.resolve(__dirname, "../commands/tasks.ts");
-const tasksContent = fs.readFileSync(tasksTsPath, "utf-8");
-
-// ── Unit tests for getTaskStatus ──────────────────────────────────
-
-describe("getTaskStatus", () => {
- it("returns status from claim with field='status'", () => {
- const detail = {
- node: { attrs: { status: "pending" } },
- claims: [{ field: "status", value: "done" }],
- edges: [],
- };
- expect(getTaskStatus(detail)).toBe("done");
- });
-
- it("returns status from claim with statement containing 'status'", () => {
- const detail = {
- node: { attrs: { status: "pending" } },
- claims: [{ statement: "task status update", value: "in_progress" }],
- edges: [],
- };
- expect(getTaskStatus(detail)).toBe("in_progress");
- });
-
- it("falls back to attrs.status when no claims match", () => {
- const detail = {
- node: { attrs: { status: "blocked" } },
- claims: [{ field: "workflow", value: {} }],
- edges: [],
- };
- expect(getTaskStatus(detail)).toBe("blocked");
- });
-
- it("falls back to attrs.status when claims array is empty", () => {
- const detail = {
- node: { attrs: { status: "in_progress" } },
- claims: [],
- edges: [],
- };
- expect(getTaskStatus(detail)).toBe("in_progress");
- });
-
- it("returns 'pending' when no claims and no attrs.status", () => {
- const detail = {
- node: { attrs: {} },
- claims: [],
- edges: [],
- };
- expect(getTaskStatus(detail)).toBe("pending");
- });
-
- it("ignores invalid claim values and falls back", () => {
- const detail = {
- node: { attrs: { status: "done" } },
- claims: [{ field: "status", value: "INVALID_STATUS" }],
- edges: [],
- };
- expect(getTaskStatus(detail)).toBe("done");
- });
-
- it("handles null claims gracefully", () => {
- const detail = {
- node: { attrs: { status: "abandoned" } },
- claims: null as any,
- edges: [],
- };
- expect(getTaskStatus(detail)).toBe("abandoned");
- });
-});
-
-// ── Source-reading: plan.ts and tasks.ts import getTaskStatus from task-utils ──
-
-describe("plan.ts uses shared getTaskStatus", () => {
- it("imports getTaskStatus from task-utils", () => {
- expect(planContent).toContain("getTaskStatus");
- expect(planContent).toContain('from "../task-utils.js"');
- });
-
- it("does not have local getTaskStatus function", () => {
- // Should NOT have a local function definition
- expect(planContent).not.toMatch(/^function getTaskStatus/m);
- });
-
- it("has --run-workflow option on task update", () => {
- expect(planContent).toContain("--run-workflow");
- });
-
- it("has --status as optional (not requiredOption)", () => {
- // Should use .option not .requiredOption for --status
- expect(planContent).toContain('.option("--status <status>"');
- });
-
- it("validates at least one of --status or --run-workflow", () => {
- expect(planContent).toContain("!opts.status && !opts.runWorkflow");
- });
-});
-
-describe("tasks.ts uses shared getTaskStatus", () => {
- it("imports getTaskStatus from task-utils", () => {
- expect(tasksContent).toContain("getTaskStatus");
- expect(tasksContent).toContain('from "../task-utils.js"');
- });
-
- it("does not define local STATUS_ICONS", () => {
- expect(tasksContent).not.toMatch(/^const STATUS_ICONS/m);
- });
-
- it("imports STATUS_ICONS from task-utils", () => {
- expect(tasksContent).toContain("STATUS_ICONS");
- });
-
- it("uses Promise.all for parallel entity fetches", () => {
- expect(tasksContent).toContain("Promise.all(");
- });
-
- it("imports getWorkflowState", () => {
- expect(tasksContent).toContain("getWorkflowState");
- });
-});
diff --git a/ix-cli/src/cli/__tests__/workflow-attach.test.ts b/ix-cli/src/cli/__tests__/workflow-attach.test.ts
deleted file mode 100644
index 95712432..00000000
--- a/ix-cli/src/cli/__tests__/workflow-attach.test.ts
+++ /dev/null
@@ -1,194 +0,0 @@
-import { describe, it, expect } from "vitest";
-import * as fs from "node:fs";
-import * as path from "node:path";
-import { buildWorkflowAttachPatch } from "../commands/workflow.js";
-import { extractWorkflow, isValidWorkflow, normalizeWorkflow } from "../task-utils.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 uses extractWorkflow", () => {
- const planTsPath = path.resolve(__dirname, "../commands/plan.ts");
- const planContent = fs.readFileSync(planTsPath, "utf-8");
-
- it("task show uses extractWorkflow for workflow retrieval", () => {
- expect(planContent).toContain("extractWorkflow");
- });
-
- it("plan.ts imports extractWorkflow from task-utils", () => {
- expect(planContent).toContain('from "../task-utils.js"');
- expect(planContent).toContain("extractWorkflow");
- });
-});
diff --git a/ix-cli/src/cli/__tests__/workflow-state.test.ts b/ix-cli/src/cli/__tests__/workflow-state.test.ts
deleted file mode 100644
index 18050fb0..00000000
--- a/ix-cli/src/cli/__tests__/workflow-state.test.ts
+++ /dev/null
@@ -1,156 +0,0 @@
-import { describe, it, expect } from "vitest";
-import * as fs from "node:fs";
-import * as path from "node:path";
-import { getWorkflowState, formatWorkflowStateCompact } from "../task-utils.js";
-
-/**
- * Verify workflow stage state tracking.
- */
-
-const planTsPath = path.resolve(__dirname, "../commands/plan.ts");
-const planContent = fs.readFileSync(planTsPath, "utf-8");
-
-const tasksTsPath = path.resolve(__dirname, "../commands/tasks.ts");
-const tasksContent = fs.readFileSync(tasksTsPath, "utf-8");
-
-// ── Unit tests for getWorkflowState ────────────────────────────────
-
-describe("getWorkflowState", () => {
- it("returns workflow state from claim with field='workflow_state'", () => {
- const detail = {
- node: { attrs: {} },
- claims: [{ field: "workflow_state", value: { discover: "done", implement: "running" } }],
- };
- const result = getWorkflowState(detail);
- expect(result).toEqual({ discover: "done", implement: "running" });
- });
-
- it("falls back to attrs.workflow_state when no claims", () => {
- const detail = {
- node: { attrs: { workflow_state: { discover: "done", validate: "pending" } } },
- claims: [],
- };
- const result = getWorkflowState(detail);
- expect(result).toEqual({ discover: "done", validate: "pending" });
- });
-
- it("returns null when neither claims nor attrs have workflow_state", () => {
- const detail = {
- node: { attrs: {} },
- claims: [],
- };
- expect(getWorkflowState(detail)).toBeNull();
- });
-
- it("validates stage status values", () => {
- const detail = {
- node: { attrs: {} },
- claims: [{ field: "workflow_state", value: { discover: "INVALID", implement: "done" } }],
- };
- const result = getWorkflowState(detail);
- // Only valid stage statuses are included
- expect(result).toEqual({ implement: "done" });
- });
-
- it("returns null for empty valid result", () => {
- const detail = {
- node: { attrs: {} },
- claims: [{ field: "workflow_state", value: { discover: "INVALID" } }],
- };
- expect(getWorkflowState(detail)).toBeNull();
- });
-
- it("handles all valid stage statuses", () => {
- const detail = {
- node: { attrs: {} },
- claims: [{ field: "workflow_state", value: {
- discover: "done",
- implement: "running",
- validate: "pending",
- } }],
- };
- const result = getWorkflowState(detail);
- expect(result).toEqual({ discover: "done", implement: "running", validate: "pending" });
- });
-
- it("handles 'failed' and 'skipped' statuses", () => {
- const detail = {
- node: { attrs: {} },
- claims: [{ field: "workflow_state", value: {
- discover: "failed",
- implement: "skipped",
- } }],
- };
- const result = getWorkflowState(detail);
- expect(result).toEqual({ discover: "failed", implement: "skipped" });
- });
-});
-
-// ── Source-reading: plan.ts has buildWorkflowStatePatch ──────────────
-
-describe("plan.ts workflow state integration", () => {
- it("has buildWorkflowStatePatch with field 'workflow_state'", () => {
- expect(planContent).toContain("buildWorkflowStatePatch");
- expect(planContent).toContain('field: "workflow_state"');
- });
-
- it("task show includes workflowState in JSON", () => {
- expect(planContent).toContain("workflowState");
- });
-
- it("imports getWorkflowState from task-utils", () => {
- expect(planContent).toContain("getWorkflowState");
- });
-});
-
-describe("tasks.ts workflow state integration", () => {
- it("imports getWorkflowState from task-utils", () => {
- expect(tasksContent).toContain("getWorkflowState");
- expect(tasksContent).toContain('from "../task-utils.js"');
- });
-});
-
-// ── Unit tests for formatWorkflowStateCompact ───────────────────────
-
-describe("formatWorkflowStateCompact", () => {
- it("formats all three stages", () => {
- const result = formatWorkflowStateCompact({
- discover: "done",
- implement: "running",
- validate: "pending",
- });
- // Format: [discover✓ implement… validate○]
- expect(result).toContain("discover");
- expect(result).toContain("implement");
- expect(result).toContain("validate");
- expect(result).toMatch(/^\[.*\]$/);
- });
-
- it("formats single stage", () => {
- const result = formatWorkflowStateCompact({ discover: "done" });
- expect(result).toContain("discover");
- expect(result).not.toContain("implement");
- });
-
- it("returns empty string for empty state", () => {
- const result = formatWorkflowStateCompact({});
- expect(result).toBe("");
- });
-
- it("uses stage name directly (not abbreviation)", () => {
- const result = formatWorkflowStateCompact({ discover: "done" });
- // Should contain full stage name, not just "D:"
- expect(result).toContain("discover");
- expect(result).not.toContain("D:");
- });
-
- it("uses … icon for running stage", () => {
- const result = formatWorkflowStateCompact({ implement: "running" });
- expect(result).toContain("\u2026"); // ellipsis
- });
-
- it("uses ✓ icon for done stage", () => {
- const result = formatWorkflowStateCompact({ discover: "done" });
- expect(result).toContain("\u2713"); // check mark
- });
-});
diff --git a/ix-cli/src/cli/commands/briefing.ts b/ix-cli/src/cli/commands/briefing.ts
deleted file mode 100644
index 6bb763a1..00000000
--- a/ix-cli/src/cli/commands/briefing.ts
+++ /dev/null
@@ -1,379 +0,0 @@
-import type { Command } from "commander";
-import { IxClient } from "../../client/api.js";
-import { getEndpoint } from "../config.js";
-import chalk from "chalk";
-
-interface BriefingGoal {
- id: string;
- name: string;
-}
-
-interface BriefingPlan {
- id: string;
- name: string;
- taskSummary: { total: number; done: number; pending: number };
- nextTask: string | null;
-}
-
-interface BriefingBug {
- id: string;
- title: string;
- severity: string;
- status: string;
-}
-
-interface BriefingDecision {
- id: string;
- name: string;
- rationale: string;
-}
-
-interface BriefingChange {
- patchId: string;
- intent: string | null;
- rev: number;
- timestamp: string | null;
-}
-
-interface BriefingFreshness {
- lastIngestAt: string | null;
- ageMinutes: number | null;
- stale: boolean;
-}
-
-export interface BriefingResult {
- lastIngestAt: string | null;
- revision: number | null;
- freshness: BriefingFreshness;
- goalCount: number;
- activeGoals: BriefingGoal[];
- activePlans: BriefingPlan[];
- openBugs: BriefingBug[];
- recentDecisions: BriefingDecision[];
- recentChanges: BriefingChange[];
- conflicts: unknown[];
- diagnostics: string[];
-}
-
-export async function buildBriefing(
- client: IxClient,
- opts: { activeOnly?: boolean } = {}
-): Promise<BriefingResult> {
- const diagnostics: string[] = [];
-
- // Fetch all data sources in parallel
- const [healthResult, goals, plans, bugs, decisions, patches, conflicts] =
- await Promise.all([
- client.health().catch(() => {
- diagnostics.push("health endpoint unreachable");
- return null;
- }),
- client.listByKind("intent", { limit: 50 }).catch(() => {
- diagnostics.push("could not list goals");
- return [] as any[];
- }),
- client.listByKind("plan", { limit: 50 }).catch(() => {
- diagnostics.push("could not list plans");
- return [] as any[];
- }),
- client.listByKind("bug", { limit: 50 }).catch(() => {
- diagnostics.push("could not list bugs");
- return [] as any[];
- }),
- client.listDecisions({ limit: 5 }).catch(() => {
- diagnostics.push("could not list decisions");
- return [] as any[];
- }),
- client.listPatches({ limit: 10 }).catch(() => {
- diagnostics.push("could not list patches");
- return [] as any[];
- }),
- client.conflicts().catch(() => {
- diagnostics.push("could not check conflicts");
- return [] as unknown[];
- }),
- ]);
-
- // Extract last ingest time and revision from patches
- let lastIngestAt: string | null = null;
- let revision: number | null = null;
- if (patches.length > 0) {
- const latest = patches[0] as any;
- lastIngestAt = latest.timestamp ?? null;
- revision = latest.rev ?? null;
- }
-
- // Compute freshness
- let ageMinutes: number | null = null;
- let stale = false;
- if (lastIngestAt) {
- const ingestDate = new Date(lastIngestAt);
- const now = new Date();
- ageMinutes = Math.round((now.getTime() - ingestDate.getTime()) / 60000);
- stale = ageMinutes > 60;
- }
- const freshness: BriefingFreshness = { lastIngestAt, ageMinutes, stale };
-
- // Map goals
- const allGoals: BriefingGoal[] = goals.map((g: any) => ({
- id: g.id,
- name: g.name ?? g.attrs?.statement ?? "(unnamed)",
- }));
- const goalCount = allGoals.length;
-
- // Map bugs — filter to open/investigating only
- const openBugs: BriefingBug[] = bugs
- .filter((b: any) => {
- const status = b.attrs?.status ?? "open";
- return status === "open" || status === "investigating";
- })
- .map((b: any) => ({
- id: b.id,
- title: b.name,
- severity: b.attrs?.severity ?? "medium",
- status: b.attrs?.status ?? "open",
- }));
-
- // Map decisions
- const recentDecisions: BriefingDecision[] = decisions.map((d: any) => ({
- id: d.id,
- name: d.name ?? d.title ?? "(unnamed)",
- rationale: d.attrs?.rationale ?? d.rationale ?? "",
- }));
-
- // Map patches/changes with timestamp
- const recentChanges: BriefingChange[] = patches.map((p: any) => ({
- patchId: p.patch_id ?? p.patchId ?? p.id,
- intent: p.intent ?? null,
- rev: p.rev ?? 0,
- timestamp: p.timestamp ?? null,
- }));
-
- // Enrich plans with task summaries (up to 5 plans)
- const activePlans: BriefingPlan[] = [];
- const plansToProcess = plans.slice(0, 5);
-
- // Track which plans have pending tasks (for activeOnly goal filtering)
- const plansWithPendingTasks = new Set<string>();
-
- for (const plan of plansToProcess) {
- try {
- const { nodes: taskNodes } = await client.expand(plan.id, {
- direction: "out",
- predicates: ["PLAN_HAS_TASK"],
- });
-
- const tasks = taskNodes.filter((n: any) => n.kind === "task");
- let doneCount = 0;
- let pendingCount = 0;
- let nextTask: string | null = null;
-
- // Get status for each task
- const doneIds = new Set<string>();
- const taskDetails: { id: string; name: string; status: string; dependsOn: string[] }[] = [];
-
- for (const t of tasks) {
- const detail = await client.entity(t.id);
- const statusClaim = detail.claims?.find(
- (c: any) => c.field === "status" || c.statement?.includes("status")
- );
- let status = "pending";
- if (statusClaim) {
- const val = (statusClaim as any).value ?? (statusClaim as any).statement;
- if (typeof val === "string") status = val;
- } else if (detail.node?.attrs?.status) {
- status = detail.node.attrs.status as string;
- }
-
- if (status === "done") {
- doneCount++;
- doneIds.add(t.id);
- } else if (status === "pending") {
- pendingCount++;
- }
-
- const { edges: depEdges } = await client.expand(t.id, {
- direction: "out",
- predicates: ["DEPENDS_ON"],
- });
- taskDetails.push({
- id: t.id,
- name: t.name,
- status,
- dependsOn: depEdges.map((e: any) => e.dst as string),
- });
- }
-
- if (pendingCount > 0) {
- plansWithPendingTasks.add(plan.id);
- }
-
- // Find next actionable
- const actionable = taskDetails.find(
- (t) =>
- t.status !== "done" &&
- t.status !== "abandoned" &&
- t.dependsOn.every((dep) => doneIds.has(dep))
- );
- if (actionable) nextTask = actionable.name;
-
- activePlans.push({
- id: plan.id,
- name: plan.name ?? "(unnamed)",
- taskSummary: { total: tasks.length, done: doneCount, pending: pendingCount },
- nextTask,
- });
- } catch {
- activePlans.push({
- id: plan.id,
- name: plan.name ?? "(unnamed)",
- taskSummary: { total: 0, done: 0, pending: 0 },
- nextTask: null,
- });
- }
- }
-
- // Filter goals if --active-only
- let activeGoals = allGoals;
- if (opts.activeOnly) {
- // For each goal (up to 20), check if it has at least one plan with pending tasks
- const goalsToCheck = allGoals.slice(0, 20);
- const activeGoalIds = new Set<string>();
-
- for (const goal of goalsToCheck) {
- try {
- const { nodes: goalPlans } = await client.expand(goal.id, {
- direction: "out",
- predicates: ["GOAL_HAS_PLAN"],
- });
- for (const gp of goalPlans) {
- if (plansWithPendingTasks.has(gp.id)) {
- activeGoalIds.add(goal.id);
- break;
- }
- }
- } catch {
- // If we can't expand, include it to be safe
- activeGoalIds.add(goal.id);
- }
- }
- activeGoals = allGoals.filter((g) => activeGoalIds.has(g.id));
- }
-
- return {
- lastIngestAt,
- revision,
- freshness,
- goalCount,
- activeGoals,
- activePlans,
- openBugs,
- recentDecisions,
- recentChanges,
- conflicts,
- diagnostics,
- };
-}
-
-export function registerBriefingCommand(program: Command): void {
- program
- .command("briefing")
- .description("Session-resume briefing — aggregated project status")
- .option("--active-only", "Only show goals with active plans (plans with pending tasks)")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (opts: { activeOnly?: boolean; format: string }) => {
- const client = new IxClient(getEndpoint());
- const briefing = await buildBriefing(client, { activeOnly: opts.activeOnly });
-
- if (opts.format === "json") {
- console.log(JSON.stringify(briefing, null, 2));
- } else {
- // Header
- console.log(chalk.bold("Ix Briefing"));
- if (briefing.revision !== null) {
- console.log(chalk.dim(` Revision: ${briefing.revision}`));
- }
- if (briefing.lastIngestAt) {
- console.log(chalk.dim(` Last ingest: ${briefing.lastIngestAt}`));
- }
-
- // Freshness warning
- if (briefing.freshness.stale) {
- const ageStr = briefing.freshness.ageMinutes! >= 60
- ? `${Math.round(briefing.freshness.ageMinutes! / 60)}h ago`
- : `${briefing.freshness.ageMinutes}m ago`;
- console.log(chalk.yellow(` \u26A0 Graph is stale (last ingest: ${ageStr})`));
- }
-
- // Goals
- if (briefing.activeGoals.length > 0) {
- const countLabel = briefing.goalCount !== briefing.activeGoals.length
- ? ` (${briefing.activeGoals.length} of ${briefing.goalCount})`
- : ` (${briefing.activeGoals.length})`;
- console.log(`\n${chalk.bold("Goals")}${countLabel}`);
- for (const g of briefing.activeGoals) {
- console.log(` ${chalk.cyan("\u25C6")} ${g.name}`);
- }
- }
-
- // Plans
- if (briefing.activePlans.length > 0) {
- console.log(`\n${chalk.bold("Plans")} (${briefing.activePlans.length})`);
- for (const p of briefing.activePlans) {
- const { done, total } = p.taskSummary;
- console.log(` ${chalk.cyan("\u25B8")} ${p.name} ${chalk.dim(`(${done}/${total} done)`)}`);
- if (p.nextTask) {
- console.log(` ${chalk.green("Next:")} ${p.nextTask}`);
- }
- }
- }
-
- // Bugs
- if (briefing.openBugs.length > 0) {
- console.log(`\n${chalk.bold("Open Bugs")} (${briefing.openBugs.length})`);
- for (const b of briefing.openBugs) {
- const sev = b.severity === "critical" || b.severity === "high"
- ? chalk.red(b.severity)
- : chalk.yellow(b.severity);
- console.log(` ${chalk.red("\u25CB")} ${b.title} ${chalk.dim(`[${sev}]`)}`);
- }
- }
-
- // Decisions
- if (briefing.recentDecisions.length > 0) {
- console.log(`\n${chalk.bold("Recent Decisions")} (${briefing.recentDecisions.length})`);
- for (const d of briefing.recentDecisions) {
- console.log(` ${chalk.magenta("\u25C7")} ${d.name}`);
- if (d.rationale) {
- console.log(` ${chalk.dim(d.rationale.slice(0, 80))}`);
- }
- }
- }
-
- // Changes
- if (briefing.recentChanges.length > 0) {
- console.log(`\n${chalk.bold("Recent Changes")} (${briefing.recentChanges.length})`);
- for (const c of briefing.recentChanges) {
- const label = c.intent ?? chalk.dim("(no intent)");
- console.log(` rev ${chalk.dim(String(c.rev))} ${label}`);
- }
- }
-
- // Conflicts
- if (briefing.conflicts.length > 0) {
- console.log(`\n${chalk.red.bold("Conflicts")} (${briefing.conflicts.length})`);
- for (const c of briefing.conflicts as any[]) {
- console.log(` ${chalk.red("\u26A0")} ${c.reason ?? JSON.stringify(c)}`);
- }
- }
-
- // Diagnostics
- if (briefing.diagnostics.length > 0) {
- console.log(`\n${chalk.yellow("Diagnostics:")}`);
- for (const d of briefing.diagnostics) {
- console.log(` ${chalk.yellow("!")} ${d}`);
- }
- }
- }
- });
-}
diff --git a/ix-cli/src/cli/commands/bug.ts b/ix-cli/src/cli/commands/bug.ts
deleted file mode 100644
index 01cb40ea..00000000
--- a/ix-cli/src/cli/commands/bug.ts
+++ /dev/null
@@ -1,242 +0,0 @@
-import type { Command } from "commander";
-import type { GraphPatchPayload, PatchOp } from "../../client/types.js";
-import { IxClient } from "../../client/api.js";
-import { getEndpoint } from "../config.js";
-import { deterministicId } from "../github/transform.js";
-import { resolveEntity } from "../resolve.js";
-import { stderr } from "../stderr.js";
-import chalk from "chalk";
-
-// ── Patch builders (exported for testing) ──────────────────────────
-
-function makeBugPatchEnvelope(ops: PatchOp[], intent?: string): GraphPatchPayload {
- return {
- patchId: deterministicId(`bug-patch-${Date.now()}-${Math.random()}`),
- actor: "ix-cli",
- timestamp: new Date().toISOString(),
- source: {
- uri: "ix-cli://bug",
- extractor: "ix-cli-bug",
- sourceType: "cli",
- },
- baseRev: 0,
- ops,
- replaces: [],
- intent,
- };
-}
-
-interface BugLinkOpts {
- affects?: { id: string; kind: string; name: string }[];
-}
-
-export function buildBugPatch(
- title: string,
- description: string,
- severity: string = "medium",
- linkOpts: BugLinkOpts = {}
-): GraphPatchPayload {
- const now = new Date().toISOString();
- const bugId = deterministicId(`bug:${title}:${now}`);
- const ops: PatchOp[] = [];
-
- ops.push({
- type: "UpsertNode",
- id: bugId,
- kind: "bug",
- name: title,
- attrs: { description, status: "open", severity, created_at: now },
- });
-
- if (linkOpts.affects) {
- for (const entity of linkOpts.affects) {
- ops.push({
- type: "UpsertEdge",
- id: deterministicId(`${bugId}:BUG_AFFECTS:${entity.id}`),
- src: bugId,
- dst: entity.id,
- predicate: "BUG_AFFECTS",
- attrs: {},
- });
- }
- }
-
- return makeBugPatchEnvelope(ops, `Create bug: ${title}`);
-}
-
-export function buildBugUpdatePatch(bugId: string, status: string): GraphPatchPayload {
- const ops: PatchOp[] = [
- {
- type: "AssertClaim",
- entityId: bugId,
- field: "status",
- value: status,
- confidence: 1.0,
- },
- ];
- return makeBugPatchEnvelope(ops, `Update bug ${bugId} status to ${status}`);
-}
-
-// ── CLI commands ───────────────────────────────────────────────────
-
-const VALID_STATUSES = ["open", "investigating", "resolved", "closed"];
-const VALID_SEVERITIES = ["low", "medium", "high", "critical"];
-
-const STATUS_ICONS: Record<string, string> = {
- open: "○",
- investigating: "◐",
- resolved: "●",
- closed: "✓",
-};
-
-export function registerBugCommand(program: Command): void {
- const bug = program
- .command("bug")
- .description("Manage bugs")
- .addHelpText(
- "after",
- `\nSubcommands:
- create <title> Create a new bug
- show <bugId> Show bug details
- update <bugId> Update a bug's status
-
-Examples:
- ix bug create "Auth crash" --severity high --affects AuthService
- ix bug show <bug-id> --format json
- ix bug update <bug-id> --status resolved`
- );
-
- bug
- .command("create <title>")
- .description("Create a new bug")
- .option("--description <text>", "Bug description", "")
- .option("--affects <entities>", "Comma-separated entity names to link (creates BUG_AFFECTS edges)")
- .option("--severity <level>", `Severity (${VALID_SEVERITIES.join("|")})`, "medium")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (title: string, opts: { description: string; affects?: string; severity: string; format: string }) => {
- if (!VALID_SEVERITIES.includes(opts.severity)) {
- stderr(`Invalid severity "${opts.severity}". Valid: ${VALID_SEVERITIES.join(", ")}`);
- process.exitCode = 1;
- return;
- }
-
- const client = new IxClient(getEndpoint());
- let resolvedAffects: { id: string; kind: string; name: string }[] | undefined;
-
- if (opts.affects) {
- const names = opts.affects.split(",").map(s => s.trim());
- resolvedAffects = [];
- for (const name of names) {
- const resolved = await resolveEntity(client, name, [
- "class", "module", "file", "function", "method", "trait", "object", "interface",
- ]);
- if (resolved) {
- resolvedAffects.push({ id: resolved.id, kind: resolved.kind, name: resolved.name });
- }
- }
- }
-
- const patch = buildBugPatch(title, opts.description, opts.severity, {
- affects: resolvedAffects,
- });
- const result = await client.commitPatch(patch);
- const bugId = patch.ops[0].id as string;
-
- if (opts.format === "json") {
- console.log(JSON.stringify({ bugId, rev: result.rev, status: result.status }, null, 2));
- } else {
- console.log(`Bug created: ${bugId} (rev ${result.rev})`);
- if (resolvedAffects?.length) {
- console.log(` Linked to: ${resolvedAffects.map(e => e.name).join(", ")}`);
- }
- }
- });
-
- bug
- .command("show <bugId>")
- .description("Show bug details")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (bugId: string, opts: { format: string }) => {
- const client = new IxClient(getEndpoint());
- const details = await client.entity(bugId);
- const node = details.node as any;
-
- // Expand BUG_AFFECTS and RESPONDS_TO edges
- const [affectsResult, respondsToResult] = await Promise.all([
- client.expand(bugId, { direction: "out", predicates: ["BUG_AFFECTS"] }),
- client.expand(bugId, { direction: "in", predicates: ["RESPONDS_TO"] }),
- ]);
-
- const affects = affectsResult.nodes.map((n: any) => ({
- id: n.id,
- kind: n.kind,
- name: n.name || n.attrs?.name || "(unnamed)",
- }));
-
- const plans = respondsToResult.nodes.map((n: any) => ({
- id: n.id,
- name: n.name || n.attrs?.name || "(unnamed)",
- }));
-
- // Get status from claims or attrs
- const statusClaim = details.claims?.find(
- (c: any) => c.field === "status" || c.statement?.includes("status")
- );
- const status = statusClaim
- ? ((statusClaim as any).value ?? (statusClaim as any).statement ?? "open")
- : (node.attrs?.status ?? "open");
-
- if (opts.format === "json") {
- console.log(JSON.stringify({
- bugId,
- title: node.name,
- description: node.attrs?.description ?? "",
- status,
- severity: node.attrs?.severity ?? "medium",
- created_at: node.attrs?.created_at ?? node.createdAt,
- affects,
- plans,
- }, null, 2));
- } else {
- console.log(`Bug: ${chalk.bold(node.name)}`);
- console.log(` Status: ${status}`);
- console.log(` Severity: ${node.attrs?.severity ?? "medium"}`);
- if (node.attrs?.description) {
- console.log(` ${chalk.dim(node.attrs.description)}`);
- }
- if (affects.length > 0) {
- console.log(`\nAffects:`);
- for (const a of affects) {
- console.log(` ${chalk.cyan(a.kind)} ${a.name}`);
- }
- }
- if (plans.length > 0) {
- console.log(`\nPlans responding:`);
- for (const p of plans) {
- console.log(` ${p.name} (${chalk.dim(p.id.slice(0, 8))})`);
- }
- }
- }
- });
-
- bug
- .command("update <bugId>")
- .description("Update a bug's status")
- .requiredOption("--status <status>", `Status (${VALID_STATUSES.join("|")})`)
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (bugId: string, opts: { status: string; format: string }) => {
- if (!VALID_STATUSES.includes(opts.status)) {
- stderr(`Invalid status "${opts.status}". Valid: ${VALID_STATUSES.join(", ")}`);
- process.exitCode = 1;
- return;
- }
- const client = new IxClient(getEndpoint());
- const patch = buildBugUpdatePatch(bugId, opts.status);
- const result = await client.commitPatch(patch);
- if (opts.format === "json") {
- console.log(JSON.stringify({ bugId, status: opts.status, rev: result.rev }, null, 2));
- } else {
- console.log(`Bug ${bugId.slice(0, 8)} updated to ${opts.status} (rev ${result.rev})`);
- }
- });
-}
diff --git a/ix-cli/src/cli/commands/bugs.ts b/ix-cli/src/cli/commands/bugs.ts
deleted file mode 100644
index c06bea78..00000000
--- a/ix-cli/src/cli/commands/bugs.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import type { Command } from "commander";
-import { IxClient } from "../../client/api.js";
-import { getEndpoint } from "../config.js";
-import { formatBugs } from "../format.js";
-
-export function registerBugsCommand(program: Command): void {
- program
- .command("bugs")
- .description("List all bugs")
- .option("--status <status>", "Filter by status (open|investigating|resolved|closed)")
- .option("--limit <n>", "Max results", "50")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (opts: { status?: string; limit: string; format: string }) => {
- const client = new IxClient(getEndpoint());
- let nodes = await client.listByKind("bug", { limit: parseInt(opts.limit, 10) });
-
- if (opts.status) {
- nodes = nodes.filter((n: any) => {
- const status = n.attrs?.status ?? "open";
- return status === opts.status;
- });
- }
-
- formatBugs(nodes, opts.format);
- });
-}
diff --git a/ix-cli/src/cli/commands/decide.ts b/ix-cli/src/cli/commands/decide.ts
deleted file mode 100644
index b97e1c70..00000000
--- a/ix-cli/src/cli/commands/decide.ts
+++ /dev/null
@@ -1,173 +0,0 @@
-import type { Command } from "commander";
-import { IxClient } from "../../client/api.js";
-import { getEndpoint } from "../config.js";
-import { resolveEntity } from "../resolve.js";
-import { deterministicId } from "../github/transform.js";
-import type { GraphPatchPayload, PatchOp } from "../../client/types.js";
-
-interface DecisionLinkOpts {
- affects?: { id: string; kind: string; name: string }[];
- supersedes?: string;
- parent?: string;
- respondsTo?: string;
-}
-// Test comment
-export function buildDecisionPatch(
- title: string,
- rationale: string,
- linkOpts: DecisionLinkOpts = {}
-): GraphPatchPayload {
- const now = new Date().toISOString();
- const decisionId = deterministicId(`decision:${title}:${now}`);
- const ops: PatchOp[] = [];
-
- // 1. UpsertNode for the decision
- ops.push({
- type: "UpsertNode",
- id: decisionId,
- kind: "decision",
- name: title,
- attrs: { rationale, created_at: now },
- });
-
- // 2. DECISION_AFFECTS edges
- if (linkOpts.affects) {
- for (const entity of linkOpts.affects) {
- ops.push({
- type: "UpsertEdge",
- id: deterministicId(`${decisionId}:DECISION_AFFECTS:${entity.id}`),
- src: decisionId,
- dst: entity.id,
- predicate: "DECISION_AFFECTS",
- attrs: {},
- });
- }
- }
-
- // 3. DECISION_SUPERSEDES edge
- if (linkOpts.supersedes) {
- ops.push({
- type: "UpsertEdge",
- id: deterministicId(`${decisionId}:DECISION_SUPERSEDES:${linkOpts.supersedes}`),
- src: decisionId,
- dst: linkOpts.supersedes,
- predicate: "DECISION_SUPERSEDES",
- attrs: {},
- });
- }
-
- // 4. DECISION_CHILD edge (parent → child)
- if (linkOpts.parent) {
- ops.push({
- type: "UpsertEdge",
- id: deterministicId(`${linkOpts.parent}:DECISION_CHILD:${decisionId}`),
- src: linkOpts.parent,
- dst: decisionId,
- predicate: "DECISION_CHILD",
- attrs: {},
- });
- }
-
- // 5. DECISION_RESPONDS_TO_BUG edge
- if (linkOpts.respondsTo) {
- ops.push({
- type: "UpsertEdge",
- id: deterministicId(`${decisionId}:DECISION_RESPONDS_TO_BUG:${linkOpts.respondsTo}`),
- src: decisionId,
- dst: linkOpts.respondsTo,
- predicate: "DECISION_RESPONDS_TO_BUG",
- attrs: {},
- });
- }
-
- return {
- patchId: decisionId,
- actor: "ix-cli",
- timestamp: now,
- source: {
- uri: `ix://decision/${encodeURIComponent(title)}`,
- extractor: "ix-cli:decide",
- sourceType: "decision",
- },
- baseRev: 0,
- ops,
- replaces: [],
- };
-}
-
-export function registerDecideCommand(program: Command): void {
- program
- .command("decide <title>")
- .description("Record a design decision")
- .requiredOption("--rationale <text>", "Rationale for the decision")
- .option("--intent-id <id>", "Link to an intent")
- .option("--affects <entities>", "Comma-separated entity names to link (creates DECISION_AFFECTS edges)")
- .option("--supersedes <id>", "Decision ID this supersedes")
- .option("--parent <id>", "Parent decision ID")
- .option("--responds-to <bugId>", "Bug ID this decision responds to (creates DECISION_RESPONDS_TO_BUG edge)")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(
- async (
- title: string,
- opts: {
- rationale: string;
- intentId?: string;
- affects?: string;
- supersedes?: string;
- parent?: string;
- respondsTo?: string;
- format: string;
- }
- ) => {
- const client = new IxClient(getEndpoint());
- const hasLinks = opts.affects || opts.supersedes || opts.parent || opts.respondsTo;
-
- if (hasLinks) {
- // Use GraphPatch path for linked decisions
- let resolvedAffects: { id: string; kind: string; name: string }[] | undefined;
-
- if (opts.affects) {
- const names = opts.affects.split(",").map((s) => s.trim());
- resolvedAffects = [];
- for (const name of names) {
- const resolved = await resolveEntity(client, name, [
- "class", "module", "file", "function", "method", "trait", "object", "interface",
- ]);
- if (resolved) {
- resolvedAffects.push({ id: resolved.id, kind: resolved.kind, name: resolved.name });
- }
- }
- }
-
- const patch = buildDecisionPatch(title, opts.rationale, {
- affects: resolvedAffects,
- supersedes: opts.supersedes,
- parent: opts.parent,
- respondsTo: opts.respondsTo,
- });
-
- if (opts.intentId) {
- patch.intent = opts.intentId;
- }
-
- const result = await client.commitPatch(patch);
- if (opts.format === "json") {
- console.log(JSON.stringify({ ...result, decisionId: patch.ops[0].id }, null, 2));
- } else {
- console.log(`Decision recorded: ${patch.ops[0].id} (rev ${result.rev})`);
- if (resolvedAffects?.length) {
- console.log(` Linked to: ${resolvedAffects.map((e) => e.name).join(", ")}`);
- }
- }
- } else {
- // Use the original backend endpoint for simple decisions
- const result = await client.decide(title, opts.rationale, { intentId: opts.intentId });
- if (opts.format === "json") {
- console.log(JSON.stringify(result, null, 2));
- } else {
- console.log(`Decision recorded: ${result.nodeId} (rev ${result.rev})`);
- }
- }
- }
- );
-}
diff --git a/ix-cli/src/cli/commands/decisions.ts b/ix-cli/src/cli/commands/decisions.ts
deleted file mode 100644
index 7bed539e..00000000
--- a/ix-cli/src/cli/commands/decisions.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import type { Command } from "commander";
-import { IxClient } from "../../client/api.js";
-import { getEndpoint } from "../config.js";
-import { formatDecisions } from "../format.js";
-
-export function registerDecisionsCommand(program: Command): void {
- program
- .command("decisions")
- .description("List recorded design decisions")
- .option("--limit <n>", "Max results", "50")
- .option("--topic <topic>", "Filter by topic keyword")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (opts: { limit: string; topic?: string; format: string }) => {
- const client = new IxClient(getEndpoint());
- const nodes = await client.listDecisions({
- limit: parseInt(opts.limit, 10),
- topic: opts.topic,
- });
- formatDecisions(nodes, opts.format);
- });
-}
diff --git a/ix-cli/src/cli/commands/goal.ts b/ix-cli/src/cli/commands/goal.ts
deleted file mode 100644
index c54df92c..00000000
--- a/ix-cli/src/cli/commands/goal.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-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
- .command("goal")
- .description("Manage project goals")
- .addHelpText(
- "after",
- `\nSubcommands:
- 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 goals`
- );
-
- goal
- .command("create <statement>")
- .description("Create a new goal")
- .option("--parent <id>", "Parent goal ID")
- .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.listGoals();
- 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.createGoal(statement, opts.parent);
- if (opts.format === "json") {
- console.log(JSON.stringify(result, null, 2));
- } else {
- console.log(`Goal created: ${result.nodeId} (rev ${result.rev})`);
- }
- });
-
- 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.listGoals();
- 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")
- .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.listGoals();
-
- if (opts.status === "active") {
- // Filter to goals that have at least one plan with pending tasks
- 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 {
- // Include on error to be safe
- 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/goals.ts b/ix-cli/src/cli/commands/goals.ts
deleted file mode 100644
index ef8f84ab..00000000
--- a/ix-cli/src/cli/commands/goals.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-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.listGoals();
-
- 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/plan.ts b/ix-cli/src/cli/commands/plan.ts
deleted file mode 100644
index 69af96fe..00000000
--- a/ix-cli/src/cli/commands/plan.ts
+++ /dev/null
@@ -1,813 +0,0 @@
-import type { Command } from "commander";
-import type { GraphPatchPayload, PatchOp } from "../../client/types.js";
-import { IxClient } from "../../client/api.js";
-import { getEndpoint } from "../config.js";
-import { deterministicId } from "../github/transform.js";
-import { resolveEntity, printResolved } from "../resolve.js";
-import { stderr } from "../stderr.js";
-import chalk from "chalk";
-import {
- type StagedWorkflow,
- type WorkflowRunResult,
- type WorkflowState,
- type WorkflowStageStatus,
- VALID_STATUSES,
- STATUS_ICONS,
- VALID_WORKFLOW_STAGES,
- isValidWorkflow,
- normalizeWorkflow,
- getTaskStatus,
- getWorkflowState,
- extractWorkflow,
- runWorkflowStages,
- formatWorkflowStateCompact,
-} from "../task-utils.js";
-
-// Re-export for backward compatibility (other modules may import from plan.js)
-export { type StagedWorkflow, VALID_WORKFLOW_STAGES, isValidWorkflow, normalizeWorkflow };
-
-// ── Patch builders (exported for testing) ──────────────────────────
-
-function makePatchEnvelope(ops: PatchOp[], intent?: string): GraphPatchPayload {
- return {
- patchId: deterministicId(`plan-patch-${Date.now()}-${Math.random()}`),
- actor: "ix-cli",
- timestamp: new Date().toISOString(),
- source: {
- uri: "ix-cli://plan",
- extractor: "ix-cli-plan",
- sourceType: "cli",
- },
- baseRev: 0,
- ops,
- replaces: [],
- intent,
- };
-}
-
-export function buildPlanPatch(title: string, goalId: string, respondsTo?: string): GraphPatchPayload {
- const planId = deterministicId(`plan:${title}:${goalId}`);
- const edgeId = deterministicId(`${goalId}:GOAL_HAS_PLAN:${planId}`);
- const ops: PatchOp[] = [
- {
- type: "UpsertNode",
- id: planId,
- kind: "plan",
- name: title,
- attrs: { created_at: new Date().toISOString() },
- },
- {
- type: "UpsertEdge",
- id: edgeId,
- src: goalId,
- dst: planId,
- predicate: "GOAL_HAS_PLAN",
- attrs: {},
- },
- ];
-
- if (respondsTo) {
- ops.push({
- type: "UpsertEdge",
- id: deterministicId(`${planId}:RESPONDS_TO:${respondsTo}`),
- src: planId,
- dst: respondsTo,
- predicate: "RESPONDS_TO",
- attrs: {},
- });
- }
-
- return makePatchEnvelope(ops, `Create plan: ${title}`);
-}
-
-export interface TaskOpts {
- planId: string;
- dependsOn?: string;
- affects?: { id: string; kind: string; name: string }[];
- workflow?: string[] | StagedWorkflow;
- resolves?: string;
-}
-
-export function buildTaskPatch(title: string, opts: TaskOpts): GraphPatchPayload {
- const taskId = deterministicId(`task:${title}:${opts.planId}`);
- const edgeId = deterministicId(`${opts.planId}:PLAN_HAS_TASK:${taskId}`);
- const ops: PatchOp[] = [
- {
- type: "UpsertNode",
- id: taskId,
- kind: "task",
- name: title,
- attrs: {
- status: "pending",
- created_at: new Date().toISOString(),
- ...(opts.workflow ? { workflow: opts.workflow } : {}),
- },
- },
- {
- type: "UpsertEdge",
- id: edgeId,
- src: opts.planId,
- dst: taskId,
- predicate: "PLAN_HAS_TASK",
- attrs: {},
- },
- ];
-
- if (opts.dependsOn) {
- const depEdgeId = deterministicId(`${taskId}:DEPENDS_ON:${opts.dependsOn}`);
- ops.push({
- type: "UpsertEdge",
- id: depEdgeId,
- src: taskId,
- dst: opts.dependsOn,
- predicate: "DEPENDS_ON",
- attrs: {},
- });
- }
-
- if (opts.affects) {
- for (const entity of opts.affects) {
- const affectsEdgeId = deterministicId(`${taskId}:TASK_AFFECTS:${entity.id}`);
- ops.push({
- type: "UpsertEdge",
- id: affectsEdgeId,
- src: taskId,
- dst: entity.id,
- predicate: "TASK_AFFECTS",
- attrs: { kind: entity.kind, name: entity.name },
- });
- }
- }
-
- if (opts.resolves) {
- ops.push({
- type: "UpsertEdge",
- id: deterministicId(`${taskId}:TASK_RESOLVES_BUG:${opts.resolves}`),
- src: taskId,
- dst: opts.resolves,
- predicate: "TASK_RESOLVES_BUG",
- attrs: {},
- });
- }
-
- return makePatchEnvelope(ops, `Create task: ${title}`);
-}
-
-export function buildTaskUpdatePatch(taskId: string, status: string): GraphPatchPayload {
- const ops: PatchOp[] = [
- {
- type: "AssertClaim",
- entityId: taskId,
- field: "status",
- value: status,
- confidence: 1.0,
- },
- ];
- return makePatchEnvelope(ops, `Update task ${taskId} status to ${status}`);
-}
-
-export function buildWorkflowStatePatch(taskId: string, state: WorkflowState): GraphPatchPayload {
- return makePatchEnvelope([{
- type: "AssertClaim",
- entityId: taskId,
- field: "workflow_state",
- value: state,
- confidence: 1.0,
- }], `Update workflow state for ${taskId}`);
-}
-
-// ── CLI commands ───────────────────────────────────────────────────
-
-export function registerPlanCommand(program: Command): void {
- const plan = program
- .command("plan")
- .description("Manage plans and plan tasks")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .addHelpText(
- "after",
- `\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 (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 List all plans
- ix plan --format json List all plans as 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`
- )
- .action(async (opts: { format: string }) => {
- const client = new IxClient(getEndpoint());
- const plans = await client.listByKind("plan", { limit: 50 });
- if (opts.format === "json") {
- console.log(JSON.stringify(plans.map((p: any) => ({
- id: p.id,
- name: p.name,
- status: p.attrs?.status ?? "active",
- })), null, 2));
- } else {
- if (plans.length === 0) {
- console.log("No plans found. Create one with: ix plan create <title> --goal <goal>");
- return;
- }
- for (const p of plans) {
- console.log(` ${chalk.bold((p.name ?? "(unnamed)").padEnd(40))} ${chalk.dim(p.id.slice(0, 8))}`);
- }
- }
- });
-
- plan
- .command("create <title>")
- .description("Create a new plan linked to a goal")
- .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());
-
- // Resolve goal reference (accepts name or ID)
- let goalId: string;
- try {
- goalId = await client.resolvePrefix(opts.goal);
- } catch {
- const goals = await client.listGoals();
- const match = goals.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") {
- console.log(JSON.stringify({ planId, rev: result.rev, status: result.status }, null, 2));
- } else {
- console.log(`Plan created: ${planId} (rev ${result.rev})`);
- }
- });
-
- plan
- .command("task <title>")
- .description("Add a task to a plan")
- .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")
- .option("--workflow-staged <json>", "Staged workflow as JSON (keys: discover, implement, validate)")
- .option("--resolves <bugId>", "Bug ID this task resolves (creates TASK_RESOLVES_BUG edge)")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .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());
- affectsEntities = [];
- for (const name of names) {
- const resolved = await resolveEntity(client, name, ["class", "function", "module", "file"]);
- if (!resolved) {
- stderr(`Could not resolve entity: ${name}`);
- process.exitCode = 1;
- return;
- }
- affectsEntities.push({ id: resolved.id, kind: resolved.kind, name: resolved.name });
- }
- }
-
- let workflow: string[] | StagedWorkflow | undefined;
- if (opts.workflowStaged) {
- try {
- const parsed = JSON.parse(opts.workflowStaged);
- if (!isValidWorkflow(parsed) || Array.isArray(parsed)) {
- stderr(`Invalid staged workflow JSON. Valid keys: ${VALID_WORKFLOW_STAGES.join(", ")}`);
- process.exitCode = 1;
- return;
- }
- workflow = parsed as StagedWorkflow;
- } catch {
- stderr("Invalid JSON for --workflow-staged");
- process.exitCode = 1;
- return;
- }
- } else if (opts.workflow) {
- workflow = opts.workflow.split(",").map(s => s.trim());
- }
-
- const patch = buildTaskPatch(title, {
- planId,
- dependsOn: opts.dependsOn,
- affects: affectsEntities,
- workflow,
- resolves: opts.resolves,
- });
- const result = await client.commitPatch(patch);
- const taskId = patch.ops[0].id as string;
- if (opts.format === "json") {
- console.log(JSON.stringify({ taskId, rev: result.rev, status: result.status }, null, 2));
- } else {
- console.log(`Task created: ${taskId} (rev ${result.rev})`);
- }
- });
-
- 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(resolvedPlanId, {
- direction: "out",
- predicates: ["PLAN_HAS_TASK"],
- });
-
- const tasks: { id: string; title: string; status: string; dependsOn: string[]; workflowState: WorkflowState | null }[] = [];
-
- for (const node of taskNodes) {
- if (node.kind !== "task") continue;
- // Get entity details for status and deps
- const entityDetail = await client.entity(node.id);
- const status = getTaskStatus(entityDetail);
- const wfState = getWorkflowState(entityDetail);
-
- // Expand DEPENDS_ON for this task
- const { edges: depEdges } = await client.expand(node.id, {
- direction: "out",
- predicates: ["DEPENDS_ON"],
- });
- const dependsOn = depEdges.map((e: any) => e.dst as string);
-
- tasks.push({
- id: node.id,
- title: node.name,
- status,
- dependsOn,
- workflowState: wfState,
- });
- }
-
- // Build a set of done task IDs
- const doneIds = new Set(tasks.filter(t => t.status === "done").map(t => t.id));
-
- // Next actionable: not done, all deps satisfied
- const nextActionable = tasks.find(t =>
- t.status !== "done" && t.status !== "abandoned" &&
- t.dependsOn.every(dep => doneIds.has(dep))
- );
-
- // Critical path: tasks with most downstream dependents
- const downstreamCount = new Map<string, number>();
- for (const t of tasks) {
- downstreamCount.set(t.id, 0);
- }
- for (const t of tasks) {
- for (const dep of t.dependsOn) {
- downstreamCount.set(dep, (downstreamCount.get(dep) ?? 0) + 1);
- }
- }
- const criticalPath = [...downstreamCount.entries()]
- .sort((a, b) => b[1] - a[1])
- .filter(([, count]) => count > 0)
- .map(([id]) => id);
-
- // Count open bugs linked via RESPONDS_TO
- const { nodes: respondNodes } = await client.expand(resolvedPlanId, {
- direction: "out",
- predicates: ["RESPONDS_TO"],
- });
- const openBugCount = respondNodes.filter((n: any) => n.kind === "bug").length;
-
- const summary = {
- total: tasks.length,
- done: tasks.filter(t => t.status === "done").length,
- pending: tasks.filter(t => t.status === "pending").length,
- inProgress: tasks.filter(t => t.status === "in_progress").length,
- blocked: tasks.filter(t => t.status === "blocked").length,
- openBugCount,
- };
-
- if (opts.format === "json") {
- console.log(JSON.stringify({
- planId: resolvedPlanId,
- tasks: tasks.map(t => {
- const entry: Record<string, unknown> = { title: t.title, status: t.status, id: t.id };
- if (t.workflowState) entry.workflowState = t.workflowState;
- return entry;
- }),
- criticalPath,
- nextActionable: nextActionable ? nextActionable.id : null,
- summary,
- }, null, 2));
- } else {
- for (const t of tasks) {
- const icon = STATUS_ICONS[t.status] ?? "?";
- const wfSuffix = t.workflowState ? ` ${chalk.dim(formatWorkflowStateCompact(t.workflowState))}` : "";
- console.log(` ${icon} ${chalk.dim(`[${t.status}]`.padEnd(14))} ${t.title}${wfSuffix}`);
- }
- if (nextActionable) {
- console.log(`\n${chalk.green("Next:")} ${nextActionable.title}`);
- }
- console.log(chalk.dim(`\n${summary.done}/${summary.total} done`));
- }
- });
-
- plan
- .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; runWorkflow?: boolean; stage?: string; 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 {
- // 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"],
- });
-
- const tasks: { id: string; title: string; status: string; dependsOn: string[] }[] = [];
-
- for (const node of taskNodes) {
- if (node.kind !== "task") continue;
- const entityDetail = await client.entity(node.id);
- const status = getTaskStatus(entityDetail);
-
- const { edges: depEdges } = await client.expand(node.id, {
- direction: "out",
- predicates: ["DEPENDS_ON"],
- });
- const dependsOn = depEdges.map((e: any) => e.dst as string);
-
- tasks.push({ id: node.id, title: node.name, status, dependsOn });
- }
-
- const doneIds = new Set(tasks.filter(t => t.status === "done").map(t => t.id));
- const nextActionable = tasks.find(t =>
- t.status !== "done" && t.status !== "abandoned" &&
- t.dependsOn.every(dep => doneIds.has(dep))
- );
-
- // Determine reason when no actionable task
- let noActionReason = "no actionable tasks";
- if (!nextActionable) {
- if (tasks.length === 0) {
- noActionReason = "no tasks in plan";
- } else if (tasks.every(t => t.status === "done" || t.status === "abandoned")) {
- noActionReason = "all tasks done";
- } else {
- noActionReason = "all remaining tasks blocked";
- }
- }
-
- // ── Run workflow if requested ──────────────────────────────────
- let workflowResults: WorkflowRunResult[] | null = null;
- let workflowData: StagedWorkflow | null = null;
- let nextWorkflowState: WorkflowState | null = null;
-
- if (nextActionable && (opts.withWorkflow || opts.runWorkflow)) {
- const detail = await client.entity(nextActionable.id);
- workflowData = extractWorkflow(detail.node, detail.claims);
- nextWorkflowState = getWorkflowState(detail);
- }
-
- 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> = {
- task: nextActionable.title,
- taskId: nextActionable.id,
- reason: "all dependencies satisfied",
- };
- if (workflowData) {
- result.workflow = workflowData;
- }
- if (nextWorkflowState) {
- result.workflowState = nextWorkflowState;
- }
- if (workflowResults) {
- result.workflowResults = workflowResults;
- }
- console.log(JSON.stringify(result, null, 2));
- } else {
- console.log(JSON.stringify({ task: null, reason: noActionReason }, null, 2));
- }
- } else {
- if (nextActionable) {
- console.log(`${chalk.green("Next:")} ${nextActionable.title} (${nextActionable.id.slice(0, 8)})`);
- 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}`));
- }
- }
- });
-}
-
-export function registerTaskCommand(program: Command): void {
- const task = program
- .command("task")
- .description("Manage tasks")
- .addHelpText(
- "after",
- `\nSubcommands:
- show <taskId> Show task details
- update <taskId> Update a task's status
-
-Examples:
- ix task show <task-id> --with-workflow
- ix task update <task-id> --status done`
- );
-
- task
- .command("show <taskId>")
- .description("Show task details")
- .option("--with-workflow", "Include workflow commands in output")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (taskId: string, opts: { withWorkflow?: boolean; format: string }) => {
- const client = new IxClient(getEndpoint());
-
- // 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 status = getTaskStatus(details);
- const workflow = extractWorkflow(node, details.claims);
- const workflowState = getWorkflowState(details);
-
- if (opts.format === "json") {
- const result: Record<string, unknown> = {
- taskId: resolvedTaskId,
- title: node.name,
- status,
- created_at: node.attrs?.created_at ?? node.createdAt,
- };
- if (opts.withWorkflow) {
- result.workflow = workflow ?? {};
- }
- if (workflowState) {
- result.workflowState = workflowState;
- }
- console.log(JSON.stringify(result, null, 2));
- } else {
- const icon = STATUS_ICONS[status] ?? "?";
- console.log(`${icon} ${chalk.bold(node.name)}`);
- console.log(` Status: ${status}`);
- if (workflowState) {
- const parts: string[] = [];
- for (const stage of VALID_WORKFLOW_STAGES) {
- const sv = (workflowState as any)[stage];
- if (sv) parts.push(`${stage} [${sv}]`);
- }
- if (parts.length > 0) {
- console.log(` Workflow: ${parts.join(" ")}`);
- }
- }
- if (opts.withWorkflow && workflow) {
- console.log(chalk.dim(" Workflow commands:"));
- 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}`);
- }
- }
- }
- }
- }
- });
-
- task
- .command("update <taskId>")
- .description("Update a task's status and/or run a workflow stage")
- .option("--status <status>", `Status (${VALID_STATUSES.join("|")})`)
- .option("--run-workflow <stage>", "Run a workflow stage (discover|implement|validate)")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (taskId: string, opts: { status?: string; runWorkflow?: string; format: string }) => {
- if (!opts.status && !opts.runWorkflow) {
- stderr("At least one of --status or --run-workflow is required.");
- process.exitCode = 1;
- return;
- }
- if (opts.status && !VALID_STATUSES.includes(opts.status)) {
- stderr(`Invalid status "${opts.status}". Valid: ${VALID_STATUSES.join(", ")}`);
- process.exitCode = 1;
- return;
- }
- if (opts.runWorkflow && !VALID_WORKFLOW_STAGES.includes(opts.runWorkflow)) {
- stderr(`Invalid stage "${opts.runWorkflow}". Valid: ${VALID_WORKFLOW_STAGES.join(", ")}`);
- process.exitCode = 1;
- return;
- }
- const client = new IxClient(getEndpoint());
-
- // 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) {
- process.exitCode = 1;
- return;
- }
- resolvedTaskId = target.id;
- }
-
- let lastRev: number | undefined;
-
- // Handle --status
- if (opts.status) {
- const patch = buildTaskUpdatePatch(resolvedTaskId, opts.status);
- const result = await client.commitPatch(patch);
- lastRev = result.rev;
- }
-
- // Handle --run-workflow
- let workflowResults: WorkflowRunResult[] | null = null;
- if (opts.runWorkflow) {
- const details = await client.entity(resolvedTaskId);
- const workflow = extractWorkflow(details.node, details.claims);
- if (!workflow) {
- stderr("No workflow attached to this task.");
- if (!opts.status) {
- process.exitCode = 1;
- return;
- }
- } else {
- // Get current workflow state or initialize
- const currentState = getWorkflowState(details) ?? {};
- const stage = opts.runWorkflow as keyof WorkflowState;
-
- // Set stage to "running"
- const runningState: WorkflowState = { ...currentState, [stage]: "running" as WorkflowStageStatus };
- const runningPatch = buildWorkflowStatePatch(resolvedTaskId, runningState);
- await client.commitPatch(runningPatch);
-
- // Run the stage
- workflowResults = await runWorkflowStages(workflow, [opts.runWorkflow]);
-
- // Determine final stage status
- let finalStatus: WorkflowStageStatus = "done";
- if (workflowResults.length === 0) {
- finalStatus = "skipped";
- } else if (workflowResults.some(r => r.status === "error")) {
- finalStatus = "failed";
- }
-
- // Persist final stage state
- const finalState: WorkflowState = { ...runningState, [stage]: finalStatus };
- const finalPatch = buildWorkflowStatePatch(resolvedTaskId, finalState);
- const finalResult = await client.commitPatch(finalPatch);
- lastRev = finalResult.rev;
- }
- }
-
- if (opts.format === "json") {
- const result: Record<string, unknown> = { taskId: resolvedTaskId };
- if (opts.status) result.status = opts.status;
- if (lastRev !== undefined) result.rev = lastRev;
- if (workflowResults) result.workflowResults = workflowResults;
- console.log(JSON.stringify(result, null, 2));
- } else {
- if (opts.status) {
- console.log(`Task ${resolvedTaskId.slice(0, 8)} updated to ${opts.status}${lastRev !== undefined ? ` (rev ${lastRev})` : ""}`);
- }
- if (workflowResults) {
- for (const r of workflowResults) {
- const icon = r.status === "ok" ? chalk.green("\u2713")
- : r.status === "error" ? chalk.red("\u2717")
- : chalk.yellow("\u2298");
- console.log(` ${icon} ${chalk.dim(`[${r.stage}]`)} ${r.command}`);
- if (r.status === "error" && r.error) {
- console.log(` ${chalk.red(r.error)}`);
- }
- }
- }
- }
- });
-}
-
diff --git a/ix-cli/src/cli/commands/plans.ts b/ix-cli/src/cli/commands/plans.ts
deleted file mode 100644
index e2306740..00000000
--- a/ix-cli/src/cli/commands/plans.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import type { Command } from "commander";
-import { IxClient } from "../../client/api.js";
-import { getEndpoint } from "../config.js";
-import { formatNodes } from "../format.js";
-
-export function registerPlansCommand(program: Command): void {
- program
- .command("plans")
- .description("List all plans")
- .option("--limit <n>", "Max results", "50")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (opts: { limit: string; format: string }) => {
- const client = new IxClient(getEndpoint());
- const nodes = await client.listByKind("plan", { limit: parseInt(opts.limit, 10) });
- formatNodes(nodes, opts.format);
- });
-}
diff --git a/ix-cli/src/cli/commands/tasks.ts b/ix-cli/src/cli/commands/tasks.ts
deleted file mode 100644
index 243faa06..00000000
--- a/ix-cli/src/cli/commands/tasks.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-import type { Command } from "commander";
-import { IxClient } from "../../client/api.js";
-import { getEndpoint } from "../config.js";
-import chalk from "chalk";
-import {
- STATUS_ICONS,
- getTaskStatus,
- getWorkflowState,
- formatWorkflowStateCompact,
-} from "../task-utils.js";
-
-export function registerTasksCommand(program: Command): void {
- program
- .command("tasks")
- .description("List all tasks across plans")
- .option("--status <status>", "Filter by status (pending|in_progress|blocked|done|abandoned)")
- .option("--plan <id>", "Filter to tasks in a specific plan")
- .option("--limit <n>", "Max results", "100")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .addHelpText(
- "after",
- `\nExamples:
- ix tasks
- ix tasks --status pending
- ix tasks --plan <plan-id>
- ix tasks --format json`
- )
- .action(
- async (opts: {
- status?: string;
- plan?: string;
- limit: string;
- format: string;
- }) => {
- const client = new IxClient(getEndpoint());
- const isJson = opts.format === "json";
- const limit = parseInt(opts.limit, 10);
-
- let taskNodes: any[];
-
- if (opts.plan) {
- // Get tasks for a specific plan via PLAN_HAS_TASK edges
- const { nodes } = await client.expand(opts.plan, {
- direction: "out",
- predicates: ["PLAN_HAS_TASK"],
- });
- taskNodes = nodes.filter((n: any) => n.kind === "task");
- } else {
- // Get all task nodes
- taskNodes = await client.listByKind("task", { limit });
- }
-
- // Fetch entity details per task to read claim-based status
- const entityDetails = await Promise.all(
- taskNodes.map((n: any) => client.entity(n.id).catch(() => null))
- );
-
- let results = taskNodes.map((n: any, i: number) => {
- const detail = entityDetails[i];
- const status = detail
- ? getTaskStatus(detail)
- : ((n.attrs?.status as string) ?? "pending");
- const workflowState = detail ? getWorkflowState(detail) : null;
- return {
- id: n.id,
- name: n.name || n.attrs?.name || "(unnamed)",
- status,
- planId: opts.plan ?? null,
- ...(workflowState ? { workflowState } : {}),
- };
- });
-
- const total = results.length;
-
- // Filter by status if provided
- if (opts.status) {
- results = results.filter((t) => t.status === opts.status);
- }
-
- if (isJson) {
- console.log(
- JSON.stringify(
- {
- results,
- summary: { total, filtered: results.length },
- },
- null,
- 2
- )
- );
- } else {
- if (results.length === 0) {
- console.log(chalk.dim("No tasks found."));
- return;
- }
- console.log(chalk.bold(`Tasks (${results.length})`));
- for (const t of results) {
- const icon = STATUS_ICONS[t.status] ?? "?";
- const wfSuffix = (t as any).workflowState
- ? ` ${chalk.dim(formatWorkflowStateCompact((t as any).workflowState))}`
- : "";
- console.log(
- ` ${icon} ${chalk.dim(`[${t.status}]`.padEnd(14))} ${t.name}${wfSuffix}`
- );
- }
- if (total !== results.length) {
- console.log(chalk.dim(`\n${results.length} of ${total} tasks shown (filtered by --status ${opts.status})`));
- }
- }
- }
- );
-}
diff --git a/ix-cli/src/cli/commands/truth.ts b/ix-cli/src/cli/commands/truth.ts
deleted file mode 100644
index aac51b09..00000000
--- a/ix-cli/src/cli/commands/truth.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import type { Command } from "commander";
-import { IxClient } from "../../client/api.js";
-import { getEndpoint } from "../config.js";
-import { formatIntents } from "../format.js";
-
-export function registerTruthCommand(program: Command): void {
- const truth = program
- .command("truth")
- .description("Manage project intents (truth)");
-
- truth
- .command("list")
- .description("List all intents")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (opts: { format: string }) => {
- const client = new IxClient(getEndpoint());
- const intents = await client.listTruth();
- formatIntents(intents, opts.format);
- });
-
- truth
- .command("add <statement>")
- .description("Add a new intent")
- .option("--parent <id>", "Parent intent ID")
- .option("--format <fmt>", "Output format (text|json)", "text")
- .action(async (statement: string, opts: { parent?: string; format: string }) => {
- const client = new IxClient(getEndpoint());
- const result = await client.createTruth(statement, opts.parent);
- if (opts.format === "json") {
- console.log(JSON.stringify(result, null, 2));
- } else {
- console.log(`Intent created: ${result.nodeId} (rev ${result.rev})`);
- }
- });
-}
diff --git a/ix-cli/src/cli/commands/workflow.ts b/ix-cli/src/cli/commands/workflow.ts
deleted file mode 100644
index 40968e5f..00000000
--- a/ix-cli/src/cli/commands/workflow.ts
+++ /dev/null
@@ -1,429 +0,0 @@
-import * as fs from "node:fs";
-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,
- extractWorkflow,
- VALID_WORKFLOW_STAGES,
- runWorkflowStages,
- type WorkflowRunResult,
-} from "../task-utils.js";
-import { stderr } from "../stderr.js";
-
-// ── 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;
- }
-}
-
-
-// ── 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 e0444f31..64b5130d 100644
--- a/ix-cli/src/cli/commands/workflows.ts
+++ b/ix-cli/src/cli/commands/workflows.ts
@@ -43,14 +43,30 @@ Task Listing:
ix tasks --plan <id> Tasks in a specific plan
`;
+const ADVANCED_TEXT = `
+Advanced (low-level graph commands):
+ contains <symbol> Show members of a class/module/file
+ callers <symbol> Show callers of a function/method
+ callees <symbol> Show callees of a function/method
+ imports <symbol> Show what an entity imports
+ imported-by <symbol> Show what imports an entity
+ depends <symbol> Show reverse dependencies
+ entity <id> Get entity details with claims and edges
+ text <term> Fast lexical/text search (ripgrep)
+ conflicts Detect contradictory information
+ query <nql> Raw NQL graph query (deprecated)
+
+Use "ix <command> --help" for details on any command.
+`;
+
export function registerWorkflowsHelpCommand(program: Command): void {
const help = program
.command("help [topic]")
.description("Additional help topics")
.action((topic: string | undefined) => {
if (!topic) {
- // ix help — show full program help
- program.outputHelp();
+ // ix help — call our overridden helpInformation() directly
+ console.log(program.helpInformation());
return;
}
@@ -59,6 +75,11 @@ export function registerWorkflowsHelpCommand(program: Command): void {
return;
}
+ if (topic === "advanced") {
+ console.log(ADVANCED_TEXT);
+ return;
+ }
+
// "goals" → forward to "goal" command help
if (topic === "goals") {
const goalCmd = program.commands.find(
diff --git a/ix-cli/src/cli/help-text.ts b/ix-cli/src/cli/help-text.ts
new file mode 100644
index 00000000..01364c72
--- /dev/null
+++ b/ix-cli/src/cli/help-text.ts
@@ -0,0 +1,46 @@
+const OSS_HELP = `ix — Code Memory CLI
+
+Core:
+ init Initialize Ix in a project directory
+ search <term> Search the knowledge graph by term
+ locate <symbol> Resolve symbol to definition with context
+ explain <symbol> Explain an entity with history
+ impact <target> Blast-radius / dependency analysis
+ overview <target> One-shot structural summary
+ watch Watch files and auto-ingest on change
+
+Utilities:
+ read <target> Read file content or symbol source code
+ inventory List entities by kind
+ rank Hotspot discovery by metric
+ history <entityId> Show entity provenance chain
+ diff <from> <to> Show diff between revisions
+
+System:
+ ingest [path] Ingest source files or GitHub data
+ status Show backend health
+ stats Show graph statistics
+ doctor Check system health
+ docker <action> Manage the IX backend containers
+`;
+
+const FOOTER = `Use "ix help advanced" for low-level graph commands.
+Use "ix <command> --help" for details on any command.
+`;
+
+export function buildHelpText(
+ proCommands?: { name: string; desc: string }[],
+): string {
+ let text = OSS_HELP;
+
+ if (proCommands && proCommands.length > 0) {
+ text += "\nPro:\n";
+ for (const { name, desc } of proCommands) {
+ text += ` ${name.padEnd(20)}${desc}\n`;
+ }
+ text += "\n";
+ }
+
+ text += FOOTER;
+ return text;
+}
diff --git a/ix-cli/src/cli/main.ts b/ix-cli/src/cli/main.ts
index 8d499b8f..09244736 100644
--- a/ix-cli/src/cli/main.ts
+++ b/ix-cli/src/cli/main.ts
@@ -1,144 +1,33 @@
#!/usr/bin/env node
import { Command } from "commander";
-import { registerQueryCommand } from "./commands/query.js";
-import { registerIngestCommand } from "./commands/ingest.js";
-import { registerDecideCommand } from "./commands/decide.js";
-import { registerDecisionsCommand } from "./commands/decisions.js";
-import { registerSearchCommand } from "./commands/search.js";
-import { registerTruthCommand } from "./commands/truth.js";
-import { registerPatchesCommand } from "./commands/patches.js";
-import { registerStatusCommand } from "./commands/status.js";
-import { registerEntityCommand } from "./commands/entity.js";
-import { registerHistoryCommand } from "./commands/history.js";
-import { registerConflictsCommand } from "./commands/conflicts.js";
-import { registerDiffCommand } from "./commands/diff.js";
-import { registerInitCommand } from "./commands/init.js";
-import { registerTextCommand } from "./commands/text.js";
-import { registerLocateCommand } from "./commands/locate.js";
-import { registerExplainCommand } from "./commands/explain.js";
-import { registerCallersCommand } from "./commands/callers.js";
-import { registerImportsCommand } from "./commands/imports.js";
-import { registerContainsCommand } from "./commands/contains.js";
-import { registerStatsCommand } from "./commands/stats.js";
-import { registerDoctorCommand } from "./commands/doctor.js";
-import { registerDependsCommand } from "./commands/depends.js";
-import { registerReadCommand } from "./commands/read.js";
-import { registerInventoryCommand } from "./commands/inventory.js";
-import { registerImpactCommand } from "./commands/impact.js";
-import { registerRankCommand } from "./commands/rank.js";
-import { registerOverviewCommand } from "./commands/overview.js";
-import { registerGoalCommand } from "./commands/goal.js";
-import { registerPlanCommand, registerTaskCommand } from "./commands/plan.js";
-import { registerBugCommand } from "./commands/bug.js";
-import { registerBugsCommand } from "./commands/bugs.js";
-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";
-import { registerDockerCommand } from "./commands/docker.js";
+import { registerOssCommands, registerProStubs } from "./register/oss.js";
+import { tryLoadProCommands } from "./register/pro-loader.js";
+import { buildHelpText } from "./help-text.js";
-const HELP_HEADER = `
-Workflow Commands (start here):
- briefing Session-resume briefing
- overview <target> One-shot structural summary
- impact <target> Blast-radius / dependency analysis
- rank Hotspot discovery by metric
- inventory List entities by kind
-
-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
- search <term> Search the knowledge graph by term
- locate <symbol> Resolve symbol to definition with context
- contains <symbol> Show members of a class/module/file
- callers <symbol> Show callers of a function/method
- callees <symbol> Show callees of a function/method
- imports <symbol> Show what an entity imports
- imported-by <symbol> Show what imports an entity
- depends <symbol> Show reverse dependencies
- entity <id> Get entity details with claims and edges
- explain <symbol> Explain an entity with history
+const program = new Command();
+program
+ .name("ix")
+ .version("0.1.0");
-Infrastructure:
- docker start Start the IX backend (ArangoDB + Memory Layer)
- docker stop Stop the backend (--remove-data to wipe volumes)
- docker status Show container and health status
- docker logs Tail backend logs
- docker restart Restart backend containers
+// Start with OSS-only help; updated after Pro probe.
+program.helpInformation = () => buildHelpText();
-Diagnostics / State / History:
- ingest [path] Ingest source files or GitHub data
- status Show backend health
- stats Show graph statistics
- doctor Check system health
- history <entityId> Show entity provenance chain
- diff <from> <to> Show diff between revisions
- truth Manage project intents
- text <term> Fast lexical/text search (ripgrep)
+registerOssCommands(program);
-Use "ix help workflows" for the recommended development loop.
-Use "ix <command> --help" for details on any command.
-`;
+(async () => {
+ const ossCmdNames = new Set(program.commands.map((c: Command) => c.name()));
-const program = new Command();
-program
- .name("ix")
- .description("Ix Memory — Persistent Memory for LLM Systems")
- .version("0.1.0")
- .addHelpText("before", HELP_HEADER);
+ const proLoaded = await tryLoadProCommands(program);
+ if (proLoaded) {
+ // Collect commands that Pro added (weren't in OSS set)
+ const proCommands = program.commands
+ .filter((c: Command) => !ossCmdNames.has(c.name()))
+ .map((c: Command) => ({ name: c.name(), desc: c.description() }));
-registerQueryCommand(program);
-registerIngestCommand(program);
-registerDecideCommand(program);
-registerDecisionsCommand(program);
-registerSearchCommand(program);
-registerTruthCommand(program);
-registerPatchesCommand(program);
-registerStatusCommand(program);
-registerEntityCommand(program);
-registerHistoryCommand(program);
-registerConflictsCommand(program);
-registerDiffCommand(program);
-registerInitCommand(program);
-registerTextCommand(program);
-registerLocateCommand(program);
-registerExplainCommand(program);
-registerCallersCommand(program);
-registerImportsCommand(program);
-registerContainsCommand(program);
-registerStatsCommand(program);
-registerDoctorCommand(program);
-registerDependsCommand(program);
-registerReadCommand(program);
-registerInventoryCommand(program);
-registerImpactCommand(program);
-registerRankCommand(program);
-registerOverviewCommand(program);
-registerGoalCommand(program);
-registerPlanCommand(program);
-registerTaskCommand(program);
-registerBugCommand(program);
-registerBugsCommand(program);
-registerPlansCommand(program);
-registerWatchCommand(program);
-registerBriefingCommand(program);
-registerWorkflowCommand(program);
-registerWorkflowsHelpCommand(program);
-registerTasksCommand(program);
-registerGoalsCommand(program);
-registerDockerCommand(program);
+ program.helpInformation = () => buildHelpText(proCommands);
+ } else {
+ registerProStubs(program);
+ }
-program.parse();
+ program.parse();
+})();
diff --git a/ix-cli/src/cli/register/oss.ts b/ix-cli/src/cli/register/oss.ts
new file mode 100644
index 00000000..6416e11b
--- /dev/null
+++ b/ix-cli/src/cli/register/oss.ts
@@ -0,0 +1,104 @@
+import type { Command } from "commander";
+import { registerQueryCommand } from "../commands/query.js";
+import { registerIngestCommand } from "../commands/ingest.js";
+import { registerSearchCommand } from "../commands/search.js";
+import { registerStatusCommand } from "../commands/status.js";
+import { registerEntityCommand } from "../commands/entity.js";
+import { registerHistoryCommand } from "../commands/history.js";
+import { registerConflictsCommand } from "../commands/conflicts.js";
+import { registerDiffCommand } from "../commands/diff.js";
+import { registerInitCommand } from "../commands/init.js";
+import { registerTextCommand } from "../commands/text.js";
+import { registerLocateCommand } from "../commands/locate.js";
+import { registerExplainCommand } from "../commands/explain.js";
+import { registerCallersCommand } from "../commands/callers.js";
+import { registerImportsCommand } from "../commands/imports.js";
+import { registerContainsCommand } from "../commands/contains.js";
+import { registerStatsCommand } from "../commands/stats.js";
+import { registerDoctorCommand } from "../commands/doctor.js";
+import { registerDependsCommand } from "../commands/depends.js";
+import { registerReadCommand } from "../commands/read.js";
+import { registerInventoryCommand } from "../commands/inventory.js";
+import { registerImpactCommand } from "../commands/impact.js";
+import { registerRankCommand } from "../commands/rank.js";
+import { registerOverviewCommand } from "../commands/overview.js";
+import { registerWatchCommand } from "../commands/watch.js";
+import { registerDockerCommand } from "../commands/docker.js";
+import { registerWorkflowsHelpCommand } from "../commands/workflows.js";
+
+const PRO_COMMANDS: { name: string; desc: string }[] = [
+ { name: "briefing", desc: "Session-resume briefing" },
+ { name: "bug", desc: "Manage bugs" },
+ { name: "bugs", desc: "List all bugs" },
+ { name: "decide", desc: "Record a design decision" },
+ { name: "decisions", desc: "List recorded design decisions" },
+ { name: "goal", desc: "Manage project goals" },
+ { name: "goals", desc: "List all goals" },
+ { name: "patches", desc: "List recent patches" },
+ { name: "plan", desc: "Manage plans and plan tasks" },
+ { name: "task", desc: "Manage tasks" },
+ { name: "plans", desc: "List all plans" },
+ { name: "tasks", desc: "List all tasks across plans" },
+ { name: "truth", desc: "Manage project intents (truth)" },
+ { name: "workflow", desc: "Attach, show, validate, or run staged workflows" },
+];
+
+/** Commands hidden from default help but still callable. */
+const ADVANCED_COMMANDS = [
+ "contains", "callers", "callees", "imports", "imported-by",
+ "depends", "entity", "text", "conflicts", "query",
+];
+
+export function registerOssCommands(program: Command): void {
+ registerQueryCommand(program);
+ registerIngestCommand(program);
+ registerSearchCommand(program);
+ registerStatusCommand(program);
+ registerEntityCommand(program);
+ registerHistoryCommand(program);
+ registerConflictsCommand(program);
+ registerDiffCommand(program);
+ registerInitCommand(program);
+ registerTextCommand(program);
+ registerLocateCommand(program);
+ registerExplainCommand(program);
+ registerCallersCommand(program);
+ registerImportsCommand(program);
+ registerContainsCommand(program);
+ registerStatsCommand(program);
+ registerDoctorCommand(program);
+ registerDependsCommand(program);
+ registerReadCommand(program);
+ registerInventoryCommand(program);
+ registerImpactCommand(program);
+ registerRankCommand(program);
+ registerOverviewCommand(program);
+ registerWatchCommand(program);
+ registerDockerCommand(program);
+ registerWorkflowsHelpCommand(program);
+
+ // Hide advanced commands from default help
+ const advancedSet = new Set(ADVANCED_COMMANDS);
+ for (const cmd of program.commands) {
+ if (advancedSet.has(cmd.name())) {
+ (cmd as any).hidden = true;
+ }
+ }
+}
+
+export function registerProStubs(program: Command): void {
+ const registered = new Set(program.commands.map((c: Command) => c.name()));
+ for (const { name, desc } of PRO_COMMANDS) {
+ if (registered.has(name)) continue;
+ const stub = program
+ .command(name)
+ .description(desc)
+ .allowUnknownOption(true)
+ .action(() => {
+ console.error(`The '${name}' command requires Ix Pro.`);
+ console.error(`Install @ix/pro to enable premium features.`);
+ process.exitCode = 1;
+ });
+ (stub as any).hidden = true;
+ }
+}
diff --git a/ix-cli/src/cli/register/pro-loader.ts b/ix-cli/src/cli/register/pro-loader.ts
new file mode 100644
index 00000000..5f2a07bc
--- /dev/null
+++ b/ix-cli/src/cli/register/pro-loader.ts
@@ -0,0 +1,21 @@
+import type { Command } from "commander";
+
+export async function tryLoadProCommands(program: Command): Promise<boolean> {
+ try {
+ const dynamicImport = new Function(
+ "specifier",
+ "return import(specifier)"
+ ) as (specifier: string) => Promise<any>;
+
+ const mod = await dynamicImport("@ix/pro/register");
+
+ if (mod?.registerProCommands) {
+ mod.registerProCommands(program);
+ return true;
+ }
+
+ return false;
+ } catch {
+ return false;
+ }
+}
diff --git a/ix-cli/src/cli/task-utils.ts b/ix-cli/src/cli/task-utils.ts
deleted file mode 100644
index e927de59..00000000
--- a/ix-cli/src/cli/task-utils.ts
+++ /dev/null
@@ -1,215 +0,0 @@
-import { execFile } from "node:child_process";
-import { promisify } from "node:util";
-
-const execFileAsync = promisify(execFile);
-
-// ── Types ───────────────────────────────────────────────────────────
-
-export interface StagedWorkflow {
- discover?: string[];
- implement?: string[];
- validate?: string[];
-}
-
-export const VALID_WORKFLOW_STAGES = ["discover", "implement", "validate"];
-
-export const VALID_STATUSES = ["pending", "in_progress", "blocked", "done", "abandoned"];
-
-export const STATUS_ICONS: Record<string, string> = {
- pending: "\u25CB",
- in_progress: "\u25D0",
- blocked: "\u2716",
- done: "\u25CF",
- abandoned: "\u2298",
-};
-
-// ── Workflow type guards / normalizers ───────────────────────────────
-
-export function isValidWorkflow(w: unknown): w is string[] | StagedWorkflow {
- if (Array.isArray(w)) return w.every(s => typeof s === "string");
- if (typeof w === "object" && w !== null) {
- return Object.keys(w).every(k => VALID_WORKFLOW_STAGES.includes(k));
- }
- return false;
-}
-
-/** Normalize any workflow form to StagedWorkflow for display */
-export function normalizeWorkflow(w: string[] | StagedWorkflow): StagedWorkflow {
- if (Array.isArray(w)) return { discover: w };
- return w;
-}
-
-// ── Unified status reader ───────────────────────────────────────────
-
-/**
- * Read task status from entity detail.
- * Priority: claims (field==="status" OR statement includes "status") > attrs.status > "pending"
- * Validates against VALID_STATUSES before returning.
- */
-export function getTaskStatus(entityDetail: { node: any; claims: any[]; edges: any[] }): string {
- // Check claims first (status updates come via AssertClaim)
- const statusClaim = entityDetail.claims?.find(
- (c: any) => c.field === "status" || c.statement?.includes("status")
- );
- if (statusClaim) {
- const val = (statusClaim as any).value ?? (statusClaim as any).statement;
- if (typeof val === "string" && VALID_STATUSES.includes(val)) return val;
- }
- // Fall back to node attrs
- const attrStatus = entityDetail.node?.attrs?.status;
- if (typeof attrStatus === "string") return attrStatus;
- return "pending";
-}
-
-// ── Workflow extraction ─────────────────────────────────────────────
-
-/**
- * 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);
-}
-
-// ── Workflow stage state ────────────────────────────────────────────
-
-export type WorkflowStageStatus = "pending" | "running" | "done" | "failed" | "skipped";
-
-export interface WorkflowState {
- discover?: WorkflowStageStatus;
- implement?: WorkflowStageStatus;
- validate?: WorkflowStageStatus;
-}
-
-const VALID_STAGE_STATUSES: WorkflowStageStatus[] = ["pending", "running", "done", "failed", "skipped"];
-
-/**
- * Read workflow stage state from entity detail.
- * Reads claim with field "workflow_state", falls back to attrs.workflow_state.
- */
-export function getWorkflowState(entityDetail: { node: any; claims: any[] }): WorkflowState | null {
- // Check claims first
- const stateClaim = entityDetail.claims?.find(
- (c: any) => c.field === "workflow_state"
- );
- if (stateClaim) {
- const val = (stateClaim as any).value;
- if (val && typeof val === "object" && !Array.isArray(val)) {
- // Validate stage statuses
- const result: WorkflowState = {};
- for (const stage of VALID_WORKFLOW_STAGES) {
- const sv = (val as any)[stage];
- if (typeof sv === "string" && VALID_STAGE_STATUSES.includes(sv as WorkflowStageStatus)) {
- (result as any)[stage] = sv;
- }
- }
- return Object.keys(result).length > 0 ? result : null;
- }
- }
- // Fall back to attrs
- const attrState = entityDetail.node?.attrs?.workflow_state;
- if (attrState && typeof attrState === "object" && !Array.isArray(attrState)) {
- const result: WorkflowState = {};
- for (const stage of VALID_WORKFLOW_STAGES) {
- const sv = (attrState as any)[stage];
- if (typeof sv === "string" && VALID_STAGE_STATUSES.includes(sv as WorkflowStageStatus)) {
- (result as any)[stage] = sv;
- }
- }
- return Object.keys(result).length > 0 ? result : null;
- }
- return null;
-}
-
-// ── Workflow execution ──────────────────────────────────────────────
-
-export interface WorkflowRunResult {
- stage: string;
- command: string;
- status: "ok" | "error" | "skipped";
- output?: unknown;
- error?: string;
-}
-
-export 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();
- }
-}
-
-export 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;
-}
-
-// ── Workflow stage state display ────────────────────────────────────
-
-const STAGE_STATUS_ICONS: Record<WorkflowStageStatus, string> = {
- pending: "\u25CB",
- running: "\u2026",
- done: "\u2713",
- failed: "\u2717",
- skipped: "\u2298",
-};
-
-export function formatWorkflowStateCompact(state: WorkflowState): string {
- const parts: string[] = [];
- for (const stage of VALID_WORKFLOW_STAGES) {
- const s = (state as any)[stage] as WorkflowStageStatus | undefined;
- if (s) {
- const icon = STAGE_STATUS_ICONS[s] ?? "?";
- parts.push(`${stage}${icon}`);
- }
- }
- return parts.length > 0 ? `[${parts.join(" ")}]` : "";
-}