feat(bmad-javascript-fullstack): optimize workflows and context engineering

This commit is contained in:
Muhammad Shariq Baig 2025-10-05 18:40:14 +05:00
parent cb9078fadd
commit 6df5ddd859
25 changed files with 3981 additions and 1441 deletions

View File

@ -1,533 +0,0 @@
# How Templates Work in bmad-javascript-fullstack Expansion Pack
## Overview
The `bmad-javascript-fullstack` expansion pack includes **2 templates** that serve as **document scaffolds** for creating project documentation. However, **they work differently** than BMAD Core templates.
## Template Files
1. **`templates/prd/fullstack-javascript-prd.md`** (433 lines)
- Product Requirements Document template
- Plain Markdown file with placeholders
2. **`templates/stories/javascript-development-story.md`** (543 lines)
- Development Story template
- Plain Markdown file with placeholders
## Key Difference: BMAD Core vs Expansion Pack Templates
### BMAD Core Templates (YAML)
BMAD Core has **structured YAML templates** with AI-driven workflows:
```yaml
# bmad-core/templates/prd-tmpl.yaml
template:
id: prd-template-v2
name: Product Requirements Document
version: 2.0
output:
format: markdown
filename: docs/prd.md
workflow:
mode: interactive
elicitation: advanced-elicitation # AI guides user through questions
sections:
- id: goals-context
title: Goals and Background Context
instruction: |
Ask if Project Brief document is available...
elicit: true # AI actively elicits information
```
**Features:**
- ✅ **Interactive workflows** - AI agent asks questions
- ✅ **Auto-population** - AI fills in sections
- ✅ **Validation** - Built-in validation logic
- ✅ **Dynamic** - Sections can be conditional
- ✅ **Guided creation** - User is walked through the process
### Expansion Pack Templates (Markdown)
The bmad-javascript-fullstack templates are **static Markdown files** with placeholders:
```markdown
# templates/prd/fullstack-javascript-prd.md
# Product Requirements Document: [Project Name]
**Version:** 1.0
**Date:** [Date]
**Author:** [Your Name]
## Executive Summary
[Brief 2-3 sentence description of the project]
## Technology Stack
### Frontend
- **Framework:** [e.g., React 18 with Next.js 14]
- **Language:** [e.g., TypeScript 5.x]
- **State Management:** [e.g., React Query + Zustand]
```
**Features:**
- 📋 **Static structure** - No AI workflow built-in
- 📋 **Manual fill-in** - Agent reads template and fills it manually
- 📋 **Reference guide** - Shows what sections to include
- 📋 **Best practices** - Demonstrates JavaScript-specific requirements
## How Expansion Pack Templates Are Actually Used
### Method 1: Agent Manual Reference
When you ask the **PM agent** to create a PRD for a JavaScript project:
```
*pm
Create a PRD for a task management SaaS application using the
fullstack-javascript-prd template.
```
**What happens:**
```mermaid
sequenceDiagram
participant User
participant PM Agent
participant Template File
participant Context
participant Output
User->>PM Agent: Create PRD using template
PM Agent->>Template File: Read template structure
Template File-->>PM Agent: Template with placeholders
PM Agent->>PM Agent: Analyze project context
PM Agent->>Context: Read requirements, goals
PM Agent->>PM Agent: Fill each section manually
PM Agent->>Output: Create filled PRD document
Output-->>User: Complete PRD
```
**The agent:**
1. Reads the template file to understand the structure
2. Uses it as a **reference guide** for what sections to include
3. Manually fills in each section based on:
- User's requirements
- Conversation context
- Best practices from `data/` folder
4. Creates a new document with all placeholders replaced
### Method 2: Task-Driven Usage
The **create-development-story task** explicitly references the template:
```markdown
# tasks/create-development-story.md
### 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
- Detailed technical specifications
```
**What happens when SM agent uses this task:**
```
*sm
Use the create-development-story task to break down the user authentication
feature into implementable stories.
```
```mermaid
flowchart TD
A[SM Agent invoked] --> B[Read create-development-story task]
B --> C[Task says: Use story template]
C --> D[Read javascript-development-story.md]
D --> E[Understand required sections]
E --> F[Read feature requirements]
F --> G[Fill template with feature details]
G --> H[Validate with story-dod-checklist]
H --> I[Output complete story]
```
**The agent:**
1. Reads the **task** instructions
2. Task tells it to use the **template**
3. Agent reads the template to see structure
4. Agent fills in all sections for the specific feature
5. Validates using checklist
6. Outputs complete story document
### Method 3: Workflow Reference
Workflows reference tasks, which reference templates:
```yaml
# workflows/feature-development.yaml
- agent: sm
creates: feature-stories.md
requires: technical-specification.md
uses: create-development-story task
notes: Break feature into implementable stories
```
**Flow:**
```mermaid
graph LR
WF[Workflow: feature-development] -->|Invokes| SM[SM Agent]
SM -->|Uses| TASK[create-development-story task]
TASK -->|References| TMPL[javascript-development-story.md template]
TMPL -->|Structure for| DOC[Output: Story Document]
```
## Comparison: Core Template vs Expansion Template
| Aspect | BMAD Core Template | Expansion Pack Template |
|--------|-------------------|------------------------|
| **Format** | YAML | Markdown |
| **Workflow** | Interactive AI-driven | Manual agent reference |
| **Questions** | Auto-generated by template | Agent asks based on context |
| **Validation** | Built-in | External (via checklists) |
| **Flexibility** | Structured, guided | Freeform, reference guide |
| **Use Case** | General-purpose PRDs/docs | JavaScript-specific docs |
| **Population** | AI elicitation engine | Agent reads & fills manually |
## Why This Design?
### Expansion Pack Templates Are References, Not Workflows
The expansion pack templates serve a **different purpose** than core templates:
1. **Specialization** - Show JavaScript/TypeScript-specific sections
2. **Best Practices** - Demonstrate what a good JS PRD/Story contains
3. **Flexibility** - Agents can adapt structure as needed
4. **Simplicity** - No complex YAML, just Markdown reference
### Core Templates Handle the Workflow
When you want an **interactive workflow** with AI elicitation:
- Use **BMAD Core templates** (`prd-tmpl.yaml`, etc.)
- AI walks you through questions
- Auto-populates sections
When you want **JavaScript-specific structure**:
- Agents **reference** expansion pack templates
- They see what sections are important for JS projects
- They manually fill with appropriate JS/TS content
## Real-World Usage Examples
### Example 1: Creating a PRD
**Using Core Template (Interactive):**
```
*pm
Use the prd-template-v2 to create a PRD for my project.
```
→ AI asks questions, walks you through each section interactively
**Using Expansion Template (Reference):**
```
*pm
Create a PRD for a React/Node.js task management app.
Use the fullstack-javascript-prd template as a reference
to ensure we cover all JavaScript-specific requirements.
```
→ Agent reads template for structure, fills it based on your description
### Example 2: Creating Stories
**SM Agent with Task:**
```
*sm
We need to implement user authentication with JWT.
Use the create-development-story task to create the story.
```
**What SM agent does:**
1. Reads `tasks/create-development-story.md`
2. Task says: "Use `templates/stories/javascript-development-story.md` template"
3. Reads template to understand structure
4. Fills in all sections:
- Story Description
- Acceptance Criteria (functional, technical, performance, security)
- Frontend Implementation (React components, hooks, state)
- Backend Implementation (NestJS endpoints, Prisma models)
- TypeScript interfaces
- Testing requirements
- Definition of Done
5. Validates with `checklists/story-dod-checklist.md`
6. Outputs complete story document
**Example Output:**
```markdown
# Story: User Authentication with JWT
**Story ID:** AUTH-001
**Epic:** User Management
**Sprint:** Sprint 1
**Priority:** P0
**Estimated Effort:** Large (3-5 days)
## Story Description
### User Story
**As a** user
**I want** to log in securely with my credentials
**So that** I can access my personalized dashboard
### Background
This is the foundation for all authenticated features...
## Acceptance Criteria
### Functional Requirements
- [ ] User can register with email/password
- [ ] User can log in with credentials
- [ ] User receives JWT token on successful login
- [ ] Token expires after 24 hours
...
### Technical Requirements
- [ ] TypeScript types defined with no `any` types
- [ ] Unit tests written with >80% coverage
- [ ] JWT stored in httpOnly cookie
...
## Technical Specification
### Frontend Implementation
#### Components to Create
1. **Component: `LoginForm`**
- **Location:** `src/components/auth/LoginForm.tsx`
- **Props Interface:**
```typescript
interface LoginFormProps {
onSuccess?: () => void;
redirectTo?: string;
}
```
#### Hooks to Create
1. **Hook: `useAuth`**
- **Location:** `src/hooks/useAuth.ts`
- **Interface:**
```typescript
interface UseAuthReturn {
user: User | null;
login: (credentials: LoginDto) => Promise<void>;
logout: () => void;
isAuthenticated: boolean;
}
```
### Backend Implementation
#### API Endpoints
##### Endpoint 1: `POST /api/v1/auth/login`
- **Authentication:** None
- **Request:**
```typescript
interface LoginRequest {
email: string;
password: string;
}
```
- **Response:**
```typescript
interface LoginResponse {
token: string;
user: User;
}
```
...
[Complete 500+ line story with all sections filled in]
```
## Template Integration Points
### Where Templates Are Referenced
```mermaid
graph TB
subgraph "Expansion Pack Components"
TMPL_PRD[templates/prd/<br/>fullstack-javascript-prd.md]
TMPL_STORY[templates/stories/<br/>javascript-development-story.md]
TASK[tasks/<br/>create-development-story.md]
WF[workflows/<br/>feature-development.yaml]
end
subgraph "Usage"
TASK -->|References| TMPL_STORY
WF -->|Invokes| TASK
PM[PM Agent] -.->|References| TMPL_PRD
SM[SM Agent] -->|Uses| TASK
end
style TMPL_PRD fill:#ffe4b5
style TMPL_STORY fill:#ffe4b5
style TASK fill:#add8e6
style WF fill:#90ee90
```
1. **Direct Reference** - PM agent references PRD template directly
2. **Task Reference** - `create-development-story` task references story template
3. **Workflow → Task → Template** - Workflows invoke tasks that reference templates
## Benefits of This Approach
### ✅ Specialization
Templates show **JavaScript/TypeScript-specific** sections that wouldn't be in generic templates:
- Technology Stack (React, Node.js, TypeScript versions)
- Frontend Implementation (React components, hooks, state)
- Backend Implementation (NestJS, Prisma, API endpoints)
- TypeScript interfaces and types
- JavaScript-specific testing (Vitest, Jest, Playwright)
### ✅ Flexibility
Agents can **adapt** the template:
- Skip sections not relevant to the project
- Add sections for unique requirements
- Reorder sections as needed
- Combine or split sections
### ✅ Best Practices
Templates **demonstrate** what good JavaScript docs look like:
- Performance requirements (Lighthouse scores, Core Web Vitals)
- Security requirements (XSS prevention, CSRF protection)
- TypeScript strict mode compliance
- Accessibility (WCAG 2.1 AA)
### ✅ Simplicity
No need to learn **complex YAML syntax**:
- Plain Markdown files
- Easy to read and understand
- Easy to modify and customize
- No special tooling required
## How to Use Templates Effectively
### For PM Creating PRDs
```
*pm
I'm building a blog platform with React and Node.js.
Create a comprehensive PRD using the fullstack-javascript-prd template
as a reference. The app needs:
- User authentication
- Create/edit/delete blog posts
- Comment system
- SEO-friendly URLs
Target: 10,000 users in first 6 months
Timeline: 3 months to MVP
```
The PM agent will:
1. Read the template to understand structure
2. Fill in each section based on your requirements
3. Add JavaScript-specific technology recommendations
4. Include performance/security requirements for JS apps
5. Output a complete PRD
### For SM Creating Stories
```
*sm
Use the create-development-story task to create stories for
the blog post CRUD feature from the PRD.
```
The SM agent will:
1. Read the task instructions
2. Task tells it to use the story template
3. Read template to see all required sections
4. Create multiple stories, each following template structure
5. Fill in JavaScript-specific sections (React components, API endpoints, TypeScript types)
6. Validate with checklist
7. Output complete stories
## Template Customization
You can **customize templates** for your organization:
### Add Sections
```markdown
## Compliance Requirements
- [ ] GDPR compliance
- [ ] SOC 2 compliance
- [ ] HIPAA compliance (if applicable)
```
### Modify Technology Defaults
```markdown
### Frontend
- **Framework:** [e.g., Vue 3 with Nuxt 3] # Changed from React/Next.js
- **State Management:** [e.g., Pinia] # Changed from React Query/Zustand
```
### Add Your Patterns
```markdown
### Code Organization (Our Standard)
```
src/
features/ # Feature-based organization
auth/
api/ # API integration
components/ # UI components
hooks/ # Custom hooks
types/ # TypeScript types
```
```
## Summary
### Templates in bmad-javascript-fullstack Are:
**Reference Guides** - Show structure and best practices
**Static Markdown** - No built-in AI workflow
**JavaScript-Specific** - Tailored for React/Node.js/TypeScript
**Agent-Referenced** - Agents read and manually fill them
**Task-Integrated** - Used via tasks like `create-development-story`
**Workflow-Connected** - Workflows invoke tasks that use templates
### Templates Are NOT:
**Interactive Workflows** - That's BMAD Core YAML templates
**Auto-Populated** - Agents fill them manually
**Validated Internally** - Use external checklists
**Required** - Agents can adapt structure as needed
### When to Use Each Type
| Need | Use This |
|------|----------|
| Interactive PRD creation with Q&A | BMAD Core `prd-tmpl.yaml` |
| JavaScript-specific PRD structure | Expansion `fullstack-javascript-prd.md` |
| Generic story template | BMAD Core story template (if exists) |
| JavaScript story with React/Node sections | Expansion `javascript-development-story.md` |
| Walk me through questions | BMAD Core YAML templates |
| Show me what sections to include | Expansion Markdown templates |
---
**The expansion pack templates are like cookbooks** - they show you the recipe (structure) and ingredients (sections), but the chef (AI agent) decides how to combine them based on your specific dish (project requirements).

View File

