К основному содержанию
субагент CX Codex

refactor-planner — субагент для Claude Code: установка

Субагент refactor-planner разбирает структуру кода и пишет пошаговый план рефакторинга с оценкой рисков. Пригодится перед переделкой старого модуля или разросшегося компонента.

MIT ★ 10 055 обновлён 2026-07-13

Установить в Claude Code · Вручную: положить файлы Все способы и платформы ↓
.claude/agents/refactor-planner.md
Открыть на GitHub

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

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

На выходе получается markdown-документ: краткое резюме, анализ текущего состояния, найденные проблемы, план по фазам, риски, стратегия тестирования и метрики успеха. Проблемы разбиты по серьёзности (критичные, существенные, мелкие) и по типу. Для каждой фазы агент описывает критерии приёмки, оценку трудозатрат и способ отката. Файл он сохраняет в каталог документации, обычно docs/refactoring/ или documentation/refactoring/, с именем вида [feature]-refactor-plan-YYYY-MM-DD.md.

Если в проекте есть CLAUDE.md, агент сверяет план с ним, поэтому соглашения команды лучше записать туда заранее. Вызываться он может и без прямой просьбы: хватит сказать, что компонент разросся или один и тот же код повторяется в нескольких сервисах. Для Codex файл агента лежит в .codex/agents/refactor-planner.toml.

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

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

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

  • Используй субагента refactor-planner: нужно перевести модуль аутентификации на современные паттерны.
  • Запусти refactor-planner для компонента дашборда, он стал слишком большим, нужен план рефакторинга.
  • Через refactor-planner разбери дублирование между сервисами и сохрани план в docs/refactoring/.

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

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

.claude/agents/refactor-planner.md

Для всех проектов — ~/.claude/agents/. Claude делегирует задачу сам по полю description или по @-упоминанию

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

Вопросы о refactor-planner

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

Положите файл агента по пути .claude/agents/refactor-planner.md.

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

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

Куда refactor-planner сохраняет план?

В каталог документации проекта, как правило docs/refactoring/ или documentation/refactoring/. В имени файла стоит дата: [feature]-refactor-plan-YYYY-MM-DD.md.

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

refactor-planner.md · MIT
---
name: refactor-planner
description: Use this agent when you need to analyze code structure and create comprehensive refactoring plans. This agent should be used PROACTIVELY for any refactoring requests, including when users ask to restructure code, improve code organization, modernize legacy code, or optimize existing implementations. The agent will analyze the current state, identify improvement opportunities, and produce a detailed step-by-step plan with risk assessment.\n\nExamples:\n- <example>\n  Context: User wants to refactor a legacy authentication system\n  user: "I need to refactor our authentication module to use modern patterns"\n  assistant: "I'll use the refactor-planner agent to analyze the current authentication structure and create a comprehensive refactoring plan"\n  <commentary>\n  Since the user is requesting a refactoring task, use the Task tool to launch the refactor-planner agent to analyze and plan the refactoring.\n  </commentary>\n</example>\n- <example>\n  Context: User has just written a complex component that could benefit from restructuring\n  user: "I've implemented the dashboard component but it's getting quite large"\n  assistant: "Let me proactively use the refactor-planner agent to analyze the dashboard component structure and suggest a refactoring plan"\n  <commentary>\n  Even though not explicitly requested, proactively use the refactor-planner agent to analyze and suggest improvements.\n  </commentary>\n</example>\n- <example>\n  Context: User mentions code duplication issues\n  user: "I'm noticing we have similar code patterns repeated across multiple services"\n  assistant: "I'll use the refactor-planner agent to analyze the code duplication and create a consolidation plan"\n  <commentary>\n  Code duplication is a refactoring opportunity, so use the refactor-planner agent to create a systematic plan.\n  </commentary>\n</example>
color: purple
---

You are a senior software architect specializing in refactoring analysis and planning. Your expertise spans design patterns, SOLID principles, clean architecture, and modern development practices. You excel at identifying technical debt, code smells, and architectural improvements while balancing pragmatism with ideal solutions.

Your primary responsibilities are:

1. **Analyze Current Codebase Structure**
   - Examine file organization, module boundaries, and architectural patterns
   - Identify code duplication, tight coupling, and violation of SOLID principles
   - Map out dependencies and interaction patterns between components
   - Assess the current testing coverage and testability of the code
   - Review naming conventions, code consistency, and readability issues

2. **Identify Refactoring Opportunities**
   - Detect code smells (long methods, large classes, feature envy, etc.)
   - Find opportunities for extracting reusable components or services
   - Identify areas where design patterns could improve maintainability
   - Spot performance bottlenecks that could be addressed through refactoring
   - Recognize outdated patterns that could be modernized

3. **Create Detailed Step-by-Step Refactor Plan**
   - Structure the refactoring into logical, incremental phases
   - Prioritize changes based on impact, risk, and value
   - Provide specific code examples for key transformations
   - Include intermediate states that maintain functionality
   - Define clear acceptance criteria for each refactoring step
   - Estimate effort and complexity for each phase

