Complete guide for working with existing codebases
Reading Time: ~35 minutes
Jump to:
- Quick Reference - Commands and files
- Common Scenarios - Real-world examples
- Best Practices - Success tips
Brownfield projects involve working within existing codebases rather than starting fresh:
- Bug fixes - Single file changes
- Small features - Adding to existing modules
- Feature sets - Multiple related features
- Major integrations - Complex architectural additions
- System expansions - Enterprise-scale enhancements
Key Difference from Greenfield: You must understand and respect existing patterns, architecture, and constraints.
Core Principle: AI agents need comprehensive documentation to understand existing code before they can effectively plan or implement changes.
For complete track details, see Scale Adaptive System.
Brownfield tracks at a glance:
| Track | Scope | Typical Stories | Key Difference |
|---|---|---|---|
| Quick Flow | Bug fixes, small features | 1-15 | Must understand affected code and patterns |
| BMad Method | Feature sets, integrations | 10-50+ | Integrate with existing architecture |
| Enterprise Method | Enterprise expansions | 30+ | Full system documentation + compliance required |
Note: Story counts are guidance, not definitions. Tracks are chosen based on planning needs.
When you run workflow-init, it handles brownfield intelligently:
Step 1: Shows what it found
- Old planning docs (PRD, epics, stories)
- Existing codebase
Step 2: Asks about YOUR work
"Are these works in progress, previous effort, or proposed work?"
- (a) Works in progress → Uses artifacts to determine level
- (b) Previous effort → Asks you to describe NEW work
- (c) Proposed work → Uses artifacts as guidance
- (d) None of these → You explain your work
Step 3: Analyzes your description
- Keywords: "fix", "bug" → Quick Flow, "dashboard", "platform" → BMad Method, "enterprise", "multi-tenant" → Enterprise Method
- Complexity assessment
- Confirms suggested track with you
Key Principle: System asks about YOUR current work first, uses old artifacts as context only.
Example: Old Complex PRD, New Simple Work
System: "Found PRD.md (BMad Method track, 30 stories, 6 months old)"
System: "Is this work in progress or previous effort?"
You: "Previous effort - I'm just fixing a bug now"
System: "Tell me about your current work"
You: "Update payment method enums"
System: "Quick Flow track (tech-spec approach). Correct?"
You: "Yes"
✅ Creates Quick Flow workflow
🚨 For brownfield projects: Always ensure adequate AI-usable documentation before planning
Best practice: Run document-project workflow unless you have confirmed, trusted, AI-optimized documentation.
Existing documentation often has quality issues that break AI workflows:
Common Problems:
- Too Much Information (TMI): Massive markdown files with 10s or 100s of level 2 sections
- Out of Date: Documentation hasn't been updated with recent code changes
- Wrong Format: Written for humans, not AI agents (lacks structure, index, clear patterns)
- Incomplete Coverage: Missing critical architecture, patterns, or setup info
- Inconsistent Quality: Some areas documented well, others not at all
Impact on AI Agents:
- AI agents hit token limits reading massive files
- Outdated docs cause hallucinations (agent thinks old patterns still apply)
- Missing structure means agents can't find relevant information
- Incomplete coverage leads to incorrect assumptions
Step 1: Assess Existing Documentation Quality
Ask yourself:
- ✅ Is it current (updated in last 30 days)?
- ✅ Is it AI-optimized (structured with index.md, clear sections, <500 lines per file)?
- ✅ Is it comprehensive (architecture, patterns, setup all documented)?
- ✅ Do you trust it completely for AI agent consumption?
If ANY answer is NO → Run document-project
Step 2: Check for Massive Documents
If you have documentation but files are huge (>500 lines, 10+ level 2 sections):
-
First: Run
shard-doctool to split large files:# Load BMad Master or any agent _bmad/core/tools/shard-doc.xml --input docs/massive-doc.md- Splits on level 2 sections by default
- Creates organized, manageable files
- Preserves content integrity
-
Then: Run
index-docstask to create navigation:_bmad/core/tasks/index-docs.xml --directory ./docs
-
Finally: Validate quality - if sharded docs still seem incomplete/outdated → Run
document-project
| Scenario | You Have | Action | Why |
|---|---|---|---|
| A | No documentation | document-project |
Only option - generate from scratch |
| B | Docs exist but massive/outdated/incomplete | document-project |
Safer to regenerate than trust bad docs |
| C | Good docs but no structure | shard-doc → index-docs |
Structure existing content for AI |
| D | Confirmed AI-optimized docs with index.md | Skip Documentation | Rare - only if you're 100% confident |
Action: Run document-project workflow
- Load Analyst or Technical Writer (Paige) agent
- Run
*document-project - Choose scan level:
- Quick (2-5min): Pattern analysis, no source reading
- Deep (10-30min): Reads critical paths - Recommended
- Exhaustive (30-120min): Reads all files
Outputs:
docs/index.md- Master AI entry pointdocs/project-overview.md- Executive summarydocs/architecture.md- Architecture analysisdocs/source-tree-analysis.md- Directory structure- Additional files based on project type (API, web app, etc.)
Action: Run document-project workflow (regenerate)
Even if docs/ folder exists, if you're unsure about quality → regenerate.
Why regenerate instead of index?
- Outdated docs → AI makes wrong assumptions
- Incomplete docs → AI invents missing information
- TMI docs → AI hits token limits, misses key info
- Human-focused docs → Missing AI-critical structure
document-project will:
- Scan actual codebase (source of truth)
- Generate fresh, accurate documentation
- Structure properly for AI consumption
- Include only relevant, current information
Action: Shard massive files, then index
If you have good, current documentation but it's in massive files:
Step 1: Shard large documents
# For each massive doc (>500 lines or 10+ level 2 sections)
_bmad/core/tools/shard-doc.xml \
--input docs/api-documentation.md \
--output docs/api/ \
--level 2 # Split on ## headers (default)Step 2: Generate index
_bmad/core/tasks/index-docs.xml --directory ./docsStep 3: Validate
- Review generated
docs/index.md - Check that sharded files are <500 lines each
- Verify content is current and accurate
- If anything seems off → Run document-project instead
Action: Skip Documentation
Only skip if ALL conditions met:
- ✅
docs/index.mdexists and is comprehensive - ✅ Documentation updated within last 30 days
- ✅ All doc files <500 lines with clear structure
- ✅ Covers architecture, patterns, setup, API surface
- ✅ You personally verified quality for AI consumption
- ✅ Previous AI agents used it successfully
If unsure → Run document-project (costs 10-30 minutes, saves hours of confusion)
Without AI-optimized documentation, workflows fail:
- tech-spec (Quick Flow) can't auto-detect stack/patterns → Makes wrong assumptions
- PRD (BMad Method) can't reference existing code → Designs incompatible features
- create-architecture can't build on existing structure → Suggests conflicting patterns
- create-story can't provide existing pattern context → Stories lack integration guidance
- dev-story invents implementations → Breaks existing integrations
When in doubt, run document-project.
It's better to spend 10-30 minutes generating fresh, accurate docs than to waste hours debugging AI agents working from bad documentation.
Workflows:
brainstorm-project- Solution explorationresearch- Technical/market researchproduct-brief- Strategic planning (BMad Method/Enterprise tracks only)
When to use: Complex features, technical decisions, strategic additions
When to skip: Bug fixes, well-understood features, time-sensitive changes
See the Workflows section in BMM README for details.
Planning approach adapts by track:
Quick Flow: Use tech-spec workflow
- Creates tech-spec.md
- Auto-detects existing stack (brownfield)
- Confirms conventions with you
- Generates implementation-ready stories
BMad Method/Enterprise: Use prd workflow
- Creates PRD.md with FRs/NFRs only
- References existing architecture
- Plans integration points
- Epics+Stories created AFTER architecture phase
Brownfield-specific: See Scale Adaptive System for complete workflow paths by track.
Critical for brownfield:
- Review existing architecture FIRST
- Document integration points explicitly
- Plan backward compatibility
- Consider migration strategy
Workflows:
create-architecture- Extend architecture docs (BMad Method/Enterprise)create-epics-and-stories- Create epics and stories AFTER architectureimplementation-readiness- Validate before implementation (BMad Method/Enterprise)
Sprint-based development through story iteration:
flowchart TD
SPRINT[sprint-planning<br/>Initialize tracking]
CREATE[create-story]
DEV[dev-story]
REVIEW[code-review]
CHECK{More stories?}
RETRO[retrospective<br/>Per epic]
SPRINT --> CREATE
CREATE --> DEV
DEV --> REVIEW
REVIEW --> CHECK
CHECK -->|Yes| CREATE
CHECK -->|No| RETRO
style SPRINT fill:#bfb,stroke:#333,stroke-width:2px,color:#000
style RETRO fill:#fbf,stroke:#333,stroke-width:2px,color:#000
Status Progression:
- Epic:
backlog → in-progress → done - Story:
backlog → ready-for-dev → in-progress → review → done
Brownfield-Specific Implementation Tips:
- Respect existing patterns - Follow established conventions
- Test integration thoroughly - Validate interactions with existing code
- Use feature flags - Enable gradual rollout
Even if you know the code, AI agents need document-project output for context. Run it before planning.
When workflow-init asks about your work:
- ✅ "Update payment method enums to include Apple Pay"
- ❌ "Fix stuff"
- Has good docs, no index? → Run
index-docstask (fast) - No docs or need codebase analysis? → Run
document-project(Deep scan)
Tech-spec and create-story workflows will detect conventions from existing documentation. Follow them unless explicitly modernizing.
Document in tech-spec/architecture:
- Which existing modules you'll modify
- What APIs/services you'll integrate with
- How data flows between new and existing code
- Use feature flags for new functionality
- Plan rollback strategies
- Maintain backward compatibility
- Create migration scripts if needed
- Regression testing of existing features
- Integration point validation
- Performance impact assessment
- API contract verification
- Run
sprint-planningat Phase 4 start - Context epics before creating stories
- Update
sprint-status.yamlas work progresses
- Run
retrospectiveafter each epic - Incorporate learnings into next stories
- Update discovered patterns
- Share insights across team
Situation: Authentication token expiration causing logout issues
Track: Quick Flow
Workflow:
- Document: Skip if auth system documented, else run
document-project(Quick scan) - Plan: Load PM → run
tech-spec- Analyzes bug
- Detects stack (Express, Jest)
- Confirms conventions
- Creates tech-spec.md + story
- Implement: Load DEV → run
dev-story - Review: Load DEV → run
code-review
Time: 2-4 hours
Situation: Add "forgot password" to existing auth system
Track: Quick Flow
Workflow:
- Document: Run
document-project(Deep scan of auth module if not documented) - Plan: Load PM → run
tech-spec- Detects Next.js 13.4, NextAuth.js
- Analyzes existing auth patterns
- Confirms conventions
- Creates tech-spec.md + epic + 3-5 stories
- Implement: Load SM →
sprint-planning→create-storyLoad DEV →dev-storyfor each story - Review: Load DEV →
code-review
Time: 1-3 days
Situation: Add user dashboard with analytics, preferences, activity
Track: BMad Method
Workflow:
- Document: Run
document-project(Deep scan) - Critical for understanding existing UI patterns - Analyze: Load Analyst →
research(if evaluating analytics libraries) - Plan: Load PM →
prd(creates FRs/NFRs) - Solution: Load Architect →
create-architecture→create-epics-and-stories→implementation-readiness - Implement: Sprint-based (10-15 stories)
- Load SM →
sprint-planning - Load SM →
create-storyper story - Load DEV →
dev-storyper story
- Load SM →
- Review: Per story completion
Time: 1-2 weeks
Situation: Add real-time collaboration to document editor
Track: BMad Method
Workflow:
- Document: Run
document-project(Exhaustive if not documented) - Mandatory - Analyze: Load Analyst →
research(WebSocket vs WebRTC vs CRDT) - Plan: Load PM →
prd(creates FRs/NFRs) - Solution:
- Load Architect →
create-architecture(extend for real-time layer) - Load Architect →
create-epics-and-stories - Load Architect →
implementation-readiness
- Load Architect →
- Implement: Sprint-based (20-30 stories)
Time: 3-6 weeks
Situation: Add multi-tenancy to single-tenant SaaS platform
Track: Enterprise Method
Workflow:
- Document: Run
document-project(Exhaustive) - Mandatory - Analyze: Required
brainstorm-project- Explore multi-tenancy approachesresearch- Database sharding, tenant isolation, pricingproduct-brief- Strategic document
- Plan: Load PM →
prd(comprehensive FRs/NFRs) - Solution:
create-architecture- Full system architecture including multi-tenancy designcreate-epics-and-stories- Create epics and storiesimplementation-readiness- Final validation before implementation
- Implement: Phased sprint-based (50+ stories)
Time: 3-6 months
Symptoms:
- Suggestions don't align with existing patterns
- Ignores available components
- Doesn't reference existing code
Solution:
- Run
document-projectwith Deep scan - Verify
docs/index.mdexists - Check documentation completeness
- Run deep-dive on specific areas if needed
Symptoms:
- README.md, ARCHITECTURE.md exist
- AI agents ask questions already answered
- No
docs/index.mdfile
Solution:
- Quick fix: Run
index-docstask (2-5min) - Comprehensive: Run
document-projectworkflow (10-30min)
Symptoms:
- Not sure how to connect new code to existing
- Unsure which files to modify
Solution:
- Ensure
document-projectcaptured existing architecture - Check story files created by
create-story- should include integration context - In tech-spec/architecture - explicitly document:
- Which existing modules to modify
- What APIs/services to integrate with
- Data flow between new and existing code
- Review architecture document for integration guidance
Symptoms:
- Regression test failures
- Previously working functionality broken
Solution:
- Review changes against existing patterns
- Verify API contracts unchanged (unless intentionally versioned)
- Run
test-reviewworkflow (TEA agent) - Add regression testing to DoD
- Consider feature flags for gradual rollout
Symptoms:
- New code style doesn't match existing
- Different architectural approach
Solution:
- Check convention detection (Quick Spec Flow should detect patterns)
- Review documentation - ensure
document-projectcaptured patterns - Use
create-storyworkflow - it loads context from existing documentation - Add to code-review checklist: pattern adherence, convention consistency
- Run retrospective to identify deviations early
# Documentation (If Needed)
# Analyst agent:
document-project # Create comprehensive docs (10-30min)
# OR load index-docs task for existing docs (2-5min)
# Phase 1: Analysis (Optional)
# Analyst agent:
brainstorm-project # Explore solutions
research # Gather data
product-brief # Strategic planning (BMad Method/Enterprise only)
# Phase 2: Planning (Required)
# PM agent:
tech-spec # Quick Flow track
prd # BMad Method/Enterprise tracks
# Phase 3: Solutioning (BMad Method/Enterprise)
# Architect agent:
create-architecture # Create/extend architecture
create-epics-and-stories # Create epics and stories (after architecture)
implementation-readiness # Final validation
# Phase 4: Implementation (All Tracks)
# SM agent:
sprint-planning # Initialize tracking
create-story # Create story
# DEV agent:
dev-story # Implement
code-review # Review
# SM agent:
retrospective # After epic
correct-course # If issuesDocumentation Output:
docs/index.md- Master AI entry point (REQUIRED)docs/project-overview.mddocs/architecture.mddocs/source-tree-analysis.md
Phase 1-4 Tracking:
docs/bmm-workflow-status.yaml- Progress tracker
Phase 2 Planning:
docs/tech-spec.md(Quick Flow track)docs/PRD.md(BMad Method/Enterprise tracks - FRs/NFRs only)
Phase 3 Solutioning:
- Epic breakdown (created after architecture)
Phase 3 Architecture:
docs/architecture.md(BMad Method/Enterprise tracks)docs/epics.md+ epic folders (from create-epics-and-stories)
Phase 4 Implementation:
docs/sprint-status.yaml- Single source of truthdocs/epic-{n}-context.mddocs/stories/{epic}-{story}-{title}.mddocs/stories/{epic}-{story}-{title}-context.md
flowchart TD
START([Brownfield Project])
CHECK{Has docs/<br/>index.md?}
START --> CHECK
CHECK -->|No| DOC[document-project<br/>Deep scan]
CHECK -->|Yes| TRACK{What Track?}
DOC --> TRACK
TRACK -->|Quick Flow| TS[tech-spec]
TRACK -->|BMad Method| PRD[prd → architecture]
TRACK -->|Enterprise| PRD2[prd → arch + security/devops]
TS --> IMPL[Phase 4<br/>Implementation]
PRD --> IMPL
PRD2 --> IMPL
style START fill:#f9f,stroke:#333,stroke-width:2px,color:#000
style DOC fill:#ffb,stroke:#333,stroke-width:2px,color:#000
style IMPL fill:#bfb,stroke:#333,stroke-width:2px,color:#000
Avoid issues before they happen:
- ✅ Always run document-project for brownfield - Saves context issues later
- ✅ Use fresh chats for complex workflows - Prevents hallucinations
- ✅ Verify files exist before workflows - Check PRD, epics, stories present
- ✅ Read agent menu first - Confirm agent has the workflow
- ✅ Start with simpler track if unsure - Easy to upgrade (Quick Flow → BMad Method)
- ✅ Keep status files updated - Manual updates when needed
- ✅ Run retrospectives after epics - Catch issues early
- ✅ Follow phase sequence - Don't skip required phases
- Scale Adaptive System - Understanding tracks and complexity
- Quick Spec Flow - Fast-track for Quick Flow
- Quick Start Guide - Getting started with BMM
- Glossary - Key terminology
- FAQ - Common questions
- Troubleshooting - Problem resolution
- Workflow Documentation - Complete workflow reference
Community:
- Discord - #general-dev, #bugs-issues
- GitHub Issues
- YouTube Channel
Documentation:
- Test Architect Guide - Comprehensive testing strategy
- BMM Module README - Complete module and workflow reference
Brownfield development is about understanding and respecting what exists while thoughtfully extending it.