codiff 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.
Files changed (45) hide show
  1. codiff/__init__.py +1 -0
  2. codiff/__main__.py +5 -0
  3. codiff/cli.py +247 -0
  4. codiff/db/__init__.py +16 -0
  5. codiff/db/engine.py +31 -0
  6. codiff/db/models.py +119 -0
  7. codiff/db/operations.py +238 -0
  8. codiff/diff/__init__.py +1 -0
  9. codiff/diff/analysis.py +145 -0
  10. codiff/diff/differ.py +45 -0
  11. codiff/diff/engine.py +80 -0
  12. codiff/diff/indexer.py +134 -0
  13. codiff/diff/snapshot.py +325 -0
  14. codiff/export/__init__.py +5 -0
  15. codiff/export/json.py +43 -0
  16. codiff/export/mermaid.py +475 -0
  17. codiff/export/terminal.py +866 -0
  18. codiff/languages/__init__.py +29 -0
  19. codiff/languages/parser.py +214 -0
  20. codiff/languages/python/__init__.py +0 -0
  21. codiff/languages/python/parser.py +927 -0
  22. codiff/languages/python/resolver.py +178 -0
  23. codiff/languages/repository.py +245 -0
  24. codiff/languages/resolver.py +582 -0
  25. codiff/languages/typescript/__init__.py +0 -0
  26. codiff/languages/typescript/parser.py +612 -0
  27. codiff/languages/typescript/resolver.py +95 -0
  28. codiff/mcp_server.py +83 -0
  29. codiff/schema/__init__.py +25 -0
  30. codiff/schema/diff.py +110 -0
  31. codiff/schema/parsing.py +76 -0
  32. codiff/setup.py +103 -0
  33. codiff/utils/__init__.py +0 -0
  34. codiff/utils/args.py +114 -0
  35. codiff/utils/files.py +62 -0
  36. codiff/utils/git.py +101 -0
  37. codiff/utils/instructions.py +14 -0
  38. codiff/utils/instructions.yaml +50 -0
  39. codiff/utils/terminal.py +10 -0
  40. codiff-0.1.0.dist-info/METADATA +487 -0
  41. codiff-0.1.0.dist-info/RECORD +45 -0
  42. codiff-0.1.0.dist-info/WHEEL +5 -0
  43. codiff-0.1.0.dist-info/entry_points.txt +3 -0
  44. codiff-0.1.0.dist-info/licenses/LICENSE +201 -0
  45. codiff-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,866 @@
