with one click
domain-analysis
// [Architecture] Use when you need to analyze business domain: bounded contexts, aggregates, entities, ERD, domain events, and cross-context integration.
// [Architecture] Use when you need to analyze business domain: bounded contexts, aggregates, entities, ERD, domain events, and cross-context integration.
[HINT] Download the complete skill directory including SKILL.md and all related files
| name | domain-analysis |
| description | [Architecture] Use when you need to analyze business domain: bounded contexts, aggregates, entities, ERD, domain events, and cross-context integration. |
Codex compatibility note:
- Invoke repository skills with
$skill-namein Codex; this mirrored copy rewrites legacy Claude/skill-namereferences.- Prefer the
plan-hardskill for planning guidance in this Codex mirror.- 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_agentsubagent(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 does not receive Claude hook-based doc injection. 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)Situation-based docs:
backend-patterns-reference.md, domain-entities-reference.md, project-structure-reference.mdfrontend-patterns-reference.md, scss-styling-guide.md, design-system/README.mdfeature-docs-reference.mdintegration-test-reference.mde2e-test-reference.mdcode-review-rules.md plus domain docs above based on changed filesDo 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_progresswhen step starts, setcompletedwhen 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.
Goal: Analyze business domain: bounded contexts, aggregates, entities, VOs, domain events, cross-context relationships. Generate domain model report + ERD.
Workflow:
Key Rules:
Be skeptical. Every claim needs traced proof, confidence percentages >80% to act.
| Signal | Action |
|---|---|
| Same term, different meaning across teams | Separate bounded contexts |
| Different data lifecycles for same concept | Separate contexts |
| Different invariants on same entity | Separate contexts |
| Team ownership conflict (Conway's Law) | Separate contexts |
| Shared DB table touched by two services | Extract shared kernel or introduce ACL |
Ubiquitous Language Rules:
| Situation | Pattern |
|---|---|
| Two teams, joint success/failure, equal power | Partnership |
| Small shared code nucleus, joint governance acceptable | Shared Kernel |
| Downstream can influence upstream roadmap | Customer-Supplier |
| Downstream has no influence on upstream | Conformist |
| External/legacy system with hostile or polluting model | Anti-Corruption Layer (ACL) |
| One upstream, many downstream consumers | Open Host Service + Published Language |
| Integration cost exceeds integration value | Separate Ways |
ACL — when to use: Upstream is external/legacy/third-party (Salesforce, SAP, Workday). Upstream types NEVER cross ACL into domain model.
Shared Kernel — when NOT to use: Teams cannot coordinate on every change → use Customer-Supplier + Published Language instead.
| Question | Entity | Value Object |
|---|---|---|
| Has identity beyond its attributes? | YES | no |
| Can two instances with same data be distinct? | YES | no |
| Has a lifecycle (created, modified, deleted)? | YES | no |
| Identified by an ID in any downstream system? | YES | no |
| Measured or described (quantity, address, money)? | no | YES |
| Replaced rather than modified on change? | no | YES |
| Must be found independently of parent? | YES | no |
Fast heuristics:
| VO | Attributes | Key Invariants |
|---|---|---|
Money | amount: Decimal, currency: Currency | amount ≥ 0, valid ISO currency; Add/Subtract require same currency |
Email | value: string | RFC 5322 format, normalized to lowercase |
Address | street, city, country, postalCode | All fields non-empty; composed of Country + PostalCode VOs |
DateRange | start: DateOnly, end: DateOnly | start ≤ end; operations: Contains, Overlaps, Duration |
PhoneNumber | countryCode, number | E.164 format |
Percentage | value: int | 0 ≤ value ≤ 100 |
| Primitive Usage | Replace With |
|---|---|
string employeeId | EmployeeId typed wrapper |
decimal amount, string currency | Money { amount, currency } |
string street, string city, string zip | Address { ... } |
DateTime start, DateTime end | DateRange { start, end } |
string email | Email { value } |
int percentage | Percentage { value } |
string phoneNumber | PhoneNumber { countryCode, number } |
Rule: Primitive with validation rules, formatting, or always passed grouped with other primitives → missing Value Object.
// Self-validating VO — never an invalid instance in memory
public sealed class Email : PlatformValueObject<Email>
{
private Email(string value) { Value = value; }
public string Value { get; }
public static Email Of(string raw)
{
var normalized = raw?.Trim().ToLowerInvariant();
if (string.IsNullOrWhiteSpace(normalized) || !IsValidFormat(normalized))
throw new DomainException($"Invalid email: {raw}");
return new Email(normalized);
}
}
Rules:
Of() / Create()) enforces invariantsemail = Email.Of(newValue), NEVER email.Value = newValue| Strategy | When to Use | Trade-offs |
|---|---|---|
| Owned types (EF Core) | VO maps to same table as owning entity | Simple, no FK, nullable columns possible |
| Embedded document (MongoDB) | VO stored as subdocument | Natural fit, no joins |
| JSON column | Complex VO, low query frequency on VO fields | Flexible, not queryable by parts |
| Serialized string | Simple VOs (Email, PostalCode) | Compact, unqueryable by parts |
Rule: VOs NEVER have own table with primary key — that makes them entities by infrastructure.
| Strategy | When to Use | Trade-offs |
|---|---|---|
| ULID (default) | New entities in distributed system | Sortable, URL-safe, monotonic, 128-bit |
| UUID v4 | True randomness / security-sensitive IDs | Not sortable, fragmented indexes |
| UUID v7 | Sortable UUID needed | Time-ordered, good index locality |
| Natural key | Domain guarantees permanent uniqueness (SSN, EAN) | Unstable — domain can change |
| Surrogate int | Legacy/single-DB sequences | No distributed generation |
| Composite key | Relationship/join table | Harder to reference from other aggregates |
Rules:
| Anemic (Anti-Pattern) | Rich (Correct) |
|---|---|
| Entity is data bag, logic in services | Entity contains behavior + invariants |
public set on all properties | Private setters, mutation via named methods |
EmployeeService.Activate(employee) | employee.Activate() |
| Service checks rules then mutates entity | Entity refuses invalid state transitions |
| Logic duplicated across services | Single authoritative location in entity |
Tell Don't Ask Principle:
if (employee.Status == Active) { employee.Status = Suspended; } (external ask + mutate)employee.Suspend(reason) (entity enforces its own invariants)public class Employee : RootAuditedEntity<Employee, string, string>
{
private Employee() { } // ORM hydration only
public static Employee Create(string name, Email email, DepartmentId departmentId)
{
Guard.NotNullOrWhitespace(name, nameof(name));
Guard.NotNull(email, nameof(email));
return new Employee
{
Id = Ulid.NewUlid().ToString(),
Name = name,
Email = email,
DepartmentId = departmentId,
Status = EmployeeStatus.Active
};
}
public void Terminate(string reason, DateOnly terminationDate)
{
if (Status == EmployeeStatus.Terminated)
throw new DomainException("Employee already terminated");
if (terminationDate < DateOnly.FromDateTime(DateTime.UtcNow))
throw new DomainException("Termination date cannot be in the past");
Status = EmployeeStatus.Terminated;
TerminationReason = reason;
TerminationDate = terminationDate;
AddDomainEvent(new EmployeeTerminatedDomainEvent(Id, terminationDate));
}
}
Document ALL transitions explicitly. Unmodeled transitions throw DomainException.
Draft → Submitted (Submit())
Submitted → Approved (Approve(approverId))
Submitted → Rejected (Reject(reason))
Approved → Active (Activate())
Active → Suspended (Suspend(reason))
Suspended → Active (Reinstate())
Active → Archived (Archive())
| Pattern | When to Use |
|---|---|
| Status enum + transition methods | Simple linear/branching lifecycles (most cases) |
| State pattern (class per state) | Complex per-state behavior, many states |
| Event sourcing | Full audit trail + point-in-time reconstruction required |
| Layer | What It Validates | Returns |
|---|---|---|
| Value Object | Single-value format/range invariants | Exception or Result at construction |
| Entity method | Aggregate consistency rules, state transitions | DomainException |
| Application service | Cross-aggregate rules, authorization, existence | ValidationResult / ProblemDetails |
| Infrastructure | DB constraints (last resort, NEVER first line) | Database exception |
Decision rule:
Use when: construction requires domain logic, multiple paths, raises domain events, or object graph initialization.
Naming:
Employee.Create(...) — primary creationEmployee.Hire(...) — semantically loaded creation (domain language)Two time axes: valid time (fact true in real world) + transaction time (recorded in system).
EmployeeSalary {
validFrom: DateOnly // valid time: salary effective from
validTo: DateOnly // valid time: salary effective until
recordedAt: DateTime // transaction time: when entered into system
}
Use when: regulatory compliance, retroactive corrections, "as-of" queries.
| Heuristic | Guideline |
|---|---|
| Default | Start with single-entity aggregate unless invariant demands more |
| Add member | Only when invariant requires atomic consistency across root + member |
| Max size | > 5 entities → redesign; likely missing sub-aggregates |
| Concurrent writes conflict | Reduce aggregate size |
Rule: Outside code NEVER holds direct reference to non-root entity within aggregate.
| Rule | Detail |
|---|---|
| Reference by ID only | NEVER order.Customer.Name — load separately |
| No FK object navigation | CustomerId field, NEVER Customer Customer navigation property |
| Cross-aggregate transactions are eventual | Need them in same transaction → boundaries are wrong |
| Deletion cascade | Domain event → handler → compensating action in other aggregate |
public void AddLineItem(ProductId productId, int quantity, Money unitPrice)
{
if (Status != OrderStatus.Draft)
throw new DomainException("Cannot modify confirmed order");
if (LineItems.Count >= 50)
throw new DomainException("Order cannot exceed 50 line items");
var item = OrderLineItem.Create(productId, quantity, unitPrice);
_lineItems.Add(item);
RecalculateTotal(); // invariant: Total == sum(lineItems)
}
| Pattern | When to Use |
|---|---|
| Single-entity aggregate | Default — most entities are their own aggregate |
| Nested aggregate | Invariant requires atomic consistency across root + children |
| Aggregate with VOs | Root + embedded value objects (no IDs, no own table) |
| Situation | Acceptable Pragmatism |
|---|---|
| ORM limitation (EF owned entities) | Allow private owned collections even if not strictly necessary |
| Performance — 1-query load | Embed child data as VO/owned type rather than separate aggregate |
| Legacy schema migration | Accept cross-aggregate FK temporarily, document as debt |
Rule: Breaking aggregate rules acceptable ONLY when explicitly documented as technical debt with mitigation plan.
| Cardinality | Mermaid | When to Use |
|---|---|---|
| 1:1 | |o--o| | Same-table extension, optional sub-type, shared lifecycle |
| 1:N | |o--{ | Parent-child, one entity owns many dependent records |
| M:N | }o--o{ | Peer relationship; ALWAYS use explicit join/association entity |
M:N rule: Relationship has attributes (date joined, role) → make join table explicit named entity.
1:1 decision: Same concept with optional attributes → same table. Different concepts with independent lifecycles → separate tables with FK.
| Normal Form | Rule | Use For |
|---|---|---|
| 1NF | Atomic values, no repeating groups | Always — baseline |
| 2NF | No partial dependency on composite key | Composite PKs only |
| 3NF | No transitive dependencies | OLTP — standard target |
| BCNF | Every determinant is a candidate key | When 3NF still has anomalies |
| Denormalized | Intentional redundancy | Read models, projections, OLAP |
Rule: 3NF for OLTP write models; denormalize only in read models/projections with documented justification.
| Type | FK in Child PK? | Child Existence |
|---|---|---|
| Identifying | YES (FK is part of PK) | Child cannot exist without parent (line item without order) |
| Non-identifying | NO (FK is separate column) | Child can exist independently (employee without department) |
Mapping to DDD: Identifying relationship → child entity inside parent aggregate. Non-identifying FK → likely separate aggregates.
ExternalEntityId (string/ULID) — ID only, no relationship line| Anti-Pattern | Problem | Fix |
|---|---|---|
| God table (50+ columns) | Every feature adds more columns | Extract sub-entities, decompose by bounded context |
| Cross-service FK | Direct FK across microservice schemas | Replicate needed data, use events to sync |
| Polymorphic association | entityType + entityId columns | Separate tables per concrete type or JSON column |
| EAV (Entity-Attribute-Value) | Key-value rows replacing typed columns | JSON column or explicit schema with migration |
| Implicit M:N (two FK cols, no PK) | Hard to add relationship attributes | Explicit join table with surrogate PK |
| Nullable FK everywhere | Unclear cardinality | Separate optional relationship into explicit table |
| ERD Pattern | DDD Mapping |
|---|---|
| Parent-child with identifying relationship | Child entity inside parent aggregate |
| Parent-child with non-identifying FK | Likely separate aggregates (independent lifecycle) |
| M:N join table with no extra attributes | Both sides separate aggregates, IDs in domain events |
| M:N join table with attributes | Association entity as separate aggregate |
| Strong entity + many weak dependents | Root entity + owned collection aggregate |
Format: {AggregateNoun}{PastTenseVerb} — what happened, not what to do.
| Good | Bad |
|---|---|
EmployeeTerminated | TerminateEmployee (command naming) |
OrderConfirmed | OrderStatusChanged (too generic) |
PaymentProcessed | PaymentComplete (not past tense) |
SalaryBandUpdated | SalaryChanged (vague) |
| Decision | Rule |
|---|---|
| Minimal vs fat | Minimal (default): AggregateId + what changed. Consumer queries for rest if needed |
| Fat event | Accept when: round-trip cost high AND consumers known AND staleness acceptable |
| Required fields always | AggregateId, OccurredOn: DateTime (UTC), Version, CorrelationId |
| No mutable references | Payload contains value copies, not object references |
| Dimension | Domain Event | Integration Event |
|---|---|---|
| Scope | Within one bounded context | Across bounded contexts |
| Delivery | In-process, post-commit | Via message bus (RabbitMQ, Kafka) |
| Schema ownership | Domain owns, internal | Published Language contract |
| Versioning | Internal refactor freely | Versioned, backward-compatible |
| Failure handling | Transaction rollback | At-least-once delivery, idempotent consumer |
Rule: Domain event raised → in-process handlers fire → if cross-service needed, handler publishes integration event to message bus.
| Strategy | Mechanism | Trade-offs |
|---|---|---|
| Additive only | NEVER remove/rename fields, only add | Simple, payload bloats over time |
| Multiple versions | OrderConfirmedV1, OrderConfirmedV2 | Clear versioning, consumers handle both |
| Upcasting | Transform old events to new on deserialization | Transparent to consumers, complex infra |
Backward compatibility rules:
GetActiveEmployeesInDepartment() not FindAll(e => e.Status == Active)IQueryable, no DbSet, no connection strings in interfaceTask<T> or IAsyncEnumerable<T>| Repository | DAO |
|---|---|
| Domain-oriented interface | Data-oriented interface |
| Returns entities/VOs | Returns DTOs or raw data |
| Used in application/domain layer | Used in infrastructure layer |
| Hides persistence mechanism | Often tied to persistence mechanism |
Use when: rule used in multiple places, warrants naming + testing, needs composition.
// Static expression on entity — composable, testable
public static Expression<Func<Employee, bool>> ByDepartmentExpression(string deptId)
=> e => e.DepartmentId == deptId && e.Status == EmployeeStatus.Active;
When NOT to use Specification: Simple single-use predicate → inline lambda. Rule only used once → repository method directly.
| Anti-Pattern | Detection Signal | Fix |
|---|---|---|
| Anemic domain model | Services have entity-specific logic; entity has all public setters | Move logic to entity |
| God aggregate | Aggregate > 5 entities or 100+ ms load time | Extract sub-aggregates |
| Leaky aggregate | External code mutates child entities directly | Private setters + root mutation methods |
| Primitive obsession | 3+ primitives always travel together as group | Introduce Value Object |
| Implicit concept | Domain expert names it, code doesn't model it | Explicit class |
| Feature envy | Method uses more of B's data than A's | Move method to B |
| Getter/setter entity | All mutation via property assignment, no intent-named methods | Replace with Terminate(), Approve(), etc. |
| Cross-aggregate loading | Full aggregate loaded just to read one field | Pass scalar; resolve in app service |
| Side effects in handler | Command handler calls multiple services after save | Domain event + separate handlers |
| Cross-service FK | Database FK across microservice schemas | ID reference + event-driven sync |
| Shared Kernel overuse | Two teams, one shared model, constant coordination overhead | Split to Customer-Supplier |
| Missing ACL | External model types bleed into domain classes | ACL at integration boundary |
plans/*$plan-hard.md sorted by modification time — find active plan directoryplan.md — project scope, goals, prior decisions{plan-dir}$research/*.md — avoid duplicating prior workdocs/project-reference/domain-entities-reference.md (if exists) — project's single source of truth for domain entities (read directly when relevant; do not rely on hook-injected conversation text){plan-dir} variable — all outputs write to this directoryIf no plan directory, create using naming convention from session context.
MUST ATTENTION update {plan-dir}$plan-hard.md with domain model summary section after completing analysis.
Read artifacts from prior workflow steps (search plans/ + team-artifacts/):
{plan-dir}$plan-hard.md) — scope, goals, constraintsExtract and list:
Group related entities using DDD principles. Apply context boundary signals from reference table above.
### Bounded Context: {Name}
**Purpose:** {What this context owns — one sentence}
**Classification:** Core domain / Supporting / Generic
**Key Responsibility:** {primary business capability}
**Team ownership:** {suggested team or role}
**Ubiquitous language:** {key terms and their meaning in this context}
Context boundary tests:
MANDATORY IMPORTANT MUST ATTENTION present identified contexts to user via a direct user question:
Per bounded context: classify each concept using Entity vs VO matrix above, then apply aggregate boundary rules.
### {Context Name}
**Aggregate Root:** {EntityName}
**Identity:** {ULID / UUID / Natural key — justify}
**Lifecycle states:** {Draft → Active → Archived, etc.}
- **Child Entities:** {list — share aggregate boundary, identifying FK}
- **Value Objects:** {list — immutable, no identity, embedded}
- **Invariants:** {business rules this aggregate enforces atomically}
- **Factory method:** {Employee.Create(...) / Employee.Hire(...)}
**Other Aggregates in this Context:**
- {Entity} — {purpose, identity strategy, lifecycle}
| Entity | Classification | Identity | Key Fields | Lifecycle States | Invariants |
|---|---|---|---|---|---|
| {Name} | Aggregate Root / Entity / Value Object | ULID / UUID / Composite | {fields} | {states} | {business rules} |
VO Composition — MUST ATTENTION verify:
Aggregate Boundary — MUST ATTENTION verify:
| From | To | Type | Cardinality | Relationship Kind | Description |
| ---- | --------- | ---- | --------------- | ----------------------- | ------------------------ |
| Job | Candidate | M:N | via Application | Non-identifying (assoc) | Candidates apply to jobs |
Apply identifying vs non-identifying rule:
| Upstream Context | Downstream Context | Pattern | Integration Point | Sync Mechanism |
| ---------------- | ------------------ | ------- | -------------------------- | -------------- |
| Recruitment | Employee | ACL | Candidate becomes Employee | Domain event |
Integration patterns to apply (see context map reference table above):
Identify events crossing bounded context boundaries. Apply naming: {AggregateNoun}{PastTenseVerb}.
| Event | Source Context | Target Context(s) | Payload (minimal) | Trigger |
|---|---|---|---|---|
CandidateHired | Recruitment | Employee, Onboarding | candidateId, jobId, hireDate | Offer accepted |
Event design — MUST ATTENTION verify:
Produce Mermaid ER diagram. Apply ERD-to-Aggregate mapping + anti-patterns from reference above.
```mermaid
erDiagram
%% Bounded Context: {Name}
ENTITY_A ||--o{ ENTITY_B: "has many"
ENTITY_A {
string id PK
string name
string status
datetime createdAt
}
ENTITY_B {
string id PK
string entityAId FK
string externalServiceId "ID only - no FK across services"
string type
}
```
ERD requirements:
%% Context: ...)ERD — MUST ATTENTION verify before finalizing:
MANDATORY IMPORTANT MUST ATTENTION present domain model and ask 5-8 questions via a direct user question:
After user confirms, update report with final decisions and mark as status: confirmed.
MANDATORY IMPORTANT MUST ATTENTION compare domain analysis results against docs/project-reference/domain-entities-reference.md (if exists):
If docs/project-reference/domain-entities-reference.md does NOT exist, ask user:
After user confirms: update/create docs/project-reference/domain-entities-reference.md following existing format. Append new entities to appropriate bounded context section. Update field lists + relationships for modified entities.
Read {plan-dir}$plan-hard.md, append/update ## Domain Model section:
## Domain Model
- **Bounded Contexts:** {N} — {list names with context map patterns between them}
- **Total Entities:** {N} ({N} aggregates, {N} child entities, {N} value objects)
- **Domain Events:** {N} cross-context events
- **Key Aggregates:** {list with invariant summaries}
- **Key Relationships:** {summary of critical relationships}
- **ERD:** See `phase-01-domain-model.md`
- **Full Analysis:** See `research/domain-analysis.md`
{plan-dir}$research/domain-analysis.md # Full domain analysis report
{plan-dir}/phase-01-domain-model.md # Confirmed domain model with ERD
{plan-dir}$plan-hard.md # Updated with domain model summary
docs/project-reference/domain-entities-reference.md # Updated/created with new/modified entities
Report structure:
Report must be ≤250 lines. Use tables over prose.
MANDATORY IMPORTANT MUST ATTENTION break work into small todo tasks using task tracking BEFORE starting. MANDATORY IMPORTANT MUST ATTENTION validate EVERY bounded context and key relationship with user via a direct user question. MANDATORY IMPORTANT MUST ATTENTION include Mermaid ERD and confidence % for all architectural decisions. MANDATORY IMPORTANT MUST ATTENTION add a final review todo task to verify work quality.
MANDATORY IMPORTANT MUST ATTENTION — NO EXCEPTIONS after completing this skill, use a direct user question to present these options:
MANDATORY IMPORTANT MUST ATTENTION use task tracking to break ALL work into small tasks BEFORE starting. MANDATORY IMPORTANT MUST ATTENTION use a direct user question at EVERY decision point — validate every bounded context and entity relationship with user. MANDATORY IMPORTANT MUST ATTENTION produce ERD diagram (Mermaid) and domain model report with confidence %.
External Memory: For complex or lengthy work (research, analysis, scan, review), write intermediate findings and final results to a report file in
plans/reports/— prevents context loss and serves as deliverable.
Evidence Gate: MANDATORY IMPORTANT MUST ATTENTION — every claim, finding, and recommendation requires
file:lineproof or traced evidence with confidence percentage (>80% to act, <80% must verify first).
AI Mistake Prevention — Failure modes to avoid on every task:
Check downstream references before deleting. Deleting components causes documentation and code staleness cascades. Map all referencing files before removal. Verify AI-generated content against actual code. AI hallucinates APIs, class names, and method signatures. Always grep to confirm existence before documenting or referencing. Trace full dependency chain after edits. Changing a definition misses downstream variables and consumers derived from it. Always trace the full chain. Trace ALL code paths when verifying correctness. Confirming code exists is not confirming it executes. Always trace early exits, error branches, and conditional skips — not just happy path. When debugging, ask "whose responsibility?" before fixing. Trace whether bug is in caller (wrong data) or callee (wrong handling). Fix at responsible layer — never patch symptom site. Assume existing values are intentional — ask WHY before changing. Before changing any constant, limit, flag, or pattern: read comments, check git blame, examine surrounding code. Verify ALL affected outputs, not just the first. Changes touching multiple stacks require verifying EVERY output. One green check is not all green checks. Holistic-first debugging — resist nearest-attention trap. When investigating any failure, list EVERY precondition first (config, env vars, DB names, endpoints, DI registrations, data preconditions), then verify each against evidence before forming any code-layer hypothesis. Surgical changes — apply the diff test. Bug fix: every changed line must trace directly to the bug. Don't restyle or improve adjacent code. Enhancement task: implement improvements AND announce them explicitly. Surface ambiguity before coding — don't pick silently. If request has multiple interpretations, present each with effort estimate and ask. Never assume all-records, file-based, or more complex path.
Critical Thinking Mindset — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act. Anti-hallucination: Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence root of all hallucination.
MUST ATTENTION apply critical thinking — every claim needs traced proof, confidence >80% to act. Anti-hallucination: never present guess as fact.
MUST ATTENTION apply AI mistake prevention — holistic-first debugging, fix at responsible layer, surface ambiguity before coding, re-read files after compaction.
IMPORTANT MUST ATTENTION follow declared step order for this skill; NEVER skip, reorder, or merge steps without explicit user approval
IMPORTANT MUST ATTENTION for every step/sub-skill call: set in_progress before execution, set completed after execution
IMPORTANT MUST ATTENTION every skipped step MUST include explicit reason; every completed step MUST include concise evidence
IMPORTANT MUST ATTENTION if Task tools unavailable, maintain an equivalent step-by-step plan tracker with synchronized statuses
MUST ATTENTION task tracking ALL tasks BEFORE starting — never begin without task breakdown
MUST ATTENTION validate EVERY bounded context + key relationship with user via a direct user question — never auto-decide
MUST ATTENTION domain events ALWAYS follow {AggregateNoun}{PastTenseVerb} naming — NEVER command-style
MUST ATTENTION NEVER have cross-service FK in ERD — ID reference + event-driven sync only
MUST ATTENTION entity vs VO classification: replace with equal-valued copy breaks nothing? → VO. Else → Entity
MUST ATTENTION add final review task to verify work quality
[TASK-PLANNING] Before acting, analyze task scope and systematically break it into small todo tasks and sub-tasks using task tracking.
[IMPORTANT] Analyze how big the task is and break it into many small todo tasks systematically before starting — this is very important.
Source: .claude/hooks/lib/prompt-injections.cjs + .claude/.ck.json
$workflow-start <workflowId> for standard; sequence custom steps manually[CRITICAL] Hard-won project debugging/architecture rules. MUST ATTENTION apply BEFORE forming hypothesis or writing code.
Goal: Prevent recurrence of known failure patterns — debugging, architecture, naming, AI orchestration, environment.
Top Rules (apply always):
ExecuteInjectScopedAsync for parallel async + repo/UoW — NEVER ExecuteUowTaskwhere python/where py) — NEVER assume python/python3 resolvesExecuteInjectScopedAsync, NEVER ExecuteUowTask. ExecuteUowTask creates new UoW but reuses outer DI scope (same DbContext) — parallel iterations sharing non-thread-safe DbContext silently corrupt data. ExecuteInjectScopedAsync creates new UoW + new DI scope (fresh repo per iteration).AccountUserEntityEventBusMessage = Accounts owns). Core services (Accounts, Communication) are leaders. Feature services (Growth, Talents) sending to core MUST use {CoreServiceName}...RequestBusMessage — never define own event for core to consume.HrManagerOrHrOrPayrollHrOperationsPolicy names set members, not what it guards. Add role → rename = broken abstraction. Rule: names express DOES/GUARDS, not CONTAINS. Test: adding/removing member forces rename? YES = content-driven = bad → rename to purpose (e.g., HrOperationsAccessPolicy). Nuance: "Or" fine in behavioral idioms (FirstOrDefault, SuccessOrThrow) — expresses HAPPENS, not membership.python/python3 resolves — verify alias first. Python may not be in bash PATH under those names. Check: where python / where py. Prefer py (Windows Python Launcher) for one-liners, node if JS alternative exists.Test-specific lessons →
docs/project-reference/integration-test-reference.mdLessons Learned section. Production-code anti-patterns →docs/project-reference/backend-patterns-reference.mdAnti-Patterns section. Generic debugging/refactoring reminders → System Lessons in.claude/hooks/lib/prompt-injections.cjs.
ExecuteInjectScopedAsync, NEVER ExecuteUowTask (shared DbContext = silent data corruption){CoreServiceName}...RequestBusMessagepython/python3 resolves — run where python/where py first, use py launcher or nodeBreak work into small tasks (task tracking) before starting. Add final task: "Analyze AI mistakes & lessons learned".
Extract lessons — ROOT CAUSE ONLY, not symptom fixes:
$learn.$code-review/$code-simplifier/$security/$lint catch this?" — Yes → improve review skill instead.$learn.
[TASK-PLANNING] [MANDATORY] BEFORE executing any workflow or skill step, create/update task tracking for all planned steps, then keep it synchronized as each step starts/completes.