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): retain fresh edges before dangling-target cleanup
Lum1104562dd6eccfd8
diff --git a/tests/skill/understand/test_merge_batch_graphs.py b/tests/skill/understand/test_merge_batch_graphs.pyindex 1dcd39e3..f1eca691 100644--- a/tests/skill/understand/test_merge_batch_graphs.py+++ b/tests/skill/understand/test_merge_batch_graphs.py@@ -1445,5 +1445,27 @@ class TestUaDirResolution(unittest.TestCase):self.assertFalse((self.tmp / ".ua" / "intermediate" / "assembled-graph.json").exists())+class TestIncrementalEdgeCandidates(unittest.TestCase):+ def test_preserves_only_current_normalized_dangling_targets(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 = [+ {"source": source["id"], "target": "function:src/a.ts:lost", "type": "calls", "direction": "both", "weight": 0.6},+ {"source": source["id"], "target": "function:src/a.ts:lost", "type": "calls", "direction": "both", "weight": 0.9},+ {"source": "missing", "target": "function:src/a.ts:lost", "type": "calls"},+ ]+ candidates: list[dict[str, Any]] = []+ assembled, _report = mbg.merge_and_normalize(+ [{"nodes": [source], "edges": [old_edge]}, {"nodes": [], "edges": fresh_edges}],+ current_edge_ids={id(edge) for edge in fresh_edges},+ dangling_candidates=candidates,+ )+ self.assertEqual(assembled["edges"], [])+ self.assertEqual(candidates, [{+ "source": "file:src/b.ts", "target": "function:src/a.ts:lost", "type": "calls",+ "direction": "bidirectional", "weight": 0.9,+ }])++if __name__ == "__main__":unittest.main()diff --git a/tests/skill/understand/test_prepare_incremental.test.mjs b/tests/skill/understand/test_prepare_incremental.test.mjsindex 123854cd..715dcf0b 100644--- a/tests/skill/understand/test_prepare_incremental.test.mjs+++ b/tests/skill/understand/test_prepare_incremental.test.mjs@@ -285,9 +285,15 @@ describe('incremental symbol publication gate', { timeout: 30_000 }, () => {{ 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: initialMethod.id, type: 'calls', direction: 'forward', weight: 0.8 },+ { source: otherFunction.id, target: f.methodNodes[1].id, type: 'calls', direction: 'forward', weight: 0.6 },+ { source: otherFunction.id, target: f.methodNodes[1].id, type: 'calls', direction: 'forward', weight: 0.9 },{ source: initialMethod.id, target: otherFunction.id, type: 'calls', direction: 'forward', weight: 0.5 },] });expect(spawnSync(python, [mergeScript, f.root]).status).toBe(1);+ expect(f.read('assembled-graph.json').edges.some(edge => edge.target === f.methodNodes[1].id)).toBe(false);+ expect(f.read('incremental-edge-candidates.json').edges).toContainEqual(expect.objectContaining({+ source: otherFunction.id, target: f.methodNodes[1].id, weight: 0.9,+ }));run(process.execPath, [retryScript, f.root], f.root);const retry = f.read('incremental-symbol-retry.json');expect(retry.filesToReanalyze).toEqual(['src/a.ts']);@@ -318,6 +324,7 @@ describe('incremental symbol publication gate', { timeout: 30_000 }, () => {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 === 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({oldId: initialMethod.id, newId: repairedMethods[0].id,@@ -341,6 +348,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-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.mdindex 90aa04cb..6a19ec31 100644--- a/understand-anything-plugin/hooks/auto-update-prompt.md+++ b/understand-anything-plugin/hooks/auto-update-prompt.md@@ -65,6 +65,8 @@ 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.+If the report has `unresolvedFiles`, prepare one targeted symbol retry:```bashdiff --git a/understand-anything-plugin/skills/understand/SKILL.md b/understand-anything-plugin/skills/understand/SKILL.mdindex 79e3c2f7..a76d60dc 100644--- a/understand-anything-plugin/skills/understand/SKILL.md+++ b/understand-anything-plugin/skills/understand/SKILL.md@@ -412,6 +412,8 @@ 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.+When the report has `unresolvedFiles`, prepare exactly one repair:```bashdiff --git a/understand-anything-plugin/skills/understand/merge-batch-graphs.py b/understand-anything-plugin/skills/understand/merge-batch-graphs.pyindex 67d1b121..5a8614b1 100644--- a/understand-anything-plugin/skills/understand/merge-batch-graphs.py+++ b/understand-anything-plugin/skills/understand/merge-batch-graphs.py@@ -782,7 +782,12 @@ def link_tests(# ── Main merge + normalize ────────────────────────────────────────────────-def merge_and_normalize(batches: list[dict[str, Any]]) -> tuple[dict[str, Any], list[str]]:+def merge_and_normalize(+ batches: list[dict[str, Any]],+ *,+ current_edge_ids: set[int] | None = None,+ dangling_candidates: list[dict[str, Any]] | None = None,+) -> tuple[dict[str, Any], list[str]]:"""Merge batch results and normalize. Returns (assembled_graph, report_lines)."""# ── Pattern counters for "Fixed" report ──────────────────────────@@ -875,14 +880,28 @@ def merge_and_normalize(batches: list[dict[str, Any]]) -> tuple[dict[str, Any],# overwrite a `bidirectional` one (or vice versa); they're different# semantic relationships that the dashboard renders distinctly.edges_by_key: dict[tuple[str, str, str, str], dict] = {}+ dangling_by_key: dict[tuple[str, str, str, str], dict] = {}for edge in all_edges:src = edge.get("source", "")tgt = edge.get("target", "")etype = edge.get("type", "")direction = normalize_direction(edge.get("direction"))edge["direction"] = direction+ 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.+ if (+ dangling_candidates is not None+ and current_edge_ids is not None+ and 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)):+ dangling_by_key[key] = dict(edge)missing = []if src not in node_ids:missing.append(f"source '{src}'")@@ -891,11 +910,13 @@ def merge_and_normalize(batches: list[dict[str, Any]]) -> tuple[dict[str, Any],unfixable.append(f"Edge {src} → {tgt} ({etype}): dropped, missing {', '.join(missing)}")continue- key = (src, tgt, etype, direction)existing = edges_by_key.get(key)if existing is None or _num(edge.get("weight", 0)) > _num(existing.get("weight", 0)):edges_by_key[key] = edge+ if dangling_candidates is not None:+ dangling_candidates.extend(dangling_by_key.values())+# ── Build report ─────────────────────────────────────────────────report: list[str] = []report.append(f"Input: {total_input_nodes} nodes, {total_input_edges} edges")@@ -1116,6 +1137,9 @@ def main() -> None:project_root = Path(sys.argv[1]).resolve()intermediate_dir = resolve_ua_dir(project_root) / "intermediate"+ plan_path = intermediate_dir / "incremental-plan.json"+ plan = json.loads(plan_path.read_text(encoding="utf-8")) if plan_path.exists() else {}+ incremental = plan.get("action") in ("PARTIAL_UPDATE", "ARCHITECTURE_UPDATE")if not intermediate_dir.is_dir():print(f"Error: {intermediate_dir} does not exist", file=sys.stderr)@@ -1198,6 +1222,7 @@ def main() -> None:# merged graph with content the agent labeled incorrectly.unrecognized_set = set(unrecognized_batch_files)batches: list[dict[str, Any]] = []+ current_edge_ids: set[int] = set()empty_batch_warnings: list[str] = []for f in batch_files:if f.name in unrecognized_set:@@ -1205,6 +1230,8 @@ def main() -> None:batch = load_batch(f)if batch is not None:batches.append(batch)+ if incremental and f.name != "batch-existing.json":+ current_edge_ids.update(id(edge) for edge in batch.get("edges", []))n = len(batch.get("nodes", []))e = len(batch.get("edges", []))print(f" {f.name}: {n} nodes, {e} edges", file=sys.stderr)@@ -1225,7 +1252,11 @@ def main() -> None:sys.exit(1)# Merge and normalize- assembled, report = merge_and_normalize(batches)+ dangling_candidates: list[dict[str, Any]] = []+ assembled, report = merge_and_normalize(+ batches, current_edge_ids=current_edge_ids if incremental else None,+ dangling_candidates=dangling_candidates if incremental else None,+ )# Surface missing multi-part files to the phase report (parallel to# unrecognized-filename handling below). Stderr lines emitted during@@ -1299,6 +1330,14 @@ def main() -> None:if plan_path.exists():plan = json.loads(plan_path.read_text(encoding="utf-8"))if plan.get("action") in ("PARTIAL_UPDATE", "ARCHITECTURE_UPDATE"):+ candidate_path = intermediate_dir / "incremental-edge-candidates.json"+ candidate_temp = candidate_path.with_name(f"{candidate_path.name}.tmp-{os.getpid()}")+ candidate_temp.write_text(json.dumps({+ "baseCommit": plan["baseCommit"],+ "headCommit": plan["headCommit"],+ "edges": dangling_candidates,+ }, indent=2, ensure_ascii=False), encoding="utf-8")+ candidate_temp.replace(candidate_path)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:diff --git a/understand-anything-plugin/skills/understand/prepare-incremental.mjs b/understand-anything-plugin/skills/understand/prepare-incremental.mjsindex 0595057c..2d7d103d 100644--- a/understand-anything-plugin/skills/understand/prepare-incremental.mjs+++ b/understand-anything-plugin/skills/understand/prepare-incremental.mjs@@ -124,6 +124,7 @@ function clearIncrementalScratch(intermediateDir) {'layers.json','tour.json','incremental-symbol-report.json',+ 'incremental-edge-candidates.json',]);for (const name of readdirSync(intermediateDir)) {if (exactNames.has(name) || /^batch-\d+(?:-part-\d+)?\.json$/.test(name)) {diff --git a/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjs b/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjsindex 4c3a0c5a..01dcce15 100644--- a/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjs+++ b/understand-anything-plugin/skills/understand/prepare-symbol-retry.mjs@@ -69,8 +69,18 @@ async function main() {batch.missingSymbols = report.files.filter(file => files.has(file.filePath));}const assembled = readJson(join(intermediateDir, 'assembled-graph.json'));+ const candidates = readJson(join(intermediateDir, 'incremental-edge-candidates.json'));+ if (candidates.baseCommit !== plan.baseCommit || candidates.headCommit !== plan.headCommit+ || !Array.isArray(candidates.edges)) throw new Error('Current edge candidates do not match the incremental plan; rerun merge');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 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)+ || (typeof id === 'string' && [...paths].some(path => id.includes(`:${path}:`)));+ const inboundEdgeCandidates = [...assembled.edges, ...candidates.edges].filter(edge =>+ retainedIds.has(edge.source) && targetsAffectedFile(edge.target));const retained = {nodes: assembled.nodes.filter(node => !removedIds.has(node.id)),// Other files are not reanalyzed. Preserve their current inbound edge@@ -86,7 +96,7 @@ 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)),+ inboundEdgeCandidates,replacedFiles: [...paths].map(filePath => {const nodes = assembled.nodes.filter(node => normalizePath(node.filePath) === filePath);const ids = new Set(nodes.map(node => node.id));diff --git a/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs b/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjsindex 9bdeb549..ffc44b74 100644--- a/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs+++ b/understand-anything-plugin/skills/understand/validate-incremental-symbols.mjs@@ -254,7 +254,10 @@ export async function validateIncrementalSymbols(projectRoot, { graph, intermediif (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();+ // A target omitted in the initial merge has no current node 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) {@@ -263,8 +266,8 @@ export async function validateIncrementalSymbols(projectRoot, { graph, intermediconst 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));+ 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 }));@@ -272,10 +275,16 @@ export async function validateIncrementalSymbols(projectRoot, { graph, intermediconst 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++;+ } else {+ const index = existing.get(edgeKey(edge));+ if (index === undefined) {+ existing.set(edgeKey(edge), graph.edges.length);+ graph.edges.push(edge);+ report.reconciledRetryEdges++;+ } else if (Number(edge.weight) > Number(graph.edges[index].weight)) {+ graph.edges[index] = edge;+ report.reconciledRetryEdges++;+ }}}// Merge's earlier dangling-edge cleanup cannot see semantic ID aliases.