1
+ """Render an AnalysisResult to the terminal using Rich.
2
+
3
+ Groups changes into source vs. test functions and renders a UML-style
4
+ box layout: one panel per file, side by side when they fit the terminal,
5
+ with arrows between connected panels.
6
+
7
+ Color scheme
8
+ ------------
9
+ - New functions that share a call-graph chain are assigned a distinct color.
10
+ The same color is used consistently in both the function name and every
11
+ Caller / Callee reference, so you can visually trace a chain at a glance.
12
+ - New functions that belong to no chain (isolated additions) stay white.
13
+ - Existing / pre-diff functions are rendered dim (gray).
14
+ """
15
+
16
+ from collections import defaultdict
17
+ from typing import Optional
18
+
19
+ from rich.box import Box
20
+ from rich.console import Console, Group
21
+ from rich.panel import Panel
22
+ from rich.table import Table
23
+ from rich.text import Text
24
+
25
+ from codiff.schema.diff import (
26
+ AddedFunctionInfo,
27
+ AnalysisResult,
28
+ ModifiedFunctionInfo,
29
+ RemovedFunctionInfo,
30
+ )
31
+ from codiff.utils.terminal import detect_width
32
+
33
+ console = Console(force_terminal=True)
34
+
35
+ # Dashed box for class sub-panels inside a file panel.
36
+ # Rich Box format: exactly 4 chars per row = (left, fill, mid-divider, right)
37
+ _CLASS_BOX = Box(
38
+ "╭╌╌╮\n" # top
39
+ "│ │\n" # head
40
+ "├╌╌┤\n" # head_row (separator under title)
41
+ "│ │\n" # mid
42
+ "├╌╌┤\n" # row
43
+ "├╌╌┤\n" # foot_row
44
+ "│ │\n" # foot
45
+ "╰╌╌╯\n", # bottom
46
+ ascii=False,
47
+ )
48
+
49
+ # Distinct colors for call-chain groups. Green/red/yellow are reserved for
50
+ # the +/~/- indicators, cyan for the header rule.
51
+ _CHAIN_COLORS = [
52
+ "magenta",
53
+ "cornflower_blue",
54
+ "orange3",
55
+ "medium_purple1",
56
+ "spring_green2",
57
+ "hot_pink",
58
+ "sky_blue1",
59
+ "gold3",
60
+ ]
61
+
62
+
63
+ # ---------------------------------------------------------------------------
64
+ # Color map: connected components of new functions
65
+ # ---------------------------------------------------------------------------
66
+
67
+
68
+ def _build_color_map(result: AnalysisResult) -> dict[str, str]:
69
+ """Assign a chain color to every function that belongs to a connected call chain.
70
+
71
+ The graph includes both added and modified functions so that a modified
72
+ function calling an added function shares the same color across modules.
73
+ Single-node components get no color (white for added, yellow for modified).
74
+ """
75
+ all_ids = {fn.function_id for fn in result.added} | {fn.function_id for fn in result.modified}
76
+
77
+ adj: dict[str, set[str]] = defaultdict(set)
78
+
79
+ # Added functions: full adjacency via new_calls / new_callers
80
+ for fn in result.added:
81
+ for callee in fn.new_calls:
82
+ adj[fn.function_id].add(callee)
83
+ adj[callee].add(fn.function_id)
84
+ for caller in fn.new_callers:
85
+ adj[fn.function_id].add(caller)
86
+ adj[caller].add(fn.function_id)
87
+
88
+ # Modified functions: connect to added functions they now call
89
+ for mod_fn in result.modified:
90
+ for callee_id in mod_fn.calls_added_new:
91
+ adj[mod_fn.function_id].add(callee_id)
92
+ adj[callee_id].add(mod_fn.function_id)
93
+
94
+ visited: set[str] = set()
95
+ components: list[list[str]] = []
96
+ for fid in sorted(all_ids):
97
+ if fid in visited:
98
+ continue
99
+ component: list[str] = []
100
+ queue = [fid]
101
+ while queue:
102
+ node = queue.pop(0)
103
+ if node in visited:
104
+ continue
105
+ visited.add(node)
106
+ component.append(node)
107
+ for neighbor in sorted(adj.get(node, set())):
108
+ if neighbor in all_ids and neighbor not in visited:
109
+ queue.append(neighbor)
110
+ components.append(component)
111
+
112
+ components.sort(key=lambda c: (-len(c), c[0]))
113
+
114
+ color_map: dict[str, str] = {}
115
+ color_idx = 0
116
+ for component in components:
117
+ if len(component) >= 2:
118
+ color = _CHAIN_COLORS[color_idx % len(_CHAIN_COLORS)]
119
+ color_idx += 1
120
+ for fid in component:
121
+ color_map[fid] = color
122
+
123
+ return color_map
124
+
125
+
126
+ # ---------------------------------------------------------------------------
127
+ # Helpers
128
+ # ---------------------------------------------------------------------------
129
+
130
+
131
+ def _name(function_id: str) -> str:
132
+ """Compact label: just the bare function name (last dotted segment)."""
133
+ return function_id.split(".")[-1]
134
+
135
+
136
+ def _display_name(fn: object) -> str:
137
+ """ClassName.method for class methods, outer.inner for nested functions, else just name."""
138
+ class_name = getattr(fn, "class_name", None)
139
+ function_id = getattr(fn, "function_id", "")
140
+ name = function_id.split(".")[-1]
141
+
142
+ if class_name:
143
+ return f"{class_name}.{name}"
144
+
145
+ # Detect nested: strip the module prefix (derived from file_path) and check
146
+ # if what remains is "outer.inner" rather than a bare function name.
147
+ file_path = getattr(fn, "file_path", "")
148
+ module = file_path.replace("/", ".").replace(".py", "")
149
+ if function_id.startswith(module + "."):
150
+ remaining = function_id[len(module) + 1 :] # e.g. "build_from_path.walk"
151
+ parts = remaining.split(".")
152
+ if len(parts) > 1:
153
+ return ".".join(parts[-2:])
154
+
155
+ return name
156
+
157
+
158
+ def _is_test(file_path: str) -> bool:
159
+ from codiff.utils.files import is_test_file
160
+
161
+ return is_test_file(file_path)
162
+
163
+
164
+ def _partition(items: list, *, test: bool) -> list:
165
+ return [i for i in items if _is_test(i.file_path) == test]
166
+
167
+
168
+ def _group_key(fn: object) -> tuple[str, str]:
169
+ """Sort/group key: (file_path, class_name) for section breaks."""
170
+ return (fn.file_path, fn.class_name or "") # type: ignore[attr-defined]
171
+
172
+
173
+ def _order_group(
174
+ fns: list[AddedFunctionInfo],
175
+ color_map: dict[str, str] | None = None,
176
+ ) -> list[AddedFunctionInfo]:
177
+ """Order functions within a (file, class) group for readability.
178
+
179
+ Entry points (nothing calls them within the group) come first.
180
+ DFS follows new_calls within the group so callee rows flow directly
181
+ after their caller — but only across same-color connections, so chains
182
+ stay visually consistent with the color coding.
183
+ """
184
+ if len(fns) <= 1:
185
+ return fns
186
+
187
+ by_id = {fn.function_id: fn for fn in fns}
188
+ g_ids = set(by_id)
189
+ cm = color_map or {}
190
+
191
+ starts = [fn for fn in fns if fn.is_entry_point or not (set(fn.new_callers) & g_ids)]
192
+ starts.sort(key=lambda fn: (0 if fn.is_entry_point else 1, _name(fn.function_id)))
193
+
194
+ ordered: list[AddedFunctionInfo] = []
195
+ visited: set[str] = set()
196
+ for start in starts:
197
+ stack = [start.function_id]
198
+ while stack:
199
+ fid = stack.pop()
200
+ if fid in visited:
201
+ continue
202
+ visited.add(fid)
203
+ ordered.append(by_id[fid])
204
+ my_color = cm.get(fid)
205
+ for callee_id in reversed(sorted(by_id[fid].new_calls)):
206
+ if callee_id not in g_ids or callee_id in visited:
207
+ continue
208
+ # Only follow same-color edges so chains stay contiguous
209
+ if my_color is not None and cm.get(callee_id) == my_color:
210
+ stack.append(callee_id)
211
+
212
+ # Append anything not yet reached (cross-chain callees, isolated nodes)
213
+ for fn in sorted(fns, key=lambda fn: _name(fn.function_id)):
214
+ if fn.function_id not in visited:
215
+ ordered.append(fn)
216
+
217
+ return ordered
218
+
219
+
220
+ # ---------------------------------------------------------------------------
221
+ # Summary
222
+ # ---------------------------------------------------------------------------
223
+
224
+
225
+ def _render_summary(
226
+ added: list,
227
+ modified: list,
228
+ removed: list,
229
+ ) -> None:
230
+ total = len(added) + len(modified) + len(removed)
231
+ if total == 0:
232
+ console.print("\n [dim]No structural changes detected.[/dim]")
233
+ return
234
+ parts: list[str] = []
235
+ if added:
236
+ parts.append(f"[green]+{len(added)} added[/green]")
237
+ if modified:
238
+ parts.append(f"[yellow]~{len(modified)} modified[/yellow]")
239
+ if removed:
240
+ parts.append(f"[red]-{len(removed)} removed[/red]")
241
+ modules = {fn.file_path for fn in added + modified + removed}
242
+ n = len(modules)
243
+ parts.append(f"[dim]{n} module{'s' if n != 1 else ''}[/dim]")
244
+ console.print(" " + " · ".join(parts))
245
+
246
+
247
+ # ---------------------------------------------------------------------------
248
+ # Group renderer
249
+ # ---------------------------------------------------------------------------
250
+
251
+
252
+ def render(
253
+ result: AnalysisResult,
254
+ base_ref: str = "HEAD",
255
+ head_ref: str = "working tree",
256
+ include_tests: bool = False,
257
+ ) -> None:
258
+ """Print the full structural diff report."""
259
+ term_w = detect_width()
260
+ console.print()
261
+ console.rule(
262
+ f"[bold cyan]codiff[/bold cyan] [dim]{base_ref}[/dim] [dim]→[/dim] {head_ref}",
263
+ style="cyan",
264
+ )
265
+
266
+ src_added = _partition(result.added, test=False)
267
+ src_modified = _partition(result.modified, test=False)
268
+ src_removed = _partition(result.removed, test=False)
269
+
270
+ if include_tests:
271
+ tst_added = _partition(result.added, test=True)
272
+ tst_modified = _partition(result.modified, test=True)
273
+ tst_removed = _partition(result.removed, test=True)
274
+ else:
275
+ tst_added = tst_modified = tst_removed = []
276
+
277
+ visible_added = src_added + tst_added
278
+ visible_modified = src_modified + tst_modified
279
+ visible_removed = src_removed + tst_removed
280
+
281
+ _render_summary(visible_added, visible_modified, visible_removed)
282
+
283
+ color_map = _build_color_map(result)
284
+
285
+ _render_group(
286
+ "Source", src_added, src_modified, src_removed, color_map, term_w, result.class_parents
287
+ )
288
+ if include_tests:
289
+ _render_group(
290
+ "Tests", tst_added, tst_modified, tst_removed, color_map, term_w, result.class_parents
291
+ )
292
+ console.print()
293
+
294
+
295
+ def _render_group(
296
+ title: str,
297
+ added: list[AddedFunctionInfo],
298
+ modified: list[ModifiedFunctionInfo],
299
+ removed: list[RemovedFunctionInfo],
300
+ color_map: dict[str, str],
301
+ term_w: int,
302
+ class_parents: dict[str, list[str]] | None = None,
303
+ ) -> None:
304
+ if not added and not modified and not removed:
305
+ return
306
+ console.print()
307
+ console.rule(f"[bold]{title}[/bold]", style="dim blue")
308
+ console.print()
309
+ _render_uml(added, modified, removed, color_map, term_w, class_parents)
310
+
311
+
312
+ # ---------------------------------------------------------------------------
313
+ # UML layout
314
+ # ---------------------------------------------------------------------------
315
+
316
+
317
+ def _render_uml(
318
+ added: list[AddedFunctionInfo],
319
+ modified: list[ModifiedFunctionInfo],
320
+ removed: list[RemovedFunctionInfo],
321
+ color_map: dict[str, str],
322
+ term_w: int,
323
+ class_parents: dict[str, list[str]] | None = None,
324
+ ) -> None:
325
+ """Render file boxes side-by-side with arrows for cross-file relationships."""
326
+ # Group changes by file
327
+ files: dict[str, dict] = {}
328
+ for a_fn in added:
329
+ files.setdefault(a_fn.file_path, {"added": [], "modified": [], "removed": []})
330
+ files[a_fn.file_path]["added"].append(a_fn)
331
+ for m_fn in modified:
332
+ files.setdefault(m_fn.file_path, {"added": [], "modified": [], "removed": []})
333
+ files[m_fn.file_path]["modified"].append(m_fn)
334
+ for r_fn in removed:
335
+ files.setdefault(r_fn.file_path, {"added": [], "modified": [], "removed": []})
336
+ files[r_fn.file_path]["removed"].append(r_fn)
337
+
338
+ # Map function_id → file_path for changed functions only
339
+ fn_to_file: dict[str, str] = {}
340
+ for a_fn in added:
341
+ fn_to_file[a_fn.function_id] = a_fn.file_path
342
+ for m_fn in modified:
343
+ fn_to_file[m_fn.function_id] = m_fn.file_path
344
+ for r_fn in removed:
345
+ fn_to_file[r_fn.function_id] = r_fn.file_path
346
+
347
+ # Detect cross-file call relationships between changed files.
348
+ # (from_file, to_file) → list of callee function_ids (used for chain color)
349
+ cross: dict[tuple[str, str], list[str]] = defaultdict(list)
350
+
351
+ for a_fn in added:
352
+ for caller_id in a_fn.existing_callers + a_fn.new_callers:
353
+ caller_file = fn_to_file.get(caller_id)
354
+ if caller_file and caller_file != a_fn.file_path:
355
+ cross[(caller_file, a_fn.file_path)].append(a_fn.function_id)
356
+
357
+ for m_fn in modified:
358
+ for callee_id in m_fn.calls_added_new + m_fn.calls_added_existing:
359
+ callee_file = fn_to_file.get(callee_id)
360
+ if callee_file and callee_file != m_fn.file_path:
361
+ cross[(m_fn.file_path, callee_file)].append(callee_id)
362
+
363
+ # Detect cross-file inheritance from ClassChunk.superclasses (via class_parents).
364
+ # class_parents: class_id → list of superclass names (e.g. "PreChunkBuilder")
365
+ # We map each class_id to its file via the changed functions, then check if any
366
+ # superclass name matches a class in a different file.
367
+ inherit: set[tuple[str, str]] = set()
368
+ if class_parents:
369
+ # Build: class_name → file_path from changed functions
370
+ class_name_to_file: dict[str, str] = {}
371
+ for fn in list(added) + list(modified) + list(removed):
372
+ if fn.class_name:
373
+ class_name_to_file[fn.class_name] = fn.file_path
374
+
375
+ # Build: class_id → file_path (class_id = "module.path.ClassName")
376
+ class_id_to_file: dict[str, str] = {}
377
+ for fn in list(added) + list(modified) + list(removed):
378
+ if fn.class_name:
379
+ # Derive class_id prefix from function_id
380
+ parts = fn.function_id.split(".")
381
+ if len(parts) >= 2:
382
+ class_id = ".".join(parts[:-1]) # drop the method name
383
+ class_id_to_file[class_id] = fn.file_path
384
+
385
+ for class_id, parents in class_parents.items():
386
+ child_file = class_id_to_file.get(class_id)
387
+ if not child_file:
388
+ continue
389
+ for parent_name in parents:
390
+ # Strip generic type params (e.g. "BaseModel[T]" → "BaseModel")
391
+ parent_name = parent_name.split("[")[0].strip()
392
+ parent_file = class_name_to_file.get(parent_name)
393
+ if parent_file and parent_file != child_file:
394
+ inherit.add((child_file, parent_file))
395
+
396
+ # Count how many cross-file call arrows point INTO each file
397
+ in_count: dict[str, int] = defaultdict(int)
398
+ for _, to_f in cross:
399
+ in_count[to_f] += 1
400
+
401
+ # Files deferred to the end: has removals AND nobody calls into it.
402
+ # This covers both removed-only files and mixed files that happen to
403
+ # not be depended upon — their deletions are easier to read last.
404
+ deferred = {fp for fp in files if files[fp]["removed"] and in_count[fp] == 0}
405
+ primary = {fp for fp in files if fp not in deferred}
406
+
407
+ # Sort primary files so connected pairs are adjacent (maximises arrows).
408
+ placed: set[str] = set()
409
+ all_fps: list[str] = []
410
+ for from_fp, to_fp in sorted(cross):
411
+ for fp in (from_fp, to_fp):
412
+ if fp in primary and fp not in placed:
413
+ all_fps.append(fp)
414
+ placed.add(fp)
415
+ for fp in sorted(primary):
416
+ if fp not in placed:
417
+ all_fps.append(fp)
418
+
419
+ # Deferred files (have removals, not called by anyone) come last
420
+ all_fps.extend(sorted(deferred))
421
+
422
+ panels = {fp: _build_file_panel(fp, files[fp], color_map, class_parents) for fp in all_fps}
423
+ widths = {fp: _panel_min_width(fp, files[fp], color_map) for fp in all_fps}
424
+
425
+ # Greedy row packing — fit as many panels per row as the terminal allows.
426
+ # Arrows show automatically when two adjacent same-row panels are connected.
427
+ _ARROW_W = 14
428
+
429
+ rows: list[list[str]] = []
430
+ current_row: list[str] = []
431
+ current_w = 0
432
+ for fp in all_fps:
433
+ slot_w = widths[fp] + 4 + (_ARROW_W if current_row else 0)
434
+ if current_row and current_w + slot_w > term_w:
435
+ rows.append(current_row)
436
+ current_row = [fp]
437
+ current_w = widths[fp] + 4
438
+ else:
439
+ current_row.append(fp)
440
+ current_w += slot_w
441
+ if current_row:
442
+ rows.append(current_row)
443
+
444
+ for row_fps in rows:
445
+ grid = Table.grid(padding=(0, 2))
446
+ for i, fp in enumerate(row_fps):
447
+ grid.add_column(vertical="top", min_width=widths[fp])
448
+ if i < len(row_fps) - 1:
449
+ grid.add_column(vertical="middle", width=12) # centred arrow column
450
+ row_cells: list = []
451
+ for i, fp in enumerate(row_fps):
452
+ row_cells.append(panels[fp])
453
+ if i < len(row_fps) - 1:
454
+ next_fp = row_fps[i + 1]
455
+ fwd = cross.get((fp, next_fp), [])
456
+ rev = cross.get((next_fp, fp), [])
457
+ callee_ids = fwd + rev
458
+ has_calls = bool(callee_ids)
459
+ has_inherits = (fp, next_fp) in inherit or (next_fp, fp) in inherit
460
+ if has_calls or has_inherits:
461
+ row_cells.append(
462
+ _arrow_cell(
463
+ callee_ids,
464
+ color_map,
465
+ reverse=bool(rev and not fwd),
466
+ has_calls=has_calls,
467
+ has_inherits=has_inherits,
468
+ inherit_reverse=(next_fp, fp) in inherit
469
+ and (fp, next_fp) not in inherit,
470
+ )
471
+ )
472
+ else:
473
+ row_cells.append(Text(""))
474
+ grid.add_row(*row_cells)
475
+ console.print(grid)
476
+
477
+
478
+ def _panel_min_width(file_path: str, funcs: dict, color_map: dict[str, str]) -> int:
479
+ """Minimum panel width: widest row (indicator + indent + name + annotation) + borders."""
480
+ depth: dict[str, int] = {}
481
+ added_sorted: list[AddedFunctionInfo] = []
482
+ fn_by_grp: dict[tuple[str, str], list[AddedFunctionInfo]] = defaultdict(list)
483
+ for fn in funcs["added"]:
484
+ fn_by_grp[_group_key(fn)].append(fn)
485
+ for grp_key in _topo_order_groups(funcs["added"]):
486
+ added_sorted.extend(_order_group(fn_by_grp[grp_key], color_map))
487
+ for i, fn in enumerate(added_sorted):
488
+ my_color = color_map.get(fn.function_id)
489
+ parent_depth2: Optional[int] = None
490
+ for j in range(i - 1, -1, -1):
491
+ prev = added_sorted[j]
492
+ if (
493
+ prev.function_id in fn.new_callers
494
+ and my_color is not None
495
+ and color_map.get(prev.function_id) == my_color
496
+ ):
497
+ broken = any(
498
+ depth[added_sorted[k].function_id] == 0
499
+ and color_map.get(added_sorted[k].function_id) != my_color
500
+ for k in range(j + 1, i)
501
+ )
502
+ if not broken:
503
+ parent_depth2 = depth[prev.function_id]
504
+ break
505
+ depth[fn.function_id] = (parent_depth2 + 1) if parent_depth2 is not None else 0
506
+
507
+ rows = []
508
+ for fn in added_sorted:
509
+ d = depth[fn.function_id]
510
+ indent = " " * d + ("→ " if d > 0 else "+ ")
511
+ label = indent + _display_name(fn)
512
+ if fn.is_entry_point:
513
+ label += " entry point"
514
+ rows.append(len(label))
515
+ for fn in funcs["modified"]:
516
+ label = f"~ {_display_name(fn)}"
517
+ if fn.signature_changed:
518
+ label += " sig changed"
519
+ elif fn.calls_added_new or fn.calls_added_existing or fn.calls_removed:
520
+ label += " calls changed"
521
+ else:
522
+ label += " body changed"
523
+ rows.append(len(label))
524
+ for fn in funcs["removed"]:
525
+ rows.append(len(f"- {_display_name(fn)}"))
526
+ rows.append(len(file_path))
527
+ # +4 for panel border (2) + padding (2)
528
+ return max(rows, default=20) + 4
529
+
530
+
531
+ def _topo_order_groups(
532
+ added_fns: list[AddedFunctionInfo],
533
+ ) -> list[tuple[str, str]]:
534
+ """Return (file, class) groups in topological call order.
535
+
536
+ Groups are sorted so that if class A calls any new function in class B,
537
+ A comes before B. This keeps same-chain functions adjacent in the panel.
538
+ Cycles (rare) fall back to alphabetical order.
539
+ """
540
+ # Map function_id → its group key
541
+ fn_to_group: dict[str, tuple[str, str]] = {fn.function_id: _group_key(fn) for fn in added_fns}
542
+
543
+ # Collect groups preserving first-seen order
544
+ groups: list[tuple[str, str]] = []
545
+ seen: set[tuple[str, str]] = set()
546
+ for fn in added_fns:
547
+ g = _group_key(fn)
548
+ if g not in seen:
549
+ groups.append(g)
550
+ seen.add(g)
551
+
552
+ # Build directed edges: group A → group B when fn in A calls fn in B
553
+ edges: dict[tuple[str, str], set[tuple[str, str]]] = {g: set() for g in groups}
554
+ for fn in added_fns:
555
+ my_g = _group_key(fn)
556
+ for callee_id in fn.new_calls:
557
+ callee_g = fn_to_group.get(callee_id)
558
+ if callee_g and callee_g != my_g and callee_g in seen:
559
+ edges[my_g].add(callee_g)
560
+
561
+ # Kahn's topological sort
562
+ in_deg: dict[tuple[str, str], int] = {g: 0 for g in groups}
563
+ for g, callees in edges.items():
564
+ for cg in callees:
565
+ in_deg[cg] += 1
566
+
567
+ queue = sorted([g for g in groups if in_deg[g] == 0], key=lambda g: g[1])
568
+ result: list[tuple[str, str]] = []
569
+ while queue:
570
+ g = queue.pop(0)
571
+ result.append(g)
572
+ for cg in sorted(edges[g], key=lambda g: g[1]):
573
+ in_deg[cg] -= 1
574
+ if in_deg[cg] == 0:
575
+ queue.append(cg)
576
+
577
+ # Cycles or isolated groups not yet placed — append alphabetically
578
+ placed = set(result)
579
+ result.extend(sorted((g for g in groups if g not in placed), key=lambda g: g[1]))
580
+ return result
581
+
582
+
583
+ def _build_file_panel(
584
+ file_path: str,
585
+ funcs: dict,
586
+ color_map: dict[str, str],
587
+ class_parents: dict[str, list[str]] | None = None,
588
+ ) -> Panel:
589
+ """Build a Rich Panel listing the changed functions in one file.
590
+
591
+ Methods belonging to the same class are wrapped in a dashed sub-panel
592
+ for visual grouping. Standalone functions (no class) appear directly.
593
+ """
594
+ # ── Order added functions (entry-points first, then DFS by chain) ────────
595
+ added_ordered: list[AddedFunctionInfo] = []
596
+ fn_by_group: dict[tuple[str, str], list[AddedFunctionInfo]] = defaultdict(list)
597
+ for fn in funcs["added"]:
598
+ fn_by_group[_group_key(fn)].append(fn)
599
+ for grp_key in _topo_order_groups(funcs["added"]):
600
+ added_ordered.extend(_order_group(fn_by_group[grp_key], color_map))
601
+
602
+ # Compute indent depth within each class group (depth rule: same-color caller)
603
+ depth: dict[str, int] = {}
604
+ for i, fn in enumerate(added_ordered):
605
+ my_color = color_map.get(fn.function_id)
606
+ parent_depth: Optional[int] = None
607
+ for j in range(i - 1, -1, -1):
608
+ prev = added_ordered[j]
609
+ if (
610
+ prev.function_id in fn.new_callers
611
+ and my_color is not None
612
+ and color_map.get(prev.function_id) == my_color
613
+ ):
614
+ broken = any(
615
+ depth[added_ordered[k].function_id] == 0
616
+ and color_map.get(added_ordered[k].function_id) != my_color
617
+ for k in range(j + 1, i)
618
+ )
619
+ if not broken:
620
+ parent_depth = depth[prev.function_id]
621
+ break
622
+ depth[fn.function_id] = (parent_depth + 1) if parent_depth is not None else 0
623
+
624
+ # ── Bucket all functions by class ─────────────────────────────────────────
625
+ # class_name → {"added": [...], "modified": [...], "removed": [...]}
626
+ # Preserve the topo ordering for added; sort modified and removed.
627
+ class_buckets: dict[str | None, dict] = {}
628
+ for fn in added_ordered:
629
+ cn = fn.class_name
630
+ class_buckets.setdefault(cn, {"added": [], "modified": [], "removed": []})["added"].append(
631
+ fn
632
+ )
633
+ for fn in sorted(funcs["modified"], key=lambda f: _display_name(f)):
634
+ cn = fn.class_name
635
+ class_buckets.setdefault(cn, {"added": [], "modified": [], "removed": []})[
636
+ "modified"
637
+ ].append(fn)
638
+ for fn in sorted(funcs["removed"], key=lambda f: _display_name(f)):
639
+ cn = fn.class_name
640
+ class_buckets.setdefault(cn, {"added": [], "modified": [], "removed": []})[
641
+ "removed"
642
+ ].append(fn)
643
+
644
+ # Order: standalone (None) first, then classes in the order they appeared
645
+ ordered_classes: list[str | None] = []
646
+ if None in class_buckets:
647
+ ordered_classes.append(None)
648
+ seen: set[str | None] = {None}
649
+ for fn in added_ordered:
650
+ if fn.class_name not in seen:
651
+ ordered_classes.append(fn.class_name)
652
+ seen.add(fn.class_name)
653
+ for cn in class_buckets:
654
+ if cn not in seen:
655
+ ordered_classes.append(cn)
656
+ seen.add(cn)
657
+
658
+ # ── Detect intra-file relationships ──────────────────────────────────────
659
+ # class_name → list of (rel_type, target_class_name) for classes in this file
660
+ all_class_names = {cn for cn in class_buckets if cn is not None}
661
+ file_module = file_path.replace("/", ".").replace(".py", "")
662
+
663
+ # Inheritance: use class_parents (ClassChunk.superclasses)
664
+ intra_inherit: dict[str, list[str]] = defaultdict(list)
665
+ if class_parents:
666
+ for cn in all_class_names:
667
+ cid = f"{file_module}.{cn}"
668
+ for parent in class_parents.get(cid, []):
669
+ parent = parent.split("[")[0].strip() # strip generics
670
+ if parent in all_class_names and parent != cn:
671
+ intra_inherit[cn].append(parent)
672
+
673
+ # Calls: scan callee function_ids for other class names in this file
674
+ def _is_class_like(name: str) -> bool:
675
+ stripped = name.lstrip("_")
676
+ return bool(stripped) and stripped[0].isupper()
677
+
678
+ intra_calls: dict[str, list[str]] = defaultdict(list)
679
+ for cn in all_class_names:
680
+ seen_callees: set[str] = set()
681
+ all_fns_in_class = (
682
+ class_buckets[cn]["added"]
683
+ + class_buckets[cn]["modified"]
684
+ + class_buckets[cn]["removed"]
685
+ )
686
+ for fn in all_fns_in_class:
687
+ fn_calls = (
688
+ list(getattr(fn, "new_calls", []))
689
+ + list(getattr(fn, "existing_calls", []))
690
+ + list(getattr(fn, "calls_added_new", []))
691
+ + list(getattr(fn, "calls_added_existing", []))
692
+ )
693
+ for call_id in fn_calls:
694
+ parts_c = call_id.split(".")
695
+ if len(parts_c) >= 2:
696
+ potential = parts_c[-2]
697
+ if (
698
+ potential in all_class_names
699
+ and potential != cn
700
+ and potential not in seen_callees
701
+ and _is_class_like(potential)
702
+ ):
703
+ seen_callees.add(potential)
704
+ intra_calls[cn].append(potential)
705
+
706
+ # Merge into per-class relation list: [(rel_type, target), ...]
707
+ class_relations: dict[str, list[tuple[str, str]]] = defaultdict(list)
708
+ for cn, parents in intra_inherit.items():
709
+ for p in sorted(set(parents)):
710
+ class_relations[cn].append(("inherits", p))
711
+ for cn, callees in intra_calls.items():
712
+ for c in sorted(set(callees)):
713
+ # Skip if already listed as inheritance (avoids duplication
714
+ # when a class both inherits and calls methods of the parent)
715
+ if not any(r == "inherits" and t == c for r, t in class_relations[cn]):
716
+ class_relations[cn].append(("calls", c))
717
+
718
+ # ── Build content per class ───────────────────────────────────────────────
719
+ def _build_class_text(
720
+ bucket: dict,
721
+ use_short_name: bool = False,
722
+ relations: list[tuple[str, str]] | None = None,
723
+ ) -> "Text | Panel | Group":
724
+ """Render the methods in one class bucket, optionally prefixed with
725
+ a dim relationship section listing intra-file calls/inheritance."""
726
+
727
+ def label(fn: object) -> str:
728
+ return _name(getattr(fn, "function_id", "")) if use_short_name else _display_name(fn) # type: ignore[arg-type]
729
+
730
+ # ── Added + modified ──────────────────────────────────────────────
731
+ text = Text(justify="left")
732
+ first = True
733
+
734
+ # Relationship section at the top of each class box
735
+ if relations:
736
+ for rel_type, target in relations:
737
+ if not first:
738
+ text.append("\n")
739
+ first = False
740
+ text.append(f"{rel_type} ", style="dim")
741
+ text.append(target, style="dim italic")
742
+ text.append("\n")
743
+ text.append("──────────", style="dim")
744
+
745
+ for fn in bucket["added"]:
746
+ d = 0 if use_short_name else depth.get(fn.function_id, 0)
747
+ if not first:
748
+ text.append("\n" if use_short_name else ("\n\n" if d == 0 else "\n"))
749
+ first = False
750
+ chain_color = color_map.get(fn.function_id)
751
+ name_style = f"bold {chain_color}" if chain_color else "bold"
752
+ if d == 0:
753
+ text.append("+ ", style="bold green")
754
+ else:
755
+ text.append(" " * d)
756
+ text.append("→ ", style="dim green")
757
+ text.append(label(fn), style=name_style)
758
+ if fn.is_entry_point:
759
+ text.append(" entry point", style="dim")
760
+
761
+ for fn in bucket["modified"]:
762
+ if not first:
763
+ text.append("\n")
764
+ first = False
765
+ text.append("~ ", style="bold yellow")
766
+ chain_color = color_map.get(fn.function_id)
767
+ text.append(label(fn), style=chain_color if chain_color else "default")
768
+ if fn.signature_changed:
769
+ text.append(" sig changed", style="dim")
770
+ elif fn.calls_added_new or fn.calls_added_existing or fn.calls_removed:
771
+ text.append(" calls changed", style="dim")
772
+ else:
773
+ text.append(" body changed", style="dim")
774
+
775
+ # ── Removed → red "deleted" sub-panel ────────────────────────────
776
+ if not bucket["removed"]:
777
+ return text
778
+
779
+ removed_text = Text(justify="left")
780
+ for i, fn in enumerate(bucket["removed"]):
781
+ if i:
782
+ removed_text.append("\n")
783
+ removed_text.append("- ", style="bold red")
784
+ chain_color = color_map.get(fn.function_id)
785
+ removed_text.append(label(fn), style=chain_color if chain_color else "default")
786
+
787
+ deleted_panel = Panel(
788
+ removed_text,
789
+ title="[bold red]deleted[/bold red]",
790
+ box=_CLASS_BOX,
791
+ border_style="red",
792
+ padding=(0, 1),
793
+ expand=True,
794
+ )
795
+
796
+ # If there were added/modified entries above, stack with spacing
797
+ if not first:
798
+ return Group(text, deleted_panel)
799
+ return deleted_panel
800
+
801
+ # ── Assemble renderables ──────────────────────────────────────────────────
802
+ parts: list = []
803
+ for cn in ordered_classes:
804
+ bucket = class_buckets[cn]
805
+ if cn is None:
806
+ # Standalone functions — no sub-box, use full display name
807
+ parts.append(_build_class_text(bucket, use_short_name=False))
808
+ else:
809
+ # Class methods — dashed sub-panel.
810
+ panel = Panel(
811
+ _build_class_text(bucket, use_short_name=True, relations=class_relations.get(cn)),
812
+ title=f"[dim italic]{cn}[/dim italic]",
813
+ box=_CLASS_BOX,
814
+ border_style="grey50",
815
+ padding=(0, 1),
816
+ expand=True,
817
+ )
818
+ parts.append(panel)
819
+
820
+ content = Group(*parts) if len(parts) > 1 else (parts[0] if parts else Text())
821
+
822
+ return Panel(
823
+ content,
824
+ title=f"[dim]{file_path}[/dim]",
825
+ border_style="grey50",
826
+ padding=(1, 1), # top=1 gives the breathing room previously added via Text("")
827
+ expand=False,
828
+ )
829
+
830
+
831
+ def _arrow_cell(
832
+ callee_ids: list[str],
833
+ color_map: dict[str, str],
834
+ reverse: bool = False,
835
+ has_calls: bool = True,
836
+ has_inherits: bool = False,
837
+ inherit_reverse: bool = False,
838
+ ) -> Text:
839
+ """Arrow(s) between two connected panels, each labeled with its type.
840
+
841
+ All arrows share the same shape (────▶ / ◀────); the label above
842
+ distinguishes the relationship type so new types can be added easily.
843
+ """
844
+ cell = Text(justify="center")
845
+ first = True
846
+
847
+ if has_calls:
848
+ call_color = "dim green"
849
+ for fid in callee_ids:
850
+ c = color_map.get(fid)
851
+ if c:
852
+ call_color = c
853
+ break
854
+ if not first:
855
+ cell.append("\n")
856
+ first = False
857
+ cell.append("calls\n", style="dim")
858
+ cell.append("◀────" if reverse else "────▶", style=call_color)
859
+
860
+ if has_inherits:
861
+ if not first:
862
+ cell.append("\n")
863
+ cell.append("inherits\n", style="dim")
864
+ cell.append("◀────" if inherit_reverse else "────▶", style="dim blue")
865
+
866
+ return cell