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

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/types.ts CHANGED
@@ -88,6 +88,8 @@ export interface TransitionDef {
88
88
  readonly description?: string;
89
89
  readonly trigger?: string;
90
90
  readonly guard?: GuardDef;
91
+ /** Declared terminal reason carried onto the runs row when this edge closes the run. */
92
+ readonly terminalReason?: string;
91
93
  }
92
94
 
93
95
  /** State-machine workflow definition. */
@@ -196,6 +198,8 @@ export interface GuardContext {
196
198
  readonly current: string;
197
199
  readonly vars: Vars;
198
200
  readonly workdir?: string;
201
+ /** Run env (allowed-env filtered) — guards resolve `${env.X}` identically to actions (task 0087 R5). */
202
+ readonly env?: Record<string, string>;
199
203
  readonly lastActionResult?: ActionResult;
200
204
  }
201
205
 
@@ -276,6 +280,9 @@ export interface WorkflowRunRecord {
276
280
  readonly owner_pid?: number | null;
277
281
  /** Reason recorded by the last interruption (task 0902 R2). */
278
282
  readonly interrupt_reason?: string | null;
283
+ /** Opaque terminal reason recorded when the run was finalized (paused rows keep the
284
+ * pre-resume reason until the next finalize overwrites it; running rows read null). */
285
+ readonly terminal_reason?: string | null;
279
286
  }
280
287
 
281
288
  /** Result of force-setting the current state of a run. */
@@ -326,13 +333,36 @@ export interface ActionRunRecord {
326
333
  readonly completed_at: string | null;
327
334
  }
328
335
 
336
+ /**
337
+ * Resolves to `void`. Derived from an existing return position because the repo
338
+ * lints `noConfusingVoidType` with `--error-on-warnings` and rejects a literal
339
+ * `void` in a union, while the task-0086 R8 contract needs `boolean | void` on
340
+ * `finalizeRun` so legacy 3-arg `Promise<void>` adapters stay assignable.
341
+ * No runtime effect.
342
+ */
343
+ export type LegacyAdapterVoid = Awaited<ReturnType<WorkflowPersistenceAdapter['savePhase']>>;
344
+
329
345
  /** Optional redaction hook: given action options, return sanitized options for persistence. */
330
346
  export type ActionRedactor = (kind: string, options: Record<string, unknown>) => Record<string, unknown>;
331
347
 
332
348
  /** Persistence adapter implemented by DB-backed and test stores. */
333
349
  export interface WorkflowPersistenceAdapter {
334
350
  createRun(record: WorkflowRunRecord): Promise<void>;
335
- finalizeRun(runId: string, status: WorkflowStatus, completedAt: string): Promise<void>;
351
+ /**
352
+ * Finalize a run. Adapters that track `owner_attempt` MUST treat a supplied
353
+ * `fence` as an ownership precondition: when the run's current owner differs
354
+ * (or the run is not active), the row stays untouched and `false` is returned
355
+ * (task 0086 AC11). Adapters without owner tracking may ignore `fence` and
356
+ * return void — legacy custom adapters with the old 3-arg signature remain
357
+ * assignable to this interface.
358
+ */
359
+ finalizeRun(
360
+ runId: string,
361
+ status: WorkflowStatus,
362
+ completedAt: string,
363
+ fence?: { readonly ownerAttempt: string },
364
+ reason?: string,
365
+ ): Promise<boolean | LegacyAdapterVoid>;
336
366
  savePhase(runId: string, phase: string, status: WorkflowStatus): Promise<void>;
337
367
  saveTransition(runId: string, from: string, to: string, trigger: string | null): Promise<void>;
338
368
  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'`.