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
roam/api.py ADDED
@@ -0,0 +1,238 @@
1
+ """Programmatic Python API for running roam in-process.
2
+
3
+ This provides a clean embedding surface for agent frameworks and tools
4
+ that want structured roam output without shelling out to subprocesses.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ from contextlib import contextmanager
12
+ from pathlib import Path
13
+ from typing import Iterator
14
+
15
+ from click.testing import CliRunner
16
+
17
+ from roam.db.connection import find_project_root, open_db
18
+ from roam.exit_codes import EXIT_GATE_FAILURE
19
+
20
+
21
+ class RoamAPIError(RuntimeError):
22
+ """Raised when a programmatic roam invocation fails."""
23
+
24
+ def __init__(
25
+ self,
26
+ message: str,
27
+ *,
28
+ command: list[str] | None = None,
29
+ exit_code: int | None = None,
30
+ output: str | None = None,
31
+ payload: dict | None = None,
32
+ ) -> None:
33
+ super().__init__(message)
34
+ self.command = command or []
35
+ self.exit_code = exit_code
36
+ self.output = output
37
+ self.payload = payload or {}
38
+
39
+
40
+ def _cwd_scope(path: Path | None):
41
+ """Context manager for temporary cwd changes."""
42
+ if path is None:
43
+
44
+ @contextmanager
45
+ def _noop():
46
+ yield
47
+
48
+ return _noop()
49
+
50
+ @contextmanager
51
+ def _chdir():
52
+ old = Path.cwd()
53
+ os.chdir(path)
54
+ try:
55
+ yield
56
+ finally:
57
+ os.chdir(old)
58
+
59
+ return _chdir()
60
+
61
+
62
+ def _normalise_project_root(project_root: str | Path | None) -> Path | None:
63
+ if project_root is None:
64
+ return None
65
+ return Path(project_root).resolve()
66
+
67
+
68
+ def _extract_json_dict(text: str) -> tuple[dict | None, Exception | None]:
69
+ """Parse the first JSON object found in possibly mixed command output."""
70
+ if not text:
71
+ return None, None
72
+
73
+ decoder = json.JSONDecoder()
74
+ starts = [i for i, ch in enumerate(text) if ch == "{"]
75
+ last_err: Exception | None = None
76
+
77
+ for start in starts:
78
+ snippet = text[start:].lstrip()
79
+ if not snippet:
80
+ continue
81
+ try:
82
+ obj, _ = decoder.raw_decode(snippet)
83
+ if isinstance(obj, dict):
84
+ return obj, None
85
+ except Exception as exc:
86
+ last_err = exc
87
+ continue
88
+
89
+ return None, last_err
90
+
91
+
92
+ def run_json(
93
+ command: str,
94
+ *args: str,
95
+ project_root: str | Path | None = None,
96
+ allow_gate_failure: bool = True,
97
+ budget: int | None = None,
98
+ detail: bool = False,
99
+ compact: bool = False,
100
+ agent: bool = False,
101
+ sarif: bool = False,
102
+ include_excluded: bool = False,
103
+ ) -> dict:
104
+ """Run a roam command in-process and return parsed JSON output.
105
+
106
+ Parameters
107
+ ----------
108
+ command:
109
+ CLI command name (e.g. ``"health"``, ``"metrics"``).
110
+ *args:
111
+ Command-specific arguments.
112
+ project_root:
113
+ Working directory for command execution.
114
+ allow_gate_failure:
115
+ When True, exit code 5 returns parsed JSON with ``gate_failure=True``.
116
+ When False, gate failures raise :class:`RoamAPIError`.
117
+ """
118
+ from roam.cli import cli
119
+
120
+ cmd: list[str] = []
121
+ if compact:
122
+ cmd.append("--compact")
123
+ if agent:
124
+ cmd.append("--agent")
125
+ if budget is not None and budget > 0:
126
+ cmd.extend(["--budget", str(budget)])
127
+ if detail:
128
+ cmd.append("--detail")
129
+ if sarif:
130
+ cmd.append("--sarif")
131
+ if include_excluded:
132
+ cmd.append("--include-excluded")
133
+ cmd.append("--json")
134
+ cmd.append(command)
135
+ cmd.extend(str(a) for a in args)
136
+
137
+ root = _normalise_project_root(project_root)
138
+ runner = CliRunner()
139
+
140
+ with _cwd_scope(root):
141
+ result = runner.invoke(cli, cmd, catch_exceptions=True)
142
+
143
+ raw_output = (result.output or "").strip()
144
+ parsed, parse_error = _extract_json_dict(raw_output)
145
+
146
+ if result.exit_code == 0:
147
+ if parsed is None:
148
+ raise RoamAPIError(
149
+ "Expected JSON output but command returned non-JSON text",
150
+ command=cmd,
151
+ exit_code=result.exit_code,
152
+ output=raw_output,
153
+ )
154
+ return parsed
155
+
156
+ if result.exit_code == EXIT_GATE_FAILURE and allow_gate_failure and parsed is not None:
157
+ parsed.setdefault("gate_failure", True)
158
+ parsed.setdefault("exit_code", EXIT_GATE_FAILURE)
159
+ return parsed
160
+
161
+ if parsed is not None:
162
+ raise RoamAPIError(
163
+ "Roam command failed",
164
+ command=cmd,
165
+ exit_code=result.exit_code,
166
+ output=raw_output,
167
+ payload=parsed,
168
+ )
169
+
170
+ if parse_error is not None:
171
+ raise RoamAPIError(
172
+ f"Roam command failed and output was not valid JSON: {parse_error}",
173
+ command=cmd,
174
+ exit_code=result.exit_code,
175
+ output=raw_output,
176
+ )
177
+
178
+ raise RoamAPIError(
179
+ "Roam command failed with empty output",
180
+ command=cmd,
181
+ exit_code=result.exit_code,
182
+ output=raw_output,
183
+ )
184
+
185
+
186
+ class RoamClient:
187
+ """Reusable client for programmatic in-process roam calls."""
188
+
189
+ def __init__(self, project_root: str | Path | None = None) -> None:
190
+ self.project_root = Path(project_root).resolve() if project_root is not None else find_project_root()
191
+
192
+ def run(self, command: str, *args: str, **kwargs) -> dict:
193
+ kwargs.setdefault("project_root", self.project_root)
194
+ return run_json(command, *args, **kwargs)
195
+
196
+ def index(
197
+ self,
198
+ *,
199
+ force: bool = False,
200
+ verbose: bool = False,
201
+ quiet: bool = True,
202
+ include_excluded: bool = False,
203
+ ) -> dict:
204
+ args: list[str] = []
205
+ if force:
206
+ args.append("--force")
207
+ if verbose:
208
+ args.append("--verbose")
209
+ if quiet:
210
+ args.append("--quiet")
211
+ return self.run("index", *args, include_excluded=include_excluded)
212
+
213
+ def health(
214
+ self,
215
+ *,
216
+ detail: bool = False,
217
+ gate: bool = False,
218
+ allow_gate_failure: bool = True,
219
+ ) -> dict:
220
+ args: list[str] = ["--gate"] if gate else []
221
+ return self.run(
222
+ "health",
223
+ *args,
224
+ detail=detail,
225
+ allow_gate_failure=allow_gate_failure,
226
+ )
227
+
228
+ def context(self, symbol: str, *, depth: int = 2) -> dict:
229
+ return self.run("context", symbol, "--depth", str(depth))
230
+
231
+ def metrics(self, target: str) -> dict:
232
+ return self.run("metrics", target)
233
+
234
+ @contextmanager
235
+ def db(self, *, readonly: bool = True) -> Iterator:
236
+ """Open a DB connection scoped to this client project root."""
237
+ with open_db(readonly=readonly, project_root=self.project_root) as conn:
238
+ yield conn
@@ -0,0 +1,3 @@
1
+ """Cross-language bridge framework for symbol resolution."""
2
+
3
+ from __future__ import annotations
roam/bridges/base.py ADDED
@@ -0,0 +1,49 @@
1
+ """Abstract base class for cross-language bridges."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+
7
+
8
+ class LanguageBridge(ABC):
9
+ """Base class for cross-language symbol resolution bridges.
10
+
11
+ A bridge resolves symbols that cross language boundaries:
12
+ - Protobuf .proto -> generated Go/Java/Python stubs
13
+ - Salesforce Apex -> Aura/LWC/Visualforce
14
+ - GraphQL schema -> TypeScript/Python codegen
15
+ - OpenAPI spec -> client SDKs
16
+ """
17
+
18
+ @property
19
+ @abstractmethod
20
+ def name(self) -> str:
21
+ """Short identifier for this bridge (e.g. 'protobuf', 'salesforce')."""
22
+
23
+ @property
24
+ @abstractmethod
25
+ def source_extensions(self) -> frozenset[str]:
26
+ """File extensions this bridge reads from (e.g. frozenset({'.proto'}))."""
27
+
28
+ @property
29
+ @abstractmethod
30
+ def target_extensions(self) -> frozenset[str]:
31
+ """File extensions this bridge generates/links to."""
32
+
33
+ @abstractmethod
34
+ def detect(self, file_paths: list[str]) -> bool:
35
+ """Return True if this bridge is relevant for the given file set."""
36
+
37
+ @abstractmethod
38
+ def resolve(self, source_path: str, source_symbols: list[dict], target_files: dict[str, list[dict]]) -> list[dict]:
39
+ """Resolve cross-language symbol links.
40
+
41
+ Args:
42
+ source_path: Path of the source file (e.g. foo.proto)
43
+ source_symbols: Symbols extracted from source_path
44
+ target_files: {path: [symbols]} for candidate target files
45
+
46
+ Returns:
47
+ List of edge dicts: [{"source": qualified_name, "target": qualified_name,
48
+ "kind": "x-lang", "bridge": self.name}]
49
+ """
@@ -0,0 +1,218 @@
1
+ """Config string cross-language bridge: config files <-> code config reads.
2
+
3
+ Resolves cross-references between:
4
+ - Environment variable definitions in .env files and code that reads them
5
+ - YAML/JSON/TOML/INI config key definitions and code config lookups
6
+ - Settings objects (Django settings.X, process.env.X) and their definitions
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import re
13
+
14
+ from roam.bridges.base import LanguageBridge
15
+ from roam.bridges.registry import register_bridge
16
+
17
+ # Config file extensions
18
+ _CONFIG_EXTS = frozenset({".env", ".yml", ".yaml", ".json", ".toml", ".ini", ".cfg", ".conf"})
19
+
20
+ # Code file extensions that read config
21
+ _CODE_EXTS = frozenset({".py", ".js", ".ts", ".jsx", ".tsx", ".go", ".java", ".rb"})
22
+
23
+ # --- Config key extraction patterns ---
24
+
25
+ # .env file: KEY=value
26
+ _ENV_KEY_RE = re.compile(r"^([A-Z_][A-Z0-9_]*)\s*=", re.MULTILINE)
27
+
28
+ # YAML top-level keys: key: value (indentation 0)
29
+ _YAML_KEY_RE = re.compile(r"^([a-zA-Z_]\w*)\s*:", re.MULTILINE)
30
+
31
+ # --- Code config read patterns ---
32
+
33
+ # Python: os.environ.get('KEY'), os.environ['KEY'], os.getenv('KEY')
34
+ _PY_ENV_RE = re.compile(
35
+ r"""os\s*\.\s*(?:environ\s*\.\s*get|environ\s*\[|getenv)\s*\(\s*['"]([\w]+)['"]""",
36
+ )
37
+
38
+ # Python: config['key'], config.get('key'), settings.KEY
39
+ _PY_CONFIG_RE = re.compile(
40
+ r"""(?:config|settings|conf|cfg)\s*(?:\[['"](\w+)['"]\]|\.get\s*\(\s*['"](\w+)['"]|\.(\w+))""",
41
+ re.IGNORECASE,
42
+ )
43
+
44
+ # JS/TS: process.env.KEY, process.env['KEY']
45
+ _JS_ENV_RE = re.compile(
46
+ r"""process\s*\.\s*env\s*(?:\.(\w+)|\[\s*['"](\w+)['"]\s*\])""",
47
+ )
48
+
49
+ # JS/TS: config.get('key'), config.key, config['key']
50
+ _JS_CONFIG_RE = re.compile(
51
+ r"""config\s*(?:\.get\s*\(\s*['"](\w[\w.]+)['"]|\.(\w+)|\[\s*['"](\w+)['"]\s*\])""",
52
+ re.IGNORECASE,
53
+ )
54
+
55
+ # Go: os.Getenv("KEY"), viper.GetString("key")
56
+ _GO_ENV_RE = re.compile(
57
+ r"""(?:os\.Getenv|viper\.Get\w*)\s*\(\s*["'](\w+)["']""",
58
+ )
59
+
60
+ # Java: System.getenv("KEY"), System.getProperty("key")
61
+ _JAVA_ENV_RE = re.compile(
62
+ r"""System\s*\.\s*(?:getenv|getProperty)\s*\(\s*["'](\w+)["']""",
63
+ )
64
+
65
+
66
+ class ConfigBridge(LanguageBridge):
67
+ """Bridge between config files and code that reads configuration."""
68
+
69
+ @property
70
+ def name(self) -> str:
71
+ return "config"
72
+
73
+ @property
74
+ def source_extensions(self) -> frozenset[str]:
75
+ return _CONFIG_EXTS
76
+
77
+ @property
78
+ def target_extensions(self) -> frozenset[str]:
79
+ return _CODE_EXTS
80
+
81
+ def detect(self, file_paths: list[str]) -> bool:
82
+ """Detect if project has config files."""
83
+ for fp in file_paths:
84
+ ext = os.path.splitext(fp)[1].lower()
85
+ basename = os.path.basename(fp).lower()
86
+ if ext in _CONFIG_EXTS or basename == ".env":
87
+ return True
88
+ return False
89
+
90
+ def resolve(self, source_path: str, source_symbols: list[dict], target_files: dict[str, list[dict]]) -> list[dict]:
91
+ """Resolve config key definitions to code that reads them.
92
+
93
+ Strategies:
94
+ 1. Environment variable matching: .env KEY=val -> os.environ.get('KEY')
95
+ 2. Config key matching: YAML key -> config['key'] or config.key
96
+ """
97
+ edges: list[dict] = []
98
+ source_ext = os.path.splitext(source_path)[1].lower()
99
+ source_basename = os.path.basename(source_path).lower()
100
+
101
+ if source_ext not in _CONFIG_EXTS and source_basename != ".env":
102
+ return edges
103
+
104
+ # Extract config keys from source
105
+ config_keys = self._extract_config_keys(source_symbols, source_ext, source_basename)
106
+
107
+ if not config_keys:
108
+ return edges
109
+
110
+ source_file_label = os.path.basename(source_path)
111
+
112
+ # Scan code files for config reads
113
+ for tpath, tsymbols in target_files.items():
114
+ text_ext = os.path.splitext(tpath)[1].lower()
115
+ if text_ext not in _CODE_EXTS:
116
+ continue
117
+
118
+ code_keys = self._extract_code_config_reads(tsymbols, text_ext)
119
+
120
+ # Match keys
121
+ for config_key in config_keys:
122
+ for code_key, sym_qname in code_keys:
123
+ if self._keys_match(config_key, code_key):
124
+ edges.append(
125
+ {
126
+ "source": f"{source_file_label}:{config_key}",
127
+ "target": sym_qname,
128
+ "kind": "x-lang",
129
+ "bridge": self.name,
130
+ "mechanism": "config-read",
131
+ "key": config_key,
132
+ "confidence": 0.85,
133
+ }
134
+ )
135
+
136
+ return edges
137
+
138
+ def _extract_config_keys(self, symbols: list[dict], ext: str, basename: str) -> set[str]:
139
+ """Extract configuration key names from config file symbols."""
140
+ keys: set[str] = set()
141
+ for sym in symbols:
142
+ name = sym.get("name", "")
143
+ sig = sym.get("signature", "") or ""
144
+ doc = sym.get("docstring", "") or ""
145
+ text = f"{name} {sig} {doc}"
146
+
147
+ if basename == ".env" or ext == ".env":
148
+ keys.update(m.group(1) for m in _ENV_KEY_RE.finditer(text))
149
+ if ext in (".yml", ".yaml"):
150
+ keys.update(m.group(1) for m in _YAML_KEY_RE.finditer(text))
151
+
152
+ # Also treat symbol names themselves as config keys
153
+ # (the indexer extracts top-level keys as symbols in YAML/JSON)
154
+ if name and not name.startswith("_"):
155
+ keys.add(name)
156
+
157
+ return keys
158
+
159
+ def _extract_code_config_reads(self, symbols: list[dict], ext: str) -> list[tuple[str, str]]:
160
+ """Extract config key reads from code symbols.
161
+
162
+ Returns list of (key_name, symbol_qualified_name).
163
+ """
164
+ results: list[tuple[str, str]] = []
165
+ for sym in symbols:
166
+ qname = sym.get("qualified_name", sym.get("name", ""))
167
+ sig = sym.get("signature", "") or ""
168
+ doc = sym.get("docstring", "") or ""
169
+ text = f"{sig} {doc}"
170
+
171
+ keys_found: list[str] = []
172
+
173
+ if ext == ".py":
174
+ keys_found.extend(m.group(1) for m in _PY_ENV_RE.finditer(text))
175
+ for m in _PY_CONFIG_RE.finditer(text):
176
+ # Groups: [1] bracket, [2] .get(), [3] dotattr
177
+ key = m.group(1) or m.group(2) or m.group(3)
178
+ if key:
179
+ keys_found.append(key)
180
+ elif ext in (".js", ".ts", ".jsx", ".tsx"):
181
+ for m in _JS_ENV_RE.finditer(text):
182
+ key = m.group(1) or m.group(2)
183
+ if key:
184
+ keys_found.append(key)
185
+ for m in _JS_CONFIG_RE.finditer(text):
186
+ key = m.group(1) or m.group(2) or m.group(3)
187
+ if key:
188
+ keys_found.append(key)
189
+ elif ext == ".go":
190
+ keys_found.extend(m.group(1) for m in _GO_ENV_RE.finditer(text))
191
+ elif ext == ".java":
192
+ keys_found.extend(m.group(1) for m in _JAVA_ENV_RE.finditer(text))
193
+
194
+ for key in keys_found:
195
+ results.append((key, qname))
196
+
197
+ return results
198
+
199
+ def _keys_match(self, config_key: str, code_key: str) -> bool:
200
+ """Check if a config file key matches a code config read.
201
+
202
+ Supports:
203
+ - Exact match: DATABASE_URL == DATABASE_URL
204
+ - Case-insensitive match: database_url == DATABASE_URL
205
+ - Dotted path match: database.host matches database
206
+ """
207
+ if config_key == code_key:
208
+ return True
209
+ if config_key.lower() == code_key.lower():
210
+ return True
211
+ # Dotted path: config_key might be a prefix
212
+ if "." in code_key and code_key.split(".")[0].lower() == config_key.lower():
213
+ return True
214
+ return False
215
+
216
+
217
+ # Auto-register on import
218
+ register_bridge(ConfigBridge())