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,319 @@
1
+ """Plugin DSL for custom governance rules.
2
+
3
+ Users define architectural rules as YAML files in ``.roam/rules/``.
4
+ Roam evaluates them against the indexed graph and reports violations.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+
11
+ import click
12
+
13
+ from roam.commands.resolve import ensure_index
14
+ from roam.db.connection import find_project_root, open_db
15
+ from roam.output.formatter import json_envelope, to_json
16
+
17
+ # ---------------------------------------------------------------------------
18
+ # Example rule YAML templates
19
+ # ---------------------------------------------------------------------------
20
+
21
+ _EXAMPLE_PATH_RULE = """\
22
+ # Rule: Controllers must not call DB layer directly
23
+ name: "No controller calls DB directly"
24
+ description: "Controllers must go through service layer"
25
+ severity: error
26
+
27
+ match:
28
+ from:
29
+ file_glob: "**/controllers/**"
30
+ kind: [function, method]
31
+ to:
32
+ file_glob: "**/db/**"
33
+ kind: [function, method]
34
+ max_distance: 1
35
+
36
+ exempt:
37
+ symbols: [health_check]
38
+ files: ["**/admin/**"]
39
+ """
40
+
41
+ _EXAMPLE_SYMBOL_RULE = """\
42
+ # Rule: Exported functions must have test coverage
43
+ name: "Exported functions need tests"
44
+ description: "All exported functions with fan-in >= 2 must have test coverage"
45
+ severity: warning
46
+
47
+ match:
48
+ kind: [function]
49
+ exported: true
50
+ min_fan_in: 2
51
+ require:
52
+ has_test: true
53
+
54
+ exempt:
55
+ symbols: [main, cli]
56
+ files: ["**/migrations/**"]
57
+ """
58
+
59
+ _EXAMPLE_AST_RULE = """\
60
+ # Rule: Forbid dynamic eval-style execution
61
+ name: "No eval-style execution"
62
+ description: "Disallow eval(...) calls in Python source"
63
+ severity: error
64
+ type: ast_match
65
+
66
+ match:
67
+ ast: "eval($EXPR)"
68
+ language: python
69
+ file_glob: "**/*.py"
70
+ max_matches: 50
71
+
72
+ exempt:
73
+ files: ["**/tests/**"]
74
+ """
75
+
76
+ _EXAMPLE_DATAFLOW_RULE = """\
77
+ # Rule: Detect intra-procedural dataflow issues
78
+ name: "Basic dataflow hygiene"
79
+ description: "Find dead assignments, unused params, and source-to-sink flows in functions"
80
+ severity: warning
81
+ type: dataflow_match
82
+
83
+ match:
84
+ patterns: [dead_assignment, unused_param, source_to_sink]
85
+ file_glob: "**/*.py"
86
+ max_matches: 100
87
+ sources: ["input(", "request.args"]
88
+ sinks: ["eval(", "exec("]
89
+
90
+ exempt:
91
+ files: ["**/tests/**"]
92
+ """
93
+
94
+
95
+ # ---------------------------------------------------------------------------
96
+ # CLI command
97
+ # ---------------------------------------------------------------------------
98
+
99
+
100
+ @click.command("rules")
101
+ @click.option("--init", "do_init", is_flag=True, help="Generate example rule files in .roam/rules/.")
102
+ @click.option("--ci", "ci_mode", is_flag=True, help="Exit code 1 on error-severity violations.")
103
+ @click.option("--rules-dir", "rules_dir_opt", default=None, help="Custom rules directory path.")
104
+ @click.pass_context
105
+ def rules(ctx, do_init, ci_mode, rules_dir_opt):
106
+ """Evaluate custom governance rules defined in .roam/rules/.
107
+
108
+ Rules are YAML files that define architectural constraints. Two rule
109
+ types are supported: path_match (edges between from/to patterns),
110
+ symbol_match (symbols matching criteria with optional require),
111
+ ast_match (AST structural patterns with `$METAVAR` captures),
112
+ and dataflow_match (basic intra-procedural dataflow heuristics).
113
+
114
+ Use --init to create example rule files. Use --ci for CI gates
115
+ (exit code 1 on error-severity violations).
116
+ """
117
+ json_mode = ctx.obj.get("json") if ctx.obj else False
118
+ sarif_mode = ctx.obj.get("sarif") if ctx.obj else False
119
+ root = find_project_root()
120
+
121
+ # --init: create example rules
122
+ if do_init:
123
+ _handle_init(root, json_mode, rules_dir_opt)
124
+ return
125
+
126
+ ensure_index()
127
+
128
+ # Determine rules directory
129
+ if rules_dir_opt:
130
+ rules_dir = Path(rules_dir_opt)
131
+ else:
132
+ rules_dir = root / ".roam" / "rules"
133
+
134
+ # Graceful handling when no rules directory exists
135
+ if not rules_dir.is_dir():
136
+ verdict = "no rules directory found"
137
+ if sarif_mode:
138
+ from roam.output.sarif import rules_to_sarif, write_sarif
139
+
140
+ sarif = rules_to_sarif([])
141
+ click.echo(write_sarif(sarif))
142
+ return
143
+ if json_mode:
144
+ click.echo(
145
+ to_json(
146
+ json_envelope(
147
+ "rules",
148
+ summary={
149
+ "verdict": verdict,
150
+ "passed": 0,
151
+ "failed": 0,
152
+ "warnings": 0,
153
+ "total": 0,
154
+ },
155
+ results=[],
156
+ )
157
+ )
158
+ )
159
+ else:
160
+ click.echo(f"VERDICT: {verdict}")
161
+ click.echo()
162
+ click.echo(f"Create rules in {rules_dir} or run 'roam rules --init'.")
163
+ return
164
+
165
+ from roam.rules.engine import evaluate_all
166
+
167
+ with open_db(readonly=True) as conn:
168
+ results = evaluate_all(rules_dir, conn)
169
+
170
+ # Tally results
171
+ total = len(results)
172
+ passed = sum(1 for r in results if r["passed"])
173
+ failed_errors = sum(1 for r in results if not r["passed"] and r["severity"] == "error")
174
+ failed_warnings = sum(1 for r in results if not r["passed"] and r["severity"] == "warning")
175
+ failed_infos = sum(1 for r in results if not r["passed"] and r["severity"] == "info")
176
+ failed = total - passed
177
+
178
+ if failed == 0:
179
+ verdict = f"all {total} rules passed" if total > 0 else "no rules found"
180
+ else:
181
+ parts = []
182
+ if failed_errors > 0:
183
+ parts.append(f"{failed_errors} error(s)")
184
+ if failed_warnings > 0:
185
+ parts.append(f"{failed_warnings} warning(s)")
186
+ if failed_infos > 0:
187
+ parts.append(f"{failed_infos} info")
188
+ verdict = f"{passed} of {total} rules passed, {', '.join(parts)}"
189
+
190
+ # --- SARIF output ---
191
+ if sarif_mode:
192
+ from roam.output.sarif import rules_to_sarif, write_sarif
193
+
194
+ sarif = rules_to_sarif(results)
195
+ click.echo(write_sarif(sarif))
196
+ if ci_mode and failed_errors > 0:
197
+ from roam.exit_codes import EXIT_GATE_FAILURE
198
+
199
+ ctx.exit(EXIT_GATE_FAILURE)
200
+ return
201
+
202
+ # --- JSON output ---
203
+ if json_mode:
204
+ click.echo(
205
+ to_json(
206
+ json_envelope(
207
+ "rules",
208
+ summary={
209
+ "verdict": verdict,
210
+ "passed": passed,
211
+ "failed": failed,
212
+ "warnings": failed_warnings,
213
+ "total": total,
214
+ },
215
+ results=results,
216
+ )
217
+ )
218
+ )
219
+ if ci_mode and failed_errors > 0:
220
+ from roam.exit_codes import EXIT_GATE_FAILURE
221
+
222
+ ctx.exit(EXIT_GATE_FAILURE)
223
+ return
224
+
225
+ # --- Text output ---
226
+ click.echo(f"VERDICT: {verdict}")
227
+ click.echo()
228
+
229
+ for r in results:
230
+ status = "PASS" if r["passed"] else "FAIL"
231
+ sev = r["severity"].upper()
232
+ name = r["name"]
233
+ violations = r.get("violations", [])
234
+ count = len(violations)
235
+
236
+ if r["passed"]:
237
+ click.echo(f" [{status}] {name}")
238
+ else:
239
+ click.echo(f" [{status}] [{sev}] {name} ({count} violation(s))")
240
+ for v in violations[:10]:
241
+ sym = v.get("symbol", "")
242
+ fpath = v.get("file", "")
243
+ line = v.get("line")
244
+ reason = v.get("reason", "")
245
+ loc = f"{fpath}:{line}" if line else fpath
246
+ click.echo(f" - {sym} at {loc}")
247
+ if reason:
248
+ click.echo(f" {reason}")
249
+ if count > 10:
250
+ click.echo(f" (+{count - 10} more)")
251
+
252
+ if ci_mode and failed_errors > 0:
253
+ ctx.exit(1)
254
+
255
+
256
+ # ---------------------------------------------------------------------------
257
+ # --init handler
258
+ # ---------------------------------------------------------------------------
259
+
260
+
261
+ def _handle_init(root: Path, json_mode: bool, rules_dir_opt: str | None):
262
+ """Create example rule files in .roam/rules/."""
263
+ if rules_dir_opt:
264
+ rules_dir = Path(rules_dir_opt)
265
+ else:
266
+ rules_dir = root / ".roam" / "rules"
267
+
268
+ rules_dir.mkdir(parents=True, exist_ok=True)
269
+
270
+ path_rule_file = rules_dir / "no_controller_calls_db.yaml"
271
+ symbol_rule_file = rules_dir / "exported_need_tests.yaml"
272
+ ast_rule_file = rules_dir / "no_eval_style_execution.yaml"
273
+ dataflow_rule_file = rules_dir / "basic_dataflow_hygiene.yaml"
274
+
275
+ created: list[str] = []
276
+
277
+ if not path_rule_file.exists():
278
+ path_rule_file.write_text(_EXAMPLE_PATH_RULE, encoding="utf-8")
279
+ created.append(str(path_rule_file))
280
+
281
+ if not symbol_rule_file.exists():
282
+ symbol_rule_file.write_text(_EXAMPLE_SYMBOL_RULE, encoding="utf-8")
283
+ created.append(str(symbol_rule_file))
284
+
285
+ if not ast_rule_file.exists():
286
+ ast_rule_file.write_text(_EXAMPLE_AST_RULE, encoding="utf-8")
287
+ created.append(str(ast_rule_file))
288
+
289
+ if not dataflow_rule_file.exists():
290
+ dataflow_rule_file.write_text(_EXAMPLE_DATAFLOW_RULE, encoding="utf-8")
291
+ created.append(str(dataflow_rule_file))
292
+
293
+ if json_mode:
294
+ verdict = f"created {len(created)} example rule(s)" if created else "rule files already exist"
295
+ click.echo(
296
+ to_json(
297
+ json_envelope(
298
+ "rules",
299
+ summary={
300
+ "verdict": verdict,
301
+ "passed": 0,
302
+ "failed": 0,
303
+ "warnings": 0,
304
+ "total": 0,
305
+ },
306
+ created=created,
307
+ )
308
+ )
309
+ )
310
+ else:
311
+ if created:
312
+ click.echo(f"Created {len(created)} example rule file(s):")
313
+ for c in created:
314
+ click.echo(f" {c}")
315
+ click.echo()
316
+ click.echo("Edit these files, then run 'roam rules' to evaluate.")
317
+ else:
318
+ click.echo("Example rule files already exist.")
319
+ click.echo(f"Edit them in {rules_dir}/")
@@ -0,0 +1,224 @@
1
+ """Check if a symbol can be safely deleted."""
2
+
3
+ import os
4
+
5
+ import click
6
+
7
+ from roam.commands.resolve import ensure_index, find_symbol, symbol_not_found
8
+ from roam.db.connection import open_db
9
+ from roam.output.formatter import abbrev_kind, format_table, json_envelope, loc, to_json
10
+
11
+ _TEST_NAME_PATS = ["test_", "_test.", ".test.", ".spec."]
12
+ _TEST_DIR_PATS = ["tests/", "test/", "__tests__/", "spec/"]
13
+
14
+
15
+ def _is_test_file(path):
16
+ p = path.replace("\\", "/")
17
+ bn = os.path.basename(p)
18
+ return any(pat in bn for pat in _TEST_NAME_PATS) or any(d in p for d in _TEST_DIR_PATS)
19
+
20
+
21
+ @click.command("safe-delete")
22
+ @click.argument("name")
23
+ @click.pass_context
24
+ def safe_delete(ctx, name):
25
+ """Check if a symbol can be safely deleted.
26
+
27
+ Combines dead-code check, impact analysis, and test coverage
28
+ into a single verdict: SAFE / REVIEW / UNSAFE.
29
+ """
30
+ json_mode = ctx.obj.get("json") if ctx.obj else False
31
+ ensure_index()
32
+
33
+ with open_db(readonly=True) as conn:
34
+ sym = find_symbol(conn, name)
35
+ if sym is None:
36
+ click.echo(symbol_not_found(conn, name, json_mode=json_mode))
37
+ raise SystemExit(1)
38
+
39
+ sym_id = sym["id"]
40
+
41
+ # --- Direct references ---
42
+ callers = conn.execute(
43
+ "SELECT s.name, s.kind, f.path as file_path, e.kind as edge_kind "
44
+ "FROM edges e JOIN symbols s ON e.source_id = s.id "
45
+ "JOIN files f ON s.file_id = f.id "
46
+ "WHERE e.target_id = ?",
47
+ (sym_id,),
48
+ ).fetchall()
49
+
50
+ test_callers = [c for c in callers if _is_test_file(c["file_path"])]
51
+ non_test_callers = [c for c in callers if not _is_test_file(c["file_path"])]
52
+
53
+ # --- Transitive impact ---
54
+ import networkx as nx
55
+
56
+ from roam.graph.builder import build_symbol_graph
57
+
58
+ G = build_symbol_graph(conn)
59
+ dependent_count = 0
60
+ affected_files = set()
61
+ if sym_id in G:
62
+ RG = G.reverse()
63
+ dependents = nx.descendants(RG, sym_id)
64
+ dependent_count = len(dependents)
65
+ for d in dependents:
66
+ node = G.nodes.get(d, {})
67
+ fp = node.get("file_path")
68
+ if fp:
69
+ affected_files.add(fp)
70
+
71
+ # --- File-level import check ---
72
+ file_imported = False
73
+ file_row = conn.execute("SELECT id FROM files WHERE path = ?", (sym["file_path"],)).fetchone()
74
+ if file_row:
75
+ imp = conn.execute(
76
+ "SELECT COUNT(*) FROM file_edges WHERE target_file_id = ?",
77
+ (file_row["id"],),
78
+ ).fetchone()[0]
79
+ file_imported = imp > 0
80
+
81
+ # --- Sibling check (other symbols in same file that ARE referenced) ---
82
+ sibling_refs = 0
83
+ if file_row:
84
+ sibling_refs = conn.execute(
85
+ "SELECT COUNT(*) FROM symbols s "
86
+ "WHERE s.file_id = ? AND s.is_exported = 1 AND s.id != ? "
87
+ "AND s.id IN (SELECT target_id FROM edges)",
88
+ (file_row["id"], sym_id),
89
+ ).fetchone()[0]
90
+
91
+ # --- Verdict ---
92
+ if len(non_test_callers) == 0 and dependent_count == 0:
93
+ if file_imported and sibling_refs > 0:
94
+ verdict = "SAFE"
95
+ reason = (
96
+ f"No references. File is imported but {sibling_refs} "
97
+ f"sibling symbols are used — this one is skipped."
98
+ )
99
+ elif file_imported:
100
+ verdict = "SAFE"
101
+ reason = "No references. File is imported but no one uses this symbol."
102
+ else:
103
+ verdict = "SAFE"
104
+ reason = "No references and file is not imported by anyone."
105
+ elif len(non_test_callers) == 0 and dependent_count > 0:
106
+ verdict = "REVIEW"
107
+ reason = (
108
+ f"No direct callers but {dependent_count} transitive dependents in graph — check for dynamic usage."
109
+ )
110
+ elif len(non_test_callers) <= 3:
111
+ verdict = "REVIEW"
112
+ names = ", ".join(c["name"] for c in non_test_callers[:3])
113
+ reason = f"{len(non_test_callers)} caller(s): {names}"
114
+ else:
115
+ verdict = "UNSAFE"
116
+ reason = (
117
+ f"{len(non_test_callers)} direct callers, "
118
+ f"{dependent_count} transitive dependents "
119
+ f"across {len(affected_files)} files."
120
+ )
121
+
122
+ # Bump SAFE → REVIEW for likely public-API symbols
123
+ if verdict == "SAFE" and sym["is_exported"]:
124
+ _api_prefixes = (
125
+ "get",
126
+ "use",
127
+ "create",
128
+ "validate",
129
+ "fetch",
130
+ "update",
131
+ "delete",
132
+ "find",
133
+ "check",
134
+ "make",
135
+ "build",
136
+ "parse",
137
+ "format",
138
+ )
139
+ name_lower = sym["name"].lower()
140
+ base_name = os.path.basename(sym["file_path"]).lower()
141
+ is_barrel = base_name.startswith("index.") or base_name == "__init__.py"
142
+ if any(name_lower.startswith(p) for p in _api_prefixes):
143
+ verdict = "REVIEW"
144
+ reason = (
145
+ "No references found, but exported with public-API naming pattern — may be consumed externally."
146
+ )
147
+ elif is_barrel:
148
+ verdict = "REVIEW"
149
+ reason = f"No references found, but exported from {base_name} — likely part of public API."
150
+
151
+ test_note = ""
152
+ if test_callers:
153
+ test_note = f"{len(test_callers)} test(s) would break"
154
+ elif len(non_test_callers) > 0:
155
+ test_note = "No tests cover this symbol — deletion may go unnoticed"
156
+ else:
157
+ test_note = "No tests reference this symbol"
158
+
159
+ if json_mode:
160
+ click.echo(
161
+ to_json(
162
+ json_envelope(
163
+ "safe-delete",
164
+ summary={
165
+ "verdict": verdict,
166
+ "direct_callers": len(non_test_callers),
167
+ "affected_files": len(affected_files),
168
+ },
169
+ symbol=sym["qualified_name"] or sym["name"],
170
+ kind=sym["kind"],
171
+ location=loc(sym["file_path"], sym["line_start"]),
172
+ verdict=verdict,
173
+ reason=reason,
174
+ direct_callers=len(non_test_callers),
175
+ transitive_dependents=dependent_count,
176
+ affected_files=len(affected_files),
177
+ test_callers=len(test_callers),
178
+ test_note=test_note,
179
+ file_imported=file_imported,
180
+ sibling_refs=sibling_refs,
181
+ callers=[
182
+ {
183
+ "name": c["name"],
184
+ "kind": c["kind"],
185
+ "file": c["file_path"],
186
+ "edge_kind": c["edge_kind"],
187
+ }
188
+ for c in non_test_callers[:10]
189
+ ],
190
+ )
191
+ )
192
+ )
193
+ return
194
+
195
+ # --- Text output ---
196
+ click.echo(f"=== Safe Delete: {sym['name']} ===")
197
+ click.echo(
198
+ f"{abbrev_kind(sym['kind'])} {sym['qualified_name'] or sym['name']} "
199
+ f"{loc(sym['file_path'], sym['line_start'])}"
200
+ )
201
+ click.echo()
202
+ click.echo(f"Verdict: {verdict}")
203
+ click.echo(f" {reason}")
204
+ click.echo()
205
+ click.echo(f"References: {len(non_test_callers)} direct, {dependent_count} transitive")
206
+ click.echo(f"Affected files: {len(affected_files)}")
207
+ click.echo(f"Tests: {test_note}")
208
+ click.echo(f"File imported: {'yes' if file_imported else 'no'} | Sibling refs: {sibling_refs}")
209
+
210
+ if non_test_callers:
211
+ click.echo(f"\nCallers ({len(non_test_callers)}):")
212
+ rows = []
213
+ for c in non_test_callers[:10]:
214
+ rows.append(
215
+ [
216
+ abbrev_kind(c["kind"]),
217
+ c["name"],
218
+ c["file_path"],
219
+ c["edge_kind"] or "",
220
+ ]
221
+ )
222
+ click.echo(format_table(["kind", "name", "file", "edge"], rows))
223
+ if len(non_test_callers) > 10:
224
+ click.echo(f" (+{len(non_test_callers) - 10} more)")