continuous-improvement 3.9.2 → 3.12.3

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 (160) hide show
  1. package/.claude-plugin/marketplace.json +3 -3
  2. package/CHANGELOG.md +95 -0
  3. package/LICENSE +21 -21
  4. package/QUICKSTART.md +13 -8
  5. package/README.md +94 -162
  6. package/SKILL.md +1 -1
  7. package/bin/analyze.sh +161 -161
  8. package/bin/backfill.mjs +19 -19
  9. package/bin/check-docs-substrings.mjs +73 -0
  10. package/bin/check-scripts-citation-drift.mjs +210 -0
  11. package/bin/check-skill-count.mjs +110 -0
  12. package/bin/check-test-imports-only.mjs +126 -0
  13. package/bin/check-tool-count.mjs +129 -0
  14. package/bin/companion-preference-status.mjs +231 -0
  15. package/bin/gateguard-clear.mjs +53 -0
  16. package/bin/generate-plugin-manifests.mjs +8 -1
  17. package/bin/harvest-friction.mjs +1 -1
  18. package/bin/hook-stats.mjs +21 -21
  19. package/bin/install.mjs +185 -28
  20. package/bin/mcp-server.mjs +216 -3
  21. package/bin/refresh-third-party.mjs +315 -313
  22. package/commands/audit.md +34 -0
  23. package/commands/companion-preference.md +58 -0
  24. package/commands/continuous-improvement.md +115 -115
  25. package/commands/dashboard.md +56 -56
  26. package/commands/discipline.md +14 -0
  27. package/commands/distill.md +39 -0
  28. package/commands/goal-check.md +53 -0
  29. package/commands/grill-me.md +40 -0
  30. package/commands/grill-with-docs.md +38 -0
  31. package/commands/handoff.md +42 -0
  32. package/commands/harvest.md +1 -1
  33. package/commands/proceed-with-the-recommendation.md +20 -0
  34. package/commands/recall.md +49 -0
  35. package/commands/reconcile.md +47 -0
  36. package/commands/seven-laws.md +16 -16
  37. package/commands/superpowers.md +3 -3
  38. package/commands/verify-install.md +55 -0
  39. package/commands/workspace-surface-audit.md +77 -77
  40. package/hooks/companion-preference.mjs +190 -0
  41. package/hooks/gateguard.mjs +72 -25
  42. package/hooks/goal-drift-stop.mjs +183 -0
  43. package/hooks/observe.sh +15 -1
  44. package/hooks/recall-briefing.mjs +167 -0
  45. package/hooks/route-prompt.mjs +180 -0
  46. package/hooks/route-table.json +35 -0
  47. package/hooks/session.sh +106 -106
  48. package/hooks/three-section-close.mjs +134 -132
  49. package/instinct-packs/go.json +58 -58
  50. package/instinct-packs/meta.json +16 -16
  51. package/instinct-packs/python.json +58 -58
  52. package/instinct-packs/react.json +58 -58
  53. package/lib/gateguard-state.mjs +54 -2
  54. package/lib/goal-drift-gate.mjs +50 -0
  55. package/lib/goal-state.mjs +285 -0
  56. package/lib/plugin-metadata.mjs +134 -15
  57. package/lib/recall-briefing.mjs +57 -0
  58. package/lib/recall-index.mjs +175 -0
  59. package/lib/skill-distill.mjs +222 -0
  60. package/llms.txt +2 -2
  61. package/package.json +12 -7
  62. package/plugins/beginner.json +9 -4
  63. package/plugins/continuous-improvement/.claude-plugin/marketplace.json +2 -2
  64. package/plugins/continuous-improvement/.claude-plugin/plugin.json +2 -2
  65. package/plugins/continuous-improvement/LICENSE +21 -21
  66. package/plugins/continuous-improvement/agents/README.md +3 -3
  67. package/plugins/continuous-improvement/bin/backfill.mjs +19 -19
  68. package/plugins/continuous-improvement/bin/gateguard-clear.mjs +53 -0
  69. package/plugins/continuous-improvement/bin/mcp-server.mjs +216 -3
  70. package/plugins/continuous-improvement/commands/audit.md +34 -0
  71. package/plugins/continuous-improvement/commands/companion-preference.md +58 -0
  72. package/plugins/continuous-improvement/commands/continuous-improvement.md +115 -115
  73. package/plugins/continuous-improvement/commands/dashboard.md +56 -56
  74. package/plugins/continuous-improvement/commands/discipline.md +14 -0
  75. package/plugins/continuous-improvement/commands/distill.md +39 -0
  76. package/plugins/continuous-improvement/commands/goal-check.md +53 -0
  77. package/plugins/continuous-improvement/commands/grill-me.md +40 -0
  78. package/plugins/continuous-improvement/commands/grill-with-docs.md +38 -0
  79. package/plugins/continuous-improvement/commands/handoff.md +42 -0
  80. package/plugins/continuous-improvement/commands/harvest.md +1 -1
  81. package/plugins/continuous-improvement/commands/proceed-with-the-recommendation.md +20 -0
  82. package/plugins/continuous-improvement/commands/recall.md +49 -0
  83. package/plugins/continuous-improvement/commands/reconcile.md +47 -0
  84. package/plugins/continuous-improvement/commands/seven-laws.md +16 -16
  85. package/plugins/continuous-improvement/commands/superpowers.md +3 -3
  86. package/plugins/continuous-improvement/commands/verify-install.md +55 -0
  87. package/plugins/continuous-improvement/commands/workspace-surface-audit.md +77 -77
  88. package/plugins/continuous-improvement/hooks/companion-preference.mjs +190 -0
  89. package/plugins/continuous-improvement/hooks/gateguard.mjs +72 -25
  90. package/plugins/continuous-improvement/hooks/goal-drift-stop.mjs +183 -0
  91. package/plugins/continuous-improvement/hooks/hooks.json +23 -2
  92. package/plugins/continuous-improvement/hooks/observe.sh +15 -1
  93. package/plugins/continuous-improvement/hooks/recall-briefing.mjs +167 -0
  94. package/plugins/continuous-improvement/hooks/route-prompt.mjs +180 -0
  95. package/plugins/continuous-improvement/hooks/route-table.json +35 -0
  96. package/plugins/continuous-improvement/hooks/session.sh +106 -106
  97. package/plugins/continuous-improvement/hooks/three-section-close.mjs +134 -132
  98. package/plugins/continuous-improvement/instinct-packs/go.json +58 -58
  99. package/plugins/continuous-improvement/instinct-packs/meta.json +16 -16
  100. package/plugins/continuous-improvement/instinct-packs/python.json +58 -58
  101. package/plugins/continuous-improvement/instinct-packs/react.json +58 -58
  102. package/plugins/continuous-improvement/lib/gateguard-state.mjs +137 -0
  103. package/plugins/continuous-improvement/lib/goal-drift-gate.mjs +50 -0
  104. package/plugins/continuous-improvement/lib/goal-state.mjs +285 -0
  105. package/plugins/continuous-improvement/lib/plugin-metadata.mjs +134 -15
  106. package/plugins/continuous-improvement/lib/recall-briefing.mjs +57 -0
  107. package/plugins/continuous-improvement/lib/recall-index.mjs +175 -0
  108. package/plugins/continuous-improvement/lib/skill-distill.mjs +222 -0
  109. package/plugins/continuous-improvement/skills/README.md +8 -0
  110. package/plugins/continuous-improvement/skills/audit/SKILL.md +73 -0
  111. package/plugins/continuous-improvement/skills/continuous-improvement/SKILL.md +1 -1
  112. package/plugins/continuous-improvement/skills/deploy-receipt/SKILL.md +13 -17
  113. package/plugins/continuous-improvement/skills/gateguard/SKILL.md +36 -17
  114. package/plugins/continuous-improvement/skills/goal-monitor/SKILL.md +81 -0
  115. package/plugins/continuous-improvement/skills/grill-me/SKILL.md +66 -0
  116. package/plugins/continuous-improvement/skills/grill-with-docs/SKILL.md +252 -0
  117. package/plugins/continuous-improvement/skills/handoff/SKILL.md +59 -0
  118. package/plugins/continuous-improvement/skills/para-memory-files/SKILL.md +1 -1
  119. package/plugins/continuous-improvement/skills/proceed-with-the-recommendation/SKILL.md +82 -6
  120. package/plugins/continuous-improvement/skills/ralph/SKILL.md +1 -0
  121. package/plugins/continuous-improvement/skills/recall/SKILL.md +50 -0
  122. package/plugins/continuous-improvement/skills/reconcile/SKILL.md +80 -0
  123. package/plugins/continuous-improvement/skills/recovery-classification/SKILL.md +1 -0
  124. package/plugins/continuous-improvement/skills/safety-guard/SKILL.md +1 -0
  125. package/plugins/continuous-improvement/skills/skill-distillation/SKILL.md +57 -0
  126. package/plugins/continuous-improvement/skills/state-reconciliation/SKILL.md +1 -0
  127. package/plugins/continuous-improvement/skills/strategic-compact/SKILL.md +1 -0
  128. package/plugins/continuous-improvement/skills/superpowers/SKILL.md +77 -3
  129. package/plugins/continuous-improvement/skills/tdd-workflow/SKILL.md +411 -411
  130. package/plugins/continuous-improvement/skills/token-budget-advisor/SKILL.md +1 -1
  131. package/plugins/continuous-improvement/skills/verification-loop/SKILL.md +28 -20
  132. package/plugins/continuous-improvement/skills/wild-risa-balance/SKILL.md +1 -0
  133. package/plugins/continuous-improvement/skills/workspace-surface-audit/SKILL.md +1 -1
  134. package/plugins/continuous-improvement/skills/worktree-safety/SKILL.md +3 -2
  135. package/plugins/expert.json +28 -3
  136. package/skills/README.md +3 -0
  137. package/skills/audit.md +73 -0
  138. package/skills/deploy-receipt.md +13 -17
  139. package/skills/gateguard.md +36 -17
  140. package/skills/goal-monitor.md +81 -0
  141. package/skills/grill-me.md +66 -0
  142. package/skills/grill-with-docs.md +252 -0
  143. package/skills/handoff.md +59 -0
  144. package/skills/para-memory-files.md +1 -1
  145. package/skills/proceed-with-the-recommendation.md +82 -6
  146. package/skills/ralph.md +1 -0
  147. package/skills/recall.md +50 -0
  148. package/skills/reconcile.md +80 -0
  149. package/skills/recovery-classification.md +1 -0
  150. package/skills/safety-guard.md +1 -0
  151. package/skills/skill-distillation.md +57 -0
  152. package/skills/state-reconciliation.md +1 -0
  153. package/skills/strategic-compact.md +1 -0
  154. package/skills/superpowers.md +77 -3
  155. package/skills/tdd-workflow.md +411 -411
  156. package/skills/token-budget-advisor.md +1 -1
  157. package/skills/verification-loop.md +28 -20
  158. package/skills/wild-risa-balance.md +1 -0
  159. package/skills/workspace-surface-audit.md +1 -1
  160. package/skills/worktree-safety.md +3 -2
