refactor-guided — команда для Claude Code: рефакторинг
Команда refactor-guided проводит структурный рефакторинг по шагам и проверяет тесты после каждого изменения. Подходит для безопасной перестройки кода без добавления функций.
MIT ★ 1 424 обновлён 2026-10-06
.claude/commands/refactor-guided.mdЧто делает refactor-guided
Команда сначала определяет область изменений: целевые файлы, зависимости, зависимые модули и возможный радиус затрагивания. Затем проверяет существующие тесты, при необходимости добавляет покрытие текущего поведения и фиксирует исходный результат.
Рефакторинг идёт небольшими шагами. После каждого изменения команда запускает тесты, при успехе создаёт отдельный коммит с префиксом refactor:, а при сбое откатывает попытку и разбирает причину. Она умеет извлекать функции, переименовывать элементы, убирать дублирование, упрощать условия и разделять крупные файлы.
При незакоммиченных изменениях команда остановится и попросит решить, что с ними делать, поэтому чистое рабочее дерево нужно подготовить заранее. Для работы используются git, менеджеры пакетов, тестовые команды и инструменты чтения и редактирования файлов.
Какие задачи решает
- разбить крупный файл или функцию на части
- переименовать элементы без изменения внешнего поведения
- убрать дублирование в коде
- проверить рефакторинг тестами после каждого шага
- зафиксировать структурные изменения отдельными коммитами
Примеры запросов агенту
- Запусти
/refactor-guidedдля анализа последних изменённых файлов и предложи безопасные шаги рефакторинга. - Запусти
/refactor-guidedи вынеси повторяющуюся логику изsrc/orders.tsв отдельную функцию. - Запусти
/refactor-guidedдля каталогаsrc/apiи проверяй тесты после каждого изменения.
Как установить refactor-guided
Вручную: положить файлы
.claude/commands/refactor-guided.mdВызов — /refactor-guided. Для всех проектов — ~/.claude/commands/
Вручную: положить файлы
~/.codex/prompts/refactor-guided.mdВызов — /prompts:refactor-guided. В Codex этот формат помечен устаревшим, замена — скиллы
Вручную: положить файлы
.github/prompts/refactor-guided.prompt.mdВручную: положить файлы
.gemini/commands/refactor-guided.tomlGemini хранит команды в TOML: текст запроса — в поле prompt
Вопросы о refactor-guided
Как установить refactor-guided в Claude Code?
Поместите файл команды в .claude/commands/refactor-guided.md. После этого вызовите её в Claude Code через /refactor-guided.
Что делает refactor-guided?
Команда анализирует область рефакторинга, проверяет тестовое покрытие и применяет структурные изменения по одному. После каждого шага она запускает тесты и создаёт отдельный коммит или откатывает неудачную попытку.
Что произойдёт, если в рабочем дереве есть незакоммиченные изменения?
Команда остановится и попросит пользователя решить, как с ними поступить. Она не будет самостоятельно прятать или коммитить эти изменения.
Исходный текст
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