SevyDevy

Spec-Driven Development Explained: Make AI Agents Code to a Contract

, Last updated , 20 min read

Summary

  • Spec driven development means you write a short spec and the tests first, then let an AI coding agent write code until those tests pass. You review the spec and tests closely.
  • A spec is a plain list of rules the code must follow. Tests are small programs that check those rules automatically, so nobody has to trust the agent's word that it is done.
  • Spec and tests together form the contract. The agent may change the code but never the contract, and an automatic check on every change fails if it tries.
  • Tests can be too weak. In our run, two example tests passed a wrong bill splitter, while property-based tests, which check a rule on 100 generated inputs by default, caught it at once.
  • Beginners can stop after the step-by-step section. Engineers get runnable tests in pytest and Hypothesis (Python testing tools), a planted-bug check where weak tests caught 0 of 4 bugs, and a script that blocks test edits.

What goes wrong when you let an AI agent code from a one-line request?

The agent fills every gap in your request with its own guess, and the code looks finished either way. You then have two bad choices: read every line, or trust it. Spec driven development gives you a third choice.

An AI coding agent is a program that uses a large model to read your files, edit code and run commands until it thinks the task is done. It is fast. It is also confident when it is wrong.

Picture a common setup. A small team runs an expense app where friends split restaurant bills, and they ask an agent to "add a function that splits a bill evenly". The setup is made up, but the bug below is real and we ran it. The agent writes three lines, adds two tests, and both pass.

A week later a user splits a 100 rupee bill three ways. Each person is charged 3,333 paise, which is 9,999 paise in total. One paisa has vanished. Across 1 lakh (100,000) bills a day, those paise add up, and the accounts stop matching (made up).

Nothing in the request said what "evenly" means when the money does not divide. The agent picked an answer, wrote tests that agreed with its own answer, and reported success. Spec driven development fixes this by deciding those answers before any code exists.

Which words do you need before spec driven development?

You need five words: spec, test, contract, agent and property. Each gets a plain meaning here.

  • Spec: a short written list of rules the code must follow. It says what must be true, not how to write the code.
  • Test: a tiny program that calls your code and checks one result. It prints pass or fail, so a machine can judge the work.
  • Contract: the spec plus its tests. It is the part you, the human, own and review.
  • Agent: the AI coding program that writes the code. It works inside a loop of editing files and running commands.
  • Property: a rule that must hold for every input, such as "the shares always add up to the total". A property-based test checks it on many generated inputs.

Specs often use the words MUST, SHOULD and MAY. RFC 2119, a 1997 internet standards document, fixed their meaning. MUST is an absolute requirement, SHOULD allows exceptions you can justify, and MAY is truly optional.

What is spec driven development?

Spec driven development is a way of working where a written spec, checked by tests, is the source of truth for both you and the AI agent. The agent writes code to satisfy it, and you judge the result against it.

The term is new and still shifting. An October 2025 article on martinfowler.com described a spec as a structured, behaviour-focused document written in plain language to guide a coding agent. The same article warned that people already stretch "spec" to mean any detailed prompt.

That article also named three levels of commitment. They differ in what happens to the spec after the first task.

Three levels of spec driven development (from the October 2025 martinfowler.com article)
LevelWhat happens to the specWho edits the code later
Spec-firstWritten before the task and used for that task onlyHumans and agents, as usual
Spec-anchoredKept after the task and updated when the feature changesHumans and agents, with the spec kept in step
Spec-as-sourceThe spec is the main file; code is regenerated from itNobody edits code by hand

This guide teaches spec-anchored work with tests attached. The spec lives in the repository next to the code, and its tests run on every change. Spec-as-source was still experimental in that article, which also found that one spec could produce different code each time.

If this sounds like test-driven development, it is close. Test-driven development, credited to Kent Beck in the late 1990s, means writing a failing test, then just enough code to pass it, then cleaning up. Spec driven development keeps the tests-first habit but hands the middle step to an agent.

How does spec driven development work, step by step?

You write the rules, turn them into tests, and let the agent loop until the tests pass. Then you review the contract and the risky parts of the code, not every line.

Think of an exam. The spec is the question paper, the tests are the marking scheme, and the agent is the student writing answers. The examiner does not reread every word; the marking scheme decides most marks.

