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(graph): reconcile refreshed import edges

Lum110447f9e615c356
diff --git a/tests/skill/understand/test_prepare_incremental.test.mjs b/tests/skill/understand/test_prepare_incremental.test.mjs
index 023ed2e6..d1e14566 100644
--- a/tests/skill/understand/test_prepare_incremental.test.mjs
+++ b/tests/skill/understand/test_prepare_incremental.test.mjs
@@ -127,6 +127,18 @@ function buildBaseline(root, baseCommit) {
tags: ['fixture'],
complexity: 'simple',
}));
+ const nodeIdByPath = new Map(nodes.map(node => [node.filePath, node.id]));
+ const edges = Object.entries(importMap).flatMap(([sourcePath, targets]) =>
+ targets
+ .filter(targetPath => nodeIdByPath.has(sourcePath) && nodeIdByPath.has(targetPath))
+ .map(targetPath => ({
+ source: nodeIdByPath.get(sourcePath),
+ target: nodeIdByPath.get(targetPath),
+ type: 'imports',
+ direction: 'forward',
+ weight: 0.7,
+ })),
+ );
writeFileSync(
join(root, '.ua', 'knowledge-graph.json'),
JSON.stringify({
@@ -140,7 +152,7 @@ function buildBaseline(root, baseCommit) {
gitCommitHash: baseCommit,
},
nodes,
- edges: [],
+ edges,
layers: [{
id: 'layer:source',
name: 'Source',
@@ -308,6 +320,34 @@ describe('prepare-incremental.mjs', { timeout: 30_000 }, () => {
const { plan, scan } = prepare(root, baseCommit);
expect(plan.filesToReanalyze).toEqual(['src/foo.ts']);
expect(scan.importMap['src/index.ts']).toEqual(['src/foo.ts']);
+ const intermediate = join(root, '.ua', 'intermediate');
+ const retained = JSON.parse(readFileSync(join(intermediate, 'batch-existing.json'), 'utf-8'));
+ expect(retained.edges).not.toContainEqual(
+ expect.objectContaining({ source: 'file:src/index.ts', type: 'imports' }),
+ );
+ writeFileSync(
+ join(intermediate, 'batch-0.json'),
+ JSON.stringify({
+ nodes: [{
+ id: 'file:src/foo.ts',
+ type: 'file',
+ name: 'foo.ts',
+ filePath: 'src/foo.ts',
+ summary: 'Preferred TypeScript candidate',
+ tags: ['typescript'],
+ complexity: 'simple',
+ }],
+ edges: [],
+ }),
+ 'utf-8',
+ );
+ run(python, [mergeScript, root], root);
+ const assembled = JSON.parse(
+ readFileSync(join(intermediate, 'assembled-graph.json'), 'utf-8'),
+ );
+ expect(assembled.edges.filter(edge => edge.source === 'file:src/index.ts')).toEqual([
+ expect.objectContaining({ target: 'file:src/foo.ts', type: 'imports' }),
+ ]);
});
it('re-resolves unchanged importers to a fallback when a preferred candidate is deleted', () => {
@@ -364,6 +404,11 @@ describe('prepare-incremental.mjs', { timeout: 30_000 }, () => {
expect(plan.cosmeticFiles).toEqual(['src/index.js']);
expect(plan.filesToReanalyze).toEqual([]);
expect(scan.importMap['src/index.js']).toEqual(['src/b.js']);
+ run(process.execPath, [finalizeScript, root], root);
+ const graph = JSON.parse(readFileSync(join(root, '.ua', 'knowledge-graph.json'), 'utf-8'));
+ expect(graph.edges.filter(edge => edge.source === 'file:src/index.js')).toEqual([
+ expect.objectContaining({ target: 'file:src/b.js', type: 'imports' }),
+ ]);
});
it('treats LF-to-CRLF conversion as cosmetic and schedules no analyzer', () => {
diff --git a/understand-anything-plugin/skills/understand/finalize-incremental.mjs b/understand-anything-plugin/skills/understand/finalize-incremental.mjs
index 38f1724b..9902b789 100644
--- a/understand-anything-plugin/skills/understand/finalize-incremental.mjs
+++ b/understand-anything-plugin/skills/understand/finalize-incremental.mjs
@@ -267,6 +267,39 @@ function normalizeAssembled(assembled) {
return { nodes, edges };
}
+function refreshGraphImports(graph, importMap, refreshPaths) {
+ const pathIndex = buildPathIndex(graph.nodes);
+ const refreshedSourceIds = new Set(
+ refreshPaths.map(path => pathIndex.get(path)).filter(Boolean),
+ );
+ const edges = graph.edges.filter(
+ edge => !(edge.type === 'imports' && refreshedSourceIds.has(edge.source)),
+ );
+ const seen = new Set(edges.map(edge => `${edge.source}\0${edge.target}\0${edge.type}`));
+
+ for (const sourcePath of refreshPaths) {
+ const source = pathIndex.get(sourcePath);
+ if (!source) continue;
+ const targets = Array.isArray(importMap?.[sourcePath]) ? importMap[sourcePath] : [];
+ for (const targetPath of targets) {
+ const target = pathIndex.get(targetPath);
+ if (!target || source === target) continue;
+ const key = `${source}\0${target}\0imports`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ edges.push({
+ source,
+ target,
+ type: 'imports',
+ direction: 'forward',
+ weight: 0.7,
+ recoveredFromImportMap: true,
+ });
+ }
+ }
+ return { ...graph, edges };
+}
+
function normalizeFingerprintStore(raw, baseCommit) {
if (raw && raw.files && typeof raw.files === 'object' && !Array.isArray(raw.files)) {
return raw;
@@ -354,14 +387,22 @@ function main() {
}
const graphPath = join(uaDir, 'knowledge-graph.json');
+ const importMapRefreshPaths = Array.isArray(plan.importMapRefreshPaths)
+ ? plan.importMapRefreshPaths
+ : [];
if (plan.action === 'SKIP') {
const previousGraph = readJson(graphPath);
if (!previousGraph || !Array.isArray(previousGraph.nodes) || !Array.isArray(previousGraph.edges)) {
throw new Error('knowledge-graph.json is missing or invalid; baseline not advanced');
}
+ const refreshedGraph = refreshGraphImports(
+ previousGraph,
+ scan.importMap ?? {},
+ importMapRefreshPaths,
+ );
atomicWriteJson(graphPath, {
- ...previousGraph,
+ ...refreshedGraph,
project: projectMetadata(previousGraph.project, plan, scan),
});
}
@@ -372,7 +413,11 @@ function main() {
if (!assembledRaw || !Array.isArray(assembledRaw.nodes) || !Array.isArray(assembledRaw.edges)) {
throw new Error('assembled-graph.json is missing or invalid; baseline not advanced');
}
- const assembled = normalizeAssembled(assembledRaw);
+ const assembled = refreshGraphImports(
+ normalizeAssembled(assembledRaw),
+ scan.importMap ?? {},
+ importMapRefreshPaths,
+ );
const nodeIds = new Set(assembled.nodes.map(node => node.id));
const pathIndex = buildPathIndex(assembled.nodes);
const missingAnalyzedPaths = plan.filesToReanalyze.filter(path => !pathIndex.has(path));
@@ -438,4 +483,4 @@ if (isCliEntry()) {
}
}
-export { assignLayers, commonParentDepth, normalizeTour };
+export { assignLayers, commonParentDepth, normalizeTour, refreshGraphImports };
diff --git a/understand-anything-plugin/skills/understand/prepare-incremental.mjs b/understand-anything-plugin/skills/understand/prepare-incremental.mjs
index a31f7be0..21c21722 100644
--- a/understand-anything-plugin/skills/understand/prepare-incremental.mjs
+++ b/understand-anything-plugin/skills/understand/prepare-incremental.mjs
@@ -60,6 +60,15 @@ const {
const SCAN_SCRIPT = join(__dirname, 'scan-project.mjs');
const IMPORT_SCRIPT = join(__dirname, 'extract-import-map.mjs');
const GENERATED_ROOTS = new Set(['.ua', '.understand-anything']);
+const WHOLE_FILE_TYPES = new Set([
+ 'file',
+ 'config',
+ 'document',
+ 'service',
+ 'pipeline',
+ 'schema',
+ 'resource',
+]);
function comparePaths(a, b) {
if (a === b) return 0;
@@ -387,19 +396,31 @@ function refreshImportMap({ projectRoot, intermediateDir, oldScan, currentScan,
return importMap;
}
-function pruneExistingGraph(graph, pathsToReplace) {
+function pruneExistingGraph(graph, pathsToReplace, importPathsToRefresh = new Set()) {
const removedNodeIds = new Set();
+ const refreshedImportSourceIds = new Set();
const nodes = [];
for (const node of graph?.nodes ?? []) {
const path = normalizeRelativePath(node?.filePath);
if (path && pathsToReplace.has(path)) removedNodeIds.add(node.id);
- else nodes.push(node);
+ else {
+ nodes.push(node);
+ if (
+ path
+ && importPathsToRefresh.has(path)
+ && WHOLE_FILE_TYPES.has(node.type)
+ && node.id === `${node.type}:${path}`
+ ) {
+ refreshedImportSourceIds.add(node.id);
+ }
+ }
}
const retainedIds = new Set(nodes.map(node => node.id));
const edges = (graph?.edges ?? []).filter(
edge =>
!removedNodeIds.has(edge.source)
&& !removedNodeIds.has(edge.target)
+ && !(edge.type === 'imports' && refreshedImportSourceIds.has(edge.source))
&& retainedIds.has(edge.source)
&& retainedIds.has(edge.target),
);
@@ -591,6 +612,7 @@ async function main() {
cosmeticFiles: analysis.cosmeticOnlyFiles,
ignoredFiles,
generatedArtifactFiles,
+ importMapRefreshPaths: importAnalysisPaths,
rerunArchitecture: decision.rerunArchitecture,
rerunTour: decision.rerunTour,
reason: decision.reason,
@@ -614,7 +636,7 @@ async function main() {
const pathsToReplace = new Set([...filesToReanalyze, ...deletedFiles]);
atomicWriteJson(
join(intermediateDir, 'batch-existing.json'),
- pruneExistingGraph(graph, pathsToReplace),
+ pruneExistingGraph(graph, pathsToReplace, new Set(importAnalysisPaths)),
);
}
atomicWriteJson(join(intermediateDir, 'incremental-plan.json'), plan);