@juicesharp/rpiv-workflow 1.20.0 → 2.0.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 (106) hide show
  1. package/api.ts +1 -1
  2. package/audit-ctx.ts +103 -0
  3. package/audit-rows.ts +18 -0
  4. package/audit.ts +119 -164
  5. package/built-ins.ts +26 -6
  6. package/chain-state.ts +119 -68
  7. package/command-run.ts +35 -30
  8. package/command.ts +10 -4
  9. package/docs/workflow-authoring.md +34 -2
  10. package/events.ts +44 -4
  11. package/execution-host.ts +75 -0
  12. package/host.ts +137 -82
  13. package/internal-utils.ts +89 -3
  14. package/internal.ts +1 -0
  15. package/judge.ts +23 -11
  16. package/load/alias.ts +3 -3
  17. package/load/index.ts +15 -1
  18. package/load/issues.ts +2 -2
  19. package/load/legacy.ts +2 -2
  20. package/load/resolve-default.ts +3 -4
  21. package/load/skill-contract-phase.ts +1 -1
  22. package/loop-constructors.ts +19 -618
  23. package/loop-def.ts +60 -15
  24. package/loop-kinds.ts +319 -62
  25. package/loop-parallel.ts +250 -0
  26. package/loop-waves.ts +99 -0
  27. package/loop.ts +106 -80
  28. package/loops/constructors.ts +334 -0
  29. package/loops/derivations.ts +65 -0
  30. package/loops/introspection.ts +184 -0
  31. package/loops/panel.ts +196 -0
  32. package/loops/verify.ts +99 -0
  33. package/messages.ts +58 -33
  34. package/outcomes/collectors/index.ts +1 -0
  35. package/outcomes/collectors/text-scan.ts +47 -0
  36. package/outcomes/collectors/transcript-path.ts +2 -15
  37. package/outcomes/collectors/union.ts +2 -1
  38. package/outcomes/collectors/url.ts +2 -14
  39. package/outcomes/collectors/workspace-diff.ts +1 -1
  40. package/outcomes/git-commit.ts +57 -6
  41. package/output-spec.ts +1 -1
  42. package/output.ts +59 -1
  43. package/package.json +16 -6
  44. package/preview.ts +18 -18
  45. package/registration.ts +11 -4
  46. package/routing-dsl.ts +53 -41
  47. package/routing.ts +46 -0
  48. package/runner/chain-advance.ts +30 -17
  49. package/runner/errors.ts +7 -30
  50. package/runner/failure.ts +67 -13
  51. package/runner/input-validation.ts +8 -5
  52. package/runner/preflight.ts +17 -21
  53. package/runner/resume-entry.ts +23 -3
  54. package/runner/resume-loop.ts +50 -29
  55. package/runner/resume.ts +96 -10
  56. package/runner/run-context.ts +20 -16
  57. package/runner/run-stage.ts +125 -91
  58. package/runner/runner.ts +163 -69
  59. package/runner/script-stage.ts +23 -29
  60. package/schema-compat.ts +1 -2
  61. package/semaphore.ts +55 -0
  62. package/sessions/extraction.ts +103 -60
  63. package/sessions/halt-routing.ts +195 -0
  64. package/sessions/index.ts +2 -2
  65. package/sessions/locate.ts +60 -9
  66. package/sessions/reattach.ts +28 -20
  67. package/sessions/sessions.ts +103 -191
  68. package/sessions/spawn.ts +132 -119
  69. package/sessions/success-persist.ts +89 -0
  70. package/skill-contracts/composition.ts +8 -10
  71. package/skill-contracts/harvest.ts +3 -2
  72. package/skill-contracts/registry.ts +1 -1
  73. package/stage-def.ts +115 -47
  74. package/stage-errors.ts +84 -0
  75. package/stage-identity.ts +56 -0
  76. package/startup.ts +1 -0
  77. package/state/paths.ts +11 -3
  78. package/state/raw.ts +2 -3
  79. package/state/resolve.ts +3 -3
  80. package/state/state.ts +26 -3
  81. package/state/writes.ts +1 -1
  82. package/types.ts +97 -43
  83. package/validate/contract-compat.ts +16 -11
  84. package/validate/graph.ts +10 -1
  85. package/validate/issue.ts +20 -6
  86. package/validate/stage-rules.ts +139 -60
  87. package/validate-output.ts +27 -20
  88. package/validate-workflow.ts +5 -3
  89. package/validation-bounds.ts +35 -0
  90. package/load/cache.test.ts +0 -82
  91. package/load/shape-guards.test.ts +0 -77
  92. package/outcomes/collectors/directory-path.test.ts +0 -64
  93. package/outcomes/collectors/tool-call.test.ts +0 -112
  94. package/outcomes/collectors/transcript-path.test.ts +0 -70
  95. package/outcomes/collectors/union.test.ts +0 -113
  96. package/outcomes/collectors/url.test.ts +0 -67
  97. package/outcomes/collectors/workspace-diff.test.ts +0 -120
  98. package/outcomes/git-commit.test.ts +0 -240
  99. package/outcomes/parsers/json-body.test.ts +0 -80
  100. package/runner/by-name.test.ts +0 -95
  101. package/runner/by-run-id.test.ts +0 -115
  102. package/runner/header-write-failure.test.ts +0 -64
  103. package/runner/resume-loop.test.ts +0 -1410
  104. package/runner/resume-session.test.ts +0 -400
  105. package/runner/resume.test.ts +0 -1805
  106. package/sessions/locate.test.ts +0 -77
