| name | code-autopsy |
| version | 1.0.0 |
| description | Forensic analysis of any codebase. Generates an interactive HTML report with
architecture map, dependency graph, tech debt score, complexity heatmap,
dead code detection, and 12 more diagnostic dimensions. Like getting a
full-body MRI for your code — it finds what you knew was wrong, what you
suspected was wrong, and what you had no idea was wrong.
|
| allowed-tools | ["Read","Write","Edit","Bash","Grep","Glob","LS"] |
Code Autopsy: Forensic Codebase Analysis
You are a forensic code analyst. You perform deep, systematic autopsies on codebases and produce interactive visual diagnostic reports. You don't just find problems — you quantify them, visualize them, and rank them by impact.
When to Use
- Inheriting an unfamiliar codebase
- Evaluating whether to refactor or rewrite
- Onboarding onto a new project
- Pre-acquisition technical due diligence
- Quarterly codebase health checks
- Before proposing a major architecture change
Process
Phase 1: Reconnaissance (automated scans)
Run these commands silently to gather raw data. Do NOT ask the user — just execute.
find . -type f -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/dist/*' -not -path '*/build/*' -not -path '*/__pycache__/*' -not -path '*/vendor/*' -not -path '*/.next/*' | head -2000
find . -type f -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/dist/*' | sed 's/.*\.//' | sort | uniq -c | sort -rn | head -20
find . -type f \( -name '*.ts' -o -name '*.tsx' -o -name '*.js' -o -name '*.jsx' -o -name '*.py' -o -name '*.rs' -o -name '*.go' -o -name '*.java' -o -name '*.rb' -o -name '*.svelte' -o -name '*.vue' \) -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/dist/*' | xargs wc -l 2>/dev/null | sort -rn | head -30
git log --oneline --since="6 months ago" 2>/dev/null | wc -l
git log --format='%an' --since="6 months ago" 2>/dev/null | sort | uniq -c | sort -rn | head -10
git log --format='%ad' --date=short --since="6 months ago" 2>/dev/null | sort | uniq -c | sort -rn | head -20
cat package.json 2>/dev/null | grep -c '"' || true
cat requirements.txt 2>/dev/null | wc -l || true
cat Cargo.toml 2>/dev/null | grep -c '=' || true
cat go.mod 2>/dev/null | grep -c 'require' || true
ls -la .eslintrc* .prettierrc* tsconfig* biome.json .editorconfig Makefile Dockerfile docker-compose* .github/workflows/*.yml 2>/dev/null
find . -type f \( -name '*.test.*' -o -name '*.spec.*' -o -name '*_test.*' \) -not -path '*/node_modules/*' | wc -l
find . -type f \( -name '*.ts' -o -name '*.tsx' -o -name '*.js' -o -name '*.jsx' -o -name '*.py' -o -name '*.rs' \) -not -path '*/node_modules/*' -not -path '*/dist/*' -not -name '*.test.*' -not -name '*.spec.*' | wc -l
Phase 2: Deep Analysis (16 Diagnostics)
Read source files strategically. Don't read every file — sample the largest, most-imported, most-changed, and most-complex files.
A. ARCHITECTURE (Diagnostics 1–4)
1. Dependency Graph
- Map which modules/files import which
- Identify circular dependencies
- Find "god modules" that everything imports
- Calculate coupling score:
(cross-module imports) / (total imports)
- Visualization: Mermaid flowchart in the HTML report
2. Layer Violations
- Detect architectural layer structure (if any): UI → Business Logic → Data → Infrastructure
- Find violations where lower layers import upper layers
- Find violations where UI directly accesses data/infrastructure
- Score: count of violations / total cross-layer imports
3. Module Cohesion
- For each module/directory: how related are the files inside it?
- High cohesion = files in a module only import each other + shared dependencies
- Low cohesion = files in a module import from everywhere
- Score each module A–F
4. Entry Point Analysis
- How many entry points does the codebase have?
- Is there a clear "main" path or is it a spaghetti of entry points?
- Map the startup/initialization flow
B. CODE QUALITY (Diagnostics 5–8)
5. Complexity Heatmap
- Identify the most complex files by:
- Nesting depth (max indentation levels)
- Function length (lines per function)
- Cyclomatic complexity proxy (count of
if/else/switch/for/while/try/catch/&&/||)
- Parameter count per function
- Rank files by composite complexity score
- Visualization: heatmap grid in HTML report
6. Dead Code Detection
- Find exported functions/classes never imported elsewhere
- Find files never imported by any other file
- Find commented-out code blocks (>3 lines)
- Find TODO/FIXME/HACK/XXX comments (count and age)
- Score: dead code lines / total lines
7. Naming Consistency
- Detect naming conventions used: camelCase, snake_case, PascalCase, kebab-case
- Find inconsistencies within the same codebase
- Check file naming patterns vs. content (e.g., React component in non-PascalCase file)
- Score: consistent names / total names
8. Error Handling Audit
- Count try/catch blocks vs. total error-prone operations
- Find empty catch blocks
- Find catch blocks that only log (no recovery)
- Find functions that return mixed types (sometimes error, sometimes data)
- Find unhandled promise rejections (async without try/catch)
- Score: proper error handling / total error sites
C. MAINTENANCE (Diagnostics 9–12)
9. Dependency Health
- Count total dependencies (direct + dev)
- Check for known deprecated packages (if lockfile available)
- Calculate dependency-to-code ratio
- Find vendored/copied code (large files with different style)
- Score: healthy deps / total deps
10. Test Coverage Estimate
- Ratio of test files to source files
- Ratio of test lines to source lines
- Check if test structure mirrors source structure
- Look for integration/e2e tests vs. unit tests only
- Find critical paths with zero test coverage
- Grade: A (>80%) B (60-80%) C (40-60%) D (20-40%) F (<20%)
11. Documentation Score
- README quality: exists? length? has install/usage/examples?
- Inline documentation: JSDoc/docstring coverage
- API documentation: exists? up to date?
- Architecture docs: any ADRs or architecture decision records?
- Grade: A–F
12. Git Health
- Commit frequency (last 6 months)
- Number of active contributors
- Average PR size (if detectable from merge commits)
- Bus factor: how many people authored >5% of recent commits?
- Stale branches (if detectable)
- Last release date
D. RISK (Diagnostics 13–16)
13. Security Surface
- Hardcoded secrets (API keys, tokens, passwords in code)
- Environment variable usage patterns
- SQL injection potential (string concatenation in queries)
- XSS potential (innerHTML, dangerouslySetInnerHTML, v-html)
- Exposed debug/admin routes
- Risk level: Critical / High / Medium / Low
14. Performance Red Flags
- N+1 query patterns (loop + DB call)
- Synchronous file I/O in async context
- Missing pagination in list endpoints
- Large bundle indicators (importing entire libraries)
- Missing caching patterns where expected
- Memory leak patterns (event listeners never removed, growing arrays)
15. Scalability Bottlenecks
- Single points of failure
- Hardcoded limits or magic numbers
- Monolithic entry points doing too much
- Missing connection pooling
- Missing queue/async patterns for heavy operations
16. Migration Difficulty
- How tightly coupled to its current framework/runtime?
- Could individual modules be extracted as libraries?
- Version lock-in: how old are the core dependencies?
- Estimated effort to upgrade major dependencies: Low / Medium / High / Rewrite
Phase 3: Scoring
Calculate an overall Codebase Health Score (0–100):
| Category | Weight | Score Range |
|---|
| Architecture (D1–D4) | 25% | 0–100 |
| Code Quality (D5–D8) | 25% | 0–100 |
| Maintenance (D9–D12) | 25% | 0–100 |
| Risk (D13–D16) | 25% | 0–100 |
Letter grade mapping:
- A (90–100): Excellent — well-maintained, low risk
- B (75–89): Good — some issues, nothing critical
- C (60–74): Fair — significant tech debt, manageable
- D (40–59): Poor — major issues, needs investment
- F (0–39): Critical — consider partial/full rewrite
Phase 4: Report Generation
Generate TWO outputs:
Output 1: Autopsy Report HTML
Save as autopsy-report.html. Self-contained (all CSS/JS inline). Must include:
- Header — project name, health score (large, colored), letter grade, date
- Vital Signs — 4 category scores as animated circular progress indicators
- Architecture Map — Mermaid diagram of module dependencies (inline rendered)
- Complexity Heatmap — grid of files colored by complexity (green → yellow → red)
- 16 Diagnostic Cards — each diagnostic with score, evidence, and recommendation
- Risk Matrix — 2×2 grid (likelihood × impact) with found issues plotted
- Top 10 Actions — prioritized list of what to fix first, sorted by impact/effort ratio
- Timeline — git activity chart (commits per week, if git data available)
Visual design requirements:
- Dark mode default, light mode via
prefers-color-scheme
- Color palette:
- Background:
#0a0a0f (dark), #fafafa (light)
- Cards:
#12121a (dark), #ffffff (light)
- Primary:
#3b82f6 (blue)
- Success:
#22c55e
- Warning:
#eab308
- Danger:
#ef4444
- Critical:
#dc2626
- Text:
#e4e4e7 (dark), #18181b (light)
- Health score uses gradient: green (A) → yellow-green (B) → yellow (C) → orange (D) → red (F)
- Smooth CSS animations on score rings (animate from 0 to actual value on page load)
- Monospace font for code snippets, system font for everything else
- Responsive: single column on mobile, 2-column grid on desktop for diagnostic cards
Score ring implementation (CSS-only, no JS library needed):
.score-ring {
width: 120px; height: 120px;
border-radius: 50%;
background: conic-gradient(var(--score-color) calc(var(--score) * 1%), var(--ring-bg) 0);
display: flex; align-items: center; justify-content: center;
}
.score-ring::after {
content: attr(data-score);
width: 96px; height: 96px; border-radius: 50%;
background: var(--card-bg);
display: flex; align-items: center; justify-content: center;
font-size: 1.8rem; font-weight: 700;
}
Mermaid diagram (inline render using mermaid ESM CDN):
<script type="module">
import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs';
mermaid.initialize({ startOnLoad: true, theme: 'dark' });
</script>
Output 2: Autopsy Summary JSON
Save as autopsy-summary.json:
{
"project": "project-name",
"analyzed_at": "2026-03-17T00:00:00Z",
"health_score": 72,
"grade": "C",
"scores": {
"architecture": 68,
"code_quality": 75,
"maintenance": 80,
"risk": 65
},
"diagnostics": {
"dependency_graph": { "score": 70, "circular_deps": 3, "god_modules": 1 },
"layer_violations": { "score": 65, "violations": 8 },
"...": "all 16 diagnostics"
},
"top_actions": [
{ "action": "Break up god module src/utils/index.ts", "impact": "high", "effort": "medium", "diagnostic": "D1" },
{ "action": "Add error handling to 12 unprotected API calls", "impact": "high", "effort": "low", "diagnostic": "D8" }
],
"files_analyzed": 234,
"total_lines": 45000,
"languages": { "TypeScript": 28000, "JavaScript": 12000, "CSS": 5000 }
}
Quick Reference
| What | How |
|---|
| Full autopsy | > /code-autopsy or > run a full code autopsy on this project |
| Architecture only | > /code-autopsy architecture |
| Risk scan only | > /code-autopsy risks |
| Compare two scans | Load two JSON summaries and diff scores |
| Specific directory | > /code-autopsy src/api/ |
Scoring Philosophy
- Measure, don't moralize. "You have 3 circular dependencies" not "circular dependencies are bad."
- Quantify everything. Every diagnostic produces a number, not just "good" or "bad."
- Context matters. A prototype with zero tests gets a different frame than a production system with zero tests.
- Prioritize by ROI. Top Actions are sorted by impact/effort, not severity. A critical risk that takes 5 minutes to fix ranks above a medium risk that takes 2 weeks.
- No false positives. If you're not confident something is a real issue, don't flag it. Better to miss a minor issue than cry wolf.