[BLOCKING] Execute skill steps in declared order. NEVER skip, reorder, or merge steps without explicit user approval.
[BLOCKING] Before each step or sub-skill call, update task tracking: set in_progress when step starts, set completed when step ends.
[BLOCKING] Every completed/skipped step MUST include brief evidence or explicit skip reason.
[BLOCKING] If Task tools are unavailable, create and maintain an equivalent step-by-step plan tracker with the same status transitions.
Quick Summary
Goal: Create or run database migrations following the repository's documented patterns.
Workflow:
- Identify — Determine migration type (schema migration vs data/document migration)
- Create — Generate migration using the configured migration tool or data migration executor (see docs/project-reference/backend-patterns-reference.md)
- Verify — Run migration and confirm schema/data changes
Key Rules:
- Follow the repository's migration patterns (see CLAUDE.md / project-reference docs)
- For CREATE: present the migration design and wait for explicit user approval before creating migration files
- Always backup data before destructive migrations
- Use the configured data migration executor for data/document migrations (see docs/project-reference/backend-patterns-reference.md)
Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence percentages (Idea should be more than 80%).
Database migration: $ARGUMENTS
Instructions
Parse arguments:
add <name> → Create new schema/data migration with the configured tool
update → Apply pending migrations
list → List all migrations and status
rollback → Revert last migration
- No argument → Show migration status
Identify database provider + migration tooling from project config and project-reference docs:
- Relational stores: managed by the configured schema-migration tool.
- Document/key-value/event stores: may use code-based migrations or startup executors defined by the repository.
For schema migrations:
Add migration:
```bash
{configured-migration-add-command} <MigrationName>
```
Update database:
```bash
{configured-migration-update-command}
```
List migrations:
```bash
{configured-migration-list-command}
```
For data/document migrations:
- Often code-based migrations run by the configured migration executor (see docs/project-reference/backend-patterns-reference.md)
- Location: the repository's configured migration folder — discover from
docs/project-reference/backend-patterns-reference.md
- Migrations run automatically on application startup
- To create: Generate new migration class following existing patterns
Safety checks:
- Warn before applying migrations to production
- Show what changes will be applied
- Recommend backup before destructive operations
Migration Safety Review (MANDATORY for non-local environments):
- Before applying to staging/production, spawn
database-admin sub-agent (subagent_type: "database-admin") for safety review
- Review criteria: locking behavior on large tables, index creation impact under concurrent writes, rollback strategy, zero-downtime feasibility
- Present findings and get explicit user approval before running the configured migration apply command on non-local environments
Sub-Agent Type Override
MANDATORY for non-local migration apply: Spawn database-admin sub-agent (subagent_type: "database-admin") for safety review BEFORE applying to staging or production.
Rationale: database-admin specializes in query plans, index impact analysis, locking behavior, backup/restore, and replication — context the main agent lacks for production-safe migration decisions.
[IMPORTANT] Use TaskCreate to break ALL work into small tasks BEFORE starting — including tasks for each file read. This prevents context loss from long files. For simple tasks, AI MUST ATTENTION ask user whether to skip.
Prerequisites: MUST ATTENTION READ before executing:
docs/project-reference/domain-entities-reference.md — Domain entity catalog, relationships, cross-service sync (read when task involves business entities/models)
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 OR flagging one as a defect. Before changing or reporting a constant, limit, flag, cutoff, wording, or pattern, read nearby context and history, the CALLER's ordering, and 2+ sibling call sites of the same convention. A doc stating WHAT without WHY is missing rationale, not proof of a missing guard.
Surface ambiguity before acting — don't pick silently. Multiple valid interpretations require an explicit question or stated assumption with risk.
Assert the outcome your system owns, not the intermediate state your infrastructure owns. When verifying async work, assert the final business state — never the delivery/retry bookkeeping held in shared infrastructure that any co-running process can write. Such a check passes when run alone and flakes the moment anything else shares that infrastructure.
Keep shared guidance role-relevant. Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
Sub-Agent Selection — Full routing contract: .claude/skills/shared/sub-agent-selection-guide.md
Rule: Route specialized domains (architecture, security, performance, DB, E2E, integration-test, git) to the matching specialist agent (see guide above) — NEVER use code-reviewer for these. — why: code-reviewer lacks each domain's checklist, so specialized issues slip through.
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
TaskList first. If a matching active parent workflow row exists, set nested=true and record parentTaskId; 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_progress before work and completed immediately after evidence is written.
- Complete the parent only after all child tasks are completed or explicitly cancelled with reason.
Blocked until: TaskList 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.
- Read
docs/project-config.json first — the project's machine-readable map. It is the single source of truth for THIS repo (modules/paths, framework + search keywords, test/E2E/integration run-commands, design system, architecture rules, workflow patterns); ground exact paths, run-commands, and conventions on it before investigating, planning, or coding — never assume framework defaults (CLAUDE.md + reference docs are derived from it). If it — or the docs index, lessons.md, CLAUDE.md, AGENTS.md, or any required reference doc — is missing or stale, auto-run /project-init or the narrow route (/project-config, /docs-init, /scan-all, /scan --target=<key>, /claude-md-init) first; if Codex mirrors or AGENTS.md are stale, ask the user to run /sync-codex (never auto-run it).
- Required docs by trigger: always
docs/project-reference/lessons.md; doc lookup docs-index-reference.md; review code-review-rules.md; backend/CQRS/API backend-patterns-reference.md; domain/entity domain-entities-reference.md; frontend/UI frontend-patterns-reference.md; styles/design scss-styling-guide.md + design-system/design-system-canonical.md; integration tests integration-test-reference.md; E2E e2e-test-reference.md; feature docs/specs feature-spec-reference.md + spec-system-reference.md + spec-principles.md; behavior/public-contract/spec-test-code sync workflow-spec-test-code-cycle-reference.md; derived spec index/ERD/reimplementation guides spec-system-reference.md + source Feature Specs under docs/specs/; architecture/new area project-structure-reference.md.
- Read every required doc, then before target work state:
Reference docs read: ... | Not applicable: ....
Ready when: scope evaluated, docs/project-config.json consulted, required docs checked/read or setup route completed, lessons.md confirmed, citation emitted.
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) — cite file:line evidence
- Read existing files in target area — understand structure, base classes, conventions
- Run
python .claude/scripts/code_graph trace <file> --direction both --json when .code-graph/graph.db exists
- Map dependencies via
connections or callers_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
- MANDATORY IMPORTANT MUST ATTENTION search 3+ existing patterns and read code BEFORE any modification. Run graph trace when graph.db exists.
- MANDATORY IMPORTANT MUST ATTENTION cite
file:line evidence for every claim. Confidence >80% to act, <60% = do NOT recommend.
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 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.
- MANDATORY Before investigating, planning, or coding, read
docs/project-config.json (the project map: modules/paths, run-commands, conventions, architecture/workflow rules) + the required project-reference docs, and cite Reference docs read: ....
- MANDATORY Always include
lessons.md; project config + conventions override generic framework defaults.
- MANDATORY If project config, root instruction files, or any required reference doc is missing or stale, auto-run
/project-init or the narrow lower-level route before ordinary project-specific work.
- MANDATORY Parent workflow rows do not replace child phase tracking; expand phases and link the parent when nested.
- MANDATORY Orchestrators pre-expand child skill phases before invocation; use
[N.M] $skill-name — phase prefixes and one-in_progress discipline.
Prompt-Enhance Closing Anchors
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
Parallel Sub-Agent Dispatch — Plan parallelism the moment a task breakdown exists, BEFORE executing it — running provably independent tasks sequentially wastes wall-clock. Applies to every multi-step job: workflow steps, planning, batch updates, investigation, research, scans, reviews, doc sync. Plan execution is metadata-gated, NEVER default-parallel — fan-out follows ONLY what the plan declares (PAR/SEQ tags + per-phase write set); an untagged plan runs sequentially — why: a derived write set cannot see cascade or generated writes.
- Tag every task
PAR or SEQ. PAR = inputs exclude every pending task's output AND write set disjoint from every other PAR. Else SEQ — MUST ATTENTION name the dependency forcing it.
- Group
PAR into waves. No edge between members. Two writers of one file NEVER share a wave. Read-only work (search, investigation, review, research) parallelizes freely.
- Declare before dispatch:
Parallel plan: wave 1 = [...] · wave 2 = [...] · SEQ = [...] (reason).
- Spawn each wave in ONE message — every
Agent call in one response, NEVER dripped per turn. Route each task to its specialist (.claude/skills/shared/sub-agent-selection-guide.md); NEVER code-reviewer as catch-all.
- Brief each sub-agent self-contained: goal · scope + owned files · reference docs · return contract (summary +
Full report: path, per SYNC:subagent-return-contract) · incremental persistence to plans/reports/ (per SYNC:incremental-persistence).
- Barrier per wave. Advance ONLY after EVERY member returns (a skipped conditional counts as returned). Merge, mark each task completed/skipped, THEN dispatch the next wave. Mutating steps wait for the barrier.
- One level deep. A dispatched sub-agent executes its own brief; further fan-out stays the orchestrator's job unless that agent's
.claude/agents/*.md definition authorizes it.
NEVER parallelize: tasks sharing a write target · a task consuming a pending task's output · trivial single-file work (dispatch overhead > gain) · an order a skill or workflow explicitly fixes · gates awaiting user approval.
Blocked until: MUST ATTENTION every task tagged PAR/SEQ with a named reason per SEQ · waves declared + write-set disjointness checked · each wave spawned in ONE message · barrier honored before the next wave.
- MANDATORY After planning tasks, tag each PAR/SEQ and spawn every PAR wave as parallel sub-agents in ONE message — default parallel for workflows, batch updates, investigation, research, reviews; plan execution fans out ONLY on what the plan declares.
- MANDATORY Disjoint write sets per wave · all-return barrier before the next wave · specialist routing · sub-agents NEVER fan out further unless their own agent definition authorizes it.
Project Protocol Overlay — Before executing this skill, resolve any PROJECT overlay rules layered onto it: match this skill's name against the Target column of the project's skill-protocol index (docs/project-reference/skill-protocols-reference.md by default; a referenceDocs entry in docs/project-config.json overrides the path), taking the most specific matching tier ONLY — exact name > glob > *. That precedence orders overlays against EACH OTHER, never against this skill. Read ONLY the matched bodies, resolved as <protocols-dir>/<Name>.md; a row's Body link is display text, never a read path. A matched body that is missing or malformed is REPORTED and skipped — never reconstructed from the index Description. No index, or no match -> proceed with no overlay, silently. Full contract: .claude/skills/project-skill-protocol/references/registry.md.
Overlays are ADDITIVE ONLY: they ADD rules on top of this skill's own protocol and NEVER replace, override, disable, or reinterpret a rule it already states — removing every overlay must return this skill to exactly its documented behavior. An overlay is a BRIEF, not an authority escalation: it can NEVER waive a workflow gate, git discipline, a review gate, or a user-confirmation gate. A genuine overlay-vs-skill conflict, or two equally-specific overlays that directly contradict -> surface both to the user; NEVER resolve silently.
MUST ATTENTION resolve project protocol overlays for this skill BEFORE executing — most specific matching tier only (exact > glob > *, which ranks overlays against each other, NEVER against this skill), read only matched bodies at <protocols-dir>/<Name>.md; a missing or malformed body is reported, never reconstructed. Overlays are ADDITIVE ONLY (they never replace this skill's own rules) and are a brief, NEVER an authority escalation; an equal-specificity contradiction goes to the user.
Closing Reminders
Protocols in force (concise digest of the SYNC/shared blocks this skill carries):
Source/Test Drift: Source change → inspect affected tests; don't test migration code.
AI Mistake Prevention: verify generated content against evidence, trace downstream references, verify all affected outputs, re-read after context loss, surface ambiguity.
Sub-Agent Selection: Route specialized domains to matching specialist agent; NEVER code-reviewer.
Nested Task Creation: Expand child phases, link parent when nested, one in_progress.
Project Reference Docs: Read required project docs (always lessons.md) before target work.
Critical Thinking: Traced file:line proof per claim; confidence >80% to act.
Understand Code First: Search 3+ patterns and read code before any modification.
MANDATORY IMPORTANT MUST ATTENTION break work into small todo tasks using TaskCreate BEFORE starting
MANDATORY IMPORTANT MUST ATTENTION search codebase for 3+ similar patterns before creating new code
MANDATORY IMPORTANT MUST ATTENTION cite file:line evidence for every claim (confidence >80% to act)
MANDATORY IMPORTANT MUST ATTENTION add a final review todo task to verify work quality
Parallel Sub-Agent Dispatch: Tag tasks PAR/SEQ, group PAR into disjoint-write-set waves, spawn each wave in ONE message, barrier before advancing.
MANDATORY IMPORTANT MUST ATTENTION READ the following files before starting:
[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.
1---2name: db-migrate-33description: [DevOps] Use when you need to run or create database migrations.4---56<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:START -->78> **[BLOCKING]** Execute skill steps in declared order. NEVER skip, reorder, or merge steps without explicit user approval.9> **[BLOCKING]** Before each step or sub-skill call, update task tracking: set `in_progress` when step starts, set `completed` when step ends.10> **[BLOCKING]** Every completed/skipped step MUST include brief evidence or explicit skip reason.11> **[BLOCKING]** If Task tools are unavailable, create and maintain an equivalent step-by-step plan tracker with the same status transitions.1213<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:END -->1415## Quick Summary1617**Goal:** Create or run database migrations following the repository's documented patterns.1819**Workflow:**20211. **Identify** — Determine migration type (schema migration vs data/document migration)222. **Create** — Generate migration using the configured migration tool or data migration executor (see docs/project-reference/backend-patterns-reference.md)233. **Verify** — Run migration and confirm schema/data changes2425**Key Rules:**2627- Follow the repository's migration patterns (see CLAUDE.md / project-reference docs)28- For CREATE: present the migration design and wait for explicit user approval before creating migration files29- Always backup data before destructive migrations30- Use the configured data migration executor for data/document migrations (see docs/project-reference/backend-patterns-reference.md)3132**Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence percentages (Idea should be more than 80%).**3334Database migration: $ARGUMENTS3536## Instructions37381. **Parse arguments**:39 - `add <name>` → Create new schema/data migration with the configured tool40 - `update` → Apply pending migrations41 - `list` → List all migrations and status42 - `rollback` → Revert last migration43 - No argument → Show migration status44452. **Identify database provider + migration tooling** from project config and project-reference docs:46 - Relational stores: managed by the configured schema-migration tool.47 - Document/key-value/event stores: may use code-based migrations or startup executors defined by the repository.48493. **For schema migrations**:5051Add migration:5253 ```bash54 {configured-migration-add-command} <MigrationName>55 ```5657Update database:5859 ```bash60 {configured-migration-update-command}61 ```6263List migrations:6465 ```bash66 {configured-migration-list-command}67 ```68694. **For data/document migrations**:70 - Often code-based migrations run by the configured migration executor (see docs/project-reference/backend-patterns-reference.md)71 - Location: the repository's configured migration folder — discover from `docs/project-reference/backend-patterns-reference.md`72 - Migrations run automatically on application startup73 - To create: Generate new migration class following existing patterns74755. **Safety checks**:76 - Warn before applying migrations to production77 - Show what changes will be applied78 - Recommend backup before destructive operations79806. **Migration Safety Review (MANDATORY for non-local environments)**:81 - Before applying to staging/production, spawn `database-admin` sub-agent (`subagent_type: "database-admin"`) for safety review82 - Review criteria: locking behavior on large tables, index creation impact under concurrent writes, rollback strategy, zero-downtime feasibility83 - Present findings and get explicit user approval before running the configured migration apply command on non-local environments8485## Sub-Agent Type Override8687> **MANDATORY for non-local migration apply:** Spawn `database-admin` sub-agent (`subagent_type: "database-admin"`) for safety review BEFORE applying to staging or production.88> **Rationale:** `database-admin` specializes in query plans, index impact analysis, locking behavior, backup/restore, and replication — context the main agent lacks for production-safe migration decisions.8990---9192> **[IMPORTANT]** Use `TaskCreate` to break ALL work into small tasks BEFORE starting — including tasks for each file read. This prevents context loss from long files. For simple tasks, AI MUST ATTENTION ask user whether to skip.9394**Prerequisites:** **MUST ATTENTION READ** before executing:9596- `docs/project-reference/domain-entities-reference.md` — Domain entity catalog, relationships, cross-service sync (read when task involves business entities/models)9798<!-- SYNC:source-test-drift-check -->99100> **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.101102<!-- /SYNC:source-test-drift-check -->103104<!-- SYNC:ai-mistake-prevention -->105106> **AI Mistake Prevention** — Failure modes to avoid on every task:107>108> **Re-read files after context changes.** Context compaction, resume, or long-running work can make memory stale; verify current files before acting.109> **Verify generated content against source evidence.** AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.110> **Check downstream references before deleting or renaming.** Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.111> **Trace the full impact chain after edits.** Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.112> **Verify ALL affected outputs, not just the first.** One green check is not all green checks; validate every output surface the change can affect.113> **Assume existing values are intentional — ask WHY before changing OR flagging one as a defect.** Before changing or reporting a constant, limit, flag, cutoff, wording, or pattern, read nearby context and history, the CALLER's ordering, and 2+ sibling call sites of the same convention. A doc stating WHAT without WHY is missing rationale, not proof of a missing guard.114> **Surface ambiguity before acting — don't pick silently.** Multiple valid interpretations require an explicit question or stated assumption with risk.115> **Assert the outcome your system owns, not the intermediate state your infrastructure owns.** When verifying async work, assert the final business state — never the delivery/retry bookkeeping held in shared infrastructure that any co-running process can write. Such a check passes when run alone and flakes the moment anything else shares that infrastructure.116> **Keep shared guidance role-relevant.** Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.117118<!-- /SYNC:ai-mistake-prevention -->119120<!-- SYNC:sub-agent-selection -->121122> **Sub-Agent Selection** — Full routing contract: `.claude/skills/shared/sub-agent-selection-guide.md`123> **Rule:** Route specialized domains (architecture, security, performance, DB, E2E, integration-test, git) to the matching specialist agent (see guide above) — NEVER use `code-reviewer` for these. — why: `code-reviewer` lacks each domain's checklist, so specialized issues slip through.124125<!-- /SYNC:sub-agent-selection -->126127<!-- SYNC:nested-task-creation -->128129> **Nested Task Expansion Contract** — For workflow-step invocation, the `[Workflow] ...` row is only a parent container; the child skill still creates visible phase tasks.130>131> 1. Call `TaskList` first. If a matching active parent workflow row exists, set `nested=true` and record `parentTaskId`; otherwise run standalone.132> 2. Create one task per declared phase before phase work. When nested, prefix subjects `[N.M] $skill-name — phase`.133> 3. When nested, link the parent with `TaskUpdate(parentTaskId, addBlockedBy: [childIds])`.134> 4. Orchestrators must pre-expand a child skill's phase list and link the workflow row before invoking that child skill or sub-agent.135> 5. Mark exactly one child `in_progress` before work and `completed` immediately after evidence is written.136> 6. Complete the parent only after all child tasks are completed or explicitly cancelled with reason.137>138> **Blocked until:** `TaskList` done, child phases created, parent linked when nested, first child marked `in_progress`.139140<!-- /SYNC:nested-task-creation -->141142<!-- SYNC:project-reference-docs-guide -->143144> **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.145>146> 1. Identify scope: file types, domain area, and operation.147> 2. **Read `docs/project-config.json` first — the project's machine-readable map.** It is the single source of truth for THIS repo (modules/paths, framework + search keywords, test/E2E/integration run-commands, design system, architecture rules, workflow patterns); ground exact paths, run-commands, and conventions on it **before investigating, planning, or coding** — never assume framework defaults (`CLAUDE.md` + reference docs are derived from it). If it — or the docs index, `lessons.md`, `CLAUDE.md`, `AGENTS.md`, or any required reference doc — is missing or stale, auto-run `/project-init` or the narrow route (`/project-config`, `/docs-init`, `/scan-all`, `/scan --target=<key>`, `/claude-md-init`) first; if Codex mirrors or `AGENTS.md` are stale, ask the user to run `/sync-codex` (never auto-run it).148> 3. Required docs by trigger: always `docs/project-reference/lessons.md`; doc lookup `docs-index-reference.md`; review `code-review-rules.md`; backend/CQRS/API `backend-patterns-reference.md`; domain/entity `domain-entities-reference.md`; frontend/UI `frontend-patterns-reference.md`; styles/design `scss-styling-guide.md` + `design-system/design-system-canonical.md`; integration tests `integration-test-reference.md`; E2E `e2e-test-reference.md`; feature docs/specs `feature-spec-reference.md` + `spec-system-reference.md` + `spec-principles.md`; behavior/public-contract/spec-test-code sync `workflow-spec-test-code-cycle-reference.md`; derived spec index/ERD/reimplementation guides `spec-system-reference.md` + source Feature Specs under `docs/specs/`; architecture/new area `project-structure-reference.md`.149> 4. Read every required doc, then before target work state: `Reference docs read: ... | Not applicable: ...`.150>151> **Ready when:** scope evaluated, `docs/project-config.json` consulted, required docs checked/read or setup route completed, `lessons.md` confirmed, citation emitted.152153<!-- /SYNC:project-reference-docs-guide -->154155<!-- SYNC:critical-thinking-mindset -->156157> **Critical Thinking Mindset** — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.158> **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.159160<!-- /SYNC:critical-thinking-mindset -->161162<!-- SYNC:understand-code-first -->163164> **Understand Code First** — HARD-GATE: Do NOT write, plan, or fix until you READ existing code.165>166> 1. Search 3+ similar patterns (`grep`/`glob`) — cite `file:line` evidence167> 2. Read existing files in target area — understand structure, base classes, conventions168> 3. Run `python .claude/scripts/code_graph trace <file> --direction both --json` when `.code-graph/graph.db` exists169> 4. Map dependencies via `connections` or `callers_of` — know what depends on your target170> 5. Write investigation to `.ai/workspace/analysis/` for non-trivial tasks (3+ files)171> 6. Re-read analysis file before implementing — never work from memory alone. — why: long context drifts from the file; the file is ground truth172> 7. NEVER invent new patterns when existing ones work — match exactly or document deviation. — why: divergent patterns fragment the codebase and slow every future reader173>174> **BLOCKED until:** `- [ ]` Read target files `- [ ]` Grep 3+ patterns `- [ ]` Graph trace (if graph.db exists) `- [ ]` Assumptions verified with evidence175176<!-- /SYNC:understand-code-first -->177178<!-- SYNC:understand-code-first:reminder -->179180- **MANDATORY IMPORTANT MUST ATTENTION** search 3+ existing patterns and read code BEFORE any modification. Run graph trace when graph.db exists.181 <!-- /SYNC:understand-code-first:reminder -->182183<!-- SYNC:evidence-based-reasoning:reminder -->184185- **MANDATORY IMPORTANT MUST ATTENTION** cite `file:line` evidence for every claim. Confidence >80% to act, <60% = do NOT recommend.186 <!-- /SYNC:evidence-based-reasoning:reminder -->187188<!-- SYNC:critical-thinking-mindset:reminder -->189190**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.191192<!-- /SYNC:critical-thinking-mindset:reminder -->193194<!-- SYNC:ai-mistake-prevention:reminder -->195196**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.197198<!-- /SYNC:ai-mistake-prevention:reminder -->199200<!-- SYNC:project-reference-docs-guide:reminder -->201202- **MANDATORY** Before investigating, planning, or coding, read `docs/project-config.json` (the project map: modules/paths, run-commands, conventions, architecture/workflow rules) + the required project-reference docs, and cite `Reference docs read: ...`.203- **MANDATORY** Always include `lessons.md`; project config + conventions override generic framework defaults.204- **MANDATORY** If project config, root instruction files, or any required reference doc is missing or stale, auto-run `/project-init` or the narrow lower-level route before ordinary project-specific work.205206<!-- /SYNC:project-reference-docs-guide:reminder -->207208<!-- SYNC:nested-task-creation:reminder -->209210- **MANDATORY** Parent workflow rows do not replace child phase tracking; expand phases and link the parent when nested.211- **MANDATORY** Orchestrators pre-expand child skill phases before invocation; use `[N.M] $skill-name — phase` prefixes and one-`in_progress` discipline.212213<!-- /SYNC:nested-task-creation:reminder -->214215<!-- PROMPT-ENHANCE:STEP-TASK-CLOSING:START -->216217## Prompt-Enhance Closing Anchors218219**IMPORTANT MUST ATTENTION** follow declared step order for this skill; NEVER skip, reorder, or merge steps without explicit user approval220**IMPORTANT MUST ATTENTION** for every step/sub-skill call: set `in_progress` before execution, set `completed` after execution221**IMPORTANT MUST ATTENTION** every skipped step MUST include explicit reason; every completed step MUST include concise evidence222**IMPORTANT MUST ATTENTION** if Task tools unavailable, maintain an equivalent step-by-step plan tracker with synchronized statuses223224<!-- PROMPT-ENHANCE:STEP-TASK-CLOSING:END -->225226<!-- SYNC:parallel-subagent-dispatch -->227228> **Parallel Sub-Agent Dispatch** — Plan parallelism the moment a task breakdown exists, BEFORE executing it — running provably independent tasks sequentially wastes wall-clock. Applies to every multi-step job: workflow steps, planning, batch updates, investigation, research, scans, reviews, doc sync. **Plan execution is metadata-gated, NEVER default-parallel** — fan-out follows ONLY what the plan declares (`PAR`/`SEQ` tags + per-phase write set); an untagged plan runs sequentially — why: a derived write set cannot see cascade or generated writes.229>230> 1. **Tag every task `PAR` or `SEQ`.** `PAR` = inputs exclude every pending task's output AND write set disjoint from every other `PAR`. Else `SEQ` — MUST ATTENTION name the dependency forcing it.231> 2. **Group `PAR` into waves.** No edge between members. Two writers of one file NEVER share a wave. Read-only work (search, investigation, review, research) parallelizes freely.232> 3. **Declare before dispatch:** `Parallel plan: wave 1 = [...] · wave 2 = [...] · SEQ = [...] (reason)`.233> 4. **Spawn each wave in ONE message** — every `Agent` call in one response, NEVER dripped per turn. Route each task to its specialist (`.claude/skills/shared/sub-agent-selection-guide.md`); NEVER `code-reviewer` as catch-all.234> 5. **Brief each sub-agent self-contained:** goal · scope + owned files · reference docs · return contract (summary + `Full report:` path, per SYNC:subagent-return-contract) · incremental persistence to `plans/reports/` (per SYNC:incremental-persistence).235> 6. **Barrier per wave.** Advance ONLY after EVERY member returns (a skipped conditional counts as returned). Merge, mark each task completed/skipped, THEN dispatch the next wave. Mutating steps wait for the barrier.236> 7. **One level deep.** A dispatched sub-agent executes its own brief; further fan-out stays the orchestrator's job unless that agent's `.claude/agents/*.md` definition authorizes it.237>238> **NEVER parallelize:** tasks sharing a write target · a task consuming a pending task's output · trivial single-file work (dispatch overhead > gain) · an order a skill or workflow explicitly fixes · gates awaiting user approval.239>240> **Blocked until:** MUST ATTENTION every task tagged PAR/SEQ with a named reason per SEQ · waves declared + write-set disjointness checked · each wave spawned in ONE message · barrier honored before the next wave.241242<!-- /SYNC:parallel-subagent-dispatch -->243244<!-- SYNC:parallel-subagent-dispatch:reminder -->245246- **MANDATORY** After planning tasks, tag each PAR/SEQ and spawn every PAR wave as parallel sub-agents in ONE message — default parallel for workflows, batch updates, investigation, research, reviews; plan execution fans out ONLY on what the plan declares.247- **MANDATORY** Disjoint write sets per wave · all-return barrier before the next wave · specialist routing · sub-agents NEVER fan out further unless their own agent definition authorizes it.248249<!-- /SYNC:parallel-subagent-dispatch:reminder -->250251<!-- SYNC:project-protocol-overlay -->252253> **Project Protocol Overlay** — Before executing this skill, resolve any PROJECT overlay rules layered onto it: match this skill's name against the `Target` column of the project's skill-protocol index (`docs/project-reference/skill-protocols-reference.md` by default; a `referenceDocs` entry in `docs/project-config.json` overrides the path), taking the most specific matching tier ONLY — exact name > glob > `*`. **That precedence orders overlays against EACH OTHER, never against this skill.** Read ONLY the matched bodies, resolved as `<protocols-dir>/<Name>.md`; a row's Body link is display text, never a read path. A matched body that is missing or malformed is REPORTED and skipped — never reconstructed from the index Description. No index, or no match -> proceed with no overlay, silently. Full contract: `.claude/skills/project-skill-protocol/references/registry.md`.254>255> Overlays are **ADDITIVE ONLY**: they ADD rules on top of this skill's own protocol and NEVER replace, override, disable, or reinterpret a rule it already states — removing every overlay must return this skill to exactly its documented behavior. An overlay is a BRIEF, not an authority escalation: it can NEVER waive a workflow gate, git discipline, a review gate, or a user-confirmation gate. A genuine overlay-vs-skill conflict, or two equally-specific overlays that directly contradict -> surface both to the user; NEVER resolve silently.256257<!-- /SYNC:project-protocol-overlay -->258259<!-- SYNC:project-protocol-overlay:reminder -->260261**MUST ATTENTION** resolve project protocol overlays for this skill BEFORE executing — most specific matching tier only (exact > glob > `*`, which ranks overlays against each other, NEVER against this skill), read only matched bodies at `<protocols-dir>/<Name>.md`; a missing or malformed body is reported, never reconstructed. Overlays are ADDITIVE ONLY (they never replace this skill's own rules) and are a brief, NEVER an authority escalation; an equal-specificity contradiction goes to the user.262263<!-- /SYNC:project-protocol-overlay:reminder -->264265## Closing Reminders266267**Protocols in force (concise digest of the SYNC/shared blocks this skill carries):**268269- **Source/Test Drift:** Source change → inspect affected tests; don't test migration code.270- **AI Mistake Prevention:** verify generated content against evidence, trace downstream references, verify all affected outputs, re-read after context loss, surface ambiguity.271- **Sub-Agent Selection:** Route specialized domains to matching specialist agent; NEVER `code-reviewer`.272- **Nested Task Creation:** Expand child phases, link parent when nested, one `in_progress`.273- **Project Reference Docs:** Read required project docs (always `lessons.md`) before target work.274- **Critical Thinking:** Traced `file:line` proof per claim; confidence >80% to act.275- **Understand Code First:** Search 3+ patterns and read code before any modification.276277- **MANDATORY IMPORTANT MUST ATTENTION** break work into small todo tasks using `TaskCreate` BEFORE starting278- **MANDATORY IMPORTANT MUST ATTENTION** search codebase for 3+ similar patterns before creating new code279- **MANDATORY IMPORTANT MUST ATTENTION** cite `file:line` evidence for every claim (confidence >80% to act)280- **MANDATORY IMPORTANT MUST ATTENTION** add a final review todo task to verify work quality281- **Parallel Sub-Agent Dispatch:** Tag tasks PAR/SEQ, group PAR into disjoint-write-set waves, spawn each wave in ONE message, barrier before advancing.282 **MANDATORY IMPORTANT MUST ATTENTION** READ the following files before starting:283284**[TASK-PLANNING]** Before acting, analyze task scope and systematically break it into small todo tasks and sub-tasks using TaskCreate.285286> **[IMPORTANT]** Analyze how big the task is and break it into many small todo tasks systematically before starting — this is very important.