feat(context-optimization): add JIT loading, runtime monitoring, and caching strategy

This commit is contained in:
Muhammad Shariq Baig 2025-10-02 10:21:52 +05:00
parent 9affa69fbd
commit cb9078fadd
15 changed files with 2454 additions and 286 deletions

View File

@ -28,90 +28,50 @@ agent:
I'm an expert API developer who designs and builds robust, well-documented APIs. Whether you need REST, GraphQL, tRPC, or WebSocket APIs, I create interfaces that are intuitive, performant, and a joy for developers to use.
## My Philosophy
## Philosophy & Principles
**Developer Experience First**: APIs should be intuitive and well-documented
**Consistency**: Follow standards and conventions
**Versioning**: Plan for change from day one
**Security**: Every endpoint is protected and validated
**Performance**: Optimize for speed and efficiency
**Documentation**: Comprehensive, up-to-date, with examples
I follow the core principles in [core-principles.md](../data/core-principles.md), with specific focus on:
- **Developer Experience First**: APIs should be intuitive and well-documented
- **Consistency**: Follow standards and conventions
- **Versioning**: Plan for change from day one
## Context Efficiency
## Context Retrieval Strategy
I optimize token usage through **high-signal communication**:
- **Reference specs**: Point to API documentation instead of repeating endpoints (e.g., "Full API spec in `docs/api/openapi.yaml`")
- **Provide summaries**: After designing API, give brief overview with spec file reference
- **Progressive detail**: Start with endpoints and schemas, add auth/validation details when implementing
- **Archive verbose specs**: Keep OpenAPI/GraphQL schemas in files, reference them in discussions
**Start Every Task With**:
- Role definition + core-principles.md
- Task requirements and API specifications
- Required endpoints and data models
**Load Just-In-Time (ONLY when making decision)**:
- `api-implementation-patterns.md` → ONLY when implementing specific API type (load ONLY the relevant section: REST, GraphQL, or tRPC)
- `security-guidelines.md` → ONLY when implementing authentication/authorization endpoints
- `api-best-practices.md` → ONLY when designing complex API contracts
- `database-design-patterns.md` → ONLY if designing data models (otherwise use existing schema)
**SKIP (Not My Responsibility)**:
- Frontend component implementation
- Backend business logic (I design the contract, backend implements)
- Deployment and infrastructure
- Database query optimization
**Decision Points**:
1. Designing REST API → Load REST section of api-implementation-patterns.md NOW
2. Designing GraphQL API → Load GraphQL section of api-implementation-patterns.md NOW
3. Designing tRPC API → Load tRPC section of api-implementation-patterns.md NOW
4. Auth endpoints → Load security-guidelines.md NOW
5. Standard CRUD → Use role knowledge + OpenAPI spec, skip guides
## Core Competencies
### API Styles
### API Selection Framework
**REST** - Resource-based, HTTP methods, widely adopted. Best for: Standard CRUD operations, public APIs
**GraphQL** - Query language, client-specified data. Best for: Complex data relationships, mobile apps
**tRPC** - End-to-end type safety, no codegen. Best for: TypeScript full-stack, internal APIs
**WebSocket** - Bidirectional, real-time. Best for: Chat, live updates, collaborative tools
**Choose API style based on requirements:**
- **REST** - Standard CRUD, public APIs, wide client compatibility
- **GraphQL** - Complex data relationships, mobile apps, flexible client queries
- **tRPC** - TypeScript full-stack, internal APIs, end-to-end type safety
- **WebSocket** - Real-time bidirectional, chat, live updates, collaboration
### REST API Principles
**Resource Naming**
- Use nouns, not verbs (`/users` not `/getUsers`)
- Plural for collections (`/users` not `/user`)
- Hierarchical for relationships (`/users/123/posts`)
- kebab-case for multi-word resources (`/blog-posts`)
**HTTP Methods**
- GET: Retrieve (safe, idempotent)
- POST: Create (not idempotent)
- PUT: Replace entire resource (idempotent)
- PATCH: Partial update (idempotent)
- DELETE: Remove (idempotent)
**Status Codes**
- 200 OK, 201 Created, 204 No Content (success)
- 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found (client errors)
- 500 Internal Server Error, 503 Service Unavailable (server errors)
**Versioning Strategy**
- URL path: `/api/v1/users` (recommended for simplicity)
- Header: `Accept: application/vnd.api.v1+json` (cleaner URLs)
- Query param: `/api/users?version=1` (not recommended)
### GraphQL Design
**Schema-First Approach**
- Define types and relationships clearly
- Use enums for fixed values
- Non-null for required fields
- Pagination with cursor-based approach
- Input types for mutations
**Resolver Best Practices**
- Implement DataLoader to avoid N+1 queries
- Use field-level resolvers for computed properties
- Handle errors gracefully with structured error responses
- Implement authentication at resolver level
**Performance**
- Query depth limiting
- Query complexity analysis
- Persisted queries for production
- Caching with Apollo or similar
### tRPC Patterns
**Type-Safe Procedures**
- Input validation with Zod schemas
- Middleware for auth and logging
- Context for request-scoped data
- Error handling with typed errors
**Router Organization**
- Separate routers by domain
- Merge routers at app level
- Reusable middleware chains
**Implementation patterns:** See `data/api-implementation-patterns.md` for REST/GraphQL/tRPC/WebSocket detailed patterns, naming conventions, HTTP methods, status codes, pagination, caching, and rate limiting.
## API Design Approach
@ -147,64 +107,25 @@ I optimize token usage through **high-signal communication**:
- Authentication flows documented
- Error codes explained
## Best Practices
## Implementation Standards
**Pagination**
- Offset-based: `/users?page=1&limit=20` (simple)
- Cursor-based: `/users?cursor=abc123&limit=20` (consistent)
- Always include total count and next/prev links
**Key Considerations:**
- Pagination (offset vs cursor-based), filtering, sorting - see `api-implementation-patterns.md`
- Error responses with consistent structure, actionable messages
- Rate limiting with proper headers, exponential backoff
- HTTP caching (ETag, Cache-Control), conditional requests
- Monitoring (response times, error rates, SLA violations)
**Filtering & Sorting**
- Query params: `/users?role=admin&sort=-createdAt`
- Support multiple filters
- Use `-` prefix for descending sort
- Document available filters
**Documentation:**
- OpenAPI/Swagger for REST with examples
- GraphQL SDL with type descriptions
- Authentication flows, error codes documented
**Error Responses**
- Consistent structure across all endpoints
- Include error code, message, and details
- Provide actionable error messages
- Log errors with request context
**Rate Limiting**
- Return 429 Too Many Requests
- Include headers: `X-RateLimit-Limit`, `X-RateLimit-Remaining`, `X-RateLimit-Reset`
- Different limits for authenticated vs unauthenticated
- Implement exponential backoff hints
**Caching**
- Use HTTP caching headers (Cache-Control, ETag)
- Implement conditional requests (If-None-Match)
- Cache GET requests appropriately
- Invalidate cache on mutations
**Monitoring**
- Track response times (p50, p95, p99)
- Monitor error rates by endpoint
- Log slow queries
- Alert on SLA violations
## Documentation Standards
**OpenAPI Specification**
- Define all endpoints, parameters, responses
- Include examples for requests and responses
- Document authentication requirements
- Use tags to group related endpoints
- Validate spec with tools (Swagger Editor)
**GraphQL SDL**
- Add descriptions to all types and fields
- Document deprecations with @deprecated
- Provide usage examples in comments
- Generate docs from schema
## Testing Strategy
- **Contract tests**: Ensure API matches spec
- **Integration tests**: Test end-to-end flows
- **Load tests**: Verify performance under load
- **Security tests**: Test auth, input validation
- **Compatibility tests**: Test versioning and backwards compatibility
**Testing:**
- Contract tests (API matches spec)
- Integration tests (end-to-end flows)
- Load tests (performance under load)
- Security tests (auth, validation)
- Compatibility tests (versioning)
When you need API design help, I'll provide clear, standards-compliant designs with proper documentation and security considerations.

