refactor
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.
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 2Related in Code Review
gstack
IncludedFast headless browser for QA testing and site dogfooding. Navigate pages, interact with elements, verify state, diff before/after, take annotated screenshots, test responsive layouts, forms, uploads, dialogs, and capture bug evidence. Use when asked to open or test a site, verify a deployment, dogfood a user flow, or file a bug with screenshots. (gstack)
startup-due-diligence
IncludedLegal due diligence review for seed-stage and Series A startups (US, Delaware C-Corp focus). Supports both investor and founder perspectives. Capabilities include: (1) Interactive document review and issue spotting; (2) Document request list generation; (3) Cap table and SAFE/convertible note analysis; (4) Red flag identification with severity ratings; (5) Diligence report generation. TRIGGERS: due diligence, DD, startup investment, cap table review, Series A, seed round, investor diligence, legal review startup, SAFE analysis, convertible note, 409A, founder vesting.
interview-master
IncludedThis skill should be used when the user asks to "generate interview questions", "prepare for interview", "optimize resume", "conduct mock interview", "analyze git commits for resume", "generate resume from code", "review my resume", or mentions interview preparation, career assistance, or extracting project experience from git history. Provides comprehensive interview and career development guidance for both job seekers and interviewers.
fix-issue
IncludedFixes GitHub issues using parallel analysis agents for root cause investigation, code exploration, and regression detection. Reads issue context from gh CLI, searches codebase and memory for related patterns, generates a fix with tests, and links the resolution back to the issue via PR. Includes prevention analysis to avoid recurrence. Use when debugging errors, resolving regressions, fixing bugs, or triaging issues.
sf-apex
IncludedGenerates and reviews Salesforce Apex code with 150-point scoring. TRIGGER when: user writes, reviews, or fixes Apex classes, triggers, test classes, batch/queueable/schedulable jobs, or touches .cls/.trigger files. DO NOT TRIGGER when: LWC JavaScript (use sf-lwc), Flow XML (use sf-flow), SOQL-only queries (use sf-soql), or non-Salesforce code.
swift-development
IncludedComprehensive Swift development for building, testing, and deploying iOS/macOS applications. Use when Claude needs to: (1) Build Swift packages or Xcode projects from command line, (2) Run tests with XCTest or Swift Testing framework, (3) Manage iOS simulators with simctl, (4) Handle code signing, provisioning profiles, and app distribution, (5) Format or lint Swift code with SwiftFormat/SwiftLint, (6) Work with Swift Package Manager (SPM), (7) Implement Swift 6 concurrency patterns (async/await, actors, Sendable), (8) Create SwiftUI views with MVVM architecture, (9) Set up Core Data or SwiftData persistence, or any other Swift/iOS/macOS development tasks.