moicle 1.3.1 → 1.4.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.
@@ -1,756 +1,338 @@
1
1
  ---
2
2
  name: refactor
3
- description: Refactoring workflow for improving code quality without changing behavior. Use when refactoring, cleaning up code, improving structure, or when user says "refactor", "clean up", "improve code", "restructure".
3
+ description: DDD refactoring workflow with phase-based checks and review loop. Refactor existing code to DDD architecture or improve existing DDD structure. Use when user says "refactor", "clean up", "improve code", "restructure", "migrate to ddd", "refactor ddd".
4
+ args: "[MODULE] [DOMAIN]"
4
5
  ---
5
6
 
6
- # Refactoring Workflow
7
+ # DDD Refactor Workflow
7
8
 
8
- Systematic workflow for improving code quality and structure without changing external behavior.
9
+ Refactor existing code into DDD architecture, or improve existing DDD structure. Execute phases sequentially, run rule checks after each phase.
9
10
 
10
- ## IMPORTANT: Read Architecture First
11
+ **ARGUMENTS:** `<module> <domain>` e.g., `marketing notification`, `users identity`, `products catalog`
11
12
 
12
- **Before refactoring, you MUST read the appropriate architecture reference:**
13
+ ## Read Architecture First
13
14
 
14
- ### Global Architecture Files
15
- ```
16
- ~/.claude/architecture/
17
- ├── clean-architecture.md # Core principles for all projects
18
- ├── flutter-mobile.md # Flutter + Riverpod
19
- ├── react-frontend.md # React + Vite + TypeScript
20
- ├── go-backend.md # Go + Gin
21
- ├── laravel-backend.md # Laravel + PHP
22
- ├── remix-fullstack.md # Remix fullstack
23
- └── monorepo.md # Monorepo structure
24
- ```
15
+ **Before starting, MUST read TWO files:**
25
16
 
26
- ### Project-specific (if exists)
27
- ```
28
- .claude/architecture/ # Project overrides
29
- ```
17
+ 1. **Core DDD spec**: `.claude/architecture/ddd-architecture.md`
18
+ 2. **Stack-specific doc**: detect stack → read the corresponding architecture doc
30
19
 
31
- **Refactoring should align code with these architecture patterns.**
32
-
33
- ## Recommended Agents
34
-
35
- | Phase | Agent | Purpose |
36
- |-------|-------|---------|
37
- | ANALYZE | `@refactor` | Identify refactoring opportunities |
38
- | ANALYZE | `@code-reviewer` | Code smell detection |
39
- | PLAN | `@clean-architect` | Architecture alignment strategy |
40
- | REFACTOR | `@react-frontend-dev`, `@go-backend-dev`, `@laravel-backend-dev`, `@flutter-mobile-dev`, `@remix-fullstack-dev` | Stack-specific refactoring |
41
- | TEST | `@test-writer` | Regression tests |
42
- | REVIEW | `@code-reviewer` | Final quality check |
43
- | REVIEW | `@perf-optimizer` | Performance validation |
44
-
45
- ## Workflow Overview
20
+ ### Stack Detection
21
+ | File | Stack Doc |
22
+ |------|-----------|
23
+ | `go.mod` | `go-backend.md` |
24
+ | `package.json` + `vite.config.*` | `react-frontend.md` |
25
+ | `pubspec.yaml` | `flutter-mobile.md` |
26
+ | `composer.json` | `laravel-backend.md` |
27
+ | `remix.config.*` | `remix-fullstack.md` |
46
28
 
29
+ ### Architecture Files Location
47
30
  ```
48
- ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
49
- │1. ANALYZE│──▶│ 2. PLAN │──▶│3. REFACTOR──▶│ 4. TEST │──▶│5. REVIEW │
50
- └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘
51
- │ │ │
52
- │ Fail? │ │
53
- └──────◀───────┴──────◀───────┘
54
- Feedback Loop
31
+ .claude/architecture/{name}.md # Project-specific (priority)
32
+ ~/.claude/architecture/{name}.md # Global
55
33
  ```
56
34
 
57
35
  ---
58
36
 
59
- ## Phase 1: ANALYZE
37
+ ## Workflow
60
38
 
