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,967 @@
1
+ """Detect implicit N+1 I/O patterns across ORM frameworks.
2
+
3
+ Unlike ``roam algo``'s explicit "I/O in loop" detector, this command finds
4
+ **implicit** N+1 patterns: computed properties on data classes that trigger
5
+ I/O (DB queries, HTTP calls) when the object is serialized in a collection.
6
+
7
+ Supported frameworks:
8
+ - Laravel/Eloquent: $appends accessors → relationship lazy loading
9
+ - Django: @property → related manager access
10
+ - Rails/ActiveRecord: methods → association access
11
+ - SQLAlchemy: @hybrid_property → relationship access
12
+ - JPA/Hibernate: @Transient → entity association access
13
+ - Generic: any collection-iterable class with I/O in computed properties
14
+
15
+ Detection algorithm:
16
+ 1. Find "data classes" (ORM models, entities, DTOs)
17
+ 2. Find computed/virtual properties on those classes
18
+ 3. Trace call chains from properties to I/O operations
19
+ 4. Check if the class appears in collection/pagination contexts
20
+ 5. Check for eager-loading / prefetch configuration
21
+ 6. Flag: property triggers I/O per-instance without batch loading
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import os
27
+ import re
28
+ from collections import defaultdict
29
+
30
+ import click
31
+
32
+ from roam.commands.resolve import ensure_index
33
+ from roam.db.connection import open_db
34
+ from roam.output.formatter import json_envelope, loc, to_json
35
+
36
+ # ---------------------------------------------------------------------------
37
+ # Framework detection helpers
38
+ # ---------------------------------------------------------------------------
39
+
40
+ # Patterns that identify ORM model classes by parent class or trait
41
+ _MODEL_PARENTS = {
42
+ # Laravel / Eloquent
43
+ "Model",
44
+ "Eloquent",
45
+ "Authenticatable",
46
+ # Django
47
+ "models.Model",
48
+ "Model",
49
+ # Rails / ActiveRecord
50
+ "ApplicationRecord",
51
+ "ActiveRecord::Base",
52
+ # SQLAlchemy
53
+ "Base",
54
+ "DeclarativeBase",
55
+ # JPA / Hibernate
56
+ "Serializable",
57
+ # TypeScript ORMs
58
+ "BaseEntity",
59
+ "Entity",
60
+ }
61
+
62
+ # Symbols that indicate "this class is a data/model class"
63
+ _MODEL_INDICATORS = {
64
+ # Laravel
65
+ "$fillable",
66
+ "$guarded",
67
+ "$casts",
68
+ "$appends",
69
+ "$table",
70
+ "$hidden",
71
+ # Django
72
+ "objects",
73
+ "Meta",
74
+ "DoesNotExist",
75
+ # Rails
76
+ "has_many",
77
+ "belongs_to",
78
+ "has_one",
79
+ "scope",
80
+ # SQLAlchemy
81
+ "__tablename__",
82
+ "Column",
83
+ "relationship",
84
+ # JPA
85
+ "@Entity",
86
+ "@Table",
87
+ }
88
+
89
+ # Property/accessor patterns per framework
90
+ _ACCESSOR_PATTERNS = {
91
+ # Laravel: get{Name}Attribute methods
92
+ "laravel": re.compile(r"^get(\w+)Attribute$"),
93
+ # Django: properties (detected by kind='property' or @property decorator)
94
+ "django": re.compile(r".*"), # any property on a Model
95
+ # Rails: instance methods that access associations
96
+ "rails": re.compile(r".*"),
97
+ }
98
+
99
+ # Relationship access patterns (method calls that trigger lazy loading)
100
+ _RELATIONSHIP_CALLS = {
101
+ # Laravel Eloquent
102
+ "hasMany",
103
+ "hasOne",
104
+ "belongsTo",
105
+ "belongsToMany",
106
+ "morphMany",
107
+ "morphOne",
108
+ "morphTo",
109
+ "morphToMany",
110
+ # Django ORM
111
+ "all",
112
+ "filter",
113
+ "get",
114
+ "first",
115
+ "last",
116
+ "count",
117
+ "exists",
118
+ "select_related",
119
+ "prefetch_related",
120
+ # Rails ActiveRecord
121
+ "where",
122
+ "find",
123
+ "find_by",
124
+ "pluck",
125
+ # SQLAlchemy
126
+ "query",
127
+ "filter_by",
128
+ # Generic DB
129
+ "load",
130
+ "fetch",
131
+ "findOrFail",
132
+ "find",
133
+ }
134
+
135
+ # I/O operations that indicate a DB query or network call
136
+ _IO_INDICATORS = {
137
+ # Database
138
+ "query",
139
+ "execute",
140
+ "select",
141
+ "where",
142
+ "find",
143
+ "findOrFail",
144
+ "first",
145
+ "get",
146
+ "all",
147
+ "count",
148
+ "exists",
149
+ "pluck",
150
+ "save",
151
+ "create",
152
+ "update",
153
+ "delete",
154
+ # HTTP
155
+ "fetch",
156
+ "request",
157
+ "get",
158
+ "post",
159
+ "put",
160
+ # File
161
+ "fopen",
162
+ "file_get_contents",
163
+ "read",
164
+ "readFile",
165
+ }
166
+
167
+ # Eager loading configuration patterns
168
+ _EAGER_LOAD_PATTERNS = {
169
+ "with",
170
+ "eagerLoad",
171
+ "eager_load",
172
+ "select_related",
173
+ "prefetch_related",
174
+ "includes",
175
+ "eager_load_relations",
176
+ "joinedload",
177
+ "subqueryload",
178
+ "JOIN FETCH",
179
+ }
180
+
181
+
182
+ def _is_test_path(path: str) -> bool:
183
+ p = path.replace("\\", "/").lower()
184
+ base = os.path.basename(p)
185
+ if base.startswith("test_") or base.endswith("_test.py"):
186
+ return True
187
+ if "tests/" in p or "test/" in p or "__tests__/" in p or "spec/" in p:
188
+ return True
189
+ return False
190
+
191
+
192
+ def _detect_framework(conn) -> str:
193
+ """Detect the primary ORM framework from file languages and symbol names."""
194
+ lang_counts = {}
195
+ for r in conn.execute("SELECT language, COUNT(*) as cnt FROM files GROUP BY language").fetchall():
196
+ lang_counts[r["language"]] = r["cnt"]
197
+
198
+ # Check for framework-specific symbols (PHP parser stores without $ prefix)
199
+ laravel_signals = conn.execute(
200
+ "SELECT COUNT(*) as cnt FROM symbols WHERE name IN "
201
+ "('fillable', 'appends', 'casts', 'guarded', "
202
+ " '$fillable', '$appends', '$casts', '$guarded')"
203
+ ).fetchone()["cnt"]
204
+
205
+ django_signals = conn.execute(
206
+ "SELECT COUNT(*) as cnt FROM symbols WHERE name IN ('objects', 'Meta', '__tablename__')"
207
+ ).fetchone()["cnt"]
208
+
209
+ if lang_counts.get("php", 0) > 10 and laravel_signals > 0:
210
+ return "laravel"
211
+ if lang_counts.get("python", 0) > 10 and django_signals > 0:
212
+ return "django"
213
+ if lang_counts.get("ruby", 0) > 10:
214
+ return "rails"
215
+ if lang_counts.get("java", 0) > 10:
216
+ return "jpa"
217
+ return "generic"
218
+
219
+
220
+ # ---------------------------------------------------------------------------
221
+ # Core detection: find model classes and their computed properties
222
+ # ---------------------------------------------------------------------------
223
+
224
+
225
+ def _find_model_classes(conn):
226
+ """Find all ORM model / data classes in the codebase.
227
+
228
+ Uses two strategies since some parsers (PHP) don't set parent_id:
229
+ 1. Classes with indicator children (via parent_id OR same-file line range)
230
+ 2. Classes in Model/Entity directories
231
+ """
232
+ model_classes = {}
233
+
234
+ # Strategy 1a: Classes with children via parent_id
235
+ rows = conn.execute(
236
+ "SELECT DISTINCT parent.id, parent.name, parent.qualified_name, "
237
+ "parent.kind, f.path as file_path, parent.file_id, "
238
+ "parent.line_start, parent.line_end "
239
+ "FROM symbols parent "
240
+ "JOIN files f ON parent.file_id = f.id "
241
+ "JOIN symbols child ON child.parent_id = parent.id "
242
+ "WHERE parent.kind = 'class' "
243
+ "AND child.name IN ('fillable', 'appends', 'casts', 'guarded', "
244
+ " 'table', 'hidden', 'connection', "
245
+ " '$fillable', '$appends', '$casts', '$guarded', "
246
+ " '$table', '$hidden', '$connection', "
247
+ " '__tablename__', 'Meta') "
248
+ ).fetchall()
249
+ for r in rows:
250
+ model_classes[r["id"]] = dict(r)
251
+
252
+ # Strategy 1b: Classes with indicator properties in same file/line range
253
+ # (for parsers like PHP that don't set parent_id)
254
+ indicator_names = (
255
+ "'fillable', 'appends', 'casts', 'guarded', 'table', 'hidden', "
256
+ "'connection', '$fillable', '$appends', '$casts', '$guarded', "
257
+ "'$table', '$hidden', '$connection', '__tablename__', 'Meta'"
258
+ )
259
+ classes = conn.execute(
260
+ "SELECT s.id, s.name, s.qualified_name, s.kind, "
261
+ "f.path as file_path, s.file_id, s.line_start, s.line_end "
262
+ "FROM symbols s "
263
+ "JOIN files f ON s.file_id = f.id "
264
+ "WHERE s.kind = 'class' AND s.line_end IS NOT NULL"
265
+ ).fetchall()
266
+
267
+ for cls in classes:
268
+ if cls["id"] in model_classes:
269
+ continue
270
+ # Check if any indicator property exists in the same file within class line range
271
+ indicator = conn.execute(
272
+ f"SELECT 1 FROM symbols WHERE file_id = ? "
273
+ f"AND kind = 'property' AND name IN ({indicator_names}) "
274
+ f"AND line_start >= ? AND line_start <= ? LIMIT 1",
275
+ (cls["file_id"], cls["line_start"], cls["line_end"] or 999999),
276
+ ).fetchone()
277
+ if indicator:
278
+ model_classes[cls["id"]] = dict(cls)
279
+
280
+ # Strategy 2: Classes in Model/Entity directories
281
+ suffix_rows = conn.execute(
282
+ "SELECT s.id, s.name, s.qualified_name, s.kind, "
283
+ "f.path as file_path, s.file_id, s.line_start, s.line_end "
284
+ "FROM symbols s "
285
+ "JOIN files f ON s.file_id = f.id "
286
+ "WHERE s.kind = 'class' "
287
+ "AND (f.path LIKE '%/Models/%' OR f.path LIKE '%/models/%' "
288
+ " OR f.path LIKE '%/Entity/%' OR f.path LIKE '%/entities/%')"
289
+ ).fetchall()
290
+ for r in suffix_rows:
291
+ if r["id"] not in model_classes:
292
+ model_classes[r["id"]] = dict(r)
293
+
294
+ return model_classes
295
+
296
+
297
+ def _find_appends_properties(conn, model_id, model_info):
298
+ """Find $appends array entries for a Laravel model.
299
+
300
+ Returns list of appended attribute names (e.g., ['full_name', 'is_admin']).
301
+ Handles both parent_id-linked and flat (same-file line range) symbol structures.
302
+ If default_value is not captured by the parser, reads from source file.
303
+ """
304
+ # Try parent_id first
305
+ appends_sym = conn.execute(
306
+ "SELECT s.id, s.default_value, s.line_start, s.line_end, f.path as file_path "
307
+ "FROM symbols s JOIN files f ON s.file_id = f.id "
308
+ "WHERE s.parent_id = ? AND s.name IN ('appends', '$appends')",
309
+ (model_id,),
310
+ ).fetchone()
311
+
312
+ # Fallback: same file, within class line range
313
+ if not appends_sym:
314
+ appends_sym = conn.execute(
315
+ "SELECT s.id, s.default_value, s.line_start, s.line_end, f.path as file_path "
316
+ "FROM symbols s JOIN files f ON s.file_id = f.id "
317
+ "WHERE s.file_id = (SELECT file_id FROM symbols WHERE id = ?) "
318
+ "AND s.name IN ('appends', '$appends') "
319
+ "AND s.kind = 'property' "
320
+ "AND s.line_start >= ? AND s.line_start <= ?",
321
+ (model_id, model_info["line_start"], model_info.get("line_end") or 999999),
322
+ ).fetchone()
323
+
324
+ if not appends_sym:
325
+ return []
326
+
327
+ # If default_value is captured, use it
328
+ if appends_sym["default_value"]:
329
+ return re.findall(r"['\"](\w+)['\"]", appends_sym["default_value"])
330
+
331
+ # Otherwise read from source file
332
+ file_path = appends_sym["file_path"]
333
+ line_start = appends_sym["line_start"]
334
+ line_end = appends_sym["line_end"] or line_start + 20
335
+
336
+ # Resolve to absolute path from project root
337
+ from roam.db.connection import find_project_root
338
+
339
+ root = find_project_root()
340
+ abs_path = root / file_path if root else None
341
+
342
+ if abs_path and abs_path.is_file():
343
+ try:
344
+ with open(abs_path, encoding="utf-8", errors="replace") as fh:
345
+ lines = fh.readlines()
346
+ # Extract the appends array from source (line_start is 1-indexed)
347
+ snippet = "".join(lines[max(0, line_start - 1) : line_end])
348
+ return re.findall(r"['\"](\w+)['\"]", snippet)
349
+ except OSError:
350
+ pass
351
+
352
+ return []
353
+
354
+
355
+ def _find_accessor_methods(conn, model_id, model_info, appended_names):
356
+ """Find accessor methods for appended attributes.
357
+
358
+ For Laravel: get{StudlyName}Attribute methods.
359
+ Returns list of (accessor_symbol_row, appended_name) tuples.
360
+ Handles both parent_id-linked and flat symbol structures.
361
+ """
362
+ accessors = []
363
+
364
+ # Get all methods in this class (try parent_id first, then line range)
365
+ methods = conn.execute(
366
+ "SELECT s.id, s.name, s.qualified_name, s.kind, "
367
+ "f.path as file_path, s.line_start, s.line_end "
368
+ "FROM symbols s "
369
+ "JOIN files f ON s.file_id = f.id "
370
+ "WHERE s.parent_id = ? AND s.kind = 'method'",
371
+ (model_id,),
372
+ ).fetchall()
373
+
374
+ if not methods:
375
+ # Fallback: same file, within class line range
376
+ methods = conn.execute(
377
+ "SELECT s.id, s.name, s.qualified_name, s.kind, "
378
+ "f.path as file_path, s.line_start, s.line_end "
379
+ "FROM symbols s "
380
+ "JOIN files f ON s.file_id = f.id "
381
+ "WHERE s.file_id = (SELECT file_id FROM symbols WHERE id = ?) "
382
+ "AND s.kind = 'method' "
383
+ "AND s.line_start >= ? AND s.line_start <= ?",
384
+ (model_id, model_info["line_start"], model_info.get("line_end") or 999999),
385
+ ).fetchall()
386
+
387
+ # Build lookup: snake_case appended name → StudlyCase accessor name
388
+ for attr_name in appended_names:
389
+ # Convert snake_case to StudlyCase: "full_name" → "FullName"
390
+ studly = "".join(part.capitalize() for part in attr_name.split("_"))
391
+ accessor_name = f"get{studly}Attribute"
392
+
393
+ for m in methods:
394
+ if m["name"] == accessor_name:
395
+ accessors.append((dict(m), attr_name))
396
+ break
397
+
398
+ return accessors
399
+
400
+
401
+ def _trace_accessor_io(conn, accessor_id, accessor_info, model_methods):
402
+ """Trace an accessor method to see if it triggers I/O.
403
+
404
+ Uses two strategies:
405
+ 1. Edge-based: follow outgoing edges to relationship/query methods
406
+ 2. Source-based: pattern-match $this->relation in accessor source code
407
+ (needed for PHP where property access doesn't generate edges)
408
+
409
+ Returns list of (relationship_name, io_type) tuples found.
410
+ """
411
+ io_chains = []
412
+ model_method_names = {m["name"] for m in model_methods}
413
+
414
+ # --- Strategy 1: Edge-based tracing ---
415
+ callees = conn.execute(
416
+ "SELECT t.id, t.name, t.qualified_name, t.kind, "
417
+ "f.path as file_path, e.kind as edge_kind "
418
+ "FROM edges e "
419
+ "JOIN symbols t ON e.target_id = t.id "
420
+ "JOIN files f ON t.file_id = f.id "
421
+ "WHERE e.source_id = ?",
422
+ (accessor_id,),
423
+ ).fetchall()
424
+
425
+ for callee in callees:
426
+ name = callee["name"]
427
+ if name in model_method_names and callee["kind"] == "method":
428
+ sub_callees = conn.execute(
429
+ "SELECT t.name FROM edges e JOIN symbols t ON e.target_id = t.id WHERE e.source_id = ?",
430
+ (callee["id"],),
431
+ ).fetchall()
432
+ sub_names = {r["name"] for r in sub_callees}
433
+ rel_methods = sub_names & {
434
+ "hasMany",
435
+ "hasOne",
436
+ "belongsTo",
437
+ "belongsToMany",
438
+ "morphMany",
439
+ "morphOne",
440
+ "morphTo",
441
+ "morphToMany",
442
+ "hasManyThrough",
443
+ }
444
+ if rel_methods:
445
+ io_chains.append((name, f"relationship ({', '.join(rel_methods)})"))
446
+ continue
447
+
448
+ if name in (
449
+ "first",
450
+ "get",
451
+ "exists",
452
+ "count",
453
+ "pluck",
454
+ "find",
455
+ "findOrFail",
456
+ "all",
457
+ "orderBy",
458
+ "where",
459
+ ):
460
+ io_chains.append((name, "query builder"))
461
+
462
+ # --- Strategy 2: Source-based pattern matching ---
463
+ # Read accessor source and look for $this->relationName patterns
464
+ if not io_chains:
465
+ file_path = accessor_info.get("file_path", "")
466
+ line_start = accessor_info.get("line_start", 0)
467
+ line_end = accessor_info.get("line_end") or line_start + 30
468
+
469
+ from roam.db.connection import find_project_root
470
+
471
+ root = find_project_root()
472
+ abs_path = root / file_path if root else None
473
+
474
+ if abs_path and abs_path.is_file():
475
+ try:
476
+ with open(abs_path, encoding="utf-8", errors="replace") as fh:
477
+ lines = fh.readlines()
478
+ snippet = "".join(lines[max(0, line_start - 1) : line_end])
479
+
480
+ # Pattern: $this->someRelation (property access that triggers lazy load)
481
+ # Matches: $this->branch, $this->lines, $this->attachments()
482
+ this_accesses = re.findall(
483
+ r"\$this->(\w+?)(?:\s*->|\s*\?->|(?:\(\))\s*->|\s*;|\s*\))",
484
+ snippet,
485
+ )
486
+
487
+ # Also catch: $this->relation()->method() pattern
488
+ this_method_calls = re.findall(
489
+ r"\$this->(\w+)\(\)",
490
+ snippet,
491
+ )
492
+
493
+ # Helper calls to skip (not relationships)
494
+ _SKIP_METHODS = {
495
+ "relationLoaded",
496
+ "getAttribute",
497
+ "setAttribute",
498
+ "getKey",
499
+ "toArray",
500
+ "toJson",
501
+ }
502
+
503
+ # Check which accessed names are relationship methods on the model
504
+ # by verifying the method body contains a relationship definition
505
+ for accessed in set(this_accesses + this_method_calls):
506
+ if accessed in _SKIP_METHODS:
507
+ continue
508
+ if accessed not in model_method_names:
509
+ continue
510
+
511
+ # Verify this method is actually a relationship (not just a helper)
512
+ # by reading its source and checking for relationship calls
513
+ method_sym = None
514
+ for m in model_methods:
515
+ if m["name"] == accessed:
516
+ method_sym = m
517
+ break
518
+ if not method_sym:
519
+ continue
520
+
521
+ # Read the method source to check for relationship definitions
522
+ m_sym_full = conn.execute(
523
+ "SELECT s.line_start, s.line_end FROM symbols s WHERE s.id = ?",
524
+ (method_sym["id"],),
525
+ ).fetchone()
526
+ if m_sym_full:
527
+ m_start = max(0, m_sym_full["line_start"] - 1)
528
+ m_end = m_sym_full["line_end"] or m_start + 15
529
+ method_snippet = "".join(lines[m_start:m_end])
530
+ # Check if method body contains relationship calls
531
+ _REL_CALLS = (
532
+ "hasMany",
533
+ "hasOne",
534
+ "belongsTo",
535
+ "belongsToMany",
536
+ "morphMany",
537
+ "morphOne",
538
+ "morphTo",
539
+ "morphToMany",
540
+ "hasManyThrough",
541
+ "hasOneThrough",
542
+ )
543
+ if any(rc in method_snippet for rc in _REL_CALLS):
544
+ io_chains.append((accessed, "lazy-load relationship"))
545
+ # Also check if it calls query builder methods
546
+ elif any(
547
+ qb in method_snippet
548
+ for qb in (
549
+ "->first()",
550
+ "->get()",
551
+ "->exists()",
552
+ "->count()",
553
+ "->pluck()",
554
+ )
555
+ ):
556
+ io_chains.append((accessed, "query builder"))
557
+
558
+ except OSError:
559
+ pass
560
+
561
+ return io_chains
562
+
563
+
564
+ def _find_eager_loads(conn, model_name):
565
+ """Find eager loading configuration for a model.
566
+
567
+ Checks:
568
+ 1. Model $with property (auto-eager-load on every query)
569
+ 2. Resource config files (Laravel: ->eagerLoad([...]) in config/resources.php)
570
+ 3. Controller ::with() calls
571
+
572
+ For sources where the parser doesn't capture method chains as symbols,
573
+ falls back to reading source files and pattern matching.
574
+
575
+ Returns set of relationship names that are eager loaded.
576
+ """
577
+ eager_loaded = set()
578
+
579
+ from roam.db.connection import find_project_root
580
+
581
+ root = find_project_root()
582
+
583
+ # --- 1. Check $with property on the model ---
584
+ with_sym = conn.execute(
585
+ "SELECT s.default_value, s.line_start, s.line_end, f.path as file_path "
586
+ "FROM symbols s JOIN files f ON s.file_id = f.id "
587
+ "WHERE s.name IN ('with', '$with') AND s.kind = 'property' "
588
+ "AND f.path LIKE ?",
589
+ (f"%{model_name}.php",),
590
+ ).fetchone()
591
+
592
+ if with_sym:
593
+ if with_sym["default_value"]:
594
+ eager_loaded.update(re.findall(r"['\"](\w+)['\"]", with_sym["default_value"]))
595
+ elif root:
596
+ # Read from source
597
+ abs_path = root / with_sym["file_path"]
598
+ if abs_path.is_file():
599
+ try:
600
+ with open(abs_path, encoding="utf-8", errors="replace") as fh:
601
+ lines = fh.readlines()
602
+ start = max(0, with_sym["line_start"] - 1)
603
+ end = with_sym["line_end"] or start + 10
604
+ snippet = "".join(lines[start:end])
605
+ eager_loaded.update(re.findall(r"['\"](\w+)['\"]", snippet))
606
+ except OSError:
607
+ pass
608
+
609
+ # --- 2. Check resource config files for eagerLoad ---
610
+ config_files = conn.execute(
611
+ "SELECT f.path FROM files f WHERE f.path LIKE '%config/resources.php' OR f.path LIKE '%config/resources/%'"
612
+ ).fetchall()
613
+
614
+ # Convert model class name to resource key pattern
615
+ # e.g., "Post" → look for Post::class or 'posts' near eagerLoad
616
+ model_lower = model_name.lower()
617
+
618
+ for cf in config_files:
619
+ if not root:
620
+ continue
621
+ abs_path = root / cf["path"]
622
+ if not abs_path.is_file():
623
+ continue
624
+ try:
625
+ content = abs_path.read_text(encoding="utf-8", errors="replace")
626
+ # Find eagerLoad([...]) calls and extract relationship names
627
+ # Pattern: ->eagerLoad(['rel1', 'rel2', ...])
628
+ for match in re.finditer(
629
+ r"->eagerLoad\(\s*\[(.*?)\]\s*\)",
630
+ content,
631
+ re.DOTALL,
632
+ ):
633
+ # Check if this eagerLoad is near the model reference
634
+ # Look backwards from match for the model class name
635
+ start = max(0, match.start() - 500)
636
+ context = content[start : match.end()]
637
+ if model_name in context or f"{model_name}::class" in context or model_lower in context.lower():
638
+ rels = re.findall(r"['\"](\w+)['\"]", match.group(1))
639
+ eager_loaded.update(rels)
640
+ except OSError:
641
+ pass
642
+
643
+ # --- 3. Check controller with() calls ---
644
+ # Look for Model::with(['rel']) or ->with(['rel']) near model references
645
+ controller_files = conn.execute(
646
+ "SELECT f.path FROM files f WHERE f.path LIKE '%Controller%' AND f.path LIKE '%.php'"
647
+ ).fetchall()
648
+
649
+ for cf in controller_files:
650
+ if not root:
651
+ continue
652
+ abs_path = root / cf["path"]
653
+ if not abs_path.is_file():
654
+ continue
655
+ try:
656
+ content = abs_path.read_text(encoding="utf-8", errors="replace")
657
+ if model_name not in content:
658
+ continue
659
+ # Find ::with(['rel1', 'rel2']) near model name
660
+ for match in re.finditer(
661
+ rf"{model_name}::with\(\s*\[(.*?)\]\s*\)",
662
+ content,
663
+ re.DOTALL,
664
+ ):
665
+ rels = re.findall(r"['\"](\w+)['\"]", match.group(1))
666
+ eager_loaded.update(rels)
667
+ except OSError:
668
+ pass
669
+
670
+ return eager_loaded
671
+
672
+
673
+ def _find_collection_contexts(conn, model_id, model_name):
674
+ """Check if a model is used in collection/pagination contexts.
675
+
676
+ Returns list of locations where the model is paginated or collected.
677
+ """
678
+ contexts = []
679
+
680
+ # Find references to this model class
681
+ refs = conn.execute(
682
+ "SELECT s.name, s.qualified_name, s.kind, f.path as file_path, "
683
+ "s.line_start, e.kind as edge_kind "
684
+ "FROM edges e "
685
+ "JOIN symbols s ON e.source_id = s.id "
686
+ "JOIN files f ON s.file_id = f.id "
687
+ "WHERE e.target_id = ?",
688
+ (model_id,),
689
+ ).fetchall()
690
+
691
+ for ref in refs:
692
+ path_lower = ref["file_path"].replace("\\", "/").lower()
693
+ # Controller files are collection contexts
694
+ if "controller" in path_lower or "resource" in path_lower:
695
+ contexts.append(
696
+ {
697
+ "location": loc(ref["file_path"], ref["line_start"]),
698
+ "type": "controller",
699
+ "symbol": ref["qualified_name"] or ref["name"],
700
+ }
701
+ )
702
+ # Service files with pagination
703
+ if "service" in path_lower:
704
+ contexts.append(
705
+ {
706
+ "location": loc(ref["file_path"], ref["line_start"]),
707
+ "type": "service",
708
+ "symbol": ref["qualified_name"] or ref["name"],
709
+ }
710
+ )
711
+
712
+ return contexts
713
+
714
+
715
+ # ---------------------------------------------------------------------------
716
+ # Main analysis: run all detection passes
717
+ # ---------------------------------------------------------------------------
718
+
719
+
720
+ def analyze_n1(conn, confidence_filter=None):
721
+ """Run full N+1 implicit I/O analysis.
722
+
723
+ Returns list of finding dicts with:
724
+ - model_name, model_location
725
+ - accessor_name, accessor_location
726
+ - appended_attribute
727
+ - relationship_chain (what I/O it triggers)
728
+ - eager_loaded (bool — is this relationship pre-loaded?)
729
+ - collection_contexts (where the model is used in collections)
730
+ - confidence, severity
731
+ - suggestion
732
+ """
733
+ framework = _detect_framework(conn)
734
+ findings = []
735
+
736
+ models = _find_model_classes(conn)
737
+ if not models:
738
+ return findings, framework
739
+
740
+ for model_id, model_info in models.items():
741
+ if _is_test_path(model_info["file_path"]):
742
+ continue
743
+
744
+ model_name = model_info["name"]
745
+
746
+ # Get all methods on this model (for relationship detection)
747
+ # Try parent_id first, then fall back to same-file line range
748
+ model_methods = conn.execute(
749
+ "SELECT s.id, s.name, s.kind FROM symbols s WHERE s.parent_id = ? AND s.kind = 'method'",
750
+ (model_id,),
751
+ ).fetchall()
752
+ if not model_methods:
753
+ model_methods = conn.execute(
754
+ "SELECT s.id, s.name, s.kind FROM symbols s "
755
+ "WHERE s.file_id = ? AND s.kind = 'method' "
756
+ "AND s.line_start >= ? AND s.line_start <= ?",
757
+ (
758
+ model_info.get("file_id")
759
+ or conn.execute("SELECT file_id FROM symbols WHERE id = ?", (model_id,)).fetchone()["file_id"],
760
+ model_info["line_start"],
761
+ model_info.get("line_end") or 999999,
762
+ ),
763
+ ).fetchall()
764
+
765
+ # Step 1: Find $appends / virtual properties
766
+ appended = _find_appends_properties(conn, model_id, model_info)
767
+ if not appended:
768
+ continue
769
+
770
+ # Step 2: Find accessor methods for each appended attribute
771
+ accessors = _find_accessor_methods(conn, model_id, model_info, appended)
772
+ if not accessors:
773
+ continue
774
+
775
+ # Step 3: Find what's already eager loaded
776
+ eager_loaded = _find_eager_loads(conn, model_name)
777
+
778
+ # Step 4: Find collection contexts
779
+ collection_ctxs = _find_collection_contexts(conn, model_id, model_name)
780
+
781
+ # Step 5: For each accessor, trace I/O chains
782
+ for accessor_info, attr_name in accessors:
783
+ io_chains = _trace_accessor_io(conn, accessor_info["id"], accessor_info, model_methods)
784
+
785
+ if not io_chains:
786
+ continue
787
+
788
+ # Check if the relationships found are eager loaded
789
+ for rel_name, io_type in io_chains:
790
+ is_eager = rel_name in eager_loaded
791
+
792
+ if is_eager:
793
+ continue # This one is handled, skip it
794
+
795
+ # Determine confidence
796
+ confidence = "medium"
797
+ if collection_ctxs:
798
+ confidence = "high" # Used in collection context = definitely N+1
799
+ if not collection_ctxs:
800
+ confidence = "low" # No collection context found = might be OK
801
+
802
+ # Determine severity based on likely query count
803
+ severity = "per-item query on serialization"
804
+
805
+ suggestion = _build_suggestion(framework, model_name, rel_name, attr_name, io_type)
806
+
807
+ findings.append(
808
+ {
809
+ "model_name": model_info["qualified_name"] or model_name,
810
+ "model_location": loc(model_info["file_path"], model_info["line_start"]),
811
+ "accessor_name": accessor_info["name"],
812
+ "accessor_location": loc(accessor_info["file_path"], accessor_info["line_start"]),
813
+ "appended_attribute": attr_name,
814
+ "relationship": rel_name,
815
+ "io_type": io_type,
816
+ "eager_loaded": False,
817
+ "confidence": confidence,
818
+ "severity": severity,
819
+ "collection_contexts": collection_ctxs[:3], # Top 3
820
+ "suggestion": suggestion,
821
+ }
822
+ )
823
+
824
+ # Apply confidence filter
825
+ if confidence_filter:
826
+ findings = [f for f in findings if f["confidence"] == confidence_filter]
827
+
828
+ return findings, framework
829
+
830
+
831
+ def _build_suggestion(framework, model_name, rel_name, attr_name, io_type):
832
+ """Build a framework-specific fix suggestion."""
833
+ if framework == "laravel":
834
+ return (
835
+ f"Add '{rel_name}' to eagerLoad in config/resources.php, "
836
+ f"or add '{rel_name}' to $with on {model_name}, "
837
+ f"or use ::with('{rel_name}') in the controller query"
838
+ )
839
+ if framework == "django":
840
+ return f"Add .select_related('{rel_name}') or .prefetch_related('{rel_name}') to the QuerySet"
841
+ if framework == "rails":
842
+ return f"Add .includes(:{rel_name}) or .eager_load(:{rel_name}) to the ActiveRecord query"
843
+ return f"Pre-load '{rel_name}' data before iterating the collection to avoid per-item I/O"
844
+
845
+
846
+ # ---------------------------------------------------------------------------
847
+ # CLI command
848
+ # ---------------------------------------------------------------------------
849
+
850
+
851
+ @click.command("n1")
852
+ @click.option(
853
+ "--confidence",
854
+ "confidence_filter",
855
+ default=None,
856
+ type=click.Choice(["high", "medium", "low"], case_sensitive=False),
857
+ help="Filter by confidence level",
858
+ )
859
+ @click.option("--limit", "-n", default=30, help="Max findings to show")
860
+ @click.option("--verbose", "-v", is_flag=True, help="Show I/O trace chains")
861
+ @click.pass_context
862
+ def n1_cmd(ctx, confidence_filter, limit, verbose):
863
+ """Detect implicit N+1 I/O patterns in ORM models.
864
+
865
+ Finds computed properties on model classes that trigger database
866
+ queries when the model is serialized in a collection (pagination,
867
+ API responses, etc.).
868
+
869
+ Unlike 'roam algo' which finds explicit loops with I/O, this
870
+ command finds IMPLICIT N+1 patterns where the loop is hidden
871
+ inside the ORM's serialization layer.
872
+
873
+ Supports: Laravel/Eloquent, Django, Rails, SQLAlchemy, JPA.
874
+
875
+ \b
876
+ Examples:
877
+ roam n1 # Full scan
878
+ roam n1 --confidence high # Only high-confidence findings
879
+ roam n1 -v # Show I/O trace details
880
+ """
881
+ json_mode = ctx.obj.get("json") if ctx.obj else False
882
+ ensure_index()
883
+
884
+ with open_db(readonly=True) as conn:
885
+ findings, framework = analyze_n1(conn, confidence_filter)
886
+
887
+ # Sort: high first
888
+ _conf_order = {"high": 0, "medium": 1, "low": 2}
889
+ findings.sort(key=lambda f: _conf_order.get(f["confidence"], 9))
890
+
891
+ # Apply limit
892
+ truncated = len(findings) > limit
893
+ findings = findings[:limit]
894
+
895
+ # Confidence counts
896
+ by_confidence = defaultdict(int)
897
+ for f in findings:
898
+ by_confidence[f["confidence"]] += 1
899
+
900
+ total = len(findings)
901
+ conf_parts = [f"{by_confidence[c]} {c}" for c in ("high", "medium", "low") if by_confidence.get(c)]
902
+ conf_str = ", ".join(conf_parts) if conf_parts else "none"
903
+
904
+ verdict = (
905
+ f"{total} implicit N+1 pattern{'s' if total != 1 else ''} found ({conf_str})"
906
+ if total
907
+ else "No implicit N+1 patterns detected"
908
+ )
909
+
910
+ # --- JSON output ---
911
+ if json_mode:
912
+ click.echo(
913
+ to_json(
914
+ json_envelope(
915
+ "n1",
916
+ summary={
917
+ "verdict": verdict,
918
+ "total": total,
919
+ "framework": framework,
920
+ "by_confidence": dict(by_confidence),
921
+ "truncated": truncated,
922
+ },
923
+ findings=findings,
924
+ )
925
+ )
926
+ )
927
+ return
928
+
929
+ # --- Text output ---
930
+ click.echo(f"VERDICT: {verdict}")
931
+ if framework != "generic":
932
+ click.echo(f"Framework: {framework}")
933
+ if not findings:
934
+ return
935
+
936
+ click.echo()
937
+
938
+ # Group by model
939
+ by_model = defaultdict(list)
940
+ for f in findings:
941
+ by_model[f["model_name"]].append(f)
942
+
943
+ for model_name, model_findings in by_model.items():
944
+ model_loc = model_findings[0]["model_location"]
945
+ click.echo(f"{model_name} {model_loc}")
946
+
947
+ for f in model_findings:
948
+ conf = f["confidence"]
949
+ attr = f["appended_attribute"]
950
+ rel = f["relationship"]
951
+ accessor = f["accessor_name"]
952
+ acc_loc = f["accessor_location"]
953
+
954
+ click.echo(f" [{conf}] ${attr}")
955
+ click.echo(f" Accessor: {accessor} {acc_loc}")
956
+ click.echo(f" Triggers: {rel} ({f['io_type']})")
957
+ click.echo(f" Fix: {f['suggestion']}")
958
+
959
+ if verbose and f["collection_contexts"]:
960
+ click.echo(" Used in:")
961
+ for ctx_info in f["collection_contexts"]:
962
+ click.echo(f" {ctx_info['type']}: {ctx_info['location']}")
963
+
964
+ click.echo()
965
+
966
+ if truncated:
967
+ click.echo(f" (showing {limit} of more findings, use --limit to see more)")