How to Safely Refactor a Large Codebase With Claude Code
By Ashley Gross
·
·
Claude

Agentic coding tools feel dangerous when one bad command can touch hundreds of files. Allowing an AI agent to roam freely through a monorepo or legacy backend usually ends with broken dependencies, uncommitted draft edits, and failing test suites. You can run sweeping architectural refactors safely by setting strict execution guardrails, working in small committed steps, and enforcing git-backed review loops.
What You Need
Plan level: Pro, Max, Team, or Enterprise plan, or a Console (API) account. The free plan does not include Claude Code.
System requirements: macOS, Linux, or Windows. You only need Node.js if you install with npm.
Environment: A clean git repository with passing automated test suites.
Setup time: 15 minutes for installation and configuration.
Step-by-Step Walkthrough
1. Set Up Safety Guardrails and Permissions
Install Claude Code in your terminal via standard native installation or Homebrew (brew install --cask claude-code). Recent versions start in auto mode, where a second model approves actions for you. Start with claude --permission-mode manual to approve every action yourself. Your current mode shows at the bottom of the screen, and Shift+Tab switches modes. Always create a dedicated git working branch before launching your session.
Why it matters: Setting explicit permission modes prevents Claude Code from running destructive terminal commands or pushing unreviewed edits directly to your primary branch.

2. Write a CLAUDE.md Memory File
Create a CLAUDE.md file at the root of your repository. Store high-level facts, build commands, test instructions, and architectural guidelines inside this file. Claude Code reads this file automatically at the start of every session to align with your project conventions.
Why it matters: A central project memory file prevents you from repeating style guidelines, test commands, and architectural constraints in every prompt.

3. Plan Before Editing
Ask Claude Code to analyze your target files and generate a step-by-step refactoring plan before modifying code. Review the proposed execution plan, check affected dependencies, and instruct the agent to pause for confirmation before touching files.
Why it matters: Requesting a written plan first isolates logic errors and prevents uncoordinated multi-file edits across your repository.

4. Refactor in Small, Tested, Committed Steps
Instruct Claude Code to execute the refactoring plan one module or batch at a time. After making file edits, require the agent to execute your test runner, review failures, fix broken syntax, and create a descriptive git commit before moving to the next batch.
Why it matters: Incremental testing and committing ensures each stage remains stable, making it easy to revert bad changes without losing hours of progress.

5. Manage Context and Delegate Workload
As sessions grow longer, token usage rises and model context degrades. Run the /compact command to summarize session history while retaining core working memory. Run /context to see how many tokens you are using. For large codebases, use subagents in .claude/agents/ to handle background tasks like running test suites or scanning for linting errors without polluting your primary chat context.
Why it matters: Active context management keeps Claude Code fast, lowers token costs, and stops old conversation history from degrading response accuracy.


6. Open a Pull Request and Review the Diff
Once all batches complete, command Claude Code to analyze your branch against your primary repository branch. Have the agent generate a summarized pull request title, description, and list of changed modules, then open the PR with the GitHub CLI (gh), which must be installed and logged in.
Why it matters: Generating structured pull requests gives your human team full visibility into automated edits before merging code into production.

Real Example: Express API Migration
We ran this exact workflow on a small Express API with three controller files, four route handlers, and six passing tests. Here is what happened.
Project Memory Config (CLAUDE.md)
The CLAUDE.md file listed the test command and two off-limits paths: the database module and the test folder. Claude Code followed both rules in every batch.
Planning Execution
"Analyze our /src/controllers directory. Map all route handlers currently using callback signatures. Write a step-by-step refactoring plan to convert them to async/await in small batches."
What Claude Code Flagged
All six tests passed after every batch. Claude Code still reported two gaps:
The tests never exercise the 404 and 500 error paths. One error case now returns a 500 response where it used to go unhandled.
Passing tests did not mean the change was fully covered. That is why you read the diff.
Final Result
Claude Code mapped four handlers, split them into three batches by risk, and made one commit per batch. The final diff touched four files, with 59 lines added and 27 removed. It then wrote the pull request summary from the diff against main.

Common Mistakes
Granting broad permissions on primary branches: Running Claude Code in auto or accept edits mode directly on
mainormastercan result in unverified commits that break production deployments. Always use working feature branches.Executing giant single-prompt refactors: Asking the agent to modify 50 files in one turn causes lost context, missed syntax errors, and huge, unreviewable diffs. Break large refactors into small, committed batches.
Skipping the project memory file: Omitting a
CLAUDE.mdfile forces Claude Code to guess build scripts, test suites, and formatting standards every single session, wasting tokens and introducing inconsistent code styles.
Take It Further
Add custom post-action hooks inside your .claude/settings.json file. Configure a hook that automatically executes your linter or code formatter (like Prettier or ESLint) every time Claude Code edits a file. This ensures every automated edit matches your repository styling rules before tests run.
Summary and Call to Action
You can manage large codebases agentically without sacrificing safety by pairing strict permission settings with project memory files and small git-backed iterations. Install Claude Code, draft your initial CLAUDE.md file today, and run your next migration on a clean working branch.
