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

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

Скилл refactor для Claude Code реорганизует код без изменения логики с проверкой тестами до и после правок. Включается по запросу на очистку, дедупликацию или вынесение функции.

Apache-2.0 123 установок ★ 458 обновлён 2026-11-13

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add boshu2/agentops --skill refactor -a claude-code
Открыть на GitHub

Что делает refactor

Скилл выполняет ровно одну выбранную трансформацию: выделение функции, перенос, инлайнинг или удаление мёртвого кода. Он сверяет поведение программы: байт в байт сравнивает тексты ошибок, хэши сгенерированного вывода и коды возврата.

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

При отсутствии тестов или среды выполнения скилл выводит точные команды для ручной сверки и помечает непроверенные границы в секции not checked. Он не делает коммитов и не пытается откатывать изменения при падении тестов.

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

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

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

  • Вынеси дублирующуюся валидацию из auth.py в отдельную функцию и проверь тесты
  • Упрости условия в calculate_total без изменения поведения и покажи хэши вывода
  • Удали мёртвый код в модуле экспорта и подтверди сохранение контрактов

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

1Через Skills CLI (Vercel)

npx skills add boshu2/agentops --skill refactor -a claude-code

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

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

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

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

Вопросы о refactor

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

Для установки выполните команду npx skills add boshu2/agentops --skill refactor -a claude-code. Также можно разместить файл скилла по пути ~/.claude/skills/refactor/SKILL.md.

Что делает refactor?

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

Что делает скилл при обнаружении бага в коде?

Он не исправляет найденную ошибку внутри рефакторинга. Скилл указывает файл, строку и причину в отчёте, оставляя исправление на усмотрение разработчика.

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

SKILL.md · Apache-2.0
---
name: refactor
description: 'Restructure or clean up code with no behavior change, proved by before-and-after checks. Use when: asked to clean up, extract, dedupe or simplify, even one function.'
practices:
- refactoring
- legacy-code-seams
- design-patterns
hexagonal_role: supporting
consumes:
- repo-context
produces:
- code-changes
context_rel: []
skill_api_version: 1
user-invocable: true
metadata:
  capabilities: [refactor]
  effects: [modify_source_files]
  canonical_status: canonical
  disposition: keep_specialist
  tier: execution
  dependencies: []
output_contract: code changes with regression evidence
---
# Refactor — one structural experiment

Refactor changes structure while preserving observable behavior. It performs one
caller-selected transformation and reports the result. "Behavior-preserving" is
a claim to prove with before/after checks, never to assert. A user sees it
worked when the report shows the same checks run before and after with
identical results, and any suspected bug listed unfixed.

## What counts as behavior

Unless the caller explicitly excluded a surface, all of these must survive:

- **Messages and exit codes.** Error and output text compares byte-for-byte;
  exit codes, error types and which input raises which error stay the same.
  Scripts and callers parse them. Preserve an inconsistent message and report
  it; normalizing it is a behavior change.
- **Differences between near-duplicates.** When merging duplicated branches,
  carry every difference (constants, comparisons, messages, extra steps) as a
  parameter or a branch. Do not unify a difference the caller has not declared
  accidental.
- **Interfaces.** Public signatures, defaults, return types, persisted field
  names, protocol values and CLI flags. Renaming one is a compatibility change
  unless the accepted scope provides for it.
- **Order and coverage.** Branch priority, default handling, evaluation count,
  side-effect order, and the set of tests that run. A pre-existing red that
  vanishes, or a test that stops running, is a behavior change.
- **Protective checks.** Trust-boundary validation, data-loss guards, security
  controls and accessibility affordances stay, even when another layer,
  upstream or downstream, duplicates one or no test reaches it. The neutrality
  gates cannot see their removal, so looking redundant is no reason to delete
  one.

## Procedure

1. Name the preserved behavior, the focused acceptance surface and the concrete
   structural problem for its callers, in the caller's domain terms.
2. Run the focused check and the smallest regression check the changed surface
   justifies, error paths included, and record that honest baseline, including
   reproducible ambient failures. Add any characterization test the
   transformation needs now, before the edit, so it is part of the baseline.
   For output-producing surfaces (generators, serializers, formatters,
   reports), hash the output over fixed inputs. When the caller's evaluation
   compares the built program before and after the change, pin the starting
   source, build its baseline before edits and keep that binary and the
   comparison inputs.
