# Test Driven Development

> >

- **Type:** Skill
- **Install:** `agentstack add skill-lockp111-agent-ddd-engineering-test-driven-development`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [lockp111](https://agentstack.voostack.com/s/lockp111)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [lockp111](https://github.com/lockp111)
- **Source:** https://github.com/lockp111/agent-ddd-engineering/tree/main/skills/test-driven-development

## Install

```sh
agentstack add skill-lockp111-agent-ddd-engineering-test-driven-development
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# Test-Driven Development

## Overview

TDD IS the Phase 7 coding process. It is the sole driving skill during implementation. The MAP→ITERATE→DIFF cycle replaces ad-hoc coding. TDD embeds key constraints from Phase 6 (behavioral conformity) and coding-isolated-domains (architecture rules) via shared references — no need to load three skills simultaneously.

**Anti-hallucination role:** Tests are executable proof, not discovery aids. Position in the stack: DDD (semantic truth) → Phase 5 (structural truth) → Phase 6 (conformity truth) → **TDD (execution proof)**.

**Foundational Principle:** Tests are **executable proof, not optional verification**. Code without corresponding tests is unproven. Tests derived from implementation (not from behavior contracts) are biased. All rules in this skill are mandatory constraints — the MAP→ITERATE→DIFF cycle is the sole coding process, not an optional add-on. There is no complexity threshold below which you may skip TDD.

**Execution model:** This skill runs inside a **per-context subagent** dispatched by the orchestrator. Each subagent receives only the Phase 6 behavior contract and schema files for its own bounded context — not the full project's artifacts. This keeps the context window clean and prevents cross-context pollution. See [coding-isolated-domains](../coding-isolated-domains/SKILL.md) § Context-per-Session Execution Model for details.

## When to Use

- Phase 7 coding begins and Phase 6 behavior contracts + Phase 5 schemas exist
- Domain code needs to be implemented from behavior contract or schema definitions
- When tempted to write code before tests, skip test output verification, or derive tests from implementation
- When returning to a project where specs have changed since last coding session

**Do NOT use when:** No Phase 6 behavior contracts exist (run [spec-driven-development](../spec-driven-development/SKILL.md) first), making trivial changes (single config line, typo fix), or working on pure infrastructure adapters outside domain layer. **REQUIRED PREREQUISITES:** Phase 6 behavior contracts in `docs/ddd/phase-6/` (from [spec-driven-development](../spec-driven-development/SKILL.md)) AND Phase 5 schema files (from [defining-schemas](../defining-schemas/SKILL.md)).

**Simplified Mode Exception:** When `ddd-progress.md` shows `workflow_mode: simplified`, Phase 5 and Phase 6 do not exist. In this case, TDD is NOT dispatched — [coding-isolated-domains](../coding-isolated-domains/SKILL.md) uses its Minimal Technical Checklist path from `decisions-log.md` instead. If an orchestrator dispatches TDD without Phase 6 artifacts, return STOP immediately: "Phase 6 behavior contracts required but not found — cannot derive test plan."

## Quick Reference

| Step | Action | Output |
|:---|:---|:---|
| Entry Check | `git diff` on Phase 6 + Phase 5 source files; if changed → RECONCILE | Mode decision |
| RECONCILE | Diff spec changes → update test-map + affected tests → re-run ITERATE for changed tests only | Updated `test-map.md` + re-verified tests |
| MAP | Read Phase 6 behavior contracts + Phase 5 schemas + derive complete test plan + adversarial review | `docs/ddd/test-map.md` |
| ITERATE | Per test: RED → GREEN → REFACTOR; per 5 tests: Focus Refresh | Test files + domain code |
| DIFF | Spec↔Test↔Code coverage + chain integrity check | `docs/ddd/test-coverage.md` |
| Post-DIFF | Use Case Orchestration TDD (category 8: RED→GREEN→REFACTOR per write use case) then adapter implementation (converter → repo → server → wiring → integration test) | See [coding-isolated-domains Step 6](../coding-isolated-domains/SKILL.md) |

## Ambiguity Handling

Follow the [Ambiguity Handling Protocol](../ddd-protocol/ambiguity-handling-reference.md) throughout this skill.

**TDD STOP triggers — confirm immediately:**

| Ambiguity | Why STOP |
|:---|:---|
| Phase 6 behavior contract has no error types defined | Cannot derive error path tests — Phase 6 may have missed this; surface upstream |
| Test fails for unexpected reason (not "feature missing") | Could indicate spec inconsistency or environment issue — diagnose before proceeding |
| Architecture red line violated and no obvious fix | Domain boundary decision needed — may require revisiting Phase 3 contracts |

**TDD ASSUME & RECORD — proceed with explicit assumption:**

| Ambiguity | Default assumption |
|:---|:---|
| Test execution framework unspecified | Use project's existing framework; if new project, follow Phase 4 tech stack conventions; record |
| Spec does not specify concurrency behavior | Assume single-threaded for domain tests; record; note for integration test phase |
| Mock boundary unclear for port tests | Mock only external ports (database, external API); never mock domain internals; record |
| Mock boundary unclear for use case orchestration tests | Mock repo ports + event publisher ports; use real domain objects; never mock aggregates or value objects; record |

### Orchestrator Mode Exception

When dispatched by an orchestrator, TDD runs autonomously: MAP in single pass, ITERATE without per-test human interaction (Focus Refresh still triggers), DIFF writes immediately, RECONCILE auto-commits, Golden Reference auto-captures. STOP triggers return to orchestrator. Post-DIFF results persist and return — orchestrator manages human checkpoint. Standalone mode: full interactive session mandatory.

## Implementation

### Core Cycle

```
Entry Check → MAP → ITERATE → DIFF
                      ↑         │
                      └─────────┘  (per aggregate unit: mini-DIFF → next unit)
```

The aggregate is the universal chunking boundary — it serves as consistency boundary (DDD), behavior contract organization unit (Phase 6), and AI working memory chunk (TDD). Three methodologies converge naturally at the aggregate. Process one aggregate at a time through the full cycle before moving to the next.

Context budget per aggregate: MAP ~200 lines active, ITERATE ~280 lines, DIFF ~550 lines (peak). Safe for any context window. If an aggregate's behavior contract section exceeds 200 lines, the aggregate is too large — split it upstream in Phase 6.

### Entry Check

Before starting MAP, check whether Phase 6 or Phase 5 source files have changed:

1. If `docs/ddd/test-map.md` does not exist → **normal flow** (first run). Proceed to MAP.
2. If `docs/ddd/test-map.md` exists → use `git diff --name-only` to check whether the Phase 6 context files (`docs/ddd/phase-6/*.md`) or Phase 5 schema files (listed in `docs/ddd/schema-manifest.md`) have changed since `test-map.md` was last committed.
   - No changes → **normal flow**. Resume from where `test-map.md` progress left off.
   - Any changes detected → **RECONCILE mode**. Phase 6 behavior contracts or Phase 5 schemas changed since last MAP (human edit, Phase 6 merge, or new iteration). Run the RECONCILE Protocol before continuing normal flow.

### MAP

Per aggregate unit (aggregate | saga | query):

1. **Discover available contexts** — read `docs/ddd/phase-6-behavior-contracts.md` (index). The Context Summary table lists every context name and its corresponding file path. Pick the context matching this aggregate unit.
2. **Read Phase 6 behavior contract** for this unit: `docs/ddd/phase-6/{context}.md` (REQUIRED — behavioral rules, state machines, invariants, scenarios).
3. **Read Phase 5 schema files** for this aggregate (REQUIRED — field constraints, value ranges for boundary tests). Locate via `docs/ddd/schema-manifest.md`.
4. **Read Phase 1 domain events + Phase 2 ubiquitous language** (if they exist — enrich test derivation; see Graceful Degradation if absent).
5. **Derive complete test plan** across all 8 categories:
   - **Behavioral** — command → event mapping (e.g., `CreateOrder` → `OrderCreated`) ← Phase 6 scenarios
   - **Invariant** — aggregate business rules that must always hold (e.g., order total > 0) ← Phase 6 invariants
   - **Domain rule** — specific business rules from ubiquitous language ← Phase 6 + Phase 2
   - **Value object** — immutability, validation, equality semantics ← Phase 5 schema constraints
   - **Port** — interface contract compliance (port methods accept and return expected types) ← Phase 6 Blueprint
   - **Error path** — every domain error type defined in the spec gets at least one test ← Phase 6 scenarios
   - **Boundary** — field constraint edge cases ← Phase 5 schema constraints. For each constrained field, derive boundary tests per the **Boundary Derivation Protocol** in [test-derivation-reference.md](./test-derivation-reference.md) section 5. This is NOT a suggestion list — derive one test per applicable boundary per constrained field.
   - **Use Case Orchestration** — command (write) use case wiring correctness ← Phase 6 command scenarios + Blueprint app structure. Scope: write use cases only; query use cases defer to integration tests. See [test-derivation-reference.md](./test-derivation-reference.md) section 8 for derivation rules. These tests are planned in MAP but executed in Stage 3 (Post-DIFF), when app layer code is driven into existence via RED→GREEN→REFACTOR.
6. **Adversarial self-review** — after deriving the initial plan, challenge it:
   - "What error paths did I miss? Does every behavior contract error type have a test?"
   - "What happens at zero, empty, max, concurrent? Are boundary values covered?"
   - "What if dependencies fail? Are port failure paths tested?"
   - "Am I only testing happy paths?" (Happy-path bias is AI's systematic deficiency.)
   - "Does every write use case have an orchestration test? Load→command→save→publish — can any step be forgotten? What if save or publish fails?"
   - Add any discovered gaps to the test plan before writing.
7. **Write** traceability test plan → `docs/ddd/test-map.md` (see Artifact: test-map.md below).

### ITERATE

Per-test cycle: RED → GREEN → REFACTOR. Focus Refresh every 5 tests. Full checklists for each phase: see [tdd-cycle-reference.md](./tdd-cycle-reference.md).

**Key rules (always in context):**
- **RED**: actual failure output MUST appear in context. "It should fail" is not evidence.
- **GREEN**: minimal code only. Architecture red lines checked per [domain-architecture-reference](../ddd-protocol/domain-architecture-reference.md). Violation = delete and redo.
- **REFACTOR**: no behavior changes. Full test suite + linter must pass.
- **Focus Refresh**: every 5 tests, re-read Phase 6 contract + test-map progress. Not optional.

**RED essentials:** (1) Write the test BEFORE any implementation code exists. (2) Run the test and confirm it fails for the expected reason (not a compile error or wrong import). (3) Test name must reflect the behavioral rule from Phase 6, not the implementation.

**GREEN essentials:** (1) Write the MINIMUM code to make the failing test pass — no extra logic. (2) Do not modify the test to make it pass. (3) Verify no architecture red lines are violated (no ORM tags in domain, no HTTP in domain).

**REFACTOR essentials:** (1) Improve code structure without changing behavior — tests must still pass. (2) Extract duplication only if it appears 3+ times. (3) Do not add new functionality during refactor.

After completing each test: update `test-map.md`, mark test status (pass or pending with reason).

**After completing each aggregate's domain TDD (Stage 2):**

1. **Mini-DIFF**: coverage check for this unit only — are all behavior contract methods and error types tested?
2. **Checkpoint**: update `test-map.md` with completed status and pass/pending markers for this unit.
3. **Context cleanup**: prior units' raw test output and implementation detail can be dropped from working memory. Keep only summaries (pass counts, any notable issues). This prevents context bloat across multi-aggregate sessions and keeps the active context within budget.

**Use Case Orchestration TDD (Stage 3 — NOT during domain TDD):**

After DIFF passes for ALL aggregates and user approves, execute category 8 tests first in Stage 3. Per write use case: RED→GREEN→REFACTOR (same cycle as domain TDD). Mock boundary per ASSUME table. See [test-derivation-reference.md](./test-derivation-reference.md) § 8 for derivation rules and procedural steps. After all use case TDD completes, proceed to remaining adapters (converter → repo → server → wiring → integration test). Checkpoint: update `test-map.md` with use case orchestration test status.

### DIFF

After all aggregate units are complete, run the 5-dimension coverage check:

1. **Contract → Test**: every Phase 6 behavior contract method/scenario and Phase 5 schema error type has a corresponding test? Any contract item without a test is a coverage gap. Every constrained field (from Phase 5 schemas) has boundary tests? Edge cases derived per the Boundary Derivation Protocol are covered?
2. **Test → Code**: every test exercises real code (not mock bypasses)? Tests that only exercise mocks prove nothing about production behavior. All 7+4 architecture red lines verified (from [domain-architecture-reference](../ddd-protocol/domain-architecture-reference.md))?
3. **Code → Contracts**: code types, fields, and method signatures match Phase 6 behavior contract + Phase 5 schema definitions? Code that deviates from contracts is drift — even if tests pass.
4. **Chain integrity**: Event → Contract (Phase 6) → Test → Code — each link present? (PRD → Event is optional, only if Phase 1 annotated it.) A broken link means something in the chain was invented, not derived.
5. **Use Case Orchestration**: every write use case has orchestration tests (happy path + error propagation + port failures + event publishing)? Query use cases explicitly deferred to integration tests?

**Persist to Filesystem:** Output → `docs/ddd/test-coverage.md` (format template: [test-coverage-template](../full-ddd/templates/test-coverage-template.md)). DIFF Decision: all 5 dimensions pass → next aggregate, or gaps found → re-enter ITERATE.

Update `docs/ddd/ddd-progress.md` TDD status to `in-progress` (not `complete` — Phase 7 completes only after adapter implementation in Step 7). Append **TDD-specific** decisions to `docs/ddd/decisions-log.md`: test coverage summary, traceability gaps found, spec deviations resolved. **This step is mandatory — do not skip even if all tests are green in the conversation.** Architectural design decisions (aggregate proposals, invariant changes) are recorded later by `coding-isolated-domains` Step 7 — do NOT duplicate them here.

### Post-DIFF: Adapter Implementation

**User approval gate:** After DIFF passes, present the DIFF summary to the user and ask explicitly: *"Domain TDD for this context is complete. All aggregates pass. Shall I proceed to adapter implementation (Step 6)?"* Do not interpret silence, brief acknowledgment, or topic change as approval. Wait for an explicit yes.

After the user approves, **domain code for this context is complete**. The remaining Phase 7 work — app use case TDD (category 8) then adapter implementation (converter, repo), server handlers, wiring, and integration tests — is guided by [coding-isolated-domains](../coding-isolated-domains/SKILL.md) Step 6. See the [Phase 7 Execution Order](../coding-isolated-domains/SKILL.md#phase-7-execution-order-per-bounded-context) for the full stage sequence.

### RECONCILE Protocol

Triggered when Entry Check detects spec changes. See [reconcile-protocol-reference.md](./reconcile-protocol-reference.md) for the full 7-step protocol (DETECT → DELTA → IMPACT → RE-MAP → RE-ITERATE → RE-DIFF → commit).

### Golden Reference Aggregate

The first aggregate implemented gets a human style review — an **advisory checkpoint** (not a formal gate):

1. Complete first aggregate's full MAP → ITERATE → DIFF cycle.
2. Present code to human: "This is the first aggregate. Please review code style, naming conventions, and structural patterns. Your corrections become the golden reference for all subsequent aggregates."
3. Human corrects or approves → this becomes the style reference.
4. Subseq

…

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [lockp111](https://github.com/lockp111)
- **Source:** [lockp111/agent-ddd-engineering](https://github.com/lockp111/agent-ddd-engineering)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-lockp111-agent-ddd-engineering-test-driven-development
- Seller: https://agentstack.voostack.com/s/lockp111
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
