---
roadcrew_template_name: "analyze-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"
---

# analyze-epic

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

You are analyzing Github Epic {{EPIC_NUMBER}} to create an implementation plan. Use the Github CLI to get context.

**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).

**Prerequisites:** GitHub authentication required. See `.cursorrules.md` (lines 20-25) for authentication methods and workflow requirements.

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

**COST OPTIMIZATION (minimize-cost patterns built-in):**
- Concise, structured output (no verbose explanations)
- Report issues only (skip confirming what's correct)
- Use GitHub CLI (not API when possible to reduce calls)
- Close unrelated files before analysis
- Expected savings: 65-70% fewer tokens vs verbose mode

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

WORKFLOW:

0. CONTEXT REVIEW
   
   **📁 Context Setup:** Close all unrelated files. Only @ mention files as needed during analysis.
   
   - Review @.cursorrules.md (coding standards, workflow preferences, branch strategy)
   - Review @ai-context.yml (project type, deployment modes, template rules)
   - Review @analyze-epic.md (this file - analysis steps)
   - Review @memory-bank/techContext.md (project type, deployment, CI/CD, testing)
   - Detect project context from tech-stack.md:
     * Deployment method (GitHub Actions, Vercel, Docker, Manual, None)
     * Test framework (Jest, Playwright, pytest, Go test, None)
     * Base branch (dev for roadcrew, main/master for typical projects)
     * Schema management (Prisma, SQL, TypeORM, None)

0.5. TEMPLATE VALIDATION (PRE-FLIGHT CHECK)

   **CRITICAL: Validate epic format before proceeding with analysis**
   
   Run template validation to ensure Epic {{EPIC_NUMBER}} and child issues match required formats:
   
   ```bash
   npx ts-node scripts/validate-github-templates.ts {{EPIC_NUMBER}}
   ```
   
   Expected output:
   ```
   ✅ Template validation passed - epic is ready for implementation
   ```
   
   Exit codes:
   - **0** = Template validation passed ✅ → Continue to step 1
   - **1** = Template validation failed ❌ → Stop and ask user to fix issues on GitHub
   
   If validation fails:
   ```
   ❌ Template validation failed - fix issues above before proceeding
   
   Please fix the issues listed above on GitHub and re-run /analyze-epic {{EPIC_NUMBER}}
   ```

1. EPIC ANALYSIS AND OPEN QUESTIONS CHECK
   
   **A) Fetch Epic Details**
   - Use Github CLI to view Epic {{EPIC_NUMBER}}
   - Read full Epic description
   
   **B) Check for Critical Open Questions**
   
   If Epic contains `## Critical Open Questions` section:
   
   ```bash
   # Extract open questions section
   EPIC_BODY=$(gh issue view {{EPIC_NUMBER}} --json body -q .body)
   
   # Check if has Critical Open Questions
   if echo "$EPIC_BODY" | grep -q "## Critical Open Questions"; then
     # Parse questions and check status
     UNANSWERED=$(echo "$EPIC_BODY" | grep -A 100 "## Critical Open Questions" | grep "^- \[ \]" | wc -l)
     ANSWERED=$(echo "$EPIC_BODY" | grep -A 100 "## Critical Open Questions" | grep "^- \[x\]" | wc -l)
     
     if [ "$UNANSWERED" -gt 0 ]; then
       echo "❌ Epic has $UNANSWERED unanswered questions:"
       echo "$EPIC_BODY" | grep -A 100 "## Critical Open Questions" | grep "^- \[ \]"
       echo ""
       echo "Please answer all questions in the Epic description, then re-run /analyze-epic {{EPIC_NUMBER}}"
       exit 1
     else
       echo "✅ All $ANSWERED Critical Open Questions answered!"
       echo "Proceeding to generate child issues from Epic + answers..."
     fi
   fi
   ```
   
   **C) Analyze Existing Structure**
   - If Epic has child issues already: Analyze existing issues
   - If Epic has open questions (all answered): Generate child issues from Epic context
   - If Epic has no questions and no children: Flag as incomplete
   
   **D) Parse Dependencies and Scope**
   - Read issue descriptions, acceptance criteria, comments
   - Identify dependencies between issues (use issue-classification utilities)
   - Assess scope (flag if >7 issues - too large, suggest split)
   - Uses `scripts/utils/issue-classification.ts` for validation rules

