Claude
Skills
Sign in
Back

refactor

Included with Lifetime
$97 forever

Safe codebase refactoring with characterization tests, incremental changes, and continuous verification. Automatically activates when users want to refactor code, extract methods/classes, simplify logic, reduce duplication, improve naming, restructure modules, or clean up technical debt.

Code Review

What this skill does


# Refactor

Refactor code safely using characterization tests, incremental changes, and continuous verification. Every change preserves existing behavior while improving code structure, readability, and maintainability.

## Refactoring Goal

$ARGUMENTS

## Core Principle: Behavior Preservation

**CRITICAL**: Refactoring changes code structure WITHOUT changing behavior. Every step must be verified against existing tests. If tests break, the refactoring introduced a bug — revert and retry.

## Anti-Hallucination Guidelines

1. **Read before changing** — Never refactor code that has not been read and understood. Understand all callers and dependencies first.
2. **Test before and after** — Run the full test suite before starting. Run it again after every incremental change. The results must match.
3. **Characterization tests first** — If test coverage is insufficient for the target code, write characterization tests that capture current behavior BEFORE refactoring.
4. **Incremental changes** — Make one small, verifiable change at a time. Never combine multiple refactoring steps into a single edit.
5. **No feature changes** — Do not add features, fix bugs, or change behavior during refactoring. These are separate tasks.
6. **Reference real code** — Never make claims about code structure that has not been verified by reading the actual files.

## Quality Gates

This skill includes automatic refactoring verification before completion:

### Safety Verification (Stop Hook)

When attempting to stop working, an automated verification agent runs to ensure the refactoring is safe:

**Verification Steps:**
1. **Behavior preserved**: Full test suite passes (same results as before refactoring)
2. **No regressions**: Linter and type checker report no new errors
3. **Characterization tests**: Any tests added to capture behavior still pass
4. **Clean diff**: Only intentional structural changes exist

**Behavior:**
- ✅ **All verifications pass**: Refactoring marked complete
- ❌ **Any test fails**: Completion blocked, Claude reverts or fixes the breaking change
- ⚠️ **New lint/type errors**: Completion blocked until resolved

**Example blocked completion:**
```
⚠️ Refactoring verification failed:

Tests: ❌ FAILED (2 tests failing)
  - test_calculate_total: Expected 150.0, got 150
  - test_format_output: AssertionError: output format changed

Lint: ✅ PASSED
Type Check: ✅ PASSED

🔧 Refactoring introduced behavior changes. Revert the last change and retry
with a smaller step.
```

## Task Management

This skill uses Claude Code's Task Management System for strict sequential dependency tracking through the refactoring workflow.

**When to Use Tasks:**
- Multi-step refactoring across files or modules
- Extract method/class operations requiring dependency analysis
- Large-scale restructuring with many callers
- Work requiring progress tracking across sessions

**When to Skip Tasks:**
- Simple rename (single variable/function)
- Trivial formatting or style fix
- Single-line simplification

**Task Structure:**
Refactoring creates a strict sequential chain where each phase must complete before the next can start, ensuring characterization tests exist before any structural changes begin.

## Implementation Workflow

**Task tracking replaces TodoWrite.** Create task chain at start, update as completing each phase.

### Phase 0: Project Discovery (REQUIRED)

**Step 0.1: Create Task Dependency Chain**

Before refactoring, create the strict sequential task structure:

