@gobing-ai/ts-dual-workflow-engine 0.4.69 → 0.5.1

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.
@@ -1,8 +1,9 @@
1
1
  import type { DbAdapter, DbBatchOp } from '@gobing-ai/ts-db';
2
2
  import { RunCollisionError } from './errors';
3
- import { WORKFLOW_ENGINE_SCHEMA_SQL } from './schema-sql';
3
+ import { WORKFLOW_ENGINE_MIGRATIONS_SQL, WORKFLOW_ENGINE_SCHEMA_SQL } from './schema-sql';
4
4
  import type {
5
5
  ActionRedactor,
6
+ ResumeOwnership,
6
7
  WorkflowPersistenceAdapter,
7
8
  WorkflowReseedResult,
8
9
  WorkflowRunRecord,
@@ -15,6 +16,17 @@ export async function applyWorkflowEngineSchema(db: DbAdapter): Promise<void> {
15
16
  const sql = statement.trim();
16
17
  if (sql.length > 0) await db.exec(sql);
17
18
  }
19
+ // Fresh databases already have the new columns (duplicate-column error → ignored);
20
+ // pre-0.5.0 databases get them via these guarded ALTERs.
21
+ for (const statement of WORKFLOW_ENGINE_MIGRATIONS_SQL.split(';')) {
22
+ const sql = statement.trim();
23
+ if (sql.length === 0) continue;
24
+ try {
25
+ await db.exec(sql);
26
+ } catch (error) {
27
+ if (!/duplicate column/i.test(String(error))) throw error;
28
+ }
29
+ }
18
30
  }
19
31
 
20
32
  /** Narrow to a non-array object record. */
@@ -70,8 +82,8 @@ export class DbWorkflowPersistenceAdapter implements WorkflowPersistenceAdapter
70
82
  if (existing !== undefined) throw new RunCollisionError(record.id);
71
83
  await this.ensureSchema();
72
84
  await this.db.run(
73
- `INSERT INTO runs (id, workflow_name, mode, status, external_key, started_at, completed_at, metadata_json, created_at, updated_at)
74
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
85
+ `INSERT INTO runs (id, workflow_name, mode, status, external_key, started_at, completed_at, metadata_json, owner_attempt, owner_pid, created_at, updated_at)
86
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
75
87
  record.id,
76
88
  record.workflow_name,
77
89
  record.mode,
@@ -80,6 +92,8 @@ export class DbWorkflowPersistenceAdapter implements WorkflowPersistenceAdapter
80
92
  record.started_at,
81
93
  record.completed_at,
82
94
  record.metadata_json,
95
+ record.owner_attempt ?? null,
96
+ record.owner_pid ?? null,
83
97
  Date.now(),
84
98
  Date.now(),
85
99
  );
@@ -96,6 +110,40 @@ export class DbWorkflowPersistenceAdapter implements WorkflowPersistenceAdapter
96
110
  );
97
111
  }
98
112
 
113
+ /** CAS-claim a resumable run to running, recording the owner at the mutation. */
114
+ async claimRunOwnership(
115
+ runId: string,
116
+ owner: ResumeOwnership,
117
+ expectedStatuses: readonly ('paused' | 'interrupted')[],
118
+ ): Promise<WorkflowRunRecord | undefined> {
119
+ await this.ensureSchema();
120
+ const placeholders = expectedStatuses.map(() => '?').join(', ');
121
+ await this.db.run(
122
+ `UPDATE runs SET status = 'running', completed_at = NULL, owner_attempt = ?, owner_pid = ?, updated_at = ?
123
+ WHERE id = ? AND status IN (${placeholders})`,
124
+ owner.attemptId,
125
+ owner.pid ?? null,
126
+ Date.now(),
127
+ runId,
128
+ ...expectedStatuses,
129
+ );
130
+ const run = await this.loadRun(runId);
131
+ return run !== undefined && run.status === 'running' && run.owner_attempt === owner.attemptId ? run : undefined;
132
+ }
133
+
134
+ /** CAS running → interrupted with a reason (lost-owner / crash reconciliation). */
135
+ async interruptRun(runId: string, reason: string): Promise<WorkflowRunRecord | undefined> {
136
+ await this.ensureSchema();
137
+ await this.db.run(
138
+ "UPDATE runs SET status = 'interrupted', interrupt_reason = ?, completed_at = NULL, updated_at = ? WHERE id = ? AND status = 'running'",
139
+ reason,
140
+ Date.now(),
141
+ runId,
142
+ );
143
+ const run = await this.loadRun(runId);
144
+ return run !== undefined && run.status === 'interrupted' ? run : undefined;
145
+ }
146
+
99
147
  /** Save one phase/state execution record. */
