---
roadcrew_template_name: "implement-epic.md"
roadcrew_template_type: "command"
execution_mode: "auto-execute"
roadcrew_template_version: "v1.0"
roadcrew_last_updated: "2025-10-25"
roadcrew_min_version: "1.5.0"
roadcrew_license: "See LICENSE file in .roadcrew folder"
roadcrew_copyright: "Copyright (c) 2025 North Star Holdings, LLC"
spdx_license_identifier: "LicenseRef-RoadcrewLicense-1.0"
---

# implement-epic

<!-- Usage: /implement-epic 231 [--repo https://github.com/org/repo] -->

You are implementing Github Epic {{EPIC_NUMBER}} in batch mode.

> **Execution:** Runs immediately with automatic issue processing. No approval pauses between issues.

**Standalone Mode Support:** If --repo flag provided, use that repo for GitHub CLI commands and look for config in config/repos/org-repo/. If no --repo flag, use current repo (integrated mode).

**PREREQUISITE:** User must run `/analyze-epic {{EPIC_NUMBER}}` first. This command assumes analysis is complete and approved.

**MANDATORY CURSORRULES COMPLIANCE:** Reference @.cursorrules.md throughout this work.

**COST OPTIMIZATION (minimize-cost patterns built-in):**
- Concise commit messages and summaries
- Auto-proceed between issues (no verbose status reports)
- "Done" when complete (no lengthy explanations)
- Close unrelated files during implementation
- Expected savings: 65-70% fewer tokens vs verbose mode

**STRICT SCOPE:** Only work on Epic {{EPIC_NUMBER}} and its child issues. Note unrelated issues but don't fix them.

WORKFLOW:

0. PRE-FLIGHT CHECKS & TODO LIST CREATION

   **📁 Context Setup:** Close all unrelated files before implementation.
   
   Use the ImplementationCoordinator to manage epic state and context:
   
   ```typescript
   import { ImplementationCoordinator } from './scripts/utils/roadcrew/implementation-coordinator.js';
   
   const coordinator = new ImplementationCoordinator({{EPIC_NUMBER}});
   coordinator.loadState();
   
   // Run preflight checks using coordinator
   const projectContext = await coordinator.detectProjectContext();
   const authValid = await coordinator.validateGitHubAuth();
   
   if (!projectContext || !authValid) {
     console.error('❌ Preflight checks failed');
     console.error('See .cursorrules.md (lines 20-25) for setup');
     process.exit(1);
   }
   
   console.log(`✅ Project detected: ${projectContext.type}`);
   console.log(`✅ Test framework: ${projectContext.testFramework}`);
   console.log(`✅ Base branch: ${projectContext.baseBranch}`);
   ```
   
   Coordinator automatically:
   - Detects project type (Node.js/Python/Library/CLI/Web App)
   - Detects deployment method (GitHub Actions/Vercel/Docker/Manual/None)
   - Detects test framework (Jest/Playwright/pytest/Go test/None)
   - Detects base branch (dev for roadcrew, main/master for typical)
   - Detects schema management (Prisma/SQL/TypeORM/None)
   - Validates GitHub authentication
   - Saves state to `.roadcrew/epic-{{EPIC_NUMBER}}-state.json`
   
   **CREATE COMPREHENSIVE TODO LIST:**
   After preflight checks pass, create a TODO list with all workflow steps:
   
   ```
   Epic #{{EPIC_NUMBER}} Implementation Checklist:
   
   1. ✅ Pre-flight checks complete
   2. [ ] Create epic branch (epic-{{EPIC_NUMBER}})
   3. [ ] Present scope summary (auto-proceed)
   4. [ ] Implement all child issues in dependency order
   5. [ ] Present implementation summary (auto-proceed)
   6. [ ] Create PR: epic-{{EPIC_NUMBER}} → dev (automatic)
   7. [ ] Wait for CI checks to pass (automatic)
   8. [ ] 🧑 CHECKPOINT: Run manual tests (if required)
   9. [ ] Auto-merge PR to dev (automatic)
   10. [ ] Create release PR: dev → main (automatic)
   11. [ ] 🧑 CHECKPOINT: Review and merge release PR to main
   
   🧑 = Human checkpoint required (only for manual tests and main merge)
   ```
   
   **This TODO list ensures no steps are skipped, especially:**
   - The PR creation for epic branch → dev/main
   - The separate release PR creation for dev → main
   - All human approval checkpoints

1. CREATE EPIC BRANCH
   - Branch from base branch (detected from tech-stack.md or .cursorrules.md):
     * Roadcrew projects: `epic-{{EPIC_NUMBER}}` from `dev`
     * Typical open source: `epic-{{EPIC_NUMBER}}` from `main` or `master`
   - Rebase from base branch before starting each issue
   - Mark TODO item #2 as complete

1.5. CONFIRM SCOPE (AUTO-PROCEED CHECKPOINT)
   
   **Mark TODO item #3 as in_progress**
   
   **Present short bullet summary and auto-proceed:**
   ```
   Epic #{{EPIC_NUMBER}}: [Title]
   
   Scope:
   - [Issue #X: Brief description]
   - [Issue #Y: Brief description]
   - [Issue #Z: Brief description]
   
   Total: N issues, M-P hours estimated
   
   Auto-proceeding with implementation...
   (Interrupt now if you need to adjust scope)
   ```
   
   **Auto-proceed behavior:**
   - Present the scope summary
   - Immediately mark TODO item #3 as complete
   - Continue to step 1.6 without waiting
   - User can interrupt/cancel if needed before work begins

1.6. PARSE DEPENDENCIES AND ORDER ISSUES
   
  **Fetch child issues:**
  ```bash
  # Get all child issues for the epic
  # Search for issues that reference the epic number in their body
  CHILD_ISSUES=$(gh issue list --search "is:issue #{{EPIC_NUMBER}} in:body" --json number,title,body --limit 100)
  ```
   
   **Parse dependencies from issue bodies:**
   ```typescript
   // For each issue, extract dependencies from body:
   // - Look for "Depends on: #X" or "Depends on: #X, #Y"
   // - Look for "Blocks: #Z" to understand reverse dependencies
   // Parse into IssueWithDependencies format:
   
   interface IssueWithDependencies {
     id: string;          // Issue number (e.g., "77")
     title: string;
     dependsOn: string[]; // Array of issue numbers this depends on
     effort?: number;
     risk?: RiskLevel;
   }
   ```
   
   **Use issue-classification utilities to order:**
   ```typescript
   import {
     orderIssuesByDependencies,
     detectCircularDependencies
   } from './scripts/utils/issue-classification';
   
   // Check for circular dependencies
   const circular = detectCircularDependencies(issues);
   if (circular) {
     console.error('Circular dependencies detected:', circular);
     console.log('Falling back to numeric order...');
     // Use numeric order as fallback
   }
   
   // Order by dependencies (topological sort)
   const ordered = orderIssuesByDependencies(issues);
   ```
   
   **Display phased implementation plan and auto-proceed:**
   ```
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
   📋 IMPLEMENTATION SEQUENCE (Dependency Order)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
   
   Phase 1 (Parallel - can implement simultaneously):
   - #77: Add dependency validation utilities (2-3 hrs)
   - #78: Add analyze-repo integration (1-2 hrs)
   - #85: Create /update-my-documents command (4-5 hrs)
   
   Phase 2 (Sequential - implement in order):
   - #79: Add template validation (needs #77, #78) (2-3 hrs)
   - #80: Add Critical Open Questions (needs #79) (2-3 hrs)
   - #81: Add open questions to analyze-epic (needs #77, #80) (2-3 hrs)
   - #83: Enforce template usage (needs #77) (3-4 hrs)
   
   Phase 3 (Final):
   - #82: Update documentation (needs all above) (1-2 hrs)
   - #87: Update implement-epic sequencing (needs #77) (2-3 hrs)
   
   Total Estimated Effort: 22-28 hours
   
   Auto-proceeding with this sequence...
   (Interrupt now if you need to adjust the order)
   ```
   
   **Auto-proceed behavior:**
   - Present the implementation sequence
   - Immediately proceed with dependency-ordered sequence
   - User can interrupt/cancel if they need to adjust the order
   
   **Fallback behavior:**
   - If no dependencies found: Use numeric order (#77 → #78 → #79...)
   - If circular dependencies: Use numeric order with warning
   - If dependency parsing fails: Use numeric order
   
   **Store ordered sequence:**
   - Save to variable for step 2 implementation loop
   - Track which phase each issue belongs to (for better logging)

2. IMPLEMENT ISSUES IN DEPENDENCY ORDER
   
   **Mark TODO item #4 as in_progress**
   
   **CRITICAL: CONTINUOUS IMPLEMENTATION MODE**
   - Implement ALL issues in the epic without pausing for approval between issues
   - DO NOT ask "Ready to continue?" or "Pause for review?" between issues
   - DO NOT recommend "Continue in next session" - keep going until all issues complete
   - Complex/time-consuming work is EXPECTED in epics - continue regardless of complexity
   - Only pause at the human checkpoints defined in the TODO list (step 3, 5, 8, 11)
   
   For each issue (in ordered sequence from step 1.5):
   - **TRACK METRICS:** Record start time/tokens → implement → record end time/tokens
     * Duration: end time - start time
     * Tokens: end count - start count
     * Files modified: count
     * Lines changed: +X / -Y
     * Tests added: count (if applicable)
     * Breaking changes: Yes/No
     * Add to epic metrics log
   - Review @.cursorrules.md and @implement-epic.md (refresh context)
   - Review @memory-bank/techContext.md (project context)
   - Create comprehensive TODO list (no approval needed - batched)
   - TEST-FIRST APPROACH (adapted to project type):
     * If test framework detected: Create/update automated tests
     * If no tests: Document manual test steps
     * Implement code with conservative approach
     * Review code changes locally
   - Implement all code changes for the issue
   - Checkpoint commit with test plan in message:
     ```
     feat(epic-{{EPIC_NUMBER}}): [Issue #N] description
     
     [Implementation details]
     
     Test Plan:
     - [ ] Test step 1
     - [ ] Test step 2
     - [ ] Expected result
     
     Implementation Metrics:
     - Duration: [X hours Y minutes]
     - Tokens: [N tokens used]
     - Files Modified: [count]
     - Lines Changed: [+X / -Y]
     - Tests Added: [count] (if applicable)
     - Breaking Changes: [Yes/No]
     ```
   - NO manual testing execution (deferred to end)
   - **IMMEDIATELY continue to next issue** (no pause, no approval needed)
   
   **After all issues implemented:** Mark TODO item #4 as complete

3. IMPLEMENTATION COMPLETE - NOTIFICATION (AUTO-PROCEED)
   
   **Mark TODO item #5 as in_progress**
   
   **After all issues implemented, present short summary and auto-proceed:**
   ```
   Epic #{{EPIC_NUMBER}} implementation complete.
   
   Automated: X% coverage (N tests passing)
   Manual tests: [list or "None"]
   
   Creating PR (epic-{{EPIC_NUMBER}} → dev)...
   ```
   
   **No approval needed - immediately proceed to step 4**
   
   **Metrics included in PR description:**
   - Total Duration, Tokens, Files Modified, Lines Changed
   - Breaking Changes (if any)
   - Manual test list (if any)

4. CREATE PR & AUTOMATED TESTING (AUTOMATIC - NO APPROVAL NEEDED)
   
   **Mark TODO item #6 as in_progress**
   
   **This step happens automatically after user approves step 3 - do not ask for additional approval**
   
   - **CREATE PR:**
     * Push epic branch
     
     * **VALIDATE PR FORMAT (MANDATORY - NEW):**
       ```bash
       # Build PR title and body for epic → dev PR
       PR_TITLE="feat(epic-{{EPIC_NUMBER}}): {{EPIC_TITLE}}"
       PR_BODY="## Implementation Summary
       
       Implemented {{TOTAL_ISSUES}} issues in Epic #{{EPIC_NUMBER}}
       
       Metrics:
       - Duration: {{DURATION}}
       - Files Modified: {{FILES_CHANGED}}
       - Tests Added: {{TESTS_ADDED}}
       - Coverage: {{COVERAGE}}%
       
       All acceptance criteria met. Ready for review and merge.
       
       Closes all child issues when released to main."
       
       # Validate PR before pushing
       node scripts/core/validate-pr-command.ts \
         --title "$PR_TITLE" \
         --body "$PR_BODY" \
         --command "implement-epic" \
         --auto-fix
       ```
     
     * Create PR: epic-{{EPIC_NUMBER}} → dev (or main for projects without dev branch)
     * Include metrics, test results, manual test list in PR description
     * Display PR URL
     * **ADD PENDING-CLOSURE LABELS:**
       - Add `pending-closure` label to the epic issue #{{EPIC_NUMBER}}
       - Add `pending-closure` label to ALL child issues
       - Add comment to each issue: "✅ Implementation complete in epic branch. This issue will auto-close when the epic merges to main."
       - Command: `gh issue edit <issue_number> --add-label "pending-closure"`
     * Mark TODO item #6 as complete
   
   **Mark TODO item #7 as in_progress**
   
   - **AUTOMATED PR CHECKS:**
     * Cursor Bugbot auto-reviews code
     * CI runs: linting, type checking, unit tests, integration tests
     * Pre-commit hooks already ran locally
   
   - **CI WAIT STRATEGY:**
     ```
     PR created → Check CI status immediately
                    ↓
     CI running? → Present status, note that Background Agent will auto-fix issues
                    ↓
     CI passed? → Continue to step 5
                    ↓
     CI failed? → Present error summary, let Background Agent handle or ask user
     ```
     
     * **If CI passes immediately:** Mark TODO item #7 as complete, continue to step 5
     * **If CI is running:** Present status message: "CI checks running. Background Agent will handle any failures. Check PR: [URL]" then mark TODO item #7 as complete and continue
     * **If CI fails:** Present error summary and PR URL for user/agent to fix
     
5. AUTO-MERGE TO DEV & CREATE RELEASE PR
   
   **IMPORTANT: Merging to dev is AUTOMATIC after CI passes (and optional manual tests)**
   **Only merging to main requires human approval (step 6)**
   
   **If all automated tests pass + no manual tests required:**
   
   **Mark TODO item #8 as complete (no manual tests)**
   **Mark TODO item #9 as in_progress**
   
   ```
   PR #{{PR_NUMBER}} (epic-{{EPIC_NUMBER}} → dev) ready.
   All CI tests passing. No manual tests required.
   
   Auto-merging to dev...
   ```
   
   **Automatically merge without asking - proceed immediately**
   
   **If all automated tests pass + manual tests required:**
   
   **Mark TODO item #8 as in_progress**
   
   ```
   PR #{{PR_NUMBER}} (epic-{{EPIC_NUMBER}} → dev) ready.
   All CI tests passing.
   
   Manual tests required:
   - [Test 1]
   - [Test 2]
   
   Run manual tests then confirm. Done? Y/N
   ```
   
   **After manual tests confirmed (or if no manual tests):**
   
   **Mark TODO item #8 as complete**
   **Mark TODO item #9 as in_progress**
   
   ```
   Auto-merging PR to dev...
   ```
   
   **Automatically merge the PR (no additional approval needed):**
   - Merge the PR (epic-{{EPIC_NUMBER}} → dev) without asking for merge approval
   - Mark TODO item #9 as complete
   - Mark TODO item #10 as in_progress
   - Immediately continue to step 5.2 to create release PR
   
5.1. UPDATE RELEASE ISSUE (AUTOMATIC)
   
   **After PR merges to main (not dev):**
   
   ```
   Epic #{{EPIC_NUMBER}} merged to main via PR #{{PR_NUMBER}}.
   
   Updating Release issue progress...
   ```
   
   **Automatically update Release issue:**
   - Find Release issue containing this epic
   - Mark epic as complete in checklist: `- [ ]` → `- [x]`
   - Recalculate progress metrics (epics/issues complete, %)
   - Add completion comment: "✅ Epic #{{EPIC_NUMBER}} completed and merged to main via PR #{{PR_NUMBER}}"
   - If all epics complete, update status: "🚧 In Progress" → "✅ Ready for Release"
   - Run: `npm run update-release-progress {{EPIC_NUMBER}} {{PR_NUMBER}}`
   
5.2. AUTO-CREATE RELEASE PR (AUTOMATIC)
   
   **This step is MANDATORY for projects with dev branch (like roadcrew)**
   **Mark TODO item #10 as in_progress**
   
   ```
   Epic branch merged to dev successfully.
   
   Creating release PR (dev → main)...
   ```
   
   **Automatically create the release PR:**
   - Mark TODO item #10 as complete
   - Mark TODO item #11 as in_progress
   - Run `/create-release-pr` command or create PR manually
   - Create PR: dev → main with proper `Closes #N` keywords
   - Display PR URL and details
   - Prompt user to review and approve the merge to main
   
   ```
   Release PR #{{PR_NUMBER}} created: dev → main
   
   This PR will close the following issues when merged to main:
   - #{{EPIC_NUMBER}}: [Epic title] (EPIC)
   - #{{ISSUE_1}}: [Issue title]
   - #{{ISSUE_2}}: [Issue title]
   
   Note: The epic issue #{{EPIC_NUMBER}} is included and will auto-close with its child issues.
   
   Please review and merge the release PR to main when ready.
   The PR is ready for your review at: [PR_URL]
   ```

6. HUMAN REVIEW & MERGE TO MAIN (HUMAN CHECKPOINT - CRITICAL)
   
   **This is the ONLY human approval checkpoint for merging**
   
   - The release PR (dev → main) has been created automatically
   - Human review is REQUIRED before merging to main
   - The `/create-release-pr` command or manual PR creation handles:
     * Creating dev → main PR
     * Including `Closes #N` keywords for all pending issues
     * Auto-closure on merge to main
   - **Note:** Epic implementation is complete at this point
   - **Note:** Issues auto-close when release PR merges to main
   - **Note:** TODO item #11 should be marked complete after user confirms merge
   
   **User must manually:**
   1. Review the release PR
   2. Approve and merge the PR to main (via GitHub UI or CLI)
   3. Verify issues auto-close after merge

**GUARDRAILS:**

1. **Scope Control**
   - Max 7 issues per epic
   - If >7 issues: propose epic split with dependencies
   - Flag if issues are loosely coupled (suggest parallel implementation)

2. **Checkpoint Commits**
   - One commit per issue (easy to bisect if problems)
   - Clear commit messages: "feat(epic-{{EPIC_NUMBER}}): [Issue #N] description"
   - Rebase from base branch before each issue if epic is multi-day
   - Mark breaking changes in commit message if applicable

3. **Critical Validation Points**
   - Identify 2-3 critical checkpoints upfront
   - Schema changes: validate migrations work before continuing
   - Breaking changes: verify upgrade path before continuing
   - Optional: --validate flag for mid-epic testing
   - Always test at epic completion (automated + manual)

4. **Escape Hatches**
   - If issue blocked: document, skip, continue
   - If major issue discovered: pause, get approval
   - If scope creep detected: flag immediately

5. **Authentication Failures**
   - If auth fails mid-epic: commit WIP, document state
   - Prompt user to re-authenticate:
     * See `.cursorrules.md` (lines 20-25) for authentication setup instructions
   - User re-runs /implement-epic {{EPIC_NUMBER}} to resume

**BEST USE CASES:**
✅ Tightly coupled issues (shared files/functions)
✅ Sequential dependencies (Issue B needs Issue A)
✅ Feature development (coherent user story)
✅ Refactoring epics (architectural changes)

**AVOID FOR:**
❌ Epics with >10 issues (split into smaller epics)
❌ Issues with no dependencies (use implement-issue in parallel)
❌ Hotfixes (use implement-issue)
❌ Exploratory work (unknown scope)

**EFFICIENCY GAINS:**
- 30% time reduction vs per-issue workflow
- Reduced context switching (1× vs N×)
- Single deployment cycle
- Batch testing (better integration coverage)
- Single PR review cycle

**TODO LIST MANAGEMENT:**

The TODO list created in step 0 is MANDATORY and must be:
1. Created at the start of epic implementation (after pre-flight checks)
2. Updated as each step completes (mark items as in_progress → complete)
3. Referenced throughout the workflow to ensure no steps are skipped
4. Kept visible to the user to track progress

**CRITICAL:** The TODO list explicitly includes:
- PR creation for epic → dev (automatic merge after CI passes)
- Release PR creation for dev → main (automatic creation)
- Human checkpoint ONLY for merging release PR to main (marked with 🧑)
- Clear separation between automated and manual steps

**AUTOMATION FLOW:**
- epic-{{EPIC_NUMBER}} → dev: Auto-merge after CI passes (no human approval)
- dev → main: Auto-create PR, but REQUIRES human approval to merge

Behavior:

- If invoked with trailing text (e.g., "/implement-epic 231"), interpret that text as {{EPIC_NUMBER}} and proceed.
- If {{EPIC_NUMBER}} is missing, ask me once for it before proceeding.
- If user hasn't run `/analyze-epic {{EPIC_NUMBER}}` first, remind them to do so
- Generate comprehensive test plan before requesting manual testing
- **ALWAYS create and maintain the TODO list throughout the entire workflow**