@gobing-ai/ts-dual-workflow-engine 0.5.17 → 0.5.19

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/README.md CHANGED
@@ -164,6 +164,24 @@ erDiagram
164
164
  | `transition-flow` | `TransitionFlowDriver` | Single-cursor node/edge walk; declared fork/join regions run branches concurrently |
165
165
  | `dag` | `DagDriver` | Nodes dispatch as their `dependsOn` prerequisites settle; acyclic only (ADR-034) |
166
166
 
167
+ Structured parallel nodes declare `branches` and a `join` target. Branches keep isolated variable
168
+ deltas; paused branches resume from their saved node without replaying completed siblings. With
169
+ `failurePolicy: 'collect'`, the join action runs with merged outputs before aggregate failure is
170
+ recorded; `fail-fast` cancels active siblings. Branch checkpoints and join commits use the run's
171
+ owner-attempt fence. `saveBranchFinalize` accepts an optional checkpoint with `parallelNode`, `node`,
172
+ and `ownerAttempt`; `commitJoin` accepts optional owner-attempt, transition-count and collected-failure
173
+ arguments. Collected failure is preserved across restart at the join.
174
+
175
+ DAG nodes publish completion and string variable deltas only after their action audit and terminal
176
+ ledger write settle. Recovery uses the `__dag__` ledger: completed actions stay completed, and
177
+ `transitionsTaken` counts distinct done/paused nodes without counting acknowledgements or replays twice.
178
+ Recovered variables merge in this order: workflow defaults, snapshot baseline, completed-node deltas
179
+ in stable topological order (declaration order breaks ties), then caller overrides. Live sibling
180
+ collisions follow durable completion order. A pause action completes before acknowledgement;
181
+ `skip-enter` acknowledges it once, while `rerun-enter` requires that node's `resumeRerun: true` marker.
182
+ Every previously unfinished action needs its own marker for replay. Recovery is at least once for
183
+ action effects not yet durably recorded; stop or reconcile the previous owner before resuming.
184
+
167
185
  All three delegate run identity, persistence sequencing, and observability to `RunLifecycle`:
168
186
 
