@lifeaitools/rdc-skills 0.24.6 → 0.24.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/.claude-plugin/plugin.json +20 -5
  2. package/.github/workflows/self-test.yml +34 -34
  3. package/MANIFEST.md +23 -0
  4. package/README.md +37 -0
  5. package/commands/build.md +181 -181
  6. package/commands/collab.md +180 -180
  7. package/commands/deploy.md +148 -148
  8. package/commands/fixit.md +105 -105
  9. package/commands/handoff.md +173 -173
  10. package/commands/overnight.md +218 -218
  11. package/commands/plan.md +158 -158
  12. package/commands/preplan.md +131 -131
  13. package/commands/prototype.md +145 -145
  14. package/commands/report.md +99 -99
  15. package/commands/review.md +120 -120
  16. package/commands/status.md +86 -86
  17. package/commands/workitems.md +127 -127
  18. package/git-sha.json +1 -1
  19. package/guides/agent-bootstrap.md +195 -195
  20. package/guides/agents/backend.md +102 -102
  21. package/guides/agents/content.md +94 -94
  22. package/guides/agents/cs2.md +56 -56
  23. package/guides/agents/data.md +86 -86
  24. package/guides/agents/design.md +77 -77
  25. package/guides/agents/frontend.md +91 -91
  26. package/guides/agents/infrastructure.md +81 -81
  27. package/guides/agents/setup.md +272 -272
  28. package/guides/agents/verify.md +119 -119
  29. package/guides/agents/viz.md +106 -106
  30. package/hooks/task-completed-gate.js +25 -3
  31. package/package.json +1 -1
  32. package/scripts/self-test.mjs +1458 -1458
  33. package/skills/build/SKILL.md +554 -554
  34. package/skills/channel-formatter/SKILL.md +174 -9
  35. package/skills/collab/SKILL.md +239 -239
  36. package/skills/deploy/SKILL.md +541 -541
  37. package/skills/design/SKILL.md +205 -205
  38. package/skills/fixit/SKILL.md +165 -165
  39. package/skills/handoff/SKILL.md +200 -200
  40. package/skills/overnight/SKILL.md +251 -251
  41. package/skills/plan/SKILL.md +314 -314
  42. package/skills/preplan/SKILL.md +90 -90
  43. package/skills/prototype/SKILL.md +150 -150
  44. package/skills/release/SKILL.md +140 -140
  45. package/skills/report/SKILL.md +100 -100
  46. package/skills/review/SKILL.md +152 -152
  47. package/skills/self-test/SKILL.md +123 -123
  48. package/skills/status/SKILL.md +99 -99
  49. package/skills/watch/SKILL.md +90 -90
  50. package/skills/workitems/SKILL.md +151 -151
  51. package/tests/harness-gates.test.mjs +30 -0
