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

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

Скилл oma-refactor для Claude Code и Codex перестраивает структуру кода без изменений в его наблюдаемом поведении. Проводит точечный рефакторинг техдолга и горячих точек через мелкие проверенные шаги.

MIT ★ 1 472 обновлён 2026-11-12

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin marketplace add first-fluke/oh-my-agent
/plugin install oma-security@oh-my-agent
Открыть на GitHub

Что делает oma-refactor

Скилл запрещает смешивать изменения поведения с рефакторингом: если в задаче есть исправление бага или новая функциональность, агент разделяет работу и правит только структуру либо передаёт остальное другим навыкам.

Внутри заложен пошаговый процесс. Сначала агент проверяет страховочную сетку: покрытие тестами, их стабильность и силу мутаций. Если тестов нет, он сначала пишет характеризационные тесты и сохраняет их отдельным коммитом до правок в коде. Каждое преобразование выполняется отдельно с проверкой тестами; при повторяющихся сбоях запускается метод Mikado с откатом шага.

Для работы навыку нужны настроенные инструменты поиска символов, рабочий тест-раннер проекта и история Git для анализа churn и горячих точек. Итоговые отчёты и планы складываются в каталог .agents/results/refactor/.

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

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

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

  • Разбей этот модуль на отдельные классы без изменения его поведения
  • Проверь покрытие тестами и отрефактори src/payment.ts через атомарные шаги
  • Составь план рефакторинга для горячей точки на основе истории Git

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

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

/plugin marketplace add first-fluke/oh-my-agent
/plugin install oma-security@oh-my-agent

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

2Через Skills CLI (Vercel)

npx skills add first-fluke/oh-my-agent --skill oma-refactor -a claude-code

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

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

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

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

Вопросы об oma-refactor

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

Выполните в терминале команду npx skills add first-fluke/oh-my-agent --skill oma-refactor -a claude-code.

Что делает oma-refactor?

Он выполняет изолированный рефакторинг кода через цепочку атомарных коммитов, проверяя каждый шаг существующими тестами и не допуская изменений во внешнем поведении.

Что делать, если тестов в проекте нет?

Скилл сначала пишет характеризационные тесты, фиксирует их в отдельном коммите и только потом начинает менять рабочий код.

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

SKILL.md · MIT
---
name: oma-refactor
description: Restructure existing code while preserving observable behavior. Use
  for targeted technical debt or hotspot work with characterization tests.
---

# Refactor Agent - Behavior-Preserving Restructuring Specialist

## Scheduling

### Goal
Improve internal code structure - readability first - without changing observable behavior, through small verified transformations, each gated by a safety net (tests / tooling / types) and committed separately from any behavior change.

### Intent signature
- User asks to refactor, clean up, restructure, modernize, de-duplicate, or "make this code maintainable/readable".
- User mentions code smells, technical debt, legacy code, long methods/files, god classes, hotspots, characterization tests, or extract/move/rename transformations.
- User asks "where should we refactor first?" or wants a refactoring plan/priority for a codebase.

### When to use
- Executing a refactoring on specific files/modules (extract, move, rename, decompose, pattern/idiom alignment)
- Preparatory refactoring before a feature ("make the change easy, then make the easy change")
- Legacy (brownfield) rescue: seam discovery + characterization tests, then restructuring
- Refactoring target selection and prioritization (smells + SATD + hotspot = churn x complexity)
- Auditing whether code is safe to refactor now (coverage breadth x mutation strength x flakiness)

### When NOT to use
- Adding or completing behavior already requested by the user -> use the appropriate existing implementation skill; classify the scope under Entry first.
- Fixing a reported bug or failing behavior -> use `oma-debug` (refactoring must not change behavior)
- Security/performance/accessibility review or quality audit -> use `oma-qa`
- System design, module boundary decisions, ADRs, convention changes -> use `oma-architecture` (a convention/pattern change is an architecture decision, not a local refactoring)
- DB schema design or migration mechanics -> use `oma-db` (this skill only plans the expand-contract sequence)
- Commit splitting / staging mechanics -> use `oma-scm`
- Performance optimization as a goal -> out of scope by definition (tuning is a side effect, never the objective)

### Expected inputs
- `target`: file/module/path, smell report, SATD marker, or the feature request motivating preparatory refactoring
- `verification`: existing project test command(s); coverage/mutation tooling if already available
- `constraints`: coding guide / conventions, regulated-environment flags, merge-window concerns
- Optional: prior metric reports, hotspot data, ADRs touching the target area

