@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.
package/src/index.ts CHANGED
@@ -37,6 +37,7 @@ export {
37
37
  DagNodeDefSchema,
38
38
  DagWorkflowDefSchema,
39
39
  GuardDefSchema,
40
+ StateDisplaySchema,
40
41
  StateMachineWorkflowDefSchema,
41
42
  TransitionFlowWorkflowDefSchema,
42
43
  WorkflowDefSchema,
@@ -66,6 +67,7 @@ export type {
66
67
  OnErrorPolicy,
67
68
  ResumeOwnership,
68
69
  StateDef,
70
+ StateDisplay,
69
71
  StateMachineWorkflowDef,
70
72
  TransitionAllowed,
71
73
  TransitionDef,
@@ -1,5 +1,5 @@
1
1
  import type { DbAdapter, DbBatchOp } from '@gobing-ai/ts-db';
2
- import { RunCollisionError } from './errors';
2
+ import { RunCollisionError, WorkflowResumeError } from './errors';
3
3
  import { WORKFLOW_ENGINE_MIGRATIONS_SQL, WORKFLOW_ENGINE_SCHEMA_SQL } from './schema-sql';
4
4
  import type {
5
5
  ActionRedactor,
@@ -413,15 +413,24 @@ export class DbWorkflowPersistenceAdapter implements WorkflowPersistenceAdapter
413
413
  }
414
414
 
415
415
  /** Record the start of a branch execution in a parallel region. */
416
- async saveBranchStart(runId: string, parallelNode: string, branchId: string, startNode: string): Promise<string> {
416
+ async saveBranchStart(
417
+ runId: string,
418
+ parallelNode: string,
419
+ branchId: string,
420
+ startNode: string,
421
+ ownerAttempt?: string,
422
+ ): Promise<string> {
423
+ await this.assertBranchOwner(runId, ownerAttempt);
417
424
  await this.ensureSchema();
418
425
  const id = crypto.randomUUID();
419
426
  const now = Date.now();
420
427
  await this.db.run(
421
428
  `INSERT INTO workflow_branches (id, run_id, parallel_node, branch_id, status, node, started_at, created_at, updated_at)
422
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
429
+ SELECT ?, ?, ?, ?, ?, ?, ?, ?, ?
430
+ WHERE (? IS NULL OR EXISTS (SELECT 1 FROM runs WHERE id = ? AND owner_attempt = ? AND status = 'running'))
423
431
  ON CONFLICT(run_id, parallel_node, branch_id) DO UPDATE SET
424
- status = 'running', node = excluded.node, started_at = excluded.started_at, completed_at = NULL, error = NULL, updated_at = excluded.updated_at`,
432
+ status = 'running', node = excluded.node, started_at = excluded.started_at, completed_at = NULL, error = NULL, updated_at = excluded.updated_at
433
+ WHERE (? IS NULL OR EXISTS (SELECT 1 FROM runs WHERE id = ? AND owner_attempt = ? AND status = 'running'))`,
425
434
  id,
426
435
  runId,
427
436
  parallelNode,
@@ -431,8 +440,16 @@ export class DbWorkflowPersistenceAdapter implements WorkflowPersistenceAdapter
431
440
  new Date(now).toISOString(),
432
441
  now,
433
442
  now,
443
+ ownerAttempt ?? null,
444
+ runId,
445
+ ownerAttempt ?? null,
446
+ ownerAttempt ?? null,
447
+ runId,
448
+ ownerAttempt ?? null,
434
449
  );
435
- return id;
450
+ await this.assertBranchOwner(runId, ownerAttempt);
451
+ const branches = await this.listRunBranches(runId, parallelNode);
452
+ return branches.find((branch) => branch.branch_id === branchId)?.id ?? id;
436
453
  }
437
454
 
438
455
  /** Finalize a branch execution with terminal status, duration, output variables, and optional error. */
@@ -443,22 +460,32 @@ export class DbWorkflowPersistenceAdapter implements WorkflowPersistenceAdapter
443
460
  durationMs: number,
444
461
  outputVars?: Vars,
445
462
  error?: string,
463
+ checkpoint?: { readonly parallelNode: string; readonly node: string; readonly ownerAttempt?: string },
446
464
  ): Promise<void> {
465
+ await this.assertBranchOwner(runId, checkpoint?.ownerAttempt);
447
466
  await this.ensureSchema();
448
467
  const now = Date.now();
449
468
  await this.db.run(
450
469
  `UPDATE workflow_branches
451
- SET status = ?, duration_ms = ?, output_vars_json = ?, error = ?, completed_at = ?, updated_at = ?
452
- WHERE run_id = ? AND branch_id = ?`,
470
+ SET status = ?, duration_ms = ?, output_vars_json = ?, error = ?, completed_at = ?, updated_at = ?, node = COALESCE(?, node)
471
+ WHERE run_id = ? AND branch_id = ? AND (? IS NULL OR parallel_node = ?)
472
+ AND (? IS NULL OR EXISTS (SELECT 1 FROM runs WHERE id = ? AND owner_attempt = ? AND status = 'running'))`,
453
473
  status,
454
474
  durationMs,
455
475
  outputVars !== undefined ? JSON.stringify(outputVars) : null,
456
476
  error ?? null,
457
- new Date(now).toISOString(),
477
+ status === 'running' ? null : new Date(now).toISOString(),
458
478
  now,
479
+ checkpoint?.node ?? null,
459
480
  runId,
460
481
  branchId,
482
+ checkpoint?.parallelNode ?? null,
483
+ checkpoint?.parallelNode ?? null,
484
+ checkpoint?.ownerAttempt ?? null,
485
+ runId,
486
+ checkpoint?.ownerAttempt ?? null,
461
487
  );
488
+ await this.assertBranchOwner(runId, checkpoint?.ownerAttempt);
462
489
  }
463
490
 
464
491
  /** List all branch records for a run, optionally filtered by parallel node ID. */
@@ -484,11 +511,58 @@ export class DbWorkflowPersistenceAdapter implements WorkflowPersistenceAdapter
484
511
  joinNode: string,
485
512
  mergedVars?: Vars,
486
513
  phase?: { phase: string; status: WorkflowStatus },
514
+ ownerAttempt?: string,
515
+ transitionsTaken?: number,
516
+ collectedFailure?: string,
487
517
  ): Promise<void> {
488
- await this.ensureSchema();
489
- const data: Record<string, unknown> = {};
518
+ await this.assertBranchOwner(runId, ownerAttempt);
519
+ const data: Record<string, unknown> = { transitionsTaken };
520
+ if (collectedFailure !== undefined) data.collectedFailure = collectedFailure;
490
521
  if (mergedVars !== undefined) data.effectiveVars = mergedVars;
491
- await this.commitTransition(runId, parallelNode, joinNode, '__join__', joinNode, data, phase);
522
+ const now = Date.now();
523
+ const branches = await this.listRunBranches(runId, parallelNode);
524
+ const ops: DbBatchOp[] = branches.map((branch) => ({
525
+ sql: `UPDATE workflow_branches SET status = ?, node = ?, output_vars_json = ?, error = ?, duration_ms = ?, completed_at = ?, updated_at = ? WHERE id = ?`,
526
+ params: [
527
+ branch.status,
528
+ branch.node,
529
+ branch.output_vars_json,
530
+ branch.error,
531
+ branch.duration_ms,
532
+ branch.completed_at,
533
+ now,
534
+ branch.id,
535
+ ],
536
+ }));
537
+ ops.push(
538
+ this.transitionRow(runId, parallelNode, joinNode, '__join__', now),
539
+ this.stateRow(runId, joinNode, data, now),
540
+ );
541
+ if (phase) ops.push(this.phaseRow(runId, phase.phase, phase.status, now));
542
+ // Each mutation carries the fence inside the transaction; a stale owner cannot
543
+ // rewrite ledger outcomes or activate a join after another attempt claims the run.
544
+ const fenced =
545
+ ownerAttempt === undefined
546
+ ? ops
547
+ : ops.map((op) => ({
548
+ sql: op.sql.startsWith('INSERT')
549
+ ? op.sql.replace(
550
+ /VALUES \(([^)]*)\)/,
551
+ "SELECT $1 WHERE EXISTS (SELECT 1 FROM runs WHERE id = ? AND owner_attempt = ? AND status = 'running')",
552
+ )
553
+ : `${op.sql} AND EXISTS (SELECT 1 FROM runs WHERE id = ? AND owner_attempt = ? AND status = 'running')`,
554
+ params: [...op.params, runId, ownerAttempt],
555
+ }));
556
+ await this.db.batch(fenced);
557
+ await this.assertBranchOwner(runId, ownerAttempt);
558
+ }
559
+
560
+ private async assertBranchOwner(runId: string, ownerAttempt?: string): Promise<void> {
561
+ if (ownerAttempt === undefined) return;
562
+ const run = await this.loadRun(runId);
563
+ if (run?.status !== 'running' || run.owner_attempt !== ownerAttempt) {
564
+ throw new WorkflowResumeError(`Stale branch owner "${ownerAttempt}" for run "${runId}"`);
565
+ }
492
566
  }
493
567
  }
