---
roadcrew_template_name: "implement-issue.md"
roadcrew_template_type: "command"
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"
execution_mode: "auto-execute"
---

# implement-issue

<!-- Usage: /implement-issue {{ISSUE_NUMBER}} [--repo <repo-url>] -->

Implement a single GitHub issue, including requirements extraction, implementation, and testing.

> **Execution:** Runs immediately with automatic code generation. No approval pauses.

**Prerequisites:** Issue must have a clear description. Reference `/analyze-issue` first if needed for context.

## Usage

```
/implement-issue <issue_number>
```

**Examples:**
- `/implement-issue 226`
- `/implement-issue 42`

## What This Command Does

1. Fetches issue details from GitHub
2. Analyzes scope and creates TODO list
3. Implements using strict TDD (test first, minimal code)
4. Pushes changes and creates PR

## Process

### 1. Fetch Issue Details

Use GitHub CLI to get context:
```bash
gh issue view {{ISSUE_NUMBER}} --json title,body,labels,assignees,milestone
```

Extract:
- Issue title and description
- Acceptance criteria
- Labels and priority
- Related epic or parent issue

### 2. Analyze Scope & Detect Test Framework

Use the centralized analysis and test framework detection utilities:

```typescript
import { 
  analyzeIssueScope, 
  getIssueDependencies 
} from '../scripts/utils/issue-analysis.js';
import { detectTestFramework } from '../scripts/utils/roadcrew/testing-harness.js';

const analysis = await analyzeIssueScope({{ISSUE_NUMBER}});
const dependencies = await getIssueDependencies({{ISSUE_NUMBER}});

// Detect test framework for this project
const packageJsonContent = fs.readFileSync('package.json', 'utf-8');
const framework = detectTestFramework(packageJsonContent);
console.log(`🧪 Test Framework Detected: ${framework}`);
```

**If scope is NOT appropriate (analysis.needsSubIssues = true):**

```
❌ Scope too large for single PR: #{{ISSUE_NUMBER}}

Estimated Effort: {{ANALYSIS.estimatedHours}} hours
Recommendation: Break into multiple issues

Identified Risks:
- {{ANALYSIS.risks.join('\n- ')}}

Suggested Sub-Issues:
- {{ANALYSIS.subtaskSuggestions.join('\n- ')}}

Please break this issue into smaller sub-issues first.
Update the GitHub issue and re-run /implement-issue {{ISSUE_NUMBER}}
```

**Exit implementation and wait for user to create sub-issues.**

**If scope is appropriate (analysis.isAppropriate = true):**

```
✅ Issue #{{ISSUE_NUMBER}} Analysis Complete

Estimated Effort: {{ANALYSIS.estimatedHours}} hours
Acceptance Criteria: {{ANALYSIS.acceptanceCriteria.length}} items
Risks Identified: {{ANALYSIS.risks.length}} risks

📋 Proceeding to TODO list creation...
```

**If issue has blockers (dependencies.dependsOn.length > 0):**

```
⚠️  Issue #{{ISSUE_NUMBER}} has dependencies:
- {{DEPENDENCIES.dependsOn.map(n => `#${n}`).join(', ')}}

Ensure dependencies are completed before merging.
```

**Continue with TODO list creation using analysis.acceptanceCriteria**

### 3. Create TODO List

Generate comprehensive, sequential TODO list:
- Break down into small, testable steps
- Order by dependencies (tests before implementation)
- Include specific files/functions to modify
- Estimate effort for each step

**Get approval before implementation.**

### 3.5. Validate RED State (After Writing Tests)

**Before you start implementation, validate tests using the testing harness:**

```typescript
import { generateTestCases, isTestingRequired } from '../scripts/utils/roadcrew/testing-harness.js';

// Generate test cases from acceptance criteria
const testCases = generateTestCases(acceptanceCriteria, issueTitle);

if (isTestingRequired(framework)) {
  // Create test file based on framework
  const testContent = createTestFileContent(framework, testCases, moduleName);
  fs.writeFileSync(testFile, testContent);
  
  // Validate RED state
  node scripts/core/validate-red-state.ts {{TEST_FILE_PATH}}
}
```

This validates:
- ✅ Test file exists and is readable
- ✅ Active (non-skipped) test cases found
- ✅ Tests have `expect()` assertions
- ✅ No placeholder TODO comments in tests

**If validation FAILS:**
```
❌ RED state validation failed:
- {{ERRORS.join('\n- ')}}

