---
title: "Spec-Driven Development with Domain Models"
description: "DDD as code + SDD: domain models in ZFL, ZDL, OpenAPI and AsyncAPI as the spec, a deterministic generator for the boring parts, and natural-language rules for the last mile that agents complete."
url: https://www.zenwave360.io/docs/spec-driven-development/
---

# Spec-Driven Development with Domain Models

Model your domain. Generate the boring parts. Use your domain models as SDD specs.

This page is the technical reference for how ZenWave does spec-driven development, which we call **DDD as code + SDD**. The reasoning behind it is in the articles linked from each section.

Agents can work away from the keyboard only on what a human approved, and a human can approve only what they can read. LLMs write Markdown faster than anyone can read it. A spec written in prose ends up approved without being read, and agents treat it as decided ([Markdown is the bottleneck](https://ivangsa.com/articles/sdd-markdown-is-the-bottleneck/)).

So ZenWave puts a domain model at the center of the spec. Business flows, bounded contexts and API contracts are written in structured languages that humans and agents can both read, and that a parser can validate. A human designs the system in a loop with agents (HITL). Then agents implement it in a loop of their own (AFK).

[![The two loops of model-driven development with agents: Discover, then Shape as a human-in-the-loop design loop, an approval gate, Implement & Verify as an away-from-keyboard agentic loop, and Navigate, with model-change proposals going back from the agents to the human](https://www.zenwave360.io/images/two-loops-model-driven-development.light.webp)](https://www.zenwave360.io/images/two-loops-model-driven-development.light.png)

## Principles

1. **The model is the spec.** Business flows in [ZFL](https://www.zenwave360.io/docs/event-driven-design/zenwave-flow-language.md), bounded contexts in [ZDL](https://www.zenwave360.io/docs/event-driven-design/zenwave-domain-language.md), contracts in [OpenAPI](https://www.zenwave360.io/API-First/OpenAPI.md) and [AsyncAPI](https://www.zenwave360.io/API-First/AsyncAPI.md).
2. **Prose lives inside the model.** Doc comments, `rules` and ADRs explain the model. Free-standing documents (PRDs, research notes) feed the design and never reach the implementation.
3. **Humans review projections, not prose.** Diagrams, state machines, sequence diagrams per branch, API contracts and generated code are projections of the same model, and they are faster to validate than a document.
4. **Approved means approved.** Agents treat as decided only what is in the approved, tagged baseline.
5. **Agents challenge the model but never edit it.** When implementation shows the model is wrong, agents stop and propose a change. A human decides.
6. **Agents make tests pass, but they don't decide what passing means.** Expected results come from the model and from test data a human validated.
7. **Humans review evidence, not code.** At the end of an autonomous run the human gets reports, test results and open proposals, not a diff to read line by line.
8. **One batch at a time.** Both loops run in parallel on different batches of flows.
9. **Generate what is deterministic.** A generator turns the approved model into most of the code and its tests, in seconds and with no tokens. Agents write only what is left.

More in [DDD as Code + SDD: use domain models instead of Markdown](https://ivangsa.com/articles/ddd-as-code-sdd-domain-models-instead-of-markdown/).

## The spec is the model

A spec in DDD as code has three levels. Each maps to a practice teams already use:

| Level         | What it describes                                                                                                 | Language                                                                                                               | Event Storming level |
| ------------- | ----------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | -------------------- |
| Flow model    | What the business does across services: policies (`when <event> do <command>`), outcomes, failures, compensations | [ZFL](https://www.zenwave360.io/docs/event-driven-design/zenwave-flow-language.md)                                     | Process modelling    |
| Domain model  | How one bounded context is built: aggregates, entities, commands, domain events, state transitions                | [ZDL](https://www.zenwave360.io/docs/event-driven-design/zenwave-domain-language.md)                                   | Software design      |
| API contracts | What each context exposes and publishes                                                                           | [OpenAPI](https://www.zenwave360.io/API-First/OpenAPI.md), [AsyncAPI](https://www.zenwave360.io/API-First/AsyncAPI.md) |                      |

The same command or event has the same name in the flow, the bounded context and the contract, so the three levels work as a structured ubiquitous language. Their references connect them into one graph.

What makes a model work as a spec:

- **Human-readable.** It reads as code, built on DDD building blocks. A medium-sized service fits in under 200 lines of ZDL.
- **Machine-checkable.** Plain text with a grammar and a validator. It can be versioned, diffed, parsed and linted, and cross-references between levels can be resolved.
- **Compact.** A human can read all of it and an agent can hold it in context. The whole [Arcadia Editions](https://github.com/arcadia-editions) system, one ZFL flow and six ZDLs, is 1,454 lines, roughly 14k tokens.
- **Approved at a gate.** Valid, reviewed, covered by test data, then committed and tagged. See [the gate](#the-gate).

More in [Three pillars: Domain-Driven Design as code](https://ivangsa.com/articles/three-pillars-domain-driven-design-as-code/), [From Event Storming to a model your agents can read](https://ivangsa.com/articles/sdd-from-event-storming-to-a-model-your-agents-can-read/) and [What's wrong with spec-driven development](https://ivangsa.com/articles/whats-wrong-with-spec-driven-development-and-how-to-fix-it/).

## Generate the boring parts, specify the last mile

A model that parses can be turned into code deterministically. [ZenWave SDK](https://www.zenwave360.io/docs/zenwave-sdk.md) generates the boring \~80% of a Spring Boot backend from ZDL, in Java or Kotlin: services, aggregates, repositories, REST and event adapters, DTOs and test suites.

Generating less code with AI is how you avoid AI slop. Agents copy the patterns they find in the repository. If the structure was generated from your best templates, the agents keep those patterns, and quality stays consistent as the code grows. Generation takes seconds, uses no tokens and gives the same output every time.

The generator stops at structure, because it cannot know what `reserveStock` means and so it cannot implement it. That last mile is left to people or to LLMs, and its spec is the natural-language `rules` inside the model. A `rules` block can name the aggregate it is about (in ZFL, also a view across aggregates). `@invariant` marks a rule that must hold in every state.

From the Orders bounded context of Arcadia Editions:

**orders-checkout-domain-model.zdl: rules (Order)** - `2026-12/orders-checkout-domain-model.zdl` (lines 56-65), [source](https://github.com/arcadia-editions/arcadia-editions-modulith-api/blob/website-docs/2026-12/orders-checkout-domain-model.zdl#L56-L65)

```zdl
rules (Order) {
    @invariant orderTotal "totalAmount equals the sum of quantity * unitPrice over all items, in the order's currency"
    @invariant checkoutSnapshotFixed "customerId, customerEmail, paymentMethodId, items, shippingAddress, totalAmount and currency are fixed at checkout and never change"
    @invariant orderOnlyWithReservedStock "An Order exists only if its stock was reserved: StockUnavailable persists nothing"
    @invariant cancelledIsFinal "CANCELLED is terminal: no command takes an Order out of it"
    @invariant cancelledNeverConfirmed "A CANCELLED Order is never confirmed: a late authorization is answered with OrderConfirmationRejected"
    @invariant confirmationData "confirmedAt is set exactly when the Order reaches CONFIRMED and is never cleared"
    @invariant cancellationData "cancelledAt and cancellationReason are set if and only if the Order is CANCELLED"
    singleCancellation "An Order is cancelled at most once: a redelivered cancellation is a no-op with no event"
}
```

A ZFL flow states the rules that cross bounded contexts. These are invariants over a view that joins the Order with its stock reservations, payment and fulfillment:

**place-order-flow\.zfl: rules (PlaceOrderView)** - `2026-12/business-flows/place-order-flow.zfl` (lines 79-88), [source](https://github.com/arcadia-editions/arcadia-editions-architecture/blob/website-docs/2026-12/business-flows/place-order-flow.zfl#L79-L88)

```zfl
    rules (PlaceOrderView) {
        @invariant neverChargedAndCancelled "An order is never both CANCELLED and with a CAPTURED Payment"
        @invariant confirmedHoldsStock "A CONFIRMED Order has every StockReservation line CONFIRMED"
        @invariant cancelledReleasesStock "A CANCELLED Order has every StockReservation line RELEASED and no READY_TO_SHIP Fulfillment"
        @invariant noShipWithoutCapture "A Fulfillment is READY_TO_SHIP only if the Payment is CAPTURED"
        @invariant noCaptureWithoutFulfillment "A Payment is CAPTURED only if the Order is CONFIRMED and has a Fulfillment"
        @invariant noOrderWithoutStock "When stock is unavailable there is neither an Order nor a Payment"
        @invariant amountsMatch "Payment.amount and currency equal Order.totalAmount and currency"
        @invariant contentsMatch "Fulfillment.items and shippingAddress equal those of the Order"
    }
```

Commands and policies name the rules they apply with `@rules(...)`. Syntax: [ZDL business rules](https://www.zenwave360.io/docs/event-driven-design/zenwave-domain-language.md#rules) and [ZFL rules](https://www.zenwave360.io/docs/event-driven-design/zenwave-flow-language.md#rules).

This is where it differs from MDA. An MDA transformer understands structure but not semantics, so the model had to be complete and every gap broke the pipeline. Here the model gives the structure and the vocabulary, and an LLM fills in the semantics. When it cannot, it sends a proposal back (see [When the model is wrong](#when-the-model-is-wrong)).

More in [DDD as Code + SDD](https://ivangsa.com/articles/ddd-as-code-sdd-domain-models-instead-of-markdown/#code-generation-is-optional).

## The cycle at a glance

| Stage                                                                      | Who leads                  | Produces                                                               | Ends when                                | ZenWave tools                                                                                                                                                                                    |
| -------------------------------------------------------------------------- | -------------------------- | ---------------------------------------------------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| [Discover](#discover)                                                      | Humans, assisted by agents | PRD, Event Storming findings, first ZFL draft                          | A flow can be written as ZFL             | Event Storming, agentic interviews                                                                                                                                                               |
| [Shape](#shape-the-human-in-the-loop-loop) (HITL)                          | Humans, assisted by agents | Approved models, ADRs, validated test data, generated code, task board | The [gate](#the-gate) passes             | ZFL, ZDL, OpenAPI, AsyncAPI, [ZenWave Platform](https://www.zenwave360.io/zenwave-platform.md), [ZenWave SDK](https://www.zenwave360.io/docs/zenwave-sdk.md), [zenwave-sdd](#zenwave-sdd) skills |
| [Implement & Verify](#implement--verify-the-away-from-keyboard-loop) (AFK) | Agents                     | Working, tested code; review reports; model-change proposals           | The [exit criteria](#exit-criteria) pass | Any agentic loop that takes the models as its spec                                                                                                                                               |
| [Navigate](#navigate)                                                      | Humans and agents          | Understanding of the whole architecture                                | Never: it runs alongside                 | [zenwave-architecture](https://github.com/ZenWave360/zenwave-architecture), ZenWave Platform                                                                                                     |

The stages form a cycle: for an existing system, Navigate is the input to Discover. The approach on one page: [When Code Is Cheap](https://ivangsa.com/agentic-engineering/).

## Discover

Discovery comes before the loops. It can start with a **PRD**, which seeds an agentic interview: the agent asks, you decide. It continues with an **Event Storming** session between technical and domain experts. The findings become a first ZFL draft of each flow.

Prose is fine here, because the PRD and research notes are only inputs to the design. Agents in the AFK loop never read them, and once the models are approved the PRD is deleted so it can't mislead the next agent.

**Ends when** a flow can be written as a first ZFL draft.

More in [From Event Storming to a model your agents can read](https://ivangsa.com/articles/sdd-from-event-storming-to-a-model-your-agents-can-read/) and [Three pillars: Domain-Driven Design as code](https://ivangsa.com/articles/three-pillars-domain-driven-design-as-code/).

## Shape: the Human-in-the-Loop loop

The human drives the design and agents assist. The loop repeats until the gate passes:

- **Model.** Write the business flow in ZFL and one ZDL per bounded context, with their `rules`. Agents can draft them from the decisions taken in Discover. API contracts are derived from the ZDL.
- **Project.** Explore what the model derives in [ZenWave Platform](https://www.zenwave360.io/zenwave-platform.md): the EventFlow diagram, sequence diagrams for every alternative branch of a ZFL flow, class diagrams and state machines per aggregate, commands, events, OpenAPI and AsyncAPI.
- **Generate.** If the stack matches, [ZenWave SDK](https://www.zenwave360.io/docs/zenwave-sdk.md) generates services, APIs, event handlers and tests. Generated code is one more projection. Early on, throw it away and generate again.
- **Probe.** Generated tests start without proper test data or complete assertions. Use them as entry points: start a debug session, or write a few lines by hand, to check that the model covers the requirements.
- **Challenge.** Agents read the whole model looking for contradictions, missing outcomes, missing correlations and decisions nobody made. Answers change the model or become ADRs.
- **Prepare the handover.** Generate test data for each use case and branch of the flow with an agent's help, and validate it. Split the work into tasks.

[![One model, many projections: a human-owned ZFL and ZDL model produces EventFlow, sequence diagrams, a class diagram, a state machine, OpenAPI, AsyncAPI, and code with tests](https://www.zenwave360.io/images/one-model-many-projections.light.webp)](https://www.zenwave360.io/images/one-model-many-projections.light.png)

More in [Two loops: Model-Driven Human in the Loop](https://ivangsa.com/articles/sdd-two-loops-model-driven-human-in-the-loop/).

### Task splitting

Splitting is a discrete step at the end of Shape, though it may take a few passes. The human splits the work, assisted by an agent that derives a task list from the approved model, and from the generated code when there is some.

Tasks are sliced vertically along the paths of the flow, happy path first, so every slice can be tested end to end. The result is a list or a graph. Each task:

- points at the model lines it implements and the test data that defines done;
- states its **difficulty**, so it can be routed to a suitable model;
- states its **blockers**, the tasks it depends on.

Tasks don't describe behavior in prose, because the model already does.

### The gate

A batch of flows passes from Shape to Implement & Verify when it is:

1. **Valid.** Models parse and references resolve: every ZFL service exists in a ZDL, every emitted event is declared, every API channel exists. Deterministic, no LLM.
2. **Reviewed.** Agents have no open questions left, and the human has reviewed the projections.
3. **Covered by test data.** Each use case and branch has test data with inputs and expected results, validated by the human. This is the definition of correctness the AFK loop is checked against, so it must exist before the loop starts.
4. **Split.** The task board is approved.
5. **Approved.** The human commits and tags the models, test data and board as the baseline.
6. **Generated** (when a generator exists). The last generation run compiles and runs. It is the AFK loop's starting point.

The batch can be a single flow, a module or a whole system.

The test data at the gate is a first step toward defining correctness before implementation. [Behaviour Validation](https://ivangsa.com/articles/three-pillars-behaviour-validation/) goes further, with a Verification Contract approved at the gate. [Formal Verification](https://ivangsa.com/articles/three-pillars-formal-verification/) explores model-checking ZFL and ZDL before the handover. Both are still being explored.

## Implement & Verify: the Away-From-Keyboard loop

The approved models fit **any** agentic implementation loop. The only requirement is that the loop treats the models as its spec. It can be an orchestrator with implementer and reviewer agents, an existing SDD tool such as [OpenSpec](https://github.com/Fission-AI/OpenSpec), [Spec Kit](https://github.com/github/spec-kit) or [BMAD](https://github.com/bmad-code-org/BMAD-METHOD), a loop runner like [Sandcastle](https://www.aihero.dev/sandcastle/branch-strategies), or a team.

Whatever runs it, it reads **only** the approved models, the ADRs, the validated test data, the task board and the generated code, and it follows three rules:

1. **The model is the spec.**
2. **Agents never edit the models, the contracts or the test data.**
3. **Gaps come back as proposals.**

With an orchestrator and implementer and reviewer agents (the setup in [zenwave-sdd](#zenwave-sdd)), the loop works like this:

- It hands each ready task (blockers done) to an implementer agent, choosing the model by the task's difficulty.
- Each implementer works in a fresh context on its own copy of the code. It writes the failing test first from the approved test data, then the code, and runs only the focused tests for its task.
- Each finished vertical slice goes to a reviewer, a different model from the one that wrote it. The reviewer runs the full suite and checks the slice against the model and the test data. A **FIX** verdict sends the work back.
- It repeats until the board is cleared or every remaining task is blocked.

Only the orchestrator writes to the board, and the human talks to the orchestrator, not to the workers.

More in [Two loops: Agentic Away from Keyboard Loop](https://ivangsa.com/articles/sdd-two-loops-agentic-away-from-keyboard-loop/).

### When the model is wrong

An implementer or reviewer that finds a gap in the model does not work around it in code and does not edit the model. It:

1. marks the task as blocked by the model;
2. writes a proposal: the problem, the model lines involved, the evidence (failing test, code location) and one or more options. The proposal never changes the model;
3. hands it to the human, while the loop continues with other ready tasks.

A gap found while building Arcadia Editions:

```markdown
## P-01 T-08 blocked: model gap
Problem: catalog-inventory/domain-model.zdl:27 says one reservation per
order line, but confirmStockReservation(id) (domain-model.zdl:121) takes
the id of a single StockReservation. An order has many.
Evidence: test place-order/confirm-stock, order with 3 lines.
Options:
- A: confirm all the reservations of an order in one command, by orderId.
- B: one StockReservation per order, with its lines inside.
```

The human picks or adjusts a solution in Shape, updates the model, regenerates and tags a new baseline. The regenerated code is reconciled with the code already merged, and the blocked tasks become ready again.

### Exit criteria

A batch is done when:

- every task of the approved board is done;
- every slice review is clean (no FIX);
- the full suite is green;
- structural assertions and approved test data have not changed since the baseline;
- there are no open model-change proposals.

**Extra check:** once the board is cleared, run the task-list agent again over the result. An empty list means nothing is missing between the model and the code.

The human then reviews the evidence: review reports, test results per branch, open proposals and the running application. Code review is by sampling, or for what the model does not cover. The agents commit to their own branch, and the human signs the merge.

## Where the loops meet

The two loops connect in two places:

- **The gate**, going forward: an approved batch of models, test data and tasks.
- **Model-change proposals**, going back: reports that point at lines of the model, so a human can review them in minutes and change the model in Shape.

[![Where the two loops meet: the human-led Shape loop sends an approved baseline of models, test data and tasks to the agent-led Implement & Verify loop; agents return model-change proposals to the human and produce evidence through reports and tests](https://www.zenwave360.io/images/two-loops-handover.light.webp)](https://www.zenwave360.io/images/two-loops-handover.light.png)

Both loops run at the same time on different batches. When a later batch changes a shared ZDL, that is a new baseline: regenerate, approve, reconcile.

More in [Two loops: Model-Driven Human in the Loop](https://ivangsa.com/articles/sdd-two-loops-model-driven-human-in-the-loop/#hitl-handover-to-the-afk-loop).

## Navigate

Navigate runs outside the loops. ZFL and the ZDLs form one connected graph that can be parsed deterministically. [zenwave-architecture](https://github.com/ZenWave360/zenwave-architecture) builds it from all the models and APIs listed in the architecture manifest, and ZenWave Platform makes it explorable. Use it to understand an existing architecture and the blast radius of a change. For an existing system, it is where the next Discover begins.

More in [From Event Storming to a model your agents can read](https://ivangsa.com/articles/sdd-from-event-storming-to-a-model-your-agents-can-read/#it-connects-everything).

## zenwave-sdd

[zenwave-sdd](https://github.com/ZenWave360/zenwave-sdd) is **one optional way** to use ZenWave models with agents. It is not a software factory. Most of its skills are for the **HITL** loop:

| Skill                                                                 | Loop       | What it does                                                                     |
| --------------------------------------------------------------------- | ---------- | -------------------------------------------------------------------------------- |
| `zenwave-grill-domain`                                                | HITL       | Interview from a brief to a glossary, ADRs and a draft of every ZFL flow and ZDL |
| `zenwave-extend-models`                                               | HITL       | Add what a new ZFL flow needs to the existing ZDLs, change list first            |
| `zenwave-grill-models`                                                | HITL       | Challenge the models; resolve proposals                                          |
| `zenwave-regenerate`                                                  | HITL       | Regenerate after a model change and merge only what the change adds              |
| `zenwave-test-data`, `zenwave-test-scenarios`                         | HITL       | Test data and fixture chains per branch and outcome                              |
| `zenwave-tasks-from-models`, `zenwave-tasks-from-code-and-models`     | HITL, exit | The task board, and the final check                                              |
| `zenwave-gate-check`                                                  | gate       | The checklist before tagging the baseline                                        |
| `zenwave-implement-task`, `zenwave-review-slice`, `zenwave-model-gap` | AFK        | Implementer, reviewer and proposal skills                                        |

It also ships an orchestrator agent for the AFK loop, but you start it and talk to it, so it does not run unattended. If you want agents to run unattended, use a loop runner outside zenwave-sdd; the board and the skills work with it.

The skills are early, extracted from [Arcadia Editions](https://ivangsa.com/articles/arcadia/), where this method is tested end to end. The grilling interview it starts with is described in [Two loops: Model-Driven Human in the Loop](https://ivangsa.com/articles/sdd-two-loops-model-driven-human-in-the-loop/#everything-starts-with-business-discovery).

## Without a generator

ZenWave SDK targets Spring Boot, in Java and Kotlin. In other stacks the method still works, with more left to the agents:

- Shape still produces models, projections, test data and tasks, minus the generated code;
- the task list starts from a blank slate;
- the gate drops its last check;
- the AFK loop writes all of the code instead of the last \~20%, still from a structured blueprint.

More in [DDD as Code + SDD: code generation is optional](https://ivangsa.com/articles/ddd-as-code-sdd-domain-models-instead-of-markdown/#code-generation-is-optional).

## Hard rules and optional practices

Hard rules:

- the model is the spec;
- agents never edit the models, the contracts or the test data;
- agents never invent expected behavior;
- nothing crosses into the AFK loop without passing the gate.

Optional practices: the generator, zenwave-sdd, the board backend (a Markdown list, a folder of task files, Jira, GitHub issues), routing by difficulty, and the extra exit check.

More in [DDD as Code + SDD: the baseline and the rules for whoever implements it](https://ivangsa.com/articles/ddd-as-code-sdd-domain-models-instead-of-markdown/#the-baseline-and-the-rules-for-whoever-implements-it).

## Further reading

The human-voice version of this page, in Iván García Sainz-Aja's articles:

- [When Code Is Cheap: Software Engineering in 2027](https://ivangsa.com/agentic-engineering/), the approach on one page
- [Markdown is the bottleneck](https://ivangsa.com/articles/sdd-markdown-is-the-bottleneck/)
- [From Event Storming to a model your agents can read](https://ivangsa.com/articles/sdd-from-event-storming-to-a-model-your-agents-can-read/)
- [Two loops: Model-Driven Human in the Loop](https://ivangsa.com/articles/sdd-two-loops-model-driven-human-in-the-loop/)
- [Two loops: Agentic Away from Keyboard Loop](https://ivangsa.com/articles/sdd-two-loops-agentic-away-from-keyboard-loop/)
- [DDD as Code + SDD: use domain models instead of Markdown](https://ivangsa.com/articles/ddd-as-code-sdd-domain-models-instead-of-markdown/)
- [What's wrong with spec-driven development, and how to fix it](https://ivangsa.com/articles/whats-wrong-with-spec-driven-development-and-how-to-fix-it/)
- The three pillars of agentic engineering: [overview](https://ivangsa.com/articles/three-pillars-of-agentic-engineering/), [DDD as code](https://ivangsa.com/articles/three-pillars-domain-driven-design-as-code/), [Formal Verification](https://ivangsa.com/articles/three-pillars-formal-verification/), [Behaviour Validation](https://ivangsa.com/articles/three-pillars-behaviour-validation/)
