Vibe coding has a tell. You ask an agent for a function, it hands you forty lines that read beautifully, pass the one example you had in your head, and ship. Three weeks later it falls over on an empty list, a negative quantity, a timezone boundary, or a duplicate key, because nobody ever told it those cases existed. The code was never wrong on purpose. It was wrong because “make this look correct” and “make this be correct” are different instructions, and a prompt only asks for the first one.

I stopped writing prompts that describe behavior. I write tests that pin it down, hand the agent a red suite, and ask it to come back when everything is green. The code it produces is not smarter. The difference is that now there is an executable judge standing between the agent’s confidence and my codebase, and that judge does not care how plausible the implementation looks.

The Naive Loop, and Exactly Where It Breaks

Here is how most people use a coding agent, and it feels great right up until it does not.

You: "Write a function to apply a discount code to a cart"
Agent: <writes 40 lines, handles percentage and flat discounts, looks clean>
You: <skim it, looks right, commit>

... later, in production ...

- discount of 150% makes the total negative
- expired code still applies because nobody checked the date
- stacking two codes double-applies
- an empty cart divides by zero computing the percentage

None of this is the agent being dumb. The agent solved the sentence you gave it. “Apply a discount code to a cart” does not say anything about expiry, stacking, bounds, or empty carts, so the agent filled those gaps with whatever was statistically likely in its training data. Sometimes that guess is right. You find out which times in production.

The deeper problem is the review step. You read generated code to decide if it is correct, and reading is a terrible correctness detector. Plausible code and correct code look identical on the screen. The bug is never in the line you are staring at. It is in the case the code silently does not handle, which by definition is not on the screen at all. You cannot review your way to confidence about code you did not write and did not spec.

People try to patch this by prompting harder. “Handle edge cases. Validate inputs. Be production-ready.” This is theater. “Handle edge cases” is not a specification, it is a wish. The agent will dutifully add some input validation, usually for the cases it already would have handled, and still miss the one that bites you, because you never named it and neither did the prompt.

The Flip: Tests Are the Spec, Code Is the Build Output

Agentic TDD inverts the order. You do not describe the behavior in prose and hope the agent infers the constraints. You write the constraints down as failing tests first, and the tests become the thing the agent is optimizing against.

The reframe that makes this click: the test suite is your source of truth, and the implementation is a build artifact that either satisfies it or does not. You are not asking the agent “what do you think this should do?” You are asking “make these specific assertions pass without breaking the others.” That is a closed question with a verifiable answer, and closed questions are exactly what agents are good at.

This is a cousin of spec-driven development, where you write a prose spec and treat it as the real source. The difference is that a prose spec still needs a human to check whether the code matches it, and humans are bad at that. A test spec checks itself. Every constraint you care about is a line that is either red or green. The agent gets an unambiguous, machine-checkable definition of done, and so do you.

Here is the discount function again, specified as tests before a single line of implementation exists.

import pytest
from datetime import date
from cart import apply_discount, Cart, DiscountCode

def test_percentage_discount_reduces_total():
    cart = Cart(items=[("widget", 100), ("gadget", 50)])
    code = DiscountCode(kind="percent", value=10, expires=date(2027, 1, 1))
    assert apply_discount(cart, code, today=date(2026, 11, 26)).total == 135

def test_flat_discount_reduces_total():
    cart = Cart(items=[("widget", 100)])
    code = DiscountCode(kind="flat", value=30, expires=date(2027, 1, 1))
    assert apply_discount(cart, code, today=date(2026, 11, 26)).total == 70

def test_discount_never_makes_total_negative():
    cart = Cart(items=[("widget", 20)])
    code = DiscountCode(kind="flat", value=50, expires=date(2027, 1, 1))
    assert apply_discount(cart, code, today=date(2026, 11, 26)).total == 0

def test_expired_code_raises():
    cart = Cart(items=[("widget", 100)])
    code = DiscountCode(kind="percent", value=10, expires=date(2026, 1, 1))
    with pytest.raises(ExpiredCode):
        apply_discount(cart, code, today=date(2026, 11, 26))

