@atlashub/smartstack-cli 3.16.0 → 3.18.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 (26) hide show
  1. package/dist/index.js +74 -42
  2. package/dist/index.js.map +1 -1
  3. package/dist/mcp-entry.mjs +752 -53
  4. package/dist/mcp-entry.mjs.map +1 -1
  5. package/package.json +1 -1
  6. package/templates/agents/gitflow/finish.md +21 -3
  7. package/templates/agents/gitflow/start.md +14 -4
  8. package/templates/skills/application/templates-backend.md +12 -1
  9. package/templates/skills/business-analyse/SKILL.md +4 -4
  10. package/templates/skills/business-analyse/html/ba-interactive.html +11 -5
  11. package/templates/skills/business-analyse/html/src/scripts/05-render-specs.js +11 -5
  12. package/templates/skills/business-analyse/references/deploy-data-build.md +25 -9
  13. package/templates/skills/business-analyse/references/validation-checklist.md +29 -2
  14. package/templates/skills/business-analyse/steps/step-00-init.md +23 -5
  15. package/templates/skills/business-analyse/steps/step-03a2-analysis.md +21 -3
  16. package/templates/skills/business-analyse/steps/step-03b-ui.md +31 -1
  17. package/templates/skills/business-analyse/steps/step-03d-validate.md +41 -4
  18. package/templates/skills/business-analyse/steps/step-05b-deploy.md +9 -7
  19. package/templates/skills/business-analyse/steps/step-05c-ralph-readiness.md +222 -40
  20. package/templates/skills/ralph-loop/SKILL.md +41 -1
  21. package/templates/skills/ralph-loop/references/category-rules.md +106 -1
  22. package/templates/skills/ralph-loop/references/compact-loop.md +85 -24
  23. package/templates/skills/ralph-loop/references/core-seed-data.md +48 -0
  24. package/templates/skills/ralph-loop/steps/step-00-init.md +30 -54
  25. package/templates/skills/ralph-loop/steps/step-01-task.md +102 -1
  26. package/templates/skills/ralph-loop/steps/step-04-check.md +87 -40
@@ -1,16 +1,17 @@
1
1
  ---
2
2
  name: step-05c-ralph-readiness
3
- description: Validation gate before ralph-loop - verify completeness, integrity, and readiness
4
- model: sonnet
3
+ description: ULTRATHINK quality review + validation gate before ralph-loop
4
+ model: opus
5
5
  next_step: null
6
6
  ---
7
7
 
8
8
  > **Context files:** `_shared.md`
9
9
 
10
- # Step 5c: Ralph Readiness Check
10
+ # Step 5c: ULTRATHINK Quality Review & Ralph Readiness Check
11
11
 
12
12
  ## MANDATORY EXECUTION RULES
13
13
 
14
+ - **ALWAYS** use ULTRATHINK mode for the quality review (section 0b)
14
15
  - **ALWAYS** run ALL validation checks (NEVER skip)
15
16
  - **BLOCKING RULE:** If ANY check fails → STOP, DO NOT proceed to ralph-loop
16
17
  - **ALWAYS** provide actionable fix instructions for failures
@@ -19,7 +20,7 @@ next_step: null
19
20
 
20
21
  ## YOUR TASK
21
22
 
22
- Perform comprehensive validation to ensure the business analysis is ready for implementation via /ralph-loop. This is a **BLOCKING** gate - all checks must pass before development can proceed.
23
+ Perform a deep ULTRATHINK quality review of the entire business analysis output, then run comprehensive structural validation to ensure readiness for /ralph-loop. This is a **BLOCKING** gate all checks must pass before development can proceed.
23
24
 
24
25
  ---
25
26
 
@@ -31,9 +32,177 @@ Display validation banner:
31
32
 
