agentleFS
gufrancogufranco/claude-engineering-rules/skills/refactor/SKILL.md

refactor

Skill3 starsChanged 30 days agoMITView on GitHub

Guided refactoring with behavior preservation verification. Identifies candidates (long functions, deep nesting, duplicated logic, god classes), proposes a refactoring plan, executes incrementally with tests between steps, and verifies no behavior change. Use when user says "refactor", "clean up this code", "simplify", "extract", "restructure", "reduce complexity", "split this file", or wants to improve code structure without changing behavior. For new features, use /plan; for bug fixes, use /investigate; for code review, use /review.

196 other projects use a version of this.

Adopted by

Most recently taken up by

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.
  • SethGammonSkill

    ascii-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

  • zebbernSkill

    debug-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

  • parcadeiSkill

    agent-context-isolation

    Agent Context Isolation

    Also in 3 projects that use this

  • parcadeiSkill

    agentica-infrastructure

    Reference guide for Agentica multi-agent infrastructure APIs

    Also in 3 projects that use this

  • +8 more from parcadei

The file

Show its rules and text

We split this skill into the rules it gives an agent

24 rules. 0 are common, 21 are distinctive, and 3 are very specific to this project.

  • 0

    Common

    Most of the 169 edited versions we read keep these.

  • 21

    Distinctive

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    No arguments: analyze the current branch diff for refactoring candidates.

    line 23
  2. Distinctive:

    Record coverage: If a coverage tool is configured, record the current coverage numbers for affected files.

    line 33
  3. Very specific:

    Write characterization tests first: tests that pin the current observable behavior, including behavior that looks wrong, through the public …

    line 36
  4. Distinctive:

    Stop and report which units lack coverage.

    line 37
  5. Very specific:

    If --plan-only was passed, stop here.

    line 65
  6. Distinctive:

    Predict the test outcome: All existing tests must continue to pass with no modifications.

    line 72
  7. Distinctive:

    Run tests: If tests fail:

    line 74
  8. Distinctive:

    If the alternative also fails, skip this candidate and move to the next.

    line 78
  9. Distinctive:

    Run the formatter check. No changes.

    line 87
  10. Distinctive:

    Run the full test suite. All tests pass.

    line 88
  11. Distinctive:

    Run the linter. Zero warnings.

    line 89
  12. Distinctive:

    Run the type checker. Zero errors.

    line 90
  13. Distinctive:

    Run the build. Clean build.

    line 91
  14. Distinctive:

    Never change behavior. A refactoring that alters what the code does is a bug, not a refactoring.

    line 97
  15. Distinctive:

    Never combine refactoring with feature work in the same commit.

    line 98
  16. Distinctive:

    Never modify test assertions during refactoring.

    line 99
  17. Distinctive:

    Do not refactor code you do not understand.

    line 102
  18. Distinctive:

    Stop before any change when the Phase 1 test run fails.

    line 115
  19. Distinctive:

    Stop and write characterization tests, or report the gap, when a candidate touches lines no test reaches.

    line 116
  20. Distinctive:

    Stop and revert when a test fails after a step.

    line 117
  21. Distinctive:

    Stop and read the function, its callers, and its tests when the next edit targets code you have not read.

    line 118
  22. Distinctive:

    Stop and split the commit when its diff mixes a structural change with a behavior change.

    line 119
  23. Very specific:

    Stop at the Phase 3 table when --plan-only was passed.

    line 120
  24. Distinctive:

    Every skipped candidate is listed with the test failure that ruled it out.

    line 128

“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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Overview

Incremental refactoring workflow that enforces behavior preservation at every step. Each refactoring is a separate commit with test verification before and after.

The refactoring principles follow ../../rules/code-style.md. This skill provides the execution workflow.

When to Use

  • Tests pass, and a function, file, or class crosses one of the Phase 2 thresholds.
  • A feature is next, and the code it lands in has to be made easy to change first.
  • /module-audit produced a consolidation the user picked.
  • For new behavior, use /plan; for a bug, use /investigate; for feedback on a diff, use /review.

Arguments

  • No arguments: analyze the current branch diff for refactoring candidates.
  • <path>: refactor the specified file or directory.
  • --plan-only: identify and rank candidates without executing any changes.

Process

Phase 1: Establish Baseline

  1. Run the full test suite. Record the result. If tests fail, stop. Do not refactor code with a failing test suite. The user must fix tests first.
  2. Record coverage. If a coverage tool is configured, record the current coverage numbers for affected files. Coverage must not decrease after refactoring.
  3. Gate on coverage of the target. Every line and branch the refactoring will move needs a test that observes its behavior; the suite passing proves nothing about code no test reaches. When coverage of the target is insufficient, or no coverage tool exists to show it, take one of two paths:
    • Write characterization tests first: tests that pin the current observable behavior, including behavior that looks wrong, through the public interface. Commit them alone as test(<scope>): characterize <unit> before any structural change.
    • Stop and report which units lack coverage. Never refactor uncovered code.

