Skip to content

Skills for Claude Code CLI such as full stack dev Cloudflare, React, Tailwind v4, and AI integrations.

Add project-planning skill for comprehensive project structuring

Jez76e5e10c2012
diff --git a/skills/project-planning/README.md b/skills/project-planning/README.md
new file mode 100644
index 00000000..51132832
--- /dev/null
+++ b/skills/project-planning/README.md
@@ -0,0 +1,342 @@
+# Project Planning Skill
+
+**Version**: 1.0
+**Last Updated**: 2025-10-25
+**Status**: Production Ready
+
+---
+
+## Purpose
+
+This skill generates comprehensive, context-optimized planning documentation for web application projects. It structures work into manageable phases with built-in verification, ensuring projects can be built iteratively while maintaining clarity between sessions.
+
+---
+
+## When to Use This Skill
+
+### Primary Use Cases
+
+**1. Starting a New Project** (Most Common)
+```
+User: "I want to build a task management app with authentication"
+Claude: "Let me use the project-planning skill to structure this properly"
+→ Skill generates planning docs
+→ Review and refine
+→ Start building
+```
+
+**2. Adding a Major Feature**
+```
+User: "I need to add real-time collaboration to the existing app"
+Claude: "Let me use project-planning to create phases for this feature"
+→ Skill generates new phases
+→ Append to existing IMPLEMENTATION_PHASES.md
+```
+
+**3. Re-planning a Messy Project**
+```
+User: "This project has gotten out of hand, let's restructure it"
+Claude: "Let me use project-planning to reorganize the work"
+→ Skill analyzes current state
+→ Generates new phase structure
+```
+
+**4. Validating Existing Phases**
+```
+User: "Does Phase 3 look reasonable, or is it too big?"
+Claude: "Let me use project-planning to validate this phase"
+→ Skill checks sizing rules
+→ Suggests improvements
+```
+
+---
+
+## What This Skill Generates
+
+### Core Output (Always)
+- **IMPLEMENTATION_PHASES.md** - Structured phase breakdown with verification criteria
+
+### Optional Outputs (Generated When Needed)
+- **DATABASE_SCHEMA.md** - Tables, relationships, indexes, migrations
+- **API_ENDPOINTS.md** - Routes, methods, auth, request/response schemas
+- **ARCHITECTURE.md** - System design, data flow, service boundaries
+- **UI_COMPONENTS.md** - Component hierarchy, state management, forms
+- **TESTING.md** - Test strategy, E2E flows, integration tests
+- **AGENTS_CONFIG.md** - AI agents, tools, workflows (for AI-enabled apps)
+- **INTEGRATION.md** - Third-party services, webhooks, API integrations
+
+**Decision Logic**: Skill asks if additional docs are needed, or auto-generates based on project complexity
+- Database with >3 tables → Suggest DATABASE_SCHEMA.md
+- API with >5 endpoints → Suggest API_ENDPOINTS.md
+- Multiple services/workers → Suggest ARCHITECTURE.md
+- AI-powered features → Suggest AGENTS_CONFIG.md
+
+---
+
+## How It Works
+
+### 1. Smart Defaults for Web Apps
+
+The skill knows your preferred stack from CLAUDE.md:
+- **Frontend**: Vite + React + Tailwind v4 + shadcn/ui
+- **Backend**: Cloudflare Workers (with Static Assets for frontend)
+- **Database**: D1 (SQL migrations)
+- **Storage**: R2 (files), KV (config/cache)
+- **Auth**: Clerk (JWT verification)
+- **Deployment**: Wrangler CLI
+
+It only asks clarifying questions when:
+- Non-standard tech is mentioned
+- Project complexity suggests alternatives
+- User specifies different preferences
+
+### 2. Hybrid Interaction
+
+**Template-driven with smart questions**:
+1. Analyzes project description
+2. Identifies phase types needed (Infrastructure, Database, API, UI, Integration, Testing)
+3. Asks targeted questions:
+ - "Do you need social auth (Google, GitHub)?"
+ - "Should users have roles/permissions?"
+ - "Any real-time features (Durable Objects)?"
+4. Generates docs with completed defaults and your specific choices
+
+### 3. Phase Validation Rules
+
+Every generated phase follows context-safe sizing:
+- **Max file scope**: 5-8 files per phase
+- **Max dependencies**: Shouldn't require deep knowledge of >2 other phases
+- **Time estimate**: Includes implementation + verification + expected fixes
+- **Verification required**: Every phase has checkbox criteria
+- **Exit criteria required**: Clear "done" definition
+
+If a phase violates these rules, skill auto-suggests splitting it.
+
+---
+
+## Phase Types
+
+The skill uses standardized templates for common web app patterns:
+
+### Infrastructure Phase
+- Project scaffolding (Vite, Wrangler, dependencies)
+- Build/deploy configuration
+- **Verification**: Can deploy to Cloudflare, dev server runs
+
+### Database Phase
+- Schema design (tables, relationships, indexes)
+- Migration files
+- Seed data for testing
+- **Verification**: CRUD operations work, constraints enforced
+
+### API Phase
+- Route definitions
+- Middleware (auth, CORS, error handling)
+- Request/response validation (Zod schemas)
+- **Verification**: Endpoint tests pass (200, 401, 400, 500 cases)
+
+### UI Phase
+- Component structure (shadcn/ui composition)
+- Form validation (Zod + React Hook Form)
+- State management (TanStack Query for server state, Zustand for client state)
+- **Verification**: User flows work, forms validate, states update correctly
+
+### Integration Phase
+- Third-party API setup (Clerk, Stripe, OpenAI, etc)
+- Webhook handlers
+- Configuration (environment variables, bindings)
+- **Verification**: External service integration works, webhooks fire correctly
+
+### Testing Phase (Optional)
+- E2E test setup
+- Integration tests for critical flows
+- **Verification**: Test suite passes, coverage meets threshold
+
+---
+
+## Auto-Trigger Keywords
+
+Claude Code will automatically discover this skill when you mention:
+
+**Project Initiation**:
+- "new project", "start a project", "create app", "build app", "scaffold project"
+- "planning documentation", "project planning", "implementation phases"
+- "structure project", "organize project", "plan features"
+
+**Planning Documents**:
+- "IMPLEMENTATION_PHASES.md", "DATABASE_SCHEMA.md", "API_ENDPOINTS.md"
+- "ARCHITECTURE.md", "session handoff", "phase breakdown"
+- "planning docs", "project spec", "requirements doc"
+
+**Phase Management**:
+- "phases", "phased approach", "implementation phases", "context-safe phases"
+- "verification criteria", "exit criteria", "phase validation"
+- "split phase", "merge phases", "adjust phases"
+
+**Stack Keywords**:
+- "Cloudflare Workers", "Vite + React", "D1 database", "full-stack app"
+- "Clerk auth", "Tailwind v4", "shadcn/ui", "TanStack Query"
+
+**Use Cases**:
+- "major feature", "restructure project", "plan sprint", "roadmap"
+- "session tracking", "context management", "git checkpoint"
+
+**AI/Integration Projects**:
+- "AI agents", "LLM features", "third-party integration", "webhooks"
+- "real-time features", "Durable Objects", "websockets"
+
+---
+
+## Invocation
+
+### Automatic (Recommended)
+When you describe a new project, Claude Code will automatically suggest using this skill:
+```
+User: "I want to build a blog with comments and user profiles"
+Claude: "Let me use the project-planning skill to structure this"
+```
+
+### Manual
+Explicitly request the skill:
+```
+"Use the project-planning skill to plan this project"
+"Generate planning docs for this feature"
+"Validate my existing phases with project-planning"
+```
+
+---
+
+## Example Workflow
+
+**User**: "I want to build a URL shortener with analytics"
+
+**Skill**:
+```
+Analyzing project requirements...
+
+Project Type: Web App (CRUD + Analytics)
+Suggested Stack: Cloudflare Workers + D1 + Vite + React
+
+Questions:
+1. Auth required? (public tool vs user accounts)
+2. Custom short URLs or auto-generated?
+3. Analytics detail level? (simple count vs detailed visitor data)
+4. Admin dashboard needed?
+```
+
+**User**: "User accounts, auto-generated, detailed analytics, yes to dashboard"
+
+**Skill Generates**:
+- IMPLEMENTATION_PHASES.md (6 phases)
+- DATABASE_SCHEMA.md (users, urls, analytics_events tables)
+- API_ENDPOINTS.md (auth, URL CRUD, redirect, analytics)
+
+**Output Preview**:
+```markdown
+# Implementation Phases: URL Shortener
+
+## Phase 1: Project Setup (2 hours)
+**Type**: Infrastructure
+**Files**: package.json, wrangler.jsonc, vite.config.ts, src/index.ts
+
+**Tasks**:
+- [x] Scaffold Cloudflare Worker with Vite
+- [x] Configure Tailwind v4 + shadcn/ui
+- [x] Setup D1 database binding
+- [x] Test deployment
+
+**Verification**:
+- [ ] `npm run dev` starts without errors
+- [ ] Can deploy to Cloudflare
+- [ ] Worker serves React app
+
+**Exit Criteria**: Working dev environment and successful deployment
+
+---
+
+## Phase 2: Database Schema (2-3 hours)
+**Type**: Database
+**Files**: migrations/0001_initial.sql, src/db/schema.ts
+
+[... and so on for each phase ...]
+```
+
+---
+
+## What This Skill Does NOT Do
+
+**Not a code generator**: Generates planning docs, not implementation code
+**Not a session tracker**: Doesn't update SESSION.md (that's Claude's job)
+**Not an architect**: Doesn't make technical decisions (Claude does that with you)
+**Not mandatory**: Optional tool - use when beneficial
+
+---
+
+## Expanding the Skill
+
+Easy to add new document templates:
+1. Create template in `templates/` directory
+2. Add generation logic to SKILL.md
+3. Update this README
+
+Future possibilities:
+- `phase-split`: Break oversized phase into sub-phases
+- `session-init`: Generate SESSION.md from IMPLEMENTATION_PHASES.md
+- More phase types (Migration, Optimization, Security)
+
+---
+
+## Files in This Skill
+
+```
+project-planning/
+├── README.md # This file
+├── SKILL.md # Main skill logic (planning assistant)
+├── templates/
+│ ├── IMPLEMENTATION_PHASES.md # Phase breakdown template
+│ ├── DATABASE_SCHEMA.md # Database design template
+│ ├── API_ENDPOINTS.md # API routes template
+│ ├── ARCHITECTURE.md # System design template
+│ ├── UI_COMPONENTS.md # Component structure template
+│ ├── TESTING.md # Test strategy template
+│ ├── AGENTS_CONFIG.md # AI agents template
+│ └── INTEGRATION.md # Third-party integrations template
+└── examples/
+ ├── simple-web-app.md # Basic CRUD example
+ ├── auth-web-app.md # Authentication example
+ └── ai-web-app.md # AI-powered app example
+```
+
+---
+
+## Tips for Best Results
+
+**Be specific in project description**: "Task manager with tags and due dates" is better than "to-do app"
+
+**Mention non-standard requirements early**: "Need to support 10k concurrent users" or "Must integrate with legacy SOAP API"
+
+**Review generated phases before starting**: Easier to refine planning docs than mid-implementation
+
+**Use examples for reference**: Check `examples/` directory for similar projects
+
+**Iterate if needed**: Regenerate or refine phases if initial output doesn't feel right
+
+---
+
+## Integration with Session Workflow
+
+After this skill generates IMPLEMENTATION_PHASES.md:
+
+1. Review and refine phases
+2. Create SESSION.md (manually or with future `session-init` tool)
+3. Start Phase 1
+4. Update SESSION.md as you progress
+5. Create git checkpoints at phase boundaries
+
+See main CLAUDE.md for full session handoff protocol.
+
+---
+
+## Questions?
+
+This skill is designed to evolve based on usage. If something doesn't work as expected or you'd like additional capabilities, refine SKILL.md and templates directly.
diff --git a/skills/project-planning/SKILL.md b/skills/project-planning/SKILL.md
new file mode 100644
index 00000000..d6cd62b0
--- /dev/null
+++ b/skills/project-planning/SKILL.md
@@ -0,0 +1,624 @@
+---
+name: project-planning
+description: >
+ Generates comprehensive planning documentation for web application projects, structuring work
+ into context-safe phases with built-in verification criteria. Creates IMPLEMENTATION_PHASES.md,
+ DATABASE_SCHEMA.md, API_ENDPOINTS.md, ARCHITECTURE.md, and other planning docs based on project
+ needs. Optimized for Cloudflare Workers + Vite + React stack. Use when starting new projects,
+ adding major features, or restructuring existing work into manageable phases.
+license: MIT
+---
+
+# Project Planning Skill
+
+You are a specialized project planning assistant. Your role is to help structure web application projects into well-organized, context-safe phases with comprehensive planning documentation.
+
+---
+
+## Your Capabilities
+
+You generate planning documentation for web app projects:
+- IMPLEMENTATION_PHASES.md (always)
+- DATABASE_SCHEMA.md (when data model is significant)
+- API_ENDPOINTS.md (when API surface is complex)
+- ARCHITECTURE.md (when multiple services/workers)
+- UI_COMPONENTS.md (when UI is complex or needs planning)
+- TESTING.md (when testing strategy needs documentation)
+- AGENTS_CONFIG.md (when project uses AI agents)
+- INTEGRATION.md (when third-party integrations are numerous)
+
+---
+
+## Default Stack Knowledge
+
+Unless the user specifies otherwise, assume this preferred stack (from their CLAUDE.md):
+
+**Frontend**: Vite + React + Tailwind v4 + shadcn/ui
+**Backend**: Cloudflare Workers with Static Assets
+**Database**: D1 (SQL with migrations)
+**Storage**: R2 (object storage), KV (key-value cache/config)
+**Auth**: Clerk (JWT verification with custom templates)
+**State Management**: TanStack Query (server), Zustand (client)
+**Forms**: React Hook Form + Zod validation
+**Deployment**: Wrangler CLI
+**Runtime**: Cloudflare Workers (not Node.js)
+
+Only ask about stack choices when:
+- User mentions non-standard tech
+- Project has unique requirements (high scale, legacy integration, etc)
+- Cloudflare stack seems inappropriate
+
+---
+
+## Planning Workflow
+
+### Step 1: Analyze Project Requirements
+
+When invoked, the user will have described a project. Extract:
+1. **Core functionality** - What does the app do?
+2. **User interactions** - Who uses it and how?
+3. **Data model** - What entities and relationships?
+4. **Integrations** - Third-party services needed?
+5. **Complexity signals** - Scale, real-time, AI, etc?
+
+### Step 2: Ask Clarifying Questions
+
+Ask 3-5 targeted questions to fill gaps. Focus on:
+- **Auth**: Public tool, user accounts, social auth, roles/permissions?
+- **Data**: Entities, relationships, volume expectations
+- **Features**: Real-time, file uploads, email, payments, AI?
+- **Integrations**: Specific third-party services?
+- **Scope**: MVP or full-featured? Timeline constraints?
+
+**Example question set**:
+```
+I'll help structure this project. A few questions to optimize the planning:
+
+1. **Authentication**: Do users need accounts, or is this a public tool?
+ - If accounts: Social auth (Google/GitHub)? Roles/permissions?
+
+2. **Data Model**: You mentioned [entities]. Any relationships I should know about?
+ - One-to-many? Many-to-many? Hierarchical?
+
+3. **Key Features**: Which of these apply?
+ - Real-time updates (websockets/Durable Objects)
+ - File uploads (images, documents, etc)
+ - Email notifications
+ - Payment processing
+ - AI-powered features
+
+4. **Scope**: Is this an MVP or full-featured app?
+ - MVP: Core features only, can iterate
+ - Full: Complete feature set from start
+
+5. **Timeline**: Any constraints? (helps with phase sizing)
+```
+
+### Step 3: Determine Document Set
+
+Based on answers, decide which docs to generate:
+
+**Always generate**:
+- IMPLEMENTATION_PHASES.md
+
+**Generate if**:
+- DATABASE_SCHEMA.md → Project has ≥3 tables OR complex relationships
+- API_ENDPOINTS.md → Project has ≥5 endpoints OR needs API documentation
+- ARCHITECTURE.md → Multiple services/workers OR complex data flow
+- UI_COMPONENTS.md → Complex UI OR needs component planning
+- TESTING.md → Testing strategy is non-trivial OR user requested
+- AGENTS_CONFIG.md → Uses AI agents OR LLM features
+- INTEGRATION.md → ≥3 third-party integrations OR complex webhooks
+
+**Ask user**: "I'll generate IMPLEMENTATION_PHASES.md. Should I also create [DATABASE_SCHEMA.md / API_ENDPOINTS.md / etc]?"
+
+### Step 4: Generate IMPLEMENTATION_PHASES.md
+
+Create structured phases using these types:
+
+#### Phase Type: Infrastructure
+**When**: Project start, deployment setup
+**Scope**: Scaffolding, build config, initial deployment
+**Files**: 3-5 (package.json, wrangler.jsonc, vite.config.ts, etc)
+**Duration**: 1-3 hours
+**Verification**: Dev server runs, can deploy, basic "Hello World" works
+
+#### Phase Type: Database
+**When**: Data model setup, schema changes
+**Scope**: Migrations, schema definition, seed data
+**Files**: 2-4 (migration files, schema types)
+**Duration**: 2-4 hours
+**Verification**: CRUD works, constraints enforced, relationships correct
+
+#### Phase Type: API
+**When**: Backend endpoints needed
+**Scope**: Routes, middleware, validation, error handling
+**Files**: 3-6 (route files, middleware, schemas)
+**Duration**: 3-6 hours (per endpoint group)
+**Verification**: All HTTP methods tested (200, 400, 401, 500), CORS works
+
+#### Phase Type: UI
+**When**: User interface components
+**Scope**: Components, forms, state, styling
+**Files**: 4-8 (component files)
+**Duration**: 4-8 hours (per feature)
+**Verification**: User flows work, forms validate, states update, responsive
+
+#### Phase Type: Integration
+**When**: Third-party services (auth, payments, AI, etc)
+**Scope**: API setup, webhooks, configuration
+**Files**: 2-4 (integration files, middleware)
+**Duration**: 3-5 hours (per integration)
+**Verification**: Service works, webhooks fire, errors handled
+
+#### Phase Type: Testing
+**When**: Need formal test suite (optional)
+**Scope**: E2E tests, integration tests
+**Files**: Test files
+**Duration**: 3-6 hours
+**Verification**: Tests pass, coverage meets threshold
+
+---
+
+## Phase Validation Rules
+
+Every phase you generate MUST follow these constraints:
+
+### Context-Safe Sizing
+- **Max files**: 5-8 files touched per phase
+- **Max dependencies**: Phase shouldn't require deep understanding of >2 other phases
+- **Max duration**: Implementation + verification + fixes should fit in one 2-4 hour session
+
+### Required Elements
+Every phase MUST have:
+1. **Type** - Infrastructure / Database / API / UI / Integration / Testing
+2. **Estimated duration** - In hours (and minutes of human time)
+3. **Files** - Specific files that will be created/modified
+4. **Task list** - Ordered checklist with clear actions
+5. **Verification criteria** - Checkbox list of tests to confirm phase works
+6. **Exit criteria** - Clear definition of "done"
+
+### Verification Requirements
+- **API phases**: Test all HTTP status codes (200, 400, 401, 404, 500)
+- **UI phases**: Test user flows, form validation, error states
+- **Database phases**: Test CRUD, constraints, relationships
+- **Integration phases**: Test service connectivity, webhooks, error handling
+
+### Auto-Split Logic
+If a phase violates sizing rules, automatically suggest splitting:
+```
+⚠️ Phase 4 "Complete User Management" is too large (12 files, 8-10 hours).
+
+Suggested split:
+- Phase 4a: User CRUD API (5 files, 4 hours)
+- Phase 4b: User Profile UI (6 files, 5 hours)
+```
+
+---
+
+## Template Structures
+
+### IMPLEMENTATION_PHASES.md Template
+
+```markdown
+# Implementation Phases: [Project Name]
+
+**Project Type**: [Web App / Dashboard / API / etc]
+**Stack**: Cloudflare Workers + Vite + React + D1
+**Estimated Total**: [X hours] (~[Y minutes] human time)
+
+---
+
+## Phase 1: [Name]
+**Type**: [Infrastructure/Database/API/UI/Integration/Testing]
+**Estimated**: [X hours]
+**Files**: [file1.ts, file2.tsx, ...]
+
+**Tasks**:
+- [ ] Task 1
+- [ ] Task 2
+- [ ] Task 3
+- [ ] Test basic functionality
+
+**Verification Criteria**:
+- [ ] Specific test 1
+- [ ] Specific test 2
+- [ ] Specific test 3
+
+**Exit Criteria**: [Clear definition of when this phase is complete]
+
+---
+
+## Phase 2: [Name]
+[... repeat structure ...]
+
+---
+
+## Notes
+
+**Testing Strategy**: [Inline per-phase / Separate testing phase / Both]
+**Deployment Strategy**: [Deploy per phase / Deploy at milestones / Final deploy]
+**Context Management**: Phases sized to fit in single session with verification
+```
+
+### DATABASE_SCHEMA.md Template
+
+```markdown
+# Database Schema: [Project Name]
+
+**Database**: Cloudflare D1
+**Migrations**: Located in `migrations/`
+**ORM**: [Drizzle / Raw SQL / None]
+
+---
+
+## Tables
+
+### `users`
+**Purpose**: User accounts and authentication
+
+| Column | Type | Constraints | Notes |
+|--------|------|-------------|-------|
+| id | INTEGER | PRIMARY KEY | Auto-increment |
+| email | TEXT | UNIQUE, NOT NULL | Used for login |
+| created_at | INTEGER | NOT NULL | Unix timestamp |
+
+**Indexes**:
+- `idx_users_email` on `email` (for login lookups)
+
+**Relationships**:
+- One-to-many with `tasks`
+
+---
+
+### `tasks`
+[... repeat structure ...]
+
+---
+
+## Migrations
+
+### Migration 1: Initial Schema
+**File**: `migrations/0001_initial.sql`
+**Creates**: users, tasks tables
+
+### Migration 2: Add Tags
+**File**: `migrations/0002_tags.sql`
+**Creates**: tags, task_tags tables
+
+---
+
+## Seed Data
+
+For development, seed with:
+- 3 sample users
+- 10 sample tasks across users
+- 5 tags
+```
+
+### API_ENDPOINTS.md Template
+
+```markdown
+# API Endpoints: [Project Name]
+
+**Base URL**: `/api`
+**Auth**: Clerk JWT (custom template with email + metadata)
+**Framework**: Hono (on Cloudflare Workers)
+
+---
+
+## Authentication
+
+### POST /api/auth/verify
+**Purpose**: Verify JWT token
+**Auth**: None (public)
+**Request**:
+```json
+{
+ "token": "string"
+}
+```
+**Responses**:
+- 200: Token valid → `{ "valid": true, "email": "[email protected]" }`
+- 401: Token invalid → `{ "error": "Invalid token" }`
+
+---
+
+## Users
+
+### GET /api/users/me
+**Purpose**: Get current user profile
+**Auth**: Required (JWT)
+**Responses**:
+- 200: `{ "id": 1, "email": "[email protected]", "created_at": 1234567890 }`
+- 401: Not authenticated
+
+[... repeat for all endpoints ...]
+
+---
+
+## Error Handling
+
+All endpoints return errors in this format:
+```json
+{
+ "error": "Human-readable message",
+ "code": "ERROR_CODE",
+ "details": {} // optional
+}
+```
+
+**Standard Codes**:
+- 400: Bad request (validation failed)
+- 401: Unauthorized (not logged in / invalid token)
+- 403: Forbidden (insufficient permissions)
+- 404: Not found
+- 500: Internal server error
+```
+
+### ARCHITECTURE.md Template
+
+```markdown
+# Architecture: [Project Name]
+
+**Deployment**: Cloudflare Workers
+**Frontend**: Vite + React (served as static assets)
+**Backend**: Worker handles API routes
+
+---
+
+## System Overview
+
+```
+┌─────────────────┐
+│ Browser │
+└────────┬────────┘
+ │
+ ↓ HTTPS
+┌─────────────────────────────────────┐
+│ Cloudflare Worker │
+│ ┌──────────────┐ ┌──────────────┐│
+│ │ Static Assets│ │ API Routes ││
+│ │ (Vite build) │ │ (Hono) ││
+│ └──────────────┘ └───────┬──────┘│
+└─────────────────────────────┼───────┘
+ │
+ ┌─────────────────┼─────────────────┐
+ ↓ ↓ ↓
+ ┌──────────┐ ┌──────────┐ ┌──────────┐
+ │ D1 │ │ R2 │ │ Clerk │
+ │ (Database)│ │(Storage) │ │ (Auth) │
+ └──────────┘ └──────────┘ └──────────┘
+```
+
+---
+
+## Data Flow
+
+### User Authentication
+1. User submits login form
+2. Frontend sends credentials to Clerk
+3. Clerk returns JWT
+4. Frontend includes JWT in API requests
+5. Worker middleware verifies JWT
+6. Protected routes accessible
+
+### Task Creation
+1. User submits task form
+2. Frontend validates with Zod
+3. POST /api/tasks with validated data
+4. Worker validates again server-side
+5. Insert into D1 database
+6. Return created task
+7. Frontend updates UI via TanStack Query
+
+[... more flows as needed ...]
+
+---
+
+## Service Boundaries
+
+**Frontend Responsibilities**:
+- User interaction
+- Client-side validation
+- Optimistic updates
+- State management (TanStack Query + Zustand)
+
+**Worker Responsibilities**:
+- Request routing
+- Authentication/authorization
+- Server-side validation
+- Business logic
+- Database operations
+- Third-party API calls
+
+**Cloudflare Services**:
+- D1: Persistent relational data
+- R2: File storage (images, documents)
+- KV: Configuration, feature flags, cache
+
+---
+
+## Security
+
+**Authentication**: Clerk JWT with custom claims
+**Authorization**: Middleware checks user ownership before mutations
+**Input Validation**: Zod schemas on client AND server
+**CORS**: Restricted to production domain
+**Secrets**: Environment variables in wrangler.jsonc (not committed)
+```
+
+---
+
+## Generation Logic
+
+### When User Invokes Skill
+
+1. **Analyze** their project description
+2. **Ask** 3-5 clarifying questions
+3. **Determine** which docs to generate
+4. **Generate** IMPLEMENTATION_PHASES.md first
+5. **Offer** to generate additional docs
+6. **Validate** all phases meet sizing rules
+7. **Output** docs to project `/docs` directory
+
+### Conversation Flow
+
+```
+User: [Describes project]
+↓
+Skill: "I'll help structure this. A few questions..."
+ [Ask 3-5 targeted questions]
+↓
+User: [Answers]
+↓
+Skill: "Great! I'll generate:
+ - IMPLEMENTATION_PHASES.md
+ Should I also create DATABASE_SCHEMA.md? [Y/n]"
+↓
+User: [Confirms]
+↓
+Skill: [Generates all confirmed docs]
+ "Planning docs created in /docs:
+ - IMPLEMENTATION_PHASES.md (8 phases, ~15 hours)
+ - DATABASE_SCHEMA.md (4 tables)
+
+ Review these docs and let me know if any phases need adjustment.
+ When ready, we'll create SESSION.md and start Phase 1."
+```
+
+---
+
+## Special Cases
+
+### AI-Powered Apps
+If project mentions AI, LLMs, agents, or ChatGPT-like features:
+- Ask about AI provider (OpenAI, Claude, Gemini, Cloudflare AI)
+- Suggest AGENTS_CONFIG.md
+- Add Integration phase for AI setup
+- Consider token management, streaming, error handling in phases
+
+### Real-Time Features
+If project needs websockets or real-time updates:
+- Suggest Durable Objects
+- Add Infrastructure phase for DO setup
+- Consider state synchronization in phases
+
+### High Scale / Performance
+If project mentions scale, performance, or high traffic:
+- Ask about expected load
+- Suggest caching strategy (KV, R2)
+- Consider Hyperdrive for database connections
+- Add Performance phase
+
+### Legacy Integration
+If project integrates with legacy systems:
+- Ask about integration points (REST, SOAP, DB)
+- Suggest INTEGRATION.md
+- Add Integration phase with extra time for unknowns
+- Consider Hyperdrive or API wrappers
+
+---
+
+## Quality Checklist
+
+Before outputting planning docs, verify:
+
+✅ **Every phase has**:
+- Type specified
+- Time estimate
+- File list
+- Task checklist
+- Verification criteria
+- Exit criteria
+
+✅ **Phases are context-safe**:
+- ≤8 files per phase
+- ≤2 phase dependencies
+- Fits in one session (2-4 hours)
+
+✅ **Verification is specific**:
+- Not "test the feature"
+- But "valid login returns 200 + token, invalid login returns 401"
+
+✅ **Exit criteria are clear**:
+- Not "API is done"
+- But "All endpoints return correct status codes, CORS configured, deployed"
+
+✅ **Phases are ordered logically**:
+- Infrastructure → Database → API → UI → Integration → Testing
+- Dependencies flow correctly (can't build UI before API)
+
+✅ **Time estimates are realistic**:
+- Include implementation + verification + expected fixes
+- Convert to human time (~1 hour = ~1 minute)
+
+---
+
+## Output Format
+
+Generate docs as markdown files for the user to review. Use this structure:
+
+```markdown
+I've structured your [Project Name] into [N] phases. Here's the planning documentation:
+
+---
+
+## IMPLEMENTATION_PHASES.md
+
+[Full content of IMPLEMENTATION_PHASES.md]
+
+---
+
+## DATABASE_SCHEMA.md
+
+[Full content of DATABASE_SCHEMA.md if generated]
+
+---
+
+[Additional docs if generated]
+
+---
+
+**Summary**:
+- **Total Phases**: [N]
+- **Estimated Duration**: [X hours] (~[Y minutes] human time)
+- **Phases with Testing**: All phases include verification criteria
+- **Deployment Strategy**: [When to deploy]
+
+**Next Steps**:
+1. Review these planning docs
+2. Refine any phases that feel wrong
+3. Create SESSION.md (or I can help with that)
+4. Start Phase 1 when ready
+
+Let me know if you'd like me to adjust any phases or add more detail anywhere!
+```
+
+---
+
+## Your Tone and Style
+
+- **Professional but conversational** - You're a helpful planning assistant
+- **Ask smart questions** - Don't ask about things you can infer from stack defaults
+- **Be concise** - Planning docs should be clear, not exhaustive
+- **Validate and suggest** - If a phase looks wrong, say so and suggest fixes
+- **Acknowledge uncertainty** - If you're unsure about something, ask rather than assume
+
+---
+
+## Remember
+
+You are a **planning assistant**, not a code generator. Your job is to:
+- Structure work into manageable phases
+- Ensure phases are context-safe
+- Provide clear verification criteria
+- Make it easy to track progress across sessions
+
+You are NOT responsible for:
+- Writing implementation code
+- Tracking session state (that's SESSION.md)
+- Making architectural decisions (that's Claude + user)
+- Forcing a specific approach (offer suggestions, not mandates)
+
+Your output should make it **easy to start coding** and **easy to resume after context clears**.
diff --git a/skills/project-planning/examples/ai-web-app.md b/skills/project-planning/examples/ai-web-app.md
new file mode 100644
index 00000000..4b9408e6
--- /dev/null
+++ b/skills/project-planning/examples/ai-web-app.md
@@ -0,0 +1,596 @@
+# Example: AI-Powered Research Assistant
+
+This example shows planning docs for an AI-powered research assistant with agents and tools.
+
+**User Request**: "I want to build an AI research assistant that can search the web, summarize articles, and help me organize research notes. Users should be able to chat with the AI and have it perform actions on their behalf."
+
+---
+
+## IMPLEMENTATION_PHASES.md (Excerpt)
+
+# Implementation Phases: AI Research Assistant
+
+**Project Type**: AI-Powered Web App with Agents
+**Stack**: Cloudflare Workers + Vite + React + D1 + Clerk + OpenAI
+**Estimated Total**: 30 hours (~30 minutes human time)
+**Created**: 2025-10-25
+
+---
+
+## Phase 1-3: [Standard setup phases - Infrastructure, Database, Auth]
+
+[Similar to auth-web-app.md example]
+
+---
+
+## Phase 4: OpenAI Integration
+**Type**: Integration
+**Estimated**: 3 hours
+**Files**: `src/lib/openai-client.ts`, `src/routes/ai.ts`
+
+### Tasks
+- [ ] Create OpenAI account and get API key
+- [ ] Install `openai` package
+- [ ] Create AI client wrapper
+- [ ] Test basic chat completion
+- [ ] Implement streaming responses
+- [ ] Add error handling and retries
+- [ ] Test token usage tracking
+
+### Verification Criteria
+- [ ] Can send message to OpenAI
+- [ ] Receives streaming response
+- [ ] Streams correctly to frontend
+- [ ] Errors handled gracefully (rate limits, API down)
+- [ ] Token usage logged
+
+### Exit Criteria
+OpenAI integration working with streaming responses.
+
+---
+
+## Phase 5: AI Tools (Functions)
+**Type**: Integration
+**Estimated**: 5 hours
+**Files**: `src/lib/ai-tools.ts`, `src/lib/web-search.ts`
+
+### Tasks
+- [ ] Define tool: `search_web` (using Brave Search API or similar)
+- [ ] Define tool: `save_note` (save to user's notes in D1)
+- [ ] Define tool: `search_notes` (search user's existing notes)
+- [ ] Define tool: `summarize_url` (fetch and summarize webpage)
+- [ ] Implement tool execution logic
+- [ ] Add tool result formatting
+- [ ] Test each tool independently
+
+### Verification Criteria
+- [ ] `search_web` returns relevant results
+- [ ] `save_note` creates note in database
+- [ ] `search_notes` finds user's notes
+- [ ] `summarize_url` fetches and summarizes content
+- [ ] Tools work when called by AI
+- [ ] Tool errors handled (404, timeout, etc)
+
+### Exit Criteria
+All AI tools implemented and tested.
+
+---
+
+## Phase 6: Research Agent
+**Type**: Integration
+**Estimated**: 4 hours
+**Files**: `src/agents/research-agent.ts`, `src/routes/agents.ts`
+
+### Tasks
+- [ ] Design research agent system prompt
+- [ ] Implement agent with tool calling
+- [ ] Add conversation state (Durable Object or in-memory)
+- [ ] Implement streaming tool calls to frontend
+- [ ] Add agent endpoint: POST /api/agents/research
+- [ ] Test multi-step research workflow
+
+### Verification Criteria
+- [ ] Agent responds to questions
+- [ ] Agent calls tools when needed
+- [ ] Tool results incorporated into response
+- [ ] Multi-turn conversation works
+- [ ] Streaming updates show tool usage to user
+
+### Exit Criteria
+Research agent working with tool integration.
+
+---
+
+## Phase 7: Notes Management
+**Type**: API + UI
+**Estimated**: 6 hours
+**Files**: `src/routes/notes.ts`, `src/components/NotesList.tsx`, etc.
+
+### Tasks
+- [ ] Create notes CRUD API
+- [ ] Build notes list UI
+- [ ] Build note viewer/editor
+- [ ] Add markdown rendering
+- [ ] Add note search functionality
+- [ ] Integrate AI-saved notes with manual notes
+
+### Verification Criteria
+- [ ] Can view all notes
+- [ ] Can create/edit/delete notes manually
+- [ ] AI-saved notes appear in list
+- [ ] Markdown renders correctly
+- [ ] Search finds notes
+
+### Exit Criteria
+Complete notes management system.
+
+---
+
+## Phase 8: Chat Interface
+**Type**: UI
+**Estimated**: 8 hours
+**Files**: `src/components/ChatInterface.tsx`, `src/components/Message.tsx`, etc.
+
+### Tasks
+- [ ] Install Vercel AI SDK (`@ai-sdk/react`)
+- [ ] Build chat UI with message list
+- [ ] Implement message input with auto-resize
+- [ ] Add streaming message display
+- [ ] Show tool call indicators (loading states)
+- [ ] Display tool results inline
+- [ ] Add conversation history persistence
+- [ ] Style with shadcn/ui components
+
+### Verification Criteria
+- [ ] Messages stream correctly
+- [ ] Tool calls show loading indicators
+- [ ] Tool results displayed clearly
+- [ ] Can continue conversation
+- [ ] Conversation history persists
+- [ ] UI handles errors gracefully
+
+### Exit Criteria
+Polished chat interface with full AI interaction.
+
+---
+
+## AGENTS_CONFIG.md (Excerpt)
+
+# AI Agents Configuration: AI Research Assistant
+
+**AI Provider**: OpenAI
+**Model**: gpt-5
+**Framework**: Vercel AI SDK
+
+---
+
+## Agents
+
+### Research Agent
+
+**Purpose**: Help users research topics by searching the web, summarizing content, and organizing notes.
+
+**Model**: gpt-5 (for complex reasoning, tool use)
+
+**System Prompt**:
+```
+You are a research assistant helping users gather and organize information.
+
+Your capabilities:
+- Search the web for information on any topic
+- Summarize articles and web pages
+- Save important findings as notes
+- Search through saved notes
+- Provide citations and sources
+
+Your workflow:
+1. When asked about a topic, search the web for recent information
+2. Summarize key findings concisely
+3. Offer to save important information as notes
+4. Always cite sources with URLs
+
+Guidelines:
+- Be thorough but concise
+- Verify information from multiple sources when possible
+- Organize information logically
+- Ask clarifying questions if user request is vague
+- Always provide sources for claims
+
+Response format:
+- Use markdown for structure
+- Use bullet points for lists
+- Bold important findings
+- Include clickable links to sources
+```
+
+**Available Tools**:
+- `search_web` - Search the web using Brave Search API
+- `summarize_url` - Fetch and summarize a specific webpage
+- `save_note` - Save information as a note in user's database
+- `search_notes` - Search user's existing notes
+
+**Example Conversation**:
+```
+User: "What are the latest developments in quantum computing?"
+
+Agent: I'll search for recent information on quantum computing.
+
+[Calls: search_web({ query: "latest quantum computing developments 2025" })]
+
+Based on recent sources, here are the latest developments:
+
+1. **IBM's 1000-qubit processor** - Announced in Q3 2025
+ - Source: [IBM Research](https://...)
+
+2. **Google's error correction breakthrough** - Published in Nature
+ - Reduced error rates by 50%
+ - Source: [Nature article](https://...)
+
+3. **Commercial applications emerging**
+ - Drug discovery (Pfizer partnership)
+ - Financial modeling (Goldman Sachs)
+
+Would you like me to save any of these findings as notes?
+
+User: "Yes, save the IBM development"
+
+Agent: [Calls: save_note({ title: "IBM 1000-qubit processor", content: "...", source: "..." })]
+
+✓ Saved note: "IBM 1000-qubit processor"
+```
+
+---
+
+## Tools
+
+### Tool: `search_web`
+
+**Purpose**: Search the web for information
+
+**Parameters**:
+```typescript
+{
+ query: string, // Search query
+ limit?: number // Max results (default 5)
+}
+```
+
+**Implementation**:
+```typescript
+export async function search_web(
+ { query, limit = 5 }: SearchWebParams,
+ context: Context
+) {
+ const response = await fetch('https://api.search.brave.com/res/v1/web/search', {
+ headers: {
+ 'X-Subscription-Token': context.env.BRAVE_API_KEY
+ },
+ params: { q: query, count: limit }
+ })
+
+ const data = await response.json()
+
+ return {
+ success: true,
+ results: data.web.results.map(r => ({
+ title: r.title,
+ url: r.url,
+ description: r.description
+ }))
+ }
+}
+```
+
+**Example**:
+```typescript
+// Agent calls
+const results = await search_web({
+ query: "quantum computing 2025",
+ limit: 5
+})
+
+// Returns
+{
+ success: true,
+ results: [
+ {
+ title: "IBM announces 1000-qubit processor",
+ url: "https://...",
+ description: "IBM has unveiled..."
+ }
+ ]
+}
+```
+
+---
+
+### Tool: `summarize_url`
+
+**Purpose**: Fetch and summarize a webpage
+
+**Parameters**:
+```typescript
+{
+ url: string // URL to fetch and summarize
+}
+```
+
+**Implementation**:
+```typescript
+export async function summarize_url(
+ { url }: SummarizeUrlParams,
+ context: Context
+) {
+ // Fetch webpage
+ const response = await fetch(url)
+ const html = await response.text()
+
+ // Extract main content (simplified - use Readability or similar in production)
+ const text = extractMainContent(html)
+
+ // Summarize with OpenAI
+ const summary = await context.env.AI.run('@cf/meta/llama-3-8b-instruct', {
+ prompt: `Summarize this article in 3-5 bullet points:\n\n${text}`
+ })
+
+ return {
+ success: true,
+ summary: summary.response,
+ url
+ }
+}
+```
+
+---
+
+### Tool: `save_note`
+
+**Purpose**: Save information as a note
+
+**Parameters**:
+```typescript
+{
+ title: string, // Note title
+ content: string, // Note content (markdown)
+ source?: string, // Optional source URL
+ tags?: string[] // Optional tags
+}
+```
+
+**Implementation**:
+```typescript
+export async function save_note(
+ { title, content, source, tags }: SaveNoteParams,
+ context: Context
+) {
+ const userId = context.get('userId')
+
+ const result = await context.env.DB.prepare(`
+ INSERT INTO notes (user_id, title, content, source, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?, ?)
+ `).bind(userId, title, content, source, Date.now(), Date.now()).run()
+
+ // Add tags if provided
+ if (tags?.length) {
+ // ... insert tag associations
+ }
+
+ return {
+ success: true,
+ noteId: result.meta.last_row_id
+ }
+}
+```
+
+---
+
+### Tool: `search_notes`
+
+**Purpose**: Search user's existing notes
+
+**Parameters**:
+```typescript
+{
+ query: string, // Search query
+ limit?: number // Max results (default 5)
+}
+```
+
+**Implementation**:
+```typescript
+export async function search_notes(
+ { query, limit = 5 }: SearchNotesParams,
+ context: Context
+) {
+ const userId = context.get('userId')
+
+ // Simple full-text search (use Vectorize for semantic search in production)
+ const results = await context.env.DB.prepare(`
+ SELECT id, title, content, source, created_at
+ FROM notes
+ WHERE user_id = ? AND (title LIKE ? OR content LIKE ?)
+ ORDER BY created_at DESC
+ LIMIT ?
+ `).bind(userId, `%${query}%`, `%${query}%`, limit).all()
+
+ return {
+ success: true,
+ notes: results.results
+ }
+}
+```
+
+---
+
+## Streaming Responses
+
+**Server** (POST /api/agents/research):
+```typescript
+import { openai } from '@ai-sdk/openai'
+import { streamText } from 'ai'
+
+app.post('/api/agents/research', async (c) => {
+ const { message, conversationId } = await c.req.json()
+ const userId = c.get('userId')
+
+ // Get conversation history (from Durable Object or DB)
+ const history = await getConversationHistory(conversationId)
+
+ const result = await streamText({
+ model: openai('gpt-5'),
+ messages: [
+ { role: 'system', content: RESEARCH_AGENT_PROMPT },
+ ...history,
+ { role: 'user', content: message }
+ ],
+ tools: {
+ search_web,
+ summarize_url,
+ save_note,
+ search_notes
+ },
+ onFinish: async ({ text }) => {
+ // Save conversation
+ await saveMessage(conversationId, { role: 'assistant', content: text })
+ }
+ })
+
+ return result.toAIStreamResponse()
+})
+```
+
+**Client** (React):
+```typescript
+import { useChat } from '@ai-sdk/react'
+
+export function ChatInterface() {
+ const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({
+ api: '/api/agents/research'
+ })
+
+ return (
+ <div className="flex flex-col h-screen">
+ <div className="flex-1 overflow-y-auto p-4 space-y-4">
+ {messages.map(m => (
+ <Message key={m.id} message={m} />
+ ))}
+ </div>
+
+ <form onSubmit={handleSubmit} className="border-t p-4">
+ <textarea
+ value={input}
+ onChange={handleInputChange}
+ placeholder="Ask me anything..."
+ className="w-full p-2 border rounded"
+ />
+ <button type="submit" disabled={isLoading}>
+ Send
+ </button>
+ </form>
+ </div>
+ )
+}
+```
+
+**Tool Call Display**:
+```typescript
+function Message({ message }) {
+ return (
+ <div className={cn('flex', message.role === 'user' ? 'justify-end' : 'justify-start')}>
+ <div className="max-w-[80%] rounded-lg p-4 bg-muted">
+ <ReactMarkdown>{message.content}</ReactMarkdown>
+
+ {message.toolInvocations?.map((tool, i) => (
+ <div key={i} className="mt-2 text-sm border-l-2 pl-2">
+ <span className="font-semibold">🔧 {tool.toolName}</span>
+ {tool.state === 'result' && (
+ <div className="text-muted-foreground">
+ ✓ {tool.result.success ? 'Success' : 'Failed'}
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ )
+}
+```
+
+---
+
+## DATABASE_SCHEMA.md (Additions)
+
+### `notes`
+| Column | Type | Constraints | Notes |
+|--------|------|-------------|-------|
+| `id` | INTEGER | PRIMARY KEY | |
+| `user_id` | INTEGER | FOREIGN KEY | References users(id) |
+| `title` | TEXT | NOT NULL | Note title |
+| `content` | TEXT | NOT NULL | Note content (markdown) |
+| `source` | TEXT | NULL | Source URL if from web |
+| `created_at` | INTEGER | NOT NULL | |
+| `updated_at` | INTEGER | NOT NULL | |
+
+### `conversations`
+| Column | Type | Constraints | Notes |
+|--------|------|-------------|-------|
+| `id` | INTEGER | PRIMARY KEY | |
+| `user_id` | INTEGER | FOREIGN KEY | References users(id) |
+| `title` | TEXT | NULL | Auto-generated from first message |
+| `created_at` | INTEGER | NOT NULL | |
+| `updated_at` | INTEGER | NOT NULL | |
+
+### `messages`
+| Column | Type | Constraints | Notes |
+|--------|------|-------------|-------|
+| `id` | INTEGER | PRIMARY KEY | |
+| `conversation_id` | INTEGER | FOREIGN KEY | References conversations(id) |
+| `role` | TEXT | NOT NULL | 'user' or 'assistant' |
+| `content` | TEXT | NOT NULL | Message content |
+| `tool_calls` | TEXT | NULL | JSON array of tool calls |
+| `created_at` | INTEGER | NOT NULL | |
+
+---
+
+## INTEGRATION.md (Additions)
+
+### OpenAI
+
+**Purpose**: AI-powered chat and tool use
+
+**Environment Variables**:
+```env
+OPENAI_API_KEY=sk-...
+```
+
+**API Client**:
+```typescript
+import { openai } from '@ai-sdk/openai'
+
+const model = openai('gpt-5')
+```
+
+**Rate Limits**: 10,000 requests/minute (Tier 5)
+
+**Token Management**:
+- Use `gpt-5-mini` for simple tasks (cheaper)
+- Use `gpt-5` for complex research (better reasoning)
+- Limit conversation history to last 20 messages
+- Track token usage per user (optional billing)
+
+---
+
+### Brave Search API
+
+**Purpose**: Web search for research agent
+
+**Environment Variables**:
+```env
+BRAVE_API_KEY=...
+```
+
+**Rate Limits**: 15,000 queries/month (free tier)
+
+---
+
+**Note**: This example demonstrates a complete AI-powered application with agents, tools, and streaming responses. Adjust complexity based on actual requirements.
diff --git a/skills/project-planning/examples/auth-web-app.md b/skills/project-planning/examples/auth-web-app.md
new file mode 100644
index 00000000..f6413bce
--- /dev/null
+++ b/skills/project-planning/examples/auth-web-app.md
@@ -0,0 +1,515 @@
+# Example: Personal Task Manager with Authentication
+
+This example shows planning docs for a task manager with user authentication using Clerk.
+
+**User Request**: "I want to build a task manager where users can sign up, log in, and manage their own tasks privately. Users should be able to organize tasks with tags and due dates."
+
+---
+
+## IMPLEMENTATION_PHASES.md (Excerpt)
+
+# Implementation Phases: Personal Task Manager
+
+**Project Type**: Authenticated Web App (Multi-user CRUD)
+**Stack**: Cloudflare Workers + Vite + React + Tailwind v4 + shadcn/ui + D1 + Clerk
+**Estimated Total**: 20 hours (~20 minutes human time)
+**Created**: 2025-10-25
+
+---
+
+## Phase 1: Project Setup
+**Type**: Infrastructure
+**Estimated**: 2-3 hours
+**Files**: `package.json`, `wrangler.jsonc`, `vite.config.ts`, `src/index.ts`
+
+[Same structure as simple example]
+
+---
+
+## Phase 2: Database Schema
+**Type**: Database
+**Estimated**: 3-4 hours
+**Files**: `migrations/0001_initial.sql`, `src/lib/db-types.ts`
+
+### Tasks
+- [ ] Create D1 database
+- [ ] Design schema for users, tasks, tags, task_tags tables
+- [ ] Write migration SQL
+- [ ] Create TypeScript types
+- [ ] Apply migration locally
+
+### Verification Criteria
+- [ ] All tables created successfully
+- [ ] Foreign keys work (task references user)
+- [ ] Unique constraints work (user email, tag name per user)
+- [ ] Can query with joins (tasks with their tags)
+
+### Exit Criteria
+Complete database schema with relationships working.
+
+---
+
+## Phase 3: Clerk Authentication Setup
+**Type**: Integration
+**Estimated**: 3 hours
+**Files**: `src/main.tsx`, `src/middleware/auth.ts`, `src/lib/clerk-types.ts`
+
+### Tasks
+- [ ] Create Clerk account and application
+- [ ] Install `@clerk/clerk-react` and `@clerk/backend`
+- [ ] Configure Clerk in frontend (ClerkProvider)
+- [ ] Create custom JWT template in Clerk dashboard
+- [ ] Implement auth middleware for Worker
+- [ ] Test JWT verification
+- [ ] Create protected route wrapper component
+
+### Verification Criteria
+- [ ] Can sign up new user (Clerk modal)
+- [ ] Can sign in existing user
+- [ ] JWT is included in API requests
+- [ ] Worker middleware verifies JWT correctly
+- [ ] Invalid JWT returns 401
+- [ ] Protected routes redirect if not authenticated
+
+### Exit Criteria
+Authentication flow working end-to-end. Users can sign up, log in, and access protected routes.
+
+---
+
+## Phase 4: User Sync (Webhook)
+**Type**: Integration
+**Estimated**: 2 hours
+**Files**: `src/routes/webhooks.ts`, `src/lib/webhook-verify.ts`
+
+### Tasks
+- [ ] Install `svix` package
+- [ ] Create webhook endpoint `/api/webhooks/clerk`
+- [ ] Implement signature verification
+- [ ] Handle `user.created` event (insert into database)
+- [ ] Handle `user.updated` event
+- [ ] Handle `user.deleted` event
+- [ ] Configure webhook in Clerk dashboard
+
+### Verification Criteria
+- [ ] New user signup triggers webhook
+- [ ] User record created in D1 database
+- [ ] Invalid webhook signature rejected
+- [ ] User updates sync to database
+- [ ] User deletions remove tasks (cascade)
+
+### Exit Criteria
+User data synced between Clerk and D1 database.
+
+---
+
+## Phase 5: Tasks API
+**Type**: API
+**Estimated**: 5 hours
+**Files**: `src/routes/tasks.ts`, `src/lib/schemas.ts`
+
+### Tasks
+- [ ] Define Zod schemas for task validation
+- [ ] GET /api/tasks (user's tasks only)
+- [ ] POST /api/tasks (create for current user)
+- [ ] PATCH /api/tasks/:id (update if user owns)
+- [ ] DELETE /api/tasks/:id (delete if user owns)
+- [ ] Add authorization checks (verify ownership)
+- [ ] Filter by completion, tag, due date
+
+### Verification Criteria
+- [ ] GET /api/tasks returns only current user's tasks
+- [ ] Cannot access other users' tasks
+- [ ] Cannot update/delete other users' tasks (403)
+- [ ] Filters work (completed, tag, due date)
+- [ ] All CRUD operations tested
+
+### Exit Criteria
+Tasks API complete with proper authorization.
+
+---
+
+## Phase 6: Tags API
+**Type**: API
+**Estimated**: 2 hours
+**Files**: `src/routes/tags.ts`
+
+### Tasks
+- [ ] GET /api/tags (user's tags)
+- [ ] POST /api/tags (create tag)
+- [ ] DELETE /api/tags/:id (delete tag)
+- [ ] POST /api/tasks/:id/tags (add tag to task)
+- [ ] DELETE /api/tasks/:id/tags/:tagId (remove tag from task)
+
+### Verification Criteria
+- [ ] Can create tags
+- [ ] Can attach tags to tasks
+- [ ] Can filter tasks by tag
+- [ ] Deleting tag doesn't delete tasks
+
+### Exit Criteria
+Tag management working with task associations.
+
+---
+
+## Phase 7: Dashboard UI
+**Type**: UI
+**Estimated**: 6 hours
+**Files**: `src/pages/Dashboard.tsx`, `src/components/layout/Sidebar.tsx`, etc.
+
+### Tasks
+- [ ] Build dashboard layout with sidebar
+- [ ] Add user menu with sign out
+- [ ] Create task list view
+- [ ] Add task filtering (completed, tags, due date)
+- [ ] Build task creation dialog
+- [ ] Build task editing dialog
+- [ ] Add task deletion with confirmation
+
+### Verification Criteria
+- [ ] Dashboard shows user's tasks
+- [ ] Filters work correctly
+- [ ] Can create tasks via dialog
+- [ ] Can edit existing tasks
+- [ ] Can delete tasks
+- [ ] UI updates optimistically
+
+### Exit Criteria
+Complete dashboard with full task management.
+
+---
+
+## Phase 8: Tags UI
+**Type**: UI
+**Estimated**: 3 hours
+**Files**: `src/components/TagManager.tsx`, `src/components/TagBadge.tsx`
+
+### Tasks
+- [ ] Build tag creation form
+- [ ] Build tag list component
+- [ ] Add tag selection to task form (multi-select)
+- [ ] Display tags as badges on tasks
+- [ ] Allow removing tags from tasks
+
+### Verification Criteria
+- [ ] Can create new tags
+- [ ] Can select tags when creating/editing task
+- [ ] Tags display on task cards
+- [ ] Can filter by tag
+- [ ] Can remove tags from tasks
+
+### Exit Criteria
+Full tag management integrated with tasks.
+
+---
+
+## DATABASE_SCHEMA.md (Excerpt)
+
+# Database Schema: Personal Task Manager
+
+---
+
+## Tables
+
+### `users`
+| Column | Type | Constraints | Notes |
+|--------|------|-------------|-------|
+| `id` | INTEGER | PRIMARY KEY | Auto-increment |
+| `clerk_id` | TEXT | UNIQUE, NOT NULL | Clerk user ID |
+| `email` | TEXT | UNIQUE, NOT NULL | User email |
+| `display_name` | TEXT | NULL | Display name |
+| `created_at` | INTEGER | NOT NULL | Unix timestamp |
+| `updated_at` | INTEGER | NOT NULL | Unix timestamp |
+
+**Indexes**: `idx_users_clerk_id`, `idx_users_email`
+
+---
+
+### `tasks`
+| Column | Type | Constraints | Notes |
+|--------|------|-------------|-------|
+| `id` | INTEGER | PRIMARY KEY | Auto-increment |
+| `user_id` | INTEGER | FOREIGN KEY, NOT NULL | References users(id) |
+| `title` | TEXT | NOT NULL | Task title |
+| `description` | TEXT | NULL | Task description |
+| `completed` | INTEGER | NOT NULL | 0 or 1 |
+| `due_date` | INTEGER | NULL | Unix timestamp |
+| `created_at` | INTEGER | NOT NULL | Unix timestamp |
+| `updated_at` | INTEGER | NOT NULL | Unix timestamp |
+
+**Indexes**: `idx_tasks_user_id`, `idx_tasks_due_date`, `idx_tasks_completed`
+
+**Relationships**: Many-to-one with users
+
+**Cascade**: ON DELETE CASCADE (deleting user deletes their tasks)
+
+---
+
+### `tags`
+| Column | Type | Constraints | Notes |
+|--------|------|-------------|-------|
+| `id` | INTEGER | PRIMARY KEY | Auto-increment |
+| `user_id` | INTEGER | FOREIGN KEY, NOT NULL | References users(id) |
+| `name` | TEXT | NOT NULL | Tag name |
+| `color` | TEXT | NOT NULL | Hex color code |
+| `created_at` | INTEGER | NOT NULL | Unix timestamp |
+
+**Indexes**: `idx_tags_user_id`, `idx_tags_name_user_id UNIQUE`
+
+**Unique Constraint**: (user_id, name) - users can't have duplicate tag names
+
+---
+
+### `task_tags`
+| Column | Type | Constraints | Notes |
+|--------|------|-------------|-------|
+| `id` | INTEGER | PRIMARY KEY | Auto-increment |
+| `task_id` | INTEGER | FOREIGN KEY, NOT NULL | References tasks(id) |
+| `tag_id` | INTEGER | FOREIGN KEY, NOT NULL | References tags(id) |
+| `created_at` | INTEGER | NOT NULL | Unix timestamp |
+
+**Indexes**: `idx_task_tags_task_id`, `idx_task_tags_tag_id`, `idx_task_tags_composite UNIQUE`
+
+**Unique Constraint**: (task_id, tag_id) - can't add same tag to task twice
+
+**Cascade**: ON DELETE CASCADE (deleting task or tag removes association)
+
+---
+
+## Relationships Diagram
+
+```
+┌─────────────┐
+│ users │
+└──────┬──────┘
+ │ 1
+ │
+ ├─────────────────────┬
+ │ N │ N
+┌──────┴──────────┐ ┌──────┴──────────┐
+│ tasks │ │ tags │
+└──────┬──────────┘ └──────┬──────────┘
+ │ N │ N
+ │ │
+ └──────────┬──────────┘
+ │
+ ┌──────┴──────────┐
+ │ task_tags │
+ │ (junction) │
+ └─────────────────┘
+```
+
+---
+
+## API_ENDPOINTS.md (Excerpt)
+
+# API Endpoints: Personal Task Manager
+
+**Auth**: Required on all `/api/*` routes (except webhooks)
+
+---
+
+## Authentication
+
+### GET `/api/auth/me`
+**Purpose**: Get current user profile
+
+**Response 200**:
+```json
+{
+ "data": {
+ "id": 1,
+ "email": "[email protected]",
+ "displayName": "John Doe",
+ "createdAt": 1234567890
+ }
+}
+```
+
+---
+
+## Tasks
+
+### GET `/api/tasks`
+**Purpose**: Get current user's tasks
+
+**Query Parameters**:
+- `completed` (optional): `true` or `false`
+- `tag` (optional): Tag ID to filter by
+- `dueBefore` (optional): Unix timestamp
+- `dueAfter` (optional): Unix timestamp
+
+**Response 200**:
+```json
+{
+ "data": [
+ {
+ "id": 1,
+ "title": "Review PR",
+ "description": "Check the new feature",
+ "completed": false,
+ "dueDate": 1234567890,
+ "tags": [
+ { "id": 1, "name": "work", "color": "#3b82f6" }
+ ],
+ "createdAt": 1234567890,
+ "updatedAt": 1234567890
+ }
+ ]
+}
+```
+
+---
+
+### POST `/api/tasks`
+**Purpose**: Create task for current user
+
+**Request Body**:
+```json
+{
+ "title": "New Task",
+ "description": "Optional",
+ "dueDate": 1234567890,
+ "tagIds": [1, 2]
+}
+```
+
+**Validation**:
+```typescript
+z.object({
+ title: z.string().min(1).max(100),
+ description: z.string().optional(),
+ dueDate: z.number().optional(),
+ tagIds: z.array(z.number()).optional()
+})
+```
+
+**Response 201**: Created task with tags
+
+---
+
+## Tags
+
+### GET `/api/tags`
+**Purpose**: Get current user's tags
+
+**Response 200**:
+```json
+{
+ "data": [
+ { "id": 1, "name": "work", "color": "#3b82f6" },
+ { "id": 2, "name": "personal", "color": "#10b981" }
+ ]
+}
+```
+
+---
+
+### POST `/api/tags`
+**Purpose**: Create tag for current user
+
+**Request Body**:
+```json
+{
+ "name": "urgent",
+ "color": "#ef4444"
+}
+```
+
+**Response 201**: Created tag
+
+**Response 400**: Duplicate tag name (user already has tag with this name)
+
+---
+
+## INTEGRATION.md (Excerpt)
+
+# Third-Party Integrations: Personal Task Manager
+
+---
+
+## Clerk (Authentication)
+
+**Purpose**: User authentication and management
+
+**Environment Variables**:
+```env
+VITE_CLERK_PUBLISHABLE_KEY=pk_test_...
+CLERK_SECRET_KEY=sk_test_...
+CLERK_WEBHOOK_SECRET=whsec_...
+```
+
+**Custom JWT Template** (Clerk dashboard):
+```json
+{
+ "email": "{{user.primary_email_address}}",
+ "userId": "{{user.id}}",
+ "firstName": "{{user.first_name}}",
+ "lastName": "{{user.last_name}}"
+}
+```
+
+**Frontend**:
+```tsx
+import { ClerkProvider, SignedIn, SignedOut, UserButton } from '@clerk/clerk-react'
+
+<ClerkProvider publishableKey={...}>
+ <SignedIn>
+ <Dashboard />
+ <UserButton />
+ </SignedIn>
+ <SignedOut>
+ <LandingPage />
+ </SignedOut>
+</ClerkProvider>
+```
+
+**Backend Middleware**:
+```typescript
+import { verifyToken } from '@clerk/backend'
+
+export async function authMiddleware(c: Context, next: Next) {
+ const token = c.req.header('Authorization')?.replace('Bearer ', '')
+ const verified = await verifyToken(token, {
+ secretKey: c.env.CLERK_SECRET_KEY
+ })
+ c.set('clerkUserId', verified.userId)
+ c.set('email', verified.email)
+
+ // Get local user ID from database
+ const user = await c.env.DB.prepare(
+ 'SELECT id FROM users WHERE clerk_id = ?'
+ ).bind(verified.userId).first()
+
+ c.set('userId', user.id)
+ await next()
+}
+```
+
+**Webhook** (User Sync):
+```typescript
+app.post('/api/webhooks/clerk', async (c) => {
+ const payload = await c.req.text()
+ const verified = await verifyClerkWebhook(payload, c.req.raw.headers, c.env.CLERK_WEBHOOK_SECRET)
+
+ const event = JSON.parse(payload)
+
+ if (event.type === 'user.created') {
+ await c.env.DB.prepare(`
+ INSERT INTO users (clerk_id, email, display_name, created_at, updated_at)
+ VALUES (?, ?, ?, ?, ?)
+ `).bind(
+ event.data.id,
+ event.data.email_addresses[0].email_address,
+ `${event.data.first_name} ${event.data.last_name}`,
+ Date.now(),
+ Date.now()
+ ).run()
+ }
+
+ return c.json({ received: true })
+})
+```
+
+---
+
+**Note**: This example shows the complete structure for an authenticated multi-user app. For AI-powered features, see `ai-web-app.md`.
diff --git a/skills/project-planning/examples/simple-web-app.md b/skills/project-planning/examples/simple-web-app.md
new file mode 100644
index 00000000..f31aa104
--- /dev/null
+++ b/skills/project-planning/examples/simple-web-app.md
@@ -0,0 +1,334 @@
+# Example: Simple Task Manager (No Auth)
+
+This is an example of planning docs generated for a simple public task manager web app (no user accounts).
+
+**User Request**: "I want to build a simple task manager where anyone can create, edit, and complete tasks. Just a public tool, no user accounts needed."
+
+---
+
+## IMPLEMENTATION_PHASES.md
+
+# Implementation Phases: Simple Task Manager
+
+**Project Type**: Public Web App (CRUD)
+**Stack**: Cloudflare Workers + Vite + React + Tailwind v4 + shadcn/ui + D1
+**Estimated Total**: 12 hours (~12 minutes human time with AI assistance)
+**Created**: 2025-10-25
+
+---
+
+## Phase 1: Project Setup
+**Type**: Infrastructure
+**Estimated**: 2-3 hours
+**Files**: `package.json`, `wrangler.jsonc`, `vite.config.ts`, `src/index.ts`, `src/index.css`
+
+### Tasks
+- [ ] Scaffold Cloudflare Worker with Vite using `npm create cloudflare@latest`
+- [ ] Install dependencies: React, Tailwind v4, shadcn/ui, Hono
+- [ ] Configure `wrangler.jsonc` with D1 database binding
+- [ ] Setup Tailwind v4 with `@tailwindcss/vite` plugin
+- [ ] Initialize shadcn/ui with dark mode support
+- [ ] Create basic "Hello World" component
+- [ ] Test local dev server
+- [ ] Test deployment to Cloudflare
+
+### Verification Criteria
+- [ ] `npm run dev` starts without errors
+- [ ] `localhost:5173` shows React app with Tailwind styling
+- [ ] Dark/light mode toggle works
+- [ ] `npm run build` succeeds
+- [ ] `npx wrangler deploy` deploys successfully
+- [ ] Deployed URL shows working app
+
+### Exit Criteria
+Working development environment with successful test deployment. Can iterate on code locally and deploy to Cloudflare.
+
+---
+
+## Phase 2: Database Schema
+**Type**: Database
+**Estimated**: 2 hours
+**Files**: `migrations/0001_initial.sql`, `src/lib/db-types.ts`
+
+### Tasks
+- [ ] Create D1 database using `npx wrangler d1 create task-manager-db`
+- [ ] Design `tasks` table schema
+- [ ] Write migration SQL file
+- [ ] Apply migration to local database
+- [ ] Create TypeScript types for database schema
+- [ ] Write test query in Worker to verify database connection
+
+### Verification Criteria
+- [ ] Migration runs without errors
+- [ ] Can insert test task
+- [ ] Can query tasks from Worker
+- [ ] TypeScript types match database schema
+
+### Exit Criteria
+Database schema deployed locally, can perform CRUD operations from Worker.
+
+---
+
+## Phase 3: Tasks API
+**Type**: API
+**Estimated**: 4 hours
+**Files**: `src/routes/tasks.ts`, `src/lib/schemas.ts`, `src/middleware/cors.ts`
+
+### Tasks
+- [ ] Define Zod schema for task validation
+- [ ] Create CORS middleware
+- [ ] Implement GET /api/tasks (list all tasks)
+- [ ] Implement POST /api/tasks (create task)
+- [ ] Implement PATCH /api/tasks/:id (update task)
+- [ ] Implement DELETE /api/tasks/:id (delete task)
+- [ ] Add error handling middleware
+- [ ] Test all endpoints manually with curl
+
+### Verification Criteria
+- [ ] GET /api/tasks returns empty array initially
+- [ ] POST /api/tasks with valid data returns 201
+- [ ] POST /api/tasks with invalid data returns 400
+- [ ] PATCH /api/tasks/:id updates task and returns 200
+- [ ] DELETE /api/tasks/:id removes task and returns 204
+- [ ] Invalid task ID returns 404
+- [ ] CORS headers present in responses
+
+### Exit Criteria
+All CRUD endpoints working, tested with curl, proper error handling.
+
+---
+
+## Phase 4: Task List UI
+**Type**: UI
+**Estimated**: 3-4 hours
+**Files**: `src/components/TaskList.tsx`, `src/components/TaskCard.tsx`, `src/lib/api.ts`
+
+### Tasks
+- [ ] Setup TanStack Query for data fetching
+- [ ] Create API client functions (fetch tasks, create, update, delete)
+- [ ] Build `TaskList` component with loading/error states
+- [ ] Build `TaskCard` component to display individual tasks
+- [ ] Add "Mark complete" toggle functionality
+- [ ] Add delete button with confirmation
+- [ ] Style with Tailwind and shadcn/ui components
+
+### Verification Criteria
+- [ ] Task list displays fetched tasks
+- [ ] Loading skeleton shows while fetching
+- [ ] Error message shows if API fails
+- [ ] Can toggle task completion (optimistic update)
+- [ ] Can delete task (shows confirmation dialog)
+- [ ] UI updates immediately after mutations
+
+### Exit Criteria
+Task list displays correctly with all CRUD operations working from UI.
+
+---
+
+## Phase 5: Task Creation Form
+**Type**: UI
+**Estimated**: 2-3 hours
+**Files**: `src/components/TaskForm.tsx`, `src/components/CreateTaskDialog.tsx`
+
+### Tasks
+- [ ] Install React Hook Form and Zod resolver
+- [ ] Create `TaskForm` component with title and description fields
+- [ ] Add client-side validation (Zod schema)
+- [ ] Build `CreateTaskDialog` modal wrapper
+- [ ] Implement form submission with TanStack Query mutation
+- [ ] Add loading state during submission
+- [ ] Show success/error feedback
+- [ ] Clear form and close dialog on success
+
+### Verification Criteria
+- [ ] Form validates empty title (shows error)
+- [ ] Form validates title length (max 100 chars)
+- [ ] Successful submission creates task in database
+- [ ] Task appears in list immediately (optimistic update)
+- [ ] Form resets after successful submission
+- [ ] Dialog closes after successful submission
+- [ ] Error message shows if submission fails
+
+### Exit Criteria
+Can create tasks via form, validation works, UX is smooth.
+
+---
+
+## Notes
+
+### Testing Strategy
+Testing built into each phase via verification criteria. No separate testing phase needed for this simple project.
+
+### Deployment Strategy
+Deploy after each phase to test in production environment:
+```bash
+npm run build && npx wrangler deploy
+```
+
+### Context Management
+Phases sized to complete in single session including implementation, verification, and expected debugging.
+
+---
+
+## DATABASE_SCHEMA.md
+
+# Database Schema: Simple Task Manager
+
+**Database**: Cloudflare D1 (SQLite)
+**Migrations**: `migrations/` directory
+**ORM**: None (raw SQL)
+
+---
+
+## Tables
+
+### `tasks`
+**Purpose**: Store tasks (public, no user association)
+
+| Column | Type | Constraints | Default | Notes |
+|--------|------|-------------|---------|-------|
+| `id` | INTEGER | PRIMARY KEY | AUTO | Auto-increment |
+| `title` | TEXT | NOT NULL | - | Task title (max 100 chars) |
+| `description` | TEXT | NULL | - | Task description (optional) |
+| `completed` | INTEGER | NOT NULL | 0 | 0 = incomplete, 1 = complete |
+| `created_at` | INTEGER | NOT NULL | - | Unix timestamp |
+| `updated_at` | INTEGER | NOT NULL | - | Unix timestamp |
+
+**Indexes**:
+- `idx_tasks_created_at` on `created_at` (for sorting by date)
+- `idx_tasks_completed` on `completed` (for filtering complete/incomplete)
+
+---
+
+## Migrations
+
+### Migration 0001: Initial Schema
+**File**: `migrations/0001_initial_schema.sql`
+**Purpose**: Create tasks table
+
+```sql
+CREATE TABLE tasks (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ title TEXT NOT NULL,
+ description TEXT,
+ completed INTEGER NOT NULL DEFAULT 0,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+);
+
+CREATE INDEX idx_tasks_created_at ON tasks(created_at);
+CREATE INDEX idx_tasks_completed ON tasks(completed);
+```
+
+**Run**:
+```bash
+npx wrangler d1 execute task-manager-db --local --file=migrations/0001_initial_schema.sql
+npx wrangler d1 execute task-manager-db --remote --file=migrations/0001_initial_schema.sql
+```
+
+---
+
+## Seed Data
+
+**File**: `migrations/seed.sql`
+
+```sql
+INSERT INTO tasks (title, description, completed, created_at, updated_at)
+VALUES
+ ('Build database schema', 'Create tasks table with migrations', 1, strftime('%s', 'now'), strftime('%s', 'now')),
+ ('Create API endpoints', 'Implement CRUD operations for tasks', 1, strftime('%s', 'now'), strftime('%s', 'now')),
+ ('Build UI components', 'Task list and creation form', 0, strftime('%s', 'now'), strftime('%s', 'now'));
+```
+
+---
+
+## API_ENDPOINTS.md
+
+# API Endpoints: Simple Task Manager
+
+**Base URL**: `/api`
+**Framework**: Hono
+**Auth**: None (public API)
+**Validation**: Zod schemas
+
+---
+
+## Tasks
+
+### GET `/api/tasks`
+**Purpose**: List all tasks
+
+**Query Parameters**:
+- `completed` (optional): Filter by completion status (`true` or `false`)
+
+**Response 200**:
+```json
+{
+ "data": [
+ {
+ "id": 1,
+ "title": "Sample Task",
+ "description": "Task description",
+ "completed": false,
+ "createdAt": 1234567890,
+ "updatedAt": 1234567890
+ }
+ ]
+}
+```
+
+---
+
+### POST `/api/tasks`
+**Purpose**: Create a new task
+
+**Request Body**:
+```json
+{
+ "title": "New Task",
+ "description": "Optional description"
+}
+```
+
+**Validation**:
+```typescript
+z.object({
+ title: z.string().min(1).max(100),
+ description: z.string().optional()
+})
+```
+
+**Response 201**: Created task object
+
+**Response 400**: Validation error
+
+---
+
+### PATCH `/api/tasks/:id`
+**Purpose**: Update a task
+
+**Request Body**:
+```json
+{
+ "title": "Updated title",
+ "description": "Updated description",
+ "completed": true
+}
+```
+
+**Response 200**: Updated task object
+
+**Response 404**: Task not found
+
+---
+
+### DELETE `/api/tasks/:id`
+**Purpose**: Delete a task
+
+**Response 204**: No content (success)
+
+**Response 404**: Task not found
+
+---
+
+**Note**: This is a simplified example for a public task manager. For a production app with user accounts, see the `auth-web-app.md` example.
diff --git a/skills/project-planning/templates/AGENTS_CONFIG.md b/skills/project-planning/templates/AGENTS_CONFIG.md
new file mode 100644
index 00000000..c1fac33a
--- /dev/null
+++ b/skills/project-planning/templates/AGENTS_CONFIG.md
@@ -0,0 +1,567 @@
+# AI Agents Configuration: [Project Name]
+
+**AI Provider**: [OpenAI / Claude / Gemini / Cloudflare AI]
+**Framework**: [Vercel AI SDK / Custom / Cloudflare Workers AI]
+**Agent Architecture**: [Single agent / Multi-agent / Agentic workflows]
+**Last Updated**: [Date]
+
+---
+
+## Overview
+
+This document defines AI agents, their capabilities, tools, and workflows for this project.
+
+**Agent Philosophy**:
+- **Purpose-built agents** - Each agent has a specific, well-defined role
+- **Tool-equipped** - Agents have access to functions they need
+- **Conversational** - Agents can ask clarifying questions
+- **Stateful when needed** - Use Durable Objects for long-running conversations
+- **Fail gracefully** - Always have fallback responses
+
+---
+
+## AI Provider Configuration
+
+### Primary Provider: [Provider Name]
+
+**Model**: [e.g., gpt-5, claude-sonnet-4-5, gemini-2.5-pro]
+**API Key**: Stored in environment variable `[KEY_NAME]`
+**Base URL**: [API endpoint]
+
+**Configuration**:
+```typescript
+// src/lib/ai-config.ts
+export const aiConfig = {
+ provider: '[provider]',
+ model: '[model-name]',
+ apiKey: process.env.[KEY_NAME],
+ temperature: 0.7,
+ maxTokens: 2000,
+ topP: 1.0
+}
+```
+
+**Fallback Provider** (optional): [Secondary provider if primary fails]
+
+---
+
+## Agents
+
+### Agent 1: [Agent Name]
+
+**Purpose**: [What this agent does]
+**Model**: [Specific model if different from default]
+**Context Window**: [Token limit for this agent]
+
+**Capabilities**:
+- [Capability 1]
+- [Capability 2]
+- [Capability 3]
+
+**System Prompt**:
+```
+You are [agent role]. Your goal is to [agent purpose].
+
+Guidelines:
+- [Guideline 1]
+- [Guideline 2]
+- [Guideline 3]
+
+When you need information you don't have:
+- Use available tools
+- Ask the user clarifying questions
+- Provide your best answer with caveats
+
+Response format:
+- Be concise and actionable
+- Use markdown for formatting
+- Include code examples when helpful
+```
+
+**Available Tools**:
+- `[tool_name]` - [Description]
+- `[tool_name]` - [Description]
+
+**Example Conversation**:
+```
+User: [Example input]
+Agent: [Example response]
+
+User: [Follow-up]
+Agent: [Agent uses tool and responds]
+```
+
+**Endpoint**: `POST /api/agents/[agent-name]`
+
+**Request**:
+```json
+{
+ "message": "User message",
+ "conversationId": "optional-conversation-id",
+ "context": { "optional": "context" }
+}
+```
+
+**Response** (streaming):
+```
+data: {"type":"text","content":"Agent response..."}
+data: {"type":"tool_call","name":"search","args":{"query":"..."}}
+data: {"type":"tool_result","result":{...}}
+data: {"type":"done"}
+```
+
+---
+
+### Agent 2: [Agent Name]
+
+**Purpose**: [What this agent does]
+
+[... repeat structure from Agent 1 ...]
+
+---
+
+## Tools (Functions)
+
+AI agents can call these functions to perform actions or retrieve information.
+
+### Tool: `[tool_name]`
+
+**Purpose**: [What this tool does]
+
+**Parameters**:
+```typescript
+{
+ param1: string, // Description
+ param2: number, // Description
+ param3?: boolean // Optional description
+}
+```
+
+**Implementation**:
+```typescript
+// src/lib/ai-tools.ts
+export async function [tool_name](params: ToolParams, context: Context) {
+ // Tool logic
+ const result = await performAction(params)
+ return result
+}
+```
+
+**Example**:
+```typescript
+// Agent calls tool
+const result = await [tool_name]({
+ param1: "value",
+ param2: 42
+})
+
+// Tool returns
+{
+ success: true,
+ data: { /* result */ }
+}
+```
+
+**Failure Handling**: [How tool handles errors]
+
+---
+
+### Tool: `search_database`
+
+**Purpose**: Search the database for user-specific information
+
+**Parameters**:
+```typescript
+{
+ query: string, // Natural language search query
+ table: string, // Which table to search
+ limit?: number // Max results (default 5)
+}
+```
+
+**Implementation**:
+```typescript
+export async function search_database(
+ { query, table, limit = 5 }: SearchParams,
+ context: Context
+) {
+ const userId = context.get('userId')
+
+ // Convert natural language to SQL (simplified example)
+ const results = await context.env.DB.prepare(
+ `SELECT * FROM ${table} WHERE user_id = ? LIMIT ?`
+ ).bind(userId, limit).all()
+
+ return {
+ success: true,
+ data: results.results
+ }
+}
+```
+
+---
+
+## Agent Workflows
+
+### Workflow: [Workflow Name]
+
+**Purpose**: [What this workflow accomplishes]
+
+**Agents Involved**:
+1. [Agent 1] - [Role in workflow]
+2. [Agent 2] - [Role in workflow]
+
+**Flow**:
+```
+1. User submits [input]
+ ↓
+2. [Agent 1] analyzes input
+ ↓
+3. [Agent 1] calls tool: [tool_name]
+ ↓
+4. Tool returns data
+ ↓
+5. [Agent 1] generates response
+ ↓
+6. If needed: Hand off to [Agent 2]
+ ↓
+7. [Agent 2] completes task
+ ↓
+8. Return final result to user
+```
+
+**Example**:
+```
+User: "Find all high-priority tasks and create a summary report"
+
+[Planner Agent] → Calls search_database(query="high priority tasks")
+ → Receives 5 tasks
+ → Hands off to [Writer Agent] with task data
+
+[Writer Agent] → Generates formatted report
+ → Returns markdown report to user
+```
+
+---
+
+## Conversation State
+
+### Stateless Agents (Default)
+
+**When to use**: Single-turn interactions, no context needed
+
+**Implementation**: Each request is independent
+
+**Example**: Simple Q&A, content generation
+
+---
+
+### Stateful Agents (Durable Objects)
+
+**When to use**: Multi-turn conversations, context retention
+
+**Implementation**: Store conversation history in Durable Object
+
+**Setup**:
+```typescript
+// src/durable-objects/conversation.ts
+export class Conversation implements DurableObject {
+ private messages: Message[] = []
+
+ async fetch(request: Request) {
+ const { message } = await request.json()
+
+ // Add user message to history
+ this.messages.push({ role: 'user', content: message })
+
+ // Call AI with full conversation history
+ const response = await callAI({
+ messages: this.messages,
+ tools: availableTools
+ })
+
+ // Add assistant response to history
+ this.messages.push({ role: 'assistant', content: response })
+
+ return new Response(JSON.stringify({ response }))
+ }
+}
+```
+
+**Wrangler Config**:
+```jsonc
+{
+ "durable_objects": {
+ "bindings": [
+ {
+ "name": "CONVERSATIONS",
+ "class_name": "Conversation",
+ "script_name": "app"
+ }
+ ]
+ }
+}
+```
+
+**Usage**:
+```typescript
+// Create/get conversation
+const conversationId = crypto.randomUUID()
+const durableObjectId = env.CONVERSATIONS.idFromName(conversationId)
+const stub = env.CONVERSATIONS.get(durableObjectId)
+
+// Send message to conversation
+const response = await stub.fetch(request)
+```
+
+---
+
+## Streaming Responses
+
+**Why stream**: Better UX, appears faster, shows progress
+
+**Implementation** (Server-Sent Events):
+```typescript
+// src/routes/agents.ts
+app.post('/api/agents/:agentName', async (c) => {
+ const { message } = await c.req.json()
+
+ const stream = await streamAIResponse({
+ message,
+ agent: c.req.param('agentName')
+ })
+
+ return c.newResponse(stream, {
+ headers: {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive'
+ }
+ })
+})
+```
+
+**Client** (Vercel AI SDK):
+```typescript
+import { useChat } from '@ai-sdk/react'
+
+export function ChatInterface() {
+ const { messages, input, handleInputChange, handleSubmit } = useChat({
+ api: '/api/agents/chat'
+ })
+
+ return (
+ <div>
+ {messages.map(m => (
+ <div key={m.id}>{m.content}</div>
+ ))}
+ <form onSubmit={handleSubmit}>
+ <input value={input} onChange={handleInputChange} />
+ </form>
+ </div>
+ )
+}
+```
+
+---
+
+## Prompt Engineering
+
+### System Prompt Best Practices
+
+**Structure**:
+1. **Role definition** - "You are a [role]"
+2. **Capabilities** - What the agent can do
+3. **Constraints** - What the agent cannot do
+4. **Tone/style** - How the agent should respond
+5. **Output format** - Markdown, JSON, etc
+
+**Example**:
+```
+You are a helpful task management assistant.
+
+Your capabilities:
+- Search user's tasks
+- Create, update, delete tasks
+- Generate task summaries and reports
+- Set reminders and priorities
+
+Your constraints:
+- Never access other users' data
+- Always confirm before deleting tasks
+- Ask for clarification if user intent is unclear
+
+Response style:
+- Be concise and actionable
+- Use bullet points for lists
+- Include task IDs for reference
+
+Output format:
+- Use markdown formatting
+- Bold important information
+- Use code blocks for task IDs
+```
+
+---
+
+## Token Management
+
+**Cost Optimization**:
+- Use smaller models for simple tasks (gpt-5-mini, claude-haiku-4-5)
+- Use larger models only when needed (gpt-5, claude-sonnet-4-5)
+- Limit conversation history (keep last N messages)
+- Summarize long conversations to reduce tokens
+
+**Token Budgets**:
+```typescript
+const TOKEN_BUDGETS = {
+ 'simple-qa': {
+ model: 'gpt-5-mini',
+ maxInputTokens: 500,
+ maxOutputTokens: 500
+ },
+ 'complex-analysis': {
+ model: 'gpt-5',
+ maxInputTokens: 4000,
+ maxOutputTokens: 2000
+ }
+}
+```
+
+---
+
+## Error Handling
+
+### AI Provider Failures
+
+**Handle**:
+- Rate limits (retry with backoff)
+- API errors (fallback provider or error message)
+- Timeout (abort and inform user)
+
+**Example**:
+```typescript
+try {
+ const response = await callAI({ message, tools })
+ return response
+} catch (error) {
+ if (error.code === 'rate_limit') {
+ // Retry with exponential backoff
+ await sleep(2000)
+ return await callAI({ message, tools })
+ } else {
+ // Return graceful error
+ return {
+ error: true,
+ message: "I'm having trouble processing that right now. Please try again."
+ }
+ }
+}
+```
+
+---
+
+## Testing AI Agents
+
+### Unit Tests (Tool Functions)
+
+Test each tool independently:
+```typescript
+describe('search_database tool', () => {
+ it('returns user-specific results', async () => {
+ const result = await search_database({
+ query: 'high priority',
+ table: 'tasks'
+ }, mockContext)
+
+ expect(result.success).toBe(true)
+ expect(result.data.length).toBeGreaterThan(0)
+ })
+})
+```
+
+---
+
+### Integration Tests (Agent Endpoints)
+
+Test agent responses:
+```typescript
+describe('POST /api/agents/assistant', () => {
+ it('responds to simple query', async () => {
+ const res = await app.request('/api/agents/assistant', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': 'Bearer token'
+ },
+ body: JSON.stringify({
+ message: 'List my tasks'
+ })
+ })
+
+ expect(res.status).toBe(200)
+ const data = await res.json()
+ expect(data.response).toContain('task')
+ })
+})
+```
+
+---
+
+### Manual Testing
+
+**Test Prompts**:
+- Simple queries: "What tasks do I have?"
+- Tool usage: "Create a new task called 'Review PR'"
+- Edge cases: "Delete all my tasks" (should confirm first)
+- Unclear input: "Do the thing" (should ask for clarification)
+- Multi-step: "Find high-priority tasks and summarize them"
+
+---
+
+## Monitoring and Observability
+
+**Metrics to track**:
+- Agent invocations per day
+- Average response time
+- Token usage (input + output)
+- Tool call frequency
+- Error rate
+
+**Logging**:
+```typescript
+console.log('[Agent]', {
+ agent: 'assistant',
+ userId: context.get('userId'),
+ message: message.substring(0, 50),
+ tokensUsed: response.usage.total_tokens,
+ toolsCalled: toolCalls.map(t => t.name),
+ responseTime: Date.now() - startTime
+})
+```
+
+**Cloudflare Workers Analytics Engine** (optional):
+```typescript
+await env.ANALYTICS.writeDataPoint({
+ indexes: [userId],
+ doubles: [responseTime, tokensUsed],
+ blobs: [agentName, toolsCalled]
+})
+```
+
+---
+
+## Future Agent Enhancements
+
+- [ ] Add [agent name] for [purpose]
+- [ ] Integrate [tool name] for [capability]
+- [ ] Implement [workflow name]
+- [ ] Add voice input/output
+- [ ] Multi-modal support (images, files)
+
+---
+
+## Revision History
+
+**v1.0** ([Date]): Initial agent configuration
+**v1.1** ([Date]): [Changes made]
diff --git a/skills/project-planning/templates/API_ENDPOINTS.md b/skills/project-planning/templates/API_ENDPOINTS.md
new file mode 100644
index 00000000..407b6421
--- /dev/null
+++ b/skills/project-planning/templates/API_ENDPOINTS.md
@@ -0,0 +1,438 @@
+# API Endpoints: [Project Name]
+
+**Base URL**: `/api`
+**Framework**: Hono (Cloudflare Workers)
+**Auth**: Clerk JWT with custom template
+**Validation**: Zod schemas
+**Last Updated**: [Date]
+
+---
+
+## Overview
+
+All API endpoints follow RESTful conventions and return JSON responses.
+
+**Base URL**:
+- Local dev: `http://localhost:5173/api`
+- Production: `https://[your-domain].workers.dev/api`
+
+**Authentication**: Most endpoints require a valid Clerk JWT in the `Authorization` header:
+```
+Authorization: Bearer <jwt_token>
+```
+
+**Content Type**: All requests and responses use `application/json`
+
+---
+
+## Response Format
+
+### Success Response
+```json
+{
+ "data": { /* response data */ },
+ "meta": { /* optional metadata like pagination */ }
+}
+```
+
+### Error Response
+```json
+{
+ "error": "Human-readable error message",
+ "code": "ERROR_CODE",
+ "details": { /* optional additional context */ }
+}
+```
+
+**Standard Error Codes**:
+- `VALIDATION_ERROR` (400): Request body failed validation
+- `UNAUTHORIZED` (401): Missing or invalid JWT
+- `FORBIDDEN` (403): Valid JWT but insufficient permissions
+- `NOT_FOUND` (404): Resource doesn't exist
+- `INTERNAL_ERROR` (500): Server error
+
+---
+
+## Authentication Endpoints
+
+### POST `/api/auth/verify`
+**Purpose**: Verify JWT token validity
+**Auth**: None (public endpoint)
+
+**Request Body**:
+```json
+{
+ "token": "string"
+}
+```
+
+**Response 200**:
+```json
+{
+ "data": {
+ "valid": true,
+ "email": "[email protected]",
+ "userId": "clerk_user_123"
+ }
+}
+```
+
+**Response 401**:
+```json
+{
+ "error": "Invalid or expired token",
+ "code": "UNAUTHORIZED"
+}
+```
+
+**Validation**:
+```typescript
+const schema = z.object({
+ token: z.string().min(1)
+})
+```
+
+---
+
+### GET `/api/auth/me`
+**Purpose**: Get current authenticated user's profile
+**Auth**: Required
+
+**Response 200**:
+```json
+{
+ "data": {
+ "id": 1,
+ "email": "[email protected]",
+ "displayName": "John Doe",
+ "avatarUrl": "https://r2.../avatar.jpg",
+ "createdAt": 1234567890
+ }
+}
+```
+
+**Response 401**:
+```json
+{
+ "error": "Not authenticated",
+ "code": "UNAUTHORIZED"
+}
+```
+
+---
+
+## [Resource] Endpoints
+
+### GET `/api/[resource]`
+**Purpose**: List all [resources] for authenticated user
+**Auth**: Required
+
+**Query Parameters**:
+- `limit` (optional): Number of items to return (default: 50, max: 100)
+- `offset` (optional): Number of items to skip (default: 0)
+- `sort` (optional): Sort field (default: `created_at`)
+- `order` (optional): Sort order - `asc` or `desc` (default: `desc`)
+
+**Example**: `/api/[resource]?limit=20&offset=0&sort=created_at&order=desc`
+
+**Response 200**:
+```json
+{
+ "data": [
+ {
+ "id": 1,
+ "userId": 1,
+ "[field]": "value",
+ "createdAt": 1234567890,
+ "updatedAt": 1234567890
+ }
+ ],
+ "meta": {
+ "total": 42,
+ "limit": 20,
+ "offset": 0
+ }
+}
+```
+
+**Response 401**: Not authenticated
+
+---
+
+### GET `/api/[resource]/:id`
+**Purpose**: Get a specific [resource] by ID
+**Auth**: Required
+
+**Response 200**:
+```json
+{
+ "data": {
+ "id": 1,
+ "userId": 1,
+ "[field]": "value",
+ "createdAt": 1234567890,
+ "updatedAt": 1234567890
+ }
+}
+```
+
+**Response 404**:
+```json
+{
+ "error": "[Resource] not found",
+ "code": "NOT_FOUND"
+}
+```
+
+**Response 403**: User doesn't own this resource
+
+---
+
+### POST `/api/[resource]`
+**Purpose**: Create a new [resource]
+**Auth**: Required
+
+**Request Body**:
+```json
+{
+ "[field1]": "value",
+ "[field2]": "value"
+}
+```
+
+**Validation**:
+```typescript
+const schema = z.object({
+ [field1]: z.string().min(1).max(100),
+ [field2]: z.string().optional(),
+ // ... other fields
+})
+```
+
+**Response 201**:
+```json
+{
+ "data": {
+ "id": 42,
+ "userId": 1,
+ "[field1]": "value",
+ "[field2]": "value",
+ "createdAt": 1234567890,
+ "updatedAt": 1234567890
+ }
+}
+```
+
+**Response 400** (validation error):
+```json
+{
+ "error": "Validation failed",
+ "code": "VALIDATION_ERROR",
+ "details": {
+ "field1": "Must be at least 1 character"
+ }
+}
+```
+
+---
+
+### PATCH `/api/[resource]/:id`
+**Purpose**: Update an existing [resource]
+**Auth**: Required
+
+**Request Body** (all fields optional):
+```json
+{
+ "[field1]": "new value",
+ "[field2]": "new value"
+}
+```
+
+**Validation**:
+```typescript
+const schema = z.object({
+ [field1]: z.string().min(1).max(100).optional(),
+ [field2]: z.string().optional(),
+}).refine(data => Object.keys(data).length > 0, {
+ message: "At least one field must be provided"
+})
+```
+
+**Response 200**:
+```json
+{
+ "data": {
+ "id": 42,
+ "userId": 1,
+ "[field1]": "new value",
+ "[field2]": "new value",
+ "createdAt": 1234567890,
+ "updatedAt": 1234567999
+ }
+}
+```
+
+**Response 404**: Resource not found
+**Response 403**: User doesn't own this resource
+
+---
+
+### DELETE `/api/[resource]/:id`
+**Purpose**: Delete a [resource]
+**Auth**: Required
+
+**Response 204**: No content (success)
+
+**Response 404**: Resource not found
+**Response 403**: User doesn't own this resource
+
+---
+
+## Middleware
+
+### CORS Middleware
+**Applies to**: All routes
+**Headers**:
+```
+Access-Control-Allow-Origin: https://[your-domain].com
+Access-Control-Allow-Methods: GET, POST, PATCH, DELETE, OPTIONS
+Access-Control-Allow-Headers: Content-Type, Authorization
+Access-Control-Max-Age: 86400
+```
+
+### Auth Middleware
+**Applies to**: All routes except public endpoints
+**Validates**: Clerk JWT in Authorization header
+**Adds to context**: `c.get('userId')`, `c.get('email')`
+**Rejects**: Missing, invalid, or expired tokens (401)
+
+### Error Handler Middleware
+**Applies to**: All routes
+**Catches**: Unhandled errors
+**Returns**: 500 with sanitized error message
+**Logs**: Full error details for debugging
+
+### Validation Middleware
+**Applies to**: POST and PATCH routes
+**Validates**: Request body against Zod schema
+**Returns**: 400 with field-specific errors if validation fails
+
+---
+
+## Rate Limiting
+
+[Optional: Define rate limits if applicable]
+
+**Default Limits**:
+- Anonymous requests: 10 requests per minute
+- Authenticated requests: 100 requests per minute
+
+**Headers**:
+```
+X-RateLimit-Limit: 100
+X-RateLimit-Remaining: 95
+X-RateLimit-Reset: 1234567890
+```
+
+---
+
+## Webhook Endpoints
+
+[Optional: Document webhooks if applicable]
+
+### POST `/api/webhooks/[service]`
+**Purpose**: Handle webhook from [third-party service]
+**Auth**: Webhook signature verification
+**Source**: [Service name]
+
+**Expected Payload**:
+```json
+{
+ "event": "event_type",
+ "data": { /* event data */ }
+}
+```
+
+**Response 200**: Webhook processed successfully
+**Response 400**: Invalid signature or payload
+
+---
+
+## Testing
+
+### Manual Testing with curl
+
+**Create resource**:
+```bash
+curl -X POST http://localhost:5173/api/[resource] \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer YOUR_JWT_TOKEN" \
+ -d '{"field1": "value"}'
+```
+
+**Get resource**:
+```bash
+curl http://localhost:5173/api/[resource]/1 \
+ -H "Authorization: Bearer YOUR_JWT_TOKEN"
+```
+
+**Update resource**:
+```bash
+curl -X PATCH http://localhost:5173/api/[resource]/1 \
+ -H "Content-Type: application/json" \
+ -H "Authorization: Bearer YOUR_JWT_TOKEN" \
+ -d '{"field1": "new value"}'
+```
+
+**Delete resource**:
+```bash
+curl -X DELETE http://localhost:5173/api/[resource]/1 \
+ -H "Authorization: Bearer YOUR_JWT_TOKEN"
+```
+
+### Getting a Test JWT
+
+Use Clerk's development mode or sign in to get a token:
+```javascript
+// In browser console after logging in
+const token = await window.Clerk.session.getToken();
+console.log(token);
+```
+
+---
+
+## Deployment
+
+**Wrangler Configuration**: Ensure `wrangler.jsonc` includes necessary bindings:
+```jsonc
+{
+ "vars": {
+ "CLERK_PUBLISHABLE_KEY": "pk_test_..."
+ },
+ "d1_databases": [
+ {
+ "binding": "DB",
+ "database_name": "[your-database]",
+ "database_id": "[database-id]"
+ }
+ ]
+}
+```
+
+**Environment Variables** (set via dashboard or CLI):
+- `CLERK_SECRET_KEY`: Secret key for JWT verification
+
+---
+
+## Future Endpoints
+
+Planned endpoints to implement:
+- [ ] `/api/[feature]` - [Description]
+- [ ] `/api/[other-feature]` - [Description]
+
+---
+
+## Revision History
+
+**v1.0** ([Date]): Initial API design
+**v1.1** ([Date]): [Changes made]
diff --git a/skills/project-planning/templates/ARCHITECTURE.md b/skills/project-planning/templates/ARCHITECTURE.md
new file mode 100644
index 00000000..35baa715
--- /dev/null
+++ b/skills/project-planning/templates/ARCHITECTURE.md
@@ -0,0 +1,495 @@
+# Architecture: [Project Name]
+
+**Deployment Platform**: Cloudflare Workers
+**Frontend**: Vite + React + Tailwind v4 + shadcn/ui
+**Backend**: Hono (API routes on same Worker)
+**Database**: Cloudflare D1 (SQLite)
+**Storage**: Cloudflare R2 (object storage)
+**Auth**: Clerk (JWT-based)
+**Last Updated**: [Date]
+
+---
+
+## System Overview
+
+```
+┌──────────────────────────────────────────────────────────────┐
+│ Browser │
+│ ┌────────────────────────────────────────────────────────┐ │
+│ │ React App (Vite build) │ │
+│ │ - Components (shadcn/ui + custom) │ │
+│ │ - State (TanStack Query + Zustand) │ │
+│ │ - Forms (React Hook Form + Zod) │ │
+│ └───────────┬────────────────────────────────────────────┘ │
+└──────────────┼───────────────────────────────────────────────┘
+ │ HTTPS
+ ↓
+┌──────────────────────────────────────────────────────────────┐
+│ Cloudflare Worker (Edge Runtime) │
+│ ┌────────────────────────┐ ┌──────────────────────────┐ │
+│ │ Static Assets │ │ API Routes (Hono) │ │
+│ │ (Vite build output) │ │ /api/* │ │
+│ │ Served directly │ │ │ │
+│ │ │ │ Middleware: │ │
+│ │ / → index.html │ │ - CORS │ │
+│ │ /assets/* │ │ - Auth (JWT verify) │ │
+│ │ │ │ - Error handling │ │
+│ └────────────────────────┘ │ - Validation (Zod) │ │
+│ └───────┬──────────────────┘ │
+│ │ │
+└────────────────────────────────────────┼─────────────────────┘
+ │
+ ┌──────────────────────────────┼──────────────────────────┐
+ │ │ │
+ ↓ ↓ ↓
+┌───────────────────┐ ┌───────────────────┐ ┌──────────────────┐
+│ Cloudflare D1 │ │ Cloudflare R2 │ │ Clerk Auth │
+│ (Database) │ │ (File Storage) │ │ (External) │
+│ │ │ │ │ │
+│ - users │ │ - avatars/ │ │ - User accounts │
+│ - [other tables] │ │ - uploads/ │ │ - JWT tokens │
+│ │ │ │ │ - Social auth │
+└───────────────────┘ └───────────────────┘ └──────────────────┘
+```
+
+---
+
+## Components Breakdown
+
+### Frontend (Browser)
+
+**Technology**: React 19 + Vite + Tailwind v4
+
+**Responsibilities**:
+- Render UI components
+- Handle user interactions
+- Client-side validation (Zod)
+- Optimistic updates
+- State management
+- Routing (React Router or TanStack Router)
+
+**Key Libraries**:
+- `@clerk/clerk-react` - Authentication UI and hooks
+- `@tanstack/react-query` - Server state management (caching, refetching)
+- `zustand` - Client state management (UI state, preferences)
+- `react-hook-form` - Form state and validation
+- `zod` - Schema validation
+- `shadcn/ui` - UI component library (Radix UI primitives)
+
+**State Architecture**:
+```
+Server State (TanStack Query)
+ ↓
+ Cached API responses, auto-refetch, background sync
+ Examples: user data, tasks, analytics
+
+Client State (Zustand)
+ ↓
+ UI state, form state, user preferences
+ Examples: sidebar open/closed, theme, filters
+```
+
+---
+
+### Backend (Cloudflare Worker)
+
+**Technology**: Hono web framework on Cloudflare Workers
+
+**Responsibilities**:
+- Serve static assets (Vite build)
+- API request routing
+- Authentication/authorization
+- Server-side validation
+- Business logic
+- Database operations
+- Third-party API integration
+
+**Route Structure**:
+```typescript
+app.use('*', cors())
+app.use('/api/*', authMiddleware)
+
+// Static assets
+app.get('/', serveStatic({ path: './dist/index.html' }))
+app.get('/assets/*', serveStatic({ root: './dist' }))
+
+// API routes
+app.route('/api/auth', authRoutes)
+app.route('/api/[resource]', [resource]Routes)
+// ... more routes
+
+app.onError(errorHandler)
+```
+
+**Middleware Pipeline**:
+```
+Request
+ ↓
+CORS Middleware (allow frontend origin)
+ ↓
+Auth Middleware (verify JWT for /api/* routes)
+ ↓
+Route Handler
+ ↓
+Validation Middleware (Zod schema)
+ ↓
+Business Logic
+ ↓
+Response
+ ↓
+Error Handler (catch unhandled errors)
+```
+
+---
+
+### Database (Cloudflare D1)
+
+**Technology**: SQLite (via D1)
+
+**Access Pattern**: SQL queries via Worker bindings
+
+**Schema**: See `DATABASE_SCHEMA.md` for full details
+
+**Usage**:
+```typescript
+// In Worker
+const result = await c.env.DB.prepare(
+ 'SELECT * FROM users WHERE id = ?'
+).bind(userId).first()
+```
+
+**Migrations**: Manual SQL files in `migrations/`
+
+**Backups**: Export via `npx wrangler d1 export`
+
+---
+
+### Storage (Cloudflare R2)
+
+**Technology**: S3-compatible object storage
+
+**Use Cases**:
+- User avatars
+- File uploads
+- Generated assets
+
+**Access Pattern**: Direct upload from Worker, signed URLs for browser access
+
+**Bucket Structure**:
+```
+[bucket-name]/
+├── avatars/
+│ ├── user-1.jpg
+│ └── user-2.png
+├── uploads/
+│ └── [user-id]/
+│ └── document.pdf
+└── generated/
+ └── export-123.csv
+```
+
+---
+
+### Authentication (Clerk)
+
+**Technology**: Clerk (external SaaS)
+
+**Flow**:
+```
+1. User clicks "Sign In"
+2. Clerk modal opens (handled by @clerk/clerk-react)
+3. User authenticates (email/password or social)
+4. Clerk returns JWT
+5. Frontend includes JWT in API requests (Authorization: Bearer ...)
+6. Worker verifies JWT using Clerk secret key
+7. Worker extracts user email/ID from JWT
+8. Worker processes request with user context
+```
+
+**JWT Custom Template** (configured in Clerk):
+```json
+{
+ "email": "{{user.primary_email_address}}",
+ "userId": "{{user.id}}",
+ "metadata": {
+ "displayName": "{{user.first_name}} {{user.last_name}}"
+ }
+}
+```
+
+**Verification** (in Worker):
+```typescript
+import { verifyToken } from '@clerk/backend'
+
+const token = c.req.header('Authorization')?.replace('Bearer ', '')
+const verified = await verifyToken(token, {
+ secretKey: c.env.CLERK_SECRET_KEY
+})
+```
+
+---
+
+## Data Flow Patterns
+
+### User Authentication Flow
+
+```
+1. User loads app
+ → React app served from Worker static assets
+ → ClerkProvider wraps app
+
+2. User not authenticated
+ → Show sign-in button
+ → User clicks sign-in
+ → Clerk modal opens
+
+3. User signs in
+ → Clerk handles authentication
+ → Returns JWT to browser
+ → React stores JWT in memory (via ClerkProvider)
+
+4. User makes API request
+ → React includes JWT in Authorization header
+ → Worker middleware verifies JWT
+ → Extracts user info from JWT
+ → Passes to route handler via context
+```
+
+---
+
+### CRUD Operation Flow (Example: Create Task)
+
+```
+1. User fills out form
+ ↓
+2. React Hook Form validates locally (Zod schema)
+ ↓
+3. Validation passes → Submit to API
+ ↓
+4. POST /api/tasks with JWT in header
+ ↓
+5. Worker receives request
+ ↓
+6. CORS middleware allows request
+ ↓
+7. Auth middleware verifies JWT → extracts userId
+ ↓
+8. Route handler receives request
+ ↓
+9. Validation middleware validates body (Zod schema)
+ ↓
+10. Business logic creates task in D1
+ INSERT INTO tasks (user_id, title, ...) VALUES (?, ?, ...)
+ ↓
+11. Return created task (201)
+ ↓
+12. TanStack Query updates cache
+ ↓
+13. React re-renders with new task
+```
+
+---
+
+### File Upload Flow
+
+```
+1. User selects file in browser
+ ↓
+2. React sends file to POST /api/upload
+ ↓
+3. Worker receives file (multipart/form-data)
+ ↓
+4. Worker validates file (size, type)
+ ↓
+5. Worker uploads to R2
+ await c.env.R2_BUCKET.put(`uploads/${userId}/${filename}`, file)
+ ↓
+6. Worker creates DB record with R2 key
+ INSERT INTO files (user_id, r2_key, filename, ...) VALUES (...)
+ ↓
+7. Return file metadata (200)
+ ↓
+8. Frontend shows uploaded file with signed URL
+ GET /api/files/:id/url → Worker generates R2 signed URL
+```
+
+---
+
+## Deployment Architecture
+
+### Development Environment
+
+```
+localhost:5173
+ ↓
+Vite dev server (HMR)
+ ↓
+@cloudflare/vite-plugin runs Worker alongside Vite
+ ↓
+Worker connects to local D1 database
+ ↓
+All requests proxied correctly (frontend ↔ API on same port)
+```
+
+**Start dev**:
+```bash
+npm run dev
+# Vite serves frontend on :5173
+# Worker API available at :5173/api
+# Uses local D1 and R2 buckets
+```
+
+---
+
+### Production Environment
+
+```
+https://[app-name].[account].workers.dev (or custom domain)
+ ↓
+Cloudflare Worker (edge locations globally)
+ ↓
+Static assets cached at edge
+API requests hit Worker
+ ↓
+D1 database (regional, auto-replicated)
+R2 storage (global, low latency)
+```
+
+**Deploy**:
+```bash
+npm run build # Vite builds frontend → dist/
+npx wrangler deploy # Uploads Worker + assets
+```
+
+---
+
+## Security Architecture
+
+### Authentication
+- **JWT verification** on all protected routes
+- **Clerk handles** password hashing, session management, social auth
+- **No passwords stored** in our database
+
+### Authorization
+- **User ownership checks** before mutations
+- Example: Can't delete another user's task
+```typescript
+const task = await getTask(id)
+if (task.user_id !== c.get('userId')) {
+ return c.json({ error: 'Forbidden' }, 403)
+}
+```
+
+### Input Validation
+- **Client-side** (Zod): Fast feedback, better UX
+- **Server-side** (Zod): Security, trust boundary
+- **Same schemas** used on both sides
+
+### CORS
+- **Restrict origins** to production domain
+- **Allow credentials** for JWT cookies (if used)
+
+### Secrets Management
+- **Environment variables** for API keys
+- **Never committed** to git
+- **Wrangler secrets** for production
+
+### Rate Limiting
+[Optional: Add if implemented]
+- X requests per minute per IP
+- Higher limits for authenticated users
+
+---
+
+## Scaling Considerations
+
+### Current Architecture Scales to:
+- **Requests**: Millions/day (Cloudflare Workers auto-scale)
+- **Users**: 10k-100k (D1 suitable for this range)
+- **Data**: Moderate (D1 max 10GB per database)
+
+### If You Need to Scale Beyond:
+- **Database**: Consider Hyperdrive + external Postgres for >100k users
+- **Storage**: R2 scales infinitely
+- **Real-time**: Add Durable Objects for WebSocket connections
+- **Compute**: Workers already global and auto-scaling
+
+---
+
+## Monitoring and Observability
+
+[Optional: Define monitoring strategy]
+
+**Metrics to Track**:
+- Request volume and latency
+- Error rates (4xx, 5xx)
+- Database query performance
+- R2 upload/download volumes
+
+**Tools**:
+- Cloudflare Analytics (built-in)
+- Workers Analytics Engine (custom metrics)
+- Sentry or similar for error tracking
+
+---
+
+## Development Workflow
+
+1. **Local development**: `npm run dev`
+2. **Make changes**: Edit code, hot reload
+3. **Test locally**: Manual testing or automated tests
+4. **Commit**: `git commit -m "feat: add feature"`
+5. **Deploy**: `npx wrangler deploy`
+6. **Monitor**: Check Cloudflare dashboard for errors
+
+---
+
+## Technology Choices Rationale
+
+**Why Cloudflare Workers?**
+- Global edge deployment (low latency)
+- Auto-scaling (no server management)
+- Integrated services (D1, R2, KV)
+- Cost-effective for moderate traffic
+
+**Why Vite?**
+- Fast dev server with HMR
+- Excellent React support
+- Simple config
+- `@cloudflare/vite-plugin` integrates perfectly with Workers
+
+**Why Hono?**
+- Lightweight and fast
+- Express-like API (familiar)
+- Native TypeScript support
+- Works on any runtime (including Workers)
+
+**Why Clerk?**
+- Handles complex auth flows
+- Social auth out of the box
+- Great DX
+- No need to build/maintain auth system
+
+**Why Tailwind v4?**
+- Utility-first CSS
+- shadcn/ui compatibility
+- Dark mode support
+- v4 Vite plugin (no PostCSS needed)
+
+---
+
+## Future Architecture Enhancements
+
+Potential additions:
+- [ ] Durable Objects for real-time features (WebSockets)
+- [ ] Workers AI for AI-powered features
+- [ ] Queues for background jobs
+- [ ] Hyperdrive for external database connections
+- [ ] Vectorize for semantic search
+
+---
+
+## Revision History
+
+**v1.0** ([Date]): Initial architecture design
+**v1.1** ([Date]): [Changes made]
diff --git a/skills/project-planning/templates/DATABASE_SCHEMA.md b/skills/project-planning/templates/DATABASE_SCHEMA.md
new file mode 100644
index 00000000..453eb790
--- /dev/null
+++ b/skills/project-planning/templates/DATABASE_SCHEMA.md
@@ -0,0 +1,269 @@
+# Database Schema: [Project Name]
+
+**Database**: Cloudflare D1 (SQLite)
+**Migrations**: `migrations/` directory
+**ORM**: [Drizzle ORM / Raw SQL / None]
+**Schema Version**: 1.0
+**Last Updated**: [Date]
+
+---
+
+## Overview
+
+This document defines the complete database schema including tables, relationships, indexes, and migrations.
+
+**Design Principles**:
+- Normalize data to reduce redundancy
+- Index frequently queried columns
+- Use foreign keys for referential integrity
+- Include timestamps for audit trail
+- Use INTEGER for IDs (SQLite auto-increment)
+- Use TEXT for strings (SQLite doesn't enforce varchar limits)
+- Use INTEGER for booleans (0 = false, 1 = true)
+- Use INTEGER for timestamps (Unix epoch)
+
+---
+
+## Tables
+
+### `users`
+**Purpose**: User accounts and authentication data
+
+| Column | Type | Constraints | Default | Notes |
+|--------|------|-------------|---------|-------|
+| `id` | INTEGER | PRIMARY KEY | AUTO | Auto-increment |
+| `email` | TEXT | UNIQUE, NOT NULL | - | Login identifier |
+| `clerk_id` | TEXT | UNIQUE, NOT NULL | - | Clerk user ID |
+| `display_name` | TEXT | NULL | - | User's display name |
+| `avatar_url` | TEXT | NULL | - | Profile picture URL (R2) |
+| `created_at` | INTEGER | NOT NULL | - | Unix timestamp |
+| `updated_at` | INTEGER | NOT NULL | - | Unix timestamp |
+
+**Indexes**:
+- `idx_users_email` on `email` (for login lookups)
+- `idx_users_clerk_id` on `clerk_id` (for auth verification)
+
+**Relationships**:
+- One-to-many with `[related_table]`
+
+**Notes**:
+- `clerk_id` comes from Clerk authentication
+- `avatar_url` points to R2 storage if user uploads custom avatar
+- Emails are unique and used for account identification
+
+---
+
+### `[table_name]`
+**Purpose**: [Description of what this table stores]
+
+| Column | Type | Constraints | Default | Notes |
+|--------|------|-------------|---------|-------|
+| `id` | INTEGER | PRIMARY KEY | AUTO | Auto-increment |
+| `user_id` | INTEGER | FOREIGN KEY, NOT NULL | - | References `users(id)` |
+| `[field]` | [TYPE] | [CONSTRAINTS] | [DEFAULT] | [Notes] |
+| `created_at` | INTEGER | NOT NULL | - | Unix timestamp |
+| `updated_at` | INTEGER | NOT NULL | - | Unix timestamp |
+
+**Indexes**:
+- `idx_[table]_user_id` on `user_id` (for user-specific queries)
+- `idx_[table]_[field]` on `[field]` (if frequently queried)
+
+**Relationships**:
+- Many-to-one with `users`
+- [Other relationships]
+
+**Notes**:
+- [Important details about this table]
+
+---
+
+### `[junction_table]` (for many-to-many relationships)
+**Purpose**: Links [table_a] and [table_b] in many-to-many relationship
+
+| Column | Type | Constraints | Default | Notes |
+|--------|------|-------------|---------|-------|
+| `id` | INTEGER | PRIMARY KEY | AUTO | Auto-increment |
+| `[table_a]_id` | INTEGER | FOREIGN KEY, NOT NULL | - | References `[table_a](id)` |
+| `[table_b]_id` | INTEGER | FOREIGN KEY, NOT NULL | - | References `[table_b](id)` |
+| `created_at` | INTEGER | NOT NULL | - | Unix timestamp |
+
+**Indexes**:
+- `idx_[junction]_[table_a]_id` on `[table_a]_id`
+- `idx_[junction]_[table_b]_id` on `[table_b]_id`
+- `idx_[junction]_composite` on `([table_a]_id, [table_b]_id)` UNIQUE
+
+**Relationships**:
+- Many-to-one with `[table_a]`
+- Many-to-one with `[table_b]`
+
+**Notes**:
+- Composite unique index prevents duplicate associations
+
+---
+
+## Relationships Diagram
+
+```
+┌─────────────┐
+│ users │
+└──────┬──────┘
+ │ 1
+ │
+ │ N
+┌──────┴──────────┐
+│ [child_table] │
+└─────────────────┘
+
+[Add more relationships as needed]
+```
+
+---
+
+## Migrations
+
+### Migration 0001: Initial Schema
+**File**: `migrations/0001_initial_schema.sql`
+**Created**: [Date]
+**Purpose**: Create initial tables for [core entities]
+
+**Creates**:
+- `users` table
+- `[other_tables]` tables
+
+**Indexes**:
+- All primary indexes for frequently queried columns
+
+**Run**:
+```bash
+npx wrangler d1 execute [DB_NAME] --local --file=migrations/0001_initial_schema.sql
+npx wrangler d1 execute [DB_NAME] --remote --file=migrations/0001_initial_schema.sql
+```
+
+---
+
+### Migration 0002: [Description]
+**File**: `migrations/0002_[name].sql`
+**Created**: [Date]
+**Purpose**: [What this migration does]
+
+**Changes**:
+- Add `[column]` to `[table]`
+- Create `[new_table]` table
+- Add index `[index_name]`
+
+**Run**:
+```bash
+npx wrangler d1 execute [DB_NAME] --local --file=migrations/0002_[name].sql
+npx wrangler d1 execute [DB_NAME] --remote --file=migrations/0002_[name].sql
+```
+
+---
+
+## Seed Data
+
+For development and testing, seed the database with sample data.
+
+**File**: `migrations/seed.sql` (run manually, not in production)
+
+**Sample Data**:
+- 3-5 test users
+- [Other sample data relevant to testing]
+
+**Run**:
+```bash
+npx wrangler d1 execute [DB_NAME] --local --file=migrations/seed.sql
+```
+
+**Sample Users**:
+```sql
+INSERT INTO users (email, clerk_id, display_name, created_at, updated_at)
+VALUES
+ ('[email protected]', 'clerk_test_1', 'Test User 1', strftime('%s', 'now'), strftime('%s', 'now')),
+ ('[email protected]', 'clerk_test_2', 'Test User 2', strftime('%s', 'now'), strftime('%s', 'now')),
+ ('[email protected]', 'clerk_test_3', 'Test User 3', strftime('%s', 'now'), strftime('%s', 'now'));
+```
+
+---
+
+## Query Patterns
+
+### Common Queries
+
+**Get user by email**:
+```sql
+SELECT * FROM users WHERE email = ?;
+```
+
+**Get all [items] for a user**:
+```sql
+SELECT * FROM [table] WHERE user_id = ? ORDER BY created_at DESC;
+```
+
+**Get [item] with related data**:
+```sql
+SELECT
+ [table].*,
+ users.display_name,
+ users.avatar_url
+FROM [table]
+JOIN users ON [table].user_id = users.id
+WHERE [table].id = ?;
+```
+
+---
+
+## Constraints and Validation
+
+### Enforced at Database Level
+- Primary keys (unique, not null)
+- Foreign keys (referential integrity)
+- Unique constraints (email, composite indexes)
+- Not null constraints (required fields)
+
+### Enforced at Application Level (Zod)
+- Email format validation
+- String length limits
+- Enum values
+- Complex business logic
+
+**Why split?**: Database enforces data integrity, application provides user-friendly error messages.
+
+---
+
+## Backup and Restore
+
+### Export Database
+```bash
+npx wrangler d1 export [DB_NAME] --local --output=backup.sql
+npx wrangler d1 export [DB_NAME] --remote --output=backup.sql
+```
+
+### Import Database
+```bash
+npx wrangler d1 execute [DB_NAME] --local --file=backup.sql
+npx wrangler d1 execute [DB_NAME] --remote --file=backup.sql
+```
+
+---
+
+## Performance Considerations
+
+**Indexes**: All frequently queried columns are indexed
+**Query Optimization**: Use `EXPLAIN QUERY PLAN` to check query performance
+**Pagination**: Use `LIMIT` and `OFFSET` for large result sets
+**Caching**: Consider Workers KV for frequently accessed, rarely changed data
+
+---
+
+## Future Enhancements
+
+Potential schema changes to consider:
+- [ ] [Feature requiring schema change]
+- [ ] [Another potential enhancement]
+
+---
+
+## Revision History
+
+**v1.0** ([Date]): Initial schema design
+**v1.1** ([Date]): [Changes made]
diff --git a/skills/project-planning/templates/IMPLEMENTATION_PHASES.md b/skills/project-planning/templates/IMPLEMENTATION_PHASES.md
new file mode 100644
index 00000000..687d3db0
--- /dev/null
+++ b/skills/project-planning/templates/IMPLEMENTATION_PHASES.md
@@ -0,0 +1,168 @@
+# Implementation Phases: [Project Name]
+
+**Project Type**: [Web App / Dashboard / API / Tool / etc]
+**Stack**: Cloudflare Workers + Vite + React + Tailwind v4 + shadcn/ui + D1
+**Estimated Total**: [X hours] (~[Y minutes] human time with AI assistance)
+**Created**: [Date]
+
+---
+
+## Overview
+
+This document breaks down the project into context-safe phases. Each phase:
+- Can be completed in one 2-4 hour session
+- Includes built-in verification criteria
+- Has clear exit criteria
+- Touches 5-8 files maximum
+- Requires minimal context from other phases
+
+---
+
+## Phase 1: [Name - Usually "Project Setup"]
+**Type**: Infrastructure
+**Estimated**: 2-3 hours (~2-3 minutes human time)
+**Files**: `package.json`, `wrangler.jsonc`, `vite.config.ts`, `src/index.ts`, `src/index.css`
+
+### Tasks
+- [ ] Scaffold Cloudflare Worker with Vite
+- [ ] Install dependencies (React, Tailwind v4, shadcn/ui, etc)
+- [ ] Configure `wrangler.jsonc` with bindings
+- [ ] Setup Tailwind v4 with `@tailwindcss/vite` plugin
+- [ ] Initialize shadcn/ui with dark mode support
+- [ ] Create basic "Hello World" component
+- [ ] Test local dev server
+- [ ] Test deployment to Cloudflare
+
+### Verification Criteria
+- [ ] `npm run dev` starts without errors
+- [ ] `localhost:5173` shows React app with Tailwind styling
+- [ ] Dark/light mode toggle works
+- [ ] `npm run build` succeeds
+- [ ] `npx wrangler deploy` deploys successfully
+- [ ] Deployed URL shows working app
+
+### Exit Criteria
+Working development environment with successful test deployment. Can iterate on code locally and deploy to Cloudflare.
+
+---
+
+## Phase 2: [Name - Usually "Database Schema" or next major component]
+**Type**: [Database/API/UI/Integration]
+**Estimated**: [X hours]
+**Files**: [List specific files]
+
+### Tasks
+- [ ] [Specific task 1]
+- [ ] [Specific task 2]
+- [ ] [Specific task 3]
+- [ ] Test basic functionality
+
+### Verification Criteria
+- [ ] [Specific test 1]
+- [ ] [Specific test 2]
+- [ ] [Specific test 3]
+
+### Exit Criteria
+[Clear definition of when this phase is complete]
+
+---
+
+## Phase 3: [Name]
+**Type**: [Database/API/UI/Integration]
+**Estimated**: [X hours]
+**Files**: [List specific files]
+
+### Tasks
+- [ ] [Tasks...]
+
+### Verification Criteria
+- [ ] [Tests...]
+
+### Exit Criteria
+[Definition of done]
+
+---
+
+## Phase 4: [Name]
+**Type**: [Database/API/UI/Integration]
+**Estimated**: [X hours]
+**Files**: [List specific files]
+
+### Tasks
+- [ ] [Tasks...]
+
+### Verification Criteria
+- [ ] [Tests...]
+
+### Exit Criteria
+[Definition of done]
+
+---
+
+## Phase 5: [Name - Optional: Testing/Polish/Deployment]
+**Type**: [Testing/Integration]
+**Estimated**: [X hours]
+**Files**: [List specific files]
+
+### Tasks
+- [ ] [Tasks...]
+
+### Verification Criteria
+- [ ] [Tests...]
+
+### Exit Criteria
+[Definition of done]
+
+---
+
+## Notes
+
+### Testing Strategy
+[Describe when/how testing happens]
+- Option A: Testing built into each phase (verification criteria)
+- Option B: Separate testing phase at end
+- Option C: Hybrid - smoke tests per phase, comprehensive tests at end
+
+### Deployment Strategy
+[Describe deployment approach]
+- Option A: Deploy after each phase (continuous deployment)
+- Option B: Deploy at milestones (after groups of phases)
+- Option C: Deploy at end (single production push)
+
+### Context Management
+Phases are sized to fit within a single session including:
+- Implementation time
+- Verification time
+- Expected debugging/fixes time
+- Documentation updates
+
+If a phase can't be completed in one session, it should be split into sub-phases (e.g., Phase 3.1, Phase 3.2).
+
+### Dependencies
+Phases are ordered to minimize dependencies:
+1. Infrastructure (no dependencies)
+2. Database (depends on Infrastructure)
+3. API (depends on Infrastructure + Database)
+4. UI (depends on API)
+5. Integration (depends on relevant phases)
+6. Testing (depends on all implementation phases)
+
+### Known Risks
+[Optional: List any known challenges or uncertainties]
+- Risk 1: [Description and mitigation]
+- Risk 2: [Description and mitigation]
+
+---
+
+## Success Metrics
+
+**Phase Completion**: All verification criteria met, exit criteria satisfied
+**Session Handoff**: SESSION.md updated, git checkpoint created
+**Overall Success**: [Define what "done" means for this project]
+
+---
+
+## Revision History
+
+**v1.0** ([Date]): Initial phase breakdown
+**v1.1** ([Date]): [Changes made]
diff --git a/skills/project-planning/templates/INTEGRATION.md b/skills/project-planning/templates/INTEGRATION.md
new file mode 100644
index 00000000..425f729a
--- /dev/null
+++ b/skills/project-planning/templates/INTEGRATION.md
@@ -0,0 +1,612 @@
+# Third-Party Integrations: [Project Name]
+
+**Primary Integrations**: [List main services - e.g., Clerk, Stripe, OpenAI]
+**Webhooks**: [Number of webhook handlers]
+**Last Updated**: [Date]
+
+---
+
+## Overview
+
+This document describes all third-party service integrations including API setup, authentication, webhooks, and error handling.
+
+**Integration Principles**:
+- **Environment-based config** - API keys in env vars, never committed
+- **Graceful degradation** - App works (reduced functionality) if service is down
+- **Webhook verification** - Always verify webhook signatures
+- **Rate limit awareness** - Respect provider rate limits
+- **Error handling** - Catch and log integration failures
+
+---
+
+## Integrations
+
+### Clerk (Authentication)
+
+**Purpose**: User authentication and management
+**Docs**: https://clerk.com/docs
+**Dashboard**: https://dashboard.clerk.com
+
+**Setup**:
+```bash
+npm install @clerk/clerk-react @clerk/backend
+```
+
+**Environment Variables**:
+```env
+# Frontend
+VITE_CLERK_PUBLISHABLE_KEY=pk_test_...
+
+# Backend (Wrangler secret)
+CLERK_SECRET_KEY=sk_test_...
+```
+
+**Frontend Integration**:
+```tsx
+// src/main.tsx
+import { ClerkProvider } from '@clerk/clerk-react'
+
+ReactDOM.createRoot(document.getElementById('root')!).render(
+ <ClerkProvider publishableKey={import.meta.env.VITE_CLERK_PUBLISHABLE_KEY}>
+ <App />
+ </ClerkProvider>
+)
+```
+
+**Backend Integration** (JWT verification):
+```typescript
+// src/middleware/auth.ts
+import { verifyToken } from '@clerk/backend'
+
+export async function authMiddleware(c: Context, next: Next) {
+ const token = c.req.header('Authorization')?.replace('Bearer ', '')
+ if (!token) {
+ return c.json({ error: 'Unauthorized' }, 401)
+ }
+
+ try {
+ const verified = await verifyToken(token, {
+ secretKey: c.env.CLERK_SECRET_KEY
+ })
+ c.set('userId', verified.sub)
+ c.set('email', verified.email)
+ await next()
+ } catch (error) {
+ return c.json({ error: 'Invalid token' }, 401)
+ }
+}
+```
+
+**Custom JWT Template** (configured in Clerk dashboard):
+```json
+{
+ "email": "{{user.primary_email_address}}",
+ "userId": "{{user.id}}",
+ "firstName": "{{user.first_name}}",
+ "lastName": "{{user.last_name}}"
+}
+```
+
+**Webhooks**: See webhook section below
+
+**Rate Limits**: 100 requests/second (Pro plan)
+
+**Error Handling**:
+- Token expired → Return 401, frontend refreshes token
+- Service down → Return 503, show maintenance message
+
+---
+
+### [Integration Name - e.g., Stripe]
+
+**Purpose**: [What this service provides - e.g., Payment processing]
+**Docs**: [Documentation URL]
+**Dashboard**: [Dashboard URL]
+
+**Setup**:
+```bash
+npm install [package-name]
+```
+
+**Environment Variables**:
+```env
+[SERVICE]_API_KEY=...
+[SERVICE]_WEBHOOK_SECRET=...
+```
+
+**API Client**:
+```typescript
+// src/lib/[service]-client.ts
+import [ServiceSDK] from '[package-name]'
+
+export function create[Service]Client(apiKey: string) {
+ return new [ServiceSDK]({
+ apiKey,
+ // other config
+ })
+}
+```
+
+**Usage Example**:
+```typescript
+// In route handler
+const client = create[Service]Client(c.env.[SERVICE]_API_KEY)
+const result = await client.[method]({ params })
+```
+
+**Webhooks**: [Yes/No - see webhook section if yes]
+
+**Rate Limits**: [Limits for this service]
+
+**Error Handling**: [How to handle failures]
+
+---
+
+### OpenAI (AI Features) - Example
+
+**Purpose**: AI-powered features (chat, completions, embeddings)
+**Docs**: https://platform.openai.com/docs
+**Dashboard**: https://platform.openai.com
+
+**Setup**:
+```bash
+npm install openai
+```
+
+**Environment Variables**:
+```env
+OPENAI_API_KEY=sk-...
+```
+
+**API Client**:
+```typescript
+// src/lib/openai-client.ts
+import OpenAI from 'openai'
+
+export function createOpenAIClient(apiKey: string) {
+ return new OpenAI({ apiKey })
+}
+```
+
+**Usage**:
+```typescript
+const openai = createOpenAIClient(c.env.OPENAI_API_KEY)
+
+const response = await openai.chat.completions.create({
+ model: 'gpt-5',
+ messages: [{ role: 'user', content: 'Hello!' }],
+ stream: true
+})
+
+// Stream response to client
+return new Response(response.body, {
+ headers: { 'Content-Type': 'text/event-stream' }
+})
+```
+
+**Rate Limits**:
+- Free tier: 3 requests/minute
+- Paid: 10,000 requests/minute
+
+**Error Handling**:
+```typescript
+try {
+ const response = await openai.chat.completions.create({ ... })
+ return response
+} catch (error) {
+ if (error.code === 'rate_limit_exceeded') {
+ return c.json({ error: 'Too many requests. Please try again later.' }, 429)
+ } else {
+ console.error('OpenAI error:', error)
+ return c.json({ error: 'AI service unavailable' }, 503)
+ }
+}
+```
+
+---
+
+## Webhooks
+
+Webhooks are HTTP callbacks from third-party services to notify our app of events.
+
+### Webhook: Clerk User Events
+
+**Purpose**: Sync user data when Clerk users are created, updated, or deleted
+
+**Endpoint**: `POST /api/webhooks/clerk`
+
+**Events**:
+- `user.created` - New user signed up
+- `user.updated` - User profile changed
+- `user.deleted` - User account deleted
+
+**Payload Example**:
+```json
+{
+ "type": "user.created",
+ "data": {
+ "id": "user_abc123",
+ "email_addresses": [
+ { "email_address": "[email protected]" }
+ ],
+ "first_name": "John",
+ "last_name": "Doe"
+ }
+}
+```
+
+**Signature Verification**:
+```typescript
+import { Webhook } from 'svix'
+
+export async function verifyClerkWebhook(
+ payload: string,
+ headers: Headers,
+ secret: string
+) {
+ const wh = new Webhook(secret)
+
+ try {
+ return wh.verify(payload, {
+ 'svix-id': headers.get('svix-id')!,
+ 'svix-timestamp': headers.get('svix-timestamp')!,
+ 'svix-signature': headers.get('svix-signature')!
+ })
+ } catch (error) {
+ throw new Error('Invalid webhook signature')
+ }
+}
+```
+
+**Handler**:
+```typescript
+app.post('/api/webhooks/clerk', async (c) => {
+ const payload = await c.req.text()
+ const verified = await verifyClerkWebhook(
+ payload,
+ c.req.raw.headers,
+ c.env.CLERK_WEBHOOK_SECRET
+ )
+
+ const event = JSON.parse(payload)
+
+ switch (event.type) {
+ case 'user.created':
+ await createUserInDatabase(event.data)
+ break
+ case 'user.updated':
+ await updateUserInDatabase(event.data)
+ break
+ case 'user.deleted':
+ await deleteUserInDatabase(event.data.id)
+ break
+ }
+
+ return c.json({ received: true })
+})
+```
+
+**Configuration** (Clerk dashboard):
+1. Go to Webhooks section
+2. Add endpoint: `https://[your-app].workers.dev/api/webhooks/clerk`
+3. Select events: user.created, user.updated, user.deleted
+4. Copy signing secret to environment variables
+
+---
+
+### Webhook: [Service Name]
+
+**Purpose**: [What events this webhook handles]
+
+**Endpoint**: `POST /api/webhooks/[service]`
+
+**Events**: [List of event types]
+
+**Signature Verification**: [How to verify]
+
+**Handler**: [Implementation details]
+
+---
+
+## Environment Variables
+
+### Development (.dev.vars)
+```env
+# Clerk
+CLERK_SECRET_KEY=sk_test_...
+CLERK_WEBHOOK_SECRET=whsec_...
+
+# OpenAI
+OPENAI_API_KEY=sk-...
+
+# Stripe
+STRIPE_SECRET_KEY=sk_test_...
+STRIPE_WEBHOOK_SECRET=whsec_...
+
+# [Other services]
+```
+
+### Production (Wrangler secrets)
+```bash
+# Set secrets via CLI
+npx wrangler secret put CLERK_SECRET_KEY
+npx wrangler secret put OPENAI_API_KEY
+npx wrangler secret put STRIPE_SECRET_KEY
+
+# Or via dashboard
+# Cloudflare Dashboard → Workers → [Your Worker] → Settings → Variables
+```
+
+**Never commit secrets to git**. Use `.dev.vars` locally (gitignored) and Wrangler secrets in production.
+
+---
+
+## API Rate Limiting
+
+### Handling Rate Limits
+
+**Strategy**: Exponential backoff + retry
+
+**Implementation**:
+```typescript
+async function callWithRetry<T>(
+ fn: () => Promise<T>,
+ maxRetries = 3
+): Promise<T> {
+ let attempt = 0
+
+ while (attempt < maxRetries) {
+ try {
+ return await fn()
+ } catch (error) {
+ if (error.code === 'rate_limit' && attempt < maxRetries - 1) {
+ const delay = Math.pow(2, attempt) * 1000 // 1s, 2s, 4s
+ await new Promise(resolve => setTimeout(resolve, delay))
+ attempt++
+ } else {
+ throw error
+ }
+ }
+ }
+
+ throw new Error('Max retries exceeded')
+}
+
+// Usage
+const result = await callWithRetry(() =>
+ openai.chat.completions.create({ ... })
+)
+```
+
+---
+
+## Error Handling
+
+### Integration Failure Patterns
+
+**1. Service Temporarily Down**:
+```typescript
+try {
+ const result = await callExternalService()
+ return result
+} catch (error) {
+ console.error('Service error:', error)
+ return c.json({
+ error: 'Service temporarily unavailable. Please try again later.',
+ code: 'SERVICE_UNAVAILABLE'
+ }, 503)
+}
+```
+
+**2. Invalid Credentials**:
+```typescript
+if (error.code === 'invalid_api_key') {
+ console.error('Invalid API key for [service]')
+ return c.json({
+ error: 'Configuration error. Please contact support.',
+ code: 'CONFIGURATION_ERROR'
+ }, 500)
+}
+```
+
+**3. Rate Limited**:
+```typescript
+if (error.code === 'rate_limit_exceeded') {
+ return c.json({
+ error: 'Too many requests. Please wait a moment and try again.',
+ code: 'RATE_LIMIT_EXCEEDED',
+ retryAfter: error.retryAfter
+ }, 429)
+}
+```
+
+---
+
+## Testing Integrations
+
+### Mocking External Services
+
+**Use MSW (Mock Service Worker)** for tests:
+
+```typescript
+// tests/mocks/handlers.ts
+import { http, HttpResponse } from 'msw'
+
+export const handlers = [
+ http.post('https://api.openai.com/v1/chat/completions', () => {
+ return HttpResponse.json({
+ choices: [
+ { message: { content: 'Mocked response' } }
+ ]
+ })
+ })
+]
+```
+
+**Setup**:
+```typescript
+// tests/setup.ts
+import { setupServer } from 'msw/node'
+import { handlers } from './mocks/handlers'
+
+const server = setupServer(...handlers)
+
+beforeAll(() => server.listen())
+afterEach(() => server.resetHandlers())
+afterAll(() => server.close())
+```
+
+---
+
+### Testing Webhooks
+
+**Test webhook signature verification**:
+```typescript
+describe('POST /api/webhooks/clerk', () => {
+ it('rejects invalid signature', async () => {
+ const res = await app.request('/api/webhooks/clerk', {
+ method: 'POST',
+ headers: {
+ 'svix-signature': 'invalid_signature'
+ },
+ body: JSON.stringify({ type: 'user.created', data: {} })
+ })
+
+ expect(res.status).toBe(401)
+ })
+
+ it('processes valid webhook', async () => {
+ // Generate valid signature for testing
+ const payload = JSON.stringify({ type: 'user.created', data: {...} })
+ const signature = generateTestSignature(payload)
+
+ const res = await app.request('/api/webhooks/clerk', {
+ method: 'POST',
+ headers: {
+ 'svix-signature': signature,
+ 'svix-id': 'msg_123',
+ 'svix-timestamp': Date.now().toString()
+ },
+ body: payload
+ })
+
+ expect(res.status).toBe(200)
+ })
+})
+```
+
+---
+
+## Monitoring
+
+### Track Integration Health
+
+**Metrics**:
+- API call success rate (per service)
+- API call latency (average, p95, p99)
+- Rate limit hits
+- Webhook delivery success rate
+
+**Logging**:
+```typescript
+console.log('[Integration]', {
+ service: 'openai',
+ method: 'chat.completions.create',
+ success: true,
+ latency: responseTime,
+ tokensUsed: response.usage.total_tokens
+})
+```
+
+**Alerts**:
+- Integration success rate < 95% → Alert
+- Average latency > 5s → Alert
+- Webhook failures > 10 in 1 hour → Alert
+
+---
+
+## Graceful Degradation
+
+**If integration fails, app should still function** (with reduced features).
+
+**Example**: AI chat unavailable
+```typescript
+try {
+ const response = await openai.chat.completions.create({ ... })
+ return response
+} catch (error) {
+ console.error('OpenAI unavailable:', error)
+
+ // Fallback: Return canned response
+ return {
+ content: "I'm currently unavailable. Please try again later or contact support.",
+ fallback: true
+ }
+}
+```
+
+**Example**: Payment processing down
+```typescript
+if (!stripe.isHealthy()) {
+ return (
+ <Alert variant="warning">
+ Payment processing is temporarily unavailable. Please try again later.
+ </Alert>
+ )
+}
+```
+
+---
+
+## Security Best Practices
+
+### API Keys
+- ✅ Store in environment variables
+- ✅ Use Wrangler secrets in production
+- ✅ Rotate keys periodically
+- ❌ Never commit to git
+- ❌ Never log in production
+
+### Webhook Security
+- ✅ Always verify signatures
+- ✅ Use HTTPS endpoints only
+- ✅ Validate payload structure
+- ✅ Implement replay protection (check timestamp)
+- ❌ Never trust webhook data without verification
+
+### CORS
+- ✅ Restrict origins to your domain
+- ✅ Allow only necessary methods
+- ❌ Don't use wildcard (*) in production
+
+---
+
+## Future Integrations
+
+Planned integrations:
+- [ ] [Service name] - [Purpose]
+- [ ] [Service name] - [Purpose]
+
+---
+
+## Integration Checklist
+
+When adding a new integration:
+- [ ] Install SDK/package
+- [ ] Add environment variables
+- [ ] Create API client wrapper
+- [ ] Implement error handling
+- [ ] Add rate limit handling
+- [ ] Setup webhook handler (if applicable)
+- [ ] Verify webhook signatures
+- [ ] Write tests (mock external calls)
+- [ ] Document in this file
+- [ ] Add monitoring/logging
+- [ ] Test in staging before production
+
+---
+
+## Revision History
+
+**v1.0** ([Date]): Initial integration documentation
+**v1.1** ([Date]): [Changes made]
diff --git a/skills/project-planning/templates/TESTING.md b/skills/project-planning/templates/TESTING.md
new file mode 100644
index 00000000..3f38524a
--- /dev/null
+++ b/skills/project-planning/templates/TESTING.md
@@ -0,0 +1,508 @@
+# Testing Strategy: [Project Name]
+
+**Testing Framework**: Vitest (unit/integration)
+**E2E Framework**: Playwright (optional)
+**Coverage Target**: 70%+ for critical paths
+**Last Updated**: [Date]
+
+---
+
+## Overview
+
+This document defines the testing strategy including what to test, how to test, and when to test.
+
+**Testing Philosophy**:
+- **Test behavior, not implementation** - Focus on user-facing functionality
+- **Test critical paths first** - Auth, data CRUD, payments, etc
+- **Fast feedback** - Unit tests run in milliseconds
+- **Realistic tests** - Integration tests use real-ish data
+- **E2E for happy paths** - Cover main user workflows
+
+**Testing Pyramid**:
+```
+ ┌──────────┐
+ │ E2E │ ← Few (slow, brittle)
+ └──────────┘
+ ┌──────────────┐
+ │ Integration │ ← Some (medium speed)
+ └──────────────┘
+ ┌───────────────────┐
+ │ Unit Tests │ ← Many (fast, focused)
+ └───────────────────┘
+```
+
+---
+
+## What to Test
+
+### ✅ Do Test
+
+**Business Logic**:
+- Data validation (Zod schemas)
+- Data transformations
+- Complex calculations
+- State management logic
+
+**API Endpoints**:
+- All HTTP methods (GET, POST, PATCH, DELETE)
+- All response codes (200, 400, 401, 404, 500)
+- Request validation
+- Authorization checks
+
+**User Workflows**:
+- Authentication flow
+- CRUD operations (create, read, update, delete)
+- Form submissions
+- Error handling
+
+**Critical Paths**:
+- Payment processing (if applicable)
+- Data export/import
+- Email notifications
+- File uploads
+
+---
+
+### ❌ Don't Test
+
+**Third-party libraries**: Trust that React, Tailwind, shadcn/ui work
+
+**Implementation details**: Internal function calls, component props (unless part of public API)
+
+**Trivial code**: Simple getters/setters, pass-through functions
+
+**UI styling**: Visual regression testing is overkill for most projects
+
+---
+
+## Testing Layers
+
+### 1. Unit Tests (Many)
+
+**Purpose**: Test individual functions and utilities in isolation
+
+**Tool**: Vitest
+
+**What to test**:
+- Utility functions (`src/lib/utils.ts`)
+- Zod schemas (`src/lib/schemas.ts`)
+- Data transformations
+- Pure functions
+
+**Example**:
+```typescript
+// src/lib/utils.test.ts
+import { describe, it, expect } from 'vitest'
+import { formatDate, cn } from './utils'
+
+describe('formatDate', () => {
+ it('formats Unix timestamp to readable date', () => {
+ expect(formatDate(1234567890)).toBe('Feb 14, 2009')
+ })
+
+ it('handles invalid timestamps', () => {
+ expect(formatDate(-1)).toBe('Invalid Date')
+ })
+})
+
+describe('cn', () => {
+ it('merges class names', () => {
+ expect(cn('foo', 'bar')).toBe('foo bar')
+ })
+
+ it('handles conditional classes', () => {
+ expect(cn('foo', false && 'bar', 'baz')).toBe('foo baz')
+ })
+})
+```
+
+**Run**: `npm run test`
+
+---
+
+### 2. Integration Tests (Some)
+
+**Purpose**: Test API endpoints with real database interactions
+
+**Tool**: Vitest + Miniflare (Cloudflare Workers simulator)
+
+**What to test**:
+- API routes (`/api/*`)
+- Middleware (auth, CORS, error handling)
+- Database operations (CRUD)
+
+**Setup**:
+```typescript
+// tests/setup.ts
+import { beforeAll, afterAll, beforeEach } from 'vitest'
+import { env, createExecutionContext, waitOnExecutionContext } from 'cloudflare:test'
+
+beforeAll(async () => {
+ // Setup test database
+ await env.DB.exec('CREATE TABLE IF NOT EXISTS users (...)')
+})
+
+beforeEach(async () => {
+ // Clear database before each test
+ await env.DB.exec('DELETE FROM users')
+})
+
+afterAll(async () => {
+ // Cleanup
+})
+```
+
+**Example Test**:
+```typescript
+// tests/api/tasks.test.ts
+import { describe, it, expect } from 'vitest'
+import app from '../../src/index'
+
+describe('POST /api/tasks', () => {
+ it('creates a task for authenticated user', async () => {
+ const res = await app.request('/api/tasks', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': 'Bearer valid_jwt_token'
+ },
+ body: JSON.stringify({
+ title: 'Test Task',
+ description: 'Test Description'
+ })
+ })
+
+ expect(res.status).toBe(201)
+ const data = await res.json()
+ expect(data.title).toBe('Test Task')
+ })
+
+ it('returns 401 without auth', async () => {
+ const res = await app.request('/api/tasks', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ title: 'Test' })
+ })
+
+ expect(res.status).toBe(401)
+ })
+
+ it('returns 400 with invalid data', async () => {
+ const res = await app.request('/api/tasks', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': 'Bearer valid_jwt_token'
+ },
+ body: JSON.stringify({
+ title: '' // invalid: empty title
+ })
+ })
+
+ expect(res.status).toBe(400)
+ })
+})
+```
+
+**Run**: `npm run test`
+
+---
+
+### 3. E2E Tests (Few) - Optional
+
+**Purpose**: Test complete user workflows in real browser
+
+**Tool**: Playwright
+
+**What to test**:
+- Authentication flow (sign up, sign in, sign out)
+- Main CRUD workflows
+- Critical paths (payments, exports, etc)
+
+**Setup**:
+```bash
+npm install -D @playwright/test
+npx playwright install
+```
+
+**Example Test**:
+```typescript
+// e2e/auth.spec.ts
+import { test, expect } from '@playwright/test'
+
+test('user can sign in and create a task', async ({ page }) => {
+ // Sign in
+ await page.goto('http://localhost:5173')
+ await page.click('text=Sign In')
+ await page.fill('input[name="email"]', '[email protected]')
+ await page.fill('input[name="password"]', 'password123')
+ await page.click('button[type="submit"]')
+
+ // Wait for redirect to dashboard
+ await expect(page).toHaveURL(/\/dashboard/)
+
+ // Create task
+ await page.click('text=Create Task')
+ await page.fill('input[name="title"]', 'New Task')
+ await page.fill('textarea[name="description"]', 'Task description')
+ await page.click('button:has-text("Save")')
+
+ // Verify task appears
+ await expect(page.locator('text=New Task')).toBeVisible()
+})
+```
+
+**Run**: `npm run test:e2e`
+
+---
+
+## Test Coverage
+
+**Target Coverage**: 70%+ for critical code
+
+**What to cover**:
+- ✅ All API routes
+- ✅ All middleware
+- ✅ Business logic and utilities
+- ✅ Zod schemas (validation tests)
+- ⚠️ React components (optional - prefer E2E for UI)
+
+**Generate Coverage Report**:
+```bash
+npm run test -- --coverage
+```
+
+**View Report**: `coverage/index.html`
+
+---
+
+## Testing Checklist
+
+Before marking a phase complete, verify:
+
+### API Phase
+- [ ] All endpoints return correct status codes (200, 400, 401, 404, 500)
+- [ ] Request validation works (invalid data → 400)
+- [ ] Authorization works (no token → 401, wrong user → 403)
+- [ ] Database operations succeed
+- [ ] Error handling catches exceptions
+
+### UI Phase
+- [ ] Forms validate input (Zod schemas)
+- [ ] Forms show error messages
+- [ ] Loading states display correctly
+- [ ] Error states display correctly
+- [ ] Happy path works (create, read, update, delete)
+
+### Integration Phase
+- [ ] Third-party service integration works
+- [ ] Webhooks fire correctly
+- [ ] Error handling for external failures
+
+---
+
+## Manual Testing
+
+**Automated tests don't catch everything**. Manually test:
+
+### Before Each Deployment
+- [ ] Sign in works
+- [ ] Main workflows work (create, edit, delete)
+- [ ] Forms validate correctly
+- [ ] Errors display properly
+- [ ] Dark/light mode works
+- [ ] Mobile layout works
+
+### Smoke Test Checklist
+```
+1. Visit homepage → Should load
+2. Click Sign In → Should show Clerk modal
+3. Sign in → Should redirect to dashboard
+4. Create [resource] → Should appear in list
+5. Edit [resource] → Changes should save
+6. Delete [resource] → Should remove from list
+7. Sign out → Should return to homepage
+```
+
+---
+
+## Continuous Integration (CI)
+
+**GitHub Actions** (optional):
+
+```yaml
+# .github/workflows/test.yml
+name: Tests
+
+on: [push, pull_request]
+
+jobs:
+ test:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v3
+ - uses: actions/setup-node@v3
+ with:
+ node-version: 18
+ - run: npm install
+ - run: npm run test
+ - run: npm run build
+```
+
+**Run tests on**:
+- Every push
+- Every pull request
+- Before deployment
+
+---
+
+## Test Data
+
+### Seed Data for Testing
+
+Create `migrations/seed.sql` with realistic test data:
+
+```sql
+INSERT INTO users (email, clerk_id, display_name, created_at, updated_at)
+VALUES
+ ('[email protected]', 'clerk_alice', 'Alice', strftime('%s', 'now'), strftime('%s', 'now')),
+ ('[email protected]', 'clerk_bob', 'Bob', strftime('%s', 'now'), strftime('%s', 'now'));
+
+INSERT INTO tasks (user_id, title, description, created_at, updated_at)
+VALUES
+ (1, 'Review PR', 'Review the new feature PR', strftime('%s', 'now'), strftime('%s', 'now')),
+ (1, 'Write tests', 'Add tests for API endpoints', strftime('%s', 'now'), strftime('%s', 'now')),
+ (2, 'Deploy app', 'Deploy to production', strftime('%s', 'now'), strftime('%s', 'now'));
+```
+
+**Load seed data**:
+```bash
+npx wrangler d1 execute [DB_NAME] --local --file=migrations/seed.sql
+```
+
+---
+
+## Testing Tools
+
+### Installed
+- **Vitest**: Unit and integration tests
+- **@cloudflare/vitest-pool-workers**: Test Workers in Miniflare
+- **@vitest/coverage-v8**: Code coverage
+
+### Optional
+- **Playwright**: E2E browser testing
+- **@testing-library/react**: React component testing (if needed)
+- **MSW**: Mock Service Worker (mock external APIs)
+
+---
+
+## Test Scripts
+
+**package.json**:
+```json
+{
+ "scripts": {
+ "test": "vitest",
+ "test:ui": "vitest --ui",
+ "test:coverage": "vitest --coverage",
+ "test:e2e": "playwright test"
+ }
+}
+```
+
+**Run tests**:
+```bash
+npm run test # Run all tests (watch mode)
+npm run test:coverage # Generate coverage report
+npm run test:e2e # Run E2E tests (Playwright)
+```
+
+---
+
+## Debugging Tests
+
+**Vitest UI** (visual test runner):
+```bash
+npm run test:ui
+```
+
+**Debug single test**:
+```typescript
+it.only('specific test', () => {
+ // Only this test runs
+})
+```
+
+**Console logs in tests**: They appear in terminal output
+
+**Playwright debug mode**:
+```bash
+npx playwright test --debug
+```
+
+---
+
+## Testing Best Practices
+
+### ✅ Do
+
+- **Arrange, Act, Assert** - Structure tests clearly
+- **One assertion per test** (when possible)
+- **Descriptive test names** - "should return 401 when token is missing"
+- **Test edge cases** - Empty strings, null values, large numbers
+- **Use realistic data** - Test with production-like data
+
+### ❌ Don't
+
+- **Test implementation details** - Internal state, private methods
+- **Over-mock** - Use real database in integration tests
+- **Brittle selectors** - Avoid testing specific CSS classes
+- **Flaky tests** - Fix immediately or remove
+- **Slow tests** - Optimize or move to E2E
+
+---
+
+## Test-Driven Development (TDD) - Optional
+
+**For critical features**, consider writing tests first:
+
+1. Write failing test
+2. Implement feature (test passes)
+3. Refactor
+4. Repeat
+
+**Benefits**: Better design, fewer bugs, built-in documentation
+
+**When to use**: Complex business logic, critical paths, bug fixes
+
+---
+
+## Monitoring Test Health
+
+**Metrics to track**:
+- Test pass rate (should be 100%)
+- Test coverage (target 70%+)
+- Test execution time (keep fast)
+- Flaky test count (should be 0)
+
+**Weekly review**:
+- Are tests passing?
+- Is coverage dropping?
+- Are tests slowing down?
+- Any flaky tests to fix?
+
+---
+
+## Future Testing Enhancements
+
+- [ ] Add visual regression testing (if needed)
+- [ ] Add performance testing (if needed)
+- [ ] Add accessibility testing (axe-core)
+- [ ] Add API contract testing (Pact)
+
+---
+
+## Revision History
+
+**v1.0** ([Date]): Initial testing strategy
+**v1.1** ([Date]): [Changes made]
diff --git a/skills/project-planning/templates/UI_COMPONENTS.md b/skills/project-planning/templates/UI_COMPONENTS.md
new file mode 100644
index 00000000..a670224f
--- /dev/null
+++ b/skills/project-planning/templates/UI_COMPONENTS.md
@@ -0,0 +1,653 @@
+# UI Components: [Project Name]
+
+**Framework**: React 19
+**Component Library**: shadcn/ui (Radix UI primitives)
+**Styling**: Tailwind v4
+**Forms**: React Hook Form + Zod
+**State**: TanStack Query (server) + Zustand (client)
+**Last Updated**: [Date]
+
+---
+
+## Overview
+
+This document outlines the component hierarchy, reusable components, forms, and UI patterns.
+
+**Component Philosophy**:
+- **Composition over configuration** - Build complex UIs from simple parts
+- **Accessibility first** - All components keyboard navigable, ARIA compliant
+- **shadcn/ui ownership** - Components copied to codebase, not npm dependency
+- **Tailwind utility classes** - Minimal custom CSS
+- **Dark mode support** - All components adapt to theme
+
+---
+
+## Component Hierarchy
+
+```
+App
+├── Providers
+│ ├── ClerkProvider (auth)
+│ ├── ThemeProvider (dark/light mode)
+│ └── QueryClientProvider (TanStack Query)
+│
+├── Layout
+│ ├── Header
+│ │ ├── Logo
+│ │ ├── Navigation
+│ │ └── UserMenu
+│ ├── Main (page content)
+│ └── Footer (optional)
+│
+└── Pages (routes)
+ ├── HomePage
+ │ ├── HeroSection
+ │ ├── FeaturesSection
+ │ └── CTASection
+ │
+ ├── DashboardPage
+ │ ├── Sidebar
+ │ │ └── NavLinks
+ │ └── DashboardContent
+ │ ├── StatsCards
+ │ └── [ResourceList]
+ │
+ ├── [Resource]Page
+ │ ├── [Resource]List
+ │ │ ├── [Resource]Card (for each item)
+ │ │ └── Pagination
+ │ └── [Resource]CreateDialog
+ │
+ └── [Resource]DetailPage
+ ├── [Resource]Header
+ ├── [Resource]Info
+ └── [Resource]Actions
+```
+
+---
+
+## Core Layout Components
+
+### `App.tsx`
+**Purpose**: Root component with providers
+
+**Structure**:
+```tsx
+import { ClerkProvider } from '@clerk/clerk-react'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { ThemeProvider } from '@/components/theme-provider'
+import { Router } from '@/router'
+
+const queryClient = new QueryClient()
+
+export function App() {
+ return (
+ <ClerkProvider publishableKey={...}>
+ <QueryClientProvider client={queryClient}>
+ <ThemeProvider defaultTheme="system" storageKey="app-theme">
+ <Router />
+ </ThemeProvider>
+ </QueryClientProvider>
+ </ClerkProvider>
+ )
+}
+```
+
+---
+
+### `Layout.tsx`
+**Purpose**: Common layout wrapper for authenticated pages
+
+**Props**: None (uses `Outlet` from react-router)
+
+**Structure**:
+```tsx
+export function Layout() {
+ return (
+ <div className="min-h-screen bg-background">
+ <Header />
+ <main className="container mx-auto px-4 py-8">
+ <Outlet />
+ </main>
+ <Footer />
+ </div>
+ )
+}
+```
+
+**Files**: `src/components/layout/Layout.tsx`, `Header.tsx`, `Footer.tsx`
+
+---
+
+### `Header.tsx`
+**Purpose**: Top navigation bar
+
+**Features**:
+- Logo/brand
+- Navigation links
+- User menu (authenticated) or Sign In button (unauthenticated)
+- Theme toggle (dark/light mode)
+
+**Structure**:
+```tsx
+export function Header() {
+ return (
+ <header className="border-b bg-background">
+ <div className="container mx-auto flex h-16 items-center justify-between px-4">
+ <div className="flex items-center gap-6">
+ <Logo />
+ <Navigation />
+ </div>
+ <div className="flex items-center gap-4">
+ <ThemeToggle />
+ <UserButton />
+ </div>
+ </div>
+ </header>
+ )
+}
+```
+
+**Files**: `src/components/layout/Header.tsx`
+
+---
+
+## shadcn/ui Components Used
+
+### Installed Components
+Run these to add components:
+```bash
+pnpm dlx shadcn@latest add button
+pnpm dlx shadcn@latest add dialog
+pnpm dlx shadcn@latest add dropdown-menu
+pnpm dlx shadcn@latest add form
+pnpm dlx shadcn@latest add input
+pnpm dlx shadcn@latest add label
+pnpm dlx shadcn@latest add select
+pnpm dlx shadcn@latest add textarea
+pnpm dlx shadcn@latest add card
+pnpm dlx shadcn@latest add badge
+pnpm dlx shadcn@latest add avatar
+pnpm dlx shadcn@latest add skeleton
+pnpm dlx shadcn@latest add toast
+```
+
+**Location**: `src/components/ui/`
+
+**Ownership**: These are now part of our codebase, modify as needed
+
+---
+
+## Custom Components
+
+### `[Resource]List.tsx`
+**Purpose**: Display list of [resources] with loading/error states
+
+**Props**:
+```typescript
+interface [Resource]ListProps {
+ // No props - uses TanStack Query internally
+}
+```
+
+**Structure**:
+```tsx
+export function [Resource]List() {
+ const { data, isLoading, error } = useQuery({
+ queryKey: ['[resources]'],
+ queryFn: fetch[Resources]
+ })
+
+ if (isLoading) return <[Resource]ListSkeleton />
+ if (error) return <ErrorMessage error={error} />
+
+ return (
+ <div className="space-y-4">
+ {data.map(item => (
+ <[Resource]Card key={item.id} item={item} />
+ ))}
+ </div>
+ )
+}
+```
+
+**Files**: `src/components/[resource]/[Resource]List.tsx`
+
+---
+
+### `[Resource]Card.tsx`
+**Purpose**: Display single [resource] item
+
+**Props**:
+```typescript
+interface [Resource]CardProps {
+ item: [Resource]
+ onEdit?: (id: number) => void
+ onDelete?: (id: number) => void
+}
+```
+
+**Structure**:
+```tsx
+export function [Resource]Card({ item, onEdit, onDelete }: [Resource]CardProps) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{item.title}</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <p>{item.description}</p>
+ </CardContent>
+ <CardFooter>
+ <Button onClick={() => onEdit?.(item.id)}>Edit</Button>
+ <Button variant="destructive" onClick={() => onDelete?.(item.id)}>Delete</Button>
+ </CardFooter>
+ </Card>
+ )
+}
+```
+
+**Files**: `src/components/[resource]/[Resource]Card.tsx`
+
+---
+
+### `[Resource]Form.tsx`
+**Purpose**: Create or edit [resource]
+
+**Props**:
+```typescript
+interface [Resource]FormProps {
+ item?: [Resource] // undefined for create, populated for edit
+ onSuccess?: () => void
+}
+```
+
+**Structure** (using React Hook Form + Zod):
+```tsx
+import { useForm } from 'react-hook-form'
+import { zodResolver } from '@hookform/resolvers/zod'
+import { [resource]Schema } from '@/lib/schemas'
+
+export function [Resource]Form({ item, onSuccess }: [Resource]FormProps) {
+ const form = useForm({
+ resolver: zodResolver([resource]Schema),
+ defaultValues: item || {
+ field1: '',
+ field2: ''
+ }
+ })
+
+ const mutation = useMutation({
+ mutationFn: item ? update[Resource] : create[Resource],
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['[resources]'] })
+ onSuccess?.()
+ }
+ })
+
+ return (
+ <Form {...form}>
+ <form onSubmit={form.handleSubmit(data => mutation.mutate(data))}>
+ <FormField name="field1" control={form.control} render={({ field }) => (
+ <FormItem>
+ <FormLabel>Field 1</FormLabel>
+ <FormControl>
+ <Input {...field} />
+ </FormControl>
+ <FormMessage />
+ </FormItem>
+ )} />
+
+ <Button type="submit" disabled={mutation.isPending}>
+ {mutation.isPending ? 'Saving...' : 'Save'}
+ </Button>
+ </form>
+ </Form>
+ )
+}
+```
+
+**Files**: `src/components/[resource]/[Resource]Form.tsx`
+
+---
+
+### `[Resource]CreateDialog.tsx`
+**Purpose**: Modal dialog for creating new [resource]
+
+**Structure**:
+```tsx
+export function [Resource]CreateDialog() {
+ const [open, setOpen] = useState(false)
+
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogTrigger asChild>
+ <Button>Create [Resource]</Button>
+ </DialogTrigger>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>Create New [Resource]</DialogTitle>
+ </DialogHeader>
+ <[Resource]Form onSuccess={() => setOpen(false)} />
+ </DialogContent>
+ </Dialog>
+ )
+}
+```
+
+**Files**: `src/components/[resource]/[Resource]CreateDialog.tsx`
+
+---
+
+## Loading and Error States
+
+### `[Resource]ListSkeleton.tsx`
+**Purpose**: Loading state for [resource] list
+
+**Structure**:
+```tsx
+export function [Resource]ListSkeleton() {
+ return (
+ <div className="space-y-4">
+ {[1, 2, 3].map(i => (
+ <Card key={i}>
+ <CardHeader>
+ <Skeleton className="h-6 w-48" />
+ </CardHeader>
+ <CardContent>
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-3/4 mt-2" />
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ )
+}
+```
+
+---
+
+### `ErrorMessage.tsx`
+**Purpose**: Reusable error display
+
+**Props**:
+```typescript
+interface ErrorMessageProps {
+ error: Error
+ retry?: () => void
+}
+```
+
+**Structure**:
+```tsx
+export function ErrorMessage({ error, retry }: ErrorMessageProps) {
+ return (
+ <div className="rounded-lg border border-destructive bg-destructive/10 p-4">
+ <h3 className="font-semibold text-destructive">Error</h3>
+ <p className="text-sm text-muted-foreground">{error.message}</p>
+ {retry && (
+ <Button variant="outline" onClick={retry} className="mt-2">
+ Retry
+ </Button>
+ )}
+ </div>
+ )
+}
+```
+
+---
+
+## State Management Patterns
+
+### Server State (TanStack Query)
+
+**Use for**: Data from API (users, tasks, analytics, etc)
+
+**Example**:
+```tsx
+// In component
+const { data, isLoading, error } = useQuery({
+ queryKey: ['tasks'],
+ queryFn: () => api.get('/api/tasks').then(res => res.data)
+})
+
+// Mutation
+const mutation = useMutation({
+ mutationFn: (newTask) => api.post('/api/tasks', newTask),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ['tasks'] })
+ }
+})
+```
+
+**Files**: Queries/mutations defined in `src/lib/api.ts` or component files
+
+---
+
+### Client State (Zustand)
+
+**Use for**: UI state, preferences, filters
+
+**Example Store**:
+```tsx
+// src/stores/ui-store.ts
+import { create } from 'zustand'
+import { persist } from 'zustand/middleware'
+
+interface UIStore {
+ sidebarOpen: boolean
+ setSidebarOpen: (open: boolean) => void
+ theme: 'light' | 'dark' | 'system'
+ setTheme: (theme: 'light' | 'dark' | 'system') => void
+}
+
+export const useUIStore = create<UIStore>()(
+ persist(
+ (set) => ({
+ sidebarOpen: true,
+ setSidebarOpen: (open) => set({ sidebarOpen: open }),
+ theme: 'system',
+ setTheme: (theme) => set({ theme })
+ }),
+ { name: 'ui-store' }
+ )
+)
+```
+
+**Usage**:
+```tsx
+const { sidebarOpen, setSidebarOpen } = useUIStore()
+```
+
+---
+
+## Theme System
+
+### ThemeProvider
+**Purpose**: Manage dark/light/system theme
+
+**Structure**:
+```tsx
+// src/components/theme-provider.tsx
+export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
+ return (
+ <NextThemesProvider
+ attribute="class"
+ defaultTheme="system"
+ enableSystem
+ disableTransitionOnChange
+ {...props}
+ >
+ {children}
+ </NextThemesProvider>
+ )
+}
+
+export function useTheme() {
+ return useNextTheme()
+}
+```
+
+**Files**: `src/components/theme-provider.tsx`
+
+---
+
+### ThemeToggle
+**Purpose**: Toggle between light/dark/system themes
+
+**Structure**:
+```tsx
+export function ThemeToggle() {
+ const { theme, setTheme } = useTheme()
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="icon">
+ <Sun className="rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
+ <Moon className="absolute rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem onClick={() => setTheme('light')}>Light</DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setTheme('dark')}>Dark</DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setTheme('system')}>System</DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
+```
+
+---
+
+## Form Patterns
+
+All forms use **React Hook Form + Zod** for validation.
+
+**Schema Definition** (shared client + server):
+```typescript
+// src/lib/schemas.ts
+import { z } from 'zod'
+
+export const taskSchema = z.object({
+ title: z.string().min(1, 'Title required').max(100),
+ description: z.string().optional(),
+ dueDate: z.string().optional(),
+ priority: z.enum(['low', 'medium', 'high']).default('medium')
+})
+
+export type TaskFormData = z.infer<typeof taskSchema>
+```
+
+**Form Component**:
+```tsx
+const form = useForm<TaskFormData>({
+ resolver: zodResolver(taskSchema),
+ defaultValues: { ... }
+})
+```
+
+---
+
+## Responsive Design
+
+**Breakpoints** (Tailwind defaults):
+- `sm`: 640px
+- `md`: 768px
+- `lg`: 1024px
+- `xl`: 1280px
+- `2xl`: 1536px
+
+**Patterns**:
+```tsx
+// Stack on mobile, grid on desktop
+<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
+
+// Hide on mobile, show on desktop
+<div className="hidden md:block">
+
+// Different padding on mobile vs desktop
+<div className="px-4 md:px-8">
+```
+
+---
+
+## Accessibility
+
+**Requirements**:
+- All interactive elements keyboard navigable
+- Focus states visible (use `ring` classes)
+- Images have alt text
+- Forms have associated labels
+- Color contrast meets WCAG AA
+- Screen reader friendly (ARIA labels)
+
+**shadcn/ui benefits**: All components built with Radix UI (accessible by default)
+
+---
+
+## File Structure
+
+```
+src/
+├── components/
+│ ├── ui/ # shadcn/ui components
+│ │ ├── button.tsx
+│ │ ├── dialog.tsx
+│ │ ├── form.tsx
+│ │ └── ...
+│ ├── layout/ # Layout components
+│ │ ├── Header.tsx
+│ │ ├── Footer.tsx
+│ │ └── Layout.tsx
+│ ├── [resource]/ # Feature-specific components
+│ │ ├── [Resource]List.tsx
+│ │ ├── [Resource]Card.tsx
+│ │ ├── [Resource]Form.tsx
+│ │ └── [Resource]CreateDialog.tsx
+│ ├── theme-provider.tsx
+│ └── error-message.tsx
+├── lib/
+│ ├── schemas.ts # Zod schemas
+│ ├── api.ts # API client
+│ └── utils.ts # cn() helper
+├── stores/
+│ └── ui-store.ts # Zustand stores
+└── pages/
+ ├── HomePage.tsx
+ ├── DashboardPage.tsx
+ └── ...
+```
+
+---
+
+## Design Tokens
+
+See `src/index.css` for theme configuration.
+
+**Colors** (semantic):
+- `background` / `foreground`
+- `primary` / `primary-foreground`
+- `secondary` / `secondary-foreground`
+- `destructive` / `destructive-foreground`
+- `muted` / `muted-foreground`
+- `accent` / `accent-foreground`
+- `border`
+- `ring`
+
+**Usage**: These adapt to light/dark mode automatically.
+
+---
+
+## Future Components
+
+Components to build:
+- [ ] `[Component]` - [Description]
+- [ ] `[Component]` - [Description]
+
+---
+
+## Revision History
+
+**v1.0** ([Date]): Initial component structure
+**v1.1** ([Date]): [Changes made]