specweave 0.3.13 → 0.4.1

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 (168) hide show
  1. package/CLAUDE.md +506 -17
  2. package/README.md +100 -58
  3. package/bin/install-all.sh +9 -2
  4. package/bin/install-hooks.sh +57 -0
  5. package/bin/specweave.js +16 -0
  6. package/dist/adapters/adapter-base.d.ts +21 -0
  7. package/dist/adapters/adapter-base.d.ts.map +1 -1
  8. package/dist/adapters/adapter-base.js +28 -0
  9. package/dist/adapters/adapter-base.js.map +1 -1
  10. package/dist/adapters/adapter-interface.d.ts +41 -0
  11. package/dist/adapters/adapter-interface.d.ts.map +1 -1
  12. package/dist/adapters/claude/adapter.d.ts +36 -0
  13. package/dist/adapters/claude/adapter.d.ts.map +1 -1
  14. package/dist/adapters/claude/adapter.js +135 -0
  15. package/dist/adapters/claude/adapter.js.map +1 -1
  16. package/dist/adapters/copilot/adapter.d.ts +25 -0
  17. package/dist/adapters/copilot/adapter.d.ts.map +1 -1
  18. package/dist/adapters/copilot/adapter.js +112 -0
  19. package/dist/adapters/copilot/adapter.js.map +1 -1
  20. package/dist/adapters/cursor/adapter.d.ts +36 -0
  21. package/dist/adapters/cursor/adapter.d.ts.map +1 -1
  22. package/dist/adapters/cursor/adapter.js +140 -0
  23. package/dist/adapters/cursor/adapter.js.map +1 -1
  24. package/dist/adapters/generic/adapter.d.ts +25 -0
  25. package/dist/adapters/generic/adapter.d.ts.map +1 -1
  26. package/dist/adapters/generic/adapter.js +111 -0
  27. package/dist/adapters/generic/adapter.js.map +1 -1
  28. package/dist/cli/commands/init.d.ts.map +1 -1
  29. package/dist/cli/commands/init.js +103 -1
  30. package/dist/cli/commands/init.js.map +1 -1
  31. package/dist/cli/commands/plugin.d.ts +37 -0
  32. package/dist/cli/commands/plugin.d.ts.map +1 -0
  33. package/dist/cli/commands/plugin.js +296 -0
  34. package/dist/cli/commands/plugin.js.map +1 -0
  35. package/dist/core/agent-model-manager.d.ts +52 -0
  36. package/dist/core/agent-model-manager.d.ts.map +1 -0
  37. package/dist/core/agent-model-manager.js +120 -0
  38. package/dist/core/agent-model-manager.js.map +1 -0
  39. package/dist/core/cost-tracker.d.ts +108 -0
  40. package/dist/core/cost-tracker.d.ts.map +1 -0
  41. package/dist/core/cost-tracker.js +281 -0
  42. package/dist/core/cost-tracker.js.map +1 -0
  43. package/dist/core/model-selector.d.ts +57 -0
  44. package/dist/core/model-selector.d.ts.map +1 -0
  45. package/dist/core/model-selector.js +115 -0
  46. package/dist/core/model-selector.js.map +1 -0
  47. package/dist/core/phase-detector.d.ts +62 -0
  48. package/dist/core/phase-detector.d.ts.map +1 -0
  49. package/dist/core/phase-detector.js +229 -0
  50. package/dist/core/phase-detector.js.map +1 -0
  51. package/dist/core/plugin-detector.d.ts +96 -0
  52. package/dist/core/plugin-detector.d.ts.map +1 -0
  53. package/dist/core/plugin-detector.js +349 -0
  54. package/dist/core/plugin-detector.js.map +1 -0
  55. package/dist/core/plugin-loader.d.ts +111 -0
  56. package/dist/core/plugin-loader.d.ts.map +1 -0
  57. package/dist/core/plugin-loader.js +319 -0
  58. package/dist/core/plugin-loader.js.map +1 -0
  59. package/dist/core/plugin-manager.d.ts +144 -0
  60. package/dist/core/plugin-manager.d.ts.map +1 -0
  61. package/dist/core/plugin-manager.js +393 -0
  62. package/dist/core/plugin-manager.js.map +1 -0
  63. package/dist/core/schemas/plugin-manifest.schema.json +253 -0
  64. package/dist/core/types/plugin.d.ts +252 -0
  65. package/dist/core/types/plugin.d.ts.map +1 -0
  66. package/dist/core/types/plugin.js +48 -0
  67. package/dist/core/types/plugin.js.map +1 -0
  68. package/dist/integrations/jira/jira-mapper.d.ts +2 -2
  69. package/dist/integrations/jira/jira-mapper.js +2 -2
  70. package/dist/types/cost-tracking.d.ts +43 -0
  71. package/dist/types/cost-tracking.d.ts.map +1 -0
  72. package/dist/types/cost-tracking.js +8 -0
  73. package/dist/types/cost-tracking.js.map +1 -0
  74. package/dist/types/model-selection.d.ts +53 -0
  75. package/dist/types/model-selection.d.ts.map +1 -0
  76. package/dist/types/model-selection.js +12 -0
  77. package/dist/types/model-selection.js.map +1 -0
  78. package/dist/utils/cost-reporter.d.ts +58 -0
  79. package/dist/utils/cost-reporter.d.ts.map +1 -0
  80. package/dist/utils/cost-reporter.js +224 -0
  81. package/dist/utils/cost-reporter.js.map +1 -0
  82. package/dist/utils/pricing-constants.d.ts +70 -0
  83. package/dist/utils/pricing-constants.d.ts.map +1 -0
  84. package/dist/utils/pricing-constants.js +71 -0
  85. package/dist/utils/pricing-constants.js.map +1 -0
  86. package/package.json +13 -9
  87. package/src/adapters/adapter-base.ts +33 -0
  88. package/src/adapters/adapter-interface.ts +46 -0
  89. package/src/adapters/claude/adapter.ts +164 -0
  90. package/src/adapters/copilot/adapter.ts +138 -0
  91. package/src/adapters/cursor/adapter.ts +170 -0
  92. package/src/adapters/generic/adapter.ts +137 -0
  93. package/src/agents/architect/AGENT.md +3 -0
  94. package/src/agents/code-reviewer.md +156 -0
  95. package/src/agents/data-scientist/AGENT.md +181 -0
  96. package/src/agents/database-optimizer/AGENT.md +147 -0
  97. package/src/agents/devops/AGENT.md +3 -0
  98. package/src/agents/diagrams-architect/AGENT.md +3 -0
  99. package/src/agents/docs-writer/AGENT.md +3 -0
  100. package/src/agents/kubernetes-architect/AGENT.md +142 -0
  101. package/src/agents/ml-engineer/AGENT.md +150 -0
  102. package/src/agents/mlops-engineer/AGENT.md +201 -0
  103. package/src/agents/network-engineer/AGENT.md +149 -0
  104. package/src/agents/observability-engineer/AGENT.md +213 -0
  105. package/src/agents/payment-integration/AGENT.md +35 -0
  106. package/src/agents/performance/AGENT.md +3 -0
  107. package/src/agents/performance-engineer/AGENT.md +153 -0
  108. package/src/agents/pm/AGENT.md +3 -0
  109. package/src/agents/qa-lead/AGENT.md +3 -0
  110. package/src/agents/security/AGENT.md +3 -0
  111. package/src/agents/sre/AGENT.md +3 -0
  112. package/src/agents/tdd-orchestrator/AGENT.md +169 -0
  113. package/src/agents/tech-lead/AGENT.md +3 -0
  114. package/src/commands/specweave.costs.md +261 -0
  115. package/src/commands/specweave.increment.md +48 -4
  116. package/src/commands/specweave.ml-pipeline.md +292 -0
  117. package/src/commands/specweave.monitor-setup.md +501 -0
  118. package/src/commands/specweave.slo-implement.md +1055 -0
  119. package/src/commands/specweave.sync-github.md +1 -1
  120. package/src/commands/specweave.tdd-cycle.md +199 -0
  121. package/src/commands/specweave.tdd-green.md +842 -0
  122. package/src/commands/specweave.tdd-red.md +135 -0
  123. package/src/commands/specweave.tdd-refactor.md +165 -0
  124. package/src/hooks/post-increment-plugin-detect.sh +142 -0
  125. package/src/hooks/post-task-completion.sh +53 -11
  126. package/src/hooks/pre-task-plugin-detect.sh +96 -0
  127. package/src/skills/SKILLS-INDEX.md +18 -10
  128. package/src/skills/billing-automation/SKILL.md +559 -0
  129. package/src/skills/distributed-tracing/SKILL.md +438 -0
  130. package/src/skills/e2e-playwright/README.md +1 -1
  131. package/src/skills/e2e-playwright/package.json +1 -1
  132. package/src/skills/gitops-workflow/SKILL.md +285 -0
  133. package/src/skills/gitops-workflow/references/argocd-setup.md +134 -0
  134. package/src/skills/gitops-workflow/references/sync-policies.md +131 -0
  135. package/src/skills/grafana-dashboards/SKILL.md +369 -0
  136. package/src/skills/helm-chart-scaffolding/SKILL.md +544 -0
  137. package/src/skills/helm-chart-scaffolding/assets/Chart.yaml.template +42 -0
  138. package/src/skills/helm-chart-scaffolding/assets/values.yaml.template +185 -0
  139. package/src/skills/helm-chart-scaffolding/references/chart-structure.md +500 -0
  140. package/src/skills/helm-chart-scaffolding/scripts/validate-chart.sh +244 -0
  141. package/src/skills/k8s-manifest-generator/SKILL.md +511 -0
  142. package/src/skills/k8s-manifest-generator/assets/configmap-template.yaml +296 -0
  143. package/src/skills/k8s-manifest-generator/assets/deployment-template.yaml +203 -0
  144. package/src/skills/k8s-manifest-generator/assets/service-template.yaml +171 -0
  145. package/src/skills/k8s-manifest-generator/references/deployment-spec.md +753 -0
  146. package/src/skills/k8s-manifest-generator/references/service-spec.md +724 -0
  147. package/src/skills/k8s-security-policies/SKILL.md +334 -0
  148. package/src/skills/k8s-security-policies/assets/network-policy-template.yaml +177 -0
  149. package/src/skills/k8s-security-policies/references/rbac-patterns.md +187 -0
  150. package/src/skills/ml-pipeline-workflow/SKILL.md +245 -0
  151. package/src/skills/paypal-integration/SKILL.md +467 -0
  152. package/src/skills/pci-compliance/SKILL.md +466 -0
  153. package/src/skills/prometheus-configuration/SKILL.md +392 -0
  154. package/src/skills/slo-implementation/SKILL.md +329 -0
  155. package/src/skills/stripe-integration/SKILL.md +442 -0
  156. package/src/skills/tdd-workflow/SKILL.md +378 -0
  157. package/src/templates/README.md.template +1 -1
  158. package/src/skills/bmad-method-expert/SKILL.md +0 -626
  159. package/src/skills/bmad-method-expert/scripts/analyze-project.js +0 -318
  160. package/src/skills/bmad-method-expert/scripts/check-setup.js +0 -208
  161. package/src/skills/bmad-method-expert/scripts/generate-template.js +0 -1149
  162. package/src/skills/bmad-method-expert/scripts/validate-documents.js +0 -340
  163. package/src/skills/context-optimizer/SKILL.md +0 -588
  164. package/src/skills/figma-designer/SKILL.md +0 -149
  165. package/src/skills/figma-implementer/SKILL.md +0 -148
  166. package/src/skills/figma-mcp-connector/SKILL.md +0 -136
  167. package/src/skills/figma-to-code/SKILL.md +0 -128
  168. package/src/skills/spec-kit-expert/SKILL.md +0 -1010
