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,222 @@
1
+ """Framework gate presets for coverage-gaps policy enforcement.
2
+
3
+ Each preset defines:
4
+ - Which files must have test coverage
5
+ - What constitutes acceptable coverage (test file exists, test function count, etc.)
6
+ - Framework-specific conventions for test discovery
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field
12
+
13
+
14
+ @dataclass
15
+ class GateRule:
16
+ """A single gate rule: which files must have tests."""
17
+
18
+ name: str
19
+ description: str
20
+ # Glob patterns for files that MUST have tests
21
+ include_patterns: list[str] = field(default_factory=list)
22
+ # Glob patterns for files exempt from this rule
23
+ exclude_patterns: list[str] = field(default_factory=list)
24
+ # Minimum number of test functions expected
25
+ min_test_count: int = 1
26
+ # Severity: "error" (blocks CI) or "warning" (advisory)
27
+ severity: str = "warning"
28
+
29
+
30
+ @dataclass
31
+ class GatePreset:
32
+ """A collection of gate rules for a framework/language."""
33
+
34
+ name: str
35
+ description: str
36
+ languages: list[str] = field(default_factory=list)
37
+ rules: list[GateRule] = field(default_factory=list)
38
+ # Files that auto-detect this preset
39
+ detect_files: list[str] = field(default_factory=list)
40
+
41
+
42
+ # ---------------------------------------------------------------------------
43
+ # Built-in presets
44
+ # ---------------------------------------------------------------------------
45
+
46
+ PRESET_PYTHON = GatePreset(
47
+ name="python",
48
+ description="Python project with pytest conventions",
49
+ languages=["python"],
50
+ detect_files=["pyproject.toml", "setup.py", "setup.cfg", "tox.ini"],
51
+ rules=[
52
+ GateRule(
53
+ name="source-modules",
54
+ description="All Python source modules should have test coverage",
55
+ include_patterns=["src/**/*.py", "**/*.py"],
56
+ exclude_patterns=[
57
+ "tests/**",
58
+ "test/**",
59
+ "conftest.py",
60
+ "setup.py",
61
+ "**/migrations/**",
62
+ "**/__init__.py",
63
+ "**/conftest.py",
64
+ "docs/**",
65
+ "scripts/**",
66
+ "examples/**",
67
+ ],
68
+ min_test_count=1,
69
+ severity="warning",
70
+ ),
71
+ GateRule(
72
+ name="critical-modules",
73
+ description="Core business logic must have thorough tests",
74
+ include_patterns=["src/**/models*.py", "src/**/service*.py", "src/**/api*.py"],
75
+ exclude_patterns=["tests/**"],
76
+ min_test_count=3,
77
+ severity="error",
78
+ ),
79
+ ],
80
+ )
81
+
82
+ PRESET_JAVASCRIPT = GatePreset(
83
+ name="javascript",
84
+ description="JavaScript/TypeScript project with Jest/Vitest conventions",
85
+ languages=["javascript", "typescript"],
86
+ detect_files=["package.json", "tsconfig.json"],
87
+ rules=[
88
+ GateRule(
89
+ name="source-modules",
90
+ description="All JS/TS source modules should have test coverage",
91
+ include_patterns=["src/**/*.{js,ts,jsx,tsx}"],
92
+ exclude_patterns=[
93
+ "**/*.test.*",
94
+ "**/*.spec.*",
95
+ "**/__tests__/**",
96
+ "**/node_modules/**",
97
+ "**/*.config.*",
98
+ "**/*.d.ts",
99
+ ],
100
+ min_test_count=1,
101
+ severity="warning",
102
+ ),
103
+ ],
104
+ )
105
+
106
+ PRESET_GO = GatePreset(
107
+ name="go",
108
+ description="Go project with colocated _test.go files",
109
+ languages=["go"],
110
+ detect_files=["go.mod", "go.sum"],
111
+ rules=[
112
+ GateRule(
113
+ name="packages",
114
+ description="All Go packages should have test files",
115
+ include_patterns=["**/*.go"],
116
+ exclude_patterns=["**/*_test.go", "vendor/**", "cmd/**"],
117
+ min_test_count=1,
118
+ severity="warning",
119
+ ),
120
+ ],
121
+ )
122
+
123
+ PRESET_JAVA = GatePreset(
124
+ name="java-maven",
125
+ description="Java Maven project with JUnit conventions",
126
+ languages=["java"],
127
+ detect_files=["pom.xml", "build.gradle", "build.gradle.kts"],
128
+ rules=[
129
+ GateRule(
130
+ name="main-classes",
131
+ description="Main source classes should have test counterparts",
132
+ include_patterns=["src/main/**/*.java"],
133
+ exclude_patterns=["**/dto/**", "**/entity/**", "**/config/**"],
134
+ min_test_count=1,
135
+ severity="warning",
136
+ ),
137
+ ],
138
+ )
139
+
140
+ PRESET_RUST = GatePreset(
141
+ name="rust",
142
+ description="Rust project with inline #[test] and tests/ directory",
143
+ languages=["rust"],
144
+ detect_files=["Cargo.toml"],
145
+ rules=[
146
+ GateRule(
147
+ name="library-crates",
148
+ description="Library source files should have tests",
149
+ include_patterns=["src/**/*.rs"],
150
+ exclude_patterns=["src/main.rs", "tests/**", "benches/**"],
151
+ min_test_count=1,
152
+ severity="warning",
153
+ ),
154
+ ],
155
+ )
156
+
157
+ ALL_PRESETS = [
158
+ PRESET_PYTHON,
159
+ PRESET_JAVASCRIPT,
160
+ PRESET_GO,
161
+ PRESET_JAVA,
162
+ PRESET_RUST,
163
+ ]
164
+
165
+
166
+ def get_preset(name: str) -> GatePreset | None:
167
+ """Get a preset by name."""
168
+ for p in ALL_PRESETS:
169
+ if p.name == name:
170
+ return p
171
+ return None
172
+
173
+
174
+ def detect_preset(file_paths: list[str]) -> GatePreset | None:
175
+ """Auto-detect the best preset for a project based on its files."""
176
+ import os
177
+
178
+ basenames = {os.path.basename(f) for f in file_paths}
179
+
180
+ for preset in ALL_PRESETS:
181
+ if any(df in basenames for df in preset.detect_files):
182
+ return preset
183
+ return None
184
+
185
+
186
+ def load_gates_config(config_path: str) -> list[GateRule]:
187
+ """Load gate rules from a .roam-gates.yml file.
188
+
189
+ Expected YAML format::
190
+
191
+ rules:
192
+ - name: critical-api
193
+ description: API modules must have tests
194
+ include: ["src/api/**/*.py"]
195
+ exclude: ["**/__init__.py"]
196
+ min_tests: 3
197
+ severity: error
198
+ """
199
+ try:
200
+ import yaml
201
+ except ImportError:
202
+ return []
203
+
204
+ with open(config_path) as f:
205
+ data = yaml.safe_load(f)
206
+
207
+ if not data or "rules" not in data:
208
+ return []
209
+
210
+ rules = []
211
+ for r in data["rules"]:
212
+ rules.append(
213
+ GateRule(
214
+ name=r.get("name", "unnamed"),
215
+ description=r.get("description", ""),
216
+ include_patterns=r.get("include", []),
217
+ exclude_patterns=r.get("exclude", []),
218
+ min_test_count=r.get("min_tests", 1),
219
+ severity=r.get("severity", "warning"),
220
+ )
221
+ )
222
+ return rules
@@ -0,0 +1,93 @@
1
+ """Shared graph utilities for command modules.
2
+
3
+ Provides reusable adjacency-list builders and BFS helpers used by
4
+ cmd_coverage_gaps, cmd_entry_points, cmd_context, and cmd_safe_zones.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections import defaultdict, deque
10
+
11
+
12
+ def build_forward_adj(conn):
13
+ """Build forward adjacency list from edges table (source -> set of targets)."""
14
+ adj = defaultdict(set)
15
+ for row in conn.execute("SELECT source_id, target_id FROM edges").fetchall():
16
+ adj[row["source_id"]].add(row["target_id"])
17
+ return adj
18
+
19
+
20
+ def bfs_reachable(adj, start_ids, max_depth=None):
21
+ """BFS from *start_ids* through an adjacency dict.
22
+
23
+ Parameters
24
+ ----------
25
+ adj : dict[int, set[int]]
26
+ Adjacency list (forward or reverse).
27
+ start_ids : set[int] | list[int]
28
+ Seed node IDs.
29
+ max_depth : int | None
30
+ Maximum BFS depth. ``None`` means unlimited.
31
+
32
+ Returns
33
+ -------
34
+ set[int]
35
+ All reachable node IDs (including seeds).
36
+ """
37
+ visited = set(start_ids)
38
+ queue = deque((sid, 0) for sid in start_ids)
39
+
40
+ while queue:
41
+ current, depth = queue.popleft()
42
+ if max_depth is not None and depth >= max_depth:
43
+ continue
44
+ for neighbor in adj.get(current, ()):
45
+ if neighbor not in visited:
46
+ visited.add(neighbor)
47
+ queue.append((neighbor, depth + 1))
48
+
49
+ return visited
50
+
51
+
52
+ def bfs_nx(graph, start_ids, max_depth, direction="forward"):
53
+ """BFS traversal on a NetworkX DiGraph returning visited node IDs with depths.
54
+
55
+ Parameters
56
+ ----------
57
+ graph : nx.DiGraph
58
+ The symbol graph.
59
+ start_ids : set[int]
60
+ Seed node IDs.
61
+ max_depth : int
62
+ Maximum BFS depth.
63
+ direction : str
64
+ ``"forward"`` follows outgoing edges (callees),
65
+ ``"backward"`` follows incoming edges (callers).
66
+
67
+ Returns
68
+ -------
69
+ dict[int, int]
70
+ Mapping of visited node ID to its BFS depth.
71
+ """
72
+ visited: dict[int, int] = {}
73
+ queue: deque[tuple[int, int]] = deque()
74
+
75
+ for sid in start_ids:
76
+ if sid in graph:
77
+ visited[sid] = 0
78
+ queue.append((sid, 0))
79
+
80
+ while queue:
81
+ node, depth = queue.popleft()
82
+ if depth >= max_depth:
83
+ continue
84
+ if direction == "forward":
85
+ neighbors = graph.successors(node)
86
+ else:
87
+ neighbors = graph.predecessors(node)
88
+ for nb in neighbors:
89
+ if nb not in visited:
90
+ visited[nb] = depth + 1
91
+ queue.append((nb, depth + 1))
92
+
93
+ return visited
@@ -0,0 +1,298 @@
1
+ """Collect and persist health metrics for snapshot/trend tracking."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import subprocess
7
+ import time
8
+
9
+ from roam.db.connection import find_project_root
10
+ from roam.db.queries import TOP_BY_BETWEENNESS, TOP_BY_DEGREE, UNREFERENCED_EXPORTS
11
+
12
+
13
+ def _is_test_path(file_path):
14
+ """Check if a file is a test file (discovered by pytest, not imported)."""
15
+ base = os.path.basename(file_path).lower()
16
+ return base.startswith("test_") or base.endswith("_test.py")
17
+
18
+
19
+ def _compute_health_score(
20
+ conn,
21
+ G,
22
+ symbols,
23
+ god_items,
24
+ bn_items,
25
+ bn_p90,
26
+ layer_violations,
27
+ find_cycles_fn,
28
+ is_utility_path_fn,
29
+ ):
30
+ """Compute the weighted geometric mean health score (0-100)."""
31
+ import math
32
+
33
+ def _hf(value, scale):
34
+ return math.exp(-value / scale) if scale > 0 else 1.0
35
+
36
+ tangle_r = 0.0
37
+ if G is not None and symbols > 0:
38
+ try:
39
+ cyc_ids = set()
40
+ for scc in find_cycles_fn(G):
41
+ cyc_ids.update(scc)
42
+ tangle_r = len(cyc_ids) / symbols * 100
43
+ except Exception:
44
+ pass
45
+
46
+ god_critical = sum(
47
+ 1 for g in god_items if (g["degree"] > 150 if is_utility_path_fn(g["file"]) else g["degree"] > 50)
48
+ )
49
+ bn_critical = sum(
50
+ 1 for b in bn_items if b["betweenness"] > bn_p90 * (1.5 if is_utility_path_fn(b["file"]) else 1.0)
51
+ )
52
+
53
+ god_signal = god_critical * 3 + len(god_items) * 0.5
54
+ bn_signal = bn_critical * 2 + len(bn_items) * 0.3
55
+
56
+ factors = [
57
+ (_hf(tangle_r, 10), 0.30),
58
+ (_hf(god_signal, 5), 0.20),
59
+ (_hf(bn_signal, 4), 0.15),
60
+ (_hf(layer_violations, 5), 0.15),
61
+ ]
62
+ try:
63
+ avg_fh = conn.execute("SELECT AVG(health_score) FROM file_stats WHERE health_score IS NOT NULL").fetchone()[0]
64
+ factors.append((min(1.0, (avg_fh or 10) / 10.0), 0.20))
65
+ except Exception:
66
+ factors.append((1.0, 0.20))
67
+
68
+ log_score = sum(w * math.log(max(h, 1e-9)) for h, w in factors)
69
+ return max(0, min(100, int(100 * math.exp(log_score))))
70
+
71
+
72
+ def collect_metrics(conn):
73
+ """Query the DB for all health metrics and compute a health score.
74
+
75
+ Returns a dict with keys: files, symbols, edges, cycles,
76
+ god_components, bottlenecks, dead_exports, layer_violations,
77
+ health_score (0-100, higher = healthier).
78
+ """
79
+ files = conn.execute("SELECT COUNT(*) FROM files").fetchone()[0]
80
+ symbols = conn.execute("SELECT COUNT(*) FROM symbols").fetchone()[0]
81
+ edges = conn.execute("SELECT COUNT(*) FROM edges").fetchone()[0]
82
+ # Keep health math aligned with `roam health`.
83
+ from roam.commands.cmd_health import _is_utility_path, _percentile
84
+
85
+ # Cycles
86
+ try:
87
+ from roam.graph.builder import build_symbol_graph
88
+ from roam.graph.cycles import find_cycles
89
+
90
+ G = build_symbol_graph(conn)
91
+ cycles = len(find_cycles(G))
92
+ except Exception:
93
+ cycles = 0
94
+ G = None
95
+
96
+ # God components (same query + thresholds as cmd_health.py)
97
+ degree_rows = conn.execute(TOP_BY_DEGREE, (50,)).fetchall()
98
+ god_items = []
99
+ for r in degree_rows:
100
+ total = (r["in_degree"] or 0) + (r["out_degree"] or 0)
101
+ if total > 20:
102
+ god_items.append(
103
+ {
104
+ "degree": total,
105
+ "file": r["file_path"],
106
+ }
107
+ )
108
+ god_components = len(god_items)
109
+
110
+ # Bottlenecks (same query + thresholds as cmd_health.py)
111
+ all_bw = sorted(
112
+ r[0] for r in conn.execute("SELECT betweenness FROM graph_metrics WHERE betweenness > 0").fetchall()
113
+ )
114
+ bn_p90 = _percentile(all_bw, 90)
115
+
116
+ bw_rows = conn.execute(TOP_BY_BETWEENNESS, (15,)).fetchall()
117
+ _round = round
118
+ bn_items = [
119
+ {"betweenness": _round(r["betweenness"] or 0, 1), "file": r["file_path"]}
120
+ for r in bw_rows
121
+ if (r["betweenness"] or 0) > 0.5
122
+ ]
123
+ bottlenecks = len(bn_items)
124
+
125
+ # Dead exports (filter test files — they're discovered by pytest, not imported)
126
+ dead_rows = conn.execute(UNREFERENCED_EXPORTS).fetchall()
127
+ dead_rows = [r for r in dead_rows if not _is_test_path(r["file_path"])]
128
+ dead_exports = len(dead_rows)
129
+
130
+ # Layer violations
131
+ layer_violations = 0
132
+ if G is not None:
133
+ try:
134
+ from roam.graph.layers import detect_layers, find_violations
135
+
136
+ layer_map = detect_layers(G)
137
+ if layer_map:
138
+ layer_violations = len(find_violations(G, layer_map))
139
+ except Exception:
140
+ pass
141
+
142
+ health_score = _compute_health_score(
143
+ conn,
144
+ G,
145
+ symbols,
146
+ god_items,
147
+ bn_items,
148
+ bn_p90,
149
+ layer_violations,
150
+ find_cycles,
151
+ _is_utility_path,
152
+ )
153
+
154
+ # Tangle ratio: percentage of symbols in cycles
155
+ tangle_ratio = 0.0
156
+ if G is not None and symbols > 0:
157
+ try:
158
+ from roam.graph.cycles import find_cycles as _find_cycles
159
+
160
+ cycle_list = _find_cycles(G)
161
+ cycle_sym_ids = set()
162
+ for scc in cycle_list:
163
+ cycle_sym_ids.update(scc)
164
+ tangle_ratio = round(len(cycle_sym_ids) / symbols * 100, 1)
165
+ except Exception:
166
+ pass
167
+
168
+ # Average complexity from symbol_metrics
169
+ avg_complexity = 0.0
170
+ try:
171
+ row = conn.execute("SELECT AVG(cognitive_complexity) FROM symbol_metrics").fetchone()
172
+ if row and row[0] is not None:
173
+ avg_complexity = round(row[0], 1)
174
+ except Exception:
175
+ pass
176
+
177
+ # Brain methods (cc >= 25 AND line_count >= 50)
178
+ brain_methods = 0
179
+ try:
180
+ row = conn.execute(
181
+ "SELECT COUNT(*) FROM symbol_metrics WHERE cognitive_complexity >= 25 AND line_count >= 50"
182
+ ).fetchone()
183
+ if row:
184
+ brain_methods = row[0]
185
+ except Exception:
186
+ pass
187
+
188
+ return {
189
+ "files": files,
190
+ "symbols": symbols,
191
+ "edges": edges,
192
+ "cycles": cycles,
193
+ "god_components": god_components,
194
+ "bottlenecks": bottlenecks,
195
+ "dead_exports": dead_exports,
196
+ "layer_violations": layer_violations,
197
+ "health_score": health_score,
198
+ "tangle_ratio": tangle_ratio,
199
+ "avg_complexity": avg_complexity,
200
+ "brain_methods": brain_methods,
201
+ }
202
+
203
+
204
+ def _git_info(root):
205
+ """Get current git branch and commit hash."""
206
+ branch = None
207
+ commit = None
208
+ try:
209
+ r = subprocess.run(
210
+ ["git", "rev-parse", "--abbrev-ref", "HEAD"],
211
+ cwd=str(root),
212
+ capture_output=True,
213
+ text=True,
214
+ timeout=5,
215
+ )
216
+ if r.returncode == 0:
217
+ branch = r.stdout.strip()
218
+ except Exception:
219
+ pass
220
+ try:
221
+ r = subprocess.run(
222
+ ["git", "rev-parse", "--short", "HEAD"],
223
+ cwd=str(root),
224
+ capture_output=True,
225
+ text=True,
226
+ timeout=5,
227
+ )
228
+ if r.returncode == 0:
229
+ commit = r.stdout.strip()
230
+ except Exception:
231
+ pass
232
+ return branch, commit
233
+
234
+
235
+ def append_snapshot(conn, tag=None, source="snapshot"):
236
+ """Insert a new snapshot row with current metrics and git info.
237
+
238
+ Returns the snapshot dict that was inserted.
239
+ """
240
+ root = find_project_root()
241
+ metrics = collect_metrics(conn)
242
+ branch, commit = _git_info(root)
243
+
244
+ conn.execute(
245
+ """INSERT INTO snapshots
246
+ (timestamp, tag, source, git_branch, git_commit,
247
+ files, symbols, edges, cycles, god_components,
248
+ bottlenecks, dead_exports, layer_violations, health_score,
249
+ tangle_ratio, avg_complexity, brain_methods)
250
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
251
+ (
252
+ int(time.time()),
253
+ tag,
254
+ source,
255
+ branch,
256
+ commit,
257
+ metrics["files"],
258
+ metrics["symbols"],
259
+ metrics["edges"],
260
+ metrics["cycles"],
261
+ metrics["god_components"],
262
+ metrics["bottlenecks"],
263
+ metrics["dead_exports"],
264
+ metrics["layer_violations"],
265
+ metrics["health_score"],
266
+ metrics.get("tangle_ratio", 0),
267
+ metrics.get("avg_complexity", 0),
268
+ metrics.get("brain_methods", 0),
269
+ ),
270
+ )
271
+ conn.commit()
272
+
273
+ return {
274
+ "tag": tag,
275
+ "source": source,
276
+ "git_branch": branch,
277
+ "git_commit": commit,
278
+ **metrics,
279
+ }
280
+
281
+
282
+ def get_snapshots(conn, limit=None, since=None):
283
+ """Fetch snapshot history, newest first.
284
+
285
+ Args:
286
+ limit: Max rows to return.
287
+ since: Unix timestamp — only return snapshots after this time.
288
+ """
289
+ sql = "SELECT * FROM snapshots"
290
+ params = []
291
+ if since is not None:
292
+ sql += " WHERE timestamp >= ?"
293
+ params.append(since)
294
+ sql += " ORDER BY timestamp DESC"
295
+ if limit is not None:
296
+ sql += " LIMIT ?"
297
+ params.append(limit)
298
+ return conn.execute(sql, params).fetchall()