sdd-mcp-server 3.5.1 → 5.0.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 (124) hide show
  1. package/README.md +92 -683
  2. package/agents/architect.md +15 -93
  3. package/agents/implementer.md +16 -141
  4. package/agents/planner.md +16 -84
  5. package/agents/reviewer.md +16 -239
  6. package/agents/security-auditor.md +16 -114
  7. package/agents/tdd-guide.md +17 -228
  8. package/dist/adapters/cli/SDDToolAdapter.d.ts +14 -8
  9. package/dist/adapters/cli/SDDToolAdapter.js +188 -405
  10. package/dist/adapters/cli/SDDToolAdapter.js.map +1 -1
  11. package/dist/application/services/ContextCompactionService.d.ts +88 -16
  12. package/dist/application/services/ContextCompactionService.js +474 -187
  13. package/dist/application/services/ContextCompactionService.js.map +1 -1
  14. package/dist/application/services/ProjectService.js +3 -3
  15. package/dist/application/services/ProjectService.js.map +1 -1
  16. package/dist/application/services/SpecPathResolver.d.ts +24 -0
  17. package/dist/application/services/SpecPathResolver.js +70 -0
  18. package/dist/application/services/SpecPathResolver.js.map +1 -0
  19. package/dist/application/services/WorkflowEngineService.d.ts +214 -50
  20. package/dist/application/services/WorkflowEngineService.js +1447 -292
  21. package/dist/application/services/WorkflowEngineService.js.map +1 -1
  22. package/dist/application/services/WorkflowErrors.d.ts +16 -0
  23. package/dist/application/services/WorkflowErrors.js +53 -0
  24. package/dist/application/services/WorkflowErrors.js.map +1 -0
  25. package/dist/application/services/WorkflowValidationService.d.ts +25 -46
  26. package/dist/application/services/WorkflowValidationService.js +284 -627
  27. package/dist/application/services/WorkflowValidationService.js.map +1 -1
  28. package/dist/cli/install-skills.d.ts +3 -9
  29. package/dist/cli/install-skills.js +129 -174
  30. package/dist/cli/install-skills.js.map +1 -1
  31. package/dist/cli/install-target.d.ts +42 -8
  32. package/dist/cli/install-target.js +27 -9
  33. package/dist/cli/install-target.js.map +1 -1
  34. package/dist/cli/sdd-mcp-cli.d.ts +1 -1
  35. package/dist/cli/sdd-mcp-cli.js +7 -6
  36. package/dist/cli/sdd-mcp-cli.js.map +1 -1
  37. package/dist/cli/tool-support/claude-code.js +17 -34
  38. package/dist/cli/tool-support/claude-code.js.map +1 -1
  39. package/dist/cli/tool-support/codex.d.ts +0 -53
  40. package/dist/cli/tool-support/codex.js +10 -94
  41. package/dist/cli/tool-support/codex.js.map +1 -1
  42. package/dist/cli/tool-support/index.d.ts +3 -2
  43. package/dist/cli/tool-support/index.js +3 -1
  44. package/dist/cli/tool-support/index.js.map +1 -1
  45. package/dist/cli/tool-support/mcp-registration.d.ts +22 -0
  46. package/dist/cli/tool-support/mcp-registration.js +275 -0
  47. package/dist/cli/tool-support/mcp-registration.js.map +1 -0
  48. package/dist/cli/tool-support/omp.d.ts +5 -0
  49. package/dist/cli/tool-support/omp.js +47 -0
  50. package/dist/cli/tool-support/omp.js.map +1 -0
  51. package/dist/cli/tool-support/root-guidance.d.ts +2 -9
  52. package/dist/cli/tool-support/root-guidance.js +44 -37
  53. package/dist/cli/tool-support/root-guidance.js.map +1 -1
  54. package/dist/cli/tool-support/target-agent-renderer.d.ts +1 -0
  55. package/dist/cli/tool-support/target-agent-renderer.js +37 -4
  56. package/dist/cli/tool-support/target-agent-renderer.js.map +1 -1
  57. package/dist/cli/tool-support/target-installer.d.ts +9 -3
  58. package/dist/cli/tool-support/target-installer.js +100 -26
  59. package/dist/cli/tool-support/target-installer.js.map +1 -1
  60. package/dist/cli/utils/preserving-writer.d.ts +56 -0
  61. package/dist/cli/utils/preserving-writer.js +603 -10
  62. package/dist/cli/utils/preserving-writer.js.map +1 -1
  63. package/dist/domain/ports.d.ts +4 -0
  64. package/dist/domain/types.d.ts +52 -7
  65. package/dist/domain/types.js +5 -4
  66. package/dist/domain/types.js.map +1 -1
  67. package/dist/index.d.ts +13 -10
  68. package/dist/index.js +16 -1199
  69. package/dist/index.js.map +1 -1
  70. package/dist/infrastructure/adapters/NodeFileSystemAdapter.d.ts +3 -0
  71. package/dist/infrastructure/adapters/NodeFileSystemAdapter.js +10 -0
  72. package/dist/infrastructure/adapters/NodeFileSystemAdapter.js.map +1 -1
  73. package/dist/infrastructure/mcp/CapabilityNegotiator.js +3 -3
  74. package/dist/infrastructure/mcp/CapabilityNegotiator.js.map +1 -1
  75. package/dist/infrastructure/mcp/MCPServer.js +13 -13
  76. package/dist/infrastructure/mcp/MCPServer.js.map +1 -1
  77. package/dist/infrastructure/mcp/ToolRegistry.d.ts +5 -1
  78. package/dist/infrastructure/mcp/ToolRegistry.js +11 -4
  79. package/dist/infrastructure/mcp/ToolRegistry.js.map +1 -1
  80. package/dist/infrastructure/mcp/sddToolDefinitions.d.ts +6 -0
  81. package/dist/infrastructure/mcp/sddToolDefinitions.js +110 -0
  82. package/dist/infrastructure/mcp/sddToolDefinitions.js.map +1 -0
  83. package/dist/infrastructure/schemas/project.schema.d.ts +2 -2
  84. package/dist/infrastructure/schemas/project.schema.js +2 -2
  85. package/dist/infrastructure/schemas/project.schema.js.map +1 -1
  86. package/dist/shared/version.d.ts +3 -0
  87. package/dist/shared/version.js +4 -0
  88. package/dist/shared/version.js.map +1 -0
  89. package/dist/utils/atomicWrite.d.ts +8 -35
  90. package/dist/utils/atomicWrite.js +24 -57
  91. package/dist/utils/atomicWrite.js.map +1 -1
  92. package/dist/utils/withFilesystemLock.d.ts +22 -0
  93. package/dist/utils/withFilesystemLock.js +219 -0
  94. package/dist/utils/withFilesystemLock.js.map +1 -0
  95. package/mcp-server.js +5 -2883
  96. package/package.json +8 -3
  97. package/scripts/context-usage-report.mjs +602 -0
  98. package/sdd-entry.js +17 -6
  99. package/skills/sdd-commit/REFERENCE.md +31 -0
  100. package/skills/sdd-commit/SKILL.md +17 -273
  101. package/skills/sdd-design/REFERENCE.md +51 -0
  102. package/skills/sdd-design/SKILL.md +25 -262
  103. package/skills/sdd-implement/REFERENCE.md +30 -0
  104. package/skills/sdd-implement/SKILL.md +27 -284
  105. package/skills/sdd-requirements/REFERENCE.md +39 -0
  106. package/skills/sdd-requirements/SKILL.md +28 -132
  107. package/skills/sdd-review/REFERENCE.md +26 -0
  108. package/skills/sdd-review/SKILL.md +17 -181
  109. package/skills/sdd-security-check/REFERENCE.md +19 -0
  110. package/skills/sdd-security-check/SKILL.md +18 -184
  111. package/skills/sdd-steering/REFERENCE.md +25 -0
  112. package/skills/sdd-steering/SKILL.md +18 -216
  113. package/skills/sdd-steering-custom/REFERENCE.md +27 -0
  114. package/skills/sdd-steering-custom/SKILL.md +19 -203
  115. package/skills/sdd-tasks/REFERENCE.md +25 -0
  116. package/skills/sdd-tasks/SKILL.md +27 -244
  117. package/skills/sdd-test-gen/REFERENCE.md +15 -0
  118. package/skills/sdd-test-gen/SKILL.md +17 -287
  119. package/skills/simple-task/REFERENCE.md +22 -0
  120. package/skills/simple-task/SKILL.md +17 -138
  121. package/templates/CLAUDE.md +13 -31
  122. package/templates/codex-AGENTS.md +7 -9
  123. package/rules/git-workflow.md +0 -92
  124. package/rules/sdd-workflow.md +0 -116