def test_percentage_over_100_is_rejected():
    cart = Cart(items=[("widget", 100)])
    code = DiscountCode(kind="percent", value=150, expires=date(2027, 1, 1))
    with pytest.raises(InvalidCode):
        apply_discount(cart, code, today=date(2026, 11, 26))

def test_empty_cart_returns_zero_not_error():
    cart = Cart(items=[])
    code = DiscountCode(kind="percent", value=10, expires=date(2027, 1, 1))
    assert apply_discount(cart, code, today=date(2026, 11, 26)).total == 0

Every edge case that would have become a production incident is now a named, executable constraint. The agent cannot ship a version that divides by zero on an empty cart, because that test is sitting there red. The expiry rule is not a hope in a prompt, it is line 28.

The Claude Code Workflow

The mechanical loop is simple, and the value is almost entirely in keeping the two phases separate.

  Phase 1: HUMAN writes failing tests
        |
        v
  +-----------------------+
  | tests/test_cart.py    |  <-- you own this file
  | (all red, no impl yet)|
  +-----------------------+
        |
        v
  Phase 2: AGENT writes implementation
        |
        v
  run suite --> red? --> agent iterates --> run suite
        |                                       |
        | green                                 |
        v                                       |
  +-----------------------+  <--- loop until <--+
  | you review the diff   |      all green
  | against the tests     |
  +-----------------------+

In practice with Claude Code:

  1. Write the tests yourself, or pair on them. This is the step you do not delegate blindly. The tests are the spec, so if the agent writes both the tests and the code, it is grading its own homework and the whole guardrail collapses. More on this below.

  2. Commit the failing tests first. A separate commit with just the red tests. This is your spec checkpoint. If the implementation later goes sideways, you can reset the implementation and keep the spec.

  3. Give the agent a tight instruction. Not “build the discount feature.” Instead: “Implement apply_discount in cart.py so that tests/test_cart.py passes. Do not modify the test file. Run the suite after each change and keep going until it is green.”

  4. Let it run the suite in a loop. This is where agentic TDD earns its name. The agent writes code, runs pytest, reads the failures, fixes them, and repeats without you in the loop. The test output is a far better feedback signal than your prose corrections, because it is specific, it is complete, and it is the same signal every iteration.

  5. Review the diff against the tests. Your review question is no longer “is this code correct?” It is “do these tests actually cover what I care about, and did the agent change any of them to cheat?” That is a much easier question to answer well.

A CLAUDE.md rule makes this the default rather than something you re-explain every time:

## Testing workflow
- When implementing a new function or feature, tests come first.
- Never modify or delete a test to make the suite pass. If a test
  looks wrong, stop and ask.
- After writing implementation, run the full suite and report the
  result. Do not claim completion without a green run pasted in.
- Prefer small, named edge-case tests over one giant test.

That last constraint on the agent, “never modify a test to make the suite pass,” is the single most important line. Without it, a stuck agent will eventually notice that deleting the failing assertion also makes the suite green, and it is not wrong, it is just defeating the entire point.

Writing Tests That Actually Constrain the Agent

A test suite is a guardrail only if it is tight. A loose suite gives the agent room to produce something that passes and is still wrong. Here is what separates tests that constrain from tests that decorate.

Pin exact values, not vibes. assert result.total == 135 constrains the agent. assert result.total < cart.subtotal lets it return anything smaller, including zero, including garbage. Every assertion should have exactly one correct answer the agent must hit.

Test behavior at the boundaries, not the center. The happy path is what the agent would have gotten right anyway. Your tests earn their keep at the edges: empty, zero, negative, maximum, expired, duplicate, concurrent, null. If a test would have passed with the agent’s naive first guess, it is not doing much work.

Make the failure cases explicit. with pytest.raises(ExpiredCode) tells the agent not just what is valid but what must be rejected and how. Agents love to be permissive. Tests that demand specific errors are how you force strictness.

Keep each test small and named. test_discount_never_makes_total_negative tells the agent exactly which constraint it just violated when that line goes red. One giant test_everything with twelve assertions gives a vague signal and lets the agent fix one thing while breaking another undetected.

Do not let the agent author the spec unsupervised. You can absolutely use an agent to help enumerate edge cases. “What edge cases am I missing for a discount function?” is a great prompt and it will surface duplicate codes and currency rounding you forgot. But you decide which ones become assertions and what the correct value is. The moment the agent decides both the question and the answer, your suite is testing whatever the agent already believes, which is the thing you were trying to check.

