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.
TypeScript antigravity-skillsbusiness-knowledgeclaude-codeclaude-skillscodebase-analysiscodexcodex-skillsdeveloper-tools-ai-agentgemini-cli-skillskarpathy-llm-wikiknowledge-baseknowledge-graphmemoryopencode-skillspi-agentunderstandcodevibe-coding
fix(incremental): reconcile changed endpoint IDs on every merge
Lum110450c4e8c05fab
diff --git a/tests/skill/understand/test_merge_batch_graphs.py b/tests/skill/understand/test_merge_batch_graphs.pyindex f1eca691..a68563a0 100644--- a/tests/skill/understand/test_merge_batch_graphs.py+++ b/tests/skill/understand/test_merge_batch_graphs.py@@ -1446,7 +1446,7 @@ class TestUaDirResolution(unittest.TestCase):class TestIncrementalEdgeCandidates(unittest.TestCase):- def test_preserves_only_current_normalized_dangling_targets(self) -> None:+ def test_preserves_only_current_normalized_dangling_edges(self) -> None:source = _file_node("src/b.ts", id="demo:file:src/b.ts")old_edge = {"source": source["id"], "target": "function:src/a.ts:old", "type": "calls"}fresh_edges = [@@ -1464,6 +1464,8 @@ class TestIncrementalEdgeCandidates(unittest.TestCase):self.assertEqual(candidates, [{"source": "file:src/b.ts", "target": "function:src/a.ts:lost", "type": "calls","direction": "bidirectional", "weight": 0.9,+ }, {+ "source": "missing", "target": "function:src/a.ts:lost", "type": "calls", "direction": "forward",}])diff --git a/tests/skill/understand/test_prepare_incremental.test.mjs b/tests/skill/understand/test_prepare_incremental.test.mjsindex 715dcf0b..26a63f2a 100644--- a/tests/skill/understand/test_prepare_incremental.test.mjs+++ b/tests/skill/understand/test_prepare_incremental.test.mjs@@ -188,7 +188,7 @@ function prepare(root, baseCommit, extraArgs = []) {};}-function symbolFixture(count = 20) {+function symbolFixture(count = 20, extraFiles = {}) {const source = methods => `export class Service {\n${methods.map(name => ` ${name}() { return 1; }`).join('\n')}\n}\n`;const names = Array.from({ length: count }, (_, i) => `method${i}`);const fixture = setupRepository({@@ -196,6 +196,7 @@ function symbolFixture(count = 20) {'src/b.ts': 'export const b = 1;\n','src/c.ts': 'export const c = 1;\n','src/d.ts': 'export const d = 1;\n',+ ...extraFiles,});const { root } = fixture;const dataDir = join(root, '.ua');@@ -231,6 +232,40 @@ afterEach(async () => {});describe('incremental symbol publication gate', { timeout: 30_000 }, () => {+ it('reconciles accepted replacement IDs on the first pass without requiring a retry', () => {+ const f = symbolFixture(2, { 'src/b.ts': 'export function b() {}\n' });+ const oldSource = { ...f.methodNodes[0], id: 'func:src/b.ts:b', filePath: 'src/b.ts', name: 'b' };+ const previous = JSON.parse(f.persisted()[0]);+ previous.nodes.push(oldSource);+ writeFileSync(join(f.dataDir, 'knowledge-graph.json'), JSON.stringify(previous));+ writeProjectFile(f.root, 'src/a.ts', f.source([...f.names, 'added']));+ writeProjectFile(f.root, 'src/b.ts', 'export function b(value: number) { return value; }\n');+ commit(f.root, 'add method');+ prepare(f.root, f.baseCommit);+ const replacements = f.methodNodes.map(node => ({ ...node, id: node.id.replace('Service.', 'Service::') }));+ const newSource = { ...oldSource, id: 'function:src/b.ts:b' };+ const source = newSource.id;+ f.write('batch-1.json', {+ nodes: [f.fileNode, f.classNode, ...replacements, previous.nodes.find(node => node.id === 'file:src/b.ts'), newSource],+ edges: [{ source: oldSource.id, target: f.methodNodes[1].id, type: 'calls', direction: 'forward', weight: 0.7 }],+ });+ run(python, [mergeScript, f.root], f.root);+ const report = f.read('incremental-symbol-report.json');+ expect(report.ok).toBe(true);+ expect(report.unresolvedFiles).toEqual([]);+ expect(report.idReplacements).toContainEqual({ oldId: f.methodNodes[1].id, newId: replacements[1].id });+ expect(report.idReplacements).toContainEqual({ oldId: oldSource.id, newId: newSource.id });+ expect(() => f.read('incremental-symbol-retry.json')).toThrow();+ const assembled = f.read('assembled-graph.json');+ expect(assembled.edges.some(edge => edge.source === source && edge.target === replacements[1].id)).toBe(true);+ // The final save gate independently reconciles the same current evidence.+ assembled.edges = assembled.edges.filter(edge => edge.type !== 'calls');+ f.write('assembled-graph.json', assembled);+ run(process.execPath, [finalizeScript, f.root], f.root);+ expect(JSON.parse(f.persisted()[0]).edges.some(edge => edge.source === source+ && edge.target === replacements[1].id && edge.weight === 0.7)).toBe(true);+ });+it('rejects changed analyzer inputs even when all old symbol IDs survive', () => {const f = symbolFixture(2);writeProjectFile(f.root, 'src/a.ts', f.source([...f.names, 'added']));@@ -326,7 +361,7 @@ describe('incremental symbol publication gate', { timeout: 30_000 }, () => {expect(graph.edges.find(edge => edge.source === otherFunction.id && edge.target === repairedMethods[0].id)?.weight).toBe(0.8);expect(graph.edges.find(edge => edge.source === otherFunction.id && edge.target === repairedMethods[1].id)?.weight).toBe(0.9);if (outcome === 'renamed-ids') {- expect(f.read('incremental-symbol-report.json').retryIdReplacements).toContainEqual({+ expect(f.read('incremental-symbol-report.json').idReplacements).toContainEqual({oldId: initialMethod.id, newId: repairedMethods[0].id,});// Finalize must reconcile independently if its candidate loses thediff --git a/understand-anything-plugin/hooks/auto-update-prompt.md b/understand-anything-plugin/hooks/auto-update-prompt.mdindex 6a19ec31..475b0552 100644--- a/understand-anything-plugin/hooks/auto-update-prompt.md+++ b/understand-anything-plugin/hooks/auto-update-prompt.md@@ -65,7 +65,7 @@ It combines `batch-existing.json` with fresh batches and recovers imports from tMerge runs `validate-incremental-symbols.mjs`, comparing the preserved old symbols with the candidate and base/current source. Read `incremental-symbol-report.json` for per-file counts, missing IDs/names, and still-present/deleted/unknown classifications. A same-size node set can still have missing symbols. Confirmed deletions are allowed; still-present or unknown omissions block publication.-Merge also preserves normalized dangling inbound candidates from fresh batches in `incremental-edge-candidates.json` before discarding their missing targets. Retry can reconcile these after the omitted symbols return, including changed ID spellings. This evidence excludes `batch-existing.json` and is cleared by fresh preparation.+Merge also preserves normalized dangling edge candidates from fresh batches in `incremental-edge-candidates.json` before discarding unresolved endpoints. Every successful validation reconciles both endpoint IDs, including first-pass updates without a retry and repairs where omitted symbols return. This evidence excludes `batch-existing.json` and is cleared by fresh preparation.If the report has `unresolvedFiles`, prepare one targeted symbol retry:diff --git a/understand-anything-plugin/skills/understand/SKILL.md b/understand-anything-plugin/skills/understand/SKILL.mdindex a76d60dc..205b97ae 100644--- a/understand-anything-plugin/skills/understand/SKILL.md+++ b/understand-anything-plugin/skills/understand/SKILL.md@@ -412,7 +412,7 @@ The merge combines `batch-existing.json` with any fresh batch output. Its import**Symbol-loss gate and one targeted retry:** Merge invokes `validate-incremental-symbols.mjs`. Read `incremental-symbol-report.json`: it reports per-file before/after counts and missing node IDs/names even when counts stay equal. Missing functions, classes, and methods (including `classes[].methods`) are classified against base/current source with the same strict parser. Only confirmed source deletions are allowed; still-present and unknown symbols block publication.-Before dropping dangling targets, merge records normalized inbound candidates from fresh batches in `incremental-edge-candidates.json`, bound to the base/head commits. Retry uses these alongside surviving current edges, so an edge to the initially omitted symbol can be restored after repair, including accepted ID spelling changes. Edges from `batch-existing.json` are not collected as fresh evidence.+Before dropping dangling endpoints, merge records normalized edge candidates from fresh batches in `incremental-edge-candidates.json`, bound to the base/head commits. Every successful validation reconciles their source and target IDs against accepted symbol replacements, including first-pass updates that need no retry. Retry also preserves these alongside surviving current edges, so an edge to the initially omitted symbol can be restored after repair. Edges from `batch-existing.json` are not collected as fresh evidence.When the report has `unresolvedFiles`, prepare exactly one repair:diff --git a/understand-anything-plugin/skills/understand/merge-batch-graphs.py b/understand-anything-plugin/skills/understand/merge-batch-graphs.pyindex 5a8614b1..5165363a 100644--- a/understand-anything-plugin/skills/understand/merge-batch-graphs.py+++ b/understand-anything-plugin/skills/understand/merge-batch-graphs.py@@ -890,14 +890,12 @@ def merge_and_normalize(key = (src, tgt, etype, direction)if src not in node_ids or tgt not in node_ids:- # Preserve normalized CURRENT analyzer evidence before the missing- # target is discarded. Never collect edges from batch-existing.+ # Preserve normalized CURRENT analyzer evidence before unresolved+ # endpoints are discarded. Never collect edges from batch-existing.if (dangling_candidates is not Noneand current_edge_ids is not Noneand id(edge) in current_edge_ids- and src in node_ids- and tgt not in node_ids):previous = dangling_by_key.get(key)if previous is None or _num(edge.get("weight", 0)) > _num(previous.get("weight", 0)):diff --git a/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjs b/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjsindex 01dcce15..6468e8a9 100644--- a/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjs+++ b/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjs@@ -79,7 +79,10 @@ async function main() {.flatMap(file => file.nodes.map(node => node.id)));const targetsAffectedFile = id => removedIds.has(id) || previousIds.has(id)|| (typeof id === 'string' && [...paths].some(path => id.includes(`:${path}:`)));- const inboundEdgeCandidates = [...assembled.edges, ...candidates.edges].filter(edge =>+ const sourceRemap = new Map(report.files.flatMap(file => file.replacements)+ .map(({ oldId, newId }) => [oldId, newId]));+ const inboundEdgeCandidates = [...assembled.edges, ...candidates.edges]+ .map(edge => ({ ...edge, source: sourceRemap.get(edge.source) ?? edge.source })).filter(edge =>retainedIds.has(edge.source) && targetsAffectedFile(edge.target));const retained = {nodes: assembled.nodes.filter(node => !removedIds.has(node.id)),diff --git a/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs b/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjsindex ffc44b74..cb3020b4 100644--- a/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs+++ b/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs@@ -251,16 +251,24 @@ export async function validateIncrementalSymbols(projectRoot, { graph, intermediif (report.ok) {const retryPath = join(intermediateDir, 'incremental-symbol-retry.json');const retry = existsSync(retryPath) ? readJson(retryPath) : null;- if (retry?.baseCommit === plan.baseCommit && retry.headCommit === plan.headCommit- && Array.isArray(retry.inboundEdgeCandidates) && Array.isArray(retry.replacedFiles)) {+ const candidatePath = join(intermediateDir, 'incremental-edge-candidates.json');+ const currentCandidates = existsSync(candidatePath) ? readJson(candidatePath) : null;+ if (currentCandidates && (currentCandidates.baseCommit !== plan.baseCommit+ || currentCandidates.headCommit !== plan.headCommit || !Array.isArray(currentCandidates.edges))) {+ throw new Error('Current edge candidates do not match the incremental plan');+ }+ const hasRetry = retry?.baseCommit === plan.baseCommit && retry.headCommit === plan.headCommit+ && Array.isArray(retry.inboundEdgeCandidates) && Array.isArray(retry.replacedFiles);+ const candidates = [...(currentCandidates?.edges ?? []), ...(hasRetry ? retry.inboundEdgeCandidates : [])];+ if (candidates.length || hasRetry) {const ids = new Set(graph.nodes.map(node => node.id));- // A target omitted in the initial merge has no current node descriptor;+ // An endpoint omitted in the initial merge has no current descriptor;// use its independently verified baseline-to-current identity mapping.const remap = new Map(report.files.flatMap(file => file.replacements).map(({ oldId, newId }) => [oldId, newId]));// These descriptors belong to the initial CURRENT analysis, not the// old published graph. Both sides therefore map against HEAD source.- for (const previous of retry.replacedFiles) {+ for (const previous of hasRetry ? retry.replacedFiles : []) {if (!previous.nodes.some(node => !ids.has(node.id) && symbolKind(node))) continue;const evidence = (await parseRevisions(previous.filePath)).head;const result = compareFileSymbols(previous, fileGraph(previous.filePath), evidence, evidence);@@ -268,28 +276,32 @@ export async function validateIncrementalSymbols(projectRoot, { graph, intermedi}const edgeKey = edge => JSON.stringify([edge.source, edge.target, edge.type, edge.direction]);const existing = new Map(graph.edges.map((edge, index) => [edgeKey(edge), index]));- report.reconciledRetryEdges = 0;- report.droppedRetryEdges = [];- report.retryIdReplacements = [...remap].map(([oldId, newId]) => ({ oldId, newId }));- for (const candidate of retry.inboundEdgeCandidates) {- const edge = { ...candidate, target: remap.get(candidate.target) ?? candidate.target };+ report.reconciledCurrentEdges = 0;+ report.droppedCurrentEdges = [];+ report.idReplacements = [...remap].map(([oldId, newId]) => ({ oldId, newId }));+ for (const candidate of candidates) {+ const edge = {+ ...candidate,+ source: remap.get(candidate.source) ?? candidate.source,+ target: remap.get(candidate.target) ?? candidate.target,+ };if (!ids.has(edge.source) || !ids.has(edge.target)) {- report.droppedRetryEdges.push({ source: candidate.source, target: candidate.target, type: candidate.type });+ report.droppedCurrentEdges.push({ source: candidate.source, target: candidate.target, type: candidate.type });} else {const index = existing.get(edgeKey(edge));if (index === undefined) {existing.set(edgeKey(edge), graph.edges.length);graph.edges.push(edge);- report.reconciledRetryEdges++;+ report.reconciledCurrentEdges++;} else if (Number(edge.weight) > Number(graph.edges[index].weight)) {graph.edges[index] = edge;- report.reconciledRetryEdges++;+ report.reconciledCurrentEdges++;}}}// Merge's earlier dangling-edge cleanup cannot see semantic ID aliases.// Save the reconciled candidate before architecture/tour consumers run.- if (graphFromDisk && report.reconciledRetryEdges > 0) {+ if (graphFromDisk && report.reconciledCurrentEdges > 0) {atomicWriteJson(join(intermediateDir, 'assembled-graph.json'), graph);}report.graphHash = createHash('sha256').update(JSON.stringify(graph)).digest('hex');@@ -310,9 +322,9 @@ export function formatSymbolReport(report) {for (const node of file.missing) lines.push(` ${node.status}: ${JSON.stringify(node.id)} (${JSON.stringify(node.name)}) — ${node.reason}`);}lines.push(...report.errors.map(error => ` Error: ${error}`));- if (report.reconciledRetryEdges) lines.push(` Reconciled ${report.reconciledRetryEdges} current inbound retry edge(s)`);- for (const edge of report.droppedRetryEdges ?? []) {- lines.push(` Dropped retry edge with unresolved endpoint: ${JSON.stringify(edge)}`);+ if (report.reconciledCurrentEdges) lines.push(` Reconciled ${report.reconciledCurrentEdges} current edge(s)`);+ for (const edge of report.droppedCurrentEdges ?? []) {+ lines.push(` Dropped current edge with unresolved endpoint: ${JSON.stringify(edge)}`);}lines.push(report.ok ? 'Symbol validation passed' : 'Symbol validation blocked publication; baseline not advanced');return lines.join('\n');