Skip to main content
skill CX Codex

refactor · sethgammon — Claude Code skill: what it does, how to install

Multi-file refactoring with automated Git rollback, typechecking, and test baseline verification across edits.

MIT ★ 937 updated 2026-10-29

Install into Claude Code · Plugin marketplace All methods and platforms ↓
/plugin marketplace add SethGammon/Citadel
/plugin install citadel@citadel-local
Open on GitHub

What refactor does

This skill executes multi-file structural code modifications through a phased protocol. It starts by establishing a baseline using npm run typecheck and your test suite. If existing type errors are present, execution halts immediately. The agent then maps out every import, re-export, and call site before writing any edits.

Changes apply in a strict sequence: new files are created first, references are redirected, the source file updates, and deprecated files are deleted last. After applying edits, it re-runs tests against the baseline. If regressions occur, the skill permits two fix attempts before running git checkout to restore your working tree.

What it helps with

  • rename a symbol or module across all project files
  • extract a component or function into a separate file
  • split a large file into smaller logical modules
  • inline a function back into its call sites

Example prompts for the agent

  • /refactor extract UserService from src/services/api.ts
  • /refactor rename OldButton to PrimaryButton
  • /refactor --dry-run split src/utils/helpers.ts

How to install refactor

1Plugin marketplace

/plugin marketplace add SethGammon/Citadel
/plugin install citadel@citadel-local

This installs the whole citadel plugin with all its skills

2Skills CLI (Vercel)

npx skills add SethGammon/Citadel --skill refactor -a claude-code

3Manually: put the files in place

~/.claude/skills/refactor/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/refactor/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about refactor

How to install refactor in Claude Code?

Run /plugin marketplace add SethGammon/Citadel followed by /plugin install citadel@citadel-local. You can also run npx skills add SethGammon/Citadel --skill refactor -a claude-code.

What does the refactor skill do?

It restructures code across multiple files, keeps imports in sync, and verifies that no new typecheck or test errors appear.

What happens if tests fail after refactoring?

The skill makes two attempts to resolve the detected errors. If verification still fails, it discards changes using git checkout and removes new files.

Source text

SKILL.md · MIT
---
name: refactor
license: MIT
description: >-
  Safe multi-file refactoring with automatic rollback. Establishes a type/test
  baseline, plans all changes, executes file-by-file, and verifies zero
  regressions. Reverts if verification fails after two fix attempts.
  Handles renames, extracts, moves, splits, merges, and inlines.
user-invocable: true
auto-trigger: false
trigger_keywords:
  - refactor
  - rename
  - extract
  - inline
  - move file
  - split file
  - merge files
last-updated: 2026-03-20
---

# /refactor — Safe Multi-File Refactoring

## Orientation

Use `/refactor` when you need to:
- Rename a symbol, file, or module across the codebase
- Extract a function, component, hook, class, or module from existing code
- Inline a function or module back into its callers
- Move a file or set of files to a new location
- Split a large file into smaller pieces
- Merge related files into one
- Change a function signature and update all call sites

**Don't use when:** debugging a specific bug (use /systematic-debugging); adding new features (use /marshal or /scaffold); deleting dead code (use /marshal for a targeted cleanup).

**Boundary with /organize:** /refactor changes code structure within files (extract, inline, split, merge, rename) and moves files as part of those operations. Repository-wide file/directory placement, naming sweeps, and where-does-this-belong decisions are /organize.

**Behavior does not change.** Tests pass before and after, no new type errors — the refactoring is correct.

## Commands

| Command | Behavior |
|---|---|
| `/refactor rename [old] to [new]` | Rename symbol, file, or module |
| `/refactor extract [target] from [source]` | Extract function/component/module |
| `/refactor inline [target]` | Inline a function/module into callers |
| `/refactor move [source] to [dest]` | Move file(s) with import updates |
| `/refactor split [file]` | Split a file into logical pieces |
| `/refactor merge [files...]` | Merge related files into one |
| `/refactor [freeform description]` | Auto-detect refactoring type from description |
| `/refactor --dry-run [any above]` | Plan only, show what would change |

## Protocol

### Phase 1: BASELINE

Run typecheck (via `node scripts/run-with-timeout.js 300 npm run typecheck`) and tests. Record error/failure counts — pre-existing issues are not your responsibility, but you must not add to them. Warn if there are uncommitted changes in files you plan to modify.