@@ -1,411 +1,411 @@
1
- ---
2
- name: tdd-workflow
3
- tier: "1"
4
- description: Enforces Law 3 (One Thing at a Time) and Law 4 (Verify Before Reporting) of the 7 Laws of AI Agent Discipline. Use this skill when writing new features, fixing bugs, or refactoring code. Enforces test-driven development with 80%+ coverage including unit, integration, and E2E tests.
5
- origin: continuous-improvement
6
- ---
7
-
8
- # Test-Driven Development Workflow
9
-
10
- This skill ensures all code development follows TDD principles with comprehensive test coverage.
11
-
12
- ## When to Activate
13
-
14
- - Writing new features or functionality
15
- - Fixing bugs or issues
16
- - Refactoring existing code
17
- - Adding API endpoints
18
- - Creating new components
19
-
20
- ## Core Principles
21
-
22
- ### 1. Tests BEFORE Code
23
- ALWAYS write tests first, then implement code to make tests pass.
24
-
25
- ### 2. Coverage Requirements
26
- - Minimum 80% coverage (unit + integration + E2E)
27
- - All edge cases covered
28
- - Error scenarios tested
29
- - Boundary conditions verified
30
-
31
- ### 3. Test Types
32
-
33
- #### Unit Tests
34
- - Individual functions and utilities
35
- - Component logic
36
- - Pure functions
37
- - Helpers and utilities
38
-
39
- #### Integration Tests
40
- - API endpoints
41
- - Database operations
42
- - Service interactions
43
- - External API calls
44
-
45
- #### E2E Tests (Playwright)
46
- - Critical user flows
47
- - Complete workflows
48
- - Browser automation
49
- - UI interactions
50
-
51
- ## TDD Workflow Steps
52
-
53
- ### Step 1: Write User Journeys
54
- ```
55
- As a [role], I want to [action], so that [benefit]
56
-
57
- Example:
58
- As a user, I want to search for markets semantically,
59
- so that I can find relevant markets even without exact keywords.
60
- ```
61
-
62
- ### Step 2: Generate Test Cases
63
- For each user journey, create comprehensive test cases:
64
-
65
- ```typescript
66
- describe('Semantic Search', () => {
67
- it('returns relevant markets for query', async () => {
68
- // Test implementation
69
- })
70
-
71
- it('handles empty query gracefully', async () => {
72
- // Test edge case
73
- })
74
-
75
- it('falls back to substring search when Redis unavailable', async () => {
76
- // Test fallback behavior
77
- })
78
-
79
- it('sorts results by similarity score', async () => {
80
- // Test sorting logic
81
- })
82
- })
83
- ```
84
-
85
- ### Step 3: Run Tests (They Should Fail)
86
- ```bash
87
- npm test
88
- # Tests should fail - we haven't implemented yet
89
- ```
90
-
91
- ### Step 4: Implement Code
92
- Write minimal code to make tests pass:
93
-
94
- ```typescript
95
- // Implementation guided by tests
96
- export async function searchMarkets(query: string) {
97
- // Implementation here
98
- }
99
- ```
100
-
101
- ### Step 5: Run Tests Again
102
- ```bash
103
- npm test
104
- # Tests should now pass
105
- ```
106
-
107
- ### Step 6: Refactor
108
- Improve code quality while keeping tests green:
109
- - Remove duplication
110
- - Improve naming
111
- - Optimize performance
112
- - Enhance readability
113
-
114
- ### Step 7: Verify Coverage
115
- ```bash
116
- npm run test:coverage
117
- # Verify 80%+ coverage achieved
118
- ```
119
-
120
- ## Testing Patterns
121
-
122
- ### Unit Test Pattern (Jest/Vitest)
123
- ```typescript
124
- import { render, screen, fireEvent } from '@testing-library/react'
125
- import { Button } from './Button'
126
-
127
- describe('Button Component', () => {
128
- it('renders with correct text', () => {
129
- render(<Button>Click me</Button>)
130
- expect(screen.getByText('Click me')).toBeInTheDocument()
131
- })
132
-
133
- it('calls onClick when clicked', () => {
134
- const handleClick = jest.fn()
135
- render(<Button onClick={handleClick}>Click</Button>)
136
-
137
- fireEvent.click(screen.getByRole('button'))
138
-
139
- expect(handleClick).toHaveBeenCalledTimes(1)
140
- })
141
-
142
- it('is disabled when disabled prop is true', () => {
143
- render(<Button disabled>Click</Button>)
144
- expect(screen.getByRole('button')).toBeDisabled()
145
- })
146
- })
147
- ```
148
-
149
- ### API Integration Test Pattern
150
- ```typescript
151
- import { NextRequest } from 'next/server'
152
- import { GET } from './route'
153
-
154
- describe('GET /api/markets', () => {
155
- it('returns markets successfully', async () => {
156
- const request = new NextRequest('http://localhost/api/markets')
157
- const response = await GET(request)
158
- const data = await response.json()
159
-
160
- expect(response.status).toBe(200)
161
- expect(data.success).toBe(true)
162
- expect(Array.isArray(data.data)).toBe(true)
163
- })
164
-
165
- it('validates query parameters', async () => {
166
- const request = new NextRequest('http://localhost/api/markets?limit=invalid')
167
- const response = await GET(request)
168
-
169
- expect(response.status).toBe(400)
170
- })
171
-
172
- it('handles database errors gracefully', async () => {
173
- // Mock database failure
174
- const request = new NextRequest('http://localhost/api/markets')
175
- // Test error handling
176
- })
177
- })
178
- ```
179
-
180
- ### E2E Test Pattern (Playwright)
181
- ```typescript
182
- import { test, expect } from '@playwright/test'
183
-
184
- test('user can search and filter markets', async ({ page }) => {
185
- // Navigate to markets page
186
- await page.goto('/')
187
- await page.click('a[href="/markets"]')
188
-
189
- // Verify page loaded
190
- await expect(page.locator('h1')).toContainText('Markets')
191
-
192
- // Search for markets
193
- await page.fill('input[placeholder="Search markets"]', 'election')
194
-
195
- // Wait for debounce and results
196
- await page.waitForTimeout(600)
197
-
198
- // Verify search results displayed
199
- const results = page.locator('[data-testid="market-card"]')
200
- await expect(results).toHaveCount(5, { timeout: 5000 })
201
-
202
- // Verify results contain search term
203
- const firstResult = results.first()
204
- await expect(firstResult).toContainText('election', { ignoreCase: true })
205
-
206
- // Filter by status
207
- await page.click('button:has-text("Active")')
208
-
209
- // Verify filtered results
210
- await expect(results).toHaveCount(3)
211
- })
212
-
213
- test('user can create a new market', async ({ page }) => {
214
- // Login first
215
- await page.goto('/creator-dashboard')
216
-
217
- // Fill market creation form
218
- await page.fill('input[name="name"]', 'Test Market')
219
- await page.fill('textarea[name="description"]', 'Test description')
220
- await page.fill('input[name="endDate"]', '2025-12-31')
221
-
222
- // Submit form
223
- await page.click('button[type="submit"]')
224
-
225
- // Verify success message
226
- await expect(page.locator('text=Market created successfully')).toBeVisible()
227
-
228
- // Verify redirect to market page
229
- await expect(page).toHaveURL(/\/markets\/test-market/)
230
- })
231
- ```
232
-
233
- ## Test File Organization
234
-
235
- ```
236
- src/
237
- ├── components/
238
- │ ├── Button/
239
- │ │ ├── Button.tsx
240
- │ │ ├── Button.test.tsx # Unit tests
241
- │ │ └── Button.stories.tsx # Storybook
242
- │ └── MarketCard/
243
- │ ├── MarketCard.tsx
244
- │ └── MarketCard.test.tsx
245
- ├── app/
246
- │ └── api/
247
- │ └── markets/
248
- │ ├── route.ts
249
- │ └── route.test.ts # Integration tests
250
- └── e2e/
251
- ├── markets.spec.ts # E2E tests
252
- ├── trading.spec.ts
253
- └── auth.spec.ts
254
- ```
255
-
256
- ## Mocking External Services
257
-
258
- ### Supabase Mock
259
- ```typescript
260
- jest.mock('@/lib/supabase', () => ({
261
- supabase: {
262
- from: jest.fn(() => ({
263
- select: jest.fn(() => ({
264
- eq: jest.fn(() => Promise.resolve({
265
- data: [{ id: 1, name: 'Test Market' }],
266
- error: null
267
- }))
268
- }))
269
- }))
270
- }
271
- }))
272
- ```
273
-
274
- ### Redis Mock
275
- ```typescript
276
- jest.mock('@/lib/redis', () => ({
277
- searchMarketsByVector: jest.fn(() => Promise.resolve([
278
- { slug: 'test-market', similarity_score: 0.95 }
279
- ])),
280
- checkRedisHealth: jest.fn(() => Promise.resolve({ connected: true }))
281
- }))
282
- ```
283
-
284
- ### OpenAI Mock
285
- ```typescript
286
- jest.mock('@/lib/openai', () => ({
287
- generateEmbedding: jest.fn(() => Promise.resolve(
288
- new Array(1536).fill(0.1) // Mock 1536-dim embedding
289
- ))
290
- }))
291
- ```
292
-
293
- ## Test Coverage Verification
294
-
295
- ### Run Coverage Report
296
- ```bash
297
- npm run test:coverage
298
- ```
299
-
300
- ### Coverage Thresholds
301
- ```json
302
- {
303
- "jest": {
304
- "coverageThresholds": {
305
- "global": {
306
- "branches": 80,
307
- "functions": 80,
308
- "lines": 80,
309
- "statements": 80
310
- }
311
- }
312
- }
313
- }
314
- ```
315
-
316
- ## Common Testing Mistakes to Avoid
317
-
318
- ### FAIL: WRONG: Testing Implementation Details
319
- ```typescript
320
- // Don't test internal state
321
- expect(component.state.count).toBe(5)
322
- ```
323
-
324
- ### PASS: CORRECT: Test User-Visible Behavior
325
- ```typescript
326
- // Test what users see
327
- expect(screen.getByText('Count: 5')).toBeInTheDocument()
328
- ```
329
-
330
- ### FAIL: WRONG: Brittle Selectors
331
- ```typescript
332
- // Breaks easily
333
- await page.click('.css-class-xyz')
334
- ```
335
-
336
- ### PASS: CORRECT: Semantic Selectors
337
- ```typescript
338
- // Resilient to changes
339
- await page.click('button:has-text("Submit")')
340
- await page.click('[data-testid="submit-button"]')
341
- ```
342
-
343
- ### FAIL: WRONG: No Test Isolation
344
- ```typescript
345
- // Tests depend on each other
346
- test('creates user', () => { /* ... */ })
347
- test('updates same user', () => { /* depends on previous test */ })
348
- ```
349
-
350
- ### PASS: CORRECT: Independent Tests
351
- ```typescript
352
- // Each test sets up its own data
353
- test('creates user', () => {
354
- const user = createTestUser()
355
- // Test logic
356
- })
357
-
358
- test('updates user', () => {
359
- const user = createTestUser()
360
- // Update logic
361
- })
362
- ```
363
-
364
- ## Continuous Testing
365
-
366
- ### Watch Mode During Development
367
- ```bash
368
- npm test -- --watch
369
- # Tests run automatically on file changes
370
- ```
371
-
372
- ### Pre-Commit Hook
373
- ```bash
374
- # Runs before every commit
375
- npm test && npm run lint
376
- ```
377
-
378
- ### CI/CD Integration
379
- ```yaml
380
- # GitHub Actions
381
- - name: Run Tests
382
- run: npm test -- --coverage
383
- - name: Upload Coverage
384
- uses: codecov/codecov-action@v3
385
- ```
386
-
387
- ## Best Practices
388
-
389
- 1. **Write Tests First** - Always TDD
390
- 2. **One Assert Per Test** - Focus on single behavior
391
- 3. **Descriptive Test Names** - Explain what's tested
392
- 4. **Arrange-Act-Assert** - Clear test structure
393
- 5. **Mock External Dependencies** - Isolate unit tests
394
- 6. **Test Edge Cases** - Null, undefined, empty, large
395
- 7. **Test Error Paths** - Not just happy paths
396
- 8. **Keep Tests Fast** - Unit tests < 50ms each
397
- 9. **Clean Up After Tests** - No side effects
398
- 10. **Review Coverage Reports** - Identify gaps
399
-
400
- ## Success Metrics
401
-
402
- - 80%+ code coverage achieved
403
- - All tests passing (green)
404
- - No skipped or disabled tests
405
- - Fast test execution (< 30s for unit tests)
406
- - E2E tests cover critical user flows
407
- - Tests catch bugs before production
408
-
409
- ---
410
-
411
- **Remember**: Tests are not optional. They are the safety net that enables confident refactoring, rapid development, and production reliability.
1
+ ---
2
+ name: tdd-workflow
3
+ tier: "1"
4
+ description: Enforces Law 3 (One Thing at a Time) and Law 4 (Verify Before Reporting) of the 7 Laws of AI Agent Discipline. Use this skill when writing new features, fixing bugs, or refactoring code. Enforces test-driven development with 80%+ coverage including unit, integration, and E2E tests.
5
+ origin: continuous-improvement
6
+ ---
7
+
8
+ # Test-Driven Development Workflow
9
+
10
+ This skill ensures all code development follows TDD principles with comprehensive test coverage.
11
+
12
+ ## When to Activate
13
+
14
+ - Writing new features or functionality
15
+ - Fixing bugs or issues
16
+ - Refactoring existing code
17
+ - Adding API endpoints
18
+ - Creating new components
19
+
20
+ ## Core Principles
21
+
22
+ ### 1. Tests BEFORE Code
23
+ ALWAYS write tests first, then implement code to make tests pass.
24
+
25
+ ### 2. Coverage Requirements
26
+ - Minimum 80% coverage (unit + integration + E2E)
27
+ - All edge cases covered
28
+ - Error scenarios tested
29
+ - Boundary conditions verified
30
+
31
+ ### 3. Test Types
32
+
33
+ #### Unit Tests
34
+ - Individual functions and utilities
35
+ - Component logic
36
+ - Pure functions
37
+ - Helpers and utilities
38
+
39
+ #### Integration Tests
40
+ - API endpoints
41
+ - Database operations
42
+ - Service interactions
43
+ - External API calls
44
+
45
+ #### E2E Tests (Playwright)
46
+ - Critical user flows
47
+ - Complete workflows
48
+ - Browser automation
49
+ - UI interactions
50
+
51
+ ## TDD Workflow Steps
52
+
53
+ ### Step 1: Write User Journeys
54
+ ```
55
+ As a [role], I want to [action], so that [benefit]
56
+
57
+ Example:
58
+ As a user, I want to search for markets semantically,
59
+ so that I can find relevant markets even without exact keywords.
60
+ ```
61
+
62
+ ### Step 2: Generate Test Cases
63
+ For each user journey, create comprehensive test cases:
64
+
65
+ ```typescript
66
+ describe('Semantic Search', () => {
67
+ it('returns relevant markets for query', async () => {
68
+ // Test implementation
69
+ })
70
+
71
+ it('handles empty query gracefully', async () => {
72
+ // Test edge case
73
+ })
74
+
75
+ it('falls back to substring search when Redis unavailable', async () => {
76
+ // Test fallback behavior
77
+ })
78
+
79
+ it('sorts results by similarity score', async () => {
80
+ // Test sorting logic
81
+ })
82
+ })
83
+ ```
84
+
85
+ ### Step 3: Run Tests (They Should Fail)
86
+ ```bash
87
+ npm test
88
+ # Tests should fail - we haven't implemented yet
89
+ ```
90
+
91
+ ### Step 4: Implement Code
92
+ Write minimal code to make tests pass:
93
+
94
+ ```typescript
95
+ // Implementation guided by tests
96
+ export async function searchMarkets(query: string) {
97
+ // Implementation here
98
+ }
99
+ ```
100
+
101
+ ### Step 5: Run Tests Again
102
+ ```bash
103
+ npm test
104
+ # Tests should now pass
105
+ ```
106
+
107
+ ### Step 6: Refactor
108
+ Improve code quality while keeping tests green:
109
+ - Remove duplication
110
+ - Improve naming
111
+ - Optimize performance
112
+ - Enhance readability
113
+
114
+ ### Step 7: Verify Coverage
115
+ ```bash
116
+ npm run test:coverage
117
+ # Verify 80%+ coverage achieved
118
+ ```
119
+
120
+ ## Testing Patterns
121
+
122
+ ### Unit Test Pattern (Jest/Vitest)
123
+ ```typescript
124
+ import { render, screen, fireEvent } from '@testing-library/react'
125
+ import { Button } from './Button'
126
+
127
+ describe('Button Component', () => {
128
+ it('renders with correct text', () => {
129
+ render(<Button>Click me</Button>)
130
+ expect(screen.getByText('Click me')).toBeInTheDocument()
131
+ })
132
+
133
+ it('calls onClick when clicked', () => {
134
+ const handleClick = jest.fn()
135
+ render(<Button onClick={handleClick}>Click</Button>)
136
+
137
+ fireEvent.click(screen.getByRole('button'))
138
+
139
+ expect(handleClick).toHaveBeenCalledTimes(1)
140
+ })
141
+
142
+ it('is disabled when disabled prop is true', () => {
143
+ render(<Button disabled>Click</Button>)
144
+ expect(screen.getByRole('button')).toBeDisabled()
145
+ })
146
+ })
147
+ ```
148
+
149
+ ### API Integration Test Pattern
150
+ ```typescript
151
+ import { NextRequest } from 'next/server'
152
+ import { GET } from './route'
153
+
154
+ describe('GET /api/markets', () => {
155
+ it('returns markets successfully', async () => {
156
+ const request = new NextRequest('http://localhost/api/markets')
157
+ const response = await GET(request)
158
+ const data = await response.json()
159
+
160
+ expect(response.status).toBe(200)
161
+ expect(data.success).toBe(true)
162
+ expect(Array.isArray(data.data)).toBe(true)
163
+ })
164
+
165
+ it('validates query parameters', async () => {
166
+ const request = new NextRequest('http://localhost/api/markets?limit=invalid')
167
+ const response = await GET(request)
168
+
169
+ expect(response.status).toBe(400)
170
+ })
171
+
172
+ it('handles database errors gracefully', async () => {
173
+ // Mock database failure
174
+ const request = new NextRequest('http://localhost/api/markets')
175
+ // Test error handling
176
+ })
177
+ })
178
+ ```
179
+
180
+ ### E2E Test Pattern (Playwright)
181
+ ```typescript
182
+ import { test, expect } from '@playwright/test'
183
+
184
+ test('user can search and filter markets', async ({ page }) => {
185
+ // Navigate to markets page
186
+ await page.goto('/')
187
+ await page.click('a[href="/markets"]')
188
+
189
+ // Verify page loaded
190
+ await expect(page.locator('h1')).toContainText('Markets')
191
+
192
+ // Search for markets
193
+ await page.fill('input[placeholder="Search markets"]', 'election')
194
+
195
+ // Wait for debounce and results
196
+ await page.waitForTimeout(600)
197
+
198
+ // Verify search results displayed
199
+ const results = page.locator('[data-testid="market-card"]')
200
+ await expect(results).toHaveCount(5, { timeout: 5000 })
201
+
202
+ // Verify results contain search term
203
+ const firstResult = results.first()
204
+ await expect(firstResult).toContainText('election', { ignoreCase: true })
205
+
206
+ // Filter by status
207
+ await page.click('button:has-text("Active")')
208
+
209
+ // Verify filtered results
210
+ await expect(results).toHaveCount(3)
211
+ })
212
+
213
+ test('user can create a new market', async ({ page }) => {
214
+ // Login first
215
+ await page.goto('/creator-dashboard')
216
+
217
+ // Fill market creation form
218
+ await page.fill('input[name="name"]', 'Test Market')
219
+ await page.fill('textarea[name="description"]', 'Test description')
220
+ await page.fill('input[name="endDate"]', '2025-12-31')
221
+
222
+ // Submit form
223
+ await page.click('button[type="submit"]')
224
+
225
+ // Verify success message
226
+ await expect(page.locator('text=Market created successfully')).toBeVisible()
227
+
228
+ // Verify redirect to market page
229
+ await expect(page).toHaveURL(/\/markets\/test-market/)
230
+ })
231
+ ```
232
+
233
+ ## Test File Organization
234
+
235
+ ```
236
+ src/
237
+ ├── components/
238
+ │ ├── Button/
239
+ │ │ ├── Button.tsx
240
+ │ │ ├── Button.test.tsx # Unit tests
241
+ │ │ └── Button.stories.tsx # Storybook
242
+ │ └── MarketCard/
243
+ │ ├── MarketCard.tsx
244
+ │ └── MarketCard.test.tsx
245
+ ├── app/
246
+ │ └── api/
247
+ │ └── markets/
248
+ │ ├── route.ts
249
+ │ └── route.test.ts # Integration tests
250
+ └── e2e/
251
+ ├── markets.spec.ts # E2E tests
252
+ ├── trading.spec.ts
253
+ └── auth.spec.ts
254
+ ```
255
+
256
+ ## Mocking External Services
257
+
258
+ ### Supabase Mock
259
+ ```typescript
260
+ jest.mock('@/lib/supabase', () => ({
261
+ supabase: {
262
+ from: jest.fn(() => ({
263
+ select: jest.fn(() => ({
264
+ eq: jest.fn(() => Promise.resolve({
265
+ data: [{ id: 1, name: 'Test Market' }],
266
+ error: null
267
+ }))
268
+ }))
269
+ }))
270
+ }
271
+ }))
272
+ ```
273
+
274
+ ### Redis Mock
275
+ ```typescript
276
+ jest.mock('@/lib/redis', () => ({
277
+ searchMarketsByVector: jest.fn(() => Promise.resolve([
278
+ { slug: 'test-market', similarity_score: 0.95 }
279
+ ])),
280
+ checkRedisHealth: jest.fn(() => Promise.resolve({ connected: true }))
281
+ }))
282
+ ```
283
+
284
+ ### OpenAI Mock
285
+ ```typescript
286
+ jest.mock('@/lib/openai', () => ({
287
+ generateEmbedding: jest.fn(() => Promise.resolve(
288
+ new Array(1536).fill(0.1) // Mock 1536-dim embedding
289
+ ))
290
+ }))
291
+ ```
292
+
293
+ ## Test Coverage Verification
294
+
295
+ ### Run Coverage Report
296
+ ```bash
297
+ npm run test:coverage
298
+ ```
299
+
300
+ ### Coverage Thresholds
301
+ ```json
302
+ {
303
+ "jest": {
304
+ "coverageThresholds": {
305
+ "global": {
306
+ "branches": 80,
307
+ "functions": 80,
308
+ "lines": 80,
309
+ "statements": 80
310
+ }
311
+ }
312
+ }
313
+ }
314
+ ```
315
+
316
+ ## Common Testing Mistakes to Avoid
317
+
318
+ ### FAIL: WRONG: Testing Implementation Details
319
+ ```typescript
320
+ // Don't test internal state
321
+ expect(component.state.count).toBe(5)
322
+ ```
323
+
324
+ ### PASS: CORRECT: Test User-Visible Behavior
325
+ ```typescript
326
+ // Test what users see
327
+ expect(screen.getByText('Count: 5')).toBeInTheDocument()
328
+ ```
329
+
330
+ ### FAIL: WRONG: Brittle Selectors
331
+ ```typescript
332
+ // Breaks easily
333
+ await page.click('.css-class-xyz')
334
+ ```
335
+
336
+ ### PASS: CORRECT: Semantic Selectors
337
+ ```typescript
338
+ // Resilient to changes
339
+ await page.click('button:has-text("Submit")')
340
+ await page.click('[data-testid="submit-button"]')
341
+ ```
342
+
343
+ ### FAIL: WRONG: No Test Isolation
344
+ ```typescript
345
+ // Tests depend on each other
346
+ test('creates user', () => { /* ... */ })
347
+ test('updates same user', () => { /* depends on previous test */ })
348
+ ```
349
+
350
+ ### PASS: CORRECT: Independent Tests
351
+ ```typescript
352
+ // Each test sets up its own data
353
+ test('creates user', () => {
354
+ const user = createTestUser()
355
+ // Test logic
356
+ })
357
+
358
+ test('updates user', () => {
359
+ const user = createTestUser()
360
+ // Update logic
361
+ })
362
+ ```
363
+
364
+ ## Continuous Testing
365
+
366
+ ### Watch Mode During Development
367
+ ```bash
368
+ npm test -- --watch
369
+ # Tests run automatically on file changes
370
+ ```
371
+
372
+ ### Pre-Commit Hook
373
+ ```bash
374
+ # Runs before every commit
375
+ npm test && npm run lint
376
+ ```
377
+
378
+ ### CI/CD Integration
379
+ ```yaml
380
+ # GitHub Actions
381
+ - name: Run Tests
382
+ run: npm test -- --coverage
383
+ - name: Upload Coverage
384
+ uses: codecov/codecov-action@v3
385
+ ```
386
+
387
+ ## Best Practices
388
+
389
+ 1. **Write Tests First** - Always TDD
390
+ 2. **One Assert Per Test** - Focus on single behavior
391
+ 3. **Descriptive Test Names** - Explain what's tested
392
+ 4. **Arrange-Act-Assert** - Clear test structure
393
+ 5. **Mock External Dependencies** - Isolate unit tests
394
+ 6. **Test Edge Cases** - Null, undefined, empty, large
395
+ 7. **Test Error Paths** - Not just happy paths
396
+ 8. **Keep Tests Fast** - Unit tests < 50ms each
397
+ 9. **Clean Up After Tests** - No side effects
398
+ 10. **Review Coverage Reports** - Identify gaps
399
+
400
+ ## Success Metrics
401
+
402
+ - 80%+ code coverage achieved
403
+ - All tests passing (green)
404
+ - No skipped or disabled tests
405
+ - Fast test execution (< 30s for unit tests)
406
+ - E2E tests cover critical user flows
407
+ - Tests catch bugs before production
408
+
409
+ ---
410
+
411
+ **Remember**: Tests are not optional. They are the safety net that enables confident refactoring, rapid development, and production reliability.