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,533 @@
1
+ """Show domain-weighted risk ranking of symbols."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+
9
+ import click
10
+
11
+ from roam.commands.resolve import ensure_index
12
+ from roam.db.connection import batched_in, open_db
13
+ from roam.output.formatter import abbrev_kind, format_table, json_envelope, loc, to_json
14
+
15
+ # Default domain keyword -> weight multiplier mapping.
16
+ # Symbols matching high-weight domains rank higher in risk output.
17
+ _DEFAULT_DOMAINS = {
18
+ # Financial / accounting (critical -- bugs lose money)
19
+ "money": 10,
20
+ "payment": 10,
21
+ "invoice": 10,
22
+ "ledger": 10,
23
+ "balance": 10,
24
+ "transaction": 10,
25
+ "credit": 10,
26
+ "debit": 10,
27
+ "tax": 10,
28
+ "vat": 10,
29
+ "price": 8,
30
+ "cost": 8,
31
+ "amount": 8,
32
+ "currency": 8,
33
+ "billing": 8,
34
+ "refund": 8,
35
+ "receipt": 8,
36
+ "accounting": 10,
37
+ "fiscal": 10,
38
+ "journal": 8,
39
+ # Auth / security (critical -- bugs leak data)
40
+ "auth": 8,
41
+ "password": 10,
42
+ "token": 8,
43
+ "session": 3,
44
+ "permission": 8,
45
+ "encrypt": 10,
46
+ "decrypt": 10,
47
+ "secret": 10,
48
+ "credential": 10,
49
+ "login": 6,
50
+ "logout": 4,
51
+ # Data integrity
52
+ "delete": 6,
53
+ "destroy": 6,
54
+ "migrate": 6,
55
+ "truncate": 8,
56
+ "backup": 6,
57
+ "restore": 6,
58
+ "sync": 4,
59
+ "import": 1.5,
60
+ "export": 1.5,
61
+ # Business logic (medium)
62
+ "order": 2,
63
+ "customer": 5,
64
+ "user": 4,
65
+ "account": 5,
66
+ "calculate": 5,
67
+ "validate": 4,
68
+ "process": 1.5,
69
+ "approve": 5,
70
+ "schedule": 4,
71
+ "notify": 3,
72
+ "report": 4,
73
+ # UI / presentation (dampened -- less risky than business logic)
74
+ "render": 0.3,
75
+ "display": 0.3,
76
+ "show": 0.3,
77
+ "hide": 0.3,
78
+ "style": 0.3,
79
+ "theme": 0.3,
80
+ "color": 0.3,
81
+ "icon": 0.3,
82
+ "modal": 0.3,
83
+ "tooltip": 0.3,
84
+ "animation": 0.3,
85
+ "layout": 0.3,
86
+ "grid": 0.3,
87
+ "menu": 0.3,
88
+ "button": 0.3,
89
+ "dialog": 0.3,
90
+ "drawer": 0.3,
91
+ "spinner": 0.3,
92
+ "badge": 0.3,
93
+ "card": 0.3,
94
+ "panel": 0.3,
95
+ "tab": 0.3,
96
+ }
97
+
98
+
99
+ def _load_custom_domains():
100
+ """Load custom domain weights from .roam/domain-weights.json if present."""
101
+ path = os.path.join(".roam", "domain-weights.json")
102
+ if not os.path.isfile(path):
103
+ return {}
104
+ try:
105
+ with open(path) as f:
106
+ data = json.load(f)
107
+ if isinstance(data, dict):
108
+ return {str(k).lower(): float(v) for k, v in data.items() if isinstance(v, (int, float))}
109
+ except (json.JSONDecodeError, ValueError, OSError):
110
+ pass
111
+ return {}
112
+
113
+
114
+ # ---- Path-zone matching ----
115
+
116
+ _DEFAULT_PATH_ZONES = {
117
+ "accounting": (("kiniseis/", "accounting/", "vat/", "ledger/", "journal/"), 10),
118
+ "auth": (("auth/", "login/", "session/"), 8),
119
+ "backup": (("backup/", "restore/"), 6),
120
+ "data": (("migration", "seed"), 4),
121
+ }
122
+
123
+
124
+ def _load_custom_path_zones():
125
+ """Load custom path zones from .roam/path-zones.json if present."""
126
+ path = os.path.join(".roam", "path-zones.json")
127
+ if not os.path.isfile(path):
128
+ return {}
129
+ try:
130
+ with open(path) as f:
131
+ data = json.load(f)
132
+ if isinstance(data, dict):
133
+ result = {}
134
+ for zone_name, zone_cfg in data.items():
135
+ if isinstance(zone_cfg, dict):
136
+ patterns = zone_cfg.get("patterns", [])
137
+ weight = zone_cfg.get("weight", 5)
138
+ if isinstance(patterns, list) and isinstance(weight, (int, float)):
139
+ result[str(zone_name)] = (tuple(str(p) for p in patterns), float(weight))
140
+ return result
141
+ except (json.JSONDecodeError, ValueError, OSError):
142
+ pass
143
+ return {}
144
+
145
+
146
+ def _match_path_zone(file_path, path_zones):
147
+ """Return the highest path-zone weight for a file path."""
148
+ p = file_path.replace("\\", "/").lower()
149
+ best_weight = 0
150
+ best_zone = ""
151
+ for zone_name, (patterns, weight) in path_zones.items():
152
+ for pat in patterns:
153
+ if pat.lower() in p:
154
+ if weight > best_weight:
155
+ best_weight = weight
156
+ best_zone = zone_name
157
+ break
158
+ return best_weight, best_zone
159
+
160
+
161
+ _UI_PATH_PATTERNS = (
162
+ "components/",
163
+ "views/",
164
+ "pages/",
165
+ "templates/",
166
+ "layouts/",
167
+ "/ui/",
168
+ "widgets/",
169
+ "screens/",
170
+ )
171
+ _UI_EXTENSIONS = (".vue", ".svelte", ".jsx", ".tsx")
172
+
173
+
174
+ def _is_ui_file(file_path):
175
+ """Check if a file is in a UI-related directory or has a UI extension."""
176
+ p = file_path.replace("\\", "/").lower()
177
+ return any(pat in p for pat in _UI_PATH_PATTERNS) or any(p.endswith(ext) for ext in _UI_EXTENSIONS)
178
+
179
+
180
+ _SPLIT_RE = re.compile(r"[A-Z][a-z]+|[a-z]+|[A-Z]+(?=[A-Z][a-z]|\b)")
181
+
182
+
183
+ def _match_domain(name, domains):
184
+ """Return the highest domain weight for a symbol name."""
185
+ words = [w.lower() for w in _SPLIT_RE.findall(name)]
186
+ best_weight = None
187
+ matched = ""
188
+ for w in words:
189
+ if w in domains:
190
+ wt = domains[w]
191
+ if best_weight is None or wt > best_weight:
192
+ best_weight = wt
193
+ matched = w
194
+ if best_weight is None:
195
+ return 1, "" # No domain match -- neutral
196
+ return best_weight, matched
197
+
198
+
199
+ # ---- Callee-chain domain analysis ----
200
+
201
+ _CALLEE_DECAY = [1.0, 0.5, 0.25] # distance decay per hop
202
+
203
+
204
+ def _callee_chain_domain(conn, symbol_id, domains, max_depth=3):
205
+ """Walk callee graph up to max_depth hops, find strongest domain match.
206
+
207
+ Returns (effective_weight, domain_match, via_symbol_name, chain_path).
208
+ ``chain_path`` is a list of symbol names from source to matched callee.
209
+ """
210
+ best_weight = 0
211
+ best_match = ""
212
+ best_via = ""
213
+ best_chain: list[str] = []
214
+
215
+ # BFS through callees — track parent pointers for chain reconstruction
216
+ visited = {symbol_id}
217
+ parent: dict[int, int] = {} # child_id -> parent_id
218
+ id_to_name: dict[int, str] = {}
219
+ frontier = [symbol_id]
220
+
221
+ for depth in range(min(max_depth, len(_CALLEE_DECAY))):
222
+ if not frontier:
223
+ break
224
+ callees = batched_in(
225
+ conn,
226
+ "SELECT e.target_id, s.name FROM edges e "
227
+ "JOIN symbols s ON e.target_id = s.id "
228
+ "WHERE e.source_id IN ({ph}) "
229
+ "AND e.kind IN ('call', 'uses')",
230
+ frontier,
231
+ )
232
+ next_frontier = []
233
+ for callee_id, callee_name in callees:
234
+ if callee_id in visited:
235
+ continue
236
+ visited.add(callee_id)
237
+ id_to_name[callee_id] = callee_name
238
+ # Record first parent only (BFS guarantees shortest path)
239
+ if callee_id not in parent:
240
+ # find which frontier node led here
241
+ for fid in frontier:
242
+ parent[callee_id] = fid
243
+ break
244
+
245
+ w, m = _match_domain(callee_name, domains)
246
+ if w <= 1:
247
+ next_frontier.append(callee_id)
248
+ continue
249
+ effective = w * _CALLEE_DECAY[depth]
250
+ if effective > best_weight:
251
+ best_weight = effective
252
+ best_match = m
253
+ best_via = callee_name
254
+ # Reconstruct chain
255
+ chain = [callee_name]
256
+ cur = callee_id
257
+ while cur in parent:
258
+ cur = parent[cur]
259
+ if cur in id_to_name:
260
+ chain.append(id_to_name[cur])
261
+ chain.reverse()
262
+ best_chain = chain
263
+ next_frontier.append(callee_id)
264
+ frontier = next_frontier
265
+
266
+ return best_weight, best_match, best_via, best_chain
267
+
268
+
269
+ @click.command()
270
+ @click.option("-n", "count", default=30, help="Number of symbols to show")
271
+ @click.option(
272
+ "--domain",
273
+ "domain_keywords",
274
+ default=None,
275
+ help='Comma-separated high-weight domain keywords (e.g. "payment,tax,ledger")',
276
+ )
277
+ @click.option("--explain", is_flag=True, help="Show full callee-chain reasoning per symbol")
278
+ @click.pass_context
279
+ def risk(ctx, count, domain_keywords, explain):
280
+ """Show domain-weighted risk ranking of symbols.
281
+
282
+ Combines static risk (fan-in + fan-out + betweenness) with domain
283
+ criticality weights. Financial, auth, and data-integrity symbols
284
+ rank higher than UI symbols.
285
+
286
+ Domain matching uses three sources (highest wins):
287
+ - Symbol name keyword matching
288
+ - Callee-chain analysis (what the symbol calls, up to 3 hops)
289
+ - File path zone matching (e.g. kiniseis/ -> accounting zone)
290
+ """
291
+ json_mode = ctx.obj.get("json") if ctx.obj else False
292
+ ensure_index()
293
+
294
+ # Build domain map: defaults -> .roam/domain-weights.json -> CLI overrides
295
+ domains = dict(_DEFAULT_DOMAINS)
296
+ custom = _load_custom_domains()
297
+ if custom:
298
+ domains.update(custom)
299
+ if domain_keywords:
300
+ for kw in domain_keywords.split(","):
301
+ kw = kw.strip().lower()
302
+ if kw:
303
+ domains[kw] = 10 # User-specified keywords get max weight
304
+
305
+ # Build path zones: defaults -> .roam/path-zones.json
306
+ path_zones = dict(_DEFAULT_PATH_ZONES)
307
+ custom_zones = _load_custom_path_zones()
308
+ if custom_zones:
309
+ path_zones.update(custom_zones)
310
+
311
+ with open_db(readonly=True) as conn:
312
+ rows = conn.execute("""
313
+ SELECT s.id, s.name, s.kind, f.path as file_path, s.line_start,
314
+ gm.in_degree, gm.out_degree, gm.betweenness, gm.pagerank
315
+ FROM graph_metrics gm
316
+ JOIN symbols s ON gm.symbol_id = s.id
317
+ JOIN files f ON s.file_id = f.id
318
+ WHERE s.kind IN ('function', 'class', 'method', 'interface', 'struct')
319
+ AND (gm.in_degree + gm.out_degree) > 0
320
+ """).fetchall()
321
+
322
+ if not rows:
323
+ if json_mode:
324
+ click.echo(
325
+ to_json(
326
+ json_envelope(
327
+ "risk",
328
+ summary={"items": 0, "max_risk": 0},
329
+ items=[],
330
+ )
331
+ )
332
+ )
333
+ else:
334
+ click.echo("No graph metrics available. Run `roam index` first.")
335
+ return
336
+
337
+ # Compute static risk (0-10 scale)
338
+ max_total = max(((r["in_degree"] or 0) + (r["out_degree"] or 0)) for r in rows) or 1
339
+ max_bw = max((r["betweenness"] or 0) for r in rows) or 1
340
+
341
+ scored = []
342
+ for r in rows:
343
+ total_deg = (r["in_degree"] or 0) + (r["out_degree"] or 0)
344
+ bw = r["betweenness"] or 0
345
+
346
+ # Static risk: weighted combination of degree and betweenness
347
+ static_risk = (total_deg / max_total) * 5 + (bw / max_bw) * 5
348
+
349
+ # --- Three-source domain matching ---
350
+ name_weight, name_match = _match_domain(r["name"], domains)
351
+ zone_weight, zone_match = _match_path_zone(r["file_path"], path_zones)
352
+ callee_weight, callee_match, callee_via, callee_chain = _callee_chain_domain(conn, r["id"], domains)
353
+
354
+ # Pick the strongest source
355
+ domain_weight = name_weight
356
+ domain_match = name_match
357
+ domain_source = "name"
358
+
359
+ if callee_weight > domain_weight:
360
+ domain_weight = callee_weight
361
+ domain_match = callee_match
362
+ domain_source = "callee"
363
+
364
+ if zone_weight > domain_weight:
365
+ domain_weight = zone_weight
366
+ domain_match = zone_match
367
+ domain_source = "zone"
368
+
369
+ # File-path UI dampening: if symbol is in a UI file and matched
370
+ # a non-UI domain keyword (e.g. "restore" in a component),
371
+ # halve the domain weight to avoid false positives
372
+ ui_dampened = False
373
+ if domain_weight > 1 and domain_source != "zone" and _is_ui_file(r["file_path"]):
374
+ domain_weight = max(1, domain_weight * 0.5)
375
+ ui_dampened = True
376
+
377
+ adjusted_risk = static_risk * domain_weight
378
+
379
+ # Build domain description string for text output
380
+ if domain_source == "name" and domain_weight > 1:
381
+ domain_desc = f"x{domain_weight:.4g} ({domain_match})"
382
+ elif domain_source == "callee" and domain_weight > 1:
383
+ domain_desc = f"x{domain_weight:.4g} ({domain_match}) via {callee_via}"
384
+ elif domain_source == "zone" and domain_weight > 1:
385
+ domain_desc = f"x{domain_weight:.4g} [{domain_match} zone]"
386
+ else:
387
+ domain_desc = ""
388
+
389
+ scored.append(
390
+ {
391
+ "name": r["name"],
392
+ "kind": r["kind"],
393
+ "file_path": r["file_path"],
394
+ "line_start": r["line_start"],
395
+ "static_risk": round(static_risk, 1),
396
+ "domain_weight": domain_weight,
397
+ "domain_match": domain_match,
398
+ "domain_source": domain_source,
399
+ "domain_desc": domain_desc,
400
+ "ui_dampened": ui_dampened,
401
+ "adjusted_risk": round(adjusted_risk, 1),
402
+ "in_degree": r["in_degree"] or 0,
403
+ "out_degree": r["out_degree"] or 0,
404
+ "betweenness": round(bw, 1),
405
+ "callee_chain": callee_chain,
406
+ "callee_via": callee_via,
407
+ "name_weight": name_weight,
408
+ "name_match": name_match,
409
+ "zone_weight": zone_weight,
410
+ "zone_match": zone_match,
411
+ "callee_weight": callee_weight,
412
+ "callee_match": callee_match,
413
+ }
414
+ )
415
+
416
+ scored.sort(key=lambda x: -x["adjusted_risk"])
417
+ scored = scored[:count]
418
+
419
+ if json_mode:
420
+ items = []
421
+ for s in scored:
422
+ item = {
423
+ "name": s["name"],
424
+ "kind": s["kind"],
425
+ "static_risk": s["static_risk"],
426
+ "domain_weight": s["domain_weight"],
427
+ "domain_match": s["domain_match"],
428
+ "domain_source": s["domain_source"],
429
+ "ui_dampened": s["ui_dampened"],
430
+ "adjusted_risk": s["adjusted_risk"],
431
+ "location": loc(s["file_path"], s["line_start"]),
432
+ }
433
+ if explain:
434
+ item["in_degree"] = s["in_degree"]
435
+ item["out_degree"] = s["out_degree"]
436
+ item["betweenness"] = s["betweenness"]
437
+ item["chain"] = s["callee_chain"]
438
+ item["domain_sources"] = {}
439
+ if s["name_weight"] > 1:
440
+ item["domain_sources"]["name"] = {
441
+ "keyword": s["name_match"],
442
+ "weight": s["name_weight"],
443
+ }
444
+ if s["callee_weight"] > 1:
445
+ item["domain_sources"]["callee"] = {
446
+ "keyword": s["callee_match"],
447
+ "weight": s["callee_weight"],
448
+ "via": s["callee_via"],
449
+ }
450
+ if s["zone_weight"] > 1:
451
+ item["domain_sources"]["zone"] = {
452
+ "pattern": s["zone_match"],
453
+ "weight": s["zone_weight"],
454
+ }
455
+ items.append(item)
456
+ click.echo(
457
+ to_json(
458
+ json_envelope(
459
+ "risk",
460
+ summary={"count": len(items), "explain": explain},
461
+ items=items,
462
+ )
463
+ )
464
+ )
465
+ return
466
+
467
+ # --- Text output ---
468
+ click.echo("=== Domain-Weighted Risk ===")
469
+ if domain_keywords:
470
+ click.echo(f" Custom domain keywords: {domain_keywords}")
471
+ click.echo()
472
+
473
+ if explain:
474
+ # Detailed per-symbol reasoning
475
+ for s in scored:
476
+ flag = ""
477
+ if s["adjusted_risk"] >= 30:
478
+ flag = "CRITICAL"
479
+ elif s["adjusted_risk"] >= 15:
480
+ flag = "HIGH"
481
+ elif s["adjusted_risk"] >= 5:
482
+ flag = "MEDIUM"
483
+
484
+ click.echo(f"{flag:8s} {s['name']} (adjusted: {s['adjusted_risk']:.1f})")
485
+ click.echo(
486
+ f" Static risk: {s['static_risk']:.1f} "
487
+ f"(fan-in: {s['in_degree']}, fan-out: {s['out_degree']}, "
488
+ f"betweenness: {s['betweenness']:.0f})"
489
+ )
490
+ if s["name_weight"] > 1:
491
+ click.echo(f" Name match: x{s['name_weight']:.4g} ({s['name_match']})")
492
+ if s["callee_chain"]:
493
+ chain_str = " -> ".join(s["callee_chain"])
494
+ click.echo(f" Callee chain: {chain_str} (matched: {s['callee_match']}, x{s['callee_weight']:.4g})")
495
+ if s["zone_weight"] > 1:
496
+ click.echo(f" Path zone: {s['zone_match']} (x{s['zone_weight']:.4g})")
497
+ if s["ui_dampened"]:
498
+ click.echo(" UI dampened: yes")
499
+ click.echo(f" Location: {loc(s['file_path'], s['line_start'])}")
500
+ click.echo()
501
+ else:
502
+ table_rows = []
503
+ for s in scored:
504
+ flag = ""
505
+ if s["adjusted_risk"] >= 30:
506
+ flag = "CRITICAL"
507
+ elif s["adjusted_risk"] >= 15:
508
+ flag = "HIGH"
509
+ elif s["adjusted_risk"] >= 5:
510
+ flag = "MEDIUM"
511
+
512
+ notes = s["domain_desc"]
513
+ if s["ui_dampened"]:
514
+ notes += " [UI dampened]" if notes else "[UI dampened]"
515
+
516
+ table_rows.append(
517
+ [
518
+ abbrev_kind(s["kind"]),
519
+ s["name"],
520
+ f"{s['static_risk']:.1f}",
521
+ notes,
522
+ f"{s['adjusted_risk']:.1f}",
523
+ flag,
524
+ loc(s["file_path"], s["line_start"]),
525
+ ]
526
+ )
527
+
528
+ click.echo(
529
+ format_table(
530
+ ["Kind", "Name", "Static", "Domain", "Adjusted", "Level", "Location"],
531
+ table_rows,
532
+ )
533
+ )