mulle-roam-code 0.0.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.
Files changed (257) hide show
  1. mulle_roam_code-0.0.1.dist-info/METADATA +1590 -0
  2. mulle_roam_code-0.0.1.dist-info/RECORD +257 -0
  3. mulle_roam_code-0.0.1.dist-info/WHEEL +5 -0
  4. mulle_roam_code-0.0.1.dist-info/entry_points.txt +3 -0
  5. mulle_roam_code-0.0.1.dist-info/licenses/LICENSE +21 -0
  6. mulle_roam_code-0.0.1.dist-info/top_level.txt +1 -0
  7. roam/__init__.py +8 -0
  8. roam/__main__.py +5 -0
  9. roam/analysis/__init__.py +1 -0
  10. roam/analysis/effects.py +639 -0
  11. roam/analysis/taint.py +689 -0
  12. roam/api.py +238 -0
  13. roam/bridges/__init__.py +3 -0
  14. roam/bridges/base.py +49 -0
  15. roam/bridges/bridge_config.py +218 -0
  16. roam/bridges/bridge_protobuf.py +352 -0
  17. roam/bridges/bridge_rest_api.py +242 -0
  18. roam/bridges/bridge_salesforce.py +198 -0
  19. roam/bridges/bridge_template.py +247 -0
  20. roam/bridges/registry.py +51 -0
  21. roam/catalog/__init__.py +0 -0
  22. roam/catalog/detectors.py +2242 -0
  23. roam/catalog/fixes.py +86 -0
  24. roam/catalog/smells.py +599 -0
  25. roam/catalog/tasks.py +1260 -0
  26. roam/cli.py +548 -0
  27. roam/commands/__init__.py +0 -0
  28. roam/commands/changed_files.py +139 -0
  29. roam/commands/cmd_adversarial.py +699 -0
  30. roam/commands/cmd_affected.py +432 -0
  31. roam/commands/cmd_affected_tests.py +375 -0
  32. roam/commands/cmd_agent_context.py +168 -0
  33. roam/commands/cmd_agent_export.py +890 -0
  34. roam/commands/cmd_agent_plan.py +315 -0
  35. roam/commands/cmd_ai_ratio.py +765 -0
  36. roam/commands/cmd_ai_readiness.py +775 -0
  37. roam/commands/cmd_alerts.py +409 -0
  38. roam/commands/cmd_annotate.py +210 -0
  39. roam/commands/cmd_api_changes.py +796 -0
  40. roam/commands/cmd_api_drift.py +781 -0
  41. roam/commands/cmd_attest.py +913 -0
  42. roam/commands/cmd_auth_gaps.py +799 -0
  43. roam/commands/cmd_bisect.py +216 -0
  44. roam/commands/cmd_breaking.py +464 -0
  45. roam/commands/cmd_budget.py +413 -0
  46. roam/commands/cmd_bus_factor.py +403 -0
  47. roam/commands/cmd_capsule.py +275 -0
  48. roam/commands/cmd_check_rules.py +574 -0
  49. roam/commands/cmd_clean.py +147 -0
  50. roam/commands/cmd_closure.py +294 -0
  51. roam/commands/cmd_clusters.py +457 -0
  52. roam/commands/cmd_codeowners.py +600 -0
  53. roam/commands/cmd_complexity.py +364 -0
  54. roam/commands/cmd_config.py +310 -0
  55. roam/commands/cmd_context.py +1151 -0
  56. roam/commands/cmd_conventions.py +697 -0
  57. roam/commands/cmd_coupling.py +462 -0
  58. roam/commands/cmd_coverage_gaps.py +638 -0
  59. roam/commands/cmd_cut.py +235 -0
  60. roam/commands/cmd_dark_matter.py +127 -0
  61. roam/commands/cmd_dashboard.py +365 -0
  62. roam/commands/cmd_dead.py +1585 -0
  63. roam/commands/cmd_debt.py +731 -0
  64. roam/commands/cmd_deps.py +121 -0
  65. roam/commands/cmd_describe.py +959 -0
  66. roam/commands/cmd_dev_profile.py +580 -0
  67. roam/commands/cmd_diagnose.py +377 -0
  68. roam/commands/cmd_diff.py +633 -0
  69. roam/commands/cmd_digest.py +214 -0
  70. roam/commands/cmd_doc_staleness.py +334 -0
  71. roam/commands/cmd_docs_coverage.py +193 -0
  72. roam/commands/cmd_doctor.py +319 -0
  73. roam/commands/cmd_drift.py +377 -0
  74. roam/commands/cmd_duplicates.py +559 -0
  75. roam/commands/cmd_effects.py +362 -0
  76. roam/commands/cmd_endpoints.py +768 -0
  77. roam/commands/cmd_entry_points.py +358 -0
  78. roam/commands/cmd_fan.py +311 -0
  79. roam/commands/cmd_file.py +334 -0
  80. roam/commands/cmd_fingerprint.py +172 -0
  81. roam/commands/cmd_fitness.py +723 -0
  82. roam/commands/cmd_fn_coupling.py +295 -0
  83. roam/commands/cmd_forecast.py +366 -0
  84. roam/commands/cmd_grep.py +282 -0
  85. roam/commands/cmd_guard.py +434 -0
  86. roam/commands/cmd_health.py +922 -0
  87. roam/commands/cmd_hooks.py +458 -0
  88. roam/commands/cmd_hotspots.py +606 -0
  89. roam/commands/cmd_impact.py +228 -0
  90. roam/commands/cmd_index.py +102 -0
  91. roam/commands/cmd_ingest_trace.py +143 -0
  92. roam/commands/cmd_init.py +166 -0
  93. roam/commands/cmd_intent.py +459 -0
  94. roam/commands/cmd_invariants.py +301 -0
  95. roam/commands/cmd_layers.py +387 -0
  96. roam/commands/cmd_map.py +275 -0
  97. roam/commands/cmd_math.py +213 -0
  98. roam/commands/cmd_mcp_setup.py +135 -0
  99. roam/commands/cmd_metrics.py +663 -0
  100. roam/commands/cmd_migration_safety.py +712 -0
  101. roam/commands/cmd_minimap.py +519 -0
  102. roam/commands/cmd_missing_index.py +885 -0
  103. roam/commands/cmd_module.py +204 -0
  104. roam/commands/cmd_mutate.py +400 -0
  105. roam/commands/cmd_n1.py +967 -0
  106. roam/commands/cmd_onboard.py +740 -0
  107. roam/commands/cmd_orchestrate.py +180 -0
  108. roam/commands/cmd_orphan_routes.py +754 -0
  109. roam/commands/cmd_over_fetch.py +633 -0
  110. roam/commands/cmd_owner.py +299 -0
  111. roam/commands/cmd_partition.py +714 -0
  112. roam/commands/cmd_path_coverage.py +564 -0
  113. roam/commands/cmd_patterns.py +689 -0
  114. roam/commands/cmd_plan.py +616 -0
  115. roam/commands/cmd_plan_refactor.py +432 -0
  116. roam/commands/cmd_pr_diff.py +292 -0
  117. roam/commands/cmd_pr_risk.py +677 -0
  118. roam/commands/cmd_preflight.py +706 -0
  119. roam/commands/cmd_relate.py +405 -0
  120. roam/commands/cmd_report.py +304 -0
  121. roam/commands/cmd_reset.py +117 -0
  122. roam/commands/cmd_risk.py +533 -0
  123. roam/commands/cmd_rules.py +319 -0
  124. roam/commands/cmd_safe_delete.py +224 -0
  125. roam/commands/cmd_safe_zones.py +295 -0
  126. roam/commands/cmd_schema.py +166 -0
  127. roam/commands/cmd_search.py +295 -0
  128. roam/commands/cmd_search_semantic.py +101 -0
  129. roam/commands/cmd_secrets.py +636 -0
  130. roam/commands/cmd_semantic_diff.py +538 -0
  131. roam/commands/cmd_simulate.py +296 -0
  132. roam/commands/cmd_simulate_departure.py +632 -0
  133. roam/commands/cmd_sketch.py +160 -0
  134. roam/commands/cmd_smells.py +179 -0
  135. roam/commands/cmd_snapshot.py +50 -0
  136. roam/commands/cmd_spectral.py +183 -0
  137. roam/commands/cmd_split.py +432 -0
  138. roam/commands/cmd_suggest_refactoring.py +486 -0
  139. roam/commands/cmd_suggest_reviewers.py +491 -0
  140. roam/commands/cmd_supply_chain.py +831 -0
  141. roam/commands/cmd_symbol.py +135 -0
  142. roam/commands/cmd_syntax_check.py +301 -0
  143. roam/commands/cmd_test_gaps.py +574 -0
  144. roam/commands/cmd_testmap.py +308 -0
  145. roam/commands/cmd_tour.py +377 -0
  146. roam/commands/cmd_trace.py +304 -0
  147. roam/commands/cmd_trend.py +461 -0
  148. roam/commands/cmd_trends.py +929 -0
  149. roam/commands/cmd_understand.py +763 -0
  150. roam/commands/cmd_uses.py +170 -0
  151. roam/commands/cmd_verify.py +812 -0
  152. roam/commands/cmd_verify_imports.py +435 -0
  153. roam/commands/cmd_vibe_check.py +932 -0
  154. roam/commands/cmd_visualize.py +361 -0
  155. roam/commands/cmd_vuln_map.py +139 -0
  156. roam/commands/cmd_vuln_reach.py +289 -0
  157. roam/commands/cmd_vulns.py +414 -0
  158. roam/commands/cmd_watch.py +759 -0
  159. roam/commands/cmd_weather.py +118 -0
  160. roam/commands/cmd_why.py +325 -0
  161. roam/commands/cmd_ws.py +755 -0
  162. roam/commands/cmd_xlang.py +170 -0
  163. roam/commands/context_helpers.py +1137 -0
  164. roam/commands/gate_presets.py +222 -0
  165. roam/commands/graph_helpers.py +93 -0
  166. roam/commands/metrics_history.py +298 -0
  167. roam/commands/next_steps.py +107 -0
  168. roam/commands/resolve.py +302 -0
  169. roam/competitor_site_data.py +2229 -0
  170. roam/coverage_reports.py +462 -0
  171. roam/db/__init__.py +0 -0
  172. roam/db/connection.py +359 -0
  173. roam/db/queries.py +151 -0
  174. roam/db/schema.py +335 -0
  175. roam/exit_codes.py +100 -0
  176. roam/graph/__init__.py +43 -0
  177. roam/graph/anomaly.py +493 -0
  178. roam/graph/builder.py +61 -0
  179. roam/graph/clusters.py +286 -0
  180. roam/graph/cycles.py +210 -0
  181. roam/graph/dark_matter.py +207 -0
  182. roam/graph/diff.py +467 -0
  183. roam/graph/fingerprint.py +297 -0
  184. roam/graph/layers.py +134 -0
  185. roam/graph/pagerank.py +171 -0
  186. roam/graph/partition.py +437 -0
  187. roam/graph/pathfinding.py +119 -0
  188. roam/graph/propagation.py +208 -0
  189. roam/graph/simulate.py +286 -0
  190. roam/graph/spectral.py +260 -0
  191. roam/index/__init__.py +5 -0
  192. roam/index/complexity.py +1108 -0
  193. roam/index/discovery.py +338 -0
  194. roam/index/file_roles.py +586 -0
  195. roam/index/git_stats.py +577 -0
  196. roam/index/incremental.py +75 -0
  197. roam/index/indexer.py +1191 -0
  198. roam/index/parser.py +461 -0
  199. roam/index/relations.py +537 -0
  200. roam/index/symbols.py +71 -0
  201. roam/index/test_conventions.py +508 -0
  202. roam/languages/__init__.py +21 -0
  203. roam/languages/apex_lang.py +241 -0
  204. roam/languages/aura_lang.py +228 -0
  205. roam/languages/base.py +111 -0
  206. roam/languages/c_lang.py +458 -0
  207. roam/languages/csharp_lang.py +1215 -0
  208. roam/languages/foxpro_lang.py +1554 -0
  209. roam/languages/generic_lang.py +702 -0
  210. roam/languages/go_lang.py +392 -0
  211. roam/languages/hcl_lang.py +398 -0
  212. roam/languages/java_lang.py +418 -0
  213. roam/languages/javascript_lang.py +799 -0
  214. roam/languages/kotlin_lang.py +147 -0
  215. roam/languages/objc_lang.py +401 -0
  216. roam/languages/php_lang.py +696 -0
  217. roam/languages/python_lang.py +850 -0
  218. roam/languages/registry.py +283 -0
  219. roam/languages/ruby_lang.py +429 -0
  220. roam/languages/rust_lang.py +545 -0
  221. roam/languages/sfxml_lang.py +276 -0
  222. roam/languages/swift_lang.py +173 -0
  223. roam/languages/typescript_lang.py +323 -0
  224. roam/languages/visualforce_lang.py +151 -0
  225. roam/languages/yaml_lang.py +566 -0
  226. roam/mcp_server.py +4794 -0
  227. roam/output/__init__.py +0 -0
  228. roam/output/formatter.py +557 -0
  229. roam/output/mermaid.py +62 -0
  230. roam/output/sarif.py +897 -0
  231. roam/output/schema_registry.py +57 -0
  232. roam/plugins.py +208 -0
  233. roam/refactor/__init__.py +0 -0
  234. roam/refactor/codegen.py +106 -0
  235. roam/refactor/transforms.py +711 -0
  236. roam/rules/__init__.py +0 -0
  237. roam/rules/ast_match.py +238 -0
  238. roam/rules/builtin.py +617 -0
  239. roam/rules/dataflow.py +515 -0
  240. roam/rules/engine.py +943 -0
  241. roam/runtime/__init__.py +3 -0
  242. roam/runtime/hotspots.py +138 -0
  243. roam/runtime/trace_ingest.py +535 -0
  244. roam/search/__init__.py +1 -0
  245. roam/search/framework_packs.py +673 -0
  246. roam/search/index_embeddings.py +732 -0
  247. roam/search/onnx_embeddings.py +233 -0
  248. roam/search/tfidf.py +355 -0
  249. roam/security/__init__.py +1 -0
  250. roam/security/vuln_reach.py +246 -0
  251. roam/security/vuln_store.py +334 -0
  252. roam/surface_counts.py +158 -0
  253. roam/workspace/__init__.py +3 -0
  254. roam/workspace/aggregator.py +426 -0
  255. roam/workspace/api_scanner.py +538 -0
  256. roam/workspace/config.py +95 -0
  257. roam/workspace/db.py +136 -0
