Spec-Driven Development: How to Write Executable Specifications for AI Coding Agents

A SPEC.md checklist beside an Undo example that reopens the task Book room 204 and keeps its title.
TL;DR

Write a feature spec an AI coding agent can work from. Use the copyable template and follow a task-list Undo feature through failing and passing acceptance tests.

“Add Undo when someone completes a task” sounds like a small ticket. Complete two tasks, though, and the ticket already needs a decision. Does Undo reopen the last task, or does it walk backward through every completion? And if you rename a task before undoing its completion, which title should survive?

Spec-driven development means writing down the behavior you want, reviewing it, and checking the finished code against it. For an AI coding agent, a versioned SPEC.md gives the task a definition of done that survives the chat. The file describes what should happen. Automated tests make the covered behaviors executable, and manual checks can cover things the test suite cannot observe.

Copy the SPEC.md template · Get the runnable example files

Vibe coding vs. spec-driven development

A chat-first sketch is useful when you are still deciding where Undo should appear. Ask for two variations, try them, and see which one makes sense. Once other people will rely on the behavior, put the decision somewhere a reviewer can find it.

QuestionChat-first prototypeSpec-driven change
What does “Undo” mean?The developer and agent work it out while trying the feature.The spec records which action can be reversed and when that option expires.
How do you check it tomorrow?Open the prototype or reconstruct the decisions from the conversation.Run the acceptance tests and review the scenarios in the spec.
When is it useful?You are still exploring the interaction.You need predictable behavior through implementation and later changes.

Scale the spec to the decision. Changing a label can fit in an issue with one example. Adding Undo needs a few more lines because the correct result depends on the order of events.

If a prototype already exists, use it to collect questions. Try completing the same task twice. Try Undo after removing a task. Write down the expected outcomes before you ask the agent to build the production version. You can keep the prototype if it fits those decisions, or throw it away if it makes the wrong behavior hard to change. Either way, the useful output from that session is the set of decisions you can review.

What goes in AGENTS.md and SPEC.md?

AGENTS.md explains how to work in the repository. It can tell an agent where tests live, how to run them, and which conventions apply across changes. SPEC.md explains what this feature should do. It can say that Undo reopens the latest completed task and keeps the current title. The implementation plan can name the files you need to change. Pristren’s AGENTS.md guide

For a repository with several active features, give each a path such as specs/task-undo/SPEC.md. Name the path in the handoff so the agent starts with the right spec. Keep the acceptance IDs stable when you refine the wording so reviewers can follow the same behavior from spec to test.

The split is easiest to see in review. “Run tests with the existing Node runner” belongs in the repository instructions because it applies to every feature. “Keep the current title when reopening a task” belongs in the feature spec because it describes a particular result. “Read the current record by ID before changing completed” can live in the implementation plan. A reviewer can reject that implementation approach while keeping the agreed behavior intact.

A copyable SPEC.md template

Fill in the sections that affect the feature. A good acceptance row names a starting state, an action, and an outcome you can observe. Give each row a test or a manual check.

markdown
# [Feature name]

Status: Draft or approved  
Owner: [Who decides unresolved behavior?]  
Context: [Issue, useful paths, or related feature spec]

## Goal and scope

- User and job: [Who needs to do what?]
- Observable outcome: [What can the user now see or do?]
- In scope: [The smallest change that delivers the outcome.]
- Out of scope: [A plausible adjacent change we are deferring.]

## Data model

| Field or state | Type and allowed values | Default, owner, and lifetime |
| --- | --- | --- |
| [New or affected field] | [Type and valid range] | [Initial value, writer, where it lives, when it resets] |

Describe what happens to existing records if a field is absent. If storage is unaffected, say which data stays the same.

## Invariants

- [Write a rule that must hold before and after every supported operation.]
- [Name something this feature must preserve, such as an existing edit, permission, or record ordering.]

## Edge cases and open decisions

| Starting condition or event | Expected behavior | Decision owner if unresolved |
| --- | --- | --- |
| [Missing data, duplicate action, or empty state] | [Visible result and any state change] | [Name or role] |

Write open questions explicitly. Resolve questions that change the acceptance criteria before implementing those criteria.

## Acceptance tests