169
187
  ```
package/dist/config.js CHANGED
@@ -206,7 +206,7 @@ function validateTransitionFlow(workflow) {
206
206
  if (visited.has(currentId))
207
207
  return;
208
208
  const currentNode = nodeMap.get(currentId);
209
- if (currentNode && currentNode.id !== node.id && currentNode.type === 'parallel') {
209
+ if (currentNode && currentNode.type === 'parallel') {
210
210
  errors.push(`Parallel node "${currentNode.id}" is nested inside parallel node "${node.id}" (nested parallel regions are forbidden)`);
211
211
  }
212
212
  visiting.add(currentId);
package/dist/dag.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { WorkflowEngineHost } from './host';
2
- import type { DagWorkflowDef, WorkflowPersistenceAdapter, WorkflowRunOptions, WorkflowRunResult } from './types';
2
+ import type { DagNodeDef, DagWorkflowDef, WorkflowBranchRecord, WorkflowPersistenceAdapter, WorkflowResumeMode, WorkflowRunOptions, WorkflowRunResult } from './types';
3
3
  /** Dependencies required by the static dependency DAG driver. */
4
4
  export interface DagDriverOptions {
5
5
  readonly host: WorkflowEngineHost;
@@ -7,6 +7,35 @@ export interface DagDriverOptions {
7
7
  }
8
8
  /** Execution status of a single DAG node within a run. */
9
9
  export type DagNodeStatus = 'pending' | 'ready' | 'running' | 'done' | 'failed' | 'skipped' | 'paused';
10
+ /**
11
+ * Stable topological order over declared nodes: repeatedly take the earliest
12
+ * declared node whose dependencies are all placed (declaration order breaks
13
+ * ties between equally ready nodes). Leftover nodes (validated-elsewhere
14
+ * cycles) keep declaration order. Task 0104 Design 4.
15
+ */
16
+ export declare function dagTopoOrder(nodes: readonly DagNodeDef[]): string[];
17
+ /**
18
+ * Ledger-derived resume anchor for runs without a snapshot (task 0104 Design 1):
19
+ * the first paused row in declaration order, otherwise the first unfinished
20
+ * declared row, otherwise the first declared node.
21
+ */
22
+ export declare function deriveDagResumeAnchor(nodes: readonly DagNodeDef[], statusByNode: ReadonlyMap<string, WorkflowBranchRecord['status']>): string | undefined;
23
+ /** Result of DAG resume admission checks (task 0104 Design 6). */
24
+ export interface DagResumeAdmission {
25
+ /** Declared node naming where the resumed run logically continues from. */
26
+ readonly anchor: string;
27
+ /** Paused node whose acknowledgement this resume performs, if any. */
28
+ readonly pausedTarget?: string;
29
+ }
30
+ /**
31
+ * DAG-only resume admission (task 0104 Design 6). Checks every previously
32
+ * unfinished (running/pending) action node: it may replay only under
33
+ * rerun-enter with its own resumeRerun marker — never-started nodes need no
34
+ * marker, done non-paused rows never replay. A paused anchor replays under
35
+ * rerun-enter only with its marker; skip-enter is always safe (acknowledgement).
36
+ * Exported for service.ts admission only — not part of the public package surface.
37
+ */
38
+ export declare function assertDagResumeAllowed(workflow: DagWorkflowDef, runId: string, persistence: WorkflowPersistenceAdapter, resumeMode: WorkflowResumeMode): Promise<DagResumeAdmission>;
10
39
  /**
11
40
  * Static dependency DAG workflow driver (task 0100, ADR-034).
12
41
  * Manages an in-process ready queue of runnable nodes, dispatching them as upstream
package/dist/dag.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"dag.d.ts","sourceRoot":"","sources":["../src/dag.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,QAAQ,CAAC;AAEjD,OAAO,KAAK,EAER,cAAc,EAEd,0BAA0B,EAC1B,kBAAkB,EAClB,iBAAiB,EACpB,MAAM,SAAS,CAAC;AAGjB,iEAAiE;AACjE,MAAM,WAAW,gBAAgB;IAC7B,QAAQ,CAAC,IAAI,EAAE,kBAAkB,CAAC;IAClC,QAAQ,CAAC,WAAW,EAAE,0BAA0B,CAAC;CACpD;AAED,0DAA0D;AAC1D,MAAM,MAAM,aAAa,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,GAAG,MAAM,GAAG,QAAQ,GAAG,SAAS,GAAG,QAAQ,CAAC;AAKvG;;;;;GAKG;AACH,qBAAa,SAAS;IACN,OAAO,CAAC,QAAQ,CAAC,OAAO;gBAAP,OAAO,EAAE,gBAAgB;IAEtD,2DAA2D;IACrD,GAAG,CAAC,QAAQ,EAAE,cAAc,EAAE,OAAO,GAAE,kBAAuB,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAUjG,wCAAwC;IAClC,MAAM,CACR,QAAQ,EAAE,cAAc,EACxB,KAAK,EAAE,MAAM,EACb,WAAW,EAAE,MAAM,GAAG,SAAS,EAC/B,OAAO,GAAE,kBAAuB,GACjC,OAAO,CAAC,iBAAiB,CAAC;YAYf,IAAI;CAyOrB"}
1
+ {"version":3,"file":"dag.d.ts","sourceRoot":"","sources":["../src/dag.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,QAAQ,CAAC;AAEjD,OAAO,KAAK,EACR,UAAU,EACV,cAAc,EAEd,oBAAoB,EACpB,0BAA0B,EAC1B,kBAAkB,EAClB,kBAAkB,EAClB,iBAAiB,EACpB,MAAM,SAAS,CAAC;AAGjB,iEAAiE;AACjE,MAAM,WAAW,gBAAgB;IAC7B,QAAQ,CAAC,IAAI,EAAE,kBAAkB,CAAC;IAClC,QAAQ,CAAC,WAAW,EAAE,0BAA0B,CAAC;CACpD;AAED,0DAA0D;AAC1D,MAAM,MAAM,aAAa,GAAG,SAAS,GAAG,OAAO,GAAG,SAAS,GAAG,MAAM,GAAG,QAAQ,GAAG,SAAS,GAAG,QAAQ,CAAC;AAKvG;;;;;GAKG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,SAAS,UAAU,EAAE,GAAG,MAAM,EAAE,CAenE;AAoCD;;;;GAIG;AACH,wBAAgB,qBAAqB,CACjC,KAAK,EAAE,SAAS,UAAU,EAAE,EAC5B,YAAY,EAAE,WAAW,CAAC,MAAM,EAAE,oBAAoB,CAAC,QAAQ,CAAC,CAAC,GAClE,MAAM,GAAG,SAAS,CASpB;AAED,kEAAkE;AAClE,MAAM,WAAW,kBAAkB;IAC/B,2EAA2E;IAC3E,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,sEAAsE;IACtE,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;CAClC;AAED;;;;;;;GAOG;AACH,wBAAsB,sBAAsB,CACxC,QAAQ,EAAE,cAAc,EACxB,KAAK,EAAE,MAAM,EACb,WAAW,EAAE,0BAA0B,EACvC,UAAU,EAAE,kBAAkB,GAC/B,OAAO,CAAC,kBAAkB,CAAC,CA0C7B;AAED;;;;;GAKG;AACH,qBAAa,SAAS;IACN,OAAO,CAAC,QAAQ,CAAC,OAAO;gBAAP,OAAO,EAAE,gBAAgB;IAEtD,2DAA2D;IACrD,GAAG,CAAC,QAAQ,EAAE,cAAc,EAAE,OAAO,GAAE,kBAAuB,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAUjG,wCAAwC;IAClC,MAAM,CACR,QAAQ,EAAE,cAAc,EACxB,KAAK,EAAE,MAAM,EACb,WAAW,EAAE,MAAM,GAAG,SAAS,EAC/B,OAAO,GAAE,kBAAuB,GACjC,OAAO,CAAC,iBAAiB,CAAC;YAmBf,IAAI;CAmYrB"}
package/dist/dag.js CHANGED
@@ -1,8 +1,126 @@
1
1
  import { runActionStep } from './action-step.js';
2
- import { allowedEnv, RunLifecycle, snapshotTransitions } from './run-lifecycle.js';
2
+ import { FSMError, WorkflowResumeError } from './errors.js';
3
+ import { allowedEnv, RunLifecycle } from './run-lifecycle.js';
3
4
  import { mergeSetVars, mergeVars, resolveShellCommandTemplates, resolveTemplates } from './variables.js';
4
5
  // Reserved parallel_node namespace reusing the 0094 branch ledger for per-node DAG execution records.
5
6
  const DAG_LEDGER_NAMESPACE = '__dag__';
7
+ /**
8
+ * Stable topological order over declared nodes: repeatedly take the earliest
9
+ * declared node whose dependencies are all placed (declaration order breaks
10
+ * ties between equally ready nodes). Leftover nodes (validated-elsewhere
11
+ * cycles) keep declaration order. Task 0104 Design 4.
12
+ */
13
+ export function dagTopoOrder(nodes) {
14
+ const placed = [];
15
+ const placedIds = new Set();
16
+ const remaining = [...nodes];
17
+ while (remaining.length > 0) {
18
+ const nextIdx = remaining.findIndex((node) => (node.dependsOn ?? []).every((dep) => placedIds.has(dep)));
19
+ if (nextIdx === -1)
20
+ break;
21
+ const node = remaining[nextIdx];
22
+ remaining.splice(nextIdx, 1);
23
+ if (node === undefined)
24
+ break;
25
+ placed.push(node.id);
26
+ placedIds.add(node.id);
27
+ }
28
+ for (const node of remaining)
29
+ placed.push(node.id);
30
+ return placed;
31
+ }
32
+ /** Keep only string→string entries, mirroring mergeSetVars' defensive filter. */
33
+ function pickStringEntries(setVars) {
34
+ const accepted = {};
35
+ for (const [key, value] of Object.entries(setVars)) {
36
+ if (typeof value === 'string')
37
+ accepted[key] = value;
38
+ }
39
+ return accepted;
40
+ }
41
+ /**
42
+ * Parse one persisted branch delta (task 0104 Design 4). A null payload is an
43
+ * empty legacy delta; malformed payloads fail loudly before any execution.
44
+ */
45
+ function parseBranchDelta(raw, nodeId) {
46
+ if (raw === null)
47
+ return {};
48
+ let parsed;
49
+ try {
50
+ parsed = JSON.parse(raw);
51
+ }
52
+ catch (error) {
53
+ throw new WorkflowResumeError(`DAG node "${nodeId}" has malformed persisted output: ${error.message}`);
54
+ }
55
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
56
+ throw new WorkflowResumeError(`DAG node "${nodeId}" has malformed persisted output: expected an object`);
57
+ }
58
+ for (const [key, value] of Object.entries(parsed)) {
59
+ if (typeof value !== 'string') {
60
+ throw new WorkflowResumeError(`DAG node "${nodeId}" persisted output "${key}" is not a string`);
61
+ }
62
+ }
63
+ return parsed;
64
+ }
65
+ /**
66
+ * Ledger-derived resume anchor for runs without a snapshot (task 0104 Design 1):
67
+ * the first paused row in declaration order, otherwise the first unfinished
68
+ * declared row, otherwise the first declared node.
69
+ */
70
+ export function deriveDagResumeAnchor(nodes, statusByNode) {
71
+ const firstPaused = nodes.find((node) => statusByNode.get(node.id) === 'paused')?.id;
72
+ if (firstPaused !== undefined)
73
+ return firstPaused;
74
+ const firstUnfinished = nodes.find((node) => {
75
+ const prior = statusByNode.get(node.id);
76
+ return prior === 'running' || prior === 'pending';
77
+ })?.id;
78
+ if (firstUnfinished !== undefined)
79
+ return firstUnfinished;
80
+ return nodes[0]?.id;
81
+ }
82
+ /**
83
+ * DAG-only resume admission (task 0104 Design 6). Checks every previously
84
+ * unfinished (running/pending) action node: it may replay only under
85
+ * rerun-enter with its own resumeRerun marker — never-started nodes need no
86
+ * marker, done non-paused rows never replay. A paused anchor replays under
87
+ * rerun-enter only with its marker; skip-enter is always safe (acknowledgement).
88
+ * Exported for service.ts admission only — not part of the public package surface.
89
+ */
90
+ export async function assertDagResumeAllowed(workflow, runId, persistence, resumeMode) {
91
+ const rows = await persistence.listRunBranches(runId, DAG_LEDGER_NAMESPACE);
92
+ const statusByNode = new Map(rows.map((row) => [row.branch_id, row.status]));
93
+ for (const node of workflow.nodes) {
94
+ const prior = statusByNode.get(node.id);
95
+ if ((prior === 'running' || prior === 'pending') && node.action) {
96
+ if (resumeMode !== 'rerun-enter' || node.resumeRerun !== true) {
97
+ throw new FSMError(`DAG node "${node.id}" has an unfinished action that is not marked resumeRerun: true — ` +
98
+ 'replaying it requires resumeMode: "rerun-enter" and its own resumeRerun marker');
99
+ }
100
+ }
101
+ }
102
+ const snapshot = await persistence.loadLatestStateSnapshot(runId);
103
+ const snapshotState = snapshot?.state;
104
+ if (snapshot === undefined && rows.length === 0) {
105
+ throw new WorkflowResumeError(`Run "${runId}" has no persisted DAG progress to resume from`);
106
+ }
107
+ const pausedTarget = snapshotState !== undefined && statusByNode.get(snapshotState) === 'paused'
108
+ ? snapshotState
109
+ : workflow.nodes.find((node) => statusByNode.get(node.id) === 'paused')?.id;
110
+ if (pausedTarget !== undefined && resumeMode === 'rerun-enter') {
111
+ const target = workflow.nodes.find((node) => node.id === pausedTarget);
112
+ if (target?.resumeRerun !== true) {
113
+ throw new FSMError(`Cannot rerun-resume into "${pausedTarget}": not marked resumeRerun: true ` +
114
+ '(mark it safe to re-run — idempotent or deduped — or resume with resumeMode: "skip-enter")');
115
+ }
116
+ }
117
+ const anchor = (snapshotState !== undefined && statusByNode.has(snapshotState) ? snapshotState : undefined) ??
118
+ deriveDagResumeAnchor(workflow.nodes, statusByNode);
119
+ if (anchor === undefined) {
120
+ throw new WorkflowResumeError(`Run "${runId}" cannot resume: the workflow declares no nodes`);
121
+ }
122
+ return { anchor, pausedTarget };
123
+ }
6
124
  /**
7
125
  * Static dependency DAG workflow driver (task 0100, ADR-034).
8
126
  * Manages an in-process ready queue of runnable nodes, dispatching them as upstream
@@ -20,46 +138,116 @@ export class DagDriver {
20
138
  }
21
139
  /** Resume a paused DAG workflow run. */
22
140
  async resume(workflow, runId, externalKey, options = {}) {
23
- return await RunLifecycle.resume(workflow.name, 'dag', { persistence: this.options.persistence, events: options.events }, runId, externalKey, (lifecycle) => this.loop(workflow, options, lifecycle), options.resumeOwner?.attemptId);
141
+ // Task 0104 Design 6: direct driver resume is admission-checked too.
142
+ // Resolve an absent resumeMode from the run's paused/interrupted status
143
+ // (matching service.resumeRun's 0902 defaults) before dispatching.
144
+ const resumeMode = options.resumeMode ??
145
+ ((await this.options.persistence.loadRun(runId))?.status === 'interrupted' ? 'rerun-enter' : 'skip-enter');
146
+ await assertDagResumeAllowed(workflow, runId, this.options.persistence, resumeMode);
147
+ return await RunLifecycle.resume(workflow.name, 'dag', { persistence: this.options.persistence, events: options.events }, runId, externalKey, (lifecycle) => this.loop(workflow, { ...options, resumeMode }, lifecycle), options.resumeOwner?.attemptId);
24
148
  }
25
149
  async loop(workflow, options, lifecycle) {
26
150
  const runId = lifecycle.runId;
27
- let vars = mergeVars(workflow.vars, options.vars);
28
151
  const env = allowedEnv(workflow.env?.allow ?? [], options.env);
29
152
  const defaultOnError = workflow.defaultOnError;
30
- // Restore snapshot if resuming
153
+ // Task 0104 Design 4: the per-node ledger is the recovery source. Settled
154
+ // nodes keep their terminal status, terminal (done/paused) rows carry the
155
+ // accepted string setVars delta via outputVars, and everything else
156
+ // (running/pending rows, never-started nodes) re-enters via the deps rule.
31
157
  const snapshot = await this.options.persistence.loadLatestStateSnapshot(runId);
32
- let transitionsTaken = snapshotTransitions(snapshot?.data);
33
- if (snapshot?.data?.effectiveVars && typeof snapshot.data.effectiveVars === 'object') {
34
- vars = mergeVars(vars, snapshot.data.effectiveVars);
35
- }
36
- const nodeStatuses = new Map();
37
- // If resuming, determine if any node was already paused or completed
38
- const pausedNodeId = snapshot?.state;
39
- // Seed from the durable per-node ledger (task 0101): settled nodes are never
40
- // re-dispatched. 'cancelled' rows are condition-skipped nodes; 'paused'/'running'/
41
- // 'pending' rows fall through to the dependsOn rule so interrupted nodes re-run.
42
158
  const priorRows = await this.options.persistence.listRunBranches(runId, DAG_LEDGER_NAMESPACE);
43
- const priorByNode = new Map(priorRows.map((r) => [r.branch_id, r.status]));
159
+ const rowByNode = new Map(priorRows.map((row) => [row.branch_id, row]));
160
+ const nodeStatuses = new Map();
161
+ const nodeDeltas = new Map();
162
+ let transitionsTaken = 0; // task 0104 Design 5: distinct completed nodes, recounted from the ledger
44
163
  for (const node of workflow.nodes) {
45
164
  const deps = node.dependsOn ?? [];
46
- const prior = priorByNode.get(node.id);
47
- if (prior === 'done') {
165
+ const prior = rowByNode.get(node.id);
166
+ const priorStatus = prior?.status;
167
+ if (priorStatus === 'done') {
48
168
  nodeStatuses.set(node.id, 'done');
169
+ transitionsTaken++;
170
+ nodeDeltas.set(node.id, parseBranchDelta(prior?.output_vars_json ?? null, node.id));
49
171
  }
50
- else if (prior === 'cancelled') {
172
+ else if (priorStatus === 'paused') {
173
+ nodeStatuses.set(node.id, 'paused');
174
+ transitionsTaken++;
175
+ nodeDeltas.set(node.id, parseBranchDelta(prior?.output_vars_json ?? null, node.id));
176
+ }
177
+ else if (priorStatus === 'cancelled') {
51
178
  nodeStatuses.set(node.id, 'skipped');
52
179
  }
53
- else if (prior === 'failed') {
180
+ else if (priorStatus === 'failed') {
54
181
  nodeStatuses.set(node.id, 'failed');
55
182
  }
56
- else if (pausedNodeId && node.id === pausedNodeId) {
57
- nodeStatuses.set(node.id, 'done');
58
- }
59
183
  else {
60
184
  nodeStatuses.set(node.id, deps.length === 0 ? 'ready' : 'pending');
61
185
  }
62
186
  }
187
+ // Terminal deltas merge in stable topological order (task 0104 Design 4):
188
+ // declared order among equally ready nodes, so collisions resolve
189
+ // deterministically. Precedence: workflow defaults → snapshot baseline →
190
+ // ledger deltas → caller options.vars.
191
+ let ledgerDelta = {};
192
+ for (const nodeId of dagTopoOrder(workflow.nodes)) {
193
+ const delta = nodeDeltas.get(nodeId);
194
+ if (delta !== undefined)
195
+ ledgerDelta = mergeVars(ledgerDelta, delta);
196
+ }
197
+ // 1. workflow defaults → 2. snapshot baseline → 3. ledger deltas → 4. caller.
198
+ let vars = workflow.vars ?? {};
199
+ if (snapshot?.data?.effectiveVars && typeof snapshot.data.effectiveVars === 'object') {
200
+ vars = mergeVars(vars, snapshot.data.effectiveVars);
201
+ }
202
+ vars = mergeVars(vars, ledgerDelta);
203
+ vars = mergeVars(vars, options.vars);
204
+ // Task 0104 Design 1: persist a ledger-derived anchor so a crash right
205
+ // after the ownership claim still leaves a recoverable checkpoint. Fresh
206
+ // runs anchor at the first declared node; interrupted runs without a
207
+ // snapshot derive their anchor from the ledger (after the CAS).
208
+ if (!options.dryRun && snapshot === undefined && workflow.nodes.length > 0) {
209
+ const declaredAnchor = workflow.nodes[0]?.id;
210
+ const anchor = priorRows.length > 0
211
+ ? deriveDagResumeAnchor(workflow.nodes, new Map(priorRows.map((r) => [r.branch_id, r.status])))
212
+ : declaredAnchor;
213
+ if (anchor !== undefined) {
214
+ await this.options.persistence.saveWorkflowState(runId, anchor, {
215
+ effectiveVars: vars,
216
+ transitionsTaken,
217
+ });
218
+ }
219
+ }
220
+ // Task 0104 Design 7: acknowledge exactly one paused node before the wave
221
+ // loop. The target is the snapshot anchor when it names a paused row,
222
+ // otherwise the first paused row in declaration order (interrupted recovery).
223
+ const snapshotState = snapshot?.state;
224
+ let pausedTarget;
225
+ if (snapshotState !== undefined && rowByNode.get(snapshotState)?.status === 'paused') {
226
+ pausedTarget = snapshotState;
227
+ }
228
+ else {
229
+ pausedTarget = workflow.nodes.find((node) => rowByNode.get(node.id)?.status === 'paused')?.id;
230
+ }
231
+ let rerunPauseBypass;
232
+ if (pausedTarget !== undefined) {
233
+ const targetNode = workflow.nodes.find((node) => node.id === pausedTarget);
234
+ if (options.resumeMode === 'rerun-enter') {
235
+ if (targetNode?.resumeRerun !== true) {
236
+ throw new FSMError(`Cannot rerun-resume into "${pausedTarget}": not marked resumeRerun: true ` +
237
+ '(mark it safe to re-run — idempotent or deduped — or resume with resumeMode: "skip-enter")');
238
+ }
239
+ rerunPauseBypass = pausedTarget;
240
+ nodeStatuses.set(pausedTarget, 'ready');
241
+ }
242
+ else {
243
+ // skip-enter: the paused action is accepted as complete — settle its
244
+ // row done with the existing delta before allowing dependents.
245
+ if (!options.dryRun) {
246
+ await this.options.persistence.saveBranchFinalize(runId, pausedTarget, 'done', 0, nodeDeltas.get(pausedTarget));
247
+ }
248
+ nodeStatuses.set(pausedTarget, 'done');
249
+ }
250
+ }
63
251
  const checkDependenciesSatisfied = (node) => {
64
252
  const deps = node.dependsOn ?? [];
65
253
  if (deps.length === 0)
@@ -92,119 +280,205 @@ export class DagDriver {
92
280
  }
93
281
  return { ready: false, shouldSkip: false };
94
282
  };
95
- let pausedNode;
96
283
  let failureError;
97
- while (true) {
98
- // Find nodes ready to run
99
- const readyNodes = [];
100
- for (const node of workflow.nodes) {
101
- const status = nodeStatuses.get(node.id);
102
- if (status === 'pending') {
103
- const check = checkDependenciesSatisfied(node);
104
- if (check.shouldSkip) {
105
- nodeStatuses.set(node.id, 'skipped');
284
+ const inFlight = new Map();
285
+ const settlements = [];
286
+ const outcomes = new Array(workflow.nodes.length).fill(undefined);
287
+ let stopAdmission = false;
288
+ let coordinatorCaught = false;
289
+ let coordinatorError;
290
+ // Whole-node execution. Readiness publishes only when this promise
291
+ // settles, so a successful host return alone never dispatches a child.
292
+ const executeNode = async (node) => {
293
+ // Ledger rows make per-node completion durable; dryRun executes nothing and records nothing.
294
+ const nodeStartMs = Date.now();
295
+ if (!options.dryRun) {
296
+ await this.options.persistence.saveBranchStart(runId, DAG_LEDGER_NAMESPACE, node.id, node.id);
297
+ }
298
+ // Check condition if declared
299
+ if (node.condition) {
300
+ const resolvedOptions = node.condition.kind === 'shell'
301
+ ? resolveShellCommandTemplates(node.condition.options ?? {}, { vars, env })
302
+ : resolveTemplates(node.condition.options ?? {}, { vars, env });
303
+ const passed = await this.options.host.evaluateGuard(node.condition.kind, resolvedOptions, {
304
+ runId,
305
+ current: node.id,
306
+ vars,
307
+ env,
308
+ workdir: options.workdir,
309
+ });
310
+ if (!passed) {
311
+ // BranchStatus has no 'skipped'; 'cancelled' marks settled-without-running.
312
+ if (!options.dryRun) {
313
+ await this.options.persistence.saveBranchFinalize(runId, node.id, 'cancelled', Date.now() - nodeStartMs);
106
314
  }
107
- else if (check.ready) {
108
- nodeStatuses.set(node.id, 'ready');
109
- readyNodes.push(node);
315
+ return { id: node.id, status: 'skipped' };
316
+ }
317
+ }
318
+ // Task 0104 Design 8: the ordinary pause check moved after action
319
+ // execution — a pause node with an action completes the action and
320
+ // its audit chain first, persists its accepted delta as a 'paused'
321
+ // row, and only then surfaces the pause result. Fail outcomes and
322
+ // thrown guard/persistence exceptions still outrank pause.
323
+ const isPauseNode = node.pause === true && node.id !== rerunPauseBypass;
324
+ let acceptedDelta;
325
+ if (!options.dryRun && node.action) {
326
+ const step = await runActionStep(node.action, vars, {
327
+ host: this.options.host,
328
+ persistence: this.options.persistence,
329
+ lifecycle,
330
+ workflowName: workflow.name,
331
+ stateOrNodeId: node.id,
332
+ runId,
333
+ mode: 'dag',
334
+ transitionsTaken,
335
+ env,
336
+ options,
337
+ defaultOnError,
338
+ });
339
+ if (step.outcome === 'fail') {
340
+ if (!options.dryRun) {
341
+ await this.options.persistence.saveBranchFinalize(runId, node.id, 'failed', Date.now() - nodeStartMs, undefined, step.result?.error ?? 'failed');
110
342
  }
343
+ return { id: node.id, status: 'failed', error: step.result?.error ?? 'failed' };
111
344
  }
112
- else if (status === 'ready') {
113
- readyNodes.push(node);
345
+ if (step.result?.setVars) {
346
+ acceptedDelta = pickStringEntries(step.result.setVars);
114
347
  }
115
348
  }
116
- if (readyNodes.length === 0) {
117
- break;
349
+ // Task 0104 R1: persist the accepted string setVars delta through
350
+ // outputVars so dependent resumes recover produced variables even
351
+ // without a snapshot. No-action nodes store an empty delta.
352
+ if (!options.dryRun) {
353
+ await this.options.persistence.saveBranchFinalize(runId, node.id, isPauseNode ? 'paused' : 'done', Date.now() - nodeStartMs, acceptedDelta);
118
354
  }
119
- // Dispatch ready nodes concurrently
120
- const results = await Promise.all(readyNodes.map(async (node) => {
121
- nodeStatuses.set(node.id, 'running');
122
- // Ledger rows make per-node completion durable; dryRun executes nothing and records nothing.
123
- const nodeStartMs = Date.now();
124
- if (!options.dryRun) {
125
- await this.options.persistence.saveBranchStart(runId, DAG_LEDGER_NAMESPACE, node.id, node.id);
355
+ // Publish output/count only after the terminal ledger write succeeds.
356
+ vars = mergeSetVars(vars, acceptedDelta ?? {});
357
+ if (!nodeDeltas.has(node.id))
358
+ transitionsTaken++;
359
+ if (isPauseNode) {
360
+ return { id: node.id, status: 'paused' };
361
+ }
362
+ return { id: node.id, status: 'done' };
363
+ };
364
+ const admit = (node, index) => {
365
+ // Synchronous reservation before any await: exactly-once admission.
366
+ nodeStatuses.set(node.id, 'running');
367
+ const tracking = executeNode(node).then((result) => {
368
+ nodeStatuses.set(node.id, result.status);
369
+ settlements.push({ kind: 'fulfilled', id: node.id, index, result });
370
+ if (result.status === 'failed' || result.status === 'paused')
371
+ stopAdmission = true;
372
+ }, (reason) => {
373
+ // The observer swallows the rejection; the discriminator
374
+ // carries it (never filter by truthiness). No raw
375
+ // rejection is ever left unobserved.
376
+ settlements.push({ kind: 'rejected', id: node.id, index, reason });
377
+ stopAdmission = true;
378
+ });
379
+ inFlight.set(node.id, { index, tracking });
380
+ };
381
+ const consumeSettlements = () => {
382
+ while (settlements.length > 0) {
383
+ const outcome = settlements.shift();
384
+ if (outcome === undefined)
385
+ continue;
386
+ inFlight.delete(outcome.id);
387
+ outcomes[outcome.index] = outcome;
388
+ }
389
+ };
390
+ const drainInFlight = async () => {
391
+ if (inFlight.size > 0) {
392
+ await Promise.allSettled(Array.from(inFlight.values()).map((entry) => entry.tracking));
393
+ }
394
+ consumeSettlements();
395
+ };
396
+ try {
397
+ while (true) {
398
+ if (stopAdmission) {
399
+ // Terminal outcome observed: admit nothing new; every admitted
400
+ // node's full chain settles before routing (drain barrier).
401
+ await drainInFlight();
402
+ break;
126
403
  }
127
- // Check condition if declared
128
- if (node.condition) {
129
- const resolvedOptions = node.condition.kind === 'shell'
130
- ? resolveShellCommandTemplates(node.condition.options ?? {}, { vars, env })
131
- : resolveTemplates(node.condition.options ?? {}, { vars, env });
132
- const passed = await this.options.host.evaluateGuard(node.condition.kind, resolvedOptions, {
133
- runId,
134
- current: node.id,
135
- vars,
136
- env,
137
- workdir: options.workdir,
138
- });
139
- if (!passed) {
140
- nodeStatuses.set(node.id, 'skipped');
141
- // BranchStatus has no 'skipped'; 'cancelled' marks settled-without-running.
142
- if (!options.dryRun) {
143
- await this.options.persistence.saveBranchFinalize(runId, node.id, 'cancelled', Date.now() - nodeStartMs);
404
+ consumeSettlements();
405
+ // Readiness + skip propagation to a fixed point (declaration
406
+ // order), so backward-declared all-skipped chains settle.
407
+ let changed = true;
408
+ while (changed) {
409
+ changed = false;
410
+ for (const [index, node] of workflow.nodes.entries()) {
411
+ const status = nodeStatuses.get(node.id);
412
+ if (status === 'ready') {
413
+ admit(node, index);
414
+ changed = true;
144
415
  }
145
- return { id: node.id, status: 'skipped' };
146
- }
147
- }
148
- if (node.pause === true) {
149
- nodeStatuses.set(node.id, 'paused');
150
- if (!options.dryRun) {
151
- await this.options.persistence.saveBranchFinalize(runId, node.id, 'paused', Date.now() - nodeStartMs);
152
- }
153
- return { id: node.id, status: 'paused' };
154
- }
155
- if (!options.dryRun && node.action) {
156
- const step = await runActionStep(node.action, vars, {
157
- host: this.options.host,
158
- persistence: this.options.persistence,
159
- lifecycle,
160
- workflowName: workflow.name,
161
- stateOrNodeId: node.id,
162
- runId,
163
- mode: 'dag',
164
- transitionsTaken,
165
- env,
166
- options,
167
- defaultOnError,
168
- });
169
- if (step.outcome === 'fail') {
170
- nodeStatuses.set(node.id, 'failed');
171
- if (!options.dryRun) {
172
- await this.options.persistence.saveBranchFinalize(runId, node.id, 'failed', Date.now() - nodeStartMs, undefined, step.result?.error ?? 'failed');
416
+ else if (status === 'pending') {
417
+ const check = checkDependenciesSatisfied(node);
418
+ if (check.shouldSkip) {
419
+ nodeStatuses.set(node.id, 'skipped');
420
+ changed = true;
421
+ }
422
+ else if (check.ready) {
423
+ admit(node, index);
424
+ changed = true;
425
+ }
173
426
  }
174
- return { id: node.id, status: 'failed', error: step.result?.error ?? 'failed' };
175
- }
176
- if (step.result?.setVars) {
177
- vars = mergeSetVars(vars, step.result.setVars);
178
427
  }
179
428
  }
180
- nodeStatuses.set(node.id, 'done');
181
- transitionsTaken++;
182
- if (!options.dryRun) {
183
- await this.options.persistence.saveBranchFinalize(runId, node.id, 'done', Date.now() - nodeStartMs);
184
- }
185
- return { id: node.id, status: 'done' };
186
- }));
187
- // Check if any failed or paused
188
- for (const res of results) {
189
- if (res.status === 'failed') {
190
- failureError = res.error;
191
- }
192
- else if (res.status === 'paused') {
193
- pausedNode = res.id;
194
- }
195
- }
196
- if (failureError) {
197
- return await lifecycle.fail('dag', transitionsTaken, failureError);
198
- }
199
- if (pausedNode) {
200
- return await lifecycle.pause(pausedNode, transitionsTaken, vars);
429
+ if (stopAdmission)
430
+ continue;
431
+ if (inFlight.size === 0)
432
+ break;
433
+ // Race is notification only — routing happens at the loop top,
434
+ // after re-checking the queue and the stop flag, so simultaneous
435
+ // fatal outcomes cannot be bypassed by a success.
436
+ await Promise.race(Array.from(inFlight.values()).map((entry) => entry.tracking));
201
437
  }
202
438
  }
439
+ catch (error) {
440
+ // Coordinator/checkpoint exception: drain admitted work, retain its
441
+ // outcomes, and let unified routing below compose the reasons.
442
+ coordinatorCaught = true;
443
+ coordinatorError = error;
444
+ await drainInFlight();
445
+ }
446
+ // Task 0103 R2 contract on the completion-driven scheduler: node
447
+ // exceptions outrank fulfilled fail-policy results, which outrank
448
+ // pauses. Outcomes are retained by declaration index, so iteration
449
+ // order IS declaration order.
450
+ const nodeReasons = [];
451
+ for (const outcome of outcomes) {
452
+ if (outcome === undefined)
453
+ continue;
454
+ if (outcome.kind === 'rejected')
455
+ nodeReasons.push(outcome.reason);
456
+ else if (outcome.result.status === 'failed')
457
+ failureError = outcome.result.error;
458
+ }
459
+ if (nodeReasons.length === 1 && !coordinatorCaught) {
460
+ throw nodeReasons[0];
461
+ }
462
+ if (nodeReasons.length === 0 && coordinatorCaught)
463
+ throw coordinatorError;
464
+ if (nodeReasons.length > 0 || coordinatorCaught) {
465
+ const reasons = [...nodeReasons];
466
+ if (coordinatorCaught)
467
+ reasons.push(coordinatorError);
468
+ throw new AggregateError(reasons, 'DAG node execution failed');
469
+ }
203
470
  // Final completion check
204
471
  const anyFailed = Array.from(nodeStatuses.values()).some((s) => s === 'failed');
205
472
  if (anyFailed) {
206
473
  return await lifecycle.fail('dag', transitionsTaken, failureError ?? 'dag-failed');
207
474
  }
475
+ // Task 0104 Design 7: paused rows other than the acknowledged target stay
476
+ // barriers — surface the next outstanding pause (declaration order) once
477
+ // admitted work has drained, instead of reporting done early.
478
+ const nextPaused = workflow.nodes.find((node) => nodeStatuses.get(node.id) === 'paused');
479
+ if (nextPaused !== undefined) {
480
+ return await lifecycle.pause(nextPaused.id, transitionsTaken, vars);
481
+ }
208
482
  // Never report done while a node is stranded (task 0101 R3): unreachable = loud failure.
209
483
  const stuck = workflow.nodes.filter((n) => nodeStatuses.get(n.id) === 'pending').map((n) => n.id);
210
484
  if (stuck.length > 0) {