@@ -1,264 +1,47 @@
1
1
  ---
2
2
  name: sdd-tasks
3
- description: Generate TDD task breakdown for SDD workflow. Use when breaking down design into implementable tasks with test-first approach. Invoked via /sdd-tasks <feature-name>.
3
+ description: Generate an approved-design task plan with test-first slices and measurable completion.
4
+ disable-model-invocation: true
4
5
  ---
5
6
 
6
- # SDD Task Breakdown Generation
7
+ # SDD Tasks
7
8
 
8
- Generate comprehensive TDD-based task breakdowns that translate approved designs into implementable work items.
9
+ The user invokes this Skill; backend lifecycle calls are internal. Never tell the user to call a raw MCP tool or expose revision, hash, fingerprint, or backend JSON except in explicit debug output.
9
10
 
10
- ## Prerequisites
11
+ ## Resolve and Restore
11
12
 
12
- Before generating tasks:
13
- 1. Design must be generated using `/sdd-design`
14
- 2. Design phase should be approved (use `sdd-approve design` MCP tool)
15
- 3. Review the design document in `.spec/specs/{feature}/design.md`
13
+ 1. Internally resolve status. If no feature name is supplied, resume the sole incomplete feature or ask the user to select when several exist.
14
+ 2. Design and requirements must be approved. If durable status says otherwise, present the persisted blocker and make no file change.
15
+ 3. Load the latest approved compact context before method work. Load an unapproved tasks draft only with full mode and explicit unapproved inclusion.
16
+ 4. The saved test-case-review choice is authoritative. Ask once only when status has no choice; reuse it on every revision.
17
+ 5. If status reports an observed artifact identity for an orphan or manual edit, read that exact tasks file before revising. Never acknowledge its hash without inspecting and deliberately incorporating or replacing its content.
16
18
 