61
- **Goal**: Identify code smells and improvement opportunities
62
-
63
- ### Actions
64
- 1. **Identify project stack and read architecture doc**
65
-
66
- 2. Analyze codebase for common issues:
67
- ```
68
- Code Smells:
69
- - Long methods (> 50 lines)
70
- - Large classes (> 300 lines)
71
- - Duplicate code
72
- - Deep nesting (> 3 levels)
73
- - Long parameter lists (> 4 params)
74
- - God classes/modules
75
- - Feature envy
76
- - Data clumps
77
- - Primitive obsession
78
- ```
79
-
80
- 3. Check architecture compliance:
81
- - [ ] Layer boundaries violated?
82
- - [ ] Circular dependencies?
83
- - [ ] Missing abstractions?
84
- - [ ] Wrong patterns used?
85
- - [ ] Naming conventions violated?
86
-
87
- 4. Assess technical debt:
88
- ```bash
89
- # Find TODOs and FIXMEs
90
- grep -r "TODO\|FIXME\|HACK\|XXX" --exclude-dir=node_modules --exclude-dir=vendor
91
-
92
- # Check test coverage
93
- [use coverage tool from architecture doc]
94
-
95
- # Find large files
96
- find . -type f -name "*.ts" -o -name "*.go" -o -name "*.php" -o -name "*.dart" | xargs wc -l | sort -rn | head -20
97
- ```
98
-
99
- ### Output
100
- ```markdown
101
- ## Refactoring Analysis
102
-
103
- ### Stack & Architecture
104
- - Stack: [Flutter/React/Go/Laravel/Remix]
105
- - Architecture Doc: [path to doc]
106
-
107
- ### Code Smells Found
108
- 1. [Smell]: [location] - [description]
109
- 2. [Smell]: [location] - [description]
110
-
111
- ### Architecture Violations
112
- - [ ] Layer X depends on Layer Y (should be reversed)
113
- - [ ] Missing [pattern] from architecture doc
114
- - [ ] Naming doesn't follow [convention from doc]
115
-
116
- ### Technical Debt Areas
117
- - [ ] Area 1: [description]
118
- - [ ] Area 2: [description]
119
-
120
- ### Metrics
121
- - Large files (> 300 lines): [count]
122
- - Duplicate code blocks: [count]
123
- - Test coverage: [percentage]
124
- - TODO/FIXME count: [count]
39
+ ```
40
+ PHASE 0: Foundation Check
41
+ PHASE 1: Analyze Current Module
42
+ PHASE 2: Build Domain Layer
43
+ → PHASE 3: Build Infrastructure Layer
44
+ PHASE 4: Build Application Layer
45
+ → PHASE 5: Domain Tests
46
+ PHASE 6: Integration & Cleanup
47
+ REVIEW LOOP (run /architect-review, fix, repeat until clean)
125
48
  ```
126
49
 
127
- ### Gate
128
- - [ ] Architecture doc read
129
- - [ ] Code smells identified
130
- - [ ] Architecture violations documented
131
- - [ ] Scope defined
50
+ Each phase has a Rule Check. DO NOT skip any phase.
132
51
 
133
52
  ---
134
53
 
135
- ## Phase 2: PLAN
54
+ ## PHASE 0: Foundation Check
136
55
 
137
- **Goal**: Design refactoring strategy aligned with architecture
56
+ Verify DDD foundation exists in the project.
138
57
 
139
- ### Actions
140
- 1. **Re-read architecture doc** for target patterns
141
-
142
- 2. Prioritize refactorings:
143
- ```
144
- Priority Matrix:
145
- HIGH IMPACT + LOW RISK → Do first
146
- HIGH IMPACT + HIGH RISK → Plan carefully
147
- LOW IMPACT + LOW RISK → Do if time permits
148
- LOW IMPACT + HIGH RISK → Skip
149
- ```
150
-
151
- 3. Break down into incremental steps:
152
- - Each step should be small
153
- - Each step should be testable
154
- - Each step should compile
155
- - Follow architecture patterns
156
-
157
- 4. Identify risks:
158
- - [ ] Breaking changes possible?
159
- - [ ] Performance impact?
160
- - [ ] Dependencies affected?
161
- - [ ] Rollback plan needed?
162
-
163
- ### Planning Template
164
- ```markdown
165
- ## Refactoring Plan
166
-
167
- ### Architecture Reference
168
- - Doc: [path to architecture doc]
169
- - Target patterns: [patterns from doc]
170
-
171
- ### Strategy
172
- Move from: [current structure]
173
- Move to: [architecture-compliant structure]
174
-
175
- ### Incremental Steps (smallest possible)
176
- 1. [Step 1] - Risk: [Low/Medium/High]
177
- - Files: [list]
178
- - Pattern: [pattern from doc]
179
- - Estimated effort: [time]
180
-
181
- 2. [Step 2] - Risk: [Low/Medium/High]
182
- - Files: [list]
183
- - Pattern: [pattern from doc]
184
- - Estimated effort: [time]
185
-
186
- 3. [Continue...]
187
-
188
- ### Risks & Mitigation
189
- | Risk | Impact | Mitigation |
190
- |------|--------|------------|
191
- | [Risk 1] | [High/Medium/Low] | [How to mitigate] |
192
-
193
- ### Success Criteria
194
- - [ ] Code follows architecture doc
195
- - [ ] All tests pass
196
- - [ ] No behavior changes
197
- - [ ] Performance maintained/improved
198
- - [ ] Complexity reduced
58
+ ### For new DDD projects (no domain/ dir yet)
59
+ Create shared foundation:
60
+ - `domain/shared/` — base event types, event collector, event dispatcher interface
61
+ - Event bus / dispatcher infrastructure
62
+ - Bootstrap/app config struct
63
+
64
+ ### For existing DDD projects
65
+ Verify foundation is intact:
66
+ ```bash
67
+ # Check shared domain types exist
68
+ ls {domain_root}/shared/ 2>/dev/null && echo "PASS" || echo "NEED SETUP"
69
+
70
+ # Check event infrastructure exists (if applicable)
71
+ ls {eventbus_path}/ 2>/dev/null && echo "PASS" || echo "NEED SETUP"
199
72
  ```