Fix your tests and retry before proceeding to implementation.
TDD requires tests to be written FIRST and failing.
```

**If validation PASSES:**
```
🔴 RED State Validated
- {{RESULT.testState.activeTests}} active test cases
- {{RESULT.testState.passing}} passing, {{RESULT.testState.failing}} failing

Ready to implement! Only write enough code to make tests pass.
```

### 4. Implement Using TDD

**MANDATORY TDD SEQUENCE:**

For each feature/function:
1. Write failing test first
2. Run test to confirm it fails
3. Write ONLY enough code to make that test pass
4. Run test to confirm it passes
5. Refactor if needed (while keeping tests green)
6. Repeat for next feature

**Strict Scope:**
- Only work on {{ISSUE_NUMBER}} requirements
- Note unrelated issues but don't fix them
- No scope creep beyond acceptance criteria

**Cursorrules Compliance:**
- Reference @.cursorrules.md throughout
- Follow all code quality standards
- Maintain architecture patterns
- Document with JSDoc comments

### 4.5. Validate GREEN State (After Implementation Complete)

**After implementation is complete, validate that tests pass:**

```bash
node scripts/core/validate-green-state.ts {{TEST_FILE_PATH}} {{IMPL_FILE_PATH}}
```

This validates:
- ✅ Test file has adequate `expect()` assertions
- ✅ Implementation file exists and is substantial (>100 chars)
- ✅ Test coverage is ≥ 50%
- ✅ No placeholder/stub implementations

**If validation FAILS:**
```
❌ GREEN state validation failed:
- {{ERRORS.join('\n- ')}}

Fix your implementation and retry until tests pass.
Minimum 50% of tests must have passing assertions.
```

**If validation PASSES:**
```
🟢 GREEN State Validated
- {{RESULT.testState.passing}} tests passing
- {{RESULT.testState.coverage}}% coverage

TDD workflow complete! Ready for PR creation.
```

### 4.6. Validate PR Before Pushing (MANDATORY - NEW)

**Before creating the PR, validate the PR title and body using PRValidationWrapper:**

```bash
# Run PR validation with detailed reporting
node scripts/core/validate-pr-command.ts \
  --title "feat(issue-{{ISSUE_NUMBER}}): {{ISSUE_TITLE}}" \
  --body "## Summary{{PR_BODY_CONTENT}}" \
  --command "implement-issue" \
  --auto-fix
```

**This validates:**
- ✅ PR title is properly formatted and ≤72 characters
- ✅ PR body has required sections (Summary, Acceptance Criteria, Testing Evidence)
- ✅ No placeholder text in PR description
- ✅ All checkboxes properly formatted
- ✅ Minimum description length met

**Validation output:**
```
✅ PR format validation passed
- Title: 68 characters (✓)
- Body sections: Complete (✓)
- Checkboxes: Properly formatted (✓)
- Description: Adequate detail (✓)

Proceeding with PR creation...
```

**If validation FAILS with errors:**
```
❌ PR validation failed:
- Title exceeds 72 characters: "your long title here"
- Missing "Acceptance Criteria" section
- Incomplete checkboxes found

Options:
  1. Fix issues manually and run validation again
  2. Use --auto-fix flag to automatically correct common issues
  3. Check /validate-pr command for detailed PR validation rules

Retry: node scripts/core/validate-pr-command.ts [options] --auto-fix
```

**If validation PASSES (or passes with non-blocking warnings):**
```
✅ PR validation complete. Proceeding with PR creation...
```

### 4. Push to GitHub and Create PR

#### 4a. Create PR with Proper Base Branch

```typescript
import { validatePRBeforePush } from '../scripts/utils/pr-validation-wrapper';

