✓ Takes 2 minutes • No credit card required • Instant on-screen output
✓ Takes 2 minutes • No credit card required • Instant on-screen output

How to Safely Refactor a Large Codebase With Claude Code

By Ashley Gross

·

·

Claude

Claude Code terminal interface illustrating safe codebase refactoring with automated test validations

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.


# Create a fresh git working branch
git checkout -b refactor/express-async-await

# Launch Claude Code with manual approval mode enforced
claude --permission-mode manual
# Create a fresh git working branch
git checkout -b refactor/express-async-await

# Launch Claude Code with manual approval mode enforced
claude --permission-mode manual
# Create a fresh git working branch
git checkout -b refactor/express-async-await

# Launch Claude Code with manual approval mode enforced
claude --permission-mode manual
Claude Code asking for approval before overwriting a file in manual mode

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.


# Project Memory: Express API Service

## Build & Test Commands
- Run tests: `npm test`
- Run single test file: `npx jest path/to/file.test.js`
- Run linter: `npm run lint`

## Architecture Rules
- Use async/await syntax exclusively; do not use callback signatures.
- Wrap all route handler logic in try/catch.
- Do not modify database schemas or migration files

# Project Memory: Express API Service

## Build & Test Commands
- Run tests: `npm test`
- Run single test file: `npx jest path/to/file.test.js`
- Run linter: `npm run lint`

## Architecture Rules
- Use async/await syntax exclusively; do not use callback signatures.
- Wrap all route handler logic in try/catch.
- Do not modify database schemas or migration files

# Project Memory: Express API Service

## Build & Test Commands
- Run tests: `npm test`
- Run single test file: `npx jest path/to/file.test.js`
- Run linter: `npm run lint`

## Architecture Rules
- Use async/await syntax exclusively; do not use callback signatures.
- Wrap all route handler logic in try/catch.
- Do not modify database schemas or migration files

A CLAUDE.md file with test commands and architecture rules

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.


[PLANNING PROMPT]
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.
Do not edit any files yet. Present the plan for review first

[PLANNING PROMPT]
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.
Do not edit any files yet. Present the plan for review first

[PLANNING PROMPT]
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.
Do not edit any files yet. Present the plan for review first

A three-batch refactor plan from Claude Code

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.


[EXECUTION & COMMIT PROMPT]
Execute Batch 1 of the refactor plan. 
Convert callbacks to async/await syntax according to CLAUDE.md guidelines. 
Run 'npm test' to verify. 
Once all tests pass, stage the modified files and commit with a clear git message

[EXECUTION & COMMIT PROMPT]
Execute Batch 1 of the refactor plan. 
Convert callbacks to async/await syntax according to CLAUDE.md guidelines. 
Run 'npm test' to verify. 
Once all tests pass, stage the modified files and commit with a clear git message

[EXECUTION & COMMIT PROMPT]
Execute Batch 1 of the refactor plan. 
Convert callbacks to async/await syntax according to CLAUDE.md guidelines. 
Run 'npm test' to verify. 
Once all tests pass, stage the modified files and commit with a clear git message

Claude Code running tests and committing the first batch

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.


# Compact conversation history within an active CLI session
/compact

# Clear conversational history entirely for a new subtask
/clear
# Compact conversation history within an active CLI session
/compact

# Clear conversational history entirely for a new subtask
/clear
# Compact conversation history within an active CLI session
/compact

# Clear conversational history entirely for a new subtask
/clear
The /compact command confirming the conversation was compactedThe /context command in Claude Code showing token usage by category

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.


Compare our current refactor branch against main. 
Summarize all converted route handlers, list test results, and open a GitHub pull request titled "refactor(api): convert controllers from callbacks to async/await"

Compare our current refactor branch against main. 
Summarize all converted route handlers, list test results, and open a GitHub pull request titled "refactor(api): convert controllers from callbacks to async/await"

Compare our current refactor branch against main. 
Summarize all converted route handlers, list test results, and open a GitHub pull request titled "refactor(api): convert controllers from callbacks to async/await"

Claude Code summarizing the branch and drafting a pull request title and description

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.

Terminal showing three batch commits, four changed files, and six passing tests

Common Mistakes

  1. Granting broad permissions on primary branches: Running Claude Code in auto or accept edits mode directly on main or master can result in unverified commits that break production deployments. Always use working feature branches.

  2. 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.

  3. Skipping the project memory file: Omitting a CLAUDE.md file 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.