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,486 @@
1
+ """Proactive refactoring recommendations ranked by structural risk signals."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import defaultdict
6
+
7
+ import click
8
+
9
+ from roam.catalog.smells import run_all_detectors
10
+ from roam.commands.resolve import ensure_index
11
+ from roam.db.connection import open_db
12
+ from roam.output.formatter import (
13
+ abbrev_kind,
14
+ budget_truncate,
15
+ format_table,
16
+ json_envelope,
17
+ loc,
18
+ to_json,
19
+ )
20
+
21
+ _CANDIDATES_SQL = """
22
+ SELECT
23
+ s.id,
24
+ s.name,
25
+ COALESCE(s.qualified_name, s.name) AS qualified_name,
26
+ s.kind,
27
+ s.line_start,
28
+ s.line_end,
29
+ f.path AS file_path,
30
+ COALESCE(sm.cognitive_complexity, 0) AS cognitive_complexity,
31
+ COALESCE(sm.nesting_depth, 0) AS nesting_depth,
32
+ COALESCE(
33
+ sm.line_count,
34
+ CASE
35
+ WHEN s.line_start IS NOT NULL AND s.line_end IS NOT NULL
36
+ THEN (s.line_end - s.line_start + 1)
37
+ ELSE 0
38
+ END
39
+ ) AS line_count,
40
+ COALESCE(sm.param_count, 0) AS param_count,
41
+ sm.coverage_pct AS symbol_coverage_pct,
42
+ fs.coverage_pct AS file_coverage_pct,
43
+ COALESCE(gm.pagerank, 0.0) AS pagerank,
44
+ COALESCE(gm.in_degree, 0) AS in_degree,
45
+ COALESCE(gm.out_degree, 0) AS out_degree,
46
+ COALESCE(gm.debt_score, 0.0) AS debt_score,
47
+ COALESCE(fs.total_churn, 0) AS total_churn,
48
+ COALESCE(fs.commit_count, 0) AS commit_count
49
+ FROM symbols s
50
+ JOIN files f ON s.file_id = f.id
51
+ LEFT JOIN symbol_metrics sm ON sm.symbol_id = s.id
52
+ LEFT JOIN graph_metrics gm ON gm.symbol_id = s.id
53
+ LEFT JOIN file_stats fs ON fs.file_id = s.file_id
54
+ WHERE s.kind IN ('function', 'method', 'class', 'interface', 'struct', 'enum')
55
+ AND (s.is_exported = 1 OR s.kind IN ('class', 'interface', 'struct', 'enum'))
56
+ AND f.path NOT LIKE '%/tests/%'
57
+ AND f.path NOT LIKE '%/test/%'
58
+ AND f.path NOT LIKE '%test\\_%' ESCAPE '\\'
59
+ AND f.path NOT LIKE '%\\_test.%' ESCAPE '\\'
60
+ ORDER BY f.path, s.line_start
61
+ """
62
+
63
+
64
+ _SEVERITY_WEIGHT = {
65
+ "critical": 2.0,
66
+ "warning": 1.0,
67
+ "info": 0.5,
68
+ }
69
+
70
+
71
+ def _normalize(values: list[float]) -> list[float]:
72
+ if not values:
73
+ return []
74
+ max_v = max(values)
75
+ if max_v <= 0:
76
+ return [0.0 for _ in values]
77
+ return [min(1.0, max(0.0, (v / max_v))) for v in values]
78
+
79
+
80
+ def _coverage_pct(row: dict) -> float | None:
81
+ sym_cov = row.get("symbol_coverage_pct")
82
+ if sym_cov is not None:
83
+ return float(sym_cov)
84
+ file_cov = row.get("file_coverage_pct")
85
+ if file_cov is not None:
86
+ return float(file_cov)
87
+ return None
88
+
89
+
90
+ def _coverage_gap(row: dict) -> float:
91
+ cov = _coverage_pct(row)
92
+ if cov is None:
93
+ # Unknown imported coverage should not dominate ranking.
94
+ return 0.35
95
+ return min(1.0, max(0.0, (80.0 - cov) / 80.0))
96
+
97
+
98
+ def _parse_location(location: str) -> tuple[str, int | None]:
99
+ text = (location or "").replace("\\", "/").strip()
100
+ if not text:
101
+ return "", None
102
+ path, sep, tail = text.rpartition(":")
103
+ if sep and tail.isdigit():
104
+ return path, int(tail)
105
+ return text, None
106
+
107
+
108
+ def _line_span(symbol: dict) -> tuple[int, int]:
109
+ start = int(symbol.get("line_start") or 0)
110
+ end = int(symbol.get("line_end") or start)
111
+ if end < start:
112
+ end = start
113
+ return start, end
114
+
115
+
116
+ def _best_symbol_for_smell(
117
+ symbols: list[dict],
118
+ *,
119
+ line: int | None,
120
+ symbol_name: str,
121
+ ) -> dict | None:
122
+ if not symbols:
123
+ return None
124
+
125
+ if line is not None:
126
+ matches = []
127
+ for sym in symbols:
128
+ start, end = _line_span(sym)
129
+ if start <= line <= end:
130
+ matches.append((end - start, start, sym))
131
+ if matches:
132
+ matches.sort(key=lambda t: (t[0], t[1], t[2]["name"]))
133
+ return matches[0][2]
134
+
135
+ if symbol_name:
136
+ wanted = symbol_name.lower()
137
+ for sym in symbols:
138
+ if (sym.get("name") or "").lower() == wanted:
139
+ return sym
140
+ return None
141
+
142
+
143
+ def _build_smell_index(findings: list[dict], candidates: list[dict]) -> dict[int, dict]:
144
+ by_file: dict[str, list[dict]] = defaultdict(list)
145
+ by_name: dict[str, list[dict]] = defaultdict(list)
146
+
147
+ for sym in candidates:
148
+ path = (sym.get("file_path") or "").replace("\\", "/")
149
+ by_file[path].append(sym)
150
+ key = (sym.get("name") or "").lower()
151
+ if key:
152
+ by_name[key].append(sym)
153
+
154
+ index: dict[int, dict] = {}
155
+ for finding in findings:
156
+ path, line = _parse_location(str(finding.get("location") or ""))
157
+ symbol_name = str(finding.get("symbol_name") or "")
158
+ bucket = _best_symbol_for_smell(
159
+ by_file.get(path, []),
160
+ line=line,
161
+ symbol_name=symbol_name,
162
+ )
163
+ if bucket is None and symbol_name:
164
+ matches = by_name.get(symbol_name.lower(), [])
165
+ if len(matches) == 1:
166
+ bucket = matches[0]
167
+ if bucket is None:
168
+ continue
169
+
170
+ sym_id = int(bucket["id"])
171
+ row = index.setdefault(
172
+ sym_id,
173
+ {
174
+ "count": 0,
175
+ "critical": 0,
176
+ "warning": 0,
177
+ "info": 0,
178
+ "weighted": 0.0,
179
+ "types": set(),
180
+ },
181
+ )
182
+ sev = str(finding.get("severity") or "info").lower()
183
+ if sev not in ("critical", "warning", "info"):
184
+ sev = "info"
185
+ row["count"] += 1
186
+ row[sev] += 1
187
+ row["weighted"] += _SEVERITY_WEIGHT[sev]
188
+ smell_id = str(finding.get("smell_id") or "").strip()
189
+ if smell_id:
190
+ row["types"].add(smell_id)
191
+
192
+ for row in index.values():
193
+ row["types"] = sorted(row["types"])
194
+ return index
195
+
196
+
197
+ def _suggest_action(row: dict, smells: dict) -> str:
198
+ kind = str(row.get("kind") or "")
199
+ cc = float(row.get("cognitive_complexity") or 0.0)
200
+ line_count = int(row.get("line_count") or 0)
201
+ coupling = int(row.get("in_degree") or 0) + int(row.get("out_degree") or 0)
202
+ smell_count = int(smells.get("count") or 0)
203
+ nesting = int(row.get("nesting_depth") or 0)
204
+
205
+ if kind in ("class", "interface", "struct", "enum") and line_count >= 220:
206
+ return "split"
207
+ if cc >= 28 or line_count >= 90:
208
+ return "extract"
209
+ if coupling >= 16:
210
+ return "decouple"
211
+ if smell_count >= 2 or nesting >= 4:
212
+ return "simplify"
213
+ return "extract"
214
+
215
+
216
+ def _effort_bucket(row: dict, smells: dict, coverage_gap: float) -> str:
217
+ points = 0
218
+ cc = float(row.get("cognitive_complexity") or 0.0)
219
+ line_count = int(row.get("line_count") or 0)
220
+ coupling = int(row.get("in_degree") or 0) + int(row.get("out_degree") or 0)
221
+ churn = int(row.get("total_churn") or 0)
222
+ smell_count = int(smells.get("count") or 0)
223
+
224
+ if cc >= 30:
225
+ points += 2
226
+ elif cc >= 15:
227
+ points += 1
228
+
229
+ if line_count >= 120:
230
+ points += 2
231
+ elif line_count >= 60:
232
+ points += 1
233
+
234
+ if coupling >= 20:
235
+ points += 2
236
+ elif coupling >= 10:
237
+ points += 1
238
+
239
+ if churn >= 300:
240
+ points += 1
241
+ if smell_count >= 3:
242
+ points += 1
243
+ if coverage_gap >= 0.6:
244
+ points += 1
245
+
246
+ if points <= 2:
247
+ return "S"
248
+ if points <= 5:
249
+ return "M"
250
+ return "L"
251
+
252
+
253
+ def _reasons(
254
+ row: dict,
255
+ smells: dict,
256
+ *,
257
+ complexity_n: float,
258
+ coupling_n: float,
259
+ churn_n: float,
260
+ smell_n: float,
261
+ debt_n: float,
262
+ coverage_gap: float,
263
+ ) -> list[str]:
264
+ reasons: list[str] = []
265
+ cc = float(row.get("cognitive_complexity") or 0.0)
266
+ nesting = int(row.get("nesting_depth") or 0)
267
+ coupling = int(row.get("in_degree") or 0) + int(row.get("out_degree") or 0)
268
+ churn = int(row.get("total_churn") or 0)
269
+ commits = int(row.get("commit_count") or 0)
270
+ debt = float(row.get("debt_score") or 0.0)
271
+ coverage_pct = _coverage_pct(row)
272
+
273
+ if complexity_n >= 0.6 or cc >= 20:
274
+ reasons.append(f"High complexity (CC {cc:.0f}, nesting {nesting})")
275
+ if coupling_n >= 0.6 or coupling >= 10:
276
+ reasons.append(
277
+ f"High coupling (fan-in {int(row.get('in_degree') or 0)}, fan-out {int(row.get('out_degree') or 0)})",
278
+ )
279
+ if churn_n >= 0.6 and churn > 0:
280
+ reasons.append(f"High churn ({churn} changed lines across {commits} commits)")
281
+ if smell_n >= 0.45 and int(smells.get("count") or 0) > 0:
282
+ critical = int(smells.get("critical") or 0)
283
+ reasons.append(f"Smell signals ({int(smells.get('count') or 0)} findings, {critical} critical)")
284
+ if coverage_gap >= 0.45:
285
+ if coverage_pct is None:
286
+ reasons.append("Coverage unknown (no imported coverage data)")
287
+ else:
288
+ reasons.append(f"Low test coverage ({coverage_pct:.1f}%)")
289
+ if debt_n >= 0.55 or debt >= 0.3:
290
+ reasons.append(f"High structural debt score ({debt:.3f})")
291
+
292
+ if not reasons:
293
+ reasons.append("Combined risk signals suggest refactoring leverage")
294
+ return reasons
295
+
296
+
297
+ @click.command("suggest-refactoring")
298
+ @click.option(
299
+ "-n",
300
+ "--limit",
301
+ default=20,
302
+ show_default=True,
303
+ help="Maximum number of recommendations to return.",
304
+ )
305
+ @click.option(
306
+ "--min-score",
307
+ default=45,
308
+ show_default=True,
309
+ type=int,
310
+ help="Only include recommendations with score >= N (0-100).",
311
+ )
312
+ @click.pass_context
313
+ def suggest_refactoring(ctx, limit, min_score):
314
+ """Rank symbols that are likely to yield high-value refactoring wins."""
315
+ json_mode = ctx.obj.get("json") if ctx.obj else False
316
+ token_budget = ctx.obj.get("budget", 0) if ctx.obj else 0
317
+ detail = bool(ctx.obj.get("detail", False)) if ctx.obj else False
318
+ ensure_index()
319
+
320
+ with open_db(readonly=True) as conn:
321
+ candidates = [dict(r) for r in conn.execute(_CANDIDATES_SQL).fetchall()]
322
+ smells = run_all_detectors(conn)
323
+
324
+ smell_index = _build_smell_index(smells, candidates)
325
+
326
+ complexity_raw: list[float] = []
327
+ coupling_raw: list[float] = []
328
+ churn_raw: list[float] = []
329
+ smell_raw: list[float] = []
330
+ debt_raw: list[float] = []
331
+ coverage_raw: list[float] = []
332
+ for row in candidates:
333
+ sym_smells = smell_index.get(row["id"], {})
334
+ cc = float(row.get("cognitive_complexity") or 0.0)
335
+ line_count = int(row.get("line_count") or 0)
336
+ nesting = int(row.get("nesting_depth") or 0)
337
+ complexity_raw.append(cc + (nesting * 2.0) + max(0, line_count - 30) / 30.0)
338
+ coupling_raw.append(float(int(row.get("in_degree") or 0) + int(row.get("out_degree") or 0)))
339
+ churn_raw.append(float(int(row.get("total_churn") or 0)))
340
+ smell_raw.append(float(sym_smells.get("weighted") or 0.0))
341
+ debt_raw.append(float(row.get("debt_score") or 0.0))
342
+ coverage_raw.append(_coverage_gap(row))
343
+
344
+ complexity_n = _normalize(complexity_raw)
345
+ coupling_n = _normalize(coupling_raw)
346
+ churn_n = _normalize(churn_raw)
347
+ smell_n = _normalize(smell_raw)
348
+ debt_n = _normalize(debt_raw)
349
+
350
+ scored: list[dict] = []
351
+ for idx, row in enumerate(candidates):
352
+ sym_smells = smell_index.get(
353
+ row["id"],
354
+ {"count": 0, "critical": 0, "warning": 0, "info": 0, "weighted": 0.0, "types": []},
355
+ )
356
+ cov_gap = coverage_raw[idx]
357
+ weighted = (
358
+ (0.25 * complexity_n[idx])
359
+ + (0.20 * coupling_n[idx])
360
+ + (0.15 * churn_n[idx])
361
+ + (0.15 * smell_n[idx])
362
+ + (0.15 * cov_gap)
363
+ + (0.10 * debt_n[idx])
364
+ )
365
+ score = int(round(weighted * 100))
366
+
367
+ reasons = _reasons(
368
+ row,
369
+ sym_smells,
370
+ complexity_n=complexity_n[idx],
371
+ coupling_n=coupling_n[idx],
372
+ churn_n=churn_n[idx],
373
+ smell_n=smell_n[idx],
374
+ debt_n=debt_n[idx],
375
+ coverage_gap=cov_gap,
376
+ )
377
+ action = _suggest_action(row, sym_smells)
378
+ effort = _effort_bucket(row, sym_smells, cov_gap)
379
+
380
+ coverage_pct = _coverage_pct(row)
381
+ scored.append(
382
+ {
383
+ "symbol": row["qualified_name"] or row["name"],
384
+ "name": row["name"],
385
+ "kind": row["kind"],
386
+ "file": row["file_path"],
387
+ "line": int(row.get("line_start") or 1),
388
+ "score": score,
389
+ "effort": effort,
390
+ "action": action,
391
+ "reasons": reasons,
392
+ "signals": {
393
+ "complexity": float(row.get("cognitive_complexity") or 0.0),
394
+ "nesting_depth": int(row.get("nesting_depth") or 0),
395
+ "line_count": int(row.get("line_count") or 0),
396
+ "fan_in": int(row.get("in_degree") or 0),
397
+ "fan_out": int(row.get("out_degree") or 0),
398
+ "pagerank": round(float(row.get("pagerank") or 0.0), 6),
399
+ "debt_score": round(float(row.get("debt_score") or 0.0), 3),
400
+ "total_churn": int(row.get("total_churn") or 0),
401
+ "commit_count": int(row.get("commit_count") or 0),
402
+ "smell_count": int(sym_smells.get("count") or 0),
403
+ "critical_smells": int(sym_smells.get("critical") or 0),
404
+ "coverage_pct": round(coverage_pct, 1) if coverage_pct is not None else None,
405
+ },
406
+ },
407
+ )
408
+
409
+ scored.sort(
410
+ key=lambda x: (
411
+ -x["score"],
412
+ -float(x["signals"]["pagerank"]),
413
+ x["file"],
414
+ x["line"],
415
+ x["symbol"],
416
+ ),
417
+ )
418
+
419
+ filtered = [item for item in scored if item["score"] >= int(min_score)]
420
+ shown = filtered[: int(limit)]
421
+
422
+ top_score = shown[0]["score"] if shown else 0
423
+ verdict = (
424
+ f"{len(filtered)} refactoring candidate(s) scored >= {min_score}/100"
425
+ if filtered
426
+ else f"No symbols scored >= {min_score}/100"
427
+ )
428
+
429
+ if json_mode:
430
+ payload = json_envelope(
431
+ "suggest-refactoring",
432
+ summary={
433
+ "verdict": verdict,
434
+ "considered_symbols": len(scored),
435
+ "candidates": len(filtered),
436
+ "shown": len(shown),
437
+ "min_score": int(min_score),
438
+ "top_score": top_score,
439
+ },
440
+ recommendations=shown,
441
+ scoring={
442
+ "weights": {
443
+ "complexity": 0.25,
444
+ "coupling": 0.20,
445
+ "churn": 0.15,
446
+ "smells": 0.15,
447
+ "coverage_gap": 0.15,
448
+ "debt": 0.10,
449
+ },
450
+ },
451
+ )
452
+ if not detail:
453
+ payload.pop("scoring", None)
454
+ click.echo(to_json(payload))
455
+ return
456
+
457
+ if not shown:
458
+ click.echo(f"VERDICT: {verdict}")
459
+ return
460
+
461
+ headers = ["Score", "Eff", "Action", "Symbol", "Location", "Reasons"]
462
+ rows: list[list[str]] = []
463
+ for item in shown:
464
+ reasons = item["reasons"] if detail else item["reasons"][:2]
465
+ rows.append(
466
+ [
467
+ str(item["score"]),
468
+ item["effort"],
469
+ item["action"],
470
+ f"{abbrev_kind(item['kind'])} {item['symbol']}",
471
+ loc(item["file"], item["line"]),
472
+ "; ".join(reasons),
473
+ ],
474
+ )
475
+
476
+ lines = [
477
+ "Refactoring recommendations",
478
+ "",
479
+ f"VERDICT: {verdict}",
480
+ "",
481
+ format_table(headers, rows),
482
+ ]
483
+ if len(filtered) > len(shown):
484
+ lines.append("")
485
+ lines.append(f"(+{len(filtered) - len(shown)} more candidates; increase --limit to view all)")
486
+ click.echo(budget_truncate("\n".join(lines), token_budget))