refactor-clean
Skill47 starsChanged 4 months agoMITView on GitHub
Use when code has grown complex, duplicated, or cluttered — clean up structure and remove dead code without changing observable behavior
10 other projects use a version of this.
Adopted by
Most recently taken up by
- dzhng/skillstheir own version, first seen Oct 4, 2026
- dzhng/jevgreptheir own version, first seen Oct 2, 2026
- dzhng/duet-agenttheir own version, first seen Oct 2, 2026
- PatriotAgenticLLC/better_claude_skillztheir own version, first seen Jul 1, 2026
- vasuag09/harness-claudetheir own version, first seen Jun 10, 2026
- QuentinHsu/skillstheir own version, first seen May 10, 2026
Used with
Projects with it also use audit-choices, close-spec and 10 more.
Other files people use alongside this one.
Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
dzhngSkillaudit-choices
Audit the choices an implementing agent made, not its diff — a pure decision audit that traces the session's history into a choices ledger, changes no code, and never blocks an unsupervised run. Working code still embeds architecture the user never chose; surface it because future work inherits it. Use when the user wants to review the decisions the AI made on their behalf, before merging or committing AI-implemented work, when integrating a delegated subagent's pass, or when a fix "works" but might be a point fix.
Also in 3 projects that use this
dzhngSkillclose-spec
When a spec under specs/<feature>/ is done shipping (a write-spec build, or any planned task that produced a spec), archive it to specs/done/ and rewrite it from a build-plan into a durable rationale — the why, the principles, the invariants — pointing back to the real code for the how. Use when implementation has landed and the plan no longer matches what shipped, or the user says a feature/spec is finished. Pairs with [write-spec](../write-spec/SKILL.md) (the plan this closes) and [review](../review/SKILL.md) (run before closing).
Also in 3 projects that use this
LucasMatuszewskiSkillaudit-agents
Audit and maintain agent configuration files (.claude/agents, AGENTS.md, CLAUDE.md, agent-memory). Checks for duplicates, outdated info, naming conflicts, wrong technical facts, and files over 200 lines. Fixes all issues and commits.
Also in 3 projects that use this
Halcyon666Skillwrite-skills
Creates high-quality Agent Skills (SKILL.md files) that follow the open Agent Skills specification. Use when asked to create a skill, write a SKILL.md, package agent instructions, build a reusable capability, or turn a workflow into a shareable skill. Produces spec-compliant, concise, well-structured skills optimized for agent discovery and execution.
Also in 3 projects that use this
isLinXuSkilleval-skills
AI Agent Skill unit testing framework. A framework-agnostic toolkit for discovering, scaffolding, selecting, evaluating, and reporting on AI skills. Use this skill to assess skill quality before production, compare candidate skills on the same benchmark, enforce quality gates in CI/CD, and generate human-readable evaluation reports.
Also in 3 projects that use this
TrecekSkillaudit-tests
Audit the test suite for useless tests, consolidation opportunities, over-mocking, weak assertions, and other test quality issues. Use when user says "audit tests", "audit test suite", "review tests", or "test quality check". Generates an improvement plan in temp/ with explanations for each proposed change.
Also in 3 projects that use this
- +6 more from dzhng
Other versions10 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 10
- dzhng/jevgrep★ 2.3ksame name
- dzhng/skills★ 978same name
- julianromli/ai-skills★ 192same name
- dzhng/duet-agent★ 46same name
- jiten-singh-shahi/salesforce-claude-code★ 17same name
- PatriotAgenticLLC/better_claude_skillz★ 3same name
- peopleforrester/claude-dotfiles★ 3same name
- QuentinHsu/skills★ 2same name
- vasuag09/harness-claude★ 2same name
- TheKREATORS/my-claude-skills★ 1same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository111 other files it gives its agents.
- AGENTS.mdAGENTS.md
- COPILOT-INSTRUCTIONS.mdCopilot instructions
- .github/copilot-instructions.mdCopilot instructions
- ai-visibilitySkill
- content-strategySkill
- seoSkill
- actions-debuggingSkill
- agentic-engineeringSkill
- autopilot-patternsSkill
- background-agentSkill
- context-primeSkill
- copilot-memorySkill
- cross-session-memorySkill
- ecosystem-intakeSkill
- fleet-parallelSkill
- github-code-searchSkill
- github-codespaces-efficiencySkill
- github-issue-triageSkill
- github-pr-workflowSkill
- ide-switchingSkill
- knowledge-curatorSkill
- mcp-builderSkill
- mcp-ecosystemSkill
- multi-model-strategySkill
- plan-mode-masterySkill
- scope-guardSkill
- session-managementSkill
- stack-detectorSkill
- sub-agent-sandboxingSkill
- task-intake-routerSkill
- team-plannerSkill
- token-cost-optimizerSkill
- api-and-interface-designSkill
- code-reviewSkill
- context-engineeringSkill
- cpp-debuggingSkill
- deprecation-and-migrationSkill
- diagnoseSkill
- fix-build-errorsSkill
- fix-github-issueSkill
- implementSkill
- improve-codebase-architectureSkill
- nestjs-prismaSkill
- nextjs-prismaSkill
- performance-optimizationSkill
- pr-multi-perspective-reviewSkill
- prototypeSkill
- react-vitestSkill
- receiving-code-reviewSkill
- reviewSkill
- skill-creatorSkill
- source-driven-developmentSkill
- spec-driven-developmentSkill
- systematic-debuggingSkill
- tdd-workflowSkill
- zoom-outSkill
- add-to-changelogSkill
- api-documentationSkill
- architecture-decisionsSkill
- code-tourSkill
- The first 60 shown.
The file
We split this skill into the rules it gives an agent
8 rules. 0 are common, 6 are distinctive, and 2 are very specific to this project.
0
Common
Most of the 10 edited versions we read keep these.
6
Distinctive
This author's own choices. Worth a look.
2
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 17
After a rapid prototype that needs production-quality cleanup
- Distinctive: line 22
All tests passing before starting
- Distinctive: line 62
Before touching code, decide on the transformation:
- Distinctive: line 156
No verification that the same tests pass before and after refactoring
- Very specific: line 170
Use explore agent to understand call graphs before renaming or moving functions
- Very specific: line 171
Use grep to find all callers before changing a function signature
- Distinctive: line 172
If tests are missing, write them first — refactoring without tests is gambling
- Distinctive: line 173
Commit after every successful small refactoring — you can always squash later
“Common” is measured: kept by at least 6 in 10 of the 10 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Refactor & Clean Code
When to Use
- Code is correct but hard to read, modify, or extend
- Duplicated logic exists across multiple files
- Functions or classes have grown too large
- Preparing code for a new feature that requires structural changes
- After a rapid prototype that needs production-quality cleanup
Prerequisites
- Existing tests that cover the code to refactor (add tests first if missing)
- All tests passing before starting
- Code committed so you can revert if needed
Workflow
1. Identify Code Smells
# Find long files (likely doing too much)
Get-ChildItem -Recurse -Include *.ts,*.js,*.py,*.go | Where-Object { (Get-Content $_.FullName | Measure-Object -Line).Lines -gt 300 } | Select-Object FullName, @{N='Lines';E={(Get-Content $_.FullName | Measure-Object -Line).Lines}}
# Find duplicated string patterns
grep -rn "pattern-you-suspect-is-duplicated" src/ --include="*.ts"
# Find functions with too many parameters (>4 is a smell)
grep -n "function.*,.*,.*,.*," src/**/*.tsCommon smells to look for:
- Long functions (>40 lines) — extract smaller functions
- Duplicate code — extract shared utility
- Deep nesting (>3 levels) — use early returns or extract
- God objects — split into focused classes/modules
- Primitive obsession — introduce domain types
- Feature envy — move logic to the class that owns the data
2. Establish a Safety Net
# Run existing tests and record baseline
npm test 2>&1 | Tee-Object -Variable baseline
echo $baseline | Select-Object -Last 5
# If coverage is low, write characterization tests first
npm test -- --coverage --collectCoverageFrom="src/module-to-refactor.ts"3. Plan the Refactoring
Before touching code, decide on the transformation:
- Extract Function — pull a block into a named function
- Extract Module — move related functions to a new file
- Rename — improve names for clarity
- Inline — remove unnecessary indirection
- Replace Conditional with Polymorphism — use strategy pattern
- Introduce Parameter Object — group related parameters
4. Make Small, Incremental Changes
Each change should be:
- A single refactoring operation
- Followed by running tests
- Committed if tests pass
# After each refactoring step
npm test 2>&1 | Select-Object -Last 10
# If tests break, revert and try a smaller step
git checkout -- src/module-to-refactor.ts5. Verify Behavior is Preserved
# Full test suite must still pass
npm test
# Compare coverage — it should not decrease
npm test -- --coverageExamples
Extract Repeated Logic
// BEFORE: duplicated validation in multiple handlers
function createUser(data) {
if (!data.email || !data.email.includes('@')) throw new Error('Invalid email');
// ... create logic
}
function updateUser(data) {
if (!data.email || !data.email.includes('@')) throw new Error('Invalid email');
// ... update logic
}
// AFTER: extracted to a shared validator
function validateEmail(email: string): void {
if (!email || !email.includes('@')) throw new Error('Invalid email');
}
function createUser(data) { validateEmail(data.email); /* ... */ }
function updateUser(data) { validateEmail(data.email); /* ... */ }Flatten Deep Nesting with Early Returns
// BEFORE
function process(input) {
if (input) {
if (input.isValid) {
if (input.data.length > 0) {
return transform(input.data);
}
}
}
return null;
}
// AFTER
function process(input) {
if (!input || !input.isValid || input.data.length === 0) return null;
return transform(input.data);
}Common Rationalizations
| Rationalization | Reality |
| "I'm not sure what this code does, but it looks unused" | If you're not sure, don't remove it. Use git blame to understand the context first. (Chesterton's Fence) |
| "I'll add a feature while refactoring" | Separate refactoring from feature work. Mixing the two makes debugging impossible. |
| "Tests still pass, so the refactor is correct" | Tests must exist before refactoring to have any meaning. If not, write them first. |
| "TypeScript isn't warning, so it's safe to delete" | Dynamic imports, reflection, and external references are invisible to the type system. |
Red Flags
- Refactoring commit contains feature changes
- Dead code removed without any tests
- Type errors suppressed with
// @ts-ignoreoranytypes - No verification that the same tests pass before and after refactoring
- Complex code left with "clean up later" TODO and no action
Verification
npm testpasses identically before and after the refactor- Removed code confirmed as unused (
grep -rnor IDE reference search) - Complexity metrics improved (reduced function length, nesting depth)
- Refactor commit contains no feature changes (commit message:
refactor:) - PR describes the motivation for the refactor (why this code was cleaned up)
Tips
- Never refactor and add features in the same commit — keep them separate
- Use
exploreagent to understand call graphs before renaming or moving functions - Use
grepto find all callers before changing a function signature - If tests are missing, write them first — refactoring without tests is gambling
- Commit after every successful small refactoring — you can always squash later
- The best refactoring is deleting code: look for dead code with
grepand remove it
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

