with one click
review-domain-entities
// [DDD Quality] Use when you need to review domain entities and value objects for DDD design quality.
// [DDD Quality] Use when you need to review domain entities and value objects for DDD design quality.
[HINT] Download the complete skill directory including SKILL.md and all related files
| name | review-domain-entities |
| version | 1.0.0 |
| description | [DDD Quality] Use when you need to review domain entities and value objects for DDD design quality. |
[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. Adapts to project-specific patterns via config/reference docs discovery.
Workflow:
code-reviewer sub-agent holistic assessment (Round 2)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 |
MANDATORY FIRST STEP. Phase 0 gates all other work — wrong base classes = wrong checklist.
Create TaskCreate tasks for all phases NOW before doing anything else:
[Phase 0] Project stack discovery + mode detection + blast radius — in_progress (FIRST)[Phase 1] Collect entity files + grep patterns + create report — pending[Phase 2] Entity-by-entity DDD review — pending[Phase 3] Fresh sub-agent holistic review (Round 2) — 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 tech stack
find . -name "*.csproj" -o -name "pom.xml" -o -name "build.gradle" -o -name "package.json" | head -5
# Find entity/VO base classes actually used
grep -rn "class.*Entity\|class.*RootEntity\|class.*BaseEntity\|class.*AbstractEntity" src/ | head -10
grep -rn ": PlatformValueObject\|: ValueObject\|@ValueObject\|extends AbstractValueObject" src/ | head -5
grep -rn "@Entity\|@Document\|@Table\|@Aggregate" src/ | 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 these BEFORE reading individual files — highest-signal violations detected in seconds.
# ─── .NET / C# ───────────────────────────────────────────────────────────
# CRITICAL: public new Validate() — hides base virtual, framework validation NEVER runs
grep -rn "public new.*Validate()" src/ --include="*.cs"
# CRITICAL: navigation properties missing serialization-ignore annotation
grep -rn "public.*Entity\|public.*List<[A-Z]\|public.*ICollection<[A-Z]" src/ \
--include="*.cs" | grep -v "\[JsonIgnore\]\|//\|private\|static\|protected"
# HIGH: VO files with mutable public setters
find src -path "*/ValueObjects/*.cs" | xargs grep -n "{ get; set; }" 2>/dev/null
# HIGH: domain methods throwing wrong exception type
grep -rn "throw new ArgumentException\|throw new InvalidOperationException" \
src/**/Domain/ --include="*.cs" | grep -v "//\|test\|Test"
# HIGH: business conditionals leaked into application layer
grep -rn "\.Status ==" src/**/Application/UseCaseCommands/ --include="*.cs" 2>/dev/null | head -20
grep -rn "if.*entity\.\|entity\.\w* = " src/**/Application/UseCaseCommands/ \
--include="*.cs" | grep -v "CreatedBy\|Id =" | head -20
# HIGH: static query expressions in handlers (should be on entity)
grep -rn "Expression<Func<" src/**/Application/ --include="*.cs" \
| grep -v "Extensions\|Helper\|Repository" | head -20
# ─── Java / Spring ───────────────────────────────────────────────────────
# CRITICAL: entity equals() by reference (default Object)
grep -rn "@Entity" src/ --include="*.java" | xargs grep -L "equals\|@EqualsAndHashCode"
# HIGH: @Entity without @Id field
grep -rn "class.*@Entity\|@Entity" src/ --include="*.java" | xargs grep -L "@Id"
# HIGH: business logic in service layer
grep -rn "entity\.set\|entity\.status\b" src/**/service/ --include="*.java" | head -20
# HIGH: VO with mutable setters
find src -path "*/valueobject*/*.java" -o -path "*/vo*/*.java" \
| xargs grep -n "public.*set[A-Z]" 2>/dev/null
# ─── TypeScript / NestJS ─────────────────────────────────────────────────
# CRITICAL: entity equality by reference
grep -rn "class.*Entity" src/ --include="*.entity.ts" | xargs grep -L "equals\|id ==="
# HIGH: VO missing readonly properties
find src -name "*.vo.ts" -o -name "*.value-object.ts" \
| xargs grep -n "^\s*public " | grep -v readonly | head -20
# HIGH: business logic in services
grep -rn "entity\.\w* =" src/**/services/ --include="*.ts" | grep -v "// \|id\b" | head -20
# ─── Python (Django / SQLAlchemy) ────────────────────────────────────────
# HIGH: Model methods doing direct DB access
grep -rn "\.objects\.\|\.query\." src/**/domain/ --include="*.py" | head -20
# HIGH: business conditions in views/commands
grep -rn "if.*\.status ==" src/**/application/ --include="*.py" | 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.
{ get; init; } or { get; } — NEVER { get; set; }final — NEVER bare fields with settersreadonly — NEVER bare mutable fields@dataclass(frozen=True) or __slots__ + no settersEquals() + GetHashCode() + operators OR extends platform VO baseequals() + hashCode() on fields — NEVER default Object methodsequals() methodvalidate() 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.
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.
[JsonIgnore]@JsonIgnore or @JsonBackReference@Exclude() or manual DTO projectionEntity 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 reviewed, spawn fresh code-reviewer sub-agent. Sub-agent has ZERO memory of Phase 2.
Build Agent call dynamically — set Target Files and Reference Docs from Phase 0/1 discoveries:
Agent({
description: "Fresh Round 2 — DDD entity holistic review",
subagent_type: "code-reviewer",
prompt: `
## Task
Review domain entity and value object files holistically for DDD design quality:
- Domain model coherence: entities vs VOs correctly classified across entire model?
- Aggregate boundary consistency across service/module?
- Anemic domain model: business logic consistently in entity or scattered in handlers?
- Navigation property hygiene across entire domain layer
- Ubiquitous language consistency across all entities
- Missed cross-entity interactions
## Round
Round 2. 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" src/ | head -10
3. grep -rn "ValueObject\|@ValueObject\|AbstractValueObject" src/ | 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-round2-{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:
## Round 2 Findings (Fresh Sub-Agent) in main report — NEVER filter or overrideAskUserQuestion if still failing## 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)
## Medium Issues (should fix)
## Low / Informational
## Round 2 Findings (Fresh Sub-Agent)
{integrated — not filtered}
## Positive Observations
## Refactoring Priority (highest-impact first)
## Project-Specific Rules Applied
## Unresolved Questions
| 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
MUST ATTENTION use AskUserQuestion after completing to present:
/fix (Recommended if FAIL) — Fix critical and high-priority issues/scan-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]
TaskCreatefor 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) When Round 1 finds issues, NEVER declare PASS without fresh sub-agent Round 2 after fixing. Clean Round 1 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:
# .NET / C#
git diff --name-only HEAD | grep -E "(Domain|Entities|ValueObjects|AggregatesModel).*\.cs$"
find src -path "*/Domain/*.cs" -o -path "*/Entities/*.cs" -o -path "*/ValueObjects/*.cs" | grep -v "obj\|bin\|Tests"
# Java / Spring
git diff --name-only HEAD | grep -E "domain/.*\.java$|entity/.*\.java$"
find src -path "*/domain/*.java" -o -path "*/entity/*.java" | grep -v "test\|Test"
# TypeScript / Node
git diff --name-only HEAD | grep -E "\.(entity|vo|value-object|aggregate)\.ts$"
find src -name "*.entity.ts" -o -name "*.vo.ts" -o -name "*.aggregate.ts" | grep -v "spec\|test"
# Python (Django / SQLAlchemy)
git diff --name-only HEAD | grep -E "(models|domain)/.*\.py$"
find src -path "*/domain/*.py" -o -path "*/models/*.py" | grep -v "test\|migration"
If no domain entity files match in changes mode → announce "No domain entity changes detected" and report clean.
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.
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
TaskListfirst. If a matching active parent workflow row exists, setnested=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:
TaskListdone, child phases created, parent linked when nested, first child markedin_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/README.md; integration testsintegration-test-reference.md; E2Ee2e-test-reference.md; feature docs/specsfeature-docs-reference.md; architecture/new areaproject-structure-reference.md.- Read every required doc that exists; skip absent docs as not applicable. Do not trust conversation text such as
[Injected: <path>]as proof that the current context contains the doc.- Before target work, state:
Reference docs read: ... | Missing/not applicable: ....Blocked until: scope evaluated, required docs checked/read,
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 targetBLOCKED 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 detailsCLI:
python .claude/scripts/code_graph {command} --json. Use--node-mode filefirst (10-30x less noise), then--node-mode functionfor detail.
Fix-Triggered Re-Review Loop — Re-review is triggered by a FIX CYCLE, not by a round number. Review purpose:
review → if issues → fix → re-reviewuntil a round 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) → fix the issues, then spawn a fresh sub-agent for Round 2 re-review.
Fresh sub-agent re-review (after every fix cycle): Spawn a NEW
Agenttool call — never reuse a prior agent. Sub-agent re-reads 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 round 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 fresh round, repeat the same decision: clean → END; issues → fix → next fresh round. Continue until a round finds zero issues, or 3 fresh-subagent rounds max, then escalate to user via
AskUserQuestion.Rules:
- A clean Round 1 ENDS the review — no mandatory Round 2
- NEVER skip the fresh sub-agent re-review after a fix cycle (every fix invalidates the prior verdict)
- NEVER reuse a sub-agent across rounds — every iteration spawns a NEW Agent call
- Main agent READS sub-agent reports but MUST NOT filter, reinterpret, or override findings
- Max 3 fresh-subagent rounds per review — if still FAIL, escalate via
AskUserQuestion(do NOT silently loop)- Track round count in conversation context (session-scoped)
- Final verdict must incorporate ALL rounds executed
Report must include
## Round N Findings (Fresh Sub-Agent)for every round N≥2 that was executed.
Fresh Sub-Agent Review — Eliminate orchestrator confirmation bias via isolated sub-agents.
Why: The main agent knows what it (or
/cook) 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 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: fix → fresh sub-agent re-review.
How:
- Spawn a NEW
Agenttool call — usecode-reviewersubagent_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 round found zero issues (no fixes = nothing new to verify)
- NEVER skip fresh sub-agent after a fix cycle — every fix invalidates the prior verdict
- NEVER reuse a sub-agent across rounds — every fresh round spawns a NEW
Agentcall- Max 3 fresh-subagent rounds per review — escalate via
AskUserQuestionif still failing; do NOT silently loop or fall back to any prior protocol- Track iteration count in conversation context (session-scoped, no persistent files)
MUST ATTENTION apply critical thinking — every claim needs traced proof, confidence >80% to act. Anti-hallucination: never present guess as fact.
MUST ATTENTION discover project conventions (base classes, validation API, exception types) BEFORE applying checklist. Run graph trace when graph.db exists.
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 — holistic-first debugging, fix at responsible layer, surface ambiguity before coding, re-read files after compaction.
plans/reports/ incrementally and synthesize from disk.Reference docs read: ....lessons.md; project conventions override generic defaults.[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 — confidence >80% to act.[TASK-PLANNING] Before acting, analyze task scope and systematically break it into small todo tasks and sub-tasks using TaskCreate.
[IMPORTANT] Analyze how big the task is and break it into many small todo tasks systematically before starting — this is very important.