@juicesharp/rpiv-workflow 1.19.1 → 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 (136) hide show
  1. package/README.md +81 -8
  2. package/api.ts +18 -703
  3. package/audit-ctx.ts +103 -0
  4. package/audit-rows.ts +154 -0
  5. package/audit.ts +158 -190
  6. package/built-ins.ts +40 -45
  7. package/chain-state.ts +220 -0
  8. package/command-run.ts +64 -31
  9. package/command.ts +123 -21
  10. package/docs/workflow-authoring.md +356 -63
  11. package/{lifecycle.ts → events.ts} +161 -37
  12. package/execution-host.ts +75 -0
  13. package/host.ts +149 -64
  14. package/index.ts +25 -81
  15. package/internal-utils.ts +171 -71
  16. package/internal.ts +22 -1
  17. package/judge.ts +241 -0
  18. package/layers.ts +10 -15
  19. package/load/alias.ts +6 -12
  20. package/load/cache.ts +9 -6
  21. package/load/index.ts +27 -106
  22. package/load/issues.ts +31 -0
  23. package/load/legacy.ts +102 -0
  24. package/load/merge.ts +2 -2
  25. package/load/resolve-default.ts +3 -4
  26. package/load/shape-guards.ts +3 -6
  27. package/load/skill-contract-phase.ts +94 -0
  28. package/loop-constructors.ts +24 -0
  29. package/loop-def.ts +285 -0
  30. package/loop-kinds.ts +750 -0
  31. package/loop-parallel.ts +250 -0
  32. package/loop-waves.ts +99 -0
  33. package/loop.ts +330 -0
  34. package/loops/constructors.ts +334 -0
  35. package/loops/derivations.ts +65 -0
  36. package/loops/introspection.ts +184 -0
  37. package/loops/panel.ts +196 -0
  38. package/loops/verify.ts +99 -0
  39. package/messages.ts +249 -156
  40. package/outcomes/collectors/directory-path.ts +7 -3
  41. package/outcomes/collectors/index.ts +1 -0
  42. package/outcomes/collectors/require-opt.ts +11 -0
  43. package/outcomes/collectors/text-scan.ts +47 -0
  44. package/outcomes/collectors/tool-call.ts +8 -3
  45. package/outcomes/collectors/transcript-path.ts +4 -18
  46. package/outcomes/collectors/union.ts +30 -10
  47. package/outcomes/collectors/url.ts +9 -14
  48. package/outcomes/collectors/workspace-diff.ts +21 -14
  49. package/outcomes/exec.ts +17 -0
  50. package/outcomes/git-commit.ts +190 -100
  51. package/outcomes/index.ts +1 -0
  52. package/outcomes/parsers/json-body.ts +2 -2
  53. package/outcomes/side-effect.ts +3 -3
  54. package/output-spec.ts +36 -10
  55. package/output.ts +98 -20
  56. package/package.json +27 -11
  57. package/predicates.ts +11 -8
  58. package/preview.ts +81 -21
  59. package/registration.ts +117 -36
  60. package/routing-dsl.ts +322 -0
  61. package/routing.ts +48 -2
  62. package/runner/by-name.ts +2 -1
  63. package/runner/by-run-id.ts +2 -1
  64. package/runner/chain-advance.ts +84 -56
  65. package/runner/errors.ts +10 -0
  66. package/runner/failure.ts +163 -0
  67. package/runner/index.ts +7 -13
  68. package/runner/input-validation.ts +16 -23
  69. package/runner/preflight.ts +169 -0
  70. package/runner/resolve-stage.ts +68 -0
  71. package/runner/resume-entry.ts +121 -0
  72. package/runner/resume-loop.ts +131 -0
  73. package/runner/resume.ts +368 -262
  74. package/runner/run-context.ts +165 -0
  75. package/runner/run-stage.ts +490 -0
  76. package/runner/runner.ts +202 -449
  77. package/runner/script-stage.ts +104 -112
  78. package/schema-compat.ts +12 -1
  79. package/semaphore.ts +55 -0
  80. package/sessions/extraction.ts +146 -81
  81. package/sessions/halt-routing.ts +195 -0
  82. package/sessions/index.ts +3 -1
  83. package/sessions/locate.ts +141 -0
  84. package/sessions/reattach.ts +71 -0
  85. package/sessions/sessions.ts +114 -199
  86. package/sessions/spawn.ts +132 -119
  87. package/sessions/success-persist.ts +89 -0
  88. package/skill-contract.ts +22 -25
  89. package/skill-contracts/composition.ts +86 -37
  90. package/skill-contracts/{registries.ts → extension-points.ts} +45 -12
  91. package/skill-contracts/harvest.ts +4 -4
  92. package/skill-contracts/index.ts +15 -8
  93. package/skill-contracts/registry.ts +33 -50
  94. package/stage-def.ts +595 -0
  95. package/stage-errors.ts +84 -0
  96. package/stage-identity.ts +56 -0
  97. package/startup.ts +4 -1
  98. package/state/index.ts +8 -1
  99. package/state/names.ts +91 -65
  100. package/state/paths.ts +20 -0
  101. package/state/raw.ts +77 -0
  102. package/state/reads.ts +103 -85
  103. package/state/resolve.ts +73 -0
  104. package/state/state.ts +135 -15
  105. package/state/writes.ts +29 -12
  106. package/transcript.ts +24 -0
  107. package/triggers.ts +11 -3
  108. package/types.ts +290 -78
  109. package/validate/contract-compat.ts +198 -0
  110. package/validate/graph.ts +134 -0
  111. package/validate/issue.ts +328 -0
  112. package/validate/stage-rules.ts +499 -0
  113. package/validate-output.ts +82 -7
  114. package/validate-workflow.ts +57 -759
  115. package/validation-bounds.ts +35 -0
  116. package/control-flow.ts +0 -135
  117. package/fanout.ts +0 -102
  118. package/iterate.ts +0 -155
  119. package/load/cache.test.ts +0 -82
  120. package/load/shape-guards.test.ts +0 -74
  121. package/outcomes/collectors/directory-path.test.ts +0 -64
  122. package/outcomes/collectors/tool-call.test.ts +0 -110
  123. package/outcomes/collectors/transcript-path.test.ts +0 -70
  124. package/outcomes/collectors/union.test.ts +0 -59
  125. package/outcomes/collectors/url.test.ts +0 -67
  126. package/outcomes/collectors/workspace-diff.test.ts +0 -107
  127. package/outcomes/git-commit.test.ts +0 -194
  128. package/outcomes/parsers/json-body.test.ts +0 -80
  129. package/runner/by-name.test.ts +0 -95
  130. package/runner/by-run-id.test.ts +0 -115
  131. package/runner/resume-fanout.test.ts +0 -331
  132. package/runner/resume-fanout.ts +0 -136
  133. package/runner/resume-iterate.test.ts +0 -444
  134. package/runner/resume-iterate.ts +0 -111
  135. package/runner/resume.test.ts +0 -1130
  136. package/runner/stage-lifecycle.ts +0 -500