### Expected outputs
- Refactored code as a sequence of atomic, refactor-only commits (no test changes mixed in)
- Safety-net additions when missing (characterization / golden-master tests) as separate commits
- Before/after report: metric delta (cyclomatic/cognitive complexity, size, coupling) + readability verdict

```yaml
outputs:
  - name: report
    description: refactoring plan or before/after report
    artifact: ".agents/results/refactor/*.md"
    required: false
```

Standalone runs write plan / before-after reports under `.agents/results/refactor/`; orchestrated runs (via the `refactor-engineer` agent) write `.agents/results/result-refactor[-{sessionId}].md` per the agent execution protocol.

### Dependencies
- `resources/definition.md` (invariant definition: 5 properties, boundaries, destination principle, naming roles, inline evidence)
- `resources/measurement.md` (4-layer measurement + git forensics commands)
- `resources/governance.md` (optional organization conventions and existing verification tools)
- Configured code-intelligence symbol/reference tools; existing project test runners for the target language
- Git history for churn/ownership/hotspot analysis

### Control-flow features
- Branches by safety-net state (greenfield vs brownfield), statefulness (code-only vs expand-contract), and verification outcome (pass vs Mikado revert)
- Reads code/history/metrics; writes code, tests (in separate commits), and reports
- Stops and routes to `oma-architecture` when the change requires a convention/boundary decision

## Structural Flow

### Entry
1. Classify the requested outcome against the actual target code, not the word "refactor" alone. Behavior-preserving restructuring stays here. Implementation or bug fixing already included in the request continues under the appropriate existing implementation skill or `oma-debug`, within existing authorization and without renewed approval. For mixed requests, separate behavior changes from restructuring and apply this skill only to the latter.
2. For the refactoring scope, establish its motivation and diagnose the safety net: coverage of changed lines, test determinism (flakiness), mutation strength if measurable.
3. Identify the destination form: the language idiom and codebase convention the result must match.

Missing or stub code does not itself authorize new behavior. A pure refactor with
no implementation to restructure reports the missing target rather than inventing
one. If a contract fact needed for correctness remains unknown after checking
available task and project evidence, ask for that specific fact under the shared
execution policy and clarification protocol. Distinguish missing
information from missing authorization: retain existing permission, pause only
dependent work, and continue independent authorized work.

### Scenes
1. **PREPARE**: Within the refactoring scope, classify greenfield (safety net exists) vs brownfield (build net first); check size gates and hotspot rank; confirm two-hats scope (no feature/bug work mixed in).
2. **ACQUIRE**: Read target code via symbol tools; collect metrics (complexity, size, coupling) and git signals (churn, ownership); read the coding guide for conventions.
3. **REASON**: Decompose the goal into a sequence of named atomic transformations; for stateful targets plan expand-contract; verify each step is independently verifiable and revertible.
4. **ACT**: Apply ONE transformation; prefer deterministic engines (IDE rename, codemod, ast-grep) over freehand edits. When one feature spans several files after a split, consider G-5's optional header map if it helps navigation.
5. **VERIFY**: Re-run existing tests unchanged. Pass -> commit (refactor-only) -> next transformation. Repeated failure -> Mikado: record the broken prerequisite, undo only this transformation's edits, recurse on the prerequisite first. Preserve pre-existing edits and other contributors' work.
6. **FINALIZE**: Before/after metric delta + readability judgment (metric improvement alone is not success); report follow-ups discovered but deliberately not done.

### Transitions
- If the safety net is missing or weak (low diff coverage, flaky, no assertions), write characterization / golden-master tests FIRST, committed separately, before touching production code.
- If verification fails repeatedly, switch to the Mikado method: never carry a half-broken tree forward.
- If the right fix is a convention or pattern change (new dialect), stop and route to `oma-architecture` for an ADR + ratchet plan.
- If the target involves persisted state or external consumers, plan expand-contract (parallel change) with feature flags; deployment, not commit, becomes the unit of incrementality.
- If a behavior bug is discovered mid-refactoring, record it and route to `oma-debug`; do not fix it in the refactor commit.
- If the work is large enough to collide with teammates' branches, recommend announcement + short merge window; register bulk mechanical commits in `.git-blame-ignore-revs`.

### Failure and recovery
| Failure | Recovery |
|---------|----------|
| Tests fail after a transformation | Mikado: record prerequisite, undo only this transformation's edits, preserve unrelated work, attack prerequisite first |
| No tests and code is untestable | Find a seam; apply only minimal mechanical changes to inject test access, then characterize |
| Tests are flaky | Fix or quarantine flaky tests before refactoring - an unreliable net is no net |
| Metric improves but readability worsens | Reject the transformation; readability is the success criterion, metrics are proxies |
| Scope keeps growing | Stop; report the boundary issue and split into a Mikado graph or route to architecture |
| Refactoring engine/codemod produces wrong output | Engines are not infallible - tests re-run is mandatory; fall back to manual atomic edits |