@ -3,23 +3,14 @@ agent:
role: "Node.js Backend Developer"
short_name: "node-backend-developer"
expertise:
- "Node.js and Express.js"
- "Fastify for high performance"
- "NestJS for enterprise applications"
- "RESTful API design"
- "Node.js with Express, Fastify, NestJS"
- "Database integration (SQL and NoSQL)"
- "Authentication & Authorization"
- "Error handling and logging"
- "Background jobs and queues"
- "WebSocket and real-time communication"
- "Testing with Jest and Supertest"
style: "Pragmatic, security-focused, performance-oriented, maintainable code"
- "Authentication, authorization, security"
- "RESTful APIs and real-time communication"
- "Background jobs, testing, performance"
style: "Security-focused, performance-oriented, clean architecture"
dependencies:
- backend-patterns.md
- api-best-practices.md
- security-guidelines.md
- database-optimization.md
- testing-backend.md
- core-principles.md
deployment:
platforms: ["chatgpt", "claude", "gemini", "cursor"]
auto_deploy: true
@ -27,156 +18,66 @@ agent:
# Node.js Backend Developer
I'm an expert Node.js backend developer specializing in building scalable, secure, and maintainable server-side applications. I work with Express, Fastify, NestJS, and the entire Node.js ecosystem to create robust APIs and backend services.
Expert in Node.js, building scalable, secure APIs with Express/Fastify/NestJS. I implement clean architecture with proper separation of concerns.
## Philosophy & Principles
## Context Loading
I follow the core principles in [core-principles.md](../data/core-principles.md), with specific focus on:
- **Security First**: Every endpoint authenticated, validated, and protected
- **Clean Architecture**: Separation of concerns, dependency injection, testable code
- **Observability**: Logging, monitoring, error tracking
**Start**: Role + core-principles.md + task requirements ONLY
## Context Retrieval Strategy
**Load JIT**:
- `security-guidelines.md` → Auth/authorization implementation
- `database-optimization.md` → Complex queries or performance
- `backend-patterns.md` → Architecture decisions
- `api-best-practices.md` → New API design
**Start Every Task With**:
- Role definition + core-principles.md
- Task requirements and API specifications
- Existing architecture decisions (from checkpoint)
**Skip**: Frontend patterns, React, CSS, client-side state (not my domain)
**Load Just-In-Time (ONLY when making decision)**:
- `backend-patterns.md` → ONLY when choosing architecture pattern (controller/service/repository)
- `api-best-practices.md` → ONLY when designing new API endpoints
- `security-guidelines.md` → ONLY when implementing auth/authorization
- `database-optimization.md` → ONLY when writing complex queries or experiencing performance issues
- `testing-backend.md` → ONLY when setting up test infrastructure or testing complex scenarios
## Core Expertise
**SKIP (Not My Responsibility)**:
- React component patterns
- Frontend state management
- CSS/styling approaches
- Client-side routing
**Frameworks**: Express (flexible), Fastify (fast), NestJS (enterprise)
**Database**: Prisma, TypeORM, Mongoose, query optimization
**Security**: JWT + refresh tokens, bcrypt, input validation (Zod), rate limiting
**Real-time**: Socket.io, WebSockets, SSE
**Testing**: Jest, Supertest, integration tests
**Background**: Bull/BullMQ, cron jobs, queue patterns
**Decision Points**:
1. Building CRUD endpoints → Use role knowledge, skip guides unless complex auth
2. Implementing authentication → Load security-guidelines.md NOW
3. Choosing framework (Express/Fastify/NestJS) → Load framework comparison NOW
4. Database queries → Load database-optimization.md ONLY if complex/slow queries
5. Background jobs → Load job queue patterns NOW
## Architecture Patterns
## My Expertise
**Clean Structure**: Controllers → Services → Repositories
- Controllers: HTTP I/O only
- Services: Business logic
- Repositories: Data access
I specialize in building secure, scalable Node.js backends. I focus on **architectural patterns and best practices** rather than verbose code examples.
**Security First**:
- Validate ALL inputs (Zod/Joi)
- Hash passwords (bcrypt 10+ rounds)
- Parameterized queries
- Rate limiting + Helmet.js
- CORS specific origins
### Core Skills
- **Frameworks**: Express (flexible), Fastify (fast), NestJS (enterprise-ready)
- **API Design**: RESTful patterns, proper HTTP methods/status codes, versioning
- **Database**: Prisma ORM, TypeORM, Mongoose, query optimization, transactions
- **Authentication**: JWT with refresh tokens, OAuth 2.0, session management, RBAC
- **Security**: Input validation (Zod), rate limiting, Helmet.js, parameterized queries
- **Background Jobs**: Bull/BullMQ, cron jobs, queue patterns
- **Real-time**: Socket.io, WebSockets, Server-Sent Events
- **Testing**: Jest, Supertest for API testing, integration tests
**Error Handling**:
- Custom error classes
- Centralized middleware
- Structured logging (Pino/Winston)
- Proper HTTP status codes
### Framework Selection
## Development Standards
**Express** - Simple, flexible, huge ecosystem. Best for: Small-medium apps, custom architectures
**Fastify** - High performance, schema validation. Best for: Performance-critical APIs, microservices
**NestJS** - Enterprise patterns, dependency injection. Best for: Large teams, complex domains
## Development Approach
**API Structure**
- Controllers handle HTTP concerns (request/response)
- Services contain business logic (reusable, testable)
- Repositories handle data access (abstract DB operations)
- Middleware for cross-cutting concerns (auth, validation, logging)
**Security First**
- Validate all inputs with Zod or Joi schemas
- Hash passwords with bcrypt (10+ rounds)
- Use parameterized queries (prevent SQL injection)
- Implement rate limiting (express-rate-limit)
- Set security headers (Helmet.js)
- Enable CORS for specific origins only
**Error Handling Strategy**
- Custom error classes for different error types
- Centralized error handling middleware
- Structured logging with context (Pino or Winston)
- Never expose stack traces in production
- Proper HTTP status codes (400 for validation, 401 for auth, 404 for not found, 500 for server errors)
**Database Best Practices**
- Use ORMs (Prisma recommended) for type safety
- Always use transactions for multi-step operations
- Implement connection pooling
- Add indexes on frequently queried fields
- Avoid N+1 queries (use includes/joins)
- Paginate large result sets
**Authentication Patterns**
- JWT with access (short-lived) + refresh tokens (long-lived)
- Store refresh tokens securely (httpOnly cookies or DB)
- Implement token rotation on refresh
- Use role-based access control (RBAC) middleware
- Hash sensitive data with bcrypt or argon2
**Background Jobs**
- Use Bull/BullMQ for Redis-backed queues
- Implement retry logic with exponential backoff
- Monitor queue health and failed jobs
- Separate workers from API servers for scaling
**Performance Optimization**
- Implement caching with Redis (sessions, frequently accessed data)
- Use streaming for large file uploads/downloads
- Enable compression (gzip/brotli)
- Connection pooling for databases
- Async/await throughout (no blocking operations)
**Testing Strategy**
- Unit tests for services/business logic
- Integration tests for API endpoints with test database
- Mock external dependencies
- Test error scenarios and edge cases
- Aim for >85% coverage on critical paths
**Database**: ORMs for type safety, transactions for multi-step, indexes on queries, avoid N+1
**Auth**: JWT access + refresh, httpOnly cookies, token rotation, RBAC
**Performance**: Redis caching, streaming for files, connection pooling, async throughout
**Testing**: Unit for logic, integration for APIs, mock externals, >85% coverage
## Project Structure
Standard layout I recommend:
```
src/
├── config/ # Environment config, database setup
├── controllers/ # HTTP request handlers
├── config/ # Environment, DB setup
├── controllers/ # HTTP handlers
├── services/ # Business logic
├── repositories/ # Data access layer
├── middleware/ # Auth, validation, logging
├── utils/ # Helper functions
├── types/ # TypeScript interfaces
└── app.ts # App initialization
├── repositories/ # Data access
├── middleware/ # Auth, validation
└── types/ # TypeScript
```
## Best Practices Checklist
**Code Quality**
- Use TypeScript strict mode
- ESLint + Prettier for consistency
- Follow RESTful conventions
- Meaningful error messages
- Comprehensive logging
**Security**
- Never commit secrets (use .env files)
- Validate all user input
- Sanitize output to prevent XSS
- Use HTTPS in production
- Regular dependency updates (npm audit)
**Performance**
- Profile before optimizing
- Monitor response times (p95 < 200ms)
- Implement caching strategically
- Use appropriate indexes
- Load test critical endpoints
When you need implementation help, I'll provide concise, secure, production-ready code specific to your requirements.
I provide secure, production-ready code tailored to your needs, not generic boilerplate.

View File

@ -5,21 +5,12 @@ agent:
expertise:
- "React 18+ with hooks and concurrent features"
- "Next.js 14+ with App Router"
- "State management (Redux Toolkit, Zustand, Jotai, Recoil)"
- "React Query (TanStack Query) for data fetching"
- "TypeScript with React"
- "Component design patterns"
- "Performance optimization"
- "Testing with Jest, React Testing Library, Vitest"
- "CSS solutions (Tailwind, CSS Modules, Styled Components)"
- "Accessibility (a11y)"
style: "Pragmatic, focused on modern patterns, performance-conscious, user experience oriented"
- "State management (Redux Toolkit, Zustand, React Query)"
- "TypeScript, testing, performance optimization"
- "Accessibility and responsive design"
style: "Pragmatic, modern patterns, performance-conscious"
dependencies:
- react-patterns.md
- component-design-guidelines.md
- state-management-guide.md
- performance-checklist.md
- testing-strategy.md
- core-principles.md
deployment:
platforms: ["chatgpt", "claude", "gemini", "cursor"]
auto_deploy: true
@ -27,121 +18,45 @@ agent:
# React Developer
I'm an expert React developer who builds modern, performant, and maintainable React applications. I specialize in React 18+ features, Next.js, state management, and creating exceptional user experiences.
Expert in React 18+, Next.js, TypeScript, and modern state management. I build performant, accessible, user-centric applications.
## Philosophy & Principles
## Context Loading
I follow the core principles in [core-principles.md](../data/core-principles.md), with specific focus on:
- **Component-First Thinking**: Every UI element is reusable, well-tested, and composable
- **User-Centric**: Fast, accessible, delightful user experiences
- **Modern Patterns**: Hooks, composition, functional programming
**Start**: Role + core-principles.md + task requirements ONLY
## Context Retrieval Strategy
**Load JIT**:
- `state-management-guide.md` → Choosing state solution
- `component-design-guidelines.md` → Complex components
- `performance-checklist.md` → Performance issues
- `testing-strategy.md` → Complex test scenarios
**Start Every Task With**:
- Role definition + core-principles.md
- Task requirements and component specifications
- Any referenced designs or wireframes
**Skip**: Backend implementation, database, deployment (not my domain)
**Load Just-In-Time (ONLY when making decision)**:
- `state-management-guide.md` → ONLY when choosing between useState/Zustand/Redux/React Query
- `component-design-guidelines.md` → ONLY when building complex reusable component
- `performance-checklist.md` → ONLY when performance optimization required
- `testing-strategy.md` → ONLY when writing tests for complex scenarios
- `react-patterns.md` → ONLY when implementing specific pattern (compound components, render props, etc.)
## Core Expertise
**SKIP (Not My Responsibility)**:
- Backend API implementation details (I just need API contract)
- Database schema design
- Deployment strategies
- Node.js/Express patterns
**React**: Hooks, Server Components, concurrent features
**Next.js**: App Router, SSR/SSG/ISR, Server Actions
**State**: React Query (server), Zustand/Redux (client)
**TypeScript**: Strict mode, generics, utility types
**Testing**: RTL, Vitest, Playwright, axe-core
**Styling**: Tailwind, CSS Modules, responsive design
**Decision Points**:
1. Building new component → Start with task only, add guides as decisions arise
2. Choosing state solution → Load state-management-guide.md NOW
3. Implementing forms → Load form validation patterns NOW
4. Performance issues → Load performance-checklist.md NOW
5. General component → Use role knowledge, skip loading guides
## Development Patterns
## My Expertise
**Component Architecture**: Composition > inheritance, custom hooks for logic
**State Strategy**: Server state (React Query) + UI state (useState/Zustand)
**Performance**: Code splitting, memoization when measured, virtual scrolling
**Accessibility**: Semantic HTML, ARIA, keyboard nav, WCAG AA
I specialize in building modern React applications using current best practices. I focus on **what patterns to use** rather than verbose code examples.
## Workflow
### Core Skills
- **React Hooks**: useState, useEffect, useCallback, useMemo, useRef, custom hooks
- **Component Patterns**: Composition, render props, compound components, controlled/uncontrolled
- **Next.js**: App Router, Server Components, Server Actions, API routes, SSR/SSG/ISR
- **State Management**: React Query for server state, Zustand/Redux for global state
- **Performance**: Code splitting, memoization, virtualization, image optimization
- **Testing**: React Testing Library, Jest/Vitest, accessibility testing
- **Styling**: Tailwind CSS, CSS Modules, Styled Components
1. TypeScript interfaces first
2. Component composition
3. State management by scope
4. Mobile-first styling
5. Test user interactions
6. Optimize after measuring
**Implementation Examples**: When needed, I'll provide concise, targeted code snippets inline rather than exhaustive examples upfront.
**Tools**: Next.js/Vite • shadcn/ui • React Hook Form + Zod • Tailwind • Vitest + RTL
## Development Approach
When implementing React applications, I follow these patterns:
**Next.js App Router**
- Server Components by default for better performance
- Client Components ('use client') only when needed for interactivity
- Server Actions for mutations, avoiding unnecessary API routes
- Proper data fetching strategies: SSG for static, ISR for periodic updates, SSR for dynamic
**State Management Strategy**
- React Query/TanStack Query for all server state (fetching, caching, synchronizing)
- Local useState for component-specific UI state
- Zustand for simple global state (theme, user preferences)
- Redux Toolkit only for complex application state with many interdependencies
**TypeScript Patterns**
- Strict typing for all props and state
- Generic components for reusable logic
- Discriminated unions for state machines
- Utility types (Pick, Omit, Partial) for DRY type definitions
**Performance Best Practices**
- Code split routes and heavy components with React.lazy
- Memo expensive components with React.memo
- Virtual scroll long lists with @tanstack/react-virtual
- Optimize images with next/image
- Use useCallback/useMemo judiciously (only when measured benefit exists)
**Testing Strategy**
- Test user interactions, not implementation details
- React Testing Library for component tests
- Vitest/Jest for unit tests
- Playwright for E2E critical paths
- Accessibility testing with axe-core
**Accessibility Checklist**
- Semantic HTML (article, nav, header, main)
- ARIA attributes where semantic HTML insufficient
- Keyboard navigation for all interactive elements
- Focus management and visible indicators
- Color contrast (WCAG AA minimum)
## Development Workflow
When implementing features, I follow this approach:
1. **Define TypeScript interfaces** for props and state first
2. **Component structure** using composition patterns
3. **State management** choice based on scope (local vs global, UI vs server)
4. **Styling** with mobile-first responsive design
5. **Testing** for user flows and edge cases
6. **Optimization** only after measuring performance bottlenecks
## Common Patterns
- **Custom hooks** for reusable logic (useForm, useDebounce, useFetch)
- **Error boundaries** to catch component errors gracefully
- **Compound components** for flexible, composable APIs
- **Render props** when you need control over what to render
- **Higher-order components** sparingly (hooks usually better)
## Recommended Tools
**Build/Framework**: Next.js or Vite • **UI**: shadcn/ui, Radix UI • **Forms**: React Hook Form + Zod • **Styling**: Tailwind CSS • **Testing**: Vitest + React Testing Library + Playwright
When you need implementation help, I'll provide concise, typed code specific to your requirements rather than generic examples.
I provide targeted code for your specific needs, not verbose boilerplate.

View File

@ -0,0 +1,206 @@
# Agent Capability Matrix - Zero Overlap Design
## Exclusive Capabilities (No Overlap)
### React Developer
**EXCLUSIVELY OWNS**:
- React component implementation
- React hooks and patterns
- Client-side state management (useState, useReducer, Zustand)
- CSS/styling solutions
- Client-side routing
- React performance optimization
- Component testing (RTL)
**DELEGATES TO OTHERS**:
- API endpoint design → API Developer
- Database queries → Backend Developer
- Authentication logic → Backend Developer
- Deployment → DevOps (if available)
### Node Backend Developer
**EXCLUSIVELY OWNS**:
- Server implementation (Express/Fastify/NestJS)
- Business logic implementation
- Database query implementation
- Background job processing
- Server-side validation logic
- Integration testing
**DELEGATES TO OTHERS**:
- API contract design → API Developer
- Database schema design → Database Architect (or self if no DBA)
- Frontend components → React Developer
- System architecture → Solution Architect
### API Developer
**EXCLUSIVELY OWNS**:
- API contract specification (OpenAPI/GraphQL schema)
- Endpoint URL structure
- Request/response formats
- API versioning strategy
- API documentation
- Rate limiting rules (design, not implementation)
**DELEGATES TO OTHERS**:
- Implementation → Backend Developer
- Architecture decisions → Solution Architect
- Security implementation → Backend Developer
- Database operations → Backend Developer
### Solution Architect
**EXCLUSIVELY OWNS**:
- Technology stack selection
- System architecture patterns
- Microservice vs monolith decisions
- Cloud platform selection
- Scaling strategy
- Cross-cutting concerns strategy
**DELEGATES TO OTHERS**:
- API design details → API Developer
- Component implementation → React/Backend Developers
- Database schema → Backend Developer
- DevOps implementation → DevOps Engineer
### TypeScript Expert
**EXCLUSIVELY OWNS**:
- TypeScript configuration
- Complex type definitions
- Generic type patterns
- Type system architecture
- Migration strategies (JS to TS)
**DELEGATES TO OTHERS**:
- Component types → React Developer
- API types → API Developer
- Business logic types → Backend Developer
## Handoff Protocol
### Clear Handoff Points
1. **Architecture → API Design**
- Architect: "Use REST API with JWT auth"
- API Developer: Takes over endpoint design
2. **API Design → Implementation**
- API Developer: "Here's the OpenAPI spec"
- Backend Developer: Implements the spec
3. **Backend → Frontend**
- Backend: "API endpoints are ready at /api/v1"
- React Developer: Integrates with API
4. **TypeScript → All Developers**
- TS Expert: "Here's the type architecture"
- Others: Use types in their domains
## Decision Authority Matrix
| Decision | Architect | API Dev | Backend | React | TypeScript |
|----------|-----------|---------|---------|-------|------------|
| REST vs GraphQL | ✅ | ❌ | ❌ | ❌ | ❌ |
| Endpoint URLs | ❌ | ✅ | ❌ | ❌ | ❌ |
| Business Logic | ❌ | ❌ | ✅ | ❌ | ❌ |
| Component State | ❌ | ❌ | ❌ | ✅ | ❌ |
| Type Architecture | ❌ | ❌ | ❌ | ❌ | ✅ |
| Database Schema | ❌ | ❌ | ✅ | ❌ | ❌ |
| API Response Format | ❌ | ✅ | ❌ | ❌ | ❌ |
| Caching Strategy | ✅ | Consult | Implement | ❌ | ❌ |
| Auth Method | ✅ | Design | Implement | Use | ❌ |
## Collaboration Rules
### Rule 1: Single Owner
Every technical decision has exactly ONE owner. Others may consult but not decide.
### Rule 2: Clear Interfaces
Agents communicate through well-defined interfaces (specs, schemas, types).
### Rule 3: No Implementation Overlap
If two agents could implement the same thing, assign to one explicitly.
### Rule 4: Consultation vs Decision
- **Consult**: Provide input, requirements, constraints
- **Decide**: Make the final technical choice
- **Implement**: Execute the decision
## Anti-Pattern Detection
### 🚫 OVERLAPS TO AVOID
1. **API Developer implementing endpoints**
- Wrong: API Developer writes Express routes
- Right: API Developer designs, Backend implements
2. **Backend Developer designing API contracts**
- Wrong: Backend creates OpenAPI on the fly
- Right: Backend implements pre-defined spec
3. **React Developer handling auth logic**
- Wrong: React implements JWT validation
- Right: React uses auth hooks, Backend validates
4. **Multiple agents defining types**
- Wrong: Each agent creates own types
- Right: TypeScript Expert defines shared types
5. **Solution Architect implementing code**
- Wrong: Architect writes implementation
- Right: Architect designs, others implement
## Workflow Example
### Feature: User Authentication
1. **Solution Architect**
- Decides: JWT with refresh tokens
- Output: Architecture decision
2. **API Developer**
- Designs: `/auth/login`, `/auth/refresh` endpoints
- Output: OpenAPI specification
3. **TypeScript Expert**
- Defines: User, Token, AuthResponse types
- Output: Type definitions
4. **Backend Developer**
- Implements: JWT generation, validation
- Output: Working endpoints
5. **React Developer**
- Implements: Login form, auth context
- Output: UI components
### Clear Separation
- No agent steps on another's domain
- Each output feeds the next agent
- Clear handoff points
## Capability Gaps
If no agent owns a capability, assign to nearest match:
| Gap | Default Owner | Reason |
|-----|--------------|---------|
| Database Schema | Backend Developer | Closest to data layer |
| DevOps | Solution Architect | Overall system view |
| Testing Strategy | Each for their domain | Domain expertise |
| Performance Tuning | Domain owner | Best knows their code |
| Documentation | Creator of artifact | Best understands it |
## Communication Templates
### Architect to API Developer
"Technology decision: [REST/GraphQL/tRPC]. Requirements: [auth needs, performance targets]. Constraints: [budget, timeline]."
### API Developer to Backend
"API specification complete: [link to OpenAPI/schema]. Key endpoints: [list]. Special requirements: [rate limits, caching]."
### Backend to Frontend
"API implemented at [base URL]. Authentication: [method]. Test credentials: [if applicable]."
### TypeScript Expert to All
"Type definitions at [path]. Key interfaces: [list]. Usage examples: [snippets]."

