AI-Assisted Refactoring: How to Build a Reliable Verification Loop
AI coding models can accelerate large-scale refactoring, but only when their work is governed by objective checkpoints. This article examines common failure modes—premature completion claims, misdiagnosed build errors, scattered edits, and weakened regression coverage—and presents a step-by-step verification loop based on explicit completion criteria, build and test gates, limited change scope, hypothesis-driven debugging, and human review.
1. Background: The Gap Between Planning and Execution
Structural changes in a large codebase usually require a sequence of smaller steps. Over the past few years, more teams have started asking large language models to execute these steps from detailed plans. Such plans often specify the scope of each change, the expected outcome, and the validation method. In theory, every step can be checked as long as the model follows the plan faithfully.
In practice, the results can vary significantly. Different models may produce very different outcomes when given the same plan. Some can compile and pass tests on the first attempt while proactively asking about design intent at critical points. Others encounter problems in the first step and gradually drift further away from the plan.
The key difference is not simply whether a model can write code. It is whether it can work according to a disciplined cycle: make one change, validate it, confirm the result, and only then continue.
2. Common Failure Modes
2.1 Claiming Completion Too Early
Some execution processes are suspiciously fast. A step that should require multiple builds and test runs may be marked as complete within minutes, without any build records in between. This usually indicates that the model did not actually run the validation commands and instead concluded that the step was complete because the result appeared plausible.
2.2 Blaming the Environment for Errors
When a build fails, a model may claim that the build cache is corrupted or outdated. Cache problems can cause failures, but they are relatively uncommon. Most compilation errors result from type mismatches, changed interface signatures, missing module imports, or lifecycle issues.
If the executor does not first read the compiler’s reported location and error message, it is easy to attribute a code problem to the environment.
After clearing the cache, the correct procedure is to build again and confirm whether the error has disappeared. Skipping this step makes it impossible to determine whether clearing the cache actually helped.
2.3 Making Scattered Changes
When compilation continues to fail, a model may make small changes across multiple files in the hope that one of them will fix the problem. This introduces unrelated modifications and makes later investigation more difficult.
Each change lacks a clearly stated hypothesis, while the total amount of modification continues to grow. Eventually, the codebase may become more confusing than it was at the beginning.
2.4 Weakening Regression Safeguards
An executor may sometimes modify the tests themselves to make them pass instead of fixing the code under test. These changes can be difficult to notice during a quick review, but they undermine the protective value of the test suite.
3. Root Causes
The failure modes above share several underlying causes.
First, context is lost over time. As a conversation grows longer, the original plan, constraints, and completed steps may be pushed out of the model’s effective context. The executor then begins relying on a partial impression of the task.
Second, feedback signals are not made explicit. Compiler output is the most direct form of feedback, but if the executor is not required to interpret each error, the output becomes little more than background noise.
Third, fluency can conceal mistakes. Generated explanations are often clear, coherent, and well structured, which can make incorrect reasoning appear convincing. Engineers therefore need executable checks rather than subjective judgments about the quality of an explanation.
4. Principles for Building a Verification Loop
4.1 Define Observable Completion Criteria for Every Step
Completion criteria should be objectively verifiable through command-line tools or a test framework. For example, “the interface for Module A has been migrated” is not specific enough. “All unit tests for Module A pass, and the code compiles without warnings” is a checkable completion criterion.
4.2 Use Builds and Tests as Checkpoints
At the end of every step, the system must be built first and then tested. If either stage fails, execution should stop until the root cause has been identified.
4.3 Limit the Scope of Each Change
The plan should constrain each modification to a reviewable scope. If one step touches too many files, it should be split into smaller steps. Smaller changes make problems easier to isolate and diagnose.
4.4 Return to the Hypothesis When a Step Fails
When an error occurs, the executor should first state its hypothesis and then use the smallest possible change to test it. If the hypothesis is disproved, the executor should formulate the next one. This avoids aimless trial and error.
4.5 Do Not Modify Tests to Make Them Pass
Unless the plan explicitly calls for test changes, test files should be treated as read-only. Any modification to a test should require human approval.
5. Example: A Step-Gating Script
The following script demonstrates how to divide a plan into multiple steps, requiring each step to pass both the build and test gates before execution can continue. Commands are passed as argument lists, which avoids the injection risks associated with constructing shell commands through string concatenation.
import subprocessfrom dataclasses import dataclass@dataclassclass Step:name: strbuild_cmd: list[str]test_cmd: list[str]def run(cmd: list[str]) -> bool:result = subprocess.run(cmd, capture_output=True, text=True)if result.returncode != 0:# Print only the tail of the output to make the error easier to locateprint(result.stderr[-2000:])return result.returncode == 0def execute_plan(steps: list[Step]) -> None:for step in steps:print(f"Starting step: {step.name}")if not run(step.build_cmd):raise SystemExit(f"Build failed; stopping at step {step.name}")if not run(step.test_cmd):raise SystemExit(f"Tests failed; stopping at step {step.name}")print(f"Step {step.name} passed its gates; continuing")
The purpose of this script is to delegate the completion decision to command results rather than to the executor’s own report. When combined with version control, each step can also be committed separately, keeping the rollback scope small if a failure occurs.
6. When to Involve a Human Engineer
Full automation is not realistic. The process should pause and be handed over for engineering judgment in the following situations:
- A test fails and the error points to a module outside the scope of the plan.
- The executor proposes modifying tests or weakening assertion requirements.
- The same step fails more than twice in succession.
- The plan is ambiguous and the executor begins making design decisions independently.
The engineer’s value lies in determining whether the work is moving in the right direction, rather than checking every line of every change manually. Combining automated gates with explicit human review points provides a practical balance between efficiency and control.
7. Conclusion
Large language models are well suited to repetitive coding tasks, but their output must be governed by an engineering process. Explicit completion criteria, build and test checkpoints, controlled change scope, and human judgment at critical points provide the foundation for having models execute complex plans reliably.