32
33
  ```
33
34
  ═══════════════════════════════════════════════════════════════
34
- RALPH READINESS CHECK - {application_name}
35
+ ULTRATHINK QUALITY REVIEW & RALPH READINESS CHECK
36
+ {application_name}
35
37
  ═══════════════════════════════════════════════════════════════
36
- Validating business analysis completeness before development...
38
+ Phase 1: Deep quality review (ULTRATHINK)...
39
+ Phase 2: Structural validation (8 checks)...
40
+ ```
41
+
42
+ ---
43
+
44
+ ### 0b. ULTRATHINK Deep Quality Review (MANDATORY)
45
+
46
+ > **This section MUST be executed in ULTRATHINK mode.**
47
+ > Take the time to deeply analyze the ENTIRE business analysis output.
48
+ > This is the last chance to catch quality issues before development begins.
49
+
50
+ **Objective:** Perform a thorough, deep-thinking review of the business analysis quality — not just structural checks, but semantic coherence, completeness, and production-readiness.
51
+
52
+ **Process:**
53
+
54
+ 1. **Read ALL module feature.json files** (master + each module)
55
+ 2. **Activate ULTRATHINK** and analyze the following 6 dimensions:
56
+
57
+ #### Dimension 1: Specification Coherence
58
+
59
+ ```
60
+ For EACH module:
61
+ - Do use cases (UCs) tell a coherent story?
62
+ - Are functional requirements (FRs) logically derived from UCs?
63
+ - Do business rules (BRs) cover all edge cases mentioned in UCs?
64
+ - Are gherkin scenarios testing the RIGHT behaviors (not trivial CRUD)?
65
+ - Do entity relationships make domain sense?
66
+
67
+ Flag: Orphan FRs (not linked to any UC), UCs with no FR coverage,
68
+ BRs that don't map to any entity/field
69
+ ```
70
+
71
+ #### Dimension 2: Permission & Security Model
72
+
73
+ ```
74
+ For EACH module:
75
+ - Is the permission hierarchy logical? (admin > manager > contributor > viewer)
76
+ - Are there actions that should be restricted but aren't?
77
+ - Do API endpoints all have permissions assigned?
78
+ - Are there over-permissive roles? (e.g., contributor with delete access)
79
+ - Cross-module: can a user in Module A access data in Module B through indirect routes?
80
+
81
+ Flag: Endpoints without permissions, roles with excessive access,
82
+ missing permission paths
83
+ ```
84
+
85
+ #### Dimension 3: Data Model Integrity
86
+
87
+ ```
88
+ For EACH module:
89
+ - Are all entity relationships bidirectional where needed?
90
+ - Are FK references correct (target entity exists, correct field type)?
91
+ - Are there missing audit fields (CreatedAt, UpdatedAt, CreatedBy)?
92
+ - Do lifecycle states cover all business scenarios?
93
+ - Are cascade delete/update rules safe? (no orphan risk)
94
+
95
+ Cross-module:
96
+ - Are shared entity references correct?
97
+ - Is the dependency graph honest? (no hidden dependencies)
98
+
99
+ Flag: Missing relationships, unsafe cascades, missing audit fields,
100
+ hidden cross-module dependencies
101
+ ```
102
+
103
+ #### Dimension 4: UI/UX Completeness
104
+
105
+ ```
106
+ For EACH module:
107
+ - Does every section have at least one wireframe?
108
+ - Do wireframes cover ALL use cases? (no UC without UI representation)
109
+ - Are navigation entries correct and complete?
110
+ - Do wireframe actions map to real API endpoints?
111
+ - Are form fields aligned with entity attributes?
112
+ - Are validation rules defined for all user-input fields?
113
+
114
+ Flag: UCs with no wireframe, wireframes with unmapped actions,
115
+ missing form validations, navigation gaps
116
+ ```
117
+
118
+ #### Dimension 5: i18n & Messages Quality
119
+
120
+ ```
121
+ For EACH module:
122
+ - Are all user-facing strings covered by i18n keys?
123
+ - Are error messages specific enough? (not generic "Error occurred")
124
+ - Do validation messages reference the field name?
125
+ - Are success/confirmation messages present for all write operations?
126
+ - Are there missing translations in any language?
127
+
128
+ Flag: Generic error messages, missing field-specific validations,
129
+ incomplete language coverage
130
+ ```
131
+
132
+ #### Dimension 6: Implementation Feasibility
133
+
134
+ ```
135
+ For EACH module:
136
+ - Is the handoff.filesToCreate list realistic? (no missing files, no impossible paths)
137
+ - Do brToCodeMapping entries have enough detail for generation?
138
+ - Are API endpoint paths following REST conventions?
139
+ - Are DTO structures aligned with entity attributes?
140
+ - Is the seed data sufficient for testing all use cases?
141
+ - Are there any features that would require infrastructure not in the stack?
142
+
143
+ Flag: Unrealistic file counts, vague BR mappings, non-RESTful routes,
144
+ missing seed data for critical test scenarios
145
+ ```
146
+
147
+ 3. **Produce Quality Verdict:**
148
+
149
+ ```
150
+ ═══════════════════════════════════════════════════════════════
151
+ ULTRATHINK QUALITY REVIEW - RESULTS
152
+ ═══════════════════════════════════════════════════════════════
153
+
154
+ | Dimension | Score | Issues |
155
+ |-----------|-------|--------|
156
+ | Specification Coherence | A/B/C/D | {count} issues |
157
+ | Permission & Security | A/B/C/D | {count} issues |
158
+ | Data Model Integrity | A/B/C/D | {count} issues |
159
+ | UI/UX Completeness | A/B/C/D | {count} issues |
160
+ | i18n & Messages | A/B/C/D | {count} issues |
161
+ | Implementation Feasibility | A/B/C/D | {count} issues |
162
+
163
+ Overall Quality: {A/B/C/D}
164
+ A = Production-ready (0 critical, ≤3 warnings)
165
+ B = Good (0 critical, >3 warnings)
166
+ C = Needs fixes (1-2 critical issues)
167
+ D = Major rework needed (>2 critical issues)
168
+ ```
169
+
170
+ 4. **Display Issues (if any):**
171
+
172
+ ```
173
+ Critical Issues (MUST fix before /ralph-loop):
174
+ ✗ [Dimension] Issue description
175
+ → Fix: Specific action to resolve
176
+
177
+ Warnings (SHOULD fix, not blocking):
178
+ ⚠ [Dimension] Issue description
179
+ → Recommendation: How to improve
180
+
181
+ Suggestions (nice-to-have):
182
+ ℹ [Dimension] Suggestion
183
+ ```
184
+
185
+ 5. **Decision:**
186
+
187
+ ```
188
+ IF overall quality = D:
189
+ BLOCKING ERROR: Major quality issues detected
190
+ → Return to appropriate step to fix critical issues
191
+ → DO NOT proceed to structural validation
192
+
193
+ IF overall quality = C:
194
+ Ask via AskUserQuestion:
195
+ question: "Des problèmes de qualité ont été détectés. Comment souhaitez-vous procéder ?"
196
+ header: "Qualité"
197
+ options:
198
+ - label: "Corriger les problèmes critiques"
199
+ description: "Retourner aux étapes concernées pour corriger"
200
+ - label: "Continuer malgré les problèmes"
201
+ description: "Accepter les risques et poursuivre la validation structurelle"
202
+
203
+ IF overall quality = A or B:
204
+ Display: "✓ Quality review passed — proceeding to structural validation..."
205
+ → Continue to section 1
37
206
  ```