2. CLASSIFICATION ASSESSMENT
   
   Use centralized issue classification utilities for consistent 1-10 scoring:
   
   ```typescript
   import { classifyIssue, getIssueDependencies } from '../scripts/utils/issue-analysis.js';
   
   const classificationResults = [];
   let highestClassification = 1; // Track for epic-level classification
   
   for (const issue of childIssues) {
     const classification = await classifyIssue(issue.number);
     const dependencies = await getIssueDependencies(issue.number);
     
     classificationResults.push({
       number: issue.number,
       title: issue.title,
       classification: classification.classification,     // 1-10
       zone: classification.zone,                         // ai-solo, ai-led, ai-assisted, ai-limited
       reasoning: classification.reasoning,
       dependsOn: dependencies.dependsOn,
       blocks: dependencies.blocks
     });
     
     highestClassification = Math.max(highestClassification, classification.classification);
   }
   ```
   
   **Display Classification Summary Table:**
   
   ```
   ┌─────┬──────────────────────────────┬─────────────────┬──────────────┬────────────────────────────┐
   │ # │ Title                         │ Classification  │ Zone         │ Reasoning                  │
   ├─────┼──────────────────────────────┼─────────────────┼──────────────┼────────────────────────────┤
   │ #77 │ Create analysis utility      │ 3 (ai-solo)     │ ai-solo      │ Fully automated, templates │
   │ #78 │ Update command               │ 6 (ai-led)      │ ai-led       │ Integration testing needed │
   └─────┴──────────────────────────────┴─────────────────┴──────────────┴────────────────────────────┘
   ```
   
   **Calculate Overall Epic Classification:**
   
   ```
   If highestClassification 1-3:   → LOW complexity
   If highestClassification 4-6:   → MEDIUM complexity
   If highestClassification 7-8:   → HIGH complexity
   If highestClassification 9-10:  → CRITICAL complexity
   ```
   
   Display: `Epic #{{EPIC_NUMBER}} Complexity: {{LEVEL}} (based on most complex child issue)`

3. IMPLEMENTATION SEQUENCING
   
   **Use TOC Sequencer for Optimal Ordering:**
   
   ```typescript
   // Import TOC integration utilities
   import { analyzeEpicWithTOC } from './scripts/utils/analyze-epic-toc';
   
   // Fetch child issues
   const childIssues = await fetchChildIssues(epicNumber);
   
   // Run TOC analysis
   const { sequencedPlan, formattedOutput, issues } = analyzeEpicWithTOC(childIssues);
   
   // Display TOC-optimized sequence
   console.log(formattedOutput);
   ```
   
   **TOC Sequencing provides:**
   - Dependency-aware ordering (foundational issues first)
   - Phase grouping (parallel vs sequential work)
   - Expert work optimization (minimize wait time)
   - Critical path identification
   - Resource allocation (expert/junior/AI work distribution)
   
   **Fallback (if TOC fails):**
   - Order issues by dependencies manually using issue-classification utilities
   - Identify critical validation checkpoints
   - Estimate effort per issue and total
   - Note if schema migrations required (affects testing approach)
   - Flag breaking changes early in sequence (requires version coordination)

3a. ASSIGNMENT VALIDATION (if config/assignment-rules.yml exists)
   - Check GitHub issue assignees against classification levels
   - Validate assignments match assignment rules
   - Flag mismatches for review:
     * ai-assisted/ai-limited (7-10) issues assigned to low-classification developers
     * ai-solo (1-3) issues assigned to senior developers (capacity concern)
   - Recommend reassignments based on classification zones if needed

