@juho0719/cckit 0.1.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 (111) hide show
  1. package/assets/agents/architect.md +211 -0
  2. package/assets/agents/build-error-resolver.md +114 -0
  3. package/assets/agents/ccwin-code-reviewer.md +224 -0
  4. package/assets/agents/database-reviewer.md +91 -0
  5. package/assets/agents/doc-updater.md +107 -0
  6. package/assets/agents/e2e-runner.md +107 -0
  7. package/assets/agents/planner.md +212 -0
  8. package/assets/agents/python-reviewer.md +98 -0
  9. package/assets/agents/refactor-cleaner.md +85 -0
  10. package/assets/agents/security-reviewer.md +108 -0
  11. package/assets/agents/superpower-code-reviewer.md +48 -0
  12. package/assets/agents/tdd-guide.md +80 -0
  13. package/assets/commands/build-fix.md +62 -0
  14. package/assets/commands/checkpoint.md +74 -0
  15. package/assets/commands/code-review.md +40 -0
  16. package/assets/commands/e2e.md +362 -0
  17. package/assets/commands/eval.md +120 -0
  18. package/assets/commands/orchestrate.md +172 -0
  19. package/assets/commands/plan.md +113 -0
  20. package/assets/commands/python-review.md +297 -0
  21. package/assets/commands/refactor-clean.md +80 -0
  22. package/assets/commands/sessions.md +305 -0
  23. package/assets/commands/tdd.md +326 -0
  24. package/assets/commands/test-coverage.md +69 -0
  25. package/assets/commands/update-codemaps.md +72 -0
  26. package/assets/commands/update-docs.md +84 -0
  27. package/assets/commands/verify.md +59 -0
  28. package/assets/hooks/post-edit-format.js +49 -0
  29. package/assets/hooks/post-edit-typecheck.js +96 -0
  30. package/assets/mcps/mcp-servers.json +92 -0
  31. package/assets/rules/common/agents.md +49 -0
  32. package/assets/rules/common/coding-style.md +48 -0
  33. package/assets/rules/common/git-workflow.md +45 -0
  34. package/assets/rules/common/hooks.md +30 -0
  35. package/assets/rules/common/patterns.md +31 -0
  36. package/assets/rules/common/performance.md +55 -0
  37. package/assets/rules/common/security.md +29 -0
  38. package/assets/rules/common/testing.md +29 -0
  39. package/assets/rules/python/coding-style.md +42 -0
  40. package/assets/rules/python/hooks.md +19 -0
  41. package/assets/rules/python/patterns.md +39 -0
  42. package/assets/rules/python/security.md +30 -0
  43. package/assets/rules/python/testing.md +38 -0
  44. package/assets/rules/typescript/coding-style.md +18 -0
  45. package/assets/rules/typescript/hooks.md +19 -0
  46. package/assets/rules/typescript/patterns.md +39 -0
  47. package/assets/rules/typescript/security.md +30 -0
  48. package/assets/rules/typescript/testing.md +38 -0
  49. package/assets/skills/api-design/SKILL.md +522 -0
  50. package/assets/skills/backend-patterns/SKILL.md +597 -0
  51. package/assets/skills/brainstorming/SKILL.md +96 -0
  52. package/assets/skills/coding-standards/SKILL.md +529 -0
  53. package/assets/skills/database-migrations/SKILL.md +334 -0
  54. package/assets/skills/deployment-patterns/SKILL.md +426 -0
  55. package/assets/skills/dispatching-parallel-agents/SKILL.md +180 -0
  56. package/assets/skills/docker-patterns/SKILL.md +363 -0
  57. package/assets/skills/e2e-testing/SKILL.md +325 -0
  58. package/assets/skills/eval-harness/SKILL.md +235 -0
  59. package/assets/skills/executing-plans/SKILL.md +84 -0
  60. package/assets/skills/finishing-a-development-branch/SKILL.md +200 -0
  61. package/assets/skills/frontend-patterns/SKILL.md +641 -0
  62. package/assets/skills/iterative-retrieval/SKILL.md +210 -0
  63. package/assets/skills/postgres-patterns/SKILL.md +145 -0
  64. package/assets/skills/python-patterns/SKILL.md +749 -0
  65. package/assets/skills/python-testing/SKILL.md +815 -0
  66. package/assets/skills/receiving-code-review/SKILL.md +213 -0
  67. package/assets/skills/requesting-code-review/SKILL.md +105 -0
  68. package/assets/skills/requesting-code-review/code-reviewer-template.md +146 -0
  69. package/assets/skills/subagent-driven-development/SKILL.md +242 -0
  70. package/assets/skills/subagent-driven-development/code-quality-reviewer-prompt.md +20 -0
  71. package/assets/skills/subagent-driven-development/implementer-prompt.md +78 -0
  72. package/assets/skills/subagent-driven-development/spec-reviewer-prompt.md +61 -0
  73. package/assets/skills/systematic-debugging/CREATION-LOG.md +114 -0
  74. package/assets/skills/systematic-debugging/SKILL.md +296 -0
  75. package/assets/skills/systematic-debugging/condition-based-waiting-example.ts +158 -0
  76. package/assets/skills/systematic-debugging/condition-based-waiting.md +115 -0
  77. package/assets/skills/systematic-debugging/defense-in-depth.md +122 -0
  78. package/assets/skills/systematic-debugging/root-cause-tracing.md +169 -0
  79. package/assets/skills/systematic-debugging/scripts/find-polluter.sh +63 -0
  80. package/assets/skills/systematic-debugging/test-academic.md +14 -0
  81. package/assets/skills/systematic-debugging/test-pressure-1.md +58 -0
  82. package/assets/skills/systematic-debugging/test-pressure-2.md +68 -0
  83. package/assets/skills/systematic-debugging/test-pressure-3.md +69 -0
  84. package/assets/skills/tdd-workflow/SKILL.md +409 -0
  85. package/assets/skills/test-driven-development/SKILL.md +371 -0
  86. package/assets/skills/test-driven-development/testing-anti-patterns.md +299 -0
  87. package/assets/skills/using-git-worktrees/SKILL.md +218 -0
  88. package/assets/skills/verification-before-completion/SKILL.md +139 -0
  89. package/assets/skills/verification-loop/SKILL.md +125 -0
  90. package/assets/skills/writing-plans/SKILL.md +116 -0
  91. package/dist/agents-AEKT67A6.js +9 -0
  92. package/dist/chunk-3GUKEMND.js +28 -0
  93. package/dist/chunk-3UNN3IBE.js +54 -0
  94. package/dist/chunk-3Y26YU4R.js +27 -0
  95. package/dist/chunk-5XOKKPAA.js +21 -0
  96. package/dist/chunk-6B46AIFM.js +136 -0
  97. package/dist/chunk-EYY2IZ7N.js +27 -0
  98. package/dist/chunk-K25UZZVG.js +17 -0
  99. package/dist/chunk-KEENFBLL.js +24 -0
  100. package/dist/chunk-RMUKD7CW.js +44 -0
  101. package/dist/chunk-W63UKEIT.js +50 -0
  102. package/dist/cli-VZRGF733.js +238 -0
  103. package/dist/commands-P5LILVZ5.js +9 -0
  104. package/dist/hooks-IIG2XK4I.js +9 -0
  105. package/dist/index.js +131 -0
  106. package/dist/mcps-67Q7TBGW.js +6 -0
  107. package/dist/paths-FT6KBIRD.js +10 -0
  108. package/dist/registry-EGXWYWWK.js +17 -0
  109. package/dist/rules-2CPBVNNJ.js +7 -0
  110. package/dist/skills-ULMW3UCM.js +8 -0
  111. package/package.json +36 -0