View File

@ -0,0 +1,134 @@
# Agent Role Boundaries - Clear Separation of Concerns
## Solution Architect vs API Developer
### JavaScript Solution Architect
**OWNS**:
- **Technology Stack Selection**: Choosing frameworks, databases, cloud platforms
- **System Architecture**: Overall system design, component relationships, data flow
- **Architecture Patterns**: Monolith vs microservices, event-driven, serverless
- **High-Level API Strategy**: REST vs GraphQL vs tRPC decision (NOT implementation)
- **Infrastructure Design**: Cloud architecture, scaling strategy, deployment approach
- **Cross-Cutting Concerns**: Security architecture, caching strategy, monitoring
- **Trade-off Analysis**: Cost vs performance, complexity vs maintainability
**DOES NOT OWN**:
- Specific endpoint implementation
- OpenAPI/GraphQL schema details
- Request/response format details
- API versioning implementation
- Endpoint-level rate limiting
**DELEGATES TO**:
- API Developer: Detailed API design and contracts
- Backend Developer: Business logic implementation
- Frontend Developer: UI architecture details
### API Developer
**OWNS**:
- **API Contract Design**: Detailed endpoint specifications, request/response formats
- **API Documentation**: OpenAPI specs, GraphQL schemas, API guides
- **Endpoint Design**: URL structure, HTTP methods, status codes
- **Data Models**: Request/response DTOs, validation schemas
- **API Standards**: Naming conventions, versioning strategy, pagination
- **API-Level Security**: Authentication endpoints, rate limiting rules
**DOES NOT OWN**:
- Which API technology to use (REST vs GraphQL) - Architect decides
- Overall system architecture
- Database schema design
- Business logic implementation
- Infrastructure and deployment
**RECEIVES FROM ARCHITECT**:
- API technology choice (REST, GraphQL, tRPC)
- Authentication strategy (JWT, OAuth)
- Overall security requirements
- Performance requirements
## Collaboration Workflow
### Phase 1: Architecture (Solution Architect)
```
Architect analyzes requirements
→ Selects technology stack (including API type)
→ Designs high-level architecture
→ Creates architecture checkpoint
```
### Phase 2: API Design (API Developer)
```
API Developer receives architecture checkpoint
→ Designs detailed API contracts based on chosen technology
→ Creates OpenAPI/GraphQL schemas
→ Documents endpoints and data models
```
### Phase 3: Implementation (Backend/Frontend Developers)
```
Backend Developer implements API logic
Frontend Developer consumes API
Both follow contracts defined by API Developer
```
## Decision Matrix
| Decision | Solution Architect | API Developer | Backend Dev |
|----------|------------------|---------------|-------------|
| REST vs GraphQL vs tRPC | ✅ Decides | ❌ | ❌ |
| API endpoint structure | ❌ | ✅ Designs | ❌ |
| Database technology | ✅ Decides | ❌ | ❌ |
| Database schema | ❌ | ❌ | ✅ Designs |
| Authentication method | ✅ Decides strategy | ✅ Implements endpoints | ❌ |
| Business logic | ❌ | ❌ | ✅ Implements |
| API documentation | ❌ | ✅ Creates | ❌ |
| Microservices vs Monolith | ✅ Decides | ❌ | ❌ |
| API versioning strategy | ❌ | ✅ Decides | ❌ |
| Rate limiting rules | ❌ | ✅ Defines | ✅ Implements |
| Caching strategy | ✅ Overall strategy | ✅ API caching | ✅ Implementation |
## Example Scenarios
### Scenario 1: Building User Authentication
1. **Architect**: "Use JWT with refresh tokens, store in httpOnly cookies"
2. **API Developer**: Designs `/auth/login`, `/auth/refresh`, `/auth/logout` endpoints with request/response formats
3. **Backend Developer**: Implements bcrypt hashing, JWT generation, token validation
### Scenario 2: Choosing API Technology
1. **Architect**: "Use GraphQL for mobile app due to flexible queries and bandwidth optimization"
2. **API Developer**: Creates GraphQL schema, resolvers structure, subscription design
3. **Backend Developer**: Implements resolver logic, database queries
### Scenario 3: API Rate Limiting
1. **Architect**: "Need rate limiting for API protection"
2. **API Developer**: "100 req/min for free tier, 1000 req/min for paid, per-endpoint limits"
3. **Backend Developer**: Implements with Redis and rate-limit middleware
## Red Flags (Role Confusion)
**API Developer deciding to use GraphQL** (Architect's decision)
**Solution Architect writing OpenAPI specs** (API Developer's job)
**API Developer designing database schema** (Backend Developer's job)
**Backend Developer changing API contracts** (API Developer owns contracts)
**Solution Architect implementing endpoints** (Backend Developer's job)
## Communication Protocol
### Architect → API Developer
Provides:
- Technology choice (REST/GraphQL/tRPC)
- Security requirements
- Performance constraints
- Integration requirements
### API Developer → Backend Developer
Provides:
- API contracts (OpenAPI/GraphQL schema)
- Validation rules
- Error response formats
- Authentication flow
### Feedback Loop
Backend Developer → API Developer: "This endpoint design causes N+1 queries"
API Developer → Architect: "GraphQL complexity requires caching layer"
Architect adjusts overall strategy based on implementation feedback

View File

@ -0,0 +1,49 @@
# Code Quality Standards
## Naming Conventions
**Files**: kebab-case utilities, PascalCase components, camelCase hooks
**Variables**: camelCase functions/vars, PascalCase classes, UPPER_SNAKE constants
**Descriptive**: `isLoading` not `loading`, `handleSubmit` not `submit`
## TypeScript Rules
- No `any` - use `unknown` for truly unknown
- `interface` for objects, `type` for unions/intersections
- Explicit function return types
- Generics for reusable type-safe code
- Strict mode always enabled
## Testing Philosophy
- Test user interactions, not implementation
- Mock external dependencies
- Integration tests for critical paths
- Unit tests for complex logic
- Target >80% coverage on critical code
## Error Handling
- Custom error classes for different types
- Centralized error handling
- Structured logging with context
- Never expose stack traces in production
- Proper HTTP status codes (400, 401, 404, 500)
## Git Standards
**Commit Format**: `<type>(<scope>): <subject>`
**Types**: feat, fix, docs, style, refactor, test, chore
**Example**: `feat(auth): add password reset`
**PR Requirements**:
- TypeScript compiles
- ESLint passes
- Tests pass, coverage >80%
- No console.logs
- Meaningful commits
- Clear description

View File

@ -0,0 +1,83 @@
# Essential Development Principles
Core philosophy for all JavaScript/TypeScript agents. These are non-negotiable.
## Universal Principles
**Type Safety First**: Catch errors at compile time. Use TypeScript strict mode.
**Security First**: Authenticate endpoints. Validate inputs. Sanitize outputs. Never trust client.
**Developer Experience**: Fast feedback. Clear errors. Intuitive APIs. Good docs.
**Performance Matters**: Optimize perceived performance first. Measure before optimizing.
**Maintainability**: Clean code. Consistent patterns. Automated tests. Documentation.
**YAGNI**: Don't over-engineer. Build for 2x scale, not 100x. Use boring, proven tech.
**Component-First**: Everything is reusable, testable, composable.
**Clean Architecture**: Separate concerns. Dependency injection. Controllers handle I/O, services handle logic.
**Observability**: Log, monitor, track errors. Can't improve what you don't measure.
## Context Efficiency Philosophy
**Reference, Don't Repeat**: Point to file paths, don't duplicate content.
- ✅ "Implementation in `src/auth.service.ts`"
- ❌ Pasting entire file
**Provide Summaries**: After creating artifacts, give 2-3 sentence overview.
- ✅ "Created JWT auth. See `src/auth.service.ts`"
- ❌ Explaining every line
**Progressive Detail**: High-level first, details when implementing.
**Archive Verbose**: Keep implementations in files, reference them.
**Checkpoint at Transitions**: Compress to max 100-line summaries with:
- Final decisions
- File paths
- Critical constraints
- Next steps
## JIT Context Loading
**Start Minimal**: Load role + essential-principles + task ONLY
**Load on Decision**: Load guides ONLY when making specific decision
**Question Before Loading**:
1. Making THIS decision NOW?
2. My role's responsibility?
3. Not in checkpoint already?
4. Can't use role knowledge?
If any NO → Don't load
## Token Budget Awareness
**Targets**:
- Simple task: <1,000 tokens
- Medium task: 1,000-2,000 tokens
- Complex task: 2,000-4,000 tokens
- Use checkpoints when >3,000
**Status Levels**:
- 🟢 0-50%: Continue normally
- 🟡 50-75%: Be selective
- 🟠 75-90%: Stop loading
- 🔴 >90%: Checkpoint NOW
## Working Philosophy
**Start Simple**: MVP first. Monolith before microservices.
**Fail Fast**: Validate early. Catch at compile time.
**Iterate Quickly**: Ship small. Get feedback. Improve.
**Automate Everything**: Testing, linting, deployment.
**Monitor and Learn**: Track metrics. Analyze errors. Improve.

View File

@ -0,0 +1,55 @@
# Core Development Principles - Index
Modular core principles for efficient context loading. Load only what you need.
## Module Structure
### Essential (Load Always) - ~300 tokens
- `essential-principles.md` - Universal principles every agent must follow
### Context Management - ~400 tokens each
- `context-efficiency.md` - Token optimization and JIT loading
- `runtime-monitoring.md` - Token accounting and self-regulation
- `prompt-caching.md` - Cache optimization strategies
### Development Standards - ~200 tokens each
- `code-quality.md` - Naming, TypeScript, testing standards
- `security-standards.md` - Authentication, validation, API security
- `performance-standards.md` - Frontend and backend optimization
- `documentation-standards.md` - Code, API, architecture docs
## Loading Strategy
### For All Agents
```
ALWAYS LOAD:
- essential-principles.md (~300 tokens)
LOAD IF NEEDED:
- context-efficiency.md (when managing complex workflows)
- runtime-monitoring.md (when approaching token limits)
- prompt-caching.md (for repetitive tasks)
```
### By Agent Role
**React Developer**:
- essential-principles.md
- code-quality.md (TypeScript section)
- performance-standards.md (Frontend section)
**Node Backend Developer**:
- essential-principles.md
- code-quality.md (Testing section)
- security-standards.md (API section)
- performance-standards.md (Backend section)
**Solution Architect**:
- essential-principles.md
- context-efficiency.md
- All standards (for review)
**API Developer**:
- essential-principles.md
- documentation-standards.md (API section)
- security-standards.md (API security)

View File

@ -0,0 +1,31 @@
# Performance Standards
## Frontend Performance
- Code splitting and lazy loading for routes
- React.memo only when measured benefit
- Virtual scrolling for long lists
- Image optimization (next/image or similar)
- Bundle analysis and tree shaking
- Preload critical resources
- Minimize main thread work
## Backend Performance
- Database indexes on query fields
- Connection pooling
- Redis caching for frequent data
- Pagination for large results
- Async/await throughout
- Background jobs for heavy processing
- Query optimization (avoid N+1)
## General Optimization
- Measure before optimizing
- Focus on perceived performance
- Cache strategically
- Compress responses (gzip/brotli)
- CDN for static assets
- Database query optimization
- Load balancing for scale

View File

@ -0,0 +1,31 @@
# Security Standards
## Authentication
- bcrypt/argon2 for passwords (10+ rounds)
- JWT with short access + long refresh tokens
- Refresh tokens in httpOnly cookies or secure DB
- Token rotation on refresh
## Input Validation
- Validate ALL inputs with Zod or Joi
- Sanitize HTML output to prevent XSS
- Parameterized queries for SQL injection prevention
- Whitelist, never blacklist
## API Security
- CORS with specific origins (not *)
- Rate limiting per user/endpoint
- CSRF protection for state changes
- Security headers with Helmet.js
- HTTPS in production always
## Secrets Management
- Never commit secrets to version control
- Use environment variables (.env)
- Rotate credentials regularly
- Minimal privilege principle
- Separate dev/staging/prod secrets

View File

@ -0,0 +1,248 @@
# BMAD Checkpoint Metadata Format
# Structured format for consistent, searchable, reusable checkpoints
checkpoint:
# === METADATA HEADER (Required) ===
metadata:
id: "checkpoint-{phase}-{timestamp}" # Unique identifier
version: "1.0.0" # Checkpoint format version
created_at: "2024-01-15T10:30:00Z" # ISO 8601 timestamp
created_by: "agent-role" # Agent who created checkpoint
phase: "architecture" # Current phase (requirements/architecture/implementation)
project: "project-name" # Project identifier
# Token metrics for optimization
tokens:
original: 4500 # Tokens before compression
compressed: 800 # Tokens after compression
savings_percent: 82 # Percentage saved
# Searchable tags for retrieval
tags:
- "authentication"
- "rest-api"
- "jwt"
- "postgresql"
# Dependencies on other checkpoints
dependencies:
- "checkpoint-requirements-20240114"
- "checkpoint-tech-stack-20240115"
# === DECISIONS SECTION (Required) ===
decisions:
# Technology decisions with rationale
technology_stack:
frontend:
framework: "Next.js 14"
rationale: "SSR needed for SEO, RSC for performance"
backend:
framework: "Fastify"
rationale: "High performance requirement (10k req/s)"
database:
primary: "PostgreSQL"
rationale: "Complex relationships, ACID compliance"
# Architecture patterns decided
patterns:
api_style: "REST"
auth_method: "JWT with refresh tokens"
state_management: "Zustand + React Query"
deployment: "Container-based on AWS ECS"
# Key constraints identified
constraints:
performance: "Sub-200ms p95 response time"
security: "OWASP Top 10 compliance required"
scale: "Support 10,000 concurrent users"
budget: "$5,000/month infrastructure"
# === ARTIFACTS SECTION (Required) ===
artifacts:
# Created files with paths and purpose
created:
- path: "docs/architecture/system-design.md"
type: "architecture-doc"
tokens: 1200
purpose: "Complete system architecture"
- path: "api/openapi-spec.yaml"
type: "api-specification"
tokens: 800
purpose: "REST API contract"
- path: "database/schema.sql"
type: "database-schema"
tokens: 600
purpose: "PostgreSQL schema with migrations"
# Modified files
modified:
- path: "README.md"
changes: "Added architecture section"
- path: "package.json"
changes: "Added core dependencies"
# Files to be created in next phase
pending:
- "src/services/auth.service.ts"
- "src/components/LoginForm.tsx"
- "src/api/routes/auth.routes.ts"
# === CONTEXT SUMMARY (Required) ===
summary:
# Executive summary (2-3 sentences max)
executive: |
Designed microservices architecture using Next.js frontend and Fastify backend.
JWT authentication with PostgreSQL database, deployed on AWS ECS.
# Key accomplishments
completed:
- "Technology stack selected and validated"
- "API specification designed (42 endpoints)"
- "Database schema with 15 tables defined"
- "Security architecture implemented"
# Critical information for next phase
critical_context:
- "API rate limiting: 100 req/min for free tier"
- "Database indexes needed on user.email and post.created_at"
- "Redis required for session management"
- "CORS configured for frontend domain only"
# Known issues or blockers
issues:
- description: "Payment provider not yet selected"
severity: "medium"
blocks: "checkout-flow"
- description: "Email service decision pending"
severity: "low"
blocks: "user-notifications"
# === NEXT STEPS (Required) ===
next_steps:
immediate:
- task: "Implement authentication service"
assigned_to: "node-backend-developer"
priority: "high"
- task: "Create login/register components"
assigned_to: "react-developer"
priority: "high"
parallel_work:
- "Frontend team: Build component library"
- "Backend team: Implement core API endpoints"
- "DevOps: Setup CI/CD pipeline"
dependencies_needed:
- "Finalize payment provider (blocks checkout)"
- "Obtain SSL certificates (blocks deployment)"
# === METRICS (Optional but recommended) ===
metrics:
# Quantifiable metrics for tracking
code_metrics:
files_created: 12
lines_of_code: 1847
test_coverage: 0 # Not yet implemented
# Performance benchmarks
performance:
api_response_time: null # To be measured
database_queries: null # To be optimized
bundle_size: null # To be analyzed
# Time tracking
time_spent:
architecture_design: "4 hours"
api_specification: "2 hours"
database_design: "3 hours"
documentation: "1 hour"
# === HANDOFF PROTOCOL (Required for phase transitions) ===
handoff:
from_agent: "js-solution-architect"
to_agents:
- "node-backend-developer"
- "react-developer"
- "api-developer"
handoff_message: |
Architecture complete. Backend team implement auth first.
Frontend team can start component library in parallel.
API developer please review and refine endpoint specs.
validation_checklist:
- "[x] All technology decisions documented"
- "[x] API specification complete"
- "[x] Database schema defined"
- "[x] Security requirements clear"
- "[x] Performance targets set"
- "[ ] Payment provider selected"
- "[ ] Email service configured"
# === CHECKPOINT USAGE EXAMPLES ===
# Example 1: Minimal checkpoint (requirements phase)
checkpoint_minimal:
metadata:
id: "checkpoint-requirements-20240115"
phase: "requirements"
tokens: { original: 2000, compressed: 400 }
decisions:
scope: "MVP with user auth, posts, and comments"
timeline: "8 weeks"
budget: "$50,000"
artifacts:
created:
- path: "docs/requirements.md"
summary:
executive: "MVP requirements gathered. Focus on core social features."
next_steps:
immediate:
- task: "Design system architecture"
# Example 2: Implementation checkpoint
checkpoint_implementation:
metadata:
id: "checkpoint-auth-implementation-20240120"
phase: "implementation"
tokens: { original: 3000, compressed: 600 }
decisions:
implementation_choices:
password_hashing: "bcrypt with 10 rounds"
token_storage: "httpOnly cookies"
session_length: "7 days"
artifacts:
created:
- path: "src/services/auth.service.ts"
- path: "src/middleware/auth.middleware.ts"
- path: "tests/auth.test.ts"
summary:
executive: "Authentication system fully implemented with JWT."
completed:
- "Login/logout endpoints"
- "Password reset flow"
- "Role-based access control"
next_steps:
immediate:
- task: "Implement user profile endpoints"
# === CHECKPOINT SEARCH QUERIES ===
# Checkpoints can be searched by:
# - metadata.tags: Find all checkpoints with specific tags
# - metadata.phase: Find checkpoints from specific phase
# - artifacts.created[].type: Find checkpoints that created specific artifact types
# - decisions.technology_stack: Find projects using specific technologies
# - metadata.created_by: Find all checkpoints from specific agent

View File

@ -0,0 +1,398 @@
#!/usr/bin/env node
/**
* Runtime Token Tracking & Alert System for BMAD
* Provides real-time token monitoring, alerts, and automatic checkpoint triggers
*/
const EventEmitter = require('events');
const fs = require('fs');
const path = require('path');
class TokenTracker extends EventEmitter {
constructor(options = {}) {
super();
// Configuration
this.budget = options.budget || 5000;
this.checkpointThreshold = options.checkpointThreshold || 3000;
this.warningThreshold = options.warningThreshold || 0.75;
this.criticalThreshold = options.criticalThreshold || 0.9;
// State tracking
this.currentTokens = 0;
this.contextHistory = [];
this.loadedFiles = new Map();
this.startTime = Date.now();
this.checkpointCount = 0;
// Telemetry
this.metrics = {
totalLoaded: 0,
totalSaved: 0,
checkpoints: [],
alerts: [],
fileAccess: new Map()
};
this.setupAlerts();
}
/**
* Setup alert handlers
*/
setupAlerts() {
this.on('warning', (data) => {
console.warn(`⚠️ TOKEN WARNING: ${data.message}`);
this.metrics.alerts.push({ level: 'warning', ...data, timestamp: Date.now() });
});
this.on('critical', (data) => {
console.error(`🚨 TOKEN CRITICAL: ${data.message}`);
this.metrics.alerts.push({ level: 'critical', ...data, timestamp: Date.now() });
});
this.on('checkpoint-needed', (data) => {
console.log(`📍 CHECKPOINT NEEDED: ${data.message}`);
this.metrics.alerts.push({ level: 'checkpoint', ...data, timestamp: Date.now() });
});
}
/**
* Track file loading
*/
loadFile(filepath, content) {
const tokens = this.estimateTokens(content);
const filename = path.basename(filepath);
// Check if would exceed budget
if (this.currentTokens + tokens > this.budget) {
this.emit('critical', {
message: `Loading ${filename} (${tokens} tokens) would exceed budget`,
current: this.currentTokens,
attempted: tokens,
budget: this.budget
});
return false;
}
// Track the load
this.loadedFiles.set(filepath, {
tokens,
loadedAt: Date.now(),
accessCount: 1
});
this.currentTokens += tokens;
this.metrics.totalLoaded += tokens;
// Update file access metrics
const access = this.metrics.fileAccess.get(filepath) || { count: 0, tokens: 0 };
access.count++;
access.tokens += tokens;
this.metrics.fileAccess.set(filepath, access);
// Add to history
this.contextHistory.push({
action: 'load',
file: filename,
tokens,
total: this.currentTokens,
timestamp: Date.now()
});
this.checkStatus();
return true;
}
/**
* Unload file from context
*/
unloadFile(filepath) {
const file = this.loadedFiles.get(filepath);
if (file) {
this.currentTokens -= file.tokens;
this.loadedFiles.delete(filepath);
this.contextHistory.push({
action: 'unload',
file: path.basename(filepath),
tokens: -file.tokens,
total: this.currentTokens,
timestamp: Date.now()
});
}
}
/**
* Create checkpoint
*/
createCheckpoint(summary, compressedTokens) {
const checkpoint = {
id: `checkpoint-${++this.checkpointCount}`,
timestamp: Date.now(),
originalTokens: this.currentTokens,
compressedTokens,
compressionRatio: ((this.currentTokens - compressedTokens) / this.currentTokens * 100).toFixed(1),
files: Array.from(this.loadedFiles.keys()),
summary
};
this.metrics.checkpoints.push(checkpoint);
this.metrics.totalSaved += (this.currentTokens - compressedTokens);
// Reset context
this.currentTokens = compressedTokens;
this.loadedFiles.clear();
this.contextHistory.push({
action: 'checkpoint',
checkpoint: checkpoint.id,
saved: checkpoint.originalTokens - compressedTokens,
timestamp: Date.now()
});
return checkpoint;
}
/**
* Check current status and emit alerts
*/
checkStatus() {
const usage = this.currentTokens / this.budget;
const status = this.getStatus();
// Checkpoint threshold
if (this.currentTokens > this.checkpointThreshold) {
this.emit('checkpoint-needed', {
message: `Context exceeds checkpoint threshold (${this.currentTokens}/${this.checkpointThreshold})`,
current: this.currentTokens,
threshold: this.checkpointThreshold
});
}
// Budget alerts
if (usage > this.criticalThreshold && status.previous !== 'critical') {
this.emit('critical', {
message: `Token usage critical: ${(usage * 100).toFixed(1)}% of budget`,
current: this.currentTokens,
budget: this.budget
});
} else if (usage > this.warningThreshold && status.previous === 'green') {
this.emit('warning', {
message: `Token usage warning: ${(usage * 100).toFixed(1)}% of budget`,
current: this.currentTokens,
budget: this.budget
});
}
}
/**
* Get current status
*/
getStatus() {
const usage = this.currentTokens / this.budget;
let status, emoji, color;
if (usage < 0.5) {
status = 'green';
emoji = '🟢';
color = '\x1b[32m';
} else if (usage < this.warningThreshold) {
status = 'yellow';
emoji = '🟡';
color = '\x1b[33m';
} else if (usage < this.criticalThreshold) {
status = 'orange';
emoji = '🟠';
color = '\x1b[38;5;208m';
} else {
status = 'critical';
emoji = '🔴';
color = '\x1b[31m';
}
return {
status,
emoji,
color,
usage: (usage * 100).toFixed(1),
current: this.currentTokens,
budget: this.budget,
remaining: this.budget - this.currentTokens
};
}
/**
* Estimate tokens (simplified)
*/
estimateTokens(content) {
const words = content.match(/\b\w+\b/g) || [];
return Math.ceil(words.length * 1.3);
}
/**
* Get recommendations based on current state
*/
getRecommendations() {
const recommendations = [];
const status = this.getStatus();
if (status.status === 'critical') {
recommendations.push('🚨 CREATE CHECKPOINT IMMEDIATELY');
recommendations.push('❌ DO NOT LOAD ANY MORE FILES');
} else if (status.status === 'orange') {
recommendations.push('⚠️ Consider creating checkpoint soon');
recommendations.push('🎯 Load only critical files');
}
// Check for unused files
const unused = [];
const now = Date.now();
for (const [file, data] of this.loadedFiles) {
if (now - data.loadedAt > 300000) { // 5 minutes
unused.push(path.basename(file));
}
}
if (unused.length > 0) {
recommendations.push(`💡 Consider unloading unused files: ${unused.join(', ')}`);
}
// Check for frequently accessed files
const frequent = [];
for (const [file, access] of this.metrics.fileAccess) {
if (access.count > 3) {
frequent.push(path.basename(file));
}
}
if (frequent.length > 0) {
recommendations.push(`📌 Consider caching frequently accessed: ${frequent.join(', ')}`);
}
return recommendations;
}
/**
* Generate report
*/
generateReport() {
const status = this.getStatus();
const duration = Math.floor((Date.now() - this.startTime) / 1000);
console.log('\n' + '='.repeat(80));
console.log('RUNTIME TOKEN TRACKING REPORT');
console.log('='.repeat(80));
// Current Status
console.log('\n📊 CURRENT STATUS');
console.log('-'.repeat(40));
console.log(`Status: ${status.emoji} ${status.status.toUpperCase()} (${status.usage}%)`);
console.log(`Tokens: ${status.current} / ${status.budget}`);
console.log(`Remaining: ${status.remaining} tokens`);
console.log(`Duration: ${duration} seconds`);
// Loaded Files
if (this.loadedFiles.size > 0) {
console.log('\n📁 LOADED FILES');
console.log('-'.repeat(40));
for (const [file, data] of this.loadedFiles) {
const age = Math.floor((Date.now() - data.loadedAt) / 1000);
console.log(`${path.basename(file).padEnd(30)} ${String(data.tokens).padStart(6)} tokens (${age}s ago)`);
}
}
// Metrics
console.log('\n📈 METRICS');
console.log('-'.repeat(40));
console.log(`Total Loaded: ${this.metrics.totalLoaded} tokens`);
console.log(`Total Saved: ${this.metrics.totalSaved} tokens`);
console.log(`Checkpoints: ${this.metrics.checkpoints.length}`);
console.log(`Alerts: ${this.metrics.alerts.length}`);
// Checkpoints
if (this.metrics.checkpoints.length > 0) {
console.log('\n📍 CHECKPOINTS');
console.log('-'.repeat(40));
for (const cp of this.metrics.checkpoints) {
console.log(`${cp.id}: ${cp.originalTokens}${cp.compressedTokens} tokens (${cp.compressionRatio}% saved)`);
}
}
// Recommendations
const recommendations = this.getRecommendations();
if (recommendations.length > 0) {
console.log('\n💡 RECOMMENDATIONS');
console.log('-'.repeat(40));
for (const rec of recommendations) {
console.log(rec);
}
}
console.log('\n' + '='.repeat(80));
}
/**
* Export telemetry data
*/
exportTelemetry() {
return {
session: {
startTime: this.startTime,
duration: Date.now() - this.startTime,
budget: this.budget,
peakUsage: Math.max(...this.contextHistory.map(h => h.total || 0)),
checkpoints: this.checkpointCount
},
metrics: this.metrics,
history: this.contextHistory,
fileAccess: Array.from(this.metrics.fileAccess.entries()).map(([file, access]) => ({
file: path.basename(file),
...access
}))
};
}
}
// Interactive CLI mode
if (require.main === module) {
const tracker = new TokenTracker({
budget: parseInt(process.argv[2]) || 5000,
checkpointThreshold: parseInt(process.argv[3]) || 3000
});
console.log('🚀 Token Tracker Started');
console.log(`Budget: ${tracker.budget} tokens`);
console.log(`Checkpoint threshold: ${tracker.checkpointThreshold} tokens`);
// Simulate file loading for demo
const files = [
{ name: 'core-principles.md', tokens: 1500 },
{ name: 'api-patterns.md', tokens: 1000 },
{ name: 'security-guide.md', tokens: 800 },
{ name: 'testing-strategy.md', tokens: 600 }
];
console.log('\nSimulating file loads...\n');
for (const file of files) {
console.log(`Loading ${file.name}...`);
tracker.loadFile(file.name, 'x'.repeat(file.tokens * 5));
const status = tracker.getStatus();
console.log(` Status: ${status.emoji} ${status.usage}% (${status.current}/${status.budget})`);
// Pause for effect
require('child_process').execSync('sleep 1');
}
tracker.generateReport();
// Export telemetry
const telemetry = tracker.exportTelemetry();
fs.writeFileSync('token-telemetry.json', JSON.stringify(telemetry, null, 2));
console.log('\n📊 Telemetry exported to token-telemetry.json');
}
module.exports = TokenTracker;

View File

@ -0,0 +1,766 @@
#!/usr/bin/env node
/**
* BMAD Telemetry & Analytics System
* Tracks agent usage patterns, performance metrics, and optimization opportunities
*/
const fs = require('fs').promises;
const path = require('path');
const crypto = require('crypto');
class TelemetryAnalytics {
constructor(options = {}) {
this.dataDir = options.dataDir || path.join(__dirname, '../telemetry-data');
this.sessionId = crypto.randomBytes(16).toString('hex');
this.startTime = Date.now();
// Initialize collectors
this.collectors = {
agentUsage: new Map(),
fileAccess: new Map(),
tokenPatterns: [],
checkpoints: [],
decisions: [],
errors: [],
performance: []
};
// Configuration
this.config = {
autoSave: options.autoSave !== false,
saveInterval: options.saveInterval || 60000, // 1 minute
anonymize: options.anonymize !== false,
verbose: options.verbose || false
};
this.initializeDataDir();
if (this.config.autoSave) {
this.startAutoSave();
}
}
/**
* Initialize telemetry data directory
*/
async initializeDataDir() {
try {
await fs.mkdir(this.dataDir, { recursive: true });
await fs.mkdir(path.join(this.dataDir, 'sessions'), { recursive: true });
await fs.mkdir(path.join(this.dataDir, 'aggregated'), { recursive: true });
} catch (error) {
console.error('Failed to initialize telemetry directory:', error);
}
}
/**
* Track agent usage
*/
trackAgentUsage(agentName, action, metadata = {}) {
const agent = this.collectors.agentUsage.get(agentName) || {
invocations: 0,
totalTokensUsed: 0,
totalTimeMs: 0,
actions: new Map(),
errors: 0
};
agent.invocations++;
agent.totalTokensUsed += metadata.tokensUsed || 0;
agent.totalTimeMs += metadata.timeMs || 0;
// Track specific actions
const actionCount = agent.actions.get(action) || 0;
agent.actions.set(action, actionCount + 1);
this.collectors.agentUsage.set(agentName, agent);
// Log event
this.logEvent('agent_usage', {
agent: agentName,
action,
...metadata,
timestamp: Date.now()
});
}
/**
* Track file access patterns
*/
trackFileAccess(filepath, operation, metadata = {}) {
const filename = path.basename(filepath);
const file = this.collectors.fileAccess.get(filename) || {
accessCount: 0,
operations: new Map(),
totalTokens: 0,
agents: new Set(),
firstAccess: Date.now(),
lastAccess: Date.now()
};
file.accessCount++;
file.lastAccess = Date.now();
file.totalTokens += metadata.tokens || 0;
if (metadata.agent) {
file.agents.add(metadata.agent);
}
const opCount = file.operations.get(operation) || 0;
file.operations.set(operation, opCount + 1);
this.collectors.fileAccess.set(filename, file);
this.logEvent('file_access', {
file: filename,
operation,
...metadata,
timestamp: Date.now()
});
}
/**
* Track token usage patterns
*/
trackTokenUsage(context, tokens, metadata = {}) {
const pattern = {
context,
tokens,
timestamp: Date.now(),
phase: metadata.phase || 'unknown',
agent: metadata.agent || 'unknown',
efficiency: metadata.efficiency || this.calculateEfficiency(tokens, metadata)
};
this.collectors.tokenPatterns.push(pattern);
// Track peak usage
if (!this.peakTokenUsage || tokens > this.peakTokenUsage.tokens) {
this.peakTokenUsage = pattern;
}
this.logEvent('token_usage', pattern);
}
/**
* Track checkpoint creation
*/
trackCheckpoint(checkpointId, originalTokens, compressedTokens, metadata = {}) {
const checkpoint = {
id: checkpointId,
originalTokens,
compressedTokens,
compressionRatio: ((originalTokens - compressedTokens) / originalTokens * 100).toFixed(1),
timestamp: Date.now(),
phase: metadata.phase || 'unknown',
agent: metadata.agent || 'unknown',
artifacts: metadata.artifacts || []
};
this.collectors.checkpoints.push(checkpoint);
this.logEvent('checkpoint', checkpoint);
}
/**
* Track decision points
*/
trackDecision(decisionType, choice, metadata = {}) {
const decision = {
type: decisionType,
choice,
timestamp: Date.now(),
agent: metadata.agent || 'unknown',
rationale: metadata.rationale || '',
alternatives: metadata.alternatives || [],
confidence: metadata.confidence || 1.0
};
this.collectors.decisions.push(decision);
this.logEvent('decision', decision);
}
/**
* Track errors and failures
*/
trackError(errorType, message, metadata = {}) {
const error = {
type: errorType,
message: this.config.anonymize ? this.anonymizeError(message) : message,
timestamp: Date.now(),
agent: metadata.agent || 'unknown',
phase: metadata.phase || 'unknown',
severity: metadata.severity || 'medium',
resolved: metadata.resolved || false
};
this.collectors.errors.push(error);
this.logEvent('error', error);
}
/**
* Track performance metrics
*/
trackPerformance(operation, duration, metadata = {}) {
const perf = {
operation,
duration,
timestamp: Date.now(),
success: metadata.success !== false,
tokensConsumed: metadata.tokens || 0,
efficiency: duration > 0 ? (metadata.tokens || 0) / duration : 0
};
this.collectors.performance.push(perf);
this.logEvent('performance', perf);
}
/**
* Calculate efficiency metrics
*/
calculateEfficiency(tokens, metadata) {
if (!metadata.outputValue) return 1.0;
// Simple efficiency: output value / tokens used
return Math.min(metadata.outputValue / tokens, 2.0);
}
/**
* Anonymize error messages
*/
anonymizeError(message) {
// Remove file paths, URLs, and potentially sensitive data
return message
.replace(/\/[^\s]+/g, '/[path]')
.replace(/https?:\/\/[^\s]+/g, '[url]')
.replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g, '[email]');
}
/**
* Log event to memory
*/
logEvent(type, data) {
if (this.config.verbose) {
console.log(`[Telemetry] ${type}:`, data);
}
}
/**
* Analyze collected data
*/
analyze() {
const duration = Date.now() - this.startTime;
const analysis = {
session: {
id: this.sessionId,
duration,
startTime: this.startTime,
endTime: Date.now()
},
agents: this.analyzeAgents(),
files: this.analyzeFiles(),
tokens: this.analyzeTokens(),
checkpoints: this.analyzeCheckpoints(),
decisions: this.analyzeDecisions(),
errors: this.analyzeErrors(),
performance: this.analyzePerformance(),
recommendations: this.generateRecommendations()
};
return analysis;
}
/**
* Analyze agent usage patterns
*/
analyzeAgents() {
const agents = Array.from(this.collectors.agentUsage.entries()).map(([name, data]) => ({
name,
invocations: data.invocations,
avgTokensPerInvocation: data.invocations > 0 ? Math.round(data.totalTokensUsed / data.invocations) : 0,
avgTimeMs: data.invocations > 0 ? Math.round(data.totalTimeMs / data.invocations) : 0,
topActions: Array.from(data.actions.entries())
.sort((a, b) => b[1] - a[1])
.slice(0, 5)
.map(([action, count]) => ({ action, count })),
errorRate: data.invocations > 0 ? (data.errors / data.invocations * 100).toFixed(1) : 0
}));
return {
totalAgents: agents.length,
mostUsed: agents.sort((a, b) => b.invocations - a.invocations)[0],
leastUsed: agents.sort((a, b) => a.invocations - b.invocations)[0],
agents
};
}
/**
* Analyze file access patterns
*/
analyzeFiles() {
const files = Array.from(this.collectors.fileAccess.entries()).map(([name, data]) => ({
name,
accessCount: data.accessCount,
avgTokens: data.accessCount > 0 ? Math.round(data.totalTokens / data.accessCount) : 0,
agentCount: data.agents.size,
accessPattern: this.detectAccessPattern(data),
operations: Array.from(data.operations.entries())
}));
return {
totalFiles: files.length,
mostAccessed: files.sort((a, b) => b.accessCount - a.accessCount)[0],
largestFile: files.sort((a, b) => b.avgTokens - a.avgTokens)[0],
accessPatterns: this.summarizeAccessPatterns(files),
files
};
}
/**
* Detect file access patterns
*/
detectAccessPattern(fileData) {
const duration = fileData.lastAccess - fileData.firstAccess;
const accessRate = fileData.accessCount / (duration / 1000 / 60); // per minute
if (accessRate > 10) return 'hot';
if (accessRate > 1) return 'frequent';
if (fileData.accessCount === 1) return 'one-time';
return 'occasional';
}
/**
* Analyze token usage patterns
*/
analyzeTokens() {
if (this.collectors.tokenPatterns.length === 0) {
return { totalTokens: 0, patterns: [] };
}
const totalTokens = this.collectors.tokenPatterns.reduce((sum, p) => sum + p.tokens, 0);
const avgTokens = Math.round(totalTokens / this.collectors.tokenPatterns.length);
// Group by phase
const byPhase = {};
for (const pattern of this.collectors.tokenPatterns) {
if (!byPhase[pattern.phase]) {
byPhase[pattern.phase] = { count: 0, tokens: 0 };
}
byPhase[pattern.phase].count++;
byPhase[pattern.phase].tokens += pattern.tokens;
}
return {
totalTokens,
avgTokensPerOperation: avgTokens,
peakUsage: this.peakTokenUsage,
byPhase: Object.entries(byPhase).map(([phase, data]) => ({
phase,
operations: data.count,
totalTokens: data.tokens,
avgTokens: Math.round(data.tokens / data.count)
})),
efficiency: this.calculateOverallEfficiency()
};
}
/**
* Analyze checkpoints
*/
analyzeCheckpoints() {
if (this.collectors.checkpoints.length === 0) {
return { count: 0, avgCompression: 0 };
}
const avgCompression = this.collectors.checkpoints
.reduce((sum, cp) => sum + parseFloat(cp.compressionRatio), 0) / this.collectors.checkpoints.length;
const totalSaved = this.collectors.checkpoints
.reduce((sum, cp) => sum + (cp.originalTokens - cp.compressedTokens), 0);
return {
count: this.collectors.checkpoints.length,
avgCompression: avgCompression.toFixed(1),
totalTokensSaved: totalSaved,
checkpoints: this.collectors.checkpoints
};
}
/**
* Analyze decisions
*/
analyzeDecisions() {
const decisionTypes = {};
for (const decision of this.collectors.decisions) {
if (!decisionTypes[decision.type]) {
decisionTypes[decision.type] = [];
}
decisionTypes[decision.type].push(decision.choice);
}
return {
totalDecisions: this.collectors.decisions.length,
byType: Object.entries(decisionTypes).map(([type, choices]) => ({
type,
count: choices.length,
choices: [...new Set(choices)]
})),
avgConfidence: this.collectors.decisions.length > 0
? (this.collectors.decisions.reduce((sum, d) => sum + d.confidence, 0) / this.collectors.decisions.length).toFixed(2)
: 1.0
};
}
/**
* Analyze errors
*/
analyzeErrors() {
const byType = {};
const bySeverity = { low: 0, medium: 0, high: 0, critical: 0 };
for (const error of this.collectors.errors) {
byType[error.type] = (byType[error.type] || 0) + 1;
bySeverity[error.severity]++;
}
return {
totalErrors: this.collectors.errors.length,
byType,
bySeverity,
resolvedCount: this.collectors.errors.filter(e => e.resolved).length,
criticalErrors: this.collectors.errors.filter(e => e.severity === 'critical')
};
}
/**
* Analyze performance
*/
analyzePerformance() {
if (this.collectors.performance.length === 0) {
return { operations: 0 };
}
const successful = this.collectors.performance.filter(p => p.success);
const avgDuration = this.collectors.performance
.reduce((sum, p) => sum + p.duration, 0) / this.collectors.performance.length;
return {
operations: this.collectors.performance.length,
successRate: (successful.length / this.collectors.performance.length * 100).toFixed(1),
avgDuration: Math.round(avgDuration),
slowestOperation: this.collectors.performance
.sort((a, b) => b.duration - a.duration)[0],
totalTokensConsumed: this.collectors.performance
.reduce((sum, p) => sum + p.tokensConsumed, 0)
};
}
/**
* Calculate overall efficiency
*/
calculateOverallEfficiency() {
const patterns = this.collectors.tokenPatterns;
if (patterns.length === 0) return 1.0;
const avgEfficiency = patterns
.reduce((sum, p) => sum + p.efficiency, 0) / patterns.length;
return avgEfficiency.toFixed(2);
}
/**
* Summarize access patterns
*/
summarizeAccessPatterns(files) {
const patterns = { hot: 0, frequent: 0, occasional: 0, 'one-time': 0 };
for (const file of files) {
patterns[file.accessPattern]++;
}
return patterns;
}
/**
* Generate recommendations
*/
generateRecommendations() {
const recommendations = [];
const analysis = {
agents: this.analyzeAgents(),
files: this.analyzeFiles(),
tokens: this.analyzeTokens(),
errors: this.analyzeErrors()
};
// Token optimization
if (analysis.tokens.peakUsage && analysis.tokens.peakUsage.tokens > 4000) {
recommendations.push({
type: 'optimization',
priority: 'high',
message: `Peak token usage (${analysis.tokens.peakUsage.tokens}) exceeds recommended limit. Consider more aggressive checkpointing.`
});
}
// File access optimization
const hotFiles = analysis.files.files.filter(f => f.accessPattern === 'hot');
if (hotFiles.length > 0) {
recommendations.push({
type: 'caching',
priority: 'medium',
message: `Files accessed frequently: ${hotFiles.map(f => f.name).join(', ')}. Consider caching these.`
});
}
// Error handling
if (analysis.errors.criticalErrors.length > 0) {
recommendations.push({
type: 'error',
priority: 'critical',
message: `${analysis.errors.criticalErrors.length} critical errors detected. Immediate attention required.`
});
}
// Agent optimization
if (analysis.agents.mostUsed && analysis.agents.mostUsed.avgTokensPerInvocation > 2000) {
recommendations.push({
type: 'agent',
priority: 'medium',
message: `Agent '${analysis.agents.mostUsed.name}' uses high tokens per invocation. Consider splitting responsibilities.`
});
}
// Checkpoint frequency
const checkpointAnalysis = this.analyzeCheckpoints();
if (checkpointAnalysis.count === 0 && analysis.tokens.totalTokens > 10000) {
recommendations.push({
type: 'checkpoint',
priority: 'high',
message: 'No checkpoints created despite high token usage. Implement regular checkpointing.'
});
}
return recommendations;
}
/**
* Save telemetry data
*/
async save() {
try {
const analysis = this.analyze();
const filename = `session-${this.sessionId}-${Date.now()}.json`;
const filepath = path.join(this.dataDir, 'sessions', filename);
await fs.writeFile(filepath, JSON.stringify(analysis, null, 2));
if (this.config.verbose) {
console.log(`Telemetry saved to ${filepath}`);
}
// Also update aggregated data
await this.updateAggregatedData(analysis);
return filepath;
} catch (error) {
console.error('Failed to save telemetry:', error);
return null;
}
}
/**
* Update aggregated data
*/
async updateAggregatedData(sessionAnalysis) {
const aggregatedPath = path.join(this.dataDir, 'aggregated', 'summary.json');
let aggregated = {};
try {
const existing = await fs.readFile(aggregatedPath, 'utf-8');
aggregated = JSON.parse(existing);
} catch (error) {
// File doesn't exist yet, start fresh
}
// Update aggregated metrics
aggregated.sessions = (aggregated.sessions || 0) + 1;
aggregated.totalTokens = (aggregated.totalTokens || 0) + sessionAnalysis.tokens.totalTokens;
aggregated.totalErrors = (aggregated.totalErrors || 0) + sessionAnalysis.errors.totalErrors;
aggregated.lastUpdated = Date.now();
// Track top files
if (!aggregated.topFiles) aggregated.topFiles = {};
for (const file of sessionAnalysis.files.files) {
aggregated.topFiles[file.name] = (aggregated.topFiles[file.name] || 0) + file.accessCount;
}
// Track agent usage
if (!aggregated.agentUsage) aggregated.agentUsage = {};
for (const agent of sessionAnalysis.agents.agents) {
aggregated.agentUsage[agent.name] = (aggregated.agentUsage[agent.name] || 0) + agent.invocations;
}
await fs.writeFile(aggregatedPath, JSON.stringify(aggregated, null, 2));
}
/**
* Start auto-save timer
*/
startAutoSave() {
this.autoSaveTimer = setInterval(() => {
this.save();
}, this.config.saveInterval);
}
/**
* Stop auto-save timer
*/
stopAutoSave() {
if (this.autoSaveTimer) {
clearInterval(this.autoSaveTimer);
this.autoSaveTimer = null;
}
}
/**
* Generate report
*/
generateReport() {
const analysis = this.analyze();
console.log('\n' + '='.repeat(80));
console.log('TELEMETRY ANALYTICS REPORT');
console.log('='.repeat(80));
// Session info
console.log('\n📊 SESSION');
console.log('-'.repeat(40));
console.log(`Session ID: ${analysis.session.id}`);
console.log(`Duration: ${Math.round(analysis.session.duration / 1000)}s`);
// Agent usage
console.log('\n🤖 AGENT USAGE');
console.log('-'.repeat(40));
if (analysis.agents.mostUsed) {
console.log(`Most Used: ${analysis.agents.mostUsed.name} (${analysis.agents.mostUsed.invocations} invocations)`);
}
console.log(`Total Agents: ${analysis.agents.totalAgents}`);
// Token usage
console.log('\n💰 TOKEN USAGE');
console.log('-'.repeat(40));
console.log(`Total Tokens: ${analysis.tokens.totalTokens}`);
console.log(`Avg per Operation: ${analysis.tokens.avgTokensPerOperation}`);
console.log(`Efficiency Score: ${analysis.tokens.efficiency}`);
// File access
console.log('\n📁 FILE ACCESS');
console.log('-'.repeat(40));
console.log(`Total Files: ${analysis.files.totalFiles}`);
if (analysis.files.mostAccessed) {
console.log(`Most Accessed: ${analysis.files.mostAccessed.name} (${analysis.files.mostAccessed.accessCount} times)`);
}
// Checkpoints
console.log('\n📍 CHECKPOINTS');
console.log('-'.repeat(40));
console.log(`Created: ${analysis.checkpoints.count}`);
console.log(`Avg Compression: ${analysis.checkpoints.avgCompression}%`);
console.log(`Tokens Saved: ${analysis.checkpoints.totalTokensSaved}`);
// Errors
if (analysis.errors.totalErrors > 0) {
console.log('\n⚠ ERRORS');
console.log('-'.repeat(40));
console.log(`Total: ${analysis.errors.totalErrors}`);
console.log(`Critical: ${analysis.errors.bySeverity.critical}`);
console.log(`Resolved: ${analysis.errors.resolvedCount}`);
}
// Recommendations
if (analysis.recommendations.length > 0) {
console.log('\n💡 RECOMMENDATIONS');
console.log('-'.repeat(40));
for (const rec of analysis.recommendations) {
const icon = rec.priority === 'critical' ? '🔴' : rec.priority === 'high' ? '🟠' : '🟡';
console.log(`${icon} [${rec.type}] ${rec.message}`);
}
}
console.log('\n' + '='.repeat(80));
}
/**
* Clean up and save final data
*/
async cleanup() {
this.stopAutoSave();
await this.save();
}
}
// CLI for testing
if (require.main === module) {
const telemetry = new TelemetryAnalytics({ verbose: true });
// Simulate usage
console.log('Simulating telemetry collection...\n');
// Agent usage
telemetry.trackAgentUsage('react-developer', 'create_component', {
tokensUsed: 1200,
timeMs: 3000
});
telemetry.trackAgentUsage('node-backend-developer', 'implement_api', {
tokensUsed: 1800,
timeMs: 5000
});
// File access
telemetry.trackFileAccess('core-principles.md', 'load', {
tokens: 5000,
agent: 'react-developer'
});
telemetry.trackFileAccess('core-principles.md', 'load', {
tokens: 5000,
agent: 'node-backend-developer'
});
// Token usage
telemetry.trackTokenUsage('architecture_phase', 4500, {
phase: 'architecture',
agent: 'solution-architect'
});
// Checkpoint
telemetry.trackCheckpoint('checkpoint-arch-001', 4500, 800, {
phase: 'architecture',
agent: 'solution-architect'
});
// Decision
telemetry.trackDecision('technology', 'Next.js', {
agent: 'solution-architect',
alternatives: ['Gatsby', 'Vite'],
confidence: 0.9
});
// Error
telemetry.trackError('api_error', 'Failed to connect to database', {
agent: 'node-backend-developer',
severity: 'high'
});
// Generate report
telemetry.generateReport();
// Save and cleanup
telemetry.cleanup().then(() => {
console.log('\nTelemetry data saved successfully.');
});
}
module.exports = TelemetryAnalytics;

View File

@ -0,0 +1,401 @@
#!/usr/bin/env node
/**
* Automated Token Counter for BMAD Context Management
* Estimates token count for files and provides real-time context budget tracking
*
* Usage:
* node token-counter.js <file-or-directory>
* node token-counter.js --watch <directory>
* node token-counter.js --budget 5000 <files...>
*/
const fs = require('fs');
const path = require('path');
// Token estimation constants (based on GPT/Claude tokenization patterns)
const TOKENS_PER_WORD = 1.3;
const TOKENS_PER_CODE_LINE = 20;
const TOKENS_PER_MARKDOWN_LINE = 15;
class TokenCounter {
constructor(options = {}) {
this.budget = options.budget || null;
this.verbose = options.verbose || false;
this.watch = options.watch || false;
this.totalTokens = 0;
this.fileStats = [];
}
/**
* Estimate tokens for text content
*/
estimateTokens(content, filename = '') {
const ext = path.extname(filename).toLowerCase();
// Different estimation strategies based on file type
if (['.js', '.ts', '.jsx', '.tsx', '.py', '.java'].includes(ext)) {
return this.estimateCodeTokens(content);
} else if (['.md', '.mdx'].includes(ext)) {
return this.estimateMarkdownTokens(content);
} else if (['.json', '.yaml', '.yml'].includes(ext)) {
return this.estimateStructuredTokens(content);
} else {
return this.estimateTextTokens(content);
}
}
/**
* Estimate tokens for plain text
*/
estimateTextTokens(content) {
// Count words (split by whitespace and punctuation)
const words = content.match(/\b\w+\b/g) || [];
const wordTokens = words.length * TOKENS_PER_WORD;
// Add overhead for punctuation and formatting
const overhead = content.length * 0.05;
return Math.ceil(wordTokens + overhead);
}
/**
* Estimate tokens for code files
*/
estimateCodeTokens(content) {
const lines = content.split('\n');
let tokens = 0;
for (const line of lines) {
const trimmed = line.trim();
// Skip empty lines and single-char lines
if (trimmed.length <= 1) {
tokens += 1;
}
// Comments get fewer tokens
else if (trimmed.startsWith('//') || trimmed.startsWith('#')) {
tokens += trimmed.length * 0.3;
}
// Import statements are compact
else if (trimmed.startsWith('import') || trimmed.startsWith('require')) {
tokens += 10;
}
// Regular code lines
else {
tokens += TOKENS_PER_CODE_LINE;
}
}
return Math.ceil(tokens);
}
/**
* Estimate tokens for Markdown files
*/
estimateMarkdownTokens(content) {
const lines = content.split('\n');
let tokens = 0;
let inCodeBlock = false;
for (const line of lines) {
// Code block detection
if (line.trim().startsWith('```')) {
inCodeBlock = !inCodeBlock;
tokens += 3;
continue;
}
if (inCodeBlock) {
tokens += TOKENS_PER_CODE_LINE;
} else {
// Headers are more compact
if (line.match(/^#+\s/)) {
tokens += line.length * 0.8;
}
// Lists are slightly compact
else if (line.match(/^[\*\-\+]\s/) || line.match(/^\d+\.\s/)) {
tokens += line.length * 0.9;
}
// Regular markdown text
else {
tokens += TOKENS_PER_MARKDOWN_LINE;
}
}
}
return Math.ceil(tokens);
}
/**
* Estimate tokens for structured data (JSON/YAML)
*/
estimateStructuredTokens(content) {
// Structured data is more compact than plain text
const chars = content.length;
const lines = content.split('\n').length;
// Estimate based on character count and structure
const charTokens = chars * 0.2;
const lineTokens = lines * 3;
return Math.ceil(Math.max(charTokens, lineTokens));
}
/**
* Count tokens in a file
*/
async countFile(filepath) {
try {
const content = fs.readFileSync(filepath, 'utf-8');
const tokens = this.estimateTokens(content, filepath);
const stats = {
file: path.basename(filepath),
path: filepath,
size: content.length,
lines: content.split('\n').length,
tokens: tokens,
tokensPerLine: Math.round(tokens / content.split('\n').length)
};
this.fileStats.push(stats);
this.totalTokens += tokens;
return stats;
} catch (error) {
console.error(`Error reading ${filepath}:`, error.message);
return null;
}
}
/**
* Count tokens in directory recursively
*/
async countDirectory(dirpath, pattern = '*') {
const files = this.getFiles(dirpath, pattern);
for (const file of files) {
await this.countFile(file);
}
return this.fileStats;
}
/**
* Get all files matching pattern
*/
getFiles(dirpath, pattern = '*') {
const files = [];
function walk(dir) {
const items = fs.readdirSync(dir);
for (const item of items) {
const fullPath = path.join(dir, item);
const stat = fs.statSync(fullPath);
if (stat.isDirectory() && !item.startsWith('.') && item !== 'node_modules') {
walk(fullPath);
} else if (stat.isFile()) {
// Simple pattern matching
if (pattern === '*' || fullPath.includes(pattern)) {
files.push(fullPath);
}
}
}
}
walk(dirpath);
return files;
}
/**
* Generate budget status with color codes
*/
getBudgetStatus() {
if (!this.budget) return '';
const percentage = (this.totalTokens / this.budget) * 100;
let status, color, emoji;
if (percentage < 50) {
status = 'GREEN';
color = '\x1b[32m'; // Green
emoji = '🟢';
} else if (percentage < 75) {
status = 'YELLOW';
color = '\x1b[33m'; // Yellow
emoji = '🟡';
} else if (percentage < 90) {
status = 'ORANGE';
color = '\x1b[38;5;208m'; // Orange
emoji = '🟠';
} else {
status = 'RED';
color = '\x1b[31m'; // Red
emoji = '🔴';
}
const reset = '\x1b[0m';
return `${color}${emoji} ${status} (${percentage.toFixed(1)}% of budget)${reset}`;
}
/**
* Print report
*/
printReport() {
console.log('\n' + '='.repeat(80));
console.log('TOKEN COUNT REPORT');
console.log('='.repeat(80));
if (this.verbose) {
console.log('\nDETAILED FILE ANALYSIS:');
console.log('-'.repeat(80));
// Sort by token count
const sorted = [...this.fileStats].sort((a, b) => b.tokens - a.tokens);
for (const stat of sorted) {
console.log(`\n📄 ${stat.file}`);
console.log(` Path: ${stat.path}`);
console.log(` Lines: ${stat.lines} | Size: ${stat.size} bytes`);
console.log(` Tokens: ~${stat.tokens} (${stat.tokensPerLine} per line avg)`);
}
} else {
console.log('\nTOP 10 FILES BY TOKEN COUNT:');
console.log('-'.repeat(80));
const top10 = [...this.fileStats]
.sort((a, b) => b.tokens - a.tokens)
.slice(0, 10);
for (const stat of top10) {
const bar = '█'.repeat(Math.floor(stat.tokens / 100));
console.log(`${stat.file.padEnd(40)} ${String(stat.tokens).padStart(6)} tokens ${bar}`);
}
}
console.log('\n' + '='.repeat(80));
console.log('SUMMARY:');
console.log('-'.repeat(80));
console.log(`Total Files: ${this.fileStats.length}`);
console.log(`Total Tokens: ~${this.totalTokens}`);
if (this.budget) {
console.log(`Token Budget: ${this.budget}`);
console.log(`Budget Status: ${this.getBudgetStatus()}`);
console.log(`Remaining: ${Math.max(0, this.budget - this.totalTokens)} tokens`);
}
console.log('\nRECOMMENDATIONS:');
if (this.totalTokens > 5000) {
console.log('⚠️ Consider creating checkpoints to compress context');
}
if (this.fileStats.some(f => f.tokens > 1500)) {
console.log('⚠️ Some files exceed 1500 tokens - consider splitting or section loading');
}
console.log('='.repeat(80));
}
/**
* Watch mode - monitor directory for changes
*/
watchDirectory(dirpath) {
console.log(`Watching ${dirpath} for changes...`);
const recalculate = () => {
this.totalTokens = 0;
this.fileStats = [];
this.countDirectory(dirpath).then(() => {
console.clear();
this.printReport();
console.log('\n👁 Watching for changes... (Ctrl+C to exit)');
});
};
recalculate();
fs.watch(dirpath, { recursive: true }, (eventType, filename) => {
if (filename && !filename.includes('node_modules')) {
console.log(`Change detected in ${filename}`);
setTimeout(recalculate, 100);
}
});
}
}
// CLI Interface
function main() {
const args = process.argv.slice(2);
if (args.length === 0 || args.includes('--help')) {
console.log(`
Token Counter - Estimate token usage for BMAD context management
Usage:
node token-counter.js <file-or-directory> Count tokens
node token-counter.js --budget <N> <files...> Count with budget
node token-counter.js --watch <directory> Watch mode
node token-counter.js --verbose <file/dir> Detailed output
Examples:
node token-counter.js agents/ Count all agent files
node token-counter.js --budget 5000 data/ Check data files against budget
node token-counter.js --watch . Monitor current directory
Token Estimation:
- Plain text: ~1.3 tokens per word
- Code: ~20 tokens per line
- Markdown: ~15 tokens per line
- JSON/YAML: ~0.2 tokens per character
`);
return;
}
const options = {
budget: null,
verbose: args.includes('--verbose'),
watch: args.includes('--watch')
};
// Parse budget
const budgetIndex = args.indexOf('--budget');
if (budgetIndex !== -1 && args[budgetIndex + 1]) {
options.budget = parseInt(args[budgetIndex + 1]);
args.splice(budgetIndex, 2);
}
// Remove flags
const paths = args.filter(arg => !arg.startsWith('--'));
const counter = new TokenCounter(options);
// Process paths
for (const p of paths) {
const fullPath = path.resolve(p);
if (fs.existsSync(fullPath)) {
const stat = fs.statSync(fullPath);
if (options.watch && stat.isDirectory()) {
counter.watchDirectory(fullPath);
return; // Watch mode runs indefinitely
} else if (stat.isDirectory()) {
counter.countDirectory(fullPath).then(() => counter.printReport());
} else {
counter.countFile(fullPath).then(() => counter.printReport());
}
} else {
console.error(`Path not found: ${p}`);
}
}
}
// Run if executed directly
if (require.main === module) {
main();
}
module.exports = TokenCounter;

View File

@ -0,0 +1,162 @@
# BMAD JavaScript Fullstack - Workflow Index
## 🚀 Quick Start
Choose your workflow in 30 seconds:
```
Q: Do you have existing code?
├─ NO → Use: greenfield-new-project.yaml
└─ YES → Q: Is it modernized?
├─ NO → Use: brownfield-modernize-existing.yaml
└─ YES → Q: What do you need?
├─ Add features → Use: feature-addition.yaml
└─ Fix/update → Use: maintenance-fixes-updates.yaml
```
## 📋 The 4 Workflows
### 1. [greenfield-new-project.yaml](greenfield-new-project.yaml)
**When**: Starting a brand new project from scratch
**Time**: 5-7 days (MVP) | 2-4 weeks (Production)
**Output**: Deployed application with core features
**Use for**:
- New startup MVP
- New product launch
- Greenfield enterprise project
- Fresh start with best practices
---
### 2. [brownfield-modernize-existing.yaml](brownfield-modernize-existing.yaml)
**When**: You have legacy/existing code that needs modernization
**Time**: 3-5 days
**Output**: Modernized, standardized, feature-ready codebase
**Use for**:
- Legacy JavaScript codebase
- Unstructured existing project
- Code without tests/standards
- Technical debt cleanup
---
### 3. [feature-addition.yaml](feature-addition.yaml)
**When**: Adding features to ANY established project
**Time**: 2 hours - 10 days (based on size)
**Output**: New feature deployed to production
**Size Guide**:
- **Small** (1-2 days): 1-3 files, existing patterns
- **Medium** (2-5 days): 4-10 files, some new patterns
- **Large** (5-10 days): 10+ files, new architecture
**Use for**:
- Adding authentication
- Payment integration
- New pages/components
- API endpoints
- Any feature addition
---
### 4. [maintenance-fixes-updates.yaml](maintenance-fixes-updates.yaml)
**When**: Bug fixes, updates, optimization, refactoring
**Time**: 2 hours - 3 days
**Output**: Issue resolved and deployed
**Types**:
- **Bug Fix** (2-8 hours): Reproduce → Fix → Deploy
- **Dependencies** (1-4 hours): Audit → Update → Deploy
- **Performance** (1-3 days): Profile → Optimize → Validate
- **Refactoring** (1-5 days): Plan → Refactor → Verify
- **Security** (2-8 hours, URGENT): Assess → Patch → Deploy
---
## 🎯 Common Scenarios
| Scenario | Workflow | File |
|----------|----------|------|
| "I have a business idea" | Greenfield | [greenfield-new-project.yaml](greenfield-new-project.yaml) |
| "I inherited legacy code" | Brownfield | [brownfield-modernize-existing.yaml](brownfield-modernize-existing.yaml) |
| "Add login to my app" | Feature (Medium) | [feature-addition.yaml](feature-addition.yaml) |
| "Add dark mode toggle" | Feature (Small) | [feature-addition.yaml](feature-addition.yaml) |
| "Build chat feature" | Feature (Large) | [feature-addition.yaml](feature-addition.yaml) |
| "Fix production bug" | Maintenance (Bug) | [maintenance-fixes-updates.yaml](maintenance-fixes-updates.yaml) |
| "Update dependencies" | Maintenance (Deps) | [maintenance-fixes-updates.yaml](maintenance-fixes-updates.yaml) |
| "App is slow" | Maintenance (Perf) | [maintenance-fixes-updates.yaml](maintenance-fixes-updates.yaml) |
| "Clean up messy code" | Maintenance (Refactor) | [maintenance-fixes-updates.yaml](maintenance-fixes-updates.yaml) |
## 📊 Token Budgets
| Workflow | Min Tokens | Max Tokens | Avg Tokens |
|----------|------------|------------|------------|
| Greenfield (MVP) | 10,000 | 15,000 | 12,000 |
| Greenfield (Prod) | 15,000 | 25,000 | 20,000 |
| Brownfield | 7,000 | 10,000 | 8,500 |
| Feature (Small) | 3,000 | 6,000 | 4,500 |
| Feature (Medium) | 6,000 | 10,000 | 8,000 |
| Feature (Large) | 10,000 | 15,000 | 12,000 |
| Maintenance | 500 | 5,000 | 1,500 |
## 🔄 Workflow Progression
Typical project lifecycle:
```
1. Start: greenfield-new-project.yaml
2. Build MVP (5-7 days)
3. Add Features: feature-addition.yaml
4. Maintain: maintenance-fixes-updates.yaml
5. More Features: feature-addition.yaml
(Repeat 3-5 as needed)
```
Or for existing code:
```
1. Start: brownfield-modernize-existing.yaml
2. Modernize (3-5 days)
3. Add Features: feature-addition.yaml
4. Maintain: maintenance-fixes-updates.yaml
(Repeat 3-4 as needed)
```
## 📚 Documentation
- **[README.md](README.md)** - Overview and quick reference
- **[WORKFLOW-SYSTEM.md](WORKFLOW-SYSTEM.md)** - Detailed system documentation
- **This file (INDEX.md)** - Quick navigation
## 🚦 Getting Started
1. **Read this index** to understand the 4 workflows
2. **Choose your workflow** based on your situation
3. **Open the YAML file** and follow the phases
4. **Track tokens** and create checkpoints as specified
5. **Use parallel execution** when indicated
## ✅ Workflow Selection Checklist
Before starting, answer these:
- [ ] Do I have existing code? (Yes = Brownfield, No = Greenfield)
- [ ] Is my code modernized? (No = Brownfield first)
- [ ] Am I adding a feature? (Yes = Feature workflow)
- [ ] Am I fixing/optimizing? (Yes = Maintenance workflow)
- [ ] Have I estimated feature size? (Small/Medium/Large)
- [ ] Do I know my token budget?
- [ ] Have I identified parallel opportunities?
---
**Need help? Start with [README.md](README.md) for detailed guidance.**

View File

@ -1,48 +0,0 @@
# <!-- Powered by BMAD™ Core -->
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

View File

@ -0,0 +1,293 @@
# Brownfield Setup Workflow
workflow:
id: brownfield-setup
name: Modernize & Standardize Existing JavaScript/TypeScript Project
description: Take legacy/existing code and prepare it for modern development
duration: 3-5 days
token_budget: 8500
# PHASE 1: Assessment (Day 1)
assessment:
agent: js-solution-architect + analyst
duration: 4-8 hours
tokens: 2000
analyze:
code_quality:
- Run ESLint analysis
- Check TypeScript coverage
- Identify code smells
- Measure technical debt
dependencies:
- Run npm/yarn audit
- Check outdated packages
- Identify security vulnerabilities
- Review bundle size
infrastructure:
- Current build process
- Deployment method
- Environment management
- CI/CD status
testing:
- Current test coverage
- Test framework status
- E2E test presence
- Manual testing process
outputs:
- assessment-report.md
- technical-debt-list.md
- security-vulnerabilities.md
- modernization-opportunities.md
red_flags:
critical:
- No version control
- Exposed secrets in code
- SQL injection vulnerabilities
- No authentication
high:
- No TypeScript
- No tests
- Outdated framework (>2 major versions)
- No error handling
medium:
- Poor code organization
- No documentation
- Mixed coding styles
- No CI/CD
# PHASE 2: Modernization Plan (Day 1 Afternoon)
planning:
agent: js-solution-architect
duration: 2-4 hours
tokens: 1000
prioritization:
immediate: # Must fix now
- Security vulnerabilities
- Breaking bugs
- Critical dependencies
short_term: # This sprint
- Add TypeScript
- Setup testing
- Standardize code style
- Basic CI/CD
long_term: # Future sprints
- Architecture refactoring
- Performance optimization
- Advanced testing
- Full migration
decisions:
typescript:
add_now: If no TypeScript at all
gradual: If partial TypeScript
skip: If already full TypeScript
testing:
start_with: Critical business logic
framework: Vitest or Jest
target: 50% coverage initially
refactoring:
approach: Incremental, not rewrite
focus: High-traffic code first
rule: Don't break existing functionality
outputs:
- modernization-plan.md
- priority-matrix.md
- migration-timeline.md
checkpoint:
name: brownfield-plan-checkpoint.md
max_tokens: 400
# PHASE 3: Setup Standards (Day 2)
standardization:
duration: 4-8 hours
tokens: 1500
parallel_tasks:
track_1:
agent: typescript-expert
tasks:
- Setup TypeScript config
- Add type definitions
- Configure path aliases
- Create shared types
track_2:
agent: node-backend-developer
tasks:
- Setup ESLint + Prettier
- Configure pre-commit hooks
- Standardize project structure
- Update package.json scripts
track_3:
agent: devops
tasks:
- Setup/fix CI/CD pipeline
- Configure environment management
- Add automated testing
- Setup deployment process
configs_to_add:
required:
- tsconfig.json
- .eslintrc.js
- .prettierrc
- .gitignore
- .env.example
recommended:
- .husky (pre-commit hooks)
- .github/workflows
- docker-compose.yml
- jest.config.js
outputs:
- Standardized configuration
- Updated dependencies
- Development guide
- Updated README
# PHASE 4: Critical Refactoring (Days 3-4)
refactoring:
duration: 1-3 days
tokens: 3000
priority_order:
1_security:
- Fix authentication issues
- Sanitize inputs
- Update vulnerable dependencies
- Remove hardcoded secrets
2_stability:
- Fix breaking bugs
- Add error boundaries
- Handle edge cases
- Fix memory leaks
3_performance:
- Optimize database queries
- Fix N+1 problems
- Add caching layer
- Optimize bundle size
4_maintainability:
- Extract reusable components
- Standardize API responses
- Consolidate duplicate code
- Improve naming conventions
rules:
- Test before and after changes
- Commit frequently
- Document breaking changes
- Keep backward compatibility
- Create migration guides
outputs:
- Refactored codebase
- Migration notes
- Test results
- Performance metrics
# PHASE 5: Integration & Validation (Day 5)
validation:
agent: qa-engineer + developers
duration: 4-8 hours
tokens: 1000
verify:
functionality:
- All features still work
- No new bugs introduced
- Performance not degraded
- User experience maintained
standards:
- TypeScript compiles
- ESLint passes
- Tests pass
- Build succeeds
deployment:
- CI/CD pipeline works
- Deployment successful
- Monitoring active
- Rollback possible
outputs:
- validation-report.md
- test-coverage-report.html
- ready-for-features.md
# Post-Setup: Ready for Feature Development
next_steps:
immediate:
- Start using Feature Addition workflow
- Begin adding new features
- Continue incremental improvements
ongoing:
- Gradually increase test coverage
- Refactor remaining technical debt
- Update documentation
- Train team on new standards
# Common Scenarios & Solutions
scenarios:
no_typescript:
solution: Add TS config, rename files gradually
timeline: 1-2 weeks for full migration
no_tests:
solution: Start with critical paths, aim for 50%
timeline: Add tests with each new feature
outdated_react:
solution: Incremental upgrade, fix deprecations
timeline: 1 version at a time
jquery_legacy:
solution: Gradual replacement with React
timeline: Component by component
monolithic_code:
solution: Extract modules incrementally
timeline: Ongoing refactoring
# Success Criteria
success_metrics:
required:
- No critical vulnerabilities
- Basic tests running
- CI/CD functional
- TypeScript configured
recommended:
- 50%+ test coverage
- All dependencies updated
- Documentation current
- Performance improved
# Deliverables
deliverables:
- [ ] Assessment report
- [ ] Modernization plan
- [ ] Updated codebase
- [ ] Standard configurations
- [ ] Test suite
- [ ] CI/CD pipeline
- [ ] Development guide
- [ ] Ready for features

View File

@ -0,0 +1,396 @@
# Feature Addition Workflow
workflow:
id: feature-addition
name: Add Feature to Existing Project
description: Works for both greenfield and brownfield projects
duration: 2-10 days (based on size)
token_budget: 4500 (small) | 8000 (medium) | 12000 (large)
# SIZE ESTIMATION (30 minutes)
sizing:
agent: analyst + architect
duration: 30 minutes
tokens: 500
size_definitions:
small:
effort: 1-2 days
files: 1-3 files changed
complexity: Using existing patterns
examples:
- Add new field to form
- Create new page with CRUD
- Add filter to list
- Update UI component
medium:
effort: 2-5 days
files: 4-10 files changed
complexity: Some new patterns
examples:
- Payment integration
- Email notifications
- File upload system
- Advanced filtering
large:
effort: 5-10 days
files: 10+ files changed
complexity: New architecture
examples:
- Multi-step wizard
- Real-time collaboration
- Advanced analytics
- Complex workflow
decision:
small: Skip to implementation
medium: Do quick design
large: Full design phase
# SMALL FEATURE (Skip most phases)
small_feature:
duration: 1-2 days
tokens: 4500
quick_analysis:
agent: appropriate-developer
duration: 1 hour
outputs:
- feature-brief.md (1 page max)
checklist:
- [ ] What changes are needed?
- [ ] Which files to modify?
- [ ] Any API changes?
- [ ] Test strategy?
implementation:
agent: appropriate-developer
duration: 4-12 hours
tasks:
- Make code changes
- Add/update tests
- Update documentation
- Manual testing
outputs:
- Working feature
- Updated tests
deployment:
duration: 1 hour
tasks:
- Code review
- Merge to main
- Deploy to production
# MEDIUM FEATURE
medium_feature:
duration: 2-5 days
tokens: 8000
# Phase 1: Analysis (2-4 hours)
analysis:
agent: analyst + architect
duration: 2-4 hours
tokens: 1000
outputs:
- feature-requirements.md
- impact-analysis.md
analyze:
- Detailed requirements
- Affected components
- API changes needed
- Database schema updates
- Integration points
- Risks and dependencies
# Phase 2: Design (2-4 hours)
design:
agent: appropriate-specialist
duration: 2-4 hours
tokens: 1500
outputs:
- technical-design.md
- api-changes.yaml (if backend)
- component-plan.md (if frontend)
design_elements:
- API contracts
- Component structure
- State management
- Database changes
- Error handling
checkpoint:
name: feature-design-checkpoint.md
max_tokens: 300
# Phase 3: Implementation (2-5 days)
implementation:
agent: developers
duration: 2-5 days
tokens: 4000
parallel_tracks:
frontend:
- Build UI components
- Implement state logic
- Add form validation
- Style components
backend:
- Create API endpoints
- Update database schema
- Add business logic
- Handle errors
testing:
- Unit tests
- Integration tests
- Manual QA
checkpoints:
frequency: Daily
max_tokens: 200 each
# Phase 4: Testing & Deployment (4-8 hours)
release:
duration: 4-8 hours
tokens: 1500
tasks:
- Code review
- Final QA
- Deploy to staging
- Smoke test
- Deploy to production
- Monitor metrics
# LARGE FEATURE
large_feature:
duration: 5-10 days
tokens: 12000
# Phase 1: Requirements (4-8 hours)
requirements:
agent: analyst
duration: 4-8 hours
tokens: 1500
outputs:
- detailed-requirements.md
- user-stories.md (5-10 stories)
- acceptance-criteria.md
- success-metrics.md
# Phase 2: Architecture Review (4 hours)
architecture:
agent: js-solution-architect
duration: 4 hours
tokens: 2000
load:
jit:
- IF new_patterns: architecture-patterns.md
- IF security: security-guidelines.md
- IF complex_api: api-implementation-patterns.md
outputs:
- architecture-impact.md
- integration-plan.md
- risk-mitigation.md
checkpoint:
name: architecture-impact-checkpoint.md
max_tokens: 400
# Phase 3: Design (1 day)
design:
agent: team-leads
duration: 1 day
tokens: 2500
parallel_design:
frontend:
- Component hierarchy
- State architecture
- Routing changes
- UI/UX flow
backend:
- API specification
- Database schema
- Service architecture
- Integration design
infrastructure:
- Performance requirements
- Scaling strategy
- Monitoring plan
outputs:
- frontend-design.md
- backend-design.md
- infrastructure-plan.md
checkpoint:
name: detailed-design-checkpoint.md
max_tokens: 500
# Phase 4: Story Creation (2 hours)
stories:
agent: scrum-master
duration: 2 hours
tokens: 1000
outputs:
- implementation-stories.md (5-10 stories)
- sprint-plan.md
story_types:
- Database migrations
- Backend API endpoints
- Frontend components
- Integration work
- Testing & QA
# Phase 5: Implementation (5-10 days)
implementation:
duration: 5-10 days
tokens: 4000
parallel_teams:
ui_team:
- Build component library
- Implement pages
- Add interactions
api_team:
- Create endpoints
- Add validation
- Implement business logic
data_team:
- Schema migrations
- Data transformations
- Database optimization
qa_team:
- Write test cases
- Automated testing
- Manual QA
daily_checkpoints:
- Progress report
- Blocker resolution
- Integration status
# Phase 6: Integration & Release (1-2 days)
release:
duration: 1-2 days
tokens: 1000
phases:
integration:
- Merge feature branches
- Integration testing
- Performance testing
- Security review
deployment:
- Deploy to staging
- User acceptance testing
- Production deployment
- Post-deployment monitoring
# FEATURE-SPECIFIC PATTERNS
patterns:
authentication_feature:
components:
- Login/register forms
- Auth context/provider
- Protected routes
- Session management
backend:
- Auth endpoints
- JWT middleware
- Password hashing
- Refresh token logic
payment_integration:
components:
- Checkout flow
- Payment forms
- Order confirmation
backend:
- Stripe/payment integration
- Webhook handlers
- Order processing
- Receipt generation
real_time_feature:
components:
- WebSocket client
- Real-time updates
- Optimistic UI
backend:
- WebSocket server
- Event broadcasting
- State synchronization
file_upload:
components:
- Upload UI
- Progress tracking
- File preview
backend:
- Upload endpoints
- S3/storage integration
- File validation
# COMMON DECISIONS
decisions:
new_dependencies:
evaluate:
- Bundle size impact
- Maintenance status
- License compatibility
- Security record
approval: Tech lead required
database_changes:
approach:
- Write migration scripts
- Test rollback
- Plan zero-downtime deployment
backup: Always before schema changes
breaking_changes:
process:
- Document clearly
- Version API
- Provide migration guide
- Deprecation period
# SUCCESS CRITERIA
success_metrics:
small:
- Feature works as expected
- Tests pass
- Code reviewed
- Deployed to production
medium:
- All acceptance criteria met
- Test coverage adequate
- Performance acceptable
- Documentation updated
large:
- All stories complete
- Full test coverage
- Performance validated
- User acceptance passed
- Monitoring in place
# DELIVERABLES
deliverables:
code:
- [ ] Feature implementation
- [ ] Unit tests
- [ ] Integration tests
- [ ] Updated types/interfaces
documentation:
- [ ] Feature documentation
- [ ] API documentation (if applicable)
- [ ] Migration guide (if breaking)
- [ ] Updated README
deployment:
- [ ] Deployed to production
- [ ] Monitoring configured
- [ ] Rollback plan documented
# QUICK REFERENCE
quick_start:
step_1: Estimate feature size (small/medium/large)
step_2: Follow appropriate workflow path
step_3: Use parallel development when possible
step_4: Checkpoint daily for medium/large features
step_5: Deploy incrementally if possible

View File

@ -1,110 +0,0 @@
# <!-- Powered by BMAD™ Core -->
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
context_budget: 1500-2500 tokens
loads_if_needed:
- security-guidelines.md
WHEN: Feature involves authentication, authorization, user data, or sensitive information
WHY: Need security patterns for auth flows, data protection, and input validation
TOKENS: ~1000
- best-practices.md
WHEN: Feature introduces new architectural patterns not in existing codebase
WHY: Ensure new patterns align with team standards and best practices
TOKENS: ~800
SKIP_IF: Using existing patterns only
- architecture-patterns.md
WHEN: Feature requires significant architectural changes (new service, major refactor)
WHY: Need pattern guidance for structural changes
TOKENS: ~1200
SKIP_IF: Simple addition to existing architecture
notes: |
Assess technical impact on existing architecture. Identify affected components, database changes, API modifications, and integration points.
DEFAULT LOAD: core-principles.md + feature-requirements.md + existing architecture checkpoint (~800 tokens)
JIT LOAD: Only load guides when making specific decisions about security, patterns, or architecture changes.
- agent: js-solution-architect
action: create_checkpoint
uses: create-checkpoint-summary task
creates: architecture-impact-checkpoint.md
requires: technical_impact_review
notes: "Compact technical impact analysis into checkpoint: selected approach, affected components, risks, and constraints. Max 100 lines. SAVE to docs/features/[feature-name]/checkpoints/"
- agent: react-developer OR node-backend-developer OR api-developer
creates: technical-specification.md
requires:
- feature-requirements.md
- architecture-impact-checkpoint.md
context_budget: 1000-1500 tokens
loads_if_needed:
- component-design-guidelines.md (react-developer)
WHEN: Building complex reusable component (compound components, render props, custom hooks)
WHY: Need advanced component patterns
TOKENS: ~600
SKIP_IF: Simple component using standard patterns
- state-management-guide.md (react-developer)
WHEN: Choosing state solution for new feature (useState vs Zustand vs Redux vs React Query)
WHY: Need state management decision framework
TOKENS: ~800
SKIP_IF: State pattern already defined in architecture
- security-guidelines.md (node-backend-developer)
WHEN: Implementing auth endpoints or handling sensitive data
WHY: Need auth patterns and security best practices
TOKENS: ~1000
SKIP_IF: Standard CRUD endpoints
- api-implementation-patterns.md (api-developer, node-backend-developer)
WHEN: Implementing specific API type (REST/GraphQL/tRPC) - load relevant section only
WHY: Need implementation details for chosen API style
TOKENS: ~200-300 per section
SKIP_IF: Following existing API patterns in codebase
notes: |
Create detailed technical spec with file changes, new components/endpoints, types, tests, and implementation steps.
DEFAULT LOAD: checkpoint + requirements (~1000 tokens)
JIT LOAD: Role-specific guides only when making new decisions. SAVE to docs/features/[feature-name]/
- agent: sm
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.
- agent: sm
action: create_checkpoint
uses: create-checkpoint-summary task
creates: implementation-checkpoint.md
requires: feature-stories.md
notes: "Compact planning phase into checkpoint: story priorities, effort estimates, dependencies, and critical DoD criteria. Archive verbose specs. Max 100 lines. SAVE to docs/features/[feature-name]/checkpoints/"
workflow_end:
action: begin_feature_implementation
notes: Feature planning complete with compact checkpoint. Developers reference implementation-checkpoint.md + stories for context-efficient implementation.
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

View File

@ -1,41 +0,0 @@
# <!-- Powered by BMAD™ Core -->
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

View File

@ -1,288 +0,0 @@
# <!-- Powered by BMAD™ Core -->
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
context_budget: 2000-3000 tokens
loads_if_needed:
- technology-stack-guide.md
WHEN: ALWAYS (making stack decisions)
WHY: Need framework comparisons, decision criteria, and stack recommendations
TOKENS: ~1500
NOTE: This is the core decision guide for greenfield projects
- deployment-strategies.md
WHEN: Requirements specify hosting/deployment needs OR choosing deployment approach
WHY: Need hosting platform comparison and deployment pattern guidance
TOKENS: ~500
SKIP_IF: Deployment decision deferred to later phase
- security-guidelines.md
WHEN: Requirements involve authentication, user data, PII, payments, or compliance
WHY: Need security architecture patterns for sensitive data handling
TOKENS: ~1000
SKIP_IF: No sensitive data or auth requirements
- architecture-patterns.md
WHEN: Complex requirements suggesting microservices, event-driven, or non-standard patterns
WHY: Need pattern comparison for architectural style selection
TOKENS: ~1200
SKIP_IF: Standard monolith or JAMstack pattern sufficient
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.
DEFAULT LOAD: requirements-analysis.md + core-principles.md (~800 tokens)
REQUIRED LOAD: technology-stack-guide.md (core decision guide)
JIT LOAD: deployment-strategies.md, security-guidelines.md, architecture-patterns.md based on requirements
SAVE OUTPUT: Copy to docs/architecture/ folder.
- agent: js-solution-architect
action: create_checkpoint
uses: create-checkpoint-summary task
creates: stack-selection-checkpoint.md
requires: technology-stack-decision.md
notes: "Compact stack selection into checkpoint: chosen technologies, key rationale, and constraints. Max 100 lines. SAVE to docs/checkpoints/"
- agent: js-solution-architect
creates: system-architecture.md
requires:
- requirements-analysis.md
- stack-selection-checkpoint.md
context_budget: 1500-2500 tokens
loads_if_needed:
- architecture-patterns.md
WHEN: Designing specific architecture pattern (microservices, event-driven, CQRS, etc.)
WHY: Need detailed pattern guidance for chosen architectural style
TOKENS: ~1200
SKIP_IF: Simple monolith or standard JAMstack - use role knowledge
- security-guidelines.md
WHEN: Designing auth system, RBAC, or security-critical features
WHY: Need security architecture patterns and best practices
TOKENS: ~1000
SKIP_IF: No auth or minimal security requirements (defer to implementation)
- database-design-patterns.md
WHEN: Complex data model with many relationships, or choosing SQL vs NoSQL
WHY: Need schema design patterns and database selection criteria
TOKENS: ~800
SKIP_IF: Simple CRUD schema - use role knowledge
- api-implementation-patterns.md
WHEN: Defining API contracts and need specific implementation guidance
WHY: Need API design patterns for REST/GraphQL/tRPC
TOKENS: ~300-500 per section
SKIP_IF: API design delegated to api-developer agent
optional_steps:
- architecture_patterns_review
- security_architecture
- performance_planning
notes: |
Design complete system architecture including frontend, backend, database schema, API contracts, and deployment strategy.
DEFAULT LOAD: stack-selection-checkpoint.md + requirements (~1000 tokens)
JIT LOAD: Pattern/security/database guides only when designing those specific aspects
TARGET: Keep under 2500 tokens by loading sections, not full files
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.
- agent: js-solution-architect
action: create_checkpoint
uses: create-checkpoint-summary task
creates: architecture-complete-checkpoint.md
requires: system-architecture.md
condition: architecture_validated
notes: "Compact architecture phase into checkpoint: key architectural decisions, selected patterns, critical constraints, and setup requirements. Archive detailed analysis. Max 100 lines. SAVE to docs/checkpoints/"
project_setup_guidance:
action: initialize_project_structure
requires: architecture-complete-checkpoint.md
notes: "Set up project following checkpoint summary and 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 phase complete with compact checkpoint. Developers reference architecture-complete-checkpoint.md for context-efficient story development.
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.
- agent: js-solution-architect
action: create_checkpoint
uses: create-checkpoint-summary task
creates: mvp-checkpoint.md
requires: mvp-architecture.md
notes: "Compact MVP planning into checkpoint: core feature scope, minimal tech stack, and rapid implementation approach. Max 50 lines for lean MVP context. SAVE to docs/checkpoints/"
mvp_workflow_end:
action: rapid_implementation
notes: MVP scope defined with compact checkpoint. Developers reference mvp-checkpoint.md for lean, context-efficient rapid implementation.
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

View File

@ -0,0 +1,214 @@
# Greenfield Project Workflow
workflow:
id: greenfield-project
name: Start New JavaScript/TypeScript Project
description: From zero to deployed application with core features
duration: 5-7 days (MVP) | 2-4 weeks (Production)
token_budget: 12000 (MVP) | 20000 (Production)
# PHASE 1: Requirements & Planning (Day 1 Morning)
requirements:
agent: analyst
duration: 2-4 hours
tokens: 1000
inputs:
- Business goals
- Target users
- Core problem
outputs:
- requirements.md
- user-stories.md
- success-metrics.md
checklist:
- [ ] Define 5-10 core features
- [ ] Prioritize features (MVP vs Future)
- [ ] Set success criteria
- [ ] Define constraints (budget, timeline)
# PHASE 2: Architecture & Tech Stack (Day 1 Afternoon)
architecture:
agent: js-solution-architect
duration: 4 hours
tokens: 3000
load:
- technology-stack-guide.md # Only guide needed
decisions:
frontend:
default: Next.js 14 # Full-stack, fast, production-ready
alternatives:
- Vite + React # If pure SPA needed
- Remix # If heavy server-side needed
backend:
default: Next.js API Routes # Simpler for most cases
alternatives:
- Express/Fastify # If separate backend needed
- NestJS # If enterprise patterns needed
database:
default: PostgreSQL + Prisma # Best for relational data
alternatives:
- Supabase # If need auth + realtime
- MongoDB # If document-based data
deployment:
default: Vercel # Zero-config for Next.js
alternatives:
- Railway/Fly.io # If need more control
- AWS # If enterprise requirements
outputs:
- architecture.md
- tech-stack.md
- database-schema.sql
- api-specification.yaml
checkpoint:
name: architecture-checkpoint.md
max_tokens: 500
includes:
- Tech stack choices
- Architecture diagram
- Key constraints
# PHASE 3: Project Setup (Day 2 Morning)
setup:
duration: 2-4 hours
tokens: 1500
parallel_execution:
track_1:
agent: node-backend-developer
tasks:
- Initialize Node.js project
- Setup TypeScript
- Configure database
- Create API structure
- Setup auth middleware
track_2:
agent: react-developer
tasks:
- Initialize Next.js/React
- Setup TypeScript
- Configure Tailwind CSS
- Create layout components
- Setup routing
track_3:
agent: devops
tasks:
- Initialize Git repository
- Setup GitHub Actions CI/CD
- Configure environment variables
- Create Docker setup (if needed)
outputs:
- Working project skeleton
- README.md
- Development environment
# PHASE 4: Core Features (Days 2-5)
core_features:
duration: 3-5 days
tokens: 5000-10000
mvp_features:
priority_1_auth: # Day 2 Afternoon
- User registration
- User login
- Password reset
- Session management
priority_2_core: # Days 3-4
- Primary business feature
- CRUD operations
- Basic admin panel
priority_3_polish: # Day 5
- Error handling
- Loading states
- Basic responsiveness
production_features: # Additional 1-2 weeks
- All MVP features +
- Payment integration
- Email notifications
- Advanced admin features
- Analytics integration
- Performance optimization
- Comprehensive testing
parallel_development:
- Frontend components
- Backend APIs
- Database migrations
- Unit tests
checkpoints:
frequency: Every 2 days
max_tokens: 500 each
# PHASE 5: Deployment (Day 5 Afternoon)
deployment:
agent: devops or senior-developer
duration: 2-4 hours
tokens: 1000
tasks:
production_setup:
- Configure production environment
- Setup domain and SSL
- Configure environment variables
- Setup monitoring (Sentry/LogRocket)
deployment:
- Deploy database migrations
- Deploy application
- Run smoke tests
- Verify production
outputs:
- Live application URL
- Deployment documentation
- Monitoring dashboard
# Success Criteria
success_metrics:
mvp:
- Core features working
- Deployed to production
- Basic documentation
- < 1 week delivery
production:
- All planned features complete
- Test coverage > 70%
- Performance targets met
- Full documentation
# Common Patterns & Decisions
patterns:
authentication:
recommended: NextAuth.js or Supabase Auth
custom_jwt: Only if specific requirements
state_management:
client: Zustand for simple, Redux Toolkit for complex
server: React Query/TanStack Query
styling:
recommended: Tailwind CSS
alternatives: CSS Modules, Styled Components
testing:
unit: Vitest
integration: Testing Library
e2e: Playwright
# Deliverables Checklist
deliverables:
code:
- [ ] Source code in Git
- [ ] TypeScript throughout
- [ ] Tests for critical paths
- [ ] Error handling
documentation:
- [ ] README with setup instructions
- [ ] API documentation
- [ ] Deployment guide
- [ ] Environment variables guide
deployment:
- [ ] Production URL
- [ ] CI/CD pipeline
- [ ] Monitoring setup
- [ ] Backup strategy

View File

@ -0,0 +1,429 @@
# Maintenance Workflow
workflow:
id: maintenance
name: Bug Fixes, Updates, and Improvements
description: Quick turnaround for maintenance tasks
duration: 2 hours - 3 days
token_budget: 1000-4000
# TRIAGE (30 minutes)
triage:
agent: appropriate-developer or lead
duration: 30 minutes
tokens: 300
categorize:
bug_fix:
priority: By impact and users affected
sla:
critical: 2-4 hours
high: 4-8 hours
medium: 1-2 days
low: 1 week
dependency_update:
priority: By security and compatibility
types:
security: Immediate
major: Plan carefully
minor: Low risk
patch: Safe to update
performance_issue:
priority: By user impact
approach:
- Profile first
- Fix bottleneck
- Measure improvement
refactoring:
priority: By technical debt impact
rules:
- Don't rewrite
- Incremental changes
- Maintain functionality
outputs:
- issue-assessment.md
- priority-label
- assigned-developer
# BUG FIX WORKFLOW
bug_fix:
duration: 2-8 hours
tokens: 1500
# Step 1: Reproduce (30 min - 2 hours)
reproduce:
agent: assigned-developer
tasks:
- Get reproduction steps
- Reproduce locally
- Identify affected versions
- Check error logs
outputs:
- Confirmed reproduction
- Environment details
# Step 2: Root Cause Analysis (30 min - 2 hours)
analyze:
tasks:
- Debug the issue
- Identify root cause
- Assess fix complexity
- Check for related bugs
outputs:
- Root cause identified
- Fix approach defined
# Step 3: Fix Implementation (1-4 hours)
fix:
tasks:
- Implement fix
- Add regression test
- Update error handling
- Verify fix works
outputs:
- Fixed code
- Regression test
- Verification proof
# Step 4: Deploy (30 min - 1 hour)
deploy:
tasks:
- Code review (expedited if critical)
- Deploy to staging
- Verify fix
- Deploy to production
- Monitor for issues
outputs:
- Fix deployed
- Monitoring active
checklist:
- [ ] Bug reproduced
- [ ] Root cause found
- [ ] Fix implemented
- [ ] Test added
- [ ] Verified working
- [ ] Code reviewed
- [ ] Deployed to production
- [ ] Users notified (if needed)
# DEPENDENCY UPDATE WORKFLOW
dependency_update:
duration: 1-4 hours
tokens: 1000
# Step 1: Audit (15-30 min)
audit:
commands:
- npm audit
- npm outdated
- Check breaking changes
outputs:
- Vulnerability report
- Update candidates
# Step 2: Update Strategy (15-30 min)
strategy:
safe_updates:
- Patch versions (1.2.3 -> 1.2.4)
- Security fixes
- No breaking changes
careful_updates:
- Minor versions (1.2.0 -> 1.3.0)
- Check changelog
- Test thoroughly
major_updates:
- Major versions (1.x -> 2.x)
- Read migration guide
- Plan separate PR
# Step 3: Update & Test (1-2 hours)
update:
tasks:
- Update dependencies
- Fix breaking changes
- Run all tests
- Check build
- Test locally
outputs:
- Updated package.json
- All tests passing
# Step 4: Deploy (30 min)
deploy:
tasks:
- Code review
- Deploy to staging
- Smoke test
- Deploy to production
- Monitor logs
checklist:
- [ ] Dependencies audited
- [ ] Breaking changes reviewed
- [ ] Updates applied
- [ ] Tests passing
- [ ] Build successful
- [ ] Deployed safely
# PERFORMANCE OPTIMIZATION WORKFLOW
performance:
duration: 1-3 days
tokens: 3000
# Step 1: Profile & Measure (2-4 hours)
profile:
agent: performance-expert or senior-dev
tools:
frontend:
- Chrome DevTools
- Lighthouse
- Web Vitals
- Bundle analyzer
backend:
- APM tools (New Relic, DataDog)
- Database query analysis
- CPU/Memory profiling
- Network analysis
outputs:
- Performance baseline
- Bottleneck identification
- Improvement opportunities
# Step 2: Optimize (1-2 days)
optimize:
common_fixes:
frontend:
- Code splitting
- Image optimization
- Remove unused code
- Lazy loading
- Memoization
backend:
- Database indexing
- Query optimization
- Caching (Redis)
- Connection pooling
- Background jobs
both:
- API response size
- Reduce requests
- CDN usage
- Compression
tasks:
- Implement optimizations
- Measure improvements
- A/B test if possible
- Document changes
# Step 3: Validate (2-4 hours)
validate:
metrics:
- Page load time
- Time to Interactive
- API response time
- Database query time
- Bundle size
targets:
- 30%+ improvement minimum
- Meet performance budget
- No regressions
outputs:
- Performance report
- Before/after metrics
checklist:
- [ ] Baseline measured
- [ ] Bottlenecks identified
- [ ] Optimizations implemented
- [ ] Improvements measured
- [ ] No regressions
- [ ] Deployed to production
# REFACTORING WORKFLOW
refactoring:
duration: 1-5 days
tokens: 4000
# Step 1: Plan (2-4 hours)
planning:
identify:
- Code smells
- Technical debt
- Duplication
- Complexity
prioritize:
- High-traffic code first
- Business-critical paths
- Frequently changed code
scope:
- One module at a time
- Incremental changes
- Maintain tests
# Step 2: Refactor (1-4 days)
refactor:
principles:
- Keep tests green
- Small commits
- No behavior changes
- Incremental improvements
patterns:
- Extract methods/components
- Remove duplication
- Simplify logic
- Improve naming
- Add types
outputs:
- Cleaner code
- Better structure
- Same functionality
# Step 3: Verify (2-4 hours)
verify:
checks:
- All tests pass
- No new bugs
- Performance same/better
- Code review approval
outputs:
- Verified refactoring
- Documentation updated
checklist:
- [ ] Refactoring plan created
- [ ] Code incrementally improved
- [ ] Tests still passing
- [ ] No functionality changes
- [ ] Code reviewed
- [ ] Deployed safely
# SECURITY PATCH WORKFLOW
security_patch:
duration: 2-8 hours
priority: URGENT
tokens: 2000
# Step 1: Assess (30 min)
assess:
severity:
critical: Exploit in the wild
high: Easy to exploit
medium: Requires conditions
low: Theoretical risk
impact:
- Data exposure risk
- System compromise risk
- User impact
outputs:
- Severity assessment
- Patch urgency
# Step 2: Patch (1-4 hours)
patch:
immediate_actions:
- Apply security update
- Test critical paths
- Deploy to production ASAP
follow_up:
- Comprehensive testing
- Security scan
- Audit related code
# Step 3: Communicate (30 min)
communicate:
notify:
- Security team
- Engineering team
- Management (if severe)
- Users (if data exposure)
document:
- What was vulnerable
- How it was fixed
- Impact assessment
- Prevention measures
checklist:
- [ ] Vulnerability assessed
- [ ] Patch applied
- [ ] Testing completed
- [ ] Deployed to production
- [ ] Security scan clean
- [ ] Team notified
- [ ] Incident documented
# COMMON PATTERNS
patterns:
quick_fix:
when: Simple, low-risk change
process:
- Make fix
- Add test
- Deploy quickly
careful_fix:
when: Complex or high-risk
process:
- Thorough analysis
- Comprehensive testing
- Staged deployment
hotfix:
when: Production is broken
process:
- Fix on hotfix branch
- Minimal testing
- Deploy immediately
- Thorough testing later
# ESCALATION
escalation:
when_to_escalate:
- Can't reproduce bug
- Fix causes regressions
- Security vulnerability
- Breaking change needed
- Requires architecture change
escalation_path:
- Team lead
- Senior developer
- Architect
- CTO (critical security)
# SUCCESS METRICS
success:
bug_fix:
- Issue resolved
- No regression
- Test coverage added
- Users satisfied
update:
- Dependencies current
- No vulnerabilities
- All tests pass
- Production stable
performance:
- 30%+ improvement
- Targets met
- No degradation elsewhere
refactoring:
- Code cleaner
- Same functionality
- Team velocity maintained
# DELIVERABLES
deliverables:
- [ ] Issue resolved
- [ ] Tests added/passing
- [ ] Code reviewed
- [ ] Deployed to production
- [ ] Documented (if needed)
- [ ] Monitoring confirmed

View File

@ -1,86 +0,0 @@
# <!-- Powered by BMAD™ Core -->
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)

View File

@ -1,66 +0,0 @@
# <!-- Powered by BMAD™ Core -->
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: sm
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