Skip to content

Spec-Driven Development with Domain Models

Section titled “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).

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
  1. The model is the spec. Business flows in ZFL, bounded contexts in ZDL, contracts in OpenAPI and AsyncAPI.
  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.

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

LevelWhat it describesLanguageEvent Storming level
Flow modelWhat the business does across services: policies (when <event> do <command>), outcomes, failures, compensationsZFLProcess modelling
Domain modelHow one bounded context is built: aggregates, entities, commands, domain events, state transitionsZDLSoftware design
API contractsWhat each context exposes and publishesOpenAPI, AsyncAPI

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 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.

More in Three pillars: Domain-Driven Design as code, From Event Storming to a model your agents can read and What’s wrong with spec-driven development.

Generate the boring parts, specify the last mile

Section titled “Generate the boring parts, specify the last mile”

A model that parses can be turned into code deterministically. ZenWave SDK 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)
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"
}

Navigate to source

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)
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"
}

Navigate to source

Commands and policies name the rules they apply with @rules(...). Syntax: ZDL business rules and ZFL 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).

More in DDD as Code + SDD.

StageWho leadsProducesEnds whenZenWave tools
DiscoverHumans, assisted by agentsPRD, Event Storming findings, first ZFL draftA flow can be written as ZFLEvent Storming, agentic interviews
Shape (HITL)Humans, assisted by agentsApproved models, ADRs, validated test data, generated code, task boardThe gate passesZFL, ZDL, OpenAPI, AsyncAPI, ZenWave Platform, ZenWave SDK, zenwave-sdd skills
Implement & Verify (AFK)AgentsWorking, tested code; review reports; model-change proposalsThe exit criteria passAny agentic loop that takes the models as its spec
NavigateHumans and agentsUnderstanding of the whole architectureNever: it runs alongsidezenwave-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.

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 and Three pillars: Domain-Driven Design as code.

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: 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 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

More in Two loops: Model-Driven Human in the Loop.

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.

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 goes further, with a Verification Contract approved at the gate. Formal Verification explores model-checking ZFL and ZDL before the handover. Both are still being explored.

Implement & Verify: the Away-From-Keyboard loop

Section titled “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, Spec Kit or BMAD, a loop runner like Sandcastle, 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), 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.

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:

## 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.

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.

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

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.

Navigate runs outside the loops. ZFL and the ZDLs form one connected graph that can be parsed deterministically. 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.

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:

SkillLoopWhat it does
zenwave-grill-domainHITLInterview from a brief to a glossary, ADRs and a draft of every ZFL flow and ZDL
zenwave-extend-modelsHITLAdd what a new ZFL flow needs to the existing ZDLs, change list first
zenwave-grill-modelsHITLChallenge the models; resolve proposals
zenwave-regenerateHITLRegenerate after a model change and merge only what the change adds
zenwave-test-data, zenwave-test-scenariosHITLTest data and fixture chains per branch and outcome
zenwave-tasks-from-models, zenwave-tasks-from-code-and-modelsHITL, exitThe task board, and the final check
zenwave-gate-checkgateThe checklist before tagging the baseline
zenwave-implement-task, zenwave-review-slice, zenwave-model-gapAFKImplementer, 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, 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.

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.

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.

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