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: 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 ask the user directly 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 → ask the user directly 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 task tracking 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
…(truncated)
1---2name: domain-entities-review3description: "[DDD Quality] Use when you need to review domain entities and value objects for DDD design quality."4---56> Codex compatibility note:7>8> - Invoke repository skills with `$skill-name` in Codex; this mirrored copy rewrites legacy Claude `/skill-name` references.9> - Task tracker mandate: BEFORE executing any workflow or skill step, create/update task tracking for all steps and keep it synchronized as progress changes.10> - User-question prompts mean to ask the user directly in Codex.11> - Ignore Claude-specific mode-switch instructions when they appear.12> - Strict execution contract: when a user explicitly invokes a skill, execute that skill protocol as written.13> - 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.14> - Do not skip, reorder, or merge protocol steps unless the user explicitly approves the deviation first.15> - For workflow skills, execute each listed child-skill step explicitly and report step-by-step evidence.16> - If a required step/tool cannot run in this environment, stop and ask the user before adapting.1718<!-- CODEX:PROJECT-REFERENCE-LOADING:START -->1920## Codex Project-Reference Loading (No Hooks)2122Codex uses static project-reference loading instead of runtime-injected project docs.23When coding, planning, debugging, testing, or reviewing, open project docs explicitly using this routing.2425**Always read:**2627- `docs/project-config.json` (project-specific paths, commands, modules, and workflow/test settings)28- `docs/project-reference/docs-index-reference.md` (routes to the full `docs/project-reference/*` catalog)29- `docs/project-reference/lessons.md` (always-on guardrails and anti-patterns)3031**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.3233**Situation-based docs:**3435- Project structure/architecture/tech-stack/deployment/setup (any layer — backend, frontend, or infra): `project-structure-reference.md`36- Backend/CQRS/API/domain/entity changes: `backend-patterns-reference.md`, `domain-entities-reference.md`37- Frontend/UI/styling/design-system: `frontend-patterns-reference.md`, `scss-styling-guide.md`, `design-system/README.md`38- Spec authoring, `docs/specs/` pathing, or TC format: `feature-spec-reference.md`, `spec-system-reference.md`, `spec-principles.md`39- Behavior/public-contract changes or spec-test-code sync: `workflow-spec-test-code-cycle-reference.md` plus the spec docs above40- Derived spec indexes/ERDs/reimplementation guides: `spec-system-reference.md` and source Feature Specs under `docs/specs/`41- Integration test implementation/review: `integration-test-reference.md`42- E2E test implementation/review: `e2e-test-reference.md`43- Code review/audit work: `code-review-rules.md` plus domain docs above based on changed files4445Do not read all docs blindly. Start from `docs-index-reference.md`, then open only relevant files for the task.4647<!-- CODEX:PROJECT-REFERENCE-LOADING:END -->4849<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:START -->5051> **[BLOCKING]** Execute skill steps in declared order. NEVER skip, reorder, or merge steps without explicit user approval.52> **[BLOCKING]** Before each step or sub-skill call, update task tracking: set `in_progress` when step starts, set `completed` when step ends.53> **[BLOCKING]** Every completed/skipped step MUST include brief evidence or explicit skip reason.54> **[BLOCKING]** If Task tools are unavailable, create and maintain an equivalent step-by-step plan tracker with the same status transitions.5556<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:END -->5758## Quick Summary5960**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.6162**Summary:** read-this-if-nothing-else digest — the skill's main steps in order:6364- **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.65- **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).66- **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.67- **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.68- **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 ask the user directly next-steps.6970**Workflow:**71721. **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)**732. **Phase 1** — Create report; run mandatory grep patterns BEFORE per-file reads; write results immediately; categorize files743. **Phase 2** — Entity-by-entity DDD review (per-file checklist **A–P** + project-specific rules); append per file, never batch754. **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 trigger765. **Phase 4** — Final report: critical issues, health score, refactoring priority, recommendations776. **Phase 5** — Why-Review self-validation gate (MANDATORY when findings exist) → validate → fix validated → restart full review until clean → ask the user directly next-steps787. **Scale rule** — 10+ entity files → parallel `code-reviewer` sub-agents, then consolidate7980**Key Rules:**8182- MUST ATTENTION discover project base classes in Phase 0 — NEVER assume generic patterns apply — why: wrong base classes = wrong checklist.83- MUST ATTENTION run mandatory grep patterns in Phase 1 BEFORE reading individual files — why: highest-signal violations surface fastest and seed the report.84- 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.85- NEVER report a finding without `file:line` evidence at confidence >80% — why: unproven findings inflate severity downstream.86- 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.87- 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.88- 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.8990**Severity Classification:**9192| Severity | Action | Definition |93| -------- | ----------- | ---------------------------------------------------------- |94| CRITICAL | Block merge | Silent runtime failure, data corruption, validation bypass |95| HIGH | Must fix | Incorrect behavior, invariant gap, architectural violation |96| MEDIUM | Should fix | Design debt, maintainability, likely future bug |97| LOW | Nice to fix | Convention, documentation, minor clarity |9899---100101## Canonical Owner — Domain Entity Change Gate102103> 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**.104>105> 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.106>107> 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.108109---110111## First Principle — Easy to Change112113> **Success metric of every coding decision = _future change cost_.**114> DRY, SRP, abstraction, design patterns, naming, layering, tests — every technique serves one goal: **make next change cheaper**.115116Evaluating code, refactor, test, abstraction — ask: **does this make next change cheaper or more expensive?**117118- Reject "best practices" raising change cost (premature abstraction, speculative generality, leaky indirection, ceremony without payoff).119- Name real enemies in findings: **coupling, hidden state, duplicated knowledge, unclear intent, irreversible decisions exposed too early**.120- Simpler design easy to change beats sophisticated design that isn't.121122Apply this lens **before** invoking any specific rule, pattern, or checklist below — if a downstream rule raises change cost, this principle wins.123124---125126## Phase 0: Project Discovery + Mode Detection + Blast Radius127128> **MANDATORY FIRST STEP.** Phase 0 gates all other work — wrong base classes = wrong checklist.129130**Create task tracking tasks for all phases NOW before doing anything else:**131132- `[Phase 0] Project stack discovery + mode detection + blast radius` — in_progress **(FIRST)**133- `[Phase 1] Collect entity files + grep patterns + create report` — pending134- `[Phase 2] Entity-by-entity DDD review` — pending135- `[Phase 3] Holistic synthesis and fresh-context gate` — pending136- `[Phase 4] Generate final findings` — pending137138### 0.1 Discover Project Stack and Entity Conventions139140```bash141# Check for project reference docs142ls docs/project-reference/ 2>/dev/null143ls docs/ 2>/dev/null | grep -i "entity\|domain\|backend\|pattern"144145# Detect configured build/runtime markers from project config and project-reference docs146rg --files | rg "(project|package|build|config|settings|manifest)" | head -20147148# Find entity/VO base classes actually used149rg "class.*Entity|class.*RootEntity|class.*BaseEntity|class.*AbstractEntity" {configured-source-roots} | head -10150rg "ValueObject|Aggregate|Entity" {configured-source-roots} | head -20151rg "{configured-entity-markers}" {configured-source-roots} | head -10152```153154**Record in report (required before Phase 2):**155156| Convention | Discovered Value |157| ----------------------------- | -------------------------------------------------------------- |158| Entity base class(es) | `{class names with file:line}` |159| VO base class(es) | `{class names with file:line}` |160| Validation API | `{how validation done}` |161| Domain exception type | `{exception class used}` |162| Navigation/FK pattern | `{annotation + FK property pattern}` |163| Persistence annotations | `{ORM annotations}` |164| Failure-signalling convention | `{throws domain exception \| returns Result/Either \| mixed}` |165| Concurrency mechanism | `{version/rowversion/etag field on roots, or none}` |166| Modelling paradigm | `{OO-mutable \| type-driven/immutable \| event-sourced}` (0.4) |167168If project reference docs exist → read them and extract: service-specific base class requirements, documented anti-patterns, naming conventions, cross-service rules.169170### 0.2 Determine Entity File Scope171172Apply mode-appropriate command from Mode Detection table, adapted to discovered stack.173174### 0.3 Blast Radius Analysis175176```bash177# When .code-graph/graph.db exists178python .claude/scripts/code_graph trace <entity-file> --direction both --json --node-mode file179```180181Record: entity file count, downstream consumers, risk level. Use to prioritize review order (highest-impact first).182183### 0.4 Modelling Paradigm Detection (MUST ATTENTION — gates which per-file rules apply)184185> 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.186187Detect from the domain source, NEVER assume:188189| Paradigm | Detection signal | Checklist adaptation |190| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |191| **OO-mutable** (default) | Classes with private setters + state-changing methods | Full A–P checklist as written |192| **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 |193| **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 |194195- 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.196- NEVER flag a paradigm-appropriate pattern as a violation of a rule written for another paradigm — verify against 0.4 first.197- Mixed paradigms per aggregate are legitimate (event-source one aggregate, not the system) — detect per aggregate, NEVER once per repo.198199---200201## Phase 1: Collect Files + Grep Patterns + Create Report202203**Create report FIRST:** `plans/reports/domain-entities-review-{date}-{slug}.md`204205Initialize with: Mode, Tech Stack, Discovered Conventions, Blast Radius Summary.206207### Mandatory Search Intent208209MUST 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.210211Search for these intent categories with the configured source roots and discovered stack syntax:212213- Validation methods that hide or bypass the base/domain validation path.214- Relationship/navigation fields that can serialize recursively or expose internal graph structure.215- Value objects with mutable public state or missing structural equality.216- Domain methods throwing low-context generic errors instead of configured domain/validation errors.217- Business conditionals and entity mutation leaking into a higher layer when the entity/value object owns the invariant.218- Query/filter expressions placed in handlers/services when the entity, repository extension, specification, or equivalent local pattern owns them.219- Entity classes missing identity markers required by the configured persistence framework.220- Domain models performing direct persistence, network, or infrastructure work.221222Representative searches — substitute the markers and source roots discovered from `docs/project-config.json` / project-reference docs (never hardcode the examples):223224```bash225# Validation methods that hide or bypass the base/domain validation path226rg "{configured-validation-markers}" {configured-domain-source-roots} | head -20227228# Persistence/query-filter expressions or infrastructure work leaked into domain models229rg "{configured-persistence-or-query-markers}" {configured-domain-source-roots} | head -20230231# Business conditions / entity mutation leaked above the owning domain layer232rg "{configured-business-condition-patterns}" {configured-application-source-roots} | head -20233234# Entity classes missing the identity markers required by the configured persistence framework235rg "{configured-identity-markers}" {configured-domain-source-roots} | head -20236```237238Write ALL grep results to report IMMEDIATELY.239240### Categorize Files241242| Category | Definition |243| -------------- | -------------------------------------------------------- |244| Aggregate Root | Has dedicated repository; aggregate entry point |245| Entity | Has identity; accessed/persisted through root |246| Value Object | Structural equality; must be immutable |247| Unknown | Plain class in domain layer without clear classification |248249---250251## Phase 2: Entity-by-Entity DDD Review252253For EACH entity/VO file: read file → append findings to report IMMEDIATELY. NEVER batch.254255### Per-File Review Checklist256257#### A. Entity vs Value Object Classification (MUST ATTENTION)258259> Entity = unique identity persisting across time. VO = defined by attributes, immutable, interchangeable when equal. NEVER swap roles.260261- verify: does class need unique persistent identity? No → suspect VO misclassification.262- flag: "snapshot at point in time" (contact at referral, price at purchase, measurement at check-in) → MUST be VO, NEVER entity.263- CRITICAL if VO has primary key or repository → VO masquerading as entity.264- MEDIUM if entity has 3+ scalar fields always moving together → data clump → VO candidate.265- MEDIUM if entity is effectively stateless (no state changes after creation) → suspect VO.266267#### B. Base Class Compliance (MUST ATTENTION)268269> NEVER assume base class — ALWAYS use discovered values from Phase 0. Project docs override generic rules.270271- verify aggregate root extends project's root entity base (from Phase 0 discovery).272- NEVER use root entity base for non-root child entities — child entities MUST NOT have their own repository.273- verify VOs extend project's VO base class — NEVER plain POCO/POJO in domain.274- verify audited entities extend audited base where audit trail required.275- cross-check each entity's base class against service/module-specific requirements from reference docs.276277#### C. Value Object Immutability and Equality (MUST ATTENTION)278279> Mutable VOs are a design contradiction — they imply identity through mutation, which entities have, not VOs.280281- NEVER allow mutable public state on value objects. Use the immutability mechanism idiomatic to the configured language/runtime.282- Parameterless/default constructor allowed when required for framework deserialization.283- 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.284- verify `validate()` overridden when VO has constraints (format, range, required).285- verify factory method exists for non-trivial construction: `Create()`, `New()`, `Of()`, `From*()`.286- NEVER put async operations, repository calls, or infrastructure dependencies inside VO.287- Conversion/implicit operator defined when VO wraps single primitive.288289#### D. Encapsulation and Anemic Domain Model (MUST ATTENTION)290291> Anemic model = entity is data bag, all logic in handlers. Fix: move behavior to entity (lowest layer).292293- verify entity has at least ONE domain method when it has business rules — NEVER pure property bag.294- NEVER allow direct property assignment for state transitions from outside entity — MUST use domain methods (`changeStatus()`, `approve()`, `assign()`).295- flag: same guard clause in 3+ handlers for same entity → extract to `ensureCan*()` on entity.296- flag: handler doing multi-field mutation (`entity.a=x; entity.b=y; entity.c=z`) without validation → domain method candidate.297- flag: business conditionals in application layer referencing single entity's state → move to entity guard.298- Entity behavior MUST be caller-agnostic — methods describe domain intent, NEVER reference who calls them.299300**Detection signal:** `entity.property = value` assignments (non-audit) in application layer = anemic model signal.301302#### E. Domain Invariants (MUST ATTENTION)303304> Invariants enforced only in application layer = domain can reach invalid state via any other entry point.305306- verify entity validates own invariants (via `validate()`, constructor guard, or factory) — NEVER handler-only enforcement.307- verify pre-operation guards as `ensureCan*()` / `validateCan*()` methods on entity.308- NEVER throw raw language exceptions for domain violations — MUST use project's domain exception type (discovered Phase 0): `ArgumentException`, `IllegalArgumentException`, `Error`, `ValueError` all WRONG.309- Invariants from creation MUST be enforced in factory method or constructor.310- CRITICAL: `validate()` MUST NOT be hidden by same-name method without calling `super` → silent validation dead zone.311312**Detection signal:** Search for `validate()` override not calling `super.validate()` or framework base validation.313314#### E2. Spec-Loop Discipline — Invariant → Property-TC Mapping (MUST ATTENTION)315316> 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.317318- 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.319- 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.320- 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.321322**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.323324#### F. Aggregate Design (MUST ATTENTION)325326> Aggregate = consistency boundary. All invariants must flow through root. Cross-aggregate coupling = transaction trap.327328- NEVER give child entity its own repository — ONLY aggregate root has repository.329- NEVER reference another aggregate by object — MUST use ID only (`string productId` NOT `Product product`).330- NEVER expose mutable collection directly — aggregate root MUST use domain methods for collection mutations.331- verify composite-key entities implement project's composite ID pattern (discovered Phase 0).332- flag aggregates with >5 independent child entities with separate lifecycles → splitting candidate.333- Deletion of aggregate root MUST validate pre-conditions on children (orphan prevention).334335#### G. Navigation / Relationship Properties336337> Navigation properties serializing into each other = circular reference crash or infinite memory allocation.338339- CRITICAL: ALL navigation/relationship properties that can serialize recursively MUST use the configured serialization-ignore mechanism or an explicit DTO/projection boundary.340- Navigation properties MUST be nullable/optional — not always loaded.341- FK ID MUST be stored as primitive alongside navigation — NEVER navigation-only reference.342- NEVER use navigation properties in domain logic without null guard.343- Prefer unidirectional navigation — bidirectional only when both directions actively used.344345#### H. Domain Events346347> Entity raises events → handlers react. NEVER inline side effects in entity domain methods.348349- verify meaningful state changes raise domain events — NEVER tracked only by polling DB.350- Events MUST be raised INSIDE entity domain methods — NEVER from handlers/services.351- Side effects MUST go to event handlers — NEVER inline in entity domain method.352- Domain event naming: `{Entity}{Action}Event` or `{Entity}{PastTense}Event` (e.g., `OrderShippedEvent`).353- Entity domain methods MUST remain focused: raise event + update own state. Nothing else.354355#### I. Static Query Expressions356357> Query logic belongs on entity (lowest layer) — duplication in repos/handlers = wrong layer.358359- verify reusable filter expressions defined as static methods on entity (or companion class) — NEVER duplicated in repos/handlers.360- Expression naming: descriptive static method (e.g., `isActive()`, `filteredByDepartment()`).361- NEVER duplicate expressions across multiple repository or handler files.362- Query expressions MUST have corresponding database indexes (verify in migration/schema files).363364#### J. Naming and Ubiquitous Language365366> Technical names break the domain model. Entity names ARE the project's vocabulary.367368- NEVER use technical class name suffixes: `Manager`, `Helper`, `Processor`, `Util`, `Handler`, `Service`.369- Domain methods MUST use domain verbs: `approve()`, `reject()`, `assign()`, `changeStatus()` — NEVER `process()`, `handle()`, `execute()`.370- Boolean properties MUST use `is*`/`has*`/`can*` prefix: `isActive`, `hasPermission`, `canBeDeleted`.371- Status/type enums MUST be co-located with owning entity — NEVER in shared `Enums/` catch-all folder.372- Method parameters MUST use domain nouns — NEVER `data`, `model`, `obj`, `input`, `payload`.373374#### K. Code Smells375376| Smell | Detection Signal | Severity |377| ------------------------ | ------------------------------------------- | -------------------------------- |378| **Fat Entity** | >500 lines with unrelated concerns | MEDIUM — split by domain concept |379| **Feature Envy** | Method uses 5+ properties of another entity | HIGH — wrong responsibility |380| **Data Clump** | 3+ primitives always together | MEDIUM — VO candidate |381| **Primitive Obsession** | Raw `string` for email/phone/money/ID | MEDIUM — domain type opportunity |382| **Leaky Abstraction** | Entity exposes persistence internals | HIGH |383| **Collection Exposure** | Public mutable collection returned directly | HIGH — domain method needed |384| **Constructor Overload** | 5+ params without factory method | MEDIUM |385386#### L. OOP Principles387388- verify SRP: entity represents ONE domain concept — conflating two → flag for split.389- NEVER instantiate infrastructure inside entity (repositories, HTTP clients, loggers) — MUST receive as parameters.390- New behaviors MUST go via new event handlers — NEVER by modifying entity conditionals (Open/Closed).391- Capability traits added via focused interfaces — NEVER monolithic interface bundle (ISP).392- Entity subclasses MUST be substitutable for base — `base.method()` NEVER skipped in override (LSP).393394#### M. Invariant vs Validation Ownership + Failure Signalling (MUST ATTENTION)395396> 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`.397398**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.399400- 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.401- 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.402- 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.403- 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.404- 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.405- flag mutations returning bare `bool` → MEDIUM: loses WHY and is trivially ignored.406- flag silent clamping of bad input (`if (qty < 0) qty = 0`) → HIGH — why: hides a caller bug and persists wrong data with no signal.407408**Detection signal:** business rule text appearing in BOTH a validator/handler and the entity, or appearing ONLY outside the entity.409410#### N. Construction vs Reconstitution (MUST ATTENTION)411412> 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.413414**Think:** trace both paths separately — `new` from a command, and materialization by the ORM/stream fold. Ask what each is allowed to run.415416- 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.417- 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.418- flag creation rules re-run on load (clock checks, uniqueness calls, `startsOn >= today`) → HIGH: historical rows fail to load once the rule tightens.419- 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.420- 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).421- flag 5+ positional constructor params → MEDIUM: group into VOs FIRST, consider a builder only after.422- NEVER flag a framework-mandated non-public parameterless constructor as a violation — verify the discovered persistence convention first.423424**Detection signal:** one public constructor referenced by both the command handler and the ORM/mapping configuration.425426#### O. Event Dispatch Timing + Contract Boundary (MUST ATTENTION)427428> 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.429430**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.431432- 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.433- 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).434- MUST ATTENTION verify the event buffer is cleared after dispatch — an uncleared buffer republishes on the next save (MEDIUM–HIGH by blast radius).435- 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.436- flag fat events carrying the whole aggregate → MEDIUM: violates least privilege and blocks schema evolution. Events carry IDs + the minimal meaningful payload.437- flag events named as commands (`SendEmail`, `UpdateStock`) → MEDIUM: an event states what happened; command-naming re-couples producer to consumer.438- flag handlers with no idempotency guard where delivery is at-least-once → HIGH.439- 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.440441**Detection signal:** dispatch/publish call inside the same transaction scope as the repository save, or an integration-event type imported from the domain assembly.442443#### P. Aggregate Concurrency + Transaction Boundary (MUST ATTENTION)444445> Section F owns aggregate _shape_. This owns what makes "one aggregate per transaction" actually safe under concurrent load.446447**Think:** two users act on the same aggregate at the same instant — what stops the second write from silently discarding the first?448449- 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.450- 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.451- 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.452- 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.453- 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.454455**Detection signal:** repository save of two roots inside one unit-of-work scope, or a root type with no version/timestamp concurrency member.456457---458459## Phase 3: Holistic Synthesis + Fresh-Context Gate460461After 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.462463### 3.1 Model-Level Dimensions (MUST ATTENTION — judged over the whole model, NEVER per file)464465Two concerns are invisible file-by-file and only appear when the model is viewed whole. Run one focused pass each.466467**Dimension 1 — Bounded-context sharing.** **Think:** does one entity class serve two different businesses?468469- 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.470- 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.471- MUST ATTENTION verify a translation boundary exists where contexts meet (anti-corruption layer, mapper, published contract) — direct cross-context entity reuse is HIGH.472- 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.473474**Dimension 2 — Subdomain fit.** **Think:** does this code deserve a rich domain model at all?475476- 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.477- 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 with478479…(truncated)