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: merge incremental baseline batch

ZebangChengc18fdfda042f
diff --git a/tests/skill/understand/test_merge_batch_graphs.py b/tests/skill/understand/test_merge_batch_graphs.py
index a5298018..38f3fd28 100644
--- a/tests/skill/understand/test_merge_batch_graphs.py
+++ b/tests/skill/understand/test_merge_batch_graphs.py
@@ -1131,6 +1131,70 @@ class TestMultiPart(unittest.TestCase):
# ── Unrecognized batch filename handling ───────────────────────────────────
+class TestIncrementalBatchExisting(unittest.TestCase):
+ """The documented incremental baseline file must be merged, not dropped."""
+
+ def setUp(self) -> None:
+ import tempfile
+ self.tmp = Path(tempfile.mkdtemp(prefix="ua-mbg-existing-"))
+ self.intermediate = self.tmp / ".understand-anything" / "intermediate"
+ self.intermediate.mkdir(parents=True, exist_ok=True)
+
+ def tearDown(self) -> None:
+ import shutil
+ shutil.rmtree(self.tmp, ignore_errors=True)
+
+ def _write_batch(self, name: str, nodes: list, edges: list) -> None:
+ import json as _j
+ (self.intermediate / name).write_text(
+ _j.dumps({"nodes": nodes, "edges": edges}),
+ encoding="utf-8",
+ )
+
+ def _run_merge(self) -> tuple[int, str, dict]:
+ import subprocess
+ import json as _j
+ result = subprocess.run(
+ [sys.executable, str(_MODULE_PATH), str(self.tmp)],
+ capture_output=True, text=True,
+ )
+ out_path = self.intermediate / "assembled-graph.json"
+ assembled = _j.loads(out_path.read_text(encoding="utf-8")) if out_path.exists() else {}
+ return result.returncode, result.stderr, assembled
+
+ def test_batch_existing_baseline_is_loaded_before_fresh_batches(self) -> None:
+ self._write_batch("batch-existing.json", [
+ _file_node("src/unchanged.ts"),
+ _file_node("src/shared.ts", summary="old baseline summary"),
+ ], [])
+ self._write_batch("batch-1.json", [
+ _file_node("src/new.ts"),
+ _file_node("src/shared.ts", summary="fresh summary"),
+ ], [
+ {
+ "source": "file:src/new.ts",
+ "target": "file:src/shared.ts",
+ "type": "imports",
+ "direction": "forward",
+ "weight": 0.7,
+ }
+ ])
+
+ rc, stderr, assembled = self._run_merge()
+
+ self.assertEqual(rc, 0)
+ self.assertNotIn("unrecognized filenames", stderr)
+ self.assertIn("batch-existing.json: 2 nodes, 0 edges", stderr)
+ node_by_id = {n["id"]: n for n in assembled["nodes"]}
+ self.assertEqual(
+ set(node_by_id),
+ {"file:src/unchanged.ts", "file:src/shared.ts", "file:src/new.ts"},
+ )
+ self.assertEqual(node_by_id["file:src/shared.ts"]["summary"], "fresh summary")
+ edge_keys = {(e["source"], e["target"], e["type"]) for e in assembled["edges"]}
+ self.assertIn(("file:src/new.ts", "file:src/shared.ts", "imports"), edge_keys)
+
+
class TestUnrecognizedBatchFilename(unittest.TestCase):
"""File-analyzer fuses multiple batches into one output (e.g.,
`batch-fused-8-13.json`, `batch-8-13.json`) — the merge script's regex
diff --git a/understand-anything-plugin/skills/understand/merge-batch-graphs.py b/understand-anything-plugin/skills/understand/merge-batch-graphs.py
index 26f10e27..6b5ef070 100644
--- a/understand-anything-plugin/skills/understand/merge-batch-graphs.py
+++ b/understand-anything-plugin/skills/understand/merge-batch-graphs.py
@@ -135,6 +135,30 @@ def _num(v: Any) -> float:
return 0.0
+def parse_batch_filename(name: str) -> tuple[int, int | None] | None:
+ """Return the logical batch index and optional part number for a batch file.
+
+ Incremental updates write the pruned baseline graph as `batch-existing.json`;
+ treat it as a real batch that sorts before freshly analyzed numeric batches.
+ """
+ if name == "batch-existing.json":
+ return (-1, None)
+
+ match = re.match(r"batch-(\d+)(?:-part-(\d+))?\.json", name)
+ if match is None:
+ return None
+ return (int(match.group(1)), int(match.group(2)) if match.group(2) else None)
+
+
+def batch_sort_key(path: Path) -> tuple[int, int, str]:
+ parsed = parse_batch_filename(path.name)
+ if parsed is None:
+ return (sys.maxsize, sys.maxsize, path.name)
+
+ batch_index, part_number = parsed
+ return (batch_index, part_number or 0, path.name)
+
+
# ── Batch loading ─────────────────────────────────────────────────────────
def load_batch(path: Path) -> dict[str, Any] | None:
@@ -1037,12 +1061,12 @@ def main() -> None:
print(f"Error: {intermediate_dir} does not exist", file=sys.stderr)
sys.exit(1)
- # Discover batch files, sorted by numeric index (not lexicographic)
+ # Discover batch files, sorted by numeric index (not lexicographic).
+ # `batch-existing.json` is the documented incremental baseline and must
+ # sort before fresh batches so fresh duplicate nodes/edges win later.
batch_files = sorted(
intermediate_dir.glob("batch-*.json"),
- key=lambda p: int(re.search(r"batch-(\d+)", p.stem).group(1))
- if re.search(r"batch-(\d+)", p.stem)
- else 0,
+ key=batch_sort_key,
)
if not batch_files:
print("Error: no batch-*.json files found in intermediate/", file=sys.stderr)
@@ -1050,19 +1074,20 @@ def main() -> None:
# Group by logical batch index so the report distinguishes single-batch
# files from multi-part file-analyzer outputs. Files that don't match the
- # `batch-<N>.json` / `batch-<N>-part-<K>.json` pattern (e.g. fused
- # `batch-fused-8-13.json`, range `batch-8-13.json`) would otherwise be
- # silently dropped during load — flag them loudly instead so the user
- # can fix the file-analyzer agent.
+ # `batch-existing.json` / `batch-<N>.json` / `batch-<N>-part-<K>.json`
+ # pattern (e.g. fused `batch-fused-8-13.json`, range `batch-8-13.json`)
+ # would otherwise be silently dropped during load — flag them loudly
+ # instead so the user can fix the file-analyzer agent.
from collections import defaultdict as _dd
by_batch = _dd(list)
unrecognized_batch_files: list[str] = []
for f in batch_files:
- m = re.match(r"batch-(\d+)(?:-part-(\d+))?\.json", f.name)
- if m:
- by_batch[int(m.group(1))].append((f.name, int(m.group(2)) if m.group(2) else None))
- else:
+ parsed = parse_batch_filename(f.name)
+ if parsed is None:
unrecognized_batch_files.append(f.name)
+ else:
+ batch_index, part_number = parsed
+ by_batch[batch_index].append((f.name, part_number))
if unrecognized_batch_files:
preview = ", ".join(unrecognized_batch_files[:5])