| name | analyzing-codebases |
| description | Performs thorough, autonomous codebase analysis using layered deep-dive methodology. Produces comprehensive markdown report. Use when joining a project, before architectural changes, for health checks, or onboarding. Triggers include "analyze this codebase", "understand this project", "codebase overview", "what does this code do", or /analyzing-codebases. Supports --quick, --thorough, --exhaustive modes. |
Codebase Analysis - Layered Deep Dive
Produces a comprehensive markdown report at .claude/codebase-analysis.md without requiring back-and-forth interaction.
Trigger
Use this skill when:
- Joining a new project for the first time
- Before making significant architectural changes
- Performing periodic codebase health checks
- Generating onboarding context for a new Claude session
- User invokes
/analyze-codebase
Arguments
--quick — Survey mode (~5 min): Entry points, high-level patterns, health snapshot
--thorough — Default (~15-20 min): Full layered analysis, 3-5 key flow traces
--exhaustive — Leave no stone unturned (~30+ min): Every module, all flows, full cross-references
--focus=<area> — Prioritize a specific directory or module for deeper analysis
Output
Generate report at: .claude/codebase-analysis.md
If the file exists, check the commit SHA — if unchanged, offer to update specific sections rather than regenerate.
Algorithm: Layered Deep Dive
Execute these phases sequentially. Each phase builds on discoveries from previous phases.
Phase 1: Structural Survey
Goal: Understand the skeleton of the codebase.
-
Identify project type and framework
- Check for package.json, Cargo.toml, pyproject.toml, Gemfile, go.mod, etc.
- Note framework (Rails, Next.js, FastAPI, etc.)
- Record language(s) and build system
-
Map directory structure
- Identify conventional directories (src/, lib/, app/, tests/, etc.)
- Note unconventional organization patterns
- Identify generated vs. authored code
-
Find entry points
- Main files, index files, CLI entry points
- API route definitions
- Event handlers, job processors
- List with brief description of each
-
Catalog configuration
- Environment handling patterns
- Feature flags
- Secrets management approach (DO NOT read actual secrets)
Phase 2: Dependency Mapping
Goal: Understand how modules relate to each other.
-
Build import graph
- From each entry point, trace imports/requires 3 levels deep
- Identify "hub" modules (imported by 5+ other files)
- Identify "leaf" modules (import others, not imported)
-
External dependency analysis
- List key external dependencies with their purpose
- Note version constraints or pinning patterns
- Flag deprecated or concerning dependencies if obvious
-
Identify architectural boundaries
- Where are the layer separations? (API → Service → Data)
- Are boundaries clean or do they have leakage?
- Note any circular dependencies
Phase 3: Data Structure Archaeology
Goal: Understand the "nouns" of the system.
-
Find core types/models/schemas
- Database models, TypeScript interfaces, dataclasses, structs
- API request/response shapes
- Internal domain objects
-
Trace type definitions vs. usage
- Where are types defined?
- Where are they consumed?
- Are there duplicate/competing type definitions?
-
Identify data transformation patterns
- How does data change shape as it moves through the system?
- Serialization/deserialization boundaries
- Validation points
Phase 4: Flow Tracing
Goal: Understand how key operations work end-to-end.
-
Select representative flows (3-5 for thorough, all for exhaustive)
- A read operation (fetch/query)
- A write operation (create/update)
- A complex business operation
- An async/background operation if present
- An external integration if present
-
For each flow, trace:
- Entry point → Validation → Business logic → Data layer → Response
- Error handling path
- Side effects (logging, events, notifications)
-
Document as sequence or bullet narrative
Phase 5: Pattern Extraction
Goal: Understand the "grain" and conventions of the codebase.
-
Naming conventions
- File naming (kebab-case, PascalCase, etc.)
- Function/method naming
- Variable naming
- Test naming
-
Structural patterns
- How are similar things organized? (by feature, by type, by layer)
- What abstractions exist? (base classes, mixins, HOCs, hooks)
- What patterns repeat? (repository pattern, service objects, etc.)
-
Code style idioms
- Error handling style (exceptions, Result types, error codes)
- Async patterns (callbacks, promises, async/await)
- State management approach
-
Testing patterns
- Test organization (co-located, separate directory)
- Test types present (unit, integration, e2e)
- Mocking/stubbing conventions
Phase 6: Health Scan
Goal: Identify potential issues and technical debt.
-
Complexity hotspots
- Files over 500 lines (list with line counts)
- Functions over 50 lines
- Deeply nested code (4+ levels)
-
Debt markers
- Count and sample TODO comments
- Count and sample FIXME comments
- HACK, XXX, TEMP markers
-
Churn analysis (if git available)
- Most frequently modified files (last 3 months)
- Files with many authors (potential knowledge silos)
- Recently added large files
-
Test coverage signals
- Ratio of test files to source files
- Directories with no tests
- Test file staleness (tests older than source)
Smart Depth Heuristics
Apply these rules autonomously rather than asking:
| Signal | Action |
|---|
| Hub module (imported by 5+ files) | Always trace deeply, document thoroughly |
| Entry point | Trace 3 levels deep minimum |
| Large file (>500 lines) | Analyze internal structure, flag in health |
| High churn (>10 commits in 30 days) | Prioritize for pattern analysis |
| Test file | Note existence, don't deep-dive |
| Config/generated/vendor files | Skim for understanding, don't analyze |
| TODO/FIXME density > 5 per file | Flag as debt hotspot |
| Circular dependency detected | Document and flag |
Report Template
# Codebase Analysis: {project-name}
**Generated:** {timestamp}
**Mode:** {quick|thorough|exhaustive}
**Commit:** {git-short-sha}
**Analyzed by:** Claude ({model-id})
---
## Executive Summary
[2-4 sentences: What is this? What's its architecture? What's notable?]
**Quick Stats:**
- Languages: {list}
- Framework: {name}
- Entry Points: {count}
- Source Files: {count}
- Test Files: {count}
- External Dependencies: {count}
---
## Architecture Overview
### Project Type & Stack
[Framework, language, build system, key tooling]
### Directory Structure
[Annotated tree showing key directories and their purpose]
### Entry Points
| Entry Point | Type | Purpose |
|-------------|------|---------|
| ... | ... | ... |
---
## Module Relationships
### Dependency Graph
[Textual or ASCII representation of key module relationships]
### Hub Modules (high import count)
| Module | Imported By | Purpose |
|--------|-------------|---------|
| ... | {count} files | ... |
### Architectural Boundaries
[Description of layer separation, any boundary violations noted]
---
## Core Data Structures
### Primary Models/Types
| Name | Location | Purpose | Key Fields |
|------|----------|---------|------------|
| ... | ... | ... | ... |
### Data Flow Patterns
[How data transforms as it moves through the system]
---
## Key Flow Traces
### Flow 1: {name}
[Step-by-step trace from entry to completion]
### Flow 2: {name}
[...]
---
## Patterns & Conventions
### Naming Conventions
- Files: {pattern}
- Functions: {pattern}
- Variables: {pattern}
### Structural Patterns
[Repeated abstractions, organization patterns]
### Code Idioms
[Error handling, async patterns, state management]
### Testing Approach
[Organization, types, conventions]
---
## Health Assessment
### Complexity Hotspots
| File | Lines | Concern |
|------|-------|---------|
| ... | ... | ... |
### Technical Debt Markers
- TODOs: {count} ([samples])
- FIXMEs: {count} ([samples])
- Other: {count}
### High-Churn Files
| File | Recent Commits | Authors |
|------|----------------|---------|
| ... | ... | ... |
### Test Coverage Signals
[Observations about test presence and organization]
---
## Uncertainties & Questions
[Things the analysis couldn't determine or found ambiguous]
- [ ] {question or uncertainty}
- [ ] ...
---
## Recommended Investigations
Based on this analysis, these areas warrant human attention:
1. **{area}** — {why it's worth investigating}
2. ...
---
## Appendix: Raw Data
<details>
<summary>All Entry Points</summary>
[Full list]
</details>
<details>
<summary>All Hub Modules</summary>
[Full list with import counts]
</details>
<details>
<summary>All Debt Markers</summary>
[Full list with file locations]
</details>
Execution Notes
-
Use tools efficiently
- Glob for file discovery
- Grep for pattern searching
- Read for targeted file analysis
- Task/Explore agent for complex searches
- Bash for git history analysis
-
Manage context window
- Don't read entire large files; sample strategically
- Build understanding incrementally
- Write findings to report as you go (don't hold everything in memory)
-
Handle large codebases
- For repos > 1000 files, focus on src/app/lib directories
- Skip node_modules, vendor, build outputs, generated code
- Sample rather than exhaustively scan when necessary
-
Be honest about limitations
- Flag when you're uncertain
- Note when sampling rather than exhaustive analysis
- Don't invent patterns that aren't clearly there
-
Timestamp and version
- Include git SHA so analysis can be compared to codebase state
- Note analysis mode so reader knows depth level