38
207
 
39
208
  ---
@@ -394,10 +563,11 @@ Progress Tracker Validation:
394
563
 
395
564
  **Process:**
396
565
 
397
- 1. Aggregate all validation results
566
+ 1. Aggregate all validation results (quality review + 7 structural checks)
398
567
  2. Calculate readiness score:
399
568
  ```
400
569
  passedChecks / totalChecks * 100
570
+ Quality gate: overall quality must be A or B
401
571
  ```
402
572
 
403
573
  3. Display final report:
@@ -407,17 +577,23 @@ Progress Tracker Validation:
407
577
  RALPH READINESS CHECK - COMPLETE
408
578
  ═══════════════════════════════════════════════════════════════
409
579
 
410
- Validation Summary:
411
- Module status validation: PASS (5/5 modules)
412
- ✓ PRD files validation: PASS (5/5 files)
413
- Dependency graph validation: PASS (4 edges)
414
- ✓ Cross-module references validation: PASS (4 references)
415
- ✓ Handoff completeness check: PASS (5/5 modules)
416
- i18n keys validation: WARNING (1 missing translation)
580
+ ULTRATHINK Quality Review:
581
+ Quality Score: {A/B} {Production-ready / Good}
582
+ Dimensions: {6/6 reviewed}
583
+ Critical issues: {0}
584
+ Warnings: {count}
585
+
586
+ Structural Validation Summary:
587
+ ✓ Module status validation: PASS ({n}/{n} modules)
588
+ ✓ PRD files validation: PASS ({n}/{n} files)
589
+ ✓ Dependency graph validation: PASS ({n} edges)
590
+ ✓ Cross-module references validation: PASS ({n} references)
591
+ ✓ Handoff completeness check: PASS ({n}/{n} modules)
592
+ ⚠ i18n keys validation: WARNING ({n} missing translation)
417
593
  ✓ Master feature validation: PASS
