specweave 1.0.261 → 1.0.263

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