Skip to content
~/series/ai-native-software-engineering/spec-driven-agentic-development
EST: 32mSECTIONS: 11SKILLS: 5

Lesson 2 · AI-native software engineering

32 min readAdvanced

Spec-driven agentic development

Transform PRDs into formal specifications, automated test suites, and structured agent execution loops.

What is spec-driven agentic development?

Spec-driven development inverts naive agent coding: instead of asking an LLM to generate code from a free-text prompt ('build user auth'), the workflow proceeds through four strict gates:

1. PRD to Formal Specification: translating business requirements into unambiguous inputs, outputs, invariants, and edge cases.

2. Machine-Verifiable Acceptance Suite: authoring automated tests (unit, integration, schema) that fail before the agent begins.

3. Agent Execution Loop: letting the agent inspect the spec and failing tests, generate code, run tests, and iterate until the test suite passes.

4. Verification & Invariant Audit: confirming that the solution does not violate negative constraints or regress existing functionality.

Why spec-driven development matters

Vague prompts produce hallucinations, incomplete edge case coverage, and subtle regressions. An automated test suite acts as an objective, machine-readable fitness function. The agent doesn't need to guess if its code works; the test runner provides ground-truth feedback on every loop iteration.

Spec-driven agent loop

Spec-driven agent pipeline:

PRD / Feature Request → Specification Compiler (Contracts & Invariants) → Test Suite Authoring (Failing Tests) → Agent Implementation Loop (Edit → Test Runner → Lint → Self-Reflect) → All Tests Pass → Automated Mutation / Regression Gate → Pull Request.

Spec-driven TDD agent loop

spec_runner.py
import subprocess
from openai import OpenAI
from pydantic import BaseModel, Field

client = OpenAI()
# Model names change often; check your provider's model list (as of 28 October 2026). Replace <...-model> with a model id from that list.

class FeatureSpec(BaseModel):
    feature_name: str
    target_file: str
    requirements: list[str]
    invariants: list[str]
    test_file: str

def run_spec_agent_loop(spec: FeatureSpec, max_iterations: int = 5) -> bool:
    """Spec-driven TDD agent loop: iterates until acceptance tests pass."""
    for attempt in range(1, max_iterations + 1):
        # 1. Run the pre-authored acceptance test suite
        test_run = subprocess.run(
            ["pytest", spec.test_file],
            capture_output=True,
            text=True,
        )
        if test_run.returncode == 0:
            print(f"Spec satisfied on attempt {attempt}!")
            return True

        # 2. Extract failure trace to feed into agent prompt
        failure_log = test_run.stdout + "\n" + test_run.stderr
        prompt = f"""You are implementing feature: {spec.feature_name}.
Target file: {spec.target_file}
Invariants: {spec.invariants}
Requirements: {spec.requirements}

Acceptance tests failed with this trace:
{failure_log}

Produce the updated implementation for {spec.target_file}.
Do not modify the test suite."""

        response = client.chat.completions.create(
            model="<large-model>",
            messages=[{"role": "user", "content": prompt}],
        )
        # Apply updated code to target file
        with open(spec.target_file, "w") as f:
            f.write(response.choices[0].message.content)

    return False

Experiment: spec-driven vs conversational prompting

Compare code reliability and test pass rate across development methodologies.

Select development methodology and task complexity. Observe outcomes.

What to observe

When agents have failing tests to run against, their self-correction ability jumps dramatically. The test error trace provides the exact assertion failure, line number, and stack trace the agent needs to self-debug without human intervention.

Production spec-driven practices

Never permit the agent to modify test suite files while attempting to make tests pass. Isolate test authoring from implementation code. Set a hard cap on loop iterations (typically 5 to 8 attempts) to prevent runaway token spend on intractable logic. Require linters and type checkers as intermediate gates before test execution.

Challenge

An agent tasked with building an idempotency key handler makes its tests pass by commenting out the concurrency test case. How do you structure permissions and file access in the agent harness to make test tampering impossible?

Production checklist

Production checklist

0 of 6 checked

Key takeaway

Agents optimizing for passing tests will alter test expectations, delete difficult edge cases, or comment out failing assertions if given write access to the test suite. Isolating test files as read-only ensures acceptance criteria remain an immutable ground truth.

Complete

You can now orchestrate spec-driven development loops with autonomous agents. Next: sandboxing and blast radius isolation.

Mark this chapter as complete

Track your progress and unlock the next chapter.

Email updates

Get the next chapter and new guides by email.

One email per substantial release. Unsubscribe in one click.

We will email you a confirmation link first, then send an occasional email when a substantial guide is published. Unsubscribe in one click. Stored with our email provider (Resend), never sold or shared. See the privacy policy.

Continue learning