200
73
 
201
- ### Gate
202
- - [ ] Plan follows architecture doc
203
- - [ ] Steps are incremental
204
- - [ ] Risks identified
205
- - [ ] Rollback plan exists
74
+ If any FAIL → create foundation first before proceeding.
206
75
 
207
76
  ---
208
77
 
209
- ## Phase 3: REFACTOR
78
+ ## PHASE 1: Analyze Current Module
210
79
 
211
- **Goal**: Execute refactoring incrementally following architecture
212
-
213
- ### Principles
214
- 1. **Red-Green-Refactor** - Tests must pass after each step
215
- 2. **Small steps** - One pattern at a time
216
- 3. **Frequent commits** - Commit after each successful step
217
- 4. **No behavior change** - External behavior stays same
218
- 5. **Follow architecture** - Align with patterns from doc
80
+ Read ALL source files before making any changes.
219
81
 
220
82
  ### Actions
83
+ 1. Read all files in the current module/feature directory
84
+ 2. Read related models/types
85
+ 3. Read related enums/constants
86
+ 4. Read current routes/screens/providers for this module
87
+
88
+ ### Output (report to user)
89
+ - All entities/models and their fields
90
+ - All usecases (functions/methods) and their logic
91
+ - All DTOs (request/response structs)
92
+ - All validators (if any)
93
+ - All cross-module calls
94
+ - All events/side-effects (notifications, SSE, analytics)
95
+ - All external dependencies (DB, cache, messaging, etc.)
96
+ - All endpoints/screens/UI elements
97
+
98
+ ### Rule Check Phase 1
99
+ - [ ] All module files read and understood
100
+ - [ ] All entities, usecases, dependencies, endpoints listed
101
+ - [ ] Report presented to user and **CONFIRM received** before continuing
221
102
 
222
- 1. Create refactor branch:
223
- ```bash
224
- git checkout -b refactor/[scope]-[description]
225
- ```
226
-
227
- 2. **Read architecture doc** for implementation patterns
228
-
229
- 3. For each refactoring step:
230
-
231
- a. **Before refactoring**:
232
- ```bash
233
- # Run tests to establish baseline
234
- [test command from architecture doc]
235
-
236
- # Create checkpoint
237
- git add .
238
- git commit -m "refactor: checkpoint before [step description]"
239
- ```
240
-
241
- b. **Apply one refactoring pattern**:
242
- - Extract Method
243
- - Extract Class
244
- - Rename for Clarity
245
- - Move Method
246
- - Replace Conditional with Polymorphism
247
- - Introduce Parameter Object
248
- - Remove Duplication
249
- - Simplify Conditional Logic
250
- - Break Up Large Class
251
- - Extract Interface
252
-
253
- Follow patterns and naming from architecture doc
254
-
255
- c. **After refactoring**:
256
- ```bash
257
- # Verify tests still pass
258
- [test command from architecture doc]
259
-
260
- # Commit if successful
261
- git add .
262
- git commit -m "refactor: [what was done]"
263
- ```
264
-
265
- d. **If tests fail**:
266
- ```bash
267
- # Rollback
268
- git reset --hard HEAD
269
-
270
- # Re-analyze and try smaller step
271
- ```
272
-
273
- 4. Follow directory structure from architecture doc:
274
- ```
275
- [Use exact structure defined in architecture doc]
276
- ```
277
-
278
- ### Common Refactoring Patterns
279
-
280
- #### Extract Method
281
- ```
282
- Before:
283
- function processOrder() {
284
- // 50 lines of code
285
- // validation logic
286
- // business logic
287
- // persistence logic
288
- }
289
-
290
- After (following architecture doc):
291
- function processOrder() {
292
- validateOrder();
293
- applyBusinessRules();
294
- persistOrder();
295
- }
296
- ```
297
-
298
- #### Extract Class (following architecture layers)
299
- ```
300
- Before:
301
- class User {
302
- // user data
303
- // authentication logic
304
- // email sending logic
305
- // persistence logic
306
- }
307
-
308
- After (following architecture doc):
309
- - entities/User (domain)
310
- - services/AuthService (use case)
311
- - services/EmailService (use case)
312
- - repositories/UserRepository (data)
313
- ```
103
+ ---
314
104
 
