@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/README.md +1 -1
- package/dist/action-step.d.ts.map +1 -1
- package/dist/action-step.js +12 -4
- package/dist/events.d.ts +8 -0
- package/dist/events.d.ts.map +1 -1
- package/dist/host.d.ts.map +1 -1
- package/dist/host.js +65 -26
- package/dist/persistence.d.ts +19 -6
- package/dist/persistence.d.ts.map +1 -1
- package/dist/persistence.js +37 -11
- package/dist/run-lifecycle.d.ts +15 -4
- package/dist/run-lifecycle.d.ts.map +1 -1
- package/dist/run-lifecycle.js +41 -9
- package/dist/schema-sql.d.ts.map +1 -1
- package/dist/schema-sql.js +3 -1
- package/dist/schema.d.ts +2 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +2 -0
- package/dist/service.d.ts.map +1 -1
- package/dist/service.js +10 -7
- package/dist/state-machine.d.ts.map +1 -1
- package/dist/state-machine.js +21 -9
- package/dist/transition-flow.d.ts.map +1 -1
- package/dist/transition-flow.js +10 -6
- package/dist/types.d.ts +26 -1
- package/dist/types.d.ts.map +1 -1
- package/dist/variables.d.ts +22 -0
- package/dist/variables.d.ts.map +1 -1
- package/dist/variables.js +87 -17
- package/package.json +4 -4
- package/src/action-step.ts +19 -4
- package/src/events.ts +8 -0
- package/src/host.ts +77 -26
- package/src/persistence.ts +59 -10
- package/src/run-lifecycle.ts +50 -7
- package/src/schema-sql.ts +3 -1
- package/src/schema.ts +2 -0
- package/src/service.ts +11 -7
- package/src/state-machine.ts +22 -8
- package/src/transition-flow.ts +11 -5
- package/src/types.ts +31 -1
- package/src/variables.ts +92 -16
package/src/host.ts
CHANGED
|
@@ -10,6 +10,7 @@ import type {
|
|
|
10
10
|
GuardEvaluationResult,
|
|
11
11
|
GuardRunner,
|
|
12
12
|
} from './types';
|
|
13
|
+
import { SHELL_ENV_OPTION } from './variables';
|
|
13
14
|
|
|
14
15
|
/** Registry owner for workflow actions and guards. */
|
|
15
16
|
export class WorkflowEngineHost {
|
|
@@ -142,6 +143,51 @@ export class EventEmitActionRunner implements ActionRunner {
|
|
|
142
143
|
}
|
|
143
144
|
}
|
|
144
145
|
|
|
146
|
+
/** Process output shared by the shell action and guard runners. */
|
|
147
|
+
interface ShellSpawnOutcome {
|
|
148
|
+
readonly stdout: string;
|
|
149
|
+
readonly stderr: string;
|
|
150
|
+
readonly exitCode: number | null;
|
|
151
|
+
readonly timedOut: boolean;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Shared spawn path for ShellActionRunner and ShellGuardRunner (task 0086 R2).
|
|
156
|
+
*
|
|
157
|
+
* Two forms (R4/R3): `command` + explicit `args` → execFile argv (no shell, template
|
|
158
|
+
* values substituted raw are inert); `command` alone → `/bin/sh -c`, with
|
|
159
|
+
* `SHELL_ENV_OPTION` bindings forwarded as env so substituted text is never reparsed
|
|
160
|
+
* as shell syntax.
|
|
161
|
+
*/
|
|
162
|
+
async function spawnShellCommand(
|
|
163
|
+
processExecutor: ProcessExecutor,
|
|
164
|
+
options: Record<string, unknown>,
|
|
165
|
+
workdir: string | undefined,
|
|
166
|
+
): Promise<ShellSpawnOutcome> {
|
|
167
|
+
const command = stringOption(options, 'command');
|
|
168
|
+
const explicitArgs = arrayOption(options, 'args');
|
|
169
|
+
const usesShell = explicitArgs.length === 0;
|
|
170
|
+
const spawn = usesShell ? { command: '/bin/sh', args: ['-c', command] } : { command, args: explicitArgs };
|
|
171
|
+
const timeout = optionalTimeoutOption(options);
|
|
172
|
+
const envOption = options[SHELL_ENV_OPTION];
|
|
173
|
+
const env = envOption !== null && typeof envOption === 'object' ? (envOption as Record<string, string>) : undefined;
|
|
174
|
+
const result = await processExecutor.run({
|
|
175
|
+
command: spawn.command,
|
|
176
|
+
args: spawn.args,
|
|
177
|
+
cwd: optionalStringOption(options, 'cwd', workdir),
|
|
178
|
+
...(env !== undefined ? { env, envMode: 'merge' as const } : {}),
|
|
179
|
+
...(timeout !== undefined ? { timeout } : {}),
|
|
180
|
+
rejectOnError: false,
|
|
181
|
+
forceBuffered: true,
|
|
182
|
+
});
|
|
183
|
+
return {
|
|
184
|
+
stdout: result.stdout,
|
|
185
|
+
stderr: result.stderr,
|
|
186
|
+
exitCode: result.exitCode,
|
|
187
|
+
timedOut: result.outcome === 'timeout',
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
145
191
|
/** Built-in shell action backed by ts-runtime ProcessExecutor. */
|
|
146
192
|
export class ShellActionRunner implements ActionRunner {
|
|
147
193
|
readonly kind = 'shell';
|
|
@@ -158,21 +204,20 @@ export class ShellActionRunner implements ActionRunner {
|
|
|
158
204
|
* the old behavior — fails with a null exit code for any line containing spaces.
|
|
159
205
|
*/
|
|
160
206
|
async execute(options: Record<string, unknown>, context: ActionRunContext): Promise<ActionResult> {
|
|
207
|
+
const spawn = await spawnShellCommand(this.processExecutor, options, context.workdir);
|
|
208
|
+
if (spawn.timedOut) {
|
|
209
|
+
const timeout = optionalTimeoutOption(options);
|
|
210
|
+
return {
|
|
211
|
+
ok: false,
|
|
212
|
+
data: { stdout: spawn.stdout, stderr: spawn.stderr, exitCode: spawn.exitCode, timedOut: true },
|
|
213
|
+
error: `Shell action timed out after ${timeout}ms`,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
161
216
|
const command = stringOption(options, 'command');
|
|
162
|
-
const explicitArgs = arrayOption(options, 'args');
|
|
163
|
-
const usesShell = explicitArgs.length === 0;
|
|
164
|
-
const spawn = usesShell ? { command: '/bin/sh', args: ['-c', command] } : { command, args: explicitArgs };
|
|
165
|
-
const result = await this.processExecutor.run({
|
|
166
|
-
command: spawn.command,
|
|
167
|
-
args: spawn.args,
|
|
168
|
-
cwd: optionalStringOption(options, 'cwd', context.workdir),
|
|
169
|
-
rejectOnError: false,
|
|
170
|
-
forceBuffered: true,
|
|
171
|
-
});
|
|
172
217
|
return {
|
|
173
|
-
ok:
|
|
174
|
-
data: { stdout:
|
|
175
|
-
...(
|
|
218
|
+
ok: spawn.exitCode === 0,
|
|
219
|
+
data: { stdout: spawn.stdout, stderr: spawn.stderr, exitCode: spawn.exitCode },
|
|
220
|
+
...(spawn.exitCode === 0 ? {} : { error: `Command "${command}" exited with ${spawn.exitCode}` }),
|
|
176
221
|
};
|
|
177
222
|
}
|
|
178
223
|
}
|
|
@@ -184,20 +229,15 @@ export class ShellGuardRunner implements GuardRunner {
|
|
|
184
229
|
constructor(private readonly processExecutor: ProcessExecutor) {}
|
|
185
230
|
|
|
186
231
|
async evaluate(options: Record<string, unknown>, context: GuardContext): Promise<GuardEvaluationResult> {
|
|
187
|
-
const
|
|
188
|
-
const explicitArgs = arrayOption(options, 'args');
|
|
189
|
-
const usesShell = explicitArgs.length === 0;
|
|
190
|
-
const spawn = usesShell ? { command: '/bin/sh', args: ['-c', command] } : { command, args: explicitArgs };
|
|
191
|
-
const result = await this.processExecutor.run({
|
|
192
|
-
command: spawn.command,
|
|
193
|
-
args: spawn.args,
|
|
194
|
-
cwd: optionalStringOption(options, 'cwd', context.workdir),
|
|
195
|
-
rejectOnError: false,
|
|
196
|
-
forceBuffered: true,
|
|
197
|
-
});
|
|
232
|
+
const spawn = await spawnShellCommand(this.processExecutor, options, context.workdir);
|
|
198
233
|
return {
|
|
199
|
-
passed:
|
|
200
|
-
report: {
|
|
234
|
+
passed: !spawn.timedOut && spawn.exitCode === 0,
|
|
235
|
+
report: {
|
|
236
|
+
stdout: spawn.stdout,
|
|
237
|
+
stderr: spawn.stderr,
|
|
238
|
+
exitCode: spawn.exitCode,
|
|
239
|
+
...(spawn.timedOut ? { timedOut: true } : {}),
|
|
240
|
+
},
|
|
201
241
|
};
|
|
202
242
|
}
|
|
203
243
|
}
|
|
@@ -222,3 +262,14 @@ function arrayOption(options: Record<string, unknown>, key: string): string[] {
|
|
|
222
262
|
if (Array.isArray(value) && value.every((entry) => typeof entry === 'string')) return value;
|
|
223
263
|
throw new WorkflowValidationError(`Action option "${key}" must be a string array`);
|
|
224
264
|
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Resolve the optional `timeout` option in milliseconds (task 0086 AC14). Undefined
|
|
268
|
+
* passes through; anything that is not a finite positive number is rejected.
|
|
269
|
+
*/
|
|
270
|
+
function optionalTimeoutOption(options: Record<string, unknown>): number | undefined {
|
|
271
|
+
const value = options.timeout;
|
|
272
|
+
if (value === undefined) return undefined;
|
|
273
|
+
if (typeof value === 'number' && Number.isFinite(value) && value > 0) return value;
|
|
274
|
+
throw new WorkflowValidationError('shell option "timeout" must be a positive number of milliseconds');
|
|
275
|
+
}
|
package/src/persistence.ts
CHANGED
|
@@ -99,15 +99,42 @@ export class DbWorkflowPersistenceAdapter implements WorkflowPersistenceAdapter
|
|
|
99
99
|
);
|
|
100
100
|
}
|
|
101
101
|
|
|
102
|
-
/** Finalize a run with terminal status and
|
|
103
|
-
|
|
102
|
+
/** Finalize a run with terminal status, timestamp and opaque reason. With a fence (task 0086 AC11), the
|
|
103
|
+
* update only applies when the run is still running AND owned by `fence.ownerAttempt`;
|
|
104
|
+
* otherwise the row stays untouched and false is returned. Without a fence the legacy
|
|
105
|
+
* unconditional write applies (external service finalization paths). `reason` is opaque
|
|
106
|
+
* engine vocabulary (Spur owns classification) and lands in `runs.terminal_reason` —
|
|
107
|
+
* null when omitted. */
|
|
108
|
+
async finalizeRun(
|
|
109
|
+
runId: string,
|
|
110
|
+
status: WorkflowStatus,
|
|
111
|
+
completedAt: string,
|
|
112
|
+
fence?: { readonly ownerAttempt: string },
|
|
113
|
+
reason?: string,
|
|
114
|
+
): Promise<boolean> {
|
|
115
|
+
if (fence === undefined) {
|
|
116
|
+
await this.db.run(
|
|
117
|
+
'UPDATE runs SET status = ?, completed_at = ?, terminal_reason = ?, updated_at = ? WHERE id = ?',
|
|
118
|
+
status,
|
|
119
|
+
completedAt,
|
|
120
|
+
reason ?? null,
|
|
121
|
+
Date.now(),
|
|
122
|
+
runId,
|
|
123
|
+
);
|
|
124
|
+
return true;
|
|
125
|
+
}
|
|
104
126
|
await this.db.run(
|
|
105
|
-
|
|
127
|
+
"UPDATE runs SET status = ?, completed_at = ?, terminal_reason = ?, updated_at = ? WHERE id = ? AND owner_attempt = ? AND status = 'running'",
|
|
106
128
|
status,
|
|
107
129
|
completedAt,
|
|
130
|
+
reason ?? null,
|
|
108
131
|
Date.now(),
|
|
109
132
|
runId,
|
|
133
|
+
fence.ownerAttempt,
|
|
110
134
|
);
|
|
135
|
+
// Read back: the driver must learn whether its terminal write actually landed.
|
|
136
|
+
const run = await this.loadRun(runId);
|
|
137
|
+
return run !== undefined && run.status === status && run.owner_attempt === fence.ownerAttempt;
|
|
111
138
|
}
|
|
112
139
|
|
|
113
140
|
/** CAS-claim a resumable run to running, recording the owner at the mutation. */
|
|
@@ -119,7 +146,7 @@ export class DbWorkflowPersistenceAdapter implements WorkflowPersistenceAdapter
|
|
|
119
146
|
await this.ensureSchema();
|
|
120
147
|
const placeholders = expectedStatuses.map(() => '?').join(', ');
|
|
121
148
|
await this.db.run(
|
|
122
|
-
`UPDATE runs SET status = 'running', completed_at = NULL, owner_attempt = ?, owner_pid = ?, updated_at = ?
|
|
149
|
+
`UPDATE runs SET status = 'running', completed_at = NULL, terminal_reason = NULL, owner_attempt = ?, owner_pid = ?, updated_at = ?
|
|
123
150
|
WHERE id = ? AND status IN (${placeholders})`,
|
|
124
151
|
owner.attemptId,
|
|
125
152
|
owner.pid ?? null,
|
|
@@ -131,11 +158,13 @@ export class DbWorkflowPersistenceAdapter implements WorkflowPersistenceAdapter
|
|
|
131
158
|
return run !== undefined && run.status === 'running' && run.owner_attempt === owner.attemptId ? run : undefined;
|
|
132
159
|
}
|
|
133
160
|
|
|
134
|
-
/** CAS running → interrupted with a reason (lost-owner / crash reconciliation).
|
|
161
|
+
/** CAS running → interrupted with a reason (lost-owner / crash reconciliation).
|
|
162
|
+
* The reason also lands in `terminal_reason` so every closed row carries one. */
|
|
135
163
|
async interruptRun(runId: string, reason: string): Promise<WorkflowRunRecord | undefined> {
|
|
136
164
|
await this.ensureSchema();
|
|
137
165
|
await this.db.run(
|
|
138
|
-
"UPDATE runs SET status = 'interrupted', interrupt_reason = ?, completed_at = NULL, updated_at = ? WHERE id = ? AND status = 'running'",
|
|
166
|
+
"UPDATE runs SET status = 'interrupted', interrupt_reason = ?, terminal_reason = ?, completed_at = NULL, updated_at = ? WHERE id = ? AND status = 'running'",
|
|
167
|
+
reason,
|
|
139
168
|
reason,
|
|
140
169
|
Date.now(),
|
|
141
170
|
runId,
|
|
@@ -394,10 +423,27 @@ export class MemoryWorkflowPersistenceAdapter implements WorkflowPersistenceAdap
|
|
|
394
423
|
this.runs.set(record.id, record);
|
|
395
424
|
}
|
|
396
425
|
|
|
397
|
-
/** Finalize a run with terminal status and
|
|
398
|
-
|
|
426
|
+
/** Finalize a run with terminal status, timestamp and opaque reason. With a fence (task 0086 AC11),
|
|
427
|
+
* the write only applies when the run is still running AND owned by `fence.ownerAttempt`;
|
|
428
|
+
* otherwise the row stays untouched and false is returned. */
|
|
429
|
+
async finalizeRun(
|
|
430
|
+
runId: string,
|
|
431
|
+
status: WorkflowStatus,
|
|
432
|
+
completedAt: string,
|
|
433
|
+
fence?: { readonly ownerAttempt: string },
|
|
434
|
+
reason?: string,
|
|
435
|
+
): Promise<boolean> {
|
|
399
436
|
const run = this.runs.get(runId);
|
|
400
|
-
if (
|
|
437
|
+
if (fence === undefined) {
|
|
438
|
+
if (run !== undefined)
|
|
439
|
+
this.runs.set(runId, { ...run, status, completed_at: completedAt, terminal_reason: reason ?? null });
|
|
440
|
+
return true;
|
|
441
|
+
}
|
|
442
|
+
if (run === undefined || run.owner_attempt !== fence.ownerAttempt || run.status !== 'running') {
|
|
443
|
+
return false;
|
|
444
|
+
}
|
|
445
|
+
this.runs.set(runId, { ...run, status, completed_at: completedAt, terminal_reason: reason ?? null });
|
|
446
|
+
return true;
|
|
401
447
|
}
|
|
402
448
|
|
|
403
449
|
/** CAS-claim a resumable run to running, recording the owner at the mutation. */
|
|
@@ -414,6 +460,7 @@ export class MemoryWorkflowPersistenceAdapter implements WorkflowPersistenceAdap
|
|
|
414
460
|
...run,
|
|
415
461
|
status: 'running',
|
|
416
462
|
completed_at: null,
|
|
463
|
+
terminal_reason: null,
|
|
417
464
|
owner_attempt: owner.attemptId,
|
|
418
465
|
owner_pid: owner.pid ?? null,
|
|
419
466
|
};
|
|
@@ -421,7 +468,8 @@ export class MemoryWorkflowPersistenceAdapter implements WorkflowPersistenceAdap
|
|
|
421
468
|
return claimed;
|
|
422
469
|
}
|
|
423
470
|
|
|
424
|
-
/** CAS running → interrupted with a reason (lost-owner / crash reconciliation).
|
|
471
|
+
/** CAS running → interrupted with a reason (lost-owner / crash reconciliation).
|
|
472
|
+
* The reason also lands in `terminal_reason` so every closed row carries one. */
|
|
425
473
|
async interruptRun(runId: string, reason: string): Promise<WorkflowRunRecord | undefined> {
|
|
426
474
|
const run = this.runs.get(runId);
|
|
427
475
|
if (run === undefined || run.status !== 'running') return undefined;
|
|
@@ -429,6 +477,7 @@ export class MemoryWorkflowPersistenceAdapter implements WorkflowPersistenceAdap
|
|
|
429
477
|
...run,
|
|
430
478
|
status: 'interrupted',
|
|
431
479
|
interrupt_reason: reason,
|
|
480
|
+
terminal_reason: reason,
|
|
432
481
|
};
|
|
433
482
|
this.runs.set(runId, interrupted);
|
|
434
483
|
return interrupted;
|
package/src/run-lifecycle.ts
CHANGED
|
@@ -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,48 @@ 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, reason?: 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, undefined, reason);
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
const applied = await this.persistence.finalizeRun(
|
|
237
|
+
this.runId,
|
|
238
|
+
status,
|
|
239
|
+
completedAt,
|
|
240
|
+
{
|
|
241
|
+
ownerAttempt: this.ownerAttempt,
|
|
242
|
+
},
|
|
243
|
+
reason,
|
|
244
|
+
);
|
|
245
|
+
if (applied === false) {
|
|
246
|
+
void this.events?.emit('workflow.run.stale_owner', {
|
|
247
|
+
runId: this.runId,
|
|
248
|
+
ownerAttemptId: this.ownerAttempt,
|
|
249
|
+
status,
|
|
250
|
+
severity: 'warning',
|
|
251
|
+
});
|
|
252
|
+
throw new WorkflowResumeError(
|
|
253
|
+
`stale owner "${this.ownerAttempt}" cannot finalize run "${this.runId}" as "${status}": ownership was lost`,
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
217
258
|
private async execute(loop: (lifecycle: RunLifecycle) => Promise<WorkflowRunResult>): Promise<WorkflowRunResult> {
|
|
218
259
|
try {
|
|
219
260
|
return await loop(this);
|
|
220
261
|
} catch (error) {
|
|
221
262
|
// Preserve the original failure, including a failed attempt to mark the run failed.
|
|
222
263
|
try {
|
|
223
|
-
await this.
|
|
264
|
+
await this.finalizeAsOwner('failed', new Date().toISOString(), 'failed');
|
|
224
265
|
} catch (finalizeError) {
|
|
225
266
|
throw new AggregateError([error, finalizeError], 'Workflow execution and failure persistence failed');
|
|
226
267
|
}
|
|
@@ -306,10 +347,11 @@ export class RunLifecycle {
|
|
|
306
347
|
});
|
|
307
348
|
}
|
|
308
349
|
|
|
309
|
-
/** Finalize the run as succeeded and return its result.
|
|
310
|
-
|
|
350
|
+
/** Finalize the run as succeeded and return its result. `reason` carries a declared
|
|
351
|
+
* transition terminal reason when the run closed through such an edge. */
|
|
352
|
+
async done(finalState: string, transitionsTaken: number, reason?: string): Promise<WorkflowRunResult> {
|
|
311
353
|
await this.persistence.savePhase(this.runId, finalState, 'done');
|
|
312
|
-
await this.
|
|
354
|
+
await this.finalizeAsOwner('done', new Date().toISOString(), reason);
|
|
313
355
|
this.logger.info('workflow run done', { finalState, transitionsTaken });
|
|
314
356
|
addSpanEvent('workflow.run.done', { runId: this.runId, finalState, transitionsTaken });
|
|
315
357
|
void this.events?.emit('workflow.run.done', {
|
|
@@ -319,13 +361,13 @@ export class RunLifecycle {
|
|
|
319
361
|
externalKey: this.externalKey,
|
|
320
362
|
severity: 'info',
|
|
321
363
|
});
|
|
322
|
-
return this.result('done', finalState, transitionsTaken);
|
|
364
|
+
return this.result('done', finalState, transitionsTaken, reason);
|
|
323
365
|
}
|
|
324
366
|
|
|
325
367
|
/** Finalize the run as failed and return its result. */
|
|
326
368
|
async fail(finalState: string, transitionsTaken: number, reason = 'failed'): Promise<WorkflowRunResult> {
|
|
327
369
|
await this.persistence.savePhase(this.runId, finalState, 'failed');
|
|
328
|
-
await this.
|
|
370
|
+
await this.finalizeAsOwner('failed', new Date().toISOString(), reason);
|
|
329
371
|
addSpanEvent('workflow.run.failed', { runId: this.runId, finalState, reason });
|
|
330
372
|
void this.events?.emit('workflow.run.failed', {
|
|
331
373
|
runId: this.runId,
|
|
@@ -350,6 +392,7 @@ export class RunLifecycle {
|
|
|
350
392
|
transitionsTaken: number,
|
|
351
393
|
vars?: Vars,
|
|
352
394
|
lastActionResult?: ActionResult,
|
|
395
|
+
reason?: string,
|
|
353
396
|
): Promise<WorkflowRunResult> {
|
|
354
397
|
const data: Record<string, unknown> = { transitionsTaken };
|
|
355
398
|
if (vars !== undefined) data.effectiveVars = vars;
|
|
@@ -357,7 +400,7 @@ export class RunLifecycle {
|
|
|
357
400
|
if (lastActionResult !== undefined) data.lastActionResult = { ok: lastActionResult.ok };
|
|
358
401
|
await this.persistence.saveWorkflowState(this.runId, stateOrNodeId, data);
|
|
359
402
|
await this.persistence.savePhase(this.runId, stateOrNodeId, 'paused');
|
|
360
|
-
await this.
|
|
403
|
+
await this.finalizeAsOwner('paused', new Date().toISOString(), reason);
|
|
361
404
|
this.logger.info('workflow run paused', { stateOrNodeId, transitionsTaken });
|
|
362
405
|
addSpanEvent('workflow.run.paused', { runId: this.runId, node: stateOrNodeId, transitionsTaken });
|
|
363
406
|
void this.events?.emit('workflow.run.paused', {
|
package/src/schema-sql.ts
CHANGED
|
@@ -14,7 +14,8 @@ CREATE TABLE IF NOT EXISTS runs (
|
|
|
14
14
|
updated_at INTEGER NOT NULL DEFAULT 0,
|
|
15
15
|
owner_attempt TEXT,
|
|
16
16
|
owner_pid INTEGER,
|
|
17
|
-
interrupt_reason TEXT
|
|
17
|
+
interrupt_reason TEXT,
|
|
18
|
+
terminal_reason TEXT
|
|
18
19
|
);
|
|
19
20
|
|
|
20
21
|
CREATE UNIQUE INDEX IF NOT EXISTS idx_runs_external_key
|
|
@@ -76,4 +77,5 @@ export const WORKFLOW_ENGINE_MIGRATIONS_SQL = `
|
|
|
76
77
|
ALTER TABLE runs ADD COLUMN owner_attempt TEXT;
|
|
77
78
|
ALTER TABLE runs ADD COLUMN owner_pid INTEGER;
|
|
78
79
|
ALTER TABLE runs ADD COLUMN interrupt_reason TEXT;
|
|
80
|
+
ALTER TABLE runs ADD COLUMN terminal_reason TEXT;
|
|
79
81
|
`.trim();
|
package/src/schema.ts
CHANGED
|
@@ -107,6 +107,8 @@ export const StateMachineWorkflowDefSchema = z
|
|
|
107
107
|
description: z.string().optional(),
|
|
108
108
|
trigger: z.string().optional(),
|
|
109
109
|
guard: GuardDefSchema.optional(),
|
|
110
|
+
/** Declared terminal reason carried onto the runs row when this edge closes the run. */
|
|
111
|
+
terminalReason: z.string().optional(),
|
|
110
112
|
})
|
|
111
113
|
.strict(),
|
|
112
114
|
),
|
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
|
-
|
|
348
|
-
|
|
349
|
-
|
|
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);
|
package/src/state-machine.ts
CHANGED
|
@@ -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
|
|
|
@@ -74,6 +75,10 @@ export class StateMachineDriver {
|
|
|
74
75
|
// phase atomically (every iteration after the first), `enter` must skip
|
|
75
76
|
// the persist half to avoid duplicate INSERT rows (ADR-020).
|
|
76
77
|
let persistedViaHop = false;
|
|
78
|
+
// Declared `terminalReason` of the transition just taken (task 0937). Consumed only
|
|
79
|
+
// when the loop's terminal check closes the run; cleared otherwise so action-driven
|
|
80
|
+
// terminal/pause/fail paths keep their built-in reasons.
|
|
81
|
+
let declaredTerminalReason: string | undefined;
|
|
77
82
|
|
|
78
83
|
if (current === undefined) {
|
|
79
84
|
const label = resumeFromState ?? workflow.initialState;
|
|
@@ -143,9 +148,11 @@ export class StateMachineDriver {
|
|
|
143
148
|
|
|
144
149
|
const outbound = workflow.transitions.filter((transition) => transition.from === current?.id);
|
|
145
150
|
if (terminal.has(current.id) || outbound.length === 0) {
|
|
151
|
+
const declared = declaredTerminalReason;
|
|
152
|
+
declaredTerminalReason = undefined;
|
|
146
153
|
return failure.has(current.id)
|
|
147
|
-
? await lifecycle.fail(current.id, transitionsTaken, `terminal:${current.id}`)
|
|
148
|
-
: await lifecycle.done(current.id, transitionsTaken);
|
|
154
|
+
? await lifecycle.fail(current.id, transitionsTaken, declared ?? `terminal:${current.id}`)
|
|
155
|
+
: await lifecycle.done(current.id, transitionsTaken, declared);
|
|
149
156
|
}
|
|
150
157
|
|
|
151
158
|
// 5. Evaluate transition guards in declaration order and pick the first passing transition.
|
|
@@ -156,6 +163,7 @@ export class StateMachineDriver {
|
|
|
156
163
|
runId,
|
|
157
164
|
current: current.id,
|
|
158
165
|
vars,
|
|
166
|
+
env,
|
|
159
167
|
lastActionResult,
|
|
160
168
|
// Shell guards use relative paths (e.g. .spur/run/${vars.__runId}-*) —
|
|
161
169
|
// must share the run's workdir with actions or they read the process cwd.
|
|
@@ -214,6 +222,7 @@ export class StateMachineDriver {
|
|
|
214
222
|
const nextState = states.get(nextTransition.to);
|
|
215
223
|
if (nextState === undefined) throw new FSMError(`Transition target "${nextTransition.to}" is not declared`);
|
|
216
224
|
current = nextState;
|
|
225
|
+
declaredTerminalReason = nextTransition.terminalReason;
|
|
217
226
|
persistedViaHop = true;
|
|
218
227
|
}
|
|
219
228
|
}
|
|
@@ -231,11 +240,16 @@ async function firstPassingTransition(
|
|
|
231
240
|
for (const transition of transitions) {
|
|
232
241
|
if (transition.guard === undefined) return transition;
|
|
233
242
|
// 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
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
243
|
+
// same var interpolation as actions (e.g. `spur task check ${vars.wbs}`). Shell-form
|
|
244
|
+
// guards bind command refs to env instead of raw substitution (task 0086 M1); the
|
|
245
|
+
// env bindings pass through to the runner (guard options are never persisted).
|
|
246
|
+
const resolvedOptions =
|
|
247
|
+
transition.guard.kind === 'shell'
|
|
248
|
+
? resolveShellCommandTemplates(transition.guard.options ?? {}, {
|
|
249
|
+
vars: context.vars,
|
|
250
|
+
env: context.env ?? {},
|
|
251
|
+
})
|
|
252
|
+
: resolveTemplates(transition.guard.options ?? {}, { vars: context.vars, env: context.env ?? {} });
|
|
239
253
|
const passed = await host.evaluateGuard(transition.guard.kind, resolvedOptions, context);
|
|
240
254
|
lifecycle.guardEvaluated(context.current, transition.to, transition.guard.kind, passed);
|
|
241
255
|
if (passed) return transition;
|
package/src/transition-flow.ts
CHANGED
|
@@ -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
|
-
|
|
204
|
-
|
|
205
|
-
|
|
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;
|