| name | codebase-analyzer |
| description | Analyze codebases to find patterns and anti-patterns, identify code duplication, suggest optimizations, analyze dependencies, and perform automated code reviews |
| allowed-tools | ["Read","Write","Edit","Bash","Glob","Grep","Task"] |
Codebase Analyzer
Expert skill for comprehensive codebase analysis and quality assessment. Specializes in pattern detection, code duplication analysis, performance optimization, dependency auditing, and automated code review.
Core Capabilities
1. Pattern Detection
- Design patterns (Singleton, Factory, Observer, etc.)
- React patterns (HOC, Render Props, Hooks, Compound Components)
- Anti-patterns (God components, Prop drilling, Premature optimization)
- Architectural patterns (MVC, MVVM, Flux, Clean Architecture)
- Code smells (Long methods, large classes, duplicated code)
2. Code Duplication Analysis
- Exact code duplication
- Similar code blocks (clone detection)
- Copy-paste programming detection
- Opportunities for abstraction
- Refactoring suggestions
- DRY (Don't Repeat Yourself) violations
3. Optimization Opportunities
- Performance bottlenecks
- Unnecessary re-renders (React)
- Bundle size optimization
- Memory leaks
- Inefficient algorithms
- Database query optimization
- Network request optimization
4. Dependency Analysis
- Unused dependencies
- Outdated packages
- Security vulnerabilities
- Circular dependencies
- Dependency graph visualization
- Import/export analysis
- Package size impact
5. Code Quality Metrics
- Cyclomatic complexity
- Code coverage
- Maintainability index
- Technical debt assessment
- Lines of code (LOC)
- Comment ratio
- Test-to-code ratio
6. Automated Code Review
- Style consistency
- Best practices adherence
- Accessibility issues
- Type safety problems
- Security vulnerabilities
- Performance concerns
- Documentation quality
Workflow
Phase 1: Initial Analysis
-
Codebase Discovery
- Scan directory structure
- Identify project type (React, Vue, Node.js, etc.)
- Detect frameworks and libraries
- Map file organization
-
Metric Collection
- Count files, lines, components
- Measure code complexity
- Check test coverage
- Analyze bundle size
-
Quick Health Check
- TypeScript errors
- Linting issues
- Test failures
- Build warnings
Phase 2: Deep Analysis
-
Pattern Detection
- Identify common patterns
- Detect anti-patterns
- Find inconsistencies
- Note architectural issues
-
Duplication Analysis
- Find duplicate code
- Identify similar structures
- Suggest abstractions
- Calculate duplication percentage
-
Dependency Audit
- Check for vulnerabilities
- Find unused dependencies
- Identify outdated packages
- Analyze bundle impact
-
Performance Analysis
- Identify bottlenecks
- Find unnecessary renders
- Check bundle sizes
- Analyze load times
Phase 3: Reporting & Recommendations
-
Generate Report
- Executive summary
- Detailed findings
- Metrics and charts
- Priority rankings
-
Provide Recommendations
- Quick wins
- High-impact improvements
- Long-term refactoring
- Best practices
-
Create Action Plan
- Prioritized tasks
- Effort estimates
- Implementation guides
- Success metrics
Analysis Techniques
Pattern Detection Scripts
Find Large Components
import { readFileSync, readdirSync, statSync } from 'fs'
import { join } from 'path'
interface ComponentMetrics {
file: string
lines: number
complexity: number
hooks: number
props: number
}
function analyzeComponent(filePath: string): ComponentMetrics {
const content = readFileSync(filePath, 'utf-8')
const lines = content.split('\n').length
const hookMatches = content.match(/use[A-Z]\w+/g) || []
const hooks = new Set(hookMatches).size
const complexity =
(content.match(/if|else|switch|case|for|while|&&|\|\|/g) || []).length
const propsMatch = content.match(/interface \w+Props \{([^}]+)\}/)
const props = propsMatch
? propsMatch[].().( l.()).
:
{ : filePath, lines, complexity, hooks, props }
}
(): [] {
: [] = []
() {
files = (currentDir)
( file files) {
filePath = (currentDir, file)
stat = (filePath)
(stat.()) {
(!file.() && !file.()) {
(filePath)
}
} (file.()) {
metrics = (filePath)
(metrics. > || metrics. > ) {
results.(metrics)
}
}
}
}
(dir)
results.( b. - a.)
}
largeComponents = ()
.(largeComponents)
Detect Code Duplication
npx jscpd src/ --min-lines 5 --min-tokens 50 --format markdown -o duplication-report.md
{
"threshold": 3,
"reporters": ["html", "markdown", "console"],
"ignore": [
"**/node_modules/**",
"**/dist/**",
"**/*.test.ts",
"**/*.test.tsx"
],
"format": ["typescript", "javascript", "jsx", "tsx"],
"minLines": 5,
"minTokens": 50
}
Find Unused Exports
npx ts-prune --error
npx depcheck
Analyze Bundle Size
npm run build -- --analyze
npx source-map-explorer 'dist/**/*.js'
Complexity Analysis
Cyclomatic Complexity
npx complexity-report src/ --format json -o complexity.json
import { ESLint } from 'eslint'
async function analyzeComplexity() {
const eslint = new ESLint({
overrideConfig: {
rules: {
'complexity': ['error', { max: 10 }],
'max-lines-per-function': ['error', { max: 50 }],
'max-depth': ['error', { max: 4 }],
'max-params': ['error', { max: 4 }],
},
},
})
const results = await eslint.lintFiles(['src/**/*.{ts,tsx}'])
const highComplexity = results
.filter(r => r.messages.some(m => m.ruleId === 'complexity'))
return highComplexity
}
Dependency Analysis
Security Audit
npm audit --json > audit-report.json
npm audit fix
npx snyk test
npm audit --audit-level=moderate
Unused Dependencies
npx depcheck --json > unused-deps.json
npx unimported
npm list -g --depth=0
Outdated Packages
npm outdated
npx npm-check-updates -i
npx npm-check-updates -u && npm install
Analyze Import Costs
import { visualizer } from 'rollup-plugin-visualizer'
plugins: [
visualizer({
filename: './dist/stats.html',
open: true,
gzipSize: true,
brotliSize: true,
}),
]
Performance Analysis
React Performance
import { readFileSync } from 'fs'
import { glob } from 'glob'
interface RenderIssue {
file: string
issue: string
line: number
}
function findRenderIssues(): RenderIssue[] {
const issues: RenderIssue[] = []
const files = glob.sync('src/**/*.{tsx,jsx}')
for (const file of files) {
const content = readFileSync(file, 'utf-8')
const lines = content.split('\n')
lines.forEach((line, idx) => {
if (/={.*=>/.test(line)) {
issues.push({
file,
issue: 'Inline function in JSX (causes re-render)',
line: idx + 1,
})
}
if (line.includes('useEffect')) {
nextLines = lines.(idx, idx + ).()
(!.(nextLines)) {
issues.({
file,
: ,
: idx + ,
})
}
}
(.(line)) {
hasProps = content.()
hasMemo = content.() || content.()
(hasProps && !hasMemo && content.(). > ) {
issues.({
file,
: ,
: idx + ,
})
}
}
})
}
issues
}
Bundle Analysis Report
import { exec } from 'child_process'
import { promisify } from 'util'
const execAsync = promisify(exec)
async function analyzeBundleSize() {
await execAsync('npm run build')
const { stdout } = await execAsync(
'npx source-map-explorer dist/**/*.js --json'
)
const analysis = JSON.parse(stdout)
const dependencies = Object.entries(analysis.files)
.map(([name, size]) => ({ name, size: size as number }))
.sort((a, b) => b.size - a.size)
.slice(0, 20)
console.table(dependencies)
const recommendations = []
for (const dep dependencies) {
(dep. > ) {
recommendations.({
: dep.,
: (dep. / ).() + ,
: ,
})
}
}
{ dependencies, recommendations }
}
Analysis Reports
Comprehensive Health Report
import { exec } from 'child_process'
import { promisify } from 'util'
import { readFileSync } from 'fs'
import { glob } from 'glob'
const execAsync = promisify(exec)
interface HealthReport {
overview: {
totalFiles: number
totalLines: number
components: number
tests: number
coverage: number
}
quality: {
typeErrors: number
lintErrors: number
complexity: number
duplication: number
}
dependencies: {
total: number
outdated: number
vulnerable: number
unused: number
}
performance: {
bundleSize: number
renderIssues: number
memoryLeaks: number
}
: <{
:
: | |
:
:
}>
}
(): <> {
files = glob.()
totalFiles = files.
totalLines = files.( {
acc + (file, ).().
}, )
components = glob.().(
!f.() && !f.()
).
tests = glob.().
{ : coverageOutput } = ()
coverageMatch = coverageOutput.()
coverage = coverageMatch ? (coverageMatch[]) :
{ : tscOutput } = ()
typeErrors = (tscOutput.() || []).
{ : eslintOutput } = ()
eslintResults = .(eslintOutput || )
lintErrors = eslintResults.(
acc + r.,
)
{ : auditOutput } = ()
audit = .(auditOutput || )
vulnerable = audit.?.?. ||
{ : outdatedOutput } = ()
outdated = .(.(outdatedOutput || )).
{ : depcheckOutput } = ()
depcheck = .(depcheckOutput || )
unused = depcheck.?. ||
()
{ : sizeOutput } = ()
bundleSize = (sizeOutput.()[])
recommendations = []
(coverage < ) {
recommendations.({
: ,
: ,
: ,
: ,
})
}
(typeErrors > ) {
recommendations.({
: ,
: ,
: ,
: ,
})
}
(vulnerable > ) {
recommendations.({
: ,
: ,
: ,
: ,
})
}
(unused > ) {
recommendations.({
: ,
: ,
: ,
: ,
})
}
(bundleSize > ) {
recommendations.({
: ,
: ,
: ,
: ,
})
}
{
: {
totalFiles,
totalLines,
components,
tests,
coverage,
},
: {
typeErrors,
lintErrors,
: ,
: ,
},
: {
: .(
.((, )). || {}
).,
outdated,
vulnerable,
unused,
},
: {
bundleSize,
: ,
: ,
},
recommendations,
}
}
().( {
.()
.()
.(report.)
.()
.(report.)
.()
.(report.)
.()
.(report.)
.()
.(report.)
})
Best Practices for Analysis
1. Regular Analysis
- Run analysis weekly or per sprint
- Integrate into CI/CD pipeline
- Track metrics over time
- Set quality gates
2. Prioritize Findings
- High: Security, critical bugs, major performance issues
- Medium: Code quality, maintainability, moderate optimizations
- Low: Style issues, minor refactoring, nice-to-haves
3. Actionable Recommendations
- Provide specific solutions
- Include code examples
- Estimate effort required
- Link to documentation
4. Continuous Improvement
- Track progress on metrics
- Celebrate improvements
- Learn from regressions
- Update standards
Tools & Commands
Static Analysis
npx tsc --noEmit
npx eslint src/ --ext .ts,.tsx
npx complexity-report src/
npx jscpd src/
Dependency Analysis
npm audit
npx snyk test
npx depcheck
npm outdated
npx npm-check-updates
npx license-checker
Performance Analysis
npx webpack-bundle-analyzer dist/stats.json
npx source-map-explorer dist/**/*.js
npm run build -- --profile
Code Quality
npm test -- --coverage
npx stryker run
npx plato -r -d report src/
Anti-Patterns to Detect
React Anti-Patterns
- Prop Drilling: Passing props through many levels
- God Components: Components doing too much
- Inline Functions: Creating new functions on every render
- Missing Keys: Lists without proper key props
- Index as Key: Using array index as key
- Direct State Mutation: Mutating state directly
- Missing Dependencies: useEffect without proper deps
- Unnecessary Re-renders: Components re-rendering too often
General Anti-Patterns
- Magic Numbers: Hard-coded values without explanation
- Copy-Paste Code: Duplicated code blocks
- Long Functions: Functions over 50 lines
- Deep Nesting: More than 4 levels of nesting
- Too Many Parameters: Functions with 5+ parameters
- God Objects: Classes/objects doing everything
- Tight Coupling: High dependencies between modules
- Missing Error Handling: No try-catch or error boundaries
When to Use This Skill
Activate this skill when you need to:
- Analyze codebase quality
- Find performance bottlenecks
- Detect code duplication
- Audit dependencies
- Review architectural patterns
- Identify technical debt
- Assess code complexity
- Find security vulnerabilities
- Optimize bundle size
- Review code before release
- Onboard to new codebase
- Prepare for refactoring
Output Format
When analyzing codebases, provide:
- Executive Summary: Key findings and metrics
- Detailed Analysis: In-depth findings by category
- Metrics Dashboard: Visual representation of health
- Recommendations: Prioritized action items
- Code Examples: Before/after refactoring suggestions
- Implementation Plan: Steps to address issues
Always provide actionable, specific recommendations with clear priorities and estimated effort.