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,697 @@
1
+ """Auto-detect implicit codebase conventions and patterns."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections import Counter, defaultdict
7
+
8
+ import click
9
+
10
+ from roam.commands.resolve import ensure_index
11
+ from roam.db.connection import find_project_root, open_db
12
+ from roam.output.formatter import (
13
+ abbrev_kind,
14
+ format_table,
15
+ json_envelope,
16
+ loc,
17
+ to_json,
18
+ )
19
+
20
+ # ---------------------------------------------------------------------------
21
+ # Case-style detection
22
+ # ---------------------------------------------------------------------------
23
+
24
+ _CASE_PATTERNS = {
25
+ "snake_case": re.compile(r"^[a-z][a-z0-9]*(_[a-z0-9]+)+$"),
26
+ "camelCase": re.compile(r"^[a-z][a-zA-Z0-9]*[A-Z][a-zA-Z0-9]*$"),
27
+ "PascalCase": re.compile(r"^[A-Z][a-zA-Z0-9]*[a-z][a-zA-Z0-9]*$"),
28
+ "UPPER_SNAKE": re.compile(r"^[A-Z][A-Z0-9]*(_[A-Z0-9]+)+$"),
29
+ "kebab-case": re.compile(r"^[a-z][a-z0-9]*(-[a-z0-9]+)+$"),
30
+ }
31
+
32
+ # Single-word names match multiple conventions; classify them separately.
33
+ _SINGLE_LOWER = re.compile(r"^[a-z][a-z0-9]*$")
34
+ _SINGLE_UPPER = re.compile(r"^[A-Z][A-Z0-9]*$")
35
+ _SINGLE_PASCAL = re.compile(r"^[A-Z][a-z0-9]+$")
36
+
37
+ # Names that are too short or generic to classify meaningfully.
38
+ _MIN_NAME_LEN = 2
39
+
40
+ # Dunder / framework names to skip when detecting naming conventions.
41
+ _SKIP_NAMES = frozenset(
42
+ {
43
+ "__init__",
44
+ "__str__",
45
+ "__repr__",
46
+ "__new__",
47
+ "__del__",
48
+ "__enter__",
49
+ "__exit__",
50
+ "__getattr__",
51
+ "__setattr__",
52
+ "__getitem__",
53
+ "__setitem__",
54
+ "__len__",
55
+ "__iter__",
56
+ "__next__",
57
+ "__call__",
58
+ "__hash__",
59
+ "__eq__",
60
+ "__lt__",
61
+ "__gt__",
62
+ "__le__",
63
+ "__ge__",
64
+ "__ne__",
65
+ "__bool__",
66
+ "__contains__",
67
+ "__add__",
68
+ "__sub__",
69
+ "__mul__",
70
+ "__truediv__",
71
+ "__floordiv__",
72
+ "__mod__",
73
+ "__pow__",
74
+ "__and__",
75
+ "__or__",
76
+ "__xor__",
77
+ "__invert__",
78
+ "constructor",
79
+ "toString",
80
+ "valueOf",
81
+ }
82
+ )
83
+
84
+
85
+ def classify_case(name: str) -> str | None:
86
+ """Return the case style of *name*, or None if unclassifiable."""
87
+ if len(name) < _MIN_NAME_LEN or name in _SKIP_NAMES:
88
+ return None
89
+ if name.startswith("__") and name.endswith("__"):
90
+ return None # dunder
91
+
92
+ for style, pattern in _CASE_PATTERNS.items():
93
+ if pattern.match(name):
94
+ return style
95
+
96
+ # Single-word heuristics
97
+ if _SINGLE_PASCAL.match(name):
98
+ return "PascalCase"
99
+ if _SINGLE_LOWER.match(name):
100
+ return "snake_case" # single lowercase word is compatible with snake
101
+ if _SINGLE_UPPER.match(name):
102
+ return "UPPER_SNAKE"
103
+
104
+ return None
105
+
106
+
107
+ # Kind groupings for naming analysis
108
+ _KIND_GROUPS = {
109
+ "function": "functions",
110
+ "method": "functions",
111
+ "class": "classes",
112
+ "interface": "classes",
113
+ "struct": "classes",
114
+ "trait": "classes",
115
+ "enum": "classes",
116
+ "variable": "variables",
117
+ "constant": "constants",
118
+ "property": "variables",
119
+ "field": "variables",
120
+ }
121
+
122
+
123
+ def _group_for_kind(kind: str) -> str:
124
+ return _KIND_GROUPS.get(kind, "other")
125
+
126
+
127
+ # ---------------------------------------------------------------------------
128
+ # Prefix / suffix detection
129
+ # ---------------------------------------------------------------------------
130
+
131
+
132
+ def _detect_affixes(names: list[str], min_count: int = 5, min_ratio: float = 0.03) -> dict:
133
+ """Detect common prefixes and suffixes from a list of names."""
134
+ prefix_counter: Counter = Counter()
135
+ suffix_counter: Counter = Counter()
136
+
137
+ for name in names:
138
+ # Prefixes: split on _ or case boundary
139
+ parts = re.split(r"[_]", name)
140
+ if len(parts) >= 2 and len(parts[0]) >= 2:
141
+ prefix_counter[parts[0] + "_"] += 1
142
+ # Check camelCase prefix (lowercase start up to first uppercase)
143
+ m = re.match(r"^([a-z]+)[A-Z]", name)
144
+ if m and len(m.group(1)) >= 2:
145
+ prefix_counter[m.group(1)] += 1
146
+
147
+ # Suffixes
148
+ if len(parts) >= 2 and len(parts[-1]) >= 2:
149
+ suffix_counter["_" + parts[-1]] += 1
150
+ # PascalCase suffix: last uppercase word
151
+ m = re.search(r"[a-z]([A-Z][a-z]+)$", name)
152
+ if m and len(m.group(1)) >= 3:
153
+ suffix_counter[m.group(1)] += 1
154
+
155
+ total = max(len(names), 1)
156
+ threshold = max(min_count, int(total * min_ratio))
157
+
158
+ prefixes = [
159
+ {"affix": p, "count": c, "percent": round(100 * c / total, 1)}
160
+ for p, c in prefix_counter.most_common(10)
161
+ if c >= threshold
162
+ ]
163
+ suffixes = [
164
+ {"affix": s, "count": c, "percent": round(100 * c / total, 1)}
165
+ for s, c in suffix_counter.most_common(10)
166
+ if c >= threshold
167
+ ]
168
+ return {"prefixes": prefixes, "suffixes": suffixes}
169
+
170
+
171
+ # ---------------------------------------------------------------------------
172
+ # File organization detection
173
+ # ---------------------------------------------------------------------------
174
+
175
+ _TEST_PATTERNS = [
176
+ ("test_*.py", re.compile(r"(^|/)test_[^/]+\.py$")),
177
+ ("*_test.py", re.compile(r"(^|/)[^/]+_test\.py$")),
178
+ ("*.test.ts", re.compile(r"(^|/)[^/]+\.test\.ts$")),
179
+ ("*.test.tsx", re.compile(r"(^|/)[^/]+\.test\.tsx$")),
180
+ ("*.test.js", re.compile(r"(^|/)[^/]+\.test\.js$")),
181
+ ("*.test.jsx", re.compile(r"(^|/)[^/]+\.test\.jsx$")),
182
+ ("*.spec.ts", re.compile(r"(^|/)[^/]+\.spec\.ts$")),
183
+ ("*.spec.tsx", re.compile(r"(^|/)[^/]+\.spec\.tsx$")),
184
+ ("*.spec.js", re.compile(r"(^|/)[^/]+\.spec\.js$")),
185
+ ("*.spec.jsx", re.compile(r"(^|/)[^/]+\.spec\.jsx$")),
186
+ ("*_test.go", re.compile(r"(^|/)[^/]+_test\.go$")),
187
+ ("*_test.rs", re.compile(r"(^|/)[^/]+_test\.rs$")),
188
+ ("Test*.java", re.compile(r"(^|/)Test[^/]+\.java$")),
189
+ ("*Test.java", re.compile(r"(^|/)[^/]+Test\.java$")),
190
+ ]
191
+
192
+ _BARREL_NAMES = frozenset(
193
+ {
194
+ "index.ts",
195
+ "index.js",
196
+ "index.tsx",
197
+ "index.jsx",
198
+ "index.mjs",
199
+ "index.cjs",
200
+ "__init__.py",
201
+ }
202
+ )
203
+
204
+
205
+ def _analyze_files(paths: list[str]) -> dict:
206
+ """Analyze file paths for directory structure and test conventions."""
207
+ normalized = [p.replace("\\", "/") for p in paths]
208
+
209
+ # Top-level directory counts
210
+ dir_counts: Counter = Counter()
211
+ for p in normalized:
212
+ parts = p.split("/")
213
+ if len(parts) > 1:
214
+ dir_counts[parts[0] + "/"] += 1
215
+
216
+ top_dirs = [{"dir": d, "count": c} for d, c in dir_counts.most_common(15) if c >= 2]
217
+
218
+ # Test file patterns
219
+ test_pattern_counts: Counter = Counter()
220
+ test_dir_counts: Counter = Counter()
221
+ total_test_files = 0
222
+
223
+ for p in normalized:
224
+ for pattern_name, regex in _TEST_PATTERNS:
225
+ if regex.search(p):
226
+ test_pattern_counts[pattern_name] += 1
227
+ total_test_files += 1
228
+ # Track which directories contain tests
229
+ parts = p.split("/")
230
+ if len(parts) > 1:
231
+ test_dir_counts[parts[0] + "/"] += 1
232
+ break
233
+
234
+ test_patterns = [{"pattern": pat, "count": c} for pat, c in test_pattern_counts.most_common(5) if c >= 1]
235
+
236
+ test_dirs = [{"dir": d, "count": c} for d, c in test_dir_counts.most_common(5) if c >= 1]
237
+
238
+ # Barrel files
239
+ barrel_count = 0
240
+ for p in normalized:
241
+ basename = p.rsplit("/", 1)[-1] if "/" in p else p
242
+ if basename in _BARREL_NAMES:
243
+ barrel_count += 1
244
+
245
+ return {
246
+ "total_files": len(paths),
247
+ "top_dirs": top_dirs,
248
+ "test_patterns": test_patterns,
249
+ "test_dirs": test_dirs,
250
+ "test_file_count": total_test_files,
251
+ "barrel_files": barrel_count,
252
+ "has_barrels": barrel_count > 0,
253
+ }
254
+
255
+
256
+ # ---------------------------------------------------------------------------
257
+ # Import pattern detection
258
+ # ---------------------------------------------------------------------------
259
+
260
+
261
+ def _analyze_imports(conn) -> dict:
262
+ """Analyze import edges for absolute vs relative and grouping patterns."""
263
+ # Get edges with kind='imports' joining file paths
264
+ rows = conn.execute("""
265
+ SELECT fe.source_file_id, fe.target_file_id, fe.symbol_count,
266
+ sf.path as source_path, tf.path as target_path
267
+ FROM file_edges fe
268
+ JOIN files sf ON fe.source_file_id = sf.id
269
+ JOIN files tf ON fe.target_file_id = tf.id
270
+ WHERE fe.kind = 'imports'
271
+ """).fetchall()
272
+
273
+ if not rows:
274
+ return {
275
+ "total_import_edges": 0,
276
+ "absolute_imports": 0,
277
+ "relative_imports": 0,
278
+ "absolute_pct": 0,
279
+ "style": "unknown",
280
+ }
281
+
282
+ total = len(rows)
283
+ relative = 0
284
+ absolute = 0
285
+
286
+ for r in rows:
287
+ src = r["source_path"].replace("\\", "/")
288
+ tgt = r["target_path"].replace("\\", "/")
289
+
290
+ # Heuristic: if source and target share a common prefix directory,
291
+ # and the target is within 2 levels, it's likely a relative import.
292
+ src_parts = src.rsplit("/", 1)
293
+ tgt_parts = tgt.rsplit("/", 1)
294
+
295
+ src_dir = src_parts[0] if len(src_parts) > 1 else ""
296
+ tgt_dir = tgt_parts[0] if len(tgt_parts) > 1 else ""
297
+
298
+ if (
299
+ src_dir
300
+ and tgt_dir
301
+ and (src_dir == tgt_dir or src_dir.startswith(tgt_dir + "/") or tgt_dir.startswith(src_dir + "/"))
302
+ ):
303
+ relative += 1
304
+ else:
305
+ absolute += 1
306
+
307
+ abs_pct = round(100 * absolute / total, 1) if total else 0
308
+ style = "absolute" if abs_pct >= 60 else "relative" if abs_pct <= 40 else "mixed"
309
+
310
+ return {
311
+ "total_import_edges": total,
312
+ "absolute_imports": absolute,
313
+ "relative_imports": relative,
314
+ "absolute_pct": abs_pct,
315
+ "relative_pct": round(100 * relative / total, 1) if total else 0,
316
+ "style": style,
317
+ }
318
+
319
+
320
+ # ---------------------------------------------------------------------------
321
+ # Export pattern detection
322
+ # ---------------------------------------------------------------------------
323
+
324
+
325
+ def _analyze_exports(conn) -> dict:
326
+ """Analyze is_exported flag distribution across symbols."""
327
+ row = conn.execute("""
328
+ SELECT
329
+ COUNT(*) as total,
330
+ SUM(CASE WHEN is_exported = 1 THEN 1 ELSE 0 END) as exported,
331
+ SUM(CASE WHEN is_exported = 0 THEN 1 ELSE 0 END) as private
332
+ FROM symbols
333
+ WHERE kind IN ('function', 'class', 'method', 'variable', 'constant',
334
+ 'interface', 'struct', 'enum', 'type_alias')
335
+ """).fetchone()
336
+
337
+ total = row["total"] or 0
338
+ exported = row["exported"] or 0
339
+ private = row["private"] or 0
340
+ exported_pct = round(100 * exported / total, 1) if total else 0
341
+
342
+ # Per-kind breakdown
343
+ kind_rows = conn.execute("""
344
+ SELECT kind,
345
+ COUNT(*) as total,
346
+ SUM(CASE WHEN is_exported = 1 THEN 1 ELSE 0 END) as exported
347
+ FROM symbols
348
+ WHERE kind IN ('function', 'class', 'method', 'variable', 'constant',
349
+ 'interface', 'struct', 'enum', 'type_alias')
350
+ GROUP BY kind
351
+ ORDER BY total DESC
352
+ """).fetchall()
353
+
354
+ by_kind = []
355
+ for kr in kind_rows:
356
+ kt = kr["total"] or 0
357
+ ke = kr["exported"] or 0
358
+ by_kind.append(
359
+ {
360
+ "kind": kr["kind"],
361
+ "total": kt,
362
+ "exported": ke,
363
+ "exported_pct": round(100 * ke / kt, 1) if kt else 0,
364
+ }
365
+ )
366
+
367
+ # Detect default-export vs named-export preference for JS/TS
368
+ # Check if files have exactly one exported symbol (likely default export)
369
+ default_style_rows = conn.execute("""
370
+ SELECT f.id, f.path, COUNT(*) as exported_count
371
+ FROM symbols s
372
+ JOIN files f ON s.file_id = f.id
373
+ WHERE s.is_exported = 1
374
+ AND f.language IN ('typescript', 'javascript', 'tsx', 'jsx')
375
+ GROUP BY f.id
376
+ """).fetchall()
377
+
378
+ single_export_files = sum(1 for r in default_style_rows if r["exported_count"] == 1)
379
+ multi_export_files = sum(1 for r in default_style_rows if r["exported_count"] > 1)
380
+ js_ts_total = single_export_files + multi_export_files
381
+
382
+ export_style = "unknown"
383
+ if js_ts_total > 0:
384
+ if single_export_files > multi_export_files:
385
+ export_style = "default-export preferred"
386
+ else:
387
+ export_style = "named-exports preferred"
388
+
389
+ return {
390
+ "total_symbols": total,
391
+ "exported": exported,
392
+ "private": private,
393
+ "exported_pct": exported_pct,
394
+ "by_kind": by_kind,
395
+ "js_ts_export_style": export_style,
396
+ "js_ts_single_export_files": single_export_files,
397
+ "js_ts_multi_export_files": multi_export_files,
398
+ }
399
+
400
+
401
+ # ---------------------------------------------------------------------------
402
+ # Error handling detection
403
+ # ---------------------------------------------------------------------------
404
+
405
+ _ERROR_NAME_RE = re.compile(r"(Error|Exception|Err|Fault|Failure|Panic)$", re.IGNORECASE)
406
+
407
+
408
+ def _analyze_error_handling(conn) -> dict:
409
+ """Detect error/exception patterns from symbols and file complexity."""
410
+ # Count error-related symbols.
411
+ # Use a broad query then filter in Python to avoid LIKE false positives
412
+ # (e.g., DEFAULT matching %Fault%).
413
+ error_candidates = conn.execute("""
414
+ SELECT s.name, s.kind, f.path as file_path, s.line_start
415
+ FROM symbols s
416
+ JOIN files f ON s.file_id = f.id
417
+ WHERE s.name LIKE '%Error%'
418
+ OR s.name LIKE '%Exception%'
419
+ OR s.name LIKE '%Failure%'
420
+ """).fetchall()
421
+ error_symbols = [
422
+ r
423
+ for r in error_candidates
424
+ if _ERROR_NAME_RE.search(r["name"])
425
+ or "Error" in r["name"]
426
+ or "Exception" in r["name"]
427
+ or "Failure" in r["name"]
428
+ ]
429
+
430
+ error_classes = [r for r in error_symbols if r["kind"] in ("class", "struct", "interface")]
431
+ error_functions = [r for r in error_symbols if r["kind"] in ("function", "method")]
432
+
433
+ # Complexity as proxy for error handling density
434
+ complexity_rows = conn.execute("""
435
+ SELECT AVG(complexity) as avg_complexity,
436
+ MAX(complexity) as max_complexity,
437
+ COUNT(*) as file_count
438
+ FROM file_stats
439
+ WHERE complexity > 0
440
+ """).fetchone()
441
+
442
+ return {
443
+ "error_symbol_count": len(error_symbols),
444
+ "error_classes": len(error_classes),
445
+ "error_functions": len(error_functions),
446
+ "error_symbols": [
447
+ {"name": r["name"], "kind": r["kind"], "file": r["file_path"], "line": r["line_start"]}
448
+ for r in error_symbols[:20]
449
+ ],
450
+ "avg_complexity": round(complexity_rows["avg_complexity"] or 0, 1),
451
+ "max_complexity": round(complexity_rows["max_complexity"] or 0, 1),
452
+ "files_with_complexity": complexity_rows["file_count"] or 0,
453
+ }
454
+
455
+
456
+ # ---------------------------------------------------------------------------
457
+ # Main command
458
+ # ---------------------------------------------------------------------------
459
+
460
+
461
+ @click.command()
462
+ @click.option("-n", "max_outliers", default=10, help="Maximum outliers to display per category")
463
+ @click.pass_context
464
+ def conventions(ctx, max_outliers):
465
+ """Auto-detect codebase naming, file, import, and export conventions."""
466
+ json_mode = ctx.obj.get("json") if ctx.obj else False
467
+ ensure_index()
468
+
469
+ with open_db(readonly=True) as conn:
470
+ project = find_project_root().name
471
+
472
+ # ---- 1. Naming conventions ----
473
+ all_symbols = conn.execute("""
474
+ SELECT s.name, s.kind, s.line_start, f.path as file_path
475
+ FROM symbols s
476
+ JOIN files f ON s.file_id = f.id
477
+ WHERE s.kind IN ('function', 'method', 'class', 'interface',
478
+ 'struct', 'trait', 'enum', 'variable',
479
+ 'constant', 'property', 'field', 'type_alias')
480
+ """).fetchall()
481
+
482
+ # Group by kind-group, tally case styles
483
+ group_cases: dict[str, Counter] = defaultdict(Counter)
484
+ group_names: dict[str, list[str]] = defaultdict(list)
485
+ symbol_details: list[dict] = [] # for outlier detection
486
+
487
+ for sym in all_symbols:
488
+ group = _group_for_kind(sym["kind"])
489
+ style = classify_case(sym["name"])
490
+ if style:
491
+ group_cases[group][style] += 1
492
+ group_names[group].append(sym["name"])
493
+ symbol_details.append(
494
+ {
495
+ "name": sym["name"],
496
+ "kind": sym["kind"],
497
+ "group": group,
498
+ "style": style,
499
+ "file": sym["file_path"],
500
+ "line": sym["line_start"],
501
+ }
502
+ )
503
+
504
+ # Determine dominant style per group
505
+ naming_summary: dict[str, dict] = {}
506
+ for group, counter in sorted(group_cases.items()):
507
+ total = sum(counter.values())
508
+ dominant_style, dominant_count = counter.most_common(1)[0]
509
+ pct = round(100 * dominant_count / total, 1) if total else 0
510
+ naming_summary[group] = {
511
+ "dominant_style": dominant_style,
512
+ "dominant_count": dominant_count,
513
+ "total": total,
514
+ "percent": pct,
515
+ "breakdown": {s: c for s, c in counter.most_common()},
516
+ }
517
+
518
+ # Detect outliers (symbols that don't match dominant style)
519
+ outliers: list[dict] = []
520
+ for det in symbol_details:
521
+ grp_info = naming_summary.get(det["group"])
522
+ if grp_info and det["style"] != grp_info["dominant_style"]:
523
+ outliers.append(
524
+ {
525
+ "name": det["name"],
526
+ "kind": det["kind"],
527
+ "actual_style": det["style"],
528
+ "expected_style": grp_info["dominant_style"],
529
+ "file": det["file"],
530
+ "line": det["line"],
531
+ }
532
+ )
533
+
534
+ # Affix detection
535
+ all_names = [
536
+ sym["name"] for sym in all_symbols if len(sym["name"]) >= _MIN_NAME_LEN and sym["name"] not in _SKIP_NAMES
537
+ ]
538
+ affixes = _detect_affixes(all_names)
539
+
540
+ # ---- 2. File organization ----
541
+ file_rows = conn.execute("SELECT path FROM files ORDER BY path").fetchall()
542
+ file_paths = [r["path"] for r in file_rows]
543
+ file_info = _analyze_files(file_paths)
544
+
545
+ # ---- 3. Import patterns ----
546
+ import_info = _analyze_imports(conn)
547
+
548
+ # ---- 4. Error handling ----
549
+ error_info = _analyze_error_handling(conn)
550
+
551
+ # ---- 5. Export patterns ----
552
+ export_info = _analyze_exports(conn)
553
+
554
+ # ---- JSON output ----
555
+ if json_mode:
556
+ violation_list = [
557
+ {
558
+ "name": o["name"],
559
+ "kind": o["kind"],
560
+ "actual_style": o["actual_style"],
561
+ "expected_style": o["expected_style"],
562
+ "file": o["file"],
563
+ "line": o["line"],
564
+ }
565
+ for o in outliers
566
+ ]
567
+ summary = {
568
+ "total_symbols_analyzed": len(symbol_details),
569
+ "naming_groups": len(naming_summary),
570
+ "outlier_count": len(outliers),
571
+ "total_files": file_info["total_files"],
572
+ "test_files": file_info["test_file_count"],
573
+ "barrel_files": file_info["barrel_files"],
574
+ "import_style": import_info["style"],
575
+ "exported_pct": export_info["exported_pct"],
576
+ }
577
+ click.echo(
578
+ to_json(
579
+ json_envelope(
580
+ "conventions",
581
+ summary=summary,
582
+ naming=naming_summary,
583
+ affixes=affixes,
584
+ files=file_info,
585
+ imports=import_info,
586
+ exports=export_info,
587
+ errors=error_info,
588
+ violations=violation_list,
589
+ )
590
+ )
591
+ )
592
+ return
593
+
594
+ # ---- Text output ----
595
+ click.echo(f"Conventions detected in {project}:\n")
596
+
597
+ # -- Naming --
598
+ click.echo("=== Naming ===")
599
+ if naming_summary:
600
+ for group, info in sorted(naming_summary.items()):
601
+ click.echo(
602
+ f" {group.capitalize()}: {info['dominant_style']} ({info['percent']}% of {info['total']} {group})"
603
+ )
604
+ # Show minority styles if present
605
+ for style, count in info["breakdown"].items():
606
+ if style != info["dominant_style"] and count >= 2:
607
+ pct = round(100 * count / info["total"], 1)
608
+ click.echo(f" also: {style} ({pct}%, {count})")
609
+ else:
610
+ click.echo(" (no classifiable symbols found)")
611
+
612
+ if outliers:
613
+ click.echo(f"\n Outliers ({len(outliers)} total):")
614
+ for o in outliers[:max_outliers]:
615
+ click.echo(
616
+ f" {o['name']} ({o['actual_style']}, "
617
+ f"expected {o['expected_style']}) "
618
+ f"at {loc(o['file'], o['line'])}"
619
+ )
620
+ if len(outliers) > max_outliers:
621
+ click.echo(f" (+{len(outliers) - max_outliers} more)")
622
+
623
+ if affixes["prefixes"] or affixes["suffixes"]:
624
+ click.echo("\n Common affixes:")
625
+ for p in affixes["prefixes"][:5]:
626
+ click.echo(f" prefix {p['affix']} ({p['count']} symbols, {p['percent']}%)")
627
+ for s in affixes["suffixes"][:5]:
628
+ click.echo(f" suffix {s['affix']} ({s['count']} symbols, {s['percent']}%)")
629
+
630
+ # -- File organization --
631
+ click.echo(f"\n=== File Organization ({file_info['total_files']} files) ===")
632
+ if file_info["top_dirs"]:
633
+ dir_rows = [[d["dir"], str(d["count"])] for d in file_info["top_dirs"]]
634
+ click.echo(format_table(["Directory", "Files"], dir_rows))
635
+ if file_info["test_patterns"]:
636
+ click.echo(f"\n Test files: {file_info['test_file_count']} detected")
637
+ for tp in file_info["test_patterns"]:
638
+ click.echo(f" {tp['pattern']} ({tp['count']} files)")
639
+ if file_info["test_dirs"]:
640
+ dirs = ", ".join(d["dir"] for d in file_info["test_dirs"])
641
+ click.echo(f" in: {dirs}")
642
+ else:
643
+ click.echo(" Tests: (no standard test file patterns detected)")
644
+ if file_info["has_barrels"]:
645
+ click.echo(f" Barrel/index files: {file_info['barrel_files']}")
646
+
647
+ # -- Import style --
648
+ click.echo(f"\n=== Import Style ({import_info['total_import_edges']} import edges) ===")
649
+ if import_info["total_import_edges"] > 0:
650
+ click.echo(
651
+ f" {import_info['style'].capitalize()} imports preferred "
652
+ f"({import_info['absolute_pct']}% cross-directory, "
653
+ f"{import_info['relative_pct']}% same-directory)"
654
+ )
655
+ else:
656
+ click.echo(" (no import edges found)")
657
+
658
+ # -- Error handling --
659
+ click.echo("\n=== Error Handling ===")
660
+ if error_info["error_symbol_count"] > 0:
661
+ click.echo(
662
+ f" {error_info['error_symbol_count']} error-related symbols "
663
+ f"({error_info['error_classes']} classes, "
664
+ f"{error_info['error_functions']} functions)"
665
+ )
666
+ for es in error_info["error_symbols"][:5]:
667
+ click.echo(f" {es['name']} ({abbrev_kind(es['kind'])}) at {loc(es['file'], es['line'])}")
668
+ if len(error_info["error_symbols"]) > 5:
669
+ click.echo(f" (+{len(error_info['error_symbols']) - 5} more)")
670
+ else:
671
+ click.echo(" (no error/exception symbols detected)")
672
+ if error_info["files_with_complexity"] > 0:
673
+ click.echo(f" Avg file complexity: {error_info['avg_complexity']} (max {error_info['max_complexity']})")
674
+
675
+ # -- Export pattern --
676
+ click.echo(f"\n=== Export Pattern ({export_info['total_symbols']} symbols) ===")
677
+ if export_info["total_symbols"] > 0:
678
+ click.echo(f" Exported: {export_info['exported']} ({export_info['exported_pct']}%)")
679
+ click.echo(
680
+ f" Private: {export_info['private']} "
681
+ f"({round(100 * export_info['private'] / export_info['total_symbols'], 1)}%)"
682
+ )
683
+ if export_info["by_kind"]:
684
+ ek_rows = [
685
+ [
686
+ abbrev_kind(k["kind"]),
687
+ str(k["total"]),
688
+ str(k["exported"]),
689
+ f"{k['exported_pct']}%",
690
+ ]
691
+ for k in export_info["by_kind"]
692
+ ]
693
+ click.echo(format_table(["Kind", "Total", "Exported", "Rate"], ek_rows))
694
+ if export_info["js_ts_export_style"] != "unknown":
695
+ click.echo(f" JS/TS: {export_info['js_ts_export_style']}")
696
+ else:
697
+ click.echo(" (no symbols found)")