494
568
 
@@ -720,7 +794,14 @@ export class MemoryWorkflowPersistenceAdapter implements WorkflowPersistenceAdap
720
794
  readonly branches = new Map<string, WorkflowBranchRecord>();
721
795
 
722
796
  /** Record the start of a branch execution in a parallel region. */
723
- async saveBranchStart(runId: string, parallelNode: string, branchId: string, startNode: string): Promise<string> {
797
+ async saveBranchStart(
798
+ runId: string,
799
+ parallelNode: string,
800
+ branchId: string,
801
+ startNode: string,
802
+ ownerAttempt?: string,
803
+ ): Promise<string> {
804
+ this.assertBranchOwner(runId, ownerAttempt);
724
805
  const id = crypto.randomUUID();
725
806
  const now = Date.now();
726
807
  const key = `${runId}:${parallelNode}:${branchId}`;
@@ -749,15 +830,22 @@ export class MemoryWorkflowPersistenceAdapter implements WorkflowPersistenceAdap
749
830
  durationMs: number,
750
831
  outputVars?: Vars,
751
832
  error?: string,
833
+ checkpoint?: { readonly parallelNode: string; readonly node: string; readonly ownerAttempt?: string },
752
834
  ): Promise<void> {
835
+ this.assertBranchOwner(runId, checkpoint?.ownerAttempt);
753
836
  const now = Date.now();
754
837
  for (const [key, b] of this.branches.entries()) {
755
- if (b.run_id === runId && b.branch_id === branchId) {
838
+ if (
839
+ b.run_id === runId &&
840
+ b.branch_id === branchId &&
841
+ (checkpoint === undefined || b.parallel_node === checkpoint.parallelNode)
842
+ ) {
756
843
  this.branches.set(key, {
757
844
  ...b,
845
+ node: checkpoint?.node ?? b.node,
758
846
  status,
759
847
  duration_ms: durationMs,
760
- completed_at: new Date(now).toISOString(),
848
+ completed_at: status === 'running' ? null : new Date(now).toISOString(),
761
849
  output_vars_json: outputVars !== undefined ? JSON.stringify(outputVars) : null,
762
850
  error: error ?? null,
763
851
  });
@@ -784,9 +872,25 @@ export class MemoryWorkflowPersistenceAdapter implements WorkflowPersistenceAdap
784
872
  joinNode: string,
785
873
  mergedVars?: Vars,
786
874
  phase?: { phase: string; status: WorkflowStatus },
875
+ ownerAttempt?: string,
876
+ transitionsTaken?: number,
877
+ collectedFailure?: string,
787
878
  ): Promise<void> {
788
- const data: Record<string, unknown> = {};
879
+ const run = this.runs.get(runId);
880
+ if (ownerAttempt !== undefined && (run?.status !== 'running' || run.owner_attempt !== ownerAttempt)) {
881
+ throw new WorkflowResumeError(`Stale branch owner "${ownerAttempt}" for run "${runId}"`);
882
+ }
883
+ const data: Record<string, unknown> = { transitionsTaken };
884
+ if (collectedFailure !== undefined) data.collectedFailure = collectedFailure;
789
885
  if (mergedVars !== undefined) data.effectiveVars = mergedVars;
790
886
  await this.commitTransition(runId, parallelNode, joinNode, '__join__', joinNode, data, phase);
791
887
  }
888
+
889
+ private assertBranchOwner(runId: string, ownerAttempt?: string): void {
890
+ if (ownerAttempt === undefined) return;
891
+ const run = this.runs.get(runId);
892
+ if (run?.status !== 'running' || run.owner_attempt !== ownerAttempt) {
893
+ throw new WorkflowResumeError(`Stale branch owner "${ownerAttempt}" for run "${runId}"`);
894
+ }
895
+ }
792
896
  }
@@ -90,6 +90,11 @@ export class RunLifecycle {
90
90
  /** Owner attempt recorded on the run row; undefined for lifecycles that never claimed a run (external transitions, direct construction). Gates the finalize fence (task 0086 AC11). */
91
91
  private ownerAttempt: string | undefined;
92
92
 
93
+ /** Owner fence for branch ledger writes and join commits. */
94
+ get ownerAttemptId(): string | undefined {
95
+ return this.ownerAttempt;
96
+ }
97
+
93
98
  private constructor(
94
99
  runId: string,
95
100
  private readonly workflowName: string,
package/src/schema.ts CHANGED
@@ -69,6 +69,20 @@ export const GuardDefSchema = z.object({
69
69
  options: z.record(z.string(), z.unknown()).optional(),
70
70
  });
71
71
 
72
+ /**
73
+ * Zod schema for per-state presentation metadata (task 1103). Accepted and
74
+ * preserved by the engine, never read at run time; `.strict()` so author
75
+ * typos fail loud instead of silently disappearing.
76
+ */
77
+ export const StateDisplaySchema = z
78
+ .object({
79
+ phase: z.string().min(1),
80
+ phaseTitle: z.string().min(1).optional(),
81
+ title: z.string().min(1).optional(),
82
+ show: z.enum(['plan', 'on-entry']).optional(),
83
+ })
84
+ .strict();
85
+
72
86
  /** Zod schema for state-machine workflow definitions. */
73
87
  export const StateMachineWorkflowDefSchema = z
74
88
  .object({
@@ -98,6 +112,8 @@ export const StateMachineWorkflowDefSchema = z
98
112
  resumeRerun: z.boolean().optional(),
99
113
  /** Author opt-in for a fresh run to begin at this state (task 0102 R2). */
100
114
  startable: z.boolean().optional(),
115
+ /** Presentation-only display metadata; the engine never reads it (task 1103). */
116
+ display: StateDisplaySchema.optional(),
101
117
  })
102
118
  .strict(),
103
119
  ),
package/src/service.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { type BusLifecycleEvents, EventBus } from '@gobing-ai/ts-infra';
2
2
  import { loadWorkflowDef } from './config';
3
- import { DagDriver } from './dag';
3
+ import { assertDagResumeAllowed, DagDriver } from './dag';
4
4
  import { FSMError, WorkflowResumeError } from './errors';
5
5
  import type { WorkflowEngineEvents } from './events';
6
6
  import type { WorkflowEngineHost } from './host';
@@ -221,10 +221,8 @@ export class WorkflowService {
221
221
  if (run.status !== 'paused' && run.status !== 'interrupted') {
222
222
  throw new WorkflowResumeError(`Run "${runId}" is not resumable (status: ${run.status})`);
223
223
  }
224
- const currentState = await this.persistence.loadCurrentState(runId);
225
- if (currentState === undefined) {
226
- throw new WorkflowResumeError(`Run "${runId}" has no persisted state to resume from`);
227
- }
224
+ const snapshotState = await this.persistence.loadCurrentState(runId);
225
+ let currentState: string;
228
226
 
229
227
  // Resolve recovery semantics (task 0902): interrupted runs default to re-running
230
228
  // the current state's actions (they may have half-completed at the interruption);
@@ -232,14 +230,40 @@ export class WorkflowService {
232
230
  // An explicit `resumeMode` option overrides either default.
233
231
  const resumeMode: WorkflowResumeMode =
234
232
  options?.resumeMode ?? (run.status === 'interrupted' ? 'rerun-enter' : 'skip-enter');
235
- this.assertResumeRerunAllowed(workflow, currentState, resumeMode);
233
+ if (workflow.kind === 'dag') {
234
+ // Task 0104 Design 6: DAG runs admit via the per-node ledger — the
235
+ // recovery source for interrupted runs without a snapshot — so the
236
+ // generic no-snapshot refusal and anchor-only rerun check do not apply.
237
+ const admission = await assertDagResumeAllowed(workflow, runId, this.persistence, resumeMode);
238
+ currentState = snapshotState ?? admission.anchor;
239
+ } else {
240
+ if (snapshotState === undefined) {
241
+ throw new WorkflowResumeError(`Run "${runId}" has no persisted state to resume from`);
242
+ }
243
+ currentState = snapshotState;
244
+ this.assertResumeRerunAllowed(workflow, currentState, resumeMode);
245
+ // 9d56aa83: a rerun-enter resume of a fork-join parallel node must
246
+ // also clear the rerun guard for each not-yet-done branch's start node.
247
+ if (workflow.kind === 'transition-flow' && resumeMode === 'rerun-enter') {
248
+ const parallel = workflow.nodes.find((node) => node.id === currentState && node.type === 'parallel');
249
+ if (parallel) {
250
+ const branches = await this.persistence.listRunBranches(runId, parallel.id);
251
+ for (const branch of branches) {
252
+ if (branch.status === 'done') continue;
253
+ this.assertResumeRerunAllowed(workflow, branch.node, resumeMode);
254
+ }
255
+ }
256
+ }
257
+ }
236
258
 
237
259
  // Restore effectiveVars persisted in the last state snapshot so resume
238
260
  // continues with the same runtime variables (e.g. `__hitlAnswer`). Caller
239
261
  // overrides in `options.vars` win over the persisted snapshot (R3 of 0366).
262
+ // Task 0104 Design 8: DAG runs pass caller vars through un-merged — the
263
+ // DAG driver owns the snapshot → ledger-delta → caller precedence.
240
264
  const snapshot = await this.persistence.loadLatestStateSnapshot(runId);
241
265
  const persistedVars = extractEffectiveVars(snapshot?.data);
242
- const restoredVars = mergeVars(persistedVars, options?.vars);
266
+ const restoredVars = workflow.kind === 'dag' ? options?.vars : mergeVars(persistedVars, options?.vars);
243
267
  const owner: ResumeOwnership = options?.resumeOwner ?? { attemptId: crypto.randomUUID() };
244
268
  const mergedOptions: WorkflowRunOptions = { ...options, vars: restoredVars, resumeMode, resumeOwner: owner };
245
269