@juicesharp/rpiv-pi 2.13.4 → 2.13.6

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 (29) hide show
  1. package/README.md +1 -1
  2. package/extensions/rpiv-core/agents-allowlist.ts +47 -0
  3. package/extensions/rpiv-core/agents-inject.ts +151 -0
  4. package/extensions/rpiv-core/agents-manifest.ts +102 -0
  5. package/extensions/rpiv-core/agents-sync.ts +405 -0
  6. package/extensions/rpiv-core/agents-types.ts +115 -0
  7. package/extensions/rpiv-core/agents.ts +35 -773
  8. package/extensions/rpiv-core/built-in-workflows.ts +13 -1426
  9. package/extensions/rpiv-core/built-ins/citations.ts +1 -1
  10. package/extensions/rpiv-core/built-ins/gate-passes.ts +498 -0
  11. package/extensions/rpiv-core/built-ins/gate-rosters.ts +275 -0
  12. package/extensions/rpiv-core/built-ins/gates.ts +34 -951
  13. package/extensions/rpiv-core/built-ins/index.ts +5 -3
  14. package/extensions/rpiv-core/built-ins/reconcile.ts +1 -1
  15. package/extensions/rpiv-core/built-ins/slice-checks.ts +3 -3
  16. package/extensions/rpiv-core/built-ins/verdict-core.ts +202 -0
  17. package/extensions/rpiv-core/outcome-derivation.ts +2 -1
  18. package/extensions/rpiv-core/pi-compat.ts +59 -0
  19. package/extensions/rpiv-core/run-lane-registry.ts +28 -225
  20. package/extensions/rpiv-core/run-lane-types.ts +240 -0
  21. package/extensions/rpiv-core/sdk-workflow-host.ts +46 -18
  22. package/extensions/rpiv-core/workflows/build.ts +695 -0
  23. package/extensions/rpiv-core/workflows/polish.ts +62 -0
  24. package/extensions/rpiv-core/workflows/shared.ts +300 -0
  25. package/extensions/rpiv-core/workflows/ship.ts +329 -0
  26. package/extensions/rpiv-core/workflows/vet.ts +133 -0
  27. package/package.json +3 -2
  28. package/skills/_shared/stitch-elaborations.mjs +1 -1
  29. package/skills/elaborate/_helpers/validate-workflow-invariant.mjs +7 -5
@@ -1,1433 +1,20 @@
1
1
  /**
2
- * Built-in workflows shipped with rpiv-pi. Each workflow's `stages`
3
- * insertion order IS its linear stage order — `Object.keys(stages)` gives
4
- * the natural read order for previews and traversal alike.
5
- *
6
- * Route edges use `gate(...)` from `@juicesharp/rpiv-workflow`, which
7
- * attaches `.targets` metadata so reachability checks and graph
8
- * introspectors can enumerate possible branches without probing.
9
- *
10
- * These workflows name skills bundled by rpiv-pi (research, design, plan,
11
- * implement, validate, code-review, revise, commit). Installing
12
- * rpiv-workflow without rpiv-pi means these workflows aren't loaded —
13
- * users author their own over their own skills.
2
+ * Composition barrel for the built-in `/wf` workflows shipped with rpiv-pi.
3
+ * Each workflow's `defineWorkflow` graph lives in its own module under
4
+ * `./workflows/` — build / vet / polish / ship — wiring the cross-workflow
5
+ * gate and prompt factories from `./workflows/shared.ts`; `metaWorkflow`
6
+ * rides in from `./meta/presets.js`. This file only composes the array and
7
+ * re-exports the ship fanout surface the tests import: the load specifier
8
+ * (register-built-in-workflows.ts's guarded dynamic import) and the
9
+ * `builtInWorkflows` named export are the stable contract.
14
10
  */
15
11
 
16
- import { execFileSync } from "node:child_process";
17
- import { dirname, isAbsolute, join } from "node:path";
18
- import { fileURLToPath } from "node:url";
19
- import {
20
- acts,
21
- defineRoute,
22
- defineWorkflow,
23
- type EdgeFn,
24
- eq,
25
- fanin,
26
- gate,
27
- gitCommitOutcome,
28
- gt,
29
- handleToString,
30
- match,
31
- type PromptFn,
32
- produces,
33
- type RunView,
34
- setRouteNote,
35
- type Workflow,
36
- } from "@juicesharp/rpiv-workflow/registration";
37
- import { rpivBucketOutcome } from "./artifact-collector.js";
38
- import {
39
- allDimensionsPass,
40
- CODE_CONFIRM_FANOUT,
41
- CODE_DIMENSION_FANOUT,
42
- CODE_PANEL_PROGRESS,
43
- COMMIT_BASELINE_PROMPT,
44
- captureGoal,
45
- captureReviewScope,
46
- codeDemote,
47
- codeGatePasses,
48
- codeSnapshot,
49
- confirmDue,
50
- designOutcome,
51
- ELABORATE_PHASE_FANOUT,
52
- elaborationOutcome,
53
- freshVerdicts,
54
- haltPreflight,
55
- IMPLEMENT_DAG_FANOUT,
56
- IMPLEMENT_PLANS_FANOUT,
57
- implementScopeCheck,
58
- implementScopeCheckVet,
59
- latestArtifactPath,
60
- latestFsArtifact,
61
- latestPlans,
62
- latestVerdictPerDimension,
63
- PLAN_CONFIRM_FANOUT,
64
- PLAN_DIMENSION_FANOUT,
65
- PLAN_DIMENSIONS,
66
- PLAN_PANEL_PROGRESS,
67
- planAuthoredRisks,
68
- planCitationCheck,
69
- planDemote,
70
- planGatePasses,
71
- planSnapshot,
72
- REVIEW_PHASE_ITERATE,
73
- RISK_DIMENSION,
74
- reconcile,
75
- remediationOutcome,
76
- rulingEffectivePass,
77
- SHIP_DIMENSION_FANOUT,
78
- SHIP_PANEL_PROGRESS,
79
- SLICE_DESIGN_FANOUT,
80
- SLICE_DIMENSION_FANOUT,
81
- SLICE_DIMENSIONS,
82
- SLICE_PANEL_PROGRESS,
83
- SYNTH_CLUSTER_FANOUT,
84
- scopeQuarantine,
85
- seedLiftStuck,
86
- seedOnlyCiteFail,
87
- shipGatePasses,
88
- shipRoster,
89
- shipVerdictOutcome,
90
- sliceGatePasses,
91
- sliceSeedLift,
92
- sliceStructureCheck,
93
- subplanCoverageCheck,
94
- subplanGatePasses,
95
- unitFailedDimensions,
96
- VALIDATE_GOAL_PROMPT,
97
- type VerdictRecord,
98
- verdictBlocks,
99
- verdictOutcome,
100
- verdictRiskRulings,
101
- } from "./built-ins/index.js";
12
+ import type { Workflow } from "@juicesharp/rpiv-workflow/registration";
102
13
  import { metaWorkflow } from "./meta/presets.js";