| ID | Given | When | Then | Verification |
| --- | --- | --- | --- | --- |
| A1 | [Fixture or starting state] | [One action] | [Exact visible outcome or state] | [Test name, file and command, or manual steps] |
| A2 | [Boundary case] | [One action] | [Expected outcome and existing behavior to preserve] | [Test name, file and command, or manual steps] |

## Verification and changes

- Repository instructions and test runner: [Paths or commands.]
- Evidence for review: [Record pass, fail, or not run for each ID and give the reason for any gap.]
- When expected behavior changes, update the affected criterion and its check in the same review.

Spec-driven development example: undo a task completion

The example starts with two open tasks, “Book the room” and “Send the agenda.” The session keeps one pending undo at a time. Each successful completion replaces the previous undo target. Undo changes the completion status of the current task and clears that target. Keeping only the task ID makes it possible to reopen the latest version of the task, including any edits made since completion.

Before writing a test, choose what the feature owns. In this example, a task already has an id, a title, and a completed flag. The new undoTaskId sits beside the task list in session state and starts at null. If an existing app loads older task records, initialize the session field as part of loading the list. There is no change to the stored task shape. A future request to support Undo after reload would change the lifetime of that field and deserves its own scenario.

Two rules are easy to overlook. First, only a successful completion can replace the target. Completing an already completed task or passing an unknown ID should leave the previous Undo available. Second, if the target task disappears, Undo clears the pending target and leaves the surviving tasks alone. Both rules describe what a caller can observe, so both can be tested directly.

These are the six acceptance checks from the example spec. Each row appears under the same ID in the test file.

6 rows · Click column to sort
A1Complete an open task with nothing pending.The task is complete and becomes the Undo target. The input state still shows it as open.
A2Complete A, then B. Invoke Undo twice.The first Undo reopens B and clears the target. A stays complete and the second Undo leaves the list alone.
A3Complete A and rename it to Book room 204. Invoke Undo.A reopens with its edited title. The list order and B’s values are preserved.
A4B is pending. Try completing A again or completing an unknown task.Both attempts leave B pending and preserve the tasks.
A5Remove the task that was pending, then invoke Undo.Clear the target and preserve the remaining tasks.
A6Invoke Undo with nothing pending.Leave the state as it was.

For your own first spec, find one scenario that would catch a plausible wrong implementation. If your feature is an import, try importing the same file twice and say what should happen to existing rows. If it is a notification preference, change one setting and check that the other settings survive. A useful acceptance test tells you where the feature can go wrong even when the happy path works.

Consider A3 from the completed spec. Given that task A was completed and then renamed to Book room 204, when the user invokes Undo, the task should reopen under its new title. A test that only checks completed === false would miss an implementation that restored an old snapshot and silently reverted the title.

Here is the assertion from A3. The edited fixture has just had its first task renamed.

js
assert.deepEqual(undoCompletion(edited).tasks, [
  { id: 'a', title: 'Book room 204', completed: false },
  edited.tasks[1],
]);

Copy the three runnable files below into one folder and open a terminal there. Use Node.js 22 or later. The demo uses the built-in Node.js test runner and needs no package installation. Run both commands separately because the first intentionally exits with code 1. Node.js test runner documentation

bash
node verify.mjs --baseline
node verify.mjs
Run on Node.js 24.20.0PassedFailedExit
Baseline completion behavior151
Implementation with Undo600

The baseline left both tasks complete after Undo in A2. The expected result was that the first task stayed complete and the second reopened. The finished version also passed checks for a duplicate completion, a removed target, and an Undo with nothing pending. The suite exercises state directly. If you wire it to a browser button, add a browser check for the control, keyboard focus, and feedback.

Review the failure before fixing it

In the baseline run, A2 expects [true, false] for the two completion flags and receives [true, true]. That is a useful failure: the test reached the same operation users will depend on and showed which task stayed closed. If the runner had stopped on an import error, it would have told you nothing about Undo. Inspect the assertion before counting a failing baseline as evidence.

Keep that assertion in the passing run. If an agent changes the expected result while adding Undo, compare the new assertion with A2 before accepting the patch. The same expected value should apply to both implementations. Pristren’s guide to preserving the failing test