```
Baseline established:
  Typecheck: {pass | N errors (pre-existing)}
  Tests: {pass | N failures (pre-existing) | no test suite found}
  Git: {clean | M files with uncommitted changes}
```

### Phase 2: PLAN

Analyze the refactoring target and produce a concrete plan.

1. **Identify scope**: Search the codebase for every reference to the target.
   Use grep/search for:
   - Import statements referencing the target
   - Usage sites (function calls, type references, component usage)
   - Re-exports from index files
   - Test files that reference the target
   - Documentation or comments mentioning the target
   - Config files (e.g., route definitions, dependency injection)

2. **Classify the refactoring type** and apply type-specific analysis:

   **Rename (symbol):** all imports + usage sites + string references + dynamic access patterns (`obj[key]`)

   **Rename (file/module):** all import paths + path aliases + dynamic imports + index re-exports

   **Extract (function/component/module):** code to extract, enclosing-scope dependencies, return values back to caller, destination file, interface design

   **Move (file):** every import of old path → compute new relative paths, check alias boundary changes, barrel updates

   **Split (file):** logical groupings, internal cross-references, which group keeps the original path, new files per group, index if needed

   **Merge (files):** duplicates/conflicts, import consolidation, merged file organization

3. **Produce the plan** — list every file that will change and what changes:

```
Refactoring Plan: {type} — {description}

Files to modify:
  1. {file}: {what changes and why}
  2. {file}: {what changes and why}
  ...

Files to create:
  - {file}: {extracted from where, contains what}

Files to delete:
  - {file}: {contents moved to where}

Risk assessment:
  - {any concerns: dynamic references, string-based lookups, config files}
```

4. If `--dry-run` was specified, output the plan and stop.

### Phase 3: EXECUTE

Apply changes in this order to minimize intermediate breakage:
1. Create new files first (exports only, not yet imported)
2. Update importers to point to new locations/names
3. Update the source file (remove extracted code, rename, etc.)
4. Delete old files last (only after all importers are updated)
5. Update index/barrel files

Read each file before editing. Make the minimal change needed — do not reformat unrelated code.

### Phase 4: VERIFY

Run typecheck and tests from Phase 1. Compare against baseline — any NEW errors or failures? Search for import paths referencing old/deleted files.

```
Verification: PASS
  Typecheck: {pass | same N pre-existing errors}
  Tests: {pass | same N pre-existing failures}
  No new broken imports detected.
```

### Phase 5: FIX (if verification fails)

Two attempts: read errors, identify root cause (missed import update, missing re-export, type mismatch), fix, re-run verification. After 2 failed attempts: REVERT.

### Phase 6: REVERT (if fixes fail)

1. Use `git checkout -- [files]` to restore every modified file
2. Remove any newly created files
3. Verify the revert: typecheck should match baseline exactly
4. Report what went wrong

```
REVERTED — Refactoring could not be completed cleanly.

Root cause: {why the refactoring failed}
Errors encountered:
  - {error 1}
  - {error 2}

Suggestion: {what the user might do differently}
```

## Fringe Cases

- **No test baseline**: no test suite found in Phase 1 — output: "No tests found. Refactor proceeds without a safety net — abort or continue? Recommend running /test-gen first." Wait for user confirmation before continuing.
- **Baseline typecheck fails**: typecheck errors exist before any refactor changes — output: "Baseline typecheck failed. Fix existing type errors before refactoring to establish a clean baseline." Do not proceed.
- **Build fails after refactor commit**: Phase 4 build regression detected — revert the commit with `git revert HEAD --no-edit`, then report which verification step introduced the regression and what the failing error is.
- **Circular dependency detected**: import cycle surfaces during scope analysis — treat as a blocker; output: "Circular dependency detected in [file]. Resolve the cycle before proceeding." Do not modify that file without explicit user decision.
- **Target file exceeds 500 lines**: output: "Warning: [file] is [N] lines. Refactoring may split this file into multiple pieces. Confirm scope before proceeding." Show the proposed split in the plan and wait for user approval.

## Quality Gates

- **Zero new type errors** — zero NEW ones, not just fewer.
- **Zero new test failures** — baseline failures accepted, new failures are not.
- **All imports resolve** — no dangling references to old paths or removed exports.
- **Behavior unchanged** — adding logic or changing return values is scope creep; stop and do it separately.
- **Minimal diff** — no reformatting, unrelated cleanups, or whitespace changes in untouched files.
- **Plan matches execution** — every planned file modified, no unplanned files touched.

