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,638 @@
1
+ """Find unprotected entry points — symbols with no path to a required gate."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import fnmatch
6
+ import os
7
+ import re
8
+
9
+ import click
10
+
11
+ from roam.commands.gate_presets import (
12
+ ALL_PRESETS,
13
+ detect_preset,
14
+ get_preset,
15
+ load_gates_config,
16
+ )
17
+ from roam.commands.graph_helpers import build_forward_adj
18
+ from roam.commands.resolve import ensure_index
19
+ from roam.coverage_reports import ingest_coverage_reports
20
+ from roam.db.connection import batched_in, find_project_root, open_db
21
+ from roam.output.formatter import abbrev_kind, format_table, json_envelope, loc, to_json
22
+
23
+
24
+ def _find_gates(conn, gate_names, gate_pattern):
25
+ """Find gate symbol IDs by exact name or regex pattern."""
26
+ gates = set()
27
+ gate_info = {}
28
+
29
+ if gate_names:
30
+ names = [n.strip() for n in gate_names.split(",") if n.strip()]
31
+ for name in names:
32
+ rows = conn.execute(
33
+ "SELECT s.id, s.name, f.path as file_path, s.line_start "
34
+ "FROM symbols s JOIN files f ON s.file_id = f.id "
35
+ "WHERE s.name = ?",
36
+ (name,),
37
+ ).fetchall()
38
+ for r in rows:
39
+ gates.add(r["id"])
40
+ gate_info[r["id"]] = r["name"]
41
+
42
+ if gate_pattern:
43
+ regex = re.compile(gate_pattern, re.IGNORECASE)
44
+ rows = conn.execute(
45
+ "SELECT s.id, s.name, f.path as file_path, s.line_start FROM symbols s JOIN files f ON s.file_id = f.id "
46
+ ).fetchall()
47
+ for r in rows:
48
+ if regex.search(r["name"]):
49
+ gates.add(r["id"])
50
+ gate_info[r["id"]] = r["name"]
51
+
52
+ return gates, gate_info
53
+
54
+
55
+ def _find_entries(conn, scope, entry_pattern):
56
+ """Find entry point symbols — exported top-level functions, optionally scoped."""
57
+ sql = (
58
+ "SELECT s.id, s.name, s.kind, f.path as file_path, s.line_start "
59
+ "FROM symbols s JOIN files f ON s.file_id = f.id "
60
+ "WHERE s.is_exported = 1 AND s.kind IN ('function', 'method') "
61
+ "AND s.parent_id IS NULL "
62
+ )
63
+ params = []
64
+
65
+ if scope:
66
+ # Convert glob to LIKE pattern
67
+ like = scope.replace("*", "%").replace("?", "_")
68
+ sql += "AND f.path LIKE ? "
69
+ params.append(like)
70
+
71
+ sql += "ORDER BY f.path, s.line_start"
72
+ rows = conn.execute(sql, params).fetchall()
73
+
74
+ if entry_pattern:
75
+ regex = re.compile(entry_pattern, re.IGNORECASE)
76
+ rows = [r for r in rows if regex.search(r["name"])]
77
+
78
+ return rows
79
+
80
+
81
+ def _bfs_to_gate(adj, start_id, gates, max_depth):
82
+ """BFS from start_id to find shortest path to any gate symbol.
83
+
84
+ Returns (gate_name, depth, chain) or (None, None, None) if not found.
85
+ """
86
+ if start_id in gates:
87
+ return start_id, 0, [start_id]
88
+
89
+ visited = {start_id}
90
+ # Queue entries: (node_id, depth, path)
91
+ queue = [(start_id, 0, [start_id])]
92
+
93
+ while queue:
94
+ current, depth, path = queue.pop(0)
95
+ if depth >= max_depth:
96
+ continue
97
+ for neighbor in adj.get(current, set()):
98
+ if neighbor in visited:
99
+ continue
100
+ visited.add(neighbor)
101
+ new_path = path + [neighbor]
102
+ if neighbor in gates:
103
+ return neighbor, depth + 1, new_path
104
+ queue.append((neighbor, depth + 1, new_path))
105
+
106
+ return None, None, None
107
+
108
+
109
+ def _evaluate_gate_rules(conn, rules):
110
+ """Evaluate gate rules against indexed files.
111
+
112
+ Returns a list of violation dicts for files that fail a gate rule.
113
+ """
114
+ # Fetch all indexed file paths
115
+ all_files = [r["path"] for r in conn.execute("SELECT path FROM files").fetchall()]
116
+
117
+ # Build a set of test-like file paths for quick lookup
118
+ test_patterns = ["test_*", "*_test.*", "*.test.*", "*.spec.*", "*_test.go"]
119
+ test_files = set()
120
+ for fp in all_files:
121
+ basename = os.path.basename(fp)
122
+ if any(fnmatch.fnmatch(basename, tp) for tp in test_patterns):
123
+ test_files.add(fp)
124
+
125
+ # Count test functions per file
126
+ test_fn_count = {}
127
+ for fp in test_files:
128
+ row = conn.execute(
129
+ "SELECT COUNT(*) as cnt FROM symbols s JOIN files f ON s.file_id = f.id "
130
+ "WHERE f.path = ? AND s.kind = 'function' AND s.name LIKE 'test%'",
131
+ (fp,),
132
+ ).fetchone()
133
+ test_fn_count[fp] = row["cnt"] if row else 0
134
+
135
+ violations = []
136
+ for rule in rules:
137
+ # Find files matching include patterns
138
+ matched = set()
139
+ for fp in all_files:
140
+ for pat in rule.include_patterns:
141
+ if fnmatch.fnmatch(fp, pat):
142
+ matched.add(fp)
143
+ break
144
+
145
+ # Remove files matching exclude patterns
146
+ for fp in list(matched):
147
+ for pat in rule.exclude_patterns:
148
+ if fnmatch.fnmatch(fp, pat):
149
+ matched.discard(fp)
150
+ break
151
+
152
+ # For each matched file, check if a corresponding test file exists
153
+ for fp in sorted(matched):
154
+ basename = os.path.basename(fp)
155
+ stem = os.path.splitext(basename)[0]
156
+ # Look for test_<stem>.py, <stem>_test.py, <stem>.test.js, etc.
157
+ has_test = False
158
+ related_test_count = 0
159
+ for tf in test_files:
160
+ tf_base = os.path.basename(tf)
161
+ if stem in tf_base:
162
+ has_test = True
163
+ related_test_count += test_fn_count.get(tf, 0)
164
+
165
+ if not has_test or related_test_count < rule.min_test_count:
166
+ violations.append(
167
+ {
168
+ "rule": rule.name,
169
+ "severity": rule.severity,
170
+ "file": fp,
171
+ "description": rule.description,
172
+ "test_found": has_test,
173
+ "test_count": related_test_count,
174
+ "min_required": rule.min_test_count,
175
+ }
176
+ )
177
+
178
+ return violations
179
+
180
+
181
+ @click.command("coverage-gaps")
182
+ @click.option(
183
+ "--gate",
184
+ "gate_names",
185
+ default=None,
186
+ help="Comma-separated gate symbol names (e.g. 'requireAuth,validateToken')",
187
+ )
188
+ @click.option(
189
+ "--gate-pattern",
190
+ "gate_pattern",
191
+ default=None,
192
+ help="Regex to match gate symbols by name (e.g. 'auth|permission|guard')",
193
+ )
194
+ @click.option("--scope", default=None, help="File scope glob (e.g. 'app/routes/**')")
195
+ @click.option(
196
+ "--entry-pattern",
197
+ "entry_pattern",
198
+ default=None,
199
+ help="Regex to filter entry points by name (e.g. 'handler|controller')",
200
+ )
201
+ @click.option("--max-depth", default=8, show_default=True, help="Max BFS depth")
202
+ @click.option(
203
+ "--preset",
204
+ "preset_name",
205
+ default=None,
206
+ help="Use a built-in gate preset (python, javascript, go, java-maven, rust)",
207
+ )
208
+ @click.option(
209
+ "--auto-detect",
210
+ "auto_detect",
211
+ is_flag=True,
212
+ default=False,
213
+ help="Auto-detect framework preset from project files",
214
+ )
215
+ @click.option("--config", "config_path", default=None, help="Path to .roam-gates.yml config file")
216
+ @click.option(
217
+ "--import-report",
218
+ "import_reports",
219
+ multiple=True,
220
+ help="Import coverage report (.info/.xml/.json). Repeat for multiple reports.",
221
+ )
222
+ @click.option(
223
+ "--merge-imported",
224
+ is_flag=True,
225
+ default=False,
226
+ help="Merge imported coverage into existing data (default replaces old imports).",
227
+ )
228
+ @click.pass_context
229
+ def coverage_gaps(
230
+ ctx,
231
+ gate_names,
232
+ gate_pattern,
233
+ scope,
234
+ entry_pattern,
235
+ max_depth,
236
+ preset_name,
237
+ auto_detect,
238
+ config_path,
239
+ import_reports,
240
+ merge_imported,
241
+ ):
242
+ """Find entry points with no path to a required gate symbol.
243
+
244
+ Use --gate for exact names or --gate-pattern for regex matching.
245
+ Searches the call graph to find which entry points can reach a gate
246
+ and which are unprotected.
247
+
248
+ Use --preset or --auto-detect to apply framework-specific gate rules
249
+ that check file-level test coverage requirements.
250
+ """
251
+ json_mode = ctx.obj.get("json") if ctx.obj else False
252
+ ensure_index()
253
+
254
+ import_summary = None
255
+ if import_reports:
256
+ try:
257
+ with open_db(readonly=False) as conn:
258
+ import_summary = ingest_coverage_reports(
259
+ conn,
260
+ list(import_reports),
261
+ replace_existing=not merge_imported,
262
+ project_root=find_project_root(),
263
+ )
264
+ except Exception as exc:
265
+ msg = f"Coverage import failed: {exc}"
266
+ if json_mode:
267
+ click.echo(
268
+ to_json(
269
+ json_envelope(
270
+ "coverage-gaps",
271
+ summary={"error": msg},
272
+ )
273
+ )
274
+ )
275
+ else:
276
+ click.echo(msg)
277
+ raise SystemExit(1)
278
+
279
+ # --- Resolve preset / config gate rules ---
280
+ preset_used = None
281
+ gate_rules = []
282
+
283
+ if config_path:
284
+ gate_rules = load_gates_config(config_path)
285
+ if not gate_rules:
286
+ msg = f"No rules loaded from {config_path}"
287
+ if json_mode:
288
+ click.echo(
289
+ to_json(
290
+ json_envelope(
291
+ "coverage-gaps",
292
+ summary={"error": msg},
293
+ )
294
+ )
295
+ )
296
+ else:
297
+ click.echo(msg)
298
+ return
299
+
300
+ if preset_name:
301
+ preset_used = get_preset(preset_name)
302
+ if not preset_used:
303
+ available = ", ".join(p.name for p in ALL_PRESETS)
304
+ msg = f"Unknown preset '{preset_name}'. Available: {available}"
305
+ if json_mode:
306
+ click.echo(
307
+ to_json(
308
+ json_envelope(
309
+ "coverage-gaps",
310
+ summary={"error": msg},
311
+ )
312
+ )
313
+ )
314
+ else:
315
+ click.echo(msg)
316
+ return
317
+ gate_rules = preset_used.rules
318
+
319
+ if auto_detect and not preset_used:
320
+ with open_db(readonly=True) as conn:
321
+ file_paths = [r["path"] for r in conn.execute("SELECT path FROM files").fetchall()]
322
+ preset_used = detect_preset(file_paths)
323
+ if preset_used:
324
+ gate_rules = preset_used.rules
325
+
326
+ # If preset/config rules are active, evaluate them
327
+ gate_violations = []
328
+ if gate_rules:
329
+ with open_db(readonly=True) as conn:
330
+ gate_violations = _evaluate_gate_rules(conn, gate_rules)
331
+
332
+ # Import-only mode: no gate traversal requested.
333
+ if import_summary and not gate_names and not gate_pattern and not gate_rules:
334
+ coverage_pct = import_summary.get("coverage_pct")
335
+ coverage_str = f"{coverage_pct}%" if coverage_pct is not None else "n/a"
336
+ verdict = (
337
+ f"Imported {import_summary['reports']} report(s): "
338
+ f"{import_summary['matched_files']}/{import_summary['parsed_files']} files matched; "
339
+ f"coverage={coverage_str}"
340
+ )
341
+ if json_mode:
342
+ click.echo(
343
+ to_json(
344
+ json_envelope(
345
+ "coverage-gaps",
346
+ summary={
347
+ "verdict": verdict,
348
+ "imported_reports": import_summary["reports"],
349
+ "matched_files": import_summary["matched_files"],
350
+ "parsed_files": import_summary["parsed_files"],
351
+ "unmatched_files": import_summary["unmatched_count"],
352
+ "coverage_pct": import_summary["coverage_pct"],
353
+ },
354
+ import_summary=import_summary,
355
+ )
356
+ )
357
+ )
358
+ else:
359
+ click.echo(f"VERDICT: {verdict}")
360
+ click.echo(
361
+ f" Updated: {import_summary['file_rows_updated']} files, "
362
+ f"{import_summary['symbol_rows_updated']} symbols"
363
+ )
364
+ if import_summary["unmatched_count"]:
365
+ click.echo(f" Unmatched files: {import_summary['unmatched_count']}")
366
+ return
367
+
368
+ # If only preset/config mode (no --gate/--gate-pattern), output just the violations
369
+ if not gate_names and not gate_pattern and gate_rules:
370
+ errors = [v for v in gate_violations if v["severity"] == "error"]
371
+ warnings = [v for v in gate_violations if v["severity"] == "warning"]
372
+ preset_info = preset_used.name if preset_used else "custom"
373
+
374
+ if json_mode:
375
+ click.echo(
376
+ to_json(
377
+ json_envelope(
378
+ "coverage-gaps",
379
+ summary={
380
+ "verdict": "fail" if errors else "pass",
381
+ "preset": preset_info,
382
+ "total_violations": len(gate_violations),
383
+ "errors": len(errors),
384
+ "warnings": len(warnings),
385
+ "imported_coverage_pct": import_summary["coverage_pct"] if import_summary else None,
386
+ },
387
+ preset=preset_info,
388
+ gate_violations=gate_violations,
389
+ import_summary=import_summary,
390
+ )
391
+ )
392
+ )
393
+ else:
394
+ click.echo(f"=== Coverage Gaps (preset: {preset_info}) ===\n")
395
+ if import_summary:
396
+ pct = import_summary.get("coverage_pct")
397
+ pct_str = f"{pct}%" if pct is not None else "n/a"
398
+ click.echo(
399
+ f"Imported coverage: {import_summary['matched_files']}/"
400
+ f"{import_summary['parsed_files']} files, {pct_str}"
401
+ )
402
+ click.echo()
403
+ click.echo(f"Violations: {len(gate_violations)} Errors: {len(errors)} Warnings: {len(warnings)}")
404
+ click.echo()
405
+ if gate_violations:
406
+ rows = []
407
+ for v in gate_violations[:40]:
408
+ rows.append(
409
+ [
410
+ v["severity"].upper(),
411
+ v["rule"],
412
+ v["file"],
413
+ f"{v['test_count']}/{v['min_required']}",
414
+ v["description"],
415
+ ]
416
+ )
417
+ click.echo(
418
+ format_table(
419
+ ["Severity", "Rule", "File", "Tests", "Description"],
420
+ rows,
421
+ budget=40,
422
+ )
423
+ )
424
+ else:
425
+ click.echo("All gate rules pass.")
426
+ return
427
+
428
+ if not gate_names and not gate_pattern:
429
+ click.echo("Provide --gate <names> or --gate-pattern <regex>")
430
+ raise SystemExit(1)
431
+
432
+ with open_db(readonly=True) as conn:
433
+ gates, gate_info = _find_gates(conn, gate_names, gate_pattern)
434
+
435
+ if not gates:
436
+ if json_mode:
437
+ click.echo(
438
+ to_json(
439
+ json_envelope(
440
+ "coverage-gaps",
441
+ summary={"error": "No gate symbols found"},
442
+ )
443
+ )
444
+ )
445
+ else:
446
+ click.echo("No gate symbols found matching the criteria.")
447
+ return
448
+
449
+ entries = _find_entries(conn, scope, entry_pattern)
450
+ if not entries:
451
+ if json_mode:
452
+ click.echo(
453
+ to_json(
454
+ json_envelope(
455
+ "coverage-gaps",
456
+ summary={"error": "No entry points found"},
457
+ )
458
+ )
459
+ )
460
+ else:
461
+ click.echo("No entry points found in scope.")
462
+ return
463
+
464
+ adj = build_forward_adj(conn)
465
+
466
+ # Resolve symbol names for chain display
467
+ id_to_name = {}
468
+ all_ids = set()
469
+ for e in entries:
470
+ all_ids.add(e["id"])
471
+ for g in gates:
472
+ all_ids.add(g)
473
+ # Batch fetch names
474
+ if all_ids:
475
+ for r in batched_in(
476
+ conn,
477
+ "SELECT id, name FROM symbols WHERE id IN ({ph})",
478
+ list(all_ids),
479
+ ):
480
+ id_to_name[r["id"]] = r["name"]
481
+
482
+ covered = []
483
+ uncovered = []
484
+
485
+ for entry in entries:
486
+ gate_id, depth, chain = _bfs_to_gate(adj, entry["id"], gates, max_depth)
487
+ if gate_id is not None:
488
+ # Resolve chain names (lazy — fetch as needed)
489
+ chain_names = []
490
+ for sid in chain:
491
+ if sid not in id_to_name:
492
+ r = conn.execute("SELECT name FROM symbols WHERE id = ?", (sid,)).fetchone()
493
+ id_to_name[sid] = r["name"] if r else "?"
494
+ chain_names.append(id_to_name[sid])
495
+
496
+ covered.append(
497
+ {
498
+ "name": entry["name"],
499
+ "kind": entry["kind"],
500
+ "file": entry["file_path"],
501
+ "line": entry["line_start"],
502
+ "gate": gate_info.get(gate_id, "?"),
503
+ "depth": depth,
504
+ "chain": chain_names,
505
+ }
506
+ )
507
+ else:
508
+ uncovered.append(
509
+ {
510
+ "name": entry["name"],
511
+ "kind": entry["kind"],
512
+ "file": entry["file_path"],
513
+ "line": entry["line_start"],
514
+ "reason": f"no gate in call chain (searched {max_depth} hops)",
515
+ }
516
+ )
517
+
518
+ total = len(entries)
519
+ coverage_pct = round(len(covered) * 100 / total, 1) if total else 0
520
+
521
+ if json_mode:
522
+ summary = {
523
+ "total_entries": total,
524
+ "covered": len(covered),
525
+ "uncovered": len(uncovered),
526
+ "coverage_pct": coverage_pct,
527
+ "gates_found": sorted(set(gate_info.values())),
528
+ "imported_coverage_pct": import_summary["coverage_pct"] if import_summary else None,
529
+ }
530
+ extra = dict(
531
+ gates_found=sorted(set(gate_info.values())),
532
+ uncovered=uncovered,
533
+ covered=covered,
534
+ )
535
+ if preset_used:
536
+ summary["preset"] = preset_used.name
537
+ extra["preset"] = preset_used.name
538
+ if gate_violations:
539
+ summary["gate_violation_count"] = len(gate_violations)
540
+ extra["gate_violations"] = gate_violations
541
+ if import_summary:
542
+ extra["import_summary"] = import_summary
543
+ click.echo(
544
+ to_json(
545
+ json_envelope(
546
+ "coverage-gaps",
547
+ summary=summary,
548
+ **extra,
549
+ )
550
+ )
551
+ )
552
+ return
553
+
554
+ # --- Text output ---
555
+ header = "=== Coverage Gaps ==="
556
+ if preset_used:
557
+ header = f"=== Coverage Gaps (preset: {preset_used.name}) ==="
558
+ click.echo(f"{header}\n")
559
+ if import_summary:
560
+ pct = import_summary.get("coverage_pct")
561
+ pct_str = f"{pct}%" if pct is not None else "n/a"
562
+ click.echo(
563
+ f"Imported coverage: {import_summary['matched_files']}/"
564
+ f"{import_summary['parsed_files']} files, {pct_str}"
565
+ )
566
+ click.echo()
567
+ click.echo(f"Gates: {', '.join(sorted(set(gate_info.values())))}")
568
+ click.echo(
569
+ f"Entry points: {total} Covered: {len(covered)} Uncovered: {len(uncovered)} Coverage: {coverage_pct}%"
570
+ )
571
+ click.echo()
572
+
573
+ if uncovered:
574
+ click.echo(f"-- Uncovered ({len(uncovered)}) --")
575
+ rows = []
576
+ for u in uncovered[:30]:
577
+ rows.append(
578
+ [
579
+ u["name"],
580
+ abbrev_kind(u["kind"]),
581
+ loc(u["file"], u["line"]),
582
+ u["reason"],
583
+ ]
584
+ )
585
+ click.echo(
586
+ format_table(
587
+ ["Name", "Kind", "Location", "Reason"],
588
+ rows,
589
+ budget=30,
590
+ )
591
+ )
592
+ click.echo()
593
+
594
+ if covered:
595
+ click.echo(f"-- Covered ({len(covered)}) --")
596
+ rows = []
597
+ for c in covered[:20]:
598
+ chain_str = " -> ".join(c["chain"][:5])
599
+ if len(c["chain"]) > 5:
600
+ chain_str += f" (+{len(c['chain']) - 5})"
601
+ rows.append(
602
+ [
603
+ c["name"],
604
+ abbrev_kind(c["kind"]),
605
+ loc(c["file"], c["line"]),
606
+ c["gate"],
607
+ str(c["depth"]),
608
+ chain_str,
609
+ ]
610
+ )
611
+ click.echo(
612
+ format_table(
613
+ ["Name", "Kind", "Location", "Gate", "Depth", "Chain"],
614
+ rows,
615
+ budget=20,
616
+ )
617
+ )
618
+
619
+ if gate_violations:
620
+ click.echo()
621
+ click.echo(f"-- Gate Violations ({len(gate_violations)}) --")
622
+ rows = []
623
+ for v in gate_violations[:30]:
624
+ rows.append(
625
+ [
626
+ v["severity"].upper(),
627
+ v["rule"],
628
+ v["file"],
629
+ f"{v['test_count']}/{v['min_required']}",
630
+ ]
631
+ )
632
+ click.echo(
633
+ format_table(
634
+ ["Severity", "Rule", "File", "Tests"],
635
+ rows,
636
+ budget=30,
637
+ )
638
+ )