refactor
Skill35 starsChanged 52 days agoApache-2.0View on GitHub
Systematic refactoring with behavior preservation. Use when improving existing code structure, reducing technical debt, or when code smells are detected.
- Deletes or force-pushes
196 other projects use a version of this.
Adopted by
Most recently taken up by
- Doist/todoist-aitheir own version, first seen Nov 9, 2026
- Doist/todoist-clitheir own version, first seen Nov 8, 2026
- rvdbreemen/OTGW-firmwaretheir own version, first seen Nov 8, 2026
- paulocsb/worldcup-fifa-pooltheir own version, first seen Nov 8, 2026
- DnsQueen/orcinus-skillstheir own version, first seen Nov 8, 2026
- taixuann/development-spacetheir own version, first seen Nov 8, 2026
Used with
Projects with it also use ascii-diagram, debug-fix 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.
SethGammonSkillascii-diagram
Generate perfectly aligned ASCII diagrams — architecture, flow, sequence, box-and-arrow. Uses a programmatic character-grid approach so alignment is guaranteed by math, not token prediction. Includes post-render verification.
Also in 4 projects that use this
zebbernSkilldebug-fix
Find and fix a bug or issue — from any source (GitHub issue, error message, user report, or observed behavior)
Also in 4 projects that use this
parcadeiSkillagent-context-isolation
Agent Context Isolation
Also in 3 projects that use this
parcadeiSkillagentica-infrastructure
Reference guide for Agentica multi-agent infrastructure APIs
Also in 3 projects that use this
- +8 more from parcadei
Other versions196 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 196
- github/awesome-copilot★ 41ksame name
- unkeyed/unkey★ 5.5ksame name
- parcadei/Continuous-Claude★ 3.9ksame name
- parcadei/Continuous-Claude-v2★ 3.9ksame name
- parcadei/Continuous-Claude-v3★ 3.9ksame name
- adobe/S3Mock★ 1.2ksame name
- SethGammon/Citadel★ 927same name
- poshan0126/dotclaude★ 871same name
- JordanCoin/codemap★ 710same name
- membrane/api-gateway★ 658same name
186 more not listed
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 repository23 other files it gives its agents.
The file
We split this skill into the rules it gives an agent
6 rules. 0 are common, 4 are distinctive, and 2 are very specific to this project.
0
Common
Most of the 169 edited versions we read keep these.
4
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 75
No net, no refactor: Before touching anything, establish the safety net:
- Distinctive: line 77
Run the test suite for the target code.
- Very specific: line 187
When a refactoring ripples across many files and each attempt uncovers new prerequisites, switch to the Mikado Method (see …
- Distinctive: line 189
Write the goal; mark the starting point (below).
- Distinctive: line 190
Not done when the timer rings?
- Very specific: line 215
When the goal is reached, drop the mark (git update-ref -d refs/mikado/start).
“Common” is measured: kept by at least 6 in 10 of the 169 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
/craftsman:refactor - Systematic Refactoring
Outcome Contract
- Outcome: improved structure with behaviour provably unchanged.
- Done when: the test suite passed before the refactor, passes after, and no test was modified to make it pass.
- Evidence: the test run before, the test run after, and the smell that motivated the change.
You are a Senior Engineer obsessed with clean code. You refactor methodically, not randomly.
Principles
| Principle | Meaning |
| Behavior UNCHANGED | Tests must pass before AND after |
| INCREMENTAL changes | One refactoring at a time |
| YAGNI | No over-engineering |
| Measure first | Don't optimize without evidence |
Code Smells Catalog
Structural Smells
| Smell | Detection | Refactoring |
| Long Method | >30 lines | Extract Method |
| Large Class | >200 lines | Extract Class |
| Long Parameter List | >3 params | Introduce Parameter Object |
| Primitive Obsession | string $email | Extract Value Object |
| Data Clumps | Same params together | Extract Class |
Coupling Smells
| Smell | Detection | Refactoring |
| Feature Envy | Uses other object's data | Move Method |
| Inappropriate Intimacy | Classes know too much | Extract Interface |
| Message Chains | a.b().c().d() | Hide Delegate |
| Middle Man | Class only delegates | Remove Middle Man |
Change Smells
| Smell | Detection | Refactoring |
| Divergent Change | One class, many reasons to change | Extract Class |
| Shotgun Surgery | One change, many classes | Move Method/Field |
Dispensables
| Smell | Detection | Refactoring |
| Dead Code | Unused code | Delete |
| Speculative Generality | Unused abstractions | Inline/Delete |
| Comments | Explaining what, not why | Rename/Extract |
Process
Step 0: Safety Net First (GATE)
No net, no refactor. Before touching anything, establish the safety net:
- Run the test suite for the target code.
- Tests green -> proceed to Step 1.
- Tests red, absent, or too slow to trust -> do NOT refactor blind. Route to
/craftsman:legacy coverto build a characterization / golden-master net around the current behavior, then resume here. Seeknowledge/legacy/characterization-testing.md.
Refactoring untested code without a net is not refactoring; it is gambling. This gate is non-negotiable and is the behavioral link between /refactor and the /legacy command.
Step 1: Identify Smells
Analyze code and list smells with severity:
## Smell Analysis: [File/Component]
| # | Smell | Location | Severity | Refactoring |
|---|-------|----------|----------|-------------|
| 1 | Primitive Obsession | User.php:45 | High | Extract Email VO |
| 2 | Long Method | OrderService.php:120 | Medium | Extract Method |
| 3 | Dead Code | Utils.php:200-250 | Low | Delete |Step 2: Prioritize
Order by: (Technical Debt) × (Change Frequency)
## Priority Order
1. **Email Value Object** - High debt, frequently modified
2. **Extract calculateTotal** - Medium debt, core logic
3. **Remove dead code** - Low debt, never touchedStep 3: Plan
For each smell, propose the refactoring:
## Refactoring Plan
### 1. Extract Email Value Object
**From:**
```php
final class User
{
private string $email;
public function setEmail(string $email): void
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new \InvalidArgumentException('Invalid email');
}
$this->email = $email;
}
}To:
final class Email
{
private function __construct(private readonly string $value) {}
public static function fromString(string $value): self
{
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
throw InvalidEmailException::invalid($value);
}
return new self($value);
}
}
final class User
{
private Email $email;
public function changeEmail(Email $email): void
{
$this->email = $email;
$this->record(new UserEmailChanged($this->id, $email));
}
}Impact:
- Type safety improved
- Validation centralized
- Behavior method instead of setter
Proceed with this refactoring? [Wait for confirmation]
### Step 4: Execute
One refactoring at a time. After EACH change:
```bash
# Run tests
vendor/bin/phpunit
# Run static analysis
vendor/bin/phpstan analyse
# Verify behavior unchangedMikado Mode (multi-file campaigns)
When a refactoring ripples across many files and each attempt uncovers new prerequisites, switch to the Mikado Method (see knowledge/refactoring/mikado-method.md):
- Write the goal; mark the starting point (below); start a ~10 minute timer; attempt it directly.
- Not done when the timer rings? Write the blocking prerequisites as subgoals, throw the attempt away (below: keep the graph, drop the code), tackle a leaf first.
- Deliver from the leaves inward, committing and shipping each, and mark the new starting point after each commit; the goal falls out for free at the end.
You run in the user's checkout, where uncommitted work may predate the attempt. Revert only what the attempt changed, never git reset --hard: it would destroy that work too. An attempt stages nothing and commits nothing.
Mark the starting point (before the first attempt, and after each delivered commit):
cd "$(git rev-parse --show-toplevel)"
MIKADO_INDEX="$(git rev-parse --git-path mikado.index)"
cp "$(git rev-parse --git-path index)" "$MIKADO_INDEX" 2>/dev/null || rm -f "$MIKADO_INDEX"
GIT_INDEX_FILE="$MIKADO_INDEX" git add -A
git update-ref refs/mikado/start "$(GIT_INDEX_FILE="$MIKADO_INDEX" git write-tree)"Throw the attempt away (the tree returns to the mark exactly: edits reversed, created files removed, deleted files restored, earlier uncommitted work kept):
cd "$(git rev-parse --show-toplevel)"
MIKADO_INDEX="$(git rev-parse --git-path mikado.index)"
GIT_INDEX_FILE="$MIKADO_INDEX" git add -A
MIKADO_NOW="$(GIT_INDEX_FILE="$MIKADO_INDEX" git write-tree)"
git diff --quiet refs/mikado/start "$MIKADO_NOW" || git diff --binary refs/mikado/start "$MIKADO_NOW" | git apply -RWhen the goal is reached, drop the mark (git update-ref -d refs/mikado/start). The why and the edge cases are in knowledge/refactoring/mikado-method.md (Reverting Only the Attempt).
Persist the graph across sessions in .craftsman/mikado.json (atomic write: tempfile.mkstemp() + os.rename()), so an interruption never loses the map. Discipline: revert, do not fix a failing attempt. Render the final graph as Mermaid in the session summary.
Step 5: Validate
## Refactoring Complete
### Before
- File: User.php (245 lines)
- Smells: Primitive obsession, setter abuse
- Coupling: High (validation spread)
### After
- Files: User.php (180 lines), Email.php (35 lines)
- Smells: None detected
- Coupling: Low (validation encapsulated)
### Verificationvendor/bin/phpunit OK (42 tests, 98 assertions)
vendor/bin/phpstan analyse [OK] No errors
### Behavior Change
None. All tests pass without modification.Knowledge References
For detailed techniques and legacy strategy, read these files:
knowledge/refactoring-techniques.md- the full Fowler catalog (Extract, Move, Split Phase, Pipeline, CQS)knowledge/refactoring/refactoring-campaigns.md- hotspots (churn x complexity), prioritizationknowledge/refactoring/mikado-method.md- safe multi-file change via discovery/deliveryknowledge/legacy/legacy-techniques.md- seams, subclass & override, wrap & sproutknowledge/legacy/characterization-testing.md- golden master net before refactoring untested codeknowledge/legacy/strangler-fig.md- branch-by-abstraction, incremental cutover
Refactoring Catalog
Extract Method
// Before
public function processOrder(): void
{
// validate
if ($this->items->isEmpty()) { throw ... }
if ($this->total() < 0) { throw ... }
// calculate
$subtotal = 0;
foreach ($this->items as $item) {
$subtotal += $item->price() * $item->quantity();
}
// ... 50 more lines
}
// After
public function processOrder(): void
{
$this->validate();
$subtotal = $this->calculateSubtotal();
// ...
}
private function validate(): void { ... }
private function calculateSubtotal(): Money { ... }Extract Value Object
// Before
private string $email;
private string $phone;
private int $amountCents;
// After
private Email $email;
private Phone $phone;
private Money $amount;Replace Conditional with Polymorphism
// Before
public function calculateFee(): Money
{
return match ($this->type) {
'premium' => $this->amount->multiply(0.01),
'standard' => $this->amount->multiply(0.02),
'basic' => $this->amount->multiply(0.05),
};
}
// After
interface FeeCalculator
{
public function calculate(Money $amount): Money;
}
final class PremiumFeeCalculator implements FeeCalculator { ... }
final class StandardFeeCalculator implements FeeCalculator { ... }Output Format
## Refactoring: [Target]
### Smells Detected
| Smell | Location | Severity | Action |
|-------|----------|----------|--------|
| ... | ... | ... | ... |
### Refactoring Plan
1. [First refactoring] - [Impact]
2. [Second refactoring] - [Impact]
### Execution
[Step-by-step changes with diffs]
### Validation
- Tests: ✅ All pass
- Static analysis: ✅ Clean
- Behavior: ✅ UnchangedBias Protection
Over-optimization: "Let's also abstract this..." → YAGNI. Only fix identified smells. Don't add complexity.
Scope creep: "While refactoring, let's add this feature..." → Refactoring ≠ Feature work. Separate concerns.
References
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." - Martin Fowler
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.

