@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
@@ -1,331 +0,0 @@
1
- /**
2
- * End-to-end fanout-resume tests — drive `resumeWorkflow` over a fanout workflow
3
- * with a mock session chain. Complements the pure-fold cases in resume.test.ts.
4
- */
5
-
6
- import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
7
- import { tmpdir } from "node:os";
8
- import { join } from "node:path";
9
- import { createMockSessionChain, mockAssistantMessage } from "@juicesharp/rpiv-test-utils";
10
- import { Type } from "typebox";
11
- import { afterEach, beforeEach, describe, expect, it } from "vitest";
12
- import { type FanoutUnit, gate, produces, type Workflow } from "../api.js";
13
- import { fs as fsHandle } from "../handle.js";
14
- import type { OutputSpec } from "../output.js";
15
- import { eq, gt } from "../predicates.js";
16
- import { appendStage, readAllStages, type WorkflowHeader, type WorkflowStage, writeHeader } from "../state/index.js";
17
- import { typeboxSchema } from "../typebox-adapter.js";
18
- import { resumeWorkflow } from "./runner.js";
19
-
20
- let tmpDir: string;
21
- beforeEach(() => {
22
- tmpDir = mkdtempSync(join(tmpdir(), "rpiv-workflow-fanout-resume-"));
23
- });
24
- afterEach(() => {
25
- rmSync(tmpDir, { recursive: true, force: true });
26
- });
27
-
28
- const header: WorkflowHeader = {
29
- runId: "2026-06-03_07-30-00-ab12",
30
- workflow: "fanout-wf",
31
- input: "Ship it",
32
- ts: "2026-06-03T07:30:00Z",
33
- };
34
-
35
- /** Deterministic 3-unit fanout (blind to artifact, stable across re-call). */
36
- const threeUnits = (): readonly FanoutUnit[] =>
37
- [1, 2, 3].map((n) => ({ prompt: `phase ${n}`, label: `phase ${n}/3`, id: `phase-${n}` }));
38
-
39
- const fanoutWf: Workflow = {
40
- name: "fanout-wf",
41
- start: "impl",
42
- stages: { impl: { kind: "produces", sessionPolicy: "fresh", fanout: threeUnits } },
43
- edges: { impl: "stop" },
44
- } as Workflow;
45
-
46
- function writeRun(stages: WorkflowStage[]): void {
47
- writeHeader(tmpDir, header);
48
- for (const s of stages) appendStage(tmpDir, header.runId, s);
49
- }
50
- const unitRow = (n: number, num: number, status: "completed" | "failed"): WorkflowStage => ({
51
- stageNumber: num,
52
- stage: `impl (phase-${n})`,
53
- skill: "impl",
54
- status,
55
- ts: `t${num}`,
56
- ...(status === "failed" ? { errMsg: "boom" } : {}),
57
- });
58
-
59
- describe("fanout-resume", () => {
60
- it("mid-fanout failure: re-runs only the failed unit + remaining, then chains to stop", async () => {
61
- writeRun([unitRow(1, 1, "completed"), unitRow(2, 2, "completed"), unitRow(3, 3, "failed")]);
62
- const chain = createMockSessionChain({
63
- cwd: tmpDir,
64
- steps: [{ branch: [mockAssistantMessage("unit 3 done")] }],
65
- });
66
-
67
- const result = await resumeWorkflow(chain.ctx, { workflow: fanoutWf, header, ref: "@x" });
68
-
69
- expect(result.success).toBe(true);
70
- // Only unit 3 re-ran → exactly one new dispatch.
71
- expect(chain.sentMessages).toEqual(["/skill:impl phase 3"]);
72
- // New completed row appended for unit 3; total = 3 original + 1 new.
73
- const rows = readAllStages(tmpDir, header.runId);
74
- expect(rows).toHaveLength(4);
75
- expect(rows[3]).toMatchObject({ stage: "impl (phase-3)", status: "completed" });
76
- });
77
-
78
- it("process died mid-fanout (no failure row): resumes at the next unit", async () => {
79
- writeRun([unitRow(1, 1, "completed")]); // only unit 1 recorded
80
- const chain = createMockSessionChain({
81
- cwd: tmpDir,
82
- steps: [{ branch: [mockAssistantMessage("unit 2")] }, { branch: [mockAssistantMessage("unit 3")] }],
83
- });
84
-
85
- const result = await resumeWorkflow(chain.ctx, { workflow: fanoutWf, header, ref: "@x" });
86
-
87
- expect(result.success).toBe(true);
88
- expect(chain.sentMessages).toEqual(["/skill:impl phase 2", "/skill:impl phase 3"]);
89
- });
90
-
91
- it("fully-completed fanout: no-op route-onward — single completion notice, no re-announce", async () => {
92
- writeRun([unitRow(1, 1, "completed"), unitRow(2, 2, "completed"), unitRow(3, 3, "completed")]);
93
- const fanoutStarts: number[] = [];
94
- const stageStarts: string[] = [];
95
- const chain = createMockSessionChain({ cwd: tmpDir, steps: [] });
96
-
97
- const result = await resumeWorkflow(chain.ctx, {
98
- workflow: fanoutWf,
99
- header,
100
- ref: "@x",
101
- lifecycle: {
102
- onFanoutStart: (_stage, units) => {
103
- fanoutStarts.push(units.length);
104
- },
105
- onStageStart: (stage) => {
106
- stageStarts.push(stage.name);
107
- },
108
- },
109
- });
110
-
111
- expect(result.success).toBe(true);
112
- expect(chain.ctx.newSession).not.toHaveBeenCalled();
113
- expect(readAllStages(tmpDir, header.runId)).toHaveLength(3); // no new rows
114
-
115
- // Short-circuit: the finished fanout is NOT re-announced (no onStageStart /
116
- // onFanoutStart re-fire on a no-op resume).
117
- expect(fanoutStarts).toEqual([]);
118
- expect(stageStarts).toEqual([]);
119
- // ...and the only completion toast is the workflow-level one — no spurious
120
- // per-stage "✓ impl completed" (symmetric with a finished-linear resume).
121
- expect(chain.notifications.filter((n) => n.msg === "✓ impl completed")).toEqual([]);
122
- expect(chain.notifications.filter((n) => /workflow complete/.test(n.msg))).toHaveLength(1);
123
- });
124
-
125
- it("non-deterministic FanoutFn: records a terminal failure, refuses to re-run wrong units", async () => {
126
- // Recorded run had `phase-1` completed; the workflow now recomputes different ids.
127
- const drifted: Workflow = {
128
- name: "fanout-wf",
129
- start: "impl",
130
- stages: {
131
- impl: {
132
- kind: "produces",
133
- sessionPolicy: "fresh",
134
- fanout: () => [{ prompt: "x", label: "task 1", id: "task-1" }],
135
- },
136
- },
137
- edges: { impl: "stop" },
138
- } as Workflow;
139
- writeRun([unitRow(1, 1, "completed"), unitRow(2, 2, "failed")]);
140
- const chain = createMockSessionChain({ cwd: tmpDir, steps: [] });
141
-
142
- const result = await resumeWorkflow(chain.ctx, { workflow: drifted, header, ref: "@x" });
143
-
144
- expect(result.success).toBe(false);
145
- expect(result.error).toMatch(/deterministic/);
146
- // In-run failure (we got far enough to start resuming) → runId present, row written.
147
- expect(result.runId).toBe(header.runId);
148
- const rows = readAllStages(tmpDir, header.runId);
149
- expect(rows[rows.length - 1]).toMatchObject({ stage: "impl", status: "failed" });
150
- // No unit was dispatched.
151
- expect(chain.sentMessages).toEqual([]);
152
- });
153
-
154
- it("paren-in-label: a parenthesized completed prefix still resumes (no false mismatch)", async () => {
155
- // The decoration guard compares full strings — a label containing parens
156
- // (`impl (phase (a))`) must not be mis-parsed into a spurious mismatch.
157
- const parenUnits = (): readonly FanoutUnit[] => [
158
- { prompt: "first", label: "phase (a)" },
159
- { prompt: "second", label: "phase (b)" },
160
- ];
161
- const parenWf: Workflow = {
162
- name: "fanout-wf",
163
- start: "impl",
164
- stages: { impl: { kind: "produces", sessionPolicy: "fresh", fanout: parenUnits } },
165
- edges: { impl: "stop" },
166
- } as Workflow;
167
- // Unit 1 (label "phase (a)") completed; unit 2 failed.
168
- writeRun([
169
- { stageNumber: 1, stage: "impl (phase (a))", skill: "impl", status: "completed", ts: "t1" },
170
- { stageNumber: 2, stage: "impl (phase (b))", skill: "impl", status: "failed", ts: "t2", errMsg: "boom" },
171
- ]);
172
- const chain = createMockSessionChain({ cwd: tmpDir, steps: [{ branch: [mockAssistantMessage("unit b")] }] });
173
-
174
- const result = await resumeWorkflow(chain.ctx, { workflow: parenWf, header, ref: "@x" });
175
-
176
- expect(result.success).toBe(true);
177
- // Prefix matched despite the parens → only unit 2 re-ran.
178
- expect(chain.sentMessages).toEqual(["/skill:impl second"]);
179
- });
180
- });
181
-
182
- // ---------------------------------------------------------------------------
183
- // Looped fanout — a gated back-edge (review → impl) ran the fanout a SECOND
184
- // time and died mid-second-pass. Resume must continue only the trailing
185
- // generation; the fold no longer concatenates the prior pass into the prefix.
186
- // ---------------------------------------------------------------------------
187
-
188
- const PATTERN = /\.rpiv\/artifacts\/[\w.-]+\/[\w.-]+\.md/g;
189
-
190
- /** Transcript-scan outcome (rpiv-pi convention, inlined). Emits matched paths as artifacts. */
191
- const transcriptOutcome = (name: string): OutputSpec<unknown, "artifact-md", Record<string, unknown>> => ({
192
- name,
193
- collector: {
194
- collect: (ctx) => {
195
- const matches: string[] = [];
196
- for (let i = Math.max(ctx.branchOffset ?? 0, 0); i < ctx.branch.length; i++) {
197
- const entry = ctx.branch[i]!;
198
- if (entry.type !== "message" || entry.message?.role !== "assistant") continue;
199
- const content = entry.message.content;
200
- if (!Array.isArray(content)) continue;
201
- for (const part of content) {
202
- if (part.type === "text" && typeof part.text === "string") {
203
- const m = part.text.match(PATTERN);
204
- if (m) matches.push(...m);
205
- }
206
- }
207
- }
208
- if (matches.length === 0) return { kind: "fatal", message: `${ctx.skill} produced no artifact path` };
209
- return { kind: "ok", artifacts: matches.map((p) => ({ handle: fsHandle(p), role: "primary" as const })) };
210
- },
211
- },
212
- parser: { parse: () => ({ kind: "ok", payload: { kind: "artifact-md", data: {} } }) },
213
- });
214
-
215
- /** Like transcriptOutcome but parses blockers_count from the artifact's frontmatter (drives the gate). */
216
- const blockersOutcome = (name: string): OutputSpec<unknown, "artifact-md", Record<string, unknown>> => ({
217
- name,
218
- collector: transcriptOutcome(name).collector,
219
- parser: {
220
- parse: (ctx) => {
221
- const primary = ctx.artifacts[0];
222
- if (primary?.handle.kind !== "fs") return { kind: "ok", payload: { kind: "artifact-md", data: {} } };
223
- const abs = primary.handle.path.startsWith("/") ? primary.handle.path : join(ctx.cwd, primary.handle.path);
224
- const m = readFileSync(abs, "utf-8").match(/blockers_count:\s*(\d+)/);
225
- return { kind: "ok", payload: { kind: "artifact-md", data: { blockers_count: Number(m?.[1] ?? 0) } } };
226
- },
227
- },
228
- });
229
-
230
- /** Two stable units, blind to the artifact (same prefix every generation). */
231
- const implUnits = (): readonly FanoutUnit[] => [
232
- { prompt: "a", label: "a" },
233
- { prompt: "b", label: "b" },
234
- ];
235
-
236
- describe("fanout-resume — looped (corrective) back-edge", () => {
237
- let loopDir: string;
238
- beforeEach(() => {
239
- loopDir = mkdtempSync(join(tmpdir(), "rpiv-fanout-resume-loop-"));
240
- });
241
- afterEach(() => {
242
- rmSync(loopDir, { recursive: true, force: true });
243
- });
244
-
245
- const loopHeader: WorkflowHeader = {
246
- runId: "2026-06-03_09-30-00-ef56",
247
- workflow: "fanout-loop",
248
- input: "Ship it",
249
- ts: "2026-06-03T09:30:00Z",
250
- };
251
-
252
- const writeLoopArtifact = (rel: string, body: string) => {
253
- mkdirSync(join(loopDir, ...rel.split("/").slice(0, -1)), { recursive: true });
254
- writeFileSync(join(loopDir, rel), body);
255
- };
256
-
257
- const out = (stage: string, num: number, rel: string): WorkflowStage["output"] => ({
258
- kind: "artifacts",
259
- artifacts: [{ handle: fsHandle(rel), role: "primary" }],
260
- data: {},
261
- meta: { stage, stageNumber: num, ts: "", runId: "" },
262
- });
263
-
264
- it("died mid-second-pass: re-runs only the trailing generation's remaining unit, then routes onward", async () => {
265
- // seed -> impl(fanout a,b) -> review(gate: loop to impl if blockers>0, else stop).
266
- // Recorded: seed -> impl(a,b) gen 1 -> review(blockers=1, looped) -> impl(a) gen 2 done, impl(b) died.
267
- writeLoopArtifact(".rpiv/artifacts/reviews/cr2.md", "---\nblockers_count: 0\n---\n");
268
- writeHeader(loopDir, loopHeader);
269
- const rows: WorkflowStage[] = [
270
- {
271
- stageNumber: 1,
272
- stage: "seed",
273
- skill: "seed",
274
- status: "completed",
275
- ts: "t1",
276
- output: out("seed", 1, ".rpiv/artifacts/seeds/s1.md"),
277
- },
278
- { stageNumber: 2, stage: "impl (a)", skill: "impl", status: "completed", ts: "t2" },
279
- { stageNumber: 3, stage: "impl (b)", skill: "impl", status: "completed", ts: "t3" },
280
- {
281
- stageNumber: 4,
282
- stage: "review",
283
- skill: "review",
284
- status: "completed",
285
- ts: "t4",
286
- output: out("review", 4, ".rpiv/artifacts/reviews/cr1.md"),
287
- },
288
- // gen 2 — non-contiguous with gen 1 (the review row broke contiguity).
289
- { stageNumber: 5, stage: "impl (a)", skill: "impl", status: "completed", ts: "t5" },
290
- { stageNumber: 6, stage: "impl (b)", skill: "impl", status: "failed", ts: "t6", errMsg: "boom" },
291
- ];
292
- for (const s of rows) appendStage(loopDir, loopHeader.runId, s);
293
-
294
- const chain = createMockSessionChain({
295
- cwd: loopDir,
296
- steps: [
297
- { branch: [mockAssistantMessage("unit b done")] }, // impl gen-2 unit b re-run
298
- { branch: [mockAssistantMessage("wrote .rpiv/artifacts/reviews/cr2.md")] }, // review gen 2 → blockers=0
299
- ],
300
- });
301
-
302
- const wf: Workflow = {
303
- name: "fanout-loop",
304
- start: "seed",
305
- stages: {
306
- seed: produces({ outcome: transcriptOutcome("seeds") }),
307
- impl: { kind: "produces", sessionPolicy: "fresh", fanout: implUnits },
308
- review: produces({
309
- outcome: blockersOutcome("reviews"),
310
- outputSchema: typeboxSchema(Type.Object({ blockers_count: Type.Number() })),
311
- }),
312
- },
313
- edges: {
314
- seed: "impl",
315
- impl: "review",
316
- review: gate("blockers_count", { impl: gt(0), stop: eq(0) }),
317
- },
318
- } as Workflow;
319
-
320
- const result = await resumeWorkflow(chain.ctx, { workflow: wf, header: loopHeader, ref: "@x" });
321
-
322
- expect(result.success).toBe(true);
323
- // Only the trailing generation's remaining unit (b) re-ran — unit a of gen 2 did NOT.
324
- // Then review re-ran (gen 2), saw blockers=0, and the gate routed to stop.
325
- expect(chain.sentMessages).toEqual(["/skill:impl b", "/skill:review .rpiv/artifacts/reviews/cr1.md"]);
326
- // New rows appended after the originals with strictly greater stage numbers.
327
- const all = readAllStages(loopDir, loopHeader.runId);
328
- expect(all.slice(6).every((s) => s.stageNumber > 6)).toBe(true);
329
- expect(all[all.length - 1]).toMatchObject({ stage: "review", status: "completed" });
330
- });
331
- });
@@ -1,136 +0,0 @@
1
- /**
2
- * Fanout-resume dispatch. When a resumed run's trail trailer is a `def.fanout`
3
- * unit row, `resumeWorkflow` routes here instead of the single-stage arms.
4
- *
5
- * Re-calls the stage's `FanoutFn` against the reconstructed entry artifact +
6
- * state (units never move the primary, so `reconstructState` rebuilt the
7
- * pre-fanout artifact exactly — for a looped fanout that is the post-loop
8
- * primary, i.e. the trailing generation's entry), guards that the completed-unit
9
- * prefix still matches the recomputed unit list, then re-enters `runFanout` at
10
- * the first not-yet-completed unit. `reconstructState` feeds only the TRAILING
11
- * generation's prefix, so a second-pass resume compares against the right pass.
12
- * The fanout's own continuation loop + `advanceAfter` carry the chain onward.
13
- *
14
- * REQUIRES the FanoutFn to be deterministic w.r.t. its entry artifact: resume
15
- * trusts it to reproduce the same unit prefix. A divergence (FanoutFn read
16
- * mutable external state, or the entry artifact changed under it) is caught by
17
- * the prefix guard and recorded as a terminal failure — resume refuses to
18
- * re-run the wrong units rather than guess.
19
- *
20
- * `deps` are injected by `resumeWorkflow` (the same `runFanoutSession` +
21
- * `advanceChain`-backed `advanceAfter` that `tryFanout` injects), so this
22
- * module mirrors `runFanout`'s primitive-injection shape and imports no cycle
23
- * back into the session layer.
24
- */
25
-
26
- import type { FanoutUnit, StageDef } from "../api.js";
27
- import { auditCtxFor, recordTerminalFailure } from "../audit.js";
28
- import type { FanoutDeps } from "../fanout.js";
29
- import { runFanout } from "../fanout.js";
30
- import { currentPrimaryArtifact, resolveSkill } from "../internal-utils.js";
31
- import { skillStageRef } from "../lifecycle.js";
32
- import { ERR_RESUME_FANOUT_MISMATCH, MSG_RESUME_FANOUT_MISMATCH } from "../messages.js";
33
- import type { RunContext, WorkflowHostContext } from "../types.js";
34
- import { lifecycleCtxFor } from "./runner.js";
35
-
36
- /**
37
- * Resume a fanout stage whose units are a completed prefix `1..k` (with the
38
- * failure/cutoff at `k+1`). `completedDecorated` is the ordered list of
39
- * completed unit `WorkflowStage.stage` strings for this parent, from
40
- * `reconstructState`'s `fanoutProgress`.
41
- *
42
- * `idx` is the display/audit index (the trailer unit row's `stageNumber - 1`),
43
- * consistent with the approximation `resumeWorkflow` already uses for the
44
- * single-stage arms. Routing correctness keys on the parent NAME, not `idx`.
45
- */
46
- export async function resumeFanoutStage(
47
- ctx: WorkflowHostContext,
48
- parent: string,
49
- idx: number,
50
- completedDecorated: readonly string[],
51
- run: RunContext,
52
- deps: FanoutDeps,
53
- ): Promise<void> {
54
- const def = run.workflow.stages[parent]!; // caller verified parent is a fanout stage
55
- const skill = resolveSkill(def, parent); // mirror resolveStage; aliased nodes tag rows with the skill body
56
- const units = await recomputeUnits(def, run);
57
-
58
- if (fanoutPrefixDrifted(parent, completedDecorated, units)) {
59
- await recordFanoutDriftFailure(ctx, run, parent, skill);
60
- return;
61
- }
62
-
63
- // All units already completed → pure route-onward, no re-announce, no toast
64
- // (see `reannounceFanout` for why the no-op path stays silent).
65
- if (completedDecorated.length === units.length) {
66
- await deps.advanceAfter(ctx, parent, idx, run);
67
- return;
68
- }
69
-
70
- await reannounceFanout(ctx, run, parent, idx, skill, units);
71
- // p is 1-based: completedDecorated.length completed units ⇒ next is +1.
72
- await runFanout(ctx, idx, parent, skill, completedDecorated.length + 1, units, run, deps);
73
- }
74
-
75
- /**
76
- * Re-derive the unit list from the reconstructed entry context — the same call
77
- * `tryFanout` makes on the live path. Units never move the primary, so
78
- * `reconstructState` rebuilt the pre-fanout artifact exactly; the FanoutFn sees
79
- * the same input it saw originally (the determinism contract).
80
- */
81
- function recomputeUnits(def: StageDef, run: RunContext): Promise<readonly FanoutUnit[]> | readonly FanoutUnit[] {
82
- return def.fanout!({ cwd: run.cwd, artifact: currentPrimaryArtifact(run.state), state: run.state });
83
- }
84
-
85
- /**
86
- * Determinism guard: the completed prefix must still line up with the recomputed
87
- * units, by full decorated-string equality (no tag-parsing — a label/id
88
- * containing parens stays unambiguous). A divergence means the FanoutFn read
89
- * mutable external state or the entry artifact changed under it; resume refuses
90
- * rather than re-run the wrong units.
91
- */
92
- function fanoutPrefixDrifted(
93
- parent: string,
94
- completedDecorated: readonly string[],
95
- units: readonly FanoutUnit[],
96
- ): boolean {
97
- if (completedDecorated.length > units.length) return true;
98
- return completedDecorated.some((decorated, i) => decorated !== `${parent} (${units[i]!.id ?? units[i]!.label})`);
99
- }
100
-
101
- /** Record the terminal failure for a non-deterministic FanoutFn (drift caught by the prefix guard). */
102
- function recordFanoutDriftFailure(
103
- ctx: WorkflowHostContext,
104
- run: RunContext,
105
- parent: string,
106
- skill: string,
107
- ): Promise<void> {
108
- return recordTerminalFailure(ctx, auditCtxFor(run, parent, skill), {
109
- status: "failed",
110
- notifyMsg: MSG_RESUME_FANOUT_MISMATCH(parent),
111
- notifyLevel: "error",
112
- errMsg: ERR_RESUME_FANOUT_MISMATCH(parent),
113
- });
114
- }
115
-
116
- /**
117
- * Re-fire onStageStart + onFanoutStart for listener coherence (mirror tryFanout)
118
- * before re-entering the loop. The full unit list is replayed; onFanoutUnitStart/End
119
- * then fire only for the resumed units (runFanout starts at p), so listeners see
120
- * the remaining work. NOT fired on the all-complete no-op path — re-announcing a
121
- * fanout with no units left to run would mislead listeners and double the
122
- * completion notice (keeps a finished-fanout resume symmetric with a
123
- * finished-linear one: a single "workflow complete" via finalizeWorkflow).
124
- */
125
- async function reannounceFanout(
126
- ctx: WorkflowHostContext,
127
- run: RunContext,
128
- parent: string,
129
- idx: number,
130
- skill: string,
131
- units: readonly FanoutUnit[],
132
- ): Promise<void> {
133
- const ref = skillStageRef(parent, idx + 1, skill);
134
- await run.lifecycle.fire(ctx, "onStageStart", ref, lifecycleCtxFor(run));
135
- await run.lifecycle.fire(ctx, "onFanoutStart", ref, units, lifecycleCtxFor(run));
136
- }