315
- #### Introduce Parameter Object
316
- ```
317
- Before:
318
- function createUser(name, email, phone, address, city, zip)
319
-
320
- After:
321
- interface CreateUserDTO {
322
- name: string;
323
- email: string;
324
- phone: string;
325
- address: Address;
326
- }
327
- function createUser(dto: CreateUserDTO)
105
+ ## PHASE 2: Create Domain Layer
106
+
107
+ Create `domain/{domain}/` (if first module in this domain) or add to existing.
108
+
109
+ ### 2.1 Value Objects (`valueobjects/`)
110
+ - Extract typed values from existing code (status strings, rates, amounts)
111
+ - Immutable with behavior methods
112
+ - **Only stdlib imports** — check Forbidden Imports from architecture doc
113
+
114
+ ### 2.2 Entities (`entities/`)
115
+ - Convert existing model fields to domain entity
116
+ - Add constructor function/method
117
+ - Add behavior methods (state transitions, calculations)
118
+ - Add event collection (collect events on state changes)
119
+ - Add mappers to/from persistence models (if applicable)
120
+ - **No framework imports**
121
+
122
+ ### 2.3 Events (`events/`)
123
+ - One file per domain event
124
+ - Extend/embed base event type
125
+ - Carry data needed by listeners
126
+ - Extract from existing direct side-effect calls (SSE, notifications, etc.)
127
+
128
+ ### 2.4 Ports (`ports/`)
129
+ - One file per port interface
130
+ - Store ports: persistence interface from existing repository/DB calls
131
+ - Adapter ports: external service interfaces
132
+ - Platform-agnostic naming
133
+ - **No infrastructure imports**
134
+
135
+ ### 2.5 UseCases (`usecases/`)
136
+ - Extract business logic from existing controllers/handlers/services
137
+ - Import port interfaces from `ports/`
138
+ - Split by concern: one file per action group
139
+ - Business logic lives HERE
140
+ - **No infrastructure imports**
141
+
142
+ ### Rule Check Phase 2
143
+ Run check scripts from architecture doc:
144
+ ```bash
145
+ # Build domain layer
146
+ {stack_build_command_for_domain}
147
+
148
+ # Check domain purity
149
+ {grep_forbidden_imports_in_domain} && echo "FAIL" || echo "PASS"
150
+
151
+ # Check no cross-domain imports
152
+ {check_cross_domain_imports}
328
153
  ```
329
154
 
330
- ### Gate
331
- - [ ] All refactoring steps completed
332
- - [ ] Code follows architecture doc patterns
333
- - [ ] Tests pass after each step
334
- - [ ] Code compiles without warnings
335
- - [ ] No behavior changes
336
-
337
155
  ---
338
156
 
339
- ## Phase 4: TEST
340
-
341
- **Goal**: Ensure refactoring didn't break anything
157
+ ## PHASE 3: Create Infrastructure Layer
342
158
 
343
- ### Actions
159
+ ### 3.1 Store/API Implementation
160
+ - Implement interfaces from `domain/{domain}/ports/`
161
+ - Use mapper functions (domain entity ↔ persistence model)
162
+ - Compile-time interface check (where possible)
163
+ - NO business logic — pure persistence
164
+ - Keep existing persistence models where they are
344
165
 
345
- 1. **Read testing section from architecture doc**
346
-
347
- 2. Run full test suite (command from doc):
348
- ```bash
349
- flutter test # Flutter
350
- flutter test --coverage
351
-
352
- go test ./... # Go
353
- go test -cover ./...
354
-
355
- bun test # React/Remix
356
- bun test --coverage
357
-
358
- php artisan test # Laravel
359
- php artisan test --coverage
360
- ```
361
-
362
- 3. Verify test coverage didn't decrease:
363
- ```bash
364
- # Compare coverage before/after
365
- # Coverage should stay same or improve
366
- ```
367
-
368
- 4. Add tests for refactored areas (following doc patterns):
369
- ```
370
- Before refactor: 70% coverage
371
- After refactor: 70%+ coverage (should not decrease)
372
- ```
373
-
374
- 5. Manual smoke testing:
375
- - [ ] Critical user flows work
376
- - [ ] No visual regressions (if UI)
377
- - [ ] Performance is same/better
378
- - [ ] Error handling works
379
-
380
- 6. Run linter/formatter (tools from architecture doc):
381
- ```bash
382
- # Use tools specified in architecture doc
383
- flutter analyze # Flutter
384
- golangci-lint run # Go
385
- eslint . --fix # React/Remix
386
- ./vendor/bin/pint # Laravel
387
- ```
388
-
389
- ### Testing Checklist
390
- ```markdown
391
- ## Test Results
392
-
393
- ### Automated Tests
394
- - [ ] Unit tests: [X/Y passed]
395
- - [ ] Integration tests: [X/Y passed]
396
- - [ ] E2E tests: [X/Y passed]
397
-
398
- ### Coverage
399
- - Before: [percentage]
400
- - After: [percentage]
401
- - Change: [+/-]
402
-
403
- ### Manual Tests
404
- - [ ] Critical flow 1: [Pass/Fail]
405
- - [ ] Critical flow 2: [Pass/Fail]
406
- - [ ] Error scenarios: [Pass/Fail]
407
-
408
- ### Quality Checks
409
- - [ ] Linter: [Pass/Fail]
410
- - [ ] Type checker: [Pass/Fail]
411
- - [ ] Build: [Pass/Fail]
166
+ ### Rule Check Phase 3
167
+ ```bash
168
+ # Build infrastructure
169
+ {stack_build_command_for_infra}
412
170
  ```