Where the picture breaks: a student cannot rewrite the marking scheme, but an agent with file access can edit your tests. A marking scheme also only checks what it asks. Both gaps get their own section below.

  1. Write the spec

    List the rules as numbered MUST lines, plus what is out of scope. Keep it to one screen for one function or feature.

  2. Write the tests from the spec

    Give every rule at least one test, and label each test with its rule number. Run pytest once; it should report an error, because the code file does not exist yet.

  3. Protect the contract

    Mark the spec and test files as human-owned, and add a build check that fails if the agent changes them.

  4. Hand the agent the spec and the test command

    Ask it to make the tests pass without editing the spec or tests. Point it at the files rather than pasting a long prompt.

  5. Run the checks yourself

    Run the tests and the guard in CI, a server that runs checks on every change. Never accept the agent's own report that tests pass.

  6. Review the contract, then the risky code

    Read any change to the rules first. Then read the code for things tests cannot see, such as secrets, database access and speed.

The spec driven development loop

Notice that the agent sits inside the loop and the human sits at both ends. The No arrow is where most of the agent's work happens.

Diagram connections:

  • Human writes the spec to Human writes the tests (Each rule gets a test)
  • Human writes the tests to Agent edits the code (Spec and test command)
  • Agent edits the code to CI runs guard and tests (Pushes a change)
  • CI runs guard and tests to Guard and tests pass?
  • Guard and tests pass? to Agent edits the code (No: failures go back)
  • Guard and tests pass? to Human reviews (Yes)
  • Human reviews to Merged to main (Approved)
  • Human writes the spec: Numbered MUST rules and what is out of scope
  • Human writes the tests: One or more tests per rule; no code exists yet
  • Agent edits the code: May change code files only
  • CI runs guard and tests: Checks run on a server, not on the agent's word
  • Guard and tests pass?: Contract untouched and every test green
  • Human reviews: Contract changes first, then risky code
  • Merged to main: Spec, tests and code stay together

If you want to know what happens inside the agent box, our guide on coding agent architecture explains the harness loop, tools and sandbox. This guide stays on the human side of the loop.

What does a spec for an AI coding agent look like?

A good spec is short, numbered and testable. Every rule says something a test can check, and it says what the code is not supposed to do.

Here is the spec for the bill splitter. It is plain text in a file called SPEC.md, kept in the repository.

text
SPEC: split_bill
Purpose: split one restaurant bill evenly among friends, in whole paise.
Inputs: total_paise, a whole number (100 paise make 1 rupee); people, a whole number.
Output: a list of whole-number shares in paise, one per person.

R1. The function MUST return exactly one share per person.
R2. The shares MUST add up to total_paise exactly. No paisa may be lost or created.
R3. Any two shares MUST differ by at most 1 paisa.
R4. Larger shares MUST come first in the list.
R5. The function MUST raise ValueError when people is less than 1 or total_paise is negative.

Out of scope: rupee formatting, GST, tips, uneven splits.
Done when: every test in tests/test_split_bill.py passes, and the agent has not
changed this file or anything in tests/.

Three choices in this spec matter more than they look. First, money is in whole paise, not rupees with decimals, because a value like 0.1 cannot be stored exactly as a binary floating-point number. In Python, 0.1 + 0.2 prints 0.30000000000000004, while whole paise stay exact.

Second, R2 and R3 answer the question the one-line request skipped. The paise must add up, and the leftover paise are shared out one each. R4 then makes the answer predictable, so a test can know exactly which list to expect.

Third, the out-of-scope line stops the agent from being helpful in the wrong direction. Without it, an agent might add GST or rounding to the nearest rupee, and you would have new behaviour nobody asked for.

How do you turn a spec into tests an agent cannot argue with?

Write two kinds of tests: hand-picked examples for the cases you care about, and property tests for the rules that must hold everywhere. Label each with its rule number.

The file below uses pytest, a popular Python test runner, and Hypothesis, a Python library for property-based testing. We ran everything on Python 3.13.18, pytest 9.2.0 and Hypothesis 6.170.14 as of 31 October 2026.

python
import pytest
from hypothesis import given, strategies as st

from split_bill import split_bill


# R1 to R4 on hand-picked examples
@pytest.mark.parametrize("total, people, expected", [
    (30000, 3, [10000, 10000, 10000]),
    (10000, 3, [3334, 3333, 3333]),
    (5, 2, [3, 2]),
    (0, 4, [0, 0, 0, 0]),
])
def test_examples(total, people, expected):
    assert split_bill(total, people) == expected


# R5: bad input is rejected
@pytest.mark.parametrize("total, people", [(100, 0), (-1, 2)])
def test_rejects_bad_input(total, people):
    with pytest.raises(ValueError):
        split_bill(total, people)