17
- ## Workflow
19
+ If the runtime is unavailable because of host permission, report an actionable reload/trust or policy blocker; never substitute manual backend instructions.
18
20
 
19
- ### Step 1: Verify Prerequisites
21
+ ## Method and Artifact Contract
20
22
 
21
- Use `sdd-status` MCP tool to verify:
22
- - `design.generated: true`
23
- - `design.approved: true` (recommended before tasks)
23
+ 1. Map every requirement and design decision to small, ordered implementation and verification slices.
24
+ 2. Use unique `### N.M ...` task sections with same-line labels `**Covers:**`, `**Dependencies:**`, `**TDD:**`, `**Affected artifacts:**`, `**Acceptance criteria:**`, and `**Verification:**`.
25
+ 3. `Covers`, dependencies, and affected artifacts are comma-separated; an empty set is exactly `none`. Dependencies name existing task IDs and must be acyclic.
26
+ 4. `TDD` is exactly `required` or `not-applicable — <reason>`. Behavioral work uses RED → GREEN → REFACTOR and covers relevant boundaries, errors, transitions, security, migration, and integration.
27
+ 5. Mark concurrency only for genuinely independent slices.
24
28
 
25
- ### Step 2: Review Design
29
+ Internally submit complete Markdown with the exact revision and artifact identity last observed and the persisted review choice. Submission is the canonical write. Present the saved path and concise validation outcome. A failed validation remains a durable draft to revise and cannot advance.
26
30
 
27
- 1. Read `.spec/specs/{feature}/design.md`
28
- 2. Identify all components to implement
29
- 3. Note interfaces and data models
30
- 4. Understand dependencies between components
31
+ ## Human Gates
31
32
 
32
- ### Step 3: Apply TDD Workflow
33
+ If test-case review is required, present the concrete behavior, boundary, and error cases. Only explicit confirmation records the internal checkpoint for the exact tasks revision and artifact. This is separate from approval.
33
34
 
34
- For each task, follow the Red-Green-Refactor cycle:
35
+ After validation and any required review, ask **“Approve these implementation tasks?”** Only an unambiguous affirmative answer in this Skill flow permits internal approval of the exact reviewed artifact. Never self-approve. Reread status after each checkpoint and approval.
35
36
 
