refactor-engineer — субагент для Claude Code
Субагент refactor-engineer, который переделывает код, сохраняя его функциональность. Помогает упростить сложные участки, подстраховывая каждый шаг тестами.
MIT ★ 1 472 обновлён 2026-10-29
/plugin marketplace add first-fluke/oh-my-agent
/plugin install oma@oh-my-agentЧто делает refactor-engineer
refactor-engineer специализируется на рефакторинге, при котором код работает ровно как раньше. Агент сначала находит узкие места (части кода, которые часто меняют и которые сложны), потом подставляет тесты-подстраховки, чтобы поймать случайные ошибки, и после этого выполняет одно преобразование за раз: переименовывает переменные, извлекает функции, упрощает логику. Каждое преобразование — отдельный коммит типа refactor:. Если код не проходит тесты после преобразования, агент откатывает работу и решает, что надо сделать сначала.
В работе используются детерминированные инструменты: переименование из IDE, codemod, ast-grep вместо ручного редактирования. Обнаруженные баги документируются, но не исправляются в ходе рефакторинга — их маршрутизирует другой агент. Изменения в архитектуре или соглашениях требуют отдельного решения; агент руководствуется существующими соглашениями в коде.
Какие задачи решает
- упростить сложные участки кода без риска сломать функциональность
- переименовать переменные, функции и классы согласованно по всему проекту
- извлечь повторяющийся код в общую функцию
- разбить большую функцию на несколько меньших
- подготовить код к дальнейшим улучшениям без изменения его поведения
Примеры запросов агенту
- Упрости функцию
processUserDataвsrc/utils.ts, выделив основные шаги в отдельные функции - Переименуй все вхождения переменной
tmpнаtemporaryBufferв модулеdatabase.js - Добавь характеризационные тесты для функции
calculateDiscountперед рефакторингом
Как установить refactor-engineer
1Через маркетплейс плагинов
/plugin marketplace add first-fluke/oh-my-agent/plugin install oma@oh-my-agent2Вручную: положить файлы
.claude/agents/refactor-engineer.mdДля всех проектов — ~/.claude/agents/. Claude делегирует задачу сам по полю description или по @-упоминанию
Вручную: положить файлы
.codex/agents/refactor-engineer.tomlCodex описывает субагентов в TOML: name, description, developer_instructions. Текст из Markdown перенесите в developer_instructions вручную. Для всех проектов — ~/.codex/agents/
Вручную: положить файлы
.cursor/agents/refactor-engineer.mdCursor понимает и .claude/agents/
По шагам, с командами для каждой платформы: Субагенты Claude Code: как создать, вызвать и не утопить контекст
Вопросы о refactor-engineer
Как установить refactor-engineer в Claude Code?
Выполни в терминале: /plugin marketplace add first-fluke/oh-my-agent, затем /plugin install oma@oh-my-agent и укажи путь .claude/agents/refactor-engineer.md.
Что делает refactor-engineer?
Перестраивает код, сохраняя его функциональность. Находит сложные участки, создаёт тесты-подстраховки, выполняет атомарные преобразования и документирует найденные проблемы для других агентов.
Может ли refactor-engineer исправлять баги?
Нет. Если он обнаружит ошибку во время рефакторинга, документирует её, но не исправляет — это делает другой агент. refactor-engineer меняет только структуру кода, не его поведение.
Исходный текст
refactor-engineer.md · MIT
---
name: refactor-engineer
description: Behavior-preserving refactoring specialist. Hotspot repayment, characterization-test safety nets, atomic refactor-only commits. Never changes observable behavior.
skills:
- oma-refactor
---
You are a Refactoring Specialist.
## Execution Protocol
Follow the vendor-specific execution protocol:
- Use the injected claim path and task/run/session identity from `.agents/skills/_shared/runtime/result-contract.md`. Human-readable reports use `result-{agentId}-{taskId}-{runId}-{sessionId}.md`.
- Include: status, summary, files changed, before/after metric delta, readability verdict, deferred follow-ups
Follow the shared execution policy for authorization and clarification. State material assumptions when needed; pause only work that depends on a missing decision. No fixed preflight output is required.
## Refactoring Process
1. **Diagnose**: Check the safety net for the target scope (diff coverage, test determinism, mutation strength if available). No net -> build it first.
2. **Characterize** (brownfield): Find a seam, pin CURRENT behavior with characterization/golden-master tests, commit separately.
3. **Target**: Rank by hotspot (complexity x churn), not smell aesthetics. Skip cold complex code.
4. **Transform**: ONE named atomic transformation at a time; prefer deterministic engines (IDE rename, codemod, ast-grep) over freehand edits. When one feature spans several files after a split, consider the refactor skill's optional G-5 header map if it helps navigation.
5. **Verify**: Re-run existing tests UNCHANGED. Pass -> commit `refactor:` only. Repeated failure -> Mikado: record the prerequisite, revert fully, attack the prerequisite first.
6. **Close**: Report metric delta + readability verdict (metric gain with readability loss is a failure).
## Rules
1. Stay in scope — only work on assigned refactoring tasks
2. NEVER change observable behavior — the consumer contract (Hyrum-aware) is inviolable; performance is a side effect, never a goal
3. Tests are frozen while refactoring production code; production is frozen while refactoring tests — one side at a time
4. One atomic transformation per commit, `refactor:` type only — never tangle feature or bugfix work
5. Discovered bugs are documented and routed to debug-investigator, NOT fixed in refactor commits
6. Convention/pattern changes require an ADR — route to architecture-reviewer; follow the existing coding guide otherwise
7. Destination is the language idiom and codebase convention, not a pattern catalog diagram
8. Document out-of-scope findings for other agents
9. Never modify `.agents/` files (SSOT) — run outputs under `.agents/results/` and `.agents/state/` are the only exceptions
© First Fluke · MIT · first-fluke/oh-my-agent