# R1 to R4 on many generated inputs (100 by default)
@given(st.integers(min_value=0, max_value=10**9),
       st.integers(min_value=1, max_value=500))
def test_rules_hold_for_any_bill(total, people):
    shares = split_bill(total, people)
    assert len(shares) == people                       # R1
    assert sum(shares) == total                        # R2
    assert max(shares) - min(shares) in (0, 1)         # R3
    assert shares == sorted(shares, reverse=True)      # R4

The parametrize line runs one test several times, once per row of inputs. The given line asks Hypothesis to generate the inputs itself. By default it tries 100 inputs per test, including edge cases you might not think of.

Look at the last test. It never states one answer. It states the rules R1 to R4 and lets Hypothesis hunt for any bill that breaks them. That is the difference between an example and a property.

To try it, install the pinned tools with pip install pytest==9.2.0 hypothesis==6.170.14. Put the code in good/split_bill.py, then run PYTHONPATH=good pytest -q test_split_bill.py. With correct code you should see 7 passed. This small demo keeps the test file at the top level; in a real repository it lives in tests/, as the spec says.

Why do example tests alone let wrong code pass?

Because an agent that writes both the code and the tests only checks the cases it already thought of. Its blind spots appear in both files at once.

Here is the code an agent might plausibly write from the one-line request. We wrote it to look like a typical first try. It is shown as the naive version on purpose.

python
def split_bill(total_paise, people):
    share = round(total_paise / people)
    return [share] * people

The tests it came with checked 30,000 paise among 3 people and 1,00,000 paise (1,000 rupees) among 4 people. Both divide evenly, so both pass. We ran them: 2 passed.

We then ran the spec's test file against the same naive code. Five tests failed and two passed. Here are the useful lines of the output, trimmed to fit.

text
FAILED test_split_bill.py::test_examples[10000-3-expected1]
FAILED test_split_bill.py::test_examples[5-2-expected2]
FAILED test_split_bill.py::test_rejects_bad_input[100-0] - ZeroDivisionError
FAILED test_split_bill.py::test_rejects_bad_input[-1-2] - Failed: DID NOT RAISE ValueError
FAILED test_split_bill.py::test_rules_hold_for_any_bill - assert 0 == 1
    Failing test case: test_rules_hold_for_any_bill(total=1, people=2)
5 failed, 2 passed

What just happened? The naive code breaks R2 and R5. A 100 rupee bill among three loses a paisa. Zero people crashes with the wrong error, and a negative bill is accepted silently.

The property test found the smallest possible failure: 1 paisa split between 2 people. Hypothesis shrinks a failing input to a simpler one before reporting it. In 10 fresh runs, each with its saved examples deleted first, it reported exactly that case every time.

Why does 1 paisa become 0? Python's round sends a value exactly halfway between two whole numbers to the even one, so round(0.5) is 0 and round(2.5) is 2. That is why 5 paise between 2 people also gave 2 and 2.

Research points the same way. A 2024 paper found that giving a model the tests along with the problem statement raised how many coding problems it solved. A 2023 paper gave a popular coding benchmark about 80 times as many tests.

With those stronger tests, the share of problems counted as solved fell by up to 19.3 to 28.9 percent, depending on the scoring setting. Weak tests had been counting wrong code as correct.

How do you check that your tests are strong enough?

Break the correct code on purpose and see whether the tests notice. This is called mutation testing, and each broken copy is called a mutant.

Here is the correct implementation. divmod returns the whole-number quotient and the remainder together, so the leftover paise are handed out one each.

python
from operator import lt  # lt(a, b) means "a is less than b"


def split_bill(total_paise, people):
    if lt(people, 1) or lt(total_paise, 0):
        raise ValueError("people must be at least 1 and total_paise at least 0")
    base, extra = divmod(total_paise, people)
    return [base + 1] * extra + [base] * (people - extra)

The script below makes four small, believable mistakes in that file, one at a time. It runs both test files against each mutant and counts how many mutants each file catches.

python
import os
import pathlib
import shutil
import subprocess
import sys
import tempfile

GOOD = pathlib.Path("good/split_bill.py").read_text()

# Each mutant is one small, plausible mistake: (old text, new text)
MUTANTS = {
    "extra paise dropped": ("[base + 1] * extra", "[base] * extra"),
    "small shares first": ("[base + 1] * extra + [base] * (people - extra)",
                           "[base] * (people - extra) + [base + 1] * extra"),
    "negative total allowed": (" or lt(total_paise, 0)", ""),
    "zero people allowed": ("lt(people, 1)", "lt(people, 0)"),
}

