clean-codebase
Remove dead code, unused imports, fix lint warnings, and normalize formatting across a codebase without changing business logic or architecture. Use when lint warnings have piled up during rapid development, unused imports and variables clutter files, dead code paths were never removed, formatting is inconsistent, or static analysis tools report fixable hygiene issues.
Best use case
clean-codebase is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Remove dead code, unused imports, fix lint warnings, and normalize formatting across a codebase without changing business logic or architecture. Use when lint warnings have piled up during rapid development, unused imports and variables clutter files, dead code paths were never removed, formatting is inconsistent, or static analysis tools report fixable hygiene issues.
Teams using clean-codebase should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/clean-codebase/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How clean-codebase Compares
| Feature / Agent | clean-codebase | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Remove dead code, unused imports, fix lint warnings, and normalize formatting across a codebase without changing business logic or architecture. Use when lint warnings have piled up during rapid development, unused imports and variables clutter files, dead code paths were never removed, formatting is inconsistent, or static analysis tools report fixable hygiene issues.
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
SKILL.md Source
# clean-codebase
## When to Use
Use this skill when a codebase has accumulated hygiene debt:
- Lint warnings have piled up during rapid development
- Unused imports and variables clutter files
- Dead code paths exist but were never removed
- Formatting is inconsistent across files
- Static analysis tools report fixable issues
**Do NOT use** for architectural refactoring, bug fixes, or business logic changes. This skill focuses purely on hygiene and automated cleanup.
## Inputs
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `codebase_path` | string | Yes | Absolute path to codebase root |
| `language` | string | Yes | Primary language (js, python, r, rust, etc.) |
| `cleanup_mode` | enum | No | `safe` (default) or `aggressive` |
| `run_tests` | boolean | No | Run test suite after cleanup (default: true) |
| `backup` | boolean | No | Create backup before deletion (default: true) |
## Procedure
### Step 1: Pre-Cleanup Assessment
Measure the current state to quantify improvements later.
```bash
# Count lint warnings by severity
lint_tool --format json > lint_before.json
# Count lines of code
cloc . --json > cloc_before.json
# List unused symbols (language-dependent)
# JavaScript/TypeScript: ts-prune or depcheck
# Python: vulture
# R: lintr unused function checks
```
**Got:** Baseline metrics saved to `lint_before.json` and `cloc_before.json`
**If fail:** If lint tool not found, skip automated fixes and focus on manual review
### Step 2: Fix Automated Lint Warnings
Apply safe automated fixes (spacing, quotes, semicolons, trailing whitespace).
**JavaScript/TypeScript**:
```bash
eslint --fix .
prettier --write .
```
**Python**:
```bash
black .
isort .
ruff check --fix .
```
**R**:
```bash
Rscript -e "styler::style_dir('.')"
```
**Rust**:
```bash
cargo fmt
cargo clippy --fix --allow-dirty
```
**Got:** All safe lint warnings resolved; files formatted consistently
**If fail:** If automated fixes introduce test failures, revert changes and escalate
### Step 3: Identify Dead Code Paths
Use static analysis to find unreferenced functions, unused variables, and orphaned files.
**JavaScript/TypeScript**:
```bash
ts-prune | tee dead_code.txt
depcheck | tee unused_deps.txt
```
**Python**:
```bash
vulture . | tee dead_code.txt
```
**R**:
```bash
Rscript -e "lintr::lint_dir('.', linters = lintr::unused_function_linter())"
```
**General approach**:
1. Grep for function definitions
2. Grep for function calls
3. Report functions defined but never called
**Got:** `dead_code.txt` lists unused functions, variables, and files
**If fail:** If static analysis tool unavailable, manually review recent commit history for orphaned code
### Step 4: Remove Unused Imports
Clean up import blocks by removing references to packages never used.
**JavaScript**:
```bash
eslint --fix --rule 'no-unused-vars: error'
```
**Python**:
```bash
autoflake --remove-all-unused-imports --in-place --recursive .
```
**R**:
```bash
# Manual review: grep for library() calls, check if package used
grep -r "library(" . | cut -d: -f2 | sort | uniq
```
**Got:** All unused import statements removed
**If fail:** If removing imports breaks build, they were used indirectly — restore and document
### Step 5: Remove Dead Code (Mode-Dependent)
**Safe Mode** (default):
- Only remove code explicitly marked as deprecated
- Remove commented-out code blocks (if >10 lines and >6 months old)
- Remove TODO comments referencing completed issues
**Aggressive Mode** (opt-in):
- Remove all functions identified as unused in Step 3
- Remove private methods with zero references
- Remove feature flags for deprecated features
For each candidate deletion:
1. Verify zero references in codebase
2. Check git history for recent activity (skip if modified in last 30 days)
3. Remove code and add entry to `CLEANUP_LOG.md`
**Got:** Dead code removed; `CLEANUP_LOG.md` documents all deletions
**If fail:** If uncertain whether code is truly dead, move to `archive/` directory instead
### Step 6: Normalize Formatting
Ensure consistent formatting across all files (even if not caught by linters).
1. Normalize line endings (LF vs CRLF)
2. Ensure single newline at end of file
3. Remove trailing whitespace
4. Normalize indentation (spaces vs tabs, indent width)
```bash
# Example: Fix line endings and trailing whitespace
find . -type f -name "*.js" -exec sed -i 's/\r$//' {} +
find . -type f -name "*.js" -exec sed -i 's/[[:space:]]*$//' {} +
```
**Got:** All files follow consistent formatting conventions
**If fail:** If sed breaks binary files, skip and document
### Step 7: Run Tests
Validate that cleanup didn't break functionality.
```bash
# Language-specific test command
npm test # JavaScript
pytest # Python
R CMD check # R
cargo test # Rust
```
**Got:** All tests pass (or same failures as before cleanup)
**If fail:** Revert changes incrementally to identify breaking change, then escalate
### Step 8: Generate Cleanup Report
Document all changes for review.
```markdown
# Codebase Cleanup Report
**Date**: YYYY-MM-DD
**Mode**: safe | aggressive
**Language**: <language>
## Metrics
| Metric | Before | After | Change |
|--------|--------|-------|--------|
| Lint warnings | X | Y | -Z |
| Lines of code | A | B | -C |
| Unused imports | D | 0 | -D |
| Dead functions | E | F | -G |
## Changes Applied
1. Fixed X lint warnings (automated)
2. Removed Y unused imports
3. Deleted Z lines of dead code (see CLEANUP_LOG.md)
4. Normalized formatting across W files
## Escalations
- [Issue description requiring human review]
- [Uncertain deletion moved to archive/]
## Validation
- [x] All tests pass
- [x] Backup created: backup_YYYYMMDD/
- [x] CLEANUP_LOG.md updated
```
**Got:** Report saved to `CLEANUP_REPORT.md` in project root
**If fail:** (N/A — generate report regardless of outcome)
## Validation Checklist
After cleanup:
- [ ] All tests pass (or same failures as before)
- [ ] No new lint warnings introduced
- [ ] Backup created before any deletions
- [ ] `CLEANUP_LOG.md` documents all removed code
- [ ] Cleanup report generated with metrics
- [ ] Git diff reviewed for unexpected changes
- [ ] CI pipeline passes
## Pitfalls
1. **Removing Code Still Used via Reflection**: Static analysis misses dynamic calls (e.g., `eval()`, metaprogramming). Always check git history.
2. **Breaking Implicit Dependencies**: Removing imports that were used by dependencies. Run tests after every import removal.
3. **Deleting Feature Flags for Active Features**: Even if unused in current branch, feature flags may be active in other environments. Check deployment configs.
4. **Over-Aggressive Formatting**: Tools like `black` or `prettier` may reformat code in ways that trigger unnecessary diffs. Configure tools to match project style.
5. **Ignoring Test Coverage**: Cannot safely clean codebases without tests. If coverage is low, escalate for test additions first.
6. **Not Backing Up**: Always create `backup_YYYYMMDD/` directory before deleting anything, even if using git.
7. **Wrong R binary on hybrid systems**: On WSL or Docker, `Rscript` may resolve to a cross-platform wrapper instead of native R. Check with `which Rscript && Rscript --version`. Prefer the native R binary (e.g., `/usr/local/bin/Rscript` on Linux/WSL) for reliability. See [Setting Up Your Environment](../../guides/setting-up-your-environment.md) for R path configuration.
## Related Skills
- [tidy-project-structure](../tidy-project-structure/SKILL.md) — Organize directory layout, update READMEs
- [repair-broken-references](../repair-broken-references/SKILL.md) — Fix dead links and imports
- [escalate-issues](../escalate-issues/SKILL.md) — Route complex problems to specialists
- [r-packages/run-r-cmd-check](../../r-packages/run-r-cmd-check/SKILL.md) — Run full R package checks
- [devops/dependency-audit](../../devops/dependency-audit/SKILL.md) — Check for outdated dependenciesRelated Skills
security-audit-codebase
Perform a security audit of a codebase checking for exposed secrets, vulnerable dependencies, injection vulnerabilities, insecure configurations, and OWASP Top 10 issues. Use before publishing or deploying a project, for periodic security reviews, after adding authentication or API integration, before open-sourcing a private repository, or when preparing for a security compliance audit.
review-codebase
Multi-phase deep codebase review with severity ratings and structured output. Covers architecture, security, code quality, and UX/accessibility in a single coordinated pass. Produces a prioritized findings table suitable for direct conversion to GitHub issues via the create-github-issues skill.
analyze-codebase-workflow
Analyze an arbitrary codebase to auto-detect workflows, data pipelines, and file dependencies using putior's put_auto() engine. Produces an annotation plan that maps detected I/O patterns to source files across 30+ supported languages with 902 auto-detection patterns. Use when onboarding onto an unfamiliar codebase to understand data flow, starting putior integration in a project without existing annotations, auditing a project's data pipeline before documentation, or preparing an annotation plan before running annotate-source-files.
analyze-codebase-for-mcp
Analyze an arbitrary codebase to identify functions, APIs, and data sources suitable for exposure as MCP tools, producing a tool specification document. Use when planning an MCP server for an existing project, auditing a codebase before wrapping it as an AI-accessible tool surface, comparing what a codebase can do versus what is already exposed via MCP, or generating a tool spec to hand off to scaffold-mcp-server.
skill-name-here
One to three sentences describing what this skill accomplishes, followed by key activation triggers. This field is the primary mechanism agents use to decide whether to activate the skill — it is read during discovery before the full body is loaded. Start with a verb. Include the most important "when to use" conditions inline. Max 1024 characters.
write-vignette
Create R package vignettes using R Markdown or Quarto. Covers vignette setup, YAML configuration, code chunk options, building and testing, and CRAN requirements for vignettes. Use when adding a Getting Started tutorial, documenting complex workflows spanning multiple functions, creating domain-specific guides, or when CRAN submission requires user-facing documentation beyond function help pages.
write-validation-documentation
Write IQ/OQ/PQ validation documentation for computerized systems in regulated environments. Covers protocols, reports, test scripts, deviation handling, and approval workflows. Use when validating R or other software for regulated use, preparing for a regulatory audit, documenting qualification of computing environments, or creating and updating validation protocols and reports for new or re-qualified systems.
write-testthat-tests
Write comprehensive testthat (edition 3) tests for R package functions. Covers test organization, expectations, fixtures, mocking, snapshot tests, parameterized tests, and achieving high coverage. Use when adding tests for new package functions, increasing test coverage for existing code, writing regression tests for bug fixes, or setting up test infrastructure for a package that lacks it.
write-standard-operating-procedure
Write a GxP-compliant Standard Operating Procedure (SOP). Covers regulatory SOP template structure (purpose, scope, definitions, responsibilities, procedure, references, revision history), approval workflow design, periodic review scheduling, and operational procedures for system use. Use when a new validated system requires operational procedures, when existing informal procedures need formalisation, when an audit finding cites missing procedures, when a change control triggers SOP updates, or when periodic review identifies outdated procedural content.
write-roxygen-docs
Write roxygen2 documentation for R package functions, datasets, and classes. Covers all standard tags, cross-references, examples, and generating NAMESPACE entries. Follows tidyverse documentation style. Use when adding documentation to new exported functions, documenting internal helpers or datasets, documenting S3/S4/R6 classes and methods, or fixing documentation-related R CMD check notes.
write-incident-runbook
Create structured incident runbooks with diagnostic steps, resolution procedures, escalation paths, and communication templates for effective incident response. Use when documenting response procedures for recurring alerts, standardizing incident response across an on-call rotation, reducing MTTR with clear diagnostic steps, creating training materials for new team members, or linking alert annotations directly to resolution procedures.
write-helm-chart
Create production-ready Helm charts for Kubernetes application deployment with templating, values management, chart dependencies, hooks, and testing. Covers chart structure, Go template syntax, values.yaml design, chart repositories, versioning, and best practices for maintainable and reusable charts. Use when packaging a Kubernetes application for repeatable deployments, parameterizing manifests for multiple environments, managing complex multi-component applications with dependencies, or standardizing deployment practices with versioned rollback capability across teams.