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/catalog/fixes.py ADDED
@@ -0,0 +1,86 @@
1
+ """Actionable fix templates for algorithm findings."""
2
+
3
+ from __future__ import annotations
4
+
5
+ _LANG_ALIASES = {
6
+ "js": "javascript",
7
+ "ts": "typescript",
8
+ }
9
+
10
+
11
+ _TASK_GENERIC_FIX = {
12
+ "sorting": "Replace manual nested loops with the language built-in sort.",
13
+ "search-sorted": "Use binary search APIs instead of linear scan on sorted data.",
14
+ "membership": "Prebuild a set/hash once, then do O(1) membership checks.",
15
+ "string-concat": "Accumulate pieces and join once after the loop.",
16
+ "unique": "Use set/hash dedup instead of nested loop checks.",
17
+ "max-min": "Use built-in max/min helpers unless custom tie-breaking is required.",
18
+ "accumulation": "Use sum/reduce style primitives when no side effects are needed.",
19
+ "manual-power": "Use pow/exponentiation operator instead of repeated multiplication.",
20
+ "manual-gcd": "Use math/library gcd implementation.",
21
+ "fibonacci": "Use iterative DP or memoization to avoid exponential recursion.",
22
+ "nested-lookup": "Build a hash map for one side, then join in one pass.",
23
+ "groupby": "Use grouping helpers (defaultdict/groupingBy/collectors).",
24
+ "string-reverse": "Use built-in reverse/slice helpers.",
25
+ "matrix-mult": "Use vectorized/BLAS-backed matrix multiplication APIs.",
26
+ "busy-wait": "Replace sleep polling loops with event/condition synchronization.",
27
+ "regex-in-loop": "Compile regex once before the loop and reuse it.",
28
+ "io-in-loop": "Batch I/O outside the loop and map results by key.",
29
+ "list-prepend": "Use deque or append-then-reverse instead of front insert/remove.",
30
+ "sort-to-select": "Use min/max or top-k heap selection without full sort.",
31
+ "loop-lookup": "Prebuild lookup set/dict outside loop.",
32
+ "branching-recursion": "Add memoization cache or convert to iterative DP.",
33
+ "quadratic-string": "Use builder/list accumulation + final join.",
34
+ "loop-invariant-call": "Move loop-invariant call outside the loop and reuse result.",
35
+ }
36
+
37
+
38
+ _TEMPLATES = {
39
+ ("io-in-loop", "python"): (
40
+ "ids = [item.id for item in items]\n"
41
+ "rows = fetch_many(ids)\n"
42
+ "by_id = {r.id: r for r in rows}\n"
43
+ "for item in items:\n"
44
+ " item.data = by_id.get(item.id)"
45
+ ),
46
+ ("io-in-loop", "javascript"): (
47
+ "const ids = items.map(x => x.id);\n"
48
+ "const rows = await repo.findMany({ where: { id: { in: ids } } });\n"
49
+ "const byId = new Map(rows.map(r => [r.id, r]));"
50
+ ),
51
+ ("io-in-loop", "typescript"): (
52
+ "const ids = items.map(x => x.id);\n"
53
+ "const rows = await repo.findMany({ where: { id: { in: ids } } });\n"
54
+ "const byId = new Map(rows.map(r => [r.id, r]));"
55
+ ),
56
+ ("io-in-loop", "ruby"): ("users = User.where(id: ids).includes(:profile)\nby_id = users.index_by(&:id)"),
57
+ ("io-in-loop", "php"): ("$rows = User::whereIn('id', $ids)->get()->keyBy('id');"),
58
+ ("io-in-loop", "java"): (
59
+ "Map<Long, User> byId = repository.findAllById(ids).stream()\n"
60
+ " .collect(Collectors.toMap(User::getId, u -> u));"
61
+ ),
62
+ ("loop-lookup", "python"): ("lookup = set(blacklist)\nfor item in items:\n if item in lookup:\n ..."),
63
+ ("sort-to-select", "python"): ("best = min(items)\ntop_k = heapq.nsmallest(k, items)"),
64
+ ("list-prepend", "python"): ("from collections import deque\nout = deque()\nfor v in vals:\n out.appendleft(v)"),
65
+ ("regex-in-loop", "python"): ("pat = re.compile(pattern)\nfor line in lines:\n m = pat.search(line)"),
66
+ ("branching-recursion", "python"): ("@functools.lru_cache(maxsize=None)\ndef solve(n):\n ..."),
67
+ ("quadratic-string", "python"): ("parts = []\nfor x in values:\n parts.append(render(x))\nout = ''.join(parts)"),
68
+ ("loop-invariant-call", "python"): ("cfg = get_config()\nfor item in items:\n use(item, cfg)"),
69
+ }
70
+
71
+
72
+ def _norm_language(language: str | None) -> str:
73
+ if not language:
74
+ return ""
75
+ norm = language.lower().strip()
76
+ return _LANG_ALIASES.get(norm, norm)
77
+
78
+
79
+ def get_fix(task_id: str, language: str | None = None) -> str:
80
+ """Return an actionable fix template for a task and language."""
81
+ lang = _norm_language(language)
82
+ if lang:
83
+ tpl = _TEMPLATES.get((task_id, lang))
84
+ if tpl:
85
+ return tpl
86
+ return _TASK_GENERIC_FIX.get(task_id, "")
roam/catalog/smells.py ADDED
@@ -0,0 +1,599 @@
1
+ """Code smell detection: query DB signals to find structural anti-patterns.
2
+
3
+ Each detector has signature ``(conn) -> list[dict]`` and returns findings
4
+ with fields: smell_id, severity, symbol_name, kind, location, metric_value,
5
+ threshold, description.
6
+
7
+ Severity levels:
8
+ - critical: High-impact structural issue that should be refactored
9
+ - warning: Moderate issue worth investigating
10
+ - info: Minor concern or code style observation
11
+
12
+ 15 deterministic detectors querying the SQLite index. No heuristics,
13
+ no source reading -- pure DB queries for speed and reproducibility.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import re
19
+
20
+
21
+ def _loc(path: str, line: int | None) -> str:
22
+ if line is not None:
23
+ return f"{path}:{line}"
24
+ return path
25
+
26
+
27
+ def _finding(
28
+ smell_id: str,
29
+ severity: str,
30
+ symbol_name: str,
31
+ kind: str,
32
+ location: str,
33
+ metric_value: float | int,
34
+ threshold: float | int,
35
+ description: str,
36
+ ) -> dict:
37
+ return {
38
+ "smell_id": smell_id,
39
+ "severity": severity,
40
+ "symbol_name": symbol_name,
41
+ "kind": kind,
42
+ "location": location,
43
+ "metric_value": metric_value,
44
+ "threshold": threshold,
45
+ "description": description,
46
+ }
47
+
48
+
49
+ def _parse_param_count(signature: str | None) -> int:
50
+ """Count parameters from a signature string, excluding self/cls."""
51
+ if not signature:
52
+ return 0
53
+ # Extract content between first pair of parentheses
54
+ m = re.search(r"\(([^)]*)\)", signature)
55
+ if not m:
56
+ return 0
57
+ params_str = m.group(1).strip()
58
+ if not params_str:
59
+ return 0
60
+ # Split by comma, handling nested generics/brackets
61
+ depth = 0
62
+ parts: list[str] = []
63
+ current: list[str] = []
64
+ for ch in params_str:
65
+ if ch in ("(", "[", "<", "{"):
66
+ depth += 1
67
+ current.append(ch)
68
+ elif ch in (")", "]", ">", "}"):
69
+ depth -= 1
70
+ current.append(ch)
71
+ elif ch == "," and depth == 0:
72
+ parts.append("".join(current).strip())
73
+ current = []
74
+ else:
75
+ current.append(ch)
76
+ if current:
77
+ parts.append("".join(current).strip())
78
+ # Filter out self/cls and empty parts
79
+ filtered = [p for p in parts if p and p.split(":")[0].split("=")[0].strip().lower() not in ("self", "cls", "")]
80
+ return len(filtered)
81
+
82
+
83
+ # ---------------------------------------------------------------------------
84
+ # Individual detectors
85
+ # ---------------------------------------------------------------------------
86
+
87
+
88
+ def detect_brain_method(conn) -> list[dict]:
89
+ """Functions with complexity > 60 AND > 100 LOC."""
90
+ rows = conn.execute(
91
+ "SELECT s.name, s.kind, s.line_start, s.line_end, f.path as file_path, "
92
+ "sm.cognitive_complexity "
93
+ "FROM symbols s "
94
+ "JOIN files f ON s.file_id = f.id "
95
+ "JOIN symbol_metrics sm ON sm.symbol_id = s.id "
96
+ "WHERE s.kind IN ('function', 'method') "
97
+ "AND sm.cognitive_complexity > 60 "
98
+ "AND (s.line_end - s.line_start) > 100"
99
+ ).fetchall()
100
+ results = []
101
+ for r in rows:
102
+ loc_str = _loc(r["file_path"], r["line_start"])
103
+ line_count = (r["line_end"] or 0) - (r["line_start"] or 0)
104
+ results.append(
105
+ _finding(
106
+ "brain-method",
107
+ "critical",
108
+ r["name"],
109
+ r["kind"],
110
+ loc_str,
111
+ r["cognitive_complexity"],
112
+ 60,
113
+ f"Brain method: complexity {r['cognitive_complexity']:.0f}, {line_count} LOC",
114
+ )
115
+ )
116
+ return results
117
+
118
+
119
+ def detect_deep_nesting(conn) -> list[dict]:
120
+ """Symbols with nesting depth > 4."""
121
+ rows = conn.execute(
122
+ "SELECT s.name, s.kind, s.line_start, f.path as file_path, "
123
+ "sm.nesting_depth "
124
+ "FROM symbols s "
125
+ "JOIN files f ON s.file_id = f.id "
126
+ "JOIN symbol_metrics sm ON sm.symbol_id = s.id "
127
+ "WHERE sm.nesting_depth > 4 "
128
+ "AND s.kind IN ('function', 'method')"
129
+ ).fetchall()
130
+ results = []
131
+ for r in rows:
132
+ loc_str = _loc(r["file_path"], r["line_start"])
133
+ results.append(
134
+ _finding(
135
+ "deep-nesting",
136
+ "warning",
137
+ r["name"],
138
+ r["kind"],
139
+ loc_str,
140
+ r["nesting_depth"],
141
+ 4,
142
+ f"Deep nesting: depth {r['nesting_depth']}",
143
+ )
144
+ )
145
+ return results
146
+
147
+
148
+ def detect_long_params(conn) -> list[dict]:
149
+ """Functions with > 5 parameters (excluding self/cls)."""
150
+ rows = conn.execute(
151
+ "SELECT s.name, s.kind, s.line_start, s.signature, f.path as file_path "
152
+ "FROM symbols s "
153
+ "JOIN files f ON s.file_id = f.id "
154
+ "WHERE s.kind IN ('function', 'method') "
155
+ "AND s.signature IS NOT NULL "
156
+ "AND s.signature != ''"
157
+ ).fetchall()
158
+ results = []
159
+ for r in rows:
160
+ count = _parse_param_count(r["signature"])
161
+ if count > 5:
162
+ loc_str = _loc(r["file_path"], r["line_start"])
163
+ results.append(
164
+ _finding(
165
+ "long-params",
166
+ "warning",
167
+ r["name"],
168
+ r["kind"],
169
+ loc_str,
170
+ count,
171
+ 5,
172
+ f"Long parameter list: {count} params",
173
+ )
174
+ )
175
+ return results
176
+
177
+
178
+ def detect_large_class(conn) -> list[dict]:
179
+ """Classes with > 500 LOC AND > 20 methods."""
180
+ rows = conn.execute(
181
+ "SELECT s.id, s.name, s.kind, s.line_start, s.line_end, f.path as file_path "
182
+ "FROM symbols s "
183
+ "JOIN files f ON s.file_id = f.id "
184
+ "WHERE s.kind = 'class' "
185
+ "AND (s.line_end - s.line_start) > 500"
186
+ ).fetchall()
187
+ results = []
188
+ for r in rows:
189
+ method_count = conn.execute(
190
+ "SELECT COUNT(*) FROM symbols "
191
+ "WHERE file_id = (SELECT file_id FROM symbols WHERE id = ?) "
192
+ "AND kind = 'method' "
193
+ "AND line_start >= ? AND line_end <= ?",
194
+ (r["id"], r["line_start"] or 0, r["line_end"] or 0),
195
+ ).fetchone()[0]
196
+ if method_count > 20:
197
+ loc_str = _loc(r["file_path"], r["line_start"])
198
+ line_count = (r["line_end"] or 0) - (r["line_start"] or 0)
199
+ results.append(
200
+ _finding(
201
+ "large-class",
202
+ "critical",
203
+ r["name"],
204
+ r["kind"],
205
+ loc_str,
206
+ line_count,
207
+ 500,
208
+ f"Large class: {line_count} LOC, {method_count} methods",
209
+ )
210
+ )
211
+ return results
212
+
213
+
214
+ def detect_god_class(conn) -> list[dict]:
215
+ """Classes with > 30 methods OR > 1000 LOC."""
216
+ rows = conn.execute(
217
+ "SELECT s.id, s.name, s.kind, s.line_start, s.line_end, "
218
+ "f.path as file_path, s.file_id "
219
+ "FROM symbols s "
220
+ "JOIN files f ON s.file_id = f.id "
221
+ "WHERE s.kind = 'class'"
222
+ ).fetchall()
223
+ results = []
224
+ for r in rows:
225
+ line_count = (r["line_end"] or 0) - (r["line_start"] or 0)
226
+ method_count = conn.execute(
227
+ "SELECT COUNT(*) FROM symbols WHERE file_id = ? AND kind = 'method' AND line_start >= ? AND line_end <= ?",
228
+ (r["file_id"], r["line_start"] or 0, r["line_end"] or 0),
229
+ ).fetchone()[0]
230
+ if method_count > 30 or line_count > 1000:
231
+ loc_str = _loc(r["file_path"], r["line_start"])
232
+ metric = max(method_count, line_count)
233
+ threshold = 30 if method_count > 30 else 1000
234
+ parts = []
235
+ if method_count > 30:
236
+ parts.append(f"{method_count} methods")
237
+ if line_count > 1000:
238
+ parts.append(f"{line_count} LOC")
239
+ results.append(
240
+ _finding(
241
+ "god-class",
242
+ "critical",
243
+ r["name"],
244
+ r["kind"],
245
+ loc_str,
246
+ metric,
247
+ threshold,
248
+ f"God class: {', '.join(parts)}",
249
+ )
250
+ )
251
+ return results
252
+
253
+
254
+ def detect_feature_envy(conn) -> list[dict]:
255
+ """Functions where > 50% of edge targets are in other files (min 4 refs)."""
256
+ rows = conn.execute(
257
+ "SELECT s.id, s.name, s.kind, s.line_start, s.file_id, "
258
+ "f.path as file_path "
259
+ "FROM symbols s "
260
+ "JOIN files f ON s.file_id = f.id "
261
+ "WHERE s.kind IN ('function', 'method')"
262
+ ).fetchall()
263
+ results = []
264
+ for r in rows:
265
+ edges = conn.execute(
266
+ "SELECT e.target_id, t.file_id as target_file_id "
267
+ "FROM edges e "
268
+ "JOIN symbols t ON e.target_id = t.id "
269
+ "WHERE e.source_id = ?",
270
+ (r["id"],),
271
+ ).fetchall()
272
+ total = len(edges)
273
+ if total < 4:
274
+ continue
275
+ external = sum(1 for e in edges if e["target_file_id"] != r["file_id"])
276
+ ratio = external / total
277
+ if ratio > 0.5:
278
+ loc_str = _loc(r["file_path"], r["line_start"])
279
+ results.append(
280
+ _finding(
281
+ "feature-envy",
282
+ "warning",
283
+ r["name"],
284
+ r["kind"],
285
+ loc_str,
286
+ round(ratio * 100, 1),
287
+ 50,
288
+ f"Feature envy: {external}/{total} refs ({ratio:.0%}) to other files",
289
+ )
290
+ )
291
+ return results
292
+
293
+
294
+ def detect_shotgun_surgery(conn) -> list[dict]:
295
+ """Symbols with in_degree > 7 in graph_metrics."""
296
+ rows = conn.execute(
297
+ "SELECT s.name, s.kind, s.line_start, f.path as file_path, "
298
+ "gm.in_degree "
299
+ "FROM symbols s "
300
+ "JOIN files f ON s.file_id = f.id "
301
+ "JOIN graph_metrics gm ON gm.symbol_id = s.id "
302
+ "WHERE gm.in_degree > 7"
303
+ ).fetchall()
304
+ results = []
305
+ for r in rows:
306
+ loc_str = _loc(r["file_path"], r["line_start"])
307
+ results.append(
308
+ _finding(
309
+ "shotgun-surgery",
310
+ "warning",
311
+ r["name"],
312
+ r["kind"],
313
+ loc_str,
314
+ r["in_degree"],
315
+ 7,
316
+ f"Shotgun surgery: {r['in_degree']} incoming dependencies",
317
+ )
318
+ )
319
+ return results
320
+
321
+
322
+ def detect_data_clumps(conn) -> list[dict]:
323
+ """3+ params repeated across 3+ functions (group by sorted first-3 param names)."""
324
+ rows = conn.execute(
325
+ "SELECT s.name, s.kind, s.line_start, s.signature, f.path as file_path "
326
+ "FROM symbols s "
327
+ "JOIN files f ON s.file_id = f.id "
328
+ "WHERE s.kind IN ('function', 'method') "
329
+ "AND s.signature IS NOT NULL "
330
+ "AND s.signature != ''"
331
+ ).fetchall()
332
+
333
+ # Build param-group map
334
+ from collections import defaultdict
335
+
336
+ param_groups: dict[str, list[dict]] = defaultdict(list)
337
+ for r in rows:
338
+ sig = r["signature"]
339
+ m = re.search(r"\(([^)]*)\)", sig or "")
340
+ if not m:
341
+ continue
342
+ params_str = m.group(1).strip()
343
+ if not params_str:
344
+ continue
345
+ # Simple split by comma (top-level only)
346
+ depth = 0
347
+ parts: list[str] = []
348
+ current: list[str] = []
349
+ for ch in params_str:
350
+ if ch in ("(", "[", "<", "{"):
351
+ depth += 1
352
+ current.append(ch)
353
+ elif ch in (")", "]", ">", "}"):
354
+ depth -= 1
355
+ current.append(ch)
356
+ elif ch == "," and depth == 0:
357
+ parts.append("".join(current).strip())
358
+ current = []
359
+ else:
360
+ current.append(ch)
361
+ if current:
362
+ parts.append("".join(current).strip())
363
+ # Extract just param names, skip self/cls
364
+ names = []
365
+ for p in parts:
366
+ name = p.split(":")[0].split("=")[0].strip().lower()
367
+ if name and name not in ("self", "cls", ""):
368
+ names.append(name)
369
+ if len(names) >= 3:
370
+ key = ",".join(sorted(names[:3]))
371
+ param_groups[key].append(r)
372
+
373
+ results = []
374
+ seen_groups: set[str] = set()
375
+ for key, funcs in param_groups.items():
376
+ if len(funcs) >= 3 and key not in seen_groups:
377
+ seen_groups.add(key)
378
+ # Report one finding per clump using the first function
379
+ r = funcs[0]
380
+ loc_str = _loc(r["file_path"], r["line_start"])
381
+ func_names = [f["name"] for f in funcs[:5]]
382
+ results.append(
383
+ _finding(
384
+ "data-clumps",
385
+ "info",
386
+ r["name"],
387
+ r["kind"],
388
+ loc_str,
389
+ len(funcs),
390
+ 3,
391
+ f"Data clump: params ({key}) repeated in {len(funcs)} functions: {', '.join(func_names)}",
392
+ )
393
+ )
394
+ return results
395
+
396
+
397
+ def detect_dead_params(conn) -> list[dict]:
398
+ """Functions with 4+ params but complexity <= 1 (likely unused params)."""
399
+ rows = conn.execute(
400
+ "SELECT s.name, s.kind, s.line_start, s.signature, f.path as file_path, "
401
+ "sm.cognitive_complexity "
402
+ "FROM symbols s "
403
+ "JOIN files f ON s.file_id = f.id "
404
+ "JOIN symbol_metrics sm ON sm.symbol_id = s.id "
405
+ "WHERE s.kind IN ('function', 'method') "
406
+ "AND sm.cognitive_complexity <= 1 "
407
+ "AND s.signature IS NOT NULL "
408
+ "AND s.signature != ''"
409
+ ).fetchall()
410
+ results = []
411
+ for r in rows:
412
+ count = _parse_param_count(r["signature"])
413
+ if count >= 4:
414
+ loc_str = _loc(r["file_path"], r["line_start"])
415
+ results.append(
416
+ _finding(
417
+ "dead-params",
418
+ "info",
419
+ r["name"],
420
+ r["kind"],
421
+ loc_str,
422
+ count,
423
+ 4,
424
+ f"Dead params: {count} params but complexity {r['cognitive_complexity']:.0f}",
425
+ )
426
+ )
427
+ return results
428
+
429
+
430
+ def detect_empty_catch(conn) -> list[dict]:
431
+ """Placeholder: empty catch/except blocks. Returns []."""
432
+ return []
433
+
434
+
435
+ def detect_low_cohesion(conn) -> list[dict]:
436
+ """Classes with 5+ methods but fewer than methods/2 internal edges."""
437
+ rows = conn.execute(
438
+ "SELECT s.id, s.name, s.kind, s.line_start, s.line_end, "
439
+ "f.path as file_path, s.file_id "
440
+ "FROM symbols s "
441
+ "JOIN files f ON s.file_id = f.id "
442
+ "WHERE s.kind = 'class'"
443
+ ).fetchall()
444
+ results = []
445
+ for r in rows:
446
+ # Count methods within the class line range
447
+ methods = conn.execute(
448
+ "SELECT id FROM symbols WHERE file_id = ? AND kind = 'method' AND line_start >= ? AND line_end <= ?",
449
+ (r["file_id"], r["line_start"] or 0, r["line_end"] or 0),
450
+ ).fetchall()
451
+ method_count = len(methods)
452
+ if method_count < 5:
453
+ continue
454
+ method_ids = [m["id"] for m in methods]
455
+ if not method_ids:
456
+ continue
457
+ # Count internal edges between methods of this class
458
+ ph = ",".join("?" for _ in method_ids)
459
+ internal_edges = conn.execute(
460
+ f"SELECT COUNT(*) FROM edges WHERE source_id IN ({ph}) AND target_id IN ({ph})",
461
+ method_ids + method_ids,
462
+ ).fetchone()[0]
463
+ threshold = method_count // 2
464
+ if internal_edges < threshold:
465
+ loc_str = _loc(r["file_path"], r["line_start"])
466
+ results.append(
467
+ _finding(
468
+ "low-cohesion",
469
+ "warning",
470
+ r["name"],
471
+ r["kind"],
472
+ loc_str,
473
+ internal_edges,
474
+ threshold,
475
+ f"Low cohesion: {method_count} methods but only {internal_edges} internal edges "
476
+ f"(threshold: {threshold})",
477
+ )
478
+ )
479
+ return results
480
+
481
+
482
+ def detect_message_chain(conn) -> list[dict]:
483
+ """Functions with out_degree > 10 in graph_metrics."""
484
+ rows = conn.execute(
485
+ "SELECT s.name, s.kind, s.line_start, f.path as file_path, "
486
+ "gm.out_degree "
487
+ "FROM symbols s "
488
+ "JOIN files f ON s.file_id = f.id "
489
+ "JOIN graph_metrics gm ON gm.symbol_id = s.id "
490
+ "WHERE gm.out_degree > 10 "
491
+ "AND s.kind IN ('function', 'method')"
492
+ ).fetchall()
493
+ results = []
494
+ for r in rows:
495
+ loc_str = _loc(r["file_path"], r["line_start"])
496
+ results.append(
497
+ _finding(
498
+ "message-chain",
499
+ "info",
500
+ r["name"],
501
+ r["kind"],
502
+ loc_str,
503
+ r["out_degree"],
504
+ 10,
505
+ f"Message chain: {r['out_degree']} outgoing calls",
506
+ )
507
+ )
508
+ return results
509
+
510
+
511
+ def detect_refused_bequest(conn) -> list[dict]:
512
+ """Placeholder: classes that override parent methods to do nothing. Returns []."""
513
+ return []
514
+
515
+
516
+ def detect_primitive_obsession(conn) -> list[dict]:
517
+ """Placeholder: excessive use of primitive types. Returns []."""
518
+ return []
519
+
520
+
521
+ def detect_duplicate_conditionals(conn) -> list[dict]:
522
+ """Placeholder: repeated conditional logic. Returns []."""
523
+ return []
524
+
525
+
526
+ # ---------------------------------------------------------------------------
527
+ # Detector registry
528
+ # ---------------------------------------------------------------------------
529
+
530
+ ALL_DETECTORS: list[tuple[str, callable]] = [
531
+ ("brain-method", detect_brain_method),
532
+ ("deep-nesting", detect_deep_nesting),
533
+ ("long-params", detect_long_params),
534
+ ("large-class", detect_large_class),
535
+ ("god-class", detect_god_class),
536
+ ("feature-envy", detect_feature_envy),
537
+ ("shotgun-surgery", detect_shotgun_surgery),
538
+ ("data-clumps", detect_data_clumps),
539
+ ("dead-params", detect_dead_params),
540
+ ("empty-catch", detect_empty_catch),
541
+ ("low-cohesion", detect_low_cohesion),
542
+ ("message-chain", detect_message_chain),
543
+ ("refused-bequest", detect_refused_bequest),
544
+ ("primitive-obsession", detect_primitive_obsession),
545
+ ("duplicate-conditionals", detect_duplicate_conditionals),
546
+ ]
547
+
548
+ _SEVERITY_ORDER = {"critical": 0, "warning": 1, "info": 2}
549
+
550
+
551
+ def run_all_detectors(conn) -> list[dict]:
552
+ """Run all 15 smell detectors and return combined findings.
553
+
554
+ Returns list of finding dicts sorted by severity (critical first).
555
+ """
556
+ findings: list[dict] = []
557
+ for _smell_id, detect_fn in ALL_DETECTORS:
558
+ try:
559
+ hits = detect_fn(conn)
560
+ except Exception:
561
+ continue
562
+ findings.extend(hits)
563
+ # Sort: critical first, then warning, then info
564
+ findings.sort(key=lambda f: _SEVERITY_ORDER.get(f.get("severity", "info"), 2))
565
+ return findings
566
+
567
+
568
+ def file_health_scores(conn) -> dict[str, float]:
569
+ """Compute per-file health scores from smell findings.
570
+
571
+ Returns {file_path: score} where score is 1-10 (10 = healthy).
572
+ Penalties: critical = -3, warning = -1.5, info = -0.5. Min score = 1.
573
+ """
574
+ findings = run_all_detectors(conn)
575
+ penalties: dict[str, float] = {}
576
+ for f in findings:
577
+ loc_str = f.get("location", "")
578
+ # Extract file path from location (path:line or path)
579
+ file_path = loc_str.split(":")[0] if ":" in loc_str else loc_str
580
+ if not file_path:
581
+ continue
582
+ sev = f.get("severity", "info")
583
+ if sev == "critical":
584
+ penalty = 3.0
585
+ elif sev == "warning":
586
+ penalty = 1.5
587
+ else:
588
+ penalty = 0.5
589
+ penalties[file_path] = penalties.get(file_path, 0.0) + penalty
590
+
591
+ # Get all indexed files
592
+ files = conn.execute("SELECT path FROM files").fetchall()
593
+ scores: dict[str, float] = {}
594
+ for row in files:
595
+ path = row["path"]
596
+ penalty = penalties.get(path, 0.0)
597
+ score = max(1.0, 10.0 - penalty)
598
+ scores[path] = round(score, 1)
599
+ return scores