413
171
 
414
- ### Gate
415
- - [ ] All tests pass
416
- - [ ] Coverage maintained/improved
417
- - [ ] Manual tests pass
418
- - [ ] Quality checks pass
172
+ ---
419
173
 
420
- ### Feedback Loop
421
- If tests fail:
422
- 1. Identify which refactoring step broke it
423
- 2. Use git bisect if needed: `git bisect start`
424
- 3. Return to REFACTOR phase
425
- 4. Fix or rollback that step
426
- 5. Re-test
174
+ ## PHASE 4: Create Application Layer
427
175
 
428
- ---
176
+ ### 4.1 Listeners (extract from existing side-effects)
177
+ - **CRITICAL:** Side-effects (notifications, SSE, analytics, async jobs) MUST NOT be called directly in usecases or infrastructure
178
+ - They MUST flow through: entity collects events → usecase dispatches → listener handles
179
+ - One file per event listener
180
+ - Register in event bus/registry
429
181
 
430
- ## Phase 5: REVIEW
182
+ ### 4.2 Service
183
+ - Thin wrapper delegating to domain usecases
184
+ - NO business logic
431
185
 
432
- **Goal**: Verify improvements and architecture compliance
186
+ ### 4.3 Handler/Controller/Screen
187
+ - Registration/wiring function
188
+ - Thin: parse input → call service → return output
189
+ - DTOs in separate file
190
+ - All endpoints/routes must match the old ones (same path + method)
433
191
 
434
- ### Actions
192
+ ### Rule Check Phase 4
193
+ ```bash
194
+ # Build application layer
195
+ {stack_build_command_for_application}
196
+ ```
435
197
 
