From ai-plugins
Refactor and improve code quality across an entire project using parallel specialized sub-agents. Covers Go, TypeScript/React, Python, Rust, Database, Shell/Build, K8s/Config, and Observability domains with a safety-first iterative approach. Use when the user wants to improve code quality, readability, maintainability, or modernize a codebase without breaking functionality.
How this skill is triggered — by the user, by Claude, or both
Slash command
/ai-plugins:code-refactorThe summary Claude sees in its skill listing — used to decide when to auto-load this skill
A four-phase refactoring workflow: **Analyze → Plan → Refactor → Verify** with iterative sub-agent execution until the entire project is covered.
A four-phase refactoring workflow: Analyze → Plan → Refactor → Verify with iterative sub-agent execution until the entire project is covered.
/code-refactor <describe what to refactor, or "full project" for comprehensive coverage>
$ARGUMENTS - The refactoring scope, target area, or "full project" for end-to-end coverage. Optional flags the user may include:
Execute these four phases in order. After the Verify phase, loop back to Refactor for the next chunk of work. Repeat until the entire project is covered or the user's specified scope is complete.
+-----------+ +--------+ +-----------+ +----------+
| ANALYZE | --> | PLAN | --> | REFACTOR | --> | VERIFY |
+-----------+ +--------+ +-----------+ +----------+
^ |
| next chunk |
| or fixes |
+-----------------+
Role: You are an analysis agent. You have READ-ONLY access. You do not modify any code in this phase.
Goal: Understand the project structure, tech stack, existing patterns, and identify all refactoring targets across the entire codebase.
Read project documentation.
AGENTS.md, README.md, CONTRIBUTING.md, CLAUDE.md, or equivalent files.Discover build and test commands.
Makefile, package.json scripts, Cargo.toml, pyproject.toml, or equivalent build configuration.Detect the technology stack.
Before any refactoring, the project must be in a green state.
If the baseline is not green, report the failures to the user and STOP. Do not refactor a broken project. Explain what needs to be fixed first.
Walk the entire directory tree and build an inventory:
File catalog — For each source file, record:
Domain classification — Assign each file to a technology domain using the mapping in refactor-perspectives.md. Each domain has its own checklist under perspectives/ — read only the relevant domain files. Files may belong to multiple domains (e.g., a Go file with database queries belongs to both "Go Backend" and "Database").
Size analysis — Flag files that exceed these thresholds:
For each technology domain present in the project, assess the current state:
Dependency injection — Are dependencies passed as constructor parameters? Are interfaces used at boundaries? Or is there tight coupling with concrete types?
Testing patterns — What testing framework is used? What is the mock strategy? Is there a pattern for test helpers? Approximate test coverage level.
Observability — Does the project already have logging, metrics, or tracing infrastructure? Which libraries/frameworks? Where is it initialized? Only plan to add observability instrumentation if the project already has the foundational setup.
Error handling — What conventions exist? Wrapped errors? Sentinel errors? Custom error types?
Documentation — Are there docstrings on functions? What style? What percentage of exported functions have documentation?
File organization — What is the package/module layout pattern? Is there a clear separation of concerns?
Scan the entire codebase and flag files, functions, and packages that need attention. For each target, note:
Categories of targets:
| Category | Trigger | Risk |
|---|---|---|
| Missing interfaces / DI | Concrete type dependencies at boundaries | Medium |
| Missing or weak tests | Functions without test coverage, missing edge cases | Low |
| Missing docstrings | Exported functions without documentation | Low |
| Large files | > 400 lines, no logical separation | Medium |
| Large functions | > 50 lines, doing multiple things | Medium |
| Duplicated code | Similar logic in multiple places | Medium |
| Missing observability | Logging/metrics/tracing gaps where infrastructure exists | Low |
| Inconsistent patterns | Mixed conventions within the same domain | Low |
| Missing error handling | Discarded errors, bare panics, generic catches | High |
| Tight coupling | Cross-package concrete dependencies | Medium |
Write the complete analysis to:
docs/plans/code-refactor-analysis.md
Include: project overview, tech stack, baseline results, file inventory summary, pattern assessment, and the full list of refactoring targets grouped by domain.
Output: Present the analysis summary to the user before proceeding to Phase 2.
Role: You are a planning agent. You have READ-ONLY access. You do not modify any code in this phase.
Goal: Create an ordered, chunked refactoring plan that maximizes impact while minimizing risk of breaking changes.
Order targets by dependency and risk:
Assign refactoring targets to sub-agent specializations. The exact set of sub-agents depends on the project's tech stack. Common specializations:
Only create sub-agents for domains that exist in the project.
Within each domain, group files into chunks that can be refactored together without breaking intermediate states:
Organize chunks into iteration rounds:
Each round should leave the project in a buildable, testable state.
Write the complete refactoring plan to:
docs/plans/code-refactor-plan.md
Include: prioritized target list, domain assignments, chunk breakdown, iteration rounds, and risk assessment for each chunk.
Output: Present the plan summary to the user before proceeding to Phase 3.
Role: You are a staff-level refactoring agent orchestrating parallel specialized sub-agents. You write production-grade code that preserves all existing functionality.
Goal: Execute the current iteration round from the plan, using parallel sub-agents for each technology domain.
Before making any changes in this round:
If either fails, diagnose and fix the issue before proceeding with new refactoring work.
For each technology domain that has work in the current round, spawn a specialized sub-agent. Each sub-agent receives:
perspectives/*.md file (see refactor-perspectives.md for the mapping)Use this template for each sub-agent task prompt:
You are a specialized {DOMAIN_NAME} refactoring agent. Your job is to improve code quality in the assigned files WITHOUT BREAKING any existing functionality.
## Project Context
- Project: {project name and description}
- Build command: {discovered build command}
- Test command: {discovered test command}
- Existing patterns: {relevant patterns from the analysis}
## Your Domain: {DOMAIN_NAME}
{paste the complete refactoring checklist for this domain from refactor-perspectives.md}
## Files to Refactor
{list of files with their identified targets}
## Refactoring Targets for These Files
{specific targets from the plan for each file}
## Critical Rules
1. NEVER break existing functionality. Preserve all current behavior.
2. Add docstrings to every function you touch.
3. Follow the project's existing conventions and patterns.
4. If you introduce an interface, ensure all existing callers are updated.
5. If you split a file, ensure all imports are updated.
6. If you change a function signature, update all call sites.
7. Run the build and test commands after your changes to verify nothing broke.
## What to Do
For each file:
1. Read the file and understand its current purpose and dependencies.
2. Read adjacent files (callers, callees, tests) to understand the impact of changes.
3. Apply the refactoring targets identified in the plan.
4. Add docstrings to all functions.
5. Follow the domain-specific checklist.
6. Verify your changes compile and tests pass.
## Output
Report what you changed:
- Files modified (with summary of changes)
- Files created (if splitting)
- Files deleted (if consolidating)
- Tests added or modified
- Any issues encountered
- Build/test results after changes
Spawn all sub-agents concurrently. If the project has many files, split a single domain across multiple sub-agents (e.g., "Go Backend - pkg/api" and "Go Backend - pkg/service").
After all sub-agents complete:
After integrating all sub-agent changes:
If any step fails:
Role: You are a verification agent reviewing the refactoring changes for quality and safety.
Goal: Confirm that all changes improve code quality without breaking functionality, and decide whether to continue with the next round or finish.
All must pass. If any fail, go back to Phase 3 to fix the issues.
Use the reusable review workflow in ../review-engine/SKILL.md and the perspective criteria in ../review-engine/review-perspectives.md.
When running the review for code-refactor, pass the following context:
docs/plans/code-refactor-analysis.mddocs/plans/code-refactor-plan.mdThe review MUST specifically check:
After the review:
After all iteration rounds are complete and verified:
Update AGENTS.md (create if it does not exist):
Update README.md if structural changes affect:
Present a comprehensive summary to the user:
## Code Refactoring Complete
### Rounds Completed: N of N
### Changes by Domain
| Domain | Files Modified | Files Created | Files Deleted | Tests Added |
|--------|---------------|---------------|---------------|-------------|
| ... | ... | ... | ... | ... |
### Key Improvements
- {list the most impactful changes}
### Patterns Introduced
- {list new patterns: interfaces, DI, testing conventions, etc.}
### Observability Added
- {list new logging, metrics, or tracing — only if infrastructure existed}
### Documentation Updated
- AGENTS.md: {what was added}
- README.md: {what was changed, if anything}
### Remaining Items
- {anything that was identified but not addressed, with explanation}
### Build/Test Status
- Build: ✅ PASS
- Tests: ✅ PASS (N tests, +M new)
- Lint: ✅ PASS
Stop iterating when:
If the refactoring is interrupted or the user wants to continue later:
docs/plans/code-refactor-plan.mdnpx claudepluginhub schseba/ai-plugins --plugin ai-pluginsCreates bite-sized, testable implementation plans from specs or requirements, with file structure and task decomposition. Activates before coding multi-step tasks.