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.

feat(incremental): prepare one targeted symbol recovery attempt

Lum1104373ea2bffac5
diff --git a/tests/skill/understand/test_prepare_incremental.test.mjs b/tests/skill/understand/test_prepare_incremental.test.mjs
index 7feeaa51..fb52a943 100644
--- a/tests/skill/understand/test_prepare_incremental.test.mjs
+++ b/tests/skill/understand/test_prepare_incremental.test.mjs
@@ -23,6 +23,7 @@ const fingerprintScript = join(skillDir, 'build-fingerprints.mjs');
const prepareScript = join(skillDir, 'prepare-incremental.mjs');
const finalizeScript = join(skillDir, 'finalize-incremental.mjs');
const mergeScript = join(skillDir, 'merge-batch-graphs.py');
+const retryScript = join(skillDir, 'prepare-symbol-retry.mjs');
const python = (() => {
for (const command of ['python3', 'python']) {
@@ -230,6 +231,64 @@ 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 => {
+ 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');
+ const head = commit(f.root, 'change two files');
+ const before = f.persisted();
+ prepare(f.root, f.baseCommit);
+ const otherFile = { ...f.fileNode, id: 'file:src/b.ts', filePath: 'src/b.ts', name: 'b.ts' };
+ const otherFunction = {
+ ...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: [] });
+ 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 },
+ ] });
+ expect(spawnSync(python, [mergeScript, f.root]).status).toBe(1);
+ run(process.execPath, [retryScript, f.root], f.root);
+ const retry = f.read('incremental-symbol-retry.json');
+ expect(retry.filesToReanalyze).toEqual(['src/a.ts']);
+ expect(retry.batches.flatMap(batch => batch.files.map(file => file.path))).toEqual(['src/a.ts']);
+ expect(retry.batches[0].previousSymbols.map(node => node.id)).toContain(f.methodNodes[1].id);
+ expect(retry.batches[0].previousSymbols.some(node => 'summary' in node)).toBe(false);
+ for (const name of ['batch-7-part-1.json', 'batch-7-part-2.json', 'assembled-graph.json']) {
+ expect(() => f.read(name)).toThrow();
+ }
+ const retained = f.read('batch-0.json');
+ 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(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: [],
+ });
+ const merged = spawnSync(python, [mergeScript, f.root], { encoding: 'utf8' });
+ const finalized = spawnSync(process.execPath, [finalizeScript, f.root], { encoding: 'utf8' });
+ if (outcome === 'success') {
+ expect(merged.status, merged.stderr).toBe(0);
+ expect(finalized.status, finalized.stderr).toBe(0);
+ const graph = JSON.parse(f.persisted()[0]);
+ expect(graph.project.gitCommitHash).toBe(head);
+ expect(graph.nodes.find(node => node.id === otherFunction.id)?.summary).toBe(otherFunction.summary);
+ expect(graph.nodes.some(node => node.id === obsolete.id)).toBe(false);
+ } else {
+ expect(merged.status).toBe(1);
+ expect(finalized.status).toBe(1);
+ expect(f.persisted()).toEqual(before);
+ const secondRetry = spawnSync(process.execPath, [retryScript, f.root], { encoding: 'utf8' });
+ expect(secondRetry.status).toBe(1);
+ expect(secondRetry.stderr).toContain('already used');
+ prepare(f.root, f.baseCommit);
+ expect(f.read('incremental-symbol-retry.json').attempt).toBe(1);
+ expect(spawnSync(process.execPath, [retryScript, f.root]).status).toBe(1);
+ expect(f.persisted()).toEqual(before);
+ }
+ });
+
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']));
diff --git a/understand-anything-plugin/skills/understand/prepare-incremental.mjs b/understand-anything-plugin/skills/understand/prepare-incremental.mjs
index 29137ea6..389b8461 100644
--- a/understand-anything-plugin/skills/understand/prepare-incremental.mjs
+++ b/understand-anything-plugin/skills/understand/prepare-incremental.mjs
@@ -518,8 +518,8 @@ async function main() {
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');
+ if (graph?.project?.gitCommitHash && graph.project.gitCommitHash !== baseCommit) {
+ throw new Error('Previous graph commit does not match the requested base and no symbol baseline exists; cannot safely retry');
}
atomicWriteJson(baselineSnapshotPath, { baseCommit, scan: baselineScan, graph: baselineGraph });
}
@@ -541,15 +541,9 @@ async function main() {
}
const currentInventory = sorted(currentScan.files.map(file => file.path));
const currentInventorySet = new Set(currentInventory);
- // If a previous attempt saved the graph but failed before fingerprints/meta,
- // its project hash is already HEAD. Do not let that partially advanced graph
- // redefine the previous inventory; the preserved scan + old fingerprints are
- // the retry baseline. A graph still tied to baseCommit remains useful for
- // recovering files omitted by an older scan/fingerprint format.
- const graphMatchesUncommittedHead =
- graph?.project?.gitCommitHash === headCommit && headCommit !== baseCommit;
- const inventoryGraph = graphMatchesUncommittedHead ? {} : graph;
- const oldInventory = inventoryFrom(baselineScan, inventoryGraph, oldFingerprints);
+ // The durable graph may have advanced before a failed fingerprints/meta save.
+ // Use only the preserved graph, even when retrying against a different HEAD.
+ const oldInventory = inventoryFrom(baselineScan, baselineGraph, oldFingerprints);
const oldInventorySet = new Set(oldInventory);
const trackedPaths = new Set(parseNulPaths(run(
'git',
diff --git a/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjs b/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjs
new file mode 100644
index 00000000..70331273
--- /dev/null
+++ b/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjs
@@ -0,0 +1,106 @@
+#!/usr/bin/env node
+/** Prepare exactly one targeted analyzer retry after the symbol gate fails. */
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { existsSync, readdirSync, realpathSync, unlinkSync } from 'node:fs';
+import { spawnSync } from 'node:child_process';
+import {
+ atomicWriteJson,
+ getIntermediateDir,
+ loadSymbolContext,
+ normalizePath,
+ readJson,
+ symbolKind,
+ validateIncrementalSymbols,
+} from './validate-incremental-symbols.mjs';
+
+async function main() {
+ if (process.argv.length !== 3) throw new Error('Usage: node prepare-symbol-retry.mjs <projectRoot>');
+ const projectRoot = realpathSync(process.argv[2]);
+ const intermediateDir = await getIntermediateDir(projectRoot);
+ const { plan, baseline } = loadSymbolContext(projectRoot, intermediateDir);
+ if (!['PARTIAL_UPDATE', 'ARCHITECTURE_UPDATE'].includes(plan.action)) {
+ throw new Error('Symbol retry requires a partial or architecture incremental update');
+ }
+ const retryPath = join(intermediateDir, 'incremental-symbol-retry.json');
+ if (existsSync(retryPath)) {
+ const retry = readJson(retryPath);
+ if (retry.baseCommit === plan.baseCommit && retry.headCommit === plan.headCommit && retry.attempt === 1) {
+ throw new Error('Symbol retry already used for these commits; stop without advancing the baseline');
+ }
+ }
+ // Do not trust an old report or a caller-supplied list of files to replace.
+ const report = await validateIncrementalSymbols(projectRoot, { intermediateDir });
+ if (report.ok || report.unresolvedFiles.length === 0) {
+ throw new Error('No unresolved symbol files eligible for a targeted retry; inspect the symbol report');
+ }
+ const paths = new Set(report.unresolvedFiles);
+ const changedFilesPath = join(intermediateDir, 'incremental-symbol-retry-files.json');
+ const batchesPath = join(intermediateDir, 'incremental-symbol-retry-batches.json');
+ atomicWriteJson(changedFilesPath, [...paths]);
+ const skillDir = dirname(fileURLToPath(import.meta.url));
+ const batching = spawnSync(process.execPath, [
+ join(skillDir, 'compute-batches.mjs'), projectRoot,
+ `--changed-files=${changedFilesPath}`, `--output=${batchesPath}`,
+ ], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
+ if (batching.stderr) process.stderr.write(batching.stderr);
+ if (batching.status !== 0) throw new Error(`Retry batching failed: ${batching.error ?? batching.status}`);
+ const batches = readJson(batchesPath).batches;
+ const scheduled = batches.flatMap(batch => batch.files.map(file => file.path));
+ if (JSON.stringify([...scheduled].sort()) !== JSON.stringify([...paths].sort())) {
+ throw new Error('Retry batches do not cover exactly the affected files');
+ }
+ for (const batch of batches) {
+ if (!Number.isInteger(batch.batchIndex) || batch.batchIndex < 1) throw new Error('Invalid retry batch index');
+ const files = new Set(batch.files.map(file => file.path));
+ batch.previousSymbols = baseline.files.filter(file => files.has(file.filePath)).flatMap(file =>
+ file.nodes.filter(symbolKind).map(node => {
+ const parents = new Set(file.edges.filter(edge => edge.type === 'contains' && edge.target === node.id)
+ .map(edge => edge.source));
+ const owners = file.nodes.filter(parent => parent.type === 'class' && parents.has(parent.id))
+ .map(parent => parent.name);
+ return {
+ id: node.id, name: node.name, type: node.type, filePath: node.filePath,
+ ...(node.lineRange ? { lineRange: node.lineRange } : {}),
+ ...(owners.length ? { owners } : {}),
+ };
+ }),
+ );
+ batch.missingSymbols = report.files.filter(file => files.has(file.filePath));
+ }
+ const assembled = readJson(join(intermediateDir, 'assembled-graph.json'));
+ const removedIds = new Set(assembled.nodes.filter(node => paths.has(normalizePath(node.filePath)))
+ .map(node => node.id));
+ const retained = {
+ nodes: assembled.nodes.filter(node => !removedIds.has(node.id)),
+ edges: assembled.edges.filter(edge => !removedIds.has(edge.source) && !removedIds.has(edge.target)),
+ };
+
+ // Persist the attempt BEFORE mutating batches: a crash must not buy another
+ // automatic retry. Only current merged contributions are compacted here;
+ // no old symbol or semantic edge is copied back from the symbol baseline.
+ atomicWriteJson(retryPath, {
+ version: 1, baseCommit: plan.baseCommit, headCommit: plan.headCommit, attempt: 1,
+ filesToReanalyze: [...paths], batches,
+ });
+ // Replace all numeric shards with one normalized retained contribution.
+ // Merely overwriting the main batch leaves stale -part-* files capable of
+ // masking a failed repair or resurrecting an obsolete node/edge.
+ for (const name of readdirSync(intermediateDir)) {
+ if (/^batch-\d+(?:-part-\d+)?\.json$/.test(name)) unlinkSync(join(intermediateDir, name));
+ }
+ atomicWriteJson(join(intermediateDir, 'batch-0.json'), retained);
+ // Force another merge and regenerate any architecture/tour based on the
+ // incomplete candidate. Keep the failure report for inspection.
+ for (const name of ['assembled-graph.json', 'layers.json', 'tour.json']) {
+ if (existsSync(join(intermediateDir, name))) unlinkSync(join(intermediateDir, name));
+ }
+ process.stdout.write(`Prepared symbol retry 1/1 for ${paths.size} file(s); dispatch batches from ${retryPath}\n`);
+}
+
+try {
+ await main();
+} catch (error) {
+ process.stderr.write(`prepare-symbol-retry.mjs failed: ${error.message}\n`);
+ process.exitCode = 1;
+}
diff --git a/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs b/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs
index 6d70d25e..3e4a2046 100644
--- a/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs
+++ b/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs
@@ -22,6 +22,10 @@ async function getCore() {
return corePromise;
}
+export async function getIntermediateDir(projectRoot) {
+ return join((await getCore()).resolveUaDir(projectRoot), 'intermediate');
+}
+
export function readJson(path) {
return JSON.parse(readFileSync(path, 'utf8'));
}
@@ -167,7 +171,8 @@ export function loadSymbolContext(projectRoot, intermediateDir) {
|| !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) {
+ || paths.some(path => !normalizePath(path) || (plan.deletedFiles ?? []).includes(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) {
@@ -190,7 +195,6 @@ export async function validateIncrementalSymbols(projectRoot, { graph, intermedi
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)) };