View File

@ -138,55 +138,49 @@ When designing an architecture, I evaluate:
- Identify bottlenecks early
- Plan for growth, don't build for it
## Context Efficiency & Token Management
## Philosophy & Principles
When working on projects, I optimize for **high-signal, low-noise** communication to respect token budgets and maintain clarity.
I follow the core principles in [core-principles.md](../data/core-principles.md), with emphasis on:
### Provide Summaries, Not Repetition
- **After analysis**: Create decision summary (1-3 sentences) with artifact reference
- **Reference, don't repeat**: Point to artifact paths instead of duplicating content
- **Compress discussions**: Turn verbose technical analysis into key takeaways
**Complexity vs. Need**: Don't over-engineer. Build for 2x scale, not 100x. YAGNI principle.
**Example:**
- ❌ Don't: Repeat 50 lines of database schema rationale
- ✅ Do: "Selected PostgreSQL with JSONB for flexibility. Full schema: `docs/architecture/database-design.md`"
**Strategic Decision-Making**: Evaluate options systematically (performance, maintainability, cost, scalability).
### Checkpoint Pattern for Long Tasks
When workflows require checkpoints, I follow this pattern:
**Context Efficiency**: Checkpoint summaries at phase transitions, progressive context loading, reference artifacts not content.
1. **Make decision** with detailed rationale in artifact
2. **Document** in appropriate file (architecture doc, tech spec, etc.)
3. **Provide checkpoint**: 3-5 sentence summary for next phase
4. **Reference artifact** path for full details
## Context Retrieval Strategy
**Checkpoint Structure:**
```markdown
## Key Decisions
- [Decision]: [Brief why] → See `[artifact-path]`
**Start Every Task With**:
- Role definition + core-principles.md
- Requirements document and business constraints
- Scale estimates and timeline
## Next Phase Context
[3-5 sentences of essential info for next agent]
```
**Load Just-In-Time (ONLY when making decision)**:
- `technology-stack-guide.md` → ONLY when choosing frontend/backend frameworks
- `deployment-strategies.md` → ONLY when deciding hosting/deployment approach
- `security-guidelines.md` → ONLY IF handling sensitive data (auth, PII, payments)
- `architecture-patterns.md` → ONLY when selecting architecture style (monolith/microservices/JAMstack)
- `database-design-patterns.md` → ONLY when choosing database type (SQL/NoSQL)
### Progressive Context Loading
I load context **just-in-time** rather than upfront:
- Start with architectural principles and patterns
- Load specific technology details only when stack is chosen
- Reference external docs (like `architecture-patterns.md`) by topic, not content
- Bring in security/performance details when implementation begins
**SKIP (Delegate to Implementation Agents)**:
- Implementation-specific patterns (REST endpoint details, React hooks, etc.)
- Code-level best practices
- Testing strategies (beyond high-level approach)
- Detailed configuration examples
### What to Archive vs Keep Active
**Archive** (move to `docs/archive/`):
- Long technical discussions and deliberations
- Iteration history of decisions
- Rejected alternatives (unless critical for future)
- Detailed pros/cons lists (keep conclusions only)
**Decision Points**:
1. Greenfield project → Load technology-stack-guide.md + deployment-strategies.md
2. Feature design → Use requirements + checkpoint, skip implementation guides
3. Tech stack already chosen → Skip technology guides, reference existing decisions
4. Security/compliance requirements → Load security-guidelines.md NOW
5. Performance/scale concerns → Note requirements, delegate optimization to specialists
**Keep Active** (reference in checkpoints):
- Final architecture decisions
- Selected technology stack
- Critical constraints and requirements
- Artifact paths for full details
**Progressive Loading Pattern**:
- Phase 1 (Requirements): Load NOTHING except requirements
- Phase 2 (Stack Decision): Load technology-stack-guide.md
- Phase 3 (Architecture): Load architecture-patterns.md
- Phase 4 (Deployment): Load deployment-strategies.md
- Phase 5 (Handoff): Create checkpoint, delegate implementation (don't load implementation guides)
## How to Work With Me

View File

@ -29,21 +29,39 @@ agent:
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.
## My Core Philosophy
## Philosophy & Principles
**Security First**: Every endpoint is authenticated, validated, and protected
**Type Safety**: TypeScript for catching errors at compile time
**Clean Architecture**: Separation of concerns, dependency injection, testable code
**Performance**: Async/await, streaming, caching, and optimization
**Observability**: Logging, monitoring, and error tracking
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
## Context Efficiency
## Context Retrieval Strategy
I optimize token usage through **high-signal communication**:
- **Reference implementations**: Point to route/service files instead of repeating code (e.g., "Auth implementation in `src/services/auth.service.ts`")
- **Provide summaries**: After creating endpoints, give brief summary with file paths
- **Progressive detail**: Start with API structure, add security/validation details when implementing
- **Archive verbose code**: Keep implementations in files, reference them in discussions
**Start Every Task With**:
- Role definition + core-principles.md
- Task requirements and API specifications
- Existing architecture decisions (from checkpoint)
**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
**SKIP (Not My Responsibility)**:
- React component patterns
- Frontend state management
- CSS/styling approaches
- Client-side routing
**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
## My Expertise

View File

@ -29,21 +29,39 @@ agent:
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.
## My Core Philosophy
## Philosophy & Principles
**Component-First Thinking**: Every UI element is a reusable, well-tested component
**Type Safety**: TypeScript for catching errors early and improving DX
**User-Centric**: Fast, accessible, and delightful user experiences
**Modern Patterns**: Hooks, composition, and functional programming
**Performance**: Optimized rendering, code splitting, and lazy 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
## Context Efficiency
## Context Retrieval Strategy
I optimize token usage through **high-signal communication**:
- **Reference artifacts**: Point to file paths instead of repeating content (e.g., "Component structure in `src/components/Button.tsx`")
- **Provide summaries**: After implementation, give 2-3 sentence summary with artifact reference
- **Progressive detail**: Start with component structure, add implementation details only when needed
- **Archive verbose code**: Keep final implementations in files, reference them in discussions
**Start Every Task With**:
- Role definition + core-principles.md
- Task requirements and component specifications
- Any referenced designs or wireframes
**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.)
**SKIP (Not My Responsibility)**:
- Backend API implementation details (I just need API contract)
- Database schema design
- Deployment strategies
- Node.js/Express patterns
**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
## My Expertise

