@davidbalzan/groundwork 0.3.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 (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +323 -0
  3. package/docs/DECISIONS.md +170 -0
  4. package/package.json +38 -0
  5. package/payload/doc-templates/COMMANDS.md +419 -0
  6. package/payload/doc-templates/DECISIONS.md +168 -0
  7. package/payload/doc-templates/FACTS.md +43 -0
  8. package/payload/doc-templates/GROUNDWORK_METHODOLOGY.md +1300 -0
  9. package/payload/doc-templates/STACK_MAP.md +90 -0
  10. package/payload/doc-templates/WORKSTREAMS.md +79 -0
  11. package/payload/doc-templates/_INDEX.md +54 -0
  12. package/payload/doc-templates/phases/README.md +36 -0
  13. package/payload/doc-templates/phases/templates/README.md +63 -0
  14. package/payload/doc-templates/phases/templates/TASK_TEMPLATE.md +302 -0
  15. package/payload/doc-templates/phases/templates/task_template_prompt.md +229 -0
  16. package/payload/doc-templates/templates/ARCHITECTURE_GUIDE_TEMPLATE.md +250 -0
  17. package/payload/doc-templates/templates/DESIGN_SYSTEM_TEMPLATE.md +336 -0
  18. package/payload/doc-templates/templates/DONE_TEMPLATE.md +21 -0
  19. package/payload/doc-templates/templates/PHASES_README_TEMPLATE.md +144 -0
  20. package/payload/doc-templates/templates/PHASE_README_TEMPLATE.md +142 -0
  21. package/payload/doc-templates/templates/PRD_TEMPLATE.md +348 -0
  22. package/payload/doc-templates/templates/PRODUCTION_ROADMAP_TEMPLATE.md +168 -0
  23. package/payload/doc-templates/templates/QUEUE_TEMPLATE.md +17 -0
  24. package/payload/doc-templates/templates/TECH_STACK_TEMPLATE.md +199 -0
  25. package/payload/scripts/check-task.mjs +98 -0
  26. package/payload/scripts/check-versions.mjs +113 -0
  27. package/payload/scripts/phase-status.mjs +69 -0
  28. package/payload/scripts/set-fact.mjs +86 -0
  29. package/payload/skills/add-data-layer/SKILL.md +129 -0
  30. package/payload/skills/check-task/SKILL.md +35 -0
  31. package/payload/skills/check-versions/SKILL.md +47 -0
  32. package/payload/skills/create-prd/SKILL.md +90 -0
  33. package/payload/skills/domain-model/SKILL.md +90 -0
  34. package/payload/skills/kickstart/SKILL.md +157 -0
  35. package/payload/skills/log-decision/SKILL.md +65 -0
  36. package/payload/skills/next/SKILL.md +65 -0
  37. package/payload/skills/plan-phase/SKILL.md +108 -0
  38. package/payload/skills/remember/SKILL.md +77 -0
  39. package/payload/skills/start-session/SKILL.md +52 -0
  40. package/payload/skills/update-workstreams/SKILL.md +60 -0
  41. package/src/cli.mjs +115 -0
  42. package/src/commands/add.mjs +39 -0
  43. package/src/commands/artifacts.mjs +24 -0
  44. package/src/commands/doctor.mjs +292 -0
  45. package/src/commands/init.mjs +147 -0
  46. package/src/commands/knowledge.mjs +148 -0
  47. package/src/commands/list.mjs +61 -0
  48. package/src/commands/status.mjs +96 -0
  49. package/src/commands/update.mjs +128 -0
  50. package/src/lib/adr-tripwire.mjs +171 -0
  51. package/src/lib/artifacts.mjs +124 -0
  52. package/src/lib/config.mjs +43 -0
  53. package/src/lib/fs.mjs +46 -0
  54. package/src/lib/log.mjs +22 -0
  55. package/src/lib/paths.mjs +36 -0
  56. package/src/lib/progress.mjs +26 -0
  57. package/src/lib/skills.mjs +42 -0
@@ -0,0 +1,1300 @@
1
+ ---
2
+ title: "Groundwork Methodology"
3
+ tags: [groundwork/core]
4
+ aliases: ["Methodology"]
5
+ ---
6
+
7
+ # Groundwork Methodology
8
+
9
+ A documentation-driven approach to building software projects with AI assistance. This document serves as a prompt/template to bootstrap new projects with a structured, phase-based development methodology.
10
+
11
+ ---
12
+
13
+ ## 🎯 Philosophy
14
+
15
+ **Groundwork** is about maintaining momentum while building complex software with AI assistance. The key principles:
16
+
17
+ 1. **Documentation as Code** - Plans are living documents with checkboxes that track progress
18
+ 2. **Phase-Based Development** - Break overwhelming projects into digestible phases
19
+ 3. **Progressive Disclosure** - Each phase folder contains increasing detail levels
20
+ 4. **AI-Friendly Structure** - Clear hierarchy helps AI assistants maintain context
21
+ 5. **Iterative Planning** - Plans evolve as you learn more about the domain
22
+
23
+ ---
24
+
25
+ ## πŸ“ Monorepo Project Structure
26
+
27
+ This approach uses a **monorepo structure** with separate packages for client and server, unified by shared documentation and tooling at the root level.
28
+
29
+ ```
30
+ project-root/
31
+ β”œβ”€β”€ README.md # Quick start, setup, overview
32
+ β”œβ”€β”€ package.json # Root package.json (workspace config)
33
+ β”œβ”€β”€ pnpm-workspace.yaml # Workspace definition (or npm/yarn equivalent)
34
+ β”‚
35
+ β”œβ”€β”€ apps/
36
+ β”‚ β”œβ”€β”€ web/ # Frontend application
37
+ β”‚ β”‚ β”œβ”€β”€ package.json # Client dependencies
38
+ β”‚ β”‚ β”œβ”€β”€ src/
39
+ β”‚ β”‚ β”‚ β”œβ”€β”€ components/ # UI components
40
+ β”‚ β”‚ β”‚ β”œβ”€β”€ features/ # Feature modules (domain logic + UI)
41
+ β”‚ β”‚ β”‚ β”œβ”€β”€ pages/ # Route pages
42
+ β”‚ β”‚ β”‚ β”œβ”€β”€ api/ # API client / WebSocket handlers
43
+ β”‚ β”‚ β”‚ β”œβ”€β”€ store.ts # State management
44
+ β”‚ β”‚ β”‚ └── main.tsx # Entry point
45
+ β”‚ β”‚ β”œβ”€β”€ public/ # Static assets
46
+ β”‚ β”‚ └── index.html
47
+ β”‚ β”‚
48
+ β”‚ └── api/ # Backend application
49
+ β”‚ β”œβ”€β”€ package.json # Server dependencies
50
+ β”‚ β”œβ”€β”€ src/
51
+ β”‚ β”‚ β”œβ”€β”€ routes/ # REST route handlers
52
+ β”‚ β”‚ β”œβ”€β”€ features/ # Feature modules (business logic)
53
+ β”‚ β”‚ β”œβ”€β”€ middleware/ # Request middleware
54
+ β”‚ β”‚ β”œβ”€β”€ services/ # Shared services
55
+ β”‚ β”‚ β”œβ”€β”€ auth/ # Authentication logic
56
+ β”‚ β”‚ β”œβ”€β”€ config/ # Configuration management
57
+ β”‚ β”‚ β”œβ”€β”€ utils/ # Utility functions
58
+ β”‚ β”‚ └── index.ts # Entry point
59
+ β”‚ β”œβ”€β”€ migrations/ # (optional) DB migrations β€” added by /add-data-layer
60
+ β”‚ └── drizzle.config.ts # (optional) ORM config β€” added by /add-data-layer
61
+ β”‚
62
+ β”œβ”€β”€ packages/
63
+ β”‚ └── shared/ # Shared utilities and types
64
+ β”‚ β”œβ”€β”€ package.json
65
+ β”‚ └── src/
66
+ β”‚ └── index.ts
67
+ β”‚
68
+ └── docs/ # Project documentation
69
+ β”œβ”€β”€ README.md # Documentation index & navigation
70
+ β”œβ”€β”€ PRODUCTION_ROADMAP.md # High-level roadmap with all phases
71
+ β”œβ”€β”€ TECH_STACK.md # Technology choices & versions
72
+ β”œβ”€β”€ ARCHITECTURE_GUIDE.md # System architecture & decisions
73
+ β”‚
74
+ └── phases/ # Detailed implementation plans
75
+ β”œβ”€β”€ README.md # Phase overview & progress tracking
76
+ β”œβ”€β”€ phase1/
77
+ β”‚ β”œβ”€β”€ README.md # Phase overview, deliverables, timeline
78
+ β”‚ └── PHASE1_TASKS.md # Detailed tasks with checkboxes
79
+ β”œβ”€β”€ phase2/
80
+ β”‚ β”œβ”€β”€ README.md
81
+ β”‚ └── PHASE2_TASKS.md
82
+ └── ... (phases 3-N)
83
+ ```
84
+
85
+ ### Why Monorepo?
86
+
87
+ - **Shared tooling** - Single ESLint, TypeScript, and Prettier config
88
+ - **Atomic commits** - Frontend and backend changes in one commit
89
+ - **Simplified dependencies** - Shared types, protocols, and utilities
90
+ - **Unified documentation** - One `docs/` folder covers the whole system
91
+ - **Easier refactoring** - Cross-package changes are easier to coordinate
92
+
93
+ ### Package Boundaries
94
+
95
+ | Package | Responsibility | Dependencies |
96
+ | ------------------ | -------------------------------------- | --------------------------- |
97
+ | `apps/web/` | UI, user interactions, state | API client, shared types |
98
+ | `apps/api/` | Business logic, data persistence, auth | Database, external services |
99
+ | `packages/shared/` | Shared utilities, types, constants | None |
100
+ | `docs/` | Documentation only | N/A |
101
+
102
+ ### Feature-Based Organization
103
+
104
+ Both `apps/web/` and `apps/api/` use a **feature-based** organization pattern inside their `features/` directories. Each feature is a self-contained module:
105
+
106
+ ```
107
+ features/
108
+ β”œβ”€β”€ wallet/ # Wallet feature
109
+ β”‚ β”œβ”€β”€ WalletDisplay.tsx # (client) UI component
110
+ β”‚ β”œβ”€β”€ walletSlice.ts # (client) State management
111
+ β”‚ β”œβ”€β”€ walletRoutes.ts # (server) API routes
112
+ β”‚ β”œβ”€β”€ walletService.ts # (server) Business logic
113
+ β”‚ └── walletTypes.ts # Shared types
114
+ β”‚
115
+ β”œβ”€β”€ leaderboard/ # Leaderboard feature
116
+ β”‚ β”œβ”€β”€ Leaderboard.tsx
117
+ β”‚ β”œβ”€β”€ leaderboardRoutes.ts
118
+ β”‚ └── ...
119
+ β”‚
120
+ └── [feature-name]/ # Pattern repeats
121
+ ```
122
+
123
+ **Benefits**:
124
+
125
+ - **Colocation** - Related code lives together
126
+ - **Discoverability** - Easy to find all code for a feature
127
+ - **Modularity** - Features can be developed/tested in isolation
128
+ - **Scalability** - Add new features without touching existing code
129
+
130
+ ---
131
+
132
+ ## πŸ“‹ Core Document Types
133
+
134
+ ### 1. Production Roadmap ([[PRODUCTION_ROADMAP]])
135
+
136
+ **Purpose**: The master document that provides a bird's-eye view of the entire journey from POC to production. This is the first document stakeholders read.
137
+
138
+ **Key Sections Explained**:
139
+
140
+ #### Current State Assessment
141
+
142
+ Be brutally honest about where you are. This creates urgency and justifies the work.
143
+
144
+ ```markdown
145
+ ## Current State Assessment
146
+
147
+ ### βœ… What We Have (POC Level)
148
+
149
+ - 6 working games (Slots, Wheel, Pigman, Blackjack, High/Low, Roulette)
150
+ - Basic wallet system (balance, transactions)
151
+ - WebSocket and REST APIs
152
+ - Interactive API documentation
153
+
154
+ ### ⚠️ What's Missing for Production
155
+
156
+ - Authentication & authorization
157
+ - Rate limiting & abuse prevention
158
+ - Error handling & monitoring
159
+ - Security hardening
160
+ - Multi-tenancy support
161
+ ```
162
+
163
+ #### Phase Breakdown
164
+
165
+ Each phase gets a summary with **specific deliverables** (not vague goals):
166
+
167
+ ````markdown
168
+ ## Phase 2: Authentication & Authorization
169
+
170
+ **Goal:** Implement flexible authentication supporting multiple providers
171
+ **Duration:** 3-4 weeks
172
+
173
+ ### 2.1 Authentication Architecture
174
+
175
+ [Include ASCII diagrams showing the flow]
176
+
177
+ ### 2.2 Implementation Tasks
178
+
179
+ - [ ] JWT validation middleware (support multiple issuers)
180
+ - [ ] Claims-based authorization middleware
181
+ - [ ] Role definition system (player, admin, operator, super-admin)
182
+ - [ ] Tenant isolation middleware
183
+
184
+ ### 2.3 Authorization Roles & Permissions
185
+
186
+ ```typescript
187
+ enum Role {
188
+ PLAYER = "player", // Play games, view own data
189
+ MODERATOR = "moderator", // Ban users, view reports
190
+ OPERATOR = "operator", // Configure games, view analytics
191
+ ADMIN = "admin", // Full access to tenant
192
+ }
193
+ ```
194
+ ````
195
+
196
+ ````
197
+
198
+ #### Implementation Priority Matrix
199
+ The roadmap must clearly communicate **dependencies** and **blocking items**:
200
+
201
+ ```markdown
202
+ ## Implementation Priority Matrix
203
+
204
+ | Phase | Priority | Blocking? | Complexity | Duration |
205
+ |-------|----------|-----------|------------|----------|
206
+ | Phase 1: API Endpoints | πŸ”΄ HIGH | Yes | Medium | 2-3 weeks |
207
+ | Phase 2: Auth | πŸ”΄ HIGH | Yes | High | 3-4 weeks |
208
+ | Phase 3: Security | πŸ”΄ HIGH | Yes | Medium | 2 weeks |
209
+ | Phase 4: Monitoring | 🟑 MEDIUM | No | Medium | 2 weeks |
210
+ | Phase 5: Performance | 🟑 MEDIUM | No | High | 2-3 weeks |
211
+ ````
212
+
213
+ #### Quick Wins Section
214
+
215
+ Identify things that can be done **immediately** to show progress:
216
+
217
+ ```markdown
218
+ ## Quick Wins (Can Start Immediately)
219
+
220
+ 1. **Enhanced Wallet Endpoints** (1 week)
221
+ - Transaction history with filtering
222
+ - Wallet summary endpoints
223
+ 2. **Input Validation** (3 days)
224
+ - Add Zod schemas to all endpoints
225
+ 3. **Error Handling** (3 days)
226
+ - Standardize error responses
227
+ - Add structured logging
228
+ ```
229
+
230
+ #### Success Metrics
231
+
232
+ Define what "done" looks like with **measurable criteria**:
233
+
234
+ ```markdown
235
+ ## Success Metrics
236
+
237
+ **Technical:**
238
+
239
+ - βœ… 99.9% uptime
240
+ - βœ… <200ms p95 API latency
241
+ - βœ… Support 10,000 concurrent users
242
+ - βœ… 0 critical security vulnerabilities
243
+
244
+ **Business:**
245
+
246
+ - βœ… 5+ tenants onboarded
247
+ - βœ… <24h tenant onboarding time
248
+ - βœ… Self-service documentation coverage >80%
249
+ ```
250
+
251
+ ---
252
+
253
+ ### 2. Tech Stack (`TECH_STACK.md`)
254
+
255
+ **Purpose**: Project-level narrative of the technology choices and why they were made. **Version numbers are NOT restated here** β€” they live in exactly one place, [[STACK_MAP]], so they can never drift. `TECH_STACK.md` links to it.
256
+
257
+ **Key Sections**:
258
+
259
+ ```markdown
260
+ # Project - Complete Tech Stack
261
+
262
+ ## πŸ“‹ Overview
263
+
264
+ A **monorepo-based platform** built with modern web technologies.
265
+ For pinned versions and upgrade targets, see [[STACK_MAP]] (single source of truth).
266
+
267
+ ## 🎨 Frontend (apps/web/)
268
+
269
+ - **React** β€” component UI with concurrent rendering
270
+ - **Vite** β€” dev server + build (HMR, ESM-native)
271
+ - **TypeScript** β€” strict mode across all packages
272
+ - **Tailwind CSS** β€” utility-first styling with design tokens
273
+
274
+ ## πŸ–₯️ Backend (apps/api/)
275
+
276
+ - **Node.js** β€” server runtime via `@hono/node-server`
277
+ - **Hono** β€” lightweight, Web-Standards web framework
278
+ - **Zod** β€” runtime validation at the edges
279
+
280
+ ## πŸ—„οΈ Persistence (optional)
281
+
282
+ The starter ships **no database** by default β€” it is intentionally generic.
283
+ Add one when a feature needs it via `/add-data-layer` (Drizzle ORM + PostgreSQL
284
+ by default). Once adopted, its versions move into [[STACK_MAP]].
285
+
286
+ ## πŸ“¦ Infrastructure
287
+
288
+ - **pnpm** β€” monorepo workspaces
289
+ - **Turborepo** β€” build orchestration + caching
290
+ - Local: Frontend `http://localhost:5173` Β· Backend `http://localhost:3000`
291
+
292
+ ## πŸ“ˆ Versions
293
+
294
+ See [[STACK_MAP]] β€” the canonical table of pinned versions, latest-stable targets,
295
+ and which files to touch when bumping each dependency.
296
+ ```
297
+
298
+ > **Why no versions here?** Restating "Vite 6.x" in five documents guarantees four of
299
+ > them go stale. [[STACK_MAP]] is the only place a version number appears.
300
+
301
+ ---
302
+
303
+ ### 3. Architecture Guide (`ARCHITECTURE_GUIDE.md`)
304
+
305
+ **Purpose**: Documents **why** architectural decisions were made, not just what they are. Critical for onboarding and maintaining consistency.
306
+
307
+ **Key Sections**:
308
+
309
+ ```markdown
310
+ # Project - Architecture Guide
311
+
312
+ ## Current Architecture Overview
313
+ ```
314
+
315
+ [ASCII diagram of system components]
316
+
317
+ ````
318
+
319
+ ## Why [Decision X]?
320
+
321
+ ### Problems [Alternative] Creates
322
+ 1. **Problem 1**
323
+ - Code example showing the issue
324
+
325
+ 2. **Problem 2**
326
+ - Performance/maintenance implications
327
+
328
+ ## Why Current Approach is Better
329
+
330
+ ### [Pattern Name]
331
+ - βœ… Benefit 1
332
+ - βœ… Benefit 2
333
+ - βœ… Benefit 3
334
+
335
+ ```tsx
336
+ // Code example showing the preferred pattern
337
+ ````
338
+
339
+ ## Related Documents
340
+
341
+ - **[[DECISIONS|Decisions Log]]** - Detailed ADRs for major choices
342
+ - **[[WORKSTREAMS|Workstreams]]** - Live state of parallel work streams
343
+
344
+ ## Upgrade Paths
345
+
346
+ ### Phase 1: Current State βœ… (Now)
347
+
348
+ **What:** Current approach
349
+ **Best for:** Current scale
350
+ **Effort:** None - already implemented
351
+
352
+ ### Phase 2: Growing Complexity β†’ [Next Approach]
353
+
354
+ **When to upgrade:**
355
+
356
+ - Trigger condition 1
357
+ - Trigger condition 2
358
+
359
+ **Migration effort:** Low/Medium/High (X days)
360
+
361
+ ## Decision Matrix
362
+
363
+ | Need | Solution | Effort | When |
364
+ | ----------------- | ---------- | -------- | -------- |
365
+ | Quick prototype | Current | ⭐ | Now βœ“ |
366
+ | Prevent conflicts | Next level | ⭐⭐ | Growth |
367
+ | External sharing | Advanced | ⭐⭐⭐⭐ | Maturity |
368
+
369
+ ## Best Practices
370
+
371
+ ### 1. Pattern Name
372
+
373
+ ```tsx
374
+ // DO: Good example
375
+ // DON'T: Bad example
376
+ ```
377
+
378
+ ## Performance Implications
379
+
380
+ ### Current Approach
381
+
382
+ ```
383
+ Bundle Size: Xkb
384
+ Runtime: Optimal
385
+ ```
386
+
387
+ ````
388
+
389
+ ---
390
+
391
+ ### 3a. Domain Context (`CONTEXT.md`)
392
+
393
+ **Purpose**: The project's **ubiquitous language** β€” a glossary of canonical domain terms
394
+ (each with the synonyms to `_Avoid_`), kept free of implementation detail. For systems
395
+ with multiple bounded contexts, a `CONTEXT-MAP.md` lists the contexts and their
396
+ relationships, with a `CONTEXT.md` beside each context's code.
397
+
398
+ Built and sharpened with `/domain-model` (run during `/kickstart` Stage 3 and whenever
399
+ terminology is being decided). Read at `/start-session` so the assistant uses your terms,
400
+ and consulted by `/plan-phase` when naming tasks and types. Precise shared vocabulary up
401
+ front keeps architecture, types, and phases consistent.
402
+
403
+ ---
404
+
405
+ ### 4. Workstreams (`WORKSTREAMS.md`)
406
+
407
+ **Purpose**: The live state of every parallel stream of work β€” the swarm-native
408
+ replacement for a single "current focus". With multiple agents (or people) working
409
+ at once there is no one "current" task; there are several concurrent streams, each
410
+ with an owner, a branch/worktree, and a status. Working solo is just the one-row case.
411
+
412
+ It is the live counterpart to the [[QUEUE]]:
413
+
414
+ - **`QUEUE.md`** = the *inbound* queue β€” what to pick up next.
415
+ - **`WORKSTREAMS.md`** = the *live* state β€” what is in flight right now.
416
+ - **`DONE.md`** = the *completion log* β€” what shipped, append-only.
417
+
418
+ **Key Sections**:
419
+
420
+ ```markdown
421
+ # Workstreams
422
+
423
+ ## Active Streams
424
+
425
+ | Stream | Owner / Agent | Branch Β· Worktree | Status | Blocker | Last note |
426
+ | -------------- | ------------- | ---------------------------- | -------------- | ------- | ------------------ |
427
+ | Phase 2 · Auth | agent-api | `feat/phase2-auth` · wt-auth | 🚧 In Progress | None | RBAC next |
428
+ | Bugfix Β· logs | agent-infra | `fix/log-rotation` Β· wt-log | πŸ” In Review | None | PR open |
429
+
430
+ ## Recently Closed
431
+
432
+ - βœ… Phase 1 Β· Foundation β€” agent-api Β· merged YYYY-MM-DD
433
+ ```
434
+
435
+ **Usage**:
436
+
437
+ - Update with `/update-workstreams` whenever a stream starts, progresses, or closes.
438
+ - One row per live stream; closed streams move to `Recently Closed`.
439
+ - Record branch + worktree so any agent can resume the exact context.
440
+
441
+ ---
442
+
443
+ ### 4a. Multi-agent seam
444
+
445
+ Groundwork works **solo out of the box** β€” a single-row `WORKSTREAMS.md`, no coordinator,
446
+ no extra machinery. The multi-agent seam is an **optional upgrade**: when you want a
447
+ swarm, Groundwork hands off cleanly to an **external coordinator** via a file contract
448
+ split by writer: `QUEUE.md` (inbound) β†’ `WORKSTREAMS.md` (live) β†’ `DONE.md` (completion
449
+ log) β†’ `FACTS.md` (verified world-state). It never bundles or depends on the orchestration layer.
450
+
451
+ ```
452
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” pulls next β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” writes live β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
453
+ /plan-phase β”‚ QUEUE.md β”‚ ─────────────▢ β”‚ Coordinator β”‚ ──────────────▢ β”‚ WORKSTREAMS.md β”‚
454
+ + human β”‚ (inbound) β”‚ β”‚ + workers β”‚ ──appends──▢ DONE.md (log) β”‚
455
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
456
+ ```
457
+
458
+ - **`QUEUE.md`** β€” written by `/plan-phase` and the human, and nobody else. Each phase is
459
+ one queue item.
460
+ - The coordinator pulls the next unblocked item, opens a stream, and updates
461
+ **`WORKSTREAMS.md`** as work progresses β€” the same file `/update-workstreams` writes
462
+ (`workstreams.v1`: Stream Β· Owner Β· Branch Β· Status Β· Blocker Β· Last note).
463
+ On completion it appends one line to **`DONE.md`** (its only write in the queue seam) β€”
464
+ one writer per *file*, so concurrent edits never contend.
465
+ - **`FACTS.md`** β€” settled world-state. One writer per fact: whoever verified it.
466
+ Chat claims are hypotheses until they have a `verified:` line. `groundwork doctor`
467
+ flags entries older than 14 days.
468
+ - The coordinator's protocol (rooms, worktrees, messaging) stays **out** of Groundwork.
469
+ The only coupling is these files β€” so the methodology is portable across any
470
+ orchestration layer (or none).
471
+
472
+ **Dependency direction (one-way):** the coordinator depends on Groundwork's seam, **not
473
+ the reverse**. Groundwork has no knowledge of any coordinator and runs fully without one.
474
+
475
+ **Reference coordinator:** **`coord-mcp`** β€” an MCP-based coordination server (rooms +
476
+ worktree isolation over a shared bus) β€” is the reference implementation of this seam. It
477
+ reads `QUEUE.md` and writes `WORKSTREAMS.md` + `DONE.md`, and is an **optional layer that
478
+ builds on a Groundwork-initialised project**. MCP keeps it harness-agnostic (works across
479
+ Claude Code, Cursor, etc.), the same principle as Groundwork itself. Any other orchestrator
480
+ that honours the file contract drops in just as well.
481
+
482
+ **The board lives in `WORKSTREAMS.md`.** Under a coordinator, `WORKSTREAMS.md` *is* the
483
+ single board: the core (`## Active Streams` + `## Recently Closed`) that `/update-workstreams`
484
+ writes, plus coordinator-only extension sections after a fence (Open PRs, Cutover Gates, Needs
485
+ David, Risks, Rooms, Decisions Recorded). `/update-workstreams` and `groundwork status` parse
486
+ only the core and preserve the extensions verbatim. There is no separate board file.
487
+
488
+ **Repo shape ↔ bus topology.** A **monorepo** runs **one** coordination bus over a single
489
+ worktree space β€” the simplest setup for a swarm, and why agents work better here (shared
490
+ context, atomic cross-package changes). **Split repos** are supported, but you assign a
491
+ `coord-mcp` bus **per module/repo**, which is more to coordinate and makes cross-repo
492
+ changes harder. Prefer a monorepo for agentic work; reach for split repos only when module
493
+ boundaries genuinely demand separate repos.
494
+
495
+ ---
496
+
497
+ ### 4b. Testing philosophy (spec-first, minimal tests)
498
+
499
+ Groundwork is **spec-first, not test-first** β€” by deliberate choice, not omission. Rigor
500
+ lives in the **docs/spec** (PRD, ARCHITECTURE_GUIDE, CONTEXT, phase tasks), and the spec is
501
+ the artifact you invest in. Heavy test suites are treated as optional, not default.
502
+
503
+ **Why minimal tests:**
504
+
505
+ - Capable systems ship this way β€” the spec + a running app you actually exercise covers
506
+ most correctness.
507
+ - Tests are **context/token weight**: an agent reloads them on every pass. Tests you can
508
+ live without are negative value. Spend the effort speccing instead.
509
+
510
+ **Why it holds in a swarm:** a coordinated swarm self-QAs. Specialised agents own
511
+ **drift management** β€” they review changes against the spec and each other's work β€” which
512
+ substitutes for the regression net a test suite would otherwise provide *within* the swarm.
513
+
514
+ **⚠️ Where tests still earn their keep β€” human handover.** The model above relies on the
515
+ spec discipline *and* the swarm's QA layer. Hand the project to **other humans who engineer
516
+ differently** β€” less agentic, more manual β€” and neither safety net applies for them:
517
+ silent regressions surface. Before/at a human handover, add a thin **tripwire** β€” `build` +
518
+ `typecheck` pass, plus a handful of **smoke/integration tests on the critical paths only**
519
+ (not coverage targets, not unit tests everywhere). Tests as insurance on what would hurt if
520
+ it broke, not as a discipline.
521
+
522
+ **Verification is the bottleneck, not building.** With agents, *adding* a feature is cheap β€”
523
+ so cheap that they over-produce. *Trusting* one is not: every feature still needs a gate,
524
+ and for now that gate is human. Two rules follow:
525
+
526
+ - **Build only what was requested/specced.** Unrequested features are a liability β€” they add
527
+ review burden without delivering requested value. Surface ideas as suggestions; don't
528
+ silently ship them.
529
+ - **"Done" means human-gated, not just implemented.** Keep scope tight so the review queue
530
+ stays manageable β€” the limiting resource is reviewer time, not agent output.
531
+
532
+ **Future improvement:** revisit a thin automated verify layer (smoke + build gate in the
533
+ work loop) as model/token costs fall β€” the context-bloat objection weakens as inference gets
534
+ cheaper, and some gating can shift from humans to swarm QA. Tracked as a deliberate "later,"
535
+ not an oversight.
536
+
537
+ ---
538
+
539
+ ### 5. Decisions Log (`DECISIONS.md`)
540
+
541
+ **Purpose**: Architectural Decision Records (ADRs) that capture the "why" behind significant technical choices. Invaluable for onboarding and preventing repeated debates.
542
+
543
+ **Key Sections**:
544
+
545
+ ```markdown
546
+ # Architectural Decision Records
547
+
548
+ ## πŸ“‹ Decision Log
549
+
550
+ | ID | Decision | Status | Date |
551
+ | ------- | ------------------------- | ----------- | ---------- |
552
+ | ADR-001 | Use Hono over Express | βœ… Accepted | 2026-01-12 |
553
+ | ADR-002 | PostgreSQL for primary DB | βœ… Accepted | 2026-01-13 |
554
+
555
+ ---
556
+
557
+ ## ADR-001: Use Hono over Express
558
+
559
+ **Status**: βœ… Accepted
560
+ **Date**: 2026-01-12
561
+ **Deciders**: Engineering team
562
+
563
+ ### Context
564
+
565
+ Need to choose a web framework for the API server.
566
+
567
+ ### Decision
568
+
569
+ Use **Hono** for its TypeScript-first design and OpenAPI integration.
570
+
571
+ ### Consequences
572
+
573
+ **Positive:**
574
+
575
+ - Type-safe routing out of the box
576
+ - Built-in OpenAPI generation
577
+ - Lightweight (~14kb)
578
+
579
+ **Negative:**
580
+
581
+ - Smaller ecosystem than Express
582
+ - Team needs to learn new patterns
583
+
584
+ ### Alternatives Considered
585
+
586
+ | Alternative | Why Not |
587
+ | ----------- | -------------------------------------- |
588
+ | Express | Legacy patterns, no native TypeScript |
589
+ | Fastify | More complex, less OpenAPI integration |
590
+ ```
591
+
592
+ **When to Write an ADR**:
593
+
594
+ - Choosing between technologies
595
+ - Defining architectural patterns
596
+ - Security or compliance decisions
597
+ - Any decision a new team member would question
598
+
599
+ **Key Rule**: ADRs are immutable. If a decision changes, mark old as "Superseded" and create new ADR.
600
+
601
+ ---
602
+
603
+ ### 6. Design System (`DESIGN_SYSTEM.md`)
604
+
605
+ **Purpose**: Visual language reference for consistent UI. Essential for AI when generating frontend code.
606
+
607
+ **Key Sections**:
608
+
609
+ ```markdown
610
+ # Project - Design System
611
+
612
+ ## Color Palette
613
+
614
+ ### Primary Colors
615
+
616
+ - **Primary**: `#3b82f6` - Main actions, buttons
617
+ - **Primary Dark**: `#1e40af` - Hover states
618
+ - **Primary Light**: `#dbeafe` - Backgrounds
619
+
620
+ ### Status Colors
621
+
622
+ - **Success**: `#10b981` (Green) - Positive feedback
623
+ - **Warning**: `#f59e0b` (Amber) - Cautions
624
+ - **Error**: `#ef4444` (Red) - Errors, destructive
625
+
626
+ ### Neutral Scale
627
+ ```
628
+
629
+ 50 #f9fafb (Page background)
630
+ 100 #f3f4f6 (Alt background)
631
+ 200 #e5e7eb (Borders)
632
+ 500 #6b7280 (Secondary text)
633
+ 900 #111827 (Primary text)
634
+
635
+ ````
636
+
637
+ ## Typography
638
+
639
+ ### Font Stack
640
+ ```css
641
+ --font-primary: 'Inter', sans-serif;
642
+ ````
643
+
644
+ ### Type Scale
645
+
646
+ - **Display**: 24px - Page headings
647
+ - **Title**: 18px - Section headings
648
+ - **Body**: 14px - Main content
649
+ - **Caption**: 12px - Meta info
650
+
651
+ ## Components
652
+
653
+ ### Cards
654
+
655
+ ```css
656
+ background: #ffffff;
657
+ border: 1px solid #e5e7eb;
658
+ border-radius: 12px;
659
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
660
+ ```
661
+
662
+ ### Buttons
663
+
664
+ ```tsx
665
+ // Primary
666
+ className =
667
+ "bg-blue-600 text-white px-4 py-2 rounded-lg font-semibold hover:bg-blue-700";
668
+
669
+ // Secondary
670
+ className = "bg-gray-100 text-gray-900 px-4 py-2 rounded-lg hover:bg-gray-200";
671
+ ```
672
+
673
+ ## Spacing Scale
674
+
675
+ ```
676
+ 1 4px
677
+ 2 8px
678
+ 4 16px
679
+ 6 24px
680
+ 8 32px
681
+ ```
682
+
683
+ ## Accessibility
684
+
685
+ ### Contrast Ratios
686
+
687
+ - Normal text: Minimum 4.5:1
688
+ - Large text: Minimum 3:1
689
+
690
+ ### Focus States
691
+
692
+ - 2px focus ring on all interactive elements
693
+
694
+ ````
695
+
696
+ ---
697
+
698
+ ### 7. Phases Overview (`phases/README.md`)
699
+
700
+ **Purpose**: Track overall phase progress, provide navigation, and summarize each phase.
701
+
702
+ **Structure**:
703
+ ```markdown
704
+ # Production Readiness Phases
705
+
706
+ ## πŸ“‚ Phase Organization
707
+ Each phase has its own folder with:
708
+ - [[README]] - Phase overview and quick reference
709
+ - `PHASE[N]_TASKS.md` - Detailed task breakdown with checklists
710
+
711
+ ## πŸ—ΊοΈ Roadmap Overview
712
+ | Phase | Focus Area | Duration | Status |
713
+ |-------|-----------|----------|--------|
714
+ | [Phase 1](./phase1/) | [Description] | X weeks | 🚧 Ready to Start |
715
+
716
+ ## πŸ“‹ Phase Summaries
717
+
718
+ ### Phase 1: [Name] (X weeks)
719
+ **Goal**: [One-liner goal]
720
+
721
+ **Key Deliverables**:
722
+ - Deliverable 1
723
+ - Deliverable 2
724
+
725
+ **Success Criteria**: [How we know it's done]
726
+
727
+ ---
728
+ [Repeat for each phase]
729
+
730
+ ## πŸ“Š Progress Tracking
731
+ - **Completed Phases**: 0/N
732
+ - **Current Phase**: Phase 1
733
+ - **Overall Progress**: 0%
734
+
735
+ ## πŸ“ Documentation Standards
736
+ Each phase follows the same structure:
737
+ - Clear overview with goals and deliverables
738
+ - Detailed task breakdown with checkboxes
739
+ - Code examples and implementation patterns
740
+ - Testing requirements
741
+ - Success criteria
742
+ ````
743
+
744
+ ---
745
+
746
+ ### 8. Individual Phase README (`phases/phaseN/README.md`)
747
+
748
+ **Purpose**: Quick reference for a specific phase. Used for sprint planning, stakeholder updates, and onboarding new team members to a phase.
749
+
750
+ **Key Sections Explained**:
751
+
752
+ ````markdown
753
+ # Phase 2: Authentication & Authorization
754
+
755
+ **Duration**: 3-4 weeks
756
+ **Status**: 🚧 IN PROGRESS
757
+ **Priority**: πŸ”΄ CRITICAL - Blocking for production
758
+
759
+ ---
760
+
761
+ ## 🎯 Phase Overview
762
+
763
+ **Goal**: Implement flexible authentication supporting external providers with full RBAC.
764
+
765
+ **Current State**: No authentication - all endpoints publicly accessible
766
+ **Target State**: JWT-based auth with role-based access control and tenant isolation
767
+
768
+ ---
769
+
770
+ ## πŸ“Š Quick Stats
771
+
772
+ - **Sprints**: 3 (Foundation, RBAC, Multi-Tenancy)
773
+ - **Major Tasks**: 10
774
+ - **New Files**: ~25 files (~3,500 lines)
775
+ - **Database Changes**: 4 new tables + 5 modified
776
+ - **Test Coverage Target**: 80%+
777
+ - **Performance Target**: Auth latency <20ms p95
778
+
779
+ ---
780
+
781
+ ## 🎯 Key Deliverables
782
+
783
+ ### Sprint 1: Auth Foundation (Week 1)
784
+
785
+ - βœ… JWT verification middleware
786
+ - βœ… Claims extraction
787
+ - βœ… WebSocket authentication
788
+
789
+ ### Sprint 2: Authorization & RBAC (Week 2)
790
+
791
+ - βœ… Role-based access control
792
+ - βœ… Permission enforcement
793
+ - βœ… Audit logging
794
+
795
+ ### Sprint 3: Multi-Tenancy (Week 3-4)
796
+
797
+ - βœ… Tenant isolation
798
+ - 🚧 Rate limiting
799
+ - ⏳ API key authentication
800
+
801
+ ---
802
+
803
+ ## βœ… Success Criteria
804
+
805
+ ### Functional Requirements
806
+
807
+ - [ ] All API endpoints require valid authentication
808
+ - [ ] WebSocket connections require authentication
809
+ - [ ] Role-based access control (RBAC) enforced
810
+ - [ ] Admin endpoints restricted to admin/operator roles
811
+ - [ ] Players can only access their own data
812
+ - [ ] Multi-tenancy with complete data isolation
813
+
814
+ ### Security Requirements
815
+
816
+ - [ ] JWT signature verification using JWKS
817
+ - [ ] Token expiration checking
818
+ - [ ] Tenant isolation verified (no cross-tenant access)
819
+ - [ ] API keys stored as hashed values
820
+ - [ ] Error messages don't leak sensitive info
821
+
822
+ ### Quality Requirements
823
+
824
+ - [ ] 80%+ test coverage for auth code
825
+ - [ ] Auth latency <20ms p95
826
+ - [ ] All endpoints documented with required permissions
827
+ - [ ] Zero breaking changes to existing game logic
828
+
829
+ ---
830
+
831
+ ## ⚠️ Risks & Mitigation
832
+
833
+ | Risk | Impact | Likelihood | Mitigation |
834
+ | ----------------------------- | ----------- | ---------- | ---------------------------------------------- |
835
+ | Token refresh race conditions | 🟑 Medium | 🟑 Medium | Queue requests during refresh |
836
+ | Cross-tenant data leakage | πŸ”΄ Critical | 🟒 Low | Database-level tenant filters, security review |
837
+ | Performance degradation | 🟑 Medium | 🟑 Medium | Cache JWKS keys, optimize middleware |
838
+ | Integration complexity | 🟑 Medium | πŸ”΄ High | Incremental rollout, feature flags |
839
+
840
+ ---
841
+
842
+ ## πŸ”— Dependencies
843
+
844
+ - **Blocks**: Phase 3 (Security), Phase 4 (Monitoring)
845
+ - **Required**: Phase 1 (API Endpoints) - COMPLETE
846
+ - **Optional**: Redis (for rate limiting - can add later)
847
+
848
+ ---
849
+
850
+ ## πŸš€ Getting Started
851
+
852
+ ```bash
853
+ # 1. Create development branch
854
+ git checkout -b feature/phase2-auth
855
+
856
+ # 2. Review the detailed task plan
857
+ cat docs/phases/phase2/PHASE2_TASKS.md
858
+
859
+ # 3. Start with Task 1 (Auth Types)
860
+ # Follow sub-steps in the task document
861
+ ```
862
+ ````
863
+
864
+ ---
865
+
866
+ ## 🎯 Next Phase
867
+
868
+ After completion: β†’ [Phase 3: Security Hardening](../phase3/)
869
+
870
+ ````
871
+
872
+ ---
873
+
874
+ ### 9. Phase Tasks (`phases/phaseN/PHASEN_TASKS.md`)
875
+
876
+ **Purpose**: The most detailed document. This is where AI and developers spend most of their time. Each task must be specific enough that someone unfamiliar with the codebase can execute it.
877
+
878
+ **Key Sections Explained**:
879
+
880
+ #### Header with Real-Time Status
881
+ Always include current progress prominently at the top:
882
+
883
+ ```markdown
884
+ # Phase 2: Authentication & Authorization - Implementation Plan
885
+
886
+ **Duration:** 3-4 weeks
887
+ **Status:** 🚧 IN PROGRESS (Sprint 3 - Task 8 complete)
888
+ **Priority:** πŸ”΄ HIGH - Blocking for production
889
+ **Last Updated:** 2025-10-24
890
+
891
+ ### πŸ“ˆ Current Progress
892
+ - βœ… Sprint 1 (Auth Foundation): 100% complete (4/4 tasks)
893
+ - βœ… Sprint 2 (Authorization & RBAC): 100% complete (3/3 tasks)
894
+ - 🚧 Sprint 3 (Multi-Tenancy): 75% complete (3/4 tasks done)
895
+
896
+ **Components Implemented:** 9.75 / 10 (97.5%)
897
+ **Lines Added:** +3,450 / ~3,500
898
+ **Branch:** `feature/phase2-auth-multitenant`
899
+ ````
900
+
901
+ #### πŸ” Audit Summary with Risk Assessment
902
+
903
+ **This is critical.** Before writing tasks, you must audit the current state and identify risks:
904
+
905
+ ```markdown
906
+ ## πŸ” Authentication Audit Summary
907
+
908
+ **CRITICAL FINDINGS**: Currently **NO authentication or authorization** exists.
909
+
910
+ ### πŸ“Š Security Gaps Identified:
911
+
912
+ - **No Authentication**: All API endpoints are publicly accessible
913
+ - **No Authorization**: No role-based access control (RBAC)
914
+ - **No Tenant Isolation**: Single-tenant architecture
915
+ - **Direct playerId Access**: Any client can impersonate any player
916
+ - **Admin Endpoints Exposed**: `/api/wallet/freeze` has no protection
917
+
918
+ ### ⚠️ Impact Assessment:
919
+
920
+ - **Critical Security Risk**: Anyone can access/modify any player's data
921
+ - **No Production Readiness**: Cannot deploy without authentication
922
+ - **Compliance Risk**: GDPR/privacy violations without access controls
923
+ - **Business Risk**: Cannot support multiple tenants/customers
924
+ - **Fraud Risk**: No protection against player impersonation
925
+
926
+ ### πŸ“ˆ Scale of Work:
927
+
928
+ - **10 Major Tasks** (Tasks 1-10) β†’ βœ… **7 COMPLETE**, **3 REMAINING**
929
+ - **45+ Sub-Steps** β†’ βœ… **38 COMPLETED**, **7+ REMAINING**
930
+ - **3-4 Weeks** estimated β†’ **~1 Week REMAINING**
931
+ ```
932
+
933
+ #### 🎯 Target Architecture
934
+
935
+ Include **diagrams** (ASCII is fine) showing the end state:
936
+
937
+ ```markdown
938
+ ## 🎯 Target Architecture
939
+
940
+ ### Authentication Flow
941
+ ```
942
+
943
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
944
+ β”‚ External Auth Provider β”‚
945
+ β”‚ β€’ OAuth2 / OpenID Connect β”‚
946
+ β”‚ β€’ Custom JWT issuer β”‚
947
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
948
+ β”‚ Issues JWT token
949
+ β–Ό
950
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
951
+ β”‚ Game1 API Server (Middleware) β”‚
952
+ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
953
+ β”‚ β”‚ 1. JWT Verification Middleware β”‚ β”‚
954
+ β”‚ β”‚ β€’ Validate signature (JWKS) β”‚ β”‚
955
+ β”‚ β”‚ β€’ Check expiration β”‚ β”‚
956
+ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
957
+ β”‚ β–Ό β”‚
958
+ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
959
+ β”‚ β”‚ 2. Authorization Middleware β”‚ β”‚
960
+ β”‚ β”‚ β€’ Check required permissions β”‚ β”‚
961
+ β”‚ β”‚ β€’ Enforce tenant isolation β”‚ β”‚
962
+ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
963
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
964
+
965
+ ```
966
+
967
+ ### Directory Structure (New)
968
+ ```
969
+
970
+ apps/api/src/auth/
971
+ β”œβ”€β”€ middleware/
972
+ β”‚ β”œβ”€β”€ jwtAuth.ts # JWT verification
973
+ β”‚ β”œβ”€β”€ requireAuth.ts # Enforce authentication
974
+ β”‚ └── requireRole.ts # Role-based authorization
975
+ β”œβ”€β”€ providers/
976
+ β”‚ β”œβ”€β”€ JwtProvider.ts # JWT-based auth provider
977
+ β”‚ └── ApiKeyProvider.ts # API key provider
978
+ β”œβ”€β”€ types.ts # Auth type definitions
979
+ └── roles.ts # Role definitions
980
+
981
+ ```
982
+
983
+ ```
984
+
985
+ #### πŸ“‹ Task Structure with Completion Tracking
986
+
987
+ Each task should be **comprehensive** with sub-steps and completion notes:
988
+
989
+ ```markdown
990
+ ## πŸ“‹ Implementation Tasks
991
+
992
+ ### Sprint 1: Authentication Foundation (Week 1)
993
+
994
+ #### βœ… Task 1: Auth Configuration & Types
995
+
996
+ **Priority**: πŸ”΄ CRITICAL
997
+ **Complexity**: 🟒 EASY
998
+ **Package**: `apps/api/src/auth/`
999
+ **Dependencies**: None
1000
+ **Status**: βœ… COMPLETE
1001
+
1002
+ **Sub-Steps**:
1003
+
1004
+ - [x] 1.1: Create `auth/types.ts` with TypeScript interfaces
1005
+ - [x] 1.2: Create `auth/roles.ts` with role and permission enums
1006
+ - [x] 1.3: Create `auth/config.ts` for auth configuration
1007
+ - [x] 1.4: Add environment variables to `.env.example`
1008
+ - [x] 1.5: Document auth configuration in README
1009
+
1010
+ **Deliverables**:
1011
+
1012
+ - βœ… `auth/types.ts` (167 lines) - AuthUser, AuthClaims, AuthProvider
1013
+ - βœ… `auth/roles.ts` (220 lines) - 5 roles, 21 permissions
1014
+ - βœ… `auth/config.ts` (190 lines) - Multi-mode config
1015
+
1016
+ **βœ… COMPLETION NOTES**:
1017
+
1018
+ - All TypeScript types properly defined with full JSDoc
1019
+ - RBAC system: 5 roles (Player→Super Admin), 21 permissions
1020
+ - Multi-mode auth: Production, Development, Disabled
1021
+ - Total: 577 lines of production-ready code
1022
+ - Commit: 408bae6
1023
+
1024
+ ---
1025
+
1026
+ #### 🚧 Task 8: Multi-Tenancy Implementation
1027
+
1028
+ **Priority**: πŸ”΄ CRITICAL
1029
+ **Complexity**: πŸ”΄ HARD
1030
+ **Package**: `server/src/`
1031
+ **Dependencies**: Tasks 1-6
1032
+ **Status**: 🚧 IN PROGRESS (Sessions 1-3 Complete)
1033
+
1034
+ **Implementation Strategy**: Phased approach with 4 sessions:
1035
+
1036
+ - βœ… **Session 1**: Schema & Foundation (Complete)
1037
+ - βœ… **Session 2**: Query Updates (Complete)
1038
+ - βœ… **Session 3**: Advanced Features (Complete)
1039
+ - ⏳ **Session 4**: Testing & Polish (Remaining)
1040
+
1041
+ **Sub-Steps**:
1042
+
1043
+ - [x] 8.1: Create tenants table
1044
+ - [x] 8.2: Add `tenant_id` to all existing tables
1045
+ - [x] 8.3: Create database migration for tenant columns
1046
+ - [x] 8.4: Create tenant isolation helpers
1047
+ - [x] 8.5: Update all Drizzle queries to include `tenant_id` filter
1048
+ - [x] 8.6: Add tenant context to WebSocket connections
1049
+ - [x] 8.7: Implement tenant management API
1050
+ - [ ] 8.8: Write multi-tenancy tests (Session 4)
1051
+ - [ ] 8.9: Performance test with multiple tenants (Session 4)
1052
+
1053
+ **Known Issues**:
1054
+
1055
+ 1. **Scalar Lock Icon Missing**: Only 7 of 29 endpoints have `security`
1056
+ - Fix: Add global security to OpenAPI root
1057
+ 2. **WebSocket Tenant Context**: Currently using hardcoded 'default'
1058
+ - Fix: Extract tenantId from JWT in WebSocket auth
1059
+
1060
+ **Session 3 Deliverables**:
1061
+
1062
+ - βœ… `server/src/api/tenants.ts` - Tenant management API (223 lines)
1063
+ - βœ… `docs/TENANT_SECURITY_ANALYSIS.md` (152 lines)
1064
+ - βœ… Updated 29 API endpoints with tenant filtering
1065
+ ```
1066
+
1067
+ ---
1068
+
1069
+ ## ⚠️ Risk Identification & Mitigation
1070
+
1071
+ **Risk management is embedded throughout the task documents.** Here's how:
1072
+
1073
+ ### Risk Categories to Track
1074
+
1075
+ ```markdown
1076
+ ### ⚠️ Risk Assessment
1077
+
1078
+ | Risk | Impact | Likelihood | Mitigation |
1079
+ | -------------------------------- | ----------- | ---------- | --------------------------------------------------- |
1080
+ | Database performance degradation | πŸ”΄ High | 🟑 Medium | Add indexes on tenant_id, test with large datasets |
1081
+ | Breaking changes to API | πŸ”΄ High | 🟒 Low | Version API, comprehensive testing, backward compat |
1082
+ | Scope creep | 🟑 Medium | πŸ”΄ High | Stick to defined endpoints, defer nice-to-haves |
1083
+ | Testing time underestimated | 🟑 Medium | 🟑 Medium | Write tests in parallel with implementation |
1084
+ | Security bypass vulnerability | πŸ”΄ Critical | 🟒 Low | Penetration testing, security review |
1085
+ ```
1086
+
1087
+ ### Risk Indicators in Task Status
1088
+
1089
+ Use status indicators to flag risky tasks:
1090
+
1091
+ ```markdown
1092
+ #### Task 4: WebSocket Authentication
1093
+
1094
+ **Priority**: πŸ”΄ CRITICAL
1095
+ **Complexity**: πŸ”΄ HARD ← Red = high risk
1096
+ **Risk Flag**: ⚠️ Integration complexity with existing game handlers
1097
+ ```
1098
+
1099
+ ### Known Issues Section
1100
+
1101
+ Every task in progress should document discovered issues:
1102
+
1103
+ ```markdown
1104
+ **Known Issues**:
1105
+
1106
+ 1. **Token Refresh Race Condition** ⚠️
1107
+ - Problem: Concurrent requests during refresh cause 401s
1108
+ - Workaround: Queue requests during refresh
1109
+ - Fix ETA: Task 9
1110
+ 2. **Memory Leak in Auth Cache** 🟑
1111
+ - Problem: JWKS cache not invalidating properly
1112
+ - Impact: ~2MB/hour growth
1113
+ - Fix: Add TTL cleanup in Task 10
1114
+ ```
1115
+
1116
+ ### Security Considerations Section
1117
+
1118
+ For security-critical phases, include explicit guidance:
1119
+
1120
+ ```markdown
1121
+ ### Security Considerations
1122
+
1123
+ - **Never log tokens** in plain text
1124
+ - **Use secure random** for API key generation
1125
+ - **Hash API keys** before storage (bcrypt or argon2)
1126
+ - **Rotate JWKS keys** periodically
1127
+ - **Set proper CORS** per tenant
1128
+ - **Use HTTPS** in production (enforce)
1129
+ - **Implement token refresh** coordination
1130
+ ```
1131
+
1132
+ ### Migration & Compatibility Notes
1133
+
1134
+ Document how changes affect existing functionality:
1135
+
1136
+ ```markdown
1137
+ ### Compatibility Notes
1138
+
1139
+ - Maintain REST API contract (no breaking changes)
1140
+ - WebSocket protocol unchanged (auth in connection, not messages)
1141
+ - Game logic unchanged (replace hardcoded playerId with auth user)
1142
+ - Frontend changes minimal (add Authorization header, handle 401)
1143
+
1144
+ ### Migration Strategy
1145
+
1146
+ - **Phase 2.1** (Week 1): Add auth middleware as optional
1147
+ - **Phase 2.2** (Week 2-3): Enable on new endpoints first
1148
+ - **Phase 2.3** (Week 4): Full enforcement, remove optional mode
1149
+ ```
1150
+
1151
+ ---
1152
+
1153
+ ## πŸš€ Getting Started Checklist
1154
+
1155
+ When bootstrapping a new project:
1156
+
1157
+ ### 1. Create Monorepo Structure
1158
+
1159
+ ```bash
1160
+ # Create package structure
1161
+ mkdir -p apps/web/src/{components,features,pages,api}
1162
+ mkdir -p apps/api/src/{routes,features,middleware,services,auth,config,utils}
1163
+ mkdir -p packages/shared/src
1164
+ mkdir -p docs/phases/phase{1,2,3,4,5}/
1165
+
1166
+ # Initialize workspaces
1167
+ npm init -y
1168
+ # Edit package.json to add workspaces or pnpm-workspace.yaml
1169
+ ```
1170
+
1171
+ ### 2. Create Core Documents
1172
+
1173
+ - [ ] [[README]] - Project overview, quick start
1174
+ - [ ] [[WORKSTREAMS]] - Live state of parallel work streams (AI session handoffs)
1175
+ - [ ] [[QUEUE]] - Inbound task queue (feeds an external coordinator)
1176
+ - [ ] [[DONE]] - Completion log (append-only, executor-written)
1177
+ - [ ] [[TECH_STACK]] - Technology choices (versions live in [[STACK_MAP]])
1178
+ - [ ] [[STACK_MAP]] - Single source of truth for versions
1179
+ - [ ] [[ARCHITECTURE_GUIDE]] - Why decisions were made, patterns
1180
+ - [ ] [[DECISIONS]] - Architectural Decision Records (ADRs)
1181
+ - [ ] [[DESIGN_SYSTEM]] - Colors, typography, components
1182
+ - [ ] [[PRODUCTION_ROADMAP]] - High-level roadmap
1183
+ - [ ] `docs/phases/README.md` - Phase overview
1184
+
1185
+ ### 3. Define Your Phases
1186
+
1187
+ Identify 4-8 major phases based on:
1188
+
1189
+ - **Foundation** - Core infrastructure, basic features
1190
+ - **Security** - Auth, validation, hardening
1191
+ - **Quality** - Testing, monitoring, observability
1192
+ - **Scale** - Performance, caching, optimization
1193
+ - **Operations** - DevOps, deployment, backups
1194
+ - **Experience** - DX, documentation, SDKs
1195
+ - **Compliance** - Legal, regulatory, auditing
1196
+
1197
+ ### 4. Create Phase Documents
1198
+
1199
+ For each phase:
1200
+
1201
+ - [ ] `docs/phases/phaseN/README.md` - Overview
1202
+ - [ ] `docs/phases/phaseN/PHASEN_TASKS.md` - Detailed tasks
1203
+
1204
+ ### 5. Start Phase 1
1205
+
1206
+ - [ ] Audit current state of the codebase
1207
+ - [ ] Generate detailed task breakdown with checkboxes
1208
+ - [ ] Begin implementation with checkbox tracking
1209
+
1210
+ ---
1211
+
1212
+ ## πŸ”„ Workflow
1213
+
1214
+ ### Daily Development Flow
1215
+
1216
+ 1. Open current `PHASEN_TASKS.md`
1217
+ 2. Find next unchecked task
1218
+ 3. Implement with AI assistance
1219
+ 4. Check off completed sub-tasks
1220
+ 5. Update status section
1221
+ 6. Commit with descriptive message
1222
+
1223
+ ### Phase Completion Flow
1224
+
1225
+ 1. Verify all checkboxes in `PHASEN_TASKS.md`
1226
+ 2. Update phase README status
1227
+ 3. Update `phases/README.md` progress
1228
+ 4. Update [[PRODUCTION_ROADMAP]] status
1229
+ 5. Create branch for next phase
1230
+ 6. Begin next phase planning
1231
+
1232
+ ### Adding New Phases
1233
+
1234
+ 1. Copy existing phase folder structure
1235
+ 2. Audit the codebase for the new phase's scope
1236
+ 3. Generate comprehensive task breakdown with AI assistance
1237
+ 4. Update roadmap and phase README
1238
+
1239
+ ---
1240
+
1241
+ ## πŸ’‘ Best Practices
1242
+
1243
+ ### For Documentation
1244
+
1245
+ - **Use emojis** for visual scanning (βœ… 🚧 ⏳ 🎯 ⚠️)
1246
+ - **Keep checkboxes granular** - Each should be ~1-4 hours of work
1247
+ - **Update status sections** - Future you will thank you
1248
+ - **Link between documents** - Navigation matters
1249
+
1250
+ ### For AI Collaboration
1251
+
1252
+ - **Seed context** - AI reads your docs to understand the project
1253
+ - **Reference task IDs** - "Working on Task 3.2" gives clear context
1254
+ - **Keep tasks atomic** - AI works better with focused tasks
1255
+ - **Document decisions** - Add notes about why, not just what
1256
+
1257
+ ### For Progress Tracking
1258
+
1259
+ - **Daily updates** - Check boxes as you complete them
1260
+ - **Phase boundaries** - Don't blur phases together
1261
+ - **Celebrate wins** - βœ… COMPLETE feels good
1262
+
1263
+ ---
1264
+
1265
+ ## πŸ“Š Status Indicators
1266
+
1267
+ Use consistently across all documents:
1268
+
1269
+ | Indicator | Meaning |
1270
+ | --------- | ----------------- |
1271
+ | βœ… | Complete |
1272
+ | 🚧 | In Progress |
1273
+ | ⏳ | Not Started |
1274
+ | πŸ”΄ | Critical Priority |
1275
+ | 🟑 | Medium Priority |
1276
+ | 🟒 | Low Priority |
1277
+ | ⚠️ | Warning/Risk |
1278
+ | 🎯 | Goal/Target |
1279
+ | πŸ“‹ | Task List |
1280
+ | πŸ“Š | Statistics |
1281
+ | πŸ“… | Timeline |
1282
+ | πŸ”— | Dependencies |
1283
+
1284
+ ---
1285
+
1286
+ ## 🎨 Customization Points
1287
+
1288
+ Adapt this template for your domain:
1289
+
1290
+ 1. **Phase Names** - Match your domain (e.g., "Data Pipeline" instead of "API Endpoints")
1291
+ 2. **Success Metrics** - Define what matters for your project
1292
+ 3. **Risk Categories** - Identify domain-specific risks
1293
+ 4. **Timeline Estimates** - Calibrate to your team velocity
1294
+ 5. **Quality Gates** - Set appropriate coverage/latency targets
1295
+
1296
+ ---
1297
+
1298
+ **This document is your starting point. Fork it, adapt it, and make it yours.**
1299
+
1300
+ The goal isn't perfect documentationβ€”it's maintaining momentum while building complex software with AI assistance. Let the checkboxes guide you forward. πŸš€