Codex compatibility note:
- Invoke repository skills with
$skill-name in Codex; this mirrored copy rewrites legacy Claude /skill-name references.
- Task tracker mandate: BEFORE executing any workflow or skill step, create/update task tracking for all steps and keep it synchronized as progress changes.
- User-question prompts mean to ask the user directly in Codex.
- Ignore Claude-specific mode-switch instructions when they appear.
- Strict execution contract: when a user explicitly invokes a skill, execute that skill protocol as written.
- Subagent authorization: when a skill is user-invoked or AI-detected and its protocol requires subagents, that skill activation authorizes use of the required
spawn_agent subagent(s) for that task.
- Do not skip, reorder, or merge protocol steps unless the user explicitly approves the deviation first.
- For workflow skills, execute each listed child-skill step explicitly and report step-by-step evidence.
- If a required step/tool cannot run in this environment, stop and ask the user before adapting.
Codex Project-Reference Loading (No Hooks)
Codex uses static project-reference loading instead of runtime-injected project docs.
When coding, planning, debugging, testing, or reviewing, open project docs explicitly using this routing.
Always read:
docs/project-config.json (project-specific paths, commands, modules, and workflow/test settings)
docs/project-reference/docs-index-reference.md (routes to the full docs/project-reference/* catalog)
docs/project-reference/lessons.md (always-on guardrails and anti-patterns)
Missing/stale context route: If docs/project-config.json, the docs index, lessons.md, CLAUDE.md, AGENTS.md, or any task-required reference doc is missing or stale, auto-run $project-init or the narrow setup route ($project-config, $docs-init, $scan-all, $scan --target=<key>, $claude-md-init) before ordinary project-specific work. If Codex mirrors or AGENTS.md are missing/stale, ask the user to run $sync-codex; do not auto-run it.
Situation-based docs:
- Project structure/architecture/tech-stack/deployment/setup (any layer — backend, frontend, or infra):
project-structure-reference.md
- Backend/CQRS/API/domain/entity changes:
backend-patterns-reference.md, domain-entities-reference.md
- Frontend/UI/styling/design-system:
frontend-patterns-reference.md, scss-styling-guide.md, design-system/README.md
- Spec authoring,
docs/specs/ pathing, or TC format: feature-spec-reference.md, spec-system-reference.md, spec-principles.md
- Behavior/public-contract changes or spec-test-code sync:
workflow-spec-test-code-cycle-reference.md plus the spec docs above
- Derived spec indexes/ERDs/reimplementation guides:
spec-system-reference.md and source Feature Specs under docs/specs/
- Integration test implementation/review:
integration-test-reference.md
- E2E test implementation/review:
e2e-test-reference.md
- Code review/audit work:
code-review-rules.md plus domain docs above based on changed files
Do not read all docs blindly. Start from docs-index-reference.md, then open only relevant files for the task.
[BLOCKING] Execute skill steps in declared order. NEVER skip, reorder, or merge steps without explicit user approval.
[BLOCKING] Before each step or sub-skill call, update task tracking: set in_progress when step starts, set completed when step ends.
[BLOCKING] Every completed/skipped step MUST include brief evidence or explicit skip reason.
[BLOCKING] If Task tools are unavailable, create and maintain an equivalent step-by-step plan tracker with the same status transitions.
Quick Summary
Goal: Analyze business domain (bounded contexts, aggregates, entities, VOs, domain events, cross-context relationships) and generate a domain model report + ERD — producing a user-validated DDD domain model with correct bounded contexts, aggregate boundaries, and event flows so downstream implementation builds on the right invariants and avoids costly boundary rework after consumers depend on them.
Summary:
- Purpose: turn business artifacts into a user-validated DDD domain model (bounded contexts, aggregates, entities, VOs, domain events, ERD) so downstream code builds on correct invariants — never re-cut boundaries after consumers depend on them.
- Ten ordered steps (do all, none skippable): 0 locate active plan +
domain-entities-reference.md → 1 load business context (nouns→entities, verbs→events) → 2 identify bounded contexts → 3 model entities & aggregates → 4 map relationships → 5 domain events → 6 generate Mermaid ERD → 7 user-validation interview → 8 entity-change assessment vs reference doc → 9 update plan.md ## Domain Model.
- Drive the model from business artifacts, not guesses: load plan/PBI/business-eval inputs and
domain-entities-reference.md, then extract nouns→entities, verbs→events, roles, and processes before classifying anything.
- Every concept passes the Entity-vs-VO matrix and aggregate boundary rules (≤5 entities, one transaction, reference-by-ID only, root is the sole mutation entry) — flag primitive obsession and anemic models as you go.
- User validation is non-skippable: present bounded contexts and the Mermaid ERD, then run the 5-8 question ask the user directly interview to confirm boundaries, aggregate roots, and event flows before marking the model confirmed.
- Close the loop on persistence: reconcile findings against
domain-entities-reference.md (new/modified/deprecated), update the ## Domain Model section of plan.md, and keep cross-context communication event-driven with {AggregateNoun}{PastTenseVerb} naming and no cross-service FKs.
Workflow:
- Locate Active Plan & Domain Reference — Glob
plans/*/plan.md, read plan + prior research + domain-entities-reference.md; set {plan-dir}
- Load Business Context — Read idea, business evaluation, refined PBI artifacts; extract nouns→entities, verbs→events, roles, processes
- Identify Bounded Contexts — Group related concepts, define context boundaries (validate grouping with user)
- Model Entities & Aggregates — Define aggregates, entities, value objects per context
- Map Relationships — Entity relationships, cross-context integration points (context map)
- Domain Events — Identify events crossing context boundaries,
{AggregateNoun}{PastTenseVerb}
- Generate ERD — Mermaid ER diagram with all entities and relationships
- User Validation — Present model, ask 5-8 questions, confirm decisions →
status: confirmed
- Domain Entity Change Assessment — Compare against
domain-entities-reference.md, update/create if needed
- Update Main Plan — Append/update
## Domain Model section of {plan-dir}/plan.md
Key Rules:
- MANDATORY IMPORTANT MUST ATTENTION validate every bounded context boundary with user
- MANDATORY IMPORTANT MUST ATTENTION include Mermaid ERD diagram in report
- MANDATORY IMPORTANT MUST ATTENTION run user validation interview at end (NEVER skip)
- Every entity belongs to exactly one bounded context
- Cross-context communication via domain events only — NEVER direct references
Be skeptical. Every claim needs traced proof, confidence percentages >80% to act.
DDD Reference: Strategic Design
Bounded Context Rules
| Signal |
Action |
| Same term, different meaning across teams |
Separate bounded contexts |
| Different data lifecycles for same concept |
Separate contexts |
| Different invariants on same entity |
Separate contexts |
| Team ownership conflict (Conway's Law) |
Separate contexts |
| Shared DB table touched by two services |
Extract shared kernel or introduce ACL |
Ubiquitous Language Rules:
- Every noun in codebase matches domain expert vocabulary exactly (not "User" when the domain says "Customer")
- Class/method/variable names reflect ubiquitous language — zero translation layers inside bounded context
- Developers say "we call it X but domain means Y" → model is wrong, fix it
Context Map Pattern Decision Table
| Situation |
Pattern |
| Two teams, joint success/failure, equal power |
Partnership |
| Small shared code nucleus, joint governance acceptable |
Shared Kernel |
| Downstream can influence upstream roadmap |
Customer-Supplier |
| Downstream has no influence on upstream |
Conformist |
| External/legacy system with hostile or polluting model |
Anti-Corruption Layer (ACL) |
| One upstream, many downstream consumers |
Open Host Service + Published Language |
| Integration cost exceeds integration value |
Separate Ways |
ACL — when to use: Upstream is external/legacy/third-party (Salesforce, SAP, Workday). Upstream types NEVER cross ACL into domain model.
Shared Kernel — when NOT to use: Teams cannot coordinate on every change → use Customer-Supplier + Published Language instead.
DDD Reference: Entity vs Value Object
Decision Matrix
| Question |
Entity |
Value Object |
| Has identity beyond its attributes? |
YES |
no |
| Can two instances with same data be distinct? |
YES |
no |
| Has a lifecycle (created, modified, deleted)? |
YES |
no |
| Identified by an ID in any downstream system? |
YES |
no |
| Measured or described (quantity, address, money)? |
no |
YES |
| Replaced rather than modified on change? |
no |
YES |
| Must be found independently of parent? |
YES |
no |
Fast heuristics:
- Replace with equal-valued copy → breaks nothing? → Value Object
- Must be tracked across time or fetched by ID? → Entity
- Always retrieved as part of another object? → likely Value Object
- Two instances with same data are interchangeable? → Value Object
Canonical Value Objects
| VO |
Attributes |
Key Invariants |
Money |
amount: Decimal, currency: Currency |
amount ≥ 0, valid ISO currency; Add/Subtract require same currency |
Email |
value: string |
RFC 5322 format, normalized to lowercase |
Address |
street, city, country, postalCode |
All fields non-empty; composed of Country + PostalCode VOs |
DateRange |
start: DateOnly, end: DateOnly |
start ≤ end; operations: Contains, Overlaps, Duration |
PhoneNumber |
countryCode, number |
E.164 format |
Percentage |
value: int |
0 ≤ value ≤ 100 |
Primitive Obsession → Value Object Mapping
| Primitive Usage |
Replace With |
string orderId |
OrderId typed wrapper |
decimal amount, string currency |
Money { amount, currency } |
string street, string city, string zip |
Address { ... } |
DateTime start, DateTime end |
DateRange { start, end } |
string email |
Email { value } |
int percentage |
Percentage { value } |
string phoneNumber |
PhoneNumber { countryCode, number } |
Rule: Primitive with validation rules, formatting, or always passed grouped with other primitives → missing Value Object.
Value Object Construction Pattern
A VO is self-validating: invariants enforced at construction via a factory (no public constructor that can produce an invalid instance), immutable, and equality-by-value. The base class and factory names below are one illustrative instantiation — translate to your language's equivalents.
Example (illustrative — adapt to your language):
// Self-validating VO — never an invalid instance in memory
public sealed class Email : ValueObject<Email>
{
private Email(string value) { Value = value; }
public string Value { get; }
public static Email Of(string raw)
{
var normalized = raw?.Trim().ToLowerInvariant();
if (string.IsNullOrWhiteSpace(normalized) || !IsValidFormat(normalized))
throw new DomainException($"Invalid email: {raw}");
return new Email(normalized);
}
}
Rules:
- No public constructor without validation — factory method (
Of() / Create()) enforces invariants
- VOs can reference other VOs; VOs NEVER reference entities (lifecycle coupling)
- Mutation means replacement:
email = Email.Of(newValue), NEVER email.Value = newValue
VO Persistence Strategies
| Strategy |
When to Use |
Trade-offs |
| Owned types (EF Core) |
VO maps to same table as owning entity |
Simple, no FK, nullable columns possible |
| Embedded document store |
VO stored as subdocument |
Natural fit, no joins |
| JSON column |
Complex VO, low query frequency on VO fields |
Flexible, not queryable by parts |
| Serialized string |
Simple VOs (Email, PostalCode) |
Compact, unqueryable by parts |
Rule: VOs NEVER have own table with primary key — that makes them entities by infrastructure.
DDD Reference: Entity Design
Identity Strategies
| Strategy |
When to Use |
Trade-offs |
| ULID (default) |
New entities in distributed system |
Sortable, URL-safe, monotonic, 128-bit |
| UUID v4 |
True randomness / security-sensitive IDs |
Not sortable, fragmented indexes |
| UUID v7 |
Sortable UUID needed |
Time-ordered, good index locality |
| Natural key |
Domain guarantees permanent uniqueness (SSN, EAN) |
Unstable — domain can change |
| Surrogate int |
Legacy/single-DB sequences |
No distributed generation |
| Composite key |
Relationship/join table |
Harder to reference from other aggregates |
Rules:
- Prefer ULID for new entities — sortable, no coordination overhead
- NEVER use email/username as PK — users change them
- Cross-service references use same ID type as the owning service
Rich vs Anemic Domain Model
| Anemic (Anti-Pattern) |
Rich (Correct) |
| Entity is data bag, logic in services |
Entity contains behavior + invariants |
public set on all properties |
Private setters, mutation via named methods |
OrderService.Confirm(order) |
order.Confirm() |
| Service checks rules then mutates entity |
Entity refuses invalid state transitions |
| Logic duplicated across services |
Single authoritative location in entity |
Tell Don't Ask Principle:
- BAD:
if (order.Status == Confirmed) { order.Status = OnHold; } (external ask + mutate)
- GOOD:
order.Hold(reason) (entity enforces its own invariants)
Entity Invariant Enforcement
A rich entity guards its own state: a private constructor reserved for ORM/persistence hydration, named factory methods for valid creation, and intent-named mutation methods that reject invalid transitions and emit domain events. The base class, guard helper, and ID generator below are one illustrative instantiation — substitute your language's equivalents.
Example (illustrative — adapt to your language):
public class Order : AuditedAggregateRoot<Order, string>
{
private Order() { } // ORM hydration only
public static Order Create(string name, Email email, WarehouseId warehouseId)
{
Guard.NotNullOrWhitespace(name, nameof(name));
Guard.NotNull(email, nameof(email));
return new Order
{
Id = Ulid.NewUlid().ToString(),
Name = name,
Email = email,
WarehouseId = warehouseId,
Status = OrderStatus.Confirmed
};
}
public void Cancel(string reason, DateOnly cancellationDate)
{
if (Status == OrderStatus.Cancelled)
throw new DomainException("Order already cancelled");
if (cancellationDate < DateOnly.FromDateTime(DateTime.UtcNow))
throw new DomainException("Cancellation date cannot be in the past");
Status = OrderStatus.Cancelled;
CancellationReason = reason;
CancellationDate = cancellationDate;
AddDomainEvent(new OrderCancelledDomainEvent(Id, cancellationDate));
}
}
Entity Lifecycle State Machines
Document ALL transitions explicitly. Unmodeled transitions throw DomainException.
Draft → Submitted (Submit())
Submitted → Approved (Approve(approverId))
Submitted → Rejected (Reject(reason))
Approved → Active (Activate())
Active → Suspended (Suspend(reason))
Suspended → Active (Reinstate())
Active → Archived (Archive())
| Pattern |
When to Use |
| Status enum + transition methods |
Simple linear/branching lifecycles (most cases) |
| State pattern (class per state) |
Complex per-state behavior, many states |
| Event sourcing |
Full audit trail + point-in-time reconstruction required |
Domain Validation Layers
| Layer |
What It Validates |
Failure Signal (per stack) |
| Value Object |
Single-value format/range invariants |
Construction failure (raised error or result type) |
| Entity method |
Aggregate consistency rules, state transitions |
Domain rule violation (e.g. DomainException) |
| Application service |
Cross-aggregate rules, authorization, existence |
Structured validation result (e.g. ValidationResult / problem-details payload) |
| Infrastructure |
DB constraints (last resort, NEVER first line) |
Persistence-layer error (last-resort constraint) |
Decision rule:
- Rule requires loading another aggregate? → Application service
- Rule needs only data within aggregate? → Entity method
- Rule concerns single value's format? → Value Object constructor
Factory Methods on Entities
Use when: construction requires domain logic, multiple paths, raises domain events, or object graph initialization.
Naming:
Order.Create(...) — primary creation
Order.Place(...) — semantically loaded creation (domain language)
- Private constructor — ORM hydration only, NEVER called directly
Temporal (Bi-Temporal) Entities
Two time axes: valid time (fact true in real world) + transaction time (recorded in system).
ProductPrice {
validFrom: DateOnly // valid time: price effective from
validTo: DateOnly // valid time: price effective until
recordedAt: DateTime // transaction time: when entered into system
}
Use when: regulatory compliance, retroactive corrections, "as-of" queries.
DDD Reference: Aggregate Design
Aggregate Boundary Rules
- Invariant scope — boundary = objects needed to enforce invariants atomically
- Transaction boundary — exactly one database transaction per aggregate operation
- Consistency scope — must be consistent atomically? same aggregate. Eventual consistency acceptable? separate aggregates
- Small aggregates preferred — fewer members = fewer transaction conflicts = better scalability
Aggregate Size Heuristics
| Heuristic |
Guideline |
| Default |
Start with single-entity aggregate unless invariant demands more |
| Add member |
Only when invariant requires atomic consistency across root + member |
| Max size |
> 5 entities → redesign; likely missing sub-aggregates |
| Concurrent writes conflict |
Reduce aggregate size |
Aggregate Root Responsibilities
- Maintain all invariants across all members
- All mutation paths go through root (child entities NEVER directly accessible from outside)
- Emit domain events for significant state changes
- Control creation of child entities (factory methods on root)
- Assign IDs to child entities
Rule: Outside code NEVER holds direct reference to non-root entity within aggregate.
Cross-Aggregate References
| Rule |
Detail |
| Reference by ID only |
NEVER order.Customer.Name — load separately |
| No FK object navigation |
CustomerId field, NEVER Customer Customer navigation property |
| Cross-aggregate transactions are eventual |
Need them in same transaction → boundaries are wrong |
| Deletion cascade |
Domain event → handler → compensating action in other aggregate |
Aggregate Invariant Enforcement
All mutation flows through the aggregate root, which checks every invariant before applying a change and recomputes derived state so no member can be left inconsistent. The throw-on-violation idiom below is one illustrative instantiation — your language may surface invariant breaches differently (exceptions, result types).
Example (illustrative — adapt to your language):
public void AddLineItem(ProductId productId, int quantity, Money unitPrice)
{
if (Status != OrderStatus.Draft)
throw new DomainException("Cannot modify confirmed order");
if (LineItems.Count >= 50)
throw new DomainException("Order cannot exceed 50 line items");
var item = OrderLineItem.Create(productId, quantity, unitPrice);
_lineItems.Add(item);
RecalculateTotal(); // invariant: Total == sum(lineItems)
}
Aggregate Design Patterns
| Pattern |
When to Use |
| Single-entity aggregate |
Default — most entities are their own aggregate |
| Nested aggregate |
Invariant requires atomic consistency across root + children |
| Aggregate with VOs |
Root + embedded value objects (no IDs, no own table) |
When to Break Aggregate Rules (Pragmatic DDD)
| Situation |
Acceptable Pragmatism |
| ORM limitation (EF owned entities) |
Allow private owned collections even if not strictly necessary |
| Performance — 1-query load |
Embed child data as VO/owned type rather than separate aggregate |
| Legacy schema migration |
Accept cross-aggregate FK temporarily, document as debt |
Rule: Breaking aggregate rules acceptable ONLY when explicitly documented as technical debt with mitigation plan.
DDD Reference: ERD Design
Cardinality Types
| Cardinality |
Mermaid |
When to Use |
| 1:1 |
|o--o| |
Same-table extension, optional sub-type, shared lifecycle |
| 1:N |
|o--{ |
Parent-child, one entity owns many dependent records |
| M:N |
}o--o{ |
Peer relationship; ALWAYS use explicit join/association entity |
M:N rule: Relationship has attributes (date joined, role) → make join table explicit named entity.
1:1 decision: Same concept with optional attributes → same table. Different concepts with independent lifecycles → separate tables with FK.
Normalization Targets
| Normal Form |
Rule |
Use For |
| 1NF |
Atomic values, no repeating groups |
Always — baseline |
| 2NF |
No partial dependency on composite key |
Composite PKs only |
| 3NF |
No transitive dependencies |
OLTP — standard target |
| BCNF |
Every determinant is a candidate key |
When 3NF still has anomalies |
| Denormalized |
Intentional redundancy |
Read models, projections, OLAP |
Rule: 3NF for OLTP write models; denormalize only in read models/projections with documented justification.
Identifying vs Non-Identifying Relationships
| Type |
FK in Child PK? |
Child Existence |
| Identifying |
YES (FK is part of PK) |
Child cannot exist without parent (line item without order) |
| Non-identifying |
NO (FK is separate column) |
Child can exist independently (order without warehouse) |
Mapping to DDD: Identifying relationship → child entity inside parent aggregate. Non-identifying FK → likely separate aggregates.
ERD for Microservices
- Each bounded context has its OWN ERD — NEVER cross-service entity arrows
- Cross-service references shown as
ExternalEntityId (string/ULID) — ID only, no relationship line
- Shared data shown as replicated/synced data note, NEVER shared table
- Event-sourced aggregates: ERD shows current state projection, not event stream
ERD Anti-Patterns
| Anti-Pattern |
Problem |
Fix |
| God table (50+ columns) |
Every feature adds more columns |
Extract sub-entities, decompose by bounded context |
| Cross-service FK |
Direct FK across microservice schemas |
Replicate needed data, use events to sync |
| Polymorphic association |
entityType + entityId columns |
Separate tables per concrete type or JSON column |
| EAV (Entity-Attribute-Value) |
Key-value rows replacing typed columns |
JSON column or explicit schema with migration |
| Implicit M:N (two FK cols, no PK) |
Hard to add relationship attributes |
Explicit join table with surrogate PK |
| Nullable FK everywhere |
Unclear cardinality |
Separate optional relationship into explicit table |
ERD to Aggregate Mapping
| ERD Pattern |
DDD Mapping |
| Parent-child with identifying relationship |
Child entity inside parent aggregate |
| Parent-child with non-identifying FK |
Likely separate aggregates (independent lifecycle) |
| M:N join table with no extra attributes |
Both sides separate aggregates, IDs in domain events |
| M:N join table with attributes |
Association entity as separate aggregate |
| Strong entity + many weak dependents |
Root entity + owned collection aggregate |
DDD Reference: Domain Events
Event Naming Conventions
Format: {AggregateNoun}{PastTenseVerb} — what happened, not what to do.
| Good |
Bad |
OrderCancelled |
CancelOrder (command naming) |
OrderConfirmed |
OrderStatusChanged (too generic) |
PaymentProcessed |
PaymentComplete (not past tense) |
SalaryBandUpdated |
SalaryChanged (vague) |
Event Payload Design Rules
| Decision |
Rule |
| Minimal vs fat |
Minimal (default): AggregateId + what changed. Consumer queries for rest if needed |
| Fat event |
Accept when: round-trip cost high AND consumers known AND staleness acceptable |
| Required fields always |
AggregateId, OccurredOn (UTC timestamp), Version, CorrelationId |
| No mutable references |
Payload contains value copies, not object references |
Domain Events vs Integration Events
| Dimension |
Domain Event |
Integration Event |
| Scope |
Within one bounded context |
Across bounded contexts |
| Delivery |
In-process, post-commit |
Via configured message bus or event stream |
| Schema ownership |
Domain owns, internal |
Published Language contract |
| Versioning |
Internal refactor freely |
Versioned, backward-compatible |
| Failure handling |
Transaction rollback |
At-least-once delivery, idempotent consumer |
Rule: Domain event raised → in-process handlers fire → if cross-service needed, handler publishes integration event to message bus.
Event Versioning Strategies
| Strategy |
Mechanism |
Trade-offs |
| Additive only |
NEVER remove/rename fields, only add |
Simple, payload bloats over time |
| Multiple versions |
OrderConfirmedV1, OrderConfirmedV2 |
Clear versioning, consumers handle both |
| Upcasting |
Transform old events to new on deserialization |
Transparent to consumers, complex infra |
Backward compatibility rules:
- Adding optional field → backward compatible
- Removing or renaming field → breaking
- Changing field type → breaking
DDD Reference: Repository Pattern
Interface Design Principles
- One repository per aggregate root — NEVER one for child entities
- Domain language in methods —
GetConfirmedOrdersInWarehouse() not FindAll(e => e.Status == Active)
- Return domain objects — repositories return entities, not DTOs
- No infrastructure concerns — no leaked query/ORM types or connection strings in the interface.
- Async-first — methods return the configured runtime's async primitive.
Repository vs DAO
| Repository |
DAO |
| Domain-oriented interface |
Data-oriented interface |
| Returns entities/VOs |
Returns DTOs or raw data |
| Used in application/domain layer |
Used in infrastructure layer |
| Hides persistence mechanism |
Often tied to persistence mechanism |
Query Objects — When to Use Specification
Use when: rule used in multiple places, warrants naming + testing, needs composition.
A specification names a query predicate as a reusable, composable, testable unit owned by the domain. The expression-tree form below is one illustrative instantiation — your language may model it as a predicate function, query builder, or specification object.
Example (illustrative — adapt to your language):
// Static expression on entity — composable, testable
public static Expression<Func<Order, bool>> ByWarehouseExpression(string warehouseId)
=> o => o.WarehouseId == warehouseId && o.Status == OrderStatus.Confirmed;
When NOT to use Specification: Simple single-use predicate → inline lambda. Rule only used once → repository method directly.
DDD Reference: Anti-Patterns Quick Reference
| Anti-Pattern |
Detection Signal |
Fix |
| Anemic domain model |
Services have entity-specific logic; entity has all public setters |
Move logic to entity |
| God aggregate |
Aggregate > 5 entities or 100+ ms load time |
Extract sub-aggregates |
| Leaky aggregate |
External code mutates child entities directly |
Private setters + root mutation methods |
| Primitive obsession |
3+ primitives always travel together as group |
Introduce Value Object |
| Implicit concept |
Domain expert names it, code doesn't model it |
Explicit class |
| Feature envy |
Method uses more of B's data than A's |
Move method to B |
| Getter/setter entity |
All mutation via property assignment, no intent-named methods |
Replace with Cancel(), Approve(), etc. |
| Cross-aggregate loading |
Full aggregate loaded just to read one field |
Pass scalar; resolve in app service |
| Side effects in handler |
Command handler calls multiple services after save |
Domain event + separate handlers |
| Cross-service FK |
Database FK across microservice schemas |
ID reference + event-driven sync |
| Shared Kernel overuse |
Two teams, one shared model, constant coordination overhead |
Split to Customer-Supplier |
| Missing ACL |
External model types bleed into domain classes |
ACL at integration boundary |
Skill Workflow
Step 0: Locate Active Plan & Domain Reference (MANDATORY)
- Glob
plans/*/plan.md sorted by modification time — find active plan directory
- Read
plan.md — project scope, goals, prior decisions
- Read all
{plan-dir}/research/*.md — avoid duplicating prior work
- Read
docs/project-reference/domain-entities-reference.md (if exists) — project's single source of truth for domain entities
- Set
{plan-dir} variable — all outputs write to this directory
If no plan directory, create using naming convention from session context.
MUST ATTENTION update {plan-dir}/plan.md with domain model summary section after completing analysis.
Step 1: Load Business Context
Read artifacts from prior workflow steps (search plans/ + team-artifacts/):
- Active plan (
{plan-dir}/plan.md) — scope, goals, constraints
- Business evaluation report — value proposition, customer segments
- Refined PBI — acceptance criteria, user stories, features
- Discovery interview notes — problem statement, user roles
Extract and list:
- Nouns — Candidate entities (user, order, product, etc.)
- Verbs — Candidate domain events (created, approved, assigned, etc.)
- Roles — User types with different permissions/views
- Processes — Business workflows (application flow, review cycle, etc.)
Step 2: Identify Bounded Contexts
Group related entities using DDD principles. Apply context boundary signals from reference table above.
### Bounded Context: {Name}
**Purpose:** {What this context owns — one sentence}
**Classification:** Core domain / Supporting / Generic
**Key Responsibility:** {primary business capability}
**Team ownership:** {suggested team or role}
**Ubiquitous language:** {key terms and their meaning in this context}
Context boundary tests:
- Same term used by two teams with different meanings? → separate contexts
- Two entities with same name but different invariants? → separate contexts
- Can this context be worked on without understanding the other? → good separation
MANDATORY IMPORTANT MUST ATTENTION present identified contexts to user by asking the user directly:
- "I identified {N} bounded contexts: {list}. Does this grouping make sense?"
- Options: Agree (Recommended) | Merge {X} and {Y} | Split {Z} | Add missing context
Step 3: Model Entities & Aggregates
Per bounded context: classify each concept using Entity vs VO matrix above, then apply aggregate boundary rules.
### {Context Name}
**Aggregate Root:** {EntityName}
**Identity:** {ULID / UUID / Natural key — justify}
**Lifecycle states:** {Draft → Active → Archived, etc.}
- **Child Entities:** {list — share aggregate boundary, identifying FK}
- **Value Objects:** {list — immutable, no identity, embedded}
- **Invariants:** {business rules this aggregate enforces atomically}
- **Factory method:** {Order.Create(...) / Order.Place(...)}
**Other Aggregates in this Context:**
- {Entity} — {purpose, identity strategy, lifecycle}
Entity Detail Template
| Entity |
Classification |
Identity |
Key Fields |
Lifecycle States |
Invariants |
…(truncated)
1---
2name: domain-analysis
3description: '[Architecture] Use when you need to analyze business domain: bounded contexts, aggregates, entities, ERD, domain events, and cross-context integration.'
4metadata:
5 source: https://skillmd.com/skills/duc01226/domain-analysis
6---
7
8> Codex compatibility note:
9>
10> - Invoke repository skills with `$skill-name` in Codex; this mirrored copy rewrites legacy Claude `/skill-name` references.
11> - Task tracker mandate: BEFORE executing any workflow or skill step, create/update task tracking for all steps and keep it synchronized as progress changes.
12> - User-question prompts mean to ask the user directly in Codex.
13> - Ignore Claude-specific mode-switch instructions when they appear.
14> - Strict execution contract: when a user explicitly invokes a skill, execute that skill protocol as written.
15> - Subagent authorization: when a skill is user-invoked or AI-detected and its protocol requires subagents, that skill activation authorizes use of the required `spawn_agent` subagent(s) for that task.
16> - Do not skip, reorder, or merge protocol steps unless the user explicitly approves the deviation first.
17> - For workflow skills, execute each listed child-skill step explicitly and report step-by-step evidence.
18> - If a required step/tool cannot run in this environment, stop and ask the user before adapting.
19
20<!-- CODEX:PROJECT-REFERENCE-LOADING:START -->
21
22## Codex Project-Reference Loading (No Hooks)
23
24Codex uses static project-reference loading instead of runtime-injected project docs.
25When coding, planning, debugging, testing, or reviewing, open project docs explicitly using this routing.
26
27**Always read:**
28
29- `docs/project-config.json` (project-specific paths, commands, modules, and workflow/test settings)
30- `docs/project-reference/docs-index-reference.md` (routes to the full `docs/project-reference/*` catalog)
31- `docs/project-reference/lessons.md` (always-on guardrails and anti-patterns)
32
33**Missing/stale context route:** If `docs/project-config.json`, the docs index, `lessons.md`, `CLAUDE.md`, `AGENTS.md`, or any task-required reference doc is missing or stale, auto-run `$project-init` or the narrow setup route (`$project-config`, `$docs-init`, `$scan-all`, `$scan --target=<key>`, `$claude-md-init`) before ordinary project-specific work. If Codex mirrors or `AGENTS.md` are missing/stale, ask the user to run `$sync-codex`; do not auto-run it.
34
35**Situation-based docs:**
36
37- Project structure/architecture/tech-stack/deployment/setup (any layer — backend, frontend, or infra): `project-structure-reference.md`
38- Backend/CQRS/API/domain/entity changes: `backend-patterns-reference.md`, `domain-entities-reference.md`
39- Frontend/UI/styling/design-system: `frontend-patterns-reference.md`, `scss-styling-guide.md`, `design-system/README.md`
40- Spec authoring, `docs/specs/` pathing, or TC format: `feature-spec-reference.md`, `spec-system-reference.md`, `spec-principles.md`
41- Behavior/public-contract changes or spec-test-code sync: `workflow-spec-test-code-cycle-reference.md` plus the spec docs above
42- Derived spec indexes/ERDs/reimplementation guides: `spec-system-reference.md` and source Feature Specs under `docs/specs/`
43- Integration test implementation/review: `integration-test-reference.md`
44- E2E test implementation/review: `e2e-test-reference.md`
45- Code review/audit work: `code-review-rules.md` plus domain docs above based on changed files
46
47Do not read all docs blindly. Start from `docs-index-reference.md`, then open only relevant files for the task.
48
49<!-- CODEX:PROJECT-REFERENCE-LOADING:END -->
50
51<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:START -->
52
53> **[BLOCKING]** Execute skill steps in declared order. NEVER skip, reorder, or merge steps without explicit user approval.
54> **[BLOCKING]** Before each step or sub-skill call, update task tracking: set `in_progress` when step starts, set `completed` when step ends.
55> **[BLOCKING]** Every completed/skipped step MUST include brief evidence or explicit skip reason.
56> **[BLOCKING]** If Task tools are unavailable, create and maintain an equivalent step-by-step plan tracker with the same status transitions.
57
58<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:END -->
59
60## Quick Summary
61
62**Goal:** Analyze business domain (bounded contexts, aggregates, entities, VOs, domain events, cross-context relationships) and generate a domain model report + ERD — producing a user-validated DDD domain model with correct bounded contexts, aggregate boundaries, and event flows so downstream implementation builds on the right invariants and avoids costly boundary rework after consumers depend on them.
63
64**Summary:**
65
66- **Purpose:** turn business artifacts into a user-validated DDD domain model (bounded contexts, aggregates, entities, VOs, domain events, ERD) so downstream code builds on correct invariants — never re-cut boundaries after consumers depend on them.
67- **Ten ordered steps (do all, none skippable):** 0 locate active plan + `domain-entities-reference.md` → 1 load business context (nouns→entities, verbs→events) → 2 identify bounded contexts → 3 model entities & aggregates → 4 map relationships → 5 domain events → 6 generate Mermaid ERD → 7 user-validation interview → 8 entity-change assessment vs reference doc → 9 update `plan.md` `## Domain Model`.
68- Drive the model from business artifacts, not guesses: load plan/PBI/business-eval inputs and `domain-entities-reference.md`, then extract nouns→entities, verbs→events, roles, and processes before classifying anything.
69- Every concept passes the Entity-vs-VO matrix and aggregate boundary rules (≤5 entities, one transaction, reference-by-ID only, root is the sole mutation entry) — flag primitive obsession and anemic models as you go.
70- User validation is non-skippable: present bounded contexts and the Mermaid ERD, then run the 5-8 question ask the user directly interview to confirm boundaries, aggregate roots, and event flows before marking the model confirmed.
71- Close the loop on persistence: reconcile findings against `domain-entities-reference.md` (new/modified/deprecated), update the `## Domain Model` section of `plan.md`, and keep cross-context communication event-driven with `{AggregateNoun}{PastTenseVerb}` naming and no cross-service FKs.
72
73**Workflow:**
74
750. **Locate Active Plan & Domain Reference** — Glob `plans/*/plan.md`, read plan + prior research + `domain-entities-reference.md`; set `{plan-dir}`
761. **Load Business Context** — Read idea, business evaluation, refined PBI artifacts; extract nouns→entities, verbs→events, roles, processes
772. **Identify Bounded Contexts** — Group related concepts, define context boundaries (validate grouping with user)
783. **Model Entities & Aggregates** — Define aggregates, entities, value objects per context
794. **Map Relationships** — Entity relationships, cross-context integration points (context map)
805. **Domain Events** — Identify events crossing context boundaries, `{AggregateNoun}{PastTenseVerb}`
816. **Generate ERD** — Mermaid ER diagram with all entities and relationships
827. **User Validation** — Present model, ask 5-8 questions, confirm decisions → `status: confirmed`
838. **Domain Entity Change Assessment** — Compare against `domain-entities-reference.md`, update/create if needed
849. **Update Main Plan** — Append/update `## Domain Model` section of `{plan-dir}/plan.md`
85
86**Key Rules:**
87
88- **MANDATORY IMPORTANT MUST ATTENTION** validate every bounded context boundary with user
89- **MANDATORY IMPORTANT MUST ATTENTION** include Mermaid ERD diagram in report
90- **MANDATORY IMPORTANT MUST ATTENTION** run user validation interview at end (NEVER skip)
91- Every entity belongs to exactly one bounded context
92- Cross-context communication via domain events only — NEVER direct references
93
94**Be skeptical. Every claim needs traced proof, confidence percentages >80% to act.**
95
96---
97
98## DDD Reference: Strategic Design
99
100### Bounded Context Rules
101
102| Signal | Action |
103| ------------------------------------------ | -------------------------------------- |
104| Same term, different meaning across teams | Separate bounded contexts |
105| Different data lifecycles for same concept | Separate contexts |
106| Different invariants on same entity | Separate contexts |
107| Team ownership conflict (Conway's Law) | Separate contexts |
108| Shared DB table touched by two services | Extract shared kernel or introduce ACL |
109
110**Ubiquitous Language Rules:**
111
112- Every noun in codebase matches domain expert vocabulary exactly (not "User" when the domain says "Customer")
113- Class/method/variable names reflect ubiquitous language — zero translation layers inside bounded context
114- Developers say "we call it X but domain means Y" → model is wrong, fix it
115
116### Context Map Pattern Decision Table
117
118| Situation | Pattern |
119| ------------------------------------------------------ | -------------------------------------- |
120| Two teams, joint success/failure, equal power | Partnership |
121| Small shared code nucleus, joint governance acceptable | Shared Kernel |
122| Downstream can influence upstream roadmap | Customer-Supplier |
123| Downstream has no influence on upstream | Conformist |
124| External/legacy system with hostile or polluting model | Anti-Corruption Layer (ACL) |
125| One upstream, many downstream consumers | Open Host Service + Published Language |
126| Integration cost exceeds integration value | Separate Ways |
127
128**ACL — when to use:** Upstream is external/legacy/third-party (Salesforce, SAP, Workday). Upstream types NEVER cross ACL into domain model.
129
130**Shared Kernel — when NOT to use:** Teams cannot coordinate on every change → use Customer-Supplier + Published Language instead.
131
132---
133
134## DDD Reference: Entity vs Value Object
135
136### Decision Matrix
137
138| Question | Entity | Value Object |
139| ------------------------------------------------- | ------ | ------------ |
140| Has identity beyond its attributes? | YES | no |
141| Can two instances with same data be distinct? | YES | no |
142| Has a lifecycle (created, modified, deleted)? | YES | no |
143| Identified by an ID in any downstream system? | YES | no |
144| Measured or described (quantity, address, money)? | no | YES |
145| Replaced rather than modified on change? | no | YES |
146| Must be found independently of parent? | YES | no |
147
148**Fast heuristics:**
149
150- Replace with equal-valued copy → breaks nothing? → **Value Object**
151- Must be tracked across time or fetched by ID? → **Entity**
152- Always retrieved as part of another object? → likely **Value Object**
153- Two instances with same data are interchangeable? → **Value Object**
154
155### Canonical Value Objects
156
157| VO | Attributes | Key Invariants |
158| ------------- | ----------------------------------- | ------------------------------------------------------------------ |
159| `Money` | amount: Decimal, currency: Currency | amount ≥ 0, valid ISO currency; Add/Subtract require same currency |
160| `Email` | value: string | RFC 5322 format, normalized to lowercase |
161| `Address` | street, city, country, postalCode | All fields non-empty; composed of Country + PostalCode VOs |
162| `DateRange` | start: DateOnly, end: DateOnly | start ≤ end; operations: Contains, Overlaps, Duration |
163| `PhoneNumber` | countryCode, number | E.164 format |
164| `Percentage` | value: int | 0 ≤ value ≤ 100 |
165
166### Primitive Obsession → Value Object Mapping
167
168| Primitive Usage | Replace With |
169| ---------------------------------------- | ------------------------------------- |
170| `string orderId` | `OrderId` typed wrapper |
171| `decimal amount, string currency` | `Money { amount, currency }` |
172| `string street, string city, string zip` | `Address { ... }` |
173| `DateTime start, DateTime end` | `DateRange { start, end }` |
174| `string email` | `Email { value }` |
175| `int percentage` | `Percentage { value }` |
176| `string phoneNumber` | `PhoneNumber { countryCode, number }` |
177
178**Rule:** Primitive with validation rules, formatting, or always passed grouped with other primitives → missing Value Object.
179
180### Value Object Construction Pattern
181
182A VO is self-validating: invariants enforced at construction via a factory (no public constructor that can produce an invalid instance), immutable, and equality-by-value. The base class and factory names below are one illustrative instantiation — translate to your language's equivalents.
183
184**Example (illustrative — adapt to your language):**
185
186```csharp
187// Self-validating VO — never an invalid instance in memory
188public sealed class Email : ValueObject<Email>
189{
190 private Email(string value) { Value = value; }
191 public string Value { get; }
192
193 public static Email Of(string raw)
194 {
195 var normalized = raw?.Trim().ToLowerInvariant();
196 if (string.IsNullOrWhiteSpace(normalized) || !IsValidFormat(normalized))
197 throw new DomainException($"Invalid email: {raw}");
198 return new Email(normalized);
199 }
200}
201```
202
203**Rules:**
204
205- No public constructor without validation — factory method (`Of()` / `Create()`) enforces invariants
206- VOs can reference other VOs; VOs NEVER reference entities (lifecycle coupling)
207- Mutation means replacement: `email = Email.Of(newValue)`, NEVER `email.Value = newValue`
208
209### VO Persistence Strategies
210
211| Strategy | When to Use | Trade-offs |
212| ----------------------- | -------------------------------------------- | ---------------------------------------- |
213| Owned types (EF Core) | VO maps to same table as owning entity | Simple, no FK, nullable columns possible |
214| Embedded document store | VO stored as subdocument | Natural fit, no joins |
215| JSON column | Complex VO, low query frequency on VO fields | Flexible, not queryable by parts |
216| Serialized string | Simple VOs (Email, PostalCode) | Compact, unqueryable by parts |
217
218**Rule:** VOs NEVER have own table with primary key — that makes them entities by infrastructure.
219
220---
221
222## DDD Reference: Entity Design
223
224### Identity Strategies
225
226| Strategy | When to Use | Trade-offs |
227| ------------------ | ------------------------------------------------- | ----------------------------------------- |
228| **ULID** (default) | New entities in distributed system | Sortable, URL-safe, monotonic, 128-bit |
229| **UUID v4** | True randomness / security-sensitive IDs | Not sortable, fragmented indexes |
230| **UUID v7** | Sortable UUID needed | Time-ordered, good index locality |
231| **Natural key** | Domain guarantees permanent uniqueness (SSN, EAN) | Unstable — domain can change |
232| **Surrogate int** | Legacy/single-DB sequences | No distributed generation |
233| **Composite key** | Relationship/join table | Harder to reference from other aggregates |
234
235**Rules:**
236
237- Prefer ULID for new entities — sortable, no coordination overhead
238- NEVER use email/username as PK — users change them
239- Cross-service references use same ID type as the owning service
240
241### Rich vs Anemic Domain Model
242
243| Anemic (Anti-Pattern) | Rich (Correct) |
244| ---------------------------------------- | ------------------------------------------- |
245| Entity is data bag, logic in services | Entity contains behavior + invariants |
246| `public set` on all properties | Private setters, mutation via named methods |
247| `OrderService.Confirm(order)` | `order.Confirm()` |
248| Service checks rules then mutates entity | Entity refuses invalid state transitions |
249| Logic duplicated across services | Single authoritative location in entity |
250
251**Tell Don't Ask Principle:**
252
253- BAD: `if (order.Status == Confirmed) { order.Status = OnHold; }` (external ask + mutate)
254- GOOD: `order.Hold(reason)` (entity enforces its own invariants)
255
256### Entity Invariant Enforcement
257
258A rich entity guards its own state: a private constructor reserved for ORM/persistence hydration, named factory methods for valid creation, and intent-named mutation methods that reject invalid transitions and emit domain events. The base class, guard helper, and ID generator below are one illustrative instantiation — substitute your language's equivalents.
259
260**Example (illustrative — adapt to your language):**
261
262```csharp
263public class Order : AuditedAggregateRoot<Order, string>
264{
265 private Order() { } // ORM hydration only
266
267 public static Order Create(string name, Email email, WarehouseId warehouseId)
268 {
269 Guard.NotNullOrWhitespace(name, nameof(name));
270 Guard.NotNull(email, nameof(email));
271 return new Order
272 {
273 Id = Ulid.NewUlid().ToString(),
274 Name = name,
275 Email = email,
276 WarehouseId = warehouseId,
277 Status = OrderStatus.Confirmed
278 };
279 }
280
281 public void Cancel(string reason, DateOnly cancellationDate)
282 {
283 if (Status == OrderStatus.Cancelled)
284 throw new DomainException("Order already cancelled");
285 if (cancellationDate < DateOnly.FromDateTime(DateTime.UtcNow))
286 throw new DomainException("Cancellation date cannot be in the past");
287
288 Status = OrderStatus.Cancelled;
289 CancellationReason = reason;
290 CancellationDate = cancellationDate;
291 AddDomainEvent(new OrderCancelledDomainEvent(Id, cancellationDate));
292 }
293}
294```
295
296### Entity Lifecycle State Machines
297
298Document ALL transitions explicitly. Unmodeled transitions throw `DomainException`.
299
300```
301Draft → Submitted (Submit())
302Submitted → Approved (Approve(approverId))
303Submitted → Rejected (Reject(reason))
304Approved → Active (Activate())
305Active → Suspended (Suspend(reason))
306Suspended → Active (Reinstate())
307Active → Archived (Archive())
308```
309
310| Pattern | When to Use |
311| -------------------------------- | -------------------------------------------------------- |
312| Status enum + transition methods | Simple linear/branching lifecycles (most cases) |
313| State pattern (class per state) | Complex per-state behavior, many states |
314| Event sourcing | Full audit trail + point-in-time reconstruction required |
315
316### Domain Validation Layers
317
318| Layer | What It Validates | Failure Signal (per stack) |
319| ----------------------- | ----------------------------------------------- | -------------------------------------------------------------------------------- |
320| **Value Object** | Single-value format/range invariants | Construction failure (raised error or result type) |
321| **Entity method** | Aggregate consistency rules, state transitions | Domain rule violation (e.g. `DomainException`) |
322| **Application service** | Cross-aggregate rules, authorization, existence | Structured validation result (e.g. `ValidationResult` / problem-details payload) |
323| **Infrastructure** | DB constraints (last resort, NEVER first line) | Persistence-layer error (last-resort constraint) |
324
325**Decision rule:**
326
327- Rule requires loading another aggregate? → Application service
328- Rule needs only data within aggregate? → Entity method
329- Rule concerns single value's format? → Value Object constructor
330
331### Factory Methods on Entities
332
333Use when: construction requires domain logic, multiple paths, raises domain events, or object graph initialization.
334
335**Naming:**
336
337- `Order.Create(...)` — primary creation
338- `Order.Place(...)` — semantically loaded creation (domain language)
339- Private constructor — ORM hydration only, NEVER called directly
340
341### Temporal (Bi-Temporal) Entities
342
343Two time axes: **valid time** (fact true in real world) + **transaction time** (recorded in system).
344
345```
346ProductPrice {
347 validFrom: DateOnly // valid time: price effective from
348 validTo: DateOnly // valid time: price effective until
349 recordedAt: DateTime // transaction time: when entered into system
350}
351```
352
353Use when: regulatory compliance, retroactive corrections, "as-of" queries.
354
355---
356
357## DDD Reference: Aggregate Design
358
359### Aggregate Boundary Rules
360
3611. **Invariant scope** — boundary = objects needed to enforce invariants atomically
3622. **Transaction boundary** — exactly one database transaction per aggregate operation
3633. **Consistency scope** — must be consistent atomically? same aggregate. Eventual consistency acceptable? separate aggregates
3644. **Small aggregates preferred** — fewer members = fewer transaction conflicts = better scalability
365
366### Aggregate Size Heuristics
367
368| Heuristic | Guideline |
369| -------------------------- | -------------------------------------------------------------------- |
370| Default | Start with single-entity aggregate unless invariant demands more |
371| Add member | Only when invariant requires atomic consistency across root + member |
372| Max size | > 5 entities → redesign; likely missing sub-aggregates |
373| Concurrent writes conflict | Reduce aggregate size |
374
375### Aggregate Root Responsibilities
376
3771. Maintain all invariants across all members
3782. All mutation paths go through root (child entities NEVER directly accessible from outside)
3793. Emit domain events for significant state changes
3804. Control creation of child entities (factory methods on root)
3815. Assign IDs to child entities
382
383**Rule:** Outside code NEVER holds direct reference to non-root entity within aggregate.
384
385### Cross-Aggregate References
386
387| Rule | Detail |
388| ----------------------------------------- | ----------------------------------------------------------------- |
389| Reference by ID only | NEVER `order.Customer.Name` — load separately |
390| No FK object navigation | `CustomerId` field, NEVER `Customer Customer` navigation property |
391| Cross-aggregate transactions are eventual | Need them in same transaction → boundaries are wrong |
392| Deletion cascade | Domain event → handler → compensating action in other aggregate |
393
394### Aggregate Invariant Enforcement
395
396All mutation flows through the aggregate root, which checks every invariant before applying a change and recomputes derived state so no member can be left inconsistent. The throw-on-violation idiom below is one illustrative instantiation — your language may surface invariant breaches differently (exceptions, result types).
397
398**Example (illustrative — adapt to your language):**
399
400```csharp
401public void AddLineItem(ProductId productId, int quantity, Money unitPrice)
402{
403 if (Status != OrderStatus.Draft)
404 throw new DomainException("Cannot modify confirmed order");
405 if (LineItems.Count >= 50)
406 throw new DomainException("Order cannot exceed 50 line items");
407
408 var item = OrderLineItem.Create(productId, quantity, unitPrice);
409 _lineItems.Add(item);
410 RecalculateTotal(); // invariant: Total == sum(lineItems)
411}
412```
413
414### Aggregate Design Patterns
415
416| Pattern | When to Use |
417| ----------------------- | ------------------------------------------------------------ |
418| Single-entity aggregate | Default — most entities are their own aggregate |
419| Nested aggregate | Invariant requires atomic consistency across root + children |
420| Aggregate with VOs | Root + embedded value objects (no IDs, no own table) |
421
422### When to Break Aggregate Rules (Pragmatic DDD)
423
424| Situation | Acceptable Pragmatism |
425| ---------------------------------- | ---------------------------------------------------------------- |
426| ORM limitation (EF owned entities) | Allow private owned collections even if not strictly necessary |
427| Performance — 1-query load | Embed child data as VO/owned type rather than separate aggregate |
428| Legacy schema migration | Accept cross-aggregate FK temporarily, document as debt |
429
430**Rule:** Breaking aggregate rules acceptable ONLY when explicitly documented as technical debt with mitigation plan.
431
432---
433
434## DDD Reference: ERD Design
435
436### Cardinality Types
437
438| Cardinality | Mermaid | When to Use |
439| ----------- | ---------- | -------------------------------------------------------------- |
440| 1:1 | `\|o--o\|` | Same-table extension, optional sub-type, shared lifecycle |
441| 1:N | `\|o--{` | Parent-child, one entity owns many dependent records |
442| M:N | `}o--o{` | Peer relationship; ALWAYS use explicit join/association entity |
443
444**M:N rule:** Relationship has attributes (date joined, role) → make join table explicit named entity.
445
446**1:1 decision:** Same concept with optional attributes → same table. Different concepts with independent lifecycles → separate tables with FK.
447
448### Normalization Targets
449
450| Normal Form | Rule | Use For |
451| ------------ | -------------------------------------- | ------------------------------ |
452| 1NF | Atomic values, no repeating groups | Always — baseline |
453| 2NF | No partial dependency on composite key | Composite PKs only |
454| 3NF | No transitive dependencies | OLTP — standard target |
455| BCNF | Every determinant is a candidate key | When 3NF still has anomalies |
456| Denormalized | Intentional redundancy | Read models, projections, OLAP |
457
458**Rule:** 3NF for OLTP write models; denormalize only in read models/projections with documented justification.
459
460### Identifying vs Non-Identifying Relationships
461
462| Type | FK in Child PK? | Child Existence |
463| --------------- | -------------------------- | ----------------------------------------------------------- |
464| Identifying | YES (FK is part of PK) | Child cannot exist without parent (line item without order) |
465| Non-identifying | NO (FK is separate column) | Child can exist independently (order without warehouse) |
466
467**Mapping to DDD:** Identifying relationship → child entity inside parent aggregate. Non-identifying FK → likely separate aggregates.
468
469### ERD for Microservices
470
471- Each bounded context has its OWN ERD — NEVER cross-service entity arrows
472- Cross-service references shown as `ExternalEntityId (string/ULID)` — ID only, no relationship line
473- Shared data shown as replicated/synced data note, NEVER shared table
474- Event-sourced aggregates: ERD shows current state projection, not event stream
475
476### ERD Anti-Patterns
477
478| Anti-Pattern | Problem | Fix |
479| --------------------------------- | -------------------------------------- | -------------------------------------------------- |
480| God table (50+ columns) | Every feature adds more columns | Extract sub-entities, decompose by bounded context |
481| Cross-service FK | Direct FK across microservice schemas | Replicate needed data, use events to sync |
482| Polymorphic association | `entityType + entityId` columns | Separate tables per concrete type or JSON column |
483| EAV (Entity-Attribute-Value) | Key-value rows replacing typed columns | JSON column or explicit schema with migration |
484| Implicit M:N (two FK cols, no PK) | Hard to add relationship attributes | Explicit join table with surrogate PK |
485| Nullable FK everywhere | Unclear cardinality | Separate optional relationship into explicit table |
486
487### ERD to Aggregate Mapping
488
489| ERD Pattern | DDD Mapping |
490| ------------------------------------------ | ---------------------------------------------------- |
491| Parent-child with identifying relationship | Child entity inside parent aggregate |
492| Parent-child with non-identifying FK | Likely separate aggregates (independent lifecycle) |
493| M:N join table with no extra attributes | Both sides separate aggregates, IDs in domain events |
494| M:N join table with attributes | Association entity as separate aggregate |
495| Strong entity + many weak dependents | Root entity + owned collection aggregate |
496
497---
498
499## DDD Reference: Domain Events
500
501### Event Naming Conventions
502
503**Format:** `{AggregateNoun}{PastTenseVerb}` — what happened, not what to do.
504
505| Good | Bad |
506| ------------------- | ---------------------------------- |
507| `OrderCancelled` | `CancelOrder` (command naming) |
508| `OrderConfirmed` | `OrderStatusChanged` (too generic) |
509| `PaymentProcessed` | `PaymentComplete` (not past tense) |
510| `SalaryBandUpdated` | `SalaryChanged` (vague) |
511
512### Event Payload Design Rules
513
514| Decision | Rule |
515| ---------------------- | -------------------------------------------------------------------------------------- |
516| Minimal vs fat | **Minimal (default):** AggregateId + what changed. Consumer queries for rest if needed |
517| Fat event | Accept when: round-trip cost high AND consumers known AND staleness acceptable |
518| Required fields always | `AggregateId`, `OccurredOn` (UTC timestamp), `Version`, `CorrelationId` |
519| No mutable references | Payload contains value copies, not object references |
520
521### Domain Events vs Integration Events
522
523| Dimension | Domain Event | Integration Event |
524| ---------------- | -------------------------- | ------------------------------------------- |
525| Scope | Within one bounded context | Across bounded contexts |
526| Delivery | In-process, post-commit | Via configured message bus or event stream |
527| Schema ownership | Domain owns, internal | Published Language contract |
528| Versioning | Internal refactor freely | Versioned, backward-compatible |
529| Failure handling | Transaction rollback | At-least-once delivery, idempotent consumer |
530
531**Rule:** Domain event raised → in-process handlers fire → if cross-service needed, handler publishes integration event to message bus.
532
533### Event Versioning Strategies
534
535| Strategy | Mechanism | Trade-offs |
536| ----------------- | ---------------------------------------------- | --------------------------------------- |
537| Additive only | NEVER remove/rename fields, only add | Simple, payload bloats over time |
538| Multiple versions | `OrderConfirmedV1`, `OrderConfirmedV2` | Clear versioning, consumers handle both |
539| Upcasting | Transform old events to new on deserialization | Transparent to consumers, complex infra |
540
541**Backward compatibility rules:**
542
543- Adding optional field → backward compatible
544- Removing or renaming field → breaking
545- Changing field type → breaking
546
547---
548
549## DDD Reference: Repository Pattern
550
551### Interface Design Principles
552
5531. One repository per aggregate root — NEVER one for child entities
5542. Domain language in methods — `GetConfirmedOrdersInWarehouse()` not `FindAll(e => e.Status == Active)`
5553. Return domain objects — repositories return entities, not DTOs
5564. No infrastructure concerns — no leaked query/ORM types or connection strings in the interface.
5575. Async-first — methods return the configured runtime's async primitive.
558
559### Repository vs DAO
560
561| Repository | DAO |
562| -------------------------------- | ----------------------------------- |
563| Domain-oriented interface | Data-oriented interface |
564| Returns entities/VOs | Returns DTOs or raw data |
565| Used in application/domain layer | Used in infrastructure layer |
566| Hides persistence mechanism | Often tied to persistence mechanism |
567
568### Query Objects — When to Use Specification
569
570Use when: rule used in multiple places, warrants naming + testing, needs composition.
571
572A specification names a query predicate as a reusable, composable, testable unit owned by the domain. The expression-tree form below is one illustrative instantiation — your language may model it as a predicate function, query builder, or specification object.
573
574**Example (illustrative — adapt to your language):**
575
576```csharp
577// Static expression on entity — composable, testable
578public static Expression<Func<Order, bool>> ByWarehouseExpression(string warehouseId)
579 => o => o.WarehouseId == warehouseId && o.Status == OrderStatus.Confirmed;
580```
581
582**When NOT to use Specification:** Simple single-use predicate → inline lambda. Rule only used once → repository method directly.
583
584---
585
586## DDD Reference: Anti-Patterns Quick Reference
587
588| Anti-Pattern | Detection Signal | Fix |
589| --------------------------- | ------------------------------------------------------------------ | ------------------------------------------ |
590| **Anemic domain model** | Services have entity-specific logic; entity has all public setters | Move logic to entity |
591| **God aggregate** | Aggregate > 5 entities or 100+ ms load time | Extract sub-aggregates |
592| **Leaky aggregate** | External code mutates child entities directly | Private setters + root mutation methods |
593| **Primitive obsession** | 3+ primitives always travel together as group | Introduce Value Object |
594| **Implicit concept** | Domain expert names it, code doesn't model it | Explicit class |
595| **Feature envy** | Method uses more of B's data than A's | Move method to B |
596| **Getter/setter entity** | All mutation via property assignment, no intent-named methods | Replace with `Cancel()`, `Approve()`, etc. |
597| **Cross-aggregate loading** | Full aggregate loaded just to read one field | Pass scalar; resolve in app service |
598| **Side effects in handler** | Command handler calls multiple services after save | Domain event + separate handlers |
599| **Cross-service FK** | Database FK across microservice schemas | ID reference + event-driven sync |
600| **Shared Kernel overuse** | Two teams, one shared model, constant coordination overhead | Split to Customer-Supplier |
601| **Missing ACL** | External model types bleed into domain classes | ACL at integration boundary |
602
603---
604
605## Skill Workflow
606
607### Step 0: Locate Active Plan & Domain Reference (MANDATORY)
608
6091. Glob `plans/*/plan.md` sorted by modification time — find active plan directory
6102. Read `plan.md` — project scope, goals, prior decisions
6113. Read all `{plan-dir}/research/*.md` — avoid duplicating prior work
6124. Read `docs/project-reference/domain-entities-reference.md` (if exists) — project's single source of truth for domain entities
6135. Set `{plan-dir}` variable — all outputs write to this directory
614
615If no plan directory, create using naming convention from session context.
616
617**MUST ATTENTION update `{plan-dir}/plan.md`** with domain model summary section after completing analysis.
618
619### Step 1: Load Business Context
620
621Read artifacts from prior workflow steps (search `plans/` + `team-artifacts/`):
622
623- Active plan (`{plan-dir}/plan.md`) — scope, goals, constraints
624- Business evaluation report — value proposition, customer segments
625- Refined PBI — acceptance criteria, user stories, features
626- Discovery interview notes — problem statement, user roles
627
628Extract and list:
629
630- **Nouns** — Candidate entities (user, order, product, etc.)
631- **Verbs** — Candidate domain events (created, approved, assigned, etc.)
632- **Roles** — User types with different permissions/views
633- **Processes** — Business workflows (application flow, review cycle, etc.)
634
635### Step 2: Identify Bounded Contexts
636
637Group related entities using DDD principles. Apply context boundary signals from reference table above.
638
639```markdown
640### Bounded Context: {Name}
641
642**Purpose:** {What this context owns — one sentence}
643**Classification:** Core domain / Supporting / Generic
644**Key Responsibility:** {primary business capability}
645**Team ownership:** {suggested team or role}
646**Ubiquitous language:** {key terms and their meaning in this context}
647```
648
649**Context boundary tests:**
650
651- Same term used by two teams with different meanings? → separate contexts
652- Two entities with same name but different invariants? → separate contexts
653- Can this context be worked on without understanding the other? → good separation
654
655**MANDATORY IMPORTANT MUST ATTENTION** present identified contexts to user by asking the user directly:
656
657- "I identified {N} bounded contexts: {list}. Does this grouping make sense?"
658- Options: Agree (Recommended) | Merge {X} and {Y} | Split {Z} | Add missing context
659
660### Step 3: Model Entities & Aggregates
661
662Per bounded context: classify each concept using Entity vs VO matrix above, then apply aggregate boundary rules.
663
664```markdown
665### {Context Name}
666
667**Aggregate Root:** {EntityName}
668**Identity:** {ULID / UUID / Natural key — justify}
669**Lifecycle states:** {Draft → Active → Archived, etc.}
670
671- **Child Entities:** {list — share aggregate boundary, identifying FK}
672- **Value Objects:** {list — immutable, no identity, embedded}
673- **Invariants:** {business rules this aggregate enforces atomically}
674- **Factory method:** {Order.Create(...) / Order.Place(...)}
675
676**Other Aggregates in this Context:**
677
678- {Entity} — {purpose, identity strategy, lifecycle}
679```
680
681### Entity Detail Template
682
683| Entity | Classification | Identity | Key Fields | Lifecycle States | Invariants |
684| ------ | -------------------------------------- | ----------------------- | ---------- | ---------------- | ---------------- |
685| {Name} | Aggregate Root / Entity / Value Object | ULID / UUID / Composite | {fields} | {states} | {business rules} |
686
687**VO Composition — MUST ATTENTION verify:**
688
689- 3+ primitives always travel together? → extract VO
690- String field has format rules? → extract VO (Email, PhoneNumber)
691- Numeric field has range rules? → extract VO (Percentage, Money)
692- Concept named by domain experts but not modeled? → make explicit class
693
694**Aggregate Boundary — MUST ATTENTION verify:**
695
696- All entities in aggregate enforced in one transaction?
697- Cross-aggregate references use ID only (no navigation properties)?
698- Aggregate root is sole entry point for ALL mutations?
699- Aggregate ≤ 5 entities? If not — justify or decompose
700
701### Step 4: Map Relationships
702
703#### Intra-Context Relationships
704
705```markdown
706| From | To | Type | Cardinality | Relationship Kind | Description |
707| ----- | ------- | ---- | ------------- | ----------------------- | ----------------------- |
708| Order | Product | M:N | via OrderLine | Non-identifying (assoc) | Orders contain products |
709```
710
711Apply identifying vs non-identifying rule:
712
713- Identifying relationship (child FK is part of PK) → child entity inside parent aggregate
714- Non-identifying FK → likely separate aggregates
715
716#### Cross-Context Integration (Context Map)
717
718```markdown
719| Upstream Context | Downstream Context | Pattern | Integration Point | Sync Mechanism |
720| ---------------- | ------------------ | ------- | ------------------ | -------------- |
721| Sales | Order | ACL | Cart becomes Order | Domain event |
722```
723
724Integration patterns to apply (see context map reference table above):
725
726- **Anti-Corruption Layer** — external/hostile upstream model
727- **Customer-Supplier** — downstream can negotiate with upstream
728- **Open Host Service** — one upstream, many consumers
729- **Conformist** — no negotiating power with upstream
730
731### Step 5: Domain Events
732
733Identify events crossing bounded context boundaries. Apply naming: `{AggregateNoun}{PastTenseVerb}`.
734
735| Event | Source Context | Target Context(s) | Payload (minimal) | Trigger |
736| ------------- | -------------- | ------------------ | ----------------------------- | ------------------ |
737| `OrderPlaced` | Sales | Order, Fulfillment | cartId, productId, placedDate | Checkout completed |
738
739**Event design — MUST ATTENTION verify:**
740
741- Name is past tense + includes aggregate noun?
742- Payload includes AggregateId, OccurredOn (UTC), Version?
743- Payload minimal — just what changed + correlation IDs?
744- Version field included for schema evolution?
745- Domain event vs integration event clearly classified?
746
747### Step 6: Generate ERD
748
749Produce Mermaid ER diagram. Apply ERD-to-Aggregate mapping + anti-patterns from reference above.
750
751````markdown
752```mermaid
753erDiagram
754 %% Bounded Context: {Name}
755 ENTITY_A ||--o{ ENTITY_B: "has many"
756 ENTITY_A {
757 string id PK
758 string name
759 string status
760 datetime createdAt
761 }
762 ENTITY_B {
763 string id PK
764 string entityAId FK
765 string externalServiceId "ID only - no FK across services"
766 string type
767 }
768```
769````
770
771**ERD requirements:**
772
773- Group entities by bounded context (use Mermaid comments `%% Context: ...`)
774- Show PK/FK fields and key business fields (not all fields)
775- Show cardinality (1:1, 1:N, M:N) using Crow's Foot notation
776- Cross-service references: string/ULID field with comment, no relationship line
777- Identify association entities for M:N relationships
778
779**ERD — MUST ATTENTION verify before finalizing:**
780
781- No God tables (>20 columns — consider decomposing)?
782- No cross-service FK arrows?
783- All M:N through explicit named join entity?
784- No nullable FK everywhere (clarify optional relationships)?
785
786### Step 7: User Validation Interview
787
788**MANDATORY IMPORTANT MUST ATTENTION** present domain model and ask 5-8 questions by asking the user directly:
789
790#### Required Questions
791
7921. **Context boundaries** — "Are these {N} bounded contexts correct? Any missing or misplaced?"
793 - Options: Correct (Recommended) | Need changes | Not sure, explain more
7942. **Aggregate roots** — "Is {Entity} the right aggregate root for {Context}? It controls {child entities}."
7953. **Entity vs VO** — "I modeled {concept} as a Value Object because it has no independent identity. Does that match the business model?"
7964. **Relationship verification** — "The {Entity A} to {Entity B} relationship is {type/cardinality}. Is that correct?"
7975. **Missing entities** — "Are there business concepts — workflows, roles, rules — I haven't captured as explicit domain objects?"
7986. **Event verification** — "When {event} happens, should {contexts} be notified? What data do they need?"
799
800#### Deep-Dive Questions (pick 2-3 based on complexity)
801
802- "Should {Entity} be a separate aggregate or part of {Aggregate}? [separating = eventual consistency between them]"
803- "Is {field} really a Value Object or does it need its own identity and lifecycle?"
804- "How does {process} work step-by-step? What state transitions are involved?"
805- "What happens when {edge case}? Which invariant prevents the bad state?"
806- "Which entities change most frequently under concurrent load? (impacts aggregate design)"
807- "Any concepts domain experts name that I haven't modeled explicitly?"
808
809After user confirms, update report with final decisions and mark as `status: confirmed`.
810
811### Step 8: Domain Entity Change Assessment (MANDATORY)
812
813**MANDATORY IMPORTANT MUST ATTENTION** compare domain analysis results against `docs/project-reference/domain-entities-reference.md` (if exists):
814
8151. **Identify new entities** — in analysis but not in reference doc
8162. **Identify modified entities** — changed fields, relationships, or bounded context assignment
8173. **Identify deprecated entities** — in reference doc but no longer needed by feature
8184. **Present changes to user** by asking the user directly:
819 - "Domain entity changes detected: {N} new, {N} modified, {N} deprecated. Proceed with updating domain-entities-reference.md?"
820 - Options: Approve all (Recommended) | Review each change | Skip update
821
822If `docs/project-reference/domain-entities-reference.md` does NOT exist, ask user:
823
824- "No domain-entities-reference.md found. Create it with all entities from this analysis?"
825- Options: Yes, create it (Recommended) | No, skip
826
827**After user confirms:** update/create `docs/project-reference/domain-entities-reference.md` following existing format. Append new entities to appropriate bounded context section. Update field lists + relationships for modified entities.
828
829### Step 9: Update Main Plan (MANDATORY)
830
831Read `{plan-dir}/plan.md`, append/update `## Domain Model` section:
832
833```markdown
834## Domain Model
835
836- **Bounded Contexts:** {N} — {list names with context map patterns between them}
837- **Total Entities:** {N} ({N} aggregates, {N} child entities, {N} value objects)
838- **Domain Events:** {N} cross-context events
839- **Key Aggregates:** {list with invariant summaries}
840- **Key Relationships:** {summary of critical relationships}
841- **ERD:** See `phase-01-domain-model.md`
842- **Full Analysis:** See `research/domain-analysis.md`
843```
844
845---
846
847## Output
848
849```
850{plan-dir}/research/domain-analysis.md # Full domain analysis report
851{plan-dir}/phase-01-domain-model.md # Confirmed domain model with ERD
852{plan-dir}/plan.md # Updated with domain model summary
853docs/project-reference/domain-entities-reference.md # Updated/created with new/modified entities
854```
855
856Report structure:
857
8581. Executive summary (bounded contexts + entity count + key decisions)
8592. Context map (bounded contexts with integration patterns)
8603. Per-context entity/aggregate detail with identity strategy and invariants
8614. Relationship tables (intra + cross-context, identifying vs non-identifying)
8625. Value Objects catalog (VO type, attributes, invariants)
8636. Domain events catalog (with payload design)
8647. Mermaid ERD diagram
8658. Anti-pattern warnings (any detected issues in model)
8669. Unresolved questions
867
868Report must be **≤250 lines**. Use tables over prose.
869
870---
871
872**MANDATORY IMPORTANT MUST ATTENTION** break work into small todo tasks using task tracking BEFORE starting.
873**MANDATORY IMPORTANT MUST ATTENTION** validate EVERY bounded context and key relationship with user by asking the user directly.
874**MANDATORY IMPORTANT MUST ATTENTION** include Mermaid ERD and confidence % for all architectural decisions.
875**MANDATORY IMPORTANT MUST ATTENTION** add a final review todo task to verify work quality.
876
877---
878
879## Next Steps
880
881**MANDATORY IMPORTANT MUST ATTENTION — NO EXCEPTIONS** after completing this skill, use ask the user directly to present these options:
882
883- **"$domain-entities-review (Recommended)"** — Review DDD quality of entities modeled/modified in this analysis (anemic model, VO classification, invariant enforcement, aggregate boundaries)
884- **"$tech-stack-research"** — Research tech stack based on domain model
885- **"$plan"** — If tech stack already decided and entity quality already reviewed
886- **"Skip, continue manually"** — user decides
887
888### Council escalation (always-offer, second prompt)
889
890After the existing `## Next Steps` prompt above resolves, present a **second**, independent ask the user directly call (do NOT merge into the first):
891
892- **"Skip council — proceed with model (Recommended)"** — Continue with the bounded contexts / aggregate boundaries as drawn. Recommended default.
893- **"Escalate to $llm-council"** — Run 11 sub-agent council (5 advisors + 5 reviewers + chairman). Best applied when bounded-context splits or aggregate boundaries are contested (multiple defensible cuts), the model touches >=3 services, or invariants span aggregates. DDD boundary decisions are hard to reverse once consumers depend on them. Cheaper alternatives: `$why-review`, `$plan-validate` (run these first if you haven't).
894
895---
896
897**MANDATORY IMPORTANT MUST ATTENTION** use task tracking to break ALL work into small tasks BEFORE starting.
898**MANDATORY IMPORTANT MUST ATTENTION** use ask the user directly at EVERY decision point — validate every bounded context and entity relationship with user.
899**MANDATORY IMPORTANT MUST ATTENTION** produce ERD diagram (Mermaid) and domain model report with confidence %.
900
901> **External Memory:** For complex or lengthy work (research, analysis, scan, review), write intermediate findings and final results to a report file in `plans/reports/` — prevents context loss and serves as deliverable.
902
903> **Evidence Gate:** MANDATORY IMPORTANT MUST ATTENTION — every claim, finding, and recommendation requires `file:line` proof or traced evidence with confidence percentage (>80% to act, <80% must verify first).
904
905---
906
907<!-- SYNC:ai-mistake-prevention -->
908
909> **AI Mistake Prevention** — Failure modes to avoid on every task:
910>
911> **Re-read files after context changes.** Context compaction, resume, or long-running work can make memory stale; verify current files before acting.
912> **Verify generated content against source evidence.** AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.
913> **Check downstream references before deleting or renaming.** Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.
914> **Trace the full impact chain after edits.** Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.
915> **Verify ALL affected outputs, not just the first.** One green check is not all green checks; validate every output surface the change can affect.
916> **Assume existing values are intentional — ask WHY before changing OR flagging one as a defect.** Before changing or reporting a constant, limit, flag, cutoff, wording, or pattern, read nearby context and history, the CALLER's ordering, and 2+ sibling call sites of the same convention. A doc stating WHAT without WHY is missing rationale, not proof of a missing guard.
917> **Surface ambiguity before acting — don't pick silently.** Multiple valid interpretations require an explicit question or stated assumption with risk.
918> **Assert the outcome your system owns, not the intermediate state your infrastructure owns.** When verifying async work, assert the final business state — never the delivery/retry bookkeeping held in shared infrastructure that any co-running process can write. Such a check passes when run alone and flakes the moment anything else shares that infrastructure.
919> **Keep shared guidance role-relevant.** Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
920
921<!-- /SYNC:ai-mistake-prevention -->
922
923<!-- SYNC:critical-thinking-mindset -->
924
925> **Critical Thinking Mindset** — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
926> **Anti-hallucination:** Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence root of all hallucination.
927
928<!-- /SYNC:critical-thinking-mindset -->
929
930<!-- SYNC:critical-thinking-mindset:reminder -->
931
932**MUST ATTENTION** apply critical + sequential thinking — every claim needs appropriate traced evidence (`file:line` for repo/code claims; source URL or artifact section for research, product, content, and docs claims); confidence >80% to act, <60% DO NOT recommend. Anti-hallucination: never present guess as fact, admit uncertainty freely, cross-reference independently, stay skeptical of own confidence.
933
934<!-- /SYNC:critical-thinking-mindset:reminder -->
935
936<!-- SYNC:ai-mistake-prevention:reminder -->
937
938**MUST ATTENTION** apply AI mistake prevention — verify generated content against evidence, trace downstream references before deleting or renaming, verify all affected outputs, re-read files after context loss, and surface ambiguity before acting.
939
940<!-- /SYNC:ai-mistake-prevention:reminder -->
941
942<!-- PROMPT-ENHANCE:STEP-TASK-CLOSING:START -->
943
944## Prompt-Enhance Closing Anchors
945
946**IMPORTANT MUST ATTENTION** follow declared step order for this skill; NEVER skip, reorder, or merge steps without explicit user approval
947**IMPORTANT MUST ATTENTION** for every step/sub-skill call: set `in_progress` before execution, set `completed` after execution
948**IMPORTANT MUST ATTENTION** every skipped step MUST include explicit reason; every completed step MUST include concise evidence
949**IMPORTANT MUST ATTENTION** if Task tools unavailable, maintain an equivalent step-by-step plan tracker with synchronized statuses
950
951<!-- PROMPT-ENHANCE:STEP-TASK-CLOSING:END -->
952
953<!-- SYNC:project-protocol-overlay -->
954
955> **Project Protocol Overlay** — Before executing this skill, resolve any PROJECT overlay rules layered onto it: match this skill's name against the `Target` column of the project's skill-protocol index (`docs/project-reference/skill-protocols-reference.md` by default; a `referenceDocs` entry in `docs/project-config.json` overrides the path), taking the most specific matching tier ONLY — exact name > glob > `*`. **That precedence orders overlays against EACH OTHER, never against this skill.** Read ONLY the matched bodies, resolved as `<protocols-dir>/<Name>.md`; a row's Body link is display text, never a read path. A matched body that is missing or malformed is REPORTED and skipped — never reconstructed from the index Description. No index, or no match -> proceed with no overlay, silently. Full contract: `.claude/skills/project-skill-protocol/references/registry.md`.
956>
957> Overlays are **ADDITIVE ONLY**: they ADD rules on top of this skill's own protocol and NEVER replace, override, disable, or reinterpret a rule it already states — removing every overlay must return this skill to exactly its documented behavior. An overlay is a BRIEF, not an authority escalation: it can NEVER waive a workflow gate, git discipline, a review gate, or a user-confirmation gate. A genuine overlay-vs-skill conflict, or two equally-specific overlays that directly contradict -> surface both to the user; NEVER resolve silently.
958
959<!-- /SYNC:project-protocol-overlay -->
960
961<!-- SYNC:project-protocol-overlay:reminder -->
962
963**MUST ATTENTION** resolve project protocol overlays for this skill BEFORE executing — most specific matching tier only (exact > glob > `*`, which ranks overlays against each other, NEVER against this skill), read only matched bodies at `<protocols-dir>/<Name>.md`; a missing or malformed body is reported, never reconstructed. Overlays are ADDITIVE ONLY (they never replace this skill's own rules) and are a brief, NEVER an authority escalation; an equal-specificity contradiction goes to the user.
964
965<!-- /SYNC:project-protocol-overlay:reminder -->
966
967## Closing Reminders
968
969**IMPORTANT MUST ATTENTION Goal:** Produce a user-validated DDD domain model — correct bounded contexts, aggregate boundaries, and event flows — so downstream implementation builds on the right invariants and avoids costly boundary rework after consumers depend on them.
970
971**Protocols in force (concise digest of the SYNC/shared blocks this skill carries):**
972
973- **AI Mistake Prevention:** verify generated content against evidence, trace downstream references, verify all affected outputs, re-read after context loss, surface ambiguity.
974- **Critical Thinking:** Traced proof per claim; confidence >80% to act, NEVER guess as fact.
975
976**IMPORTANT MUST ATTENTION** run ALL ten ordered steps, none skippable: 0 locate plan + reference → 1 load context → 2 bounded contexts → 3 entities/aggregates → 4 relationships → 5 domain events → 6 Mermaid ERD → 7 user-validation interview → 8 entity-change assessment → 9 update `plan.md` — why: AI keeps dropping Step 0 (plan load) and Step 9 (plan update), leaving the model un-anchored and un-persisted.
977**IMPORTANT MUST ATTENTION** validate EVERY bounded context + key relationship with user by asking the user directly — NEVER auto-decide a boundary — why: DDD boundaries are hard to reverse once consumers depend on them; one wrong cut costs days of rework.
978**IMPORTANT MUST ATTENTION** domain events ALWAYS follow `{AggregateNoun}{PastTenseVerb}` naming — NEVER command-style (`CancelOrder`) or generic (`OrderStatusChanged`) — why: command/generic names hide what happened and break consumer routing.
979**IMPORTANT MUST ATTENTION** NEVER place cross-service FK in the ERD — use ID reference (`{Entity}Id` string/ULID) + event-driven sync only — why: cross-service FK couples schemas and blocks independent deployment.
980
981**MUST ATTENTION** task tracking ALL tasks BEFORE the first artifact read or write; mark one `in_progress`, complete immediately after evidence; on context loss the current task list first — why: compaction wipes prior-work memory, duplicated tasks waste budget.
982**MUST ATTENTION** load business artifacts FIRST (plan/PBI/business-eval + `domain-entities-reference.md`) and derive nouns→entities, verbs→events — NEVER model from guesses — why: a model built on assumptions encodes the wrong invariants.
983**MUST ATTENTION** search 3+ existing entities in `domain-entities-reference.md` before introducing a new one; reconcile new/modified/deprecated against it and follow its existing format — why: divergent or duplicated domain models fragment the source of truth.
984**MUST ATTENTION** evaluate fit before reusing a nearby aggregate/VO pattern — verify the new concept shares the same identity, lifecycle, and transaction scope — why: closest example ≠ matching preconditions.
985**MUST ATTENTION** entity vs VO classification — replace with equal-valued copy breaks nothing? → Value Object. Tracked across time or fetched by ID? → Entity. Flag primitive obsession (3+ primitives travel together) and anemic models as you go.
986**MUST ATTENTION** every aggregate passes boundary rules — ≤5 entities, one transaction, reference-by-ID only, root is the sole mutation entry; >5 entities → decompose or justify as documented debt.
987**MUST ATTENTION** include the Mermaid ERD and a confidence % (>80% to act, <80% verify first) for EVERY architectural decision; cite `file:line` / artifact evidence — NEVER present a boundary or classification as fact without traced proof.
988**MUST ATTENTION** persist intermediate findings to `plans/reports/` incrementally and add a final review task to verify work quality — why: long analysis hits context cutoffs; batched writes lose findings.
989
990**Anti-Rationalization:**
991
992| Evasion | Rebuttal |
993| ----------------------------------------------- | ---------------------------------------------------------------------------------------- |
994| "Boundaries are obvious, skip user validation" | User validation is non-skippable — run the 5-8 question ask the user directly interview. |
995| "Already know the entities, skip reference doc" | Show `file:line` from `domain-entities-reference.md`. No proof = not checked. |
996| "This concept is clearly an entity" | Run the Entity-vs-VO matrix anyway — state confidence %. Pattern-matching skips context. |
997| "Small model, skip task tracking" | Still task tracking first. Skip depth, never skip tracking. |
998| "Cross-service link is just one FK" | Never — ID reference + event-driven sync. One FK couples two schemas permanently. |
999
1000**[TASK-PLANNING]** Before acting, analyze task scope and systematically break it into small todo tasks and sub-tasks using task tracking.
1001
1002**IMPORTANT MUST ATTENTION** validate EVERY bounded context with the user, name domain events `{AggregateNoun}{PastTenseVerb}`, and keep cross-service links as ID-reference + events — these three are the most-skipped, highest-blast-radius rules of this skill.
1003
1004> **[IMPORTANT]** Analyze how big the task is and break it into many small todo tasks systematically before starting — this is very important.
1005
1006<!-- CODEX:SYNC-PROMPT-PROTOCOLS:START -->
1007
1008## Hookless Prompt Protocol Mirror (Auto-Synced)
1009
1010Source: `.claude/.ck.json` + `.claude/skills/shared/sync-inline-versions.md` (`:full` blocks) + `.claude/scripts/lib/hookless-prompt-protocol.cjs`
1011
1012## [WORKFLOW-EXECUTION-PROTOCOL] [BLOCKING] Workflow Execution Protocol — MANDATORY IMPORTANT MUST CRITICAL. Do not skip for any reason.
1013
1014**Generic portability boundary:** Reusable skills and protocol text stay project-neutral; project-specific conventions are discovered from docs/project-config.json and docs/project-reference/. Apply shared AI-SDD from `shared/sdd-artifact-contract.md`. Read `docs/project-config.json` and `docs/project-reference/docs-index-reference.md`, then open the project reference docs named there. For spec, test-case, behavior-change, public-contract, or `docs/specs/` work, route through the local spec docs named by the docs index: `feature-spec-reference.md`, `spec-system-reference.md`, `spec-principles.md`, and `workflow-spec-test-code-cycle-reference.md` when specs/tests/code must stay synchronized. If either file or a required reference doc is missing or stale, auto-run `$project-init` (or the narrow lower-level route such as `$project-config`, `$docs-init`, `$scan-all`, or `$scan --target=<key>`) before ordinary project-specific work. Any supported AI tool may execute when this shared context and local docs are available.
1015
10161. **DETECT:** If the prompt starts with an explicit slash skill/workflow command, execute it directly. Otherwise match the prompt against the workflow catalog and skill list.
10172. **ANALYZE:** Choose the best option: execute directly, invoke a skill, activate a standard workflow, or compose a custom step combination.
10183. **AUTO-SELECT:** Pick the best option yourself. Do not ask the user to choose between direct execution, skill, standard workflow, or custom workflow.
10194. **ACTIVATE:** For a selected workflow, call `$start-workflow <workflowId>`; for a selected skill, invoke that skill; for a custom workflow, sequence custom steps directly; for direct execution, proceed with the task.
10205. **CREATE TASKS:** task tracking for ALL workflow/skill/custom steps before execution when the selected path has multiple steps.
10216. **PARALLELIZE:** Before executing the task list, tag each task `PAR` (independent inputs + write set disjoint from every other `PAR` task) or `SEQ` (name the blocking dependency), group `PAR` tasks into waves, declare the wave plan, and spawn each wave's sub-agents in ONE message — all-return barrier per wave, fan-out one level deep unless a sub-agent's own definition authorizes further fan-out. Sequential-by-default is a defect when tasks are independent; do not parallelize shared write targets, output-consuming tasks, trivial single-file work, ordering a skill or workflow explicitly fixes, or user-approval gates.
10227. **EXECUTE:** Advance per the **Workflow Step Advancement & Parallel Phases** rule in your context instructions — model-driven; a sub-agent completion advances a step identically to an inline call; a parallel-phase group is an all-return barrier (advance only after ALL members return, never serialize it)
1023
1024## Shared AI-SDD Protocol Markers
1025
1026Source: `.claude/skills/shared/sync-inline-versions.md`
1027
1028## SYNC:ai-sdd-artifact-contract
1029
1030> **AI-SDD Artifact Contract** — Shared spec-driven development rules stay portable and source-owned.
1031>
1032> 1. Keep reusable AI-SDD principles in `.claude`; put repository-specific paths, commands, owners, products, and formats in project config/reference docs.
1033> 2. Preserve cycle: `spec -> plan -> tasks -> implement -> verify -> update spec/docs`.
1034> 3. Trace every requirement or invariant through decision, task, TC/test, source evidence, and docs/spec update.
1035> 4. Treat code-to-spec extraction as reference-only until accepted by the canonical spec owner.
1036> 5. Any supported AI tool may plan, implement, review, or verify with synced context; using multiple tools is optional.
1037> 6. Update `.claude` source first, then sync generated mirrors; do not manually edit `.agents`, `.codex`, or `AGENTS.md`. — why: mirrors are generated artifacts; hand-edits are overwritten on the next sync
1038> 7. If `docs/project-config.json`, root instruction files, or a required project-reference doc is missing or stale, auto-run `$project-init` or the narrow lower-level route before ordinary project-specific work.
1039>
1040> **Active reference:** `shared/sdd-artifact-contract.md` in the active skills root.
1041
1042---
1043
1044## SYNC:ai-sdd-artifact-contract:reminder
1045
1046- **MANDATORY** Apply `shared/sdd-artifact-contract.md`; keep reusable AI-SDD in `.claude` and local rules in project docs.
1047- **MANDATORY** Code-to-spec extraction is reference-only until canonical acceptance; any supported AI tool may execute with synced context.
1048- **MANDATORY** Update `.claude` source before syncing generated mirrors; do not manually edit `.agents`, `.codex`, or `AGENTS.md`.
1049- **MANDATORY** Missing or stale project config, root instruction files, or required reference docs route project-specific work through `$project-init` or the narrow setup route automatically.
1050 **[TASK-PLANNING] [MANDATORY]** BEFORE executing any workflow or skill step, create/update task tracking for all planned steps, then keep it synchronized as each step starts/completes.
1051
1052## [LESSON-LEARNED-REMINDER] [BLOCKING] Task Planning & Continuous Improvement — MANDATORY. Do not skip.
1053
1054Break work into small tasks (task tracking) before starting. Add final task: "Analyze AI mistakes & lessons learned".
1055
1056**Extract lessons — ROOT CAUSE ONLY, not symptom fixes:**
1057
10581. Name the FAILURE MODE (reasoning/assumption failure), not symptom — "assumed API existed without reading source" not "used wrong enum value".
10592. Generality test: does this failure mode apply to ≥3 contexts/codebases? If not, abstract one level up.
10603. Write as a universal rule — strip project-specific names/paths/classes. Useful on any codebase.
10614. Consolidate: multiple mistakes sharing one failure mode → ONE lesson.
10625. **Recurrence gate:** "Would this recur in future session WITHOUT this reminder?" — No → skip `$learn`.
10636. **Auto-fix gate:** "Could `$code-review`/`$code-simplifier`/`$security-review`/`$lint` catch this?" — Yes → improve review skill instead.
10647. BOTH gates pass → ask user to run `$learn`.
1065 **[CRITICAL-THINKING-MINDSET]** Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
1066 **Anti-hallucination principle:** Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence root of all hallucination.
1067 **AI Attention principle (Primacy-Recency):** Put the 3 most critical rules at both top and bottom of long prompts/protocols so instruction adherence survives long context windows.
1068 **Goal-driven execution:** Define success criteria first, loop until verified, and stop only when observable checks pass.
1069 **Tests verify intent:** Tests must protect business rules/invariants and fail when the protected intent breaks, not only mirror current behavior.
1070
1071## Common AI Mistake Prevention (System Lessons)
1072
1073- **Re-read files after context compaction.** Edit requires prior Read in same context; compaction wipes read state. Re-read before editing.
1074- **Grep for old terms after bulk replacements.** AI over-trusts find/replace completeness. Grep full repo after bulk edits for missed refs in docs/configs/catalogs.
1075- **Check downstream references before deleting.** Deletions cascade doc/code staleness. Map referencing files before removal.
1076- **After memory loss, check existing state before creating new.** Compaction wipes prior-work memory. Query current state to resume — never blindly duplicate.
1077- **Verify AI-generated content against actual code.** AI hallucinates APIs, class names, method signatures. Grep to confirm existence before documenting/referencing.
1078- **Trace full dependency chain after edits.** Changing a definition misses downstream consumers. Trace the full chain.
1079- **When renaming, grep ALL consumer file types.** Some file types silently ignore missing refs (no compile error). Search code, templates, configs, generated files.
1080- **Trace ALL code paths when verifying correctness.** Code existing ≠ code executing. Trace early exits, error branches, conditional skips — not just happy path.
1081- **Update docs that embed canonical data when source changes.** Docs inlining derived data (workflows, schemas, configs) go stale silently. Update all embedding docs alongside source.
1082- **Verify sub-agent results after context recovery.** Background agents may finish while parent compacted — grep-verify output, don't trust assumed completion.
1083- **Cross-check full target list against sub-agent assignments.** Parallel sub-agents by category miss boundary items. Reconcile union of assignments against target list before proceeding.
1084- **Sub-agents inherit knowledge only from their agent .md definition — use custom agent types, not built-in Explore.** Tool adoption = permission + knowledge + enforcement (numbered workflow step).
1085- **Persist sub-agent findings incrementally, not as a final batch.** Long sub-agents hit cutoffs before final write — findings lost. Instruct append-per-section to report file.
1086- **When debugging, ask "whose responsibility?" before fixing.** Trace caller (wrong data) vs callee (wrong handling). Fix at responsible layer — never patch symptom site.
1087- **Test failure → record a provisional verdict before trace/edit, then investigate.** Use the full five-way taxonomy: SOURCE-WRONG (production violates intent), TEST-WRONG (assertion/setup is stale), TEST-NOT-OPTIMAL (valid but fragile or low-signal test), ENVIRONMENT-BLOCKED (external state prevents a verdict), or AMBIGUOUS (intent/evidence cannot choose safely). Then trace root cause and triangulate against the governing spec (`docs/specs/**` if one exists) AND source. NEVER weaken an assertion, add a skip, relax a timeout, or change source merely to force green.
1088- **Grep ALL removed names after extraction/refactoring.** Primary file "done" ≠ secondary files clean. Grep entire scope for every removed symbol before declaring complete.
1089- **Assume existing values are intentional — ask WHY before changing OR flagging one as a defect.** Pattern-matching as "wrong" skips context. Before changing or reporting any constant/limit/flag/cutoff: read comments, git blame, the CALLER's ordering (the guarantee that makes the value correct usually lives in code running immediately BEFORE the cited line), and 2+ sibling call sites of the same convention. A doc stating WHAT without WHY is missing rationale, not proof of a missing guard — and in a validation pass, an accurate `file:line` citation proves the transcription, never the defect.
1090- **Verify ALL affected outputs, not just the first.** One build green ≠ all green. Multi-stack changes (backend/frontend/tests/docs) require verifying EVERY output.
1091- **Evaluate fit before copying a nearby pattern.** Closest example ≠ matching preconditions — verify the new context shares the same constraints, base classes, scope, lifetime.
1092- **Holistic-first debugging — resist nearest-attention trap.** Don't dive into first plausible cause. List EVERY precondition (config, env vars, paths, DB, endpoints, creds, versions, DI, data). Verify each against evidence (grep/query — not reasoning). Ask "what would falsify this?" — if nothing, it's not a hypothesis. Most expensive failure: going deeper in "obvious" layer while bug sits in layer never questioned.
1093- **Surgical changes — apply the diff test (context-aware).** Two modes: (1) Bug fix → every line traces to the bug; no restyling; orphan cleanup only for imports YOUR changes made unused. (2) Review/enhancement → implement improvements AND announce as "Enhancement beyond main request: [what]". Never silently scope-creep. Diff test: "Would this line exist if I wasn't asked to do X?" — if no, delete or announce.
1094- **Surface ambiguity before coding — don't pick silently.** Multiple valid interpretations → present each with effort: "[Request] could mean (1) [N h], (2) [N h]. Which matters?" List scope/format/volume/constraints assumptions first. If simpler path exists, say so. Never silently pick.
1095- **[MANDATORY FIRST ACTION] ALWAYS activate a suitable skill or workflow BEFORE responding.** Match task against workflow catalog + skill list; invoke via skill invocation or `$start-workflow <workflowId>`. NEVER answer or write code before checking. Skip = protocol violation.
1096- **Why-Review adversarial mindset — apply when reviewing any plan, decision, or design.** Default SKEPTIC not VALIDATOR: steel-man a rejected alternative, invert each stated reason ("what does it sacrifice?"), stress-test top 2-3 assumptions, run pre-mortem ("ships, fails in 3 months — what breaks?"), surface 1-2 alternatives author missed. Section presence ≠ quality; quality = causal reasoning + concrete mitigations + evidence, not "it's better" or "monitor closely".
1097- **Front-load report-write in sub-agent prompts for large reviews.** Many-file sub-agents hit budget before final write — findings lost. Design prompts so: (1) report-write is first explicit deliverable, (2) append per-file/section (not batched), (3) scope bounded so reads don't exhaust budget. Truncated mid-sentence with no report file → spawn narrower scope, don't retry same prompt.
1098- **After context compaction, re-verify all prior phase outcomes before continuing.** Summaries describe intent, not environment state (git index, filesystem, processes). On resume, FIRST audit: git status, re-read modified files, verify filesystem. Every "completed" claim is an untested hypothesis until evidence confirms.
1099- **OOM/memory: check row count before row size.** Triage: (1) Unbounded query — no DB filter for trigger? Push filter to DB; eliminates OOM. (2) Large rows? Projection reduces proportionally. Row reduction > projection in ROI.
1100- **Assert the outcome your system OWNS, never the intermediate state your INFRASTRUCTURE owns.** When testing anything asynchronous (queue/broker delivery, retries, background jobs, caches, replication), assert the final business/entity state. NEVER assert the delivery bookkeeping — consume/send status, attempt counts, last-error, row existence or counts in a broker, scheduler, or outbox/inbox table. That bookkeeping lives in shared infrastructure that ANY co-running process (a peer worker, a second replica, a leftover local container) can write, usually under a deterministic shared key, so the assertion silently tests the developer's environment instead of the system: green when run alone, flaky the instant anything else shares that broker + database. Gate question for every assertion: "would this hold no matter WHICH process did the work?" — if no, assert the converged data state instead. Corollary: process-local fault injection and in-process telemetry cannot gate work any process may perform — use them as stress amplifiers (arm → bounded window → disarm → assert convergence), never as preconditions.
1101- **Keep domain concepts out of generic/shared/infrastructure layers.** Reusable layer (shared library, framework, infra module) must reference NO consumer-specific domain concept — tenant/customer/product IDs, business entities, feature rules. Leak compiles + runs → passes review silently while coupling the "reusable" layer to one consumer. Keep shared type domain-free; push domain fields/logic down into the consumer via subclass/composition. — why: a layer coupled to one consumer's domain is no longer reusable.
1102
1103<!-- CODEX:SYNC-PROMPT-PROTOCOLS:END -->