36
- ```
37
- ┌─────────────────────────────────────────────────────────────┐
38
- │ TDD CYCLE │
39
- ├─────────────────────────────────────────────────────────────┤
40
- │ │
41
- │ 1. RED ──────> Write failing test first │
42
- │ (Test describes expected behavior) │
43
- │ │
44
- │ 2. GREEN ──────> Write minimal code to pass │
45
- │ (Just enough to make test green) │
46
- │ │
47
- │ 3. REFACTOR ────> Clean up, maintain tests passing │
48
- │ (Improve design without breaking) │
49
- │ │
50
- │ ───────────────────────────────────────────────────── │
51
- │ REPEAT │
52
- └─────────────────────────────────────────────────────────────┘
53
- ```
54
-
55
- ### Step 4: Choose Test Case Review Checkpoint
56
-
57
- Ask the user whether they want to review TDD test cases before implementation:
58
-
59
- - If yes, enable the checkpoint when generating tasks by setting `reviewTestCases: true` where the MCP tool supports it, or record the choice in `spec.json` under `workflow_options.review_test_cases`.
60
- - Generate a concise **Test Case Review Checklist** in `tasks.md` listing the behavior, edge, and error scenarios that need approval.
61
- - Before approving tasks, the user or agent should run `sdd-review-test-cases` after reviewing the test cases.
62
-
63
- Keep this checkpoint optional. If the user declines, continue with normal task approval.
64
-
65
- ### Step 5: Apply Test Pyramid
66
-
67
- Structure tests following the 70/20/10 ratio:
68
-
69
- ```
70
- ╱╲
71
- ╱ ╲
72
- ╱ E2E╲ 10% - Critical user journeys
73
- ╱──────╲
74
- ╱ ╲
75
- ╱Integration╲ 20% - Component interactions
76
- ╱────────────╲
77
- ╱ ╲
78
- ╱ Unit Tests ╲ 70% - Individual functions
79
- ╱──────────────────╲
80
- ```
81
-
82
- | Level | Coverage | Scope | Speed |
83
- |-------|----------|-------|-------|
84
- | **Unit** | 70% | Single function/class | Fast (ms) |
85
- | **Integration** | 20% | Component interactions | Medium (s) |
86
- | **E2E** | 10% | Full user journeys | Slow (min) |
87
-
88
- ### Step 6: Generate Task Breakdown
89
-
90
- Structure tasks hierarchically:
91
-
92
- ```markdown
93
- # Tasks: {Feature Name}
94
-
95
- ## Overview
96
- {Summary of implementation approach}
97
-
98
- ## Task Groups
99
-
100
- ### 1. {Component/Layer Name}
101
-
102
- #### 1.1 {Task Name}
103
- **Type:** Unit | Integration | E2E
104
- **Estimated Effort:** S | M | L | XL
105
- **Dependencies:** {Task IDs}
106
-
107
- **TDD Steps:**
108
- 1. RED: Write test for {specific behavior}
109
- ```typescript
110
- describe('{Component}', () => {
111
- it('should {expected behavior}', () => {
112
- // Arrange
113
- // Act
114
- // Assert
115
- });
116
- });
117
- ```
118
- 2. GREEN: Implement {minimal solution}
119
- 3. REFACTOR: {Specific improvements}
120
-
121
- **Acceptance Criteria:**
122
- - [ ] Test passes
123
- - [ ] Code coverage >= 80%
124
- - [ ] No lint errors
125
-
126
- #### 1.2 {Next Task}
127
- ...
128
-
129
- ### 2. {Next Component}
130
- ...
131
-
132
- ## Implementation Order
133
-
134
- ```
135
- [1.1] ──> [1.2] ──> [2.1]
136
- │
137
- └──> [1.3] ──> [2.2]
138
- ```
139
-
140
- ## Definition of Done
141
- - [ ] All tests pass
142
- - [ ] Code coverage >= 80%
143
- - [ ] No lint/type errors
144
- - [ ] TDD test cases reviewed (if checkpoint enabled)
145
- - [ ] Code reviewed
146
- - [ ] Documentation updated
147
- ```
148
-
149
- ### Step 7: Task Sizing Guidelines
150
-
151
- | Size | Description | Test Count | Time |
152
- |------|-------------|------------|------|
153
- | **S** | Single function, 1-2 tests | 1-2 | < 1 hour |
154
- | **M** | Multiple functions, 3-5 tests | 3-5 | 1-4 hours |
155
- | **L** | Component with integration | 5-10 | 4-8 hours |
156
- | **XL** | Complex component, many edge cases | 10+ | 1-2 days |
157
-
158
- ### Step 8: Test-First Task Template
159
-
160
- For each implementation task:
161
-
162
- ```markdown
163
- #### Task {X.Y}: {Task Name}
164
-
165
- **Component:** {ComponentName}
166
- **Type:** Unit Test → Implementation
167
-
168
- **Test Scenarios:**
169
- 1. Happy path: {Expected behavior when inputs are valid}
170
- 2. Edge case: {Boundary conditions}
171
- 3. Error case: {Invalid inputs, failures}
172
-
173
- **Test Code (RED):**
174
- ```typescript
175
- import { {Component} } from './{component}';
176
-
177
- describe('{Component}', () => {
178
- describe('{method}', () => {
179
- it('should {happy path behavior}', async () => {
180
- // Arrange
181
- const input = { /* valid input */ };
182
-
183
- // Act
184
- const result = await component.method(input);
185
-
186
- // Assert
187
- expect(result).toEqual({ /* expected */ });
188
- });
189
-
190
- it('should throw when {error condition}', async () => {
191
- // Arrange
192
- const invalidInput = { /* invalid */ };
193
-
194
- // Act & Assert
195
- await expect(component.method(invalidInput))
196
- .rejects.toThrow('{ErrorType}');
197
- });
198
- });
199
- });
200
- ```
201
-
202
- **Implementation (GREEN):**
203
- {Brief description of minimal implementation}
204
-
205
- **Refactor:**
206
- - Extract {helper function} if needed
207
- - Apply {specific pattern}
208
- ```
209
-
210
- ### Step 9: Save and Execute
211
-
212
- 1. Save tasks to `.spec/specs/{feature}/tasks.md`
213
- 2. If test-case review is enabled, review the Test Case Review Checklist and run `sdd-review-test-cases`
214
- 3. Use `sdd-approve tasks` MCP tool to mark phase complete
215
- 4. Use `sdd-spec-impl` MCP tool to execute tasks with TDD
216
-
217
- ## MCP Tool Integration
218
-
219
- | Tool | When to Use |
220
- |------|-------------|
221
- | `sdd-status` | Verify design phase complete |
222
- | `sdd-review-test-cases` | Mark optional TDD test-case review complete |
223
- | `sdd-approve` | Mark tasks phase as approved |
224
- | `sdd-spec-impl` | Execute tasks using TDD methodology |
225
- | `sdd-quality-check` | Validate code quality during implementation |
226
-
227
- ## Quality Checklist
228
-
229
- - [ ] All design components have corresponding tasks
230
- - [ ] Tasks follow TDD (test first)
231
- - [ ] Test pyramid ratio maintained (70/20/10)
232
- - [ ] Dependencies between tasks are clear
233
- - [ ] Each task has specific acceptance criteria
234
- - [ ] Tasks are sized appropriately (avoid XL when possible)
235
- - [ ] Implementation order respects dependencies
236
- - [ ] Definition of Done is clear
237
-
238
- ## Steering Document References
239
-
240
- Apply these steering documents during task breakdown:
241
-
242
- | Document | Purpose | Key Application |
243
- |----------|---------|-----------------|
244
- | `.spec/steering/tdd-guideline.md` | Test-Driven Development | Structure all tasks using Red-Green-Refactor cycle, follow test pyramid (70/20/10) |
37
+ ## Specialist Delegation
245
38
 
