---
roadcrew_template_name: "optimize-command.md"
roadcrew_template_type: "command"
execution_mode: "auto-execute"
roadcrew_template_version: "v1.0"
roadcrew_last_updated: "2025-10-25"
roadcrew_min_version: "1.5.0"
roadcrew_license: "See LICENSE file in .roadcrew folder"
roadcrew_copyright: "Copyright (c) 2025 North Star Holdings, LLC"
spdx_license_identifier: "LicenseRef-RoadcrewLicense-1.0"
---

# optimize-command

<!-- Usage: /optimize-command --command "command-name" [--auto] [--dry-run] -->

Analyze an existing Cursor command and propose optimizations to reduce AI dependencies and replace with deterministic scripts.

**Purpose:** Improve command reliability, performance, and cost-efficiency by replacing AI-based logic where non-AI solutions work equally or better.

**Process:**
1. Load and analyze the specified command
2. Identify optimization opportunities
3. Propose changes with risk assessment
4. Get user approval
5. Apply changes to markdown and scripts
6. Run simulated tests to verify improvements

---

## 🎯 Command Execution

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

**Flags:**
- `--command "name"` - Command to optimize (required, kebab-case)
- `--auto` - Apply all low-risk changes automatically (beta)
- `--dry-run` - Show what would change without making changes
- No flags - Interactive mode (analyze → propose → approve → apply)

**Behavior:**
- Reads markdown and TypeScript files for command
- Performs static analysis on code
- Identifies optimization patterns
- Proposes specific changes with rationale
- Requests approval before modifications
- Applies changes and verifies with tests

---

## 📊 Workflow: Load → Analyze → Propose → Approve → Apply → Test

### Phase 1: Load Command

**Load command files:**
```
✓ Reading: commands/roadcrew/[tier]/[name].md
✓ Reading: scripts/[name].ts
✓ Parsing markdown frontmatter
✓ Parsing TypeScript structure
```

**Extract metadata:**
- Command name and tier
- Current AI dependencies
- Template variables used
- Import statements
- Function signatures
- Error handling patterns

### Phase 2: Analysis

**Analyze for optimization opportunities:**

1. **AI Dependency Analysis**
   - Identify all `import` statements related to AI/LLMs
   - Find all API calls (OpenAI, Claude, etc)
   - Locate prompt engineering code
   - Find variable substitution that could be static

2. **Pattern Detection**
   - Look for deterministic operations (file I/O, git, grep)
   - Identify redundant API calls
   - Find where caching could help
   - Detect regex/string operations
   - Find hardcoded thresholds

3. **Performance Analysis**
   - Identify slow async operations
   - Find sequential operations that could be parallel
   - Locate n+1 query patterns
   - Find inefficient loops

4. **Reliability Analysis**
   - Identify timeout risks
   - Find error handling gaps
   - Locate retry logic that could be improved
   - Identify API rate limit exposure

### Phase 3: Propose Changes

**Display detailed proposal:**

