Help us improve
Share bugs, ideas, or general feedback.
From claude-swe-workflows
Iteratively scans code for DRY, dead code, naming, and complexity issues, implements fixes, verifies with QA, and commits atomically until no improvements remain.
npx claudepluginhub chrisallenlane/claude-swe-workflows --plugin claude-swe-workflowsHow this skill is triggered — by the user, by Claude, or both
Slash command
/claude-swe-workflows:refactoropusThe summary Claude sees in its skill listing — used to decide when to auto-load this skill
Autonomous refactoring workflow that iteratively improves code quality within the existing architecture, always preferring the least aggressive change available, until no further opportunities exist.
Autonomous comprehensive refactoring through a three-phase pipeline: tactical cleanup, architectural restructuring, then final tactical pass.
Orchestrates a multi-step refactoring pipeline: analyzes code quality, plans improvements, optionally writes tests, implements changes, and reviews results. Routes simple refactors to a lighter workflow.
Refactors existing code for guideline compliance and testability using 4 parallel analysis agents. Use after /optimus:init to align code or before /optimus:unit-test to remove testability barriers.
Share bugs, ideas, or general feedback.
Autonomous refactoring workflow that iteratively improves code quality within the existing architecture, always preferring the least aggressive change available, until no further opportunities exist.
Clarity is the goal. Every iteration should make the codebase easier to form a correct mental model of. Red diffs are the strongest signal - less code almost always means clearer code, and every iteration should delete more than it adds. But when reducing lines would hurt comprehensibility, clarity wins.
Err on the side of trying. When uncertain whether a refactoring is worthwhile, attempt it anyway. Git makes failed experiments free - the workflow will revert changes that don't pass QA. Missed opportunities are invisible; failed attempts teach you something. Be bold, knowing that version control provides the safety net.
Work within the existing architecture. This workflow improves code quality - DRY, dead code, naming, complexity - without questioning module boundaries or reorganizing the system. For architectural analysis (noun extraction, module dissolution, blueprint-driven restructuring), use /review-arch instead.
┌─────────────────────────────────────────────────────┐
│ REFACTORING LOOP │
├─────────────────────────────────────────────────────┤
│ 1. Determine scope │
│ 2. Select aggression ceiling │
│ 3. Gather QA instructions │
│ 4. Spawn fresh swe-code-reviewer agent (full scan) │
│ 5. Select least aggressive changes available │
│ 6. If none remain → exit to summary │
│ 7. Spawn SME agent (implement batch) │
│ 8. Spawn QA agent (verify) │
│ ├─ PASS → commit, goto 4 │
│ └─ FAIL → retry (max 3), then abort batch │
│ 9. Completion summary │
│ 10. Update documentation (/tidy-docs) │
└─────────────────────────────────────────────────────┘
Default: Entire codebase.
Boundary: version-controlled files only. The refactoring workflow operates exclusively on files tracked by git. Untracked files and directories must never be modified or deleted — their loss could be irreversible. This boundary is non-negotiable regardless of scope setting.
If user specifies scope: Respect that scope (directory, files, module). Pass scope constraint to all spawned agents.
Ask the user: "How aggressive should refactoring be?"
Present these options:
The workflow still proceeds from least aggressive to more aggressive - this setting determines how far up the ladder to climb before stopping.
Ask the user: "Are there any special verification steps for the QA agent? For example: visual checks, manual testing commands, specific scenarios to validate."
If provided: Pass these instructions to the QA agent on every verification cycle, in addition to standard test suite execution.
Examples of custom QA instructions:
make demo and check that output matches expected behavior"/health endpoint and verify 200 response"./tool --help"If none provided: QA agent runs standard verification (test suite, linters, formatters).
Always make the least aggressive change available, up to the user's chosen ceiling (step 2).
The swe-code-reviewer agent returns recommendations organized by risk level: SAFEST → SAFE → MODERATE → AGGRESSIVE. These aren't gates to pass through sequentially. Instead:
For each iteration:
Spawn fresh swe-code-reviewer agent:
Why full scan every time:
Prompt the agent with:
Scan for ALL refactoring opportunities across all aggression levels.
Scope: [entire codebase | user-specified scope]
Return recommendations organized by risk level (SAFEST → AGGRESSIVE).
Prioritize changes that produce RED diffs (net code reduction) while improving clarity.
Orchestrator selects least aggressive changes:
Set aside user-decision items:
Review recommendations from scan. Group related changes into atomic batches.
Batching criteria:
For each batch, prepare:
Detect appropriate SME and spawn based on primary file type in batch:
swe-sme-golangswe-sme-dockerswe-sme-makefileswe-sme-graphqlswe-sme-ansibleswe-sme-zigswe-sme-typescriptswe-sme-javascriptswe-sme-htmlswe-sme-cssFor languages without a dedicated SME (Python, Rust, etc.): implement directly as orchestrator, following language idioms and project conventions.
For mixed-language batches: split into per-language batches, or implement directly if changes are mechanical (e.g., dead code removal across file types).
Prompt the SME with:
Implement the following refactorings:
[List of specific changes from batch]
These changes should:
- Follow existing project conventions
- Maintain all existing behavior
- Result in net code reduction where possible
Report when complete.
SME implements and reports back.
Spawn qa-engineer agent:
On PASS: Proceed to commit.
On FAIL:
After 3 consecutive failures for a batch:
git checkout -- .)Create atomic commit for successful batch:
git add [specific files modified in this batch]
git diff --staged # verify only intended changes
git commit -m "$(cat <<'EOF'
refactor: [brief description of changes]
[Details of what was refactored and why]
EOF
)"
Commit guidelines:
git add -A)refactor: prefix in commit messageReturn to step 5a with fresh agent instance.
Loop continues until:
When workflow completes, present summary:
## Refactoring Complete
### Statistics
- Commits made: N
- Net lines changed: -XXX (target: negative)
- Batches completed: N
- Batches aborted: N
### Changes by Category
- Dead code removal: N instances
- DRY consolidation: N instances
- [etc.]
### Aborted Batches (if any)
- [Batch description]: [reason for failure]
Then present user-decision items collected across all passes:
Commented-out code: List each location and what the code appears to be (debugging helper, disabled feature, TODO, etc.). Ask the user which, if any, should be deleted. Implement deletions for the items the user selects.
Apparently-unused public APIs: List each symbol and location. Note that these may be consumed by external users of the package. These are informational only — do not offer to delete them.
After the refactoring summary, run the /tidy-docs workflow to bring project documentation up to date. Even tactical refactoring can rename functions, move code between files, and change APIs — documentation that references the old state becomes stale.
Invoke the skill directly:
/tidy-docs
This spawns a doc-maintainer agent that audits all project documentation and fixes issues it finds. Any changes are committed separately from the refactoring commits.
Fresh instances for context management:
swe-code-reviewer agent for each scan passSequential execution:
State to maintain (as orchestrator):
Abort current batch:
Abort entire workflow:
Agent failures:
Do NOT abort for:
/refactor vs /review-arch: /refactor is tactical cleanup within existing architecture (DRY, dead code, naming, complexity). /review-arch is strategic — it questions the architecture and proposes restructuring (advisory; offers to cut tickets). Use /refactor for routine cleanup; use /review-arch when the module structure itself needs rethinking.
/scope → /refactor: For a large refactoring effort, use /scope first to plan the work, then /refactor to execute autonomously.
> /refactor
Scope: entire codebase
How aggressive should refactoring be?
> High (up to MODERATE changes)
Any special QA instructions?
> Run `make test && make lint` after each change
Starting iterative refactoring...
[Pass 1]
Spawning swe-code-reviewer agent for scan...
Found opportunities across levels:
SAFEST: 8 dead code blocks (Prune), 2 lint failures
SAFE: 3 DRY violations
MODERATE: 1 cross-module DRY opportunity
Selecting least aggressive: dead code + lint (SAFEST)
Spawning swe-sme-golang for implementation...
Implementation complete.
Spawning qa-engineer for verification...
All tests pass.
Committed: "refactor: remove dead code and fix lint issues"
[Pass 2]
Spawning swe-code-reviewer agent for scan...
Found opportunities across levels:
SAFEST: (none)
SAFE: 3 DRY violations, 1 single-use wrapper (Prune)
MODERATE: 1 cross-module DRY opportunity
Selecting least aggressive: DRY + prune (SAFE)
Spawning swe-sme-golang for implementation...
Implementation complete.
Spawning qa-engineer for verification...
Test failure: TestParseConfig
Returning to swe-sme-golang for repair (attempt 1/3)...
Repair complete.
Spawning qa-engineer for verification...
All tests pass.
Committed: "refactor: consolidate duplicate parsing logic"
[Pass 3]
Spawning swe-code-reviewer agent for scan...
Found opportunities across levels:
SAFEST: 1 new dead code block exposed by DRY consolidation (Prune)
SAFE: (none)
MODERATE: 1 cross-module DRY opportunity
Selecting least aggressive: dead code (SAFEST)
...
[Passes 4-7...]
[Pass 8]
Spawning swe-code-reviewer agent for scan...
No opportunities found at any level.
## Refactoring Complete
### Statistics
- Commits made: 7
- Net lines changed: -312
- Batches completed: 7
- Batches aborted: 0
### Changes by Category
- Prune (dead code, unused indirection): 11 instances
- DRY consolidation: 5 instances
- Lint fixes: 2 instances
Running /tidy-docs to update documentation...
Spawning doc-maintainer agent...
No documentation changes needed.