246
- **Key TDD Principles for Tasks:**
247
- 1. **RED**: Every task starts with writing a failing test
248
- 2. **GREEN**: Implement minimal code to pass the test
249
- 3. **REFACTOR**: Clean up while keeping tests green
250
- 4. **Test Pyramid**: 70% unit, 20% integration, 10% E2E
39
+ Target renderers provide the `planner` route. When a native advisor is required, dispatch exactly one compact handoff with `specialistDepth: 1`; include only approved decisions, constraints, dependencies, and the task contract. The specialist must not delegate again. Keep the handoff and returned summary at or below 2,048 estimated tokens. If unavailable, record one fallback and continue in the parent without retrying or selecting a generic child.
251
40
 
252
- ## Common Anti-Patterns to Avoid
41
+ ## Output
253
42
 
254
- | Anti-Pattern | Problem | Solution |
255
- |--------------|---------|----------|
256
- | **Test After** | Missing edge cases | Always write test first |
257
- | **Ice Cream Cone** | Too many E2E tests | Follow pyramid (70/20/10) |
258
- | **Big Tasks** | Hard to track progress | Break into S/M sizes |
259
- | **No Dependencies** | Blocked work | Map dependencies explicitly |
260
- | **Vague Criteria** | Unclear completion | Specific, measurable criteria |
43
+ Return the canonical saved path, traceability, saved checkpoint choice, concise validation evidence, the current human decision, and durable blockers. Do not present raw MCP operations as next steps.
261
44
 
262
- ## Specialist Delegation
45
+ ## Optional Reference
263
46
 
264
- When the host supports subagents, delegate this phase to the `planner` role with a compact handoff containing only the approved design, constraints, dependencies, and required task format. Wait for the specialist and then integrate its result into the current workflow. If specialist delegation is unavailable, state the fallback and continue in the current agent.
47
+ Read [REFERENCE.md](REFERENCE.md) only for the exact task template, sizing heuristics, dependency diagrams, or extended checklist.
@@ -0,0 +1,15 @@
1
+ # Test Generation Reference
2
+
3
+ Read only when selecting cases or matching a framework.
4
+
5
+ ## Behavior Matrix
6
+
7
+ For each contract consider: normal input, empty/zero, minimum/maximum boundary, malformed input, missing dependency, dependency error identity, repeated call/idempotency, ordering/precedence, concurrent transition, cancellation/cleanup, authorization, and sensitive output. Include only cases plausible for the target.
8
+
9
+ ## Test Quality
10
+
11
+ Name the condition and expected behavior. Arrange only necessary state, act once, and assert the observable result plus critical side effects. Keep time, randomness, network, and filesystem boundaries deterministic. Restore global state and close resources. Prefer table-driven cases when inputs share one contract.
12
+
13
+ ## Framework Guidance
14
+
15
+ Detect the existing runner and nearby conventions from project files; do not assume Jest. Place tests beside or under the established test tree. Reuse existing helpers only when they preserve isolation. Run the narrowest supported command that executes the new test. A valid RED run must reach the intended assertion and fail because the behavior is missing.
@@ -1,299 +1,29 @@
1
1
  ---
