1---
2name: plan-execute
3description: '[Implementation] Use when you need to start coding & testing an existing plan. Flags: --approval=off (auto/trust mode, no approval gate), --tests=off (skip the test step), --parallel={auto|on|off} (default off — sequential; --parallel/=on opts in to parallel sub-agent waves; =auto fans out only when the plan declares PAR/SEQ tags and write sets).'
4metadata:
5 source: https://skillmd.com/skills/duc01226/plan-execute
6---
7
8> Codex compatibility note:
9>
10> - Invoke repository skills with `$skill-name` in Codex; this mirrored copy rewrites legacy Claude `/skill-name` references.
11> - Task tracker mandate: BEFORE executing any workflow or skill step, create/update task tracking for all steps and keep it synchronized as progress changes.
12> - User-question prompts mean to ask the user directly in Codex.
13> - Ignore Claude-specific mode-switch instructions when they appear.
14> - Strict execution contract: when a user explicitly invokes a skill, execute that skill protocol as written.
15> - Subagent authorization: when a skill is user-invoked or AI-detected and its protocol requires subagents, that skill activation authorizes use of the required `spawn_agent` subagent(s) for that task.
16> - Do not skip, reorder, or merge protocol steps unless the user explicitly approves the deviation first.
17> - For workflow skills, execute each listed child-skill step explicitly and report step-by-step evidence.
18> - If a required step/tool cannot run in this environment, stop and ask the user before adapting.
19
20<!-- CODEX:PROJECT-REFERENCE-LOADING:START -->
21
22## Codex Project-Reference Loading (No Hooks)
23
24Codex uses static project-reference loading instead of runtime-injected project docs.
25When coding, planning, debugging, testing, or reviewing, open project docs explicitly using this routing.
26
27**Always read:**
28
29- `docs/project-config.json` (project-specific paths, commands, modules, and workflow/test settings)
30- `docs/project-reference/docs-index-reference.md` (routes to the full `docs/project-reference/*` catalog)
31- `docs/project-reference/lessons.md` (always-on guardrails and anti-patterns)
32
33**Missing/stale context route:** If `docs/project-config.json`, the docs index, `lessons.md`, `CLAUDE.md`, `AGENTS.md`, or any task-required reference doc is missing or stale, auto-run `$project-init` or the narrow setup route (`$project-config`, `$docs-init`, `$scan-all`, `$scan --target=<key>`, `$claude-md-init`) before ordinary project-specific work. If Codex mirrors or `AGENTS.md` are missing/stale, ask the user to run `$sync-codex`; do not auto-run it.
34
35**Situation-based docs:**
36
37- Project structure/architecture/tech-stack/deployment/setup (any layer — backend, frontend, or infra): `project-structure-reference.md`
38- Backend/CQRS/API/domain/entity changes: `backend-patterns-reference.md`, `domain-entities-reference.md`
39- Frontend/UI/styling/design-system: `frontend-patterns-reference.md`, `scss-styling-guide.md`, `design-system/README.md`
40- Spec authoring, `docs/specs/` pathing, or TC format: `feature-spec-reference.md`, `spec-system-reference.md`, `spec-principles.md`
41- Behavior/public-contract changes or spec-test-code sync: `workflow-spec-test-code-cycle-reference.md` plus the spec docs above
42- Derived spec indexes/ERDs/reimplementation guides: `spec-system-reference.md` and source Feature Specs under `docs/specs/`
43- Integration test implementation/review: `integration-test-reference.md`
44- E2E test implementation/review: `e2e-test-reference.md`
45- Code review/audit work: `code-review-rules.md` plus domain docs above based on changed files
46
47Do not read all docs blindly. Start from `docs-index-reference.md`, then open only relevant files for the task.
48
49<!-- CODEX:PROJECT-REFERENCE-LOADING:END -->
50
51<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:START -->
52
53> **[BLOCKING]** Execute skill steps in declared order. NEVER skip, reorder, or merge steps without explicit user approval.
54> **[BLOCKING]** Before each step or sub-skill call, update task tracking: set `in_progress` when step starts, set `completed` when step ends.
55> **[BLOCKING]** Every completed/skipped step MUST include brief evidence or explicit skip reason.
56> **[BLOCKING]** If Task tools are unavailable, create and maintain an equivalent step-by-step plan tracker with the same status transitions.
57
58<!-- PROMPT-ENHANCE:STEP-TASK-ANCHOR:END -->
59
60## Quick Summary
61
62**Goal:** Land the selected plan phase as working, fully-tested, reviewed, user-approved code — executing it phase-by-phase through testing, code review, and approval gates — committed only after every quality gate (100% tests, 0 critical issues, explicit approval) passes — NEVER bypass a gate to declare done.
63
64**Summary:**
65
66- **Purpose:** consume an EXISTING plan, one phase per run — Step 0 detects `plans/*.md` + selects the next incomplete phase (prefer IN_PROGRESS, else earliest Planned). Use `$feature-implement` instead when no plan exists yet — it creates plans, this consumes them.
67- **Full step spine (run in declared order, emit `✓ Step N:` each):** Step 1 Analysis & Task Extraction (read plan fully, Goal-Contract read, Trace Gate, seed task tracking 0–6) → Step 2 Implementation (code step-by-step, type-check + compile; UI → `ui-ux-designer`) → Step 3 Testing (`tester`, loop `debugger` until 100%) → Step 4 Code Review (`code-reviewer` until 0 critical) → Step 5 User Approval (BLOCKING — stop and wait) → Step 6 Finalize (`project-manager` + `docs-manager` status/docs, `git-manager` auto-commit).
68- **Three BLOCKING gates cannot be faked-green:** Step 3 tests 100% pass, Step 4 zero critical issues, Step 5 explicit user approval before Finalize/commit. — why: a partial-green gate ships the regression the test exists to catch.
69- **Two STOP-before-coding gates:** Pre-Implementation Granularity Gate (refuse planning verbs / unnamed files / unresolved decisions → sub-plan with `$plan`) + bugfix Trace Gate (require the End→Start debugger trace for any bug/regression/behavior-changing plan). Also the Spec-Loop Gate (property TC + mutation-killed test + Dual-Feedback) closes any behavior change.
70- **Step 2 is SEQUENTIAL by default; wave fan-out is OPT-IN.** `--parallel` / `--parallel=on` dispatches disjoint-write-set phases as one wave of `fullstack-developer` subagents in ONE message, barrier, then recomputes the next wave against the updated repo. `--parallel=auto` fans out ONLY when every in-scope phase carries the `## Parallel Execution` block (`PAR`/`SEQ` tag + declared write set) written by `$plan` — no block, no fan-out.
71- **Mode flags** add/remove ONE step, never relax a running gate: `--approval=off` (auto/trust, skip Step 5, optional `$ALL_PHASES` loop over every incomplete phase), `--tests=off` (skip Step 3), `--parallel={auto|on|off}` (`off` default = sequential; bare `--parallel`/`on` opts in to wave dispatch; `auto` fans out only on plan-declared `PAR`/`SEQ` metadata). No flags = full 7-step spine, run sequentially.
72- **Standalone** (no parent `[Workflow]` row via the current task list) → wrap the spine in plan → plan-review → proceed → `$changes-review` → `$why-review`, the two reviews as the LAST todos.
73
74> **Slash-command routing:** `/code`, `/code-auto`, `/code-no-test`, `/code-parallel` no longer resolve — use `$plan-execute` with the matching flag: `/code-auto` → `--approval=off`, `/code-no-test` → `--tests=off`, `/code-parallel` → `--parallel`.
75
76**Workflow:**
77
781. **Plan Detection** — Find latest plan or use provided path, select next incomplete phase
792. **Analysis & Tasks** — Extract tasks from phase file into task tracking
803. **Implementation** — Implement step-by-step, run type checks
814. **Testing** — Call tester subagent; must reach 100% pass before proceeding
825. **Code Review** — Call code-reviewer subagent; must reach 0 critical issues
836. **User Approval** — BLOCKING gate: wait for explicit user approval
847. **Finalize** — Update status, docs, and auto-commit
85
86**Key Rules:**
87
88- Tests must be 100% passing (Step 3 gate)
89- Critical issues must be 0 (Step 4 gate)
90- User must explicitly approve before finalize (Step 5 gate)
91- One plan phase per command run — a multi-phase run requires `--approval=off` with `$ALL_PHASES=Yes`
92- Phases run sequentially unless fan-out is explicitly opted in; even then, two phases writing the same file NEVER share a wave
93- **Mode flags** (see [Mode Flags](#mode-flags)): `--approval=off` (auto/trust, no approval gate + optional all-phases loop), `--tests=off` (skip the test step), `--parallel={auto|on|off}` (default `off` = sequential; `on` = opt in to wave dispatch; `auto` = fan out only when the plan declares `PAR`/`SEQ` tags + write sets). No flags = full 7-step spine below, run sequentially.
94
95**MUST ATTENTION READ** `CLAUDE.md` then **THINK HARDER** to start working on the following plan:
96
97**Be skeptical. Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence percentages (Idea should be more than 80%).**
98
99<plan>$ARGUMENTS</plan>
100
101---
102
103> **plan-execute vs feature-implement:** `plan-execute` **executes an EXISTING plan** phase-by-phase (Step 0 detects `plans/*.md`) and owns the back of the pipeline — phase gates, auto-commit, and the `--parallel`/`--approval`/`--tests` flags. Use `$feature-implement` instead when you have only a feature description and need research + planning done first. feature-implement creates plans; plan-execute consumes them.
104
105## Standalone Mode Pipeline (skip entirely if invoked inside a workflow)
106
107> **MANDATORY — standalone `$plan-execute` only.** When this skill is invoked OUTSIDE a workflow, wrap the core spine (Steps 0-6) in this quality loop. Detect an active workflow via the current task list FIRST: if a parent `[Workflow]` row exists, SKIP this section — the surrounding workflow already sequences plan/review/why-review (e.g. `workflow-refactor`).
108>
109> Create these as task tracking tasks up front, in order, then execute them:
110>
111> 1. **`$plan`** — if Step 0 finds no plan for the request, author one first. If a plan already exists, record that and skip to step 2.
112> 2. **`$plan-review`** — recursively review/validate the plan; fix validated findings before proceeding.
113> 3. **Proceed** — run the core spine (Steps 0-6) against the approved plan.
114> 4. **`$changes-review`** — review the diff before commit (the post-gate; see _Standalone Review Gate_ below).
115> 5. **`$why-review`** — review rationale and change quality of the implementation.
116>
117> This is the single pre+post quality loop for standalone runs.
118
119## Mode Flags
120
121`$plan-execute` runs the full step spine below by default. Optional flags adapt the spine for the cases formerly served by dedicated skills — each flag only adds or removes a single step against the **host step numbering** (Step 3 Testing, Step 4 Code Review, Step 5 User Approval, Step 6 Finalize); the shared spine and every quality bar are otherwise unchanged.
122
123| Flag | Default | Effect |
124| ---------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
125| `--approval={on\|off}` | `on` | `off` = **trust/auto mode**: skip the Step 5 user-approval blocking gate and finalize without waiting. Pair with `$ALL_PHASES` to run every incomplete phase in one pass. |
126| `--tests={on\|off}` | `on` | `off` = skip the Step 3 Testing gate entirely (Implementation → Code Review → Approval → Finalize only). Use ONLY when the plan explicitly defers tests. |
127| `--parallel={auto\|on\|off}` | `off` | `off` = **default**: implement every phase sequentially in the main agent. `on` (also bare `--parallel`) = **explicit opt-in**: Step 2 groups disjoint-write-set phases into waves of `fullstack-developer` subagents with strict file-ownership boundaries; the user has accepted the risk, and YOU must still name every phase's write set — including its cascade/generated writes — before grouping. `auto` = **metadata-gated**: fan out only when every in-scope phase carries a `## Parallel Execution` block (`PAR`/`SEQ` tag + declared write set) written by `$plan`; absent that block, fall back to sequential — NEVER derive write sets optimistically. |
128
129**`$ALL_PHASES` (only meaningful with `--approval=off`):** `Yes` (default in auto mode) processes ALL incomplete phases in one run, auto-looping to the next phase after each Finalize; `No` implements one phase then asks before continuing. With `--approval=on` (default), always one phase per run — so cross-phase wave dispatch is only ever reachable in a multi-phase run (`--approval=off` + `$ALL_PHASES=Yes`) or on a phase whose sub-phases are independently implementable.
130
131### Flag-modified step behavior
132
133- **`--parallel=auto` → Step 2 (Implementation):** metadata-gated fan-out — dispatch waves ONLY when every in-scope phase carries a `## Parallel Execution` block written by `$plan`; the moment one phase lacks it, the whole run reverts to sequential. `auto` NEVER derives a write set from the plan's prose — see [Step 2 Wave Dispatch](#step-2-wave-dispatch-opt-in---parallelon).
134- **`--parallel` / `--parallel=on` → Step 2:** the explicit opt-in — dispatch waves even when the plan declares no `PAR`/`SEQ` tags or `## Execution Waves` line. You MUST first derive each phase's write set yourself from its `Related Code Files` / Implementation Steps **and** from the generated/mirrored artifacts those edits cascade into; a phase whose write set you cannot name stays out of the wave. Colliding phases still go in different waves — opting in never authorizes co-scheduling two writers of one file.
135- **`--parallel=off` (DEFAULT) → Step 2:** no wave dispatch; implement every phase sequentially in the main agent. This is the normal path and needs no justification — no flag is required to stay sequential. All gates and quality bars unchanged.
136- **`--tests=off` → Step 3 (Testing):** Skip entirely. Proceed Implementation → Code Review. The Source/test drift check still applies to any tests that already exist. Keep existing tests real and genuinely passing — NEVER comment out tests, weaken assertions, or use fake data to make them pass — why: faked green hides the regression the test exists to catch.
137- **`--approval=off` → Step 5 (User Approval):** Skip the blocking gate. Finalize (status, docs, auto-commit) runs once Steps 1-4 pass. When `$ALL_PHASES=Yes`, loop back to Step 0 for the next incomplete phase; on the last phase, generate the summary report and ask about `/preview`.
138
139> **Behavior preserved:** the debugger-trace gate, granularity gate, testing/review quality bars, and all SYNC blocks apply in EVERY mode. Flags change _which gates run_, never _how rigorously a running gate is enforced_.
140
141---
142
143## Pre-Implementation Granularity Gate (MANDATORY)
144
145<HARD-GATE>
146
147If ANY check fails → STOP. Ask user: "Phase needs more detail before implementation. Refine with $plan? [Y/n]"
148Implement only phases with named files, concrete actions, and resolved decisions — DO NOT implement a phase containing planning verbs, unnamed files, or unresolved decisions.
149</HARD-GATE>
150
151---
152
153## Step 0: Plan Detection & Phase Selection
154
155**If `$ARGUMENTS` is empty:**
156
1571. Find latest `plan.md` in `./plans`
1582. Parse plan for phases and status, auto-select next incomplete (prefer IN_PROGRESS or earliest Planned)
159
160**If `$ARGUMENTS` provided:** Use that plan and detect which phase to work on.
161
162**Output:** `✓ Step 0: [Plan Name] - [Phase Name]`
163
164---
165
166## Workflow Sequence
167
168**Rules:** Follow steps 1-6 in order. Each step requires output marker `✓ Step N:`. Mark each complete in task tracking before proceeding. Do not skip steps.
169
170---
171
172## Step 1: Analysis & Task Extraction
173
174Read plan file completely. Map dependencies. List ambiguities. Identify required skills and activate from catalog. If the plan references analysis files in `.ai/workspace/analysis/`, re-read them before implementation.
175
176**Goal Contract read (BEFORE any code change):** resolve the active Goal Contract per `SYNC:goal-contract-satisfaction-loop` — active plan `goal.md` → `plans/goals/{YYMMDD-HHmm}-{slug}/goal.md` → create from the current request via `.claude/templates/goal-contract-template.md` — and read its saved success criteria. After implementation/verification (Step 3+), append an Iteration Log entry with evidence and remaining gaps.
177
178**Pre-Implementation Trace Gate:** If the plan is for a bugfix, failed verification, stale/incorrect final output, regression, or behavior-changing fix, MUST ATTENTION verify the plan or referenced analysis includes `Debugger Trace: End -> Start`, all feeder paths, hypothesis matrix, owning fix layer, and forward convergence proof. If missing, STOP and report the missing trace links instead of implementing.
179
180**task tracking Initialization:**
181
182- Initialize task tracking with `Step 0: [Plan Name] - [Phase Name]` and all steps (1-6)
183- Read phase file, look for tasks/steps/phases/sections/numbered/bulleted lists
184- Convert to task tracking tasks with UNIQUE names:
185 - Phase Implementation tasks → Step 2.X (Step 2.1, Step 2.2, etc.)
186 - Phase Testing tasks → Step 3.X
187 - Phase Code Review tasks → Step 4.X
188
189**Output:** `✓ Step 1: Found [N] tasks across [M] phases - Ambiguities: [list or "none"]`
190
191---
192
193## Step 2: Implementation
194
195Implement selected plan phase step-by-step following extracted tasks. Mark tasks complete as done. UI work → call `ui-ux-designer` subagent. Run type check + compile to verify.
196
197### Step 2 Wave Dispatch (opt-in — `--parallel=on`)
198
199Fan-out is OFF unless opted in. Run this section only when BOTH hold: (a) this run covers more than one phase (`$ALL_PHASES=Yes`, or a phase whose sub-phases are independently implementable), AND (b) the user passed `--parallel` / `--parallel=on`, or passed `--parallel=auto` and every in-scope phase carries a `## Parallel Execution` block. Either condition unmet → implement sequentially. Sequential is the safe default and needs no justification.
200
2011. **Take the write set of every in-scope phase from the plan's declaration** — its `## Parallel Execution` block (Mode · Write set · Wave · SEQ dependency) written by `$plan`. Under `--parallel=auto` that block is MANDATORY: a plan lacking it falls back to sequential, and you NEVER reconstruct a write set from `Related Code Files` / Implementation Steps — why: a derived write set structurally cannot see cascade or generated writes, so two phases editing different source files can both write the same generated/mirrored/catalog/lockfile artifact that neither phase would ever name, and the wave corrupts it. Under `--parallel=on` the user has accepted that risk: derive the set yourself, then explicitly enumerate the generated, mirrored, and regenerated artifacts each phase's edits trigger and add them to that phase's write set before grouping. A phase whose write set still cannot be named is INELIGIBLE for a wave — implement it inline or send it back to `$plan`.
2022. **Refuse to co-schedule two writers of the same file** — ANY path shared between two phases puts them in different waves. No "they only touch different functions" exception: the unit of ownership is the file. A phase tagged `SEQ`, or whose named dependency has not yet returned, never joins the current wave.
2033. **Declare, then spawn in ONE message** — emit `Parallel plan: wave 1 = [...] · wave 2 = [...] · SEQ = [...] (reason)`, then spawn EVERY member of the wave in a single response as `fullstack-developer` subagents (UI-only phase → `ui-ux-designer`; route other specialties per `.claude/skills/shared/sub-agent-selection-guide.md`). Brief each with: its phase-file path, environment info, its EXCLUSIVE file-ownership boundary (cross-boundary edits forbidden — report the conflict instead), and its return contract.
2044. **Barrier, then re-evaluate against the updated repo** — advance only after EVERY member returns. The barrier is YOUR accounting, not a signal you wait for: hold the wave's member list in the task tracker and mark each member by name as `returned` / `failed` / `timed-out` / `partial`. An unaccounted member is never dropped and never assumed successful. When every member is accounted for AND all returned cleanly, verify no file was written outside its owner's boundary, run type-check + compile on the merged result, THEN recompute the next wave against the repo as it now stands — never against the wave plan you computed before dispatch, because a returned phase can change what a later phase writes.
2055. **Wave failure branch — the barrier does NOT advance on an incomplete wave.** If any member fails, times out, or returns partial work:
206 - **Classify partial as FAILED.** A member reporting "mostly done", or whose evidence does not match its declared write set, counts as failed — not returned.
207 - **Never let the survivors stand in for the missing member,** and never proceed to Step 3 on a wave that is not fully accounted for.
208 - **Quarantine the failed member's work** — inspect exactly what it wrote, and revert its partial edits if they leave the tree uncompilable. Record the files it touched.
209 - **Fall back to sequential for that phase** — merge the clean returns, restore compile-green, then re-implement the failed phase INLINE in the main agent (never re-dispatch it into another wave). A phase that also fails sequentially → STOP and report; do not carry it into the next wave.
210 - **A cross-boundary write fails the whole wave** — revert the out-of-boundary edits, re-run that phase sequentially, and drop fan-out for the remainder of the run: the write-set model that authorized the wave is proven wrong.
211 - **Report the failure in the Step 2 output** — a wave that fell back is never reported as a clean fan-out.
2126. **Do not dispatch when the gain is not there** — a single-phase run, a one-file phase, or a wave of one implements inline (dispatch overhead > gain).
213
214**Gates are SEQ boundaries and are never parallelized away.** Step 3 Testing, Step 4 Code Review, and the Step 5 user-approval gate run AFTER the barrier on the merged result — never concurrently with the phases they gate, and a subagent's own self-check NEVER substitutes for the host gate.
215
216**Output:** `✓ Step 2: Implemented [N] files - [X/Y] tasks complete, compilation passed` — when waves ran, append `- waves: [w1 members] → [w2 members]`, and name any member that failed/timed-out plus the phase that fell back to sequential
217
218---
219
220## Step 3: Testing
221
222Call `tester` subagent. ANY tests fail → STOP, call `debugger` subagent, fix, re-run. Repeat until 100% pass.
223
224**Testing standards:** Unit tests may use mocks. Integration tests use test environment. Forbidden: commenting out tests, changing assertions to pass, TODO/FIXME to defer fixes.
225
226**Output:** `✓ Step 3: Tests [X/X passed] - All requirements met`
227
228**Validation:** If X ≠ total, Step 3 INCOMPLETE - do not proceed.
229
230---
231
232## Step 4: Code Review
233
234Call `code-reviewer` subagent. Critical issues found → STOP, fix, re-run `tester`, re-run `code-reviewer`. Repeat until no critical issues.
235
236**Output:** `✓ Step 4: Code reviewed - [0] critical issues`
237
238**Validation:** If critical issues > 0, Step 4 INCOMPLETE - do not proceed.
239
240---
241
242## Spec-Loop Gate (applies in EVERY mode, standalone included)
243
244> **A behavior change is not "done" until the spec-loop closes** (canonical: `SYNC:spec-loop-discipline` in `.claude/skills/shared/sync-inline-versions.md`). After implementing a behavior-bearing phase, the four rules gate completion: (1) every [HARD] §4 rule / §5 invariant the phase touched has a **universally-quantified property TC** ("for ALL inputs in {domain}, {invariant} holds") + boundary counter-case, not just an example; (2) the changed core-logic line is **mutation-killed** — a surviving mutant on a changed line is a missing invariant, write the killing test (MUTATION-SCORE bar, not line-coverage %); (3) the finding fed the **Dual-Feedback Ledger** into BOTH the spec AND the tests (a blank Spec-feedback OR Test-feedback cell = INCOMPLETE), never a code-only change. A phase with a behavior change but no property TC, no mutation-killed test, and no Dual-Feedback entry is **INCOMPLETE** — re-verify the whole package (spec + tests + code, not just the diff) before reporting success.
245
246---
247
248## Step 5: User Approval ⏸ BLOCKING GATE
249
250Present summary (3-5 bullets): what implemented (name the waves when Step 2 fanned out), tests passed, code review outcome.
251
252**This gate is a SEQ boundary** — it is never merged into a wave, never delegated to a subagent, and never satisfied by "the parallel phases all reported success". Only `--approval=off` removes it.
253
254**Ask user explicitly:** "Phase implementation complete. All tests pass, code reviewed. Approve changes?"
255
256**Stop and wait** - do not proceed until user responds.
257
258**Output:** `✓ Step 5: User approved - Ready to complete`
259
260---
261
262## Step 6: Finalize
263
264**Prerequisites:** User approved in Step 5.
265
2661. **STATUS UPDATE (one wave — PAR):** spawn `project-manager` (plan status file) and `docs-manager` (documentation) together in ONE message — disjoint write sets — and barrier on both returns before continuing.
267
2682. **ONBOARDING CHECK:** Detect onboarding requirements + generate summary.
269
2703. **AUTO-COMMIT (SEQ — after the barrier):** Call `git-manager` subagent; it stages the merged result of BOTH updates, so it never shares the wave above. Run only if Steps 1-2 successful + User approved + Tests passed.
271
272**Output:** `✓ Step 6: Finalize - Status updated - Git committed`
273
274---
275
276## First Principle — Easy to Change
277
278> **The success metric of every coding decision is _future change cost_.**
279> DRY, SRP, abstraction, design patterns, naming, layering, tests — every
280> technique exists to serve one goal: **making the next change cheaper**.
281
282When evaluating code, a refactor, a test, or an abstraction, ask:
283**does this make the next change cheaper or more expensive?**
284
285- Reject "best practices" that raise change cost (premature abstraction,
286 speculative generality, leaky indirection, ceremony without payoff).
287- Name the real enemies in findings: **coupling, hidden state, duplicated
288 knowledge, unclear intent, irreversible decisions exposed too early**.
289- A simpler design that is easy to change beats a sophisticated design that
290 isn't.
291
292Apply this lens **before** invoking any specific rule, pattern, or checklist
293below — if a downstream rule would raise change cost, this principle wins.
294
295---
296
297## Critical Enforcement Rules
298
299**Step output format:** `✓ Step [N]: [Brief status] - [Key metrics]`
300
301**task tracking tracking required:** Initialize at Step 0, mark each step complete before next.
302
303**Mandatory subagent calls:** Step 3: `tester` | Step 4: `code-reviewer` | Step 6: `project-manager` AND `docs-manager` AND `git-manager`
304
305**Blocking gates:**
306
307- Step 3: Tests must be 100% passing
308- Step 4: Critical issues must be 0
309- Step 5: User must explicitly approve
310
311Execute every step in declared order; proceed only when validation passes and the user has approved; run one plan phase per command. Do not skip steps, proceed on failed validation, or assume approval without a user response.
312
313---
314
315## Workflow Recommendation
316
317> **MANDATORY IMPORTANT MUST ATTENTION — NO EXCEPTIONS:** If you are NOT already in a workflow, you MUST ATTENTION use ask the user directly to ask the user. Do NOT judge task complexity or decide this is "simple enough to skip" — the user decides whether to use a workflow, not you:
318>
319> 1. **Activate `workflow-refactor` workflow** (Recommended) — scout → investigate → plan → plan-execute → review → production-readiness-review → test → docs
320> 2. **Execute `$plan-execute` directly** — run this skill standalone
321
322---
323
324## Next Steps (Standalone: MUST ATTENTION ask user by asking the user directly. Skip if inside workflow.)
325
326**MANDATORY IMPORTANT MUST ATTENTION — NO EXCEPTIONS** after completing this skill, you MUST ATTENTION use ask the user directly to present these options. Do NOT skip because the task seems "simple" or "obvious" — the user decides:
327
328- **"Proceed with full workflow (Recommended)"** — I'll detect the best workflow to continue from here (code implemented). This ensures review, testing, and docs steps aren't skipped.
329- **"$code-simplifier"** — Simplify implementation
330- **"$integration-test"** — Generate/update integration tests from test specs
331- **"$workflow-review-changes"** — Review changes before commit
332- **"Skip, continue manually"** — user decides
333
334## Standalone Review Gate (Non-Workflow Only)
335
336> **Post-gate of the [Standalone Mode Pipeline](#standalone-mode-pipeline-skip-entirely-if-invoked-inside-a-workflow).** Full standalone loop: plan → plan-review → proceed → `$changes-review` → `$why-review`; the two review steps below are its tail.
337>
338> **MANDATORY IMPORTANT MUST ATTENTION:** If this skill is called **outside a workflow** (standalone `$plan-execute`), you MUST ATTENTION create task tracking todo tasks for `$changes-review` then `$why-review` as the **last tasks** in your task list. This ensures all changes are reviewed before commit even without a workflow enforcing it.
339>
340> If already running inside a workflow (e.g., `workflow-feature`, `workflow-refactor`), skip this — the workflow sequence handles `$changes-review` at the appropriate step.
341
342> **[IMPORTANT]** Use task tracking 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.
343
344**Prerequisites:** **MUST ATTENTION READ** before executing:
345
346- `docs/project-reference/frontend-patterns-reference.md`
347- `docs/project-reference/scss-styling-guide.md` — Styling/BEM guide (read when task involves frontend/UI)
348- `docs/project-reference/design-system/README.md` — Design system tokens (read when task involves frontend/UI)
349- `docs/project-reference/domain-entities-reference.md` — Domain entity catalog, relationships, cross-service sync (read when task involves business entities/models)
350
351> **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.
352
353> **Evidence Gate:** MANDATORY IMPORTANT MUST ATTENTION — every claim, finding, and recommendation requires `file:line` proof or traced evidence with confidence percentage (>80% to act, <80% must verify first).
354
355<!-- SYNC:end-to-start-debugger-trace -->
356
357> **End-to-Start Debugger Trace** — For non-trivial bugs, failed verification, regression fixes, behavior-changing code, or unclear code flow, start from the observed final state and walk backward before proposing a fix.
358>
359> 1. **Frame 0: observed end state** — Name the exact user-visible output, failing assertion, log line, persisted value, API response, rendered UI, or aggregate bucket. Record the reader/query/renderer that produced it with `file:line` evidence.
360> 2. **Walk backward one hop at a time** — Trace final reader -> projection/cache/storage -> writer -> consumer/handler/job -> producer/caller -> original trigger. At every hop record: input, transformation, output, owner, and evidence.
361> 3. **Enumerate all feeder paths** — Find every upstream producer/caller/event/job that can write into the final path, including retry, async, cache, background, and alternate UI/API paths. Mark each path verified, ruled out, or still unknown.
362> 4. **Build the hypothesis matrix** — For each plausible cause, list evidence for, evidence against, how to reproduce/verify, blast radius, and status (`primary`, `contributing`, `ruled out`, `latent`). Do not fix until competing causes are explicitly resolved or bounded.
363> 5. **Choose the owning fix layer** — Identify the invariant owner and the lowest shared point that protects all downstream consumers. A fix at the symptom site is rejected unless the symptom site owns the invariant.
364> 6. **Prove convergence forward** — After choosing the fix, walk start -> end again and show how the corrected state reaches the observed final output. Map each root cause to a fix part and each fix part to a test/proof.
365>
366> **BLOCKED until:** final state named · backward trace written · all feeder paths enumerated · hypothesis matrix completed · owning fix layer justified · forward convergence proof mapped to tests.
367>
368> **NEVER:** Start at the first suspicious code path. Collapse multiple producers into one "flow". Treat duplicate symptoms as duplicate records without proving the read model. Skip ruled-out hypotheses.
369
370<!-- /SYNC:end-to-start-debugger-trace -->
371
372<!-- SYNC:plan-granularity -->
373
374> **Plan Granularity** — Every phase must pass 5-point check before implementation:
375>
376> 1. Lists exact file paths to modify (not generic "implement X")
377> 2. No planning verbs (research, investigate, analyze, determine, figure out)
378> 3. Steps ≤30min each, phase total ≤3h
379> 4. ≤5 files per phase
380> 5. No open decisions or TBDs in approach
381>
382> **Failing phases →** create sub-plan. Repeat until ALL leaf phases pass (max depth: 3).
383> **Self-question:** "Can I start coding RIGHT NOW? If any step needs 'figuring out' → sub-plan it."
384
385<!-- /SYNC:plan-granularity -->
386
387<!-- SYNC:nested-task-creation -->
388
389> **Nested Task Expansion Contract** — For workflow-step invocation, the `[Workflow] ...` row is only a parent container; the child skill still creates visible phase tasks.
390>
391> 1. Call the current task list first. If a matching active parent workflow row exists, set `nested=true` and record `parentTaskId`; otherwise run standalone.
392> 2. Create one task per declared phase before phase work. When nested, prefix subjects `[N.M] $skill-name — phase`.
393> 3. When nested, link the parent with `TaskUpdate(parentTaskId, addBlockedBy: [childIds])`.
394> 4. Orchestrators must pre-expand a child skill's phase list and link the workflow row before invoking that child skill or sub-agent.
395> 5. Mark exactly one child `in_progress` before work and `completed` immediately after evidence is written.
396> 6. Complete the parent only after all child tasks are completed or explicitly cancelled with reason.
397>
398> **Blocked until:** the current task list done, child phases created, parent linked when nested, first child marked `in_progress`.
399
400<!-- /SYNC:nested-task-creation -->
401
402<!-- SYNC:project-reference-docs-guide -->
403
404> **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.
405>
406> 1. Identify scope: file types, domain area, and operation.
407> 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).
408> 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`.
409> 4. Read every required doc, then before target work state: `Reference docs read: ... | Not applicable: ...`.
410>
411> **Ready when:** scope evaluated, `docs/project-config.json` consulted, required docs checked/read or setup route completed, `lessons.md` confirmed, citation emitted.
412
413<!-- /SYNC:project-reference-docs-guide -->
414
415<!-- SYNC:critical-thinking-mindset -->
416
417> **Critical Thinking Mindset** — Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
418> **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.
419
420<!-- /SYNC:critical-thinking-mindset -->
421
422<!-- SYNC:understand-code-first -->
423
424> **Understand Code First** — HARD-GATE: Do NOT write, plan, or fix until you READ existing code.
425>
426> 1. Search 3+ similar patterns (`grep`/`glob`) — cite `file:line` evidence
427> 2. Read existing files in target area — understand structure, base classes, conventions
428> 3. Run `python .claude/scripts/code_graph trace <file> --direction both --json` when `.code-graph/graph.db` exists
429> 4. Map dependencies via `connections` or `callers_of` — know what depends on your target
430> 5. Write investigation to `.ai/workspace/analysis/` for non-trivial tasks (3+ files)
431> 6. Re-read analysis file before implementing — never work from memory alone. — why: long context drifts from the file; the file is ground truth
432> 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
433>
434> **BLOCKED until:** `- [ ]` Read target files `- [ ]` Grep 3+ patterns `- [ ]` Graph trace (if graph.db exists) `- [ ]` Assumptions verified with evidence
435
436<!-- /SYNC:understand-code-first -->
437
438<!-- SYNC:source-test-drift-check -->
439
440> **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.
441
442<!-- /SYNC:source-test-drift-check -->
443
444<!-- SYNC:ai-mistake-prevention -->
445
446> **AI Mistake Prevention** — Failure modes to avoid on every task:
447>
448> **Re-read files after context changes.** Context compaction, resume, or long-running work can make memory stale; verify current files before acting.
449> **Verify generated content against source evidence.** AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.
450> **Check downstream references before deleting or renaming.** Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.
451> **Trace the full impact chain after edits.** Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.
452> **Verify ALL affected outputs, not just the first.** One green check is not all green checks; validate every output surface the change can affect.
453> **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.
454> **Surface ambiguity before acting — don't pick silently.** Multiple valid interpretations require an explicit question or stated assumption with risk.
455> **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.
456> **Keep shared guidance role-relevant.** Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
457
458<!-- /SYNC:ai-mistake-prevention -->
459
460<!-- SYNC:plan-granularity:reminder -->
461
462**IMPORTANT MUST ATTENTION** verify all phases pass 5-point granularity check. Failing phases → sub-plan. "Can I start coding RIGHT NOW?"
463
464<!-- /SYNC:plan-granularity:reminder -->
465
466<!-- SYNC:understand-code-first:reminder -->
467
468**IMPORTANT MUST ATTENTION** search 3+ existing patterns and read code BEFORE any modification. Run graph trace when graph.db exists.
469
470<!-- /SYNC:understand-code-first:reminder -->
471
472<!-- SYNC:evidence-based-reasoning:reminder -->
473
474- **MANDATORY IMPORTANT MUST ATTENTION** cite `file:line` evidence for every claim. Confidence >80% to act, <60% = do NOT recommend.
475 <!-- /SYNC:evidence-based-reasoning:reminder -->
476
477<!-- SYNC:critical-thinking-mindset:reminder -->
478
479**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.
480
481<!-- /SYNC:critical-thinking-mindset:reminder -->
482
483<!-- SYNC:ai-mistake-prevention:reminder -->
484
485**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.
486
487<!-- /SYNC:ai-mistake-prevention:reminder -->
488
489<!-- SYNC:project-reference-docs-guide:reminder -->
490
491- **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: ...`.
492- **MANDATORY** Always include `lessons.md`; project config + conventions override generic framework defaults.
493- **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.
494
495<!-- /SYNC:project-reference-docs-guide:reminder -->
496
497<!-- SYNC:end-to-start-debugger-trace:reminder -->
498
499**IMPORTANT MUST ATTENTION** debugger trace gate: for non-trivial bug/fix/investigation/review work, start at the observed final output and trace backward through reader -> storage/projection -> writer -> consumer/job -> producer/trigger. Enumerate all feeder paths and hypotheses before fixing. **BLOCKED until** trace, hypothesis matrix, owning fix layer, and forward convergence proof exist.
500
501<!-- /SYNC:end-to-start-debugger-trace:reminder -->
502
503<!-- SYNC:nested-task-creation:reminder -->
504
505- **MANDATORY** Parent workflow rows do not replace child phase tracking; expand phases and link the parent when nested.
506- **MANDATORY** Orchestrators pre-expand child skill phases before invocation; use `[N.M] $skill-name — phase` prefixes and one-`in_progress` discipline.
507
508<!-- /SYNC:nested-task-creation:reminder -->
509
510<!-- SYNC:goal-contract-satisfaction-loop:reminder -->
511
512- **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.
513- **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.
514
515<!-- /SYNC:goal-contract-satisfaction-loop:reminder -->
516
517<!-- PROMPT-ENHANCE:STEP-TASK-CLOSING:START -->
518
519## Prompt-Enhance Closing Anchors
520
521**IMPORTANT MUST ATTENTION** follow declared step order for this skill; NEVER skip, reorder, or merge steps without explicit user approval
522**IMPORTANT MUST ATTENTION** for every step/sub-skill call: set `in_progress` before execution, set `completed` after execution
523**IMPORTANT MUST ATTENTION** every skipped step MUST include explicit reason; every completed step MUST include concise evidence
524**IMPORTANT MUST ATTENTION** if Task tools unavailable, maintain an equivalent step-by-step plan tracker with synchronized statuses
525
526<!-- PROMPT-ENHANCE:STEP-TASK-CLOSING:END -->
527
528<!-- SYNC:parallel-subagent-dispatch -->
529
530> **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.
531>
532> 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.
533> 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.
534> 3. **Declare before dispatch:** `Parallel plan: wave 1 = [...] · wave 2 = [...] · SEQ = [...] (reason)`.
535> 4. **Spawn each wave in ONE message** — every `spawn_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.
536> 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).
537> 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.
538> 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.
539>
540> **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.
541>
542> **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.
543
544<!-- /SYNC:parallel-subagent-dispatch -->
545
546<!-- SYNC:parallel-subagent-dispatch:reminder -->
547
548- **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.
549- **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.
550
551<!-- /SYNC:parallel-subagent-dispatch:reminder -->
552
553<!-- SYNC:project-protocol-overlay -->
554
555> **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`.
556>
557> 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.
558
559<!-- /SYNC:project-protocol-overlay -->
560
561<!-- SYNC:project-protocol-overlay:reminder -->
562
563**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.
564
565<!-- /SYNC:project-protocol-overlay:reminder -->
566
567## Closing Reminders
568
569**IMPORTANT MUST ATTENTION Goal:** Land the selected plan phase as working, fully-tested, reviewed, user-approved code — executing it phase-by-phase through testing, code review, and approval gates — committed only after every quality gate (100% tests, 0 critical issues, explicit approval) passes — NEVER bypass a gate to declare done.
570
571**Protocols in force (concise digest of the SYNC/shared blocks this skill carries):**
572
573- **End-To-Start Debugger Trace:** Trace observed end state backward through all feeders before fixing.
574- **Plan Granularity:** Verify every phase passes the 5-point check; sub-plan failures.
575- **Nested Task Creation:** Expand child phases and link the parent when nested.
576- **Project Reference Docs Guide:** Read required project-reference docs (always `lessons.md`); cite them first.
577- **Critical Thinking:** Apply critical + sequential thinking; traced proof, confidence >80% to act.
578- **Understand Code First:** Search 3+ patterns and read code before any modification.
579- **Source/Test Drift Check:** When behavior changes, reconcile affected tests from evidence.
580- **AI Mistake Prevention:** verify generated content against evidence, trace downstream references, verify all affected outputs, re-read after context loss, surface ambiguity.
581- **Parallel Sub-Agent Dispatch:** Tag tasks PAR/SEQ, group PAR into disjoint-write-set waves, spawn each wave in ONE message, barrier before advancing.
582
583**IMPORTANT MUST ATTENTION** run the full step spine in declared order, emit `✓ Step N:` each: Step 0 detect plan + select next incomplete phase → Step 1 Analysis & Task Extraction (read plan, Goal-Contract read, Trace Gate, seed task tracking) → Step 2 Implementation (code + type-check/compile; UI → `ui-ux-designer`) → Step 3 Testing (`tester`→`debugger` until 100%) → Step 4 Code Review (`code-reviewer` until 0 critical) → Step 5 User Approval (BLOCKING, wait) → Step 6 Finalize (`project-manager` + `docs-manager` + `git-manager`).
584**IMPORTANT MUST ATTENTION** execute Steps 0-6 in declared order; the three BLOCKING gates — tests 100% (Step 3), critical issues 0 (Step 4), explicit user approval (Step 5) — cannot be faked-green: NEVER skip a step, proceed on failed validation, or assume approval — why: a faked-green gate ships the regression the test exists to catch.
585**IMPORTANT MUST ATTENTION** cite `file:line` evidence for every claim, finding, and recommendation with confidence % — >80% to act, <80% verify first, <60% do NOT recommend — why: speculation passed as fact is the root of every hallucinated fix.
586**IMPORTANT MUST ATTENTION** break work into small task tracking todos BEFORE the first read/edit, keep exactly one `in_progress`, mark `completed` immediately after each step's evidence, add a final review todo — on context loss call the current task list first, never duplicate — why: long files exhaust context and silently lose findings.
587
588**IMPORTANT MUST ATTENTION** Pre-Implementation Granularity Gate + Trace Gate STOP the run BEFORE coding — refuse phases with planning verbs / unnamed files / unresolved decisions (sub-plan instead), and require the End→Start `Debugger Trace` (final state → reader → storage → writer → producer → trigger, all feeder paths, hypothesis matrix, owning fix layer, forward convergence) for any bug/regression/behavior-changing plan — why: implementing a vague phase or fixing the symptom site wastes the run.
589**IMPORTANT MUST ATTENTION** search 3+ existing patterns and READ target code (cite `file:line`) before writing — match local conventions over generic framework defaults, run a graph trace when `.code-graph/graph.db` exists; never invent a pattern when one exists — why: projects carry local conventions that framework defaults violate.
590**IMPORTANT MUST ATTENTION** fix at the LOWEST owning layer (Entity/Model > Service > Component/Handler), never patch the symptom/crash site — trace "whose responsibility?" first — why: one fix at the invariant owner protects all downstream consumers.
591**IMPORTANT MUST ATTENTION** a behavior change is NOT done until the Spec-Loop closes — universally-quantified property TC + boundary counter-case for every [HARD] rule touched, a mutation-killed test on each changed core-logic line, and a Dual-Feedback Ledger entry into BOTH spec AND tests — re-verify the whole package (spec + tests + code), not just the diff.
592**IMPORTANT MUST ATTENTION** keep existing tests real and genuinely passing — NEVER comment out tests, weaken assertions, change assertions to pass, or use fake data; apply the source/test drift check when behavior changes — why: faked green hides the regression the test exists to catch.
593**IMPORTANT MUST ATTENTION** mode flags add/remove ONE step, never relax a running gate — `--approval=off` skips Step 5, `--tests=off` skips Step 3, `--parallel={auto|on|off}` controls Step 2 fan-out (`off` = default sequential, `on` = explicit opt-in, `auto` = fan out only on plan-declared `PAR`/`SEQ` metadata); debugger-trace + granularity + quality bars + all SYNC blocks apply in EVERY mode.
594**IMPORTANT MUST ATTENTION** Step 2 is SEQUENTIAL by default — fan out only on the explicit `--parallel`/`--parallel=on` opt-in, or under `--parallel=auto` when EVERY in-scope phase carries a plan-declared `## Parallel Execution` block; `auto` with no such block falls back to sequential and NEVER derives write sets optimistically — why: a derived write set cannot see cascade/generated writes, so two "disjoint" phases silently collide on the same generated artifact.
595**IMPORTANT MUST ATTENTION** when a wave does run — NEVER co-schedule two writers of the same file, declare the wave plan, spawn every member in ONE message, then hold the barrier until EVERY member is accounted for by name; a failed, timed-out, or partial member blocks the barrier, is never assumed successful, and its phase is re-implemented sequentially before the next wave — why: an advanced barrier on an incomplete wave ships half a phase as if it were whole.
596**IMPORTANT MUST ATTENTION** gates are SEQ boundaries — Step 3 Testing, Step 4 Code Review, and the Step 5 approval gate run after the barrier on the merged result; a subagent's self-report NEVER substitutes for a host gate — why: parallelism may shorten the run, never the gate.
597**IMPORTANT MUST ATTENTION** standalone (no parent `[Workflow]` row via the current task list) → wrap Steps 0-6 in plan → plan-review → proceed → `$changes-review` → `$why-review`, with `$changes-review` + `$why-review` as the LAST todos; validate decisions with the user by asking the user directly — never auto-decide — why: standalone runs have no workflow enforcing review before commit.
598**IMPORTANT MUST ATTENTION** READ `CLAUDE.md` and the path-matched project-reference docs (frontend/scss/design-system for UI, domain-entities for models) before starting.
599**IMPORTANT MUST ATTENTION** Easy to Change is the success metric — every finding, test, refactor, abstraction must make the NEXT change cheaper; name the real enemies (coupling, hidden state, duplicated knowledge, unclear intent) and reject anything that raises change cost.
600
601**Anti-Rationalization:**
602
603| Evasion | Rebuttal |
604| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
605| "Tests are basically passing" | 100% or Step 3 is INCOMPLETE — loop `tester`→`debugger` until X/X — partial green ships the bug. |
606| "Code review found only minor issues" | 0 critical or Step 4 is INCOMPLETE — fix, re-run `tester`, re-run `code-reviewer`. |
607| "Obviously approved / they'll approve" | Step 5 is BLOCKING — stop and wait for an explicit user response, never assume approval. |
608| "Phase is clear enough to start" | Run the Granularity Gate — planning verbs / unnamed files / open decisions → sub-plan, don't code. |
609| "It's a quick fix, skip the trace" | Bug/regression plan needs the End→Start trace + hypothesis matrix BEFORE the fix. |
610| "Code change is enough, spec/tests later" | Behavior change → property TC + mutation-killed test + Dual-Feedback into spec AND tests, or INCOMPLETE. |
611| "Standalone, so skip review" | No workflow = YOU add `$changes-review` + `$why-review` as the last todos. |
612| "The plan looks parallelizable — fan it out" | Fan-out is OPT-IN: `--parallel`/`--parallel=on`, or `--parallel=auto` **plus** a plan-declared `## Parallel Execution` block. No opt-in, no metadata → sequential. |
613| "I can infer the write sets from the plan" | Not under `auto` — a derived set misses cascade/generated writes and collides on files no phase names. Fall back to sequential. |
614| "Both phases only touch different functions" | The unit of ownership is the FILE — any shared path splits the phases into different waves. |
615| "One wave member never came back, the rest passed" | The barrier does NOT advance — account for every member by name; failed/timed-out/partial → re-run that phase sequentially. |
616
617---
618
619**IMPORTANT MUST ATTENTION** the three BLOCKING gates (tests 100% · 0 critical · explicit approval) cannot be faked-green — NEVER bypass a gate to declare done.
620**IMPORTANT MUST ATTENTION** cite `file:line` + confidence % for every claim; search 3+ patterns and read code before writing.
621**IMPORTANT MUST ATTENTION** break work into small task tracking todos BEFORE starting; add a final review todo; on context loss call the current task list first.
622
623<!-- CODEX:SYNC-PROMPT-PROTOCOLS:START -->
624
625## Hookless Prompt Protocol Mirror (Auto-Synced)
626
627Source: `.claude/.ck.json` + `.claude/skills/shared/sync-inline-versions.md` (`:full` blocks) + `.claude/scripts/lib/hookless-prompt-protocol.cjs`
628
629## [WORKFLOW-EXECUTION-PROTOCOL] [BLOCKING] Workflow Execution Protocol — MANDATORY IMPORTANT MUST CRITICAL. Do not skip for any reason.
630
631**Generic portability boundary:** Reusable skills and protocol text stay project-neutral; project-specific conventions are discovered from docs/project-config.json and docs/project-reference/. Apply shared AI-SDD from `shared/sdd-artifact-contract.md`. Read `docs/project-config.json` and `docs/project-reference/docs-index-reference.md`, then open the project reference docs named there. For spec, test-case, behavior-change, public-contract, or `docs/specs/` work, route through the local spec docs named by the docs index: `feature-spec-reference.md`, `spec-system-reference.md`, `spec-principles.md`, and `workflow-spec-test-code-cycle-reference.md` when specs/tests/code must stay synchronized. If either file or a required reference doc is missing or stale, auto-run `$project-init` (or the narrow lower-level route such as `$project-config`, `$docs-init`, `$scan-all`, or `$scan --target=<key>`) before ordinary project-specific work. Any supported AI tool may execute when this shared context and local docs are available.
632
6331. **DETECT:** If the prompt starts with an explicit slash skill/workflow command, execute it directly. Otherwise match the prompt against the workflow catalog and skill list.
6342. **ANALYZE:** Choose the best option: execute directly, invoke a skill, activate a standard workflow, or compose a custom step combination.
6353. **AUTO-SELECT:** Pick the best option yourself. Do not ask the user to choose between direct execution, skill, standard workflow, or custom workflow.
6364. **ACTIVATE:** For a selected workflow, call `$start-workflow <workflowId>`; for a selected skill, invoke that skill; for a custom workflow, sequence custom steps directly; for direct execution, proceed with the task.
6375. **CREATE TASKS:** task tracking for ALL workflow/skill/custom steps before execution when the selected path has multiple steps.
6386. **PARALLELIZE:** Before executing the task list, tag each task `PAR` (independent inputs + write set disjoint from every other `PAR` task) or `SEQ` (name the blocking dependency), group `PAR` tasks into waves, declare the wave plan, and spawn each wave's sub-agents in ONE message — all-return barrier per wave, fan-out one level deep unless a sub-agent's own definition authorizes further fan-out. Sequential-by-default is a defect when tasks are independent; do not parallelize shared write targets, output-consuming tasks, trivial single-file work, ordering a skill or workflow explicitly fixes, or user-approval gates.
6397. **EXECUTE:** Advance per the **Workflow Step Advancement & Parallel Phases** rule in your context instructions — model-driven; a sub-agent completion advances a step identically to an inline call; a parallel-phase group is an all-return barrier (advance only after ALL members return, never serialize it)
640
641## Shared AI-SDD Protocol Markers
642
643Source: `.claude/skills/shared/sync-inline-versions.md`
644
645## SYNC:ai-sdd-artifact-contract
646
647> **AI-SDD Artifact Contract** — Shared spec-driven development rules stay portable and source-owned.
648>
649> 1. Keep reusable AI-SDD principles in `.claude`; put repository-specific paths, commands, owners, products, and formats in project config/reference docs.
650> 2. Preserve cycle: `spec -> plan -> tasks -> implement -> verify -> update spec/docs`.
651> 3. Trace every requirement or invariant through decision, task, TC/test, source evidence, and docs/spec update.
652> 4. Treat code-to-spec extraction as reference-only until accepted by the canonical spec owner.
653> 5. Any supported AI tool may plan, implement, review, or verify with synced context; using multiple tools is optional.
654> 6. Update `.claude` source first, then sync generated mirrors; do not manually edit `.agents`, `.codex`, or `AGENTS.md`. — why: mirrors are generated artifacts; hand-edits are overwritten on the next sync
655> 7. If `docs/project-config.json`, root instruction files, or a required project-reference doc is missing or stale, auto-run `$project-init` or the narrow lower-level route before ordinary project-specific work.
656>
657> **Active reference:** `shared/sdd-artifact-contract.md` in the active skills root.
658
659---
660
661## SYNC:ai-sdd-artifact-contract:reminder
662
663- **MANDATORY** Apply `shared/sdd-artifact-contract.md`; keep reusable AI-SDD in `.claude` and local rules in project docs.
664- **MANDATORY** Code-to-spec extraction is reference-only until canonical acceptance; any supported AI tool may execute with synced context.
665- **MANDATORY** Update `.claude` source before syncing generated mirrors; do not manually edit `.agents`, `.codex`, or `AGENTS.md`.
666- **MANDATORY** Missing or stale project config, root instruction files, or required reference docs route project-specific work through `$project-init` or the narrow setup route automatically.
667 **[TASK-PLANNING] [MANDATORY]** BEFORE executing any workflow or skill step, create/update task tracking for all planned steps, then keep it synchronized as each step starts/completes.
668
669## [LESSON-LEARNED-REMINDER] [BLOCKING] Task Planning & Continuous Improvement — MANDATORY. Do not skip.
670
671Break work into small tasks (task tracking) before starting. Add final task: "Analyze AI mistakes & lessons learned".
672
673**Extract lessons — ROOT CAUSE ONLY, not symptom fixes:**
674
6751. Name the FAILURE MODE (reasoning/assumption failure), not symptom — "assumed API existed without reading source" not "used wrong enum value".
6762. Generality test: does this failure mode apply to ≥3 contexts/codebases? If not, abstract one level up.
6773. Write as a universal rule — strip project-specific names/paths/classes. Useful on any codebase.
6784. Consolidate: multiple mistakes sharing one failure mode → ONE lesson.
6795. **Recurrence gate:** "Would this recur in future session WITHOUT this reminder?" — No → skip `$learn`.
6806. **Auto-fix gate:** "Could `$code-review`/`$code-simplifier`/`$security-review`/`$lint` catch this?" — Yes → improve review skill instead.
6817. BOTH gates pass → ask user to run `$learn`.
682 **[CRITICAL-THINKING-MINDSET]** Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
683 **Anti-hallucination principle:** Never present guess as fact — cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence — certainty without evidence root of all hallucination.
684 **AI Attention principle (Primacy-Recency):** Put the 3 most critical rules at both top and bottom of long prompts/protocols so instruction adherence survives long context windows.
685 **Goal-driven execution:** Define success criteria first, loop until verified, and stop only when observable checks pass.
686 **Tests verify intent:** Tests must protect business rules/invariants and fail when the protected intent breaks, not only mirror current behavior.
687
688## Common AI Mistake Prevention (System Lessons)
689
690- **Re-read files after context compaction.** Edit requires prior Read in same context; compaction wipes read state. Re-read before editing.
691- **Grep for old terms after bulk replacements.** AI over-trusts find/replace completeness. Grep full repo after bulk edits for missed refs in docs/configs/catalogs.
692- **Check downstream references before deleting.** Deletions cascade doc/code staleness. Map referencing files before removal.
693- **After memory loss, check existing state before creating new.** Compaction wipes prior-work memory. Query current state to resume — never blindly duplicate.
694- **Verify AI-generated content against actual code.** AI hallucinates APIs, class names, method signatures. Grep to confirm existence before documenting/referencing.
695- **Trace full dependency chain after edits.** Changing a definition misses downstream consumers. Trace the full chain.
696- **When renaming, grep ALL consumer file types.** Some file types silently ignore missing refs (no compile error). Search code, templates, configs, generated files.
697- **Trace ALL code paths when verifying correctness.** Code existing ≠ code executing. Trace early exits, error branches, conditional skips — not just happy path.
698- **Update docs that embed canonical data when source changes.** Docs inlining derived data (workflows, schemas, configs) go stale silently. Update all embedding docs alongside source.
699- **Verify sub-agent results after context recovery.** Background agents may finish while parent compacted — grep-verify output, don't trust assumed completion.
700- **Cross-check full target list against sub-agent assignments.** Parallel sub-agents by category miss boundary items. Reconcile union of assignments against target list before proceeding.
701- **Sub-agents inherit knowledge only from their agent .md definition — use custom agent types, not built-in Explore.** Tool adoption = permission + knowledge + enforcement (numbered workflow step).
702- **Persist sub-agent findings incrementally, not as a final batch.** Long sub-agents hit cutoffs before final write — findings lost. Instruct append-per-section to report file.
703- **When debugging, ask "whose responsibility?" before fixing.** Trace caller (wrong data) vs callee (wrong handling). Fix at responsible layer — never patch symptom site.
704- **Test failure → record a provisional verdict before trace/edit, then investigate.** Use the full five-way taxonomy: SOURCE-WRONG (production violates intent), TEST-WRONG (assertion/setup is stale), TEST-NOT-OPTIMAL (valid but fragile or low-signal test), ENVIRONMENT-BLOCKED (external state prevents a verdict), or AMBIGUOUS (intent/evidence cannot choose safely). Then trace root cause and triangulate against the governing spec (`docs/specs/**` if one exists) AND source. NEVER weaken an assertion, add a skip, relax a timeout, or change source merely to force green.
705- **Grep ALL removed names after extraction/refactoring.** Primary file "done" ≠ secondary files clean. Grep entire scope for every removed symbol before declaring complete.
706- **Assume existing values are intentional — ask WHY before changing OR flagging one as a defect.** Pattern-matching as "wrong" skips context. Before changing or reporting any constant/limit/flag/cutoff: read comments, git blame, the CALLER's ordering (the guarantee that makes the value correct usually lives in code running immediately BEFORE the cited line), and 2+ sibling call sites of the same convention. A doc stating WHAT without WHY is missing rationale, not proof of a missing guard — and in a validation pass, an accurate `file:line` citation proves the transcription, never the defect.
707- **Verify ALL affected outputs, not just the first.** One build green ≠ all green. Multi-stack changes (backend/frontend/tests/docs) require verifying EVERY output.
708- **Evaluate fit before copying a nearby pattern.** Closest example ≠ matching preconditions — verify the new context shares the same constraints, base classes, scope, lifetime.
709- **Holistic-first debugging — resist nearest-attention trap.** Don't dive into first plausible cause. List EVERY precondition (config, env vars, paths, DB, endpoints, creds, versions, DI, data). Verify each against evidence (grep/query — not reasoning). Ask "what would falsify this?" — if nothing, it's not a hypothesis. Most expensive failure: going deeper in "obvious" layer while bug sits in layer never questioned.
710- **Surgical changes — apply the diff test (context-aware).** Two modes: (1) Bug fix → every line traces to the bug; no restyling; orphan cleanup only for imports YOUR changes made unused. (2) Review/enhancement → implement improvements AND announce as "Enhancement beyond main request: [what]". Never silently scope-creep. Diff test: "Would this line exist if I wasn't asked to do X?" — if no, delete or announce.
711- **Surface ambiguity before coding — don't pick silently.** Multiple valid interpretations → present each with effort: "[Request] could mean (1) [N h], (2) [N h]. Which matters?" List scope/format/volume/constraints assumptions first. If simpler path exists, say so. Never silently pick.
712- **[MANDATORY FIRST ACTION] ALWAYS activate a suitable skill or workflow BEFORE responding.** Match task against workflow catalog + skill list; invoke via skill invocation or `$start-workflow <workflowId>`. NEVER answer or write code before checking. Skip = protocol violation.
713- **Why-Review adversarial mindset — apply when reviewing any plan, decision, or design.** Default SKEPTIC not VALIDATOR: steel-man a rejected alternative, invert each stated reason ("what does it sacrifice?"), stress-test top 2-3 assumptions, run pre-mortem ("ships, fails in 3 months — what breaks?"), surface 1-2 alternatives author missed. Section presence ≠ quality; quality = causal reasoning + concrete mitigations + evidence, not "it's better" or "monitor closely".
714- **Front-load report-write in sub-agent prompts for large reviews.** Many-file sub-agents hit budget before final write — findings lost. Design prompts so: (1) report-write is first explicit deliverable, (2) append per-file/section (not batched), (3) scope bounded so reads don't exhaust budget. Truncated mid-sentence with no report file → spawn narrower scope, don't retry same prompt.
715- **After context compaction, re-verify all prior phase outcomes before continuing.** Summaries describe intent, not environment state (git index, filesystem, processes). On resume, FIRST audit: git status, re-read modified files, verify filesystem. Every "completed" claim is an untested hypothesis until evidence confirms.
716- **OOM/memory: check row count before row size.** Triage: (1) Unbounded query — no DB filter for trigger? Push filter to DB; eliminates OOM. (2) Large rows? Projection reduces proportionally. Row reduction > projection in ROI.
717- **Assert the outcome your system OWNS, never the intermediate state your INFRASTRUCTURE owns.** When testing anything asynchronous (queue/broker delivery, retries, background jobs, caches, replication), assert the final business/entity state. NEVER assert the delivery bookkeeping — consume/send status, attempt counts, last-error, row existence or counts in a broker, scheduler, or outbox/inbox table. That bookkeeping lives in shared infrastructure that ANY co-running process (a peer worker, a second replica, a leftover local container) can write, usually under a deterministic shared key, so the assertion silently tests the developer's environment instead of the system: green when run alone, flaky the instant anything else shares that broker + database. Gate question for every assertion: "would this hold no matter WHICH process did the work?" — if no, assert the converged data state instead. Corollary: process-local fault injection and in-process telemetry cannot gate work any process may perform — use them as stress amplifiers (arm → bounded window → disarm → assert convergence), never as preconditions.
718- **Keep domain concepts out of generic/shared/infrastructure layers.** Reusable layer (shared library, framework, infra module) must reference NO consumer-specific domain concept — tenant/customer/product IDs, business entities, feature rules. Leak compiles + runs → passes review silently while coupling the "reusable" layer to one consumer. Keep shared type domain-free; push domain fields/logic down into the consumer via subclass/composition. — why: a layer coupled to one consumer's domain is no longer reusable.
719
720<!-- CODEX:SYNC-PROMPT-PROTOCOLS:END -->