@juicesharp/rpiv-workflow 1.19.0 → 1.20.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 (114) hide show
  1. package/README.md +81 -8
  2. package/api.ts +18 -703
  3. package/audit-rows.ts +136 -0
  4. package/audit.ts +139 -126
  5. package/built-ins.ts +20 -45
  6. package/chain-state.ts +169 -0
  7. package/command-run.ts +31 -3
  8. package/command.ts +116 -20
  9. package/docs/workflow-authoring.md +322 -61
  10. package/{lifecycle.ts → events.ts} +119 -35
  11. package/host.ts +30 -0
  12. package/index.ts +25 -81
  13. package/internal-utils.ts +92 -78
  14. package/internal.ts +21 -1
  15. package/judge.ts +229 -0
  16. package/layers.ts +10 -15
  17. package/load/alias.ts +6 -12
  18. package/load/cache.ts +9 -6
  19. package/load/index.ts +16 -109
  20. package/load/issues.ts +31 -0
  21. package/load/legacy.ts +102 -0
  22. package/load/merge.ts +2 -2
  23. package/load/shape-guards.test.ts +4 -1
  24. package/load/shape-guards.ts +3 -6
  25. package/load/skill-contract-phase.ts +94 -0
  26. package/loop-constructors.ts +623 -0
  27. package/loop-def.ts +240 -0
  28. package/loop-kinds.ts +493 -0
  29. package/loop.ts +304 -0
  30. package/messages.ts +225 -157
  31. package/outcomes/collectors/directory-path.ts +7 -3
  32. package/outcomes/collectors/require-opt.ts +11 -0
  33. package/outcomes/collectors/tool-call.test.ts +3 -1
  34. package/outcomes/collectors/tool-call.ts +8 -3
  35. package/outcomes/collectors/transcript-path.ts +2 -3
  36. package/outcomes/collectors/union.test.ts +54 -0
  37. package/outcomes/collectors/union.ts +28 -9
  38. package/outcomes/collectors/url.ts +7 -0
  39. package/outcomes/collectors/workspace-diff.test.ts +13 -0
  40. package/outcomes/collectors/workspace-diff.ts +21 -14
  41. package/outcomes/exec.ts +17 -0
  42. package/outcomes/git-commit.test.ts +76 -30
  43. package/outcomes/git-commit.ts +139 -100
  44. package/outcomes/index.ts +1 -0
  45. package/outcomes/parsers/json-body.ts +2 -2
  46. package/outcomes/side-effect.ts +3 -3
  47. package/output-spec.ts +36 -10
  48. package/output.ts +40 -20
  49. package/package.json +13 -7
  50. package/predicates.ts +11 -8
  51. package/preview.ts +77 -17
  52. package/registration.ts +109 -35
  53. package/routing-dsl.ts +310 -0
  54. package/routing.ts +2 -2
  55. package/runner/by-name.ts +2 -1
  56. package/runner/by-run-id.ts +2 -1
  57. package/runner/chain-advance.ts +59 -44
  58. package/runner/errors.ts +33 -0
  59. package/runner/failure.ts +109 -0
  60. package/runner/header-write-failure.test.ts +64 -0
  61. package/runner/index.ts +7 -13
  62. package/runner/input-validation.ts +11 -21
  63. package/runner/preflight.ts +173 -0
  64. package/runner/resolve-stage.ts +68 -0
  65. package/runner/resume-entry.ts +101 -0
  66. package/runner/resume-loop.test.ts +1410 -0
  67. package/runner/resume-loop.ts +110 -0
  68. package/runner/resume-session.test.ts +400 -0
  69. package/runner/resume.test.ts +881 -206
  70. package/runner/resume.ts +281 -261
  71. package/runner/run-context.ts +161 -0
  72. package/runner/run-stage.ts +456 -0
  73. package/runner/runner.ts +59 -400
  74. package/runner/script-stage.ts +103 -105
  75. package/schema-compat.ts +13 -1
  76. package/sessions/extraction.ts +53 -31
  77. package/sessions/index.ts +3 -1
  78. package/sessions/locate.test.ts +77 -0
  79. package/sessions/locate.ts +90 -0
  80. package/sessions/reattach.ts +63 -0
  81. package/sessions/sessions.ts +130 -127
  82. package/skill-contract.ts +22 -25
  83. package/skill-contracts/composition.ts +88 -37
  84. package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
  85. package/skill-contracts/harvest.ts +2 -3
  86. package/skill-contracts/index.ts +15 -8
  87. package/skill-contracts/registry.ts +33 -50
  88. package/stage-def.ts +527 -0
  89. package/startup.ts +3 -1
  90. package/state/index.ts +8 -1
  91. package/state/names.ts +91 -65
  92. package/state/paths.ts +12 -0
  93. package/state/raw.ts +78 -0
  94. package/state/reads.ts +103 -85
  95. package/state/resolve.ts +73 -0
  96. package/state/state.ts +112 -15
  97. package/state/writes.ts +29 -12
  98. package/transcript.ts +24 -0
  99. package/triggers.ts +11 -3
  100. package/types.ts +202 -44
  101. package/validate/contract-compat.ts +193 -0
  102. package/validate/graph.ts +125 -0
  103. package/validate/issue.ts +314 -0
  104. package/validate/stage-rules.ts +420 -0
  105. package/validate-output.ts +69 -1
  106. package/validate-workflow.ts +55 -759
  107. package/control-flow.ts +0 -135
  108. package/fanout.ts +0 -102
  109. package/iterate.ts +0 -155
  110. package/runner/resume-fanout.test.ts +0 -331
  111. package/runner/resume-fanout.ts +0 -136
  112. package/runner/resume-iterate.test.ts +0 -444
  113. package/runner/resume-iterate.ts +0 -111
  114. package/runner/stage-lifecycle.ts +0 -500
