Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:53:07 +08:00
commit b5ab310674
19 changed files with 5687 additions and 0 deletions

View File

@@ -0,0 +1,495 @@
# Example: File Coordination for Parallel Agents
This example shows how to prevent file path collisions when multiple agents create documentation in parallel.
## Scenario
**User Request:** "Document our codebase patterns for authentication, caching, and error handling"
## Initial Decomposition (Incorrect)
```
❌ WRONG APPROACH
Activities:
1. Document authentication patterns
2. Document caching patterns
3. Document error handling patterns
All parallel, all OUTPUT: "docs/patterns/[pattern-name].md"
Problem: What if agents choose same filename?
- Agent 1 might create: docs/patterns/auth.md
- Agent 2 might create: docs/patterns/cache.md
- Agent 3 might create: docs/patterns/error.md
OR worse:
- Agent 1: docs/patterns/authentication.md
- Agent 2: docs/patterns/authentication-patterns.md
- Both trying to document auth? Collision!
Result: Ambiguous, potential collisions, inconsistent naming
```
## Correct Decomposition (File Coordination)
```
✅ CORRECT APPROACH
Activities:
1. Document authentication patterns
- OUTPUT: docs/patterns/authentication-flow.md (EXPLICIT PATH)
2. Document caching patterns
- OUTPUT: docs/patterns/caching-strategy.md (EXPLICIT PATH)
3. Document error handling patterns
- OUTPUT: docs/patterns/error-handling.md (EXPLICIT PATH)
File Coordination Check:
✅ All paths explicit and unique
✅ No ambiguity in naming
✅ No collision risk
Status: SAFE FOR PARALLEL EXECUTION
```
## Agent Prompts with File Coordination
### Agent 1: Authentication Pattern
```
DISCOVERY_FIRST: Before starting, check existing documentation:
- List docs/patterns/ directory
- Search for existing auth-related files
- Note naming conventions used
- Check if authentication-flow.md already exists
FOCUS: Document authentication patterns discovered in codebase
- JWT token generation and validation
- Password hashing (bcrypt usage)
- Session management approach
- Protected route patterns
- Error responses for auth failures
EXCLUDE:
- Don't document caching (Agent 2 handles this)
- Don't document error handling generally (Agent 3 handles this)
- Don't create multiple files (single document)
- Don't modify existing authentication files if they exist
CONTEXT: Documenting patterns found in src/middleware/auth.*, src/routes/auth.*
- Focus on how authentication works, not implementation details
- Use pattern template: docs/templates/pattern-template.md
- Follow existing documentation style
OUTPUT: EXACTLY this path: docs/patterns/authentication-flow.md
- If file exists: STOP and report (don't overwrite)
- If file doesn't exist: Create new
- Use pattern template structure
- Include code examples from codebase
SUCCESS: Authentication patterns documented
- File created at exact path specified
- Follows pattern template
- Includes JWT, bcrypt, and session patterns
- Code examples are accurate
- No collision with other agents
TERMINATION:
- Documentation complete at specified path
- File already exists (report to user)
- No authentication patterns found in codebase
```
### Agent 2: Caching Pattern
```
DISCOVERY_FIRST: Before starting, check existing documentation:
- List docs/patterns/ directory
- Search for existing cache-related files
- Note naming conventions
- Check if caching-strategy.md already exists
FOCUS: Document caching patterns discovered in codebase
- Redis usage patterns
- Cache key naming conventions
- TTL (time-to-live) strategies
- Cache invalidation approaches
- What gets cached and why
EXCLUDE:
- Don't document authentication (Agent 1 handles this)
- Don't document error handling (Agent 3 handles this)
- Don't create multiple files (single document)
- Don't overlap with Agent 1's work
CONTEXT: Documenting patterns found in src/cache/*, src/services/*
- Focus on caching strategy, not Redis API details
- Use pattern template
- Follow existing documentation style
OUTPUT: EXACTLY this path: docs/patterns/caching-strategy.md
- If file exists: STOP and report (don't overwrite)
- If file doesn't exist: Create new
- Use pattern template structure
- Include code examples from codebase
SUCCESS: Caching patterns documented
- File created at exact path specified
- Follows pattern template
- Includes Redis patterns and cache strategies
- No collision with other agents
TERMINATION:
- Documentation complete at specified path
- File already exists (report)
- No caching patterns found
```
### Agent 3: Error Handling Pattern
```
DISCOVERY_FIRST: Before starting, check existing documentation:
- List docs/patterns/ directory
- Search for existing error-related files
- Note naming conventions
- Check if error-handling.md already exists
FOCUS: Document error handling patterns discovered in codebase
- Error class hierarchy
- HTTP status code mapping
- Error response format
- Logging strategy for errors
- Recovery patterns
EXCLUDE:
- Don't document authentication (Agent 1's domain)
- Don't document caching (Agent 2's domain)
- Don't create multiple files
- Don't overlap with other agents
CONTEXT: Documenting patterns found in src/errors/*, src/middleware/error.*
- Focus on error handling strategy and patterns
- Use pattern template
- Follow existing documentation style
OUTPUT: EXACTLY this path: docs/patterns/error-handling.md
- If file exists: STOP and report (don't overwrite)
- If file doesn't exist: Create new
- Use pattern template structure
- Include code examples
SUCCESS: Error handling patterns documented
- File created at exact path specified
- Follows pattern template
- Includes error classes and response patterns
- No collision with other agents
TERMINATION:
- Documentation complete at specified path
- File already exists (report)
- No error handling patterns found
```
## File Coordination Checklist
Before launching these agents:
```
📋 File Coordination Pre-Flight Check
Agent 1 OUTPUT: docs/patterns/authentication-flow.md
Agent 2 OUTPUT: docs/patterns/caching-strategy.md
Agent 3 OUTPUT: docs/patterns/error-handling.md
✅ All paths are explicit (no ambiguity)
✅ All paths are unique (no two agents write same file)
✅ All paths follow convention (docs/patterns/[name].md)
✅ All agents instructed to check if file exists first
✅ All agents instructed to STOP if collision detected
File Collision Risk: NONE
Safe to launch in parallel: YES
```
## Execution Flow
### Launch All Three Agents in Parallel
```
🚀 Launching 3 parallel documentation agents
Agent 1: Authentication Pattern → RUNNING
TARGET: docs/patterns/authentication-flow.md
Agent 2: Caching Pattern → RUNNING
TARGET: docs/patterns/caching-strategy.md
Agent 3: Error Handling Pattern → RUNNING
TARGET: docs/patterns/error-handling.md
File coordination: ✅ All unique paths
Collision risk: ✅ None
Parallel safety: ✅ Confirmed
```
### Monitoring for Collisions
```
⏳ Agents running...
[Agent 1] Checking: docs/patterns/authentication-flow.md → NOT EXISTS
[Agent 1] Safe to create → PROCEEDING
[Agent 2] Checking: docs/patterns/caching-strategy.md → NOT EXISTS
[Agent 2] Safe to create → PROCEEDING
[Agent 3] Checking: docs/patterns/error-handling.md → NOT EXISTS
[Agent 3] Safe to create → PROCEEDING
No collisions detected. All agents proceeding independently.
```
### Completion
```
Agent 1: COMPLETE ✅ (22 minutes)
Created: docs/patterns/authentication-flow.md (3.2 KB)
Agent 2: COMPLETE ✅ (18 minutes)
Created: docs/patterns/caching-strategy.md (2.8 KB)
Agent 3: COMPLETE ✅ (25 minutes)
Created: docs/patterns/error-handling.md (4.1 KB)
All agents complete. No collisions occurred.
```
## Results
```
📁 docs/patterns/
├── authentication-flow.md ✅ Created by Agent 1
├── caching-strategy.md ✅ Created by Agent 2
└── error-handling.md ✅ Created by Agent 3
```
**Total time:** 25 minutes (parallel)
**Sequential would take:** 65 minutes
**Time saved:** 40 minutes (61% faster)
## Alternative Coordination Strategies
### Strategy 1: Directory Separation
If agents might create multiple files:
```
Agent 1 OUTPUT: docs/patterns/authentication/
- flow.md
- jwt-tokens.md
- session-management.md
Agent 2 OUTPUT: docs/patterns/caching/
- redis-usage.md
- invalidation.md
- key-naming.md
Agent 3 OUTPUT: docs/patterns/error-handling/
- error-classes.md
- response-format.md
- recovery-patterns.md
```
**Result:** Each agent owns a directory, no file collisions possible.
### Strategy 2: Timestamp-Based Naming
For logs or reports that accumulate:
```
Agent 1 OUTPUT: logs/auth-analysis-2025-01-24-10-30-00.md
Agent 2 OUTPUT: logs/cache-analysis-2025-01-24-10-30-00.md
Agent 3 OUTPUT: logs/error-analysis-2025-01-24-10-30-00.md
```
**Result:** Timestamps ensure uniqueness even if same topic.
### Strategy 3: Agent ID Namespacing
When dynamic number of agents:
```
For each module in [moduleA, moduleB, moduleC, moduleD]:
Launch agent with OUTPUT: analysis/module-${MODULE_NAME}.md
Results:
- analysis/module-moduleA.md
- analysis/module-moduleB.md
- analysis/module-moduleC.md
- analysis/module-moduleD.md
```
**Result:** Template-based naming prevents collisions.
## What Could Go Wrong (Anti-Patterns)
### ❌ Anti-Pattern 1: Ambiguous Paths
```
BAD:
Agent 1 OUTPUT: "Create pattern documentation"
Agent 2 OUTPUT: "Document caching patterns"
Problem: Where exactly? What filename?
Result: Agents might choose same name or wrong location
```
### ❌ Anti-Pattern 2: Overlapping Domains
```
BAD:
Agent 1 FOCUS: "Document authentication and security"
Agent 2 FOCUS: "Document security patterns"
Problem: Both might document auth security!
Result: Duplicate or conflicting documentation
```
**Fix:** Clear FOCUS boundaries, explicit EXCLUDE
### ❌ Anti-Pattern 3: No Existence Check
```
BAD:
OUTPUT: docs/patterns/auth.md
(No instruction to check if exists)
Problem: If file exists, agent might overwrite
Result: Lost documentation
```
**Fix:** Always include existence check in FOCUS or OUTPUT
### ❌ Anti-Pattern 4: Generic Filenames
```
BAD:
Agent 1 OUTPUT: docs/patterns/pattern.md
Agent 2 OUTPUT: docs/patterns/patterns.md
Agent 3 OUTPUT: docs/patterns/pattern-doc.md
Problem: All similar, confusing, might collide
Result: Unclear which agent created what
```
**Fix:** Descriptive, specific filenames
## File Coordination Best Practices
### 1. Explicit Paths
**Always specify exact OUTPUT path:**
```
OUTPUT: docs/patterns/authentication-flow.md
NOT: "Document authentication patterns"
```
### 2. Unique Names
**Ensure all agents have unique filenames:**
```
Before launching:
- Agent 1: authentication-flow.md
- Agent 2: caching-strategy.md
- Agent 3: error-handling.md
✅ All unique → SAFE
```
### 3. Existence Checks
**Instruct agents to check before creating:**
```
OUTPUT: docs/patterns/authentication-flow.md
- If file exists: STOP and report (don't overwrite)
- If file doesn't exist: Create new
```
### 4. Clear Boundaries
**Use EXCLUDE to prevent overlap:**
```
Agent 1:
FOCUS: Document authentication
EXCLUDE: Don't document caching (Agent 2) or errors (Agent 3)
Agent 2:
FOCUS: Document caching
EXCLUDE: Don't document auth (Agent 1) or errors (Agent 3)
```
### 5. Validation
**Check coordination before launching:**
```
Checklist:
- [ ] All paths explicit
- [ ] All paths unique
- [ ] All agents have existence checks
- [ ] Clear FOCUS boundaries
- [ ] No overlap in domains
```
## Integration with Documentation Skill
When these agents complete, documentation skill may activate:
```
Agent 1 completes → Creates authentication-flow.md
Documentation skill notices "pattern" created
Checks: Is this in correct location? (docs/patterns/ ✅)
Checks: Does it follow template? (✅)
Checks: Should it be cross-referenced? (Yes)
Documentation skill adds cross-references:
- Links to related authentication interfaces
- Links to domain rules about user permissions
```
**Coordination:** Agent-delegation ensures unique paths, documentation skill ensures quality and linking.
## Lessons Learned
### What Worked
**Explicit paths:** Zero ambiguity, zero collisions
**Existence checks:** Prevented accidental overwrites
**Clear boundaries:** No domain overlap
**Parallel execution:** 61% time savings
### What to Watch For
⚠️ **Naming conventions:** Ensure consistency (kebab-case vs snake_case)
⚠️ **Template usage:** All agents should use same template
⚠️ **Directory structure:** Verify docs/patterns/ exists before launching
## Reusable Coordination Template
For any parallel file creation:
```
1. List all files to be created
2. Verify all paths are unique
3. Add existence checks to OUTPUT
4. Use EXCLUDE to prevent overlap
5. Launch in parallel with confidence
```
**This prevents:**
- File path collisions
- Accidental overwrites
- Domain overlap
- Naming inconsistencies

