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(incremental): preserve current meanings of reused endpoint IDs

Lum1104577e33f6ffb3
diff --git a/tests/skill/understand/test_prepare_incremental.test.mjs b/tests/skill/understand/test_prepare_incremental.test.mjs
index 709811f0..6e42f048 100644
--- a/tests/skill/understand/test_prepare_incremental.test.mjs
+++ b/tests/skill/understand/test_prepare_incremental.test.mjs
@@ -232,6 +232,68 @@ afterEach(async () => {
});
describe('incremental symbol publication gate', { timeout: 30_000 }, () => {
+ it.each([false, true])('preserves current endpoint meanings when baseline IDs are reused (rename again=%s)', renameAgain => {
+ const service = names => `export class Service { ${names.map(name => `${name}() { return 1; }`).join(' ')} }\n`;
+ const other = 'export class Other { method0() { return 2; } }\n';
+ const third = 'export class Third { method0() { return 3; } }\n';
+ const a = 'src/a.ts';
+ const b = 'src/b.ts';
+ const f = symbolFixture(2, { [a]: service(['method0', 'method1']) + other + third, [b]: service(['method0']) + other });
+ const cls = (filePath, name) => ({ ...f.classNode, id: `class:${filePath}:${name}`, filePath, name });
+ const method = (filePath, owner, generic = false) => ({
+ ...f.methodNodes[0], filePath,
+ id: `function:${filePath}:${generic ? 'method0' : `${owner}.method0`}`,
+ name: generic ? 'method0' : `${owner}.method0`,
+ });
+ const contains = (parent, child) => ({ source: parent.id, target: child.id, type: 'contains', direction: 'forward', weight: 1 });
+ const oldA = method(a, 'Service', true);
+ const oldB = method(b, 'Service', true);
+ const aOther = cls(a, 'Other');
+ const aThird = cls(a, 'Third');
+ const bService = cls(b, 'Service');
+ const bOther = cls(b, 'Other');
+ const previous = JSON.parse(f.persisted()[0]);
+ previous.nodes = previous.nodes.map(node => node.id === f.methodNodes[0].id ? oldA : node);
+ previous.nodes.push(aOther, aThird, bService, bOther, oldB);
+ previous.edges = previous.edges.map(edge => edge.target === f.methodNodes[0].id ? { ...edge, target: oldA.id } : edge);
+ previous.edges.push(contains(bService, oldB));
+ writeFileSync(join(f.dataDir, 'knowledge-graph.json'), JSON.stringify(previous));
+ writeProjectFile(f.root, a, service([...f.names, 'added']) + other + third);
+ writeProjectFile(f.root, b, service(['method0', 'added']) + other);
+ commit(f.root, 'change both services');
+ prepare(f.root, f.baseCommit);
+ const aServiceRun = method(a, 'Service');
+ const bServiceRun = method(b, 'Service');
+ const aOtherRun = method(a, 'Other', true);
+ const bOtherRun = method(b, 'Other', true);
+ f.write('batch-1.json', {
+ nodes: [f.fileNode, f.classNode, aOther, aThird, aServiceRun, aOtherRun,
+ previous.nodes.find(node => node.id === `file:${b}`), bService, bOther, bServiceRun, bOtherRun],
+ edges: [contains(f.classNode, aServiceRun), contains(aOther, aOtherRun),
+ contains(bService, bServiceRun), contains(bOther, bOtherRun),
+ { source: bOtherRun.id, target: aOtherRun.id, type: 'calls', direction: 'forward', weight: 0.8 }],
+ });
+ 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([a]);
+ expect(retry.inboundEdgeCandidates).toContainEqual(expect.objectContaining({ source: bOtherRun.id, target: aOtherRun.id }));
+ const restoredOther = renameAgain ? method(a, 'Other') : aOtherRun;
+ const thirdRun = method(a, 'Third', true);
+ const repairedNodes = [f.fileNode, f.classNode, aOther, aThird, aServiceRun, f.methodNodes[1], restoredOther];
+ const repairedEdges = [contains(f.classNode, aServiceRun), contains(f.classNode, f.methodNodes[1]), contains(aOther, restoredOther)];
+ if (renameAgain) {
+ repairedNodes.push(thirdRun);
+ repairedEdges.push(contains(aThird, thirdRun));
+ }
+ for (const batch of retry.batches) f.write(`batch-${batch.batchIndex}.json`, { nodes: repairedNodes, edges: repairedEdges });
+ run(python, [mergeScript, f.root], f.root);
+ run(process.execPath, [finalizeScript, f.root], f.root);
+ expect(JSON.parse(f.persisted()[0]).edges.filter(edge => edge.type === 'calls')).toEqual([
+ { source: bOtherRun.id, target: restoredOther.id, type: 'calls', direction: 'forward', weight: 0.8 },
+ ]);
+ });
+
it('blocks owner substitution behind an unchanged generic method ID in merge and finalize', () => {
const otherSource = 'export class Other { method0() { return 2; } }\n';
const f = symbolFixture(2, {
@@ -369,8 +431,9 @@ describe('incremental symbol publication gate', { timeout: 30_000 }, () => {
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(true);
- expect(retained.edges.some(edge => edge.source === otherFunction.id && edge.target === initialMethod.id)).toBe(true);
+ expect(retained.edges.some(edge => edge.target === obsolete.id)).toBe(false);
+ expect(retained.edges.some(edge => edge.source === otherFunction.id && edge.target === initialMethod.id)).toBe(false);
+ expect(retry.inboundEdgeCandidates.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`, {
@@ -389,7 +452,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').idReplacements).toContainEqual({
+ expect(f.read('incremental-symbol-report.json').currentIdBindings).toContainEqual({
oldId: initialMethod.id, newId: repairedMethods[0].id,
});
// Finalize must reconcile independently if its candidate loses the
@@ -411,6 +474,7 @@ describe('incremental symbol publication gate', { timeout: 30_000 }, () => {
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(f.read('incremental-symbol-retry.json')).not.toHaveProperty('currentFiles');
expect(() => f.read('incremental-edge-candidates.json')).toThrow();
expect(spawnSync(process.execPath, [retryScript, f.root]).status).toBe(1);
expect(f.persisted()).toEqual(before);
diff --git a/understand-anything-plugin/hooks/auto-update-prompt.md b/understand-anything-plugin/hooks/auto-update-prompt.md
index 475b0552..f69fb045 100644
--- a/understand-anything-plugin/hooks/auto-update-prompt.md
+++ b/understand-anything-plugin/hooks/auto-update-prompt.md
@@ -67,6 +67,8 @@ Merge runs `validate-incremental-symbols.mjs`, comparing the preserved old symbo
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.
+Current endpoint descriptors take precedence over baseline aliases when IDs are reused. Repair defers incoming edges outside the retained batch until their original HEAD identities are matched, preventing a reused ID from attaching an old current-analysis reference to a different symbol.
+
If the report has `unresolvedFiles`, prepare one targeted symbol retry:
```bash
diff --git a/understand-anything-plugin/skills/understand/SKILL.md b/understand-anything-plugin/skills/understand/SKILL.md
index e7fbcf75..10b68af1 100644
--- a/understand-anything-plugin/skills/understand/SKILL.md
+++ b/understand-anything-plugin/skills/understand/SKILL.md
@@ -414,6 +414,8 @@ The merge combines `batch-existing.json` with any fresh batch output. Its import
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.
+Candidate endpoints use the current analysis's node and ownership descriptors before any baseline alias is applied: an ID reused by a different current symbol must keep its current meaning. During repair, incoming edges are deferred outside the ordinary retained batch until those original HEAD descriptors can be matched against replacement nodes, so temporary ID reuse cannot create a false edge during merge.
+
When the report has `unresolvedFiles`, prepare exactly one repair:
```bash
diff --git a/understand-anything-plugin/skills/understand/prepare-incremental.mjs b/understand-anything-plugin/skills/understand/prepare-incremental.mjs
index 2d7d103d..9b8d0c61 100644
--- a/understand-anything-plugin/skills/understand/prepare-incremental.mjs
+++ b/understand-anything-plugin/skills/understand/prepare-incremental.mjs
@@ -694,6 +694,7 @@ async function main() {
// from a discarded batch generation into a fresh prepare run.
delete retry.inboundEdgeCandidates;
delete retry.replacedFiles;
+ delete retry.currentFiles;
atomicWriteJson(retryPath, retry);
}
diff --git a/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjs b/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjs
index 6468e8a9..bed832d8 100644
--- a/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjs
+++ b/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjs
@@ -75,6 +75,7 @@ async function main() {
const removedIds = new Set(assembled.nodes.filter(node => paths.has(normalizePath(node.filePath)))
.map(node => node.id));
const retainedIds = new Set(assembled.nodes.filter(node => !removedIds.has(node.id)).map(node => node.id));
+ const currentNodes = new Map(assembled.nodes.map(node => [node.id, node]));
const previousIds = new Set(baseline.files.filter(file => paths.has(file.filePath))
.flatMap(file => file.nodes.map(node => node.id)));
const targetsAffectedFile = id => removedIds.has(id) || previousIds.has(id)
@@ -82,15 +83,19 @@ async function main() {
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 =>
+ .map(edge => ({ ...edge, source: currentNodes.has(edge.source) ? edge.source : sourceRemap.get(edge.source) ?? edge.source })).filter(edge =>
retainedIds.has(edge.source) && targetsAffectedFile(edge.target));
+ const contextPaths = new Set(paths);
+ for (const edge of inboundEdgeCandidates) {
+ for (const id of [edge.source, edge.target]) {
+ if (currentNodes.has(id)) contextPaths.add(normalizePath(currentNodes.get(id).filePath));
+ }
+ }
const retained = {
nodes: assembled.nodes.filter(node => !removedIds.has(node.id)),
- // Other files are not reanalyzed. Preserve their current inbound edge
- // candidates until replacement nodes exist; merge resolves their endpoints
- // and drops candidates whose targets were actually removed. Only outgoing
- // edges from the affected files need regeneration by the retry analyzer.
- edges: assembled.edges.filter(edge => !removedIds.has(edge.source)),
+ // Defer inbound edges to the descriptor-bound manifest below. Re-merging
+ // their bare IDs here could attach them to different symbols reusing IDs.
+ edges: assembled.edges.filter(edge => retainedIds.has(edge.source) && retainedIds.has(edge.target)),
};
// Persist the attempt BEFORE mutating batches: a crash must not buy another
@@ -100,7 +105,7 @@ async function main() {
version: 1, baseCommit: plan.baseCommit, headCommit: plan.headCommit, attempt: 1,
filesToReanalyze: [...paths], batches,
inboundEdgeCandidates,
- replacedFiles: [...paths].map(filePath => {
+ currentFiles: [...contextPaths].map(filePath => {
const nodes = assembled.nodes.filter(node => normalizePath(node.filePath) === filePath);
const ids = new Set(nodes.map(node => node.id));
return {
diff --git a/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs b/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs
index e5efb60e..7f99f019 100644
--- a/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs
+++ b/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs
@@ -231,20 +231,25 @@ export async function validateIncrementalSymbols(projectRoot, { graph, intermedi
report.graphHash = createHash('sha256').update(JSON.stringify(graph)).digest('hex');
let parser;
const evidenceByPath = new Map();
- const parseRevisions = async path => {
- if (evidenceByPath.has(path)) return evidenceByPath.get(path);
+ const parseHead = async path => {
+ if (evidenceByPath.get(path)?.head) return evidenceByPath.get(path).head;
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),
- };
+ const evidence = { head: parser.analyzeFileStrict(path, headContent) };
evidenceByPath.set(path, evidence);
+ return evidence.head;
+ };
+ const parseRevisions = async path => {
+ await parseHead(path);
+ const evidence = evidenceByPath.get(path);
+ if (!evidence.base) {
+ const oldContent = git(projectRoot, ['show', `${plan.baseCommit}:./${path}`]);
+ evidence.base = parser.analyzeFileStrict(path, oldContent);
+ }
return evidence;
};
const fileGraph = filePath => {
@@ -282,32 +287,56 @@ export async function validateIncrementalSymbols(projectRoot, { graph, intermedi
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 : [])];
+ && Array.isArray(retry.inboundEdgeCandidates);
+ if (hasRetry && !Array.isArray(retry.currentFiles)) throw new Error('Retry endpoint descriptors are missing');
+ const candidates = [
+ ...(currentCandidates?.edges ?? []).map(edge => ({ edge, saved: false })),
+ ...(hasRetry ? retry.inboundEdgeCandidates : []).map(edge => ({ edge, saved: true })),
+ ];
if (candidates.length || hasRetry) {
const ids = new Set(graph.nodes.map(node => node.id));
- // 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)
+ const replacements = new Map(report.files.flatMap(file => file.replacements)
.map(({ oldId, newId }) => [oldId, newId]));
+ const deleted = new Set(report.files.flatMap(file => file.missing.map(node => node.id)));
+ const baselineBindings = new Map(baseline.files.flatMap(file => file.nodes.filter(symbolKind))
+ .map(node => [node.id, deleted.has(node.id) ? null : replacements.get(node.id) ?? node.id]));
+ const currentBindings = 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 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);
- for (const replacement of result.replacements) remap.set(replacement.oldId, replacement.newId);
+ for (const previous of hasRetry ? retry.currentFiles : []) {
+ const current = fileGraph(previous.filePath);
+ const needsEvidence = previous.nodes.some(node => symbolKind(node) && !hasPreservedIdentity(node, previous, current));
+ const evidence = needsEvidence && previous.filePath ? await parseHead(previous.filePath) : undefined;
+ const result = compareFileSymbols(previous, current, evidence, evidence);
+ const missing = new Set(result.missing.map(node => node.id));
+ const aliases = new Map(result.replacements.map(({ oldId, newId }) => [oldId, newId]));
+ for (const node of previous.nodes) {
+ const match = symbolKind(node)
+ ? missing.has(node.id) ? null : aliases.get(node.id) ?? node.id
+ : current.nodes.some(candidate => candidate.id === node.id && candidate.type === node.type && candidate.name === node.name)
+ ? node.id : null;
+ // Even a failed match overrides the old baseline meaning of this
+ // ID. The current analysis may have reused it for another symbol.
+ currentBindings.set(node.id, match);
+ }
}
+ const endpoint = (id, saved) => {
+ if (saved && currentBindings.has(id)) return currentBindings.get(id);
+ if (!saved && ids.has(id)) return id;
+ if (baselineBindings.has(id)) return baselineBindings.get(id);
+ return ids.has(id) ? id : null;
+ };
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.reconciledCurrentEdges = 0;
report.droppedCurrentEdges = [];
- report.idReplacements = [...remap].map(([oldId, newId]) => ({ oldId, newId }));
- for (const candidate of candidates) {
+ report.idReplacements = [...replacements].map(([oldId, newId]) => ({ oldId, newId }));
+ report.currentIdBindings = [...currentBindings].map(([oldId, newId]) => ({ oldId, newId }));
+ for (const { edge: candidate, saved } of candidates) {
const edge = {
...candidate,
- source: remap.get(candidate.source) ?? candidate.source,
- target: remap.get(candidate.target) ?? candidate.target,
+ source: endpoint(candidate.source, saved),
+ target: endpoint(candidate.target, saved),
};
if (!ids.has(edge.source) || !ids.has(edge.target)) {
report.droppedCurrentEdges.push({ source: candidate.source, target: candidate.target, type: candidate.type });