Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
feat: unified task status, real textual diff, full-tree depends, resolver consistency
Tanner Kocherb88a7836ad82
diff --git a/ix-cli/src/cli/__tests__/depends-semantics.test.ts b/ix-cli/src/cli/__tests__/depends-semantics.test.tsnew file mode 100644index 00000000..2405f539--- /dev/null+++ b/ix-cli/src/cli/__tests__/depends-semantics.test.ts@@ -0,0 +1,138 @@+import { describe, it, expect } from "vitest";+import * as fs from "node:fs";+import * as path from "node:path";++/**+ * Verify that `ix depends` presents results in dependency direction,+ * uses full-tree traversal, and has correct semantics.+ */++const dependsTsPath = path.resolve(__dirname, "../commands/depends.ts");+const dependsContent = fs.readFileSync(dependsTsPath, "utf-8");++// ── Direction semantics ─────────────────────────────────────────────++describe("depends direction semantics", () => {+ it("description says downstream dependents", () => {+ expect(dependsContent).toContain("downstream dependents");+ expect(dependsContent).not.toContain("reverse CALLS");+ });++ it("text heading uses dependency-oriented language", () => {+ expect(dependsContent).toContain("Downstream dependents of");+ });++ it("empty state message uses dependency language", () => {+ expect(dependsContent).toContain("No downstream dependents found");+ });++ it("uses dependency-oriented relation values", () => {+ expect(dependsContent).toContain('"called_by"');+ expect(dependsContent).toContain('"imported_by"');+ });+});++// ── Full-tree traversal ─────────────────────────────────────────────++describe("depends full-tree traversal", () => {+ it("has buildDependencyTree function", () => {+ expect(dependsContent).toContain("buildDependencyTree");+ });++ it("expands recursively via one-hop calls", () => {+ // Uses hops: 1 for each level, then recurses+ expect(dependsContent).toContain("hops: 1");+ expect(dependsContent).toContain("await expand(n.id, depth + 1)");+ });++ it("defaults to full traversal without --depth", () => {+ // --depth has no default value in option declaration+ expect(dependsContent).toContain('depth?: string');+ expect(dependsContent).toContain("DEFAULT_MAX_DEPTH");+ });++ it("--depth acts as optional limiter", () => {+ expect(dependsContent).toContain('"--depth <n>"');+ expect(dependsContent).toContain("Limit traversal depth");+ });++ it("has cycle detection", () => {+ expect(dependsContent).toContain("visited.has(n.id)");+ expect(dependsContent).toContain("cycle: true");+ });++ it("has node cap safety limit", () => {+ expect(dependsContent).toContain("MAX_NODES");+ expect(dependsContent).toContain("nodesVisited >= maxNodes");+ });++ it("reports truncation when limits hit", () => {+ expect(dependsContent).toContain("truncated = true");+ expect(dependsContent).toContain("tree truncated");+ });+});++// ── Nested tree output ──────────────────────────────────────────────++describe("depends nested tree structure", () => {+ it("has DependencyNode interface with children", () => {+ expect(dependsContent).toContain("interface DependencyNode");+ expect(dependsContent).toContain("children: DependencyNode[]");+ });++ it("JSON outputs tree field not flat results", () => {+ expect(dependsContent).toContain("tree,");+ expect(dependsContent).not.toMatch(/\bresults: allDependents\.map\b/);+ });++ it("JSON includes traversal metadata", () => {+ expect(dependsContent).toContain("nodesVisited");+ expect(dependsContent).toContain("maxDepthReached");+ expect(dependsContent).toContain("truncated");+ });++ it("renders text tree with box-drawing glyphs", () => {+ expect(dependsContent).toContain("└─");+ expect(dependsContent).toContain("├─");+ expect(dependsContent).toContain("│");+ });++ it("JSON includes semantics field", () => {+ expect(dependsContent).toContain('"downstream_dependents"');+ });+});++// ── Input validation ────────────────────────────────────────────────++describe("depends input validation", () => {+ it("validates --pick as positive integer", () => {+ expect(dependsContent).toContain("Invalid value for --pick");+ expect(dependsContent).toContain("must be a positive integer");+ });++ it("supports --pick option", () => {+ expect(dependsContent).toContain('"--pick <n>"');+ });++ it("supports --kind option", () => {+ expect(dependsContent).toContain('"--kind <kind>"');+ });++ it("supports --path option", () => {+ expect(dependsContent).toContain('"--path <path>"');+ });++ it("supports --format option", () => {+ expect(dependsContent).toContain('"--format <fmt>"');+ });++ it("uses resolveFileOrEntity with resolveOpts", () => {+ expect(dependsContent).toContain("resolveFileOrEntity(client, symbol, resolveOpts)");+ });++ it("traverses CALLS and IMPORTS edges in reverse", () => {+ expect(dependsContent).toContain('direction: "in"');+ expect(dependsContent).toContain('predicates: ["CALLS"]');+ expect(dependsContent).toContain('predicates: ["IMPORTS"]');+ });+});diff --git a/ix-cli/src/cli/__tests__/diff-content.test.ts b/ix-cli/src/cli/__tests__/diff-content.test.tsnew file mode 100644index 00000000..128cf813--- /dev/null+++ b/ix-cli/src/cli/__tests__/diff-content.test.ts@@ -0,0 +1,247 @@+import { describe, it, expect } from "vitest";+import * as fs from "node:fs";+import * as path from "node:path";+import { computeLineDiff, computeTextualDiff } from "../commands/diff.js";++const diffTsPath = path.resolve(__dirname, "../commands/diff.ts");+const diffContent = fs.readFileSync(diffTsPath, "utf-8");++// ── Unit tests for computeLineDiff ──────────────────────────────────++describe("computeLineDiff", () => {+ it("identical input produces all context lines", () => {+ const result = computeLineDiff("a\nb\nc", "a\nb\nc");+ expect(result).toEqual([" a", " b", " c"]);+ });++ it("added lines produce + prefixed lines", () => {+ const result = computeLineDiff("a\nb", "a\nb\nc");+ expect(result).toEqual([" a", " b", "+ c"]);+ });++ it("removed lines produce - prefixed lines", () => {+ const result = computeLineDiff("a\nb\nc", "a\nb");+ expect(result).toEqual([" a", " b", "- c"]);+ });++ it("modified lines produce - then + pairs", () => {+ const result = computeLineDiff("a\nold\nc", "a\nnew\nc");+ expect(result).toEqual([" a", "- old", "+ new", " c"]);+ });++ it("empty before produces all + lines", () => {+ const result = computeLineDiff("", "a\nb");+ expect(result).toEqual(["- ", "+ a", "+ b"]);+ });++ it("empty after produces - then + for first line, then - for remaining", () => {+ const result = computeLineDiff("a\nb", "");+ expect(result).toEqual(["- a", "+ ", "- b"]);+ });++ it("both empty produces single context line", () => {+ const result = computeLineDiff("", "");+ expect(result).toEqual([" "]);+ });+});++// ── Unit tests for computeTextualDiff ───────────────────────────────++describe("computeTextualDiff", () => {+ it("returns empty array for identical content", async () => {+ const result = await computeTextualDiff("a\nb\nc\n", "a\nb\nc\n");+ expect(result).toEqual([]);+ });++ it("shows added lines with + prefix", async () => {+ const result = await computeTextualDiff("a\nb\n", "a\nb\nc\n");+ const added = result.filter(l => l.startsWith("+"));+ expect(added.length).toBeGreaterThan(0);+ expect(added.some(l => l.includes("c"))).toBe(true);+ });++ it("shows removed lines with - prefix", async () => {+ const result = await computeTextualDiff("a\nb\nc\n", "a\nb\n");+ const removed = result.filter(l => l.startsWith("-"));+ expect(removed.length).toBeGreaterThan(0);+ expect(removed.some(l => l.includes("c"))).toBe(true);+ });++ it("replacement shows - then + without identical pairs", async () => {+ const result = await computeTextualDiff("// old comment\n", "// new comment\n");+ const removed = result.filter(l => l.startsWith("-"));+ const added = result.filter(l => l.startsWith("+"));+ expect(removed.length).toBeGreaterThan(0);+ expect(added.length).toBeGreaterThan(0);+ // Must not have identical - and + lines+ for (const r of removed) {+ for (const a of added) {+ expect(r.slice(1)).not.toBe(a.slice(1));+ }+ }+ });++ it("replacement + insertion renders correctly", async () => {+ const before = "line1\n// old comment\nline3\n";+ const after = "line1\n// Another test comment replacing old\n// new comment entirely\nline3\n";+ const result = await computeTextualDiff(before, after);+ const removed = result.filter(l => l.startsWith("-"));+ const added = result.filter(l => l.startsWith("+"));+ expect(removed.some(l => l.includes("old comment"))).toBe(true);+ expect(added.some(l => l.includes("Another test comment"))).toBe(true);+ expect(added.some(l => l.includes("new comment entirely"))).toBe(true);+ });++ it("comment-only change is detected", async () => {+ const before = "function foo() {\n return 1;\n}\n";+ const after = "function foo() {\n // test comment\n return 1;\n}\n";+ const result = await computeTextualDiff(before, after);+ expect(result.length).toBeGreaterThan(0);+ const added = result.filter(l => l.startsWith("+"));+ expect(added.some(l => l.includes("test comment"))).toBe(true);+ });+});++// ── Source-reading: diff.ts structure ───────────────────────────────++describe("diff.ts textual diff model", () => {+ it("has computeTextualDiff using git diff --no-index", () => {+ expect(diffContent).toContain("computeTextualDiff");+ expect(diffContent).toContain("--no-index");+ });++ it("has loadFileAtTimestamp for full file content via git", () => {+ expect(diffContent).toContain("loadFileAtTimestamp");+ expect(diffContent).toContain("--before=");+ });++ it("has loadFileFromDisk for current disk content", () => {+ expect(diffContent).toContain("loadFileFromDisk");+ });++ it("uses git show to retrieve historical file content", () => {+ expect(diffContent).toMatch(/`\$\{hash\}:\$\{relPath\}`/);+ expect(diffContent).toContain('"show"');+ });++ it("falls back to readSourceSpan on git failure", () => {+ expect(diffContent).toContain("return readSourceSpan(node)");+ });++ it("has readSourceSpanAtTimestamp for span-level historical content", () => {+ expect(diffContent).toContain("readSourceSpanAtTimestamp");+ });++ it("formatDiffContent is async", () => {+ expect(diffContent).toContain("async function formatDiffContent");+ });++ it("uses await formatDiffContent at call site", () => {+ expect(diffContent).toContain("await formatDiffContent(result)");+ });++ it("parseDiffOutput strips git diff headers", () => {+ expect(diffContent).toContain("parseDiffOutput");+ expect(diffContent).toContain('line.startsWith("@@")');+ });++ it("resolves before timestamp from graph changes or patch list", () => {+ expect(diffContent).toContain("resolveFromTimestamp");+ expect(diffContent).toContain("getRevisionTimestamp");+ });++ it("resolves after timestamp for non-latest revisions", () => {+ expect(diffContent).toContain("resolveToTimestamp");+ });++ it("has loadContentAtRev for revision-aware content loading", () => {+ expect(diffContent).toContain("loadContentAtRev");+ expect(diffContent).toContain("loadFileFromDisk(fileUri)");+ expect(diffContent).toContain("loadFileAtTimestamp(fileUri, ts)");+ });++ it("content mode uses loadContentAtRev for both sides", () => {+ expect(diffContent).toContain('loadContentAtRev(client, fileUri, from, changes, "from")');+ expect(diffContent).toContain('loadContentAtRev(client, fileUri, to, changes, "to")');+ });++ it("detects textual changes when graph shows no changes", () => {+ expect(diffContent).toContain("textualChanges");+ expect(diffContent).toContain("not captured by parser");+ });++ it("uses computeTextualDiff for source span diffs in graph fallback", () => {+ expect(diffContent).toContain("computeTextualDiff(beforeSource, afterSource)");+ });++ it("writes temp files to os.tmpdir for git diff --no-index", () => {+ expect(diffContent).toContain("os.tmpdir()");+ expect(diffContent).toContain("unlinkSync");+ });+});++// ── Resolver flags in diff ──────────────────────────────────────────++describe("diff.ts resolver flags", () => {+ it("supports --pick option", () => {+ expect(diffContent).toContain('"--pick <n>"');+ });++ it("supports --kind option", () => {+ expect(diffContent).toContain('"--kind <kind>"');+ });++ it("supports --path option", () => {+ expect(diffContent).toContain('"--path <path>"');+ });++ it("passes resolver opts to resolveFileOrEntity", () => {+ expect(diffContent).toContain("resolveFileOrEntity(client, target, resolveOpts)");+ });++ it("converts --pick string to number", () => {+ expect(diffContent).toContain("parseInt(opts.pick, 10)");+ });++ it("imports printResolved for text-mode output", () => {+ expect(diffContent).toContain("printResolved");+ });++ it("outputs structured JSON for ambiguous targets", () => {+ expect(diffContent).toContain("resolveEntityFull");+ expect(diffContent).toContain("fullResult.ambiguous");+ });+});++// ── Symbol diff body extraction ─────────────────────────────────────++describe("diff.ts symbol diff correctness", () => {+ it("has getSymbolSpans for before/after line ranges", () => {+ expect(diffContent).toContain("getSymbolSpans");+ expect(diffContent).toContain("symbolSpans.before");+ expect(diffContent).toContain("symbolSpans.after");+ });++ it("extracts symbol body via sliceContent", () => {+ expect(diffContent).toContain("sliceContent");+ expect(diffContent).toContain("sliceContent(beforeFile");+ expect(diffContent).toContain("sliceContent(afterFile");+ });++ it("diffs symbol bodies directly instead of slicing hunks", () => {+ // Symbol diff computes textual diff on extracted bodies, not sliced file hunks+ expect(diffContent).toContain("computeTextualDiff(beforeBody, afterBody)");+ });++ it("keeps file diff separate from symbol diff", () => {+ // File targets diff the whole file+ expect(diffContent).toContain("computeTextualDiff(beforeFile, afterFile)");+ // Symbol targets use extracted bodies+ expect(diffContent).toContain("computeTextualDiff(beforeBody, afterBody)");+ });++ it("reports correct diffMode for file vs symbol", () => {+ expect(diffContent).toContain('diffMode = "symbol"');+ expect(diffContent).toContain('diffMode = "file"');+ });+});diff --git a/ix-cli/src/cli/__tests__/goal-truth-separation.test.ts b/ix-cli/src/cli/__tests__/goal-truth-separation.test.tsnew file mode 100644index 00000000..6d3d1d20--- /dev/null+++ b/ix-cli/src/cli/__tests__/goal-truth-separation.test.ts@@ -0,0 +1,99 @@+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/goal endpoint", () => {+ expect(apiContent).toContain('"/v1/goal"');+ });++ 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__/name-resolution.test.ts b/ix-cli/src/cli/__tests__/name-resolution.test.tsindex c5dfc979..de7ce97b 100644--- a/ix-cli/src/cli/__tests__/name-resolution.test.ts+++ b/ix-cli/src/cli/__tests__/name-resolution.test.ts@@ -22,9 +22,9 @@ const mainContent = fs.readFileSync(mainTsPath, "utf-8");// ── Name-based resolution for --goal and --plan ──────────────────────describe("plan create --goal accepts name", () => {- it("plan create resolves --goal via resolvePrefix then listTruth", () => {+ it("plan create resolves --goal via resolvePrefix then listGoals", () => {expect(planContent).toContain("client.resolvePrefix(opts.goal)");- expect(planContent).toContain("client.listTruth()");+ expect(planContent).toContain("client.listGoals()");});it("plan create --goal option says id-or-name", () => {@@ -37,7 +37,7 @@ describe("plan create --goal accepts name", () => {});it("plan create falls back to goal name search when prefix fails", () => {- // Should search listTruth and find by name+ // Should search listGoals and find by nameexpect(planContent).toContain("opts.goal.toLowerCase()");});});@@ -77,9 +77,9 @@ describe("goal show command", () => {expect(goalContent).toContain('command("show <ref>")');});- it("goal show resolves by name via listTruth", () => {+ it("goal show resolves by name via listGoals", () => {expect(goalContent).toContain("client.resolvePrefix(ref)");- expect(goalContent).toContain("client.listTruth()");+ expect(goalContent).toContain("client.listGoals()");});it("goal show fetches entity details", () => {@@ -103,7 +103,7 @@ describe("goal show command", () => {describe("goal create duplicate prevention", () => {it("goal create checks for existing goal with same name", () => {- expect(goalContent).toContain("client.listTruth()");+ expect(goalContent).toContain("client.listGoals()");expect(goalContent).toContain("statement.toLowerCase()");});diff --git a/ix-cli/src/cli/__tests__/rank-filters.test.ts b/ix-cli/src/cli/__tests__/rank-filters.test.tsindex 4d5f6c02..207dd726 100644--- a/ix-cli/src/cli/__tests__/rank-filters.test.ts+++ b/ix-cli/src/cli/__tests__/rank-filters.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from "vitest";-import { applyPathFilters, applyKindExclusion, getSourceUri } from "../commands/rank.js";+import { applyPathFilters, applyKindExclusion, getSourceUri, pluralize } from "../commands/rank.js";describe("getSourceUri", () => {it("extracts from provenance.sourceUri", () => {@@ -76,3 +76,34 @@ describe("applyKindExclusion", () => {expect(result.length).toBe(4);});});++describe("pluralize", () => {+ it("pluralizes regular words", () => {+ expect(pluralize("method")).toBe("methods");+ expect(pluralize("module")).toBe("modules");+ expect(pluralize("function")).toBe("functions");+ });++ it("pluralizes words ending in 's'", () => {+ expect(pluralize("class")).toBe("classes");+ });++ it("pluralizes words ending in 'ss'", () => {+ expect(pluralize("class")).toBe("classes");+ });++ it("pluralizes words ending in 'ch', 'sh', 'x'", () => {+ expect(pluralize("match")).toBe("matches");+ expect(pluralize("index")).toBe("indexes");+ });++ it("pluralizes words ending in consonant + 'y'", () => {+ expect(pluralize("entry")).toBe("entries");+ expect(pluralize("factory")).toBe("factories");+ });++ it("does not change 'y' after vowel", () => {+ expect(pluralize("key")).toBe("keys");+ expect(pluralize("array")).toBe("arrays");+ });+});diff --git a/ix-cli/src/cli/__tests__/resolver-consistency.test.ts b/ix-cli/src/cli/__tests__/resolver-consistency.test.tsnew file mode 100644index 00000000..f0c056de--- /dev/null+++ b/ix-cli/src/cli/__tests__/resolver-consistency.test.ts@@ -0,0 +1,37 @@+import { describe, it, expect } from "vitest";+import * as fs from "node:fs";+import * as path from "node:path";++/**+ * Verify that all content-producing resolver commands support+ * --pick, --kind, and --path for consistent ambiguity resolution.+ */++const CONTENT_COMMANDS = ["read", "overview", "locate", "diff", "history"];++const commandFiles = CONTENT_COMMANDS.map(cmd => {+ const tsPath = path.resolve(__dirname, `../commands/${cmd}.ts`);+ return { cmd, tsPath, content: fs.readFileSync(tsPath, "utf-8") };+});++describe("resolver flag consistency across content commands", () => {+ for (const { cmd, content } of commandFiles) {+ describe(cmd, () => {+ it("supports --pick", () => {+ expect(content).toContain('"--pick <n>"');+ });++ it("supports --kind", () => {+ expect(content).toContain('"--kind <kind>"');+ });++ it("supports --path", () => {+ expect(content).toContain('"--path <path>"');+ });++ it("passes pick as number to resolver", () => {+ expect(content).toContain("parseInt(opts.pick, 10)");+ });+ });+ }+});diff --git a/ix-cli/src/cli/__tests__/task-status.test.ts b/ix-cli/src/cli/__tests__/task-status.test.tsnew file mode 100644index 00000000..df5b4225--- /dev/null+++ b/ix-cli/src/cli/__tests__/task-status.test.ts@@ -0,0 +1,131 @@+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__/watch-dedup.test.ts b/ix-cli/src/cli/__tests__/watch-dedup.test.tsnew file mode 100644index 00000000..a0fdc2da--- /dev/null+++ b/ix-cli/src/cli/__tests__/watch-dedup.test.ts@@ -0,0 +1,57 @@+import { describe, it, expect } from "vitest";+import * as fs from "node:fs";+import * as path from "node:path";+import { readFileContent } from "../commands/watch.js";++const watchTsPath = path.resolve(__dirname, "../commands/watch.ts");+const watchContent = fs.readFileSync(watchTsPath, "utf-8");++// ── Unit tests for readFileContent ──────────────────────────────────++describe("readFileContent", () => {+ it("reads an existing file", () => {+ const result = readFileContent(watchTsPath);+ expect(result).not.toBeNull();+ expect(result).toContain("readFileContent");+ });++ it("returns null for non-existent file", () => {+ const result = readFileContent("/tmp/ix-test-nonexistent-file-abc123.ts");+ expect(result).toBeNull();+ });+});++// ── Source-reading: watch.ts watcher correctness ────────────────────++describe("watch.ts watcher correctness", () => {+ it("uses content hash for deduplication", () => {+ expect(watchContent).toContain("hashContent");+ expect(watchContent).toContain("createHash");+ expect(watchContent).toContain('lastHash.get(filePath) === hash');+ });++ it("re-reads file at ingest time, not event time", () => {+ // readFileContent called inside ingestFile, not in the event handler+ expect(watchContent).toContain("readFileContent(filePath)");+ // The debounce callback does NOT read the file+ expect(watchContent).toContain("content is re-read at ingest time");+ });++ it("uses short debounce (300ms)", () => {+ expect(watchContent).toContain("DEBOUNCE_MS = 300");+ });++ it("tracks last hash per file", () => {+ expect(watchContent).toContain("lastHash");+ expect(watchContent).toContain("lastHash.set(filePath, hash)");+ });++ it("skips ingest when content hash unchanged", () => {+ expect(watchContent).toContain("unchanged (hash)");+ });++ it("coalesces rapid events per file via debounce map", () => {+ expect(watchContent).toContain("pending.get(fullPath)");+ expect(watchContent).toContain("clearTimeout(existing)");+ });+});diff --git a/ix-cli/src/cli/__tests__/workflow-attach.test.ts b/ix-cli/src/cli/__tests__/workflow-attach.test.tsindex 5efec3c3..95712432 100644--- a/ix-cli/src/cli/__tests__/workflow-attach.test.ts+++ b/ix-cli/src/cli/__tests__/workflow-attach.test.ts@@ -1,8 +1,8 @@import { describe, it, expect } from "vitest";import * as fs from "node:fs";import * as path from "node:path";-import { buildWorkflowAttachPatch, extractWorkflow } from "../commands/workflow.js";-import { isValidWorkflow, normalizeWorkflow } from "../commands/plan.js";+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");@@ -179,19 +179,16 @@ describe("extractWorkflow claims integration", () => {});});-describe("plan.ts workflow retrieval checks claims", () => {+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 checks claims for workflow", () => {- // Should check both field and statement keys for claim matching- expect(planContent).toContain('c.field === "workflow" || c.statement === "workflow"');+ it("task show uses extractWorkflow for workflow retrieval", () => {+ expect(planContent).toContain("extractWorkflow");});- it("plan next checks claims for workflow", () => {- // Should have two occurrences of workflow claim checking (task show + plan next)- const matches = planContent.match(/c\.field === "workflow" \|\| c\.statement === "workflow"/g);- expect(matches).not.toBeNull();- expect(matches!.length).toBeGreaterThanOrEqual(2);+ 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.tsnew file mode 100644index 00000000..18050fb0--- /dev/null+++ b/ix-cli/src/cli/__tests__/workflow-state.test.ts@@ -0,0 +1,156 @@+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/depends.ts b/ix-cli/src/cli/commands/depends.tsindex 3da38a86..5ce7115c 100644--- a/ix-cli/src/cli/commands/depends.ts+++ b/ix-cli/src/cli/commands/depends.ts@@ -3,121 +3,212 @@ import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";import { resolveFileOrEntity, printResolved, isRawId } from "../resolve.js";+import { stderr } from "../stderr.js";++// ── Tree types ──────────────────────────────────────────────────────++export interface DependencyNode {+ id: string;+ name: string;+ kind: string;+ resolved: boolean;+ relation: "called_by" | "imported_by";+ sourceEdge: "CALLS" | "IMPORTS";+ path?: string;+ children: DependencyNode[];+ cycle?: boolean;+}++const MAX_NODES = 200;+const DEFAULT_MAX_DEPTH = 20;++// ── Tree building ───────────────────────────────────────────────────++/**+ * Build a full dependency tree by recursive one-hop expansion.+ * Stops at: frontier end, cycle, depth limit, or node cap.+ */+export async function buildDependencyTree(+ client: IxClient,+ rootId: string,+ opts?: { maxDepth?: number; maxNodes?: number },+): Promise<{ tree: DependencyNode[]; truncated: boolean; nodesVisited: number; maxDepthReached: number }> {+ const maxDepth = opts?.maxDepth ?? DEFAULT_MAX_DEPTH;+ const maxNodes = opts?.maxNodes ?? MAX_NODES;+ const visited = new Set<string>([rootId]);+ let nodesVisited = 0;+ let truncated = false;+ let maxDepthReached = 0;++ async function expand(nodeId: string, depth: number): Promise<DependencyNode[]> {+ if (depth > maxDepth) { truncated = true; return []; }+ if (nodesVisited >= maxNodes) { truncated = true; return []; }++ maxDepthReached = Math.max(maxDepthReached, depth);++ const [callResult, importResult] = await Promise.all([+ client.expand(nodeId, { direction: "in", predicates: ["CALLS"], hops: 1 }),+ client.expand(nodeId, { direction: "in", predicates: ["IMPORTS"], hops: 1 }),+ ]);++ const children: DependencyNode[] = [];++ const processNodes = async (nodes: any[], relation: "called_by" | "imported_by", sourceEdge: "CALLS" | "IMPORTS") => {+ for (const n of nodes) {+ if (nodesVisited >= maxNodes) { truncated = true; break; }+ const name = n.name || n.attrs?.name || "";+ const resolved = !!name && !isRawId(name);+ const isCycle = visited.has(n.id);++ nodesVisited++;+ visited.add(n.id);++ const child: DependencyNode = {+ id: n.id,+ name: resolved ? name : n.id.slice(0, 8),+ kind: n.kind ?? "unknown",+ resolved,+ relation,+ sourceEdge,+ path: n.provenance?.source_uri ?? n.provenance?.sourceUri ?? n.attrs?.path ?? undefined,+ children: [],+ ...(isCycle ? { cycle: true } : {}),+ };++ if (!isCycle && resolved) {+ child.children = await expand(n.id, depth + 1);+ }++ children.push(child);+ }+ };++ await processNodes(callResult.nodes, "called_by", "CALLS");+ await processNodes(importResult.nodes, "imported_by", "IMPORTS");++ return children;+ }++ const tree = await expand(rootId, 1);+ return { tree, truncated, nodesVisited, maxDepthReached };+}++// ── Tree rendering ──────────────────────────────────────────────────++function renderTree(children: DependencyNode[], prefix: string, isLast: boolean[]): string[] {+ const lines: string[] = [];++ for (let i = 0; i < children.length; i++) {+ const child = children[i];+ const last = i === children.length - 1;+ const connector = last ? "└─ " : "├─ ";++ // Build indent from parent structure+ let indent = "";+ for (let j = 0; j < isLast.length; j++) {+ indent += isLast[j] ? " " : "│ ";+ }++ const kindStr = chalk.cyan((child.kind ?? "").padEnd(10));+ const nameStr = child.resolved ? chalk.bold(child.name) : chalk.dim(child.name);+ const cycleMark = child.cycle ? chalk.yellow(" (cycle)") : "";++ lines.push(`${indent}${connector}${kindStr} ${nameStr}${cycleMark}`);++ if (child.children.length > 0) {+ lines.push(...renderTree(child.children, prefix, [...isLast, last]));+ }+ }++ return lines;+}++// ── CLI command ─────────────────────────────────────────────────────export function registerDependsCommand(program: Command): void {program.command("depends <symbol>")- .description("Show what depends on the given entity (reverse CALLS + IMPORTS)")+ .description("Show downstream dependents of the given entity (full tree by default)").option("--kind <kind>", "Filter target entity by kind")+ .option("--path <path>", "Prefer symbols from files matching this path substring").option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")- .option("--depth <n>", "Traversal depth (default 1)", "1")- .option("--limit <n>", "Max results to show", "50")+ .option("--depth <n>", "Limit traversal depth (default: full tree)").option("--format <fmt>", "Output format (text|json)", "text")- .addHelpText("after", "\nExamples:\n ix depends verify_token\n ix depends AuthProvider --depth 2 --format json\n ix depends parser.py --kind file --limit 20")- .action(async (symbol: string, opts: { kind?: string; pick?: string; depth: string; limit: string; format: string }) => {+ .addHelpText("after", `\nExamples:+ ix depends verify_token+ ix depends pickBest --format json+ ix depends AuthProvider --depth 2+ ix depends parser.py --kind file`)+ .action(async (symbol: string, opts: { kind?: string; path?: string; pick?: string; depth?: string; format: string }) => {const client = new IxClient(getEndpoint());- const limit = parseInt(opts.limit, 10);- const resolveOpts = { kind: opts.kind, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };- const target = await resolveFileOrEntity(client, symbol, resolveOpts);- if (!target) return;-- const hops = parseInt(opts.depth, 10) || 1;- const [callResult, importResult] = await Promise.all([- client.expand(target.id, { direction: "in", predicates: ["CALLS"], hops }),- client.expand(target.id, { direction: "in", predicates: ["IMPORTS"], hops }),- ]);-- const seen = new Set<string>();- const callers: any[] = [];- const importers: any[] = [];-- for (const n of callResult.nodes) {- if (!seen.has(n.id)) {- seen.add(n.id);- callers.push({ ...n, via: "CALLS" });- }- }- for (const n of importResult.nodes) {- if (!seen.has(n.id)) {- seen.add(n.id);- importers.push({ ...n, via: "IMPORTS" });+ // Validate --pick+ if (opts.pick !== undefined) {+ const pickVal = parseInt(opts.pick, 10);+ if (isNaN(pickVal) || pickVal < 1) {+ stderr(`Invalid value for --pick: must be a positive integer.`);+ return;}}- const allDependents = [...callers, ...importers].slice(0, limit);+ const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };+ const target = await resolveFileOrEntity(client, symbol, resolveOpts);+ if (!target) return;- const mapDependent = (d: any) => {- const name = d.name || d.attrs?.name || "";- const resolved = !!name && !isRawId(name);- return {- name: resolved ? name : undefined,- kind: d.kind,- id: resolved ? d.id : undefined,- resolved,- via: d.via,- path: d.provenance?.source_uri ?? d.provenance?.sourceUri ?? d.attrs?.path ?? undefined,- ...(resolved ? { suggestedCommand: `ix explain "${name}"` } : { rawId: d.id }),- };- };+ const maxDepth = opts.depth ? parseInt(opts.depth, 10) : DEFAULT_MAX_DEPTH;++ const { tree, truncated, nodesVisited, maxDepthReached } = await buildDependencyTree(+ client, target.id, { maxDepth },+ );+ // ── JSON output ──────────────────────────────────────────────if (opts.format === "json") {- const results = allDependents.map(mapDependent);- const unresolvedCount = results.filter(r => !r.resolved).length;const output: any = {resolvedTarget: target,resolutionMode: target.resolutionMode,resultSource: "graph",- results,- summary: {- total: allDependents.length,- resolved: allDependents.length - unresolvedCount,- unresolved: unresolvedCount,- viaCalls: callers.length,- viaImports: importers.length,+ semantics: "downstream_dependents",+ tree,+ traversal: {+ nodesVisited,+ maxDepthReached,+ truncated,+ ...(opts.depth ? { depthLimit: maxDepth } : {}),},};- if (allDependents.length === 0) {- output.diagnostics = [{ code: "no_edges", message: `No CALLS or IMPORTS edges found pointing to resolved entity.` }];- } else if (unresolvedCount > 0) {- output.diagnostics = [{ code: "dangling_reference_filtered", message: `${unresolvedCount} dependent(s) could not be resolved to named entities.` }];+ if (tree.length === 0) {+ output.diagnostics = [{ code: "no_edges", message: `No downstream dependents found for resolved entity.` }];+ }+ if (truncated) {+ output.diagnostics = output.diagnostics ?? [];+ output.diagnostics.push({ code: "truncated", message: `Traversal truncated (depth: ${maxDepth}, node cap: ${MAX_NODES}).` });}console.log(JSON.stringify(output, null, 2));return;}+ // ── Text output ──────────────────────────────────────────────printResolved(target);- if (allDependents.length === 0) {- console.log(`Resolved to ${target.kind} ${target.name}; no CALLS/IMPORTS edges found at current graph state.`);++ if (tree.length === 0) {+ console.log(` No downstream dependents found at current graph state.`);return;}- if (callers.length > 0) {- console.log(chalk.bold(` via CALLS (${callers.length}):`));- for (const d of callers) {- const shortId = d.id?.slice(0, 8) ?? "";- const name = d.name || d.attrs?.name || "";- if (!name || isRawId(name)) {- console.log(` ${chalk.cyan((d.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${chalk.dim("(unresolved)")}`);- } else {- console.log(` ${chalk.cyan((d.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${name}`);- }- }+ console.log(chalk.bold(`\n Downstream dependents of ${target.kind} ${target.name}:\n`));++ const rootLine = ` ${chalk.cyan((target.kind ?? "").padEnd(10))} ${chalk.bold(target.name)}`;+ console.log(rootLine);++ const treeLines = renderTree(tree, " ", []);+ for (const line of treeLines) {+ console.log(` ${line}`);}- if (importers.length > 0) {- console.log(chalk.bold(` via IMPORTS (${importers.length}):`));- for (const d of importers) {- const shortId = d.id?.slice(0, 8) ?? "";- const name = d.name || d.attrs?.name || "";- if (!name || isRawId(name)) {- console.log(` ${chalk.cyan((d.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${chalk.dim("(unresolved)")}`);- } else {- console.log(` ${chalk.cyan((d.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${name}`);- }- }+ if (truncated) {+ console.log(chalk.yellow(`\n (tree truncated — ${nodesVisited} nodes visited, depth ${maxDepthReached})`));}- console.log(chalk.dim(`\n Total: ${allDependents.length} direct dependents`));+ console.log(chalk.dim(`\n ${nodesVisited} downstream dependents, depth ${maxDepthReached}`));});}diff --git a/ix-cli/src/cli/commands/diff.ts b/ix-cli/src/cli/commands/diff.tsindex 6621f967..6690c773 100644--- a/ix-cli/src/cli/commands/diff.ts+++ b/ix-cli/src/cli/commands/diff.ts@@ -1,13 +1,352 @@import * as fs from "node:fs";+import * as os from "node:os";import * as path from "node:path";+import { execFile } from "node:child_process";+import { promisify } from "node:util";import type { Command } from "commander";import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";-import { resolveFileOrEntity } from "../resolve.js";+import { resolveFileOrEntity, resolveEntityFull, printResolved, looksFileLike, type ResolvedEntity } from "../resolve.js";import { formatDiff } from "../format.js";import { stderr } from "../stderr.js";+const execFileAsync = promisify(execFile);++// ── Line-level diff (legacy, kept for backward compat) ─────────────++/** Simple sequential line diff producing `+ `, `- `, ` ` prefixed lines. */+export function computeLineDiff(before: string, after: string): string[] {+ const beforeLines = before.split("\n");+ const afterLines = after.split("\n");+ const result: string[] = [];+ const maxLen = Math.max(beforeLines.length, afterLines.length);++ for (let i = 0; i < maxLen; i++) {+ const bLine = i < beforeLines.length ? beforeLines[i] : undefined;+ const aLine = i < afterLines.length ? afterLines[i] : undefined;++ if (bLine === aLine) {+ result.push(` ${bLine}`);+ } else {+ if (bLine !== undefined) result.push(`- ${bLine}`);+ if (aLine !== undefined) result.push(`+ ${aLine}`);+ }+ }++ return result;+}++// ── File content loading ────────────────────────────────────────────++/** Load full file content from current disk. */+export function loadFileFromDisk(uri: string): string | null {+ const filePath = path.resolve(uri);+ try {+ if (!fs.existsSync(filePath)) return null;+ return fs.readFileSync(filePath, "utf-8");+ } catch {+ return null;+ }+}++/**+ * Load full file content at a specific timestamp via git.+ * Returns null if git fails or file doesn't exist at that point.+ */+export async function loadFileAtTimestamp(uri: string, timestamp: string): Promise<string | null> {+ const relPath = uri;+ try {+ const { stdout: commitHash } = await execFileAsync("git", [+ "log", "-1", "--format=%H", `--before=${timestamp}`, "--", relPath,+ ], { timeout: 10_000 });+ const hash = commitHash.trim();+ if (!hash) return null;+ const { stdout: fileContent } = await execFileAsync("git", [+ "show", `${hash}:${relPath}`,+ ], { timeout: 10_000 });+ return fileContent;+ } catch {+ return null;+ }+}++/**+ * Get the timestamp for a specific graph revision by scanning the patch list.+ * Falls back to current time if revision not found.+ */+async function getRevisionTimestamp(client: IxClient, rev: number): Promise<string | null> {+ try {+ const patches = await client.listPatches({ limit: 200 });+ // Find the patch at or closest to this revision+ const exact = patches.find((p: any) => p.rev === rev);+ if (exact?.timestamp) return exact.timestamp;+ // Find nearest rev <= target+ const earlier = patches+ .filter((p: any) => p.rev <= rev && p.timestamp)+ .sort((a: any, b: any) => b.rev - a.rev);+ if (earlier.length > 0) return (earlier[0] as any).timestamp;+ return null;+ } catch {+ return null;+ }+}++// ── Textual diff via git ────────────────────────────────────────────++/**+ * Compute a unified diff between two strings using git diff --no-index.+ * Returns parsed hunk lines (starting with @@, +, -, or space).+ * Returns empty array if contents are identical.+ */+export async function computeTextualDiff(+ before: string,+ after: string,+): Promise<string[]> {+ const tmpDir = os.tmpdir();+ const ts = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;+ const beforePath = path.join(tmpDir, `ix-diff-a-${ts}`);+ const afterPath = path.join(tmpDir, `ix-diff-b-${ts}`);+ fs.writeFileSync(beforePath, before);+ fs.writeFileSync(afterPath, after);++ try {+ await execFileAsync("git", [+ "diff", "--no-index", "--unified=3", "--no-color",+ "--", beforePath, afterPath,+ ], { timeout: 10_000 });+ // Exit code 0 = identical+ return [];+ } catch (err: any) {+ // Exit code 1 = files differ (normal for git diff --no-index)+ const stdout: string = err.stdout ?? "";+ if (!stdout) return [];+ return parseDiffOutput(stdout);+ } finally {+ try { fs.unlinkSync(beforePath); } catch {}+ try { fs.unlinkSync(afterPath); } catch {}+ }+}++/** Parse git diff output — keep only hunk headers and content lines. */+function parseDiffOutput(raw: string): string[] {+ const lines = raw.split("\n");+ const result: string[] = [];+ let inHunk = false;+ for (const line of lines) {+ if (line.startsWith("@@")) {+ inHunk = true;+ result.push(line);+ } else if (inHunk) {+ if (line.startsWith("diff ") || line.startsWith("index ") ||+ line.startsWith("--- ") || line.startsWith("+++ ") ||+ line.startsWith("\\ No newline")) {+ // New diff section or metadata — skip+ if (line.startsWith("diff ")) inHunk = false;+ continue;+ }+ result.push(line);+ }+ }+ return result;+}++/**+ * Slice textual diff hunks to only include lines within a line range.+ * Returns only hunks that overlap with [lineStart, lineEnd].+ */+function sliceHunksToSpan(diffLines: string[], lineStart: number, lineEnd: number): string[] {+ const result: string[] = [];+ let afterLineNo = 0;+ let inRange = false;++ for (const line of diffLines) {+ if (line.startsWith("@@")) {+ // Parse hunk header: @@ -a,b +c,d @@+ const match = line.match(/@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);+ if (match) {+ afterLineNo = parseInt(match[1], 10);+ // Check if this hunk overlaps with our range+ inRange = false; // Will be set per-line+ continue;+ }+ }++ if (line.startsWith("+")) {+ if (afterLineNo >= lineStart && afterLineNo <= lineEnd) {+ if (!inRange) {+ result.push(`@@ line ${afterLineNo} @@`);+ inRange = true;+ }+ result.push(line);+ }+ afterLineNo++;+ } else if (line.startsWith("-")) {+ // Removed lines: if we're in range, include them+ if (afterLineNo >= lineStart && afterLineNo <= lineEnd + 1) {+ if (!inRange) {+ result.push(`@@ line ${afterLineNo} @@`);+ inRange = true;+ }+ result.push(line);+ }+ } else {+ // Context line+ if (afterLineNo >= lineStart && afterLineNo <= lineEnd) {+ if (inRange) {+ result.push(line);+ }+ } else {+ inRange = false;+ }+ afterLineNo++;+ }+ }+ return result;+}++// ── Source span reading (for graph-driven diff) ─────────────────────++/** Try to read source lines from disk using entity provenance and line spans. */+function readSourceSpan(node: any): string | null {+ if (!node) return null;+ const uri: string = node.provenance?.source_uri ?? node.provenance?.sourceUri ?? "";+ if (!uri) return null;++ const attrs = node.attrs ?? {};+ const lineStart = attrs.line_start ?? attrs.lineStart;+ const lineEnd = attrs.line_end ?? attrs.lineEnd;+ if (lineStart == null || lineEnd == null) return null;++ const filePath = path.resolve(uri);+ try {+ if (!fs.existsSync(filePath)) return null;+ const content = fs.readFileSync(filePath, "utf-8");+ const lines = content.split("\n");+ const start = Math.max(0, Number(lineStart) - 1);+ const end = Math.min(lines.length, Number(lineEnd));+ if (start >= end) return null;+ return lines.slice(start, end).join("\n");+ } catch {+ return null;+ }+}++/**+ * Read source span at a historical point in time using git.+ * Falls back to readSourceSpan (current disk) if git fails.+ */+export async function readSourceSpanAtTimestamp(node: any): Promise<string | null> {+ if (!node) return null;+ const uri: string = node.provenance?.source_uri ?? node.provenance?.sourceUri ?? "";+ if (!uri) return null;++ const attrs = node.attrs ?? {};+ const lineStart = attrs.line_start ?? attrs.lineStart;+ const lineEnd = attrs.line_end ?? attrs.lineEnd;+ if (lineStart == null || lineEnd == null) return null;++ const timestamp = node.updatedAt ?? node.createdAt;+ if (!timestamp) return readSourceSpan(node);++ const relPath = uri;+ try {+ const { stdout: commitHash } = await execFileAsync("git", [+ "log", "-1", "--format=%H", `--before=${timestamp}`, "--", relPath,+ ], { timeout: 10_000 });+ const hash = commitHash.trim();+ if (!hash) return readSourceSpan(node);++ const { stdout: fileContent } = await execFileAsync("git", [+ "show", `${hash}:${relPath}`,+ ], { timeout: 10_000 });++ const lines = fileContent.split("\n");+ const start = Math.max(0, Number(lineStart) - 1);+ const end = Math.min(lines.length, Number(lineEnd));+ if (start >= end) return readSourceSpan(node);+ return lines.slice(start, end).join("\n");+ } catch {+ return readSourceSpan(node);+ }+}++// ── Get file URI from resolved entity or graph changes ──────────────++function getFileUri(resolved: ResolvedEntity | null, changes: any[]): string | null {+ // From resolved entity path+ if (resolved?.path) return resolved.path;++ // From graph changes provenance+ for (const c of changes) {+ const node = c.atToRev ?? c.atFromRev;+ const uri = node?.provenance?.source_uri ?? node?.provenance?.sourceUri;+ if (uri) return uri;+ }+ return null;+}++function getLineSpan(resolved: ResolvedEntity | null, changes: any[]): { start: number; end: number } | null {+ // Symbol targets (non-file kinds) have line spans+ if (resolved && resolved.kind !== "file") {+ for (const c of changes) {+ const node = c.atToRev ?? c.atFromRev;+ const attrs = node?.attrs ?? {};+ const lineStart = attrs.line_start ?? attrs.lineStart;+ const lineEnd = attrs.line_end ?? attrs.lineEnd;+ if (lineStart != null && lineEnd != null) {+ return { start: Number(lineStart), end: Number(lineEnd) };+ }+ }+ }+ return null;+}++/**+ * Get line spans for both before and after revisions of a symbol.+ * Returns null if the target is a file or spans can't be determined.+ */+function getSymbolSpans(resolved: ResolvedEntity | null, changes: any[]): {+ before: { start: number; end: number } | null;+ after: { start: number; end: number } | null;+} | null {+ if (!resolved || resolved.kind === "file") return null;++ let before: { start: number; end: number } | null = null;+ let after: { start: number; end: number } | null = null;++ for (const c of changes) {+ if (c.atFromRev) {+ const attrs = c.atFromRev.attrs ?? {};+ const ls = attrs.line_start ?? attrs.lineStart;+ const le = attrs.line_end ?? attrs.lineEnd;+ if (ls != null && le != null) before = { start: Number(ls), end: Number(le) };+ }+ if (c.atToRev) {+ const attrs = c.atToRev.attrs ?? {};+ const ls = attrs.line_start ?? attrs.lineStart;+ const le = attrs.line_end ?? attrs.lineEnd;+ if (ls != null && le != null) after = { start: Number(ls), end: Number(le) };+ }+ }++ if (!before && !after) return null;+ return { before, after };+}++/**+ * Extract a slice of lines from full file content.+ * lineStart and lineEnd are 1-based inclusive.+ */+function sliceContent(content: string, lineStart: number, lineEnd: number): string {+ const lines = content.split("\n");+ const start = Math.max(0, lineStart - 1);+ const end = Math.min(lines.length, lineEnd);+ return lines.slice(start, end).join("\n");+}++// ── CLI command ─────────────────────────────────────────────────────+export function registerDiffCommand(program: Command): void {program.command("diff <fromRev> <toRev> [target]")@@ -18,28 +357,60 @@ export function registerDiffCommand(program: Command): void {.option("--limit <n>", "Max changes to return (default 100)").option("--full", "Return all changes (no limit)").option("--format <fmt>", "Output format (text|json)", "text")+ .option("--kind <kind>", "Filter target entity by kind")+ .option("--path <path>", "Prefer symbols from files matching this path substring")+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)").addHelpText("after", `\nExamples:ix diff 3 5ix diff 3 5 ix-cli/src/cli/commands/decide.tsix diff 3 5 decide.ts --content- ix diff 3 5 buildDecisionPatch+ ix diff 3 5 buildDecisionPatch --content --pick 1ix diff 3 5 --summary`).action(async (fromRev: string, toRev: string, target: string | undefined, opts: {entity?: string; summary?: boolean; content?: boolean; limit?: string; full?: boolean; format: string;+ kind?: string; path?: string; pick?: string;}) => {const client = new IxClient(getEndpoint());const from = parseInt(fromRev, 10);const to = parseInt(toRev, 10);// Resolve the scope entity from positional target or --entity flag+ const resolveOpts = {+ kind: opts.kind,+ path: opts.path,+ pick: opts.pick ? parseInt(opts.pick, 10) : undefined,+ };let entityId: string | undefined = opts.entity;+ let resolved: ResolvedEntity | null = null;if (target && !entityId) {- const resolved = await resolveFileOrEntity(client, target);- if (!resolved) return;- entityId = resolved.id;- if (opts.format !== "json") {- stderr(`${chalk.dim("Scoped to:")} ${chalk.cyan(resolved.kind)} ${chalk.bold(resolved.name)}\n`);+ if (opts.format === "json") {+ // Use full resolver for structured JSON ambiguity output+ const allKinds = ["file", "class", "object", "trait", "interface", "module", "function", "method"];+ const isFile = looksFileLike(target);+ if (!isFile) {+ const fullResult = await resolveEntityFull(client, target, allKinds, resolveOpts);+ if (fullResult.resolved) {+ resolved = fullResult.entity;+ } else if (fullResult.ambiguous) {+ console.log(JSON.stringify(fullResult.result, null, 2));+ return;+ } else {+ console.log(JSON.stringify({ error: `No entity found matching "${target}".` }, null, 2));+ return;+ }+ } else {+ resolved = await resolveFileOrEntity(client, target, resolveOpts);+ if (!resolved) {+ console.log(JSON.stringify({ error: `No entity found matching "${target}".` }, null, 2));+ return;+ }+ }+ } else {+ resolved = await resolveFileOrEntity(client, target, resolveOpts);+ if (!resolved) return;+ printResolved(resolved);}+ entityId = resolved.id;}if (opts.summary) {@@ -62,20 +433,145 @@ export function registerDiffCommand(program: Command): void {const limit = opts.full ? undefined : (opts.limit ? parseInt(opts.limit, 10) : undefined);const result: any = await client.diff(from, to, { entityId, limit });+ const changes: any[] = result.changes ?? [];- if (opts.format === "json") {- if (opts.content) {- // Augment each change with source content when available- const changes = (result as any).changes ?? [];+ // ── Content mode: textual diff is primary ───────────────────────+ if (opts.content) {+ // Try to get file URI for textual diffing+ const fileUri = getFileUri(resolved, changes);++ if (fileUri) {+ // Load full file content at both revisions+ const beforeFile = await loadContentAtRev(client, fileUri, from, changes, "from");+ const afterFile = await loadContentAtRev(client, fileUri, to, changes, "to");++ if (beforeFile !== null && afterFile !== null) {+ const symbolSpans = getSymbolSpans(resolved, changes);+ let diffLines: string[];+ let diffMode: string;+ let displaySpan: { start: number; end: number } | null = null;++ if (symbolSpans) {+ // Symbol target: extract symbol body at each revision and diff those+ const beforeBody = symbolSpans.before+ ? sliceContent(beforeFile, symbolSpans.before.start, symbolSpans.before.end)+ : "";+ const afterBody = symbolSpans.after+ ? sliceContent(afterFile, symbolSpans.after.start, symbolSpans.after.end)+ : "";+ diffLines = await computeTextualDiff(beforeBody, afterBody);+ diffMode = "symbol";+ displaySpan = symbolSpans.after ?? symbolSpans.before;+ } else {+ // File target: diff the whole file+ diffLines = await computeTextualDiff(beforeFile, afterFile);+ diffMode = "file";+ }++ if (opts.format === "json") {+ const jsonResult: any = {+ ...result,+ textualDiff: diffLines,+ hasTextualChanges: diffLines.length > 0,+ diffMode,+ };+ if (displaySpan) {+ jsonResult.lineSpan = displaySpan;+ }+ console.log(JSON.stringify(jsonResult, null, 2));+ } else {+ console.log(chalk.cyan.bold(`\nDiff: rev ${from} → ${to}`));+ if (diffLines.length === 0) {+ console.log(chalk.dim(" No textual changes detected."));+ } else {+ console.log(` ${chalk.dim("file:")} ${fileUri}`);+ if (displaySpan) {+ console.log(` ${chalk.dim(`scoped to lines ${displaySpan.start}-${displaySpan.end}`)}`);+ }+ console.log();+ for (const line of diffLines) {+ if (line.startsWith("@@")) {+ console.log(` ${chalk.cyan(line)}`);+ } else if (line.startsWith("+")) {+ console.log(` ${chalk.green(line)}`);+ } else if (line.startsWith("-")) {+ console.log(` ${chalk.red(line)}`);+ } else {+ console.log(` ${line}`);+ }+ }+ }++ // Also show graph-level changes if any+ if (changes.length > 0) {+ console.log(chalk.dim(`\n Graph changes: ${changes.length}`));+ for (const c of changes) {+ const name = c.atToRev?.name ?? c.atFromRev?.name ?? "?";+ const kind = c.atToRev?.kind ?? c.atFromRev?.kind ?? "unknown";+ const typeChar = c.changeType === "added" ? "+" : c.changeType === "removed" ? "-" : "~";+ console.log(` ${chalk.dim(typeChar)} ${chalk.dim(kind)} ${chalk.dim(name)}`);+ }+ }+ console.log();+ }+ return;+ }+ }++ // Fallback: graph-driven content diff (no file URI or git failed)+ if (opts.format === "json") {for (const c of changes) {- const node = c.atToRev ?? c.atFromRev;- const source = readSourceSpan(node);- if (source) c.sourceContent = source;+ const beforeSource = await readSourceSpanAtTimestamp(c.atFromRev);+ const afterSource = readSourceSpan(c.atToRev);+ if (beforeSource !== null) c.sourceContentBefore = beforeSource;+ if (afterSource !== null) c.sourceContentAfter = afterSource;+ if (beforeSource !== null && afterSource !== null) {+ c.sourceDiff = await computeTextualDiff(beforeSource, afterSource);+ } else if (beforeSource !== null || afterSource !== null) {+ c.sourceContent = afterSource ?? beforeSource;+ }+ }+ console.log(JSON.stringify(result, null, 2));+ } else {+ await formatDiffContent(result);+ }+ return;+ }++ // ── Non-content mode ────────────────────────────────────────────+ // If target is a file/symbol and graph shows no changes,+ // check for textual changes as a supplementary signal.+ if (resolved && changes.length === 0) {+ const fileUri = getFileUri(resolved, changes) ?? resolved.path;+ if (fileUri) {+ const beforeContent = await loadContentAtRev(client, fileUri, from, changes, "from");+ const afterContent = await loadContentAtRev(client, fileUri, to, changes, "to");++ if (beforeContent !== null && afterContent !== null && beforeContent !== afterContent) {+ const diffLines = await computeTextualDiff(beforeContent, afterContent);+ const changeCount = diffLines.filter(l => l.startsWith("+") || l.startsWith("-")).length;++ if (opts.format === "json") {+ console.log(JSON.stringify({+ ...result,+ textualChanges: {+ detected: true,+ lineChanges: changeCount,+ note: "Textual changes detected but not captured by graph parser (e.g. comments, whitespace).",+ },+ }, null, 2));+ } else {+ const name = resolved.name ?? fileUri;+ console.log(chalk.yellow(`${name} modified (${changeCount} textual changes — not captured by parser)`));+ console.log(chalk.dim(" Use --content to see full diff."));+ }+ return;}}+ }++ if (opts.format === "json") {console.log(JSON.stringify(result, null, 2));- } else if (opts.content) {- formatDiffContent(result);} else {if (result.truncated) {console.log(chalk.yellow(`Showing ${result.changes.length} of ${result.totalChanges} changes. Use --full to see all.\n`));@@ -85,34 +581,75 @@ export function registerDiffCommand(program: Command): void {});}-/** Try to read source lines from disk using entity provenance and line spans. */-function readSourceSpan(node: any): string | null {- if (!node) return null;- const uri: string = node.provenance?.source_uri ?? node.provenance?.sourceUri ?? "";- if (!uri) return null;-- const attrs = node.attrs ?? {};- const lineStart = attrs.line_start ?? attrs.lineStart;- const lineEnd = attrs.line_end ?? attrs.lineEnd;- if (lineStart == null || lineEnd == null) return null;+/**+ * Resolve the "before" timestamp for textual diffing.+ * Tries: graph change snapshots → patch list → null.+ */+async function resolveFromTimestamp(+ client: IxClient,+ fromRev: number,+ changes: any[],+): Promise<string | null> {+ // Try to get timestamp from graph change snapshots+ for (const c of changes) {+ const ts = c.atFromRev?.updatedAt ?? c.atFromRev?.createdAt;+ if (ts) return ts;+ }+ // Fall back to patch list+ return getRevisionTimestamp(client, fromRev);+}- // Resolve path relative to cwd- const filePath = path.resolve(uri);+/**+ * Resolve the "after" timestamp for textual diffing.+ * Tries: graph change snapshots → patch list → null.+ * Returns null if toRev is the latest revision (caller should use disk).+ */+async function resolveToTimestamp(+ client: IxClient,+ toRev: number,+ changes: any[],+): Promise<string | null> {+ // Check if toRev is the latest revisiontry {- if (!fs.existsSync(filePath)) return null;- const content = fs.readFileSync(filePath, "utf-8");- const lines = content.split("\n");- const start = Math.max(0, Number(lineStart) - 1);- const end = Math.min(lines.length, Number(lineEnd));- if (start >= end) return null;- return lines.slice(start, end).join("\n");- } catch {- return null;+ const patches = await client.listPatches({ limit: 1 });+ if (patches.length > 0 && (patches[0] as any).rev === toRev) {+ return null; // Latest rev — use disk+ }+ } catch {}+ // Try to get timestamp from graph change snapshots+ for (const c of changes) {+ const ts = c.atToRev?.updatedAt ?? c.atToRev?.createdAt;+ if (ts) return ts;+ }+ // Fall back to patch list+ return getRevisionTimestamp(client, toRev);+}++/**+ * Load file content for a specific revision.+ * Uses disk for latest revision, git for historical revisions.+ */+async function loadContentAtRev(+ client: IxClient,+ fileUri: string,+ rev: number,+ changes: any[],+ side: "from" | "to",+): Promise<string | null> {+ if (side === "from") {+ const ts = await resolveFromTimestamp(client, rev, changes);+ return ts ? loadFileAtTimestamp(fileUri, ts) : loadFileFromDisk(fileUri);+ } else {+ const ts = await resolveToTimestamp(client, rev, changes);+ // null timestamp = latest rev = use disk+ return ts ? loadFileAtTimestamp(fileUri, ts) : loadFileFromDisk(fileUri);}}+// ── Graph-driven content display (fallback) ─────────────────────────+/** Render detailed attribute-level changes with source code for each entity. */-function formatDiffContent(result: any): void {+async function formatDiffContent(result: any): Promise<void> {console.log(chalk.cyan.bold(`\nDiff: rev ${result.fromRev} → ${result.toRev}`));const changes = result.changes ?? [];if (changes.length === 0) {@@ -140,13 +677,36 @@ function formatDiffContent(result: any): void {diffAttrs(" ", before.attrs ?? {}, after.attrs ?? {});}- // Show source code from disk when available- const source = readSourceSpan(activeNode);- if (source) {- const lineStart = (activeNode.attrs?.line_start ?? activeNode.attrs?.lineStart) || "?";- console.log(` ${chalk.dim(`source (L${lineStart}):`)} `);- for (const line of source.split("\n")) {- console.log(` ${chalk.dim("│")} ${line}`);+ // Textual diff using git for historical before content+ const beforeSource = await readSourceSpanAtTimestamp(before);+ const afterSource = readSourceSpan(after);+ if (beforeSource !== null && afterSource !== null && c.changeType === "modified") {+ const diffLines = await computeTextualDiff(beforeSource, afterSource);+ if (diffLines.length > 0) {+ console.log(` ${chalk.dim("source diff:")}`);+ for (const line of diffLines) {+ if (line.startsWith("@@")) {+ console.log(` ${chalk.dim("│")} ${chalk.cyan(line)}`);+ } else if (line.startsWith("+")) {+ console.log(` ${chalk.dim("│")} ${chalk.green(line)}`);+ } else if (line.startsWith("-")) {+ console.log(` ${chalk.dim("│")} ${chalk.red(line)}`);+ } else {+ console.log(` ${chalk.dim("│")} ${line}`);+ }+ }+ } else {+ console.log(` ${chalk.dim("(no textual changes in source span)")}`);+ }+ } else {+ // Single-revision fallback+ const source = readSourceSpan(activeNode);+ if (source) {+ const lineStart = (activeNode.attrs?.line_start ?? activeNode.attrs?.lineStart) || "?";+ console.log(` ${chalk.dim(`source (L${lineStart}):`)} `);+ for (const line of source.split("\n")) {+ console.log(` ${chalk.dim("│")} ${line}`);+ }}}}@@ -163,6 +723,7 @@ function printAttrs(indent: string, attrs: Record<string, unknown> | undefined):}function diffAttrs(indent: string, before: Record<string, unknown>, after: Record<string, unknown>): void {+ //symbol testconst allKeys = new Set([...Object.keys(before), ...Object.keys(after)]);for (const key of allKeys) {const bVal = before[key];@@ -180,3 +741,6 @@ function diffAttrs(indent: string, before: Record<string, unknown>, after: Recor}}}+// Let's see if this works+// how about this+// new comment\ No newline at end of filediff --git a/ix-cli/src/cli/commands/goal.ts b/ix-cli/src/cli/commands/goal.tsindex 94dcac26..c54df92c 100644--- a/ix-cli/src/cli/commands/goal.ts+++ b/ix-cli/src/cli/commands/goal.ts@@ -8,7 +8,7 @@ import { stderr } from "../stderr.js";export function registerGoalCommand(program: Command): void {const goal = program.command("goal")- .description("Manage project goals (aliases for ix truth)")+ .description("Manage project goals").addHelpText("after",`\nSubcommands:@@ -35,7 +35,7 @@ Examples:const client = new IxClient(getEndpoint());// Check duplicate goal name- const existing = await client.listTruth();+ const existing = await client.listGoals();const dup = existing.find((i: any) => (i.name || i.statement || "").toLowerCase() === statement.toLowerCase(),);@@ -45,7 +45,7 @@ Examples:return;}- const result = await client.createTruth(statement, opts.parent);+ const result = await client.createGoal(statement, opts.parent);if (opts.format === "json") {console.log(JSON.stringify(result, null, 2));} else {@@ -65,7 +65,7 @@ Examples:try {goalId = await client.resolvePrefix(ref);} catch {- const intents = await client.listTruth();+ const intents = await client.listGoals();const match = intents.find((i: any) => (i.name || i.statement || "").toLowerCase() === ref.toLowerCase(),);@@ -114,7 +114,7 @@ Examples:.option("--format <fmt>", "Output format (text|json)", "text").action(async (opts: { status: string; format: string }) => {const client = new IxClient(getEndpoint());- let intents = await client.listTruth();+ let intents = await client.listGoals();if (opts.status === "active") {// Filter to goals that have at least one plan with pending tasksdiff --git a/ix-cli/src/cli/commands/goals.ts b/ix-cli/src/cli/commands/goals.tsindex 7266b739..ef8f84ab 100644--- a/ix-cli/src/cli/commands/goals.ts+++ b/ix-cli/src/cli/commands/goals.ts@@ -11,7 +11,7 @@ export function registerGoalsCommand(program: Command): void {.option("--format <fmt>", "Output format (text|json)", "text").action(async (opts: { status: string; format: string }) => {const client = new IxClient(getEndpoint());- let intents = await client.listTruth();+ let intents = await client.listGoals();if (opts.status === "active") {const activeGoalIds = new Set<string>();diff --git a/ix-cli/src/cli/commands/history.ts b/ix-cli/src/cli/commands/history.tsindex 87dce290..b90f1526 100644--- a/ix-cli/src/cli/commands/history.ts+++ b/ix-cli/src/cli/commands/history.ts@@ -10,15 +10,18 @@ export function registerHistoryCommand(program: Command): void {.command("history <target>").description("Show provenance chain for a file or entity").option("--kind <kind>", "Filter target entity by kind")+ .option("--path <path>", "Prefer symbols from files matching this path substring")+ .option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)").option("--format <fmt>", "Output format (text|json)", "text").addHelpText("after", `\nExamples:ix history ix-cli/src/cli/commands/decide.tsix history decide.tsix history IngestionService --kind classix history <entity-uuid>`)- .action(async (target: string, opts: { kind?: string; format: string }) => {+ .action(async (target: string, opts: { kind?: string; path?: string; pick?: string; format: string }) => {const client = new IxClient(getEndpoint());- const resolved = await resolveFileOrEntity(client, target, opts);+ const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };+ const resolved = await resolveFileOrEntity(client, target, resolveOpts);if (!resolved) return;if (opts.format !== "json") printResolved(resolved);diff --git a/ix-cli/src/cli/commands/plan.ts b/ix-cli/src/cli/commands/plan.tsindex bbb4d948..540d2d6b 100644--- a/ix-cli/src/cli/commands/plan.ts+++ b/ix-cli/src/cli/commands/plan.ts@@ -1,93 +1,30 @@import type { Command } from "commander";import type { GraphPatchPayload, PatchOp } from "../../client/types.js";-import { execFile } from "node:child_process";-import { promisify } from "node:util";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";import { deterministicId } from "../github/transform.js";import { resolveEntity, printResolved } from "../resolve.js";import { stderr } from "../stderr.js";import chalk from "chalk";--const execFileAsync = promisify(execFile);--// ── Types ───────────────────────────────────────────────────────────--export interface StagedWorkflow {- discover?: string[];- implement?: string[];- validate?: string[];-}--export const VALID_WORKFLOW_STAGES = ["discover", "implement", "validate"];--export function isValidWorkflow(w: unknown): w is string[] | StagedWorkflow {- if (Array.isArray(w)) return w.every(s => typeof s === "string");- 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;-}--/** Run workflow stages — constrained to ix commands only. */-interface WorkflowRunResult {- stage: string;- command: string;- status: "ok" | "error" | "skipped";- output?: unknown;- error?: string;-}--async function executeIxCommand(cmd: string): Promise<unknown> {- const trimmed = cmd.replace(/^ix\s+/, "");- const args = trimmed.split(/\s+/);- if (!args.includes("--format") && !args.includes("-f")) {- args.push("--format", "json");- }- const { stdout } = await execFileAsync("ix", args, {- maxBuffer: 10 * 1024 * 1024,- timeout: 60_000,- });- try {- return JSON.parse(stdout);- } catch {- return stdout.trim();- }-}--async function runWorkflowStages(- workflow: StagedWorkflow,- stages: string[],-): Promise<WorkflowRunResult[]> {- const results: WorkflowRunResult[] = [];- for (const stage of stages) {- const cmds = workflow[stage as keyof StagedWorkflow];- if (!cmds || cmds.length === 0) continue;- for (const cmd of cmds) {- if (!cmd.trimStart().startsWith("ix ") && cmd.trim() !== "ix") {- results.push({ stage, command: cmd, status: "skipped", error: "Only ix commands are allowed" });- continue;- }- if (/[|;&`$()]/.test(cmd)) {- results.push({ stage, command: cmd, status: "skipped", error: "Shell operators not allowed" });- continue;- }- try {- const output = await executeIxCommand(cmd);- results.push({ stage, command: cmd, status: "ok", output });- } catch (err: any) {- results.push({ stage, command: cmd, status: "error", error: err.message || String(err) });- }- }- }- return results;-}+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) ──────────────────────────@@ -229,17 +166,17 @@ export function buildTaskUpdatePatch(taskId: string, status: string): GraphPatchreturn makePatchEnvelope(ops, `Update task ${taskId} status to ${status}`);}-// ── CLI commands ───────────────────────────────────────────────────--const VALID_STATUSES = ["pending", "in_progress", "blocked", "done", "abandoned"];+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}`);+}-const STATUS_ICONS: Record<string, string> = {- pending: "○",- in_progress: "◐",- blocked: "✖",- done: "●",- abandoned: "⊘",-};+// ── CLI commands ───────────────────────────────────────────────────export function registerPlanCommand(program: Command): void {const plan = program@@ -279,8 +216,8 @@ Examples:try {goalId = await client.resolvePrefix(opts.goal);} catch {- const intents = await client.listTruth();- const match = intents.find(+ const goals = await client.listGoals();+ const match = goals.find((i: any) => (i.name || i.statement || "").toLowerCase() === opts.goal.toLowerCase(),);if (match) {@@ -427,13 +364,14 @@ Examples:predicates: ["PLAN_HAS_TASK"],});- const tasks: { id: string; title: string; status: string; dependsOn: string[] }[] = [];+ 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 depsconst entityDetail = await client.entity(node.id);const status = getTaskStatus(entityDetail);+ const wfState = getWorkflowState(entityDetail);// Expand DEPENDS_ON for this taskconst { edges: depEdges } = await client.expand(node.id, {@@ -447,6 +385,7 @@ Examples:title: node.name,status,dependsOn,+ workflowState: wfState,});}@@ -493,7 +432,11 @@ Examples:if (opts.format === "json") {console.log(JSON.stringify({planId: resolvedPlanId,- tasks: tasks.map(t => ({ title: t.title, status: t.status, id: t.id })),+ 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,@@ -501,7 +444,8 @@ Examples:} else {for (const t of tasks) {const icon = STATUS_ICONS[t.status] ?? "?";- console.log(` ${icon} ${chalk.dim(`[${t.status}]`.padEnd(14))} ${t.title}`);+ 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}`);@@ -573,17 +517,12 @@ Examples:// ── 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);- // Check claims first (for workflows attached via `ix workflow attach`), then attrs- const wfClaim = detail.claims?.find(- (c: any) => c.field === "workflow" || c.statement === "workflow"- );- const rawWorkflow = wfClaim ? (wfClaim as any).value : detail.node?.attrs?.workflow;- if (rawWorkflow) {- workflowData = normalizeWorkflow(rawWorkflow as string[] | StagedWorkflow);- }+ workflowData = extractWorkflow(detail.node, detail.claims);+ nextWorkflowState = getWorkflowState(detail);}if (nextActionable && opts.runWorkflow && workflowData) {@@ -609,6 +548,9 @@ Examples:if (workflowData) {result.workflow = workflowData;}+ if (nextWorkflowState) {+ result.workflowState = nextWorkflowState;+ }if (workflowResults) {result.workflowResults = workflowResults;}@@ -689,19 +631,9 @@ Examples:const details = await client.entity(resolvedTaskId);const node = details.node as any;-- 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 ?? "pending")- : (node.attrs?.status ?? "pending");-- // Check claims first (for workflows attached via `ix workflow attach`), then attrs- const workflowClaim = details.claims?.find(- (c: any) => c.field === "workflow" || c.statement === "workflow"- );- const rawWorkflow = (workflowClaim ? (workflowClaim as any).value : node.attrs?.workflow) as string[] | StagedWorkflow | undefined;+ const status = getTaskStatus(details);+ const workflow = extractWorkflow(node, details.claims);+ const workflowState = getWorkflowState(details);if (opts.format === "json") {const result: Record<string, unknown> = {@@ -711,20 +643,30 @@ Examples:created_at: node.attrs?.created_at ?? node.createdAt,};if (opts.withWorkflow) {- result.workflow = rawWorkflow- ? normalizeWorkflow(rawWorkflow)- : {};+ 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 (opts.withWorkflow && rawWorkflow) {- const staged = normalizeWorkflow(rawWorkflow);- console.log(chalk.dim(" Workflow:"));+ if (workflowState) {+ const parts: string[] = [];for (const stage of VALID_WORKFLOW_STAGES) {- const cmds = staged[stage as keyof StagedWorkflow];+ 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) {@@ -738,39 +680,112 @@ Examples:task.command("update <taskId>")- .description("Update a task's status")- .requiredOption("--status <status>", `Status (${VALID_STATUSES.join("|")})`)+ .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; format: string }) => {- if (!VALID_STATUSES.includes(opts.status)) {+ .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());- const patch = buildTaskUpdatePatch(taskId, opts.status);- const result = await client.commitPatch(patch);++ // 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") {- console.log(JSON.stringify({ taskId, status: opts.status, rev: result.rev }, null, 2));+ 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 {- console.log(`Task ${taskId.slice(0, 8)} updated to ${opts.status} (rev ${result.rev})`);+ 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)}`);+ }+ }+ }}});}-// ── Helpers ────────────────────────────────────────────────────────--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";-}diff --git a/ix-cli/src/cli/commands/rank.ts b/ix-cli/src/cli/commands/rank.tsindex a2a40ae2..6ad63ae9 100644--- a/ix-cli/src/cli/commands/rank.ts+++ b/ix-cli/src/cli/commands/rank.ts@@ -48,6 +48,64 @@ export function applyKindExclusion(nodes: any[], excludeKinds: string[]): any[]return nodes.filter((node: any) => !excluded.has(node.kind));}+/** Pluralize an entity kind for display */+export function pluralize(kind: string): string {+ if (kind.endsWith("ss") || kind.endsWith("ch") || kind.endsWith("sh") || kind.endsWith("x")) return kind + "es";+ if (kind.endsWith("s")) return kind + "es";+ if (kind.endsWith("y") && !/[aeiou]y$/i.test(kind)) return kind.slice(0, -1) + "ies";+ return kind + "s";+}++interface ScoredEntity {+ id: string;+ name: string;+ kind: string;+ score: number;+}++/** Score all candidates in batches to avoid overwhelming the backend */+async function scoreAllCandidates(+ candidates: any[],+ config: { direction: string; predicates: string[] },+ client: IxClient,+ diagnostics: string[],+ entityKind: string,+): Promise<ScoredEntity[]> {+ const batchSize = 20;+ const results: ScoredEntity[] = [];+ for (let i = 0; i < candidates.length; i += batchSize) {+ const batch = candidates.slice(i, i + batchSize);+ const batchResults = await Promise.all(+ batch.map(async (node: any) => {+ try {+ const result = await client.expand(node.id, {+ direction: config.direction,+ predicates: config.predicates,+ });+ const seen = new Set<string>();+ for (const n of result.nodes) seen.add(n.id);+ return {+ id: node.id,+ name: node.name || node.attrs?.name || "(unnamed)",+ kind: node.kind || entityKind,+ score: seen.size,+ };+ } catch {+ diagnostics.push(`Failed to expand entity ${node.id}`);+ return {+ id: node.id,+ name: node.name || node.attrs?.name || "(unnamed)",+ kind: node.kind || entityKind,+ score: 0,+ };+ }+ })+ );+ results.push(...batchResults);+ }+ return results;+}+export function registerRankCommand(program: Command): void {program.command("rank")@@ -95,7 +153,7 @@ export function registerRankCommand(program: Command): void {const diagnostics: string[] = [];// 1. Fetch all entities of the given kind- const allNodes = await client.listByKind(opts.kind, { limit: 200 });+ const allNodes = await client.listByKind(opts.kind, { limit: 2000 });if (allNodes.length === 0) {if (isJson) {@@ -141,48 +199,9 @@ export function registerRankCommand(program: Command): void {return;}- const totalCandidates = candidates.length;-- // 4. Performance guard: cap entities to evaluate- const evalCap = Math.min(topN * 3, 60);- const toEvaluate = candidates.slice(0, evalCap);- if (candidates.length > evalCap) {- diagnostics.push(- `Evaluated ${evalCap} of ${totalCandidates} candidates (${totalCandidates} total). Increase --top or narrow --path for full coverage.`- );- }-- // 5. Expand each entity and count the metric+ // 4. Score ALL candidates (batched for performance)const config = METRIC_CONFIG[metric];- const scored = await Promise.all(- toEvaluate.map(async (node: any) => {- try {- const result = await client.expand(node.id, {- direction: config.direction,- predicates: config.predicates,- });- // Count unique nodes by id- const seen = new Set<string>();- for (const n of result.nodes) {- seen.add(n.id);- }- return {- id: node.id,- name: node.name || node.attrs?.name || "(unnamed)",- kind: node.kind || opts.kind,- score: seen.size,- };- } catch {- diagnostics.push(`Failed to expand entity ${node.id}`);- return {- id: node.id,- name: node.name || node.attrs?.name || "(unnamed)",- kind: node.kind || opts.kind,- score: 0,- };- }- })- );+ const scored = await scoreAllCandidates(candidates, config, client, diagnostics, opts.kind);// 6. Sort descending, take top Nscored.sort((a, b) => b.score - a.score);@@ -195,11 +214,11 @@ export function registerRankCommand(program: Command): void {kind: opts.kind,scope: opts.path ?? null,results,- summary: { evaluated: toEvaluate.length, totalCandidates, returned: results.length },+ summary: { evaluated: candidates.length, totalCandidates: candidates.length, returned: results.length },diagnostics,}, null, 2));} else {- console.log(chalk.bold(`Top ${results.length} ${opts.kind}s by ${metric}:`));+ console.log(chalk.bold(`Top ${results.length} ${pluralize(opts.kind)} by ${metric}:`));const maxNameLen = Math.max(...results.map((r) => r.name.length), 1);for (let i = 0; i < results.length; i++) {const r = results[i];diff --git a/ix-cli/src/cli/commands/tasks.ts b/ix-cli/src/cli/commands/tasks.tsindex b0850515..243faa06 100644--- a/ix-cli/src/cli/commands/tasks.ts+++ b/ix-cli/src/cli/commands/tasks.ts@@ -2,14 +2,12 @@ import type { Command } from "commander";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";import chalk from "chalk";--const STATUS_ICONS: Record<string, string> = {- pending: "○",- in_progress: "◐",- blocked: "✖",- done: "●",- abandoned: "⊘",-};+import {+ STATUS_ICONS,+ getTaskStatus,+ getWorkflowState,+ formatWorkflowStateCompact,+} from "../task-utils.js";export function registerTasksCommand(program: Command): void {program@@ -52,13 +50,25 @@ export function registerTasksCommand(program: Command): void {taskNodes = await client.listByKind("task", { limit });}- // Map to result shape using attrs (fast path, no per-entity fetch)- let results = taskNodes.map((n: any) => ({- id: n.id,- name: n.name || n.attrs?.name || "(unnamed)",- status: (n.attrs?.status as string) ?? "pending",- planId: opts.plan ?? null,- }));+ // 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;@@ -86,8 +96,11 @@ export function registerTasksCommand(program: Command): void {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}`+ ` ${icon} ${chalk.dim(`[${t.status}]`.padEnd(14))} ${t.name}${wfSuffix}`);}if (total !== results.length) {diff --git a/ix-cli/src/cli/commands/watch.ts b/ix-cli/src/cli/commands/watch.tsindex 32a2576a..86963b32 100644--- a/ix-cli/src/cli/commands/watch.ts+++ b/ix-cli/src/cli/commands/watch.ts@@ -1,5 +1,6 @@import * as fs from "node:fs";import * as path from "node:path";+import * as crypto from "node:crypto";import type { Command } from "commander";import chalk from "chalk";import { IxClient } from "../../client/api.js";@@ -26,7 +27,22 @@ const IGNORE_DIRS = new Set([".cache", "__pycache__", ".ix", ".claude",]);-const DEBOUNCE_MS = 1500;+const DEBOUNCE_MS = 300;++/** Compute SHA-256 hash of file content for dedup. */+function hashContent(content: string): string {+ return crypto.createHash("sha256").update(content).digest("hex");+}++/** Read file content safely, returning null if inaccessible. */+export function readFileContent(filePath: string): string | null {+ try {+ if (!fs.existsSync(filePath)) return null;+ return fs.readFileSync(filePath, "utf-8");+ } catch {+ return null;+ }+}export function registerWatchCommand(program: Command): void {program@@ -60,8 +76,9 @@ export function registerWatchCommand(program: Command): void {console.log(chalk.dim(`[watch] Debounce: ${DEBOUNCE_MS}ms`));console.log(chalk.dim("[watch] Press Ctrl+C to stop.\n"));- // Track pending changes with debounce+ // Track pending changes with debounce + content hash dedupconst pending = new Map<string, NodeJS.Timeout>();+ const lastHash = new Map<string, string>();function shouldWatch(filePath: string): boolean {const ext = path.extname(filePath).toLowerCase();@@ -74,8 +91,21 @@ export function registerWatchCommand(program: Command): void {async function ingestFile(filePath: string): Promise<void> {const rel = path.relative(root, filePath);++ // Re-read content at actual ingest time (not at event time)+ const content = readFileContent(filePath);+ if (content === null) return;++ // Skip if content hash is unchanged since last ingest+ const hash = hashContent(content);+ if (lastHash.get(filePath) === hash) {+ console.log(`${chalk.dim("[watch]")} unchanged (hash): ${rel}`);+ return;+ }+try {const result = await client.ingest(filePath, false);+ lastHash.set(filePath, hash);if (result.patchesApplied > 0) {console.log(`${chalk.cyan("[watch]")} ingested: ${chalk.bold(rel)} → rev ${result.latestRev}`);} else {@@ -102,13 +132,9 @@ export function registerWatchCommand(program: Command): void {const existing = pending.get(fullPath);if (existing) clearTimeout(existing);- // Set new debounce+ // Set new debounce — content is re-read at ingest time, not herepending.set(fullPath, setTimeout(async () => {pending.delete(fullPath);-- // Double-check file still exists and is stable- if (!fs.existsSync(fullPath)) return;-console.log(`${chalk.dim("[watch]")} changed: ${rel}`);await ingestFile(fullPath);}, DEBOUNCE_MS));diff --git a/ix-cli/src/cli/commands/workflow.ts b/ix-cli/src/cli/commands/workflow.tsindex c6c37a06..40968e5f 100644--- a/ix-cli/src/cli/commands/workflow.ts+++ b/ix-cli/src/cli/commands/workflow.ts@@ -1,6 +1,4 @@import * as fs from "node:fs";-import { execFile } from "node:child_process";-import { promisify } from "node:util";import type { Command } from "commander";import chalk from "chalk";import type { PatchOp, GraphPatchPayload } from "../../client/types.js";@@ -11,12 +9,13 @@ import {type StagedWorkflow,isValidWorkflow,normalizeWorkflow,+ extractWorkflow,VALID_WORKFLOW_STAGES,-} from "./plan.js";+ runWorkflowStages,+ type WorkflowRunResult,+} from "../task-utils.js";import { stderr } from "../stderr.js";-const execFileAsync = promisify(execFile);-// ── Helpers ────────────────────────────────────────────────────────async function resolveTargetEntity(@@ -57,109 +56,6 @@ async function resolveTargetEntity(}}-/**- * Extract workflow from an entity, checking claims first (for post-attach updates),- * then falling back to node.attrs (for inline workflows set at creation time).- */-export function extractWorkflow(node: any, claims?: any[]): StagedWorkflow | null {- // Claims take precedence (workflow set via AssertClaim, e.g. workflow attach)- if (claims) {- const workflowClaim = claims.find(- (c: any) => c.field === "workflow" || c.statement === "workflow"- );- if (workflowClaim) {- const val = (workflowClaim as any).value;- if (val && isValidWorkflow(val)) {- return normalizeWorkflow(val as string[] | StagedWorkflow);- }- }- }- // Fall back to node attrs (workflow set at creation time)- const raw = node.attrs?.workflow;- if (!raw) return null;- if (!isValidWorkflow(raw)) return null;- return normalizeWorkflow(raw as string[] | StagedWorkflow);-}--interface WorkflowRunResult {- stage: string;- command: string;- status: "ok" | "error" | "skipped";- output?: unknown;- error?: string;-}--async function executeIxCommand(cmd: string): Promise<WorkflowRunResult["output"]> {- // Strip leading "ix " and split into args- const trimmed = cmd.replace(/^ix\s+/, "");- const args = trimmed.split(/\s+/);-- // Always append --format json for structured output- if (!args.includes("--format") && !args.includes("-f")) {- args.push("--format", "json");- }-- const { stdout } = await execFileAsync("ix", args, {- maxBuffer: 10 * 1024 * 1024,- timeout: 60_000,- });-- try {- return JSON.parse(stdout);- } catch {- return stdout.trim();- }-}--async function runWorkflowStages(- workflow: StagedWorkflow,- stages: string[],-): Promise<WorkflowRunResult[]> {- const results: WorkflowRunResult[] = [];-- for (const stage of stages) {- const cmds = workflow[stage as keyof StagedWorkflow];- if (!cmds || cmds.length === 0) continue;-- for (const cmd of cmds) {- // Security: only allow ix commands- if (!cmd.trimStart().startsWith("ix ") && cmd.trim() !== "ix") {- results.push({- stage,- command: cmd,- status: "skipped",- error: "Only ix commands are allowed in workflows",- });- continue;- }-- // Security: no pipes, semicolons, backticks, $(), etc.- if (/[|;&`$()]/.test(cmd)) {- results.push({- stage,- command: cmd,- status: "skipped",- error: "Pipes, shell operators, and variable expansion are not allowed",- });- continue;- }-- try {- const output = await executeIxCommand(cmd);- results.push({ stage, command: cmd, status: "ok", output });- } catch (err: any) {- results.push({- stage,- command: cmd,- status: "error",- error: err.message || String(err),- });- }- }- }-- return results;-}// ── Patch builder ─────────────────────────────────────────────────diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.tsindex d2217a8c..b71cd46e 100644--- a/ix-cli/src/cli/resolve.ts+++ b/ix-cli/src/cli/resolve.ts@@ -172,6 +172,8 @@ function pickBest(preferredKinds: string[],opts?: { kind?: string; path?: string }): ResolveResult | null {+ // Here is a test+ // LEt's see if it worked// Score all candidatesconst scored = candidates.map(n => ({node: n,@@ -308,6 +310,7 @@ function nodeToResolved(node: any, symbol: string, mode: ResolutionMode): Resolv}function buildAmbiguous(nodes: any[], scores?: number[]): AmbiguousResult {+ //this is a testconst seen = new Set<string>();const candidates: AmbiguousResult["candidates"] = [];let rank = 0;diff --git a/ix-cli/src/cli/task-utils.ts b/ix-cli/src/cli/task-utils.tsnew file mode 100644index 00000000..e927de59--- /dev/null+++ b/ix-cli/src/cli/task-utils.ts@@ -0,0 +1,215 @@+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(" ")}]` : "";+}diff --git a/ix-cli/src/client/api.ts b/ix-cli/src/client/api.tsindex dff096cf..495d19a8 100644--- a/ix-cli/src/client/api.ts+++ b/ix-cli/src/client/api.ts@@ -115,6 +115,17 @@ export class IxClient {});}+ async listGoals(): Promise<GraphNode[]> {+ return this.get("/v1/goal");+ }++ async createGoal(+ statement: string,+ parentGoal?: string+ ): Promise<{ status: string; nodeId: string; rev: number }> {+ return this.post("/v1/goal", { statement, parentGoal });+ }+async listTruth(): Promise<GraphNode[]> {return this.get("/v1/truth");}