Developer

AI code refactoring

Run /refactor to modernize code, reduce complexity, and improve maintainability. The agent identifies what to change and why — then does it with test verification.

/refactor

Refactor code for readability, maintainability, and modern patterns. The agent identifies improvement opportunities and applies changes with full test verification.

AI code refactoring

Capabilities

Clean code, automatically

Pattern modernization

Pattern modernization

Updates legacy patterns to modern equivalents. Callbacks to async/await, class components to hooks, old APIs to current ones.

Complexity reduction

Complexity reduction

Identifies overly complex functions and simplifies them. Extracts methods, reduces nesting, and improves naming.

Safe refactoring

Safe refactoring

Every change is verified against existing tests. New tests are added when coverage gaps are found during refactoring.

How It Works

How /refactor works

1

Type /refactor

Run the command on a file, module, or directory. Optionally specify what kind of refactoring you want.

2

Agent analyzes and proposes

Your AI agent identifies refactoring opportunities, explains why each change improves the code, and proposes a plan.

3

Apply and verify

Changes are applied with test verification. If tests fail, the agent diagnoses and fixes the issue.

Try It

Example prompts

/refactor src/utils/ — modernize to ES2024 patterns
/refactor reduce complexity in the auth middleware
/refactor extract the validation logic into its own module

Full Skill Source

Use this skill in your project

Copy the full text below or download it as a markdown file. Place it in your project's .claude/commands/ directory to use it as a slash command.

---
name: code-refactorer
description: Analyze code for cleanup opportunities and perform systematic refactoring with safety checks. Use when modernizing legacy code, reducing duplication, improving readability, or restructuring modules.
allowed-tools: ["Read", "Edit", "Write", "Bash", "Glob", "Grep"]
---

# /refactor

Analyze code for improvement opportunities and perform safe, systematic refactoring with test verification at each step.

## What This Command Does

1. Analyzes the target code for refactoring opportunities
2. Categorizes findings by type (duplication, complexity, naming, structure)
3. Proposes a refactoring plan with prioritized changes
4. Executes refactoring steps incrementally
5. Verifies tests pass after each change
6. Produces a summary of all changes made

## Usage

```
/refactor [target] [--type focus-area] [--scope conservative|moderate|aggressive]
```

**Examples:**
- `/refactor src/services/auth.ts` -- refactor a single file
- `/refactor src/components/ --type duplication` -- find and eliminate duplication across components
- `/refactor src/api/ --scope conservative` -- minimal, safe changes only
- `/refactor src/utils/ --type naming` -- improve variable and function names

## Execution Steps

1. **Analyze the target code**

   Read all files in the target path and build an understanding of:
   - **File structure**: How files relate to each other (imports, exports, dependencies)
   - **Code patterns**: Repeated patterns, inconsistent approaches to the same problem
   - **Complexity hotspots**: Functions over 30 lines, deep nesting (3+ levels), high cyclomatic complexity
   - **Naming issues**: Unclear names, inconsistent conventions, misleading identifiers
   - **Dead code**: Unused exports, unreachable branches, commented-out code
   - **Type issues**: `any` types, missing return types, loose interfaces (TypeScript)

2. **Categorize refactoring opportunities**

   Group findings into these categories:

   | Category | Description | Risk Level |
   |----------|-------------|------------|
   | **Duplication** | Same or very similar code in multiple places | Low |
   | **Extraction** | Long functions that should be broken into smaller ones | Low |
   | **Naming** | Unclear or inconsistent variable/function/file names | Low |
   | **Simplification** | Overly complex logic that can be simplified | Medium |
   | **Restructuring** | Moving code between files, changing module boundaries | Medium |
   | **Modernization** | Replacing old patterns with modern language features | Medium |
   | **Architecture** | Changing how components interact or data flows | High |

3. **Create the refactoring plan**

   For each opportunity, document:
   - What the current code does and why it needs change
   - What the refactored code will look like
   - Which files are affected
   - Risk level (low/medium/high)
   - Dependencies (does this change need to happen before/after another?)

   Present the plan to the user before executing. Order by:
   1. Low-risk, high-impact changes first
   2. Changes that other changes depend on
   3. Higher-risk changes last

