[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: Detect DDD design quality violations in domain entities and value objects across any technology stack — adapting to project-specific patterns via config/reference docs discovery — so domain entities and value objects preserve invariants, aggregate boundaries, and discovered DDD conventions.
Summary: read-this-if-nothing-else digest — the skill's main steps in order:
- Phase 0 (gate): discover the project's real entity/VO base classes, validation API, domain exception type, failure-signalling convention, concurrency mechanism + blast radius FIRST, then 0.4 detect the modelling paradigm (OO-mutable / type-driven-immutable / event-sourced) per aggregate — discovered conventions override every generic DDD rule. — why: wrong base classes = wrong checklist, and setter rules applied to an immutable or event-sourced model manufacture false findings.
- Phase 1: create the report, run the mandatory high-signal grep patterns (hidden
validate() overrides, leaked persistence/business logic, missing identity markers) BEFORE reading individual files, write every grep result immediately, categorize files (root/entity/VO/unknown).
- Phase 2: per-file checklist A–P — A–L (entity-vs-VO classification, base-class compliance, VO immutability/structural equality, anemic-model detection, domain invariants, invariant→property-TC Dual-Feedback, aggregate-by-ID, navigation serialization safety, domain events, query expressions, ubiquitous language, OOP) plus M invariant-vs-validation ownership + failure signalling, N construction-vs-reconstitution, O event dispatch timing/outbox/domain-vs-integration contract, P aggregate concurrency + transaction boundary — append findings per file, NEVER batch.
- Phase 3 → 4: holistic cross-entity synthesis in the current pass, including 3.1 model-level dimensions (bounded-context sharing; subdomain fit — judge whether a rich model is warranted BEFORE reporting anemia), then final report with health score (
100 − (CRIT×25 + HIGH×10 + MED×3 + LOW×1)); 10+ entity files → switch to parallel code-reviewer sub-agents automatically.
- Phase 5 (validation-first loop): validate via
/why-review gate before any fix, fix only validated findings, then restart the FULL review; a clean pass ENDS the review. Every finding needs file:line at confidence >80%. Close with AskUserQuestion next-steps.
Workflow:
- Phase 0 — Discover project stack + entity/VO base classes + validation API + domain exception type + failure-signalling convention + concurrency mechanism + blast radius, then 0.4 detect modelling paradigm per aggregate (MANDATORY FIRST)
- Phase 1 — Create report; run mandatory grep patterns BEFORE per-file reads; write results immediately; categorize files
- Phase 2 — Entity-by-entity DDD review (per-file checklist A–P + project-specific rules); append per file, never batch
- Phase 3 — Holistic cross-entity synthesis in the current pass, incl. 3.1 model-level dimensions (bounded-context sharing, subdomain fit); fresh-context sub-agent only after validated fixes or explicit high-risk trigger
- Phase 4 — Final report: critical issues, health score, refactoring priority, recommendations
- Phase 5 — Why-Review self-validation gate (MANDATORY when findings exist) → validate → fix validated → restart full review until clean →
AskUserQuestion next-steps
- Scale rule — 10+ entity files → parallel
code-reviewer sub-agents, then consolidate
Key Rules:
- MUST ATTENTION discover project base classes in Phase 0 — NEVER assume generic patterns apply — why: wrong base classes = wrong checklist.
- MUST ATTENTION run mandatory grep patterns in Phase 1 BEFORE reading individual files — why: highest-signal violations surface fastest and seed the report.
- MUST ATTENTION validate findings via the Phase 5
/why-review gate before any fix, then restart the full review after validated fixes — a clean pass ENDS the review — why: every fix invalidates the prior verdict and AI reports inherit confirmation bias.
- NEVER report a finding without
file:line evidence at confidence >80% — why: unproven findings inflate severity downstream.
- MUST ATTENTION append findings per file and persist to
plans/reports/ incrementally; 10+ entity files → parallel sub-agents — why: batched writes vanish on context/budget cutoff.
- MUST ATTENTION detect the modelling paradigm (0.4) before applying any setter/mutability rule, and judge subdomain fit (3.1) before reporting anemic model — NEVER flag a paradigm-appropriate or appropriately-simple design as a violation — why: uniform tactical DDD over CRUD is itself an anti-pattern, and rules written for mutable OO are meaningless against an immutable or event-sourced model.
- MUST ATTENTION treat invariant and validation as different questions with different owners (entity vs boundary), and keep failure signalling consistent with the Phase 0 convention — why: collapsing them buries UX checks in entities and parks business rules in bypassable validators.
Severity Classification:
| Severity |
Action |
Definition |
| CRITICAL |
Block merge |
Silent runtime failure, data corruption, validation bypass |
| HIGH |
Must fix |
Incorrect behavior, invariant gap, architectural violation |
| MEDIUM |
Should fix |
Design debt, maintainability, likely future bug |
| LOW |
Nice to fix |
Convention, documentation, minor clarity |
Canonical Owner — Domain Entity Change Gate
This skill is the canonical owner of SYNC:domain-entity-change-gate. /plan, /plan-review, and /changes-review inline that gate and route here for the full checklist, so a design planned under the gate is reviewed under the same rules. The gate's 6 decision points map to this skill as: classification → A · invariant ownership + failure signalling → E/M · aggregate boundary + concurrency → F/P · construction vs reconstitution → N · events → H/O · test obligation → E2; paradigm detection is 0.4 and subdomain fit is 3.1.
Do NOT apply the gate as a separate pass when running this skill — Phase 2 A–P is the gate, in full. Record Gate is this skill's own body — A–P checklist owns it. — why: a second pass over the same rules duplicates findings and inflates severity counts.
Changing an entity rule here → update .claude/skills/shared/sync-inline-versions.md FIRST if the rule belongs to the gate's 6 decision points, then propagate to the three consumers. NEVER edit an inlined copy directly.
First Principle — Easy to Change
Success metric of every coding decision = future change cost.
DRY, SRP, abstraction, design patterns, naming, layering, tests — every technique serves one goal: make next change cheaper.
Evaluating code, refactor, test, abstraction — ask: does this make next change cheaper or more expensive?
- Reject "best practices" raising change cost (premature abstraction, speculative generality, leaky indirection, ceremony without payoff).
- Name real enemies in findings: coupling, hidden state, duplicated knowledge, unclear intent, irreversible decisions exposed too early.
- Simpler design easy to change beats sophisticated design that isn't.
Apply this lens before invoking any specific rule, pattern, or checklist below — if a downstream rule raises change cost, this principle wins.
Phase 0: Project Discovery + Mode Detection + Blast Radius
MANDATORY FIRST STEP. Phase 0 gates all other work — wrong base classes = wrong checklist.
Create TaskCreate tasks for all phases NOW before doing anything else:
[Phase 0] Project stack discovery + mode detection + blast radius — in_progress (FIRST)
[Phase 1] Collect entity files + grep patterns + create report — pending
[Phase 2] Entity-by-entity DDD review — pending
[Phase 3] Holistic synthesis and fresh-context gate — pending
[Phase 4] Generate final findings — pending
0.1 Discover Project Stack and Entity Conventions
# Check for project reference docs
ls docs/project-reference/ 2>/dev/null
ls docs/ 2>/dev/null | grep -i "entity\|domain\|backend\|pattern"
# Detect configured build/runtime markers from project config and project-reference docs
rg --files | rg "(project|package|build|config|settings|manifest)" | head -20
# Find entity/VO base classes actually used
rg "class.*Entity|class.*RootEntity|class.*BaseEntity|class.*AbstractEntity" {configured-source-roots} | head -10
rg "ValueObject|Aggregate|Entity" {configured-source-roots} | head -20
rg "{configured-entity-markers}" {configured-source-roots} | head -10
Record in report (required before Phase 2):
| Convention |
Discovered Value |
| Entity base class(es) |
{class names with file:line} |
| VO base class(es) |
{class names with file:line} |
| Validation API |
{how validation done} |
| Domain exception type |
{exception class used} |
| Navigation/FK pattern |
{annotation + FK property pattern} |
| Persistence annotations |
{ORM annotations} |
| Failure-signalling convention |
{throws domain exception | returns Result/Either | mixed} |
| Concurrency mechanism |
{version/rowversion/etag field on roots, or none} |
| Modelling paradigm |
{OO-mutable | type-driven/immutable | event-sourced} (0.4) |
If project reference docs exist → read them and extract: service-specific base class requirements, documented anti-patterns, naming conventions, cross-service rules.
0.2 Determine Entity File Scope
Apply mode-appropriate command from Mode Detection table, adapted to discovered stack.
0.3 Blast Radius Analysis
# When .code-graph/graph.db exists
python .claude/scripts/code_graph trace <entity-file> --direction both --json --node-mode file
Record: entity file count, downstream consumers, risk level. Use to prioritize review order (highest-impact first).
0.4 Modelling Paradigm Detection (MUST ATTENTION — gates which per-file rules apply)
Sections C/D/N assume a mutable OO entity. Applying them to an immutable or event-sourced model manufactures false findings — detect the paradigm BEFORE the checklist. — why: "no public setters" is a finding in OO code and meaningless in a model that has no setters by construction.
Detect from the domain source, NEVER assume:
| Paradigm |
Detection signal |
Checklist adaptation |
| OO-mutable (default) |
Classes with private setters + state-changing methods |
Full A–P checklist as written |
| Type-driven / immutable |
Sealed hierarchies, discriminated unions, records-only, With*()/copy-returning methods, smart constructors returning Result |
Section C immutability applies to entities too; Section D reads "no state-mutating method returns void"; illegal-state-representability replaces runtime guards — flag a status enum + nullable per-status fields as the union that was never made |
| Event-sourced |
apply/evolve/when per event, From(events) / stream-fold reconstitution, no persisted state |
Section C setter rules N/A; Section N reconstitution = the fold; Section O owns event-schema evolution; a CRUD-shaped event ({Entity}Updated with full payload) is a HIGH finding — it carries no business meaning |
- MUST ATTENTION record the detected paradigm in the report before Phase 2 and state which sections were adapted or marked N/A — why: an unrecorded adaptation reads as a skipped check.
- NEVER flag a paradigm-appropriate pattern as a violation of a rule written for another paradigm — verify against 0.4 first.
- Mixed paradigms per aggregate are legitimate (event-source one aggregate, not the system) — detect per aggregate, NEVER once per repo.
Phase 1: Collect Files + Grep Patterns + Create Report
Create report FIRST: plans/reports/domain-entities-review-{date}-{slug}.md
Initialize with: Mode, Tech Stack, Discovered Conventions, Blast Radius Summary.
Mandatory Search Intent
MUST ATTENTION run high-signal searches BEFORE reading individual files. Derive the actual roots, file globs, framework markers, and naming conventions from docs/project-config.json plus the repository's project-reference docs. Do not copy a source-root, extension, framework type, or folder name from this skill as if it were canonical.
Search for these intent categories with the configured source roots and discovered stack syntax:
- Validation methods that hide or bypass the base/domain validation path.
- Relationship/navigation fields that can serialize recursively or expose internal graph structure.
- Value objects with mutable public state or missing structural equality.
- Domain methods throwing low-context generic errors instead of configured domain/validation errors.
- Business conditionals and entity mutation leaking into a higher layer when the entity/value object owns the invariant.
- Query/filter expressions placed in handlers/services when the entity, repository extension, specification, or equivalent local pattern owns them.
- Entity classes missing identity markers required by the configured persistence framework.
- Domain models performing direct persistence, network, or infrastructure work.
Representative searches — substitute the markers and source roots discovered from docs/project-config.json / project-reference docs (never hardcode the examples):
# Validation methods that hide or bypass the base/domain validation path
rg "{configured-validation-markers}" {configured-domain-source-roots} | head -20
# Persistence/query-filter expressions or infrastructure work leaked into domain models
rg "{configured-persistence-or-query-markers}" {configured-domain-source-roots} | head -20
# Business conditions / entity mutation leaked above the owning domain layer
rg "{configured-business-condition-patterns}" {configured-application-source-roots} | head -20
# Entity classes missing the identity markers required by the configured persistence framework
rg "{configured-identity-markers}" {configured-domain-source-roots} | head -20
Write ALL grep results to report IMMEDIATELY.
Categorize Files
| Category |
Definition |
| Aggregate Root |
Has dedicated repository; aggregate entry point |
| Entity |
Has identity; accessed/persisted through root |
| Value Object |
Structural equality; must be immutable |
| Unknown |
Plain class in domain layer without clear classification |
Phase 2: Entity-by-Entity DDD Review
For EACH entity/VO file: read file → append findings to report IMMEDIATELY. NEVER batch.
Per-File Review Checklist
A. Entity vs Value Object Classification (MUST ATTENTION)
Entity = unique identity persisting across time. VO = defined by attributes, immutable, interchangeable when equal. NEVER swap roles.
- verify: does class need unique persistent identity? No → suspect VO misclassification.
- flag: "snapshot at point in time" (contact at referral, price at purchase, measurement at check-in) → MUST be VO, NEVER entity.
- CRITICAL if VO has primary key or repository → VO masquerading as entity.
- MEDIUM if entity has 3+ scalar fields always moving together → data clump → VO candidate.
- MEDIUM if entity is effectively stateless (no state changes after creation) → suspect VO.
B. Base Class Compliance (MUST ATTENTION)
NEVER assume base class — ALWAYS use discovered values from Phase 0. Project docs override generic rules.
- verify aggregate root extends project's root entity base (from Phase 0 discovery).
- NEVER use root entity base for non-root child entities — child entities MUST NOT have their own repository.
- verify VOs extend project's VO base class — NEVER plain POCO/POJO in domain.
- verify audited entities extend audited base where audit trail required.
- cross-check each entity's base class against service/module-specific requirements from reference docs.
C. Value Object Immutability and Equality (MUST ATTENTION)
Mutable VOs are a design contradiction — they imply identity through mutation, which entities have, not VOs.
- NEVER allow mutable public state on value objects. Use the immutability mechanism idiomatic to the configured language/runtime.
- Parameterless/default constructor allowed when required for framework deserialization.
- verify equality based on structural value — NEVER reference equality. Use the equality mechanism idiomatic to the configured language/runtime or the repository's documented value-object base pattern.
- verify
validate() overridden when VO has constraints (format, range, required).
- verify factory method exists for non-trivial construction:
Create(), New(), Of(), From*().
- NEVER put async operations, repository calls, or infrastructure dependencies inside VO.
- Conversion/implicit operator defined when VO wraps single primitive.
D. Encapsulation and Anemic Domain Model (MUST ATTENTION)
Anemic model = entity is data bag, all logic in handlers. Fix: move behavior to entity (lowest layer).
- verify entity has at least ONE domain method when it has business rules — NEVER pure property bag.
- NEVER allow direct property assignment for state transitions from outside entity — MUST use domain methods (
changeStatus(), approve(), assign()).
- flag: same guard clause in 3+ handlers for same entity → extract to
ensureCan*() on entity.
- flag: handler doing multi-field mutation (
entity.a=x; entity.b=y; entity.c=z) without validation → domain method candidate.
- flag: business conditionals in application layer referencing single entity's state → move to entity guard.
- Entity behavior MUST be caller-agnostic — methods describe domain intent, NEVER reference who calls them.
Detection signal: entity.property = value assignments (non-audit) in application layer = anemic model signal.
E. Domain Invariants (MUST ATTENTION)
Invariants enforced only in application layer = domain can reach invalid state via any other entry point.
- verify entity validates own invariants (via
validate(), constructor guard, or factory) — NEVER handler-only enforcement.
- verify pre-operation guards as
ensureCan*() / validateCan*() methods on entity.
- NEVER throw raw language exceptions for domain violations — MUST use project's domain exception type (discovered Phase 0):
ArgumentException, IllegalArgumentException, Error, ValueError all WRONG.
- Invariants from creation MUST be enforced in factory method or constructor.
- CRITICAL:
validate() MUST NOT be hidden by same-name method without calling super → silent validation dead zone.
Detection signal: Search for validate() override not calling super.validate() or framework base validation.
E2. Spec-Loop Discipline — Invariant → Property-TC Mapping (MUST ATTENTION)
Every §5 invariant you verify is a property the spec should name and a test should guard universally — an enforced invariant with no property test is one refactor away from silent regression.
- verify each entity/VO invariant maps to a universally-quantified property TC (holds for ALL valid inputs) plus a boundary counter-case — NEVER accept a single happy-path example as coverage for an invariant.
- flag any invariant with no guarding property TC as a Dual-Feedback finding: the spec must NAME the invariant AND a test must GUARD it — blank either axis = INCOMPLETE, NEVER report a behavior-affecting invariant finding as code-only.
- review the whole package (spec + tests + entity code), not the entity diff alone; loop until zero new invariant→property-TC gaps remain — each cycle enriches the spec.
Detection signal: an invariant enforced in the entity (constructor/validate()/ensureCan*()) with no corresponding property TC in the spec's Section 8 or test suite → Dual-Feedback gap.
F. Aggregate Design (MUST ATTENTION)
Aggregate = consistency boundary. All invariants must flow through root. Cross-aggregate coupling = transaction trap.
- NEVER give child entity its own repository — ONLY aggregate root has repository.
- NEVER reference another aggregate by object — MUST use ID only (
string productId NOT Product product).
- NEVER expose mutable collection directly — aggregate root MUST use domain methods for collection mutations.
- verify composite-key entities implement project's composite ID pattern (discovered Phase 0).
- flag aggregates with >5 independent child entities with separate lifecycles → splitting candidate.
- Deletion of aggregate root MUST validate pre-conditions on children (orphan prevention).
G. Navigation / Relationship Properties
Navigation properties serializing into each other = circular reference crash or infinite memory allocation.
- CRITICAL: ALL navigation/relationship properties that can serialize recursively MUST use the configured serialization-ignore mechanism or an explicit DTO/projection boundary.
- Navigation properties MUST be nullable/optional — not always loaded.
- FK ID MUST be stored as primitive alongside navigation — NEVER navigation-only reference.
- NEVER use navigation properties in domain logic without null guard.
- Prefer unidirectional navigation — bidirectional only when both directions actively used.
H. Domain Events
Entity raises events → handlers react. NEVER inline side effects in entity domain methods.
- verify meaningful state changes raise domain events — NEVER tracked only by polling DB.
- Events MUST be raised INSIDE entity domain methods — NEVER from handlers/services.
- Side effects MUST go to event handlers — NEVER inline in entity domain method.
- Domain event naming:
{Entity}{Action}Event or {Entity}{PastTense}Event (e.g., OrderShippedEvent).
- Entity domain methods MUST remain focused: raise event + update own state. Nothing else.
I. Static Query Expressions
Query logic belongs on entity (lowest layer) — duplication in repos/handlers = wrong layer.
- verify reusable filter expressions defined as static methods on entity (or companion class) — NEVER duplicated in repos/handlers.
- Expression naming: descriptive static method (e.g.,
isActive(), filteredByDepartment()).
- NEVER duplicate expressions across multiple repository or handler files.
- Query expressions MUST have corresponding database indexes (verify in migration/schema files).
J. Naming and Ubiquitous Language
Technical names break the domain model. Entity names ARE the project's vocabulary.
- NEVER use technical class name suffixes:
Manager, Helper, Processor, Util, Handler, Service.
- Domain methods MUST use domain verbs:
approve(), reject(), assign(), changeStatus() — NEVER process(), handle(), execute().
- Boolean properties MUST use
is*/has*/can* prefix: isActive, hasPermission, canBeDeleted.
- Status/type enums MUST be co-located with owning entity — NEVER in shared
Enums/ catch-all folder.
- Method parameters MUST use domain nouns — NEVER
data, model, obj, input, payload.
K. Code Smells
| Smell |
Detection Signal |
Severity |
| Fat Entity |
>500 lines with unrelated concerns |
MEDIUM — split by domain concept |
| Feature Envy |
Method uses 5+ properties of another entity |
HIGH — wrong responsibility |
| Data Clump |
3+ primitives always together |
MEDIUM — VO candidate |
| Primitive Obsession |
Raw string for email/phone/money/ID |
MEDIUM — domain type opportunity |
| Leaky Abstraction |
Entity exposes persistence internals |
HIGH |
| Collection Exposure |
Public mutable collection returned directly |
HIGH — domain method needed |
| Constructor Overload |
5+ params without factory method |
MEDIUM |
L. OOP Principles
- verify SRP: entity represents ONE domain concept — conflating two → flag for split.
- NEVER instantiate infrastructure inside entity (repositories, HTTP clients, loggers) — MUST receive as parameters.
- New behaviors MUST go via new event handlers — NEVER by modifying entity conditionals (Open/Closed).
- Capability traits added via focused interfaces — NEVER monolithic interface bundle (ISP).
- Entity subclasses MUST be substitutable for base —
base.method() NEVER skipped in override (LSP).
M. Invariant vs Validation Ownership + Failure Signalling (MUST ATTENTION)
Two different questions wearing one word. Invariant = "can this state legally exist?" — owned by the entity, failure is a bug. Validation = "is this input acceptable right now?" — owned by the application boundary, failure is a user error. Collapsing them produces both classic defects at once: form validation buried in entities, and business rules parked in a bypassable Validator.
Think: for each rule the entity enforces, ask who is allowed to violate it. A user typo → boundary validation. A code path reaching an impossible state → entity invariant.
- flag input-shape checks inside the entity (required-field, max-length, format-for-UX, localized messages) → MEDIUM, belongs at the boundary — why: the entity now changes when the form changes.
- flag a business rule living ONLY in a
*Validator / *Rules / handler guard while the entity permits the state → HIGH invariant gap — why: every other entry point reaches invalid state.
- NEVER accept a database constraint or trigger as the invariant's enforcement — it is a backstop; the model must state the rule — why: an opaque SQL error is not a domain contract and cannot be unit-tested.
- MUST ATTENTION verify failure signalling matches the convention discovered in Phase 0 — mixed exception/
Result for the SAME class of failure is a HIGH finding — why: callers cannot know which to handle, so one path goes unhandled.
- Expected business outcomes (insufficient funds, slot taken) returning
Result, unreachable-state guards throwing → correct split; flag the inverse (throwing for expected outcomes in a hot path, or Result for a "cannot happen") as MEDIUM.
- flag mutations returning bare
bool → MEDIUM: loses WHY and is trivially ignored.
- flag silent clamping of bad input (
if (qty < 0) qty = 0) → HIGH — why: hides a caller bug and persists wrong data with no signal.
Detection signal: business rule text appearing in BOTH a validator/handler and the entity, or appearing ONLY outside the entity.
N. Construction vs Reconstitution (MUST ATTENTION)
Creating a new entity runs business rules and raises events. Loading an existing one from storage MUST do neither. One constructor serving both makes creation rules unenforceable without breaking loading.
Think: trace both paths separately — new from a command, and materialization by the ORM/stream fold. Ask what each is allowed to run.
- MUST ATTENTION verify a distinct reconstitution path exists (private/protected ctor, ORM materialization hook, or
From(events) fold) separate from the creation factory — why: without it, creation invariants must be weakened until loading passes.
- CRITICAL if the load path raises domain events — loading N entities emits N phantom events — why: downstream handlers fire for things that did not happen.
- flag creation rules re-run on load (clock checks, uniqueness calls,
startsOn >= today) → HIGH: historical rows fail to load once the rule tightens.
- MUST ATTENTION verify required data sits in the constructor/factory and optional data in methods — an entity constructible without a value it cannot exist without is a HIGH invariant gap.
- flag public parameterless constructor + public setters as the creation path → CRITICAL anemic entry point (paradigm-adjusted per 0.4; framework-required non-public ctors are fine).
- flag 5+ positional constructor params → MEDIUM: group into VOs FIRST, consider a builder only after.
- NEVER flag a framework-mandated non-public parameterless constructor as a violation — verify the discovered persistence convention first.
Detection signal: one public constructor referenced by both the command handler and the ORM/mapping configuration.
O. Event Dispatch Timing + Contract Boundary (MUST ATTENTION)
Section H owns event raising. This owns what happens after — when they dispatch, who may consume them, and how they evolve. Wrong timing silently couples an unrelated handler's failure to the core write.
Think: follow one raised event to its consumer and ask what happens if the consumer throws, if the transaction rolls back, and if the event is delivered twice.
- CRITICAL if events dispatch synchronously INSIDE the write transaction — a handler failure rolls back the business operation — why: an unrelated feature can now break the core write.
- CRITICAL if events publish to a broker BEFORE the transaction commits — you announced a fact that may never have happened; require the transactional outbox (events persisted in the SAME transaction, relayed after commit).
- MUST ATTENTION verify the event buffer is cleared after dispatch — an uncleared buffer republishes on the next save (MEDIUM–HIGH by blast radius).
- MUST ATTENTION verify internal domain events are distinct from published integration events — flag an internal event placed on the bus as HIGH — why: consumers become coupled to your model's internal shape, permanently, and it can no longer be refactored.
- flag fat events carrying the whole aggregate → MEDIUM: violates least privilege and blocks schema evolution. Events carry IDs + the minimal meaningful payload.
- flag events named as commands (
SendEmail, UpdateStock) → MEDIUM: an event states what happened; command-naming re-couples producer to consumer.
- flag handlers with no idempotency guard where delivery is at-least-once → HIGH.
- Event-sourced projects (0.4): MUST ATTENTION verify a versioning/upcasting strategy exists — why: a past event can never be changed, only upcast, and the first schema change without a plan has no rollback.
Detection signal: dispatch/publish call inside the same transaction scope as the repository save, or an integration-event type imported from the domain assembly.
P. Aggregate Concurrency + Transaction Boundary (MUST ATTENTION)
Section F owns aggregate shape. This owns what makes "one aggregate per transaction" actually safe under concurrent load.
Think: two users act on the same aggregate at the same instant — what stops the second write from silently discarding the first?
- MUST ATTENTION verify aggregate roots carry an optimistic-concurrency token (version/rowversion/etag) when the discovered persistence layer supports one — absence is HIGH on any contended or money/data-integrity path — why: last-write-wins silently discards a committed decision.
- NEVER accept a concurrency token on a CHILD entity as the aggregate's token — the version belongs to the ROOT, because a change anywhere inside the aggregate is a change to the aggregate.
- flag a single transaction mutating 2+ aggregate roots → HIGH: lock-ordering and deadlock risk, and it blocks later service extraction. Route the second change through a domain event.
- flag an aggregate whose parts are routinely written by different users concurrently → MEDIUM sizing finding: the boundary is too big and produces concurrency failures on unrelated work.
- MUST ATTENTION check invariants claimed to span aggregates (uniqueness across all instances, "max N active per tenant") — these cannot live inside one aggregate; verify the owning mechanism (DB constraint + domain service, or a reservation pattern) exists and is stated — why: a set-based invariant enforced by an in-memory check races under concurrency and passes every single-threaded test.
Detection signal: repository save of two roots inside one unit-of-work scope, or a root type with no version/timestamp concurrency member.
Phase 3: Holistic Synthesis + Fresh-Context Gate
After all Phase 2 files are reviewed, synthesize cross-entity DDD concerns in the current report. Do not spawn a fresh sub-agent only because findings exist. Findings must go through the why-review validation gate before any fix.
3.1 Model-Level Dimensions (MUST ATTENTION — judged over the whole model, NEVER per file)
Two concerns are invisible file-by-file and only appear when the model is viewed whole. Run one focused pass each.
Dimension 1 — Bounded-context sharing. Think: does one entity class serve two different businesses?
- MUST ATTENTION flag a single entity class consumed by two contexts with divergent rules (a
Customer used by Sales, Support, AND Billing) → HIGH — why: the class accretes every context's fields and rules, becomes the god entity nobody can change, and no context owns it.
- The same word meaning different things per context is CORRECT, NEVER a duplication to eliminate — flag an attempt to unify them as a MEDIUM finding against the unifier.
- MUST ATTENTION verify a translation boundary exists where contexts meet (anti-corruption layer, mapper, published contract) — direct cross-context entity reuse is HIGH.
- flag domain concepts leaking into a shared/generic/infrastructure layer (tenant/customer/product IDs, business rules in a "reusable" base) → HIGH — why: a layer coupled to one consumer's domain is no longer reusable.
Dimension 2 — Subdomain fit. Think: does this code deserve a rich domain model at all?
- MUST ATTENTION judge fit BEFORE reporting anemic-model findings: a rich entity is correct in a core subdomain (complex, differentiating, changes often); Active Record or Transaction Script is CORRECT in supporting/generic subdomains and in pure CRUD.
- NEVER report "anemic model" against code whose subdomain has no invariants beyond required-field — that is CRUD, and the finding is noise — why: uniform tactical DDD over CRUD is itself an anti-pattern, adding ceremony and indirection with no invariant to protect.
- flag the inverse too: a core subdomain implemented as Transaction Script with business rules scattered across handlers → HIGH, this is where the rich model was owed.
- flag generic subdomains modelled in-house (auth, billing, email, scheduling) → MEDIUM: buy or adopt, do not model.
- MUST ATTENTION state the subdomain judgment and its evidence in the report — an anemic-model finding without it is unproven — why: "anemic" and "appropriately simple" look identical in a diff.
Spawn a fresh code-reviewer sub-agent only when one of these conditions is true:
- A validated-finding fix cycle has already changed the entity review target and this is the full re-review restart.
- The user/workflow explicitly requests an independent high-risk synthesis pass for broad entity-model changes.
- Phase 2 produced contradictory evidence that cannot be resolved in the current session without an independent read.
When a fresh-context pass is triggered, build the Agent call dynamically — set Target Files and Reference Docs from Phase 0/1 discoveries:
Agent({
description: "Fresh full DDD entity review after validated fixes or explicit high-risk trigger",
subagent_type: "code-reviewer",
prompt: `
## Task
Review domain entity and value object files holistically for DDD design quality:
- Domain model coherence: entities vs VOs correctly classified across entire model?
- Aggregate boundary consistency across service/module?
- Anemic domain model: business logic consistently in entity or scattered in handlers?
- Navigation property hygiene across entire domain layer
- Ubiquitous language consistency across all entities
- Missed cross-entity interactions
- Bounded-context sharing: one entity class serving two contexts with divergent rules?
- Subdomain fit: does this model deserve rich entities, or is Active Record / Transaction Script correct here?
- Concurrency: do aggregate roots carry an optimistic-concurrency token? Any transaction mutating 2+ roots?
- Set-based invariants (uniqueness across all instances) — enforced by a real mechanism, or by a racy in-memory check?
## Review Mode
Fresh full review after a validated fix cycle or explicit high-risk trigger. ZERO memory of prior rounds. Re-read all target files from scratch via own tool calls.
## Protocols (follow VERBATIM)
### Evidence-Based Reasoning
Every claim needs proof. Cite file:line or grep results. Confidence: >80% act, 60-80% verify first, <60% DO NOT report.
NEVER write: "obviously", "I think", "should be", "probably".
### Project-Specific Discovery (MANDATORY before any finding)
1. Check docs/project-reference/ for entity reference docs, backend patterns, code review rules
2. grep -rn "class.*Entity\|class.*BaseEntity\|class.*RootEntity" <source-root>/ | head -10
3. grep -rn "ValueObject\|@ValueObject\|AbstractValueObject" <source-root>/ | head -10
4. Read discovered project reference docs — extract project-specific rules
5. NEVER flag violations contradicting discovered project conventions — verify against docs first
### Bug Detection for Domain Entities
Check every entity:
1. Null Safety: navigation properties guarded before use? Computed properties NPE-safe?
2. Boundary Conditions: empty collections in domain methods? Zero/negative invariants?
3. Error Handli
…(truncated)
1---2name: domain-entities-review-23description: "[DDD Quality] Use when you need to review domain entities and value objects for DDD design quality."4---56<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:START -->78> **[BLOCKING]** Execute skill steps in declared order. NEVER skip, reorder, or merge steps without explicit user approval.9> **[BLOCKING]** Before each step or sub-skill call, update task tracking: set `in_progress` when step starts, set `completed` when step ends.10> **[BLOCKING]** Every completed/skipped step MUST include brief evidence or explicit skip reason.11> **[BLOCKING]** If Task tools are unavailable, create and maintain an equivalent step-by-step plan tracker with the same status transitions.1213<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:END -->1415## Quick Summary1617**Goal:** Detect DDD design quality violations in domain entities and value objects across any technology stack — adapting to project-specific patterns via config/reference docs discovery — so domain entities and value objects preserve invariants, aggregate boundaries, and discovered DDD conventions.1819**Summary:** read-this-if-nothing-else digest — the skill's main steps in order:2021- **Phase 0 (gate):** discover the project's real entity/VO base classes, validation API, domain exception type, failure-signalling convention, concurrency mechanism + blast radius FIRST, then **0.4 detect the modelling paradigm** (OO-mutable / type-driven-immutable / event-sourced) per aggregate — discovered conventions override every generic DDD rule. — why: wrong base classes = wrong checklist, and setter rules applied to an immutable or event-sourced model manufacture false findings.22- **Phase 1:** create the report, run the mandatory high-signal grep patterns (hidden `validate()` overrides, leaked persistence/business logic, missing identity markers) BEFORE reading individual files, write every grep result immediately, categorize files (root/entity/VO/unknown).23- **Phase 2:** per-file checklist **A–P** — A–L (entity-vs-VO classification, base-class compliance, VO immutability/structural equality, anemic-model detection, domain invariants, invariant→property-TC Dual-Feedback, aggregate-by-ID, navigation serialization safety, domain events, query expressions, ubiquitous language, OOP) plus **M** invariant-vs-validation ownership + failure signalling, **N** construction-vs-reconstitution, **O** event dispatch timing/outbox/domain-vs-integration contract, **P** aggregate concurrency + transaction boundary — append findings per file, NEVER batch.24- **Phase 3 → 4:** holistic cross-entity synthesis in the current pass, including **3.1 model-level dimensions** (bounded-context sharing; subdomain fit — judge whether a rich model is warranted BEFORE reporting anemia), then final report with health score (`100 − (CRIT×25 + HIGH×10 + MED×3 + LOW×1)`); 10+ entity files → switch to parallel `code-reviewer` sub-agents automatically.25- **Phase 5 (validation-first loop):** validate via `/why-review` gate before any fix, fix only validated findings, then restart the FULL review; a clean pass ENDS the review. Every finding needs `file:line` at confidence >80%. Close with `AskUserQuestion` next-steps.2627**Workflow:**28291. **Phase 0** — Discover project stack + entity/VO base classes + validation API + domain exception type + failure-signalling convention + concurrency mechanism + blast radius, then **0.4 detect modelling paradigm per aggregate** **(MANDATORY FIRST)**302. **Phase 1** — Create report; run mandatory grep patterns BEFORE per-file reads; write results immediately; categorize files313. **Phase 2** — Entity-by-entity DDD review (per-file checklist **A–P** + project-specific rules); append per file, never batch324. **Phase 3** — Holistic cross-entity synthesis in the current pass, incl. **3.1 model-level dimensions** (bounded-context sharing, subdomain fit); fresh-context sub-agent only after validated fixes or explicit high-risk trigger335. **Phase 4** — Final report: critical issues, health score, refactoring priority, recommendations346. **Phase 5** — Why-Review self-validation gate (MANDATORY when findings exist) → validate → fix validated → restart full review until clean → `AskUserQuestion` next-steps357. **Scale rule** — 10+ entity files → parallel `code-reviewer` sub-agents, then consolidate3637**Key Rules:**3839- MUST ATTENTION discover project base classes in Phase 0 — NEVER assume generic patterns apply — why: wrong base classes = wrong checklist.40- MUST ATTENTION run mandatory grep patterns in Phase 1 BEFORE reading individual files — why: highest-signal violations surface fastest and seed the report.41- MUST ATTENTION validate findings via the Phase 5 `/why-review` gate before any fix, then restart the full review after validated fixes — a clean pass ENDS the review — why: every fix invalidates the prior verdict and AI reports inherit confirmation bias.42- NEVER report a finding without `file:line` evidence at confidence >80% — why: unproven findings inflate severity downstream.43- MUST ATTENTION append findings per file and persist to `plans/reports/` incrementally; 10+ entity files → parallel sub-agents — why: batched writes vanish on context/budget cutoff.44- MUST ATTENTION detect the modelling paradigm (0.4) before applying any setter/mutability rule, and judge subdomain fit (3.1) before reporting anemic model — NEVER flag a paradigm-appropriate or appropriately-simple design as a violation — why: uniform tactical DDD over CRUD is itself an anti-pattern, and rules written for mutable OO are meaningless against an immutable or event-sourced model.45- MUST ATTENTION treat invariant and validation as different questions with different owners (entity vs boundary), and keep failure signalling consistent with the Phase 0 convention — why: collapsing them buries UX checks in entities and parks business rules in bypassable validators.4647**Severity Classification:**4849| Severity | Action | Definition |50| -------- | ----------- | ---------------------------------------------------------- |51| CRITICAL | Block merge | Silent runtime failure, data corruption, validation bypass |52| HIGH | Must fix | Incorrect behavior, invariant gap, architectural violation |53| MEDIUM | Should fix | Design debt, maintainability, likely future bug |54| LOW | Nice to fix | Convention, documentation, minor clarity |5556---5758## Canonical Owner — Domain Entity Change Gate5960> This skill is the **canonical owner** of `SYNC:domain-entity-change-gate`. `/plan`, `/plan-review`, and `/changes-review` inline that gate and route here for the full checklist, so a design planned under the gate is reviewed under the same rules. The gate's 6 decision points map to this skill as: classification → **A** · invariant ownership + failure signalling → **E/M** · aggregate boundary + concurrency → **F/P** · construction vs reconstitution → **N** · events → **H/O** · test obligation → **E2**; paradigm detection is **0.4** and subdomain fit is **3.1**.61>62> Do NOT apply the gate as a separate pass when running this skill — Phase 2 A–P **is** the gate, in full. Record `Gate is this skill's own body — A–P checklist owns it.` — why: a second pass over the same rules duplicates findings and inflates severity counts.63>64> Changing an entity rule here → update `.claude/skills/shared/sync-inline-versions.md` FIRST if the rule belongs to the gate's 6 decision points, then propagate to the three consumers. NEVER edit an inlined copy directly.6566---6768## First Principle — Easy to Change6970> **Success metric of every coding decision = _future change cost_.**71> DRY, SRP, abstraction, design patterns, naming, layering, tests — every technique serves one goal: **make next change cheaper**.7273Evaluating code, refactor, test, abstraction — ask: **does this make next change cheaper or more expensive?**7475- Reject "best practices" raising change cost (premature abstraction, speculative generality, leaky indirection, ceremony without payoff).76- Name real enemies in findings: **coupling, hidden state, duplicated knowledge, unclear intent, irreversible decisions exposed too early**.77- Simpler design easy to change beats sophisticated design that isn't.7879Apply this lens **before** invoking any specific rule, pattern, or checklist below — if a downstream rule raises change cost, this principle wins.8081---8283## Phase 0: Project Discovery + Mode Detection + Blast Radius8485> **MANDATORY FIRST STEP.** Phase 0 gates all other work — wrong base classes = wrong checklist.8687**Create `TaskCreate` tasks for all phases NOW before doing anything else:**8889- `[Phase 0] Project stack discovery + mode detection + blast radius` — in_progress **(FIRST)**90- `[Phase 1] Collect entity files + grep patterns + create report` — pending91- `[Phase 2] Entity-by-entity DDD review` — pending92- `[Phase 3] Holistic synthesis and fresh-context gate` — pending93- `[Phase 4] Generate final findings` — pending9495### 0.1 Discover Project Stack and Entity Conventions9697```bash98# Check for project reference docs99ls docs/project-reference/ 2>/dev/null100ls docs/ 2>/dev/null | grep -i "entity\|domain\|backend\|pattern"101102# Detect configured build/runtime markers from project config and project-reference docs103rg --files | rg "(project|package|build|config|settings|manifest)" | head -20104105# Find entity/VO base classes actually used106rg "class.*Entity|class.*RootEntity|class.*BaseEntity|class.*AbstractEntity" {configured-source-roots} | head -10107rg "ValueObject|Aggregate|Entity" {configured-source-roots} | head -20108rg "{configured-entity-markers}" {configured-source-roots} | head -10109```110111**Record in report (required before Phase 2):**112113| Convention | Discovered Value |114| ----------------------------- | -------------------------------------------------------------- |115| Entity base class(es) | `{class names with file:line}` |116| VO base class(es) | `{class names with file:line}` |117| Validation API | `{how validation done}` |118| Domain exception type | `{exception class used}` |119| Navigation/FK pattern | `{annotation + FK property pattern}` |120| Persistence annotations | `{ORM annotations}` |121| Failure-signalling convention | `{throws domain exception \| returns Result/Either \| mixed}` |122| Concurrency mechanism | `{version/rowversion/etag field on roots, or none}` |123| Modelling paradigm | `{OO-mutable \| type-driven/immutable \| event-sourced}` (0.4) |124125If project reference docs exist → read them and extract: service-specific base class requirements, documented anti-patterns, naming conventions, cross-service rules.126127### 0.2 Determine Entity File Scope128129Apply mode-appropriate command from Mode Detection table, adapted to discovered stack.130131### 0.3 Blast Radius Analysis132133```bash134# When .code-graph/graph.db exists135python .claude/scripts/code_graph trace <entity-file> --direction both --json --node-mode file136```137138Record: entity file count, downstream consumers, risk level. Use to prioritize review order (highest-impact first).139140### 0.4 Modelling Paradigm Detection (MUST ATTENTION — gates which per-file rules apply)141142> Sections C/D/N assume a mutable OO entity. Applying them to an immutable or event-sourced model manufactures false findings — detect the paradigm BEFORE the checklist. — why: "no public setters" is a finding in OO code and meaningless in a model that has no setters by construction.143144Detect from the domain source, NEVER assume:145146| Paradigm | Detection signal | Checklist adaptation |147| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |148| **OO-mutable** (default) | Classes with private setters + state-changing methods | Full A–P checklist as written |149| **Type-driven / immutable** | Sealed hierarchies, discriminated unions, records-only, `With*()`/copy-returning methods, smart constructors returning `Result` | Section C immutability applies to entities too; Section D reads "no state-mutating method returns void"; illegal-state-representability replaces runtime guards — flag a status enum + nullable per-status fields as the union that was never made |150| **Event-sourced** | `apply`/`evolve`/`when` per event, `From(events)` / stream-fold reconstitution, no persisted state | Section C setter rules N/A; Section N reconstitution = the fold; Section O owns event-schema evolution; a CRUD-shaped event (`{Entity}Updated` with full payload) is a HIGH finding — it carries no business meaning |151152- MUST ATTENTION record the detected paradigm in the report before Phase 2 and state which sections were adapted or marked N/A — why: an unrecorded adaptation reads as a skipped check.153- NEVER flag a paradigm-appropriate pattern as a violation of a rule written for another paradigm — verify against 0.4 first.154- Mixed paradigms per aggregate are legitimate (event-source one aggregate, not the system) — detect per aggregate, NEVER once per repo.155156---157158## Phase 1: Collect Files + Grep Patterns + Create Report159160**Create report FIRST:** `plans/reports/domain-entities-review-{date}-{slug}.md`161162Initialize with: Mode, Tech Stack, Discovered Conventions, Blast Radius Summary.163164### Mandatory Search Intent165166MUST ATTENTION run high-signal searches BEFORE reading individual files. Derive the actual roots, file globs, framework markers, and naming conventions from `docs/project-config.json` plus the repository's project-reference docs. Do not copy a source-root, extension, framework type, or folder name from this skill as if it were canonical.167168Search for these intent categories with the configured source roots and discovered stack syntax:169170- Validation methods that hide or bypass the base/domain validation path.171- Relationship/navigation fields that can serialize recursively or expose internal graph structure.172- Value objects with mutable public state or missing structural equality.173- Domain methods throwing low-context generic errors instead of configured domain/validation errors.174- Business conditionals and entity mutation leaking into a higher layer when the entity/value object owns the invariant.175- Query/filter expressions placed in handlers/services when the entity, repository extension, specification, or equivalent local pattern owns them.176- Entity classes missing identity markers required by the configured persistence framework.177- Domain models performing direct persistence, network, or infrastructure work.178179Representative searches — substitute the markers and source roots discovered from `docs/project-config.json` / project-reference docs (never hardcode the examples):180181```bash182# Validation methods that hide or bypass the base/domain validation path183rg "{configured-validation-markers}" {configured-domain-source-roots} | head -20184185# Persistence/query-filter expressions or infrastructure work leaked into domain models186rg "{configured-persistence-or-query-markers}" {configured-domain-source-roots} | head -20187188# Business conditions / entity mutation leaked above the owning domain layer189rg "{configured-business-condition-patterns}" {configured-application-source-roots} | head -20190191# Entity classes missing the identity markers required by the configured persistence framework192rg "{configured-identity-markers}" {configured-domain-source-roots} | head -20193```194195Write ALL grep results to report IMMEDIATELY.196197### Categorize Files198199| Category | Definition |200| -------------- | -------------------------------------------------------- |201| Aggregate Root | Has dedicated repository; aggregate entry point |202| Entity | Has identity; accessed/persisted through root |203| Value Object | Structural equality; must be immutable |204| Unknown | Plain class in domain layer without clear classification |205206---207208## Phase 2: Entity-by-Entity DDD Review209210For EACH entity/VO file: read file → append findings to report IMMEDIATELY. NEVER batch.211212### Per-File Review Checklist213214#### A. Entity vs Value Object Classification (MUST ATTENTION)215216> Entity = unique identity persisting across time. VO = defined by attributes, immutable, interchangeable when equal. NEVER swap roles.217218- verify: does class need unique persistent identity? No → suspect VO misclassification.219- flag: "snapshot at point in time" (contact at referral, price at purchase, measurement at check-in) → MUST be VO, NEVER entity.220- CRITICAL if VO has primary key or repository → VO masquerading as entity.221- MEDIUM if entity has 3+ scalar fields always moving together → data clump → VO candidate.222- MEDIUM if entity is effectively stateless (no state changes after creation) → suspect VO.223224#### B. Base Class Compliance (MUST ATTENTION)225226> NEVER assume base class — ALWAYS use discovered values from Phase 0. Project docs override generic rules.227228- verify aggregate root extends project's root entity base (from Phase 0 discovery).229- NEVER use root entity base for non-root child entities — child entities MUST NOT have their own repository.230- verify VOs extend project's VO base class — NEVER plain POCO/POJO in domain.231- verify audited entities extend audited base where audit trail required.232- cross-check each entity's base class against service/module-specific requirements from reference docs.233234#### C. Value Object Immutability and Equality (MUST ATTENTION)235236> Mutable VOs are a design contradiction — they imply identity through mutation, which entities have, not VOs.237238- NEVER allow mutable public state on value objects. Use the immutability mechanism idiomatic to the configured language/runtime.239- Parameterless/default constructor allowed when required for framework deserialization.240- verify equality based on structural value — NEVER reference equality. Use the equality mechanism idiomatic to the configured language/runtime or the repository's documented value-object base pattern.241- verify `validate()` overridden when VO has constraints (format, range, required).242- verify factory method exists for non-trivial construction: `Create()`, `New()`, `Of()`, `From*()`.243- NEVER put async operations, repository calls, or infrastructure dependencies inside VO.244- Conversion/implicit operator defined when VO wraps single primitive.245246#### D. Encapsulation and Anemic Domain Model (MUST ATTENTION)247248> Anemic model = entity is data bag, all logic in handlers. Fix: move behavior to entity (lowest layer).249250- verify entity has at least ONE domain method when it has business rules — NEVER pure property bag.251- NEVER allow direct property assignment for state transitions from outside entity — MUST use domain methods (`changeStatus()`, `approve()`, `assign()`).252- flag: same guard clause in 3+ handlers for same entity → extract to `ensureCan*()` on entity.253- flag: handler doing multi-field mutation (`entity.a=x; entity.b=y; entity.c=z`) without validation → domain method candidate.254- flag: business conditionals in application layer referencing single entity's state → move to entity guard.255- Entity behavior MUST be caller-agnostic — methods describe domain intent, NEVER reference who calls them.256257**Detection signal:** `entity.property = value` assignments (non-audit) in application layer = anemic model signal.258259#### E. Domain Invariants (MUST ATTENTION)260261> Invariants enforced only in application layer = domain can reach invalid state via any other entry point.262263- verify entity validates own invariants (via `validate()`, constructor guard, or factory) — NEVER handler-only enforcement.264- verify pre-operation guards as `ensureCan*()` / `validateCan*()` methods on entity.265- NEVER throw raw language exceptions for domain violations — MUST use project's domain exception type (discovered Phase 0): `ArgumentException`, `IllegalArgumentException`, `Error`, `ValueError` all WRONG.266- Invariants from creation MUST be enforced in factory method or constructor.267- CRITICAL: `validate()` MUST NOT be hidden by same-name method without calling `super` → silent validation dead zone.268269**Detection signal:** Search for `validate()` override not calling `super.validate()` or framework base validation.270271#### E2. Spec-Loop Discipline — Invariant → Property-TC Mapping (MUST ATTENTION)272273> Every §5 invariant you verify is a property the spec should name and a test should guard universally — an enforced invariant with no property test is one refactor away from silent regression.274275- verify each entity/VO invariant maps to a **universally-quantified property TC** (holds for ALL valid inputs) plus a **boundary counter-case** — NEVER accept a single happy-path example as coverage for an invariant.276- flag any invariant with no guarding property TC as a **Dual-Feedback finding**: the spec must NAME the invariant AND a test must GUARD it — blank either axis = INCOMPLETE, NEVER report a behavior-affecting invariant finding as code-only.277- review the whole package (spec + tests + entity code), not the entity diff alone; loop until zero new invariant→property-TC gaps remain — each cycle enriches the spec.278279**Detection signal:** an invariant enforced in the entity (constructor/`validate()`/`ensureCan*()`) with no corresponding property TC in the spec's Section 8 or test suite → Dual-Feedback gap.280281#### F. Aggregate Design (MUST ATTENTION)282283> Aggregate = consistency boundary. All invariants must flow through root. Cross-aggregate coupling = transaction trap.284285- NEVER give child entity its own repository — ONLY aggregate root has repository.286- NEVER reference another aggregate by object — MUST use ID only (`string productId` NOT `Product product`).287- NEVER expose mutable collection directly — aggregate root MUST use domain methods for collection mutations.288- verify composite-key entities implement project's composite ID pattern (discovered Phase 0).289- flag aggregates with >5 independent child entities with separate lifecycles → splitting candidate.290- Deletion of aggregate root MUST validate pre-conditions on children (orphan prevention).291292#### G. Navigation / Relationship Properties293294> Navigation properties serializing into each other = circular reference crash or infinite memory allocation.295296- CRITICAL: ALL navigation/relationship properties that can serialize recursively MUST use the configured serialization-ignore mechanism or an explicit DTO/projection boundary.297- Navigation properties MUST be nullable/optional — not always loaded.298- FK ID MUST be stored as primitive alongside navigation — NEVER navigation-only reference.299- NEVER use navigation properties in domain logic without null guard.300- Prefer unidirectional navigation — bidirectional only when both directions actively used.301302#### H. Domain Events303304> Entity raises events → handlers react. NEVER inline side effects in entity domain methods.305306- verify meaningful state changes raise domain events — NEVER tracked only by polling DB.307- Events MUST be raised INSIDE entity domain methods — NEVER from handlers/services.308- Side effects MUST go to event handlers — NEVER inline in entity domain method.309- Domain event naming: `{Entity}{Action}Event` or `{Entity}{PastTense}Event` (e.g., `OrderShippedEvent`).310- Entity domain methods MUST remain focused: raise event + update own state. Nothing else.311312#### I. Static Query Expressions313314> Query logic belongs on entity (lowest layer) — duplication in repos/handlers = wrong layer.315316- verify reusable filter expressions defined as static methods on entity (or companion class) — NEVER duplicated in repos/handlers.317- Expression naming: descriptive static method (e.g., `isActive()`, `filteredByDepartment()`).318- NEVER duplicate expressions across multiple repository or handler files.319- Query expressions MUST have corresponding database indexes (verify in migration/schema files).320321#### J. Naming and Ubiquitous Language322323> Technical names break the domain model. Entity names ARE the project's vocabulary.324325- NEVER use technical class name suffixes: `Manager`, `Helper`, `Processor`, `Util`, `Handler`, `Service`.326- Domain methods MUST use domain verbs: `approve()`, `reject()`, `assign()`, `changeStatus()` — NEVER `process()`, `handle()`, `execute()`.327- Boolean properties MUST use `is*`/`has*`/`can*` prefix: `isActive`, `hasPermission`, `canBeDeleted`.328- Status/type enums MUST be co-located with owning entity — NEVER in shared `Enums/` catch-all folder.329- Method parameters MUST use domain nouns — NEVER `data`, `model`, `obj`, `input`, `payload`.330331#### K. Code Smells332333| Smell | Detection Signal | Severity |334| ------------------------ | ------------------------------------------- | -------------------------------- |335| **Fat Entity** | >500 lines with unrelated concerns | MEDIUM — split by domain concept |336| **Feature Envy** | Method uses 5+ properties of another entity | HIGH — wrong responsibility |337| **Data Clump** | 3+ primitives always together | MEDIUM — VO candidate |338| **Primitive Obsession** | Raw `string` for email/phone/money/ID | MEDIUM — domain type opportunity |339| **Leaky Abstraction** | Entity exposes persistence internals | HIGH |340| **Collection Exposure** | Public mutable collection returned directly | HIGH — domain method needed |341| **Constructor Overload** | 5+ params without factory method | MEDIUM |342343#### L. OOP Principles344345- verify SRP: entity represents ONE domain concept — conflating two → flag for split.346- NEVER instantiate infrastructure inside entity (repositories, HTTP clients, loggers) — MUST receive as parameters.347- New behaviors MUST go via new event handlers — NEVER by modifying entity conditionals (Open/Closed).348- Capability traits added via focused interfaces — NEVER monolithic interface bundle (ISP).349- Entity subclasses MUST be substitutable for base — `base.method()` NEVER skipped in override (LSP).350351#### M. Invariant vs Validation Ownership + Failure Signalling (MUST ATTENTION)352353> Two different questions wearing one word. **Invariant** = "can this state legally exist?" — owned by the entity, failure is a bug. **Validation** = "is this input acceptable right now?" — owned by the application boundary, failure is a user error. Collapsing them produces both classic defects at once: form validation buried in entities, and business rules parked in a bypassable `Validator`.354355**Think:** for each rule the entity enforces, ask who is allowed to violate it. A user typo → boundary validation. A code path reaching an impossible state → entity invariant.356357- flag input-shape checks inside the entity (required-field, max-length, format-for-UX, localized messages) → MEDIUM, belongs at the boundary — why: the entity now changes when the form changes.358- flag a business rule living ONLY in a `*Validator` / `*Rules` / handler guard while the entity permits the state → HIGH invariant gap — why: every other entry point reaches invalid state.359- NEVER accept a database constraint or trigger as the invariant's enforcement — it is a backstop; the model must state the rule — why: an opaque SQL error is not a domain contract and cannot be unit-tested.360- MUST ATTENTION verify failure signalling matches the convention discovered in Phase 0 — mixed exception/`Result` for the SAME class of failure is a HIGH finding — why: callers cannot know which to handle, so one path goes unhandled.361- Expected business outcomes (insufficient funds, slot taken) returning `Result`, unreachable-state guards throwing → correct split; flag the inverse (throwing for expected outcomes in a hot path, or `Result` for a "cannot happen") as MEDIUM.362- flag mutations returning bare `bool` → MEDIUM: loses WHY and is trivially ignored.363- flag silent clamping of bad input (`if (qty < 0) qty = 0`) → HIGH — why: hides a caller bug and persists wrong data with no signal.364365**Detection signal:** business rule text appearing in BOTH a validator/handler and the entity, or appearing ONLY outside the entity.366367#### N. Construction vs Reconstitution (MUST ATTENTION)368369> Creating a new entity runs business rules and raises events. Loading an existing one from storage MUST do neither. One constructor serving both makes creation rules unenforceable without breaking loading.370371**Think:** trace both paths separately — `new` from a command, and materialization by the ORM/stream fold. Ask what each is allowed to run.372373- MUST ATTENTION verify a distinct reconstitution path exists (private/protected ctor, ORM materialization hook, or `From(events)` fold) separate from the creation factory — why: without it, creation invariants must be weakened until loading passes.374- CRITICAL if the load path raises domain events — loading N entities emits N phantom events — why: downstream handlers fire for things that did not happen.375- flag creation rules re-run on load (clock checks, uniqueness calls, `startsOn >= today`) → HIGH: historical rows fail to load once the rule tightens.376- MUST ATTENTION verify required data sits in the constructor/factory and optional data in methods — an entity constructible without a value it cannot exist without is a HIGH invariant gap.377- flag public parameterless constructor + public setters as the creation path → CRITICAL anemic entry point (paradigm-adjusted per 0.4; framework-required non-public ctors are fine).378- flag 5+ positional constructor params → MEDIUM: group into VOs FIRST, consider a builder only after.379- NEVER flag a framework-mandated non-public parameterless constructor as a violation — verify the discovered persistence convention first.380381**Detection signal:** one public constructor referenced by both the command handler and the ORM/mapping configuration.382383#### O. Event Dispatch Timing + Contract Boundary (MUST ATTENTION)384385> Section H owns event **raising**. This owns what happens **after** — when they dispatch, who may consume them, and how they evolve. Wrong timing silently couples an unrelated handler's failure to the core write.386387**Think:** follow one raised event to its consumer and ask what happens if the consumer throws, if the transaction rolls back, and if the event is delivered twice.388389- CRITICAL if events dispatch synchronously INSIDE the write transaction — a handler failure rolls back the business operation — why: an unrelated feature can now break the core write.390- CRITICAL if events publish to a broker BEFORE the transaction commits — you announced a fact that may never have happened; require the transactional outbox (events persisted in the SAME transaction, relayed after commit).391- MUST ATTENTION verify the event buffer is cleared after dispatch — an uncleared buffer republishes on the next save (MEDIUM–HIGH by blast radius).392- MUST ATTENTION verify internal domain events are distinct from published integration events — flag an internal event placed on the bus as HIGH — why: consumers become coupled to your model's internal shape, permanently, and it can no longer be refactored.393- flag fat events carrying the whole aggregate → MEDIUM: violates least privilege and blocks schema evolution. Events carry IDs + the minimal meaningful payload.394- flag events named as commands (`SendEmail`, `UpdateStock`) → MEDIUM: an event states what happened; command-naming re-couples producer to consumer.395- flag handlers with no idempotency guard where delivery is at-least-once → HIGH.396- Event-sourced projects (0.4): MUST ATTENTION verify a versioning/upcasting strategy exists — why: a past event can never be changed, only upcast, and the first schema change without a plan has no rollback.397398**Detection signal:** dispatch/publish call inside the same transaction scope as the repository save, or an integration-event type imported from the domain assembly.399400#### P. Aggregate Concurrency + Transaction Boundary (MUST ATTENTION)401402> Section F owns aggregate _shape_. This owns what makes "one aggregate per transaction" actually safe under concurrent load.403404**Think:** two users act on the same aggregate at the same instant — what stops the second write from silently discarding the first?405406- MUST ATTENTION verify aggregate roots carry an optimistic-concurrency token (version/rowversion/etag) when the discovered persistence layer supports one — absence is HIGH on any contended or money/data-integrity path — why: last-write-wins silently discards a committed decision.407- NEVER accept a concurrency token on a CHILD entity as the aggregate's token — the version belongs to the ROOT, because a change anywhere inside the aggregate is a change to the aggregate.408- flag a single transaction mutating 2+ aggregate roots → HIGH: lock-ordering and deadlock risk, and it blocks later service extraction. Route the second change through a domain event.409- flag an aggregate whose parts are routinely written by different users concurrently → MEDIUM sizing finding: the boundary is too big and produces concurrency failures on unrelated work.410- MUST ATTENTION check invariants claimed to span aggregates (uniqueness across all instances, "max N active per tenant") — these cannot live inside one aggregate; verify the owning mechanism (DB constraint + domain service, or a reservation pattern) exists and is stated — why: a set-based invariant enforced by an in-memory check races under concurrency and passes every single-threaded test.411412**Detection signal:** repository save of two roots inside one unit-of-work scope, or a root type with no version/timestamp concurrency member.413414---415416## Phase 3: Holistic Synthesis + Fresh-Context Gate417418After all Phase 2 files are reviewed, synthesize cross-entity DDD concerns in the current report. Do not spawn a fresh sub-agent only because findings exist. Findings must go through the why-review validation gate before any fix.419420### 3.1 Model-Level Dimensions (MUST ATTENTION — judged over the whole model, NEVER per file)421422Two concerns are invisible file-by-file and only appear when the model is viewed whole. Run one focused pass each.423424**Dimension 1 — Bounded-context sharing.** **Think:** does one entity class serve two different businesses?425426- MUST ATTENTION flag a single entity class consumed by two contexts with divergent rules (a `Customer` used by Sales, Support, AND Billing) → HIGH — why: the class accretes every context's fields and rules, becomes the god entity nobody can change, and no context owns it.427- The same word meaning different things per context is CORRECT, NEVER a duplication to eliminate — flag an attempt to unify them as a MEDIUM finding against the unifier.428- MUST ATTENTION verify a translation boundary exists where contexts meet (anti-corruption layer, mapper, published contract) — direct cross-context entity reuse is HIGH.429- flag domain concepts leaking into a shared/generic/infrastructure layer (tenant/customer/product IDs, business rules in a "reusable" base) → HIGH — why: a layer coupled to one consumer's domain is no longer reusable.430431**Dimension 2 — Subdomain fit.** **Think:** does this code deserve a rich domain model at all?432433- MUST ATTENTION judge fit BEFORE reporting anemic-model findings: a rich entity is correct in a **core** subdomain (complex, differentiating, changes often); Active Record or Transaction Script is CORRECT in supporting/generic subdomains and in pure CRUD.434- NEVER report "anemic model" against code whose subdomain has no invariants beyond required-field — that is CRUD, and the finding is noise — why: uniform tactical DDD over CRUD is itself an anti-pattern, adding ceremony and indirection with no invariant to protect.435- flag the inverse too: a **core** subdomain implemented as Transaction Script with business rules scattered across handlers → HIGH, this is where the rich model was owed.436- flag generic subdomains modelled in-house (auth, billing, email, scheduling) → MEDIUM: buy or adopt, do not model.437- MUST ATTENTION state the subdomain judgment and its evidence in the report — an anemic-model finding without it is unproven — why: "anemic" and "appropriately simple" look identical in a diff.438439Spawn a fresh `code-reviewer` sub-agent only when one of these conditions is true:440441- A validated-finding fix cycle has already changed the entity review target and this is the full re-review restart.442- The user/workflow explicitly requests an independent high-risk synthesis pass for broad entity-model changes.443- Phase 2 produced contradictory evidence that cannot be resolved in the current session without an independent read.444445When a fresh-context pass is triggered, build the Agent call dynamically — set Target Files and Reference Docs from Phase 0/1 discoveries:446447```448Agent({449 description: "Fresh full DDD entity review after validated fixes or explicit high-risk trigger",450 subagent_type: "code-reviewer",451 prompt: `452## Task453Review domain entity and value object files holistically for DDD design quality:454- Domain model coherence: entities vs VOs correctly classified across entire model?455- Aggregate boundary consistency across service/module?456- Anemic domain model: business logic consistently in entity or scattered in handlers?457- Navigation property hygiene across entire domain layer458- Ubiquitous language consistency across all entities459- Missed cross-entity interactions460- Bounded-context sharing: one entity class serving two contexts with divergent rules?461- Subdomain fit: does this model deserve rich entities, or is Active Record / Transaction Script correct here?462- Concurrency: do aggregate roots carry an optimistic-concurrency token? Any transaction mutating 2+ roots?463- Set-based invariants (uniqueness across all instances) — enforced by a real mechanism, or by a racy in-memory check?464465## Review Mode466Fresh full review after a validated fix cycle or explicit high-risk trigger. ZERO memory of prior rounds. Re-read all target files from scratch via own tool calls.467468## Protocols (follow VERBATIM)469470### Evidence-Based Reasoning471Every claim needs proof. Cite file:line or grep results. Confidence: >80% act, 60-80% verify first, <60% DO NOT report.472NEVER write: "obviously", "I think", "should be", "probably".473474### Project-Specific Discovery (MANDATORY before any finding)4751. Check docs/project-reference/ for entity reference docs, backend patterns, code review rules4762. grep -rn "class.*Entity\|class.*BaseEntity\|class.*RootEntity" <source-root>/ | head -104773. grep -rn "ValueObject\|@ValueObject\|AbstractValueObject" <source-root>/ | head -104784. Read discovered project reference docs — extract project-specific rules4795. NEVER flag violations contradicting discovered project conventions — verify against docs first480481### Bug Detection for Domain Entities482Check every entity:4831. Null Safety: navigation properties guarded before use? Computed properties NPE-safe?4842. Boundary Conditions: empty collections in domain methods? Zero/negative invariants?4853. Error Handli486487…(truncated)