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(merge): warn, persist, and retry dropped structural subdomain edges
Lum1104f71224446e59
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex adaee2bd..968f417d 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -58,4 +58,4 @@ jobs:run: pnpm test- name: Test Python skill helpers- run: python -m unittest tests.skill.understand.test_merge_batch_graphs -v+ run: python -m unittest tests.skill.understand.test_merge_batch_graphs tests.skill.understand.test_merge_subdomain_graphs -vdiff --git a/tests/skill/understand/test_merge_subdomain_graphs.py b/tests/skill/understand/test_merge_subdomain_graphs.pynew file mode 100644index 00000000..174c9c8f--- /dev/null+++ b/tests/skill/understand/test_merge_subdomain_graphs.py@@ -0,0 +1,147 @@+#!/usr/bin/env python3+"""+test_merge_subdomain_graphs.py — Tests for structural-edge drop reporting+and cross-run recovery in merge-subdomain-graphs.py (issue #529).++Run from the repo root:+ python -m unittest tests.skill.understand.test_merge_subdomain_graphs -v+"""++from __future__ import annotations++import importlib.util+import json+import sys+import tempfile+import unittest+from pathlib import Path+from typing import Any+++# ── Module loader ─────────────────────────────────────────────────────────+# `merge-subdomain-graphs.py` has hyphens in its name, so we cannot `import`+# it directly. Load it via importlib so we can call its module-level helpers.++_HERE = Path(__file__).resolve().parent+_REPO_ROOT = _HERE.parent.parent.parent+_MODULE_PATH = (+ _REPO_ROOT+ / "understand-anything-plugin"+ / "skills"+ / "understand"+ / "merge-subdomain-graphs.py"+)+++def _load_module() -> Any:+ spec = importlib.util.spec_from_file_location("merge_subdomain_graphs", _MODULE_PATH)+ if spec is None or spec.loader is None:+ raise RuntimeError(f"Could not load module from {_MODULE_PATH}")+ module = importlib.util.module_from_spec(spec)+ sys.modules["merge_subdomain_graphs"] = module+ spec.loader.exec_module(module)+ return module+++msg = _load_module()+++# ── Helpers ───────────────────────────────────────────────────────────────++def _node(nid: str) -> dict[str, Any]:+ return {+ "id": nid,+ "type": "domain",+ "name": nid,+ "summary": "",+ "tags": [],+ "complexity": "simple",+ }+++def _edge(src: str, tgt: str, etype: str) -> dict[str, Any]:+ return {"source": src, "target": tgt, "type": etype, "direction": "forward", "weight": 0.8}+++def _graph(nodes: list[dict], edges: list[dict]) -> dict[str, Any]:+ return {"nodes": nodes, "edges": edges, "layers": [], "tour": [], "project": {}}+++# ── Tests ─────────────────────────────────────────────────────────────────++class TestStructuralEdgeDrops(unittest.TestCase):+ def test_structural_drop_emits_warning_and_is_recorded(self) -> None:+ g = _graph([_node("domain:auth")], [_edge("domain:auth", "flow:login", "contains_flow")])+ merged, report, dropped = msg.merge_graphs([g])++ self.assertEqual(merged["edges"], [])+ self.assertEqual(len(dropped), 1)+ self.assertEqual(dropped[0]["type"], "contains_flow")+ self.assertIn("target 'flow:login'", dropped[0]["missing"][0])+ warnings = [line for line in report if line.startswith("Warning: dropped structural edge")]+ self.assertEqual(len(warnings), 1)+ self.assertIn("contains_flow", warnings[0])++ def test_non_structural_drop_stays_in_could_not_fix(self) -> None:+ g = _graph([_node("domain:auth")], [_edge("domain:auth", "file:gone.py", "related")])+ merged, report, dropped = msg.merge_graphs([g])++ self.assertEqual(len(dropped), 1)+ self.assertFalse(any(line.startswith("Warning: dropped structural edge") for line in report))+ self.assertTrue(any("Could not fix" in line for line in report))++ def test_valid_edges_are_untouched(self) -> None:+ g = _graph(+ [_node("domain:auth"), _node("flow:login")],+ [_edge("domain:auth", "flow:login", "contains_flow")],+ )+ merged, _report, dropped = msg.merge_graphs([g])+ self.assertEqual(len(merged["edges"]), 1)+ self.assertEqual(dropped, [])+++class TestCrossRunRecovery(unittest.TestCase):+ def test_dropped_structural_edge_recovers_when_endpoint_arrives(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ report_path = Path(tmp) / "merge-report.json"++ # Run 1: cross_domain edge whose target subdomain doesn't exist yet.+ g1 = _graph([_node("domain:auth")], [_edge("domain:auth", "domain:billing", "cross_domain")])+ merged1, _r1, dropped1 = msg.merge_graphs([g1])+ msg.write_merge_report(report_path, merged1, dropped1, 0)++ # Run 2: the billing subdomain graph has arrived; the pending edge+ # is re-injected exactly the way main() does it.+ pending = msg.load_pending_structural_edges(report_path)+ self.assertEqual(len(pending), 1)+ self.assertNotIn("missing", pending[0])++ g2 = _graph([_node("domain:auth"), _node("domain:billing")], [])+ merged2, _r2, dropped2 = msg.merge_graphs([g2, {"nodes": [], "edges": pending}])++ self.assertEqual(dropped2, [])+ self.assertEqual(len(merged2["edges"]), 1)+ self.assertEqual(merged2["edges"][0]["type"], "cross_domain")++ def test_non_structural_dropped_edges_are_not_retried(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ report_path = Path(tmp) / "merge-report.json"+ g = _graph([_node("domain:auth")], [_edge("domain:auth", "file:gone.py", "related")])+ merged, _report, dropped = msg.merge_graphs([g])+ msg.write_merge_report(report_path, merged, dropped, 0)++ # The related edge is persisted for investigation but not re-injected.+ data = json.loads(report_path.read_text(encoding="utf-8"))+ self.assertEqual(len(data["droppedEdges"]), 1)+ self.assertEqual(msg.load_pending_structural_edges(report_path), [])++ def test_missing_or_corrupt_report_yields_no_pending(self) -> None:+ with tempfile.TemporaryDirectory() as tmp:+ missing = Path(tmp) / "merge-report.json"+ self.assertEqual(msg.load_pending_structural_edges(missing), [])+ missing.write_text("{not json", encoding="utf-8")+ self.assertEqual(msg.load_pending_structural_edges(missing), [])+++if __name__ == "__main__":+ unittest.main()diff --git a/understand-anything-plugin/skills/understand/merge-subdomain-graphs.py b/understand-anything-plugin/skills/understand/merge-subdomain-graphs.pyindex 4b82ef0e..f166a4ae 100644--- a/understand-anything-plugin/skills/understand/merge-subdomain-graphs.py+++ b/understand-anything-plugin/skills/understand/merge-subdomain-graphs.py@@ -24,6 +24,13 @@ from collections import Counterfrom pathlib import Pathfrom typing import Any+# Edge types that carry the domain hierarchy. Dropping one of these changes+# downstream graph traversal (unlike a routine `related` edge), so they are+# warned about loudly and re-tried on later runs via merge-report.json —+# subdomain graph files are cleaned up after assembly, so a drop would+# otherwise be permanent even once the missing endpoint's subdomain arrives.+STRUCTURAL_EDGE_TYPES = {"contains_flow", "flow_step", "cross_domain"}+def _num(v: Any) -> float:"""Coerce a value to float for safe comparison (handles string weights)."""@@ -49,8 +56,13 @@ def load_graph(path: Path) -> dict[str, Any] | None:return data-def merge_graphs(graphs: list[dict[str, Any]]) -> tuple[dict[str, Any], list[str]]:- """Merge multiple knowledge graph dicts into one. Returns (merged, report_lines)."""+def merge_graphs(graphs: list[dict[str, Any]]) -> tuple[dict[str, Any], list[str], list[dict[str, Any]]]:+ """Merge multiple knowledge graph dicts into one.++ Returns (merged, report_lines, dropped_edges) — dropped_edges holds the+ full edge dicts that were removed for missing endpoints, each with an+ extra "missing" key naming which endpoint(s) were absent.+ """# ── Pattern counters for "Fixed" report ──────────────────────────node_dedup_by_type: Counter[str] = Counter()@@ -91,6 +103,8 @@ def merge_graphs(graphs: list[dict[str, Any]]) -> tuple[dict[str, Any], list[str# Drop edges referencing missing nodesnode_ids = set(nodes_by_id.keys())valid_edges: list[dict] = []+ dropped_edges: list[dict[str, Any]] = []+ structural_warnings: list[str] = []for e in edges_by_key.values():src, tgt = e.get("source", ""), e.get("target", "")if src in node_ids and tgt in node_ids:@@ -101,7 +115,15 @@ def merge_graphs(graphs: list[dict[str, Any]]) -> tuple[dict[str, Any], list[strmissing.append(f"source '{src}'")if tgt not in node_ids:missing.append(f"target '{tgt}'")- unfixable.append(f"Edge {src} → {tgt} ({e.get('type', '?')}): dropped, missing {', '.join(missing)}")+ etype = e.get("type", "?")+ dropped_edges.append({**e, "missing": missing})+ if etype in STRUCTURAL_EDGE_TYPES:+ structural_warnings.append(+ f"Warning: dropped structural edge {src} → {tgt} ({etype}), "+ f"missing {', '.join(missing)} — will retry on the next merge run"+ )+ else:+ unfixable.append(f"Edge {src} → {tgt} ({etype}): dropped, missing {', '.join(missing)}")# ── Layers: merge by id, union nodeIds ────────────────────────────layers_by_id: dict[str, dict] = {}@@ -202,6 +224,12 @@ def merge_graphs(graphs: list[dict[str, Any]]) -> tuple[dict[str, Any], list[strreport.append(f"Fixed ({total_fixed} corrections):")report.extend(fixed_lines)+ # Structural drops surface as loud warnings, not buried counters —+ # losing hierarchy/cross-domain edges changes downstream traversal.+ if structural_warnings:+ report.append("")+ report.extend(structural_warnings)+# Could not fix sectionif unfixable:report.append("")@@ -229,7 +257,49 @@ def merge_graphs(graphs: list[dict[str, Any]]) -> tuple[dict[str, Any], list[str"tour": all_tour_steps,}- return merged, report+ return merged, report, dropped_edges+++def load_pending_structural_edges(report_path: Path) -> list[dict[str, Any]]:+ """Read structural edges dropped by a previous run from merge-report.json.++ Subdomain graph files are cleaned up after assembly, so these edges only+ survive in the report — re-injecting them lets a later run resolve them+ once the missing endpoint's subdomain graph has been merged.+ """+ if not report_path.exists():+ return []+ try:+ data = json.loads(report_path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as e:+ print(f"Warning: could not read {report_path.name}: {e}", file=sys.stderr)+ return []+ pending = []+ for entry in data.get("droppedEdges", []):+ if isinstance(entry, dict) and entry.get("type") in STRUCTURAL_EDGE_TYPES:+ pending.append({k: v for k, v in entry.items() if k != "missing"})+ return pending+++def write_merge_report(+ report_path: Path,+ merged: dict[str, Any],+ dropped_edges: list[dict[str, Any]],+ recovered_count: int,+) -> None:+ """Persist the dropped-edge report so investigations don't require re-instrumenting the script."""+ report = {+ "generatedBy": "merge-subdomain-graphs.py",+ "output": {+ "nodes": len(merged.get("nodes", [])),+ "edges": len(merged.get("edges", [])),+ "layers": len(merged.get("layers", [])),+ "tourSteps": len(merged.get("tour", [])),+ },+ "recoveredStructuralEdges": recovered_count,+ "droppedEdges": dropped_edges,+ }+ report_path.write_text(json.dumps(report, indent=2, ensure_ascii=False), encoding="utf-8")def main() -> None:@@ -289,16 +359,35 @@ def main() -> None:print(f" Loaded base knowledge-graph.json: {node_count} nodes, {edge_count} edges", file=sys.stderr)graphs.insert(0, base) # Base first — subdomain data wins on conflict+ # Re-inject structural edges a previous run had to drop; if their missing+ # endpoints have arrived in the meantime, this run resolves them.+ report_path = ua_dir / "merge-report.json"+ pending_edges = load_pending_structural_edges(report_path)+ if pending_edges:+ print(f" Retrying {len(pending_edges)} structural edges dropped by a previous run", file=sys.stderr)+ graphs.append({"nodes": [], "edges": pending_edges})+# Merge- merged, report = merge_graphs(graphs)+ merged, report, dropped_edges = merge_graphs(graphs)# Print reportprint("", file=sys.stderr)for line in report:print(line, file=sys.stderr)+ # Count how many previously-dropped structural edges made it in this time+ merged_edge_keys = {(e.get("source", ""), e.get("target", ""), e.get("type", "")) for e in merged["edges"]}+ recovered = sum(+ 1 for e in pending_edges+ if (e.get("source", ""), e.get("target", ""), e.get("type", "")) in merged_edge_keys+ )+ if recovered:+ print(f"Recovered {recovered} structural edges dropped by a previous run", file=sys.stderr)+# Write outputoutput_path.write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8")+ write_merge_report(report_path, merged, dropped_edges, recovered)+ print(f"Merge report written to {report_path}", file=sys.stderr)size_kb = output_path.stat().st_size / 1024print(f"\nWritten to {output_path} ({size_kb:.0f} KB)", file=sys.stderr)