How to Keep AI-Generated Code Reliable: Close the Loop with Tests
When AI now writes the majority of code in advanced teams, generating code is no longer the bottleneck — controlling its quality is. This article explains how to build an evidence loop in which an independent grading tool checks AI output against explicit acceptance criteria, shifting engineers from line-by-line reviewers into standard setters and exception arbiters. It covers why grading criteria are the most valuable infrastructure to invest in, how to turn recurring AI mistakes into durable rules and automation hooks, the two fatal failure modes to avoid (flaky and slow tests), and the test types most worth building — end-to-end and property-based testing first, with unit and contract tests as supplements. Readers will learn how fast, stable, hard-to-game verification is what makes AI-assisted development reliable and scalable.
Introduction: In the Age of AI-Generated Code, Management Matters More Than Generation
In leading AI coding teams, a striking pattern has emerged: roughly 90% of the code is now written by AI, and most of the self-review and self-checking is done by AI as well. Once generating code is no longer the bottleneck, the ability to “keep AI in check” becomes the core engineering capability. Here, “keeping it in check” does not mean restricting AI to write less. It means using an end-to-end, automatically executable verification system that keeps AI output continuously aligned with real goals. Understanding this logic offers direct value for any team that wants to bring AI into collaborative development without sacrificing quality.
1. The Evidence Loop: How One Person Directs Dozens of AIs
Human line-by-line review is a linear bottleneck. When every AI output must be checked by a person from top to bottom, one person can keep an eye on only one or two AIs at a time, and scale cannot grow.
What breaks this bottleneck is the so-called “evidence loop.” The idea is simple: instead of letting AI grade its own work, an independent grading tool checks AI output against explicit acceptance criteria. The grading tool has no bias; it answers just one question — did this output actually meet the standard?
Once the loop is in place, the human’s role shifts from “line-by-line reviewer” to “standard setter and exception arbiter.” An engineer no longer needs to read every line of code, only to define clearly what “correct” means and then handle the few failures the grading tool reports. This is why one person can direct dozens — even hundreds — of AIs working in parallel without worrying about quality spiraling out of control. The precondition for scale is precisely automated and standardized verification.
2. Why Grading Criteria Are the Infrastructure Most Worth Investing In
One counterintuitive but important observation from practice: when an independent grading tool rigorously checks AI output against criteria, task success rates improve by roughly ten percentage points, and the harder the problem, the more pronounced the improvement.
The reason is not hard to understand. Without grading criteria, AI can only rely on its own understanding to decide whether it is “done,” and it tends to wrap up while feeling good about itself. Once explicit acceptance criteria exist, AI gains a continuous, objective feedback signal: it keeps iterating until it truly passes. In essence, grading criteria convert a “vague subjective judgment” into a “clear programmatic signal” — exactly the kind of thing AI is best at exploiting.
In the past, writing tests, building benchmarks, and drafting technical specifications carried high marginal costs, so teams often hesitated to invest. Generative AI has changed that cost structure: a well-structured test, benchmark, or specification can now be drafted in seconds. More importantly, once generated, these tests become software that can be run repeatedly with deterministic behavior. Running them over and over costs almost no additional inference — which is fundamentally different from “regenerating the answer each time.” A one-time investment, reused over the long term: that is exactly the reason to pour resources into the test system.
3. Making Corrections Stick: Handling Errors AI Keeps Repeating
AI has a typical flaw: it falls into the same pit again and again. For example, it always prints user privacy fields into logs, or ignores a certain kind of boundary validation. If every correction relies on verbal reminders from humans, the errors are bound to recur.
The right approach is to turn corrections into durable constraints, across two layers.
The first is a rules file. Maintain an AI behavior constraint list at the project root that spells out what is “absolutely forbidden” and what “must be satisfied.” For example:
# Project-level AI behavior constraints (example)- Never output user PII fields in logs or exception messages (phone numbers, ID numbers, tokens)- All database migrations and data-cleaning logic must be idempotent: running once must equal running multiple times- End-to-end tests and property-based tests must pass before commit; a failing run cannot be merged- Justify new external dependencies before adding them, and prefer reusing existing capabilities
The second is automation hooks. Trigger checks automatically at key points (such as pre-commit or pre-merge), and block immediately when a rule is violated. The rules file is responsible for “telling AI what to do,” while the hooks are responsible for “forcefully blocking it when it gets it wrong.” The former provides guidance; the latter is a safety net. Combined, they prevent the same class of problems from recurring in later tasks.
4. Two Fatal Failure Modes
For this system to actually work, you must avoid two common ways it can “die.”
Flaky tests. If the tests themselves pass and fail intermittently, AI will “learn” an opportunistic strategy: instead of actually fixing the code, it reruns the suite repeatedly to gamble on a pass. This seems absurd on the surface, but for an agent whose optimization target is “pass the tests,” it is a perfectly rational choice. Once tests become flaky, what they convey is no longer a real quality signal but noise — and AI will optimize the noise rather than the code.
Slow tests. If a single test round takes too long, the frequency at which AI can batch-investigate problems drops sharply. Locating a defect normally requires multiple rounds of fast trial and error, but slow feedback makes each attempt expensive, stretches out the investigation cycle, and makes pinning down a problem extremely difficult.
The conclusion is direct: tests must be both fast and stable. Fast, so they can support high-frequency iteration; stable, so the signal stays trustworthy. Fail either one, and no amount of AI will amount to anything but idle spinning.
5. The Test Types Most Worth Investing In
Teams have narrowed down a few test types with the best return on investment. The core principle: prioritize verification methods that are “hard to bypass with shortcuts.”
First choice: End-to-end (E2E) tests
If you have energy for only one kind of test, choose end-to-end. It directly simulates what real users do — for example, adding a product to the cart, entering checkout, and landing on the payment-success page. These tests are hard to fool: the entire flow either works or it doesn’t, with no room for a lucky in-between state.
Their diagnostic value also far exceeds that of unit tests. When a unit test times out, it often only throws a vague error like “30-second timeout,” giving no clue about where things got stuck; an end-to-end test, by contrast, takes screenshots and produces a full execution trace, clearly pinpointing a concrete problem such as “why the checkout button is disabled.”
To make end-to-end tests genuinely reflect reality, give AI permission to operate a real environment: drive web pages through browser automation, run mobile apps through a mobile emulator, control desktop software through desktop automation, or bring up backend services directly on localhost. Pairing with this is a feature map that lists real users’ operation paths, key shortcuts, and expected behavior, serving directly as AI’s implementation guide and grading criteria — AI writes code against it and is also checked against it.
Illustrative end-to-end case (pseudocode):
Scenario: checkout1. Open the product detail page2. Click "Add to cart"3. Go to the cart and assert item count == 14. Click "Checkout" and assert the checkout button is clickable5. Submit the order and assert navigation to the "Payment successful" pageOn failure at any step: capture a screenshot + record the current page trace
Second choice: Property-based testing
Many tests cover only the paths humans can think of. Property-based testing targets the extreme edge cases that both humans and AI tend to miss. The approach: first write down one rule that “must never be broken” (an invariant), then use a property-based testing framework to automatically generate thousands of random inputs and try everything to break the program.
Common assertable properties include:
- Data must be fully restored after serialization and then deserialization;
- An account balance must never go negative under any sequence of inputs;
- The same migration or cleaning logic must produce exactly the same result whether run once or twice (idempotency);
- An optimized new implementation must produce bit-for-bit identical output to the old one on the same inputs.
Pseudocode example:
# Serialization round-trip invariant: any valid object should restore losslessly@given(generate_any_valid_data_object())def test_serialization_round_trip(data):assert deserialize(serialize(data)) == data# Idempotency: running a migration twice yields the same result as running it once@given(generate_any_valid_data_set())def test_migration_idempotent(data):once = run_migration(data)twice = run_migration(once)assert once == twice
Random boundary inputs carry no subjective bias, which makes them especially good at guarding against AI’s “taking things for granted.” They are particularly valuable in one scenario: refactoring. When the original specification has drifted from production reality and the documentation is outdated, rather than trusting human-written cases, it is better to lock down behavior directly with a property like “old and new outputs must be identical.”
Supplement: Unit and contract tests
Beyond the two types above, unit tests are still indispensable — they quickly lock down local logic. In systems with many split services, contract tests ensure that the interface agreements between services are not broken. Their shared role is that of “fast, local, stable” gatekeepers, forming complementary layers with end-to-end and property-based tests that span from micro to macro and from deterministic to randomized. When building a test system, you don’t need to pursue all of them; instead, prioritize laying the solid foundation of end-to-end and property-based tests, the two that are “hard to bypass.”
Conclusion
What makes AI-generated code truly reliable is never how fast it writes, but the fact that behind it stands a fast, stable, and hard-to-gamble-on verification system that continuously corrects course. Treat grading criteria as infrastructure to be built, turn corrections into rules and hooks, and drive the cost of generating and running tests down to near zero — do these things, and one person can calmly direct multiple AIs advancing in parallel while holding the line on delivery quality. This is the underlying logic that makes AI collaborative development genuinely scalable.