View File

@@ -0,0 +1,337 @@
# Example: Parallel Research Delegation
This example shows how to decompose a research task into parallel specialist activities.
## Scenario
**User Request:** "Research competitive landscape for our B2B SaaS pricing strategy"
## Task Decomposition
```
Original Task: Research competitive landscape for B2B SaaS pricing
Activities Identified:
1. Analyze Competitor A (Salesforce) pricing
- Expertise: Market research
- Output: Pricing analysis document
- Dependencies: None
2. Analyze Competitor B (HubSpot) pricing
- Expertise: Market research
- Output: Pricing analysis document
- Dependencies: None
3. Analyze Competitor C (Zendesk) pricing
- Expertise: Market research
- Output: Pricing analysis document
- Dependencies: None
4. Synthesize competitive findings
- Expertise: Strategic analysis
- Output: Unified competitive strategy
- Dependencies: Activities 1, 2, 3
Execution Strategy: Mixed
- Parallel: Activities 1-3 (independent research)
- Sequential: Activity 4 (requires all results)
Reasoning: Each competitor analysis is independent. Synthesis must wait for all analyses to complete.
```
## Agent Prompts Generated
### Agent 1: Salesforce Analysis
```
FOCUS: Research Salesforce's B2B SaaS pricing strategy
- Identify all pricing tiers (Essentials, Professional, Enterprise, Unlimited)
- Map features to each tier
- Note promotional strategies and discounts
- Calculate price-per-user for each tier
- Identify what features drive tier upgrades
EXCLUDE:
- Don't analyze their technology stack or implementation
- Don't make pricing recommendations yet (synthesis phase)
- Don't compare to other competitors (separate analyses)
- Don't analyze Salesforce Platform (focus on CRM product)
CONTEXT: We're researching competitive landscape for our B2B SaaS pricing strategy.
- Target market: Mid-market companies (100-500 employees)
- Looking for pricing patterns and positioning insights
- Focus on transparent, public pricing only
OUTPUT: Structured analysis document including:
- Pricing Tiers Table (tier name, price, billing cycle)
- Feature Matrix by Tier (features mapped to each tier)
- Key Insights (3-5 bullet points about their strategy)
- Notable Patterns (what we can learn from their approach)
- Competitive Positioning (how they position each tier)
SUCCESS: Complete analysis with actionable data
- All publicly available tiers documented
- Features accurately mapped to tiers
- Insights are specific and evidence-based
- Patterns identified are relevant to our market
TERMINATION:
- Analysis complete with all sections filled
- Information not publicly available (document what's missing)
- Maximum 2 hours of research time reached
```
### Agent 2: HubSpot Analysis
```
FOCUS: Research HubSpot's B2B SaaS pricing strategy
- Identify all pricing tiers (Starter, Professional, Enterprise)
- Map features to each tier
- Note freemium offering and upgrade triggers
- Calculate price-per-contact for marketing hub
- Identify bundling strategy across products
EXCLUDE:
- Don't analyze technology implementation
- Don't make pricing recommendations yet
- Don't compare to other competitors
- Don't analyze HubSpot Academy or services pricing
CONTEXT: Competitive landscape research for B2B SaaS pricing.
- Target market: Mid-market companies (100-500 employees)
- Interest in freemium-to-paid conversion strategies
- Focus on Marketing Hub and Sales Hub pricing
OUTPUT: Structured analysis document including:
- Pricing Tiers Table
- Feature Matrix by Tier
- Freemium Analysis (what's free, what triggers upgrade)
- Key Insights (3-5 bullet points)
- Bundling Strategy (how products bundle together)
- Notable Patterns
SUCCESS: Complete analysis with freemium insights
- All tiers documented
- Freemium model understood
- Bundle pricing analyzed
- Insights are actionable
TERMINATION:
- Analysis complete
- Information unavailable
- 2 hours research time reached
```
### Agent 3: Zendesk Analysis
```
FOCUS: Research Zendesk's B2B SaaS pricing strategy
- Identify all pricing tiers (Suite Team, Growth, Professional, Enterprise)
- Map features to each tier
- Note per-agent pricing model
- Analyze add-on pricing strategy
- Identify what drives customer to higher tiers
EXCLUDE:
- Don't analyze implementation details
- Don't make recommendations yet
- Don't compare to competitors
- Don't analyze Zendesk Sell (focus on Support product)
CONTEXT: Competitive research for B2B SaaS pricing strategy.
- Target market: Mid-market companies
- Interest in per-seat vs per-usage pricing models
- Focus on customer support software pricing
OUTPUT: Structured analysis including:
- Pricing Tiers Table
- Feature Matrix by Tier
- Per-Agent Economics (cost per agent at scale)
- Add-On Pricing (what extras cost money)
- Key Insights (3-5 bullet points)
- Upgrade Drivers (what makes customers move up tiers)
SUCCESS: Complete analysis with per-seat insights
- All tiers documented
- Per-agent model understood
- Add-on strategy mapped
- Insights are specific
TERMINATION:
- Analysis complete
- Information unavailable
- 2 hours research reached
```
### Agent 4: Synthesis (Sequential, after 1-3)
```
FOCUS: Synthesize competitive pricing findings into unified strategy insights
EXCLUDE:
- Don't create our pricing (separate decision)
- Don't add new competitor research
- Don't analyze product features (stick to pricing patterns)
CONTEXT: We have three completed competitor analyses.
- Salesforce analysis: [Results from Agent 1]
- HubSpot analysis: [Results from Agent 2]
- Zendesk analysis: [Results from Agent 3]
- Goal: Extract patterns and strategic insights
OUTPUT: Competitive Pricing Strategy Document including:
- Cross-Competitor Patterns (themes across all three)
- Pricing Model Comparison (per-user vs per-contact vs per-usage)
- Tier Strategy Analysis (how competitors structure tiers)
- Freemium Insights (who uses it, how it works)
- Feature Differentiation (what features separate tiers)
- Positioning Opportunities (gaps or opportunities for us)
- Strategic Recommendations (3-5 actionable insights)
SUCCESS: Unified synthesis with strategic value
- Patterns identified across competitors
- Comparisons are fair and evidence-based
- Recommendations are actionable
- No contradiction between analyses
TERMINATION:
- Synthesis complete
- Conflicting data needs clarification (escalate)
- All sections filled
```
## Execution Flow
### Phase 1: Launch Parallel Research (Agents 1-3)
```
🚀 Launching 3 parallel research agents
Agent 1: Salesforce Analysis → RUNNING
Agent 2: HubSpot Analysis → RUNNING
Agent 3: Zendesk Analysis → RUNNING
File Coordination Check:
✅ Agent 1 OUTPUT: research/salesforce-pricing.md
✅ Agent 2 OUTPUT: research/hubspot-pricing.md
✅ Agent 3 OUTPUT: zendesk-pricing.md
✅ All paths unique - No collision risk
Parallel Safety Check:
✅ Independent tasks - No dependencies
✅ Read-only research - No shared state
✅ Separate validation - Each can be reviewed independently
✅ Won't block - Different data sources
Status: ✅ SAFE FOR PARALLEL EXECUTION
```
### Phase 2: Await Completion
```
⏳ Waiting for parallel agents...
Agent 1: COMPLETE ✅ (45 minutes)
- Salesforce analysis delivered
- All sections complete
- 4 tiers documented
Agent 2: COMPLETE ✅ (52 minutes)
- HubSpot analysis delivered
- Freemium model analyzed
- 3 tiers + free tier documented
Agent 3: COMPLETE ✅ (38 minutes)
- Zendesk analysis delivered
- Per-agent model mapped
- 4 tiers + add-ons documented
All parallel agents complete. Proceeding to synthesis.
```
### Phase 3: Launch Synthesis (Agent 4)
```
🚀 Launching synthesis agent
Agent 4: Competitive Synthesis → RUNNING
Context provided:
- Salesforce results (from Agent 1)
- HubSpot results (from Agent 2)
- Zendesk results (from Agent 3)
Agent 4: COMPLETE ✅ (25 minutes)
- Cross-competitor patterns identified
- 5 strategic recommendations generated
- Positioning opportunities highlighted
```
## Results
### Total Time: 52 minutes (parallel) + 25 minutes (synthesis) = 77 minutes
**Compare to sequential:** 45 + 52 + 38 + 25 = 160 minutes
**Time saved:** 83 minutes (52% faster)
### Deliverables
```
📁 research/
├── salesforce-pricing.md (Agent 1)
├── hubspot-pricing.md (Agent 2)
├── zendesk-pricing.md (Agent 3)
└── competitive-strategy.md (Agent 4 synthesis)
```
### Key Insights Generated
From the synthesis agent:
1. **Tiering Pattern:** All three use 3-4 tier structure with similar progression (basic → professional → enterprise)
2. **Pricing Models:** Mixed approaches
- Salesforce: Per-user, all-inclusive features
- HubSpot: Per-contact, freemium base
- Zendesk: Per-agent, add-on marketplace
3. **Feature Gating:** Core features in all tiers, advanced analytics/automation in top tiers
4. **Freemium:** Only HubSpot uses freemium successfully (strong upgrade triggers identified)
5. **Opportunity:** Gap in mid-market transparent pricing - competitors hide "contact sales" behind top tier
## Lessons Learned
### What Worked Well
**Parallel execution:** Saved 52% time
**Independent research:** No coordination overhead
**Synthesis phase:** Unified findings effectively
**Unique file paths:** No collisions
**Explicit FOCUS/EXCLUDE:** Agents stayed on task
### Improvements for Next Time
- Add time limits to prevent research rabbit holes
- Specify exact format (all agents used slightly different table formats)
- Request specific pricing data points (some agents missed cost-per-user calculations)
- Consider adding validation agent before synthesis (check data accuracy)
## Reusable Template
This pattern works for any parallel research:
```
1. Decompose research into independent topics
2. Create identical FOCUS/EXCLUDE templates
3. Customize context and output paths only
4. Launch all in parallel
5. Synthesis agent consolidates findings
```
**Use when:**
- Researching multiple competitors
- Analyzing multiple technologies
- Gathering multiple data sources
- Interviewing multiple stakeholders

