refactoring
Refactoring patterns - improving code design without changing behavior
SKILL.md
| Name | refactoring |
| Description | Refactoring patterns - improving code design without changing behavior |
name: refactoring description: Systematic code cleanup with MANDATORY verification. All issues must be fixed.
/refactoring [target]
Systematically refactor code. ALL identified issues must be fixed.
No arguments? Describe this skill and stop. Do not execute.
First: Activate Workflow
mkdir -p .claude && echo '{"skill":"refactoring","started":"'$(date -Iseconds)'"}' > .claude/active-workflow.json
Craft Standards (MANDATORY)
Refactor toward code a master craftsperson would be proud of.
The goal is code that looks like it was written by a skilled human engineer, not generated by AI.
AI Antipatterns to ELIMINATE
In addition to standard refactoring, actively hunt and remove:
- Over-abstraction (factories/wrappers used only once → inline them)
- Defensive paranoia (null checks where null is impossible → remove them)
- Comment spam (
// increment counter→ delete it) - Speculative features (config options nobody uses → remove them)
- Wrapper classes that add no value → unwrap them
- Enterprise patterns in simple code → simplify ruthlessly
Human Craft to ACHIEVE
After refactoring, code should have:
- Functions that do exactly one thing
- Names so clear they don't need comments
- No code a senior engineer would delete
- Every abstraction justified by actual use
Test: Would someone reviewing this PR say "why is this here?" If yes, remove it.
⚠️ STRICT REQUIREMENTS - NO JUDGMENT CALLS
You MUST check for and FIX all of these issues. Not "consider" - FIX:
- FUNCTIONS > 30 LINES - Split them. No exceptions.
- FILES > 300 LINES - Split into focused modules. Create thin re-export index if needed.
- COMPLEXITY > 10 - Cyclomatic complexity too high. Flatten with early returns, extract helpers.
- VAGUE NAMES - Rename data/result/temp/item/info to meaningful names.
- DUPLICATE CODE - Extract to shared function. Run
lens dedupeto find cross-file duplications. - CROSS-FILE DUPLICATION - Same function in multiple files → extract to utils/.
- DEEP NESTING - Flatten with early returns.
- MAGIC NUMBERS/STRINGS - Extract to named constants.
- MISSING ERROR HANDLING - Add it.
- GOD FILES - Split files with multiple concerns.
FORBIDDEN (Phase will FAIL if detected):
- Saying "could be improved" without fixing
- Skipping issues because they're "minor"
- Suggesting future refactorings instead of doing them
- Leaving any identified issue unfixed
- Tests failing after refactoring
Process
Step 0: Load Expert Guidance
Before starting, read these canon skills and apply their principles throughout:
Always load (base brain — all 10):
canon/clarity/SUMMARY.mdcanon/pragmatism/SUMMARY.mdcanon/simplicity/SUMMARY.mdcanon/composition/SUMMARY.mdcanon/distributed/SUMMARY.mdcanon/data-first/SUMMARY.mdcanon/correctness/SUMMARY.mdcanon/algorithms/SUMMARY.mdcanon/abstraction/SUMMARY.mdcanon/optimization/SUMMARY.md
Then load (domain-specific):
11. canon/design-patterns/SUMMARY.md
12. canon/refactoring/SKILL.md
Auto-detect domain canon (check files, load matches):
| Check | If found, also read |
|---|---|
*.ts or *.js files in target | canon/javascript/typescript/SUMMARY.md, canon/javascript/js-safety/SUMMARY.md, canon/javascript/js-perf/SUMMARY.md, canon/javascript/js-internals/SUMMARY.md, canon/javascript/functional/SUMMARY.md |
angular.json in project root | canon/angular/angular-arch/SUMMARY.md, canon/angular/angular-core/SUMMARY.md, canon/angular/angular-perf/SUMMARY.md, canon/angular/rxjs/SUMMARY.md |
package.json contains "react" | canon/javascript/react-state/SUMMARY.md, canon/javascript/react-test/SUMMARY.md, canon/javascript/reactivity/SUMMARY.md |
pom.xml or build.gradle in project | canon/java/SUMMARY.md |
*.py files in target | canon/python/python-advanced/SUMMARY.md, canon/python/python-idioms/SUMMARY.md, canon/python/python-patterns/SUMMARY.md, canon/python/python-protocols/SUMMARY.md |
*.cs files or *.csproj in project | canon/csharp/csharp-depth/SUMMARY.md, canon/csharp/type-systems/SUMMARY.md, canon/csharp/async/SUMMARY.md |
.tsx, .jsx, or HTML template files | canon/ui-ux/components/SUMMARY.md, canon/ui-ux/usability/SUMMARY.md, canon/ui-ux/tokens/SUMMARY.md |
d3 in package.json or imports | canon/visualization/d3/SUMMARY.md, canon/visualization/charts/SUMMARY.md, canon/visualization/dashboards/SUMMARY.md |
| SQL files or ORM imports | canon/database/sql/SUMMARY.md, canon/database/sql-perf/SUMMARY.md |
| Auth, tokens, secrets, encryption | canon/security/security-mindset/SUMMARY.md, canon/security/owasp/SUMMARY.md, canon/security/web-security/SUMMARY.md |
If a skill file doesn't exist (not installed in this project), skip it and continue.
List loaded experts in EXPERTS_LOADED. Tag each fix with (via [expert-skill]) showing which expert drove it.
Step 0b: Check Known Pitfalls
Read canon/pitfalls/SKILL.md if it exists. Apply its patterns as you refactor:
- Code Quality Traps → actively hunt for these patterns (dead exports, unused imports, redundant verification reads)
- Logic Traps → check for these bug patterns during refactoring (TOCTOU, missing validation)
- AI-Generated Antipatterns → look for single-use helpers to inline, JSDoc restating function names, impossible null checks, empty catch blocks
If the file doesn't exist, skip and continue.
Step 1: Identify Issues
- Identify Issues - Find all code quality problems
- Fix Each One - Use Edit tool to fix
- Run Tests - Verify behavior preserved
- Report - Document what was fixed
REQUIRED Output Format
## Refactoring: [target]
ISSUES_IDENTIFIED:
- [file:line] [issue type] [description]
- [file:line] [issue type] [description]
REFACTORED:
- [file:line] [issue type] - FIXED: [what was done] (via [expert-skill])
- [file:line] [issue type] - FIXED: [what was done] (via [expert-skill])
ISSUES_REMAINING: 0 (must be zero)
REFACTOR_COUNT: N
TESTS_PASS: yes
EXPERTS_LOADED: [list of skill names actually read]
REFACTORING_COMPLETE
Evidence Checklists (MANDATORY)
After refactoring, produce three evidence checklists. Write each to .claude/evidence/ (create directory if needed).
Checklist 4a: Name Sufficiency
Review EVERY exported function and constant. Write to .claude/evidence/refactor-4a.md:
# Evidence: Refactor 4a — Name Sufficiency
| Location | Item | Verdict | Reasoning |
|----------|------|---------|-----------|
| src/foo.ts:barFunction | Name describes behavior | PASS | Name clearly indicates what it does |
| src/baz.ts:processData | Vague name | FAIL | 'processData' says nothing about what processing occurs |
Checklist 4b: Single Responsibility
Review EVERY exported function. Write to .claude/evidence/refactor-4b.md:
# Evidence: Refactor 4b — Single Responsibility
| Location | Item | Verdict | Reasoning |
|----------|------|---------|-----------|
| src/foo.ts:createUser | Does one thing | PASS | Only creates user record |
| src/bar.ts:handleRequest | Multiple concerns | FAIL | Validates, transforms, saves, and logs |
Checklist 4c: Magic Values
Review for magic numbers and strings. Write to .claude/evidence/refactor-4c.md:
# Evidence: Refactor 4c — Magic Values
| Location | Item | Verdict | Reasoning |
|----------|------|---------|-----------|
| src/config.ts:10 | Timeout 5000 | PASS | Named constant TIMEOUT_MS |
| src/auth.ts:24 | Literal "admin" | FAIL | Role string should be a constant |
Every row must have a PASS or FAIL verdict. No blanks. The machine gate validates row counts against codebase counters — incomplete checklists block the pipeline.
Pipeline Constraints
When running as part of a pipeline (called by /build or /improve):
SCOPE CONSTRAINT: Only modify code directly related to issues you identify. Do not refactor, rename, or restructure code that was not flagged as an issue.
COMPLEXITY BUDGET: After your changes, the codebase must have the same or fewer: files, exported functions, types/interfaces, and total lines. If your fix adds lines, find lines elsewhere to remove. Net-zero or net-negative. EXCEPTION: Security fixes are exempt.
NO SILENT FAILURES: Do not change a throw/crash to a log-and-continue. Fail-fast on misconfiguration is always correct.
Validation (Phase will FAIL if violated)
- ISSUES_REMAINING > 0
- TESTS_PASS: no
- Issues identified but not in REFACTORED section
- Any file > 300 lines after refactoring
- Any function with cyclomatic complexity > 10 after refactoring
- Evidence checklists missing or incomplete
🛑 MANDATORY STOP
After refactoring:
- DO NOT proceed to next phase
- DO NOT continue with "let me also..."
Your turn ends here. Output REFACTORING_COMPLETE and STOP.