```
TaskCreate:
  subject: "Phase 0: Discover project workflow"
  description: "Identify test, lint, type-check commands from CLAUDE.md and task runners"
  activeForm: "Discovering project workflow"

TaskCreate:
  subject: "Phase 1: Analyze refactoring scope"
  description: "Map dependencies, callers, and test coverage for target code"
  activeForm: "Analyzing refactoring scope"

TaskCreate:
  subject: "Phase 2: Write characterization tests"
  description: "Ensure sufficient test coverage before making structural changes"
  activeForm: "Writing characterization tests"

TaskCreate:
  subject: "Phase 3: Incremental refactoring"
  description: "Apply refactoring in small verified steps"
  activeForm: "Refactoring incrementally"

TaskCreate:
  subject: "Phase 4: Final verification"
  description: "Run full test suite, lint, type-check — confirm behavior preserved"
  activeForm: "Verifying refactoring safety"

TaskCreate:
  subject: "Phase 5: Final commit"
  description: "Create conventional commit with refactoring summary"
  activeForm: "Creating final commit"

# Set up strict sequential chain
TaskUpdate: { taskId: "2", addBlockedBy: ["1"] }
TaskUpdate: { taskId: "3", addBlockedBy: ["2"] }
TaskUpdate: { taskId: "4", addBlockedBy: ["3"] }
TaskUpdate: { taskId: "5", addBlockedBy: ["4"] }
TaskUpdate: { taskId: "6", addBlockedBy: ["5"] }

# Start first task
TaskUpdate: { taskId: "1", status: "in_progress" }
```

**Step 0.2: Discover Project Workflow**

Use Haiku-powered Explore agent for token-efficient discovery:

```
Use Task tool with Explore agent:
- prompt: "Discover the development workflow for this project:
    1. Read CLAUDE.md if it exists - extract testing and quality conventions
    2. Check for task runners: Makefile, justfile, package.json scripts, pyproject.toml scripts
    3. Identify the test command (e.g., make test, just test, npm test, pytest, bun test)
    4. Identify how to run a single test file or specific test
    5. Identify the lint command (e.g., make lint, npm run lint, ruff check)
    6. Identify the type-check command if applicable (e.g., pyright, tsc, mypy)
    7. Note any pre-commit hooks or quality gates
    8. Check for code coverage tooling (e.g., pytest --cov, nyc, c8)
    Return a structured summary of all available commands."
- subagent_type: "Explore"
- model: "haiku"  # Token-efficient for discovery
```

Store discovered commands for use in later phases.

**Step 0.3: Run Baseline Tests**

**CRITICAL**: Run the full test suite BEFORE making any changes. Record the results as the baseline. Every subsequent test run must match or exceed this baseline.

```bash
# Run full test suite and record results
[DISCOVERED_TEST_COMMAND]
```

If tests already fail before refactoring, document the pre-existing failures. These are not caused by the refactoring and should remain unchanged (same tests fail with same errors).

**Step 0.4: Complete Phase 0**

```
TaskUpdate: { taskId: "1", status: "completed" }
TaskList  # Check that Task 2 is now unblocked
```

### Phase 1: Scope Analysis

**Goal**: Understand the full impact of the refactoring before touching any code.

**Step 1.1: Start Phase 1**

```
TaskUpdate: { taskId: "2", status: "in_progress" }
```

**Step 1.2: Parallel Scope Analysis**

Spawn two Explore agents in parallel to map the refactoring scope:

```
Agent 1 - Dependency & Caller Analysis (Explore, Haiku):
  prompt: "Analyze dependencies and callers for the refactoring target:

    Refactoring target: [DESCRIBE TARGET CODE]

    1. Read the target code — understand its current structure and public API
    2. Find ALL callers and dependents using Grep:
       - Direct function/method calls
       - Import statements referencing the target
       - Type references (if applicable)
       - Configuration or dependency injection references
    3. Map the dependency graph:
       - What does the target depend on?
       - What depends on the target?
       - Are there circular dependencies?
    4. Identify the public API surface:
       - Which functions/methods/classes are called externally?
       - Which are internal-only (safe to change freely)?
    5. Note any dynamic references (string-based lookups, reflection, decorators)

    Return:
    - Complete caller list with file:line references
    - Dependency graph (what depends on what)
    - Public vs internal API surface
    - Risks: dynamic references, external consumers, serialization"
  subagent_type: "Explore"
  model: "haiku"

Agent 2
Files: 2
Size: 29.9 KB
Complexity: 49/100
Category: Code Review

Related in Code Review