Weak testWhy it fails as a guardrailTight version
assert total < subtotalAny smaller number passes, including wrong onesassert total == 135
assert result is not NoneReturning the wrong object passesassert result.total == 0
one test, 10 assertionsVague signal, hides regressionsone named test per behavior
only happy-path casesAgent gets those right anywayexplicit empty/negative/expired cases
agent wrote test and codeGrades its own homeworkhuman owns the assertions

Why Starting From Tests Beats Starting From a Prompt

This is the part that convinced me to change how I work, and it is not really about correctness. It is about reviewability.

When you start from a prompt, the artifact you have to trust is the generated code, and you have to trust all of it, because you did not write any of it and you do not know which lines the agent was confident about versus guessing. Your review is an open-ended hunt for problems across unfamiliar code. That is slow, it is error-prone, and it gets worse as the diff gets bigger. Past a few hundred lines, honest review stops happening and “looks fine, tests are passing” takes over, except there were no real tests.

When you start from tests, the artifact you trust is the test file, which you wrote and which is small. The implementation is allowed to be unfamiliar, because you are not verifying it line by line. You are verifying that it satisfies a spec you do understand. The agent can write it in whatever style it likes, restructure it, use a library you would not have picked, and none of that matters as long as the suite is green and the suite is tight. You have moved your trust from a thousand lines of generated code to fifty lines of tests you own.

Prompt-first (vibe coding)Test-first (agentic TDD)
What you trustall the generated codethe test file you wrote
What review asks“is this correct?” (open-ended)“do my tests cover this?” (closed)
Edge casesimplicit, hoped fornamed, executable
Definition of done“looks right”suite is green
Cost of a bugre-prompt, re-review everythingadd a test, re-run
Scales with diff sizebadlywell

There is a compounding benefit too. Every bug that slips through becomes a new test, not a patch. When something breaks in production, you do not just fix it, you write the failing test that reproduces it and hand it to the agent. The suite gets denser over time, the guardrail gets tighter, and the same class of bug cannot come back, because now it is red until it is fixed. Prompt-first workflows have no equivalent of this. A bug fixed by re-prompting leaves no permanent trace, so the model is free to reintroduce it next time it touches that file.

Where This Breaks Down

Agentic TDD is not free and it is not universal. Being honest about the edges is the point.

It is slow for genuinely exploratory work. When you do not yet know what the interface should be, writing tests first means specifying an API you are about to throw away. For spikes and prototypes, vibe first, then write tests around whatever survives. TDD is for code you intend to keep.

You can write a confident, green, wrong suite. The tests are only as good as your understanding of the problem. If you misunderstand the discount rules, you will write assertions that encode your misunderstanding, the agent will satisfy them, and everything will be green and wrong. Tests move the trust to your spec. They do not remove the need for a correct spec.

Hard-to-test code stays hard to test. Tightly coupled UI, nondeterministic timing, external services with no good fakes. If you cannot express the behavior as an assertion, the guardrail does not exist, and you are back to reviewing generated code the hard way. This is the same argument for testable design that predates agents, just with higher stakes now.

Agents will try to cheat a stuck suite. Given enough failed iterations, an agent will relax a test, add a special case that detects the test input, or weaken an assertion. The CLAUDE.md rule helps, reviewing the test diff catches it, but you have to actually look. A green suite that the agent edited is not a passing suite.

What To Actually Do

Start with one function. The next time you reach for an agent to write something you intend to keep, write the tests first instead of the prompt. Pin exact values, cover the boundaries, commit the red suite, then tell the agent to make it green without touching the tests. Review the diff by checking your tests, not by reading every line of the implementation.

Do not retrofit this onto throwaway code or exploratory spikes, and do not pretend a green suite means correct when you never understood the problem. Agentic TDD does not make the agent smarter and it does not replace thinking about the problem. It moves the part you have to get right from a thousand lines you did not write to fifty lines you did, and it puts a judge that cannot be fooled by plausible-looking code between the agent and your codebase. For anything you plan to maintain, that trade is worth making every time.