# IMPLEMENT Pattern Analysis: Scripts & Token Optimization

**Status:** 📊 Detailed Analysis Complete  
**Focus:** 4 core IMPLEMENT commands, token reduction opportunities, and script reuse  
**Tier Coverage:** STARTER (4)  
**Total Tokens:** ~17K

---

## Executive Summary

### Decision Points

This document presents opportunities to extract shared utilities from IMPLEMENT pattern commands to reduce token usage and increase script reuse. Key decisions to address:

1. **Phase 1:** Extract `epic-orchestrator.ts` (shared epic analysis/planning logic)
2. **Phase 2:** Extract `implementation-coordinator.ts` (shared issue/code generation logic)  
3. **Phase 3:** Extract `testing-harness.ts` (shared test framework setup/validation)
4. **Support Decisions:** Script organization, testing strategy, measurement/validation, rollout approach

### Key Findings

- **IMPLEMENT is purely orchestration:** All 4 commands are orchestrators (autopilot, implement-epic, analyze-epic, implement-issue)
- **Heavy duplication:** analyze-epic + implement-epic + autopilot all share issue parsing, dependency ordering, and complexity assessment
- **Potential savings:** 1.95-2.75K tokens (12-16% of IMPLEMENT pattern)
- **Granular builders missing:** No `/scaffold-project`, `/generate-module`, or similar command-level builders
- **Note:** update-my-documents removed (not an IMPLEMENT command - belongs elsewhere)

---

## Current IMPLEMENT Commands

### 1. autopilot (7,171 tokens) - STARTER

**Command Text Summary:**
Combined analysis + implementation workflow for a GitHub epic in a single conversation. Orchestrates 200+ lines of:
- Template validation (validate-github-templates.ts)
- Epic fetching and open questions checking
- Child issue analysis and dependency ordering (analyze-epic-toc.ts)
- Risk assessment and classification
- Continuous implementation mode (no approval pauses between issues)
- PR creation with pending-closure labels
- Auto-merge to dev, release PR creation
- Manual test coordination

**Capabilities:**
- Validates epic template structure
- Checks for unanswered critical questions
- Orders issues by dependencies (topological sort)
- Analyzes classification (1-10 scale)
- Tracks implementation metrics (tokens, duration, files, lines)
- Creates epic branch, implements all issues, creates PR, auto-merges
- 40% faster than separate analyze-epic + implement-epic workflow

**Key Files & I/O:**
- Reads: .cursorrules.md, ai-context.yml, memory-bank/techContext.md, GitHub issues
- Calls: validate-github-templates.ts, analyze-epic-toc.js
- API: GitHub (fetch epic, child issues, create PR, add labels)
- Output: Epic branch created, PR to dev, metrics logged

**Scripts Called:**
1. validate-github-templates.ts - Template validation
2. analyze-epic-toc.js - Dependency ordering with TOC
3. GitHub API (built-in orchestration, not a separate script)

---

### 2. implement-epic (4,922 tokens) - STARTER

**Command Text Summary:**
Implements a GitHub epic after analysis. Orchestrates 200+ lines of:
- Pre-flight checks (GitHub auth, project tools, tech-stack detection)
- Epic branch creation from base branch
- Scope confirmation and auto-proceeding
- Dependency parsing and issue ordering
- Issue implementation in sequence (no approval between issues)
- Continuous implementation mode with metrics tracking
- PR creation, CI waiting, auto-merge, release PR creation
- Expects `/analyze-epic` to run first

**Capabilities:**
- Pre-flight validation (auth, tools, project type)
- Creates epic branch from dev/main
- Displays implementation sequence (dependency-ordered)
- Implements each issue with test-first approach
- Tracks implementation metrics per issue
- Auto-merge to dev after CI passes
- Creates release PR (dev → main) for manual approval
- 30% faster than per-issue implementation workflow

