debtector 0.4.1__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.
debtector/cli.py ADDED
@@ -0,0 +1,1435 @@
1
+ """
2
+ CLI para Debtector.
3
+
4
+ Uso:
5
+ debtector index ./mi-proyecto
6
+ debtector --json search "UserService"
7
+ debtector summary src/auth/service.py
8
+ debtector impact src/auth/service.py
9
+ debtector imports flask
10
+ debtector status
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import datetime
17
+ import json
18
+ import sys
19
+ import time
20
+ from pathlib import Path
21
+
22
+ import structlog
23
+
24
+ from .config import Severity, load_config
25
+ from .git_history import (
26
+ compute_bus_factor,
27
+ compute_hotspots,
28
+ compute_temporal_coupling,
29
+ )
30
+ from .graph_store import GraphStore
31
+ from .indexer import Indexer
32
+ from .logging import configure_logging
33
+ from .metrics import compute_metrics, find_cycles, god_modules
34
+ from .models import node_to_dict
35
+
36
+ log = structlog.get_logger()
37
+
38
+ # ──────────────────────────────────────────────
39
+ # Helpers
40
+ # ──────────────────────────────────────────────
41
+
42
+
43
+ def _debtector_dir(project: str) -> Path:
44
+ """Return the ``.debtector/`` directory for *project*, creating it if needed.
45
+
46
+ Args:
47
+ project: Path to the project root.
48
+
49
+ Returns:
50
+ A :class:`~pathlib.Path` pointing to ``{project}/.debtector/``.
51
+ """
52
+ d = Path(project) / ".debtector"
53
+ d.mkdir(parents=True, exist_ok=True)
54
+ gitignore = d / ".gitignore"
55
+ gitignore.write_text(
56
+ "# Managed by debtector — do not edit manually\n*\n!.gitignore\n!baseline.json\n",
57
+ encoding="utf-8",
58
+ )
59
+ return d
60
+
61
+
62
+ def _auto_index(project: str) -> None:
63
+ """Index the project silently before running analysis commands.
64
+
65
+ Uses SHA-256 change detection: if no files have changed since the last
66
+ index run, this is effectively a no-op. All output goes to the log file;
67
+ nothing is printed to stdout.
68
+
69
+ Args:
70
+ project: Path to the project root directory.
71
+ """
72
+ try:
73
+ indexer = Indexer(project)
74
+ indexer.index(project)
75
+ except Exception: # noqa: BLE001
76
+ # Never let a failed auto-index abort the analysis command that called it.
77
+ log.warning("auto_index_failed", project=project, exc_info=True)
78
+
79
+
80
+ def _get_store(project: str) -> GraphStore:
81
+ """Open the :class:`~debtector.graph_store.GraphStore` for *project*.
82
+
83
+ The SQLite database lives at ``{project}/.debtector/index.db``.
84
+
85
+ Args:
86
+ project: Path to the project root directory.
87
+
88
+ Returns:
89
+ An open :class:`~debtector.graph_store.GraphStore` instance.
90
+ """
91
+ db_path = _debtector_dir(project) / "index.db"
92
+ return GraphStore(str(db_path))
93
+
94
+
95
+ def _json_out(data) -> None:
96
+ """Print *data* as compact JSON to stdout.
97
+
98
+ Args:
99
+ data: Any JSON-serialisable object.
100
+ """
101
+ print(json.dumps(data, default=str))
102
+
103
+
104
+ # ──────────────────────────────────────────────
105
+ # Subcomandos
106
+ # ──────────────────────────────────────────────
107
+
108
+
109
+ def cmd_index(args) -> None:
110
+ """Run the indexer on a project directory and print a summary.
111
+
112
+ Args:
113
+ args: Parsed argument namespace. Expected attributes:
114
+
115
+ - ``project`` (str): Root directory where ``.debtector/`` is stored.
116
+ - ``path`` (str): Directory tree to scan and index.
117
+ - ``json`` (bool): Emit JSON instead of human-readable text.
118
+ """
119
+ store = _get_store(args.project)
120
+ indexer = Indexer(store)
121
+
122
+ if not args.json:
123
+ print(f"Indexando {args.path}...")
124
+
125
+ stats = indexer.index(args.path)
126
+ store.close()
127
+
128
+ if args.json:
129
+ _json_out(stats)
130
+ else:
131
+ print(f"\n Archivos escaneados: {stats['scanned']}")
132
+ print(f" Indexados: {stats['indexed']}")
133
+ print(f" Sin cambios: {stats['skipped']}")
134
+ print(f" Errores: {stats['errors']}")
135
+ print(f" Eliminados: {stats['removed']}")
136
+
137
+
138
+ def cmd_search(args) -> None:
139
+ """Search the index for symbols matching a query and print results.
140
+
141
+ Args:
142
+ args: Parsed argument namespace. Expected attributes:
143
+
144
+ - ``project`` (str): Path to the project root.
145
+ - ``query`` (str): Free-text search query.
146
+ - ``kind`` (str | None): Optional node kind filter (e.g. ``"Class"``).
147
+ - ``json`` (bool): Emit JSON instead of human-readable text.
148
+ """
149
+ store = _get_store(args.project)
150
+ results = store.search_nodes(args.query, kind=args.kind)
151
+ store.close()
152
+
153
+ if args.json:
154
+ _json_out([node_to_dict(n) for n in results])
155
+ else:
156
+ print(f"\nResultados para: '{args.query}'")
157
+ print("─" * 60)
158
+ for n in results:
159
+ print(f" {n.kind:10s} {n.qualified_name}")
160
+ if n.signature:
161
+ print(f" {n.signature}")
162
+ print()
163
+ print(f"Total: {len(results)}")
164
+
165
+
166
+ def cmd_summary(args) -> None:
167
+ """Print a structural summary (symbols and edges) for a single file.
168
+
169
+ Exits with status 1 if the file is not found in the index.
170
+
171
+ Args:
172
+ args: Parsed argument namespace. Expected attributes:
173
+
174
+ - ``project`` (str): Path to the project root.
175
+ - ``file`` (str): Relative path of the file to summarise.
176
+ - ``json`` (bool): Emit JSON instead of human-readable text.
177
+ """
178
+ _auto_index(args.project)
179
+ store = _get_store(args.project)
180
+ summary = store.get_file_summary(args.file)
181
+ store.close()
182
+
183
+ if not summary:
184
+ if args.json:
185
+ _json_out({"error": f"file not found: {args.file}"})
186
+ else:
187
+ print(f"Archivo no encontrado: {args.file}")
188
+ sys.exit(1)
189
+
190
+ if args.json:
191
+ _json_out(summary)
192
+ else:
193
+ print(f"\n{summary['path']} ({summary['language']})")
194
+ print("─" * 60)
195
+ if summary["nodes"]:
196
+ print("\n Símbolos:")
197
+ for s in summary["nodes"]:
198
+ parent = " └─ " if s["parent"] else " "
199
+ print(f" {parent}{s['kind']:10s} {s.get('signature') or s['name']}")
200
+ if summary["edges"]:
201
+ print("\n Relaciones:")
202
+ for e in summary["edges"]:
203
+ print(f" {e['kind']:15s} {e['source']} → {e['target']}")
204
+
205
+
206
+ def cmd_impact(args) -> None:
207
+ """Perform an impact-radius analysis and print affected files and nodes.
208
+
209
+ Args:
210
+ args: Parsed argument namespace. Expected attributes:
211
+
212
+ - ``project`` (str): Path to the project root.
213
+ - ``files`` (list[str]): List of changed file paths (seeds).
214
+ - ``depth`` (int): Maximum traversal depth.
215
+ - ``json`` (bool): Emit JSON instead of human-readable text.
216
+ """
217
+ _auto_index(args.project)
218
+ store = _get_store(args.project)
219
+ result = store.get_impact_radius(args.files, max_depth=args.depth)
220
+ store.close()
221
+
222
+ if args.json:
223
+ _json_out(
224
+ {
225
+ "changed_nodes": [n.qualified_name for n in result["changed_nodes"]],
226
+ "impacted_nodes": [node_to_dict(n) for n in result["impacted_nodes"]],
227
+ "impacted_files": sorted(result["impacted_files"]),
228
+ }
229
+ )
230
+ else:
231
+ print(f"\nAnálisis de impacto (profundidad {args.depth}):")
232
+ print("─" * 60)
233
+ print(f"\n Nodos cambiados: {len(result['changed_nodes'])}")
234
+ print(f" Nodos impactados: {len(result['impacted_nodes'])}")
235
+ print(f" Archivos afectados: {len(result['impacted_files'])}")
236
+ if result["impacted_files"]:
237
+ print("\n Archivos impactados:")
238
+ for f in sorted(result["impacted_files"]):
239
+ print(f" {f}")
240
+ if result["impacted_nodes"]:
241
+ print("\n Nodos impactados:")
242
+ for n in result["impacted_nodes"][:20]:
243
+ print(f" {n.kind:10s} {n.qualified_name}")
244
+ if len(result["impacted_nodes"]) > 20:
245
+ print(f" ... y {len(result['impacted_nodes']) - 20} más")
246
+
247
+
248
+ def cmd_imports(args) -> None:
249
+ """Search for files that import a given module and print results.
250
+
251
+ Args:
252
+ args: Parsed argument namespace. Expected attributes:
253
+
254
+ - ``project`` (str): Path to the project root.
255
+ - ``module`` (str): Module name substring to search for.
256
+ - ``json`` (bool): Emit JSON instead of human-readable text.
257
+ """
258
+ _auto_index(args.project)
259
+ store = _get_store(args.project)
260
+ results = store.search_imports(args.module)
261
+ store.close()
262
+
263
+ if args.json:
264
+ _json_out(results)
265
+ else:
266
+ print(f"\nArchivos que importan '{args.module}':")
267
+ print("─" * 60)
268
+ for r in results:
269
+ print(f" {r['file_path']} (línea {r['line']})")
270
+ print(f"\nTotal: {len(results)}")
271
+
272
+
273
+ def cmd_status(args) -> None:
274
+ """Print index statistics (file count, node/edge counts, breakdown by kind).
275
+
276
+ Args:
277
+ args: Parsed argument namespace. Expected attributes:
278
+
279
+ - ``project`` (str): Path to the project root.
280
+ - ``json`` (bool): Emit JSON instead of human-readable text.
281
+ """
282
+ store = _get_store(args.project)
283
+ stats = store.get_stats()
284
+ store.close()
285
+
286
+ if args.json:
287
+ _json_out(
288
+ {
289
+ "files": stats.files_count,
290
+ "total_nodes": stats.total_nodes,
291
+ "total_edges": stats.total_edges,
292
+ "languages": stats.languages,
293
+ "nodes_by_kind": stats.nodes_by_kind,
294
+ "edges_by_kind": stats.edges_by_kind,
295
+ "embeddings_count": stats.embeddings_count,
296
+ }
297
+ )
298
+ else:
299
+ print("\nEstado del índice:")
300
+ print("─" * 40)
301
+ print(f" Archivos: {stats.files_count}")
302
+ print(f" Nodos: {stats.total_nodes}")
303
+ print(f" Aristas: {stats.total_edges}")
304
+ print(f" Embeddings: {stats.embeddings_count}")
305
+ print(f" Lenguajes: {', '.join(stats.languages)}")
306
+ if stats.nodes_by_kind:
307
+ print("\n Nodos por tipo:")
308
+ for k, v in stats.nodes_by_kind.items():
309
+ print(f" {k:12s} {v}")
310
+ if stats.edges_by_kind:
311
+ print("\n Aristas por tipo:")
312
+ for k, v in stats.edges_by_kind.items():
313
+ print(f" {k:15s} {v}")
314
+
315
+
316
+ def cmd_semantic(args) -> None:
317
+ """[DEPRECADO] Búsqueda semántica por concepto.
318
+
319
+ Este comando está congelado. La búsqueda semántica (embeddings + sqlite-vec)
320
+ no forma parte del objetivo actual de debtector (análisis de acoplamiento para CI/PR).
321
+ El código se conserva pero no se desarrollará más.
322
+
323
+ Instala ``debtector[semantic]`` si necesitas usar esta funcionalidad.
324
+
325
+ Args:
326
+ args: Parsed argument namespace. Expected attributes:
327
+
328
+ - ``project`` (str): Path to the project root.
329
+ - ``query`` (str): Natural-language search string.
330
+ - ``limit`` (int): Maximum number of results.
331
+ - ``json`` (bool): Emit JSON instead of human-readable text.
332
+ """
333
+ msg = (
334
+ "El comando 'semantic' está deprecado y congelado.\n"
335
+ "La búsqueda semántica no forma parte del objetivo actual de debtector.\n"
336
+ "Si aún necesitas esta funcionalidad: uv add 'debtector[semantic]'"
337
+ )
338
+ if args.json:
339
+ _json_out({"error": msg})
340
+ else:
341
+ print(f"DEPRECADO: {msg}", file=sys.stderr)
342
+ sys.exit(1)
343
+
344
+
345
+ def cmd_callers(args) -> None:
346
+ """Print all callers of a given symbol (by qualified name).
347
+
348
+ Args:
349
+ args: Parsed argument namespace. Expected attributes:
350
+
351
+ - ``project`` (str): Path to the project root.
352
+ - ``qualified_name`` (str): The qualified name of the target symbol.
353
+ - ``json`` (bool): Emit JSON instead of human-readable text.
354
+ """
355
+ _auto_index(args.project)
356
+ store = _get_store(args.project)
357
+ callers = store.callers_of(args.qualified_name)
358
+ store.close()
359
+
360
+ if args.json:
361
+ _json_out([node_to_dict(n) for n in callers])
362
+ else:
363
+ print(f"\n¿Quién llama a {args.qualified_name}?")
364
+ print("─" * 60)
365
+ for n in callers:
366
+ print(f" {n.kind:10s} {n.qualified_name}")
367
+ print(f" {n.file_path}:{n.line_start}")
368
+ print(f"\nTotal: {len(callers)}")
369
+
370
+
371
+ def cmd_untested(args) -> None:
372
+ """List production symbols (Function/Method) that have no COVERS edge.
373
+
374
+ Args:
375
+ args: Parsed argument namespace. Expected attributes:
376
+
377
+ - ``project`` (str): Path to the project root.
378
+ - ``path`` (str | None): Optional file or directory prefix to filter results.
379
+ - ``json`` (bool): Emit JSON instead of human-readable text.
380
+ """
381
+ _auto_index(args.project)
382
+ store = _get_store(args.project)
383
+ symbols = store.get_uncovered_symbols(path_filter=args.path or None)
384
+ store.close()
385
+
386
+ if args.json:
387
+ _json_out([node_to_dict(n) for n in symbols])
388
+ else:
389
+ if not symbols:
390
+ print("✓ All symbols are covered.")
391
+ return
392
+ print(f"\nSímbolos sin test ({len(symbols)}):")
393
+ print("─" * 60)
394
+ for n in symbols:
395
+ print(f" {n.kind:10s} {n.name}")
396
+ print(f" {n.file_path}:{n.line_start}")
397
+
398
+
399
+ # ──────────────────────────────────────────────
400
+ # ──────────────────────────────────────────────
401
+ # Baseline
402
+ # ──────────────────────────────────────────────
403
+
404
+ _BASELINE_FILE = ".debtector/baseline.json"
405
+ # Tolerancia de inestabilidad: diferencia mínima para considerar una regresión.
406
+ # Un delta < 5% se trata como ruido de redondeo, no como degradación real.
407
+ _INSTABILITY_TOLERANCE = 0.05
408
+
409
+
410
+ def _baseline_path(project: str) -> Path:
411
+ return Path(project) / _BASELINE_FILE
412
+
413
+
414
+ def _blocks(issues: list, severity: Severity) -> bool:
415
+ """Return True if *issues* are non-empty and *severity* is ERROR."""
416
+ return bool(issues) and severity == Severity.ERROR
417
+
418
+
419
+ def _warns(issues: list, severity: Severity) -> bool:
420
+ """Return True if *issues* are non-empty and *severity* is ERROR or WARNING."""
421
+ return bool(issues) and severity in (Severity.ERROR, Severity.WARNING)
422
+
423
+
424
+ def cmd_baseline(args) -> None:
425
+ """Save or compare coupling metrics against a stored baseline.
426
+
427
+ Sub-commands:
428
+
429
+ * ``save`` — snapshot current metrics to ``.debtector/baseline.json``.
430
+ * ``status`` — compare current metrics to the baseline and report regressions.
431
+
432
+ Args:
433
+ args: Parsed argument namespace. Expected attributes:
434
+
435
+ - ``project`` (str): Path to the project root.
436
+ - ``baseline_cmd`` (str): ``"save"`` or ``"status"``.
437
+ - ``json`` (bool): Emit JSON instead of human-readable text.
438
+ """
439
+ if args.baseline_cmd == "save":
440
+ _baseline_save(args)
441
+ elif args.baseline_cmd == "status":
442
+ _baseline_status(args)
443
+ else:
444
+ print("Uso: debtector baseline <save|status>", file=sys.stderr)
445
+ sys.exit(1)
446
+
447
+
448
+ def _baseline_save(args) -> None:
449
+ """Snapshot current metrics to ``.debtector/baseline.json``."""
450
+ cfg = load_config(args.project)
451
+ store = _get_store(args.project)
452
+ modules = compute_metrics(store)
453
+ cycles = find_cycles(store)
454
+ gods = god_modules(store, percentile=cfg.metrics.thresholds.god_module_percentile)
455
+ store.close()
456
+
457
+ snapshot = {
458
+ "saved_at": datetime.datetime.now(datetime.UTC).isoformat(),
459
+ "modules": [
460
+ {
461
+ "file_path": m.file_path,
462
+ "fan_in": round(m.fan_in, 3),
463
+ "fan_out": round(m.fan_out, 3),
464
+ "instability": round(m.instability, 4),
465
+ }
466
+ for m in modules
467
+ ],
468
+ "cycles": cycles,
469
+ "god_modules": [m.file_path for m in gods],
470
+ }
471
+
472
+ path = _baseline_path(args.project)
473
+ path.parent.mkdir(parents=True, exist_ok=True)
474
+ path.write_text(json.dumps(snapshot, indent=2), encoding="utf-8")
475
+
476
+ if args.json:
477
+ _json_out({"status": "saved", "path": str(path), "modules": len(modules)})
478
+ else:
479
+ print(f"Baseline guardado: {path} ({len(modules)} módulos)")
480
+
481
+
482
+ def _baseline_status(args) -> None:
483
+ """Compare current metrics to the stored baseline and report regressions.
484
+
485
+ Each issue type (cycles, god_modules, instability) is filtered through the
486
+ severity configured in ``debtector.toml``:
487
+
488
+ - ``error`` — contributes to exit code 1 (blocks CI).
489
+ - ``warning`` — printed but does not block CI (exit 0).
490
+ - ``info`` — silent; neither printed nor blocking.
491
+ """
492
+ path = _baseline_path(args.project)
493
+
494
+ if not path.exists():
495
+ if args.json:
496
+ _json_out({"error": "no baseline — ejecuta: debtector baseline save"})
497
+ else:
498
+ print("Sin baseline. Ejecuta primero: debtector baseline save")
499
+ return
500
+
501
+ baseline = json.loads(path.read_text(encoding="utf-8"))
502
+ baseline_cycles = [frozenset(c) for c in baseline.get("cycles", [])]
503
+ baseline_gods = set(baseline.get("god_modules", []))
504
+
505
+ cfg = load_config(args.project)
506
+ sev = cfg.metrics.severity
507
+ store = _get_store(args.project)
508
+ current_modules = compute_metrics(store)
509
+ current_cycles = find_cycles(store)
510
+ current_gods = god_modules(store, percentile=cfg.metrics.thresholds.god_module_percentile)
511
+ store.close()
512
+
513
+ # Detectar regresiones por tipo
514
+ new_cycles = [c for c in current_cycles if frozenset(c) not in baseline_cycles]
515
+ new_gods = [m.file_path for m in current_gods if m.file_path not in baseline_gods]
516
+
517
+ regressions: list[dict] = []
518
+ baseline_map = {m["file_path"]: m for m in baseline.get("modules", [])}
519
+ for m in current_modules:
520
+ prev = baseline_map.get(m.file_path)
521
+ if prev is None:
522
+ continue
523
+ if m.instability > prev["instability"] + _INSTABILITY_TOLERANCE:
524
+ regressions.append(
525
+ {
526
+ "file_path": m.file_path,
527
+ "metric": "instability",
528
+ "before": prev["instability"],
529
+ "after": round(m.instability, 4),
530
+ }
531
+ )
532
+
533
+ # Determinar si cada tipo de regresión bloquea el CI según su severidad
534
+ has_blocking = (
535
+ _blocks(new_cycles, sev.cycles)
536
+ or _blocks(new_gods, sev.god_modules)
537
+ or _blocks(regressions, sev.instability)
538
+ )
539
+
540
+ if args.json:
541
+ _json_out(
542
+ {
543
+ "regressions": regressions,
544
+ "new_cycles": new_cycles,
545
+ "new_god_modules": new_gods,
546
+ }
547
+ )
548
+ if has_blocking:
549
+ sys.exit(1)
550
+ return
551
+
552
+ has_any_warning = (
553
+ _warns(new_cycles, sev.cycles)
554
+ or _warns(new_gods, sev.god_modules)
555
+ or _warns(regressions, sev.instability)
556
+ )
557
+
558
+ reporter = getattr(args, "reporter", None)
559
+
560
+ if not has_any_warning:
561
+ print("✓ Sin cambios respecto al baseline")
562
+ return
563
+
564
+ if reporter == "github":
565
+ _emit_github_annotations(new_cycles, new_gods, regressions, sev)
566
+ elif reporter == "gitlab":
567
+ _emit_gitlab_report(new_cycles, new_gods, regressions, sev)
568
+ else:
569
+ if _warns(new_cycles, sev.cycles):
570
+ label = "⛔" if sev.cycles == Severity.ERROR else "⚠"
571
+ print(f"\n{label} Nuevos ciclos ({len(new_cycles)}):")
572
+ for cycle in new_cycles:
573
+ print(" " + " → ".join(cycle) + " → ...")
574
+
575
+ if _warns(new_gods, sev.god_modules):
576
+ label = "⛔" if sev.god_modules == Severity.ERROR else "⚠"
577
+ print(f"\n{label} Nuevos god modules ({len(new_gods)}):")
578
+ for path_str in new_gods:
579
+ print(f" {path_str}")
580
+
581
+ if _warns(regressions, sev.instability):
582
+ label = "⛔" if sev.instability == Severity.ERROR else "⚠"
583
+ print(f"\n{label} Regresiones de inestabilidad ({len(regressions)}):")
584
+ for r in regressions:
585
+ print(f" {r['file_path']} I: {r['before']:.3f} → {r['after']:.3f}")
586
+
587
+ if has_blocking:
588
+ sys.exit(1)
589
+
590
+
591
+ def _annotation_level(severity: Severity) -> str:
592
+ """Map a :class:`Severity` to its GitHub Annotation level string."""
593
+ return "error" if severity == Severity.ERROR else "warning"
594
+
595
+
596
+ def _safe_annotation_path(path: str) -> str:
597
+ """Sanitize a file path for use in a GitHub Actions annotation.
598
+
599
+ GitHub's ``::level file=<path>,...::`` format uses ``::`` as a delimiter.
600
+ If a path contains ``::`` (e.g. a Debtector qualified_name), the annotation
601
+ would be malformed. Replace any occurrence with ``/`` to keep it readable.
602
+
603
+ Args:
604
+ path: Raw file path or qualified_name string.
605
+
606
+ Returns:
607
+ Path safe to embed inside a GitHub annotation parameter value.
608
+ """
609
+ return path.replace("::", "/")
610
+
611
+
612
+ def _emit_github_annotations(
613
+ new_cycles: list,
614
+ new_gods: list,
615
+ regressions: list,
616
+ sev,
617
+ ) -> None:
618
+ """Print GitHub Actions workflow commands for each regression.
619
+
620
+ Format: ``::level file=<path>,line=1::<message>``
621
+
622
+ Args:
623
+ new_cycles: List of cycle node lists.
624
+ new_gods: List of god module file paths.
625
+ regressions: List of instability regression dicts.
626
+ sev: :class:`~debtector.config.MetricsSeverity` instance.
627
+ """
628
+ if _warns(new_cycles, sev.cycles):
629
+ level = _annotation_level(sev.cycles)
630
+ for cycle in new_cycles:
631
+ safe_path = _safe_annotation_path(cycle[0])
632
+ msg = f"Ciclo de importación: {' → '.join(cycle)}"
633
+ print(f"::{level} file={safe_path},line=1::{msg}")
634
+
635
+ if _warns(new_gods, sev.god_modules):
636
+ level = _annotation_level(sev.god_modules)
637
+ for path_str in new_gods:
638
+ safe_path = _safe_annotation_path(path_str)
639
+ print(
640
+ f"::{level} file={safe_path},line=1::God module: Ca excede el percentil configurado"
641
+ )
642
+
643
+ if _warns(regressions, sev.instability):
644
+ level = _annotation_level(sev.instability)
645
+ for r in regressions:
646
+ safe_path = _safe_annotation_path(r["file_path"])
647
+ msg = f"Inestabilidad: {r['before']:.3f} → {r['after']:.3f}"
648
+ print(f"::{level} file={safe_path},line=1::{msg}")
649
+
650
+
651
+ def _emit_gitlab_report(
652
+ new_cycles: list,
653
+ new_gods: list,
654
+ regressions: list,
655
+ sev,
656
+ ) -> None:
657
+ """Print a GitLab CI–friendly report for each regression.
658
+
659
+ Uses GitLab's ``section_start``/``section_end`` markers for collapsible
660
+ log sections when issues are found.
661
+
662
+ Args:
663
+ new_cycles: List of cycle node lists.
664
+ new_gods: List of god module file paths.
665
+ regressions: List of instability regression dicts.
666
+ sev: :class:`~debtector.config.MetricsSeverity` instance.
667
+ """
668
+ ts = int(time.time())
669
+
670
+ if _warns(new_cycles, sev.cycles):
671
+ label = "ERROR" if sev.cycles == Severity.ERROR else "WARNING"
672
+ print(
673
+ f"\x1b[0Ksection_start:{ts}:cycles\r\x1b[0K[{label}] Nuevos ciclos ({len(new_cycles)})"
674
+ )
675
+ for cycle in new_cycles:
676
+ print(" " + " → ".join(cycle) + " → ...")
677
+ print(f"\x1b[0Ksection_end:{ts}:cycles\r\x1b[0K")
678
+
679
+ if _warns(new_gods, sev.god_modules):
680
+ label = "ERROR" if sev.god_modules == Severity.ERROR else "WARNING"
681
+ print(
682
+ f"\x1b[0Ksection_start:{ts}:god_modules\r\x1b[0K"
683
+ f"[{label}] Nuevos god modules ({len(new_gods)})"
684
+ )
685
+ for path_str in new_gods:
686
+ print(f" {path_str}")
687
+ print(f"\x1b[0Ksection_end:{ts}:god_modules\r\x1b[0K")
688
+
689
+ if _warns(regressions, sev.instability):
690
+ label = "ERROR" if sev.instability == Severity.ERROR else "WARNING"
691
+ print(
692
+ f"\x1b[0Ksection_start:{ts}:instability\r\x1b[0K"
693
+ f"[{label}] Regresiones de inestabilidad ({len(regressions)})"
694
+ )
695
+ for r in regressions:
696
+ print(f" {r['file_path']} I: {r['before']:.3f} → {r['after']:.3f}")
697
+ print(f"\x1b[0Ksection_end:{ts}:instability\r\x1b[0K")
698
+
699
+
700
+ # ──────────────────────────────────────────────
701
+ # Acoplamiento estructural (ex-metrics)
702
+ # ──────────────────────────────────────────────
703
+
704
+
705
+ def cmd_coupling(args) -> None:
706
+ """Print structural coupling metrics (Ca, Ce, I, cycles, god modules).
707
+
708
+ Reads ``debtector.toml`` from the project root to apply configured
709
+ thresholds. With ``--json`` emits a single JSON object with keys
710
+ ``modules``, ``cycles``, and ``god_modules``.
711
+
712
+ Args:
713
+ args: Parsed argument namespace. Expected attributes:
714
+
715
+ - ``project`` (str): Path to the project root.
716
+ - ``json`` (bool): Emit JSON instead of human-readable text.
717
+ - ``sort`` (str): Column to sort by (``fan_in``, ``fan_out``,
718
+ ``instability``). Default: ``fan_in``.
719
+ - ``limit`` (int | None): Max rows to show. ``None`` = all.
720
+ """
721
+ _auto_index(args.project)
722
+ cfg = load_config(args.project)
723
+ store = _get_store(args.project)
724
+ modules = compute_metrics(store)
725
+ cycles = find_cycles(store)
726
+ gods = god_modules(store, percentile=cfg.metrics.thresholds.god_module_percentile)
727
+ store.close()
728
+
729
+ god_paths = {m.file_path for m in gods}
730
+
731
+ if args.json:
732
+ _json_out(
733
+ {
734
+ "modules": [
735
+ {
736
+ "file_path": m.file_path,
737
+ "fan_in": round(m.fan_in, 2),
738
+ "fan_out": round(m.fan_out, 2),
739
+ "instability": round(m.instability, 3),
740
+ "god_module": m.file_path in god_paths,
741
+ }
742
+ for m in modules
743
+ ],
744
+ "cycles": cycles,
745
+ "god_modules": [m.file_path for m in gods],
746
+ }
747
+ )
748
+ return
749
+
750
+ if not modules:
751
+ print("Sin datos — ejecuta primero: debtector index <directorio>")
752
+ return
753
+
754
+ # Ordenar
755
+ sort_key = getattr(args, "sort", "fan_in")
756
+ modules_sorted = sorted(modules, key=lambda m: getattr(m, sort_key, 0), reverse=True)
757
+ if args.limit:
758
+ modules_sorted = modules_sorted[: args.limit]
759
+
760
+ # Cabecera
761
+ col_w = max((len(m.file_path) for m in modules_sorted), default=30)
762
+ col_w = max(col_w, 30)
763
+ header = f"{'Módulo':<{col_w}} {'Ca':>6} {'Ce':>6} {'I':>6} {'Flags'}"
764
+ print()
765
+ print(header)
766
+ print("─" * len(header))
767
+
768
+ instability_warn = cfg.metrics.thresholds.instability_threshold
769
+ for m in modules_sorted:
770
+ flags = ""
771
+ if m.file_path in god_paths:
772
+ flags += " ● god"
773
+ if m.fan_in > 0 and m.instability >= instability_warn:
774
+ flags += " ⚠ inestable"
775
+ print(
776
+ f"{m.file_path:<{col_w}} {m.fan_in:>6.1f} {m.fan_out:>6.1f}"
777
+ f" {m.instability:>6.3f} {flags}"
778
+ )
779
+
780
+ print("─" * len(header))
781
+ print(f"Total: {len(modules)} módulos")
782
+
783
+ # Ciclos
784
+ if cycles:
785
+ print(f"\n⚠ Ciclos detectados ({len(cycles)}):")
786
+ for cycle in cycles:
787
+ print(" " + " → ".join(cycle) + " → ...")
788
+ else:
789
+ print("\n✓ Sin ciclos")
790
+
791
+ # God modules
792
+ if gods:
793
+ print(f"\n● God modules (Ca > p{int(cfg.metrics.thresholds.god_module_percentile)}):")
794
+ for m in gods:
795
+ print(f" {m.file_path} Ca={m.fan_in:.1f}")
796
+
797
+
798
+ # Backward-compat alias — keeps existing imports and tests working
799
+ cmd_metrics = cmd_coupling
800
+
801
+
802
+ # ──────────────────────────────────────────────
803
+ # Git-coupling: behavioral analysis
804
+ # ──────────────────────────────────────────────
805
+
806
+
807
+ def cmd_hotspots(args) -> None:
808
+ """Print hotspot ranking: files with high churn × structural coupling.
809
+
810
+ Args:
811
+ args: Parsed argument namespace. Expected attributes:
812
+
813
+ - ``project`` (str): Path to the project root.
814
+ - ``json`` (bool): Emit JSON.
815
+ - ``limit`` (int | None): Max results.
816
+ - ``since`` (str | None): Date filter (e.g. ``"6 months ago"``).
817
+ - ``min_coupling`` (float): Minimum coupling to include. Default 0.
818
+ """
819
+ _auto_index(args.project)
820
+ store = _get_store(args.project)
821
+ hotspots = compute_hotspots(
822
+ store,
823
+ args.project,
824
+ since=getattr(args, "since", None),
825
+ limit=getattr(args, "limit", None),
826
+ )
827
+ store.close()
828
+
829
+ if args.json:
830
+ _json_out(
831
+ {
832
+ "hotspots": [
833
+ {
834
+ "file_path": h.file_path,
835
+ "churn": h.churn,
836
+ "coupling": round(h.coupling, 2),
837
+ "hotspot_score": round(h.hotspot_score, 2),
838
+ }
839
+ for h in hotspots
840
+ ]
841
+ }
842
+ )
843
+ return
844
+
845
+ if not hotspots:
846
+ print("Sin hotspots — ejecuta primero: debtector index <directorio>")
847
+ return
848
+
849
+ col_w = max((len(h.file_path) for h in hotspots), default=30)
850
+ col_w = max(col_w, 30)
851
+ header = f"{'Módulo':<{col_w}} {'Churn':>7} {'Coupling':>9} {'Score':>8}"
852
+ print()
853
+ print(header)
854
+ print("─" * len(header))
855
+ for h in hotspots:
856
+ print(f"{h.file_path:<{col_w}} {h.churn:>7} {h.coupling:>9.2f} {h.hotspot_score:>8.2f}")
857
+ print("─" * len(header))
858
+ print(f"Total: {len(hotspots)} hotspots")
859
+
860
+
861
+ def cmd_temporal_coupling(args) -> None:
862
+ """Print pairs of files that frequently change together.
863
+
864
+ Args:
865
+ args: Parsed argument namespace. Expected attributes:
866
+
867
+ - ``project`` (str): Path to the project root.
868
+ - ``json`` (bool): Emit JSON.
869
+ - ``limit`` (int | None): Max results.
870
+ - ``since`` (str | None): Date filter.
871
+ - ``min_shared`` (int): Minimum shared commits. Default 5.
872
+ - ``min_ratio`` (float): Minimum coupling ratio. Default 0.3.
873
+ """
874
+ pairs = compute_temporal_coupling(
875
+ args.project,
876
+ min_shared=getattr(args, "min_shared", 5),
877
+ min_ratio=getattr(args, "min_ratio", 0.3),
878
+ since=getattr(args, "since", None),
879
+ )
880
+
881
+ if args.json:
882
+ _json_out(
883
+ {
884
+ "temporal_coupling": [
885
+ {
886
+ "file_a": t.file_a,
887
+ "file_b": t.file_b,
888
+ "shared_commits": t.shared_commits,
889
+ "coupling_ratio": round(t.coupling_ratio, 4),
890
+ }
891
+ for t in pairs
892
+ ]
893
+ }
894
+ )
895
+ return
896
+
897
+ if not pairs:
898
+ print("Sin acoplamiento temporal detectado")
899
+ return
900
+
901
+ col_w = max(
902
+ (max(len(t.file_a), len(t.file_b)) for t in pairs),
903
+ default=30,
904
+ )
905
+ col_w = max(col_w, 25)
906
+ header = f"{'Archivo A':<{col_w}} {'Archivo B':<{col_w}} {'Commits':>7} {'Ratio':>6}"
907
+ print()
908
+ print(header)
909
+ print("─" * len(header))
910
+ limit = getattr(args, "limit", None)
911
+ shown = pairs[:limit] if limit else pairs
912
+ for t in shown:
913
+ print(
914
+ f"{t.file_a:<{col_w}} {t.file_b:<{col_w}}"
915
+ f" {t.shared_commits:>7} {t.coupling_ratio:>6.3f}"
916
+ )
917
+ print("─" * len(header))
918
+ print(f"Total: {len(pairs)} pares")
919
+
920
+
921
+ def cmd_bus_factor(args) -> None:
922
+ """Print bus-factor risk per file (knowledge concentration).
923
+
924
+ Args:
925
+ args: Parsed argument namespace. Expected attributes:
926
+
927
+ - ``project`` (str): Path to the project root.
928
+ - ``json`` (bool): Emit JSON.
929
+ - ``limit`` (int | None): Max results.
930
+ """
931
+ _auto_index(args.project)
932
+ store = _get_store(args.project)
933
+ results = compute_bus_factor(store, args.project)
934
+ store.close()
935
+
936
+ limit = getattr(args, "limit", None)
937
+ if limit:
938
+ results = results[:limit]
939
+
940
+ if args.json:
941
+ _json_out(
942
+ {
943
+ "bus_factor": [
944
+ {
945
+ "file_path": b.file_path,
946
+ "top_author": b.top_author,
947
+ "top_author_pct": round(b.top_author_pct, 1),
948
+ "bus_factor": b.bus_factor,
949
+ }
950
+ for b in results
951
+ ]
952
+ }
953
+ )
954
+ return
955
+
956
+ if not results:
957
+ print("Sin datos — ejecuta primero: debtector index <directorio>")
958
+ return
959
+
960
+ col_w = max((len(b.file_path) for b in results), default=30)
961
+ col_w = max(col_w, 30)
962
+ aut_w = max((len(b.top_author) for b in results), default=15)
963
+ aut_w = max(aut_w, 15)
964
+ header = f"{'Módulo':<{col_w}} {'Top autor':<{aut_w}} {'% líneas':>9} {'Bus factor':>10}"
965
+ print()
966
+ print(header)
967
+ print("─" * len(header))
968
+ for b in results:
969
+ risk = " ⚠" if b.bus_factor == 1 else ""
970
+ print(
971
+ f"{b.file_path:<{col_w}} {b.top_author:<{aut_w}}"
972
+ f" {b.top_author_pct:>8.1f}% {b.bus_factor:>10}{risk}"
973
+ )
974
+ print("─" * len(header))
975
+ print(f"Total: {len(results)} archivos analizados")
976
+
977
+
978
+ def cmd_git_coupling(args) -> None:
979
+ """Print all behavioral coupling metrics: hotspots, temporal coupling, bus factor.
980
+
981
+ Args:
982
+ args: Parsed argument namespace. Expected attributes:
983
+
984
+ - ``project`` (str): Path to the project root.
985
+ - ``json`` (bool): Emit JSON with keys hotspots, temporal_coupling, bus_factor.
986
+ - ``limit`` (int | None): Applied to hotspots and bus factor.
987
+ - ``since`` (str | None): Date filter for hotspots and temporal coupling.
988
+ - ``min_shared`` (int): Min shared commits for temporal coupling.
989
+ - ``min_ratio`` (float): Min ratio for temporal coupling.
990
+ """
991
+ _auto_index(args.project)
992
+ store = _get_store(args.project)
993
+ hotspots = compute_hotspots(
994
+ store,
995
+ args.project,
996
+ since=getattr(args, "since", None),
997
+ limit=getattr(args, "limit", None),
998
+ )
999
+ temporal = compute_temporal_coupling(
1000
+ args.project,
1001
+ min_shared=getattr(args, "min_shared", 5),
1002
+ min_ratio=getattr(args, "min_ratio", 0.3),
1003
+ since=getattr(args, "since", None),
1004
+ )
1005
+ bus = compute_bus_factor(store, args.project)
1006
+ store.close()
1007
+
1008
+ limit = getattr(args, "limit", None)
1009
+ if limit is not None:
1010
+ bus = bus[:limit]
1011
+
1012
+ if args.json:
1013
+ _json_out(
1014
+ {
1015
+ "hotspots": [
1016
+ {
1017
+ "file_path": h.file_path,
1018
+ "churn": h.churn,
1019
+ "coupling": round(h.coupling, 2),
1020
+ "hotspot_score": round(h.hotspot_score, 2),
1021
+ }
1022
+ for h in hotspots
1023
+ ],
1024
+ "temporal_coupling": [
1025
+ {
1026
+ "file_a": t.file_a,
1027
+ "file_b": t.file_b,
1028
+ "shared_commits": t.shared_commits,
1029
+ "coupling_ratio": round(t.coupling_ratio, 4),
1030
+ }
1031
+ for t in temporal
1032
+ ],
1033
+ "bus_factor": [
1034
+ {
1035
+ "file_path": b.file_path,
1036
+ "top_author": b.top_author,
1037
+ "top_author_pct": round(b.top_author_pct, 1),
1038
+ "bus_factor": b.bus_factor,
1039
+ }
1040
+ for b in bus
1041
+ ],
1042
+ }
1043
+ )
1044
+ return
1045
+
1046
+ # Human output: print each section
1047
+ _print_section("Hotspots", "─")
1048
+ if hotspots:
1049
+ col_w = max((len(h.file_path) for h in hotspots), default=30)
1050
+ col_w = max(col_w, 30)
1051
+ for h in hotspots:
1052
+ print(
1053
+ f" {h.file_path:<{col_w}} churn={h.churn} coupling={h.coupling:.2f}"
1054
+ f" score={h.hotspot_score:.2f}"
1055
+ )
1056
+ else:
1057
+ print(" (sin datos)")
1058
+
1059
+ _print_section("Acoplamiento temporal", "─")
1060
+ if temporal:
1061
+ for t in temporal:
1062
+ print(
1063
+ f" {t.file_a} ↔ {t.file_b}"
1064
+ f" ({t.shared_commits} commits, ratio={t.coupling_ratio:.3f})"
1065
+ )
1066
+ else:
1067
+ print(" (sin datos)")
1068
+
1069
+ _print_section("Bus factor", "─")
1070
+ if bus:
1071
+ for b in bus:
1072
+ risk = " ⚠" if b.bus_factor == 1 else ""
1073
+ print(
1074
+ f" {b.file_path} {b.top_author}"
1075
+ f" ({b.top_author_pct:.1f}%) bf={b.bus_factor}{risk}"
1076
+ )
1077
+ else:
1078
+ print(" (sin datos)")
1079
+
1080
+
1081
+ def _print_section(title: str, sep: str = "─") -> None:
1082
+ """Print a section header for human-readable output."""
1083
+ print(f"\n{'━' * 4} {title} {'━' * 4}")
1084
+
1085
+
1086
+ def cmd_report(args) -> None:
1087
+ """Print a full coupling report: structural (Ca/Ce/I) + behavioral (git).
1088
+
1089
+ Args:
1090
+ args: Parsed argument namespace. Accepts all flags from both
1091
+ ``coupling`` and ``git-coupling`` commands.
1092
+ """
1093
+ _auto_index(args.project)
1094
+
1095
+ # ── Structural coupling ──
1096
+ cfg = load_config(args.project)
1097
+ store = _get_store(args.project)
1098
+ modules = compute_metrics(store)
1099
+ cycles = find_cycles(store)
1100
+ gods = god_modules(store, percentile=cfg.metrics.thresholds.god_module_percentile)
1101
+ god_paths = {m.file_path for m in gods}
1102
+
1103
+ # ── Behavioral coupling ──
1104
+ hotspots = compute_hotspots(
1105
+ store,
1106
+ args.project,
1107
+ since=getattr(args, "since", None),
1108
+ limit=getattr(args, "limit", None),
1109
+ )
1110
+ temporal = compute_temporal_coupling(
1111
+ args.project,
1112
+ min_shared=getattr(args, "min_shared", 5),
1113
+ min_ratio=getattr(args, "min_ratio", 0.3),
1114
+ since=getattr(args, "since", None),
1115
+ )
1116
+ bus = compute_bus_factor(store, args.project)
1117
+ store.close()
1118
+
1119
+ # Shared filter threshold used by both JSON and human output
1120
+ instability_warn = cfg.metrics.thresholds.instability_threshold
1121
+
1122
+ if args.json:
1123
+ flagged_modules = [
1124
+ m
1125
+ for m in modules
1126
+ if m.file_path in god_paths or (m.fan_in > 0 and m.instability >= instability_warn)
1127
+ ]
1128
+ _json_out(
1129
+ {
1130
+ "modules": [
1131
+ {
1132
+ "file_path": m.file_path,
1133
+ "fan_in": round(m.fan_in, 2),
1134
+ "fan_out": round(m.fan_out, 2),
1135
+ "instability": round(m.instability, 3),
1136
+ "god_module": m.file_path in god_paths,
1137
+ "instability_flag": m.fan_in > 0 and m.instability >= instability_warn,
1138
+ }
1139
+ for m in flagged_modules
1140
+ ],
1141
+ "cycles": cycles,
1142
+ "god_modules": [m.file_path for m in gods],
1143
+ "hotspots": [
1144
+ {
1145
+ "file_path": h.file_path,
1146
+ "churn": h.churn,
1147
+ "coupling": round(h.coupling, 2),
1148
+ "hotspot_score": round(h.hotspot_score, 2),
1149
+ }
1150
+ for h in hotspots
1151
+ if h.hotspot_score > 0
1152
+ ],
1153
+ "temporal_coupling": [
1154
+ {
1155
+ "file_a": t.file_a,
1156
+ "file_b": t.file_b,
1157
+ "shared_commits": t.shared_commits,
1158
+ "coupling_ratio": round(t.coupling_ratio, 4),
1159
+ }
1160
+ for t in temporal
1161
+ ],
1162
+ "bus_factor": [
1163
+ {
1164
+ "file_path": b.file_path,
1165
+ "top_author": b.top_author,
1166
+ "top_author_pct": round(b.top_author_pct, 1),
1167
+ "bus_factor": b.bus_factor,
1168
+ }
1169
+ for b in bus
1170
+ if b.bus_factor == 1
1171
+ ],
1172
+ }
1173
+ )
1174
+ return
1175
+
1176
+ # Human output — only show items that signal a problem in each section
1177
+
1178
+ # ── Structural coupling: only flagged modules ──
1179
+ _print_section("Acoplamiento estructural")
1180
+ flagged: list[tuple] = []
1181
+ for m in sorted(modules, key=lambda x: x.fan_in, reverse=True):
1182
+ flags = []
1183
+ if m.file_path in god_paths:
1184
+ flags.append("● god")
1185
+ if m.fan_in > 0 and m.instability >= instability_warn:
1186
+ flags.append("⚠ inestable")
1187
+ if flags:
1188
+ flagged.append((m, " ".join(flags)))
1189
+
1190
+ if cycles:
1191
+ print(f" ✗ Ciclos ({len(cycles)}):")
1192
+ for cycle in cycles:
1193
+ print(" " + " → ".join(cycle))
1194
+ if flagged:
1195
+ col_w = max((len(m.file_path) for m, _ in flagged), default=30)
1196
+ col_w = max(col_w, 30)
1197
+ for m, flags_str in flagged:
1198
+ print(
1199
+ f" {m.file_path:<{col_w}} Ca={m.fan_in:>5.1f} Ce={m.fan_out:>5.1f}"
1200
+ f" I={m.instability:.3f} {flags_str}"
1201
+ )
1202
+ if not cycles and not flagged:
1203
+ print(" ✓ Sin problemas")
1204
+
1205
+ # ── Hotspots: files with score > 0 ──
1206
+ _print_section("Hotspots")
1207
+ active = [h for h in hotspots if h.hotspot_score > 0]
1208
+ if active:
1209
+ col_w = max((len(h.file_path) for h in active), default=30)
1210
+ col_w = max(col_w, 30)
1211
+ for h in active[:10]:
1212
+ print(
1213
+ f" {h.file_path:<{col_w}} churn={h.churn:>4}"
1214
+ f" coupling={h.coupling:>6.1f} score={h.hotspot_score:>8.1f}"
1215
+ )
1216
+ else:
1217
+ print(" ✓ Sin hotspots relevantes")
1218
+
1219
+ # ── Temporal coupling: all results already filtered by min_shared/min_ratio ──
1220
+ _print_section("Acoplamiento temporal")
1221
+ if temporal:
1222
+ for t in temporal[:10]:
1223
+ print(
1224
+ f" {t.file_a} ↔ {t.file_b}"
1225
+ f" ({t.shared_commits} commits, ratio={t.coupling_ratio:.2f})"
1226
+ )
1227
+ else:
1228
+ print(" ✓ Sin acoplamiento temporal implícito")
1229
+
1230
+ # ── Bus factor: only single-author files (bf == 1) ──
1231
+ _print_section("Bus factor")
1232
+ silos = [b for b in bus if b.bus_factor == 1]
1233
+ if silos:
1234
+ col_w = max((len(b.file_path) for b in silos), default=30)
1235
+ col_w = max(col_w, 30)
1236
+ for b in silos:
1237
+ print(f" {b.file_path:<{col_w}} {b.top_author} ({b.top_author_pct:.1f}%) ⚠ bf=1")
1238
+ else:
1239
+ print(" ✓ Sin archivos con autor único")
1240
+
1241
+
1242
+ # Entry point
1243
+ # ──────────────────────────────────────────────
1244
+
1245
+
1246
+ def main() -> None:
1247
+ """Entry point for the ``debtector`` CLI.
1248
+
1249
+ Parses arguments first, then configures structured logging so that the
1250
+ correct project path (and therefore log file location) is known.
1251
+ Dispatches to the appropriate sub-command handler and exits.
1252
+ Prints help and exits with status 0 if no sub-command is provided.
1253
+ """
1254
+ parser = argparse.ArgumentParser(
1255
+ prog="debtector",
1256
+ description="Debtector - Guardarraíl de acoplamiento para CI/PR",
1257
+ )
1258
+ parser.add_argument("--project", "-p", default=".", help="Ruta al proyecto")
1259
+ parser.add_argument(
1260
+ "--json",
1261
+ action="store_true",
1262
+ default=False,
1263
+ help="Emitir JSON compacto en stdout (para consumo por IA)",
1264
+ )
1265
+
1266
+ sub = parser.add_subparsers(dest="command")
1267
+
1268
+ # index
1269
+ p_idx = sub.add_parser("index", help="Indexar un proyecto")
1270
+ p_idx.add_argument("path", help="Ruta al directorio a indexar")
1271
+
1272
+ # search
1273
+ p_search = sub.add_parser("search", help="Buscar símbolos")
1274
+ p_search.add_argument("query", help="Texto a buscar")
1275
+ p_search.add_argument("--kind", "-k", help="Filtrar: Class, Function, Method")
1276
+
1277
+ # summary
1278
+ p_sum = sub.add_parser("summary", help="Resumen de un archivo")
1279
+ p_sum.add_argument("file", help="Ruta relativa del archivo")
1280
+
1281
+ # impact
1282
+ p_imp = sub.add_parser("impact", help="Análisis de impacto")
1283
+ p_imp.add_argument("files", nargs="+", help="Archivos modificados")
1284
+ p_imp.add_argument("--depth", "-d", type=int, default=2, help="Profundidad máxima")
1285
+
1286
+ # imports
1287
+ p_imports = sub.add_parser("imports", help="Buscar imports de un módulo")
1288
+ p_imports.add_argument("module", help="Módulo a buscar")
1289
+
1290
+ # status
1291
+ sub.add_parser("status", help="Estadísticas del índice")
1292
+
1293
+ # baseline
1294
+ p_baseline = sub.add_parser("baseline", help="Gestión del baseline de métricas")
1295
+ p_baseline_sub = p_baseline.add_subparsers(dest="baseline_cmd")
1296
+ p_baseline_sub.add_parser("save", help="Guardar snapshot de métricas como baseline")
1297
+ p_status = p_baseline_sub.add_parser(
1298
+ "status", help="Comparar métricas actuales con el baseline"
1299
+ )
1300
+ p_status.add_argument(
1301
+ "--reporter",
1302
+ choices=["github", "gitlab"],
1303
+ default=None,
1304
+ help="Formato CI: github (Annotations) o gitlab (section markers)",
1305
+ )
1306
+ # semantic (congelado — no forma parte del objetivo CI/PR)
1307
+ p_sem = sub.add_parser(
1308
+ "semantic",
1309
+ help="[DEPRECADO] Búsqueda semántica por concepto. Congelado; no se desarrollará más.",
1310
+ )
1311
+ p_sem.add_argument("query", help="Query en lenguaje natural")
1312
+ p_sem.add_argument(
1313
+ "--limit",
1314
+ "-l",
1315
+ type=int,
1316
+ default=10,
1317
+ help="Número máximo de resultados (default: 10)",
1318
+ )
1319
+
1320
+ # coupling (ex-metrics)
1321
+ p_coupling = sub.add_parser(
1322
+ "coupling", help="Acoplamiento estructural (Ca, Ce, I, ciclos, god modules)"
1323
+ )
1324
+ p_coupling.add_argument(
1325
+ "--sort",
1326
+ choices=["fan_in", "fan_out", "instability"],
1327
+ default="fan_in",
1328
+ help="Columna de ordenación (default: fan_in)",
1329
+ )
1330
+ p_coupling.add_argument(
1331
+ "--limit",
1332
+ "-l",
1333
+ type=int,
1334
+ default=None,
1335
+ help="Número máximo de filas a mostrar",
1336
+ )
1337
+
1338
+ # metrics — deprecated alias for coupling
1339
+ p_metrics_alias = sub.add_parser(
1340
+ "metrics",
1341
+ help="[DEPRECADO] Usa 'coupling'. Métricas de acoplamiento estructural.",
1342
+ )
1343
+ p_metrics_alias.add_argument(
1344
+ "--sort",
1345
+ choices=["fan_in", "fan_out", "instability"],
1346
+ default="fan_in",
1347
+ )
1348
+ p_metrics_alias.add_argument("--limit", "-l", type=int, default=None)
1349
+
1350
+ # callers
1351
+ p_callers = sub.add_parser("callers", help="¿Quién llama a un símbolo?")
1352
+ p_callers.add_argument("qualified_name", help="qualified_name del símbolo")
1353
+
1354
+ # untested
1355
+ p_untested = sub.add_parser("untested", help="Símbolos sin tests (sin arista COVERS)")
1356
+ p_untested.add_argument(
1357
+ "path",
1358
+ nargs="?",
1359
+ default=None,
1360
+ help="Ruta o prefijo de directorio para filtrar (opcional)",
1361
+ )
1362
+
1363
+ # hotspots
1364
+ p_hotspots = sub.add_parser("hotspots", help="Hotspots: churn × acoplamiento estructural")
1365
+ p_hotspots.add_argument("--limit", "-l", type=int, default=None)
1366
+ p_hotspots.add_argument("--since", default=None, help="Filtro de fecha (e.g. '6 months ago')")
1367
+ p_hotspots.add_argument("--min-coupling", type=float, default=0.0, dest="min_coupling")
1368
+
1369
+ # temporal-coupling
1370
+ p_tc = sub.add_parser("temporal-coupling", help="Archivos que co-cambian frecuentemente")
1371
+ p_tc.add_argument("--limit", "-l", type=int, default=None)
1372
+ p_tc.add_argument("--since", default=None)
1373
+ p_tc.add_argument("--min-shared", type=int, default=5, dest="min_shared")
1374
+ p_tc.add_argument("--min-ratio", type=float, default=0.3, dest="min_ratio")
1375
+
1376
+ # bus-factor
1377
+ p_bus = sub.add_parser("bus-factor", help="Riesgo de autor único por archivo")
1378
+ p_bus.add_argument("--limit", "-l", type=int, default=None)
1379
+
1380
+ # git-coupling
1381
+ p_git = sub.add_parser(
1382
+ "git-coupling", help="Análisis behavioral completo: hotspots + temporal + bus factor"
1383
+ )
1384
+ p_git.add_argument("--limit", "-l", type=int, default=None)
1385
+ p_git.add_argument("--since", default=None)
1386
+ p_git.add_argument("--min-shared", type=int, default=5, dest="min_shared")
1387
+ p_git.add_argument("--min-ratio", type=float, default=0.3, dest="min_ratio")
1388
+
1389
+ # report
1390
+ p_report = sub.add_parser(
1391
+ "report", help="Informe completo: acoplamiento estructural + behavioral"
1392
+ )
1393
+ p_report.add_argument(
1394
+ "--sort",
1395
+ choices=["fan_in", "fan_out", "instability"],
1396
+ default="fan_in",
1397
+ )
1398
+ p_report.add_argument("--limit", "-l", type=int, default=None)
1399
+ p_report.add_argument("--since", default=None)
1400
+ p_report.add_argument("--min-shared", type=int, default=5, dest="min_shared")
1401
+ p_report.add_argument("--min-ratio", type=float, default=0.3, dest="min_ratio")
1402
+
1403
+ args = parser.parse_args()
1404
+
1405
+ # Configure logging after parsing so the project path is known
1406
+ configure_logging(project=args.project)
1407
+
1408
+ if not args.command:
1409
+ parser.print_help()
1410
+ sys.exit(0)
1411
+
1412
+ cmds = {
1413
+ "index": cmd_index,
1414
+ "search": cmd_search,
1415
+ "semantic": cmd_semantic,
1416
+ "summary": cmd_summary,
1417
+ "impact": cmd_impact,
1418
+ "imports": cmd_imports,
1419
+ "status": cmd_status,
1420
+ "coupling": cmd_coupling,
1421
+ "metrics": cmd_coupling, # deprecated alias
1422
+ "baseline": cmd_baseline,
1423
+ "callers": cmd_callers,
1424
+ "untested": cmd_untested,
1425
+ "hotspots": cmd_hotspots,
1426
+ "temporal-coupling": cmd_temporal_coupling,
1427
+ "bus-factor": cmd_bus_factor,
1428
+ "git-coupling": cmd_git_coupling,
1429
+ "report": cmd_report,
1430
+ }
1431
+ cmds[args.command](args)
1432
+
1433
+
1434
+ if __name__ == "__main__":
1435
+ main()