Skip to content

armgit / Ix

Public Imported from GitHub
0

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

fix: weighted search, CALLS extraction, help routing, and read ambiguity

Tanner Kocherd00b5fc17635
diff --git a/ix-cli/src/cli/__tests__/help-coverage.test.ts b/ix-cli/src/cli/__tests__/help-coverage.test.ts
new file mode 100644
index 00000000..61e44362
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/help-coverage.test.ts
@@ -0,0 +1,40 @@
+import { describe, it, expect } from "vitest";
+import * as fs from "node:fs";
+import * as path from "node:path";
+
+/**
+ * Verify that HELP_HEADER in main.ts mentions all core commands.
+ * This prevents regression where new commands become invisible.
+ */
+
+const mainTsPath = path.resolve(__dirname, "../main.ts");
+const mainTsContent = fs.readFileSync(mainTsPath, "utf-8");
+
+// Extract the HELP_HEADER string from main.ts
+const headerMatch = mainTsContent.match(/const HELP_HEADER = `([\s\S]*?)`;/);
+const HELP_HEADER = headerMatch?.[1] ?? "";
+
+const REQUIRED_COMMANDS = [
+ "read", "search", "locate", "contains", "callers", "callees",
+ "imports", "entity", "status", "stats", "doctor", "history", "diff",
+ "briefing", "overview", "impact", "rank", "inventory",
+ "plan", "task", "tasks", "bug", "bugs", "decide", "goal",
+ "ingest", "truth", "text", "explain",
+];
+
+describe("help coverage", () => {
+ it("HELP_HEADER is non-empty", () => {
+ expect(HELP_HEADER.length).toBeGreaterThan(100);
+ });
+
+ it("HELP_HEADER mentions all core commands", () => {
+ const missing: string[] = [];
+ for (const cmd of REQUIRED_COMMANDS) {
+ // Match command name at start of a line (with leading whitespace)
+ if (!HELP_HEADER.includes(cmd)) {
+ missing.push(cmd);
+ }
+ }
+ expect(missing).toEqual([]);
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/help-topics.test.ts b/ix-cli/src/cli/__tests__/help-topics.test.ts
new file mode 100644
index 00000000..9ec7010c
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/help-topics.test.ts
@@ -0,0 +1,34 @@
+import { describe, it, expect } from "vitest";
+import * as fs from "node:fs";
+import * as path from "node:path";
+
+/**
+ * Verify that the help command properly routes topic arguments
+ * to the matching command's help, not just the workflows subcommand.
+ */
+
+const workflowsTsPath = path.resolve(__dirname, "../commands/workflows.ts");
+const workflowsContent = fs.readFileSync(workflowsTsPath, "utf-8");
+
+describe("help topic routing", () => {
+ it("help command accepts an optional [topic] argument", () => {
+ // The help command should be registered as "help [topic]" not "help"
+ // so it can handle arbitrary topic names like task, plan, bug, goal
+ expect(workflowsContent).toContain('command("help [topic]")');
+ });
+
+ it("help action looks up commands on the program", () => {
+ // The action should delegate to program.commands for arbitrary topics
+ expect(workflowsContent).toContain("program.commands.find");
+ expect(workflowsContent).toContain("outputHelp");
+ });
+
+ it("help action handles the workflows topic directly", () => {
+ expect(workflowsContent).toContain('topic === "workflows"');
+ expect(workflowsContent).toContain("WORKFLOWS_TEXT");
+ });
+
+ it("help action handles unknown topics with an error", () => {
+ expect(workflowsContent).toContain("Unknown help topic");
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/read-symbol-spans.test.ts b/ix-cli/src/cli/__tests__/read-symbol-spans.test.ts
new file mode 100644
index 00000000..46cbdbcf
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/read-symbol-spans.test.ts
@@ -0,0 +1,83 @@
+import { describe, it, expect } from "vitest";
+
+/**
+ * Verify that read command logic correctly extracts symbol line ranges
+ * from entity attrs containing line_start / line_end.
+ */
+
+describe("read symbol span extraction", () => {
+ it("extracts lines using line_start and line_end from attrs", () => {
+ const node: { name: string; kind: string; attrs: Record<string, any>; provenance: Record<string, any> } = {
+ name: "MyClass",
+ kind: "class",
+ attrs: { line_start: 5, line_end: 10 },
+ provenance: { source_uri: "/tmp/test.ts" },
+ };
+
+ const lineStart = node.attrs?.line_start ?? 1;
+ const lineEnd = node.attrs?.line_end;
+
+ expect(lineStart).toBe(5);
+ expect(lineEnd).toBe(10);
+
+ // Simulate extracting lines from a file
+ const fileLines = [
+ "// line 1",
+ "// line 2",
+ "// line 3",
+ "// line 4",
+ "export class MyClass {", // line 5
+ " private x: number;", // line 6
+ " constructor() {}", // line 7
+ " getX() { return this.x }", // line 8
+ " setX(v: number) {}", // line 9
+ "}", // line 10
+ "// line 11",
+ "// line 12",
+ ];
+
+ const content = fileLines.slice(lineStart - 1, lineEnd).join("\n");
+ expect(content).toContain("export class MyClass");
+ expect(content).toContain("}");
+ expect(content).not.toContain("// line 1");
+ expect(content).not.toContain("// line 11");
+ // Should be exactly 6 lines (5 through 10)
+ expect(content.split("\n")).toHaveLength(6);
+ });
+
+ it("falls back to whole file when line_start and line_end are missing", () => {
+ const node: { name: string; kind: string; attrs: Record<string, any>; provenance: Record<string, any> } = {
+ name: "OldEntity",
+ kind: "class",
+ attrs: {},
+ provenance: { source_uri: "/tmp/old.ts" },
+ };
+
+ const lineStart = node.attrs?.line_start ?? 1;
+ const lineEnd = node.attrs?.line_end;
+
+ expect(lineStart).toBe(1);
+ expect(lineEnd).toBeUndefined();
+
+ // When lineEnd is undefined, read.ts uses allLines.length as effectiveEnd
+ const fileLines = ["a", "b", "c"];
+ const effectiveEnd = lineEnd ?? fileLines.length;
+ const content = fileLines.slice(lineStart - 1, effectiveEnd).join("\n");
+ expect(content).toBe("a\nb\nc");
+ });
+
+ it("handles camelCase attr names as fallback", () => {
+ const node: { name: string; kind: string; attrs: Record<string, any> } = {
+ name: "LegacyEntity",
+ kind: "function",
+ attrs: { lineStart: 3, lineEnd: 7 },
+ };
+
+ // read.ts checks both: node.attrs?.lineStart ?? node.attrs?.line_start
+ const lineStart = node.attrs?.lineStart ?? node.attrs?.line_start ?? 1;
+ const lineEnd = node.attrs?.lineEnd ?? node.attrs?.line_end;
+
+ expect(lineStart).toBe(3);
+ expect(lineEnd).toBe(7);
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/search-ranking.test.ts b/ix-cli/src/cli/__tests__/search-ranking.test.ts
new file mode 100644
index 00000000..ecb00327
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/search-ranking.test.ts
@@ -0,0 +1,116 @@
+import { describe, it, expect } from "vitest";
+
+/**
+ * Verify that search ranking correctly incorporates backend _search_weight.
+ *
+ * We replicate the rankScore logic here to test tier assignment
+ * without needing a running backend.
+ */
+
+/** Minimal scoreCandidate replica for testing (exact name = 0, prefix = 15, fuzzy = 30). */
+function scoreCandidate(node: any, term: string, opts?: { kind?: string; path?: string }): number {
+ const name: string = (node.name || "").toLowerCase();
+ const kind: string = (node.kind || "").toLowerCase();
+ const symbolLower = term.toLowerCase();
+ let score = 50;
+ if (name === symbolLower) score = 0;
+ else if (name.startsWith(symbolLower)) score = 15;
+ else score = 30;
+ if (opts?.kind && kind === opts.kind.toLowerCase()) score -= 5;
+ if (["class", "trait", "object", "interface", "module", "file"].includes(kind)) score -= 3;
+ else if (["function", "method"].includes(kind)) score -= 1;
+ return score;
+}
+
+/** Replicate the production rankScore logic for testing. */
+function rankScore(
+ node: any,
+ term: string,
+ requestedKind: string | undefined,
+ pathFilter: string | undefined,
+): { tier: number; score: number; matchSource: string } {
+ // Weight comes through attrs (embedded by AQL into attrs JSON)
+ const backendWeight: number = node.attrs?._search_weight ?? node._search_weight ?? 0;
+ const resolverScore = scoreCandidate(node, term, { kind: requestedKind, path: pathFilter });
+
+ if (backendWeight >= 100) {
+ if (resolverScore <= -3) return { tier: 0, score: -backendWeight + resolverScore, matchSource: "name_exact" };
+ if (resolverScore <= 0) return { tier: 1, score: -backendWeight + resolverScore, matchSource: "name_exact" };
+ return { tier: 2, score: -backendWeight + resolverScore, matchSource: "name_exact" };
+ }
+ if (backendWeight >= 60) {
+ return { tier: 3, score: -backendWeight + resolverScore, matchSource: "name_partial" };
+ }
+ if (backendWeight >= 40) return { tier: 4, score: -backendWeight, matchSource: "provenance" };
+ if (backendWeight >= 20) return { tier: 4, score: -backendWeight, matchSource: "claim_or_decision" };
+
+ if (resolverScore <= -8) return { tier: 0, score: resolverScore, matchSource: "resolver" };
+ if (resolverScore <= -3) return { tier: 0, score: resolverScore, matchSource: "resolver" };
+ if (resolverScore <= 0) return { tier: 1, score: resolverScore, matchSource: "resolver" };
+ if (resolverScore <= 2) return { tier: 2, score: resolverScore, matchSource: "resolver" };
+ return { tier: 5, score: resolverScore, matchSource: "attrs" };
+}
+
+describe("search ranking with backend weight", () => {
+ it("assigns tier 0-1 for exact name match with backend weight 100", () => {
+ // Weight comes through attrs (as it does from real backend after parseNode)
+ const node = { name: "IngestionService", kind: "class", attrs: { _search_weight: 100 } };
+ const result = rankScore(node, "IngestionService", "class", undefined);
+ expect(result.tier).toBeLessThanOrEqual(1);
+ expect(result.matchSource).toBe("name_exact");
+ });
+
+ it("assigns tier 3 for partial name match with backend weight 60", () => {
+ const node = { name: "IngestionServiceImpl", kind: "class", attrs: { _search_weight: 60 } };
+ const result = rankScore(node, "Ingestion", undefined, undefined);
+ expect(result.tier).toBe(3);
+ expect(result.matchSource).toBe("name_partial");
+ });
+
+ it("assigns tier 4 for provenance match with backend weight 40", () => {
+ const node = { name: "unrelated", kind: "file", attrs: { _search_weight: 40 } };
+ const result = rankScore(node, "ingestion", undefined, undefined);
+ expect(result.tier).toBe(4);
+ expect(result.matchSource).toBe("provenance");
+ });
+
+ it("assigns tier 4 for claim/decision match with backend weight 20", () => {
+ const node = { name: "something", kind: "decision", attrs: { _search_weight: 20 } };
+ const result = rankScore(node, "ingestion", undefined, undefined);
+ expect(result.tier).toBe(4);
+ expect(result.matchSource).toBe("claim_or_decision");
+ });
+
+ it("assigns tier 5 for no backend weight and fuzzy resolver match", () => {
+ const node = { name: "totally_different", kind: "function" };
+ const result = rankScore(node, "ingestion", undefined, undefined);
+ expect(result.tier).toBe(5);
+ expect(result.matchSource).toBe("attrs");
+ });
+
+ it("sorts exact matches above partial matches", () => {
+ const exact = { name: "Node", kind: "class", attrs: { _search_weight: 100 } };
+ const partial = { name: "NodeImpl", kind: "class", attrs: { _search_weight: 60 } };
+ const rExact = rankScore(exact, "Node", undefined, undefined);
+ const rPartial = rankScore(partial, "Node", undefined, undefined);
+ expect(rExact.tier).toBeLessThan(rPartial.tier);
+ });
+
+ it("reads weight from attrs (real backend path) not top-level", () => {
+ // This is the critical test: weight MUST come through attrs to survive
+ // the parseNode → GraphNode → JSON serialization pipeline
+ const nodeWithAttrsWeight = { name: "Node", kind: "class", attrs: { _search_weight: 100 } };
+ const nodeWithTopLevelWeight = { name: "Node", kind: "class", _search_weight: 100 };
+ const nodeWithNoWeight = { name: "Node", kind: "class", attrs: {} };
+
+ const r1 = rankScore(nodeWithAttrsWeight, "Node", undefined, undefined);
+ const r2 = rankScore(nodeWithTopLevelWeight, "Node", undefined, undefined);
+ const r3 = rankScore(nodeWithNoWeight, "Node", undefined, undefined);
+
+ // Both attrs and top-level paths should work (fallback chain)
+ expect(r1.tier).toBeLessThanOrEqual(2);
+ expect(r2.tier).toBeLessThanOrEqual(2);
+ // No weight → falls through to resolver
+ expect(r3.matchSource).toBe("resolver");
+ });
+});
diff --git a/ix-cli/src/cli/commands/callers.ts b/ix-cli/src/cli/commands/callers.ts
index de8c416d..2b4636a6 100644
--- a/ix-cli/src/cli/commands/callers.ts
+++ b/ix-cli/src/cli/commands/callers.ts
@@ -74,11 +74,12 @@ export function registerCallersCommand(program: Command): void {
},
diagnostics: [{
code: "text_fallback_used",
- message: "No graph-backed callers found; showing bounded lexical candidates.",
+ message: "No graph-backed CALLS edges found. If files were ingested before CALLS extraction was added, run: ix ingest --force --recursive .",
}],
}, null, 2));
} else {
- stderr(chalk.dim("No graph-backed callers found. Showing text-based candidate usages.\n"));
+ stderr(chalk.dim("No graph-backed CALLS edges found. Showing text-based candidate usages."));
+ stderr(chalk.dim("Tip: if files were ingested before CALLS extraction, run: ix ingest --force --recursive .\n"));
for (const r of textResults) {
const snippet = r.attrs?.snippet ?? "";
console.log(` ${chalk.dim(r.name)} ${snippet}`);
diff --git a/ix-cli/src/cli/commands/ingest.ts b/ix-cli/src/cli/commands/ingest.ts
index 3143500e..5a43c3c3 100644
--- a/ix-cli/src/cli/commands/ingest.ts
+++ b/ix-cli/src/cli/commands/ingest.ts
@@ -19,22 +19,25 @@ export function registerIngestCommand(program: Command): void {
program
.command("ingest [path]")
.description("Ingest source files or GitHub data into the knowledge graph")
+ .option("--path <dir>", "Path to ingest (alternative to positional argument)")
.option("--recursive", "Recursively ingest directory")
.option("--github <owner/repo>", "Ingest issues, PRs, and commits from a GitHub repository")
.option("--token <pat>", "GitHub personal access token")
.option("--since <date>", "Only fetch items updated after this date (ISO 8601)")
.option("--limit <n>", "Max items per category (default 50)", "50")
+ .option("--force", "Force re-ingest even if files are unchanged (useful after parser upgrades)")
.option("--format <fmt>", "Output format (text|json)", "text")
.option("--root <dir>", "Workspace root directory")
- .addHelpText("after", "\nExamples:\n ix ingest ./src --recursive\n ix ingest --github owner/repo\n ix ingest --github owner/repo --since 2026-01-01 --limit 20 --format json\n ix ingest --github owner/repo --token ghp_xxxx")
- .action(async (path: string | undefined, opts: {
- recursive?: boolean; github?: string; token?: string;
+ .addHelpText("after", "\nExamples:\n ix ingest ./src --recursive\n ix ingest --path ./src --recursive --force\n ix ingest --github owner/repo\n ix ingest --github owner/repo --since 2026-01-01 --limit 20 --format json\n ix ingest --github owner/repo --token ghp_xxxx")
+ .action(async (positionalPath: string | undefined, opts: {
+ path?: string; recursive?: boolean; force?: boolean; github?: string; token?: string;
since?: string; limit: string; format: string; root?: string
}) => {
+ const effectivePath = positionalPath ?? opts.path;
if (opts.github) {
await ingestGitHub(opts);
- } else if (path) {
- await ingestFiles(path, opts);
+ } else if (effectivePath) {
+ await ingestFiles(effectivePath, opts);
} else {
console.error("Error: provide a <path> or use --github <owner/repo>");
process.exit(1);
@@ -44,7 +47,7 @@ export function registerIngestCommand(program: Command): void {
async function ingestFiles(
path: string,
- opts: { recursive?: boolean; format: string; root?: string }
+ opts: { recursive?: boolean; force?: boolean; format: string; root?: string }
): Promise<void> {
const resolvedPath = nodePath.isAbsolute(path)
? path
@@ -60,7 +63,7 @@ async function ingestFiles(
}, 200) : null;
try {
- const result = await client.ingest(resolvedPath, opts.recursive);
+ const result = await client.ingest(resolvedPath, opts.recursive, opts.force);
if (interval) {
clearInterval(interval);
process.stderr.write("\r" + " ".repeat(40) + "\r");
diff --git a/ix-cli/src/cli/commands/overview.ts b/ix-cli/src/cli/commands/overview.ts
index f65485ae..f19a36cd 100644
--- a/ix-cli/src/cli/commands/overview.ts
+++ b/ix-cli/src/cli/commands/overview.ts
@@ -255,6 +255,10 @@ async function overviewCallable(
const callers = callersResult.nodes;
const callees = calleesResult.nodes;
+ if (callers.length === 0 && callees.length === 0) {
+ diagnostics.push("No CALLS edges found. If files were ingested before CALLS extraction, run: ix ingest --force --recursive .");
+ }
+
const decisions = decisionsResult.nodes.map((n: any) => ({
id: n.id,
title: n.name || n.attrs?.name || "(unnamed)",
@@ -324,5 +328,11 @@ async function overviewCallable(
console.log(` ${icon} [${b.status}] ${chalk.red(b.severity)} ${b.title}`);
}
}
+
+ if (diagnostics.length > 0) {
+ for (const d of diagnostics) {
+ console.log(chalk.dim(`\n ${d}`));
+ }
+ }
}
}
diff --git a/ix-cli/src/cli/commands/read.ts b/ix-cli/src/cli/commands/read.ts
index 7cb21c71..746e094f 100644
--- a/ix-cli/src/cli/commands/read.ts
+++ b/ix-cli/src/cli/commands/read.ts
@@ -4,7 +4,7 @@ import type { Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint, resolveWorkspaceRoot } from "../config.js";
-import { resolveEntity } from "../resolve.js";
+import { resolveEntityFull } from "../resolve.js";
import { stderr } from "../stderr.js";
import { isFileStale } from "../stale.js";
@@ -308,35 +308,32 @@ type SymbolResult =
/**
* Search the graph for a symbol using the shared scored resolver.
* read prefers file/structural entities (class, object, file) before methods/functions.
+ *
+ * Calls resolveEntityFull once to avoid duplicate ambiguity output.
*/
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 full = await resolveEntityFull(client, symbol, preferredKinds, opts);
- 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" };
+ if (full.resolved) {
+ const details = await client.entity(full.entity.id);
+ const fullNode = details.node as any;
+ const sourceUri = fullNode.provenance?.source_uri ?? fullNode.provenance?.sourceUri ?? null;
+ return { type: "resolved", node: fullNode, sourceUri };
+ }
+
+ if (full.ambiguous) {
+ return {
+ type: "ambiguous",
+ candidates: full.result.candidates.map(c => ({
+ name: c.name, kind: c.kind, path: c.path, id: c.id,
+ })),
+ };
}
- // 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 };
+ return { type: "not-found" };
}
diff --git a/ix-cli/src/cli/commands/search.ts b/ix-cli/src/cli/commands/search.ts
index bbe32e4b..d407b91b 100644
--- a/ix-cli/src/cli/commands/search.ts
+++ b/ix-cli/src/cli/commands/search.ts
@@ -13,15 +13,15 @@ const STRUCTURAL_KINDS = new Set([
* 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.
+ * Combines backend weight (_search_weight from AQL) with client-side
+ * resolver scoring for fine-grained ranking.
*
* 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
+ * 3 — partial name match (backend weight 60)
+ * 4 — provenance/claim/decision match
* 5 — fuzzy/incidental match
*/
function rankScore(
@@ -29,44 +29,45 @@ function rankScore(
term: string,
requestedKind: string | undefined,
pathFilter: string | undefined
-): number {
- // Use the shared resolver scoring as the base
+): { tier: number; score: number; matchSource: string } {
+ // Weight is embedded in attrs by the backend AQL (survives parseNode → GraphNode → JSON)
+ const backendWeight: number = node.attrs?._search_weight ?? (node as any)._search_weight ?? 0;
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;
+ // Backend weight provides relevance signal, resolver refines within tier
+ if (backendWeight >= 100) {
+ // Exact backend name match — use resolver to sub-rank
+ if (resolverScore <= -3) return { tier: 0, score: -backendWeight + resolverScore, matchSource: "name_exact" };
+ if (resolverScore <= 0) return { tier: 1, score: -backendWeight + resolverScore, matchSource: "name_exact" };
+ return { tier: 2, score: -backendWeight + resolverScore, matchSource: "name_exact" };
}
-
- // Tier 4: prefix match or name starts with term
- if (name.startsWith(termLower)) {
- return 4;
+ if (backendWeight >= 60) {
+ return { tier: 3, score: -backendWeight + resolverScore, matchSource: "name_partial" };
+ }
+ if (backendWeight >= 40) {
+ return { tier: 4, score: -backendWeight, matchSource: "provenance" };
+ }
+ if (backendWeight >= 20) {
+ return { tier: 4, score: -backendWeight, matchSource: "claim_or_decision" };
}
- return 5;
+ // No backend weight — fall back to pure resolver scoring
+ if (resolverScore <= -8) return { tier: 0, score: resolverScore, matchSource: "resolver" };
+ if (resolverScore <= -3) return { tier: 0, score: resolverScore, matchSource: "resolver" };
+ if (resolverScore <= 0) return { tier: 1, score: resolverScore, matchSource: "resolver" };
+ if (resolverScore <= 2) return { tier: 2, score: resolverScore, matchSource: "resolver" };
+ return { tier: 5, score: resolverScore, matchSource: "attrs" };
}
/**
- * Full sort key: (tier, structural-boost, name).
+ * Full sort key: (tier, sub-score, 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;
+function searchSort(
+ a: { node: any; rank: { tier: number; score: number; matchSource: string } },
+ b: { node: any; rank: { tier: number; score: number; matchSource: string } }
+): number {
+ if (a.rank.tier !== b.rank.tier) return a.rank.tier - b.rank.tier;
+ if (a.rank.score !== b.rank.score) return a.rank.score - b.rank.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;
@@ -116,15 +117,16 @@ Examples:
asOfRev: opts.asOf ? parseInt(opts.asOf, 10) : undefined,
});
- // Re-rank client-side using shared scoring
+ // Re-rank client-side using shared scoring + backend weight
const scored = nodes.map(n => ({
node: n,
- score: rankScore(n, term, opts.kind, opts.path),
+ rank: rankScore(n, term, opts.kind, opts.path),
}));
scored.sort(searchSort);
- const ranked = scored.slice(0, limit).map(s => s.node);
+ const trimmed = scored.slice(0, limit);
+ const ranked = trimmed.map(s => s.node);
if (opts.format === "json") {
const diagnostics: { code: string; message: string }[] = [];
@@ -135,13 +137,15 @@ Examples:
});
}
console.log(JSON.stringify({
- 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,
+ results: trimmed.map((s, i) => ({
+ id: s.node.id,
+ name: s.node.name || (s.node.attrs as any)?.name || "(unnamed)",
+ kind: s.node.kind,
+ path: s.node.provenance?.sourceUri ?? undefined,
rank: i + 1,
- tier: scored.find(s => s.node === n)?.score ?? 5,
+ tier: s.rank.tier,
+ score: s.rank.score,
+ matchSource: s.rank.matchSource,
})),
summary: {
count: ranked.length,
diff --git a/ix-cli/src/cli/commands/workflows.ts b/ix-cli/src/cli/commands/workflows.ts
index 0ba67378..c337e18e 100644
--- a/ix-cli/src/cli/commands/workflows.ts
+++ b/ix-cli/src/cli/commands/workflows.ts
@@ -26,13 +26,29 @@ Task Listing:
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);
+ .command("help [topic]")
+ .description("Additional help topics")
+ .action((topic: string | undefined) => {
+ if (!topic) {
+ // ix help — show full program help
+ program.outputHelp();
+ return;
+ }
+
+ if (topic === "workflows") {
+ console.log(WORKFLOWS_TEXT);
+ return;
+ }
+
+ // Look up the topic as a registered command and show its help
+ const cmd = program.commands.find(
+ (c: Command) => c.name() === topic
+ );
+ if (cmd) {
+ cmd.outputHelp();
+ } else {
+ console.error(`Unknown help topic: "${topic}". Try "ix --help" for available commands.`);
+ process.exitCode = 1;
+ }
});
}
diff --git a/ix-cli/src/cli/main.ts b/ix-cli/src/cli/main.ts
index c3640540..841238e8 100644
--- a/ix-cli/src/cli/main.ts
+++ b/ix-cli/src/cli/main.ts
@@ -54,6 +54,29 @@ Planning & Tracking:
decide <title> Record a design decision
goal Manage project goals
+Core Graph / Code Commands:
+ read <target> Read file content or symbol source code
+ search <term> Search the knowledge graph by term
+ locate <symbol> Resolve symbol to definition with context
+ contains <symbol> Show members of a class/module/file
+ callers <symbol> Show callers of a function/method
+ callees <symbol> Show callees of a function/method
+ imports <symbol> Show what an entity imports
+ imported-by <symbol> Show what imports an entity
+ depends <symbol> Show reverse dependencies
+ entity <id> Get entity details with claims and edges
+ explain <symbol> Explain an entity with history
+
+Diagnostics / State / History:
+ ingest [path] Ingest source files or GitHub data
+ status Show backend health
+ stats Show graph statistics
+ doctor Check system health
+ history <entityId> Show entity provenance chain
+ diff <from> <to> Show diff between revisions
+ truth Manage project intents
+ text <term> Fast lexical/text search (ripgrep)
+
Use "ix help workflows" for the recommended development loop.
Use "ix <command> --help" for details on any command.
`;
@@ -63,7 +86,7 @@ program
.name("ix")
.description("Ix Memory — Persistent Memory for LLM Systems")
.version("0.1.0")
- .addHelpText("beforeAll", HELP_HEADER);
+ .addHelpText("before", HELP_HEADER);
registerQueryCommand(program);
registerIngestCommand(program);
diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.ts
index 3a3180c3..ccd39bed 100644
--- a/ix-cli/src/cli/resolve.ts
+++ b/ix-cli/src/cli/resolve.ts
@@ -122,7 +122,7 @@ export async function resolveEntityFull(
opts?: { kind?: string; path?: string }
): Promise<ResolveResult> {
const kindFilter = opts?.kind;
- const nodes = await client.search(symbol, { limit: 20, kind: kindFilter });
+ const nodes = await client.search(symbol, { limit: 20, kind: kindFilter, nameOnly: true });
if (nodes.length === 0) {
stderr(`No entity found matching "${symbol}".`);
diff --git a/ix-cli/src/client/api.ts b/ix-cli/src/client/api.ts
index 8c71244f..dff096cf 100644
--- a/ix-cli/src/client/api.ts
+++ b/ix-cli/src/client/api.ts
@@ -19,11 +19,11 @@ export class IxClient {
return this.post("/v1/context", { query: question, ...opts });
}
- async ingest(path: string, recursive?: boolean): Promise<IngestResult> {
+ async ingest(path: string, recursive?: boolean, force?: boolean): Promise<IngestResult> {
const resp = await fetch(`${this.endpoint}/v1/ingest`, {
method: "POST",
headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ path, recursive }),
+ body: JSON.stringify({ path, recursive, force: force || undefined }),
signal: AbortSignal.timeout(30 * 60 * 1000), // 30 minute timeout for large repos
});
if (!resp.ok) {
@@ -43,7 +43,7 @@ export class IxClient {
async search(
term: string,
- opts?: { limit?: number; kind?: string; language?: string; asOfRev?: number }
+ opts?: { limit?: number; kind?: string; language?: string; asOfRev?: number; nameOnly?: boolean }
): Promise<GraphNode[]> {
return this.post("/v1/search", {
term,
@@ -51,6 +51,7 @@ export class IxClient {
kind: opts?.kind,
language: opts?.language,
asOfRev: opts?.asOfRev,
+ nameOnly: opts?.nameOnly,
});
}
diff --git a/memory-layer/src/main/scala/ix/memory/api/IngestionRoutes.scala b/memory-layer/src/main/scala/ix/memory/api/IngestionRoutes.scala
index b2334c56..d393c47d 100644
--- a/memory-layer/src/main/scala/ix/memory/api/IngestionRoutes.scala
+++ b/memory-layer/src/main/scala/ix/memory/api/IngestionRoutes.scala
@@ -12,7 +12,7 @@ import org.http4s.dsl.io._
import ix.memory.ingestion.{BulkIngestionService, IngestionProgress, IngestionService}
import org.typelevel.log4cats.slf4j.Slf4jLogger
-case class IngestRequest(path: String, language: Option[String], recursive: Option[Boolean])
+case class IngestRequest(path: String, language: Option[String], recursive: Option[Boolean], force: Option[Boolean])
object IngestRequest {
implicit val decoder: Decoder[IngestRequest] = deriveDecoder[IngestRequest]
@@ -50,7 +50,7 @@ class IngestionRoutes(ingestionService: IngestionService, bulkIngestionService:
new IllegalArgumentException("Path traversal not allowed")
)
path = Paths.get(body.path)
- result <- bulkIngestionService.ingestPath(path, body.language, body.recursive.getOrElse(false), progressLog)
+ result <- bulkIngestionService.ingestPath(path, body.language, body.recursive.getOrElse(false), progressLog, body.force.getOrElse(false))
resp <- Ok(IngestResponse(
filesProcessed = result.filesProcessed,
patchesApplied = result.patchesApplied,
diff --git a/memory-layer/src/main/scala/ix/memory/api/SearchRoutes.scala b/memory-layer/src/main/scala/ix/memory/api/SearchRoutes.scala
index 5800c466..10bec70d 100644
--- a/memory-layer/src/main/scala/ix/memory/api/SearchRoutes.scala
+++ b/memory-layer/src/main/scala/ix/memory/api/SearchRoutes.scala
@@ -16,7 +16,8 @@ case class SearchRequest(
limit: Option[Int] = None,
kind: Option[String] = None,
language: Option[String] = None,
- asOfRev: Option[Long] = None
+ asOfRev: Option[Long] = None,
+ nameOnly: Option[Boolean] = None
)
object SearchRequest {
@@ -29,7 +30,7 @@ class SearchRoutes(queryApi: GraphQueryApi) {
case req @ POST -> Root / "v1" / "search" =>
(for {
body <- req.as[SearchRequest]
- nodes <- queryApi.searchNodes(body.term, body.limit.getOrElse(20), body.kind, body.language, body.asOfRev.map(Rev(_)))
+ nodes <- queryApi.searchNodes(body.term, body.limit.getOrElse(20), body.kind, body.language, body.asOfRev.map(Rev(_)), body.nameOnly.getOrElse(false))
resp <- Ok(nodes.asJson)
} yield resp).handleErrorWith(ErrorHandler.handle(_))
}
diff --git a/memory-layer/src/main/scala/ix/memory/db/ArangoGraphQueryApi.scala b/memory-layer/src/main/scala/ix/memory/db/ArangoGraphQueryApi.scala
index 9a2162c7..50b91b5d 100644
--- a/memory-layer/src/main/scala/ix/memory/db/ArangoGraphQueryApi.scala
+++ b/memory-layer/src/main/scala/ix/memory/db/ArangoGraphQueryApi.scala
@@ -75,7 +75,8 @@ class ArangoGraphQueryApi(client: ArangoClient) extends GraphQueryApi {
limit: Int = 20,
kind: Option[String] = None,
language: Option[String] = None,
- asOfRev: Option[Rev] = None
+ asOfRev: Option[Rev] = None,
+ nameOnly: Boolean = false
): IO[Vector[GraphNode]] = {
val liveFilter = asOfRev match {
case Some(r) => s"AND n.created_rev <= ${r.value} AND (n.deleted_rev == null OR ${r.value} < n.deleted_rev)"
@@ -88,19 +89,39 @@ class ArangoGraphQueryApi(client: ArangoClient) extends GraphQueryApi {
val kindFilter = kind.map(_ => "FILTER n2.kind == @kind").getOrElse("")
val langFilter = language.map(_ => "FILTER CONTAINS(LOWER(TO_STRING(n2.provenance.source_uri)), LOWER(@language))").getOrElse("")
- val aql =
+ val nameOnlyAql =
s"""LET name_matches = (
| FOR n IN nodes
| FILTER CONTAINS(LOWER(n.name), LOWER(@text))
| $liveFilter
- | RETURN DISTINCT n.logical_id
+ | LET w = (LOWER(n.name) == LOWER(@text) ? 100 : 60)
+ | RETURN DISTINCT { id: n.logical_id, weight: w }
+ |)
+ |
+ |FOR entry IN name_matches
+ | FOR n2 IN nodes
+ | FILTER n2.logical_id == entry.id AND n2.deleted_rev == null
+ | $kindFilter
+ | $langFilter
+ | LET symbol_priority = n2.kind IN ["function", "method", "class", "trait", "object", "interface"] ? 0 : 1
+ | SORT entry.weight DESC, symbol_priority ASC, n2.name ASC
+ | LIMIT @limit
+ | RETURN MERGE(n2, { attrs: MERGE(n2.attrs, { _search_weight: entry.weight }) })""".stripMargin
+
+ val fullAql =
+ s"""LET name_matches = (
+ | FOR n IN nodes
+ | FILTER CONTAINS(LOWER(n.name), LOWER(@text))
+ | $liveFilter
+ | LET w = (LOWER(n.name) == LOWER(@text) ? 100 : 60)
+ | RETURN DISTINCT { id: n.logical_id, weight: w }
|)
|
|LET provenance_matches = (
| FOR n IN nodes
| FILTER CONTAINS(LOWER(n.provenance.source_uri), LOWER(@text))
| $liveFilter
- | RETURN DISTINCT n.logical_id
+ | RETURN DISTINCT { id: n.logical_id, weight: 40 }
|)
|
|LET claim_matches = (
@@ -110,7 +131,7 @@ class ArangoGraphQueryApi(client: ArangoClient) extends GraphQueryApi {
| OR CONTAINS(LOWER(TO_STRING(c.value)), LOWER(@text))
| )
| $claimLiveFilter
- | RETURN DISTINCT c.entity_id
+ | RETURN DISTINCT { id: c.entity_id, weight: 20 }
|)
|
|LET decision_matches = (
@@ -121,27 +142,35 @@ class ArangoGraphQueryApi(client: ArangoClient) extends GraphQueryApi {
| CONTAINS(LOWER(TO_STRING(n.attrs.title)), LOWER(@text))
| OR CONTAINS(LOWER(TO_STRING(n.attrs.rationale)), LOWER(@text))
| )
- | RETURN DISTINCT n.logical_id
+ | RETURN DISTINCT { id: n.logical_id, weight: 20 }
|)
|
|LET attr_matches = (
| FOR n IN nodes
| FILTER CONTAINS(LOWER(TO_STRING(n.attrs)), LOWER(@text))
| $liveFilter
- | RETURN DISTINCT n.logical_id
+ | RETURN DISTINCT { id: n.logical_id, weight: 10 }
|)
|
- |LET all_ids = UNION_DISTINCT(name_matches, provenance_matches, claim_matches, decision_matches, attr_matches)
+ |LET all_scored = UNION(name_matches, provenance_matches, claim_matches, decision_matches, attr_matches)
|
- |FOR id IN all_ids
+ |LET best_per_id = (
+ | FOR s IN all_scored
+ | COLLECT id = s.id AGGREGATE maxWeight = MAX(s.weight)
+ | RETURN { id, weight: maxWeight }
+ |)
+ |
+ |FOR entry IN best_per_id
| FOR n2 IN nodes
- | FILTER n2.logical_id == id AND n2.deleted_rev == null
+ | FILTER n2.logical_id == entry.id AND n2.deleted_rev == null
| $kindFilter
| $langFilter
| LET symbol_priority = n2.kind IN ["function", "method", "class", "trait", "object", "interface"] ? 0 : 1
- | SORT symbol_priority ASC, n2.name ASC
+ | SORT entry.weight DESC, symbol_priority ASC, n2.name ASC
| LIMIT @limit
- | RETURN n2""".stripMargin
+ | RETURN MERGE(n2, { attrs: MERGE(n2.attrs, { _search_weight: entry.weight }) })""".stripMargin
+
+ val aql = if (nameOnly) nameOnlyAql else fullAql
val binds = scala.collection.mutable.Map[String, AnyRef](
"text" -> text.asInstanceOf[AnyRef],
diff --git a/memory-layer/src/main/scala/ix/memory/db/GraphQueryApi.scala b/memory-layer/src/main/scala/ix/memory/db/GraphQueryApi.scala
index 3c27bfdb..7be285f8 100644
--- a/memory-layer/src/main/scala/ix/memory/db/GraphQueryApi.scala
+++ b/memory-layer/src/main/scala/ix/memory/db/GraphQueryApi.scala
@@ -10,7 +10,8 @@ trait GraphQueryApi {
def listDecisions(limit: Int = 50, topic: Option[String] = None): IO[Vector[GraphNode]]
def searchNodes(text: String, limit: Int = 20,
kind: Option[String] = None, language: Option[String] = None,
- asOfRev: Option[Rev] = None): IO[Vector[GraphNode]]
+ asOfRev: Option[Rev] = None,
+ nameOnly: Boolean = false): IO[Vector[GraphNode]]
def expand(nodeId: NodeId, direction: Direction,
predicates: Option[Set[String]] = None, hops: Int = 1,
asOfRev: Option[Rev] = None): IO[ExpandResult]
diff --git a/memory-layer/src/main/scala/ix/memory/ingestion/BulkIngestionService.scala b/memory-layer/src/main/scala/ix/memory/ingestion/BulkIngestionService.scala
index f4991319..3d685cf8 100644
--- a/memory-layer/src/main/scala/ix/memory/ingestion/BulkIngestionService.scala
+++ b/memory-layer/src/main/scala/ix/memory/ingestion/BulkIngestionService.scala
@@ -42,12 +42,13 @@ class BulkIngestionService(
path: Path,
language: Option[String],
recursive: Boolean,
- onProgress: IngestionProgress => IO[Unit] = _ => IO.unit
+ onProgress: IngestionProgress => IO[Unit] = _ => IO.unit,
+ force: Boolean = false
): IO[IngestionResult] = {
for {
files <- discoverFiles(path, language, recursive)
_ <- onProgress(IngestionProgress(files.size, 0, 0, 0))
- hashMap <- loadExistingHashes(files)
+ hashMap <- if (force) IO.pure(Map.empty[String, String]) else loadExistingHashes(files)
outcomes <- files.parTraverseN(parallelism) { f =>
parseFile(f, hashMap).handleErrorWith { err =>
logger.warn(s"Parse error: ${f.toString} — ${err.getMessage}") *>
diff --git a/memory-layer/src/main/scala/ix/memory/ingestion/GraphPatchBuilder.scala b/memory-layer/src/main/scala/ix/memory/ingestion/GraphPatchBuilder.scala
index d1f1c9d4..7ae90eb0 100644
--- a/memory-layer/src/main/scala/ix/memory/ingestion/GraphPatchBuilder.scala
+++ b/memory-layer/src/main/scala/ix/memory/ingestion/GraphPatchBuilder.scala
@@ -36,9 +36,12 @@ object GraphPatchBuilder {
else "unknown-parser/1.0"
val nodeOps = parseResult.entities.map { e =>
+ val baseAttrs = e.attrs +
+ ("line_start" -> Json.fromInt(e.lineStart)) +
+ ("line_end" -> Json.fromInt(e.lineEnd))
val attrsWithFp = e.contentFingerprint match {
- case Some(fp) => e.attrs + ("content_fingerprint" -> Json.fromString(fp))
- case None => e.attrs
+ case Some(fp) => baseAttrs + ("content_fingerprint" -> Json.fromString(fp))
+ case None => baseAttrs
}
PatchOp.UpsertNode(nodeIdFor(e.name), e.kind, e.name, attrsWithFp)
}
diff --git a/memory-layer/src/test/scala/ix/memory/db/SearchAqlSpec.scala b/memory-layer/src/test/scala/ix/memory/db/SearchAqlSpec.scala
new file mode 100644
index 00000000..cfa3d709
--- /dev/null
+++ b/memory-layer/src/test/scala/ix/memory/db/SearchAqlSpec.scala
@@ -0,0 +1,37 @@
+package ix.memory.db
+
+import org.scalatest.flatspec.AnyFlatSpec
+import org.scalatest.matchers.should.Matchers
+
+/**
+ * Verify that search AQL queries use Arango-compatible functions.
+ * COALESCE() is SQL — ArangoDB uses NOT_NULL() or direct field access.
+ */
+class SearchAqlSpec extends AnyFlatSpec with Matchers {
+
+ // Read the source file to inspect AQL strings
+ private val sourceFile = scala.io.Source.fromFile(
+ "memory-layer/src/main/scala/ix/memory/db/ArangoGraphQueryApi.scala"
+ ).mkString
+
+ "ArangoGraphQueryApi AQL" should "not use COALESCE (not valid AQL)" in {
+ sourceFile should not include "COALESCE"
+ }
+
+ it should "embed _search_weight into attrs via MERGE" in {
+ sourceFile should include ("_search_weight: entry.weight")
+ sourceFile should include ("MERGE(n2.attrs, { _search_weight")
+ }
+
+ it should "use weighted scoring in nameOnly mode" in {
+ // nameOnly AQL should still return weight
+ sourceFile should include ("LOWER(n.name) == LOWER(@text) ? 100 : 60")
+ }
+
+ it should "use weighted scoring in full mode with multiple match tiers" in {
+ // Full AQL should have name (100/60), provenance (40), claim (20), decision (20), attrs (10)
+ sourceFile should include ("weight: 40")
+ sourceFile should include ("weight: 20")
+ sourceFile should include ("weight: 10")
+ }
+}
diff --git a/memory-layer/src/test/scala/ix/memory/ingestion/GraphPatchBuilderSpec.scala b/memory-layer/src/test/scala/ix/memory/ingestion/GraphPatchBuilderSpec.scala
new file mode 100644
index 00000000..f8734e98
--- /dev/null
+++ b/memory-layer/src/test/scala/ix/memory/ingestion/GraphPatchBuilderSpec.scala
@@ -0,0 +1,95 @@
+package ix.memory.ingestion
+
+import org.scalatest.flatspec.AnyFlatSpec
+import org.scalatest.matchers.should.Matchers
+import io.circe.Json
+
+import ix.memory.model._
+
+class GraphPatchBuilderSpec extends AnyFlatSpec with Matchers {
+
+ private def mkEntity(
+ name: String,
+ kind: NodeKind,
+ lineStart: Int,
+ lineEnd: Int,
+ attrs: Map[String, Json] = Map.empty,
+ contentFingerprint: Option[String] = None
+ ): ParsedEntity =
+ ParsedEntity(name, kind, attrs, lineStart, lineEnd, contentFingerprint)
+
+ "GraphPatchBuilder" should "include line_start and line_end in UpsertNode attrs" in {
+ val parseResult = ParseResult(
+ entities = Vector(
+ mkEntity("MyClass", NodeKind.Class, lineStart = 5, lineEnd = 25),
+ mkEntity("myMethod", NodeKind.Method, lineStart = 10, lineEnd = 20)
+ ),
+ relationships = Vector.empty
+ )
+
+ val patch = GraphPatchBuilder.build("src/main.ts", Some("abc123"), parseResult)
+ val upsertNodes = patch.ops.collect { case op: PatchOp.UpsertNode => op }
+
+ upsertNodes should have size 2
+
+ val classNode = upsertNodes.find(_.name == "MyClass").get
+ classNode.attrs("line_start") shouldBe Json.fromInt(5)
+ classNode.attrs("line_end") shouldBe Json.fromInt(25)
+
+ val methodNode = upsertNodes.find(_.name == "myMethod").get
+ methodNode.attrs("line_start") shouldBe Json.fromInt(10)
+ methodNode.attrs("line_end") shouldBe Json.fromInt(20)
+ }
+
+ it should "include content_fingerprint alongside line spans" in {
+ val parseResult = ParseResult(
+ entities = Vector(
+ mkEntity("MyClass", NodeKind.Class, lineStart = 1, lineEnd = 50, contentFingerprint = Some("fp123"))
+ ),
+ relationships = Vector.empty
+ )
+
+ val patch = GraphPatchBuilder.build("src/main.ts", Some("abc"), parseResult)
+ val node = patch.ops.collect { case op: PatchOp.UpsertNode => op }.head
+
+ node.attrs("line_start") shouldBe Json.fromInt(1)
+ node.attrs("line_end") shouldBe Json.fromInt(50)
+ node.attrs("content_fingerprint") shouldBe Json.fromString("fp123")
+ }
+
+ it should "not generate claims for line_start or line_end" in {
+ val parseResult = ParseResult(
+ entities = Vector(
+ mkEntity("MyClass", NodeKind.Class, lineStart = 5, lineEnd = 25,
+ attrs = Map("language" -> Json.fromString("typescript")))
+ ),
+ relationships = Vector.empty
+ )
+
+ val patch = GraphPatchBuilder.build("src/main.ts", Some("abc"), parseResult)
+ val claims = patch.ops.collect { case op: PatchOp.AssertClaim => op }
+
+ // Should only have a claim for "language", not for line_start/line_end
+ claims.map(_.field) should contain("language")
+ claims.map(_.field) should not contain "line_start"
+ claims.map(_.field) should not contain "line_end"
+ }
+
+ it should "preserve existing attrs alongside line spans" in {
+ val parseResult = ParseResult(
+ entities = Vector(
+ mkEntity("myFunc", NodeKind.Function, lineStart = 3, lineEnd = 8,
+ attrs = Map("visibility" -> Json.fromString("public"), "language" -> Json.fromString("scala")))
+ ),
+ relationships = Vector.empty
+ )
+
+ val patch = GraphPatchBuilder.build("src/main.scala", None, parseResult)
+ val node = patch.ops.collect { case op: PatchOp.UpsertNode => op }.head
+
+ node.attrs("line_start") shouldBe Json.fromInt(3)
+ node.attrs("line_end") shouldBe Json.fromInt(8)
+ node.attrs("visibility") shouldBe Json.fromString("public")
+ node.attrs("language") shouldBe Json.fromString("scala")
+ }
+}
diff --git a/memory-layer/src/test/scala/ix/memory/ingestion/parsers/ScalaParserSpec.scala b/memory-layer/src/test/scala/ix/memory/ingestion/parsers/ScalaParserSpec.scala
index 0fd4beaf..3e41edc0 100644
--- a/memory-layer/src/test/scala/ix/memory/ingestion/parsers/ScalaParserSpec.scala
+++ b/memory-layer/src/test/scala/ix/memory/ingestion/parsers/ScalaParserSpec.scala
@@ -163,4 +163,41 @@ class ScalaParserSpec extends AnyFlatSpec with Matchers {
val obj = result.entities.find(e => e.name == "ConfidenceScorerImpl" && e.kind == NodeKind.Object).get
obj.attrs.get("scala_kind") shouldBe Some(Json.fromString("object"))
}
+
+ // --- Symbol span tests ---
+
+ it should "compute lineStart and lineEnd for trait definitions" in {
+ val result = parser.parse("ConfidenceScorer.scala", sampleCode)
+ val tr = result.entities.find(e => e.name == "ConfidenceScorer" && e.kind == NodeKind.Trait).get
+ tr.lineStart should be >= 1
+ tr.lineEnd should be > tr.lineStart
+ }
+
+ it should "compute lineStart and lineEnd for class definitions" in {
+ val result = parser.parse("ConfidenceScorer.scala", sampleCode)
+ val cls = result.entities.find(e => e.name == "ConfidenceScorerImpl" && e.kind == NodeKind.Class).get
+ cls.lineStart should be >= 1
+ cls.lineEnd should be > cls.lineStart
+ }
+
+ it should "compute lineStart and lineEnd for object definitions" in {
+ val result = parser.parse("ConfidenceScorer.scala", sampleCode)
+ val obj = result.entities.find(e => e.name == "ConfidenceScorerImpl" && e.kind == NodeKind.Object).get
+ obj.lineStart should be >= 1
+ obj.lineEnd should be > obj.lineStart
+ }
+
+ it should "compute method spans with valid ranges" in {
+ val result = parser.parse("ConfidenceScorer.scala", sampleCode)
+ val methods = result.entities.filter(_.kind == NodeKind.Method)
+ methods should not be empty
+ methods.foreach { m =>
+ m.lineStart should be >= 1
+ m.lineEnd should be >= m.lineStart
+ }
+ // computeBase is private to ConfidenceScorerImpl — verify it has a bounded span
+ val computeBase = result.entities.find(_.name == "computeBase").get
+ computeBase.lineStart should be > 1
+ computeBase.lineEnd should be > computeBase.lineStart
+ }
}
diff --git a/memory-layer/src/test/scala/ix/memory/ingestion/parsers/TypeScriptParserSpec.scala b/memory-layer/src/test/scala/ix/memory/ingestion/parsers/TypeScriptParserSpec.scala
index c3442c78..36f83960 100644
--- a/memory-layer/src/test/scala/ix/memory/ingestion/parsers/TypeScriptParserSpec.scala
+++ b/memory-layer/src/test/scala/ix/memory/ingestion/parsers/TypeScriptParserSpec.scala
@@ -318,4 +318,77 @@ class TypeScriptParserSpec extends AnyFlatSpec with Matchers {
fetch.attrs.get("signature").flatMap(_.asString) shouldBe defined
fetch.attrs("signature").asString.get should include("fetch")
}
+
+ // --- Symbol span tests ---
+
+ it should "compute lineStart and lineEnd for classes" in {
+ val source = """// header
+ |
+ |export class UserService {
+ | getUser(id: string): User {
+ | return this.db.find(id);
+ | }
+ |}
+ |
+ |// footer
+ """.stripMargin
+ val result = parser.parse("service.ts", source)
+ val cls = result.entities.find(e => e.name == "UserService" && e.kind == NodeKind.Class).get
+ cls.lineStart should be >= 1
+ cls.lineEnd should be > cls.lineStart
+ }
+
+ it should "extract CALLS between module-level functions" in {
+ val source = """
+ |export async function resolveEntityFull(client: any, symbol: string) {
+ | const result = pickBest(candidates, symbol);
+ | return result;
+ |}
+ |
+ |function pickBest(candidates: any[], symbol: string) {
+ | return candidates[0];
+ |}
+ """.stripMargin
+ val result = parser.parse("resolve.ts", source)
+ result.relationships.exists(r =>
+ r.srcName == "resolveEntityFull" && r.dstName == "pickBest" && r.predicate == "CALLS"
+ ) shouldBe true
+ }
+
+ it should "extract CALLS for await-prefixed function calls" in {
+ val source = """
+ |async function processData(url: string) {
+ | const data = await fetchRemote(url);
+ | return transform(data);
+ |}
+ """.stripMargin
+ val result = parser.parse("process.ts", source)
+ result.relationships.exists(r =>
+ r.srcName == "processData" && r.dstName == "fetchRemote" && r.predicate == "CALLS"
+ ) shouldBe true
+ result.relationships.exists(r =>
+ r.srcName == "processData" && r.dstName == "transform" && r.predicate == "CALLS"
+ ) shouldBe true
+ }
+
+ it should "compute method spans bounded within their class" in {
+ val source = """export class Api {
+ | fetch(url: string) {
+ | return url;
+ | }
+ |
+ | parse(data: string) {
+ | return data;
+ | }
+ |}
+ """.stripMargin
+ val result = parser.parse("api.ts", source)
+ val cls = result.entities.find(e => e.name == "Api" && e.kind == NodeKind.Class).get
+ val methods = result.entities.filter(_.kind == NodeKind.Method)
+ methods should not be empty
+ methods.foreach { m =>
+ m.lineStart should be >= cls.lineStart
+ m.lineEnd should be <= cls.lineEnd
+ }
+ }
}