for suite in ["test_weak.py", "test_split_bill.py"]:
    caught = 0
    for name, (old, new) in MUTANTS.items():
        assert old in GOOD, name
        shutil.rmtree(".hypothesis", ignore_errors=True)
        with tempfile.TemporaryDirectory() as tmp:
            pathlib.Path(tmp, "split_bill.py").write_text(GOOD.replace(old, new, 1))
            run = subprocess.run(
                [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider", suite],
                env={**os.environ, "PYTHONPATH": tmp}, capture_output=True)
            caught += run.returncode != 0
    print(f"{suite}: caught {caught} of {len(MUTANTS)} mutants")

Run it with python mutate.py from the folder holding both test files and the good folder. Keep no split_bill.py beside the tests. When we left a copy there, pytest imported it instead of the mutant, and both suites caught 0 of 4. This is what we got with the right layout.

text
test_weak.py: caught 0 of 4 mutants
test_split_bill.py: caught 4 of 4 mutants
Which spec rule catches each planted mistake (run on pytest 9.2.0 and Hypothesis 6.170.14)
MutantWhat the bug doesCaught by the agent's two tests?Caught by the spec's tests?
Extra paise dropped10,000 among 3 gives 3,333 each, losing 1 paisaNoYes, R2
Small shares firstPuts the extra paisa at the end of the listNoYes, R4
Negative total allowedAccepts a bill of minus 1 paisaNoYes, R5
Zero people allowedCrashes with ZeroDivisionError, not ValueErrorNoYes, R5

The weak tests passed every broken version, so they would have approved any of them. That is the real risk of reviewing only the tests: a green tick from a weak suite proves very little.

Four hand-made mutants are a teaching tool, not a full audit. Dedicated mutation testing tools generate mutants automatically across a whole codebase. The habit matters more than the tool: before you trust a suite, watch it fail on purpose.

How do you stop the agent from changing the tests?

Treat the spec and tests as human-owned files, and make the build fail if the agent's branch touches them. Then run the tests on a server, not inside the agent's session.

This is not a made-up worry. A 2025 benchmark built impossible tasks, where the written spec and the unit tests contradicted each other. Any pass therefore meant a shortcut.

The authors report shortcuts ranging from simply editing the tests to more complex tricks such as overloading operators. Overloading means redefining what a symbol like == does, so a wrong answer compares as equal.

Hard-coding is another shortcut. We wrote a version of split_bill that simply returns the four expected answers from the example table. It passed all six example-based tests, and the property test still caught it at 1 paisa between 2 people.

This small script is the guard. It lists files changed on the agent's branch since it left main, and fails if any are protected.

bash
#!/usr/bin/env bash
# Fail the build if the agent's branch touched human-owned files.
protected=$(git diff --name-only main...HEAD -- SPEC.md tests/)
if [ -n "$protected" ]; then
  echo "Agent branch changed protected files:"
  echo "$protected"
  exit 1
fi
echo "Spec and tests untouched"

We tested it in a fresh git repository on git 2.43.0. A branch that only added split_bill.py printed "Spec and tests untouched" and exited with 0. A branch that also changed one expected answer in the tests printed the file name and exited with 1.

Who owns which files

Follow the arrows into CI: it trusts nothing the agent says about itself. The guard and the tests both have to pass before a human looks.

Diagram connections:

  • Human author to SPEC.md (Writes)
  • Human author to tests folder (Writes)
  • SPEC.md to AI coding agent (Read; edits fail the build)
  • tests folder to AI coding agent (Read; edits fail the build)
  • AI coding agent to split_bill.py (Edits)
  • split_bill.py to Guard script (Branch diff checked)
  • Guard script to CI test run (Only if untouched)
  • Human author: Owns the contract
  • SPEC.md: Rules R1 to R5, protected
  • tests folder: One or more tests per rule, protected
  • AI coding agent: Reads the contract, writes code only
  • split_bill.py: The only file the agent should change
  • Guard script: Fails if protected files changed
  • CI test run: Runs pytest on a clean machine

Sometimes the spec really is wrong, and the tests must change. That is fine, but the change comes from a human in its own commit, reviewed like any rule change. The agent can suggest it; it cannot make it.

What should you still review line by line?

Review every change to the contract, plus any code that touches what the tests cannot see. Tests check behaviour the spec describes; they say nothing about things the spec never mentions.

Where to spend review time in spec driven development
AreaCan the contract cover it?What to do
Rules the spec statesYes, if the tests are strongCheck the tests map to rules, then skim the code
Changes to SPEC.md or testsNo, this is the contract itselfRead every line, as you would a rule change
Secrets, logins, permissionsRarelyRead the code line by line
Database queries and migrationsPartlyRead the code and check what data it touches
New libraries the agent addedNoCheck the package name, its owner and its licence
Speed and memory on real dataOnly with separate testsMeasure with a benchmark or load test

So "review the contract instead of every line" is a shift of attention, not permission to stop reading code. For a pure function like split_bill, strong tests carry most of the weight. For code that handles passwords or payments, they carry far less.

The October 2025 article raised fair doubts too. Its author saw one spec tool turn a small bug into four user stories with 16 acceptance criteria. Another produced long files that were tedious to review, and its agent ignored notes it had been given.

Our takeaway is to keep specs short and close to tests. A rule that has a test cannot be quietly ignored, because the build fails. A rule without a test is only a hope.

When is spec driven development worth it in 2026?

It pays off when the rules are clear, the code is easy to test and mistakes are costly. It is overkill for one-off scripts and for exploring an idea you do not yet understand.

  • Good fit: money and billing logic, data parsing and validation, API request and response rules, and any function with tricky edge cases.
  • Good fit: large changes split into small tasks, where each task gets its own short spec and test file.
  • Poor fit: user interface look and feel, where a test cannot easily say what "looks right" means.
  • Poor fit: early prototypes, where the rules change every hour and writing them down first slows learning.

A simple test of fit: if you cannot write the first three MUST rules in five minutes, you do not understand the problem well enough yet. Explore first, then write the spec once the rules settle.

How do you explain spec driven development in a system design interview?

Frame it as a control loop with a human-owned contract, an agent-owned implementation and a server that enforces the boundary.

  1. Define the contract

    Say the human writes a short spec of numbered MUST rules and a test for each rule before any code exists.

  2. Place the agent inside the loop

    The agent edits code and reruns the tests until they pass, and any change it makes to the contract fails the build.

  3. Enforce the boundary in CI

    A guard fails the build if the spec or tests change, and tests run on a clean server, not in the agent's session.

  4. Prove the tests are strong

    Mention property-based tests for invariants and mutation testing, which plants bugs to see if the tests notice.

  5. Say what tests cannot cover

    Security, data access, new dependencies and speed still need human review or separate checks.

  6. Close with the trade-off

    Writing the contract takes time up front, so you use this where rules are clear and errors are costly.

Use the bill splitter as your example. One line does it: the agent's own tests passed, the spec's tests caught a lost paisa, and the guard stopped the agent from editing the answer key.

Questions people ask

Is spec driven development the same as test-driven development?

No, but it is a close relative. Test-driven development means a human writes a failing test, then just enough code to pass it, then tidies up. Spec driven development keeps the tests-first habit and adds a written spec. It also hands the code-writing step to an AI agent while the human owns the rules and the tests.

Do I still need to read the code an AI agent writes?

Yes, but you can spend your time differently. When strong tests cover the spec, you can skim code for pure logic and read the tests closely instead. Code that handles secrets, permissions, database changes or new libraries still needs a line-by-line read, because no spec test checks those things.

Can the AI agent write the tests too?

It can draft them, but a human must review and own them before the code is written. If the same agent writes code and tests together, its blind spots appear in both. In our run, two example tests of the kind an agent might write passed code that lost a paisa on a 100 rupee bill.

What should a spec file contain?

A spec file should contain a one-line purpose, the inputs and outputs, numbered rules using MUST or SHOULD, an out-of-scope list and a definition of done. Keep it to about one screen per feature. Every rule should be something a test can check, otherwise it is only a wish.

What is property-based testing in simple words?

Property-based testing checks a rule on many generated inputs instead of a few hand-picked ones. You write a rule such as "the shares always add up to the total", and a library like Hypothesis tries 100 inputs by default. When one fails, it shrinks it to the simplest failing case it can find.

How do I stop an AI agent from editing my tests?

Make the spec and test files human-owned and add a CI check that fails when an agent's branch changes them. Our guard script uses git diff to list protected files changed since main, and exits with 1 if it finds any. Also run the tests on a server, never trusting the agent's own report.

Is spec driven development worth it for small tasks?

Usually not for one-off scripts or early prototypes, where the rules change too fast to write down. It earns its cost for logic with clear rules and costly mistakes, such as billing, parsing and API validation. A quick check: if you can write three MUST rules in five minutes, a short spec will help.