100
148
  async savePhase(runId: string, phase: string, status: WorkflowStatus): Promise<void> {
101
149
  const op = this.phaseRow(runId, phase, status, Date.now());
@@ -256,14 +304,14 @@ export class DbWorkflowPersistenceAdapter implements WorkflowPersistenceAdapter
256
304
  /** Create a run or attach to an existing one by external key. */
257
305
  async createOrAttachRun(record: WorkflowRunRecord): Promise<WorkflowRunRecord> {
258
306
  await this.ensureSchema();
259
- if (record.external_key) {
307
+ if (record.external_key !== undefined && record.external_key !== null) {
260
308
  const existing = await this.findRunByKey(record.workflow_name, record.external_key);
261
309
  if (existing) return existing;
262
310
  }
263
311
  try {
264
312
  await this.createRun(record);
265
313
  } catch (error) {
266
- if (record.external_key) {
314
+ if (record.external_key !== undefined && record.external_key !== null) {
267
315
  const existing = await this.findRunByKey(record.workflow_name, record.external_key);
268
316
  if (existing) return existing;
269
317
  }
@@ -352,6 +400,40 @@ export class MemoryWorkflowPersistenceAdapter implements WorkflowPersistenceAdap
352
400
  if (run !== undefined) this.runs.set(runId, { ...run, status, completed_at: completedAt });
353
401
  }
354
402
 
403
+ /** CAS-claim a resumable run to running, recording the owner at the mutation. */
404
+ async claimRunOwnership(
405
+ runId: string,
406
+ owner: ResumeOwnership,
407
+ expectedStatuses: readonly ('paused' | 'interrupted')[],
408
+ ): Promise<WorkflowRunRecord | undefined> {
409
+ const run = this.runs.get(runId);
410
+ if (run === undefined || !expectedStatuses.includes(run.status as 'paused' | 'interrupted')) {
411
+ return undefined;
412
+ }
413
+ const claimed: WorkflowRunRecord = {
414
+ ...run,
415
+ status: 'running',
416
+ completed_at: null,
417
+ owner_attempt: owner.attemptId,
418
+ owner_pid: owner.pid ?? null,
419
+ };
420
+ this.runs.set(runId, claimed);
421
+ return claimed;
422
+ }
423
+
424
+ /** CAS running → interrupted with a reason (lost-owner / crash reconciliation). */
425
+ async interruptRun(runId: string, reason: string): Promise<WorkflowRunRecord | undefined> {
426
+ const run = this.runs.get(runId);
427
+ if (run === undefined || run.status !== 'running') return undefined;
428
+ const interrupted: WorkflowRunRecord = {
429
+ ...run,
430
+ status: 'interrupted',
431
+ interrupt_reason: reason,
432
+ };
433
+ this.runs.set(runId, interrupted);
434
+ return interrupted;
435
+ }
436
+
355
437
  readonly actionRuns: Array<{
356
438
  id: string;
357
439
  runId: string;
@@ -454,11 +536,16 @@ export class MemoryWorkflowPersistenceAdapter implements WorkflowPersistenceAdap
454
536
 
455
537
  /** Create a run or attach to an existing one by external key. */
456
538
  async createOrAttachRun(record: WorkflowRunRecord): Promise<WorkflowRunRecord> {
457
- if (record.external_key) {
458
- const existing = await this.findRunByKey(record.workflow_name, record.external_key);
459
- if (existing) return existing;
539
+ // Keep lookup and insertion in one synchronous turn, matching the DB unique constraint.
540
+ if (record.external_key !== undefined && record.external_key !== null) {
541
+ for (const existing of this.runs.values()) {
542
+ if (existing.workflow_name === record.workflow_name && existing.external_key === record.external_key) {
543
+ return existing;
544
+ }
545
+ }
460
546
  }
461
- await this.createRun(record);
547
+ if (this.runs.has(record.id)) throw new RunCollisionError(record.id);
548
+ this.runs.set(record.id, record);
462
549
  return { ...record };
463
550
  }
464
551
 
@@ -9,6 +9,7 @@ import {
9
9
  import { getProcessEnv } from '@gobing-ai/ts-runtime';
10
10
  import type { WorkflowEngineEvents } from './events';
11
11
  import type {
12
+ ActionResult,
12
13
  Vars,
13
14
  WorkflowPersistenceAdapter,
14
15
  WorkflowRunOptions,
@@ -136,19 +137,36 @@ export class RunLifecycle {
136
137
  'workflow.run',
137
138
  async () => {
138
139
  const startedAt = new Date().toISOString();
139
- const proposed = RunLifecycle.runRecord(
140
- options.runId ?? crypto.randomUUID(),
141
- workflowName,
142
- mode,
143
- startedAt,
144
- options.metadata,
145
- options.externalKey,
146
- );
140
+ const proposed: WorkflowRunRecord = {
141
+ ...RunLifecycle.runRecord(
142
+ options.runId ?? crypto.randomUUID(),
143
+ workflowName,
144
+ mode,
145
+ startedAt,
146
+ options.metadata,
147
+ options.externalKey,
148
+ ),
149
+ owner_attempt: crypto.randomUUID(),
150
+ };
147
151
  let record = proposed;
148
152
  if (options.externalKey === undefined) {
149
153
  await deps.persistence.createRun(proposed);
150
154
  } else {
151
155
  record = await deps.persistence.createOrAttachRun(proposed);
156
+ if (record.owner_attempt !== proposed.owner_attempt) {
157
+ const snapshot = await deps.persistence.loadLatestStateSnapshot(record.id);
158
+ return {
159
+ runId: record.id,
160
+ workflowName: record.workflow_name,
161
+ mode:
162
+ record.mode === 'transition-flow'
163
+ ? ('transition-flow' as const)
164
+ : ('state-machine' as const),
165
+ status: record.status,
166
+ finalState: snapshot?.state ?? '',
167
+ transitionsTaken: snapshotTransitions(snapshot?.data),
168
+ };
169
+ }
152
170
  }
153
171
  const extKey = record.external_key ?? undefined;
154
172
  const lifecycle = new RunLifecycle(record.id, workflowName, mode, deps, extKey);
@@ -167,7 +185,7 @@ export class RunLifecycle {
167
185
  externalKey: extKey,
168
186
  severity: 'info',
169
187
  });
170
- return await loop(lifecycle);
188
+ return await lifecycle.execute(loop);
171
189
  },
172
190
  { attributes: { 'workflow.name': workflowName, 'workflow.mode': mode } },
173
191
  );
@@ -190,12 +208,26 @@ export class RunLifecycle {
190
208
  async () => {
191
209
  const lifecycle = new RunLifecycle(runId, workflowName, mode, deps, externalKey);
192
210
  lifecycle.logger.info('workflow run resumed');
193
- return await loop(lifecycle);
211
+ return await lifecycle.execute(loop);
194
212
  },
195
213
  { attributes: { 'workflow.name': workflowName, 'workflow.mode': mode } },
196
214
  );
197
215
  }
198
216
 
217
+ private async execute(loop: (lifecycle: RunLifecycle) => Promise<WorkflowRunResult>): Promise<WorkflowRunResult> {
218
+ try {
219
+ return await loop(this);
220
+ } catch (error) {
221
+ // Preserve the original failure, including a failed attempt to mark the run failed.
222
+ try {
223
+ await this.persistence.finalizeRun(this.runId, 'failed', new Date().toISOString());
224
+ } catch (finalizeError) {
225
+ throw new AggregateError([error, finalizeError], 'Workflow execution and failure persistence failed');
226
+ }
227
+ throw error;
228
+ }
229
+ }
230
+
199
231
  /**
200
232
  * Persist the current state/node snapshot and mark its phase running.
201
233
  * When `persist` is false (set by driver loops after `commitHop` already
@@ -313,9 +345,16 @@ export class RunLifecycle {
313
345
  * would otherwise be lost because the prior snapshot predates this state's
314
346
  * action execution (R3 of 0366).
315
347
  */
316
- async pause(stateOrNodeId: string, transitionsTaken: number, vars?: Vars): Promise<WorkflowRunResult> {
348
+ async pause(
349
+ stateOrNodeId: string,
350
+ transitionsTaken: number,
351
+ vars?: Vars,
352
+ lastActionResult?: ActionResult,
353
+ ): Promise<WorkflowRunResult> {
317
354
  const data: Record<string, unknown> = { transitionsTaken };
318
355
  if (vars !== undefined) data.effectiveVars = vars;
356
+ // Only persist the control bit: raw action data must not bypass result redaction.
357
+ if (lastActionResult !== undefined) data.lastActionResult = { ok: lastActionResult.ok };
319
358
  await this.persistence.saveWorkflowState(this.runId, stateOrNodeId, data);
320
359
  await this.persistence.savePhase(this.runId, stateOrNodeId, 'paused');
321
360
  await this.persistence.finalizeRun(this.runId, 'paused', new Date().toISOString());
@@ -331,17 +370,6 @@ export class RunLifecycle {
331
370
  return this.result('paused', stateOrNodeId, transitionsTaken);
332
371
  }
333
372
 
334
- /** Emit the resumed event (called by WorkflowService after re-creating a lifecycle for resume). */
335
- emitResumed(node: string): void {
336
- addSpanEvent('workflow.run.resumed', { runId: this.runId, node });
337
- void this.events?.emit('workflow.run.resumed', {
338
- runId: this.runId,
339
- node,
340
- externalKey: this.externalKey,
341
- severity: 'info',
342
- });
343
- }
344
-
345
373
  /** Emit action-level observability before a host action is invoked. */
346
374
  actionStart(stateOrNodeId: string, kind: string): void {
347
375
  addSpanEvent('workflow.action.start', { runId: this.runId, node: stateOrNodeId, kind });
@@ -449,3 +477,17 @@ export class RunLifecycle {
449
477
  };
450
478
  }
451
479
  }
480
+
481
+ /** Older snapshots have no run-wide counter or guard context. */
482
+ export function snapshotTransitions(data: Record<string, unknown> | undefined): number {
483
+ const value = data?.transitionsTaken;
484
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : 0;
485
+ }
486
+
487
+ /** Restore only the persisted guard success bit, never unredacted action data. */
488
+ export function snapshotActionResult(data: Record<string, unknown> | undefined): ActionResult | undefined {
489
+ const value = data?.lastActionResult;
490
+ return value !== null && typeof value === 'object' && 'ok' in value && typeof value.ok === 'boolean'
491
+ ? { ok: value.ok }
492
+ : undefined;
493
+ }
package/src/schema-sql.ts CHANGED
@@ -11,7 +11,10 @@ CREATE TABLE IF NOT EXISTS runs (
11
11
  completed_at TEXT,
12
12
  metadata_json TEXT NOT NULL DEFAULT '{}',
13
13
  created_at INTEGER NOT NULL DEFAULT 0,
14
- updated_at INTEGER NOT NULL DEFAULT 0
14
+ updated_at INTEGER NOT NULL DEFAULT 0,
15
+ owner_attempt TEXT,
16
+ owner_pid INTEGER,
17
+ interrupt_reason TEXT
15
18
  );
16
19
 
17
20
  CREATE UNIQUE INDEX IF NOT EXISTS idx_runs_external_key
@@ -67,3 +70,10 @@ CREATE TABLE IF NOT EXISTS action_runs (
67
70
  FOREIGN KEY (run_id) REFERENCES runs(id)
68
71
  );
69
72
  `.trim();
73
+
74
+ /** Guarded ALTERs adding the 0.5.0 ownership/interruption columns for databases created before them. */
75
+ export const WORKFLOW_ENGINE_MIGRATIONS_SQL = `
76
+ ALTER TABLE runs ADD COLUMN owner_attempt TEXT;
77
+ ALTER TABLE runs ADD COLUMN owner_pid INTEGER;
78
+ ALTER TABLE runs ADD COLUMN interrupt_reason TEXT;
79
+ `.trim();
package/src/schema.ts CHANGED
@@ -94,6 +94,8 @@ export const StateMachineWorkflowDefSchema = z
94
94
  onExit: z.array(ActionDefSchema).optional(),
95
95
  /** When true, the engine pauses the run at this state instead of auto-advancing. */
96
96
  pause: z.boolean().optional(),
97
+ /** Author declaration that re-running this state's on-enter actions after an interruption is safe. */
98
+ resumeRerun: z.boolean().optional(),
97
99
  })
98
100
  .strict(),
99
101
  ),
@@ -136,6 +138,8 @@ export const TransitionFlowWorkflowDefSchema = z
136
138
  action: ActionDefSchema.optional(),
137
139
  /** When true, the engine pauses the run at this node instead of auto-advancing. */
138
140
  pause: z.boolean().optional(),
141
+ /** Author declaration that re-running this node's action after an interruption is safe. */
142
+ resumeRerun: z.boolean().optional(),
139
143
  })
140
144
  .strict(),
141
145
  ),
package/src/service.ts CHANGED
@@ -3,16 +3,18 @@ import { loadWorkflowDef } from './config';
3
3
  import { FSMError, WorkflowResumeError } from './errors';
4
4
  import type { WorkflowEngineEvents } from './events';
5
5
  import type { WorkflowEngineHost } from './host';
6
- import { RunLifecycle } from './run-lifecycle';
6
+ import { RunLifecycle, snapshotActionResult, snapshotTransitions } from './run-lifecycle';
7
7
  import { StateMachineDriver } from './state-machine';
8
8
  import { TransitionFlowDriver } from './transition-flow';
9
9
  import type {
10
+ ResumeOwnership,
10
11
  StateMachineWorkflowDef,
11
12
  TransitionDenied,
12
13
  TransitionRequestResult,
13
14
  Vars,
14
15
  WorkflowDef,
15
16
  WorkflowPersistenceAdapter,
17
+ WorkflowResumeMode,
16
18
  WorkflowRunOptions,
17
19
  WorkflowRunRecord,
18
20
  WorkflowRunResult,
@@ -157,34 +159,55 @@ export class WorkflowService {
157
159
  if (run === undefined) {
158
160
  throw new WorkflowResumeError(`Run "${runId}" not found`);
159
161
  }
160
- if (run.status !== 'paused') {
161
- throw new WorkflowResumeError(`Run "${runId}" is not paused (status: ${run.status})`);
162
+ if (run.status !== 'paused' && run.status !== 'interrupted') {
163
+ throw new WorkflowResumeError(`Run "${runId}" is not resumable (status: ${run.status})`);
162
164
  }
163
165
  const currentState = await this.persistence.loadCurrentState(runId);
164
166
  if (currentState === undefined) {
165
167
  throw new WorkflowResumeError(`Run "${runId}" has no persisted state to resume from`);
166
168
  }
167
169
 
170
+ // Resolve recovery semantics (task 0902): interrupted runs default to re-running
171
+ // the current state's actions (they may have half-completed at the interruption);
172
+ // paused runs default to skipping them (pause is declared after actions complete).
173
+ // An explicit `resumeMode` option overrides either default.
174
+ const resumeMode: WorkflowResumeMode =
175
+ options?.resumeMode ?? (run.status === 'interrupted' ? 'rerun-enter' : 'skip-enter');
176
+ this.assertResumeRerunAllowed(workflow, currentState, resumeMode);
177
+
168
178
  // Restore effectiveVars persisted in the last state snapshot so resume
169
179
  // continues with the same runtime variables (e.g. `__hitlAnswer`). Caller
170
180
  // overrides in `options.vars` win over the persisted snapshot (R3 of 0366).
171
181
  const snapshot = await this.persistence.loadLatestStateSnapshot(runId);
172
182
  const persistedVars = extractEffectiveVars(snapshot?.data);
173
183
  const restoredVars = mergeVars(persistedVars, options?.vars);
174
- const mergedOptions: WorkflowRunOptions = { ...options, vars: restoredVars };
184
+ const owner: ResumeOwnership = options?.resumeOwner ?? { attemptId: crypto.randomUUID() };
185
+ const mergedOptions: WorkflowRunOptions = { ...options, vars: restoredVars, resumeMode };
186
+
187
+ // Atomically claim ownership (task 0902 R3): the status flip and owner recording
188
+ // happen in one CAS update, so exactly one concurrent resume wins; losers and
189
+ // stale owners get a typed error instead of double-driving the run.
190
+ const claimed = await this.persistence.claimRunOwnership(runId, owner, ['paused', 'interrupted']);
191
+ if (claimed === undefined) {
192
+ const current = await this.persistence.loadRun(runId);
193
+ throw new WorkflowResumeError(
194
+ `Run "${runId}" could not be claimed for resume ` +
195
+ `(status: ${current?.status ?? 'unknown'}, owner: ${current?.owner_attempt ?? 'none'})`,
196
+ );
197
+ }
175
198
 
176
- // Re-open the run as running.
177
- const extKey = run.external_key ?? undefined;
178
- await this.persistence.finalizeRun(runId, 'running', '');
199
+ const extKey = claimed.external_key ?? undefined;
179
200
  const events = this.resolveEvents(mergedOptions.events);
180
201
  void events?.emit('workflow.run.resumed', {
181
202
  runId,
182
203
  node: currentState,
204
+ resumeMode,
205
+ ownerAttemptId: owner.attemptId,
183
206
  externalKey: extKey,
184
207
  severity: 'info',
185
208
  });
186
209
 
187
- // Resume through the appropriate driver, starting from the paused state (skip on-enter).
210
+ // Resume through the appropriate driver, starting from the persisted state.
188
211
  if (workflow.kind === 'transition-flow') {
189
212
  return await new TransitionFlowDriver({
190
213
  host: this.host,
@@ -197,6 +220,45 @@ export class WorkflowService {
197
220
  }).resume(workflow as StateMachineWorkflowDef, runId, currentState, extKey, mergedOptions);
198
221
  }
199
222
 
223
+ /**
224
+ * Mark a running run as interrupted (task 0902 R2) — crash/lost-owner
225
+ * reconciliation so an abandoned run can later be rerun-resumed instead of
226
+ * wedging in 'running' forever. CAS: returns undefined when the run is
227
+ * missing or not running (already terminal/paused/claimed).
228
+ */
229
+ async interruptRun(runId: string, reason: string): Promise<WorkflowRunRecord | undefined> {
230
+ const interrupted = await this.persistence.interruptRun(runId, reason);
231
+ if (interrupted !== undefined) {
232
+ const events = this.resolveEvents(undefined);
233
+ void events?.emit('workflow.run.interrupted', {
234
+ runId,
235
+ reason,
236
+ externalKey: interrupted.external_key ?? undefined,
237
+ severity: 'warning',
238
+ });
239
+ }
240
+ return interrupted;
241
+ }
242
+
243
+ /** Refuse rerun-resume into states the author has not declared safe to re-run (task 0902 R1/R2). */
244
+ private assertResumeRerunAllowed(
245
+ workflow: WorkflowDef,
246
+ currentState: string,
247
+ resumeMode: WorkflowResumeMode,
248
+ ): void {
249
+ if (resumeMode !== 'rerun-enter') return;
250
+ const node =
251
+ workflow.kind === 'transition-flow'
252
+ ? workflow.nodes.find((candidate) => candidate.id === currentState)
253
+ : (workflow as StateMachineWorkflowDef).states.find((candidate) => candidate.id === currentState);
254
+ if (node !== undefined && node.resumeRerun !== true) {
255
+ throw new FSMError(
256
+ `Cannot rerun-resume into "${currentState}": not marked resumeRerun: true ` +
257
+ '(mark its actions as safe to re-run — idempotent or deduped by runId+state — or resume with resumeMode: "skip-enter")',
258
+ );
259
+ }
260
+ }
261
+
200
262
  /** List runs currently paused. Optional filters and ordering. */
201
263
  async listPausedRuns(options?: { workflowName?: string; limit?: number }): Promise<readonly WorkflowRunRecord[]> {
202
264
  return await this.persistence.listPausedRuns(options);
@@ -274,19 +336,23 @@ export class WorkflowService {
274
336
  });
275
337
  }
276
338
 
339
+ const snapshot = await this.persistence.loadLatestStateSnapshot(runId);
340
+ const vars = mergeVars(mergeVars(workflow.vars, extractEffectiveVars(snapshot?.data)), options?.vars);
341
+
277
342
  // Evaluate guard if present.
278
343
  if (transition.guard !== undefined) {
279
- // Resolve ${vars.*} templates in guard options against the workflow's vars —
344
+ // Resolve ${vars.*} templates against the restored and overridden runtime vars —
280
345
  // external transitions (requestTransition) must interpolate the same way the
281
346
  // driver's firstPassingTransition does (e.g. `spur task check ${vars.wbs}`).
282
347
  const resolvedGuardOptions = resolveTemplates(transition.guard.options ?? {}, {
283
- vars: workflow.vars ?? {},
348
+ vars,
284
349
  env: {},
285
350
  });
286
351
  const guardResult = await this.host.evaluateGuardResult(transition.guard.kind, resolvedGuardOptions, {
287
352
  runId,
288
353
  current: currentState,
289
- vars: workflow.vars ?? {},
354
+ lastActionResult: snapshotActionResult(snapshot?.data),
355
+ vars,
290
356
  workdir: options?.workdir,
291
357
  });
292
358
  lifecycle.guardEvaluated(currentState, toState, transition.guard.kind, guardResult.passed);
@@ -304,7 +370,14 @@ export class WorkflowService {
304
370
  // batch (ADR-020), then emit the external-only requested event. No phase
305
371
  // record — external transitions don't drive phase tracking.
306
372
  const trigger = transition.trigger ?? null;
307
- await lifecycle.commitHop(currentState, toState, trigger, 0);
373
+ await lifecycle.commitHop(
374
+ currentState,
375
+ toState,
376
+ trigger,
377
+ snapshotTransitions(snapshot?.data) + 1,
378
+ undefined,
379
+ vars,
380
+ );
308
381
  void events?.emit('workflow.transition.requested', {
309
382
  runId,
310
383
  from: currentState,
@@ -1,7 +1,7 @@
1
1
  import { runActionSequence } from './action-step';
2
2
  import { FSMError } from './errors';
3
3
  import type { WorkflowEngineHost } from './host';
4
- import { allowedEnv, RunLifecycle } from './run-lifecycle';
4
+ import { allowedEnv, RunLifecycle, snapshotActionResult, snapshotTransitions } from './run-lifecycle';
5
5
  import type {
6
6
  ActionResult,
7
7
  StateMachineWorkflowDef,
@@ -63,11 +63,13 @@ export class StateMachineDriver {
63
63
  let vars = mergeVars(workflow.vars, options.vars);
64
64
  const env = allowedEnv(workflow.env?.allow ?? [], options.env);
65
65
  let current = resumeFromState !== undefined ? states.get(resumeFromState) : states.get(workflow.initialState);
66
- let transitionsTaken = 0;
67
- let lastActionResult: ActionResult | undefined;
66
+ const snapshot =
67
+ resumeFromState === undefined ? undefined : await this.options.persistence.loadLatestStateSnapshot(runId);
68
+ let transitionsTaken = snapshotTransitions(snapshot?.data);
69
+ let lastActionResult: ActionResult | undefined = snapshotActionResult(snapshot?.data);
68
70
  const iterationBound = workflow.iterationBound ?? 50;
69
71
  const defaultOnError = workflow.defaultOnError;
70
- let isResume = resumeFromState !== undefined;
72
+ let resumeMode = resumeFromState !== undefined ? (options.resumeMode ?? 'skip-enter') : undefined;
71
73
  // When `commitHop` has already persisted the new state's snapshot +
72
74
  // phase atomically (every iteration after the first), `enter` must skip
73
75
  // the persist half to avoid duplicate INSERT rows (ADR-020).
@@ -79,11 +81,24 @@ export class StateMachineDriver {
79
81
  }
80
82
 
81
83
  while (true) {
82
- if (isResume) {
84
+ if (resumeMode === 'skip-enter') {
83
85
  // Resume: skip enter actions on the first iteration (already ran before pause).
84
- isResume = false;
86
+ resumeMode = undefined;
85
87
  persistedViaHop = true; // state already persisted before the pause
86
88
  } else {
89
+ if (resumeMode === 'rerun-enter') {
90
+ // Rerun-resume re-executes on-enter actions; only states the author marked
91
+ // resumable may be re-entered (0902: loud refusal before any action runs,
92
+ // never a silent replay of unclassified side effects).
93
+ if (current.resumeRerun !== true) {
94
+ throw new FSMError(
95
+ `Cannot rerun-resume into state "${current.id}": not marked resumeRerun: true ` +
96
+ '(mark its on-enter actions as safe to re-run, or resume with resumeMode: "skip-enter")',
97
+ );
98
+ }
99
+ resumeMode = undefined;
100
+ persistedViaHop = true; // snapshot exists from the pre-interruption enter
101
+ }
87
102
  // 1. Persist current state snapshot before work starts (skipped when
88
103
  // commitHop already persisted it atomically on the previous hop).
89
104
  await lifecycle.enter(current.id, transitionsTaken, !persistedViaHop, vars);
@@ -122,7 +137,7 @@ export class StateMachineDriver {
122
137
 
123
138
  // Pause: if the state declares pause, stop advancing and persist the paused position.
124
139
  if (current.pause === true) {
125
- return await lifecycle.pause(current.id, transitionsTaken, vars);
140
+ return await lifecycle.pause(current.id, transitionsTaken, vars, lastActionResult);
126
141
  }
127
142
  }
128
143
 
@@ -171,6 +186,11 @@ export class StateMachineDriver {
171
186
  });
172
187
  if (exit.result !== undefined) lastActionResult = exit.result;
173
188
  if (exit.setVars) vars = mergeSetVars(vars, exit.setVars);
189
+ if (exit.outcome === 'terminal') {
190
+ return failure.has(current.id)
191
+ ? await lifecycle.fail(current.id, transitionsTaken, `terminal:${current.id}`)
192
+ : await lifecycle.done(current.id, transitionsTaken);
193
+ }
174
194
  if (exit.outcome === 'fail') return await lifecycle.fail(current.id, transitionsTaken, exit.result?.error);
175
195
 
176
196
  // 7. Atomically commit the transition + new state snapshot + phase in a
@@ -1,7 +1,7 @@
1
1
  import { runActionStep } from './action-step';
2
2
  import { FSMError } from './errors';
3
3
  import type { WorkflowEngineHost } from './host';
4
- import { allowedEnv, RunLifecycle } from './run-lifecycle';
4
+ import { allowedEnv, RunLifecycle, snapshotActionResult, snapshotTransitions } from './run-lifecycle';
5
5
  import type {
6
6
  ActionResult,
7
7
  TransitionFlowWorkflowDef,
@@ -62,11 +62,13 @@ export class TransitionFlowDriver {
62
62
  let vars = mergeVars(workflow.vars, options.vars);
63
63
  const env = allowedEnv(workflow.env?.allow ?? [], options.env);
64
64
  let current = resumeFromNode !== undefined ? nodes.get(resumeFromNode) : nodes.get(workflow.initialNode);
65
- let transitionsTaken = 0;
66
- let lastActionResult: ActionResult | undefined;
65
+ const snapshot =
66
+ resumeFromNode === undefined ? undefined : await this.options.persistence.loadLatestStateSnapshot(runId);
67
+ let transitionsTaken = snapshotTransitions(snapshot?.data);
68
+ let lastActionResult: ActionResult | undefined = snapshotActionResult(snapshot?.data);
67
69
  const iterationBound = workflow.iterationBound ?? 50;
68
70
  const defaultOnError = workflow.defaultOnError;
69
- let isResume = resumeFromNode !== undefined;
71
+ let resumeMode = resumeFromNode !== undefined ? (options.resumeMode ?? 'skip-enter') : undefined;
70
72
  // When `commitHop` has already persisted the new node's snapshot +
71
73
  // phase atomically (every iteration after the first), `enter` must skip
72
74
  // the persist half to avoid duplicate INSERT rows (ADR-020).
@@ -78,11 +80,23 @@ export class TransitionFlowDriver {
78
80
  }
79
81
 
80
82
  while (true) {
81
- if (isResume) {
83
+ if (resumeMode === 'skip-enter') {
82
84
  // Resume: skip enter + node action on the first iteration (already ran before pause).
83
- isResume = false;
85
+ resumeMode = undefined;
84
86
  persistedViaHop = true; // node already persisted before the pause
85
87
  } else {
88
+ if (resumeMode === 'rerun-enter') {
89
+ // Rerun-resume re-executes the node action; only nodes the author marked
90
+ // resumable may be re-entered (0902: loud refusal before any action runs).
91
+ if (current.resumeRerun !== true) {
92
+ throw new FSMError(
93
+ `Cannot rerun-resume into node "${current.id}": not marked resumeRerun: true ` +
94
+ '(mark its action as safe to re-run, or resume with resumeMode: "skip-enter")',
95
+ );
96
+ }
97
+ resumeMode = undefined;
98
+ persistedViaHop = true; // snapshot exists from the pre-interruption enter
99
+ }
86
100
  // 1. Persist current node snapshot before action execution (skipped when
87
101
  // commitHop already persisted it atomically on the previous hop).
88
102
  await lifecycle.enter(current.id, transitionsTaken, !persistedViaHop, vars);
@@ -118,7 +132,7 @@ export class TransitionFlowDriver {
118
132
 
119
133
  // Pause: if the node declares pause, stop advancing and persist the paused position.
120
134
  if (current.pause === true) {
121
- return await lifecycle.pause(current.id, transitionsTaken, vars);
135
+ return await lifecycle.pause(current.id, transitionsTaken, vars, lastActionResult);
122
136
  }
123
137
  }
124
138