436
- 1. **Compare with architecture doc**:
437
- - [ ] Layers properly separated
438
- - [ ] Dependencies flow correctly (from doc)
439
- - [ ] Patterns used correctly
440
- - [ ] Naming follows conventions
441
- - [ ] Directory structure matches doc
442
-
443
- 2. Measure improvements:
444
- ```markdown
445
- ## Metrics Comparison
446
-
447
- | Metric | Before | After | Change |
448
- |--------|--------|-------|--------|
449
- | Avg method length | X lines | Y lines | -Z% |
450
- | Avg class size | X lines | Y lines | -Z% |
451
- | Cyclomatic complexity | X | Y | -Z% |
452
- | Duplicate code | X blocks | Y blocks | -Z% |
453
- | Test coverage | X% | Y% | +Z% |
454
- | Build time | X sec | Y sec | -Z% |
455
- ```
456
-
457
- 3. Code review checklist:
458
- - [ ] Code is more readable
459
- - [ ] Code is more maintainable
460
- - [ ] Complexity reduced
461
- - [ ] Duplication removed
462
- - [ ] Architecture violations fixed
463
- - [ ] No over-engineering
464
-
465
- 4. Performance check:
466
- ```bash
467
- # Run performance tests
468
- # Compare with baseline
469
- # Should be same or better
470
- ```
471
-
472
- 5. Security check:
473
- - [ ] No new vulnerabilities introduced
474
- - [ ] Security patterns still apply
475
- - [ ] Input validation intact
476
- - [ ] Authentication/authorization unchanged
477
-
478
- ### Review Output
479
- ```markdown
480
- ## Refactoring Review
198
+ ---
481
199
 
482
- ### Architecture Compliance: [Pass/Fail]
483
- - Reference: [architecture doc path]
484
- - Violations fixed: [list]
485
- - Remaining issues: [list]
200
+ ## PHASE 5: Domain Tests
486
201
 
487
- ### Quality Improvements: [Good/Excellent]
488
- | Aspect | Rating | Notes |
489
- |--------|--------|-------|
490
- | Readability | [1-5] | [comments] |
491
- | Maintainability | [1-5] | [comments] |
492
- | Testability | [1-5] | [comments] |
493
- | Simplicity | [1-5] | [comments] |
202
+ **CRITICAL:** MUST read old tests before writing new ones. Copy all test cases and business scenarios to domain tests. Do not lose any test coverage.
494
203
 
495
- ### Metrics: [Improved/Same/Worse]
496
- [Insert metrics table from above]
204
+ ### 5.1 Process
205
+ 1. Read ALL test files in old module
206
+ 2. List all test cases and business scenarios
207
+ 3. Write domain tests covering all those scenarios
208
+ 4. Focus on business logic (pure unit tests, no integration needed yet)
497
209
 
498
- ### Performance: [Improved/Same/Worse]
499
- [Performance test results]
210
+ ### 5.2 Entity Tests
211
+ - Behavior methods (state transitions, validations, calculations)
212
+ - Edge cases (zero values, boundary conditions)
213
+ - Business rules
214
+ - NO mocking needed — pure tests
500
215
 
501
- ### Security: [Pass/Fail]
502
- [Security check results]
216
+ ### 5.3 UseCase Tests
217
+ - Mock port interfaces
218
+ - All business flows (happy path + error cases)
219
+ - Input validation
220
+ - Domain event collection (if applicable)
503
221
 
504
- ### Recommendation: [Approve/Revise]
222
+ ### Rule Check Phase 5
223
+ ```bash
224
+ # Run domain tests
225
+ {stack_test_command_for_domain}
505
226
  ```
506
227
 
507
- ### Gate
508
- - [ ] Architecture doc followed
509
- - [ ] Code quality improved
510
- - [ ] Metrics show improvement
511
- - [ ] Performance maintained/improved
512
- - [ ] Security maintained
228
+ ---
513
229
 
514
- ### Feedback Loop
515
- If review fails:
516
- - Return to REFACTOR phase
517
- - Address issues found
518
- - Re-test and re-review
230
+ ## PHASE 6: Integration & Cleanup
519
231
 
520
- ---
232
+ ### 6.1 Update Router/Provider/Registry
233
+ - Add new registration calls
234
+ - Remove old module routes/registrations
235
+ - All endpoints/screens must match the old ones
521
236
 
522
- ## Phase 6: COMPLETE
237
+ ### 6.2 Remove Old Module
238
+ - Delete old module directory ONLY AFTER verifying build + test pass
239
+ - DO NOT delete shared models/types that other modules still use
523
240
 
524
- **Goal**: Finalize and document the refactoring
241
+ ### Rule Check Phase 6
242
+ ```bash
243
+ # Full build
244
+ {stack_full_build_command}
525
245
 
526
- ### Actions
246
+ # Verify old module removed
247
+ test -d {old_module_path} && echo "FAIL: old module exists" || echo "PASS"
527
248
 
