Claude Code for Large Multi-File Refactors
Claude needs structural context to refactor safely across multiple files.
Sponsored by Graphide

A production incident tells the story precisely: an agent refactored a set of synchronized blocks into a cleaner concurrency pattern, every test passed, and the system still broke once it hit concurrent load in production. The race condition that the original code happened to avoid had nothing to do with syntax, so no test written against surface behavior caught it. Claude Code can produce changes that are correct in isolation and still break the system they belong to, because long sessions and unconstrained prompts let it lose track of the dependency graph connecting one file to the rest of the codebase.
Mechanical refactors and architectural refactors fail in different ways, and the difference matters for how a developer should think about risk. A rename, an import cleanup, a type update, or a repeated API migration tends to break specific callsites: a function signature changes, something downstream calls it the old way, and the failure is loud and local. An architectural refactor, the kind that moves responsibilities between modules or changes who owns what, can shift the boundaries of the system in ways that pass every test and still raise the long-term cost of maintaining it. The root cause behind both failure modes is the same. Claude was given a file to edit, not a map of the system the file lives inside.
Structural Context Claude Code Needs
Context is a deliberate input the developer has to supply before a refactoring prompt does anything useful. A fresh context window carries no knowledge of the contracts that hold a codebase together: it doesn't know that UserService calls AuthService under the hood, that the database layer expects snake_case while the application layer uses camelCase, or that the codebase migrated off one state management library onto another eighteen months ago. Those facts live in the heads of the engineers who built the system, and unless they're stated explicitly, Claude has no way to recover them from the files alone.
The minimum viable input, before any refactoring prompt, is three things: the file being changed, every file that imports from it, and every file that it imports from. Skipping this step makes Claude pattern-match on filenames and naming conventions instead of reading the actual dependencies that connect those files. The summary step that follows is not a nicety to skip when the session feels short on time. Prompting Claude to summarize what the target file does, and what would break if its interface changed, forces it to actually read the code rather than guess from surface patterns, and it gives the developer a chance to check Claude's mental model against reality before a single line changes.
Scope matters as much as inclusion. Handing Claude Code a single function to refactor produces better output than handing it an entire file, a distinction lowcode.agency's legacy refactoring guide identifies as a direct lever on output quality: a narrower target gives Claude less surface area to misread and less room to introduce unintended side effects. Done this way, Claude's read of the code becomes one of its real advantages over a linter or a static analyzer. A linter sees only what's declared. Claude, reading the actual bodies of the functions involved, can surface implicit contracts in the code it reads, such as a method that silently assumes its caller has already validated an argument, which no static tool would ever flag because no static tool reads intent.
Using CLAUDE.md to hold architectural rules across sessions
Single-session discipline solves the problem of one session going off the rails. It does nothing for a refactor that spans five sessions over two weeks, and that's the gap CLAUDE.md is built to close. Without a shared CLAUDE.md, every new session starts blind, and each one tends to make its own convention choices: a different logger here, a different ORM method there, a different error-handling pattern in the next file over. The codebase drifts further from its intended shape precisely because of the refactoring effort meant to clean it up, which is as costly an outcome as the problem the refactor was supposed to solve.
A working CLAUDE.md for a refactor in progress needs several concrete sections. It should state the explicit rules the refactor must hold to: which endpoints must keep their existing contracts, what dependency injection pattern is expected, what the repository layer requires, what shape error responses must take. It should track what's already done, with tests passing, separately from what's still in progress, so a new session doesn't waste time re-verifying settled work or, worse, re-opening it. It should carry a "do not touch" list naming the files and external contracts that are frozen for the duration of the refactor. And it should name, explicitly, which libraries are approved and which are forbidden, since that list is what stops Claude from quietly introducing a new dependency mid-refactor to solve a problem it could have solved with what's already there.
Of everything that can go into a CLAUDE.md for an existing codebase, the "must never do" section is the most important, a point lowcode.agency's existing-codebase guide makes directly. A rule phrased as a constraint on what must not happen is harder to misread than a positive instruction, and it survives translation across sessions better than a style preference does. The real value of the file is that it compresses context. Instead of re-explaining the system's architecture, its conventions, and its history at the start of every session, CLAUDE.md lets each session start from the same informed baseline, which turns a refactor from a series of disconnected conversations into one continuous piece of work.
The four-step execution loop: understand, plan, execute in chunks, verify
Multi-file refactors that hold together in practice all follow a version of the same four-step loop: understand, plan, execute in chunks, verify. Collapsing any one of those steps into the next is where refactors come apart, and each step earns its place by catching a different category of mistake.
Understanding comes first, and it starts with a question, not a change. Instead of asking Claude to modify OrderService.ts, the first prompt should ask Claude to read OrderService.ts and every file that imports from it, then summarize what the service does and where its natural boundaries sit. Only once that answer matches the developer's own mental model of the system does it make sense to move forward. This is the session where Claude, working through a "god service" split, identifies payment logic, inventory logic, and notification logic bundled together inside one class, before a single line of code has moved.
Planning comes next, and the plan has to exist in full before any code gets written. Claude should propose the refactoring as a concrete list: each new component or module, what it will contain, what its interface will look like to the rest of the system. A plan is the cheapest place to catch a bad idea, since reversing a decision on paper costs nothing compared to reversing it across a dozen files already changed.
Execution happens in vertical slices, never as one horizontal sweep across a large file. One logical change gets one commit. In the god-service pattern, the second session extracts all the payment-related methods into PaymentService.ts, while OrderService keeps calling PaymentService with no interface changes visible to its own callers, all inside one session and one commit. The discipline here is practical: when three things break at once, debugging time scales with the number of simultaneous changes, so narrowing the blast radius of each session is what keeps debugging tractable. The same logic applies to a rename spread across many files: use grep to find every file touching the old name, list them without changing anything yet, review that list for false positives such as comments, test fixtures, or generated code that shouldn't be touched, and only then execute the rename. Scope boundaries should be treated as a hard constraint through the whole process, not a suggestion. A prompt that says "only touch files in src/payments/ and tests/test_payments/" keeps Claude from making a well-intentioned change outside the area the session was meant to cover.
Verification closes the loop, and it happens after each chunk, not once at the end. Tests run after every slice of work, /compact gets used between major chunks to keep the context window clean, and the developer reviews the diff explicitly rather than trusting a green test suite to speak for itself. The diff review is where subtle regressions appear, such as a prop quietly renamed in a way that still compiles, or a changed behavior that no existing test happens to cover. For TypeScript refactors specifically, renaming an interface field calls for a manual check of destructuring patterns elsewhere in the code, since the type system flags mismatches it was told to expect but says nothing about assumptions no one declared. The question to ask at every point in this loop is what the smallest safe change is, in the right part of the codebase, and that reframing is what keeps each session bounded to work that can actually be verified before it ends.
Why passing tests do not confirm a refactor is correct
Everything described so far is necessary and still not sufficient, and the race condition from the opening section is the clearest demonstration of why. The agent's refactor of the synchronized blocks compiled cleanly and passed the full test suite, because the race condition only manifested under concurrent load, a condition the test suite never exercised. That failure has nothing to do with inadequate testing in the ordinary sense. It's a failure of behavioral equivalence, the kind no unit test is built to catch, because unit tests verify that given inputs produce given outputs, not that a system under concurrent load behaves the same way it did before.
One defense against this gap is sequencing: generate tests against the current behavior before anything changes, rather than writing tests against the new code after the fact. Refactoring without a baseline of tests written against existing behavior amounts to guesswork; refactoring with one is engineering, a distinction lowcode.agency's legacy refactoring guide draws explicitly, though the firm reserves the stronger label "non-negotiable" specifically for committing incrementally, not for the baseline-testing step itself.
The diff review step described in the execution loop is not redundant with test coverage, and it earns its place precisely because tests miss things that stay invisible until a human reads the actual change. A prop renamed in a way that still compiles, a missing aria-label attribute, an error response whose shape changed in a way some downstream consumer depends on: none of these fail a test suite, and all of them show up in a diff a developer actually reads.
Enforcing architectural constraints in CI so agents cannot silently violate them
Documentation and a well-written CLAUDE.md tell an agent what the architecture is supposed to look like, and neither one stops the agent from violating that architecture anyway. An architecture decision record captures a decision and the reasoning behind it, but it does nothing to a diff, and there's no guarantee any agent reads it or acts on it before generating code. A boundary that exists only in a document is invisible to the thing actually generating the change.
Enforcement built into the pipeline itself, in the form of fitness functions, is the structural answer: build checks that fail automatically on architectural violations, regardless of whether a human or an agent produced the change. Instructions guide what an agent attempts. Enforcement is what protects the codebase when an agent attempts the wrong thing anyway. CI-level architectural checks do three concrete things: they stop violations before code ever enters the repository, they convert architecture from a documentation claim into a machine-readable fact the pipeline can test, and they let new developers and new agents onboard faster, because "the system enforces this" is a clearer statement to work from than "we do this by convention."
This matters specifically for multi-file refactors, because a refactor can look clean file by file and still violate a layer boundary or introduce a dependency the architecture forbids, in a way no single diff ever reveals. A diff is a poor interface for answering a repository-wide question. A graph-level check, built to ask whether a given layer is permitted to depend on another, answers "does this refactor preserve the architecture?" with a binary, automated result, which is the only kind of answer that scales to the pace an agent can generate changes.
Parallel Agents and Worktrees for Large Refactors
Parallel agents working in separate git worktrees can compress the wall-clock time a large refactor takes, provided the work is partitioned so that no two agents touch the same files at once. Shared file access is where the parallel approach collapses: two agents editing the same file in different worktrees produce conflicts that erase the time saved by running them in parallel.
The SWE-Refactor benchmark, built to evaluate repository-level refactoring tasks, tested this directly. A multi-agent workflow pairing a Developer Agent that generates refactored code with a Reviewer Agent that provides iterative feedback achieved the highest overall success rate among the approaches tested, with 579 successful refactorings, ahead of a RAG-based approach at 451 and basic prompting at 438. The advantage was not uniform across all refactoring types. The advantage concentrated on complex cases, where the multi-agent workflow handled more Move Method and Extract-plus-Move refactorings than the simpler strategies managed, and the paper attributes the gain to the iterative reasoning and feedback that passes between the two agents.
That result lines up with everything the rest of this workflow depends on: a second agent, or a second human reviewer, catching what the first pass missed is the same discipline as the diff review step, just running at a different scale. Parallel agents are a way to multiply a sound process across more of the codebase at once. Parallel agents still depend on the context discipline, the planning step, and the verification loop that make any single agent's output trustworthy. Research on constraint accumulation in LLM agents backs this caution directly: as structural requirements pile up in a single prompt, even capable agent configurations show a substantial decline in correctness, losing an average of 30 points in assertion pass rates. That finding argues for the same conclusion the rest of this piece has been building toward. Keep each agent's scope narrow, keep the architectural rules enforced outside the agent rather than inside its prompt, and let parallelism multiply disciplined work.


