@juicesharp/rpiv-workflow 1.19.1 → 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
package/runner/resume.ts CHANGED
@@ -1,333 +1,353 @@
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 (strictly
12
+ * stronger than the old per-primitive half-guards). Drift (or a 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 } 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";
31
+ import { formatError } from "../internal-utils.js";
32
+ import { panelMembers } from "../judge.js";
33
+ import { projectResult, publishPanelVerdict } from "../loop.js";
34
+ import { effectiveLoopOf } from "../loop-constructors.js";
35
+ import { advanceCursor, freshCursor, judgeStageDef, type LoopCursor, loopStrategyOf } from "../loop-kinds.js";
36
+ import { ERR_RESUME_LOOP_MISMATCH } from "../messages.js";
30
37
  import type { Output } from "../output.js";
31
- import { readAllStages } from "../state/index.js";
32
- import type { WorkflowHeader, WorkflowStage } from "../state/state.js";
38
+ import {
39
+ readAllStagesForResume,
40
+ STATE_SCHEMA_VERSION,
41
+ type WorkflowHeader,
42
+ type WorkflowStage,
43
+ } from "../state/index.js";
33
44
  import type { RunState } from "../types.js";
45
+ import { freshRunState } from "./run-context.js";
34
46
 
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 {
47
+ /** Trailing open generation — everything `resume-loop.ts` needs to re-enter `runLoop`. */
48
+ export interface LoopResumePoint {
49
+ parent: string;
65
50
  entryArtifact: Artifact | undefined;
66
- accumulated: Output[];
51
+ entryPair: { output: Output | undefined; primaryArtifact: Artifact | undefined };
52
+ /**
53
+ * Round-0 producer arg, FROZEN at generation open (assess-kind loops only;
54
+ * `""` otherwise). `undefined` = the trail no longer carries the rows that
55
+ * published this stage's inputs (truncated/corrupted) — re-entry records a
56
+ * refusal instead of dispatching with a wrong arg.
57
+ */
58
+ entryArgs: string | undefined;
59
+ /** The driver's own cursor, reconstructed: next (role, index), accumulated, lastProduce, lastVerdict. */
60
+ cursor: LoopCursor;
61
+ /** Fanout: the recomputed-and-verified unit list (re-entry reuses it — no second compute). */
62
+ units?: readonly Unit[];
67
63
  }
68
- export type IterateProgress = ReadonlyMap<string, IterateResumePoint>;
69
64
 
70
65
  export type ReconstructResult =
71
66
  | {
72
67
  ok: true;
73
68
  state: RunState;
74
69
  lastStageNumber: number;
70
+ /**
71
+ * 0-based chain index of the trail's LAST activation — the fold's
72
+ * reconstruction of the `idx` the live chain was at (one activation per
73
+ * top-level stage row or loop generation; a resume re-run of a failed
74
+ * stage keeps its index). NOT `stageNumber - 1`: the allocator counts
75
+ * every row including loop units, so the two diverge past any loop.
76
+ */
77
+ lastChainIndex: number;
75
78
  visited: Set<string>;
76
79
  rows: WorkflowStage[];
77
- fanoutProgress: FanoutProgress;
78
- iterateProgress: IterateProgress;
80
+ /** Open generation at trail end, un-projected (the driver projects at its advance). */
81
+ trailing?: LoopResumePoint;
82
+ /** Guard tripped mid-fold — the resume entry records this as a terminal failure. */
83
+ drift?: { parent: string; errMsg: string };
79
84
  }
80
- | { ok: false; reason: "no-rows" | "stage-gone"; detail: string };
81
-
82
- // ---------------------------------------------------------------------------
83
- // Fanout-decoration helpers (shared with resumeWorkflow dispatch)
84
- // ---------------------------------------------------------------------------
85
+ | { ok: false; reason: "no-rows" | "stage-gone" | "malformed-row" | "version-mismatch"; detail: string };
85
86
 
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 };
87
+ export async function reconstructState(
88
+ cwd: string,
89
+ workflow: Workflow,
90
+ header: WorkflowHeader,
91
+ ): Promise<ReconstructResult> {
92
+ // Version gate first: the fold replays rows under the CURRENT shapes, so a
93
+ // file written under a different schema version must refuse cleanly rather
94
+ // than mis-replay. Absent `v` = version 1 (pre-field files) — see
95
+ // STATE_SCHEMA_VERSION's back-compat rule.
96
+ const v = header.v ?? 1;
97
+ if (v !== STATE_SCHEMA_VERSION) {
98
+ return { ok: false, reason: "version-mismatch", detail: `run ${header.runId} was written under schema v${v}` };
154
99
  }
155
-
156
- const fanoutNames = fanoutStageNames(workflow);
157
- const iterateNames = iterateStageNames(workflow);
100
+ // Strict reader: a stage-shaped row failing the deep guard REFUSES here —
101
+ // the fold replays the trail as its system of record, so a silently
102
+ // skipped row would replay a hole and route onward past it.
103
+ const read = readAllStagesForResume(cwd, header.runId);
104
+ if (!read.ok) return { ok: false, reason: "malformed-row", detail: read.detail };
105
+ const rows = read.rows;
106
+ if (rows.length === 0) return { ok: false, reason: "no-rows", detail: header.runId };
158
107
 
159
108
  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
- },
109
+ cwd,
110
+ state: freshRunState(header.input),
170
111
  visited: new Set<string>(),
