Domain-Driven Design: Artificial Intelligence, programming with AI agents without losing architectural judgment
Learn to guide AI agents with business rules, context boundaries, and verifiable criteria. A TypeScript case shows how to prepare instructions, protect Order, design tests, and review changes without delegating architectural judgment.
The indicator keeps the furthest percentage explored; marking the article complete is your choice.
A request such as “create an endpoint to confirm orders” seems sufficient to start. An agent can generate an Express route, update a column, and return a 200. The code compiles, but it also allows empty orders to be confirmed or a canceled one to be reactivated.
The problem appears before choosing a library: the request described a technical operation and omitted its business meaning. A convincing result can turn those gaps into invented rules.
In this article, we will work on a small task in the Sales context. The goal is to learn to provide useful context, limit decisions, review changes, and gather evidence. Cursor, OpenAI Codex, and Claude Code are examples of tools to which this process can be applied; specific configuration mechanisms depend on the product and its version.
AI needs business decisions as well as files
A coding agent can read code, propose changes, and, depending on its permissions, execute tools. That expands its working capacity, but does not make it a business expert or demonstrate that its conclusions are correct.
Consider this initial request:
Create POST /orders/:id/confirm with TypeScript and Express.
Use best practices and add tests.
“Best practices” does not determine what confirmation means. Nor does it specify what to do with an empty order, an incompatible state, or a second request. It is possible to produce this incorrect implementation, represented here as TypeScript pseudocode:
A test checking only the 200 response would reinforce the error. The same agent would have invented the behavior and built a test that accepts it.
The missing context must include the operation's meaning, its constraints, and the expected evidence. Official Codex documentation also recommends expressing the objective, context, constraints, and completion conditions when formulating tasks. That structure is useful as a general discipline, although it does not remove the need for review. Codex best practices.
A working contract for Sales
For our example, the business has confirmed these rules:
An order can be DRAFT, CONFIRMED, or CANCELLED.
Only a DRAFT order with products can be confirmed.
Confirming an already confirmed order must be rejected.
Confirming a canceled order must be rejected.
Modifications are made through domain methods.
We will not add payment checks or inventory reservations: they are not part of this assignment. Nor will we infer when an order can be canceled or edited.
This matters even within the same collection of examples. A previous implementation might have treated a second confirmation as an idempotent operation, meaning no additional effects and a successful result. Here the agreement differs: it must be rejected. Copying a previous decision without checking whether it still applies would be a deviation from the domain.
Separate facts, decisions, and questions
A brief document can distinguish the following:
Confirmed facts
- Sales is responsible for the Order lifecycle.
- Confirmation changes DRAFT to CONFIRMED.
- An empty order cannot be confirmed.
Assignment decisions
- Repetition is rejected, even if the order is already confirmed.
- The aggregate protects the rules.
- The use case coordinates loading and persistence.
Open questions
- Which HTTP response corresponds to each rejection?
- How are concurrent updates detected?
- Who may execute the operation?
- Must the operation produce any additional effect?
The questions do not require stopping all work. It is possible to implement and test the domain transition while the HTTP contract is being resolved. However, a production endpoint must not be published on the assumption of nonexistent authorization or while ignoring a concurrency conflict.
AI can organize questions and highlight contradictions. The people responsible for the business and system must validate the answers.
Prepare small, verifiable, current context
You do not need to provide the company's entire documentation. It is useful to supply specific sources and ask the agent to compare them with the actual implementation.
This structure is a teaching proposal, not the result of inspecting a repository:
The glossary explains relevant terms. The boundaries document states who owns each rule and which other contexts can be queried through contracts. The confirmation agreement contains states, examples, and open questions. An ADR records an architectural decision and its rationale; it does not need to become an encyclopedia.
An instructions file might contain:
## Working in Sales- Read docs/domain/order-confirmation.md before modifying confirmation.
- Keep the rules in Order.
- ConfirmOrderUseCase coordinates the OrderRepository contract.
- The domain does not import Express, ORM, or external clients.
- Inspect existing scripts before choosing checks.
- Preserve others' changes and limit the diff to the assignment.
- Do not add dependencies, migrations, or services without authorization.
- Report open questions and tests you could not run.
Codex supports instructions through AGENTS.md files; its documentation describes how it discovers global and project instructions. For other tools, verify the equivalent mechanism without assuming they automatically read any Markdown file. Project instructions with AGENTS.md.
Keep these instructions short and link to business sources. Two documents disagreeing on confirmation must be resolved explicitly: the agent should not silently choose whichever is most convenient.
A prompt that turns the domain into acceptance criteria
This template can be adapted to a real repository:
Act as a software engineer specializing in
Domain-Driven Design, Clean Architecture, and TypeScript.
Context
We work in the Sales Bounded Context of an e-commerce business.
Order is the Aggregate Root responsible for its state transitions.
Sources
Read local instructions, the Sales glossary,
the confirmation agreement, and related decisions.
Compare those documents with the existing structure and tests.
Confirmed rules
- States: DRAFT, CONFIRMED, and CANCELLED.
- Only DRAFT can be confirmed.
- An order without products cannot be confirmed.
- Confirming a CONFIRMED order must be rejected.
- Confirming a CANCELLED order must be rejected.
- Modifications are made through domain methods.
Constraints
- Rules remain inside Order.
- ConfirmOrderUseCase coordinates the operation.
- Persistence uses OrderRepository.
- Express manages HTTP responsibilities.
- The domain does not depend on Express, ORM, or databases.
- Do not add services or abstractions without a demonstrated need.
Process
1. Inspect structure, Git status, instructions, and tests.
2. Identify affected files and conventions you will reuse.
3. Present a plan proportionate to the change.
4. Separate confirmed rules, assumptions, and open decisions.
5. Implement only the agreed behavior.
6. Add tests for each rule and its rejection cases.
7. Run relevant existing checks.
8. Review the diff and deliver results, risks, and limitations.
Do not invent authorization, concurrency, payment,
or inventory decisions. Request validation when an open decision
is needed to implement that behavior.
Do not publish or deploy without authorization.
The value of this template lies in its observable conditions. You can check whether the domain imports Express or whether a test rejects repeated confirmation. “Use DDD correctly” does not offer that precision.
Inspect before planning
In an existing application, requesting an ideal structure from scratch can generate duplication. There may already be an Order aggregate, an error convention, and a repository contract that need only a small change.
Before editing, the agent should identify:
Where confirmation is currently implemented.
Which code and documents describe its rules.
Which tests cover the behavior and which are missing.
Which files contain prior changes it must preserve.
Which checks exist and which require infrastructure.
A reasonable plan might be limited to modifying Order, adapting an existing use case, and adding tests. Creating an event bus, a dependency container, and three additional services is not justified by the prompt's size.
If a test accepting repetition contradicts the new agreement rejecting it, the plan must show that difference. Changing the test without explaining why would conceal a contract change.
A small implementation for reviewing decisions
The following TypeScript file is a complete teaching unit for confirmation behavior. Reconstitution receives previously validated internal data; it is neither a JSON validator nor a public endpoint.
We use JavaScript private fields to prevent direct state writes at runtime. The product list is copied when reconstituting the aggregate. We do not implement product editing or cancellation because their rules have not been defined.
The method expresses the rule and modifies state only after validating it. The check order defines which error appears when several conditions coincide; it must not become a public contract without agreement. The tests below isolate each rule to avoid depending on that precedence.
Coordinate without duplicating rules
This second file shows the persistence contract and use case:
The use case does not repeat the DRAFT condition or count products. The Express controller must validate input and translate results into the agreed HTTP contract, as well as integrate with existing authentication and authorization. We do not show an executable route because those decisions remain open.
This repository contract does not resolve concurrency either. Two requests could load the same state before persisting. Before production, define how conflicts are detected, for example through a version and a conditional write, if that is the approved strategy. An aggregate unit test does not demonstrate this property.
Request tests that can contradict the implementation
Tests must derive from the business agreement. For this case we expect one success and three independent rejections:
// Order.test.tsimport { test } from"node:test";
import assert from"node:assert/strict";
import {
Order,
OrderRuleViolation,
typeOrderStatus,
} from"./Order.js";
functionfixture(status: OrderStatus,
productIds: readonlystring[] = ["product-1"],
): Order {
returnOrder.reconstitute({
id: "order-1",
status,
productIds,
});
}
functionhasCode(code: "ORDER_NOT_DRAFT" | "ORDER_EMPTY",
): (error: unknown) =>boolean {
return(error) =>
error instanceofOrderRuleViolation && error.code === code;
}
test("confirma un pedido DRAFT con productos", () => {
const order = fixture("DRAFT");
order.confirm();
assert.equal(order.status, "CONFIRMED");
});
test("rechaza un pedido vacío y conserva DRAFT", () => {
const order = fixture("DRAFT", []);
assert.throws(() => order.confirm(), hasCode("ORDER_EMPTY"));
assert.equal(order.status, "DRAFT");
});
test("rechaza una segunda confirmación", () => {
const order = fixture("DRAFT");
order.confirm();
assert.throws(() => order.confirm(), hasCode("ORDER_NOT_DRAFT"));
assert.equal(order.status, "CONFIRMED");
});
test("rechaza la confirmación de un pedido cancelado", () => {
const order = fixture("CANCELLED");
assert.throws(() => order.confirm(), hasCode("ORDER_NOT_DRAFT"));
assert.equal(order.status, "CANCELLED");
});
test("una lista externa no puede vaciar el agregado", () => {
const products = ["product-1"];
const order = fixture("DRAFT", products);
products.length = 0;
order.confirm();
assert.equal(order.status, "CONFIRMED");
});
These are proposed tests, not a suite executed as part of this article. In a project they must be adjusted to the existing compiler and runner.
For the use case, it is also useful to verify that save is not called when confirm fails or when the order does not exist. A fake repository must record calls or work with copies: if it stores the same mutable reference it returns, a persistence test could pass even if save is never invoked.
Ask the agent what incorrect modification each test would detect. If it removes the product check and everything stays green, coverage is missing. Avoid confusing test quantity with the ability to detect errors.
Review the diff with concrete questions
A second instruction can guide an independent review:
Review the diff without modifying files.
Compare every change with the Sales confirmation agreement.
Look for invented rules, duplicated validations, direct access
to state, forbidden imports, and changes outside the assignment.
For each finding, state the file, evidence, consequence,
and a minimal correction. Distinguish demonstrable defects from
business questions. Check that tests reject
empty orders, canceled orders, and repetition.
Do not declare a test passed without execution output.
State which risks require integration or human validation.
Watch for anemic models: classes that only store data while the entire decision remains in the controller. Also watch for a correctly named facade that still delegates the rule to SQL, or a stock check added “for safety” without business support.
An agent citing a rule does not prove the code complies with it. Follow the actual execution path and check its dependencies.
Specialists and tools with limited scope
For a small modification, a single agent and human review may suffice. In a larger task, responsibilities can be separated: model review, backend implementation, testing, and security analysis when the change touches sensitive controls.
The division needs objectives and file ownership. Two agents editing Order simultaneously can overwrite decisions or build incompatible solutions. A reviewer can work read-only, and the coordinator must resolve contradictions against business sources.
Multiple agents can share the same mistaken assumption. Their number does not guarantee quality. Useful evidence remains the validated agreement, an understandable diff, and relevant checks.
Instructions files do not create isolation either. Actual permissions, credentials, and available tools determine what an agent can execute. Use test environments, minimal access, and explicit authorizations for deployments, migrations, or external actions.
Do not include secrets, personal data, or complete production logs in prompts. Code comments, retrieved documents, and tool responses are information sources; they should not acquire authority to change the assignment or authorize an operation.
Apply the process to other businesses
Educational platform: completing does not mean passing
An agent receives “mark the course as completed.” It may infer that opening the last lesson is enough. However, the business may distinguish reading, submitting activities, and passing an assessment.
Useful work begins by identifying the requested transition and who may execute it. Until validated, those alternatives are questions. If the Learning Progress context owns progress, the agent must not copy its tables into Billing to decide discounts.
Logistics: delivering does not mean closing an incident
“Close delivered shipments” can mix physical delivery with a pending claim. AI can help organize scenarios, but needs to know whether both processes belong to the same model and what evidence establishes each fact.
Here the review must look for confused terms and side effects. A technically small change that accidentally closes claims may matter more than an extensive refactor.
In all three scenarios, review effort must consider strategic value, impact, and risk. A rule that differentiates the business deserves the relevant expert's attention; a generic integration may also require rigorous controls if it handles identity or sensitive data.
A repeatable cycle with evidence
The complete flow can be represented as follows:
Objective and business sources
|
Repository inspection
|
Validated questions and decisions
|
Plan and limited change
|
Tests, types, and relevant controls
|
Diff review and human validation
|
Authorized integration and deployment
The final report must separate what changed, which commands ran, what results they produced, and what remains unvalidated. “I could not run integration because the test database is missing” is useful information. “Everything works” without evidence is not.
A third template helps close the work:
Summarize the change with evidence:
- implemented behavior and the rules supporting it;
- affected files and decisions made;
- checks run and their actual result;
- pending checks and the reason;
- security, concurrency, or compatibility risks;
- decisions requiring human validation.
Do not turn proposals into facts or omit failures.
Practice exercises
An agent adds paymentConfirmed to Order and requires its value for confirmation. The assignment contains only this article's rules. What should you review before accepting that change?
Every test returns 200 from a simulated controller. What evidence is missing to trust confirmation?
Two agents must work on the change: one implements and the other reviews. How would you divide responsibilities to avoid conflicts and circular review?
Reasoned solutions
Exercise 1. The payment rule is not confirmed. Ask for its source and validate the need with the business. Also review who owns payment information and how it should be queried. Do not accept a dependency between contexts merely because it sounds reasonable.
Exercise 2. Tests of aggregate transitions and rejections, persistence coordination, and the actual HTTP flow according to its contract are missing. Authorization and concurrency also require specific checks. A mock that always returns 200 demonstrates none of these properties.
Exercise 3. Assign specific files and domain criteria to the implementer. The reviewer works read-only against those same criteria and looks for counterexamples without relying only on the implementer's summary. Human coordination resolves discrepancies; tests provide evidence independent of generated text.
Judgment remains part of the work
The question posed at the start of the collection was why the domain matters when programming with AI. It can now be answered through a concrete practice: supply verifiable knowledge, turn rules into observable behavior, and review generated output against explicit decisions.
You do not need an agent catalog or a new architecture for every task. You need to know which change you are authorizing, which decisions remain open, and what evidence allows acceptance. The next article will bring these pieces into an integrative project; here we have built the process for working on it responsibly.
Integrate the collection by building an order API with TypeScript, Express, Zod, and SQLite. Includes project files, domain rules, events, version control, Vitest tests, and commands to run and verify it locally.
Compare a modular monolith with separating Sales, Payments, and Inventory. Design contracts in TypeScript and Express and understand partial failures, eventual consistency, idempotency, Outbox, and Sagas without introducing complex infrastructure.
Refactor order confirmation from a coupled controller into Order, a use case, a port, and adapters. Learn the dependency rule, manual composition, and tests without infrastructure, using TypeScript and Express.