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 normalized source and retry symbol identities
Lum1104d6590c4b30c1
diff --git a/tests/skill/understand/test_incremental_symbols.test.mjs b/tests/skill/understand/test_incremental_symbols.test.mjsindex 9242d6f3..5560f3e3 100644--- a/tests/skill/understand/test_incremental_symbols.test.mjs+++ b/tests/skill/understand/test_incremental_symbols.test.mjs@@ -30,6 +30,7 @@ describe('incremental symbol matching', () => {[node('run', { id: 'func:src/a.ts:A::run', lineRange: [6, 6] })],'class A {\n run() {}\n}', '\n\n\n\nclass A {\n run() {}\n}');expect(result.missing).toEqual([]);+ expect(result.replacements).toEqual([{ oldId: 'function:src/a.ts:A.run', newId: 'func:src/a.ts:A::run' }]);});it('does not substitute a different class with the same method name', () => {diff --git a/tests/skill/understand/test_prepare_incremental.test.mjs b/tests/skill/understand/test_prepare_incremental.test.mjsindex 1c34be77..123854cd 100644--- a/tests/skill/understand/test_prepare_incremental.test.mjs+++ b/tests/skill/understand/test_prepare_incremental.test.mjs@@ -231,7 +231,38 @@ afterEach(async () => {});describe('incremental symbol publication gate', { timeout: 30_000 }, () => {- it.each(['success', 'failure'])('retries only affected files once, preserves other results, and handles retry %s', outcome => {+ 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']));+ commit(f.root, 'add method');+ const before = f.persisted();+ prepare(f.root, f.baseCommit);+ writeProjectFile(f.root, 'src/a.ts', f.source([...f.names, 'uncommitted']));+ f.write('batch-0.json', { nodes: [f.fileNode, f.classNode, ...f.methodNodes], edges: [] });+ expect(spawnSync(python, [mergeScript, f.root]).status).toBe(1);+ expect(spawnSync(process.execPath, [finalizeScript, f.root]).status).toBe(1);+ expect(f.persisted()).toEqual(before);+ });++ it.each([false, true])('uses Git cleanliness for CRLF source when dirty=%s', dirty => {+ const f = symbolFixture(2);+ writeProjectFile(f.root, '.gitattributes', 'src/a.ts text eol=crlf\n');+ writeProjectFile(f.root, 'src/a.ts', f.source([f.names[0]]).replaceAll('\n', '\r\n'));+ commit(f.root, 'delete method with CRLF checkout');+ const before = f.persisted();+ prepare(f.root, f.baseCommit);+ if (dirty) writeProjectFile(f.root, 'src/a.ts', f.source([...f.names, 'dirty']).replaceAll('\n', '\r\n'));+ const attributes = { ...f.fileNode, id: 'file:.gitattributes', filePath: '.gitattributes', name: '.gitattributes' };+ f.write('batch-0.json', { nodes: [attributes, f.fileNode, f.classNode, f.methodNodes[0]], edges: [] });+ const merged = spawnSync(python, [mergeScript, f.root], { encoding: 'utf8' });+ const finalized = spawnSync(process.execPath, [finalizeScript, f.root], { encoding: 'utf8' });+ expect(merged.status, merged.stderr).toBe(dirty ? 1 : 0);+ expect(finalized.status, finalized.stderr).toBe(dirty ? 1 : 0);+ if (dirty) expect(f.persisted()).toEqual(before);+ else expect(f.read('incremental-symbol-report.json').files.find(file => file.filePath === 'src/a.ts').missing[0].status).toBe('deleted');+ });++ it.each(['success', 'failure', 'renamed-ids'])('retries only affected files once, preserves other results, and handles retry %s', outcome => {const f = symbolFixture(2);writeProjectFile(f.root, 'src/a.ts', f.source([...f.names, 'added']));writeProjectFile(f.root, 'src/b.ts', 'export function b() { return 2; }\n');@@ -243,12 +274,18 @@ describe('incremental symbol publication gate', { timeout: 30_000 }, () => {...f.methodNodes[0], id: 'function:src/b.ts:b', filePath: 'src/b.ts', name: 'b', summary: 'Fresh analysis to retain',};const obsolete = { ...f.methodNodes[0], id: 'function:src/a.ts:obsolete', name: 'obsolete' };- f.write('batch-7-part-1.json', { nodes: [f.fileNode, f.classNode, f.methodNodes[0], otherFile], edges: [] });+ const initialMethod = outcome === 'renamed-ids'+ ? { ...f.methodNodes[0], id: f.methodNodes[0].id.replace('Service.', 'Service#') }+ : f.methodNodes[0];+ const repairedMethods = outcome === 'renamed-ids'+ ? f.methodNodes.map(node => ({ ...node, id: node.id.replace('Service.', 'Service::') }))+ : outcome === 'success' ? f.methodNodes : [f.methodNodes[0]];+ f.write('batch-7-part-1.json', { nodes: [f.fileNode, f.classNode, initialMethod, otherFile], edges: [] });f.write('batch-7-part-2.json', { nodes: [otherFunction, obsolete], edges: [{ source: otherFile.id, target: otherFunction.id, type: 'contains', direction: 'forward', weight: 1 },{ source: otherFunction.id, target: obsolete.id, type: 'calls', direction: 'forward', weight: 1 },- { source: otherFunction.id, target: f.methodNodes[0].id, type: 'calls', direction: 'forward', weight: 0.8 },- { source: f.methodNodes[0].id, target: otherFunction.id, type: 'calls', direction: 'forward', weight: 0.5 },+ { source: otherFunction.id, target: initialMethod.id, type: 'calls', direction: 'forward', weight: 0.8 },+ { source: initialMethod.id, target: otherFunction.id, type: 'calls', direction: 'forward', weight: 0.5 },] });expect(spawnSync(python, [mergeScript, f.root]).status).toBe(1);run(process.execPath, [retryScript, f.root], f.root);@@ -264,15 +301,15 @@ describe('incremental symbol publication gate', { timeout: 30_000 }, () => {expect(retained.nodes.find(node => node.id === otherFunction.id)?.summary).toBe(otherFunction.summary);expect(retained.nodes.some(node => node.filePath === 'src/a.ts')).toBe(false);expect(retained.edges.some(edge => edge.target === obsolete.id)).toBe(true);- expect(retained.edges.some(edge => edge.source === otherFunction.id && edge.target === f.methodNodes[0].id)).toBe(true);- expect(retained.edges.some(edge => edge.source === f.methodNodes[0].id)).toBe(false);+ expect(retained.edges.some(edge => edge.source === otherFunction.id && edge.target === initialMethod.id)).toBe(true);+ expect(retained.edges.some(edge => edge.source === initialMethod.id)).toBe(false);expect(retained.edges.some(edge => edge.target === otherFunction.id)).toBe(true);for (const batch of retry.batches) f.write(`batch-${batch.batchIndex}.json`, {- nodes: [f.fileNode, f.classNode, ...(outcome === 'success' ? f.methodNodes : [f.methodNodes[0]])], edges: [],+ nodes: [f.fileNode, f.classNode, ...repairedMethods], edges: [],});const merged = spawnSync(python, [mergeScript, f.root], { encoding: 'utf8' });const finalized = spawnSync(process.execPath, [finalizeScript, f.root], { encoding: 'utf8' });- if (outcome === 'success') {+ if (outcome !== 'failure') {expect(merged.status, merged.stderr).toBe(0);expect(finalized.status, finalized.stderr).toBe(0);const graph = JSON.parse(f.persisted()[0]);@@ -280,7 +317,20 @@ describe('incremental symbol publication gate', { timeout: 30_000 }, () => {expect(graph.nodes.find(node => node.id === otherFunction.id)?.summary).toBe(otherFunction.summary);expect(graph.nodes.some(node => node.id === obsolete.id)).toBe(false);expect(graph.edges.some(edge => edge.target === obsolete.id)).toBe(false);- expect(graph.edges.find(edge => edge.source === otherFunction.id && edge.target === f.methodNodes[0].id)?.weight).toBe(0.8);+ expect(graph.edges.find(edge => edge.source === otherFunction.id && edge.target === repairedMethods[0].id)?.weight).toBe(0.8);+ if (outcome === 'renamed-ids') {+ expect(f.read('incremental-symbol-report.json').retryIdReplacements).toContainEqual({+ oldId: initialMethod.id, newId: repairedMethods[0].id,+ });+ // Finalize must reconcile independently if its candidate loses the+ // recovered edge after merge; the report is not a save authorization.+ const candidate = f.read('assembled-graph.json');+ candidate.edges = candidate.edges.filter(edge => edge.target !== repairedMethods[0].id);+ f.write('assembled-graph.json', candidate);+ run(process.execPath, [finalizeScript, f.root], f.root);+ expect(JSON.parse(f.persisted()[0]).edges.some(edge => edge.source === otherFunction.id+ && edge.target === repairedMethods[0].id)).toBe(true);+ }} else {expect(merged.status).toBe(1);expect(finalized.status).toBe(1);@@ -290,6 +340,7 @@ describe('incremental symbol publication gate', { timeout: 30_000 }, () => {expect(secondRetry.stderr).toContain('already used');prepare(f.root, f.baseCommit);expect(f.read('incremental-symbol-retry.json').attempt).toBe(1);+ expect(f.read('incremental-symbol-retry.json')).not.toHaveProperty('inboundEdgeCandidates');expect(spawnSync(process.execPath, [retryScript, f.root]).status).toBe(1);expect(f.persisted()).toEqual(before);}diff --git a/understand-anything-plugin/skills/understand/prepare-incremental.mjs b/understand-anything-plugin/skills/understand/prepare-incremental.mjsindex 389b8461..0595057c 100644--- a/understand-anything-plugin/skills/understand/prepare-incremental.mjs+++ b/understand-anything-plugin/skills/understand/prepare-incremental.mjs@@ -688,6 +688,12 @@ async function main() {const retry = readJson(retryPath);if (retry && (retry.baseCommit !== baseCommit || retry.headCommit !== headCommit)) {unlinkSync(retryPath);+ } else if (retry) {+ // Retain the attempt limit, but never import current-analysis candidates+ // from a discarded batch generation into a fresh prepare run.+ delete retry.inboundEdgeCandidates;+ delete retry.replacedFiles;+ atomicWriteJson(retryPath, retry);}atomicWriteJson(join(intermediateDir, 'fingerprint-patch.json'), {diff --git a/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjs b/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjsindex ac7e43fd..4c3a0c5a 100644--- a/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjs+++ b/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjs@@ -86,6 +86,15 @@ async function main() {atomicWriteJson(retryPath, {version: 1, baseCommit: plan.baseCommit, headCommit: plan.headCommit, attempt: 1,filesToReanalyze: [...paths], batches,+ inboundEdgeCandidates: assembled.edges.filter(edge => !removedIds.has(edge.source) && removedIds.has(edge.target)),+ replacedFiles: [...paths].map(filePath => {+ const nodes = assembled.nodes.filter(node => normalizePath(node.filePath) === filePath);+ const ids = new Set(nodes.map(node => node.id));+ return {+ filePath, nodes,+ edges: assembled.edges.filter(edge => edge.type === 'contains' && ids.has(edge.source) && ids.has(edge.target)),+ };+ }),});// Replace all numeric shards with one normalized retained contribution.// Merely overwriting the main batch leaves stale -part-* files capable ofdiff --git a/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs b/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjsindex 33c58059..9bdeb549 100644--- a/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs+++ b/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs@@ -116,6 +116,7 @@ export function compareFileSymbols(previous, current, baseEvidence, headEvidenceconst oldMappings = oldSymbols.map(node => resolveSymbol(node, previous, baseSource));const newMappings = newSymbols.map(node => resolveSymbol(node, current, headSource));const missing = [];+ const replacements = [];for (let index = 0; index < oldSymbols.length; index++) {const node = oldSymbols[index];if (newSymbols.some(candidate => candidate.id === node.id@@ -129,7 +130,11 @@ export function compareFileSymbols(previous, current, baseEvidence, headEvidence} else {const matches = headSource.filter(symbol => symbolKey(symbol) === symbolKey(old));const graphMatches = newMappings.filter(symbol => symbol && symbolKey(symbol) === symbolKey(old));- if (matches.length === 1 && graphMatches.length === 1) continue;+ if (matches.length === 1 && graphMatches.length === 1) {+ const matchedIndex = newMappings.findIndex(symbol => symbol && symbolKey(symbol) === symbolKey(old));+ replacements.push({ oldId: node.id, newId: newSymbols[matchedIndex].id });+ continue;+ }if (matches.length === 1) {entry.status = 'still-present';entry.reason = 'Symbol still exists in current source but is missing or ambiguous in the new graph';@@ -154,6 +159,7 @@ export function compareFileSymbols(previous, current, baseEvidence, headEvidencebeforeSymbolCount: oldSymbols.length,afterSymbolCount: newSymbols.length,missing,+ replacements,};}@@ -177,6 +183,11 @@ export function loadSymbolContext(projectRoot, intermediateDir) {if (git(projectRoot, ['rev-parse', 'HEAD']).trim() !== plan.headCommit) {throw new Error('HEAD changed since prepare; baseline not advanced');}+ // Check every analyzer input, even if all IDs survive and parsing is skipped.+ // Git compares normalized contents, including repository clean/EOL rules.+ if (paths.length) git(projectRoot, [+ 'diff', '--quiet', '--no-ext-diff', plan.headCommit, '--', ...paths.map(path => `:(literal)${path}`),+ ]);return { plan, baseline };}@@ -185,6 +196,7 @@ export async function validateIncrementalSymbols(projectRoot, { graph, intermediintermediateDir ??= join(core.resolveUaDir(projectRoot), 'intermediate');const reportPath = join(intermediateDir, 'incremental-symbol-report.json');const report = { version: 1, ok: false, files: [], unresolvedFiles: [], errors: [] };+ const graphFromDisk = graph === undefined;try {const { plan, baseline } = loadSymbolContext(projectRoot, intermediateDir);report.baseCommit = plan.baseCommit;@@ -193,28 +205,38 @@ export async function validateIncrementalSymbols(projectRoot, { graph, intermediif (!Array.isArray(graph.nodes) || !Array.isArray(graph.edges)) throw new Error('Invalid assembled graph');report.graphHash = createHash('sha256').update(JSON.stringify(graph)).digest('hex');let parser;- for (const previous of baseline.files) {- const nodes = graph.nodes.filter(node => normalizePath(node.filePath) === previous.filePath);+ const evidenceByPath = new Map();+ const parseRevisions = async path => {+ if (evidenceByPath.has(path)) return evidenceByPath.get(path);+ if (!parser) {+ parser = new core.TreeSitterPlugin(core.builtinLanguageConfigs.filter(config => config.treeSitter));+ await parser.init();+ }+ // :./ keeps git-show relative to projectRoot, including monorepo subdirectories.+ const oldContent = git(projectRoot, ['show', `${plan.baseCommit}:./${path}`]);+ const headContent = git(projectRoot, ['show', `${plan.headCommit}:./${path}`]);+ const evidence = {+ base: parser.analyzeFileStrict(path, oldContent),+ head: parser.analyzeFileStrict(path, headContent),+ };+ evidenceByPath.set(path, evidence);+ return evidence;+ };+ const fileGraph = filePath => {+ const nodes = graph.nodes.filter(node => normalizePath(node.filePath) === filePath);const ids = new Set(nodes.map(node => node.id));- const current = { nodes, edges: graph.edges.filter(edge => ids.has(edge.source) && ids.has(edge.target)) };+ return { nodes, edges: graph.edges.filter(edge => ids.has(edge.source) && ids.has(edge.target)) };+ };+ for (const previous of baseline.files) {+ const current = fileGraph(previous.filePath);let baseEvidence;let headEvidence;- if (previous.nodes.some(node => symbolKind(node) && !nodes.some(candidate => candidate.id === node.id+ if (previous.nodes.some(node => symbolKind(node) && !current.nodes.some(candidate => candidate.id === node.id&& candidate.name === node.name && symbolKind(candidate) === symbolKind(node)))) {try {- if (!parser) {- parser = new core.TreeSitterPlugin(core.builtinLanguageConfigs.filter(config => config.treeSitter));- await parser.init();- }- const path = previous.filePath;- // :./ keeps git-show relative to projectRoot, including monorepo subdirectories.- const oldContent = git(projectRoot, ['show', `${plan.baseCommit}:./${path}`]);- const headContent = git(projectRoot, ['show', `${plan.headCommit}:./${path}`]);- if (readFileSync(join(projectRoot, path), 'utf8') !== headContent) {- throw new Error('Working source changed since prepare');- }- baseEvidence = parser.analyzeFileStrict(path, oldContent);- headEvidence = parser.analyzeFileStrict(path, headContent);+ const evidence = await parseRevisions(previous.filePath);+ baseEvidence = evidence.base;+ headEvidence = evidence.head;} catch (error) {baseEvidence = { status: 'failed' };headEvidence = { status: 'failed' };@@ -226,7 +248,46 @@ export async function validateIncrementalSymbols(projectRoot, { graph, intermediif (result.missing.some(node => node.status !== 'deleted')) report.unresolvedFiles.push(previous.filePath);}report.ok = report.errors.length === 0 && report.unresolvedFiles.length === 0;+ if (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 ids = new Set(graph.nodes.map(node => node.id));+ const remap = new Map();+ // 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) {+ 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);+ for (const replacement of result.replacements) remap.set(replacement.oldId, replacement.newId);+ }+ const edgeKey = edge => JSON.stringify([edge.source, edge.target, edge.type]);+ const existing = new Set(graph.edges.map(edgeKey));+ 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 };+ if (!ids.has(edge.source) || !ids.has(edge.target)) {+ report.droppedRetryEdges.push({ source: candidate.source, target: candidate.target, type: candidate.type });+ } else if (!existing.has(edgeKey(edge))) {+ graph.edges.push(edge);+ existing.add(edgeKey(edge));+ report.reconciledRetryEdges++;+ }+ }+ // 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) {+ atomicWriteJson(join(intermediateDir, 'assembled-graph.json'), graph);+ }+ report.graphHash = createHash('sha256').update(JSON.stringify(graph)).digest('hex');+ }+ }} catch (error) {+ report.ok = false;report.errors.push(error.message);}atomicWriteJson(reportPath, report);@@ -240,6 +301,10 @@ 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)}`);+ }lines.push(report.ok ? 'Symbol validation passed' : 'Symbol validation blocked publication; baseline not advanced');return lines.join('\n');}