@gobing-ai/ts-dual-workflow-engine 0.5.16 → 0.5.18

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.
@@ -82,6 +82,8 @@ export class TransitionFlowDriver {
82
82
  // phase atomically (every iteration after the first), `enter` must skip
83
83
  // the persist half to avoid duplicate INSERT rows (ADR-020).
84
84
  let persistedViaHop = false;
85
+ let collectedFailure =
86
+ typeof snapshot?.data.collectedFailure === 'string' ? snapshot.data.collectedFailure : undefined;
85
87
 
86
88
  if (current === undefined) {
87
89
  const label = entryNode ?? workflow.initialNode;
@@ -132,7 +134,7 @@ export class TransitionFlowDriver {
132
134
  });
133
135
  lastActionResult = step.result;
134
136
  if (step.result?.setVars) vars = mergeSetVars(vars, step.result.setVars);
135
- if (step.outcome === 'terminal') {
137
+ if (step.outcome === 'terminal' && collectedFailure === undefined) {
136
138
  return await lifecycle.done(current.id, transitionsTaken);
137
139
  }
138
140
  if (step.outcome === 'fail') {
@@ -146,6 +148,10 @@ export class TransitionFlowDriver {
146
148
  }
147
149
  }
148
150
 
151
+ if (collectedFailure !== undefined) {
152
+ return await lifecycle.fail(current.id, transitionsTaken, collectedFailure);
153
+ }
154
+
149
155
  // Structured parallel fork-join execution
150
156
  if (current.type === 'parallel') {
151
157
  if (!current.branches || !current.join) {
@@ -160,10 +166,6 @@ export class TransitionFlowDriver {
160
166
  for (const b of parallelNode.branches) {
161
167
  const ctrl = new AbortController();
162
168
  branchControllers.set(b.id, ctrl);
163
- if (options.signal) {
164
- if (options.signal.aborted) ctrl.abort();
165
- else options.signal.addEventListener('abort', () => ctrl.abort(), { once: true });
166
- }
167
169
  }
168
170
 
169
171
  const abortSiblings = (failingBranchId: string) => {
@@ -192,13 +194,21 @@ export class TransitionFlowDriver {
192
194
  }
193
195
 
194
196
  const branchCtrl = branchControllers.get(branch.id) ?? new AbortController();
197
+ const branchSignal = options.signal
198
+ ? AbortSignal.any([options.signal, branchCtrl.signal])
199
+ : branchCtrl.signal;
195
200
  const branchStartMs = Date.now();
196
201
  let branchCurrent: FlowNodeDef | undefined;
197
202
  let skipEnter = false;
198
203
 
199
- if (existing?.status === 'paused') {
204
+ if (existing?.status === 'paused' || existing?.status === 'running') {
200
205
  branchCurrent = nodes.get(existing.node) ?? nodes.get(branch.startNode);
201
- skipEnter = (resumeMode ?? options.resumeMode ?? 'skip-enter') === 'skip-enter';
206
+ skipEnter = (options.resumeMode ?? 'skip-enter') === 'skip-enter';
207
+ if (!skipEnter && branchCurrent?.resumeRerun !== true) {
208
+ throw new FSMError(
209
+ `Cannot rerun-resume branch node "${branchCurrent?.id}": not marked resumeRerun: true`,
210
+ );
211
+ }
202
212
  } else {
203
213
  branchCurrent = nodes.get(branch.startNode);
204
214
  await this.options.persistence.saveBranchStart(
@@ -206,16 +216,19 @@ export class TransitionFlowDriver {
206
216
  parallelNode.id,
207
217
  branch.id,
208
218
  branch.startNode,
219
+ lifecycle.ownerAttemptId,
209
220
  );
210
221
  }
211
222
 
212
223
  lifecycle.branchStarted(parallelNode.id, branch.id, branchCurrent?.id ?? branch.startNode);
213
224
 
214
- let branchVars = { ...vars };
215
- let branchSetVars: Vars = {};
225
+ let branchSetVars: Vars = existing?.output_vars_json
226
+ ? JSON.parse(existing.output_vars_json)
227
+ : {};
228
+ let branchVars = mergeSetVars(vars, branchSetVars);
216
229
 
217
230
  while (branchCurrent && branchCurrent.id !== parallelNode.join) {
218
- if (branchCtrl.signal.aborted) {
231
+ if (branchSignal.aborted) {
219
232
  lifecycle.branchFailed(parallelNode.id, branch.id, 'cancelled');
220
233
  await this.options.persistence.saveBranchFinalize(
221
234
  runId,
@@ -224,6 +237,11 @@ export class TransitionFlowDriver {
224
237
  Date.now() - branchStartMs,
225
238
  undefined,
226
239
  'cancelled',
240
+ {
241
+ parallelNode: parallelNode.id,
242
+ node: branchCurrent.id,
243
+ ownerAttempt: lifecycle.ownerAttemptId,
244
+ },
227
245
  );
228
246
  return { ok: false, branchId: branch.id, error: 'cancelled' };
229
247
  }
@@ -231,6 +249,19 @@ export class TransitionFlowDriver {
231
249
  if (skipEnter) {
232
250
  skipEnter = false;
233
251
  } else {
252
+ await this.options.persistence.saveBranchFinalize(
253
+ runId,
254
+ branch.id,
255
+ 'running',
256
+ Date.now() - branchStartMs,
257
+ branchSetVars,
258
+ undefined,
259
+ {
260
+ parallelNode: parallelNode.id,
261
+ node: branchCurrent.id,
262
+ ownerAttempt: lifecycle.ownerAttemptId,
263
+ },
264
+ );
234
265
  if (branchCurrent.action !== undefined) {
235
266
  const step = await runActionStep(branchCurrent.action, branchVars, {
236
267
  host: this.options.host,
@@ -244,13 +275,13 @@ export class TransitionFlowDriver {
244
275
  env,
245
276
  options,
246
277
  defaultOnError,
247
- signal: branchCtrl.signal,
278
+ signal: branchSignal,
248
279
  });
249
280
  if (step.result?.setVars) {
250
281
  branchVars = mergeSetVars(branchVars, step.result.setVars);
251
282
  branchSetVars = mergeSetVars(branchSetVars, step.result.setVars);
252
283
  }
253
- if (branchCtrl.signal.aborted) {
284
+ if (branchSignal.aborted) {
254
285
  lifecycle.branchFailed(parallelNode.id, branch.id, 'cancelled');
255
286
  await this.options.persistence.saveBranchFinalize(
256
287
  runId,
@@ -259,6 +290,11 @@ export class TransitionFlowDriver {
259
290
  Date.now() - branchStartMs,
260
291
  undefined,
261
292
  'cancelled',
293
+ {
294
+ parallelNode: parallelNode.id,
295
+ node: branchCurrent.id,
296
+ ownerAttempt: lifecycle.ownerAttemptId,
297
+ },
262
298
  );
263
299
  return { ok: false, branchId: branch.id, error: 'cancelled' };
264
300
  }
@@ -273,6 +309,11 @@ export class TransitionFlowDriver {
273
309
  Date.now() - branchStartMs,
274
310
  undefined,
275
311
  err,
312
+ {
313
+ parallelNode: parallelNode.id,
314
+ node: branchCurrent.id,
315
+ ownerAttempt: lifecycle.ownerAttemptId,
316
+ },
276
317
  );
277
318
  return {
278
319
  ok: false,
@@ -293,6 +334,12 @@ export class TransitionFlowDriver {
293
334
  'paused',
294
335
  Date.now() - branchStartMs,
295
336
  branchSetVars,
337
+ undefined,
338
+ {
339
+ parallelNode: parallelNode.id,
340
+ node: branchCurrent.id,
341
+ ownerAttempt: lifecycle.ownerAttemptId,
342
+ },
296
343
  );
297
344
  return {
298
345
  ok: true,
@@ -307,19 +354,40 @@ export class TransitionFlowDriver {
307
354
  if (outbound.length === 0 || terminal.has(branchCurrent.id)) {
308
355
  break;
309
356
  }
310
- const edge = await firstPassingEdge(
311
- outbound,
312
- this.options.host,
313
- {
357
+ let edge: TransitionFlowWorkflowDef['edges'][number] | undefined;
358
+ try {
359
+ edge = await firstPassingEdge(
360
+ outbound,
361
+ this.options.host,
362
+ {
363
+ runId,
364
+ current: branchCurrent.id,
365
+ vars: branchVars,
366
+ env,
367
+ workdir: options.workdir,
368
+ signal: branchSignal,
369
+ },
370
+ lifecycle,
371
+ );
372
+ } catch (error) {
373
+ abortSiblings(branch.id);
374
+ const reason = error instanceof Error ? error.message : String(error);
375
+ lifecycle.branchFailed(parallelNode.id, branch.id, reason);
376
+ await this.options.persistence.saveBranchFinalize(
314
377
  runId,
315
- current: branchCurrent.id,
316
- vars: branchVars,
317
- env,
318
- workdir: options.workdir,
319
- signal: branchCtrl.signal,
320
- },
321
- lifecycle,
322
- );
378
+ branch.id,
379
+ 'failed',
380
+ Date.now() - branchStartMs,
381
+ branchSetVars,
382
+ reason,
383
+ {
384
+ parallelNode: parallelNode.id,
385
+ node: branchCurrent.id,
386
+ ownerAttempt: lifecycle.ownerAttemptId,
387
+ },
388
+ );
389
+ return { ok: false, branchId: branch.id, error: reason };
390
+ }
323
391
  if (edge === undefined) {
324
392
  abortSiblings(branch.id);
325
393
  lifecycle.branchFailed(parallelNode.id, branch.id, 'no-passing-edge');
@@ -330,13 +398,18 @@ export class TransitionFlowDriver {
330
398
  Date.now() - branchStartMs,
331
399
  undefined,
332
400
  'no-passing-edge',
401
+ {
402
+ parallelNode: parallelNode.id,
403
+ node: branchCurrent.id,
404
+ ownerAttempt: lifecycle.ownerAttemptId,
405
+ },
333
406
  );
334
407
  return { ok: false, branchId: branch.id, error: 'no-passing-edge' };
335
408
  }
336
409
  branchCurrent = nodes.get(edge.to);
337
410
  }
338
411
 
339
- if (branchCtrl.signal.aborted) {
412
+ if (branchSignal.aborted) {
340
413
  lifecycle.branchFailed(parallelNode.id, branch.id, 'cancelled');
341
414
  await this.options.persistence.saveBranchFinalize(
342
415
  runId,
@@ -345,6 +418,11 @@ export class TransitionFlowDriver {
345
418
  Date.now() - branchStartMs,
346
419
  undefined,
347
420
  'cancelled',
421
+ {
422
+ parallelNode: parallelNode.id,
423
+ node: branchCurrent?.id ?? branch.startNode,
424
+ ownerAttempt: lifecycle.ownerAttemptId,
425
+ },
348
426
  );
349
427
  return { ok: false, branchId: branch.id, error: 'cancelled' };
350
428
  }
@@ -356,30 +434,55 @@ export class TransitionFlowDriver {
356
434
  'done',
357
435
  Date.now() - branchStartMs,
358
436
  branchSetVars,
437
+ undefined,
438
+ {
439
+ parallelNode: parallelNode.id,
440
+ node: branchCurrent?.id ?? branch.startNode,
441
+ ownerAttempt: lifecycle.ownerAttemptId,
442
+ },
359
443
  );
360
444
  return { ok: true, branchId: branch.id, setVars: branchSetVars };
361
445
  },
446
+ () => {
447
+ for (const controller of branchControllers.values()) controller.abort();
448
+ },
362
449
  );
363
450
 
364
- const failed = branchResults.find((r) => !r.ok);
451
+ const failed =
452
+ branchResults.find((r) => !r.ok && r.error !== 'cancelled') ?? branchResults.find((r) => !r.ok);
365
453
  if (failed) {
366
- return await lifecycle.fail(current.id, transitionsTaken, failed.error ?? 'branch-failed');
454
+ if (parallelNode.failurePolicy === 'fail-fast' || options.signal?.aborted) {
455
+ return await lifecycle.fail(current.id, transitionsTaken, failed.error ?? 'branch-failed');
456
+ }
457
+ collectedFailure = failed.error ?? 'branch-failed';
367
458
  }
368
459
 
369
460
  const anyPaused = branchResults.some((r) => 'paused' in r && r.paused === true);
461
+ if (anyPaused && collectedFailure === undefined) {
462
+ return await lifecycle.pause(current.id, transitionsTaken, vars);
463
+ }
370
464
  for (const res of branchResults) {
371
465
  if (res.setVars) vars = mergeSetVars(vars, res.setVars);
372
466
  }
373
- if (anyPaused) {
374
- return await lifecycle.pause(current.id, transitionsTaken, vars);
375
- }
376
467
  }
377
468
 
378
469
  transitionsTaken += 1;
379
- await this.options.persistence.commitJoin(runId, current.id, parallelNode.join, vars, {
380
- phase: parallelNode.join,
381
- status: 'running',
382
- });
470
+ await this.options.persistence.commitJoin(
471
+ runId,
472
+ current.id,
473
+ parallelNode.join,
474
+ vars,
475
+ {
476
+ phase: parallelNode.join,
477
+ status: 'running',
478
+ },
479
+ lifecycle.ownerAttemptId,
480
+ transitionsTaken,
481
+ collectedFailure,
482
+ );
483
+ if (transitionsTaken > iterationBound) {
484
+ return await lifecycle.fail(current.id, transitionsTaken, 'iteration-bound-exceeded');
485
+ }
383
486
 
384
487
  const joinNode = nodes.get(parallelNode.join);
385
488
  if (joinNode === undefined) {
@@ -476,6 +579,7 @@ async function runWithConcurrencyLimit<T, R>(
476
579
  items: readonly T[],
477
580
  limit: number,
478
581
  fn: (item: T) => Promise<R>,
582
+ onError: () => void,
479
583
  ): Promise<R[]> {
480
584
  const results: R[] = new Array(items.length);
481
585
  let nextIndex = 0;
@@ -485,10 +589,17 @@ async function runWithConcurrencyLimit<T, R>(
485
589
  const index = nextIndex++;
486
590
  const item = items[index];
487
591
  if (item !== undefined) {
488
- results[index] = await fn(item);
592
+ try {
593
+ results[index] = await fn(item);
594
+ } catch (error) {
595
+ onError();
596
+ throw error;
597
+ }
489
598
  }
490
599
  }
491
600
  });
492
- await Promise.all(workers);
601
+ const settled = await Promise.allSettled(workers);
602
+ const failed = settled.find((result) => result.status === 'rejected');
603
+ if (failed?.status === 'rejected') throw failed.reason;
493
604
  return results;
494
605
  }
package/src/types.ts CHANGED
@@ -62,6 +62,22 @@ export interface WorkflowExtensions {
62
62
  readonly guards?: readonly string[];
63
63
  }
64
64
 
65
+ /**
66
+ * Author-declared presentation metadata for a single state (task 1103). Consumed by
67
+ * plan/UI generators reading the workflow definition; the engine never reads it at
68
+ * run time — it is accepted, preserved and otherwise inert.
69
+ */
70
+ export interface StateDisplay {
71
+ /** Stable phase label this state belongs to (e.g. 'build', 'verify'). */
72
+ readonly phase: string;
73
+ /** Optional human title for the phase group this state belongs to. */
74
+ readonly phaseTitle?: string;
75
+ /** Optional human title for the state in plan/UI views. */
76
+ readonly title?: string;
77
+ /** Optional visibility hint for plan generators. Defaults to 'plan' when absent (interpreted by consumers, not the engine). */
78
+ readonly show?: 'plan' | 'on-entry';
79
+ }
80
+
65
81
  /** One state in a state-machine workflow. */
66
82
  export interface StateDef {
67
83
  readonly id: string;
@@ -85,6 +101,8 @@ export interface StateDef {
85
101
  * artifacts must fail loud rather than silently skip them (task 0102 R2).
86
102
  */
87
103
  readonly startable?: boolean;
104
+ /** Presentation-only display metadata; the engine never reads it (task 1103). */
105
+ readonly display?: StateDisplay;
88
106
  }
89
107
 
90
108
  /** One transition in a state-machine workflow. */
@@ -542,7 +560,13 @@ export interface WorkflowPersistenceAdapter {
542
560
  */
543
561
  interruptRun(runId: string, reason: string): Promise<WorkflowRunRecord | undefined>;
544
562
  /** Record the start of a branch execution in a parallel region. */
545
- saveBranchStart(runId: string, parallelNode: string, branchId: string, startNode: string): Promise<string>;
563
+ saveBranchStart(
564
+ runId: string,
565
+ parallelNode: string,
566
+ branchId: string,
567
+ startNode: string,
568
+ ownerAttempt?: string,
569
+ ): Promise<string>;
546
570
  /** Finalize a branch execution with terminal status, duration, output variables, and optional error. */
547
571
  saveBranchFinalize(
548
572
  runId: string,
@@ -551,6 +575,7 @@ export interface WorkflowPersistenceAdapter {
551
575
  durationMs: number,
552
576
  outputVars?: Vars,
553
577
  error?: string,
578
+ checkpoint?: { readonly parallelNode: string; readonly node: string; readonly ownerAttempt?: string },
554
579
  ): Promise<void>;
555
580
  /** List all branch records for a run, optionally filtered by parallel node ID. */
556
581
  listRunBranches(runId: string, parallelNode?: string): Promise<readonly WorkflowBranchRecord[]>;
@@ -561,5 +586,8 @@ export interface WorkflowPersistenceAdapter {
561
586
  joinNode: string,
562
587
  mergedVars?: Vars,
563
588
  phase?: { phase: string; status: WorkflowStatus },
589
+ ownerAttempt?: string,
590
+ transitionsTaken?: number,
591
+ collectedFailure?: string,
564
592
  ): Promise<void>;
565
593
  }