From 11bf31837f8c1c0ee2458dd8f859e2bc902e8530 Mon Sep 17 00:00:00 2001 From: Muhammad Shariq Baig Date: Tue, 30 Sep 2025 12:24:49 +0500 Subject: [PATCH] Added agent teams, checklists, tasks --- .../DOCUMENTATION/README.md | 87 +- .../DOCUMENTATION/user-guide.md | 2307 +++++++++++++++++ .../agent-teams/backend-team.yaml | 15 + .../agent-teams/frontend-team.yaml | 14 + .../agent-teams/fullstack-team.yaml | 17 + .../checklists/api-design-checklist.md | 62 + .../architecture-review-checklist.md | 182 ++ .../checklists/backend-checklist.md | 121 + .../deployment-readiness-checklist.md | 105 + .../checklists/frontend-checklist.md | 98 + .../checklists/performance-checklist.md | 120 + .../checklists/security-checklist.md | 118 + .../checklists/story-dod-checklist.md | 82 + .../javascript-fullstack-pack/config.yaml | 10 + .../data/architecture-patterns.md | 180 ++ .../data/best-practices.md | 194 ++ .../data/deployment-strategies.md | 306 +++ .../data/development-guidelines.md | 355 +++ .../data/security-guidelines.md | 210 ++ .../data/technology-stack-guide.md | 175 ++ .../javascript-fullstack-pack/package.json | 6 + .../tasks/code-review.md | 144 + .../tasks/create-api-spec.md | 96 + .../tasks/create-architecture-doc.md | 112 + .../tasks/create-development-story.md | 225 ++ .../tasks/performance-optimization.md | 241 ++ .../tasks/setup-project.md | 199 ++ .../workflows/backend-api-development.yaml | 48 + .../workflows/feature-development.yaml | 52 + .../workflows/frontend-app-development.yaml | 41 + .../workflows/fullstack-greenfield.yaml | 211 ++ .../workflows/migration-to-typescript.yaml | 86 + .../workflows/mvp-rapid-prototype.yaml | 66 + 33 files changed, 6244 insertions(+), 41 deletions(-) create mode 100644 expansion-packs/javascript-fullstack-pack/DOCUMENTATION/user-guide.md create mode 100644 expansion-packs/javascript-fullstack-pack/agent-teams/backend-team.yaml create mode 100644 expansion-packs/javascript-fullstack-pack/agent-teams/frontend-team.yaml create mode 100644 expansion-packs/javascript-fullstack-pack/agent-teams/fullstack-team.yaml create mode 100644 expansion-packs/javascript-fullstack-pack/checklists/api-design-checklist.md create mode 100644 expansion-packs/javascript-fullstack-pack/checklists/architecture-review-checklist.md create mode 100644 expansion-packs/javascript-fullstack-pack/checklists/backend-checklist.md create mode 100644 expansion-packs/javascript-fullstack-pack/checklists/deployment-readiness-checklist.md create mode 100644 expansion-packs/javascript-fullstack-pack/checklists/frontend-checklist.md create mode 100644 expansion-packs/javascript-fullstack-pack/checklists/performance-checklist.md create mode 100644 expansion-packs/javascript-fullstack-pack/checklists/security-checklist.md create mode 100644 expansion-packs/javascript-fullstack-pack/checklists/story-dod-checklist.md create mode 100644 expansion-packs/javascript-fullstack-pack/config.yaml create mode 100644 expansion-packs/javascript-fullstack-pack/data/architecture-patterns.md create mode 100644 expansion-packs/javascript-fullstack-pack/data/best-practices.md create mode 100644 expansion-packs/javascript-fullstack-pack/data/deployment-strategies.md create mode 100644 expansion-packs/javascript-fullstack-pack/data/development-guidelines.md create mode 100644 expansion-packs/javascript-fullstack-pack/data/security-guidelines.md create mode 100644 expansion-packs/javascript-fullstack-pack/data/technology-stack-guide.md create mode 100644 expansion-packs/javascript-fullstack-pack/tasks/code-review.md create mode 100644 expansion-packs/javascript-fullstack-pack/tasks/create-api-spec.md create mode 100644 expansion-packs/javascript-fullstack-pack/tasks/create-architecture-doc.md create mode 100644 expansion-packs/javascript-fullstack-pack/tasks/create-development-story.md create mode 100644 expansion-packs/javascript-fullstack-pack/tasks/performance-optimization.md create mode 100644 expansion-packs/javascript-fullstack-pack/tasks/setup-project.md create mode 100644 expansion-packs/javascript-fullstack-pack/workflows/backend-api-development.yaml create mode 100644 expansion-packs/javascript-fullstack-pack/workflows/feature-development.yaml create mode 100644 expansion-packs/javascript-fullstack-pack/workflows/frontend-app-development.yaml create mode 100644 expansion-packs/javascript-fullstack-pack/workflows/fullstack-greenfield.yaml create mode 100644 expansion-packs/javascript-fullstack-pack/workflows/migration-to-typescript.yaml create mode 100644 expansion-packs/javascript-fullstack-pack/workflows/mvp-rapid-prototype.yaml diff --git a/expansion-packs/javascript-fullstack-pack/DOCUMENTATION/README.md b/expansion-packs/javascript-fullstack-pack/DOCUMENTATION/README.md index 9054f058..9981c826 100644 --- a/expansion-packs/javascript-fullstack-pack/DOCUMENTATION/README.md +++ b/expansion-packs/javascript-fullstack-pack/DOCUMENTATION/README.md @@ -14,26 +14,18 @@ This expansion pack provides a complete team of AI agents specialized in JavaScr - **Testing**: Jest, Vitest, Cypress, Playwright - **Deployment**: Docker, Kubernetes, Serverless -## Agents Included +## Agents Included (5 Total) ### Planning & Architecture -- **JS Solution Architect**: Designs full-stack JavaScript architectures -- **Frontend Architect**: Specializes in frontend architecture and state management -- **Backend Architect**: Focuses on API design, microservices, and scalability +- **JS Solution Architect**: Designs full-stack JavaScript architectures, technology selection, and system design ### Development Agents -- **React Developer**: Expert in React, Next.js, and modern React patterns -- **Vue Developer**: Specializes in Vue 3, Nuxt, and composition API -- **Node Backend Developer**: Backend development with Express, Fastify, NestJS -- **API Developer**: REST, GraphQL, and modern API patterns -- **Full-Stack Developer**: End-to-end JavaScript development +- **React Developer**: Expert in React 18+, Next.js 14, hooks, and modern state management +- **Node Backend Developer**: Backend development with Express, Fastify, NestJS, and database integration +- **API Developer**: REST, GraphQL, tRPC API design with versioning and documentation ### Specialized Roles -- **TypeScript Expert**: Type safety, advanced types, and migration -- **Performance Engineer**: Optimization, profiling, and monitoring -- **DevOps Engineer**: CI/CD, containerization, and deployment -- **Security Specialist**: Security best practices and vulnerability assessment -- **Testing Engineer**: Test strategy, automation, and quality assurance +- **TypeScript Expert**: Type safety, advanced type patterns, migration strategies, and strict mode configuration ## Installation @@ -123,32 +115,50 @@ npm install bmad-expansion-javascript-fullstack - Migration from JavaScript - Type safety for APIs -## Templates Included +## Structure -### PRD Templates -- `js-fullstack-prd.md`: Full-stack project requirements -- `frontend-app-prd.md`: Frontend application requirements -- `backend-api-prd.md`: Backend API requirements -- `microservices-prd.md`: Microservices architecture requirements +### Agent Teams +- `fullstack-team.yaml`: Complete full-stack development team +- `frontend-team.yaml`: Frontend-focused development team +- `backend-team.yaml`: Backend and API development team -### Architecture Templates -- `fullstack-architecture.md`: Complete stack architecture -- `frontend-architecture.md`: Frontend-specific architecture -- `backend-architecture.md`: Backend system design -- `api-architecture.md`: API design and documentation +### Workflows (6 Total) +- `fullstack-greenfield.yaml`: New full-stack project from scratch +- `frontend-app-development.yaml`: Frontend application workflow +- `backend-api-development.yaml`: Backend API development workflow +- `feature-development.yaml`: Adding features to existing apps +- `mvp-rapid-prototype.yaml`: Fast MVP and prototype development +- `migration-to-typescript.yaml`: JavaScript to TypeScript migration -### Story Templates -- `frontend-feature-story.md`: Frontend feature development -- `backend-endpoint-story.md`: Backend endpoint implementation -- `api-integration-story.md`: API integration work -- `performance-optimization-story.md`: Performance improvements -- `security-enhancement-story.md`: Security implementations +### Checklists (8 Total) +- `architecture-review-checklist.md`: Architecture validation +- `api-design-checklist.md`: API design quality +- `frontend-checklist.md`: React/Next.js quality +- `backend-checklist.md`: Node.js backend quality +- `security-checklist.md`: Security validation +- `performance-checklist.md`: Performance optimization +- `deployment-readiness-checklist.md`: Production deployment +- `story-dod-checklist.md`: Story definition of done -### Workflow Plans -- `fullstack-mvp-workflow.md`: MVP development workflow -- `feature-development-workflow.md`: Adding new features -- `refactoring-workflow.md`: Code refactoring process -- `deployment-workflow.md`: Deployment and release process +### Tasks (6 Total) +- `create-development-story.md`: Story creation guide +- `create-architecture-doc.md`: Architecture documentation +- `create-api-spec.md`: API specification creation +- `setup-project.md`: Project initialization +- `code-review.md`: Code review process +- `performance-optimization.md`: Performance tuning + +### Data/Reference (6 Total) +- `development-guidelines.md`: Coding standards and conventions +- `architecture-patterns.md`: Common architecture patterns +- `best-practices.md`: Full-stack best practices +- `technology-stack-guide.md`: Stack selection guide +- `security-guidelines.md`: Security implementation +- `deployment-strategies.md`: Deployment patterns + +### Templates (2 Total) +- `fullstack-javascript-prd.md`: Comprehensive PRD template +- `javascript-development-story.md`: Detailed story template ## Use Cases @@ -212,14 +222,9 @@ expansion_packs: agents: - js-solution-architect - react-developer - - vue-developer - node-backend-developer - api-developer - typescript-expert - - performance-engineer - - devops-engineer - - security-specialist - - testing-engineer ``` ## Contributing diff --git a/expansion-packs/javascript-fullstack-pack/DOCUMENTATION/user-guide.md b/expansion-packs/javascript-fullstack-pack/DOCUMENTATION/user-guide.md new file mode 100644 index 00000000..b665962a --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/DOCUMENTATION/user-guide.md @@ -0,0 +1,2307 @@ +# JavaScript Full-Stack Expansion Pack — User Guide + +This guide explains how to effectively use the JavaScript Full-Stack Expansion Pack with the BMad Method for building modern JavaScript/TypeScript applications. + +## Overview + +The JavaScript Full-Stack Expansion Pack provides specialized agents, workflows, and templates for: + +- **Frontend Development**: React 18+, Next.js 14, modern state management +- **Backend Development**: Node.js, Express, Fastify, NestJS +- **API Design**: REST, GraphQL, tRPC with versioning and documentation +- **Type Safety**: TypeScript strict mode, advanced patterns, migration +- **Full-Stack Integration**: Coordinated frontend/backend development + +## The JavaScript Full-Stack Workflow + +### Planning Phase: Greenfield Projects + +For new JavaScript/TypeScript projects, follow this specialized planning workflow: + +```mermaid +graph TD + A["Start: New JS Project"] --> B{Optional: Analyst Research} + B -->|Yes| C["Analyst: Brainstorming & Research"] + B -->|No| G{Project Brief Available?} + C --> C2["Analyst: Competitor Analysis"] + C2 --> D["Analyst: Create Project Brief"] + D --> G + G -->|Yes| E["PM: Create PRD (JS Template)"] + G -->|No| E2["PM: Interactive PRD Creation"] + E --> F["PRD with JS-Specific Requirements"] + E2 --> F + + F --> F2{UX Required?} + F2 -->|Yes| F3["UX Expert: Create Frontend Spec"] + F2 -->|No| H["JS Solution Architect: Tech Stack Selection"] + F3 --> H + + H --> H2["JS Solution Architect: Database Schema Design"] + H2 --> H3["JS Solution Architect: API Contract Definition"] + H3 --> H4["JS Solution Architect: System Architecture"] + + H4 --> TS{TypeScript Migration?} + TS -->|Existing JS Codebase| TS2["TypeScript Expert: Migration Strategy"] + TS -->|New Project| I + TS2 --> I["Architect: Complete Architecture Document"] + + I --> Q{Early Test Strategy?} + Q -->|Yes| R["QA: Risk Assessment + Test Strategy"] + Q -->|No| V + R --> V["PO: Master Checklist Validation"] + + V --> J{Documents Aligned?} + J -->|Yes| K["Planning Complete"] + J -->|No| L["PO: Update Epics & Stories"] + L --> M["Update PRD/Architecture"] + M --> V + + K --> N["📁 Switch to IDE"] + N --> O["PO: Shard Documents"] + O --> P["Ready for Development"] + + style A fill:#f5f5f5,color:#000 + style B fill:#e3f2fd,color:#000 + style C fill:#e8f5e9,color:#000 + style C2 fill:#e8f5e9,color:#000 + style D fill:#e8f5e9,color:#000 + style E fill:#fff3e0,color:#000 + style E2 fill:#fff3e0,color:#000 + style F fill:#fff3e0,color:#000 + style F2 fill:#e3f2fd,color:#000 + style F3 fill:#e1f5fe,color:#000 + style G fill:#e3f2fd,color:#000 + style H fill:#f3e5f5,color:#000 + style H2 fill:#f3e5f5,color:#000 + style H3 fill:#f3e5f5,color:#000 + style H4 fill:#f3e5f5,color:#000 + style TS fill:#e3f2fd,color:#000 + style TS2 fill:#f3e5f5,color:#000 + style I fill:#f3e5f5,color:#000 + style Q fill:#e3f2fd,color:#000 + style R fill:#ffd54f,color:#000 + style V fill:#f9ab00,color:#fff + style J fill:#e3f2fd,color:#000 + style K fill:#34a853,color:#fff + style L fill:#f9ab00,color:#fff + style M fill:#fff3e0,color:#000 + style N fill:#1a73e8,color:#fff + style O fill:#f9ab00,color:#fff + style P fill:#34a853,color:#fff +``` + +#### Planning Artifacts (JavaScript Projects) + +```text +PRD → docs/prd.md (uses fullstack-javascript-prd.md template) +Architecture → docs/architecture.md +Tech Stack Decision → docs/architecture/tech-stack-decision.md +Database Schema → docs/architecture/database-schema.md +API Specification → docs/architecture/api-specification.md +Frontend Architecture → docs/architecture/frontend-architecture.md +Backend Architecture → docs/architecture/backend-architecture.md +TypeScript Config → docs/architecture/typescript-configuration.md +Sharded Epics → docs/epics/ +Sharded Stories → docs/stories/ +QA Assessments → docs/qa/assessments/ +QA Gates → docs/qa/gates/ +``` + +### Development Phase: Full-Stack Implementation + +Once planning is complete, follow this development workflow with JavaScript-specific considerations: + +```mermaid +graph TD + A["Development Phase Start"] --> B["SM: Review Previous Story Notes"] + B --> B2["SM: Draft Story from Epic + Architecture"] + B2 --> ST{Story Type?} + + ST -->|Full-Stack Feature| ST1["Include Frontend + Backend + API Tasks"] + ST -->|Frontend Only| ST2["Include React/Next.js Tasks"] + ST -->|Backend Only| ST3["Include Node.js/API Tasks"] + ST -->|TypeScript Migration| ST4["Include Migration Tasks"] + + ST1 --> S + ST2 --> S + ST3 --> S + ST4 --> S + + S{High-Risk Story?} + S -->|Yes| T["QA: *risk + *design"] + S -->|No| B3 + T --> U["Test Strategy Created"] + U --> B3{PO: Validate Story?} + + B3 -->|Yes| B4["PO: Validate Against Architecture"] + B3 -->|Skip| C + B4 --> C{User Approval} + + C -->|Approved| D["Dev: Select Appropriate Agent(s)"] + C -->|Needs Changes| B2 + + D --> D2{Implementation Type?} + D2 -->|Frontend| D3["React Developer: Implement Components"] + D2 -->|Backend| D4["Node Backend Developer: Implement Services"] + D2 -->|API| D5["API Developer: Implement Endpoints"] + D2 -->|Types| D6["TypeScript Expert: Define Types"] + D2 -->|Full-Stack| D7["Coordinate Multiple Agents"] + + D3 --> E + D4 --> E + D5 --> E + D6 --> E + D7 --> E + + E["Dev: Implementation + Tests"] + E --> E2["Frontend: Component Tests + E2E"] + E2 --> E3["Backend: Unit Tests + Integration Tests"] + E3 --> E4["API: Contract Tests + Documentation"] + E4 --> E5["TypeScript: Type Checking"] + + E5 --> V{Mid-Dev QA Check?} + V -->|Yes| W["QA: *trace or *nfr"] + V -->|No| F + W --> X["Dev: Address Gaps"] + X --> F + + F["Dev: Run All Validations"] + F --> F2["✓ TypeScript: tsc --noEmit"] + F2 --> F3["✓ Linting: ESLint"] + F3 --> F4["✓ Tests: Unit + Integration + E2E"] + F4 --> F5["✓ Build: Frontend + Backend"] + F5 --> F6["✓ Checklists: Frontend/Backend/API"] + + F6 --> G["Dev: Mark Ready for Review + Notes"] + G --> H{User Verification} + + H -->|Request QA Review| I["QA: Full Test Architecture Review"] + H -->|Approve Without QA| M + I --> J["QA: Requirements Tracing + Refactoring"] + J --> L{QA Decision} + + L -->|Needs Dev Work| D + L -->|Approved| M + H -->|Needs Fixes| D + + M["CRITICAL: Verify Tests + Linting Pass"] + M --> M2["CRITICAL: Test on Dev Environment"] + M2 --> N["CRITICAL: COMMIT CHANGES!"] + + N --> Y{Gate Update?} + Y -->|Yes| Z["QA: *gate to Update Status"] + Y -->|No| K + Z --> K["Mark Story Complete"] + K --> K2["Update Story Status in Epic"] + K2 --> B + + style A fill:#f5f5f5,color:#000 + style B fill:#e8f5e9,color:#000 + style B2 fill:#e8f5e9,color:#000 + style ST fill:#e3f2fd,color:#000 + style ST1 fill:#bbdefb,color:#000 + style ST2 fill:#c8e6c9,color:#000 + style ST3 fill:#fff9c4,color:#000 + style ST4 fill:#f8bbd0,color:#000 + style S fill:#e3f2fd,color:#000 + style T fill:#ffd54f,color:#000 + style U fill:#ffd54f,color:#000 + style B3 fill:#e3f2fd,color:#000 + style B4 fill:#fce4ec,color:#000 + style C fill:#e3f2fd,color:#000 + style D fill:#e3f2fd,color:#000 + style D2 fill:#e3f2fd,color:#000 + style D3 fill:#c8e6c9,color:#000 + style D4 fill:#fff9c4,color:#000 + style D5 fill:#ffecb3,color:#000 + style D6 fill:#f8bbd0,color:#000 + style D7 fill:#bbdefb,color:#000 + style E fill:#e3f2fd,color:#000 + style E2 fill:#c8e6c9,color:#000 + style E3 fill:#fff9c4,color:#000 + style E4 fill:#ffecb3,color:#000 + style E5 fill:#f8bbd0,color:#000 + style V fill:#e3f2fd,color:#000 + style W fill:#ffd54f,color:#000 + style X fill:#e3f2fd,color:#000 + style F fill:#e3f2fd,color:#000 + style F2 fill:#e1f5fe,color:#000 + style F3 fill:#e1f5fe,color:#000 + style F4 fill:#e1f5fe,color:#000 + style F5 fill:#e1f5fe,color:#000 + style F6 fill:#e1f5fe,color:#000 + style G fill:#e3f2fd,color:#000 + style H fill:#e3f2fd,color:#000 + style I fill:#f9ab00,color:#fff + style J fill:#ffd54f,color:#000 + style K fill:#34a853,color:#fff + style K2 fill:#34a853,color:#fff + style L fill:#e3f2fd,color:#000 + style M fill:#ff5722,color:#fff + style M2 fill:#ff5722,color:#fff + style N fill:#d32f2f,color:#fff + style Y fill:#e3f2fd,color:#000 + style Z fill:#ffd54f,color:#000 +``` + +### Feature Development Workflow + +For adding features to existing JavaScript applications: + +```mermaid +graph TD + A["New Feature Request"] --> B["Analyst: Gather Requirements"] + B --> C["PM: Document Feature Requirements"] + C --> D["JS Solution Architect: Assess Impact"] + + D --> D2{Impact Analysis} + D2 -->|Frontend Changes| D3["Identify Affected Components"] + D2 -->|Backend Changes| D4["Identify Affected Services"] + D2 -->|API Changes| D5["API Versioning Strategy"] + D2 -->|Database Changes| D6["Schema Migration Plan"] + + D3 --> E + D4 --> E + D5 --> E + D6 --> E + + E["Create Technical Specification"] + E --> E2["Define TypeScript Interfaces"] + E2 --> E3["Document API Changes"] + E3 --> E4["Plan Test Strategy"] + + E4 --> F["SM: Create Feature Stories"] + F --> F2{Story Priority} + + F2 -->|P0: Critical| G["Implement Immediately"] + F2 -->|P1: Important| H["Schedule in Sprint"] + F2 -->|P2: Nice-to-Have| I["Backlog"] + + G --> J["Development Cycle"] + H --> J + I --> K["End"] + + J --> J2["Frontend: React Developer"] + J2 --> J3["Backend: Node Backend Developer"] + J3 --> J4["API: API Developer"] + J4 --> J5["Types: TypeScript Expert"] + + J5 --> L["Integration Testing"] + L --> M["Deploy to Staging"] + M --> N["QA Validation"] + N --> O{Tests Pass?} + + O -->|Yes| P["Deploy to Production"] + O -->|No| J + + P --> Q["Monitor Metrics"] + Q --> K + + style A fill:#f5f5f5,color:#000 + style B fill:#e8f5e9,color:#000 + style C fill:#fff3e0,color:#000 + style D fill:#f3e5f5,color:#000 + style D2 fill:#e3f2fd,color:#000 + style D3 fill:#c8e6c9,color:#000 + style D4 fill:#fff9c4,color:#000 + style D5 fill:#ffecb3,color:#000 + style D6 fill:#f8bbd0,color:#000 + style E fill:#e3f2fd,color:#000 + style E2 fill:#f8bbd0,color:#000 + style E3 fill:#ffecb3,color:#000 + style E4 fill:#ffd54f,color:#000 + style F fill:#e8f5e9,color:#000 + style F2 fill:#e3f2fd,color:#000 + style G fill:#ff5722,color:#fff + style H fill:#ff9800,color:#fff + style I fill:#9e9e9e,color:#fff + style J fill:#e3f2fd,color:#000 + style J2 fill:#c8e6c9,color:#000 + style J3 fill:#fff9c4,color:#000 + style J4 fill:#ffecb3,color:#000 + style J5 fill:#f8bbd0,color:#000 + style L fill:#e3f2fd,color:#000 + style M fill:#bbdefb,color:#000 + style N fill:#ffd54f,color:#000 + style O fill:#e3f2fd,color:#000 + style P fill:#34a853,color:#fff + style Q fill:#1a73e8,color:#fff + style K fill:#34a853,color:#fff +``` + +### TypeScript Migration Workflow + +For migrating existing JavaScript codebases to TypeScript: + +```mermaid +graph TD + A["Start: JS Codebase"] --> B["TypeScript Expert: Assess Codebase"] + B --> B2["Estimate Effort & Complexity"] + B2 --> C["Create Migration Strategy"] + + C --> D["Phase 1: Setup TypeScript"] + D --> D2["Configure tsconfig.json (allowJs: true)"] + D2 --> D3["Install @types packages"] + D3 --> D4["Add Type Definitions"] + + D4 --> E["Phase 2: Incremental Conversion"] + E --> E2{File Selection Strategy} + + E2 -->|Bottom-Up| E3["Convert Utilities First"] + E2 -->|Top-Down| E4["Convert Entry Points First"] + E2 -->|Risk-Based| E5["Convert Critical Paths First"] + + E3 --> F + E4 --> F + E5 --> F + + F["Convert Files in Batches (5-10 files)"] + F --> F2["Run Tests After Each Batch"] + F2 --> F3{Tests Pass?} + + F3 -->|Yes| G["Commit Changes"] + F3 -->|No| F4["Fix Issues"] + F4 --> F2 + + G --> H{More Files?} + H -->|Yes| F + H -->|No| I["Phase 3: Enable Strict Mode"] + + I --> I2["Enable noImplicitAny"] + I2 --> I3["Fix Errors"] + I3 --> I4["Enable strictNullChecks"] + I4 --> I5["Fix Errors"] + I5 --> I6["Enable All Strict Flags"] + I6 --> I7["Fix Remaining Errors"] + + I7 --> J["Phase 4: Refinement"] + J --> J2["Replace 'any' with Proper Types"] + J2 --> J3["Add Generics Where Appropriate"] + J3 --> J4["Document Complex Types"] + + J4 --> K["Migration Complete"] + K --> L["Update Documentation"] + L --> M["Train Team on TypeScript"] + M --> N["Establish TypeScript Standards"] + + style A fill:#f5f5f5,color:#000 + style B fill:#f8bbd0,color:#000 + style B2 fill:#f8bbd0,color:#000 + style C fill:#f3e5f5,color:#000 + style D fill:#e1f5fe,color:#000 + style D2 fill:#e1f5fe,color:#000 + style D3 fill:#e1f5fe,color:#000 + style D4 fill:#e1f5fe,color:#000 + style E fill:#fff3e0,color:#000 + style E2 fill:#e3f2fd,color:#000 + style E3 fill:#c8e6c9,color:#000 + style E4 fill:#fff9c4,color:#000 + style E5 fill:#ffecb3,color:#000 + style F fill:#e3f2fd,color:#000 + style F2 fill:#ffd54f,color:#000 + style F3 fill:#e3f2fd,color:#000 + style F4 fill:#ff5722,color:#fff + style G fill:#34a853,color:#fff + style H fill:#e3f2fd,color:#000 + style I fill:#fff3e0,color:#000 + style I2 fill:#ffecb3,color:#000 + style I3 fill:#e3f2fd,color:#000 + style I4 fill:#ffecb3,color:#000 + style I5 fill:#e3f2fd,color:#000 + style I6 fill:#ffecb3,color:#000 + style I7 fill:#e3f2fd,color:#000 + style J fill:#c8e6c9,color:#000 + style J2 fill:#c8e6c9,color:#000 + style J3 fill:#c8e6c9,color:#000 + style J4 fill:#c8e6c9,color:#000 + style K fill:#34a853,color:#fff + style L fill:#1a73e8,color:#fff + style M fill:#1a73e8,color:#fff + style N fill:#34a853,color:#fff +``` + +## Specialized Agents + +### JS Solution Architect + +**When to Use:** Architecture design, tech stack selection, system design + +**Key Responsibilities:** +- Technology stack selection (Next.js vs Vite, Express vs NestJS, etc.) +- Architecture pattern selection (Monolith, Microservices, JAMstack, Serverless) +- Database design (SQL vs NoSQL, schema design) +- API contract definition (REST vs GraphQL vs tRPC) +- Performance and scalability planning +- Security architecture + +**Example Usage:** +``` +@js-solution-architect I need to build a SaaS application with: +- React frontend with real-time updates +- Node.js backend +- PostgreSQL database +- 10,000 expected users +- Multi-tenant architecture + +Please recommend the tech stack and create the architecture. +``` + +**Key Outputs:** +- `docs/architecture/tech-stack-decision.md` +- `docs/architecture/system-architecture.md` +- `docs/architecture/database-schema.md` +- `docs/architecture/api-specification.md` + +### React Developer + +**When to Use:** Frontend implementation, React components, state management + +**Key Responsibilities:** +- Component implementation (React 18+, Next.js 14) +- State management (React Query, Zustand, Redux) +- Routing (file-based or React Router) +- Styling (Tailwind CSS, CSS Modules) +- Performance optimization (code splitting, lazy loading) +- Accessibility (WCAG compliance) + +**Example Usage:** +``` +@react-developer Implement a user dashboard with: +- User profile card +- Activity feed with infinite scroll +- Real-time notifications +- Dark mode support +- Fully responsive +- Accessible (WCAG AA) + +Use React Query for data fetching and Tailwind for styling. +``` + +**Validation Checklist:** +- Uses `checklists/frontend-checklist.md` +- TypeScript types for all props +- Component tests with React Testing Library +- Accessibility tests +- Performance checks (bundle size, re-renders) + +### Node Backend Developer + +**When to Use:** Backend services, business logic, database operations + +**Key Responsibilities:** +- Express/Fastify/NestJS implementation +- Database integration (Prisma, TypeORM) +- Authentication & authorization (JWT, OAuth) +- Background jobs (Bull, BullMQ) +- Caching strategies (Redis) +- Error handling and logging + +**Example Usage:** +``` +@node-backend-developer Implement user authentication service: +- Email/password registration +- JWT access tokens (15 min expiry) +- Refresh token strategy +- Password reset flow +- Rate limiting (5 attempts per 15 min) +- Bcrypt password hashing + +Use Express with Prisma and PostgreSQL. +``` + +**Validation Checklist:** +- Uses `checklists/backend-checklist.md` +- Input validation (Zod schemas) +- Unit tests for business logic +- Integration tests for API endpoints +- Security checks (SQL injection, XSS prevention) + +### API Developer + +**When to Use:** API design, endpoint implementation, documentation + +**Key Responsibilities:** +- RESTful API design (resource-based URLs, proper HTTP methods) +- GraphQL schema and resolvers +- tRPC for type-safe APIs +- API versioning strategies +- Rate limiting and throttling +- OpenAPI/Swagger documentation + +**Example Usage:** +``` +@api-developer Design the REST API for a blog platform: +- User management (CRUD) +- Post management (with drafts, publishing) +- Comments (nested, moderation) +- Tags and categories +- Search functionality +- Pagination (cursor-based) + +Include OpenAPI specification and example requests. +``` + +**Validation Checklist:** +- Uses `checklists/api-design-checklist.md` +- RESTful conventions followed +- Proper HTTP status codes +- Pagination implemented +- Rate limiting configured +- API documentation complete + +### TypeScript Expert + +**When to Use:** Type definitions, advanced patterns, migration + +**Key Responsibilities:** +- TypeScript configuration (strict mode) +- Advanced type patterns (generics, mapped types, conditional types) +- Type inference and narrowing +- JavaScript to TypeScript migration +- Shared types between frontend/backend +- Type-safe API client design + +**Example Usage:** +``` +@typescript-expert Create type-safe API client: +- Define all request/response types +- Implement generic fetch wrapper +- Type-safe query parameters +- Discriminated unions for API responses +- Error types with proper narrowing + +No 'any' types allowed, full type safety end-to-end. +``` + +**Validation:** +- `tsc --noEmit` passes with no errors +- No `any` types (use `unknown` if needed) +- Proper type guards for runtime checks +- Comprehensive interfaces for all DTOs + +## Agent Teams + +### Full-Stack Team + +**Use When:** Building complete applications from scratch + +**Team Composition:** +- Analyst (core BMAD) +- BMad-Orchestrator (core BMAD) +- JS Solution Architect +- React Developer +- Node Backend Developer +- API Developer +- TypeScript Expert + +**Workflows:** +- `fullstack-greenfield.yaml` +- `feature-development.yaml` +- `mvp-rapid-prototype.yaml` + +### Frontend Team + +**Use When:** Frontend-only or frontend-heavy projects + +**Team Composition:** +- Analyst (core BMAD) +- BMad-Orchestrator (core BMAD) +- JS Solution Architect +- React Developer +- TypeScript Expert + +**Workflows:** +- `frontend-app-development.yaml` +- `feature-development.yaml` + +### Backend Team + +**Use When:** API services, backend systems, microservices + +**Team Composition:** +- Analyst (core BMAD) +- BMad-Orchestrator (core BMAD) +- JS Solution Architect +- Node Backend Developer +- API Developer +- TypeScript Expert + +**Workflows:** +- `backend-api-development.yaml` +- `feature-development.yaml` + +## Quality Checklists + +The expansion pack includes comprehensive quality checklists for each phase: + +### Architecture Phase +- **`architecture-review-checklist.md`**: Validates architecture completeness + - Frontend architecture (framework, state, routing, styling) + - Backend architecture (framework, API, auth, middleware) + - Database design (schema, indexes, migrations) + - API design (versioning, pagination, rate limiting) + - Non-functional requirements (performance, security, scalability) + +### Development Phase +- **`frontend-checklist.md`**: React/Next.js code quality + - Component structure and TypeScript types + - React best practices (hooks, memoization, error boundaries) + - State management + - Performance (code splitting, bundle size, Core Web Vitals) + - Accessibility (WCAG compliance) + +- **`backend-checklist.md`**: Node.js backend quality + - API endpoint quality (RESTful design, status codes) + - Authentication & authorization + - Database operations (ORM usage, transactions, indexes) + - Error handling + - Security (Helmet.js, input validation, rate limiting) + +- **`api-design-checklist.md`**: API quality standards + - REST API design (resource naming, HTTP methods) + - Request/response format + - Authentication strategy + - Error handling + - Documentation (OpenAPI/Swagger) + +- **`security-checklist.md`**: Security validation + - Authentication (password hashing, token management) + - Authorization (RBAC, resource-level permissions) + - Input validation (frontend and backend) + - SQL injection prevention + - XSS and CSRF protection + - OWASP Top 10 coverage + +- **`performance-checklist.md`**: Performance optimization + - Frontend performance (Core Web Vitals, bundle size) + - Backend performance (API response time, database queries) + - Caching strategy + - Network optimization (CDN, compression, HTTP/2) + +### Deployment Phase +- **`deployment-readiness-checklist.md`**: Production readiness + - Code quality (tests pass, no TypeScript errors) + - Environment configuration + - Database migrations tested + - Security headers configured + - Performance targets met + - Monitoring and logging configured + +- **`story-dod-checklist.md`**: Definition of Done + - Requirements met + - Code quality (TypeScript, linting) + - Testing (unit, integration, E2E) + - Frontend-specific (responsive, accessible) + - Backend-specific (validation, error handling) + - Security and documentation + +## Task Guides + +Detailed step-by-step guides for common tasks: + +### `create-development-story.md` +- Story identification and scoping +- Using the JavaScript story template +- Full-stack coordination (frontend + backend + API) +- TypeScript interface definitions +- Testing requirements +- Validation process + +### `create-architecture-doc.md` +- Architecture document structure +- Technology stack selection +- Database schema design +- API contract definition +- Non-functional requirements +- Development standards + +### `create-api-spec.md` +- API specification structure +- Endpoint documentation template +- TypeScript DTO definitions +- OpenAPI/Swagger generation +- Best practices + +### `setup-project.md` +- Monorepo setup (Turborepo) +- TypeScript configuration +- Linting and formatting (ESLint, Prettier) +- Database setup (Prisma) +- Testing frameworks (Vitest, Jest, Playwright) +- CI/CD pipeline + +### `code-review.md` +- Code review checklist +- TypeScript quality checks +- React best practices +- Backend security checks +- Performance considerations +- Git hygiene + +### `performance-optimization.md` +- Performance measurement +- Frontend optimization (bundle, images, caching) +- Backend optimization (database, Redis, background jobs) +- Network optimization +- Monitoring setup + +## Reference Materials + +### `development-guidelines.md` +- TypeScript standards (strict mode, naming conventions) +- React best practices (hooks, memoization) +- Backend patterns (error handling, validation) +- Code organization +- Testing standards + +### `architecture-patterns.md` +- Monolithic Full-Stack +- JAMstack with Serverless +- Microservices +- Backend for Frontend (BFF) +- Event-Driven Architecture +- Decision matrix and migration paths + +### `best-practices.md` +- General principles +- Frontend best practices +- Backend best practices +- Testing strategy +- DevOps and deployment +- Common anti-patterns to avoid + +### `technology-stack-guide.md` +- Decision framework +- Recommended stacks by use case (MVP, SaaS, E-commerce, etc.) +- Technology comparison tables +- Decision trees for framework/database selection + +### `security-guidelines.md` +- Authentication (password hashing, JWT) +- Input validation (Zod schemas) +- SQL injection prevention +- XSS and CSRF protection +- CORS configuration +- Rate limiting +- Secrets management +- OWASP Top 10 checklist + +### `deployment-strategies.md` +- Deployment patterns (Rolling, Blue-Green, Canary) +- Platform-specific deployment (Vercel, Railway, AWS) +- CI/CD setup (GitHub Actions) +- Database migrations +- Environment management +- Rollback strategies +- Health checks and monitoring + +## Best Practices + +### Planning Phase +1. **Start with Tech Stack Selection**: Let JS Solution Architect evaluate options +2. **Define API Contracts Early**: Enables parallel frontend/backend development +3. **Consider TypeScript from Day One**: Easier than migration later +4. **Plan for Testing**: Include test strategy in architecture +5. **Document NFRs**: Performance, security, scalability requirements + +### Development Phase +1. **Use Appropriate Agent**: Match agent to task (React Dev for components, API Dev for endpoints) +2. **Coordinate Full-Stack Features**: Define TypeScript interfaces shared between frontend/backend +3. **Test at Multiple Levels**: Unit tests (logic), integration tests (APIs), E2E tests (user flows) +4. **Run Checklists**: Use quality checklists before marking stories complete +5. **Commit Often**: Save work after each story completion + +### Code Quality +1. **TypeScript Strict Mode**: Enable all strict flags +2. **No `any` Types**: Use proper types or `unknown` +3. **Lint and Format**: ESLint + Prettier configured +4. **Test Coverage**: >80% for frontend, >85% for backend +5. **Security First**: Validate all inputs, sanitize outputs + +### Performance +1. **Monitor Metrics**: Track Core Web Vitals, API response times +2. **Optimize Bundle Size**: Code splitting, lazy loading +3. **Database Indexes**: Add indexes on frequently queried fields +4. **Caching Strategy**: Use Redis for frequently accessed data +5. **CDN for Static Assets**: Serve assets from edge locations + +### Deployment +1. **CI/CD Pipeline**: Automate tests and deployment +2. **Environment Variables**: Never commit secrets +3. **Database Migrations**: Test on staging first +4. **Health Checks**: Implement `/health` endpoint +5. **Monitor Post-Deployment**: Watch for 24 hours after launch + +## Common Workflows + +### MVP Rapid Prototype Workflow + +For time-constrained projects (1-2 weeks), use the streamlined MVP workflow: + +```mermaid +graph TD + A["Start: MVP Concept"] --> B["Day 1: Planning (4 hours)"] + B --> B2["Analyst: Quick Requirements (1 hour)"] + B2 --> B3["PM: Lean PRD (1 hour)"] + B3 --> B4["JS Architect: Minimal Architecture (2 hours)"] + + B4 --> C["Day 2-3: Setup + Core Features"] + C --> C2["Dev: Project Setup (2 hours)"] + C2 --> C3["Node Dev: Auth + DB (4 hours)"] + C3 --> C4["React Dev: Core UI (6 hours)"] + C4 --> C5["API Dev: Basic Endpoints (4 hours)"] + + C5 --> D["Day 4-5: Features + Integration"] + D --> D2["React Dev: Feature Components (8 hours)"] + D2 --> D3["Node Dev: Business Logic (6 hours)"] + D3 --> D4["Integration + Basic Tests (2 hours)"] + + D4 --> E["Day 6-7: Polish + Deploy"] + E --> E2["Dev: Bug Fixes (4 hours)"] + E2 --> E3["Dev: Essential Tests (2 hours)"] + E3 --> E4["Dev: Deploy to Staging (1 hour)"] + E4 --> E5["QA: Quick Validation (2 hours)"] + E5 --> E6["Dev: Deploy to Production (1 hour)"] + + E6 --> F["MVP Complete"] + + style A fill:#f5f5f5,color:#000 + style B fill:#fff3e0,color:#000 + style B2 fill:#e8f5e9,color:#000 + style B3 fill:#fff3e0,color:#000 + style B4 fill:#f3e5f5,color:#000 + style C fill:#e3f2fd,color:#000 + style C2 fill:#e1f5fe,color:#000 + style C3 fill:#fff9c4,color:#000 + style C4 fill:#c8e6c9,color:#000 + style C5 fill:#ffecb3,color:#000 + style D fill:#e3f2fd,color:#000 + style D2 fill:#c8e6c9,color:#000 + style D3 fill:#fff9c4,color:#000 + style D4 fill:#ffd54f,color:#000 + style E fill:#e3f2fd,color:#000 + style E2 fill:#e3f2fd,color:#000 + style E3 fill:#ffd54f,color:#000 + style E4 fill:#bbdefb,color:#000 + style E5 fill:#ffd54f,color:#000 + style E6 fill:#34a853,color:#fff + style F fill:#34a853,color:#fff +``` + +**Key MVP Principles:** +- **Time-boxing**: Strict 2-hour max per planning phase +- **Minimal Documentation**: PRD + lean architecture only +- **Essential Features Only**: Core user flow, no nice-to-haves +- **Basic Testing**: Critical paths only +- **Fast Deployment**: Vercel/Railway for instant deploy + +--- + +### Step-by-Step MVP Commands (For Beginners) + +Here's exactly what to type and run for a simple MVP project. **Example: Building a basic Todo App MVP** + +#### **Day 1: Planning (Morning - 4 hours)** + +**Step 1: Define Your Idea (1 hour)** +```bash +# In Web UI, prompt the Analyst: +@analyst I want to build a simple Todo app MVP with: +- User can add, edit, delete todos +- Mark todos as complete +- Simple login (email/password) +- Mobile responsive +- Deploy in 1 week + +Please create a brief project outline. +``` + +**Step 2: Create PRD (1 hour)** +```bash +# After analyst completes, prompt PM: +@pm Create a minimal PRD for this Todo app MVP focusing on: +- Core features only (add, edit, delete, complete todos) +- User authentication +- Simple UI +- 1-week timeline +``` + +**Step 3: Architecture Design (2 hours)** +```bash +# Switch to IDE, prompt JS Solution Architect: +@js-solution-architect Design minimal architecture for Todo MVP: +- Frontend: Next.js with App Router +- Backend: Next.js API routes +- Database: PostgreSQL with Prisma +- Auth: NextAuth.js +- Deployment: Vercel + +Create tech stack document and simple database schema. +``` + +--- + +#### **Day 2: Project Setup (Morning - 2 hours)** + +**Step 1: Initialize Project** +```bash +# In your terminal, create the project: +npx create-next-app@latest todo-mvp --typescript --tailwind --app + +# Navigate into project: +cd todo-mvp + +# Install dependencies: +npm install prisma @prisma/client next-auth bcryptjs +npm install -D @types/bcryptjs +``` + +**Step 2: Setup Database** +```bash +# Initialize Prisma: +npx prisma init + +# In IDE, prompt: +@typescript-expert Create Prisma schema for Todo app with: +- User model (id, email, password, name) +- Todo model (id, title, completed, userId, createdAt) + +Update prisma/schema.prisma file. +``` + +```bash +# After schema is created, run migration: +npx prisma migrate dev --name init +npx prisma generate +``` + +**Step 3: Configure Environment** +```bash +# Create .env.local file: +@dev Create .env.local with: +- DATABASE_URL +- NEXTAUTH_SECRET +- NEXTAUTH_URL + +Generate secure secret with: openssl rand -base64 32 +``` + +--- + +#### **Day 2-3: Authentication (Afternoon - 4 hours)** + +**Step 1: Setup NextAuth** +```bash +# In IDE, prompt: +@node-backend-developer Setup NextAuth.js with: +- Credentials provider (email/password) +- JWT strategy +- Bcrypt password hashing +- Session handling + +Create app/api/auth/[...nextauth]/route.ts +``` + +**Step 2: Create Auth API** +```bash +# Prompt API Developer: +@api-developer Create registration endpoint at /api/auth/register: +- Validate email and password +- Hash password with bcrypt +- Create user in database +- Return success/error +``` + +**Step 3: Create Login UI** +```bash +# Prompt React Developer: +@react-developer Create authentication pages: +- app/login/page.tsx (email/password form) +- app/register/page.tsx (registration form) +- Use Tailwind CSS +- Form validation +- Loading states +``` + +--- + +#### **Day 3: Todo Backend (Afternoon - 4 hours)** + +**Step 1: Create Todo API Endpoints** +```bash +# Prompt API Developer: +@api-developer Create Todo CRUD API endpoints: +- GET /api/todos (list all user todos) +- POST /api/todos (create todo) +- PATCH /api/todos/[id] (update todo) +- DELETE /api/todos/[id] (delete todo) + +All endpoints require authentication. +``` + +**Step 2: Test API Endpoints** +```bash +# In terminal, test with curl or use Postman: +# (After implementing endpoints) + +# Login to get session +curl -X POST http://localhost:3000/api/auth/callback/credentials \ + -H "Content-Type: application/json" \ + -d '{"email":"test@example.com","password":"password123"}' + +# Test creating a todo +curl -X POST http://localhost:3000/api/todos \ + -H "Content-Type: application/json" \ + -d '{"title":"Test Todo"}' +``` + +--- + +#### **Day 3-4: Todo Frontend (Evening/Morning - 6 hours)** + +**Step 1: Create Todo Components** +```bash +# Prompt React Developer: +@react-developer Create Todo UI components: +- TodoList component (displays all todos) +- TodoItem component (single todo with edit/delete) +- AddTodoForm component (input + add button) +- Use Tailwind CSS for styling +- Mobile responsive +``` + +**Step 2: Add State Management** +```bash +# Prompt React Developer: +@react-developer Add state management: +- Use React hooks (useState, useEffect) +- Fetch todos on page load +- Optimistic UI updates +- Error handling +``` + +**Step 3: Create Main Todo Page** +```bash +# Prompt React Developer: +@react-developer Create main todo page at app/dashboard/page.tsx: +- Protected route (requires login) +- Display TodoList component +- Add AddTodoForm at top +- Logout button +``` + +--- + +#### **Day 4-5: Polish & Features (8 hours)** + +**Step 1: Add Todo Completion** +```bash +# Prompt: +@react-developer Add toggle completion feature: +- Click checkbox to mark todo complete +- Strikethrough completed todos +- Update database via PATCH /api/todos/[id] +``` + +**Step 2: Add Edit Functionality** +```bash +# Prompt: +@react-developer Add inline edit for todos: +- Double-click to edit +- Save on Enter or blur +- Cancel on Escape +``` + +**Step 3: Improve UI/UX** +```bash +# Prompt: +@react-developer Polish the UI: +- Add loading spinners +- Empty state (no todos message) +- Success/error toasts +- Smooth animations +- Better mobile layout +``` + +--- + +#### **Day 5: Testing (Afternoon - 2 hours)** + +**Step 1: Manual Testing Checklist** +```bash +# Test in browser: +□ Register new user +□ Login with credentials +□ Add 5 different todos +□ Mark 2 todos as complete +□ Edit a todo title +□ Delete a todo +□ Logout and login again +□ Verify todos persist +□ Test on mobile screen size +``` + +**Step 2: Fix Critical Bugs** +```bash +# If you find bugs, prompt: +@dev Fix bug: [describe the issue] + +# Example: +@dev Fix bug: Todos not persisting after refresh. +Check if API is returning correct user todos. +``` + +--- + +#### **Day 6: Deployment (Morning - 1 hour)** + +**Step 1: Prepare for Deployment** +```bash +# In terminal, verify build works: +npm run build + +# Check for TypeScript errors: +npx tsc --noEmit + +# Run Prisma generate: +npx prisma generate +``` + +**Step 2: Setup Database (Production)** +```bash +# Option A: Vercel Postgres +# - Go to vercel.com +# - Create new Postgres database +# - Copy DATABASE_URL + +# Option B: Supabase +# - Go to supabase.com +# - Create project +# - Copy connection string +``` + +**Step 3: Deploy to Vercel** +```bash +# Install Vercel CLI: +npm i -g vercel + +# Login to Vercel: +vercel login + +# Deploy: +vercel + +# Follow prompts: +# - Link to project: Yes +# - Project name: todo-mvp +# - Framework: Next.js + +# Set environment variables in Vercel dashboard: +# - DATABASE_URL +# - NEXTAUTH_SECRET +# - NEXTAUTH_URL (https://your-app.vercel.app) + +# Run migration on production database: +npx prisma migrate deploy +``` + +--- + +#### **Day 6: Staging Validation (Afternoon - 2 hours)** + +**Step 1: Test Production App** +```bash +# Open your deployed URL: https://todo-mvp.vercel.app + +# Test complete flow: +□ Register new user +□ Login +□ Add todos +□ Edit todos +□ Complete todos +□ Delete todos +□ Logout/Login +□ Test on mobile device +``` + +**Step 2: Monitor for Issues** +```bash +# Check Vercel logs: +# - Go to Vercel dashboard +# - Click on your project +# - Go to "Logs" tab +# - Watch for errors + +# Check database connections: +# - Verify todos are saving to production DB +``` + +--- + +#### **Day 7: Final Polish & Launch (2 hours)** + +**Step 1: Add Final Touches** +```bash +# Prompt: +@react-developer Add finishing touches: +- Update page title and meta tags +- Add favicon +- Improve loading states +- Add basic error boundaries +``` + +**Step 2: Production Deploy** +```bash +# In terminal, commit all changes: +git add . +git commit -m "feat: MVP complete - todo app with auth" +git push origin main + +# Vercel auto-deploys from main branch +# Wait for deployment to complete + +# Visit production URL and verify everything works +``` + +**Step 3: Share Your MVP!** +```bash +# Your MVP is live! 🎉 +# Share the URL: https://todo-mvp.vercel.app + +# Next steps (post-MVP): +# - Gather user feedback +# - Monitor usage +# - Plan v2 features +``` + +--- + +### Complete Command Reference (Copy-Paste Ready) + +Here's a complete script you can follow: + +```bash +# === DAY 1: SETUP === +npx create-next-app@latest todo-mvp --typescript --tailwind --app +cd todo-mvp +npm install prisma @prisma/client next-auth bcryptjs zod +npm install -D @types/bcryptjs +npx prisma init + +# === DAY 2: DATABASE === +# (After updating schema.prisma) +npx prisma migrate dev --name init +npx prisma generate + +# === DAY 3-5: DEVELOPMENT === +# Use IDE agents to build features +# Test locally: +npm run dev +# Open: http://localhost:3000 + +# === DAY 6: TESTING === +npm run build +npx tsc --noEmit +npm test # if you added tests + +# === DAY 7: DEPLOY === +vercel login +vercel --prod +npx prisma migrate deploy + +# === DONE! === +``` + +### What You'll Have After 7 Days + +✅ **Working Todo App** with authentication +✅ **Live URL** (e.g., todo-mvp.vercel.app) +✅ **User registration & login** +✅ **Full CRUD** for todos +✅ **Mobile responsive** design +✅ **Production database** +✅ **Deployed & running** + +**Total Lines of Code:** ~800-1000 lines +**Total Time:** 35-40 hours (1 week) +**Cost:** $0 (free tier Vercel + Supabase) + +### Complete Full-Stack Feature Workflow + +Detailed step-by-step workflow for implementing a full-stack feature: + +```mermaid +graph TD + A["Feature Request"] --> B["Step 1: Requirements"] + B --> B2["Analyst: Interview Stakeholders"] + B2 --> B3["Analyst: Document User Stories"] + B3 --> B4["PM: Add to PRD"] + + B4 --> C["Step 2: Technical Planning"] + C --> C2["JS Architect: Impact Analysis"] + C2 --> C3{Requires New Architecture?} + C3 -->|Yes| C4["JS Architect: Design New Components"] + C3 -->|No| D + C4 --> D + + D["Step 3: Type Definitions"] + D --> D2["TypeScript Expert: Define DTOs"] + D2 --> D3["TypeScript Expert: Frontend Types"] + D3 --> D4["TypeScript Expert: Backend Types"] + D4 --> D5["TypeScript Expert: API Types"] + + D5 --> E["Step 4: API Contract"] + E --> E2["API Dev: Define Endpoints"] + E2 --> E3["API Dev: Document Request/Response"] + E3 --> E4["API Dev: Create OpenAPI Spec"] + + E4 --> F["Step 5: Database Changes"] + F --> F2{Schema Changes?} + F2 -->|Yes| F3["Node Dev: Create Migration"] + F2 -->|No| G + F3 --> F4["Node Dev: Test Migration"] + F4 --> G + + G["Step 6: Backend Implementation"] + G --> G2["Node Dev: Service Layer"] + G2 --> G3["Node Dev: Unit Tests"] + G3 --> G4["API Dev: Endpoint Implementation"] + G4 --> G5["API Dev: Integration Tests"] + + G5 --> H["Step 7: Frontend Implementation"] + H --> H2["React Dev: Component Structure"] + H2 --> H3["React Dev: State Management"] + H3 --> H4["React Dev: API Integration"] + H4 --> H5["React Dev: Component Tests"] + + H5 --> I["Step 8: Integration"] + I --> I2["Dev: E2E Tests"] + I2 --> I3["Dev: Manual Testing"] + I3 --> I4{Issues Found?} + I4 -->|Yes| I5["Dev: Fix Issues"] + I4 -->|No| J + I5 --> I2 + + J["Step 9: Quality Validation"] + J --> J2["Dev: Frontend Checklist"] + J2 --> J3["Dev: Backend Checklist"] + J3 --> J4["Dev: API Checklist"] + J4 --> J5["Dev: Security Checklist"] + + J5 --> K["Step 10: Review"] + K --> K2["QA: Test Architecture Review"] + K2 --> K3{QA Approval?} + K3 -->|Yes| L + K3 -->|No| M["Dev: Address Feedback"] + M --> I2 + + L["Step 11: Deployment"] + L --> L2["Dev: Deploy to Staging"] + L2 --> L3["QA: Staging Validation"] + L3 --> L4{Ready for Prod?} + L4 -->|Yes| L5["Dev: Production Deploy"] + L4 -->|No| M + + L5 --> N["Step 12: Monitoring"] + N --> N2["Dev: Watch Error Logs"] + N2 --> N3["Dev: Monitor Performance"] + N3 --> N4["Dev: Track User Metrics"] + + N4 --> O["Feature Complete"] + + style A fill:#f5f5f5,color:#000 + style B fill:#e8f5e9,color:#000 + style C fill:#f3e5f5,color:#000 + style D fill:#f8bbd0,color:#000 + style E fill:#ffecb3,color:#000 + style F fill:#fff9c4,color:#000 + style G fill:#fff9c4,color:#000 + style H fill:#c8e6c9,color:#000 + style I fill:#e3f2fd,color:#000 + style J fill:#ffd54f,color:#000 + style K fill:#f9ab00,color:#fff + style L fill:#bbdefb,color:#000 + style M fill:#ff5722,color:#fff + style N fill:#1a73e8,color:#fff + style O fill:#34a853,color:#fff +``` + +### Technology Stack Selection Workflow + +Decision tree for choosing the right technology stack: + +```mermaid +graph TD + A["New Project"] --> B{Project Type?} + + B -->|Web App| C{Frontend Complexity?} + B -->|API Service| D{API Type?} + B -->|Mobile App| E["React Native + Backend"] + + C -->|Simple| C2["Next.js (App Router)"] + C -->|Complex| C3["React + Vite"] + + C2 --> F{Backend Needs?} + C3 --> F + + F -->|None| F2["Next.js API Routes"] + F -->|Simple| F3["Express"] + F -->|Complex| F4["NestJS"] + + D -->|REST| D2["Express + OpenAPI"] + D -->|GraphQL| D3["Apollo Server"] + D -->|Type-Safe| D4["tRPC"] + + F2 --> G{Database?} + F3 --> G + F4 --> G + D2 --> G + D3 --> G + D4 --> G + E --> G + + G -->|Relational| G2["PostgreSQL + Prisma"] + G -->|Document| G3["MongoDB + Mongoose"] + G -->|Key-Value| G4["Redis"] + + G2 --> H{State Management?} + G3 --> H + G4 --> H + + H -->|Server State| H2["React Query"] + H -->|Client State| H3{Complexity?} + + H3 -->|Simple| H4["Zustand"] + H3 -->|Complex| H5["Redux Toolkit"] + + H2 --> I{Authentication?} + H4 --> I + H5 --> I + + I -->|Simple| I2["NextAuth.js"] + I -->|Custom| I3["JWT + Refresh Tokens"] + I -->|Enterprise| I4["Auth0/Clerk"] + + I2 --> J["Tech Stack Complete"] + I3 --> J + I4 --> J + + style A fill:#f5f5f5,color:#000 + style B fill:#e3f2fd,color:#000 + style C fill:#e3f2fd,color:#000 + style C2 fill:#c8e6c9,color:#000 + style C3 fill:#c8e6c9,color:#000 + style D fill:#e3f2fd,color:#000 + style D2 fill:#ffecb3,color:#000 + style D3 fill:#ffecb3,color:#000 + style D4 fill:#ffecb3,color:#000 + style E fill:#f8bbd0,color:#000 + style F fill:#e3f2fd,color:#000 + style F2 fill:#fff9c4,color:#000 + style F3 fill:#fff9c4,color:#000 + style F4 fill:#fff9c4,color:#000 + style G fill:#e3f2fd,color:#000 + style G2 fill:#e1f5fe,color:#000 + style G3 fill:#e1f5fe,color:#000 + style G4 fill:#e1f5fe,color:#000 + style H fill:#e3f2fd,color:#000 + style H2 fill:#f3e5f5,color:#000 + style H3 fill:#e3f2fd,color:#000 + style H4 fill:#f3e5f5,color:#000 + style H5 fill:#f3e5f5,color:#000 + style I fill:#e3f2fd,color:#000 + style I2 fill:#fff3e0,color:#000 + style I3 fill:#fff3e0,color:#000 + style I4 fill:#fff3e0,color:#000 + style J fill:#34a853,color:#fff +``` + +## Detailed Example Workflows + +### Example 1: Building a SaaS Application (12-Week Timeline) + +**Project:** Task management SaaS with teams, projects, and real-time collaboration + +#### Week 1-2: Planning & Architecture + +**Day 1-2: Requirements Gathering** +```bash +# Web UI +@analyst Create project brief for team task management SaaS +# Output: docs/project-brief.md + +@analyst Research competitors (Asana, Linear, Monday.com) +# Output: docs/research/competitor-analysis.md + +@pm Create comprehensive PRD from project brief +# Output: docs/prd.md +``` + +**Day 3-5: Technical Architecture** +```bash +# Web UI +@js-solution-architect Design architecture for: +- 5,000 teams (50,000 users) +- Real-time collaboration +- Multi-tenant database +- PostgreSQL + Redis +- Next.js 14 + NestJS backend + +# Outputs: +# - docs/architecture/tech-stack-decision.md +# - docs/architecture/system-architecture.md +# - docs/architecture/database-schema.md +# - docs/architecture/api-specification.md + +@typescript-expert Define core TypeScript types +# Output: docs/architecture/typescript-types.md +``` + +**Day 6-7: Validation & Planning** +```bash +@po Run master checklist validation +@po Shard documents into epics and stories +# Output: docs/epics/ and docs/stories/ +``` + +#### Week 3-4: Project Setup & Authentication + +**Day 8: Project Initialization** +```bash +# IDE +@dev Initialize monorepo with Turborepo +# Creates: apps/web, apps/api, packages/shared-types + +@typescript-expert Configure strict TypeScript +# Creates: tsconfig.json, tsconfig.base.json + +@dev Setup Prisma with PostgreSQL +# Creates: packages/database/ +``` + +**Day 9-11: Authentication System** +```bash +# IDE +@sm Draft authentication story +# Output: docs/stories/auth-001-user-authentication.md + +@typescript-expert Define auth types +# Creates: packages/shared-types/src/auth.ts + +@node-backend-developer Implement JWT authentication +# Creates: +# - apps/api/src/auth/auth.service.ts +# - apps/api/src/auth/auth.controller.ts +# - apps/api/src/auth/strategies/jwt.strategy.ts + +@api-developer Document auth endpoints +# Updates: docs/architecture/api-specification.md + +@react-developer Create login/register components +# Creates: +# - apps/web/src/components/auth/LoginForm.tsx +# - apps/web/src/components/auth/RegisterForm.tsx + +@dev Run frontend and backend checklists +@dev Commit: "feat: implement user authentication system" +``` + +**Day 12-14: Team Management** +```bash +@sm Draft team management story +@node-backend-developer Implement team CRUD +@react-developer Create team UI +@dev Run integration tests +@dev Commit: "feat: add team management" +``` + +#### Week 5-6: Core Task Management + +**Day 15-18: Task CRUD** +```bash +@sm Draft task management story + +@node-backend-developer Implement task service: +- Create, read, update, delete tasks +- Task assignments +- Due dates and priorities +- Task comments + +@api-developer Create REST endpoints: +- POST /api/tasks +- GET /api/tasks/:id +- PATCH /api/tasks/:id +- DELETE /api/tasks/:id +- POST /api/tasks/:id/comments + +@react-developer Implement task components: +- TaskList component +- TaskCard component +- TaskForm component +- TaskDetail component + +@dev Run all tests +@dev Commit: "feat: implement core task management" +``` + +**Day 19-21: Project Organization** +```bash +@sm Draft project organization story +@node-backend-developer Implement projects and boards +@react-developer Create project views +@dev Integration tests +@dev Commit: "feat: add project organization" +``` + +#### Week 7-8: Real-Time Features + +**Day 22-25: WebSocket Integration** +```bash +@js-solution-architect Design real-time architecture +# Updates: docs/architecture/realtime-architecture.md + +@node-backend-developer Implement Socket.io server: +- WebSocket connection handling +- Room management (team/project rooms) +- Event broadcasting + +@react-developer Implement WebSocket client: +- Connection management +- Event listeners +- Real-time UI updates + +@dev Test real-time collaboration +@dev Commit: "feat: add real-time collaboration" +``` + +**Day 26-28: Live Updates** +```bash +@react-developer Implement real-time features: +- Live task updates +- Online user presence +- Typing indicators +- Instant notifications + +@dev Performance testing +@dev Commit: "feat: implement live updates" +``` + +#### Week 9-10: Advanced Features + +**Day 29-32: File Uploads** +```bash +@js-solution-architect Design file storage strategy (S3) +@node-backend-developer Implement file upload service +@react-developer Create file upload UI +@dev Test file uploads +@dev Commit: "feat: add file attachments" +``` + +**Day 33-35: Search & Filters** +```bash +@node-backend-developer Implement full-text search +@react-developer Create advanced filters UI +@dev Test search performance +@dev Commit: "feat: implement search and filters" +``` + +#### Week 11: Testing & Optimization + +**Day 36-38: Comprehensive Testing** +```bash +@qa Create comprehensive test plan +@dev Write E2E tests with Playwright +@dev Performance testing +@dev Fix identified issues +``` + +**Day 39-42: Performance Optimization** +```bash +@react-developer Optimize bundle size: +- Code splitting +- Lazy loading +- Tree shaking + +@node-backend-developer Optimize database: +- Add indexes +- Query optimization +- Redis caching + +@dev Monitor Core Web Vitals +@dev Commit: "perf: optimize application performance" +``` + +#### Week 12: Deployment & Launch + +**Day 43-45: Deployment Setup** +```bash +@dev Setup CI/CD with GitHub Actions +@dev Configure Vercel for frontend +@dev Configure Railway for backend +@dev Setup monitoring (Sentry, LogRocket) +``` + +**Day 46-47: Staging Testing** +```bash +@qa Full staging validation +@dev Fix staging issues +@dev Run deployment readiness checklist +``` + +**Day 48: Production Launch** +```bash +@dev Deploy to production +@dev Monitor for 24 hours +@dev Track error rates and performance +``` + +### Example 2: Adding Real-Time Notifications Feature (4-Day Implementation) + +**Context:** Existing SaaS application needs real-time notification system + +#### Day 1: Planning & Architecture + +**Morning: Requirements** +```bash +# Web UI +@analyst Document notification requirements: +- Task assignments +- Comments and mentions +- Project updates +- Team invitations + +# Output: docs/features/notifications-requirements.md + +@js-solution-architect Assess technical impact: +- WebSocket vs Server-Sent Events +- Database schema changes +- Caching strategy +- Performance impact + +# Output: docs/features/notifications-architecture.md +``` + +**Afternoon: Type Definitions & API Design** +```bash +# IDE +@typescript-expert Define notification types +# Creates: packages/shared-types/src/notifications.ts +``` + +```typescript +// packages/shared-types/src/notifications.ts +export enum NotificationType { + TASK_ASSIGNED = 'TASK_ASSIGNED', + TASK_COMMENT = 'TASK_COMMENT', + MENTION = 'MENTION', + PROJECT_UPDATE = 'PROJECT_UPDATE', + TEAM_INVITATION = 'TEAM_INVITATION', +} + +export interface Notification { + id: string; + userId: string; + type: NotificationType; + title: string; + message: string; + data: Record; + read: boolean; + createdAt: Date; +} + +export interface NotificationPreferences { + emailNotifications: boolean; + pushNotifications: boolean; + notificationTypes: NotificationType[]; +} +``` + +```bash +@api-developer Define notification endpoints +# Updates: docs/architecture/api-specification.md +``` + +#### Day 2: Backend Implementation + +**Morning: Database & Service Layer** +```bash +# IDE +@node-backend-developer Create Prisma migration +``` + +```bash +# packages/database/prisma/migrations/ +npx prisma migrate dev --name add_notifications +``` + +```bash +@node-backend-developer Implement notification service +# Creates: +# - apps/api/src/notifications/notification.service.ts +# - apps/api/src/notifications/notification.controller.ts +# - apps/api/src/notifications/notification.gateway.ts +``` + +**Afternoon: WebSocket Integration** +```bash +@node-backend-developer Implement WebSocket gateway: +- Connect/disconnect handlers +- Room management +- Event broadcasting +- Authentication + +# Updates: apps/api/src/notifications/notification.gateway.ts + +@node-backend-developer Write unit tests +# Creates: apps/api/src/notifications/__tests__/ + +@dev Run backend checklist +@dev Commit: "feat(api): implement notification backend" +``` + +#### Day 3: Frontend Implementation + +**Morning: Notification Components** +```bash +# IDE +@react-developer Create notification components +# Creates: +# - apps/web/src/components/notifications/NotificationBell.tsx +# - apps/web/src/components/notifications/NotificationList.tsx +# - apps/web/src/components/notifications/NotificationItem.tsx +# - apps/web/src/components/notifications/NotificationPreferences.tsx +``` + +```tsx +// Example component structure +export function NotificationBell() { + const { notifications, unreadCount } = useNotifications(); + + return ( + + + + + + + + + ); +} +``` + +**Afternoon: WebSocket Client & State Management** +```bash +@react-developer Implement WebSocket client hook +# Creates: apps/web/src/hooks/useNotifications.ts + +@react-developer Integrate React Query for state +# Updates: apps/web/src/lib/api/notifications.ts + +@dev Write component tests +# Creates: apps/web/src/components/notifications/__tests__/ + +@dev Run frontend checklist +@dev Commit: "feat(web): implement notification UI" +``` + +#### Day 4: Integration, Testing & Deployment + +**Morning: Integration Testing** +```bash +@dev Write E2E tests +# Creates: apps/web/e2e/notifications.spec.ts + +@dev Manual testing: +- Create task → verify assignment notification +- Add comment → verify comment notification +- Mention user → verify mention notification +- Test real-time delivery +- Test notification preferences + +@dev Fix any issues found +``` + +**Afternoon: Quality & Deployment** +```bash +@qa *review notification feature + +@dev Run all checklists: +- Frontend checklist +- Backend checklist +- Security checklist +- Performance checklist + +@dev Deploy to staging +@qa Staging validation +@dev Deploy to production +@dev Monitor for issues + +@dev Commit: "feat: complete real-time notifications feature" +``` + +### Example 3: Migrating JavaScript to TypeScript (12-Week Migration) + +**Context:** Large JavaScript codebase (500+ files) migrating to TypeScript + +#### Week 1-2: Assessment & Planning + +**Week 1: Codebase Analysis** +```bash +# Web UI +@typescript-expert Assess codebase: +- Count files (JavaScript vs TypeScript) +- Identify complex areas +- List external dependencies +- Estimate effort + +# Output: docs/migration/assessment.md + +@typescript-expert Create migration strategy: +- Phase breakdown +- File prioritization (bottom-up approach) +- Risk mitigation +- Timeline + +# Output: docs/migration/strategy.md +``` + +**Week 2: Environment Setup** +```bash +# IDE +@typescript-expert Configure TypeScript +# Creates: tsconfig.json +``` + +```json +{ + "compilerOptions": { + "target": "ES2020", + "module": "ESNext", + "lib": ["ES2020", "DOM"], + "allowJs": true, + "checkJs": false, + "noEmit": true, + "strict": false, + "esModuleInterop": true, + "skipLibCheck": true + }, + "include": ["src/**/*"], + "exclude": ["node_modules"] +} +``` + +```bash +@typescript-expert Install @types packages +npm install -D @types/react @types/node @types/express + +@dev Setup ESLint for TypeScript +# Updates: .eslintrc.js + +@dev Commit: "chore: setup TypeScript environment" +``` + +#### Week 3-5: Phase 1 - Utilities & Helpers (Bottom-Up) + +**Week 3: Core Utilities** +```bash +@typescript-expert Convert utility files (Batch 1: 20 files) +# Converts: +# - src/utils/date.js → src/utils/date.ts +# - src/utils/string.js → src/utils/string.ts +# - src/utils/validation.js → src/utils/validation.ts +# - src/utils/format.js → src/utils/format.ts + +@dev Run tests after each file +npm test + +@dev Commit: "refactor: convert core utilities to TypeScript" +``` + +**Week 4: Data Models & Types** +```bash +@typescript-expert Define shared types +# Creates: src/types/ + +@typescript-expert Convert model files (Batch 2: 25 files) +# Converts: +# - src/models/*.js → src/models/*.ts + +@dev Run tests +@dev Commit: "refactor: convert data models to TypeScript" +``` + +**Week 5: Service Layer** +```bash +@typescript-expert Convert service files (Batch 3: 30 files) +# Converts: +# - src/services/auth.js → src/services/auth.ts +# - src/services/user.js → src/services/user.ts +# - src/services/task.js → src/services/task.ts + +@dev Integration tests +@dev Commit: "refactor: convert service layer to TypeScript" +``` + +#### Week 6-8: Phase 2 - Components & API + +**Week 6: React Components (Batch 4: 50 files)** +```bash +@typescript-expert Convert utility components first +@react-developer Update component props to TypeScript +``` + +```typescript +// Before (JavaScript) +export function Button({ children, onClick, variant }) { + return ( + + ); +} + +// After (TypeScript) +interface ButtonProps { + children: React.ReactNode; + onClick?: () => void; + variant?: 'primary' | 'secondary' | 'danger'; +} + +export function Button({ + children, + onClick, + variant = 'primary' +}: ButtonProps) { + return ( + + ); +} +``` + +```bash +@dev Test each component +@dev Commit: "refactor: convert utility components to TypeScript" +``` + +**Week 7: Complex Components (Batch 5: 40 files)** +```bash +@typescript-expert Convert feature components +@react-developer Add proper type inference for hooks +@dev Component tests +@dev Commit: "refactor: convert feature components to TypeScript" +``` + +**Week 8: API Layer (Batch 6: 35 files)** +```bash +@api-developer Convert API routes and controllers +@typescript-expert Define request/response types +@dev API tests +@dev Commit: "refactor: convert API layer to TypeScript" +``` + +#### Week 9-10: Phase 3 - Enable Strict Mode + +**Week 9: Enable noImplicitAny** +```bash +# IDE +@typescript-expert Update tsconfig.json +``` + +```json +{ + "compilerOptions": { + "noImplicitAny": true + } +} +``` + +```bash +@typescript-expert Fix implicit any errors (100+ errors) +# Systematically add types to all parameters and variables + +@dev Run tests continuously +@dev Commit: "refactor: enable noImplicitAny and fix errors" +``` + +**Week 10: Enable strictNullChecks** +```bash +@typescript-expert Update tsconfig.json +``` + +```json +{ + "compilerOptions": { + "strictNullChecks": true + } +} +``` + +```bash +@typescript-expert Fix null/undefined errors (200+ errors) +# Add proper null checks and optional chaining + +@dev Run tests +@dev Commit: "refactor: enable strictNullChecks and fix errors" +``` + +#### Week 11: Phase 4 - Full Strict Mode + +**Enable All Strict Flags** +```bash +@typescript-expert Update tsconfig.json to full strict mode +``` + +```json +{ + "compilerOptions": { + "strict": true, + "noImplicitAny": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "strictBindCallApply": true, + "strictPropertyInitialization": true, + "noImplicitThis": true, + "alwaysStrict": true + } +} +``` + +```bash +@typescript-expert Fix remaining strict errors (150+ errors) +@dev Run full test suite +@dev Commit: "refactor: enable full strict mode" +``` + +#### Week 12: Refinement & Documentation + +**Replace 'any' Types** +```bash +@typescript-expert Find all 'any' types: +npm run find-any-types # Custom script + +@typescript-expert Replace with proper types: +- Use generics where appropriate +- Create specific interfaces +- Use 'unknown' for truly unknown types +- Add type guards for runtime checks + +@dev Commit: "refactor: eliminate 'any' types" +``` + +**Add Generics & Advanced Types** +```bash +@typescript-expert Improve type safety: +- Add generics to reusable functions +- Use conditional types where appropriate +- Implement type guards +- Add discriminated unions + +@dev Commit: "refactor: add advanced TypeScript patterns" +``` + +**Documentation & Training** +```bash +@typescript-expert Document TypeScript standards +# Creates: docs/typescript-standards.md + +@typescript-expert Create migration retrospective +# Creates: docs/migration/retrospective.md + +@dev Update team documentation +@dev Commit: "docs: complete TypeScript migration documentation" +``` + +**Final Validation** +```bash +# Verify TypeScript compilation +tsc --noEmit + +# Run all tests +npm test + +# Check bundle size impact +npm run build && npm run analyze + +# Performance testing +npm run test:perf + +# Deploy to staging for final validation +@dev Deploy to staging +@qa Full regression testing +@dev Deploy to production + +@dev Commit: "chore: complete TypeScript migration 🎉" +``` + +## Integration with Core BMAD + +This expansion pack integrates seamlessly with core BMAD agents: + +- **Analyst**: Gathers requirements for JavaScript projects +- **PM**: Uses JavaScript-specific PRD template +- **Architect**: Collaborates with JS Solution Architect +- **Scrum Master**: Creates stories using JavaScript story template +- **Dev**: Executes using specialized JavaScript agents +- **QA**: Tests with JavaScript testing frameworks +- **PO**: Validates using JavaScript-specific checklists + +## Getting Help + +- **Expansion Pack Issues**: Check `DOCUMENTATION/` folder +- **Core BMAD Help**: Reference main user guide +- **Community**: Join BMAD Discord +- **Examples**: See `data/` folder for reference implementations + +## Quick Reference + +### Agent Selection +- Architecture/Tech Stack → `@js-solution-architect` +- React Components → `@react-developer` +- Backend Services → `@node-backend-developer` +- API Endpoints → `@api-developer` +- TypeScript Types → `@typescript-expert` + +### Quality Gates +- Architecture → `architecture-review-checklist.md` +- Frontend Code → `frontend-checklist.md` +- Backend Code → `backend-checklist.md` +- API Design → `api-design-checklist.md` +- Security → `security-checklist.md` +- Performance → `performance-checklist.md` +- Deployment → `deployment-readiness-checklist.md` + +### Common Commands +```bash +# Planning +@js-solution-architect Design architecture for {project} +@typescript-expert Create type definitions for {feature} + +# Development +@react-developer Implement {component} +@node-backend-developer Implement {service} +@api-developer Create {endpoint} + +# Quality +@dev Run all validations +@qa *review {story} + +# Deployment +@dev Deploy to staging +@dev Monitor production metrics +``` + +## Conclusion + +The JavaScript Full-Stack Expansion Pack enhances BMAD Method with specialized expertise for modern JavaScript/TypeScript development. Use the appropriate agents for each task, follow the quality checklists, and leverage the comprehensive reference materials to build high-quality full-stack applications efficiently. + +Remember: This expansion pack works best when integrated with core BMAD workflows. Use it as a specialized toolkit while following the overall BMAD methodology for planning, development, and quality assurance. \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/agent-teams/backend-team.yaml b/expansion-packs/javascript-fullstack-pack/agent-teams/backend-team.yaml new file mode 100644 index 00000000..eb71fd7e --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/agent-teams/backend-team.yaml @@ -0,0 +1,15 @@ +# +bundle: + name: Backend API Team + icon: 🔧 + description: Specialized team for Node.js backend and API development with TypeScript. +agents: + - analyst + - bmad-orchestrator + - js-solution-architect + - node-backend-developer + - api-developer + - typescript-expert +workflows: + - backend-api-development.yaml + - feature-development.yaml \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/agent-teams/frontend-team.yaml b/expansion-packs/javascript-fullstack-pack/agent-teams/frontend-team.yaml new file mode 100644 index 00000000..932a56a6 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/agent-teams/frontend-team.yaml @@ -0,0 +1,14 @@ +# +bundle: + name: Frontend Development Team + icon: ⚛️ + description: Specialized team for React/Next.js frontend development with TypeScript. +agents: + - analyst + - bmad-orchestrator + - js-solution-architect + - react-developer + - typescript-expert +workflows: + - frontend-app-development.yaml + - feature-development.yaml \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/agent-teams/fullstack-team.yaml b/expansion-packs/javascript-fullstack-pack/agent-teams/fullstack-team.yaml new file mode 100644 index 00000000..72f1e767 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/agent-teams/fullstack-team.yaml @@ -0,0 +1,17 @@ +# +bundle: + name: JavaScript Full-Stack Team + icon: 🚀 + description: Complete team for full-stack JavaScript/TypeScript development with React, Node.js, and modern tooling. +agents: + - analyst + - bmad-orchestrator + - js-solution-architect + - react-developer + - node-backend-developer + - api-developer + - typescript-expert +workflows: + - fullstack-greenfield.yaml + - feature-development.yaml + - mvp-rapid-prototype.yaml \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/checklists/api-design-checklist.md b/expansion-packs/javascript-fullstack-pack/checklists/api-design-checklist.md new file mode 100644 index 00000000..ff64247b --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/checklists/api-design-checklist.md @@ -0,0 +1,62 @@ +# + +# API Design Quality Checklist + +## REST API Design +- [ ] **Resource Naming** - Plural nouns for collections (/users, /posts) +- [ ] **Nested Resources** - Logical nesting (/users/:id/posts) +- [ ] **HTTP Methods** - GET (read), POST (create), PATCH (update), DELETE (delete) +- [ ] **Filtering** - Query params for filtering (?status=active) +- [ ] **Sorting** - ?sort=createdAt&order=desc +- [ ] **Pagination** - Cursor or offset-based with hasMore/nextCursor +- [ ] **Field Selection** - ?fields=id,name,email to reduce payload +- [ ] **API Versioning** - /api/v1/ in URL or Accept header + +## GraphQL API Design (if applicable) +- [ ] **Schema First** - Schema defined before implementation +- [ ] **Naming Conventions** - camelCase for fields, PascalCase for types +- [ ] **Pagination** - Relay-style cursor pagination +- [ ] **N+1 Prevention** - DataLoader for batching +- [ ] **Error Handling** - GraphQL errors with extensions + +## tRPC API Design (if applicable) +- [ ] **Router Structure** - Logical router organization +- [ ] **Input Validation** - Zod schemas for all inputs +- [ ] **Type Safety** - Full end-to-end type safety +- [ ] **Error Handling** - TRPCError with proper codes + +## Request/Response Format +- [ ] **Content-Type** - application/json for JSON APIs +- [ ] **Request Body** - Well-structured, validated JSON +- [ ] **Response Format** - Consistent structure across endpoints +- [ ] **Date Format** - ISO 8601 timestamps +- [ ] **Null vs Undefined** - Consistent handling (prefer null) + +## Authentication & Authorization +- [ ] **Auth Strategy** - JWT, OAuth 2.0, or API keys +- [ ] **Token Location** - Authorization header (Bearer token) +- [ ] **Permissions** - Resource-level permissions defined +- [ ] **Scope-based Access** - Fine-grained scopes if needed + +## Error Handling +- [ ] **Error Format** - { error: string, details?: array, code?: string } +- [ ] **Status Codes** - Appropriate HTTP status codes +- [ ] **Error Messages** - User-friendly messages +- [ ] **Validation Errors** - Field-specific error details +- [ ] **Error Codes** - Machine-readable error codes + +## Performance +- [ ] **Response Time** - Target < 200ms (p95) +- [ ] **Caching Headers** - ETag, Cache-Control, Last-Modified +- [ ] **Compression** - gzip/brotli compression +- [ ] **Rate Limiting** - Per-endpoint rate limits +- [ ] **Batch Endpoints** - Batch operations where appropriate + +## Documentation +- [ ] **OpenAPI Spec** - Complete OpenAPI 3.0 specification +- [ ] **Example Requests** - cURL examples for each endpoint +- [ ] **Example Responses** - Success and error examples +- [ ] **Authentication** - Auth requirements clearly documented +- [ ] **Status Codes** - All possible status codes documented + +**API Quality Rating:** ⭐⭐⭐⭐⭐ \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/checklists/architecture-review-checklist.md b/expansion-packs/javascript-fullstack-pack/checklists/architecture-review-checklist.md new file mode 100644 index 00000000..8dcce16d --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/checklists/architecture-review-checklist.md @@ -0,0 +1,182 @@ +# + +# Architecture Review Checklist + +## Document Completeness + +### Executive Summary +- [ ] **System Overview** - Clear 2-3 paragraph description of the system +- [ ] **Technology Stack** - All major technologies listed with versions +- [ ] **Architecture Pattern** - Pattern identified (monolith, microservices, serverless, JAMstack) +- [ ] **Key Design Decisions** - 3-5 major decisions documented with rationale +- [ ] **Scalability Overview** - High-level scalability approach described + +### Frontend Architecture +- [ ] **Framework Choice** - React, Vue, or other with version and justification +- [ ] **Build Tool** - Vite, Next.js, or Webpack with configuration approach +- [ ] **State Management** - Clear strategy (React Query, Zustand, Redux, Context) +- [ ] **Routing** - Client-side vs server-side routing explained +- [ ] **Styling Approach** - CSS solution chosen (Tailwind, CSS Modules, Styled Components) +- [ ] **Component Structure** - Folder structure and component organization defined +- [ ] **Code Splitting** - Strategy for bundle optimization +- [ ] **SEO Strategy** - SSR, SSG, or CSR approach with reasoning + +### Backend Architecture +- [ ] **Runtime and Framework** - Node.js version and framework (Express, Fastify, NestJS) +- [ ] **API Design** - REST, GraphQL, or tRPC with endpoint organization +- [ ] **Authentication** - Strategy defined (JWT, OAuth, session-based) +- [ ] **Authorization** - RBAC, ABAC, or other approach +- [ ] **Middleware Stack** - Security, logging, error handling middleware +- [ ] **Background Jobs** - Queue system if needed (Bull, BullMQ) +- [ ] **File Uploads** - Strategy for handling file uploads +- [ ] **Email System** - Email sending approach (SendGrid, SES, SMTP) + +### Database Design +- [ ] **Database Choice** - SQL vs NoSQL with justification +- [ ] **Schema Design** - Entity relationships documented +- [ ] **Indexes** - Key indexes identified for performance +- [ ] **Migrations** - Migration strategy defined +- [ ] **Seeding** - Data seeding approach for development +- [ ] **Backup Strategy** - Backup frequency and retention +- [ ] **Connection Pooling** - Connection management strategy + +### API Design +- [ ] **Versioning Strategy** - URL-based, header-based, or other +- [ ] **Request/Response Format** - JSON schema or GraphQL schema +- [ ] **Error Handling** - Standardized error response format +- [ ] **Pagination** - Cursor-based or offset-based approach +- [ ] **Rate Limiting** - Rate limit strategy and thresholds +- [ ] **CORS Configuration** - Allowed origins and methods +- [ ] **API Documentation** - OpenAPI/Swagger or other documentation + +### TypeScript Configuration +- [ ] **Strict Mode** - Strict TypeScript settings justified +- [ ] **Path Aliases** - Import aliases configured (@/, ~/) +- [ ] **Type Definitions** - Strategy for third-party type definitions +- [ ] **Shared Types** - Location of shared types between frontend/backend + +## Non-Functional Requirements + +### Performance +- [ ] **Performance Targets** - Specific metrics defined (Lighthouse score, API latency) +- [ ] **Caching Strategy** - Redis, CDN, or in-memory caching approach +- [ ] **Database Optimization** - Query optimization and indexing plan +- [ ] **Asset Optimization** - Image optimization, lazy loading strategy +- [ ] **Bundle Size** - Target bundle sizes and code splitting approach + +### Security +- [ ] **Authentication Security** - Token expiration, refresh strategy +- [ ] **Authorization Checks** - Where and how authorization is enforced +- [ ] **Input Validation** - Validation on both frontend and backend +- [ ] **SQL Injection Prevention** - Parameterized queries or ORM usage +- [ ] **XSS Prevention** - Content Security Policy and sanitization +- [ ] **CSRF Protection** - Token-based CSRF protection +- [ ] **Secrets Management** - Environment variables and secret storage +- [ ] **HTTPS Enforcement** - SSL/TLS configuration +- [ ] **Security Headers** - Helmet.js or equivalent configuration +- [ ] **Dependency Scanning** - npm audit or Snyk integration + +### Scalability +- [ ] **Horizontal Scaling** - Stateless application design +- [ ] **Database Scaling** - Read replicas or sharding strategy +- [ ] **Caching Layer** - Cache invalidation strategy +- [ ] **CDN Usage** - Static asset delivery via CDN +- [ ] **Load Balancing** - Load balancer configuration if needed +- [ ] **Auto-scaling** - Metrics and triggers for scaling + +### Reliability +- [ ] **Error Handling** - Global error handling strategy +- [ ] **Logging Strategy** - Structured logging with correlation IDs +- [ ] **Monitoring** - APM and error tracking tools (Sentry, Datadog) +- [ ] **Health Checks** - Liveness and readiness endpoints +- [ ] **Graceful Shutdown** - Proper cleanup on application shutdown +- [ ] **Database Migrations** - Zero-downtime migration strategy +- [ ] **Rollback Plan** - How to rollback failed deployments + +### DevOps & Deployment +- [ ] **CI/CD Pipeline** - Build, test, and deploy automation +- [ ] **Environment Strategy** - Development, staging, production environments +- [ ] **Infrastructure as Code** - Terraform, CloudFormation, or Docker Compose +- [ ] **Container Strategy** - Docker configuration and orchestration +- [ ] **Deployment Strategy** - Blue-green, canary, or rolling deployments +- [ ] **Backup and Disaster Recovery** - RTO and RPO defined + +## Implementation Readiness + +### Development Environment +- [ ] **Local Setup** - Clear README with setup instructions +- [ ] **Environment Variables** - .env.example file with all required variables +- [ ] **Database Setup** - Local database setup instructions +- [ ] **Seed Data** - Development seed data available +- [ ] **Hot Reload** - Development server with hot module replacement + +### Code Quality +- [ ] **Linting** - ESLint configuration defined +- [ ] **Formatting** - Prettier configuration +- [ ] **Pre-commit Hooks** - Husky or lint-staged configuration +- [ ] **Code Style Guide** - Naming conventions and patterns documented +- [ ] **TypeScript Standards** - Type usage guidelines + +### Testing Strategy +- [ ] **Unit Testing** - Framework chosen (Jest, Vitest) +- [ ] **Integration Testing** - API testing approach (Supertest) +- [ ] **E2E Testing** - E2E framework (Playwright, Cypress) +- [ ] **Coverage Goals** - Target code coverage percentages +- [ ] **CI Integration** - Tests run in CI pipeline + +### Documentation +- [ ] **Architecture Diagrams** - System architecture visualized +- [ ] **Database Schema** - ER diagram or schema documentation +- [ ] **API Documentation** - Endpoint documentation (Swagger, GraphQL introspection) +- [ ] **Deployment Guide** - How to deploy to production +- [ ] **ADRs** - Architecture Decision Records for key choices + +## Risk Assessment + +### Technical Risks +- [ ] **Complexity Risks** - Over-engineering or under-engineering identified +- [ ] **Performance Bottlenecks** - Potential bottlenecks documented +- [ ] **Scalability Limits** - Known scalability constraints +- [ ] **Technology Risks** - Unproven or bleeding-edge tech flagged +- [ ] **Dependency Risks** - Critical third-party dependencies assessed + +### Mitigation Strategies +- [ ] **Risk Mitigation** - Plan for each identified risk +- [ ] **Fallback Options** - Alternative approaches documented +- [ ] **Monitoring Plan** - How risks will be monitored in production + +## Validation Questions + +### Alignment with Requirements +- [ ] **Requirements Coverage** - All functional requirements addressed +- [ ] **Non-functional Requirements** - Performance, security, scalability covered +- [ ] **Scope Appropriateness** - Architecture matches project scope +- [ ] **Over-engineering Check** - Not adding unnecessary complexity +- [ ] **Future-proofing** - Extensible without being over-architected + +### Team Capability +- [ ] **Team Skills** - Team has or can acquire necessary skills +- [ ] **Learning Curve** - New technologies have acceptable learning curve +- [ ] **Support Resources** - Documentation and community support available +- [ ] **Maintenance Burden** - Architecture is maintainable long-term + +### Cost Considerations +- [ ] **Infrastructure Costs** - Estimated monthly costs +- [ ] **Development Costs** - Time and effort realistic +- [ ] **Third-party Services** - External service costs budgeted +- [ ] **Scaling Costs** - Cost implications of scaling understood + +## Final Assessment + +**Architecture Quality Rating:** ⭐⭐⭐⭐⭐ + +**Ready for Implementation:** [ ] Yes [ ] No + +**Critical Issues to Address:** +_List any must-fix issues before development begins_ + +**Recommendations:** +_Suggestions for improvement or alternative approaches_ + +**Next Steps:** +_What needs to happen before story creation begins_ \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/checklists/backend-checklist.md b/expansion-packs/javascript-fullstack-pack/checklists/backend-checklist.md new file mode 100644 index 00000000..1cca7686 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/checklists/backend-checklist.md @@ -0,0 +1,121 @@ +# + +# Backend Quality Checklist + +## API Endpoint Quality + +### RESTful Design +- [ ] **Resource-Based URLs** - Nouns not verbs (/users not /getUsers) +- [ ] **HTTP Methods** - GET, POST, PATCH, DELETE used correctly +- [ ] **Status Codes** - Appropriate status codes (200, 201, 400, 401, 404, 500) +- [ ] **Idempotency** - PUT and DELETE are idempotent +- [ ] **Versioning** - API versioned (e.g., /api/v1/) + +### Request Handling +- [ ] **Input Validation** - All inputs validated (Zod, Joi, class-validator) +- [ ] **Type Safety** - TypeScript types for request/response +- [ ] **Query Parameters** - Pagination, filtering, sorting supported +- [ ] **Request Size Limits** - Body size limited (express.json limit) +- [ ] **Rate Limiting** - Rate limits applied per route + +### Response Formatting +- [ ] **Consistent Format** - Standardized response structure +- [ ] **Error Responses** - Consistent error format with details +- [ ] **Pagination** - Cursor or offset pagination with metadata +- [ ] **Field Filtering** - Ability to select fields if needed +- [ ] **Timestamps** - ISO 8601 format timestamps + +## Authentication & Authorization + +- [ ] **Authentication** - JWT, OAuth, or session-based implemented +- [ ] **Token Expiration** - Access tokens expire (15-60 minutes) +- [ ] **Refresh Tokens** - Refresh token strategy implemented +- [ ] **Password Hashing** - bcrypt or argon2 with proper rounds +- [ ] **Authorization Middleware** - Role-based checks on protected routes +- [ ] **CORS** - Properly configured CORS headers +- [ ] **Rate Limiting** - Stricter limits on auth endpoints + +## Database Operations + +- [ ] **ORM Usage** - Prisma, TypeORM, or similar ORM used +- [ ] **Parameterized Queries** - No raw SQL with string concatenation +- [ ] **Transactions** - Multi-step operations use transactions +- [ ] **Connection Pooling** - Connection pool configured +- [ ] **Indexes** - Indexes on frequently queried fields +- [ ] **N+1 Prevention** - No N+1 query problems +- [ ] **Pagination** - Large datasets paginated + +## Error Handling + +- [ ] **Global Error Handler** - Centralized error handling middleware +- [ ] **Custom Error Classes** - Typed error classes for different errors +- [ ] **Error Logging** - Errors logged with context +- [ ] **Error Responses** - User-friendly error messages +- [ ] **Stack Traces** - Stack traces in development, hidden in production +- [ ] **Unhandled Rejections** - Process handlers for unhandled promises + +## Security + +- [ ] **Helmet.js** - Security headers configured +- [ ] **SQL Injection** - Protected via parameterized queries +- [ ] **XSS Prevention** - Input sanitization +- [ ] **CSRF Protection** - CSRF tokens or SameSite cookies +- [ ] **Secrets Management** - Environment variables, no hardcoded secrets +- [ ] **Dependency Scanning** - npm audit or Snyk in CI +- [ ] **HTTPS Only** - Redirect HTTP to HTTPS in production +- [ ] **Input Sanitization** - All user inputs sanitized + +## Performance + +- [ ] **Response Time** - < 200ms for p95 +- [ ] **Caching** - Redis caching for frequently accessed data +- [ ] **Database Optimization** - Queries optimized with EXPLAIN +- [ ] **Compression** - Response compression enabled +- [ ] **Connection Reuse** - HTTP keep-alive enabled +- [ ] **Background Jobs** - Long-running tasks in queue (Bull, BullMQ) + +## Testing + +- [ ] **Unit Tests** - Business logic covered (>85%) +- [ ] **Integration Tests** - API endpoints tested (Supertest) +- [ ] **Database Tests** - Database operations tested +- [ ] **Authentication Tests** - Auth flows tested +- [ ] **Error Cases** - Error scenarios tested +- [ ] **CI Integration** - Tests run on every commit + +## TypeScript Quality + +- [ ] **Strict Mode** - TypeScript strict mode enabled +- [ ] **DTO Types** - DTOs typed with Zod or class-validator +- [ ] **Service Interfaces** - Services have TypeScript interfaces +- [ ] **No Any** - No `any` types (use `unknown`) +- [ ] **Type Guards** - Type guards for runtime type checking + +## Logging & Monitoring + +- [ ] **Structured Logging** - JSON logs with correlation IDs +- [ ] **Log Levels** - Appropriate log levels (error, warn, info, debug) +- [ ] **Error Tracking** - Sentry or similar integrated +- [ ] **Performance Monitoring** - APM tool integrated +- [ ] **Health Checks** - /health endpoint implemented +- [ ] **Metrics** - Prometheus or similar metrics + +## API Documentation + +- [ ] **OpenAPI/Swagger** - API documented with OpenAPI spec +- [ ] **Example Requests** - Example requests in documentation +- [ ] **Authentication** - Auth requirements documented +- [ ] **Error Codes** - All error codes documented +- [ ] **Rate Limits** - Rate limits documented + +## Code Quality + +- [ ] **Separation of Concerns** - Controller, Service, Repository layers +- [ ] **DRY Principle** - No code duplication +- [ ] **Function Size** - Functions under 50 lines +- [ ] **Dependency Injection** - Dependencies injected, not hardcoded +- [ ] **Configuration** - Environment-based configuration + +**Quality Rating:** ⭐⭐⭐⭐⭐ + +**Ready for Production:** [ ] Yes [ ] No \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/checklists/deployment-readiness-checklist.md b/expansion-packs/javascript-fullstack-pack/checklists/deployment-readiness-checklist.md new file mode 100644 index 00000000..55d11a59 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/checklists/deployment-readiness-checklist.md @@ -0,0 +1,105 @@ +# + +# Deployment Readiness Checklist + +## Code Quality +- [ ] **All Tests Pass** - Unit, integration, E2E tests green +- [ ] **No TypeScript Errors** - tsc --noEmit passes +- [ ] **No Lint Errors** - ESLint passes +- [ ] **Code Coverage** - Meets target (80%+) +- [ ] **Code Review** - All changes peer reviewed +- [ ] **Dependencies Updated** - No critical vulnerabilities + +## Environment Configuration +- [ ] **Environment Variables** - All required env vars documented +- [ ] **Secrets Configured** - Production secrets set in hosting platform +- [ ] **Database URL** - Production database URL configured +- [ ] **API Keys** - All third-party API keys set +- [ ] **Feature Flags** - Feature flag configuration ready + +## Database +- [ ] **Migrations Tested** - Migrations tested on staging +- [ ] **Rollback Plan** - Migration rollback tested +- [ ] **Seed Data** - Production seed data if needed +- [ ] **Backups** - Automated backups configured +- [ ] **Connection Pool** - Connection pooling configured + +## Security +- [ ] **HTTPS** - SSL certificate installed and tested +- [ ] **Security Headers** - All security headers configured +- [ ] **CORS** - CORS properly configured for production domain +- [ ] **Rate Limiting** - Rate limiting enabled +- [ ] **Authentication** - Auth flows tested in production-like environment +- [ ] **Secrets Rotation** - Secrets rotation plan in place +- [ ] **npm audit** - No high/critical vulnerabilities + +## Performance +- [ ] **Load Testing** - Tested at 2x expected load +- [ ] **CDN Configuration** - CDN configured and tested +- [ ] **Caching** - Redis/caching layer configured +- [ ] **Database Indexes** - Critical indexes in place +- [ ] **Bundle Size** - Frontend bundle size optimized +- [ ] **Lighthouse Score** - >90 on all metrics + +## Monitoring & Logging +- [ ] **Error Tracking** - Sentry or similar configured +- [ ] **Logging** - Structured logging configured +- [ ] **APM** - Application monitoring configured +- [ ] **Uptime Monitoring** - Uptime monitors set up +- [ ] **Alerts** - Critical alerts configured +- [ ] **Dashboards** - Monitoring dashboards created + +## CI/CD Pipeline +- [ ] **Automated Tests** - All tests run in CI +- [ ] **Build Process** - Build succeeds in CI +- [ ] **Deployment Script** - Automated deployment configured +- [ ] **Rollback Process** - Rollback procedure documented and tested +- [ ] **Blue-Green/Canary** - Safe deployment strategy +- [ ] **Health Checks** - Health check endpoints working + +## Documentation +- [ ] **README** - Complete setup and deployment instructions +- [ ] **API Docs** - API documentation up to date +- [ ] **Architecture** - Architecture docs current +- [ ] **Runbooks** - Incident response runbooks +- [ ] **Changelog** - Release notes prepared + +## Infrastructure +- [ ] **DNS** - DNS configured and propagated +- [ ] **Load Balancer** - Load balancer configured if needed +- [ ] **Auto-scaling** - Auto-scaling rules configured +- [ ] **Firewall Rules** - Firewall properly configured +- [ ] **Database Backups** - Automated backups running +- [ ] **Disaster Recovery** - DR plan documented + +## Third-Party Services +- [ ] **Payment Gateway** - Stripe/payment provider in production mode +- [ ] **Email Service** - Email provider configured +- [ ] **Storage** - S3 or file storage configured +- [ ] **Analytics** - Analytics tracking configured +- [ ] **CDN** - CDN service active + +## Pre-Launch Checklist +- [ ] **Smoke Tests** - Critical paths tested on production +- [ ] **Performance Test** - Production performance verified +- [ ] **Security Scan** - Final security audit completed +- [ ] **Backup Verified** - Can restore from backup +- [ ] **Rollback Tested** - Rollback procedure verified +- [ ] **Team Notified** - All team members aware of launch +- [ ] **Support Ready** - Support team briefed + +## Post-Launch +- [ ] **Monitor Metrics** - Watch dashboards for 24 hours +- [ ] **Error Rates** - Monitor error rates closely +- [ ] **Performance** - Verify performance targets met +- [ ] **User Feedback** - Collect and monitor user feedback +- [ ] **Hotfix Process** - Hotfix procedure ready if needed + +**Deployment Readiness:** [ ] Go [ ] No-Go + +**Blockers:** +_List any items preventing deployment_ + +**Launch Date:** _________ +**Launch Time:** _________ +**Launch Coordinator:** _________ \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/checklists/frontend-checklist.md b/expansion-packs/javascript-fullstack-pack/checklists/frontend-checklist.md new file mode 100644 index 00000000..04061ef9 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/checklists/frontend-checklist.md @@ -0,0 +1,98 @@ +# + +# Frontend Quality Checklist + +## React/Next.js Component Quality + +### Component Structure +- [ ] **Single Responsibility** - Each component has one clear purpose +- [ ] **Proper TypeScript Types** - Props interface defined with no `any` +- [ ] **Component Size** - Under 300 lines (extract smaller components if larger) +- [ ] **Named Exports** - Prefer named exports for better refactoring +- [ ] **File Organization** - Component, styles, tests, and types co-located + +### React Best Practices +- [ ] **Hooks Usage** - Hooks used correctly (no conditional hooks) +- [ ] **useEffect Dependencies** - All dependencies included in dependency array +- [ ] **Memoization** - useMemo/useCallback used for expensive operations +- [ ] **Key Props** - Proper unique keys on list items +- [ ] **Ref Usage** - useRef used appropriately for DOM access +- [ ] **Error Boundaries** - Error boundaries wrap components that may fail + +### State Management +- [ ] **Local State** - useState for component-local state +- [ ] **Server State** - React Query/SWR for API data +- [ ] **Global State** - Zustand/Redux only when necessary +- [ ] **Derived State** - Computed values use useMemo +- [ ] **State Location** - State lifted to appropriate level + +### Performance +- [ ] **Code Splitting** - Large components lazy loaded +- [ ] **Bundle Size** - No unnecessary dependencies +- [ ] **Re-renders** - React DevTools shows minimal re-renders +- [ ] **Images Optimized** - next/image or optimized images +- [ ] **Virtualization** - Long lists use react-virtual or similar + +### Styling +- [ ] **Consistent Approach** - One styling method used consistently +- [ ] **Responsive Design** - Mobile, tablet, desktop breakpoints +- [ ] **Dark Mode** - Dark mode support if required +- [ ] **Design System** - Follows established design tokens +- [ ] **No Inline Styles** - Styles in CSS/Tailwind, not inline (unless dynamic) + +## Accessibility + +- [ ] **Semantic HTML** - article, nav, main, section used appropriately +- [ ] **ARIA Labels** - Proper ARIA labels on interactive elements +- [ ] **Keyboard Navigation** - All interactions work with keyboard +- [ ] **Focus Management** - Visible focus indicators +- [ ] **Color Contrast** - Meets WCAG AA standards (4.5:1) +- [ ] **Screen Reader** - Tested with screen reader +- [ ] **Form Labels** - All inputs have associated labels +- [ ] **Alt Text** - All images have descriptive alt text + +## User Experience + +- [ ] **Loading States** - Skeletons or spinners during data fetching +- [ ] **Error States** - User-friendly error messages +- [ ] **Empty States** - Helpful messages when no data +- [ ] **Success Feedback** - Confirmation of successful actions +- [ ] **Optimistic Updates** - UI updates before server confirms (when appropriate) +- [ ] **Transitions** - Smooth transitions between states + +## Testing + +- [ ] **Component Tests** - React Testing Library tests written +- [ ] **User Interactions** - Click, type, submit events tested +- [ ] **Conditional Rendering** - All branches tested +- [ ] **Error Cases** - Error states tested +- [ ] **Accessibility Tests** - axe-core or similar used +- [ ] **Coverage** - >80% test coverage + +## TypeScript Quality + +- [ ] **Props Typed** - Complete interface for props +- [ ] **Event Handlers** - Proper event types used +- [ ] **Children Typing** - ReactNode for children prop +- [ ] **Generics** - Generic components properly typed +- [ ] **No Any** - No `any` types (use `unknown` if necessary) + +## Build & Performance + +- [ ] **Lighthouse Score** - >90 on all metrics +- [ ] **Core Web Vitals** - LCP < 2.5s, FID < 100ms, CLS < 0.1 +- [ ] **Bundle Analysis** - No duplicate dependencies +- [ ] **Tree Shaking** - Unused code eliminated +- [ ] **Critical CSS** - Above-fold CSS inlined + +## Security + +- [ ] **XSS Prevention** - User input sanitized +- [ ] **CSP Headers** - Content Security Policy configured +- [ ] **Secure Cookies** - httpOnly, secure flags set +- [ ] **No Secrets** - No API keys or secrets in frontend code +- [ ] **HTTPS Only** - All requests over HTTPS + +**Quality Rating:** ⭐⭐⭐⭐⭐ + +**Ready for Production:** [ ] Yes [ ] No \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/checklists/performance-checklist.md b/expansion-packs/javascript-fullstack-pack/checklists/performance-checklist.md new file mode 100644 index 00000000..e8df220e --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/checklists/performance-checklist.md @@ -0,0 +1,120 @@ +# + +# Performance Optimization Checklist + +## Frontend Performance + +### Core Web Vitals +- [ ] **LCP** - Largest Contentful Paint < 2.5s +- [ ] **FID** - First Input Delay < 100ms +- [ ] **CLS** - Cumulative Layout Shift < 0.1 +- [ ] **TTFB** - Time to First Byte < 600ms +- [ ] **TTI** - Time to Interactive < 3.5s + +### Bundle Optimization +- [ ] **Code Splitting** - Route-based code splitting +- [ ] **Lazy Loading** - Components lazy loaded with React.lazy +- [ ] **Tree Shaking** - Unused code eliminated +- [ ] **Bundle Analysis** - webpack-bundle-analyzer or similar +- [ ] **Chunk Optimization** - Vendor chunks separated +- [ ] **Total Bundle** - < 200KB initial load (gzipped) + +### Image Optimization +- [ ] **Next/Image** - Use next/image or optimized images +- [ ] **WebP Format** - Serve WebP with fallbacks +- [ ] **Lazy Loading** - Images lazy loaded below fold +- [ ] **Responsive Images** - srcset for different sizes +- [ ] **CDN Delivery** - Images served from CDN +- [ ] **Compression** - Images compressed (TinyPNG, etc.) + +### Caching Strategy +- [ ] **Service Worker** - Service worker for caching (PWA) +- [ ] **Cache-Control** - Appropriate cache headers +- [ ] **Static Assets** - Versioned static assets +- [ ] **API Caching** - React Query cache configuration + +### Rendering Strategy +- [ ] **SSR/SSG** - Server rendering or static generation where appropriate +- [ ] **Streaming** - Streaming SSR for large pages +- [ ] **Incremental Static Regeneration** - ISR for dynamic content +- [ ] **Client-side Hydration** - Minimal hydration overhead + +### React Performance +- [ ] **Memo** - React.memo for expensive components +- [ ] **useCallback** - Callbacks memoized +- [ ] **useMemo** - Expensive computations memoized +- [ ] **Virtual Scrolling** - react-window or react-virtual for long lists +- [ ] **Avoid Re-renders** - Unnecessary re-renders eliminated + +## Backend Performance + +### API Response Time +- [ ] **Response Time** - < 200ms for p95 +- [ ] **Slow Query Detection** - Queries > 100ms logged +- [ ] **Timeout Configuration** - Reasonable timeouts set +- [ ] **Connection Pooling** - Database connection pool configured + +### Database Optimization +- [ ] **Indexes** - Indexes on frequently queried fields +- [ ] **Query Optimization** - EXPLAIN ANALYZE used +- [ ] **N+1 Prevention** - No N+1 query problems +- [ ] **Pagination** - Large datasets paginated +- [ ] **Connection Pool** - Pool size optimized +- [ ] **Query Caching** - Database query caching + +### Caching Layer +- [ ] **Redis Caching** - Frequently accessed data cached +- [ ] **Cache Invalidation** - Clear cache invalidation strategy +- [ ] **Cache TTL** - Appropriate TTL for each cache +- [ ] **Cache-Aside Pattern** - Fetch from cache, then DB +- [ ] **Session Caching** - User sessions in Redis + +### API Optimization +- [ ] **Compression** - gzip/brotli compression enabled +- [ ] **Response Size** - Minimal response payloads +- [ ] **GraphQL** - DataLoader for batching (if GraphQL) +- [ ] **Batch Endpoints** - Batch operations available +- [ ] **HTTP/2** - HTTP/2 enabled + +### Background Jobs +- [ ] **Queue System** - Long tasks in queue (Bull, BullMQ) +- [ ] **Async Operations** - Non-blocking async operations +- [ ] **Job Retry** - Failed jobs retry with backoff +- [ ] **Job Monitoring** - Job queue monitored + +## Network Performance + +### CDN Usage +- [ ] **Static Assets** - Static files served via CDN +- [ ] **Geographic Distribution** - CDN has global coverage +- [ ] **Cache Headers** - Long cache times for static assets +- [ ] **Compression** - CDN compresses responses + +### Request Optimization +- [ ] **HTTP/2** - HTTP/2 or HTTP/3 enabled +- [ ] **Keep-Alive** - Connection reuse enabled +- [ ] **DNS Prefetch** - +- [ ] **Preconnect** - for critical origins +- [ ] **Resource Hints** - Prefetch, preload for critical resources + +## Monitoring & Profiling + +### Performance Monitoring +- [ ] **Lighthouse CI** - Lighthouse scores in CI +- [ ] **RUM** - Real User Monitoring (Datadog, New Relic) +- [ ] **APM** - Application Performance Monitoring +- [ ] **Error Rate** - Error rate < 0.1% +- [ ] **Uptime** - 99.9% uptime + +### Profiling Tools +- [ ] **React DevTools** - Profiler for React performance +- [ ] **Chrome DevTools** - Performance audits +- [ ] **Node.js Profiler** - Backend profiling +- [ ] **Database Profiler** - Query performance profiling + +### Alerts +- [ ] **Performance Alerts** - Alert on performance degradation +- [ ] **Error Rate Alerts** - Alert on increased errors +- [ ] **Response Time Alerts** - Alert on slow responses + +**Performance Rating:** ⭐⭐⭐⭐⭐ \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/checklists/security-checklist.md b/expansion-packs/javascript-fullstack-pack/checklists/security-checklist.md new file mode 100644 index 00000000..60e752e2 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/checklists/security-checklist.md @@ -0,0 +1,118 @@ +# + +# Security Checklist + +## Authentication +- [ ] **Password Hashing** - bcrypt/argon2 with sufficient rounds (10-12) +- [ ] **Token Expiration** - Access tokens expire (15-60 min) +- [ ] **Refresh Tokens** - Secure refresh token strategy +- [ ] **Token Storage** - HttpOnly cookies or secure storage +- [ ] **Password Requirements** - Min length, complexity enforced +- [ ] **Password Reset** - Secure password reset flow with expiring tokens +- [ ] **Account Lockout** - Lock after N failed attempts +- [ ] **Session Management** - Secure session handling + +## Authorization +- [ ] **Route Protection** - All protected routes check auth +- [ ] **Resource Authorization** - Users can only access their resources +- [ ] **Role-Based Access** - RBAC implemented where needed +- [ ] **Principle of Least Privilege** - Minimal permissions by default + +## Input Validation +- [ ] **Frontend Validation** - Client-side validation for UX +- [ ] **Backend Validation** - Server-side validation (never trust client) +- [ ] **Schema Validation** - Zod, Joi, or class-validator +- [ ] **Type Checking** - TypeScript for compile-time checks +- [ ] **Sanitization** - DOMPurify or similar for HTML content +- [ ] **File Uploads** - File type and size validation + +## SQL Injection Prevention +- [ ] **Parameterized Queries** - Never concatenate SQL strings +- [ ] **ORM Usage** - Use Prisma, TypeORM, or similar +- [ ] **Input Validation** - Validate all user inputs + +## XSS Prevention +- [ ] **Content Security Policy** - CSP headers configured +- [ ] **Output Encoding** - Escape user-generated content +- [ ] **Sanitization** - Sanitize HTML inputs +- [ ] **React Safety** - Use React's built-in XSS protection (dangerouslySetInnerHTML only when necessary) + +## CSRF Protection +- [ ] **CSRF Tokens** - Tokens for state-changing operations +- [ ] **SameSite Cookies** - SameSite=Strict or Lax +- [ ] **Origin Validation** - Validate request origin + +## CORS Configuration +- [ ] **Allowed Origins** - Whitelist specific origins, no wildcards in production +- [ ] **Credentials** - credentials: true only when necessary +- [ ] **Allowed Methods** - Only required methods +- [ ] **Preflight Caching** - maxAge set appropriately + +## Secrets Management +- [ ] **Environment Variables** - All secrets in env vars +- [ ] **No Hardcoded Secrets** - No secrets in code +- [ ] **Secret Rotation** - Plan for rotating secrets +- [ ] **.env in .gitignore** - Never commit .env files +- [ ] **Production Secrets** - Use secret management service (AWS Secrets Manager, etc.) + +## HTTPS/TLS +- [ ] **HTTPS Only** - All traffic over HTTPS +- [ ] **HTTP to HTTPS** - Redirect HTTP to HTTPS +- [ ] **HSTS Header** - Strict-Transport-Security header +- [ ] **TLS Version** - TLS 1.2 or higher +- [ ] **Valid Certificate** - Properly configured SSL certificate + +## Security Headers +- [ ] **Helmet.js** - Use Helmet for Express/Fastify +- [ ] **X-Content-Type-Options** - nosniff +- [ ] **X-Frame-Options** - DENY or SAMEORIGIN +- [ ] **X-XSS-Protection** - 1; mode=block +- [ ] **Referrer-Policy** - no-referrer or strict-origin-when-cross-origin +- [ ] **Permissions-Policy** - Restrict browser features + +## Rate Limiting +- [ ] **Global Rate Limit** - Prevent abuse (100 req/15min) +- [ ] **Auth Rate Limit** - Strict limits on login (5 req/15min) +- [ ] **Per-User Limits** - User-specific rate limits +- [ ] **Redis-backed** - Use Redis for distributed rate limiting + +## Dependency Security +- [ ] **npm audit** - Run regularly and fix issues +- [ ] **Snyk/Dependabot** - Automated dependency scanning +- [ ] **Update Dependencies** - Keep dependencies up to date +- [ ] **Lock Files** - Commit package-lock.json or yarn.lock +- [ ] **Audit Third-party Code** - Review third-party packages + +## API Security +- [ ] **API Keys** - Secure API key management +- [ ] **Token Rotation** - Rotate API keys periodically +- [ ] **Request Signing** - Sign sensitive requests +- [ ] **Rate Limiting** - Per-API-key rate limits +- [ ] **IP Whitelisting** - Whitelist IPs where appropriate + +## Logging & Monitoring +- [ ] **Security Events** - Log authentication failures, authorization failures +- [ ] **No Sensitive Data** - Never log passwords, tokens, credit cards +- [ ] **Anomaly Detection** - Monitor for unusual patterns +- [ ] **Audit Trail** - Log important user actions + +## Infrastructure Security +- [ ] **Firewall** - Proper firewall rules +- [ ] **Database Access** - Database not publicly accessible +- [ ] **Principle of Least Privilege** - Minimal IAM permissions +- [ ] **Regular Backups** - Encrypted backups +- [ ] **Vulnerability Scanning** - Regular security scans + +## OWASP Top 10 Coverage +- [ ] **A01 Broken Access Control** - Authorization checks +- [ ] **A02 Cryptographic Failures** - Proper encryption +- [ ] **A03 Injection** - Input validation +- [ ] **A04 Insecure Design** - Security by design +- [ ] **A05 Security Misconfiguration** - Secure defaults +- [ ] **A06 Vulnerable Components** - Updated dependencies +- [ ] **A07 Authentication Failures** - Secure auth +- [ ] **A08 Data Integrity Failures** - Integrity checks +- [ ] **A09 Logging Failures** - Adequate logging +- [ ] **A10 SSRF** - SSRF prevention + +**Security Rating:** ⭐⭐⭐⭐⭐ \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/checklists/story-dod-checklist.md b/expansion-packs/javascript-fullstack-pack/checklists/story-dod-checklist.md new file mode 100644 index 00000000..ad6fe410 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/checklists/story-dod-checklist.md @@ -0,0 +1,82 @@ +# + +# Story Definition of Done Checklist + +## Story Quality + +### Requirements +- [ ] **Clear Description** - Story purpose is clear and specific +- [ ] **User Story Format** - As a [user], I want [action], so that [benefit] +- [ ] **Acceptance Criteria** - All AC clearly defined and testable +- [ ] **Technical Specs** - Implementation details provided +- [ ] **File List** - All files to create/modify listed +- [ ] **Dependencies** - All dependencies identified + +### Implementation +- [ ] **Code Complete** - All code written and working +- [ ] **TypeScript** - No TypeScript errors +- [ ] **Linting** - No ESLint warnings/errors +- [ ] **Code Review** - Peer reviewed and approved +- [ ] **Refactoring** - No obvious tech debt introduced + +### Testing +- [ ] **Unit Tests** - Tests written for new logic +- [ ] **Integration Tests** - API tests if backend changes +- [ ] **Component Tests** - React component tests if frontend +- [ ] **E2E Tests** - E2E test if critical user flow +- [ ] **Test Coverage** - Meets coverage requirements (>80%) +- [ ] **All Tests Pass** - Green CI build +- [ ] **Manual Testing** - Tested manually by developer + +### Frontend Specific +- [ ] **Responsive** - Works on mobile, tablet, desktop +- [ ] **Accessibility** - Keyboard navigation, ARIA labels, screen reader +- [ ] **Loading States** - Loading indicators implemented +- [ ] **Error States** - Error messages user-friendly +- [ ] **Empty States** - Empty state handling +- [ ] **Performance** - No performance regressions + +### Backend Specific +- [ ] **Input Validation** - All inputs validated +- [ ] **Error Handling** - Proper error responses +- [ ] **Logging** - Important actions logged +- [ ] **Authentication** - Auth checks if needed +- [ ] **Authorization** - Permission checks if needed +- [ ] **Database** - Migrations run, indexes added + +### Security +- [ ] **Input Sanitized** - User inputs sanitized +- [ ] **SQL Injection** - Protected (parameterized queries) +- [ ] **XSS Prevention** - Output encoded +- [ ] **Authentication** - Protected routes checked +- [ ] **No Secrets** - No hardcoded secrets + +### Documentation +- [ ] **Code Comments** - Complex logic commented +- [ ] **README Updated** - If new setup required +- [ ] **API Docs** - API documentation updated +- [ ] **Types Documented** - TypeScript interfaces documented + +### Git & Deployment +- [ ] **Branch Up-to-date** - Merged latest main +- [ ] **Commits** - Meaningful commit messages +- [ ] **PR Description** - Clear PR description with context +- [ ] **No Merge Conflicts** - Conflicts resolved +- [ ] **CI Passing** - All CI checks green +- [ ] **Deployed to Staging** - Tested on staging environment + +### Product/Business +- [ ] **Acceptance Criteria Met** - All AC satisfied +- [ ] **Product Owner Approved** - PO signed off +- [ ] **QA Tested** - QA tested and approved (if QA exists) +- [ ] **User Feedback** - Tested by end user if possible + +## Definition of DONE + +**Story Complete:** [ ] Yes [ ] No + +**Verified By:** _________ +**Date:** _________ + +**Notes:** +_Any additional context or issues encountered_ \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/config.yaml b/expansion-packs/javascript-fullstack-pack/config.yaml new file mode 100644 index 00000000..e40e2d97 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/config.yaml @@ -0,0 +1,10 @@ +# +name: bmad-javascript-fullstack +version: 1.0.0 +short-title: JavaScript Full-Stack Dev Pack +description: >- + Comprehensive expansion pack for modern JavaScript/TypeScript full-stack + development. Specialized agents for React, Node.js, API design, and + TypeScript expertise. Complete workflows from architecture to deployment. +author: BMAD Community +slashPrefix: bmad-js \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/data/architecture-patterns.md b/expansion-packs/javascript-fullstack-pack/data/architecture-patterns.md new file mode 100644 index 00000000..04c67c9d --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/data/architecture-patterns.md @@ -0,0 +1,180 @@ +# + +# JavaScript Architecture Patterns + +## Pattern 1: Monolithic Full-Stack +**Best For:** Small to medium applications, teams < 10, MVP phase + +**Stack:** +- Frontend: Next.js with App Router +- Backend: Next.js API routes or separate Express/NestJS +- Database: PostgreSQL with Prisma +- Deployment: Vercel or single container + +**Pros:** +- Simple to develop and deploy +- Easy to reason about +- Fast initial development +- Shared types between frontend/backend + +**Cons:** +- Harder to scale parts independently +- Can become unwieldy as it grows +- Single point of failure + +**When to Use:** +- MVP or small applications +- Small team (1-10 developers) +- Tight coupling acceptable +- Simple deployment needs + +## Pattern 2: JAMstack with Serverless +**Best For:** Content-heavy sites, marketing sites, blogs + +**Stack:** +- Frontend: Next.js (Static Export) or Astro +- Backend: Serverless functions (Vercel, Netlify) +- Database: Supabase, Planetscale, or Firebase +- CMS: Contentful, Sanity, Strapi +- Deployment: Vercel or Netlify + +**Pros:** +- Excellent performance +- Cost-effective (pay per use) +- Great developer experience +- Global CDN distribution + +**Cons:** +- Cold starts for functions +- Limited execution time (30s typically) +- Harder to debug +- Vendor lock-in + +## Pattern 3: Microservices +**Best For:** Large teams, complex domains, independent scaling needs + +**Stack:** +- Frontend: Next.js or multiple SPAs +- API Gateway: Kong or custom Express +- Services: NestJS or Express services +- Message Queue: RabbitMQ or Kafka +- Databases: Polyglot (PostgreSQL, MongoDB, Redis) +- Container Orchestration: Kubernetes or Docker Swarm + +**Pros:** +- Independent scaling +- Team autonomy +- Technology flexibility +- Fault isolation + +**Cons:** +- Complex to operate +- Distributed system challenges +- Higher infrastructure costs +- Requires DevOps expertise + +## Pattern 4: Backend for Frontend (BFF) +**Best For:** Multiple client types (web, mobile, desktop) + +**Stack:** +- Frontends: Next.js (web), React Native (mobile) +- BFF Layer: Express or Fastify per client type +- Backend Services: Shared microservices +- Database: PostgreSQL with Prisma + +**Pros:** +- Optimized for each client +- Decoupled client and server evolution +- Flexible data aggregation + +**Cons:** +- Code duplication across BFFs +- More services to maintain +- Complexity in coordination + +## Pattern 5: Event-Driven Architecture +**Best For:** Real-time features, complex workflows, high decoupling + +**Stack:** +- Frontend: Next.js with WebSocket or Server-Sent Events +- Backend: Express/NestJS with event emitters +- Message Queue: RabbitMQ, Kafka, or AWS SQS +- Event Store: EventStoreDB or custom +- Databases: PostgreSQL + Redis + +**Pros:** +- Loose coupling +- Scalable +- Async processing +- Event sourcing capabilities + +**Cons:** +- Eventual consistency +- Debugging complexity +- Requires event schema management +- Learning curve + +## Decision Matrix + +| Pattern | Team Size | Complexity | Scale | Cost | DX | +|---------|-----------|------------|-------|------|-----| +| Monolith | 1-10 | Low | Low-Med | Low | Excellent | +| JAMstack | 1-5 | Low | Med-High | Low | Excellent | +| Microservices | 10+ | High | High | High | Good | +| BFF | 5-15 | Med | Med-High | Med | Good | +| Event-Driven | 5+ | High | High | Med-High | Fair | + +## Technology Selection Guide + +### Frontend Frameworks +- **Next.js**: Full-stack React, SSR/SSG, API routes +- **Vite + React**: SPA, fast dev, flexible +- **Astro**: Content-focused, islands architecture +- **Remix**: Full-stack React, nested routing + +### Backend Frameworks +- **Express**: Flexible, minimalist, huge ecosystem +- **Fastify**: High performance, schema validation +- **NestJS**: Enterprise-ready, Angular-inspired, TypeScript-first +- **tRPC**: Type-safe APIs, no code generation + +### Databases +- **PostgreSQL**: Relational, ACID, JSON support +- **MongoDB**: Document, flexible schema +- **Redis**: Caching, sessions, pub/sub +- **Supabase**: PostgreSQL + auth + realtime + +### State Management +- **React Query**: Server state (recommended) +- **Zustand**: Lightweight global state +- **Redux Toolkit**: Complex global state +- **Context API**: Simple prop drilling solution + +### Styling +- **Tailwind CSS**: Utility-first (recommended) +- **CSS Modules**: Scoped styles +- **Styled Components**: CSS-in-JS +- **Emotion**: CSS-in-JS with better perf + +## Migration Paths + +### From Monolith to Microservices +1. Identify bounded contexts +2. Extract one service at a time +3. Start with least-coupled features +4. Use API gateway for routing +5. Migrate data gradually + +### From JavaScript to TypeScript +1. Enable TypeScript with allowJs +2. Add type definitions incrementally +3. Convert files one by one +4. Enable strict mode gradually +5. Remove allowJs when done + +### From CSR to SSR/SSG +1. Adopt Next.js or similar +2. Convert pages to SSR/SSG +3. Optimize data fetching +4. Implement ISR where needed +5. Measure performance gains \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/data/best-practices.md b/expansion-packs/javascript-fullstack-pack/data/best-practices.md new file mode 100644 index 00000000..346d4e65 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/data/best-practices.md @@ -0,0 +1,194 @@ +# + +# Full-Stack JavaScript Best Practices + +## General Principles +- **Type Safety First** - Use TypeScript strict mode +- **Test Critical Paths** - Focus testing on business logic +- **Security by Default** - Validate all inputs, sanitize outputs +- **Performance Matters** - Optimize from the start +- **Document Decisions** - Use ADRs for major choices + +## Frontend Best Practices + +### React +- Use functional components with hooks +- Memoize expensive computations with useMemo/useCallback +- Extract custom hooks for reusable logic +- Keep components small (< 300 lines) +- Use React.memo for expensive components +- Implement error boundaries +- Handle loading and error states + +### State Management +- Use React Query for server state +- Keep state as local as possible +- Lift state only when needed +- Avoid prop drilling (use Context sparingly) +- Use Zustand for simple global state +- Redux Toolkit for complex state + +### Performance +- Code split routes and heavy components +- Lazy load images below the fold +- Use next/image or optimized images +- Virtual scroll long lists +- Prefetch critical resources +- Minimize bundle size + +### Accessibility +- Use semantic HTML +- Add ARIA labels where needed +- Ensure keyboard navigation +- Test with screen readers +- Maintain color contrast (4.5:1) +- Provide focus indicators + +## Backend Best Practices + +### API Design +- Follow RESTful conventions +- Version APIs from day one (/api/v1/) +- Use proper HTTP methods and status codes +- Implement pagination for lists +- Add rate limiting +- Document with OpenAPI/Swagger + +### Security +- Hash passwords with bcrypt +- Use JWT with short expiration +- Validate all inputs (Zod, Joi) +- Sanitize user-generated content +- Use parameterized queries +- Enable CORS for specific origins +- Set security headers (Helmet.js) + +### Database +- Use an ORM (Prisma recommended) +- Add indexes on frequently queried fields +- Avoid N+1 queries +- Use transactions for multi-step operations +- Implement connection pooling +- Regular backups + +### Error Handling +- Use custom error classes +- Centralized error handling middleware +- Log errors with context +- Return user-friendly messages +- Hide stack traces in production +- Monitor error rates + +## Testing Best Practices + +### Frontend +- Test user interactions, not implementation +- Use React Testing Library +- Mock external dependencies +- Test accessibility with axe-core +- E2E tests for critical flows (Playwright) +- Aim for > 80% coverage + +### Backend +- Test business logic thoroughly +- Integration tests for APIs (Supertest) +- Mock external services +- Test error scenarios +- Database tests with test database +- Aim for > 85% coverage + +## DevOps Best Practices + +### CI/CD +- Run tests on every commit +- Lint and type check in CI +- Automated deployments to staging +- Manual approval for production +- Rollback capability + +### Monitoring +- Set up error tracking (Sentry) +- Application performance monitoring +- Log aggregation +- Uptime monitoring +- Alert on critical issues + +### Deployment +- Use environment variables +- Blue-green or canary deployments +- Health check endpoints +- Database migrations before deployment +- Zero-downtime deployments + +## Code Quality + +### General +- Follow single responsibility principle +- DRY (Don't Repeat Yourself) +- KISS (Keep It Simple, Stupid) +- YAGNI (You Aren't Gonna Need It) +- Write self-documenting code + +### Code Review +- Review all changes before merging +- Provide constructive feedback +- Approve only when standards met +- Share knowledge through reviews + +### Documentation +- README with setup instructions +- Architecture decision records (ADRs) +- API documentation (OpenAPI) +- Inline comments for complex logic +- Keep documentation up to date + +## Performance Budgets + +### Frontend +- LCP < 2.5s +- FID < 100ms +- CLS < 0.1 +- Bundle size < 200KB (gzipped) + +### Backend +- API response < 200ms (p95) +- Database query < 100ms +- Uptime > 99.9% +- Error rate < 0.1% + +## Common Anti-Patterns to Avoid + +### Frontend +- ❌ Prop drilling (use Context or state library) +- ❌ Inline functions in render +- ❌ Mutating state directly +- ❌ Missing key props in lists +- ❌ Using index as key +- ❌ Too many useEffect dependencies + +### Backend +- ❌ Callback hell (use async/await) +- ❌ Not validating inputs +- ❌ Ignoring errors +- ❌ Synchronous operations +- ❌ Missing error handling +- ❌ Not using transactions + +### Database +- ❌ N+1 queries +- ❌ Missing indexes +- ❌ SELECT * (select specific fields) +- ❌ Not using pagination +- ❌ Storing unencrypted sensitive data + +## Quick Wins +- Add TypeScript for type safety +- Enable ESLint and Prettier +- Set up pre-commit hooks (Husky) +- Add database indexes +- Enable gzip compression +- Use CDN for static assets +- Implement caching (Redis) +- Add monitoring (Sentry) +- Write integration tests +- Document setup in README \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/data/deployment-strategies.md b/expansion-packs/javascript-fullstack-pack/data/deployment-strategies.md new file mode 100644 index 00000000..773168d8 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/data/deployment-strategies.md @@ -0,0 +1,306 @@ +# + +# Deployment Strategies for JavaScript Applications + +## Deployment Patterns + +### 1. Rolling Deployment +**How it works:** Gradually replace old instances with new ones + +**Pros:** +- Simple to implement +- No additional infrastructure needed +- Zero downtime + +**Cons:** +- During deployment, old and new versions run simultaneously +- Rollback requires another deployment + +**Best for:** Most applications, default choice + +### 2. Blue-Green Deployment +**How it works:** Two identical environments, switch traffic between them + +**Pros:** +- Instant rollback (switch back) +- Test new version before switching +- Zero downtime + +**Cons:** +- Double infrastructure cost during deployment +- Database migrations can be tricky + +**Best for:** Critical applications needing instant rollback + +### 3. Canary Deployment +**How it works:** Route small % of traffic to new version, gradually increase + +**Pros:** +- Test with real users safely +- Early problem detection +- Gradual rollout reduces risk + +**Cons:** +- Complex routing logic +- Need good monitoring +- Longer deployment time + +**Best for:** High-risk changes, large user bases + +## Platform-Specific Deployment + +### Vercel (Recommended for Next.js) +```bash +# Install Vercel CLI +npm i -g vercel + +# Deploy +vercel --prod + +# Environment variables +vercel env add DATABASE_URL production +``` + +**Features:** +- Automatic HTTPS +- Global CDN +- Preview deployments for PRs +- Zero-config for Next.js +- Serverless functions + +### Railway (Backend/Full-stack) +```bash +# Install Railway CLI +npm i -g @railway/cli + +# Login and init +railway login +railway init + +# Deploy +railway up +``` + +**Features:** +- PostgreSQL, Redis, MongoDB +- Environment variables +- Automatic SSL +- GitHub integration + +### Docker + Fly.io +```dockerfile +# Dockerfile +FROM node:18-alpine +WORKDIR /app +COPY package*.json ./ +RUN npm ci --only=production +COPY . . +RUN npm run build +CMD ["npm", "start"] +``` + +```bash +# Deploy +fly launch +fly deploy +``` + +### AWS (EC2/ECS/Fargate) +- Most flexible +- Complex setup +- Full control +- Higher costs + +### DigitalOcean App Platform +- Simple like Heroku +- Reasonable pricing +- Good for full-stack apps + +## CI/CD Setup + +### GitHub Actions +**.github/workflows/deploy.yml:** +```yaml +name: Deploy to Production + +on: + push: + branches: [main] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + with: + node-version: 18 + - run: npm ci + - run: npm test + - run: npm run build + + deploy: + needs: test + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Deploy to Vercel + run: npx vercel --prod --token=${{ secrets.VERCEL_TOKEN }} +``` + +## Database Migrations + +### Strategy 1: Migrations Before Deployment +```bash +# Run migrations before deploying new code +npm run db:migrate +npm run deploy +``` + +**Pros:** Safer, new code expects new schema + +**Cons:** Brief downtime if migration is slow + +### Strategy 2: Backward-Compatible Migrations +```bash +# 1. Deploy code that works with old and new schema +# 2. Run migration +# 3. Deploy code that uses new schema only +``` + +**Pros:** Zero downtime + +**Cons:** More complex, requires multiple deploys + +### Prisma Migrations +```bash +# Generate migration +npx prisma migrate dev --name add_user_role + +# Apply in production +npx prisma migrate deploy +``` + +## Environment Management + +### Environments +- **Development:** Local machine +- **Staging:** Pre-production testing +- **Production:** Live application + +### Environment Variables +```bash +# Development (.env.local) +DATABASE_URL=postgresql://localhost:5432/dev +NEXT_PUBLIC_API_URL=http://localhost:3000 + +# Staging +DATABASE_URL=postgresql://staging.db/app +NEXT_PUBLIC_API_URL=https://staging.app.com + +# Production +DATABASE_URL=postgresql://prod.db/app +NEXT_PUBLIC_API_URL=https://app.com +``` + +## Rollback Strategies + +### 1. Git Revert + Redeploy +```bash +git revert HEAD +git push origin main +# Triggers new deployment +``` + +### 2. Previous Build Rollback +Most platforms keep previous builds: +```bash +# Vercel +vercel rollback + +# Railway +railway rollback + +# Fly.io +fly releases +fly deploy --image +``` + +### 3. Blue-Green Switch Back +If using blue-green, switch traffic back to previous environment + +## Health Checks + +```typescript +// /api/health endpoint +app.get('/health', async (req, res) => { + try { + // Check database + await prisma.$queryRaw`SELECT 1`; + + // Check Redis + await redis.ping(); + + res.json({ status: 'healthy' }); + } catch (error) { + res.status(503).json({ status: 'unhealthy', error }); + } +}); +``` + +## Monitoring Post-Deployment + +### Metrics to Watch +- Error rate +- Response time (p50, p95, p99) +- CPU/Memory usage +- Database connection pool +- API endpoint latencies + +### Tools +- **Sentry:** Error tracking +- **Datadog:** Full APM +- **Vercel Analytics:** Frontend vitals +- **PostHog:** Product analytics +- **Uptime Robot:** Uptime monitoring + +## Deployment Checklist + +### Pre-Deployment +- [ ] All tests pass locally and in CI +- [ ] Code reviewed and approved +- [ ] Database migrations tested on staging +- [ ] Environment variables configured +- [ ] Rollback plan ready +- [ ] Team notified of deployment + +### During Deployment +- [ ] Monitor error rates +- [ ] Check health endpoints +- [ ] Verify critical user flows +- [ ] Watch application metrics + +### Post-Deployment +- [ ] Smoke test production +- [ ] Check error tracking (Sentry) +- [ ] Monitor for 24 hours +- [ ] Update changelog +- [ ] Mark deployment as successful + +## Common Issues & Solutions + +**Issue:** Database connection pool exhausted + +**Solution:** Increase pool size or implement connection pooling middleware + +**Issue:** Cold starts in serverless + +**Solution:** Use provisioned concurrency or switch to container-based hosting + +**Issue:** Build failing in CI + +**Solution:** Ensure all dependencies in package.json, check environment variables + +**Issue:** Rollback needed + +**Solution:** Use platform-specific rollback or git revert + redeploy \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/data/development-guidelines.md b/expansion-packs/javascript-fullstack-pack/data/development-guidelines.md new file mode 100644 index 00000000..5aec5c54 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/data/development-guidelines.md @@ -0,0 +1,355 @@ +# + +# JavaScript/TypeScript Development Guidelines + +## Overview +This document establishes coding standards, best practices, and conventions for JavaScript/TypeScript full-stack development. These guidelines ensure consistency, quality, and maintainability. + +## TypeScript Standards + +### Configuration +**Required tsconfig.json settings:** +```json +{ + "compilerOptions": { + "strict": true, + "noImplicitAny": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "noImplicitReturns": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true + } +} +``` + +### Type Definitions +- **No `any` types** - Use `unknown` if type is truly unknown +- **Interface vs Type** - Prefer interfaces for object shapes, types for unions/intersections +- **Explicit return types** - Always specify return types for functions +- **Proper generics** - Use generics for reusable type-safe code + +```typescript +// ✅ Good +interface UserProps { + id: string; + name: string; + email: string; +} + +function getUser(id: string): Promise { + return db.user.findUnique({ where: { id } }); +} + +// ❌ Bad +function getUser(id: any): any { + return db.user.findUnique({ where: { id } }); +} +``` + +## Naming Conventions + +### Files and Folders +- **kebab-case** for utility files: `api-client.ts`, `string-utils.ts` +- **PascalCase** for components: `UserProfile.tsx`, `TodoList.tsx` +- **camelCase** for hooks: `useAuth.ts`, `useLocalStorage.ts` + +### Variables and Functions +- **camelCase** for variables and functions: `userName`, `fetchData()` +- **PascalCase** for classes and components: `UserService`, `Button` +- **UPPER_SNAKE_CASE** for constants: `API_BASE_URL`, `MAX_RETRIES` +- **Descriptive names** - `isLoading` not `loading`, `handleSubmit` not `submit` + +```typescript +// ✅ Good +const MAX_RETRY_COUNT = 3; +const isAuthenticated = checkAuth(); +function calculateTotalPrice(items: Item[]): number { } + +// ❌ Bad +const max = 3; +const auth = checkAuth(); +function calc(items: any): any { } +``` + +## React Best Practices + +### Component Structure +```typescript +// ✅ Good component structure +interface ButtonProps { + children: React.ReactNode; + onClick: () => void; + variant?: 'primary' | 'secondary'; + disabled?: boolean; +} + +export function Button({ + children, + onClick, + variant = 'primary', + disabled = false +}: ButtonProps) { + return ( + + ); +} +``` + +### Hooks Rules +- Call hooks at the top level +- Call hooks in the same order +- Only call hooks from React functions + +```typescript +// ✅ Good +function Component() { + const [state, setState] = useState(0); + const data = useFetch('/api/data'); + + useEffect(() => { + // effect + }, []); + + return
{data}
; +} + +// ❌ Bad - conditional hook +function Component() { + if (condition) { + useState(0); // ❌ Don't do this + } +} +``` + +### State Management +- **Local state** - `useState` for component-only state +- **Server state** - React Query/SWR for API data +- **Global state** - Zustand/Redux only when necessary +- **Derived state** - `useMemo` for computed values + +## Backend Best Practices + +### API Endpoints +```typescript +// ✅ Good - RESTful design +GET /api/v1/users +POST /api/v1/users +PATCH /api/v1/users/:id +DELETE /api/v1/users/:id + +// ❌ Bad - non-RESTful +GET /api/v1/getUsers +POST /api/v1/createUser +POST /api/v1/updateUser/:id +``` + +### Error Handling +```typescript +// ✅ Good - centralized error handling +class AppError extends Error { + constructor( + public statusCode: number, + public message: string, + public isOperational = true + ) { + super(message); + } +} + +app.use((err: Error, req: Request, res: Response, next: NextFunction) => { + if (err instanceof AppError) { + return res.status(err.statusCode).json({ + error: err.message + }); + } + + console.error(err); + res.status(500).json({ error: 'Internal server error' }); +}); +``` + +### Input Validation +```typescript +// ✅ Good - Zod validation +import { z } from 'zod'; + +const createUserSchema = z.object({ + email: z.string().email(), + name: z.string().min(2), + password: z.string().min(8), +}); + +app.post('/users', async (req, res) => { + const result = createUserSchema.safeParse(req.body); + + if (!result.success) { + return res.status(400).json({ + errors: result.error.errors + }); + } + + const user = await createUser(result.data); + res.status(201).json(user); +}); +``` + +## Code Organization + +### Frontend Structure +``` +src/ +├── components/ +│ ├── ui/ # Reusable UI components +│ ├── features/ # Feature-specific components +│ └── layout/ # Layout components +├── hooks/ # Custom React hooks +├── lib/ # Utilities and helpers +├── pages/ # Next.js pages or routes +├── styles/ # Global styles +├── types/ # TypeScript types +└── utils/ # Utility functions +``` + +### Backend Structure +``` +src/ +├── controllers/ # Request handlers +├── services/ # Business logic +├── repositories/ # Data access layer +├── middleware/ # Express/Fastify middleware +├── routes/ # Route definitions +├── types/ # TypeScript types +├── utils/ # Utility functions +└── config/ # Configuration files +``` + +## Testing Standards + +### Frontend Tests +```typescript +// ✅ Good - React Testing Library +import { render, screen, fireEvent } from '@testing-library/react'; +import { Button } from './Button'; + +describe('Button', () => { + it('calls onClick when clicked', async () => { + const handleClick = jest.fn(); + render(); + + await fireEvent.click(screen.getByText('Click me')); + + expect(handleClick).toHaveBeenCalledTimes(1); + }); +}); +``` + +### Backend Tests +```typescript +// ✅ Good - Supertest API tests +import request from 'supertest'; +import { app } from '../app'; + +describe('POST /users', () => { + it('creates a new user', async () => { + const response = await request(app) + .post('/users') + .send({ + email: 'test@example.com', + name: 'Test User', + password: 'password123', + }) + .expect(201); + + expect(response.body).toMatchObject({ + email: 'test@example.com', + name: 'Test User', + }); + }); +}); +``` + +## Security Guidelines + +### Authentication +- Hash passwords with bcrypt (10-12 rounds) +- Use JWT with short expiration (15-60 min) +- Implement refresh tokens +- Store tokens in httpOnly cookies + +### Authorization +- Check permissions on every protected route +- Implement RBAC or ABAC +- Never trust client-side checks + +### Input Validation +- Validate ALL user inputs +- Sanitize HTML content +- Use parameterized queries for SQL +- Validate file uploads (type, size) + +### API Security +- Enable CORS with specific origins +- Use rate limiting +- Implement CSRF protection +- Set security headers (Helmet.js) + +## Performance Guidelines + +### Frontend +- Code split routes and heavy components +- Lazy load images below the fold +- Use next/image for automatic optimization +- Memoize expensive computations +- Virtual scroll long lists + +### Backend +- Add database indexes on frequently queried fields +- Use connection pooling +- Implement caching (Redis) +- Paginate large datasets +- Use background jobs for long tasks + +## Git Commit Conventions + +```bash +# Format: (): + +# Types: +feat: # New feature +fix: # Bug fix +docs: # Documentation only +style: # Code style (formatting, no logic change) +refactor: # Code refactoring +test: # Adding tests +chore: # Maintenance (deps, build, etc) + +# Examples: +feat(auth): add password reset functionality +fix(api): handle null values in user endpoint +docs(readme): update setup instructions +refactor(components): extract Button component +``` + +## Code Review Checklist + +Before submitting PR: +- [ ] TypeScript compiles without errors +- [ ] ESLint passes with no warnings +- [ ] All tests pass +- [ ] Test coverage meets requirements (>80%) +- [ ] No console.logs or debugger statements +- [ ] Meaningful commit messages +- [ ] PR description explains changes +- [ ] Documentation updated if needed + +This living document should be updated as the team establishes new patterns and best practices. \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/data/security-guidelines.md b/expansion-packs/javascript-fullstack-pack/data/security-guidelines.md new file mode 100644 index 00000000..1b425233 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/data/security-guidelines.md @@ -0,0 +1,210 @@ +# + +# Security Guidelines for JavaScript Applications + +## Authentication + +### Password Security +- Use bcrypt or argon2 with 10-12 rounds +- Minimum length: 8 characters +- Require mix of letters, numbers, symbols +- Store only hashed passwords, never plain text +- Implement password reset with expiring tokens + +### JWT Tokens +- Short expiration (15-60 minutes) +- Refresh token strategy +- Store in httpOnly cookies or secure storage +- Sign with strong secret (256-bit) +- Include user ID and minimal claims only + +### Example: +```typescript +import bcrypt from 'bcrypt'; +import jwt from 'jsonwebtoken'; + +// Hash password +const hashedPassword = await bcrypt.hash(password, 10); + +// Generate JWT +const token = jwt.sign( + { userId: user.id }, + process.env.JWT_SECRET!, + { expiresIn: '15m' } +); +``` + +## Input Validation + +### Frontend Validation +- For UX, not security +- Validate with React Hook Form + Zod +- Show user-friendly error messages + +### Backend Validation (Critical) +```typescript +import { z } from 'zod'; + +const userSchema = z.object({ + email: z.string().email(), + name: z.string().min(2).max(100), + age: z.number().int().min(0).max(150), +}); + +// Validate +const result = userSchema.safeParse(req.body); +if (!result.success) { + return res.status(400).json({ errors: result.error }); +} +``` + +## SQL Injection Prevention +- Always use parameterized queries +- Use ORMs (Prisma, TypeORM) +- Never concatenate user input into SQL + +```typescript +// ✅ Good - Prisma +const user = await prisma.user.findUnique({ + where: { email: userEmail } +}); + +// ❌ Bad - Raw SQL with concatenation +const query = `SELECT * FROM users WHERE email = '${userEmail}'`; +``` + +## XSS Prevention +- React escapes by default +- Avoid dangerouslySetInnerHTML +- Use DOMPurify if HTML needed +- Set Content Security Policy headers + +```typescript +// CSP Header +app.use(helmet({ + contentSecurityPolicy: { + directives: { + defaultSrc: ["'self'"], + scriptSrc: ["'self'", "'unsafe-inline'"], + styleSrc: ["'self'", "'unsafe-inline'"], + imgSrc: ["'self'", "data:", "https:"], + } + } +})); +``` + +## CSRF Protection +- Use CSRF tokens for state-changing operations +- SameSite cookies (Strict or Lax) +- Validate request origin + +```typescript +import csrf from 'csurf'; + +const csrfProtection = csrf({ cookie: true }); +app.use(csrfProtection); +``` + +## CORS Configuration +```typescript +import cors from 'cors'; + +app.use(cors({ + origin: process.env.ALLOWED_ORIGINS?.split(','), + credentials: true, + methods: ['GET', 'POST', 'PATCH', 'DELETE'], + maxAge: 86400, +})); +``` + +## Rate Limiting +```typescript +import rateLimit from 'express-rate-limit'; + +const limiter = rateLimit({ + windowMs: 15 * 60 * 1000, // 15 minutes + max: 100, // limit each IP + message: 'Too many requests', +}); + +app.use('/api', limiter); + +// Stricter for auth +const authLimiter = rateLimit({ + windowMs: 15 * 60 * 1000, + max: 5, +}); + +app.use('/api/auth', authLimiter); +``` + +## Security Headers +```typescript +import helmet from 'helmet'; + +app.use(helmet()); +// Sets: X-Content-Type-Options, X-Frame-Options, +// Strict-Transport-Security, etc. +``` + +## Secrets Management +- Never commit .env files +- Use environment variables +- Rotate secrets regularly +- Use secret management services (AWS Secrets Manager) + +```.env.example +DATABASE_URL=postgresql://... +JWT_SECRET=your-secret-here +STRIPE_SECRET_KEY=sk_test_... +``` + +## HTTPS/TLS +- Use HTTPS in production (always) +- Redirect HTTP to HTTPS +- Use HSTS header +- Valid SSL certificate + +## File Uploads +```typescript +import multer from 'multer'; + +const upload = multer({ + limits: { + fileSize: 5 * 1024 * 1024, // 5MB + }, + fileFilter: (req, file, cb) => { + const allowed = ['image/jpeg', 'image/png', 'image/gif']; + if (!allowed.includes(file.mimetype)) { + return cb(new Error('Invalid file type')); + } + cb(null, true); + }, +}); +``` + +## OWASP Top 10 Checklist +- [ ] A01: Broken Access Control - Implement proper authorization +- [ ] A02: Cryptographic Failures - Use HTTPS, encrypt sensitive data +- [ ] A03: Injection - Use parameterized queries +- [ ] A04: Insecure Design - Security by design +- [ ] A05: Security Misconfiguration - Secure defaults +- [ ] A06: Vulnerable Components - Keep dependencies updated +- [ ] A07: Authentication Failures - Strong auth implementation +- [ ] A08: Data Integrity Failures - Validate and verify data +- [ ] A09: Logging Failures - Log security events +- [ ] A10: Server-Side Request Forgery - Validate URLs + +## Security Audit Checklist +- [ ] npm audit passes (no high/critical vulnerabilities) +- [ ] All inputs validated on backend +- [ ] Passwords properly hashed +- [ ] JWT tokens expire appropriately +- [ ] HTTPS enforced in production +- [ ] Security headers configured +- [ ] Rate limiting enabled +- [ ] CORS properly configured +- [ ] Secrets not in code +- [ ] Database uses parameterized queries +- [ ] Error messages don't leak info +- [ ] Logging doesn't include sensitive data \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/data/technology-stack-guide.md b/expansion-packs/javascript-fullstack-pack/data/technology-stack-guide.md new file mode 100644 index 00000000..3867b004 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/data/technology-stack-guide.md @@ -0,0 +1,175 @@ +# + +# Technology Stack Selection Guide + +## Decision Framework + +### Consider These Factors +1. **Team expertise** - What does your team know? +2. **Project requirements** - What are you building? +3. **Scale requirements** - Expected traffic and data volume? +4. **Timeline** - How fast do you need to ship? +5. **Budget** - Infrastructure and development costs? +6. **Maintenance** - Long-term support needs? + +## Recommended Stacks by Use Case + +### 1. MVP / Startup (Speed Priority) +**Stack:** T3 Stack or Next.js + Supabase +- Frontend: Next.js 14 +- Backend: Next.js API routes or tRPC +- Database: Supabase (PostgreSQL + Auth + Realtime) +- Deployment: Vercel +- Why: Fastest time to market, minimal config, great DX + +### 2. SaaS Application (Scale Priority) +**Stack:** Next.js + NestJS + PostgreSQL +- Frontend: Next.js 14 with App Router +- Backend: NestJS (modular, testable) +- Database: PostgreSQL with Prisma +- Cache: Redis +- Queue: Bull/BullMQ +- Deployment: Frontend (Vercel), Backend (Railway/Render) +- Why: Enterprise-ready, scales well, great TypeScript support + +### 3. E-commerce (Performance Priority) +**Stack:** Next.js + Shopify/Stripe + PostgreSQL +- Frontend: Next.js with ISR +- Payment: Stripe or Shopify +- Database: PostgreSQL with Prisma +- Cache: Redis +- CDN: CloudFlare or Vercel Edge +- Why: Fast page loads, built-in payments, SEO-friendly + +### 4. Real-time App (Chat, Collaboration) +**Stack:** Next.js + Express + Socket.io + Redis +- Frontend: Next.js +- Backend: Express with Socket.io +- Database: PostgreSQL + MongoDB (messages) +- Cache/Pub-Sub: Redis +- Why: Excellent WebSocket support, real-time updates + +### 5. API-First / Mobile Backend +**Stack:** Fastify + PostgreSQL + Redis +- Backend: Fastify (high performance) +- Database: PostgreSQL with Prisma +- Cache: Redis +- API: REST or GraphQL +- Deployment: Railway, Fly.io, or AWS +- Why: Fast, lightweight, API-focused + +### 6. Enterprise Application +**Stack:** NestJS + PostgreSQL + Microservices +- Backend: NestJS (modular architecture) +- Database: PostgreSQL +- Message Queue: RabbitMQ or Kafka +- Monitoring: Datadog or New Relic +- Container: Docker + Kubernetes +- Why: Enterprise patterns, testable, maintainable + +## Technology Comparison + +### Frontend Frameworks +| Framework | Best For | Learning Curve | Performance | Ecosystem | +|-----------|----------|----------------|-------------|-----------| +| Next.js | Full-stack apps | Medium | Excellent | Huge | +| Vite + React | SPAs | Low | Excellent | Huge | +| Remix | Full-stack, data-heavy | Medium | Excellent | Growing | +| Astro | Content sites | Low | Excellent | Growing | + +### Backend Frameworks +| Framework | Best For | Learning Curve | Performance | DX | +|-----------|----------|----------------|-------------|-----| +| Express | Flexibility | Low | Good | Good | +| Fastify | Performance | Low | Excellent | Good | +| NestJS | Enterprise | Medium-High | Good | Excellent | +| tRPC | Type safety | Low | Good | Excellent | + +### Databases +| Database | Best For | Scaling | Query Language | ACID | +|----------|----------|---------|----------------|------| +| PostgreSQL | Relational data | Excellent | SQL | Yes | +| MongoDB | Flexible schema | Excellent | MQL | No | +| MySQL | Traditional apps | Good | SQL | Yes | +| Redis | Caching, sessions | Excellent | Commands | No | + +### ORMs +| ORM | Best For | DX | Type Safety | Performance | +|-----|----------|-----|-------------|-------------| +| Prisma | Modern apps | Excellent | Excellent | Good | +| TypeORM | TypeScript | Good | Good | Good | +| Drizzle | Performance | Good | Excellent | Excellent | +| Mongoose | MongoDB | Good | Fair | Good | + +## Decision Trees + +### Choosing Frontend Framework +``` +Need SEO? + Yes → Need dynamic data? + Yes → Next.js (SSR/ISR) + No → Next.js (SSG) or Astro + No → Need maximum performance? + Yes → Vite + React + No → Next.js (great all-rounder) +``` + +### Choosing Backend Framework +``` +Team experience? + Beginners → Express (simple) + TypeScript experts → NestJS (structured) + Performance critical → Fastify + Need end-to-end types → tRPC +``` + +### Choosing Database +``` +Data structure? + Fixed schema → PostgreSQL + Flexible/nested → MongoDB + Need ACID → PostgreSQL + Document storage → MongoDB + Caching only → Redis +``` + +## Stack Templates + +### Starter Template +```json +{ + "frontend": "Next.js 14", + "backend": "Next.js API routes", + "database": "Supabase", + "hosting": "Vercel" +} +``` + +### Production Template +```json +{ + "frontend": "Next.js 14", + "backend": "NestJS", + "database": "PostgreSQL + Prisma", + "cache": "Redis", + "queue": "Bull", + "hosting": { + "frontend": "Vercel", + "backend": "Railway" + } +} +``` + +### Enterprise Template +```json +{ + "frontend": "Next.js 14 + TypeScript", + "backend": "NestJS microservices", + "database": "PostgreSQL + MongoDB", + "cache": "Redis Cluster", + "queue": "RabbitMQ", + "container": "Docker + Kubernetes", + "monitoring": "Datadog", + "ci_cd": "GitHub Actions" +} +``` \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/package.json b/expansion-packs/javascript-fullstack-pack/package.json index 7ed3ecd2..f2db6be1 100644 --- a/expansion-packs/javascript-fullstack-pack/package.json +++ b/expansion-packs/javascript-fullstack-pack/package.json @@ -48,6 +48,12 @@ "file": "agents/api-developer.md", "shortName": "api-developer", "description": "REST, GraphQL, and tRPC API design and implementation" + }, + { + "name": "TypeScript Expert", + "file": "agents/typescript-expert.md", + "shortName": "typescript-expert", + "description": "Advanced TypeScript patterns, type safety, and migration expertise" } ], "templates": { diff --git a/expansion-packs/javascript-fullstack-pack/tasks/code-review.md b/expansion-packs/javascript-fullstack-pack/tasks/code-review.md new file mode 100644 index 00000000..30369b46 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/tasks/code-review.md @@ -0,0 +1,144 @@ +# + +# Code Review Task + +## Purpose +Systematic code review process for JavaScript/TypeScript pull requests to maintain code quality and catch issues before production. + +## When to Use +- Before merging any pull request +- After completing a feature or story +- Regular code quality audits + +## Code Review Checklist + +### 1. Functional Correctness +- [ ] **Implements Requirements** - All acceptance criteria met +- [ ] **No Regressions** - Existing functionality still works +- [ ] **Edge Cases** - Handles edge cases and errors +- [ ] **User Experience** - UX is intuitive and polished + +### 2. Code Quality +- [ ] **Readable** - Code is self-documenting +- [ ] **No Duplication** - DRY principle followed +- [ ] **Single Responsibility** - Functions/components have single purpose +- [ ] **Appropriate Complexity** - Not over-engineered or under-engineered +- [ ] **Naming** - Variables, functions, components well-named + +### 3. TypeScript Quality +- [ ] **No `any` Types** - Proper types used everywhere +- [ ] **Type Safety** - No type assertions unless necessary +- [ ] **Interfaces** - Props and DTOs properly typed +- [ ] **Generics** - Generic types used appropriately +- [ ] **No TypeScript Errors** - `tsc --noEmit` passes + +### 4. React Best Practices (if applicable) +- [ ] **Hooks Rules** - Hooks used correctly +- [ ] **Dependencies** - useEffect dependencies complete +- [ ] **Memoization** - useMemo/useCallback where needed +- [ ] **Component Size** - Components are reasonably sized +- [ ] **No Inline Functions** - Callbacks memoized in render-heavy components + +### 5. Backend Best Practices (if applicable) +- [ ] **Input Validation** - All inputs validated +- [ ] **Error Handling** - Errors handled gracefully +- [ ] **Authentication** - Auth checks on protected routes +- [ ] **SQL Injection** - Parameterized queries used +- [ ] **Logging** - Important actions logged + +### 6. Testing +- [ ] **Tests Written** - New code has tests +- [ ] **Tests Pass** - All tests green +- [ ] **Coverage** - Meets coverage goals +- [ ] **Test Quality** - Tests are meaningful, not just for coverage +- [ ] **Edge Cases Tested** - Error paths tested + +### 7. Security +- [ ] **No Secrets** - No hardcoded secrets +- [ ] **Input Sanitized** - User inputs validated and sanitized +- [ ] **Authorization** - Proper permission checks +- [ ] **Dependencies** - No vulnerable dependencies + +### 8. Performance +- [ ] **No Performance Regressions** - Page load times acceptable +- [ ] **Database Queries** - Queries optimized +- [ ] **Bundle Size** - No unnecessary dependencies added +- [ ] **Images** - Images optimized + +### 9. Documentation +- [ ] **Code Comments** - Complex logic commented +- [ ] **README** - Updated if needed +- [ ] **API Docs** - API documentation updated +- [ ] **Changelog** - Changes documented + +### 10. Git Hygiene +- [ ] **Commit Messages** - Clear, descriptive commits +- [ ] **No Merge Conflicts** - Conflicts resolved +- [ ] **Branch Up-to-date** - Merged latest main +- [ ] **PR Description** - Clear description with context + +## Review Process + +### As Reviewer +1. **Understand Context** - Read PR description and linked issues +2. **Check CI** - Verify CI passes +3. **Review Code** - Go through changes systematically +4. **Test Locally** - Pull branch and test if needed +5. **Provide Feedback** - Be constructive and specific +6. **Approve or Request Changes** + +### Providing Feedback +- **Be Specific** - "Consider extracting this into a helper" not "needs refactoring" +- **Explain Why** - "This could cause a memory leak because..." +- **Suggest Solutions** - Provide code examples when possible +- **Be Kind** - Assume positive intent, critique code not person +- **Differentiate** - Mark comments as "blocking" vs "nit" vs "question" + +### As Author +1. **Respond to All Comments** - Address or discuss each comment +2. **Make Changes** - Fix blocking issues +3. **Re-request Review** - After making changes +4. **Merge** - Only after approval + +## Common Issues to Watch For + +### JavaScript/TypeScript +- Using `var` instead of `const/let` +- Not handling promises properly +- Ignoring TypeScript errors with `@ts-ignore` +- Using `any` instead of proper types +- Not validating inputs + +### React +- Missing keys in lists +- Incorrect useEffect dependencies +- Large components (>300 lines) +- Inline function definitions in JSX +- Not handling loading/error states + +### Backend +- Not validating request bodies +- Missing error handling +- SQL injection vulnerabilities +- Missing authorization checks +- Not logging errors + +### General +- Hardcoded values instead of configuration +- No tests for new code +- Breaking changes without migration +- Poor naming +- Duplicated code + +## Tools +- GitHub/GitLab PR interface +- VS Code with ESLint extension +- React DevTools for frontend +- Postman/Insomnia for API testing + +## Quality Gates +- [ ] All review comments addressed +- [ ] CI passing +- [ ] At least one approval +- [ ] No merge conflicts +- [ ] Up to date with main branch \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/tasks/create-api-spec.md b/expansion-packs/javascript-fullstack-pack/tasks/create-api-spec.md new file mode 100644 index 00000000..0c3a1e93 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/tasks/create-api-spec.md @@ -0,0 +1,96 @@ +# + +# Create API Specification Task + +## Purpose +Define complete API contracts for a JavaScript/TypeScript backend to ensure frontend-backend alignment and enable parallel development. + +## When to Use +- Before starting backend implementation +- When adding new API endpoints +- Documenting existing APIs +- Enabling frontend-backend parallel development + +## API Specification Structure + +### 1. Overview +- API Purpose and Scope +- Base URL (`https://api.example.com/v1`) +- Authentication Method (JWT, OAuth, API Key) +- Rate Limiting Policy +- Versioning Strategy + +### 2. Authentication +```typescript +POST /auth/login +POST /auth/register +POST /auth/refresh +POST /auth/logout +``` + +### 3. Resource Endpoints +For each resource, document: + +``` +GET /api/v1/users # List users +GET /api/v1/users/:id # Get user by ID +POST /api/v1/users # Create user +PATCH /api/v1/users/:id # Update user +DELETE /api/v1/users/:id # Delete user +``` + +### 4. Endpoint Documentation Template + +**Endpoint:** `POST /api/v1/users` + +**Description:** Create a new user account + +**Authentication:** Required (Bearer token) + +**Request Body:** +```typescript +interface CreateUserRequest { + email: string; + name: string; + password: string; +} +``` + +**Response (201 Created):** +```typescript +interface CreateUserResponse { + id: string; + email: string; + name: string; + createdAt: string; +} +``` + +**Error Responses:** +- `400 Bad Request` - Validation error +- `401 Unauthorized` - Missing or invalid token +- `409 Conflict` - Email already exists +- `500 Internal Server Error` - Server error + +### 5. Type Definitions +Create comprehensive TypeScript interfaces for all DTOs + +### 6. OpenAPI/Swagger +Generate OpenAPI 3.0 specification for documentation and testing + +## Best Practices + +- Use consistent naming (camelCase for JSON fields) +- Document all possible error codes +- Include example requests and responses +- Define pagination format for list endpoints +- Specify rate limits per endpoint +- Version the API from day one + +## Validation +Use `checklists/api-design-checklist.md` to validate API design quality + +## Tools +- Swagger Editor for OpenAPI specs +- Postman/Insomnia for testing +- TypeScript for type safety \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/tasks/create-architecture-doc.md b/expansion-packs/javascript-fullstack-pack/tasks/create-architecture-doc.md new file mode 100644 index 00000000..7e1db152 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/tasks/create-architecture-doc.md @@ -0,0 +1,112 @@ +# + +# Create Architecture Document Task + +## Purpose +Document the technical architecture of a JavaScript/TypeScript full-stack application to guide implementation and ensure team alignment. + +## When to Use +- Starting a new greenfield project +- Major system refactoring +- Adding significant new capabilities +- Onboarding new team members +- Technical planning phase + +## Prerequisites +- Requirements analysis complete +- Technology stack decision made (or to be documented) +- Understanding of scale and performance needs +- Budget and timeline constraints known + +## Architecture Document Structure + +### 1. Executive Summary +- **System Overview** (2-3 paragraphs) +- **Technology Stack** (Frontend, Backend, Database, Infrastructure) +- **Architecture Pattern** (Monolith, Microservices, JAMstack, Serverless) +- **Key Decisions** (3-5 major decisions with rationale) +- **Scalability Overview** + +### 2. Frontend Architecture +- **Framework:** React/Next.js version with justification +- **Build Tool:** Vite, Webpack, Next.js built-in +- **State Management:** React Query + Zustand/Redux/Context +- **Routing:** File-based (Next.js) or React Router +- **Styling:** Tailwind, CSS Modules, Styled Components +- **Component Structure:** Folder organization +- **Code Splitting:** Strategy for optimization +- **SEO Strategy:** SSR, SSG, or CSR approach + +### 3. Backend Architecture +- **Runtime:** Node.js version +- **Framework:** Express, Fastify, NestJS +- **API Design:** REST, GraphQL, tRPC +- **Authentication:** JWT, OAuth, Sessions +- **Authorization:** RBAC, ABAC +- **Middleware:** Security, logging, error handling +- **Background Jobs:** Bull, BullMQ (if needed) + +### 4. Database Design +- **Database Choice:** PostgreSQL, MongoDB, etc with reasoning +- **ORM:** Prisma, TypeORM, Mongoose +- **Schema Design:** Entity relationships +- **Indexes:** Performance-critical indexes +- **Migrations:** Strategy and tooling +- **Backup:** Frequency and retention + +### 5. API Design +- **Versioning:** URL-based (/api/v1/) +- **Request/Response:** JSON schemas +- **Error Handling:** Standardized format +- **Pagination:** Cursor or offset +- **Rate Limiting:** Strategy and limits +- **Documentation:** OpenAPI/Swagger + +### 6. Non-Functional Requirements +- **Performance Targets:** Response time, page load +- **Security:** Authentication, encryption, OWASP +- **Scalability:** Horizontal scaling approach +- **Reliability:** Uptime, error rates +- **Monitoring:** Logging, APM, error tracking + +### 7. Infrastructure +- **Hosting:** Vercel, AWS, Railway, etc +- **CI/CD:** GitHub Actions, GitLab CI +- **Environments:** Dev, Staging, Production +- **Secrets Management:** Environment variables, vaults + +### 8. Development Standards +- **TypeScript:** tsconfig.json settings +- **Linting:** ESLint configuration +- **Testing:** Frameworks and coverage goals +- **Git:** Branch strategy, commit conventions + +## Best Practices + +### Keep It Practical +- Document decisions, not obvious choices +- Focus on "why" not just "what" +- Include diagrams for complex systems +- Keep it maintainable and up-to-date + +### Make It Actionable +- Clear enough for developers to implement +- Specific technology versions +- Configuration examples +- Code snippets for patterns + +### Use Architecture Decision Records (ADRs) +For each major decision: +- **Context:** What problem does this solve? +- **Decision:** What did we choose? +- **Consequences:** What are the trade-offs? + +## Validation +Use `checklists/architecture-review-checklist.md` to validate completeness + +## Handoff +Once complete: +1. Review with team +2. Get stakeholder approval +3. Save to `docs/architecture/` +4. Use as basis for story creation \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/tasks/create-development-story.md b/expansion-packs/javascript-fullstack-pack/tasks/create-development-story.md new file mode 100644 index 00000000..5fc5634d --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/tasks/create-development-story.md @@ -0,0 +1,225 @@ +# + +# Create Development Story Task + +## Purpose +Create detailed, actionable development stories for JavaScript/TypeScript full-stack features that enable developers to implement without additional design decisions. + +## When to Use +- Breaking down epics into implementable stories +- Converting architecture documents into development tasks +- Preparing work for sprint planning +- Ensuring clear handoffs from design to development + +## Prerequisites +Before creating stories, ensure you have: +- Completed architecture document +- PRD or feature requirements +- Epic definition this story belongs to +- Clear understanding of the specific feature + +## Process + +### 1. Story Identification +**Review Context:** +- Understand the epic's overall goal +- Review architecture document sections +- Identify specific feature to implement +- Verify no duplicate work + +**Feature Analysis:** +- Reference specific requirements +- Understand user experience goals +- Identify technical complexity +- Estimate implementation scope (1-3 days ideal) + +### 2. Story Scoping +**Single Responsibility:** +- Focus on one specific feature or component +- Ensure story is completable in 1-3 days +- Break down complex features into multiple stories +- Maintain clear boundaries with other stories + +**Implementation Clarity:** +- Define exactly what needs to be built +- Specify all technical requirements +- Include all necessary integration points +- Provide clear success criteria + +### 3. Template Execution +**Use Template:** +Use `templates/stories/javascript-development-story.md` template + +**Key Focus Areas:** +- Clear, actionable description with user story format +- Specific acceptance criteria (functional, technical, security) +- Detailed technical specifications +- Complete implementation task list +- Comprehensive testing requirements +- Type definitions and interfaces + +### 4. Story Validation +**Technical Review:** +- Verify all technical specifications are complete +- Ensure integration points are clearly defined +- Confirm file paths and structure +- Validate TypeScript interfaces + +**Architecture Alignment:** +- Confirm story implements architecture requirements +- Verify technology choices match architecture doc +- Check database changes align with schema +- Ensure API contracts are consistent + +**Implementation Readiness:** +- All dependencies identified and listed +- Asset requirements specified if needed +- Testing criteria defined +- Definition of Done complete + +### 5. Quality Assurance +**Apply Checklist:** +Execute `checklists/story-dod-checklist.md` against completed story + +**Story Criteria:** +- Story is immediately actionable +- No design decisions left to developer +- Technical requirements are complete +- Testing requirements are comprehensive +- Security requirements specified + +### 6. Story Refinement +**Developer Perspective:** +- Can a developer start implementation immediately? +- Are all technical questions answered? +- Is the scope appropriate for the estimated points? +- Are all dependencies clearly identified? + +**Iterative Improvement:** +- Address any gaps or ambiguities +- Clarify complex technical requirements +- Ensure story fits within epic scope +- Verify story points estimation (1, 2, 3, 5, 8) + +## Story Elements Checklist + +### Required Sections +- [ ] Clear user story (As a, I want, So that) +- [ ] Complete acceptance criteria (functional, technical) +- [ ] Detailed technical specifications +- [ ] File creation/modification list +- [ ] TypeScript interfaces and types +- [ ] Integration point specifications +- [ ] Ordered implementation tasks +- [ ] Comprehensive testing requirements +- [ ] Performance criteria +- [ ] Security considerations +- [ ] Dependencies clearly identified +- [ ] Definition of Done checklist + +### Full-Stack Considerations +- [ ] Frontend changes (if applicable) +- [ ] Backend changes (if applicable) +- [ ] API contract (if applicable) +- [ ] Database migrations (if applicable) +- [ ] Both client and server validation +- [ ] Error handling on both layers +- [ ] Loading states and user feedback + +### Technical Quality +- [ ] TypeScript strict mode compliance +- [ ] Architecture document alignment +- [ ] Code organization follows standards +- [ ] Error handling requirements +- [ ] Logging requirements +- [ ] Testing strategy defined + +## Common Pitfalls + +**Scope Issues:** +- Story too large (break into multiple stories - 1-3 days max) +- Story too vague (add specific requirements) +- Missing dependencies (identify all prerequisites) +- Unclear boundaries (define what's in/out of scope) + +**Technical Issues:** +- Missing integration details (API contracts, events) +- Incomplete technical specifications +- Undefined TypeScript interfaces +- Missing performance requirements +- No error handling specified + +**Full-Stack Coordination:** +- Frontend and backend changes not aligned +- API contract not defined +- Database changes not included +- Missing validation on both layers + +## Success Criteria + +**Story Readiness:** +- [ ] Developer can start implementation immediately +- [ ] No additional design decisions required +- [ ] All technical questions answered +- [ ] Testing strategy is complete +- [ ] Performance requirements are clear +- [ ] Security requirements specified +- [ ] Story fits within epic scope +- [ ] Estimated effort realistic (1-3 days) + +**Quality Validation:** +- [ ] Story DOD checklist passes +- [ ] Architecture alignment confirmed +- [ ] Requirements covered +- [ ] Implementation tasks are ordered and specific +- [ ] Dependencies are complete and accurate + +## Handoff Protocol + +**To Developer:** +1. Provide story document +2. Confirm access to architecture docs and requirements +3. Verify all dependencies are met +4. Answer any clarification questions +5. Establish check-in schedule + +**Story Status Updates:** +- To Do → In Development +- In Development → Code Review +- Code Review → QA Testing +- QA Testing → Done + +## Story Template Sections + +**Header:** +- Story ID, Epic, Sprint, Assignee, Status, Priority, Effort + +**Description:** +- User story format +- Background and context +- Goals + +**Acceptance Criteria:** +- Functional requirements (user-facing) +- Technical requirements (code quality) +- Performance requirements +- Security requirements + +**Technical Specification:** +- Frontend implementation (components, hooks, state) +- Backend implementation (endpoints, services, database) +- TypeScript types and interfaces +- Integration points + +**Testing:** +- Unit tests required +- Integration tests required +- E2E tests if critical flow +- Manual testing checklist + +**Dependencies:** +- Blocked by (must complete first) +- Blocks (what depends on this) +- Related stories + +This task ensures development stories are comprehensive, actionable, and enable efficient implementation of full-stack JavaScript features. \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/tasks/performance-optimization.md b/expansion-packs/javascript-fullstack-pack/tasks/performance-optimization.md new file mode 100644 index 00000000..fd82acbf --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/tasks/performance-optimization.md @@ -0,0 +1,241 @@ +# + +# Performance Optimization Task + +## Purpose +Systematic approach to identifying and resolving performance issues in JavaScript/TypeScript full-stack applications. + +## When to Use +- Performance targets not being met +- User complaints about slow loading +- High server costs due to inefficiency +- Preparing for increased scale +- Regular performance audits + +## Performance Optimization Process + +### 1. Measure Current Performance + +**Frontend Metrics:** +```bash +# Lighthouse CI +npm install -g @lhci/cli +lhci autorun +``` + +**Backend Metrics:** +- API response times (p50, p95, p99) +- Database query times +- Memory usage +- CPU usage + +**Tools:** +- Lighthouse for frontend +- Chrome DevTools Performance tab +- React DevTools Profiler +- APM tools (Datadog, New Relic) +- Database query analyzers (EXPLAIN ANALYZE) + +### 2. Identify Bottlenecks + +**Common Frontend Issues:** +- Large bundle size +- Slow images +- Too many re-renders +- Blocking JavaScript +- Large third-party scripts + +**Common Backend Issues:** +- Slow database queries (N+1 problems) +- Missing indexes +- No caching +- Synchronous operations +- Memory leaks + +### 3. Frontend Optimization + +#### Bundle Optimization +```bash +# Analyze bundle +npm run build +npx webpack-bundle-analyzer +``` + +**Actions:** +- Code split large components +- Lazy load routes +- Tree shake unused code +- Use dynamic imports +- Remove unused dependencies + +#### Image Optimization +- Use next/image for automatic optimization +- Serve WebP format with fallbacks +- Lazy load images below fold +- Use appropriate sizes (responsive images) +- Compress images (TinyPNG, ImageOptim) + +#### React Performance +```typescript +// Memoize expensive components +const ExpensiveComponent = React.memo(({ data }) => { + // ... +}); + +// Memoize callbacks +const handleClick = useCallback(() => { + // ... +}, [deps]); + +// Memoize expensive calculations +const sortedData = useMemo(() => { + return data.sort((a, b) => a.value - b.value); +}, [data]); + +// Virtual scrolling for long lists +import { useVirtualizer } from '@tanstack/react-virtual'; +``` + +#### Caching Strategy +```typescript +// React Query caching +const { data } = useQuery({ + queryKey: ['todos'], + queryFn: fetchTodos, + staleTime: 5 * 60 * 1000, // 5 minutes + cacheTime: 10 * 60 * 1000, // 10 minutes +}); +``` + +### 4. Backend Optimization + +#### Database Optimization +```typescript +// Add indexes +await prisma.$executeRaw` + CREATE INDEX idx_users_email ON users(email); +`; + +// Optimize queries +const users = await prisma.user.findMany({ + select: { + id: true, + name: true, + email: true, + // Only select needed fields + }, + where: { + isActive: true, + }, + take: 20, // Limit results +}); + +// Prevent N+1 +const postsWithAuthors = await prisma.post.findMany({ + include: { + author: true, // Eager load + }, +}); +``` + +#### Caching Layer +```typescript +import Redis from 'ioredis'; + +const redis = new Redis(); + +async function getCachedData(key: string, fetchFn: () => Promise) { + // Try cache first + const cached = await redis.get(key); + if (cached) return JSON.parse(cached); + + // Fetch and cache + const data = await fetchFn(); + await redis.setex(key, 300, JSON.stringify(data)); // 5 min TTL + return data; +} +``` + +#### Background Jobs +```typescript +import Queue from 'bull'; + +const emailQueue = new Queue('email', { + redis: { host: 'localhost', port: 6379 }, +}); + +// Don't block API responses +app.post('/send-email', async (req, res) => { + await emailQueue.add({ to, subject, body }); + res.json({ message: 'Email queued' }); +}); +``` + +### 5. Network Optimization + +**Enable Compression:** +```typescript +import compression from 'compression'; +app.use(compression()); +``` + +**CDN for Static Assets:** +- Host images, CSS, JS on CDN +- Use CloudFlare, AWS CloudFront, or Vercel Edge + +**HTTP/2:** +- Enable HTTP/2 on server +- Reduces latency for multiple requests + +### 6. Monitoring + +**Set Up Continuous Monitoring:** +- Lighthouse CI in GitHub Actions +- Error rate alerts +- Response time alerts +- CPU/Memory usage alerts + +**Performance Budget:** +```json +{ + "budgets": [{ + "path": "/*", + "timings": [{ + "metric": "interactive", + "budget": 3000 + }], + "resourceSizes": [{ + "resourceType": "script", + "budget": 200 + }] + }] +} +``` + +## Performance Targets + +### Frontend +- Lighthouse score: >90 +- LCP (Largest Contentful Paint): < 2.5s +- FID (First Input Delay): < 100ms +- CLS (Cumulative Layout Shift): < 0.1 +- Time to Interactive: < 3.5s + +### Backend +- API response time: < 200ms (p95) +- Database query time: < 100ms +- Error rate: < 0.1% +- Uptime: 99.9% + +## Validation +Use `checklists/performance-checklist.md` to validate all optimizations + +## Common Quick Wins +- Add database indexes +- Enable gzip compression +- Use CDN for static assets +- Add Redis caching +- Code split frontend +- Optimize images +- Lazy load components +- Remove unused dependencies \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/tasks/setup-project.md b/expansion-packs/javascript-fullstack-pack/tasks/setup-project.md new file mode 100644 index 00000000..4179c1d2 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/tasks/setup-project.md @@ -0,0 +1,199 @@ +# + +# Project Setup Task + +## Purpose +Initialize a new JavaScript/TypeScript full-stack project with proper tooling, configuration, and folder structure. + +## Prerequisites +- Architecture document complete +- Technology stack decided +- Development environment ready (Node.js 18+, Git) + +## Setup Steps + +### 1. Create Project Structure + +#### Monorepo (Recommended for Full-Stack) +```bash +npx create-turbo@latest my-app +# or +pnpm create turbo@latest my-app +``` + +**Structure:** +``` +my-app/ +├── apps/ +│ ├── web/ # Next.js frontend +│ └── api/ # Express/Fastify backend +├── packages/ +│ ├── ui/ # Shared React components +│ ├── types/ # Shared TypeScript types +│ └── config/ # Shared configs +├── package.json +└── turbo.json +``` + +#### Separate Repos +```bash +# Frontend +npx create-next-app@latest frontend --typescript --tailwind --app + +# Backend +mkdir backend && cd backend +npm init -y +npm install express prisma typescript @types/node +``` + +### 2. TypeScript Configuration + +**tsconfig.json** (Backend): +```json +{ + "compilerOptions": { + "target": "ES2022", + "module": "commonjs", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true, + "outDir": "./dist", + "baseUrl": ".", + "paths": { + "@/*": ["./src/*"] + } + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} +``` + +### 3. Install Dependencies + +**Frontend:** +```bash +pnpm add react-query zustand +pnpm add -D @types/react vitest +``` + +**Backend:** +```bash +pnpm add express prisma zod +pnpm add -D @types/express typescript tsx +``` + +### 4. Configure Linting & Formatting + +**ESLint (.eslintrc.json):** +```json +{ + "extends": ["next/core-web-vitals", "prettier"], + "rules": { + "no-console": "warn", + "@typescript-eslint/no-explicit-any": "error" + } +} +``` + +**Prettier (.prettierrc):** +```json +{ + "semi": true, + "singleQuote": true, + "trailingComma": "es5", + "printWidth": 100 +} +``` + +### 5. Set Up Database + +**Install Prisma:** +```bash +pnpm add -D prisma +npx prisma init +``` + +**Update .env:** +``` +DATABASE_URL="postgresql://user:pass@localhost:5432/mydb" +``` + +### 6. Configure Git + +**.gitignore:** +``` +node_modules/ +.env +.env.local +dist/ +.next/ +.turbo/ +coverage/ +``` + +### 7. Set Up Testing + +**Vitest (Frontend):** +```bash +pnpm add -D vitest @testing-library/react +``` + +**Jest (Backend):** +```bash +pnpm add -D jest @types/jest ts-jest supertest +``` + +### 8. Configure CI/CD + +**GitHub Actions (.github/workflows/ci.yml):** +```yaml +name: CI +on: [push, pull_request] +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: pnpm/action-setup@v2 + - uses: actions/setup-node@v3 + with: + node-version: 18 + - run: pnpm install + - run: pnpm test + - run: pnpm build +``` + +### 9. Environment Variables + +**Create .env.example:** +``` +DATABASE_URL=postgresql://... +JWT_SECRET=your-secret-here +NEXT_PUBLIC_API_URL=http://localhost:3000 +``` + +### 10. README Documentation + +Document: +- Setup instructions +- Available scripts +- Environment variables +- Deployment process + +## Verification Checklist + +- [ ] Project initializes without errors +- [ ] TypeScript compiles (no errors) +- [ ] ESLint passes +- [ ] Tests run successfully +- [ ] Git initialized with .gitignore +- [ ] Environment variables documented +- [ ] README complete with setup instructions +- [ ] CI/CD pipeline configured + +## Next Steps +- Begin story-driven development +- Set up development database +- Create first feature branch \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/workflows/backend-api-development.yaml b/expansion-packs/javascript-fullstack-pack/workflows/backend-api-development.yaml new file mode 100644 index 00000000..a58e5aa6 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/workflows/backend-api-development.yaml @@ -0,0 +1,48 @@ +# +workflow: + id: backend-api-development + name: Backend API Development + description: Specialized workflow for building Node.js backend services and APIs with Express, Fastify, or NestJS. + type: backend-focused + project_types: + - rest-api + - graphql-api + - microservice + - api-gateway + - backend-for-frontend + + sequence: + - agent: analyst + creates: api-requirements.md + notes: "Document API requirements, endpoints, data models, integrations, and non-functional requirements. SAVE to docs/requirements/" + + - agent: api-developer + creates: api-specification.md + requires: api-requirements.md + notes: "Design API contracts: endpoints, request/response schemas, authentication, rate limiting, and versioning strategy. SAVE to docs/api/" + + - agent: js-solution-architect + creates: backend-architecture.md + requires: api-specification.md + notes: "Design backend architecture: framework choice, database design, caching strategy, background jobs, and scalability approach. SAVE to docs/architecture/" + + - agent: node-backend-developer + validates: implementation_feasibility + uses: backend-checklist + notes: Review architecture for Node.js best practices and identify potential issues. + + - agent: typescript-expert + creates: backend-types.md + requires: backend-architecture.md + notes: Define TypeScript types for DTOs, entities, service interfaces, and middleware. + + workflow_end: + action: begin_api_implementation + notes: Architecture and API spec validated. Initialize Node.js project and begin endpoint development. + + recommended_stack: + framework: Express, Fastify, or NestJS + database: PostgreSQL with Prisma ORM or MongoDB with Mongoose + authentication: JWT with refresh tokens or OAuth 2.0 + caching: Redis for sessions and data caching + testing: Jest + Supertest for API tests \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/workflows/feature-development.yaml b/expansion-packs/javascript-fullstack-pack/workflows/feature-development.yaml new file mode 100644 index 00000000..7d436bcd --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/workflows/feature-development.yaml @@ -0,0 +1,52 @@ +# +workflow: + id: feature-development + name: Feature Development Workflow + description: Agile workflow for adding new features to existing JavaScript/TypeScript applications. Story-driven development from requirement to deployment. + type: feature-addition + project_types: + - existing-application + - continuous-delivery + - agile-sprint + + sequence: + - agent: analyst + creates: feature-requirements.md + notes: "Document feature requirements, user stories, acceptance criteria, and success metrics. SAVE to docs/features/[feature-name]/" + + - agent: js-solution-architect + reviews: technical_impact + requires: feature-requirements.md + notes: Assess technical impact on existing architecture. Identify affected components, database changes, API modifications, and integration points. + + - agent: react-developer OR node-backend-developer OR api-developer + creates: technical-specification.md + requires: + - feature-requirements.md + - technical_impact_review + notes: "Create detailed technical spec with file changes, new components/endpoints, types, tests, and implementation steps. SAVE to docs/features/[feature-name]/" + + - agent: scrum-master + creates: feature-stories.md + requires: technical-specification.md + uses: create-development-story task + notes: Break feature into implementable stories with clear acceptance criteria and DoD. + + workflow_end: + action: begin_feature_implementation + notes: Feature fully specified and broken into stories. Developers can begin implementation following story sequence. + + story_flow: + - Create feature branch from main + - Implement stories in sequence + - Write tests for each story + - Code review before merging + - Deploy to staging for QA + - Merge to main and deploy to production + + best_practices: + - Keep feature branches short-lived (< 3 days) + - Deploy incrementally with feature flags + - Write tests before code (TDD) + - Update documentation with code changes + - Monitor metrics post-deployment \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/workflows/frontend-app-development.yaml b/expansion-packs/javascript-fullstack-pack/workflows/frontend-app-development.yaml new file mode 100644 index 00000000..ed1da6c7 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/workflows/frontend-app-development.yaml @@ -0,0 +1,41 @@ +# +workflow: + id: frontend-app-development + name: Frontend Application Development + description: Specialized workflow for building React/Next.js frontend applications. Covers everything from component architecture to deployment. + type: frontend-focused + project_types: + - single-page-application + - static-site-generation + - server-side-rendering + - progressive-web-app + + sequence: + - agent: analyst + creates: frontend-requirements.md + notes: "Document UI/UX requirements, user flows, and frontend-specific needs. SAVE to docs/requirements/" + + - agent: js-solution-architect + creates: frontend-architecture.md + requires: frontend-requirements.md + notes: "Design frontend architecture: component structure, state management, routing, styling approach, and performance strategy. SAVE to docs/architecture/" + + - agent: react-developer + validates: architecture_feasibility + uses: frontend-checklist + notes: Review architecture for React best practices and implementation feasibility. + + - agent: typescript-expert + creates: type-definitions.md + requires: frontend-architecture.md + notes: Define TypeScript interfaces for props, state, API responses, and utilities. + + workflow_end: + action: begin_component_development + notes: Architecture validated. Initialize React/Next.js project and begin story-driven component development. + + recommended_stack: + framework: Next.js 14 with App Router or Vite + React 18 + styling: Tailwind CSS with shadcn/ui or CSS Modules + state_management: React Query for server state, Zustand for client state + testing: Vitest + React Testing Library + Playwright \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/workflows/fullstack-greenfield.yaml b/expansion-packs/javascript-fullstack-pack/workflows/fullstack-greenfield.yaml new file mode 100644 index 00000000..a7e16b23 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/workflows/fullstack-greenfield.yaml @@ -0,0 +1,211 @@ +# +workflow: + id: fullstack-greenfield + name: Full-Stack JavaScript - Greenfield Project + description: Complete workflow for building a new full-stack JavaScript/TypeScript application from concept to deployment. Guides teams through requirements gathering, architecture design, technology selection, and story-driven development. + type: greenfield + project_types: + - web-application + - saas-platform + - api-service + - mobile-backend + - enterprise-app + - startup-mvp + + full_sequence: + - agent: analyst + creates: requirements-analysis.md + optional_steps: + - stakeholder_interviews + - competitive_analysis + - user_research + notes: "Gather and document all project requirements, business goals, and user needs. SAVE OUTPUT: Copy to docs/requirements/ folder." + + - agent: js-solution-architect + creates: technology-stack-decision.md + requires: requirements-analysis.md + optional_steps: + - technology_research + - scalability_analysis + - cost_estimation + notes: "Select appropriate technology stack based on requirements. Choose frontend framework, backend framework, database, hosting, and tools. SAVE OUTPUT: Copy to docs/architecture/ folder." + + - agent: js-solution-architect + creates: system-architecture.md + requires: + - requirements-analysis.md + - technology-stack-decision.md + optional_steps: + - architecture_patterns_review + - security_architecture + - performance_planning + notes: "Design complete system architecture including frontend, backend, database schema, API contracts, and deployment strategy. SAVE OUTPUT: Copy to docs/architecture/ folder." + + - agent: js-solution-architect + validates: architecture_completeness + requires: system-architecture.md + uses: architecture-review-checklist + notes: Validate architecture document for completeness, feasibility, and alignment with requirements. May require updates. + + - agent: various + updates: architecture_documents + condition: validation_issues_found + notes: If validation finds issues, return to js-solution-architect to fix and re-export updated documents. + + project_setup_guidance: + action: initialize_project_structure + notes: "Set up project following architecture document: Initialize monorepo (if needed), configure TypeScript, set up frontend (Next.js/Vite), backend (Express/Fastify/NestJS), and database (Prisma). Configure linting, formatting, and testing." + + workflow_end: + action: move_to_story_development + notes: Architecture complete and validated. Set up development environment. Use Scrum Master to create implementation epics and stories from architecture document. + + mvp_sequence: + - step: assess_mvp_scope + action: identify_core_features + notes: Define minimal feature set for MVP. Focus on core value proposition and essential functionality. + + - agent: analyst + creates: mvp-requirements.md + optional_steps: + - feature_prioritization + - timeline_planning + notes: "Document MVP scope with prioritized features. SAVE OUTPUT: Copy to docs/ folder." + + - agent: js-solution-architect + creates: mvp-architecture.md + uses: create-doc mvp-architecture OR jump to stories + requires: mvp-requirements.md + notes: Create streamlined architecture focused on MVP features. Can skip detailed architecture for very simple MVPs and jump directly to stories. + + mvp_workflow_end: + action: rapid_implementation + notes: MVP scope defined. Begin implementation focusing on core features. Use feature-development workflow for agile story creation and execution. + + flow_diagram: | + ```mermaid + graph TD + A[Start: New Full-Stack Project] --> B{Project Scope?} + B -->|Full Production App| C[analyst: requirements-analysis.md] + B -->|MVP/Rapid Prototype| D[analyst: mvp-requirements.md] + + C --> E[js-solution-architect: technology-stack-decision.md] + E --> F[js-solution-architect: system-architecture.md] + F --> G[js-solution-architect: validate architecture] + G --> H{Validation issues?} + H -->|Yes| I[Return to architect for fixes] + H -->|No| J[Initialize project structure] + I --> G + J --> K[Move to Story Development] + + D --> L[js-solution-architect: mvp-architecture.md] + L --> M[Move to Rapid Implementation] + + C -.-> C1[Optional: stakeholder interviews] + C -.-> C2[Optional: competitive analysis] + E -.-> E1[Optional: technology research] + F -.-> F1[Optional: security architecture] + D -.-> D1[Optional: feature prioritization] + + style K fill:#90EE90 + style M fill:#90EE90 + style C fill:#FFE4B5 + style E fill:#FFE4B5 + style F fill:#FFE4B5 + style D fill:#FFB6C1 + style L fill:#FFB6C1 + ``` + + decision_guidance: + use_full_sequence_when: + - Building production applications or SaaS platforms + - Multiple team members or contractors + - Complex requirements with multiple integrations + - Long-term development timeline (3+ months) + - Enterprise or business-critical applications + - Need comprehensive documentation for team coordination + - Regulatory compliance requirements + - Scalability is critical from day one + + use_mvp_sequence_when: + - Startup MVP or proof-of-concept + - Solo developer or very small team (2-3 people) + - Simple CRUD applications + - Quick validation of product ideas + - Limited budget or tight timeline + - Learning projects or portfolio pieces + - Internal tools with simple requirements + + handoff_prompts: + analyst_to_architect: Requirements analysis complete. Save as docs/requirements/requirements-analysis.md, then create technology stack decision document. + stack_to_architecture: Technology stack selected. Save as docs/architecture/technology-stack-decision.md, then create comprehensive system architecture. + architecture_review: Architecture complete. Save as docs/architecture/system-architecture.md. Please validate using architecture-review-checklist. + validation_issues: Architecture validation found issues with [specific areas]. Please return to js-solution-architect to address and re-save. + full_complete: All architecture artifacts validated and saved. Initialize project structure per architecture document and move to story development. + mvp_to_architecture: MVP requirements defined. Save as docs/mvp-requirements.md, then create MVP architecture or jump to implementation stories. + mvp_complete: MVP scope defined. Initialize lean project structure and begin rapid feature implementation. + + story_development_guidance: + epic_breakdown: + - Frontend Core - React/Next.js setup, routing, base components, state management + - Backend Core - API setup, database schema, authentication, core endpoints + - User Authentication - Login, registration, password reset, session management + - Core Features - Main application features from requirements + - Integration Layer - External APIs, third-party services, webhooks + - UI/UX Polish - Responsive design, loading states, error handling, animations + - Testing - Unit tests, integration tests, E2E tests + - DevOps - CI/CD pipeline, deployment, monitoring, logging + + story_creation_process: + - Use Scrum Master to create detailed implementation stories + - Each story references specific architecture sections + - Include technical specs (TypeScript interfaces, API contracts) + - Specify frontend AND backend changes for full-stack features + - Apply story-dod-checklist for quality validation + - Ensure stories are immediately actionable by developers + + development_best_practices: + technical_standards: + - TypeScript strict mode for all code + - Component-based architecture + - RESTful or GraphQL API design + - Comprehensive error handling + - Input validation on frontend and backend + - Authentication and authorization on all protected routes + + testing_strategy: + - Unit tests for business logic (80%+ coverage) + - Integration tests for API endpoints + - E2E tests for critical user flows + - Component tests for React components + + performance_targets: + - Lighthouse score > 90 for frontend + - API response time < 200ms (p95) + - Time to Interactive < 3 seconds + - Bundle size optimization + + security_requirements: + - OWASP Top 10 mitigations + - Input sanitization and validation + - Secure authentication (JWT, OAuth) + - HTTPS only in production + - Secrets management (environment variables, vaults) + - Rate limiting on API endpoints + + success_criteria: + architecture_phase_complete: + - All architecture documents created and validated + - Technology stack selected and justified + - Database schema designed + - API contracts defined + - Security and performance requirements established + - Deployment strategy planned + + implementation_readiness: + - Development environment configured + - Code repository initialized + - CI/CD pipeline skeleton in place + - Team has access to all tools and services + - First sprint of stories ready + - Definition of Done established \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/workflows/migration-to-typescript.yaml b/expansion-packs/javascript-fullstack-pack/workflows/migration-to-typescript.yaml new file mode 100644 index 00000000..b1138313 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/workflows/migration-to-typescript.yaml @@ -0,0 +1,86 @@ +# +workflow: + id: migration-to-typescript + name: JavaScript to TypeScript Migration + description: Systematic workflow for migrating existing JavaScript codebases to TypeScript. Incremental approach that maintains functionality while adding type safety. + type: migration + project_types: + - javascript-legacy + - codebase-modernization + - technical-debt + + sequence: + - agent: typescript-expert + creates: migration-assessment.md + notes: "Assess codebase: size, complexity, test coverage, dependencies. Estimate effort and create migration phases. SAVE to docs/migration/" + + - agent: typescript-expert + creates: migration-strategy.md + requires: migration-assessment.md + notes: "Define strategy: strict mode timeline, file conversion order, type definition approach, and team training plan. SAVE to docs/migration/" + + - step: phase1_setup + action: configure_typescript + notes: Add TypeScript to project. Configure tsconfig.json with `allowJs: true, checkJs: false, strict: false`. Rename no files yet. + + - step: phase2_type_definitions + action: add_type_files + notes: Create .d.ts files for core types and interfaces. Add @ts-check comments to critical files to catch obvious errors. + + - agent: typescript-expert + creates: type-definitions-catalog.md + notes: Document all major types, interfaces, and where they're used. This guides developers during conversion. + + - step: phase3_incremental_conversion + action: convert_files_incrementally + notes: | + Convert files in this order: + 1. Utility functions (pure functions, no side effects) + 2. Constants and configuration + 3. Type definitions and interfaces + 4. Data models and entities + 5. API clients and services + 6. React components (leaf components first) + 7. Pages and routes + 8. Main application files + + - step: phase4_enable_strict_checking + action: gradual_strict_mode + notes: | + Gradually enable strict checks: + 1. Enable noImplicitAny + 2. Enable strictNullChecks + 3. Enable strictFunctionTypes + 4. Enable all strict flags + Fix errors in each phase before moving to next. + + - agent: typescript-expert + validates: migration_completeness + notes: Verify all files converted, strict mode enabled, no ts-ignore except where documented, and tests passing. + + workflow_end: + action: migration_complete + notes: Full TypeScript migration complete. Update team documentation, remove migration tracking, and establish TypeScript as standard. + + conversion_best_practices: + - Convert small batches (5-10 files at a time) + - Run tests after each batch + - Start with any instead of complex types (refine later) + - Use Type Assertions sparingly, document why needed + - Prefer interfaces over types for object shapes + - Create shared types in dedicated files + + common_challenges: + third_party_types: + solution: Install @types packages or create custom declarations + implicit_any: + solution: Start with explicit any, refine incrementally + null_undefined_checks: + solution: Use optional chaining and nullish coalescing + this_binding: + solution: Use arrow functions or explicit this typing + + timeline_estimates: + small_codebase: 2-4 weeks (< 10k lines) + medium_codebase: 1-3 months (10k-50k lines) + large_codebase: 3-6 months (> 50k lines) \ No newline at end of file diff --git a/expansion-packs/javascript-fullstack-pack/workflows/mvp-rapid-prototype.yaml b/expansion-packs/javascript-fullstack-pack/workflows/mvp-rapid-prototype.yaml new file mode 100644 index 00000000..4a98aa89 --- /dev/null +++ b/expansion-packs/javascript-fullstack-pack/workflows/mvp-rapid-prototype.yaml @@ -0,0 +1,66 @@ +# +workflow: + id: mvp-rapid-prototype + name: MVP & Rapid Prototype Workflow + description: Fast-track workflow for building MVPs and prototypes. Focus on speed and core functionality over comprehensive documentation. + type: rapid-development + project_types: + - mvp + - proof-of-concept + - hackathon + - demo + - investor-pitch + + sequence: + - agent: analyst + creates: mvp-brief.md + notes: "Quick brief: core problem, target users, essential features (3-5 max), and success criteria. Keep it to 1-2 pages. SAVE to docs/" + + - agent: js-solution-architect + creates: tech-stack-choice.md + requires: mvp-brief.md + notes: "Choose fastest stack to implement. Recommend: Next.js + Prisma + PostgreSQL/Supabase OR T3 Stack. SAVE to docs/" + + - agent: scrum-master + creates: mvp-stories.md + requires: + - mvp-brief.md + - tech-stack-choice.md + notes: Create 5-10 high-priority stories covering core features only. Each story should be completable in < 1 day. + + workflow_end: + action: rapid_implementation + notes: Begin implementation immediately. Deploy early and often. Use hosted services (Vercel, Supabase, Planetscale) to move fast. + + time_boxing: + mvp_planning: 2-4 hours + core_implementation: 3-7 days + polish_and_demo: 1-2 days + total_timeline: 1-2 weeks maximum + + shortcuts_for_speed: + - Use Next.js for full-stack (API routes + frontend) + - Use Supabase for database + auth + - Use shadcn/ui for ready-made components + - Use Vercel for zero-config deployment + - Skip comprehensive testing (manual testing only) + - Minimal documentation (README + inline comments) + - Use third-party services instead of building (Stripe, SendGrid, etc) + + what_to_skip: + - Comprehensive testing suite + - Complex CI/CD pipelines + - Performance optimization + - Extensive error handling + - Multi-environment setup + - Detailed documentation + - Code reviews (if solo) + + what_not_to_skip: + - TypeScript (saves time debugging) + - Basic authentication + - Input validation + - Error boundaries in React + - Environment variables for secrets + - Git version control + - Basic README with setup instructions \ No newline at end of file