rails-hyperdrive-layered-rails 0.1.0

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 (62) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +30 -0
  3. data/README.md +89 -0
  4. data/UPSTREAM +4 -0
  5. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/SKILL.md.erb +315 -0
  6. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/examples/authorization-to-policy.md +79 -0
  7. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/examples/callbacks-to-service.md +72 -0
  8. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/examples/complex-input-to-form-object.md +119 -0
  9. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/examples/current-from-model.md +63 -0
  10. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/examples/god-object-decomposition.md +81 -0
  11. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/examples/implicit-to-explicit-state-machine.md +77 -0
  12. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/examples/query-to-query-object.md +63 -0
  13. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/examples/view-logic-to-presenter.md +60 -0
  14. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/anti-patterns/callbacks.md +114 -0
  15. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/anti-patterns/concerns.md +92 -0
  16. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/anti-patterns/helpers.md +66 -0
  17. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/anti-patterns/jobs.md +71 -0
  18. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/anti-patterns/layer-violations.md +176 -0
  19. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/anti-patterns/service-objects.md +131 -0
  20. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/anti-patterns/testing.md +37 -0
  21. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/core/architecture-layers.md +204 -0
  22. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/core/extraction-signals.md +314 -0
  23. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/core/specification-test.md +229 -0
  24. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/gems/action-policy.md +437 -0
  25. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/gems/active-agent.md +275 -0
  26. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/gems/active-delivery.md +221 -0
  27. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/gems/active-job-performs.md +171 -0
  28. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/gems/alba.md +257 -0
  29. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/gems/anyway-config.md +212 -0
  30. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/gems/rubanok.md +246 -0
  31. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/gems/view-component.md +223 -0
  32. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/gems/workflow.md +305 -0
  33. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/patterns/collaborator-objects.md +209 -0
  34. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/patterns/concerns.md +381 -0
  35. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/patterns/filter-objects.md +222 -0
  36. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/patterns/form-objects.md +267 -0
  37. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/patterns/policy-objects.md +298 -0
  38. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/patterns/presenters.md +257 -0
  39. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/patterns/query-objects.md +208 -0
  40. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/patterns/repositories.md +382 -0
  41. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/patterns/serializers.md +256 -0
  42. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/patterns/service-objects.md +170 -0
  43. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/patterns/state-machines.md +368 -0
  44. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/patterns/value-objects.md +267 -0
  45. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/topics/ai-integration.md +372 -0
  46. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/topics/authorization.md +398 -0
  47. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/topics/callbacks.md +336 -0
  48. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/topics/configuration.md +383 -0
  49. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/topics/current-attributes.md +307 -0
  50. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/topics/instrumentation.md +386 -0
  51. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/topics/notifications.md +373 -0
  52. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/references/topics/view-components.md +454 -0
  53. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/workflows/analyze-callbacks.md +255 -0
  54. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/workflows/analyze-gods.md +279 -0
  55. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/workflows/analyze-services.md +1444 -0
  56. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/workflows/analyze.md +376 -0
  57. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/workflows/plan.md +249 -0
  58. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/workflows/review.md +473 -0
  59. data/lib/rails-hyperdrive-layered-rails/hyperdrive/skills/layered-rails/workflows/spec-test.md +282 -0
  60. data/lib/rails-hyperdrive-layered-rails/version.rb +3 -0
  61. data/lib/rails-hyperdrive-layered-rails.rb +7 -0
  62. metadata +106 -0
