Specialist Unused Code Cleaner
Comprehensive agent designed for detects, removes, unused, code. Includes structured workflows, validation checks, and reusable patterns for development tools.
Specialist Unused Code Cleaner
A static analysis specialist that safely identifies and removes dead code across multiple programming languages, using dependency graphs, entry point mapping, and safety checks to ensure no functional code is accidentally removed.
When to Use This Agent
Choose Specialist Unused Code Cleaner when:
- Codebase has accumulated dead code from feature removals or refactors
- Reducing bundle size by removing unused exports and modules
- Cleaning up after feature flag removals or deprecated feature sunset
- Preparing for major refactors by eliminating unused code paths first
- Conducting periodic codebase hygiene sweeps
Consider alternatives when:
- Refactoring live code (use Refactoring Specialist Strategist)
- Simplifying complex but actively-used functions (use Code Simplifier Consultant)
- Removing unused dependencies from package.json (use Specialist Dependency Ally)
Quick Start
# .claude/agents/specialist-unused-code-cleaner.yml name: Specialist Unused Code Cleaner description: Safely detect and remove dead code model: claude-sonnet tools: - Read - Edit - Bash - Glob - Grep
Example invocation:
claude "Scan the src/ directory for unused exports, functions, and components, then safely remove them with a report of what was deleted and why"
Core Concepts
Dead Code Detection Strategy
| Detection Method | Finds | Misses |
|---|---|---|
| Static import analysis | Unused exports, imports | Dynamic imports, reflection |
| Tree shaking report | Unused modules in bundle | Server-side code, test-only code |
| Reference counting | Functions never called | Callbacks, event handlers |
| Type narrowing | Unreachable branches | Runtime-dependent branches |
| Coverage analysis | Code never executed in tests | Code only used in production |
Safe Removal Workflow
## Dead Code Analysis Report ### Phase 1: Entry Point Mapping - Application entry: src/index.ts - API routes: src/app/api/**/route.ts (23 routes) - Page components: src/app/**/page.tsx (15 pages) - Exports: src/lib/index.ts (public API) - Scripts: scripts/*.ts (5 scripts) - Tests: **/*.test.ts (excluded from dead code) ### Phase 2: Dependency Graph Construction - Total modules: 342 - Reachable from entry points: 298 - Potentially unused: 44 modules ### Phase 3: Safety Checks - Dynamic imports: 8 modules loaded via dynamic import() - String references: 3 modules referenced by name in configs - Event handlers: 12 functions registered as event callbacks - After safety checks: 31 confirmed dead modules ### Phase 4: Removal Plan | File | Type | Confidence | Reason | |------|------|-----------|--------| | src/utils/legacyAuth.ts | Module | High | No imports after auth migration | | src/components/OldHeader.tsx | Component | High | Replaced by NewHeader | | src/services/v1Api.ts | Module | Medium | Only imported in deleted tests |
Detection Tools
# TypeScript unused exports npx ts-prune --project tsconfig.json # JavaScript unused files npx unimported # Unused dependencies in package.json npx depcheck # Webpack bundle unused modules npx webpack --json | npx webpack-bundle-analyzer # ESLint unused variables and imports npx eslint --rule 'no-unused-vars: error' src/
Configuration
| Parameter | Description | Default |
|---|---|---|
entry_points | Application entry points to trace from | Auto-detect |
confidence_threshold | Minimum confidence to remove (high, medium, low) | high |
exclude_patterns | Patterns to exclude from analysis | ["**/*.test.*", "**/*.d.ts"] |
check_dynamic_imports | Scan for dynamic import() references | true |
check_string_references | Scan for string-based module references | true |
dry_run | Report findings without deleting | true |
Best Practices
-
Map all entry points before analyzing reachability. Dead code analysis traces from entry points through the dependency graph. Missing an entry point causes the entire reachable tree from that entry to be falsely flagged as dead. Identify: application entry files, route handlers, exported library APIs, CLI scripts, worker files, and configuration files that reference modules by string.
-
Check for dynamic references before removing "unused" code. Static analysis cannot detect
require(variableName),import(pathFromConfig), dependency injection containers, reflection-based access, and event handler registrations in configuration files. Search for string occurrences of the function/module name across the entire codebase, including JSON, YAML, and environment files, before confirming code as dead. -
Remove dead code in small, reviewable batches. Deleting 50 files in a single PR makes review impractical and rollback granularity poor. Group removals by feature or module: "Remove legacy auth system" (8 files), "Remove v1 API endpoints" (12 files). Each batch should be independently deployable and revertable. Deploy and monitor each batch before proceeding to the next.
-
Keep a removal log with rationale for each deletion. Document why each piece of code was identified as dead. "Replaced by NewHeader in PR #423 on 2025-08-15. No remaining imports." This log helps if someone later asks "what happened to OldHeader?" and provides evidence for the removal decision if code needs to be restored.
-
Run the full test suite and build after each removal batch. Dead code analysis can misidentify code that is used by tests, build scripts, or configuration processing. Run
npm test,npm run build, andnpm run lintafter each removal to catch false positives. If tests fail, investigate whether the test was testing dead code (remove the test too) or the code was not actually dead (restore it).
Common Issues
Removing "unused" code breaks features accessed via dynamic routing. Framework-specific patterns like Next.js page routes, Express route files loaded via glob, and plugin systems that discover modules at runtime are invisible to static analysis. These modules have no explicit import statements but are very much in use. Understand the framework's module discovery mechanism and exclude those patterns from dead code analysis.
Exported types and interfaces are flagged as unused. TypeScript types used only in .d.ts files, type-only imports (import type { Foo }), or generic constraints may not appear in the JavaScript output, causing tools to flag them as unused. Configure analysis tools to understand TypeScript type references. Use ts-prune with --ignore 'used in type' to filter type-only references. Only remove types that are genuinely not referenced anywhere.
Code that appears unused is actually part of a public API consumed by external packages. Libraries and shared packages export functions for consumers in other repositories. Those exports have no internal callers but are very much in use externally. Mark public API exports explicitly (in an index.ts barrel file or a publicApi config) and exclude them from dead code analysis. For internal packages in a monorepo, trace usage across all packages, not just the current one.
Reviews
No reviews yet. Be the first to review this template!
Similar Templates
API Endpoint Builder
Agent that scaffolds complete REST API endpoints with controller, service, route, types, and tests. Supports Express, Fastify, and NestJS.
Documentation Auto-Generator
Agent that reads your codebase and generates comprehensive documentation including API docs, architecture guides, and setup instructions.
Ai Ethics Advisor Partner
All-in-one agent covering ethics, responsible, development, specialist. Includes structured workflows, validation checks, and reusable patterns for ai specialists.