@juicesharp/rpiv-workflow 1.17.0 → 1.18.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.
@@ -0,0 +1,333 @@
1
+ /**
2
+ * State reconstruction for resuming a failed (or cut-off) workflow run.
3
+ * Pure fold over the JSONL audit trail — no I/O beyond `readAllStages`.
4
+ *
5
+ * Used by `resumeWorkflow` (runner.ts) to rebuild `RunState` from a past
6
+ * run's stage rows, then re-enter the chain machinery at the right seam.
7
+ * New rows **append to the same JSONL file** so the trail reads as one
8
+ * story: *ran → failed → resumed → continued*.
9
+ *
10
+ * Folds `def.fanout` unit rows so fanout runs are resumable; this REQUIRES the
11
+ * stage's FanoutFn to be deterministic w.r.t. its entry artifact (the resume
12
+ * dispatch re-calls it and guards the unit prefix — see `resume-fanout.ts`). The
13
+ * fold is generation-aware: a looped fanout records only the TRAILING generation's
14
+ * unit prefix, so a second-pass resume compares against the right pass.
15
+ * Folds `def.iterate` unit rows as full produces passes (each unit ran the
16
+ * produces path on the live run, so its `Output` is persisted in the row): it
17
+ * rolls the primary, appends to `state.named`, and rebuilds the trailing
18
+ * generation's `accumulated` prefix + frozen entry artifact for the resume
19
+ * dispatch. This REQUIRES the IterateFn to be deterministic w.r.t. its entry
20
+ * artifact + accumulated outputs — `resume-iterate.ts` guards only the ONE
21
+ * checkable boundary (the re-pulled next unit vs the failed trailer's recorded
22
+ * decoration); the already-completed prefix is covered by that contract, not
23
+ * replayed (the generator sees a mutating `state` per unit, so faithful
24
+ * intermediate replay is infeasible).
25
+ */
26
+
27
+ import type { StageDef, Workflow } from "../api.js";
28
+ import type { Artifact } from "../handle.js";
29
+ import { applyCompletedStage } from "../internal-utils.js";
30
+ import type { Output } from "../output.js";
31
+ import { readAllStages } from "../state/index.js";
32
+ import type { WorkflowHeader, WorkflowStage } from "../state/state.js";
33
+ import type { RunState } from "../types.js";
34
+
35
+ // ---------------------------------------------------------------------------
36
+ // Result type
37
+ // ---------------------------------------------------------------------------
38
+
39
+ /**
40
+ * Per-fanout-parent record of the TRAILING generation's COMPLETED unit rows, in
41
+ * trail order, as their decorated `WorkflowStage.stage` strings (`"impl (phase 1/4)"`).
42
+ * Consumed by `resumeFanoutStage` to compute the resume point + guard FanoutFn
43
+ * determinism by full-string comparison. A failed unit row is NOT recorded here
44
+ * (it's the `k+1` that resume re-runs). On a looped fanout the array resets per
45
+ * generation, so a second-pass resume compares only the second pass's prefix.
46
+ */
47
+ export type FanoutProgress = ReadonlyMap<string, readonly string[]>;
48
+
49
+ /**
50
+ * Per-iterate-parent resume point — the TRAILING contiguous generation's state.
51
+ * Consumed by `resumeIterateStage` to re-enter the pull loop.
52
+ *
53
+ * - `entryArtifact` — the primary FROZEN at the generation's first unit (units
54
+ * roll the primary forward, so the rebuilt `state.primaryArtifact` is the LAST
55
+ * unit's artifact, not this). `undefined` if the iterate stage was the entry.
56
+ * - `accumulated` — the completed `Output`s of the trailing generation, in order
57
+ * (the IterateFn pull prefix; `index` resumes at `accumulated.length`). A failed
58
+ * unit contributes nothing (it's the unit resume re-pulls + re-runs).
59
+ *
60
+ * Reset whenever a non-iterate row (or a different parent) breaks contiguity, so a
61
+ * corrective-loop second pass overwrites the first pass's point. `state.named` still
62
+ * accumulates across ALL generations — only this prefix resets.
63
+ */
64
+ export interface IterateResumePoint {
65
+ entryArtifact: Artifact | undefined;
66
+ accumulated: Output[];
67
+ }
68
+ export type IterateProgress = ReadonlyMap<string, IterateResumePoint>;
69
+
70
+ export type ReconstructResult =
71
+ | {
72
+ ok: true;
73
+ state: RunState;
74
+ lastStageNumber: number;
75
+ visited: Set<string>;
76
+ rows: WorkflowStage[];
77
+ fanoutProgress: FanoutProgress;
78
+ iterateProgress: IterateProgress;
79
+ }
80
+ | { ok: false; reason: "no-rows" | "stage-gone"; detail: string };
81
+
82
+ // ---------------------------------------------------------------------------
83
+ // Fanout-decoration helpers (shared with resumeWorkflow dispatch)
84
+ // ---------------------------------------------------------------------------
85
+
86
+ /** Stage record keys whose def opts into `fanout`. */
87
+ export function fanoutStageNames(workflow: Workflow): ReadonlySet<string> {
88
+ const names = new Set<string>();
89
+ for (const [name, def] of Object.entries(workflow.stages)) {
90
+ if (def.fanout) names.add(name);
91
+ }
92
+ return names;
93
+ }
94
+
95
+ /** Stage record keys whose def opts into `iterate`. */
96
+ export function iterateStageNames(workflow: Workflow): ReadonlySet<string> {
97
+ const names = new Set<string>();
98
+ for (const [name, def] of Object.entries(workflow.stages)) {
99
+ if (def.iterate) names.add(name);
100
+ }
101
+ return names;
102
+ }
103
+
104
+ /**
105
+ * Recover the parent stage name from a decorated unit-row key. Matches the
106
+ * `fanoutRowStage`/`iterateRowStage` projection (`${parent} (${id ?? label})`,
107
+ * audit.ts:57,69) with an exact `${parent} (` prefix + `)` suffix. The space
108
+ * before `(` disambiguates prefix-name collisions (`"build-extra (x)"` does NOT
109
+ * start with `"build ("`); identifier-style stage names never contain `" ("`,
110
+ * so at most one parent matches. Returns undefined for a non-decorated key.
111
+ */
112
+ export function matchFanoutParent(stageKey: string, parents: ReadonlySet<string>): string | undefined {
113
+ if (!stageKey.endsWith(")")) return undefined;
114
+ for (const parent of parents) {
115
+ if (stageKey.startsWith(`${parent} (`)) return parent;
116
+ }
117
+ return undefined;
118
+ }
119
+
120
+ // ---------------------------------------------------------------------------
121
+ // Reconstruction fold
122
+ // ---------------------------------------------------------------------------
123
+
124
+ /**
125
+ * Rebuild `RunState` by folding over the completed stage rows in a run's
126
+ * JSONL audit trail. Returns a discriminated result so the entry point
127
+ * (`resumeWorkflow`) maps refusals to error envelopes.
128
+ *
129
+ * Rules:
130
+ * - A row whose `stage` is a real `workflow.stages` key → fold as a normal
131
+ * stage (completed rows seed via `applyCompletedStage`; non-completed rows
132
+ * bump counters only). A bare `def.iterate`-parent row is never written by
133
+ * the runner; should one exist it folds harmlessly here (iterate mandates
134
+ * `kind: "produces"`).
135
+ * - A row whose `stage` is NOT a key — a decorated unit row, a renamed
136
+ * stage, or a removed one:
137
+ * - matches a `def.fanout` parent → fold counters-only (mirror the
138
+ * live `recordFanoutSuccess`: bump `stagesCompleted` on a completed
139
+ * row, add parent to `visited`, advance `lastStageNumber`; NO
140
+ * `applyCompletedStage`, NO `state.output` write) + record the
141
+ * completed decorated string under the parent in `fanoutProgress`,
142
+ * resetting that prefix on a new generation (a looped fanout).
143
+ * - matches a `def.iterate` parent → fold as a full produces pass
144
+ * (`foldIterateUnit`): roll the primary, append to `state.named`, set
145
+ * `state.output`, bump counters, and track the trailing generation's
146
+ * `accumulated` + frozen entry artifact in `iterateProgress`.
147
+ * - no match → refuse `stage-gone`.
148
+ */
149
+ export function reconstructState(cwd: string, workflow: Workflow, header: WorkflowHeader): ReconstructResult {
150
+ const rows = readAllStages(cwd, header.runId);
151
+
152
+ if (rows.length === 0) {
153
+ return { ok: false, reason: "no-rows", detail: header.runId };
154
+ }
155
+
156
+ const fanoutNames = fanoutStageNames(workflow);
157
+ const iterateNames = iterateStageNames(workflow);
158
+
159
+ const acc: FoldAcc = {
160
+ state: {
161
+ originalInput: header.input,
162
+ primaryArtifact: undefined,
163
+ output: undefined,
164
+ named: {},
165
+ stagesCompleted: 0,
166
+ lastAllocatedStageNumber: 0,
167
+ telemetry: { backwardJumps: 0, droppedRoutingRows: [] },
168
+ termination: { success: false, error: undefined },
169
+ },
170
+ visited: new Set<string>(),
171
+ fanoutProgress: new Map<string, string[]>(),
172
+ iterateProgress: new Map<string, IterateResumePoint>(),
173
+ lastFoldedUnitParent: undefined,
174
+ lastStageNumber: 0,
175
+ };
176
+
177
+ for (const row of rows) {
178
+ const def = workflow.stages[row.stage];
179
+ const step = def
180
+ ? foldKnownStage(acc, def, row)
181
+ : foldDecoratedRow(acc, workflow, row, fanoutNames, iterateNames);
182
+ if (step.refuse) return { ok: false, reason: step.reason, detail: step.detail };
183
+ }
184
+
185
+ acc.state.lastAllocatedStageNumber = acc.lastStageNumber; // allocator continues monotonically on append
186
+
187
+ return {
188
+ ok: true,
189
+ state: acc.state,
190
+ lastStageNumber: acc.lastStageNumber,
191
+ visited: acc.visited,
192
+ rows,
193
+ fanoutProgress: acc.fanoutProgress,
194
+ iterateProgress: acc.iterateProgress,
195
+ };
196
+ }
197
+
198
+ // ---------------------------------------------------------------------------
199
+ // Per-row fold helpers
200
+ // ---------------------------------------------------------------------------
201
+
202
+ /** Mutable accumulator threaded through the per-row fold. */
203
+ interface FoldAcc {
204
+ state: RunState;
205
+ visited: Set<string>;
206
+ fanoutProgress: Map<string, string[]>;
207
+ iterateProgress: Map<string, IterateResumePoint>;
208
+ /** Parent of the immediately-preceding folded row IF it was a fanout OR iterate unit; else undefined. Drives generation reset for both. */
209
+ lastFoldedUnitParent: string | undefined;
210
+ lastStageNumber: number;
211
+ }
212
+
213
+ /** A folded row either advanced the accumulator (`refuse: false`) or hit an unresumable trail. */
214
+ type FoldStep = { refuse: false } | { refuse: true; reason: "stage-gone"; detail: string };
215
+
216
+ const FOLD_OK: FoldStep = { refuse: false };
217
+ const refuse = (reason: "stage-gone", detail: string): FoldStep => ({
218
+ refuse: true,
219
+ reason,
220
+ detail,
221
+ });
222
+
223
+ /**
224
+ * Fold a row whose `stage` is a real `workflow.stages` key — a normal stage:
225
+ * completed rows seed `state.output` + primary + named via `applyCompletedStage`;
226
+ * non-completed rows bump `visited`/`lastStageNumber` only. A bare (undecorated)
227
+ * iterate-parent or fanout-parent row is never written by the runner; should one
228
+ * exist it folds harmlessly here — iterate mandates `kind: "produces"` so
229
+ * `applyCompletedStage` runs, and fanout rows carry no output so the `!row.output`
230
+ * guard skips it. A real-key row always breaks iterate contiguity (it is not a
231
+ * decorated unit), so the generation cursor resets.
232
+ */
233
+ function foldKnownStage(acc: FoldAcc, def: StageDef, row: WorkflowStage): FoldStep {
234
+ acc.lastFoldedUnitParent = undefined;
235
+ acc.visited.add(row.stage);
236
+ acc.lastStageNumber = Math.max(acc.lastStageNumber, row.stageNumber);
237
+ if (row.status !== "completed") return FOLD_OK;
238
+ acc.state.stagesCompleted++;
239
+ if (!row.output) return FOLD_OK;
240
+ acc.state.output = row.output;
241
+ applyCompletedStage(acc.state, def, row.stage, row.output);
242
+ return FOLD_OK;
243
+ }
244
+
245
+ /**
246
+ * Fold a row whose `stage` is NOT a key — a decorated unit row, a renamed stage,
247
+ * or a removed one. A fanout-parent match folds counters-only; an iterate-parent
248
+ * match folds a full produces pass (`foldIterateUnit`); no match refuses
249
+ * `stage-gone`.
250
+ */
251
+ function foldDecoratedRow(
252
+ acc: FoldAcc,
253
+ workflow: Workflow,
254
+ row: WorkflowStage,
255
+ fanoutNames: ReadonlySet<string>,
256
+ iterateNames: ReadonlySet<string>,
257
+ ): FoldStep {
258
+ const fanoutParent = matchFanoutParent(row.stage, fanoutNames);
259
+ if (fanoutParent) {
260
+ foldFanoutUnit(acc, fanoutParent, row);
261
+ return FOLD_OK;
262
+ }
263
+ const iterateParent = matchFanoutParent(row.stage, iterateNames);
264
+ if (iterateParent) {
265
+ foldIterateUnit(acc, workflow.stages[iterateParent]!, iterateParent, row);
266
+ return FOLD_OK;
267
+ }
268
+ return refuse("stage-gone", row.stage);
269
+ }
270
+
271
+ /**
272
+ * Counters-only fold for one decorated fanout-unit row — mirrors the live
273
+ * `recordFanoutSuccess`: bump `stagesCompleted` on a completed row, add the
274
+ * parent to `visited`, advance `lastStageNumber`; NO `applyCompletedStage`, NO
275
+ * `state.output` write. The completed decorated string is recorded under the
276
+ * parent in `fanoutProgress` (the resume point + determinism-guard input).
277
+ *
278
+ * Generation tracking: a row whose parent differs from the immediately-preceding
279
+ * unit row STARTS a new fanout generation — reset `fanoutProgress[parent]` so a
280
+ * looped fanout's trailing pass overwrites the prior pass's prefix. `stagesCompleted`
281
+ * stays cumulative (it mirrors the live count); only the resume-point array resets.
282
+ * Fanout units never roll the primary, so the reconstructed `state.primaryArtifact`
283
+ * already sits on the trailing generation's entry — no entry-artifact capture (the
284
+ * iterate asymmetry; see resume-iterate.ts).
285
+ */
286
+ function foldFanoutUnit(acc: FoldAcc, parent: string, row: WorkflowStage): void {
287
+ const newGeneration = acc.lastFoldedUnitParent !== parent;
288
+ acc.visited.add(parent);
289
+ acc.lastStageNumber = Math.max(acc.lastStageNumber, row.stageNumber);
290
+ acc.lastFoldedUnitParent = parent;
291
+ // New generation → fresh prefix; same generation → the array already exists (set on its first row).
292
+ if (newGeneration || !acc.fanoutProgress.has(parent)) acc.fanoutProgress.set(parent, []);
293
+ if (row.status !== "completed") return;
294
+ acc.state.stagesCompleted++;
295
+ acc.fanoutProgress.get(parent)!.push(row.stage); // trailing generation only
296
+ }
297
+
298
+ /**
299
+ * Fold one decorated iterate-unit row as a full produces pass (mirrors the live
300
+ * `recordStageSuccess` → `applyCompletedStage`): roll the primary, append to
301
+ * `state.named[outcome.name]`, set `state.output`, bump `stagesCompleted`. The
302
+ * decorated `row.stage` is SAFE for named keying — iterate mandates `outcome.name`,
303
+ * so `resolvePublishName` ignores the decoration (audit.ts:104).
304
+ *
305
+ * Generation tracking: a row whose parent differs from the immediately-preceding
306
+ * iterate row STARTS a new generation — snapshot the (pre-apply) primary as the
307
+ * frozen `entryArtifact` and reset `accumulated`. Contiguous units append. This
308
+ * keeps `iterateProgress` pointed at the TRAILING generation for a corrective loop,
309
+ * while `state.named` accumulates every generation (matching the live run).
310
+ *
311
+ * `visited` records the PARENT (not the decorated key), mirroring the live
312
+ * `advanceChain` visit + `foldFanoutUnit`. The generation cursor is shared with
313
+ * fanout — a fanout parent and an iterate parent are always distinct keys, so a
314
+ * row of the other kind always reads as a new generation here.
315
+ */
316
+ function foldIterateUnit(acc: FoldAcc, def: StageDef, parent: string, row: WorkflowStage): void {
317
+ const newGeneration = acc.lastFoldedUnitParent !== parent;
318
+ let point = acc.iterateProgress.get(parent);
319
+ if (newGeneration || !point) {
320
+ point = { entryArtifact: acc.state.primaryArtifact, accumulated: [] };
321
+ acc.iterateProgress.set(parent, point);
322
+ }
323
+ acc.visited.add(parent);
324
+ acc.lastStageNumber = Math.max(acc.lastStageNumber, row.stageNumber);
325
+ acc.lastFoldedUnitParent = parent;
326
+
327
+ if (row.status !== "completed") return; // failed/aborted/skipped — not accumulated (the unit resume re-runs)
328
+ acc.state.stagesCompleted++;
329
+ if (!row.output) return; // defensive — completed iterate rows always carry output
330
+ acc.state.output = row.output;
331
+ applyCompletedStage(acc.state, def, row.stage, row.output); // rolls primary + pushes named[outcome.name]
332
+ point.accumulated.push(row.output);
333
+ }