2
2
  name: sdd-test-gen
3
- description: Generate comprehensive tests following TDD methodology. Creates unit tests, integration tests, and edge case coverage. Works with existing test frameworks in the project. Invoked via /sdd-test-gen [file-path or function-name].
3
+ description: Generate focused tests for observable behavior, boundaries, and real failures.
4
+ disable-model-invocation: true
4
5
  ---
5
6
 
6
- # SDD Test Generation
7
+ # Test Generation
7
8
 
8
- Generate comprehensive tests following Test-Driven Development (TDD) methodology. Write tests that serve as living documentation and ensure code correctness.
9
+ Work inline in the current turn; do not create a serial TDD specialist.
9
10
 
10
- ## TDD Philosophy
11
+ ## Required Workflow
11
12
 
12
- > "Write a failing test before you write the code to make it pass."
13
+ 1. Identify the exact behavior contract, scope, framework, and existing test conventions.
14
+ 2. Read related requirements/design and nearby tests. Avoid duplicate coverage and incidental implementation assertions.
15
+ 3. Write the smallest focused test that proves observable behavior. Cover relevant boundaries, invariants, transitions, precedence, concurrency, and real error propagation.
16
+ 4. Keep tests deterministic, isolated, and full-suite safe. Prefer real domain collaborators; mock only external or nondeterministic boundaries.
17
+ 5. Run the new test before production changes and confirm it fails for the intended reason. A syntax/import failure is not valid RED evidence.
18
+ 6. If implementation is in scope, make the minimal change, rerun the focused test to GREEN, refactor, and rerun.
19
+ 7. Never weaken assertions, snapshot unstable output, add sleeps, or claim coverage/test results that were not observed.
13
20
 
14
- Tests are not an afterthought—they're a design tool that:
15
- 1. **Document behavior** - Tests show how code is intended to be used
16
- 2. **Prevent regressions** - Catch bugs before they ship
17
- 3. **Enable refactoring** - Change with confidence
18
- 4. **Drive design** - Writing tests first leads to better interfaces
21
+ Use focused test commands during the cycle. Broader verification belongs after the requested behavior works.
19
22
 
20
- ## The TDD Cycle
23
+ ## Output
21
24
 
22
- ```
23
- ┌─────────────────────────────────────┐
24
- │ │
25
- │ ┌─────────┐ Write failing test │
26
- │ │ RED │◄──────────────────────┤
27
- │ └────┬────┘ │
28
- │ │ │
29
- │ ▼ Make it pass │
30
- │ ┌─────────┐ │
31
- │ │ GREEN │ │
32
- │ └────┬────┘ │
33
- │ │ │
34
- │ ▼ Improve code │
35
- │ ┌─────────┐ │
36
- │ │REFACTOR │───────────────────────┘
37
- │ └─────────┘
38
- └─────────────────────────────────────┘
39
- ```
25
+ Report tests added or changed, contracts protected, the expected failing-test evidence, focused passing-test evidence, affected artifacts, and unresolved blockers.
40
26
 
41
- ## Workflow
27
+ ## Optional Reference
42
28
 