3. Apply one bounded transformation: extract, move, rename, inline, simplify a
   conditional, reduce parameters, encapsulate, substitute existing code, or
   delete dead code; the
   [refactoring catalog](references/behavior-preserving-simplification.md#refactoring-catalog)
   holds per-pattern safety checks. Judge it by what callers must
   understand and where a domain rule must change, not by file size.
4. A bug or suspicious inconsistency found on the way is reported separately
   (location, why it looks wrong) and left unfixed. Fixing it inside the
   refactor hides a behavior change the caller did not authorize.
5. Rerun exactly the step-2 checks over the same inputs and compare any
   output hashes byte-for-byte.
6. Report, then stop. A red result is evidence for the caller; this skill does
   not revert, narrow, retry, commit, validate, or route subsequent work.

When nothing can be executed (no runtime, no tests, code supplied in a
message), neutrality is unproven: give the exact before/after commands and
inputs the caller must run, error paths included, and list every surface under
`not checked`.

```text
transformation: <the one change>
preserved:      <behavior and surfaces from step 1>
checks:         <command>: before -> <result>; after -> <result>   (or "not run")
outputs:        <before/after hashes when the surface produces output>
abstraction:    <a new one and the second use or contract that justifies it, or "none">
diff:           <files touched>; only those the transformation names, plus tests added before the change
suspected bugs: <file:line, why>; reported, not fixed
not checked:    <surfaces no check covered>; present even when empty
```

## Neutrality gates

The checks from step 2 give the same result after as before: no new red, no
vanished red, identical output hashes. A mismatch is a behavior diff to surface
and explain, never to shrug at; the caller decides whether to keep, narrow, or
reverse it. A gate skipped or narrowed after the fact is the **post-hoc
neutrality** failure mode — the diff decides what got tested. Name any surface
the gates did not cover under `not checked`.

## Boundaries and tests

Refactoring after a check goes green is the step of test-driven development
that held for agents
([practice ledger](https://github.com/boshu2/agentops/blob/main/docs/practice-ledger.md#holds-in-a-different-shape)).

- Use [Implement](../implement/SKILL.md) to change behavior; it tidies its own
  fresh change under its acceptance checks.
- Use Refactor when restructuring is the request, or reaches code the behavior
  change did not touch; that green result is the baseline.
- Use [Architecture](../architecture/SKILL.md#procedure) to choose where to
  restructure or a new module boundary; this skill executes one transformation
  in the area the caller selected.

Reject a wrapper that only adds another name or pushes the same coordination into its callers. Keep
internal test seams private when callers need no substitution. Exercise the
preserved behavior through the caller-facing boundary; retain existing tests
until equivalent coverage of their distinct cases is demonstrated. Moving a
test is not permission to delete the behavior it protected.

Use the caller's vocabulary for extracted operations and types. A naming
ambiguity that changes behavior belongs with the existing domain definition;
consult [Domain](../domain/SKILL.md) only when that distinction needs work.

When the caller-chosen transformation can be cut more than one way (which
lines an extraction takes, where a chosen interface sits), probe before you
cut. A choice between module boundaries the caller has not made goes to
Architecture first.
Run the probe in disposable isolation (a scratch branch, worktree, or copied
tree the caller's policy allows): rough in the seam, see what it forces —
signature churn, import cycles, test rewrites — then discard the probe and
keep only the knowledge. Stop condition: at most two probes; if the second
candidate seam also fights back, report both findings to the caller instead of
trying a third. Cutting the first imaginable seam directly into the working
tree is the **premature seam** failure mode: the wrong boundary calcifies
because reverting it now costs more than living with it.

## References

- [Behavior-preserving simplification](references/behavior-preserving-simplification.md) — refactoring catalog and per-pattern safety checks
- [Codebase design](https://github.com/mattpocock/skills/blob/main/skills/engineering/codebase-design/SKILL.md) — Matt Pocock; the wrapper and test-seam rules under Boundaries and tests adapt it.

© boshu2 · Apache-2.0 · boshu2/agentops

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

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

Сначала — 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 pproenca Скилл refactor для Claude Code содержит 43 правила рефакторинга по каталогу Мартина Фаулера и принципам Clean Code. Агент применяет их при правке чужого кода. CX Codex +1 661установок refactor FradSer Скилл refactor запускает автоматический рефакторинг выбранных файлов, папок или недавних правок через агента упрощения кода. CX Codex +1 113установок oma-refactor First Fluke Скилл oma-refactor для Claude Code и Codex перестраивает структуру кода без изменений в его наблюдаемом поведении. Проводит точечный рефакторинг техдолга и горячих точек через мелкие проверенные шаги. CX Codex +1 ★ 1 472звёзд репо refactor-expert alirezarezvani Субагент refactor-expert для Claude Code анализирует качество кода и планирует безопасный рефакторинг. Ищет дублирование, архитектурные проблемы и пробелы в тестах. CX Codex ★ 788звёзд репо code-refactoring akillness Скилл code-refactoring помогает спланировать рефакторинг без изменения поведения: от фиксации текущих гарантий до небольших проверяемых шагов. CX Codex +1 552установок refactor-code davila7 Слэш-команда refactor-code ведёт агента по 17 шагам рефакторинга: от анализа и тестов до проверки производительности и подготовки к ревью. CX Codex +1 4 890установок safe-refactor JuliusBrussee Скилл safe-refactor ограничивает рефакторинг сохранением поведения: фиксирует проверки до правок кода, запрещает смешивать перенос структуры с новыми фичами. CX Codex +1 130 700установок refactor-project FradSer Скилл refactor-project для Claude Code, Codex, Cursor и других агентов запускает автоматический рефакторинг сразу по всем файлам проекта. Находит дубли, выравнивает стиль и убирает устаревший код за один прогон. CX Codex +1 122установок

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

council Скилл council для Claude Code собирает независимые мнения нескольких контекстов и сводит согласия и разногласия. Запускается для обсуждения вариантов, разбора плана или обобщения нескольких ревью. CX Codex +1 3 100установок rpi Доводит согласованную задачу до финала через реализацию и тесты без лишнего планирования. Включается при просьбе провести работу по методике RPI. CX Codex +1 1 500установок implement Скилл implement для Claude Code вносит изменения по задаче и проверяет результат командами репозитория. Запускается по просьбе исправить баг, изменить или создать код. CX Codex +1 1 500установок plan Скилл plan превращает размытый запрос в один сквозной срез с наблюдаемым результатом. Запускается при планировании, декомпозиции и ограничении объёма изменений. CX Codex +1 1 500установок research Скилл research для Claude Code отвечает на вопросы о коде и истории изменений с опорой на цитируемые источники. Подключается, когда нужно проверить заявление о готовности работы или понять, заслуживает ли повторяющийся паттерн правила. CX Codex +1 1 500установок security Скилл security проверяет код, зависимости, секреты и поверхности промптов на риски безопасности. Запускайте его для ревью перед выпуском или проверки проекта. CX Codex +1 1 400установок

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

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