---
roadcrew_template_name: "scope-release.md"
roadcrew_template_type: "command"
roadcrew_template_version: "v1.0"
roadcrew_last_updated: "2025-10-29"
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"
execution_mode: "auto-execute"
---

# scope-release

Scope release with epic grouping, validation, and auto-remediation. Generates issues.yml and supports multi-repo releases.

> **Execution:** Runs immediately. Epic confirmation checkpoints only (user reviews epic summaries before issue creation).

**Cost Optimization:** Concise summaries, consolidated validation, script-first approach.

<!-- Usage: /scope-release [--current|--minor] [--project "Project Name"] -->

Convert a scoped release plan to GitHub epics and issues.

**Prerequisites:** GitHub authentication required. See `.cursor/rules/03-github.mdc` for authentication methods and workflow requirements.

---

## 🔒 CRITICAL POLICY: GitHub-First, No Interim Documentation

**`/scope-release` MUST ALWAYS:**
- ✅ **Create ALL issues directly in GitHub** - Never create interim .md documentation files
- ✅ **Verify every issue was created** - Extract and confirm GitHub issue numbers for Release, all Epics, and all Child Issues
- ✅ **Record issue numbers in current-release.md** - Update file with actual GitHub issue numbers
- ✅ **Sync issue numbers to memory-bank/activeContext.md** - Keep strategic roadmap in sync with GitHub issues

**`/scope-release` MUST NEVER:**
- ❌ **Create interim documentation files** (e.g., `memory-bank/requirements/source-docs/issue-*.md`, `memory-bank/requirements/specs/issue-*.md`)
- ❌ **Leave template placeholders** (e.g., `{{GITHUB_ISSUE_NUMBER}}`, `<!-- TODO: enrich -->`)
- ❌ **Complete without verifying all issues exist in GitHub** - Must confirm all expected GitHub issue numbers
- ❌ **Create GitHub issue without writing number back to markdown** - File must document the issue numbers

**Verification Checkpoints:**
```
BEFORE completing /scope-release:

1. ✅ Release issue created? Does it have a GitHub issue number (#NNN)?
2. ✅ All epics created? Does each have a GitHub issue number (#NNN)?
3. ✅ All child issues created? Does each have a GitHub issue number (#NNN)?
4. ✅ Issue numbers recorded? Are they in current-release.md?
5. ✅ No interim files? Check git status for new .md files
6. ✅ Full enrichment applied? No <!-- TODO: enrich --> markers remain?

If ANY check fails → STOP and report error. Do not complete /scope-release.
```

---

## Command Execution

This command runs the TypeScript script:
- **Instance installation:** `scripts/scope-release.ts`
- **Submodule installation:** `.roadcrew/scripts/scope-release.ts` or `roadcrew/scripts/scope-release.ts`

**Flags:**
- `--current` - Use current-release.md (major release)
- `--minor` - Use minor-release.md (minor release)
- `--inspect` - Create only first epic, then ask to continue with remaining epics
- `--project "Name"` - Add issues to GitHub Project (future feature)
- No flag - Auto-detect populated file