@@ -0,0 +1,842 @@
1
+ Implement minimal code to make failing tests pass in TDD green phase:
2
+
3
+ [Extended thinking: This tool uses the test-automator agent to implement the minimal code necessary to make tests pass. It focuses on simplicity, avoiding over-engineering while ensuring all tests become green.]
4
+
5
+ ## Implementation Process
6
+
7
+ Use Task tool with subagent_type="unit-testing::test-automator" to implement minimal passing code.
8
+
9
+ Prompt: "Implement MINIMAL code to make these failing tests pass: $ARGUMENTS. Follow TDD green phase principles:
10
+
11
+ 1. **Pre-Implementation Analysis**
12
+ - Review all failing tests and their error messages
13
+ - Identify the simplest path to make tests pass
14
+ - Map test requirements to minimal implementation needs
15
+ - Avoid premature optimization or over-engineering
16
+ - Focus only on making tests green, not perfect code
17
+
18
+ 2. **Implementation Strategy**
19
+ - **Fake It**: Return hard-coded values when appropriate
20
+ - **Obvious Implementation**: When solution is trivial and clear
21
+ - **Triangulation**: Generalize only when multiple tests require it
22
+ - Start with the simplest test and work incrementally
23
+ - One test at a time - don't try to pass all at once
24
+
25
+ 3. **Code Structure Guidelines**
26
+ - Write the minimal code that could possibly work
27
+ - Avoid adding functionality not required by tests
28
+ - Use simple data structures initially
29
+ - Defer architectural decisions until refactor phase
30
+ - Keep methods/functions small and focused
31
+ - Don't add error handling unless tests require it
32
+
33
+ 4. **Language-Specific Patterns**
34
+ - **JavaScript/TypeScript**: Simple functions, avoid classes initially
35
+ - **Python**: Functions before classes, simple returns
36
+ - **Java**: Minimal class structure, no patterns yet
37
+ - **C#**: Basic implementations, no interfaces yet
38
+ - **Go**: Simple functions, defer goroutines/channels
39
+ - **Ruby**: Procedural before object-oriented when possible
40
+
41
+ 5. **Progressive Implementation**
42
+ - Make first test pass with simplest possible code
43
+ - Run tests after each change to verify progress
44
+ - Add just enough code for next failing test
45
+ - Resist urge to implement beyond test requirements
46
+ - Keep track of technical debt for refactor phase
47
+ - Document assumptions and shortcuts taken
48
+
49
+ 6. **Common Green Phase Techniques**
50
+ - Hard-coded returns for initial tests
51
+ - Simple if/else for limited test cases
52
+ - Basic loops only when iteration tests require
53
+ - Minimal data structures (arrays before complex objects)
54
+ - In-memory storage before database integration
55
+ - Synchronous before asynchronous implementation
56
+
57
+ 7. **Success Criteria**
58
+ ✓ All tests pass (green)
59
+ ✓ No extra functionality beyond test requirements
60
+ ✓ Code is readable even if not optimal
61
+ ✓ No broken existing functionality
62
+ ✓ Implementation time is minimized
63
+ ✓ Clear path to refactoring identified
64
+
65
+ 8. **Anti-Patterns to Avoid**
66
+ - Gold plating or adding unrequested features
67
+ - Implementing design patterns prematurely
68
+ - Complex abstractions without test justification
69
+ - Performance optimizations without metrics
70
+ - Adding tests during green phase
71
+ - Refactoring during implementation
72
+ - Ignoring test failures to move forward
73
+
74
+ 9. **Implementation Metrics**
75
+ - Time to green: Track implementation duration
76
+ - Lines of code: Measure implementation size
77
+ - Cyclomatic complexity: Keep it low initially
78
+ - Test pass rate: Must reach 100%
79
+ - Code coverage: Verify all paths tested
80
+
81
+ 10. **Validation Steps**
82
+ - Run all tests and confirm they pass
83
+ - Verify no regression in existing tests
84
+ - Check that implementation is truly minimal
85
+ - Document any technical debt created
86
+ - Prepare notes for refactoring phase
87
+
88
+ Output should include:
89
+ - Complete implementation code
90
+ - Test execution results showing all green
91
+ - List of shortcuts taken for later refactoring
92
+ - Implementation time metrics
93
+ - Technical debt documentation
94
+ - Readiness assessment for refactor phase"
95
+
96
+ ## Post-Implementation Checks
97
+
98
+ After implementation:
99
+ 1. Run full test suite to confirm all tests pass
100
+ 2. Verify no existing tests were broken
101
+ 3. Document areas needing refactoring
102
+ 4. Check implementation is truly minimal
103
+ 5. Record implementation time for metrics
104
+
105
+ ## Recovery Process
106
+
107
+ If tests still fail:
108
+ - Review test requirements carefully
109
+ - Check for misunderstood assertions
110
+ - Add minimal code to address specific failures
111
+ - Avoid the temptation to rewrite from scratch
112
+ - Consider if tests themselves need adjustment
113
+
114
+ ## Integration Points
115
+
116
+ - Follows from tdd-red.md test creation
117
+ - Prepares for tdd-refactor.md improvements
118
+ - Updates test coverage metrics
119
+ - Triggers CI/CD pipeline verification
120
+ - Documents technical debt for tracking
121
+
122
+ ## Best Practices
123
+
124
+ - Embrace "good enough" for this phase
125
+ - Speed over perfection (perfection comes in refactor)
126
+ - Make it work, then make it right, then make it fast
127
+ - Trust that refactoring phase will improve code
128
+ - Keep changes small and incremental
129
+ - Celebrate reaching green state!
130
+
131
+ ## Complete Implementation Examples
132
+
133
+ ### Example 1: Minimal → Production-Ready (User Service)
134
+
135
+ **Test Requirements:**
136
+ ```typescript
137
+ describe('UserService', () => {
138
+ it('should create a new user', async () => {
139
+ const user = await userService.create({ email: 'test@example.com', name: 'Test' });
140
+ expect(user.id).toBeDefined();
141
+ expect(user.email).toBe('test@example.com');
142
+ });
143
+
144
+ it('should find user by email', async () => {
145
+ await userService.create({ email: 'test@example.com', name: 'Test' });
146
+ const user = await userService.findByEmail('test@example.com');
147
+ expect(user).toBeDefined();
148
+ });
149
+ });
150
+ ```
151
+
152
+ **Stage 1: Fake It (Minimal)**
153
+ ```typescript
154
+ class UserService {
155
+ create(data: { email: string; name: string }) {
156
+ return { id: '123', email: data.email, name: data.name };
157
+ }
158
+
159
+ findByEmail(email: string) {
160
+ return { id: '123', email: email, name: 'Test' };
161
+ }
162
+ }
163
+ ```
164
+ *Tests pass. Implementation is obviously fake but validates test structure.*
165
+
166
+ **Stage 2: Simple Real Implementation**
167
+ ```typescript
168
+ class UserService {
169
+ private users: Map<string, User> = new Map();
170
+ private nextId = 1;
171
+
172
+ create(data: { email: string; name: string }) {
173
+ const user = { id: String(this.nextId++), ...data };
174
+ this.users.set(user.email, user);
175
+ return user;
176
+ }
177
+
178
+ findByEmail(email: string) {
179
+ return this.users.get(email) || null;
180
+ }
181
+ }
182
+ ```
183
+ *In-memory storage. Tests pass. Good enough for green phase.*
184
+
185
+ **Stage 3: Production-Ready (Refactor Phase)**
186
+ ```typescript
187
+ class UserService {
188
+ constructor(private db: Database) {}
189
+
190
+ async create(data: { email: string; name: string }) {
191
+ const existing = await this.db.query('SELECT * FROM users WHERE email = ?', [data.email]);
192
+ if (existing) throw new Error('User exists');
193
+
194
+ const id = await this.db.insert('users', data);
195
+ return { id, ...data };
196
+ }
197
+
198
+ async findByEmail(email: string) {
199
+ return this.db.queryOne('SELECT * FROM users WHERE email = ?', [email]);
200
+ }
201
+ }
202
+ ```
203
+ *Database integration, error handling, validation - saved for refactor phase.*
204
+
205
+ ### Example 2: API-First Implementation (Express)
206
+
207
+ **Test Requirements:**
208
+ ```javascript
209
+ describe('POST /api/tasks', () => {
210
+ it('should create task and return 201', async () => {
211
+ const res = await request(app)
212
+ .post('/api/tasks')
213
+ .send({ title: 'Test Task' });
214
+
215
+ expect(res.status).toBe(201);
216
+ expect(res.body.id).toBeDefined();
217
+ expect(res.body.title).toBe('Test Task');
218
+ });
219
+ });
220
+ ```
221
+
222
+ **Stage 1: Hardcoded Response**
223
+ ```javascript
224
+ app.post('/api/tasks', (req, res) => {
225
+ res.status(201).json({ id: '1', title: req.body.title });
226
+ });
227
+ ```
228
+ *Tests pass immediately. No logic needed yet.*
229
+
230
+ **Stage 2: Simple Logic**
231
+ ```javascript
232
+ let tasks = [];
233
+ let nextId = 1;
234
+
235
+ app.post('/api/tasks', (req, res) => {
236
+ const task = { id: String(nextId++), title: req.body.title };
237
+ tasks.push(task);
238
+ res.status(201).json(task);
239
+ });
240
+ ```
241
+ *Minimal state management. Ready for more tests.*
242
+
243
+ **Stage 3: Layered Architecture (Refactor)**
244
+ ```javascript
245
+ // Controller
246
+ app.post('/api/tasks', async (req, res) => {
247
+ try {
248
+ const task = await taskService.create(req.body);
249
+ res.status(201).json(task);
250
+ } catch (error) {
251
+ res.status(400).json({ error: error.message });
252
+ }
253
+ });
254
+
255
+ // Service layer
256
+ class TaskService {
257
+ constructor(private repository: TaskRepository) {}
258
+
259
+ async create(data: CreateTaskDto): Promise<Task> {
260
+ this.validate(data);
261
+ return this.repository.save(data);
262
+ }
263
+ }
264
+ ```
265
+ *Proper separation of concerns added during refactor phase.*
266
+
267
+ ### Example 3: Database Integration (Django)
268
+
269
+ **Test Requirements:**
270
+ ```python
271
+ def test_product_creation():
272
+ product = Product.objects.create(name="Widget", price=9.99)
273
+ assert product.id is not None
274
+ assert product.name == "Widget"
275
+
276
+ def test_product_price_validation():
277
+ with pytest.raises(ValidationError):
278
+ Product.objects.create(name="Widget", price=-1)
279
+ ```
280
+
281
+ **Stage 1: Model Only**
282
+ ```python
283
+ class Product(models.Model):
284
+ name = models.CharField(max_length=200)
285
+ price = models.DecimalField(max_digits=10, decimal_places=2)
286
+ ```
287
+ *First test passes. Second test fails - validation not implemented.*
288
+
289
+ **Stage 2: Add Validation**
290
+ ```python
291
+ class Product(models.Model):
292
+ name = models.CharField(max_length=200)
293
+ price = models.DecimalField(max_digits=10, decimal_places=2)
294
+
295
+ def clean(self):
296
+ if self.price < 0:
297
+ raise ValidationError("Price cannot be negative")
298
+
299
+ def save(self, *args, **kwargs):
300
+ self.clean()
301
+ super().save(*args, **kwargs)
302
+ ```
303
+ *All tests pass. Minimal validation logic added.*
304
+
305
+ **Stage 3: Rich Domain Model (Refactor)**
306
+ ```python
307
+ class Product(models.Model):
308
+ name = models.CharField(max_length=200)
309
+ price = models.DecimalField(max_digits=10, decimal_places=2)
310
+ category = models.ForeignKey(Category, on_delete=models.CASCADE)
311
+ created_at = models.DateTimeField(auto_now_add=True)
312
+ updated_at = models.DateTimeField(auto_now=True)
313
+
314
+ class Meta:
315
+ indexes = [models.Index(fields=['category', '-created_at'])]
316
+
317
+ def clean(self):
318
+ if self.price < 0:
319
+ raise ValidationError("Price cannot be negative")
320
+ if self.price > 10000:
321
+ raise ValidationError("Price exceeds maximum")
322
+
323
+ def apply_discount(self, percentage: float) -> Decimal:
324
+ return self.price * (1 - percentage / 100)
325
+ ```
326
+ *Additional features, indexes, business logic added when needed.*
327
+
328
+ ### Example 4: React Component Implementation
329
+
330
+ **Test Requirements:**
331
+ ```typescript
332
+ describe('UserProfile', () => {
333
+ it('should display user name', () => {
334
+ render(<UserProfile user={{ name: 'John', email: 'john@test.com' }} />);
335
+ expect(screen.getByText('John')).toBeInTheDocument();
336
+ });
337
+
338
+ it('should display email', () => {
339
+ render(<UserProfile user={{ name: 'John', email: 'john@test.com' }} />);
340
+ expect(screen.getByText('john@test.com')).toBeInTheDocument();
341
+ });
342
+ });
343
+ ```
344
+
345
+ **Stage 1: Minimal JSX**
346
+ ```typescript
347
+ interface UserProfileProps {
348
+ user: { name: string; email: string };
349
+ }
350
+
351
+ const UserProfile: React.FC<UserProfileProps> = ({ user }) => (
352
+ <div>
353
+ <div>{user.name}</div>
354
+ <div>{user.email}</div>
355
+ </div>
356
+ );
357
+ ```
358
+ *Tests pass. No styling, no structure.*
359
+
360
+ **Stage 2: Basic Structure**
361
+ ```typescript
362
+ const UserProfile: React.FC<UserProfileProps> = ({ user }) => (
363
+ <div className="user-profile">
364
+ <h2>{user.name}</h2>
365
+ <p>{user.email}</p>
366
+ </div>
367
+ );
368
+ ```
369
+ *Added semantic HTML, className for styling hook.*
370
+
371
+ **Stage 3: Production Component (Refactor)**
372
+ ```typescript
373
+ const UserProfile: React.FC<UserProfileProps> = ({ user }) => {
374
+ const [isEditing, setIsEditing] = useState(false);
375
+
376
+ return (
377
+ <div className="user-profile" role="article" aria-label="User profile">
378
+ <header>
379
+ <h2>{user.name}</h2>
380
+ <button onClick={() => setIsEditing(true)} aria-label="Edit profile">
381
+ Edit
382
+ </button>
383
+ </header>
384
+ <section>
385
+ <p>{user.email}</p>
386
+ {user.bio && <p>{user.bio}</p>}
387
+ </section>
388
+ </div>
389
+ );
390
+ };
391
+ ```
392
+ *Accessibility, interaction, additional features added incrementally.*
393
+
394
+ ## Decision Frameworks
395
+
396
+ ### Framework 1: Fake vs. Real Implementation
397
+
398
+ **When to Fake It:**
399
+ - First test for a new feature
400
+ - Complex external dependencies (payment gateways, APIs)
401
+ - Implementation approach is still uncertain
402
+ - Need to validate test structure first
403
+ - Time pressure to see all tests green
404
+
405
+ **When to Go Real:**
406
+ - Second or third test reveals pattern
407
+ - Implementation is obvious and simple
408
+ - Faking would be more complex than real code
409
+ - Need to test integration points
410
+ - Tests explicitly require real behavior
411
+
412
+ **Decision Matrix:**
413
+ ```
414
+ Complexity Low | High
415
+ ↓ | ↓
416
+ Simple → REAL | FAKE first, real later
417
+ Complex → REAL | FAKE, evaluate alternatives
418
+ ```
419
+
420
+ ### Framework 2: Complexity Trade-off Analysis
421
+
422
+ **Simplicity Score Calculation:**
423
+ ```
424
+ Score = (Lines of Code) + (Cyclomatic Complexity × 2) + (Dependencies × 3)
425
+
426
+ < 20 → Simple enough, implement directly
427
+ 20-50 → Consider simpler alternative
428
+ > 50 → Defer complexity to refactor phase
429
+ ```
430
+
431
+ **Example Evaluation:**
432
+ ```typescript
433
+ // Option A: Direct implementation (Score: 45)
434
+ function calculateShipping(weight: number, distance: number, express: boolean): number {
435
+ let base = weight * 0.5 + distance * 0.1;
436
+ if (express) base *= 2;
437
+ if (weight > 50) base += 10;
438
+ if (distance > 1000) base += 20;
439
+ return base;
440
+ }
441
+
442
+ // Option B: Simplest for green phase (Score: 15)
443
+ function calculateShipping(weight: number, distance: number, express: boolean): number {
444
+ return express ? 50 : 25; // Fake it until more tests drive real logic
445
+ }
446
+ ```
447
+ *Choose Option B for green phase, evolve to Option A as tests require.*
448
+
449
+ ### Framework 3: Performance Consideration Timing
450
+
451
+ **Green Phase: Focus on Correctness**
452
+ ```
453
+ ❌ Avoid:
454
+ - Caching strategies
455
+ - Database query optimization
456
+ - Algorithmic complexity improvements
457
+ - Premature memory optimization
458
+
459
+ ✓ Accept:
460
+ - O(n²) if it makes code simpler
461
+ - Multiple database queries
462
+ - Synchronous operations
463
+ - Inefficient but clear algorithms
464
+ ```
465
+
466
+ **When Performance Matters in Green Phase:**
467
+ 1. Performance is explicit test requirement
468
+ 2. Implementation would cause timeout in test suite
469
+ 3. Memory leak would crash tests
470
+ 4. Resource exhaustion prevents testing
471
+
472
+ **Performance Testing Integration:**
473
+ ```typescript
474
+ // Add performance test AFTER functional tests pass
475
+ describe('Performance', () => {
476
+ it('should handle 1000 users within 100ms', () => {
477
+ const start = Date.now();
478
+ for (let i = 0; i < 1000; i++) {
479
+ userService.create({ email: `user${i}@test.com`, name: `User ${i}` });
480
+ }
481
+ expect(Date.now() - start).toBeLessThan(100);
482
+ });
483
+ });
484
+ ```
485
+
486
+ ## Framework-Specific Patterns
487
+
488
+ ### React Patterns
489
+
490
+ **Simple Component → Hooks → Context:**
491
+ ```typescript
492
+ // Green Phase: Props only
493
+ const Counter = ({ count, onIncrement }) => (
494
+ <button onClick={onIncrement}>{count}</button>
495
+ );
496
+
497
+ // Refactor: Add hooks
498
+ const Counter = () => {
499
+ const [count, setCount] = useState(0);
500
+ return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
501
+ };
502
+
503
+ // Refactor: Extract to context
504
+ const Counter = () => {
505
+ const { count, increment } = useCounter();
506
+ return <button onClick={increment}>{count}</button>;
507
+ };
508
+ ```
509
+
510
+ ### Django Patterns
511
+
512
+ **Function View → Class View → Generic View:**
513
+ ```python
514
+ # Green Phase: Simple function
515
+ def product_list(request):
516
+ products = Product.objects.all()
517
+ return JsonResponse({'products': list(products.values())})
518
+
519
+ # Refactor: Class-based view
520
+ class ProductListView(View):
521
+ def get(self, request):
522
+ products = Product.objects.all()
523
+ return JsonResponse({'products': list(products.values())})
524
+
525
+ # Refactor: Generic view
526
+ class ProductListView(ListView):
527
+ model = Product
528
+ context_object_name = 'products'
529
+ ```
530
+
531
+ ### Express Patterns
532
+
533
+ **Inline → Middleware → Service Layer:**
534
+ ```javascript
535
+ // Green Phase: Inline logic
536
+ app.post('/api/users', (req, res) => {
537
+ const user = { id: Date.now(), ...req.body };
538
+ users.push(user);
539
+ res.json(user);
540
+ });
541
+
542
+ // Refactor: Extract middleware
543
+ app.post('/api/users', validateUser, (req, res) => {
544
+ const user = userService.create(req.body);
545
+ res.json(user);
546
+ });
547
+
548
+ // Refactor: Full layering
549
+ app.post('/api/users',
550
+ validateUser,
551
+ asyncHandler(userController.create)
552
+ );
553
+ ```
554
+
555
+ ## Refactoring Resistance Patterns
556
+
557
+ ### Pattern 1: Test Anchor Points
558
+
559
+ Keep tests green during refactoring by maintaining interface contracts:
560
+
561
+ ```typescript
562
+ // Original implementation (tests green)
563
+ function calculateTotal(items: Item[]): number {
564
+ return items.reduce((sum, item) => sum + item.price, 0);
565
+ }
566
+
567
+ // Refactoring: Add tax calculation (keep interface)
568
+ function calculateTotal(items: Item[]): number {
569
+ const subtotal = items.reduce((sum, item) => sum + item.price, 0);
570
+ const tax = subtotal * 0.1;
571
+ return subtotal + tax;
572
+ }
573
+
574
+ // Tests still green because return type/behavior unchanged
575
+ ```
576
+
577
+ ### Pattern 2: Parallel Implementation
578
+
579
+ Run old and new implementations side by side:
580
+
581
+ ```python
582
+ def process_order(order):
583
+ # Old implementation (tests depend on this)
584
+ result_old = legacy_process(order)
585
+
586
+ # New implementation (testing in parallel)
587
+ result_new = new_process(order)
588
+
589
+ # Verify they match
590
+ assert result_old == result_new, "Implementation mismatch"
591
+
592
+ return result_old # Keep tests green
593
+ ```
594
+
595
+ ### Pattern 3: Feature Flags for Refactoring
596
+
597
+ ```javascript
598
+ class PaymentService {
599
+ processPayment(amount) {
600
+ if (config.USE_NEW_PAYMENT_PROCESSOR) {
601
+ return this.newPaymentProcessor(amount);
602
+ }
603
+ return this.legacyPaymentProcessor(amount);
604
+ }
605
+ }
606
+ ```
607
+
608
+ ## Performance-First Green Phase Strategies
609
+
610
+ ### Strategy 1: Type-Driven Development
611
+
612
+ Use types to guide minimal implementation:
613
+
614
+ ```typescript
615
+ // Types define contract
616
+ interface UserRepository {
617
+ findById(id: string): Promise<User | null>;
618
+ save(user: User): Promise<void>;
619
+ }
620
+
621
+ // Green phase: In-memory implementation
622
+ class InMemoryUserRepository implements UserRepository {
623
+ private users = new Map<string, User>();
624
+
625
+ async findById(id: string) {
626
+ return this.users.get(id) || null;
627
+ }
628
+
629
+ async save(user: User) {
630
+ this.users.set(user.id, user);
631
+ }
632
+ }
633
+
634
+ // Refactor: Database implementation (same interface)
635
+ class DatabaseUserRepository implements UserRepository {
636
+ constructor(private db: Database) {}
637
+
638
+ async findById(id: string) {
639
+ return this.db.query('SELECT * FROM users WHERE id = ?', [id]);
640
+ }
641
+
642
+ async save(user: User) {
643
+ await this.db.insert('users', user);
644
+ }
645
+ }
646
+ ```
647
+
648
+ ### Strategy 2: Contract Testing Integration
649
+
650
+ ```typescript
651
+ // Define contract
652
+ const userServiceContract = {
653
+ create: {
654
+ input: { email: 'string', name: 'string' },
655
+ output: { id: 'string', email: 'string', name: 'string' }
656
+ }
657
+ };
658
+
659
+ // Green phase: Implementation matches contract
660
+ class UserService {
661
+ create(data: { email: string; name: string }) {
662
+ return { id: '123', ...data }; // Minimal but contract-compliant
663
+ }
664
+ }
665
+
666
+ // Contract test ensures compliance
667
+ describe('UserService Contract', () => {
668
+ it('should match create contract', () => {
669
+ const result = userService.create({ email: 'test@test.com', name: 'Test' });
670
+ expect(typeof result.id).toBe('string');
671
+ expect(typeof result.email).toBe('string');
672
+ expect(typeof result.name).toBe('string');
673
+ });
674
+ });
675
+ ```
676
+
677
+ ### Strategy 3: Continuous Refactoring Workflow
678
+
679
+ **Micro-Refactoring During Green Phase:**
680
+
681
+ ```python
682
+ # Test passes with this
683
+ def calculate_discount(price, customer_type):
684
+ if customer_type == 'premium':
685
+ return price * 0.8
686
+ return price
687
+
688
+ # Immediate micro-refactor (tests still green)
689
+ DISCOUNT_RATES = {
690
+ 'premium': 0.8,
691
+ 'standard': 1.0
692
+ }
693
+
694
+ def calculate_discount(price, customer_type):
695
+ rate = DISCOUNT_RATES.get(customer_type, 1.0)
696
+ return price * rate
697
+ ```
698
+
699
+ **Safe Refactoring Checklist:**
700
+ - ✓ Tests green before refactoring
701
+ - ✓ Change one thing at a time
702
+ - ✓ Run tests after each change
703
+ - ✓ Commit after each successful refactor
704
+ - ✓ No behavior changes, only structure
705
+
706
+ ## Modern Development Practices (2024/2025)
707
+
708
+ ### Type-Driven Development
709
+
710
+ **Python Type Hints:**
711
+ ```python
712
+ from typing import Optional, List
713
+ from dataclasses import dataclass
714
+
715
+ @dataclass
716
+ class User:
717
+ id: str
718
+ email: str
719
+ name: str
720
+
721
+ class UserService:
722
+ def create(self, email: str, name: str) -> User:
723
+ return User(id="123", email=email, name=name)
724
+
725
+ def find_by_email(self, email: str) -> Optional[User]:
726
+ return None # Minimal implementation
727
+ ```
728
+
729
+ **TypeScript Strict Mode:**
730
+ ```typescript
731
+ // Enable strict mode in tsconfig.json
732
+ {
733
+ "compilerOptions": {
734
+ "strict": true,
735
+ "noUncheckedIndexedAccess": true,
736
+ "exactOptionalPropertyTypes": true
737
+ }
738
+ }
739
+
740
+ // Implementation guided by types
741
+ interface CreateUserDto {
742
+ email: string;
743
+ name: string;
744
+ }
745
+
746
+ class UserService {
747
+ create(data: CreateUserDto): User {
748
+ // Type system enforces contract
749
+ return { id: '123', email: data.email, name: data.name };
750
+ }
751
+ }
752
+ ```
753
+
754
+ ### AI-Assisted Green Phase
755
+
756
+ **Using Copilot/AI Tools:**
757
+ 1. Write test first (human-driven)
758
+ 2. Let AI suggest minimal implementation
759
+ 3. Verify suggestion passes tests
760
+ 4. Accept if truly minimal, reject if over-engineered
761
+ 5. Iterate with AI for refactoring phase
762
+
763
+ **AI Prompt Pattern:**
764
+ ```
765
+ Given these failing tests:
766
+ [paste tests]
767
+
768
+ Provide the MINIMAL implementation that makes tests pass.
769
+ Do not add error handling, validation, or features beyond test requirements.
770
+ Focus on simplicity over completeness.
771
+ ```
772
+
773
+ ### Cloud-Native Patterns
774
+
775
+ **Local → Container → Cloud:**
776
+ ```javascript
777
+ // Green Phase: Local implementation
778
+ class CacheService {
779
+ private cache = new Map();
780
+
781
+ get(key) { return this.cache.get(key); }
782
+ set(key, value) { this.cache.set(key, value); }
783
+ }
784
+
785
+ // Refactor: Redis-compatible interface
786
+ class CacheService {
787
+ constructor(private redis) {}
788
+
789
+ async get(key) { return this.redis.get(key); }
790
+ async set(key, value) { return this.redis.set(key, value); }
791
+ }
792
+
793
+ // Production: Distributed cache with fallback
794
+ class CacheService {
795
+ constructor(private redis, private fallback) {}
796
+
797
+ async get(key) {
798
+ try {
799
+ return await this.redis.get(key);
800
+ } catch {
801
+ return this.fallback.get(key);
802
+ }
803
+ }
804
+ }
805
+ ```
806
+
807
+ ### Observability-Driven Development
808
+
809
+ **Add observability hooks during green phase:**
810
+ ```typescript
811
+ class OrderService {
812
+ async createOrder(data: CreateOrderDto): Promise<Order> {
813
+ console.log('[OrderService] Creating order', { data }); // Simple logging
814
+
815
+ const order = { id: '123', ...data };
816
+
817
+ console.log('[OrderService] Order created', { orderId: order.id }); // Success log
818
+
819
+ return order;
820
+ }
821
+ }
822
+
823
+ // Refactor: Structured logging
824
+ class OrderService {
825
+ constructor(private logger: Logger) {}
826
+
827
+ async createOrder(data: CreateOrderDto): Promise<Order> {
828
+ this.logger.info('order.create.start', { data });
829
+
830
+ const order = await this.repository.save(data);
831
+
832
+ this.logger.info('order.create.success', {
833
+ orderId: order.id,
834
+ duration: Date.now() - start
835
+ });
836
+
837
+ return order;
838
+ }
839
+ }
840
+ ```
841
+
842
+ Tests to make pass: $ARGUMENTS