# 🚀 GitHub PR Creator – Technical Specification {#spec-ROADCREW-002}

> This document defines **how** to implement GitHub PR creation with proper API integration and template-driven content.

## 1. Mapping: Requirements → Spec

| Requirement | Satisfied In Spec Section |
|---|---|
| R1: API-first PR creation | 4.1.1, 4.3 |
| R2: Conventional commits formatting | 4.1.2, 4.3 |
| R3: Template-driven body generation | 4.1.3, 4.2 |
| R4: PR splitting integration | 4.1.4, 8.3 |
| R5: Retry + rate limiting | 4.1.1, 8.4 |
| R6: Batch operations | 4.1.1, 4.3 |

## 2. Technical Requirements

### 2.1 Functional Requirements
- Create pull requests using GitHub API (Octokit) with proper authentication
- Format PR titles using conventional commits: `feat(scope):`, `fix(scope):`, `refactor(scope):`
- Generate PR bodies from templates following pr-guidelines.md structure
- Support feature, bugfix, and refactor PR types with appropriate templates
- Integrate with pr-splitter.ts to create multi-PR workflows from SplitProposal
- Handle retries with exponential backoff for transient failures
- Batch process multiple PRs with rate limiting

### 2.2 Non-Functional Requirements
- **Performance:** PR creation completes in <2 seconds per PR; batch operations respect GitHub rate limits
- **Reliability:** Retry logic with exponential backoff for network/rate-limit errors
- **Scalability:** Support creating 10+ PRs per workflow; 1000+ PRs lifetime
- **API Usage:** GitHub API only (no CLI fallback for primary operations)

### 2.3 Out of Scope
- Automatic PR merging or approval workflows
- Advanced code review assignment logic beyond labels
- PR update/modification after creation
- Webhook handling or listener patterns

## 3. Design Overview (≤100 words)

Create `github-pr-creator.ts` following github-issue-closer.ts and github-creator.ts patterns. Use Octokit for all API calls. Implement title formatter using conventional commits conventions. Generate PR bodies from structured templates (feature/bugfix/refactor) derived from pr-guidelines.md. Support batch operations with retry logic and rate limiting. Optionally integrate with pr-splitter.ts for multi-PR workflows. Maintain full backward compatibility with existing commands.

## 4. Architecture & Implementation

### 4.1 New/Modified Services

#### 4.1.1 GitHub PR Creator
- **Module:** `scripts/utils/roadcrew/github-pr-creator.ts` – Core PR creation with API + retry logic
- **Purpose:** Unified PR creation following established patterns (github-issue-closer, github-creator)

#### 4.1.2 Conventional Commits Formatter
- **Module:** `scripts/utils/roadcrew/pr-title-formatter.ts` – Format PR titles
- **Purpose:** Generate proper titles: `feat(scope): description`, etc.

#### 4.1.3 PR Template Generator
- **Module:** `scripts/utils/roadcrew/pr-template-generator.ts` – Populate PR body
- **Purpose:** Generate feature/bugfix/refactor PR bodies from pr-guidelines.md

#### 4.1.4 PR Splitter Integration (Optional)
- **Module:** Integration in github-pr-creator.ts with pr-splitter.ts output
- **Purpose:** Create multiple coordinated PRs from SplitProposal

### 4.2 Data Model Changes

```typescript
interface CreatePROptions {
  title: string;              // PR title (will be formatted)
  body: string;               // PR body (markdown)
  head: string;               // Feature branch
  base: string;               // Target branch (main/dev)
  type: 'feature' | 'bugfix' | 'refactor';  // PR type for template
  draft?: boolean;            // Create as draft PR?
  reviewers?: string[];       // GitHub usernames
  labels?: string[];          // GitHub labels
}

interface CreatePRResult {
  number: number;             // PR number
  url: string;                // PR URL
  title: string;              // Actual title created
  sha: string;                // Commit SHA
}

interface CreateSplitPRsOptions {
  splitProposal: SplitProposal;
  branchPrefix: string;       // e.g., "feature/split-"
  reviewers?: string[];
  labels?: string[];
}
```

### 4.3 API Design

| Function | Signature | Purpose |
|---|---|---|
| formatPRTitle | (title: string, scope: string, type: PRType) => string | Format as conventional commit |
| generatePRBody | (type: PRType, content: Record<string, string>) => string | Populate template |
| createPullRequest | (opts: CreatePROptions, octokit: Octokit) => Promise<CreatePRResult> | Create single PR with retry |
| createPullRequestWithRetry | (opts: CreatePROptions, octokit: Octokit, retries?: number) => Promise<CreatePRResult> | Retry wrapper |
| createSplitPRs | (opts: CreateSplitPRsOptions, octokit: Octokit) => Promise<CreatePRResult[]> | Create multiple PRs |

## 5. Execution Plan

### Phase 1: Core PR Creator Module
Implement `github-pr-creator.ts` with single PR creation, retry logic (exponential backoff), rate limiting, error classification. Unit tests for all error cases. Follows github-issue-closer.ts pattern.

### Phase 2: Title & Body Generation
Create `pr-title-formatter.ts` (conventional commits) and `pr-template-generator.ts` (populate from pr-guidelines templates). Support feature/bugfix/refactor types. Unit tests for all template variations.

### Phase 3: Batch Operations
Add batch PR creation to github-pr-creator.ts with proper rate limiting. Add integration with pr-splitter.ts for multi-PR workflows. Integration tests with real PR proposals.

