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,633 @@
1
+ """Show blast radius of uncommitted changes."""
2
+
3
+ import fnmatch
4
+
5
+ import click
6
+
7
+ from roam.commands.changed_files import get_changed_files, resolve_changed_to_db
8
+ from roam.commands.resolve import ensure_index
9
+ from roam.db.connection import find_project_root, open_db
10
+ from roam.output.formatter import format_table, json_envelope, to_json
11
+
12
+ # ---------------------------------------------------------------------------
13
+ # Affected tests helper
14
+ # ---------------------------------------------------------------------------
15
+
16
+
17
+ def _collect_affected_tests(conn, sym_by_file):
18
+ """Gather affected tests for all symbols across changed files.
19
+
20
+ Returns (test_entries, pytest_cmd) where test_entries is the list from
21
+ ``_gather_affected_tests`` and pytest_cmd is a runnable pytest string.
22
+ """
23
+ from roam.commands.cmd_affected_tests import _gather_affected_tests
24
+
25
+ all_sym_ids = set()
26
+ all_file_paths = set()
27
+ for path, syms in sym_by_file.items():
28
+ all_file_paths.add(path)
29
+ all_sym_ids.update(s["id"] for s in syms)
30
+
31
+ if not all_sym_ids:
32
+ return [], ""
33
+
34
+ results = _gather_affected_tests(conn, all_sym_ids, all_file_paths)
35
+
36
+ # Build deduplicated ordered file list for pytest command
37
+ seen_order = []
38
+ seen_set = set()
39
+ for r in results:
40
+ if r["file"] not in seen_set:
41
+ seen_set.add(r["file"])
42
+ seen_order.append(r["file"])
43
+
44
+ pytest_cmd = "pytest " + " ".join(seen_order) if seen_order else ""
45
+ return results, pytest_cmd
46
+
47
+
48
+ # ---------------------------------------------------------------------------
49
+ # Coupling warnings helper
50
+ # ---------------------------------------------------------------------------
51
+
52
+
53
+ def _collect_coupling_warnings(conn, file_map, min_cochanges=3):
54
+ """Find temporally-coupled files that are NOT in the changeset.
55
+
56
+ Returns a list of dicts with keys: path, cochanges, strength, partner_of.
57
+ """
58
+ change_fids = set(file_map.values())
59
+
60
+ # Build lookup tables
61
+ id_to_path = {}
62
+ file_commits = {}
63
+ for f in conn.execute("SELECT id, path FROM files").fetchall():
64
+ id_to_path[f["id"]] = f["path"]
65
+ for fs in conn.execute("SELECT file_id, commit_count FROM file_stats").fetchall():
66
+ file_commits[fs["file_id"]] = fs["commit_count"] or 1
67
+
68
+ warnings = {} # keyed by path, keep highest cochange
69
+
70
+ for path, fid in file_map.items():
71
+ rows = conn.execute(
72
+ """SELECT file_id_a, file_id_b, cochange_count
73
+ FROM git_cochange
74
+ WHERE (file_id_a = ? OR file_id_b = ?)
75
+ AND cochange_count >= ?""",
76
+ (fid, fid, min_cochanges),
77
+ ).fetchall()
78
+
79
+ for r in rows:
80
+ partner_fid = r["file_id_b"] if r["file_id_a"] == fid else r["file_id_a"]
81
+ if partner_fid in change_fids:
82
+ continue # already in the diff, no warning needed
83
+
84
+ cochanges = r["cochange_count"]
85
+ avg = (file_commits.get(fid, 1) + file_commits.get(partner_fid, 1)) / 2
86
+ strength = cochanges / avg if avg > 0 else 0
87
+
88
+ partner_path = id_to_path.get(partner_fid, f"file_id={partner_fid}")
89
+ if partner_path not in warnings or cochanges > warnings[partner_path]["cochanges"]:
90
+ warnings[partner_path] = {
91
+ "path": partner_path,
92
+ "cochanges": cochanges,
93
+ "strength": round(strength, 2),
94
+ "partner_of": path,
95
+ }
96
+
97
+ return sorted(warnings.values(), key=lambda x: -x["cochanges"])
98
+
99
+
100
+ # ---------------------------------------------------------------------------
101
+ # Fitness check helper (scoped to changed files)
102
+ # ---------------------------------------------------------------------------
103
+
104
+
105
+ def _collect_fitness_violations(conn, file_map, root):
106
+ """Run fitness rules scoped to the changed files.
107
+
108
+ For dependency rules: only report violations where the source is in the
109
+ changed files (i.e. edges introduced/present in the diff).
110
+ For metric rules on per-symbol metrics: only report symbols in changed files.
111
+ For global metrics and naming rules: run normally (not file-scoped).
112
+
113
+ Returns (rule_results, violations) lists.
114
+ """
115
+ from roam.commands.cmd_fitness import _load_rules
116
+
117
+ rules = _load_rules(root)
118
+ if not rules:
119
+ return [], []
120
+
121
+ changed_paths = set(file_map.keys())
122
+ changed_fids = set(file_map.values())
123
+
124
+ all_violations = []
125
+ rule_results = []
126
+
127
+ for rule in rules:
128
+ rtype = rule.get("type", "")
129
+ violations = []
130
+
131
+ if rtype == "dependency":
132
+ violations = _check_dep_rule_scoped(rule, conn, changed_paths)
133
+ elif rtype == "metric":
134
+ violations = _check_metric_rule_scoped(rule, conn, changed_fids)
135
+ elif rtype == "naming":
136
+ violations = _check_naming_rule_scoped(rule, conn, changed_fids)
137
+
138
+ status = "PASS" if not violations else "FAIL"
139
+ rule_results.append(
140
+ {
141
+ "name": rule.get("name", "unnamed"),
142
+ "type": rtype,
143
+ "status": status,
144
+ "violations": len(violations),
145
+ }
146
+ )
147
+ all_violations.extend(violations)
148
+
149
+ return rule_results, all_violations
150
+
151
+
152
+ def _check_dep_rule_scoped(rule, conn, changed_paths):
153
+ """Check dependency rule, only reporting edges whose source is in changed files."""
154
+ from_pattern = rule.get("from", "**")
155
+ to_pattern = rule.get("to", "**")
156
+ allow = rule.get("allow", False)
157
+
158
+ rows = conn.execute(
159
+ """SELECT e.source_id, e.target_id, e.kind, e.line,
160
+ sf.path as source_path, tf.path as target_path,
161
+ ss.name as source_name, ts.name as target_name
162
+ FROM edges e
163
+ JOIN symbols ss ON e.source_id = ss.id
164
+ JOIN symbols ts ON e.target_id = ts.id
165
+ JOIN files sf ON ss.file_id = sf.id
166
+ JOIN files tf ON ts.file_id = tf.id"""
167
+ ).fetchall()
168
+
169
+ violations = []
170
+ for r in rows:
171
+ # Only flag edges originating from changed files
172
+ if r["source_path"] not in changed_paths:
173
+ continue
174
+ src_match = fnmatch.fnmatch(r["source_path"], from_pattern)
175
+ tgt_match = fnmatch.fnmatch(r["target_path"], to_pattern)
176
+
177
+ if src_match and tgt_match and not allow:
178
+ violations.append(
179
+ {
180
+ "rule": rule["name"],
181
+ "type": "dependency",
182
+ "message": f"{r['source_name']} -> {r['target_name']}",
183
+ "source": f"{r['source_path']}:{r['line'] or '?'}",
184
+ "target": r["target_path"],
185
+ "edge_kind": r["kind"],
186
+ }
187
+ )
188
+
189
+ return violations
190
+
191
+
192
+ def _check_metric_rule_scoped(rule, conn, changed_fids):
193
+ """Check metric rules scoped to changed files where applicable."""
194
+ from roam.output.formatter import loc
195
+
196
+ metric = rule.get("metric", "")
197
+ max_val = rule.get("max")
198
+ violations = []
199
+
200
+ if metric == "cognitive_complexity" and changed_fids:
201
+ threshold = max_val if max_val is not None else 999
202
+ ph = ",".join("?" for _ in changed_fids)
203
+ rows = conn.execute(
204
+ f"""SELECT sm.cognitive_complexity, s.name, s.kind,
205
+ s.line_start, f.path
206
+ FROM symbol_metrics sm
207
+ JOIN symbols s ON sm.symbol_id = s.id
208
+ JOIN files f ON s.file_id = f.id
209
+ WHERE s.file_id IN ({ph})
210
+ AND sm.cognitive_complexity > ?
211
+ ORDER BY sm.cognitive_complexity DESC""",
212
+ list(changed_fids) + [threshold],
213
+ ).fetchall()
214
+ for r in rows:
215
+ violations.append(
216
+ {
217
+ "rule": rule["name"],
218
+ "type": "metric",
219
+ "message": (f"{r['name']} complexity={r['cognitive_complexity']:.0f} (max={threshold})"),
220
+ "source": loc(r["path"], r["line_start"]),
221
+ "metric": "cognitive_complexity",
222
+ "value": r["cognitive_complexity"],
223
+ "threshold": threshold,
224
+ }
225
+ )
226
+ elif metric in ("cycles", "health_score"):
227
+ # Global metrics -- delegate to full checker
228
+ from roam.commands.cmd_fitness import _check_metric_rule
229
+
230
+ violations = _check_metric_rule(rule, conn)
231
+ # Other count-based metrics run globally too
232
+ elif metric in ("god_components", "bottlenecks", "dead_exports"):
233
+ from roam.commands.cmd_fitness import _check_metric_rule
234
+
235
+ violations = _check_metric_rule(rule, conn)
236
+
237
+ return violations
238
+
239
+
240
+ def _check_naming_rule_scoped(rule, conn, changed_fids):
241
+ """Check naming rules scoped to changed files."""
242
+ import re
243
+
244
+ from roam.output.formatter import loc
245
+
246
+ kind = rule.get("kind", "function")
247
+ pattern = rule.get("pattern", "")
248
+ exclude = rule.get("exclude", "")
249
+
250
+ if not pattern or not changed_fids:
251
+ return []
252
+
253
+ regex = re.compile(pattern)
254
+ exclude_re = re.compile(exclude) if exclude else None
255
+
256
+ ph = ",".join("?" for _ in changed_fids)
257
+ rows = conn.execute(
258
+ f"""SELECT s.name, s.kind, s.line_start, f.path
259
+ FROM symbols s
260
+ JOIN files f ON s.file_id = f.id
261
+ WHERE s.kind = ? AND s.file_id IN ({ph})""",
262
+ [kind] + list(changed_fids),
263
+ ).fetchall()
264
+
265
+ violations = []
266
+ for r in rows:
267
+ name = r["name"]
268
+ if exclude_re and exclude_re.match(name):
269
+ continue
270
+ if not regex.match(name):
271
+ violations.append(
272
+ {
273
+ "rule": rule["name"],
274
+ "type": "naming",
275
+ "message": f"{name} does not match {pattern}",
276
+ "source": loc(r["path"], r["line_start"]),
277
+ }
278
+ )
279
+
280
+ return violations
281
+
282
+
283
+ # ---------------------------------------------------------------------------
284
+ # CLI command
285
+ # ---------------------------------------------------------------------------
286
+
287
+
288
+ @click.command("diff")
289
+ @click.argument("commit_range", required=False, default=None)
290
+ @click.option("--staged", is_flag=True, help="Analyze staged changes instead of unstaged")
291
+ @click.option(
292
+ "--full",
293
+ is_flag=True,
294
+ help="Show all results without truncation and enable --tests --coupling --fitness",
295
+ )
296
+ @click.option("--tests", is_flag=True, help="Show affected test files")
297
+ @click.option("--coupling", is_flag=True, help="Warn about missing co-change partners")
298
+ @click.option("--fitness", is_flag=True, help="Check fitness rules against changed files")
299
+ @click.pass_context
300
+ def diff_cmd(ctx, commit_range, staged, full, tests, coupling, fitness):
301
+ """Show blast radius: what code is affected by your changes.
302
+
303
+ Optionally pass a COMMIT_RANGE (e.g. HEAD~3..HEAD, abc123, main..feature)
304
+ to analyze committed changes instead of uncommitted ones.
305
+
306
+ Use --tests, --coupling, --fitness to add extra analysis sections,
307
+ or --full to enable all three plus untruncated output.
308
+ """
309
+ json_mode = ctx.obj.get("json") if ctx.obj else False
310
+ ensure_index()
311
+ root = find_project_root()
312
+
313
+ # --full implies all three extras
314
+ if full:
315
+ tests = True
316
+ coupling = True
317
+ fitness = True
318
+
319
+ changed = get_changed_files(root, staged=staged, commit_range=commit_range)
320
+ if not changed:
321
+ label = commit_range or ("staged" if staged else "unstaged")
322
+ click.echo(f"No changes found for {label}.")
323
+ return
324
+
325
+ with open_db(readonly=True) as conn:
326
+ # Map changed files to file IDs
327
+ file_map = resolve_changed_to_db(conn, changed)
328
+
329
+ if not file_map:
330
+ click.echo(f"Changed files not found in index ({len(changed)} files changed).")
331
+ click.echo("Try running `roam index` first.")
332
+ return
333
+
334
+ # Get symbols in changed files
335
+ sym_by_file = {}
336
+ for path, fid in file_map.items():
337
+ syms = conn.execute("SELECT id, name, kind FROM symbols WHERE file_id = ?", (fid,)).fetchall()
338
+ sym_by_file[path] = syms
339
+
340
+ total_syms = sum(len(s) for s in sym_by_file.values())
341
+
342
+ # Build graph and compute impact
343
+ try:
344
+ import networkx as nx
345
+
346
+ from roam.graph.builder import build_symbol_graph
347
+ except ImportError:
348
+ click.echo("Graph module not available.")
349
+ return
350
+
351
+ G = build_symbol_graph(conn)
352
+ RG = G.reverse()
353
+
354
+ # Per-file impact analysis
355
+ file_impacts = []
356
+ all_affected_files = set()
357
+ all_affected_syms = set()
358
+
359
+ for path, syms in sym_by_file.items():
360
+ file_dependents = set()
361
+ file_affected_files = set()
362
+ for s in syms:
363
+ sid = s["id"]
364
+ if sid in RG:
365
+ deps = nx.descendants(RG, sid)
366
+ file_dependents.update(deps)
367
+ for d in deps:
368
+ node = G.nodes.get(d, {})
369
+ fp = node.get("file_path")
370
+ if fp and fp != path:
371
+ file_affected_files.add(fp)
372
+
373
+ all_affected_syms.update(file_dependents)
374
+ all_affected_files.update(file_affected_files)
375
+
376
+ file_impacts.append(
377
+ {
378
+ "path": path,
379
+ "symbols": len(syms),
380
+ "affected_syms": len(file_dependents),
381
+ "affected_files": len(file_affected_files),
382
+ }
383
+ )
384
+
385
+ # Sort by blast radius
386
+ file_impacts.sort(key=lambda x: x["affected_syms"], reverse=True)
387
+
388
+ # ── Extra analyses ───────────────────────────────────────────
389
+
390
+ # Affected tests
391
+ test_results = []
392
+ pytest_cmd = ""
393
+ if tests:
394
+ test_results, pytest_cmd = _collect_affected_tests(conn, sym_by_file)
395
+
396
+ # Coupling warnings
397
+ coupling_warnings = []
398
+ if coupling:
399
+ try:
400
+ coupling_warnings = _collect_coupling_warnings(conn, file_map)
401
+ except Exception:
402
+ pass # table may not exist in older indexes
403
+
404
+ # Fitness violations
405
+ fitness_rule_results = []
406
+ fitness_violations = []
407
+ if fitness:
408
+ try:
409
+ fitness_rule_results, fitness_violations = _collect_fitness_violations(conn, file_map, root)
410
+ except Exception:
411
+ pass # fitness.yaml may not exist
412
+
413
+ # ── JSON output ──────────────────────────────────────────────
414
+
415
+ if json_mode:
416
+ envelope_data = dict(
417
+ label=commit_range or ("staged" if staged else "unstaged"),
418
+ changed_files=len(file_map),
419
+ symbols_defined=total_syms,
420
+ affected_symbols=len(all_affected_syms),
421
+ affected_files=len(all_affected_files),
422
+ per_file=file_impacts,
423
+ blast_radius=sorted(all_affected_files),
424
+ )
425
+
426
+ summary = {
427
+ "changed_files": len(file_map),
428
+ "affected_symbols": len(all_affected_syms),
429
+ "affected_files": len(all_affected_files),
430
+ }
431
+
432
+ if tests:
433
+ direct = sum(1 for t in test_results if t["kind"] == "DIRECT")
434
+ transitive = sum(1 for t in test_results if t["kind"] == "TRANSITIVE")
435
+ colocated = sum(1 for t in test_results if t["kind"] == "COLOCATED")
436
+ test_files = []
437
+ seen = set()
438
+ for t in test_results:
439
+ if t["file"] not in seen:
440
+ seen.add(t["file"])
441
+ test_files.append(t["file"])
442
+
443
+ summary["affected_tests"] = len(test_results)
444
+ envelope_data["affected_tests"] = {
445
+ "total": len(test_results),
446
+ "direct": direct,
447
+ "transitive": transitive,
448
+ "colocated": colocated,
449
+ "test_files": test_files,
450
+ "pytest_command": pytest_cmd,
451
+ "tests": [
452
+ {
453
+ "file": t["file"],
454
+ "symbol": t["symbol"],
455
+ "kind": t["kind"],
456
+ "hops": t["hops"],
457
+ "via": t["via"],
458
+ }
459
+ for t in test_results
460
+ ],
461
+ }
462
+
463
+ if coupling:
464
+ summary["coupling_warnings"] = len(coupling_warnings)
465
+ envelope_data["coupling_warnings"] = coupling_warnings
466
+
467
+ if fitness:
468
+ failed_count = sum(1 for r in fitness_rule_results if r["status"] == "FAIL")
469
+ summary["fitness_violations"] = len(fitness_violations)
470
+ summary["fitness_rules_failed"] = failed_count
471
+ envelope_data["fitness_violations"] = {
472
+ "rules": fitness_rule_results,
473
+ "violations": fitness_violations[:100],
474
+ }
475
+
476
+ click.echo(
477
+ to_json(
478
+ json_envelope(
479
+ "diff",
480
+ summary=summary,
481
+ **envelope_data,
482
+ )
483
+ )
484
+ )
485
+ return
486
+
487
+ # ── Text output ──────────────────────────────────────────────
488
+
489
+ if commit_range:
490
+ label = commit_range
491
+ else:
492
+ label = "staged" if staged else "unstaged"
493
+ click.echo(f"=== Blast Radius ({label} changes) ===\n")
494
+ click.echo(f"Changed files: {len(file_map)} Symbols defined: {total_syms}")
495
+ click.echo(f"Affected symbols: {len(all_affected_syms)} Affected files: {len(all_affected_files)}")
496
+ click.echo()
497
+
498
+ # Per-file breakdown
499
+ rows = []
500
+ display = file_impacts if full else file_impacts[:15]
501
+ for fi in display:
502
+ rows.append(
503
+ [
504
+ fi["path"],
505
+ str(fi["symbols"]),
506
+ str(fi["affected_syms"]),
507
+ str(fi["affected_files"]),
508
+ ]
509
+ )
510
+ click.echo(
511
+ format_table(
512
+ ["Changed file", "Symbols", "Affected syms", "Affected files"],
513
+ rows,
514
+ )
515
+ )
516
+ if not full and len(file_impacts) > 15:
517
+ click.echo(f"\n(+{len(file_impacts) - 15} more files)")
518
+
519
+ # List affected files
520
+ if all_affected_files:
521
+ click.echo(f"\nFiles in blast radius ({len(all_affected_files)}):")
522
+ sorted_files = sorted(all_affected_files)
523
+ show = sorted_files if full else sorted_files[:20]
524
+ for fp in show:
525
+ click.echo(f" {fp}")
526
+ if not full and len(sorted_files) > 20:
527
+ click.echo(f" (+{len(sorted_files) - 20} more)")
528
+
529
+ # ── Affected tests section ───────────────────────────────────
530
+
531
+ if tests:
532
+ click.echo()
533
+ if not test_results:
534
+ click.echo("=== Affected Tests ===\n")
535
+ click.echo("No affected tests found.")
536
+ else:
537
+ direct = sum(1 for t in test_results if t["kind"] == "DIRECT")
538
+ transitive = sum(1 for t in test_results if t["kind"] == "TRANSITIVE")
539
+ colocated = sum(1 for t in test_results if t["kind"] == "COLOCATED")
540
+ click.echo(
541
+ f"=== Affected Tests ({len(test_results)}: "
542
+ f"{direct} direct, {transitive} transitive, "
543
+ f"{colocated} colocated) ===\n"
544
+ )
545
+
546
+ display_tests = test_results if full else test_results[:20]
547
+ for t in display_tests:
548
+ kind_tag = f"{t['kind']:<12s}"
549
+ if t["symbol"]:
550
+ test_label = f"{t['file']}::{t['symbol']}"
551
+ else:
552
+ test_label = t["file"]
553
+
554
+ if t["kind"] == "DIRECT":
555
+ detail = f"({t['hops']} hop)"
556
+ elif t["kind"] == "TRANSITIVE":
557
+ via_str = f" via {t['via']}" if t["via"] else ""
558
+ detail = f"({t['hops']} hops{via_str})"
559
+ else:
560
+ detail = "(same directory)"
561
+
562
+ click.echo(f" {kind_tag} {test_label:<55s} {detail}")
563
+
564
+ if not full and len(test_results) > 20:
565
+ click.echo(f" (+{len(test_results) - 20} more)")
566
+
567
+ if pytest_cmd:
568
+ click.echo(f"\nRun: {pytest_cmd}")
569
+
570
+ # ── Coupling warnings section ────────────────────────────────
571
+
572
+ if coupling:
573
+ click.echo()
574
+ click.echo("=== Coupling Warnings ===\n")
575
+ if not coupling_warnings:
576
+ click.echo("No missing co-change partners.")
577
+ else:
578
+ click.echo(f"Missing co-change partners ({len(coupling_warnings)}):")
579
+ click.echo("(files you usually change together but are not in this diff)")
580
+ cpl_rows = []
581
+ display_cpl = coupling_warnings if full else coupling_warnings[:10]
582
+ for w in display_cpl:
583
+ cpl_rows.append(
584
+ [
585
+ w["path"],
586
+ str(w["cochanges"]),
587
+ f"{w['strength']:.0%}",
588
+ w["partner_of"],
589
+ ]
590
+ )
591
+ click.echo(
592
+ format_table(
593
+ [
594
+ "Usually changes with",
595
+ "Co-changed",
596
+ "Strength",
597
+ "Partner of",
598
+ ],
599
+ cpl_rows,
600
+ )
601
+ )
602
+ if not full and len(coupling_warnings) > 10:
603
+ click.echo(f"\n(+{len(coupling_warnings) - 10} more warnings)")
604
+
605
+ # ── Fitness violations section ───────────────────────────────
606
+
607
+ if fitness:
608
+ click.echo()
609
+ if not fitness_rule_results:
610
+ click.echo("=== Fitness Check ===\n")
611
+ click.echo("No fitness rules found. Create .roam/fitness.yaml or run: roam fitness --init")
612
+ else:
613
+ failed = sum(1 for r in fitness_rule_results if r["status"] == "FAIL")
614
+ passed = sum(1 for r in fitness_rule_results if r["status"] == "PASS")
615
+ click.echo(
616
+ f"=== Fitness Check ({len(fitness_rule_results)} rules, {passed} passed, {failed} failed) ===\n"
617
+ )
618
+
619
+ for rr in fitness_rule_results:
620
+ icon = "PASS" if rr["status"] == "PASS" else "FAIL"
621
+ detail = f" ({rr['violations']} violations)" if rr["violations"] else ""
622
+ click.echo(f" [{icon}] {rr['name']}{detail}")
623
+
624
+ if fitness_violations:
625
+ click.echo(f"\nViolations in changed files ({len(fitness_violations)}):\n")
626
+ display_v = fitness_violations if full else fitness_violations[:15]
627
+ for v in display_v:
628
+ src = v.get("source", "")
629
+ click.echo(f" {v['rule']}: {v['message']}")
630
+ if src:
631
+ click.echo(f" at {src}")
632
+ if not full and len(fitness_violations) > 15:
633
+ click.echo(f"\n (+{len(fitness_violations) - 15} more)")