@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/dag.ts CHANGED
@@ -1,11 +1,14 @@
1
1
  import { runActionStep } from './action-step';
2
+ import { FSMError, WorkflowResumeError } from './errors';
2
3
  import type { WorkflowEngineHost } from './host';
3
- import { allowedEnv, RunLifecycle, snapshotTransitions } from './run-lifecycle';
4
+ import { allowedEnv, RunLifecycle } from './run-lifecycle';
4
5
  import type {
5
6
  DagNodeDef,
6
7
  DagWorkflowDef,
7
8
  Vars,
9
+ WorkflowBranchRecord,
8
10
  WorkflowPersistenceAdapter,
11
+ WorkflowResumeMode,
9
12
  WorkflowRunOptions,
10
13
  WorkflowRunResult,
11
14
  } from './types';
@@ -23,6 +26,147 @@ export type DagNodeStatus = 'pending' | 'ready' | 'running' | 'done' | 'failed'
23
26
  // Reserved parallel_node namespace reusing the 0094 branch ledger for per-node DAG execution records.
24
27
  const DAG_LEDGER_NAMESPACE = '__dag__';
25
28
 
29
+ /**
30
+ * Stable topological order over declared nodes: repeatedly take the earliest
31
+ * declared node whose dependencies are all placed (declaration order breaks
32
+ * ties between equally ready nodes). Leftover nodes (validated-elsewhere
33
+ * cycles) keep declaration order. Task 0104 Design 4.
34
+ */
35
+ export function dagTopoOrder(nodes: readonly DagNodeDef[]): string[] {
36
+ const placed: string[] = [];
37
+ const placedIds = new Set<string>();
38
+ const remaining = [...nodes];
39
+ while (remaining.length > 0) {
40
+ const nextIdx = remaining.findIndex((node) => (node.dependsOn ?? []).every((dep) => placedIds.has(dep)));
41
+ if (nextIdx === -1) break;
42
+ const node = remaining[nextIdx];
43
+ remaining.splice(nextIdx, 1);
44
+ if (node === undefined) break;
45
+ placed.push(node.id);
46
+ placedIds.add(node.id);
47
+ }
48
+ for (const node of remaining) placed.push(node.id);
49
+ return placed;
50
+ }
51
+
52
+ /** Keep only string→string entries, mirroring mergeSetVars' defensive filter. */
53
+ function pickStringEntries(setVars: Vars): Vars {
54
+ const accepted: Vars = {};
55
+ for (const [key, value] of Object.entries(setVars)) {
56
+ if (typeof value === 'string') accepted[key] = value;
57
+ }
58
+ return accepted;
59
+ }
60
+
61
+ /**
62
+ * Parse one persisted branch delta (task 0104 Design 4). A null payload is an
63
+ * empty legacy delta; malformed payloads fail loudly before any execution.
64
+ */
65
+ function parseBranchDelta(raw: string | null, nodeId: string): Vars {
66
+ if (raw === null) return {};
67
+ let parsed: unknown;
68
+ try {
69
+ parsed = JSON.parse(raw);
70
+ } catch (error) {
71
+ throw new WorkflowResumeError(
72
+ `DAG node "${nodeId}" has malformed persisted output: ${(error as Error).message}`,
73
+ );
74
+ }
75
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
76
+ throw new WorkflowResumeError(`DAG node "${nodeId}" has malformed persisted output: expected an object`);
77
+ }
78
+ for (const [key, value] of Object.entries(parsed as Record<string, unknown>)) {
79
+ if (typeof value !== 'string') {
80
+ throw new WorkflowResumeError(`DAG node "${nodeId}" persisted output "${key}" is not a string`);
81
+ }
82
+ }
83
+ return parsed as Vars;
84
+ }
85
+
86
+ /**
87
+ * Ledger-derived resume anchor for runs without a snapshot (task 0104 Design 1):
88
+ * the first paused row in declaration order, otherwise the first unfinished
89
+ * declared row, otherwise the first declared node.
90
+ */
91
+ export function deriveDagResumeAnchor(
92
+ nodes: readonly DagNodeDef[],
93
+ statusByNode: ReadonlyMap<string, WorkflowBranchRecord['status']>,
94
+ ): string | undefined {
95
+ const firstPaused = nodes.find((node) => statusByNode.get(node.id) === 'paused')?.id;
96
+ if (firstPaused !== undefined) return firstPaused;
97
+ const firstUnfinished = nodes.find((node) => {
98
+ const prior = statusByNode.get(node.id);
99
+ return prior === 'running' || prior === 'pending';
100
+ })?.id;
101
+ if (firstUnfinished !== undefined) return firstUnfinished;
102
+ return nodes[0]?.id;
103
+ }
104
+
105
+ /** Result of DAG resume admission checks (task 0104 Design 6). */
106
+ export interface DagResumeAdmission {
107
+ /** Declared node naming where the resumed run logically continues from. */
108
+ readonly anchor: string;
109
+ /** Paused node whose acknowledgement this resume performs, if any. */
110
+ readonly pausedTarget?: string;
111
+ }
112
+
113
+ /**
114
+ * DAG-only resume admission (task 0104 Design 6). Checks every previously
115
+ * unfinished (running/pending) action node: it may replay only under
116
+ * rerun-enter with its own resumeRerun marker — never-started nodes need no
117
+ * marker, done non-paused rows never replay. A paused anchor replays under
118
+ * rerun-enter only with its marker; skip-enter is always safe (acknowledgement).
119
+ * Exported for service.ts admission only — not part of the public package surface.
120
+ */
121
+ export async function assertDagResumeAllowed(
122
+ workflow: DagWorkflowDef,
123
+ runId: string,
124
+ persistence: WorkflowPersistenceAdapter,
125
+ resumeMode: WorkflowResumeMode,
126
+ ): Promise<DagResumeAdmission> {
127
+ const rows = await persistence.listRunBranches(runId, DAG_LEDGER_NAMESPACE);
128
+ const statusByNode = new Map(rows.map((row) => [row.branch_id, row.status]));
129
+
130
+ for (const node of workflow.nodes) {
131
+ const prior = statusByNode.get(node.id);
132
+ if ((prior === 'running' || prior === 'pending') && node.action) {
133
+ if (resumeMode !== 'rerun-enter' || node.resumeRerun !== true) {
134
+ throw new FSMError(
135
+ `DAG node "${node.id}" has an unfinished action that is not marked resumeRerun: true — ` +
136
+ 'replaying it requires resumeMode: "rerun-enter" and its own resumeRerun marker',
137
+ );
138
+ }
139
+ }
140
+ }
141
+
142
+ const snapshot = await persistence.loadLatestStateSnapshot(runId);
143
+ const snapshotState = snapshot?.state;
144
+ if (snapshot === undefined && rows.length === 0) {
145
+ throw new WorkflowResumeError(`Run "${runId}" has no persisted DAG progress to resume from`);
146
+ }
147
+ const pausedTarget =
148
+ snapshotState !== undefined && statusByNode.get(snapshotState) === 'paused'
149
+ ? snapshotState
150
+ : workflow.nodes.find((node) => statusByNode.get(node.id) === 'paused')?.id;
151
+ if (pausedTarget !== undefined && resumeMode === 'rerun-enter') {
152
+ const target = workflow.nodes.find((node) => node.id === pausedTarget);
153
+ if (target?.resumeRerun !== true) {
154
+ throw new FSMError(
155
+ `Cannot rerun-resume into "${pausedTarget}": not marked resumeRerun: true ` +
156
+ '(mark it safe to re-run — idempotent or deduped — or resume with resumeMode: "skip-enter")',
157
+ );
158
+ }
159
+ }
160
+
161
+ const anchor =
162
+ (snapshotState !== undefined && statusByNode.has(snapshotState) ? snapshotState : undefined) ??
163
+ deriveDagResumeAnchor(workflow.nodes, statusByNode);
164
+ if (anchor === undefined) {
165
+ throw new WorkflowResumeError(`Run "${runId}" cannot resume: the workflow declares no nodes`);
166
+ }
167
+ return { anchor, pausedTarget };
168
+ }
169
+
26
170
  /**
27
171
  * Static dependency DAG workflow driver (task 0100, ADR-034).
28
172
  * Manages an in-process ready queue of runnable nodes, dispatching them as upstream
@@ -50,13 +194,20 @@ export class DagDriver {
50
194
  externalKey: string | undefined,
51
195
  options: WorkflowRunOptions = {},
52
196
  ): Promise<WorkflowRunResult> {
197
+ // Task 0104 Design 6: direct driver resume is admission-checked too.
198
+ // Resolve an absent resumeMode from the run's paused/interrupted status
199
+ // (matching service.resumeRun's 0902 defaults) before dispatching.
200
+ const resumeMode: WorkflowResumeMode =
201
+ options.resumeMode ??
202
+ ((await this.options.persistence.loadRun(runId))?.status === 'interrupted' ? 'rerun-enter' : 'skip-enter');
203
+ await assertDagResumeAllowed(workflow, runId, this.options.persistence, resumeMode);
53
204
  return await RunLifecycle.resume(
54
205
  workflow.name,
55
206
  'dag',
56
207
  { persistence: this.options.persistence, events: options.events },
57
208
  runId,
58
209
  externalKey,
59
- (lifecycle) => this.loop(workflow, options, lifecycle),
210
+ (lifecycle) => this.loop(workflow, { ...options, resumeMode }, lifecycle),
60
211
  options.resumeOwner?.attemptId,
61
212
  );
62
213
  }
@@ -67,43 +218,113 @@ export class DagDriver {
67
218
  lifecycle: RunLifecycle,
68
219
  ): Promise<WorkflowRunResult> {
69
220
  const runId = lifecycle.runId;
70
- let vars = mergeVars(workflow.vars, options.vars);
71
221
  const env = allowedEnv(workflow.env?.allow ?? [], options.env);
72
222
  const defaultOnError = workflow.defaultOnError;
73
223
 
74
- // Restore snapshot if resuming
224
+ // Task 0104 Design 4: the per-node ledger is the recovery source. Settled
225
+ // nodes keep their terminal status, terminal (done/paused) rows carry the
226
+ // accepted string setVars delta via outputVars, and everything else
227
+ // (running/pending rows, never-started nodes) re-enters via the deps rule.
75
228
  const snapshot = await this.options.persistence.loadLatestStateSnapshot(runId);
76
- let transitionsTaken = snapshotTransitions(snapshot?.data);
77
- if (snapshot?.data?.effectiveVars && typeof snapshot.data.effectiveVars === 'object') {
78
- vars = mergeVars(vars, snapshot.data.effectiveVars as Vars);
79
- }
80
-
81
- const nodeStatuses = new Map<string, DagNodeStatus>();
82
- // If resuming, determine if any node was already paused or completed
83
- const pausedNodeId = snapshot?.state;
84
-
85
- // Seed from the durable per-node ledger (task 0101): settled nodes are never
86
- // re-dispatched. 'cancelled' rows are condition-skipped nodes; 'paused'/'running'/
87
- // 'pending' rows fall through to the dependsOn rule so interrupted nodes re-run.
88
229
  const priorRows = await this.options.persistence.listRunBranches(runId, DAG_LEDGER_NAMESPACE);
89
- const priorByNode = new Map(priorRows.map((r) => [r.branch_id, r.status]));
230
+ const rowByNode = new Map(priorRows.map((row) => [row.branch_id, row]));
90
231
 
232
+ const nodeStatuses = new Map<string, DagNodeStatus>();
233
+ const nodeDeltas = new Map<string, Vars>();
234
+ let transitionsTaken = 0; // task 0104 Design 5: distinct completed nodes, recounted from the ledger
91
235
  for (const node of workflow.nodes) {
92
236
  const deps = node.dependsOn ?? [];
93
- const prior = priorByNode.get(node.id);
94
- if (prior === 'done') {
237
+ const prior = rowByNode.get(node.id);
238
+ const priorStatus = prior?.status;
239
+ if (priorStatus === 'done') {
95
240
  nodeStatuses.set(node.id, 'done');
96
- } else if (prior === 'cancelled') {
241
+ transitionsTaken++;
242
+ nodeDeltas.set(node.id, parseBranchDelta(prior?.output_vars_json ?? null, node.id));
243
+ } else if (priorStatus === 'paused') {
244
+ nodeStatuses.set(node.id, 'paused');
245
+ transitionsTaken++;
246
+ nodeDeltas.set(node.id, parseBranchDelta(prior?.output_vars_json ?? null, node.id));
247
+ } else if (priorStatus === 'cancelled') {
97
248
  nodeStatuses.set(node.id, 'skipped');
98
- } else if (prior === 'failed') {
249
+ } else if (priorStatus === 'failed') {
99
250
  nodeStatuses.set(node.id, 'failed');
100
- } else if (pausedNodeId && node.id === pausedNodeId) {
101
- nodeStatuses.set(node.id, 'done');
102
251
  } else {
103
252
  nodeStatuses.set(node.id, deps.length === 0 ? 'ready' : 'pending');
104
253
  }
105
254
  }
106
255
 
256
+ // Terminal deltas merge in stable topological order (task 0104 Design 4):
257
+ // declared order among equally ready nodes, so collisions resolve
258
+ // deterministically. Precedence: workflow defaults → snapshot baseline →
259
+ // ledger deltas → caller options.vars.
260
+ let ledgerDelta: Vars = {};
261
+ for (const nodeId of dagTopoOrder(workflow.nodes)) {
262
+ const delta = nodeDeltas.get(nodeId);
263
+ if (delta !== undefined) ledgerDelta = mergeVars(ledgerDelta, delta);
264
+ }
265
+ // 1. workflow defaults → 2. snapshot baseline → 3. ledger deltas → 4. caller.
266
+ let vars = workflow.vars ?? {};
267
+ if (snapshot?.data?.effectiveVars && typeof snapshot.data.effectiveVars === 'object') {
268
+ vars = mergeVars(vars, snapshot.data.effectiveVars as Vars);
269
+ }
270
+ vars = mergeVars(vars, ledgerDelta);
271
+ vars = mergeVars(vars, options.vars);
272
+ // Task 0104 Design 1: persist a ledger-derived anchor so a crash right
273
+ // after the ownership claim still leaves a recoverable checkpoint. Fresh
274
+ // runs anchor at the first declared node; interrupted runs without a
275
+ // snapshot derive their anchor from the ledger (after the CAS).
276
+ if (!options.dryRun && snapshot === undefined && workflow.nodes.length > 0) {
277
+ const declaredAnchor = workflow.nodes[0]?.id;
278
+ const anchor =
279
+ priorRows.length > 0
280
+ ? deriveDagResumeAnchor(workflow.nodes, new Map(priorRows.map((r) => [r.branch_id, r.status])))
281
+ : declaredAnchor;
282
+ if (anchor !== undefined) {
283
+ await this.options.persistence.saveWorkflowState(runId, anchor, {
284
+ effectiveVars: vars,
285
+ transitionsTaken,
286
+ });
287
+ }
288
+ }
289
+
290
+ // Task 0104 Design 7: acknowledge exactly one paused node before the wave
291
+ // loop. The target is the snapshot anchor when it names a paused row,
292
+ // otherwise the first paused row in declaration order (interrupted recovery).
293
+ const snapshotState = snapshot?.state;
294
+ let pausedTarget: string | undefined;
295
+ if (snapshotState !== undefined && rowByNode.get(snapshotState)?.status === 'paused') {
296
+ pausedTarget = snapshotState;
297
+ } else {
298
+ pausedTarget = workflow.nodes.find((node) => rowByNode.get(node.id)?.status === 'paused')?.id;
299
+ }
300
+ let rerunPauseBypass: string | undefined;
301
+ if (pausedTarget !== undefined) {
302
+ const targetNode = workflow.nodes.find((node) => node.id === pausedTarget);
303
+ if (options.resumeMode === 'rerun-enter') {
304
+ if (targetNode?.resumeRerun !== true) {
305
+ throw new FSMError(
306
+ `Cannot rerun-resume into "${pausedTarget}": not marked resumeRerun: true ` +
307
+ '(mark it safe to re-run — idempotent or deduped — or resume with resumeMode: "skip-enter")',
308
+ );
309
+ }
310
+ rerunPauseBypass = pausedTarget;
311
+ nodeStatuses.set(pausedTarget, 'ready');
312
+ } else {
313
+ // skip-enter: the paused action is accepted as complete — settle its
314
+ // row done with the existing delta before allowing dependents.
315
+ if (!options.dryRun) {
316
+ await this.options.persistence.saveBranchFinalize(
317
+ runId,
318
+ pausedTarget,
319
+ 'done',
320
+ 0,
321
+ nodeDeltas.get(pausedTarget),
322
+ );
323
+ }
324
+ nodeStatuses.set(pausedTarget, 'done');
325
+ }
326
+ }
327
+
107
328
  const checkDependenciesSatisfied = (node: DagNodeDef): { ready: boolean; shouldSkip: boolean } => {
108
329
  const deps = node.dependsOn ?? [];
109
330
  if (deps.length === 0) return { ready: true, shouldSkip: false };
@@ -139,145 +360,221 @@ export class DagDriver {
139
360
  return { ready: false, shouldSkip: false };
140
361
  };
141
362
 
142
- let pausedNode: string | undefined;
143
363
  let failureError: string | undefined;
144
364
 
145
- while (true) {
146
- // Find nodes ready to run
147
- const readyNodes: DagNodeDef[] = [];
148
- for (const node of workflow.nodes) {
149
- const status = nodeStatuses.get(node.id);
150
- if (status === 'pending') {
151
- const check = checkDependenciesSatisfied(node);
152
- if (check.shouldSkip) {
153
- nodeStatuses.set(node.id, 'skipped');
154
- } else if (check.ready) {
155
- nodeStatuses.set(node.id, 'ready');
156
- readyNodes.push(node);
157
- }
158
- } else if (status === 'ready') {
159
- readyNodes.push(node);
160
- }
161
- }
365
+ // Task 0105: completion-driven admission replaces fixed waves. A newly
366
+ // eligible child is admitted as soon as its prerequisites' entire node
367
+ // promises (condition → action → audit → terminal branch write) settle —
368
+ // not when an unrelated in-flight sibling settles. Loop-local state only.
369
+ type NodeStepResult = { id: string; status: 'done' | 'failed' | 'paused' | 'skipped'; error?: string };
370
+ type NodeOutcome =
371
+ | { kind: 'fulfilled'; id: string; index: number; result: NodeStepResult }
372
+ | { kind: 'rejected'; id: string; index: number; reason: unknown };
373
+ const inFlight = new Map<string, { index: number; tracking: Promise<void> }>();
374
+ const settlements: NodeOutcome[] = [];
375
+ const outcomes: (NodeOutcome | undefined)[] = new Array(workflow.nodes.length).fill(undefined);
376
+ let stopAdmission = false;
377
+ let coordinatorCaught = false;
378
+ let coordinatorError: unknown;
162
379
 
163
- if (readyNodes.length === 0) {
164
- break;
380
+ // Whole-node execution. Readiness publishes only when this promise
381
+ // settles, so a successful host return alone never dispatches a child.
382
+ const executeNode = async (node: DagNodeDef): Promise<NodeStepResult> => {
383
+ // Ledger rows make per-node completion durable; dryRun executes nothing and records nothing.
384
+ const nodeStartMs = Date.now();
385
+ if (!options.dryRun) {
386
+ await this.options.persistence.saveBranchStart(runId, DAG_LEDGER_NAMESPACE, node.id, node.id);
165
387
  }
166
388
 
167
- // Dispatch ready nodes concurrently
168
- const results = await Promise.all(
169
- readyNodes.map(async (node) => {
170
- nodeStatuses.set(node.id, 'running');
171
- // Ledger rows make per-node completion durable; dryRun executes nothing and records nothing.
172
- const nodeStartMs = Date.now();
389
+ // Check condition if declared
390
+ if (node.condition) {
391
+ const resolvedOptions =
392
+ node.condition.kind === 'shell'
393
+ ? resolveShellCommandTemplates(node.condition.options ?? {}, { vars, env })
394
+ : resolveTemplates(node.condition.options ?? {}, { vars, env });
395
+ const passed = await this.options.host.evaluateGuard(node.condition.kind, resolvedOptions, {
396
+ runId,
397
+ current: node.id,
398
+ vars,
399
+ env,
400
+ workdir: options.workdir,
401
+ });
402
+ if (!passed) {
403
+ // BranchStatus has no 'skipped'; 'cancelled' marks settled-without-running.
173
404
  if (!options.dryRun) {
174
- await this.options.persistence.saveBranchStart(runId, DAG_LEDGER_NAMESPACE, node.id, node.id);
175
- }
176
-
177
- // Check condition if declared
178
- if (node.condition) {
179
- const resolvedOptions =
180
- node.condition.kind === 'shell'
181
- ? resolveShellCommandTemplates(node.condition.options ?? {}, { vars, env })
182
- : resolveTemplates(node.condition.options ?? {}, { vars, env });
183
- const passed = await this.options.host.evaluateGuard(node.condition.kind, resolvedOptions, {
405
+ await this.options.persistence.saveBranchFinalize(
184
406
  runId,
185
- current: node.id,
186
- vars,
187
- env,
188
- workdir: options.workdir,
189
- });
190
- if (!passed) {
191
- nodeStatuses.set(node.id, 'skipped');
192
- // BranchStatus has no 'skipped'; 'cancelled' marks settled-without-running.
193
- if (!options.dryRun) {
194
- await this.options.persistence.saveBranchFinalize(
195
- runId,
196
- node.id,
197
- 'cancelled',
198
- Date.now() - nodeStartMs,
199
- );
200
- }
201
- return { id: node.id, status: 'skipped' as const };
202
- }
407
+ node.id,
408
+ 'cancelled',
409
+ Date.now() - nodeStartMs,
410
+ );
203
411
  }
412
+ return { id: node.id, status: 'skipped' as const };
413
+ }
414
+ }
204
415
 
205
- if (node.pause === true) {
206
- nodeStatuses.set(node.id, 'paused');
207
- if (!options.dryRun) {
208
- await this.options.persistence.saveBranchFinalize(
209
- runId,
210
- node.id,
211
- 'paused',
212
- Date.now() - nodeStartMs,
213
- );
214
- }
215
- return { id: node.id, status: 'paused' as const };
216
- }
416
+ // Task 0104 Design 8: the ordinary pause check moved after action
417
+ // execution — a pause node with an action completes the action and
418
+ // its audit chain first, persists its accepted delta as a 'paused'
419
+ // row, and only then surfaces the pause result. Fail outcomes and
420
+ // thrown guard/persistence exceptions still outrank pause.
421
+ const isPauseNode = node.pause === true && node.id !== rerunPauseBypass;
217
422
 
218
- if (!options.dryRun && node.action) {
219
- const step = await runActionStep(node.action, vars, {
220
- host: this.options.host,
221
- persistence: this.options.persistence,
222
- lifecycle,
223
- workflowName: workflow.name,
224
- stateOrNodeId: node.id,
225
- runId,
226
- mode: 'dag',
227
- transitionsTaken,
228
- env,
229
- options,
230
- defaultOnError,
231
- });
232
- if (step.outcome === 'fail') {
233
- nodeStatuses.set(node.id, 'failed');
234
- if (!options.dryRun) {
235
- await this.options.persistence.saveBranchFinalize(
236
- runId,
237
- node.id,
238
- 'failed',
239
- Date.now() - nodeStartMs,
240
- undefined,
241
- step.result?.error ?? 'failed',
242
- );
243
- }
244
- return { id: node.id, status: 'failed' as const, error: step.result?.error ?? 'failed' };
245
- }
246
- if (step.result?.setVars) {
247
- vars = mergeSetVars(vars, step.result.setVars);
248
- }
249
- }
250
-
251
- nodeStatuses.set(node.id, 'done');
252
- transitionsTaken++;
423
+ let acceptedDelta: Vars | undefined;
424
+ if (!options.dryRun && node.action) {
425
+ const step = await runActionStep(node.action, vars, {
426
+ host: this.options.host,
427
+ persistence: this.options.persistence,
428
+ lifecycle,
429
+ workflowName: workflow.name,
430
+ stateOrNodeId: node.id,
431
+ runId,
432
+ mode: 'dag',
433
+ transitionsTaken,
434
+ env,
435
+ options,
436
+ defaultOnError,
437
+ });
438
+ if (step.outcome === 'fail') {
253
439
  if (!options.dryRun) {
254
440
  await this.options.persistence.saveBranchFinalize(
255
441
  runId,
256
442
  node.id,
257
- 'done',
443
+ 'failed',
258
444
  Date.now() - nodeStartMs,
445
+ undefined,
446
+ step.result?.error ?? 'failed',
259
447
  );
260
448
  }
261
- return { id: node.id, status: 'done' as const };
262
- }),
449
+ return { id: node.id, status: 'failed' as const, error: step.result?.error ?? 'failed' };
450
+ }
451
+ if (step.result?.setVars) {
452
+ acceptedDelta = pickStringEntries(step.result.setVars);
453
+ }
454
+ }
455
+
456
+ // Task 0104 R1: persist the accepted string setVars delta through
457
+ // outputVars so dependent resumes recover produced variables even
458
+ // without a snapshot. No-action nodes store an empty delta.
459
+ if (!options.dryRun) {
460
+ await this.options.persistence.saveBranchFinalize(
461
+ runId,
462
+ node.id,
463
+ isPauseNode ? 'paused' : 'done',
464
+ Date.now() - nodeStartMs,
465
+ acceptedDelta,
466
+ );
467
+ }
468
+ // Publish output/count only after the terminal ledger write succeeds.
469
+ vars = mergeSetVars(vars, acceptedDelta ?? {});
470
+ if (!nodeDeltas.has(node.id)) transitionsTaken++;
471
+ if (isPauseNode) {
472
+ return { id: node.id, status: 'paused' as const };
473
+ }
474
+ return { id: node.id, status: 'done' as const };
475
+ };
476
+
477
+ const admit = (node: DagNodeDef, index: number): void => {
478
+ // Synchronous reservation before any await: exactly-once admission.
479
+ nodeStatuses.set(node.id, 'running');
480
+ const tracking = executeNode(node).then(
481
+ (result) => {
482
+ nodeStatuses.set(node.id, result.status);
483
+ settlements.push({ kind: 'fulfilled', id: node.id, index, result });
484
+ if (result.status === 'failed' || result.status === 'paused') stopAdmission = true;
485
+ },
486
+ (reason) => {
487
+ // The observer swallows the rejection; the discriminator
488
+ // carries it (never filter by truthiness). No raw
489
+ // rejection is ever left unobserved.
490
+ settlements.push({ kind: 'rejected', id: node.id, index, reason });
491
+ stopAdmission = true;
492
+ },
263
493
  );
494
+ inFlight.set(node.id, { index, tracking });
495
+ };
264
496
 
265
- // Check if any failed or paused
266
- for (const res of results) {
267
- if (res.status === 'failed') {
268
- failureError = res.error;
269
- } else if (res.status === 'paused') {
270
- pausedNode = res.id;
271
- }
497
+ const consumeSettlements = (): void => {
498
+ while (settlements.length > 0) {
499
+ const outcome = settlements.shift();
500
+ if (outcome === undefined) continue;
501
+ inFlight.delete(outcome.id);
502
+ outcomes[outcome.index] = outcome;
272
503
  }
504
+ };
273
505
 
274
- if (failureError) {
275
- return await lifecycle.fail('dag', transitionsTaken, failureError);
506
+ const drainInFlight = async (): Promise<void> => {
507
+ if (inFlight.size > 0) {
508
+ await Promise.allSettled(Array.from(inFlight.values()).map((entry) => entry.tracking));
276
509
  }
510
+ consumeSettlements();
511
+ };
512
+
513
+ try {
514
+ while (true) {
515
+ if (stopAdmission) {
516
+ // Terminal outcome observed: admit nothing new; every admitted
517
+ // node's full chain settles before routing (drain barrier).
518
+ await drainInFlight();
519
+ break;
520
+ }
521
+ consumeSettlements();
277
522
 
278
- if (pausedNode) {
279
- return await lifecycle.pause(pausedNode, transitionsTaken, vars);
523
+ // Readiness + skip propagation to a fixed point (declaration
524
+ // order), so backward-declared all-skipped chains settle.
525
+ let changed = true;
526
+ while (changed) {
527
+ changed = false;
528
+ for (const [index, node] of workflow.nodes.entries()) {
529
+ const status = nodeStatuses.get(node.id);
530
+ if (status === 'ready') {
531
+ admit(node, index);
532
+ changed = true;
533
+ } else if (status === 'pending') {
534
+ const check = checkDependenciesSatisfied(node);
535
+ if (check.shouldSkip) {
536
+ nodeStatuses.set(node.id, 'skipped');
537
+ changed = true;
538
+ } else if (check.ready) {
539
+ admit(node, index);
540
+ changed = true;
541
+ }
542
+ }
543
+ }
544
+ }
545
+ if (stopAdmission) continue;
546
+ if (inFlight.size === 0) break;
547
+ // Race is notification only — routing happens at the loop top,
548
+ // after re-checking the queue and the stop flag, so simultaneous
549
+ // fatal outcomes cannot be bypassed by a success.
550
+ await Promise.race(Array.from(inFlight.values()).map((entry) => entry.tracking));
280
551
  }
552
+ } catch (error) {
553
+ // Coordinator/checkpoint exception: drain admitted work, retain its
554
+ // outcomes, and let unified routing below compose the reasons.
555
+ coordinatorCaught = true;
556
+ coordinatorError = error;
557
+ await drainInFlight();
558
+ }
559
+
560
+ // Task 0103 R2 contract on the completion-driven scheduler: node
561
+ // exceptions outrank fulfilled fail-policy results, which outrank
562
+ // pauses. Outcomes are retained by declaration index, so iteration
563
+ // order IS declaration order.
564
+ const nodeReasons: unknown[] = [];
565
+ for (const outcome of outcomes) {
566
+ if (outcome === undefined) continue;
567
+ if (outcome.kind === 'rejected') nodeReasons.push(outcome.reason);
568
+ else if (outcome.result.status === 'failed') failureError = outcome.result.error;
569
+ }
570
+ if (nodeReasons.length === 1 && !coordinatorCaught) {
571
+ throw nodeReasons[0];
572
+ }
573
+ if (nodeReasons.length === 0 && coordinatorCaught) throw coordinatorError;
574
+ if (nodeReasons.length > 0 || coordinatorCaught) {
575
+ const reasons = [...nodeReasons];
576
+ if (coordinatorCaught) reasons.push(coordinatorError);
577
+ throw new AggregateError(reasons, 'DAG node execution failed');
281
578
  }
282
579
 
283
580
  // Final completion check
@@ -286,6 +583,14 @@ export class DagDriver {
286
583
  return await lifecycle.fail('dag', transitionsTaken, failureError ?? 'dag-failed');
287
584
  }
288
585
 
586
+ // Task 0104 Design 7: paused rows other than the acknowledged target stay
587
+ // barriers — surface the next outstanding pause (declaration order) once
588
+ // admitted work has drained, instead of reporting done early.
589
+ const nextPaused = workflow.nodes.find((node) => nodeStatuses.get(node.id) === 'paused');
590
+ if (nextPaused !== undefined) {
591
+ return await lifecycle.pause(nextPaused.id, transitionsTaken, vars);
592
+ }
593
+
289
594
  // Never report done while a node is stranded (task 0101 R3): unreachable = loud failure.
290
595
  const stuck = workflow.nodes.filter((n) => nodeStatuses.get(n.id) === 'pending').map((n) => n.id);
291
596
  if (stuck.length > 0) {