@@ -0,0 +1,376 @@
1
+ # Architecture Analysis Workflow
2
+
3
+ Comprehensive layered architecture analysis of a Rails codebase or specific directory. Evaluates how well the codebase follows layered architecture principles, identifying:
4
+ - Layer violations
5
+ - Abstraction opportunities
6
+ - God objects
7
+ - Callback concerns
8
+ - Missing patterns
9
+
10
+ ## Contents
11
+
12
+ - [Analysis Process](#analysis-process)
13
+ - [Reporting Principles](#reporting-principles)
14
+ - [Output Format](#output-format)
15
+ - [Severity Levels](#severity-levels)
16
+
17
+ ## Analysis Process
18
+
19
+ ### 1. Structural Assessment
20
+
21
+ Map existing code to layers:
22
+
23
+ ```
24
+ Presentation Layer:
25
+ - app/controllers/
26
+ - app/views/
27
+ - app/components/
28
+ - app/helpers/
29
+ - app/presenters/
30
+
31
+ Application Layer:
32
+ - app/services/
33
+ - app/operations/
34
+ - app/policies/
35
+ - app/forms/
36
+ - app/queries/
37
+ - app/deliveries/
38
+
39
+ Domain Layer:
40
+ - app/models/
41
+
42
+ Infrastructure Layer:
43
+ - app/mailers/
44
+ - app/jobs/
45
+ - app/channels/
46
+ - app/configs/
47
+ ```
48
+
49
+ **Service Layer Brief** (when `app/services/` exists OR `app/models/` shows service-like classes):
50
+
51
+ This sub-step runs a *lite version* of the service-layer audit and produces a single short section in the final report (see Output Format → "## Service Layer Brief"). The brief stays under ~25 lines; it does not include per-cluster proposal blocks, contracts, current-pain prose, or test-win paragraphs — those live in the dedicated service-layer audit. **Recommend running the service-layer audit (`analyze-services` workflow) whenever the brief surfaces a non-trivial finding.**
52
+
53
+ What to compute, in order:
54
+
55
+ 1. **Waiting-room gate.** Count files and LOC under `app/services/`; compute service share of `app/`. If `service_count < 10` OR `service_share < 0.10`, set tier to `Waiting room (gate fired)` and skip cluster detection — but still scan `app/models/` for service-like classes (next step).
56
+
57
+ 2. **Empirical mirror — one sentence.** Sample 5–10 representative service files (most-recently-modified + largest + a few short ones) and synthesize the team's implicit design pattern for a service: class shape, call interface, parameter style, return shape. The brief reports exactly **one sentence**, no code or numbers. Even when no convention has emerged, name the pattern that has: *"any Ruby object placed under `app/services/`"* is a definition. Never write "not defined".
58
+
59
+ 3. **Hidden services in `app/models/`.** Scan for non-AR classes with action interfaces and service-like names (`*_service`, `*_command`, `*_sync`, `*_importer`, `*_processor`, `*_notifier`, `*_calculator`, `*_resolver`, `*_query`, `*_finder`). Classify each as **domain** (calculators, queries, resolvers — pure derivation from domain data) or **application** (notifiers, syncs, importers — orchestrate side effects).
60
+
61
+ 4. **Architecture tier.** Pick one:
62
+ - **Mature decomposition** — `app/services/` is small (gate fires) AND ≥3 specialization folders exist (`forms/`, `queries/`, `policies/`, `deliveries/`, `presenters/`, `operations/`).
63
+ - **Mature decomposition (models-first variant)** — `app/services/` intentionally absent AND deep model namespacing carries the orchestration.
64
+ - **Mixed** — some specializations promoted, others still in services.
65
+ - **Pre-decomposition** — `app/services/` is large AND zero specialization folders.
66
+
67
+ 5. **Convention strength — one word per axis, no percentages in the brief.** For base class, call interface, parameter style, naming suffix/form, return value: classify as Strong / Mixed / Weak. Roll up into a single overall verdict (Strong / Mixed / Weak / "bag of random objects").
68
+
69
+ 6. **Cluster headlines — top 3 only.** Tokenize service basenames; group by suffix/prefix. Surface the three largest clusters as one-liners: `<pattern> (N services) — <promote candidate / demote candidate / strong cluster / borderline>`. **No proposal blocks in the brief.** If the codebase has a clearly *healthy* cluster (shared base, single deferral surface, infra separated), name it as the **healthy reference** so the team has an anchor.
70
+
71
+ 7. **Specialization folder verdicts.** For each of `app/forms/`, `app/queries/`, `app/policies/`, `app/deliveries/`, `app/notifiers/`, `app/presenters/`, `app/components/`, `app/operations/`, `app/clients/`: emit ✓ healthy / ⚠ ghost (folder exists but <3 files OR no base OR same-shape candidates hidden elsewhere) / ✗ absent. Ghosts are more actionable than absences — flag them.
72
+
73
+ 8. **Cross-cutting smell counts.** One line each, with counts only:
74
+ - Naming smells (`-er` suspects, tautological pairs, scheduling-frequency names) — count.
75
+ - Layer-hygiene issues (`request`/`params`/`flash`/`render` in services, authorization leaks) — count.
76
+ - Implicit-workflow chains of length ≥3 — count.
77
+ - Misplaced code (non-services, mixed-layer files, console/CLI utilities) — count.
78
+
79
+ 9. **Anemic-model risk.** Count models heavily referenced from services that have <3 substantive instance methods. A non-zero count flips the brief's diagnosis from "promote services" to "the domain is too thin."
80
+
81
+ **Scoring guidance:**
82
+
83
+ - Never label a large service directory (100+ files) as "Strong" or "Excellent" without verifying organization. A flat `app/services/` with 200+ files is a red flag regardless of count.
84
+ - A well-namespaced service layer with clear decomposition patterns can be healthy even at high counts.
85
+ - The brief must stay short. If any of the per-cluster proposals would take >2 lines to summarize honestly, that's the signal to defer to the service-layer audit — not to inline a longer brief.
86
+ - The brief always closes with: *"For per-cluster proposals (contracts, current pain, test wins, placement options), run the analyze-services workflow."*
87
+
88
+ For the full audit framework — empirical-mirror rationale, classification rules, cluster proposal blocks, and the reporting principles that govern the headline content — see the analyze-services workflow.
89
+
90
+ ### 2. Layer Violation Detection
91
+
92
+ Search for common violations:
93
+
94
+ **Upward Dependencies in Models**
95
+
96
+ Search for ALL types of upward-layer invocations from models:
97
+
98
+ ```bash
99
+ # Mailer/Delivery calls
100
+ grep -rn "Mailer\.\|Delivery\.\|deliver_later\|deliver_now" app/models/
101
+
102
+ # Direct service invocations
103
+ grep -rn "Service\.\|Service\.call\|Service\.new" app/models/
104
+
105
+ # Job enqueuing from models
106
+ grep -rn "perform_later\|perform_async\|perform_in\|perform_at" app/models/
107
+
108
+ # HTTP/API client calls
109
+ grep -rn "HTTP\.\|Faraday\.\|RestClient\.\|Net::HTTP\|HTTParty\.\|\.post(\|\.get(" app/models/
110
+ ```
111
+
112
+ **Only include in report if violations are found.** Omit this section entirely if no upward dependencies exist in models.
113
+
114
+ **Current in Models**
115
+
116
+ Search for `Current\.` in models, then classify each usage:
117
+
118
+ - **Acceptable patterns** (do not report as violations):
119
+ - AR attribute defaults: `default: -> { Current.user }`, `default: -> { Current.account }`
120
+ - Audit logging: `self.updated_by = Current.user` in `before_save`
121
+ - Context restoration: `Current.set(...)` blocks
122
+ - Overridable default arguments: `def something(user: Current.user)`
123
+
124
+ - **Concerning patterns** (report as violations):
125
+ - Hardcoded non-overridable access in business logic: `Current.user.admin?`
126
+ - Business logic decisions: `if Current.organization.premium?`
127
+ - Query building: `where(org: Current.organization)`, `scope` using Current
128
+ - Authorization checks: `Current.user.can_do_something?`
129
+
130
+ ```bash
131
+ grep -rn "Current\." app/models/
132
+ ```
133
+
134
+ **Reporting rules:**
135
+ - If only acceptable patterns found → mention briefly: "Current usage follows acceptable patterns (AR defaults, audit logging)"
136
+ - If concerning patterns found → report those specifically as violations
137
+ - If no Current usage → omit entirely
138
+
139
+ See [Current Attributes](../references/topics/current-attributes.md) for the full "Where Current IS Appropriate" table.
140
+
141
+ **Request Objects in Services**
142
+ ```bash
143
+ # VIOLATION: Application layer accessing presentation
144
+ grep -r "request\." app/services/
145
+ grep -r "params\[" app/services/
146
+ ```
147
+
148
+ **Business Logic in Controllers**
149
+ ```ruby
150
+ # VIOLATION: Controllers doing more than coordination
151
+ # Look for: complex conditionals, multiple model operations, business rules
152
+ ```
153
+
154
+ **Authorization in Models**
155
+ ```bash
156
+ # VIOLATION: Domain layer checking permissions
157
+ grep -r "can_.*\?" app/models/
158
+ grep -r "\.admin\?" app/models/
159
+ ```
160
+
161
+ For each violation found:
162
+ 1. Trace the call chain (who calls this code?)
163
+ 2. Find existing orchestrators (services, forms, controllers)
164
+ 3. Recommend moving side effects to the orchestrator
165
+ 4. If no orchestrator exists, list options (service, form, controller)
166
+
167
+ ### 3. God Object Identification
168
+
169
+ Using churn × complexity heuristic:
170
+
171
+ ```bash
172
+ # Find most-changed files
173
+ git log --format=format: --name-only --since="6 months ago" app/models/ | \
174
+ sort | uniq -c | sort -rn | head -20
175
+
176
+ # Cross-reference with file size/complexity
177
+ wc -l app/models/*.rb | sort -rn | head -20
178
+ ```
179
+
180
+ Candidates scoring high on both metrics are god object suspects.
181
+
182
+ ### 4. Callback Analysis
183
+
184
+ Score all callbacks in models:
185
+
186
+ | Score | Assessment |
187
+ |-------|------------|
188
+ | 5/5 | Transformer - keep |
189
+ | 4/5 | Maintainer - keep |
190
+ | 3/5 | Timestamp - acceptable |
191
+ | 2/5 | Background trigger - consider extracting |
192
+ | 1/5 | Operation - should extract |
193
+
194
+ ### 5. Coupling Analysis via Specification Test
195
+
196
+ Apply the [specification test](../references/core/specification-test.md) to the top 3-5 suspicious entities identified during analysis:
197
+
198
+ **Pick candidates from:**
199
+ - Controllers with complex actions (business logic detected in Step 2)
200
+ - Jobs with non-trivial logic (more than delegation)
201
+ - Large services (high line count or many dependencies)
202
+ - Models with mixed-layer responsibilities
203
+
204
+ **For each candidate:**
205
+
206
+ 1. List every responsibility the entity handles
207
+ 2. Categorize each responsibility by layer (Presentation / Application / Domain / Infrastructure)
208
+ 3. Identify misplaced responsibilities — anything outside the entity's primary layer
209
+
210
+ **Report format:**
211
+
212
+ ```
213
+ Entity: OrdersController#create
214
+ - Parse parameters → Presentation ✓
215
+ - Authenticate user → Presentation ✓
216
+ - Validate inventory → Domain ✗ (extract to model)
217
+ - Calculate pricing → Domain ✗ (extract to model)
218
+ - Send confirmation email → Infrastructure ✗ (extract to service)
219
+ Recommendation: Extract domain logic to Order model, orchestrate via CreateOrderService
220
+ ```
221
+
222
+ Keep this focused — apply to the most suspicious entities only, not exhaustively. Omit this section if no candidates warrant the specification test.
223
+
224
+ ### 6. Concern Health Check
225
+
226
+ For each concern, verify:
227
+ - [ ] Used by multiple models (not single-model organization)
228
+ - [ ] Methods are cohesively related
229
+ - [ ] No hidden dependencies on including class
230
+ - [ ] Doesn't recreate callback problems
231
+
232
+ ### 7. Anti-Pattern Detection
233
+
234
+ Check for common anti-patterns. The SKILL.md "Common Violations" table groups them by category and links to detailed references — consult it for the full taxonomy.
235
+
236
+ **Anemic Jobs**
237
+ ```bash
238
+ # Find job files with single-line perform methods
239
+ grep -l "def perform" app/jobs/*.rb | xargs -I{} sh -c \
240
+ 'echo "=== {} ===" && grep -A5 "def perform" {}'
241
+ ```
242
+
243
+ Signal: Job's `perform` is single delegation to model method. Fix: Use `active_job-performs` gem.
244
+
245
+ **Helper HTML Construction**
246
+ ```bash
247
+ # Find helpers building HTML programmatically
248
+ grep -r "tag\.\|content_tag" app/helpers/
249
+ ```
250
+
251
+ Signal: Heavy `tag.div`, `tag.button` chains. Fix: Extract to ViewComponent.
252
+
253
+ **Callback Control Flags**
254
+ ```bash
255
+ # Find skip flags in models
256
+ grep -r "attr_accessor :skip_" app/models/
257
+ grep -r "unless: :skip_" app/models/
258
+ ```
259
+
260
+ Signal: Virtual attributes to bypass callbacks. Fix: Extract callbacks to explicit service calls.
261
+
262
+ For each anti-pattern, reference the specific fix in the anti-patterns documentation.
263
+
264
+ ### 8. Pattern Gap Analysis
265
+
266
+ Identify missing abstractions:
267
+
268
+ - **No policies?** Check for authorization in controllers/models
269
+ - **No form objects?** Check for complex params handling
270
+ - **No query objects?** Check for long scope chains
271
+ - **No presenters?** Check for view logic in models
272
+
273
+ ## Reporting Principles
274
+
275
+ **Conditional reporting:** Only include a section in the report if there are meaningful findings. Do not report "No violations found" for every check — omit empty sections entirely. Focus the report on what matters for this specific codebase.
276
+
277
+ ## Output Format
278
+
279
+ ```markdown
280
+ # Layered Architecture Analysis
281
+
282
+ ## Summary
283
+ - Overall health: [Good/Fair/Needs Attention/Critical]
284
+ - Layer compliance: [percentage]
285
+ - God object candidates: [count]
286
+ - Callback concerns: [count]
287
+ - Anti-patterns detected: [count]
288
+ - Service layer tier: [Mature decomposition | Mature decomposition (models-first) | Mixed | Pre-decomposition | Waiting room]
289
+
290
+ ## Service Layer Brief
291
+
292
+ **In this project, a Service Object is:** <one sentence — the empirical mirror>
293
+
294
+ - **Architecture tier:** Mature decomposition | Mature decomposition (models-first variant) | Mixed | Pre-decomposition | Waiting room
295
+ - **Convention strength:** Strong | Mixed | Weak (bag of random objects)
296
+ - **Specialization folders:** forms ✓ | queries ⚠ ghost (2 files, no base) | policies ✓ | deliveries ✗ | presenters ✗
297
+ - **Top clusters (3):**
298
+ 1. `*Importer` (8 services) — promote candidate
299
+ 2. `*Notifier` (6 services) — strong cluster, healthy reference
300
+ 3. `*Processor` (4 services) — borderline; watch for premature consolidation
301
+ - **Hidden in `app/models/`:** N service-like classes (D domain candidates / A application leaks)
302
+ - **Cross-cutting smells:** K naming, M layer-hygiene, J implicit workflows, P misplaced
303
+ - **Anemic-model risk:** Q models with <3 substantive methods
304
+
305
+ > For per-cluster proposals (contracts, current pain, test wins, placement options), run the analyze-services workflow.
306
+
307
+ Omit any bullet whose finding is zero. Skip the entire section only when `app/services/` is intentionally absent AND the `app/models/` scan finds no application-layer leaks AND no demote candidates — in which case the Summary's tier line carries the verdict.
308
+
309
+ ## Layer Violations
310
+
311
+ ### Critical
312
+ 1. `app/models/user.rb:45` - `Current.user.admin?` used for business logic decision
313
+ - Impact: Domain coupled to request context for authorization
314
+ - Fix: Move to policy object or pass user explicitly through service layer
315
+
316
+ ### Major
317
+ ...
318
+
319
+ ### Minor
320
+ ...
321
+
322
+ ## God Object Candidates
323
+
324
+ | Model | Lines | Churn | Complexity | Recommendation |
325
+ |-------|-------|-------|------------|----------------|
326
+ | User | 450 | High | High | Extract concerns, services |
327
+ | Order | 380 | Medium | High | State machine, form objects |
328
+
329
+ ## Callback Concerns
330
+
331
+ | File | Callback | Score | Recommendation |
332
+ |------|----------|-------|----------------|
333
+ | user.rb | after_create :send_welcome | 1/5 | Extract to service |
334
+ | post.rb | before_save :update_slug | 5/5 | Keep |
335
+
336
+ ## Anti-Patterns
337
+
338
+ | Type | Location | Fix |
339
+ |------|----------|-----|
340
+ | Anemic Job | `NotifyRecipientsJob` | Use `performs` gem |
341
+ | Helper HTML | `messages_helper.rb` | Extract to ViewComponent |
342
+
343
+ The SKILL.md "Common Violations" section has the per-category references.
344
+
345
+ ## Pattern Recommendations
346
+
347
+ ### Immediate Actions
348
+ 1. Extract `User` authentication logic to `AuthenticateUser` service
349
+ 2. Move `Order#can_cancel?` authorization to `OrderPolicy`
350
+ 3. Replace `Post` callbacks with `PublishPost` service
351
+
352
+ ### Future Improvements
353
+ 1. Add form objects for multi-model forms
354
+ 2. Consider query objects for reporting
355
+ 3. Extract view logic to presenters
356
+ ```
357
+
358
+ ## Severity Levels
359
+
360
+ ### Critical
361
+ - Domain layer using Current for business logic, authorization, or query building
362
+ - Circular dependencies between layers
363
+ - Business logic in views
364
+
365
+ ### Major
366
+ - Heavy callback chains (5+ callbacks)
367
+ - God objects (>300 lines, high churn)
368
+ - Authorization scattered across layers
369
+ - Callback control flags (`skip_*` attributes)
370
+
371
+ ### Minor
372
+ - Missing abstractions (could benefit from patterns)
373
+ - Concerns used by single model
374
+ - Overly complex scopes
375
+ - Anemic jobs (single-delegation wrappers)
376
+ - Helper HTML construction (candidates for ViewComponents)
@@ -0,0 +1,249 @@
1
+ # Gradual Layerification Workflow
2
+
3
+ Plan incremental adoption of layered architecture for Rails codebases. Create a practical, low-risk roadmap for introducing layered patterns to an existing codebase without big-bang rewrites.
4
+
5
+ ## Contents
6
+
7
+ - [Inputs](#inputs)
8
+ - [Process](#process)
9
+ - [Output Format](#output-format)
10
+ - [Guidelines](#guidelines)
11
+ - [Related](#related)
12
+
13
+ ## Inputs
14
+
15
+ - **Goal** (optional): Specific focus area. If not specified, create a full roadmap.
16
+
17
+ ## Process
18
+
19
+ ### 1. Understand the Goal
20
+
21
+ Parse the user's goal to determine focus and identify the canonical refactoring scenario for it:
22
+
23
+ | Goal keywords | Focus area | Key patterns | Reference scenario |
24
+ |---------------|------------|--------------|--------------------|
25
+ | authorization, permissions, policies | Authorization layer | Policy objects, Action Policy | [Extract authorization to policy](../examples/authorization-to-policy.md) |
26
+ | fat controllers, controller logic | Controller extraction | Form objects, filter objects | [Complex input to form object](../examples/complex-input-to-form-object.md) |
27
+ | callbacks, after_create, side effects | Callback extraction | Services, move to callers | [Callbacks to service](../examples/callbacks-to-service.md) |
28
+ | god object, large model, User model | Model decomposition | Concerns, associated objects | [God object decomposition](../examples/god-object-decomposition.md) |
29
+ | Current.user, current_user in models | Context extraction | Policy + controller seams | [Extract Current from model](../examples/current-from-model.md) |
30
+ | state machine, status, workflow | Explicit state machine | Workflow gem | [Implicit to explicit state machine](../examples/implicit-to-explicit-state-machine.md) |
31
+ | query, scopes, reports | Query extraction | Query objects | [Query to query object](../examples/query-to-query-object.md) |
32
+ | presenter, view logic, helpers | View extraction | Presenters, ViewComponents | [View logic to presenter](../examples/view-logic-to-presenter.md) |
33
+ | notifications, mailers, deliveries | Notification extraction | Move to orchestrators | (no canonical scenario yet — derive from caller context) |
34
+ | (none specified) | Full assessment | Prioritized roadmap | (consult scenarios per phase) |
35
+
36
+ When a phase matches a Reference Scenario, **read the scenario file before drafting before/after code.** The scenarios are canonical templates — adapt them to the user's actual class names and call sites, don't re-derive the structure from scratch. Always cite the scenario file in the phase output so the user can see the full template.
37
+
38
+ ### 2. Assess Current State
39
+
40
+ Run targeted analysis:
41
+
42
+ ```bash
43
+ # Check for existing abstractions
44
+ ls app/services app/forms app/policies 2>/dev/null
45
+
46
+ # Check for base classes
47
+ grep -r "class Application" app/
48
+
49
+ # Check for gem usage
50
+ grep -E "action_policy|dry-|pundit|reform" Gemfile
51
+ ```
52
+
53
+ Determine architectural style:
54
+ - **DHH/37signals**: Fat models, thin controllers, minimal abstractions
55
+ - **Partial layered**: Some services/forms/policies present
56
+ - **Layered**: Full abstraction layer structure
57
+
58
+ ### 3. Find Existing Patterns
59
+
60
+ Look for conventions to follow:
61
+
62
+ ```bash
63
+ # Existing service patterns
64
+ head -20 app/services/*.rb 2>/dev/null
65
+
66
+ # Existing form patterns
67
+ head -20 app/forms/*.rb 2>/dev/null
68
+
69
+ # Existing policy patterns
70
+ head -20 app/policies/*.rb 2>/dev/null
71
+ ```
72
+
73
+ If patterns exist, follow their conventions. If not, suggest establishing them.
74
+
75
+ ### 4. Analyze Relevant Code
76
+
77
+ Based on goal, search for:
78
+
79
+ **Authorization focus:**
80
+ ```bash
81
+ grep -r "can_\|admin\?\|role\|permission" app/models/ app/controllers/
82
+ ```
83
+
84
+ **Callback focus:**
85
+ ```bash
86
+ grep -r "after_create\|after_save\|after_commit\|before_" app/models/
87
+ ```
88
+
89
+ **Fat controller focus:**
90
+ ```bash
91
+ wc -l app/controllers/*.rb | sort -rn | head -10
92
+ ```
93
+
94
+ **God object focus:**
95
+ ```bash
96
+ wc -l app/models/*.rb | sort -rn | head -10
97
+ ```
98
+
99
+ **Helper/Presenter focus (for ViewComponent opportunities):**
100
+ ```bash
101
+ # Check helper sizes
102
+ wc -l app/helpers/*.rb | sort -rn | head -10
103
+
104
+ # Check for HTML construction in helpers (extraction signal)
105
+ grep -r "tag\.\|content_tag" app/helpers/
106
+
107
+ # Check for presenters building HTML
108
+ grep -r "\.render\|context: self" app/helpers/ app/presenters/
109
+ ```
110
+
111
+ **Important:** Before dismissing presenters/ViewComponents as unnecessary, actually examine helper files for:
112
+ - Heavy `tag.div`, `tag.button`, `tag.span` usage → ViewComponent candidates
113
+ - Complex `data: { ... }` attribute hashes → Stimulus wiring belongs in components
114
+ - Presenters with `.render` methods → Already doing component work without benefits
115
+ - Helpers over 50 lines → Likely mixing logic and markup
116
+
117
+ ### 5. Trace Call Chains
118
+
119
+ For each violation or extraction candidate:
120
+ 1. Find all callers (grep for method/class usage)
121
+ 2. Identify existing orchestrators (services, forms, controllers)
122
+ 3. Determine best location for extracted code
123
+
124
+ **Key question:** Is there already an orchestrator where this logic can move?
125
+
126
+ ### 6. Prioritize Changes
127
+
128
+ Order by value/risk ratio:
129
+
130
+ **High Value, Low Risk (Phase 1):**
131
+ - Extract authorization to policies (isolated, testable)
132
+ - Add form objects for multi-model forms (encapsulated)
133
+ - Move notifications from models to existing callers
134
+
135
+ **High Value, Medium Risk (Phase 2-3):**
136
+ - Extract god objects with associated objects pattern
137
+ - Introduce services for complex callback chains
138
+ - Add query objects for complex scopes
139
+
140
+ **Lower Priority (Later phases):**
141
+ - Presenters (cosmetic improvement) — *unless helpers are building HTML*
142
+ - Serializers (only if API-heavy)
143
+ - ViewComponents — *move UP priority if helpers use `tag.*` extensively*
144
+ - Repositories (only if needed)
145
+
146
+ **Priority adjustment:** If helpers contain heavy `tag.*` usage, move ViewComponent extraction to Phase 2 (High Value, Medium Risk). HTML-building helpers create maintenance burden and miss component benefits.
147
+
148
+ ### 7. Generate Phased Plan
149
+
150
+ For each phase include:
151
+ - Specific files to change
152
+ - Pattern to apply with reference link
153
+ - Reference scenario link (when one applies — see step 1)
154
+ - Before/after code examples adapted from the scenario
155
+ - Dependencies on other phases
156
+ - Estimated scope (small/medium/large)
157
+ - "Stop here if..." guidance
158
+
159
+ ## Output Format
160
+
161
+ ```markdown
162
+ # Gradual Layerification Plan: [Goal]
163
+
164
+ ## Current State
165
+
166
+ - **Style:** [DHH/37signals / partial layered / fully layered]
167
+ - **Existing abstractions:** [list what exists or "none"]
168
+ - **Relevant findings:** [issues related to the goal]
169
+
170
+ ## Approach
171
+
172
+ [Explain why this order, what's the strategy based on goal and findings]
173
+
174
+ ## Phase 1: [Name]
175
+
176
+ **Scope:** Small / Medium / Large
177
+ **Goal:** [What this phase achieves]
178
+
179
+ ### Change 1: [Description]
180
+
181
+ **File:** `app/models/user.rb`
182
+
183
+ **Current:**
184
+ ` ` `ruby
185
+ class User < ApplicationRecord
186
+ def can_administer?(message)
187
+ administrator? || message.creator == self
188
+ end
189
+ end
190
+ ` ` `
191
+
192
+ **After:**
193
+ ` ` `ruby
194
+ # app/policies/message_policy.rb
195
+ class MessagePolicy < ApplicationPolicy
196
+ def administer?
197
+ user.administrator? || record.creator == user
198
+ end
199
+ end
200
+ ` ` `
201
+
202
+ **Pattern:** Policy Objects (see references/patterns/policy-objects.md)
203
+ **Scenario:** Extract Authorization to Policy (see examples/authorization-to-policy.md)
204
+
205
+ ### Change 2: ...
206
+
207
+ **Stop here if:** The app is small and the team prefers DHH-style simplicity.
208
+
209
+ ---
210
+
211
+ ## Phase 2: [Name]
212
+
213
+ **Scope:** ...
214
+ **Depends on:** Phase 1
215
+
216
+ ...
217
+
218
+ ---
219
+
220
+ ## Not Recommended for This Codebase
221
+
222
+ - **[Pattern]:** [Why it doesn't fit]
223
+ - **[Pattern]:** [Why it doesn't fit]
224
+
225
+ ---
226
+
227
+ ## Next Steps
228
+
229
+ 1. Run the review workflow after implementing each phase
230
+ 2. Add tests for new abstractions before refactoring
231
+ 3. Consider [specific gem] for [specific pattern]
232
+ ```
233
+
234
+ ## Guidelines
235
+
236
+ - **Don't over-engineer small apps** - suggest minimal changes for simple codebases
237
+ - **Build on existing patterns** - follow conventions already in the codebase
238
+ - **One pattern at a time** - don't overwhelm with too many changes per phase
239
+ - **Provide escape hatches** - "stop here if..." lets teams choose their depth
240
+ - **Be specific** - name actual files and show real code transformations
241
+ - **Respect the existing style** - acknowledge DHH-style as valid choice
242
+
243
+ ## Related
244
+
245
+ - [Policy Objects](../references/patterns/policy-objects.md)
246
+ - [Service Objects](../references/patterns/service-objects.md)
247
+ - [Form Objects](../references/patterns/form-objects.md)
248
+ - [Concerns](../references/patterns/concerns.md)
249
+ - [Extraction signals](../references/core/extraction-signals.md)