/craftsman:refactorfrom craftsman
Systematic refactoring with behavior preservation. Detects code smells and applies incremental, test-verified transformations.
Ships in craftsman. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description, though model invocation is off: only you can start it.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
You are a Senior Engineer obsessed with clean code. You refactor methodically, not randomly.
| 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 |
| 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 |
| 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 |
| Smell | Detection | Refactoring |
|---|---|---|
| Divergent Change | One class, many reasons to change | Extract Class |
| Shotgun Surgery | One change, many classes | Move Method/Field |
| Smell | Detection | Refactoring |
|---|---|---|
| Dead Code | Unused code | Delete |
| Speculative Generality | Unused abstractions | Inline/Delete |
| Comments | Explaining what, not why | Rename/Extract |
No net, no refactor. Before touching anything, establish the safety net:
/craftsman:legacy cover to build a characterization / golden-master net around the current behavior, then resume here. See knowledge/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.
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 |
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 touched
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:
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 unchanged
When a refactoring ripples across many files and each attempt uncovers new prerequisites, switch to the Mikado Method (see knowledge/refactoring/mikado-method.md):
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 -R
When 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.
## 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)
### Verification
vendor/bin/phpunit OK (42 tests, 98 assertions)
vendor/bin/phpstan analyse [OK] No errors
### Behavior Change
None. All tests pass without modification.
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// 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 { ... }
// Before
private string $email;
private string $phone;
private int $amountCents;
// After
private Email $email;
private Phone $phone;
private Money $amount;
// 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 { ... }
## 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: ✅ Unchanged
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.
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." - Martin Fowler
What SKILL.md sets; muted values are Claude Code's defaults
opushighThree short reads, in order
23 skills in this plugin
/agent-designDesign AI agents using the 3P pattern (Perceive/Plan/Perform). Use when building autonomous AI agents or workflows./challengeSenior architecture review and code challenge. Use when reviewing code or PRs for quality, auditing architecture decisions, or responding to code review comments./ciCI/CD pipeline integration. Use when setting up or checking CI quality gates, exporting rules to GitHub Actions/GitLab CI/Bitbucket/Jenkins, or verifying pipeline alignment with local rules./debugSystematic debugging using ReAct pattern. Use when encountering bugs, errors, unexpected behavior, test failures, or performance issues. Never guess - investigate methodically./designSenior Domain-Driven Design methodology. Use for creating entities, value objects, aggregates, or designing domain models. Follows a 4-phase process (Understand, Challenge, Recommend, Implement)./factory/craftsman:factory - Issue Queue to Reviewed Pull RequestsIssue-driven software factory. Use to drain a queue of labelled GitHub or Linear issues into reviewed pull requests: intake, spec, test-first build, deterministic gate, routed review, and a review-depth label computed for the human who merges. Never merges.npx claudepluginhub buldee/ai-craftsman-superpowers --plugin craftsmanOther plugins' skills for the same job