## Exit Protocol

Report the result:

```
=== Refactor Report ===

Type: {rename | extract | inline | move | split | merge}
Target: {what was refactored}

Changes:
  Modified: {N} files
  Created: {N} files
  Deleted: {N} files

Verification:
  Typecheck: {pass | same baseline errors}
  Tests: {pass | same baseline failures | no test suite}

Key decisions:
- {any non-obvious choices made during execution}
```

```
---HANDOFF---
- Refactored {target}: {what changed}
- {N} files modified, {N} created, {N} deleted
- Typecheck and tests pass (no regressions)
- {any follow-up suggestions}
- Reversibility: green -- single atomic commit, revert with git revert HEAD
---
```

© SethGammon · MIT · SethGammon/Citadel

Similar skills

All skills for Code review and refactoring →

refactor by other authors comes first.

refactor official github The refactor skill reshapes existing code without changing its external behavior. Use it for gradual cleanup of large functions, duplication, weak types, and code smells. CX Codex +1 22,321installs refactor parcadei refactor is a Claude Code skill that guides code changes through analysis, planning, implementation, review, and test validation. It activates for refactoring requests that should preserve existing behavior. CX Codex +1 625installs refactor smallnest refactor restructures code safely based on Martin Fowler's catalog without altering external behavior. Fixes code smells through small, verifiable steps. CX Codex +1 538installs refactor boshu2 refactor — a Claude Code skill for restructuring code without changing observable behavior. Runs on requests to clean up, extract functions, remove dead code, or simplify logic. CX Codex +1 123installs refactor pproenca A skill with 43 refactoring rules drawn from Martin Fowler's catalog and Clean Code. Useful when you want the agent to restructure code by a fixed set of rules instead of guessing. CX Codex +1 661installs refactor-guided CloudAI-X refactor-guided guides structural refactoring in small steps and runs tests after each change. It keeps feature work separate from code restructuring. CX Codex +1 ★ 1,424repo stars refactor-clean sangrokjung The refactor-clean command finds unused code, proposes cautious deletions, and checks the test suite around every change. CX Codex +1 ★ 880repo stars refactor-plan official github This skill investigates a codebase and writes a step-by-step multi-file refactor plan before edits begin. Use it when the proposed change needs review first. CX Codex +1 12,965installs review-and-refactor official github review-and-refactor reviews project code against local instructions and refactors parts that need changes. Use it before review or when cleaning up an existing codebase. CX Codex +1 11,056installs w-refactor blockmatic-icebox The w-refactor Claude Code skill restructures selected code while preserving its behavior. It starts by recording a baseline with tests, type checks, or a manual scenario. CX Codex +1 647installs refactor-legacy-code aj-geddes refactor-legacy-code guides systematic legacy code refactoring without breaking features. Built for paying down technical debt and replacing deprecated patterns. CX Codex +1 611installs

From the same set55

The whole set →
workspace workspace coordinates changes across multiple repositories in a single task. Breaks work into waves, runs campaigns per repo, verifies contracts between them. CX Codex +1 ★ 937repo stars create-skill create-skill interviews you about a recurring workflow, compiles it into a structured SKILL.md file, and tests it against real project files. CX Codex +1 ★ 937repo stars arbiter arbiter is a Claude Code subagent that reruns project checks and gives a final verdict on changes. It steps in after a worker runs out of retries or when a run needs a holistic completion review. CX Codex ★ 937repo stars infra-audit infra-audit maps a project's databases, caches and queues from docker-compose, env files and ORM configs, then flags infrastructure layers that look missing. CX Codex +1 ★ 937repo stars review This skill reviews code in five passes, covering correctness, security, performance, readability, and consistency. Use it on a file, directory, or Git diff. CX Codex +1 ★ 937repo stars schedule Schedules recurring and one-off agent runs: by default it writes a native Task Scheduler or cron entry instead of spending routine quota. CX Codex +1 ★ 937repo stars qa qa launches a real Chromium browser, clicks UI elements, tests frontend user flows, and writes a report with screenshots. CX Codex +1 ★ 937repo stars scaffold scaffold studies existing files before generating new ones, then connects them to registration points the project already uses. It fits codebases with established patterns. CX Codex +1 ★ 937repo stars

Project sponsors

Companies that keep this analytics open