418
594
  ✓ Progress tracker validation: PASS
419
595
 
420
- Readiness Score: 100% (7/7 critical checks passed, 1 warning)
596
+ Readiness Score: 100% (8/8 checks passed, {n} warnings)
421
597
 
422
598
  ═══════════════════════════════════════════════════════════════
423
599
 
@@ -425,7 +601,7 @@ Status: READY FOR DEVELOPMENT ✓
425
601
 
426
602
  Next Steps:
427
603
  1. Address warnings (recommended but not blocking):
428
- - Add missing DE translation for "timeEntry.validation.overlapping" in TimeTracking module
604
+ - {list warnings from quality review + structural checks}
429
605
 
430
606
  2. Review progress tracker: .ralph/progress.txt
431
607
 
@@ -434,14 +610,14 @@ Next Steps:
434
610
  /ralph-loop -r
435
611
 
436
612
  4. Ralph-loop will:
437
- - Process modules in topological order: [Projects, TimeTracking, LeaveManagement, AbsenceManagement, Reporting]
438
- - Generate 183 files across 7 layers
439
- - Execute 247 tasks tracked in progress.txt
613
+ - Process modules in topological order: [{module list}]
614
+ - Generate {n} files across 7 layers
615
+ - Execute {n} tasks tracked in progress.txt
440
616
 
441
617
  ═══════════════════════════════════════════════════════════════
442
618
  ```
443
619
 
444
- **IF readiness score < 100% (critical checks failed):**
620
+ **IF readiness score < 100% OR quality = C/D (critical checks failed):**
445
621
 
446
622
  ```
447
623
  ═══════════════════════════════════════════════════════════════
@@ -450,21 +626,24 @@ Next Steps:
450
626
 
451
627
  Status: NOT READY FOR DEVELOPMENT ✗
452
628
 
453
- Critical Issues Found:
454
- Module status validation: FAIL (1/5 modules incomplete)
455
- - Reporting module status is "specified", must be "handed-off"
456
- - Fix: Return to step-05a-handoff.md for Reporting module
629
+ {IF quality = C/D:}
630
+ Quality Issues Found:
631
+ ULTRATHINK quality review: {C/D} {Needs fixes / Major rework}
632
+ - {List critical quality issues from section 0b}
633
+ - Fix: Return to appropriate step (see quality review details above)
457
634
 
458
- PRD files validation: FAIL (1/5 files invalid)
459
- - prd-Reporting.json has wrong structure (filesToCreate at root level)
460
- - Fix: Re-run ss derive-prd --feature docs/business/HumanResources/Reporting/business-analyse/v1.0/feature.json --output .ralph/prd-Reporting.json
635
+ {IF structural checks failed:}
636
+ Structural Issues Found:
637
+ {check name}: FAIL ({details})
638
+ - {specific issue}
639
+ - Fix: {specific action}
461
640
 
462
641
  Required Actions:
463
642
  1. Fix all critical issues listed above
464
643
  2. Re-run validation: load step-05c-ralph-readiness.md
465
- 3. Only proceed to /ralph-loop when all critical checks pass
644
+ 3. Only proceed to /ralph-loop when all checks pass AND quality ≥ B
466
645
 
467
- DO NOT PROCEED TO /ralph-loop UNTIL ALL CRITICAL CHECKS PASS
646
+ DO NOT PROCEED TO /ralph-loop UNTIL ALL CHECKS PASS
468
647
  ═══════════════════════════════════════════════════════════════
