@gobing-ai/ts-dual-workflow-engine 0.5.4 → 0.5.5

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.
@@ -7,6 +7,7 @@ import {
7
7
  traceAsync,
8
8
  } from '@gobing-ai/ts-infra';
9
9
  import { getProcessEnv } from '@gobing-ai/ts-runtime';
10
+ import { WorkflowResumeError } from './errors';
10
11
  import type { WorkflowEngineEvents } from './events';
11
12
  import type {
12
13
  ActionResult,
@@ -86,6 +87,8 @@ export class RunLifecycle {
86
87
  private readonly persistence: WorkflowPersistenceAdapter;
87
88
  private readonly events: EventBus<WorkflowEngineEvents> | undefined;
88
89
  private readonly logger: Logger;
90
+ /** Owner attempt recorded on the run row; undefined for lifecycles that never claimed a run (external transitions, direct construction). Gates the finalize fence (task 0086 AC11). */
91
+ private ownerAttempt: string | undefined;
89
92
 
90
93
  private constructor(
91
94
  runId: string,
@@ -170,6 +173,7 @@ export class RunLifecycle {
170
173
  }
171
174
  const extKey = record.external_key ?? undefined;
172
175
  const lifecycle = new RunLifecycle(record.id, workflowName, mode, deps, extKey);
176
+ lifecycle.ownerAttempt = proposed.owner_attempt ?? undefined;
173
177
  lifecycle.logger.info('workflow run started');
174
178
  addSpanEvent('workflow.run.started', {
175
179
  workflowName,
@@ -202,11 +206,13 @@ export class RunLifecycle {
202
206
  runId: string,
203
207
  externalKey: string | undefined,
204
208
  loop: (lifecycle: RunLifecycle) => Promise<WorkflowRunResult>,
209
+ ownerAttempt?: string,
205
210
  ): Promise<WorkflowRunResult> {
206
211
  return await traceAsync(
207
212
  'workflow.run',
208
213
  async () => {
209
214
  const lifecycle = new RunLifecycle(runId, workflowName, mode, deps, externalKey);
215
+ lifecycle.ownerAttempt = ownerAttempt;
210
216
  lifecycle.logger.info('workflow run resumed');
211
217
  return await lifecycle.execute(loop);
212
218
  },
@@ -214,13 +220,42 @@ export class RunLifecycle {
214
220
  );
215
221
  }
216
222
 
223
+ /**
224
+ * Terminal write guarded by the owner fence (task 0086 AC11): when this lifecycle
225
+ * claimed the run, the persistence adapter only applies the finalize if the run is
226
+ * still running and owned by this attempt. A rejected write emits
227
+ * `workflow.run.stale_owner` and raises a typed resume error instead of stomping a
228
+ * newer attempt's state.
229
+ */
230
+ private async finalizeAsOwner(status: WorkflowStatus, completedAt: string): Promise<void> {
231
+ if (this.ownerAttempt === undefined) {
232
+ // Lifecycle without an ownership claim (external transitions) keeps the legacy write.
233
+ await this.persistence.finalizeRun(this.runId, status, completedAt);
234
+ return;
235
+ }
236
+ const applied = await this.persistence.finalizeRun(this.runId, status, completedAt, {
237
+ ownerAttempt: this.ownerAttempt,
238
+ });
239
+ if (applied === false) {
240
+ void this.events?.emit('workflow.run.stale_owner', {
241
+ runId: this.runId,
242
+ ownerAttemptId: this.ownerAttempt,
243
+ status,
244
+ severity: 'warning',
245
+ });
246
+ throw new WorkflowResumeError(
247
+ `stale owner "${this.ownerAttempt}" cannot finalize run "${this.runId}" as "${status}": ownership was lost`,
248
+ );
249
+ }
250
+ }
251
+
217
252
  private async execute(loop: (lifecycle: RunLifecycle) => Promise<WorkflowRunResult>): Promise<WorkflowRunResult> {
218
253
  try {
219
254
  return await loop(this);
220
255
  } catch (error) {
221
256
  // Preserve the original failure, including a failed attempt to mark the run failed.
222
257
  try {
223
- await this.persistence.finalizeRun(this.runId, 'failed', new Date().toISOString());
258
+ await this.finalizeAsOwner('failed', new Date().toISOString());
224
259
  } catch (finalizeError) {
225
260
  throw new AggregateError([error, finalizeError], 'Workflow execution and failure persistence failed');
226
261
  }
@@ -309,7 +344,7 @@ export class RunLifecycle {
309
344
  /** Finalize the run as succeeded and return its result. */
310
345
  async done(finalState: string, transitionsTaken: number): Promise<WorkflowRunResult> {
311
346
  await this.persistence.savePhase(this.runId, finalState, 'done');
312
- await this.persistence.finalizeRun(this.runId, 'done', new Date().toISOString());
347
+ await this.finalizeAsOwner('done', new Date().toISOString());
313
348
  this.logger.info('workflow run done', { finalState, transitionsTaken });
314
349
  addSpanEvent('workflow.run.done', { runId: this.runId, finalState, transitionsTaken });
315
350
  void this.events?.emit('workflow.run.done', {
@@ -325,7 +360,7 @@ export class RunLifecycle {
325
360
  /** Finalize the run as failed and return its result. */
326
361
  async fail(finalState: string, transitionsTaken: number, reason = 'failed'): Promise<WorkflowRunResult> {
327
362
  await this.persistence.savePhase(this.runId, finalState, 'failed');
328
- await this.persistence.finalizeRun(this.runId, 'failed', new Date().toISOString());
363
+ await this.finalizeAsOwner('failed', new Date().toISOString());
329
364
  addSpanEvent('workflow.run.failed', { runId: this.runId, finalState, reason });
330
365
  void this.events?.emit('workflow.run.failed', {
331
366
  runId: this.runId,
@@ -357,7 +392,7 @@ export class RunLifecycle {
357
392
  if (lastActionResult !== undefined) data.lastActionResult = { ok: lastActionResult.ok };
358
393
  await this.persistence.saveWorkflowState(this.runId, stateOrNodeId, data);
359
394
  await this.persistence.savePhase(this.runId, stateOrNodeId, 'paused');
360
- await this.persistence.finalizeRun(this.runId, 'paused', new Date().toISOString());
395
+ await this.finalizeAsOwner('paused', new Date().toISOString());
361
396
  this.logger.info('workflow run paused', { stateOrNodeId, transitionsTaken });
362
397
  addSpanEvent('workflow.run.paused', { runId: this.runId, node: stateOrNodeId, transitionsTaken });
363
398
  void this.events?.emit('workflow.run.paused', {
package/src/service.ts CHANGED
@@ -3,7 +3,7 @@ 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, snapshotActionResult, snapshotTransitions } from './run-lifecycle';
6
+ import { allowedEnv, RunLifecycle, snapshotActionResult, snapshotTransitions } from './run-lifecycle';
7
7
  import { StateMachineDriver } from './state-machine';
8
8
  import { TransitionFlowDriver } from './transition-flow';
9
9
  import type {
@@ -19,7 +19,7 @@ import type {
19
19
  WorkflowRunRecord,
20
20
  WorkflowRunResult,
21
21
  } from './types';
22
- import { mergeVars, resolveTemplates } from './variables';
22
+ import { mergeVars, resolveShellCommandTemplates, resolveTemplates } from './variables';
23
23
 
24
24
  /** High-level workflow service for loading, running, and listing persisted workflow runs. */
25
25
  export class WorkflowService {
@@ -182,7 +182,7 @@ export class WorkflowService {
182
182
  const persistedVars = extractEffectiveVars(snapshot?.data);
183
183
  const restoredVars = mergeVars(persistedVars, options?.vars);
184
184
  const owner: ResumeOwnership = options?.resumeOwner ?? { attemptId: crypto.randomUUID() };
185
- const mergedOptions: WorkflowRunOptions = { ...options, vars: restoredVars, resumeMode };
185
+ const mergedOptions: WorkflowRunOptions = { ...options, vars: restoredVars, resumeMode, resumeOwner: owner };
186
186
 
187
187
  // Atomically claim ownership (task 0902 R3): the status flip and owner recording
188
188
  // happen in one CAS update, so exactly one concurrent resume wins; losers and
@@ -338,21 +338,25 @@ export class WorkflowService {
338
338
 
339
339
  const snapshot = await this.persistence.loadLatestStateSnapshot(runId);
340
340
  const vars = mergeVars(mergeVars(workflow.vars, extractEffectiveVars(snapshot?.data)), options?.vars);
341
+ // Guards resolve ${env.X} against the same allowed-env map actions use (task 0087 R5).
342
+ const env = allowedEnv(workflow.env?.allow ?? [], options?.env);
341
343
 
342
344
  // Evaluate guard if present.
343
345
  if (transition.guard !== undefined) {
344
346
  // Resolve ${vars.*} templates against the restored and overridden runtime vars —
345
347
  // external transitions (requestTransition) must interpolate the same way the
346
348
  // driver's firstPassingTransition does (e.g. `spur task check ${vars.wbs}`).
347
- const resolvedGuardOptions = resolveTemplates(transition.guard.options ?? {}, {
348
- vars,
349
- env: {},
350
- });
349
+ // Shell-form guards bind command refs to env instead of raw substitution (task 0086 M1).
350
+ const resolvedGuardOptions =
351
+ transition.guard.kind === 'shell'
352
+ ? resolveShellCommandTemplates(transition.guard.options ?? {}, { vars, env })
353
+ : resolveTemplates(transition.guard.options ?? {}, { vars, env });
351
354
  const guardResult = await this.host.evaluateGuardResult(transition.guard.kind, resolvedGuardOptions, {
352
355
  runId,
353
356
  current: currentState,
354
357
  lastActionResult: snapshotActionResult(snapshot?.data),
355
358
  vars,
359
+ env,
356
360
  workdir: options?.workdir,
357
361
  });
358
362
  lifecycle.guardEvaluated(currentState, toState, transition.guard.kind, guardResult.passed);
@@ -9,7 +9,7 @@ import type {
9
9
  WorkflowRunOptions,
10
10
  WorkflowRunResult,
11
11
  } from './types';
12
- import { mergeSetVars, mergeVars, resolveTemplates } from './variables';
12
+ import { mergeSetVars, mergeVars, resolveShellCommandTemplates, resolveTemplates } from './variables';
13
13
 
14
14
  /** Dependencies required by the state-machine driver. */
15
15
  export interface StateMachineDriverOptions {
@@ -47,6 +47,7 @@ export class StateMachineDriver {
47
47
  runId,
48
48
  externalKey,
49
49
  (lifecycle) => this.loop(workflow, options, lifecycle, resumeFromState),
50
+ options.resumeOwner?.attemptId,
50
51
  );
51
52
  }
52
53
 
@@ -156,6 +157,7 @@ export class StateMachineDriver {
156
157
  runId,
157
158
  current: current.id,
158
159
  vars,
160
+ env,
159
161
  lastActionResult,
160
162
  // Shell guards use relative paths (e.g. .spur/run/${vars.__runId}-*) —
161
163
  // must share the run's workdir with actions or they read the process cwd.
@@ -231,11 +233,16 @@ async function firstPassingTransition(
231
233
  for (const transition of transitions) {
232
234
  if (transition.guard === undefined) return transition;
233
235
  // Resolve ${vars.*} templates in guard options before evaluation — guards use the
234
- // same var interpolation as actions (e.g. `spur task check ${vars.wbs}`).
235
- const resolvedOptions = resolveTemplates(transition.guard.options ?? {}, {
236
- vars: context.vars,
237
- env: {},
238
- });
236
+ // same var interpolation as actions (e.g. `spur task check ${vars.wbs}`). Shell-form
237
+ // guards bind command refs to env instead of raw substitution (task 0086 M1); the
238
+ // env bindings pass through to the runner (guard options are never persisted).
239
+ const resolvedOptions =
240
+ transition.guard.kind === 'shell'
241
+ ? resolveShellCommandTemplates(transition.guard.options ?? {}, {
242
+ vars: context.vars,
243
+ env: context.env ?? {},
244
+ })
245
+ : resolveTemplates(transition.guard.options ?? {}, { vars: context.vars, env: context.env ?? {} });
239
246
  const passed = await host.evaluateGuard(transition.guard.kind, resolvedOptions, context);
240
247
  lifecycle.guardEvaluated(context.current, transition.to, transition.guard.kind, passed);
241
248
  if (passed) return transition;
@@ -9,7 +9,7 @@ import type {
9
9
  WorkflowRunOptions,
10
10
  WorkflowRunResult,
11
11
  } from './types';
12
- import { mergeSetVars, mergeVars, resolveTemplates } from './variables';
12
+ import { mergeSetVars, mergeVars, resolveShellCommandTemplates, resolveTemplates } from './variables';
13
13
 
14
14
  /** Dependencies required by the transition-flow driver. */
15
15
  export interface TransitionFlowDriverOptions {
@@ -47,6 +47,7 @@ export class TransitionFlowDriver {
47
47
  runId,
48
48
  externalKey,
49
49
  (lifecycle) => this.loop(workflow, options, lifecycle, resumeFromNode),
50
+ options.resumeOwner?.attemptId,
50
51
  );
51
52
  }
52
53
 
@@ -150,6 +151,7 @@ export class TransitionFlowDriver {
150
151
  runId,
151
152
  current: current.id,
152
153
  vars,
154
+ env,
153
155
  lastActionResult,
154
156
  // Shell conditions must share the run workdir with actions (relative paths).
155
157
  workdir: options.workdir,
@@ -200,10 +202,14 @@ async function firstPassingEdge(
200
202
  if (edge.condition === undefined) return edge;
201
203
  // Resolve ${vars.*} templates in condition options before evaluation — conditions use
202
204
  // the same var interpolation as actions (symmetry with state-machine guard resolution).
203
- const resolvedOptions = resolveTemplates(edge.condition.options ?? {}, {
204
- vars: context.vars,
205
- env: {},
206
- });
205
+ // Shell-form conditions bind command refs to env instead of raw substitution (task 0086 M1).
206
+ const resolvedOptions =
207
+ edge.condition.kind === 'shell'
208
+ ? resolveShellCommandTemplates(edge.condition.options ?? {}, {
209
+ vars: context.vars,
210
+ env: context.env ?? {},
211
+ })
212
+ : resolveTemplates(edge.condition.options ?? {}, { vars: context.vars, env: context.env ?? {} });
207
213
  const passed = await host.evaluateGuard(edge.condition.kind, resolvedOptions, context);
208
214
  lifecycle.guardEvaluated(context.current, edge.to, edge.condition.kind, passed);
209
215
  if (passed) return edge;
package/src/types.ts CHANGED
@@ -196,6 +196,8 @@ export interface GuardContext {
196
196
  readonly current: string;
197
197
  readonly vars: Vars;
198
198
  readonly workdir?: string;
199
+ /** Run env (allowed-env filtered) — guards resolve `${env.X}` identically to actions (task 0087 R5). */
200
+ readonly env?: Record<string, string>;
199
201
  readonly lastActionResult?: ActionResult;
200
202
  }
201
203
 
@@ -326,13 +328,35 @@ export interface ActionRunRecord {
326
328
  readonly completed_at: string | null;
327
329
  }
328
330
 
331
+ /**
332
+ * Resolves to `void`. Derived from an existing return position because the repo
333
+ * lints `noConfusingVoidType` with `--error-on-warnings` and rejects a literal
334
+ * `void` in a union, while the task-0086 R8 contract needs `boolean | void` on
335
+ * `finalizeRun` so legacy 3-arg `Promise<void>` adapters stay assignable.
336
+ * No runtime effect.
337
+ */
338
+ export type LegacyAdapterVoid = Awaited<ReturnType<WorkflowPersistenceAdapter['savePhase']>>;
339
+
329
340
  /** Optional redaction hook: given action options, return sanitized options for persistence. */
330
341
  export type ActionRedactor = (kind: string, options: Record<string, unknown>) => Record<string, unknown>;
331
342
 
332
343
  /** Persistence adapter implemented by DB-backed and test stores. */
333
344
  export interface WorkflowPersistenceAdapter {
334
345
  createRun(record: WorkflowRunRecord): Promise<void>;
335
- finalizeRun(runId: string, status: WorkflowStatus, completedAt: string): Promise<void>;
346
+ /**
347
+ * Finalize a run. Adapters that track `owner_attempt` MUST treat a supplied
348
+ * `fence` as an ownership precondition: when the run's current owner differs
349
+ * (or the run is not active), the row stays untouched and `false` is returned
350
+ * (task 0086 AC11). Adapters without owner tracking may ignore `fence` and
351
+ * return void — legacy custom adapters with the old 3-arg signature remain
352
+ * assignable to this interface.
353
+ */
354
+ finalizeRun(
355
+ runId: string,
356
+ status: WorkflowStatus,
357
+ completedAt: string,
358
+ fence?: { readonly ownerAttempt: string },
359
+ ): Promise<boolean | LegacyAdapterVoid>;
336
360
  savePhase(runId: string, phase: string, status: WorkflowStatus): Promise<void>;
337
361
  saveTransition(runId: string, from: string, to: string, trigger: string | null): Promise<void>;
338
362
  saveWorkflowState(runId: string, state: string, data: Record<string, unknown>): Promise<void>;
package/src/variables.ts CHANGED
@@ -51,25 +51,101 @@ export function resolveTemplates<T>(value: T, context: VariableContext): T {
51
51
  /** Resolve a single template string. */
52
52
  export function resolveTemplateString(value: string, context: VariableContext): string {
53
53
  return value.replace(TEMPLATE_REF, (_match, name: string) => {
54
- if (name.startsWith('vars.')) {
55
- const key = name.slice('vars.'.length);
56
- const resolved = context.vars[key];
57
- if (resolved === undefined) throw new WorkflowValidationError(`Workflow variable "${key}" is not defined`);
58
- return resolved;
59
- }
60
- if (name.startsWith('env.')) {
61
- const key = name.slice('env.'.length);
62
- const resolved = context.env[key];
63
- if (resolved === undefined)
64
- throw new WorkflowValidationError(`Environment variable "${key}" is not defined`);
65
- return resolved;
66
- }
67
- const resolved = context.builtins?.[name];
68
- if (resolved === undefined) throw new WorkflowValidationError(`Workflow builtin "${name}" is not defined`);
69
- return String(resolved);
54
+ return lookupRef(name, context);
70
55
  });
71
56
  }
72
57
 
58
+ function lookupRef(name: string, context: VariableContext): string {
59
+ if (name.startsWith('vars.')) {
60
+ const key = name.slice('vars.'.length);
61
+ const resolved = context.vars[key];
62
+ if (resolved === undefined) throw new WorkflowValidationError(`Workflow variable "${key}" is not defined`);
63
+ return resolved;
64
+ }
65
+ if (name.startsWith('env.')) {
66
+ const key = name.slice('env.'.length);
67
+ const resolved = context.env[key];
68
+ if (resolved === undefined) throw new WorkflowValidationError(`Environment variable "${key}" is not defined`);
69
+ return resolved;
70
+ }
71
+ const resolved = context.builtins?.[name];
72
+ if (resolved === undefined) throw new WorkflowValidationError(`Workflow builtin "${name}" is not defined`);
73
+ return String(resolved);
74
+ }
75
+
76
+ /**
77
+ * Env option key carrying the shell-form template bindings (`${__WF_n}` → value).
78
+ * The shell runner forwards it as process env; call sites strip it before persisting.
79
+ */
80
+ export const SHELL_ENV_OPTION = '__wfShellEnv';
81
+
82
+ const SHELL_BINDING = /^\$\{__WF_\d+\}$/;
83
+
84
+ /** Any reserved placeholder literal in authored command text (task 0087 R2). Braced and unbraced forms both expand at exec time. */
85
+ const SHELL_BINDING_ANY = /\$\{__WF_\d+\}|\$__WF_\d+\b/;
86
+
87
+ /**
88
+ * Resolve options for `shell` actions (task 0086 M1).
89
+ *
90
+ * Shell form (`command`, no `args`): template refs in `command` are rewritten to
91
+ * numbered `${__WF_n}` placeholders and their values ride in the SHELL_ENV_OPTION env
92
+ * map, so substituted text is never reparsed as shell syntax — values survive quotes,
93
+ * `;`, `$()` etc. verbatim. Caveat (fails closed): refs the author quoted with single
94
+ * quotes no longer expand.
95
+ *
96
+ * Argv form (`command` + non-empty `args`): command/args keep raw substitution — the runner
97
+ * uses execFile, which never reparses, so injection is impossible. `args: []` falls through
98
+ * to shell form: the runner picks `/bin/sh -c` whenever there are no argv entries, so the
99
+ * predicates must agree or values would be raw-substituted into a shell line.
100
+ *
101
+ * All other options resolve as plain templates.
102
+ */
103
+ export function resolveShellCommandTemplates(
104
+ options: Record<string, unknown>,
105
+ context: VariableContext,
106
+ ): Record<string, unknown> {
107
+ const { command, args, ...rest } = options;
108
+ if (typeof command !== 'string') return resolveTemplates(rest, context);
109
+ // Task 0087 R1: a defined non-array `args` is an author typo — fail closed with a
110
+ // validation error instead of silently downgrading to shell form. `undefined`
111
+ // and `[]` keep shell form; non-empty arrays keep argv form.
112
+ if (args !== undefined && !Array.isArray(args)) {
113
+ throw new Error(`shell action "args" must be a string array when defined; got ${typeof args}`);
114
+ }
115
+ if (Array.isArray(args) && args.length > 0) {
116
+ return {
117
+ ...resolveTemplates(rest, context),
118
+ command: resolveTemplateString(command, context),
119
+ args: resolveTemplates(args, context),
120
+ };
121
+ }
122
+ const env: Record<string, string> = {};
123
+ let index = 0;
124
+ // Task 0087 R2: the `${__WF_n}` namespace is reserved for this binding pass. An
125
+ // authored command containing a placeholder literal that no binding pass produced
126
+ // would alias (or be aliased by) a bound value — fail closed. Re-resolution of
127
+ // already-bound options (SHELL_ENV_OPTION present) is the idempotent path: seed
128
+ // env/index from the existing map so bindings survive the second pass (ADV-1).
129
+ if (!(SHELL_ENV_OPTION in options) && SHELL_BINDING_ANY.test(command)) {
130
+ throw new Error(
131
+ 'shell command must not contain the reserved $__WF_ placeholder namespace; ' +
132
+ 'it is minted by the template-binding pass',
133
+ );
134
+ }
135
+ const existingBindings = options[SHELL_ENV_OPTION];
136
+ if (existingBindings !== undefined && typeof existingBindings === 'object' && existingBindings !== null) {
137
+ Object.assign(env, existingBindings);
138
+ while (`__WF_${index}` in env) index++;
139
+ }
140
+ const bound = command.replace(TEMPLATE_REF, (match, name: string) => {
141
+ if (SHELL_BINDING.test(match)) return match; // already-bound placeholder → idempotent
142
+ const key = `__WF_${index++}`;
143
+ env[key] = lookupRef(name, context);
144
+ return `\${${key}}`;
145
+ });
146
+ return { ...resolveTemplates(rest, context), command: bound, [SHELL_ENV_OPTION]: env };
147
+ }
148
+
73
149
  /**
74
150
  * Resolve the effective error policy via fixed precedence:
75
151
  * `action.onError ?? workflow.defaultOnError ?? runOptions.onError ?? 'fail'`.