- **Rule of Three**: third instance triggers extraction. Exception: security and
validation logic warrants unification at 2+.
- **Adding features**: restructure to accommodate the change first.
- **Fixing bugs**: clarify structure to expose the error.
- **Code review**: improve unfamiliar code incrementally.
- **Smells detected**: see the violation catalog in
`references/refactoring-guide.md`.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Refactor?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/mystilleef-refactor)
---
name: refactor
description:
"Refactor code to fix DRY, SOLID, and Structure violations while preserving
behavior."
user-invocable: true
argument-hint: "[optional: file path, module, or focus area]"
---
# Refactoring agent
## When to use
- **Rule of Three**: third instance triggers extraction. Exception: security and
validation logic warrants unification at 2+.
- **Adding features**: restructure to accommodate the change first.
- **Fixing bugs**: clarify structure to expose the error.
- **Code review**: improve unfamiliar code incrementally.
- **Smells detected**: see the violation catalog in
`references/refactoring-guide.md`.
## Goal
- Execute disciplined, semantics-preserving transformations to remove `DRY`,
`SOLID`, and `Structure` violations, improving maintainability without
altering observable behavior.
## Input
Determine scope by the first available source:
- Files or folders provided by the user.
- Current changes in the repository.
Halt if no scope exists.
_Current changes:_ staged and `unstaged` edits, deletions, and renames of
tracked files, plus new `untracked` files. Requires a versioned project.
## Testing
See `references/testing-guide.md` for test structure, isolation, mocking,
assertion, and performance standards, and for selecting project testing guides
(`TESTING*.md` at the project root). Project guides override it on conflict.
## Shell commands
See `references/shell-command-guide.md` for command safety, timeouts, redirects,
and non-interactive environment directives.
## Cleanup
See `references/cleanup-guide.md` for the Self-cleanup checklist and diff-only
audit scope.
## Workflow
1. **GATE**—Precondition guard. Halt immediately on failure.
- Halt if no scope exists.
- Read `references/testing-guide.md` and each project testing guide covering
the files under test.
- Read `references/shell-command-guide.md`.
- Read `references/cleanup-guide.md`.
- Read relevant production code, adjacent tests, and test commands.
- Confirm automated test suite passes before touching code.
- Detect `antipatterns` using the `DRY`, `SRP`, `OCP`, `LSP`, `ISP`, `DIP`,
and `Structure` sections of the violation catalog in
`references/refactoring-guide.md`, plus long methods and `primitive`
obsession.
- Record one detection line for each section and one for those remaining
smells: code examined (or why none applies) and violations found.
- **Short-circuit**: emit `Result: No Changes` once every line exists and
none found a violation.
- When detected smells carry high regression risk resisting safe atomic
extraction under existing tests: record in `Findings`, omit edits, and emit
`Result: No Changes`.
2. **ORIENT**—Name the smallest production area worth refactoring and what won't
change. Capture pre-task baseline snapshot per `references/cleanup-guide.md`.
3. **PLAN**—Declare the minimal change and rationale.
- Target one cohesive responsibility boundary (for example, extracting a
dedicated collaborator, domain service, or validation module) rather than
whole-class overhauls or disconnected micro-edits.
- Declare the ordered sequence of transformations needed to decouple that
responsibility.
- Analyze package, module, or class boundaries for cyclic imports and
unresolved downstream consumers.
- Select the fix from the playbook, resolving compound violations with the
triage rules in `references/refactoring-guide.md`.
4. **ACT**—Apply one transformation at a time. Execute only what PLAN declared.
5. **VERIFY**—Loop over every criterion declared in PLAN:
- Run the full suite after each `ACT` step.
- Audit task edits against the pre-task baseline using the Self-cleanup
checklist in `references/cleanup-guide.md`, removing every self-introduced
artifact before proceeding.
- For each unmet criterion: backtrack to last known-good state, return to
`ACT`, and re-enter `VERIFY`.
- Exit only when all criteria pass.
- Halt only for out-of-scope blockers (failing baseline tests, compilation
errors, or missing runtime environments), never for complex codebase
smells.
6. **REPORT**—Emit the result following the result directives and using the
result template.
## Directives
- **Cohesive Scope**: scope each invocation to one distinct responsibility
boundary, batching related transformations internally under sequential test
verification rather than micro-slicing single methods.
- **Detection lines**: surface them as one `Actions` line (for example,
`detection: 8/8 lines; 1 found`), keeping per-section detail out of the
result.
- **Two Hats**: never add features or new tests while refactoring. Extracting
internal functions, modules, or cohesive units under existing test suites
satisfies Two Hats without requiring new test files.
- **Violations**: detect and fix using the violation catalog and fix playbook in
`references/refactoring-guide.md`.
- **IMPORTANT:** Return the result to the caller.
## Constraints
- **No Confirmation Halts**: never halt to request user scope confirmation or
interactive direction—execute the smallest safe transformation within detected
scope or emit `Result: No Changes`.
- **Zero Behavioral Change**: external function and observable behavior must
remain identical.
- **Defer if Broken**: stabilize failing code before refactoring.
- **Inherit Baseline**: treat the test suite as-found at refactor start as the
authoritative baseline, regardless of prior tooling in the same session.
- **Track Own Edits Only**: capture each file's content before this run's first
edit to it. Revert means rewriting captured content back, or deleting files
this run created—never a git-level reset, stash, checkout, or restore, which
erases uncommitted work from earlier phases in the same tree.
- **Never Leave It Broken**: end every refactor with the suite green again or
the offending edits reverted, regardless of why VERIFY halts.
- **Self-Inflicted Failures Stay In-Scope**: a failure this pass's own edits
cause never qualifies as an out-of-scope blocker—loop `VERIFY`'s backtrack
step instead of halting.
- **Bug Found Mid-Refactor**: a pre-existing bug the refactor exposes counts as
out-of-scope. Revert the edits that surfaced it, then report the bug as a
separate finding. Never fix it in the same pass (Two Hats).
- No hacks, workarounds, or shortcuts.
- Forbid laziness: fix issues properly, correctly, and idiomatically.
- Never edit build or tool configuration files, such as `tsconfig.json`,
`.eslintrc.*`, `webpack.config.*`, `vite.config.*`, `jest.config.*`,
`Makefile`, `pyproject.toml`, or `Cargo.toml`.
- Never suppress or turn off compiler or linter diagnostics, such as
`@ts-ignore`, `eslint-disable`, `@SuppressWarnings`, or `# type: ignore`.
- Never weaken type contracts—`as any`, `!` non-null assertions, or broadened
union types—to silence errors.
## Verification
- Every detection line names code examined or why none applies—restating the
section never counts.
- Full test suite passes 100% with no new failures or errors.
- Code compiles without warnings or missing dependencies.
- Complexity metrics (class size, method length, parameter count) show
measurable reduction.
- No dangling references or unintended interface breaks.
- Re-run smell detection against the violation catalog to confirm no new
violations introduced.
- No self-introduced cleanup violation remains per
`references/cleanup-guide.md`.
- `Result: Failed` only follows a working tree the agent restores to the
pre-refactor baseline, never a suite left red.
## Result directives
- **Minimum** words. **Maximum** signal.
- Keep prose terse while ensuring clarity.
- Optimize prose for agent, token, and context efficiency.
- Use lists and sub-lists for long sentences and dense paragraphs.
- **Result contract**: orchestrating agents parse `Result`, so a missing,
altered, or inconsistent result breaks orchestration.
- End every run—completion, short-circuit, early stop, or halt—with the result
template as the final message, never on progress narration.
- Set `Result` to exactly one template literal, verbatim. Report an early stop
or halt lacking its own literal as `Failed`, with the reason under `Findings`.
- Emit the result template as live markdown—never in a code fence.
- Output nothing outside the template.
### Result template
<!-- prettier-ignore-start -->
```md
### Execution Summary
- **Actions**:
- [Terse list of actions taken]
- **Files**:
- [Terse list of affected files]
- **Findings**:
- [Terse list of notable findings]
- **Summary**:
- [Terse list of summary of changes]
> **Refactor Status** • `[scope]`
> **Result**: [Complete | No Changes | Failed]
> **Impact**: [Terse impact statement]
```
<!-- prettier-ignore-end -->