4. **Execute refactoring steps**

   For each approved change, follow this protocol:

   **Before each change:**
   - Run existing tests to establish a green baseline: `npm test` or equivalent
   - If tests fail before refactoring, stop and report -- do not refactor broken code

   **Make the change:**
   - Apply the smallest meaningful transformation
   - One refactoring pattern per step (don't combine extract + rename + restructure)
   - Preserve all existing behavior -- refactoring must not change what the code does

   **After each change:**
   - Run tests again to verify nothing broke
   - If tests fail, revert the change and report the failure
   - If tests pass, move to the next change

5. **Apply specific refactoring patterns**

   Common patterns to apply:

   **Extract Function:**
   - Identify a block of code that does one coherent thing
   - Move it to a new function with a descriptive name
   - Replace the original block with a call to the new function
   - Pass only the data the function needs as parameters

   **Remove Duplication:**
   - Find two or more code blocks that are similar (70%+ overlap)
   - Extract the common logic into a shared function
   - Parameterize the differences
   - Replace all instances with calls to the shared function

   **Simplify Conditionals:**
   - Replace nested if/else with early returns (guard clauses)
   - Replace complex boolean expressions with named variables
   - Replace switch statements with lookup objects where appropriate

   **Improve Naming:**
   - Variables: describe what the value IS, not how it was computed
   - Functions: describe what the function DOES, using a verb
   - Booleans: use `is`, `has`, `should`, `can` prefixes
   - Constants: UPPER_SNAKE_CASE for true constants

   **Modernize Syntax:**
   - Replace `var` with `const`/`let`
   - Replace `.then()` chains with async/await
   - Replace manual loops with array methods where clearer
   - Replace string concatenation with template literals

6. **Handle cross-file refactoring**

   When moving code between files:
   - Update ALL import statements across the codebase
   - Search for dynamic imports and string references
   - Update any re-exports in index files
   - Check for circular dependency introduction

7. **Generate the refactoring report**

## Output Format

```markdown
# Refactoring Report

**Target**: [files/directories refactored]
**Scope**: [conservative/moderate/aggressive]
**Date**: [current date]

---

## Summary

- **Files analyzed**: [count]
- **Opportunities found**: [count]
- **Changes applied**: [count]
- **Tests**: All passing / [N] failures

---

## Changes Applied

### 1. [Change description]
- **Type**: [Duplication/Extraction/Naming/etc.]
- **Files**: [affected files]
- **Before**: [brief description or code snippet]
- **After**: [brief description or code snippet]
- **Tests**: Passing

### 2. [Change description]
...

---

## Deferred Changes

| Change | Reason Deferred | Risk |
|--------|----------------|------|
| [Change] | [Why it wasn't applied] | [H/M/L] |

---

## Metrics (if measurable)

| Metric | Before | After |
|--------|--------|-------|
| Lines of code | [N] | [N] |
| Duplicate blocks | [N] | [N] |
| Average function length | [N] lines | [N] lines |
| Max nesting depth | [N] | [N] |
```

## Scope Definitions

| Scope | What It Includes | What It Skips |
|-------|-----------------|---------------|
| **Conservative** | Naming, dead code removal, simple extractions | Restructuring, architecture changes |
| **Moderate** | All conservative + duplication removal, simplification, modernization | Architecture changes |
| **Aggressive** | Everything including restructuring and architecture | Nothing (but requires user approval for high-risk changes) |

## Error Handling

- **No tests found**: Warn the user that refactoring without tests is risky; offer to write tests first
- **Tests fail before refactoring**: Stop and report; refactoring must start from a green baseline
- **Tests fail after a change**: Revert that specific change, report what went wrong, continue with other changes
- **Circular dependency created**: Revert and suggest alternative file organization

## Best Practices

- Refactoring and feature changes are separate commits; never mix them
- Start with the smallest safe changes to build confidence
- If you are unsure whether a change preserves behavior, write a test first
- Prefer many small changes over one large change
- Run the full test suite, not just tests for changed files

Related Skills

Skills that work well together

Nimbalyst is the visual workspace for building with Claude Code and Codex