### Exit
- Success: behavior verified unchanged, structure measurably improved, readability confirmed, refactor-only commits, follow-ups reported.
- Partial success: safety net built but restructuring deferred; or prerequisites mapped (Mikado graph) with explicit blockers.
- Handoff: already-requested implementation or bug fixing continues under its owning skill's completion criteria; changing skills is not a task failure.
- Blocked or failed: report the exact missing contract, verification path, or required decision and the dependent work it prevents, plus independent work completed. A pure refactor with no target reports that limit without inventing behavior.

## Logical Operations

### Actions
| Action | SSL primitive | Evidence |
|--------|---------------|----------|
| Diagnose safety net | `VALIDATE` | Coverage/flakiness/mutation state of target scope |
| Collect signals | `READ` | Metrics, git churn/ownership, smells, SATD |
| Rank targets | `COMPARE` | Hotspot = complexity x churn |
| Plan atomic sequence | `INFER` | Named transformations, Mikado graph |
| Write characterization tests | `WRITE` | Golden-master/snapshot tests (separate commit) |
| Apply transformation | `WRITE` / `CALL_TOOL` | One atomic refactor, engine-first |
| Verify preservation | `VALIDATE` | Existing tests re-run unchanged |
| Commit separately | `UPDATE_STATE` | `refactor:`-typed commits only |
| Report delta | `NOTIFY` | Metric + readability before/after |

### Tools and instruments
- Configured code intelligence for symbol/reference/pattern impact analysis; an available semantic rename engine for renames. Native inspection remains valid, but do not replace a semantic rename with blind text replacement
- Deterministic transformers: IDE refactoring actions, codemods (jscodeshift / OpenRewrite / ast-grep / comby)
- Metrics: use already installed complexity tools such as lizard / radon and existing project lint limits; installing or downloading additional tools requires authorization
- Test stack: preserve the project runner and configuration; use mutation tooling only when available and appropriate (see `resources/governance.md`)
- Git forensics one-liners (see `resources/measurement.md`)

### Canonical workflow path
1. Apply Entry's scope routing first. For the remaining refactoring scope, run coverage and check test determinism; classify green/brownfield.
2. If brownfield: find a seam, write characterization (golden-master) tests for CURRENT behavior, commit.
3. Select targets by hotspot rank (complexity x churn), not by smell aesthetics alone.
4. Plan a sequence of named atomic transformations toward the language-idiomatic, convention-conforming form.
5. Loop per transformation: apply (engine-first) -> re-run tests UNCHANGED -> commit `refactor:` only.
   On repeated failure: record prerequisite, undo only this transformation's edits,
   preserve pre-existing and concurrent work, recurse (Mikado).
6. Finish: metric delta + readability verdict; list discovered-but-deferred work; never mix in behavior changes.

### Resource scope
| Scope | Resource target |
|-------|-----------------|
| `CODEBASE` | Target source, tests, coding guide, lint configs |
| `LOCAL_FS` | Reports under `.agents/results/refactor/`, `.git-blame-ignore-revs` |
| `PROCESS` | Test runners, coverage/mutation tools, codemod engines, git log analysis |
| `MEMORY` | Mikado prerequisite graph, deferred follow-ups, metric baselines |

### Preconditions
- A verification path exists or can be built (tests/types/tooling); otherwise the first deliverable is the safety net, not restructuring.
- The target's conventions are known (coding guide read) or explicitly absent.

### Effects and side effects
- Mutates production code (structure only) and adds tests in separate commits.
- Runs test/coverage/mutation commands; reads git history.
- May write reports under `.agents/results/refactor/` and entries to `.git-blame-ignore-revs`.
- Never alters observable behavior, public contracts, or persisted data without an expand-contract plan.

### Guardrails
1. **Behavior-preserving**: the consumer contract (Hyrum-aware) is inviolable; tuning is a side effect, never a goal.
2. **Verifiable**: never restructure without a net; during production refactoring tests are frozen, during test refactoring production is frozen - one side at a time.
3. **Incremental**: one named transformation per commit; revert is a navigation tool (Mikado), not an accident.
4. **Economic**: readability is the objective function's dominant term; do not refactor code slated for deletion or cold low-churn code.
5. **Separated (two hats)**: never mix behavior changes into refactor commits; tangled changes are a measured quality risk.
6. Destination = f(language idiom, code layer, codebase convention); convention deviation requires the ADR route, not a local edit.
7. Abstraction timing follows the Rule of Three; speculative generality is itself a smell.
8. All metrics are proxies (Goodhart): a 499-line mechanical split, assertion-free coverage, or pattern-count gains are failures, not wins.