```
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔍 COMMAND OPTIMIZATION ANALYSIS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Command: /analyze-epic
Tier: starter
Current AI Dependencies: 2 (Claude API calls)
Optimization Opportunities: 3

Current State:
  • Uses AI to analyze epic scope
  • Uses AI to generate implementation plan
  • ~45 seconds execution time (wait for LLM)
  • ~2,500 tokens per run (costs ~$0.01)

───────────────────────────────────────────────────────────

OPTIMIZATION PROPOSAL 1/3: Pre-Calculate Epic Complexity
Risk: LOW
Impact: 35% faster execution (⏱️ 45s → 29s)

Current Approach:
  Uses Claude to estimate complexity by analyzing issue descriptions

Proposed Approach:
  Replace with deterministic function:
  - Count issues per epic
  - Parse classification numbers (1-10)
  - Calculate LOC estimate from file list
  - Sum hours from metadata

Benefits:
  ✅ Instant results (no LLM wait)
  ✅ Consistent results (no AI variance)
  ✅ No token cost ($0 vs $0.01)
  ✅ Easier to debug and test
  ✅ Works offline

Risks:
  ✅ LOW - Formula based on existing classification system
  ⚠️  May underestimate for unusual patterns (rare)
  ✅ Easy rollback: just call AI again if needed

Files to Modify:
  • scripts/analyze-epic.ts (add calculateComplexity function)
  • commands/roadcrew/starter/analyze-epic.md (update methodology)

Rollback Plan:
  If results differ >10%, revert to AI approach by commenting out
  deterministic calculation and re-enabling Claude API call

───────────────────────────────────────────────────────────

OPTIMIZATION PROPOSAL 2/3: Cache Epic Metadata
Risk: LOW
Impact: 50% faster for repeat calls (⏱️ 29s → 14s on repeat)

Current Approach:
  Re-fetches epic from GitHub every run

Proposed Approach:
  Store metadata in temp file with 1-hour TTL:
  - Cache git history for epic issues
  - Cache file lists per issue
  - Validate cache freshness

Benefits:
  ✅ Dramatically faster repeats
  ✅ Reduces GitHub API calls
  ✅ Reduces rate limit exposure
  ✅ Works when API rate limited

Risks:
  ✅ LOW - TTL ensures freshness
  ⚠️  Stale data if changes during work (acceptable)
  ✅ Clear cache on demand with --refresh flag

Files to Modify:
  • scripts/analyze-epic.ts (add caching layer)
  • commands/roadcrew/starter/analyze-epic.md (document --refresh flag)

Rollback Plan:
  Delete cache files and remove caching code

───────────────────────────────────────────────────────────

OPTIMIZATION PROPOSAL 3/3: Parallelize GitHub Fetches
Risk: MEDIUM
Impact: 20% faster (⏱️ 29s → 23s, but more reliable)

Current Approach:
  Fetches issues sequentially with await

Proposed Approach:
  Use Promise.all() for 4 parallel fetches
  - Fetch epic metadata
  - Fetch child issues
  - Fetch related PRs
  - Fetch commit history

Benefits:
  ✅ 20% faster overall
  ✅ Better resource utilization
  ✅ Timeout-resistant

Risks:
  ⚠️  MEDIUM - GitHub rate limits
     Current: ~60 req/hour allowed
     With parallelism: ~90 req/hour possible
  ⚠️  May hit rate limits on large epics
  ✅ Graceful degradation: falls back to sequential

Files to Modify:
  • scripts/analyze-epic.ts (refactor fetch logic)

Rollback Plan:
  Change Promise.all() back to sequential awaits

───────────────────────────────────────────────────────────

Summary by Risk Level:
  ✅ Low Risk:   2 optimizations (proposals 1-2)
  ⚠️  Medium Risk: 1 optimization (proposal 3)
  🔴 High Risk:   0 optimizations

Total Impact if All Applied:
  ⏱️  Performance: 45s → 14s (69% faster on repeats)
  💰 Cost: $0.01 → $0 per run
  📊 Reliability: Medium (current) → High (improved caching)
  🔧 Maintainability: Medium → High (less AI dependency)

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

### Phase 4: User Approval

**Show approval options:**

```
Which changes would you like to apply?

[1] Accept all low-risk changes (1-2) → Recommended
[2] Accept all changes (1-3) → More aggressive
[3] Selective approval → Choose each one
[n] Skip optimization → Keep current version
[?] Learn more about risk assessment

Enter choice (1/2/3/n/?): _
```

**If selective:**
```
Proposal 1/3: Pre-Calculate Epic Complexity (LOW risk)
  Apply? (y/n/explain): _

Proposal 2/3: Cache Epic Metadata (LOW risk)
  Apply? (y/n/explain): _

Proposal 3/3: Parallelize GitHub Fetches (MEDIUM risk)
  Apply? (y/n/explain): _
```

### Phase 5: Apply Changes

**Modify files:**

```
✅ Applying approved changes...

  Proposal 1: Pre-Calculate Epic Complexity
  ✓ Added calculateComplexity() to scripts/analyze-epic.ts
  ✓ Updated markdown documentation
  ✓ Added test cases

  Proposal 2: Cache Epic Metadata
  ✓ Added caching layer to scripts/analyze-epic.ts
  ✓ Added --refresh flag to markdown
  ✓ Updated README

  Proposal 3: SKIPPED (not approved)

✅ Building TypeScript...
  ✓ Compilation successful
```

### Phase 6: Verify with Tests

**Run simulated tests:**

```
✅ Running simulated tests...

Test 1: Epic Complexity Calculation
  Input: Epic with 5 issues (classifications: 4, 5, 6, 7, 8)
  Expected: complexity = 6 (medium-high)
  Result: complexity = 6 ✅ PASS
  Time: 2ms (was 2000ms with AI) [100x faster]

Test 2: Metadata Caching
  First run: 2,847ms (fetch + cache)
  Second run (from cache): 12ms ✅ PASS
  Time saved: 2,835ms ✅ HUGE WIN
  Cache hit rate: 95% ✅ GOOD