**Key Files & I/O:**
- Reads: .cursorrules.md, ai-context.yml, memory-bank/techContext.md, GitHub issues
- Calls: (via GitHub API - issue fetching, dependency ordering)
- API: GitHub (fetch issues, create/merge PRs, add labels, comments)
- Output: Epic branch with all issues implemented, PR created, metrics logged

**Scripts Called:**
1. GitHub CLI - Issue fetching, PR operations (no dedicated script - inline)
2. issue-classification.ts - Dependency ordering (referenced but not called directly)

---

### 3. analyze-epic (4,120 tokens) - STARTER

**Command Text Summary:**
Analyzes a GitHub epic and its child issues. Orchestrates 150+ lines of:
- Epic fetching and detailed reading
- Child issue analysis (description, acceptance criteria, dependencies)
- Classification assessment (1-10 scale)
- Dependency sequencing with Theory of Constraints (TOC)
- Risk assessment (breaking changes, unknown complexity)
- Output structured analysis for review before implementation
- Suggests scope split if >7 issues

**Capabilities:**
- Fetches epic and all child issues via GitHub API
- Parses issue descriptions and dependencies
- Applies classification scale (1-10, color-coded zones)
- Uses TOC Critical Chain method for sequencing
- Identifies risks and breaking changes
- Suggests parallel vs sequential work
- Detects bottlenecks and resource allocation needs
- Formatted output for manual review before implementing

**Key Files & I/O:**
- Reads: GitHub issues and epic
- Calls: analyze-epic-toc.js, issue-classification.ts (for parsing)
- API: GitHub (fetch epic, child issues)
- Output: Structured analysis report, dependency graph, risk assessment

**Scripts Called:**
1. analyze-epic-toc.js - TOC Critical Chain analysis
2. issue-classification.ts - Classification parsing and zone assignment

---

### 4. implement-issue (1,103 tokens) - STARTER

**Command Text Summary:**
Implements a single issue end-to-end. Orchestrates 80+ lines of:
- Issue fetching and parsing
- Acceptance criteria reading
- Test-first approach (creates tests, then code)
- Checkpoint commit
- No PR creation (for use within an epic, or standalone with --create-pr flag)
- Minimal metrics tracking

**Capabilities:**
- Fetches and analyzes single GitHub issue
- Reads acceptance criteria and specifications
- Creates tests for the issue
- Implements code to pass tests
- Creates checkpoint commit
- Optional: Creates PR for standalone use
- Minimal orchestration (no dependency management)

**Key Files & I/O:**
- Reads: GitHub issue, acceptance criteria
- API: GitHub (fetch issue, optionally create PR)
- Output: Implementation commit, optional PR

**Scripts Called:**
None (direct implementation, no dependencies)

---

## Key Duplication Opportunities

### Opportunity 1: epic-orchestrator.ts (1.5-2K tokens)

**What's Duplicated Across Commands:**

| Logic | autopilot | implement-epic | analyze-epic | Estimated Tokens |
|-------|-----------|----------------|--------------|------------------|
| Epic fetching | ✅ | ✅ | ✅ | 200-300 |
| Child issue parsing | ✅ | ✅ | ✅ | 300-400 |
| Dependency analysis | ✅ | ✅ | ✅ | 400-500 |
| Classification assessment | ✅ | ✅ | ✅ | 300-400 |
| TOC sequencing | ✅ | ✅ | ✅ | 300-400 |

**Proposed Interface:**
```typescript
interface EpicOrchestrator {
  // Epic fetching and validation
  fetchEpic(epicNumber: string): Promise<Epic>
  validateEpicTemplate(epic: Epic): TemplateValidationResult
  checkCriticalQuestions(epic: Epic): OpenQuestionsAnalysis
  
  // Child issue analysis
  fetchChildIssues(epicNumber: string): Promise<Issue[]>
  parseIssueDependencies(issues: Issue[]): DependencyMap
  detectCircularDependencies(deps: DependencyMap): Circular[]
  
  // Classification and ordering
  assessClassification(issue: Issue): ClassificationScore
  orderByDependencies(issues: Issue[], deps: DependencyMap): OrderedIssues
  analyzeWithTOC(issues: Issue[]): TOCAnalysis
  
  // Risk assessment
  assessRisk(issue: Issue): RiskAssessment
  flagBreakingChanges(issues: Issue[]): BreakingChange[]
  generateRiskReport(issues: Issue[]): RiskReport
}
```