Ask the same question when all the tests pass. If someone rewrote Undo to restore the old task object, would a test fail? A3 would, because it checks the current title along with the completion flag and the other task. This is how to catch a common gap in acceptance tests: the check proves the new behavior but forgets the old behavior you needed to preserve.

Spec-driven development with Claude Code

Start Claude Code in the repository and name the actual feature spec in your request. Claude Code can load AGENTS.md or CLAUDE.md as project instructions depending on the version and setup. For the feature spec itself, provide the path explicitly. Claude Code project instruction docs

To try the handoff with this example, save the template as SPEC.md beside the three runnable files. Fill it in with the state rules and acceptance criteria above. For your own feature, substitute the path in your repository.

text
Read the applicable repository instructions and SPEC.md.
Before editing, identify the existing completion path and show how you
would verify A1 - A6. Flag any behavior the spec leaves undecided and wait
for my reply before implementing an affected criterion.

After reviewing the plan, ask the agent to implement the agreed behavior and report the command it ran, its result, and any check it skipped. If review changes the intended behavior, update the acceptance row and its test in the same change. For example, if Undo should eventually survive a reload, decide how the target persists and add a check that actually reloads the page.

How to review the change against the spec

Start with the acceptance IDs in the pull request. A useful entry can be one line: A3 - node verify.mjs - pass - reopened task A still reads Book room 204. Ask for the same level of evidence for a manual check. For a browser implementation, that could mean starting with two open tasks, completing both with the keyboard, invoking Undo, and recording the resulting task state and focus location.

Read the diff for changes that the spec would never ask for. A new dependency, a storage migration, or a general history stack deserves an explanation in the implementation plan. Then check for decisions that only exist in the patch. If the implementation introduces a five-second expiry because an agent assumed Undo would disappear, either remove the timer or review the new behavior and revise the spec and tests to match the approved decision.

Keep the spec beside the code after merging. If the next request is “let Undo work after refresh,” the existing spec tells you which behavior changes and which rules still apply. You can add a new acceptance example for refresh without rewriting the cases for duplicate completion or title edits. That makes the document useful the second time someone touches the feature.

When is a spec-driven development framework useful?

Start with one reviewed file when one feature and a handful of checks fit on a page. A framework starts to help when the team repeatedly needs to carry requirements through review, design, and tasks.

Choose a framework by looking at where reviews stall. If reviewers often approve the prose but never see how it turns into implementation tasks, a framework can give those handoffs a repeatable shape. If the trouble is one vague acceptance criterion, fix that criterion first. A larger set of files still depends on someone deciding what the user should see.

OptionWhat it gives you
GitHub Spec KitA defined process for carrying a specification through planning, implementation, and verification.
OpenSpecProposals, tasks, and spec changes for tracking how an existing project evolves.
Kiro SpecsBuilt-in support for requirements, design, and implementation tasks, with dedicated spec types for features and bug fixes.

GitHub Spec Kit documentation · OpenSpec repository · Kiro Specs documentation

For your next feature, start with one acceptance example that a teammate could reproduce. Then give the agent the spec path and ask which test will prove that behavior. Copy the SPEC.md template

Runnable example files

Save these three blocks in the same folder using the shown names. The baseline and finished implementation share the acceptance checks in verify.mjs.

baseline.mjs

js
export function completeTask(state, taskId) {
  return {
    ...state,
    tasks: state.tasks.map((task) =>
      task.id === taskId ? { ...task, completed: true } : task,
    ),
  };
}

export function undoCompletion(state) {
  return state;
}

task-state.mjs

js
export function completeTask(state, taskId) {
  const task = state.tasks.find((entry) => entry.id === taskId);
  if (!task || task.completed) return state;

  return {
    tasks: state.tasks.map((entry) =>
      entry.id === taskId ? { ...entry, completed: true } : entry,
    ),
    undoTaskId: taskId,
  };
}

export function undoCompletion(state) {
  if (state.undoTaskId === null) return state;

  return {
    tasks: state.tasks.map((task) =>
      task.id === state.undoTaskId ? { ...task, completed: false } : task,
    ),
    undoTaskId: null,
  };
}

verify.mjs

js
import assert from 'node:assert/strict';
import test from 'node:test';