171
- fanoutProgress: new Map<string, string[]>(),
172
- iterateProgress: new Map<string, IterateResumePoint>(),
173
- lastFoldedUnitParent: undefined,
174
112
  lastStageNumber: 0,
113
+ chainIndex: -1,
114
+ prevNode: undefined,
115
+ gen: undefined,
116
+ drift: undefined,
175
117
  };
176
118
 
177
119
  for (const row of rows) {
120
+ if (row.parent !== undefined) {
121
+ const refusal = await foldUnitRow(acc, workflow, row);
122
+ if (refusal) return refusal;
123
+ continue;
124
+ }
125
+ closeGeneration(acc);
178
126
  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 };
127
+ // Unknown key refuses — including LEGACY decorated rows (pre-redesign
128
+ // runs carry no `parent`, so their unit rows land here): stage-gone.
129
+ if (!def) return { ok: false, reason: "stage-gone", detail: row.stage };
130
+ noteChainNode(acc, row.stage, row.status !== "completed");
131
+ foldKnownStage(acc, def, row);
183
132
  }
184
133
 
185
- acc.state.lastAllocatedStageNumber = acc.lastStageNumber; // allocator continues monotonically on append
134
+ acc.state.lastAllocatedStageNumber = acc.lastStageNumber; // allocator continues monotonically
186
135
 
187
136
  return {
188
137
  ok: true,
189
138
  state: acc.state,
190
139
  lastStageNumber: acc.lastStageNumber,
140
+ lastChainIndex: acc.chainIndex,
191
141
  visited: acc.visited,
192
142
  rows,
193
- fanoutProgress: acc.fanoutProgress,
194
- iterateProgress: acc.iterateProgress,
143
+ trailing: acc.gen ? toPoint(acc.gen) : undefined,
144
+ drift: acc.drift,
195
145
  };
196
146
  }
197
147
 
198
148
  // ---------------------------------------------------------------------------
199
- // Per-row fold helpers
149
+ // Fold internals
200
150
  // ---------------------------------------------------------------------------
201
151
 
