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,432 @@
1
+ """Compound refactoring plan for one symbol."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import click
6
+
7
+ from roam.commands.cmd_guard import _layer_analysis, _risk_score, _trim_signature
8
+ from roam.commands.context_helpers import (
9
+ gather_symbol_context,
10
+ get_affected_tests_bfs,
11
+ get_blast_radius,
12
+ get_graph_metrics,
13
+ get_symbol_metrics,
14
+ )
15
+ from roam.commands.resolve import ensure_index, find_symbol, symbol_not_found
16
+ from roam.db.connection import open_db
17
+ from roam.output.formatter import budget_truncate, json_envelope, loc, to_json
18
+
19
+
20
+ def _summarize_tests(test_hits: list[dict], cap: int) -> tuple[list[dict], int, int]:
21
+ by_file: dict[str, dict] = {}
22
+
23
+ for hit in test_hits:
24
+ path = hit["file"]
25
+ kind = hit["kind"]
26
+ hops = int(hit["hops"])
27
+ priority = (0 if kind == "DIRECT" else 1, hops)
28
+
29
+ existing = by_file.get(path)
30
+ if existing is None or priority < existing["_priority"]:
31
+ by_file[path] = {
32
+ "file": path,
33
+ "kind": kind,
34
+ "hops": hops,
35
+ "via": hit.get("via"),
36
+ "_priority": priority,
37
+ }
38
+
39
+ rows = sorted(
40
+ by_file.values(),
41
+ key=lambda r: (0 if r["kind"] == "DIRECT" else 1, r["hops"], r["file"]),
42
+ )
43
+ for row in rows:
44
+ row.pop("_priority", None)
45
+
46
+ direct_files = sum(1 for row in rows if row["kind"] == "DIRECT")
47
+ return rows[:cap], direct_files, len(rows)
48
+
49
+
50
+ def _default_target_file(source_file: str, operation: str) -> str:
51
+ norm = (source_file or "").replace("\\", "/")
52
+ suffix = "_refactor" if operation == "extract" else "_moved"
53
+
54
+ if "/" in norm:
55
+ directory, filename = norm.rsplit("/", 1)
56
+ else:
57
+ directory, filename = "", norm
58
+
59
+ stem, dot, ext = filename.rpartition(".")
60
+ if dot:
61
+ name = f"{stem}{suffix}.{ext}"
62
+ else:
63
+ name = f"{filename}{suffix}.py"
64
+ return f"{directory}/{name}" if directory else name
65
+
66
+
67
+ def _metric_summary(deltas: dict) -> dict:
68
+ focus = (
69
+ "health_score",
70
+ "cycles",
71
+ "layer_violations",
72
+ "modularity",
73
+ "tangle_ratio",
74
+ "propagation_cost",
75
+ )
76
+ out: dict = {}
77
+ for key in focus:
78
+ delta = deltas.get(key)
79
+ if not delta:
80
+ continue
81
+ out[key] = {
82
+ "before": delta.get("before"),
83
+ "after": delta.get("after"),
84
+ "delta": delta.get("delta"),
85
+ "direction": delta.get("direction"),
86
+ }
87
+ return out
88
+
89
+
90
+ def _simulation_previews(
91
+ conn,
92
+ sym: dict,
93
+ operation: str,
94
+ target_file: str,
95
+ ) -> list[dict]:
96
+ try:
97
+ from roam.graph.builder import build_symbol_graph
98
+ from roam.graph.simulate import (
99
+ apply_extract,
100
+ apply_move,
101
+ clone_graph,
102
+ compute_graph_metrics,
103
+ metric_delta,
104
+ )
105
+ except Exception:
106
+ return []
107
+
108
+ try:
109
+ G = build_symbol_graph(conn)
110
+ except Exception:
111
+ return []
112
+
113
+ sym_id = int(sym["id"])
114
+ if sym_id not in G:
115
+ return []
116
+
117
+ before = compute_graph_metrics(G)
118
+ ops = ["extract", "move"] if operation == "auto" else [operation]
119
+ previews: list[dict] = []
120
+
121
+ for op in ops:
122
+ tgt = target_file.strip() or _default_target_file(sym["file_path"], op)
123
+ G_sim = clone_graph(G)
124
+ if op == "extract":
125
+ op_result = apply_extract(G_sim, sym_id, tgt)
126
+ else:
127
+ op_result = apply_move(G_sim, sym_id, tgt)
128
+
129
+ after = compute_graph_metrics(G_sim)
130
+ deltas = metric_delta(before, after)
131
+ health_delta = int(after["health_score"] - before["health_score"])
132
+ cycles_delta = int(after["cycles"] - before["cycles"])
133
+ layer_delta = int(after["layer_violations"] - before["layer_violations"])
134
+ improved = sum(1 for d in deltas.values() if d.get("direction") == "improved")
135
+ degraded = sum(1 for d in deltas.values() if d.get("direction") == "degraded")
136
+
137
+ score = (health_delta * 4) + (improved - degraded) - (max(0, cycles_delta) * 3) - (max(0, layer_delta) * 3)
138
+
139
+ previews.append(
140
+ {
141
+ "operation": op,
142
+ "target_file": tgt,
143
+ "result": op_result,
144
+ "score": int(score),
145
+ "health_delta": health_delta,
146
+ "cycles_delta": cycles_delta,
147
+ "layer_violations_delta": layer_delta,
148
+ "improved_metrics": improved,
149
+ "degraded_metrics": degraded,
150
+ "metrics": _metric_summary(deltas),
151
+ },
152
+ )
153
+
154
+ previews.sort(
155
+ key=lambda p: (
156
+ -p["score"],
157
+ -p["health_delta"],
158
+ p["cycles_delta"],
159
+ p["layer_violations_delta"],
160
+ p["operation"],
161
+ ),
162
+ )
163
+ return previews
164
+
165
+
166
+ def _build_steps(
167
+ *,
168
+ symbol_name: str,
169
+ selected_preview: dict | None,
170
+ risk_score: int,
171
+ blast: dict,
172
+ direct_test_files: int,
173
+ total_test_files: int,
174
+ layers: dict,
175
+ ) -> list[dict]:
176
+ steps: list[dict] = [
177
+ {
178
+ "title": "Capture baseline safety snapshot",
179
+ "details": ("Record pre-change risk, architecture, and metrics so post-change regressions are measurable."),
180
+ "command": f"roam guard {symbol_name}",
181
+ },
182
+ ]
183
+
184
+ if direct_test_files <= 0:
185
+ steps.append(
186
+ {
187
+ "title": "Add characterization tests before changing behavior",
188
+ "details": "No direct covering tests were found for this symbol.",
189
+ "command": f"roam test-map {symbol_name}",
190
+ },
191
+ )
192
+ elif total_test_files < 2:
193
+ steps.append(
194
+ {
195
+ "title": "Strengthen regression test breadth",
196
+ "details": "Coverage exists but is thin for a structural refactor.",
197
+ "command": f"roam affected-tests {symbol_name}",
198
+ },
199
+ )
200
+
201
+ if int(layers.get("violation_count") or 0) > 0:
202
+ steps.append(
203
+ {
204
+ "title": "Resolve existing layer violations first",
205
+ "details": (
206
+ "Refactoring on top of active layer violations increases the chance of architectural drift."
207
+ ),
208
+ "command": f"roam layers --focus {symbol_name}",
209
+ },
210
+ )
211
+
212
+ if selected_preview:
213
+ op = selected_preview["operation"]
214
+ target = selected_preview["target_file"]
215
+ steps.append(
216
+ {
217
+ "title": f"Apply {op} refactor in small commit slices",
218
+ "details": (f"Target file: {target}. Use staged slices to keep rollback and review bounded."),
219
+ "command": f"roam simulate {op} {symbol_name} {target}",
220
+ },
221
+ )
222
+ else:
223
+ steps.append(
224
+ {
225
+ "title": "Apply incremental extract/simplify changes",
226
+ "details": "Graph simulation is unavailable; proceed with conservative slices.",
227
+ "command": f"roam context {symbol_name}",
228
+ },
229
+ )
230
+
231
+ dependent_symbols = int(blast.get("dependent_symbols") or 0)
232
+ dependent_files = int(blast.get("dependent_files") or 0)
233
+ if dependent_symbols > 0:
234
+ steps.append(
235
+ {
236
+ "title": "Migrate dependents and imports in bounded batches",
237
+ "details": (
238
+ f"{dependent_symbols} downstream symbols in {dependent_files} files depend on this symbol."
239
+ ),
240
+ "command": f"roam impact {symbol_name}",
241
+ },
242
+ )
243
+
244
+ if risk_score >= 60:
245
+ steps.append(
246
+ {
247
+ "title": "Use compatibility shim + deprecation window",
248
+ "details": (
249
+ "High risk score warrants a temporary compatibility layer to avoid abrupt downstream breakage."
250
+ ),
251
+ "command": "roam breaking HEAD~1..HEAD",
252
+ },
253
+ )
254
+
255
+ steps.append(
256
+ {
257
+ "title": "Run verification gates and close-out checks",
258
+ "details": "Validate architecture, tests, and policy gates before merge.",
259
+ "command": "roam verify --threshold 80",
260
+ },
261
+ )
262
+
263
+ for idx, step in enumerate(steps, start=1):
264
+ step["step"] = idx
265
+ return steps
266
+
267
+
268
+ @click.command("plan-refactor")
269
+ @click.argument("symbol")
270
+ @click.option(
271
+ "--operation",
272
+ default="auto",
273
+ type=click.Choice(["auto", "extract", "move"], case_sensitive=False),
274
+ show_default=True,
275
+ help="Preferred structural operation. 'auto' compares extract vs move previews.",
276
+ )
277
+ @click.option(
278
+ "--target-file",
279
+ default="",
280
+ help="Explicit target file path for move/extract simulation preview.",
281
+ )
282
+ @click.option(
283
+ "--max-steps",
284
+ default=7,
285
+ show_default=True,
286
+ type=int,
287
+ help="Maximum number of plan steps to return.",
288
+ )
289
+ @click.pass_context
290
+ def plan_refactor(ctx, symbol, operation, target_file, max_steps):
291
+ """Build an ordered refactoring plan with risk, test, and impact context."""
292
+ json_mode = ctx.obj.get("json") if ctx.obj else False
293
+ token_budget = ctx.obj.get("budget", 0) if ctx.obj else 0
294
+ detail = bool(ctx.obj.get("detail", False)) if ctx.obj else False
295
+ ensure_index()
296
+
297
+ operation = str(operation or "auto").lower()
298
+ test_cap = 20 if detail else 8
299
+ layer_cap = 20 if detail else 8
300
+
301
+ with open_db(readonly=True) as conn:
302
+ sym = find_symbol(conn, symbol)
303
+ if sym is None:
304
+ click.echo(symbol_not_found(conn, symbol, json_mode=json_mode))
305
+ raise SystemExit(1)
306
+
307
+ context = gather_symbol_context(conn, sym, task="refactor", use_propagation=False)
308
+ test_hits = get_affected_tests_bfs(conn, sym["id"], max_hops=8)
309
+ tests, direct_test_files, total_test_files = _summarize_tests(test_hits, cap=test_cap)
310
+
311
+ blast = get_blast_radius(conn, sym["id"])
312
+ symbol_metrics = get_symbol_metrics(conn, sym["id"])
313
+ graph_metrics = get_graph_metrics(conn, sym["id"])
314
+ layers = _layer_analysis(conn, sym["id"], cap=layer_cap)
315
+ risk_score, risk_level, risk_factors = _risk_score(
316
+ blast=blast,
317
+ symbol_metrics=symbol_metrics,
318
+ graph_metrics=graph_metrics,
319
+ direct_test_files=direct_test_files,
320
+ total_test_files=total_test_files,
321
+ layer_violation_count=layers["violation_count"],
322
+ move_sensitive_count=layers["move_sensitive_count"],
323
+ )
324
+
325
+ previews = _simulation_previews(conn, sym, operation, target_file)
326
+
327
+ selected_preview = previews[0] if previews else None
328
+ plan_steps = _build_steps(
329
+ symbol_name=sym["qualified_name"] or sym["name"],
330
+ selected_preview=selected_preview,
331
+ risk_score=risk_score,
332
+ blast=blast,
333
+ direct_test_files=direct_test_files,
334
+ total_test_files=total_test_files,
335
+ layers=layers,
336
+ )
337
+ plan_steps = plan_steps[: max(1, int(max_steps))]
338
+ for idx, step in enumerate(plan_steps, start=1):
339
+ step["step"] = idx
340
+
341
+ if selected_preview:
342
+ strategy = f"{selected_preview['operation']} -> {selected_preview['target_file']}"
343
+ else:
344
+ strategy = "manual incremental refactor (simulation unavailable)"
345
+
346
+ verdict = f"{risk_level} risk ({risk_score}/100), {len(plan_steps)}-step plan, strategy: {strategy}"
347
+
348
+ definition = {
349
+ "name": sym["name"],
350
+ "qualified_name": sym["qualified_name"] or sym["name"],
351
+ "kind": sym["kind"],
352
+ "signature": _trim_signature(sym["signature"] if "signature" in sym.keys() else None),
353
+ "location": loc(sym["file_path"], sym["line_start"]),
354
+ }
355
+
356
+ if json_mode:
357
+ payload = json_envelope(
358
+ "plan-refactor",
359
+ summary={
360
+ "verdict": verdict,
361
+ "risk_score": risk_score,
362
+ "risk_level": risk_level,
363
+ "steps": len(plan_steps),
364
+ "selected_strategy": strategy,
365
+ "callers": len(context["non_test_callers"]),
366
+ "callees": len(context["callees"]),
367
+ "test_files": total_test_files,
368
+ "dependent_symbols": int(blast.get("dependent_symbols") or 0),
369
+ "dependent_files": int(blast.get("dependent_files") or 0),
370
+ },
371
+ definition=definition,
372
+ context_counts={
373
+ "callers": len(context["non_test_callers"]),
374
+ "callees": len(context["callees"]),
375
+ "test_files": total_test_files,
376
+ "direct_test_files": direct_test_files,
377
+ },
378
+ blast_radius=blast,
379
+ risk={
380
+ "score": risk_score,
381
+ "level": risk_level,
382
+ "factors": risk_factors,
383
+ },
384
+ layer_analysis={
385
+ "current_layer": layers["current_layer"],
386
+ "violation_count": layers["violation_count"],
387
+ "move_sensitive_count": layers["move_sensitive_count"],
388
+ "violations": layers["violations"],
389
+ "move_sensitive_edges": layers["move_sensitive_edges"],
390
+ },
391
+ simulation_previews=previews if detail else previews[:1],
392
+ tests=tests if detail else tests[: min(5, len(tests))],
393
+ plan=plan_steps,
394
+ )
395
+ click.echo(to_json(payload))
396
+ return
397
+
398
+ lines = [
399
+ f"Refactor plan: {definition['qualified_name']} {definition['location']}",
400
+ f"VERDICT: {verdict}",
401
+ (
402
+ "Context: "
403
+ f"{len(context['non_test_callers'])} callers, "
404
+ f"{len(context['callees'])} callees, "
405
+ f"{direct_test_files}/{total_test_files} direct/total test files"
406
+ ),
407
+ (
408
+ "Blast radius: "
409
+ f"{int(blast.get('dependent_symbols') or 0)} symbols across "
410
+ f"{int(blast.get('dependent_files') or 0)} files"
411
+ ),
412
+ ]
413
+ if selected_preview:
414
+ lines.append(
415
+ "Simulation preview: "
416
+ f"{selected_preview['operation']} -> {selected_preview['target_file']} "
417
+ f"(health {selected_preview['health_delta']:+d}, "
418
+ f"cycles {selected_preview['cycles_delta']:+d}, "
419
+ f"layers {selected_preview['layer_violations_delta']:+d})",
420
+ )
421
+
422
+ lines.append("")
423
+ lines.append("Steps:")
424
+ for step in plan_steps:
425
+ lines.append(f"{step['step']}. {step['title']}")
426
+ if detail:
427
+ lines.append(f" {step['details']}")
428
+ lines.append(f" run: {step['command']}")
429
+ else:
430
+ lines.append(f" run: {step['command']}")
431
+
432
+ click.echo(budget_truncate("\n".join(lines), token_budget))