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,913 @@
1
+ """Proof-carrying PR attestation — bundle all evidence into one artifact."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import subprocess
8
+ from datetime import datetime, timezone
9
+ from pathlib import Path
10
+
11
+ import click
12
+
13
+ from roam.commands.changed_files import (
14
+ get_changed_files,
15
+ is_test_file,
16
+ resolve_changed_to_db,
17
+ )
18
+ from roam.commands.resolve import ensure_index
19
+ from roam.db.connection import find_project_root, open_db
20
+ from roam.output.formatter import abbrev_kind, json_envelope, to_json
21
+
22
+ # ---------------------------------------------------------------------------
23
+ # Evidence collectors
24
+ # ---------------------------------------------------------------------------
25
+
26
+
27
+ def _collect_blast_radius(conn, file_map):
28
+ """Compute blast radius for changed files.
29
+
30
+ Returns {changed_files, affected_symbols, affected_files, per_file}.
31
+ """
32
+ try:
33
+ import networkx as nx
34
+
35
+ from roam.graph.builder import build_symbol_graph
36
+ except ImportError:
37
+ return {
38
+ "changed_files": len(file_map),
39
+ "affected_symbols": 0,
40
+ "affected_files": 0,
41
+ "per_file": [],
42
+ }
43
+
44
+ G = build_symbol_graph(conn)
45
+ RG = G.reverse()
46
+
47
+ all_affected_syms = set()
48
+ all_affected_files = set()
49
+ sym_by_file = {}
50
+
51
+ for path, fid in file_map.items():
52
+ syms = conn.execute("SELECT id, name, kind FROM symbols WHERE file_id = ?", (fid,)).fetchall()
53
+ sym_by_file[path] = syms
54
+
55
+ for s in syms:
56
+ sid = s["id"]
57
+ if sid in RG:
58
+ deps = nx.descendants(RG, sid)
59
+ all_affected_syms.update(deps)
60
+ for d in deps:
61
+ node = G.nodes.get(d, {})
62
+ fp = node.get("file_path")
63
+ if fp and fp != path:
64
+ all_affected_files.add(fp)
65
+
66
+ return {
67
+ "changed_files": len(file_map),
68
+ "affected_symbols": len(all_affected_syms),
69
+ "affected_files": len(all_affected_files),
70
+ "sym_by_file": sym_by_file,
71
+ }
72
+
73
+
74
+ def _collect_risk(conn, root, file_map, staged, commit_range):
75
+ """Compute risk score.
76
+
77
+ Returns {score, level, verdict} or None on failure.
78
+ """
79
+ try:
80
+ import networkx as nx
81
+
82
+ from roam.commands.changed_files import is_low_risk_file
83
+ from roam.commands.cmd_coupling import _compute_surprise
84
+ from roam.commands.cmd_pr_risk import (
85
+ _author_count_risk,
86
+ _author_familiarity,
87
+ _calibrated_hotspot_score,
88
+ _detect_author,
89
+ )
90
+ from roam.graph.builder import build_symbol_graph
91
+ from roam.graph.layers import detect_layers # noqa: F401
92
+ except ImportError:
93
+ return None
94
+
95
+ total_syms = conn.execute("SELECT COUNT(*) FROM symbols").fetchone()[0]
96
+ author = _detect_author()
97
+
98
+ G = build_symbol_graph(conn)
99
+ RG = G.reverse()
100
+
101
+ # Blast radius factor
102
+ all_affected = set()
103
+ changed_sym_ids = set()
104
+ for path, fid in file_map.items():
105
+ syms = conn.execute("SELECT id FROM symbols WHERE file_id = ?", (fid,)).fetchall()
106
+ for s in syms:
107
+ changed_sym_ids.add(s["id"])
108
+ if s["id"] in RG:
109
+ all_affected.update(nx.descendants(RG, s["id"]))
110
+
111
+ blast_pct = len(all_affected) * 100 / total_syms if total_syms else 0
112
+
113
+ # Hotspot factor
114
+ hotspot_score = 0.0
115
+ churn_data = {}
116
+ for path, fid in file_map.items():
117
+ row = conn.execute(
118
+ "SELECT total_churn, commit_count FROM file_stats WHERE file_id = ?",
119
+ (fid,),
120
+ ).fetchone()
121
+ if row:
122
+ churn_data[path] = {"churn": row["total_churn"], "commits": row["commit_count"]}
123
+
124
+ if churn_data:
125
+ code_churn = {p: d for p, d in churn_data.items() if not is_low_risk_file(p)}
126
+ repo_churn_rows = conn.execute(
127
+ "SELECT f.path, fs.total_churn FROM file_stats fs "
128
+ "JOIN files f ON fs.file_id = f.id "
129
+ "WHERE fs.total_churn IS NOT NULL"
130
+ ).fetchall()
131
+ repo_code_churn = sorted(
132
+ float(r["total_churn"] or 0)
133
+ for r in repo_churn_rows
134
+ if (r["total_churn"] or 0) > 0 and not is_low_risk_file(r["path"])
135
+ )
136
+ if repo_code_churn and code_churn:
137
+ avg_changed = sum(d["churn"] for d in code_churn.values()) / len(code_churn)
138
+ hotspot_score = _calibrated_hotspot_score(avg_changed, repo_code_churn)
139
+
140
+ # Bus factor
141
+ author_counts = []
142
+ for path, fid in file_map.items():
143
+ if is_test_file(path) or is_low_risk_file(path):
144
+ continue
145
+ authors = conn.execute(
146
+ "SELECT DISTINCT gc.author FROM git_file_changes gfc "
147
+ "JOIN git_commits gc ON gfc.commit_id = gc.id "
148
+ "WHERE gfc.file_id = ?",
149
+ (fid,),
150
+ ).fetchall()
151
+ if authors:
152
+ author_counts.append(len(authors))
153
+ bus_factor_risk = _author_count_risk(author_counts) if author_counts else 0.0
154
+
155
+ # Test coverage
156
+ source_files = [p for p in file_map if not is_test_file(p) and not is_low_risk_file(p)]
157
+ covered_files = 0
158
+ for path in source_files:
159
+ fid = file_map[path]
160
+ has_test = any(
161
+ is_test_file(r["path"])
162
+ for r in conn.execute(
163
+ "SELECT f.path FROM file_edges fe JOIN files f ON fe.source_file_id = f.id WHERE fe.target_file_id = ?",
164
+ (fid,),
165
+ ).fetchall()
166
+ )
167
+ if has_test:
168
+ covered_files += 1
169
+ test_coverage = covered_files / len(source_files) if source_files else 0.0
170
+
171
+ # Coupling
172
+ coupling_score = 0.0
173
+ if len(file_map) > 1:
174
+ fids = list(file_map.values())
175
+ ph = ",".join("?" for _ in fids)
176
+ cross_edges = conn.execute(
177
+ f"SELECT COUNT(*) FROM file_edges WHERE source_file_id IN ({ph}) AND target_file_id IN ({ph})",
178
+ fids + fids,
179
+ ).fetchone()[0]
180
+ max_possible = len(fids) * (len(fids) - 1)
181
+ if max_possible > 0:
182
+ coupling_score = min(1.0, cross_edges / max_possible)
183
+
184
+ # Novelty
185
+ change_fids = list(file_map.values())
186
+ novelty, _, _ = _compute_surprise(conn, change_fids)
187
+
188
+ # Author familiarity
189
+ familiarity_risk = 0.0
190
+ if author:
191
+ familiarity_risk, _ = _author_familiarity(conn, author, file_map)
192
+
193
+ # Composite risk score
194
+ _factors = [
195
+ min(blast_pct / 100, 0.40),
196
+ hotspot_score * 0.30,
197
+ (1 - test_coverage) * 0.30,
198
+ bus_factor_risk * 0.20,
199
+ coupling_score * 0.20,
200
+ novelty * 0.15,
201
+ familiarity_risk,
202
+ ]
203
+ no_risk = 1.0
204
+ for f in _factors:
205
+ no_risk *= 1 - max(0, min(f, 0.99))
206
+ risk = int(min(100, (1 - no_risk) * 100))
207
+
208
+ if risk <= 25:
209
+ level = "LOW"
210
+ elif risk <= 50:
211
+ level = "MODERATE"
212
+ elif risk <= 75:
213
+ level = "HIGH"
214
+ else:
215
+ level = "CRITICAL"
216
+
217
+ return {"score": risk, "level": level}
218
+
219
+
220
+ def _collect_breaking(conn, root, base_ref):
221
+ """Detect breaking changes vs base_ref.
222
+
223
+ Returns {removed, signature_changed, renamed} lists.
224
+ """
225
+ try:
226
+ from roam.commands.cmd_breaking import (
227
+ _compare_file,
228
+ _extract_old_symbols,
229
+ _get_current_symbols,
230
+ _git_changed_files,
231
+ _git_show,
232
+ )
233
+ except ImportError:
234
+ return {"removed": [], "signature_changed": [], "renamed": []}
235
+
236
+ changed = _git_changed_files(root, base_ref)
237
+ if not changed:
238
+ return {"removed": [], "signature_changed": [], "renamed": []}
239
+
240
+ all_removed = []
241
+ all_sig_changed = []
242
+ all_renamed = []
243
+
244
+ for fpath in changed:
245
+ old_source = _git_show(root, base_ref, fpath)
246
+ if old_source is None:
247
+ continue
248
+ old_symbols = _extract_old_symbols(old_source, fpath)
249
+ if not old_symbols:
250
+ continue
251
+ new_symbols = _get_current_symbols(conn, fpath)
252
+ removed, sig_changed, renamed = _compare_file(fpath, old_symbols, new_symbols)
253
+ all_removed.extend(removed)
254
+ all_sig_changed.extend(sig_changed)
255
+ all_renamed.extend(renamed)
256
+
257
+ return {
258
+ "removed": all_removed,
259
+ "signature_changed": all_sig_changed,
260
+ "renamed": all_renamed,
261
+ }
262
+
263
+
264
+ def _collect_affected_tests_evidence(conn, sym_by_file):
265
+ """Gather affected tests.
266
+
267
+ Returns {selected, direct, transitive, colocated, command, tests}.
268
+ """
269
+ from roam.commands.cmd_diff import _collect_affected_tests
270
+
271
+ test_results, pytest_cmd = _collect_affected_tests(conn, sym_by_file)
272
+
273
+ direct = sum(1 for t in test_results if t["kind"] == "DIRECT")
274
+ transitive = sum(1 for t in test_results if t["kind"] == "TRANSITIVE")
275
+ colocated = sum(1 for t in test_results if t["kind"] == "COLOCATED")
276
+
277
+ return {
278
+ "selected": len(test_results),
279
+ "direct": direct,
280
+ "transitive": transitive,
281
+ "colocated": colocated,
282
+ "command": pytest_cmd,
283
+ "tests": [
284
+ {
285
+ "file": t["file"],
286
+ "symbol": t.get("symbol"),
287
+ "kind": t["kind"],
288
+ "hops": t.get("hops", 0),
289
+ }
290
+ for t in test_results[:50]
291
+ ],
292
+ }
293
+
294
+
295
+ def _collect_budget_evidence(conn, root):
296
+ """Evaluate budget rules.
297
+
298
+ Returns {rules_checked, passed, failed, skipped, rules}.
299
+ """
300
+ try:
301
+ from roam.commands.cmd_budget import _DEFAULT_BUDGETS, _evaluate_rule, _load_budgets
302
+ from roam.commands.metrics_history import collect_metrics
303
+ from roam.graph.diff import find_before_snapshot
304
+ except ImportError:
305
+ return {"rules_checked": 0, "passed": 0, "failed": 0, "skipped": 0, "rules": []}
306
+
307
+ cfg = root / ".roam" / "budget.yaml"
308
+ if not cfg.exists():
309
+ cfg = root / ".roam" / "budget.yml"
310
+
311
+ budgets = _load_budgets(cfg) if cfg.exists() else []
312
+ if not budgets:
313
+ budgets = list(_DEFAULT_BUDGETS)
314
+
315
+ before = find_before_snapshot(conn, root)
316
+ after = collect_metrics(conn)
317
+
318
+ if not before:
319
+ return {
320
+ "rules_checked": len(budgets),
321
+ "passed": 0,
322
+ "failed": 0,
323
+ "skipped": len(budgets),
324
+ "rules": [{"name": b.get("name", "unnamed"), "status": "SKIP"} for b in budgets],
325
+ }
326
+
327
+ results = [_evaluate_rule(b, before, after) for b in budgets]
328
+ passed = sum(1 for r in results if r["status"] == "PASS")
329
+ failed = sum(1 for r in results if r["status"] == "FAIL")
330
+ skipped = sum(1 for r in results if r["status"] == "SKIP")
331
+
332
+ return {
333
+ "rules_checked": len(results),
334
+ "passed": passed,
335
+ "failed": failed,
336
+ "skipped": skipped,
337
+ "rules": results,
338
+ }
339
+
340
+
341
+ def _collect_fitness_evidence(conn, file_map, root):
342
+ """Evaluate fitness rules scoped to changed files.
343
+
344
+ Returns {rules, violations}.
345
+ """
346
+ try:
347
+ from roam.commands.cmd_diff import _collect_fitness_violations
348
+
349
+ rule_results, violations = _collect_fitness_violations(conn, file_map, root)
350
+ return {"rules": rule_results, "violations": violations[:50]}
351
+ except Exception:
352
+ return {"rules": [], "violations": []}
353
+
354
+
355
+ def _collect_effects_evidence(conn, file_map):
356
+ """Gather effects for symbols in changed files.
357
+
358
+ Returns list of {symbol, file, direct_effects, transitive_effects}.
359
+ """
360
+ effects_list = []
361
+ try:
362
+ for path, fid in file_map.items():
363
+ rows = conn.execute(
364
+ "SELECT s.name, s.kind, se.effect_type, se.source "
365
+ "FROM symbol_effects se "
366
+ "JOIN symbols s ON se.symbol_id = s.id "
367
+ "WHERE s.file_id = ? "
368
+ "ORDER BY s.name, se.effect_type",
369
+ (fid,),
370
+ ).fetchall()
371
+
372
+ # Group by symbol
373
+ sym_effects: dict[str, dict] = {}
374
+ for r in rows:
375
+ name = r["name"]
376
+ if name not in sym_effects:
377
+ sym_effects[name] = {
378
+ "symbol": name,
379
+ "kind": r["kind"],
380
+ "file": path,
381
+ "direct_effects": [],
382
+ "transitive_effects": [],
383
+ }
384
+ if r["source"] == "direct":
385
+ sym_effects[name]["direct_effects"].append(r["effect_type"])
386
+ else:
387
+ sym_effects[name]["transitive_effects"].append(r["effect_type"])
388
+
389
+ effects_list.extend(sym_effects.values())
390
+ except Exception:
391
+ pass
392
+
393
+ return effects_list
394
+
395
+
396
+ # ---------------------------------------------------------------------------
397
+ # Content hash
398
+ # ---------------------------------------------------------------------------
399
+
400
+
401
+ def _content_hash(evidence: dict) -> str:
402
+ """Compute SHA-256 of the evidence payload for tamper detection."""
403
+ canonical = json.dumps(evidence, sort_keys=True, default=str)
404
+ return "sha256:" + hashlib.sha256(canonical.encode("utf-8")).hexdigest()
405
+
406
+
407
+ # ---------------------------------------------------------------------------
408
+ # Git range helpers
409
+ # ---------------------------------------------------------------------------
410
+
411
+
412
+ def _resolve_git_range(root, commit_range):
413
+ """Parse a commit range like 'main..HEAD' into (base_ref, head_ref).
414
+
415
+ Returns (base_ref, head_ref) tuple. For single refs, returns (ref, 'HEAD').
416
+ """
417
+ if commit_range and ".." in commit_range:
418
+ parts = commit_range.split("..", 1)
419
+ return parts[0], parts[1]
420
+ return commit_range or "HEAD", "HEAD"
421
+
422
+
423
+ def _get_git_hashes(root, base_ref, head_ref):
424
+ """Resolve refs to short hashes."""
425
+ hashes = {}
426
+ for label, ref in [("base", base_ref), ("head", head_ref)]:
427
+ try:
428
+ result = subprocess.run(
429
+ ["git", "rev-parse", "--short", ref],
430
+ cwd=str(root),
431
+ capture_output=True,
432
+ text=True,
433
+ timeout=10,
434
+ encoding="utf-8",
435
+ errors="replace",
436
+ )
437
+ if result.returncode == 0:
438
+ hashes[label] = result.stdout.strip()
439
+ except Exception:
440
+ pass
441
+ return hashes
442
+
443
+
444
+ # ---------------------------------------------------------------------------
445
+ # Verdict computation
446
+ # ---------------------------------------------------------------------------
447
+
448
+
449
+ def _compute_verdict(risk, breaking_data, fitness_data, budget_data):
450
+ """Determine safe_to_merge, conditions, and warnings.
451
+
452
+ Returns {safe_to_merge, conditions, warnings}.
453
+ """
454
+ conditions = []
455
+ warnings = []
456
+ safe = True
457
+
458
+ # Breaking changes
459
+ total_breaking = (
460
+ len(breaking_data.get("removed", []))
461
+ + len(breaking_data.get("signature_changed", []))
462
+ + len(breaking_data.get("renamed", []))
463
+ )
464
+ if total_breaking > 0:
465
+ warnings.append(f"{total_breaking} breaking changes detected")
466
+
467
+ # Risk level
468
+ if risk and risk.get("level") in ("HIGH", "CRITICAL"):
469
+ warnings.append(f"risk level is {risk['level']} ({risk['score']}/100)")
470
+
471
+ # Budget violations
472
+ budget_failed = budget_data.get("failed", 0)
473
+ if budget_failed > 0:
474
+ safe = False
475
+ conditions.append(f"{budget_failed} budget(s) exceeded")
476
+
477
+ # Fitness violations
478
+ fitness_violations = len(fitness_data.get("violations", []))
479
+ if fitness_violations > 0:
480
+ warnings.append(f"{fitness_violations} fitness violations in changed files")
481
+
482
+ # Tests needed
483
+ conditions.append("run selected tests")
484
+
485
+ return {
486
+ "safe_to_merge": safe,
487
+ "conditions": conditions,
488
+ "warnings": warnings,
489
+ }
490
+
491
+
492
+ # ---------------------------------------------------------------------------
493
+ # Markdown formatter
494
+ # ---------------------------------------------------------------------------
495
+
496
+
497
+ def _format_markdown(attestation, evidence, verdict):
498
+ """Format attestation as GitHub/GitLab compatible markdown."""
499
+ lines = []
500
+ lines.append("## Roam Attestation")
501
+ lines.append("")
502
+
503
+ # Verdict banner
504
+ safe_icon = "PASS" if verdict["safe_to_merge"] else "FAIL"
505
+ lines.append(f"**Verdict: {safe_icon}**")
506
+ if verdict["conditions"]:
507
+ lines.append("")
508
+ lines.append("Conditions:")
509
+ for c in verdict["conditions"]:
510
+ lines.append(f"- {c}")
511
+ if verdict["warnings"]:
512
+ lines.append("")
513
+ lines.append("Warnings:")
514
+ for w in verdict["warnings"]:
515
+ lines.append(f"- {w}")
516
+
517
+ lines.append("")
518
+
519
+ # Risk
520
+ risk = evidence.get("risk")
521
+ if risk:
522
+ lines.append(f"### Risk: {risk['level']} ({risk['score']}/100)")
523
+ lines.append("")
524
+
525
+ # Blast radius
526
+ br = evidence.get("blast_radius", {})
527
+ lines.append("### Blast Radius")
528
+ lines.append("")
529
+ lines.append("| Metric | Value |")
530
+ lines.append("|--------|-------|")
531
+ lines.append(f"| Changed files | {br.get('changed_files', 0)} |")
532
+ lines.append(f"| Affected symbols | {br.get('affected_symbols', 0)} |")
533
+ lines.append(f"| Affected files | {br.get('affected_files', 0)} |")
534
+ lines.append("")
535
+
536
+ # Breaking changes
537
+ bc = evidence.get("breaking_changes", {})
538
+ removed = len(bc.get("removed", []))
539
+ sig_changed = len(bc.get("signature_changed", []))
540
+ renamed = len(bc.get("renamed", []))
541
+ total_bc = removed + sig_changed + renamed
542
+ if total_bc > 0:
543
+ lines.append(f"### Breaking Changes ({total_bc})")
544
+ lines.append("")
545
+ if removed:
546
+ lines.append(f"- {removed} removed")
547
+ if sig_changed:
548
+ lines.append(f"- {sig_changed} signature changed")
549
+ if renamed:
550
+ lines.append(f"- {renamed} renamed")
551
+ lines.append("")
552
+ else:
553
+ lines.append("### Breaking Changes: None")
554
+ lines.append("")
555
+
556
+ # Budget
557
+ bg = evidence.get("budget", {})
558
+ if bg.get("rules_checked", 0) > 0:
559
+ lines.append(f"### Budget ({bg['passed']} passed, {bg['failed']} failed, {bg['skipped']} skipped)")
560
+ lines.append("")
561
+ for r in bg.get("rules", []):
562
+ status = r.get("status", "?")
563
+ name = r.get("name", "unnamed")
564
+ lines.append(f"- [{status}] {name}")
565
+ lines.append("")
566
+
567
+ # Tests
568
+ tests = evidence.get("tests", {})
569
+ if tests.get("selected", 0) > 0:
570
+ lines.append(f"### Affected Tests ({tests['selected']})")
571
+ lines.append("")
572
+ lines.append(
573
+ f"- {tests.get('direct', 0)} direct, {tests.get('transitive', 0)} transitive, {tests.get('colocated', 0)} colocated"
574
+ )
575
+ cmd = tests.get("command", "")
576
+ if cmd:
577
+ lines.append(f"- `{cmd}`")
578
+ lines.append("")
579
+
580
+ # Effects
581
+ effects = evidence.get("effects", [])
582
+ if effects:
583
+ lines.append(f"### Effects ({len(effects)} symbols)")
584
+ lines.append("")
585
+ for e in effects[:20]:
586
+ all_eff = e.get("direct_effects", []) + e.get("transitive_effects", [])
587
+ lines.append(f"- {e['symbol']}: {', '.join(all_eff)}")
588
+ lines.append("")
589
+
590
+ # Attestation metadata
591
+ lines.append("---")
592
+ lines.append(
593
+ f"*Generated by roam-code v{attestation.get('tool_version', '?')} at {attestation.get('timestamp', '?')}*"
594
+ )
595
+ if attestation.get("content_hash"):
596
+ lines.append(f"*Hash: `{attestation['content_hash']}`*")
597
+
598
+ return "\n".join(lines)
599
+
600
+
601
+ # ---------------------------------------------------------------------------
602
+ # CLI command
603
+ # ---------------------------------------------------------------------------
604
+
605
+
606
+ @click.command("attest")
607
+ @click.argument("commit_range", required=False, default=None)
608
+ @click.option("--staged", is_flag=True, help="Attest staged changes only.")
609
+ @click.option(
610
+ "--format",
611
+ "output_format",
612
+ default="text",
613
+ type=click.Choice(["text", "markdown", "json"]),
614
+ help="Output format (default: text).",
615
+ )
616
+ @click.option("--sign", is_flag=True, help="Include SHA-256 content hash for tamper detection.")
617
+ @click.option("--output", "output_file", default=None, help="Write attestation to file.")
618
+ @click.pass_context
619
+ def attest(ctx, commit_range, staged, output_format, sign, output_file):
620
+ """Generate a proof-carrying PR attestation.
621
+
622
+ Bundles blast radius, risk score, breaking changes, fitness violations,
623
+ budget consumed, affected tests, and effects into a single verifiable
624
+ evidence artifact. Use --format markdown for PR comments.
625
+
626
+ \\b
627
+ Examples:
628
+ roam attest # attest uncommitted changes
629
+ roam attest --staged # attest staged changes
630
+ roam attest main..HEAD # attest full branch
631
+ roam attest --format markdown # PR comment format
632
+ roam attest --sign --output a.json # signed JSON artifact
633
+ """
634
+ json_mode = ctx.obj.get("json") if ctx.obj else False
635
+ # --format json is equivalent to --json
636
+ if output_format == "json":
637
+ json_mode = True
638
+ ensure_index()
639
+ root = find_project_root()
640
+
641
+ # Resolve git range
642
+ base_ref, head_ref = _resolve_git_range(root, commit_range)
643
+ hashes = _get_git_hashes(root, base_ref, head_ref)
644
+
645
+ changed = get_changed_files(root, staged=staged, commit_range=commit_range)
646
+ if not changed:
647
+ label = commit_range or ("staged" if staged else "uncommitted")
648
+ if json_mode or output_format == "json":
649
+ click.echo(
650
+ to_json(
651
+ json_envelope(
652
+ "attest",
653
+ summary={"verdict": f"no changes found for {label}", "safe_to_merge": True},
654
+ )
655
+ )
656
+ )
657
+ else:
658
+ click.echo(f"No changes found for {label}.")
659
+ return
660
+
661
+ with open_db(readonly=True) as conn:
662
+ file_map = resolve_changed_to_db(conn, changed)
663
+
664
+ if not file_map:
665
+ click.echo("Changed files not found in index. Run `roam index` first.")
666
+ return
667
+
668
+ # ── Collect all evidence ──────────────────────────────────────
669
+
670
+ # 1. Blast radius
671
+ blast = _collect_blast_radius(conn, file_map)
672
+ sym_by_file = blast.pop("sym_by_file", {})
673
+
674
+ # 2. Risk score
675
+ risk = _collect_risk(conn, root, file_map, staged, commit_range)
676
+
677
+ # 3. Breaking changes
678
+ breaking_ref = base_ref if commit_range else "HEAD"
679
+ breaking = _collect_breaking(conn, root, breaking_ref)
680
+
681
+ # 4. Fitness violations
682
+ fitness = _collect_fitness_evidence(conn, file_map, root)
683
+
684
+ # 5. Budget consumed
685
+ budget = _collect_budget_evidence(conn, root)
686
+
687
+ # 6. Affected tests
688
+ tests = _collect_affected_tests_evidence(conn, sym_by_file)
689
+
690
+ # 7. Effects
691
+ effects = _collect_effects_evidence(conn, file_map)
692
+
693
+ # ── Build attestation ─────────────────────────────────────────
694
+
695
+ # Tool version
696
+ try:
697
+ import roam
698
+
699
+ tool_version = roam.__version__
700
+ except Exception:
701
+ tool_version = "unknown"
702
+
703
+ now = datetime.now(timezone.utc)
704
+
705
+ evidence = {
706
+ "blast_radius": blast,
707
+ "risk": risk,
708
+ "breaking_changes": breaking,
709
+ "fitness": fitness,
710
+ "budget": budget,
711
+ "tests": tests,
712
+ "effects": effects,
713
+ }
714
+
715
+ attestation = {
716
+ "version": "1.0",
717
+ "tool": "roam-code",
718
+ "tool_version": tool_version,
719
+ "timestamp": now.strftime("%Y-%m-%dT%H:%M:%SZ"),
720
+ "git_range": f"{hashes.get('base', base_ref)}..{hashes.get('head', head_ref)}",
721
+ }
722
+
723
+ if sign:
724
+ attestation["content_hash"] = _content_hash(evidence)
725
+
726
+ verdict = _compute_verdict(risk, breaking, fitness, budget)
727
+
728
+ # ── Output ────────────────────────────────────────────────────
729
+
730
+ if output_format == "markdown":
731
+ output = _format_markdown(attestation, evidence, verdict)
732
+ if output_file:
733
+ Path(output_file).write_text(output, encoding="utf-8")
734
+ click.echo(f"Attestation written to {output_file}")
735
+ else:
736
+ click.echo(output)
737
+ return
738
+
739
+ if json_mode or output_format == "json":
740
+ envelope = json_envelope(
741
+ "attest",
742
+ summary={
743
+ "verdict": _make_verdict_str(verdict, risk),
744
+ "safe_to_merge": verdict["safe_to_merge"],
745
+ "risk_score": risk["score"] if risk else None,
746
+ "risk_level": risk["level"] if risk else None,
747
+ "breaking_changes": (
748
+ len(breaking.get("removed", []))
749
+ + len(breaking.get("signature_changed", []))
750
+ + len(breaking.get("renamed", []))
751
+ ),
752
+ "budget_failed": budget.get("failed", 0),
753
+ "affected_tests": tests.get("selected", 0),
754
+ "effects_count": len(effects),
755
+ },
756
+ attestation=attestation,
757
+ evidence=evidence,
758
+ verdict=verdict,
759
+ )
760
+ output = to_json(envelope)
761
+ if output_file:
762
+ Path(output_file).write_text(output, encoding="utf-8")
763
+ click.echo(f"Attestation written to {output_file}")
764
+ else:
765
+ click.echo(output)
766
+ return
767
+
768
+ # ── Text output ───────────────────────────────────────────────
769
+ _emit_text(
770
+ attestation,
771
+ evidence,
772
+ verdict,
773
+ risk,
774
+ blast,
775
+ breaking,
776
+ fitness,
777
+ budget,
778
+ tests,
779
+ effects,
780
+ output_file,
781
+ )
782
+
783
+
784
+ # ---------------------------------------------------------------------------
785
+ # Text output helpers
786
+ # ---------------------------------------------------------------------------
787
+
788
+
789
+ def _make_verdict_str(verdict, risk):
790
+ """Build a short verdict string."""
791
+ safe = "safe to merge" if verdict["safe_to_merge"] else "NOT safe to merge"
792
+ risk_str = f" (risk: {risk['level']} {risk['score']}/100)" if risk else ""
793
+ return f"{safe}{risk_str}"
794
+
795
+
796
+ def _emit_text(
797
+ attestation,
798
+ evidence,
799
+ verdict,
800
+ risk,
801
+ blast,
802
+ breaking,
803
+ fitness,
804
+ budget,
805
+ tests,
806
+ effects,
807
+ output_file,
808
+ ):
809
+ """Emit plain text attestation."""
810
+ lines = []
811
+
812
+ # Verdict line
813
+ safe = "SAFE TO MERGE" if verdict["safe_to_merge"] else "NOT SAFE TO MERGE"
814
+ lines.append(f"VERDICT: {safe}")
815
+ if verdict["conditions"]:
816
+ lines.append(f" Conditions: {'; '.join(verdict['conditions'])}")
817
+ if verdict["warnings"]:
818
+ lines.append(f" Warnings: {'; '.join(verdict['warnings'])}")
819
+ lines.append("")
820
+
821
+ # Risk
822
+ if risk:
823
+ lines.append(f"RISK: {risk['level']} ({risk['score']}/100)")
824
+ lines.append("")
825
+
826
+ # Blast radius
827
+ lines.append("BLAST RADIUS:")
828
+ lines.append(f" Changed files: {blast.get('changed_files', 0)}")
829
+ lines.append(f" Affected symbols: {blast.get('affected_symbols', 0)}")
830
+ lines.append(f" Affected files: {blast.get('affected_files', 0)}")
831
+ lines.append("")
832
+
833
+ # Breaking changes
834
+ removed = len(breaking.get("removed", []))
835
+ sig_changed = len(breaking.get("signature_changed", []))
836
+ renamed = len(breaking.get("renamed", []))
837
+ total_bc = removed + sig_changed + renamed
838
+ if total_bc > 0:
839
+ lines.append(f"BREAKING CHANGES ({total_bc}):")
840
+ if removed:
841
+ lines.append(f" {removed} removed")
842
+ for r in breaking["removed"][:5]:
843
+ lines.append(f" {abbrev_kind(r.get('kind', ''))} {r['name']} {r.get('file', '')}")
844
+ if sig_changed:
845
+ lines.append(f" {sig_changed} signature changed")
846
+ if renamed:
847
+ lines.append(f" {renamed} renamed")
848
+ lines.append("")
849
+ else:
850
+ lines.append("BREAKING CHANGES: none")
851
+ lines.append("")
852
+
853
+ # Budget
854
+ if budget.get("rules_checked", 0) > 0:
855
+ lines.append(f"BUDGET ({budget['passed']} pass, {budget['failed']} fail, {budget['skipped']} skip):")
856
+ for r in budget.get("rules", []):
857
+ status = r.get("status", "?")
858
+ name = r.get("name", "unnamed")
859
+ detail = ""
860
+ if r.get("delta") is not None:
861
+ detail = f" (delta: {r['delta']}, {r.get('budget', '')})"
862
+ lines.append(f" [{status}] {name}{detail}")
863
+ lines.append("")
864
+
865
+ # Fitness
866
+ fitness_v = fitness.get("violations", [])
867
+ if fitness_v:
868
+ lines.append(f"FITNESS VIOLATIONS ({len(fitness_v)}):")
869
+ for v in fitness_v[:10]:
870
+ lines.append(f" {v.get('rule', '?')}: {v.get('message', '')}")
871
+ lines.append("")
872
+
873
+ # Affected tests
874
+ if tests.get("selected", 0) > 0:
875
+ lines.append(
876
+ f"AFFECTED TESTS ({tests['selected']}: "
877
+ f"{tests.get('direct', 0)} direct, "
878
+ f"{tests.get('transitive', 0)} transitive, "
879
+ f"{tests.get('colocated', 0)} colocated):"
880
+ )
881
+ cmd = tests.get("command", "")
882
+ if cmd:
883
+ lines.append(f" Run: {cmd}")
884
+ lines.append("")
885
+ else:
886
+ lines.append("AFFECTED TESTS: none found")
887
+ lines.append("")
888
+
889
+ # Effects
890
+ if effects:
891
+ lines.append(f"EFFECTS ({len(effects)} symbols):")
892
+ for e in effects[:15]:
893
+ all_eff = e.get("direct_effects", []) + e.get("transitive_effects", [])
894
+ lines.append(f" {e.get('symbol', '?')}: {', '.join(all_eff)}")
895
+ lines.append("")
896
+
897
+ # Attestation metadata
898
+ lines.append("---")
899
+ lines.append(
900
+ f"Attested by roam-code v{attestation.get('tool_version', '?')} at {attestation.get('timestamp', '?')}"
901
+ )
902
+ if attestation.get("content_hash"):
903
+ lines.append(f"Hash: {attestation['content_hash']}")
904
+ git_range = attestation.get("git_range", "?")
905
+ lines.append(f"Range: {git_range}")
906
+
907
+ text = "\n".join(lines)
908
+
909
+ if output_file:
910
+ Path(output_file).write_text(text, encoding="utf-8")
911
+ click.echo(f"Attestation written to {output_file}")
912
+ else:
913
+ click.echo(text)