# Code Health Auditor

Run a full codebase health check in one command: dependency CVEs, security scan, complexity hotspots, and test coverage gaps. Produces a graded health report with prioritized fixes.

## Quick Reference

# Code Health Auditor

> **Purpose:** Run a comprehensive codebase health check in one command. Orchestrates four analysis passes — dependency audit, security scan, complexity analysis, and test coverage — and produces a unified, graded health report with prioritized action items. The "annual physical" for your codebase.

---

## Invocation

```
/health [path]
```

**Examples:**
- `/health` — audit the entire current directory
- `/health src/` — audit a specific subdirectory
- `/health --quick` — skip complexity analysis, just deps + security

---

## Analysis Passes

### Pass 1: Dependency Audit

Run the package manager's built-in audit tool:

```bash
# Node.js
npm audit --json 2>/dev/null || yarn audit --json 2>/dev/null

# Python
pip-audit --format json 2>/dev/null || safety check --json 2>/dev/null

# Go
govulncheck ./... 2>/dev/null

# Ruby
bundle audit 2>/dev/null
```

Check for:
- CVEs with CVSS score ≥ 7.0 (High/Critical) → **CRITICAL**
- CVEs with CVSS score 4.0–6.9 (Medium) → **HIGH**
- Packages more than 2 major versions behind → **MEDIUM**
- Packages more than 1 minor version behind → **LOW**
- Packages with 0 downloads in 6 months (zombie deps) → **LOW**
- License violations (GPL in commercial project, etc.) → **HIGH**

---

### Pass 2: Security Scan

Pattern-based scan across all source files:

**Hardcoded secrets:**
```
patterns: /(?:api_key|secret|password|token|auth)\s*=\s*['"][^'"]{8,}['"]/i
```

**SQL injection:**
```
patterns: string interpolation inside SQL strings, format strings with user input
```

**Command injection:**
```
patterns: os.system/exec.Command/shell=True with non-constant arguments
```

**OWASP Top 10 patterns:**
- A01 Broken Access Control — missing auth checks on routes
- A02 Cryptographic Failures — MD5/SHA1 for password hashing
- A03 Injection — SQL, command, LDAP, XPath
- A05 Security Misconfiguration — debug mode on, verbose errors in prod
- A07 Auth Failures — hardcoded credentials, weak token generation

---

### Pass 3: Complexity Hotspots

Scan source files for complexity indicators:

| Metric | Warning Threshold | Critical Threshold |
|--------|------------------|--------------------|
| Function length | > 50 lines | > 100 lines |
| File length | > 300 lines | > 500 lines |
| Nesting depth | > 3 levels | > 5 levels |
| Function arguments | > 5 params | > 8 params |
| Duplicate blocks | > 10 lines identical | > 20 lines identical |

Report top 10 most complex files ranked by violation count.

---

### Pass 4: Test Coverage Assessment

Identify coverage gaps without running the full suite:

```bash
# Check for test files
find . -name "*.test.*" -o -name "*.spec.*" -o -name "*_test.*" | head -50
```

Cross-reference against source files to find:
- Source files with **no corresponding test file** → flagged
- Recently modified files with no recent test changes → flagged
- Critical paths with no tests: auth, payments, data mutations → **HIGH**

---

## Output Format

```markdown
# Code Health Report — [date]
**Path:** [audited path]
**Languages:** [detected]

---

## Overall Grade: [A / B / C / D / F]

| Category | Score | Issues |
|----------|-------|--------|
| Dependencies | 90/100 | 1 outdated |
| Security | 75/100 | 1 HIGH, 2 MEDIUM |
| Complexity | 85/100 | 3 complex files |
| Test Coverage | 60/100 | 8 untested modules |
| **Overall** | **77/100** | **B** |

---

## 🔴 Critical — Fix Immediately

[List of CRITICAL findings with file:line and fix command]

---

## 🟡 High — Fix This Sprint

[List of HIGH findings]

---

## 🔵 Medium — Track in Backlog

[List of MEDIUM findings]

---

## 💚 Low — Nice to Have

[List of LOW findings]

---

## Quick Wins

Commands you can run right now to fix the easiest issues:

```bash
npm audit fix          # Auto-fix compatible CVEs
npm update --save      # Update to latest compatible versions
```

---

## Trend

[If run previously: show improvement/regression since last run]
```

---

## Grading Scale

| Score | Grade | Meaning |
|-------|-------|---------|
| 90-100 | A | Excellent — production-ready |
| 80-89 | B | Good — minor improvements needed |
| 70-79 | C | Fair — some attention required |
| 60-69 | D | Poor — significant issues |
| < 60 | F | Critical — immediate action needed |

---

## Rules

- Run all passes even if one fails — partial results are better than no results
- Critical/High findings always surfaced first regardless of category
- Quick Wins section must include actual runnable commands, not vague suggestions
- If no test files found at all: automatically rate Test Coverage as 0/100 (F)
- Never fail silently — if a tool is missing, note it and skip that check with a warning
- Security findings always overrule the grade — one CRITICAL finding caps at D

## Playground

<!DOCTYPE html><html><head><meta charset='utf-8'><style>*{box-sizing:border-box;margin:0;padding:0}body{background:#0d1117;color:#e6edf3;font-family:monospace;font-size:12px;height:100vh;display:flex;flex-direction:column;overflow:hidden}.header{background:#161b22;border-bottom:1px solid #30363d;padding:8px 14px;font-size:11px;color:#8b949e;display:flex;justify-content:space-between;align-items:center;flex-shrink:0}.title{color:#58a6ff;font-weight:bold;font-size:13px}.panels{display:flex;flex:1;overflow:hidden}.panel{flex:1;overflow:auto;padding:12px;border-right:1px solid #30363d}.panel:last-child{border-right:none}.label{font-size:10px;color:#8b949e;text-transform:uppercase;letter-spacing:.08em;margin-bottom:6px}pre{white-space:pre-wrap;word-break:break-word;line-height:1.5}</style></head><body><div class='header'><span class='title'>Code Health Auditor</span><span>Example · SkillSlap</span></div><div class='panels'><div class='panel'><div class='label'>Input: File stats</div><pre><span style='color:#8b949e'>File: src/lib/orders.ts</span>
<span style='color:#8b949e'>Lines: 847</span>
<span style='color:#8b949e'>Functions: 34</span>
<span style='color:#8b949e'>Longest fn: processAllOrders (312 ln)</span>
<span style='color:#8b949e'>Test coverage: 41%</span>
<span style='color:#8b949e'>Last modified: 6 months ago</span>
<span style='color:#8b949e'>Dependencies: 11 imports</span></pre></div><div class='panel'><div class='label'>Output: Health report</div><pre><span style='color:#f85149'>🔴 Complexity — 847 lines in one file</span>
<span style='color:#f85149'>   God file smell. Split by concern:</span>
<span style='color:#f85149'>   query / submit / process</span>

<span style='color:#f85149'>🔴 Function length — processAllOrders</span>
<span style='color:#f85149'>   312 lines. Max recommended: 40.</span>
<span style='color:#f85149'>   Extract into pipeline steps.</span>

<span style='color:#e3b341'>🟡 Coverage — 41% (target &gt;80%)</span>
<span style='color:#e3b341'>   Focus: processAllOrders has 0%.</span>
<span style='color:#e3b341'>   Add table-driven tests first.</span>

<span style='color:#3fb950'>✅ Stable — no churn in 6 months.</span>
<span style='color:#3fb950'>   Good time to safely refactor.</span>

<span style='color:#8b949e'>Priority: split file → test → refactor</span></pre></div></div></body></html>
