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,706 @@
1
+ """Compound pre-change safety check.
2
+
3
+ Combines blast radius, affected tests, complexity, coupling, conventions,
4
+ and fitness violations into a single call -- reducing round-trips for AI
5
+ agents from 5-6 calls to 1.
6
+ """
7
+
8
+ from collections import Counter, defaultdict
9
+
10
+ import click
11
+
12
+ from roam.commands.changed_files import (
13
+ get_changed_files,
14
+ resolve_changed_to_db,
15
+ )
16
+ from roam.commands.cmd_affected_tests import (
17
+ _gather_affected_tests,
18
+ _looks_like_file,
19
+ _resolve_file_symbols,
20
+ )
21
+ from roam.commands.cmd_conventions import (
22
+ _group_for_kind,
23
+ classify_case,
24
+ )
25
+ from roam.commands.cmd_fitness import _CHECKERS, _load_rules
26
+ from roam.commands.resolve import ensure_index, find_symbol
27
+ from roam.db.connection import find_project_root, open_db
28
+ from roam.output.formatter import (
29
+ json_envelope,
30
+ loc,
31
+ to_json,
32
+ )
33
+
34
+ # ---------------------------------------------------------------------------
35
+ # Risk-level helpers
36
+ # ---------------------------------------------------------------------------
37
+
38
+
39
+ def _blast_severity(affected_syms: int, affected_files: int) -> str:
40
+ if affected_syms >= 50 or affected_files >= 15:
41
+ return "CRITICAL"
42
+ if affected_syms >= 20 or affected_files >= 8:
43
+ return "HIGH"
44
+ if affected_syms >= 5 or affected_files >= 3:
45
+ return "MEDIUM"
46
+ return "LOW"
47
+
48
+
49
+ def _test_severity(direct: int, transitive: int, colocated: int) -> str:
50
+ total = direct + transitive + colocated
51
+ if total == 0:
52
+ return "WARNING"
53
+ return "OK"
54
+
55
+
56
+ def _complexity_severity(cc: float, nesting: int) -> str:
57
+ if cc >= 25:
58
+ return "CRITICAL"
59
+ if cc >= 15 or nesting >= 5:
60
+ return "HIGH"
61
+ if cc >= 8 or nesting >= 4:
62
+ return "MEDIUM"
63
+ return "LOW"
64
+
65
+
66
+ def _coupling_severity(missing_count: int) -> str:
67
+ if missing_count >= 5:
68
+ return "HIGH"
69
+ if missing_count >= 2:
70
+ return "MEDIUM"
71
+ if missing_count >= 1:
72
+ return "LOW"
73
+ return "OK"
74
+
75
+
76
+ def _convention_severity(violation_count: int) -> str:
77
+ if violation_count >= 5:
78
+ return "HIGH"
79
+ if violation_count >= 1:
80
+ return "WARNING"
81
+ return "OK"
82
+
83
+
84
+ def _fitness_severity(failed_rules: int) -> str:
85
+ if failed_rules >= 3:
86
+ return "CRITICAL"
87
+ if failed_rules >= 1:
88
+ return "WARNING"
89
+ return "OK"
90
+
91
+
92
+ _SEVERITY_ORDER = {"CRITICAL": 4, "HIGH": 3, "WARNING": 2, "MEDIUM": 2, "LOW": 1, "OK": 0}
93
+
94
+
95
+ def _overall_risk(*severities: str) -> str:
96
+ """Compute overall risk from individual severity labels."""
97
+ max_val = max(_SEVERITY_ORDER.get(s, 0) for s in severities)
98
+ if max_val >= 4:
99
+ return "CRITICAL"
100
+ if max_val >= 3:
101
+ return "HIGH"
102
+ if max_val >= 2:
103
+ return "MEDIUM"
104
+ return "LOW"
105
+
106
+
107
+ def _severity_tag(sev: str) -> str:
108
+ return f"[{sev}]"
109
+
110
+
111
+ # ---------------------------------------------------------------------------
112
+ # 1. Blast radius
113
+ # ---------------------------------------------------------------------------
114
+
115
+
116
+ def _check_blast_radius(conn, sym_ids, file_paths):
117
+ """Compute blast radius: affected symbols and files via reverse edges."""
118
+ try:
119
+ import networkx as nx
120
+
121
+ from roam.graph.builder import build_symbol_graph
122
+ except ImportError:
123
+ return {
124
+ "affected_symbols": 0,
125
+ "affected_files": 0,
126
+ "affected_file_list": [],
127
+ "severity": "LOW",
128
+ }
129
+
130
+ G = build_symbol_graph(conn)
131
+ RG = G.reverse()
132
+
133
+ all_affected_syms = set()
134
+ all_affected_files = set()
135
+
136
+ for sid in sym_ids:
137
+ if sid in RG:
138
+ deps = nx.descendants(RG, sid)
139
+ all_affected_syms.update(deps)
140
+ for d in deps:
141
+ node = G.nodes.get(d, {})
142
+ fp = node.get("file_path")
143
+ if fp and fp not in file_paths:
144
+ all_affected_files.add(fp)
145
+
146
+ severity = _blast_severity(len(all_affected_syms), len(all_affected_files))
147
+
148
+ return {
149
+ "affected_symbols": len(all_affected_syms),
150
+ "affected_files": len(all_affected_files),
151
+ "affected_file_list": sorted(all_affected_files)[:20],
152
+ "severity": severity,
153
+ }
154
+
155
+
156
+ # ---------------------------------------------------------------------------
157
+ # 2. Affected tests
158
+ # ---------------------------------------------------------------------------
159
+
160
+
161
+ def _check_affected_tests(conn, sym_ids, file_paths):
162
+ """Find tests that need to run."""
163
+ results = _gather_affected_tests(conn, sym_ids, file_paths)
164
+
165
+ direct = sum(1 for r in results if r["kind"] == "DIRECT")
166
+ transitive = sum(1 for r in results if r["kind"] == "TRANSITIVE")
167
+ colocated = sum(1 for r in results if r["kind"] == "COLOCATED")
168
+
169
+ # Unique test files
170
+ seen = set()
171
+ test_files = []
172
+ for r in results:
173
+ if r["file"] not in seen:
174
+ seen.add(r["file"])
175
+ test_files.append(r["file"])
176
+
177
+ pytest_cmd = "pytest " + " ".join(test_files) if test_files else ""
178
+ severity = _test_severity(direct, transitive, colocated)
179
+
180
+ return {
181
+ "direct": direct,
182
+ "transitive": transitive,
183
+ "colocated": colocated,
184
+ "total": len(results),
185
+ "test_files": test_files,
186
+ "pytest_command": pytest_cmd,
187
+ "severity": severity,
188
+ }
189
+
190
+
191
+ # ---------------------------------------------------------------------------
192
+ # 3. Complexity
193
+ # ---------------------------------------------------------------------------
194
+
195
+
196
+ def _check_complexity(conn, sym_ids):
197
+ """Check complexity for target symbols."""
198
+ if not sym_ids:
199
+ return {
200
+ "max_cognitive_complexity": 0,
201
+ "max_nesting_depth": 0,
202
+ "high_complexity_symbols": [],
203
+ "severity": "LOW",
204
+ }
205
+
206
+ ph = ",".join("?" for _ in sym_ids)
207
+ rows = conn.execute(
208
+ f"""SELECT sm.cognitive_complexity, sm.nesting_depth,
209
+ sm.param_count, sm.line_count, sm.return_count,
210
+ sm.bool_op_count, sm.callback_depth,
211
+ s.name, s.kind, s.line_start, f.path as file_path
212
+ FROM symbol_metrics sm
213
+ JOIN symbols s ON sm.symbol_id = s.id
214
+ JOIN files f ON s.file_id = f.id
215
+ WHERE sm.symbol_id IN ({ph})
216
+ ORDER BY sm.cognitive_complexity DESC""",
217
+ list(sym_ids),
218
+ ).fetchall()
219
+
220
+ if not rows:
221
+ return {
222
+ "max_cognitive_complexity": 0,
223
+ "max_nesting_depth": 0,
224
+ "high_complexity_symbols": [],
225
+ "severity": "LOW",
226
+ }
227
+
228
+ max_cc = max(r["cognitive_complexity"] for r in rows)
229
+ max_nest = max(r["nesting_depth"] for r in rows)
230
+
231
+ high = [
232
+ {
233
+ "name": r["name"],
234
+ "kind": r["kind"],
235
+ "file": r["file_path"],
236
+ "line": r["line_start"],
237
+ "cognitive_complexity": r["cognitive_complexity"],
238
+ "nesting_depth": r["nesting_depth"],
239
+ }
240
+ for r in rows
241
+ if r["cognitive_complexity"] >= 8
242
+ ]
243
+
244
+ severity = _complexity_severity(max_cc, max_nest)
245
+
246
+ return {
247
+ "max_cognitive_complexity": round(max_cc, 1),
248
+ "max_nesting_depth": max_nest,
249
+ "high_complexity_symbols": high[:10],
250
+ "severity": severity,
251
+ }
252
+
253
+
254
+ # ---------------------------------------------------------------------------
255
+ # 4. Coupling (temporal co-change)
256
+ # ---------------------------------------------------------------------------
257
+
258
+
259
+ def _check_coupling(conn, file_ids, file_paths):
260
+ """Find temporally-coupled files that should change together."""
261
+ if not file_ids:
262
+ return {
263
+ "coupled_files": 0,
264
+ "missing_partners": [],
265
+ "severity": "OK",
266
+ }
267
+
268
+ change_set = set(file_ids)
269
+
270
+ # Build lookups
271
+ id_to_path = {}
272
+ file_commits = {}
273
+ for f in conn.execute("SELECT id, path FROM files").fetchall():
274
+ id_to_path[f["id"]] = f["path"]
275
+ for fs in conn.execute("SELECT file_id, commit_count FROM file_stats").fetchall():
276
+ file_commits[fs["file_id"]] = fs["commit_count"] or 1
277
+
278
+ missing = []
279
+ min_strength = 0.3
280
+ min_cochanges = 2
281
+
282
+ for fid in file_ids:
283
+ partners = conn.execute(
284
+ """SELECT file_id_a, file_id_b, cochange_count
285
+ FROM git_cochange
286
+ WHERE file_id_a = ? OR file_id_b = ?""",
287
+ (fid, fid),
288
+ ).fetchall()
289
+
290
+ for p in partners:
291
+ partner_fid = p["file_id_b"] if p["file_id_a"] == fid else p["file_id_a"]
292
+ cochanges = p["cochange_count"]
293
+ if cochanges < min_cochanges:
294
+ continue
295
+
296
+ avg = (file_commits.get(fid, 1) + file_commits.get(partner_fid, 1)) / 2
297
+ strength = cochanges / avg if avg > 0 else 0
298
+ if strength < min_strength:
299
+ continue
300
+
301
+ if partner_fid not in change_set:
302
+ partner_path = id_to_path.get(partner_fid, f"file_id={partner_fid}")
303
+ source_path = id_to_path.get(fid, f"file_id={fid}")
304
+ missing.append(
305
+ {
306
+ "path": partner_path,
307
+ "strength": round(strength, 2),
308
+ "cochanges": cochanges,
309
+ "partner_of": source_path,
310
+ }
311
+ )
312
+
313
+ # Deduplicate by path (keep highest strength)
314
+ seen = {}
315
+ for m in missing:
316
+ if m["path"] not in seen or m["strength"] > seen[m["path"]]["strength"]:
317
+ seen[m["path"]] = m
318
+ missing = sorted(seen.values(), key=lambda x: -x["strength"])
319
+
320
+ severity = _coupling_severity(len(missing))
321
+
322
+ return {
323
+ "coupled_files": len(missing),
324
+ "missing_partners": missing[:10],
325
+ "severity": severity,
326
+ }
327
+
328
+
329
+ # ---------------------------------------------------------------------------
330
+ # 5. Convention compliance
331
+ # ---------------------------------------------------------------------------
332
+
333
+
334
+ def _check_conventions(conn, sym_ids):
335
+ """Check if target symbols follow codebase naming conventions."""
336
+ if not sym_ids:
337
+ return {
338
+ "violations": [],
339
+ "violation_count": 0,
340
+ "severity": "OK",
341
+ }
342
+
343
+ # First, determine dominant naming style per kind-group from whole codebase
344
+ all_symbols = conn.execute("""
345
+ SELECT s.name, s.kind
346
+ FROM symbols s
347
+ WHERE s.kind IN ('function', 'method', 'class', 'interface',
348
+ 'struct', 'trait', 'enum', 'variable',
349
+ 'constant', 'property', 'field', 'type_alias')
350
+ """).fetchall()
351
+
352
+ group_cases = defaultdict(Counter)
353
+ for sym in all_symbols:
354
+ group = _group_for_kind(sym["kind"])
355
+ style = classify_case(sym["name"])
356
+ if style:
357
+ group_cases[group][style] += 1
358
+
359
+ # Determine dominant style per group
360
+ dominant = {}
361
+ for group, counter in group_cases.items():
362
+ if counter:
363
+ dominant[group] = counter.most_common(1)[0][0]
364
+
365
+ # Now check target symbols
366
+ ph = ",".join("?" for _ in sym_ids)
367
+ target_syms = conn.execute(
368
+ f"""SELECT s.name, s.kind, s.line_start, f.path as file_path
369
+ FROM symbols s
370
+ JOIN files f ON s.file_id = f.id
371
+ WHERE s.id IN ({ph})""",
372
+ list(sym_ids),
373
+ ).fetchall()
374
+
375
+ violations = []
376
+ for sym in target_syms:
377
+ group = _group_for_kind(sym["kind"])
378
+ style = classify_case(sym["name"])
379
+ expected = dominant.get(group)
380
+ if style and expected and style != expected:
381
+ violations.append(
382
+ {
383
+ "name": sym["name"],
384
+ "kind": sym["kind"],
385
+ "actual_style": style,
386
+ "expected_style": expected,
387
+ "file": sym["file_path"],
388
+ "line": sym["line_start"],
389
+ }
390
+ )
391
+
392
+ severity = _convention_severity(len(violations))
393
+
394
+ return {
395
+ "violations": violations,
396
+ "violation_count": len(violations),
397
+ "severity": severity,
398
+ }
399
+
400
+
401
+ # ---------------------------------------------------------------------------
402
+ # 6. Fitness rule violations
403
+ # ---------------------------------------------------------------------------
404
+
405
+
406
+ def _check_fitness(conn, root):
407
+ """Run fitness rules from .roam/fitness.yaml and report failures."""
408
+ rules = _load_rules(root)
409
+ if not rules:
410
+ return {
411
+ "rules_checked": 0,
412
+ "rules_failed": 0,
413
+ "total_violations": 0,
414
+ "failed_rules": [],
415
+ "rule_details": [],
416
+ "severity": "OK",
417
+ }
418
+
419
+ all_violations = []
420
+ rule_results = []
421
+
422
+ for rule in rules:
423
+ rtype = rule.get("type", "")
424
+ checker = _CHECKERS.get(rtype)
425
+ if checker is None:
426
+ continue
427
+
428
+ try:
429
+ violations = checker(rule, conn)
430
+ except Exception:
431
+ violations = []
432
+
433
+ status = "PASS" if not violations else "FAIL"
434
+ rule_results.append(
435
+ {
436
+ "name": rule.get("name", "unnamed"),
437
+ "type": rtype,
438
+ "status": status,
439
+ "violations": len(violations),
440
+ }
441
+ )
442
+ all_violations.extend(violations)
443
+
444
+ failed = sum(1 for r in rule_results if r["status"] == "FAIL")
445
+ failed_names = [r["name"] for r in rule_results if r["status"] == "FAIL"]
446
+ severity = _fitness_severity(failed)
447
+
448
+ return {
449
+ "rules_checked": len(rule_results),
450
+ "rules_failed": failed,
451
+ "total_violations": len(all_violations),
452
+ "failed_rules": failed_names,
453
+ "rule_details": rule_results,
454
+ "severity": severity,
455
+ }
456
+
457
+
458
+ # ---------------------------------------------------------------------------
459
+ # Target resolution
460
+ # ---------------------------------------------------------------------------
461
+
462
+
463
+ def _resolve_targets(conn, target, staged, root):
464
+ """Resolve CLI arguments into (sym_ids, file_paths, file_ids, label).
465
+
466
+ Returns a tuple of:
467
+ - sym_ids: set of symbol IDs
468
+ - file_paths: set of file paths (str)
469
+ - file_ids: list of file IDs (int)
470
+ - label: human-readable label for the target
471
+ """
472
+ sym_ids = set()
473
+ file_paths = set()
474
+ file_ids = []
475
+ label = target or "staged changes"
476
+
477
+ if staged:
478
+ changed = get_changed_files(root, staged=True)
479
+ if not changed:
480
+ return sym_ids, file_paths, file_ids, "staged (no changes)"
481
+ file_map = resolve_changed_to_db(conn, changed)
482
+ if not file_map:
483
+ return sym_ids, file_paths, file_ids, "staged (not in index)"
484
+ for path, fid in file_map.items():
485
+ file_paths.add(path)
486
+ file_ids.append(fid)
487
+ syms = conn.execute("SELECT id FROM symbols WHERE file_id = ?", (fid,)).fetchall()
488
+ sym_ids.update(s["id"] for s in syms)
489
+ label = f"staged changes ({len(file_map)} files)"
490
+
491
+ if target:
492
+ target_norm = target.replace("\\", "/")
493
+ if _looks_like_file(target_norm):
494
+ sids, fpaths = _resolve_file_symbols(conn, target_norm)
495
+ if not sids:
496
+ return sym_ids, file_paths, file_ids, f"{target} (not found)"
497
+ sym_ids.update(sids)
498
+ file_paths.update(fpaths)
499
+ # Get file IDs for the resolved paths
500
+ for fp in fpaths:
501
+ row = conn.execute("SELECT id FROM files WHERE path = ?", (fp,)).fetchone()
502
+ if row:
503
+ file_ids.append(row["id"])
504
+ label = target_norm
505
+ else:
506
+ sym = find_symbol(conn, target)
507
+ if sym is None:
508
+ return sym_ids, file_paths, file_ids, f"{target} (not found)"
509
+ sym_ids.add(sym["id"])
510
+ file_paths.add(sym["file_path"])
511
+ # Get file ID
512
+ row = conn.execute("SELECT id FROM files WHERE path = ?", (sym["file_path"],)).fetchone()
513
+ if row:
514
+ file_ids.append(row["id"])
515
+ label = f"{sym['name']} ({loc(sym['file_path'], sym['line_start'])})"
516
+
517
+ return sym_ids, file_paths, file_ids, label
518
+
519
+
520
+ # ---------------------------------------------------------------------------
521
+ # CLI command
522
+ # ---------------------------------------------------------------------------
523
+
524
+
525
+ @click.command("preflight")
526
+ @click.argument("target", required=False, default=None)
527
+ @click.option("--staged", is_flag=True, help="Check staged changes")
528
+ @click.pass_context
529
+ def preflight(ctx, target, staged):
530
+ """Run a pre-change safety checklist for a symbol, file, or staged changes.
531
+
532
+ Combines blast radius, affected tests, complexity, coupling, conventions,
533
+ and fitness checks into a single report. Ideal for AI agents that want
534
+ one-call risk assessment before making changes.
535
+ """
536
+ json_mode = ctx.obj.get("json") if ctx.obj else False
537
+
538
+ if not target and not staged:
539
+ click.echo("Provide a TARGET symbol/file or use --staged.")
540
+ raise SystemExit(1)
541
+
542
+ ensure_index()
543
+ root = find_project_root()
544
+
545
+ with open_db(readonly=True) as conn:
546
+ # Resolve targets
547
+ sym_ids, file_paths, file_ids, label = _resolve_targets(
548
+ conn,
549
+ target,
550
+ staged,
551
+ root,
552
+ )
553
+
554
+ if not sym_ids:
555
+ if json_mode:
556
+ click.echo(
557
+ to_json(
558
+ json_envelope(
559
+ "preflight",
560
+ summary={
561
+ "target": label,
562
+ "risk_level": "UNKNOWN",
563
+ "error": "No symbols found",
564
+ },
565
+ )
566
+ )
567
+ )
568
+ else:
569
+ click.echo(f"No symbols found for: {label}")
570
+ return
571
+
572
+ # Run all checks
573
+ blast = _check_blast_radius(conn, sym_ids, file_paths)
574
+ tests = _check_affected_tests(conn, sym_ids, file_paths)
575
+ compl = _check_complexity(conn, sym_ids)
576
+ coupl = _check_coupling(conn, file_ids, file_paths)
577
+ convs = _check_conventions(conn, sym_ids)
578
+ fitns = _check_fitness(conn, root)
579
+
580
+ # Overall risk
581
+ risk = _overall_risk(
582
+ blast["severity"],
583
+ tests["severity"],
584
+ compl["severity"],
585
+ coupl["severity"],
586
+ convs["severity"],
587
+ fitns["severity"],
588
+ )
589
+
590
+ # Verdict
591
+ if risk == "LOW":
592
+ verdict = f"Safe to proceed — {risk} risk for {label}"
593
+ elif risk == "MEDIUM":
594
+ verdict = f"Proceed with caution — {risk} risk for {label}"
595
+ elif risk == "HIGH":
596
+ verdict = f"Review carefully — {risk} risk, {blast['affected_symbols']} symbols affected"
597
+ else:
598
+ verdict = f"Significant risk — {risk}, {blast['affected_symbols']} symbols in blast radius"
599
+
600
+ # JSON output
601
+ if json_mode:
602
+ click.echo(
603
+ to_json(
604
+ json_envelope(
605
+ "preflight",
606
+ summary={
607
+ "verdict": verdict,
608
+ "target": label,
609
+ "risk_level": risk,
610
+ "symbols_checked": len(sym_ids),
611
+ "files_checked": len(file_paths),
612
+ },
613
+ blast_radius={
614
+ "affected_symbols": blast["affected_symbols"],
615
+ "affected_files": blast["affected_files"],
616
+ "affected_file_list": blast["affected_file_list"],
617
+ "severity": blast["severity"],
618
+ },
619
+ tests={
620
+ "direct": tests["direct"],
621
+ "transitive": tests["transitive"],
622
+ "colocated": tests["colocated"],
623
+ "total": tests["total"],
624
+ "test_files": tests["test_files"],
625
+ "pytest_command": tests["pytest_command"],
626
+ "severity": tests["severity"],
627
+ },
628
+ complexity={
629
+ "max_cognitive_complexity": compl["max_cognitive_complexity"],
630
+ "max_nesting_depth": compl["max_nesting_depth"],
631
+ "high_complexity_symbols": compl["high_complexity_symbols"],
632
+ "severity": compl["severity"],
633
+ },
634
+ coupling={
635
+ "coupled_files": coupl["coupled_files"],
636
+ "missing_partners": coupl["missing_partners"],
637
+ "severity": coupl["severity"],
638
+ },
639
+ conventions={
640
+ "violation_count": convs["violation_count"],
641
+ "violations": convs["violations"],
642
+ "severity": convs["severity"],
643
+ },
644
+ fitness={
645
+ "rules_checked": fitns["rules_checked"],
646
+ "rules_failed": fitns["rules_failed"],
647
+ "total_violations": fitns["total_violations"],
648
+ "failed_rules": fitns["failed_rules"],
649
+ "rule_details": fitns["rule_details"],
650
+ "severity": fitns["severity"],
651
+ },
652
+ )
653
+ )
654
+ )
655
+ return
656
+
657
+ # Text output
658
+ click.echo(f"VERDICT: {verdict}\n")
659
+ click.echo(f"Pre-flight check for `{label}`:\n")
660
+
661
+ # Blast radius
662
+ blast_desc = f"{blast['affected_symbols']} symbols in {blast['affected_files']} files"
663
+ click.echo(f" Blast radius: {blast_desc:<40s} {_severity_tag(blast['severity'])}")
664
+
665
+ # Affected tests
666
+ test_desc = f"{tests['direct']} direct, {tests['transitive']} transitive"
667
+ if tests["colocated"]:
668
+ test_desc += f", {tests['colocated']} colocated"
669
+ click.echo(f" Affected tests: {test_desc:<40s} {_severity_tag(tests['severity'])}")
670
+
671
+ # Complexity
672
+ cc = compl["max_cognitive_complexity"]
673
+ nest = compl["max_nesting_depth"]
674
+ compl_desc = f"cc={cc:.0f}, nest={nest}"
675
+ click.echo(f" Complexity: {compl_desc:<40s} {_severity_tag(compl['severity'])}")
676
+
677
+ # Coupling
678
+ if coupl["coupled_files"] > 0:
679
+ coupl_desc = f"{coupl['coupled_files']} files often change together"
680
+ else:
681
+ coupl_desc = "no missing co-change partners"
682
+ click.echo(f" Coupling: {coupl_desc:<40s} {_severity_tag(coupl['severity'])}")
683
+
684
+ # Conventions
685
+ if convs["violation_count"] > 0:
686
+ conv_desc = f"{convs['violation_count']} naming violations"
687
+ else:
688
+ conv_desc = "no violations"
689
+ click.echo(f" Conventions: {conv_desc:<40s} {_severity_tag(convs['severity'])}")
690
+
691
+ # Fitness
692
+ if fitns["rules_checked"] == 0:
693
+ fit_desc = "no rules configured"
694
+ elif fitns["rules_failed"] > 0:
695
+ rule_names = ", ".join(fitns["failed_rules"][:3])
696
+ fit_desc = f"{fitns['rules_failed']} rules would fail ({rule_names})"
697
+ else:
698
+ fit_desc = f"all {fitns['rules_checked']} rules pass"
699
+ click.echo(f" Fitness: {fit_desc:<40s} {_severity_tag(fitns['severity'])}")
700
+
701
+ # Overall
702
+ click.echo(f"\n Overall risk: {risk}")
703
+
704
+ # Suggested tests
705
+ if tests["pytest_command"]:
706
+ click.echo(f" Suggested tests: {tests['pytest_command']}")