@lifeaitools/rdc-skills 0.25.9 → 0.26.0

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 (77) hide show
  1. package/.claude-plugin/plugin.json +1608 -1551
  2. package/.github/workflows/self-test.yml +34 -34
  3. package/CHANGELOG.md +332 -319
  4. package/MANIFEST.md +224 -224
  5. package/README.md +368 -367
  6. package/RELEASE.md +50 -45
  7. package/bin/rdc-skills-mcp.mjs +1 -1
  8. package/commands/build.md +181 -181
  9. package/commands/collab.md +180 -180
  10. package/commands/deploy.md +173 -148
  11. package/commands/fixit.md +150 -150
  12. package/commands/handoff.md +173 -173
  13. package/commands/overnight.md +220 -220
  14. package/commands/plan.md +158 -158
  15. package/commands/preplan.md +131 -131
  16. package/commands/prototype.md +145 -145
  17. package/commands/report.md +99 -99
  18. package/commands/review.md +120 -120
  19. package/commands/status.md +86 -86
  20. package/commands/workitems.md +127 -127
  21. package/deploy/install-systemd.sh +16 -0
  22. package/deploy/systemd/rdc-skills-mcp.service +19 -0
  23. package/git-sha.json +1 -1
  24. package/guides/agent-bootstrap.md +195 -195
  25. package/guides/agents/backend.md +102 -102
  26. package/guides/agents/content.md +94 -94
  27. package/guides/agents/cs2.md +56 -56
  28. package/guides/agents/data.md +86 -86
  29. package/guides/agents/design.md +77 -77
  30. package/guides/agents/frontend.md +91 -91
  31. package/guides/agents/infrastructure.md +81 -81
  32. package/guides/agents/setup.md +272 -272
  33. package/guides/agents/verify.md +119 -119
  34. package/guides/agents/viz.md +106 -106
  35. package/guides/orchestration-epic.md +17 -0
  36. package/hooks/check-rdc-environment.js +172 -318
  37. package/hooks/lib/box-lock.js +28 -8
  38. package/package.json +1 -2
  39. package/scripts/install-rdc-skills.js +1244 -1474
  40. package/scripts/probe-installed-hooks.mjs +2 -2
  41. package/scripts/self-test.mjs +1459 -1459
  42. package/scripts/validate-publish-manifests.js +502 -502
  43. package/skills/build/SKILL.md +662 -578
  44. package/skills/channel-formatter/SKILL.md +538 -538
  45. package/skills/collab/SKILL.md +239 -239
  46. package/skills/convert/SKILL.md +138 -138
  47. package/skills/deploy/SKILL.md +583 -541
  48. package/skills/design/SKILL.md +205 -205
  49. package/skills/env/SKILL.md +146 -139
  50. package/skills/fixit/SKILL.md +203 -203
  51. package/skills/handoff/SKILL.md +236 -236
  52. package/skills/housekeeping/SKILL.md +189 -189
  53. package/skills/onramp/SKILL.md +1459 -1459
  54. package/skills/overnight/SKILL.md +251 -251
  55. package/skills/plan/SKILL.md +345 -345
  56. package/skills/preplan/SKILL.md +90 -90
  57. package/skills/prototype/SKILL.md +150 -150
  58. package/skills/refactor/SKILL.md +51 -0
  59. package/skills/regen-media/SKILL.md +94 -94
  60. package/skills/release/SKILL.md +140 -140
  61. package/skills/report/SKILL.md +100 -100
  62. package/skills/review/SKILL.md +151 -151
  63. package/skills/self-test/SKILL.md +108 -108
  64. package/skills/status/SKILL.md +99 -99
  65. package/skills/tests/MATRIX.md +59 -55
  66. package/skills/tests/README.md +1 -1
  67. package/skills/tests/onramp.test.json +101 -87
  68. package/skills/tests/rdc-env.test.json +12 -0
  69. package/skills/tests/rdc-new-model.test.json +12 -0
  70. package/skills/tests/rdc-refactor.test.json +29 -0
  71. package/skills/tests/rdc-regen-media.test.json +29 -29
  72. package/skills/watch/SKILL.md +84 -84
  73. package/skills/workitems/SKILL.md +151 -151
  74. package/tests/no-local-pm2.test.mjs +45 -0
  75. package/scripts/local-install-with-stop.sh +0 -41
  76. package/scripts/probe-lock-holders.mjs +0 -36
  77. package/scripts/rebuild-mcp.mjs +0 -107