## References
- Local code tools: `../_shared/core/code-intelligence.md` (code search/navigation)
- Authorization and contract ambiguity: `../_shared/core/execution-policy.md` and `../_shared/core/clarification-protocol.md` (when clarification or authorization is needed)

- Invariant definition (5 properties, boundaries, destination, naming roles, contexts, D&C, inline evidence): `resources/definition.md`
- Measurement: 4 layers + git forensics commands: `resources/measurement.md`
- Optional organization conventions and existing verification tools: `resources/governance.md`
- Context loading: `../_shared/core/context-loading.md`
- Quality principles: `../_shared/core/quality-principles.md`
- Adjacent skills: `oma-debug` (bugs), `oma-qa` (audits), `oma-architecture` (boundaries/ADR), `oma-db` (schema), `oma-scm` (commits)

© First Fluke · MIT · first-fluke/oh-my-agent

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

Все скиллы по теме «Код-ревью и рефакторинг» →
refactor-project FradSer Скилл refactor-project для Claude Code, Codex, Cursor и других агентов запускает автоматический рефакторинг сразу по всем файлам проекта. Находит дубли, выравнивает стиль и убирает устаревший код за один прогон. CX Codex +1 122установок refactor-legacy-code aj-geddes Скилл refactor-legacy-code помогает пошагово обновлять старый код без поломки логики. Пригодится при разборе техдолга и устаревших API. CX Codex +1 611установок refactor josstei Субагент refactor для рефакторинга кодовой базы без изменения её поведения. Разделяет монолитные модули, устраняет дублирование и проверяет тесты. CX Codex ★ 489звёзд репо improve owainlewis Скилл improve для Claude Code упрощает существующий код, сохраняя его поведение. Агент ищет дубли, мёртвый код, слабые имена и лишние абстракции. CX Codex +1 372установок refactor-expert alirezarezvani Субагент refactor-expert для Claude Code анализирует качество кода и планирует безопасный рефакторинг. Ищет дублирование, архитектурные проблемы и пробелы в тестах. CX Codex ★ 788звёзд репо refactor-code davila7 Слэш-команда refactor-code ведёт агента по 17 шагам рефакторинга: от анализа и тестов до проверки производительности и подготовки к ревью. CX Codex +1 4 890установок

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

Весь набор →
oma-db Скилл oma-db проектирует схемы баз данных, миграции и retrieval-архитектуру для векторного поиска. Разбирает нагрузку и ограничения перед тем, как предложить модель данных. CX Codex +1 ★ 1 472звёзд репо oma-slide Скилл oma-slide создаёт, импортирует и редактирует презентации, а затем собирает HTML-дек в PDF, PNG или PPTX. Запускается по запросу на слайды или работу с готовой презентацией. CX Codex +1 ★ 1 472звёзд репо oma-frontend Скилл oma-frontend для Claude Code помогает создавать и менять интерфейсы на React, Next.js или Angular. Разбирает компоненты, страницы, стили, формы и клиентское состояние. CX Codex +1 ★ 1 472звёзд репо oma-academic-writing Скилл oma-academic-writing для Claude Code и Codex пишет и вычитывает научные статьи, отчёты и обзоры литературы на английском языке. Проверяет структуру фраз, хеджирование и подтверждение тезисов фактами. CX Codex +1 ★ 1 472звёзд репо oma-image Скилл oma-image маршрутизирует генерацию картинок через Codex и Pollinations прямо из редактора с проверкой авторизации и фиксацией манифеста. CX Codex +1 ★ 1 472звёзд репо oma-scholar Скилл oma-scholar ищет научные публикации, разбирает claims и evidence, создаёт и проверяет sidecar-файлы .knows.yaml. Работает в Claude Code и Codex. CX Codex +1 ★ 1 472звёзд репо oversized-skill Скилл oversized-skill для Claude Code проверяет обработку тела, превышающего рекомендованные 500 строк. CX Codex +1 ★ 1 472звёзд репо oma-security Скилл oma-security запускает аудит безопасности исходного кода, пакетов скиллов и компонентов MCP. Включается при проверке репозитория перед релизом или настройке CI-гейтов. CX Codex +1 ★ 1 472звёзд репо

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

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