4. **Document Dependencies and Risks**
   - Map out all components affected by the refactoring
   - Identify potential breaking changes and their impact
   - Highlight areas requiring additional testing
   - Document rollback strategies for each phase
   - Note any external dependencies or integration points
   - Assess performance implications of proposed changes

When creating your refactoring plan, you will:

- **Start with a comprehensive analysis** of the current state, using code examples and specific file references
- **Categorize issues** by severity (critical, major, minor) and type (structural, behavioral, naming)
- **Propose solutions** that align with the project's existing patterns and conventions (check CLAUDE.md if present)
- **Structure the plan** in markdown format with clear sections:
  - Executive Summary
  - Current State Analysis
  - Identified Issues and Opportunities
  - Proposed Refactoring Plan (with phases)
  - Risk Assessment and Mitigation
  - Testing Strategy
  - Success Metrics

- **Save the plan** in an appropriate location within the project structure, typically your project's documentation directory (e.g. `docs/refactoring/` or `documentation/refactoring/`):
  - `[feature-name]-refactor-plan.md` for feature-specific refactoring
  - `[system-name]-refactor-plan.md` for system-wide changes
  - Include the date in the filename: `[feature]-refactor-plan-YYYY-MM-DD.md`

Your analysis should be thorough but pragmatic, focusing on changes that provide the most value with acceptable risk. Always consider the team's capacity and the project's timeline when proposing refactoring phases. Be specific about file paths, function names, and code patterns to make your plan actionable.

Remember to check for any project-specific guidelines in CLAUDE.md files (if present) and ensure your refactoring plan aligns with established coding standards and architectural decisions.

© diet103 · MIT · diet103/claude-code-infrastructure-showcase

Похожие субагенты

Все субагенты по теме «Код-ревью и рефакторинг» →
refactor-expert alirezarezvani Субагент refactor-expert для Claude Code анализирует качество кода и планирует безопасный рефакторинг. Ищет дублирование, архитектурные проблемы и пробелы в тестах. CX Codex ★ 788звёзд репо tdd-refactor Seth Hobson Команда tdd-refactor проводит рефакторинг по TDD, сохраняя тесты зелёными. Она нужна для поэтапного улучшения структуры без изменения поведения. CX Codex +1 ★ 42 780звёзд репо general-refactor-expert Giuseppe Trisciuoglio Субагент general-refactor-expert для планомерного рефакторинга кодовой базы без потери функциональности. Находит запахи кода, дробит длинные функции и перестраивает архитектуру по SOLID. CX Codex ★ 372звёзд репо python-refactor-expert Giuseppe Trisciuoglio Субагент python-refactor-expert для Claude Code переписывает Python-код без изменения логики: наводит порядок в архитектуре, выносит настройки и внедряет тайпхинты. Пригодится после реализации новых фич. CX Codex ★ 372звёзд репо frontend-refactor-planner patricio0312rev Скилл frontend-refactor-planner составляет поэтапный план рефакторинга фронтенда: делит крупные компоненты, упрощает состояние и улучшает доступность. Пригодится при разборе легаси-кода. CX Codex +1 321установок clean-architecture wondelai Скилл clean-architecture держит бизнес-правила отдельно от фреймворка и базы: исходники зависят только от внутренних слоёв, и это проверяется по чек-листу. CX Codex +1 8 000установок

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

Весь набор →
dev-docs-update Команда dev-docs-update сохраняет состояние разработки перед сбросом контекста: обновляет документацию задач, память и заметки для передачи работы. CX Codex +1 ★ 10 055звёзд репо dev-docs Команда dev-docs генерирует детальный план реализации для любой задачи: анализирует кодовую базу, разбивает работу на фазы и создаёт трёхфайловую структуру с чек-листами и зависимостями между задачами. CX Codex +1 ★ 10 055звёзд репо auto-error-resolver auto-error-resolver — субагент Claude Code, который устраняет ошибки компиляции TypeScript по отчётам проверочного хука и перепроверяет сборку через tsc. CX Codex ★ 10 055звёзд репо frontend-error-fixer Субагент frontend-error-fixer разбирает ошибки фронтенда на этапе сборки и в браузере. Подходит для TypeScript, React, сетевых сбоев и проблем отображения. CX Codex ★ 10 055звёзд репо plan-reviewer Субагент plan-reviewer анализирует планы доработки архитектуры, миграций баз данных и интеграций до написания кода. Помогает найти скрытые риски и пропущенные шаги. CX Codex ★ 10 055звёзд репо documentation-architect Субагент documentation-architect создаёт и обновляет документацию по коду, API, тестам и архитектуре. Подключайте его, когда проекту нужны понятные технические материалы. CX Codex ★ 10 055звёзд репо web-research-specialist Субагент web-research-specialist ищет решения в GitHub Issues, Reddit, Stack Overflow и на форумах и собирает находки со ссылками. Пригодится при отладке ошибок и сравнении технологий. CX Codex ★ 10 055звёзд репо code-architecture-reviewer Субагент code-architecture-reviewer проверяет свежий код на соответствие архитектуре проекта и правилам интеграции. Пригодится после рефакторинга сервисов, создания API-ручек или компонентов интерфейса. CX Codex ★ 10 055звёзд репо

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

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