202
- /** Mutable accumulator threaded through the per-row fold. */
152
+ interface OpenGeneration {
153
+ parent: string;
154
+ loop: LoopDef;
155
+ /** Parent stage def — produce-row apply (judge rows apply via judgeStageDef). */
156
+ def: StageDef;
157
+ entryArtifact: Artifact | undefined;
158
+ entryPair: { output: Output | undefined; primaryArtifact: Artifact | undefined };
159
+ /** Frozen at generation open — see LoopResumePoint.entryArgs. */
160
+ entryArgs: string | undefined;
161
+ cursor: LoopCursor;
162
+ units?: readonly Unit[];
163
+ /**
164
+ * Cached expected unit for the cursor's CURRENT index (iterate pulls once
165
+ * per index — a failed row followed by its resumed re-run row re-checks
166
+ * the same expectation without double-pulling the generator).
167
+ */
168
+ expected?: { index: number; tag: string | undefined };
169
+ }
170
+
203
171
  interface FoldAcc {
172
+ cwd: string;
204
173
  state: RunState;
205
174
  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
175
  lastStageNumber: number;
176
+ /** 0-based index of the current activation — see `ReconstructResult.lastChainIndex`. */
177
+ chainIndex: number;
178
+ /**
179
+ * Last chain-node activation. `reentrant` = a following row of the SAME
180
+ * stage continues this activation instead of opening a new one: a
181
+ * failed/aborted/skipped row (resume re-runs it at the same index) or a
182
+ * loop generation (its halt row and any resume re-entry belong to it).
183
+ */
184
+ prevNode: { stage: string; reentrant: boolean } | undefined;
185
+ gen: OpenGeneration | undefined;
186
+ drift: { parent: string; errMsg: string } | undefined;
211
187
  }
212
188
 
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
- });
189
+ /** Advance the chain index for one activation — unless the row continues the previous one. */
190
+ function noteChainNode(acc: FoldAcc, stage: string, reentrant: boolean): void {
191
+ if (!(acc.prevNode?.stage === stage && acc.prevNode.reentrant)) acc.chainIndex++;
192
+ acc.prevNode = { stage, reentrant };
193
+ }
222
194
 
223
195
  /**
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.
196
+ * Normal-stage fold. A completed row replays through `applyStageSuccess` —
197
+ * the same apply the live success persistence runs, minus the I/O (the row
198
+ * is already on disk).
232
199
  */