const { completeTask, undoCompletion } = process.argv.includes('--baseline')
  ? await import('./baseline.mjs')
  : await import('./task-state.mjs');

function taskList() {
  return {
    tasks: [
      { id: 'a', title: 'Book the room', completed: false },
      { id: 'b', title: 'Send the agenda', completed: false },
    ],
    undoTaskId: null,
  };
}

test('A1: completing an open task makes it eligible for undo', () => {
  const before = taskList();
  const after = completeTask(before, 'a');

  assert.equal(after.tasks[0].completed, true);
  assert.equal(before.tasks[0].completed, false);
  assert.equal(after.undoTaskId, 'a');
});

test('A2: two completions, followed by two Undo actions', () => {
  const completed = completeTask(completeTask(taskList(), 'a'), 'b');
  const undone = undoCompletion(completed);

  assert.deepEqual(undone.tasks.map(({ completed }) => completed), [true, false]);
  assert.deepEqual(completed.tasks.map(({ completed }) => completed), [true, true]);
  assert.equal(completed.undoTaskId, 'b');
  assert.equal(undone.undoTaskId, null);
  assert.deepEqual(undoCompletion(undone), undone);
});

test('A3: Undo preserves a title edit made after completion', () => {
  const completed = completeTask(taskList(), 'a');
  const edited = {
    ...completed,
    tasks: [{ ...completed.tasks[0], title: 'Book room 204' }, completed.tasks[1]],
  };

  assert.deepEqual(undoCompletion(edited).tasks, [
    { id: 'a', title: 'Book room 204', completed: false },
    edited.tasks[1],
  ]);
});

test('A4: duplicate completion and unknown IDs leave the pending undo intact', () => {
  const completed = completeTask(completeTask(taskList(), 'a'), 'b');

  assert.deepEqual(completeTask(completed, 'a'), completed);
  assert.deepEqual(completeTask(completed, 'missing'), completed);
  assert.equal(completed.undoTaskId, 'b');
});

test('A5: Undo clears a pending ID after its task is removed', () => {
  const removed = { tasks: taskList().tasks.slice(1), undoTaskId: 'a' };

  assert.deepEqual(undoCompletion(removed), {
    tasks: removed.tasks,
    undoTaskId: null,
  });
});

test('A6: Undo on a fresh list leaves the list as it was', () => {
  const before = taskList();

  assert.deepEqual(undoCompletion(before), before);
});

Frequently Asked Questions

Can I use SPEC.md without a framework?

Yes. Save it in the repository, give the agent its path, and map the acceptance criteria to checks you can rerun. Use your project’s existing test runner when it supports the behavior you need to verify.

Does a SPEC.md file run on its own?

Plain Markdown is documentation. To make a behavior executable, express its acceptance example in a test or another verification tool. In this walkthrough A3 is written in SPEC.md and executed by verify.mjs.

What if the agent finds an edge case the spec forgot?

Ask who owns the behavior and record the decision in the spec. Then add a check for it. For example, if a completed task disappears before Undo, deciding whether to clear the pending ID belongs in the spec and the test that covers it.

Should every acceptance criterion become an automated test?

Automate stable behaviors that a test can observe and a future change could break. Give manual checks explicit steps and expected outcomes. In this example the state tests can prove which task reopened. A browser check is needed to evaluate what happens to keyboard focus when the Undo control disappears.

#spec-driven-development#ai-coding-agents#acceptance-testing#claude-code

One AI engineering post, weekly

LLM benchmarks, prompt techniques, and token-cost breakdowns, delivered to your inbox.

What should we test or explain next?

Comments

Have a question or something to add? Sign in to join the discussion.

Mahmudul Haque Qudrati — CEO & Founder · Lead AI/ML Engineer at Pristren

Mahmudul Haque Qudrati

CEO & Founder · Lead AI/ML Engineer

Software architect, full-stack engineer, and machine learning practitioner. Founder & CEO of Pristren, CTO at Venture Kick-backed PIN Sport Application GmbH (Basel, Switzerland), Software Development Lead at DailyFrame GmbH (building Dimetra patient transport software), and creator of Zlyqor. Focused on custom workflow automation, scalable web and mobile applications, and production AI/ML systems.