View File

@@ -0,0 +1,504 @@
# Example: Sequential Build Delegation
This example shows how to coordinate dependent implementation tasks that must execute sequentially.
## Scenario
**User Request:** "Implement JWT authentication for our REST API"
## Task Decomposition
```
Original Task: Implement JWT authentication for REST API
Activities Identified:
1. Design authentication database schema
- Expertise: Database design
- Output: Schema design document
- Dependencies: None
2. Create database migration
- Expertise: Database implementation
- Output: Migration files
- Dependencies: Activity 1 (schema design)
3. Implement authentication middleware
- Expertise: Backend development
- Output: JWT middleware code
- Dependencies: Activity 2 (tables must exist)
4. Create auth endpoints (login/logout)
- Expertise: Backend development
- Output: Auth routes and controllers
- Dependencies: Activity 3 (middleware needed)
5. Add tests for auth flow
- Expertise: Test automation
- Output: Integration tests
- Dependencies: Activity 4 (endpoints must work)
Execution Strategy: Sequential
Reasoning: Each activity depends on the previous one's output. No parallelization possible in this chain.
Dependency Chain: 1 → 2 → 3 → 4 → 5
```
## Agent Prompts Generated
### Agent 1: Schema Design (First)
```
DISCOVERY_FIRST: Before starting, understand the environment:
- Check existing database structure: ls migrations/ or db/schema/
- Identify database system: PostgreSQL, MySQL, SQLite?
- Review existing table patterns: user-related tables
- Note naming conventions: snake_case, camelCase, PascalCase?
FOCUS: Design database schema for JWT authentication
- Users table (if not exists) with email, password_hash
- Sessions table for active JWT tokens
- Include created_at, updated_at timestamps
- Design appropriate indexes for performance
- Plan foreign key relationships
EXCLUDE:
- Don't create the migration yet (next task)
- Don't implement OAuth tables (separate feature)
- Don't modify existing user table if it exists
- Don't add two-factor auth tables (not in scope)
CONTEXT: Building JWT authentication for REST API.
- From security requirements: bcrypt hashing, cost factor 12
- Session expiry: 24 hours
- Email must be unique
- Follow project database conventions exactly
OUTPUT: Schema design document at docs/patterns/auth-database-schema.md
- Table definitions with column types
- Indexes and constraints
- Foreign key relationships
- Example data
SUCCESS: Schema designed and documented
- All required fields included
- Performance indexes identified
- Follows project conventions
- Ready for migration implementation
TERMINATION:
- Design complete and documented
- Blocked by missing existing schema info
```
### Agent 2: Database Migration (After Agent 1)
```
DISCOVERY_FIRST: Before starting, understand the environment:
- Check migration system: Knex, Sequelize, TypeORM, raw SQL?
- Find migration directory location
- Review existing migration file format
- Note up/down pattern used
FOCUS: Create database migration for authentication tables
- Implement users table from schema design
- Implement sessions table from schema design
- Add all indexes from schema design
- Create both up (create) and down (drop) migrations
- Follow migration naming conventions
EXCLUDE:
- Don't run the migration yet (separate step)
- Don't seed data (separate concern)
- Don't modify existing migrations
- Don't add tables not in schema design
CONTEXT: Implementing schema designed in previous step.
- Schema document: docs/patterns/auth-database-schema.md
- Tables: users (email, password_hash, created_at, updated_at)
- Tables: sessions (id, user_id, token_hash, expires_at, created_at)
- Indexes: users.email (unique), sessions.token_hash, sessions.user_id
OUTPUT: Migration file at [DISCOVERED_MIGRATION_PATH]/[timestamp]_create_auth_tables.js
- Up migration creates tables and indexes
- Down migration drops tables cleanly
- Follows project migration format
SUCCESS: Migration created and ready to run
- Matches schema design exactly
- Both up and down work correctly
- Follows project patterns
- No syntax errors
TERMINATION:
- Migration file created successfully
- Blocked by unclear migration system
- Migration format doesn't match project (document issue)
```
### Agent 3: JWT Middleware (After Agent 2)
```
DISCOVERY_FIRST: Before starting, understand the environment:
- Find existing middleware location: src/middleware/ or app/middleware/?
- Check JWT library in use: jsonwebtoken, jose, other?
- Review existing middleware patterns
- Note error handling style used
FOCUS: Implement JWT authentication middleware
- Verify JWT token from Authorization header
- Decode and validate token
- Check token against sessions table (not blacklisted)
- Attach user object to request
- Handle missing/invalid/expired tokens appropriately
EXCLUDE:
- Don't implement login/logout endpoints (next task)
- Don't implement token refresh (not in scope)
- Don't add rate limiting (separate concern)
- Don't implement permission checking (just authentication)
CONTEXT: JWT middleware for REST API authentication.
- JWT secret: from environment variable JWT_SECRET
- Token expiry: 24 hours
- Sessions table: check if token_hash exists and not expired
- Error responses: 401 for invalid/missing token
- Follow project error handling patterns
OUTPUT: Middleware file at [DISCOVERED_LOCATION]/auth.middleware.ts
- verifyJWT function (main middleware)
- Helper functions (decode, validate, etc.)
- Error handling for all cases
- TypeScript types if applicable
SUCCESS: Middleware implemented and ready to use
- Verifies JWT correctly
- Checks session validity
- Attaches user to request
- Handles all error cases
- Follows project patterns
TERMINATION:
- Middleware complete
- Blocked by missing JWT library
- Database connection pattern unclear
```
### Agent 4: Auth Endpoints (After Agent 3)
```
DISCOVERY_FIRST: Before starting, understand the environment:
- Find routes directory: src/routes/ or app/routes/?
- Check router library: Express, Fastify, Koa?
- Review existing route patterns
- Note controller/handler organization
FOCUS: Implement authentication endpoints
- POST /api/auth/login (email, password → JWT token)
- POST /api/auth/logout (invalidate current session)
- Use auth middleware from previous step
- Create sessions table entry on login
- Remove sessions table entry on logout
EXCLUDE:
- Don't implement registration (separate feature)
- Don't implement password reset (separate feature)
- Don't add OAuth endpoints (separate feature)
- Don't implement GET /me endpoint (separate task)
CONTEXT: Auth endpoints using JWT middleware implemented in previous step.
- Middleware location: [from Agent 3 OUTPUT]
- Login validates: email format, password against bcrypt hash
- Login creates: session entry, JWT token with user_id claim
- Logout requires: valid JWT (use middleware)
- Logout invalidates: session entry in database
OUTPUT:
- Routes file at [DISCOVERED_LOCATION]/auth.routes.ts
- Controller file at [DISCOVERED_LOCATION]/auth.controller.ts
- Follow project route organization pattern
SUCCESS: Endpoints implemented and functional
- Login validates credentials correctly
- Login returns valid JWT
- Logout requires authentication
- Logout invalidates session
- All errors handled appropriately
- Follows project patterns
TERMINATION:
- Endpoints complete
- Blocked by unclear auth middleware interface
- bcrypt usage pattern unclear
```
### Agent 5: Integration Tests (After Agent 4)
```
DISCOVERY_FIRST: Before starting, understand the environment:
- Find test directory: tests/, __tests__/, spec/?
- Identify test framework: Jest, Mocha, Vitest?
- Review existing test patterns
- Note test database setup approach
FOCUS: Create integration tests for authentication flow
- Test successful login (valid credentials → JWT returned)
- Test failed login (invalid credentials → 401)
- Test logout (valid JWT → session invalidated)
- Test protected route with valid JWT (→ 200)
- Test protected route with invalid JWT (→ 401)
- Test protected route with no JWT (→ 401)
EXCLUDE:
- Don't test registration (not implemented)
- Don't test password reset (not implemented)
- Don't unit test internal functions (integration tests only)
- Don't test OAuth flows (not implemented)
CONTEXT: Testing JWT authentication implemented in previous steps.
- Endpoints: POST /api/auth/login, POST /api/auth/logout
- Middleware: JWT verification from auth.middleware.ts
- Test database: Use test database, clean between tests
- Follow project testing patterns exactly
OUTPUT: Test file at [DISCOVERED_LOCATION]/auth.integration.test.ts
- All test cases listed in FOCUS
- Setup and teardown (database, test user)
- Clear test descriptions
- Assertions verify correct behavior
SUCCESS: Complete test coverage for auth flow
- All tests pass
- Tests are independent (can run in any order)
- Database cleanup works correctly
- Follows project test patterns
- Coverage includes happy path and error cases
TERMINATION:
- Tests complete and passing
- Blocked by test framework unclear
- Test database setup pattern unclear
```
## Execution Flow
### Phase 1: Schema Design (Agent 1)
```
🚀 Launching Agent 1: Schema Design
Status: RUNNING
Time: 15 minutes
Agent 1: COMPLETE ✅
Output: docs/patterns/auth-database-schema.md
Deliverables:
- Users table design (5 columns + indexes)
- Sessions table design (5 columns + indexes)
- Foreign key relationship documented
- Performance considerations noted
Validation: ✅ Ready for migration implementation
```
### Phase 2: Database Migration (Agent 2)
```
🚀 Launching Agent 2: Database Migration
Dependencies: Agent 1 complete ✅
Context provided:
- Schema document from Agent 1
- Table definitions and indexes
Status: RUNNING
Time: 20 minutes
Agent 2: COMPLETE ✅
Output: migrations/20250124120000_create_auth_tables.js
Deliverables:
- Up migration creates both tables
- Down migration drops cleanly
- All indexes included
- Follows Knex migration pattern
Validation: ✅ Ready for middleware implementation
```
### Phase 3: JWT Middleware (Agent 3)
```
🚀 Launching Agent 3: JWT Middleware
Dependencies: Agent 2 complete ✅
Context provided:
- Migration created tables
- Database schema known
Status: RUNNING
Time: 30 minutes
Agent 3: COMPLETE ✅
Output: src/middleware/auth.middleware.ts
Deliverables:
- verifyJWT middleware function
- Token validation logic
- Session checking against database
- Error handling for all cases
Validation: ✅ Ready for endpoint implementation
```
### Phase 4: Auth Endpoints (Agent 4)
```
🚀 Launching Agent 4: Auth Endpoints
Dependencies: Agent 3 complete ✅
Context provided:
- Middleware from Agent 3
- Function signatures and usage
Status: RUNNING
Time: 35 minutes
Agent 4: COMPLETE ✅
Output:
- src/routes/auth.routes.ts
- src/controllers/auth.controller.ts
Deliverables:
- POST /api/auth/login endpoint
- POST /api/auth/logout endpoint
- Integration with middleware
- Error responses
Validation: ✅ Ready for testing
```
### Phase 5: Integration Tests (Agent 5)
```
🚀 Launching Agent 5: Integration Tests
Dependencies: Agent 4 complete ✅
Context provided:
- All endpoints from Agent 4
- Middleware from Agent 3
- Expected behavior
Status: RUNNING
Time: 25 minutes
Agent 5: COMPLETE ✅
Output: tests/integration/auth.test.ts
Deliverables:
- 6 integration tests
- Database setup/teardown
- All tests passing ✅
- 95% coverage of auth flow
Validation: ✅ Feature complete and tested
```
## Results
### Total Time: 125 minutes (sequential)
**Sequential necessary:** Each task depends on previous
**No parallelization possible** in this dependency chain
### Context Accumulation
Each agent received growing context:
- Agent 1: Fresh start
- Agent 2: Agent 1's schema design
- Agent 3: Agent 2's migration + Agent 1's schema
- Agent 4: Agent 3's middleware + all prior context
- Agent 5: All previous implementations
### Deliverables
```
📁 Project structure:
├── docs/patterns/
│ └── auth-database-schema.md (Agent 1)
├── migrations/
│ └── 20250124120000_create_auth_tables.js (Agent 2)
├── src/
│ ├── middleware/
│ │ └── auth.middleware.ts (Agent 3)
│ ├── routes/
│ │ └── auth.routes.ts (Agent 4)
│ └── controllers/
│ └── auth.controller.ts (Agent 4)
└── tests/integration/
└── auth.test.ts (Agent 5)
```
## Lessons Learned
### What Worked Well
**Clear dependency chain:** Each agent knew exactly what it needed
**Context accumulation:** Prior outputs informed each subsequent agent
**DISCOVERY_FIRST:** Ensured consistency with project patterns
**Validation at each step:** Caught issues before they propagated
### Challenges Encountered
⚠️ **Agent 2 Issue:** Initial migration didn't match project format
- **Solution:** Retry with more specific Knex pattern in CONTEXT
- **Lesson:** DISCOVERY_FIRST examples critical
⚠️ **Agent 3 Issue:** Used wrong JWT library (jose instead of jsonwebtoken)
- **Solution:** More explicit in EXCLUDE and CONTEXT
- **Lesson:** Specify exact libraries when project uses specific ones
⚠️ **Agent 5 Issue:** Tests didn't clean up database properly
- **Solution:** Retry with explicit teardown requirements
- **Lesson:** Test isolation must be explicit in SUCCESS criteria
### Improvements for Next Time
1. **Specify exact libraries** in CONTEXT (don't assume agent will discover)
2. **Include output of previous agent** verbatim in next agent's CONTEXT
3. **Validation step between agents** to catch issues before next dependency
4. **Checkpoint approach:** Allow user to review after each agent before launching next
## Reusable Template
This pattern works for any sequential build:
```
1. Identify dependency chain (what depends on what)
2. Order activities by dependencies
3. Each agent's CONTEXT includes prior agent outputs
4. Launch sequentially, validate each before next
5. Accumulate context as you go
```
**Use when:**
- Building implementation layers (DB → Logic → API → UI)
- Pipeline-style workflows (Design → Build → Test → Deploy)
- Learning workflows (Research → Design → Implement → Validate)
- Any task where B genuinely needs A's output
## Comparison: What If We Tried Parallel?
**Attempted parallel (would fail):**
```
Agent 2 (Migration): Needs Agent 1's schema design → BLOCKED
Agent 3 (Middleware): Needs Agent 2's tables to exist → BLOCKED
Agent 4 (Endpoints): Needs Agent 3's middleware → BLOCKED
Agent 5 (Tests): Needs Agent 4's endpoints → BLOCKED
Result: All agents blocked or produce incorrect results
```
**Lesson:** Don't force parallelization when dependencies exist. Sequential is correct here.