@@ -0,0 +1,731 @@
1
+ """Hotspot-weighted technical debt prioritization.
2
+
3
+ Core insight (CodeScene): unhealthy code in hotspots (frequently changed files)
4
+ costs 15x more than unhealthy cold code. debt_score = health_penalty * hotspot_factor.
5
+ """
6
+
7
+ import os
8
+ from collections import defaultdict
9
+
10
+ import click
11
+
12
+ from roam.commands.resolve import ensure_index
13
+ from roam.db.connection import batched_in, open_db
14
+ from roam.output.formatter import format_table, json_envelope, loc, to_json
15
+
16
+ # ---------------------------------------------------------------------------
17
+ # Helpers
18
+ # ---------------------------------------------------------------------------
19
+
20
+
21
+ def _percentile_rank(value, sorted_values):
22
+ """Return the percentile rank (0.0-1.0) of *value* within *sorted_values*."""
23
+ if not sorted_values:
24
+ return 0.0
25
+ n = len(sorted_values)
26
+ # Count how many values are strictly less than *value*
27
+ lo = 0
28
+ for v in sorted_values:
29
+ if v < value:
30
+ lo += 1
31
+ else:
32
+ break
33
+ return lo / n
34
+
35
+
36
+ def _parent_dir(path):
37
+ """Return the parent directory of a file path, normalised with forward slashes."""
38
+ p = path.replace("\\", "/")
39
+ idx = p.rfind("/")
40
+ return p[:idx] if idx >= 0 else "."
41
+
42
+
43
+ # ---------------------------------------------------------------------------
44
+ # Per-file debt computation
45
+ # ---------------------------------------------------------------------------
46
+
47
+
48
+ def _compute_file_debt(conn):
49
+ """Compute per-file debt scores.
50
+
51
+ Returns a list of dicts sorted by debt_score descending.
52
+ """
53
+ # 1. Fetch file_stats rows (complexity, churn)
54
+ file_stats = conn.execute("""
55
+ SELECT fs.file_id, f.path, fs.complexity, fs.total_churn,
56
+ fs.commit_count, fs.distinct_authors
57
+ FROM file_stats fs
58
+ JOIN files f ON fs.file_id = f.id
59
+ """).fetchall()
60
+
61
+ if not file_stats:
62
+ return []
63
+
64
+ # Build lookup: file_id -> file_stats row
65
+ stats_by_file = {}
66
+ for r in file_stats:
67
+ stats_by_file[r["file_id"]] = dict(r)
68
+
69
+ # --- Normalise complexity (0-1) ---
70
+ complexities = [r["complexity"] or 0 for r in file_stats]
71
+ max_complexity = max(complexities) if complexities else 1
72
+ if max_complexity == 0:
73
+ max_complexity = 1
74
+
75
+ # --- Churn percentile ranks ---
76
+ churns = sorted(r["total_churn"] or 0 for r in file_stats)
77
+
78
+ # 2. Cycle membership: find which files have symbols participating in cycles
79
+ cycle_files = set()
80
+ try:
81
+ from roam.graph.builder import build_symbol_graph
82
+ from roam.graph.cycles import find_cycles
83
+
84
+ G = build_symbol_graph(conn)
85
+ cycles = find_cycles(G)
86
+ if cycles:
87
+ all_cycle_ids = set()
88
+ for scc in cycles:
89
+ all_cycle_ids.update(scc)
90
+ if all_cycle_ids:
91
+ rows = batched_in(
92
+ conn,
93
+ "SELECT DISTINCT s.file_id FROM symbols s WHERE s.id IN ({ph})",
94
+ list(all_cycle_ids),
95
+ )
96
+ cycle_files = {r["file_id"] for r in rows}
97
+ except Exception:
98
+ pass # graph not available — skip cycle detection
99
+
100
+ # 3. God component membership (high fan-in + fan-out per file)
101
+ god_files = set()
102
+ god_rows = conn.execute("""
103
+ SELECT s.file_id, SUM(gm.in_degree + gm.out_degree) as total_degree
104
+ FROM graph_metrics gm
105
+ JOIN symbols s ON gm.symbol_id = s.id
106
+ GROUP BY s.file_id
107
+ HAVING total_degree > 40
108
+ """).fetchall()
109
+ for r in god_rows:
110
+ god_files.add(r["file_id"])
111
+
112
+ # 4. Dead exports per file: symbols with is_exported=1 but zero in-degree
113
+ dead_counts = {}
114
+ total_exported = {}
115
+ dead_rows = conn.execute("""
116
+ SELECT s.file_id,
117
+ SUM(CASE WHEN gm.in_degree = 0 OR gm.in_degree IS NULL THEN 1 ELSE 0 END) as dead_count,
118
+ COUNT(*) as export_count
119
+ FROM symbols s
120
+ LEFT JOIN graph_metrics gm ON s.id = gm.symbol_id
121
+ WHERE s.is_exported = 1
122
+ AND s.kind IN ('function', 'class', 'method', 'interface', 'struct')
123
+ GROUP BY s.file_id
124
+ """).fetchall()
125
+ for r in dead_rows:
126
+ dead_counts[r["file_id"]] = r["dead_count"]
127
+ total_exported[r["file_id"]] = r["export_count"]
128
+
129
+ # 5. Coupling intensity per file: average symbol graph degree
130
+ coupling_by_file = {}
131
+ coupling_rows = conn.execute("""
132
+ SELECT s.file_id,
133
+ AVG(COALESCE(gm.in_degree, 0) + COALESCE(gm.out_degree, 0)) AS avg_degree,
134
+ MAX(COALESCE(gm.in_degree, 0) + COALESCE(gm.out_degree, 0)) AS max_degree
135
+ FROM symbols s
136
+ LEFT JOIN graph_metrics gm ON s.id = gm.symbol_id
137
+ GROUP BY s.file_id
138
+ """).fetchall()
139
+ for r in coupling_rows:
140
+ coupling_by_file[r["file_id"]] = {
141
+ "avg_degree": float(r["avg_degree"] or 0.0),
142
+ "max_degree": float(r["max_degree"] or 0.0),
143
+ }
144
+
145
+ # --- Compute per-file debt ---
146
+ results = []
147
+ for fid, info in stats_by_file.items():
148
+ complexity_raw = info["complexity"] or 0
149
+ churn_raw = info["total_churn"] or 0
150
+ path = info["path"]
151
+
152
+ # Complexity normalised 0-1
153
+ complexity_norm = complexity_raw / max_complexity
154
+
155
+ # Churn percentile rank 0-1
156
+ churn_pctile = _percentile_rank(churn_raw, churns)
157
+
158
+ # Cycle penalty: 1.0 if file has symbols in cycles, else 0
159
+ cycle_penalty = 1.0 if fid in cycle_files else 0.0
160
+
161
+ # God component penalty: 1.0 if file has high-degree symbols, else 0
162
+ god_penalty = 1.0 if fid in god_files else 0.0
163
+
164
+ # Dead export ratio
165
+ n_dead = dead_counts.get(fid, 0)
166
+ n_exported = total_exported.get(fid, 0)
167
+ dead_ratio = (n_dead / n_exported) if n_exported > 0 else 0.0
168
+ coupling_info = coupling_by_file.get(fid, {})
169
+ coupling_avg_degree = coupling_info.get("avg_degree", 0.0)
170
+ coupling_max_degree = coupling_info.get("max_degree", 0.0)
171
+
172
+ # --- SQALE-inspired remediation cost (minutes) ---
173
+ # Each issue type has an estimated fix time, transforming
174
+ # heterogeneous violations into a common currency (dev-minutes).
175
+ # Reference: Letouzey (2012), "The SQALE Method."
176
+ _COST_COMPLEXITY_PER_UNIT = 30 # minutes to refactor per unit of normalized complexity
177
+ _COST_CYCLE_BREAK = 120 # minutes to break a cycle dependency
178
+ _COST_GOD_SPLIT = 240 # minutes to split a god component
179
+ _COST_DEAD_REMOVE = 10 # minutes to safely remove a dead export
180
+
181
+ remediation_minutes = (
182
+ complexity_norm * _COST_COMPLEXITY_PER_UNIT
183
+ + cycle_penalty * _COST_CYCLE_BREAK
184
+ + god_penalty * _COST_GOD_SPLIT
185
+ + n_dead * _COST_DEAD_REMOVE
186
+ )
187
+
188
+ # Health penalty: normalized 0-1 for scoring (backwards compat)
189
+ health_penalty = complexity_norm * 0.4 + cycle_penalty * 0.3 + god_penalty * 0.2 + dead_ratio * 0.1
190
+
191
+ # Hotspot factor: churn amplifies health problems (up to 3x)
192
+ hotspot_factor = max(1.0, churn_pctile * 3)
193
+
194
+ debt_score = health_penalty * hotspot_factor
195
+
196
+ results.append(
197
+ {
198
+ "file_id": fid,
199
+ "path": path,
200
+ "debt_score": round(debt_score, 3),
201
+ "health_penalty": round(health_penalty, 3),
202
+ "hotspot_factor": round(hotspot_factor, 2),
203
+ "remediation_minutes": round(remediation_minutes, 0),
204
+ "complexity_norm": round(complexity_norm, 3),
205
+ "complexity_raw": round(complexity_raw, 1),
206
+ "churn_pctile": round(churn_pctile, 3),
207
+ "churn_raw": churn_raw,
208
+ "cycle_penalty": cycle_penalty,
209
+ "god_penalty": god_penalty,
210
+ "dead_exports": n_dead,
211
+ "total_exported": n_exported,
212
+ "dead_ratio": round(dead_ratio, 3),
213
+ "coupling_avg_degree": round(coupling_avg_degree, 2),
214
+ "coupling_max_degree": round(coupling_max_degree, 2),
215
+ "commit_count": info["commit_count"] or 0,
216
+ "distinct_authors": info["distinct_authors"] or 0,
217
+ }
218
+ )
219
+
220
+ results.sort(key=lambda x: -x["debt_score"])
221
+ return results
222
+
223
+
224
+ # ---------------------------------------------------------------------------
225
+ # Summary stats
226
+ # ---------------------------------------------------------------------------
227
+
228
+
229
+ def _summary_stats(items):
230
+ """Compute aggregate project-level debt statistics."""
231
+ if not items:
232
+ return {
233
+ "total_files": 0,
234
+ "total_debt": 0,
235
+ "mean_debt": 0,
236
+ "median_debt": 0,
237
+ "worst_quartile_debt": 0,
238
+ "worst_quartile_files": 0,
239
+ "files_with_cycles": 0,
240
+ "files_with_god_components": 0,
241
+ "hotspot_files": 0,
242
+ }
243
+
244
+ scores = sorted(r["debt_score"] for r in items)
245
+ n = len(scores)
246
+ total_debt = sum(scores)
247
+ mean_debt = total_debt / n
248
+ median_debt = scores[n // 2]
249
+
250
+ # Worst quartile: top 25% of files by debt
251
+ q_cutoff = max(1, n // 4)
252
+ worst_q = items[:q_cutoff] # already sorted desc
253
+ worst_q_debt = sum(r["debt_score"] for r in worst_q)
254
+
255
+ total_remediation = sum(r.get("remediation_minutes", 0) for r in items)
256
+
257
+ return {
258
+ "total_files": n,
259
+ "total_debt": round(total_debt, 1),
260
+ "mean_debt": round(mean_debt, 3),
261
+ "median_debt": round(median_debt, 3),
262
+ "worst_quartile_debt": round(worst_q_debt, 1),
263
+ "worst_quartile_files": len(worst_q),
264
+ "total_remediation_minutes": round(total_remediation, 0),
265
+ "total_remediation_hours": round(total_remediation / 60, 1),
266
+ "files_with_cycles": sum(1 for r in items if r["cycle_penalty"] > 0),
267
+ "files_with_god_components": sum(1 for r in items if r["god_penalty"] > 0),
268
+ "hotspot_files": sum(1 for r in items if r["hotspot_factor"] > 1.0),
269
+ }
270
+
271
+
272
+ def _improvement_suggestions(items):
273
+ """Generate actionable improvement suggestions based on debt distribution."""
274
+ suggestions = []
275
+ if not items:
276
+ return suggestions
277
+
278
+ # Top debt files with high hotspot factor
279
+ hot_complex = [r for r in items[:10] if r["hotspot_factor"] > 2.0 and r["complexity_norm"] > 0.5]
280
+ if hot_complex:
281
+ names = ", ".join(os.path.basename(r["path"]) for r in hot_complex[:3])
282
+ suggestions.append(
283
+ f"Refactor hot complex files first: {names} (high churn + high complexity = maximum debt leverage)"
284
+ )
285
+
286
+ # Cycle-bearing hotspots
287
+ cycle_hot = [r for r in items[:20] if r["cycle_penalty"] > 0 and r["hotspot_factor"] > 1.5]
288
+ if cycle_hot:
289
+ suggestions.append(
290
+ f"{len(cycle_hot)} hotspot file(s) participate in dependency cycles "
291
+ f"-- breaking these cycles reduces cascading change cost"
292
+ )
293
+
294
+ # Dead exports in high-churn files
295
+ dead_hot = [r for r in items[:20] if r["dead_exports"] > 0 and r["hotspot_factor"] > 1.5]
296
+ if dead_hot:
297
+ total_dead = sum(r["dead_exports"] for r in dead_hot)
298
+ suggestions.append(
299
+ f"{total_dead} dead export(s) in {len(dead_hot)} hotspot file(s) "
300
+ f"-- removing them reduces cognitive load in frequently changed code"
301
+ )
302
+
303
+ # General advice based on distribution
304
+ stats = _summary_stats(items)
305
+ if stats["worst_quartile_files"] > 0:
306
+ pct = stats["worst_quartile_debt"] / stats["total_debt"] * 100 if stats["total_debt"] > 0 else 0
307
+ suggestions.append(
308
+ f"Worst quartile ({stats['worst_quartile_files']} files) holds "
309
+ f"{pct:.0f}% of total debt -- focus refactoring budget here"
310
+ )
311
+
312
+ return suggestions
313
+
314
+
315
+ # ---------------------------------------------------------------------------
316
+ # ROI estimation
317
+ # ---------------------------------------------------------------------------
318
+
319
+
320
+ def _estimate_quarterly_touches(item):
321
+ """Estimate per-quarter touch frequency from commit and churn signals."""
322
+ commits = float(item.get("commit_count", 0) or 0.0)
323
+ churn = float(item.get("churn_raw", 0) or 0.0)
324
+ # Commits drive the baseline; churn acts as a secondary amplifier.
325
+ return max(1.0, (commits * 0.25) + (churn / 120.0))
326
+
327
+
328
+ def _estimate_review_overhead_hours(complexity_norm, coupling_norm):
329
+ """Estimate review overhead per touch (hours) from complexity/coupling."""
330
+ # Baseline 9 minutes + complexity + coupling overhead.
331
+ return 0.15 + (complexity_norm * 0.35) + (coupling_norm * 0.20)
332
+
333
+
334
+ def _estimate_refactoring_roi(items, top_n=10):
335
+ """Estimate refactoring ROI for top debt files.
336
+
337
+ Formula:
338
+ savings = complexity_reduction * touch_frequency * avg_review_overhead
339
+ """
340
+ if not items:
341
+ return {
342
+ "files_analyzed": 0,
343
+ "estimated_hours_saved_quarter": 0.0,
344
+ "estimated_hours_saved_year": 0.0,
345
+ "confidence_low_hours_saved_quarter": 0.0,
346
+ "confidence_high_hours_saved_quarter": 0.0,
347
+ "confidence": "low",
348
+ "assumptions": (
349
+ "Quarterly touch frequency derived from commit_count + churn; "
350
+ "review overhead derived from complexity + coupling."
351
+ ),
352
+ }, {}
353
+
354
+ target = items[: max(1, top_n)]
355
+ max_coupling = max((r.get("coupling_avg_degree", 0.0) or 0.0) for r in target)
356
+ if max_coupling <= 0:
357
+ max_coupling = 1.0
358
+
359
+ total_q = 0.0
360
+ low_q = 0.0
361
+ high_q = 0.0
362
+ confidence_total = 0.0
363
+ by_path = {}
364
+
365
+ for row in target:
366
+ complexity_norm = float(row.get("complexity_norm", 0.0) or 0.0)
367
+ coupling_avg = float(row.get("coupling_avg_degree", 0.0) or 0.0)
368
+ coupling_norm = min(1.0, coupling_avg / max_coupling)
369
+
370
+ complexity_reduction = 0.20 + (complexity_norm * 0.50)
371
+ touch_frequency = _estimate_quarterly_touches(row)
372
+ review_overhead = _estimate_review_overhead_hours(complexity_norm, coupling_norm)
373
+ savings_q = complexity_reduction * touch_frequency * review_overhead
374
+
375
+ # Confidence reflects how many ROI signals are present for the file.
376
+ signal_count = 0
377
+ if (row.get("commit_count", 0) or 0) > 0:
378
+ signal_count += 1
379
+ if (row.get("churn_raw", 0) or 0) > 0:
380
+ signal_count += 1
381
+ if coupling_avg > 0:
382
+ signal_count += 1
383
+ if complexity_norm > 0:
384
+ signal_count += 1
385
+ confidence_score = signal_count / 4.0
386
+
387
+ if confidence_score >= 0.75:
388
+ confidence = "high"
389
+ band = 0.20
390
+ elif confidence_score >= 0.50:
391
+ confidence = "medium"
392
+ band = 0.35
393
+ else:
394
+ confidence = "low"
395
+ band = 0.50
396
+
397
+ low = max(0.0, savings_q * (1.0 - band))
398
+ high = savings_q * (1.0 + band)
399
+
400
+ entry = {
401
+ "estimated_hours_saved_quarter": round(savings_q, 2),
402
+ "estimated_hours_saved_year": round(savings_q * 4.0, 2),
403
+ "confidence_low_hours_saved_quarter": round(low, 2),
404
+ "confidence_high_hours_saved_quarter": round(high, 2),
405
+ "confidence": confidence,
406
+ "drivers": {
407
+ "complexity_reduction": round(complexity_reduction, 3),
408
+ "touch_frequency": round(touch_frequency, 2),
409
+ "avg_review_overhead_hours": round(review_overhead, 3),
410
+ "coupling_norm": round(coupling_norm, 3),
411
+ },
412
+ }
413
+ by_path[row["path"]] = entry
414
+
415
+ total_q += savings_q
416
+ low_q += low
417
+ high_q += high
418
+ confidence_total += confidence_score
419
+
420
+ avg_conf = confidence_total / len(target) if target else 0.0
421
+ if avg_conf >= 0.75:
422
+ confidence_label = "high"
423
+ elif avg_conf >= 0.50:
424
+ confidence_label = "medium"
425
+ else:
426
+ confidence_label = "low"
427
+
428
+ summary = {
429
+ "files_analyzed": len(target),
430
+ "estimated_hours_saved_quarter": round(total_q, 1),
431
+ "estimated_hours_saved_year": round(total_q * 4.0, 1),
432
+ "confidence_low_hours_saved_quarter": round(low_q, 1),
433
+ "confidence_high_hours_saved_quarter": round(high_q, 1),
434
+ "confidence": confidence_label,
435
+ "assumptions": (
436
+ "Quarterly touch frequency derived from commit_count + churn; "
437
+ "review overhead derived from complexity + coupling."
438
+ ),
439
+ }
440
+ return summary, by_path
441
+
442
+
443
+ # ---------------------------------------------------------------------------
444
+ # Grouping
445
+ # ---------------------------------------------------------------------------
446
+
447
+
448
+ def _group_by_directory(items):
449
+ """Group debt items by parent directory."""
450
+ groups = defaultdict(list)
451
+ for item in items:
452
+ d = _parent_dir(item["path"])
453
+ groups[d].append(item)
454
+
455
+ result = []
456
+ for d, files in groups.items():
457
+ total_debt = sum(f["debt_score"] for f in files)
458
+ avg_debt = total_debt / len(files) if files else 0
459
+ result.append(
460
+ {
461
+ "directory": d,
462
+ "file_count": len(files),
463
+ "total_debt": round(total_debt, 1),
464
+ "avg_debt": round(avg_debt, 3),
465
+ "max_debt": round(max(f["debt_score"] for f in files), 3),
466
+ "files": files,
467
+ }
468
+ )
469
+
470
+ result.sort(key=lambda x: -x["total_debt"])
471
+ return result
472
+
473
+
474
+ # ---------------------------------------------------------------------------
475
+ # Click command
476
+ # ---------------------------------------------------------------------------
477
+
478
+
479
+ @click.command()
480
+ @click.option("--limit", "-n", default=20, help="Number of files to show (default 20)")
481
+ @click.option("--by-kind", "by_kind", is_flag=True, help="Group results by parent directory")
482
+ @click.option("--threshold", type=float, default=None, help="Only show files above this debt score")
483
+ @click.option("--roi", is_flag=True, help="Estimate refactoring ROI (developer-hours saved/quarter).")
484
+ @click.pass_context
485
+ def debt(ctx, limit, by_kind, threshold, roi):
486
+ """Hotspot-weighted technical debt prioritization.
487
+
488
+ Combines code health signals (complexity, cycles, god components, dead
489
+ exports) with churn hotspot data. Files that are both unhealthy AND
490
+ frequently changed get amplified debt scores -- these are the highest
491
+ leverage refactoring targets.
492
+
493
+ Formula: debt = health_penalty * hotspot_factor
494
+
495
+ \b
496
+ health_penalty = complexity*0.4 + cycles*0.3 + god*0.2 + dead*0.1
497
+ hotspot_factor = max(1.0, churn_percentile * 3) # up to 3x for hot files
498
+ """
499
+ json_mode = ctx.obj.get("json") if ctx.obj else False
500
+ token_budget = ctx.obj.get("budget", 0) if ctx.obj else 0
501
+ ensure_index()
502
+
503
+ with open_db(readonly=True) as conn:
504
+ all_items = _compute_file_debt(conn)
505
+
506
+ if not all_items:
507
+ if json_mode:
508
+ click.echo(
509
+ to_json(
510
+ json_envelope(
511
+ "debt",
512
+ summary={"total_files": 0, "total_debt": 0},
513
+ items=[],
514
+ )
515
+ )
516
+ )
517
+ else:
518
+ click.echo("No file stats available. Run `roam index` first.")
519
+ return
520
+
521
+ # Apply threshold filter
522
+ if threshold is not None:
523
+ all_items = [r for r in all_items if r["debt_score"] >= threshold]
524
+
525
+ stats = _summary_stats(all_items)
526
+ suggestions = _improvement_suggestions(all_items)
527
+ roi_summary, roi_by_path = ({}, {})
528
+ if roi:
529
+ roi_summary, roi_by_path = _estimate_refactoring_roi(
530
+ all_items,
531
+ top_n=max(limit, 10),
532
+ )
533
+
534
+ def _roi_payload(path):
535
+ entry = roi_by_path.get(path)
536
+ if not entry:
537
+ return None
538
+ return {
539
+ "estimated_hours_saved_quarter": entry["estimated_hours_saved_quarter"],
540
+ "estimated_hours_saved_year": entry["estimated_hours_saved_year"],
541
+ "confidence_low_hours_saved_quarter": (entry["confidence_low_hours_saved_quarter"]),
542
+ "confidence_high_hours_saved_quarter": (entry["confidence_high_hours_saved_quarter"]),
543
+ "confidence": entry["confidence"],
544
+ }
545
+
546
+ # --- Grouped by directory ---
547
+ if by_kind:
548
+ groups = _group_by_directory(all_items)
549
+
550
+ if json_mode:
551
+ payload = {
552
+ "summary": stats,
553
+ "budget": token_budget,
554
+ "suggestions": suggestions,
555
+ "grouping": "directory",
556
+ "groups": [
557
+ {
558
+ "directory": g["directory"],
559
+ "file_count": g["file_count"],
560
+ "total_debt": g["total_debt"],
561
+ "avg_debt": g["avg_debt"],
562
+ "max_debt": g["max_debt"],
563
+ "files": [
564
+ {
565
+ "path": f["path"],
566
+ "debt_score": f["debt_score"],
567
+ "health_penalty": f["health_penalty"],
568
+ "hotspot_factor": f["hotspot_factor"],
569
+ **({"roi": _roi_payload(f["path"])} if roi and _roi_payload(f["path"]) else {}),
570
+ }
571
+ for f in g["files"][:limit]
572
+ ],
573
+ }
574
+ for g in groups
575
+ ],
576
+ }
577
+ if roi:
578
+ payload["roi"] = roi_summary
579
+ click.echo(to_json(json_envelope("debt", **payload)))
580
+ return
581
+
582
+ # Text output: grouped
583
+ click.echo("=== Technical Debt by Directory ===\n")
584
+ _print_summary(stats, suggestions)
585
+ if roi and roi_summary:
586
+ click.echo()
587
+ click.echo(" Refactoring ROI estimate:")
588
+ click.echo(
589
+ f" Top {roi_summary['files_analyzed']} files could save "
590
+ f"~{roi_summary['estimated_hours_saved_quarter']:.1f} h/quarter "
591
+ f"({roi_summary['confidence_low_hours_saved_quarter']:.1f}-"
592
+ f"{roi_summary['confidence_high_hours_saved_quarter']:.1f} h, "
593
+ f"{roi_summary['confidence']} confidence)"
594
+ )
595
+ click.echo()
596
+
597
+ for g in groups[:limit]:
598
+ click.echo(
599
+ f" {g['directory']}/ "
600
+ f"({g['file_count']} files, "
601
+ f"total={g['total_debt']:.1f}, "
602
+ f"avg={g['avg_debt']:.3f}, "
603
+ f"max={g['max_debt']:.3f})"
604
+ )
605
+ # Show top 5 files per group
606
+ for f in g["files"][:5]:
607
+ click.echo(f" {f['debt_score']:.3f} {os.path.basename(f['path'])}")
608
+ if len(groups) > limit:
609
+ click.echo(f"\n (+{len(groups) - limit} more directories)")
610
+ return
611
+
612
+ # --- Flat list (default) ---
613
+ display = all_items[:limit]
614
+
615
+ if json_mode:
616
+ payload = {
617
+ "summary": stats,
618
+ "budget": token_budget,
619
+ "suggestions": suggestions,
620
+ "items": [
621
+ {
622
+ "path": r["path"],
623
+ "debt_score": r["debt_score"],
624
+ "health_penalty": r["health_penalty"],
625
+ "hotspot_factor": r["hotspot_factor"],
626
+ "breakdown": {
627
+ "complexity_norm": r["complexity_norm"],
628
+ "complexity_raw": r["complexity_raw"],
629
+ "churn_pctile": r["churn_pctile"],
630
+ "churn_raw": r["churn_raw"],
631
+ "cycle_penalty": r["cycle_penalty"],
632
+ "god_penalty": r["god_penalty"],
633
+ "dead_exports": r["dead_exports"],
634
+ "total_exported": r["total_exported"],
635
+ "dead_ratio": r["dead_ratio"],
636
+ "coupling_avg_degree": r["coupling_avg_degree"],
637
+ "coupling_max_degree": r["coupling_max_degree"],
638
+ },
639
+ "commit_count": r["commit_count"],
640
+ "distinct_authors": r["distinct_authors"],
641
+ **({"roi": _roi_payload(r["path"])} if roi and _roi_payload(r["path"]) else {}),
642
+ }
643
+ for r in display
644
+ ],
645
+ }
646
+ if roi:
647
+ payload["roi"] = roi_summary
648
+ click.echo(to_json(json_envelope("debt", **payload)))
649
+ return
650
+
651
+ # Text output: flat
652
+ click.echo("=== Technical Debt (hotspot-weighted) ===\n")
653
+ _print_summary(stats, suggestions)
654
+ if roi and roi_summary:
655
+ click.echo()
656
+ click.echo(" Refactoring ROI estimate:")
657
+ click.echo(
658
+ f" Top {roi_summary['files_analyzed']} files could save "
659
+ f"~{roi_summary['estimated_hours_saved_quarter']:.1f} h/quarter "
660
+ f"({roi_summary['confidence_low_hours_saved_quarter']:.1f}-"
661
+ f"{roi_summary['confidence_high_hours_saved_quarter']:.1f} h, "
662
+ f"{roi_summary['confidence']} confidence)"
663
+ )
664
+ click.echo()
665
+
666
+ table_rows = []
667
+ for r in display:
668
+ # Build compact breakdown string
669
+ parts = []
670
+ if r["complexity_norm"] > 0.3:
671
+ parts.append(f"cx={r['complexity_raw']:.0f}")
672
+ if r["cycle_penalty"]:
673
+ parts.append("cyc")
674
+ if r["god_penalty"]:
675
+ parts.append("god")
676
+ if r["dead_exports"]:
677
+ parts.append(f"dead={r['dead_exports']}")
678
+ breakdown = " ".join(parts) if parts else "-"
679
+
680
+ # Hotspot indicator
681
+ if r["hotspot_factor"] >= 2.5:
682
+ hot = "HOT"
683
+ elif r["hotspot_factor"] >= 1.5:
684
+ hot = "warm"
685
+ else:
686
+ hot = ""
687
+
688
+ row = [
689
+ f"{r['debt_score']:.3f}",
690
+ f"{r['health_penalty']:.2f}",
691
+ f"{r['hotspot_factor']:.1f}x",
692
+ hot,
693
+ ]
694
+ if roi:
695
+ roi_item = _roi_payload(r["path"])
696
+ row.append(f"{roi_item['estimated_hours_saved_quarter']:.1f}h" if roi_item else "-")
697
+ row.extend([breakdown, loc(r["path"])])
698
+ table_rows.append(row)
699
+
700
+ headers = ["Debt", "Health", "Hotspot", "Heat"]
701
+ if roi:
702
+ headers.append("ROI/qtr")
703
+ headers.extend(["Breakdown", "File"])
704
+
705
+ click.echo(format_table(headers, table_rows))
706
+
707
+ remaining = len(all_items) - limit
708
+ if remaining > 0:
709
+ click.echo(f"\n (+{remaining} more files, use --limit to show more)")
710
+
711
+
712
+ def _print_summary(stats, suggestions):
713
+ """Print text summary block."""
714
+ click.echo(
715
+ f" Project: {stats['total_files']} files, "
716
+ f"total debt = {stats['total_debt']:.1f}, "
717
+ f"mean = {stats['mean_debt']:.3f}, "
718
+ f"median = {stats['median_debt']:.3f}"
719
+ )
720
+ click.echo(f" Worst quartile: {stats['worst_quartile_files']} files hold {stats['worst_quartile_debt']:.1f} debt")
721
+ click.echo(
722
+ f" Signals: {stats['files_with_cycles']} files in cycles, "
723
+ f"{stats['files_with_god_components']} with god components, "
724
+ f"{stats['hotspot_files']} hotspots"
725
+ )
726
+
727
+ if suggestions:
728
+ click.echo()
729
+ click.echo(" Suggestions:")
730
+ for s in suggestions:
731
+ click.echo(f" - {s}")