Skip to content

armgit / Ix

Public Imported from GitHub
0

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

fix: TS/JS CALLS graph correction — brace matching, edge IDs, search relevance

Tanner Kocher98a1644122e7
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 50b91b5d..1d3aee1c 100644
--- a/memory-layer/src/main/scala/ix/memory/db/ArangoGraphQueryApi.scala
+++ b/memory-layer/src/main/scala/ix/memory/db/ArangoGraphQueryApi.scala
@@ -108,6 +108,18 @@ class ArangoGraphQueryApi(client: ArangoClient) extends GraphQueryApi {
| LIMIT @limit
| RETURN MERGE(n2, { attrs: MERGE(n2.attrs, { _search_weight: entry.weight }) })""".stripMargin
+ // Gate attr_matches on term length to avoid noise from short/common terms
+ val attrMatchAql = if (text.length >= 6) {
+ s"""LET attr_matches = (
+ | FOR n IN nodes
+ | FILTER CONTAINS(LOWER(TO_STRING(n.attrs)), LOWER(@text))
+ | $liveFilter
+ | RETURN DISTINCT { id: n.logical_id, weight: 10 }
+ |)""".stripMargin
+ } else {
+ "LET attr_matches = []"
+ }
+
val fullAql =
s"""LET name_matches = (
| FOR n IN nodes
@@ -145,12 +157,7 @@ class ArangoGraphQueryApi(client: ArangoClient) extends GraphQueryApi {
| 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 { id: n.logical_id, weight: 10 }
- |)
+ |$attrMatchAql
|
|LET all_scored = UNION(name_matches, provenance_matches, claim_matches, decision_matches, attr_matches)
|
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 7ae90eb0..c11587ef 100644
--- a/memory-layer/src/main/scala/ix/memory/ingestion/GraphPatchBuilder.scala
+++ b/memory-layer/src/main/scala/ix/memory/ingestion/GraphPatchBuilder.scala
@@ -26,7 +26,7 @@ object GraphPatchBuilder {
NodeId(UUID.nameUUIDFromBytes(s"$filePath:$name".getBytes("UTF-8")))
def edgeIdFor(src: String, dst: String, predicate: String): EdgeId =
- EdgeId(UUID.nameUUIDFromBytes(s"$src:$dst:$predicate".getBytes("UTF-8")))
+ EdgeId(UUID.nameUUIDFromBytes(s"$filePath:$src:$dst:$predicate".getBytes("UTF-8")))
val extractor = if (filePath.endsWith(".py")) "tree-sitter-python/1.0"
else if (filePath.endsWith(".ts") || filePath.endsWith(".tsx")) "typescript-parser/1.0"
diff --git a/memory-layer/src/main/scala/ix/memory/ingestion/parsers/TypeScriptParser.scala b/memory-layer/src/main/scala/ix/memory/ingestion/parsers/TypeScriptParser.scala
index 4ef7f691..9535a061 100644
--- a/memory-layer/src/main/scala/ix/memory/ingestion/parsers/TypeScriptParser.scala
+++ b/memory-layer/src/main/scala/ix/memory/ingestion/parsers/TypeScriptParser.scala
@@ -293,17 +293,26 @@ class TypeScriptParser extends Parser {
/**
* Find end of a brace-delimited block starting near `startIdx`.
+ *
+ * Uses end-of-line brace depth to detect block entry. This correctly
+ * skips inline TypeScript type annotations like `{ kind?: string }`
+ * that balance to zero on a single line, which would otherwise cause
+ * the parser to think the function body ended on the parameter line.
*/
private def findBraceBlockEnd(lines: Array[String], startIdx: Int): Int = {
var braceCount = 0
- var foundOpen = false
+ var entered = false
var i = startIdx
while (i < lines.length) {
for (ch <- lines(i)) {
- if (ch == '{') { braceCount += 1; foundOpen = true }
+ if (ch == '{') braceCount += 1
if (ch == '}') braceCount -= 1
}
- if (foundOpen && braceCount <= 0) return i + 1
+ // Only mark as entered when braceCount > 0 at end of line.
+ // This skips inline type annotations like { a: string; b: number }
+ // that balance to 0 within the same line.
+ if (!entered && braceCount > 0) entered = true
+ if (entered && braceCount <= 0) return i + 1
i += 1
}
lines.length
@@ -354,6 +363,18 @@ class TypeScriptParser extends Parser {
"WeakMap", "WeakSet", "Symbol",
"setTimeout", "setInterval", "clearTimeout", "clearInterval",
"require", "module", "exports",
- "fetch", "Response", "Request", "URL", "Buffer", "process"
+ "fetch", "Response", "Request", "URL", "Buffer", "process",
+ // Array/iterable methods
+ "map", "filter", "reduce", "forEach", "sort", "find", "some", "every",
+ "includes", "indexOf", "slice", "splice", "push", "pop", "shift", "unshift",
+ "concat", "join", "flat", "flatMap", "fill", "from",
+ // String methods
+ "split", "replace", "trim", "toUpperCase", "toLowerCase", "substring",
+ "charAt", "startsWith", "endsWith", "padStart", "padEnd", "match", "test",
+ // Object methods
+ "keys", "values", "entries", "assign", "create", "freeze",
+ "defineProperty", "getOwnPropertyNames", "hasOwnProperty",
+ // Promise methods
+ "then", "catch", "finally", "all", "race", "resolve", "reject"
)
}
diff --git a/memory-layer/src/test/scala/ix/memory/db/SearchAqlSpec.scala b/memory-layer/src/test/scala/ix/memory/db/SearchAqlSpec.scala
index cfa3d709..a8ae4909 100644
--- a/memory-layer/src/test/scala/ix/memory/db/SearchAqlSpec.scala
+++ b/memory-layer/src/test/scala/ix/memory/db/SearchAqlSpec.scala
@@ -34,4 +34,18 @@ class SearchAqlSpec extends AnyFlatSpec with Matchers {
sourceFile should include ("weight: 20")
sourceFile should include ("weight: 10")
}
+
+ it should "gate attr_matches on minimum term length to avoid short-term noise" in {
+ // The code should check text.length >= 6 before including attr_matches
+ sourceFile should include ("text.length >= 6")
+ sourceFile should include ("LET attr_matches = []")
+ }
+
+ it should "include filePath in edge ID generation for cross-file uniqueness" in {
+ // Read the GraphPatchBuilder source to verify edge IDs include filePath
+ val gpbSource = scala.io.Source.fromFile(
+ "memory-layer/src/main/scala/ix/memory/ingestion/GraphPatchBuilder.scala"
+ ).mkString
+ gpbSource should include ("$filePath:$src:$dst:$predicate")
+ }
}
diff --git a/memory-layer/src/test/scala/ix/memory/ingestion/GraphPatchBuilderSpec.scala b/memory-layer/src/test/scala/ix/memory/ingestion/GraphPatchBuilderSpec.scala
index f8734e98..647cd602 100644
--- a/memory-layer/src/test/scala/ix/memory/ingestion/GraphPatchBuilderSpec.scala
+++ b/memory-layer/src/test/scala/ix/memory/ingestion/GraphPatchBuilderSpec.scala
@@ -75,6 +75,80 @@ class GraphPatchBuilderSpec extends AnyFlatSpec with Matchers {
claims.map(_.field) should not contain "line_end"
}
+ it should "generate distinct edge IDs for same-name CALLS in different files" in {
+ val rel = ParsedRelationship("main", "helper", "CALLS")
+ val pr = ParseResult(
+ entities = Vector(
+ mkEntity("main", NodeKind.Function, 1, 10),
+ mkEntity("helper", NodeKind.Function, 12, 20)
+ ),
+ relationships = Vector(rel)
+ )
+
+ val patchA = GraphPatchBuilder.build("src/a.ts", None, pr)
+ val patchB = GraphPatchBuilder.build("src/b.ts", None, pr)
+
+ val edgeA = patchA.ops.collect { case op: PatchOp.UpsertEdge => op }.head
+ val edgeB = patchB.ops.collect { case op: PatchOp.UpsertEdge => op }.head
+
+ edgeA.id should not be edgeB.id
+ }
+
+ it should "generate distinct node IDs for same-name entities in different files" in {
+ val pr = ParseResult(
+ entities = Vector(mkEntity("main", NodeKind.Function, 1, 10)),
+ relationships = Vector.empty
+ )
+
+ val patchA = GraphPatchBuilder.build("src/a.ts", None, pr)
+ val patchB = GraphPatchBuilder.build("src/b.ts", None, pr)
+
+ val nodeA = patchA.ops.collect { case op: PatchOp.UpsertNode => op }.head
+ val nodeB = patchB.ops.collect { case op: PatchOp.UpsertNode => op }.head
+
+ nodeA.id should not be nodeB.id
+ }
+
+ it should "produce CALLS edges with matching src/dst node IDs for TS functions" in {
+ // End-to-end: parser → GraphPatchBuilder produces edges whose
+ // src/dst match the node IDs created for the same functions.
+ val parser = new ix.memory.ingestion.parsers.TypeScriptParser()
+ val source = """
+ |export async function resolveEntityFull(
+ | client: any,
+ | symbol: string,
+ | opts?: { kind?: string; path?: string }
+ |): Promise<any> {
+ | const winner = pickBest(candidates, symbol);
+ | return winner;
+ |}
+ |
+ |function pickBest(candidates: any[], symbol: string) {
+ | return candidates[0];
+ |}
+ """.stripMargin
+
+ val parseResult = parser.parse("resolve.ts", source)
+ val filePath = "/project/ix-cli/src/cli/resolve.ts"
+ val patch = GraphPatchBuilder.build(filePath, Some("hash"), parseResult)
+
+ val nodes = patch.ops.collect { case op: PatchOp.UpsertNode => op }
+ val edges = patch.ops.collect { case op: PatchOp.UpsertEdge => op }
+
+ // Find the CALLS edge
+ val callsEdges = edges.filter(_.predicate == EdgePredicate("CALLS"))
+ callsEdges should not be empty
+
+ val resolveToPickBest = callsEdges.find(e => {
+ val srcNode = nodes.find(_.id == NodeId(e.src.value))
+ val dstNode = nodes.find(_.id == NodeId(e.dst.value))
+ srcNode.exists(_.name == "resolveEntityFull") &&
+ dstNode.exists(_.name == "pickBest")
+ })
+
+ resolveToPickBest shouldBe defined
+ }
+
it should "preserve existing attrs alongside line spans" in {
val parseResult = ParseResult(
entities = Vector(
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 36f83960..37fbdf4d 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
@@ -371,6 +371,118 @@ class TypeScriptParserSpec extends AnyFlatSpec with Matchers {
) shouldBe true
}
+ it should "extract CALLS through functions with object-type parameters" in {
+ // This is the exact pattern that broke pickBest extraction in resolve.ts:
+ // the { kind?: string; path?: string } type annotation was confusing
+ // findBraceBlockEnd because braces in the type balanced on the same line.
+ val source = """
+ |export async function resolveEntityFull(
+ | client: IxClient,
+ | symbol: string,
+ | preferredKinds: string[],
+ | opts?: { kind?: string; path?: string }
+ |): Promise<ResolveResult> {
+ | const exactName = nodes.filter((n: any) => n.name === symbol);
+ | const winner = pickBest(exactName, symbol, preferredKinds, opts);
+ | if (winner) return winner;
+ | return { resolved: false, ambiguous: false };
+ |}
+ |
+ |function pickBest(
+ | candidates: any[],
+ | symbol: string,
+ | preferredKinds: string[],
+ | opts?: { kind?: string; path?: string }
+ |): ResolveResult | null {
+ | const scored = candidates.map(n => ({
+ | node: n,
+ | score: scoreCandidate(n, symbol, opts),
+ | }));
+ | scored.sort((a, b) => a.score - b.score);
+ | return scored.length > 0 ? scored[0] : null;
+ |}
+ """.stripMargin
+ val result = parser.parse("resolve.ts", source)
+
+ // resolveEntityFull should call pickBest
+ result.relationships.exists(r =>
+ r.srcName == "resolveEntityFull" && r.dstName == "pickBest" && r.predicate == "CALLS"
+ ) shouldBe true
+
+ // pickBest should call scoreCandidate (not map/sort which are builtins)
+ result.relationships.exists(r =>
+ r.srcName == "pickBest" && r.dstName == "scoreCandidate" && r.predicate == "CALLS"
+ ) shouldBe true
+
+ // Array builtins should NOT appear as CALLS targets
+ result.relationships.exists(r =>
+ r.predicate == "CALLS" && r.dstName == "map"
+ ) shouldBe false
+ result.relationships.exists(r =>
+ r.predicate == "CALLS" && r.dstName == "sort"
+ ) shouldBe false
+ }
+
+ it should "handle braces in function return types" in {
+ val source = """
+ |function getData(): { name: string; age: number } {
+ | return processResult();
+ |}
+ """.stripMargin
+ val result = parser.parse("data.ts", source)
+ result.relationships.exists(r =>
+ r.srcName == "getData" && r.dstName == "processResult" && r.predicate == "CALLS"
+ ) shouldBe true
+ }
+
+ it should "handle class method calls and this.method patterns" in {
+ val source = """
+ |class Service {
+ | async process(input: string) {
+ | const data = this.validate(input);
+ | return transform(data);
+ | }
+ |
+ | private validate(s: string) {
+ | return check(s);
+ | }
+ |}
+ """.stripMargin
+ val result = parser.parse("service.ts", source)
+ // process should call transform (bare function call)
+ result.relationships.exists(r =>
+ r.srcName == "process" && r.dstName == "transform" && r.predicate == "CALLS"
+ ) shouldBe true
+ // validate should call check
+ result.relationships.exists(r =>
+ r.srcName == "validate" && r.dstName == "check" && r.predicate == "CALLS"
+ ) shouldBe true
+ }
+
+ it should "not extract builtins like filter, map, forEach as CALLS" in {
+ val source = """
+ |function processItems(items: Item[]) {
+ | const filtered = items.filter(i => i.active);
+ | const mapped = filtered.map(i => i.name);
+ | mapped.forEach(n => console.log(n));
+ | const found = items.find(i => i.id === "x");
+ | items.reduce((acc, i) => acc + i.value, 0);
+ | const joined = mapped.join(", ");
+ | return realHelper(found);
+ |}
+ """.stripMargin
+ val result = parser.parse("process.ts", source)
+ val calls = result.relationships.filter(r => r.predicate == "CALLS" && r.srcName == "processItems")
+ // Should only have realHelper
+ calls.map(_.dstName) should contain("realHelper")
+ calls.map(_.dstName) should not contain "filter"
+ calls.map(_.dstName) should not contain "map"
+ calls.map(_.dstName) should not contain "forEach"
+ calls.map(_.dstName) should not contain "find"
+ calls.map(_.dstName) should not contain "reduce"
+ calls.map(_.dstName) should not contain "join"
+ }
+
it should "compute method spans bounded within their class" in {
val source = """export class Api {
| fetch(url: string) {