Last updated 13 October 2026
Using Claude Code to refactor legacy code
Initial exploration of the legacy codebase
Legacy codebases often feel like a house of cards where every change threatens the whole structure. You are likely staring at a directory full of files written in outdated syntax or using abandoned patterns that make adding new features a nightmare. The immediate hurdle is not just writing new code but understanding the existing flow without spending weeks on manual tracing. You need a way to map these dependencies and identify where the modern syntax can replace the old without breaking the runtime logic of your system.
Start by running the command claude in your project root to open the interactive interface. Your first task is discovery rather than modification. Use the agent to find patterns by asking it to use the Glob and Grep tools to identify all instances of a specific legacy pattern across the codebase. For example, if you are replacing old callback patterns with modern async-await, ask the agent to find every file that uses the old style. This gives you a list of targets and helps you estimate the scope of the refactor before you touch a single line of code.
While the agent scans the files, it builds a mental model of the project structure. It reads the files using the Read tool and keeps the most relevant parts in its context. This is the stage where you verify if the agent understands the logic. Ask it to explain how a specific module interacts with its neighbors. If the explanation matches your understanding, you are ready to move to the next phase. If it misses something, you can point it out now before the agent starts suggesting edits that might introduce subtle bugs into your project.
Establishing project standards with CLAUDE.md
Before you let an agent edit your files, you must define the rules of the road. Claude Code looks for a file named CLAUDE.md in the root of your repository to understand your project instructions. This is where you specify the coding standards you want the refactor to follow. If you are moving from a specific library to a newer one, list the preferred patterns here. Explicit instructions in this file prevent the agent from making inconsistent choices across different modules during the refactor.
You can also use CLAUDE.md to define the build and test commands. This is vital because it allows the agent to verify its own work. If the agent knows that running a specific test command is the standard for your project, it can use the Bash tool to run those tests after every edit. This creates a tight feedback loop. The agent can catch its own syntax errors or logic breaks before you even see the diff, saving you time during the review process.
If your project is large, you can place additional CLAUDE.md files in subdirectories. This is useful when different parts of your tree have different requirements. For example, a legacy frontend directory might need different linting rules than a modern backend directory. The agent will respect the instructions in the most local CLAUDE.md file, ensuring that the refactoring logic adapts to the specific context of the files it is currently editing. This hierarchical approach keeps your global instructions clean and manageable.
Automating edits with permission modes
Refactoring hundreds of files manually is what you are trying to avoid. Claude Code offers different permission modes to control how much autonomy the agent has. By default, it will ask for your permission before using tools. However, when you are doing a repetitive refactor like updating imports or changing function signatures, constant prompting becomes a distraction. You can cycle through permission modes using Shift plus Tab to find a balance between speed and safety.
The acceptEdits mode is particularly useful for refactoring tasks. In this mode, the agent can use the Edit and Write tools without asking for permission every time. This allows it to move through a list of files rapidly. If you are worried about it going too far, you can configure specific permissions in your settings.json file. You can find this file in the .claude directory of your project. This allows you to allow the Edit tool while still requiring approval for more destructive actions like the Bash tool.
If you want to see what the agent plans to do before it makes any changes, use the plan mode. This mode forces the agent to describe its intended actions without executing them. This is a great way to verify the refactoring strategy for a complex module. Once you are happy with the plan, you can switch back to default or acceptEdits to let the agent carry out the work. This toggle between planning and execution keeps you in control of the high-level architecture while the agent handles the tedious character-by-character updates.
Managing multiple refactoring tracks simultaneously
Refactoring across multiple modules often requires context switching that breaks your concentration. This is a situation where adhdTerminal provides a clear advantage by organizing your work visually. It is a native app for macOS and Windows, made by MINDBALANCER OU in Estonia, not affiliated with Anthropic. The app runs many Claude Code sessions side by side, each one a tile on a wall. This allows you to have one tile focusing on the database layer and another on the API routes, each with its own independent context and history.
Each tile has a colour, a number and a name, showing whether it is working, waiting for you, done or idle. Since tiles reopen in the same place after a restart and resume the same session, you can pause a complex refactor on one module and pick it up exactly where you left off the next morning without scrolling through terminal history. This visual persistence is helpful when a refactor spans several days or involves waiting for long build processes to complete on different parts of the system.
The free iPhone app mirrors the wall over an end to end encrypted link and can answer a prompt or send the next task. This is helpful when you need to step away from the desk but want to keep the refactor moving. When a tile on your wall finishes a large Glob search or a complex Edit task, you can see the result and give the next instruction from anywhere. This prevents the refactoring momentum from stalling when you need to step away from your workstation for a few minutes while the agent works through a large file list.
Maintaining context through long sessions
As a refactor progresses, the conversation history grows. The agent keeps track of the files it has read and the changes it has made in its context window. However, a very long session can eventually fill this window, which might make the agent less precise or slower to respond. You should monitor the session health to ensure the agent remains effective. If you notice it becoming confused about previous changes, it might be time to manage the context.
The /compact command is the tool for this job. It summarizes the session so far and frees up space in the context window. This is like giving the agent a fresh summary of the current state of the refactor while clearing out the line-by-line history of every small edit. It is a good practice to run /compact after you have successfully refactored a major component or when you are about to start a new phase of the project. This keeps the agent focused on the current task rather than being bogged down by hundreds of previous messages.
If you find that the session has become too cluttered or you want to start a fresh approach in the same folder, use the /clear command. This resets the conversation but keeps you in the same working directory. This is useful if you realized the initial refactoring strategy was wrong and you want to start over without the baggage of the previous failed attempts. Remember that you can always use the command claude --resume to pick up an older session if you realize you actually needed something from that previous context.
Executing and verifying the refactor
Once the rules are set and the context is clear, you can start the actual execution. Ask the agent to apply the modern patterns to the target files. The agent will use the Edit tool to modify the code. It is often best to do this file by file or in small batches. This makes it easier to review the diffs. Use the /review command to see what has changed. The agent can provide a summary of the edits and explain why it made specific choices, which is helpful for your own code review process.
Validation is the most critical part of a refactor. Use the Bash tool to run your test suite frequently. You can tell the agent to run the tests and if they fail, to use the output of the failure to fix the code. This self-healing loop is one of the strongest features of a terminal agent. It can read the error logs, identify the line that caused the regression, and apply a fix immediately. This reduces the time you spend debugging minor syntax errors that often occur during large-scale code transformations.
If the agent gets stuck in a loop or starts making mistakes, you can interrupt it. Pressing Escape once will stop the current action. If you need to revert to an earlier point in the conversation, press Escape twice. This will offer you a list of earlier messages to go back to. This is much faster than manually undoing edits in your IDE. It allows you to rewind the entire session to a known good state and try a different prompt or a different set of instructions to get the refactor back on track.
Monitoring resource usage and session integrity
Refactoring a large project can involve many API calls and a high volume of tokens. It is good practice to keep an eye on your resource usage. You can use the /cost command to see the financial cost of the current session. The /usage command provides a broader view of your activity. Monitoring these figures helps you decide when to use more automated modes and when to do manual checks to save on context costs. Large files consume more context, so breaking them into smaller modules before refactoring can be a smart move.
Before you finish a session, ensure that your changes are documented. The TodoWrite tool can be used to leave notes for yourself or other developers about what was changed and what still needs attention. This is a great way to handle parts of the legacy code that were too complex to refactor in one go. By creating a clear list of remaining tasks, you ensure that the momentum of the modernization effort is not lost when you switch back to feature development.
Finally, when you are done with a session, use Ctrl plus C to quit. If you want to carry on later, remember that claude --continue will take you back to the very last thing you were doing in that folder. This persistence means you do not have to re-explain the project to the agent every time you open your terminal. The combination of local settings, project-specific instructions in CLAUDE.md, and session history makes the agent a long-term partner in maintaining and improving your legacy codebase.
Questions people ask
What should I do if the agent keeps making the same mistake in every file?
You should check your CLAUDE.md file and add a specific negative constraint. Tell the agent exactly what pattern to avoid and provide an example of the correct replacement. This updates the instructions for every subsequent edit and usually stops the repetitive error immediately.
How can I refactor a file that is too large for the context window?
You can use the /compact command to free up space, or you can ask the agent to refactor the file in sections. Use the Read tool to look at specific line ranges and apply the Edit tool to only those ranges. This keeps the amount of data in the context window manageable for each step.
Can I use my existing shell aliases and tools during a refactor?
Yes, you can use the Bash tool to run any command available in your terminal. If you have custom scripts for linting or formatting, you can tell the agent to run those scripts as part of its validation process. You can also use Ctrl plus R to search your shell history while inside the Claude Code interface.
Read next
- Add build instructions to your CLAUDE.md fileImprove project context by adding specific build commands and environment requirements to your CLAUDE.md file for the AI to follow.
- Add common error fixes to CLAUDE.mdImprove project memory by adding a section for common errors and their fixes to your CLAUDE.md configuration file.
- Add custom shell aliases for Claude CodeSpeed up your workflow by creating shell aliases for common Claude Code invocations and project-specific startup commands.
- Add test commands to a CLAUDE.md fileUnderstand how to define specific test runners and environment flags in your CLAUDE.md file so the tool runs the correct test suite.