469
648
  ```
470
649
 
@@ -474,22 +653,25 @@ DO NOT PROCEED TO /ralph-loop UNTIL ALL CRITICAL CHECKS PASS
474
653
 
475
654
  Before displaying final report, VERIFY:
476
655
 
477
- 1. **ALL validation checks executed** (never skip)
478
- 2. **Results clearly marked** (PASS/FAIL/WARNING)
479
- 3. **Actionable fixes provided** for all failures
480
- 4. **Readiness score calculated** correctly
481
- 5. **Next steps displayed** with exact commands
482
- 6. **Blocking errors prevent progression** (no false positives)
656
+ 1. **ULTRATHINK quality review executed** (6 dimensions analyzed)
657
+ 2. **Quality verdict displayed** with scores per dimension
658
+ 3. **ALL 8 structural validation checks executed** (never skip)
659
+ 4. **Results clearly marked** (PASS/FAIL/WARNING)
660
+ 5. **Actionable fixes provided** for all failures
661
+ 6. **Readiness score calculated** correctly
662
+ 7. **Next steps displayed** with exact commands
663
+ 8. **Blocking errors prevent progression** (no false positives)
483
664
 
484
665
  ---
485
666
 
486
667
  ## SUCCESS CRITERIA
487
668
 
488
- - All 7 critical validation checks executed
669
+ - ULTRATHINK quality review completed with overall score A or B
670
+ - All 8 critical validation checks executed (quality review + 7 structural)
489
671
  - Clear PASS/FAIL/WARNING status for each check
490
672
  - Readiness score displayed (100% = all critical checks passed)
491
673
  - Actionable fix instructions for all failures
492
- - User can proceed to /ralph-loop only if readiness score = 100%
674
+ - User can proceed to /ralph-loop only if readiness score = 100% AND quality ≥ B
493
675
  - Warnings documented but not blocking
494
676
 
495
677
  ---
@@ -498,6 +680,7 @@ Before displaying final report, VERIFY:
498
680
 
499
681
  **Why this gate matters:**
500
682
 
683
+ - **ULTRATHINK catches semantic issues** that structural checks miss (orphan UCs, incoherent permissions, missing UI flows)
501
684
  - Prevents incomplete handoffs from reaching development
502
685
  - Catches structural issues early (PRD validation)
503
686
  - Verifies cross-module integrity before code generation
@@ -506,8 +689,7 @@ Before displaying final report, VERIFY:
506
689
 
507
690
  **When to run this gate:**
508
691
 
509
- - Automatically at end of step-05b-deploy.md (recommended)
510
- - Manually before /ralph-loop if user wants to verify
692
+ - **Automatically at end of step-05b-deploy.md (MANDATORY)**
511
693
  - After fixing any handoff issues to re-validate
512
694
 
513
695
  **What happens if checks fail:**
@@ -515,4 +697,4 @@ Before displaying final report, VERIFY:
515
697
  - Development is BLOCKED until issues are fixed
516
698
  - User returns to appropriate step to fix issues
517
699
  - Re-run validation after fixes
518
- - Only proceed when all critical checks pass
700
+ - Only proceed when all critical checks pass AND quality review passes
@@ -95,8 +95,41 @@ LOAD → GENERATE → COMPILE → TEST → [FAIL?] → FIX → RE-TEST → [PASS
95
95
  - `scaffold_tests` — test generation
96
96
  </mcp_requirements>
97
97
 
98
+ <execution_guarantee>
99
+
100
+ ## EXECUTION GUARANTEE — READ THIS FIRST
101
+
102
+ **Ralph-loop executes ALL tasks from start to finish. No exceptions.**
103
+
104
+ When the user invokes `/ralph-loop`, they are giving you the instruction to:
105
+ 1. Initialize the loop (step-00)
106
+ 2. Load ALL tasks (step-01)
107
+ 3. Execute the FIRST task (step-02)
108
+ 4. Commit (step-03)
109
+ 5. Enter the COMPACT LOOP (step-04 → compact-loop.md)
110
+ 6. **Execute ALL remaining tasks autonomously** (compact loop repeats)
111
+ 7. Generate the final report (step-05)
112
+
113
+ **You MUST NOT:**
114
+ - Stop after the first task to "ask for confirmation"
115
+ - Set `max_iterations = 1` or any reduced value
116
+ - Ask the user to choose between supervised/autonomous mode
117
+ - Ask the user to choose a completion promise
118
+ - Wait for user input between iterations
119
+ - Delegate the loop to sub-agents (except team mode)
120
+
121
+ **The ONLY valid stop conditions are:**
122
+ - ALL tasks completed (→ step-05 report)
123
+ - `max_iterations` reached (user set via `-m N`)
124
+ - Dead-end (all remaining blocked/failed)
125
+ - User Ctrl+C
126
+
127
+ **If you stop for any other reason, you have VIOLATED this guarantee.**
128
+
129
+ </execution_guarantee>
130
+
98
131
  <entry_point>
99
- **FIRST ACTION:** Load `steps/step-00-init.md`
132
+ **FIRST ACTION:** Load `steps/step-00-init.md` — then execute ALL steps through to step-05 without stopping.
100
133
  </entry_point>
101
134
 
102
135
  <step_files>
@@ -134,6 +167,13 @@ LOAD → GENERATE → COMPILE → TEST → [FAIL?] → FIX → RE-TEST → [PASS
134
167
 
135
168
  <execution_rules>
136
169
 
170
+ ### NON-NEGOTIABLE — Autonomous Full Execution
171
+ - **EXECUTE ALL TASKS** — from first to last, no user interaction, no pause, no confirmation
172
+ - **NEVER ask the user** — no mode selection, no completion promise choice, no "shall I continue?"
173
+ - **NEVER stop after first task** — the first task is just the beginning, NOT the end
174
+ - **NEVER set max_iterations = 1** — unless the user explicitly passed `-m 1`
175
+
176
+ ### Loop Mechanics
137
177
  - **Single module:** Main agent runs compact loop (NEVER delegate to sub-agent)
138
178
  - **Multi-module (2+):** Team lead + module workers via TeamCreate (see references/team-orchestration.md)
139
179
  - **Load step files ONCE** — after first iteration, use compact-loop.md
@@ -141,6 +141,86 @@ Rules:
141
141
  - DTOs separate from domain entities
142
142
  - Service interfaces in Application, implementations in Infrastructure
143
143
 
144
+ **Tenant isolation (BLOCKING — SECURITY CRITICAL):**
145
+
146
+ > **ROOT CAUSE (test-v4-005):** Services were generated WITHOUT TenantId filtering,
147
+ > creating cross-tenant data leakage on ALL 70+ CRUD endpoints.
148
+ > This is an OWASP A01 (Broken Access Control) vulnerability.
149
+
150
+ - ALL queries on tenant entities MUST include `.Where(x => x.TenantId == _currentUser.TenantId)`
151
+ - ALL entity creation MUST pass `_currentUser.TenantId` as first parameter to `Entity.Create(tenantId, ...)`
152
+ - NEVER use `new Entity { }` without `TenantId =` — always prefer factory method `Entity.Create()`
153
+ - NEVER use `Guid.Empty` as a placeholder for userId, tenantId, or any business identifier
154
+ - Service constructor MUST inject `ICurrentUserService _currentUser` to access TenantId
155
+
156
+ **MANDATORY Service Template (use as skeleton for ALL services):**
157
+
158
+ ```csharp
159
+ public class {Entity}Service : I{Entity}Service
160
+ {
161
+ private readonly IExtensionsDbContext _db;
162
+ private readonly ICurrentUserService _currentUser;
163
+
164
+ public {Entity}Service(IExtensionsDbContext db, ICurrentUserService currentUser)
165
+ {
166
+ _db = db;
167
+ _currentUser = currentUser;
168
+ }
169
+
170
+ public async Task<PagedResult<{Entity}Response>> GetAllAsync(/* filters */, CancellationToken ct)
171
+ {
172
+ var tenantId = _currentUser.TenantId;
173
+ var query = _db.{Entities}
174
+ .Where(x => x.TenantId == tenantId) // ← MANDATORY tenant filter
175
+ .AsQueryable();
176
+ // ... apply filters, pagination, projection to Response DTO
177
+ }
178
+
179
+ public async Task<{Entity}Response?> GetByIdAsync(Guid id, CancellationToken ct)
180
+ {
181
+ var tenantId = _currentUser.TenantId;
182
+ var entity = await _db.{Entities}
183
+ .Where(x => x.TenantId == tenantId) // ← MANDATORY tenant filter
184
+ .FirstOrDefaultAsync(x => x.Id == id, ct);
185
+ // ...
186
+ }
187
+
188
+ public async Task<{Entity}Response> CreateAsync(Create{Entity}Dto dto, CancellationToken ct)
189
+ {
190
+ var entity = {Entity}.Create(_currentUser.TenantId, /* dto fields */);
191
+ // ← TenantId as FIRST parameter
192
+ _db.{Entities}.Add(entity);
193
+ await _db.SaveChangesAsync(ct);
194
+ return MapToResponse(entity);
195
+ }
196
+
197
+ public async Task<{Entity}Response> UpdateAsync(Guid id, Update{Entity}Dto dto, CancellationToken ct)
198
+ {
199
+ var entity = await _db.{Entities}
200
+ .Where(x => x.TenantId == _currentUser.TenantId) // ← MANDATORY
201
+ .FirstOrDefaultAsync(x => x.Id == id, ct)
202
+ ?? throw new NotFoundException(nameof({Entity}), id);
203
+ // ... update fields
204
+ }
205
+
206
+ public async Task DeleteAsync(Guid id, CancellationToken ct)
207
+ {
208
+ var entity = await _db.{Entities}
209
+ .Where(x => x.TenantId == _currentUser.TenantId) // ← MANDATORY
210
+ .FirstOrDefaultAsync(x => x.Id == id, ct)
211
+ ?? throw new NotFoundException(nameof({Entity}), id);
212
+ // ...
213
+ }
214
+
215
+ private static {Entity}Response MapToResponse({Entity} entity) => new()
216
+ {
217
+ // Map entity fields to response DTO
218
+ };
219
+ }
220
+ ```
221
+
222
+ **POST-CHECK after writing ANY service:** Grep the file for `TenantId`. If 0 occurrences → FAIL, rewrite with tenant filtering.
223
+
144
224
  **Lifecycle-aware services:**
145
225
  - Services operating on entities with a `lifeCycle` (status field) MUST validate entity state before mutations
146
226
  - Example: `if (entity.Status == EmployeeStatus.Terminated) throw new BusinessException("Cannot update terminated employee")`
@@ -154,10 +234,31 @@ Rules:
154
234
  - DependencyInjection.cs MUST NOT be empty or contain only TODO comments
155
235
  - After writing validators, VERIFY DI registration exists — if missing, add it immediately
156
236
 
237
+ **POST-CHECK after writing validators:**
238
+ ```bash
239
+ # Count Create validators vs Update validators
240
+ CREATE_COUNT=$(find . -path "*/Validators/*" -name "Create*Validator.cs" | wc -l)
241
+ UPDATE_COUNT=$(find . -path "*/Validators/*" -name "Update*Validator.cs" | wc -l)
242
+ if [ "$CREATE_COUNT" -ne "$UPDATE_COUNT" ]; then
243
+ echo "VALIDATOR MISMATCH: $CREATE_COUNT Create vs $UPDATE_COUNT Update → MUST be equal"
244
+ # List missing UpdateValidators and CREATE them
245
+ fi
246
+ ```
247
+
248
+ **Mapper pattern (DRY):**
249
+ - Each service MUST include a `private static {Entity}Response MapToResponse({Entity} entity)` method
250
+ - For complex mappings with related entities, use an extension method in `Application/Mappings/{Module}Mappings.cs`
251
+ - NEVER duplicate mapping logic between GetAll, GetById, Create, Update — always call MapToResponse
252
+
157
253
  **FORBIDDEN:**
158
254
  - Empty DependencyInjection.cs with `// TODO` placeholder