Phase 2: Identify Candidates

Scan the target files for refactoring candidates. Check each category:

CategoryThresholdRefactoring
Long functions>30 linesExtract function
Deep nesting>3 levelsGuard clauses, early returns
Duplicated blocks>5 lines appearing 2+ timesExtract shared function
Large files>500 lines, per rules/code-style.mdSplit by responsibility
God classes>7 public methodsSplit into focused classes
Long parameter lists>4 parametersExtract options object
Circular importsAny cycleRestructure module boundaries
Dead codeUnreachable branches, unused exportsRemove
Primitive obsessionRepeated string/number with domain meaningExtract type or enum
Feature envyFunction using more of another module's data than its ownMove to the correct module

Phase 3: Rank and Present

Rank candidates by impact score: lines affected multiplied by complexity reduction. Present as a table:

PriorityFileLineIssueProposed refactoringImpact
1............High
2............Medium

If --plan-only was passed, stop here.

Phase 4: Execute Incrementally

For each approved candidate, in priority order:

  1. Describe the change. State what will change and what will stay the same.
  2. Predict the test outcome. All existing tests must continue to pass with no modifications.
  3. Apply the refactoring. One structural change at a time.
  4. Run tests. If tests fail:
    • Revert the change.
    • Analyze why the refactoring broke tests. If the tests were testing implementation details rather than behavior, note this as a separate finding.
    • Try an alternative approach.
    • If the alternative also fails, skip this candidate and move to the next.
  5. Run formatter, linter, type checker, and build. Fix any new warnings introduced by the refactoring before the commit.
  6. Commit. One commit per refactoring step:
    • refactor(scope): extract validateInput from processOrder
    • refactor(scope): flatten nested conditionals in AuthService
    • refactor(scope): remove duplicate price calculation

Phase 5: Final Verification

  1. Run the formatter check. No changes.
  2. Run the full test suite. All tests pass.
  3. Run the linter. Zero warnings.
  4. Run the type checker. Zero errors.
  5. Run the build. Clean build.
  6. Compare coverage. Coverage is equal to or higher than the baseline.
  7. Review the full diff. Confirm no behavior changes leaked in.

Rules

  • Never change behavior. A refactoring that alters what the code does is a bug, not a refactoring.
  • Never combine refactoring with feature work in the same commit. Structure changes and behavior changes are separate commits.
  • Never modify test assertions during refactoring. If a test breaks, the refactoring changed behavior.
  • One refactoring per commit. If a commit does two things, split it.
  • Revert immediately when tests fail. Do not debug a failed refactoring for more than 5 minutes. Try a different approach or skip the candidate.
  • Do not refactor code you do not understand. Read the function, its callers, and its tests before touching it.

Common Rationalizations

  • "The test only broke because it asserts an implementation detail, so updating the assertion is fine": assertions stay untouched. Revert, and report the brittle test as its own finding.
  • "The off-by-one is right here, fixing it during the extraction is quicker": a behavior change goes in its own commit, apart from the structural one.
  • "Two tiny refactorings fit in one commit": one refactoring per commit, so each step reverts alone.
  • "The suite was already red before I started": the baseline stays green. Stop until the user fixes the failing tests.
  • "The suite is green, so the refactoring is safe": green says nothing about lines no test reaches. Characterize them first, or stop.
  • "Five more minutes of debugging will save this candidate": revert, try one alternative, and skip the candidate when that also fails.

Red Flags

  • Stop before any change when the Phase 1 test run fails.
  • Stop and write characterization tests, or report the gap, when a candidate touches lines no test reaches.
  • Stop and revert when a test fails after a step.
  • Stop and read the function, its callers, and its tests when the next edit targets code you have not read.
  • Stop and split the commit when its diff mixes a structural change with a behavior change.
  • Stop at the Phase 3 table when --plan-only was passed.

Verification

  • The full test suite passes, and the diff touches no test assertion.
  • The linter reports zero warnings, the type checker zero errors, and the build is clean.
  • Coverage of the affected files is at or above the Phase 1 baseline.
  • git log shows one refactor(<scope>) commit per applied candidate.
  • Every skipped candidate is listed with the test failure that ruled it out.

Related skills

  • /review -- Review the refactoring diff before shipping.
  • /test -- Run the test suite during verification.
  • /ship commit -- Commit each refactoring step.
  • /investigate -- Debug if a refactoring unexpectedly changes behavior.

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.