233
- function foldKnownStage(acc: FoldAcc, def: StageDef, row: WorkflowStage): FoldStep {
234
- acc.lastFoldedUnitParent = undefined;
200
+ function foldKnownStage(acc: FoldAcc, def: StageDef, row: WorkflowStage): void {
235
201
  acc.visited.add(row.stage);
236
202
  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;
203
+ if (row.status !== "completed") return;
204
+ applyStageSuccess(acc.state, def, row.stage, row.output);
243
205
  }
244
206
 
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(
207
+ /** Close the open generation: project the declared result — the live loop-advance, replayed. */
208
+ function closeGeneration(acc: FoldAcc): void {
209
+ if (!acc.gen) return;
210
+ projectResult(acc.gen.loop, acc.gen.entryPair, acc.gen.cursor, acc.state);
211
+ acc.gen = undefined;
212
+ }
213
+
214
+ async function foldUnitRow(
252
215
  acc: FoldAcc,
253
216
  workflow: Workflow,
254
217
  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;
218
+ ): Promise<Extract<ReconstructResult, { ok: false }> | undefined> {
219
+ // New generation: different parent (or first unit row / after a non-unit row).
220
+ if (!acc.gen || acc.gen.parent !== row.parent) {
221
+ closeGeneration(acc);
222
+ const def = workflow.stages[row.parent!];
223
+ // `effectiveLoopOf` — a verify stage's unit rows recover their synthesized
224
+ // loop here; without it every verify-stage trailer would refuse stage-gone.
225
+ const loop = def ? effectiveLoopOf(def) : undefined;
226
+ if (!def || !loop) return { ok: false, reason: "stage-gone", detail: row.stage };
227
+ // One generation = one chain-node activation. Always reentrant: a halt
228
+ // row for the parent or a resumed re-entry continues this activation.
229
+ noteChainNode(acc, row.parent!, true);
230
+ acc.gen = {
231
+ parent: row.parent!,
232
+ loop,
233
+ def,
234
+ entryArtifact: acc.state.primaryArtifact,
235
+ entryPair: { output: acc.state.output, primaryArtifact: acc.state.primaryArtifact },
236
+ // Frozen HERE: replayed state at generation open is byte-identical to
237
+ // what the live driver saw at loop entry (THE REPLAY CONTRACT) — the
238
+ // only safe place to derive the round-0 arg. `reads` projections in
239
+ // particular must NOT be re-derived post-fold, where the generation's
240
+ // own appends have moved the `.at(-1)` cursors.
241
+ entryArgs: loop.kind === "assess" ? stageEntryArgs(def, row.parent!, workflow.start, acc.state) : "",
242
+ cursor: freshCursor(),
243
+ units: undefined,
244
+ };
245
+ if (loop.kind === "fanout") {
246
+ acc.gen.units = await guarded(acc, acc.gen.parent, () =>
247
+ (loop as Extract<LoopDef, { kind: "fanout" }>).units({
248
+ cwd: acc.cwd,
249
+ artifact: acc.state.primaryArtifact,
250
+ state: acc.state,
251
+ }),
252
+ );
253
+ }
262
254
  }
263
- const iterateParent = matchFanoutParent(row.stage, iterateNames);
264
- if (iterateParent) {
265
- foldIterateUnit(acc, workflow.stages[iterateParent]!, iterateParent, row);
266
- return FOLD_OK;
255
+
256
+ const gen = acc.gen;
257
+ acc.visited.add(gen.parent);
258
+ acc.lastStageNumber = Math.max(acc.lastStageNumber, row.stageNumber);
259
+
260
+ if (!acc.drift) await guardRow(acc, gen, row);
261
+
262
+ if (row.status !== "completed") return undefined; // pending unit — cursor stays (resume re-runs it)
263
+
264
+ if (row.role === "judge" || row.role === "verify") {
265
+ // Apply-then-project: each member verdict rolls the pair TRANSIENTLY
266
+ // (exactly like the live judge unit); projection at generation close
267
+ // restores. The member this row graded is the one the rebuilt sub-state
268
+ // currently points at — `cursor.panel.memberIndex` BEFORE `advanceCursor`
269
+ // bumps it (0 for a single judge, the panel of one). Using that member's
270
+ // own def publishes the verdict to the member's OWN channel, matching the
271
+ // live session path (`judgeStageDef(member)`) per member — `[0]` for every
272
+ // member would have mis-filed members 1..N-1 onto member 0's channel.
273
+ const judgeSlot = (gen.loop as Extract<LoopDef, { kind: "assess" }>).judge;
274
+ const memberIndex = gen.cursor.panel?.memberIndex ?? 0;
275
+ applyStageSuccess(acc.state, judgeStageDef(panelMembers(judgeSlot)[memberIndex]!), row.stage, row.output);
276
+ const role = row.role; // narrowed to "judge" | "verify" — captured for the closure below
277
+ const verdict = row.output;
278
+ if (!verdict) return undefined; // defensive — completed unit rows always carry output
279
+ // `guardRow` already verified `row.unitIndex === cursor.index` (drift
280
+ // otherwise), so the shared transition lands the same cursor the live
281
+ // driver had — and, on the last member, the same folded verdict.
282
+ //
283
+ // `advanceCursor` runs the author fold on the LAST member (`panel.fold`,
284
+ // which a sugar fold's per-member `pred` reaches too), and
285
+ // `publishPanelVerdict` lands it — BOTH behind `guarded()`. A fold/pred
286
+ // throw must become drift (a recorded terminal failure), NOT an unguarded
287
+ // rejection: this fold runs in `reconstructState`, which `resumeWorkflow`
288
+ // awaits BEFORE `executeRun` brackets the lifecycle — an escape here yields
289
+ // no JSONL failure row and no `onWorkflowEnd`. The live driver's same
290
+ // `advanceCursor`+`publishPanelVerdict` pair runs under
291
+ // `runStageOrRecordFailure`'s catch (loop.ts `dispatchUnit`); this is its
292
+ // resume-side error boundary.
293
+ await guarded(acc, gen.parent, () => {
294
+ advanceCursor(gen.cursor, role, verdict, gen.loop);
295
+ // Panel-close publish — the SAME call the live driver makes after the
296
+ // last member's advance, so the folded verdict lands byte-identically.
297
+ publishPanelVerdict(gen.loop, gen.parent, gen.cursor, acc.state);
298
+ });
299
+ return undefined;
267
300
  }
268
- return refuse("stage-gone", row.stage);
301
+
302
+ // produce row — fanout/iterate units and assess producers alike
303
+ applyStageSuccess(acc.state, gen.def, row.stage, row.output);
304
+ if (!row.output) return undefined; // defensive — completed unit rows always carry output
305
+ advanceCursor(gen.cursor, "produce", row.output, gen.loop);
306
+ gen.expected = undefined; // consumed
307
+ return undefined;
269
308
  }
270
309
 
271
310
  /**
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).
311
+ * The full-row determinism guard — every unit row is checked against the
312
+ * recomputed expectation at its boundary (the replayed state IS what the live
313
+ * driver saw). The kind-agnostic (role, unitIndex) arithmetic lives here; the
314
+ * per-kind re-check delegates to the strategy table (loop-kinds.ts). Drift
315
+ * marks `acc.drift` and stops guarding; applying continues so the failure can
316
+ * be recorded against complete state.
285
317
  */
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
318
+ async function guardRow(acc: FoldAcc, gen: OpenGeneration, row: WorkflowStage): Promise<void> {
319
+ const judgeRole = gen.def.verify ? "verify" : "judge";
320
+ const expectRole = gen.loop.kind === "assess" ? (gen.cursor.phase === "judge" ? judgeRole : "produce") : "produce";
321
+ if (row.role !== expectRole || row.unitIndex !== gen.cursor.index) return setDrift(acc, gen.parent);
322
+
323
+ const matches = await guarded(acc, gen.parent, () =>
324
+ loopStrategyOf(gen.loop.kind).guardExpectation(gen, row, acc.cwd, acc.state),
325
+ );
326
+ if (acc.drift) return;
327
+ if (!matches) setDrift(acc, gen.parent);
296
328
  }
297
329
 
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);
330
+ function setDrift(acc: FoldAcc, parent: string): void {
331
+ acc.drift = { parent, errMsg: ERR_RESUME_LOOP_MISMATCH(parent) };
332
+ }
333
+
334
+ /** Run a user fn during the fold; a throw becomes drift with the thrown reason. */
335
+ async function guarded<T>(acc: FoldAcc, parent: string, fn: () => T | Promise<T>): Promise<T | undefined> {
336
+ try {
337
+ return await fn();
338
+ } catch (e) {
339
+ acc.drift = { parent, errMsg: formatError(e) };
340
+ return undefined;
322
341
  }
323
- acc.visited.add(parent);
324
- acc.lastStageNumber = Math.max(acc.lastStageNumber, row.stageNumber);
325
- acc.lastFoldedUnitParent = parent;
342
+ }
326
343
 
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);
344
+ function toPoint(gen: OpenGeneration): LoopResumePoint {
345
+ return {
346
+ parent: gen.parent,
347
+ entryArtifact: gen.entryArtifact,
348
+ entryPair: gen.entryPair,
349
+ entryArgs: gen.entryArgs,
350
+ cursor: gen.cursor,
351
+ units: gen.units,
352
+ };
333
353
  }