@@ -0,0 +1,1410 @@
1
+ /**
2
+ * End-to-end loop-resume tests — drive `resumeWorkflow` with a mock session
3
+ * chain over real `loop`-field workflows (fanout / iterate / assess), the ONE
4
+ * driver + ONE fold path. Complements the pure-fold cases in `resume.test.ts`.
5
+ *
6
+ * Resumed trail rows carry the STRUCTURED unit identity
7
+ * (`parent`/`role`/`unitId`/`unitIndex`); the decorated `stage` string is
8
+ * display-only and never parsed. The fold reconstructs the driver's own
9
+ * `LoopCursor` and verifies EVERY unit row against the recomputed expectation
10
+ * (the full-row drift guard).
11
+ *
12
+ * A-class contracts ported here (verbatim intent from the retired
13
+ * per-primitive resume suites):
14
+ * - re-run failed + remaining units only; finished-loop resume is a SILENT
15
+ * no-op (no onStageStart/onLoopStart re-fire, no per-unit/stage toast);
16
+ * - drift refusals: a recomputed unit differs from the recorded row, or a
17
+ * generator throws mid-fold → a parent-attributed terminal failure row,
18
+ * zero dispatch;
19
+ * - generation reset on a back-edge: only the trailing generation re-runs,
20
+ * `state.named` stays cumulative, generators legally read state produced
21
+ * outside the loop;
22
+ * - assess's four pending paths: pending judge, pending produce with a
23
+ * recovered verdict (feedForward, no re-grade), done-verdict fast advance,
24
+ * round-0 re-run (start + non-start), plus the missing-upstream refusal.
25
+ */
26
+
27
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
28
+ import { tmpdir } from "node:os";
29
+ import { join } from "node:path";
30
+ import { createMockSessionChain, mockAssistantMessage } from "@juicesharp/rpiv-test-utils";
31
+ import { Type } from "typebox";
32
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
33
+ import { acts, type FanoutFn, gate, type IterateFn, produces, type Workflow } from "../api.js";
34
+ import { fs as fsHandle } from "../handle.js";
35
+ import { judge } from "../judge.js";
36
+ import { assess, fanout, iterate, majority, panel, verify } from "../loop-constructors.js";
37
+ import type { Output } from "../output.js";
38
+ import type { Outcome } from "../output-spec.js";
39
+ import { eq, gt } from "../predicates.js";
40
+ import { appendStage, readAllStages, type WorkflowHeader, type WorkflowStage, writeHeader } from "../state/index.js";
41
+ import { typeboxSchema } from "../typebox-adapter.js";
42
+ import { resumeWorkflow } from "./runner.js";
43
+
44
+ // ---------------------------------------------------------------------------
45
+ // Shared scaffolding
46
+ // ---------------------------------------------------------------------------
47
+
48
+ let tmpDir: string;
49
+ beforeEach(() => {
50
+ tmpDir = mkdtempSync(join(tmpdir(), "rpiv-resume-loop-"));
51
+ });
52
+ afterEach(() => {
53
+ rmSync(tmpDir, { recursive: true, force: true });
54
+ });
55
+
56
+ const MD_PATTERN = /\.rpiv\/artifacts\/[\w.-]+\/[\w.-]+\.md/g;
57
+ const JSON_PATTERN = /\.rpiv\/verdicts\/[\w.-]+\.json/g;
58
+
59
+ const writeFile = (rel: string, content = "") => {
60
+ mkdirSync(join(tmpDir, ...rel.split("/").slice(0, -1)), { recursive: true });
61
+ writeFileSync(join(tmpDir, rel), content);
62
+ };
63
+
64
+ /** Collect EVERY `.rpiv/artifacts/.../*.md` match across the branch as artifacts. */
65
+ const transcriptOutcome = (name: string): Outcome<unknown, "artifact-md", Record<string, unknown>> => ({
66
+ name,
67
+ collector: {
68
+ collect: (ctx) => {
69
+ const matches: string[] = [];
70
+ for (let i = Math.max(ctx.branchOffset ?? 0, 0); i < ctx.branch.length; i++) {
71
+ const entry = ctx.branch[i]!;
72
+ if (entry.type !== "message" || entry.message?.role !== "assistant") continue;
73
+ const content = entry.message.content;
74
+ if (!Array.isArray(content)) continue;
75
+ for (const part of content) {
76
+ if (part.type === "text" && typeof part.text === "string") {
77
+ const m = part.text.match(MD_PATTERN);
78
+ if (m) matches.push(...m);
79
+ }
80
+ }
81
+ }
82
+ if (matches.length === 0) return { kind: "fatal", message: `${ctx.skill} produced no artifact path` };
83
+ return { kind: "ok", artifacts: matches.map((p) => ({ handle: fsHandle(p), role: "primary" as const })) };
84
+ },
85
+ },
86
+ parser: { parse: () => ({ kind: "ok", payload: { kind: "artifact-md", data: {} } }) },
87
+ });
88
+
89
+ /** Verdict outcome: scan for the last `.rpiv/verdicts/*.json`, parse to `{ done, feedback }`. */
90
+ const verdictOutcome = (name: string): Outcome<unknown, "verdict", Record<string, unknown>> & { name: string } => ({
91
+ name,
92
+ collector: {
93
+ collect: (ctx) => {
94
+ let path: string | undefined;
95
+ for (let i = Math.max(ctx.branchOffset ?? 0, 0); i < ctx.branch.length; i++) {
96
+ const entry = ctx.branch[i]!;
97
+ if (entry.type !== "message" || entry.message?.role !== "assistant") continue;
98
+ const content = entry.message.content;
99
+ if (!Array.isArray(content)) continue;
100
+ for (const part of content) {
101
+ if (part.type === "text" && typeof part.text === "string") {
102
+ const m = part.text.match(JSON_PATTERN);
103
+ if (m) path = m[m.length - 1];
104
+ }
105
+ }
106
+ }
107
+ if (!path) return { kind: "fatal", message: `${ctx.skill} produced no verdict path` };
108
+ return { kind: "ok", artifacts: [{ handle: fsHandle(path), role: "primary" }] };
109
+ },
110
+ },
111
+ parser: {
112
+ parse: (ctx) => {
113
+ const primary = ctx.artifacts[0];
114
+ const path = primary?.handle.kind === "fs" ? primary.handle.path : undefined;
115
+ if (!path) return { kind: "ok", payload: { kind: "verdict", data: {} } };
116
+ const abs = path.startsWith("/") ? path : join(ctx.cwd, path);
117
+ return { kind: "ok", payload: { kind: "verdict", data: JSON.parse(readFileSync(abs, "utf-8")) } };
118
+ },
119
+ },
120
+ });
121
+
122
+ // ===========================================================================
123
+ // Fanout
124
+ // ===========================================================================
125
+
126
+ describe("loop-resume — fanout", () => {
127
+ const header: WorkflowHeader = {
128
+ runId: "2026-06-03_07-30-00-ab12",
129
+ workflow: "fanout-wf",
130
+ input: "Ship it",
131
+ ts: "2026-06-03T07:30:00Z",
132
+ };
133
+
134
+ /** Deterministic 3-unit fanout (blind to artifact, stable across re-call). */
135
+ const threeUnits: FanoutFn = () =>
136
+ [1, 2, 3].map((n) => ({ prompt: `phase ${n}`, label: `phase ${n}/3`, id: `phase-${n}` }));
137
+
138
+ const fanoutWf: Workflow = {
139
+ name: "fanout-wf",
140
+ start: "impl",
141
+ stages: { impl: produces({ outcome: transcriptOutcome("plans"), loop: fanout({ units: threeUnits }) }) },
142
+ edges: { impl: "stop" },
143
+ } as Workflow;
144
+
145
+ function writeRun(stages: WorkflowStage[]): void {
146
+ writeHeader(tmpDir, header);
147
+ for (const s of stages) appendStage(tmpDir, header.runId, s);
148
+ }
149
+
150
+ const unitRow = (n: number, num: number, status: "completed" | "failed"): WorkflowStage => ({
151
+ session: null,
152
+ stageNumber: num,
153
+ stage: `impl (phase-${n})`,
154
+ skill: "impl",
155
+ status,
156
+ ts: `t${num}`,
157
+ parent: "impl",
158
+ role: "produce",
159
+ unitId: `phase-${n}`,
160
+ unitIndex: n - 1,
161
+ ...(status === "completed"
162
+ ? {
163
+ output: {
164
+ kind: "artifacts",
165
+ artifacts: [{ handle: fsHandle(`.rpiv/artifacts/plans/p${n}.md`), role: "primary" }],
166
+ data: {},
167
+ meta: { stage: "impl", stageNumber: num, ts: "", runId: "" },
168
+ } satisfies Output,
169
+ }
170
+ : { errMsg: "boom" }),
171
+ });
172
+
173
+ it("mid-fanout failure: re-runs only the failed unit + remaining, then chains to stop", async () => {
174
+ writeRun([unitRow(1, 1, "completed"), unitRow(2, 2, "completed"), unitRow(3, 3, "failed")]);
175
+ const chain = createMockSessionChain({
176
+ cwd: tmpDir,
177
+ steps: [{ branch: [mockAssistantMessage("wrote .rpiv/artifacts/plans/p3.md")] }],
178
+ });
179
+
180
+ const result = await resumeWorkflow(chain.ctx, { workflow: fanoutWf, header, ref: "@x" });
181
+
182
+ expect(result.success).toBe(true);
183
+ // Only unit 3 re-ran → exactly one new dispatch.
184
+ expect(chain.sentMessages).toEqual(["/skill:impl phase 3"]);
185
+ const rows = readAllStages(tmpDir, header.runId);
186
+ expect(rows).toHaveLength(4);
187
+ expect(rows[3]).toMatchObject({ stage: "impl (phase-3)", status: "completed", parent: "impl", unitIndex: 2 });
188
+ });
189
+
190
+ it("process died mid-fanout (no failure row): resumes at the next unit", async () => {
191
+ writeRun([unitRow(1, 1, "completed")]); // only unit 1 recorded
192
+ const chain = createMockSessionChain({
193
+ cwd: tmpDir,
194
+ steps: [
195
+ { branch: [mockAssistantMessage("wrote .rpiv/artifacts/plans/p2.md")] },
196
+ { branch: [mockAssistantMessage("wrote .rpiv/artifacts/plans/p3.md")] },
197
+ ],
198
+ });
199
+
200
+ const result = await resumeWorkflow(chain.ctx, { workflow: fanoutWf, header, ref: "@x" });
201
+
202
+ expect(result.success).toBe(true);
203
+ expect(chain.sentMessages).toEqual(["/skill:impl phase 2", "/skill:impl phase 3"]);
204
+ });
205
+
206
+ it("fully-completed fanout: SILENT no-op route-onward (no re-announce, no per-stage toast)", async () => {
207
+ writeRun([unitRow(1, 1, "completed"), unitRow(2, 2, "completed"), unitRow(3, 3, "completed")]);
208
+ const loopStarts: string[] = [];
209
+ const stageStarts: string[] = [];
210
+ const chain = createMockSessionChain({ cwd: tmpDir, steps: [] });
211
+
212
+ const result = await resumeWorkflow(chain.ctx, {
213
+ workflow: fanoutWf,
214
+ header,
215
+ ref: "@x",
216
+ lifecycle: {
217
+ onLoopStart: (stage) => {
218
+ loopStarts.push(stage.name);
219
+ },
220
+ onStageStart: (stage) => {
221
+ stageStarts.push(stage.name);
222
+ },
223
+ },
224
+ });
225
+
226
+ expect(result.success).toBe(true);
227
+ expect(chain.ctx.newSession).not.toHaveBeenCalled();
228
+ expect(readAllStages(tmpDir, header.runId)).toHaveLength(3); // no new rows
229
+ // The finished loop is NOT re-announced.
230
+ expect(loopStarts).toEqual([]);
231
+ expect(stageStarts).toEqual([]);
232
+ // ...and the only completion toast is the workflow-level one.
233
+ expect(chain.notifications.filter((n) => n.msg === "✓ impl completed")).toEqual([]);
234
+ expect(chain.notifications.filter((n) => /workflow complete/.test(n.msg))).toHaveLength(1);
235
+ });
236
+
237
+ it("non-deterministic fanout: recorded terminal failure, refuses to re-run wrong units", async () => {
238
+ // Recorded run had `phase-1` completed; the workflow now recomputes a different id.
239
+ const drifted: Workflow = {
240
+ name: "fanout-wf",
241
+ start: "impl",
242
+ stages: {
243
+ impl: produces({
244
+ outcome: transcriptOutcome("plans"),
245
+ loop: fanout({ units: () => [{ prompt: "x", label: "task 1", id: "task-1" }] }),
246
+ }),
247
+ },
248
+ edges: { impl: "stop" },
249
+ } as Workflow;
250
+ writeRun([unitRow(1, 1, "completed"), unitRow(2, 2, "failed")]);
251
+ const chain = createMockSessionChain({ cwd: tmpDir, steps: [] });
252
+
253
+ const result = await resumeWorkflow(chain.ctx, { workflow: drifted, header, ref: "@x" });
254
+
255
+ expect(result.success).toBe(false);
256
+ expect(result.error).toMatch(/deterministic/);
257
+ expect(result.runId).toBe(header.runId); // in-run failure → row written
258
+ const rows = readAllStages(tmpDir, header.runId);
259
+ expect(rows[rows.length - 1]).toMatchObject({ stage: "impl", status: "failed" });
260
+ expect(chain.sentMessages).toEqual([]); // no unit dispatched
261
+ });
262
+
263
+ it("generator throw mid-fold: recorded terminal failure, zero dispatch", async () => {
264
+ const thrower: Workflow = {
265
+ name: "fanout-wf",
266
+ start: "impl",
267
+ stages: {
268
+ impl: produces({
269
+ outcome: transcriptOutcome("plans"),
270
+ loop: fanout({
271
+ units: () => {
272
+ throw new Error("units-boom");
273
+ },
274
+ }),
275
+ }),
276
+ },
277
+ edges: { impl: "stop" },
278
+ } as Workflow;
279
+ writeRun([unitRow(1, 1, "completed"), unitRow(2, 2, "failed")]);
280
+ const chain = createMockSessionChain({ cwd: tmpDir, steps: [] });
281
+
282
+ const result = await resumeWorkflow(chain.ctx, { workflow: thrower, header, ref: "@x" });
283
+
284
+ expect(result.success).toBe(false);
285
+ expect(result.error).toMatch(/units-boom/);
286
+ const rows = readAllStages(tmpDir, header.runId);
287
+ expect(rows[rows.length - 1]).toMatchObject({ stage: "impl", status: "failed" });
288
+ expect(chain.sentMessages).toEqual([]);
289
+ });
290
+ });
291
+
292
+ // ===========================================================================
293
+ // Iterate
294
+ // ===========================================================================
295
+
296
+ describe("loop-resume — iterate", () => {
297
+ const header: WorkflowHeader = {
298
+ runId: "2026-06-03_08-00-00-cd34",
299
+ workflow: "polish",
300
+ input: "Ship it",
301
+ ts: "2026-06-03T08:00:00Z",
302
+ };
303
+ const REVIEW_3_PHASES = "# Review\n\n### Phase 1 — Alpha\nx\n### Phase 2 — Beta\ny\n### Phase 3 — Gamma\nz\n";
304
+
305
+ /** Deterministic per-phase generator keyed off the FROZEN review file. */
306
+ const reviewPhaseIterate: IterateFn = ({ artifact, index, cwd }) => {
307
+ if (artifact?.handle.kind !== "fs") return null;
308
+ const abs = artifact.handle.path.startsWith("/") ? artifact.handle.path : join(cwd, artifact.handle.path);
309
+ const phases = [...readFileSync(abs, "utf-8").matchAll(/^### Phase (\d+) — (.+)$/gm)];
310
+ if (index >= phases.length) return null;
311
+ const num = phases[index]![1];
312
+ return { prompt: `plan phase ${num}`, label: `phase ${index + 1}/${phases.length}`, id: `phase-${num}` };
313
+ };
314
+
315
+ const polishWf = (gen: IterateFn = reviewPhaseIterate): Workflow =>
316
+ ({
317
+ name: "polish",
318
+ start: "review",
319
+ stages: {
320
+ review: produces({ outcome: transcriptOutcome("reviews") }),
321
+ blueprint: produces({ outcome: transcriptOutcome("plans"), loop: iterate({ next: gen }) }),
322
+ consume: acts(),
323
+ },
324
+ edges: { review: "blueprint", blueprint: "consume", consume: "stop" },
325
+ }) as Workflow;
326
+
327
+ const out = (stage: string, num: number, rel: string): Output => ({
328
+ kind: "artifacts",
329
+ artifacts: [{ handle: fsHandle(rel), role: "primary" }],
330
+ data: {},
331
+ meta: { stage, stageNumber: num, ts: "", runId: "" },
332
+ });
333
+
334
+ const reviewRow: WorkflowStage = {
335
+ session: null,
336
+ stageNumber: 1,
337
+ stage: "review",
338
+ skill: "review",
339
+ status: "completed",
340
+ ts: "t1",
341
+ output: out("review", 1, ".rpiv/artifacts/reviews/rev.md"),
342
+ };
343
+
344
+ /** A recorded blueprint iterate-unit row. `phase` is the unit's phase number (== its id). */
345
+ const planRow = (phase: number, num: number, status: "completed" | "failed"): WorkflowStage => ({
346
+ session: null,
347
+ stageNumber: num,
348
+ stage: `blueprint (phase-${phase})`,
349
+ skill: "blueprint",
350
+ status,
351
+ ts: `t${num}`,
352
+ parent: "blueprint",
353
+ role: "produce",
354
+ unitId: `phase-${phase}`,
355
+ unitIndex: phase - 1,
356
+ ...(status === "completed"
357
+ ? { output: out("blueprint", num, `.rpiv/artifacts/plans/p${phase}.md`) }
358
+ : { errMsg: "boom" }),
359
+ });
360
+
361
+ function writeRun(stages: WorkflowStage[]): void {
362
+ writeFile(".rpiv/artifacts/reviews/rev.md", REVIEW_3_PHASES);
363
+ writeHeader(tmpDir, header);
364
+ for (const s of stages) appendStage(tmpDir, header.runId, s);
365
+ }
366
+
367
+ it("mid-iterate failure: re-pulls + re-runs the failed unit + remaining, then chains to consume/stop", async () => {
368
+ writeRun([reviewRow, planRow(1, 2, "completed"), planRow(2, 3, "failed")]);
369
+ const chain = createMockSessionChain({
370
+ cwd: tmpDir,
371
+ steps: [
372
+ { branch: [mockAssistantMessage("wrote .rpiv/artifacts/plans/p2.md")] }, // phase-2 re-run
373
+ { branch: [mockAssistantMessage("wrote .rpiv/artifacts/plans/p3.md")] }, // phase-3
374
+ { branch: [mockAssistantMessage("consumed")] }, // consume
375
+ ],
376
+ });
377
+ const result = await resumeWorkflow(chain.ctx, { workflow: polishWf(), header, ref: "@x" });
378
+ expect(result.success).toBe(true);
379
+ // phase-2 (re-run), phase-3, consume — phase-1 NOT re-run.
380
+ expect(chain.sentMessages).toEqual([
381
+ "/skill:blueprint plan phase 2",
382
+ "/skill:blueprint plan phase 3",
383
+ expect.stringContaining("consume"),
384
+ ]);
385
+ const rows = readAllStages(tmpDir, header.runId);
386
+ expect(rows[rows.length - 1]).toMatchObject({ stage: "consume", status: "completed" });
387
+ });
388
+
389
+ it("fully-completed iterate trailer: no-op, routes onward; the probe pull dispatches nothing", async () => {
390
+ // All 3 phases done; trailer is the last completed unit (process died before advanceChain).
391
+ writeRun([reviewRow, planRow(1, 2, "completed"), planRow(2, 3, "completed"), planRow(3, 4, "completed")]);
392
+ const chain = createMockSessionChain({
393
+ cwd: tmpDir,
394
+ steps: [{ branch: [mockAssistantMessage("consumed")] }],
395
+ });
396
+ const result = await resumeWorkflow(chain.ctx, { workflow: polishWf(), header, ref: "@x" });
397
+ expect(result.success).toBe(true);
398
+ // Only `consume` ran; the probe pull (next→null) re-ran no blueprint unit.
399
+ expect(chain.sentMessages).toEqual([expect.stringContaining("consume")]);
400
+ });
401
+
402
+ it("non-deterministic IterateFn: boundary mismatch records terminal failure, runs no unit", async () => {
403
+ const drifted: IterateFn = ({ index }) =>
404
+ index >= 3 ? null : { prompt: "x", label: `task ${index}`, id: `task-${index}` };
405
+ writeRun([reviewRow, planRow(1, 2, "completed"), planRow(2, 3, "failed")]);
406
+ const chain = createMockSessionChain({ cwd: tmpDir, steps: [] });
407
+ const result = await resumeWorkflow(chain.ctx, { workflow: polishWf(drifted), header, ref: "@x" });
408
+ expect(result.success).toBe(false);
409
+ expect(result.error).toMatch(/deterministic/);
410
+ expect(result.runId).toBe(header.runId);
411
+ const rows = readAllStages(tmpDir, header.runId);
412
+ expect(rows[rows.length - 1]).toMatchObject({ stage: "blueprint", status: "failed" });
413
+ expect(chain.sentMessages).toEqual([]);
414
+ });
415
+
416
+ it("generator throw AFTER the fold: recorded terminal failure envelope, not an escaped rejection", async () => {
417
+ // Deterministic through the fold's two verification pulls, then throws —
418
+ // exercises the post-fold re-entry (the `hasPendingUnit` probe + the
419
+ // driver's pull), which runs outside the fold's guarded() wrapper.
420
+ let calls = 0;
421
+ const throwsAfterFold: IterateFn = (ctx) => {
422
+ calls++;
423
+ if (calls > 2) throw new Error("probe boom");
424
+ return reviewPhaseIterate(ctx);
425
+ };
426
+ writeRun([reviewRow, planRow(1, 2, "completed"), planRow(2, 3, "failed")]);
427
+ const chain = createMockSessionChain({ cwd: tmpDir, steps: [] });
428
+ const result = await resumeWorkflow(chain.ctx, { workflow: polishWf(throwsAfterFold), header, ref: "@x" });
429
+ expect(result.success).toBe(false);
430
+ expect(result.error).toBe("probe boom");
431
+ expect(result.runId).toBe(header.runId);
432
+ const rows = readAllStages(tmpDir, header.runId);
433
+ expect(rows[rows.length - 1]).toMatchObject({ stage: "blueprint", status: "failed" });
434
+ expect(chain.sentMessages).toEqual([]);
435
+ });
436
+ });
437
+
438
+ // ===========================================================================
439
+ // Iterate — corrective back-edge (generation reset + generator reads state)
440
+ // ===========================================================================
441
+
442
+ describe("loop-resume — iterate corrective back-edge", () => {
443
+ const header: WorkflowHeader = {
444
+ runId: "2026-06-03_09-00-00-ef56",
445
+ workflow: "polish-loop",
446
+ input: "Ship it",
447
+ ts: "2026-06-03T09:00:00Z",
448
+ };
449
+ const REVIEW_2_PHASES = "# Review\n\n### Phase 1 — A\nx\n### Phase 2 — B\ny\n";
450
+
451
+ /** Sources the review from state.named (robust to the rolling primary being the code-review doc on re-entry). */
452
+ const reviewFromState: IterateFn = ({ state, index, cwd }) => {
453
+ const review = state.named.architecture_reviews?.at(-1)?.artifacts.find((a) => a.handle.kind === "fs");
454
+ if (review?.handle.kind !== "fs") return null;
455
+ const abs = review.handle.path.startsWith("/") ? review.handle.path : join(cwd, review.handle.path);
456
+ const phases = [...readFileSync(abs, "utf-8").matchAll(/^### Phase (\d+) — (.+)$/gm)];
457
+ if (index >= phases.length) return null;
458
+ const num = phases[index]![1];
459
+ return {
460
+ prompt: `${review.handle.path} Phase ${num}`,
461
+ label: `phase ${index + 1}/${phases.length}`,
462
+ id: `phase-${num}`,
463
+ };
464
+ };
465
+
466
+ const blockersOutcome = (name: string): Outcome<unknown, "artifact-md", Record<string, unknown>> => ({
467
+ name,
468
+ collector: transcriptOutcome(name).collector,
469
+ parser: {
470
+ parse: (ctx) => {
471
+ const primary = ctx.artifacts[0];
472
+ if (primary?.handle.kind !== "fs") return { kind: "ok", payload: { kind: "artifact-md", data: {} } };
473
+ const abs = primary.handle.path.startsWith("/") ? primary.handle.path : join(ctx.cwd, primary.handle.path);
474
+ const m = readFileSync(abs, "utf-8").match(/blockers_count:\s*(\d+)/);
475
+ return { kind: "ok", payload: { kind: "artifact-md", data: { blockers_count: Number(m?.[1] ?? 0) } } };
476
+ },
477
+ },
478
+ });
479
+
480
+ const plansFanout: FanoutFn = ({ state }) =>
481
+ (state.named.plans ?? [])
482
+ .flatMap((o) => o.artifacts)
483
+ .filter((a) => a.handle.kind === "fs")
484
+ .map((a, i) => ({ prompt: a.handle.kind === "fs" ? a.handle.path : "", label: `plan ${i + 1}` }));
485
+
486
+ const out = (stage: string, num: number, rel: string): Output => ({
487
+ kind: "artifacts",
488
+ artifacts: [{ handle: fsHandle(rel), role: "primary" }],
489
+ data: {},
490
+ meta: { stage, stageNumber: num, ts: "", runId: "" },
491
+ });
492
+
493
+ const planRow = (phase: number, num: number, rel: string, status: "completed" | "failed"): WorkflowStage => ({
494
+ session: null,
495
+ stageNumber: num,
496
+ stage: `blueprint (phase-${phase})`,
497
+ skill: "blueprint",
498
+ status,
499
+ ts: `t${num}`,
500
+ parent: "blueprint",
501
+ role: "produce",
502
+ unitId: `phase-${phase}`,
503
+ unitIndex: phase - 1,
504
+ ...(status === "completed" ? { output: out("blueprint", num, rel) } : { errMsg: "boom" }),
505
+ });
506
+
507
+ it("resumes the trailing generation only; state.named.plans keeps both generations", async () => {
508
+ writeFile(".rpiv/artifacts/architecture_reviews/rev.md", REVIEW_2_PHASES);
509
+
510
+ writeHeader(tmpDir, header);
511
+ const rows: WorkflowStage[] = [
512
+ {
513
+ session: null,
514
+ stageNumber: 1,
515
+ stage: "review",
516
+ skill: "review",
517
+ status: "completed",
518
+ ts: "t1",
519
+ output: out("review", 1, ".rpiv/artifacts/architecture_reviews/rev.md"),
520
+ },
521
+ planRow(1, 2, ".rpiv/artifacts/plans/g1p1.md", "completed"),
522
+ planRow(2, 3, ".rpiv/artifacts/plans/g1p2.md", "completed"),
523
+ {
524
+ session: null,
525
+ stageNumber: 4,
526
+ stage: "code-review",
527
+ skill: "code-review",
528
+ status: "completed",
529
+ ts: "t4",
530
+ output: out("code-review", 4, ".rpiv/artifacts/reviews/cr1.md"),
531
+ },
532
+ // gen 2 — non-contiguous with gen 1 (the code-review row broke contiguity).
533
+ planRow(1, 5, ".rpiv/artifacts/plans/g2p1.md", "completed"),
534
+ planRow(2, 6, "", "failed"),
535
+ ];
536
+ for (const s of rows) appendStage(tmpDir, header.runId, s);
537
+
538
+ const chain = createMockSessionChain({
539
+ cwd: tmpDir,
540
+ steps: [
541
+ { branch: [mockAssistantMessage("wrote .rpiv/artifacts/plans/g2p2.md")] }, // gen-2 phase-2 re-run
542
+ { branch: [mockAssistantMessage("wrote .rpiv/artifacts/reviews/cr2.md")] }, // code-review → blockers=0
543
+ { branch: [mockAssistantMessage("impl 1")] },
544
+ { branch: [mockAssistantMessage("impl 2")] },
545
+ { branch: [mockAssistantMessage("impl 3")] },
546
+ { branch: [mockAssistantMessage("impl 4")] },
547
+ ],
548
+ });
549
+
550
+ writeFile(".rpiv/artifacts/reviews/cr2.md", "---\nblockers_count: 0\n---\n");
551
+
552
+ const wf: Workflow = {
553
+ name: "polish-loop",
554
+ start: "review",
555
+ stages: {
556
+ review: produces({ outcome: transcriptOutcome("architecture_reviews") }),
557
+ blueprint: produces({ outcome: transcriptOutcome("plans"), loop: iterate({ next: reviewFromState }) }),
558
+ "code-review": produces({
559
+ outcome: blockersOutcome("reviews"),
560
+ outputSchema: typeboxSchema(Type.Object({ blockers_count: Type.Number() })),
561
+ }),
562
+ consume: acts({ loop: fanout({ units: plansFanout }) }),
563
+ },
564
+ edges: {
565
+ review: "blueprint",
566
+ blueprint: "code-review",
567
+ "code-review": gate("blockers_count", { blueprint: gt(0), consume: eq(0) }, "consume"),
568
+ consume: "stop",
569
+ },
570
+ } as Workflow;
571
+
572
+ const result = await resumeWorkflow(chain.ctx, { workflow: wf, header, ref: "@x" });
573
+
574
+ expect(result.success).toBe(true);
575
+ // Only the trailing generation's remaining unit (phase-2) re-ran — phase-1 of gen 2 did NOT.
576
+ const blueprintMsgs = chain.sentMessages.filter((m) => m.startsWith("/skill:blueprint"));
577
+ expect(blueprintMsgs).toEqual(["/skill:blueprint .rpiv/artifacts/architecture_reviews/rev.md Phase 2"]);
578
+ // The consume fanout saw ALL FOUR plans — state.named["plans"] carried both generations.
579
+ expect(chain.sentMessages.slice(-4)).toEqual([
580
+ "/skill:consume .rpiv/artifacts/plans/g1p1.md",
581
+ "/skill:consume .rpiv/artifacts/plans/g1p2.md",
582
+ "/skill:consume .rpiv/artifacts/plans/g2p1.md",
583
+ "/skill:consume .rpiv/artifacts/plans/g2p2.md",
584
+ ]);
585
+ });
586
+ });
587
+
588
+ // ===========================================================================
589
+ // Assess — the four pending sub-step paths + refusals
590
+ // ===========================================================================
591
+
592
+ describe("loop-resume — assess", () => {
593
+ const header: WorkflowHeader = {
594
+ runId: "2026-06-03_10-00-00-aa11",
595
+ workflow: "decompose",
596
+ input: "decompose this",
597
+ ts: "2026-06-03T10:00:00Z",
598
+ };
599
+
600
+ const done = (v: Output) => Boolean((v.data as { done?: boolean }).done);
601
+ const feedForward = ({ verdict, round }: { verdict: Output; round: number }) =>
602
+ `refine round=${round} fb=${(verdict.data as { feedback?: string }).feedback}`;
603
+
604
+ /** breakdown (assess; start) → consume. */
605
+ const assessWf: Workflow = {
606
+ name: "decompose",
607
+ start: "breakdown",
608
+ stages: {
609
+ breakdown: produces({
610
+ outcome: transcriptOutcome("tasks"),
611
+ loop: assess({ judge: judge({ skill: "grade", outcome: verdictOutcome("verdict") }), done, feedForward }),
612
+ }),
613
+ consume: acts(),
614
+ },
615
+ edges: { breakdown: "consume", consume: "stop" },
616
+ } as Workflow;
617
+
618
+ const writeVerdict = (n: number, isDone: boolean, feedback = `fb${n}`): string => {
619
+ const rel = `.rpiv/verdicts/v${n}.json`;
620
+ writeFile(rel, JSON.stringify({ done: isDone, feedback }));
621
+ return rel;
622
+ };
623
+
624
+ const taskOutput = (round: number, num: number): Output => ({
625
+ kind: "artifacts",
626
+ artifacts: [{ handle: fsHandle(`.rpiv/artifacts/tasks/t${round}.md`), role: "primary" }],
627
+ data: {},
628
+ meta: { stage: "breakdown", stageNumber: num, ts: "", runId: "" },
629
+ });
630
+
631
+ const verdictOutput = (round: number, num: number, isDone: boolean): Output => ({
632
+ kind: "artifacts",
633
+ artifacts: [{ handle: fsHandle(`.rpiv/verdicts/v${round}.json`), role: "primary" }],
634
+ data: { done: isDone, feedback: `fb${round}` },
635
+ meta: { stage: "breakdown", stageNumber: num, ts: "", runId: "" },
636
+ });
637
+
638
+ const produceRow = (round: number, num: number, status: WorkflowStage["status"] = "completed"): WorkflowStage => ({
639
+ session: null,
640
+ stageNumber: num,
641
+ stage: `breakdown (r${round}·produce)`,
642
+ skill: "breakdown",
643
+ status,
644
+ ts: `t${num}`,
645
+ parent: "breakdown",
646
+ role: "produce",
647
+ unitIndex: round,
648
+ ...(status === "completed" ? { output: taskOutput(round, num) } : { errMsg: "boom" }),
649
+ });
650
+
651
+ const judgeRow = (round: number, num: number, isDone: boolean): WorkflowStage => ({
652
+ session: null,
653
+ stageNumber: num,
654
+ stage: `breakdown (r${round}·judge)`,
655
+ skill: "grade",
656
+ status: "completed",
657
+ ts: `t${num}`,
658
+ parent: "breakdown",
659
+ role: "judge",
660
+ unitIndex: round,
661
+ output: verdictOutput(round, num, isDone),
662
+ });
663
+
664
+ function writeRun(stages: WorkflowStage[]): void {
665
+ writeHeader(tmpDir, header);
666
+ for (const s of stages) appendStage(tmpDir, header.runId, s);
667
+ }
668
+
669
+ it("resume-at-judge: a completed-producer trailer grades round n, then advances on done", async () => {
670
+ writeRun([produceRow(0, 1, "completed")]); // died after the round-0 producer
671
+ writeVerdict(0, true);
672
+ const chain = createMockSessionChain({
673
+ cwd: tmpDir,
674
+ steps: [
675
+ { branch: [mockAssistantMessage("verdict .rpiv/verdicts/v0.json")] }, // judge round 0
676
+ { branch: [mockAssistantMessage("consumed")] }, // consume
677
+ ],
678
+ });
679
+
680
+ const result = await resumeWorkflow(chain.ctx, { workflow: assessWf, header, ref: "@x" });
681
+
682
+ expect(result.success).toBe(true);
683
+ expect(chain.sentMessages).toEqual([
684
+ "/skill:grade .rpiv/artifacts/tasks/t0.md",
685
+ "/skill:consume .rpiv/artifacts/tasks/t0.md",
686
+ ]);
687
+ const rows = readAllStages(tmpDir, header.runId);
688
+ expect(rows[rows.length - 1]).toMatchObject({ stage: "consume", status: "completed" });
689
+ });
690
+
691
+ it("resume-at-produce: a not-done judge trailer runs produce n+1, feedForward sees the recovered verdict (no re-grade)", async () => {
692
+ writeRun([produceRow(0, 1, "completed"), judgeRow(0, 2, false)]);
693
+ writeVerdict(1, true);
694
+ const chain = createMockSessionChain({
695
+ cwd: tmpDir,
696
+ steps: [
697
+ { branch: [mockAssistantMessage("wrote .rpiv/artifacts/tasks/t1.md")] }, // produce round 1
698
+ { branch: [mockAssistantMessage("verdict .rpiv/verdicts/v1.json")] }, // judge round 1
699
+ { branch: [mockAssistantMessage("consumed")] },
700
+ ],
701
+ });
702
+
703
+ const result = await resumeWorkflow(chain.ctx, { workflow: assessWf, header, ref: "@x" });
704
+
705
+ expect(result.success).toBe(true);
706
+ // No re-grade of round 0 — the recovered verdict (fb0) feeds straight into feedForward.
707
+ expect(chain.sentMessages).toEqual([
708
+ "/skill:breakdown refine round=0 fb=fb0",
709
+ "/skill:grade .rpiv/artifacts/tasks/t1.md",
710
+ "/skill:consume .rpiv/artifacts/tasks/t1.md",
711
+ ]);
712
+ });
713
+
714
+ it("resume-after-done: a done judge trailer advances downstream with no re-run", async () => {
715
+ writeRun([produceRow(0, 1, "completed"), judgeRow(0, 2, true)]);
716
+ const chain = createMockSessionChain({
717
+ cwd: tmpDir,
718
+ steps: [{ branch: [mockAssistantMessage("consumed")] }],
719
+ });
720
+
721
+ const result = await resumeWorkflow(chain.ctx, { workflow: assessWf, header, ref: "@x" });
722
+
723
+ expect(result.success).toBe(true);
724
+ // No breakdown/grade re-run — straight to consume with the last producer output.
725
+ expect(chain.sentMessages).toEqual(["/skill:consume .rpiv/artifacts/tasks/t0.md"]);
726
+ });
727
+
728
+ it("resume-at-produce-0: a failed round-0 producer re-runs produce 0 from the entry arg (start stage → original input)", async () => {
729
+ writeRun([produceRow(0, 1, "failed")]);
730
+ writeVerdict(0, true);
731
+ const chain = createMockSessionChain({
732
+ cwd: tmpDir,
733
+ steps: [
734
+ { branch: [mockAssistantMessage("wrote .rpiv/artifacts/tasks/t0.md")] }, // re-run produce 0
735
+ { branch: [mockAssistantMessage("verdict .rpiv/verdicts/v0.json")] }, // judge round 0
736
+ { branch: [mockAssistantMessage("consumed")] },
737
+ ],
738
+ });
739
+
740
+ const result = await resumeWorkflow(chain.ctx, { workflow: assessWf, header, ref: "@x" });
741
+
742
+ expect(result.success).toBe(true);
743
+ expect(chain.sentMessages).toEqual([
744
+ "/skill:breakdown decompose this",
745
+ "/skill:grade .rpiv/artifacts/tasks/t0.md",
746
+ "/skill:consume .rpiv/artifacts/tasks/t0.md",
747
+ ]);
748
+ });
749
+
750
+ // --- NON-start assess stage — stageEntryArgs' recovered-primary branch (frozen at fold open) ---
751
+
752
+ const seedOutput = (num: number): Output => ({
753
+ kind: "artifacts",
754
+ artifacts: [{ handle: fsHandle(".rpiv/artifacts/seed/s0.md"), role: "primary" }],
755
+ data: {},
756
+ meta: { stage: "review", stageNumber: num, ts: "", runId: "" },
757
+ });
758
+
759
+ const reviewRow = (num: number): WorkflowStage => ({
760
+ session: null,
761
+ stageNumber: num,
762
+ stage: "review",
763
+ skill: "review",
764
+ status: "completed",
765
+ ts: `t${num}`,
766
+ output: seedOutput(num),
767
+ });
768
+
769
+ const nonStartAssessWf: Workflow = {
770
+ name: "decompose",
771
+ start: "review",
772
+ stages: {
773
+ review: produces({ outcome: transcriptOutcome("seed") }),
774
+ breakdown: produces({
775
+ outcome: transcriptOutcome("tasks"),
776
+ loop: assess({ judge: judge({ skill: "grade", outcome: verdictOutcome("verdict") }), done, feedForward }),
777
+ }),
778
+ consume: acts(),
779
+ },
780
+ edges: { review: "breakdown", breakdown: "consume", consume: "stop" },
781
+ } as Workflow;
782
+
783
+ it("resume-at-produce-0 of a NON-start assess stage re-runs produce 0 from the recovered upstream primary handle", async () => {
784
+ writeRun([reviewRow(1), produceRow(0, 2, "failed")]);
785
+ writeVerdict(0, true);
786
+ const chain = createMockSessionChain({
787
+ cwd: tmpDir,
788
+ steps: [
789
+ { branch: [mockAssistantMessage("wrote .rpiv/artifacts/tasks/t0.md")] }, // re-run produce 0
790
+ { branch: [mockAssistantMessage("verdict .rpiv/verdicts/v0.json")] }, // judge round 0
791
+ { branch: [mockAssistantMessage("consumed")] },
792
+ ],
793
+ });
794
+
795
+ const result = await resumeWorkflow(chain.ctx, { workflow: nonStartAssessWf, header, ref: "@x" });
796
+
797
+ expect(result.success).toBe(true);
798
+ // Entry arg is review's recovered primary handle, NOT the original input.
799
+ expect(chain.sentMessages).toEqual([
800
+ "/skill:breakdown .rpiv/artifacts/seed/s0.md",
801
+ "/skill:grade .rpiv/artifacts/tasks/t0.md",
802
+ "/skill:consume .rpiv/artifacts/tasks/t0.md",
803
+ ]);
804
+ });
805
+
806
+ it("refuses with a recorded failure when the trail lacks the upstream primary a non-start assess re-entry needs", async () => {
807
+ // Corrupted/truncated trail: the round-0 producer row exists but the upstream review row is gone.
808
+ writeRun([produceRow(0, 1, "failed")]);
809
+ const chain = createMockSessionChain({ cwd: tmpDir, steps: [] });
810
+
811
+ const result = await resumeWorkflow(chain.ctx, { workflow: nonStartAssessWf, header, ref: "@x" });
812
+
813
+ expect(result.success).toBe(false);
814
+ expect(result.error).toMatch(/no upstream artifactPath/i);
815
+ expect(chain.sentMessages).toEqual([]);
816
+ const rows = readAllStages(tmpDir, header.runId);
817
+ expect(rows[rows.length - 1]).toMatchObject({ stage: "breakdown", status: "failed" });
818
+ });
819
+
820
+ it("done-predicate drift: a produce row for round n>0 whose recorded verdict now reads done → terminal failure", async () => {
821
+ // Recorded: round 0 judged not-done (so a round-1 producer ran). The workflow's
822
+ // `done` now returns true for that verdict — the predicate drifted.
823
+ const driftedWf: Workflow = {
824
+ name: "decompose",
825
+ start: "breakdown",
826
+ stages: {
827
+ breakdown: produces({
828
+ outcome: transcriptOutcome("tasks"),
829
+ loop: assess({
830
+ judge: judge({ skill: "grade", outcome: verdictOutcome("verdict") }),
831
+ done: () => true,
832
+ feedForward,
833
+ }),
834
+ }),
835
+ consume: acts(),
836
+ },
837
+ edges: { breakdown: "consume", consume: "stop" },
838
+ } as Workflow;
839
+ writeRun([produceRow(0, 1, "completed"), judgeRow(0, 2, false), produceRow(1, 3, "failed")]);
840
+ const chain = createMockSessionChain({ cwd: tmpDir, steps: [] });
841
+
842
+ const result = await resumeWorkflow(chain.ctx, { workflow: driftedWf, header, ref: "@x" });
843
+
844
+ expect(result.success).toBe(false);
845
+ expect(result.error).toMatch(/deterministic/);
846
+ const rows = readAllStages(tmpDir, header.runId);
847
+ expect(rows[rows.length - 1]).toMatchObject({ stage: "breakdown", status: "failed" });
848
+ expect(chain.sentMessages).toEqual([]);
849
+ });
850
+ });
851
+
852
+ describe("loop-resume — assess × panel", () => {
853
+ const header: WorkflowHeader = {
854
+ runId: "2026-06-03_11-00-00-cc33",
855
+ workflow: "decompose",
856
+ input: "decompose this",
857
+ ts: "2026-06-03T11:00:00Z",
858
+ };
859
+
860
+ // The SITE's `done` reads the FOLDED verdict's `pass`; each member's `pred`
861
+ // reads its own `{ done }` — the two predicates are deliberately distinct (§4).
862
+ const panelDone = (v: Output) => Boolean((v.data as { pass?: boolean }).pass);
863
+ const panelFeed = ({ verdict, round }: { verdict: Output; round: number }) =>
864
+ `refine round=${round} pass=${(verdict.data as { pass?: boolean }).pass}`;
865
+
866
+ /** breakdown (assess × 3-judge panel; start) → consume. */
867
+ const panelWf: Workflow = {
868
+ name: "decompose",
869
+ start: "breakdown",
870
+ stages: {
871
+ breakdown: produces({
872
+ outcome: transcriptOutcome("tasks"),
873
+ loop: assess({
874
+ judge: panel({
875
+ members: [
876
+ judge({ skill: "grade-a", outcome: verdictOutcome("verdict-a") }),
877
+ judge({ skill: "grade-b", outcome: verdictOutcome("verdict-b") }),
878
+ judge({ skill: "grade-c", outcome: verdictOutcome("verdict-c") }),
879
+ ],
880
+ fold: majority((v) => Boolean((v.data as { done?: boolean }).done)),
881
+ }),
882
+ done: panelDone,
883
+ feedForward: panelFeed,
884
+ }),
885
+ }),
886
+ consume: acts(),
887
+ },
888
+ edges: { breakdown: "consume", consume: "stop" },
889
+ } as Workflow;
890
+
891
+ const taskOutput = (round: number, num: number): Output => ({
892
+ kind: "artifacts",
893
+ artifacts: [{ handle: fsHandle(`.rpiv/artifacts/tasks/t${round}.md`), role: "primary" }],
894
+ data: {},
895
+ meta: { stage: "breakdown", stageNumber: num, ts: "", runId: "" },
896
+ });
897
+
898
+ const produceRow = (round: number, num: number, status: WorkflowStage["status"] = "completed"): WorkflowStage => ({
899
+ session: null,
900
+ stageNumber: num,
901
+ stage: `breakdown (r${round}·produce)`,
902
+ skill: "breakdown",
903
+ status,
904
+ ts: `t${num}`,
905
+ parent: "breakdown",
906
+ role: "produce",
907
+ unitIndex: round,
908
+ ...(status === "completed" ? { output: taskOutput(round, num) } : { errMsg: "boom" }),
909
+ });
910
+
911
+ const memberRow = (round: number, m: number, num: number, isDone: boolean): WorkflowStage => ({
912
+ session: null,
913
+ stageNumber: num,
914
+ stage: `breakdown (r${round}·judge#${m})`,
915
+ skill: `grade-${"abc"[m]}`,
916
+ status: "completed",
917
+ ts: `t${num}`,
918
+ parent: "breakdown",
919
+ role: "judge",
920
+ unitId: `r${round}·judge#${m}`,
921
+ unitIndex: round,
922
+ output: {
923
+ kind: "artifacts",
924
+ artifacts: [{ handle: fsHandle(`.rpiv/verdicts/v${round}${"abc"[m]}.json`), role: "primary" }],
925
+ data: { done: isDone },
926
+ meta: { stage: "breakdown", stageNumber: num, ts: "", runId: "" },
927
+ },
928
+ });
929
+
930
+ function writeRun(stages: WorkflowStage[]): void {
931
+ writeHeader(tmpDir, header);
932
+ for (const s of stages) appendStage(tmpDir, header.runId, s);
933
+ }
934
+
935
+ it("mid-panel resume: re-runs ONLY the pending member, folds all three verdicts, advances on the folded pass", async () => {
936
+ // Round 0: producer + members a, b graded; the process died before member c.
937
+ writeRun([produceRow(0, 1), memberRow(0, 0, 2, true), memberRow(0, 1, 3, true)]);
938
+ // Member c grades not-done → majority(2-of-3) still passes ⇒ done, no retry.
939
+ writeFile(".rpiv/verdicts/v0c.json", JSON.stringify({ done: false }));
940
+ const chain = createMockSessionChain({
941
+ cwd: tmpDir,
942
+ steps: [
943
+ { branch: [mockAssistantMessage("verdict .rpiv/verdicts/v0c.json")] }, // ONLY member c re-runs
944
+ { branch: [mockAssistantMessage("consumed")] },
945
+ ],
946
+ });
947
+
948
+ const result = await resumeWorkflow(chain.ctx, { workflow: panelWf, header, ref: "@x" });
949
+
950
+ expect(result.success).toBe(true);
951
+ // Members a + b replayed from the trail (no re-grade); only c re-dispatched,
952
+ // then the recomputed fold passed → straight to consume (no producer re-run).
953
+ expect(chain.sentMessages).toEqual([
954
+ "/skill:grade-c .rpiv/artifacts/tasks/t0.md",
955
+ "/skill:consume .rpiv/artifacts/tasks/t0.md",
956
+ ]);
957
+ // Member c's row landed after the two replayed members — one panel round total.
958
+ const rows = readAllStages(tmpDir, header.runId);
959
+ expect(rows.filter((r) => r.role === "judge").map((r) => r.unitId)).toEqual([
960
+ "r0·judge#0",
961
+ "r0·judge#1",
962
+ "r0·judge#2",
963
+ ]);
964
+ expect(rows[rows.length - 1]).toMatchObject({ stage: "consume", status: "completed" });
965
+ });
966
+
967
+ it("mid-panel resume drives a RETRY when the recomputed fold fails (unanimous veto via majority miss)", async () => {
968
+ // Round 0: members a (done), b (not-done) graded; died before c. If c is also
969
+ // not-done, majority is 1-of-3 → fail ⇒ feedForward + a round-1 producer.
970
+ writeRun([produceRow(0, 1), memberRow(0, 0, 2, true), memberRow(0, 1, 3, false)]);
971
+ writeFile(".rpiv/verdicts/v0c.json", JSON.stringify({ done: false })); // 1-of-3 → fold fails
972
+ writeFile(".rpiv/verdicts/v1a.json", JSON.stringify({ done: true }));
973
+ writeFile(".rpiv/verdicts/v1b.json", JSON.stringify({ done: true }));
974
+ writeFile(".rpiv/verdicts/v1c.json", JSON.stringify({ done: true })); // unanimous → round 1 passes
975
+ const chain = createMockSessionChain({
976
+ cwd: tmpDir,
977
+ steps: [
978
+ { branch: [mockAssistantMessage("verdict .rpiv/verdicts/v0c.json")] }, // member c (round 0)
979
+ { branch: [mockAssistantMessage("wrote .rpiv/artifacts/tasks/t1.md")] }, // round-1 producer
980
+ { branch: [mockAssistantMessage("verdict .rpiv/verdicts/v1a.json")] },
981
+ { branch: [mockAssistantMessage("verdict .rpiv/verdicts/v1b.json")] },
982
+ { branch: [mockAssistantMessage("verdict .rpiv/verdicts/v1c.json")] },
983
+ { branch: [mockAssistantMessage("consumed")] },
984
+ ],
985
+ });
986
+
987
+ const result = await resumeWorkflow(chain.ctx, { workflow: panelWf, header, ref: "@x" });
988
+
989
+ expect(result.success).toBe(true);
990
+ // c re-runs and folds to fail → feedForward carries the FOLDED verdict into
991
+ // round 1 (all three members re-grade), which passes → consume.
992
+ expect(chain.sentMessages).toEqual([
993
+ "/skill:grade-c .rpiv/artifacts/tasks/t0.md",
994
+ "/skill:breakdown refine round=0 pass=false",
995
+ "/skill:grade-a .rpiv/artifacts/tasks/t1.md",
996
+ "/skill:grade-b .rpiv/artifacts/tasks/t1.md",
997
+ "/skill:grade-c .rpiv/artifacts/tasks/t1.md",
998
+ "/skill:consume .rpiv/artifacts/tasks/t1.md",
999
+ ]);
1000
+ });
1001
+ });
1002
+
1003
+ describe("loop-resume — verify", () => {
1004
+ const header: WorkflowHeader = {
1005
+ runId: "2026-06-10_22-00-00-bb22",
1006
+ workflow: "gated",
1007
+ input: "build it",
1008
+ ts: "2026-06-10T22:00:00Z",
1009
+ };
1010
+
1011
+ const pass = (v: Output) => Boolean((v.data as { done?: boolean }).done);
1012
+ const vFeedForward = ({ verdict, round }: { verdict: Output; round: number }) =>
1013
+ `fix round=${round} fb=${(verdict.data as { feedback?: string }).feedback}`;
1014
+
1015
+ const gatedWf = (max = 3): Workflow =>
1016
+ ({
1017
+ name: "gated",
1018
+ start: "build",
1019
+ stages: {
1020
+ build: produces({
1021
+ outcome: transcriptOutcome("impl"),
1022
+ verify:
1023
+ max === 1
1024
+ ? verify({ judge: judge({ skill: "grade", outcome: verdictOutcome("verdict") }), done: pass })
1025
+ : verify({
1026
+ judge: judge({ skill: "grade", outcome: verdictOutcome("verdict") }),
1027
+ done: pass,
1028
+ feedForward: vFeedForward,
1029
+ max,
1030
+ }),
1031
+ }),
1032
+ consume: acts(),
1033
+ },
1034
+ edges: { build: "consume", consume: "stop" },
1035
+ }) as Workflow;
1036
+
1037
+ const writeVerdict = (n: number, isDone: boolean, feedback = `fb${n}`): string => {
1038
+ const rel = `.rpiv/verdicts/v${n}.json`;
1039
+ writeFile(rel, JSON.stringify({ done: isDone, feedback }));
1040
+ return rel;
1041
+ };
1042
+
1043
+ const implOutput = (attempt: number, num: number): Output => ({
1044
+ kind: "artifacts",
1045
+ artifacts: [{ handle: fsHandle(`.rpiv/artifacts/impl/i${attempt}.md`), role: "primary" }],
1046
+ data: {},
1047
+ meta: { stage: "build", stageNumber: num, ts: "", runId: "" },
1048
+ });
1049
+
1050
+ const verdictOutput = (attempt: number, num: number, isDone: boolean): Output => ({
1051
+ kind: "artifacts",
1052
+ artifacts: [{ handle: fsHandle(`.rpiv/verdicts/v${attempt}.json`), role: "primary" }],
1053
+ data: { done: isDone, feedback: `fb${attempt}` },
1054
+ meta: { stage: "build", stageNumber: num, ts: "", runId: "" },
1055
+ });
1056
+
1057
+ const attemptRow = (attempt: number, num: number, status: WorkflowStage["status"] = "completed"): WorkflowStage => ({
1058
+ session: null,
1059
+ stageNumber: num,
1060
+ stage: `build (a${attempt}·attempt)`,
1061
+ skill: "build",
1062
+ status,
1063
+ ts: `t${num}`,
1064
+ parent: "build",
1065
+ role: "produce",
1066
+ unitIndex: attempt,
1067
+ ...(status === "completed" ? { output: implOutput(attempt, num) } : { errMsg: "boom" }),
1068
+ });
1069
+
1070
+ const verdictRow = (attempt: number, num: number, isDone: boolean): WorkflowStage => ({
1071
+ session: null,
1072
+ stageNumber: num,
1073
+ stage: `build (a${attempt}·verify)`,
1074
+ skill: "grade",
1075
+ status: "completed",
1076
+ ts: `t${num}`,
1077
+ parent: "build",
1078
+ role: "verify",
1079
+ unitIndex: attempt,
1080
+ output: verdictOutput(attempt, num, isDone),
1081
+ });
1082
+
1083
+ function writeRun(stages: WorkflowStage[]): void {
1084
+ writeHeader(tmpDir, header);
1085
+ for (const s of stages) appendStage(tmpDir, header.runId, s);
1086
+ }
1087
+
1088
+ it("pending verify: a completed-attempt trailer grades it, then advances on pass (no attempt re-run)", async () => {
1089
+ writeRun([attemptRow(0, 1)]); // died after the attempt, before the verify
1090
+ writeVerdict(0, true);
1091
+ const chain = createMockSessionChain({
1092
+ cwd: tmpDir,
1093
+ steps: [
1094
+ { branch: [mockAssistantMessage("verdict .rpiv/verdicts/v0.json")] }, // verify attempt 0
1095
+ { branch: [mockAssistantMessage("consumed")] }, // consume
1096
+ ],
1097
+ });
1098
+
1099
+ const result = await resumeWorkflow(chain.ctx, { workflow: gatedWf(), header, ref: "@x" });
1100
+
1101
+ expect(result.success).toBe(true);
1102
+ expect(chain.sentMessages).toEqual([
1103
+ "/skill:grade .rpiv/artifacts/impl/i0.md",
1104
+ "/skill:consume .rpiv/artifacts/impl/i0.md",
1105
+ ]);
1106
+ const rows = readAllStages(tmpDir, header.runId);
1107
+ expect(rows[rows.length - 1]).toMatchObject({ stage: "consume", status: "completed" });
1108
+ });
1109
+
1110
+ it("recovered fail verdict: the next attempt runs with feedForward (no re-grade of attempt 0)", async () => {
1111
+ writeRun([attemptRow(0, 1), verdictRow(0, 2, false)]);
1112
+ writeVerdict(1, true);
1113
+ const chain = createMockSessionChain({
1114
+ cwd: tmpDir,
1115
+ steps: [
1116
+ { branch: [mockAssistantMessage("wrote .rpiv/artifacts/impl/i1.md")] }, // attempt 1
1117
+ { branch: [mockAssistantMessage("verdict .rpiv/verdicts/v1.json")] }, // verify attempt 1
1118
+ { branch: [mockAssistantMessage("consumed")] },
1119
+ ],
1120
+ });
1121
+
1122
+ const result = await resumeWorkflow(chain.ctx, { workflow: gatedWf(), header, ref: "@x" });
1123
+
1124
+ expect(result.success).toBe(true);
1125
+ expect(chain.sentMessages).toEqual([
1126
+ "/skill:build fix round=0 fb=fb0",
1127
+ "/skill:grade .rpiv/artifacts/impl/i1.md",
1128
+ "/skill:consume .rpiv/artifacts/impl/i1.md",
1129
+ ]);
1130
+ });
1131
+
1132
+ it("pass fast-advance: a passing verdict trailer goes straight downstream, zero re-runs", async () => {
1133
+ writeRun([attemptRow(0, 1), verdictRow(0, 2, true)]);
1134
+ const chain = createMockSessionChain({
1135
+ cwd: tmpDir,
1136
+ steps: [{ branch: [mockAssistantMessage("consumed")] }],
1137
+ });
1138
+
1139
+ const result = await resumeWorkflow(chain.ctx, { workflow: gatedWf(), header, ref: "@x" });
1140
+
1141
+ expect(result.success).toBe(true);
1142
+ expect(chain.sentMessages).toEqual(["/skill:consume .rpiv/artifacts/impl/i0.md"]);
1143
+ });
1144
+
1145
+ it("pass-predicate drift: a recorded fail followed by a retry row, with `pass` now true → terminal failure", async () => {
1146
+ const driftedWf = {
1147
+ ...gatedWf(),
1148
+ stages: {
1149
+ build: produces({
1150
+ outcome: transcriptOutcome("impl"),
1151
+ verify: verify({
1152
+ judge: judge({ skill: "grade", outcome: verdictOutcome("verdict") }),
1153
+ done: () => true, // drifted — the run recorded a retry after this verdict
1154
+ feedForward: vFeedForward,
1155
+ max: 3,
1156
+ }),
1157
+ }),
1158
+ consume: acts(),
1159
+ },
1160
+ } as Workflow;
1161
+ writeRun([attemptRow(0, 1), verdictRow(0, 2, false), attemptRow(1, 3, "failed")]);
1162
+ const chain = createMockSessionChain({ cwd: tmpDir, steps: [] });
1163
+
1164
+ const result = await resumeWorkflow(chain.ctx, { workflow: driftedWf, header, ref: "@x" });
1165
+
1166
+ expect(result.success).toBe(false);
1167
+ expect(result.error).toMatch(/deterministic/);
1168
+ const rows = readAllStages(tmpDir, header.runId);
1169
+ expect(rows[rows.length - 1]).toMatchObject({ stage: "build", status: "failed" });
1170
+ expect(chain.sentMessages).toEqual([]);
1171
+ });
1172
+
1173
+ it("gate-only recovered fail: max 1 + a failing verdict trailer → verification-failed halt, zero dispatch", async () => {
1174
+ writeRun([attemptRow(0, 1), verdictRow(0, 2, false)]);
1175
+ const chain = createMockSessionChain({ cwd: tmpDir, steps: [] });
1176
+
1177
+ const result = await resumeWorkflow(chain.ctx, { workflow: gatedWf(1), header, ref: "@x" });
1178
+
1179
+ expect(result.success).toBe(false);
1180
+ expect(result.error).toMatch(/Verification failed for "build"/);
1181
+ const rows = readAllStages(tmpDir, header.runId);
1182
+ expect(rows[rows.length - 1]).toMatchObject({ stage: "build", status: "failed" });
1183
+ expect(chain.sentMessages).toEqual([]);
1184
+ });
1185
+
1186
+ it("verify × reads: a failed attempt-0 trailer re-runs with the FROZEN labelled-flag arg", async () => {
1187
+ const readsWf: Workflow = {
1188
+ name: "gated",
1189
+ start: "design",
1190
+ stages: {
1191
+ design: produces({ outcome: transcriptOutcome("design") }),
1192
+ build: produces({
1193
+ outcome: transcriptOutcome("impl"),
1194
+ reads: ["design"],
1195
+ verify: verify({ judge: judge({ skill: "grade", outcome: verdictOutcome("verdict") }), done: pass }),
1196
+ }),
1197
+ consume: acts(),
1198
+ },
1199
+ edges: { design: "build", build: "consume", consume: "stop" },
1200
+ } as Workflow;
1201
+ writeRun([
1202
+ {
1203
+ session: null,
1204
+ stageNumber: 1,
1205
+ stage: "design",
1206
+ skill: "design",
1207
+ status: "completed",
1208
+ ts: "t1",
1209
+ output: {
1210
+ kind: "artifacts",
1211
+ artifacts: [{ handle: fsHandle(".rpiv/artifacts/design/d0.md"), role: "primary" }],
1212
+ data: {},
1213
+ meta: { stage: "design", stageNumber: 1, ts: "", runId: "" },
1214
+ },
1215
+ },
1216
+ attemptRow(0, 2, "failed"), // attempt 0 died — resume re-runs it with the frozen entry arg
1217
+ ]);
1218
+ writeVerdict(0, true);
1219
+ const chain = createMockSessionChain({
1220
+ cwd: tmpDir,
1221
+ steps: [
1222
+ { branch: [mockAssistantMessage("wrote .rpiv/artifacts/impl/i0.md")] },
1223
+ { branch: [mockAssistantMessage("verdict .rpiv/verdicts/v0.json")] },
1224
+ { branch: [mockAssistantMessage("consumed")] },
1225
+ ],
1226
+ });
1227
+
1228
+ const result = await resumeWorkflow(chain.ctx, { workflow: readsWf, header, ref: "@x" });
1229
+
1230
+ expect(result.success).toBe(true);
1231
+ expect(chain.sentMessages).toEqual([
1232
+ "/skill:build --design .rpiv/artifacts/design/d0.md",
1233
+ "/skill:grade .rpiv/artifacts/impl/i0.md",
1234
+ "/skill:consume .rpiv/artifacts/impl/i0.md",
1235
+ ]);
1236
+ });
1237
+ });
1238
+
1239
+ // ===========================================================================
1240
+ // Prompt dispatch — assess/verify × prompt resume paths
1241
+ // ===========================================================================
1242
+
1243
+ describe("loop-resume — prompt dispatch", () => {
1244
+ const header: WorkflowHeader = {
1245
+ runId: "2026-06-10_23-30-00-cc33",
1246
+ workflow: "gated-prompt",
1247
+ input: "build it",
1248
+ ts: "2026-06-10T23:30:00Z",
1249
+ };
1250
+
1251
+ const pass = (v: Output) => Boolean((v.data as { done?: boolean }).done);
1252
+
1253
+ const promptWf = (max = 3): Workflow =>
1254
+ ({
1255
+ name: "gated-prompt",
1256
+ start: "kickoff",
1257
+ stages: {
1258
+ kickoff: acts(),
1259
+ build: produces({
1260
+ outcome: transcriptOutcome("impl"),
1261
+ prompt: "draft the impl",
1262
+ verify:
1263
+ max === 1
1264
+ ? verify({ judge: judge({ skill: "grade", outcome: verdictOutcome("verdict") }), done: pass })
1265
+ : verify({
1266
+ judge: judge({ skill: "grade", outcome: verdictOutcome("verdict") }),
1267
+ done: pass,
1268
+ feedForward: ({ verdict, round }) =>
1269
+ `rewrite attempt=${round + 1} fb=${(verdict.data as { feedback?: string }).feedback}`,
1270
+ max,
1271
+ }),
1272
+ }),
1273
+ consume: acts(),
1274
+ },
1275
+ edges: { kickoff: "build", build: "consume", consume: "stop" },
1276
+ }) as Workflow;
1277
+
1278
+ const writeVerdict = (n: number, isDone: boolean, feedback = `fb${n}`): void => {
1279
+ writeFile(`.rpiv/verdicts/v${n}.json`, JSON.stringify({ done: isDone, feedback }));
1280
+ };
1281
+
1282
+ const kickoffRow = (): WorkflowStage => ({
1283
+ session: null,
1284
+ stageNumber: 1,
1285
+ stage: "kickoff",
1286
+ skill: "kickoff",
1287
+ status: "completed",
1288
+ ts: "t1",
1289
+ output: {
1290
+ kind: "side-effect",
1291
+ artifacts: [],
1292
+ data: {},
1293
+ meta: { stage: "kickoff", stageNumber: 1, ts: "", runId: "" },
1294
+ },
1295
+ });
1296
+
1297
+ const attemptRow = (attempt: number, num: number, status: WorkflowStage["status"] = "completed"): WorkflowStage => ({
1298
+ session: null,
1299
+ stageNumber: num,
1300
+ stage: `build (a${attempt}·attempt)`,
1301
+ skill: "build",
1302
+ status,
1303
+ ts: `t${num}`,
1304
+ parent: "build",
1305
+ role: "produce",
1306
+ unitIndex: attempt,
1307
+ ...(status === "completed"
1308
+ ? {
1309
+ output: {
1310
+ kind: "artifacts",
1311
+ artifacts: [{ handle: fsHandle(`.rpiv/artifacts/impl/i${attempt}.md`), role: "primary" }],
1312
+ data: {},
1313
+ meta: { stage: "build", stageNumber: num, ts: "", runId: "" },
1314
+ } as Output,
1315
+ }
1316
+ : { errMsg: "boom" }),
1317
+ });
1318
+
1319
+ const verdictRow = (attempt: number, num: number, isDone: boolean): WorkflowStage => ({
1320
+ session: null,
1321
+ stageNumber: num,
1322
+ stage: `build (a${attempt}·verify)`,
1323
+ skill: "grade",
1324
+ status: "completed",
1325
+ ts: `t${num}`,
1326
+ parent: "build",
1327
+ role: "verify",
1328
+ unitIndex: attempt,
1329
+ output: {
1330
+ kind: "artifacts",
1331
+ artifacts: [{ handle: fsHandle(`.rpiv/verdicts/v${attempt}.json`), role: "primary" }],
1332
+ data: { done: isDone, feedback: `fb${attempt}` },
1333
+ meta: { stage: "build", stageNumber: num, ts: "", runId: "" },
1334
+ } as Output,
1335
+ });
1336
+
1337
+ function writeRun(stages: WorkflowStage[]): void {
1338
+ writeHeader(tmpDir, header);
1339
+ for (const s of stages) appendStage(tmpDir, header.runId, s);
1340
+ }
1341
+
1342
+ it("pending verify on a prompt stage: grades the recovered attempt, advances on pass", async () => {
1343
+ writeRun([kickoffRow(), attemptRow(0, 2)]); // died after attempt 0, before its verdict
1344
+ writeVerdict(0, true);
1345
+ const chain = createMockSessionChain({
1346
+ cwd: tmpDir,
1347
+ steps: [
1348
+ { branch: [mockAssistantMessage("verdict .rpiv/verdicts/v0.json")] },
1349
+ { branch: [mockAssistantMessage("consumed")] },
1350
+ ],
1351
+ });
1352
+
1353
+ const result = await resumeWorkflow(chain.ctx, { workflow: promptWf(), header, ref: "@x" });
1354
+
1355
+ expect(result.success).toBe(true);
1356
+ expect(chain.sentMessages).toEqual([
1357
+ "/skill:grade .rpiv/artifacts/impl/i0.md",
1358
+ "/skill:consume .rpiv/artifacts/impl/i0.md",
1359
+ ]);
1360
+ });
1361
+
1362
+ it("recovered fail verdict on a prompt stage: attempt 1's message is feedForward's output RAW", async () => {
1363
+ writeRun([kickoffRow(), attemptRow(0, 2), verdictRow(0, 3, false)]);
1364
+ writeVerdict(1, true);
1365
+ const chain = createMockSessionChain({
1366
+ cwd: tmpDir,
1367
+ steps: [
1368
+ { branch: [mockAssistantMessage("wrote .rpiv/artifacts/impl/i1.md")] },
1369
+ { branch: [mockAssistantMessage("verdict .rpiv/verdicts/v1.json")] },
1370
+ { branch: [mockAssistantMessage("consumed")] },
1371
+ ],
1372
+ });
1373
+
1374
+ const result = await resumeWorkflow(chain.ctx, { workflow: promptWf(), header, ref: "@x" });
1375
+
1376
+ expect(result.success).toBe(true);
1377
+ expect(chain.sentMessages).toEqual([
1378
+ "rewrite attempt=1 fb=fb0",
1379
+ "/skill:grade .rpiv/artifacts/impl/i1.md",
1380
+ "/skill:consume .rpiv/artifacts/impl/i1.md",
1381
+ ]);
1382
+ });
1383
+
1384
+ it("attempt-0 re-run with NO upstream primary: re-resolves the stage prompt — no false refusal", async () => {
1385
+ // `kickoff` is an acts stage with no outcome — the rolling primary is
1386
+ // UNSET when `build` (non-start, prompt-dispatch) re-enters at attempt 0.
1387
+ // The entryArgs authority freezes "" for prompt stages, so the fold must
1388
+ // NOT refuse with the missing-artifact message; the driver re-resolves
1389
+ // the stage's own prompt instead.
1390
+ writeRun([kickoffRow(), attemptRow(0, 2, "failed")]);
1391
+ writeVerdict(0, true);
1392
+ const chain = createMockSessionChain({
1393
+ cwd: tmpDir,
1394
+ steps: [
1395
+ { branch: [mockAssistantMessage("wrote .rpiv/artifacts/impl/i0.md")] },
1396
+ { branch: [mockAssistantMessage("verdict .rpiv/verdicts/v0.json")] },
1397
+ { branch: [mockAssistantMessage("consumed")] },
1398
+ ],
1399
+ });
1400
+
1401
+ const result = await resumeWorkflow(chain.ctx, { workflow: promptWf(), header, ref: "@x" });
1402
+
1403
+ expect(result.success).toBe(true);
1404
+ expect(chain.sentMessages).toEqual([
1405
+ "draft the impl",
1406
+ "/skill:grade .rpiv/artifacts/impl/i0.md",
1407
+ "/skill:consume .rpiv/artifacts/impl/i0.md",
1408
+ ]);
1409
+ });
1410
+ });