// Build PR title and body based on issue
const prTitle = `feat(issue-{{ISSUE_NUMBER}}): ${issueTitle}`;
const prBody = `
## Change Summary

{{ISSUE_DESCRIPTION}}

## Acceptance Criteria Met

{{ACCEPTANCE_CRITERIA_CHECKLIST}}

## Testing Evidence

{{TEST_RESULTS_SUMMARY}}

## Reviewer Focus

{{KEY_AREAS_FOR_REVIEW}}

---

**Auto-generated by /implement-issue #{{ISSUE_NUMBER}}**
`;

// ✨ Validate PR before pushing
console.log('🔍 Validating PR format...');
const validation = await validatePRBeforePush(prTitle, prBody, 'implement-issue');

if (!validation.valid) {
  console.log('⚠️  Validation warnings:');
  validation.errors.forEach(err => console.log(`  ${err}`));
  console.log('💡 Continuing with PR creation (warnings are informational)...');
}

// Push to GitHub
git push origin issue-{{ISSUE_NUMBER}}

// Create PR using GitHub CLI
gh pr create \
  --base main \
  --head issue-{{ISSUE_NUMBER}} \
  --title "$PR_TITLE" \
  --body "$PR_BODY" \
  --label "implementation,issue-{{ISSUE_NUMBER}}"
```

#### 4b. Verify PR Creation Success

**Display PR URL and results:**
```
✅ PR #{{PR_NUMBER}} created successfully!

Details:
- Branch: issue-{{ISSUE_NUMBER}} → main
- Title: feat(issue-{{ISSUE_NUMBER}}): {{ISSUE_TITLE}}
- Validation: ✅ Passed
- Tests: {{TEST_RESULTS}} passing
- Coverage: {{COVERAGE}}%

View PR: https://github.com/tailwind-ai/roadcrew-internal/pull/{{PR_NUMBER}}

Next steps:
1. Await CI checks
2. Address review comments if any
3. Merge when approved
```

### 5. Verify Completion

Before creating PR:
- [ ] All acceptance criteria met
- [ ] All tests passing (CI green)
- [ ] No linter errors
- [ ] Code follows @.cursorrules.md standards
- [ ] PR validation passed (✅ from section 4.6)

### 6. Summary: PR Validation Integration

**PR Validation is now MANDATORY in this workflow:**

✅ **Step 4.6 validates:**
- PR title format and length (≤72 chars)
- PR body structure and completeness
- Checkbox formatting
- Description quality

✅ **Step 4a creates PR after validation passes**

✅ **Step 4b displays PR URL and next steps**

This ensures every PR created via `/implement-issue` meets quality standards before GitHub submission.

## Error Handling

- If {{ISSUE_NUMBER}} is missing, ask once before proceeding
- If issue doesn't exist, show error and exit
- If scope too large, recommend breaking into sub-issues
- If tests fail, stop and fix before continuing
- **If PR validation fails**: Review errors, fix PR title/body, then retry validation (section 4.6)
- If PR creation fails, show error but keep local changes

## Notes

- Always work on dev branch (never main)
- Always write tests before implementation
- Always get TODO approval before coding
- **PR Validation is mandatory** before PR creation (section 4.6)
- Use `--auto-fix` flag in validation if auto-correction is needed
- Can run `/review-code {{ISSUE_NUMBER}}` before creating PR
- After PR created, use `/triage-pr <PR_NUMBER>` if CI fails

## Auto-Closure Behavior

**`/implement-issue` creates PR:** `dev` → `main`
- ✅ Issues **auto-close immediately** when PR merges to main
- ✅ Uses `Closes #{{ISSUE_NUMBER}}` keyword correctly
- ✅ No additional steps needed

**vs. `/implement-epic`:**
- Creates PR: `epic-X` → `dev` (auto-merges after CI passes)
- Automatically creates follow-up PR: `dev` → `main` (requires human approval to merge)
- Issues auto-close when release PR merges to main

## When to Use `/implement-issue` vs `/implement-epic`

**Use `/implement-issue` for:**
- ✅ Standalone issues (no dependencies)
- ✅ Hotfixes (need immediate merge to main)
- ✅ Simple features (1-2 files, < 4 hours)
- ✅ Issues that can merge independently

**Use `/implement-epic` for:**
- ✅ Multiple related issues (epic scope)
- ✅ Complex features (>7 hours, multiple files)
- ✅ Issues with dependencies (need specific order)
- ✅ Features that should be reviewed/merged as a unit

