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): block publication when existing symbols disappear
Lum1104cd6751274a07
diff --git a/tests/skill/understand/test_incremental_symbols.test.mjs b/tests/skill/understand/test_incremental_symbols.test.mjsnew file mode 100644index 00000000..9242d6f3--- /dev/null+++ b/tests/skill/understand/test_incremental_symbols.test.mjs@@ -0,0 +1,86 @@+import { beforeAll, describe, expect, it } from 'vitest';+import { TreeSitterPlugin } from '../../../understand-anything-plugin/packages/core/dist/index.js';+import { compareFileSymbols } from '../../../understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs';++let parser;+beforeAll(async () => {+ parser = new TreeSitterPlugin();+ await parser.init();+});++const node = (name, extra = {}) => ({+ id: `function:src/a.ts:${name}`, name, type: 'function', filePath: 'src/a.ts', ...extra,+});+const graph = nodes => ({ filePath: 'src/a.ts', nodes, edges: [] });+const parse = content => parser.analyzeFileStrict('src/a.ts', content);+const compare = (oldNodes, newNodes, oldSource, newSource) => compareFileSymbols(+ graph(oldNodes), graph(newNodes), parse(oldSource), parse(newSource),+);++describe('incremental symbol matching', () => {+ it('detects an omitted old method even when total node counts stay the same', () => {+ const result = compare([node('A.keep'), node('A.lost')], [node('A.keep'), node('A.added')],+ 'class A { keep() {} lost() {} }', 'class A { keep() {} lost() {} added() {} }');+ expect(result.beforeCount).toBe(result.afterCount);+ expect(result.missing).toEqual([expect.objectContaining({ name: 'A.lost', status: 'still-present' })]);+ });++ it('accepts spelling changes and moved lines for a uniquely identified method', () => {+ const result = compare([node('A.run', { lineRange: [2, 2] })],+ [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([]);+ });++ it('does not substitute a different class with the same method name', () => {+ const code = 'class A { run() {} }\nclass B { run() {} }';+ const result = compare([node('A.run'), node('B.run')], [node('B.run')], code, code);+ expect(result.missing).toEqual([expect.objectContaining({ name: 'A.run', status: 'still-present' })]);+ expect(compare([node('run')], [], code, code).missing[0].status).toBe('unknown');+ });++ it('uses class containment when graph method names are unqualified', () => {+ const code = 'class A { run() {} }\nclass B { run() {} }';+ const previous = graph([node('A', { id: 'class:src/a.ts:A', type: 'class' }), node('run')]);+ previous.edges.push({ type: 'contains', source: 'class:src/a.ts:A', target: node('run').id });+ const result = compareFileSymbols(previous, graph([previous.nodes[0]]), parse(code), parse(code));+ expect(result.missing[0]).toMatchObject({ name: 'run', status: 'still-present' });+ });++ it('confirms genuine function, class, and method deletions without restoring them', () => {+ const result = compare([node('gone'), node('Old', { type: 'class' }), node('A.removed')], [],+ 'function gone() {} class Old {} class A { removed() {} keep() {} }',+ 'class A { keep() {} }');+ expect(result.missing.map(entry => entry.status)).toEqual(['deleted', 'deleted', 'deleted']);+ });++ it.each([+ ['parse error', 'class A {'],+ ['empty extraction', '// everything removed'],+ ['unextracted arrow method', 'class A { run = () => {}; }'],+ ['computed method', 'class A { ["run"]() {} }'],+ ['moved method', 'class B { run() {} }'],+ ])('treats %s as unknown, never deletion', (_label, code) => {+ expect(compare([node('A.run')], [], 'class A { run() {} }', code).missing[0].status).toBe('unknown');+ });++ it('requires valid baseline extraction and rejects unsupported languages', () => {+ for (const evidence of [{ status: 'unsupported' }, parse('class Broken {')]) {+ const result = compareFileSymbols(graph([node('lost')]), graph([]), evidence, parse('function keep() {}'));+ expect(result.missing[0].status).toBe('unknown');+ }+ });++ it('cannot use one new node to replace two old nodes with the same source identity', () => {+ const code = 'function f() {}';+ const result = compare([node('f', { id: 'old:one' }), node('f', { id: 'old:two' })],+ [node('f', { id: 'new:one' })], code, code);+ expect(result.missing.map(entry => entry.status)).toEqual(['unknown', 'unknown']);+ });++ it('keeps overloads ambiguous even when a qualified name is available', () => {+ const result = compare([node('A.run')], [],+ 'class A { run() {} run(n: number) {} }', 'class A { keep() {} }');+ expect(result.missing[0].status).toBe('unknown');+ });+});diff --git a/tests/skill/understand/test_prepare_incremental.test.mjs b/tests/skill/understand/test_prepare_incremental.test.mjsindex 3875486f..7feeaa51 100644--- a/tests/skill/understand/test_prepare_incremental.test.mjs+++ b/tests/skill/understand/test_prepare_incremental.test.mjs@@ -187,6 +187,40 @@ function prepare(root, baseCommit, extraArgs = []) {};}+function symbolFixture(count = 20) {+ 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({+ 'src/a.ts': source(names),+ 'src/b.ts': 'export const b = 1;\n',+ 'src/c.ts': 'export const c = 1;\n',+ 'src/d.ts': 'export const d = 1;\n',+ });+ const { root } = fixture;+ const dataDir = join(root, '.ua');+ const intermediate = join(dataDir, 'intermediate');+ const graphPath = join(dataDir, 'knowledge-graph.json');+ const graph = JSON.parse(readFileSync(graphPath, 'utf8'));+ const classNode = {+ id: 'class:src/a.ts:Service', name: 'Service', type: 'class', filePath: 'src/a.ts',+ summary: 'Service', tags: [], complexity: 'simple',+ };+ const methodNodes = names.map(name => ({+ ...classNode, id: `function:src/a.ts:Service.${name}`, name: `Service.${name}`, type: 'function',+ }));+ graph.nodes.push(classNode, ...methodNodes);+ graph.edges.push(...methodNodes.map(node => ({+ source: classNode.id, target: node.id, type: 'contains', direction: 'forward', weight: 1,+ })));+ writeFileSync(graphPath, JSON.stringify(graph));+ const fileNode = graph.nodes.find(node => node.id === 'file:src/a.ts');+ const read = name => JSON.parse(readFileSync(join(intermediate, name), 'utf8'));+ const write = (name, value) => writeFileSync(join(intermediate, name), JSON.stringify(value));+ const persisted = () => ['knowledge-graph.json', 'fingerprints.json', 'meta.json']+ .map(name => readFileSync(join(dataDir, name), 'utf8'));+ return { ...fixture, intermediate, dataDir, source, names, fileNode, classNode, methodNodes, read, write, persisted };+}+afterEach(async () => {for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true });// These integration tests intentionally use synchronous child processes.@@ -195,6 +229,101 @@ afterEach(async () => {await new Promise(resolve => setImmediate(resolve));});+describe('incremental symbol publication gate', { timeout: 30_000 }, () => {+ it('lists all 19 missing methods and blocks merge and direct finalize without advancing any baseline', () => {+ const f = symbolFixture();+ 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);+ f.write('batch-0.json', { nodes: [f.fileNode, f.classNode, f.methodNodes[0]], edges: [] });+ const merge = spawnSync(python, [mergeScript, f.root], { encoding: 'utf8' });+ expect(merge.status).toBe(1);+ const report = f.read('incremental-symbol-report.json');+ expect(report.ok).toBe(false);+ expect(report.files[0].missing).toHaveLength(19);+ expect(report.files[0].missing.every(node => node.status === 'still-present')).toBe(true);+ for (const method of f.methodNodes.slice(1)) expect(merge.stderr).toContain(method.id);+ // A forged/stale merge success cannot bypass finalization's shared check.+ f.write('incremental-symbol-report.json', { ok: true });+ const finalize = spawnSync(process.execPath, [finalizeScript, f.root], { encoding: 'utf8' });+ expect(finalize.status).toBe(1);+ expect(finalize.stderr).toContain('baseline not advanced');+ expect(f.persisted()).toEqual(before);+ });++ it('keeps the original symbol baseline and removes stale complete/split batches on repeated prepare', () => {+ const f = symbolFixture(2);+ writeProjectFile(f.root, 'src/a.ts', f.source([...f.names, 'added']));+ const headCommit = commit(f.root, 'add method');+ prepare(f.root, f.baseCommit);+ const original = f.read('incremental-symbol-baseline.json');+ // Simulate a graph save followed by a failure before fingerprints/meta.+ const graphPath = join(f.dataDir, 'knowledge-graph.json');+ const partial = JSON.parse(readFileSync(graphPath, 'utf8'));+ partial.project.gitCommitHash = headCommit;+ partial.nodes = partial.nodes.filter(node => node.id !== f.methodNodes[1].id);+ writeFileSync(graphPath, JSON.stringify(partial));+ for (const name of ['batch-0.json', 'batch-0-part-1.json', 'batch-0-part-2.json']) {+ f.write(name, { nodes: [f.methodNodes[1]], edges: [] });+ }+ prepare(f.root, f.baseCommit);+ expect(f.read('incremental-symbol-baseline.json')).toEqual(original);+ for (const name of ['batch-0.json', 'batch-0-part-1.json', 'batch-0-part-2.json']) {+ expect(() => f.read(name)).toThrow();+ }+ });++ it('allows a source-confirmed method deletion and does not restore old nodes or edges', () => {+ const f = symbolFixture(2);+ writeProjectFile(f.root, 'src/a.ts', f.source([f.names[0]]));+ const head = commit(f.root, 'delete method');+ prepare(f.root, f.baseCommit);+ f.write('batch-0.json', { nodes: [f.fileNode, f.classNode, f.methodNodes[0]], edges: [] });+ run(python, [mergeScript, f.root], f.root);+ expect(f.read('incremental-symbol-report.json').files[0].missing[0].status).toBe('deleted');+ run(process.execPath, [finalizeScript, f.root], f.root);+ const graph = JSON.parse(f.persisted()[0]);+ expect(graph.project.gitCommitHash).toBe(head);+ expect(graph.nodes.some(node => node.id === f.methodNodes[1].id)).toBe(false);+ expect(graph.edges.some(edge => edge.target === f.methodNodes[1].id)).toBe(false);+ });++ it.each(['delete', 'exclude'])('allows an explicit file %s with old symbols', operation => {+ const f = symbolFixture(2);+ if (operation === 'delete') {+ unlinkSync(join(f.root, 'src/a.ts'));+ commit(f.root, 'delete file');+ }+ prepare(f.root, f.baseCommit, operation === 'exclude' ? ['--exclude', 'src/a.ts'] : []);+ expect(f.read('incremental-symbol-baseline.json').files).toEqual([]);+ run(python, [mergeScript, f.root], f.root);+ run(process.execPath, [finalizeScript, f.root], f.root);+ expect(JSON.parse(f.persisted()[0]).nodes.some(node => node.filePath === 'src/a.ts')).toBe(false);+ });++ it('uses legacy data directories and refuses a missing or mismatched symbol snapshot', () => {+ const f = symbolFixture(2);+ writeProjectFile(f.root, 'src/a.ts', f.source([...f.names, 'added']));+ commit(f.root, 'add method');+ const legacy = join(f.root, '.understand-anything');+ renameSync(f.dataDir, legacy);+ run(process.execPath, [prepareScript, f.root, f.baseCommit], f.root);+ const intermediate = join(legacy, 'intermediate');+ const baselinePath = join(intermediate, 'incremental-symbol-baseline.json');+ const baseline = JSON.parse(readFileSync(baselinePath, 'utf8'));+ expect(baseline.files[0].nodes).toHaveLength(4);+ writeFileSync(join(intermediate, 'batch-0.json'), JSON.stringify({+ nodes: [f.fileNode, f.classNode, ...f.methodNodes], edges: [],+ }));+ baseline.headCommit = f.baseCommit;+ writeFileSync(baselinePath, JSON.stringify(baseline));+ expect(spawnSync(python, [mergeScript, f.root]).status).toBe(1);+ unlinkSync(baselinePath);+ expect(spawnSync(process.execPath, [finalizeScript, f.root]).status).toBe(1);+ });+});+describe('prepare-incremental.mjs', { timeout: 30_000 }, () => {it('refreshes imports in the same run and only schedules the structural source', () => {const { root, baseCommit } = setupRepository({diff --git a/understand-anything-plugin/skills/understand/finalize-incremental.mjs b/understand-anything-plugin/skills/understand/finalize-incremental.mjsindex de09ddb5..d02de8d9 100644--- a/understand-anything-plugin/skills/understand/finalize-incremental.mjs+++ b/understand-anything-plugin/skills/understand/finalize-incremental.mjs@@ -22,6 +22,7 @@ import {renameSync,writeFileSync,} from 'node:fs';+import { validateIncrementalSymbols, formatSymbolReport } from './validate-incremental-symbols.mjs';const __dirname = dirname(fileURLToPath(import.meta.url));const pluginRoot = resolve(__dirname, '../..');@@ -375,7 +376,7 @@ function projectMetadata(previousProject, plan, scan) {};}-function main() {+async function main() {const args = process.argv.slice(2);if (args.length !== 1 || args[0].startsWith('--')) {throw new Error('Usage: node finalize-incremental.mjs <projectRoot>');@@ -470,6 +471,10 @@ function main() {// Ordering is intentional: a failed graph save must never advance the// structural baseline and hide the failed update from the next run.+ // Recheck the actual graph being saved, never trust a prior merge report.+ const symbolReport = await validateIncrementalSymbols(projectRoot, { graph, intermediateDir });+ process.stderr.write(`${formatSymbolReport(symbolReport)}\n`);+ if (!symbolReport.ok) throw new Error('Unresolved incremental symbol loss; baseline not advanced');atomicWriteJson(graphPath, graph);}@@ -491,7 +496,7 @@ function isCliEntry() {if (isCliEntry()) {try {- main();+ await main();} catch (error) {process.stderr.write(`finalize-incremental.mjs failed: ${error.message}\n${error.stack}\n`);process.exit(1);diff --git a/understand-anything-plugin/skills/understand/merge-batch-graphs.py b/understand-anything-plugin/skills/understand/merge-batch-graphs.pyindex 338deaff..67d1b121 100644--- a/understand-anything-plugin/skills/understand/merge-batch-graphs.py+++ b/understand-anything-plugin/skills/understand/merge-batch-graphs.py@@ -20,6 +20,7 @@ Input/output live under the project's data dir (`.ua/`, or legacyimport jsonimport osimport re+import subprocessimport sysfrom collections import Counterfrom pathlib import Path@@ -1291,6 +1292,18 @@ def main() -> None:size_kb = output_path.stat().st_size / 1024print(f"\nWritten to {output_path} ({size_kb:.0f} KB)", file=sys.stderr)+ # The old symbols live outside batch-existing.json, which intentionally+ # excludes reanalyzed files. Keep failed output as a diagnostic artifact,+ # but return failure so the orchestrator repairs it before publication.+ plan_path = intermediate_dir / "incremental-plan.json"+ if plan_path.exists():+ plan = json.loads(plan_path.read_text(encoding="utf-8"))+ if plan.get("action") in ("PARTIAL_UPDATE", "ARCHITECTURE_UPDATE"):+ validator = Path(__file__).resolve().with_name("validate-incremental-symbols.mjs")+ result = subprocess.run(["node", str(validator), str(project_root)], check=False)+ if result.returncode != 0:+ sys.exit(result.returncode)+if __name__ == "__main__":main()diff --git a/understand-anything-plugin/skills/understand/prepare-incremental.mjs b/understand-anything-plugin/skills/understand/prepare-incremental.mjsindex b2156475..29137ea6 100644--- a/understand-anything-plugin/skills/understand/prepare-incremental.mjs+++ b/understand-anything-plugin/skills/understand/prepare-incremental.mjs@@ -11,6 +11,7 @@* - changed-files.json* - fingerprint-patch.json* - incremental-baseline.json (retry-safe copy of the pre-update scan)+ * - incremental-symbol-baseline.json (old nodes for reanalyzed files)* - batch-existing.json (PARTIAL/ARCHITECTURE only)** It also atomically refreshes scan-result.json (except for a commit whose@@ -122,6 +123,7 @@ function clearIncrementalScratch(intermediateDir) {'batches.json','layers.json','tour.json',+ 'incremental-symbol-report.json',]);for (const name of readdirSync(intermediateDir)) {if (exactNames.has(name) || /^batch-\d+(?:-part-\d+)?\.json$/.test(name)) {@@ -509,8 +511,17 @@ async function main() {const baselineScan = existingSnapshot?.baseCommit === baseCommit? existingSnapshot.scan: oldScan;- if (existingSnapshot?.baseCommit !== baseCommit) {- atomicWriteJson(baselineSnapshotPath, { baseCommit, scan: oldScan });+ const baselineGraph = existingSnapshot?.baseCommit === baseCommit && existingSnapshot.graph+ ? existingSnapshot.graph+ : graph;+ if (!Array.isArray(baselineGraph.nodes) || !Array.isArray(baselineGraph.edges)) {+ throw new Error('A valid previous graph is required for incremental symbol protection');+ }+ if (existingSnapshot?.baseCommit !== baseCommit || !existingSnapshot.graph) {+ if (graph?.project?.gitCommitHash === headCommit && headCommit !== baseCommit) {+ throw new Error('Previous graph has already advanced without a symbol baseline; cannot safely retry');+ }+ atomicWriteJson(baselineSnapshotPath, { baseCommit, scan: baselineScan, graph: baselineGraph });}// A failed prior attempt can leave complete or split analyzer batches behind.// Remove only known internal scratch names before planning the retry so the@@ -665,6 +676,26 @@ async function main() {reason: decision.reason,};+ // Always derive this manifest from the immutable pre-update graph, including+ // on repeated prepare calls after an unsuccessful merge/finalization.+ const symbolFiles = filesToReanalyze.map(filePath => {+ const nodes = baselineGraph.nodes.filter(node => normalizeRelativePath(node.filePath) === filePath);+ const ids = new Set(nodes.map(node => node.id));+ return {+ filePath,+ nodes,+ edges: baselineGraph.edges.filter(edge => ids.has(edge.source) && ids.has(edge.target)),+ };+ });+ atomicWriteJson(join(intermediateDir, 'incremental-symbol-baseline.json'), {+ version: 1, baseCommit, headCommit, files: symbolFiles,+ });+ const retryPath = join(intermediateDir, 'incremental-symbol-retry.json');+ const retry = readJson(retryPath);+ if (retry && (retry.baseCommit !== baseCommit || retry.headCommit !== headCommit)) {+ unlinkSync(retryPath);+ }+atomicWriteJson(join(intermediateDir, 'fingerprint-patch.json'), {version: '1.0.0',baseCommit,@@ -679,7 +710,7 @@ async function main() {const pathsToReplace = new Set([...filesToReanalyze, ...deletedFiles]);atomicWriteJson(join(intermediateDir, 'batch-existing.json'),- pruneExistingGraph(graph, pathsToReplace, new Set(importAnalysisPaths)),+ pruneExistingGraph(baselineGraph, pathsToReplace, new Set(importAnalysisPaths)),);}atomicWriteJson(join(intermediateDir, 'incremental-plan.json'), plan);diff --git a/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs b/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjsnew file mode 100644index 00000000..6d70d25e--- /dev/null+++ b/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs@@ -0,0 +1,260 @@+#!/usr/bin/env node+/** Shared merge/finalize gate. Reports evidence; never restores old graph data. */+import { createRequire } from 'node:module';+import { dirname, isAbsolute, join, resolve } from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';+import { existsSync, readFileSync, realpathSync, renameSync, writeFileSync } from 'node:fs';+import { spawnSync } from 'node:child_process';+import { createHash } from 'node:crypto';++const skillDir = dirname(fileURLToPath(import.meta.url));+const pluginRoot = resolve(skillDir, '../..');+const require = createRequire(join(pluginRoot, 'package.json'));+let corePromise;+async function getCore() {+ corePromise ??= (async () => {+ try {+ return await import(pathToFileURL(require.resolve('@understand-anything/core')).href);+ } catch {+ return import(pathToFileURL(join(pluginRoot, 'packages/core/dist/index.js')).href);+ }+ })();+ return corePromise;+}++export function readJson(path) {+ return JSON.parse(readFileSync(path, 'utf8'));+}++export function atomicWriteJson(path, value) {+ const temp = `${path}.tmp-${process.pid}`;+ writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`);+ renameSync(temp, path);+}++export function normalizePath(value) {+ if (typeof value !== 'string' || !value || isAbsolute(value)) return null;+ const path = (process.platform === 'win32' ? value.replaceAll('\\', '/') : value).replace(/^\.\//, '');+ return path.split('/').includes('..') ? null : path;+}++export function symbolKind(node) {+ if (node.type === 'class') return 'class';+ if (['function', 'func', 'method'].includes(node.type)) return 'callable';+ return null;+}++function qualifiedName(name) {+ return typeof name === 'string' ? name.replaceAll('::', '.').replaceAll('#', '.') : '';+}++function symbolKey(symbol) {+ return JSON.stringify([symbol.kind, symbol.owner, symbol.name]);+}++function sourceSymbols(evidence) {+ if (evidence?.status !== 'succeeded' || !evidence.structure) return [];+ const { functions, classes } = evidence.structure;+ const symbols = [];+ for (const cls of classes) {+ symbols.push({ kind: 'class', owner: '', name: cls.name, lineRange: cls.lineRange });+ for (const name of cls.methods) {+ symbols.push({ kind: 'callable', owner: cls.name, name, lineRange: cls.lineRange });+ }+ }+ for (const fn of functions) {+ // Some extractors emit methods in both functions and classes[].methods.+ // Keep overloads ambiguous, but avoid counting that dual representation.+ const owners = classes.filter(cls => cls.methods.includes(fn.name)+ && fn.lineRange[0] >= cls.lineRange[0] && fn.lineRange[1] <= cls.lineRange[1]);+ if (owners.length > 0) continue;+ symbols.push({ kind: 'callable', owner: '', name: fn.name, lineRange: fn.lineRange });+ }+ return symbols;+}++function resolveSymbol(node, graph, symbols) {+ const kind = symbolKind(node);+ const path = normalizePath(node.filePath);+ const names = new Set([qualifiedName(node.name)]);+ // Accept ID spelling changes, including func/function and class separators.+ // Path and kind are independently checked; the ID is only a name hint.+ const marker = `:${path}:`;+ if (typeof node.id === 'string' && node.id.includes(marker)) {+ names.add(qualifiedName(node.id.slice(node.id.indexOf(marker) + marker.length)));+ }+ let candidates = symbols.filter(symbol => symbol.kind === kind && (+ names.has(qualifiedName(symbol.name))+ || (symbol.owner && names.has(qualifiedName(`${symbol.owner}.${symbol.name}`)))+ ));+ const qualified = candidates.filter(symbol => symbol.owner+ && names.has(qualifiedName(`${symbol.owner}.${symbol.name}`)));+ if (qualified.length) candidates = qualified;+ const parentIds = new Set(graph.edges.filter(edge => edge.type === 'contains' && edge.target === node.id)+ .map(edge => edge.source));+ const owners = graph.nodes.filter(parent => parent.type === 'class' && parentIds.has(parent.id))+ .map(parent => parent.name);+ if (owners.length) candidates = candidates.filter(symbol => owners.includes(symbol.owner));+ // Lines locate ownership within one revision only; they are never identity+ // across revisions. Do not use lines to guess among overloads/same-name classes.+ if (candidates.length > 1 && Array.isArray(node.lineRange)) {+ const located = candidates.filter(symbol => symbol.owner+ && node.lineRange[0] >= symbol.lineRange[0] && node.lineRange[1] <= symbol.lineRange[1]);+ if (located.length === 1) candidates = located;+ }+ return candidates.length === 1 ? candidates[0] : null;+}++export function compareFileSymbols(previous, current, baseEvidence, headEvidence) {+ const oldSymbols = previous.nodes.filter(symbolKind);+ const newSymbols = current.nodes.filter(symbolKind);+ const baseSource = sourceSymbols(baseEvidence);+ const headSource = sourceSymbols(headEvidence);+ const oldMappings = oldSymbols.map(node => resolveSymbol(node, previous, baseSource));+ const newMappings = newSymbols.map(node => resolveSymbol(node, current, headSource));+ const missing = [];+ for (let index = 0; index < oldSymbols.length; index++) {+ const node = oldSymbols[index];+ if (newSymbols.some(candidate => candidate.id === node.id+ && symbolKind(candidate) === symbolKind(node) && candidate.name === node.name)) continue;+ const entry = { id: node.id, name: node.name, type: node.type, status: 'unknown', reason: '' };+ const old = oldMappings[index];+ if (!old || baseEvidence?.status !== 'succeeded' || headEvidence?.status !== 'succeeded') {+ entry.reason = 'Old symbol cannot be mapped uniquely, or source parsing is unavailable/failed';+ } else if (oldMappings.filter(symbol => symbol && symbolKey(symbol) === symbolKey(old)).length !== 1) {+ entry.reason = 'Multiple old graph nodes map to the same source symbol';+ } 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) {+ entry.status = 'still-present';+ entry.reason = 'Symbol still exists in current source but is missing or ambiguous in the new graph';+ } else if (matches.length > 1) {+ entry.reason = 'Current source has ambiguous same-name symbols';+ } else if (headSource.length === 0) {+ entry.reason = 'Empty structural extraction is not proof of deletion';+ } else if (headSource.some(symbol => symbol.name === old.name)+ || (headEvidence.leafTexts ?? []).some(text => qualifiedName(text.replace(/^['"`]|['"`]$/g, '')) === qualifiedName(old.name))) {+ entry.reason = 'Name remains in source; moved or unsupported syntax cannot be ruled out';+ } else {+ entry.status = 'deleted';+ entry.reason = 'Both revisions parsed; uniquely mapped old symbol and its name are absent from current source';+ }+ }+ missing.push(entry);+ }+ return {+ filePath: previous.filePath,+ beforeCount: previous.nodes.length,+ afterCount: current.nodes.length,+ beforeSymbolCount: oldSymbols.length,+ afterSymbolCount: newSymbols.length,+ missing,+ };+}++export function git(root, args) {+ const result = spawnSync('git', args, { cwd: root, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 });+ if (result.status !== 0) throw new Error(`git ${args[0]} failed: ${result.stderr || result.error || result.status}`);+ return result.stdout;+}++export function loadSymbolContext(projectRoot, intermediateDir) {+ const plan = readJson(join(intermediateDir, 'incremental-plan.json'));+ const baseline = readJson(join(intermediateDir, 'incremental-symbol-baseline.json'));+ if (baseline.version !== 1 || baseline.baseCommit !== plan.baseCommit || baseline.headCommit !== plan.headCommit+ || !Array.isArray(baseline.files)) throw new Error('Symbol baseline does not match the incremental plan');+ const paths = baseline.files.map(file => file.filePath).sort();+ if (JSON.stringify(paths) !== JSON.stringify([...plan.filesToReanalyze].sort())+ || paths.some(path => !normalizePath(path)) || new Set(paths).size !== paths.length) {+ throw new Error('Symbol baseline file inventory does not match the incremental plan');+ }+ if (git(projectRoot, ['rev-parse', 'HEAD']).trim() !== plan.headCommit) {+ throw new Error('HEAD changed since prepare; baseline not advanced');+ }+ return { plan, baseline };+}++export async function validateIncrementalSymbols(projectRoot, { graph, intermediateDir } = {}) {+ const core = await getCore();+ intermediateDir ??= join(core.resolveUaDir(projectRoot), 'intermediate');+ const reportPath = join(intermediateDir, 'incremental-symbol-report.json');+ const report = { version: 1, ok: false, files: [], unresolvedFiles: [], errors: [] };+ try {+ const { plan, baseline } = loadSymbolContext(projectRoot, intermediateDir);+ report.baseCommit = plan.baseCommit;+ report.headCommit = plan.headCommit;+ graph ??= readJson(join(intermediateDir, 'assembled-graph.json'));+ if (!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) {+ if ((plan.deletedFiles ?? []).includes(previous.filePath)) continue;+ const nodes = graph.nodes.filter(node => normalizePath(node.filePath) === previous.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)) };+ let baseEvidence;+ let headEvidence;+ if (previous.nodes.some(node => symbolKind(node) && !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);+ } catch (error) {+ baseEvidence = { status: 'failed' };+ headEvidence = { status: 'failed' };+ report.errors.push(`${previous.filePath}: ${error.message}`);+ }+ }+ const result = compareFileSymbols(previous, current, baseEvidence, headEvidence);+ report.files.push(result);+ if (result.missing.some(node => node.status !== 'deleted')) report.unresolvedFiles.push(previous.filePath);+ }+ report.ok = report.errors.length === 0 && report.unresolvedFiles.length === 0;+ } catch (error) {+ report.errors.push(error.message);+ }+ atomicWriteJson(reportPath, report);+ return report;+}++export function formatSymbolReport(report) {+ const lines = ['Incremental symbol validation:'];+ for (const file of report.files) {+ lines.push(` ${JSON.stringify(file.filePath)}: nodes ${file.beforeCount} -> ${file.afterCount}; symbols ${file.beforeSymbolCount} -> ${file.afterSymbolCount}`);+ 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}`));+ lines.push(report.ok ? 'Symbol validation passed' : 'Symbol validation blocked publication; baseline not advanced');+ return lines.join('\n');+}++const isCli = process.argv[1] && existsSync(process.argv[1])+ && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));+if (isCli) {+ if (process.argv.length !== 3) {+ process.stderr.write('Usage: node validate-incremental-symbols.mjs <projectRoot>\n');+ process.exitCode = 1;+ } else {+ try {+ const report = await validateIncrementalSymbols(realpathSync(process.argv[2]));+ process.stderr.write(`${formatSymbolReport(report)}\n`);+ process.exitCode = report.ok ? 0 : 1;+ } catch (error) {+ process.stderr.write(`Symbol validation failed: ${error.message}\n`);+ process.exitCode = 1;+ }+ }+}