用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
直接命令不会经过审查 Prompt;运行前请先检查来源。
npx skills add https://github.com/duc01226/EasyPlatform --skill review-domain-entities命令会保持在同一行。复制前请横向滚动并检查完整内容。
想先保存到本地?可下载 SkillsMP 当前能够提供的文件。
[Architecture] Use when designing solution architecture across backend, frontend, deployment, monitoring, testing, and code quality.
[Utilities] Use when you need to answer technical and architectural questions.
[Content] Use when you need to brainstorm as a PO/BA — structured ideation for problem-solving, new product creation, or feature enhancement.
正在显示 SKILL.md
基于 SOC 职业分类
| name | review-domain-entities |
| description | [DDD Quality] Use when you need to review domain entities and value objects for DDD design quality. |
Codex compatibility note:
- Invoke repository skills with
$skill-namein Codex; this mirrored copy rewrites legacy Claude/skill-namereferences.- 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 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:
backend-patterns-reference.md, domain-entities-reference.md, project-structure-reference.mdfrontend-patterns-reference.md, scss-styling-guide.md, design-system/README.mddocs/specs/ pathing, or TC format: feature-spec-reference.md, spec-system-reference.md, spec-principles.mdworkflow-spec-test-code-cycle-reference.md plus the spec docs abovespec-system-reference.md and source Feature Specs under docs/specs/integration-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: 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:
validate() overrides, leaked persistence/business logic, missing identity markers) BEFORE reading individual files, and write every grep result to the report immediately.file:line evidence at confidence >80%.Workflow:
Key Rules:
file:line evidenceSeverity 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 |
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?
Apply this lens before invoking any specific rule, pattern, or checklist below — if a downstream rule raises change cost, this principle wins.
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# 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} |
If project reference docs exist → read them and extract: service-specific base class requirements, documented anti-patterns, naming conventions, cross-service rules.
Apply mode-appropriate command from Mode Detection table, adapted to discovered stack.
# 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).
Create report FIRST: plans/reports/domain-entities-review-{date}-{slug}.md
Initialize with: Mode, Tech Stack, Discovered Conventions, Blast Radius Summary.
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:
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.
| 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 |
For EACH entity/VO file: read file → append findings to report IMMEDIATELY. NEVER batch.
Entity = unique identity persisting across time. VO = defined by attributes, immutable, interchangeable when equal. NEVER swap roles.
NEVER assume base class — ALWAYS use discovered values from Phase 0. Project docs override generic rules.
Mutable VOs are a design contradiction — they imply identity through mutation, which entities have, not VOs.
validate() overridden when VO has constraints (format, range, required).Create(), New(), Of(), From*().Anemic model = entity is data bag, all logic in handlers. Fix: move behavior to entity (lowest layer).
changeStatus(), approve(), assign()).ensureCan*() on entity.entity.a=x; entity.b=y; entity.c=z) without validation → domain method candidate.Detection signal: entity.property = value assignments (non-audit) in application layer = anemic model signal.
Invariants enforced only in application layer = domain can reach invalid state via any other entry point.
validate(), constructor guard, or factory) — NEVER handler-only enforcement.ensureCan*() / validateCan*() methods on entity.ArgumentException, IllegalArgumentException, Error, ValueError all WRONG.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.
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.
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.
Aggregate = consistency boundary. All invariants must flow through root. Cross-aggregate coupling = transaction trap.
string productId NOT Product product).Navigation properties serializing into each other = circular reference crash or infinite memory allocation.
Entity raises events → handlers react. NEVER inline side effects in entity domain methods.
{Entity}{Action}Event or {Entity}{PastTense}Event (e.g., OrderShippedEvent).Query logic belongs on entity (lowest layer) — duplication in repos/handlers = wrong layer.
isActive(), filteredByDepartment()).Technical names break the domain model. Entity names ARE the project's vocabulary.
Manager, Helper, Processor, Util, Handler, Service.approve(), reject(), assign(), changeStatus() — NEVER process(), handle(), execute().is*/has*/can* prefix: isActive, hasPermission, canBeDeleted.Enums/ catch-all folder.data, model, obj, input, payload.| 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 |
base.method() NEVER skipped in override (LSP).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.
Spawn a fresh code-reviewer sub-agent only when one of these conditions is true:
When a fresh-context pass is triggered, build the Agent call dynamically — set Target Files and Reference Docs from Phase 0/1 discoveries:
spawn_agent({
description: "Fresh full DDD entity review after validated fixes or explicit high-risk trigger",
agent_type: "code-reviewer",
prompt: `
## Task
Review domain entity and value object files holistically for DDD design quality:
- Domain model coherence: entities vs VOs correctly classified across entire model?
- Aggregate boundary consistency across service/module?
- Anemic domain model: business logic consistently in entity or scattered in handlers?
- Navigation property hygiene across entire domain layer
- Ubiquitous language consistency across all entities
- Missed cross-entity interactions
## Review Mode
Fresh full review after a validated fix cycle or explicit high-risk trigger. ZERO memory of prior rounds. Re-read all target files from scratch via own tool calls.
## Protocols (follow VERBATIM)
### Evidence-Based Reasoning
Every claim needs proof. Cite file:line or grep results. Confidence: >80% act, 60-80% verify first, <60% DO NOT report.
NEVER write: "obviously", "I think", "should be", "probably".
### Project-Specific Discovery (MANDATORY before any finding)
1. Check docs/project-reference/ for entity reference docs, backend patterns, code review rules
2. grep -rn "class.*Entity\|class.*BaseEntity\|class.*RootEntity" <source-root>/ | head -10
3. grep -rn "ValueObject\|@ValueObject\|AbstractValueObject" <source-root>/ | head -10
4. Read discovered project reference docs — extract project-specific rules
5. NEVER flag violations contradicting discovered project conventions — verify against docs first
### Bug Detection for Domain Entities
Check every entity:
1. Null Safety: navigation properties guarded before use? Computed properties NPE-safe?
2. Boundary Conditions: empty collections in domain methods? Zero/negative invariants?
3. Error Handling: domain violations using project-specific exception type — NEVER raw language exceptions?
4. Aggregate Safety: child collections mutable bypassing domain methods?
5. Serialization Safety: navigation properties missing serialize-ignore annotation?
### DDD Design Patterns Quality
1. Entity = identity + lifecycle. VO = structural equality + immutable. NEVER swap roles.
2. Invariants enforced at entity level (lowest layer) — NEVER application layer only.
3. Aggregate: only root has repository; cross-aggregate = ID only; child mutations = domain method.
4. Domain events raised in entity — NEVER inline side effects in entity methods.
5. Anemic model: entity has no domain methods + handlers contain all logic → CRITICAL violation.
### Fix-Layer Accountability
NEVER fix at crash site. Validation fails because handler skips entity validate()? → fix entity, not handler. Aggregate boundary violated? → fix entity relationship, not handler defensiveness.
### Graph-Assisted Investigation
When .code-graph/graph.db exists: run trace --direction both on 2-3 entity files.
CLI: python .claude/scripts/code_graph trace <file> --direction both --json --node-mode file
## Reference Docs
{insert docs discovered in Phase 0}
If none: read 3 existing entity files to infer project conventions before reviewing.
## Target Files
{insert entity/VO file list from Phase 1}
## Output
Write to plans/reports/domain-entities-rerun{N}-{date}.md:
- Status: PASS | FAIL
- Critical Issues (file:line evidence)
- High Priority Issues (file:line evidence)
- Cross-cutting DDD concerns
- Aggregate model coherence assessment
- Refactoring priority
Return report path and status. Every finding MUST have file:line evidence.
`
})
After sub-agent returns:
## Re-Review {N} Findings in main report — NEVER filter or override## Domain Entities DDD Review — Final Report
**Mode:** {scan | changes}
**Tech Stack:** {discovered}
**Entity Base Classes:** {discovered from codebase}
**VO Base Classes:** {discovered from codebase}
**Scope / Date / Entity Count:** {values}
## Blast Radius Summary
Graph risk: {HIGH | MEDIUM | LOW | N/A} | Downstream consumers: {N}
## Health Score
{score}/100 — 100 - (CRITICAL×25 + HIGH×10 + MEDIUM×3 + LOW×1), min 0
## Critical Issues (block merge)
{severity} | {description} | {file:line} | {fix}
## High Priority Issues (must fix)
{severity} | {description} | {file:line} | {fix}
## Medium Issues (should fix)
{severity} | {description} | {file:line} | {fix}
## Low / Informational
{severity} | {description} | {file:line} | {fix}
## Re-Review Findings (if a fresh full re-review ran)
{integrated — not filtered}
## Positive Observations
{observation} | {evidence}
## Refactoring Priority (highest-impact first)
{priority} | {target} | {reason}
## Repository-Specific Rules Applied
{rule} | {evidence}
## Unresolved Questions
{question} | {owner/next step}
| Question | YES → | NO → |
|---|---|---|
| Needs unique persistent identity? | Entity | VO candidate |
| Changes state after creation? | Entity | VO candidate |
| Snapshot at moment in time? | VO | Entity candidate |
| Defined by attributes, not identity? | VO | Entity |
| Two instances with same data interchangeable? | VO | Entity |
| Needs repository? | Aggregate Root | Entity or VO |
| Location | When to Use |
|---|---|
| Constructor / Factory | Invariants must hold from creation |
validate() override | State invariants run before persistence |
ensureCan*() guard | Operation preconditions (throw domain exception) |
| Before-delete hook | Pre-delete constraints |
| Application layer ONLY | ← NEVER — always enforce in entity too |
CORRECT — cross-aggregate by ID:
Entity A { string EntityBId; EntityB? entityB; } ← ID + optional navigation
WRONG — cross-aggregate by object:
Entity A { EntityB entityB; } ← object reference = implicit coupling
CORRECT — child mutation via domain method:
order.addLine(product, quantity);
WRONG — direct collection mutation:
order.lines.add(new OrderLine(product, quantity));
Fat Entity: file > 500 lines, > 20 properties → split by domain concept
Feature Envy: method accesses 5+ properties of another entity → move to that entity
Data Clump: 3+ primitives always travel together → extract as Value Object
Primitive Obs: string email, string userId, decimal price → wrap in domain type
Anemic Model: entity has 0 domain methods + all logic in handlers → move logic down
NON-NEGOTIABLE: 10+ entity files in scope → switch to parallel sub-agents automatically.
"Detected {N} entity files. Switching to parallel DDD review protocol."code-reviewer sub-agents with run_in_background: true (one per group)plans/reports/domain-entities-{group}-round1-{date}.mdDomain Entities DDD Review
Health Score: {N}/100
Critical Issues: (block merge)
- {issue}: file:line — description + fix
High Priority: (must fix)
- {issue}: file:line — description + fix
Medium Issues: (should fix)
Positive Observations:
Unresolved Questions:
Report: plans/reports/domain-entities-review-{date}-{slug}.md
Purpose: Adversarial validation of own findings BEFORE handoff. Catches over-flagged Highs, false positives, and severity inflation at the source rather than letting them propagate downstream.
Trigger: Any finding produced (Critical, High, Medium, OR Low). Skip ONLY when the report's verdict is unconditional PASS with literally zero findings.
Protocol:
plans/reports/{skill}-{date}-{slug}.md$why-review skill with arg: validate findings in plans/reports/{skill}-{date}-{slug}.md — verify each finding has file:line proof, steel-man each rejected interpretation, and stress-test severity classificationsplans/reports/why-review-validate-{date}.md## Why-Review Validation Notes section citing what changed and why## Why-Review Validation line to own report stating "All N findings re-validated against actual code; no severity changes."Skip conditions (record explicit reason if skipping):
Why this exists: AI sub-agent reports inherit confirmation bias — the orchestrator absorbs severity claims as ground truth. The 2026-05-09 review incident produced 5 Highs; adversarial validation demoted 3 of them. Codify this as standard practice.
MUST ATTENTION use a direct user question after completing to present:
$fix (Recommended if FAIL) — Fix critical and high-priority issues$scan --target=domain-entities — Update domain-entities-reference.md (scan mode)$integration-test — Add integration tests for newly-enforced invariants$docs-update — Update feature docs if entity contracts changed[IMPORTANT] task tracking for ALL phases BEFORE starting. Mark each completed immediately.
CRITICAL RULES — (1) MUST ATTENTION run Phase 0 project discovery FIRST — discovered conventions override ALL generic rules. (2) Validate findings before fixes; after validated fixes, restart a full review before declaring PASS. A clean review pass ENDS the review. (3) NEVER report a finding without
file:lineevidence.
Prerequisites — MUST ATTENTION discover project-specific rules FIRST:
Read
docs/project-reference/(entity reference, backend patterns, code review rules) andCLAUDE.md. Find entity/VO base classes, validation API, domain exception type, persistence annotations. Infer from 3+ existing entity files if no docs exist. NEVER apply generic rules that contradict discovered project conventions.
Evidence Gate: Every finding requires
file:lineproof or grep result. Confidence >80% → report. <60% → state uncertainty explicitly.
Determine mode BEFORE any other work:
| Invocation | Mode | Scope |
|---|---|---|
$review-domain-entities (default) | changes | Changed domain entity files from git diff |
$review-domain-entities changes | changes | Changed domain entity files |
$review-domain-entities scan | scan | All entity/VO files in domain layer directories |
$review-domain-entities scan <module> | scan-service | Entities in named module only |
Entity file detection — adapt to discovered stack:
git diff --name-only HEAD
rg --files {configured-source-roots}
Filter those results using the entity/value-object/aggregate naming conventions discovered from project config and project-reference docs. Never hardcode source roots, extensions, or framework folder names from this skill.
If no domain entity files match in changes mode → announce "No domain entity changes detected" and report clean.
Source/test drift check. For coding, fix, debug, investigation, test, or review work: when source behavior changes, inspect affected unit/integration/E2E tests and decide from evidence whether tests should change to match intended behavior or the source change is an unintended bug to fix. Do not write tests for migration code; schema/data migrations are one-time execution paths, not core application logic.
AI Mistake Prevention — Failure modes to avoid on every task:
Re-read files after context changes. Context compaction, resume, or long-running work can make memory stale; verify current files before acting. Verify generated content against source evidence. AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing. Check downstream references before deleting or renaming. Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first. Trace the full impact chain after edits. Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done. Verify ALL affected outputs, not just the first. One green check is not all green checks; validate every output surface the change can affect. Assume existing values are intentional — ask WHY before changing. Before changing a constant, limit, flag, wording, or pattern, read nearby context and history. Surface ambiguity before acting — don't pick silently. Multiple valid interpretations require an explicit question or stated assumption with risk. Keep shared guidance role-relevant. Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
Nested Task Expansion Contract — For workflow-step invocation, the
[Workflow] ...row is only a parent container; the child skill still creates visible phase tasks.
- Call the current task list first. If a matching active parent workflow row exists, set
nested=trueand recordparentTaskId; otherwise run standalone.- Create one task per declared phase before phase work. When nested, prefix subjects
[N.M] $skill-name — phase.- When nested, link the parent with
TaskUpdate(parentTaskId, addBlockedBy: [childIds]).- Orchestrators must pre-expand a child skill's phase list and link the workflow row before invoking that child skill or sub-agent.
- Mark exactly one child
in_progressbefore work andcompletedimmediately after evidence is written.- Complete the parent only after all child tasks are completed or explicitly cancelled with reason.
Blocked until: the current task list done, child phases created, parent linked when nested, first child marked
in_progress.
Project Reference Docs Gate — Run after task-tracking bootstrap and before target/source file reads, grep, edits, or analysis. Project docs override generic framework assumptions.
- Identify scope: file types, domain area, and operation.
- Required docs by trigger: always
docs/project-reference/lessons.md; doc lookupdocs-index-reference.md; reviewcode-review-rules.md; backend/CQRS/APIbackend-patterns-reference.md; domain/entitydomain-entities-reference.md; frontend/UIfrontend-patterns-reference.md; styles/designscss-styling-guide.md+design-system/design-system-canonical.md; integration testsintegration-test-reference.md; E2Ee2e-test-reference.md; feature docs/specsfeature-spec-reference.md+spec-system-reference.md+spec-principles.md; behavior/public-contract/spec-test-code syncworkflow-spec-test-code-cycle-reference.md; derived spec index/ERD/reimplementation guidesspec-system-reference.md+ source Feature Specs underdocs/specs/; architecture/new areaproject-structure-reference.md.- Read every required doc. 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-initor the narrow lower-level route ($project-config,$docs-init,$scan-all,$scan --target=<key>,$claude-md-init) before ordinary project-specific work. If Codex mirrors orAGENTS.mdare missing/stale, ask the user to run$sync-codex; do not auto-run it.- Before target work, state:
Reference docs read: ... | Not applicable: ....Ready when: scope evaluated, required docs checked/read or setup route completed,
lessons.mdconfirmed, citation emitted.
Task Tracking & External Report Persistence — Bootstrap this before execution; then run project-reference doc prefetch before target/source work.
- Create a small task breakdown before target file reads, grep, edits, or analysis. On context loss, inspect the current task list first.
- Mark one task
in_progressbefore work andcompletedimmediately after evidence; never batch transitions.- For plan/review work, create
plans/reports/{skill}-{YYMMDD}-{HHmm}-{slug}.mdbefore first finding.- Append findings after each file/section/decision and synthesize from the report file at the end.
- Final output cites
Full report: plans/reports/{filename}.Blocked until: task breakdown exists, report path declared for plan/review work, first finding persisted before the next finding.
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.
Understand Code First — HARD-GATE: Do NOT write, plan, or fix until you READ existing code.
- Search 3+ similar patterns (
grep/glob) — citefile:lineevidence- Read existing files in target area — understand structure, base classes, conventions
- Run
python .claude/scripts/code_graph trace <file> --direction both --jsonwhen.code-graph/graph.dbexists- Map dependencies via
connectionsorcallers_of— know what depends on your target- Write investigation to
.ai/workspace/analysis/for non-trivial tasks (3+ files)- Re-read analysis file before implementing — never work from memory alone. — why: long context drifts from the file; the file is ground truth
- NEVER invent new patterns when existing ones work — match exactly or document deviation. — why: divergent patterns fragment the codebase and slow every future reader
BLOCKED until:
- [ ]Read target files- [ ]Grep 3+ patterns- [ ]Graph trace (if graph.db exists)- [ ]Assumptions verified with evidence
Graph-Assisted Investigation — MANDATORY when
.code-graph/graph.dbexists.HARD-GATE: MUST ATTENTION run at least ONE graph command on key files before concluding any investigation.
Pattern: Grep finds files →
trace --direction bothreveals full system flow → Grep verifies details
Task Minimum Graph Action Investigation/Scout trace --direction bothon 2-3 entry filesFix/Debug callers_ofon buggy function +tests_forFeature/Enhancement connectionson files to be modifiedCode Review tests_foron changed functionsBlast Radius trace --direction downstreamCLI:
python .claude/scripts/code_graph {command} --json. Use--node-mode filefirst (10-30x less noise), then--node-mode functionfor detail.
Validated-Finding Fix + Full Re-Review Loop — Re-review is triggered by a validated finding fix cycle, not by a round number. Review purpose:
review → validate findings → fix validated findings → full re-reviewuntil a complete review pass finds no issues. A clean review ENDS the loop — no further rounds required.Round 1: Main-session review. Read target files, build understanding, note issues. Output findings + verdict (PASS / FAIL).
Decision after Round 1:
- No issues found (PASS, zero findings) → review ENDS. Do NOT spawn a fresh sub-agent for confirmation.
- Issues found (FAIL, or any non-zero findings) → run the active review skill's findings-validation gate first; for review skills the default gate is
$why-review --validate-findings <report-path>. Fix only validated findings, then restart the full review protocol from the beginning with a fresh task breakdown.Fresh full re-review after every fix cycle: Re-run the whole review protocol over the current full target. When sub-agents are part of that protocol, spawn NEW
spawn_agentcalls — never reuse prior agents. Reviewers re-read ALL files from scratch with ZERO memory of prior rounds. SeeSYNC:fresh-context-reviewfor the spawn mechanism andSYNC:review-protocol-injectionfor the canonical Agent prompt template. Each fresh full review must catch:
- Cross-cutting concerns missed in the prior round
- Interaction bugs between changed files
- Convention drift (new code vs existing patterns)
- Missing pieces that should exist but don't
- Subtle edge cases the prior round rationalized away
- Regressions introduced by the fixes themselves
Loop termination: After each full re-review, repeat the same decision: clean → END; issues → validate findings → fix → restart from the first review phase. Continue until a complete review pass finds zero issues. If the same validated finding repeats for 3 full invocations with no progress, or a fix requires product/owner input, escalate via a direct user question.
Rules:
- A clean Round 1 ENDS the review — no mandatory Round 2
- NEVER fix unvalidated findings; validate first using the caller's validation gate
- NEVER skip the full re-review after a fix cycle (every fix invalidates the prior verdict)
- NEVER reuse a sub-agent across rounds — every iteration that uses sub-agents spawns NEW Agent calls
- Main agent READS sub-agent reports but MUST NOT filter, reinterpret, or override findings
Fresh Context Re-Review — Eliminate orchestrator confirmation bias after fixes by restarting the full review with isolated sub-agents where applicable.
Why: The main agent knows what it (or
$feature-implement) just fixed and rationalizes findings accordingly. A fresh sub-agent has ZERO memory, re-reads from scratch, and catches what the main agent dismissed. Sub-agent bias is mitigated by (1) fresh context, (2) verbatim protocol injection, (3) main agent not filtering the report.When: ONLY after a validated-finding fix cycle. A review round that finds zero issues ENDS the loop — do NOT spawn a confirmation sub-agent. A review round that finds issues triggers: validate findings → fix → full review restart from the first phase.
How:
- Start a NEW full review invocation/task breakdown; when that protocol calls for agents, spawn NEW
spawn_agenttool calls — usecode-revieweragent_type for code reviews,general-purposefor plan/doc/artifact reviews- Inject ALL required review protocols VERBATIM into the prompt — see
SYNC:review-protocol-injectionfor the full list and template. Never reference protocols by file path; AI compliance drops behind file-read indirection (seeSYNC:shared-protocol-duplication-policy)- Sub-agent re-reads ALL target files from scratch via its own tool calls — never pass file contents inline in the prompt
- Sub-agent writes structured report to
plans/reports/{review-type}-round{N}-{date}.md- Main agent reads the report, integrates findings into its own report, DOES NOT override or filter
Rules:
- SKIP fresh sub-agent when the prior full review found zero issues (no fixes = nothing new to verify)
- NEVER skip the full review restart after a fix cycle — every fix invalidates the prior verdict
- NEVER reuse a sub-agent across rounds — every fresh round spawns a NEW
spawn_agentcall- Continue until a complete full review pass has zero findings; if the same blocker repeats 3 times with no progress, escalate via a direct user question
- Track iteration count and repeated blockers in conversation context (session-scoped, no persistent files)
Systematic Review Batching (map-reduce) — When a changeset is large, do NOT review files one-by-one. Partition into size-capped batches, fire one specialized sub-agent per batch in parallel, then reduce. This bounds EVERY context — each batch agent AND the orchestrator — so coverage stays complete as file count grows.
Trigger ladder (one ordered escalation — not competing thresholds):
- < 10 changed files → sequential per-file review (default; no batching).
- ≥ 10 changed files → switch to systematic parallel mode. Announce:
"Detected {N} changed files. Switching to systematic parallel review protocol."Then: categorize → size-capped batches → flat consolidation.- categories > 6 OR files > 40 → additionally insert the hierarchical synthesis tier (below). Everything from rung 2 still applies.
Step 1 — Categorize. Group changed files into logical categories derived from the project's actual structure (not forced). Category is the concern axis; orient with these examples, derive what fits the repository:
Category Type Example Groupings Agent/Tooling AI scripts, hooks, skill definitions, workflow configs, linting rules Root config/docs Root README, project config, CI/CD pipeline configs Reference docs Architecture docs, patterns references, setup guides Feature/domain docs Business feature documentation, spec files, ADRs Backend logic Service/handler/controller source (infer from project structure) Frontend logic UI component/state/API source (infer from project structure) Data/Schema Migrations, schema files, seed data Tests Unit, integration, E2E test files Infrastructure Docker, k8s, CI/CD, cloud manifests Step 2 — Size-capped batches. One sub-agent per batch of ≤8 files OR ≤2000 diff-lines, whichever hits first. Category stays the concern axis, but any category exceeding a cap splits into multiple size-capped batches (30 backend files → 4 batches). Size caps — not category caps — make "many files" safe: a category cap alone lets one giant category blow a single agent's context.
Step 2a — Sub-agent type per batch (match the batch's dominant concern):
Severity Rubric — Classify every finding by consequence, not by how easy it is to fix. One scale across all reviews so a "High" means the same thing everywhere.
Severity Action Definition CRITICAL Block merge Silent runtime failure, data corruption, validation bypass, security hole 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 Score-based skills map their numeric scale onto these tiers — do not invent a parallel vocabulary:
- 0-2 criterion scoring (e.g. production-readiness-review):
0= CRITICAL/HIGH (criterion unmet, blocks production readiness),1= MEDIUM (partial, should fix),2= pass (no finding).- Two-axis scoring (e.g. performance-review, impact × likelihood): map the resulting cell to the nearest tier — high-impact + high-likelihood → CRITICAL/HIGH; low-impact OR low-likelihood → MEDIUM/LOW.
A finding's tier drives the gate: CRITICAL/HIGH must be resolved or explicitly accepted by the owner before PASS; MEDIUM/LOW may ship with a tracked follow-up.
Category Review Thinking — A thinking framework for reviewing any category of changed files. NOT a fixed checklist — derive concerns from domain knowledge; the examples are starting points only. Your knowledge of the category exceeds any list here — trust it.
Step 1 — Understand the category's role. What is this category responsible for in the overall system? What invariants must it uphold? What are its consumer contracts (who depends on it, what do they expect)?
Step 2 — Read project conventions for this category. Search for reference docs, style guides, ADRs, or READMEs specific to this area. Grep 3+ existing similar files — extract naming conventions, structural patterns, shared base classes. If no docs exist, derive conventions empirically from existing code.
Step 3 — Derive concerns from first principles. Apply all that are relevant; expand beyond this list based on the actual category:
- Correctness: Does the logic match the intent? Trace happy path AND error path.
- Boundary contracts: Are interfaces/APIs/events/protocols honored? No implicit coupling introduced?
- Project conventions: Does new code follow the patterns found in Step 2? Evidence-confirmed, not assumed.
- Security: Auth enforced at every entry point? Input validated at boundaries? No secrets in the diff?
- Performance: Unbounded operations? N+1 patterns? Blocking calls in async context? Unindexed queries?
- Maintainability: DRY? Single responsibility? Complexity within reason? Names reveal intent?
- Test coverage: Are the changed paths covered by tests? Are existing tests still valid after the change?
- Documentation: Do related docs, specs, or READMEs reflect the changes?
Step 4 — Create sub-tasks and execute. For each identified concern: create a task tracking sub-task, work through it with
file:lineevidence, mark done. No findings without proof.Illustrative concern examples by category type (not exhaustive — trust your knowledge beyond this):
- Server-side logic: handler/service structure conventions, validation layer placement, side-effect isolation, cross-service boundary enforcement, data-access layer separation, error propagation strategy
- Client-side logic: component lifecycle management, resource cleanup (subscriptions, listeners, timers), state management patterns, API integration layer separation, reactive stream composition
- migration reversibility (rollback script), lock impact on table volume, backfill idempotency, index coverage for query patterns, deployment ordering
MUST ATTENTION apply critical + sequential thinking — every claim needs appropriate traced evidence (file:line for repo/code claims; source URL or artifact section for research, product, content, and docs claims); confidence >80% to act, <60% DO NOT recommend. Anti-hallucination: never present guess as fact, admit uncertainty freely, cross-reference independently, stay skeptical of own confidence.
MUST ATTENTION discover project conventions (base classes, validation API, exception types) BEFORE applying checklist. Run graph trace when graph.db exists.
file:line evidence for every claim. Confidence >80% to act, <60% = do NOT recommend.
MUST ATTENTION run at least ONE graph command on key entity files when graph.db exists. Pattern: grep → trace → verify.
MUST ATTENTION apply AI mistake prevention — verify generated content against evidence, trace downstream references before deleting or renaming, verify all affected outputs, re-read files after context loss, and surface ambiguity before acting.
plans/reports/ incrementally and synthesize from disk.Reference docs read: ....lessons.md; project conventions override generic defaults.$project-init or the narrow lower-level route before ordinary project-specific work.[N.M] $skill-name — phase prefixes and one-in_progress discipline.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
file:line evidence — never a fixed checklist.IMPORTANT MUST ATTENTION Goal: Detect DDD design quality violations in domain entities/value objects across any stack — adapting to project-specific patterns via config/reference-doc discovery — so entities/VOs preserve invariants, aggregate boundaries, and discovered DDD conventions.
Protocols in force — MUST ATTENTION (concise digest of the SYNC/shared blocks this skill carries):
lessons.md) before target work.plans/reports/ incrementally.file:line proof per claim; confidence >80% to act.Top-3 (primacy-recency — these 3 are also at file top):
file:line evidence — confidence >80% to report, 60-80% verify first, <60% DO NOT recommend — why: AI sub-agent reports inherit confirmation bias; unproven findings inflate severity downstream.Evidence + process gates:
validate() overrides, leaked persistence/business logic, missing identity markers) BEFORE reading individual files, and write EVERY grep result to the report immediately — why: highest-signal violations surface fastest and batched writes lose findings on context loss.in_progress, mark completed immediately after evidence; on context loss call the current task list first — never duplicate — why: phase tracking survives compaction, memory does not.lessons.md, entity/backend/code-review references) + CLAUDE.md and search 3+ existing entity files BEFORE applying any checklist — discovered conventions win — why: local conventions differ from generic framework defaults..code-graph/graph.db exists, and inspect entity callers/usages before classifying anemic model or misplaced invariant — why: code existing ≠ code executing; the bug owner is the layer the data flows through.plans/reports/ incrementally and synthesize from disk — why: long sub-agents hit budget before a final batched write and lose everything.Domain rules (this skill's invariants):
validate()/ensureCan*() — NEVER application-layer-only — why: any other entry point can then reach an invalid domain state.code-reviewer sub-agents automatically — why: one "High" must mean the same everywhere, and serial review of many files exhausts context.[TASK-PLANNING] Before acting, analyze task scope and systematically break it into small todo tasks and sub-tasks using task tracking; add a final "Analyze AI mistakes & lessons learned" review task.
Closing reminder — Easy to Change is the success metric. Every finding, test, refactor, and abstraction must answer one question: does this make the next change cheaper or more expensive? If it doesn't reduce future change cost, reject it. Coupling, hidden state, duplicated knowledge, and unclear intent are the real enemies — call them out by name.
Anti-Rationalization:
| Evasion | Rebuttal |
|---|---|
| "Generic DDD rule fits, skip Phase 0" | Discovered base classes override generic rules — verify the project's real entity/VO base FIRST or every finding is noise. |
| "Finding is obvious, skip evidence" | No file:line proof = no finding. Confidence <60% → DO NOT recommend. |
| "Clean enough, skip the re-review after fixes" | Every fix invalidates the prior verdict — restart the full review until a clean pass ENDS it. |
| "Looks anemic, flag it" | Inspect callers + base class first — pattern fit, not pattern resemblance, decides anemic vs. correct delegation. |
| "Invariant enforced in code, that's coverage" | Dual-Feedback: spec must NAME it AND a property TC must GUARD it — code-only is INCOMPLETE. |
| "Many entities, review them inline" | 10+ files → parallel sub-agents; persist per-file findings to plans/reports/ or they vanish on budget cutoff. |
IMPORTANT MUST ATTENTION Phase 0 discovery FIRST (base classes override generic rules) · NEVER report a finding without file:line evidence at confidence >80% · validate findings before fixing, then restart the full review — a clean pass ENDS it.
Source: .claude/.ck.json + .claude/skills/shared/sync-inline-versions.md (:full blocks) + .claude/scripts/lib/hookless-prompt-protocol.cjs
Generic portability boundary: Reusable skills and protocol text stay project-neutral; project-specific conventions are discovered from docs/project-config.json and docs/project-reference/. Apply shared AI-SDD from shared/sdd-artifact-contract.md. Read docs/project-config.json and docs/project-reference/docs-index-reference.md, then open the project reference docs named there. For spec, test-case, behavior-change, public-contract, or docs/specs/ work, route through the local spec docs named by the docs index: feature-spec-reference.md, spec-system-reference.md, spec-principles.md, and workflow-spec-test-code-cycle-reference.md when specs/tests/code must stay synchronized. If either file or a required reference doc is missing or stale, auto-run $project-init (or the narrow lower-level route such as $project-config, $docs-init, $scan-all, or $scan --target=<key>) before ordinary project-specific work. Any supported AI tool may execute when this shared context and local docs are available.
$start-workflow <workflowId>; for a selected skill, invoke that skill; for a custom workflow, sequence custom steps directly; for direct execution, proceed with the task.Source: .claude/skills/shared/sync-inline-versions.md
AI-SDD Artifact Contract — Shared spec-driven development rules stay portable and source-owned.
- Keep reusable AI-SDD principles in
.claude; put repository-specific paths, commands, owners, products, and formats in project config/reference docs.- Preserve cycle:
spec -> plan -> tasks -> implement -> verify -> update spec/docs.- Trace every requirement or invariant through decision, task, TC/test, source evidence, and docs/spec update.
- Treat code-to-spec extraction as reference-only until accepted by the canonical spec owner.
- Any supported AI tool may plan, implement, review, or verify with synced context; using multiple tools is optional.
- Update
.claudesource first, then sync generated mirrors; do not manually edit.agents,.codex, orAGENTS.md. — why: mirrors are generated artifacts; hand-edits are overwritten on the next sync- If
docs/project-config.json, root instruction files, or a required project-reference doc is missing or stale, auto-run$project-initor the narrow lower-level route before ordinary project-specific work.Active reference:
shared/sdd-artifact-contract.mdin the active skills root.
shared/sdd-artifact-contract.md; keep reusable AI-SDD in .claude and local rules in project docs..claude source before syncing generated mirrors; do not manually edit .agents, .codex, or AGENTS.md.$project-init or the narrow setup route automatically.
[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.Break 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-review/$lint catch this?" — Yes → improve review skill instead.$learn.
[CRITICAL-THINKING-MINDSET] Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
Anti-hallucination principle: Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence root of all hallucination.Report must include ## Round N Findings (Fresh Sub-Agent) for every round N≥2 that was executed.
code-reviewersecurity-auditorperformance-optimizergeneral-purposeEach batch sub-agent receives: its full file list; SYNC:category-review-thinking as its primary thinking model — derive each category's concerns from first principles, NOT a fixed checklist (if the consuming skill does not carry that block, apply category-first thinking directly); project reference docs relevant to its concern (discover via *patterns*, *conventions*, *style-guide*); cross-reference verification instructions (counts, tables, links). All batch agents run in parallel and write findings to plans/reports/ (per SYNC:task-tracking-external-report); reducers read from disk, never from memory.
Step 3 — Reduce.
Step 4 — Holistic assessment. With all findings combined, judge: overall coherence as a unified intent; cross-category sync (docs match code? contracts match callers?); risk areas where categories interact; missing doc/spec updates for changed artifacts.
No silent truncation. If any cap forces sampling or a batch is dropped for budget, ANNOUNCE the dropped/sampled scope explicitly — bounded coverage must never read as complete coverage.