package/runner/resume.ts CHANGED
@@ -1,333 +1,439 @@
1
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`.
2
+ * State reconstruction for resuming a run. ONE async fold over the JSONL
3
+ * trail: rows with `parent` set are loop-unit rows (the structured machine
4
+ * channel — the decorated `stage` string is never parsed); everything else
5
+ * folds as a normal stage.
4
6
  *
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*.
7
+ * THE REPLAY CONTRACT: a loop's unit source must be deterministic w.r.t. the
8
+ * fold-replayed `RunState` at the unit boundary + this generation's
9
+ * accumulated outputs. Because the fold replays rows in trail order, at row
10
+ * *i* the state is byte-identical to what the live driver saw — so the fold
11
+ * verifies EVERY unit row against the recomputed expectation. Drift (or a
12
+ * generator
13
+ * throw) does not refuse outright: the fold finishes applying so state is
14
+ * complete, and returns `drift` — `resumeWorkflow`'s entry thunk records the
15
+ * terminal failure with full lifecycle bracketing and zero dispatch.
9
16
  *
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).
17
+ * Generations: contiguous unit rows sharing a `parent`. A generation opens by
18
+ * freezing the entry pair from the replayed state (and, for fanout,
19
+ * recomputing the unit list ONCE against it); it closes when a non-unit row
20
+ * (or a different parent) appears — `projectResult` (the driver's own
21
+ * function) lands the declared result, exactly like the live loop advance.
22
+ * The TRAILING open generation is returned un-projected as a
23
+ * `LoopResumePoint` whose `cursor` is the driver's own `LoopCursor` —
24
+ * re-entry hands it straight back to `runLoop`.
25
25
  */
26
26
 
27
- import type { StageDef, Workflow } from "../api.js";
27
+ import type { LoopDef, StageDef, Unit, Workflow } from "../api.js";
28
+ import { applyStageSuccess, rollLastSession } from "../audit-rows.js";
29
+ import { stageEntryArgs } from "../chain-state.js";
28
30
  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";
31
+ import { formatError } from "../internal-utils.js";
32
+ import { panelMembers } from "../judge.js";
33
+ import { projectResult, publishPanelVerdict } from "../loop.js";
34
+ import { effectiveLoopOf, freezesEntryArgsOf } from "../loop-constructors.js";
35
+ import {
36
+ advanceCursor,
37
+ foldFanoutCompletion,
38
+ freshCursor,
39
+ judgeStageDef,
40
+ type LoopCursor,
41
+ sequentialStrategyOf,
42
+ unitTagOf,
43
+ } from "../loop-kinds.js";
44
+ import { ERR_RESUME_LOOP_MISMATCH } from "../messages.js";
45
+ import { failedOutput, type Output, outputMeta } from "../output.js";
46
+ import {
47
+ readAllStagesForResume,
48
+ STATE_SCHEMA_VERSION,
49
+ type WorkflowHeader,
50
+ type WorkflowStage,
51
+ } from "../state/index.js";
33
52
  import type { RunState } from "../types.js";
53
+ import { freshRunState } from "./run-context.js";
34
54
 
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 {
55
+ /** Trailing open generation — everything `resume-loop.ts` needs to re-enter `runLoop`. */
56
+ export interface LoopResumePoint {
57
+ parent: string;
65
58
  entryArtifact: Artifact | undefined;
66
- accumulated: Output[];
59
+ entryPair: { output: Output | undefined; primaryArtifact: Artifact | undefined };
60
+ /**
61
+ * Round-0 producer arg, FROZEN at generation open (assess-kind loops only;
62
+ * `""` otherwise). `undefined` = the trail no longer carries the rows that
63
+ * published this stage's inputs (truncated/corrupted) — re-entry records a
64
+ * refusal instead of dispatching with a wrong arg.
65
+ */
66
+ entryArgs: string | undefined;
67
+ /** The driver's own cursor, reconstructed: next (role, index), accumulated, lastProduce, lastVerdict. */
68
+ cursor: LoopCursor;
69
+ /** Fanout: the recomputed-and-verified unit list (re-entry reuses it — no second compute). */
70
+ units?: readonly Unit[];
67
71
  }
68
- export type IterateProgress = ReadonlyMap<string, IterateResumePoint>;
69
72
 
70
73
  export type ReconstructResult =
71
74
  | {
72
75
  ok: true;
73
76
  state: RunState;
74
77
  lastStageNumber: number;
78
+ /**
79
+ * 0-based chain index of the trail's LAST activation — the fold's
80
+ * reconstruction of the `idx` the live chain was at (one activation per
81
+ * top-level stage row or loop generation; a resume re-run of a failed
82
+ * stage keeps its index). NOT `stageNumber - 1`: the allocator counts
83
+ * every row including loop units, so the two diverge past any loop.
84
+ */
85
+ lastChainIndex: number;
75
86
  visited: Set<string>;
76
87
  rows: WorkflowStage[];
77
- fanoutProgress: FanoutProgress;
78
- iterateProgress: IterateProgress;
88
+ /** Open generation at trail end, un-projected (the driver projects at its advance). */
89
+ trailing?: LoopResumePoint;
90
+ /** Guard tripped mid-fold — the resume entry records this as a terminal failure. */
91
+ drift?: { parent: string; errMsg: string };
79
92
  }
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
- }
93
+ | { ok: false; reason: "no-rows" | "stage-gone" | "malformed-row" | "version-mismatch"; detail: string };
103
94
 
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 };
95
+ export async function reconstructState(
96
+ cwd: string,
97
+ workflow: Workflow,
98
+ header: WorkflowHeader,
99
+ ): Promise<ReconstructResult> {
100
+ // Version gate first: the fold replays rows under the CURRENT shapes, so a
101
+ // file written under a different schema version must refuse cleanly rather
102
+ // than mis-replay. Absent `v` = version 1 (pre-field files) — see
103
+ // STATE_SCHEMA_VERSION's back-compat rule.
104
+ const v = header.v ?? 1;
105
+ if (v !== STATE_SCHEMA_VERSION) {
106
+ return { ok: false, reason: "version-mismatch", detail: `run ${header.runId} was written under schema v${v}` };
154
107
  }
155
-
156
- const fanoutNames = fanoutStageNames(workflow);
157
- const iterateNames = iterateStageNames(workflow);
108
+ // Strict reader: a stage-shaped row failing the deep guard REFUSES here —
109
+ // the fold replays the trail as its system of record, so a silently
110
+ // skipped row would replay a hole and route onward past it.
111
+ const read = readAllStagesForResume(cwd, header.runId);
112
+ if (!read.ok) return { ok: false, reason: "malformed-row", detail: read.detail };
113
+ const rows = read.rows;
114
+ if (rows.length === 0) return { ok: false, reason: "no-rows", detail: header.runId };
158
115
 
159
116
  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
- },
117
+ cwd,
118
+ runId: header.runId,
119
+ state: freshRunState(header.input),
170
120
  visited: new Set<string>(),
171
- fanoutProgress: new Map<string, string[]>(),
172
- iterateProgress: new Map<string, IterateResumePoint>(),
173
- lastFoldedUnitParent: undefined,
174
121
  lastStageNumber: 0,
122
+ chainIndex: -1,
123
+ prevNode: undefined,
124
+ gen: undefined,
125
+ drift: undefined,
175
126
  };
176
127
 
177
128
  for (const row of rows) {
129
+ if (row.parent !== undefined) {
130
+ const refusal = await foldUnitRow(acc, workflow, row);
131
+ if (refusal) return refusal;
132
+ continue;
133
+ }
134
+ // A non-completed, parent-unset row for the SAME stage as the open FANOUT
135
+ // generation is that generation's own halt marker: a mid-flight abort
136
+ // writes a stage-level `aborted` row (recordAbortedAtSeam) AFTER the
137
+ // completed unit rows. Closing the generation on it would discard the
138
+ // reconstructed cursor whose completed-unit slots are already filled,
139
+ // forcing resume to cold-re-enter the loop and re-dispatch EVERY unit
140
+ // (finding 7: the aborted-mid-flight fanout re-ran completed units,
141
+ // duplicating the channel and collapsing the downstream fan-in). Keep the
142
+ // generation open — `trailing` then carries the filled slots and
143
+ // `pendingFanoutIndices` dispatches only the genuinely-pending units. A
144
+ // COMPLETED parent row still closes+advances; a stage with no completed
145
+ // units never opened a generation, so it falls through and re-runs whole.
146
+ if (acc.gen?.parent === row.stage && acc.gen.loop.kind === "fanout" && row.status !== "completed") {
147
+ acc.visited.add(row.stage);
148
+ acc.lastStageNumber = Math.max(acc.lastStageNumber, row.stageNumber);
149
+ continue;
150
+ }
151
+ closeGeneration(acc);
178
152
  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 };
153
+ // Unknown key refuses — including LEGACY decorated rows (older
154
+ // runs carry no `parent`, so their unit rows land here): stage-gone.
155
+ if (!def) return { ok: false, reason: "stage-gone", detail: row.stage };
156
+ noteChainNode(acc, row.stage, row.status !== "completed");
157
+ foldKnownStage(acc, def, row);
183
158
  }
184
159
 
185
- acc.state.lastAllocatedStageNumber = acc.lastStageNumber; // allocator continues monotonically on append
160
+ acc.state.lastAllocatedStageNumber = acc.lastStageNumber; // allocator continues monotonically
186
161
 
187
162
  return {
188
163
  ok: true,
189
164
  state: acc.state,
190
165
  lastStageNumber: acc.lastStageNumber,
166
+ lastChainIndex: acc.chainIndex,
191
167
  visited: acc.visited,
192
168
  rows,
193
- fanoutProgress: acc.fanoutProgress,
194
- iterateProgress: acc.iterateProgress,
169
+ trailing: acc.gen ? toPoint(acc.gen) : undefined,
170
+ drift: acc.drift,
195
171
  };
196
172
  }
197
173
 
198
174
  // ---------------------------------------------------------------------------
199
- // Per-row fold helpers
175
+ // Fold internals
200
176
  // ---------------------------------------------------------------------------
201
177
 
202
- /** Mutable accumulator threaded through the per-row fold. */
178
+ interface OpenGeneration {
179
+ parent: string;
180
+ loop: LoopDef;
181
+ /** Parent stage def — produce-row apply (judge rows apply via judgeStageDef). */
182
+ def: StageDef;
183
+ entryArtifact: Artifact | undefined;
184
+ entryPair: { output: Output | undefined; primaryArtifact: Artifact | undefined };
185
+ /** Frozen at generation open — see LoopResumePoint.entryArgs. */
186
+ entryArgs: string | undefined;
187
+ cursor: LoopCursor;
188
+ units?: readonly Unit[];
189
+ /**
190
+ * Cached expected unit for the cursor's CURRENT index (iterate pulls once
191
+ * per index — a failed row followed by its resumed re-run row re-checks
192
+ * the same expectation without double-pulling the generator).
193
+ */
194
+ expected?: { index: number; tag: string | undefined };
195
+ }
196
+
203
197
  interface FoldAcc {
198
+ cwd: string;
199
+ /** Header runId — the rebuilt `failedOutput` sentinel's meta.runId,
200
+ * byte-identical to the live `outputMetaFor`'s `s.runId`. RunState carries no id. */
201
+ runId: string;
204
202
  state: RunState;
205
203
  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
204
  lastStageNumber: number;
205
+ /** 0-based index of the current activation — see `ReconstructResult.lastChainIndex`. */
206
+ chainIndex: number;
207
+ /**
208
+ * Last chain-node activation. `reentrant` = a following row of the SAME
209
+ * stage continues this activation instead of opening a new one: a
210
+ * failed/aborted/skipped row (resume re-runs it at the same index) or a
211
+ * loop generation (its halt row and any resume re-entry belong to it).
212
+ */
213
+ prevNode: { stage: string; reentrant: boolean } | undefined;
214
+ gen: OpenGeneration | undefined;
215
+ drift: { parent: string; errMsg: string } | undefined;
211
216
  }
212
217
 
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
- });
218
+ /** Advance the chain index for one activation — unless the row continues the previous one. */
219
+ function noteChainNode(acc: FoldAcc, stage: string, reentrant: boolean): void {
220
+ if (!(acc.prevNode?.stage === stage && acc.prevNode.reentrant)) acc.chainIndex++;
221
+ acc.prevNode = { stage, reentrant };
222
+ }
222
223
 
223
224
  /**
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.
225
+ * Normal-stage fold. A completed row replays through `applyStageSuccess` —
226
+ * the same apply the live success persistence runs, minus the I/O (the row
227
+ * is already on disk).
232
228
  */
233
- function foldKnownStage(acc: FoldAcc, def: StageDef, row: WorkflowStage): FoldStep {
234
- acc.lastFoldedUnitParent = undefined;
229
+ function foldKnownStage(acc: FoldAcc, def: StageDef, row: WorkflowStage): void {
235
230
  acc.visited.add(row.stage);
236
231
  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;
232
+ if (row.status !== "completed") return;
233
+ applyStageSuccess(acc.state, def, row.stage, row.output);
234
+ // Roll the predecessor session forward through the SAME authority the live
235
+ // `recordStageSuccess` single-stage branch uses (`rollLastSession`) — so a
236
+ // post-resume cold dispatch of a `continue` stage forks the same predecessor
237
+ // the live run would have, and the null-handling can't drift. Single-stage
238
+ // rows only (unit rows fold via `foldUnitRow`, which never touches this slot).
239
+ rollLastSession(acc.state, row.session);
243
240
  }
244
241
 
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(
242
+ /** Close the open generation: project the declared result — the live loop-advance, replayed. */
243
+ function closeGeneration(acc: FoldAcc): void {
244
+ if (!acc.gen) return;
245
+ projectResult(acc.gen.loop, acc.gen.entryPair, acc.gen.cursor, acc.state);
246
+ acc.gen = undefined;
247
+ }
248
+
249
+ async function foldUnitRow(
252
250
  acc: FoldAcc,
253
251
  workflow: Workflow,
254
252
  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;
253
+ ): Promise<Extract<ReconstructResult, { ok: false }> | undefined> {
254
+ // New generation: different parent (or first unit row / after a non-unit row).
255
+ if (!acc.gen || acc.gen.parent !== row.parent) {
256
+ closeGeneration(acc);
257
+ const def = workflow.stages[row.parent!];
258
+ // `effectiveLoopOf` — a verify stage's unit rows recover their synthesized
259
+ // loop here; without it every verify-stage trailer would refuse stage-gone.
260
+ const loop = def ? effectiveLoopOf(def) : undefined;
261
+ if (!def || !loop) return { ok: false, reason: "stage-gone", detail: row.stage };
262
+ // One generation = one chain-node activation. Always reentrant: a halt
263
+ // row for the parent or a resumed re-entry continues this activation.
264
+ noteChainNode(acc, row.parent!, true);
265
+ acc.gen = {
266
+ parent: row.parent!,
267
+ loop,
268
+ def,
269
+ entryArtifact: acc.state.primaryArtifact,
270
+ entryPair: { output: acc.state.output, primaryArtifact: acc.state.primaryArtifact },
271
+ // Frozen HERE: replayed state at generation open is byte-identical to
272
+ // what the live driver saw at loop entry (THE REPLAY CONTRACT) — the
273
+ // only safe place to derive the round-0 arg. `reads` projections in
274
+ // particular must NOT be re-derived post-fold, where the generation's
275
+ // own appends have moved the `.at(-1)` cursors.
276
+ entryArgs: freezesEntryArgsOf(loop) ? stageEntryArgs(def, row.parent!, workflow.start, acc.state) : "",
277
+ cursor: freshCursor(),
278
+ units: undefined,
279
+ };
280
+ if (loop.kind === "fanout") {
281
+ acc.gen.units = await guarded(acc, acc.gen.parent, () =>
282
+ (loop as Extract<LoopDef, { kind: "fanout" }>).units({
283
+ cwd: acc.cwd,
284
+ artifact: acc.state.primaryArtifact,
285
+ state: acc.state,
286
+ }),
287
+ );
288
+ }
289
+ }
290
+
291
+ const gen = acc.gen;
292
+ acc.visited.add(gen.parent);
293
+ acc.lastStageNumber = Math.max(acc.lastStageNumber, row.stageNumber);
294
+
295
+ if (!acc.drift) await guardRow(acc, gen, row);
296
+
297
+ // Fanout: place-by-`unitIndex` (NOT trail order) so declared order survives a
298
+ // completion-ordered / out-of-order trail. A slot is FILLED — and so NOT
299
+ // re-dispatched on resume — only when the row is a COMPLETED unit or a
300
+ // COLLECTED soft-halt:
301
+ // • completed → `applyStageSuccess` (bookkeeping + state.output, mirroring the
302
+ // live `recordStageSuccess`) THEN the channel-owning `foldFanoutCompletion`;
303
+ // • collected (`status:"failed"` + `collected:true`) → rebuild the `failedOutput`
304
+ // sentinel from `errMsg` and place it via `foldFanoutCompletion` ONLY (the live
305
+ // `softHaltUnit` runs no `applyStageSuccess` — the fold owns the single channel
306
+ // write). The rebuilt meta is byte-identical to the live sentinel's (see
307
+ // `outputMetaFor`): decorated `row.stage`, `row.skill`, `row.stageNumber`.
308
+ // A hard `status:"failed"` row (no `collected`) or a genuinely pending row — and
309
+ // an aborted in-flight unit, which wrote NO row at all — leaves the slot
310
+ // unfilled so resume re-dispatches that unit. `gen.units` is absent only when the
311
+ // units generator threw at open (already drift); fall through to the produce arm's
312
+ // `advanceCursor` so the refused fold still applies bookkeeping.
313
+ if (gen.loop.kind === "fanout" && gen.units) {
314
+ if (row.status === "completed" && row.output) {
315
+ applyStageSuccess(acc.state, gen.def, row.stage, row.output);
316
+ foldFanoutCompletion(acc.state, gen.cursor, gen.def, gen.parent, row.unitIndex!, gen.units.length, row.output);
317
+ } else if (row.collected && row.errMsg !== undefined) {
318
+ const sentinel = failedOutput(
319
+ outputMeta({
320
+ stage: row.stage,
321
+ skill: row.skill,
322
+ stageNumber: row.stageNumber,
323
+ ts: row.ts,
324
+ runId: acc.runId,
325
+ }),
326
+ row.errMsg,
327
+ );
328
+ foldFanoutCompletion(acc.state, gen.cursor, gen.def, gen.parent, row.unitIndex!, gen.units.length, sentinel);
329
+ }
330
+ gen.expected = undefined; // consumed
331
+ return undefined; // pending / hard-failed slots stay unfilled — resume re-dispatches them
262
332
  }
263
- const iterateParent = matchFanoutParent(row.stage, iterateNames);
264
- if (iterateParent) {
265
- foldIterateUnit(acc, workflow.stages[iterateParent]!, iterateParent, row);
266
- return FOLD_OK;
333
+
334
+ if (row.status !== "completed") return undefined; // pending unit — cursor stays (resume re-runs it)
335
+
336
+ if (row.role === "judge" || row.role === "verify") {
337
+ // Apply-then-project: each member verdict rolls the pair TRANSIENTLY
338
+ // (exactly like the live judge unit); projection at generation close
339
+ // restores. The member this row graded is the one the rebuilt sub-state
340
+ // currently points at — `cursor.panel.memberIndex` BEFORE `advanceCursor`
341
+ // bumps it (0 for a single judge, the panel of one). Using that member's
342
+ // own def publishes the verdict to the member's OWN channel, matching the
343
+ // live session path (`judgeStageDef(member)`) per member — `[0]` for every
344
+ // member would have mis-filed members 1..N-1 onto member 0's channel.
345
+ const judgeSlot = (gen.loop as Extract<LoopDef, { kind: "assess" }>).judge;
346
+ const memberIndex = gen.cursor.panel?.memberIndex ?? 0;
347
+ applyStageSuccess(acc.state, judgeStageDef(panelMembers(judgeSlot)[memberIndex]!), row.stage, row.output);
348
+ const role = row.role; // narrowed to "judge" | "verify" — captured for the closure below
349
+ const verdict = row.output;
350
+ if (!verdict) return undefined; // defensive — completed unit rows always carry output
351
+ // `guardRow` already verified `row.unitIndex === cursor.index` (drift
352
+ // otherwise), so the shared transition lands the same cursor the live
353
+ // driver had — and, on the last member, the same folded verdict.
354
+ //
355
+ // `advanceCursor` runs the author fold on the LAST member (`panel.fold`,
356
+ // which a sugar fold's per-member `pred` reaches too), and
357
+ // `publishPanelVerdict` lands it — BOTH behind `guarded()`. A fold/pred
358
+ // throw must become drift (a recorded terminal failure), NOT an unguarded
359
+ // rejection: this fold runs in `reconstructState`, which `resumeWorkflow`
360
+ // awaits BEFORE `executeRun` brackets the lifecycle — an escape here yields
361
+ // no JSONL failure row and no `onWorkflowEnd`. The live driver's same
362
+ // `advanceCursor`+`publishPanelVerdict` pair runs under
363
+ // `runStageOrRecordFailure`'s catch (loop.ts `dispatchUnit`); this is its
364
+ // resume-side error boundary.
365
+ await guarded(acc, gen.parent, () => {
366
+ advanceCursor(gen.cursor, role, verdict, gen.loop);
367
+ // Panel-close publish — the SAME call the live driver makes after the
368
+ // last member's advance, so the folded verdict lands byte-identically.
369
+ publishPanelVerdict(gen.loop, gen.parent, gen.cursor, acc.state);
370
+ });
371
+ return undefined;
267
372
  }
268
- return refuse("stage-gone", row.stage);
373
+
374
+ // produce row — iterate units and assess producers (fanout is placed by index
375
+ // above; a fanout row only reaches here when `gen.units` is absent because the
376
+ // units generator threw at open — already drift — so `advanceCursor` keeps the
377
+ // refused fold applying bookkeeping without a `length`-of-undefined).
378
+ applyStageSuccess(acc.state, gen.def, row.stage, row.output);
379
+ if (!row.output) return undefined; // defensive — completed unit rows always carry output
380
+ advanceCursor(gen.cursor, "produce", row.output, gen.loop);
381
+ gen.expected = undefined; // consumed
382
+ return undefined;
269
383
  }
270
384
 
271
385
  /**
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).
386
+ * The full-row determinism guard — every unit row is checked against the
387
+ * recomputed expectation at its boundary (the replayed state IS what the live
388
+ * driver saw). The kind-agnostic (role, unitIndex) arithmetic lives here; the
389
+ * per-kind re-check delegates to the strategy table (loop-kinds.ts). Drift
390
+ * marks `acc.drift` and stops guarding; applying continues so the failure can
391
+ * be recorded against complete state.
285
392
  */
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
393
+ async function guardRow(acc: FoldAcc, gen: OpenGeneration, row: WorkflowStage): Promise<void> {
394
+ // Fanout no longer asserts trail order: parallel completion + resume re-dispatch
395
+ // produce out-of-order trails, and the fanout cursor tracks `filledCount` (a
396
+ // count, not a trail position), so a sequential `unitIndex === cursor.index`
397
+ // check would falsely drift. The `unitId` is a PLACEMENT key — verify it
398
+ // identifies the unit declared at `row.unitIndex`.
399
+ if (gen.loop.kind === "fanout") {
400
+ const i = row.unitIndex ?? -1;
401
+ const ok = i >= 0 && i < (gen.units?.length ?? 0) && unitTagOf(gen.units![i]!) === row.unitId;
402
+ if (!ok) setDrift(acc, gen.parent);
403
+ return;
404
+ }
405
+ const judgeRole = gen.def.verify ? "verify" : "judge";
406
+ const expectRole = gen.loop.kind === "assess" ? (gen.cursor.phase === "judge" ? judgeRole : "produce") : "produce";
407
+ if (row.role !== expectRole || row.unitIndex !== gen.cursor.index) return setDrift(acc, gen.parent);
408
+
409
+ const matches = await guarded(acc, gen.parent, () =>
410
+ sequentialStrategyOf(gen.loop.kind).guardExpectation(gen, row, acc.cwd, acc.state),
411
+ );
412
+ if (acc.drift) return;
413
+ if (!matches) setDrift(acc, gen.parent);
296
414
  }
297
415
 
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);
416
+ function setDrift(acc: FoldAcc, parent: string): void {
417
+ acc.drift = { parent, errMsg: ERR_RESUME_LOOP_MISMATCH(parent) };
418
+ }
419
+
420
+ /** Run a user fn during the fold; a throw becomes drift with the thrown reason. */
421
+ async function guarded<T>(acc: FoldAcc, parent: string, fn: () => T | Promise<T>): Promise<T | undefined> {
422
+ try {
423
+ return await fn();
424
+ } catch (e) {
425
+ acc.drift = { parent, errMsg: formatError(e) };
426
+ return undefined;
322
427
  }
323
- acc.visited.add(parent);
324
- acc.lastStageNumber = Math.max(acc.lastStageNumber, row.stageNumber);
325
- acc.lastFoldedUnitParent = parent;
428
+ }
326
429
 
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);
430
+ function toPoint(gen: OpenGeneration): LoopResumePoint {
431
+ return {
432
+ parent: gen.parent,
433
+ entryArtifact: gen.entryArtifact,
434
+ entryPair: gen.entryPair,
435
+ entryArgs: gen.entryArgs,
436
+ cursor: gen.cursor,
437
+ units: gen.units,
438
+ };
333
439
  }