159
255
  - CreateValidator without matching UpdateValidator
160
256
  - Validators not registered in DI container
257
+ - Service query without TenantId filter (cross-tenant data leak)
258
+ - `new Entity { }` without TenantId assignment
259
+ - `Guid.Empty` as a business value in services or controllers
260
+ - Entity.Create() without tenantId as first parameter
261
+ - Duplicated mapping logic (entity→response) in multiple methods
161
262
 
162
263
  ---
163
264
 
@@ -269,9 +370,13 @@ useXxx with raw axios inside hooks → hooks MUST use the shared apiCl
269
370
 
270
371
  **MCP:** `scaffold_tests`, `analyze_test_coverage`
271
372
 
373
+ > **CRITICAL:** Test generation is a MANDATORY category. If the PRD has no test tasks,
374
+ > the category completeness check (step-01 section 4b) will inject a guardrail task.
375
+ > Test projects MUST be created as the FIRST action in this category — before generating any test files.
376
+
272
377
  **Execution sequence:**
273
378
 
274
- 1. **Ensure test projects exist:**
379
+ 1. **Ensure test projects exist (FIRST — before any test generation):**
275
380
  ```bash
276
381
  # Unit test project
277
382
  UNIT_TEST_PROJECT="tests/${PROJECT_NAME}.Tests.Unit"