К основному содержанию
скилл CX Codex

refactor · sethgammon — скилл для Claude Code: что делает и как установить

Скилл refactor для Claude Code выполняет рефакторинг нескольких файлов с автооткатом через Git, проверкой типов и тестами до и после правок.

MIT ★ 937 обновлён 2026-10-29

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add SethGammon/Citadel
/plugin install citadel@citadel-local
Открыть на GitHub

Что делает refactor

Скилл проводит структурные изменения кодовой базы по строгому протоколу. Сначала он фиксирует базовое состояние: запускает проверку типов через npm run typecheck и выполняет тесты проекта. Если в коде уже есть ошибки типизации, скилл сразу остановит работу до их ручного исправления. Затем агент строит детальный план с поиском всех импортов и мест вызова.

Правки вносятся по очереди: сначала создаются новые файлы, затем обновляются ссылки на них, меняется исходный модуль и только в конце удаляются старые файлы. Такой порядок снижает риск поломки сборки на промежуточных шагах. Если после изменений появляются новые ошибки, скилл делает две попытки их исправить. При неудаче он откатывает всё дерево через git checkout.

Какие задачи решает

  • переименовать символ или модуль по всему проекту с обновлением путей
  • вынести компонент или функцию в отдельный файл
  • разбить разросшийся файл на логические части
  • встроить инлайном модуль обратно в места вызова

Примеры запросов агенту

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

Как установить refactor

1Через маркетплейс плагинов

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

Команда ставит плагин citadel целиком, со всеми его скиллами

2Через Skills CLI (Vercel)

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

3Вручную: положить файлы

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

Папка скилла целиком; для одного проекта — .claude/skills/refactor/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о refactor

Как установить refactor в Claude Code?

Сначала выполните команду /plugin marketplace add SethGammon/Citadel, затем запустите /plugin install citadel@citadel-local. Также можно установить скилл через npx skills add SethGammon/Citadel --skill refactor -a claude-code.

Что делает скилл refactor?

Он автоматизирует перенос, разделение или слияние файлов с обновлением зависимостей, сравнивая результаты тестов до и после изменений.

Что происходит при ошибках в тестах после рефакторинга?

Скилл делает две попытки исправить сломанные импорты или ошибки типов. Если проверки всё равно не проходят, он возвращает файлы в исходный вид через git checkout.

Исходный текст

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

Похожие скиллы

Все скиллы по теме «Код-ревью и рефакторинг» →

Сначала — refactor от других авторов.

refactor официальный github Скилл refactor для GitHub Copilot меняет структуру существующего кода без изменения его поведения. Помогает убирать дублирование, сложные функции и кодовые запахи. CX Codex +1 22 321установок refactor parcadei Скилл refactor для Claude Code проводит рефакторинг через анализ, план, реализацию, ревью и проверку тестов. Запускается на просьбы изменить структуру кода без смены его поведения. CX Codex +1 625установок refactor smallnest Скилл refactor для Claude Code пошагово перестраивает структуру кода по каталогу Мартина Фаулера без изменения поведения. Помогает устранять запахи кода и разбивать разросшиеся функции. CX Codex +1 538установок refactor boshu2 Скилл refactor для Claude Code реорганизует код без изменения логики с проверкой тестами до и после правок. Включается по запросу на очистку, дедупликацию или вынесение функции. CX Codex +1 123установок refactor pproenca Скилл refactor для Claude Code содержит 43 правила рефакторинга по каталогу Мартина Фаулера и принципам Clean Code. Агент применяет их при правке чужого кода. CX Codex +1 661установок refactor-guided CloudAI-X Команда refactor-guided проводит структурный рефакторинг по шагам и проверяет тесты после каждого изменения. Подходит для безопасной перестройки кода без добавления функций. CX Codex +1 ★ 1 424звёзд репо refactor-clean sangrokjung Команда refactor-clean ищет мёртвый код, предлагает безопасное удаление и проверяет тесты до и после каждого изменения. CX Codex +1 ★ 880звёзд репо refactor-plan официальный github Скилл refactor-plan изучает кодовую базу и готовит пошаговый план многофайлового рефакторинга до правок. Подходит, когда изменения нужно согласовать заранее. CX Codex +1 12 965установок review-and-refactor официальный github Скилл review-and-refactor проверяет код проекта по локальным инструкциям и рефакторит участки, которым нужна правка. Подходит перед ревью или очисткой существующего кода. CX Codex +1 11 056установок w-refactor blockmatic-icebox Скилл w-refactor для Claude Code помогает менять структуру кода, сохраняя его поведение. Перед правками он предлагает зафиксировать исходное поведение тестами, проверками типов или ручным сценарием. CX Codex +1 647установок refactor-legacy-code aj-geddes Скилл refactor-legacy-code помогает пошагово обновлять старый код без поломки логики. Пригодится при разборе техдолга и устаревших API. CX Codex +1 611установок

Из того же набора55

Весь набор →
workspace Скилл workspace координирует изменения в нескольких репозиториях в рамках одной задачи. Разбивает работу на волны, запускает кампании по репозиториям, проверяет контракты между ними. CX Codex +1 ★ 937звёзд репо create-skill Скилл create-skill интервьюирует разработчика и упаковывает повторяющийся сценарий в готовый SKILL.md с проверкой на реальном коде проекта. CX Codex +1 ★ 937звёзд репо arbiter arbiter — субагент для Claude Code, который повторно запускает проверки проекта и выносит итоговый вердикт по изменениям. Его подключают после исчерпания повторных попыток рабочего агента или для оценки целостности результата. CX Codex ★ 937звёзд репо infra-audit Скилл infra-audit сканирует docker-compose, env-файлы, ORM-конфиги и строки подключения, чтобы собрать карту инфраструктуры проекта и найти, какого слоя не хватает. CX Codex +1 ★ 937звёзд репо review Скилл review проводит код-ревью в пять проходов: проверяет корректность, безопасность, производительность, читаемость и согласованность кода. Подходит для проверки файла, каталога или изменений Git. CX Codex +1 ★ 937звёзд репо schedule Ставит повторяющиеся и разовые задачи по cron: по умолчанию пишет запись в Task Scheduler или Unix cron, а не расходует квоту routine-запусков. CX Codex +1 ★ 937звёзд репо qa Скилл qa запускает браузер через Playwright, проходит пользовательские сценарии веб-приложения и сохраняет отчёт со скриншотами. CX Codex +1 ★ 937звёзд репо scaffold Скилл scaffold для Claude Code изучает структуру и стиль проекта, создаёт новые файлы по похожим примерам и добавляет их в существующие точки регистрации. CX Codex +1 ★ 937звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой