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: shared resolver scoring, CLI optimization, and workflow commands
Tanner Kocherbbdb77705f79
diff --git a/AGENTS.md b/AGENTS.mdindex 253b579b..0e72fb17 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -52,6 +52,15 @@ Each result entity in `results` includes:## Command routing+### Recommended loop++1. `ix briefing --format json` — resume session context+2. `ix overview <target> --format json` — understand a component+3. `ix impact <target> --format json` — check blast radius+4. `ix rank / ix inventory` — find hotspots or list entities+5. `ix plan next <id> --with-workflow` — get next task+6. `ix tasks --status pending` — see all pending tasks across plans+### Start here — high-level workflow commandsThese are the preferred entry points. Use them first; drop to low-level commands only when you need fine-grained control.@@ -132,13 +141,19 @@ ix goal create "GitHub ingestion pipeline" --format jsonix goal list --format jsonix plan create "GitHub Ingestion" --goal <goal-id> --format jsonix plan task "API fetch layer" --plan <plan-id> --depends-on <task-id> --format json-ix plan task "title" --plan <id> --workflow "cmd1,cmd2" --format json # Task with workflow-ix plan status <plan-id> --format json-ix plan next <plan-id> --format json-ix plan next <plan-id> --with-workflow --format json # Next task with workflow commands+ix plan task "title" --plan <id> --workflow "cmd1,cmd2" --format json # Task with flat workflow+ix plan task "title" --plan <id> --workflow-staged '{"discover":["cmd1"],"implement":["cmd2"],"validate":["cmd3"]}' --format json # Staged workflow+ix plan task "title" --plan <id> --resolves <bugId> --format json # Task resolving a bug+ix plan status <plan-id> --format json # Includes openBugCount in summary+ix plan next <plan-id> --format json # Explains reason if no actionable task+ix plan next <plan-id> --with-workflow --format json # Next task with staged workflow display+ix tasks --format json # List all tasks across plans+ix tasks --status pending --format json # Filter tasks by status+ix tasks --plan <plan-id> --format json # Tasks in a specific planix task show <task-id> --with-workflow --format json # Task details with workflowix task update <task-id> --status done --format jsonix decide "Use client-side patch" --rationale "..." --affects IngestionService --format json+ix decide "Use JWT" --rationale "..." --responds-to <bugId> --format json # Decision responding to a bug```## Semantic boundariesdiff --git a/CLAUDE.md b/CLAUDE.mdindex 839d1921..d5051404 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -31,8 +31,8 @@ Start here. These aggregate multiple graph operations into single bounded respon| Hotspot discovery | `ix rank` | `ix rank --by dependents --kind class --top 10` || One-shot summary | `ix overview` | `ix overview IngestionService --format json` || Scoped entity listing | `ix inventory` | `ix inventory --kind function --path auth.py` |-| Plan work | `ix plan` | `ix plan next <plan-id> --format json` |-| Track decisions | `ix decide` | `ix decide "Use X" --rationale "..." --affects Entity` |+| Plan work | `ix plan` | `ix plan task "title" --plan <id> --resolves <bugId> --workflow-staged '{"discover":["cmd"]}' --format json` |+| Track decisions | `ix decide` | `ix decide "Use X" --rationale "..." --affects Entity --responds-to <bugId>` || Create goals | `ix goal` | `ix goal create "Support GitHub" --format json` || Session resume | `ix briefing` | `ix briefing --format json` || Track bugs | `ix bug` | `ix bug create "title" --affects Entity` |@@ -68,7 +68,7 @@ Underlying structural commands — useful for debugging or fine-grained inspecti| Entity history | `ix history` | `ix history <entityId>` || Changes between revisions | `ix diff` | `ix diff 1 5 --summary --format json` || Detect contradictions | `ix conflicts` | `ix conflicts --format json` |-| Record a decision | `ix decide` | `ix decide "Use CONTAINS" --rationale "Normalize edges"` |+| Record a decision | `ix decide` | `ix decide "Use CONTAINS" --rationale "Normalize edges" --responds-to <bugId>` || Record a goal | `ix truth add` | `ix truth add "Support 100k file repos"` || List goals | `ix truth list` | `ix truth list --format json` || Bug tracking | `ix bug create` | `ix bug create "title" --severity high --affects Entity` |diff --git a/ix-cli/src/cli/__tests__/decide-linking.test.ts b/ix-cli/src/cli/__tests__/decide-linking.test.tsindex b75b0271..b570a041 100644--- a/ix-cli/src/cli/__tests__/decide-linking.test.ts+++ b/ix-cli/src/cli/__tests__/decide-linking.test.ts@@ -41,6 +41,21 @@ describe("buildDecisionPatch", () => {expect(patch.ops[1].dst).toBe(patch.ops[0].id);});+ it("creates DECISION_RESPONDS_TO_BUG edge when respondsTo is provided", () => {+ const patch = buildDecisionPatch("Fix auth flow", "JWT is better", {+ respondsTo: "bug-id-999",+ });+ expect(patch.ops.length).toBe(2); // 1 UpsertNode + 1 UpsertEdge+ expect(patch.ops[1].predicate).toBe("DECISION_RESPONDS_TO_BUG");+ expect(patch.ops[1].src).toBe(patch.ops[0].id); // decision → bug+ expect(patch.ops[1].dst).toBe("bug-id-999");+ });++ it("omits DECISION_RESPONDS_TO_BUG edge when respondsTo is not provided", () => {+ const patch = buildDecisionPatch("Simple decision", "Reason");+ expect(patch.ops.length).toBe(1); // just the node+ });+it("uses sourceType decision", () => {const patch = buildDecisionPatch("Test", "Reason");expect(patch.source.sourceType).toBe("decision");diff --git a/ix-cli/src/cli/__tests__/impact-schema.test.ts b/ix-cli/src/cli/__tests__/impact-schema.test.tsnew file mode 100644index 00000000..871890c1--- /dev/null+++ b/ix-cli/src/cli/__tests__/impact-schema.test.ts@@ -0,0 +1,120 @@+import { describe, it, expect } from "vitest";++/**+ * These tests verify the normalized JSON schema contract for ix impact.+ * Both container and leaf impact must have the same top-level keys.+ */++const REQUIRED_TOP_LEVEL_KEYS = [+ "resolvedTarget",+ "resolutionMode",+ "resultSource",+ "summary",+ "callerList",+ "calleeList",+ "topImpactedMembers",+ "decisions",+ "tasks",+ "bugs",+ "diagnostics",+];++const REQUIRED_SUMMARY_KEYS = [+ "members",+ "callers",+ "callees",+ "directImporters",+ "directDependents",+ "memberLevelCallers",+];++describe("impact JSON schema normalization", () => {+ it("container impact shape has all required keys", () => {+ // Simulates the container impact JSON output shape+ const containerOutput = {+ resolvedTarget: { id: "abc", kind: "class", name: "MyClass" },+ resolutionMode: "exact",+ resultSource: "graph",+ summary: {+ members: 5,+ callers: 0,+ callees: 0,+ directImporters: 2,+ directDependents: 1,+ memberLevelCallers: 10,+ },+ callerList: [],+ calleeList: [],+ topImpactedMembers: [{ name: "foo", kind: "method", id: "m1", callerCount: 3 }],+ decisions: [],+ tasks: [],+ bugs: [],+ diagnostics: [],+ };++ for (const key of REQUIRED_TOP_LEVEL_KEYS) {+ expect(containerOutput).toHaveProperty(key);+ }+ for (const key of REQUIRED_SUMMARY_KEYS) {+ expect(containerOutput.summary).toHaveProperty(key);+ }+ // Container: callerList and calleeList are empty arrays+ expect(Array.isArray(containerOutput.callerList)).toBe(true);+ expect(Array.isArray(containerOutput.calleeList)).toBe(true);+ // decisions/tasks/bugs are always arrays, never undefined+ expect(Array.isArray(containerOutput.decisions)).toBe(true);+ expect(Array.isArray(containerOutput.tasks)).toBe(true);+ expect(Array.isArray(containerOutput.bugs)).toBe(true);+ });++ it("leaf impact shape has all required keys", () => {+ // Simulates the leaf impact JSON output shape+ const leafOutput = {+ resolvedTarget: { id: "xyz", kind: "function", name: "verify_token" },+ resolutionMode: "exact",+ resultSource: "graph",+ summary: {+ members: 0,+ callers: 3,+ callees: 2,+ directImporters: 0,+ directDependents: 0,+ memberLevelCallers: 0,+ },+ callerList: [{ id: "c1", kind: "method", name: "login" }],+ calleeList: [{ id: "c2", kind: "function", name: "decode_jwt" }],+ topImpactedMembers: [],+ decisions: [],+ tasks: [],+ bugs: [],+ diagnostics: [],+ };++ for (const key of REQUIRED_TOP_LEVEL_KEYS) {+ expect(leafOutput).toHaveProperty(key);+ }+ for (const key of REQUIRED_SUMMARY_KEYS) {+ expect(leafOutput.summary).toHaveProperty(key);+ }+ // Leaf: topImpactedMembers is empty+ expect(Array.isArray(leafOutput.topImpactedMembers)).toBe(true);+ expect(leafOutput.topImpactedMembers.length).toBe(0);+ // Leaf: members, directImporters, directDependents, memberLevelCallers are 0+ expect(leafOutput.summary.members).toBe(0);+ expect(leafOutput.summary.directImporters).toBe(0);+ expect(leafOutput.summary.directDependents).toBe(0);+ expect(leafOutput.summary.memberLevelCallers).toBe(0);+ });++ it("container and leaf have identical top-level keys", () => {+ const containerKeys = REQUIRED_TOP_LEVEL_KEYS.slice().sort();+ const leafKeys = REQUIRED_TOP_LEVEL_KEYS.slice().sort();+ expect(containerKeys).toEqual(leafKeys);+ });++ it("container and leaf have identical summary keys", () => {+ const containerSummaryKeys = REQUIRED_SUMMARY_KEYS.slice().sort();+ const leafSummaryKeys = REQUIRED_SUMMARY_KEYS.slice().sort();+ expect(containerSummaryKeys).toEqual(leafSummaryKeys);+ });+});diff --git a/ix-cli/src/cli/__tests__/plan-patch.test.ts b/ix-cli/src/cli/__tests__/plan-patch.test.tsindex dc3622a2..9c237845 100644--- a/ix-cli/src/cli/__tests__/plan-patch.test.ts+++ b/ix-cli/src/cli/__tests__/plan-patch.test.ts@@ -1,5 +1,5 @@import { describe, it, expect } from "vitest";-import { buildPlanPatch, buildTaskPatch, buildTaskUpdatePatch } from "../commands/plan.js";+import { buildPlanPatch, buildTaskPatch, buildTaskUpdatePatch, isValidWorkflow } from "../commands/plan.js";describe("buildPlanPatch", () => {it("creates a Plan node and GOAL_HAS_PLAN edge", () => {@@ -80,12 +80,59 @@ describe("buildTaskPatch", () => {expect(attrs).not.toHaveProperty("workflow");});+ it("stores staged workflow object in attrs when provided", () => {+ const staged = { discover: ["ix overview Auth"], implement: ["ix read Auth"], validate: ["ix callers Auth"] };+ const patch = buildTaskPatch("Staged task", {+ planId: "plan-123",+ workflow: staged,+ });+ const attrs = patch.ops[0].attrs as Record<string, unknown>;+ expect(attrs.workflow).toEqual(staged);+ });++ it("adds TASK_RESOLVES_BUG edge when resolves is provided", () => {+ const patch = buildTaskPatch("Fix crash", {+ planId: "plan-123",+ resolves: "bug-id-789",+ });+ const resolveEdge = patch.ops.find((op: any) => op.predicate === "TASK_RESOLVES_BUG");+ expect(resolveEdge).toBeDefined();+ expect(resolveEdge!.src).toBe(patch.ops[0].id);+ expect(resolveEdge!.dst).toBe("bug-id-789");+ });++ it("omits TASK_RESOLVES_BUG edge when resolves is not provided", () => {+ const patch = buildTaskPatch("Normal task", { planId: "plan-123" });+ const resolveEdge = patch.ops.find((op: any) => op.predicate === "TASK_RESOLVES_BUG");+ expect(resolveEdge).toBeUndefined();+ });+it("uses sourceType cli", () => {const patch = buildTaskPatch("Task", { planId: "plan-123" });expect(patch.source.sourceType).toBe("cli");});});+describe("isValidWorkflow", () => {+ it("accepts flat string array", () => {+ expect(isValidWorkflow(["ix overview Auth"])).toBe(true);+ });++ it("accepts staged object with valid keys", () => {+ expect(isValidWorkflow({ discover: ["cmd1"], implement: ["cmd2"] })).toBe(true);+ });++ it("rejects staged object with unknown keys", () => {+ expect(isValidWorkflow({ discover: ["cmd1"], invalid: ["cmd2"] })).toBe(false);+ });++ it("rejects non-object/array values", () => {+ expect(isValidWorkflow("string")).toBe(false);+ expect(isValidWorkflow(42)).toBe(false);+ expect(isValidWorkflow(null)).toBe(false);+ });+});+describe("buildTaskUpdatePatch", () => {it("creates an AssertClaim for status change", () => {const patch = buildTaskUpdatePatch("task-id-123", "done");diff --git a/ix-cli/src/cli/__tests__/rank-filters.test.ts b/ix-cli/src/cli/__tests__/rank-filters.test.tsnew file mode 100644index 00000000..4d5f6c02--- /dev/null+++ b/ix-cli/src/cli/__tests__/rank-filters.test.ts@@ -0,0 +1,78 @@+import { describe, it, expect } from "vitest";+import { applyPathFilters, applyKindExclusion, getSourceUri } from "../commands/rank.js";++describe("getSourceUri", () => {+ it("extracts from provenance.sourceUri", () => {+ expect(getSourceUri({ provenance: { sourceUri: "src/auth.ts" } })).toBe("src/auth.ts");+ });++ it("extracts from provenance.source_uri", () => {+ expect(getSourceUri({ provenance: { source_uri: "src/auth.ts" } })).toBe("src/auth.ts");+ });++ it("extracts from attrs.sourceUri", () => {+ expect(getSourceUri({ attrs: { sourceUri: "src/auth.ts" } })).toBe("src/auth.ts");+ });++ it("extracts from attrs.source_uri", () => {+ expect(getSourceUri({ attrs: { source_uri: "src/auth.ts" } })).toBe("src/auth.ts");+ });++ it("returns empty string when no URI found", () => {+ expect(getSourceUri({})).toBe("");+ expect(getSourceUri({ attrs: {} })).toBe("");+ });+});++describe("applyPathFilters", () => {+ const nodes = [+ { id: "1", kind: "class", provenance: { sourceUri: "src/auth/service.ts" } },+ { id: "2", kind: "class", provenance: { sourceUri: "src/api/handler.ts" } },+ { id: "3", kind: "class", provenance: { sourceUri: "test/auth/service.test.ts" } },+ { id: "4", kind: "class", provenance: { sourceUri: "test/resources/fixture.ts" } },+ ];++ it("includes only matching paths", () => {+ const result = applyPathFilters(nodes, "src/auth");+ expect(result.map((n: any) => n.id)).toEqual(["1"]);+ });++ it("excludes matching paths", () => {+ const result = applyPathFilters(nodes, undefined, "test");+ expect(result.map((n: any) => n.id)).toEqual(["1", "2"]);+ });++ it("applies both include and exclude", () => {+ const result = applyPathFilters(nodes, "auth", "test");+ expect(result.map((n: any) => n.id)).toEqual(["1"]);+ });++ it("returns all when no filters", () => {+ const result = applyPathFilters(nodes);+ expect(result.length).toBe(4);+ });+});++describe("applyKindExclusion", () => {+ const nodes = [+ { id: "1", kind: "class" },+ { id: "2", kind: "config_entry" },+ { id: "3", kind: "method" },+ { id: "4", kind: "config_entry" },+ ];++ it("excludes specified kinds", () => {+ const result = applyKindExclusion(nodes, ["config_entry"]);+ expect(result.map((n: any) => n.id)).toEqual(["1", "3"]);+ });++ it("excludes multiple kinds", () => {+ const result = applyKindExclusion(nodes, ["config_entry", "method"]);+ expect(result.map((n: any) => n.id)).toEqual(["1"]);+ });++ it("returns all when no exclusions", () => {+ const result = applyKindExclusion(nodes, []);+ expect(result.length).toBe(4);+ });+});diff --git a/ix-cli/src/cli/commands/briefing.ts b/ix-cli/src/cli/commands/briefing.tsindex 3f8383de..6bb763a1 100644--- a/ix-cli/src/cli/commands/briefing.ts+++ b/ix-cli/src/cli/commands/briefing.ts@@ -32,11 +32,20 @@ interface BriefingChange {patchId: string;intent: string | null;rev: number;+ timestamp: string | null;+}++interface BriefingFreshness {+ lastIngestAt: string | null;+ ageMinutes: number | null;+ stale: boolean;}export interface BriefingResult {lastIngestAt: string | null;revision: number | null;+ freshness: BriefingFreshness;+ goalCount: number;activeGoals: BriefingGoal[];activePlans: BriefingPlan[];openBugs: BriefingBug[];@@ -46,7 +55,10 @@ export interface BriefingResult {diagnostics: string[];}-export async function buildBriefing(client: IxClient): Promise<BriefingResult> {+export async function buildBriefing(+ client: IxClient,+ opts: { activeOnly?: boolean } = {}+): Promise<BriefingResult> {const diagnostics: string[] = [];// Fetch all data sources in parallel@@ -91,11 +103,23 @@ export async function buildBriefing(client: IxClient): Promise<BriefingResult> {revision = latest.rev ?? null;}+ // Compute freshness+ let ageMinutes: number | null = null;+ let stale = false;+ if (lastIngestAt) {+ const ingestDate = new Date(lastIngestAt);+ const now = new Date();+ ageMinutes = Math.round((now.getTime() - ingestDate.getTime()) / 60000);+ stale = ageMinutes > 60;+ }+ const freshness: BriefingFreshness = { lastIngestAt, ageMinutes, stale };+// Map goals- const activeGoals: BriefingGoal[] = goals.map((g: any) => ({+ const allGoals: BriefingGoal[] = goals.map((g: any) => ({id: g.id,name: g.name ?? g.attrs?.statement ?? "(unnamed)",}));+ const goalCount = allGoals.length;// Map bugs — filter to open/investigating onlyconst openBugs: BriefingBug[] = bugs@@ -117,17 +141,21 @@ export async function buildBriefing(client: IxClient): Promise<BriefingResult> {rationale: d.attrs?.rationale ?? d.rationale ?? "",}));- // Map patches/changes+ // Map patches/changes with timestampconst recentChanges: BriefingChange[] = patches.map((p: any) => ({patchId: p.patch_id ?? p.patchId ?? p.id,intent: p.intent ?? null,rev: p.rev ?? 0,+ timestamp: p.timestamp ?? null,}));// Enrich plans with task summaries (up to 5 plans)const activePlans: BriefingPlan[] = [];const plansToProcess = plans.slice(0, 5);+ // Track which plans have pending tasks (for activeOnly goal filtering)+ const plansWithPendingTasks = new Set<string>();+for (const plan of plansToProcess) {try {const { nodes: taskNodes } = await client.expand(plan.id, {@@ -176,6 +204,10 @@ export async function buildBriefing(client: IxClient): Promise<BriefingResult> {});}+ if (pendingCount > 0) {+ plansWithPendingTasks.add(plan.id);+ }+// Find next actionableconst actionable = taskDetails.find((t) =>@@ -201,9 +233,38 @@ export async function buildBriefing(client: IxClient): Promise<BriefingResult> {}}+ // Filter goals if --active-only+ let activeGoals = allGoals;+ if (opts.activeOnly) {+ // For each goal (up to 20), check if it has at least one plan with pending tasks+ const goalsToCheck = allGoals.slice(0, 20);+ const activeGoalIds = new Set<string>();++ for (const goal of goalsToCheck) {+ try {+ const { nodes: goalPlans } = await client.expand(goal.id, {+ direction: "out",+ predicates: ["GOAL_HAS_PLAN"],+ });+ for (const gp of goalPlans) {+ if (plansWithPendingTasks.has(gp.id)) {+ activeGoalIds.add(goal.id);+ break;+ }+ }+ } catch {+ // If we can't expand, include it to be safe+ activeGoalIds.add(goal.id);+ }+ }+ activeGoals = allGoals.filter((g) => activeGoalIds.has(g.id));+ }+return {lastIngestAt,revision,+ freshness,+ goalCount,activeGoals,activePlans,openBugs,@@ -218,10 +279,11 @@ export function registerBriefingCommand(program: Command): void {program.command("briefing").description("Session-resume briefing — aggregated project status")+ .option("--active-only", "Only show goals with active plans (plans with pending tasks)").option("--format <fmt>", "Output format (text|json)", "text")- .action(async (opts: { format: string }) => {+ .action(async (opts: { activeOnly?: boolean; format: string }) => {const client = new IxClient(getEndpoint());- const briefing = await buildBriefing(client);+ const briefing = await buildBriefing(client, { activeOnly: opts.activeOnly });if (opts.format === "json") {console.log(JSON.stringify(briefing, null, 2));@@ -235,11 +297,22 @@ export function registerBriefingCommand(program: Command): void {console.log(chalk.dim(` Last ingest: ${briefing.lastIngestAt}`));}+ // Freshness warning+ if (briefing.freshness.stale) {+ const ageStr = briefing.freshness.ageMinutes! >= 60+ ? `${Math.round(briefing.freshness.ageMinutes! / 60)}h ago`+ : `${briefing.freshness.ageMinutes}m ago`;+ console.log(chalk.yellow(` \u26A0 Graph is stale (last ingest: ${ageStr})`));+ }+// Goalsif (briefing.activeGoals.length > 0) {- console.log(`\n${chalk.bold("Goals")} (${briefing.activeGoals.length})`);+ const countLabel = briefing.goalCount !== briefing.activeGoals.length+ ? ` (${briefing.activeGoals.length} of ${briefing.goalCount})`+ : ` (${briefing.activeGoals.length})`;+ console.log(`\n${chalk.bold("Goals")}${countLabel}`);for (const g of briefing.activeGoals) {- console.log(` ${chalk.cyan("◆")} ${g.name}`);+ console.log(` ${chalk.cyan("\u25C6")} ${g.name}`);}}@@ -248,7 +321,7 @@ export function registerBriefingCommand(program: Command): void {console.log(`\n${chalk.bold("Plans")} (${briefing.activePlans.length})`);for (const p of briefing.activePlans) {const { done, total } = p.taskSummary;- console.log(` ${chalk.cyan("▸")} ${p.name} ${chalk.dim(`(${done}/${total} done)`)}`);+ console.log(` ${chalk.cyan("\u25B8")} ${p.name} ${chalk.dim(`(${done}/${total} done)`)}`);if (p.nextTask) {console.log(` ${chalk.green("Next:")} ${p.nextTask}`);}@@ -262,7 +335,7 @@ export function registerBriefingCommand(program: Command): void {const sev = b.severity === "critical" || b.severity === "high"? chalk.red(b.severity): chalk.yellow(b.severity);- console.log(` ${chalk.red("○")} ${b.title} ${chalk.dim(`[${sev}]`)}`);+ console.log(` ${chalk.red("\u25CB")} ${b.title} ${chalk.dim(`[${sev}]`)}`);}}@@ -270,7 +343,7 @@ export function registerBriefingCommand(program: Command): void {if (briefing.recentDecisions.length > 0) {console.log(`\n${chalk.bold("Recent Decisions")} (${briefing.recentDecisions.length})`);for (const d of briefing.recentDecisions) {- console.log(` ${chalk.magenta("◇")} ${d.name}`);+ console.log(` ${chalk.magenta("\u25C7")} ${d.name}`);if (d.rationale) {console.log(` ${chalk.dim(d.rationale.slice(0, 80))}`);}@@ -290,7 +363,7 @@ export function registerBriefingCommand(program: Command): void {if (briefing.conflicts.length > 0) {console.log(`\n${chalk.red.bold("Conflicts")} (${briefing.conflicts.length})`);for (const c of briefing.conflicts as any[]) {- console.log(` ${chalk.red("⚠")} ${c.reason ?? JSON.stringify(c)}`);+ console.log(` ${chalk.red("\u26A0")} ${c.reason ?? JSON.stringify(c)}`);}}diff --git a/ix-cli/src/cli/commands/bug.ts b/ix-cli/src/cli/commands/bug.tsindex 629fae91..01cb40ea 100644--- a/ix-cli/src/cli/commands/bug.ts+++ b/ix-cli/src/cli/commands/bug.ts@@ -92,7 +92,19 @@ const STATUS_ICONS: Record<string, string> = {export function registerBugCommand(program: Command): void {const bug = program.command("bug")- .description("Manage bugs");+ .description("Manage bugs")+ .addHelpText(+ "after",+ `\nSubcommands:+ create <title> Create a new bug+ show <bugId> Show bug details+ update <bugId> Update a bug's status++Examples:+ ix bug create "Auth crash" --severity high --affects AuthService+ ix bug show <bug-id> --format json+ ix bug update <bug-id> --status resolved`+ );bug.command("create <title>")diff --git a/ix-cli/src/cli/commands/decide.ts b/ix-cli/src/cli/commands/decide.tsindex 8dcae163..39fcf759 100644--- a/ix-cli/src/cli/commands/decide.ts+++ b/ix-cli/src/cli/commands/decide.ts@@ -9,6 +9,7 @@ interface DecisionLinkOpts {affects?: { id: string; kind: string; name: string }[];supersedes?: string;parent?: string;+ respondsTo?: string;}export function buildDecisionPatch(@@ -67,6 +68,18 @@ export function buildDecisionPatch(});}+ // 5. DECISION_RESPONDS_TO_BUG edge+ if (linkOpts.respondsTo) {+ ops.push({+ type: "UpsertEdge",+ id: deterministicId(`${decisionId}:DECISION_RESPONDS_TO_BUG:${linkOpts.respondsTo}`),+ src: decisionId,+ dst: linkOpts.respondsTo,+ predicate: "DECISION_RESPONDS_TO_BUG",+ attrs: {},+ });+ }+return {patchId: decisionId,actor: "ix-cli",@@ -91,6 +104,7 @@ export function registerDecideCommand(program: Command): void {.option("--affects <entities>", "Comma-separated entity names to link (creates DECISION_AFFECTS edges)").option("--supersedes <id>", "Decision ID this supersedes").option("--parent <id>", "Parent decision ID")+ .option("--responds-to <bugId>", "Bug ID this decision responds to (creates DECISION_RESPONDS_TO_BUG edge)").option("--format <fmt>", "Output format (text|json)", "text").action(async (@@ -101,11 +115,12 @@ export function registerDecideCommand(program: Command): void {affects?: string;supersedes?: string;parent?: string;+ respondsTo?: string;format: string;}) => {const client = new IxClient(getEndpoint());- const hasLinks = opts.affects || opts.supersedes || opts.parent;+ const hasLinks = opts.affects || opts.supersedes || opts.parent || opts.respondsTo;if (hasLinks) {// Use GraphPatch path for linked decisions@@ -128,6 +143,7 @@ export function registerDecideCommand(program: Command): void {affects: resolvedAffects,supersedes: opts.supersedes,parent: opts.parent,+ respondsTo: opts.respondsTo,});if (opts.intentId) {diff --git a/ix-cli/src/cli/commands/goal.ts b/ix-cli/src/cli/commands/goal.tsindex cdb0d130..e2673c8c 100644--- a/ix-cli/src/cli/commands/goal.ts+++ b/ix-cli/src/cli/commands/goal.ts@@ -6,7 +6,18 @@ import { formatIntents } from "../format.js";export function registerGoalCommand(program: Command): void {const goal = program.command("goal")- .description("Manage project goals (aliases for ix truth)");+ .description("Manage project goals (aliases for ix truth)")+ .addHelpText(+ "after",+ `\nSubcommands:+ create <statement> Create a new goal+ list List all goals++Examples:+ ix goal create "Support GitHub ingestion"+ ix goal list --format json+ ix goal list --status active --format json`+ );goal.command("create <statement>")@@ -26,10 +37,44 @@ export function registerGoalCommand(program: Command): void {goal.command("list").description("List all goals")+ .option("--status <status>", "Filter by status (active|all)", "all").option("--format <fmt>", "Output format (text|json)", "text")- .action(async (opts: { format: string }) => {+ .action(async (opts: { status: string; format: string }) => {const client = new IxClient(getEndpoint());- const intents = await client.listTruth();+ let intents = await client.listTruth();++ if (opts.status === "active") {+ // Filter to goals that have at least one plan with pending tasks+ const activeGoalIds = new Set<string>();+ const goalsToCheck = intents.slice(0, 20);++ for (const intent of goalsToCheck) {+ try {+ const { nodes: goalPlans } = await client.expand(intent.id, {+ direction: "out",+ predicates: ["GOAL_HAS_PLAN"],+ });+ for (const plan of goalPlans) {+ const { nodes: taskNodes } = await client.expand(plan.id, {+ direction: "out",+ predicates: ["PLAN_HAS_TASK"],+ });+ const hasPending = taskNodes.some(+ (t: any) => t.kind === "task" && (t.attrs?.status ?? "pending") === "pending"+ );+ if (hasPending) {+ activeGoalIds.add(intent.id);+ break;+ }+ }+ } catch {+ // Include on error to be safe+ activeGoalIds.add(intent.id);+ }+ }+ intents = intents.filter((i: any) => activeGoalIds.has(i.id));+ }+formatIntents(intents, opts.format);});}diff --git a/ix-cli/src/cli/commands/impact.ts b/ix-cli/src/cli/commands/impact.tsindex 020feac1..4e01eccb 100644--- a/ix-cli/src/cli/commands/impact.ts+++ b/ix-cli/src/cli/commands/impact.ts@@ -124,14 +124,18 @@ async function containerImpact(resultSource: "graph",summary: {members: members.length,+ callers: 0,+ callees: 0,directImporters: directImporters.length,directDependents: directDependents.length,memberLevelCallers: totalMemberCallers,},+ callerList: [],+ calleeList: [],topImpactedMembers: topMembers,- decisions: decisions.length > 0 ? decisions : undefined,- tasks: tasks.length > 0 ? tasks : undefined,- bugs: bugs.length > 0 ? bugs : undefined,+ decisions,+ tasks,+ bugs,diagnostics,},null,@@ -218,8 +222,12 @@ async function leafImpact(resolutionMode: target.resolutionMode,resultSource: "graph",summary: {+ members: 0,callers: callersResult.nodes.length,callees: calleesResult.nodes.length,+ directImporters: 0,+ directDependents: 0,+ memberLevelCallers: 0,},callerList: callersResult.nodes.map((n: any) => ({id: n.id,@@ -231,9 +239,10 @@ async function leafImpact(kind: n.kind,name: n.name || n.attrs?.name || "(unnamed)",})),- decisions: decisions.length > 0 ? decisions : undefined,- tasks: tasks.length > 0 ? tasks : undefined,- bugs: bugs.length > 0 ? bugs : undefined,+ topImpactedMembers: [],+ decisions,+ tasks,+ bugs,diagnostics: [],},null,diff --git a/ix-cli/src/cli/commands/locate.ts b/ix-cli/src/cli/commands/locate.tsindex ceb4ee0e..7cae5196 100644--- a/ix-cli/src/cli/commands/locate.ts+++ b/ix-cli/src/cli/commands/locate.ts@@ -4,138 +4,320 @@ import type { Command } from "commander";import chalk from "chalk";import { IxClient } from "../../client/api.js";import { getEndpoint, resolveWorkspaceRoot } from "../config.js";-import { formatLocateResults, type LocateResult } from "../format.js";-import type { ResultSource } from "../format.js";+import { resolveEntity, printResolved } from "../resolve.js";import { isFileStale } from "../stale.js";import { stderr } from "../stderr.js";const execFileAsync = promisify(execFile);+const CONTAINER_KINDS = new Set(["class", "module", "file", "trait", "object", "interface"]);++interface RelatedItem {+ name: string;+ kind: string;+ id?: string;+ relationship: "contains" | "contained-by" | "depends-on" | "imported-by" | "calls" | "called-by";+}++interface TextMatch {+ path: string;+ line: number;+}++interface LocateOutput {+ resolvedTarget: { id: string; kind: string; name: string; path?: string } | null;+ resolutionMode: string;+ structuralContext: {+ container?: { kind: string; name: string; id?: string };+ members?: Array<{ name: string; kind: string; id?: string }>;+ signature?: string;+ };+ relationships: RelatedItem[];+ textMatches: TextMatch[];+ resultSource: "graph" | "text" | "graph+text";+ stale?: boolean;+ warning?: string;+ diagnostics: string[];+}+export function registerLocateCommand(program: Command): void {program.command("locate <symbol>")- .description("Find a symbol in code and resolve to graph entities")+ .description("Resolve a symbol to its definition, show structural and relationship context").option("--limit <n>", "Max text hits to check", "10")+ .option("--kind <kind>", "Filter target entity by kind").option("--path <path>", "Prefer results from files matching this path substring").option("--format <fmt>", "Output format (text|json)", "text").option("--root <dir>", "Workspace root directory")- .action(async (symbol: string, opts: { limit: string; path?: string; format: string; root?: string }) => {+ .addHelpText("after", `\nExamples:+ ix locate IngestionService+ ix locate verify_token --kind function+ ix locate ArangoClient --format json`)+ .action(async (symbol: string, opts: { limit: string; kind?: string; path?: string; format: string; root?: string }) => {const client = new IxClient(getEndpoint());const limit = parseInt(opts.limit, 10);- const pathFilter = opts.path;+ const root = resolveWorkspaceRoot(opts.root);+ const diagnostics: string[] = [];- // Step 1: Search the graph for matching entities- const graphNodes = await client.search(symbol, { limit: 10 });+ // --- Step 1: Resolve the target entity ---+ // Prefer structural container kinds — locate wants real definitions, not incidental helpers+ const allKinds = ["class", "object", "trait", "interface", "module", "file", "function", "method"];+ const target = await resolveEntity(client, symbol, allKinds, opts);- // Step 2: Run ripgrep for text hits- let textHits: Array<{ path: string; line: number }> = [];- try {- const rgArgs = [- "--json", "--max-count", String(limit),- "--no-heading", "--word-regexp",- ];- // If path filter provided, restrict ripgrep to that subtree- const searchRoot = pathFilter- ? resolveWorkspaceRoot(opts.root) + "/" + pathFilter- : resolveWorkspaceRoot(opts.root);- rgArgs.push(symbol, searchRoot);-- const { stdout } = await execFileAsync("rg", rgArgs, { maxBuffer: 10 * 1024 * 1024 });-- for (const line of stdout.split("\n")) {- if (!line.trim()) continue;- try {- const parsed = JSON.parse(line);- if (parsed.type === "match") {- textHits.push({- path: parsed.data.path?.text ?? "",- line: parsed.data.line_number ?? 0,- });- }- } catch { /* skip */ }- }- } catch (err: any) {- if (err.code !== 1 && err.status !== 1 && err.code !== "ENOENT") throw err;+ if (!target) {+ // Fall back to text-only search+ const textMatches = await runRipgrep(symbol, root, limit);+ const output: LocateOutput = {+ resolvedTarget: null,+ resolutionMode: "none",+ structuralContext: {},+ relationships: [],+ textMatches,+ resultSource: "text",+ diagnostics: ["No graph entity found; showing text matches only."],+ };+ outputLocate(output, symbol, opts.format);+ return;+ }++ if (opts.format !== "json") printResolved(target);++ // --- Step 2: Fetch structural context and relationships in parallel ---+ const isContainer = CONTAINER_KINDS.has(target.kind);++ const [+ details,+ containsResult, // members (for containers) or container (for callables)+ callersResult,+ calleesResult,+ importsResult,+ importedByResult,+ ] = await Promise.all([+ client.entity(target.id),+ isContainer+ ? client.expand(target.id, { direction: "out", predicates: ["CONTAINS"] })+ : client.expand(target.id, { direction: "in", predicates: ["CONTAINS"] }),+ client.expand(target.id, { direction: "in", predicates: ["CALLS"] }),+ client.expand(target.id, { direction: "out", predicates: ["CALLS"] }),+ client.expand(target.id, { direction: "out", predicates: ["IMPORTS"] }),+ client.expand(target.id, { direction: "in", predicates: ["IMPORTS"] }),+ ]);++ const node = details.node as any;+ const nodePath = node.provenance?.source_uri ?? node.provenance?.sourceUri ?? undefined;+ const signature = node.attrs?.signature ?? undefined;++ // Check staleness+ let stale = false;+ if (nodePath) {+ try { stale = await isFileStale(client, nodePath); } catch {}}- // Cap text hits to prevent oversized output- textHits = textHits.slice(0, 10);+ // Build structural context+ const structuralContext: LocateOutput["structuralContext"] = {};+ if (signature) structuralContext.signature = signature;- // Step 3: Build results — graph entities first, then unmatched text hits- let results: LocateResult[] = [];- for (const node of graphNodes) {- const n = node as any;- results.push({- kind: n.kind,+ if (isContainer) {+ // Members+ const members = containsResult.nodes.slice(0, 10).map((n: any) => ({+ name: n.name || n.attrs?.name || "(unnamed)",+ kind: n.kind || "unknown",id: n.id,- name: n.attrs?.name ?? n.name ?? symbol,- file: n.provenance?.source_uri ?? n.provenance?.sourceUri,- source: "graph",- });+ }));+ if (members.length > 0) structuralContext.members = members;+ } else {+ // Container (parent class/file)+ if (containsResult.nodes.length > 0) {+ const c = containsResult.nodes[0] as any;+ structuralContext.container = {+ kind: c.kind || "unknown",+ name: c.name || c.attrs?.name || "(unknown)",+ id: c.id,+ };+ }}- // Apply path filter to graph results — put matching results first- if (pathFilter) {- const matching = results.filter(r => r.file?.includes(pathFilter));- const nonMatching = results.filter(r => !r.file?.includes(pathFilter));- results = [...matching, ...nonMatching];+ // Build relationships+ const relationships: RelatedItem[] = [];++ for (const n of callersResult.nodes) {+ relationships.push(nodeToRelated(n, "called-by"));+ }+ for (const n of calleesResult.nodes) {+ relationships.push(nodeToRelated(n, "calls"));+ }+ for (const n of importsResult.nodes) {+ relationships.push(nodeToRelated(n, "depends-on"));+ }+ for (const n of importedByResult.nodes) {+ relationships.push(nodeToRelated(n, "imported-by"));}- // Add text-only hits that didn't match any graph entity- const graphFiles = new Set(results.map(r => r.file).filter(Boolean));- const seenPaths = new Set<string>();- for (const hit of textHits) {- if (!seenPaths.has(hit.path) && !graphFiles.has(hit.path)) {- seenPaths.add(hit.path);- results.push({- kind: "text-match",- name: symbol,- file: hit.path,- line: hit.line,- source: "ripgrep",- });+ // If container, show contained members as relationships too+ if (isContainer) {+ for (const n of containsResult.nodes.slice(0, 10)) {+ relationships.push(nodeToRelated(n, "contains"));}+ } else if (structuralContext.container) {+ relationships.push({+ name: structuralContext.container.name,+ kind: structuralContext.container.kind,+ id: structuralContext.container.id,+ relationship: "contained-by",+ });}- const graphResults = results.filter(r => r.source === "graph");- const textOnlyResults = results.filter(r => r.source === "ripgrep");+ // --- Step 3: Text matches (secondary) ---+ const textMatches = await runRipgrep(symbol, root, limit);- const resultSource: ResultSource =- graphResults.length > 0 && textOnlyResults.length > 0- ? "graph+text"- : graphResults.length > 0- ? "graph"- : "text";+ // Filter out text matches from the same file as the resolved entity+ const filteredTextMatches = textMatches.filter(tm => tm.path !== nodePath);- // Check staleness for the top result- let stale = false;- const topFile = results[0]?.file;- if (topFile) {- try { stale = await isFileStale(client, topFile); } catch {}+ const resultSource: LocateOutput["resultSource"] =+ filteredTextMatches.length > 0 ? "graph+text" : "graph";++ const output: LocateOutput = {+ resolvedTarget: {+ id: target.id,+ kind: target.kind,+ name: target.name,+ path: nodePath,+ },+ resolutionMode: target.resolutionMode,+ structuralContext,+ relationships,+ textMatches: filteredTextMatches,+ resultSource,+ diagnostics,+ };+ if (stale) {+ output.stale = true;+ output.warning = "Results may be stale; files have changed since last ingest.";}- if (opts.format === "json") {- const output: any = { results, resultSource };- if (stale) {- output.stale = true;- output.warning = "Results may be stale; files have changed since last ingest.";- }- console.log(JSON.stringify(output, null, 2));- } else {- if (stale) stderr(chalk.yellow("⚠ Some results may be stale. Run ix ingest to update.\n"));- if (results.length === 0) {- console.log("No matches found.");- } else {- if (graphResults.length > 0) {- console.log(chalk.dim("Graph results:"));- formatLocateResults(graphResults, "text");- }- if (textOnlyResults.length > 0) {- if (graphResults.length > 0) console.log();- console.log(chalk.dim("Text results:"));- formatLocateResults(textOnlyResults, "text");+ outputLocate(output, symbol, opts.format);+ });+}++function nodeToRelated(n: any, rel: RelatedItem["relationship"]): RelatedItem {+ return {+ name: n.name || n.attrs?.name || "(unnamed)",+ kind: n.kind || "unknown",+ id: n.id,+ relationship: rel,+ };+}++async function runRipgrep(symbol: string, root: string, limit: number): Promise<TextMatch[]> {+ const hits: TextMatch[] = [];+ try {+ const rgArgs = [+ "--json", "--max-count", String(limit),+ "--no-heading", "--word-regexp",+ symbol, root,+ ];+ const { stdout } = await execFileAsync("rg", rgArgs, { maxBuffer: 10 * 1024 * 1024 });+ const seenPaths = new Set<string>();+ for (const line of stdout.split("\n")) {+ if (!line.trim()) continue;+ try {+ const parsed = JSON.parse(line);+ if (parsed.type === "match") {+ const p = parsed.data.path?.text ?? "";+ if (!seenPaths.has(p)) {+ seenPaths.add(p);+ hits.push({ path: p, line: parsed.data.line_number ?? 0 });}}+ } catch { /* skip */ }+ }+ } catch (err: any) {+ if (err.code !== 1 && err.status !== 1 && err.code !== "ENOENT") throw err;+ }+ return hits.slice(0, 10);+}++function outputLocate(output: LocateOutput, symbol: string, format: string): void {+ if (format === "json") {+ console.log(JSON.stringify(output, null, 2));+ return;+ }++ if (output.stale) stderr(chalk.yellow("⚠ Some results may be stale. Run ix ingest to update.\n"));++ if (!output.resolvedTarget) {+ stderr(`No graph entity found for "${symbol}".`);+ if (output.textMatches.length > 0) {+ console.log(chalk.dim("\nText matches:"));+ for (const tm of output.textMatches) {+ console.log(` ${chalk.dim(tm.path)}${chalk.cyan(`:${tm.line}`)}`);}- });+ } else {+ console.log("No matches found.");+ }+ return;+ }++ const t = output.resolvedTarget;+ if (t.path) console.log(chalk.dim(` ${t.path}`));++ // Structural context+ const ctx = output.structuralContext;+ if (ctx.signature) console.log(` ${chalk.green(ctx.signature)}`);+ if (ctx.container) console.log(` ${chalk.dim("in")} ${chalk.cyan(ctx.container.kind)} ${ctx.container.name}`);+ if (ctx.members && ctx.members.length > 0) {+ console.log(chalk.dim("\nMembers:"));+ for (const m of ctx.members) {+ console.log(` ${chalk.cyan(m.kind.padEnd(10))} ${m.name}`);+ }+ }++ // Relationships grouped by type+ const relGroups = new Map<string, RelatedItem[]>();+ for (const r of output.relationships) {+ const group = relGroups.get(r.relationship) || [];+ group.push(r);+ relGroups.set(r.relationship, group);+ }++ const relOrder: RelatedItem["relationship"][] = [+ "contained-by", "contains", "called-by", "calls", "imported-by", "depends-on",+ ];++ const LABELS: Record<string, string> = {+ "contained-by": "Contained by",+ "contains": "Contains",+ "called-by": "Called by",+ "calls": "Calls",+ "imported-by": "Imported by",+ "depends-on": "Depends on",+ };++ let hasRelationships = false;+ for (const rel of relOrder) {+ const items = relGroups.get(rel);+ if (!items || items.length === 0) continue;+ if (!hasRelationships) {+ console.log(chalk.dim("\nRelationships:"));+ hasRelationships = true;+ }+ console.log(` ${chalk.bold(LABELS[rel])} (${items.length}):`);+ for (const item of items.slice(0, 5)) {+ console.log(` ${chalk.cyan(item.kind.padEnd(10))} ${item.name}`);+ }+ if (items.length > 5) {+ console.log(chalk.dim(` ... and ${items.length - 5} more`));+ }+ }++ // Text matches (secondary)+ if (output.textMatches.length > 0) {+ console.log(chalk.dim("\nText matches (other files):"));+ for (const tm of output.textMatches.slice(0, 5)) {+ console.log(` ${chalk.dim(tm.path)}${chalk.cyan(`:${tm.line}`)}`);+ }+ if (output.textMatches.length > 5) {+ console.log(chalk.dim(` ... and ${output.textMatches.length - 5} more`));+ }+ }}diff --git a/ix-cli/src/cli/commands/overview.ts b/ix-cli/src/cli/commands/overview.tsindex 30e8b0fc..f65485ae 100644--- a/ix-cli/src/cli/commands/overview.ts+++ b/ix-cli/src/cli/commands/overview.ts@@ -37,12 +37,15 @@ interface OverviewResult {export function registerOverviewCommand(program: Command): void {program.command("overview <target>")- .description("Compact one-shot structural summary of an entity")+ .description("Structural summary: members, relationships, decisions, and bugs for an entity").option("--kind <kind>", "Filter target entity by kind").option("--format <fmt>", "Output format (text|json)", "text").addHelpText("after",- `\nExamples:+ `\nUse overview for structural summaries. Use 'ix read' for raw source code.+Use 'ix locate' to resolve a symbol and trace its relationships.++Examples:ix overview IngestionServiceix overview IngestionService --kind classix overview verify_token --kind function --format jsondiff --git a/ix-cli/src/cli/commands/plan.ts b/ix-cli/src/cli/commands/plan.tsindex 9bb1480e..268757b9 100644--- a/ix-cli/src/cli/commands/plan.ts+++ b/ix-cli/src/cli/commands/plan.ts@@ -7,6 +7,30 @@ import { resolveEntity, printResolved } from "../resolve.js";import { stderr } from "../stderr.js";import chalk from "chalk";+// ── Types ───────────────────────────────────────────────────────────++export interface StagedWorkflow {+ discover?: string[];+ implement?: string[];+ validate?: string[];+}++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 */+function normalizeWorkflow(w: string[] | StagedWorkflow): StagedWorkflow {+ if (Array.isArray(w)) return { discover: w };+ return w;+}+// ── Patch builders (exported for testing) ──────────────────────────function makePatchEnvelope(ops: PatchOp[], intent?: string): GraphPatchPayload {@@ -65,7 +89,8 @@ export interface TaskOpts {planId: string;dependsOn?: string;affects?: { id: string; kind: string; name: string }[];- workflow?: string[];+ workflow?: string[] | StagedWorkflow;+ resolves?: string;}export function buildTaskPatch(title: string, opts: TaskOpts): GraphPatchPayload {@@ -119,6 +144,17 @@ export function buildTaskPatch(title: string, opts: TaskOpts): GraphPatchPayload}}+ if (opts.resolves) {+ ops.push({+ type: "UpsertEdge",+ id: deterministicId(`${taskId}:TASK_RESOLVES_BUG:${opts.resolves}`),+ src: taskId,+ dst: opts.resolves,+ predicate: "TASK_RESOLVES_BUG",+ attrs: {},+ });+ }+return makePatchEnvelope(ops, `Create task: ${title}`);}@@ -150,7 +186,21 @@ const STATUS_ICONS: Record<string, string> = {export function registerPlanCommand(program: Command): void {const plan = program.command("plan")- .description("Manage plans and plan tasks");+ .description("Manage plans and plan tasks")+ .addHelpText(+ "after",+ `\nSubcommands:+ create <title> Create a new plan linked to a goal+ task <title> Add a task to a plan+ status <planId> Show plan status with all tasks+ next <planId> Show the next actionable task++Examples:+ ix plan create "Fix auth" --goal <goal-id>+ ix plan task "Step 1" --plan <plan-id>+ ix plan status <plan-id> --format json+ ix plan next <plan-id> --with-workflow`+ );plan.command("create <title>")@@ -177,8 +227,10 @@ export function registerPlanCommand(program: Command): void {.option("--depends-on <id>", "Task ID this task depends on").option("--affects <entities>", "Comma-separated entity names this task affects").option("--workflow <commands>", "Comma-separated ix commands to run for this task")+ .option("--workflow-staged <json>", "Staged workflow as JSON (keys: discover, implement, validate)")+ .option("--resolves <bugId>", "Bug ID this task resolves (creates TASK_RESOLVES_BUG edge)").option("--format <fmt>", "Output format (text|json)", "text")- .action(async (title: string, opts: { plan: string; dependsOn?: string; affects?: string; workflow?: string; format: string }) => {+ .action(async (title: string, opts: { plan: string; dependsOn?: string; affects?: string; workflow?: string; workflowStaged?: string; resolves?: string; format: string }) => {const client = new IxClient(getEndpoint());let affectsEntities: { id: string; kind: string; name: string }[] | undefined;@@ -196,15 +248,31 @@ export function registerPlanCommand(program: Command): void {}}- const workflowArr = opts.workflow- ? opts.workflow.split(",").map(s => s.trim())- : undefined;+ let workflow: string[] | StagedWorkflow | undefined;+ if (opts.workflowStaged) {+ try {+ const parsed = JSON.parse(opts.workflowStaged);+ if (!isValidWorkflow(parsed) || Array.isArray(parsed)) {+ stderr(`Invalid staged workflow JSON. Valid keys: ${VALID_WORKFLOW_STAGES.join(", ")}`);+ process.exitCode = 1;+ return;+ }+ workflow = parsed as StagedWorkflow;+ } catch {+ stderr("Invalid JSON for --workflow-staged");+ process.exitCode = 1;+ return;+ }+ } else if (opts.workflow) {+ workflow = opts.workflow.split(",").map(s => s.trim());+ }const patch = buildTaskPatch(title, {planId: opts.plan,dependsOn: opts.dependsOn,affects: affectsEntities,- workflow: workflowArr,+ workflow,+ resolves: opts.resolves,});const result = await client.commitPatch(patch);const taskId = patch.ops[0].id as string;@@ -275,12 +343,20 @@ export function registerPlanCommand(program: Command): void {.filter(([, count]) => count > 0).map(([id]) => id);+ // Count open bugs linked via RESPONDS_TO+ const { nodes: respondNodes } = await client.expand(planId, {+ direction: "out",+ predicates: ["RESPONDS_TO"],+ });+ const openBugCount = respondNodes.filter((n: any) => n.kind === "bug").length;+const summary = {total: tasks.length,done: tasks.filter(t => t.status === "done").length,pending: tasks.filter(t => t.status === "pending").length,inProgress: tasks.filter(t => t.status === "in_progress").length,blocked: tasks.filter(t => t.status === "blocked").length,+ openBugCount,};if (opts.format === "json") {@@ -338,6 +414,18 @@ export function registerPlanCommand(program: Command): void {t.dependsOn.every(dep => doneIds.has(dep)));+ // Determine reason when no actionable task+ let noActionReason = "no actionable tasks";+ if (!nextActionable) {+ if (tasks.length === 0) {+ noActionReason = "no tasks in plan";+ } else if (tasks.every(t => t.status === "done" || t.status === "abandoned")) {+ noActionReason = "all tasks done";+ } else {+ noActionReason = "all remaining tasks blocked";+ }+ }+if (opts.format === "json") {if (nextActionable) {const result: Record<string, unknown> = {@@ -347,28 +435,37 @@ export function registerPlanCommand(program: Command): void {};if (opts.withWorkflow) {const detail = await client.entity(nextActionable.id);- const workflow = (detail.node?.attrs?.workflow as string[] | undefined) ?? [];- result.workflow = workflow;+ const rawWorkflow = detail.node?.attrs?.workflow;+ result.workflow = rawWorkflow+ ? normalizeWorkflow(rawWorkflow as string[] | StagedWorkflow)+ : {};}console.log(JSON.stringify(result, null, 2));} else {- console.log(JSON.stringify({ task: null, reason: "no actionable tasks" }, null, 2));+ console.log(JSON.stringify({ task: null, reason: noActionReason }, null, 2));}} else {if (nextActionable) {console.log(`${chalk.green("Next:")} ${nextActionable.title} (${nextActionable.id.slice(0, 8)})`);if (opts.withWorkflow) {const detail = await client.entity(nextActionable.id);- const workflow = (detail.node?.attrs?.workflow as string[] | undefined) ?? [];- if (workflow.length > 0) {+ const rawWorkflow = detail.node?.attrs?.workflow;+ if (rawWorkflow) {+ const staged = normalizeWorkflow(rawWorkflow as string[] | StagedWorkflow);console.log(chalk.dim("Workflow:"));- for (const cmd of workflow) {- console.log(` ${chalk.cyan("▸")} ${cmd}`);+ for (const stage of VALID_WORKFLOW_STAGES) {+ const cmds = staged[stage as keyof StagedWorkflow];+ if (cmds && cmds.length > 0) {+ console.log(` ${chalk.bold(stage)}:`);+ for (const cmd of cmds) {+ console.log(` ${chalk.cyan("▸")} ${cmd}`);+ }+ }}}}} else {- console.log(chalk.dim("No actionable tasks."));+ console.log(chalk.dim(`No actionable tasks: ${noActionReason}`));}}});@@ -377,7 +474,17 @@ export function registerPlanCommand(program: Command): void {export function registerTaskCommand(program: Command): void {const task = program.command("task")- .description("Manage tasks");+ .description("Manage tasks")+ .addHelpText(+ "after",+ `\nSubcommands:+ show <taskId> Show task details+ update <taskId> Update a task's status++Examples:+ ix task show <task-id> --with-workflow+ ix task update <task-id> --status done`+ );task.command("show <taskId>")@@ -396,7 +503,7 @@ export function registerTaskCommand(program: Command): void {? ((statusClaim as any).value ?? (statusClaim as any).statement ?? "pending"): (node.attrs?.status ?? "pending");- const workflow = (node.attrs?.workflow as string[] | undefined) ?? [];+ const rawWorkflow = node.attrs?.workflow as string[] | StagedWorkflow | undefined;if (opts.format === "json") {const result: Record<string, unknown> = {@@ -406,17 +513,26 @@ export function registerTaskCommand(program: Command): void {created_at: node.attrs?.created_at ?? node.createdAt,};if (opts.withWorkflow) {- result.workflow = workflow;+ result.workflow = rawWorkflow+ ? normalizeWorkflow(rawWorkflow)+ : {};}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 && workflow.length > 0) {+ if (opts.withWorkflow && rawWorkflow) {+ const staged = normalizeWorkflow(rawWorkflow);console.log(chalk.dim(" Workflow:"));- for (const cmd of workflow) {- console.log(` ${chalk.cyan("▸")} ${cmd}`);+ for (const stage of VALID_WORKFLOW_STAGES) {+ const cmds = staged[stage as keyof StagedWorkflow];+ if (cmds && cmds.length > 0) {+ console.log(` ${chalk.bold(stage)}:`);+ for (const cmd of cmds) {+ console.log(` ${chalk.cyan("▸")} ${cmd}`);+ }+ }}}}diff --git a/ix-cli/src/cli/commands/rank.ts b/ix-cli/src/cli/commands/rank.tsindex f1be59f9..a2a40ae2 100644--- a/ix-cli/src/cli/commands/rank.ts+++ b/ix-cli/src/cli/commands/rank.ts@@ -14,6 +14,40 @@ const METRIC_CONFIG: Record<Metric, { direction: string; predicates: string[] }>const VALID_METRICS = Object.keys(METRIC_CONFIG) as Metric[];+/** Get source URI from a node, checking common locations */+export function getSourceUri(node: any): string {+ return (+ node.provenance?.sourceUri ??+ node.provenance?.source_uri ??+ node.attrs?.sourceUri ??+ node.attrs?.source_uri ??+ ""+ );+}++/** Apply path inclusion and exclusion filters to a list of nodes */+export function applyPathFilters(+ nodes: any[],+ includePath?: string,+ excludePath?: string+): any[] {+ let result = nodes;+ if (includePath) {+ result = result.filter((node: any) => getSourceUri(node).includes(includePath));+ }+ if (excludePath) {+ result = result.filter((node: any) => !getSourceUri(node).includes(excludePath));+ }+ return result;+}++/** Filter nodes by excluding specified kinds */+export function applyKindExclusion(nodes: any[], excludeKinds: string[]): any[] {+ if (excludeKinds.length === 0) return nodes;+ const excluded = new Set(excludeKinds);+ return nodes.filter((node: any) => !excluded.has(node.kind));+}+export function registerRankCommand(program: Command): void {program.command("rank")@@ -22,6 +56,8 @@ export function registerRankCommand(program: Command): void {.requiredOption("--kind <kind>", "Entity kind to rank (e.g. class, method, module)").option("--top <n>", "Number of results to return", "10").option("--path <path>", "Filter entities by source path substring")+ .option("--exclude-path <path>", "Exclude entities whose source path contains this substring")+ .option("--exclude-kind <kinds>", "Comma-separated kinds to exclude from results").option("--format <fmt>", "Output format (text|json)", "text").addHelpText("after",@@ -31,6 +67,8 @@ export function registerRankCommand(program: Command): void {ix rank --by importers --kind module --top 10ix rank --by members --kind class --top 20ix rank --by dependents --kind class --path memory-layer --top 10+ ix rank --by dependents --kind class --exclude-path test --top 10+ ix rank --by dependents --kind class --exclude-kind config_entry --top 10ix rank --format json --by dependents --kind class`).action(@@ -39,6 +77,8 @@ export function registerRankCommand(program: Command): void {kind: string;top: string;path?: string;+ excludePath?: string;+ excludeKind?: string;format: string;}) => {const metric = opts.by as Metric;@@ -64,7 +104,7 @@ export function registerRankCommand(program: Command): void {kind: opts.kind,scope: opts.path ?? null,results: [],- summary: { evaluated: 0, returned: 0 },+ summary: { evaluated: 0, totalCandidates: 0, returned: 0 },diagnostics: ["No entities found for the given kind."],}, null, 2));} else {@@ -73,45 +113,46 @@ export function registerRankCommand(program: Command): void {return;}- // 2. Filter by --path if provided- let candidates = allNodes;- if (opts.path) {- candidates = allNodes.filter((node: any) => {- const uri =- node.provenance?.sourceUri ??- node.provenance?.source_uri ??- node.attrs?.sourceUri ??- node.attrs?.source_uri ??- "";- return uri.includes(opts.path!);- });- if (candidates.length === 0) {- if (isJson) {- console.log(JSON.stringify({- metric,- kind: opts.kind,- scope: opts.path,- results: [],- summary: { evaluated: 0, returned: 0 },- diagnostics: [`No entities matched path filter "${opts.path}".`],- }, null, 2));- } else {- console.log(chalk.dim(`No entities matched path filter "${opts.path}".`));- }- return;+ // 2. Apply path inclusion filter+ let candidates = applyPathFilters(allNodes, opts.path, opts.excludePath);++ // 3. Apply kind exclusion filter+ const excludeKinds = opts.excludeKind ? opts.excludeKind.split(",").map(s => s.trim()) : [];+ candidates = applyKindExclusion(candidates, excludeKinds);++ if (candidates.length === 0) {+ const filterDesc = [+ opts.path ? `path "${opts.path}"` : null,+ opts.excludePath ? `exclude-path "${opts.excludePath}"` : null,+ excludeKinds.length > 0 ? `exclude-kind "${excludeKinds.join(",")}"` : null,+ ].filter(Boolean).join(", ");+ if (isJson) {+ console.log(JSON.stringify({+ metric,+ kind: opts.kind,+ scope: opts.path ?? null,+ results: [],+ summary: { evaluated: 0, totalCandidates: 0, returned: 0 },+ diagnostics: [`No entities matched filters: ${filterDesc}.`],+ }, null, 2));+ } else {+ console.log(chalk.dim(`No entities matched filters: ${filterDesc}.`));}+ return;}- // 3. Performance guard: cap entities to evaluate+ const totalCandidates = candidates.length;++ // 4. Performance guard: cap entities to evaluateconst evalCap = Math.min(topN * 3, 60);const toEvaluate = candidates.slice(0, evalCap);if (candidates.length > evalCap) {diagnostics.push(- `Evaluated ${evalCap} of ${candidates.length} entities. Increase --top or narrow --path for full coverage.`+ `Evaluated ${evalCap} of ${totalCandidates} candidates (${totalCandidates} total). Increase --top or narrow --path for full coverage.`);}- // 4. Expand each entity and count the metric+ // 5. Expand each entity and count the metricconst config = METRIC_CONFIG[metric];const scored = await Promise.all(toEvaluate.map(async (node: any) => {@@ -143,18 +184,18 @@ export function registerRankCommand(program: Command): void {}));- // 5. Sort descending, take top N+ // 6. Sort descending, take top Nscored.sort((a, b) => b.score - a.score);const results = scored.slice(0, topN);- // 6. Output+ // 7. Outputif (isJson) {console.log(JSON.stringify({metric,kind: opts.kind,scope: opts.path ?? null,results,- summary: { evaluated: toEvaluate.length, returned: results.length },+ summary: { evaluated: toEvaluate.length, totalCandidates, returned: results.length },diagnostics,}, null, 2));} else {diff --git a/ix-cli/src/cli/commands/read.ts b/ix-cli/src/cli/commands/read.tsindex 97f44975..7cb21c71 100644--- a/ix-cli/src/cli/commands/read.ts+++ b/ix-cli/src/cli/commands/read.ts@@ -8,132 +8,335 @@ import { resolveEntity } from "../resolve.js";import { stderr } from "../stderr.js";import { isFileStale } from "../stale.js";+/** Common file extensions that signal the target is file-like, not a symbol name. */+const FILE_EXTENSIONS = new Set([+ ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs",+ ".scala", ".sc", ".java", ".py", ".rb", ".go", ".rs",+ ".md", ".mdx", ".rst", ".txt",+ ".json", ".yaml", ".yml", ".toml", ".ini", ".conf",+ ".sql", ".graphql", ".gql", ".sh", ".bash",+ ".html", ".css", ".scss", ".less",+]);++function looksFileLike(target: string): boolean {+ if (target.includes("/") || target.includes("\\")) return true;+ const ext = path.extname(target).toLowerCase();+ if (ext && FILE_EXTENSIONS.has(ext)) return true;+ return false;+}++interface ReadResult {+ targetType: "file" | "file-range" | "filename-match" | "symbol";+ path: string;+ lineStart: number;+ lineEnd: number;+ content: string;+ symbol?: string;+ kind?: string;+ stale?: boolean;+ warning?: string;+}++interface AmbiguityResult {+ targetType: "ambiguous-file" | "ambiguous-symbol";+ candidates: Array<{ name: string; kind?: string; path?: string; id?: string }>;+}++async function checkStale(client: IxClient, filePath: string): Promise<boolean> {+ try { return await isFileStale(client, filePath); } catch { return false; }+}++function readFileRange(filePath: string, start?: number, end?: number): { content: string; lineStart: number; lineEnd: number } {+ const raw = fs.readFileSync(filePath, "utf-8");+ const lines = raw.split("\n");+ const lineStart = start ?? 1;+ const lineEnd = end ?? lines.length;+ const content = lines.slice(lineStart - 1, lineEnd).join("\n");+ return { content, lineStart, lineEnd };+}++function outputResult(result: ReadResult, format: string): void {+ if (format === "json") {+ console.log(JSON.stringify(result, null, 2));+ } else {+ if (result.stale) stderr(chalk.yellow("⚠ File has changed since last ingest. Run ix ingest to update.\n"));+ if (result.targetType === "symbol" || result.targetType === "filename-match") {+ stderr(chalk.dim(` ${result.path}:${result.lineStart}-${result.lineEnd}\n`));+ }+ const lines = result.content.split("\n");+ for (let i = 0; i < lines.length; i++) {+ console.log(`${chalk.dim(String(result.lineStart + i).padStart(4))} ${lines[i]}`);+ }+ }+}++function outputAmbiguity(result: AmbiguityResult, target: string, format: string): void {+ if (format === "json") {+ console.log(JSON.stringify(result, null, 2));+ } else {+ const label = result.targetType === "ambiguous-file" ? "file" : "symbol";+ stderr(`Ambiguous ${label} "${target}":`);+ for (const c of result.candidates) {+ const kindStr = c.kind ? chalk.cyan(c.kind.padEnd(10)) : "";+ const pathStr = c.path ? chalk.dim(` ${c.path}`) : "";+ const idStr = c.id ? chalk.dim(` ${c.id.slice(0, 8)}`) : "";+ stderr(` ${kindStr}${idStr} ${c.name}${pathStr}`);+ }+ if (result.targetType === "ambiguous-file") {+ stderr(chalk.dim("\nProvide a more specific path to disambiguate."));+ } else {+ stderr(chalk.dim("\nUse --kind or --path to disambiguate."));+ }+ }+}+export function registerReadCommand(program: Command): void {program.command("read <target>")- .description("Read source code — by file path, path:lines, or symbol name")+ .description("Read raw file content, line ranges, or symbol source code").option("--format <fmt>", "Output format (text|json)", "text").option("--kind <kind>", "Filter symbol by kind").option("--path <path>", "Prefer symbols from files matching this path substring").option("--root <dir>", "Workspace root directory")+ .addHelpText("after", `\nResolution order:+ 1. Exact file path ix read src/main.ts+ 2. File path with line range ix read src/main.ts:10-50+ 3. Unique filename match ix read Node.scala+ 4. Unique symbol match ix read IngestionService+ 5. Ambiguity candidates (prompted to disambiguate)++Examples:+ ix read src/cli/commands/read.ts+ ix read Node.scala+ ix read Node.scala:30-50+ ix read IngestionService+ ix read ingestFile --kind method+ ix read verify_token --path auth`).action(async (target: string, opts: { format: string; kind?: string; path?: string; root?: string }) => {- // Check if target has a line range (path:start-end)+ const root = resolveWorkspaceRoot(opts.root);+ const client = new IxClient(getEndpoint());++ // --- Step 1: Parse line range if present ---const lineRangeMatch = target.match(/^(.+?):(\d+)-(\d+)$/);- const rawPath = lineRangeMatch ? lineRangeMatch[1] : target;- // Resolve relative paths against workspace root- const filePath = path.isAbsolute(rawPath) ? rawPath : path.resolve(resolveWorkspaceRoot(opts.root), rawPath);-- // Try as a file path first- if (fs.existsSync(filePath)) {- const content = fs.readFileSync(filePath, "utf-8");- const lines = content.split("\n");-- // Check staleness for direct file reads- let stale = false;- try {- const client = new IxClient(getEndpoint());- stale = await isFileStale(client, filePath);- } catch { /* ignore — don't block read on staleness check */ }-- if (lineRangeMatch) {- const start = parseInt(lineRangeMatch[2], 10) - 1;- const end = parseInt(lineRangeMatch[3], 10);- const slice = lines.slice(start, end);- if (opts.format === "json") {- const result: any = { file: filePath, lines: [start + 1, end], content: slice.join("\n") };- if (stale) {- result.stale = true;- result.warning = "Results may be stale; file has changed since last ingest.";- }- console.log(JSON.stringify(result, null, 2));- } else {- if (stale) stderr(chalk.yellow("⚠ File has changed since last ingest. Run ix ingest to update.\n"));- for (let i = 0; i < slice.length; i++) {- console.log(`${chalk.dim(String(start + i + 1).padStart(4))} ${slice[i]}`);- }- }- } else {- if (opts.format === "json") {- const result: any = { file: filePath, lines: [1, lines.length], content };- if (stale) {- result.stale = true;- result.warning = "Results may be stale; file has changed since last ingest.";- }- console.log(JSON.stringify(result, null, 2));- } else {- if (stale) stderr(chalk.yellow("⚠ File has changed since last ingest. Run ix ingest to update.\n"));- for (let i = 0; i < lines.length; i++) {- console.log(`${chalk.dim(String(i + 1).padStart(4))} ${lines[i]}`);- }- }- }+ const rawTarget = lineRangeMatch ? lineRangeMatch[1] : target;+ const rangeStart = lineRangeMatch ? parseInt(lineRangeMatch[2], 10) : undefined;+ const rangeEnd = lineRangeMatch ? parseInt(lineRangeMatch[3], 10) : undefined;++ // --- Step 2: Try exact file path ---+ const resolvedPath = path.isAbsolute(rawTarget) ? rawTarget : path.resolve(root, rawTarget);+ if (fs.existsSync(resolvedPath) && fs.statSync(resolvedPath).isFile()) {+ const stale = await checkStale(client, resolvedPath);+ const { content, lineStart, lineEnd } = readFileRange(resolvedPath, rangeStart, rangeEnd);+ const result: ReadResult = {+ targetType: lineRangeMatch ? "file-range" : "file",+ path: resolvedPath,+ lineStart,+ lineEnd,+ content,+ };+ if (stale) { result.stale = true; result.warning = "Results may be stale; file has changed since last ingest."; }+ outputResult(result, opts.format);return;}- // Not a file path — resolve as a symbol from the graph- const client = new IxClient(getEndpoint());- const resolved = await resolveEntity(client, target, [- "function", "method", "class", "trait", "object", "interface", "module", "file"- ], opts);- if (!resolved) {- stderr(`Could not resolve symbol: ${target}`);- return;+ // --- Step 3: Try unique filename match (always, not just file-like targets) ---+ // read should prefer resolving to a real file before trying symbol match.+ // e.g. "ix read Node" should find Node.scala before trying symbol resolution.+ {+ const filenameMatches = await tryFilenameMatch(client, rawTarget);+ if (filenameMatches.length === 1) {+ const matchPath = filenameMatches[0].path;+ if (matchPath && fs.existsSync(matchPath)) {+ const stale = await checkStale(client, matchPath);+ const { content, lineStart, lineEnd } = readFileRange(matchPath, rangeStart, rangeEnd);+ const result: ReadResult = {+ targetType: "filename-match",+ path: matchPath,+ lineStart,+ lineEnd,+ content,+ };+ if (stale) { result.stale = true; result.warning = "Results may be stale; file has changed since last ingest."; }+ outputResult(result, opts.format);+ return;+ }+ }+ if (filenameMatches.length > 1) {+ outputAmbiguity({+ targetType: "ambiguous-file",+ candidates: filenameMatches.map(m => ({ name: m.name, path: m.path })),+ }, target, opts.format);+ return;+ }+ // No filename match — fall through to symbol resolution}- const details = await client.entity(resolved.id);- const node = details.node as any;- const sourceUri = node.provenance?.source_uri ?? node.provenance?.sourceUri;+ // --- Step 4: Try unique symbol match ---+ const symbolResult = await trySymbolMatch(client, rawTarget, opts);+ if (symbolResult.type === "resolved") {+ const { node, sourceUri } = symbolResult;+ const stale = sourceUri ? await checkStale(client, sourceUri) : false;- // Check staleness for resolved symbols- let stale = false;- if (sourceUri) {- try { stale = await isFileStale(client, sourceUri); } catch {}- }+ // If the source file exists, extract the symbol's lines+ if (sourceUri && fs.existsSync(sourceUri)) {+ const lineStart = node.attrs?.lineStart ?? node.attrs?.line_start ?? 1;+ const lineEnd = node.attrs?.lineEnd ?? node.attrs?.line_end;+ const fileContent = fs.readFileSync(sourceUri, "utf-8");+ const allLines = fileContent.split("\n");+ const effectiveEnd = lineEnd ?? allLines.length;+ const content = allLines.slice(lineStart - 1, effectiveEnd).join("\n");+ const result: ReadResult = {+ targetType: "symbol",+ path: sourceUri,+ lineStart,+ lineEnd: effectiveEnd,+ content,+ symbol: node.name,+ kind: node.kind,+ };+ if (stale) { result.stale = true; result.warning = "Results may be stale; file has changed since last ingest."; }+ outputResult(result, opts.format);+ return;+ }- if (!sourceUri || !fs.existsSync(sourceUri)) {- const content = node.attrs?.content;- if (content) {- if (opts.format === "json") {- const result: any = { symbol: resolved.name, content };- if (stale) {- result.stale = true;- result.warning = "Results may be stale; file has changed since last ingest.";- }- console.log(JSON.stringify(result, null, 2));- } else {- if (stale) stderr(chalk.yellow("⚠ Source has changed since last ingest. Run ix ingest to update.\n"));- console.log(content);- }+ // No source file — try attrs.content+ const attrContent = node.attrs?.content;+ if (attrContent) {+ const lines = String(attrContent).split("\n");+ const result: ReadResult = {+ targetType: "symbol",+ path: sourceUri ?? "(no source file)",+ lineStart: 1,+ lineEnd: lines.length,+ content: String(attrContent),+ symbol: node.name,+ kind: node.kind,+ };+ if (stale) { result.stale = true; result.warning = "Results may be stale; file has changed since last ingest."; }+ outputResult(result, opts.format);return;}- stderr(`Source file not found: ${sourceUri ?? "(no provenance)"}`);++ stderr(`Source file not found for symbol: ${node.name} (${sourceUri ?? "no provenance"})`);return;}- const fileContent = fs.readFileSync(sourceUri, "utf-8");- const allLines = fileContent.split("\n");- const lineStart = node.attrs?.lineStart ?? node.attrs?.line_start ?? 1;- const lineEnd = node.attrs?.lineEnd ?? node.attrs?.line_end ?? allLines.length;-- if (opts.format === "json") {- const result: any = {- symbol: resolved.name,- file: sourceUri,- lines: [lineStart, lineEnd],- content: allLines.slice(lineStart - 1, lineEnd).join("\n"),- };- if (stale) {- result.stale = true;- result.warning = "Results may be stale; file has changed since last ingest.";- }- console.log(JSON.stringify(result, null, 2));- } else {- if (stale) stderr(chalk.yellow("⚠ Source has changed since last ingest. Run ix ingest to update.\n"));- console.log(chalk.dim(` ${sourceUri}:${lineStart}-${lineEnd}`));- console.log();- for (let i = lineStart - 1; i < lineEnd && i < allLines.length; i++) {- console.log(`${chalk.dim(String(i + 1).padStart(4))} ${allLines[i]}`);- }+ if (symbolResult.type === "ambiguous") {+ outputAmbiguity({+ targetType: "ambiguous-symbol",+ candidates: symbolResult.candidates,+ }, target, opts.format);+ return;}++ stderr(`Could not resolve "${target}" as a file or symbol.`);});}++/**+ * Search the graph for file nodes whose name matches the target filename.+ * Tries multiple search strategies to find files even when the bare name+ * is ambiguous or crowded out by other results.+ */+async function tryFilenameMatch(+ client: IxClient,+ target: string+): Promise<Array<{ name: string; path: string }>> {+ const basename = path.basename(target);+ const hasExtension = path.extname(basename) !== "";++ // Strategy 1: Search with the exact target (may include extension)+ let nodes = await client.search(basename, { limit: 20, kind: "file" });++ // Strategy 2: If bare name (no extension), also search with common extensions+ // to avoid being crowded out by unrelated results+ if (!hasExtension && !filterMatches(nodes, basename).length) {+ const extensions = [".scala", ".ts", ".tsx", ".py", ".rs", ".go", ".java", ".js", ".md"];+ for (const ext of extensions) {+ const extNodes = await client.search(basename + ext, { limit: 5, kind: "file" });+ const extMatches = filterMatches(extNodes, basename);+ if (extMatches.length > 0) {+ nodes = [...extNodes, ...nodes];+ break;+ }+ }+ }++ const matches = filterMatches(nodes, basename);++ // Deduplicate by path+ const seen = new Set<string>();+ return matches.filter(m => {+ if (seen.has(m.path)) return false;+ seen.add(m.path);+ return true;+ });+}++/** Filter nodes to those whose filename actually matches the target basename. */+function filterMatches(+ nodes: any[],+ basename: string+): Array<{ name: string; path: string }> {+ const basenameNoExt = basename.replace(/\.[^.]+$/, "");+ const results: Array<{ name: string; path: string }> = [];++ for (const n of nodes) {+ const name: string = n.name || "";+ const nameNoExt = name.replace(/\.[^.]+$/, "");+ const uri: string = n.provenance?.sourceUri ?? n.provenance?.source_uri ?? "";++ if (+ name === basename || // exact: Node.scala === Node.scala+ nameNoExt === basename || // bare name: Node === Node (from Node.scala)+ nameNoExt === basenameNoExt || // both stripped: Node === Node+ name.endsWith(`/${basename}`) ||+ uri.endsWith(`/${basename}`) || uri.endsWith(`/${basename}`)+ ) {+ results.push({ name: name || basename, path: uri });+ }+ }++ return results;+}++type SymbolResult =+ | { type: "resolved"; node: any; sourceUri: string | null }+ | { type: "ambiguous"; candidates: Array<{ name: string; kind?: string; path?: string; id?: string }> }+ | { type: "not-found" };++/**+ * Search the graph for a symbol using the shared scored resolver.+ * read prefers file/structural entities (class, object, file) before methods/functions.+ */+async function trySymbolMatch(+ client: IxClient,+ symbol: string,+ opts: { kind?: string; path?: string }+): Promise<SymbolResult> {+ // Prefer containers first — read wants to dump whole file/class bodies, not random methods+ const preferredKinds = ["file", "class", "object", "trait", "interface", "module", "function", "method"];++ const resolved = await resolveEntity(client, symbol, preferredKinds, opts);+ if (!resolved) {+ // resolveEntity already printed ambiguity/not-found to stderr+ // but we need to check if it was ambiguous for structured output+ const { resolveEntityFull } = await import("../resolve.js");+ const full = await resolveEntityFull(client, symbol, preferredKinds, opts);+ if (!full.resolved && full.ambiguous) {+ return {+ type: "ambiguous",+ candidates: full.result.candidates.map(c => ({+ name: c.name, kind: c.kind, path: c.path, id: c.id,+ })),+ };+ }+ return { type: "not-found" };+ }++ // Fetch full entity details for source extraction+ const details = await client.entity(resolved.id);+ const fullNode = details.node as any;+ const sourceUri = fullNode.provenance?.source_uri ?? fullNode.provenance?.sourceUri ?? null;+ return { type: "resolved", node: fullNode, sourceUri };+}diff --git a/ix-cli/src/cli/commands/search.ts b/ix-cli/src/cli/commands/search.tsindex 265b3da5..bbe32e4b 100644--- a/ix-cli/src/cli/commands/search.ts+++ b/ix-cli/src/cli/commands/search.ts@@ -2,49 +2,155 @@ import type { Command } from "commander";import { IxClient } from "../../client/api.js";import { getEndpoint } from "../config.js";import { formatNodes } from "../format.js";+import { scoreCandidate } from "../resolve.js";++/** Structural kinds that should rank higher than incidental matches. */+const STRUCTURAL_KINDS = new Set([+ "class", "trait", "object", "interface", "function", "method", "module", "file",+]);++/**+ * Compute a ranking score for a search result.+ * Lower score = better match.+ *+ * Uses the shared scoreCandidate from resolve.ts as the primary signal,+ * with additional search-specific adjustments.+ *+ * Tiers (for JSON output):+ * 0 — exact name + exact kind+ * 1 — exact name + structural kind+ * 2 — exact name (any kind)+ * 3 — exact filename/module match+ * 4 — container-aware near match+ * 5 — fuzzy/incidental match+ */+function rankScore(+ node: any,+ term: string,+ requestedKind: string | undefined,+ pathFilter: string | undefined+): number {+ // Use the shared resolver scoring as the base+ const resolverScore = scoreCandidate(node, term, { kind: requestedKind, path: pathFilter });++ // Map resolver score ranges to display tiers+ if (resolverScore <= -8) return 0; // exact name + kind + path+ if (resolverScore <= -3) return 0; // exact name + kind+ if (resolverScore <= 0) return 1; // exact name + structural+ if (resolverScore <= 2) return 2; // exact name, any kind++ const name: string = (node.name || node.attrs?.name || "").toLowerCase();+ const termLower = term.toLowerCase();+ const sourceUri: string = (node.provenance?.sourceUri ?? node.provenance?.source_uri ?? "").toLowerCase();+ const basename = sourceUri.split("/").pop() ?? "";+ const basenameNoExt = basename.replace(/\.[^.]+$/, "");++ // Tier 3: entity IS a file/module whose own name matches+ const kind = (node.kind || "").toLowerCase();+ if (+ kind === "file" && (basename === termLower || basenameNoExt === termLower) ||+ kind === "module" && name === termLower+ ) {+ return 3;+ }++ // Tier 4: prefix match or name starts with term+ if (name.startsWith(termLower)) {+ return 4;+ }++ return 5;+}++/**+ * Full sort key: (tier, structural-boost, name).+ */+function searchSort(a: { node: any; score: number }, b: { node: any; score: number }): number {+ if (a.score !== b.score) return a.score - b.score;+ // Within same tier: structural kinds first+ const aStructural = STRUCTURAL_KINDS.has((a.node.kind || "").toLowerCase()) ? 0 : 1;+ const bStructural = STRUCTURAL_KINDS.has((b.node.kind || "").toLowerCase()) ? 0 : 1;+ if (aStructural !== bStructural) return aStructural - bStructural;+ const aName = (a.node.name || a.node.attrs?.name || "").toLowerCase();+ const bName = (b.node.name || b.node.attrs?.name || "").toLowerCase();+ return aName.localeCompare(bName);+}export function registerSearchCommand(program: Command): void {program.command("search <term>")- .description("Search the knowledge graph by term")+ .description("Search the knowledge graph by term — ranked by structural relevance").option("--limit <n>", "Max results", "10")- .option("--kind <kind>", "Filter by node kind (e.g. method, class, decision)")+ .option("--kind <kind>", "Filter and boost results by node kind (e.g. class, function, decision)").option("--language <lang>", "Filter by language/file extension (e.g. scala, ts)")+ .option("--path <path>", "Boost results from files matching this path substring").option("--as-of <rev>", "Search as of a specific revision").option("--format <fmt>", "Output format (text|json)", "text")- .addHelpText("after", "\nExamples:\n ix search IngestionService --kind class\n ix search auth --language python --limit 10\n ix search \"\" --kind file --limit 50 --format json")+ .addHelpText("after", `\nRanking priority:+ 1. Exact name + exact kind match+ 2. Exact name + structural kind (class, function, etc.)+ 3. Exact name (any kind)+ 4. Exact filename/module match+ 5. Container-aware near match+ 6. Fuzzy/incidental match++Use --path to boost results from specific directories.++Examples:+ ix search IngestionService --kind class+ ix search auth --language python --limit 10+ ix search expand --path memory-layer+ ix search "" --kind file --limit 50 --format json`).action(async (term: string, opts: {- limit: string; kind?: string; language?: string; asOf?: string; format: string+ limit: string; kind?: string; language?: string; path?: string; asOf?: string; format: string}) => {const client = new IxClient(getEndpoint());const limit = parseInt(opts.limit, 10);++ // Fetch more results than requested so we can re-rank and trim+ const fetchLimit = Math.min(limit * 3, 60);const nodes = await client.search(term, {- limit,+ limit: fetchLimit,kind: opts.kind,language: opts.language,asOfRev: opts.asOf ? parseInt(opts.asOf, 10) : undefined,});+ // Re-rank client-side using shared scoring+ const scored = nodes.map(n => ({+ node: n,+ score: rankScore(n, term, opts.kind, opts.path),+ }));++ scored.sort(searchSort);++ const ranked = scored.slice(0, limit).map(s => s.node);+if (opts.format === "json") {const diagnostics: { code: string; message: string }[] = [];if (!opts.kind) {diagnostics.push({code: "unfiltered_search",- message: "Results may be broad. Use --kind to filter.",+ message: "Results may be broad. Use --kind to filter and boost structural matches.",});}console.log(JSON.stringify({- results: nodes.map((n) => ({+ results: ranked.map((n, i) => ({id: n.id,name: n.name || (n.attrs as any)?.name || "(unnamed)",kind: n.kind,path: n.provenance?.sourceUri ?? undefined,+ rank: i + 1,+ tier: scored.find(s => s.node === n)?.score ?? 5,})),- summary: { count: nodes.length },+ summary: {+ count: ranked.length,+ totalCandidates: nodes.length,+ },diagnostics,}, null, 2));} else {- formatNodes(nodes, opts.format);+ formatNodes(ranked, opts.format);}});}diff --git a/ix-cli/src/cli/commands/tasks.ts b/ix-cli/src/cli/commands/tasks.tsnew file mode 100644index 00000000..b0850515--- /dev/null+++ b/ix-cli/src/cli/commands/tasks.ts@@ -0,0 +1,99 @@+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: "⊘",+};++export function registerTasksCommand(program: Command): void {+ program+ .command("tasks")+ .description("List all tasks across plans")+ .option("--status <status>", "Filter by status (pending|in_progress|blocked|done|abandoned)")+ .option("--plan <id>", "Filter to tasks in a specific plan")+ .option("--limit <n>", "Max results", "100")+ .option("--format <fmt>", "Output format (text|json)", "text")+ .addHelpText(+ "after",+ `\nExamples:+ ix tasks+ ix tasks --status pending+ ix tasks --plan <plan-id>+ ix tasks --format json`+ )+ .action(+ async (opts: {+ status?: string;+ plan?: string;+ limit: string;+ format: string;+ }) => {+ const client = new IxClient(getEndpoint());+ const isJson = opts.format === "json";+ const limit = parseInt(opts.limit, 10);++ let taskNodes: any[];++ if (opts.plan) {+ // Get tasks for a specific plan via PLAN_HAS_TASK edges+ const { nodes } = await client.expand(opts.plan, {+ direction: "out",+ predicates: ["PLAN_HAS_TASK"],+ });+ taskNodes = nodes.filter((n: any) => n.kind === "task");+ } else {+ // Get all task nodes+ taskNodes = await client.listByKind("task", { limit });+ }++ // 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,+ }));++ const total = results.length;++ // Filter by status if provided+ if (opts.status) {+ results = results.filter((t) => t.status === opts.status);+ }++ if (isJson) {+ console.log(+ JSON.stringify(+ {+ results,+ summary: { total, filtered: results.length },+ },+ null,+ 2+ )+ );+ } else {+ if (results.length === 0) {+ console.log(chalk.dim("No tasks found."));+ return;+ }+ console.log(chalk.bold(`Tasks (${results.length})`));+ for (const t of results) {+ const icon = STATUS_ICONS[t.status] ?? "?";+ console.log(+ ` ${icon} ${chalk.dim(`[${t.status}]`.padEnd(14))} ${t.name}`+ );+ }+ if (total !== results.length) {+ console.log(chalk.dim(`\n${results.length} of ${total} tasks shown (filtered by --status ${opts.status})`));+ }+ }+ }+ );+}diff --git a/ix-cli/src/cli/commands/workflows.ts b/ix-cli/src/cli/commands/workflows.tsnew file mode 100644index 00000000..0ba67378--- /dev/null+++ b/ix-cli/src/cli/commands/workflows.ts@@ -0,0 +1,38 @@+import type { Command } from "commander";++const WORKFLOWS_TEXT = `+Recommended Development Loop:++ 1. ix briefing Resume context+ 2. ix overview <target> Understand a component+ 3. ix impact <target> Check blast radius before changes+ 4. ix rank --by callers --kind method Find hotspots+ 5. ix plan next <id> --with-workflow Get next task with commands++Bug Workflow:+ ix bugs --status open See open bugs+ ix bug show <id> Get bug details+ ix plan create "Fix X" --goal <id> --responds-to <bugId>+ ix plan task "Step 1" --plan <id> --resolves <bugId>++Decision Recording:+ ix decide "Use X" --rationale "..." --affects Entity++Task Listing:+ ix tasks List all tasks+ ix tasks --status pending Only pending tasks+ ix tasks --plan <id> Tasks in a specific plan+`;++export function registerWorkflowsHelpCommand(program: Command): void {+ const help = program+ .command("help")+ .description("Additional help topics");++ help+ .command("workflows")+ .description("Show recommended development workflows")+ .action(() => {+ console.log(WORKFLOWS_TEXT);+ });+}diff --git a/ix-cli/src/cli/main.ts b/ix-cli/src/cli/main.tsindex 45a5dc1b..c3640540 100644--- a/ix-cli/src/cli/main.ts+++ b/ix-cli/src/cli/main.ts@@ -34,12 +34,36 @@ import { registerBugsCommand } from "./commands/bugs.js";import { registerPlansCommand } from "./commands/plans.js";import { registerWatchCommand } from "./commands/watch.js";import { registerBriefingCommand } from "./commands/briefing.js";+import { registerWorkflowsHelpCommand } from "./commands/workflows.js";+import { registerTasksCommand } from "./commands/tasks.js";++const HELP_HEADER = `+Workflow Commands (start here):+ briefing Session-resume briefing+ overview <target> One-shot structural summary+ impact <target> Blast-radius / dependency analysis+ rank Hotspot discovery by metric+ inventory List entities by kind++Planning & Tracking:+ plan Manage plans (create, task, status, next)+ task Manage tasks (show, update)+ tasks List all tasks across plans+ bug Manage bugs (create, show, update)+ bugs List bugs+ decide <title> Record a design decision+ goal Manage project goals++Use "ix help workflows" for the recommended development loop.+Use "ix <command> --help" for details on any command.+`;const program = new Command();program.name("ix").description("Ix Memory — Persistent Memory for LLM Systems")- .version("0.1.0");+ .version("0.1.0")+ .addHelpText("beforeAll", HELP_HEADER);registerQueryCommand(program);registerIngestCommand(program);@@ -76,5 +100,7 @@ registerBugsCommand(program);registerPlansCommand(program);registerWatchCommand(program);registerBriefingCommand(program);+registerWorkflowsHelpCommand(program);+registerTasksCommand(program);program.parse();diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.tsindex 18f9e4fc..3a3180c3 100644--- a/ix-cli/src/cli/resolve.ts+++ b/ix-cli/src/cli/resolve.ts@@ -2,7 +2,7 @@ import chalk from "chalk";import type { IxClient } from "../client/api.js";import { stderr } from "./stderr.js";-export type ResolutionMode = "exact" | "preferred-kind" | "ambiguous" | "heuristic";+export type ResolutionMode = "exact" | "preferred-kind" | "scored" | "ambiguous" | "heuristic";export interface ResolvedEntity {id: string;@@ -14,7 +14,7 @@ export interface ResolvedEntity {export interface AmbiguousResult {resolutionMode: "ambiguous";- candidates: Array<{ id: string; name: string; kind: string; path?: string }>;+ candidates: Array<{ id: string; name: string; kind: string; path?: string; score?: number }>;}export type ResolveResult =@@ -22,6 +22,74 @@ export type ResolveResult =| { resolved: false; ambiguous: true; result: AmbiguousResult }| { resolved: false; ambiguous: false };+// ── Structural kind sets ──────────────────────────────────────────────────++/** High-value container kinds — typically what callers want when resolving a bare name. */+const CONTAINER_KINDS = new Set(["file", "class", "object", "trait", "interface", "module"]);++/** All kinds that represent real code structure (vs. config/doc/decision). */+const STRUCTURAL_KINDS = new Set([+ ...CONTAINER_KINDS, "function", "method",+]);++// ── Scoring ───────────────────────────────────────────────────────────────++/**+ * Score a candidate node for resolution.+ * Lower is better. Combines:+ * - exact name match (0 vs 10)+ * - exact kind match when --kind provided (-5)+ * - strong path match when --path provided (-4)+ * - structural kind boost (-3 for container, -1 for method/function)+ * - penalty for fuzzy/incidental matches (+5)+ */+export function scoreCandidate(+ node: any,+ symbol: string,+ opts?: { kind?: string; path?: string }+): number {+ const name: string = (node.name || node.attrs?.name || "").toLowerCase();+ const kind: string = (node.kind || "").toLowerCase();+ const symbolLower = symbol.toLowerCase();+ const sourceUri: string = (node.provenance?.sourceUri ?? node.provenance?.source_uri ?? "").toLowerCase();++ let score = 50; // baseline++ // ── Name match ──────────────────────────────────────────────────────+ if (name === symbolLower) {+ score = 0; // exact name match — best tier+ } else if (name.startsWith(symbolLower)) {+ score = 15; // prefix match — moderate+ } else {+ score = 30; // fuzzy / incidental — poor+ }++ // ── Kind match ──────────────────────────────────────────────────────+ if (opts?.kind && kind === opts.kind.toLowerCase()) {+ score -= 5; // exact kind requested by user+ }++ // ── Structural boost ────────────────────────────────────────────────+ if (CONTAINER_KINDS.has(kind)) {+ score -= 3; // containers are high-value resolution targets+ } else if (STRUCTURAL_KINDS.has(kind)) {+ score -= 1; // methods/functions are useful but lower than containers+ }+ // non-structural kinds (config_entry, doc, decision, etc.) get no boost++ // ── Path match ──────────────────────────────────────────────────────+ if (opts?.path) {+ const pathLower = opts.path.toLowerCase();+ if (sourceUri.includes(pathLower)) {+ score -= 4; // strong path preference+ }+ }++ return score;+}++// ── Public API ────────────────────────────────────────────────────────────+/*** Resolve a symbol to a single entity, preferring specific kinds and path filters.* Returns null and prints guidance if no match or ambiguous.@@ -42,6 +110,10 @@ export async function resolveEntity(/*** Full resolution returning structured result for JSON consumers.+ *+ * Two-phase ranking:+ * Phase 1: Score exact-name candidates. If a clear winner exists, return it.+ * Phase 2: If no exact-name candidates or still ambiguous, include fuzzy matches.*/export async function resolveEntityFull(client: IxClient,@@ -50,7 +122,6 @@ export async function resolveEntityFull(opts?: { kind?: string; path?: string }): Promise<ResolveResult> {const kindFilter = opts?.kind;- const pathFilter = opts?.path;const nodes = await client.search(symbol, { limit: 20, kind: kindFilter });if (nodes.length === 0) {@@ -58,62 +129,129 @@ export async function resolveEntityFull(return { resolved: false, ambiguous: false };}- // Exact name matches only- const exact = nodes.filter((n: any) => {- const name = n.name || n.attrs?.name || "";- return name.toLowerCase() === symbol.toLowerCase();+ // ── Phase 1: Exact-name candidates ──────────────────────────────────+ const symbolLower = symbol.toLowerCase();+ const exactName = nodes.filter((n: any) => {+ const name = (n.name || n.attrs?.name || "").toLowerCase();+ return name === symbolLower;});- let candidates = exact.length > 0 ? exact : nodes;+ // Score exact-name candidates+ if (exactName.length > 0) {+ const winner = pickBest(exactName, symbol, preferredKinds, opts);+ if (winner) return winner;+ }- // Apply path filter if provided — prefer entities whose file path contains the filter- if (pathFilter) {- const pathMatches = candidates.filter((n: any) => {- const uri = n.provenance?.sourceUri ?? n.provenance?.source_uri ?? n.path ?? "";- return uri.includes(pathFilter);- });- if (pathMatches.length > 0) {- candidates = pathMatches;- }+ // ── Phase 2: Fall back to all candidates ────────────────────────────+ const winner = pickBest(nodes, symbol, preferredKinds, opts);+ if (winner) return winner;++ // Nothing resolved at all+ stderr(`No entity found matching "${symbol}".`);+ return { resolved: false, ambiguous: false };+}++/**+ * Given a candidate set, score them, dedup, and either pick a winner or declare ambiguity.+ */+function pickBest(+ candidates: any[],+ symbol: string,+ preferredKinds: string[],+ opts?: { kind?: string; path?: string }+): ResolveResult | null {+ // Score all candidates+ const scored = candidates.map(n => ({+ node: n,+ score: scoreCandidate(n, symbol, opts),+ }));++ // Sort by score ascending (lower = better)+ scored.sort((a, b) => {+ if (a.score !== b.score) return a.score - b.score;+ // Tie-break: prefer preferred kinds in order+ const aIdx = preferredKinds.indexOf(a.node.kind);+ const bIdx = preferredKinds.indexOf(b.node.kind);+ const aRank = aIdx >= 0 ? aIdx : preferredKinds.length;+ const bRank = bIdx >= 0 ? bIdx : preferredKinds.length;+ return aRank - bRank;+ });++ // Dedup by id+ const seen = new Set<string>();+ const unique = scored.filter(s => {+ if (seen.has(s.node.id)) return false;+ seen.add(s.node.id);+ return true;+ });++ if (unique.length === 0) return null;++ // If the best candidate has a clearly better score than the second, it wins+ const best = unique[0];+ const second = unique[1];++ // Single candidate — clear winner+ if (unique.length === 1) {+ return { resolved: true, entity: nodeToResolved(best.node, symbol, resolutionMode(best, opts)) };}- // If user specified --kind, take the first match- if (kindFilter) {- const node = candidates[0] as any;- return { resolved: true, entity: nodeToResolved(node, symbol, "exact") };+ // Best is significantly better than second (score gap >= 3) — winner+ if (second && best.score + 3 <= second.score) {+ return { resolved: true, entity: nodeToResolved(best.node, symbol, resolutionMode(best, opts)) };}- // Try preferred kinds in order- for (const pk of preferredKinds) {- const matches = candidates.filter((n: any) => n.kind === pk);- if (matches.length === 1) {- return { resolved: true, entity: nodeToResolved(matches[0], symbol, "preferred-kind") };- }- if (matches.length > 1) {- // Multiple matches of the same preferred kind — check if path disambiguates- if (pathFilter) {- // Path already filtered above, so if we still have multiple, it's genuinely ambiguous- return { resolved: false, ambiguous: true, result: buildAmbiguous(matches) };- }- // Without path filter, check if all are the same entity (dedup by id)- const uniqueIds = new Set(matches.map((n: any) => n.id));- if (uniqueIds.size === 1) {- return { resolved: true, entity: nodeToResolved(matches[0], symbol, "exact") };- }- return { resolved: false, ambiguous: true, result: buildAmbiguous(matches) };- }+ // If user specified --kind, take the best — they asked for it+ if (opts?.kind) {+ return { resolved: true, entity: nodeToResolved(best.node, symbol, "exact") };+ }++ // Check if all top candidates at the same score tier are the same entity+ const topScore = best.score;+ const topTier = unique.filter(s => s.score === topScore);+ const topIds = new Set(topTier.map(s => s.node.id));+ if (topIds.size === 1) {+ return { resolved: true, entity: nodeToResolved(best.node, symbol, resolutionMode(best, opts)) };}- // If only one candidate, use it- if (candidates.length === 1) {- const node = candidates[0] as any;- return { resolved: true, entity: nodeToResolved(node, symbol, "exact") };+ // If best is a container kind and second is a method/function, prefer the container+ const bestKind = (best.node.kind || "").toLowerCase();+ const secondKind = (second.node.kind || "").toLowerCase();+ if (CONTAINER_KINDS.has(bestKind) && !CONTAINER_KINDS.has(secondKind)) {+ return { resolved: true, entity: nodeToResolved(best.node, symbol, "scored") };+ }++ // If path was provided and best matches path but second doesn't, best wins+ if (opts?.path) {+ const bestUri = (best.node.provenance?.sourceUri ?? best.node.provenance?.source_uri ?? "").toLowerCase();+ const secondUri = (second.node.provenance?.sourceUri ?? second.node.provenance?.source_uri ?? "").toLowerCase();+ const pathLower = opts.path.toLowerCase();+ if (bestUri.includes(pathLower) && !secondUri.includes(pathLower)) {+ return { resolved: true, entity: nodeToResolved(best.node, symbol, "scored") };+ }}- // Multiple candidates, no preferred kind match — ambiguous- return { resolved: false, ambiguous: true, result: buildAmbiguous(candidates) };+ // Genuinely ambiguous — return only structurally relevant candidates+ const ambiguousCandidates = unique+ .filter(s => s.score <= topScore + 5) // only candidates within range+ .slice(0, 5);++ return {+ resolved: false,+ ambiguous: true,+ result: buildAmbiguous(ambiguousCandidates.map(s => s.node), ambiguousCandidates.map(s => s.score)),+ };}+function resolutionMode(scored: { score: number }, opts?: { kind?: string }): ResolutionMode {+ if (opts?.kind) return "exact";+ if (scored.score <= 0) return "exact";+ if (scored.score <= 5) return "preferred-kind";+ return "scored";+}++// ── Helpers ───────────────────────────────────────────────────────────────+function nodeToResolved(node: any, symbol: string, mode: ResolutionMode): ResolvedEntity {return {id: node.id,@@ -124,11 +262,11 @@ function nodeToResolved(node: any, symbol: string, mode: ResolutionMode): Resolv};}-function buildAmbiguous(nodes: any[]): AmbiguousResult {+function buildAmbiguous(nodes: any[], scores?: number[]): AmbiguousResult {const seen = new Set<string>();const candidates: AmbiguousResult["candidates"] = [];- for (const n of nodes.slice(0, 5)) {- const node = n as any;+ for (let i = 0; i < nodes.length && i < 5; i++) {+ const node = nodes[i] as any;if (seen.has(node.id)) continue;seen.add(node.id);candidates.push({@@ -136,6 +274,7 @@ function buildAmbiguous(nodes: any[]): AmbiguousResult {name: node.name || node.attrs?.name || "(unnamed)",kind: node.kind ?? "",path: node.provenance?.sourceUri ?? node.provenance?.source_uri ?? node.path,+ score: scores?.[i],});}return { resolutionMode: "ambiguous", candidates };