43
- ### Step 1: Identify Test Scope
44
-
45
- ```
46
- /sdd-test-gen src/services/UserService.ts # Generate tests for file
47
- /sdd-test-gen UserService.createUser # Generate for specific method
48
- /sdd-test-gen src/services/ --integration # Integration tests for module
49
- ```
50
-
51
- ### Step 2: Analyze the Code
52
-
53
- Before generating tests:
54
- 1. Read the source file to understand its behavior
55
- 2. Check existing tests (if any) to avoid duplication
56
- 3. Review related requirements in `.spec/specs/`
57
- 4. Identify dependencies that need mocking
58
-
59
- ### Step 3: Test File Structure
60
-
61
- Generate tests with this structure:
62
-
63
- ```typescript
64
- import { UserService } from '../UserService';
65
- import { UserRepository } from '../../repositories/UserRepository';
66
- import { EmailService } from '../../services/EmailService';
67
-
68
- // Mock dependencies
69
- jest.mock('../../repositories/UserRepository');
70
- jest.mock('../../services/EmailService');
71
-
72
- describe('UserService', () => {
73
- let userService: UserService;
74
- let mockUserRepo: jest.Mocked<UserRepository>;
75
- let mockEmailService: jest.Mocked<EmailService>;
76
-
77
- beforeEach(() => {
78
- jest.clearAllMocks();
79
- mockUserRepo = new UserRepository() as jest.Mocked<UserRepository>;
80
- mockEmailService = new EmailService() as jest.Mocked<EmailService>;
81
- userService = new UserService(mockUserRepo, mockEmailService);
82
- });
83
-
84
- describe('createUser', () => {
85
- it('should create a user with valid input', async () => {
86
- // Arrange
87
- const input = { email: 'test@example.com', name: 'Test User' };
88
- mockUserRepo.save.mockResolvedValue({ id: '1', ...input });
89
-
90
- // Act
91
- const result = await userService.createUser(input);
92
-
93
- // Assert
94
- expect(result.id).toBeDefined();
95
- expect(mockUserRepo.save).toHaveBeenCalledWith(expect.objectContaining(input));
96
- });
97
-
98
- it('should throw error when email already exists', async () => {
99
- // Arrange
100
- mockUserRepo.findByEmail.mockResolvedValue({ id: '1', email: 'test@example.com' });
101
-
102
- // Act & Assert
103
- await expect(userService.createUser({ email: 'test@example.com' }))
104
- .rejects.toThrow('Email already exists');
105
- });
106
- });
107
- });
108
- ```
109
-
110
- ## Specialist Delegation
111
-
112
- When the host supports subagents, delegate test design and generation to the `tdd-guide` role with a compact handoff containing only the behavior contract, affected code, existing test conventions, and edge cases. Wait for the specialist and then integrate its result into the current workflow. If specialist delegation is unavailable, state the fallback and continue in the current agent.
113
-
114
- ### Step 4: Test Categories to Generate
115
-
116
- #### Unit Tests
117
-
118
- Test individual functions in isolation:
119
- - Mock all external dependencies
120
- - Test one behavior per test
121
- - Use descriptive test names
122
-
123
- ```typescript
124
- describe('calculateTotal', () => {
125
- it('should sum all item prices', () => { ... });
126
- it('should apply discount when provided', () => { ... });
127
- it('should handle empty cart', () => { ... });
128
- it('should throw error for negative quantities', () => { ... });
129
- });
130
- ```
131
-
132
- #### Edge Case Tests
133
-
134
- Always test:
135
- - Null/undefined inputs
136
- - Empty arrays/objects
137
- - Boundary values (0, -1, MAX_INT)
138
- - Invalid types
139
- - Concurrent access (if applicable)
140
-
141
- ```typescript
142
- describe('edge cases', () => {
143
- it('should handle null input gracefully', () => { ... });
144
- it('should handle empty array', () => { ... });
145
- it('should handle maximum allowed length', () => { ... });
146
- it('should reject invalid email format', () => { ... });
147
- });
148
- ```
149
-
150
- #### Error Handling Tests
151
-
152
- Verify error paths:
153
- ```typescript
154
- describe('error handling', () => {
155
- it('should throw ValidationError for invalid input', async () => {
156
- await expect(service.create({})).rejects.toThrow(ValidationError);
157
- });
158
-
159
- it('should propagate database errors', async () => {
160
- mockRepo.save.mockRejectedValue(new DatabaseError('Connection failed'));
161
- await expect(service.create(validInput)).rejects.toThrow(DatabaseError);
162
- });
163
- });
164
- ```
165
-
166
- #### Integration Tests (when requested)
167
-
168
- Test component interactions:
169
- ```typescript
170
- describe('UserService integration', () => {
171
- let app: Express;
172
- let db: Database;
173
-
174
- beforeAll(async () => {
175
- db = await createTestDatabase();
176
- app = createApp({ database: db });
177
- });
178
-
179
- afterAll(async () => {
180
- await db.close();
181
- });
182
-
183
- it('should create user and send welcome email', async () => {
184
- const response = await request(app)
185
- .post('/api/users')
186
- .send({ email: 'test@example.com', name: 'Test' });
187
-
188
- expect(response.status).toBe(201);
189
- // Verify email was queued
190
- expect(await getEmailQueue()).toContainEqual(
191
- expect.objectContaining({ to: 'test@example.com' })
192
- );
193
- });
194
- });
195
- ```
196
-
197
- ### Step 5: Test Naming Convention
198
-
199
- Use the pattern: `should [expected behavior] when [condition]`
200
-
201
- ```typescript
202
- // Good
203
- it('should return empty array when no users match criteria', () => {});
204
- it('should throw AuthError when token is expired', () => {});
205
- it('should create user and return ID when input is valid', () => {});
206
-
207
- // Bad
208
- it('test createUser', () => {});
209
- it('works correctly', () => {});
210
- ```
211
-
212
- ## Test Quality Checklist
213
-
214
- For each generated test:
215
- - [ ] Test name describes behavior, not implementation
216
- - [ ] Arrange-Act-Assert pattern used
217
- - [ ] Only one assertion concept per test
218
- - [ ] Tests are independent (no shared state)
219
- - [ ] Mocks are minimal (only external deps)
220
- - [ ] Edge cases covered
221
- - [ ] Error paths tested
222
- - [ ] Async tests properly awaited
223
-
224
- ## Integration with SDD Workflow
225
-
226
- When generating tests for a spec:
227
- 1. Read requirements from `.spec/specs/{feature}/requirements.md`
228
- 2. Map each acceptance criterion to test cases
229
- 3. Check design.md for expected interfaces
230
- 4. Reference tasks.md for implementation details
231
-
232
- ## Test Generation Prompt
233
-
234
- When running `/sdd-test-gen`:
235
-
236
- ```markdown
237
- ## Test Generation Summary
238
-
239
- ### Target: {file/function}
240
-
241
- ### Tests Generated:
242
- - **Unit Tests**: {count}
243
- - **Edge Cases**: {count}
244
- - **Error Handling**: {count}
245
- - **Integration**: {count} (if requested)
246
-
247
- ### Coverage Targets:
248
- - Statements: 80%+
249
- - Branches: 75%+
250
- - Functions: 90%+
251
- - Lines: 80%+
252
-
253
- ### Files Created:
254
- - `src/__tests__/unit/{file}.test.ts`
255
- - `src/__tests__/integration/{file}.integration.test.ts` (if requested)
256
- ```
257
-
258
- ## Framework Detection
259
-
260
- Automatically detect and use project's test framework:
261
- - **Jest** (default for TypeScript/JavaScript)
262
- - **Vitest** (if vite.config.ts present)
263
- - **Mocha/Chai** (if mocha in dependencies)
264
- - **Pytest** (for Python projects)
265
-
266
- ## Example Output
267
-
268
- For input: `/sdd-test-gen src/services/AuthService.ts`
269
-
270
- ```typescript
271
- import { AuthService } from '../AuthService';
272
- import { TokenService } from '../../utils/TokenService';
273
- import { UserRepository } from '../../repositories/UserRepository';
274
-
275
- jest.mock('../../utils/TokenService');
276
- jest.mock('../../repositories/UserRepository');
277
-
278
- describe('AuthService', () => {
279
- // ... setup ...
280
-
281
- describe('login', () => {
282
- it('should return token when credentials are valid', async () => { ... });
283
- it('should throw AuthError when user not found', async () => { ... });
284
- it('should throw AuthError when password is incorrect', async () => { ... });
285
- it('should increment failed login count on failure', async () => { ... });
286
- it('should lock account after 5 failed attempts', async () => { ... });
287
- });
288
-
289
- describe('logout', () => {
290
- it('should invalidate token when called', async () => { ... });
291
- it('should handle already-logged-out user gracefully', async () => { ... });
292
- });
293
-
294
- describe('refreshToken', () => {
295
- it('should return new token when refresh token is valid', async () => { ... });
296
- it('should throw AuthError when refresh token is expired', async () => { ... });
297
- });
298
- });
299
- ```
29
+ Read [REFERENCE.md](REFERENCE.md) only for test matrices, framework examples, naming guidance, or the extended quality checklist.
@@ -0,0 +1,22 @@
1
+ # Simple Task Reference
2
+
3
+ Read only when scope or completion is unclear.
4
+
5
+ ## Appropriate Scope
6
+
7
+ Good candidates are one focused bug, a small behavior addition, a contained refactor, or a configuration correction with known acceptance behavior. Use formal SDD when the work needs competing architecture decisions, new subsystem boundaries, durable phase approvals, or a multi-step migration contract.
8
+
9
+ ## TDD Reminder
10
+
11
+ RED proves the test can detect the missing behavior. GREEN implements the complete requested contract with minimal surface area. REFACTOR removes duplication or accidental complexity while preserving GREEN. Test externally observable results and real failures rather than private calls or source text.
12
+
13
+ ## Completion Checklist
14
+
15
+ - request and non-goals remain unchanged;
16
+ - existing repository conventions were reused;
17
+ - focused RED and GREEN evidence was observed;
18
+ - relevant boundary and error behavior is protected;
19
+ - authorization, injection, secrets, and logging were considered;
20
+ - every affected caller/artifact is updated;
21
+ - unrelated user work is preserved;
22
+ - response lists exact changes, verification, and blockers without dumping file contents.