This workflow maximizes efficiency and reliability when implementing new features in unknown codebases by using strategic sub-agent delegation and systematic discovery phases.
I need to implement [FEATURE DESCRIPTION] in this unfamiliar codebase. Follow this optimized workflow with strategic sub-agent delegation:
**PHASE 0 - ENHANCED CONTEXT PREPARATION (Main Agent):**
1. Check existing knowledge graph for this codebase
2. **IF SUBSTANTIAL KNOWLEDGE EXISTS:**
- Review stored architecture, patterns, and conventions
- Identify knowledge gaps specific to the new feature
- Create targeted discovery plan focusing only on unknown areas
- Skip to abbreviated discovery (Phase 1B)
3. **IF MINIMAL KNOWLEDGE EXISTS:**
- Proceed with full discovery workflow (Phase 1)
4. Create initial todo breakdown using todo_write
5. Quick read of key project files (README, package json, etc..) for immediate context if needed
**PHASE 1A - FOUNDATIONAL DISCOVERY (Single Sub-Agent) - For New Codebases:**
6. Sub-Agent: Comprehensive codebase overview including project structure, tech stack, build system, main entry points, core configuration files, and overall architectural patterns
7. Main Agent: Process foundational findings and create targeted Context DNA for Phase 1B
**PHASE 1B - TARGETED ANALYSIS (3 Parallel Sub-Agents with Context DNA):**
8. Sub-Agent A: Receive foundational Context DNA, focus on similar features and integration points for the target feature
9. Sub-Agent B: Receive foundational Context DNA, focus on testing frameworks, error handling patterns, and validation approaches
10. Sub-Agent C: Receive foundational Context DNA, focus on deployment patterns, environment configuration, and development workflows
11. Main Agent: Validate targeted findings, resolve conflicts, and create Context DNA for Phase 2
12. **CHECKPOINT 1**: If checkpoints enabled, summarize codebase findings and confirm approach
**PHASE 1A-ALT - KNOWLEDGE-BASED DISCOVERY (When Prior Knowledge Exists):**
6. Sub-Agent: Focus only on areas/patterns not previously explored related to new feature, leveraging existing knowledge graph
7. Main Agent: Validate discoveries, merge with existing knowledge, and create Context DNA for Phase 2 (skip Phase 1B)
8. **CHECKPOINT 1**: If checkpoints enabled, summarize new findings and integration approach
**PHASE 2 - SYNTHESIS & PLANNING (Main Agent + 1 Sub-Agent):**
13. Main Agent: Synthesize discoveries, update todos with specific implementation tasks, merge with existing knowledge
14. Sub-Agent: Receive Context DNA from Phase 1, create architecture diagram showing integration approach
15. Main Agent: Plan dependency-ordered implementation, create Context DNA for Phase 3 with specific sub-agent assignments
16. **CHECKPOINT 2**: If checkpoints enabled, present implementation plan and architecture for approval
**PHASE 3 - PARALLEL IMPLEMENTATION (Multiple Sub-Agents):**
17. Deploy independent sub-agents in parallel (each receives targeted Context DNA and strict scope isolation):
- Frontend Sub-Agent: Receive frontend-specific Context DNA, handle only frontend components and related files
- Backend Sub-Agent: Receive backend-specific Context DNA, handle only backend/API logic and related files
- Data Layer Sub-Agent: Receive data-specific Context DNA, handle only data/database changes and related files
- Config Sub-Agent: Receive config-specific Context DNA, handle only configuration updates and related files
**Each sub-agent must ignore errors outside their assigned scope**
18. Deploy dependent sub-agents sequentially:
- Integration Sub-Agent: Receive consolidated Context DNA from parallel agents, connect components after all parallel agents complete
- End-to-end functionality implementation
19. Sub-Agent: Receive testing Context DNA, implement comprehensive tests
20. Main Agent: Track progress, UPDATE existing knowledge graph with new observations, update todos as completed
21. **CHECKPOINT 3**: If checkpoints enabled, summarize implementation and confirm testing approach
**PHASE 4 - VERIFICATION & RECOVERY (Sequential Sub-Agents):**
22. Sub-Agent: Run full test suite, linting, build verification
23. Sub-Agent: Validate feature works end-to-end
24. Main Agent: Handle any failures with rollback strategy, final knowledge graph updates and enhancements
**DELEGATION RULES:**
- **Main Agent**: Quick reads, coordination, decision-making, conflict resolution, todo management, Context DNA creation and curation
- **Sub-Agents**: Detailed analysis, file modifications, comprehensive testing, diagram creation, Context DNA generation
- **Dependency Handling**: Clearly specify which sub-agents must complete before others start
- **Error Recovery**: Main agent validates sub-agent results at each phase before proceeding
**SUB-AGENT SCOPE ISOLATION:**
- **CRITICAL**: Implementation sub-agents must NEVER run global checks (pnpm check, tsc, npm test, etc.)
- Each sub-agent only works on their assigned files/components and validates only their own changes
- Sub-agents must IGNORE TypeScript/lint errors from other parts of the codebase that are outside their scope
- Sub-agents should ONLY fix errors in files they are explicitly assigned to modify
- If a sub-agent encounters errors in files they didn't create/modify, they must IGNORE them - another sub-agent will handle those
- Use file-specific validation only: check syntax in individual files, not project-wide compilation
**IMPLEMENTATION PHASE BOUNDARIES:**
- **Frontend Sub-Agent**: Only modify/validate frontend files (components, styles, frontend utils)
- **Backend Sub-Agent**: Only modify/validate backend files (API routes, server logic, backend utils)
- **Data Layer Sub-Agent**: Only modify/validate database/data files (models, migrations, queries)
- **Config Sub-Agent**: Only modify/validate configuration files (package.json, tsconfig, env files)
- **Integration Sub-Agent**: Only handles connecting the above components, runs after all others complete
**VALIDATION RESTRICTIONS DURING PHASE 3:**
- Sub-agents must NOT run: `pnpm check`, `tsc`, `npm test`, `npm run build`, or any global validation
- Sub-agents CAN run: syntax validation on their specific files only
- Sub-agents must focus on completing their assigned scope, not fixing the entire project
- Global validation happens ONLY in Phase 4 by dedicated verification sub-agents
**CONTEXT DNA COMMUNICATION PROTOCOL:**
- **Main Agent Responsibilities**: Create targeted Context DNA for each sub-agent containing only relevant information for their specific task
- **Sub-Agent Task Instructions**: Every sub-agent task must include the Context DNA template and instructions
- **Sub-Agent Requirements**: When receiving Context DNA, acknowledge and use it to inform your approach without redundant discovery
- **Context DNA Format**: Human-readable summary including architecture insights, code patterns, file locations, and task-specific guidance
- **Context DNA Generation**: Sub-agents must end their final summary with Context DNA for the next phase when applicable
**CRITICAL: Include this in every sub-agent task:**
**CONTEXT DNA INSTRUCTIONS:**
End your response with Context DNA for the next phase using this format:
**CONTEXT DNA FOR NEXT PHASE:**
**Key Findings:**
[Most important discoveries from your investigation]
**Architecture/Patterns Identified:**
[Code patterns, tech stack details, conventions found]
**Important Files/Locations:**
[Specific files with line numbers, key integration points]
**Guidance for Next Phase:**
[Specific recommendations for what the next agent should focus on]
**HUMAN FEEDBACK OPTIONS:**
- **Default**: Fully autonomous execution with final summary
- **Add "WITH CHECKPOINTS"**: Pause after each major phase for review and approval
- **Add "REVIEW PLANNING"**: Pause only after Phase 2 for architectural approval before implementation
- **Add "REVIEW IMPLEMENTATION"**: Pause only after Phase 3 to review changes before testing
**CHECKPOINT BEHAVIOR:**
When pausing, provide:
1. Clear summary of work completed in current phase
2. Key findings, decisions, or architectural choices made
3. Next steps planned with specific sub-agent assignments
4. Specific questions or concerns requiring input
5. Option to continue autonomously or modify approach
**FEATURE TO IMPLEMENT:**
[FEATURE DESCRIPTION] [OPTIONAL: WITH CHECKPOINTS | REVIEW PLANNING | REVIEW IMPLEMENTATION]
Begin with Phase 0 and proceed systematically through each phase with proper validation checkpoints.
CONTEXT DNA COMMUNICATION SYSTEM:
- Purpose: Efficient context transfer between phases without token bloat
- Format: Human-readable summaries of key findings, patterns, and guidance
- Flow: Main Agent curates Context DNA for each sub-agent based on their specific needs
- Content: Architecture insights, code patterns, file locations, implementation guidance
- Benefit: Sub-agents start with relevant context without redundant discovery
KNOWLEDGE ENHANCEMENT STRATEGY:
- Throughout implementation, UPDATE existing entities rather than create duplicates
- Add new observations to existing architectural components
- Create new relations between known and newly discovered components
- Enhance existing diagrams rather than creating entirely new ones
- Build upon previous implementation patterns and decisions
- Replace
[FEATURE DESCRIPTION]with detailed description of the feature you want to implement - Choose feedback level by adding one of the optional modifiers:
- No modifier = fully autonomous
WITH CHECKPOINTS= pause after each phaseREVIEW PLANNING= pause only after planning phaseREVIEW IMPLEMENTATION= pause only after implementation phase
- For subsequent features in the same codebase, this workflow will automatically leverage existing knowledge
- Paste the complete prompt to initiate the workflow
- Systematic Discovery: Prevents misunderstanding unfamiliar codebases
- Knowledge Reuse: Leverages previous implementations to accelerate subsequent features
- Parallel Execution: Maximizes efficiency through proper sub-agent delegation
- Scope Isolation: Prevents sub-agents from interfering with each other's work
- Context Preservation: Keeps main agent context clean while delegating detailed work
- Efficient Context Transfer: Context DNA system eliminates redundant discovery and token bloat
- Flexible Feedback: Allows human input at critical decision points
- Risk Mitigation: Validates findings before proceeding to implementation
- Cumulative Learning: Each feature implementation builds upon previous knowledge
Phase 1A → Phase 1B Context DNA:
**CONTEXT DNA FROM FOUNDATIONAL DISCOVERY:**
**Codebase Architecture:**
React frontend with Next.js 13 (app router), Express API backend, PostgreSQL with Prisma ORM. Authentication uses NextAuth.js with JWT strategy. Monorepo structure with /web and /api directories.
**Tech Stack & Build System:**
- TypeScript throughout, built with Next.js build system
- Package manager: pnpm with workspaces
- Testing: Jest + React Testing Library
- Linting: ESLint + Prettier with custom configs in .eslintrc.js
**Core Entry Points:**
- Frontend: /web/src/app/layout.tsx (root layout)
- API: /api/src/server.ts (Express app entry)
- Database: /api/src/db/client.ts (Prisma client)
**Main Configuration Files:**
- /package.json (workspace config)
- /web/next.config.js (Next.js config)
- /api/tsconfig.json (TypeScript config)
- /prisma/schema.prisma (database schema)
**Overall Patterns:**
Follows domain-driven design with clear separation between web and API. Uses middleware pattern for cross-cutting concerns. Database-first approach with Prisma migrations.
Phase 1B → Phase 2 Context DNA:
**CONTEXT DNA FROM TARGETED ANALYSIS:**
**Similar Features Found:**
User management system in /web/src/app/users demonstrates standard CRUD pattern. Auth flow in /web/src/app/auth shows form handling with validation.
**Testing Patterns:**
Jest tests in __tests__ directories alongside source files. Integration tests use @testing-library/react. API tests use supertest with test database.
**Error Handling & Validation:**
- Frontend: react-hook-form + zod schemas for validation
- API: express-validator middleware + global error handler
- Error boundaries implemented at page level in /web/src/components/ErrorBoundary.tsx
**Development Workflow:**
- Local development uses docker-compose for database
- Hot reload enabled for both frontend and API
- Pre-commit hooks run linting and type checking
- CI/CD pipeline defined in .github/workflows/
- Sub-agents running global checks and seeing other agents' errors
- Parallel agents working on the same files simultaneously (eliminated by sequential→parallel discovery)
- Overlapping discovery work between parallel sub-agents (solved by foundational→targeted approach)
- Insufficient discovery leading to architectural mismatches
- Context window exhaustion from detailed analysis in main thread
- Proceeding with implementation before understanding existing patterns
- Rediscovering known architecture in subsequent feature implementations
- Creating duplicate knowledge instead of enhancing existing understanding
- Context loss between sub-agent phases causing redundant work
- Token bloat from passing full discovery results to implementation agents
Add Context DNA Communication Protocol for shared context between main agent and sub agents.