1---
2name: plan
3version: 1.0.0
4description: '[Planning] Use when you need intelligent plan creation with prompt enhancement. Flag: --mode={ci|cro} (default none — standard planning); --mode=ci plans a fix from a GitHub Actions CI run/log, --mode=cro plans conversion-rate optimization (25-item CRO framework).'
5disable-model-invocation: false
6metadata:
7 source: https://skillmd.com/skills/duc01226/plan
8---
9
10<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:START -->
11
12> **[BLOCKING]** Execute skill steps in declared order. NEVER skip, reorder, merge steps without explicit user approval.
13> **[BLOCKING]** Before each step or sub-skill call, update task tracking: `in_progress` on start, `completed` on end.
14> **[BLOCKING]** Every completed/skipped step MUST include evidence or explicit skip reason.
15> **[BLOCKING]** If Task tools unavailable, maintain equivalent step-by-step plan tracker with same status transitions.
16
17<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:END -->
18
19## Quick Summary
20
21**Goal:** Research the codebase and collaborate with the user to deliver a validated, implementation-ready phased plan — every phase startable immediately (exact file paths, zero open decisions, mapped TC IDs) — so coding proceeds without rework at minimum future change cost.
22
23**Summary:**
24
25- PLANNING ONLY — NEVER implement/execute code; produce `plan.md` + per-phase `phase-XX` files + a `goal.md` Goal Contract, then hand off.
26- **Main pipeline (the steps AI keeps forgetting):** pre-check active/suggested plan → bootstrap Goal Contract (`goal.md`) → ONE research wave (`researcher` + `scout` subagents, spawned together, barrier before synthesis) → codebase + project-reference analysis (scout if docs absent) → `planner` subagent writes `plan.md` + `phase-XX` files (Alternatives, Rationale, UI Layout, Test Specs) → parallelism pass (tag every phase PAR/SEQ + write set + `## Execution Waves`) → post-plan granularity self-check → mandatory final tasks.
27- **The plan output itself carries parallelism metadata** — every phase tagged `PAR`/`SEQ` with the write set it owns, every `SEQ` naming its forcing dependency (see [Plan Parallelism Metadata](#plan-parallelism-metadata-mandatory--every-plan-output)). Omitting it is a defect of THIS skill: `/plan-execute` fans out only on what the plan declares.
28- **`--mode={ci|cro}` routing:** `ci` plans a fix from a GitHub Actions run/log (loads `references/mode-ci.md`); `cro` plans conversion-rate optimization (25-item framework, `references/mode-cro.md`); default (no flag) = standard flow. Mode only ADDS a reference payload — SAME engine, SAME `/plan-review` gate, SAME `planner` agent.
29- Default mode HARD (parallel subagents, project-reference docs, the `/plan-review` convergence loop under its 3-round ceiling); fast mode ONLY when EVERY trivial-task condition holds. Every phase passes the 5-point granularity check ("Can I start coding RIGHT NOW?"), carries `## Test Specifications` with TC IDs, uses bottom-up estimation (phase-hours drive man-days; SP DERIVED).
30- **Mandatory final tasks + gates:** write Test Specs per phase → `/plan-validate` → `/plan-review` (convergence loop, 3-round ceiling) → `/why-review` (standalone) → re-estimate vs finalized phases; New Tech/Lib gate before approval; **Domain Entity Gate (MANDATORY when the plan touches an entity/VO/aggregate)** — apply `SYNC:domain-entity-change-gate` so the plan DECIDES classification, invariant ownership, aggregate boundary, concurrency, construction, events, and the test obligation (each naming its owning file) instead of deferring them to implementation; `AskUserQuestion` confirm before any next step.
31
32**Workflow:**
33
341. **Pre-Check** — Detect active/suggested plan or create new directory
352. **Research wave** — All independent research threads spawned in ONE message (researcher + scout subagents, max 5 tool calls each), then a barrier before synthesis
363. **Codebase Analysis** — Search for project reference docs (patterns-reference, project-structure, architecture, adr); scout if not found
374. **Plan Creation** — Planner subagent creates plan.md + phase-XX files with full sections
385. **Parallelism pass** — Tag every phase PAR/SEQ with its write set; declare `## Execution Waves` in plan.md
396. **Post-Validation** — Optionally interview user to confirm decisions via /plan-validate
40
41**Key Rules:**
42
43- PLANNING ONLY: do NOT implement or execute code changes
44- Always run /plan-review after plan creation
45- Ask user to confirm before any next step
46- **MANDATORY IMPORTANT MUST ATTENTION** detect new tech/lib in plan and create validation task (see New Tech/Lib Gate below)
47- **MANDATORY IMPORTANT MUST ATTENTION** when the plan touches an entity, value object, or aggregate, run the **Domain Entity Gate** below — state paradigm + subdomain fit BEFORE any entity task, and answer every triggered decision row with its OWNING FILE; "discover during implementation" is not an answer. Record `No domain-entity surface — gate N/A` when it does not fire
48
49## First Principle — Easy to Change
50
51> **Success metric of every coding decision: _future change cost_.**
52> DRY, SRP, abstraction, design patterns, naming, layering, tests — every
53> technique serves one goal: **making next change cheaper**.
54
55Evaluating code, refactor, test, abstraction, ask:
56**does this make next change cheaper or more expensive?**
57
58- Reject "best practices" raising change cost (premature abstraction,
59 speculative generality, leaky indirection, ceremony without payoff).
60- Name real enemies in findings: **coupling, hidden state, duplicated
61 knowledge, unclear intent, irreversible decisions exposed too early**.
62- Simpler design easy to change beats sophisticated design that isn't.
63
64Apply this lens **before** invoking any rule, pattern, or checklist
65below — if a downstream rule raises change cost, this principle wins.
66
67---
68
69## Default Mode Policy
70
71> **Default mode HARD (full rigor).** Every section below — parallel researcher subagents, the full `/plan-review` convergence loop (3-round ceiling), base-class greps, microservices/event-driven analysis, mandatory user approval — applies by default.
72>
73> **Opt out to fast mode ONLY when ALL true** (task genuinely trivial):
74>
75> - Single-file edit, ≤30 lines changed
76> - No design choice (only one reasonable approach)
77> - No cross-service impact, no contract change, no new dependency
78> - No new pattern — follows existing codebase pattern
79> - User explicitly asked for a quick change
80>
81> **Any condition fails → use full protocol below.** When in doubt, default hard — skipping rigor on a non-trivial task wastes more rework than rigor saves.
82>
83> **Fast mode skips (and only skips):** parallel researcher subagents (direct grep instead), the `/plan-review` re-review loop (single round, no fresh re-review even when findings remain), `/plan-validate` interview (inline confirm only), New Tech/Lib Gate (only if truly no new deps).
84
85## New Tech/Lib Gate (MANDATORY for all plans)
86
87**MANDATORY IMPORTANT MUST ATTENTION** after plan creation, detect new tech/packages/libraries not in project. If found: `TaskCreate` per lib → WebSearch top 3 alternatives → compare (fit, size, community, learning curve, license) → recommend with confidence % → `AskUserQuestion` to confirm. **Skip if** plan uses only existing dependencies.
88
89## Domain Entity Gate (MANDATORY when the plan touches an entity, VO, or aggregate)
90
91> Apply `SYNC:domain-entity-change-gate` (inlined below) — the SAME protocol `/plan-review` and `/changes-review` read, and whose A–P checklist `/domain-entities-review` owns. — why: a plan that leaves aggregate boundary, invariant ownership, or concurrency to "discover during implementation" ships a design review will reject, and the rework is paid twice.
92
93**Fires when** the plan introduces or changes a domain entity / value object / aggregate root, its fields, invariants, relationships, or state transitions; an aggregate boundary, repository, or cross-aggregate reference; a domain event; or a concurrency/reconstitution concern. Otherwise record `No domain-entity surface — gate N/A`.
94
95**The plan MUST name the decision AND the owning file for every triggered row** — an unanswered row is a plan that is not executable:
96
971. **Classification** — entity vs value object vs aggregate root (swap test applied).
982. **Invariant ownership** — which rules the entity enforces vs which the boundary validates; failure signalling (throw vs `Result`) consistent with the project convention.
993. **Aggregate boundary + concurrency** — what shares a transaction and why; cross-aggregate refs by ID; concurrency token on the ROOT; enforcing mechanism for any set-based invariant.
1004. **Construction vs reconstitution** — separate creation and load paths; load raises no events.
1015. **Events** — what is raised, when it dispatches (after commit / outbox), domain vs integration contract.
1026. **Test obligation** — each invariant gets a property TC + boundary counter-case as a planned task, NEVER left implicit.
103
104MUST ATTENTION state **paradigm** (OO-mutable / type-driven-immutable / event-sourced) and **subdomain fit** (core / supporting / generic / CRUD) BEFORE planning entity tasks — NEVER plan a rich domain model for a CRUD subdomain, and NEVER plan setter/mutability tasks against an immutable or event-sourced model.
105
106---
107
108## Greenfield Mode
109
110> **Auto-detected:** No existing codebase found (no discovered source directories, no manifest files, no populated `project-config.json`) → skill auto-switches to greenfield mode. Planning artifacts (docs/, plans/, .claude/) don't count — repository must have actual code directories with content.
111
112**When greenfield detected:**
113
1141. Skip codebase analysis phase (researcher subagents grepping code)
1152. **Replace with:** market research + business evaluation via WebSearch + WebFetch
1163. Delegate architecture decisions to `solution-architect` agent
1174. Output: `plans/{id}/plan.md` with greenfield-specific phases (domain model, tech stack, project structure)
1185. Skip reading project reference docs (won't exist in greenfield)
1196. Enable broad web research: tech landscape, best practices, framework comparisons
1207. Every decision point requires AskUserQuestion with 2-4 options + confidence %
1218. **[CRITICAL] Business-First Protocol:** Tech stack decisions come AFTER full business analysis. Do NOT ask user to pick tech stack upfront. Instead: complete business evaluation → derive technical requirements → research current market options → produce comparison report → present to user. See `solution-architect` agent for full tech stack research methodology.
122
123- Research reports <=150 lines; plan.md <=80 lines
124- **External Memory:** Write all research/analysis to `.ai/workspace/analysis/{task-name}.analysis.md`. Re-read ENTIRE analysis file before generating plan.
125
126Run the planning methodology engine. Load the relevant `references/engine-*.md` for each phase (skip a phase per its own skip rule):
127
128- `references/engine-research.md` — Research & Analysis (skip if given researcher reports)
129- `references/engine-figma.md` — Design Context Extraction (skip if no Figma URLs / backend-only)
130- `references/engine-codebase-understanding.md` — Codebase Understanding (skip if given scout reports)
131- `references/engine-solution-design.md` — Solution Design (trade-offs, security, performance, edge cases, architecture)
132- `references/engine-plan-organization.md` — Plan Creation, Organization & Output Standards
133
134## Mode Dispatch (`--mode={ci|cro}`)
135
136> **Default (no `--mode` flag): IGNORE this section — run the standard plan flow below, byte-for-byte unchanged.** `--mode` only adds a domain-specific reference load + intake convention on top of the SAME engine, the SAME mandatory `/plan-review` gate, and the SAME `planner` agent. It never replaces the engine.
137
138| Flag | Positional `$ARGUMENTS` | Load before planning | Plan frontmatter overrides |
139| ------------ | ----------------------------------------------------- | -------------------------------------------------------------------------------- | ----------------------------------------- |
140| `--mode=ci` | a GitHub Actions run/log URL | `references/mode-ci.md` (CI failure classes: build/test/env/Docker/dependencies) | `priority: P1`, `tags: [ci, bugfix]` |
141| `--mode=cro` | content/issues to optimize (optional screenshots/URL) | `references/mode-cro.md` (25-item CRO framework + multimodal intake) | `priority: P2`, `tags: [cro, conversion]` |
142
143When a `--mode` is present: (1) read the matching `references/mode-*.md`; (2) apply its intake + domain focus to `$ARGUMENTS`; (3) run the standard plan workflow below — same `planner` subagent, same phase-file structure, same mandatory `/plan-review`. The mode adds a reference payload only.
144
145## Scaffolding-First Protocol (Conditional)
146
147**Activation conditions (ALL must be true):**
148
1491. Active workflow is `workflow-greenfield-init` OR `workflow-big-feature`
1502. AI MUST ATTENTION self-investigate for existing base/foundational abstractions using these patterns:
151 - Abstract/base classes: `abstract class.*Base|Base[A-Z]\w+|Abstract[A-Z]\w+`
152 - Generic interfaces: `interface I\w+<|IGeneric|IBase`
153 - Infrastructure abstractions: `IRepository|IUnitOfWork|IService|IHandler`
154 - Utility/extension layers: `Extensions|Helpers|Utils|Common` (directories or classes)
155 - Frontend foundations: `base.*component|base.*service|base.*store|abstract.*component` (if frontend present)
156 - DI/IoC registration: search for DI registration patterns idiomatic to project's framework
1573. If existing scaffolding found → **SKIP.** Log: "Existing scaffolding detected at {file:line}. Skipping Phase 1 scaffolding."
1584. If NO foundational abstractions found → **PROCEED** with scaffolding phase.
159
160**When activated:**
161
162Phase 1 of plan MUST ATTENTION be **Architecture Scaffolding** — all base abstract classes, generic interfaces, infrastructure abstractions, DI registration with OOP/SOLID principles. Runs BEFORE feature stories. AI self-investigates what base classes the tech stack needs. All infrastructure behind interfaces with ≥1 concrete implementation (Dependency Inversion). Phase 1's deliverable MUST ATTENTION also include the **golden-path example set** `/scaffold` emits — one worked, compile-checked `*.example.*` per applicable pattern (backend: command · query · handler · entity-with-invariants · value-object · repository · domain event + event handler; frontend-if-UI: form · list · store · API service; tests: one integration test on happy + failure path) in an isolated, production-excluded `examples/` tree using the scaffolded base abstractions, so post-scaffold `/architecture-review-full` gate has real, gradeable code before any feature work.
163
164**When skipped:** Plan proceeds normally — feature stories build on existing base classes.
165
166## PLANNING-ONLY — Collaboration Required
167
168> **DO NOT** use the `EnterPlanMode` tool — already in a planning workflow.
169> **DO NOT** implement or execute any code changes.
170> **COLLABORATE** with user: ask decision questions, present options with recommendations.
171> After plan creation, ALWAYS run `/plan-review` to validate plan.
172> ASK user to confirm plan before any next step.
173
174## Your mission
175
176<task>
177$ARGUMENTS
178</task>
179
180## Pre-Creation Check (Active vs Suggested Plan)
181
182Check `## Plan Context` section in injected context:
183
184- If "Plan:" shows a path → Active plan exists. Ask user: "Continue with this? [Y/n]"
185- If "Suggested:" shows a path → Branch-matched hint only. Ask if user wants to activate or create new.
186- If "Plan: none" → Create new plan using naming from `## Naming` section.
187
188## Workflow
189
1901. If creating new: create directory using `Plan dir:` from `## Naming` section, then run `node .claude/scripts/set-active-plan.cjs {plan-dir}`. If reusing: use active plan path from Plan Context. Pass directory path to every subagent.
1912. **Goal Contract bootstrap (BEFORE investigation and phase writing):** resolve active goal per `SYNC:goal-contract-satisfaction-loop` — create/update `{plan-dir}/goal.md` from `.claude/templates/goal-contract-template.md`, recording original request, purpose, success criteria, constraints, required evidence. Every phase's success criteria maps to a saved goal criterion. Redact secrets.
1923. Follow strictly the "Plan Creation & Organization" rules in `references/engine-plan-organization.md`.
1934. **Project-reference preflight — BEFORE dispatch.** Resolve and read the required project-reference documents first. Record missing or stale references as scoped research inputs; never discover the governing conventions only after workers have already started.
1945. **Research wave — ONE message, ONE barrier.** Enumerate the independent research threads this task needs — per-module code investigation, pattern discovery, dependency mapping, prior-art/library search — then tag each `PAR`/`SEQ` and declare `Parallel plan: wave 1 = [...] · SEQ = [...] (reason)` before dispatch. Research is read-only, so a thread is `PAR` unless it consumes another thread's output (name that output). Spawn the whole wave in ONE message: `researcher` agents (max 2) for external/prior-art threads, max 5 tool calls per agent; `scout` agents for codebase threads, one per module/area with a disjoint read scope. Give each agent its own report path under `{plan-dir}/research/` or `{plan-dir}/scout/` so no two agents write the same file.
1956. Analyze codebase against the preflight references. **ONLY IF a required reference is missing or older than 3 days:** include a scoped `/scout <instructions>` member in the research wave to gather the missing evidence; do not launch an unplanned later round trip.
1967. **Barrier, then synthesize.** Advance only after EVERY wave member returns (a skipped thread counts as returned). Read the report FILES (not memory), reconcile conflicting findings, and record unresolved gaps — a second wave is dispatched only for gaps the first wave exposed.
1978. Main agent gathers research/scout report filepaths; pass to `planner` subagent with prompt to create implementation plan.
1989. **Parallelism pass (MANDATORY before handoff).** Validate each phase's **Mode, Wave, write set, and SEQ dependency**, then write the `## Execution Waves` line — see [Plan Parallelism Metadata](#plan-parallelism-metadata-mandatory--every-plan-output). This is what lets `/plan-execute` fan out; an untagged plan executes strictly sequentially.
19910. Main agent receives implementation plan from `planner`; ask user to review.
200
201## Post-Plan Validation (Optional)
202
203After plan creation, offer validation interview to confirm decisions before implementation.
204
205**Check `## Plan Context` → `Validation: mode=X, questions=MIN-MAX`:**
206
207| Mode | Behavior |
208| -------- | ------------------------------------------------------------------------------- |
209| `prompt` | Ask user: "Validate this plan with a brief interview?" → Yes (Recommended) / No |
210| `auto` | Automatically execute `/plan-validate {plan-path}` |
211| `off` | Skip validation step entirely |
212
213**If mode is `prompt`:** Use `AskUserQuestion` tool with options above.
214**If user chooses validation or mode is `auto`:** Execute `/plan-validate {plan-path}` SlashCommand.
215
216## Output Requirements
217
218**Plan Directory Structure** (use `Plan dir:` from `## Naming` section)
219
220```
221{plan-dir}/
222├── research/
223│ ├── researcher-XX-report.md
224│ └── ...
225├── reports/
226│ ├── XX-report.md
227│ └── ...
228├── scout/
229│ ├── scout-XX-report.md
230│ └── ...
231├── plan.md
232├── phase-XX-phase-name-here.md
233└── ...
234```
235
236**Research Output Requirements**
237
238- Research markdown reports concise (<=150 lines); cover all topics + citations.
239
240**Plan File Specification**
241
242- Every `plan.md` MUST ATTENTION start with YAML frontmatter:
243
244 ```yaml
245 ---
246 title: '{Brief title}'
247 description: '{One sentence for card preview}'
248 status: pending
249 priority: P2
250 effort: { sum of phases, e.g., 4h }
251 story_points: { sum of phase SPs, e.g., 8 }
252 man_days_traditional: '{ total e.g., 6d (4d code + 2d test) }'
253 man_days_ai: '{ total with AI e.g., 3d (2d code + 1d test) }'
254 branch: { current git branch }
255 tags: [relevant, tags]
256 created: { YYYY-MM-DD }
257 ---
258 ```
259
260- Save overview at `{plan-dir}/plan.md` (<80 lines): list each phase with status, progress, **Mode (`PAR`/`SEQ`)**, links to phase files; add the `## Execution Waves` line below the phases table.
261- For each phase, create `{plan-dir}/phase-XX-phase-name-here.md` with sections: Context links, Overview, Key Insights, Requirements, **Alternatives Considered** (minimum 2 approaches with pros/cons), **Design Rationale** (WHY chosen approach), Architecture, **UI Layout** (see below), Related code files, **Parallel Execution** (Mode `PAR`/`SEQ` · Write set · SEQ dependency — see below), Implementation Steps, Todo list, Success Criteria, Risk Assessment, Security Considerations, Next steps.
262- **UI Layout:** For frontend-facing phases, include ASCII wireframe. Classify components by tier (common/domain-shared/page-app). For backend-only phases: `## UI Layout` → `N/A — Backend-only change.`
263
264## Plan Parallelism Metadata (MANDATORY — every plan output)
265
266`/plan-execute` fans out ONLY on what the plan declares. An untagged plan forces sequential execution, so omitting this metadata is a defect of THIS skill, not of the executor.
267
2681. **Tag every phase `PAR` or `SEQ`** — in the `plan.md` phases table (`Mode` column) and in each phase file's `## Parallel Execution` section. `PAR` = its inputs contain no pending phase's output AND its write set is disjoint from every other `PAR` phase.
2692. **Declare the write set per phase** — the exact file paths the phase creates / modifies / deletes (globs only when their members are enumerable from the plan). Two `PAR` phases MUST have disjoint write sets; any overlap → merge the phases, or demote the later one to `SEQ` and name the shared file.
2703. **Every `SEQ` names its forcing dependency** — `SEQ — needs phase-02's {migration | generated type | contract | file}`. "Feels sequential", "safer in order", or an unnamed dependency is not a reason: retag it `PAR`.
2714. **Group `PAR` phases into waves** in a `## Execution Waves` line in `plan.md`:
272 `Execution waves: wave 1 = [phase-01, phase-03] · wave 2 = [phase-04] · SEQ = [phase-02 (needs phase-01 schema), phase-06 (approval gate)]`.
2735. **Gates and reviews are SEQ boundaries** — a user-approval, review, verification, or migration phase never shares a wave with the phases it gates; it runs after that wave's barrier.
2746. **Phase-file block format** (copy verbatim into each phase file):
275
276 ```markdown
277 ## Parallel Execution
278
279 - Mode: PAR | SEQ
280 - Write set: `src/a/x.ts`, `src/a/x.spec.ts`
281 - Wave: 1
282 - SEQ dependency: {name the phase + the exact artifact it produces — omit when Mode: PAR}
283 ```
284
285**Behavior/Sync Planning Checks**
286
287- For behavior-changing work, every phase should name changed behavior, unchanged behavior to preserve, TC/test proof, and docs/spec sync action.
288- For AI-extracted specs/TCs, plan must mark them reference-only until canonical acceptance.
289- For `.claude` skills/hooks/workflows/sync tooling, plan must include generated mirror sync or explicit no-sync evidence.
290
291## **IMPORTANT Task Planning Notes (MUST ATTENTION FOLLOW)**
292
293- Always break work into many small todo tasks via `TaskCreate`
294- Always add a final review todo task to verify work quality and identify fixes/enhancements
295- **MANDATORY FINAL TASKS:** After all planning todos, ALWAYS add these final tasks:
296 1. **Task: "Write test specifications for each phase"** — Add `## Test Specifications` with TC-{FEATURE}-{NNN} IDs to every phase file. Use `/spec [mode=tests]` if feature docs exist; `Evidence: TBD` for TDD-first mode.
297 2. **Task: "Run /plan-validate"** — `/plan-validate` skill interviews user with critical questions, validates plan assumptions.
298 3. **Task: "Run /plan-review"** — `/plan-review` skill, convergence loop (review → validate findings → fix → fresh full re-review) bounded by a **3-round ceiling, NEVER a target**: a clean pass ENDS the loop at ANY round, round 1 included; round 3 completing with CRITICAL/HIGH/MEDIUM still open escalates via `AskUserQuestion`, never a silent PASS. SP raises the RIGOR of each round, never a round floor: ≤3 → checklist + code-proof trace; 4-8 → + adversarial simulation; >8 → code-proof trace mandatory in every round.
299 4. **Task: "Run /why-review (standalone only)"** — If NOT inside a workflow, `/why-review` validates design rationale, alternatives considered, risk assessment. Skip if a workflow already includes `/why-review`.
300 5. **Task: "Re-evaluate estimation against finalized plan"** — Pre-completion estimates anchor on scope guesses; finalized phases reveal true cost. After phases/TCs/decisions locked: (a) re-derive `bottom_up_hours = Σ phase_hours` from finalized phase files; (b) recompute `likely_days`, `risk_margin_pct`, `min-max range` per `SYNC:estimation-framework`; (c) compare to current frontmatter `man_days_traditional` / `story_points`. If `|delta| > 20%` → UPDATE frontmatter, add `reestimate_delta_pct: <signed>` + 1-line `reestimate_reason`. If `|delta| > 50%` → flag `SHOULD-RESCOPE` and surface to user via `AskUserQuestion` before implementation.
301
302## Important Notes
303
304- Activate needed skills from catalog during process.
305- Token efficiency without sacrificing quality. Sacrifice grammar for concision in reports.
306- Unresolved questions → list at end of report.
307
308---
309
310## Standalone Review Gate (Non-Workflow Only)
311
312> **MANDATORY IMPORTANT MUST ATTENTION:** If skill is called **outside a workflow** (standalone `/plan`), generated plan MUST ATTENTION include `/changes-review` as a **final phase/task** in plan. Ensures all implementation changes get reviewed before commit even without a workflow enforcing it.
313>
314> If already running inside a workflow (e.g., `workflow-feature`, `workflow-bugfix`), skip this — workflow sequence handles `/changes-review` at appropriate step.
315
316## Next Steps (Standalone: MUST ATTENTION ask user via `AskUserQuestion`. Skip if inside workflow.)
317
318**MANDATORY IMPORTANT MUST ATTENTION — NO EXCEPTIONS** after completing this skill, MUST ATTENTION use `AskUserQuestion` to present these options. Do NOT skip because task seems "simple" or "obvious" — user decides:
319
320- **"Proceed with full workflow (Recommended)"** — Detect best workflow to continue (plan created). Ensures review, validation, implementation, testing not skipped.
321- **"/why-review"** — Validate design rationale before implementation (standalone only — skipped when workflow includes it)
322- **"/plan-review"** — Validate plan before implementation
323- **"/plan-validate"** — Interview user to confirm plan decisions
324- **"/plan-execute"** — Start coding & testing the finalized plan. Recommended implementation route after plan validated.
325- **"Skip, continue manually"** — user decides
326
327## Post-Plan Granularity Self-Check (MANDATORY)
328
329After creating all phase files, run **recursive decomposition loop**:
330
3311. Score each phase against 5-point criteria (file paths, no planning verbs, ≤30min steps, ≤5 files, no open decisions)
3322. Each FAILING phase → create task to decompose into sub-plan (with own /plan → /plan-review → /plan-validate → fix cycle)
3333. Re-score new phases. Repeat until ALL leaf phases pass (max depth: 3)
3344. **Self-question:** "For each phase, can I start coding RIGHT NOW? If any needs 'figuring out' → sub-plan it."
335
336## Preservation Inventory (MANDATORY for bugfixes)
337
338> **[IMPORTANT]** Use `TaskCreate` to break ALL work into small tasks BEFORE starting — including tasks for each file read. Prevents context loss from long files. For simple tasks, MUST ATTENTION ask user whether to skip.
339
340- `docs/project-reference/domain-entities-reference.md` — Domain entity catalog, relationships, cross-service sync (read when task involves business entities/models)
341- `docs/specs/` — Test specifications by module (read existing TCs to include test strategy in plan)
342
343> Each phase file MUST ATTENTION satisfy: <=5 files per phase, <=3h effort, clear success criteria, mapped test cases.
344
345> **Evidence Gate:** MANDATORY IMPORTANT MUST ATTENTION — every claim, finding, recommendation requires `file:line` proof or traced evidence with confidence percentage (>80% to act, <80% must verify first).
346
347> **External Memory:** For complex or lengthy work (research, analysis, scan, review), write intermediate findings and final results to a report file in `plans/reports/` — prevents context loss and serves as deliverable.
348
349<!-- SYNC:plan-granularity -->
350
351> **Plan Granularity** — Every phase must pass 5-point check before implementation:
352>
353> 1. Lists exact file paths to modify (not generic "implement X")
354> 2. No planning verbs (research, investigate, analyze, determine, figure out)
355> 3. Steps ≤30min each, phase total ≤3h
356> 4. ≤5 files per phase
357> 5. No open decisions or TBDs in approach
358>
359> **Failing phases →** create sub-plan. Repeat until ALL leaf phases pass (max depth: 3).
360> **Self-question:** "Can I start coding RIGHT NOW? If any step needs 'figuring out' → sub-plan it."
361
362<!-- /SYNC:plan-granularity -->
363
364<!-- SYNC:preservation-inventory -->
365
366> **Preservation Inventory** — MANDATORY for bugfix plans. Trigger keywords in plan title/frontmatter: `fix`, `bug`, `regression`, `broken`, `defect`. Author MUST produce this table BEFORE writing implementation steps.
367>
368> **Columns:** `Invariant | file:line | Why (data consequence if broken) | Verification (TC-ID or grep)`
369>
370> **BLOCKED until:** ≥3 rows · every File cell has `file:line` · every Verification cell has TC-ID or grep (not "manually verify")
371
372<!-- /SYNC:preservation-inventory -->
373
374<!-- SYNC:nested-task-creation -->
375
376> **Nested Task Expansion Contract** — For workflow-step invocation, the `[Workflow] ...` row is only a parent container; the child skill still creates visible phase tasks.
377>
378> 1. Call `TaskList` first. If a matching active parent workflow row exists, set `nested=true` and record `parentTaskId`; otherwise run standalone.
379> 2. Create one task per declared phase before phase work. When nested, prefix subjects `[N.M] $skill-name — phase`.
380> 3. When nested, link the parent with `TaskUpdate(parentTaskId, addBlockedBy: [childIds])`.
381> 4. Orchestrators must pre-expand a child skill's phase list and link the workflow row before invoking that child skill or sub-agent.
382> 5. Mark exactly one child `in_progress` before work and `completed` immediately after evidence is written.
383> 6. Complete the parent only after all child tasks are completed or explicitly cancelled with reason.
384>
385> **Blocked until:** `TaskList` done, child phases created, parent linked when nested, first child marked `in_progress`.
386
387<!-- /SYNC:nested-task-creation -->
388
389<!-- SYNC:project-reference-docs-guide -->
390
391> **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.
392>
393> 1. Identify scope: file types, domain area, and operation.
394> 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).
395> 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`.
396> 4. Read every required doc, then before target work state: `Reference docs read: ... | Not applicable: ...`.
397>
398> **Ready when:** scope evaluated, `docs/project-config.json` consulted, required docs checked/read or setup route completed, `lessons.md` confirmed, citation emitted.
399
400<!-- /SYNC:project-reference-docs-guide -->
401
402<!-- SYNC:task-tracking-external-report -->
403
404> **Task Tracking & External Report Persistence** — Bootstrap this before execution; then run project-reference doc prefetch before target/source work.
405>
406> 1. Create a small task breakdown before target file reads, grep, edits, or analysis. On context loss, inspect the current task list first.
407> 2. Mark one task `in_progress` before work and `completed` immediately after evidence; never batch transitions.
408> 3. For plan/review work, create `plans/reports/{skill}-{YYMMDD}-{HHmm}-{slug}.md` before first finding.
409> 4. Append findings after each file/section/decision and synthesize from the report file at the end.
410> 5. Final output cites `Full report: plans/reports/{filename}`.
411>
412> **Blocked until:** task breakdown exists, report path declared for plan/review work, first finding persisted before the next finding.
413
414<!-- /SYNC:task-tracking-external-report -->
415
416<!-- SYNC:critical-thinking-mindset -->
417
418> **Critical Thinking Mindset** — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
419> **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.
420
421<!-- /SYNC:critical-thinking-mindset -->
422
423<!-- SYNC:sequential-thinking-protocol -->
424
425> **Sequential Thinking Protocol** — Structured multi-step reasoning for complex/ambiguous work. Use when planning, reviewing, debugging, or refining ideas where one-shot reasoning is unsafe.
426>
427> **Trigger when:** complex problem decomposition · adaptive plans needing revision · analysis with course correction · unclear/emerging scope · multi-step solutions · hypothesis-driven debugging · cross-cutting trade-off evaluation.
428>
429> **Format (explicit mode — visible thought trail):**
430>
431> 1. `Thought N/M: [aspect]` — one aspect per thought, state assumptions/uncertainty
432> 2. `Thought N/M [REVISION of Thought K]: ...` — when prior reasoning invalidated; state Original / Why revised / Impact
433> 3. `Thought N/M [BRANCH A from Thought K]: ...` — explore alternative; converge with decision rationale
434> 4. `Thought N/M [HYPOTHESIS]: ...` then `[VERIFICATION]: ...` — test before acting
435> 5. `Thought N/N [FINAL]` — only when verified, all critical aspects addressed, confidence >80%
436>
437> **Mandatory closers:** Confidence % stated · Assumptions listed · Open questions surfaced · Next action concrete.
438>
439> **Stop conditions:** confidence <80% on any critical decision → escalate via AskUserQuestion · ≥3 revisions on same thought → re-frame the problem · branch count >3 → split into sub-task.
440>
441> **Implicit mode:** apply methodology internally without visible markers when adding markers would clutter the response (routine work where reasoning aids accuracy).
442>
443> **Deep-dive:** see `/sequential-thinking` skill (`.claude/skills/sequential-thinking/SKILL.md`) for worked examples (API design, debugging, architecture), advanced techniques (spiral refinement, hypothesis testing, convergence), and meta-strategies (uncertainty handling, revision cascades).
444
445<!-- /SYNC:sequential-thinking-protocol -->
446
447<!-- SYNC:understand-code-first -->
448
449> **Understand Code First** — HARD-GATE: Do NOT write, plan, or fix until you READ existing code.
450>
451> 1. Search 3+ similar patterns (`grep`/`glob`) — cite `file:line` evidence
452> 2. Read existing files in target area — understand structure, base classes, conventions
453> 3. Run `python .claude/scripts/code_graph trace <file> --direction both --json` when `.code-graph/graph.db` exists
454> 4. Map dependencies via `connections` or `callers_of` — know what depends on your target
455> 5. Write investigation to `.ai/workspace/analysis/` for non-trivial tasks (3+ files)
456> 6. Re-read analysis file before implementing — never work from memory alone. — why: long context drifts from the file; the file is ground truth
457> 7. NEVER invent new patterns when existing ones work — match exactly or document deviation. — why: divergent patterns fragment the codebase and slow every future reader
458>
459> **BLOCKED until:** `- [ ]` Read target files `- [ ]` Grep 3+ patterns `- [ ]` Graph trace (if graph.db exists) `- [ ]` Assumptions verified with evidence
460
461<!-- /SYNC:understand-code-first -->
462
463<!-- SYNC:cross-service-check -->
464
465> **Cross-Service Check** — Microservices/event-driven: MANDATORY before concluding investigation, plan, spec, or feature doc. Missing downstream consumer = silent regression.
466>
467> | Boundary | Grep terms |
468> | ------------------- | ------------------------------------------------------------------------------- |
469> | Event producers | `Publish`, `Dispatch`, `Send`, `emit`, `EventBus`, `outbox`, `IntegrationEvent` |
470> | Event consumers | `Consumer`, `EventHandler`, `Subscribe`, `@EventListener`, `inbox` |
471> | Sagas/orchestration | `Saga`, `ProcessManager`, `Choreography`, `Workflow`, `Orchestrator` |
472> | Sync service calls | HTTP/gRPC calls to/from other services |
473> | Shared contracts | OpenAPI spec, proto, shared DTO — flag breaking changes |
474> | Data ownership | Other service reads/writes same table/collection → Shared-DB anti-pattern |
475>
476> **Per touchpoint:** owner service · message name · consumers · risk (NONE / ADDITIVE / BREAKING).
477>
478> **BLOCKED until:** Producers scanned · Consumers scanned · Sagas checked · Contracts reviewed · Breaking-change risk flagged
479
480<!-- /SYNC:cross-service-check -->
481
482<!-- SYNC:estimation-framework -->
483
484> **Estimation Framework** — Bottom-up first; SP DERIVED; output min-max range when likely ≥3d. Stack-agnostic. Baseline: 3-5yr dev, 6 productive hrs/day. AI estimate assumes Claude Code + project context.
485>
486> **Method:**
487>
488> 1. **Blast Radius pass** (below) — drives code AND test cost
489> 2. Decompose phases → hours/phase → `bottom_up_hours = Σ phase_hours`
490> 3. `likely_days = ceil(bottom_up_hours / 6) × productivity_factor`
491> 4. Sum **Risk Margin** (base + add-ons) → `max_days = likely_days × (1 + margin)`
492> 5. `min_days = likely_days × 0.9`
493> 6. Output as range when `likely_days ≥3`; single point allowed `<3` (still record margin)
494> 7. `man_days_ai` = same range × AI speedup
495> 8. `story_points` DERIVED from `likely_days` via SP-Days — NEVER driver. Disagreement >50% → trust bottom-up
496>
497> **Productivity factor:** 0.8 strong scaffolding+codegen+AI hooks · 1.0 mature default · 1.2 weak patterns · 1.5 greenfield
498>
499> **Cost Driver Heuristic (apply BEFORE work-type row):**
500>
501> - **UI dominates** in CRUD/business apps — 1.5-3x backend (states, validation, responsive, a11y, polish)
502> - **Backend dominates ONLY:** multi-aggregate invariants, cross-service contracts, schema migrations, heavy query/perf, new event flows
503>
504> **Reuse-vs-Create axis (PRIMARY lever, per layer):**
505>
506> | UI tier | Cost |
507> | -------------------------------------------- | -------- |
508> | Reuse component on existing screen | 0.1-0.3d |
509> | Add control/column to existing screen | 0.3-0.8d |
510> | Compose components into NEW screen | 1-2d |
511> | NEW screen, custom layout/states/validation | 2-4d |
512> | NEW shared/common component (themed, tested) | 3-6d+ |
513>
514> | Backend tier | Cost |
515> | ---------------------------------------------------- | --------- |
516> | Reuse query/handler from new place | 0.1-0.3d |
517> | Small update existing handler/entity | 0.3-0.8d |
518> | NEW query on existing repo/model | 0.5-1d |
519> | NEW command/handler on existing aggregate (additive) | 1-2d |
520> | NEW aggregate/entity (repo, validation, events) | 2-4d |
521> | NEW cross-service contract OR schema migration | 2-4d each |
522> | Multi-aggregate invariant / heavy domain rule | 3-5d |
523>
524> **Rule:** Sum tiers across UI+backend+tests, apply productivity factor. Reuse short-circuits tiers — call out.
525>
526> **Test-Scope drivers (compute test_count EXPLICITLY — "+tests" hand-wave is #1 failure):**
527>
528> | Driver | Count |
529> | --------------------------------- | ------------------------------------------------------ |
530> | Happy-path journeys | 1 per story / AC main flow |
531> | State-machine transitions | reachable transitions × allowed actors |
532> | Multi-entity state combos | state(A) × state(B) — REACHABLE only, not Cartesian |
533> | Authorization matrix | (owner, non-owner, elevated, unauth) × each mutation |
534> | Validation rules | 1 per required field / boundary / format / cross-field |
535> | UI states (per new screen/dialog) | happy, loading, empty, error, partial — present only |
536> | Negative paths / invariants | 1 per violatable business rule |
537>
538> | Test tier (Trad, incl. setup+assert+flake) | Cost |
539> | ------------------------------------------ | -------- |
540> | 1-5 cases, fixtures reused | 0.3-0.5d |
541> | 6-12 cases, 1 new fixture | 0.5-1d |
542> | 13-25 cases, multi-entity setup | 1-2d |
543> | 26-50 cases OR new state-machine coverage | 2-3d |
544> | >50 cases OR full E2E journey | 3-5d |
545>
546> **Test multipliers:** new fixture/seed harness +0.5d · cross-service/bus assertion +0.3d each · UI E2E ×1.5 · each new role +1-2 cases
547>
548> **Blast Radius (mandatory pre-pass — affects code AND test):**
549>
550> 1. Files/components directly modified — count
551> 2. Of those, "complex" (>500 LOC, multi-handler, central, frequently-modified) — count
552> 3. Downstream consumers (callers, event subscribers, cross-service) — list
553> 4. Shared/common code touched (multi-app blast) — yes/no
554> 5. Regression scope — areas needing re-test
555>
556> **Rule:** Complex touch → add `risk_factors`. Each downstream consumer → +1-3 regression cases. Blast >5 areas OR >2 complex → re-evaluate SPLIT before estimating.
557>
558> **Risk Margin (drives max bound):**
559>
560> | likely_days | Base margin |
561> | ------------------- | ------------------------------- |
562> | <1d trivial | +10% |
563> | 1-2d small additive | +20% |
564> | 3-4d real feature | +35% |
565> | 5-7d large | +50% |
566> | 8-10d very large | +75% |
567> | >10d | +100% AND **flag SHOULD SPLIT** |
568>
569> **Risk-factor add-ons (additive — enumerate in `risk_factors`):**
570>
571> | Factor | +margin |
572> | --------------------------------------------------------------------- | ------- |
573> | `touches-complex-existing-feature` (>500 LOC, multi-handler, central) | +20% |
574> | `cross-service-contract` change | +25% |
575> | `schema-migration-on-populated-data` | +25% |
576> | `new-tech-or-unfamiliar-pattern` | +30% |
577> | `regression-fan-out` (≥3 downstream areas re-test) | +20% |
578> | `performance-or-latency-critical` | +20% |
579> | `concurrency-race-event-ordering` | +25% |
580> | `shared-common-code` (multi-consumer/multi-app) | +25% |
581> | `unclear-requirements-or-design` | +30% |
582>
583> **Collapse rule:** total margin >100% → STOP, split (padding past 2x is dishonesty). Margin <15% on `likely_days ≥5` → under-estimated, widen.
584>
585> **Work-Type Caps (hard ceilings on `likely_days`):**
586> | Work type | Max SP | Max likely |
587> | --- | --- | --- |
588> | Single field / config flag / style fix | 1 | 0.5d |
589> | Add property to existing model + bind to existing UI | 2 | 1d |
590> | **Additive endpoint + minor UI control** (button/menu/column), reuses fixtures | **3** | **2-3d** |
591> | Additive endpoint + **NEW UI surface** OR additive multi-layer + new domain rule + 2+ test files | 5 | 3-5d |
592> | NEW model/aggregate OR migration OR cross-module contract OR heavy test (>1.5d) OR NEW UI + non-trivial backend | 8 | 5-7d |
593> | NEW UI surface + (NEW aggregate OR migration OR cross-service contract) | 13 | SHOULD split |
594> | Cross-service contract + migration combined | 13 | SHOULD split |
595> | Beyond | 21 | MUST split |
596>
597> **SP→Days (validation only):** 1=0.5d/0.25d · 2=1d/0.35d · 3=2d/0.65d · 5=4d/1.0d · 8=6d/1.5d · 13=10d/2.0d (Trad/AI likely)
598> **AI speedup:** SP 1≈2x · 2-3≈3x · 5-8≈4x · 13+≈5x. AI cost = `(code_gen × 1.3) + (test_gen × 1.3)` (30% review overhead).
599>
600> **MANDATORY frontmatter:**
601>
602> ```yaml
603> story_points: <n>
604> complexity: low | medium | high | critical
605> man_days_traditional: '<min>-<max>d' # range when likely ≥3d; '<N>d' when <3d
606> man_days_ai: '<min>-<max>d'
607> risk_margin_pct: <n> # base + add-ons
608> risk_factors: [touches-complex-existing-feature, regression-fan-out] # closed-list from add-ons; [] if none
609> blast_radius:
610> touched_areas: <n>
611> complex_touched: <n>
612> downstream_consumers: [list or count]
613> shared_common_code: yes | no
614> estimate_scope_included: [code, integration-tests, frontend, i18n, docs]
615> estimate_scope_excluded: [unit-tests, e2e, perf, deployment, code-review-rounds]
616> estimate_reasoning: |
617> 5-7 lines covering:
618> (a) UI tier — row applied
619> (b) Backend tier — row applied
620> (c) Test scope — case breakdown by driver, file count, fixtures, tier row
621> (d) Cost driver — dominant tier + why
622> (e) Blast radius — touched, complex, regression scope
623> (f) Risk factors — list driving margin; why not larger/smaller
624> Example: "UI: compose Form/Table/Dialog → NEW screen (~1.5d). Backend: NEW command on existing aggregate,
625> reuses validation+repo (~1d). Tests: 4 transitions × 2 actors + 3 validation + 2 UI states = 13 cases,
626> 1 new fixture → tier 13-25 ~1.5d. Driver: UI composition + new states. Blast: 4 areas, 1 complex.
627> Risk: base 35% + touches-complex +20% = 55% → max 3.9d → range 2.5-4d."
628> ```
629>
630> **Sanity self-check:**
631>
632> - `likely_days ≥3d` and single-point? → reject, must be range
633> - Margin <15% on `likely_days ≥5d`? → under-estimated, widen
634> - Margin >100%? → STOP, split instead of buffer
635> - Complex existing feature touched, no regression budget in `(c)`? → reject
636> - Blast `>5` areas OR `>2` complex, no split discussion? → reject
637> - Purely additive on existing model AND existing UI? → cap SP 3 unless tests >1.5d
638> - NEW UI surface (page/complex form/dashboard)? → SP 5+ even if backend one endpoint
639> - Backend cross-service / migration / multi-aggregate? → SP 8+ regardless of UI
640> - `bottom_up_hours / 6` vs SP-Days disagreement >50%? → trust bottom-up, downgrade SP
641> - Without tests, SP drops ≥1 bucket? → tests dominate; state explicitly
642> - Reasoning called out UI vs backend vs blast vs risk factors? → if missing, add
643
644<!-- /SYNC:estimation-framework -->
645
646<!-- SYNC:plan-quality -->
647
648> **Plan Quality** — Every plan phase MUST ATTENTION include test specifications.
649>
650> 1. Add `## Test Specifications` section with TC-{FEATURE}-{NNN} IDs to every phase file
651> 2. Map every functional requirement to ≥1 TC (or explicit `TBD` with rationale)
652> 3. TC IDs follow `TC-{FEATURE}-{NNN}` format — reference by ID, never embed full content
653> 4. Before any new workflow step: call `TaskList` and re-read the phase file
654> 5. On context compaction: call `TaskList` FIRST — never create duplicate tasks
655> 6. Verify TC satisfaction per phase before marking complete (evidence must be `file:line`, not TBD)
656>
657> **Mode:** TDD-first → reference existing TCs with `Evidence: TBD`. Implement-first → use TBD → `/spec [mode=tests]` fills after.
658
659<!-- /SYNC:plan-quality -->
660
661<!-- SYNC:iterative-phase-quality -->
662
663> **Iterative Phase Quality** — Score complexity BEFORE planning.
664>
665> **Complexity signals:** >5 files +2, cross-service +3, new pattern +2, DB migration +2
666> **Score >=6 →** MUST ATTENTION decompose into phases. Each phase:
667>
668> - ≤5 files modified
669> - ≤3h effort
670> - Follows cycle: plan → implement → review → fix → verify
671> - Start Phase N+1 only after Phase N passes VERIFY — why: building on an unverified phase compounds errors downstream
672>
673> **Phase success = all TCs pass + code-reviewer agent approves + no CRITICAL findings.**
674
675<!-- /SYNC:iterative-phase-quality -->
676
677<!-- SYNC:fix-layer-accountability -->
678
679> **Fix-Layer Accountability** — NEVER fix at the crash site. Trace the full flow, fix at the owning layer.
680>
681> AI default behavior: see error at Place A → fix Place A. This is WRONG. The crash site is a SYMPTOM, not the cause.
682>
683> **MANDATORY before ANY fix:**
684>
685> 1. **Trace full data flow** — Map the complete path from data origin to crash site across ALL layers (storage → backend → API → frontend → UI). Identify where the bad state ENTERS, not where it CRASHES.
686> 2. **Identify the invariant owner** — Which layer's contract guarantees this value is valid? That layer is responsible. Fix at the LOWEST layer that owns the invariant — not the highest layer that consumes it.
687> 3. **One fix, maximum protection** — Ask: "If I fix here, does it protect ALL downstream consumers with ONE change?" If fix requires touching 3+ files with defensive checks, you are at the wrong layer — go lower.
688> 4. **Verify no bypass paths** — Confirm all data flows through the fix point. Check for: direct construction skipping factories, clone/spread without re-validation, raw data not wrapped in domain models, mutations outside the model layer.
689>
690> **BLOCKED until:** `- [ ]` Full data flow traced (origin → crash) `- [ ]` Invariant owner identified with `file:line` evidence `- [ ]` All access sites audited (grep count) `- [ ]` Fix layer justified (lowest layer that protects most consumers)
691>
692> **Anti-patterns (REJECT these):**
693>
694> - "Fix it where it crashes" — Crash site ≠ cause site. Trace upstream.
695> - "Add defensive checks at every consumer" — Scattered defense = wrong layer. One authoritative fix > many scattered guards.
696> - "Both fix is safer" — Pick ONE authoritative layer. Redundant checks across layers send mixed signals about who owns the invariant.
697
698<!-- /SYNC:fix-layer-accountability -->
699
700<!-- SYNC:ai-mistake-prevention -->
701
702> **AI Mistake Prevention** — Failure modes to avoid on every task:
703>
704> **Re-read files after context changes.** Context compaction, resume, or long-running work can make memory stale; verify current files before acting.
705> **Verify generated content against source evidence.** AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.
706> **Check downstream references before deleting or renaming.** Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.
707> **Trace the full impact chain after edits.** Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.
708> **Verify ALL affected outputs, not just the first.** One green check is not all green checks; validate every output surface the change can affect.
709> **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.
710> **Surface ambiguity before acting — don't pick silently.** Multiple valid interpretations require an explicit question or stated assumption with risk.
711> **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.
712> **Keep shared guidance role-relevant.** Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
713
714<!-- /SYNC:ai-mistake-prevention -->
715
716<!-- SYNC:domain-entity-change-gate -->
717
718> **Domain Entity Change Gate** — ONE protocol binding every skill or agent that PLANS, IMPLEMENTS, or REVIEWS a change touching a domain entity, value object, or aggregate, so a planner, an implementer, and a reviewer apply the SAME rules to the SAME change. `/domain-entities-review` is the canonical owner of the full A–P checklist; this gate is the shared trigger plus the decision set that must be answered. NEVER re-derive a weaker local copy — why: when planning and review disagree on entity rules, the plan ships a design that review then rejects, and the rework is paid twice.
719>
720> **Trigger — fires when ANY holds:** a new entity / value object / aggregate root is introduced · an existing one gains or loses a field, invariant, relationship, or state transition · an aggregate boundary, repository, or cross-aggregate reference changes · a domain event is added, renamed, or re-payloaded · a concurrency or reconstitution concern on a root changes. State `No domain-entity surface — gate N/A` when none holds.
721>
722> **Step 1 — Detect BEFORE deciding.** Both answers change which rules even apply:
723>
724> - **Paradigm** (per aggregate, from the code — NEVER assumed): OO-mutable · type-driven/immutable · event-sourced. Setter, mutability, and reconstitution rules are written for OO-mutable; applying them to the other two manufactures false findings and false plan tasks.
725> - **Subdomain fit:** core (rich model owed) · supporting (Active Record or light model) · generic (buy, do not model) · CRUD (Transaction Script — a rich entity here is ceremony). NEVER plan or flag a rich model where the subdomain has no invariant beyond required-field.
726>
727> **Step 2 — Answer all 6 decision points.** Each is a decision the change MUST make explicitly:
728>
729> | # | Decision point | Answered when |
730> | --- | ------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
731> | 1 | **Classification** — entity vs value object vs aggregate root | The swap test is applied ("would an identical copy be interchangeable?"); a VO is immutable with structural equality and has no repository |
732> | 2 | **Invariant ownership** — entity owns "can this state exist?", the boundary owns "is this input acceptable?" | Each rule is placed on one side and named; failure signalling (throw vs `Result`) matches the project convention consistently; a DB constraint is a backstop, NEVER the rule |
733> | 3 | **Aggregate boundary + concurrency** | Only true always-consistent invariants share an aggregate; cross-aggregate references are by ID; one aggregate mutates per transaction; the ROOT carries the concurrency token; set-based invariants (uniqueness across instances) name a real enforcing mechanism, never an in-memory check |
734> | 4 | **Construction vs reconstitution** | Creation and load are separate paths; the load path raises NO domain events and re-runs NO creation rules; required data sits in the constructor/factory |
735> | 5 | **Events** | Raised inside the aggregate; dispatched AFTER commit (outbox when crossing a process); internal domain events kept distinct from published integration contracts; handlers idempotent |
736> | 6 | **Test obligation** | Every invariant maps to a universally-quantified property TC PLUS a boundary counter-case — the spec NAMES it and a test GUARDS it (Dual-Feedback); a single happy-path example is NOT coverage |
737>
738> **Step 3 — Apply by context.** Same decisions, different obligation:
739>
740> | Calling context | Obligation |
741> | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
742> | **Planning** (`/plan`) | The plan MUST name the decision and the owning file for every triggered row. An unanswered row is a plan that is not executable — surface it, do NOT let implementation discover it. |
743> | **Plan review** (`/plan-review`) | An unanswered, hand-waved, or deferred-to-implementation row is a FINDING with `file:line` into the plan. Presence of the word "entity" is NEVER an answer. |
744> | **Implementation** (`/plan-execute`, `/fix`, and any implementing agent — e.g. `backend-developer`) | The decisions are INPUTS, not questions to reopen: implement each triggered row as the plan/spec decided it, at the owning file it named. A row that arrives UNANSWERED is a blocker — surface it and get it decided; NEVER settle it silently at the keyboard, and NEVER pick an aggregate boundary from a DB table or UI screen because the plan left it open. Paradigm and subdomain fit still gate which rules apply. |
745> | **Change review** (`/changes-review`) | Route to the owner — **Mode A (default):** read `/domain-entities-review`'s Phase 2 A–P checklist and apply it as review lenses. **Mode B (escalation):** delegate to `/domain-entities-review` when standalone AND the diff carries 3+ entity files. Findings enter the normal finding set with `file:line` + severity. |
746>
747> **Duplication guard — SKIP the gate entirely when ANY row holds.** Record the deferral line, then proceed:
748>
749> | Suppressing context | Deferral line |
750> | -------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
751> | The running skill IS `/domain-entities-review` | `Gate is this skill's own body — A–P checklist owns it.` |
752> | Invoked inside `$workflow-review-changes` (its step 5 runs `/domain-entities-review` as a dedicated conditional parallel member) | `Gate deferred to workflow step 5 /domain-entities-review.` |
753> | `/why-review` running in `--validate-findings` terminal mode | `Gate N/A — validate-findings is terminal, no sub-skill calls.` |
754>
755> — why: unguarded, this edge duplicates a review the parent workflow already runs and closes a `changes-review → domain-entities-review → why-review → changes-review` cycle.
756>
757> **BLOCKED until:** trigger evaluated (or `gate N/A` recorded) · paradigm + subdomain fit stated · all 6 triggered decision points answered or raised as findings · guard row checked before any delegation.
758
759<!-- /SYNC:domain-entity-change-gate -->
760
761<!-- SYNC:domain-entity-change-gate:reminder -->
762
763**MUST ATTENTION** when the change PLANS or REVIEWS a new/updated domain entity, value object, or aggregate, apply the **Domain Entity Change Gate** — `/domain-entities-review` owns the full A–P checklist; detect paradigm + subdomain fit FIRST, then answer all 6 decision points (classification · invariant ownership + failure signalling · aggregate boundary + concurrency · construction vs reconstitution · events · property-TC test obligation). Planning must NAME each decision; plan review treats an unanswered row as a FINDING; change review routes to the owner (Mode A read / Mode B delegate). SKIP under the 3-row duplication guard and record the deferral line. — why: one protocol shared by planner and reviewer is what stops a plan shipping an entity design that review then rejects.
764
765<!-- /SYNC:domain-entity-change-gate:reminder -->
766
767<!-- SYNC:estimation-framework:reminder -->
768
769- **MANDATORY MUST ATTENTION** estimation: bottom-up phase hours drive `man_days_traditional` (`Σh/6 × productivity_factor`); SP DERIVED. UI cost usually dominates — bump SP one bucket if NEW UI surface (page/complex form/dashboard). Frontmatter MUST include `story_points`, `complexity`, `man_days_traditional`, `man_days_ai`, `estimate_scope_included`, `estimate_scope_excluded`, `estimate_reasoning` (UI vs backend cost driver). Cap SP 3 for additive-on-existing-model+existing-UI unless test scope >1.5d. SP 13 SHOULD split, SP 21 MUST split.
770 <!-- /SYNC:estimation-framework:reminder -->
771
772<!-- SYNC:plan-quality:reminder -->
773
774**IMPORTANT MUST ATTENTION** include `## Test Specifications` with TC IDs per phase. Call `TaskList` before creating new tasks.
775
776<!-- /SYNC:plan-quality:reminder -->
777
778<!-- SYNC:plan-granularity:reminder -->
779
780**IMPORTANT MUST ATTENTION** verify all phases pass 5-point granularity check. Failing phases → sub-plan. "Can I start coding RIGHT NOW?"
781
782<!-- /SYNC:plan-granularity:reminder -->
783
784<!-- SYNC:understand-code-first:reminder -->
785
786**IMPORTANT MUST ATTENTION** search 3+ existing patterns and read code BEFORE any modification. Run graph trace when graph.db exists.
787
788<!-- /SYNC:understand-code-first:reminder -->
789
790<!-- SYNC:evidence-based-reasoning:reminder -->
791
792- **MANDATORY IMPORTANT MUST ATTENTION** cite `file:line` evidence for every claim. Confidence >80% to act, <60% = do NOT recommend.
793 <!-- /SYNC:evidence-based-reasoning:reminder -->
794
795<!-- SYNC:iterative-phase-quality:reminder -->
796
797**IMPORTANT MUST ATTENTION** score complexity first. Score >=6 → decompose. Each phase: plan → implement → review → fix → verify. No skipping.
798
799<!-- /SYNC:iterative-phase-quality:reminder -->
800
801<!-- SYNC:fix-layer-accountability:reminder -->
802
803**IMPORTANT MUST ATTENTION** trace full data flow and fix at the owning layer, not the crash site. Audit all access sites before adding `?.`.
804
805<!-- /SYNC:fix-layer-accountability:reminder -->
806
807<!-- SYNC:cross-service-check:reminder -->
808
809**IMPORTANT MUST ATTENTION** microservices/event-driven: scan producers, consumers, sagas, contracts in task scope. Per touchpoint: owner · message · consumers · risk (NONE/ADDITIVE/BREAKING). Missing consumer = silent regression.
810
811<!-- /SYNC:cross-service-check:reminder -->
812
813<!-- SYNC:critical-thinking-mindset:reminder -->
814
815**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.
816
817<!-- /SYNC:critical-thinking-mindset:reminder -->
818
819<!-- SYNC:sequential-thinking-protocol:reminder -->
820
821**MUST ATTENTION** apply sequential-thinking — multi-step Thought N/M, REVISION/BRANCH/HYPOTHESIS markers, confidence % closer; see `/sequential-thinking` skill.
822
823<!-- /SYNC:sequential-thinking-protocol:reminder -->
824
825<!-- SYNC:ai-mistake-prevention:reminder -->
826
827**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.
828
829<!-- /SYNC:ai-mistake-prevention:reminder -->
830
831<!-- SYNC:task-tracking-external-report:reminder -->
832
833- **MANDATORY** Bootstrap task tracking before target work; transition one task at a time.
834- **MANDATORY** Persist plan/review findings to `plans/reports/` incrementally and synthesize from disk.
835
836<!-- /SYNC:task-tracking-external-report:reminder -->
837
838<!-- SYNC:project-reference-docs-guide:reminder -->
839
840- **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: ...`.
841- **MANDATORY** Always include `lessons.md`; project config + conventions override generic framework defaults.
842- **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.
843
844<!-- /SYNC:project-reference-docs-guide:reminder -->
845
846<!-- SYNC:nested-task-creation:reminder -->
847
848- **MANDATORY** Parent workflow rows do not replace child phase tracking; expand phases and link the parent when nested.
849- **MANDATORY** Orchestrators pre-expand child skill phases before invocation; use `[N.M] $skill-name — phase` prefixes and one-`in_progress` discipline.
850
851<!-- /SYNC:nested-task-creation:reminder -->
852
853<!-- SYNC:goal-contract-satisfaction-loop:reminder -->
854
855- **MANDATORY** Resolve the active Goal Contract BEFORE work (active plan `goal.md` → `plans/goals/{YYMMDD-HHmm}-{slug}/goal.md` → create from current request) and read saved success criteria before editing.
856- **MANDATORY** Append iteration evidence after execution; emit a Goal Satisfaction matrix (PASS/FAIL/BLOCKED) before reporting PASS; loop on validated FAIL; escalate repeated no-progress or blockers. NEVER store secrets in goal files.
857
858<!-- /SYNC:goal-contract-satisfaction-loop:reminder -->
859
860<!-- SYNC:parallel-subagent-dispatch -->
861
862> **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.
863>
864> 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.
865> 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.
866> 3. **Declare before dispatch:** `Parallel plan: wave 1 = [...] · wave 2 = [...] · SEQ = [...] (reason)`.
867> 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.
868> 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).
869> 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.
870> 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.
871>
872> **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.
873>
874> **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.
875
876<!-- /SYNC:parallel-subagent-dispatch -->
877
878<!-- SYNC:parallel-subagent-dispatch:reminder -->
879
880- **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.
881- **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.
882
883<!-- /SYNC:parallel-subagent-dispatch:reminder -->
884
885<!-- SYNC:project-protocol-overlay -->
886
887> **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`.
888>
889> 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.
890
891<!-- /SYNC:project-protocol-overlay -->
892
893<!-- SYNC:project-protocol-overlay:reminder -->
894
895**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.
896
897<!-- /SYNC:project-protocol-overlay:reminder -->
898
899## Closing Reminders
900
901**IMPORTANT MUST ATTENTION Goal:** deliver a validated, implementation-ready plan — every phase startable immediately (exact file paths, zero open decisions, mapped TC IDs) — so coding runs without rework at minimum future change cost.
902
903**Protocols in force (concise digest of the SYNC/shared blocks this skill carries):**
904
905- **Plan Granularity:** every phase passes the 5-point check or sub-plans.
906- **Preservation Inventory:** bugfix plans tabulate invariants with `file:line` + verification.
907- **Nested Task Creation:** child skills expand visible phase tasks; link parent when nested.
908- **Project Reference Docs Guide:** ALWAYS read required project docs before target work.
909- **Task Tracking & External Report:** bootstrap tasks; persist findings to `plans/reports/`.
910- **Critical Thinking:** every claim needs traced proof; confidence >80% to act.
911- **Sequential Thinking:** multi-step Thought N/M with REVISION/BRANCH/HYPOTHESIS markers.
912- **Understand Code First:** read code + grep 3+ patterns before planning.
913- **Cross-Service Check:** scan producers, consumers, sagas, contracts for breaking risk.
914- **Estimation Framework:** bottom-up phase hours drive man-days; SP DERIVED.
915- **Plan Quality:** every phase carries `## Test Specifications` with TC IDs.
916- **Iterative Phase Quality:** score complexity first; decompose at score ≥6.
917- **Fix-Layer Accountability:** NEVER fix at the crash site; fix the invariant owner.
918- **AI Mistake Prevention:** verify generated content against evidence, trace downstream references, verify all affected outputs, re-read after context loss, surface ambiguity.
919- **Parallel Sub-Agent Dispatch:** Tag tasks PAR/SEQ, group PAR into disjoint-write-set waves, spawn each wave in ONE message, barrier before advancing.
920
921**IMPORTANT MUST ATTENTION** PLANNING ONLY — NEVER implement or execute code; produce `plan.md` + per-phase files + `goal.md` Goal Contract, then hand off — why: this skill's contract is a plan, not a change.
922**IMPORTANT MUST ATTENTION** default mode HARD — opt out to fast mode ONLY when ALL trivial-task conditions hold — why: skipping rigor on a non-trivial task costs more rework than rigor saves.
923**MANDATORY IMPORTANT MUST ATTENTION** break work into small todo tasks via `TaskCreate` BEFORE starting; add a final review todo; on context loss call `TaskList` first — never duplicate tasks.
924**MANDATORY IMPORTANT MUST ATTENTION** bootstrap the Goal Contract (`goal.md` from `goal-contract-template.md`) BEFORE investigation; every phase success criterion maps to a saved goal criterion. Redact secrets.
925**MANDATORY IMPORTANT MUST ATTENTION** validate decisions with user via `AskUserQuestion` — NEVER auto-decide because a task seems "obvious"; the user decides the next step.
926**MANDATORY IMPORTANT MUST ATTENTION** every phase passes the 5-point granularity check ("Can I start coding RIGHT NOW?") — failing phases → sub-plan (max depth 3).
927**MANDATORY IMPORTANT MUST ATTENTION** detect new tech/lib not in project → `TaskCreate` per lib → WebSearch top 3 → compare → recommend with confidence % → `AskUserQuestion` — why: an unvetted dependency is an irreversible decision exposed too early.
928**MANDATORY IMPORTANT MUST ATTENTION** estimation is bottom-up — phase hours drive `man_days_traditional` (`Σh/6 × productivity_factor`); SP DERIVED, never the driver; UI cost usually dominates; emit full `estimate_reasoning` frontmatter.
929**MANDATORY IMPORTANT MUST ATTENTION** every phase carries `## Test Specifications` with `TC-{FEATURE}-{NNN}` IDs; map every functional requirement to ≥1 TC (or explicit `Evidence: TBD` for TDD-first).
930**MANDATORY IMPORTANT MUST ATTENTION** for `.claude` skills/hooks/workflows/sync work, plans MUST include generated-mirror sync action or explicit no-sync evidence — why: a silently stale mirror diverges from source.
931**MANDATORY IMPORTANT MUST ATTENTION** NEVER skip `/plan-review` after plan creation — run it standalone or as the workflow step; standalone `/plan` also appends `/changes-review` as a final task.
932**IMPORTANT MUST ATTENTION** search 3+ existing patterns and read target code BEFORE planning; cite `file:line`; run graph trace when `.code-graph/graph.db` exists — why: local conventions override generic framework defaults.
933**MANDATORY IMPORTANT MUST ATTENTION** run the full main pipeline in order — pre-check plan → bootstrap `goal.md` → ONE research wave (`researcher` + `scout` in one message) → barrier → codebase + project-reference analysis (scout if docs absent) → `planner` writes `plan.md` + `phase-XX` → parallelism pass (PAR/SEQ + write sets + `## Execution Waves`) → granularity self-check → mandatory final tasks; NEVER skip a step because it seems obvious — why: the skipped step (Goal Contract, granularity, test specs) is the one AI silently drops.
934**MANDATORY IMPORTANT MUST ATTENTION** dispatch the research threads as ONE wave in ONE message (declare `Parallel plan:` first, one report path per agent) and synthesize only after EVERY member returns — why: dripping researchers one per turn serializes the cheapest-to-parallelize half of planning.
935**MANDATORY IMPORTANT MUST ATTENTION** the emitted plan MUST carry parallelism metadata — every phase tagged `PAR`/`SEQ`, its write set declared, every `SEQ` naming the exact artifact it waits on, and `## Execution Waves` in `plan.md` — why: `/plan-execute` fans out only on what the plan declares, so an untagged plan silently forces sequential execution.
936**MANDATORY IMPORTANT MUST ATTENTION** queue the final-task block on EVERY plan — Test Specs per phase → `/plan-validate` → `/plan-review` (convergence loop, 3-round ceiling — a clean pass ends it at any round) → `/why-review` (standalone only) → re-estimate vs finalized phases (flag `SHOULD-RESCOPE` when delta >50%).
937**IMPORTANT MUST ATTENTION** `--mode={ci|cro}` only ADDS a domain reference load (`references/mode-ci.md` / `mode-cro.md`) + intake on top of the SAME engine, gate, and `planner` agent — default (no flag) runs the standard flow byte-for-byte; NEVER let a mode replace the engine or skip `/plan-review`.
938
939**Anti-Rationalization:**
940
941| Evasion | Rebuttal |
942| --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
943| "Task too simple to plan" | Default mode HARD. Opt out ONLY when ALL trivial conditions hold. |
944| "I already know the codebase" | Show `file:line` from 3+ patterns + graph trace. No proof = not read. |
945| "Phase is clear enough" | Run the 5-point granularity check: "Can I start coding RIGHT NOW?" — else sub-plan. |
946| "Plan looks good, skip review" | NEVER skip `/plan-review` — fresh eyes catch author blind spots. |
947| "Only existing libs, skip the gate" | Prove it — grep manifests. Any new tech/lib → WebSearch + `AskUserQuestion` before approval. |
948| "I'll just estimate SP directly" | SP is DERIVED from bottom-up phase hours, never the driver. Σh/6 × productivity first. |
949| "It's a `.claude` change, no sync" | State the mirror action or explicit no-sync evidence — stale mirrors fail the oracle. |
950| "`--mode=ci`, so skip the normal flow" | Mode only ADDS a reference payload — same engine, same `/plan-review`, same `planner` agent. |
951| "Plan's done, skip the final tasks" | Test Specs → `/plan-validate` → `/plan-review` → `/why-review` → re-estimate are MANDATORY, not optional. |
952| "Phases feel sequential, skip the tags" | "Feels sequential" is not a dependency. Tag `PAR`/`SEQ`, declare write sets, and name the artifact each `SEQ` waits on. |
953| "The executor can work the order out" | It can't — `/plan-execute` fans out only on declared write sets. No tags = sequential execution you caused. |
954
955**[TASK-PLANNING]** Before acting, analyze task scope and systematically break into small todo tasks and sub-tasks via TaskCreate.
956
957**IMPORTANT MUST ATTENTION** PLANNING ONLY — never implement; cite `file:line` evidence (confidence >80% to act); NEVER skip `/plan-review` and the New Tech/Lib + Goal-Contract gates.
958
959---
960
961> **Closing reminder — Easy to Change is the success metric.** Every finding,
962> test, refactor, and abstraction must answer one question: _does this make
963> the next change cheaper or more expensive?_ If it doesn't reduce future
964> change cost, reject it. Coupling, hidden state, duplicated knowledge, and
965> unclear intent are the real enemies — call them out by name.