**Commands to Refactor:**
- autopilot → Use for epic/issue fetching + dep analysis
- implement-epic → Use for same
- analyze-epic → Use for full analysis + output

**Token Reduction:**
- autopilot: 200-300 tokens saved (~3% reduction)
- implement-epic: 200-300 tokens saved (~4-5% reduction)
- analyze-epic: 200-300 tokens saved (~5-7% reduction)
- **Total: 600-900 tokens saved**

**Command Language Reduction:**
- autopilot: 300-400 lines → 150-200 lines
- implement-epic: 200-250 lines → 100-150 lines
- analyze-epic: 150-200 lines → 75-100 lines

---

### Opportunity 2: implementation-coordinator.ts (1-1.5K tokens)

**What's Duplicated:**

| Logic | autopilot | implement-epic | implement-issue | Estimated Tokens |
|-------|-----------|----------------|-----------------|------------------|
| Issue implementation loop | ✅ | ✅ | ✅ | 300-400 |
| Metrics tracking | ✅ | ✅ | ✅ | 200-300 |
| Test-first approach | ✅ | ✅ | ✅ | 200-300 |
| Checkpoint commits | ✅ | ✅ | ✅ | 200-300 |
| Continuous mode (no pauses) | ✅ | ✅ | ✅ | 150-200 |

**Proposed Interface:**
```typescript
interface ImplementationCoordinator {
  // Pre-flight setup
  runPreflightChecks(): Promise<void>
  detectProjectContext(): ProjectContext
  createTODOList(epic: Epic): TODOList
  
  // Implementation orchestration
  createEpicBranch(epicNumber: string, baseBranch: string): void
  implementIssuesInOrder(issues: OrderedIssues): Promise<ImplementationMetrics[]>
  
  // Per-issue coordination
  implementSingleIssue(issue: Issue): Promise<ImplementationMetrics>
  runTestFirstApproach(issue: Issue): Promise<TestResult>
  createCheckpointCommit(issue: Issue, metrics: ImplementationMetrics): void
  
  // Metrics and tracking
  trackMetrics(issue: Issue): ImplementationMetrics
  generateImplementationSummary(metrics: ImplementationMetrics[]): Summary
  
  // PR and merge orchestration
  createPR(branch: string, baseBranch: string, metrics: Summary): Promise<PR>
  addPendingClosureLabels(epic: Epic, issues: Issue[]): Promise<void>
  waitForCIAndMerge(pr: PR): Promise<void>
}
```

**Commands to Refactor:**
- autopilot → Use for issue implementation loop
- implement-epic → Use for same
- implement-issue → Use for single issue implementation

**Token Reduction:**
- autopilot: 300-400 tokens saved (~4% reduction)
- implement-epic: 400-500 tokens saved (~8-10% reduction)
- implement-issue: 200-300 tokens saved (~18-27% reduction)
- **Total: 900-1.2K tokens saved**

**Command Language Reduction:**
- autopilot: 400-500 lines → 250-300 lines
- implement-epic: 300-400 lines → 150-200 lines
- implement-issue: 80-100 lines → 40-50 lines

---

### Opportunity 3: testing-harness.ts (500-800 tokens)

**What's Duplicated:**

| Logic | autopilot | implement-epic | implement-issue | Estimated Tokens |
|-------|-----------|----------------|-----------------|------------------|
| Test framework detection | ✅ | ✅ | ✅ | 150-200 |
| Test-first approach setup | ✅ | ✅ | ✅ | 150-200 |
| Test case generation | ✅ | ✅ | ✅ | 150-200 |
| CI status checking | ✅ | ✅ | ✅ | 100-150 |

