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,633 @@
1
+ """Detect API endpoints that return more data than necessary.
2
+
3
+ Finds models with many fields that are fully serialized when only a few
4
+ fields are needed — the "over-fetch" anti-pattern that bloats API responses
5
+ with unused columns, wastes bandwidth, and leaks internal schema details.
6
+
7
+ Detection checks:
8
+
9
+ 1. **Large models without $hidden** — Models with many $fillable fields
10
+ (>threshold) that don't define ``$hidden`` to suppress serialized output.
11
+ Every API response includes ALL fillable fields unless hidden or visible is set.
12
+
13
+ 2. **Models without API Resources** — Models returned directly from controllers
14
+ via ``response()->json($model)`` instead of through a Laravel API Resource
15
+ that controls which fields are exposed.
16
+
17
+ 3. **$fillable count vs $hidden count ratio** — If a model has 50 fillable
18
+ fields and only hides 2, the API response is still 48 fields.
19
+
20
+ 4. **Missing select() in queries** — Controllers/services that do
21
+ ``Model::all()`` or ``Model::paginate()`` without ``->select(['f1', 'f2'])``
22
+ to limit returned columns, especially on large models.
23
+
24
+ Confidence levels:
25
+
26
+ - ``high`` — 30+ fillable fields, no $hidden, no $visible, direct controller return
27
+ - ``medium`` — 20+ fillable fields, minimal $hidden (< 3 fields hidden)
28
+ - ``low`` — 15+ fillable fields, no select() optimization in queries
29
+
30
+ Supported frameworks: Laravel/Eloquent (PHP).
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import os
36
+ import re
37
+ from collections import defaultdict
38
+
39
+ import click
40
+
41
+ from roam.commands.resolve import ensure_index
42
+ from roam.db.connection import find_project_root, open_db
43
+ from roam.output.formatter import json_envelope, loc, to_json
44
+
45
+ # ---------------------------------------------------------------------------
46
+ # Constants
47
+ # ---------------------------------------------------------------------------
48
+
49
+ # Regex to extract entries from PHP array literals like:
50
+ # 'field1', 'field2', "field3", ...
51
+ _ARRAY_STRING_RE = re.compile(r"""['"]([^'"]+)['"]""")
52
+
53
+ # Patterns that indicate a model field is being directly returned to the client
54
+ # without going through an API Resource.
55
+ _DIRECT_RETURN_PATTERNS = [
56
+ # return $model; / return $record; / return $this->model;
57
+ re.compile(r"\breturn\s+\$\w+\s*;"),
58
+ # response()->json($model) / response()->json($record)
59
+ re.compile(r"response\s*\(\s*\)\s*->\s*json\s*\(\s*\$\w+"),
60
+ # ->json($model)
61
+ re.compile(r"->\s*json\s*\(\s*\$\w+"),
62
+ ]
63
+
64
+ # Patterns that indicate an API Resource wrapping (these are safe)
65
+ _RESOURCE_PATTERNS = [
66
+ # new SomeResource($model) / SomeResource::collection(...)
67
+ re.compile(r"\bnew\s+\w+Resource\s*\("),
68
+ re.compile(r"\w+Resource\s*::\s*collection\s*\("),
69
+ # JsonResource, AnonymousResourceCollection
70
+ re.compile(r"\bJsonResource\b"),
71
+ ]
72
+
73
+ # select() call detection — indicates developer is intentionally limiting columns
74
+ _SELECT_CALL_RE = re.compile(r"->\s*select\s*\(")
75
+
76
+ # Unoptimized query patterns (no select)
77
+ _UNOPTIMIZED_QUERY_RE = re.compile(
78
+ r"(?:Model::all\(\)|Model::paginate\(|"
79
+ r"::\s*all\s*\(\s*\)|::\s*paginate\s*\(|"
80
+ r"::\s*get\s*\(\s*\))",
81
+ )
82
+
83
+
84
+ # ---------------------------------------------------------------------------
85
+ # Helpers
86
+ # ---------------------------------------------------------------------------
87
+
88
+
89
+ def _is_test_path(path: str) -> bool:
90
+ p = path.replace("\\", "/").lower()
91
+ base = os.path.basename(p)
92
+ if base.startswith("test_") or base.endswith("_test.php"):
93
+ return True
94
+ if "/tests/" in p or "/test/" in p or "/testing/" in p:
95
+ return True
96
+ return False
97
+
98
+
99
+ def _read_file_lines(abs_path) -> list[str]:
100
+ """Read file lines safely, returning empty list on failure."""
101
+ try:
102
+ with open(abs_path, encoding="utf-8", errors="replace") as fh:
103
+ return fh.readlines()
104
+ except OSError:
105
+ return []
106
+
107
+
108
+ def _extract_array_fields(source: str, property_name: str) -> list[str]:
109
+ """Extract string values from a PHP class property array.
110
+
111
+ Handles both ``$fillable = ['a', 'b']`` and ``$fillable = ["a", "b"]``
112
+ across multiple lines.
113
+
114
+ Returns list of field name strings found, or empty list if property absent.
115
+ """
116
+ # Match: $fillable = [ ... ] or protected $fillable = [ ... ];
117
+ # Uses a non-greedy match that stops at the closing bracket.
118
+ pattern = re.compile(
119
+ rf"\$\s*{re.escape(property_name)}\s*=\s*\[([^\]]*)\]",
120
+ re.DOTALL,
121
+ )
122
+ m = pattern.search(source)
123
+ if not m:
124
+ return []
125
+ return _ARRAY_STRING_RE.findall(m.group(1))
126
+
127
+
128
+ def _has_visible_property(source: str) -> bool:
129
+ """Return True if the model defines $visible (whitelist — fully controlled)."""
130
+ return bool(re.search(r"\$\s*visible\s*=\s*\[", source))
131
+
132
+
133
+ def _find_api_resource_for_model(conn, model_name: str) -> str | None:
134
+ """Find an API Resource file matching this model name.
135
+
136
+ Looks for files named <ModelName>Resource.php in the codebase.
137
+ Returns the file path string, or None if not found.
138
+ """
139
+ resource_name = f"{model_name}Resource.php"
140
+ rows = conn.execute(
141
+ "SELECT path FROM files WHERE path LIKE ?",
142
+ (f"%{resource_name}",),
143
+ ).fetchall()
144
+ for row in rows:
145
+ p = row["path"].replace("\\", "/")
146
+ if "Resource" in p or "resource" in p:
147
+ return row["path"]
148
+ # Also check for collection resources
149
+ collection_name = f"{model_name}Collection.php"
150
+ rows2 = conn.execute(
151
+ "SELECT path FROM files WHERE path LIKE ?",
152
+ (f"%{collection_name}",),
153
+ ).fetchall()
154
+ if rows2:
155
+ return rows2[0]["path"]
156
+ return None
157
+
158
+
159
+ def _count_resource_fields(root, resource_path: str) -> int | None:
160
+ """Count fields exposed in a Laravel API Resource's ``toArray()`` method.
161
+
162
+ Parses the ``return [...]`` array inside ``toArray()`` and counts
163
+ ``'key' =>`` patterns. Returns the field count, or ``None`` if the
164
+ method cannot be parsed (e.g. dynamic or delegated responses).
165
+ """
166
+ abs_path = root / resource_path
167
+ try:
168
+ source = abs_path.read_text(encoding="utf-8", errors="replace")
169
+ except OSError:
170
+ return None
171
+
172
+ m = re.search(r"function\s+toArray\s*\(", source)
173
+ if not m:
174
+ return None
175
+
176
+ rest = source[m.end() :]
177
+ return_match = re.search(r"return\s*\[", rest)
178
+ if not return_match:
179
+ return None
180
+
181
+ bracket_pos = rest.index("[", return_match.start())
182
+ depth = 0
183
+ pos = bracket_pos
184
+ while pos < len(rest):
185
+ if rest[pos] == "[":
186
+ depth += 1
187
+ elif rest[pos] == "]":
188
+ depth -= 1
189
+ if depth == 0:
190
+ break
191
+ pos += 1
192
+
193
+ array_body = rest[bracket_pos : pos + 1]
194
+
195
+ # Each 'key' => represents one exposed field in the response
196
+ return len(re.findall(r"""['\"][^'\"]+['\"]\s*=>""", array_body))
197
+
198
+
199
+ def _check_controller_direct_returns(
200
+ conn,
201
+ model_name: str,
202
+ root,
203
+ ) -> list[dict]:
204
+ """Check controller files for direct model returns (without API Resources).
205
+
206
+ Returns list of locations where the model is returned directly.
207
+ """
208
+ direct_returns = []
209
+
210
+ controller_files = conn.execute(
211
+ "SELECT path FROM files WHERE (path LIKE '%Controller%' OR path LIKE '%controller%') AND path LIKE '%.php'",
212
+ ).fetchall()
213
+
214
+ for row in controller_files:
215
+ if _is_test_path(row["path"]):
216
+ continue
217
+ # Skip console commands and non-HTTP controllers
218
+ p_lower = row["path"].replace("\\", "/").lower()
219
+ if "/console/" in p_lower or "/commands/" in p_lower:
220
+ continue
221
+ # Only match files in HTTP controller directories
222
+ if (
223
+ "controller" in os.path.basename(row["path"]).lower()
224
+ and "/http/" not in p_lower
225
+ and "/controllers/" not in p_lower
226
+ ):
227
+ continue
228
+ abs_path = root / row["path"]
229
+ if not abs_path.is_file():
230
+ continue
231
+ try:
232
+ content = abs_path.read_text(encoding="utf-8", errors="replace")
233
+ except OSError:
234
+ continue
235
+
236
+ # Only check controllers that reference this model
237
+ if model_name not in content:
238
+ continue
239
+
240
+ lines = content.splitlines()
241
+ for line_no, line in enumerate(lines, start=1):
242
+ # Skip if the line uses a Resource (safe pattern)
243
+ if any(p.search(line) for p in _RESOURCE_PATTERNS):
244
+ continue
245
+ # Flag direct returns
246
+ for pattern in _DIRECT_RETURN_PATTERNS:
247
+ if pattern.search(line):
248
+ direct_returns.append(
249
+ {
250
+ "file": row["path"],
251
+ "line": line_no,
252
+ "location": loc(row["path"], line_no),
253
+ "snippet": line.strip()[:100],
254
+ }
255
+ )
256
+ break # one match per line is enough
257
+
258
+ return direct_returns
259
+
260
+
261
+ def _check_missing_select(
262
+ conn,
263
+ model_name: str,
264
+ root,
265
+ ) -> list[dict]:
266
+ """Check controller/service files for queries without select().
267
+
268
+ Returns list of locations where Model::all() or paginate() is used
269
+ without a preceding ->select() call to limit columns.
270
+ """
271
+ missing_select = []
272
+
273
+ # Look in controllers and services
274
+ files = conn.execute(
275
+ "SELECT path FROM files "
276
+ "WHERE path LIKE '%.php' "
277
+ "AND (path LIKE '%Controller%' OR path LIKE '%controller%' "
278
+ " OR path LIKE '%Service%' OR path LIKE '%service%' "
279
+ " OR path LIKE '%Repository%' OR path LIKE '%repository%')",
280
+ ).fetchall()
281
+
282
+ # Pattern to match Model::query(), Model::all(), Model::paginate() etc.
283
+ # We build model-specific patterns
284
+ model_query_re = re.compile(
285
+ rf"{re.escape(model_name)}\s*::\s*(?:all|paginate|get|query|where|with)\s*\(",
286
+ )
287
+
288
+ for row in files:
289
+ if _is_test_path(row["path"]):
290
+ continue
291
+ abs_path = root / row["path"]
292
+ if not abs_path.is_file():
293
+ continue
294
+ try:
295
+ content = abs_path.read_text(encoding="utf-8", errors="replace")
296
+ except OSError:
297
+ continue
298
+
299
+ if model_name not in content:
300
+ continue
301
+
302
+ lines = content.splitlines()
303
+ for line_no, line in enumerate(lines, start=1):
304
+ if not model_query_re.search(line):
305
+ continue
306
+ # Check if this line or the surrounding ±5 lines contain ->select(
307
+ context_start = max(0, line_no - 6)
308
+ context_end = min(len(lines), line_no + 5)
309
+ context_block = "\n".join(lines[context_start:context_end])
310
+ if _SELECT_CALL_RE.search(context_block):
311
+ continue # select() is nearby — OK
312
+ missing_select.append(
313
+ {
314
+ "file": row["path"],
315
+ "line": line_no,
316
+ "location": loc(row["path"], line_no),
317
+ "snippet": line.strip()[:100],
318
+ }
319
+ )
320
+
321
+ return missing_select
322
+
323
+
324
+ # ---------------------------------------------------------------------------
325
+ # Core analysis
326
+ # ---------------------------------------------------------------------------
327
+
328
+
329
+ def _find_model_files(conn) -> list[dict]:
330
+ """Find PHP model files by path and presence of $fillable."""
331
+ rows = conn.execute(
332
+ "SELECT f.id as file_id, f.path, s.id as class_id, "
333
+ "s.name as class_name, s.line_start, s.line_end "
334
+ "FROM files f "
335
+ "JOIN symbols s ON s.file_id = f.id "
336
+ "WHERE s.kind = 'class' "
337
+ "AND f.path LIKE '%.php' "
338
+ "AND ("
339
+ " f.path LIKE '%/Models/%' "
340
+ " OR f.path LIKE '%\\\\Models\\\\%' "
341
+ " OR f.path LIKE '%/Model/%' "
342
+ ") "
343
+ "ORDER BY f.path",
344
+ ).fetchall()
345
+ return [dict(r) for r in rows]
346
+
347
+
348
+ def analyze_over_fetch(conn, threshold: int, limit: int) -> list[dict]:
349
+ """Run the over-fetch detection analysis.
350
+
351
+ Returns list of finding dicts sorted by severity (high → medium → low).
352
+ """
353
+ root = find_project_root()
354
+ findings = []
355
+
356
+ model_files = _find_model_files(conn)
357
+
358
+ for model_info in model_files:
359
+ if _is_test_path(model_info["path"]):
360
+ continue
361
+
362
+ abs_path = root / model_info["path"]
363
+ if not abs_path.is_file():
364
+ continue
365
+
366
+ source = ""
367
+ try:
368
+ source = abs_path.read_text(encoding="utf-8", errors="replace")
369
+ except OSError:
370
+ continue
371
+
372
+ # Extract $fillable fields
373
+ fillable = _extract_array_fields(source, "fillable")
374
+ fillable_count = len(fillable)
375
+
376
+ # Skip models with fewer fields than the minimum threshold
377
+ if fillable_count < threshold:
378
+ continue
379
+
380
+ # Extract $hidden fields
381
+ hidden = _extract_array_fields(source, "hidden")
382
+ hidden_count = len(hidden)
383
+
384
+ # Check for $visible (whitelist — strong protection)
385
+ has_visible = _has_visible_property(source)
386
+
387
+ # Check for a matching API Resource
388
+ resource_path = _find_api_resource_for_model(conn, model_info["class_name"])
389
+ has_resource = resource_path is not None
390
+
391
+ # If a Resource exists, check how many fields it actually exposes.
392
+ # When the Resource returns significantly fewer fields than the model
393
+ # has, the output is well-filtered and the finding can be skipped.
394
+ resource_field_count = None
395
+ if has_resource and resource_path:
396
+ resource_field_count = _count_resource_fields(root, resource_path)
397
+ if resource_field_count is not None and resource_field_count < fillable_count * 0.5:
398
+ continue # Resource properly filters output
399
+
400
+ # Effective exposed fields = fillable minus hidden (when no $visible)
401
+ exposed_count = fillable_count - hidden_count if not has_visible else 0
402
+
403
+ # -------------------------------------------------------------------
404
+ # Determine confidence level
405
+ # -------------------------------------------------------------------
406
+ confidence = None
407
+ reasons = []
408
+ suggestions = []
409
+
410
+ if has_visible:
411
+ # $visible whitelist is the strictest protection — skip
412
+ continue
413
+
414
+ if fillable_count >= 30 and hidden_count == 0 and not has_resource:
415
+ confidence = "high"
416
+ reasons.append(f"Serializes {fillable_count} fields per item in list APIs")
417
+ if not has_resource:
418
+ reasons.append("No API Resource found to control output")
419
+ suggestions.append(
420
+ f"Add $hidden for unused fields, or use ->select() in queries,\n"
421
+ f" or create a {model_info['class_name']}Resource "
422
+ f"to control output\n"
423
+ f" Note: $hidden/$visible also hides fields from edit endpoints.\n"
424
+ f" For CRUD apps, prefer API Resources for response shaping."
425
+ )
426
+ elif fillable_count >= 20 and hidden_count < 3:
427
+ confidence = "medium"
428
+ reasons.append(
429
+ f"{fillable_count} fillable fields, only {hidden_count} hidden — {exposed_count} fields exposed"
430
+ )
431
+ if not has_resource:
432
+ suggestions.append(
433
+ f"Consider $hidden or a {model_info['class_name']}Resource "
434
+ f"for large list responses\n"
435
+ f" Note: $hidden/$visible also hides fields from edit endpoints.\n"
436
+ f" For CRUD apps, prefer API Resources for response shaping."
437
+ )
438
+ else:
439
+ suggestions.append(f"Verify {resource_path} limits fields for list vs detail views")
440
+ elif fillable_count >= threshold:
441
+ confidence = "low"
442
+ reasons.append(f"{fillable_count} fillable fields without select() optimization")
443
+ suggestions.append("Use ->select(['field1', 'field2']) in list queries to limit columns")
444
+
445
+ if confidence is None:
446
+ continue
447
+
448
+ # -------------------------------------------------------------------
449
+ # Controller analysis: direct returns + missing select()
450
+ # -------------------------------------------------------------------
451
+ direct_returns = []
452
+ missing_selects = []
453
+
454
+ # Only do file I/O for medium+ threshold findings to stay fast
455
+ if confidence in ("high", "medium"):
456
+ direct_returns = _check_controller_direct_returns(conn, model_info["class_name"], root)
457
+ # Upgrade to high if direct returns found and we were medium
458
+ if direct_returns and confidence == "medium":
459
+ confidence = "high"
460
+ reasons.append(f"Model returned directly from controller ({len(direct_returns)} location(s))")
461
+
462
+ if confidence == "low":
463
+ missing_selects = _check_missing_select(conn, model_info["class_name"], root)
464
+ if not missing_selects:
465
+ # No bad query patterns — downgrade / skip low-confidence
466
+ continue
467
+
468
+ findings.append(
469
+ {
470
+ "model_name": model_info["class_name"],
471
+ "model_path": model_info["path"],
472
+ "model_location": loc(model_info["path"], model_info["line_start"]),
473
+ "fillable_count": fillable_count,
474
+ "hidden_count": hidden_count,
475
+ "exposed_count": exposed_count,
476
+ "has_visible": has_visible,
477
+ "has_resource": has_resource,
478
+ "resource_path": resource_path,
479
+ "confidence": confidence,
480
+ "reasons": reasons,
481
+ "suggestions": suggestions,
482
+ "direct_returns": direct_returns[:5], # Cap to avoid noise
483
+ "missing_selects": missing_selects[:5],
484
+ }
485
+ )
486
+
487
+ # Sort: high → medium → low, then by exposed_count descending
488
+ _conf_order = {"high": 0, "medium": 1, "low": 2}
489
+ findings.sort(key=lambda f: (_conf_order.get(f["confidence"], 9), -f["exposed_count"]))
490
+
491
+ return findings[:limit]
492
+
493
+
494
+ # ---------------------------------------------------------------------------
495
+ # CLI command
496
+ # ---------------------------------------------------------------------------
497
+
498
+
499
+ @click.command("over-fetch")
500
+ @click.option(
501
+ "--threshold",
502
+ "-t",
503
+ default=20,
504
+ show_default=True,
505
+ help="Minimum number of $fillable fields to flag a model",
506
+ )
507
+ @click.option(
508
+ "--limit",
509
+ "-n",
510
+ default=30,
511
+ show_default=True,
512
+ help="Maximum number of findings to display",
513
+ )
514
+ @click.pass_context
515
+ def over_fetch_cmd(ctx, threshold, limit):
516
+ """Detect models that serialize more fields than necessary in API responses.
517
+
518
+ Finds large models ($fillable) without $hidden/$visible field filtering,
519
+ controllers that return models directly without API Resources, and
520
+ queries missing ->select() to limit fetched columns.
521
+
522
+ Confidence levels:
523
+
524
+ \b
525
+ high — 30+ fillable fields, no $hidden/$visible, no API Resource
526
+ medium — 20+ fillable fields, minimal $hidden (< 3 fields)
527
+ low — 15+ fillable fields, missing ->select() in list queries
528
+
529
+ \b
530
+ Examples:
531
+ roam over-fetch # Scan with default threshold (20 fields)
532
+ roam over-fetch --threshold 30 # Only flag very large models
533
+ roam over-fetch --limit 10 # Show top 10 findings only
534
+ roam --json over-fetch # JSON output
535
+ """
536
+ json_mode = ctx.obj.get("json") if ctx.obj else False
537
+ ensure_index()
538
+
539
+ with open_db(readonly=True) as conn:
540
+ findings = analyze_over_fetch(conn, threshold=threshold, limit=limit)
541
+
542
+ # -------------------------------------------------------------------
543
+ # Tally by confidence
544
+ # -------------------------------------------------------------------
545
+ by_confidence: dict[str, int] = defaultdict(int)
546
+ for f in findings:
547
+ by_confidence[f["confidence"]] += 1
548
+
549
+ total = len(findings)
550
+ high_count = by_confidence.get("high", 0)
551
+ medium_count = by_confidence.get("medium", 0)
552
+ low_count = by_confidence.get("low", 0)
553
+
554
+ conf_parts = []
555
+ if high_count:
556
+ conf_parts.append(f"{high_count} high")
557
+ if medium_count:
558
+ conf_parts.append(f"{medium_count} medium")
559
+ if low_count:
560
+ conf_parts.append(f"{low_count} low")
561
+ conf_str = ", ".join(conf_parts) if conf_parts else "none"
562
+
563
+ if total:
564
+ verdict = f"{total} over-fetch pattern{'s' if total != 1 else ''} found ({conf_str})"
565
+ else:
566
+ verdict = "No over-fetch patterns detected"
567
+
568
+ # -------------------------------------------------------------------
569
+ # JSON output
570
+ # -------------------------------------------------------------------
571
+ if json_mode:
572
+ click.echo(
573
+ to_json(
574
+ json_envelope(
575
+ "over-fetch",
576
+ summary={
577
+ "verdict": verdict,
578
+ "total": total,
579
+ "threshold": threshold,
580
+ "by_confidence": dict(by_confidence),
581
+ },
582
+ findings=findings,
583
+ )
584
+ )
585
+ )
586
+ return
587
+
588
+ # -------------------------------------------------------------------
589
+ # Text output
590
+ # -------------------------------------------------------------------
591
+ click.echo(f"VERDICT: {verdict}")
592
+
593
+ if not findings:
594
+ return
595
+
596
+ click.echo()
597
+ click.echo("Large models without field filtering:")
598
+
599
+ for f in findings:
600
+ conf = f["confidence"]
601
+ model = f["model_name"]
602
+ fillable = f["fillable_count"]
603
+ hidden = f["hidden_count"]
604
+ model_loc = f["model_location"]
605
+
606
+ # Header line: [confidence] ModelName (N fillable, M hidden) path:line
607
+ click.echo(f" [{conf}] {model} ({fillable} fillable, {hidden} hidden) {model_loc}")
608
+
609
+ # Reason lines
610
+ for reason in f["reasons"]:
611
+ click.echo(f" {reason}")
612
+
613
+ # API Resource status
614
+ if f["has_resource"]:
615
+ click.echo(f" Resource: {f['resource_path']}")
616
+
617
+ # Direct return locations (for high-confidence)
618
+ if f["direct_returns"]:
619
+ click.echo(f" Direct controller returns ({len(f['direct_returns'])} location(s)):")
620
+ for dr in f["direct_returns"][:3]:
621
+ click.echo(f" {dr['location']} {dr['snippet']}")
622
+
623
+ # Missing select locations (for low-confidence)
624
+ if f["missing_selects"]:
625
+ click.echo(f" Queries without ->select() ({len(f['missing_selects'])} location(s)):")
626
+ for ms in f["missing_selects"][:3]:
627
+ click.echo(f" {ms['location']} {ms['snippet']}")
628
+
629
+ # Fix suggestion(s)
630
+ for suggestion in f["suggestions"]:
631
+ click.echo(f" Fix: {suggestion}")
632
+
633
+ click.echo()