Test 3: GitHub API Calls
  Before: 12 sequential calls @ 2-3ms each = 24-36ms
  After: 4 parallel calls @ 5ms = 5ms ✅ PASS
  API savings: 66% fewer calls ✅ GREAT

Test 4: Regression - Existing Behavior
  Old approach results: Epic complexity = medium-high
  New approach results: Epic complexity = medium-high ✅ PASS
  Outputs match: 100% ✅ VERIFIED

Test 5: Edge Cases
  Empty epic (0 issues): Handled ✅ PASS
  Single large issue: Handled ✅ PASS
  Invalid classification: Defaults to 5 ✅ PASS

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ OPTIMIZATION COMPLETE
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Changes Applied: 2/3 proposals
Files Modified:
  • scripts/analyze-epic.ts (added 180 lines)
  • commands/roadcrew/starter/analyze-epic.md (updated)

Test Results: 5/5 passing ✅

Performance Improvements:
  • First run: 45s → 29s (35% faster)
  • Repeat runs: 45s → 14s (69% faster)
  • API calls: 12 → 4 per run (66% reduction)

Cost Savings:
  • Per run: $0.01 → $0
  • Annual (1000 runs): $10 → $0

Reliability Improvements:
  • Timeout resilience: Medium → High
  • Works offline: No → Yes
  • Deterministic results: No → Yes

Next Steps:
  1. Review: git diff scripts/analyze-epic.ts
  2. Test in staging: /analyze-epic 123
  3. Commit: git commit -m "opt: optimize analyze-epic with caching"
  4. Deploy: npm run build && npm run deploy

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

---

## 🎯 Optimization Patterns

**Common patterns to replace with non-AI logic:**

1. **Static Analysis → Deterministic Scoring**
   - AI analyzes code complexity
   - Replace with: Line count, cyclomatic complexity, nesting depth

2. **Natural Language Classification → Rule-Based**
   - AI classifies issues as enhancement/bug/feature
   - Replace with: Keyword matching in title/description

3. **Ad-hoc Parsing → Structured Extraction**
   - AI extracts info from unstructured text
   - Replace with: Regex patterns, schema validation

4. **Sequential Fetches → Parallel Requests**
   - AI processes items one at a time
   - Replace with: Promise.all() for parallel async

5. **Live Calculations → Cached Results**
   - AI regenerates same result every run
   - Replace with: Cache with TTL invalidation

6. **Expensive Operations → Lazy Evaluation**
   - AI computes everything upfront
   - Replace with: Compute only when needed

7. **Random Retry Logic → Exponential Backoff**
   - AI decides when to retry
   - Replace with: Algorithm-based backoff

---

## 📊 Risk Assessment Framework

**LOW Risk:**
- Replacing AI with deterministic formula
- Adding caching layer
- Simple refactoring
- Rollback is trivial
- No API changes
- Easy to test
- Previous patterns in codebase

**MEDIUM Risk:**
- Parallelizing sequential operations
- Adding new dependencies
- Changing error handling
- Rollback is straightforward
- May affect timing/order
- Requires testing
- New pattern for codebase

**HIGH Risk:**
- Removing error handling
- Changing API contracts
- Affecting other commands
- Complex rollback needed
- Breaking changes possible
- Extensive testing required
- Affects critical paths

---

## 🧪 Verification Process

**Simulated tests check:**
1. Functional correctness (same outputs)
2. Performance improvements (faster or same speed)
3. Cost reduction (fewer API calls)
4. Reliability improvements (fewer timeouts)
5. Edge case handling (unusual inputs)
6. Regression testing (old behavior preserved)
7. Integration tests (other commands still work)

---

## Configuration

Before running, ensure:
1. Command to optimize exists
2. TypeScript compiles (`npm run build`)
3. Git status is clean (for rollback)

---

## Flags

**`--command "name"`** (required)
- Name of command to optimize
- Kebab-case (e.g., analyze-epic)

**`--auto`** (optional)
- Apply all low-risk changes automatically
- Skip approval step for safe optimizations
- Still prompts for medium/high risk

**`--dry-run`** (optional)
- Show what would change without applying
- Generate report without modifying files
- Useful for previewing before commit

---

## Notes

- Created for optimizing existing Roadcrew commands
- Focuses on reducing AI dependency
- Emphasizes deterministic, testable code
- Includes thorough risk assessment
- Requires user approval before changes
- Verifies changes with simulated tests
- Supports rollback if needed

---

## See Also

- Related commands: `/create-command`, `/analyze-repo`
- Performance guide: `docs/PERFORMANCE-TUNING.md`
- Testing guide: `.cursorrules.md`
