How to Stop AI Coding Agents from Introducing New Bugs: An Engineering Guide
AI coding agents often fix one thing and break two others, especially when collaboration lacks engineering constraints. This guide explains why it happens and how to control it through task scoping, plan-first workflows, evidence-based verification, diff review, context hygiene, worktree isolation, and test-change discipline, plus a pre-completion checklist.
1. The Problem Is Not a “Dumb” Model, but a Missing Engineering Framework
Once AI coding agents became common, one complaint came up constantly: you ask for one small change, and two new problems appear. Worse, the tests turn green too, so the wrong behavior only surfaces during acceptance.
Blaming all of this on model capability is a misdiagnosis. The more common cause is that the collaboration process lacks engineering constraints. Four issues stand out:
- Task granularity is too coarse: A single sentence bundles refactoring, optimization, and bug fixing. The model has to infer the boundaries itself, and any wrong inference turns into out-of-scope changes.
- No definition of done: If you never say what “finished” means, the model defaults to “the code compiles and the tests run.”
- Session context pollution: When you keep appending instructions to the same session, early failed attempts, rejected proposals, and temporary debugging code all stay in the context. The model treats them as valid premises.
- Incomplete verification loop: You accept “the tests passed” as a conclusion without checking the command that ran, the coverage, or the actual diff.
These four issues stack up, and they will reproduce with any tool. So the fix is not “switch to a stronger model.” It is to bring code writing back into a controlled process. The methods below can be applied directly.
2. Task Breakdown: Downgrade “Refactoring” to a Verifiable Minimal Change
New bugs thrive in the extra changes a model makes “while it is there”: renaming a variable, adjusting null handling, unifying code style. Each change may be reasonable on its own, but it is unrelated to the main goal and extremely hard to trace when something breaks.
The way to constrain this is to write the scope into the instruction and explicitly declare the no-go zones:
Task: Modify only the client-side validation logic of the login form.Scope: Validation functions under the src/forms/login directory.Do not: Do not touch the API request layer, do not touch style files, do not adjust shared utility functions, do not add dependencies.Definition of done: Empty usernames and invalid email formats produce clear messages; the behavior of all other fields stays unchanged.
The key parts are the “Do not” list and the “Definition of done.” The first shrinks the change radius; the second gives a decidable termination condition. A practical rule: if a requirement contains phrases like “while you are at it,” “optimize a bit,” or “do an overall cleanup,” it has not been broken down to an acceptance-ready granularity and should be split further.
3. Plan First: Confirm Boundaries at Very Low Cost
When the requirement is on the larger side, ask for a short plan before any code is written. It costs a few lines and pays off by exposing out-of-scope intent early. The plan only needs to answer three things: which files change, what changes in each file, and how it will be verified.
Draft plan1. Modify the query conditions in user/service and add tenant-dimension filtering2. Add service-layer unit tests covering cross-tenant access scenarios3. Do not touch the controller layer or the frontendVerification: Run the service module unit tests and paste the output
One glance at this plan lets you cut out-of-scope items on the spot, which is far cheaper than rolling them back later. It is worth noting that heavy planning modes and complex skill orchestration are not daily necessities: for small changes, direct execution is more efficient. A heavier process is worth it only when the change crosses modules or touches data structures or interface contracts. Tool selection should match task complexity rather than defaulting to the highest setting.
4. Verification Loop: Accept Output, Not Conclusions
“The tests passed” is not acceptable, because it does not say which suite ran or whether it covered this change. An executable acceptance protocol is to have the model run the tests itself and paste back the full command and raw output.
Command: npm run test -- user/serviceResult: 3 passing, 0 failingDuration: 1.8s
As the receiver, check three things: whether the command targets the relevant module, whether the number of cases is proportionate to the pre-change baseline, and whether any failures were skipped. If it does not pass, have the model fix it and rerun, looping until the output is clean. This turns “trust the conclusion” into “verify the evidence,” and it is the highest-value step in the whole process.
5. Diff Review: What Green Tests Cannot Cover
There is a typical failure: the report says done, all tests are green, and acceptance still fails. The reason is that the existing cases do not cover the scenario at all. Passing tests only prove that “the covered parts have not regressed.”
So the diff must be reviewed, but not line by line. Move from coarse to fine in three layers:
- File layer: Check whether any file that should not change is in the list, especially configuration, dependency declarations, and shared components.
- Structure layer: Check which functions and branches were added, and whether abstractions unrelated to the task were introduced.
- Critical layer: Focus on the core conditional logic, boundary conditions, and error-handling paths.
A useful signal is the change size: if the number of changed lines far exceeds what the task requires, you can basically conclude there is scope creep or over-engineering.
6. Context Hygiene: When It Gets Messy, Restart Instead of Appending
When the same session starts going in circles or contradicting itself, appending more prompts usually makes the drift worse, because the failed context keeps influencing the output. The right move is to restart, and before restarting, pin the premises into a project-level instruction file (such as CLAUDE.md at the repository root) or a handoff note:
## Project constraints- Tech stack and directory responsibility boundaries- List of directories that must not be changed- Test commands that must pass before committing## Current task- Goal: Add tenant-dimension data isolation- Done: Filtering conditions in the service layer- Pitfalls already hit: Do not concatenate tenant conditions in the repository layer; it breaks indexes
Starting a new session with these premises turns “tacit agreement” into “explicit input.” It shortens the ramp-up and avoids repeating the same mistakes.
7. Parallel Development: Isolate Change Risk with Worktrees
When multiple tasks run in parallel, have multiple agents work in their own independent git worktrees, one agent per directory and branch. There are three benefits: no interference at the file level; a broken task only requires discarding its branch; and diffs can be reviewed one by one before merging, with clear responsibility boundaries. Combined with static checks, unit tests, and artifact builds in the pipeline, you can intercept most problems before merging. Logs and monitoring alerts are then used to observe real behavior after release.
8. Principles for Handling “Tests Turned Green”
Two cases must be distinguished. Updating cases to adapt to a new interface contract is normal maintenance. Loosening assertions, adding skip markers, or replacing a key dependency wholesale with a stub just to make the result green is trading tests for a pass.
The principle is: whenever you find a test file was changed, pause acceptance first and require an item-by-item explanation of what changed and why. Tests the model turned green by itself cannot serve as acceptance evidence; restore the original assertions, or add cases that genuinely reflect the expected behavior and rerun. The judgment can be simplified to one sentence: does this change make verification stricter or looser?
9. Pre-Completion Self-Check
- Can this task be split smaller, and are the no-go zones clearly written?
- For larger requirements, has the plan been confirmed free of scope creep?
- Did the model run the tests, and have I seen the command and raw output?
- Does the diff contain files or dependency changes unrelated to the task?
- Were test files modified, and did the modification make verification stricter?
- Has the context clearly become dirty, and does it need a restart with a handoff?
10. Conclusion
The output quality of AI coding tools is largely determined by input constraints and acceptance mechanisms, not by model capability alone. Cut tasks smaller, write boundaries clearly, turn verification into evidence checking, and treat context as a resource to be governed. Do these four things well, and “fix one thing, break two” turns from an occasional incident into an engineering problem that is traceable, rollback-able, and preventable. If your team already builds its R&D process in the cloud, you can further use common capabilities such as container platforms, pipelines, log services, and monitoring alerts to turn these constraints into automated gates, so the standards rely on mechanisms rather than individual memory.