### Phase 4: Integration & Documentation
Integrate into commands (scope-release, create-epic, etc.). Update pr-guidelines.md with automation examples. Provide migration guide for existing workflows.

## 6. Testing & Validation

### 6.1 Acceptance Criteria
- Single PR creation succeeds with Octokit API calls (no CLI)
- Title formatted as conventional commit: `feat(scope): description`
- PR body populated from correct template with no placeholders
- Retry logic handles transient failures (timeouts, rate limits)
- Batch operations respect GitHub rate limits (maintain <1s/PR average)
- Integration with pr-splitter produces coordinated multi-PR workflows
- All existing PR workflows continue working unchanged

### 6.2 Test Plan
- [ ] Unit tests: Title formatting for all PR types and scopes
- [ ] Unit tests: Template body generation and variable substitution
- [ ] Unit tests: Retry logic with mocked API failures
- [ ] Unit tests: Error classification (rate limit, network, permission)
- [ ] Integration tests: Create real PR (use test repo branch)
- [ ] Integration tests: Batch operations with rate limiting
- [ ] Integration tests: pr-splitter workflow end-to-end

## 7. Dependencies & Links

- **Depends On:** github-creator.ts, github-issue-closer.ts, pr-splitter.ts, pr-guidelines.md
- **Used By:** scope-release, create-epic, autopilot (future integration)
- **Related:** Release automation, PR validation

## 8. Issue Breakdown

### Issue ROADCREW-002.1: Implement Core PR Creator Module {#issue-ROADCREW-002-1}

**Overview:** Create github-pr-creator.ts with single PR creation, retry logic, and error handling following established patterns.

**Accepts:**
- createPullRequest() creates PR via Octokit with proper error handling
- createPullRequestWithRetry() retries with exponential backoff (1s, 2s, 4s)
- Error classification: network errors (retry), rate limit (wait), permission (fail)
- Result includes PR number, URL, title, and commit SHA

**Tech Approach:**
- Model github-issue-closer.ts pattern: Octokit + retry logic + error classification
- Implement error handlers for 404 (not found), 403 (permission), 429 (rate limit), timeouts
- Exponential backoff: 1s → 2s → 4s between retries
- Return CreatePRResult with all metadata

**Files/Components:** github-pr-creator.ts, github-pr-creator.test.ts

**Classification:** 4 (ai-led: Integration pattern, clear error handling)

**Size/Complexity:** M/Medium

---

### Issue ROADCREW-002.2: Implement PR Title & Body Formatting {#issue-ROADCREW-002-2}

**Overview:** Create pr-title-formatter.ts and pr-template-generator.ts to format titles and generate bodies following pr-guidelines.md.

**Accepts:**
- formatPRTitle() produces: `feat(scope): description`, `fix(scope): description`, etc.
- generatePRBody() populates feature/bugfix/refactor templates with no placeholders
- Templates match pr-guidelines.md structure (Change Summary, Testing Evidence, etc.)
- All template variables properly substituted or marked N/A

**Tech Approach:**
- Extract template sections from pr-guidelines.md (lines 84-225)
- Implement formatPRTitle() using conventional commits spec
- Map PR type → template structure (feature, bugfix, refactor)
- Substitution: replace {{VARIABLE}} with provided values

**Files/Components:** pr-title-formatter.ts, pr-template-generator.ts, *.test.ts

**Classification:** 3 (ai-solo: Template mapping, deterministic)

**Size/Complexity:** M/Low

---

### Issue ROADCREW-002.3: Add Batch Operations & PR Splitter Integration {#issue-ROADCREW-002-3}

**Overview:** Implement batch PR creation with rate limiting and integrate with pr-splitter.ts for coordinated multi-PR workflows.

**Accepts:**
- createPRs() processes batch with configurable rate limiting
- Respects GitHub rate limits: maintain <1s/PR average or explicit delay
- Integration with pr-splitter.ts: createSplitPRs(proposal) creates coordinated PRs
- Each chunk PR includes dependency tracking and risk level annotation

**Tech Approach:**
- Add batch processing loop with configurable batchSize and batchDelayMs
- Monitor rate limit headers; adapt delay dynamically
- Parse SplitProposal.chunks; create PR per chunk with dependency comments
- Chunk PRs include risk annotation (🔴🟡🟢) in body

**Files/Components:** github-pr-creator.ts extensions, integration tests

**Classification:** 5 (ai-led: Coordination logic, rate limiting)

**Size/Complexity:** L/Medium

---

### Issue ROADCREW-002.4: Integration & Documentation {#issue-ROADCREW-002-4}

**Overview:** Integrate PR creator into commands and document automation patterns.

**Accepts:**
- scope-release optionally creates PRs for epic/issue groups
- create-epic can auto-create PR with child issue links
- pr-guidelines.md updated with automation examples
- Migration guide for existing manual PR workflows

**Tech Approach:**
- Add createPR flag to scope-release and create-epic commands
- Update pr-guidelines.md with automation section
- Create tutorial: "Automated Release PRs with scope-release"
- Integration tests verify all workflows

**Files/Components:** scope-release.ts, create-epic.ts, pr-guidelines.md, integration tests

**Classification:** 5 (ai-led: Cross-command coordination)

**Size/Complexity:** L/Medium

---

## Editor Instructions:
- API-first: Octokit only, no gh CLI for primary ops
- Pattern: Follow github-issue-closer.ts design (auth, retry, batch)
- Templates: Derive from pr-guidelines.md documented structure
- Integration: Optional for pr-splitter, required for core functionality
- Backward compatibility: All existing workflows continue unchanged
