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,732 @@
1
+ """Hybrid semantic search: FTS5/BM25 + TF-IDF vector fusion."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import math
7
+ import re
8
+ from typing import Any
9
+
10
+ from roam.search.framework_packs import search_pack_symbols
11
+ from roam.search.tfidf import cosine_similarity, tokenize
12
+
13
+ # ---------------------------------------------------------------------------
14
+ # camelCase preprocessing for FTS5 tokenizer
15
+ # ---------------------------------------------------------------------------
16
+
17
+
18
+ def _camel_split(text: str) -> str:
19
+ """Insert spaces at camelCase/PascalCase boundaries for FTS5.
20
+
21
+ ``OpenDatabase`` → ``Open Database``
22
+ ``XMLParser`` → ``XML Parser``
23
+ ``file_path`` → ``file_path`` (underscores handled by unicode61)
24
+ """
25
+ if not text:
26
+ return ""
27
+ result = re.sub(r"([a-z])([A-Z])", r"\1 \2", text)
28
+ result = re.sub(r"([A-Z]+)([A-Z][a-z])", r"\1 \2", result)
29
+ return result
30
+
31
+
32
+ # ---------------------------------------------------------------------------
33
+ # FTS5 availability detection
34
+ # ---------------------------------------------------------------------------
35
+
36
+
37
+ def fts5_available(conn) -> bool:
38
+ """Check if the symbol_fts virtual table exists and is usable."""
39
+ try:
40
+ row = conn.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='symbol_fts'").fetchone()
41
+ return row is not None
42
+ except Exception:
43
+ return False
44
+
45
+
46
+ def fts5_populated(conn) -> bool:
47
+ """Check if symbol_fts has data."""
48
+ if not fts5_available(conn):
49
+ return False
50
+ try:
51
+ row = conn.execute("SELECT COUNT(*) FROM symbol_fts").fetchone()
52
+ return row is not None and row[0] > 0
53
+ except Exception:
54
+ return False
55
+
56
+
57
+ def tfidf_populated(conn) -> bool:
58
+ """Check if symbol_tfidf has data."""
59
+ try:
60
+ row = conn.execute("SELECT COUNT(*) FROM symbol_tfidf").fetchone()
61
+ return row is not None and row[0] > 0
62
+ except Exception:
63
+ return False
64
+
65
+
66
+ def onnx_populated(conn) -> bool:
67
+ """Check if ONNX embedding table has data."""
68
+ try:
69
+ row = conn.execute("SELECT COUNT(*) FROM symbol_embeddings WHERE provider='onnx'").fetchone()
70
+ return row is not None and row[0] > 0
71
+ except Exception:
72
+ return False
73
+
74
+
75
+ def _load_semantic_settings(project_root=None) -> dict[str, Any]:
76
+ """Load semantic backend settings with env-over-config precedence."""
77
+ from roam.search.onnx_embeddings import load_semantic_settings
78
+
79
+ return load_semantic_settings(project_root=project_root)
80
+
81
+
82
+ def _onnx_ready(project_root=None, settings=None):
83
+ """Return ONNX backend readiness status."""
84
+ from roam.search.onnx_embeddings import onnx_ready
85
+
86
+ return onnx_ready(project_root=project_root, settings=settings)
87
+
88
+
89
+ def _get_onnx_embedder(project_root=None, settings=None):
90
+ """Return ONNX embedder if backend is configured and dependencies are present."""
91
+ from roam.search.onnx_embeddings import get_onnx_embedder
92
+
93
+ return get_onnx_embedder(project_root=project_root, settings=settings)
94
+
95
+
96
+ # ---------------------------------------------------------------------------
97
+ # FTS5 index build (called during `roam index`)
98
+ # ---------------------------------------------------------------------------
99
+
100
+
101
+ def build_fts_index(conn, project_root=None):
102
+ """Populate the FTS5 symbol_fts table for BM25-ranked search.
103
+
104
+ Pushes tokenization and indexing entirely to SQLite's C engine.
105
+ Also persists TF-IDF vectors for hybrid ranking.
106
+ """
107
+ if not fts5_available(conn):
108
+ build_and_store_tfidf(conn)
109
+ try:
110
+ build_and_store_onnx_embeddings(conn, project_root=project_root)
111
+ except Exception:
112
+ pass
113
+ return
114
+
115
+ # Clear and rebuild — FTS5 doesn't support UPDATE well, full rebuild is fast
116
+ conn.execute("DELETE FROM symbol_fts")
117
+
118
+ rows = conn.execute(
119
+ "SELECT s.id, s.name, s.qualified_name, s.signature, s.kind, "
120
+ "f.path as file_path "
121
+ "FROM symbols s JOIN files f ON s.file_id = f.id"
122
+ ).fetchall()
123
+
124
+ if not rows:
125
+ return
126
+
127
+ # Insert with camelCase preprocessing for better tokenization
128
+ batch = []
129
+ for row in rows:
130
+ batch.append(
131
+ (
132
+ row["id"],
133
+ _camel_split(row["name"] or ""),
134
+ _camel_split(row["qualified_name"] or ""),
135
+ _camel_split(row["signature"] or ""),
136
+ row["kind"] or "",
137
+ row["file_path"] or "",
138
+ )
139
+ )
140
+ if len(batch) >= 500:
141
+ conn.executemany(
142
+ "INSERT INTO symbol_fts(rowid, name, qualified_name, "
143
+ "signature, kind, file_path) VALUES (?, ?, ?, ?, ?, ?)",
144
+ batch,
145
+ )
146
+ batch.clear()
147
+
148
+ if batch:
149
+ conn.executemany(
150
+ "INSERT INTO symbol_fts(rowid, name, qualified_name, signature, kind, file_path) VALUES (?, ?, ?, ?, ?, ?)",
151
+ batch,
152
+ )
153
+
154
+ # Keep vector signals available even when FTS5 exists (hybrid #54).
155
+ build_and_store_tfidf(conn)
156
+ # Optional dense local embeddings (ONNX) for semantic search (#56).
157
+ try:
158
+ build_and_store_onnx_embeddings(conn, project_root=project_root)
159
+ except Exception:
160
+ # ONNX is optional; TF-IDF path remains authoritative fallback.
161
+ pass
162
+
163
+
164
+ # ---------------------------------------------------------------------------
165
+ # FTS5 search (primary path)
166
+ # ---------------------------------------------------------------------------
167
+
168
+ # BM25 column weights: name=10, qualified_name=5, signature=2, kind=1, file_path=3
169
+ _BM25_WEIGHTS = "10.0, 5.0, 2.0, 1.0, 3.0"
170
+
171
+ # Hybrid fusion defaults (backlog #54).
172
+ _HYBRID_LEXICAL_WEIGHT = 0.65
173
+ _HYBRID_SEMANTIC_WEIGHT = 0.35
174
+ _HYBRID_RANK_WEIGHT = 0.40
175
+ _HYBRID_RRF_K = 60
176
+ _HYBRID_MIN_CANDIDATES = 25
177
+ _HYBRID_CANDIDATE_MULTIPLIER = 4
178
+
179
+ _FTS5_SEARCH_SQL = f"""
180
+ SELECT sf.rowid as symbol_id,
181
+ -bm25(symbol_fts, {_BM25_WEIGHTS}) as score,
182
+ s.name, f.path as file_path, s.kind, s.line_start, s.line_end
183
+ FROM symbol_fts sf
184
+ JOIN symbols s ON sf.rowid = s.id
185
+ JOIN files f ON s.file_id = f.id
186
+ WHERE symbol_fts MATCH ?
187
+ ORDER BY bm25(symbol_fts, {_BM25_WEIGHTS})
188
+ LIMIT ?
189
+ """
190
+
191
+
192
+ def search_fts(conn, query: str, top_k: int = 10) -> list[dict]:
193
+ """Search using FTS5 BM25 ranking (fast, all in C).
194
+
195
+ Returns top-k results: ``[{score, symbol_id, name, file_path, kind, line_start}]``.
196
+ """
197
+ if not query or not query.strip():
198
+ return []
199
+
200
+ # Preprocess query: camelCase split + escape FTS5 special chars
201
+ fts_query = _build_fts_query(query)
202
+ if not fts_query:
203
+ return []
204
+
205
+ try:
206
+ rows = conn.execute(_FTS5_SEARCH_SQL, (fts_query, top_k)).fetchall()
207
+ except Exception:
208
+ # FTS5 query syntax error — fall back to prefix match
209
+ try:
210
+ fts_query = _build_fts_query(query, prefix_only=True)
211
+ if fts_query:
212
+ rows = conn.execute(_FTS5_SEARCH_SQL, (fts_query, top_k)).fetchall()
213
+ else:
214
+ return []
215
+ except Exception:
216
+ return []
217
+
218
+ results = []
219
+ for row in rows:
220
+ results.append(
221
+ {
222
+ "score": round(row["score"], 4),
223
+ "symbol_id": row["symbol_id"],
224
+ "name": row["name"],
225
+ "file_path": row["file_path"],
226
+ "kind": row["kind"],
227
+ "line_start": row["line_start"],
228
+ "line_end": row["line_end"],
229
+ }
230
+ )
231
+ return results
232
+
233
+
234
+ def _build_fts_query(query: str, prefix_only: bool = False) -> str:
235
+ """Convert a natural language query into an FTS5 MATCH expression.
236
+
237
+ - Splits camelCase
238
+ - Removes FTS5 special characters
239
+ - Joins tokens with implicit AND (FTS5 default)
240
+ - Adds prefix matching (``*``) for the last token for typeahead
241
+ """
242
+ preprocessed = _camel_split(query)
243
+ # Remove FTS5 special syntax chars: ^, *, ", (, ), {, }, :
244
+ cleaned = re.sub(r"[^\w\s]", " ", preprocessed)
245
+ tokens = cleaned.split()
246
+ tokens = [t for t in tokens if len(t) >= 2]
247
+ if not tokens:
248
+ return ""
249
+
250
+ if prefix_only:
251
+ return " ".join(f'"{t}"*' for t in tokens)
252
+
253
+ # Last token gets prefix matching for typeahead behavior
254
+ parts = [f'"{t}"' for t in tokens[:-1]]
255
+ parts.append(f'"{tokens[-1]}"*')
256
+ return " ".join(parts)
257
+
258
+
259
+ # ---------------------------------------------------------------------------
260
+ # Unified search: hybrid BM25 + TF-IDF vector fusion
261
+ # ---------------------------------------------------------------------------
262
+
263
+
264
+ def _normalize_scores(results: list[dict]) -> dict[int, float]:
265
+ """Normalize result scores to [0,1] by list max score."""
266
+ if not results:
267
+ return {}
268
+ max_score = max(float(r.get("score", 0.0) or 0.0) for r in results)
269
+ if max_score <= 0:
270
+ return {int(r["symbol_id"]): 0.0 for r in results if r.get("symbol_id") is not None}
271
+ return {
272
+ int(r["symbol_id"]): float(r.get("score", 0.0) or 0.0) / max_score
273
+ for r in results
274
+ if r.get("symbol_id") is not None
275
+ }
276
+
277
+
278
+ def _fuse_hybrid_results(
279
+ lexical_results: list[dict],
280
+ semantic_results: list[dict],
281
+ top_k: int,
282
+ ) -> list[dict]:
283
+ """Fuse BM25 and TF-IDF rankings with weighted RRF + score blending."""
284
+ if not lexical_results and not semantic_results:
285
+ return []
286
+
287
+ lex_rank = {int(r["symbol_id"]): idx + 1 for idx, r in enumerate(lexical_results) if r.get("symbol_id") is not None}
288
+ sem_rank = {
289
+ int(r["symbol_id"]): idx + 1 for idx, r in enumerate(semantic_results) if r.get("symbol_id") is not None
290
+ }
291
+ lex_norm = _normalize_scores(lexical_results)
292
+ sem_norm = _normalize_scores(semantic_results)
293
+ lex_meta = {int(r["symbol_id"]): r for r in lexical_results if r.get("symbol_id") is not None}
294
+ sem_meta = {int(r["symbol_id"]): r for r in semantic_results if r.get("symbol_id") is not None}
295
+
296
+ max_rrf = 1.0 / (_HYBRID_RRF_K + 1)
297
+ merged: list[dict] = []
298
+ for sid in sorted(set(lex_rank) | set(sem_rank)):
299
+ lr = lex_rank.get(sid)
300
+ sr = sem_rank.get(sid)
301
+ lex_rrf = (1.0 / (_HYBRID_RRF_K + lr)) if lr else 0.0
302
+ sem_rrf = (1.0 / (_HYBRID_RRF_K + sr)) if sr else 0.0
303
+ rank_score = ((_HYBRID_LEXICAL_WEIGHT * lex_rrf) + (_HYBRID_SEMANTIC_WEIGHT * sem_rrf)) / max_rrf
304
+ signal_score = (_HYBRID_LEXICAL_WEIGHT * lex_norm.get(sid, 0.0)) + (
305
+ _HYBRID_SEMANTIC_WEIGHT * sem_norm.get(sid, 0.0)
306
+ )
307
+ score = (_HYBRID_RANK_WEIGHT * rank_score) + ((1.0 - _HYBRID_RANK_WEIGHT) * signal_score)
308
+
309
+ meta = lex_meta.get(sid) or sem_meta.get(sid)
310
+ if not meta:
311
+ continue
312
+ merged.append(
313
+ {
314
+ "score": round(score, 4),
315
+ "symbol_id": sid,
316
+ "name": meta["name"],
317
+ "file_path": meta["file_path"],
318
+ "kind": meta["kind"],
319
+ "line_start": meta["line_start"],
320
+ "line_end": meta.get("line_end"),
321
+ "_rank_sort": min(lr or 10_000, sr or 10_000),
322
+ }
323
+ )
324
+
325
+ merged.sort(
326
+ key=lambda r: (
327
+ -r["score"],
328
+ r["_rank_sort"],
329
+ r["name"] or "",
330
+ r["symbol_id"],
331
+ )
332
+ )
333
+ for row in merged:
334
+ row.pop("_rank_sort", None)
335
+ return merged[:top_k]
336
+
337
+
338
+ def search_stored(
339
+ conn,
340
+ query: str,
341
+ top_k: int = 10,
342
+ include_packs: bool = True,
343
+ packs: list[str] | None = None,
344
+ semantic_backend: str = "auto",
345
+ project_root=None,
346
+ ) -> list[dict]:
347
+ """Search using hybrid BM25+vector fusion with optional framework packs.
348
+
349
+ Returns top-k results: ``[{score, symbol_id, name, file_path, kind, line_start}]``.
350
+ """
351
+ if not query or not query.strip():
352
+ return []
353
+
354
+ candidate_k = max(top_k * _HYBRID_CANDIDATE_MULTIPLIER, _HYBRID_MIN_CANDIDATES)
355
+ backend = (semantic_backend or "auto").strip().lower()
356
+ if backend not in {"auto", "tfidf", "onnx", "hybrid"}:
357
+ backend = "auto"
358
+
359
+ lexical_results: list[dict] = []
360
+ semantic_results: list[dict] = []
361
+ onnx_results: list[dict] = []
362
+ tfidf_results: list[dict] = []
363
+
364
+ # Fast lexical branch (FTS5/BM25).
365
+ if fts5_populated(conn):
366
+ lexical_results = search_fts(conn, query, top_k=candidate_k)
367
+
368
+ # Dense ONNX branch.
369
+ if backend in {"auto", "onnx", "hybrid"} and onnx_populated(conn):
370
+ onnx_results = _search_onnx_stored(
371
+ conn,
372
+ query,
373
+ top_k=candidate_k,
374
+ project_root=project_root,
375
+ )
376
+
377
+ # Sparse TF-IDF branch.
378
+ if backend in {"auto", "tfidf", "hybrid"} and tfidf_populated(conn):
379
+ tfidf_results = _search_tfidf_stored(conn, query, top_k=candidate_k)
380
+
381
+ semantic_results = _merge_semantic_results(
382
+ onnx_results,
383
+ tfidf_results,
384
+ top_k=candidate_k,
385
+ )
386
+
387
+ # Optional pre-indexed framework/library packs (#96).
388
+ if include_packs:
389
+ try:
390
+ pack_results = search_pack_symbols(query, top_k=candidate_k, packs=packs)
391
+ except Exception:
392
+ pack_results = []
393
+ if pack_results:
394
+ semantic_results = sorted(
395
+ semantic_results + pack_results,
396
+ key=lambda r: (
397
+ -r.get("score", 0.0),
398
+ r.get("name", ""),
399
+ r.get("symbol_id", 0),
400
+ ),
401
+ )[:candidate_k]
402
+
403
+ # Hybrid fusion when both signals exist.
404
+ if lexical_results and semantic_results:
405
+ return _fuse_hybrid_results(lexical_results, semantic_results, top_k)
406
+
407
+ # Graceful single-branch fallback.
408
+ if lexical_results:
409
+ return lexical_results[:top_k]
410
+ if semantic_results:
411
+ return semantic_results[:top_k]
412
+ return []
413
+
414
+
415
+ # ---------------------------------------------------------------------------
416
+ # Legacy TF-IDF paths (fallback for pre-v11 databases)
417
+ # ---------------------------------------------------------------------------
418
+
419
+ # The symbol_tfidf table is defined in roam.db.schema (SCHEMA_SQL) and is
420
+ # created by ensure_schema() during open_db(). The helper below is kept for
421
+ # callers that operate on standalone connections (e.g. tests, external tools).
422
+
423
+
424
+ def ensure_tfidf_table(conn):
425
+ """Ensure the symbol_tfidf table exists.
426
+
427
+ Delegates to the canonical schema in roam.db.schema so there is a single
428
+ source of truth for the table definition.
429
+ """
430
+ from roam.db.schema import SCHEMA_SQL
431
+
432
+ conn.executescript(SCHEMA_SQL)
433
+
434
+
435
+ def build_and_store_tfidf(conn):
436
+ """Compute TF-IDF vectors for all symbols and store in symbol_tfidf.
437
+
438
+ Called during ``roam index`` as part of hybrid search index build.
439
+ """
440
+ from roam.search.tfidf import build_corpus
441
+
442
+ ensure_tfidf_table(conn)
443
+
444
+ corpus = build_corpus(conn)
445
+ if not corpus:
446
+ return
447
+
448
+ conn.execute("DELETE FROM symbol_tfidf")
449
+
450
+ batch = []
451
+ for sid, vec in corpus.items():
452
+ terms_json = json.dumps(vec)
453
+ batch.append((sid, terms_json))
454
+ if len(batch) >= 500:
455
+ conn.executemany(
456
+ "INSERT OR REPLACE INTO symbol_tfidf (symbol_id, terms) VALUES (?, ?)",
457
+ batch,
458
+ )
459
+ batch.clear()
460
+
461
+ if batch:
462
+ conn.executemany(
463
+ "INSERT OR REPLACE INTO symbol_tfidf (symbol_id, terms) VALUES (?, ?)",
464
+ batch,
465
+ )
466
+
467
+
468
+ def _build_symbol_embedding_text(row) -> str:
469
+ """Compose symbol text payload for dense embedding."""
470
+ parts = [
471
+ row["name"] or "",
472
+ row["qualified_name"] or "",
473
+ row["signature"] or "",
474
+ row["kind"] or "",
475
+ row["docstring"] or "",
476
+ ]
477
+ return " \n ".join(p for p in parts if p)
478
+
479
+
480
+ def build_and_store_onnx_embeddings(conn, project_root=None) -> dict[str, Any]:
481
+ """Compute dense ONNX vectors for symbols and store in symbol_embeddings."""
482
+ settings = _load_semantic_settings(project_root=project_root)
483
+ ready, reason, settings = _onnx_ready(project_root=project_root, settings=settings)
484
+ if not ready:
485
+ return {"enabled": False, "reason": reason}
486
+
487
+ embedder = _get_onnx_embedder(project_root=project_root, settings=settings)
488
+ if embedder is None:
489
+ return {"enabled": False, "reason": "embedder-unavailable"}
490
+
491
+ rows = conn.execute("SELECT id, name, qualified_name, signature, kind, docstring FROM symbols").fetchall()
492
+ if not rows:
493
+ return {"enabled": True, "stored": 0, "dims": 0}
494
+
495
+ texts = [_build_symbol_embedding_text(row) for row in rows]
496
+ vectors = embedder.embed_texts(texts)
497
+ if not vectors:
498
+ return {"enabled": True, "stored": 0, "dims": 0}
499
+
500
+ count = min(len(rows), len(vectors))
501
+ dims = len(vectors[0]) if vectors and vectors[0] else 0
502
+ model_id = getattr(embedder, "model_id", "onnx-model")
503
+
504
+ conn.execute("DELETE FROM symbol_embeddings WHERE provider='onnx'")
505
+ batch = []
506
+ for idx in range(count):
507
+ sid = rows[idx]["id"]
508
+ vec = vectors[idx]
509
+ batch.append((sid, json.dumps(vec), dims, "onnx", model_id))
510
+ if len(batch) >= 250:
511
+ conn.executemany(
512
+ "INSERT OR REPLACE INTO symbol_embeddings "
513
+ "(symbol_id, vector, dims, provider, model_id) "
514
+ "VALUES (?, ?, ?, ?, ?)",
515
+ batch,
516
+ )
517
+ batch.clear()
518
+
519
+ if batch:
520
+ conn.executemany(
521
+ "INSERT OR REPLACE INTO symbol_embeddings "
522
+ "(symbol_id, vector, dims, provider, model_id) "
523
+ "VALUES (?, ?, ?, ?, ?)",
524
+ batch,
525
+ )
526
+
527
+ return {
528
+ "enabled": True,
529
+ "stored": count,
530
+ "dims": dims,
531
+ "model_id": model_id,
532
+ }
533
+
534
+
535
+ def load_onnx_vectors(conn) -> dict[int, list[float]]:
536
+ """Load stored ONNX vectors from DB."""
537
+ rows = conn.execute("SELECT symbol_id, vector FROM symbol_embeddings WHERE provider='onnx'").fetchall()
538
+ result: dict[int, list[float]] = {}
539
+ for row in rows:
540
+ try:
541
+ vec = json.loads(row["vector"])
542
+ except (json.JSONDecodeError, TypeError):
543
+ continue
544
+ if isinstance(vec, list) and vec:
545
+ result[int(row["symbol_id"])] = [float(v) for v in vec]
546
+ return result
547
+
548
+
549
+ def _cosine_dense(vec_a: list[float], vec_b: list[float]) -> float:
550
+ """Cosine similarity for dense vectors."""
551
+ if not vec_a or not vec_b:
552
+ return 0.0
553
+ n = min(len(vec_a), len(vec_b))
554
+ if n == 0:
555
+ return 0.0
556
+ dot = sum(vec_a[i] * vec_b[i] for i in range(n))
557
+ norm_a = math.sqrt(sum(vec_a[i] * vec_a[i] for i in range(n)))
558
+ norm_b = math.sqrt(sum(vec_b[i] * vec_b[i] for i in range(n)))
559
+ if norm_a == 0.0 or norm_b == 0.0:
560
+ return 0.0
561
+ return dot / (norm_a * norm_b)
562
+
563
+
564
+ def _search_onnx_stored(
565
+ conn,
566
+ query: str,
567
+ top_k: int = 10,
568
+ project_root=None,
569
+ ) -> list[dict]:
570
+ """Search using precomputed ONNX vectors + query embedding."""
571
+ settings = _load_semantic_settings(project_root=project_root)
572
+ ready, _, settings = _onnx_ready(project_root=project_root, settings=settings)
573
+ if not ready:
574
+ return []
575
+
576
+ embedder = _get_onnx_embedder(project_root=project_root, settings=settings)
577
+ if embedder is None:
578
+ return []
579
+
580
+ query_vecs = embedder.embed_texts([query])
581
+ if not query_vecs:
582
+ return []
583
+ query_vec = query_vecs[0]
584
+
585
+ vectors = load_onnx_vectors(conn)
586
+ if not vectors:
587
+ return []
588
+
589
+ scores: list[tuple[float, int]] = []
590
+ for sid, vec in vectors.items():
591
+ sim = _cosine_dense(query_vec, vec)
592
+ if sim > 0:
593
+ scores.append((sim, sid))
594
+ if not scores:
595
+ return []
596
+
597
+ scores.sort(key=lambda x: -x[0])
598
+ top = scores[:top_k]
599
+
600
+ sym_ids = [sid for _, sid in top]
601
+ batch_size = 500
602
+ meta: dict[int, dict] = {}
603
+ for i in range(0, len(sym_ids), batch_size):
604
+ batch = sym_ids[i : i + batch_size]
605
+ ph = ",".join("?" for _ in batch)
606
+ rows = conn.execute(
607
+ f"SELECT s.id, s.name, f.path as file_path, s.kind, "
608
+ f"s.line_start, s.line_end "
609
+ f"FROM symbols s JOIN files f ON s.file_id = f.id "
610
+ f"WHERE s.id IN ({ph})",
611
+ batch,
612
+ ).fetchall()
613
+ for row in rows:
614
+ meta[row["id"]] = row
615
+
616
+ results = []
617
+ for score, sid in top:
618
+ row = meta.get(sid)
619
+ if not row:
620
+ continue
621
+ results.append(
622
+ {
623
+ "score": round(score, 4),
624
+ "symbol_id": sid,
625
+ "name": row["name"],
626
+ "file_path": row["file_path"],
627
+ "kind": row["kind"],
628
+ "line_start": row["line_start"],
629
+ "line_end": row["line_end"],
630
+ }
631
+ )
632
+ return results
633
+
634
+
635
+ def _merge_semantic_results(*branches: list[dict], top_k: int) -> list[dict]:
636
+ """Merge semantic result branches by symbol id, keeping max score."""
637
+ merged: dict[int, dict] = {}
638
+ for branch in branches:
639
+ for row in branch:
640
+ sid = row.get("symbol_id")
641
+ if sid is None:
642
+ continue
643
+ existing = merged.get(int(sid))
644
+ if existing is None or float(row.get("score", 0.0)) > float(existing.get("score", 0.0)):
645
+ merged[int(sid)] = dict(row)
646
+
647
+ values = list(merged.values())
648
+ values.sort(
649
+ key=lambda r: (
650
+ -float(r.get("score", 0.0)),
651
+ r.get("name", ""),
652
+ int(r.get("symbol_id", 0)),
653
+ )
654
+ )
655
+ return values[:top_k]
656
+
657
+
658
+ def load_tfidf_vectors(conn) -> dict[int, dict[str, float]]:
659
+ """Load stored TF-IDF vectors from DB."""
660
+ ensure_tfidf_table(conn)
661
+ rows = conn.execute("SELECT symbol_id, terms FROM symbol_tfidf").fetchall()
662
+
663
+ result: dict[int, dict[str, float]] = {}
664
+ for row in rows:
665
+ try:
666
+ vec = json.loads(row["terms"])
667
+ result[row["symbol_id"]] = vec
668
+ except (json.JSONDecodeError, TypeError):
669
+ continue
670
+ return result
671
+
672
+
673
+ def _search_tfidf_stored(conn, query: str, top_k: int = 10) -> list[dict]:
674
+ """Search using pre-computed TF-IDF vectors (legacy fallback)."""
675
+ query_tokens = tokenize(query)
676
+ if not query_tokens:
677
+ return []
678
+
679
+ query_vec: dict[str, float] = {}
680
+ for t in query_tokens:
681
+ query_vec[t] = query_vec.get(t, 0) + 1
682
+
683
+ vectors = load_tfidf_vectors(conn)
684
+ if not vectors:
685
+ return []
686
+
687
+ scores: list[tuple[float, int]] = []
688
+ for sid, vec in vectors.items():
689
+ sim = cosine_similarity(query_vec, vec)
690
+ if sim > 0:
691
+ scores.append((sim, sid))
692
+
693
+ if not scores:
694
+ return []
695
+
696
+ scores.sort(key=lambda x: -x[0])
697
+ top = scores[:top_k]
698
+
699
+ sym_ids = [sid for _, sid in top]
700
+ batch_size = 500
701
+ meta: dict[int, dict] = {}
702
+ for i in range(0, len(sym_ids), batch_size):
703
+ batch = sym_ids[i : i + batch_size]
704
+ ph = ",".join("?" for _ in batch)
705
+ rows = conn.execute(
706
+ f"SELECT s.id, s.name, f.path as file_path, s.kind, "
707
+ f"s.line_start, s.line_end "
708
+ f"FROM symbols s JOIN files f ON s.file_id = f.id "
709
+ f"WHERE s.id IN ({ph})",
710
+ batch,
711
+ ).fetchall()
712
+ for r in rows:
713
+ meta[r["id"]] = r
714
+
715
+ results = []
716
+ for score, sid in top:
717
+ m = meta.get(sid)
718
+ if not m:
719
+ continue
720
+ results.append(
721
+ {
722
+ "score": round(score, 4),
723
+ "symbol_id": sid,
724
+ "name": m["name"],
725
+ "file_path": m["file_path"],
726
+ "kind": m["kind"],
727
+ "line_start": m["line_start"],
728
+ "line_end": m["line_end"],
729
+ }
730
+ )
731
+
732
+ return results