domain-driven-design
This Claude Code skill applies Domain-Driven Design tactical patterns to domain modeling work, enforcing aggregate design, value objects over primitives, entity identity rules, and bounded context boundaries. Use it when creating or modifying domain models, designing aggregates, working in domain layers, or when domain terminology like aggregate, value object, entity, bounded context, or DDD appears in the conversation. The skill supports project-specific configuration through custom DDD principle documents that can override or overlay default patterns, and adapts implementation recommendations to language-specific constructs when language idiom guidance is provided.
git clone --depth 1 https://github.com/techygarg/lattice /tmp/domain-driven-design && cp -r /tmp/domain-driven-design/skills/atoms/domain-driven-design ~/.claude/skills/domain-driven-designSKILL.md
# Domain-Driven Design
## Config Resolution
The skill supports project-custom principles. Resolution:
1. Look for `.lattice/config.yaml` in the repo root.
2. If found, check `paths.ddd_principles` for a custom doc path.
3. If a custom document exists at that path, read it and check its YAML frontmatter `mode`:
- **`mode: override`**: the custom doc has full precedence.
Use it instead of the embedded default. It must be comprehensive -- sole reference.
- **`mode: overlay`** (or no mode): read the embedded `./references/defaults.md` first, then apply
the custom doc on top. A custom section replaces the matching default
section (matched by heading); new sections append after the defaults.
4. If a custom path is configured but no document exists at it → tell the user which configured path is missing, then read `./references/defaults.md`.
5. If there is no config file or no `paths.ddd_principles` key → read `./references/defaults.md`.
6. **Language adaptation**: if `paths.language_idioms` is set in the config and the document exists, read its **"Type System & Object Model"** section and adapt entity, value object, and aggregate implementation patterns to language constructs (e.g., struct vs class, trait vs interface, data class vs record). Language idioms take precedence over pseudocode defaults.
## Self-Validation Checklist
**STOP after generating each component.** Verify ALL checks before proceeding. If any check fails, fix before presenting. If a check is a judgment call with multiple valid approaches (see Ambiguity Signals), flag it — present options and reasoning rather than silently choosing; if `framework:collaborative-judgment` is loaded, use its presentation format.
1. **ENTITY VS VALUE OBJECT**: For each domain object — does the business track individual instances over time? Yes → entity with identity. No → value object, immutable and self-validating.
2. **AGGREGATE BOUNDARY**: Does a transactional invariant require this object inside the aggregate? If not → reference it from a separate aggregate by ID.
3. **RICH BEHAVIOR**: Does the entity have methods that enforce business rules, guard state transitions, raise events? If the entity is just a data holder → move logic from services into the entity.
4. **VALUE OBJECT COVERAGE**: Scan for primitives that should be value objects — string emails, number amounts, raw UUIDs as identifiers → wrap in a validating value object.
5. **AGGREGATE COHESION**: List the business rules the root enforces. Does every internal entity participate in at least one invariant? If not → it belongs in its own aggregate.
6. **DOMAIN EVENTS**: Should a domain event be raised — a state transition another aggregate reacts to, a change triggering notification, an audit/compliance requirement? Do not raise events for internal changes nothing reacts to.
7. **DOMAIN SERVICE**: Does stateless logic spanning multiple entities belong in a domain service rather than an application service? Keep I/O and infrastructure calls out of it.
8. **FACTORY**: Is complex aggregate creation encapsulated behind a factory method (`Order.create(...)`) or a standalone factory class? Are initial creation and reconstitution from persistence handled separately?
All checks pass → state "Passes domain-driven-design. [next step]."
## Active Anti-Pattern Scan
After verifying the checklist above, scan the output for these specific anti-patterns. If you find any, fix before presenting.
- [ ] **Anemic Domain Model**: Entity is a getter/setter data holder; all logic lives in services → move business rules into entities and value objects
- [ ] **Primitive Obsession**: Raw string for email, number for money, UUID for ID → wrap in a validating value object with behavior
- [ ] **God Aggregate**: Aggregate has many entities, loads slowly, high contention → decompose; keep only what shares a transactional invariant
- [ ] **Cross-Aggregate Transaction**: Service updates two aggregates in one transaction → use domain events and eventual consistency
- [ ] **Leaking Domain Logic**: Business rule in a controller, application service, or infrastructure → extract into a domain object or domain service
- [ ] **Misidentified Entity/Value Object**: Entity without a lifecycle, or value object with tracked identity → apply the identity test
## Ambiguity Signals
These checks often have multiple valid outcomes. When you encounter one, present the options rather than silently choosing. If `framework:collaborative-judgment` is loaded, use its presentation format.
- **Aggregate Boundary Size**: Small aggregate (more events, eventual consistency) vs large aggregate (simple transaction, immediate consistency). Neither is inherently correct — it depends on contention patterns and invariant scope.
- **Entity vs Value Object**: Some concepts (like `Address` or `Money`) may or may not need identity depending on domain complexity. Apply the identity test, but acknowledge when borderline.
- **Domain Service vs Entity Method**: Logic spanning multiple entities could live in a domain service or be a method on the primary entity. The choice depends on which entity "owns" the invariant.
- **Object Creation Pattern**: Factory method on the aggregate root, standalone factory class, builder pattern, or plain constructor — depends on assembly complexity and team convention. Don't prescribe a pattern; ask which approach the team prefers.
## Scope Statement
This skill operates within a single repo, single bounded context (e.g., one API -- Order, User, Pricing). It covers tactical DDD patterns only -- not strategic DDD (no context maps, no microservice topology, no bounded-context integration).
If a task appears to span multiple bounded contexts (e.g., an Order feature calling Shipping logic), flag before proceeding: "This task touches [Context A] and [Context B]. Cross-context integration is strategic DDD — outside this skill's scope. Would you like to scope to one context, or proceed knowing cross-coAudit and fix all Lattice documentation, README, docs/, PROJECT.md, GitHub issue templates, and CLAUDE.md to ensure they are fully aligned with the current skill inventory. Documentation drift is the most common source of user confusion in Lattice — a skill exists in the codebase but not in the docs, or a renamed skill leaves a stale reference in the bug report template. If you've made any change to skills/ and haven't run this, run it now. Use when the user says 'align docs', 'audit docs', 'update documentation', 'skill align', 'check docs are in sync', 'audit skill inventory', 'ensure docs are aligned', 'are the docs up to date', or 'what needs updating'. Standalone — does not call other skills.
Create a new Lattice skill — atom, molecule, or refiner — following all framework conventions. Writing skill files manually almost always produces convention violations: wrong section order, missing confirmation gates, defaults.md without the right structure. This skill knows all of that and guides you through it. Use whenever adding any new atom, molecule, or refiner to Lattice, or when the user says 'create a new skill', 'add an atom', 'add a molecule', 'add a refiner', 'build X for Lattice', 'new lattice skill', or 'skill forge'. Does not validate, align docs, or deploy — those are separate skills you run after.
Deep behavioral audit of a Lattice skill — proposes 3 review personas relevant to the skill, runs independent scenario analysis from each persona's perspective, then merges only the high-confidence, practical findings into a severity-ordered gap report with proposed fixes. Structural validation (conventions, cross-references) is skill-validate's job — this skill finds gaps that would realistically surface when someone actually uses the skill: missing scenario handling, ambiguous instructions, silent failure cases, and behavioral inconsistencies. Filters out theoretical edge cases, low-likelihood speculation, and findings owned by other skills. Use after writing or significantly changing any skill, or when the user says 'review this skill', 'deep review', 'does this skill work', 'find gaps in this skill', 'stress test this skill', 'review from different angles', or 'skill review'. Standalone — does not call other skills.
Validate any Lattice SKILL.md against all tier conventions — atoms, molecules, and refiners. Catches structural errors, broken cross-references, and convention violations before they reach the repo. If you just wrote or modified a Lattice skill file and haven't run this yet, run it now — manual review consistently misses the same categories of errors this skill is specifically designed to catch. Use when the user says 'validate this skill', 'check this skill', 'does this follow conventions', 'review this skill file', 'check my SKILL.md', or 'skill validate'. Reports PASS/FAIL with specific file-and-section findings and actionable fixes. Standalone — does not call other skills.
Architectural thinking partner for an existing repository — scans the codebase, conducts a structured interview, agrees on current architectural state and recommended direction, and produces a shareable insights document. Scoped to one repository, module, or folder. Does not execute transformation — it orients. Use when the user says 'assess my codebase architecture', 'what direction should my codebase go', 'architecture compass', 'understand my architecture', 'audit architecture drift', 'architectural assessment', or 'help me understand what is wrong with my codebase'.
Facilitate a structured conversation to define architecture principles for a repository. Supports multiple architecture styles: clean architecture (default), hexagonal / ports & adapters, modular monolith, or custom. Produces a formal architecture document that the corresponding atom will use. Use when setting up a new project, defining architecture standards, or when the user says 'setup architecture', 'define layers', 'architecture principles', 'help me define my architecture', 'hexagonal architecture', 'modular monolith', 'ports and adapters', or 'define my architecture style'.
Enforce architectural rules when generating or modifying code, and validate proposed designs before approval (design mode). Defaults to clean architecture; supports any architecture style via the architecture-refiner. Validates layer responsibilities, dependency direction, and structural constraints using the loaded architecture rules. Use when generating code, reviewing architecture, creating new files, or when the user mentions 'architecture', 'layers', 'structure', 'dependency rules', 'hexagonal architecture', 'ports and adapters', 'modular monolith', or 'onion architecture'. Also use when reviewing generated code for structural compliance.
Investigate, reproduce, and safely fix a bug with regression protection. Composes context, diagnosis, architecture, code quality, and testing guardrails into a reproduce-first repair workflow. Use when the user says 'fix this bug', 'debug this', 'investigate this failure', 'patch this regression', 'repair this issue', or 'why is this broken'.