App Analyzer & Optimizer
Systematic codebase analysis and targeted optimization workflow.
Analysis Workflow
Run analysis in this order — each stage informs the next:
1. Inventory → What's actually in this project?
2. Dependencies → What's outdated, unused, or risky?
3. Architecture → How is it structured? Any anti-patterns?
4. Performance → Where are the bottlenecks?
5. Security → What's exposed or vulnerable?
6. Recommendations → Prioritized, actionable fixes
Stage 1: Project Inventory
# Identify stack
cat package.json 2>/dev/null | head -30
cat Cargo.toml 2>/dev/null
cat pyproject.toml 2>/dev/null
cat go.mod 2>/dev/null
# Project size and structure
find . -type f -name "*.ts" -o -name "*.tsx" | grep -v node_modules | wc -l
du -sh node_modules 2>/dev/null
du -sh .next dist build 2>/dev/null
# Framework detection
ls -la | grep -E "next.config|vite.config|tailwind.config"
Inventory Checklist
- Primary language(s) and framework(s)
- Build tool / bundler
- Package manager (npm/pnpm/bun/yarn — check for multiple lockfiles = problem)
- Database and ORM
- Testing setup present?
- CI/CD configured?
Stage 2: Dependency Audit
# Outdated packages
npm outdated
# or
pnpm outdated
# Security vulnerabilities
npm audit
pnpm audit
# Unused dependencies (depcheck)
npx depcheck
# Duplicate dependencies (different versions of same pkg)
npm ls --all 2>&1 | grep -B2 "deduped"
# Bundle size impact analysis
npx bundle-phobia <package-name>
Dependency Red Flags
| Finding | Risk | Action |
|---|---|---|
| Package unmaintained >2 years | Security/compat risk | Find alternative or fork |
| Multiple lockfiles (package-lock + pnpm-lock) | Build inconsistency | Pick one PM, delete others |
| Direct + transitive version mismatch | Subtle bugs | npm dedupe or pin versions |
| Large unused dependency | Bundle bloat | Remove or tree-shake |
| Dependency with known CVE | Security | Update immediately or patch |
Stage 3: Architecture Review
Structural Red Flags
# Find overly large files (potential god objects/modules)
find src -name "*.ts" -o -name "*.tsx" | xargs wc -l | sort -rn | head -10
# Find circular dependencies
npx madge --circular --extensions ts,tsx src/
# Find deeply nested imports (architecture smell)
grep -r "from '\.\./\.\./\.\./\.\./.*'" src/ --include="*.ts*"
Architecture Checklist
- Clear separation: presentation / business logic / data access
- No circular dependencies between modules
- Consistent file/folder naming convention
- No files >500 lines (investigate for SRP violations)
- Shared types/schemas in a single source of truth (not duplicated)
- Environment config centralized (not
process.env.Xscattered everywhere)
Stage 4: Performance Analysis
Frontend (Next.js/React)
# Bundle analysis
ANALYZE=true npm run build
# requires @next/bundle-analyzer configured in next.config.ts
# Check for missing dynamic imports on heavy components
grep -rL "dynamic(" src/components --include="*.tsx" | xargs grep -l "recharts\|monaco-editor\|three"
# Lighthouse CI
npx lighthouse https://your-url.com --view
Performance Checklist
- Images using
next/image(not raw<img>) - Heavy components (charts, editors, 3D) are dynamically imported
- No unnecessary
'use client'on components that could be server components - Fonts loaded via
next/font(not external<link>) - No
fetch()calls without explicit cache strategy - Database queries — check for N+1 patterns
Backend Performance
# Check for N+1 query patterns (look for queries inside loops)
grep -rn "for.*await.*query\|forEach.*await.*find" src/
# Check connection pool configuration
grep -rn "new Pool\|createPool" src/
-- Check for missing indexes on foreign keys
SELECT
c.conrelid::regclass AS table_name,
string_agg(a.attname, ', ') AS columns
FROM pg_constraint c
JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = ANY(c.conkey)
WHERE c.contype = 'f'
AND NOT EXISTS (
SELECT 1 FROM pg_index i
WHERE i.indrelid = c.conrelid AND a.attnum = ANY(i.indkey)
)
GROUP BY c.conrelid;
Stage 5: Security Quick Scan
# Secrets accidentally committed
git log --all --full-history -- "*.env" "*secret*" "*key*"
grep -rn "sk_live\|sk_test\|AKIA\|service_role" src/ --include="*.ts*"
# Check for SQL injection risk (raw string concatenation in queries)
grep -rn "query(\`.*\${" src/ --include="*.ts*"
# Check CORS config
grep -rn "Access-Control-Allow-Origin.*\*" src/
Security Checklist
- No secrets in source code (use
git logto check history too) - No
Access-Control-Allow-Origin: *on authenticated endpoints - All SQL uses parameterized queries (no string concatenation)
- Rate limiting on public/auth endpoints
- Dependencies free of known critical CVEs (
npm audit)
Stage 6: Prioritized Recommendations
Output Format
Present findings in priority order, with effort estimate:
## Critical (Fix Now)
- [ ] **Exposed `service_role` key in client bundle** — Effort: 30min
Move to server-only env var, rotate the key.
## High Priority (This Sprint)
- [ ] **N+1 query in `/api/dashboard`** — Effort: 2hrs
47 sequential queries per page load. Batch with a single JOIN.
- [ ] **3 packages with known CVEs** — Effort: 1hr
`npm audit fix` resolves 2; `lodash` needs manual major version bump.
## Medium Priority (Next Sprint)
- [ ] **142 unused dependencies in package.json** — Effort: 3hrs
Bundle size could drop ~340KB. Run `depcheck`, verify, remove.
## Low Priority (Backlog)
- [ ] **Inconsistent file naming** (camelCase vs kebab-case) — Effort: ongoing
Standardize gradually during normal development.
Prioritization Matrix
Impact ↑
High │ Critical │ High Priority
│ (fix now) │ (this sprint)
├─────────────┼──────────────
Low │ Low Priority│ Medium Priority
│ (backlog) │ (next sprint)
└─────────────┴──────────────→
Low Effort High Effort
Optimization Execution Pattern
When executing fixes (not just reporting):
- One category at a time — don't mix dependency updates with architecture refactors in one pass
- Verify before and after — run build/tests before and after each change
- Smallest safe change first — config changes before code rewrites
- Document what changed and why — update CHANGELOG per the auto-doc-updater skill
# Standard verification loop per change
npm run build && npm run test && npm run lint
Key Rules
- Inventory before judging — understand the actual stack before recommending changes
- Measure, don't assume — use
npm audit,depcheck,madge, bundle analyzer — not guesswork - Prioritize by impact/effort, not by what's most interesting to fix
- Security findings are always "Critical" or "High" — never deprioritize exposed secrets or injection risks
- One category of change per pass — don't bundle unrelated fixes in one diff
- Verify with build+test after every optimization, not just at the end
- N+1 queries and missing indexes are the most common high-impact, low-effort backend wins
- Bundle size wins (dynamic imports, dead code removal) are usually the highest-impact, lowest-risk frontend fixes
- Never silently "optimize" away functionality — flag risky removals for confirmation
- Report findings even when not asked to fix — visibility into technical debt has value on its own