4. GROUPING ANALYSIS
   After sequencing, evaluate if issues should be combined:
   
   **Quick Decision:** Combine if same files + <2hr + same classification zone. Keep separate if independent value + different zones + >3hr.
   
   **Consider Grouping If:**
   - Sequential issues touch the same files
   - Issues are tightly coupled (one can't work without the other)
   - Combined effort < 2 hours (small, related changes)
   - Same testing requirements
   - Same classification zone (ai-solo, ai-led, ai-assisted, ai-limited)
   - Natural atomic unit (e.g., "rename file + update references")
   
   **Keep Separate If:**
   - Issues are independently valuable
   - Different classification zones (don't mix ai-limited with ai-solo)
   - Different testing requirements
   - Combined effort > 3 hours (too large)
   - Can be reviewed/rolled back independently
   
   For each grouping recommendation:
   - Explain rationale
   - Suggest updated issue structure
   - Note impact on Epic scope

5. PRESENT IMPLEMENTATION PLAN
   
   **Special Case: Epic with Answered Critical Open Questions**
   
   If Epic had Critical Open Questions (all now answered):
   - Parse answered questions from Epic description
   - Use answers to inform child issue generation
   - Present proposed child issues based on Epic scope + answers
   - Ask: "Ready to create X child issues from this Epic?"
   - User approves → Create child issues using templates (see Step 6)
   
   Format:
   ```
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
   📊 EPIC ANALYSIS: [Epic Title]
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
   
   Epic #{{EPIC_NUMBER}}: [Description]
   
   **Status**: ✅ All Critical Open Questions Answered (generating child issues)
   
   Project Context: [Detected from memory-bank/techContext.md]
   - Project Type: [Node.js/Python/Library/CLI Tool/Web App]
   - Deployment: [GitHub Actions/Vercel/Docker/Manual/None]
   - Tests: [Jest/Playwright/pytest/None]
   - Base Branch: [dev/main/master]
   
   Overall Classification: [1-10] ([Zone])
   Estimated Effort: [X-Y hours]
   Breaking Changes: [Yes/No + details if yes]
   
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
   IMPLEMENTATION SEQUENCE (TOC-Optimized)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
   
   Phase 1: Supporting work (unblock experts)
   - 🔴 Issue #XXX: [Title] (X hours) (blocks 2 issues) [can parallelize]
   - Issue #YYY: [Title] (Y hours) [can parallelize]
     Estimated: X hours
   
   Phase 2: Expert work (critical path)
   - 🔴 Issue #ZZZ: [Title] (Z hours) (blocks 1 issue)
     Estimated: Z hours
   
   Total Estimated Hours: N
     Expert Work: X hours
     Junior Work: Y hours
     AI Work: Z hours
   
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
   CRITICAL PATH ANALYSIS
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
   
   Critical Path: #XXX → #ZZZ
   Total Duration: N hours (minimum project time)
   
   ⚠️ Bottlenecks (issues blocking most work):
   1. Issue #XXX: [Title] - Blocks 2 issues
   2. Issue #ZZZ: [Title] - Blocks 1 issue
   
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
   DETAILED ISSUE ANALYSIS
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
   
   1. Issue #XXX: [Title]
      Classification: [1-10] ([Zone])
      Rationale: [Why this issue? Why this order?]
      Effort: [X hours]
      Breaking: [Yes/No]
   
   [Continue for all issues...]
   
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
   CRITICAL VALIDATION CHECKPOINTS
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
   
   • Checkpoint 1: [After which issue(s), what to validate]
   • Schema Validation: [If Prisma/schema changes detected]
   • Breaking Change Review: [If breaking changes flagged]
   
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
   DEPENDENCIES & RISKS
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
   
   Dependencies: [Cross-issue dependencies]
   High-Classification Issues: [Issue #XXX (classification 7-10) - Why + mitigation]
   Potential Blockers: [Concerns or unknowns]
   Breaking Changes Impact: [If applicable - version strategy, migration path]
   
   **Assignment Validation (if config/assignment-rules.yml exists):**
   - Check if issues have assignees that match their classification levels
   - Flag mismatches: e.g., ai-assisted/ai-limited (7-10) assigned to low-classification developer
   - Recommend reassignment based on classification zones if needed
   
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
   GROUPING RECOMMENDATIONS (if applicable)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
   
   Recommend Grouping: [Issues #XXX + #YYY - Rationale]
   Keep Separate: [Issues #AAA + #BBB - Rationale]
   
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
   ```

6. CREATE CHILD ISSUES (If Critical Open Questions Answered)
   
   **Only execute this step if:**
   - Epic had ##Critical Open Questions section
   - All questions are now answered ([x])
   - Epic has NO existing child issues
   
   **Process - Using Unified GitHub Issue Creator:**
   ```typescript
   import { createEnhancementIssue, createBugIssue } from './core/github-issue-creator.js';
   
   // Generate child issues from Epic scope + answered questions
   // Use the unified module instead of direct gh commands
   
   for (const issue of GENERATED_ISSUES) {
     // Use createEnhancementIssue for features
     if (issue.type === 'enhancement') {
       const result = await createEnhancementIssue(
         issue.title,
         issue.body, // Fully populated template
         issue.sequence,
         GENERATED_ISSUES.length
       );
       console.log(`✅ Created #${result.number}: ${issue.title}`);
     }
     
     // Or use createBugIssue for bugs
     if (issue.type === 'bug') {
       const result = await createBugIssue(
         issue.title,
         issue.body, // Fully populated template
         issue.parentEpic
       );
       console.log(`✅ Created #${result.number}: ${issue.title}`);
     }
   }
   ```
   
   **What the Unified Module Provides:**
   - ✅ Automatic template population
   - ✅ GitHub API with CLI fallback
   - ✅ Shell escaping security
   - ✅ Issue number extraction
   - ✅ Parent epic linking
   - ✅ Duplicate detection
   
   **Don't use:** Direct `gh issue create` commands or shell scripts
   
   **After creating child issues:**
   - Update Epic description with child issue links
   - Show summary: "Created X child issues for Epic #{{EPIC_NUMBER}}"
   - Continue to Step 7 (Ask for Approval for implementation)

7. ASK FOR APPROVAL
   
   **If child issues just created:**
   ```
   Created N child issues for Epic #{{EPIC_NUMBER}}.
   
   Recommend: Proceed to implementation (all questions answered, issues ready).
   
   Ready to implement? Y/N
   ```
   
   **If analyzing existing Epic:**
   ```
   Epic #{{EPIC_NUMBER}} analysis complete.
   
   Recommend: Proceed to implementation (dependencies ordered, risks assessed).
   
   Ready to implement? Y/N
   ```
   
   **If user approves (Y):** 
   ```
   Run command:
   ```
   /implement-epic {{EPIC_NUMBER}}
   ```
   ```
   
   **If user declines (N):** Ask what to adjust
   
   **Explain Auto-Closure Workflow:**
   ```
   📌 Issue Closure Workflow:
   
   1. /implement-epic {{EPIC_NUMBER}} creates PR: epic-{{EPIC_NUMBER}} → dev
      - Issues listed but NOT closed yet
      - Adds 'pending-closure' label to epic #{{EPIC_NUMBER}} and all child issues
   
   2. Review and merge epic PR to dev
      - Issues remain open with 'pending-closure' label
   
   3. /create-release-pr creates PR: dev → main
      - Automatically includes "Closes #N" for all pending issues (epic + children)
      - Epic issue #{{EPIC_NUMBER}} and all child issues auto-close when merged to main ✅
   
   4. Release issue automatically updated:
      - Epic marked complete in checklist
      - Progress metrics recalculated
      - Status changes to "Ready for Release" when all epics done
   
   Alternative: Manually create dev → main PR with "Closes #N" keywords for ALL issues
   ```

**SCOPE WARNINGS:**

- If >7 issues: Recommend splitting into multiple epics
- If issues are loosely coupled: Suggest using `/implement-issue` in parallel
- If scope unclear: Flag and request clarification before planning

**NO CODE CHANGES:**

This command is analysis-only. No branches, commits, or code changes.

Behavior:

- If invoked with trailing text (e.g., "/analyze-epic 231"), interpret that text as {{EPIC_NUMBER}} and proceed.
- If {{EPIC_NUMBER}} is missing, ask me once for it before proceeding.
- Always present full analysis before asking for approval
- Guide user to run `/implement-epic {{EPIC_NUMBER}}` when ready