528
- 1. Final cleanup:
529
- - [ ] Remove debug code
530
- - [ ] Remove commented code
531
- - [ ] Update documentation
532
- - [ ] Remove TODOs added during refactor
533
- - [ ] Format code (using tool from doc)
534
-
535
- 2. Squash commits (optional):
536
- ```bash
537
- # If many small commits, consider squashing
538
- git rebase -i HEAD~[number of commits]
539
- ```
540
-
541
- 3. Create meaningful commit:
542
- ```bash
543
- git add .
544
- git commit -m "$(cat <<'EOF'
545
- refactor: [scope] - [what was improved]
546
-
547
- Architecture compliance:
548
- - [Pattern 1 from doc applied]
549
- - [Pattern 2 from doc applied]
550
-
551
- Improvements:
552
- - [Improvement 1]
553
- - [Improvement 2]
554
-
555
- Metrics:
556
- - Complexity: -X%
557
- - Duplication: -Y%
558
- - Test coverage: +Z%
559
- EOF
560
- )"
561
- ```
562
-
563
- 4. Create PR:
564
- ```bash
565
- gh pr create --title "refactor: [scope] - [description]" --body "$(cat <<'EOF'
566
- ## Summary
567
- Refactored [area] to align with [architecture doc patterns]
568
-
569
- ## Architecture Reference
570
- - Doc: [path to architecture doc]
571
- - Patterns applied: [list]
572
-
573
- ## What Changed
574
- - [Change 1]
575
- - [Change 2]
576
- - [Change 3]
577
-
578
- ## Why
579
- - [Reason 1]
580
- - [Reason 2]
581
-
582
- ## Metrics
583
- | Metric | Before | After | Change |
584
- |--------|--------|-------|--------|
585
- | [Metric 1] | X | Y | -Z% |
586
- | [Metric 2] | X | Y | +Z% |
587
-
588
- ## Testing
589
- - [ ] All tests pass
590
- - [ ] Coverage maintained: [X%]
591
- - [ ] Manual testing complete
592
- - [ ] Performance validated
593
-
594
- ## Behavior
595
- - [ ] No external behavior changes
596
- - [ ] API unchanged (if applicable)
597
- - [ ] UI unchanged (if applicable)
598
-
599
- ## Checklist
600
- - [ ] Follows architecture doc
601
- - [ ] Tests pass
602
- - [ ] Code reviewed
603
- - [ ] Metrics improved
604
- EOF
605
- )"
606
- ```
607
-
608
- 5. Documentation (if needed):
609
- - Update README if structure changed
610
- - Update architecture docs if patterns evolved
611
- - Add migration guide if needed
612
-
613
- ### Completion Checklist
614
- - [ ] Code follows architecture doc
615
- - [ ] All tests passing
616
- - [ ] Metrics improved
617
- - [ ] Performance maintained/improved
618
- - [ ] Documentation updated
619
- - [ ] PR created
620
- - [ ] No behavior changes
249
+ # Verify no old imports remain
250
+ grep -r "{old_module_import}" --include="*.{ext}" . && echo "FAIL: old imports" || echo "PASS"
251
+ ```
621
252
 
622
253
  ---
623
254
 
624
- ## Quick Reference
625
-
626
- ### Architecture Docs
627
- | Stack | Doc |
628
- |-------|-----|
629
- | All | `clean-architecture.md` |
630
- | Flutter | `flutter-mobile.md` |
631
- | React | `react-frontend.md` |
632
- | Go | `go-backend.md` |
633
- | Laravel | `laravel-backend.md` |
634
- | Remix | `remix-fullstack.md` |
635
- | Monorepo | `monorepo.md` |
636
-
637
- ### Common Code Smells
638
-
639
- | Smell | Description | Refactoring |
640
- |-------|-------------|-------------|
641
- | Long Method | Method > 50 lines | Extract Method |
642
- | Large Class | Class > 300 lines | Extract Class |
643
- | Long Parameter List | > 4 parameters | Introduce Parameter Object |
644
- | Duplicate Code | Same code in multiple places | Extract Method/Class |
645
- | Data Clumps | Same data items together | Introduce Value Object |
646
- | Primitive Obsession | Using primitives instead of objects | Introduce Value Object |
647
- | Feature Envy | Method uses another class more | Move Method |
648
- | God Class | Class does too much | Extract Class, Split Responsibilities |
649
- | Deep Nesting | > 3 levels of nesting | Extract Method, Guard Clauses |
650
- | Dead Code | Unused code | Delete |
651
-
652
- ### Refactoring Patterns
653
-
654
- | Pattern | When to Use | Risk |
655
- |---------|-------------|------|
656
- | Extract Method | Long method, duplicate code | Low |
657
- | Extract Class | Large class, god class | Medium |
658
- | Rename | Unclear names | Low |
659
- | Move Method | Feature envy | Medium |
660
- | Extract Interface | Tight coupling | Medium |
661
- | Replace Conditional with Polymorphism | Complex conditionals | High |
662
- | Introduce Parameter Object | Long parameter list | Low |
663
- | Remove Duplication | Duplicate code | Low |
664
- | Simplify Conditional | Complex boolean logic | Low |
665
- | Break Dependencies | Circular dependencies | High |
666
-
667
- ### Refactoring Safety
255
+ ## REVIEW LOOP
256
+
257
+ After all phases complete, run the full architecture review. **Keep looping until ALL checks pass.**
668
258
 
669
259
  ```