103
-
104
- // The code-review stage's output schema is no longer declared here — every
105
- // code-review stage sources it from the skill's contract `produces.data`
106
- // (`blockers_count` required), validated by the runtime output loop via
107
- // `effectiveOutputSchema`. One source of truth, in the skill, not copy-pasted
108
- // per workflow. Every workflow with a `code-review` stage — polish AND vet —
109
- // routes on the same numeric gate: `gate("blockers_count", { <fix>: gt(0), commit: eq(0) }, "commit")`.
110
-
111
- // ===========================================================================
112
- // polish — architecture-review → blueprint (iterate, per review phase) →
113
- // implement → validate → code-review → (blueprint loop) | commit
114
- // For a large architecture review that can't be planned in one pass:
115
- // plan each review phase sequentially, each plan building on the
116
- // ones before it, then implement/validate/review the lot.
117
- // ===========================================================================
118
-
119
- /**
120
- * Hand the single validate session EVERY plan from the latest blueprint pass
121
- * (`latestPlans`). The runner's default rolling-primary — and a plain
122
- * `reads: ["plans"]`, which only reads `.at(-1)` — would point validate at the
123
- * LAST plan alone, leaving earlier phases unvalidated. A `prompt` stage owns
124
- * its whole message, so the `/skill:validate` prefix is explicit.
125
- */
126
- const VALIDATE_PLANS_PROMPT: PromptFn = ({ state, cwd }) => {
127
- const paths = latestPlans(state, cwd)
128
- .flatMap((o) => o.artifacts)
129
- .filter((a) => a.handle.kind === "fs")
130
- .map((a) => handleToString(a.handle));
131
- return `/skill:validate ${paths.join(" ")}`;
132
- };
133
-
134
- const polishWorkflow = defineWorkflow({
135
- name: "polish",
136
- description:
137
- "Architecture-review-driven polish: review → per-phase blueprint (sequential, accumulating) → implement → validate → code-review → commit. Best when a large architecture review can't be planned in one pass and each phase's plan must build on the ones before it.",
138
- start: "architecture-review",
139
- stages: {
140
- "architecture-review": produces(),
141
- blueprint: produces({ loop: REVIEW_PHASE_ITERATE }),
142
- implement: acts({ loop: IMPLEMENT_PLANS_FANOUT, reads: ["plans"] }),
143
- validate: produces({ prompt: VALIDATE_PLANS_PROMPT }),
144
- "code-review": produces(),
145
- commit: acts({ outcome: gitCommitOutcome }),
146
- },
147
- edges: {
148
- "architecture-review": "blueprint",
149
- blueprint: "implement",
150
- implement: "validate",
151
- validate: "code-review",
152
- // Backward edge: code-review → blueprint re-plans (implement needs a plan).
153
- // The iterate stage re-runs over every review phase; bounded by the
154
- // runner's default maxBackwardJumps (3 → up to 4 review iterations)
155
- // under the absolute per-stage maxLaps ceiling (default 8; both
156
- // budgets fresh per invocation — a resume re-opens the loop).
157
- "code-review": gate("blockers_count", { blueprint: gt(0), commit: eq(0) }, "commit"),
158
- commit: "stop",
159
- },
160
- });
161
-
162
- // ===========================================================================
163
- // build — goal (verbatim-brief capture) → research → acceptance (the
164
- // goal-derived executable standard of completion) → slice → slice-check
165
- // (deterministic floor) → slice-grade (design-readiness, slice-fix loop)
166
- // → slice-design (fanout) → design-review (one human checkpoint) →
167
- // subplan (cluster fanout) → plan → plan-grade (plan-fix loop) →
168
- // code (fanout) → code-splice → code-grade (code-fix loop) →
169
- // implement → implement-scope-check → reconcile → validate → commit
170
- // The sliced, panel-gated heavy path: capture the user's brief verbatim as the
171
- // `goal` channel (the north star the judgment seams — the two grade panels'
172
- // completeness/correctness dimensions and validate — anchor against), research
173
- // the brief (so every slice
174
- // rests on a real, cited footing and the plan gate can grade architecture-fit),
175
- // decompose it into independent
176
- // vertical slices, gate that breakdown BEFORE any design so each slice is
177
- // chewable by one design-slice pass. The gate is two-phase: a DETERMINISTIC
178
- // floor (`slice-check`) enforces dependency-cycle freedom and brief-coverage
179
- // conservation (a slice-fix may redistribute the brief, never drop scope to pass),
180
- // then ONE LLM `design-readiness` judgment reconciles the formerly-opposing
181
- // split/merge forces. Then design every slice in parallel and pause at ONE
182
- // consolidated human checkpoint (`design-review`) — the single fan-in seam where
183
- // every design exists and nothing parallel runs — to accept or adjust the
184
- // proposed interfaces/data types before synthesis. Then merge hierarchically
185
- // (per-cluster sub-plans → one plan) so no pass holds every design, gate the
186
- // plan on quality dimensions BEFORE any code, elaborate code per phase and
187
- // splice it in, re-grade the code-bearing plan, then implement/validate/commit.
188
- // ===========================================================================
189
-
190
- /**
191
- * `goal` displaces `research` as build's start stage, and ONLY the start stage
192
- * receives `originalInput` as its skill arg (`stageEntryArgs` case 1) — a plain
193
- * `produces()` research would silently receive the rolling primary (the goal
194
- * FILE PATH) instead of the brief text. A prompt stage owns its whole message,
195
- * so this rebuilds research's pre-goal dispatch byte-for-byte; the outcome
196
- * deriver still wires the `research` bucket off the record key (the polish
197
- * `validate` prompt-stage precedent).
198
- */
199
- const RESEARCH_BRIEF_PROMPT: PromptFn = ({ state }) => `/skill:research ${state.originalInput}`;
200
-
201
- /**
202
- * ship's research front-load — a LEANER grounding than build's `/skill:research`
203
- * pass, tiered to the brief's pre-chewedness. Bypasses the research skill: a
204
- * pre-chewed brief (root cause, files to touch, or fix already named) gets
205
- * VERIFICATION, not re-derivation — at most ONE verify-only `codebase-analyzer`
206
- * dispatch confirming each named anchor, or none at all when the anchors are
207
- * plain file paths the stage child reads itself; a symptom-only brief keeps at
208
- * most TWO targeted `codebase-analyzer` dispatches (sequentially — never
209
- * parallel, never `run_in_background`) mapping only what a lightweight
210
- * single-phase plan needs to be correct. The agent then `Write`s a grounding
211
- * doc under `.rpiv/artifacts/research/` (the prompt names the directory only —
212
- * a full example path would prime the collector's pre-write path-echo hazard),
213
- * where the research bucket collector harvests it — the grade panel's
214
- * architecture-fit dimension threads it as `--context` exactly as build's
215
- * research artifact does. A prompt stage (no skill), so the stage name
216
- * `research` drives outcome derivation (research contract → `research`
217
- * bucket), exactly as build's `RESEARCH_BRIEF_PROMPT` stage does — the prompt
218
- * text, not dispatch, is what differs. The prompt also pins a progress-marker
219
- * protocol — a `[Classified]:` first line naming the chosen tier,
220
- * `[Dispatch N/M]:` / `[Dispatch N/M returned]:` echo lines around each
221
- * grounding dispatch (plus the `[Dispatch]: none` zero-dispatch escape) — so
222
- * the lane console's live tail narrates the otherwise-silent batch window;
223
- * markers are transcript text only and never carry an artifacts path before
224
- * the write.
225
- */
226
- const SHIP_RESEARCH_PROMPT: PromptFn = ({ state }) =>
227
- [
228
- "Ground this brief for a lightweight ship plan.",
229
- "Do NOT dispatch /skill:research — size the grounding to what the brief already carries.",
230
- "Classify the brief first, then follow ONLY the matching tier:",
231
- "- Tier A (pre-chewed — the brief names the root cause, the files to touch, or the fix): VERIFY, don't re-derive. Dispatch at most ONE codebase-analyzer subagent (sequentially — never parallel, never run_in_background) in verify-only mode, confirming or denying each named anchor against the actual code and reporting drift with the corrected file:line. If the anchors are plain file paths, dispatch nothing — Read/Grep them yourself.",
232
- "- Tier B (symptom only — the brief names none of the three: no root cause, no files, no fix): dispatch at most TWO targeted codebase-analyzer subagents (sequentially — never parallel, never run_in_background) to map only what a single-phase plan needs to be correct: entry points, the relevant module's shape, and the conventions the implement lane must match.",
233
- "Progress markers — echo your status as you go: the first line of your reply, before anything else, is [Classified]: Tier A — verify-only or [Classified]: Tier B — map ground truth (the tier you classified the brief into). Before each dispatch, emit [Dispatch N/M]: <purpose phrase>; once it lands, emit [Dispatch N/M returned]: <outcome phrase> (M is the tier's dispatch ceiling: 1 for Tier A, 2 for Tier B). For Tier A's zero-dispatch escape, emit [Dispatch]: none — reading the named anchors directly. Markers are transcript text only, never artifact content, and must NEVER contain a .rpiv/artifacts/ path before the file is written.",
234
- "",
235
- `Brief: ${state.originalInput}`,
236
- "",
237
- "Then Write the grounding doc under .rpiv/artifacts/research/ (timestamped filename, under 150 lines) carrying the findings with verifiable file:line citations — Code References, Integration Points, the relevant module's shape, and the conventions the implement lane must match — announce the written file's path in your final message, and stop.",
238
- ].join("\n");
239
-
240
- /**
241
- * Verdict channels — grade writes JSON to `.rpiv/artifacts/verdicts/`, so
242
- * these use the disk-first verdict factory in `built-ins/verdict-outcome.ts`
243
- * (NOT the md `rpivBucketOutcome`). The slice gate and plan gate publish to
244
- * DISTINCT named channels (same dir, different artifact basenames) so their
245
- * verdicts never collide and `plan-fix`/`code-fix` can pick each via the
246
- * `-verdicts` suffix convention.
247
- */
248
- const sliceVerdictOutcome = verdictOutcome("slice-verdicts", "slices");
249
- const planVerdictOutcome = verdictOutcome("plan-verdicts", "plans");
250
- // The post-splice code gate re-grades the now code-bearing plan on its own
251
- // channel, so its verdicts never mix with the pre-elaborate plan gate's. Named
252
- // for the object under judgment — the code the gate grades — completing the
253
- // slice-verdicts / plan-verdicts / code-verdicts parallel.
254
- const codeVerdictOutcome = verdictOutcome("code-verdicts", "plans");
255
-
256
- /**
257
- * Absolute path to rpiv-pi's bundled deterministic stitch script. Resolved off
258
- * this module's own URL so it points inside the installed package at runtime
259
- * (built-in-workflows lives in extensions/rpiv-core; the script in skills/_shared).
260
- */
261
- const STITCH_SCRIPT = join(
262
- dirname(fileURLToPath(import.meta.url)),
263
- "..",
264
- "..",
265
- "skills",
266
- "_shared",
267
- "stitch-elaborations.mjs",
268
- );
269
-
270
- // ===========================================================================
271
- // vet — goal → code-review → (blueprint → implement → implement-scope-check
272
- // → validate → loop) | commit. Examine existing changes; capture the
273
- // brief as a goal artifact, review, and if not approved blueprint a fix
274
- // plan, implement it, scope-check it, validate, and re-review. Loops
275
- // until approved. NOTE: defined here (after captureGoal /
276
- // implementScopeCheckVet) rather than beside polish because its graph
277
- // references those later-declared `const`s — the same precedent
278
- // buildWorkflow follows (defined after its deps).
279
- // ===========================================================================
280
-
281
- /**
282
- * Scope-floor gate factory — build and vet wire IDENTICAL tiered routes; a
283
- * factory (not one shared EdgeFn) so each workflow's route-note symbol never
284
- * aliases the other's. Branches on the floor's tiered `ScopeVerdict`:
285
- * "pass" AND tracked "excess" continue to `reconcile` — the floor demotes
286
- * tracked excess to downstream adjudication (build threads the verdict to
287
- * validate via `--scope`; vet's review loop sees the whole diff) instead of
288
- * halting, the citation-floor precedent (demote where a remedy or adjudicator
289
- * exists). The excess pick is an HONEST pass-through: it attaches a route note
290
- * naming the downstream adjudicator (`opts.deferredTo` — validate on build,
291
- * code-review on vet) so the end-of-run recap's `routingNotes` can surface the
292
- * deferral; the pass pick attaches no note (a clean pass needs no
293
- * explanation). "untracked-only" takes the deterministic `scope-quarantine`
294
- * arm.
295
- * Anything else — a missing or corrupt verdict — terminates ("stop" with a
296
- * route note): the integrity clause every de-halting change has preserved.
297
- * A `match` cannot send two enum values to one target, hence `defineRoute`;
298
- * `readsData: false` — the route consults the stage's published channel, not
299
- * its projected output (matching the other deterministic-floor routes).
300
- */
301
- const scopeFloorGate = (opts: { deferredTo: string }): EdgeFn => {
302
- const route: EdgeFn = defineRoute(
303
- ["reconcile", "scope-quarantine", "stop"],
304
- ({ state }) => {
305
- const verdict = (state.named["implement-scope-check"]?.at(-1)?.data as { verdict?: unknown } | undefined)
306
- ?.verdict;
307
- if (verdict === "untracked-only") return "scope-quarantine";
308
- if (verdict === "pass") return "reconcile";
309
- if (verdict === "excess") {
310
- // Honest pass-through: the floor did not PASS, it DEFERRED — record why
311
- // on the routing row (the recap's routingNotes) instead of a silent
312
- // reconcile that reads like a clean pass.
313
- setRouteNote(route, `pass-through: implement-scope-check defers to ${opts.deferredTo}`);
314
- return "reconcile";
315
- }
316
- setRouteNote(
317
- route,
318
- `implement-scope-check verdict ${JSON.stringify(verdict ?? null)} is not a ScopeVerdict — terminated (integrity stop)`,
319
- );
320
- return "stop";
321
- },
322
- { readsData: false },
323
- );
324
- return route;
325
- };
326
-
327
- /**
328
- * The reconciliation gate — pass ⇒ validate; fail ⇒ the `reconcile-fix` repair
329
- * arm; missing/corrupt verdict ⇒ STOP (integrity clause, exactly the `match` it
330
- * replaces). The arm exists because every reconcile failure class — a malformed
331
- * directive, a stale `find`, a non-test target — is a defect in the PLAN's
332
- * directive text, which is `amend`'s exact authority ("fix the artifact, never
333
- * the repo"); the old no-arm route stopped the run on a fail that hand-repairing
334
- * the TREE could never clear (run 2026-08-31_15-21-14-57d0: a multi-line
335
- * directive re-failed every resume because the defect lived in the plan
336
- * artifact, which nothing in the pipeline could edit). Reconcile itself stays
337
- * the sole test-file writer — the arm only repairs directives; the loop
338
- * re-enters reconcile to apply them.
339
- *
340
- * A factory for the validateGate/scopeFloorGate reason — each workflow's
341
- * route-note symbol must never alias the other's. `maxFixRounds` caps the
342
- * amend hops a fail may buy, counted from the `reconcile-fix` channel — the
343
- * channel ONLY the arm itself writes (its outcome publishes there, not on
344
- * `plans`), mirroring validateGate's `remediation`-channel cap. It must NOT
345
- * count reconcile-channel entries: reconcile re-executes on paths that spend
346
- * no amend hop — ship's validate-fix loop re-enters through
347
- * implement-scope-check → reconcile, and a resume replays entries — so an
348
- * entry-count budget let the validate-fix loop spend the arm's only round
349
- * before the arm ever ran, with a stop-note claiming a fix round that never
350
- * happened (review 2026-08-31 I1; the fourth instance of the cap-must-read-a-
351
- * channel-the-arm-writes lesson). Build/vet pass no cap (the runner's
352
- * per-destination backward-jump budget on `reconcile-fix` is theirs, the
353
- * plan-fix precedent); ship caps at ONE — the same single bounded hop its
354
- * stop-on-fail identity concedes at the validate gate.
355
- */
356
- const reconcileGate = (opts?: { maxFixRounds?: number }): EdgeFn => {
357
- const maxFixRounds = opts?.maxFixRounds ?? Number.POSITIVE_INFINITY;
358
- const route: EdgeFn = defineRoute(
359
- ["validate", "reconcile-fix", "stop"],
360
- ({ state }) => {
361
- const verdict = (state.named.reconcile?.at(-1)?.data as { verdict?: unknown } | undefined)?.verdict;
362
- if (verdict === "pass") return "validate";
363
- if (verdict !== "fail") {
364
- setRouteNote(
365
- route,
366
- `reconcile verdict ${JSON.stringify(verdict ?? null)} matched no branch — terminated (no fallback)`,
367
- );
368
- return "stop";
369
- }
370
- const roundsSpent = state.named["reconcile-fix"]?.length ?? 0;
371
- if (roundsSpent >= maxFixRounds) {
372
- setRouteNote(
373
- route,
374
- `reconcile still fails after ${roundsSpent} amend round${roundsSpent === 1 ? "" : "s"} — repair the #### Reconciliation directives in the PLAN artifact by hand (the failure lives in the plan text, not the tree), then resume`,
375
- );
376
- return "stop";
377
- }
378
- return "reconcile-fix";
379
- },
380
- { readsData: false },
381
- );
382
- return route;
383
- };
384
-
385
- /**
386
- * The `reconcile-fix` arm's dispatch — `/skill:amend` over the latest plan and
387
- * the reconcile verdict. A PROMPT stage (owning its whole message, the
388
- * VALIDATE_PLANS_PROMPT precedent) because amend's generic flag parser keys
389
- * verdict inputs on the `-verdicts` name suffix, and reconcile's script stage
390
- * publishes on its stage-key channel `reconcile` — a `reads: ["reconcile"]`
391
- * skill stage would thread `--reconcile <path>`, which amend reads as a SECOND
392
- * artifact flag and refuses. The explicit `--reconcile-verdicts` spelling
393
- * parses as exactly one artifact (`--plans`) + one verdicts flag. The gate only
394
- * dispatches this arm on a fail verdict, so both channel reads are present by
395
- * construction; a torn state degrades to amend's own front-door refusal
396
- * (exactly-one-artifact + at-least-one-verdicts), never a silent guess.
397
- */
398
- const RECONCILE_FIX_PROMPT: PromptFn = ({ state }) => {
399
- const parts = ["/skill:amend"];
400
- const plan = latestFsArtifact(state, "plans");
401
- if (plan) parts.push("--plans", handleToString(plan.handle));
402
- const verdict = state.named.reconcile?.at(-1)?.artifacts.find((a) => a.handle.kind === "fs");
403
- if (verdict) parts.push("--reconcile-verdicts", handleToString(verdict.handle));
404
- return parts.join(" ");
405
- };
406
-
407
- /**
408
- * The arm's outcome — the plans-bucket collector publishing on the arm's OWN
409
- * `reconcile-fix` channel. Amend re-emits the plan IN PLACE (same path, its
410
- * hard rule), so the `plans` channel's latest entry stays correct without a
411
- * republish; what the channel choice buys is the round counter ONLY the arm
412
- * increments, which `reconcileGate`'s cap reads (the validateGate/
413
- * `remediation` pattern — see the gate doc for why counting reconcile
414
- * executions instead let the validate-fix loop spend the budget).
415
- */
416
- const RECONCILE_FIX_OUTCOME = { ...rpivBucketOutcome("plans"), name: "reconcile-fix" };
417
-
418
- const vetWorkflow = defineWorkflow({
419
- name: "vet",
420
- description:
421
- "Examine existing changes for approval; loop a fix cycle if not approved. Best when a diff already exists (yours or a teammate's) and you want a structured review with optional repair. Chain: goal → code-review → (blueprint → implement → implement-scope-check → reconcile → validate → loop) → commit.",
422
- start: "goal",
423
- stages: {
424
- // Capture the user's brief verbatim on its own `goal` channel, and snapshot
425
- // the run-start pre-existing-dirty paths (role "baseline"). Uses
426
- // `captureReviewScope` — build's capture minus the garbage-brief floor,
427
- // because vet's input is a review-scope token ("staged", a hash) that is
428
- // legitimately shorter than any brief the floor admits — so the scope-check's
429
- // `reads: ["plans", "goal"]` resolves a baseline to subtract and the goal md
430
- // rides the channel face. `goal` as start publishes the goal-md as
431
- // `artifacts[0]`; `code-review` is a plain `produces()` SKILL stage (skill
432
- // defaults to its stage key "code-review"), so it inherits that goal-md PATH
433
- // as its rolling primary — the same pattern polish's code-review uses,
434
- // and the fallback Risk r1's note conceded "likely tolerates a goal-md-path
435
- // arg." The goal-md's CONTENT is the brief (`captureGoal` writes
436
- // `state.originalInput` into it), so the skill still reaches it.
437
- //
438
- // NOTE: the plan's r1 resolution made code-review PROMPT-dispatched to
439
- // preserve `state.originalInput` byte-for-byte, but that is REVERSED here: a
440
- // prompt stage carries NO skill, so the `code-review` contract no longer
441
- // attaches its `outputSchema` and the `blockers_count` gate would read
442
- // UNVALIDATED data (NaN-route risk, not just a warning). Keeping it a skill
443
- // stage keeps `skill="code-review"` → contract schema attaches → validated.
444
- goal: produces.script({ run: captureReviewScope }),
445
- "code-review": produces(),
446
- blueprint: produces(),
447
- // Dep-gated DAG variant: implement phases now
448
- // carry `id: phase-<n>` + `deps` derived from each phase's `files:` overlap /
449
- // authored `depends_on`, so the host cap may fan them out in parallel.
450
- implement: acts({ loop: IMPLEMENT_DAG_FANOUT, reads: ["plans"] }),
451
- // Deterministic scope floor (no LLM): the lane may write ONLY the union of
452
- // every plan iteration's declared `files:` (vet's loop pushes DISTINCT
453
- // non-superseding fix plans, so the declared set is the UNION over the full
454
- // `plans` history — `implementScopeCheckVet`). The `from` form suppresses
455
- // the READS_DATA outputSchema lint, so no schema is declared, matching
456
- // `slice-check`/`plan-cite-check`. Tiered route (scopeFloorGate): pass and
457
- // tracked excess → reconcile (the review loop adjudicates the recorded
458
- // findings), untracked-only → scope-quarantine, missing verdict → STOP.
459
- "implement-scope-check": produces.script({ reads: ["plans", "goal"], run: implementScopeCheckVet }),
460
- // Deterministic remedy arm for the untracked-only tier: move (never
461
- // delete) run-created untracked excess under .rpiv/tmp/scope-quarantine/
462
- // and publish a manifest, then re-enter the floor — see scopeQuarantine.
463
- "scope-quarantine": produces.script({ reads: ["implement-scope-check"], run: scopeQuarantine }),
464
- // Deterministic post-implement reconciliation (no LLM) — the SAME `reconcile`
465
- // run-function as build (no vet twin): applies every `#### Reconciliation`
466
- // directive (write-restricted to the plan's declared write-set), fail-soft. Pass ⇒ validate;
467
- // fail ⇒ the reconcile-fix arm (see reconcileGate); missing ⇒ STOP.
468
- // `reads: ["plans"]` only — no run-start goal baseline.
469
- reconcile: produces.script({ reads: ["plans"], run: reconcile }),
470
- // Repair arm for the reconciliation gate: /skill:amend over the plan's
471
- // directives from the reconcile verdict (a prompt stage — see
472
- // RECONCILE_FIX_PROMPT), re-emitting the plan latest-wins, then back
473
- // through reconcile to apply. Bounded by the runner's per-destination
474
- // backward-jump budget (the plan-fix precedent).
475
- "reconcile-fix": produces.prompt({ prompt: RECONCILE_FIX_PROMPT, outcome: RECONCILE_FIX_OUTCOME }),
476
- validate: produces(),
477
- commit: acts({ outcome: gitCommitOutcome }),
478
- },
479
- edges: {
480
- goal: "code-review",
481
- // Same numeric gate as polish: zero remaining blockers → commit;
482
- // any blockers → loop a fix pass through blueprint. The `blockers_count`
483
- // field is sourced + validated from the code-review contract.
484
- "code-review": gate("blockers_count", { blueprint: gt(0), commit: eq(0) }, "commit"),
485
- blueprint: "implement",
486
- // Scope-check inserts BEFORE validate, INSIDE the review-fix loop. Pass →
487
- // validate; fail/missing terminates (STOP, no fallback). Byte-for-byte
488
- // build's route.
489
- implement: "implement-scope-check",
490
- // Scope-check still gates onward into `reconcile` (not validate): the
491
- // coherence backstop runs after the write-set is judged. Tiered route —
492
- // see scopeFloorGate: pass/excess ⇒ reconcile (excess carries the
493
- // code-review pass-through note), untracked-only ⇒ the quarantine arm,
494
- // missing/corrupt verdict ⇒ STOP.
495
- "implement-scope-check": scopeFloorGate({ deferredTo: "code-review" }),
496
- // Deterministic re-entry after the quarantine arm: a plain string edge
497
- // (non-counted, mirroring build's validate-fix hop) with guaranteed
498
- // progress — quarantined paths leave the dirty set, so the re-check
499
- // either passes or reveals tracked drift. At most one quarantine hop per
500
- // gate entry; no new loop budget.
501
- "scope-quarantine": "implement-scope-check",
502
- // Reconciliation gate. Pass ⇒ validate; a `fail` (malformed directive /
503
- // absent find / non-test target — all plan-TEXT defects) ⇒ the
504
- // reconcile-fix amend arm; a missing verdict ⇒ STOP (integrity clause).
505
- reconcile: reconcileGate(),
506
- // Deterministic re-entry after the amend arm: reconcile re-parses the
507
- // repaired directives and applies them (a plain string edge — the
508
- // counted decision is the gate's reconcile-fix pick).
509
- "reconcile-fix": "reconcile",
510
- // Backward edge: validate → code-review creates the review-fix loop —
511
- // UNCHANGED. The scope-check inserts before validate, so a failing scope
512
- // verdict halts before re-review, and a passing one flows into validate and
513
- // back to code-review exactly as today. Bounded by the runner's default
514
- // maxBackwardJumps (3 → at most 4 review iterations) under the absolute
515
- // per-stage maxLaps ceiling (default 8; both budgets fresh per
516
- // invocation — a resume re-opens the loop).
517
- validate: "code-review",
518
- commit: "stop",
519
- },
520
- });
521
-
522
- /**
523
- * The classifying validate gate — classifies a failing verdict BEFORE routing
524
- * to the repair arm. `remediate`'s work-list is contractually the report's
525
- * `pass: false` risk rulings plus its structured `blockers:` entries; a
526
- * `verdict: fail` carrying NEITHER (run 2026-08-22_12-14-12-64eb: two
527
- * whole-plan gate failures recorded only in report prose) has no handle the
528
- * arm may act on, so routing it to `validate-fix` buys a provably futile lap
529
- * — the arm drift-escapes without an edit and the unchanged tree re-validates
530
- * to the identical verdict until the backward-jump guard halts the run. Such
531
- * a fail STOPs at the gate with a route note naming why (the ship-gate
532
- * `setRouteNote` pattern; a noted decision stop records as a halt). The
533
- * repair-arm authority rule the slice gate learned the same way: a gate may
534
- * only loop into an arm whose authority covers the failure class.
535
- *
536
- * A factory (not one shared EdgeFn) for the scopeFloorGate reason — each
537
- * workflow's route-note symbol must never alias the other's. `maxFixRounds`
538
- * caps the remediation hops a remediable fail may buy: each `validate-fix`
539
- * pass publishes exactly one digest on the `remediation` channel, so the
540
- * channel length IS the rounds already spent. Build passes no cap (the
541
- * runner's backward-jump guard is its budget); ship caps at ONE — the single
542
- * bounded hop its stop-on-fail identity concedes (run 7299: a docs-gap
543
- * `fail` at the last stage stranded ~50 min of verified implementation).
544
- *
545
- * Reads the `validation` channel (validate's contract-derived publish bucket
546
- * — a prompt stage owns its message and can't inherit its contract's output
547
- * schema, so the gate folds the channel, never the raw stage output). A
548
- * missing/unexpected verdict stays terminal STOP, exactly as the `match` it
549
- * replaces — un-anticipated data can never route INTO commit OR the repair arm.
550
- */
551
- const validateGate = (opts?: { maxFixRounds?: number }): EdgeFn => {
552
- const maxFixRounds = opts?.maxFixRounds ?? Number.POSITIVE_INFINITY;
553
- const route: EdgeFn = defineRoute(
554
- ["commit", "validate-fix", "stop"],
555
- ({ state }) => {
556
- const latest = state.named.validation?.at(-1);
557
- const data = latest?.data as { verdict?: unknown; blockers?: unknown } | undefined;
558
- if (data?.verdict === "pass") return "commit";
559
- if (data?.verdict !== "fail") {
560
- setRouteNote(
561
- route,
562
- `validate verdict ${JSON.stringify(data?.verdict ?? null)} matched no branch — terminated (no fallback)`,
563
- );
564
- return "stop";
565
- }
566
- // Remediable handles: `pass: false` risk rulings (the arm's original
567
- // work-list) + structured `blockers:` entries (whole-plan gate failures
568
- // the validate skill attributes with a runnable command + in-delta file).
569
- const failedRulings = latest ? verdictRiskRulings(latest).filter((r) => !r.pass).length : 0;
570
- const blockers = Array.isArray(data.blockers) ? data.blockers.length : 0;
571
- if (failedRulings + blockers === 0) {
572
- setRouteNote(
573
- route,
574
- "validate failed with no remediable handle (no pass:false risk ruling, no blockers entry) — the remediation arm cannot act; fix manually or revise the plan",
575
- );
576
- return "stop";
577
- }
578
- if ((state.named.remediation?.length ?? 0) >= maxFixRounds) {
579
- setRouteNote(
580
- route,
581
- `validate still fails after ${maxFixRounds} remediation round${maxFixRounds === 1 ? "" : "s"} — fix manually, then resume to re-validate`,
582
- );
583
- return "stop";
584
- }
585
- return "validate-fix";
586
- },
587
- { readsData: false },
588
- );
589
- return route;
590
- };
591
-
592
- /**
593
- * The repair-arm progress gate — the deterministic no-op backstop. The
594
- * `remediation` channel carries `remediationOutcome`'s `{ changed }` (a
595
- * git-only tree digest snapshotted around the `validate-fix` stage): an
596
- * unchanged tree makes the re-validate lap provably futile (validate's
597
- * verdict is a function of the tree), so it STOPs with a note instead of
598
- * burning a backward-jump on an identical verdict. Only an explicit
599
- * `changed: false` stops — a missing signal (non-repo, git failure, absent
600
- * channel) proceeds, the worktree-digest degrade doctrine. A factory for the
601
- * same note-symbol-aliasing reason as `validateGate`. NOTE the resume
602
- * asymmetry this stop relies on: the runner never re-dispatches a halted
603
- * SIDE-EFFECT gate stage — resume re-enters at this gate's onward target
604
- * (implement-scope-check), so a hand-fix after this stop re-verifies
605
- * end-to-end instead of replaying a remediation that would no-op again.
606
- */
607
- const validateFixGate = (): EdgeFn => {
608
- const route: EdgeFn = defineRoute(
609
- ["implement-scope-check", "stop"],
610
- ({ state }) => {
611
- const data = state.named.remediation?.at(-1)?.data as { changed?: unknown } | undefined;
612
- if (data?.changed !== false) return "implement-scope-check";
613
- setRouteNote(
614
- route,
615
- "remediation left the working tree unchanged — re-validating cannot change the verdict; fix manually or revise the plan",
616
- );
617
- return "stop";
618
- },
619
- { readsData: false },
620
- );
621
- return route;
622
- };
623
-
624
- /**
625
- * The fix-arm note for a dead grade unit — the dimension soft-halted (after
626
- * its retry budget ran out, when the panel wires one) and left no verdict to
627
- * fold. Naming it keeps the failure legible and the repair targeted: the fix
628
- * arm re-enters the panel, `dimensionsToRegrade` still lists the dimension as
629
- * pending, and a healthy re-dispatch grades it for real.
630
- */
631
- const unitFailedNote = (dims: readonly string[]): string => `unit-failed: ${dims.join(", ")} produced no verdict`;
632
-
633
- /** The slice gate's grade edge — design-readiness pass ⇒ design; a dead
634
- * dimension unit ⇒ slice-fix with the note (a verdict-less dead dimension is
635
- * never a classification candidate). A SEED-ONLY cite fail (every finding
636
- * naming a concrete seed to add) ⇒ the deterministic `slice-seed-lift` arm,
637
- * which appends the seeds and re-enters `slice-check` for the discharge
638
- * stamp; anything else ⇒ slice-fix. Belt-and-suspenders for the live graph:
639
- * the slice roster is one dimension, so a double miss makes the generation
640
- * all-failed and `haltWhenAllFailed` halts at the panel close before any
641
- * route runs — the arms pin the route contract for any future multi-dimension
642
- * slice roster and for constructed-state trails. */
643
- const sliceGradeRoute: EdgeFn = defineRoute(
644
- ["slice-design", "slice-seed-lift", "slice-fix"],
645
- ({ state }) => {
646
- if (sliceGatePasses(state)) return "slice-design";
647
- const unitFailed = unitFailedDimensions(state, "slices", "slice-verdicts", SLICE_DIMENSIONS);
648
- if (unitFailed.length > 0) {
649
- setRouteNote(sliceGradeRoute, unitFailedNote(unitFailed));
650
- return "slice-fix";
651
- }
652
- return seedOnlyCiteFail(state) ? "slice-seed-lift" : "slice-fix";
653
- },
654
- { readsData: false },
655
- );
656
-
657
- /**
658
- * Every unit a plan/code panel can dispatch — the tier roster's dimensions
659
- * plus the risk unit `panelRoster` adds when the plan declares `risks:`. The
660
- * dead-unit preemption filters on a failed sentinel per dimension, so naming
661
- * the risk unit here is safe when it was never dispatched (no sentinel ⇒ not
662
- * listed) and load-bearing when it was (a dead risk unit is a dead panel
663
- * member, not a vacuous risk pass).
664
- */
665
- const PLAN_PANEL_UNITS: readonly string[] = [...PLAN_DIMENSIONS, RISK_DIMENSION];
666
-
667
- /** The plan gate's demote edge — the unit-failed preemption fires BEFORE the
668
- * confirm divert (a previously-passing dimension whose re-grade died is not
669
- * a flap to adjudicate; there is no verdict to adjudicate). */
670
- const planDemoteRoute: EdgeFn = defineRoute(
671
- ["code", "plan-confirm", "plan-snapshot"],
672
- ({ state }) => {
673
- if (planGatePasses(state)) return "code";
674
- const unitFailed = unitFailedDimensions(state, "plans", "plan-verdicts", PLAN_PANEL_UNITS);
675
- if (unitFailed.length > 0) {
676
- setRouteNote(planDemoteRoute, unitFailedNote(unitFailed));
677
- return "plan-snapshot";
678
- }
679
- return confirmDue(state, "plans", "plan-verdicts", PLAN_DIMENSIONS) ? "plan-confirm" : "plan-snapshot";
680
- },
681
- { readsData: false },
682
- );
683
-
684
- /** The code gate's demote edge — the plan gate's twin on `code-verdicts`. */
685
- const codeDemoteRoute: EdgeFn = defineRoute(
686
- ["implement", "code-confirm", "code-snapshot"],
687
- ({ state }) => {
688
- if (codeGatePasses(state)) return "implement";
689
- const unitFailed = unitFailedDimensions(state, "plans", "code-verdicts", PLAN_PANEL_UNITS);
690
- if (unitFailed.length > 0) {
691
- setRouteNote(codeDemoteRoute, unitFailedNote(unitFailed));
692
- return "code-snapshot";
693
- }
694
- return confirmDue(state, "plans", "code-verdicts", PLAN_DIMENSIONS) ? "code-confirm" : "code-snapshot";
695
- },
696
- { readsData: false },
697
- );
698
-
699
- const buildWorkflow = defineWorkflow({
700
- name: "build",
701
- description:
702
- "Ship, sliced: capture the verbatim brief as a goal artifact (the north star the quality gates' completeness/correctness dimensions and validate anchor against) → research the brief → derive a goal-anchored acceptance inventory (the executable standard of completion, frozen before any plan so it cannot inherit the plan's scope; the completeness gates anchor on it and validate executes its evidence commands) → decompose it into vertical slices → two-phase slice gate (a deterministic floor — dependency-cycle freedom + brief-coverage conservation so a slice-fix can't pass by dropping scope — then one LLM design-readiness judgment that each slice is chewable by a single design pass) with a slice-fix loop → design each slice in parallel → one consolidated developer checkpoint (accept or adjust the proposed interfaces/data types, adjustments applied surgically and cascaded to dependents) → synthesize hierarchically (per-cluster sub-plans → one merged plan) → tier-scaled quality-panel gate (a one-slice, <=2-phase run grades correctness+completeness only; larger or previously-failing runs grade the full completeness/correctness/actionability/pattern-following/architecture-fit roster; a plan declaring risk flags adds a concurrent risk-rulings unit at every tier) where a dimension's fresh HIGH-severity, risk-ruling, or regressed-pass blocking verdict gets one confirming second judgment before it buys a plan-fix round (a first-time medium finding routes straight to the surgical fix) → elaborate code per phase in parallel → splice it into the plan → re-grade the code-bearing plan (same tier + confirm contract) → implement → implement-scope-check → reconcile → validate → commit. Research-led; three automated gates plus one human design checkpoint, before design, before code, and after the splice.",
703
- start: "goal",
704
- stages: {
705
- // The user's brief, verbatim, on its own channel — the judgment seams
706
- // (plan/code gates' completeness+correctness, validate) anchor against
707
- // it. Deliberately NOT fed to the generative stages (slice, design-slice):
708
- // bounded per-slice context is build's whole point, and an ambient goal
709
- // there invites re-litigating settled decompositions.
710
- goal: produces.script({ run: captureGoal }),
711
- // Front-loaded research grounds every slice's footing and feeds the plan
712
- // gate's architecture-fit dimension its --context. Prompt-dispatched so it
713
- // still receives the raw brief now that `goal` holds the start slot.
714
- research: produces({ prompt: RESEARCH_BRIEF_PROMPT }),
715
- // The goal-derived acceptance inventory (see ship's twin comment): the
716
- // executable standard of completion, frozen before slicing/planning so
717
- // it cannot inherit their scope. Threaded to the plan/code gates'
718
- // completeness units (--acceptance) and to validate, which executes the
719
- // evidence commands. Deliberately NOT fed to slice/design/synthesize —
720
- // the bounded-context doctrine that keeps `goal` out of the generative
721
- // stages applies to its derived standard too.
722
- acceptance: produces({ reads: ["goal", "research"] }),
723
- // `reads: ["research"]` (not the rolling primary): `acceptance` now sits
724
- // between research and slice, so the rolling primary at this stage is
725
- // the acceptance doc — the explicit read restores the research artifact
726
- // as slice's grounding input (dispatched as `--research <path>`; the
727
- // slice skill accepts the flag form of its fresh input).
728
- slice: produces({ reads: ["research"] }),
729
- // Deterministic floor (no LLM): dependency-cycle freedom + brief-coverage conservation.
730
- "slice-check": produces.script({ reads: ["slices"], run: sliceStructureCheck }),
731
- // One LLM design-readiness judgment; verdicts on their own channel.
732
- "slice-grade": produces({
733
- skill: "grade",
734
- loop: SLICE_DIMENSION_FANOUT,
735
- outcome: sliceVerdictOutcome,
736
- // Whole-lap progress: the slice lane's three re-entered destinations
737
- // (grade/fix/seed-lift) share ONE hook instance, so every counted
738
- // re-entry reads the same verdict-channel fold.
739
- progress: SLICE_PANEL_PROGRESS,
740
- reads: ["slices"],
741
- }),
742
- // Re-cut the slice map from the failing verdicts. Routes through `slice`
743
- // (re-slice mode), NOT the surgical `amend`: a `design-readiness` or structural
744
- // failure needs STRUCTURAL authority — split an epic, break a cycle, renumber —
745
- // which a surgical "touch only the cited line" edit cannot do, so `amend`
746
- // looped without converging until the backward-jump guard halted the run.
747
- "slice-fix": produces({
748
- skill: "slice",
749
- outcome: rpivBucketOutcome("slices"),
750
- progress: SLICE_PANEL_PROGRESS,
751
- reads: ["slices", fanin("slice-verdicts"), fanin("slice-check")],
752
- }),
753
- // Deterministic seed lift — the engine-owned half of the cite remedy: a
754
- // seed-only design-readiness fail (every finding demanding a concrete
755
- // `requires` citation) is repaired by appending the seeds to the named
756
- // slices' `Draws on` lines in place, never by a full re-slice + re-grade.
757
- // Publishes on its OWN stage channel (a script stage cannot carry an
758
- // outcome; the in-place amend keeps `latestFsArtifact(state, "slices")`
759
- // resolving the same amended file), then re-enters `slice-check`, whose
760
- // re-run stamps the cite discharge the gate folds on — no second panel.
761
- "slice-seed-lift": produces.script({
762
- reads: ["slices", fanin("slice-verdicts")],
763
- run: sliceSeedLift,
764
- progress: SLICE_PANEL_PROGRESS,
765
- }),
766
- // Design every slice in parallel.
767
- // `designOutcome` derives `filename_slice` beside the frontmatter so the
768
- // design-slice contract refuses a path whose `_slice-<N>_` token is missing
769
- // or disagrees with `slice_n` while the lane can still rename it.
770
- "slice-design": produces({ skill: "design-slice", loop: SLICE_DESIGN_FANOUT, outcome: designOutcome }),
771
- // One consolidated developer checkpoint over EVERY per-slice design, at the
772
- // single fan-in seam where they all exist and nothing parallel is running.
773
- // Presents the proposed shape (interfaces, data types, scope) and lets the
774
- // developer accept or adjust; an adjustment is applied surgically in place
775
- // and cascaded to the changed contract's dependents BEFORE synthesis sees
776
- // the designs. Re-emits designs on their channel (latest-wins, same paths),
777
- // so `subplan`/`synthesize` read the accepted/edited docs. The interactive
778
- // counterpart to the LLM gates — the one human pass on the parallel path.
779
- "design-review": produces({
780
- skill: "design-review",
781
- outcome: rpivBucketOutcome("designs"),
782
- reads: [fanin("designs"), "slices"],
783
- }),
784
- // Hierarchical fan-in: merge each slice-DAG cluster into a sub-plan in
785
- // parallel (bounded context), then merge the sub-plans into one plan.
786
- subplan: produces({
787
- skill: "synthesize",
788
- loop: SYNTH_CLUSTER_FANOUT,
789
- outcome: rpivBucketOutcome("subplans"),
790
- }),
791
- // Deterministic cluster-coverage floor between the cluster fanout and the
792
- // root merge — the subplan twin of `slice-check`. Reconciles dispatched
793
- // `_cluster-<k>` sub-plans against the slice map's promised cluster count +
794
- // `sources:` design coverage BEFORE the root merge fans them in, so a lost
795
- // or clobbered cluster fails structurally and routes back to `subplan`
796
- // rather than silently dropping slices from the merged plan.
797
- "subplan-check": produces.script({ reads: [fanin("subplans"), "slices"], run: subplanCoverageCheck }),
798
- // The root merge reads `research` (threaded as `--research` so cross-slice
799
- // constraints reach the merge directly, not only via each subplan's
800
- // refraction) alongside the cluster sub-plans it fans in. `goal` +
801
- // `acceptance` reach it too: synthesize disposes every inventory id in the
802
- // plan's `acceptance:` block, the same anchors the completeness judge and
803
- // validate read.
804
- plan: produces({ skill: "synthesize", reads: ["research", "goal", "acceptance", fanin("subplans")] }),
805
- // Deterministic citation floor BEFORE the LLM plan gate (twin of `slice-check`):
806
- // a fabricated `file:line` in the plan fails structurally and routes to `plan-fix`.
807
- "plan-cite-check": produces.script({ reads: ["plans"], run: planCitationCheck("plan-cite-check") }),
808
- // Quality gate over the plan; verdicts on their own channel.
809
- "plan-grade": produces({
810
- skill: "grade",
811
- loop: PLAN_DIMENSION_FANOUT,
812
- outcome: planVerdictOutcome,
813
- // Whole-lap progress: the plan lane's three re-entered destinations
814
- // (grade/confirm/snapshot) share ONE hook instance — a lap is one unit.
815
- progress: PLAN_PANEL_PROGRESS,
816
- // `research` is read so the architecture-fit unit can thread it as
817
- // --context; `goal` so completeness/correctness anchor on the brief.
818
- reads: ["plans", "research", "goal", "acceptance"],
819
- }),
820
- // Stamp the duty demotion onto the graded verdicts as legible on-disk data
821
- // (a `risk_duty_demotions` array written in place onto each demoted
822
- // verdict JSON) one hop BEFORE the gate routes — the gate's route lives on
823
- // `plan-demote` so this write-back lands before confirm/`--prior`/amend
824
- // read the verdict. Reads `plans` (the plan-authored risk flags) and fans
825
- // in the verdicts it just graded. Gate outcomes are unchanged: every fold
826
- // consults in-memory `state.named` via `rulingEffectivePass`, never the
827
- // rewritten file (the write-back is an additive, read-only signal).
828
- "plan-demote": produces.script({ reads: ["plans", fanin("plan-verdicts")], run: planDemote }),
829
- // One independent second judgment on the blocking dimensions before they
830
- // buy a fix round (see `confirmDue`). Same panel machinery, same verdict
831
- // channel — its OWN stage name so a stronger judge model can be pinned to
832
- // exactly the verdicts about to block (models.json `stages["plan-confirm"]`).
833
- "plan-confirm": produces({
834
- skill: "grade",
835
- loop: PLAN_CONFIRM_FANOUT,
836
- outcome: planVerdictOutcome,
837
- progress: PLAN_PANEL_PROGRESS,
838
- reads: ["plans", "research", "goal", "acceptance"],
839
- }),
840
- "plan-fix": produces({
841
- skill: "amend",
842
- outcome: rpivBucketOutcome("plans"),
843
- // Lineage threads for completeness-class repairs: `goal` (verbatim brief),
844
- // `research` (architecture/precedent findings), `subplans` (per-cluster
845
- // sub-plans). `goal`/`research` mirror `plan-confirm`'s reads; `subplans`
846
- // mirrors `plan`'s own `reads: ["research", fanin("subplans")]`. `subplans`
847
- // is plan-fix-ONLY — by the code gate the plan's completeness is settled, so
848
- // code-fix repairs code-shape defects and threads no subplans.
849
- reads: [
850
- "plans",
851
- fanin("plan-verdicts"),
852
- fanin("plan-cite-check"),
853
- "goal",
854
- "acceptance",
855
- "research",
856
- fanin("subplans"),
857
- ],
858
- }),
859
- // Snapshot the graded plan BEFORE plan-fix amends it — one deterministic
860
- // hop inside the existing fix loop (plan-grade/plan-confirm → plan-snapshot
861
- // → plan-fix). The re-grade reads the prior off the snapshot's OWN channel
862
- // (`plan-snapshot`) to decide whether the amend was surgical (re-grade only
863
- // the failing dims) or broad (re-grade the full roster). `produces.script`
864
- // rides its stage-name channel, so this publishes to `plan-snapshot`, NOT
865
- // `plans` — `latestFsArtifact(state, "plans")` still resolves to the real
866
- // (amended) plan.
867
- "plan-snapshot": produces.script({ reads: ["plans"], run: planSnapshot, progress: PLAN_PANEL_PROGRESS }),
868
- // Elaborate implement-ready code into each phase in parallel (fanout),
869
- // deterministically splice it back into the plan (code-splice), then
870
- // re-grade the now code-bearing plan — guarding the blind-splice risk.
871
- code: produces({
872
- skill: "elaborate",
873
- loop: ELABORATE_PHASE_FANOUT,
874
- reads: ["plans"],
875
- outcome: elaborationOutcome,
876
- }),
877
- "code-splice": acts.script({
878
- reads: ["plans"],
879
- run: ({ state, cwd }) => {
880
- const plan = latestFsArtifact(state, "plans");
881
- if (plan?.handle.kind !== "fs") {
882
- throw haltPreflight(
883
- "code-splice",
884
- "code-splice: no plan to splice into",
885
- "code-splice: no fs plan artifact on the 'plans' channel — synthesize must run before elaborate/code-splice",
886
- );
887
- }
888
- const planPath = isAbsolute(plan.handle.path) ? plan.handle.path : join(cwd, plan.handle.path);
889
- try {
890
- execFileSync("node", [STITCH_SCRIPT, planPath], { cwd, stdio: ["ignore", "pipe", "pipe"] });
891
- } catch (err) {
892
- const stderr = (err as { stderr?: Buffer | string }).stderr?.toString().trim();
893
- throw haltPreflight(
894
- "code-splice",
895
- "code-splice: stitch refused the elaborations",
896
- stderr || (err instanceof Error ? err.message : String(err)),
897
- );
898
- }
899
- },
900
- }),
901
- // Deterministic citation floor over the SPLICED (code-bearing) plan before
902
- // the LLM code gate — the code-scope twin of `plan-cite-check`.
903
- "code-cite-check": produces.script({ reads: ["plans"], run: planCitationCheck("code-cite-check") }),
904
- "code-grade": produces({
905
- skill: "grade",
906
- loop: CODE_DIMENSION_FANOUT,
907
- outcome: codeVerdictOutcome,
908
- // Whole-lap progress: the code lane's three re-entered destinations
909
- // (grade/confirm/snapshot) share ONE hook instance — a lap is one unit.
910
- progress: CODE_PANEL_PROGRESS,
911
- // `research` is read so the architecture-fit unit can thread it as
912
- // --context; `goal` so completeness/correctness anchor on the brief.
913
- reads: ["plans", "research", "goal", "acceptance"],
914
- }),
915
- // The code-gate twin of `plan-demote`: stamp the duty demotion onto the
916
- // code-graded verdicts (re-grading `plans` on `code-verdicts`) one hop
917
- // before the code gate routes (`code-demote` owns the route body).
918
- "code-demote": produces.script({ reads: ["plans", fanin("code-verdicts")], run: codeDemote }),
919
- // Repair arm for the code gate. Surgical `amend` over the SAME code-bearing
920
- // plan from the code verdicts — NOT a blind re-elaborate: `elaborate` never
921
- // sees the findings and can only rewrite a phase's code body, so it cannot fix
922
- // what the gate actually fails on (fabricated edit anchors, drifted line
923
- // citations, a cross-phase naming collision) and sometimes regressed a passing
924
- // dimension. `amend` reads the verdicts and edits the spliced plan in place
925
- // (its embedded code blocks included), then loops straight back to re-grade —
926
- // the mirror of the plan gate's `plan-fix` arm, on its own `code-verdicts`
927
- // channel so the two loops' verdicts never cross.
928
- // The code gate's confirm arm — the mirror of `plan-confirm`, on the
929
- // `code-verdicts` channel.
930
- "code-confirm": produces({
931
- skill: "grade",
932
- loop: CODE_CONFIRM_FANOUT,
933
- outcome: codeVerdictOutcome,
934
- progress: CODE_PANEL_PROGRESS,
935
- reads: ["plans", "research", "goal", "acceptance"],
936
- }),
937
- "code-fix": produces({
938
- skill: "amend",
939
- outcome: rpivBucketOutcome("plans"),
940
- // Lineage threads for code-shape repairs: `goal`/`research` give amend the
941
- // brief + architecture context (mirroring `code-confirm`'s reads). NO
942
- // `subplans` — the plan's completeness was settled at the plan gate, so the
943
- // code arm only repairs code-shape defects (fabricated edit anchors, drifted
944
- // `file:line` citations, cross-phase naming collisions).
945
- reads: ["plans", fanin("code-verdicts"), fanin("code-cite-check"), "goal", "research"],
946
- }),
947
- // Snapshot the graded plan BEFORE code-fix amends it — the code-gate twin
948
- // of `plan-snapshot` (code-grade/code-confirm → code-snapshot → code-fix),
949
- // publishing the prior on the `code-snapshot` channel.
950
- "code-snapshot": produces.script({ reads: ["plans"], run: codeSnapshot, progress: CODE_PANEL_PROGRESS }),
951
- implement: acts({ loop: IMPLEMENT_DAG_FANOUT, reads: ["plans"] }),
952
- // Lane-level scope floor — the structural backstop beneath the quality
953
- // gates. After the (now concurrent) implement lane lands, judge the working
954
- // tree's dirty set against the plan's declared write-set: any undeclared
955
- // write is a phase that escaped the upstream write-scope discipline. Tiered
956
- // route (scopeFloorGate): untracked-only excess ⇒ the deterministic
957
- // quarantine arm; tracked excess ⇒ recorded and adjudicated by validate
958
- // (threaded via --scope); missing verdict ⇒ STOP. No schema is declared
959
- // (matching slice-check/plan-cite-check — the route reads the channel).
960
- // Reads `goal` for the run-start baseline that subtracts pre-existing dirt.
961
- // On a validate-fix re-entry the floor additionally accepts the latest
962
- // report's blockers-named writes as declared scope — a validate-fix hop's
963
- // targeted repair is the one writer the plan cannot declare (it predates
964
- // the report); fail-closed on missing/older remediation (see
965
- // validateReportAcceptance).
966
- "implement-scope-check": produces.script({ reads: ["plans", "goal"], run: implementScopeCheck }),
967
- // Deterministic remedy arm for the untracked-only tier: move (never
968
- // delete) run-created untracked excess under .rpiv/tmp/scope-quarantine/
969
- // and publish a manifest, then re-enter the floor — see scopeQuarantine.
970
- "scope-quarantine": produces.script({ reads: ["implement-scope-check"], run: scopeQuarantine }),
971
- // Deterministic post-implement reconciliation (no LLM): applies every
972
- // `#### Reconciliation` directive (find→replace, write-restricted to the
973
- // plan's declared write-set), fail-soft — a coherence backstop the parallel
974
- // implement lane needs (a phase's correct change can invalidate a sibling's test, and the
975
- // combined tree can break in ways no single phase's checks surface). Pass ⇒
976
- // validate; fail ⇒ the reconcile-fix arm (see reconcileGate); missing ⇒
977
- // STOP. `reads: ["plans"]` only — no run-start goal baseline (the scope
978
- // floor already proved the write-set).
979
- reconcile: produces.script({ reads: ["plans"], run: reconcile }),
980
- // Repair arm for the reconciliation gate: /skill:amend over the plan's
981
- // directives from the reconcile verdict (a prompt stage — see
982
- // RECONCILE_FIX_PROMPT), re-emitting the plan latest-wins, then back
983
- // through reconcile to apply. Bounded by the runner's per-destination
984
- // backward-jump budget (the plan-fix precedent).
985
- "reconcile-fix": produces.prompt({ prompt: RECONCILE_FIX_PROMPT, outcome: RECONCILE_FIX_OUTCOME }),
986
- validate: produces({ prompt: VALIDATE_GOAL_PROMPT }),
987
- // Repair arm the validate gate dispatches on a remediable `verdict: "fail"`.
988
- // `acts()` (not `produces()`) because remediate is `side-effect`/`code-mutation`
989
- // (the tools twin of `implement`: re-runs verification commands via `Bash(*)`
990
- // and edits the working tree). `reads: ["plans","validation"]` ⇒
991
- // `stageEntryArgs` derives `--plans <plan> --validation <latest-report>`;
992
- // `validation` is validate's own publish bucket, so validate-fix always reads
993
- // the latest failing report. `remediationOutcome` publishes the deterministic
994
- // did-anything-change digest verdict on the `remediation` channel (the
995
- // `commit`/`gitCommitOutcome` pattern) — the arm's OWN edge folds it, so a
996
- // no-op remediation stops instead of re-validating an unchanged tree.
997
- "validate-fix": acts({ skill: "remediate", reads: ["plans", "validation"], outcome: remediationOutcome }),
998
- commit: acts({ prompt: COMMIT_BASELINE_PROMPT, outcome: gitCommitOutcome }),
999
- },
1000
- edges: {
1001
- goal: "research",
1002
- // The acceptance inventory derives between research (which grounds its
1003
- // evidence commands) and slice (which must never see it — bounded
1004
- // context). Slice's research input rides its explicit `reads` now that
1005
- // the rolling primary here is the acceptance doc.
1006
- research: "acceptance",
1007
- acceptance: "slice",
1008
- slice: "slice-check",
1009
- // Skip the design-readiness re-grade when the gate is already satisfied — after
1010
- // a `slice-fix` that only cleared the deterministic structure floor (the common
1011
- // case: a bare-basename citation), the accumulated design-readiness verdict
1012
- // already passes, so re-grading would only re-roll a flappy judgment. Also
1013
- // skips after a fix for a `remedy: "cite"` fail once `slice-check` has
1014
- // deterministically verified the demanded seeds landed on a structurally
1015
- // unchanged map (the `citeDischarged` stamp — see `citeRemedyDischarged`),
1016
- // and after a seed lift for the same reason.
1017
- // First pass (no verdict yet) ⇒ not satisfied ⇒ into `slice-grade`. A
1018
- // seed lift that already ran and left the gate red is STUCK — re-grading
1019
- // or re-lifting cannot change the outcome — so the fail branch routes
1020
- // the structural fix arm BEFORE the re-grade fallthrough.
1021
- "slice-check": defineRoute(
1022
- ["slice-design", "slice-fix", "slice-grade"],
1023
- ({ state }) => (sliceGatePasses(state) ? "slice-design" : seedLiftStuck(state) ? "slice-fix" : "slice-grade"),
1024
- { readsData: false },
1025
- ),
1026
- // Design-readiness gate BEFORE any design. Structure + design-readiness pass ⇒
1027
- // design; a SEED-ONLY cite fail (every finding naming a concrete seed to add) ⇒
1028
- // the deterministic `slice-seed-lift` arm, which appends the seeds and re-enters
1029
- // `slice-check` for the discharge stamp — a full re-slice + re-grade for pure
1030
- // citation bookkeeping repairs nothing the verdict flagged; anything else ⇒
1031
- // slice-fix and loop back. (A dimension whose re-dispatch produced no verdict
1032
- // takes the fix arm ahead of the seed-only check — a verdict-less dead
1033
- // dimension is never seed-only.) Bounded by the runner's maxBackwardJumps
1034
- // (default 3) under the absolute per-stage maxLaps ceiling (default 8;
1035
- // both budgets fresh per invocation — a resume re-opens the loop).
1036
- "slice-grade": sliceGradeRoute,
1037
- "slice-fix": "slice-check",
1038
- // Deterministic re-entry after the seed lift: the re-run structure check
1039
- // stamps the discharge the gate folds on (a plain string edge — the
1040
- // counted decision is the slice-grade route's lift pick).
1041
- "slice-seed-lift": "slice-check",
1042
- // Design fanout → consolidated human checkpoint → hierarchical synthesis.
1043
- "slice-design": "design-review",
1044
- "design-review": "subplan",
1045
- // Route the cluster fanout through the deterministic coverage floor before
1046
- // the root merge — the twin of `slice → slice-check`. A pass folds straight
1047
- // to `plan`; a lost/clobbered cluster routes the backward edge to `subplan`,
1048
- // bounded by the runner's maxBackwardJumps (default 3) under the absolute
1049
- // per-stage maxLaps ceiling (default 8; both budgets fresh per invocation
1050
- // — a resume re-opens the loop).
1051
- subplan: "subplan-check",
1052
- // Subplan coverage gate. Pass ⇒ root merge. A fail (lost cluster, clobbered
1053
- // ordinal, tokenless basename, or a slice design absent from every sources:)
1054
- // routes the backward edge to `subplan` — re-dispatch the cluster fanout,
1055
- // which re-supplies each cluster's '--cluster <k>'. Bounded by the runner's
1056
- // maxBackwardJumps (default 3) under the absolute per-stage maxLaps ceiling
1057
- // (default 8; both budgets fresh per invocation — a resume re-opens the
1058
- // loop). `readsData: false` — the route consults only the
1059
- // deterministic verdict channel (mirrors the slice-check/plan-cite-check routes).
1060
- "subplan-check": defineRoute(
1061
- ["plan", "subplan"],
1062
- ({ state }) => (subplanGatePasses(state) ? "plan" : "subplan"),
1063
- { readsData: false },
1064
- ),
1065
- plan: "plan-cite-check",
1066
- // Skip the quality re-grade straight to `code` when the gate is already
1067
- // satisfied — a `plan-fix` that only cleared the citation floor leaves every
1068
- // dimension + risk flag already passing, so re-grading the whole panel would
1069
- // only re-roll flappy judgments. First pass (empty verdict channel) ⇒ not
1070
- // satisfied ⇒ into `plan-grade`. If a fix left the cite floor RED, the gate
1071
- // isn't satisfied and we re-enter `plan-grade` (which re-runs the subset).
1072
- "plan-cite-check": defineRoute(
1073
- ["code", "plan-grade"],
1074
- ({ state }) => (planGatePasses(state) ? "code" : "plan-grade"),
1075
- { readsData: false },
1076
- ),
1077
- // Quality gate BEFORE any code. The grade runs at `plan-grade`; the route
1078
- // lives one hop later on `plan-demote` so the duty-demotion write-back
1079
- // lands on the verdict JSON BEFORE this fold consults the downstream
1080
- // readers. `plan-grade` is now a simple always-hop edge to `plan-demote`;
1081
- // the route body below is the verbatim logic that used to live here.
1082
- "plan-grade": "plan-demote",
1083
- // Pass ⇒ code. A dimension's fresh confirm-worthy blocking verdict — a
1084
- // HIGH-severity or risk-ruling blocker, or a regressed carried pass — ⇒
1085
- // plan-confirm (one independent second judgment — see `confirmDue`; a
1086
- // first-time medium finding skips the confirm and buys the surgical fix
1087
- // directly); a confirmed blocker, or
1088
- // a failure with no dimension blocking (the citation floor alone is red) ⇒
1089
- // plan-fix, looping back THROUGH the citation floor so the amended plan
1090
- // re-verifies. Route logic unchanged — merely shifted one hop later so the
1091
- // demote write-back precedes it.
1092
- "plan-demote": planDemoteRoute,
1093
- // After the second judgment the gate re-folds on the latest verdicts: a
1094
- // confirming pass overwrote the flap and clears the gate; a confirming
1095
- // fail routes to the fix with two agreeing judgments behind it.
1096
- "plan-confirm": defineRoute(
1097
- ["code", "plan-snapshot"],
1098
- ({ state }) => (planGatePasses(state) ? "code" : "plan-snapshot"),
1099
- { readsData: false },
1100
- ),
1101
- // The snapshot is one deterministic hop between the grade/confirm route and
1102
- // the fix — no new backward edge, inside the existing fix loop.
1103
- "plan-snapshot": "plan-fix",
1104
- "plan-fix": "plan-cite-check",
1105
- code: "code-splice",
1106
- "code-splice": "code-cite-check",
1107
- // Skip the code re-grade straight to `implement` when the code gate is already
1108
- // satisfied — a `code-fix` that only cleared the citation floor leaves the
1109
- // panel already green. First pass (empty channel) ⇒ into `code-grade`.
1110
- "code-cite-check": defineRoute(
1111
- ["implement", "code-grade"],
1112
- ({ state }) => (codeGatePasses(state) ? "implement" : "code-grade"),
1113
- { readsData: false },
1114
- ),
1115
- // Re-grade the code-bearing plan at `code-grade`; the route lives one hop
1116
- // later on `code-demote` (the twin of the plan gate's split) so the
1117
- // duty-demotion write-back lands before this fold. `code-grade` is now a
1118
- // simple always-hop edge to `code-demote`; the route body below is verbatim.
1119
- "code-grade": "code-demote",
1120
- // Pass ⇒ implement. A fresh confirm-worthy blocking verdict ⇒ code-confirm (the plan
1121
- // gate's confirm contract, on the code-verdicts channel); a confirmed
1122
- // blocker or cite-floor-only failure ⇒ code-fix. Routes to `code-fix`, NOT
1123
- // back to `code`: the gate fails on plan-text defects (edit anchors, line
1124
- // citations, naming) that a per-phase code rewrite cannot reach, so the
1125
- // surgical arm is the one with authority over them. Route logic unchanged —
1126
- // merely shifted one hop later. Bounded by the runner's maxBackwardJumps
1127
- // (default 3) under the absolute per-stage maxLaps ceiling (default 8;
1128
- // both budgets fresh per invocation — a resume re-opens the loop).
1129
- "code-demote": codeDemoteRoute,
1130
- "code-confirm": defineRoute(
1131
- ["implement", "code-snapshot"],
1132
- ({ state }) => (codeGatePasses(state) ? "implement" : "code-snapshot"),
1133
- { readsData: false },
1134
- ),
1135
- // The code-gate twin of `plan-snapshot → plan-fix`.
1136
- "code-snapshot": "code-fix",
1137
- "code-fix": "code-cite-check",
1138
- implement: "implement-scope-check",
1139
- // Lane-level scope floor gate — tiered, see scopeFloorGate: pass AND
1140
- // tracked excess ⇒ reconcile (excess findings ride the verdict channel and
1141
- // validate adjudicates them via the --scope thread — the citation floor's
1142
- // demote-and-adjudicate precedent); untracked-only ⇒ the deterministic
1143
- // scope-quarantine arm; a missing/corrupt verdict ⇒ STOP (integrity
1144
- // clause). The excess pick attaches the pass-through note naming validate
1145
- // (the recap's routingNotes surface the deferral). Sourced from the
1146
- // scope-check's published verdict channel (the
1147
- // stage key for an outcome-less `produces.script`, per
1148
- // `resolvePublishName`); `readsData: false` suppresses the outputSchema lint.
1149
- "implement-scope-check": scopeFloorGate({ deferredTo: "validate" }),
1150
- // Deterministic re-entry after the quarantine arm: a plain string edge
1151
- // (non-counted, mirroring validate-fix's hop) with guaranteed progress —
1152
- // quarantined paths leave the dirty set, so the re-check either passes or
1153
- // reveals tracked drift. At most one quarantine hop per gate entry; no new
1154
- // loop budget.
1155
- "scope-quarantine": "implement-scope-check",
1156
- // Reconciliation gate. Pass ⇒ validate; a `fail` (malformed directive /
1157
- // absent find / non-test target — all plan-TEXT defects) ⇒ the
1158
- // reconcile-fix amend arm; a missing verdict ⇒ STOP (integrity clause).
1159
- // Safe by construction: the sole path onward to validate is an explicit
1160
- // `verdict: "pass"`.
1161
- reconcile: reconcileGate(),
1162
- // Deterministic re-entry after the amend arm: reconcile re-parses the
1163
- // repaired directives and applies them (a plain string edge — the
1164
- // counted decision is the gate's reconcile-fix pick).
1165
- "reconcile-fix": "reconcile",
1166
- // Gate commit on validate's own verdict — see `validateGate`. `pass` ⇒
1167
- // commit; a `fail` WITH remediable handles (a `pass: false` risk ruling or a
1168
- // structured `blockers:` entry) ⇒ validate-fix, which re-enters at
1169
- // implement-scope-check to re-reconcile + re-validate — bounded by the
1170
- // per-destination backward-jump budget; a `fail` with NO handle ⇒ STOP with
1171
- // a route note (the repair arm cannot act on prose-only failures — looping
1172
- // it re-validated an unchanged tree until the guard halted the run).
1173
- // A missing/unexpected verdict stays terminal STOP, so un-anticipated data
1174
- // can never route INTO commit OR the repair arm. Safe by construction: the
1175
- // sole path to commit is an explicit pass. No fix-round cap — the runner's
1176
- // backward-jump guard is build's remediation budget.
1177
- validate: validateGate(),
1178
- // Re-entry after the repair arm: remediate's code-mutation is followed by a
1179
- // fresh scope check → reconcile → validate pass, so a fix is re-verified
1180
- // end-to-end before the gate re-folds. Now a decision edge (`validateFixGate`
1181
- // folds the `remediation` channel's deterministic digest verdict): a
1182
- // remediation that changed nothing STOPs here — progress is verified, not
1183
- // assumed — while a real fix proceeds into the loop body.
1184
- "validate-fix": validateFixGate(),
1185
- commit: "stop",
1186
- },
1187
- });
1188
-
1189
- /**
1190
- * Reason strings for ship's two bespoke stop picks — persisted on the
1191
- * `RoutingDecision` row via `setRouteNote` so `summarizeRun` can surface
1192
- * "stopped at <gate>: <why>" in the end-of-run recap and toast. `match`/`gate`
1193
- * edges attach their own no-match diagnostics; only these two `defineRoute`
1194
- * gates would otherwise stop silently. Best-effort DIAGNOSTICS, not gates:
1195
- * `allDimensionsPass`/`shipGatePasses` stay the sole routing authorities, and
1196
- * these consult the shared `verdictBlocks` predicate — the same fold those
1197
- * gates route on — only to NAME the blockers.
1198
- */
1199
- const shipCiteStopNote = (state: RunView): string => {
1200
- const data = state.named["plan-cite-check"]?.at(-1)?.data as { findings?: unknown } | undefined;
1201
- // Blocking findings only — the gate passes an advisory-only (severity `low`)
1202
- // verdict, so when this note renders the blockers are what stopped the run.
1203
- const n = Array.isArray(data?.findings)
1204
- ? data.findings.filter((f) => (f as { advisory?: boolean } | null)?.advisory !== true).length
1205
- : 0;
1206
- return n > 0 ? `plan citation check failed (${n} finding${n === 1 ? "" : "s"})` : "plan citation check failed";
1207
- };
1208
- const shipGradeStopNote = (state: RunView): string => {
1209
- // A dead grade unit (post-re-dispatch) is the loudest blocker — name it
1210
- // ahead of the severity blockers (ship's arm is stop + hand-repair +
1211
- // resume, so the note IS the repair instruction).
1212
- const unitFailed = unitFailedDimensions(state, "plans", "ship-verdicts", shipRoster(state));
1213
- if (unitFailed.length > 0) return unitFailedNote(unitFailed);
1214
- const fresh = freshVerdicts(state.named["ship-verdicts"], latestArtifactPath(state, "plans"));
1215
- if (fresh.length === 0) return "no fresh verdicts for the current plan";
1216
- const risks = planAuthoredRisks(state, "plans");
1217
- const latest = latestVerdictPerDimension(fresh);
1218
- const blockers: string[] = [];
1219
- for (const d of shipRoster(state)) {
1220
- const o = latest.get(d);
1221
- if (!o) continue;
1222
- const v = o.data as VerdictRecord | undefined;
1223
- if (verdictBlocks(v)) blockers.push(`${d} failed (${v?.severity ?? "unrated"})`);
1224
- else if (verdictRiskRulings(o).some((r) => !rulingEffectivePass(r, risks.get(r.id))))
1225
- blockers.push(`${d} risk flag failed`);
1226
- }
1227
- return blockers.length > 0 ? blockers.join(", ") : "gate failed";
1228
- };
1229
-
1230
- // Named (not inline) so the stop branch can self-reference for setRouteNote —
1231
- // the same closure-over-own-binding pattern gate()/match() use internally.
1232
- // Citation-floor gate. Pass ⇒ grade; fail ⇒ STOP (no fix arm — the lightweight
1233
- // preset terminates on any red gate). Only BLOCKING findings fail here: an
1234
- // advisory-only verdict rates `low` and rides through `allDimensionsPass`'
1235
- // severity floor to grade, where the correctness unit adjudicates it
1236
- // (`--cite-check`). The route folds `allDimensionsPass` over
1237
- // the stage's OWN published channel, NOT `match("verdict", …)`:
1238
- // `writeStructureVerdict` (the floor's envelope) carries no `verdict` field, so
1239
- // a verdict match would misread — this mirrors build's `planGatePasses` first
1240
- // clause. `readsData: false` — the route consults the deterministic verdict
1241
- // channel only.
1242
- const shipCiteGate: EdgeFn = defineRoute(
1243
- ["grade", "stop"],
1244
- ({ state }) => {
1245
- if (allDimensionsPass(state.named["plan-cite-check"])) return "grade";
1246
- setRouteNote(shipCiteGate, shipCiteStopNote(state));
1247
- return "stop";
1248
- },
1249
- { readsData: false },
1250
- );
1251
- // Quality gate PRE-implement. `shipGatePasses` (the bespoke fold over
1252
- // SHIP_DIMENSIONS + risk flags on the `ship-verdicts` channel) does NOT re-fold
1253
- // the citation floor; this edge is the sole gate. Pass ⇒ implement; fail ⇒
1254
- // STOP — no confirm/snapshot/fix loop.
1255
- const shipGradeGate: EdgeFn = defineRoute(
1256
- ["implement", "stop"],
1257
- ({ state }) => {
1258
- if (shipGatePasses(state)) return "implement";
1259
- setRouteNote(shipGradeGate, shipGradeStopNote(state));
1260
- return "stop";
1261
- },
1262
- { readsData: false },
1263
- );
1264
-
1265
- /**
1266
- * ship — the lightweight `/wf` preset: the no-ceremony path for small-to-
1267
- * midsize tasks whose approach is obvious. goal → research → acceptance →
1268
- * plan → plan-cite-check → grade → implement → implement-scope-check →
1269
- * reconcile → validate → (validate-fix, once) | commit, stop-on-fail at every gate: a red
1270
- * gate halts the run (the agent hand-repairs and RESUMES — `/wf @<runId>`
1271
- * re-runs the halted gate against the repaired tree, reusing every upstream
1272
- * artifact) instead of looping a fix cycle. The ONE concession to that
1273
- * identity is validate's single bounded remediation hop (run 7299: a
1274
- * remediable docs-gap `fail` at the last stage stranded ~50 min of verified
1275
- * implementation behind a terminal stop). Research stays front-loaded — a
1276
- * brief-sized grounding pass (SHIP_RESEARCH_PROMPT, not a full
1277
- * `/skill:research` run: at most one verify-only dispatch when the brief names
1278
- * root cause, files, or fix — none when its anchors are plain file paths; at
1279
- * most two targeted dispatches otherwise) — because the single PRE-implement
1280
- * grade's architecture-fit dimension needs its artifact as `--context`. That
1281
- * grade is tier-independent: the bespoke SHIP_DIMENSION_FANOUT always grades
1282
- * the full correctness/completeness/architecture-fit roster (no
1283
- * gateTier/gateRoster light-tier drop), and SHIP's gate folds risk flags
1284
- * without re-folding the citation floor (that floor folds at its own edge).
1285
- */
1286
- const shipWorkflow = defineWorkflow({
1287
- name: "ship",
1288
- description:
1289
- "Ship, unsliced: capture the verbatim brief as a goal artifact → ground it with a brief-sized research pass (none or one verify-only codebase-analyzer dispatch when the brief names root cause, files, or fix; at most two targeted dispatches otherwise — no /skill:research) → derive a goal-anchored acceptance inventory (the executable standard of completion, frozen before planning; quick-plan records a per-item disposition, the completeness gate anchors on it, validate executes its evidence commands) → one lightweight quick-plan pass → deterministic citation floor (files: coverage gaps stop; citation-resolution findings are advisory and adjudicated by the grade panel) → single tier-independent quality gate (correctness/completeness/architecture-fit, stop-on-fail) → implement → implement-scope-check → reconcile → validate → commit. Every gate halts the run on fail (hand-repair, then resume with /wf @<runId> to re-run the gate) — except a reconcile fail (a plan-text directive defect), which buys ONE bounded amend hop over the plan's directives, and a validate fail carrying structured remediable handles, which buys ONE bounded remediation hop before halting.",
1290
- start: "goal",
1291
- stages: {
1292
- // build's verbatim goal capture — the brief on its own channel, plus the
1293
- // run-start pre-existing-dirty snapshot the scope-check subtracts.
1294
- goal: produces.script({ run: captureGoal }),
1295
- // The lean grounding pass — SHIP_RESEARCH_PROMPT (a custom prompt, NOT
1296
- // /skill:research), sized to the brief's pre-chewedness: at most one
1297
- // verify-only codebase-analyzer dispatch when the brief names root
1298
- // cause, files, or fix (none when its anchors are plain file paths);
1299
- // at most two targeted dispatches when it names only a symptom; then
1300
- // one grounding doc under .rpiv/artifacts/research/. A prompt stage,
1301
- // so the stage name `research` drives outcome derivation (research
1302
- // contract → `research` bucket) exactly as build's
1303
- // RESEARCH_BRIEF_PROMPT stage does.
1304
- research: produces({ prompt: SHIP_RESEARCH_PROMPT }),
1305
- // The goal-derived acceptance inventory — the executable standard of
1306
- // completion, authored BEFORE any plan exists so it cannot inherit the
1307
- // plan's scope. Items enumerate the verbatim brief's asks (research
1308
- // grounds only the evidence commands, never membership — the skill's
1309
- // hard rule, since research routinely narrows the brief). Downstream:
1310
- // quick-plan addresses-or-defers each item, the grade panel's
1311
- // completeness unit anchors on the inventory (--acceptance), and
1312
- // validate EXECUTES the evidence commands against the finished tree.
1313
- // Outcome derives from the acceptance contract (artifactKind:
1314
- // acceptance → `acceptance` bucket).
1315
- acceptance: produces({ reads: ["goal", "research"] }),
1316
- // The lightweight planner — quick-plan: ONE targeted
1317
- // codebase-pattern-finder dispatch, one `status: ready` plan, no risks
1318
- // frontmatter, no multi-slice decomposition. Derives its `plans` outcome
1319
- // from the quick-plan contract (artifactKind: plan). Reads all three
1320
- // channels explicitly (`--research <path> --goal <path>
1321
- // --acceptance <path>`) — without `goal` the stage falls to the rolling
1322
- // primary and the planner sees only the research doc, whose grounding
1323
- // routinely narrows the brief; the grade panel's completeness dimension
1324
- // anchors on the VERBATIM goal and the acceptance inventory, so the
1325
- // planner must anchor on the same artifacts and record a per-item
1326
- // disposition (implemented or deferred) instead of silently inheriting
1327
- // the drop.
1328
- plan: produces({ skill: "quick-plan", reads: ["research", "goal", "acceptance"] }),
1329
- // Deterministic citation floor BEFORE the LLM gate — build's verifier
1330
- // verbatim. Only a `files:` coverage gap fails structurally and STOPs the
1331
- // run; every citation-resolution finding (unresolved path, ambiguity,
1332
- // drift) is advisory — rates `low`, passes the gate, and reaches the
1333
- // grade panel's correctness unit as `--cite-check` for adjudication.
1334
- "plan-cite-check": produces.script({ reads: ["plans"], run: planCitationCheck("plan-cite-check") }),
1335
- // Single PRE-implement grade over the fixed three-dimension roster
1336
- // (SHIP_DIMENSION_FANOUT — tier-independent, no confirm/snapshot arms);
1337
- // verdicts on the `ship-verdicts` channel. `research` is read so the
1338
- // architecture-fit unit threads it as --context; `goal` so
1339
- // completeness/correctness anchor on the verbatim brief; `acceptance` so
1340
- // the completeness unit checks the plan's per-item dispositions against
1341
- // the frozen inventory (--acceptance).
1342
- grade: produces({
1343
- skill: "grade",
1344
- loop: SHIP_DIMENSION_FANOUT,
1345
- outcome: shipVerdictOutcome,
1346
- // Whole-lap progress: declared for uniformity — ship's grade gate
1347
- // routes implement or stop, so no edge ever re-enters this stage and
1348
- // the hook never fires.
1349
- progress: SHIP_PANEL_PROGRESS,
1350
- reads: ["plans", "research", "goal", "acceptance"],
1351
- }),
1352
- // Dep-gated DAG implement — build's lane verbatim.
1353
- implement: acts({ loop: IMPLEMENT_DAG_FANOUT, reads: ["plans"] }),
1354
- // Lane-level scope floor — build's latest-only variant (vet uses the
1355
- // union variant for its fix loop; ship has no loop, so the latest plan's
1356
- // declared write-set is the whole contract). Pass ⇒ reconcile; fail ⇒ STOP.
1357
- // The shared run function carries the validate-report acceptance: a
1358
- // validate-fix hop's blocker-named writes are accepted as declared scope
1359
- // (fail-closed on missing/older remediation) — ship's single bounded
1360
- // validate-fix hop re-enters here, landing exactly that shape.
1361
- "implement-scope-check": produces.script({ reads: ["plans", "goal"], run: implementScopeCheck }),
1362
- // Deterministic post-implement reconciliation — build's run-function
1363
- // verbatim. Pass ⇒ validate; fail ⇒ ONE bounded reconcile-fix hop
1364
- // (maxFixRounds: 1 — the validate-gate concession's twin); missing ⇒ STOP.
1365
- reconcile: produces.script({ reads: ["plans"], run: reconcile }),
1366
- // Repair arm — build's prompt stage verbatim; ship's reconcile gate
1367
- // dispatches it at most ONCE. Kept despite the stop-on-fail identity for
1368
- // the same reason as validate-fix: a reconcile fail is a plan-TEXT defect
1369
- // a hand-repair of the TREE can never clear, so the terminal stop was
1370
- // unresumable without hand-editing the plan artifact.
1371
- "reconcile-fix": produces.prompt({ prompt: RECONCILE_FIX_PROMPT, outcome: RECONCILE_FIX_OUTCOME }),
1372
- validate: produces({ prompt: VALIDATE_GOAL_PROMPT }),
1373
- // Repair arm — build's stage verbatim; ship's validate gate dispatches it
1374
- // at most ONCE (maxFixRounds: 1). Kept because the terminal gate is where
1375
- // a red verdict strands the most verified work over the least defect: the
1376
- // arm acts only on the report's structured handles, and its own progress
1377
- // gate stops a no-op remediation instead of re-validating an unchanged tree.
1378
- "validate-fix": acts({ skill: "remediate", reads: ["plans", "validation"], outcome: remediationOutcome }),
1379
- commit: acts({ prompt: COMMIT_BASELINE_PROMPT, outcome: gitCommitOutcome }),
1380
- },
1381
- edges: {
1382
- goal: "research",
1383
- research: "acceptance",
1384
- acceptance: "plan",
1385
- plan: "plan-cite-check",
1386
- // Both gates are the named EdgeFns above — they attach a stop-reason
1387
- // ROUTE_NOTE the recap surfaces; routing semantics are unchanged.
1388
- "plan-cite-check": shipCiteGate,
1389
- grade: shipGradeGate,
1390
- implement: "implement-scope-check",
1391
- // Scope floor gate — DELIBERATELY NOT build/vet's tiered scopeFloorGate:
1392
- // ship's identity is stop-on-fail with no fix loops, so the sole path
1393
- // onward stays an explicit `verdict: "pass"`. The floor's tiered
1394
- // "untracked-only"/"excess" verdicts (which build quarantines/adjudicates)
1395
- // are terminal here like any other red gate — the match's no-branch note
1396
- // names the value, and the agent hand-repairs and re-invokes. Sourced from
1397
- // the stage's own channel via the `from` form (suppresses the READS_DATA
1398
- // outputSchema lint).
1399
- "implement-scope-check": match("verdict", { reconcile: "pass" }, { from: "implement-scope-check" }),
1400
- // Reconciliation gate — build's route, capped at ONE amend round (the
1401
- // reconcile channel's entry count IS the rounds spent): pass ⇒ validate;
1402
- // first fail ⇒ reconcile-fix; a fail after the spent round, or a missing
1403
- // verdict ⇒ STOP with a route note naming the plan artifact as the
1404
- // repair site.
1405
- reconcile: reconcileGate({ maxFixRounds: 1 }),
1406
- // Re-entry after the amend arm — reconcile re-parses and applies the
1407
- // repaired directives; the spent round now stops any remaining fail.
1408
- "reconcile-fix": "reconcile",
1409
- // Validate gate — build's classifying gate, capped at ONE remediation
1410
- // round: `pass` ⇒ commit; a `fail` WITH structured remediable handles and
1411
- // no remediation spent ⇒ validate-fix; every other fail (prose-only, or
1412
- // the one round already used) ⇒ STOP with a route note. The cap is what
1413
- // keeps ship's stop-on-fail identity: the arm is a single bounded hop,
1414
- // not a loop — the runner's `remediation`-channel length enforces it
1415
- // deterministically. NOT vet's tail: vet's validate routes to
1416
- // code-review, which gates back to blueprint (a bounded backward loop).
1417
- validate: validateGate({ maxFixRounds: 1 }),
1418
- // Re-entry after the repair arm — build's edge: a remediation that
1419
- // changed nothing STOPs (progress is verified, not assumed); a real fix
1420
- // re-enters at implement-scope-check so it is re-verified end-to-end
1421
- // (scope floor → reconcile → validate) before the gate re-folds — where
1422
- // the spent round now stops any remaining fail.
1423
- "validate-fix": validateFixGate(),
1424
- commit: "stop",
1425
- },
1426
- });
1427
-
1428
- // ===========================================================================
1429
- // Exports
1430
- // ===========================================================================
14
+ import { buildWorkflow } from "./workflows/build.js";
15
+ import { polishWorkflow } from "./workflows/polish.js";
16
+ import { shipWorkflow } from "./workflows/ship.js";
17
+ import { vetWorkflow } from "./workflows/vet.js";
1431
18
 
1432
19
  export { SHIP_DIMENSION_FANOUT, SHIP_DIMENSIONS, shipGatePasses, shipVerdictOutcome } from "./built-ins/index.js";
1433
20