Skip to content

Graphs that teach > graphs that impress. Turn any code into an interactive knowledge graph you can explore, search, and ask questions about. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, and more.

fix(merge): recover imports for all whole-file node types

Lum11045bbc7589daa4
diff --git a/tests/skill/understand/test_merge_batch_graphs.py b/tests/skill/understand/test_merge_batch_graphs.py
index 38f3fd28..1dcd39e3 100644
--- a/tests/skill/understand/test_merge_batch_graphs.py
+++ b/tests/skill/understand/test_merge_batch_graphs.py
@@ -60,6 +60,38 @@ def _file_node(path: str, **extra: Any) -> dict[str, Any]:
return node
+def _whole_file_node(node_type: str, path: str) -> dict[str, Any]:
+ return _file_node(path, id=f"{node_type}:{path}", type=node_type)
+
+
+class WholeFileImportIndexTests(unittest.TestCase):
+ """Import recovery resolves every valid whole-file node type by path."""
+
+ def test_indexes_supported_whole_file_types(self) -> None:
+ nodes = [
+ _whole_file_node(node_type, f"project/{node_type}.txt")
+ for node_type in sorted(mbg.WHOLE_FILE_NODE_TYPES)
+ ]
+ index, warnings = mbg.build_whole_file_node_index(nodes)
+ self.assertEqual(warnings, [])
+ for node_type in mbg.WHOLE_FILE_NODE_TYPES:
+ path = f"project/{node_type}.txt"
+ self.assertEqual(index[path], f"{node_type}:{path}")
+
+ def test_prefers_file_and_rejects_child_or_malformed_nodes(self) -> None:
+ path = "config/app.json"
+ nodes = [
+ _whole_file_node("config", path),
+ _whole_file_node("file", path),
+ _file_node(path, id=f"table:{path}:users", type="table"),
+ _file_node("bad.json", id="config:not-bad.json", type="config"),
+ ]
+ index, warnings = mbg.build_whole_file_node_index(nodes)
+ self.assertEqual(index, {path: f"file:{path}"})
+ self.assertEqual(len(warnings), 1)
+ self.assertIn(f"selected file:{path}", warnings[0])
+
+
# ── is_test_path ──────────────────────────────────────────────────────────
class IsTestPathTests(unittest.TestCase):
diff --git a/understand-anything-plugin/skills/understand/merge-batch-graphs.py b/understand-anything-plugin/skills/understand/merge-batch-graphs.py
index 1c7746bf..338deaff 100644
--- a/understand-anything-plugin/skills/understand/merge-batch-graphs.py
+++ b/understand-anything-plugin/skills/understand/merge-batch-graphs.py
@@ -970,6 +970,56 @@ def merge_and_normalize(batches: list[dict[str, Any]]) -> tuple[dict[str, Any],
# ── Imports-edge recovery from importMap ──────────────────────────────────
+WHOLE_FILE_NODE_TYPES: frozenset[str] = frozenset(
+ {"file", "config", "document", "service", "pipeline", "schema", "resource"}
+)
+
+
+def build_whole_file_node_index(
+ nodes: list[dict[str, Any]],
+) -> tuple[dict[str, str], list[str]]:
+ """Map each filePath to its canonical whole-file node id.
+
+ Only exact ``<type>:<filePath>`` IDs qualify. This intentionally excludes
+ child constructs such as tables and endpoints, even when they carry the
+ same ``filePath``. If an analyzer emitted more than one whole-file node for
+ a path, ``file:`` wins; otherwise the first stable graph occurrence wins.
+ """
+ index: dict[str, str] = {}
+ selected_types: dict[str, str] = {}
+ warnings: list[str] = []
+
+ for node in nodes:
+ node_type = node.get("type")
+ file_path = node.get("filePath")
+ node_id = node.get("id")
+ if (
+ node_type not in WHOLE_FILE_NODE_TYPES
+ or not isinstance(file_path, str)
+ or not file_path
+ or node_id != f"{node_type}:{file_path}"
+ ):
+ continue
+
+ existing_id = index.get(file_path)
+ if existing_id is None:
+ index[file_path] = node_id
+ selected_types[file_path] = node_type
+ continue
+
+ existing_type = selected_types[file_path]
+ if node_type == "file" and existing_type != "file":
+ index[file_path] = node_id
+ selected_types[file_path] = node_type
+ selected = node_id
+ else:
+ selected = existing_id
+ warnings.append(
+ f" Warning: multiple whole-file nodes for {file_path}; selected {selected}"
+ )
+
+ return index, warnings
+
def recover_imports_from_scan(
assembled: dict[str, Any],
scan_result_path: Path,
@@ -995,11 +1045,9 @@ def recover_imports_from_scan(
if not isinstance(import_map, dict):
return 0, [f" importMap recovery skipped — no importMap field in {scan_result_path.name}"]
- # Build the set of file: node ids actually present in the assembled graph.
- file_node_ids: set[str] = set()
- for node in assembled["nodes"]:
- if node.get("type") == "file":
- file_node_ids.add(node.get("id", ""))
+ file_path_to_node_id, conflict_warnings = build_whole_file_node_index(
+ assembled["nodes"]
+ )
# Build the set of (source, target) imports edges already present.
existing: set[tuple[str, str]] = set()
@@ -1013,16 +1061,16 @@ def recover_imports_from_scan(
for src_path, targets in import_map.items():
if not isinstance(targets, list):
continue
- src_id = f"file:{src_path}"
- if src_id not in file_node_ids:
+ src_id = file_path_to_node_id.get(src_path)
+ if src_id is None:
if targets:
skipped_no_src_node += 1
continue
for tgt_path in targets:
if not isinstance(tgt_path, str) or not tgt_path:
continue
- tgt_id = f"file:{tgt_path}"
- if tgt_id not in file_node_ids:
+ tgt_id = file_path_to_node_id.get(tgt_path)
+ if tgt_id is None:
skipped_no_tgt_node += 1
continue
if src_id == tgt_id:
@@ -1040,7 +1088,7 @@ def recover_imports_from_scan(
existing.add((src_id, tgt_id))
recovered += 1
- lines: list[str] = []
+ lines: list[str] = list(conflict_warnings)
lines.append(
f" Recovered {recovered} `imports` edges from importMap "
f"({len(import_map)} entries scanned)"
@@ -1048,12 +1096,12 @@ def recover_imports_from_scan(
if skipped_no_src_node:
lines.append(
f" Skipped {skipped_no_src_node} importMap source files "
- f"with no `file:` node in graph"
+ f"with no whole-file node in graph"
)
if skipped_no_tgt_node:
lines.append(
f" Skipped {skipped_no_tgt_node} importMap target paths "
- f"with no `file:` node in graph"
+ f"with no whole-file node in graph"
)
return recovered, lines
diff --git a/understand-anything-plugin/src/__tests__/merge-recover-imports.test.mjs b/understand-anything-plugin/src/__tests__/merge-recover-imports.test.mjs
index a2817731..72508d36 100644
--- a/understand-anything-plugin/src/__tests__/merge-recover-imports.test.mjs
+++ b/understand-anything-plugin/src/__tests__/merge-recover-imports.test.mjs
@@ -53,6 +53,14 @@ function fileNode(path) {
};
}
+function wholeFileNode(type, path) {
+ return {
+ ...fileNode(path),
+ id: `${type}:${path}`,
+ type,
+ };
+}
+
function importsEdge(src, tgt) {
return {
source: `file:${src}`,
@@ -144,7 +152,7 @@ describe("merge-batch-graphs.py imports recovery", () => {
const { assembled, stderr } = runMerge();
expect(assembled.edges.filter((e) => e.type === "imports")).toHaveLength(0);
- expect(stderr).toContain("Skipped 1 importMap source files with no `file:` node");
+ expect(stderr).toContain("Skipped 1 importMap source files with no whole-file node");
});
it("skips importMap targets that don't have a file: node", () => {
@@ -164,7 +172,7 @@ describe("merge-batch-graphs.py imports recovery", () => {
const { assembled, stderr } = runMerge();
expect(assembled.edges.filter((e) => e.type === "imports")).toHaveLength(0);
- expect(stderr).toContain("Skipped 2 importMap target paths with no `file:` node");
+ expect(stderr).toContain("Skipped 2 importMap target paths with no whole-file node");
});
it("works when scan-result.json is missing (incremental update path)", () => {
@@ -201,6 +209,86 @@ describe("merge-batch-graphs.py imports recovery", () => {
const { assembled } = runMerge();
expect(assembled.edges.filter((e) => e.type === "imports")).toHaveLength(0);
});
+
+ it.each([
+ ['file', 'config'],
+ ['file', 'schema'],
+ ['config', 'file'],
+ ])('recovers %s to %s imports through whole-file nodes', (sourceType, targetType) => {
+ writeFileSync(
+ join(intermediateDir, 'batch-0.json'),
+ JSON.stringify({
+ nodes: [
+ wholeFileNode(sourceType, 'src/source.ts'),
+ wholeFileNode(targetType, 'config/target.json'),
+ ],
+ edges: [],
+ }),
+ );
+ writeFileSync(
+ join(intermediateDir, 'scan-result.json'),
+ JSON.stringify({
+ importMap: { 'src/source.ts': ['config/target.json'] },
+ }),
+ );
+
+ const { assembled } = runMerge();
+ expect(assembled.edges.filter((edge) => edge.type === 'imports')).toEqual([
+ expect.objectContaining({
+ source: `${sourceType}:src/source.ts`,
+ target: `${targetType}:config/target.json`,
+ }),
+ ]);
+ });
+
+ it('prefers file nodes over other whole-file nodes for the same path', () => {
+ writeFileSync(
+ join(intermediateDir, 'batch-0.json'),
+ JSON.stringify({
+ nodes: [
+ wholeFileNode('config', 'src/source.ts'),
+ wholeFileNode('file', 'src/source.ts'),
+ wholeFileNode('schema', 'src/target.ts'),
+ wholeFileNode('file', 'src/target.ts'),
+ ],
+ edges: [],
+ }),
+ );
+ writeFileSync(
+ join(intermediateDir, 'scan-result.json'),
+ JSON.stringify({ importMap: { 'src/source.ts': ['src/target.ts'] } }),
+ );
+
+ const { assembled, stderr } = runMerge();
+ expect(assembled.edges.filter((edge) => edge.type === 'imports')).toEqual([
+ expect.objectContaining({
+ source: 'file:src/source.ts',
+ target: 'file:src/target.ts',
+ }),
+ ]);
+ expect(stderr).toContain('multiple whole-file nodes for src/source.ts');
+ expect(stderr).toContain('selected file:src/source.ts');
+ });
+
+ it('does not use child constructs as whole-file import endpoints', () => {
+ const table = {
+ ...wholeFileNode('schema', 'db/schema.sql'),
+ id: 'table:db/schema.sql:users',
+ type: 'table',
+ };
+ writeFileSync(
+ join(intermediateDir, 'batch-0.json'),
+ JSON.stringify({ nodes: [fileNode('src/source.ts'), table], edges: [] }),
+ );
+ writeFileSync(
+ join(intermediateDir, 'scan-result.json'),
+ JSON.stringify({ importMap: { 'src/source.ts': ['db/schema.sql'] } }),
+ );
+
+ const { assembled, stderr } = runMerge();
+ expect(assembled.edges.filter((edge) => edge.type === 'imports')).toHaveLength(0);
+ expect(stderr).toContain('no whole-file node in graph');
+ });
});
describe("merge-batch-graphs.py data-dir resolution (.ua vs legacy)", () => {