@@ -0,0 +1,597 @@
1
+ ---
2
+ name: backend-patterns
3
+ description: Backend architecture patterns, API design, database optimization, and server-side best practices for Node.js, Express, and Next.js API routes.
4
+ ---
5
+
6
+ # Backend Development Patterns
7
+
8
+ Backend architecture patterns and best practices for scalable server-side applications.
9
+
10
+ ## When to Activate
11
+
12
+ - Designing REST or GraphQL API endpoints
13
+ - Implementing repository, service, or controller layers
14
+ - Optimizing database queries (N+1, indexing, connection pooling)
15
+ - Adding caching (Redis, in-memory, HTTP cache headers)
16
+ - Setting up background jobs or async processing
17
+ - Structuring error handling and validation for APIs
18
+ - Building middleware (auth, logging, rate limiting)
19
+
20
+ ## API Design Patterns
21
+
22
+ ### RESTful API Structure
23
+
24
+ ```typescript
25
+ // ✅ Resource-based URLs
26
+ GET /api/markets # List resources
27
+ GET /api/markets/:id # Get single resource
28
+ POST /api/markets # Create resource
29
+ PUT /api/markets/:id # Replace resource
30
+ PATCH /api/markets/:id # Update resource
31
+ DELETE /api/markets/:id # Delete resource
32
+
33
+ // ✅ Query parameters for filtering, sorting, pagination
34
+ GET /api/markets?status=active&sort=volume&limit=20&offset=0
35
+ ```
36
+
37
+ ### Repository Pattern
38
+
39
+ ```typescript
40
+ // Abstract data access logic
41
+ interface MarketRepository {
42
+ findAll(filters?: MarketFilters): Promise<Market[]>
43
+ findById(id: string): Promise<Market | null>
44
+ create(data: CreateMarketDto): Promise<Market>
45
+ update(id: string, data: UpdateMarketDto): Promise<Market>
46
+ delete(id: string): Promise<void>
47
+ }
48
+
49
+ class SupabaseMarketRepository implements MarketRepository {
50
+ async findAll(filters?: MarketFilters): Promise<Market[]> {
51
+ let query = supabase.from('markets').select('*')
52
+
53
+ if (filters?.status) {
54
+ query = query.eq('status', filters.status)
55
+ }
56
+
57
+ if (filters?.limit) {
58
+ query = query.limit(filters.limit)
59
+ }
60
+
61
+ const { data, error } = await query
62
+
63
+ if (error) throw new Error(error.message)
64
+ return data
65
+ }
66
+
67
+ // Other methods...
68
+ }
69
+ ```
70
+
71
+ ### Service Layer Pattern
72
+
73
+ ```typescript
74
+ // Business logic separated from data access
75
+ class MarketService {
76
+ constructor(private marketRepo: MarketRepository) {}
77
+
78
+ async searchMarkets(query: string, limit: number = 10): Promise<Market[]> {
79
+ // Business logic
80
+ const embedding = await generateEmbedding(query)
81
+ const results = await this.vectorSearch(embedding, limit)
82
+
83
+ // Fetch full data
84
+ const markets = await this.marketRepo.findByIds(results.map(r => r.id))
85
+
86
+ // Sort by similarity
87
+ return markets.sort((a, b) => {
88
+ const scoreA = results.find(r => r.id === a.id)?.score || 0
89
+ const scoreB = results.find(r => r.id === b.id)?.score || 0
90
+ return scoreA - scoreB
91
+ })
92
+ }
93
+
94
+ private async vectorSearch(embedding: number[], limit: number) {
95
+ // Vector search implementation
96
+ }
97
+ }
98
+ ```
99
+
100
+ ### Middleware Pattern
101
+
102
+ ```typescript
103
+ // Request/response processing pipeline
104
+ export function withAuth(handler: NextApiHandler): NextApiHandler {
105
+ return async (req, res) => {
106
+ const token = req.headers.authorization?.replace('Bearer ', '')
107
+
108
+ if (!token) {
109
+ return res.status(401).json({ error: 'Unauthorized' })
110
+ }
111
+
112
+ try {
113
+ const user = await verifyToken(token)
114
+ req.user = user
115
+ return handler(req, res)
116
+ } catch (error) {
117
+ return res.status(401).json({ error: 'Invalid token' })
118
+ }
119
+ }
120
+ }
121
+
122
+ // Usage
123
+ export default withAuth(async (req, res) => {
124
+ // Handler has access to req.user
125
+ })
126
+ ```
127
+
128
+ ## Database Patterns
129
+
130
+ ### Query Optimization
131
+
132
+ ```typescript
133
+ // ✅ GOOD: Select only needed columns
134
+ const { data } = await supabase
135
+ .from('markets')
136
+ .select('id, name, status, volume')
137
+ .eq('status', 'active')
138
+ .order('volume', { ascending: false })
139
+ .limit(10)
140
+
141
+ // ❌ BAD: Select everything
142
+ const { data } = await supabase
143
+ .from('markets')
144
+ .select('*')
145
+ ```
146
+
147
+ ### N+1 Query Prevention
148
+
149
+ ```typescript
150
+ // ❌ BAD: N+1 query problem
151
+ const markets = await getMarkets()
152
+ for (const market of markets) {
153
+ market.creator = await getUser(market.creator_id) // N queries
154
+ }
155
+
156
+ // ✅ GOOD: Batch fetch
157
+ const markets = await getMarkets()
158
+ const creatorIds = markets.map(m => m.creator_id)
159
+ const creators = await getUsers(creatorIds) // 1 query
160
+ const creatorMap = new Map(creators.map(c => [c.id, c]))
161
+
162
+ markets.forEach(market => {
163
+ market.creator = creatorMap.get(market.creator_id)
164
+ })
165
+ ```
166
+
167
+ ### Transaction Pattern
168
+
169
+ ```typescript
170
+ async function createMarketWithPosition(
171
+ marketData: CreateMarketDto,
172
+ positionData: CreatePositionDto
173
+ ) {
174
+ // Use Supabase transaction
175
+ const { data, error } = await supabase.rpc('create_market_with_position', {
176
+ market_data: marketData,
177
+ position_data: positionData
178
+ })
179
+
180
+ if (error) throw new Error('Transaction failed')
181
+ return data
182
+ }
183
+
184
+ // SQL function in Supabase
185
+ CREATE OR REPLACE FUNCTION create_market_with_position(
186
+ market_data jsonb,
187
+ position_data jsonb
188
+ )
189
+ RETURNS jsonb
190
+ LANGUAGE plpgsql
191
+ AS $$
192
+ BEGIN
193
+ -- Start transaction automatically
194
+ INSERT INTO markets VALUES (market_data);
195
+ INSERT INTO positions VALUES (position_data);
196
+ RETURN jsonb_build_object('success', true);
197
+ EXCEPTION
198
+ WHEN OTHERS THEN
199
+ -- Rollback happens automatically
200
+ RETURN jsonb_build_object('success', false, 'error', SQLERRM);
201
+ END;
202
+ $$;
203
+ ```
204
+
205
+ ## Caching Strategies
206
+
207
+ ### Redis Caching Layer
208
+
209
+ ```typescript
210
+ class CachedMarketRepository implements MarketRepository {
211
+ constructor(
212
+ private baseRepo: MarketRepository,
213
+ private redis: RedisClient
214
+ ) {}
215
+
216
+ async findById(id: string): Promise<Market | null> {
217
+ // Check cache first
218
+ const cached = await this.redis.get(`market:${id}`)
219
+
220
+ if (cached) {
221
+ return JSON.parse(cached)
222
+ }
223
+
224
+ // Cache miss - fetch from database
225
+ const market = await this.baseRepo.findById(id)
226
+
227
+ if (market) {
228
+ // Cache for 5 minutes
229
+ await this.redis.setex(`market:${id}`, 300, JSON.stringify(market))
230
+ }
231
+
232
+ return market
233
+ }
234
+
235
+ async invalidateCache(id: string): Promise<void> {
236
+ await this.redis.del(`market:${id}`)
237
+ }
238
+ }
239
+ ```
240
+
241
+ ### Cache-Aside Pattern
242
+
243
+ ```typescript
244
+ async function getMarketWithCache(id: string): Promise<Market> {
245
+ const cacheKey = `market:${id}`
246
+
247
+ // Try cache
248
+ const cached = await redis.get(cacheKey)
249
+ if (cached) return JSON.parse(cached)
250
+
251
+ // Cache miss - fetch from DB
252
+ const market = await db.markets.findUnique({ where: { id } })
253
+
254
+ if (!market) throw new Error('Market not found')
255
+
256
+ // Update cache
257
+ await redis.setex(cacheKey, 300, JSON.stringify(market))
258
+
259
+ return market
260
+ }
261
+ ```
262
+
263
+ ## Error Handling Patterns
264
+
265
+ ### Centralized Error Handler
266
+
267
+ ```typescript
268
+ class ApiError extends Error {
269
+ constructor(
270
+ public statusCode: number,
271
+ public message: string,
272
+ public isOperational = true
273
+ ) {
274
+ super(message)
275
+ Object.setPrototypeOf(this, ApiError.prototype)
276
+ }
277
+ }
278
+
279
+ export function errorHandler(error: unknown, req: Request): Response {
280
+ if (error instanceof ApiError) {
281
+ return NextResponse.json({
282
+ success: false,
283
+ error: error.message
284
+ }, { status: error.statusCode })
285
+ }
286
+
287
+ if (error instanceof z.ZodError) {
288
+ return NextResponse.json({
289
+ success: false,
290
+ error: 'Validation failed',
291
+ details: error.errors
292
+ }, { status: 400 })
293
+ }
294
+
295
+ // Log unexpected errors
296
+ console.error('Unexpected error:', error)
297
+
298
+ return NextResponse.json({
299
+ success: false,
300
+ error: 'Internal server error'
301
+ }, { status: 500 })
302
+ }
303
+
304
+ // Usage
305
+ export async function GET(request: Request) {
306
+ try {
307
+ const data = await fetchData()
308
+ return NextResponse.json({ success: true, data })
309
+ } catch (error) {
310
+ return errorHandler(error, request)
311
+ }
312
+ }
313
+ ```
314
+
315
+ ### Retry with Exponential Backoff
316
+
317
+ ```typescript
318
+ async function fetchWithRetry<T>(
319
+ fn: () => Promise<T>,
320
+ maxRetries = 3
321
+ ): Promise<T> {
322
+ let lastError: Error
323
+
324
+ for (let i = 0; i < maxRetries; i++) {
325
+ try {
326
+ return await fn()
327
+ } catch (error) {
328
+ lastError = error as Error
329
+
330
+ if (i < maxRetries - 1) {
331
+ // Exponential backoff: 1s, 2s, 4s
332
+ const delay = Math.pow(2, i) * 1000
333
+ await new Promise(resolve => setTimeout(resolve, delay))
334
+ }
335
+ }
336
+ }
337
+
338
+ throw lastError!
339
+ }
340
+
341
+ // Usage
342
+ const data = await fetchWithRetry(() => fetchFromAPI())
343
+ ```
344
+
345
+ ## Authentication & Authorization
346
+
347
+ ### JWT Token Validation
348
+
349
+ ```typescript
350
+ import jwt from 'jsonwebtoken'
351
+
352
+ interface JWTPayload {
353
+ userId: string
354
+ email: string
355
+ role: 'admin' | 'user'
356
+ }
357
+
358
+ export function verifyToken(token: string): JWTPayload {
359
+ try {
360
+ const payload = jwt.verify(token, process.env.JWT_SECRET!) as JWTPayload
361
+ return payload
362
+ } catch (error) {
363
+ throw new ApiError(401, 'Invalid token')
364
+ }
365
+ }
366
+
367
+ export async function requireAuth(request: Request) {
368
+ const token = request.headers.get('authorization')?.replace('Bearer ', '')
369
+
370
+ if (!token) {
371
+ throw new ApiError(401, 'Missing authorization token')
372
+ }
373
+
374
+ return verifyToken(token)
375
+ }
376
+
377
+ // Usage in API route
378
+ export async function GET(request: Request) {
379
+ const user = await requireAuth(request)
380
+
381
+ const data = await getDataForUser(user.userId)
382
+
383
+ return NextResponse.json({ success: true, data })
384
+ }
385
+ ```
386
+
387
+ ### Role-Based Access Control
388
+
389
+ ```typescript
390
+ type Permission = 'read' | 'write' | 'delete' | 'admin'
391
+
392
+ interface User {
393
+ id: string
394
+ role: 'admin' | 'moderator' | 'user'
395
+ }
396
+
397
+ const rolePermissions: Record<User['role'], Permission[]> = {
398
+ admin: ['read', 'write', 'delete', 'admin'],
399
+ moderator: ['read', 'write', 'delete'],
400
+ user: ['read', 'write']
401
+ }
402
+
403
+ export function hasPermission(user: User, permission: Permission): boolean {
404
+ return rolePermissions[user.role].includes(permission)
405
+ }
406
+
407
+ export function requirePermission(permission: Permission) {
408
+ return (handler: (request: Request, user: User) => Promise<Response>) => {
409
+ return async (request: Request) => {
410
+ const user = await requireAuth(request)
411
+
412
+ if (!hasPermission(user, permission)) {
413
+ throw new ApiError(403, 'Insufficient permissions')
414
+ }
415
+
416
+ return handler(request, user)
417
+ }
418
+ }
419
+ }
420
+
421
+ // Usage - HOF wraps the handler
422
+ export const DELETE = requirePermission('delete')(
423
+ async (request: Request, user: User) => {
424
+ // Handler receives authenticated user with verified permission
425
+ return new Response('Deleted', { status: 200 })
426
+ }
427
+ )
428
+ ```
429
+
430
+ ## Rate Limiting
431
+
432
+ ### Simple In-Memory Rate Limiter
433
+
434
+ ```typescript
435
+ class RateLimiter {
436
+ private requests = new Map<string, number[]>()
437
+
438
+ async checkLimit(
439
+ identifier: string,
440
+ maxRequests: number,
441
+ windowMs: number
442
+ ): Promise<boolean> {
443
+ const now = Date.now()
444
+ const requests = this.requests.get(identifier) || []
445
+
446
+ // Remove old requests outside window
447
+ const recentRequests = requests.filter(time => now - time < windowMs)
448
+
449
+ if (recentRequests.length >= maxRequests) {
450
+ return false // Rate limit exceeded
451
+ }
452
+
453
+ // Add current request
454
+ recentRequests.push(now)
455
+ this.requests.set(identifier, recentRequests)
456
+
457
+ return true
458
+ }
459
+ }
460
+
461
+ const limiter = new RateLimiter()
462
+
463
+ export async function GET(request: Request) {
464
+ const ip = request.headers.get('x-forwarded-for') || 'unknown'
465
+
466
+ const allowed = await limiter.checkLimit(ip, 100, 60000) // 100 req/min
467
+
468
+ if (!allowed) {
469
+ return NextResponse.json({
470
+ error: 'Rate limit exceeded'
471
+ }, { status: 429 })
472
+ }
473
+
474
+ // Continue with request
475
+ }
476
+ ```
477
+
478
+ ## Background Jobs & Queues
479
+
480
+ ### Simple Queue Pattern
481
+
482
+ ```typescript
483
+ class JobQueue<T> {
484
+ private queue: T[] = []
485
+ private processing = false
486
+
487
+ async add(job: T): Promise<void> {
488
+ this.queue.push(job)
489
+
490
+ if (!this.processing) {
491
+ this.process()
492
+ }
493
+ }
494
+
495
+ private async process(): Promise<void> {
496
+ this.processing = true
497
+
498
+ while (this.queue.length > 0) {
499
+ const job = this.queue.shift()!
500
+
501
+ try {
502
+ await this.execute(job)
503
+ } catch (error) {
504
+ console.error('Job failed:', error)
505
+ }
506
+ }
507
+
508
+ this.processing = false
509
+ }
510
+
511
+ private async execute(job: T): Promise<void> {
512
+ // Job execution logic
513
+ }
514
+ }
515
+
516
+ // Usage for indexing markets
517
+ interface IndexJob {
518
+ marketId: string
519
+ }
520
+
521
+ const indexQueue = new JobQueue<IndexJob>()
522
+
523
+ export async function POST(request: Request) {
524
+ const { marketId } = await request.json()
525
+
526
+ // Add to queue instead of blocking
527
+ await indexQueue.add({ marketId })
528
+
529
+ return NextResponse.json({ success: true, message: 'Job queued' })
530
+ }
531
+ ```
532
+
533
+ ## Logging & Monitoring
534
+
535
+ ### Structured Logging
536
+
537
+ ```typescript
538
+ interface LogContext {
539
+ userId?: string
540
+ requestId?: string
541
+ method?: string
542
+ path?: string
543
+ [key: string]: unknown
544
+ }
545
+
546
+ class Logger {
547
+ log(level: 'info' | 'warn' | 'error', message: string, context?: LogContext) {
548
+ const entry = {
549
+ timestamp: new Date().toISOString(),
550
+ level,
551
+ message,
552
+ ...context
553
+ }
554
+
555
+ console.log(JSON.stringify(entry))
556
+ }
557
+
558
+ info(message: string, context?: LogContext) {
559
+ this.log('info', message, context)
560
+ }
561
+
562
+ warn(message: string, context?: LogContext) {
563
+ this.log('warn', message, context)
564
+ }
565
+
566
+ error(message: string, error: Error, context?: LogContext) {
567
+ this.log('error', message, {
568
+ ...context,
569
+ error: error.message,
570
+ stack: error.stack
571
+ })
572
+ }
573
+ }
574
+
575
+ const logger = new Logger()
576
+
577
+ // Usage
578
+ export async function GET(request: Request) {
579
+ const requestId = crypto.randomUUID()
580
+
581
+ logger.info('Fetching markets', {
582
+ requestId,
583
+ method: 'GET',
584
+ path: '/api/markets'
585
+ })
586
+
587
+ try {
588
+ const markets = await fetchMarkets()
589
+ return NextResponse.json({ success: true, data: markets })
590
+ } catch (error) {
591
+ logger.error('Failed to fetch markets', error as Error, { requestId })
592
+ return NextResponse.json({ error: 'Internal error' }, { status: 500 })
593
+ }
594
+ }
595
+ ```
596
+
597
+ **Remember**: Backend patterns enable scalable, maintainable server-side applications. Choose patterns that fit your complexity level.
@@ -0,0 +1,96 @@
1
+ ---
2
+ name: brainstorming
3
+ description: "You MUST use this before any creative work - creating features, building components, adding functionality, or modifying behavior. Explores user intent, requirements and design before implementation."
4
+ ---
5
+
6
+ # Brainstorming Ideas Into Designs
7
+
8
+ ## Overview
9
+
10
+ Help turn ideas into fully formed designs and specs through natural collaborative dialogue.
11
+
12
+ Start by understanding the current project context, then ask questions one at a time to refine the idea. Once you understand what you're building, present the design and get user approval.
13
+
14
+ <HARD-GATE>
15
+ Do NOT invoke any implementation skill, write any code, scaffold any project, or take any implementation action until you have presented a design and the user has approved it. This applies to EVERY project regardless of perceived simplicity.
16
+ </HARD-GATE>
17
+
18
+ ## Anti-Pattern: "This Is Too Simple To Need A Design"
19
+
20
+ Every project goes through this process. A todo list, a single-function utility, a config change — all of them. "Simple" projects are where unexamined assumptions cause the most wasted work. The design can be short (a few sentences for truly simple projects), but you MUST present it and get approval.
21
+
22
+ ## Checklist
23
+
24
+ You MUST create a task for each of these items and complete them in order:
25
+
26
+ 1. **Explore project context** — check files, docs, recent commits
27
+ 2. **Ask clarifying questions** — one at a time, understand purpose/constraints/success criteria
28
+ 3. **Propose 2-3 approaches** — with trade-offs and your recommendation
29
+ 4. **Present design** — in sections scaled to their complexity, get user approval after each section
30
+ 5. **Write design doc** — save to `docs/plans/YYYY-MM-DD-<topic>-design.md` and commit
31
+ 6. **Transition to implementation** — invoke writing-plans skill to create implementation plan
32
+
33
+ ## Process Flow
34
+
35
+ ```dot
36
+ digraph brainstorming {
37
+ "Explore project context" [shape=box];
38
+ "Ask clarifying questions" [shape=box];
39
+ "Propose 2-3 approaches" [shape=box];
40
+ "Present design sections" [shape=box];
41
+ "User approves design?" [shape=diamond];
42
+ "Write design doc" [shape=box];
43
+ "Invoke writing-plans skill" [shape=doublecircle];
44
+
45
+ "Explore project context" -> "Ask clarifying questions";
46
+ "Ask clarifying questions" -> "Propose 2-3 approaches";
47
+ "Propose 2-3 approaches" -> "Present design sections";
48
+ "Present design sections" -> "User approves design?";
49
+ "User approves design?" -> "Present design sections" [label="no, revise"];
50
+ "User approves design?" -> "Write design doc" [label="yes"];
51
+ "Write design doc" -> "Invoke writing-plans skill";
52
+ }
53
+ ```
54
+
55
+ **The terminal state is invoking writing-plans.** Do NOT invoke frontend-design, mcp-builder, or any other implementation skill. The ONLY skill you invoke after brainstorming is writing-plans.
56
+
57
+ ## The Process
58
+
59
+ **Understanding the idea:**
60
+ - Check out the current project state first (files, docs, recent commits)
61
+ - Ask questions one at a time to refine the idea
62
+ - Prefer multiple choice questions when possible, but open-ended is fine too
63
+ - Only one question per message - if a topic needs more exploration, break it into multiple questions
64
+ - Focus on understanding: purpose, constraints, success criteria
65
+
66
+ **Exploring approaches:**
67
+ - Propose 2-3 different approaches with trade-offs
68
+ - Present options conversationally with your recommendation and reasoning
69
+ - Lead with your recommended option and explain why
70
+
71
+ **Presenting the design:**
72
+ - Once you believe you understand what you're building, present the design
73
+ - Scale each section to its complexity: a few sentences if straightforward, up to 200-300 words if nuanced
74
+ - Ask after each section whether it looks right so far
75
+ - Cover: architecture, components, data flow, error handling, testing
76
+ - Be ready to go back and clarify if something doesn't make sense
77
+
78
+ ## After the Design
79
+
80
+ **Documentation:**
81
+ - Write the validated design to `docs/plans/YYYY-MM-DD-<topic>-design.md`
82
+ - Use elements-of-style:writing-clearly-and-concisely skill if available
83
+ - Commit the design document to git
84
+
85
+ **Implementation:**
86
+ - Invoke the writing-plans skill to create a detailed implementation plan
87
+ - Do NOT invoke any other skill. writing-plans is the next step.
88
+
89
+ ## Key Principles
90
+
91
+ - **One question at a time** - Don't overwhelm with multiple questions
92
+ - **Multiple choice preferred** - Easier to answer than open-ended when possible
93
+ - **YAGNI ruthlessly** - Remove unnecessary features from all designs
94
+ - **Explore alternatives** - Always propose 2-3 approaches before settling
95
+ - **Incremental validation** - Present design, get approval before moving on
96
+ - **Be flexible** - Go back and clarify when something doesn't make sense