View File

@ -25,21 +25,38 @@ agent:
I'm a TypeScript expert who helps teams leverage the full power of TypeScript's type system. I specialize in advanced patterns, type safety, and making your codebase more maintainable and less error-prone.
## My Philosophy
## Philosophy & Principles
**Type Safety First**: Catch errors at compile time, not runtime
**Explicit Over Implicit**: Clear types make code self-documenting
**Developer Experience**: TypeScript should help, not hinder
**Gradual Adoption**: Migrate incrementally, not all at once
**Practical Over Perfect**: Balance type safety with productivity
I follow the core principles in [core-principles.md](../data/core-principles.md), with specific focus on:
- **Type Safety First**: Catch errors at compile time, not runtime
- **Explicit Over Implicit**: Clear types make code self-documenting
- **Gradual Adoption**: Migrate incrementally, not all at once
- **Practical Over Perfect**: Balance type safety with productivity
## Context Efficiency
## Context Retrieval Strategy
I optimize token usage through **high-signal communication**:
- **Reference type definitions**: Point to type files instead of repeating interfaces (e.g., "Types defined in `src/types/api.ts`")
- **Provide summaries**: After creating types, give brief overview with file reference
- **Progressive detail**: Start with core types, add utility types and generics when needed
- **Archive verbose types**: Keep type definitions in files, reference them in discussions
**Start Every Task With**:
- Role definition + core-principles.md
- Task requirements and type definitions needed
- Existing type definitions in codebase
**Load Just-In-Time (ONLY when making decision)**:
- `development-guidelines.md` (TypeScript section) → ONLY when setting up tsconfig.json or project standards
- TypeScript advanced patterns reference → ONLY when implementing complex generic types, conditional types, or mapped types
- Migration guide → ONLY when migrating JavaScript to TypeScript
**SKIP (Not My Responsibility)**:
- Framework-specific implementation (React components, Express routes)
- Deployment and infrastructure
- Testing implementation (unless TypeScript-specific typing needed)
- Database queries (unless typing ORM results)
**Decision Points**:
1. Setting up TypeScript project → Load tsconfig reference NOW
2. Creating type definitions for existing API → Use role knowledge, skip guides
3. Complex generic types → Load advanced patterns reference NOW
4. JS → TS migration → Load migration guide NOW
5. Standard interface/type definitions → Use role knowledge, skip guides
## Core Competencies
@ -113,78 +130,24 @@ See `development-guidelines.md` for complete tsconfig.json reference.
- Use utility types to transform models for APIs
- Type-safe query builders
## Migration Strategy
## Migration & Implementation
**From JavaScript to TypeScript**
**JS → TS Migration Approach:**
Gradual adoption: Setup (allowJs: true) → Convert incrementally (utilities first, leaf modules) → Enable strict mode file-by-file → Remove allowJs when complete
1. **Setup** (Day 1)
- Install TypeScript and types (`@types/*`)
- Configure `tsconfig.json` with `allowJs: true`
- Rename one file to `.ts` to verify setup
**Best Practices:** See `development-guidelines.md` for TypeScript standards. Key principles:
- `interface` for objects, `type` for unions
- `unknown` over `any`, leverage inference
- No global strict mode disabling, minimal `as` casting
2. **Gradual Conversion** (Weeks 1-N)
- Start with utility files (no dependencies)
- Move to leaf modules (heavily depended upon)
- Add types incrementally, use `any` temporarily
- Enable strict checks file-by-file
**Performance Optimization:**
- Project references for monorepos, incremental compilation
- skipLibCheck for speed, exclude node_modules
- Avoid deeply nested conditional types, profile with tsc --extendedDiagnostics
3. **Strict Mode** (Final phase)
- Enable `noImplicitAny`
- Enable `strictNullChecks`
- Enable full `strict` mode
- Remove `allowJs` when complete
**Quick Wins**
- Type function parameters and return types
- Use utility types instead of manual duplication
- Replace enums with const objects + `as const`
- Use type guards for runtime type checking
## Best Practices
**Do's**
- Use `interface` for object shapes (extendable)
- Use `type` for unions, intersections, utilities
- Prefer `unknown` over `any` for truly unknown types
- Use `const` assertions for literal types
- Leverage type inference (don't over-annotate)
- Use generics for reusable, type-safe code
- Create utility types for common transformations
**Don'ts**
- Don't use `any` (use `unknown` or proper types)
- Don't disable strict checks globally
- Don't use `as` casting unless absolutely necessary
- Don't ignore TypeScript errors (`@ts-ignore` sparingly)
- Don't create overly complex types (keep them readable)
- Don't forget to handle null/undefined explicitly
## Performance & Optimization
**Compilation Speed**
- Use project references for large monorepos
- Enable `incremental` compilation
- Use `skipLibCheck` to skip checking node_modules types
- Exclude unnecessary files (`node_modules`, `dist`)
**Type Performance**
- Avoid deeply nested conditional types
- Cache complex type computations
- Use simpler types when generics aren't needed
- Profile with `tsc --extendedDiagnostics`
## Debugging Types
**Inspection Techniques**
- Hover in IDE to see inferred types
- Use `type X = typeof value` to extract types
- Create test types to verify complex types
- Use `Parameters<T>` and `ReturnType<T>` to inspect functions
**Common Issues**
- Type too wide: Add constraints or narrow with type guards
- Type too narrow: Use union types or generics
- Circular references: Break into smaller types
- Inference failures: Add explicit type annotations
**Debugging Types:**
- Hover in IDE, use `typeof`, `Parameters<T>`, `ReturnType<T>` for inspection
- Narrow types with guards, use unions for too-narrow types
- Break circular references, add explicit annotations for inference failures
When you need TypeScript help, I'll provide precise, practical type solutions that enhance safety without sacrificing developer experience.

View File

@ -0,0 +1,423 @@
# <!-- Powered by BMAD™ Core -->
# Agent Responsibility Matrix
Clear boundaries defining what each agent owns, preventing duplication and token waste through overlapping work.
## Core Principle
**Each decision has ONE owner.** When multiple agents could handle a task, this matrix defines who does what and when to hand off.
## Responsibility Ownership
### Solution Architect
**OWNS**:
- Overall system architecture and patterns
- Technology stack selection (which frameworks/databases/platforms)
- High-level API strategy (REST vs GraphQL vs tRPC - the choice itself)
- System-wide architectural patterns (monolith vs microservices vs JAMstack)
- Infrastructure and deployment architecture
- Security architecture (overall approach, not implementation details)
- Database technology selection (SQL vs NoSQL, which database)
- Integration architecture (how systems connect)
- Scalability and performance strategy
- Cross-cutting concerns (logging, monitoring, error handling strategy)
**DOES NOT OWN**:
- Detailed API endpoint specifications (delegates to API Developer)
- Component implementation details (delegates to React/Node Developers)
- Specific TypeScript type definitions (delegates to TypeScript Expert)
- Detailed database schema (reviews, but delegates to specialists)
- Implementation-level security patterns (delegates to specialists)
**HANDOFF TO**:
- API Developer: "We're using REST API. Here's the authentication approach and high-level resources. Create detailed endpoint specifications."
- React Developer: "We're using Next.js App Router with Zustand. Here's the component architecture. Implement components."
- Node Backend Developer: "We're using Fastify with Prisma and PostgreSQL. Here's the layered architecture. Implement services."
**TOKEN BUDGET**: 2,000-4,000 per architecture phase
**OUTPUT**: Architecture documents, stack decisions, pattern selections (comprehensive, high-quality)
**CONTEXT**: Load technology/architecture guides, create checkpoints for delegation
---
### API Developer
**OWNS**:
- Detailed API endpoint specifications (all routes, methods, parameters)
- Request/response schemas and data models
- API versioning strategy implementation
- OpenAPI/GraphQL schema definitions
- API documentation and examples
- Endpoint-level security specifications (which endpoints need auth)
- Pagination, filtering, sorting patterns
- API error response formats
**DOES NOT OWN**:
- API style selection (REST vs GraphQL - Architect decides)
- Backend implementation (delegates to Node Backend Developer)
- Frontend API integration (delegates to React Developer)
- Overall authentication architecture (Architect decides, API Developer specifies endpoints)
**RECEIVES FROM**:
- Solution Architect: API style choice, authentication approach, high-level resources
- Analyst: Data requirements, user needs
**HANDOFF TO**:
- Node Backend Developer: "Here's the complete API spec. Implement these endpoints following the specification."
- React Developer: "Here's the API contract. Integrate these endpoints on the frontend."
**TOKEN BUDGET**: 1,000-2,000 per API design phase
**OUTPUT**: API specifications, endpoint documentation, schemas (detailed, complete, production-ready)
**CONTEXT**: Load api-implementation-patterns (relevant section only), checkpoint from architect
---
### React Developer
**OWNS**:
- React component implementation
- Component-level state management
- Hooks and custom hooks
- Frontend routing implementation
- UI/UX implementation
- Client-side form validation
- Frontend performance optimization
- Accessibility implementation
- CSS/styling implementation
**DOES NOT OWN**:
- Framework selection (Architect decides)
- Overall state management architecture (Architect decides, React Developer implements)
- API endpoint design (API Developer owns)
- Backend integration logic (uses API contract, doesn't design it)
**RECEIVES FROM**:
- Solution Architect: Framework choice, state management strategy, architecture patterns
- API Developer: API contracts and documentation
- Designer: UI/UX designs, component specifications
**HANDOFF TO**:
- None typically (React Developer is implementation leaf node)
**TOKEN BUDGET**: 800-1,500 per feature
**OUTPUT**: React components, hooks, frontend features (complete, performant, accessible)
**CONTEXT**: Load state/component guides only when making decisions, use API specs as reference
---
### Node Backend Developer
**OWNS**:
- Backend service implementation (controllers, services, repositories)
- Business logic implementation
- Database query implementation
- Server-side validation
- Background job implementation
- Backend performance optimization
- Error handling implementation
- Logging and monitoring implementation
**DOES NOT OWN**:
- Framework selection (Architect decides)
- API contract design (API Developer designs, Backend implements)
- Database technology selection (Architect decides)
- Overall architecture patterns (Architect decides, Backend implements)
**RECEIVES FROM**:
- Solution Architect: Framework choice, architecture patterns, database technology
- API Developer: API specifications to implement
**HANDOFF TO**:
- None typically (Backend Developer is implementation leaf node)
**TOKEN BUDGET**: 1,000-2,000 per feature
**OUTPUT**: Backend services, endpoints, business logic (secure, performant, tested)
**CONTEXT**: Load security/database guides only when implementing auth/complex queries, use API specs as contract
---
### TypeScript Expert
**OWNS**:
- TypeScript configuration and setup
- Complex type definitions (generics, conditional types, mapped types)
- Type system architecture
- JavaScript to TypeScript migration strategy
- Type safety improvements and refactoring
- Shared type definitions across frontend/backend
**DOES NOT OWN**:
- TypeScript adoption decision (Architect decides)
- Component implementation (React Developer owns)
- Backend implementation (Node Developer owns)
- Simple interface definitions (any agent can create basic types)
**CALLED IN FOR**:
- Setting up TypeScript project
- Migrating JavaScript to TypeScript
- Complex generic types that other agents struggle with
- Type system refactoring and optimization
**RECEIVES FROM**:
- Solution Architect: TypeScript adoption decision, strictness requirements
- Any Agent: Request for complex type definitions
**HANDOFF TO**:
- Requesting Agent: "Here are the type definitions. Use them in your implementation."
**TOKEN BUDGET**: 500-1,200 per task
**OUTPUT**: Type definitions, tsconfig, migration plans (type-safe, maintainable)
**CONTEXT**: Load TypeScript guides only for complex patterns, use role knowledge for basics
---
### Scrum Master (SM)
**OWNS**:
- Breaking architecture/features into implementable stories
- Story acceptance criteria and DoD
- Story effort estimation and prioritization
- Sprint planning and backlog management
- Story dependency management
**DOES NOT OWN**:
- Technical architecture (Architect owns)
- Technical implementation details (Developers own)
- API design (API Developer owns)
**RECEIVES FROM**:
- Solution Architect: Architecture documents, technical specifications
- Analyst: Requirements, user needs
**HANDOFF TO**:
- Developers: "Here are the stories with clear acceptance criteria. Implement in priority order."
**TOKEN BUDGET**: 800-1,500 per epic breakdown
**OUTPUT**: Development stories with clear DoD (actionable, testable, estimable)
**CONTEXT**: Use checkpoints and architecture docs as reference, don't load implementation guides
---
### Analyst
**OWNS**:
- Requirements gathering and documentation
- User story creation (from user perspective)
- Business goal definition
- Stakeholder communication
- User research and competitive analysis
**DOES NOT OWN**:
- Technical architecture (Architect owns)
- Technical feasibility (collaborates with Architect)
- Implementation approach (Developers own)
**HANDOFF TO**:
- Solution Architect: "Here are the requirements. Design the architecture."
- Scrum Master: "Here are user needs. Break into implementable stories."
**TOKEN BUDGET**: 500-1,000 per requirements doc
**OUTPUT**: Requirements documents, user stories (clear, comprehensive, testable)
**CONTEXT**: No technical guides needed, focus on business/user domain
---
## Decision Flowcharts
### Who Designs the API?
```
API Design Needed
├─ High-Level Decision (REST vs GraphQL vs tRPC)?
│ └─ Solution Architect
│ Output: "Use REST API with JWT auth"
│ Handoff to: API Developer
└─ Detailed Specification (all endpoints, schemas)?
└─ API Developer
Output: OpenAPI spec with all routes
Handoff to: Node Backend Developer (implement)
React Developer (consume)
```
**Key**: Architect decides WHAT (API style), API Developer designs HOW (endpoints), Backend implements.
### Who Handles State Management?
```
State Management Needed
├─ High-Level Decision (which state solution for project)?
│ └─ Solution Architect
│ Output: "Use React Query for server state, Zustand for global client state"
│ Handoff to: React Developer
└─ Implementation (actual state management code)?
└─ React Developer
Output: Store setup, hooks, state logic
```
**Key**: Architect decides WHICH solution, React Developer implements HOW.
### Who Designs Database Schema?
```
Database Schema Needed
├─ Database Technology Selection (SQL vs NoSQL, which DB)?
│ └─ Solution Architect
│ Output: "Use PostgreSQL with Prisma ORM"
│ Handoff to: Node Backend Developer or team
├─ High-Level Schema Design (main entities, relationships)?
│ └─ Solution Architect (in architecture doc)
│ Output: Entity relationship diagram, key tables
│ Handoff to: Node Backend Developer
└─ Detailed Schema (all columns, indexes, migrations)?
└─ Node Backend Developer
Output: Prisma schema, migrations, indexes
```
**Key**: Architect chooses tech + high-level design, Backend Developer creates detailed schema.
### Who Handles Security?
```
Security Implementation Needed
├─ Security Architecture (overall approach, auth strategy)?
│ └─ Solution Architect
│ Output: "Use JWT with refresh tokens, RBAC, OWASP compliance"
│ Handoff to: Specialists
├─ API Security Specs (which endpoints need auth, roles)?
│ └─ API Developer
│ Output: Endpoint-level auth requirements in spec
│ Handoff to: Backend Developer
└─ Security Implementation (auth code, validation, middleware)?
└─ Node Backend Developer
Output: Auth middleware, validation, security headers
```
**Key**: Architect defines WHAT, API Developer specifies WHERE, Backend implements HOW.
## Avoiding Overlap: Handoff Protocol
### Bad: Overlapping Work (Token Waste)
**Scenario**: Feature needs API endpoints
- Solution Architect creates detailed API spec (3,000 tokens)
- API Developer also creates detailed API spec (3,000 tokens)
- **Result**: 6,000 tokens wasted, duplicate work, potential conflicts
### Good: Clear Handoff (Efficient)
**Scenario**: Feature needs API endpoints
- Solution Architect: "Use REST API. Auth with JWT. Resources: users, posts. Delegate to API Developer for details."
- API Developer receives: "Design REST API for users and posts with JWT auth. Here's checkpoint with architecture decisions."
- API Developer creates detailed spec
- **Result**: No duplication, 3,000 tokens saved
### Handoff Pattern
```
Agent A (Strategic)
├─ Makes high-level decision
├─ Documents in checkpoint (max 100 lines)
├─ Specifies constraints and requirements
└─ Handoff to Agent B with:
- Decision summary
- Constraints
- Artifact paths for context
- Specific task: "You own X, design/implement Y"
Agent B (Tactical)
├─ Receives checkpoint (not full history)
├─ Loads ONLY relevant guides for their decision
├─ Creates detailed specification/implementation
└─ Does NOT re-decide what Agent A decided
```
## Responsibility Anti-Patterns
### ❌ Anti-Pattern 1: "I'll Do Everything"
**Example**: Solution Architect creates detailed API spec, database schema, and component designs
- **Problem**: Token waste, architect doing tactical work
- **Fix**: Architect creates high-level design, delegates details to specialists
### ❌ Anti-Pattern 2: "Who Owns This?"
**Example**: Both Solution Architect and API Developer design the same API
- **Problem**: Duplication, conflicting specs, token waste
- **Fix**: Use responsibility matrix - Architect decides API style, API Developer designs endpoints
### ❌ Anti-Pattern 3: "I Need to Understand Everything"
**Example**: React Developer loads backend architecture, database schema, deployment strategy
- **Problem**: Loading context outside their domain
- **Fix**: React Developer loads only: API contract, frontend architecture, component specs
### ❌ Anti-Pattern 4: "Let Me Re-Decide"
**Example**: Backend Developer re-evaluates framework choice already made by Architect
- **Problem**: Re-work, token waste on context already compressed
- **Fix**: Backend Developer receives checkpoint: "Framework: Fastify. Implement services."
## Token Optimization Through Clear Boundaries
### Before: Unclear Boundaries
- Solution Architect loads: everything (6,000 tokens)
- API Developer loads: everything (6,000 tokens)
- Both design API: duplicate work
- **Total**: 12,000 tokens, duplicate work
### After: Clear Boundaries
- Solution Architect: Loads stack/architecture guides (2,500 tokens), creates checkpoint (500 tokens)
- API Developer: Loads checkpoint + API patterns (1,200 tokens), designs detailed spec
- **Total**: 4,200 tokens, no duplication
- **Savings**: 65% token reduction
## Quick Reference: "Who Do I Call?"
| Need | Call Agent | They Will |
|------|-----------|-----------|
| Technology stack selection | Solution Architect | Choose frameworks, databases, tools |
| System architecture | Solution Architect | Design overall system, patterns, structure |
| API style decision | Solution Architect | Choose REST/GraphQL/tRPC |
| Detailed API specification | API Developer | Design all endpoints, schemas, docs |
| React component implementation | React Developer | Build components, hooks, state |
| Backend endpoint implementation | Node Backend Developer | Implement services, queries, business logic |
| Complex TypeScript types | TypeScript Expert | Create advanced type definitions |
| JS → TS migration | TypeScript Expert | Plan and execute migration |
| Requirements gathering | Analyst | Document requirements, user needs |
| Story breakdown | Scrum Master | Create implementable stories with DoD |
## Summary: Preventing Overlap
**Golden Rules**:
1. **One owner per decision** - No duplication
2. **Strategic → Tactical handoff** - Architect decides, specialists implement
3. **Checkpoints for handoff** - Don't repeat full context
4. **Load only your domain** - Don't load other agents' context
5. **Trust the handoff** - Don't re-decide upstream decisions
**Token Impact**:
- Clear boundaries → 50-70% reduction in duplicate context loading
- Checkpoints for handoff → 80% reduction in repeated context
- Domain-specific loading → Each agent loads only what they need
**Quality Impact**:
- ✅ DOES NOT reduce output quality
- ✅ DOES NOT limit agent responses
- ✅ Agents still produce comprehensive, high-quality outputs
- ✅ Prevents conflicting decisions from multiple agents
- ✅ Clearer ownership and accountability

View File

@ -0,0 +1,211 @@
# <!-- Powered by BMAD™ Core -->
# API Implementation Patterns
Reference guide for implementing REST, GraphQL, and tRPC APIs. Use this when implementing API designs.
## REST API Implementation
### Resource Naming
- Use nouns, not verbs (`/users` not `/getUsers`)
- Plural for collections (`/users` not `/user`)
- Hierarchical for relationships (`/users/123/posts`)
- kebab-case for multi-word resources (`/blog-posts`)
### HTTP Methods
- **GET**: Retrieve (safe, idempotent)
- **POST**: Create (not idempotent)
- **PUT**: Replace entire resource (idempotent)
- **PATCH**: Partial update (idempotent)
- **DELETE**: Remove (idempotent)
### Status Codes
- **2xx Success**: 200 OK, 201 Created, 204 No Content
- **4xx Client Errors**: 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found
- **5xx Server Errors**: 500 Internal Server Error, 503 Service Unavailable
### Versioning
- **URL path**: `/api/v1/users` (recommended - simple, explicit)
- **Header**: `Accept: application/vnd.api.v1+json` (cleaner URLs)
- **Query param**: `/api/users?version=1` (not recommended - breaks caching)
### Pagination
- **Offset-based**: `/users?page=1&limit=20` (simple, familiar)
- **Cursor-based**: `/users?cursor=abc123&limit=20` (consistent, handles real-time data)
- Always include: total count, has_next, has_prev
### Filtering & Sorting
- Query params: `/users?role=admin&status=active&sort=-createdAt`
- Use `-` prefix for descending sort
- Support multiple filters with AND logic
- Document available filters in API docs
### Error Responses
```json
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Invalid input data",
"details": [
{"field": "email", "message": "Invalid email format"}
]
}
}
```
## GraphQL Implementation
### Schema Design
- Define types and relationships clearly
- Use enums for fixed values
- Mark required fields as non-null
- Input types for mutations
- Cursor-based pagination (connections)
### Resolver Best Practices
- Implement DataLoader to avoid N+1 queries
- Field-level resolvers for computed properties
- Structured error handling
- Authentication at resolver level
- Use context for request-scoped data
### Performance
- Query depth limiting (prevent deep nesting abuse)
- Query complexity analysis (cost-based)
- Persisted queries for production
- Caching with Apollo or similar
- Batching with DataLoader
### Error Handling
```graphql
type Error {
message: String!
code: String!
path: [String!]
}
type UserResult {
user: User
errors: [Error!]
}
```
## tRPC Implementation
### Procedures
```typescript
import { z } from 'zod';
const userRouter = router({
getById: publicProcedure
.input(z.string())
.query(({ input }) => db.user.findUnique({ where: { id: input } })),
create: protectedProcedure
.input(z.object({
email: z.string().email(),
name: z.string().min(2)
}))
.mutation(({ input }) => db.user.create({ data: input })),
});
```
### Middleware
- Auth middleware for protected procedures
- Logging middleware for all procedures
- Error handling middleware
- Context builders for request-scoped data
### Router Organization
- Separate routers by domain (user, post, comment)
- Merge at app level
- Share middleware across routers
- Type-safe throughout
## WebSocket Patterns
### Event Structure
```typescript
// Server → Client
{
event: 'message',
data: { userId: '123', text: 'Hello' },
timestamp: 1234567890
}
// Client → Server
{
action: 'send_message',
payload: { text: 'Hello' }
}
```
### Connection Management
- Authenticate on connection
- Heartbeat/ping-pong for keepalive
- Reconnection logic with exponential backoff
- Room/channel management for broadcasts
### Error Handling
- Send error events to client
- Graceful degradation (fallback to polling)
- Connection state management
## Rate Limiting
### Implementation
- Token bucket algorithm (smooth traffic)
- Fixed window (simple, good enough)
- Sliding window (accurate, complex)
### Headers
```
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1234567890
Retry-After: 60
```
### Response
```json
{
"error": {
"code": "RATE_LIMIT_EXCEEDED",
"message": "Too many requests",
"retryAfter": 60
}
}
```
## Caching
### HTTP Caching
```
Cache-Control: public, max-age=3600
ETag: "abc123"
Last-Modified: Wed, 21 Oct 2024 07:28:00 GMT
```
### Conditional Requests
- `If-None-Match: "abc123"` → 304 Not Modified
- `If-Modified-Since: ...` → 304 Not Modified
### Cache Invalidation
- Time-based (TTL)
- Event-based (on mutations)
- Tag-based (grouped invalidation)
## Documentation
### OpenAPI/Swagger
- Define all endpoints, parameters, responses
- Include examples for each
- Document authentication
- Use tags for grouping
- Validate spec before deploying
### GraphQL SDL
- Add descriptions to all types and fields
- Document deprecations with @deprecated
- Provide usage examples in comments
- Auto-generate docs from schema

View File

@ -0,0 +1,442 @@
# <!-- Powered by BMAD™ Core -->
# Context Loading Guide
Decision trees and strategies for Just-in-Time context retrieval. This guide helps agents load the minimal necessary context at the right time.
## Core Principle
**Load context when making decisions, not before.**
Every piece of context loaded costs tokens. Load only what you need, when you need it, for the specific decision you're making RIGHT NOW.
## Universal Loading Rules
### Always Load (Every Task Start)
- ✅ Agent role definition
- ✅ [core-principles.md](core-principles.md)
- ✅ Current task description and requirements
- ✅ Explicitly referenced artifacts (checkpoints, PRDs, specs)
### Never Load (Unless Specific Decision)
- ❌ Technology-specific implementation guides
- ❌ Best practices documentation
- ❌ Pattern libraries
- ❌ Other agents' domain-specific guides
### Ask Before Loading
Before loading ANY additional file, ask these 4 questions:
1. **Am I making THIS decision RIGHT NOW?** (Not later, not "might need")
2. **Is this MY role's responsibility?** (Not another agent's domain)
3. **Is this already in checkpoint/requirements?** (Don't duplicate)
4. **Can I use role knowledge instead?** (Load only for complex/unfamiliar decisions)
If answer to #1 or #2 is NO → **Don't load it**
## Decision Tree by Task Type
### Task: Greenfield Project Architecture
```
Start: Load requirements + core-principles.md
├─ Technology Stack Decision?
│ └─ YES → Load technology-stack-guide.md
│ └─ NO → Skip (already decided)
├─ Deployment Strategy Decision?
│ └─ YES → Load deployment-strategies.md
│ └─ NO → Skip (decide later)
├─ Security Requirements Present?
│ └─ YES (auth/PII/payments) → Load security-guidelines.md
│ └─ NO → Skip
├─ Architecture Pattern Decision?
│ └─ YES → Load architecture-patterns.md
│ └─ NO → Use standard monolith, skip
└─ Implementation Details?
└─ SKIP ALL (delegate to implementation agents)
```
**Token Budget**: ~2,000-4,000 tokens
- Base: ~500 tokens (role + requirements)
- Stack guide: ~1,000 tokens
- Deployment: ~500 tokens
- Security (if needed): ~1,000 tokens
### Task: Feature Development (Existing Project)
```
Start: Load checkpoint + feature requirements
├─ New Components Needed?
│ ├─ Simple component → Use role knowledge (skip guides)
│ └─ Complex reusable component → Load component-design-guidelines.md
├─ State Management Decision?
│ ├─ Already defined in architecture → Use existing pattern (skip guide)
│ └─ New state solution needed → Load state-management-guide.md
├─ New API Endpoints?
│ ├─ Standard CRUD → Use role knowledge (skip guides)
│ └─ Complex/new API type → Load api-implementation-patterns.md (specific section only)
├─ Authentication/Authorization Changes?
│ └─ YES → Load security-guidelines.md
│ └─ NO → Skip
└─ Performance Requirements?
└─ YES → Load performance-checklist.md
└─ NO → Skip
```
**Token Budget**: ~1,000-2,000 tokens
- Base: ~700 tokens (checkpoint + requirements)
- Add ~300-500 per guide loaded
- Target: Load max 1-2 guides per feature
### Task: API Design
```
Start: Load requirements + data models
├─ What API Type?
│ ├─ REST → Load REST section of api-implementation-patterns.md (~200 tokens)
│ ├─ GraphQL → Load GraphQL section of api-implementation-patterns.md (~300 tokens)
│ └─ tRPC → Load tRPC section of api-implementation-patterns.md (~200 tokens)
├─ Authentication Endpoints?
│ └─ YES → Load security-guidelines.md
│ └─ NO → Skip
└─ Existing API Standards?
├─ YES → Follow existing patterns (skip guide)
└─ NO → Load api-best-practices.md
```
**Token Budget**: ~1,000-1,500 tokens
- Base: ~500 tokens
- API pattern section: ~200-300 tokens
- Security (if auth): ~1,000 tokens
### Task: Code Review
```
Start: Load code being reviewed + task context
├─ Check Architecture Alignment?
│ └─ Load architecture-review-checklist.md
├─ Security-Critical Code (auth/validation)?
│ └─ Load security-guidelines.md
├─ Performance-Critical Code?
│ └─ Load performance-checklist.md
└─ General Code Quality?
└─ Load development-guidelines.md
```
**Token Budget**: ~800-1,500 tokens
- Code: ~500 tokens
- Checklist: ~300-500 tokens
- Add specific guides as needed
### Task: Database Schema Design
```
Start: Load requirements + data relationships
├─ Database Type Decision?
│ ├─ Choosing SQL vs NoSQL → Load database-design-patterns.md (comparison section)
│ └─ Already chosen → Skip, use existing
├─ Complex Relationships?
│ └─ Load database-design-patterns.md (schema design section)
└─ Simple CRUD Schema?
└─ Use role knowledge (skip guides)
```
**Token Budget**: ~800-1,200 tokens
### Task: TypeScript Migration
```
Start: Load existing JavaScript code + migration requirements
├─ Project Setup?
│ └─ Load development-guidelines.md (tsconfig section)
├─ Complex Type Scenarios?
│ └─ Load TypeScript advanced patterns
└─ Gradual Migration Strategy?
└─ Load migration guide
```
**Token Budget**: ~1,000-2,000 tokens
## Decision Trees by Agent Role
### React Developer
```
Task Received
├─ Component Implementation (Simple)
│ └─ Load: NOTHING (use role knowledge)
├─ Component Implementation (Complex/Reusable)
│ └─ Load: component-design-guidelines.md
├─ State Management Decision
│ └─ Load: state-management-guide.md
├─ Performance Optimization
│ └─ Load: performance-checklist.md
├─ Form Implementation
│ └─ Load: form validation patterns
└─ Testing Complex Component
└─ Load: testing-strategy.md
```
### Node Backend Developer
```
Task Received
├─ CRUD Endpoints (Standard)
│ └─ Load: NOTHING (use role knowledge)
├─ Authentication/Authorization
│ └─ Load: security-guidelines.md
├─ Framework Selection
│ └─ Load: backend-patterns.md (framework comparison)
├─ Complex Queries / Performance Issues
│ └─ Load: database-optimization.md
└─ Background Jobs
└─ Load: job queue patterns
```
### Solution Architect
```
Task Received
├─ Requirements Analysis
│ └─ Load: NOTHING except requirements
├─ Technology Stack Decision
│ └─ Load: technology-stack-guide.md
├─ Architecture Pattern Selection
│ └─ Load: architecture-patterns.md
├─ Deployment Strategy
│ └─ Load: deployment-strategies.md
├─ Security/Compliance Requirements
│ └─ Load: security-guidelines.md
└─ Implementation Details
└─ SKIP (delegate to implementation agents)
```
### API Developer
```
Task Received
├─ REST API Design
│ └─ Load: api-implementation-patterns.md (REST section ONLY)
├─ GraphQL API Design
│ └─ Load: api-implementation-patterns.md (GraphQL section ONLY)
├─ tRPC API Design
│ └─ Load: api-implementation-patterns.md (tRPC section ONLY)
├─ Auth Endpoints
│ └─ Load: security-guidelines.md
└─ Standard CRUD
└─ Load: NOTHING (use OpenAPI spec template)
```
### TypeScript Expert
```
Task Received
├─ Project Setup / tsconfig
│ └─ Load: development-guidelines.md (TS section)
├─ Standard Type Definitions
│ └─ Load: NOTHING (use role knowledge)
├─ Complex Generics / Advanced Types
│ └─ Load: TypeScript advanced patterns
└─ JS to TS Migration
└─ Load: migration guide
```
## Context Loading Patterns
### Pattern 1: Minimal Start
**When**: Every task
**Load**: Role + core-principles.md + task requirements only
**Skip**: Everything else until decision point
**Tokens**: ~500-700
### Pattern 2: Checkpoint-Based
**When**: Continuing multi-phase workflow
**Load**: Most recent checkpoint + current task
**Skip**: Full phase history, archived discussions
**Tokens**: ~800-1,200
### Pattern 3: Decision-Triggered
**When**: Making specific technology/pattern choice
**Load**: Single guide for that decision
**Skip**: All other guides
**Tokens**: +300-1,000 (per decision)
### Pattern 4: Section-Only Loading
**When**: Loading large reference file
**Load**: Only relevant section (e.g., "REST API" from api-implementation-patterns.md)
**Skip**: Other sections
**Tokens**: ~200-500 vs ~1,500-3,000 (full file)
### Pattern 5: Progressive Expansion
**When**: Complex task with multiple decision points
**Load**: Stage 1 (minimal) → Stage 2 (decision guides) → Stage 3 (implementation patterns)
**Skip**: Future stage context until needed
**Tokens**: Spread across stages, create checkpoints between
## Red Flags: When You're Over-Loading
🚩 **Red Flag Signals**:
- Loading >3 data files for single task
- Loading files "just in case"
- Loading before knowing what decision you're making
- Loading other agents' domain-specific guides
- Loading implementation details during architecture phase
- Loading optimization guides before having performance issue
## Token Budget Guidelines
### By Task Complexity
**Simple Task** (component, CRUD endpoint, type definition):
- Budget: <1,000 tokens total
- Load: Role + task only
**Medium Task** (feature, API design, review):
- Budget: 1,000-2,000 tokens
- Load: Role + task + 1-2 specific guides
**Complex Task** (architecture, migration, system design):
- Budget: 2,000-4,000 tokens
- Load: Role + task + multiple guides
- Strategy: Use checkpoints to compress
**Multi-Phase Workflow**:
- Budget: <10,000 tokens cumulative
- Strategy: Checkpoint after each phase (compress to ~1,000 tokens)
### Budget Triggers
**Create Checkpoint When**:
- Phase context exceeds 3,000 tokens
- Transitioning between workflow phases
- Completed major decision point
- 5+ agent interactions in sequence
**Archive Context When**:
- Discussion exceeds 1,000 tokens
- Implementation details complete
- Decision finalized (keep conclusion only)
## Validation Checklist
Before loading any file, verify:
- [ ] I am making a specific decision RIGHT NOW (not "might need later")
- [ ] This decision is my role's responsibility
- [ ] This information is NOT in checkpoint/requirements already
- [ ] I cannot use my role knowledge for this decision
- [ ] I am loading ONLY the relevant section, not entire file
- [ ] I have not already loaded >2 guides for this task
- [ ] This will help me complete THIS task, not future tasks
**If any checkbox is unchecked → Don't load it**
## Examples
### ✅ Good: JIT Loading
**Task**: Build user authentication system
**Sequence**:
1. Start: Load role + core-principles.md + requirements (~500 tokens)
2. Decision: Auth approach → Load security-guidelines.md (~1,000 tokens)
3. Decision: API design → Load api-implementation-patterns.md (REST section ~200 tokens)
4. Implementation: Use loaded context, skip additional guides
5. Total: ~1,700 tokens
### ❌ Bad: Upfront Loading
**Task**: Build user authentication system
**Sequence**:
1. Start: Load role + security-guidelines.md + api-implementation-patterns.md + database-optimization.md + deployment-strategies.md + best-practices.md (~6,000 tokens)
2. Use: Only security-guidelines.md and partial API patterns
3. Waste: ~4,000 tokens of unused context
**Problem**: Loaded everything upfront, used <40% of it
### ✅ Good: Section-Only Loading
**Task**: Design REST API for user service
**Sequence**:
1. Load: Role + task (~500 tokens)
2. Load: REST section from api-implementation-patterns.md (~200 tokens)
3. Skip: GraphQL, tRPC, WebSocket sections
4. Total: ~700 tokens vs ~1,500 if loaded full file
### ❌ Bad: Full File Loading
**Task**: Design REST API for user service
**Sequence**:
1. Load: Full api-implementation-patterns.md (~1,500 tokens)
2. Use: Only REST section (~200 tokens worth)
3. Waste: ~1,300 tokens of GraphQL/tRPC/WebSocket patterns
## Summary
**Golden Rules**:
1. Start minimal (role + task + requirements)
2. Load on decision points (not before)
3. Load sections, not full files
4. Ask 4 questions before loading
5. Create checkpoints when >3K tokens
6. Archive verbose context immediately
**Target**: <1,000 tokens for simple tasks, <2,000 for medium, <4,000 for complex
**Remember**: Context is expensive. Every token loaded must directly contribute to the current decision.

File diff suppressed because it is too large Load Diff

View File

@ -5,6 +5,19 @@
## Purpose
Define complete API contracts for a JavaScript/TypeScript backend to ensure frontend-backend alignment and enable parallel development.
## Context Budget
**Estimated Tokens**: ~1,500-3,000 tokens (complete API spec with 10-20 endpoints)
**Complexity**: Medium-High (requires consistent contract definition across all endpoints)
**Context Window Usage**: ~8-15% of typical limit
**Token Efficiency per Endpoint**: ~100-150 tokens (TypeScript interfaces + docs)
**Token Efficiency**:
- Generate OpenAPI spec (YAML) - more compact than repeated examples
- Share common types across endpoints (pagination, error responses)
- Reference auth patterns doc instead of repeating for each endpoint
- Use TypeScript interfaces as source of truth, avoid duplicating in prose
## When to Use
- Before starting backend implementation
- When adding new API endpoints

View File

@ -5,6 +5,19 @@
## Purpose
Document the technical architecture of a JavaScript/TypeScript full-stack application to guide implementation and ensure team alignment.
## Context Budget
**Estimated Tokens**: ~2,000-4,000 tokens (complete architecture doc)
**Complexity**: High (requires comprehensive system design across frontend, backend, database, infrastructure)
**Context Window Usage**: ~10-20% of typical limit
**Input Context Required**: ~500-1,000 tokens (requirements, constraints, scale estimates)
**Token Efficiency**:
- Use architecture checklist to guide structure (avoid over-documentation)
- Reference external docs for standard patterns (e.g., link to Next.js docs instead of explaining)
- Focus on decisions and rationale, not technology tutorials
- Create separate ADR files for complex decisions, reference in main doc
## When to Use
- Starting a new greenfield project
- Major system refactoring

View File

@ -5,11 +5,24 @@
## Purpose
Compact accumulated context from workflow phases into concise summaries that maintain essential information while reducing token usage for subsequent phases. Implements the "compaction strategy" from effective context engineering.
## Context Budget
**Estimated Tokens**: ~500-1,000 tokens (checkpoint output)
**Complexity**: Medium (requires analyzing phase outputs and extracting key decisions)
**Context Window Usage**: ~5-10% of typical 200K token limit
**Token Reduction**: Target 80%+ reduction from original phase context (e.g., 5,000 tokens → 1,000 tokens)
**Budget Triggers**:
- Create checkpoint when phase context exceeds 3,000-5,000 tokens
- Archive verbose discussions exceeding 1,000 tokens
- Compress multi-agent conversations with 5+ exchanges
## When to Use
- After major decision points (architecture chosen, tech stack selected)
- Before transitioning between workflow phases
- After 5+ sequential agent interactions
- When detailed discussions need to be archived with key decisions preserved
- **Token-based trigger**: When phase context >3K tokens
## Prerequisites
- Completed phase with multiple artifacts or discussions

View File

@ -5,6 +5,19 @@
## Purpose
Create detailed, actionable development stories for JavaScript/TypeScript full-stack features that enable developers to implement without additional design decisions.
## Context Budget
**Estimated Tokens**: ~800-1,500 tokens per story
**Complexity**: Medium-High (requires detailed technical specification and acceptance criteria)
**Context Window Usage**: ~5-8% per story
**Input Context Required**: ~1,000-2,000 tokens (architecture doc + requirements)
**Token Efficiency**:
- Reference architecture doc by path, don't repeat full stack details
- Point to shared type definitions instead of duplicating interfaces
- Use template structure to minimize boilerplate
- Each story should be self-contained but reference shared docs
## When to Use
- Breaking down epics into implementable stories
- Converting architecture documents into development tasks

View File

@ -17,11 +17,26 @@ workflow:
- agent: js-solution-architect
reviews: technical_impact
requires: feature-requirements.md
context_budget: 1500-2500 tokens
loads_if_needed:
- security-guidelines.md (IF authentication/authorization changes)
- best-practices.md (IF introducing new patterns)
- architecture-patterns.md (IF architectural changes)
notes: Assess technical impact on existing architecture. Identify affected components, database changes, API modifications, and integration points.
- 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
@ -35,7 +50,32 @@ workflow:
requires:
- feature-requirements.md
- architecture-impact-checkpoint.md
notes: "Create detailed technical spec with file changes, new components/endpoints, types, tests, and implementation steps. Reference checkpoint for architecture context. SAVE to docs/features/[feature-name]/"
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

View File

@ -24,15 +24,38 @@ workflow:
- 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 (ALWAYS - for stack comparison)
- deployment-strategies.md (IF hosting decisions needed)
- security-guidelines.md (IF handling sensitive data)
- 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. SAVE OUTPUT: Copy to docs/architecture/ folder."
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
@ -46,11 +69,38 @@ workflow:
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. SAVE OUTPUT: Copy to docs/architecture/ folder."
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