**Proposed Interface:**
```typescript
interface TestingHarness {
  // Framework detection
  detectTestFramework(projectContext: ProjectContext): TestFramework
  initializeTestFramework(): void
  
  // Test-first approach
  generateTestCases(issue: Issue): Promise<TestCase[]>
  createTestFile(issue: Issue, tests: TestCase[]): void
  runTestsLocally(): Promise<TestResult>
  
  // CI coordination
  waitForCI(pr: PR): Promise<CIResult>
  parseFailures(ciResult: CIResult): Failure[]
  generateFixSuggestions(failures: Failure[]): Suggestion[]
  
  // Manual test coordination
  generateManualTestPlan(issue: Issue): ManualTestPlan
  confirmManualTests(): Promise<boolean>
}
```

**Commands to Refactor:**
- autopilot → Use for test framework detection + generation
- implement-epic → Use for same
- implement-issue → Use for same

**Token Reduction:**
- autopilot: 150-200 tokens saved (~2% reduction)
- implement-epic: 150-200 tokens saved (~3% reduction)
- implement-issue: 150-250 tokens saved (~14-23% reduction)
- **Total: 450-650 tokens saved**

---

## Total Opportunity Impact

| Script | Savings | Commands Affected | Complexity |
|--------|---------|-------------------|------------|
| epic-orchestrator.ts | 600-900 tokens | 3 | Medium |
| implementation-coordinator.ts | 900-1.2K tokens | 3 | Medium-High |
| testing-harness.ts | 450-650 tokens | 3 | Low-Medium |
| **Total** | **1.95-2.75K tokens** | **3 commands** | **Medium** |

**Percentage Reduction:**
- IMPLEMENT pattern: 10-13% total token savings
- Per-command average: 10-12% reduction

---

## Command Tier Analysis

### Token Distribution by Tier

| Tier | Commands | Total Tokens | % of Pattern |
|------|----------|--------------|--------------|
| STARTER | 4 (autopilot, implement-epic, analyze-epic, implement-issue) | 17,316 | 87% |
| **Total** | **4** | **17,316** | **87%** |

### Tier Hierarchy
✅ SUBSET/SUPERSET maintained
- STARTER: All orchestrators + documentation

---

## Recommendations

### Phase 1: Extract epic-orchestrator.ts
- **Priority:** HIGH (most duplicate logic)
- **Timeline:** 2-3 days
- **Refactors:** autopilot, implement-epic, analyze-epic
- **Savings:** 600-900 tokens

### Phase 2: Extract implementation-coordinator.ts  
- **Priority:** HIGH (second most duplicate logic)
- **Timeline:** 3-4 days
- **Refactors:** autopilot, implement-epic, implement-issue
- **Savings:** 900-1.2K tokens
- **Dependency:** Depends on Phase 1 (epic-orchestrator available)

### Phase 3: Extract testing-harness.ts
- **Priority:** MEDIUM (lower savings, less duplication)
- **Timeline:** 2-3 days
- **Refactors:** autopilot, implement-epic, implement-issue
- **Savings:** 450-650 tokens
- **Dependency:** Depends on Phase 2 (implementation-coordinator available)

### Support Decisions
- **Testing Strategy:** Unit + Integration tests (match ANALYSIS/RELEASE patterns)
- **Measurement:** Manual baseline + Automated CI tracking + Performance benchmarks
- **Rollout:** Sequential (Phase 1 → Phase 2 → Phase 3)
- **Organization:** `scripts/utils/roadcrew/` (distributed to customers)

---

## Next Steps

1. Review this analysis and make decisions on each phase
2. Walk through 7 decision points (Phase 1-3, Support decisions)
3. Create GitHub Epic with child issues for implementation
4. Begin sequential rollout

See COMMAND-USE-CASE-PATTERNS.md for full pattern context.
