AI Code Refactoring: How to Refactor at Scale
How AI code refactoring works, where it breaks down on large codebases, and how to apply and track refactors across every repo with Batch Changes.

How AI code refactoring works, where it breaks down on large codebases, and how to apply and track refactors across every repo with Batch Changes.
An AI agent can rename a variable, extract a method, or untangle a gnarly conditional in seconds, and when pointed at one file, the suggestion is usually good. The trouble starts when the same deprecated call lives in 300 repositories, and "refactor this" turns into "find every occurrence, change each one consistently, open the pull requests, and chase them all to merge." That gap, between a clean suggestion in one editor and a finished change across an entire org, is what most writing on AI code refactoring skips. This post covers how AI code refactoring works, where it stalls on large codebases, and the find-and-track workflow that closes the gap.
Refactoring, in Martin Fowler's original sense, is "a disciplined technique for restructuring an existing body of code, altering its internal structure without changing its external behavior." AI code refactoring preserves that definition and changes the actor: instead of a developer applying each transformation by hand, a model trained on large codebases proposes or applies the change, while the observable behavior remains the same.
What it's genuinely good at is the mechanical, local stuff. A large-scale study of AI coding agents on open-source Java projects, Agentic Refactoring: An Empirical Study of AI Coding Agents, found agents explicitly target refactoring in 26.1% of their commits, skewed heavily toward low-level edits: changing a variable type (11.8%), renaming a parameter (10.4%), renaming a variable (8.5%). The motivations were almost entirely internal quality: maintainability (52.5%) and readability (28.1%). Those percentages refer to the open-source Java dataset, not to AI refactoring in general.
What AI refactoring can't do on its own is judgment. The same study found that the structural quality gains were "small but statistically significant," most pronounced for medium-level changes on the Java dataset, with high-level design decisions remaining with human developers. A model has no idea that the class it's happily shrinking is the one your billing system depends on, or that the duplication it's collapsing is load-bearing technical debt someone left for a reason. Fowler's caution still holds in the AI era: tooling buys speed, but "small steps" and "frequent testing" buy safety. Treat an AI refactor like a fast junior engineer's PR: plausible, useful, and not done until your tests say it is.
AI refactoring tools run a three-stage loop, and knowing the stages tells you where each one breaks.
Identify. First, the tool finds what's worth changing. Some models treat code as a token stream and pattern-match for code smells such as duplicate functions, overly long methods, unclear names, and tangled conditionals. The output is a set of candidate transformations, such as extract function, move method, or rename variable.
Transform. Then it rewrites. AST-based and codemod tools don't edit text blindly; they parse code into an Abstract Syntax Tree and manipulate that, so the resulting state still has to compile, run correctly, and keep the codebase's logical structure intact. Working on the tree rather than raw characters is what separates a rename that understands scope from a find-and-replace that breaks three unrelated functions sharing one string.
Review. Finally, a human checks it. This stage is non-negotiable because models lack the contextual awareness to know which "intricate logic or sophisticated architecture" they're about to disturb. Review is also where behavior preservation gets verified: refactored code can look cleaner and still introduce a bug that only surfaces under a specific input.
That loop describes a refactor in one place. The enterprise problem is that the same diff has to land in hundreds of places at once.
A single-file refactor is a solved problem. Your IDE does it, and now an agent does it faster. The wheels come off the moment the change crosses a repository boundary, which is exactly where enterprise AI refactoring lives.
Consider a routine task: a deprecated authentication client must be replaced across the org. In one repo, that's a ten-minute job. Across hundreds of services, it splits into four problems, and AI only helps with one:
This is the half of refactoring an in-editor assistant structurally cannot reach: its context window ends at the repository it's looking at. Refactoring at scale is less a code-generation problem than a coordination problem, and coordination is where large efforts quietly die.
The fix is to invert the workflow. Instead of opening code and refactoring what you happen to see, you enumerate the change across the whole codebase, apply it everywhere from one reviewed spec, and track each changeset until it merges. Enumerate, change, track. AI-assisted refactoring plugs into the middle of that loop, while infrastructure handles the two ends an agent can't reach.
Enumerate with cross-repo search. Before changing anything, you need a trustworthy list of every place the pattern appears. Sourcegraph's Code Search runs literal, keyword, and regex queries across an entire organization's codebases, whether 100 or a million-plus repositories, and resolves symbols across repository boundaries with SCIP-based precise indexing across GitHub, GitLab, Bitbucket, Gerrit, and Perforce. Precise code intelligence narrows raw text matches to real symbol and call-site matches, so you're tracking down actual uses of the deprecated client, not every file that mentions its name. That list becomes the spec for the change.
Change and track with batch automation. Once you know the blast radius, the transformation has to land everywhere consistently and stay visible. Batch Changes applies a single declarative change across all the affected repositories, then tracks every resulting changeset through CI checks and code review as each one moves toward merge through its repo's normal process. The declarative spec is where an AI-generated transform fits naturally: an external AI assistant or codemod produces the per-file edit, and Batch Changes runs that transform across the org. It's the same mechanism teams use to pay down technical debt and ship security fixes across every repo at once.
For teams running migration agents, that cross-repo context is what lets the agent make accurate, deterministic changes instead of guessing at a codebase it only partially sees.
Walk that deprecated-auth-client refactor end-to-end. Say legacyAuth.authenticate() has to become authClient.verify() everywhere.
Step 1: Enumerate. Run a cross-repo regex search to find the call sites, then refine with symbol search or precise code navigation so you're matching real references rather than comments or unrelated mentions:
authenticate\( lang:typescript patterntype:regexp
The result is a concrete count: say, 312 call sites across 180 repositories. That number is the project plan.
Step 2: Draft the transform. Let an AI assistant write the per-file edit plus a test that proves behavior is preserved. The change is small and local, exactly what the research shows agents do well:
- const session = legacyAuth.authenticate(user, token);
+ const session = authClient.verify(user, token);
Notice the call signature and arguments stay the same; only the client changes, which is what keeps this a refactor and not a behavior change.
Step 3: Apply from one spec. Encode that edit in a declarative batch spec and run it across all 180 repositories. Each repo gets its own pull request against its own CI and owners, all from one source of truth, so the transform is identical everywhere rather than 180 slightly different hand edits.
Step 4: Track to completion. Watch the changesets as a single rollout: which PRs passed CI, which are awaiting review, and which teams are sitting on the change. The refactor is done when the last of the 312 call sites merges, not when the diff is generated, so stragglers stay visible rather than lingering in some repo nobody owns.
Scaling AI refactoring introduces failure modes that a single-file change never has. A few practices keep large efforts honest.
AI doesn't remove the human from code review; it changes what the human reviews. Your engineers stop writing each edit and start validating a consistent transform and confirming the high-level design still holds. The win is reach, not autonomy.
The temptation with any AI tooling is to measure activity (lines changed, PRs opened) instead of outcomes. For refactoring at scale, two signals matter more.
Coverage and completion. The first question isn't "how fast?"; it's "did we get all of it?" An enumerated search gives you a denominator: 312 call sites. Completion is the share merged. A migration that's 95% done with 15 call sites stranded in unmaintained repos isn't 95% safe because the stragglers are exactly where the next incident hides.
Time-to-merge, not time-to-write. AI compresses the writing; the real cost is the coordination tail of review latency, CI flakiness, and teams that need a nudge. Tracking time from spec to the last merged changeset measures the bottleneck that actually determines when a refactor ships.
Quantcast is a concrete reference point. After standardizing on organization-wide search, a single engineer analyzed thousands of repositories in a few days, work that would otherwise have taken months, saving hundreds of developer hours on a GDPR-driven refactor without risking production stability. The lever wasn't AI writing code faster; it was making the codebase searchable and the change trackable, so a refactor that was impossible for one person became a few days of work.
Workiva saw the same pattern from the other direction: an 80% reduction in time to perform code migrations by coordinating changes through the platform instead of repo by repo.
AI made the easy half of refactoring nearly free: a model drafts a clean rename or extracts a method faster than you can describe it. The half that's still hard is everything after the suggestion: finding every occurrence across the org, applying the change consistently, and tracking it to merge. Treat AI as the fast local cleanup partner it actually is, and put the cross-repo coordination on infrastructure built for it.
If your refactors keep stalling at the repository boundary, start with the enumerate-change-track loop: see how Batch Changes runs a single declarative change across every connected repo, then schedule a demo to walk through a real large refactor with the team.
Can AI refactor an entire codebase automatically? Not safely, and not on its own. AI is reliable at local, mechanical transforms (renames, type changes, extracting methods), and the research shows that's where agents concentrate. Refactoring across many repositories also means enumerating every occurrence and tracking each change to merge, which an in-editor model can't do past its own context window.
What's the best AI for refactoring code? The right tool depends on the blast radius. For a single file, your IDE's built-in refactorings or an in-editor assistant are usually enough. For a change that spans repositories, the bottleneck shifts from writing the edit to finding every occurrence and coordinating the rollout, a different class of tool. Our roundup of code refactoring tools breaks down which tier fits which job.
Can AI refactor legacy code? Yes, with guardrails. Legacy code is often where tests are thinnest, which is the worst place to trust an unverified transform. The safe pattern: add characterization tests first, let AI handle the mechanical cleanup, and keep a human on the design-level calls. The same regression-suite safeguard applies here: confidence isn't verification.

With Sourcegraph, the code understanding platform for enterprise.
Schedule a demo