**What it does:**
1. Detects and parses release file (current-release.md or minor-release.md)
2. Validates epic structure and spec references
3. **Creates Release tracking issue FIRST** (single source of truth for release progress)
4. **Checks for duplicate issues** (if found, closes old and creates new)
5. **Processes one epic at a time (epic + all child issues)**
6. For each epic:
   - Reads linked spec files
   - Researches specific details for each issue
   - Populates all template variables from specs
   - Creates epic on GitHub (or closes duplicate and recreates)
   - Links epic to Release issue (📦 Release: #N)
   - Creates all child issues with complete details
   - Links child issues to parent epic AND Release issue
7. **Updates Release issue with full epic/issue checklist**
8. **Writes GitHub issue numbers back to current-release.md**
9. Auto-fills metadata from tech-stack.md and assignment-rules.yml
10. Applies labels, assignees, and project assignments
11. Displays creation summary with Release issue link
12. **🔒 VERIFICATION STEP: Confirms ALL issues created in GitHub with proper issue numbers**
13. **🔒 VERIFICATION STEP: Confirms NO interim documentation files were created**

**Duplicate Prevention:**
- Before creating any issue, checks if an open issue with the same title exists
- If duplicate found: Closes the old issue and creates a new one with updated content
- This allows you to safely re-run `/scope-release` after fixing specs or templates
- Closed issues maintain history for reference

**Release Issue Tracking:**
- Release issue created FIRST with title: `[Release v{version}] {release name}`
- Contains checklist of all epics and child issues
- All epics and issues link back to Release issue (📦 Release: #N)
- Progress metrics automatically calculated (epics complete, issues complete, %)
- Status changes from "🚧 In Progress" to "✅ Ready for Release" when all work done
- Serves as single source of truth for release progress
- Labels: `release`, `v{version}`, `milestone`

## Workflow

```bash
# Build TypeScript first (if not already built)
npm run build

# Run the command with appropriate flag
node dist/scripts/scope-release.js {{FLAGS}}
```

**Parse user input for flags:**
- If user says "/scope-release --current" → run with --current
- If user says "/scope-release --minor" → run with --minor
- If user says "/scope-release --inspect" → run with --inspect (test mode)
- If user says "/scope-release --current --inspect" → run with both flags
- If user says "/scope-release" → run with no flags (auto-detect)
- If user says "/scope-release --project MyProject" → run with --project "MyProject"

**Inspect Mode (`--inspect` flag):**
- Creates ONLY the first epic + all its child issues
- If successful, displays summary and prompts: **"First epic created successfully. Create all remaining epics now? (y/n)"**
- If user responds `y` or `yes`: Creates all remaining epics without further prompts
- If user responds `n` or `no`: Exits, leaving remaining epics uncreated
- Useful for validating the workflow before creating dozens of issues

## Pre-Flight Validation Checklist

**CRITICAL:** Before creating ANY issues, validate all epics and specs.

### Validation Process

Run comprehensive checks on `current-release.md`:

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔍 PRE-FLIGHT VALIDATION
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Validating: current-release.md (v1.1.0)
Epics: 7
Issues: 35

Checking requirements for /scope-release...
```

### For Each Epic - Validate:

**1. Epic Structure Requirements:**
```javascript
✅ Has **Related Spec**: link
✅ Spec file exists at path
✅ Spec file is readable
✅ Has **Description**: text
✅ Has **Issues**: list (at least 1)
✅ All issue lines parseable
```

**2. Spec Content Requirements:**
```javascript
✅ Spec has Epic section matching epic title
✅ Spec has Issue subsections
✅ Spec has acceptance criteria
✅ Spec has technical approach
✅ Spec has at least 500 words (substantial)
```

**3. For Each Issue - Validate:**
```javascript
✅ Issue title present
✅ Classification present (1-10)
✅ Zone matches classification
   • 1-3 → ai-solo
   • 4-6 → ai-led
   • 7-8 → ai-assisted
   • 9-10 → ai-limited
✅ Has Spec § section reference
✅ Referenced spec section exists in file
✅ Spec section has >100 words (sufficient detail)
```

**4. Enrichment Validation (NEW):**
```javascript
✅ Overview & User Story section populated (no <!-- TODO: enrich -->)
✅ Acceptance Criteria section populated
✅ Technical Implementation section populated
✅ Dependencies section populated
✅ Estimated Effort section populated
```

### Validation Report Format

Display detailed report for each epic:

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
EPIC 1/7: Classification System Infrastructure
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Epic Validation:
  ✅ Related Spec: memory-bank/requirements/specs/ai-issue-classification.md
  ✅ Spec file exists (76 KB)
  ✅ Description present
  ✅ Has 5 issues

Spec Content Check:
  ✅ Epic section found (line 62)
  ✅ Has acceptance criteria (4 found)
  ✅ Has technical approach (8 paragraphs)
  ✅ Sufficient detail (2,635 words)

Issue 1: Update issue templates with classification field
  ❌ FAIL - Missing classification hint
  ❌ FAIL - Missing zone
  ❌ FAIL - Missing Spec § reference
  ⚠️  Cannot extract details without spec section reference

Issue 2: Remove emoji risk indicators from existing templates
  ❌ FAIL - Missing classification hint
  ❌ FAIL - Missing zone
  ❌ FAIL - Missing Spec § reference
  ⚠️  Cannot extract details without spec section reference

Issue 3: Add classification validation to scope-release
  ❌ FAIL - Missing classification hint
  ❌ FAIL - Missing zone
  ❌ FAIL - Missing Spec § reference
  ⚠️  Cannot extract details without spec section reference

❌ EPIC 1 NOT READY: 3/5 issues missing required metadata

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
EPIC 2/7: Constrained Resource Config & TOC Sequencing
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Epic Validation:
  ✅ Related Spec: memory-bank/requirements/specs/ai-issue-classification.md
  ✅ Spec file exists (76 KB)
  ✅ Description present
  ✅ Has 5 issues

Spec Content Check:
  ✅ Epic section found (line 62)
  ✅ Has acceptance criteria (4 found)
  ✅ Has technical approach (8 paragraphs)
  ✅ Sufficient detail (2,635 words)

Issue 1: Add resource configuration schema to roadcrew.yml
  ✅ Classification: 5 (ai-led)
  ✅ Zone matches classification
  ✅ Spec § Issue 1.2
  ✅ Spec section exists (line 141, 245 words)
  ✅ Ready to implement

Issue 2: Implement TOC sequencing algorithm
  ✅ Classification: 9 (ai-limited)
  ✅ Zone matches classification
  ✅ Spec § Epic 7 / Issue 7.1
  ✅ Spec section exists (line 892, 412 words)
  ✅ Ready to implement

✅ EPIC 2 READY: All 5 issues have complete metadata

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
VALIDATION SUMMARY
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Epic Status:
  ✅ Ready:     1/7 epics (Epic 2)
  ❌ Not Ready: 6/7 epics (Epics 1, 3, 4, 5, 6, 7)

Issue Status:
  ✅ Ready:     5/35 issues (14%)
  ❌ Not Ready: 30/35 issues (86%)

Critical Issues:
  • 30 issues missing classification hints
  • 30 issues missing zone labels
  • 30 issues missing Spec § references
  • Cannot extract details for 30 issues without spec sections

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
❌ VALIDATION FAILED - NOT READY FOR ISSUE CREATION
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Recommendation:
  Run: /advance-release --update
  This will validate and enrich current-release.md with:
    • Classification hints for all issues
    • Zone labels based on classification
    • Spec § section references
    • Verification that spec sections exist

After enrichment, re-run /scope-release to create issues.
```

### Validation Failure Behavior

**If validation fails:**
1. ❌ DO NOT create any GitHub issues
2. Show detailed validation report
3. List all missing requirements
4. Suggest next steps to fix issues
5. Exit with error code 1

**If enrichment incomplete:**
```
❌ ENRICHMENT INCOMPLETE

Issues missing enrichment: 12/35 (34%)

Not ready for issue creation:
  • Issue 1.1: Missing Overview & User Story
  • Issue 1.2: Missing Technical Implementation
  • Issue 2.1: Missing Acceptance Criteria
  [... more issues ...]

Next step: Run /enrich-release to populate missing details
```

**If validation passes:**
1. ✅ Show success summary
2. ✅ Analyze issue grouping opportunities
3. ✅ Analyze dependencies and sequencing
4. Ask for confirmation to proceed
5. Create all epics and issues

---

## Validation Architecture

**IMPORTANT:** `/scope-release` uses **two complementary validation layers** to ensure release quality:

**Layer 1: Size & Effort Validation** (PR #318)
- Validates epic sizing (2-25 issues, ≤40 hours)
- Validates issue effort (2-14 hours per issue)
- Validates classification consistency (hours match zone)
- Runs BEFORE GitHub creation (stops if invalid)
- See: `scripts/utils/issue-classification.ts`

**Layer 2: Template Format Validation** (Epic #296)
- Validates Release/Epic/Enhancement templates (YAML, title, labels)
- Validates no enrichment placeholders remain
- Runs AFTER GitHub creation (stops if invalid)
- See: `scripts/utils/release-issue-manager.ts`

**See full details:** `docs/VALIDATION-LAYERS.md` (Issue #323)

These layers are complementary:
- Layer 1 validates WHAT was created (sizes, efforts)
- Layer 2 validates HOW it was created (structure, format)

Both must pass before `/scope-release` completes successfully.

---

## Issue Grouping Analysis (NEW)

After validation passes, analyze if small/related issues should be merged.

### Merging Criteria

Consider merging two issues if:
1. **Both are small** (classification ≤ 3) AND independent
2. **Both are related** (same files, same subsystem) AND can be worked together
3. **Total complexity** after merge is still ≤ 6 (ai-led zone)

### Analysis Process

```typescript
function analyzeIssueGrouping(issues: Issue[]): MergeRecommendation[] {
  const recommendations: MergeRecommendation[] = [];
  
  for (let i = 0; i < issues.length - 1; i++) {
    for (let j = i + 1; j < issues.length; j++) {
      const issue1 = issues[i];
      const issue2 = issues[j];
      
      // Check if both are small
      const bothSmall = issue1.classification <= 3 && issue2.classification <= 3;
      
      // Check if related (similar files in technical implementation)
      const relatedFiles = findCommonFiles(
        issue1.technicalImplementation,
        issue2.technicalImplementation
      );
      const isRelated = relatedFiles.length > 0;
      
      // Check combined complexity
      const combinedComplexity = Math.max(
        issue1.classification + 1,
        issue2.classification + 1
      );
      const staysInAiLed = combinedComplexity <= 6;
      
      if ((bothSmall || isRelated) && staysInAiLed) {
        recommendations.push({
          issue1: issue1.fullId,
          issue2: issue2.fullId,
          reason: bothSmall ? 'Both are small and can be combined' : 'Related work in same files',
          estimatedNewComplexity: combinedComplexity,
          confidence: isRelated ? 'high' : 'medium'
        });
      }
    }
  }
  
  return recommendations;
}
```

### Display Merge Recommendations

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
💡 ISSUE GROUPING ANALYSIS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Found 3 merge opportunities:

1. Merge Issue 1.1 + Issue 1.2
   Reason: Both are small (classification 2, 2)
   Combined: Classification ~3 (ai-solo)
   Files: templates/issue-enhancement.template.md, templates/epic.template.md
   Confidence: HIGH
   
2. Merge Issue 3.2 + Issue 3.3
   Reason: Related work in same files
   Combined: Classification ~6 (ai-led)
   Files: scripts/commands/scope-release.ts
   Confidence: MEDIUM

Recommendations:
  • Accept merge #1 to reduce issue count and simplify workflow
  • Consider merge #2 if implementation order allows
  • Issue #3 skipped (combined complexity too high)

Apply suggested merges? (y/n/selective): _
```

**If user accepts merges:**
- Combine issue titles: "Issue 1.1+1.2: [Title 1] and [Title 2]"
- Merge acceptance criteria into single list
- Combine technical implementation steps
- Update dependencies for merged issue
- Adjust classification to combined value

---

## Dependency & Sequencing Analysis (NEW)

After grouping analysis, analyze optimal issue sequence.

### Dependency Extraction

Parse each issue's Dependencies section:

```typescript
interface DependencyGraph {
  nodes: Array<{
    issueId: string;
    dependsOn: string[]; // Must complete before this
    blocks: string[];    // This blocks these issues
  }>;
}

function buildDependencyGraph(issues: Issue[]): DependencyGraph {
  const nodes = issues.map(issue => {
    const dependsOn = extractDependencies(issue.dependencies, 'Depends on');
    const blocks = extractDependencies(issue.dependencies, 'Blocks');
    
    return { issueId: issue.fullId, dependsOn, blocks };
  });
  
  return { nodes };
}
```

### Sequencing Algorithm

1. **Identify Critical Path**: Longest dependency chain
2. **Find Parallelizable Work**: Issues with no dependencies
3. **Detect Cycles**: Report circular dependencies as errors
4. **Optimize for Expert Protection**: Sequence high-complexity work last

```typescript
function analyzeSequencing(graph: DependencyGraph): SequenceAnalysis {
  // Topological sort with depth tracking
  const sorted = topologicalSort(graph);
  const criticalPath = findLongestPath(graph);
  const parallelGroups = groupParallelizable(sorted);
  
  return {
    optimalSequence: sorted,
    criticalPath,
    parallelGroups,
    expertWorkGroups: groupByClassification(sorted, 7, 10) // ai-assisted + ai-limited
  };
}
```

### Display Sequencing Report

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📊 DEPENDENCY & SEQUENCING ANALYSIS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Critical Path (longest dependency chain):
  Issue 1.1 → 1.3 → 2.1 → 2.2 (4 issues, ~18 hours)

Optimal Sequence (by wave):

Wave 1 (Parallel - No dependencies):
  • Issue 1.1 (2h) - Classification: 4 (ai-led)
  • Issue 1.2 (1h) - Classification: 2 (ai-solo)
  • Issue 1.4 (2h) - Classification: 3 (ai-solo)
  Total: 5 hours (can be done in parallel)

Wave 2 (Depends on Wave 1):
  • Issue 1.3 (4h) - Classification: 5 (ai-led) - Depends on 1.1
  • Issue 1.5 (2h) - Classification: 3 (ai-solo)
  Total: 6 hours

Wave 3 (Depends on Wave 2):
  • Issue 2.1 (6h) - Classification: 7 (ai-assisted) - Depends on 1.3
  • Issue 2.3 (4h) - Classification: 6 (ai-led)
  Total: 10 hours

Expert Work (Classification 7-10):
  • Issue 2.1 (Wave 3)
  • Issue 2.2 (Wave 4) 
  • Issue 6.1 (Wave 5)
  Recommendation: Sequence last to protect expert capacity

Circular Dependencies:
  ✅ None detected

Bottlenecks:
  ⚠️  Issue 1.3 blocks 3 other issues (2.1, 2.2, 3.1)
     Recommendation: Prioritize completion of Issue 1.3

Total Estimated Time:
  • Sequential: 87 hours
  • Optimal parallel: 42 hours (52% reduction)
```

---

### Validation Confirmation Prompt

After successful validation, grouping, and sequencing:

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ VALIDATION PASSED - READY FOR ISSUE CREATION
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

All Requirements Met:
  ✅ 7/7 epics have valid spec links
  ✅ 7/7 spec files exist and have sufficient detail
  ✅ 35/35 issues have classification hints
  ✅ 35/35 issues have zone labels
  ✅ 35/35 issues have Spec § references
  ✅ All spec sections exist and have detail

Ready to create:
  • 7 epic issues
  • 35 child issues
  • Total: 42 GitHub issues

This will:
  • Close any duplicate open issues with same titles
  • Create new issues with complete specifications
  • Link child issues to parent epics

Continue with issue creation? (y/n): _
```

**If user types 'y' or 'yes':**
- Proceed with epic-by-epic creation

**If user types 'n' or 'no':**
- Exit without creating issues

### Validation Quality Gates

**Minimum requirements to pass validation:**

```javascript
// Epic-level gates
epic.hasSpecLink === true
epic.specFileExists === true
epic.specFileReadable === true
epic.description.length > 50
epic.issues.length >= 1

// Spec content gates
spec.wordCount > 500
spec.hasEpicSection === true
spec.hasAcceptanceCriteria === true
spec.hasTechnicalApproach === true

// Issue-level gates (all must pass)
issue.hasTitle === true
issue.classification >= 1 && issue.classification <= 10
issue.zoneMatchesClassification === true
issue.hasSpecSection === true
issue.specSectionExists === true
issue.specSectionWordCount > 100
```

**If ANY gate fails:**
- Entire validation fails
- No issues created
- User must fix issues and re-run

### Spec Section Validation Details

**For each Spec § reference, validate:**

1. **Parse section reference:**
   ```
   "Spec § Issue 1.2" → Look for "Issue 1.2" heading
   "Spec § Epic 7 / Issue 7.1" → Look for "Epic 7" then "Issue 7.1"
   ```

2. **Find section in spec file:**
   - Search for heading match
   - Case-insensitive
   - Accept variations (Issue 1.2, 1.2, Issue 1.2:)

3. **Validate section has content:**
   - Count words in section
   - Minimum 100 words required
   - Check for code examples
   - Check for acceptance criteria

4. **Report section status:**
   ```
   ✅ Spec § Issue 1.2 found (line 141, 245 words, 2 code blocks)
   ❌ Spec § Issue 3.4 NOT FOUND in spec file
   ⚠️  Spec § Issue 2.1 found but insufficient detail (45 words)
   ```

## Epic-by-Epic Processing

**Critical:** Process one epic at a time to ensure complete issue specifications.

### For Each Epic:

**Step 0: Validation Already Complete**
- Pre-flight validation passed
- All spec files loaded
- All section references validated
- Ready to create issues

**Step 1: Parse Epic Structure**
```markdown
### EPIC 2: Constrained Resource Config & TOC Sequencing
**Related Spec**: [memory-bank/requirements/specs/ai-issue-classification.md](...)
**Description**: [Overview]

**Issues**:
- [ ] Add resource configuration schema - Classification: 5, Spec § 1.2
- [ ] Implement TOC sequencing - Classification: 9, Spec § 1.3
```

**Step 2: Read Spec File**
- Open the linked spec file (e.g., `memory-bank/requirements/specs/ai-issue-classification.md`)
- Load full spec content into context

**Step 3: Research Issue Details**

For each child issue in the epic:

1. **Locate spec section** (from § reference)
2. **Extract complete details:**
   - Acceptance criteria (replace `{{ACCEPTANCE_CRITERION_N}}`)
   - Technical implementation approach (replace `TBD`)
   - User story (replace `TBD`)
   - Dependencies (actual issue numbers or "None")
   - Effort estimate (size, complexity)
   - Related spec sections

3. **Populate template completely:**
   ```markdown
   # [1 of 5] Add resource configuration schema to roadcrew.yml
   
   ## Overview & User Story
   
   **As a** product manager
   **I want** resource constraints defined in configuration
   **So that** TOC optimization protects expert capacity
   
   ## Acceptance Criteria
   
   - [ ] Schema validates resource types (expert/junior/ai)
   - [ ] Supports capacity limits per resource
   - [ ] Classification min/max constraints defined
   - [ ] Config file validation on load
   
   ## Technical Implementation
   
   Add YAML schema to roadcrew.yml based on spec lines 141-159:
   - Define resources block with expert/junior/ai types
   - Add capacity fields (hours/week)
   - Add classification_min/max constraints
   - Integrate with existing config validation
   
   ## Dependencies
   
   - **Depends on:** None (foundational)
   - **Blocks:** #[Next Issue Number] (TOC algorithm needs config)
   
   ## Estimated Effort
   
   **Size:** Medium
   **Complexity:** Medium (schema design + validation)
   ```

**Step 4: Create GitHub Issues (Unified Module)**

**The issue creation process uses the unified GitHub issue creator:**

```typescript
import { createEpicIssue, createEnhancementIssue } from './core/github-issue-creator.js';

// Create epic using unified module
const epicResult = await createEpicIssue(epicTitle, epicBody);
const epicNumber = epicResult.number;
console.log(`Created Epic #${epicNumber}`);

// Create child issues in sequence
const childNumbers = [];
for (let i = 0; i < issues.length; i++) {
  const issue = issues[i];
  const childResult = await createEnhancementIssue(
    issue.title,
    issue.body,
    i + 1,
    issues.length
  );
  childNumbers.push(childResult.number);
  console.log(`Created #${childResult.number}: ${issue.title}`);
}
```

**What the Unified Module Handles Automatically:**
- ✅ Template population (using @epic.template.md and @enhancement.template.md)
- ✅ GitHub API interaction (with automatic CLI fallback)
- ✅ Issue number extraction and verification
- ✅ Proper link formatting for epic → child relationship
- ✅ Shell escaping and security validation
- ✅ Duplicate detection and prevention

**You Don't Need To:**
- ❌ Run `gh issue create` commands manually
- ❌ Parse GitHub output for issue numbers
- ❌ Manually verify issues were created
- ❌ Handle shell escaping
- ❌ Worry about API failures (fallback to CLI automatic)

**Next: Use /create-epic Command**
Instead of manual GitHub commands, use the `/create-epic` command which orchestrates this entire process:
```
/create-epic
```

**Step 5: Link Issues**
- Update epic description with child issue links
- Add "Related Epic: #N" to each child issue

**Step 6: Move to Next Epic**
- Repeat steps 1-5 for next epic

**Step 7: Write Issue Numbers Back to current-release.md**

After ALL epics and issues are created successfully:

1. **Read current-release.md**
2. **For each epic, find its section and add GitHub Issue number:**
   ```markdown
   # BEFORE:
   ### EPIC 1: Classification System Infrastructure
   **Description**: Replace risk indicators with 1-10 classification scale
   
   # AFTER:
   ### EPIC 1: Classification System Infrastructure
   **GitHub Issue**: #903
   **Description**: Replace risk indicators with 1-10 classification scale
   ```

3. **For each child issue within an epic, add GitHub Issue number:**
   ```markdown
   # BEFORE:
   #### Issue 1.1: Update issue templates with classification field
   
   **Classification**: 4 (ai-led)
   
   # AFTER:
   #### Issue 1.1: Update issue templates with classification field
   
   **GitHub Issue**: #906
   **Classification**: 4 (ai-led)
   ```

4. **Write the updated content back to current-release.md**

**Implementation notes:**
- Add `**GitHub Issue**: #N` on a new line immediately after the epic/issue heading
- Place before any other metadata fields (Description, Classification, etc.)
- Preserve all existing content - only add issue number lines
- Use regex to find epic/issue headings: `^### EPIC \d+:` and `^#### Issue \d+\.\d+:`
- Insert new line after heading, before any existing content

**Success message:**
```
✅ Updated current-release.md with GitHub issue numbers:
   7 epics
   35 child issues
```

**Benefits:**
- ✅ Single source of truth: current-release.md contains GitHub issue numbers
- ✅ Enables `/sync-release-status` to read issue numbers and update checkboxes
- ✅ Makes it easy to reference issues when reviewing progress
- ✅ Supports future automation (close issues, track status, etc.)

---

**Step 8: CRITICAL - Verify ALL GitHub Issues Created Successfully**

**MANDATORY VALIDATION:** Before completing scope-release, verify that ALL expected issues were created in GitHub with proper issue numbers.

### What This Validates

```
RELEASE ISSUE:
  ✅ Release tracking issue created
  ✅ Issue number extracted (e.g., #905)
  ✅ Recorded in current-release.md

FOR EACH EPIC:
  ✅ Epic issue created in GitHub
  ✅ Issue number extracted (e.g., #906)
  ✅ Recorded in current-release.md
  ✅ All child issues linked to epic
  ✅ All child issues linked to Release issue
  
FOR EACH CHILD ISSUE:
  ✅ Issue created in GitHub
  ✅ Issue number extracted (e.g., #907)
  ✅ Recorded in current-release.md
  ✅ Linked to parent epic
  ✅ Linked to Release issue
  ✅ No template placeholders remain ({{...}} removed)
  ✅ Full enrichment applied (no <!-- TODO: enrich --> markers)
```

### Validation Process

**Step 8.1: Parse current-release.md for Issue Numbers**

Read the file that was just updated and extract ALL issue numbers:

```typescript
interface ReleaseIssueNumbers {
  releaseIssue: string;           // #905
  epics: Array<{
    epicNumber: number;           // 1
    epicTitle: string;            // "Basic License Gating"
    githubIssue: string;           // #906
    childIssues: Array<{
      issueNumber: string;        // "1.1"
      issueTitle: string;         // "Client-Side License Validation"
      githubIssue: string;        // #907
    }>;
  }>;
}
```

**Parse and validate structure:**

```javascript
const releaseMatch = content.match(/\*\*GitHub Issue\*\*:\s*#(\d+)/);
if (!releaseMatch) {
  ❌ FAIL: Release issue number not found in current-release.md
}
const releaseIssue = `#${releaseMatch[1]}`;

// For each EPIC section
for each "### EPIC N:" heading {
  const epicMatch = heading.match(/EPIC\s+(\d+):\s*(.+?)$/);
  const epicNum = epicMatch[1];
  const epicTitle = epicMatch[2];
  
  // Look for **GitHub Issue**: #NNN immediately after heading
  const nextContent = getNextSection(heading);
  const epicIssueMatch = nextContent.match(/\*\*GitHub Issue\*\*:\s*#(\d+)/);
  
  if (!epicIssueMatch) {
    ❌ FAIL: Epic ${epicNum} (${epicTitle}) - GitHub issue number not found
  }
  const epicIssue = `#${epicIssueMatch[1]}`;
  
  // For each ISSUE within epic
  for each "#### Issue N.M:" heading {
    const issueMatch = heading.match(/Issue\s+(\d+\.\d+):\s*(.+?)$/);
    const issueNum = issueMatch[1];
    const issueTitle = issueMatch[2];
    
    // Look for **GitHub Issue**: #NNN immediately after heading
    const nextContent = getNextSection(heading);
    const issueIssueMatch = nextContent.match(/\*\*GitHub Issue\*\*:\s*#(\d+)/);
    
    if (!issueIssueMatch) {
      ❌ FAIL: Issue ${issueNum} (${issueTitle}) - GitHub issue number not found
    }
    const issueIssue = `#${issueIssueMatch[1]}`;
    
    // Verify no enrichment placeholders remain
    if (nextContent.includes('<!-- TODO: enrich -->')) {
      ❌ FAIL: Issue ${issueNum} - Still contains enrichment placeholders
    }
  }
}
```

**Step 8.2: Verify Each Issue Exists in GitHub**

For EACH issue number extracted above, verify it exists in GitHub:

```bash
# For release issue
gh issue view #905 --json title,labels,state

# For each epic
gh issue view #906 --json title,labels,state

# For each child issue
gh issue view #907 --json title,labels,state
```

**Expected output for each:**
```json
{
  "title": "[Epic] Basic License Gating (Phase 1...)",
  "labels": ["epic", "v1.6.0", "release"],
  "state": "OPEN"
}
```

**If any issue doesn't exist in GitHub:**
```
❌ VALIDATION FAILED: Issue #906 not found in GitHub
   Expected: Epic 1 - Basic License Gating
   Status: Cannot find this issue in the repository
   
   This indicates GitHub creation failed.
   Do not proceed - investigate why issue creation failed.
```

**Step 8.3: Verify No Interim Documentation Created**

Check that NO markdown files were created in `context/` for issues:

```bash
# Should NOT exist (these are interim documentation - FORBIDDEN):
ls -la memory-bank/requirements/source-docs/[release-name]/
ls -la memory-bank/requirements/specs/[new-files].md
ls -la context/prds/[new-files].md

# Git status should NOT show new .md files:
git status --short | grep "??" | grep "\.md"
```

**If interim documentation found:**
```
❌ VALIDATION FAILED: Interim documentation created
   Found files:
   - memory-bank/requirements/source-docs/license-enforcement/issue-1-1.md
   - memory-bank/requirements/source-docs/license-enforcement/issue-1-2.md
   
   ERROR: scope-release should NEVER create interim documentation files.
   All issues MUST be created directly in GitHub.
   
   Delete interim files and ensure issues exist in GitHub.
```

**Step 8.4: Generate Verification Report**

Display comprehensive verification:

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ GITHUB ISSUE VERIFICATION REPORT
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Release: v1.6.0 - License Enforcement MVP

Verification Checklist:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

RELEASE ISSUE:
  ✅ Issue #905 exists in GitHub
  ✅ Title: [Release v1.6.0] License Enforcement MVP - Basic Monetization
  ✅ Labels: release, v1.6.0, milestone
  ✅ Status: OPEN (🚧 In Progress)
  ✅ Recorded in current-release.md: **GitHub Issue**: #905

EPIC 1: Basic License Gating (Phase 1 - Tier 1 Client-Side)
  ✅ Epic issue #906 exists in GitHub
  ✅ Title: [Epic] Basic License Gating (Phase 1 - Tier 1 Client-Side)
  ✅ Labels: epic, v1.6.0, release
  ✅ Status: OPEN
  ✅ Recorded in current-release.md: **GitHub Issue**: #906
  
  ✅ Issue #907 exists in GitHub
     Client-Side License Validation (Simplified)
     Classification: 8 (ai-limited)
     No enrichment placeholders
  ✅ Recorded in current-release.md: **GitHub Issue**: #907
  
  ✅ Issue #908 exists in GitHub
     Manual Trial Key Generation Script
     Classification: 6 (ai-led)
     No enrichment placeholders
  ✅ Recorded in current-release.md: **GitHub Issue**: #908

EPIC 2: Token Awareness (Phase 1 - Local Logging Only)
  ✅ Epic issue #909 exists in GitHub
  ✅ Title: [Epic] Token Awareness (Phase 1 - Local Logging Only)
  ✅ Labels: epic, v1.6.0, release
  ✅ Status: OPEN
  ✅ Recorded in current-release.md: **GitHub Issue**: #909
  
  ✅ Issue #910 exists in GitHub
     Token Usage Logging (Simplified)
     Classification: 5 (ai-led)
     No enrichment placeholders
  ✅ Recorded in current-release.md: **GitHub Issue**: #910

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

INTERIM DOCUMENTATION CHECK:
  ✅ No interim .md files created
  ✅ All work created directly in GitHub
  ✅ No memory-bank/requirements/source-docs/ files for individual issues
  ✅ No memory-bank/requirements/specs/ files for individual issues
  ✅ No context/prds/ files for individual issues

ENRICHMENT CHECK:
  ✅ All 3 child issues fully enriched (no <!-- TODO: enrich --> markers)
  ✅ No template placeholders remain in issues
  ✅ All acceptance criteria populated
  ✅ All technical implementations specified

LINKING VERIFICATION:
  ✅ All child issues linked to parent epics
  ✅ All epics linked to Release issue (#905)
  ✅ All child issues linked to Release issue (#905)
  ✅ Dependencies properly linked (Issue #910 → #907)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

SUMMARY:
  Total Issues Created: 6
    • Release issues: 1
    • Epic issues: 2
    • Child issues: 3
  
  All Issue Numbers: #905, #906, #907, #908, #909, #910
  
  Verification Result: ✅ ALL CHECKS PASSED
  
  Files Updated:
    • memory-bank/releases/current-release.md (6 issue numbers added)
    • memory-bank/activeContext.md (3 issue numbers synced)
  
  Status: ✅ READY FOR IMPLEMENTATION

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```

### Failure Cases - Stop and Report

**If validation fails at ANY point:**

❌ **Case 1: Issue Number Not Found in current-release.md**
```
❌ VERIFICATION FAILED

Issue #906 exists in GitHub but is NOT recorded in current-release.md

Expected: **GitHub Issue**: #906 in Epic 1 section
Found: None

REASON: Epic creation succeeded but number was not written back to file

ACTION REQUIRED:
  1. Manually add **GitHub Issue**: #906 to Epic 1 section in current-release.md
  2. Re-run this verification: /scope-release --verify
```

❌ **Case 2: GitHub Issue Does Not Exist**
```
❌ VERIFICATION FAILED

Issue #906 listed in current-release.md but DOES NOT EXIST in GitHub

Expected: Epic issue for "Basic License Gating"
Found: No issue with number #906

REASON: GitHub creation failed (possible rate limit, auth error, etc.)

ACTION REQUIRED:
  1. Check GitHub authentication: gh auth status
  2. Manually create the issue in GitHub
  3. Update current-release.md with correct issue number
  4. Verify all issues: /scope-release --verify
```

❌ **Case 3: Interim Documentation Found**
```
❌ VERIFICATION FAILED

Interim documentation files detected:
  - memory-bank/requirements/source-docs/license-enforcement/issue-1-1.md
  - memory-bank/requirements/source-docs/license-enforcement/issue-1-2.md

REASON: scope-release created markdown files instead of GitHub issues

ERROR POLICY: This violates the scope-release contract.
All work MUST be created in GitHub, NOT as interim documentation.

ACTION REQUIRED:
  1. Delete interim files: git rm memory-bank/requirements/source-docs/...
  2. Verify issues exist in GitHub with proper GitHub issue numbers
  3. Update current-release.md with issue numbers
  4. Commit and proceed
```

❌ **Case 4: Enrichment Placeholders Still Present**
```
❌ VERIFICATION FAILED

Issue #907 still contains enrichment placeholders:
  - Line 165: <!-- TODO: enrich | Overview -->
  - Line 173: <!-- TODO: enrich | Acceptance Criteria -->

REASON: /enrich-release was not run before /scope-release
        OR issue creation did not populate enriched content

ACTION REQUIRED:
  1. Run /enrich-release to populate issue details
  2. Re-run /scope-release to create issues with enriched content
```

### Success - Verification Passed

If ALL checks pass:

```
✅ VERIFICATION COMPLETE - ALL CHECKS PASSED

v1.6.0 Release is ready for implementation:
  • 6 GitHub issues created (Release + 2 Epics + 3 Child Issues)
  • All issue numbers recorded in current-release.md
  • All issue numbers synced to memory-bank/activeContext.md
  • No interim documentation created
  • All enrichment complete and applied
  • All dependencies linked

Next Steps:
  1. Review created issues at: https://github.com/roadcrew/issues/905
  2. Run /autopilot [epic-number] to implement each epic
  3. Track progress using Release issue #905
```

### Optional --verify Flag

Allow users to re-run verification without recreating issues:

```bash
/scope-release --verify
```

This runs ONLY steps 8.2-8.4 (verification) without creating any new issues.

Useful for:
- Checking if all issues were properly created
- Fixing missing issue numbers in current-release.md
- Verifying no interim documentation remains

---

## Step 9: Update GitHub Issue Numbers in memory-bank/activeContext.md

After updating `current-release.md`, sync the GitHub issue numbers to the activeContext.md summary:

**Update Release GitHub Issue:**
```markdown
# Before:
### **v1.6.0: License Enforcement MVP - Basic Monetization** ⏳ PENDING

**GitHub Issue:** #{{CURRENT_RELEASE_GITHUB_ISSUE}}

# After:
### **v1.6.0: License Enforcement MVP - Basic Monetization** ⏳ PENDING

**GitHub Issue:** #905
```

**Update Epic GitHub Issues:**
```markdown
# Before:
**Scope:**
- Epic 1: Basic License Gating (Client-side validation, no server calls) **GitHub Issue:** #{{CURRENT_RELEASE_EPIC_1_GITHUB_ISSUE}}
- Epic 2: Token Awareness (Local logging only, no hard blocking) **GitHub Issue:** #{{CURRENT_RELEASE_EPIC_2_GITHUB_ISSUE}}

# After:
**Scope:**
- Epic 1: Basic License Gating (Client-side validation, no server calls) **GitHub Issue:** #906
- Epic 2: Token Awareness (Local logging only, no hard blocking) **GitHub Issue:** #907
```

**Implementation notes:**
- Extract release GitHub issue number from current-release.md (line 1: `**GitHub Issue**: #NNN`)
- Extract each epic GitHub issue number from current-release.md epic sections
- Update `memory-bank/activeContext.md` in the current release section under **"Scope:"**
- Replace template variables like `#{{CURRENT_RELEASE_GITHUB_ISSUE}}` with actual issue numbers
- Replace epic template variables like `#{{CURRENT_RELEASE_EPIC_1_GITHUB_ISSUE}}` with actual epic issue numbers
- Preserve all other content in activeContext.md - only update the GitHub issue numbers

**Success message:**
```
✅ Updated memory-bank/activeContext.md with GitHub issue numbers:
   Release issue: #905
   2 epic issue numbers updated (Epic 1: #906, Epic 2: #907)
   
   Vision.md now synced with current-release.md
```

**Benefits:**
- ✅ Vision.md summary stays current with actual GitHub issue numbers
- ✅ Easy to click through from vision to GitHub issues for reference
- ✅ Maintains alignment between strategic roadmap and GitHub tracking
- ✅ Enables future automation to sync release progress back to vision

---

## Configuration Required

Before running, ensure:
1. `config/assignment-rules.yml` exists (copy from `templates/assignment-rules.template.yml`)
2. `memory-bank/techContext.md` exists (run `/analyze-repo` to generate)
3. Release file is populated with:
   - Epic titles and descriptions
   - **Spec file links** (e.g., `memory-bank/requirements/specs/[name].md`)
   - Child issue titles with classification hints
   - Spec section references (§ notation)
4. All spec files referenced exist in `memory-bank/requirements/specs/`

**Note:** `/advance-release` should generate properly structured release files automatically

## Success Output

**For epic-based releases:**
```
✅ GitHub structure created from current-release.md

Release: v1.1.0
Type: current-release

Created Structure:
- Epic #N: Classification System
  - #N+1: [1 of 5] Update templates
  - #N+2: [2 of 5] Add validation
  ...
  
Total: X epics, Y issues
```

**For flat releases:**
```
✅ GitHub issues created from minor-release.md

Release: v1.0.1

Created Issues:
- #N: [v1.0.1] Fix bug in parser
- #N+1: [v1.0.1] Update docs
...

Total: X issues
```

## Error Handling

Common errors and solutions:

**"Epic missing spec link"**
- Solution: Ensure epic has `**Related Spec**: [path]` line
- Check `/advance-release` generated proper structure

**"Spec file not found"**
- Solution: Verify spec file exists at referenced path
- Create spec file if missing (use `templates/spec.template.md`)

**"Could not extract issue details from spec"**
- Solution: Check spec has proper structure with sections
- Ensure spec section references (§) match actual content

**"could not add label: 'major-release' not found"**
- Solution: Create label with `gh label create "major-release" --color "0366d6"`

**"No populated release file found"**
- Solution: Run `/advance-release` first to generate current-release.md

**GitHub authentication errors:**
- Solution: Follow authentication setup in `.cursor/rules/03-github.mdc` (lines 20-25)

**Duplicate issues after re-running:**
- This is handled automatically! Duplicates are closed and recreated
- Old issues remain in history for reference
- Safe to re-run after updating specs or templates

## Quality Guarantees

**Pre-Flight Validation (NEW):**
- ✅ Validates ALL epics and issues BEFORE creating any GitHub issues
- ✅ Checks spec files exist and have sufficient detail
- ✅ Verifies classification hints and zones are present
- ✅ Confirms Spec § references point to actual sections
- ✅ Fails fast with detailed report if ANY requirement missing
- ✅ Prevents creation of incomplete issues

**No more incomplete issues:**
- ✅ All template variables populated from specs
- ✅ All acceptance criteria specific and testable
- ✅ All technical approaches clearly described
- ✅ All dependencies identified and linked
- ✅ All effort estimates provided

**If validation fails:**
- ❌ Stop immediately - do NOT create any GitHub issues
- 📋 Show detailed validation report with all failures
- 💡 Suggest running `/advance-release --update` to fix issues
- 🔄 Exit with error - user must fix and re-run

**If spec details insufficient:**
- Stop and report which issue needs more detail
- Request user to update spec file
- Do not create issue with placeholders

## Research Process Details

**For each issue, research from spec:**

1. **Acceptance Criteria:**
   - Look for "Acceptance Criteria" sections in spec
   - Look for "Definition of Done" 
   - Convert to specific, testable statements
   - Replace `{{ACCEPTANCE_CRITERION_N}}` with actual criteria

2. **Technical Implementation:**
   - Find relevant code examples in spec
   - Extract file paths, function names, algorithms
   - Note architecture changes required
   - Replace `TBD` with specific approach

3. **User Story:**
   - Extract "As a...I want...So that" from spec context
   - Infer from epic description if not explicit
   - Replace `TBD` with complete user story

4. **Dependencies:**
   - Parse spec for dependency mentions
   - Identify prerequisite issues within epic
   - Note external dependencies
   - Replace "#None" with actual dependencies or "None"

5. **Effort Estimate:**
   - Use classification level as guide:
     - 1-3: Small (1-4 hours)
     - 4-6: Medium (4-8 hours)
     - 7-8: Large (8-16 hours)
     - 9-10: X-Large (16+ hours)
   - Factor in spec complexity indicators
   - Replace generic estimates with specific

## Notes

- Built with Epic #105
- See documentation: `docs/COMMANDS.md` (search for /scope-release)
- Config file: `config/assignment-rules.yml` (GitHub project + assignments)
- Tech stack: Auto-loaded from `memory-bank/techContext.md` (generated by /analyze-repo)
- **Pre-flight validation prevents incomplete issues** (validates before creating ANY issues)
- **Epic-by-epic processing ensures complete issue specifications**
- **No more template placeholders in created issues**
- **Fail-fast approach saves time** (catches issues before creating 42 GitHub issues)

## Workflow Recommendation

```
1. /advance-release --update     # Validate and enrich current-release.md
2. /scope-release --current      # Pre-flight validation + create issues
```

This two-step workflow ensures:
- ✅ All metadata present before creating issues
- ✅ All spec references validated
- ✅ No wasted GitHub issues with TBD placeholders
- ✅ Fast feedback loop (fix → validate → create)

---

**Step 3.5: VALIDATION - Verify Release Issue Template Format**

**PURPOSE:** Ensure Release issue created with correct template format (YAML frontmatter, title format, and labels) before proceeding to epic creation. This validation prevents malformed Release issues that would break downstream automation.

**When it runs:** Immediately after Release issue creation, before proceeding to project setup and epic creation.

**What it validates:**

```
1. YAML FRONTMATTER VALIDATION
   ✅ Has opening delimiter: ---
   ✅ Has closing delimiter: ---
   ✅ Contains version field: version: vX.Y.Z
   ✅ Version format is valid: Must match vX.Y.Z pattern

2. TITLE FORMAT VALIDATION
   ✅ Follows template: [Release] {name}
   ✅ No version in title (version goes in labels)
   ✅ NOT: [Release v1.6.6] {name} ❌
   ✅ Correct: [Release] v1.6.6 - Freemium Model ✅

3. LABELS VALIDATION
   ✅ Has required label: release
   ✅ Has required label: milestone
   ✅ Has version label: vX.Y.Z (extracted from frontmatter)
```

**Implementation:**

Immediately after Release issue creation:

```typescript
// Step 3.5: Validate Release template format
console.log('\nStep 3.5: Validating Release issue template format...\n');

const validation = await validateReleaseTemplateFormat(releaseIssueNumber);

if (!validation.valid) {
  displayReleaseValidationErrors(validation.errors);
  throw new ReleaseTemplateValidationError(
    `Release issue #${releaseIssueNumber} failed template validation`
  );
}

console.log('✅ Release issue template format is valid\n');
```

**Error Handling:**

If Release validation FAILS:
- 🛑 **STOP** - Do NOT proceed to epic creation
- 📋 Display detailed error report showing EXACTLY what failed:
  - Missing YAML delimiters
  - Invalid version format
  - Version in title
  - Missing required labels
- 📝 Show resolution steps
- ⏸️  Exit with non-zero status (process.exit(1))

If Release validation PASSES:
- ✅ Log success message
- ➡️  Continue to project setup and epic creation

**Example error output:**

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
❌ RELEASE TEMPLATE VALIDATION FAILED
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

  ❌ Version should not be in title. Found version pattern in: "[Release v1.6.6] Model"
  ❌ Missing required label: "milestone"
  ❌ Missing version label (expected format: vX.Y.Z)

📝 Resolution:
   1. Fix all validation errors in the Release issue
   2. Ensure YAML frontmatter with version field
   3. Remove version from title (goes in labels)
   4. Apply release + milestone labels
   5. Re-run scope-release to continue

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```

**Related to Issue #302:** This validation is implemented as part of Epic #296 Phase 3, ensuring template compliance in `/scope-release` before any downstream processing.

---

**Step 5.1: VALIDATION - Verify Epic Issue Template Format**

**PURPOSE:** Validate each Epic issue has correct template format (YAML frontmatter, title format, and labels) immediately after creation. This ensures consistent epic structure before creating child issues.

**When it runs:** After each epic is created in Step 5 (right after creating epic + all its child issues).

**What it validates per Epic:**

```
1. YAML FRONTMATTER VALIDATION
   ✅ Has opening delimiter: ---
   ✅ Has closing delimiter: ---
   ✅ Contains proper YAML structure

2. TITLE FORMAT VALIDATION
   ✅ Follows template: [Epic N] {title} (Release #NNN)
   ✅ Has epic number: [Epic 1]
   ✅ Has Release reference: (Release #905)

3. LABELS VALIDATION
   ✅ Has required label: epic
   ✅ Has version label: vX.Y.Z
```

**Error Handling:**

If Epic validation FAILS:
- 🛑 **STOP** - Do NOT proceed to next epic
- 📋 Display detailed error report showing EXACTLY what failed
- ⏸️  Exit with non-zero status (process.exit(1))
- 📝 Show resolution steps

If Epic validation PASSES:
- ✅ Log success message
- ➡️  Proceed to child issue validation (Step 5.2)

---

**Step 5.2: VALIDATION - Verify Enhancement/Child Issue Template Format**

**PURPOSE:** Validate each Enhancement issue has correct template format after creation. Ensures no enrichment placeholders remain, title follows convention, and labels are correct.

**When it runs:** After each Epic's child issues are created in Step 5 (validates ALL child issues immediately after creation).

**What it validates per Enhancement/Child Issue:**

```
1. YAML FRONTMATTER VALIDATION
   ✅ Has opening delimiter: ---
   ✅ Has closing delimiter: ---
   ✅ NO enrichment placeholders (<!-- TODO: enrich -->)
   ✅ Body fully populated with implementation details

2. TITLE FORMAT VALIDATION
   ✅ Follows template: [N of M] {title} [Size/Complexity] (Epic #N)
   ✅ Has issue number: [1 of 5]
   ✅ Has Size/Complexity: [Small/Low], [Medium/High], etc.
   ✅ Has Epic reference: (Epic #280)

3. LABELS VALIDATION
   ✅ Has required label: enhancement
   ✅ Has version label: vX.Y.Z
```

**Error Handling:**

If Enhancement validation FAILS:
- 🛑 **STOP** - Do NOT proceed to next epic
- 📋 Display detailed error for EACH failed issue
- ⏸️  Exit with non-zero status (process.exit(1))
- 📝 Show resolution steps including placeholder removal guidance

If Enhancement validation PASSES:
- ✅ Log success message with count (e.g., "✅ All 12 Enhancement template formats are valid")
- ➡️  Continue to next epic

**Implementation Example:**

```typescript
// Step 5: Create GitHub issues
for (let i = 0; i < epicsToCreate; i++) {
  const epic = parsed.epics[i];
  
  // 1. Create epic and children
  const result = await createEpicWithChildren(epic, ...);
  
  // 2. Validate epic template (Step 5.1)
  const epicValidation = await validateEpicTemplateFormat(result.epicNumber, i + 1);
  if (!epicValidation.valid) {
    displayEpicValidationErrors(result.epicNumber, epicValidation.errors);
    process.exit(1);
  }
  
  // 3. Validate ALL child issues (Step 5.2)
  for (let childIdx = 0; childIdx < result.childIssues.length; childIdx++) {
    const childValidation = await validateEnhancementTemplateFormat(
      childIssue.number,
      childIdx + 1,
      result.childIssues.length,
      result.epicNumber
    );
    if (!childValidation.valid) {
      displayEnhancementValidationErrors(childIssue.number, childValidation.errors);
      process.exit(1);
    }
  }
}
```

**Related to Issue #303:** This validation is implemented as part of Epic #296 Phase 3, ensuring template compliance in `/scope-release` for epics and enhancements.

---

## Template Compliance Checklist

**IMPORTANT:** Refer to `docs/TEMPLATE-COMPLIANCE-CHECKLIST.md` for a comprehensive guide to all template requirements (Issue #304).

### Quick Reference

**Release Issue must have:**
- ✅ YAML frontmatter with `version: vX.Y.Z`
- ✅ Title format: `[Release] {name}` (NO version)
- ✅ Labels: `release`, `milestone`, `vX.Y.Z`

**Epic Issue must have:**
- ✅ YAML frontmatter with `epic_number`, `release_github_issue`
- ✅ Title format: `[Epic N] {title} (Release #NNN)`
- ✅ Labels: `epic`, `vX.Y.Z`

**Enhancement Issue must have:**
- ✅ YAML frontmatter with `issue_number`, `epic_number`
- ✅ Title format: `[N of M] {title} [Size/Complexity] (Epic #N)`
- ✅ NO `<!-- TODO: enrich -->` placeholders in body
- ✅ Body fully populated (no `{{VARIABLE}}` placeholders)
- ✅ Labels: `enhancement`, `vX.Y.Z`

### When Validation Fails

All validation failures show:
1. **Exactly what failed** - Specific format requirement
2. **How to fix it** - Step-by-step resolution
3. **Examples** - Correct vs incorrect formats

The command stops immediately (process.exit(1)) so you can fix issues manually and re-run.

**See full details:** `docs/TEMPLATE-COMPLIANCE-CHECKLIST.md` (Issue #304)

---

## 🎯 Epic #305 Enhancements: Improved Validation & Workflow (NEW)

**Overview:** Epic #305 adds comprehensive validation gates, epic-by-epic processing with user confirmations, and state tracking to prevent data loss during scope-release operations.

### 📋 New Features

#### 1. Epic-by-Epic Processing with Confirmations (Issue #341)

**What's new:** `/scope-release` now processes epics sequentially with user confirmation before creating each epic.

**Workflow:**
```
1. Display epic summary (title, issue count, estimated effort)
2. Ask for confirmation: "Create this epic and N child issues? (y/n)"
3. If YES: Create epic + all child issues
4. If NO: Skip this epic
5. Ask to continue: "Continue to next epic? (y/n)"
6. Repeat for all epics
```

**Benefits:**
- Users can review each epic before creation
- Ability to skip problematic epics
- Adjust scope incrementally
- Better control over large releases

#### 2. State Tracking & Resume (Issue #342)

**What's new:** State is persisted to `.scope-release.json` during execution, enabling resume after interruptions.

**State file includes:**
- Release metadata (version, name, start time)
- All created epics and their numbers
- All created child issues and their numbers
- Progress metrics (epics complete, issues complete)
- Resumability flag

**Benefits:**
- Survive network interruptions
- Network timeouts don't lose progress
- Resume with: `/scope-release --resume`
- See progress with: `/scope-release --status`

#### 3. Validation Checkpoints (8 Total)

**Checkpoint 1: Pre-Creation Validation (Issue #343)**
- Validates BEFORE creating any GitHub issues
- Checks epic titles, descriptions, size constraints
- Validates issue structure and classifications
- Detects placeholder variables ({{ }} and <!-- TODO)
- Reports all violations before GitHub creation

**Checkpoint 2: Post-Creation Validation (Issue #344)**
- Validates AFTER GitHub creation
- Fetches issues and checks title/body integrity
- Verifies no placeholders remain in GitHub
- Validates epic sections (Objectives, Criteria)
- Enables rollback if issues don't meet standards

**Checkpoint 3: Dependency Validation (Issue #345)**
- Parses dependency references from descriptions
- Builds dependency graph with DFS traversal
- Detects circular dependencies
- Validates all references exist
- Checks for typos in dependency format

**Checkpoint 4: Label Consistency (Issue #346)**
- Validates required labels by issue type
- Checks for approved label list
- Detects misspelled labels
- Auto-applies missing labels
- Suggests label corrections

**Checkpoint 5-8: Additional Validation**
- Issue #347: Unit tests for epic processing
- Issue #348: Unit tests for all validators
- Issue #349: Integration tests for workflow
- Issue #350: GitHub API error handling
- Issue #351: End-to-end tests with mock repo

### 🔄 Updated Workflow

```
BEFORE (old):
1. Parse release file
2. Create ALL epics + issues immediately
3. Hope for the best

AFTER (new):
1. Parse release file
2. Pre-creation validation (catches errors early)
3. CONFIRM epic #1
   → Create epic #1 + children
   → Post-creation validation
   → Dependency validation
   → Label consistency check
4. CONFIRM epic #2
   → Create epic #2 + children
   → All validations
5. Continue for remaining epics
6. Cleanup state file on success
```

### 📊 Validation Checkpoints Diagram

```
Parse Release
    ↓
Pre-Creation Validation ← NEW (Issue #343)
    ↓
FOR EACH EPIC:
    ├─ Display Summary
    ├─ Ask Confirmation ← NEW (Issue #341)
    ├─ Create Epic + Children
    ├─ Post-Creation Validation ← NEW (Issue #344)
    ├─ Dependency Validation ← NEW (Issue #345)
    ├─ Label Consistency ← NEW (Issue #346)
    └─ Record in State ← NEW (Issue #342)
    ↓
Track Progress
    ├─ Save State File ← NEW
    ├─ Show Progress Metrics ← NEW
    └─ Display Creation Summary
    ↓
Cleanup
    └─ Delete .scope-release.json on success
```

### 🚀 Usage Examples

**Standard workflow (with confirmations):**
```bash
/scope-release --current
# Will ask for confirmation for each epic
```

**Skip confirmations (trust the data):**
```bash
/scope-release --current --force
# Processes all epics without confirmation prompts
```

**Resume after interruption:**
```bash
/scope-release --resume
# Continues from where it left off
```

**Check progress:**
```bash
/scope-release --status
# Shows progress metrics from .scope-release.json
```

**Inspect mode (test first epic only):**
```bash
/scope-release --current --inspect
# Creates only first epic, then asks to continue
```

### ✅ Validation Report Example

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📋 Pre-Creation Validation Report
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Epics: 4
Issues: 12

✅ All items passed validation

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```

### 📚 Documentation Files

All new validators have TypeDoc documentation in:
- `scripts/utils/pre-creation-validator.ts` - Pre-creation checks
- `scripts/utils/post-creation-validator.ts` - Post-creation checks
- `scripts/utils/dependency-validator.ts` - Dependency analysis
- `scripts/utils/label-validator.ts` - Label consistency
- `scripts/utils/scope-release-state.ts` - State tracking

### 🧪 Testing

Comprehensive test suite in `scripts/__tests__/scope-release-validation.test.ts`:
- 35+ test cases
- 7 test suites (TC-001 through TC-007)
- Unit tests for each validator
- Integration tests for full workflow
- Mock GitHub API scenarios
- Error handling tests

Run tests with:
```bash
npm test -- scope-release-validation.test.ts
```

### 💡 Tips

**For large releases (10+ epics):**
- Use `--inspect` mode first to validate workflow
- Once confident, run full scope-release
- Check state file progress with `--status`

**For troubleshooting:**
- Check `.scope-release.json` for progress state
- View validation reports for each epic
- Use `--dry-run` to preview without creating

**For rollback:**
- Failed post-creation validation enables rollback
- Automatically closes invalid issues
- Preserves history for audit trail

---

**Related Epic:** Epic #305 - Improve /scope-release Workflow & Validation
**Status:** Implemented in epic-305 branch
**Tests:** 35+ unit and integration tests
**Documentation:** Complete with examples

---

## 🎯 Epic #356 Phase 2: Validation & Testing Infrastructure

**Overview:** Phase 2 (Issues #306-#317) adds comprehensive validation gates, epic confirmation checkpoints, and extensive test coverage to ensure template compliance and workflow reliability.

### 📋 Phase 2 Enhancements

#### 1. Epic Confirmation Checkpoint (Issue #307)

**What's new:** After each epic creation, user sees confirmation summary and can choose to continue or stop.

**Checkpoint Display:**
```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ EPIC 1 CREATED SUCCESSFULLY
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Epic: #280 - CI/CD Foundation & Automation
Child Issues: 3
  • #284 - Create Shared QA Utilities
  • #285 - Implement GitHub Actions Workflows
  • #286 - Create CI/CD Report Generator

Continue to Epic 2? (y/n): _
```

**Behavior:**
- User "y" or "yes" → Proceeds to next epic
- User "n" or "no" → Stops processing (can resume later)
- Prevents accidental creation of all epics without review

#### 2. Validation Gates (Issues #308-#311)

**4 New Validation Checkpoints:**

##### Gate 1: Release Issue Creation (Issue #308)
Validates immediately after Release issue is created:
- ✅ Release issue exists in GitHub
- ✅ GitHub issue number extracted successfully
- ✅ Release issue has correct labels (`release`, `v{X.Y.Z}`, `milestone`)
- ❌ STOP if validation fails (prevents epic creation)

##### Gate 2: Epic Issue Creation (Issue #309)
Validates immediately after each Epic issue is created:
- ✅ Epic issue exists in GitHub
- ✅ GitHub epic number extracted
- ✅ Epic has required labels (`epic`, `release`, `v{X.Y.Z}`)
- ✅ Epic linked to Release issue
- ❌ STOP if validation fails (prevents child issue creation)

##### Gate 3: Child Issue Creation (Issue #310)
Validates immediately after each child issue is created:
- ✅ Child issue exists in GitHub
- ✅ GitHub issue number extracted
- ✅ Title format correct: `[{N} of {total}] {title}`
- ✅ Has required labels (`enhancement`, `epic`, `release`, `v{X.Y.Z}`)
- ✅ No enrichment placeholders (`<!-- TODO: enrich -->`)
- ❌ STOP if validation fails (prevents proceeding)

##### Gate 4: No Interim Documentation (Issue #311)
Validates at completion before marking success:
- ✅ No files in `memory-bank/requirements/source-docs/{release}/issue-*.md`
- ✅ No files in `memory-bank/requirements/specs/*issue*.md`
- ✅ No files in `context/prds/*issue*.md`
- ✅ Git status shows no new `.md` files
- ❌ STOP if any interim files found (report exact files)

**Validation Report Example:**
```
Step 3.5: Validating Release issue creation...

✅ Release issue #279 created and verified
✅ Label 'release' present
✅ Label 'v1.6.6' present
✅ Label 'milestone' present
✅ Release issue creation gate PASSED
```

#### 3. Epic-by-Epic Processing Loop (Issue #306)

**Implementation:**
```typescript
let epicIndex = 0;
while (epicIndex < epics.length) {
  const epic = epics[epicIndex];
  
  // Display epic summary
  console.log(`📋 Epic ${epicIndex + 1}/${epics.length}: ${epic.title}`);
  console.log(`   Issues: ${epic.issues.length}`);
  console.log(`   Estimated: X hours\n`);
  
  // Ask for confirmation
  const confirmed = await promptConfirm(
    `Create this epic and ${epic.issues.length} child issues?`
  );
  
  if (confirmed) {
    // Create epic + children with validation gates
    const result = await createEpicWithChildren(...);
    
    // Validate all gates passed
    // Continue to next epic
  } else {
    // Skip this epic
    continue;
  }
  
  epicIndex++;
}
```

**Processing Order:**
1. Display next epic summary
2. Wait for user confirmation
3. If YES: Create epic + all children + validate
4. If YES + not last epic: Ask to continue to next
5. If NO: Skip or exit
6. Repeat until all epics processed

### ✅ Test Coverage (Issues #312-#316)

#### Test Suite 1: Release Issue Format (Issue #312)
- ✅ YAML frontmatter validation
- ✅ Title format: `[Release] {name}` (no version)
- ✅ Labels: `release`, `v{X.Y.Z}`, `milestone`
- ✅ Epic checklist in body
- ✅ GitHub issue number extraction

#### Test Suite 2: Epic Issue Format (Issue #313)
- ✅ YAML frontmatter with `type: epic`
- ✅ Title format: `[Epic N] {title} (Release #NNN)`
- ✅ Labels: `epic`, `release`, `v{X.Y.Z}`
- ✅ Child issues list present
- ✅ Release link in body

#### Test Suite 3: Enhancement Issue Format (Issue #314)
- ✅ YAML frontmatter with `type: enhancement`
- ✅ Title format: `[{N} of {total}] {title} [{size}/{complexity}] (Epic #{N})`
- ✅ Labels: `enhancement`, `epic`, `release`, `v{X.Y.Z}`
- ✅ No enrichment placeholders
- ✅ Acceptance criteria fully populated
- ✅ Epic reference in body

#### Test Suite 4: Epic-by-Epic Workflow (Issue #315)
- ✅ All epics processed when user confirms all
- ✅ Processing stops at correct point when user says "no"
- ✅ Epic summary displays before confirmation
- ✅ State preserved for resume
- ✅ Confirmation prompt appears for each epic
- ✅ Child issues created for selected epics

#### Test Suite 5: Validation Gates E2E (Issue #316)
- ✅ Release gate catches missing Release issue
- ✅ Epic gate catches missing Epic issue
- ✅ Epic gate catches missing labels
- ✅ Child gate catches enrichment placeholders
- ✅ Interim doc gate detects .md files
- ✅ All gates pass when workflow complete
- ✅ Any failed gate stops entire process

### 📊 Validation Flow Diagram

```
Start /scope-release
    ↓
Parse Release File
    ↓
Create Release Issue
    ↓
[GATE 1] Validate Release Issue ✅ OR ❌
    ↓ (if ✅)
For Each Epic:
    ├─ Display epic summary
    ├─ Ask for confirmation
    ├─ If YES:
    │  ├─ Create Epic Issue
    │  ├─ [GATE 2] Validate Epic Issue ✅ OR ❌
    │  ├─ For each Child Issue:
    │  │  ├─ Create Child Issue
    │  │  └─ [GATE 3] Validate Child Issue ✅ OR ❌
    │  └─ Ask to continue to next epic
    └─ If NO: Skip this epic
    ↓
[GATE 4] Verify No Interim Docs ✅ OR ❌
    ↓ (if ✅)
✅ SCOPE-RELEASE COMPLETE
```

### 🧪 Running Tests

**Run all validation tests:**
```bash
npm test -- scope-release-validation.test.ts
npm test -- scope-release-format-tests.test.ts
```

**Run specific test suite:**
```bash
npm test -- scope-release-format-tests.test.ts --testNamePattern="Release issue format"
npm test -- scope-release-format-tests.test.ts --testNamePattern="epic-by-epic"
```

### 🔄 Resume Workflow

If `/scope-release` is interrupted:

```bash
# Check current status
node dist/scripts/scope-release.js --status

# Resume from where it stopped
node dist/scripts/scope-release.js --resume
```

State is stored in `.scope-release.json`:
```json
{
  "release": "v1.6.6",
  "releaseIssueNumber": 279,
  "epicIndex": 2,
  "processedEpics": [
    {"epicNumber": 280, "childIssues": [284, 285, 286]},
    {"epicNumber": 281, "childIssues": [287]}
  ],
  "totalEpics": 4,
  "isPaused": true
}
```
