---
roadcrew_template_name: "audit-complexity.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"
---

# audit-complexity

Measure and reduce cyclomatic complexity, function size, and nesting depth to improve code maintainability.

## Usage

```bash
/audit-complexity [--max-complexity N] [--files pattern]
```

## What This Command Does

Analyzes code complexity metrics including:
- **Cyclomatic Complexity** - Number of decision paths (if/else, loops, switches)
- **Function Size** - Lines of code per function, identifies oversized functions
- **Nesting Depth** - Maximum nesting level, flags deeply nested blocks
- **Cognitive Complexity** - How hard the code is to understand
- **Maintainability Index** - Overall code quality score

Generates complexity report with recommendations for refactoring.

## Complexity Metrics Explained

### Cyclomatic Complexity

Count of decision paths through code:
- **1-3**: Simple, easy to test (✅ Good)
- **4-7**: Moderate, testable (🟡 OK)
- **8-10**: Complex, hard to test (⚠️ Warning)
- **11+**: Very complex, requires refactoring (🔴 Critical)

### Function Size

- **1-20 lines**: Small, focused (✅ Good)
- **21-50 lines**: Medium, acceptable (🟡 OK)
- **51-100 lines**: Large, consider refactoring (⚠️ Warning)
- **100+ lines**: Too large, needs refactoring (🔴 Critical)

### Nesting Depth

- **1-2 levels**: Shallow, readable (✅ Good)
- **3-4 levels**: Moderate (🟡 OK)
- **5+ levels**: Deep, hard to follow (🔴 Critical)

## Output Format

```bash
$ /audit-complexity --max-complexity 8

📊 Code Complexity Audit: roadcrew-internal

Files Analyzed: 147 | Total Functions: 892 | Scan Time: 1.2s

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
📈 COMPLEXITY SUMMARY
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Average Cyclomatic Complexity: 4.2
Maintainability Index: 72/100

Functions Exceeding Threshold (>8):
- 23 functions need refactoring
- 5 functions critical (>20 complexity)

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🚨 CRITICAL COMPLEXITY (Complexity >15)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Function 1: createIssuesInBatch()
- Location: scripts/core/github-issue-creator.ts:145
- Cyclomatic Complexity: 22
- Function Size: 148 lines
- Nesting Depth: 5
- Recommendation: Split into smaller functions, extract conditions

Function 2: parseAndValidateIssue()
- Location: scripts/utils/issue-parser.ts:67
- Cyclomatic Complexity: 18
- Function Size: 95 lines
- Nesting Depth: 4
- Recommendation: Use switch statement, reduce branching

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
⚠️ HIGH COMPLEXITY (Complexity 10-15)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

[13 functions listed with refactoring suggestions]

📊 Full report: config/reports/complexity-audit-2025-10-29.md
🔗 Create GitHub issues for critical functions?
   Run: npm run audit-complexity -- --create-issues
```

## Refactoring Strategies

### Strategy 1: Extract Conditions
```typescript
// ❌ High complexity
function process(data) {
  if (data.type === 'A' && data.status === 'active') {
    // ...
  } else if (data.type === 'B' && data.status === 'pending') {
    // ...
  }
}

// ✅ Lower complexity
function isActive(data) {
  return data.type === 'A' && data.status === 'active';
}

function process(data) {
  if (isActive(data)) {
    // ...
  } else if (isPending(data)) {
    // ...
  }
}
```

### Strategy 2: Use Guard Clauses
```typescript
// ❌ High nesting
function validate(user) {
  if (user) {
    if (user.email) {
      if (user.email.includes('@')) {
        return true;
      }
    }
  }
  return false;
}

// ✅ Lower nesting
function validate(user) {
  if (!user) return false;
  if (!user.email) return false;
  return user.email.includes('@');
}
```

### Strategy 3: Polymorphism over Conditionals
```typescript
// ❌ High complexity
function calculateFee(type) {
  if (type === 'standard') return amount * 0.1;
  if (type === 'premium') return amount * 0.05;
  if (type === 'vip') return amount * 0.02;
}

// ✅ Lower complexity with classes
class FeeCalculator {
  calculate() { /* subclass specific */ }
}

class StandardFeeCalculator extends FeeCalculator {
  calculate() { return amount * 0.1; }
}
```

## Flags & Options

```bash
--max-complexity N              # Report functions exceeding threshold (default: 10)
--files pattern                 # Analyze specific files only
--show-all                      # Show all functions (not just above threshold)
--create-issues                 # Create GitHub issues for critical functions
--sort complexity|size|nesting  # Sort results by metric
```
