The `refactor` Tool
Relevant source files
The following files were used as context for generating this wiki page:The refactor tool is a sophisticated, workflow-driven utility designed for intelligent code refactoring. It systematically analyzes codebases to identify opportunities for improvement related to code smells, decomposition, modernization, and organization. The tool guides a CLI agent through a structured investigation, ensuring a thorough examination before producing actionable recommendations. It can operate autonomously for clear-cut cases or engage an expert AI model for validation on more complex scenarios.
This tool is a key component of the Zen MCP server's code analysis and quality suite, alongside other tools like codereview and debug. It focuses on improving code structure and maintainability without altering its behavior.
Sources: tools/refactor.py:5-18, README.md:131-132, systemprompts/refactor_prompt.py:5-7
Core Architecture
The refactor tool is implemented as a WorkflowTool, which means it operates through a multi-step process rather than a single request-response cycle. This allows for a methodical investigation where the agent gathers information, forms hypotheses, and refines its analysis over several steps.
Sources: tools/refactor.py:141
Key Components
| Component | Description | Source File |
|---|---|---|
RefactorTool | The main class that orchestrates the refactoring workflow. It inherits from WorkflowTool and manages the step-by-step analysis, state, and expert model interaction. | tools/refactor.py:141 |
RefactorRequest | A Pydantic model defining the data structure for each step of the refactoring investigation. It includes fields for tracking progress, findings, and confidence. | tools/refactor.py:92 |
REFACTOR_PROMPT | The system prompt that instructs the AI model on how to perform the analysis. It contains the core refactoring rules, types, severity levels, and the required JSON output format. | systemprompts/refactor_prompt.py:5 |
Class Diagram
The diagram below shows the main classes and their relationship.
Sources: tools/refactor.py:92-143
Refactoring Workflow
The tool follows a structured, step-by-step workflow to ensure a comprehensive analysis. The process begins with an initial request and progresses through investigation steps until the analysis is complete, at which point it may either conclude locally or escalate to an expert model for validation.
Sources: tools/refactor.py:14-18
This flowchart illustrates the refactor tool's operational flow.
Request Data Model
Each step in the workflow is governed by the RefactorRequest model.
| Field | Type | Description |
|---|---|---|
step | str | A description of the plan for the current step or a report of findings. |
step_number | int | The current step index, starting at 1. |
total_steps | int | The agent's estimate of the total steps needed. |
next_step_required | bool | true if more investigation steps are planned. |
findings | str | A summary of discoveries from the current step. |
files_checked | list[str] | A list of all absolute file paths examined in the step. |
relevant_files | list[str] | A subset of files_checked containing code that requires refactoring. |
issues_found | list[dict] | A list of identified refactoring opportunities. |
confidence | Literal | The agent's confidence in its analysis: exploring, incomplete, partial, or complete. |
refactor_type | Literal | The type of analysis to perform. Only used in step 1. |
Sources: tools/refactor.py:92-136
Expert Analysis
The tool can escalate to an expert AI model for final validation. This is triggered when the agent's investigation is complete (next_step_required is false) but its confidence is less than complete. The RefactorTool prepares a detailed context for the expert model, including the initial request, investigation summary, and a list of identified opportunities.
The expert model is expected to return a structured JSON response containing a detailed analysis and actionable recommendations.
Sources: tools/refactor.py:321-337, tools/refactor.py:339-380
Refactoring Analysis Logic
The core intelligence of the refactor tool is defined in the REFACTOR_PROMPT. This prompt establishes the rules, priorities, and output format for the AI performing the analysis.
Sources: systemprompts/refactor_prompt.py
Refactoring Types
The analysis is categorized into four types, with a strict priority order.
| Type | Priority | Description |
|---|---|---|
decompose | 1 (CRITICAL) | Breaking down oversized files, classes, or functions to reduce cognitive load. This is always the highest priority. |
codesmells | 2 | Detecting and fixing quality issues like long methods, duplicate code, magic numbers, and poor naming. |
modernize | 3 | Updating code to use modern language features, syntax, and patterns. |
organization | 4 | Improving file structure, grouping related functionality, and clarifying module boundaries. |
Sources: systemprompts/refactor_prompt.py:22-26, systemprompts/refactor_prompt.py:217-226
Decomposition Strategy
Decomposition is the most critical refactoring type. The prompt defines a context-aware, adaptive threshold system to decide when and how to decompose code. If any component exceeds an "AUTOMATIC" threshold, the tool must focus exclusively on decomposition and mark the issue with CRITICAL severity.
The decomposition analysis follows a specific order, stopping at the first breached threshold.
Severity Levels
Refactoring opportunities are assigned a severity level to guide prioritization.
| Severity | Description |
|---|---|
critical | Exclusively for decomposition when automatic thresholds are breached. Blocks all other refactoring types. |
high | Major code smells, significant duplication, or architectural issues. |
medium | Moderate complexity, minor duplication, or organizational improvements. |
low | Style improvements, minor modernizations, or optional optimizations. |
Sources: systemprompts/refactor_prompt.py:230-241
JSON Output Structure
The final output of the refactoring analysis is a structured JSON object. This format is designed to be parsed and acted upon by a coding agent. It includes a list of refactor_opportunities, a priority_sequence, and next_actions.
This allows the output to be consumed by other processes, such as one guided by the GENERATE_CODE_PROMPT, which defines a protocol for applying structured code changes.
Sources: systemprompts/refactor_prompt.py:250-285, systemprompts/generate_code_prompt.py:1-10
Testing and Validation
The refactor tool's functionality is validated through end-to-end simulator tests. The test test_refactor_analysis_with_expert_validation simulates a complete workflow, from the initial call to the final expert analysis, ensuring that the tool correctly processes steps, consolidates findings, and interacts with the expert model as expected.
Sources: simulator_tests/test_refactor_validation.py:19-27
Summary
The refactor tool provides a powerful and systematic approach to improving code quality. By combining a structured, multi-step workflow with a sophisticated, rule-based AI prompt, it can identify and prioritize a wide range of refactoring opportunities. Its ability to operate autonomously or with expert validation makes it a flexible and robust solution for maintaining and evolving a codebase. The structured output ensures that its findings are not just suggestions but actionable instructions for automated or semi-automated code modification.
Sources: tools/refactor.py, systemprompts/refactor_prompt.py