@@ -1,1805 +0,0 @@
1
- /**
2
- * Reconstruction tests for `reconstructState` — the ONE async fold that
3
- * rebuilds `RunState` from a run's JSONL audit trail.
4
- *
5
- * Covers:
6
- * 1. Produces-only linear chain (primary + named + output + counters)
7
- * 2. Side-effect stage between produces (primary preserved)
8
- * 3. Terminal stage (primary cleared)
9
- * 4. Failed trailing row (output NOT seeded; stagesCompleted excludes it;
10
- * visited + lastStageNumber include it)
11
- * 5. Empty file → no-rows refusal
12
- * 6. Stage gone from workflow → stage-gone refusal
13
- * 7. Loop-unit rows keyed on the STRUCTURED `parent` field — fanout entry
14
- * projection at generation close, iterate "last" projection + trailing
15
- * cursor, assess channel separation + transient judge roll, full-row
16
- * drift guard, and the legacy-row (`parent`-less) stage-gone refusal
17
- * 8. Named-slot append-order (array history preserved across repeated calls)
18
- *
19
- * End-to-end loop-resume DISPATCH (re-run failed+remaining units, finished
20
- * no-op silence, the assess pending paths, back-edge generation reset) lives
21
- * in `resume-loop.test.ts`.
22
- */
23
-
24
- import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
25
- import { tmpdir } from "node:os";
26
- import { join } from "node:path";
27
- import { createMockSessionChain, mockAssistantMessage } from "@juicesharp/rpiv-test-utils";
28
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
29
- import { type FanoutFn, type IterateFn, produces, type Workflow } from "../api.js";
30
- import type { Artifact } from "../handle.js";
31
- import { fs as fsHandle, handleToString } from "../handle.js";
32
- import { judge } from "../judge.js";
33
- import { assess, fanout, iterate, majority, panel, verify } from "../loop-constructors.js";
34
- import { advanceCursor, freshCursor } from "../loop-kinds.js";
35
- import type { Output } from "../output.js";
36
- import {
37
- appendStage,
38
- readAllStages,
39
- stateFilePath,
40
- type WorkflowHeader,
41
- type WorkflowStage,
42
- writeHeader,
43
- } from "../state/index.js";
44
- import { reconstructState } from "./resume.js";
45
- import { resumeWorkflow } from "./runner.js";
46
-
47
- // ---------------------------------------------------------------------------
48
- // Fixtures
49
- // ---------------------------------------------------------------------------
50
-
51
- const fakeArtifact = (path: string): Artifact => ({ handle: fsHandle(path), role: "primary" });
52
-
53
- const fakeOutput = (artifacts: readonly Artifact[] = []): Output => ({
54
- kind: "artifacts",
55
- artifacts,
56
- data: {},
57
- meta: { stage: "test", stageNumber: 1, ts: "", runId: "" },
58
- });
59
-
60
- /**
61
- * Minimal named outcome for fold tests. The collector is never invoked — the
62
- * reconstruct fold replays persisted rows, not live sessions — so a stub that
63
- * satisfies `Outcome` is sufficient. `name` drives `resolvePublishName`.
64
- */
65
- const makeOutcome = (
66
- name: string,
67
- ): import("../output-spec.js").Outcome<unknown, "artifact-md", Record<string, unknown>> & { name: string } => ({
68
- name,
69
- collector: { collect: () => ({ kind: "ok", artifacts: [] }) },
70
- });
71
-
72
- /** Minimal 3-stage produces workflow used by most tests. */
73
- const linearWorkflow: Workflow = {
74
- name: "test-wf",
75
- start: "plan",
76
- stages: {
77
- plan: { kind: "produces", sessionPolicy: "fresh" },
78
- build: { kind: "produces", sessionPolicy: "fresh" },
79
- deploy: { kind: "produces", sessionPolicy: "fresh" },
80
- },
81
- edges: {
82
- plan: "build",
83
- build: "deploy",
84
- deploy: "stop",
85
- },
86
- };
87
-
88
- /** Workflow with a side-effect stage between two produces. */
89
- const sideEffectWorkflow: Workflow = {
90
- name: "test-wf",
91
- start: "plan",
92
- stages: {
93
- plan: { kind: "produces", sessionPolicy: "fresh" },
94
- commit: { kind: "side-effect", sessionPolicy: "fresh" },
95
- build: { kind: "produces", sessionPolicy: "fresh" },
96
- },
97
- edges: {
98
- plan: "commit",
99
- commit: "build",
100
- build: "stop",
101
- },
102
- };
103
-
104
- /** Workflow with a terminal stage. */
105
- const terminalWorkflow: Workflow = {
106
- name: "test-wf",
107
- start: "plan",
108
- stages: {
109
- plan: { kind: "produces", sessionPolicy: "fresh" },
110
- cleanup: { kind: "side-effect", sessionPolicy: "fresh", inheritsArtifacts: false },
111
- },
112
- edges: {
113
- plan: "cleanup",
114
- cleanup: "stop",
115
- },
116
- };
117
-
118
- const baseHeader: WorkflowHeader = {
119
- runId: "2026-06-03_07-30-00-ab12",
120
- workflow: "test-wf",
121
- input: "Add dark mode",
122
- ts: "2026-06-03T07:30:00Z",
123
- };
124
-
125
- // ---------------------------------------------------------------------------
126
- // Test harness
127
- // ---------------------------------------------------------------------------
128
-
129
- let tmpDir: string;
130
-
131
- beforeEach(() => {
132
- tmpDir = mkdtempSync(join(tmpdir(), "rpiv-workflow-resume-"));
133
- });
134
-
135
- afterEach(() => {
136
- rmSync(tmpDir, { recursive: true, force: true });
137
- });
138
-
139
- function writeRunStages(stages: WorkflowStage[]): WorkflowHeader {
140
- writeHeader(tmpDir, baseHeader);
141
- for (const stage of stages) {
142
- appendStage(tmpDir, baseHeader.runId, stage);
143
- }
144
- return baseHeader;
145
- }
146
-
147
- /** A structured loop-unit row (the machine channel — `stage` is display only). */
148
- const fanoutUnitRow = (
149
- parent: string,
150
- unitId: string,
151
- unitIndex: number,
152
- num: number,
153
- output: Output | undefined,
154
- status: WorkflowStage["status"] = "completed",
155
- ): WorkflowStage => ({
156
- session: null,
157
- stageNumber: num,
158
- stage: `${parent} (${unitId})`,
159
- skill: parent,
160
- status,
161
- ts: `t${num}`,
162
- parent,
163
- role: "produce",
164
- unitId,
165
- unitIndex,
166
- ...(output ? { output } : {}),
167
- ...(status === "failed" ? { errMsg: "boom" } : {}),
168
- });
169
-
170
- const assessProduceRow = (parent: string, round: number, num: number, output: Output): WorkflowStage => ({
171
- session: null,
172
- stageNumber: num,
173
- stage: `${parent} (r${round}·produce)`,
174
- skill: parent,
175
- status: "completed",
176
- ts: `t${num}`,
177
- parent,
178
- role: "produce",
179
- unitIndex: round,
180
- output,
181
- });
182
-
183
- const assessJudgeRow = (
184
- parent: string,
185
- judgeSkill: string,
186
- round: number,
187
- num: number,
188
- output: Output,
189
- ): WorkflowStage => ({
190
- session: null,
191
- stageNumber: num,
192
- stage: `${parent} (r${round}·judge)`,
193
- skill: judgeSkill,
194
- status: "completed",
195
- ts: `t${num}`,
196
- parent,
197
- role: "judge",
198
- unitIndex: round,
199
- output,
200
- });
201
-
202
- /** A panel member's judge row — identity-bearing (`#{memberIndex}` in `unitId`). */
203
- const assessPanelJudgeRow = (
204
- parent: string,
205
- judgeSkill: string,
206
- round: number,
207
- memberIndex: number,
208
- num: number,
209
- output: Output,
210
- ): WorkflowStage => ({
211
- session: null,
212
- stageNumber: num,
213
- stage: `${parent} (r${round}·judge#${memberIndex})`,
214
- skill: judgeSkill,
215
- status: "completed",
216
- ts: `t${num}`,
217
- parent,
218
- role: "judge",
219
- unitId: `r${round}·judge#${memberIndex}`,
220
- unitIndex: round,
221
- output,
222
- });
223
-
224
- /** A member verdict Output carrying `{ done }` data the per-member `pred` reads. */
225
- const memberVerdict = (path: string, isDone: boolean): Output => ({
226
- kind: "artifacts",
227
- artifacts: [fakeArtifact(path)],
228
- data: { done: isDone },
229
- meta: { stage: "test", stageNumber: 1, ts: "", runId: "" },
230
- });
231
-
232
- // ---------------------------------------------------------------------------
233
- // Cases
234
- // ---------------------------------------------------------------------------
235
-
236
- describe("reconstructState", () => {
237
- it("produces-only linear chain: advances primary, appends named, tracks counters", async () => {
238
- const art1 = fakeArtifact("plans/p1.md");
239
- const art2 = fakeArtifact("plans/p2.md");
240
- const out1 = fakeOutput([art1]);
241
- const out2 = fakeOutput([art2]);
242
-
243
- writeRunStages([
244
- {
245
- session: null,
246
- stageNumber: 1,
247
- stage: "plan",
248
- skill: "plan",
249
- status: "completed",
250
- ts: "2026-06-03T07:31:00Z",
251
- output: out1,
252
- },
253
- {
254
- session: null,
255
- stageNumber: 2,
256
- stage: "build",
257
- skill: "build",
258
- status: "completed",
259
- ts: "2026-06-03T07:35:00Z",
260
- output: out2,
261
- },
262
- ]);
263
-
264
- const result = await reconstructState(tmpDir, linearWorkflow, baseHeader);
265
-
266
- expect(result.ok).toBe(true);
267
- if (!result.ok) return; // type narrow
268
-
269
- expect(result.state.primaryArtifact).toStrictEqual(art2);
270
- expect(result.state.output).toStrictEqual(out2);
271
- expect(result.state.stagesCompleted).toBe(2);
272
- expect(result.state.lastAllocatedStageNumber).toBe(2);
273
- expect(result.state.named.plan).toEqual([out1]);
274
- expect(result.state.named.build).toEqual([out2]);
275
- expect(result.state.originalInput).toBe("Add dark mode");
276
- expect(result.visited).toEqual(new Set(["plan", "build"]));
277
- expect(result.lastStageNumber).toBe(2);
278
- expect(result.rows).toHaveLength(2);
279
- });
280
-
281
- it("side-effect stage between produces: primary preserved, named untouched by side-effect", async () => {
282
- const art1 = fakeArtifact("plans/p1.md");
283
- const out1 = fakeOutput([art1]);
284
- const sideOut = fakeOutput([]); // side-effect output, no artifacts
285
-
286
- writeRunStages([
287
- {
288
- session: null,
289
- stageNumber: 1,
290
- stage: "plan",
291
- skill: "plan",
292
- status: "completed",
293
- ts: "2026-06-03T07:31:00Z",
294
- output: out1,
295
- },
296
- {
297
- session: null,
298
- stageNumber: 2,
299
- stage: "commit",
300
- skill: "commit",
301
- status: "completed",
302
- ts: "2026-06-03T07:32:00Z",
303
- output: sideOut,
304
- },
305
- ]);
306
-
307
- const result = await reconstructState(tmpDir, sideEffectWorkflow, baseHeader);
308
-
309
- expect(result.ok).toBe(true);
310
- if (!result.ok) return;
311
-
312
- // Primary stays on the produces artifact
313
- expect(result.state.primaryArtifact).toStrictEqual(art1);
314
- expect(result.state.output).toStrictEqual(sideOut);
315
- expect(result.state.stagesCompleted).toBe(2);
316
- // Side-effect stage did NOT write to named
317
- expect(result.state.named.plan).toEqual([out1]);
318
- expect(result.state.named.commit).toBeUndefined();
319
- expect(result.visited).toEqual(new Set(["plan", "commit"]));
320
- });
321
-
322
- it("terminal stage (inheritsArtifacts: false): clears primary", async () => {
323
- const art1 = fakeArtifact("plans/p1.md");
324
- const out1 = fakeOutput([art1]);
325
- const termOut = fakeOutput([]);
326
-
327
- writeRunStages([
328
- {
329
- session: null,
330
- stageNumber: 1,
331
- stage: "plan",
332
- skill: "plan",
333
- status: "completed",
334
- ts: "2026-06-03T07:31:00Z",
335
- output: out1,
336
- },
337
- {
338
- session: null,
339
- stageNumber: 2,
340
- stage: "cleanup",
341
- status: "completed",
342
- ts: "2026-06-03T07:32:00Z",
343
- output: termOut,
344
- },
345
- ]);
346
-
347
- const result = await reconstructState(tmpDir, terminalWorkflow, baseHeader);
348
-
349
- expect(result.ok).toBe(true);
350
- if (!result.ok) return;
351
-
352
- expect(result.state.primaryArtifact).toBeUndefined();
353
- expect(result.state.stagesCompleted).toBe(2);
354
- // Named is never cleared by terminal
355
- expect(result.state.named.plan).toEqual([out1]);
356
- });
357
-
358
- it("failed trailing row: output NOT seeded, stagesCompleted excludes it, visited + lastStageNumber include it", async () => {
359
- const art1 = fakeArtifact("plans/p1.md");
360
- const out1 = fakeOutput([art1]);
361
-
362
- writeRunStages([
363
- {
364
- session: null,
365
- stageNumber: 1,
366
- stage: "plan",
367
- skill: "plan",
368
- status: "completed",
369
- ts: "2026-06-03T07:31:00Z",
370
- output: out1,
371
- },
372
- {
373
- session: null,
374
- stageNumber: 2,
375
- stage: "build",
376
- skill: "build",
377
- status: "failed",
378
- ts: "2026-06-03T07:35:00Z",
379
- errMsg: "Something went wrong",
380
- },
381
- ]);
382
-
383
- const result = await reconstructState(tmpDir, linearWorkflow, baseHeader);
384
-
385
- expect(result.ok).toBe(true);
386
- if (!result.ok) return;
387
-
388
- // Only the completed stage counts
389
- expect(result.state.stagesCompleted).toBe(1);
390
- // Output is from the completed row only
391
- expect(result.state.output).toStrictEqual(out1);
392
- // Primary is from the completed row only
393
- expect(result.state.primaryArtifact).toStrictEqual(art1);
394
- // lastStageNumber INCLUDES the failed row
395
- expect(result.lastStageNumber).toBe(2);
396
- expect(result.state.lastAllocatedStageNumber).toBe(2);
397
- // visited INCLUDES the failed row
398
- expect(result.visited).toEqual(new Set(["plan", "build"]));
399
- // named only has the completed stage
400
- expect(result.state.named.plan).toEqual([out1]);
401
- expect(result.state.named.build).toBeUndefined();
402
- });
403
-
404
- it("empty file (no stage rows): returns no-rows refusal", async () => {
405
- // Write header only, no stage rows
406
- writeHeader(tmpDir, baseHeader);
407
-
408
- const result = await reconstructState(tmpDir, linearWorkflow, baseHeader);
409
-
410
- expect(result.ok).toBe(false);
411
- if (result.ok) return;
412
- expect(result.reason).toBe("no-rows");
413
- expect(result.detail).toBe(baseHeader.runId);
414
- });
415
-
416
- it("REFUSES (malformed-row) instead of skipping a stage-shaped row that fails the deep guard (T9)", async () => {
417
- // Fault injection: the trail's failure row lost its valid `status` (torn
418
- // write, foreign writer). Pre-fix the shallow guard skipped it and the
419
- // fold replayed the run as if `build` never ran — a resume would route
420
- // onward past the stage that actually failed.
421
- writeRunStages([
422
- {
423
- session: null,
424
- stageNumber: 1,
425
- stage: "plan",
426
- skill: "plan",
427
- status: "completed",
428
- ts: "t1",
429
- output: fakeOutput(),
430
- },
431
- ]);
432
- appendFileSync(
433
- stateFilePath(tmpDir, baseHeader.runId),
434
- `${JSON.stringify({ stageNumber: 2, stage: "build", skill: "build", status: "exploded", ts: "t2" })}\n`,
435
- "utf-8",
436
- );
437
-
438
- const result = await reconstructState(tmpDir, linearWorkflow, baseHeader);
439
- expect(result.ok).toBe(false);
440
- if (result.ok) return;
441
- expect(result.reason).toBe("malformed-row");
442
- expect(result.detail).toContain('stage row 2 ("build")');
443
- });
444
-
445
- it("REFUSES (malformed-row) a pre-session-provenance row — no `session` key", async () => {
446
- // A dev-local file written before session provenance landed: stage rows
447
- // carry no `session` key. v1 never shipped, so the shape was redefined
448
- // in place — the strict guard refuses; the remedy is wiping
449
- // `.rpiv/workflows/runs/`.
450
- writeRunStages([
451
- {
452
- session: null,
453
- stageNumber: 1,
454
- stage: "plan",
455
- skill: "plan",
456
- status: "completed",
457
- ts: "t1",
458
- output: fakeOutput(),
459
- },
460
- ]);
461
- appendFileSync(
462
- stateFilePath(tmpDir, baseHeader.runId),
463
- `${JSON.stringify({ stageNumber: 2, stage: "build", skill: "build", status: "failed", ts: "t2", errMsg: "x" })}\n`,
464
- "utf-8",
465
- );
466
-
467
- const result = await reconstructState(tmpDir, linearWorkflow, baseHeader);
468
- expect(result.ok).toBe(false);
469
- if (result.ok) return;
470
- expect(result.reason).toBe("malformed-row");
471
- expect(result.detail).toContain('stage row 2 ("build")');
472
- });
473
-
474
- it("REFUSES (version-mismatch) a header written under an unknown schema version (T5)", async () => {
475
- writeRunStages([
476
- {
477
- session: null,
478
- stageNumber: 1,
479
- stage: "plan",
480
- skill: "plan",
481
- status: "completed",
482
- ts: "t1",
483
- output: fakeOutput(),
484
- },
485
- ]);
486
-
487
- const result = await reconstructState(tmpDir, linearWorkflow, { ...baseHeader, v: 2 });
488
- expect(result.ok).toBe(false);
489
- if (result.ok) return;
490
- expect(result.reason).toBe("version-mismatch");
491
- expect(result.detail).toContain("schema v2");
492
- });
493
-
494
- it("treats an absent header `v` as version 1 and resumes (T5 back-compat rule)", async () => {
495
- // baseHeader deliberately carries no `v` — files written before the
496
- // field existed must keep resuming.
497
- expect(baseHeader.v).toBeUndefined();
498
- writeRunStages([
499
- {
500
- session: null,
501
- stageNumber: 1,
502
- stage: "plan",
503
- skill: "plan",
504
- status: "completed",
505
- ts: "t1",
506
- output: fakeOutput(),
507
- },
508
- ]);
509
-
510
- const result = await reconstructState(tmpDir, linearWorkflow, baseHeader);
511
- expect(result.ok).toBe(true);
512
-
513
- // An explicit v: 1 resumes identically.
514
- const explicit = await reconstructState(tmpDir, linearWorkflow, { ...baseHeader, v: 1 });
515
- expect(explicit.ok).toBe(true);
516
- });
517
-
518
- it("row whose stage is not in workflow.stages: returns stage-gone refusal", async () => {
519
- writeRunStages([
520
- {
521
- session: null,
522
- stageNumber: 1,
523
- stage: "plan",
524
- skill: "plan",
525
- status: "completed",
526
- ts: "2026-06-03T07:31:00Z",
527
- },
528
- {
529
- session: null,
530
- stageNumber: 2,
531
- stage: "renamed-away",
532
- skill: "renamed-away",
533
- status: "completed",
534
- ts: "2026-06-03T07:35:00Z",
535
- },
536
- ]);
537
-
538
- // linearWorkflow only has plan, build, deploy — no "renamed-away"
539
- const result = await reconstructState(tmpDir, linearWorkflow, baseHeader);
540
-
541
- expect(result.ok).toBe(false);
542
- if (result.ok) return;
543
- expect(result.reason).toBe("stage-gone");
544
- expect(result.detail).toBe("renamed-away");
545
- });
546
-
547
- // -------------------------------------------------------------------------
548
- // Loop-unit rows — keyed on the STRUCTURED `parent` field
549
- // -------------------------------------------------------------------------
550
-
551
- it("fanout generation: units publish to the named channel; generation close restores the entry primary", async () => {
552
- const planArt = fakeArtifact("plans/p1.md");
553
- const u1 = fakeArtifact("builds/b1.md");
554
- const u2 = fakeArtifact("builds/b2.md");
555
- const tail = fakeArtifact("deploys/d1.md");
556
- const units: FanoutFn = () => [
557
- { prompt: "u1", label: "phase 1/2", id: "phase-1" },
558
- { prompt: "u2", label: "phase 2/2", id: "phase-2" },
559
- ];
560
- const wf: Workflow = {
561
- name: "test-wf",
562
- start: "plan",
563
- stages: {
564
- plan: produces({ outcome: makeOutcome("plans") }),
565
- build: produces({ outcome: makeOutcome("builds"), loop: fanout({ units }) }),
566
- deploy: produces({ outcome: makeOutcome("deploys") }),
567
- },
568
- edges: { plan: "build", build: "deploy", deploy: "stop" },
569
- } as Workflow;
570
-
571
- writeRunStages([
572
- {
573
- session: null,
574
- stageNumber: 1,
575
- stage: "plan",
576
- skill: "plan",
577
- status: "completed",
578
- ts: "t1",
579
- output: fakeOutput([planArt]),
580
- },
581
- fanoutUnitRow("build", "phase-1", 0, 2, fakeOutput([u1])),
582
- fanoutUnitRow("build", "phase-2", 1, 3, fakeOutput([u2])),
583
- {
584
- session: null,
585
- stageNumber: 4,
586
- stage: "deploy",
587
- skill: "deploy",
588
- status: "completed",
589
- ts: "t4",
590
- output: fakeOutput([tail]),
591
- },
592
- ]);
593
-
594
- const result = await reconstructState(tmpDir, wf, baseHeader);
595
- expect(result.ok).toBe(true);
596
- if (!result.ok) return;
597
-
598
- // Generation closed before deploy → primary restored to the entry (planArt),
599
- // then deploy rolled it forward to its own artifact.
600
- expect(result.state.primaryArtifact).toStrictEqual(tail);
601
- // Both units published into the builds channel (every unit collects).
602
- expect(result.state.named.builds?.map((o) => o.artifacts[0])).toEqual([u1, u2]);
603
- // Counters: plan + 2 units + deploy.
604
- expect(result.state.stagesCompleted).toBe(4);
605
- // Parent is visited; the decorated keys are not.
606
- expect(result.visited).toEqual(new Set(["plan", "build", "deploy"]));
607
- // Generation closed → no trailing open generation.
608
- expect(result.trailing).toBeUndefined();
609
- expect(result.drift).toBeUndefined();
610
- });
611
-
612
- it("fanout drift: a recomputed unit id differs from a recorded row → ok with drift set, state still applied", async () => {
613
- const units: FanoutFn = () => [{ prompt: "x", label: "task", id: "task-1" }];
614
- const wf: Workflow = {
615
- name: "test-wf",
616
- start: "build",
617
- stages: { build: produces({ outcome: makeOutcome("builds"), loop: fanout({ units }) }) },
618
- edges: { build: "stop" },
619
- } as Workflow;
620
-
621
- writeRunStages([fanoutUnitRow("build", "phase-1", 0, 1, fakeOutput([fakeArtifact("builds/b1.md")]))]);
622
-
623
- const result = await reconstructState(tmpDir, wf, baseHeader);
624
- expect(result.ok).toBe(true);
625
- if (!result.ok) return;
626
-
627
- // Drift recorded against the parent; the fold still applied the row so state is complete.
628
- expect(result.drift?.parent).toBe("build");
629
- expect(result.drift?.errMsg).toMatch(/deterministic/);
630
- expect(result.state.stagesCompleted).toBe(1);
631
- });
632
-
633
- it("legacy decorated row without `parent` refuses stage-gone (pre-redesign run, no migration)", async () => {
634
- writeRunStages([
635
- { session: null, stageNumber: 1, stage: "build (phase 1/2)", skill: "build", status: "completed", ts: "t1" },
636
- ]);
637
-
638
- const result = await reconstructState(tmpDir, linearWorkflow, baseHeader);
639
- expect(result.ok).toBe(false);
640
- if (result.ok) return;
641
- expect(result.reason).toBe("stage-gone");
642
- expect(result.detail).toBe("build (phase 1/2)");
643
- });
644
-
645
- it("iterate generation: rolls the primary forward; trailing open generation carries the accumulated cursor", async () => {
646
- const reviewArt = fakeArtifact("reviews/r1.md");
647
- const p1 = fakeArtifact("plans/p1.md");
648
- const p2 = fakeArtifact("plans/p2.md");
649
- const next: IterateFn = ({ index }) =>
650
- index >= 2 ? null : { prompt: `p${index + 1}`, label: `phase ${index + 1}`, id: `phase-${index + 1}` };
651
- const wf: Workflow = {
652
- name: "test-wf",
653
- start: "review",
654
- stages: {
655
- review: produces({ outcome: makeOutcome("reviews") }),
656
- blueprint: produces({ outcome: makeOutcome("plans"), loop: iterate({ next }) }),
657
- },
658
- edges: { review: "blueprint", blueprint: "stop" },
659
- } as Workflow;
660
-
661
- writeRunStages([
662
- {
663
- session: null,
664
- stageNumber: 1,
665
- stage: "review",
666
- skill: "review",
667
- status: "completed",
668
- ts: "t1",
669
- output: fakeOutput([reviewArt]),
670
- },
671
- fanoutUnitRow("blueprint", "phase-1", 0, 2, fakeOutput([p1])),
672
- fanoutUnitRow("blueprint", "phase-2", 1, 3, fakeOutput([p2])),
673
- ]);
674
-
675
- const result = await reconstructState(tmpDir, wf, baseHeader);
676
- expect(result.ok).toBe(true);
677
- if (!result.ok) return;
678
-
679
- // Primary rolled forward to the last unit (iterate units roll, unlike fanout).
680
- expect(result.state.primaryArtifact).toStrictEqual(p2);
681
- expect(result.state.named.plans?.map((o) => o.artifacts[0])).toEqual([p1, p2]);
682
- expect(result.visited).toEqual(new Set(["review", "blueprint"]));
683
- // Trailing open generation carries the reconstructed driver cursor + FROZEN entry.
684
- expect(result.trailing?.parent).toBe("blueprint");
685
- expect(result.trailing?.cursor.index).toBe(2);
686
- expect(result.trailing?.cursor.accumulated.map((o) => o.artifacts[0])).toEqual([p1, p2]);
687
- expect(result.trailing?.entryArtifact).toStrictEqual(reviewArt);
688
- expect(result.drift).toBeUndefined();
689
- });
690
-
691
- it("assess generation: producer + judge rows publish to separate channels; close restores the last producer pair", async () => {
692
- const p0 = fakeArtifact("tasks/t0.md");
693
- const v0 = fakeArtifact("verdicts/v0.json");
694
- const p1 = fakeArtifact("tasks/t1.md");
695
- const v1 = fakeArtifact("verdicts/v1.json");
696
- const g1 = fakeArtifact("gates/g1.md");
697
- const loop = assess({
698
- judge: judge({ skill: "grade", outcome: makeOutcome("verdict") }),
699
- done: () => false,
700
- feedForward: () => "more",
701
- });
702
- const wf: Workflow = {
703
- name: "test-wf",
704
- start: "breakdown",
705
- stages: {
706
- breakdown: produces({ outcome: makeOutcome("tasks"), loop }),
707
- gate: produces({ outcome: makeOutcome("gates") }),
708
- },
709
- edges: { breakdown: "gate", gate: "stop" },
710
- } as Workflow;
711
-
712
- writeRunStages([
713
- assessProduceRow("breakdown", 0, 1, fakeOutput([p0])),
714
- assessJudgeRow("breakdown", "grade", 0, 2, fakeOutput([v0])),
715
- assessProduceRow("breakdown", 1, 3, fakeOutput([p1])),
716
- assessJudgeRow("breakdown", "grade", 1, 4, fakeOutput([v1])),
717
- {
718
- session: null,
719
- stageNumber: 5,
720
- stage: "gate",
721
- skill: "gate",
722
- status: "completed",
723
- ts: "t5",
724
- output: fakeOutput([g1]),
725
- },
726
- ]);
727
-
728
- const result = await reconstructState(tmpDir, wf, baseHeader);
729
- expect(result.ok).toBe(true);
730
- if (!result.ok) return;
731
-
732
- // Producers and verdicts live in distinct named channels.
733
- expect(result.state.named.tasks?.map((o) => o.artifacts[0])).toEqual([p0, p1]);
734
- expect(result.state.named.verdict?.map((o) => o.artifacts[0])).toEqual([v0, v1]);
735
- // Generation closed before gate → "last" projects the last producer (p1), THEN gate rolled it.
736
- expect(result.state.primaryArtifact).toStrictEqual(g1);
737
- // Every completed row of either phase bumped the counter (2 produce + 2 judge + gate).
738
- expect(result.state.stagesCompleted).toBe(5);
739
- expect(result.visited).toEqual(new Set(["breakdown", "gate"]));
740
- expect(result.trailing).toBeUndefined();
741
- expect(result.drift).toBeUndefined();
742
- });
743
-
744
- it("assess × panel: each member verdict publishes to its OWN channel; the fold publishes to `<stage>-panel`", async () => {
745
- const p0 = fakeArtifact("tasks/t0.md");
746
- const outA = memberVerdict("verdicts/v0a.json", true);
747
- const outB = memberVerdict("verdicts/v0b.json", true);
748
- const outC = memberVerdict("verdicts/v0c.json", false); // 2-of-3 pass → majority pass
749
- const loop = assess({
750
- judge: panel({
751
- members: [
752
- judge({ skill: "grade-a", outcome: makeOutcome("verdict-a") }),
753
- judge({ skill: "grade-b", outcome: makeOutcome("verdict-b") }),
754
- judge({ skill: "grade-c", outcome: makeOutcome("verdict-c") }),
755
- ],
756
- fold: majority((v) => Boolean((v.data as { done?: boolean }).done)),
757
- }),
758
- done: (v) => Boolean((v.data as { pass?: boolean }).pass),
759
- feedForward: () => "more",
760
- });
761
- const wf: Workflow = {
762
- name: "test-wf",
763
- start: "breakdown",
764
- stages: { breakdown: produces({ outcome: makeOutcome("tasks"), loop }) },
765
- edges: { breakdown: "stop" },
766
- } as Workflow;
767
-
768
- writeRunStages([
769
- assessProduceRow("breakdown", 0, 1, fakeOutput([p0])),
770
- assessPanelJudgeRow("breakdown", "grade-a", 0, 0, 2, outA),
771
- assessPanelJudgeRow("breakdown", "grade-b", 0, 1, 3, outB),
772
- assessPanelJudgeRow("breakdown", "grade-c", 0, 2, 4, outC),
773
- ]);
774
-
775
- const result = await reconstructState(tmpDir, wf, baseHeader);
776
- expect(result.ok).toBe(true);
777
- if (!result.ok) return;
778
- expect(result.drift).toBeUndefined();
779
-
780
- // Each member rolled onto its OWN channel — the fold replays each row through
781
- // THAT member's def (`panelMembers[memberIndex]`), never member 0's. Pre-fix,
782
- // members b + c silently landed on `verdict-a`.
783
- expect(result.state.named["verdict-a"]).toEqual([outA]);
784
- expect(result.state.named["verdict-b"]).toEqual([outB]);
785
- expect(result.state.named["verdict-c"]).toEqual([outC]);
786
- // The folded verdict — recomputed-and-republished at the same transition the
787
- // live driver folds — is a data-only Output (no artifact) carrying the
788
- // canonical PANEL_VERDICT shape, on the per-stage `<stage>-panel` channel.
789
- const folded = result.state.named["breakdown-panel"];
790
- expect(folded).toHaveLength(1);
791
- expect(folded?.[0]?.artifacts).toEqual([]);
792
- expect(folded?.[0]?.data).toEqual({ pass: true, votes: { pass: 2, fail: 1 }, agreement: 2 / 3, tie: false });
793
- });
794
-
795
- it("assess × panel: a THROWING fold becomes drift (recorded terminal failure), never an unguarded rejection", async () => {
796
- // The fold runs the author `panel.fold` via `advanceCursor` on the LAST
797
- // member. It lives in `reconstructState`, which `resumeWorkflow` awaits
798
- // BEFORE `executeRun` brackets the lifecycle — so before the guard a throw
799
- // escaped as a raw promise rejection (no JSONL failure row, no
800
- // `onWorkflowEnd`). It must instead land as drift: this call RESOLVES
801
- // (ok=true, drift set) rather than rejecting.
802
- const p0 = fakeArtifact("tasks/t0.md");
803
- const outA = memberVerdict("verdicts/v0a.json", true);
804
- const outB = memberVerdict("verdicts/v0b.json", true);
805
- const outC = memberVerdict("verdicts/v0c.json", false);
806
- const loop = assess({
807
- judge: panel({
808
- members: [
809
- judge({ skill: "grade-a", outcome: makeOutcome("verdict-a") }),
810
- judge({ skill: "grade-b", outcome: makeOutcome("verdict-b") }),
811
- judge({ skill: "grade-c", outcome: makeOutcome("verdict-c") }),
812
- ],
813
- // Raw fold (requires an `outcome`) that throws on the last-member fold.
814
- fold: () => {
815
- throw new Error("fold exploded");
816
- },
817
- outcome: makeOutcome("breakdown-panel"),
818
- }),
819
- done: (v) => Boolean((v.data as { pass?: boolean }).pass),
820
- feedForward: () => "more",
821
- });
822
- const wf: Workflow = {
823
- name: "test-wf",
824
- start: "breakdown",
825
- stages: { breakdown: produces({ outcome: makeOutcome("tasks"), loop }) },
826
- edges: { breakdown: "stop" },
827
- } as Workflow;
828
-
829
- writeRunStages([
830
- assessProduceRow("breakdown", 0, 1, fakeOutput([p0])),
831
- assessPanelJudgeRow("breakdown", "grade-a", 0, 0, 2, outA),
832
- assessPanelJudgeRow("breakdown", "grade-b", 0, 1, 3, outB),
833
- assessPanelJudgeRow("breakdown", "grade-c", 0, 2, 4, outC),
834
- ]);
835
-
836
- // Resolves with drift set — the fold did not reject out of reconstructState.
837
- const result = await reconstructState(tmpDir, wf, baseHeader);
838
- expect(result.ok).toBe(true);
839
- if (!result.ok) return;
840
- expect(result.drift?.parent).toBe("breakdown");
841
- expect(result.drift?.errMsg).toMatch(/fold exploded/);
842
- // State is still complete up to the throw: the last member's verdict applied
843
- // (on its OWN channel) BEFORE `advanceCursor` ran the throwing fold.
844
- expect(result.state.named["verdict-c"]).toEqual([outC]);
845
- // The fold never produced a value, so no folded verdict was published.
846
- expect(result.state.named["breakdown-panel"]).toBeUndefined();
847
- });
848
-
849
- it("REPLAY PARITY (C1): the fold's trailing cursor is byte-equal to a live cursor advanced over the same outputs", async () => {
850
- // `advanceCursor` is the ONE cursor state machine; this test pins the
851
- // contract that the fold and the live driver advance identically. The
852
- // trail ends mid-assess (produce, judge, produce — generation open) so
853
- // the fold returns its reconstructed cursor for comparison.
854
- const p0 = fakeOutput([fakeArtifact("tasks/t0.md")]);
855
- const v0 = fakeOutput([fakeArtifact("verdicts/v0.json")]);
856
- const p1 = fakeOutput([fakeArtifact("tasks/t1.md")]);
857
- const loop = assess({
858
- judge: judge({ skill: "grade", outcome: makeOutcome("verdict") }),
859
- done: () => false,
860
- feedForward: () => "more",
861
- });
862
- const wf: Workflow = {
863
- name: "test-wf",
864
- start: "breakdown",
865
- stages: { breakdown: produces({ outcome: makeOutcome("tasks"), loop }) },
866
- edges: { breakdown: "stop" },
867
- } as Workflow;
868
-
869
- writeRunStages([
870
- assessProduceRow("breakdown", 0, 1, p0),
871
- assessJudgeRow("breakdown", "grade", 0, 2, v0),
872
- assessProduceRow("breakdown", 1, 3, p1),
873
- ]);
874
-
875
- const result = await reconstructState(tmpDir, wf, baseHeader);
876
- expect(result.ok).toBe(true);
877
- if (!result.ok) return;
878
- expect(result.drift).toBeUndefined();
879
-
880
- // The live driver's exact sequence for the same three completed units.
881
- const live = freshCursor();
882
- advanceCursor(live, "produce", p0, loop);
883
- advanceCursor(live, "judge", v0, loop);
884
- advanceCursor(live, "produce", p1, loop);
885
-
886
- expect(JSON.stringify(result.trailing?.cursor)).toBe(JSON.stringify(live));
887
- });
888
-
889
- it("REPLAY PARITY (C1): fanout trailing cursor matches the live transition", async () => {
890
- const u1 = fakeOutput([fakeArtifact("builds/b1.md")]);
891
- const units: FanoutFn = () => [
892
- { prompt: "u1", label: "phase 1/2", id: "phase-1" },
893
- { prompt: "u2", label: "phase 2/2", id: "phase-2" },
894
- ];
895
- const loop = fanout({ units });
896
- const wf: Workflow = {
897
- name: "test-wf",
898
- start: "build",
899
- stages: { build: produces({ outcome: makeOutcome("builds"), loop }) },
900
- edges: { build: "stop" },
901
- } as Workflow;
902
-
903
- writeRunStages([fanoutUnitRow("build", "phase-1", 0, 1, u1)]);
904
-
905
- const result = await reconstructState(tmpDir, wf, baseHeader);
906
- expect(result.ok).toBe(true);
907
- if (!result.ok) return;
908
- expect(result.drift).toBeUndefined();
909
-
910
- const live = freshCursor();
911
- advanceCursor(live, "produce", u1, loop);
912
-
913
- expect(JSON.stringify(result.trailing?.cursor)).toBe(JSON.stringify(live));
914
- });
915
-
916
- it("named slot accumulates across completed rows for the same key (append order)", async () => {
917
- // Simulate a backward-jump loop: plan runs twice, producing two outputs.
918
- const art1 = fakeArtifact("plans/p1.md");
919
- const art2 = fakeArtifact("plans/p2.md");
920
- const out1 = fakeOutput([art1]);
921
- const out2 = fakeOutput([art2]);
922
-
923
- writeRunStages([
924
- {
925
- session: null,
926
- stageNumber: 1,
927
- stage: "plan",
928
- skill: "plan",
929
- status: "completed",
930
- ts: "2026-06-03T07:31:00Z",
931
- output: out1,
932
- },
933
- {
934
- session: null,
935
- stageNumber: 2,
936
- stage: "plan",
937
- skill: "plan",
938
- status: "completed",
939
- ts: "2026-06-03T07:35:00Z",
940
- output: out2,
941
- },
942
- ]);
943
-
944
- const result = await reconstructState(tmpDir, linearWorkflow, baseHeader);
945
-
946
- expect(result.ok).toBe(true);
947
- if (!result.ok) return;
948
-
949
- // Primary is the latest artifact
950
- expect(result.state.primaryArtifact).toStrictEqual(art2);
951
- // Named preserves full history in order
952
- expect(result.state.named.plan).toEqual([out1, out2]);
953
- expect(result.state.stagesCompleted).toBe(2);
954
- });
955
-
956
- it("aborted row is treated like a failed row: excluded from state seeding", async () => {
957
- const art1 = fakeArtifact("plans/p1.md");
958
- const out1 = fakeOutput([art1]);
959
-
960
- writeRunStages([
961
- {
962
- session: null,
963
- stageNumber: 1,
964
- stage: "plan",
965
- skill: "plan",
966
- status: "completed",
967
- ts: "2026-06-03T07:31:00Z",
968
- output: out1,
969
- },
970
- {
971
- session: null,
972
- stageNumber: 2,
973
- stage: "build",
974
- skill: "build",
975
- status: "aborted",
976
- ts: "2026-06-03T07:35:00Z",
977
- errMsg: "User cancelled",
978
- },
979
- ]);
980
-
981
- const result = await reconstructState(tmpDir, linearWorkflow, baseHeader);
982
-
983
- expect(result.ok).toBe(true);
984
- if (!result.ok) return;
985
-
986
- expect(result.state.stagesCompleted).toBe(1);
987
- expect(result.state.output).toStrictEqual(out1);
988
- expect(result.visited).toEqual(new Set(["plan", "build"]));
989
- expect(result.lastStageNumber).toBe(2);
990
- });
991
-
992
- it("skipped row is excluded from state seeding", async () => {
993
- const art1 = fakeArtifact("plans/p1.md");
994
- const out1 = fakeOutput([art1]);
995
-
996
- writeRunStages([
997
- {
998
- session: null,
999
- stageNumber: 1,
1000
- stage: "plan",
1001
- skill: "plan",
1002
- status: "completed",
1003
- ts: "2026-06-03T07:31:00Z",
1004
- output: out1,
1005
- },
1006
- {
1007
- session: null,
1008
- stageNumber: 2,
1009
- stage: "build",
1010
- skill: "build",
1011
- status: "skipped",
1012
- ts: "2026-06-03T07:35:00Z",
1013
- },
1014
- ]);
1015
-
1016
- const result = await reconstructState(tmpDir, linearWorkflow, baseHeader);
1017
-
1018
- expect(result.ok).toBe(true);
1019
- if (!result.ok) return;
1020
-
1021
- expect(result.state.stagesCompleted).toBe(1);
1022
- expect(result.state.output).toStrictEqual(out1);
1023
- expect(result.visited).toEqual(new Set(["plan", "build"]));
1024
- });
1025
- });
1026
-
1027
- // ---------------------------------------------------------------------------
1028
- // resumeWorkflow — end-to-end resume tests
1029
- // ---------------------------------------------------------------------------
1030
-
1031
- const RPIV_ARTIFACT_PATTERN = /\.rpiv\/artifacts\/[\w.-]+\/[\w.-]+\.md/g;
1032
-
1033
- /** Minimal outcome that scans assistant text for .rpiv/artifacts paths. */
1034
- const artifactOutcome: import("../output-spec.js").Outcome<unknown, "artifact-md", Record<string, unknown>> = {
1035
- collector: {
1036
- collect: (ctx) => {
1037
- let lastMatch: string | undefined;
1038
- const start = Math.max(ctx.branchOffset ?? 0, 0);
1039
- for (let i = ctx.branch.length - 1; i >= start && !lastMatch; i--) {
1040
- const entry = ctx.branch[i]!;
1041
- if (entry.type !== "message" || entry.message?.role !== "assistant") continue;
1042
- const content = entry.message.content;
1043
- if (!Array.isArray(content)) continue;
1044
- for (let j = content.length - 1; j >= 0; j--) {
1045
- const part = content[j]!;
1046
- if (part.type === "text" && typeof part.text === "string") {
1047
- const matches = part.text.match(RPIV_ARTIFACT_PATTERN);
1048
- if (matches && matches.length > 0) {
1049
- lastMatch = matches[matches.length - 1];
1050
- break;
1051
- }
1052
- }
1053
- }
1054
- }
1055
- if (!lastMatch) {
1056
- return {
1057
- kind: "fatal",
1058
- message: `${ctx.skill} finished without producing a .rpiv/artifacts path`,
1059
- };
1060
- }
1061
- return { kind: "ok", artifacts: [{ handle: fsHandle(lastMatch), role: "primary" }] };
1062
- },
1063
- },
1064
- };
1065
-
1066
- /** Build a minimal 2-stage produces workflow for resume tests. */
1067
- const twoStageWf: Workflow = {
1068
- name: "resume-wf",
1069
- start: "plan",
1070
- stages: {
1071
- plan: { kind: "produces", sessionPolicy: "fresh", outcome: artifactOutcome },
1072
- build: { kind: "produces", sessionPolicy: "fresh", outcome: artifactOutcome },
1073
- },
1074
- edges: {
1075
- plan: "build",
1076
- build: "stop",
1077
- },
1078
- };
1079
-
1080
- // --- verify row builders (siblings of assessProduceRow/assessJudgeRow) ---
1081
-
1082
- const verifyAttemptRow = (parent: string, attempt: number, num: number, output: Output): WorkflowStage => ({
1083
- session: null,
1084
- stageNumber: num,
1085
- stage: `${parent} (a${attempt}·attempt)`,
1086
- skill: parent,
1087
- status: "completed",
1088
- ts: `t${num}`,
1089
- parent,
1090
- role: "produce",
1091
- unitIndex: attempt,
1092
- output,
1093
- });
1094
-
1095
- const verifyVerdictRow = (
1096
- parent: string,
1097
- judgeSkill: string,
1098
- attempt: number,
1099
- num: number,
1100
- output: Output,
1101
- ): WorkflowStage => ({
1102
- session: null,
1103
- stageNumber: num,
1104
- stage: `${parent} (a${attempt}·verify)`,
1105
- skill: judgeSkill,
1106
- status: "completed",
1107
- ts: `t${num}`,
1108
- parent,
1109
- role: "verify",
1110
- unitIndex: attempt,
1111
- output,
1112
- });
1113
-
1114
- describe("reconstructState — verify generations", () => {
1115
- const pass = (v: Output) => Boolean((v.data as { done?: boolean }).done);
1116
- const gateVerify = () => verify({ judge: judge({ skill: "grade", outcome: makeOutcome("verdict") }), done: pass });
1117
- const retryVerify = () =>
1118
- verify({
1119
- judge: judge({ skill: "grade", outcome: makeOutcome("verdict") }),
1120
- done: pass,
1121
- feedForward: () => "again",
1122
- max: 3,
1123
- });
1124
-
1125
- it("closed verify generation: attempts + verdicts publish to separate channels; close restores the producer pair", async () => {
1126
- const a0 = fakeArtifact("impl/i0.md");
1127
- const v0 = fakeArtifact("verdicts/v0.json");
1128
- const a1 = fakeArtifact("impl/i1.md");
1129
- const v1 = fakeArtifact("verdicts/v1.json");
1130
- const g1 = fakeArtifact("gates/g1.md");
1131
- const wf: Workflow = {
1132
- name: "test-wf",
1133
- start: "build",
1134
- stages: {
1135
- build: produces({ outcome: makeOutcome("impl"), verify: retryVerify() }),
1136
- gate: produces({ outcome: makeOutcome("gates") }),
1137
- },
1138
- edges: { build: "gate", gate: "stop" },
1139
- } as Workflow;
1140
-
1141
- writeRunStages([
1142
- verifyAttemptRow("build", 0, 1, fakeOutput([a0])),
1143
- verifyVerdictRow("build", "grade", 0, 2, fakeOutput([v0])),
1144
- verifyAttemptRow("build", 1, 3, fakeOutput([a1])),
1145
- verifyVerdictRow("build", "grade", 1, 4, fakeOutput([v1])),
1146
- {
1147
- session: null,
1148
- stageNumber: 5,
1149
- stage: "gate",
1150
- skill: "gate",
1151
- status: "completed",
1152
- ts: "t5",
1153
- output: fakeOutput([g1]),
1154
- },
1155
- ]);
1156
-
1157
- const result = await reconstructState(tmpDir, wf, baseHeader);
1158
- expect(result.ok).toBe(true);
1159
- if (!result.ok) return;
1160
-
1161
- expect(result.state.named.impl?.map((o) => o.artifacts[0])).toEqual([a0, a1]);
1162
- expect(result.state.named.verdict?.map((o) => o.artifacts[0])).toEqual([v0, v1]);
1163
- // Generation closed before gate → "last" projects the last attempt (a1), THEN gate rolled it.
1164
- expect(result.state.primaryArtifact).toStrictEqual(g1);
1165
- expect(result.state.stagesCompleted).toBe(5);
1166
- expect(result.trailing).toBeUndefined();
1167
- expect(result.drift).toBeUndefined();
1168
- });
1169
-
1170
- it("trailing pending verify: a completed-attempt trailer reconstructs cursor phase 'judge'", async () => {
1171
- const a0 = fakeArtifact("impl/i0.md");
1172
- const wf: Workflow = {
1173
- name: "test-wf",
1174
- start: "build",
1175
- stages: { build: produces({ outcome: makeOutcome("impl"), verify: gateVerify() }) },
1176
- edges: { build: "stop" },
1177
- } as Workflow;
1178
-
1179
- writeRunStages([verifyAttemptRow("build", 0, 1, fakeOutput([a0]))]);
1180
-
1181
- const result = await reconstructState(tmpDir, wf, baseHeader);
1182
- expect(result.ok).toBe(true);
1183
- if (!result.ok) return;
1184
-
1185
- // The synthesized loop is recovered (no stage-gone refusal) and the
1186
- // cursor says: attempt 0 done, verdict pending.
1187
- expect(result.trailing?.parent).toBe("build");
1188
- expect(result.trailing?.cursor.phase).toBe("judge");
1189
- expect(result.trailing?.cursor.index).toBe(0);
1190
- expect(result.trailing?.cursor.lastProduce?.artifact).toStrictEqual(a0);
1191
- expect(result.drift).toBeUndefined();
1192
- });
1193
-
1194
- it("role drift: a verdict row carrying role 'judge' on a verify stage trips the guard", async () => {
1195
- const a0 = fakeArtifact("impl/i0.md");
1196
- const v0 = fakeArtifact("verdicts/v0.json");
1197
- const wf: Workflow = {
1198
- name: "test-wf",
1199
- start: "build",
1200
- stages: { build: produces({ outcome: makeOutcome("impl"), verify: gateVerify() }) },
1201
- edges: { build: "stop" },
1202
- } as Workflow;
1203
-
1204
- writeRunStages([
1205
- verifyAttemptRow("build", 0, 1, fakeOutput([a0])),
1206
- // Wrong role for a verify stage — the driver would have emitted "verify".
1207
- assessJudgeRow("build", "grade", 0, 2, fakeOutput([v0])),
1208
- ]);
1209
-
1210
- const result = await reconstructState(tmpDir, wf, baseHeader);
1211
- expect(result.ok).toBe(true);
1212
- if (!result.ok) return;
1213
- expect(result.drift?.parent).toBe("build");
1214
- });
1215
-
1216
- it("entryArgs freeze: a reads projection is frozen at generation open (a trailing verdict's transient roll can't leak in)", async () => {
1217
- const d0 = fakeArtifact("design/d0.md");
1218
- const a0 = fakeArtifact("impl/i0.md");
1219
- const v0 = fakeArtifact("verdicts/v0.json");
1220
- const wf: Workflow = {
1221
- name: "test-wf",
1222
- start: "design",
1223
- stages: {
1224
- design: produces({ outcome: makeOutcome("design") }),
1225
- build: produces({ outcome: makeOutcome("impl"), reads: ["design"], verify: retryVerify() }),
1226
- },
1227
- edges: { design: "build", build: "stop" },
1228
- } as Workflow;
1229
-
1230
- writeRunStages([
1231
- {
1232
- session: null,
1233
- stageNumber: 1,
1234
- stage: "design",
1235
- skill: "design",
1236
- status: "completed",
1237
- ts: "t1",
1238
- output: fakeOutput([d0]),
1239
- },
1240
- verifyAttemptRow("build", 0, 2, fakeOutput([a0])),
1241
- verifyVerdictRow("build", "grade", 0, 3, fakeOutput([v0])), // fail verdict — generation still open
1242
- ]);
1243
-
1244
- const result = await reconstructState(tmpDir, wf, baseHeader);
1245
- expect(result.ok).toBe(true);
1246
- if (!result.ok) return;
1247
-
1248
- expect(result.trailing?.entryArgs).toBe(`--design ${handleToString(d0.handle)}`);
1249
- });
1250
-
1251
- it("truncated trail: a reads-bearing verify generation with no producer row yields entryArgs undefined", async () => {
1252
- const a0 = fakeArtifact("impl/i0.md");
1253
- const wf: Workflow = {
1254
- name: "test-wf",
1255
- start: "design",
1256
- stages: {
1257
- design: produces({ outcome: makeOutcome("design") }),
1258
- build: produces({ outcome: makeOutcome("impl"), reads: ["design"], verify: gateVerify() }),
1259
- },
1260
- edges: { design: "build", build: "stop" },
1261
- } as Workflow;
1262
-
1263
- // The design row is gone — only the attempt row survives.
1264
- writeRunStages([verifyAttemptRow("build", 0, 1, fakeOutput([a0]))]);
1265
-
1266
- const result = await reconstructState(tmpDir, wf, baseHeader);
1267
- expect(result.ok).toBe(true);
1268
- if (!result.ok) return;
1269
- expect(result.trailing?.entryArgs).toBeUndefined();
1270
- });
1271
- });
1272
-
1273
- // ---------------------------------------------------------------------------
1274
- // lastChainIndex (C16) — the fold reconstructs the chain index instead of
1275
- // reusing the allocator's stageNumber (which counts every loop-unit row, so
1276
- // the two diverge past any loop: a 10-unit loop made status show "stage 14/5").
1277
- // ---------------------------------------------------------------------------
1278
-
1279
- describe("reconstructState — lastChainIndex", () => {
1280
- it("linear trail: one activation per row", async () => {
1281
- writeRunStages([
1282
- {
1283
- session: null,
1284
- stageNumber: 1,
1285
- stage: "plan",
1286
- skill: "plan",
1287
- status: "completed",
1288
- ts: "t1",
1289
- output: fakeOutput(),
1290
- },
1291
- { session: null, stageNumber: 2, stage: "build", skill: "build", status: "failed", ts: "t2", errMsg: "boom" },
1292
- ]);
1293
-
1294
- const result = await reconstructState(tmpDir, linearWorkflow, baseHeader);
1295
- expect(result.ok).toBe(true);
1296
- if (!result.ok) return;
1297
- expect(result.lastChainIndex).toBe(1);
1298
- });
1299
-
1300
- it("a loop generation counts as ONE activation, however many unit rows it wrote", async () => {
1301
- const units: FanoutFn = () => [
1302
- { prompt: "u1", label: "phase 1/3", id: "phase-1" },
1303
- { prompt: "u2", label: "phase 2/3", id: "phase-2" },
1304
- { prompt: "u3", label: "phase 3/3", id: "phase-3" },
1305
- ];
1306
- const wf: Workflow = {
1307
- name: "test-wf",
1308
- start: "plan",
1309
- stages: {
1310
- plan: produces({ outcome: makeOutcome("plans") }),
1311
- build: produces({ outcome: makeOutcome("builds"), loop: fanout({ units }) }),
1312
- deploy: produces({ outcome: makeOutcome("deploys") }),
1313
- },
1314
- edges: { plan: "build", build: "deploy", deploy: "stop" },
1315
- } as Workflow;
1316
-
1317
- writeRunStages([
1318
- {
1319
- session: null,
1320
- stageNumber: 1,
1321
- stage: "plan",
1322
- skill: "plan",
1323
- status: "completed",
1324
- ts: "t1",
1325
- output: fakeOutput(),
1326
- },
1327
- fanoutUnitRow("build", "phase-1", 0, 2, fakeOutput()),
1328
- fanoutUnitRow("build", "phase-2", 1, 3, fakeOutput()),
1329
- fanoutUnitRow("build", "phase-3", 2, 4, fakeOutput()),
1330
- {
1331
- session: null,
1332
- stageNumber: 5,
1333
- stage: "deploy",
1334
- skill: "deploy",
1335
- status: "failed",
1336
- ts: "t5",
1337
- errMsg: "boom",
1338
- },
1339
- ]);
1340
-
1341
- const result = await reconstructState(tmpDir, wf, baseHeader);
1342
- expect(result.ok).toBe(true);
1343
- if (!result.ok) return;
1344
- // plan(0) → build generation(1) → deploy(2). Pre-fix this was
1345
- // `last.stageNumber - 1` = 4.
1346
- expect(result.lastChainIndex).toBe(2);
1347
- });
1348
-
1349
- it("a resume re-run of a failed stage keeps its activation index", async () => {
1350
- writeRunStages([
1351
- {
1352
- session: null,
1353
- stageNumber: 1,
1354
- stage: "plan",
1355
- skill: "plan",
1356
- status: "completed",
1357
- ts: "t1",
1358
- output: fakeOutput(),
1359
- },
1360
- { session: null, stageNumber: 2, stage: "build", skill: "build", status: "failed", ts: "t2", errMsg: "boom" },
1361
- // resumed: build re-ran (same activation), then deploy failed
1362
- {
1363
- session: null,
1364
- stageNumber: 3,
1365
- stage: "build",
1366
- skill: "build",
1367
- status: "completed",
1368
- ts: "t3",
1369
- output: fakeOutput(),
1370
- },
1371
- {
1372
- session: null,
1373
- stageNumber: 4,
1374
- stage: "deploy",
1375
- skill: "deploy",
1376
- status: "failed",
1377
- ts: "t4",
1378
- errMsg: "boom",
1379
- },
1380
- ]);
1381
-
1382
- const result = await reconstructState(tmpDir, linearWorkflow, baseHeader);
1383
- expect(result.ok).toBe(true);
1384
- if (!result.ok) return;
1385
- // plan(0) → build(1, re-run folds into the same activation) → deploy(2).
1386
- expect(result.lastChainIndex).toBe(2);
1387
- });
1388
-
1389
- it("a backward-jump revisit of a COMPLETED stage is a new activation", async () => {
1390
- writeRunStages([
1391
- {
1392
- session: null,
1393
- stageNumber: 1,
1394
- stage: "plan",
1395
- skill: "plan",
1396
- status: "completed",
1397
- ts: "t1",
1398
- output: fakeOutput(),
1399
- },
1400
- {
1401
- session: null,
1402
- stageNumber: 2,
1403
- stage: "build",
1404
- skill: "build",
1405
- status: "completed",
1406
- ts: "t2",
1407
- output: fakeOutput(),
1408
- },
1409
- // decision edge routed back to plan (retry loop) — distinct activation
1410
- {
1411
- session: null,
1412
- stageNumber: 3,
1413
- stage: "plan",
1414
- skill: "plan",
1415
- status: "completed",
1416
- ts: "t3",
1417
- output: fakeOutput(),
1418
- },
1419
- ]);
1420
-
1421
- const result = await reconstructState(tmpDir, linearWorkflow, baseHeader);
1422
- expect(result.ok).toBe(true);
1423
- if (!result.ok) return;
1424
- expect(result.lastChainIndex).toBe(2);
1425
- });
1426
- });
1427
-
1428
- const resumeHeader: WorkflowHeader = {
1429
- runId: "2026-06-03_07-30-00-ab12",
1430
- workflow: "resume-wf",
1431
- input: "Add dark mode",
1432
- ts: "2026-06-03T07:30:00Z",
1433
- };
1434
-
1435
- describe("resumeWorkflow", () => {
1436
- /** Helper: write header + stages, return the header. */
1437
- function writeRun(header: WorkflowHeader, stages: WorkflowStage[]): void {
1438
- writeHeader(tmpDir, header);
1439
- for (const stage of stages) {
1440
- appendStage(tmpDir, header.runId, stage);
1441
- }
1442
- }
1443
-
1444
- /** Helper: read all stage rows from the run's JSONL. */
1445
- function readRunStages(runId: string): WorkflowStage[] {
1446
- return readAllStages(tmpDir, runId);
1447
- }
1448
-
1449
- /** Write an artifact file at the given relative path under tmpDir. */
1450
- function writeArtifact(relPath: string, content = "") {
1451
- const parts = relPath.split("/");
1452
- const dir = join(tmpDir, ...parts.slice(0, -1));
1453
- mkdirSync(dir, { recursive: true });
1454
- writeFileSync(join(tmpDir, relPath), content);
1455
- }
1456
-
1457
- it("failed-trailer: re-runs the failed stage and continues to completion", async () => {
1458
- // Stage 1 (plan) completed, stage 2 (build) failed.
1459
- // Resume should re-run build and complete.
1460
- const art1 = fakeArtifact("plans/p1.md");
1461
- const out1 = fakeOutput([art1]);
1462
-
1463
- writeRun(resumeHeader, [
1464
- {
1465
- session: null,
1466
- stageNumber: 1,
1467
- stage: "plan",
1468
- skill: "plan",
1469
- status: "completed",
1470
- ts: "2026-06-03T07:31:00Z",
1471
- output: out1,
1472
- },
1473
- {
1474
- session: null,
1475
- stageNumber: 2,
1476
- stage: "build",
1477
- skill: "build",
1478
- status: "failed",
1479
- ts: "2026-06-03T07:35:00Z",
1480
- errMsg: "Something went wrong",
1481
- },
1482
- ]);
1483
-
1484
- writeArtifact(".rpiv/artifacts/builds/b1.md");
1485
- const chain = createMockSessionChain({
1486
- cwd: tmpDir,
1487
- steps: [{ branch: [mockAssistantMessage("Wrote .rpiv/artifacts/builds/b1.md")] }],
1488
- });
1489
-
1490
- const result = await resumeWorkflow(chain.ctx, {
1491
- workflow: twoStageWf,
1492
- header: resumeHeader,
1493
- ref: "@2026-06-03_07-30-00-ab12",
1494
- });
1495
-
1496
- expect(result.success).toBe(true);
1497
- expect(result.runId).toBe(resumeHeader.runId);
1498
- // 1 (original plan) + 1 (re-ran build) = 2
1499
- expect(result.stagesCompleted).toBe(2);
1500
- expect(result.lastArtifact).toBe(".rpiv/artifacts/builds/b1.md");
1501
-
1502
- // JSONL should have: original header + plan(completed) + build(failed) + build(completed)
1503
- const stages = readRunStages(resumeHeader.runId);
1504
- expect(stages).toHaveLength(3); // 2 original + 1 new
1505
- expect(stages[2]).toMatchObject({
1506
- stage: "build",
1507
- status: "completed",
1508
- });
1509
- // New stage number is strictly greater than the failed row's number
1510
- expect(stages[2]!.stageNumber).toBeGreaterThan(stages[1]!.stageNumber);
1511
-
1512
- // Dispatched the re-run with the prior stage's artifact as input
1513
- expect(chain.sentMessages).toEqual(["/skill:build plans/p1.md"]);
1514
- });
1515
-
1516
- it("completed-trailer: routes onward from the last completed stage", async () => {
1517
- // Stage 1 (plan) completed. The last row is completed,
1518
- // so resume should route onward to build.
1519
- const art1 = fakeArtifact("plans/p1.md");
1520
- const out1 = fakeOutput([art1]);
1521
-
1522
- writeRun(resumeHeader, [
1523
- {
1524
- session: null,
1525
- stageNumber: 1,
1526
- stage: "plan",
1527
- skill: "plan",
1528
- status: "completed",
1529
- ts: "2026-06-03T07:31:00Z",
1530
- output: out1,
1531
- },
1532
- ]);
1533
-
1534
- writeArtifact(".rpiv/artifacts/builds/b1.md");
1535
- const chain = createMockSessionChain({
1536
- cwd: tmpDir,
1537
- steps: [{ branch: [mockAssistantMessage("Wrote .rpiv/artifacts/builds/b1.md")] }],
1538
- });
1539
-
1540
- const result = await resumeWorkflow(chain.ctx, {
1541
- workflow: twoStageWf,
1542
- header: resumeHeader,
1543
- ref: "@2026-06-03_07-30-00-ab12",
1544
- });
1545
-
1546
- expect(result.success).toBe(true);
1547
- expect(result.stagesCompleted).toBe(2);
1548
-
1549
- const stages = readRunStages(resumeHeader.runId);
1550
- expect(stages).toHaveLength(2); // 1 original + 1 new (build)
1551
- expect(stages[1]).toMatchObject({ stage: "build", status: "completed" });
1552
- expect(stages[1]!.stageNumber).toBeGreaterThan(stages[0]!.stageNumber);
1553
-
1554
- expect(chain.sentMessages).toEqual(["/skill:build plans/p1.md"]);
1555
- });
1556
-
1557
- it("cleanly finished run: immediate stop no-op (stagesCompleted unchanged)", async () => {
1558
- // Both stages completed, edge is "stop". Resuming routes onward from build,
1559
- // which hits stop → finalizeWorkflow → success. No new stage rows.
1560
- const art1 = fakeArtifact("plans/p1.md");
1561
- const art2 = fakeArtifact("builds/b1.md");
1562
- const out1 = fakeOutput([art1]);
1563
- const out2 = fakeOutput([art2]);
1564
-
1565
- writeRun(resumeHeader, [
1566
- {
1567
- session: null,
1568
- stageNumber: 1,
1569
- stage: "plan",
1570
- skill: "plan",
1571
- status: "completed",
1572
- ts: "2026-06-03T07:31:00Z",
1573
- output: out1,
1574
- },
1575
- {
1576
- session: null,
1577
- stageNumber: 2,
1578
- stage: "build",
1579
- skill: "build",
1580
- status: "completed",
1581
- ts: "2026-06-03T07:35:00Z",
1582
- output: out2,
1583
- },
1584
- ]);
1585
-
1586
- const chain = createMockSessionChain({ cwd: tmpDir, steps: [] });
1587
-
1588
- const result = await resumeWorkflow(chain.ctx, {
1589
- workflow: twoStageWf,
1590
- header: resumeHeader,
1591
- ref: "@2026-06-03_07-30-00-ab12",
1592
- });
1593
-
1594
- expect(result.success).toBe(true);
1595
- expect(result.stagesCompleted).toBe(2); // unchanged
1596
- expect(result.lastArtifact).toBe("builds/b1.md");
1597
-
1598
- // No new stage rows appended
1599
- const stages = readRunStages(resumeHeader.runId);
1600
- expect(stages).toHaveLength(2);
1601
-
1602
- // No new session was spawned
1603
- expect(chain.ctx.newSession).not.toHaveBeenCalled();
1604
- });
1605
-
1606
- it("no-rows refusal: returns error envelope, no self-notify (caller surfaces it)", async () => {
1607
- // Header-only file (no stage rows)
1608
- writeHeader(tmpDir, resumeHeader);
1609
-
1610
- const chain = createMockSessionChain({ cwd: tmpDir, steps: [] });
1611
-
1612
- const result = await resumeWorkflow(chain.ctx, {
1613
- workflow: twoStageWf,
1614
- header: resumeHeader,
1615
- ref: "@2026-06-03_07-30-00-ab12",
1616
- });
1617
-
1618
- expect(result.success).toBe(false);
1619
- expect(result.error).toMatch(/no recorded stages/);
1620
- expect(result.stagesCompleted).toBe(0);
1621
- // No runId on a no-JSONL refusal — the discriminator command uses to decide
1622
- // whether to notify (the stage machinery never wrote a failure row here).
1623
- expect(result.runId).toBeUndefined();
1624
-
1625
- // Pure envelope: resumeWorkflow does NOT self-notify (mirrors runWorkflow's
1626
- // pre-flight rejections). The caller surfaces result.error.
1627
- const errorNotifies = chain.notifications.filter((n) => n.level === "error" && /no recorded stages/.test(n.msg));
1628
- expect(errorNotifies).toHaveLength(0);
1629
-
1630
- // No new JSONL rows written on refusal
1631
- const stages = readRunStages(resumeHeader.runId);
1632
- expect(stages).toHaveLength(0);
1633
- });
1634
-
1635
- it("stage-gone refusal: returns error envelope, no self-notify", async () => {
1636
- writeRun(resumeHeader, [
1637
- {
1638
- session: null,
1639
- stageNumber: 1,
1640
- stage: "plan",
1641
- skill: "plan",
1642
- status: "completed",
1643
- ts: "2026-06-03T07:31:00Z",
1644
- },
1645
- {
1646
- session: null,
1647
- stageNumber: 2,
1648
- stage: "removed-stage",
1649
- skill: "removed-stage",
1650
- status: "failed",
1651
- ts: "2026-06-03T07:35:00Z",
1652
- errMsg: "fail",
1653
- },
1654
- ]);
1655
-
1656
- const chain = createMockSessionChain({ cwd: tmpDir, steps: [] });
1657
-
1658
- const result = await resumeWorkflow(chain.ctx, {
1659
- workflow: twoStageWf,
1660
- header: resumeHeader,
1661
- ref: "@2026-06-03_07-30-00-ab12",
1662
- });
1663
-
1664
- expect(result.success).toBe(false);
1665
- expect(result.error).toMatch(/no longer exists/);
1666
- expect(result.runId).toBeUndefined();
1667
-
1668
- const errorNotifies = chain.notifications.filter((n) => n.level === "error" && /no longer exists/.test(n.msg));
1669
- expect(errorNotifies).toHaveLength(0);
1670
- });
1671
-
1672
- it("resume does not write a new header (append-only)", async () => {
1673
- // Write a completed run, then resume it. The JSONL should have exactly
1674
- // one header line (the original) — no second header was appended.
1675
- const art1 = fakeArtifact("plans/p1.md");
1676
- const out1 = fakeOutput([art1]);
1677
-
1678
- writeRun(resumeHeader, [
1679
- {
1680
- session: null,
1681
- stageNumber: 1,
1682
- stage: "plan",
1683
- skill: "plan",
1684
- status: "completed",
1685
- ts: "2026-06-03T07:31:00Z",
1686
- output: out1,
1687
- },
1688
- ]);
1689
-
1690
- writeArtifact(".rpiv/artifacts/builds/b1.md");
1691
- const chain = createMockSessionChain({
1692
- cwd: tmpDir,
1693
- steps: [{ branch: [mockAssistantMessage("Wrote .rpiv/artifacts/builds/b1.md")] }],
1694
- });
1695
-
1696
- await resumeWorkflow(chain.ctx, {
1697
- workflow: twoStageWf,
1698
- header: resumeHeader,
1699
- ref: "@2026-06-03_07-30-00-ab12",
1700
- });
1701
-
1702
- // Read raw file and count header lines (lines with runId + workflow but no stageNumber)
1703
- const content = readFileSync(stateFilePath(tmpDir, resumeHeader.runId), "utf-8");
1704
- const lines = content.trim().split("\n");
1705
- const headerLines = lines.filter((l) => {
1706
- try {
1707
- const p = JSON.parse(l);
1708
- return typeof p.runId === "string" && typeof p.stageNumber !== "number";
1709
- } catch {
1710
- return false;
1711
- }
1712
- });
1713
- expect(headerLines).toHaveLength(1);
1714
- });
1715
-
1716
- it("new stage numbers are strictly greater than all prior stage numbers", async () => {
1717
- const art1 = fakeArtifact("plans/p1.md");
1718
- const out1 = fakeOutput([art1]);
1719
-
1720
- writeRun(resumeHeader, [
1721
- {
1722
- session: null,
1723
- stageNumber: 1,
1724
- stage: "plan",
1725
- skill: "plan",
1726
- status: "completed",
1727
- ts: "2026-06-03T07:31:00Z",
1728
- output: out1,
1729
- },
1730
- {
1731
- session: null,
1732
- stageNumber: 2,
1733
- stage: "build",
1734
- skill: "build",
1735
- status: "failed",
1736
- ts: "2026-06-03T07:35:00Z",
1737
- errMsg: "fail",
1738
- },
1739
- ]);
1740
-
1741
- writeArtifact(".rpiv/artifacts/builds/b1.md");
1742
- const chain = createMockSessionChain({
1743
- cwd: tmpDir,
1744
- steps: [{ branch: [mockAssistantMessage("Wrote .rpiv/artifacts/builds/b1.md")] }],
1745
- });
1746
-
1747
- await resumeWorkflow(chain.ctx, {
1748
- workflow: twoStageWf,
1749
- header: resumeHeader,
1750
- ref: "@2026-06-03_07-30-00-ab12",
1751
- });
1752
-
1753
- const stages = readRunStages(resumeHeader.runId);
1754
- const maxOriginal = Math.max(...stages.slice(0, 2).map((s) => s.stageNumber));
1755
- const newStages = stages.slice(2);
1756
- for (const s of newStages) {
1757
- expect(s.stageNumber).toBeGreaterThan(maxOriginal);
1758
- }
1759
- });
1760
-
1761
- it("stamps resumedFrom in trigger.meta", async () => {
1762
- const art1 = fakeArtifact("plans/p1.md");
1763
- const out1 = fakeOutput([art1]);
1764
-
1765
- writeRun(resumeHeader, [
1766
- {
1767
- session: null,
1768
- stageNumber: 1,
1769
- stage: "plan",
1770
- skill: "plan",
1771
- status: "completed",
1772
- ts: "2026-06-03T07:31:00Z",
1773
- output: out1,
1774
- },
1775
- ]);
1776
-
1777
- writeArtifact(".rpiv/artifacts/builds/b1.md");
1778
- const chain = createMockSessionChain({
1779
- cwd: tmpDir,
1780
- steps: [{ branch: [mockAssistantMessage("Wrote .rpiv/artifacts/builds/b1.md")] }],
1781
- });
1782
-
1783
- // Use lifecycle listeners to capture the trigger from LifecycleContext
1784
- const capturedTriggers: unknown[] = [];
1785
- await resumeWorkflow(chain.ctx, {
1786
- workflow: twoStageWf,
1787
- header: resumeHeader,
1788
- ref: "@my-run-ref",
1789
- lifecycle: {
1790
- onWorkflowStart: (lc) => {
1791
- capturedTriggers.push(lc.trigger);
1792
- },
1793
- },
1794
- });
1795
-
1796
- expect(capturedTriggers).toHaveLength(1);
1797
- expect(capturedTriggers[0]).toMatchObject({
1798
- kind: "command",
1799
- name: "wf",
1800
- meta: { resumedFrom: "@my-run-ref" },
1801
- });
1802
- });
1803
-
1804
- // Mid-loop resume dispatch (fanout/iterate/assess) is covered end-to-end in `resume-loop.test.ts`.
1805
- });