ckgraphify 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
graphify/analyze.py ADDED
@@ -0,0 +1,575 @@
1
+ """Graph analysis: god nodes (most connected), surprising connections (cross-community), suggested questions."""
2
+ from __future__ import annotations
3
+ from pathlib import Path
4
+ import networkx as nx
5
+
6
+ from graphify.build import edge_data
7
+
8
+ # Language families — extensions sharing a runtime can legitimately call each other
9
+ _LANG_FAMILY: dict[str, str] = {
10
+ **{e: "python" for e in (".py", ".pyw")},
11
+ **{e: "js" for e in (".js", ".jsx", ".mjs", ".ejs", ".ts", ".tsx", ".vue", ".svelte")},
12
+ **{e: "go" for e in (".go",)},
13
+ **{e: "rust" for e in (".rs",)},
14
+ **{e: "jvm" for e in (".java", ".kt", ".kts", ".scala")},
15
+ **{e: "c" for e in (".c", ".h", ".cpp", ".cc", ".cxx", ".hpp")},
16
+ **{e: "ruby" for e in (".rb",)},
17
+ **{e: "swift" for e in (".swift",)},
18
+ **{e: "dotnet" for e in (".cs",)},
19
+ **{e: "php" for e in (".php",)},
20
+ **{e: "r" for e in (".r",)},
21
+ }
22
+
23
+
24
+ def _cross_language(src_a: str, src_b: str) -> bool:
25
+ """Return True if two source files belong to different language families."""
26
+ ext_a = Path(src_a).suffix.lower()
27
+ ext_b = Path(src_b).suffix.lower()
28
+ fam_a = _LANG_FAMILY.get(ext_a)
29
+ fam_b = _LANG_FAMILY.get(ext_b)
30
+ if fam_a is None or fam_b is None:
31
+ return False
32
+ return fam_a != fam_b
33
+
34
+
35
+ def _node_community_map(communities: dict[int, list[str]]) -> dict[str, int]:
36
+ """Invert communities dict: node_id -> community_id."""
37
+ return {n: cid for cid, nodes in communities.items() for n in nodes}
38
+
39
+
40
+ def _is_file_node(G: nx.Graph, node_id: str) -> bool:
41
+ """
42
+ Return True if this node is a file-level hub node (e.g. 'client', 'models')
43
+ or an AST method stub (e.g. '.auth_flow()', '.__init__()').
44
+
45
+ These are synthetic nodes created by the AST extractor and should be excluded
46
+ from god nodes, surprising connections, and knowledge gap reporting.
47
+ """
48
+ attrs = G.nodes[node_id]
49
+ label = attrs.get("label", "")
50
+ if not label:
51
+ return False
52
+ # File-level hub: label matches the actual source filename (not just any label ending in .py)
53
+ source_file = attrs.get("source_file", "")
54
+ if source_file:
55
+ from pathlib import Path as _Path
56
+ if label == _Path(source_file).name:
57
+ return True
58
+ # Method stub: AST extractor labels methods as '.method_name()'
59
+ if label.startswith(".") and label.endswith("()"):
60
+ return True
61
+ # Module-level function stub: labeled 'function_name()' - only has a contains edge
62
+ # These are real functions but structurally isolated by definition; not a gap worth flagging
63
+ if label.endswith("()") and G.degree(node_id) <= 1:
64
+ return True
65
+ return False
66
+
67
+
68
+ def god_nodes(G: nx.Graph, top_n: int = 10) -> list[dict]:
69
+ """Return the top_n most-connected real entities - the core abstractions.
70
+
71
+ File-level hub nodes are excluded: they accumulate import/contains edges
72
+ mechanically and don't represent meaningful architectural abstractions.
73
+ """
74
+ degree = dict(G.degree())
75
+ sorted_nodes = sorted(degree.items(), key=lambda x: x[1], reverse=True)
76
+ result = []
77
+ for node_id, deg in sorted_nodes:
78
+ if _is_file_node(G, node_id) or _is_concept_node(G, node_id):
79
+ continue
80
+ result.append({
81
+ "id": node_id,
82
+ "label": G.nodes[node_id].get("label", node_id),
83
+ "degree": deg,
84
+ })
85
+ if len(result) >= top_n:
86
+ break
87
+ return result
88
+
89
+
90
+ def surprising_connections(
91
+ G: nx.Graph,
92
+ communities: dict[int, list[str]] | None = None,
93
+ top_n: int = 5,
94
+ ) -> list[dict]:
95
+ """
96
+ Find connections that are genuinely surprising - not obvious from file structure.
97
+
98
+ Strategy:
99
+ - Multi-file corpora: cross-file edges between real entities (not concept nodes).
100
+ Sorted AMBIGUOUS → INFERRED → EXTRACTED.
101
+ - Single-file / single-source corpora: cross-community edges that bridge
102
+ distant parts of the graph (betweenness centrality on edges).
103
+ These reveal non-obvious structural couplings.
104
+
105
+ Concept nodes (empty source_file, or injected semantic annotations) are excluded
106
+ from surprising connections because they are intentional, not discovered.
107
+ """
108
+ # Identify unique source files (ignore empty/null source_file)
109
+ source_files = {
110
+ data.get("source_file", "")
111
+ for _, data in G.nodes(data=True)
112
+ if data.get("source_file", "")
113
+ }
114
+ is_multi_source = len(source_files) > 1
115
+
116
+ if is_multi_source:
117
+ return _cross_file_surprises(G, communities or {}, top_n)
118
+ else:
119
+ return _cross_community_surprises(G, communities or {}, top_n)
120
+
121
+
122
+ def _is_concept_node(G: nx.Graph, node_id: str) -> bool:
123
+ """
124
+ Return True if this node is a manually-injected semantic concept node
125
+ rather than a real entity found in source code.
126
+
127
+ Signals:
128
+ - Empty source_file
129
+ - source_file doesn't look like a real file path (no extension)
130
+ """
131
+ data = G.nodes[node_id]
132
+ source = data.get("source_file", "")
133
+ if not source:
134
+ return True
135
+ # Has no file extension → probably a concept label, not a real file
136
+ if "." not in source.split("/")[-1]:
137
+ return True
138
+ return False
139
+
140
+
141
+ from graphify.detect import CODE_EXTENSIONS, DOC_EXTENSIONS, PAPER_EXTENSIONS, IMAGE_EXTENSIONS
142
+
143
+
144
+ def _file_category(path: str) -> str:
145
+ ext = ("." + path.rsplit(".", 1)[-1].lower()) if "." in path else ""
146
+ if ext in CODE_EXTENSIONS:
147
+ return "code"
148
+ if ext in PAPER_EXTENSIONS:
149
+ return "paper"
150
+ if ext in IMAGE_EXTENSIONS:
151
+ return "image"
152
+ return "doc"
153
+
154
+
155
+ def _top_level_dir(path: str) -> str:
156
+ """Return the first path component - used to detect cross-repo edges."""
157
+ return path.split("/")[0] if "/" in path else path
158
+
159
+
160
+ def _surprise_score(
161
+ G: nx.Graph,
162
+ u: str,
163
+ v: str,
164
+ data: dict,
165
+ node_community: dict[str, int],
166
+ u_source: str,
167
+ v_source: str,
168
+ ) -> tuple[int, list[str]]:
169
+ """Score how surprising a cross-file edge is. Returns (score, reasons)."""
170
+ score = 0
171
+ reasons: list[str] = []
172
+
173
+ # 1. Confidence weight - uncertain connections are more noteworthy
174
+ conf = data.get("confidence", "EXTRACTED")
175
+ relation = data.get("relation", "")
176
+ conf_bonus = {"AMBIGUOUS": 3, "INFERRED": 2, "EXTRACTED": 1}.get(conf, 1)
177
+
178
+ # Cross-language INFERRED calls are likely resolver pollution, not real surprises
179
+ if conf == "INFERRED" and relation == "calls" and _cross_language(u_source, v_source):
180
+ conf_bonus = 0 # downgrade: don't promote likely false positives
181
+
182
+ score += conf_bonus
183
+ if conf in ("AMBIGUOUS", "INFERRED"):
184
+ reasons.append(f"{conf.lower()} connection - not explicitly stated in source")
185
+
186
+ # 2. Cross file-type bonus - code↔paper or code↔image is non-obvious
187
+ cat_u = _file_category(u_source)
188
+ cat_v = _file_category(v_source)
189
+ if cat_u != cat_v:
190
+ score += 2
191
+ reasons.append(f"crosses file types ({cat_u} ↔ {cat_v})")
192
+
193
+ # 3. Cross-repo bonus - different top-level directory
194
+ if _top_level_dir(u_source) != _top_level_dir(v_source):
195
+ score += 2
196
+ reasons.append("connects across different repos/directories")
197
+
198
+ # 4. Cross-community bonus - Leiden says these are structurally distant
199
+ cid_u = node_community.get(u)
200
+ cid_v = node_community.get(v)
201
+ if cid_u is not None and cid_v is not None and cid_u != cid_v:
202
+ score += 1
203
+ reasons.append("bridges separate communities")
204
+
205
+ # 4b. Semantic similarity bonus - non-obvious conceptual links score higher
206
+ if data.get("relation") == "semantically_similar_to":
207
+ score = int(score * 1.5)
208
+ reasons.append("semantically similar concepts with no structural link")
209
+
210
+ # 5. Peripheral→hub: a low-degree node connecting to a high-degree one
211
+ deg_u = G.degree(u)
212
+ deg_v = G.degree(v)
213
+ if min(deg_u, deg_v) <= 2 and max(deg_u, deg_v) >= 5:
214
+ score += 1
215
+ peripheral = G.nodes[u].get("label", u) if deg_u <= 2 else G.nodes[v].get("label", v)
216
+ hub = G.nodes[v].get("label", v) if deg_u <= 2 else G.nodes[u].get("label", u)
217
+ reasons.append(f"peripheral node `{peripheral}` unexpectedly reaches hub `{hub}`")
218
+
219
+ return score, reasons
220
+
221
+
222
+ def _cross_file_surprises(G: nx.Graph, communities: dict[int, list[str]], top_n: int) -> list[dict]:
223
+ """
224
+ Cross-file edges between real code/doc entities, ranked by a composite
225
+ surprise score rather than confidence alone.
226
+
227
+ Surprise score accounts for:
228
+ - Confidence (AMBIGUOUS > INFERRED > EXTRACTED)
229
+ - Cross file-type (code↔paper is more surprising than code↔code)
230
+ - Cross-repo (different top-level directory)
231
+ - Cross-community (Leiden says structurally distant)
232
+ - Peripheral→hub (low-degree node reaching a god node)
233
+
234
+ Each result includes a 'why' field explaining what makes it non-obvious.
235
+ """
236
+ node_community = _node_community_map(communities)
237
+ candidates = []
238
+
239
+ for u, v, data in G.edges(data=True):
240
+ relation = data.get("relation", "")
241
+ if relation in ("imports", "imports_from", "contains", "method"):
242
+ continue
243
+ if _is_concept_node(G, u) or _is_concept_node(G, v):
244
+ continue
245
+ if _is_file_node(G, u) or _is_file_node(G, v):
246
+ continue
247
+
248
+ u_source = G.nodes[u].get("source_file", "")
249
+ v_source = G.nodes[v].get("source_file", "")
250
+
251
+ if not u_source or not v_source or u_source == v_source:
252
+ continue
253
+
254
+ score, reasons = _surprise_score(G, u, v, data, node_community, u_source, v_source)
255
+ src_id = data.get("_src", u)
256
+ if src_id not in G.nodes:
257
+ src_id = u
258
+ tgt_id = data.get("_tgt", v)
259
+ if tgt_id not in G.nodes:
260
+ tgt_id = v
261
+ candidates.append({
262
+ "_score": score,
263
+ "source": G.nodes[src_id].get("label", src_id),
264
+ "target": G.nodes[tgt_id].get("label", tgt_id),
265
+ "source_files": [
266
+ G.nodes[src_id].get("source_file", ""),
267
+ G.nodes[tgt_id].get("source_file", ""),
268
+ ],
269
+ "confidence": data.get("confidence", "EXTRACTED"),
270
+ "relation": relation,
271
+ "why": "; ".join(reasons) if reasons else "cross-file semantic connection",
272
+ })
273
+
274
+ candidates.sort(key=lambda x: x["_score"], reverse=True)
275
+ for c in candidates:
276
+ c.pop("_score")
277
+
278
+ if candidates:
279
+ return candidates[:top_n]
280
+
281
+ return _cross_community_surprises(G, communities, top_n)
282
+
283
+
284
+ def _cross_community_surprises(
285
+ G: nx.Graph,
286
+ communities: dict[int, list[str]],
287
+ top_n: int,
288
+ ) -> list[dict]:
289
+ """
290
+ For single-source corpora: find edges that bridge different communities.
291
+ These are surprising because Leiden grouped everything else tightly -
292
+ these edges cut across the natural structure.
293
+
294
+ Falls back to high-betweenness edges if no community info is provided.
295
+ """
296
+ if not communities:
297
+ # No community info - use edge betweenness centrality
298
+ if G.number_of_edges() == 0:
299
+ return []
300
+ if G.number_of_nodes() > 5000:
301
+ return []
302
+ betweenness = nx.edge_betweenness_centrality(G)
303
+ top_edges = sorted(betweenness.items(), key=lambda x: x[1], reverse=True)[:top_n]
304
+ result = []
305
+ for (u, v), score in top_edges:
306
+ data = edge_data(G, u, v)
307
+ result.append({
308
+ "source": G.nodes[u].get("label", u),
309
+ "target": G.nodes[v].get("label", v),
310
+ "source_files": [
311
+ G.nodes[u].get("source_file", ""),
312
+ G.nodes[v].get("source_file", ""),
313
+ ],
314
+ "confidence": data.get("confidence", "EXTRACTED"),
315
+ "relation": data.get("relation", ""),
316
+ "note": f"Bridges graph structure (betweenness={score:.3f})",
317
+ })
318
+ return result
319
+
320
+ # Build node → community map
321
+ node_community = _node_community_map(communities)
322
+
323
+ surprises = []
324
+ for u, v, data in G.edges(data=True):
325
+ cid_u = node_community.get(u)
326
+ cid_v = node_community.get(v)
327
+ if cid_u is None or cid_v is None or cid_u == cid_v:
328
+ continue
329
+ # Skip file hub nodes and plain structural edges
330
+ if _is_file_node(G, u) or _is_file_node(G, v):
331
+ continue
332
+ relation = data.get("relation", "")
333
+ if relation in ("imports", "imports_from", "contains", "method"):
334
+ continue
335
+ # This edge crosses community boundaries - interesting
336
+ confidence = data.get("confidence", "EXTRACTED")
337
+ src_id = data.get("_src", u)
338
+ if src_id not in G.nodes:
339
+ src_id = u
340
+ tgt_id = data.get("_tgt", v)
341
+ if tgt_id not in G.nodes:
342
+ tgt_id = v
343
+ surprises.append({
344
+ "source": G.nodes[src_id].get("label", src_id),
345
+ "target": G.nodes[tgt_id].get("label", tgt_id),
346
+ "source_files": [
347
+ G.nodes[src_id].get("source_file", ""),
348
+ G.nodes[tgt_id].get("source_file", ""),
349
+ ],
350
+ "confidence": confidence,
351
+ "relation": relation,
352
+ "note": f"Bridges community {cid_u} → community {cid_v}",
353
+ "_pair": tuple(sorted([cid_u, cid_v])),
354
+ })
355
+
356
+ # Sort: AMBIGUOUS first, then INFERRED, then EXTRACTED
357
+ order = {"AMBIGUOUS": 0, "INFERRED": 1, "EXTRACTED": 2}
358
+ surprises.sort(key=lambda x: order.get(x["confidence"], 3))
359
+
360
+ # Deduplicate by community pair - one representative edge per (A→B) boundary.
361
+ # Without this, a single high-betweenness god node dominates all results.
362
+ seen_pairs: set[tuple] = set()
363
+ deduped = []
364
+ for s in surprises:
365
+ pair = s.pop("_pair")
366
+ if pair not in seen_pairs:
367
+ seen_pairs.add(pair)
368
+ deduped.append(s)
369
+ return deduped[:top_n]
370
+
371
+
372
+ def suggest_questions(
373
+ G: nx.Graph,
374
+ communities: dict[int, list[str]],
375
+ community_labels: dict[int, str],
376
+ top_n: int = 7,
377
+ ) -> list[dict]:
378
+ """
379
+ Generate questions the graph is uniquely positioned to answer.
380
+ Based on: AMBIGUOUS edges, bridge nodes, underexplored god nodes, isolated nodes.
381
+ Each question has a 'type', 'question', and 'why' field.
382
+ """
383
+ questions = []
384
+ node_community = _node_community_map(communities)
385
+
386
+ # 1. AMBIGUOUS edges → unresolved relationship questions
387
+ for u, v, data in G.edges(data=True):
388
+ if data.get("confidence") == "AMBIGUOUS":
389
+ ul = G.nodes[u].get("label", u)
390
+ vl = G.nodes[v].get("label", v)
391
+ relation = data.get("relation", "related to")
392
+ questions.append({
393
+ "type": "ambiguous_edge",
394
+ "question": f"What is the exact relationship between `{ul}` and `{vl}`?",
395
+ "why": f"Edge tagged AMBIGUOUS (relation: {relation}) - confidence is low.",
396
+ })
397
+
398
+ # 2. Bridge nodes (high betweenness) → cross-cutting concern questions
399
+ if G.number_of_edges() > 0:
400
+ k = min(100, G.number_of_nodes()) if G.number_of_nodes() > 1000 else None
401
+ betweenness = nx.betweenness_centrality(G, k=k, seed=42)
402
+ # Top bridge nodes that are NOT file-level hubs
403
+ bridges = sorted(
404
+ [(n, s) for n, s in betweenness.items()
405
+ if not _is_file_node(G, n) and not _is_concept_node(G, n) and s > 0],
406
+ key=lambda x: x[1],
407
+ reverse=True,
408
+ )[:3]
409
+ for node_id, score in bridges:
410
+ label = G.nodes[node_id].get("label", node_id)
411
+ cid = node_community.get(node_id)
412
+ comm_label = community_labels.get(cid, f"Community {cid}") if cid is not None else "unknown"
413
+ neighbors = list(G.neighbors(node_id))
414
+ neighbor_comms = {node_community.get(n) for n in neighbors if node_community.get(n) != cid}
415
+ if neighbor_comms:
416
+ other_labels = [community_labels.get(c, f"Community {c}") for c in neighbor_comms]
417
+ questions.append({
418
+ "type": "bridge_node",
419
+ "question": f"Why does `{label}` connect `{comm_label}` to {', '.join(f'`{l}`' for l in other_labels)}?",
420
+ "why": f"High betweenness centrality ({score:.3f}) - this node is a cross-community bridge.",
421
+ })
422
+
423
+ # 3. God nodes with many INFERRED edges → verification questions
424
+ degree = dict(G.degree())
425
+ top_nodes = sorted(
426
+ [(n, d) for n, d in degree.items() if not _is_file_node(G, n)],
427
+ key=lambda x: x[1],
428
+ reverse=True,
429
+ )[:5]
430
+ for node_id, _ in top_nodes:
431
+ inferred = [
432
+ (u, v, d) for u, v, d in G.edges(node_id, data=True)
433
+ if d.get("confidence") == "INFERRED"
434
+ ]
435
+ if len(inferred) >= 2:
436
+ label = G.nodes[node_id].get("label", node_id)
437
+ # Use _src/_tgt to get the correct direction; fall back to v (the other node)
438
+ others = []
439
+ for u, v, d in inferred[:2]:
440
+ src_id = d.get("_src", u)
441
+ if src_id not in G.nodes:
442
+ src_id = u
443
+ tgt_id = d.get("_tgt", v)
444
+ if tgt_id not in G.nodes:
445
+ tgt_id = v
446
+ other_id = tgt_id if src_id == node_id else src_id
447
+ others.append(G.nodes[other_id].get("label", other_id))
448
+ questions.append({
449
+ "type": "verify_inferred",
450
+ "question": f"Are the {len(inferred)} inferred relationships involving `{label}` (e.g. with `{others[0]}` and `{others[1]}`) actually correct?",
451
+ "why": f"`{label}` has {len(inferred)} INFERRED edges - model-reasoned connections that need verification.",
452
+ })
453
+
454
+ # 4. Isolated or weakly-connected nodes → exploration questions
455
+ isolated = [
456
+ n for n in G.nodes()
457
+ if G.degree(n) <= 1 and not _is_file_node(G, n) and not _is_concept_node(G, n)
458
+ ]
459
+ if isolated:
460
+ labels = [G.nodes[n].get("label", n) for n in isolated[:3]]
461
+ questions.append({
462
+ "type": "isolated_nodes",
463
+ "question": f"What connects {', '.join(f'`{l}`' for l in labels)} to the rest of the system?",
464
+ "why": f"{len(isolated)} weakly-connected nodes found - possible documentation gaps or missing edges.",
465
+ })
466
+
467
+ # 5. Low-cohesion communities → structural questions
468
+ from .cluster import cohesion_score
469
+ for cid, nodes in communities.items():
470
+ score = cohesion_score(G, nodes)
471
+ if score < 0.15 and len(nodes) >= 5:
472
+ label = community_labels.get(cid, f"Community {cid}")
473
+ questions.append({
474
+ "type": "low_cohesion",
475
+ "question": f"Should `{label}` be split into smaller, more focused modules?",
476
+ "why": f"Cohesion score {score} - nodes in this community are weakly interconnected.",
477
+ })
478
+
479
+ if not questions:
480
+ return [{
481
+ "type": "no_signal",
482
+ "question": None,
483
+ "why": (
484
+ "Not enough signal to generate questions. "
485
+ "This usually means the corpus has no AMBIGUOUS edges, no bridge nodes, "
486
+ "no INFERRED relationships, and all communities are tightly cohesive. "
487
+ "Add more files or run with --mode deep to extract richer edges."
488
+ ),
489
+ }]
490
+
491
+ return questions[:top_n]
492
+
493
+
494
+ def graph_diff(G_old: nx.Graph, G_new: nx.Graph) -> dict:
495
+ """Compare two graph snapshots and return what changed.
496
+
497
+ Returns:
498
+ {
499
+ "new_nodes": [{"id": ..., "label": ...}],
500
+ "removed_nodes": [{"id": ..., "label": ...}],
501
+ "new_edges": [{"source": ..., "target": ..., "relation": ..., "confidence": ...}],
502
+ "removed_edges": [...],
503
+ "summary": "3 new nodes, 5 new edges, 1 node removed"
504
+ }
505
+ """
506
+ old_nodes = set(G_old.nodes())
507
+ new_nodes = set(G_new.nodes())
508
+
509
+ added_node_ids = new_nodes - old_nodes
510
+ removed_node_ids = old_nodes - new_nodes
511
+
512
+ new_nodes_list = [
513
+ {"id": n, "label": G_new.nodes[n].get("label", n)}
514
+ for n in added_node_ids
515
+ ]
516
+ removed_nodes_list = [
517
+ {"id": n, "label": G_old.nodes[n].get("label", n)}
518
+ for n in removed_node_ids
519
+ ]
520
+
521
+ def edge_key(G: nx.Graph, u: str, v: str, data: dict) -> tuple:
522
+ if G.is_directed():
523
+ return (u, v, data.get("relation", ""))
524
+ return (min(u, v), max(u, v), data.get("relation", ""))
525
+
526
+ old_edge_keys = {
527
+ edge_key(G_old, u, v, d)
528
+ for u, v, d in G_old.edges(data=True)
529
+ }
530
+ new_edge_keys = {
531
+ edge_key(G_new, u, v, d)
532
+ for u, v, d in G_new.edges(data=True)
533
+ }
534
+
535
+ added_edge_keys = new_edge_keys - old_edge_keys
536
+ removed_edge_keys = old_edge_keys - new_edge_keys
537
+
538
+ new_edges_list = []
539
+ for u, v, d in G_new.edges(data=True):
540
+ if edge_key(G_new, u, v, d) in added_edge_keys:
541
+ new_edges_list.append({
542
+ "source": u,
543
+ "target": v,
544
+ "relation": d.get("relation", ""),
545
+ "confidence": d.get("confidence", ""),
546
+ })
547
+
548
+ removed_edges_list = []
549
+ for u, v, d in G_old.edges(data=True):
550
+ if edge_key(G_old, u, v, d) in removed_edge_keys:
551
+ removed_edges_list.append({
552
+ "source": u,
553
+ "target": v,
554
+ "relation": d.get("relation", ""),
555
+ "confidence": d.get("confidence", ""),
556
+ })
557
+
558
+ parts = []
559
+ if new_nodes_list:
560
+ parts.append(f"{len(new_nodes_list)} new node{'s' if len(new_nodes_list) != 1 else ''}")
561
+ if new_edges_list:
562
+ parts.append(f"{len(new_edges_list)} new edge{'s' if len(new_edges_list) != 1 else ''}")
563
+ if removed_nodes_list:
564
+ parts.append(f"{len(removed_nodes_list)} node{'s' if len(removed_nodes_list) != 1 else ''} removed")
565
+ if removed_edges_list:
566
+ parts.append(f"{len(removed_edges_list)} edge{'s' if len(removed_edges_list) != 1 else ''} removed")
567
+ summary = ", ".join(parts) if parts else "no changes"
568
+
569
+ return {
570
+ "new_nodes": new_nodes_list,
571
+ "removed_nodes": removed_nodes_list,
572
+ "new_edges": new_edges_list,
573
+ "removed_edges": removed_edges_list,
574
+ "summary": summary,
575
+ }