@@ -1,554 +1,554 @@
1
- ---
2
- name: rdc:build
3
- description: "Usage `rdc:build <epic-id>` — You have a planned epic with tasks ready to execute. Dispatches parallel typed agents, each commits atomically to develop, runs a mandatory per-wave code-review gate (pr-review-toolkit:code-reviewer), closes work items, and runs the validator gate. Call after rdc:plan or when told to build."
4
- ---
5
-
6
- > **⚠️ OUTPUT CONTRACT (READ FIRST):** `guides/output-contract.md`
7
- > Checklist-only output. No tool-call narration. No raw MCP/JSON/log dumps.
8
- > One checklist upfront, updated in place, shown again at end with a 1-line verdict.
9
-
10
- > **Sandbox contract:** This skill honors `RDC_TEST=1` per `guides/agent-bootstrap.md` § RDC_TEST Sandbox Contract. Destructive external calls short-circuit under the flag.
11
-
12
-
13
- # rdc:build — Typed Agent Dispatch Engine
14
-
15
- ## When to Use
16
- - Plan is approved and ready to execute
17
- - Project lead says "build it", "go", "execute", "do not stop"
18
- - An epic exists with child tasks ready for implementation
19
- - Called by `rdc:overnight` as part of the automated build loop
20
-
21
- ## Arguments
22
- - `rdc:build <epic-id>` — build from a specific Supabase epic
23
- - `rdc:build <topic>` — find the epic by label/title match
24
- - `rdc:build` (no args) — show open epics and ask which to build (interactive only)
25
- - `rdc:build <epic-id> --unattended` — silent mode for overnight builds
26
-
27
- ## Agent Types & Guide Files
28
-
29
- Every dispatched agent MUST read two files before starting — in this order:
30
- 1. `{PROJECT_ROOT}/.rdc/guides/agent-bootstrap.md` — credentials, git rules, completion report format
31
- (fallback: `.rdc/guides/agent-bootstrap.md` relative to cwd if `{PROJECT_ROOT}` is not substituted)
32
- 2. `{PROJECT_ROOT}/.rdc/guides/engineering-behavior.md` — assumptions, minimal changes, surgical scope, verification evidence
33
- (fallback: `.rdc/guides/engineering-behavior.md` relative to cwd if `{PROJECT_ROOT}` is not substituted)
34
- 3. `{PROJECT_ROOT}/.rdc/guides/<type>.md` — role-specific guide
35
- (fallback: `.rdc/guides/<type>.md` relative to cwd if `{PROJECT_ROOT}` is not substituted)
36
-
37
- Include both lines in every agent prompt:
38
- ```
39
- "Read {PROJECT_ROOT}/.rdc/guides/agent-bootstrap.md first (fallback: .rdc/guides/agent-bootstrap.md), then {PROJECT_ROOT}/.rdc/guides/engineering-behavior.md (fallback: .rdc/guides/engineering-behavior.md), then {PROJECT_ROOT}/.rdc/guides/<type>.md (fallback: .rdc/guides/<type>.md) before starting."
40
- ```
41
-
42
- | Agent Type | Guide File | When to dispatch |
43
- |-----------|-----------|-----------------|
44
- | `frontend` | `.rdc/guides/frontend.md` | React components, pages, UI, Tailwind, animation |
45
- | `backend` | `.rdc/guides/backend.md` | API routes, server components, database queries, auth |
46
- | `data` | `.rdc/guides/data.md` | Migrations, schema changes, RPC functions |
47
- | `design` | `.rdc/guides/design.md` | Visual design, brand palettes, OG images, token work |
48
- | `infra` | `.rdc/guides/infrastructure.md` | CI/CD, deployment, DNS, SSL |
49
- | `content` | `.rdc/guides/content.md` | Marketing copy, messaging, tone |
50
- | `cs2` | `.rdc/guides/cs2.md` | CS 2.0 paradigm work (generic) |
51
- | `hail` | `.rdc/guides/cs2.md` + `packages/hail/CLAUDE.md` | Grammar, DSL compiler, evolution |
52
- | `pal` | `.rdc/guides/cs2.md` + `packages/pal/CLAUDE.md` | Sessions, moment windows, graph memory |
53
- | `bpmn` | `.rdc/guides/cs2.md` + `docs/systems/<domain>/flowable-bpmn-architecture.md` | BPMN flows, governance |
54
- | `virtue` | `.rdc/guides/cs2.md` + `packages/virtue-engine/CLAUDE.md` | Virtue weights, coherence, certification |
55
- | `viz` | `.rdc/guides/frontend.md` + `.rdc/guides/design.md` | Custom viz components, charts, diagrams |
56
-
57
- ### How to classify a task → agent type
58
-
59
- Read the task title and description, then:
60
- - Mentions React, component, page, UI, Tailwind → `frontend`
61
- - Mentions API route, server, database query, auth → `backend`
62
- - Mentions migration, schema, table, RPC → `data`
63
- - Mentions brand, palette, typography, OG image → `design`
64
- - Mentions deploy, infrastructure, CI, DNS → `infra`
65
- - Mentions copy, messaging, email template → `content`
66
- - Mentions grammar, DSL, compiler → `hail`
67
- - Mentions session, moment, memory graph → `pal`
68
- - Mentions BPMN, flow, governance → `bpmn`
69
- - Mentions virtue, coherence, certification → `virtue`
70
- - Mentions visualization, chart, diagram, SVG → `viz`
71
- - Multiple types? Dispatch multiple agents, each with its guide.
72
-
73
- ## Procedure
74
-
75
- 1. **Load the epic and run pre-flight gate:**
76
- ```sql
77
- SELECT get_work_items_by_epic('<epic-id>', 'todo');
78
- ```
79
-
80
- **Session lock — claim the epic immediately (before any agent dispatch):**
81
-
82
- After loading the epic, check its status:
83
- - If `status = 'in_progress'` → **ABORT** with:
84
- ```
85
- SKIP: epic <id> is already in_progress — claimed by another session. Pick a different epic.
86
- ```
87
- Do NOT proceed. Do NOT dispatch any agents.
88
- - If `status = 'todo'` or `status = 'blocked'` → immediately claim it:
89
- ```sql
90
- SELECT update_work_item_status('<epic-id>'::uuid, 'in_progress',
91
- '["Claimed by build session — dispatching agents"]'::jsonb
92
- );
93
- ```
94
- This is an atomic Supabase write. A concurrent session that loads the same epic after this point will see `in_progress` and abort. **Do this before any classification, planning, or agent dispatch.**
95
-
96
- **Pre-flight gate — run after claiming:**
97
-
98
- | Condition | Action |
99
- |-----------|--------|
100
- | No child tasks returned | → Invoke `rdc:plan` on this epic. Do NOT proceed with build. |
101
- | Tasks exist but all have empty `description` fields | → Invoke `rdc:plan` on this epic. Tasks without descriptions cannot be safely dispatched. |
102
- | Plan doc missing `## Checklist Decomposition Matrix` | → Invoke `rdc:plan` on this epic. Do NOT dispatch agents. |
103
- | Plan doc missing `## Checklist Quality Gate` with `verdict: PASS` | → Invoke `rdc:plan` on this epic. Do NOT dispatch agents. |
104
- | Any implementation task lacks `decomp-*` checklist items | → Invoke `rdc:plan` on this epic. Coarse checklists cannot be safely dispatched. |
105
- | Any `decomp-*` item lacks route/file, action, expected result, or evidence artifact | → Invoke `rdc:plan` on this epic. Do NOT dispatch agents. |
106
- | Tasks exist and have descriptions | → Continue with build. |
107
-
108
- **Re-planning is not a failure — it is correct behavior.** The build skill is the last gate before agent dispatch; catching an under-specified epic here is cheaper than a wasted agent run.
109
-
110
- **How to re-plan:**
111
- - Interactive: tell the user — "Epic has no tasks / tasks lack descriptions — invoking rdc:plan first." Then invoke `rdc:plan <epic-id>`.
112
- - Unattended: invoke `rdc:plan <epic-id> --unattended` inline, wait for it to complete, then reload tasks and re-run this gate once. If tasks still missing after re-plan, escalate via advisor.
113
-
114
- **Interactive (no args):** show open epics, ask which to build.
115
-
116
- 2. **CHECK FOR EXISTING WORK (mandatory — never skip):**
117
- ```sql
118
- -- Check if prototypes exist from earlier sessions
119
- SELECT name, component, source_path, status, notes
120
- FROM prototype_registry
121
- WHERE status IN ('prototype', 'converting')
122
- ORDER BY created_at DESC;
123
-
124
- -- Check for design decisions on this topic
125
- SELECT topic, context_type, summary, source
126
- FROM design_context
127
- WHERE topic ILIKE '%<epic-topic>%'
128
- ORDER BY created_at DESC;
129
- ```
130
- **If a prototype exists: ADAPT IT. Do not build from scratch.**
131
- Tell the agent: "Read <source_path> first and convert it to the production contract."
132
-
133
- **If design decisions exist: follow them.** Include the summary in the agent prompt.
134
-
135
- 3. **Load the plan** (mandatory): check `.rdc/plans/` for matching topic (fallback: `.rdc/plans/`).
136
-
137
- 3b. **Checklist decomposition quality gate (mandatory before code):**
138
-
139
- `rdc:build` is the final gate before implementation. It MUST reject any plan or work item that is too coarse for an agent to execute and verify independently.
140
-
141
- Required plan sections:
142
- - `## Checklist Decomposition Matrix`
143
- - `## Checklist Quality Gate`
144
- - `verdict: PASS`
145
-
146
- Required task checklist shape:
147
- - Every implementation work item has at least one `decomp-*` checklist row and one `test-*` checklist row.
148
- - Every `decomp-*` row names a concrete route or file path.
149
- - Every `decomp-*` row names one user/agent action.
150
- - Every `decomp-*` row names one expected UI/API/DB result.
151
- - Every `decomp-*` row names one verification artifact: test name, route probe, Playwright screenshot, SQL query, API response, type-check, migration proof, or CLI transcript.
152
-
153
- Atomicity rubric:
154
- - One observable behavior per `decomp-*` row.
155
- - The row can pass or fail without reading hidden intent from the plan narrative.
156
- - The row is small enough for a worker to implement, tick, and cite evidence for directly.
157
- - Vague rows such as "theme management works", "UI implemented", "verified", "all screens", or "integration complete" are failures.
158
-
159
- Minimum decomposition heuristics:
160
- - UI route: at least empty/loading/loaded/error or the documented reason a state does not apply.
161
- - CRUD surface: at least list, create, edit, detail, duplicate/delete/archive where applicable, and validation failure.
162
- - API route: at least successful read/write, validation failure, and unauthorized/forbidden or documented auth bypass.
163
- - DB/migration task: at least schema object, relationship/guard, policy/permission, seed/fixture or backfill, and smoke query.
164
- - Editor/sidebar/CLI workflow: at least start, attach/open, enqueue action, observe result, timeout/error, and live refresh where applicable.
165
-
166
- ### ⛔ Deliverable / acceptance check-off table — show BEFORE any implementation
167
- Before dispatching the first wave, render a deliverable/acceptance table and
168
- keep it visible through the build (lesson 2026-06-16-build-poor-goal-execution-mdk-brain:
169
- a build satisfied generic checklist rows — tsc clean, route 200 — while never
170
- touching the surface the user actually named, because no row anchored the
171
- user's TARGET SURFACE). The table MUST contain:
172
- - **One mandatory row for the user-named TARGET SURFACE** — the exact screen,
173
- endpoint, file, or behavior the user asked for, by name. Its acceptance check
174
- is what proves THAT surface renders/works, not a proxy.
175
- - **At least one NEGATIVE verifier row** — a check that proves the WRONG thing
176
- does NOT happen (e.g. "mock data is NOT rendered", "old route returns 404",
177
- "stub component is absent from the bundle"). A positive-only suite passes
178
- even when the deliverable is wired to the wrong source.
179
-
180
- | Deliverable | Target surface? | Acceptance check | Negative verifier | Status |
181
- |---|---|---|---|---|
182
-
183
- **Gating rule:** any work item whose deliverable maps to the TARGET SURFACE row
184
- stays in `review` (never `done`) until that target-surface acceptance check
185
- passes. Generic gates (tsc, route 200) clearing is NOT sufficient to advance
186
- the target-surface item.
187
-
188
- If the gate fails:
189
- - Interactive: show the failing rows and invoke `rdc:plan <epic-id>` to repair the matrix before dispatch.
190
- - Unattended: invoke `rdc:plan <epic-id> --unattended`, reload tasks, and run this gate once more.
191
- - If the second gate fails, abort the build and return the failure list. Do not dispatch implementation agents.
192
-
193
- **Plan verifier escalation:** A separate verifier agent is optional, not default. Dispatch one only when the plan touches 5+ UI routes, 3+ data/API boundaries, auth/security, production deployment, or when this rubric fails twice. The verifier reads the plan and work-item checklists only; it does not write code.
194
-
195
- 4. **Read CLAUDE.md files** for all affected packages.
196
-
197
- 5. **Classify each task** → assign agent type from the table above.
198
-
199
- 5b. **Write or refresh the checklist into every work item before dispatching:**
200
- For each task, append the exact `decomp-*` and `test-*` checklist rows to its notes BEFORE setting to `in_progress`:
201
- ```sql
202
- SELECT update_work_item_status('<id>'::uuid, 'in_progress',
203
- '["CHECKLIST: [ ] decomp-ui-route-state: <route/file> | action=<action> | expect=<result> | evidence=<artifact>, [ ] test-smoke-route: <route probe>, [ ] committed"]'::jsonb
204
- );
205
- ```
206
- The agent must complete every item on this checklist and return it checked off in AGENT_COMPLETE.
207
- A checklist with unchecked items = incomplete work. Do not proceed to next wave with unchecked items.
208
-
209
- 6. **Group tasks into waves** — parallelize tasks with no file overlap:
210
- - Wave 1: independent tasks (different packages/files)
211
- - Wave 2: tasks that depend on Wave 1 outputs
212
- - Wave 3: integration tasks
213
-
214
- 7. **For each wave — dispatch typed agents in parallel:**
215
-
216
- ### ⛔ Agent Dispatch Non-Negotiable Defaults
217
- Every `Agent()` call MUST include these parameters:
218
- ```
219
- model: <chosen per the routing table below>
220
- max_turns: 70
221
- ```
222
- `isolation` is chosen per the dispatch-mode rule below — it is NOT a blanket
223
- default. Worktree isolation is reserved for true parallel MULTI-committer waves
224
- in the same repo; doc-only and single-committer waves default to NON-isolated.
225
-
226
- ### ⛔ Dispatch mode — non-isolated is the default for single-committer / doc-only waves
227
- Worktree isolation exists to protect a SHARED working tree from a git-index race
228
- between MULTIPLE agents committing in parallel. When there is only ONE committer,
229
- that race cannot occur, and the stale-base hazard of worktrees (see the HARD GATE
230
- below — recurring across 2026-06-10/11/15/16/17/23) is pure downside. Pick the
231
- dispatch mode by committer count, not by reflex:
232
-
233
- | Wave shape | Dispatch mode | isolation |
234
- |---|---|---|
235
- | **Doc-only wave** (markdown/docs/plans, no code build) | NON-isolated, one committer on `develop` | omit `isolation` |
236
- | **Single-committer wave** (only one agent commits, or work serializes to the supervisor) | NON-isolated, one committer on `develop` | omit `isolation` |
237
- | **True parallel MULTI-committer wave** (2+ agents committing concurrently in the same repo, disjoint files) | worktree-isolated, supervisor merges | `isolation: "worktree"` |
238
-
239
- - **Default = NON-isolated.** Only escalate to `isolation: "worktree"` when the
240
- wave genuinely has 2+ concurrent committers in the same repo.
241
- - A pure docs wave is single-committer by default: either dispatch ONE doc agent,
242
- or have parallel doc agents return diffs/patches that the supervisor commits
243
- serially. Do NOT fan out 2+ concurrent committers onto one shared `develop`
244
- tree (lesson 2026-06-13-build-concurrent-agents-same-branch-git-race: three
245
- parallel doc agents on one `develop` tree raced on the git index/stash — one
246
- commit swept in another agent's staged-but-uncommitted files under the wrong
247
- message, two agents reported the SAME SHA, a pre-commit `sync:docs` ref-lock
248
- race misattributed authorship). The fix for that race is single-committer
249
- serialization, NOT blanket worktree isolation.
250
- - When you DO need a true MULTI-committer parallel wave, worktree isolation is
251
- mandatory AND the HARD GATE below (base == develop HEAD) MUST pass before
252
- dispatch — a stale-base worktree wave is a build failure, not a warning.
253
-
254
- ### ⛔ Foreign concurrent session guard — `git status` BEFORE the build
255
- Worktree isolation protects against THIS build's own agents, not against a
256
- DIFFERENT session (another cell, a Codex run, a human) already committing on
257
- the same shared tree (lesson 2026-06-16-build-concurrent-session-shared-tree-commit-corruption:
258
- a foreign session's staged-but-uncommitted files were swept into this build's
259
- commit under the wrong message). Before dispatching any wave, run `git status`
260
- to detect foreign-dirty files you did not create. If foreign-dirty files are
261
- present: do NOT fan out concurrent committers — **serialize ALL committers to
262
- the supervisor** (agents return diffs/patches; the supervisor stages and
263
- commits each one alone). After every supervisor commit, assert the exact file
264
- set landed and nothing foreign leaked in:
265
- ```bash
266
- git show --stat <sha> # confirm ONLY the files this commit owns are listed
267
- ```
268
- A `git show --stat` that lists a file the agent did not touch = a foreign file
269
- leaked into the commit; reset and re-stage by explicit path.
270
-
271
- **Agent model routing — pick per task, not per wave.** The supervisor session model does NOT cascade to agents; you must set `model` explicitly on every dispatch.
272
-
273
- | Task character | Model | When to pick it |
274
- |---|---|---|
275
- | Updates, edits, mechanical refactors, small fixes, content tweaks, config patches, doc/copy edits, straightforward API wiring | `claude-sonnet-4-6` | Default for `frontend.md`/`content.md`/`infrastructure.md` work whose checklist is mostly "change X to Y" or "wire up endpoint Z". Budget-safe for parallel dispatch. |
276
- | Harder coding tasks — non-trivial algorithm, migration with backfill, schema reshape, multi-file refactor with subtle invariants, performance-sensitive code, anything where correctness is the bar | `claude-opus-4-6` | Default for `backend.md`/`data.md` work and any `frontend.md` task that involves state machines, race conditions, or cross-package contracts. |
277
- | Design or innovative thought — new component design, brand/UX work, CS 2.0 paradigm work (HAIL/Quad Pixel/AEMG/Virtue), grammar evolution, architecture-first design, anything where the *shape* of the solution is the deliverable rather than the implementation | `claude-opus-4-8` | Default for `design.md`/`cs2.md` work. Also use for `backend.md`/`data.md` tasks tagged with `architecture` or `design-decision` in work item labels. |
278
-
279
- **How to choose when the task straddles categories:**
280
- - If the task's checklist contains the word "design", "decide", "propose", "evaluate alternatives", "novel", or any CS 2.0 primitive → **Opus 4.8**.
281
- - If the task touches `packages/cs2*`, `packages/hail`, `packages/quad-pixel`, `packages/virtue-engine`, `packages/aemg`, `packages/planetary-ontology`, or `packages/being-state-processor` → **Opus 4.8** (CS 2.0 paradigm requires innovative thought, not transcription).
282
- - If the task is a Supabase migration that drops/renames/reshapes anything, or a refactor across ≥5 files → **Opus 4.6**.
283
- - Otherwise → **Sonnet 4.6**.
284
-
285
- **State the choice in the wave plan.** Before dispatching a wave, the supervisor must log one line per agent in the form `[wave-N agent-K] role=<role> task=<id> model=<chosen> reason=<one phrase>`. This keeps routing decisions reviewable in the transcript and lets `rdc:report` summarize the fleet mix.
286
-
287
- **Cost guardrail.** If a single wave would dispatch more than 3 Opus 4.8 agents in parallel, downshift the lowest-priority Opus-4.8 tasks to Opus 4.6 unless their work items are tagged `priority=urgent`. Opus 4.8 fast-mode is cheap individually but still ~5× a Sonnet agent at scale.
288
- Without `max_turns: 70`, agents hit the default turn cap mid-task and stop.
289
- `isolation: "worktree"` gives each agent its own git worktree and branch — eliminates push race conditions and index lock contention when multiple agents commit in parallel. The supervisor merges worktree branches after each wave (Step 9).
290
-
291
- ### ✅ PREVENTION FIRST — create worktrees fresh off origin/develop (kills stale-base by construction)
292
- The repeated stale-base failures below come from creating worktrees off a
293
- local/old ref. Eliminate the failure mode at the source: ALWAYS create agent
294
- worktrees with a fresh fetch + `origin/develop` base, e.g.
295
- `git fetch origin develop && git worktree add <dir> -b <branch> origin/develop`
296
- — or use the canonical launcher `node scripts/wt.mjs add <name>`, which does
297
- exactly that. A worktree cut from `origin/develop` HEAD **cannot** be stale.
298
- The HARD GATE below remains as the blocking backstop (detection), but
299
- construction-from-`origin/develop` is the primary defense.
300
-
301
- ### ⛔ HARD GATE — Worktree base MUST equal develop HEAD (blocking, not advisory)
302
- The worktree-isolation harness has shipped worktrees pinned to a STALE base
303
- commit (lessons 2026-06-10-build-worktree-stale-base, 2026-06-11-build-worktree-stale-base,
304
- 2026-06-15-build-worktree-stale-base, 2026-06-16-build-worktree-stale-base,
305
- 2026-06-17-build-worktree-stale-base, 2026-06-23-build-worktree-stale-base:
306
- agents branched hundreds of commits / multiple days behind develop HEAD, on a
307
- tree where the target app did not yet exist — their diffs would have silently
308
- reverted merged work or operated on a deleted structure). This is a recurring
309
- harness defect, so the check is a **HARD BLOCKING GATE, not a suggestion.**
310
-
311
- **Before dispatching ANY `isolation:"worktree"` wave**, the supervisor MUST run
312
- the base==HEAD assertion and MUST abort isolation on any mismatch — there is no
313
- "proceed anyway" path:
314
- ```bash
315
- DEV_HEAD=$(git rev-parse develop)
316
- # After worktrees are created, for each agent worktree:
317
- git worktree list # compare each agent worktree's SHA to $DEV_HEAD
318
- # If ANY worktree base != $DEV_HEAD (it is behind), the wave is UNSAFE — ABORT.
319
- ```
320
- - **MANDATORY ABORT:** if ANY worktree base != `$DEV_HEAD`, you MUST abort
321
- isolation for this wave. Do NOT merge stale worktree output. Do NOT "fast-forward
322
- and continue". Do NOT proceed with the isolated wave under any circumstance.
323
- Pivot to **sequential, non-isolated dispatch on a real `develop` checkout**
324
- (one disjoint WP at a time to avoid `.git/index` races; the supervisor pushes) —
325
- the same reason the validator runs non-isolated (it must see merged develop).
326
- - This gate is blocking by design: an isolated wave dispatched on a stale base
327
- is treated as a build failure, not a warning. Skipping or downgrading this
328
- assertion to advisory is a contract violation.
329
- - Also at every merge: `git show <branch>:<key-file> | grep -c <symbol-a-prior-wave-introduced>`
330
- — a 0 where there should be ≥1 means the branch is stale or deleted a shared
331
- export; resolve to `--ours` and re-apply that wave's real delta on current HEAD.
332
- esbuild/tsc PASS is necessary, not sufficient — pair it with a grep gate on
333
- the symbols a refactor must preserve.
334
-
335
- ### Forked agents vs. standalone agents
336
-
337
- **When the supervisor has already read the plan** (via a prior `Read` tool call in the same session),
338
- dispatch **forked agents** with short prompts. Forked agents inherit the full conversation context —
339
- including every file the supervisor has read — so you do NOT need to copy plan sections, file specs,
340
- or architecture details into the prompt. The agent already sees them.
341
-
342
- Short forked prompt template:
343
- ```
344
- You are a frontend agent building <WP name>. Work item: <uuid>.
345
- Scope: <one sentence>. Files: <list>. Verification: tsc --noEmit.
346
- Set item to review when done, return AGENT_COMPLETE with verification evidence.
347
- Read .rdc/guides/agent-bootstrap.md + .rdc/guides/engineering-behavior.md + .rdc/guides/frontend.md before starting.
348
- ```
349
-
350
- **When the supervisor has NOT read the plan** (e.g. dispatching from a fresh `rdc:build` call with
351
- only an epic ID), the agent has no plan context — write a full briefing prompt with all specs.
352
-
353
- ### ⛔ Reuse contract — when a WP builds on an existing subsystem
354
- When a work package extends an existing subsystem, "compose adapter + X"
355
- under-specifies reuse and lets an agent legitimately re-author markup/logic the
356
- subsystem already exposes (lesson 2026-06-11-build-reuse-existing-engine-prompt:
357
- an agent set up to reinvent a grid when the card engine already shipped four
358
- `CardLayout` display types + a full `parseCommand → CardSpec → adapter → CardModel[]`
359
- calling sequence). The dispatch prompt MUST:
360
- 1. **Enumerate the existing public API the agent must reuse, BY FILE** — types/enums
361
- (`packages/.../types.ts:NN`), calling-sequence functions, AND the existing
362
- display/render components — not just the data adapter.
363
- 2. **Mark which seams are extend/delegate-only.** State explicitly: "thread a
364
- pass-through prop (e.g. `layout`) to the existing components; do NOT
365
- reimplement layout/render." Verify at WP review that the agent reused the
366
- named parser/adapter/components and did not hand-roll a parallel implementation.
367
-
368
- ---
369
-
370
- ### Required agent prompt contents
371
- - Set work item to `in_progress` before dispatching
372
- - Each agent prompt MUST include:
373
- - `"Read {PROJECT_ROOT}/.rdc/guides/agent-bootstrap.md first (fallback: .rdc/guides/agent-bootstrap.md), then {PROJECT_ROOT}/.rdc/guides/<type>.md (fallback: .rdc/guides/<type>.md) before starting."`
374
- - `"Read {PROJECT_ROOT}/.rdc/guides/engineering-behavior.md (fallback: .rdc/guides/engineering-behavior.md) before editing; follow it for assumptions, minimal changes, surgical scope, evidence, and escalation."`
375
- - Specific files to create/modify (or omit if forked agent inherits plan context)
376
- - Exact deliverables and commit message
377
- - `"NEVER run pnpm build/test. NEVER modify files outside your scope."`
378
- - **`"You are running in an isolated git worktree. Commit your work normally. Do NOT push to origin — the supervisor merges your branch after the wave completes."`**
379
- - **`"When done, set your work item to 'review' (NOT 'done') and return AGENT_COMPLETE with a verification field. The validator closes work items — you do not."`**
380
- - **`"COMPLETION PROOF REQUIRED in AGENT_COMPLETE: list every file written, the exact commit hash, and paste the vitest/tsc output. A report without this evidence will be rejected."`**
381
- - **`"If you find that a file or feature already exists: you MUST still verify it satisfies the full task spec before marking review. Finding a file is not completion. Run verification, check every requirement, and report what you found vs. what was required."`**
382
- - **The decomposition items from the work item's checklist** (all `decomp-*` prefixed items). Include them verbatim in the prompt and instruct the agent:
383
- ```
384
- DECOMPOSITION CHECKLIST — you MUST implement/verify each row and tick it immediately via update_checklist_item(..., p_actor_session_id := '<your-session-id>', p_actor_role := 'agent'):
385
- - decomp-ui-xxx: <route/file> | action=<action> | expect=<result> | evidence=<artifact>
386
- - decomp-api-xxx: <route/file> | action=<action> | expect=<result> | evidence=<artifact>
387
- Tick each item as soon as that specific behavior is implemented and proven. Do NOT batch.
388
- ```
389
- - **The test plan items from the work item's checklist** (all `test-*` prefixed items). Include them verbatim in the prompt and instruct the agent:
390
- ```
391
- TEST PLAN — you MUST implement/verify each of these and tick them off via update_checklist_item(..., p_actor_session_id := '<your-session-id>', p_actor_role := 'agent'):
392
- - test-assert-xxx: <description> → write a vitest test that proves this
393
- - test-smoke-xxx: <description> → run the command and confirm the result
394
- - test-visual-xxx: <description> → note: delegate to UI audit (you cannot verify this yourself)
395
- - test-contract-xxx: <description> → verify the export/type/shape exists
396
- Tick each item as you complete it. Do NOT batch — tick immediately after each verification.
397
- ```
398
- - Use `run_in_background: true` for parallel execution
399
- - NEVER let agents overlap on the same files
400
-
401
- ### ⛔ Agent Definition-of-Done additions (include in every prompt)
402
- - **Declare every import in the package's OWN package.json.** Every import an
403
- agent adds MUST be present in that package's own `package.json`
404
- dependencies/devDependencies — never rely on monorepo-hoisted deps. A pnpm
405
- worktree can import a root-hoisted dep (e.g. `vitest`,
406
- `@supabase/supabase-js`) so `tsc`/`vitest` PASS in the worktree, then `tsc`
407
- FAILS on a clean develop checkout after merge (lesson
408
- 2026-06-10-build-card-engine-agent-deps). Agent prompt line: *"Verify that
409
- every import you add is declared in this package's own package.json — do not
410
- rely on hoisted monorepo deps."*
411
- - **A server/MCP/API task is NOT done without a committed automated test that
412
- ships in the SAME commit and exercises EVERY surface.** Manual curl / a single
413
- `/health` 200 is a proxy, not coverage (lesson 2026-06-10-build-weak-dod-no-tests).
414
- For a collection (MCP skills, API routes, CLI commands): loop over ALL items
415
- and assert `output == source` — never a single spot check. Wire an npm script
416
- and run it green before the item leaves `review`. Agent prompt line: *"This
417
- task is not done until a committed test in the same commit exercises every
418
- surface; for collections, loop all items and assert output == source."*
419
-
420
- 8. **Post-wave test gate (mandatory):**
421
- After all agents in a wave complete, before proceeding:
422
- ```bash
423
- # For each package modified in this wave:
424
- cd packages/<name> && npx vitest run 2>&1 | tail -20
425
- ```
426
- - All tests must pass before proceeding to next wave
427
- - If tests fail: fix before proceeding
428
- - NEVER use `pnpm build` or `pnpm turbo test` — vitest only per package
429
- - New code must have tests: if a modified package shows 0 new test files, flag it
430
-
431
- 9. **After all wave agents complete — merge worktrees and push:**
432
-
433
- Each completed agent returns a worktree branch (e.g. `claude/agent-frontend-abc123`). Merge them all to develop before running the test gate:
434
-
435
- ```bash
436
- # For each worktree branch returned by agents in this wave:
437
- git merge --no-ff <worktree-branch> -m "merge(<agent-type>): <task-title>"
438
- ```
439
-
440
- - Resolve any conflicts before proceeding — do not skip
441
- - Worker agents set items to `review` — **do NOT close to `done` yet**
442
- - After all branches merged, push once:
443
- ```bash
444
- if [ "$RDC_TEST" != "1" ]; then
445
- git push origin develop
446
- else
447
- echo "[RDC_TEST] skipping git push"
448
- fi
449
- ```
450
- - Then run the post-wave test gate (Step 8) on the merged state
451
- - Then run the code-review gate (Step 9b) before the next wave dispatches
452
- - Continue to next wave
453
-
454
- **If an agent fails (returns no worktree branch):**
455
- - Interactive: diagnose before retrying
456
- - Unattended: retry once; on second failure escalate via advisor
457
- ```
458
- BUILD_STATUS: { wave, tasks_done, tasks_failed, commits, escalated: true }
459
- ```
460
-
461
- 9b. **Mandatory per-wave code-review gate (runs after merge + test gate, BEFORE next wave dispatches):**
462
-
463
- ⛔ **NO wave may dispatch until the previous wave's code-review pass clears.** Memory `feedback_code_review_per_wave.md` — Davesend 2026-05-24 incident.
464
-
465
- Dispatch ONE `pr-review-toolkit:code-reviewer` agent with the wave's merged diff:
466
-
467
- ```
468
- Agent({
469
- subagent_type: "pr-review-toolkit:code-reviewer",
470
- description: "Wave <N> code review",
471
- prompt: "Review the diff `git diff <wave-base-sha>..HEAD` on develop.
472
- Focus on: bugs, logic errors, security vulnerabilities, project-convention adherence
473
- (.claude/rules/*, CLAUDE.md). Apply confidence-based filtering — high-confidence
474
- findings only. Report severity per finding: critical | high | medium | low.
475
- Return CODE_REVIEW_COMPLETE with: { critical_count, high_count, medium_count,
476
- low_count, findings: [{severity, file:line, issue, suggested_fix}] }."
477
- })
478
- ```
479
-
480
- **Severity gate (default — high+ blocks):**
481
- - `critical` or `high` findings → reopen affected work items to `todo` with finding text in notes; fix in a new wave before continuing
482
- - `medium` or `low` findings → append to each work item's `implementation_report.flags`; do NOT reopen; validator sees them
483
- - Zero findings → log `CODE_REVIEW: CLEAN` and proceed to next wave
484
-
485
- Under `RDC_TEST=1`: echo `[RDC_TEST] skipping code-review dispatch` and proceed.
486
-
487
- 10. **Mandatory validator gate (runs after ALL waves complete — before any work item closes):**
488
-
489
- ⛔ **NO work item may be set to `done` without the validator passing it.**
490
-
491
- Dispatch ONE validator agent with the complete list of `review` work items and the full git diff.
492
- ⚠️ The validator does NOT use `isolation: "worktree"` — it must read the fully merged develop branch. Omit the isolation parameter for this dispatch only.
493
-
494
- ```
495
- "Read {PROJECT_ROOT}/.rdc/guides/agent-bootstrap.md then {PROJECT_ROOT}/.rdc/guides/verify.md.
496
- Read {PROJECT_ROOT}/.rdc/guides/engineering-behavior.md before validating scope, deviations, and evidence.
497
- Validate these work items: [list of IDs and titles].
498
- Apps touched: [list].
499
- Git diff since build start: [attach or reference].
500
- You are the ONLY agent that closes work items to done.
501
- Follow verify.md procedure exactly: tsc → vitest → dev server route probes → record result per item."
502
- ```
503
-
504
- The validator:
505
- - Runs `npx tsc --noEmit` for every touched app/package
506
- - Starts the dev server and probes every modified route (expects HTTP 200, not 500)
507
- - Runs vitest for every touched package
508
- - **Verifies checklist decomposition quality per work item before functional validation:**
509
- - Every implementation work item has at least one `decomp-*` item and one `test-*` item
510
- - Every `decomp-*` item includes route/file, action, expected result, and evidence artifact
511
- - Any unchecked `decomp-*` item with `required: true` = work item CANNOT be set to `done`
512
- - Any coarse or non-falsifiable `decomp-*` item = reopen to `todo` with the specific failure
513
- - **Verifies test plan completion per work item:**
514
- - For each `test-assert-*` checklist item: confirm a corresponding vitest test exists and passes
515
- - For each `test-smoke-*` checklist item: run the command and confirm exit code / HTTP status
516
- - For each `test-visual-*` checklist item: note as "delegated to UI audit" (validator cannot verify visuals)
517
- - For each `test-contract-*` checklist item: verify the export/type/shape exists in the built code
518
- - Any unchecked `test-*` item with `required: true` = work item CANNOT be set to `done` (DB enforces this)
519
- - Sets passing items to `done`, failing items back to `todo` with failure detail
520
- - Returns `VALIDATOR_COMPLETE` report with test plan status per item
521
-
522
- **If the validator finds failures:** fix them in a new wave, then re-run the validator. Do not skip.
523
- **File existence alone is NOT verification.** A route returning 500 is a failure regardless of tsc passing.
524
- **Unchecked test plan items are a hard gate** — `update_work_item_status('done', ..., p_actor_role := 'validator')` will raise an exception if any `required: true` checklist item is unchecked, missing agent-session tick evidence, or re-ticked by a supervisor/validator.
525
-
526
- 11. **After verification passes:**
527
- - All wave commits are already on develop and pushed (Step 9 pushes after each wave merge).
528
- - Update epic version: `bump_epic_version()`
529
- - Report summary with verification evidence quoted
530
-
531
- ## Agent TDD Requirements
532
-
533
- When dispatching agents, include in every prompt:
534
- ```
535
- TDD REQUIREMENT: Write tests FIRST for new functions/modules.
536
- Run: npx vitest run packages/<name> to verify red → implement → verify green.
537
- NEVER run pnpm build or pnpm turbo. Use npx vitest run only.
538
- ```
539
-
540
- ## Rules
541
- - Branch: development branch only (auto-commit, no confirmation needed)
542
- - NEVER let two agents edit the same file
543
- - NEVER run `pnpm build` (crashes system) — code only
544
- - Every agent reads its guide file — no exceptions
545
- - Update Supabase work items IN REAL TIME — not batch at end
546
- - Push after each wave, not just at the end
547
- - Unattended: NEVER pause — continue automatically
548
- - Unattended: max 2 retries per task before escalating to advisor
549
- - Every Agent() dispatch: `model: <routed>` + `max_turns: 70` — non-negotiable. `isolation` is per the dispatch-mode rule in Step 7: NON-isolated (omit `isolation`) for doc-only and single-committer waves; `isolation: "worktree"` ONLY for true parallel MULTI-committer waves, and only after the HARD GATE (worktree base == develop HEAD) passes — a stale-base isolated wave is a build failure. Model is chosen per task per the routing table in Step 7: Sonnet 4.6 for updates/edits, Opus 4.6 for harder coding, Opus 4.8 for design/innovative thought (CS 2.0, brand/UX, architecture). Supervisor logs `model=<chosen> reason=<phrase>` per agent. Exception: validator agent in Step 10 always omits isolation; validator model stays `claude-sonnet-4-6` (verification, not generation).
550
- - Finding an existing file is NOT task completion — verify it satisfies the spec
551
-
552
- ## Capture lessons (exit step)
553
-
554
- Before the final verdict line, follow `.rdc/guides/lessons-learned-spec.md` § Capture procedure. If this run taught something non-obvious — a first root-cause theory that turned out wrong, the documented/standard path not working, a missing gate or check that cost a round, or a surprising tool/infra behavior — write one `.rdc/lessons/<YYYY-MM-DD>-build-<short-slug>.md` per lesson using the schema in that spec. Set `scope` (`simple` | `architectural`) and `status` (`open`, or `applied` if you shipped the fix in this same run, with the commit linked). Commit the lesson file(s) on `develop` alongside the run's other commits, and note "N lessons captured" in your verdict/summary. A run that taught nothing writes nothing — absence is the default.
1
+ ---
2
+ name: rdc:build
3
+ description: "Usage `rdc:build <epic-id>` — You have a planned epic with tasks ready to execute. Dispatches parallel typed agents, each commits atomically to develop, runs a mandatory per-wave code-review gate (pr-review-toolkit:code-reviewer), closes work items, and runs the validator gate. Call after rdc:plan or when told to build."
4
+ ---
5
+
6
+ > **⚠️ OUTPUT CONTRACT (READ FIRST):** `guides/output-contract.md`
7
+ > Checklist-only output. No tool-call narration. No raw MCP/JSON/log dumps.
8
+ > One checklist upfront, updated in place, shown again at end with a 1-line verdict.
9
+
10
+ > **Sandbox contract:** This skill honors `RDC_TEST=1` per `guides/agent-bootstrap.md` § RDC_TEST Sandbox Contract. Destructive external calls short-circuit under the flag.
11
+
12
+
13
+ # rdc:build — Typed Agent Dispatch Engine
14
+
15
+ ## When to Use
16
+ - Plan is approved and ready to execute
17
+ - Project lead says "build it", "go", "execute", "do not stop"
18
+ - An epic exists with child tasks ready for implementation
19
+ - Called by `rdc:overnight` as part of the automated build loop
20
+
21
+ ## Arguments
22
+ - `rdc:build <epic-id>` — build from a specific Supabase epic
23
+ - `rdc:build <topic>` — find the epic by label/title match
24
+ - `rdc:build` (no args) — show open epics and ask which to build (interactive only)
25
+ - `rdc:build <epic-id> --unattended` — silent mode for overnight builds
26
+
27
+ ## Agent Types & Guide Files
28
+
29
+ Every dispatched agent MUST read two files before starting — in this order:
30
+ 1. `{PROJECT_ROOT}/.rdc/guides/agent-bootstrap.md` — credentials, git rules, completion report format
31
+ (fallback: `.rdc/guides/agent-bootstrap.md` relative to cwd if `{PROJECT_ROOT}` is not substituted)
32
+ 2. `{PROJECT_ROOT}/.rdc/guides/engineering-behavior.md` — assumptions, minimal changes, surgical scope, verification evidence
33
+ (fallback: `.rdc/guides/engineering-behavior.md` relative to cwd if `{PROJECT_ROOT}` is not substituted)
34
+ 3. `{PROJECT_ROOT}/.rdc/guides/<type>.md` — role-specific guide
35
+ (fallback: `.rdc/guides/<type>.md` relative to cwd if `{PROJECT_ROOT}` is not substituted)
36
+
37
+ Include both lines in every agent prompt:
38
+ ```
39
+ "Read {PROJECT_ROOT}/.rdc/guides/agent-bootstrap.md first (fallback: .rdc/guides/agent-bootstrap.md), then {PROJECT_ROOT}/.rdc/guides/engineering-behavior.md (fallback: .rdc/guides/engineering-behavior.md), then {PROJECT_ROOT}/.rdc/guides/<type>.md (fallback: .rdc/guides/<type>.md) before starting."
40
+ ```
41
+
42
+ | Agent Type | Guide File | When to dispatch |
43
+ |-----------|-----------|-----------------|
44
+ | `frontend` | `.rdc/guides/frontend.md` | React components, pages, UI, Tailwind, animation |
45
+ | `backend` | `.rdc/guides/backend.md` | API routes, server components, database queries, auth |
46
+ | `data` | `.rdc/guides/data.md` | Migrations, schema changes, RPC functions |
47
+ | `design` | `.rdc/guides/design.md` | Visual design, brand palettes, OG images, token work |
48
+ | `infra` | `.rdc/guides/infrastructure.md` | CI/CD, deployment, DNS, SSL |
49
+ | `content` | `.rdc/guides/content.md` | Marketing copy, messaging, tone |
50
+ | `cs2` | `.rdc/guides/cs2.md` | CS 2.0 paradigm work (generic) |
51
+ | `hail` | `.rdc/guides/cs2.md` + `packages/hail/CLAUDE.md` | Grammar, DSL compiler, evolution |
52
+ | `pal` | `.rdc/guides/cs2.md` + `packages/pal/CLAUDE.md` | Sessions, moment windows, graph memory |
53
+ | `bpmn` | `.rdc/guides/cs2.md` + `docs/systems/<domain>/flowable-bpmn-architecture.md` | BPMN flows, governance |
54
+ | `virtue` | `.rdc/guides/cs2.md` + `packages/virtue-engine/CLAUDE.md` | Virtue weights, coherence, certification |
55
+ | `viz` | `.rdc/guides/frontend.md` + `.rdc/guides/design.md` | Custom viz components, charts, diagrams |
56
+
57
+ ### How to classify a task → agent type
58
+
59
+ Read the task title and description, then:
60
+ - Mentions React, component, page, UI, Tailwind → `frontend`
61
+ - Mentions API route, server, database query, auth → `backend`
62
+ - Mentions migration, schema, table, RPC → `data`
63
+ - Mentions brand, palette, typography, OG image → `design`
64
+ - Mentions deploy, infrastructure, CI, DNS → `infra`
65
+ - Mentions copy, messaging, email template → `content`
66
+ - Mentions grammar, DSL, compiler → `hail`
67
+ - Mentions session, moment, memory graph → `pal`
68
+ - Mentions BPMN, flow, governance → `bpmn`
69
+ - Mentions virtue, coherence, certification → `virtue`
70
+ - Mentions visualization, chart, diagram, SVG → `viz`
71
+ - Multiple types? Dispatch multiple agents, each with its guide.
72
+
73
+ ## Procedure
74
+
75
+ 1. **Load the epic and run pre-flight gate:**
76
+ ```sql
77
+ SELECT get_work_items_by_epic('<epic-id>', 'todo');
78
+ ```
79
+
80
+ **Session lock — claim the epic immediately (before any agent dispatch):**
81
+
82
+ After loading the epic, check its status:
83
+ - If `status = 'in_progress'` → **ABORT** with:
84
+ ```
85
+ SKIP: epic <id> is already in_progress — claimed by another session. Pick a different epic.
86
+ ```
87
+ Do NOT proceed. Do NOT dispatch any agents.
88
+ - If `status = 'todo'` or `status = 'blocked'` → immediately claim it:
89
+ ```sql
90
+ SELECT update_work_item_status('<epic-id>'::uuid, 'in_progress',
91
+ '["Claimed by build session — dispatching agents"]'::jsonb
92
+ );
93
+ ```
94
+ This is an atomic Supabase write. A concurrent session that loads the same epic after this point will see `in_progress` and abort. **Do this before any classification, planning, or agent dispatch.**
95
+
96
+ **Pre-flight gate — run after claiming:**
97
+
98
+ | Condition | Action |
99
+ |-----------|--------|
100
+ | No child tasks returned | → Invoke `rdc:plan` on this epic. Do NOT proceed with build. |
101
+ | Tasks exist but all have empty `description` fields | → Invoke `rdc:plan` on this epic. Tasks without descriptions cannot be safely dispatched. |
102
+ | Plan doc missing `## Checklist Decomposition Matrix` | → Invoke `rdc:plan` on this epic. Do NOT dispatch agents. |
103
+ | Plan doc missing `## Checklist Quality Gate` with `verdict: PASS` | → Invoke `rdc:plan` on this epic. Do NOT dispatch agents. |
104
+ | Any implementation task lacks `decomp-*` checklist items | → Invoke `rdc:plan` on this epic. Coarse checklists cannot be safely dispatched. |
105
+ | Any `decomp-*` item lacks route/file, action, expected result, or evidence artifact | → Invoke `rdc:plan` on this epic. Do NOT dispatch agents. |
106
+ | Tasks exist and have descriptions | → Continue with build. |
107
+
108
+ **Re-planning is not a failure — it is correct behavior.** The build skill is the last gate before agent dispatch; catching an under-specified epic here is cheaper than a wasted agent run.
109
+
110
+ **How to re-plan:**
111
+ - Interactive: tell the user — "Epic has no tasks / tasks lack descriptions — invoking rdc:plan first." Then invoke `rdc:plan <epic-id>`.
112
+ - Unattended: invoke `rdc:plan <epic-id> --unattended` inline, wait for it to complete, then reload tasks and re-run this gate once. If tasks still missing after re-plan, escalate via advisor.
113
+
114
+ **Interactive (no args):** show open epics, ask which to build.
115
+
116
+ 2. **CHECK FOR EXISTING WORK (mandatory — never skip):**
117
+ ```sql
118
+ -- Check if prototypes exist from earlier sessions
119
+ SELECT name, component, source_path, status, notes
120
+ FROM prototype_registry
121
+ WHERE status IN ('prototype', 'converting')
122
+ ORDER BY created_at DESC;
123
+
124
+ -- Check for design decisions on this topic
125
+ SELECT topic, context_type, summary, source
126
+ FROM design_context
127
+ WHERE topic ILIKE '%<epic-topic>%'
128
+ ORDER BY created_at DESC;
129
+ ```
130
+ **If a prototype exists: ADAPT IT. Do not build from scratch.**
131
+ Tell the agent: "Read <source_path> first and convert it to the production contract."
132
+
133
+ **If design decisions exist: follow them.** Include the summary in the agent prompt.
134
+
135
+ 3. **Load the plan** (mandatory): check `.rdc/plans/` for matching topic (fallback: `.rdc/plans/`).
136
+
137
+ 3b. **Checklist decomposition quality gate (mandatory before code):**
138
+
139
+ `rdc:build` is the final gate before implementation. It MUST reject any plan or work item that is too coarse for an agent to execute and verify independently.
140
+
141
+ Required plan sections:
142
+ - `## Checklist Decomposition Matrix`
143
+ - `## Checklist Quality Gate`
144
+ - `verdict: PASS`
145
+
146
+ Required task checklist shape:
147
+ - Every implementation work item has at least one `decomp-*` checklist row and one `test-*` checklist row.
148
+ - Every `decomp-*` row names a concrete route or file path.
149
+ - Every `decomp-*` row names one user/agent action.
150
+ - Every `decomp-*` row names one expected UI/API/DB result.
151
+ - Every `decomp-*` row names one verification artifact: test name, route probe, Playwright screenshot, SQL query, API response, type-check, migration proof, or CLI transcript.
152
+
153
+ Atomicity rubric:
154
+ - One observable behavior per `decomp-*` row.
155
+ - The row can pass or fail without reading hidden intent from the plan narrative.
156
+ - The row is small enough for a worker to implement, tick, and cite evidence for directly.
157
+ - Vague rows such as "theme management works", "UI implemented", "verified", "all screens", or "integration complete" are failures.
158
+
159
+ Minimum decomposition heuristics:
160
+ - UI route: at least empty/loading/loaded/error or the documented reason a state does not apply.
161
+ - CRUD surface: at least list, create, edit, detail, duplicate/delete/archive where applicable, and validation failure.
162
+ - API route: at least successful read/write, validation failure, and unauthorized/forbidden or documented auth bypass.
163
+ - DB/migration task: at least schema object, relationship/guard, policy/permission, seed/fixture or backfill, and smoke query.
164
+ - Editor/sidebar/CLI workflow: at least start, attach/open, enqueue action, observe result, timeout/error, and live refresh where applicable.
165
+
166
+ ### ⛔ Deliverable / acceptance check-off table — show BEFORE any implementation
167
+ Before dispatching the first wave, render a deliverable/acceptance table and
168
+ keep it visible through the build (lesson 2026-06-16-build-poor-goal-execution-mdk-brain:
169
+ a build satisfied generic checklist rows — tsc clean, route 200 — while never
170
+ touching the surface the user actually named, because no row anchored the
171
+ user's TARGET SURFACE). The table MUST contain:
172
+ - **One mandatory row for the user-named TARGET SURFACE** — the exact screen,
173
+ endpoint, file, or behavior the user asked for, by name. Its acceptance check
174
+ is what proves THAT surface renders/works, not a proxy.
175
+ - **At least one NEGATIVE verifier row** — a check that proves the WRONG thing
176
+ does NOT happen (e.g. "mock data is NOT rendered", "old route returns 404",
177
+ "stub component is absent from the bundle"). A positive-only suite passes
178
+ even when the deliverable is wired to the wrong source.
179
+
180
+ | Deliverable | Target surface? | Acceptance check | Negative verifier | Status |
181
+ |---|---|---|---|---|
182
+
183
+ **Gating rule:** any work item whose deliverable maps to the TARGET SURFACE row
184
+ stays in `review` (never `done`) until that target-surface acceptance check
185
+ passes. Generic gates (tsc, route 200) clearing is NOT sufficient to advance
186
+ the target-surface item.
187
+
188
+ If the gate fails:
189
+ - Interactive: show the failing rows and invoke `rdc:plan <epic-id>` to repair the matrix before dispatch.
190
+ - Unattended: invoke `rdc:plan <epic-id> --unattended`, reload tasks, and run this gate once more.
191
+ - If the second gate fails, abort the build and return the failure list. Do not dispatch implementation agents.
192
+
193
+ **Plan verifier escalation:** A separate verifier agent is optional, not default. Dispatch one only when the plan touches 5+ UI routes, 3+ data/API boundaries, auth/security, production deployment, or when this rubric fails twice. The verifier reads the plan and work-item checklists only; it does not write code.
194
+
195
+ 4. **Read CLAUDE.md files** for all affected packages.
196
+
197
+ 5. **Classify each task** → assign agent type from the table above.
198
+
199
+ 5b. **Write or refresh the checklist into every work item before dispatching:**
200
+ For each task, append the exact `decomp-*` and `test-*` checklist rows to its notes BEFORE setting to `in_progress`:
201
+ ```sql
202
+ SELECT update_work_item_status('<id>'::uuid, 'in_progress',
203
+ '["CHECKLIST: [ ] decomp-ui-route-state: <route/file> | action=<action> | expect=<result> | evidence=<artifact>, [ ] test-smoke-route: <route probe>, [ ] committed"]'::jsonb
204
+ );
205
+ ```
206
+ The agent must complete every item on this checklist and return it checked off in AGENT_COMPLETE.
207
+ A checklist with unchecked items = incomplete work. Do not proceed to next wave with unchecked items.
208
+
209
+ 6. **Group tasks into waves** — parallelize tasks with no file overlap:
210
+ - Wave 1: independent tasks (different packages/files)
211
+ - Wave 2: tasks that depend on Wave 1 outputs
212
+ - Wave 3: integration tasks
213
+
214
+ 7. **For each wave — dispatch typed agents in parallel:**
215
+
216
+ ### ⛔ Agent Dispatch Non-Negotiable Defaults
217
+ Every `Agent()` call MUST include these parameters:
218
+ ```
219
+ model: <chosen per the routing table below>
220
+ max_turns: 70
221
+ ```
222
+ `isolation` is chosen per the dispatch-mode rule below — it is NOT a blanket
223
+ default. Worktree isolation is reserved for true parallel MULTI-committer waves
224
+ in the same repo; doc-only and single-committer waves default to NON-isolated.
225
+
226
+ ### ⛔ Dispatch mode — non-isolated is the default for single-committer / doc-only waves
227
+ Worktree isolation exists to protect a SHARED working tree from a git-index race
228
+ between MULTIPLE agents committing in parallel. When there is only ONE committer,
229
+ that race cannot occur, and the stale-base hazard of worktrees (see the HARD GATE
230
+ below — recurring across 2026-06-10/11/15/16/17/23) is pure downside. Pick the
231
+ dispatch mode by committer count, not by reflex:
232
+
233
+ | Wave shape | Dispatch mode | isolation |
234
+ |---|---|---|
235
+ | **Doc-only wave** (markdown/docs/plans, no code build) | NON-isolated, one committer on `develop` | omit `isolation` |
236
+ | **Single-committer wave** (only one agent commits, or work serializes to the supervisor) | NON-isolated, one committer on `develop` | omit `isolation` |
237
+ | **True parallel MULTI-committer wave** (2+ agents committing concurrently in the same repo, disjoint files) | worktree-isolated, supervisor merges | `isolation: "worktree"` |
238
+
239
+ - **Default = NON-isolated.** Only escalate to `isolation: "worktree"` when the
240
+ wave genuinely has 2+ concurrent committers in the same repo.
241
+ - A pure docs wave is single-committer by default: either dispatch ONE doc agent,
242
+ or have parallel doc agents return diffs/patches that the supervisor commits
243
+ serially. Do NOT fan out 2+ concurrent committers onto one shared `develop`
244
+ tree (lesson 2026-06-13-build-concurrent-agents-same-branch-git-race: three
245
+ parallel doc agents on one `develop` tree raced on the git index/stash — one
246
+ commit swept in another agent's staged-but-uncommitted files under the wrong
247
+ message, two agents reported the SAME SHA, a pre-commit `sync:docs` ref-lock
248
+ race misattributed authorship). The fix for that race is single-committer
249
+ serialization, NOT blanket worktree isolation.
250
+ - When you DO need a true MULTI-committer parallel wave, worktree isolation is
251
+ mandatory AND the HARD GATE below (base == develop HEAD) MUST pass before
252
+ dispatch — a stale-base worktree wave is a build failure, not a warning.
253
+
254
+ ### ⛔ Foreign concurrent session guard — `git status` BEFORE the build
255
+ Worktree isolation protects against THIS build's own agents, not against a
256
+ DIFFERENT session (another cell, a Codex run, a human) already committing on
257
+ the same shared tree (lesson 2026-06-16-build-concurrent-session-shared-tree-commit-corruption:
258
+ a foreign session's staged-but-uncommitted files were swept into this build's
259
+ commit under the wrong message). Before dispatching any wave, run `git status`
260
+ to detect foreign-dirty files you did not create. If foreign-dirty files are
261
+ present: do NOT fan out concurrent committers — **serialize ALL committers to
262
+ the supervisor** (agents return diffs/patches; the supervisor stages and
263
+ commits each one alone). After every supervisor commit, assert the exact file
264
+ set landed and nothing foreign leaked in:
265
+ ```bash
266
+ git show --stat <sha> # confirm ONLY the files this commit owns are listed
267
+ ```
268
+ A `git show --stat` that lists a file the agent did not touch = a foreign file
269
+ leaked into the commit; reset and re-stage by explicit path.
270
+
271
+ **Agent model routing — pick per task, not per wave.** The supervisor session model does NOT cascade to agents; you must set `model` explicitly on every dispatch.
272
+
273
+ | Task character | Model | When to pick it |
274
+ |---|---|---|
275
+ | Updates, edits, mechanical refactors, small fixes, content tweaks, config patches, doc/copy edits, straightforward API wiring | `claude-sonnet-4-6` | Default for `frontend.md`/`content.md`/`infrastructure.md` work whose checklist is mostly "change X to Y" or "wire up endpoint Z". Budget-safe for parallel dispatch. |
276
+ | Harder coding tasks — non-trivial algorithm, migration with backfill, schema reshape, multi-file refactor with subtle invariants, performance-sensitive code, anything where correctness is the bar | `claude-opus-4-6` | Default for `backend.md`/`data.md` work and any `frontend.md` task that involves state machines, race conditions, or cross-package contracts. |
277
+ | Design or innovative thought — new component design, brand/UX work, CS 2.0 paradigm work (HAIL/Quad Pixel/AEMG/Virtue), grammar evolution, architecture-first design, anything where the *shape* of the solution is the deliverable rather than the implementation | `claude-opus-4-8` | Default for `design.md`/`cs2.md` work. Also use for `backend.md`/`data.md` tasks tagged with `architecture` or `design-decision` in work item labels. |
278
+
279
+ **How to choose when the task straddles categories:**
280
+ - If the task's checklist contains the word "design", "decide", "propose", "evaluate alternatives", "novel", or any CS 2.0 primitive → **Opus 4.8**.
281
+ - If the task touches `packages/cs2*`, `packages/hail`, `packages/quad-pixel`, `packages/virtue-engine`, `packages/aemg`, `packages/planetary-ontology`, or `packages/being-state-processor` → **Opus 4.8** (CS 2.0 paradigm requires innovative thought, not transcription).
282
+ - If the task is a Supabase migration that drops/renames/reshapes anything, or a refactor across ≥5 files → **Opus 4.6**.
283
+ - Otherwise → **Sonnet 4.6**.
284
+
285
+ **State the choice in the wave plan.** Before dispatching a wave, the supervisor must log one line per agent in the form `[wave-N agent-K] role=<role> task=<id> model=<chosen> reason=<one phrase>`. This keeps routing decisions reviewable in the transcript and lets `rdc:report` summarize the fleet mix.
286
+
287
+ **Cost guardrail.** If a single wave would dispatch more than 3 Opus 4.8 agents in parallel, downshift the lowest-priority Opus-4.8 tasks to Opus 4.6 unless their work items are tagged `priority=urgent`. Opus 4.8 fast-mode is cheap individually but still ~5× a Sonnet agent at scale.
288
+ Without `max_turns: 70`, agents hit the default turn cap mid-task and stop.
289
+ `isolation: "worktree"` gives each agent its own git worktree and branch — eliminates push race conditions and index lock contention when multiple agents commit in parallel. The supervisor merges worktree branches after each wave (Step 9).
290
+
291
+ ### ✅ PREVENTION FIRST — create worktrees fresh off origin/develop (kills stale-base by construction)
292
+ The repeated stale-base failures below come from creating worktrees off a
293
+ local/old ref. Eliminate the failure mode at the source: ALWAYS create agent
294
+ worktrees with a fresh fetch + `origin/develop` base, e.g.
295
+ `git fetch origin develop && git worktree add <dir> -b <branch> origin/develop`
296
+ — or use the canonical launcher `node scripts/wt.mjs add <name>`, which does
297
+ exactly that. A worktree cut from `origin/develop` HEAD **cannot** be stale.
298
+ The HARD GATE below remains as the blocking backstop (detection), but
299
+ construction-from-`origin/develop` is the primary defense.
300
+
301
+ ### ⛔ HARD GATE — Worktree base MUST equal develop HEAD (blocking, not advisory)
302
+ The worktree-isolation harness has shipped worktrees pinned to a STALE base
303
+ commit (lessons 2026-06-10-build-worktree-stale-base, 2026-06-11-build-worktree-stale-base,
304
+ 2026-06-15-build-worktree-stale-base, 2026-06-16-build-worktree-stale-base,
305
+ 2026-06-17-build-worktree-stale-base, 2026-06-23-build-worktree-stale-base:
306
+ agents branched hundreds of commits / multiple days behind develop HEAD, on a
307
+ tree where the target app did not yet exist — their diffs would have silently
308
+ reverted merged work or operated on a deleted structure). This is a recurring
309
+ harness defect, so the check is a **HARD BLOCKING GATE, not a suggestion.**
310
+
311
+ **Before dispatching ANY `isolation:"worktree"` wave**, the supervisor MUST run
312
+ the base==HEAD assertion and MUST abort isolation on any mismatch — there is no
313
+ "proceed anyway" path:
314
+ ```bash
315
+ DEV_HEAD=$(git rev-parse develop)
316
+ # After worktrees are created, for each agent worktree:
317
+ git worktree list # compare each agent worktree's SHA to $DEV_HEAD
318
+ # If ANY worktree base != $DEV_HEAD (it is behind), the wave is UNSAFE — ABORT.
319
+ ```
320
+ - **MANDATORY ABORT:** if ANY worktree base != `$DEV_HEAD`, you MUST abort
321
+ isolation for this wave. Do NOT merge stale worktree output. Do NOT "fast-forward
322
+ and continue". Do NOT proceed with the isolated wave under any circumstance.
323
+ Pivot to **sequential, non-isolated dispatch on a real `develop` checkout**
324
+ (one disjoint WP at a time to avoid `.git/index` races; the supervisor pushes) —
325
+ the same reason the validator runs non-isolated (it must see merged develop).
326
+ - This gate is blocking by design: an isolated wave dispatched on a stale base
327
+ is treated as a build failure, not a warning. Skipping or downgrading this
328
+ assertion to advisory is a contract violation.
329
+ - Also at every merge: `git show <branch>:<key-file> | grep -c <symbol-a-prior-wave-introduced>`
330
+ — a 0 where there should be ≥1 means the branch is stale or deleted a shared
331
+ export; resolve to `--ours` and re-apply that wave's real delta on current HEAD.
332
+ esbuild/tsc PASS is necessary, not sufficient — pair it with a grep gate on
333
+ the symbols a refactor must preserve.
334
+
335
+ ### Forked agents vs. standalone agents
336
+
337
+ **When the supervisor has already read the plan** (via a prior `Read` tool call in the same session),
338
+ dispatch **forked agents** with short prompts. Forked agents inherit the full conversation context —
339
+ including every file the supervisor has read — so you do NOT need to copy plan sections, file specs,
340
+ or architecture details into the prompt. The agent already sees them.
341
+
342
+ Short forked prompt template:
343
+ ```
344
+ You are a frontend agent building <WP name>. Work item: <uuid>.
345
+ Scope: <one sentence>. Files: <list>. Verification: tsc --noEmit.
346
+ Set item to review when done, return AGENT_COMPLETE with verification evidence.
347
+ Read .rdc/guides/agent-bootstrap.md + .rdc/guides/engineering-behavior.md + .rdc/guides/frontend.md before starting.
348
+ ```
349
+
350
+ **When the supervisor has NOT read the plan** (e.g. dispatching from a fresh `rdc:build` call with
351
+ only an epic ID), the agent has no plan context — write a full briefing prompt with all specs.
352
+
353
+ ### ⛔ Reuse contract — when a WP builds on an existing subsystem
354
+ When a work package extends an existing subsystem, "compose adapter + X"
355
+ under-specifies reuse and lets an agent legitimately re-author markup/logic the
356
+ subsystem already exposes (lesson 2026-06-11-build-reuse-existing-engine-prompt:
357
+ an agent set up to reinvent a grid when the card engine already shipped four
358
+ `CardLayout` display types + a full `parseCommand → CardSpec → adapter → CardModel[]`
359
+ calling sequence). The dispatch prompt MUST:
360
+ 1. **Enumerate the existing public API the agent must reuse, BY FILE** — types/enums
361
+ (`packages/.../types.ts:NN`), calling-sequence functions, AND the existing
362
+ display/render components — not just the data adapter.
363
+ 2. **Mark which seams are extend/delegate-only.** State explicitly: "thread a
364
+ pass-through prop (e.g. `layout`) to the existing components; do NOT
365
+ reimplement layout/render." Verify at WP review that the agent reused the
366
+ named parser/adapter/components and did not hand-roll a parallel implementation.
367
+
368
+ ---
369
+
370
+ ### Required agent prompt contents
371
+ - Set work item to `in_progress` before dispatching
372
+ - Each agent prompt MUST include:
373
+ - `"Read {PROJECT_ROOT}/.rdc/guides/agent-bootstrap.md first (fallback: .rdc/guides/agent-bootstrap.md), then {PROJECT_ROOT}/.rdc/guides/<type>.md (fallback: .rdc/guides/<type>.md) before starting."`
374
+ - `"Read {PROJECT_ROOT}/.rdc/guides/engineering-behavior.md (fallback: .rdc/guides/engineering-behavior.md) before editing; follow it for assumptions, minimal changes, surgical scope, evidence, and escalation."`
375
+ - Specific files to create/modify (or omit if forked agent inherits plan context)
376
+ - Exact deliverables and commit message
377
+ - `"NEVER run pnpm build/test. NEVER modify files outside your scope."`
378
+ - **`"You are running in an isolated git worktree. Commit your work normally. Do NOT push to origin — the supervisor merges your branch after the wave completes."`**
379
+ - **`"When done, set your work item to 'review' (NOT 'done') and return AGENT_COMPLETE with a verification field. The validator closes work items — you do not."`**
380
+ - **`"COMPLETION PROOF REQUIRED in AGENT_COMPLETE: list every file written, the exact commit hash, and paste the vitest/tsc output. A report without this evidence will be rejected."`**
381
+ - **`"If you find that a file or feature already exists: you MUST still verify it satisfies the full task spec before marking review. Finding a file is not completion. Run verification, check every requirement, and report what you found vs. what was required."`**
382
+ - **The decomposition items from the work item's checklist** (all `decomp-*` prefixed items). Include them verbatim in the prompt and instruct the agent:
383
+ ```
384
+ DECOMPOSITION CHECKLIST — you MUST implement/verify each row and tick it immediately via update_checklist_item(..., p_actor_session_id := '<your-session-id>', p_actor_role := 'agent'):
385
+ - decomp-ui-xxx: <route/file> | action=<action> | expect=<result> | evidence=<artifact>
386
+ - decomp-api-xxx: <route/file> | action=<action> | expect=<result> | evidence=<artifact>
387
+ Tick each item as soon as that specific behavior is implemented and proven. Do NOT batch.
388
+ ```
389
+ - **The test plan items from the work item's checklist** (all `test-*` prefixed items). Include them verbatim in the prompt and instruct the agent:
390
+ ```
391
+ TEST PLAN — you MUST implement/verify each of these and tick them off via update_checklist_item(..., p_actor_session_id := '<your-session-id>', p_actor_role := 'agent'):
392
+ - test-assert-xxx: <description> → write a vitest test that proves this
393
+ - test-smoke-xxx: <description> → run the command and confirm the result
394
+ - test-visual-xxx: <description> → note: delegate to UI audit (you cannot verify this yourself)
395
+ - test-contract-xxx: <description> → verify the export/type/shape exists
396
+ Tick each item as you complete it. Do NOT batch — tick immediately after each verification.
397
+ ```
398
+ - Use `run_in_background: true` for parallel execution
399
+ - NEVER let agents overlap on the same files
400
+
401
+ ### ⛔ Agent Definition-of-Done additions (include in every prompt)
402
+ - **Declare every import in the package's OWN package.json.** Every import an
403
+ agent adds MUST be present in that package's own `package.json`
404
+ dependencies/devDependencies — never rely on monorepo-hoisted deps. A pnpm
405
+ worktree can import a root-hoisted dep (e.g. `vitest`,
406
+ `@supabase/supabase-js`) so `tsc`/`vitest` PASS in the worktree, then `tsc`
407
+ FAILS on a clean develop checkout after merge (lesson
408
+ 2026-06-10-build-card-engine-agent-deps). Agent prompt line: *"Verify that
409
+ every import you add is declared in this package's own package.json — do not
410
+ rely on hoisted monorepo deps."*
411
+ - **A server/MCP/API task is NOT done without a committed automated test that
412
+ ships in the SAME commit and exercises EVERY surface.** Manual curl / a single
413
+ `/health` 200 is a proxy, not coverage (lesson 2026-06-10-build-weak-dod-no-tests).
414
+ For a collection (MCP skills, API routes, CLI commands): loop over ALL items
415
+ and assert `output == source` — never a single spot check. Wire an npm script
416
+ and run it green before the item leaves `review`. Agent prompt line: *"This
417
+ task is not done until a committed test in the same commit exercises every
418
+ surface; for collections, loop all items and assert output == source."*
419
+
420
+ 8. **Post-wave test gate (mandatory):**
421
+ After all agents in a wave complete, before proceeding:
422
+ ```bash
423
+ # For each package modified in this wave:
424
+ cd packages/<name> && npx vitest run 2>&1 | tail -20
425
+ ```
426
+ - All tests must pass before proceeding to next wave
427
+ - If tests fail: fix before proceeding
428
+ - NEVER use `pnpm build` or `pnpm turbo test` — vitest only per package
429
+ - New code must have tests: if a modified package shows 0 new test files, flag it
430
+
431
+ 9. **After all wave agents complete — merge worktrees and push:**
432
+
433
+ Each completed agent returns a worktree branch (e.g. `claude/agent-frontend-abc123`). Merge them all to develop before running the test gate:
434
+
435
+ ```bash
436
+ # For each worktree branch returned by agents in this wave:
437
+ git merge --no-ff <worktree-branch> -m "merge(<agent-type>): <task-title>"
438
+ ```
439
+
440
+ - Resolve any conflicts before proceeding — do not skip
441
+ - Worker agents set items to `review` — **do NOT close to `done` yet**
442
+ - After all branches merged, push once:
443
+ ```bash
444
+ if [ "$RDC_TEST" != "1" ]; then
445
+ git push origin develop
446
+ else
447
+ echo "[RDC_TEST] skipping git push"
448
+ fi
449
+ ```
450
+ - Then run the post-wave test gate (Step 8) on the merged state
451
+ - Then run the code-review gate (Step 9b) before the next wave dispatches
452
+ - Continue to next wave
453
+
454
+ **If an agent fails (returns no worktree branch):**
455
+ - Interactive: diagnose before retrying
456
+ - Unattended: retry once; on second failure escalate via advisor
457
+ ```
458
+ BUILD_STATUS: { wave, tasks_done, tasks_failed, commits, escalated: true }
459
+ ```
460
+
461
+ 9b. **Mandatory per-wave code-review gate (runs after merge + test gate, BEFORE next wave dispatches):**
462
+
463
+ ⛔ **NO wave may dispatch until the previous wave's code-review pass clears.** Memory `feedback_code_review_per_wave.md` — Davesend 2026-05-24 incident.
464
+
465
+ Dispatch ONE `pr-review-toolkit:code-reviewer` agent with the wave's merged diff:
466
+
467
+ ```
468
+ Agent({
469
+ subagent_type: "pr-review-toolkit:code-reviewer",
470
+ description: "Wave <N> code review",
471
+ prompt: "Review the diff `git diff <wave-base-sha>..HEAD` on develop.
472
+ Focus on: bugs, logic errors, security vulnerabilities, project-convention adherence
473
+ (.claude/rules/*, CLAUDE.md). Apply confidence-based filtering — high-confidence
474
+ findings only. Report severity per finding: critical | high | medium | low.
475
+ Return CODE_REVIEW_COMPLETE with: { critical_count, high_count, medium_count,
476
+ low_count, findings: [{severity, file:line, issue, suggested_fix}] }."
477
+ })
478
+ ```
479
+
480
+ **Severity gate (default — high+ blocks):**
481
+ - `critical` or `high` findings → reopen affected work items to `todo` with finding text in notes; fix in a new wave before continuing
482
+ - `medium` or `low` findings → append to each work item's `implementation_report.flags`; do NOT reopen; validator sees them
483
+ - Zero findings → log `CODE_REVIEW: CLEAN` and proceed to next wave
484
+
485
+ Under `RDC_TEST=1`: echo `[RDC_TEST] skipping code-review dispatch` and proceed.
486
+
487
+ 10. **Mandatory validator gate (runs after ALL waves complete — before any work item closes):**
488
+
489
+ ⛔ **NO work item may be set to `done` without the validator passing it.**
490
+
491
+ Dispatch ONE validator agent with the complete list of `review` work items and the full git diff.
492
+ ⚠️ The validator does NOT use `isolation: "worktree"` — it must read the fully merged develop branch. Omit the isolation parameter for this dispatch only.
493
+
494
+ ```
495
+ "Read {PROJECT_ROOT}/.rdc/guides/agent-bootstrap.md then {PROJECT_ROOT}/.rdc/guides/verify.md.
496
+ Read {PROJECT_ROOT}/.rdc/guides/engineering-behavior.md before validating scope, deviations, and evidence.
497
+ Validate these work items: [list of IDs and titles].
498
+ Apps touched: [list].
499
+ Git diff since build start: [attach or reference].
500
+ You are the ONLY agent that closes work items to done.
501
+ Follow verify.md procedure exactly: tsc → vitest → dev server route probes → record result per item."
502
+ ```
503
+
504
+ The validator:
505
+ - Runs `npx tsc --noEmit` for every touched app/package
506
+ - Starts the dev server and probes every modified route (expects HTTP 200, not 500)
507
+ - Runs vitest for every touched package
508
+ - **Verifies checklist decomposition quality per work item before functional validation:**
509
+ - Every implementation work item has at least one `decomp-*` item and one `test-*` item
510
+ - Every `decomp-*` item includes route/file, action, expected result, and evidence artifact
511
+ - Any unchecked `decomp-*` item with `required: true` = work item CANNOT be set to `done`
512
+ - Any coarse or non-falsifiable `decomp-*` item = reopen to `todo` with the specific failure
513
+ - **Verifies test plan completion per work item:**
514
+ - For each `test-assert-*` checklist item: confirm a corresponding vitest test exists and passes
515
+ - For each `test-smoke-*` checklist item: run the command and confirm exit code / HTTP status
516
+ - For each `test-visual-*` checklist item: note as "delegated to UI audit" (validator cannot verify visuals)
517
+ - For each `test-contract-*` checklist item: verify the export/type/shape exists in the built code
518
+ - Any unchecked `test-*` item with `required: true` = work item CANNOT be set to `done` (DB enforces this)
519
+ - Sets passing items to `done`, failing items back to `todo` with failure detail
520
+ - Returns `VALIDATOR_COMPLETE` report with test plan status per item
521
+
522
+ **If the validator finds failures:** fix them in a new wave, then re-run the validator. Do not skip.
523
+ **File existence alone is NOT verification.** A route returning 500 is a failure regardless of tsc passing.
524
+ **Unchecked test plan items are a hard gate** — `update_work_item_status('done', ..., p_actor_role := 'validator')` will raise an exception if any `required: true` checklist item is unchecked, missing agent-session tick evidence, or re-ticked by a supervisor/validator.
525
+
526
+ 11. **After verification passes:**
527
+ - All wave commits are already on develop and pushed (Step 9 pushes after each wave merge).
528
+ - Update epic version: `bump_epic_version()`
529
+ - Report summary with verification evidence quoted
530
+
531
+ ## Agent TDD Requirements
532
+
533
+ When dispatching agents, include in every prompt:
534
+ ```
535
+ TDD REQUIREMENT: Write tests FIRST for new functions/modules.
536
+ Run: npx vitest run packages/<name> to verify red → implement → verify green.
537
+ NEVER run pnpm build or pnpm turbo. Use npx vitest run only.
538
+ ```
539
+
540
+ ## Rules
541
+ - Branch: development branch only (auto-commit, no confirmation needed)
542
+ - NEVER let two agents edit the same file
543
+ - NEVER run `pnpm build` (crashes system) — code only
544
+ - Every agent reads its guide file — no exceptions
545
+ - Update Supabase work items IN REAL TIME — not batch at end
546
+ - Push after each wave, not just at the end
547
+ - Unattended: NEVER pause — continue automatically
548
+ - Unattended: max 2 retries per task before escalating to advisor
549
+ - Every Agent() dispatch: `model: <routed>` + `max_turns: 70` — non-negotiable. `isolation` is per the dispatch-mode rule in Step 7: NON-isolated (omit `isolation`) for doc-only and single-committer waves; `isolation: "worktree"` ONLY for true parallel MULTI-committer waves, and only after the HARD GATE (worktree base == develop HEAD) passes — a stale-base isolated wave is a build failure. Model is chosen per task per the routing table in Step 7: Sonnet 4.6 for updates/edits, Opus 4.6 for harder coding, Opus 4.8 for design/innovative thought (CS 2.0, brand/UX, architecture). Supervisor logs `model=<chosen> reason=<phrase>` per agent. Exception: validator agent in Step 10 always omits isolation; validator model stays `claude-sonnet-4-6` (verification, not generation).
550
+ - Finding an existing file is NOT task completion — verify it satisfies the spec
551
+
552
+ ## Capture lessons (exit step)
553
+
554
+ Before the final verdict line, follow `.rdc/guides/lessons-learned-spec.md` § Capture procedure. If this run taught something non-obvious — a first root-cause theory that turned out wrong, the documented/standard path not working, a missing gate or check that cost a round, or a surprising tool/infra behavior — write one `.rdc/lessons/<YYYY-MM-DD>-build-<short-slug>.md` per lesson using the schema in that spec. Set `scope` (`simple` | `architectural`) and `status` (`open`, or `applied` if you shipped the fix in this same run, with the commit linked). Commit the lesson file(s) on `develop` alongside the run's other commits, and note "N lessons captured" in your verdict/summary. A run that taught nothing writes nothing — absence is the default.