@@ -1,578 +1,662 @@
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-*` items, has < 10 attested rows, or leaves a declared surface (screen/api/db/tool) uncovered | → Invoke `rdc:plan` on this epic. Coarse/under-decomposed 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 >= 10 attested `decomp-*`/`test-*` rows and meets the
148
- per-surface completeness floors from rdc:plan (each declared surface covered; a multi-surface
149
- WP carries the SUM of its surface floors, typically 12-20). A flat 5-6-row checklist for a
150
- feature WP is REJECTED — reopen the epic to rdc:plan for full surface-area decomposition.
151
- - Every implementation work item has at least one `decomp-*` checklist row and one `test-*` checklist row.
152
- - Every `decomp-*` row names a concrete route or file path.
153
- - Every `decomp-*` row names one user/agent action.
154
- - Every `decomp-*` row names one expected UI/API/DB result.
155
- - Every `decomp-*` row names one verification artifact: test name, route probe, Playwright screenshot, SQL query, API response, type-check, migration proof, or CLI transcript.
156
-
157
- Atomicity rubric:
158
- - One observable behavior per `decomp-*` row.
159
- - The row can pass or fail without reading hidden intent from the plan narrative.
160
- - The row is small enough for a worker to implement, tick, and cite evidence for directly.
161
- - Vague rows such as "theme management works", "UI implemented", "verified", "all screens", or "integration complete" are failures.
162
-
163
- Minimum decomposition heuristics:
164
- - UI route: at least empty/loading/loaded/error or the documented reason a state does not apply.
165
- - CRUD surface: at least list, create, edit, detail, duplicate/delete/archive where applicable, and validation failure.
166
- - API route: at least successful read/write, validation failure, and unauthorized/forbidden or documented auth bypass.
167
- - DB/migration task: at least schema object, relationship/guard, policy/permission, seed/fixture or backfill, and smoke query.
168
- - Editor/sidebar/CLI workflow: at least start, attach/open, enqueue action, observe result, timeout/error, and live refresh where applicable.
169
-
170
- HARD FLOOR (mirrors rdc:plan): every implementation task carries >= 10 attested rows; a
171
- multi-surface WP carries the SUM of its per-surface floors (typically 12-20). A flat 5-6-row
172
- feature checklist, or any declared surface (screen/api/db/tool) left uncovered, is a REJECT —
173
- reopen to rdc:plan. Every row must name its surface + one verification artifact (attested).
174
-
175
- ### Deliverable / acceptance check-off table show BEFORE any implementation
176
- Before dispatching the first wave, render a deliverable/acceptance table and
177
- keep it visible through the build (lesson 2026-06-16-build-poor-goal-execution-mdk-brain:
178
- a build satisfied generic checklist rows — tsc clean, route 200 — while never
179
- touching the surface the user actually named, because no row anchored the
180
- user's TARGET SURFACE). The table MUST contain:
181
- - **One mandatory row for the user-named TARGET SURFACE** — the exact screen,
182
- endpoint, file, or behavior the user asked for, by name. Its acceptance check
183
- is what proves THAT surface renders/works, not a proxy.
184
- - **At least one NEGATIVE verifier row** — a check that proves the WRONG thing
185
- does NOT happen (e.g. "mock data is NOT rendered", "old route returns 404",
186
- "stub component is absent from the bundle"). A positive-only suite passes
187
- even when the deliverable is wired to the wrong source.
188
-
189
- | Deliverable | Target surface? | Acceptance check | Negative verifier | Status |
190
- |---|---|---|---|---|
191
-
192
- **Gating rule:** any work item whose deliverable maps to the TARGET SURFACE row
193
- stays in `review` (never `done`) until that target-surface acceptance check
194
- passes. Generic gates (tsc, route 200) clearing is NOT sufficient to advance
195
- the target-surface item.
196
-
197
- If the gate fails:
198
- - Interactive: show the failing rows and invoke `rdc:plan <epic-id>` to repair the matrix before dispatch.
199
- - Unattended: invoke `rdc:plan <epic-id> --unattended`, reload tasks, and run this gate once more.
200
- - If the second gate fails, abort the build and return the failure list. Do not dispatch implementation agents.
201
-
202
- **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.
203
-
204
- 4. **Read CLAUDE.md files** for all affected packages.
205
-
206
- 5. **Classify each task** assign agent type from the table above.
207
-
208
- 5b. **Write or refresh the checklist into every work item before dispatching:**
209
- For each task, append the exact `decomp-*` and `test-*` checklist rows to its notes BEFORE setting to `in_progress`:
210
- ```sql
211
- SELECT update_work_item_status('<id>'::uuid, 'in_progress',
212
- '["CHECKLIST: [ ] decomp-ui-route-state: <route/file> | action=<action> | expect=<result> | evidence=<artifact>, [ ] test-smoke-route: <route probe>, [ ] committed"]'::jsonb
213
- );
214
- ```
215
- The agent must complete every item on this checklist and return it checked off in AGENT_COMPLETE.
216
- A checklist with unchecked items = incomplete work. Do not proceed to next wave with unchecked items.
217
-
218
- 6. **Group tasks into waves** parallelize tasks with no file overlap:
219
- - Wave 1: independent tasks (different packages/files)
220
- - Wave 2: tasks that depend on Wave 1 outputs
221
- - Wave 3: integration tasks
222
-
223
- 7. **For each wave — dispatch typed agents in parallel:**
224
-
225
- ### Agent Dispatch Non-Negotiable Defaults
226
- Every `Agent()` call MUST include these parameters:
227
- ```
228
- model: <chosen per the routing table below>
229
- max_turns: 70
230
- ```
231
- `isolation` is chosen per the dispatch-mode rule below it is NOT a blanket
232
- default. Worktree isolation is reserved for true parallel MULTI-committer waves
233
- in the same repo; doc-only and single-committer waves default to NON-isolated.
234
-
235
- ### Dispatch mode non-isolated is the default for single-committer / doc-only waves
236
- Worktree isolation exists to protect a SHARED working tree from a git-index race
237
- between MULTIPLE agents committing in parallel. When there is only ONE committer,
238
- that race cannot occur, and the stale-base hazard of worktrees (see the HARD GATE
239
- below recurring across 2026-06-10/11/15/16/17/23) is pure downside. Pick the
240
- dispatch mode by committer count, not by reflex:
241
-
242
- | Wave shape | Dispatch mode | isolation |
243
- |---|---|---|
244
- | **Doc-only wave** (markdown/docs/plans, no code build) | NON-isolated, one committer on `develop` | omit `isolation` |
245
- | **Single-committer wave** (only one agent commits, or work serializes to the supervisor) | NON-isolated, one committer on `develop` | omit `isolation` |
246
- | **True parallel MULTI-committer wave** (2+ agents committing concurrently in the same repo, disjoint files) | worktree-isolated, supervisor merges | `isolation: "worktree"` |
247
-
248
- - **Default = NON-isolated.** Only escalate to `isolation: "worktree"` when the
249
- wave genuinely has 2+ concurrent committers in the same repo.
250
- - A pure docs wave is single-committer by default: either dispatch ONE doc agent,
251
- or have parallel doc agents return diffs/patches that the supervisor commits
252
- serially. Do NOT fan out 2+ concurrent committers onto one shared `develop`
253
- tree (lesson 2026-06-13-build-concurrent-agents-same-branch-git-race: three
254
- parallel doc agents on one `develop` tree raced on the git index/stash one
255
- commit swept in another agent's staged-but-uncommitted files under the wrong
256
- message, two agents reported the SAME SHA, a pre-commit `sync:docs` ref-lock
257
- race misattributed authorship). The fix for that race is single-committer
258
- serialization, NOT blanket worktree isolation.
259
- - When you DO need a true MULTI-committer parallel wave, worktree isolation is
260
- mandatory AND the HARD GATE below (base == develop HEAD) MUST pass before
261
- dispatch a stale-base worktree wave is a build failure, not a warning.
262
-
263
- ### Foreign concurrent session guard `git status` BEFORE the build
264
- Worktree isolation protects against THIS build's own agents, not against a
265
- DIFFERENT session (another cell, a Codex run, a human) already committing on
266
- the same shared tree (lesson 2026-06-16-build-concurrent-session-shared-tree-commit-corruption:
267
- a foreign session's staged-but-uncommitted files were swept into this build's
268
- commit under the wrong message). Before dispatching any wave, run `git status`
269
- to detect foreign-dirty files you did not create. If foreign-dirty files are
270
- present: do NOT fan out concurrent committers **serialize ALL committers to
271
- the supervisor** (agents return diffs/patches; the supervisor stages and
272
- commits each one alone). After every supervisor commit, assert the exact file
273
- set landed and nothing foreign leaked in:
274
- ```bash
275
- git show --stat <sha> # confirm ONLY the files this commit owns are listed
276
- ```
277
- A `git show --stat` that lists a file the agent did not touch = a foreign file
278
- leaked into the commit; reset and re-stage by explicit path.
279
-
280
- **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.
281
-
282
- | Task character | Model | When to pick it |
283
- |---|---|---|
284
- | Updates, edits, mechanical refactors, small fixes, content tweaks, config patches, doc/copy edits, straightforward API wiring | `claude-sonnet-5` | 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. |
285
- | 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-5` | Default for `backend.md`/`data.md` work and any `frontend.md` task that involves state machines, race conditions, or cross-package contracts. |
286
- | 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-5` | 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. |
287
-
288
- **How to choose when the task straddles categories:**
289
- - If the task's checklist contains the word "design", "decide", "propose", "evaluate alternatives", "novel", or any CS 2.0 primitive → **Opus 5**.
290
- - 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 5** (CS 2.0 paradigm requires innovative thought, not transcription).
291
- - If the task is a Supabase migration that drops/renames/reshapes anything, or a refactor across ≥5 files → **Opus 5**.
292
- - Otherwise → **Sonnet 5**.
293
-
294
- **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.
295
-
296
- **Cost guardrail.** If a single wave would dispatch more than 3 Opus 5 agents in parallel, downshift the lowest-priority Opus 5 tasks to Sonnet 5 unless their work items are tagged `priority=urgent`. Opus 5 is cheap individually but still ~2× a Sonnet 5 agent at scale.
297
- Without `max_turns: 70`, agents hit the default turn cap mid-task and stop.
298
- `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).
299
-
300
- ### PREVENTION FIRST create worktrees fresh off origin/develop (kills stale-base by construction)
301
- The repeated stale-base failures below come from creating worktrees off a
302
- local/old ref. Eliminate the failure mode at the source: ALWAYS create agent
303
- worktrees with a fresh fetch + `origin/develop` base, e.g.
304
- `git fetch origin develop && git worktree add <dir> -b <branch> origin/develop`
305
- — or use the canonical launcher `node scripts/wt.mjs add <name>`, which does
306
- exactly that. A worktree cut from `origin/develop` HEAD **cannot** be stale.
307
- The HARD GATE below remains as the blocking backstop (detection), but
308
- construction-from-`origin/develop` is the primary defense.
309
-
310
- ### ⛔ HARD GATE — Worktree base MUST equal develop HEAD (blocking, not advisory)
311
- The worktree-isolation harness has shipped worktrees pinned to a STALE base
312
- commit (lessons 2026-06-10-build-worktree-stale-base, 2026-06-11-build-worktree-stale-base,
313
- 2026-06-15-build-worktree-stale-base, 2026-06-16-build-worktree-stale-base,
314
- 2026-06-17-build-worktree-stale-base, 2026-06-23-build-worktree-stale-base:
315
- agents branched hundreds of commits / multiple days behind develop HEAD, on a
316
- tree where the target app did not yet exist their diffs would have silently
317
- reverted merged work or operated on a deleted structure). This is a recurring
318
- harness defect, so the check is a **HARD BLOCKING GATE, not a suggestion.**
319
-
320
- **Before dispatching ANY `isolation:"worktree"` wave**, the supervisor MUST run
321
- the base==HEAD assertion and MUST abort isolation on any mismatch — there is no
322
- "proceed anyway" path:
323
- ```bash
324
- DEV_HEAD=$(git rev-parse develop)
325
- # After worktrees are created, for each agent worktree:
326
- git worktree list # compare each agent worktree's SHA to $DEV_HEAD
327
- # If ANY worktree base != $DEV_HEAD (it is behind), the wave is UNSAFE — ABORT.
328
- ```
329
- - **MANDATORY ABORT:** if ANY worktree base != `$DEV_HEAD`, you MUST abort
330
- isolation for this wave. Do NOT merge stale worktree output. Do NOT "fast-forward
331
- and continue". Do NOT proceed with the isolated wave under any circumstance.
332
- Pivot to **sequential, non-isolated dispatch on a real `develop` checkout**
333
- (one disjoint WP at a time to avoid `.git/index` races; the supervisor pushes) —
334
- the same reason the validator runs non-isolated (it must see merged develop).
335
- - This gate is blocking by design: an isolated wave dispatched on a stale base
336
- is treated as a build failure, not a warning. Skipping or downgrading this
337
- assertion to advisory is a contract violation.
338
- - Also at every merge: `git show <branch>:<key-file> | grep -c <symbol-a-prior-wave-introduced>`
339
- a 0 where there should be ≥1 means the branch is stale or deleted a shared
340
- export; resolve to `--ours` and re-apply that wave's real delta on current HEAD.
341
- esbuild/tsc PASS is necessary, not sufficientpair it with a grep gate on
342
- the symbols a refactor must preserve.
343
-
344
- ### Forked agents vs. standalone agents
345
-
346
- **When the supervisor has already read the plan** (via a prior `Read` tool call in the same session),
347
- dispatch **forked agents** with short prompts. Forked agents inherit the full conversation context —
348
- including every file the supervisor has read so you do NOT need to copy plan sections, file specs,
349
- or architecture details into the prompt. The agent already sees them.
350
-
351
- Short forked prompt template:
352
- ```
353
- You are a frontend agent building <WP name>. Work item: <uuid>.
354
- Scope: <one sentence>. Files: <list>. Verification: tsc --noEmit.
355
- Set item to review when done, return AGENT_COMPLETE with verification evidence.
356
- Read .rdc/guides/agent-bootstrap.md + .rdc/guides/engineering-behavior.md + .rdc/guides/frontend.md before starting.
357
- ```
358
-
359
- **When the supervisor has NOT read the plan** (e.g. dispatching from a fresh `rdc:build` call with
360
- only an epic ID), the agent has no plan context write a full briefing prompt with all specs.
361
-
362
- ### Reuse contract when a WP builds on an existing subsystem
363
- When a work package extends an existing subsystem, "compose adapter + X"
364
- under-specifies reuse and lets an agent legitimately re-author markup/logic the
365
- subsystem already exposes (lesson 2026-06-11-build-reuse-existing-engine-prompt:
366
- an agent set up to reinvent a grid when the card engine already shipped four
367
- `CardLayout` display types + a full `parseCommand CardSpec adapter CardModel[]`
368
- calling sequence). The dispatch prompt MUST:
369
- 1. **Enumerate the existing public API the agent must reuse, BY FILE** types/enums
370
- (`packages/.../types.ts:NN`), calling-sequence functions, AND the existing
371
- display/render componentsnot just the data adapter.
372
- 2. **Mark which seams are extend/delegate-only.** State explicitly: "thread a
373
- pass-through prop (e.g. `layout`) to the existing components; do NOT
374
- reimplement layout/render." Verify at WP review that the agent reused the
375
- named parser/adapter/components and did not hand-roll a parallel implementation.
376
-
377
- ---
378
-
379
- ### Required agent prompt contents
380
- - Set work item to `in_progress` before dispatching
381
- - Each agent prompt MUST include:
382
- - `"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."`
383
- - `"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."`
384
- - Specific files to create/modify (or omit if forked agent inherits plan context)
385
- - Exact deliverables and commit message
386
- - `"NEVER run pnpm build/test. NEVER modify files outside your scope."`
387
- - **`"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."`**
388
- - **`"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."`**
389
- - **`"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."`**
390
- - **`"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."`**
391
- - **The decomposition items from the work item's checklist** (all `decomp-*` prefixed items). Include them verbatim in the prompt and instruct the agent:
392
- ```
393
- 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'):
394
- - decomp-ui-xxx: <route/file> | action=<action> | expect=<result> | evidence=<artifact>
395
- - decomp-api-xxx: <route/file> | action=<action> | expect=<result> | evidence=<artifact>
396
- Tick each item as soon as that specific behavior is implemented and proven. Do NOT batch.
397
- ```
398
- - **The test plan items from the work item's checklist** (all `test-*` prefixed items). Include them verbatim in the prompt and instruct the agent:
399
- ```
400
- 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'):
401
- - test-assert-xxx: <description> write a vitest test that proves this
402
- - test-smoke-xxx: <description> run the command and confirm the result
403
- - test-visual-xxx: <description> note: delegate to UI audit (you cannot verify this yourself)
404
- - test-contract-xxx: <description> verify the export/type/shape exists
405
- Tick each item as you complete it. Do NOT batch tick immediately after each verification.
406
- ```
407
- - Use `run_in_background: true` for parallel execution
408
- - NEVER let agents overlap on the same files
409
-
410
- ### Agent Definition-of-Done additions (include in every prompt)
411
- - **Declare every import in the package's OWN package.json.** Every import an
412
- agent adds MUST be present in that package's own `package.json`
413
- dependencies/devDependencies never rely on monorepo-hoisted deps. A pnpm
414
- worktree can import a root-hoisted dep (e.g. `vitest`,
415
- `@supabase/supabase-js`) so `tsc`/`vitest` PASS in the worktree, then `tsc`
416
- FAILS on a clean develop checkout after merge (lesson
417
- 2026-06-10-build-card-engine-agent-deps). Agent prompt line: *"Verify that
418
- every import you add is declared in this package's own package.json do not
419
- rely on hoisted monorepo deps."*
420
- - **A server/MCP/API task is NOT done without a committed automated test that
421
- ships in the SAME commit and exercises EVERY surface.** Manual curl / a single
422
- `/health` 200 is a proxy, not coverage (lesson 2026-06-10-build-weak-dod-no-tests).
423
- For a collection (MCP skills, API routes, CLI commands): loop over ALL items
424
- and assert `output == source` never a single spot check. Wire an npm script
425
- and run it green before the item leaves `review`. Agent prompt line: *"This
426
- task is not done until a committed test in the same commit exercises every
427
- surface; for collections, loop all items and assert output == source."*
428
- - **Durable workflow E2E gate (hard):** A task that creates a queue/job,
429
- background worker, storage hand-off, retry/lease, webhook, or other async
430
- cross-process workflow MUST ship a committed `test:e2e` (or equivalent)
431
- harness. Before the task leaves `review`, run it against the deploy-equivalent
432
- container plus real disposable dependencies (or an isolated mirror) and
433
- retain its receipt. The harness MUST exercise the public ingress, assert the
434
- full state transition, assert every persisted output, and clean up fixture
435
- rows/objects in `finally`; unit tests, mocks, a migration check, Docker
436
- construction, or a `/health` probe cannot substitute. If no safe disposable
437
- environment exists, create one within the work package; do not waive this
438
- gate or mark the item reviewable.
439
-
440
- 8. **Post-wave test gate (mandatory):**
441
- After all agents in a wave complete, before proceeding:
442
- ```bash
443
- # For each package modified in this wave:
444
- cd packages/<name> && npx vitest run 2>&1 | tail -20
445
- ```
446
- - All tests must pass before proceeding to next wave
447
- - If tests fail: fix before proceeding
448
- - NEVER use `pnpm build` or `pnpm turbo test` — vitest only per package
449
- - New code must have tests: if a modified package shows 0 new test files, flag it
450
-
451
- 9. **After all wave agents complete merge worktrees and push:**
452
-
453
- Each completed agent returns a worktree branch (e.g. `claude/agent-frontend-abc123`). Merge them all to develop before running the test gate:
454
-
455
- ```bash
456
- # For each worktree branch returned by agents in this wave:
457
- git merge --no-ff <worktree-branch> -m "merge(<agent-type>): <task-title>"
458
- ```
459
-
460
- - Resolve any conflicts before proceeding do not skip
461
- - Worker agents set items to `review` — **do NOT close to `done` yet**
462
- - After all branches merged, push once:
463
- ```bash
464
- if [ "$RDC_TEST" != "1" ]; then
465
- git push origin develop
466
- else
467
- echo "[RDC_TEST] skipping git push"
468
- fi
469
- ```
470
- - Then run the post-wave test gate (Step 8) on the merged state
471
- - Then run the code-review gate (Step 9b) before the next wave dispatches
472
- - Continue to next wave
473
-
474
- **If an agent fails (returns no worktree branch):**
475
- - Interactive: diagnose before retrying
476
- - Unattended: retry once; on second failure escalate via advisor
477
- ```
478
- BUILD_STATUS: { wave, tasks_done, tasks_failed, commits, escalated: true }
479
- ```
480
-
481
- 9b. **Mandatory per-wave code-review gate (runs after merge + test gate, BEFORE next wave dispatches):**
482
-
483
- ⛔ **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.
484
-
485
- Dispatch ONE `pr-review-toolkit:code-reviewer` agent with the wave's merged diff:
486
-
487
- ```
488
- Agent({
489
- subagent_type: "pr-review-toolkit:code-reviewer",
490
- description: "Wave <N> code review",
491
- prompt: "Review the diff `git diff <wave-base-sha>..HEAD` on develop.
492
- Focus on: bugs, logic errors, security vulnerabilities, project-convention adherence
493
- (.claude/rules/*, CLAUDE.md). Apply confidence-based filtering — high-confidence
494
- findings only. Report severity per finding: critical | high | medium | low.
495
- Return CODE_REVIEW_COMPLETE with: { critical_count, high_count, medium_count,
496
- low_count, findings: [{severity, file:line, issue, suggested_fix}] }."
497
- })
498
- ```
499
-
500
- **Severity gate (default high+ blocks):**
501
- - `critical` or `high` findings → reopen affected work items to `todo` with finding text in notes; fix in a new wave before continuing
502
- - `medium` or `low` findings append to each work item's `implementation_report.flags`; do NOT reopen; validator sees them
503
- - Zero findings log `CODE_REVIEW: CLEAN` and proceed to next wave
504
-
505
- Under `RDC_TEST=1`: echo `[RDC_TEST] skipping code-review dispatch` and proceed.
506
-
507
- 10. **Mandatory validator gate (runs after ALL waves complete before any work item closes):**
508
-
509
- **NO work item may be set to `done` without the validator passing it.**
510
-
511
- Dispatch ONE validator agent with the complete list of `review` work items and the full git diff.
512
- ⚠️ The validator does NOT use `isolation: "worktree"` it must read the fully merged develop branch. Omit the isolation parameter for this dispatch only.
513
-
514
- ```
515
- "Read {PROJECT_ROOT}/.rdc/guides/agent-bootstrap.md then {PROJECT_ROOT}/.rdc/guides/verify.md.
516
- Read {PROJECT_ROOT}/.rdc/guides/engineering-behavior.md before validating scope, deviations, and evidence.
517
- Validate these work items: [list of IDs and titles].
518
- Apps touched: [list].
519
- Git diff since build start: [attach or reference].
520
- You are the ONLY agent that closes work items to done.
521
- Follow verify.md procedure exactly: tsc vitest dev server route probes → record result per item."
522
- ```
523
-
524
- The validator:
525
- - Runs `npx tsc --noEmit` for every touched app/package
526
- - Starts the dev server and probes every modified route (expects HTTP 200, not 500)
527
- - Runs vitest for every touched package
528
- - For every durable workflow, runs the committed E2E harness and rejects the
529
- item unless its receipt proves public ingress -> queued/running -> terminal
530
- state, persisted outputs, and fixture cleanup on the deploy-equivalent
531
- runtime; an absent harness is a hard rejection.
532
- - **Verifies checklist decomposition quality per work item before functional validation:**
533
- - Every implementation work item has >= 10 attested `decomp-*`/`test-*` items, meets the per-surface completeness floors (each declared surface covered), and no feature WP ships a 5-6-row checklist
534
- - Every `decomp-*` item includes route/file, action, expected result, and evidence artifact
535
- - Any unchecked `decomp-*` item with `required: true` = work item CANNOT be set to `done`
536
- - Any coarse or non-falsifiable `decomp-*` item = reopen to `todo` with the specific failure
537
- - **Verifies test plan completion per work item:**
538
- - For each `test-assert-*` checklist item: confirm a corresponding vitest test exists and passes
539
- - For each `test-smoke-*` checklist item: run the command and confirm exit code / HTTP status
540
- - For each `test-visual-*` checklist item: note as "delegated to UI audit" (validator cannot verify visuals)
541
- - For each `test-contract-*` checklist item: verify the export/type/shape exists in the built code
542
- - Any unchecked `test-*` item with `required: true` = work item CANNOT be set to `done` (DB enforces this)
543
- - Sets passing items to `done`, failing items back to `todo` with failure detail
544
- - Returns `VALIDATOR_COMPLETE` report with test plan status per item
545
-
546
- **If the validator finds failures:** fix them in a new wave, then re-run the validator. Do not skip.
547
- **File existence alone is NOT verification.** A route returning 500 is a failure regardless of tsc passing.
548
- **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.
549
-
550
- 11. **After verification passes:**
551
- - All wave commits are already on develop and pushed (Step 9 pushes after each wave merge).
552
- - Update epic version: `bump_epic_version()`
553
- - Report summary with verification evidence quoted
554
-
555
- ## Agent TDD Requirements
556
-
557
- When dispatching agents, include in every prompt:
558
- ```
559
- TDD REQUIREMENT: Write tests FIRST for new functions/modules.
560
- Run: npx vitest run packages/<name> to verify red → implement → verify green.
561
- NEVER run pnpm build or pnpm turbo. Use npx vitest run only.
562
- ```
563
-
564
- ## Rules
565
- - Branch: development branch only (auto-commit, no confirmation needed)
566
- - NEVER let two agents edit the same file
567
- - NEVER run `pnpm build` (crashes system) code only
568
- - Every agent reads its guide file — no exceptions
569
- - Update Supabase work items IN REAL TIME — not batch at end
570
- - Push after each wave, not just at the end
571
- - Unattended: NEVER pause — continue automatically
572
- - Unattended: max 2 retries per task before escalating to advisor
573
- - 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 5 for updates/edits, Opus 5 for harder coding and 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-5` (verification, not generation).
574
- - Finding an existing file is NOT task completion — verify it satisfies the spec
575
-
576
- ## Capture lessons (exit step)
577
-
578
- 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-*` items, has < 10 attested rows, or leaves a declared surface (screen/api/db/tool) uncovered | → Invoke `rdc:plan` on this epic. Coarse/under-decomposed 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
+ 2b. **PROVE IT ISN'T ALREADY BUILT (mandatory never skip, never infer):**
136
+
137
+ A work item's `status` and `title` are a *claim about* the codebase, not the
138
+ codebase. They go stale silently: nobody updates a title when the thing it
139
+ describes gets built. **Treat every open task as unverified until you have
140
+ measured the code.** For each task about to be dispatched:
141
+
142
+ ```
143
+ 1. codeflow / codeflow_query on the named module or symbol
144
+ 2. grep the repo for the identifiers in the task title
145
+ 3. git log --all --oneline --name-only --diff-filter=A -- '<path-fragment>'
146
+ the file may exist on a branch, at a DIFFERENT path than the task names
147
+ 4. if the module exists: run its tests and read the test NAMES,
148
+ not just the pass count that is what tells you which behaviours are proven
149
+ ```
150
+
151
+ Then classify the task by what you measured, and say which in your checklist:
152
+
153
+ | Measured | Action |
154
+ |---|---|
155
+ | Not implemented | Dispatch as written |
156
+ | Implemented **and** tests name the behaviour | **DO NOT DISPATCH.** Record evidence, move the item to its true state |
157
+ | Implemented, no test naming the behaviour | Re-scope the task to *prove it*, not rebuild it |
158
+ | Implemented at a different path than the task says | Correct the task/plan text first, then re-classify |
159
+
160
+ **STOP RULE: never dispatch an agent to build something you have not just
161
+ proven absent.** A rebuild is worse than a no-op it burns the budget, then
162
+ produces a second implementation that must be reconciled with the first.
163
+
164
+ **Fix the record as you go.** When a task misreports reality, correcting it is
165
+ part of this build, not follow-up work: `record_evidence_probe` with the
166
+ measurement, then advance the item. Leaving a known-false status in the DB
167
+ guarantees the next session repeats the work you just avoided.
168
+
169
+ *Why this step exists:* 2026-07-26/27. Four of seven work items on the
170
+ CodeFlow orchestrator epic misreported reality at once WP-5's bridge was
171
+ implemented and tested while the item read `todo`; WP-2R's title still said
172
+ "UNTESTED and UNCONSUMED" after both were fixed; a resume plan listed four
173
+ "NOT finished" items of which three were done and the module had landed at a
174
+ different path than the plan named. Two separate sessions read those claims as
175
+ a task list. One burned ~550k tokens rebuilding site work that already
176
+ existed; the next came within one tool call of rebuilding the orchestrator.
177
+ Steps 2 and 3 as written did not catch any of it, because neither one looks at
178
+ the code.
179
+
180
+ 2c. **ROUTE TO THE TEMPLATE EPIC (mandatory before creating any work item):**
181
+
182
+ Some classes of work are governed by an **orchestration template epic** an epic that
183
+ governs a *class* of work rather than a feature, authored per
184
+ `.rdc/guides/orchestration-epic.md`. Before `insert_work_item`, check whether the files
185
+ you are about to touch fall inside one's trigger surface:
186
+
187
+ ```sql
188
+ SELECT id, title, description FROM work_items
189
+ WHERE item_type = 'epic' AND labels && ARRAY['orchestration-template','template'];
190
+ ```
191
+
192
+ If a template epic's §1 trigger surface covers your paths, the new item **MUST** be
193
+ parented to that epic (or a child of it), and inherit its receipt/trailer requirements.
194
+ A work item on a governed surface with no orchestration linkage **is invalid** the
195
+ commit gate will reject the eventual commit, and the item cannot close.
196
+
197
+ Known example: template epic `1574c3f5-d24b-439f-956c-26d9986b56c3` governs
198
+ `packages/codeflow/**`, `packages/codeflow-parser/**`, `scripts/codeflow*`,
199
+ `apps/codeflow-explorer/**`. Its §11 names `rdc:build` explicitly as a skill that must
200
+ route this way.
201
+
202
+ **Also check the inherited checklist.** `insert_work_item` auto-inherits the parent
203
+ epic's `definition_of_done` when `p_checklist` is omitted. A template epic's DoD is
204
+ written for its class of work inheriting it onto an unrelated task produces required
205
+ rows that can never be ticked, so the item can never close. **Pass an explicit
206
+ `p_checklist` with `decomp-*` and `test-*` rows scoped to the actual task.**
207
+
208
+ *Why this step exists:* 2026-07-27. A build session created two work items for edits to
209
+ `packages/codeflow/src/orchestrator/` and parented both to an unrelated feature epic
210
+ precisely the "generic work item with no orchestration linkage" §11 declares invalid.
211
+ The same two inserts inherited a 26-row place-enrollment DoD and had to be archived and
212
+ re-created twice.
213
+
214
+ 3. **Load the plan** (mandatory): check `.rdc/plans/` for matching topic (fallback: `.rdc/plans/`).
215
+ **A plan is evidence of intent, not of state** verify its claims against step 2b
216
+ before planning any work from it.
217
+
218
+ 3b. **Checklist decomposition quality gate (mandatory before code):**
219
+
220
+ `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.
221
+
222
+ Required plan sections:
223
+ - `## Checklist Decomposition Matrix`
224
+ - `## Checklist Quality Gate`
225
+ - `verdict: PASS`
226
+
227
+ Required task checklist shape:
228
+ - Every implementation work item has >= 10 attested `decomp-*`/`test-*` rows and meets the
229
+ per-surface completeness floors from rdc:plan (each declared surface covered; a multi-surface
230
+ WP carries the SUM of its surface floors, typically 12-20). A flat 5-6-row checklist for a
231
+ feature WP is REJECTED reopen the epic to rdc:plan for full surface-area decomposition.
232
+ - Every implementation work item has at least one `decomp-*` checklist row and one `test-*` checklist row.
233
+ - Every `decomp-*` row names a concrete route or file path.
234
+ - Every `decomp-*` row names one user/agent action.
235
+ - Every `decomp-*` row names one expected UI/API/DB result.
236
+ - Every `decomp-*` row names one verification artifact: test name, route probe, Playwright screenshot, SQL query, API response, type-check, migration proof, or CLI transcript.
237
+
238
+ Atomicity rubric:
239
+ - One observable behavior per `decomp-*` row.
240
+ - The row can pass or fail without reading hidden intent from the plan narrative.
241
+ - The row is small enough for a worker to implement, tick, and cite evidence for directly.
242
+ - Vague rows such as "theme management works", "UI implemented", "verified", "all screens", or "integration complete" are failures.
243
+
244
+ Minimum decomposition heuristics:
245
+ - UI route: at least empty/loading/loaded/error or the documented reason a state does not apply.
246
+ - CRUD surface: at least list, create, edit, detail, duplicate/delete/archive where applicable, and validation failure.
247
+ - API route: at least successful read/write, validation failure, and unauthorized/forbidden or documented auth bypass.
248
+ - DB/migration task: at least schema object, relationship/guard, policy/permission, seed/fixture or backfill, and smoke query.
249
+ - Editor/sidebar/CLI workflow: at least start, attach/open, enqueue action, observe result, timeout/error, and live refresh where applicable.
250
+
251
+ HARD FLOOR (mirrors rdc:plan): every implementation task carries >= 10 attested rows; a
252
+ multi-surface WP carries the SUM of its per-surface floors (typically 12-20). A flat 5-6-row
253
+ feature checklist, or any declared surface (screen/api/db/tool) left uncovered, is a REJECT —
254
+ reopen to rdc:plan. Every row must name its surface + one verification artifact (attested).
255
+
256
+ ### Deliverable / acceptance check-off table show BEFORE any implementation
257
+ Before dispatching the first wave, render a deliverable/acceptance table and
258
+ keep it visible through the build (lesson 2026-06-16-build-poor-goal-execution-mdk-brain:
259
+ a build satisfied generic checklist rows tsc clean, route 200 — while never
260
+ touching the surface the user actually named, because no row anchored the
261
+ user's TARGET SURFACE). The table MUST contain:
262
+ - **One mandatory row for the user-named TARGET SURFACE** — the exact screen,
263
+ endpoint, file, or behavior the user asked for, by name. Its acceptance check
264
+ is what proves THAT surface renders/works, not a proxy.
265
+ - **At least one NEGATIVE verifier row** a check that proves the WRONG thing
266
+ does NOT happen (e.g. "mock data is NOT rendered", "old route returns 404",
267
+ "stub component is absent from the bundle"). A positive-only suite passes
268
+ even when the deliverable is wired to the wrong source.
269
+
270
+ | Deliverable | Target surface? | Acceptance check | Negative verifier | Status |
271
+ |---|---|---|---|---|
272
+
273
+ **Gating rule:** any work item whose deliverable maps to the TARGET SURFACE row
274
+ stays in `review` (never `done`) until that target-surface acceptance check
275
+ passes. Generic gates (tsc, route 200) clearing is NOT sufficient to advance
276
+ the target-surface item.
277
+
278
+ If the gate fails:
279
+ - Interactive: show the failing rows and invoke `rdc:plan <epic-id>` to repair the matrix before dispatch.
280
+ - Unattended: invoke `rdc:plan <epic-id> --unattended`, reload tasks, and run this gate once more.
281
+ - If the second gate fails, abort the build and return the failure list. Do not dispatch implementation agents.
282
+
283
+ **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.
284
+
285
+ 4. **Read CLAUDE.md files** for all affected packages.
286
+
287
+ 5. **Classify each task** → assign agent type from the table above.
288
+
289
+ 5b. **Write or refresh the checklist into every work item before dispatching:**
290
+ For each task, append the exact `decomp-*` and `test-*` checklist rows to its notes BEFORE setting to `in_progress`:
291
+ ```sql
292
+ SELECT update_work_item_status('<id>'::uuid, 'in_progress',
293
+ '["CHECKLIST: [ ] decomp-ui-route-state: <route/file> | action=<action> | expect=<result> | evidence=<artifact>, [ ] test-smoke-route: <route probe>, [ ] committed"]'::jsonb
294
+ );
295
+ ```
296
+ The agent must complete every item on this checklist and return it checked off in AGENT_COMPLETE.
297
+ A checklist with unchecked items = incomplete work. Do not proceed to next wave with unchecked items.
298
+
299
+ 6. **Group tasks into waves** — parallelize tasks with no file overlap:
300
+ - Wave 1: independent tasks (different packages/files)
301
+ - Wave 2: tasks that depend on Wave 1 outputs
302
+ - Wave 3: integration tasks
303
+
304
+ 7. **For each wave dispatch typed agents in parallel:**
305
+
306
+ ### Agent Dispatch Non-Negotiable Defaults
307
+ Every `Agent()` call MUST include these parameters:
308
+ ```
309
+ model: <chosen per the routing table below>
310
+ max_turns: 70
311
+ ```
312
+ Every dispatched agent that may edit or commit MUST receive a unique leased
313
+ worktree. A non-isolated dispatched agent is read-only and may research,
314
+ review, or validate merged source; it may not write.
315
+
316
+ ### Dispatch modewriters are always isolated
317
+ Isolation is an ownership boundary, not a concurrency optimization. The
318
+ supervisor may implement directly as the sole writer, but once work is
319
+ dispatched, each writer gets its own fresh leased worktree:
320
+
321
+ | Wave shape | Dispatch mode | isolation |
322
+ |---|---|---|
323
+ | **Read-only research/review/validator** | shared merged source, no writes | omit `isolation` |
324
+ | **Any dispatched writer** | unique leased worktree and branch | `isolation: "worktree"` |
325
+ | **Cross-repository outcome** | one linked branch per repository | unique worktree in each repo |
326
+
327
+ - One issue may touch multiple apps in one monorepo branch when the paths are
328
+ explicitly attributed to that issue.
329
+ - Crossing repositories always creates one branch per repository, linked by
330
+ the collaboration manifest and work item.
331
+ - Independent outcomes use independent worktrees.
332
+ - The HARD GATE below applies before every writing dispatch.
333
+
334
+ ### Foreign concurrent session guard `git status` BEFORE the build
335
+ Worktree isolation protects against THIS build's own agents, not against a
336
+ DIFFERENT session (another cell, a Codex run, a human) already committing on
337
+ the same shared tree (lesson 2026-06-16-build-concurrent-session-shared-tree-commit-corruption:
338
+ a foreign session's staged-but-uncommitted files were swept into this build's
339
+ commit under the wrong message). Before dispatching any wave, run `git status`
340
+ to detect foreign-dirty files you did not create. If foreign-dirty files are
341
+ present: do NOT fan out concurrent committers **serialize ALL committers to
342
+ the supervisor** (agents return diffs/patches; the supervisor stages and
343
+ commits each one alone). After every supervisor commit, assert the exact file
344
+ set landed and nothing foreign leaked in:
345
+ ```bash
346
+ git show --stat <sha> # confirm ONLY the files this commit owns are listed
347
+ ```
348
+ A `git show --stat` that lists a file the agent did not touch = a foreign file
349
+ leaked into the commit; reset and re-stage by explicit path.
350
+
351
+ **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.
352
+
353
+ | Task character | Model | When to pick it |
354
+ |---|---|---|
355
+ | Updates, edits, mechanical refactors, small fixes, content tweaks, config patches, doc/copy edits, straightforward API wiring | `claude-sonnet-5` | 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. |
356
+ | 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-5` | Default for `backend.md`/`data.md` work and any `frontend.md` task that involves state machines, race conditions, or cross-package contracts. |
357
+ | 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-5` | 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. |
358
+
359
+ **How to choose when the task straddles categories:**
360
+ - If the task's checklist contains the word "design", "decide", "propose", "evaluate alternatives", "novel", or any CS 2.0 primitive **Opus 5**.
361
+ - 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 5** (CS 2.0 paradigm requires innovative thought, not transcription).
362
+ - If the task is a Supabase migration that drops/renames/reshapes anything, or a refactor across ≥5 files **Opus 5**.
363
+ - Otherwise **Sonnet 5**.
364
+
365
+ **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.
366
+
367
+ **Cost guardrail.** If a single wave would dispatch more than 3 Opus 5 agents in parallel, downshift the lowest-priority Opus 5 tasks to Sonnet 5 unless their work items are tagged `priority=urgent`. Opus 5 is cheap individually but still ~2× a Sonnet 5 agent at scale.
368
+ Without `max_turns: 70`, agents hit the default turn cap mid-task and stop.
369
+ `isolation: "worktree"` gives each agent its own git worktree and brancheliminates push race conditions and index lock contention when multiple agents commit in parallel. The supervisor merges worktree branches after each wave (Step 9).
370
+
371
+ ### PREVENTION FIRST create worktrees fresh off origin/develop (kills stale-base by construction)
372
+ The repeated stale-base failures below come from creating worktrees off a
373
+ local/old ref. Eliminate the failure mode at the source: ALWAYS create agent
374
+ worktrees with a fresh fetch + `origin/develop` base, e.g.
375
+ `git fetch origin develop && git worktree add <dir> -b <branch> origin/develop`
376
+ — or use the canonical launcher `node scripts/wt.mjs add <name>`, which does
377
+ exactly that. A worktree cut from `origin/develop` HEAD **cannot** be stale.
378
+ The HARD GATE below remains as the blocking backstop (detection), but
379
+ construction-from-`origin/develop` is the primary defense.
380
+
381
+ ### HARD GATE — Worktree base MUST equal develop HEAD (blocking, not advisory)
382
+ The worktree-isolation harness has shipped worktrees pinned to a STALE base
383
+ commit (lessons 2026-06-10-build-worktree-stale-base, 2026-06-11-build-worktree-stale-base,
384
+ 2026-06-15-build-worktree-stale-base, 2026-06-16-build-worktree-stale-base,
385
+ 2026-06-17-build-worktree-stale-base, 2026-06-23-build-worktree-stale-base:
386
+ agents branched hundreds of commits / multiple days behind develop HEAD, on a
387
+ tree where the target app did not yet existtheir diffs would have silently
388
+ reverted merged work or operated on a deleted structure). This is a recurring
389
+ harness defect, so the check is a **HARD BLOCKING GATE, not a suggestion.**
390
+
391
+ **Before dispatching ANY `isolation:"worktree"` wave**, the supervisor MUST run
392
+ the base==HEAD assertion and MUST abort isolation on any mismatch — there is no
393
+ "proceed anyway" path:
394
+ ```bash
395
+ DEV_HEAD=$(git rev-parse develop)
396
+ # After worktrees are created, for each agent worktree:
397
+ git worktree list # compare each agent worktree's SHA to $DEV_HEAD
398
+ # If ANY worktree base != $DEV_HEAD (it is behind), the wave is UNSAFE ABORT.
399
+ ```
400
+ - **MANDATORY ABORT:** if ANY worktree base != `$DEV_HEAD`, you MUST abort
401
+ isolation for this wave. Do NOT merge stale worktree output. Do NOT "fast-forward
402
+ and continue". Do NOT proceed with the isolated wave under any circumstance.
403
+ Recreate the worktree from the current remote integration head. Do not pivot
404
+ a dispatched writer into a shared checkout. A validator remains non-isolated
405
+ only because it is read-only and must inspect merged source.
406
+ - This gate is blocking by design: an isolated wave dispatched on a stale base
407
+ is treated as a build failure, not a warning. Skipping or downgrading this
408
+ assertion to advisory is a contract violation.
409
+ - Also at every merge: `git show <branch>:<key-file> | grep -c <symbol-a-prior-wave-introduced>`
410
+ a 0 where there should be ≥1 means the branch is stale or deleted a shared
411
+ export; resolve to `--ours` and re-apply that wave's real delta on current HEAD.
412
+ esbuild/tsc PASS is necessary, not sufficient pair it with a grep gate on
413
+ the symbols a refactor must preserve.
414
+
415
+ ### Forked agents vs. standalone agents
416
+
417
+ **When the supervisor has already read the plan** (via a prior `Read` tool call in the same session),
418
+ dispatch **forked agents** with short prompts. Forked agents inherit the full conversation context
419
+ including every file the supervisor has read — so you do NOT need to copy plan sections, file specs,
420
+ or architecture details into the prompt. The agent already sees them.
421
+
422
+ Short forked prompt template:
423
+ ```
424
+ You are a frontend agent building <WP name>. Work item: <uuid>.
425
+ Scope: <one sentence>. Files: <list>. Verification: tsc --noEmit.
426
+ Set item to review when done, return AGENT_COMPLETE with verification evidence.
427
+ Read .rdc/guides/agent-bootstrap.md + .rdc/guides/engineering-behavior.md + .rdc/guides/frontend.md before starting.
428
+ ```
429
+
430
+ **When the supervisor has NOT read the plan** (e.g. dispatching from a fresh `rdc:build` call with
431
+ only an epic ID), the agent has no plan context write a full briefing prompt with all specs.
432
+
433
+ ### Reuse contract when a WP builds on an existing subsystem
434
+ When a work package extends an existing subsystem, "compose adapter + X"
435
+ under-specifies reuse and lets an agent legitimately re-author markup/logic the
436
+ subsystem already exposes (lesson 2026-06-11-build-reuse-existing-engine-prompt:
437
+ an agent set up to reinvent a grid when the card engine already shipped four
438
+ `CardLayout` display types + a full `parseCommand → CardSpec → adapter → CardModel[]`
439
+ calling sequence). The dispatch prompt MUST:
440
+ 1. **Enumerate the existing public API the agent must reuse, BY FILE** — types/enums
441
+ (`packages/.../types.ts:NN`), calling-sequence functions, AND the existing
442
+ display/render components — not just the data adapter.
443
+ 2. **Mark which seams are extend/delegate-only.** State explicitly: "thread a
444
+ pass-through prop (e.g. `layout`) to the existing components; do NOT
445
+ reimplement layout/render." Verify at WP review that the agent reused the
446
+ named parser/adapter/components and did not hand-roll a parallel implementation.
447
+
448
+ ---
449
+
450
+ ### Required agent prompt contents
451
+ - Set work item to `in_progress` before dispatching
452
+ - Each agent prompt MUST include:
453
+ - `"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."`
454
+ - `"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."`
455
+ - Specific files to create/modify (or omit if forked agent inherits plan context)
456
+ - Exact deliverables and commit message
457
+ - `"NEVER run pnpm build/test. NEVER modify files outside your scope."`
458
+ - **`"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."`**
459
+ - **`"When done: FIRST call submit_implementation_report(<work_item_id>, {...}) including a codeflow_post with agent_session_id, summary, files_changed, verification, commit, repo_truth_state. THEN set your work item to 'review' (NOT 'done'). Return AGENT_COMPLETE with a verification field. The validator closes work items — you do not."`**
460
+ > The order is load-bearing, not stylistic: `update_work_item_status(..., 'review')`
461
+ > **raises** on a non-epic item unless `implementation_report.codeflow_post` already
462
+ > exists. An agent told only to "set review" hits that exception and either gives up
463
+ > or leaves the item in `todo` while its code sits landed on the branch.
464
+ >
465
+ > **Supervisor: verify this actually happened before closing the wave.** Query
466
+ > `status` and `implementation_report IS NOT NULL` for every dispatched item. On
467
+ > 2026-07-27 three agents landed real, verified code (`881ad3dac`, `0343de92a`,
468
+ > `b17cd4459`, 189/189 tests, tsc 0) and all three items still read `todo` with no
469
+ > report, because the dispatch prompts omitted this line. That is the identical
470
+ > drift this build was convened to fix a work item asserting `todo` about code
471
+ > that is already on develop. If the agent did not file it, the supervisor files it
472
+ > from measured evidence and flags that it was filed on the agent's behalf.
473
+ - **`"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."`**
474
+ - **`"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."`**
475
+ - **The decomposition items from the work item's checklist** (all `decomp-*` prefixed items). Include them verbatim in the prompt and instruct the agent:
476
+ ```
477
+ 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'):
478
+ - decomp-ui-xxx: <route/file> | action=<action> | expect=<result> | evidence=<artifact>
479
+ - decomp-api-xxx: <route/file> | action=<action> | expect=<result> | evidence=<artifact>
480
+ Tick each item as soon as that specific behavior is implemented and proven. Do NOT batch.
481
+ ```
482
+ - **The test plan items from the work item's checklist** (all `test-*` prefixed items). Include them verbatim in the prompt and instruct the agent:
483
+ ```
484
+ 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'):
485
+ - test-assert-xxx: <description> write a vitest test that proves this
486
+ - test-smoke-xxx: <description> → run the command and confirm the result
487
+ - test-visual-xxx: <description> → note: delegate to UI audit (you cannot verify this yourself)
488
+ - test-contract-xxx: <description> → verify the export/type/shape exists
489
+ Tick each item as you complete it. Do NOT batch — tick immediately after each verification.
490
+ ```
491
+ - Use `run_in_background: true` for parallel execution
492
+ - NEVER let agents overlap on the same files
493
+
494
+ ### Agent Definition-of-Done additions (include in every prompt)
495
+ - **Declare every import in the package's OWN package.json.** Every import an
496
+ agent adds MUST be present in that package's own `package.json`
497
+ dependencies/devDependencies — never rely on monorepo-hoisted deps. A pnpm
498
+ worktree can import a root-hoisted dep (e.g. `vitest`,
499
+ `@supabase/supabase-js`) so `tsc`/`vitest` PASS in the worktree, then `tsc`
500
+ FAILS on a clean develop checkout after merge (lesson
501
+ 2026-06-10-build-card-engine-agent-deps). Agent prompt line: *"Verify that
502
+ every import you add is declared in this package's own package.json do not
503
+ rely on hoisted monorepo deps."*
504
+ - **A server/MCP/API task is NOT done without a committed automated test that
505
+ ships in the SAME commit and exercises EVERY surface.** Manual curl / a single
506
+ `/health` 200 is a proxy, not coverage (lesson 2026-06-10-build-weak-dod-no-tests).
507
+ For a collection (MCP skills, API routes, CLI commands): loop over ALL items
508
+ and assert `output == source` — never a single spot check. Wire an npm script
509
+ and run it green before the item leaves `review`. Agent prompt line: *"This
510
+ task is not done until a committed test in the same commit exercises every
511
+ surface; for collections, loop all items and assert output == source."*
512
+ - **Durable workflow E2E gate (hard):** A task that creates a queue/job,
513
+ background worker, storage hand-off, retry/lease, webhook, or other async
514
+ cross-process workflow MUST ship a committed `test:e2e` (or equivalent)
515
+ harness. Before the task leaves `review`, run it against the deploy-equivalent
516
+ container plus real disposable dependencies (or an isolated mirror) and
517
+ retain its receipt. The harness MUST exercise the public ingress, assert the
518
+ full state transition, assert every persisted output, and clean up fixture
519
+ rows/objects in `finally`; unit tests, mocks, a migration check, Docker
520
+ construction, or a `/health` probe cannot substitute. If no safe disposable
521
+ environment exists, create one within the work package; do not waive this
522
+ gate or mark the item reviewable.
523
+
524
+ 8. **Post-wave test gate (mandatory):**
525
+ After all agents in a wave complete, before proceeding:
526
+ ```bash
527
+ # For each package modified in this wave:
528
+ cd packages/<name> && npx vitest run 2>&1 | tail -20
529
+ ```
530
+ - All tests must pass before proceeding to next wave
531
+ - If tests fail: fix before proceeding
532
+ - NEVER use `pnpm build` or `pnpm turbo test` vitest only per package
533
+ - New code must have tests: if a modified package shows 0 new test files, flag it
534
+
535
+ 9. **After all wave agents complete merge worktrees and push:**
536
+
537
+ Each completed agent returns a worktree branch (e.g. `claude/agent-frontend-abc123`). Merge them all to develop before running the test gate:
538
+
539
+ ```bash
540
+ # For each worktree branch returned by agents in this wave:
541
+ git merge --no-ff <worktree-branch> -m "merge(<agent-type>): <task-title>"
542
+ ```
543
+
544
+ - Resolve any conflicts before proceeding do not skip
545
+ - Worker agents set items to `review` — **do NOT close to `done` yet**
546
+ - After all branches merged, push once:
547
+ ```bash
548
+ if [ "$RDC_TEST" != "1" ]; then
549
+ git push origin develop
550
+ else
551
+ echo "[RDC_TEST] skipping git push"
552
+ fi
553
+ ```
554
+ - Then run the post-wave test gate (Step 8) on the merged state
555
+ - Then run the code-review gate (Step 9b) before the next wave dispatches
556
+ - Continue to next wave
557
+
558
+ **If an agent fails (returns no worktree branch):**
559
+ - Interactive: diagnose before retrying
560
+ - Unattended: retry once; on second failure escalate via advisor
561
+ ```
562
+ BUILD_STATUS: { wave, tasks_done, tasks_failed, commits, escalated: true }
563
+ ```
564
+
565
+ 9b. **Mandatory per-wave code-review gate (runs after merge + test gate, BEFORE next wave dispatches):**
566
+
567
+ ⛔ **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.
568
+
569
+ Dispatch ONE `pr-review-toolkit:code-reviewer` agent with the wave's merged diff:
570
+
571
+ ```
572
+ Agent({
573
+ subagent_type: "pr-review-toolkit:code-reviewer",
574
+ description: "Wave <N> code review",
575
+ prompt: "Review the diff `git diff <wave-base-sha>..HEAD` on develop.
576
+ Focus on: bugs, logic errors, security vulnerabilities, project-convention adherence
577
+ (.claude/rules/*, CLAUDE.md). Apply confidence-based filtering — high-confidence
578
+ findings only. Report severity per finding: critical | high | medium | low.
579
+ Return CODE_REVIEW_COMPLETE with: { critical_count, high_count, medium_count,
580
+ low_count, findings: [{severity, file:line, issue, suggested_fix}] }."
581
+ })
582
+ ```
583
+
584
+ **Severity gate (default — high+ blocks):**
585
+ - `critical` or `high` findings → reopen affected work items to `todo` with finding text in notes; fix in a new wave before continuing
586
+ - `medium` or `low` findings → append to each work item's `implementation_report.flags`; do NOT reopen; validator sees them
587
+ - Zero findings → log `CODE_REVIEW: CLEAN` and proceed to next wave
588
+
589
+ Under `RDC_TEST=1`: echo `[RDC_TEST] skipping code-review dispatch` and proceed.
590
+
591
+ 10. **Mandatory validator gate (runs after ALL waves complete — before any work item closes):**
592
+
593
+ ⛔ **NO work item may be set to `done` without the validator passing it.**
594
+
595
+ Dispatch ONE validator agent with the complete list of `review` work items and the full git diff.
596
+ ⚠️ The validator does NOT use `isolation: "worktree"` — it must read the fully merged develop branch. Omit the isolation parameter for this dispatch only.
597
+
598
+ ```
599
+ "Read {PROJECT_ROOT}/.rdc/guides/agent-bootstrap.md then {PROJECT_ROOT}/.rdc/guides/verify.md.
600
+ Read {PROJECT_ROOT}/.rdc/guides/engineering-behavior.md before validating scope, deviations, and evidence.
601
+ Validate these work items: [list of IDs and titles].
602
+ Apps touched: [list].
603
+ Git diff since build start: [attach or reference].
604
+ You are the ONLY agent that closes work items to done.
605
+ Follow verify.md procedure exactly: tsc → vitest → dev server route probes → record result per item."
606
+ ```
607
+
608
+ The validator:
609
+ - Runs `npx tsc --noEmit` for every touched app/package
610
+ - Starts the dev server and probes every modified route (expects HTTP 200, not 500)
611
+ - Runs vitest for every touched package
612
+ - For every durable workflow, runs the committed E2E harness and rejects the
613
+ item unless its receipt proves public ingress -> queued/running -> terminal
614
+ state, persisted outputs, and fixture cleanup on the deploy-equivalent
615
+ runtime; an absent harness is a hard rejection.
616
+ - **Verifies checklist decomposition quality per work item before functional validation:**
617
+ - Every implementation work item has >= 10 attested `decomp-*`/`test-*` items, meets the per-surface completeness floors (each declared surface covered), and no feature WP ships a 5-6-row checklist
618
+ - Every `decomp-*` item includes route/file, action, expected result, and evidence artifact
619
+ - Any unchecked `decomp-*` item with `required: true` = work item CANNOT be set to `done`
620
+ - Any coarse or non-falsifiable `decomp-*` item = reopen to `todo` with the specific failure
621
+ - **Verifies test plan completion per work item:**
622
+ - For each `test-assert-*` checklist item: confirm a corresponding vitest test exists and passes
623
+ - For each `test-smoke-*` checklist item: run the command and confirm exit code / HTTP status
624
+ - For each `test-visual-*` checklist item: note as "delegated to UI audit" (validator cannot verify visuals)
625
+ - For each `test-contract-*` checklist item: verify the export/type/shape exists in the built code
626
+ - Any unchecked `test-*` item with `required: true` = work item CANNOT be set to `done` (DB enforces this)
627
+ - Sets passing items to `done`, failing items back to `todo` with failure detail
628
+ - Returns `VALIDATOR_COMPLETE` report with test plan status per item
629
+
630
+ **If the validator finds failures:** fix them in a new wave, then re-run the validator. Do not skip.
631
+ **File existence alone is NOT verification.** A route returning 500 is a failure regardless of tsc passing.
632
+ **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.
633
+
634
+ 11. **After verification passes:**
635
+ - All wave commits are already on develop and pushed (Step 9 pushes after each wave merge).
636
+ - Update epic version: `bump_epic_version()`
637
+ - Report summary with verification evidence quoted
638
+
639
+ ## Agent TDD Requirements
640
+
641
+ When dispatching agents, include in every prompt:
642
+ ```
643
+ TDD REQUIREMENT: Write tests FIRST for new functions/modules.
644
+ Run: npx vitest run packages/<name> to verify red → implement → verify green.
645
+ NEVER run pnpm build or pnpm turbo. Use npx vitest run only.
646
+ ```
647
+
648
+ ## Rules
649
+ - Branch: development branch only (auto-commit, no confirmation needed)
650
+ - NEVER let two agents edit the same file
651
+ - NEVER run `pnpm build` (crashes system) — code only
652
+ - Every agent reads its guide file — no exceptions
653
+ - Update Supabase work items IN REAL TIME — not batch at end
654
+ - Push after each wave, not just at the end
655
+ - Unattended: NEVER pause — continue automatically
656
+ - Unattended: max 2 retries per task before escalating to advisor
657
+ - Every Agent() dispatch: `model: <routed>` + `max_turns: 70` — non-negotiable. Every dispatched writer uses `isolation: "worktree"` after the HARD GATE; non-isolated agents are read-only. Model is chosen per task per the routing table in Step 7. Exception: the validator omits isolation because it is read-only and must inspect merged source.
658
+ - Finding an existing file is NOT task completion — verify it satisfies the spec
659
+
660
+ ## Capture lessons (exit step)
661
+
662
+ 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.