Skip to main content
command CX Codex

refactor-guided — Claude Code command: guided refactoring

refactor-guided guides structural refactoring in small steps and runs tests after each change. It keeps feature work separate from code restructuring.

MIT ★ 1,424 updated 2026-10-06

Install into Claude Code · Manually: put the files in place All methods and platforms ↓
.claude/commands/refactor-guided.md
Open on GitHub

What refactor-guided does

The command first maps the requested scope: target files, imports, dependents, and the likely blast radius. It then checks the project’s existing tests, adds coverage for current behavior when needed, and records a baseline before changing code.

Each refactoring step is described and applied separately. Tests run immediately afterward; a passing step gets its own refactor: commit, while a failing attempt is reverted and investigated. The workflow covers extracting functions, renaming symbols, removing duplication, simplifying conditions, splitting large files, and improving type signatures.

A dirty working tree stops the command before it begins, so existing changes must be handled first. It can use git, package managers, test runners, and file read/write tools available through its command permissions.

What it helps with

  • split a large file or function into smaller units
  • rename symbols while preserving external behavior
  • remove duplicated code safely
  • run tests after each structural change
  • record refactoring steps as separate commits

Example prompts for the agent

  • Run /refactor-guided to inspect the latest changed files and suggest a safe refactoring plan.
  • Run /refactor-guided and extract the repeated logic from src/orders.ts into a separate function.
  • Run /refactor-guided on src/api and test every change before moving to the next step.

How to install refactor-guided

Manually: put the files in place

.claude/commands/refactor-guided.md

Call it with /refactor-guided. For all projects use ~/.claude/commands/

Questions about refactor-guided

How do I install refactor-guided in Claude Code?

Place the command file at .claude/commands/refactor-guided.md. Then invoke it in Claude Code with /refactor-guided.

What does refactor-guided do?

It maps the refactoring scope, checks test coverage, and applies structural changes one step at a time. Each step is tested, committed when it passes, or reverted when it fails.

What happens if the working tree has uncommitted changes?

The command stops and asks the user to handle them first. It does not stash or commit those changes on its own.

Source text

refactor-guided.md · MIT
---
allowed-tools: Bash(git:*), Bash(npm:*), Bash(npx:*), Bash(yarn:*), Bash(pnpm:*), Bash(bun:*), Bash(pytest:*), Bash(python:*), Bash(go:*), Bash(cargo:*), Read, Write, Edit, Glob, Grep
description: Systematic, safety-first refactoring with verification at each step. Never refactors and adds features simultaneously.
argument-hint: "[target file, directory, or refactoring description]"
---

# Guided Refactoring

Perform safe, incremental refactoring with test verification at every step.

## Context

- Recent changes: !`git diff --name-only HEAD~3 2>/dev/null | head -10`
- Current branch: !`git branch --show-current`
- Working tree status: !`git status --short`
- Project root files (infer the test framework from these): !`ls -a`
- Existing tests: !`git ls-files 2>/dev/null | grep -i -e test -e spec | head -10`

## Safety Rules (NON-NEGOTIABLE)

1. **NEVER refactor AND add features simultaneously.** Each change is purely structural.
2. **NEVER proceed without passing tests.** If tests fail after a refactoring, revert immediately.
3. **ONE refactoring at a time.** Each commit is a single, atomic refactoring step.
4. **Preserve external behavior.** Inputs and outputs must remain identical.
5. **Ensure clean working tree before starting.** If there are uncommitted changes, stop and ask the user — do not stash or commit their work yourself.

## Workflow

### Phase 1: Analyze Scope

1. Identify the target file(s) or directory from `$ARGUMENTS`
2. Map all dependents — files that import/use the target
3. Map all dependencies — files that the target imports/uses
4. Assess blast radius: how many files could be affected?
5. Report scope summary before proceeding:
   ```
   ## Refactoring Scope
   - Target: [file/directory]
   - Files affected: [count]
   - Dependencies: [list]
   - Dependents: [list]
   - Risk level: [low/medium/high]
   ```

### Phase 2: Ensure Test Coverage

1. Check if tests exist for the current behavior of the target
2. Run existing tests to confirm they pass (this is your safety net)
3. If test coverage is insufficient:
   - Write tests that capture the current behavior BEFORE refactoring
   - Run them to confirm they pass
   - Commit these tests separately: `test: add coverage for [target] before refactoring`
4. Record baseline test results (pass count, time)

### Phase 3: Refactor Incrementally

For each refactoring step:

1. **Describe** the specific refactoring about to be applied (e.g., "Extract method X from class Y", "Rename variable A to B", "Move function to separate module")
2. **Apply** the single refactoring change
3. **Run tests** immediately after applying
4. **If tests PASS:**
   - Commit with message: `refactor: [specific change description]`
   - Move to next refactoring step
5. **If tests FAIL:**
   - Revert the change: `git checkout -- .`, and delete any new files this step created (they are untracked, so checkout leaves them behind)
   - Analyze why it failed
   - Try a different approach or break it into smaller steps
   - Document what went wrong

Common refactoring types (apply as appropriate):

- Extract function/method
- Rename for clarity
- Remove duplication (DRY)
- Simplify conditionals
- Split large files/functions
- Improve type signatures
- Replace magic values with constants
- Consolidate imports

### Phase 4: Summary Report

After all refactoring steps are complete, provide:

```
## Refactoring Summary

### Before
- Files: [count and names]
- Lines of code: [approximate]
- Complexity: [observations]

### After
- Files: [count and names]
- Lines of code: [approximate]
- Complexity: [observations]

### Changes Applied
1. [refactoring 1] - [commit hash]
2. [refactoring 2] - [commit hash]
...

### Reverted Attempts
1. [what was tried] - [why it failed]

### Test Results
- All tests passing: [yes/no]
- Tests added: [count]
- Total test runs: [count]
```

## Target

$ARGUMENTS

If no target specified, analyze the most recently modified files and suggest refactoring opportunities.

© CloudAI-X · MIT · CloudAI-X/claude-workflow-v2

Similar slash commands

All slash commands for Code review and refactoring →

From the same set46

The whole set →
verify-changes verify-changes executes adversarial multi-subagent verification across recent code diffs to weed out bugs and false alarms. CX Codex +1 ★ 1,424repo stars save-session-learnings The save-session-learnings command for Claude Code saves useful findings from a coding session to CLAUDE.md and AGENTS.md after debugging or a substantial task. CX Codex +1 ★ 1,424repo stars analyzing-projects analyzing-projects walks through an unfamiliar codebase step by step: stack, structure, patterns, dev commands — useful when onboarding onto a project. CX Codex +1 ★ 1,424repo stars plan Creates and maintains a structured PLAN.md file in your project root to track phases, task dependencies, and progress logs. CX Codex +1 ★ 1,424repo stars convex-backend convex-backend is a Claude Code skill that loads Convex guidelines for TypeScript functions, schemas, validators, queries, mutations, actions, subscriptions, and file storage. It supports type-safe backend development. CX Codex +1 ★ 1,424repo stars dependency-upgrade The dependency-upgrade command for Claude Code updates packages one by one, runs tests after each upgrade, and rolls back changes on failures. CX Codex +1 ★ 1,424repo stars designing-apis designing-apis — a Claude Code skill that designs REST and GraphQL APIs: structures endpoints, defines request and response formats, configures error handling and versioning. CX Codex +1 ★ 1,424repo stars parallel-analyze parallel-analyze starts four subagents at once: architecture, security, performance, testing. Their findings land in one report, ranked by priority. CX Codex +1 ★ 1,424repo stars

Project sponsors

Companies that keep this analytics open