670
- Safe (Low Risk):
671
- - Rename
672
- - Extract Method (within same class)
673
- - Inline temp variable
674
- - Remove dead code
675
-
676
- Medium Risk:
677
- - Extract Class
678
- - Move Method
679
- - Extract Interface
680
- - Change signature
681
-
682
- High Risk:
683
- - Replace inheritance with delegation
684
- - Replace conditional with polymorphism
685
- - Major architecture changes
260
+ LOOP:
261
+ 1. Run /architect-review {stack} {domain}
262
+ 2. Collect violations
263
+ 3. IF violations with severity >= MEDIUM:
264
+ a. Fix all violations
265
+ b. Run full build to verify
266
+ c. Run all tests to verify
267
+ d. GOTO 1
268
+ 4. IF score >= B:
269
+ BREAK Final Report
686
270
  ```
687
271
 
688
- ### Phase Summary
689
-
690
- | Phase | Key Actions | Output |
691
- |-------|-------------|--------|
692
- | ANALYZE | Read arch doc, find smells | Analysis report |
693
- | PLAN | Design strategy per doc | Incremental plan |
694
- | REFACTOR | Apply patterns from doc | Clean code |
695
- | TEST | Verify behavior unchanged | Test results |
696
- | REVIEW | Check compliance, metrics | Review report |
697
- | COMPLETE | Commit, PR, docs | Merged refactor |
698
-
699
- ### When to Stop
700
-
701
- Stop refactoring when:
702
- - [ ] Code follows architecture doc
703
- - [ ] All code smells addressed
704
- - [ ] Metrics show improvement
705
- - [ ] Diminishing returns (over-engineering)
706
- - [ ] Time budget exceeded
707
-
708
- ### Success Criteria
709
-
710
- Refactoring is successful when:
711
- 1. Code follows architecture doc patterns
712
- 2. Code is more readable and maintainable
713
- 3. Complexity reduced (measurably)
714
- 4. Duplication removed
715
- 5. All tests pass
716
- 6. No behavior changes
717
- 7. Performance maintained/improved
718
- 8. Team can understand changes
719
-
720
272
  ---
721
273
 
722
- ## Anti-Patterns to Avoid
274
+ ## Final Report
723
275
 
724
- ### Over-Engineering
725
- ```
726
- DON'T: Add unnecessary abstractions
727
- DON'T: Create patterns not in architecture doc
728
- DON'T: Refactor without clear benefit
729
- ```
276
+ When review loop passes with score >= B:
730
277
 
731
- ### Big Bang Refactoring
732
- ```
733
- DON'T: Refactor entire codebase at once
734
- DO: Incremental, step-by-step refactoring
278
+ ```markdown
279
+ ## Refactor Complete: {module} → {domain}
280
+
281
+ ### Files Created
282
+ - List all new files
283
+
284
+ ### Files Modified
285
+ - List all modified files
286
+
287
+ ### Files Deleted
288
+ - List old module files removed
289
+
290
+ ### Endpoints/Screens Preserved
291
+ | Before | After | Status |
292
+ |--------|-------|--------|
293
+ | All old routes | Same routes, new handlers | Verified |
294
+
295
+ ### Domain Events
296
+ | Event | Listeners |
297
+ |-------|-----------|
298
+
299
+ ### Test Coverage
300
+ - X test files, Y test functions
301
+ - All old test cases migrated: YES
302
+ - Areas covered: value objects, entities, usecases
303
+
304
+ ### Review Status: ALL CHECKS PASS
305
+ - Build: PASS
306
+ - Lint: PASS
307
+ - Domain purity: PASS
308
+ - Old module removed: PASS
309
+ - No old imports: PASS
310
+ - Tests: PASS (X/X)
311
+ - Architecture score: {A/B}
735
312
  ```
736
313
 
737
- ### Changing Behavior
738
- ```
739
- DON'T: Fix bugs during refactoring
740
- DON'T: Add features during refactoring
741
- DO: Pure refactoring only
742
- ```
314
+ ---
743
315
 
744
- ### Ignoring Tests
745
- ```
746
- DON'T: Skip running tests
747
- DON'T: Disable failing tests
748
- DO: Tests pass after every step
749
- ```
316
+ ## Interaction Rules
750
317
 
751
- ### Ignoring Architecture
752
- ```
753
- DON'T: Invent your own patterns
754
- DON'T: Violate architecture doc
755
- DO: Follow architecture doc exactly
756
- ```
318
+ 1. After each phase, report Rule Check results to user
319
+ 2. If a rule fails → auto-fix if you know how, otherwise ask user
320
+ 3. **DO NOT skip any phase** — all rules must pass before moving to next
321
+ 4. If unsure about business logic → **READ the old code carefully, DO NOT invent new logic**
322
+ 5. Preserve behavior — refactor structure only, DO NOT change logic
323
+ 6. **MUST read old test files** before writing new tests
324
+ 7. When multiple modules map to same domain → first module creates domain dir, subsequent add to it
325
+ 8. After completing a module, ask user if they want to refactor the next module
326
+
327
+ ---
328
+
329
+ ## Recommended Agents
330
+
331
+ | Phase | Agent | Purpose |
332
+ |-------|-------|---------|
333
+ | ANALYZE | `@refactor` | Identify refactoring opportunities |
334
+ | ANALYZE | `@code-reviewer` | Code smell detection |
335
+ | PLAN | `@clean-architect` | Architecture alignment |
336
+ | REFACTOR | Stack-specific dev agent | Code per architecture |
337
+ | TEST | `@test-writer` | Write domain tests |
338
+ | REVIEW | `@code-reviewer` | Final quality check |