@workflow/world-local 5.0.0-beta.10 → 5.0.0-beta.3

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.
Files changed (74) hide show
  1. package/dist/config.d.ts +17 -5
  2. package/dist/config.d.ts.map +1 -1
  3. package/dist/config.js +18 -13
  4. package/dist/config.js.map +1 -1
  5. package/dist/fs.d.ts +102 -2
  6. package/dist/fs.d.ts.map +1 -1
  7. package/dist/fs.js +291 -24
  8. package/dist/fs.js.map +1 -1
  9. package/dist/index.d.ts +15 -2
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +82 -5
  12. package/dist/index.js.map +1 -1
  13. package/dist/init.d.ts +91 -0
  14. package/dist/init.d.ts.map +1 -0
  15. package/dist/init.js +268 -0
  16. package/dist/init.js.map +1 -0
  17. package/dist/instrumentObject.d.ts +8 -0
  18. package/dist/instrumentObject.d.ts.map +1 -0
  19. package/dist/instrumentObject.js +66 -0
  20. package/dist/instrumentObject.js.map +1 -0
  21. package/dist/queue.d.ts +8 -1
  22. package/dist/queue.d.ts.map +1 -1
  23. package/dist/queue.js +164 -53
  24. package/dist/queue.js.map +1 -1
  25. package/dist/storage/events-storage.d.ts +7 -0
  26. package/dist/storage/events-storage.d.ts.map +1 -0
  27. package/dist/storage/events-storage.js +760 -0
  28. package/dist/storage/events-storage.js.map +1 -0
  29. package/dist/storage/filters.d.ts +22 -0
  30. package/dist/storage/filters.d.ts.map +1 -0
  31. package/dist/storage/filters.js +33 -0
  32. package/dist/storage/filters.js.map +1 -0
  33. package/dist/storage/helpers.d.ts +18 -0
  34. package/dist/storage/helpers.d.ts.map +1 -0
  35. package/dist/storage/helpers.js +44 -0
  36. package/dist/storage/helpers.js.map +1 -0
  37. package/dist/storage/hooks-storage.d.ts +12 -0
  38. package/dist/storage/hooks-storage.d.ts.map +1 -0
  39. package/dist/storage/hooks-storage.js +93 -0
  40. package/dist/storage/hooks-storage.js.map +1 -0
  41. package/dist/storage/index.d.ts +12 -0
  42. package/dist/storage/index.d.ts.map +1 -0
  43. package/dist/storage/index.js +32 -0
  44. package/dist/storage/index.js.map +1 -0
  45. package/dist/storage/legacy.d.ts +13 -0
  46. package/dist/storage/legacy.d.ts.map +1 -0
  47. package/dist/storage/legacy.js +77 -0
  48. package/dist/storage/legacy.js.map +1 -0
  49. package/dist/storage/runs-storage.d.ts +7 -0
  50. package/dist/storage/runs-storage.d.ts.map +1 -0
  51. package/dist/storage/runs-storage.js +59 -0
  52. package/dist/storage/runs-storage.js.map +1 -0
  53. package/dist/storage/steps-storage.d.ts +7 -0
  54. package/dist/storage/steps-storage.d.ts.map +1 -0
  55. package/dist/storage/steps-storage.js +52 -0
  56. package/dist/storage/steps-storage.js.map +1 -0
  57. package/dist/storage.d.ts +9 -2
  58. package/dist/storage.d.ts.map +1 -1
  59. package/dist/storage.js +8 -455
  60. package/dist/storage.js.map +1 -1
  61. package/dist/streamer.d.ts +4 -2
  62. package/dist/streamer.d.ts.map +1 -1
  63. package/dist/streamer.js +456 -104
  64. package/dist/streamer.js.map +1 -1
  65. package/dist/telemetry.d.ts +28 -0
  66. package/dist/telemetry.d.ts.map +1 -0
  67. package/dist/telemetry.js +71 -0
  68. package/dist/telemetry.js.map +1 -0
  69. package/dist/test-helpers.d.ts +54 -0
  70. package/dist/test-helpers.d.ts.map +1 -0
  71. package/dist/test-helpers.js +118 -0
  72. package/dist/test-helpers.js.map +1 -0
  73. package/dist/util.js.map +1 -1
  74. package/package.json +12 -11
@@ -0,0 +1,760 @@
1
+ import fs from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { EntityConflictError, HookNotFoundError, RunExpiredError, RunNotSupportedError, TooEarlyError, WorkflowWorldError, } from '@workflow/errors';
4
+ import { EventSchema, HookSchema, isLegacySpecVersion, requiresNewerWorld, SPEC_VERSION_CURRENT, StepSchema, validateUlidTimestamp, WaitSchema, WorkflowRunSchema, } from '@workflow/world';
5
+ import { DEFAULT_RESOLVE_DATA_OPTION } from '../config.js';
6
+ import { assertSafeEntityId, deleteJSON, jsonReplacer, listJSONFiles, paginatedFileSystemQuery, readJSONWithFallback, resolveWithinBase, taggedPath, writeExclusive, writeJSON, } from '../fs.js';
7
+ import { stripEventDataRefs } from './filters.js';
8
+ import { getObjectCreatedAt, hashToken, monotonicUlid } from './helpers.js';
9
+ import { deleteAllHooksForRun } from './hooks-storage.js';
10
+ import { handleLegacyEvent } from './legacy.js';
11
+ /**
12
+ * Helper function to delete all waits associated with a workflow run.
13
+ * Called when a run reaches a terminal state.
14
+ */
15
+ async function deleteAllWaitsForRun(basedir, runId) {
16
+ const waitsDir = path.join(basedir, 'waits');
17
+ const files = await listJSONFiles(waitsDir);
18
+ for (const file of files) {
19
+ // fileIds may contain tag suffixes (e.g., "wrun_ABC-corrId.vitest-0")
20
+ // but startsWith still matches correctly since the tag is a suffix.
21
+ if (file.startsWith(`${runId}-`)) {
22
+ const waitPath = path.join(waitsDir, `${file}.json`);
23
+ await deleteJSON(waitPath);
24
+ }
25
+ }
26
+ }
27
+ /**
28
+ * Creates the events storage implementation using the filesystem.
29
+ * Implements the Storage['events'] interface with create, list, and listByCorrelationId operations.
30
+ */
31
+ export function createEventsStorage(basedir, tag) {
32
+ return {
33
+ async create(runId, data, params) {
34
+ const eventId = `evnt_${monotonicUlid()}`;
35
+ const now = new Date();
36
+ // Validate request-supplied IDs before they're concatenated into
37
+ // filesystem paths. This is the primary defense against path traversal
38
+ // attacks where a client supplies runId / correlationId values like
39
+ // "../../../package" to read or write files outside the storage root.
40
+ if (runId != null && runId !== '') {
41
+ assertSafeEntityId('runId', runId);
42
+ }
43
+ if ('correlationId' in data &&
44
+ typeof data.correlationId === 'string' &&
45
+ data.correlationId.length > 0) {
46
+ assertSafeEntityId('correlationId', data.correlationId);
47
+ }
48
+ // For run_created events, use client-provided runId or generate one server-side
49
+ let effectiveRunId;
50
+ if (data.eventType === 'run_created' && (!runId || runId === '')) {
51
+ effectiveRunId = `wrun_${monotonicUlid()}`;
52
+ }
53
+ else if (!runId) {
54
+ throw new Error('runId is required for non-run_created events');
55
+ }
56
+ else {
57
+ effectiveRunId = runId;
58
+ }
59
+ // Validate client-provided runId timestamp is within acceptable threshold
60
+ if (data.eventType === 'run_created' && runId && runId !== '') {
61
+ const validationError = validateUlidTimestamp(effectiveRunId, 'wrun_');
62
+ if (validationError) {
63
+ throw new WorkflowWorldError(validationError);
64
+ }
65
+ }
66
+ // specVersion is always sent by the runtime, but we provide a fallback for safety
67
+ const effectiveSpecVersion = data.specVersion ?? SPEC_VERSION_CURRENT;
68
+ // Helper to check if run is in terminal state
69
+ const isRunTerminal = (status) => ['completed', 'failed', 'cancelled'].includes(status);
70
+ // Helper to check if step is in terminal state
71
+ const isStepTerminal = (status) => ['completed', 'failed', 'cancelled'].includes(status);
72
+ // Get current run state for validation (if not creating a new run)
73
+ // Skip run validation for step_completed and step_retrying - they only operate
74
+ // on running steps, and running steps are always allowed to modify regardless
75
+ // of run state. This optimization saves filesystem reads per step event.
76
+ let currentRun = null;
77
+ const skipRunValidationEvents = ['step_completed', 'step_retrying'];
78
+ if (data.eventType !== 'run_created' &&
79
+ !skipRunValidationEvents.includes(data.eventType)) {
80
+ currentRun = await readJSONWithFallback(basedir, 'runs', effectiveRunId, WorkflowRunSchema, tag);
81
+ // Resilient start: run_started on non-existent run with eventData
82
+ // creates the run first, so the queue can bootstrap a run that
83
+ // failed to create during start().
84
+ if (data.eventType === 'run_started' &&
85
+ !currentRun &&
86
+ 'eventData' in data &&
87
+ data.eventData) {
88
+ const runInputData = data.eventData;
89
+ if (runInputData.deploymentId &&
90
+ runInputData.workflowName &&
91
+ runInputData.input !== undefined) {
92
+ // Atomically try to create the run entity. writeExclusive
93
+ // uses O_CREAT|O_EXCL so only the first writer wins,
94
+ // preventing a TOCTOU race where a concurrent run_created
95
+ // from start() could overwrite a run that was already
96
+ // transitioned to 'running'.
97
+ const createdRun = {
98
+ runId: effectiveRunId,
99
+ deploymentId: runInputData.deploymentId,
100
+ status: 'pending',
101
+ workflowName: runInputData.workflowName,
102
+ specVersion: effectiveSpecVersion,
103
+ executionContext: runInputData.executionContext,
104
+ input: runInputData.input,
105
+ output: undefined,
106
+ error: undefined,
107
+ startedAt: undefined,
108
+ completedAt: undefined,
109
+ createdAt: now,
110
+ updatedAt: now,
111
+ };
112
+ const runPath = taggedPath(basedir, 'runs', effectiveRunId, tag);
113
+ const created = await writeExclusive(runPath, JSON.stringify(createdRun, jsonReplacer));
114
+ if (created) {
115
+ // We created the run — also write the run_created event.
116
+ const runCreatedEventId = `evnt_${monotonicUlid()}`;
117
+ const runCreatedEvent = {
118
+ eventType: 'run_created',
119
+ runId: effectiveRunId,
120
+ eventId: runCreatedEventId,
121
+ createdAt: now,
122
+ specVersion: effectiveSpecVersion,
123
+ eventData: {
124
+ deploymentId: runInputData.deploymentId,
125
+ workflowName: runInputData.workflowName,
126
+ input: runInputData.input,
127
+ executionContext: runInputData.executionContext,
128
+ },
129
+ };
130
+ const createdCompositeKey = `${effectiveRunId}-${runCreatedEventId}`;
131
+ await writeJSON(taggedPath(basedir, 'events', createdCompositeKey, tag), runCreatedEvent);
132
+ currentRun = createdRun;
133
+ }
134
+ else {
135
+ // Run already exists (concurrent run_created won the
136
+ // race). Re-read it so downstream logic sees the real state.
137
+ currentRun = await readJSONWithFallback(basedir, 'runs', effectiveRunId, WorkflowRunSchema, tag);
138
+ }
139
+ }
140
+ }
141
+ }
142
+ // ============================================================
143
+ // VERSION COMPATIBILITY: Check run spec version
144
+ // ============================================================
145
+ // For events that have fetched the run, check version compatibility.
146
+ // Skip for run_created (no existing run) and runtime events (step_completed, step_retrying).
147
+ if (currentRun) {
148
+ // Check if run requires a newer world version
149
+ if (requiresNewerWorld(currentRun.specVersion)) {
150
+ throw new RunNotSupportedError(currentRun.specVersion, SPEC_VERSION_CURRENT);
151
+ }
152
+ // Route to legacy handler for pre-event-sourcing runs
153
+ if (isLegacySpecVersion(currentRun.specVersion)) {
154
+ return handleLegacyEvent(basedir, effectiveRunId, data, currentRun, params);
155
+ }
156
+ }
157
+ // ============================================================
158
+ // VALIDATION: Terminal state and event ordering checks
159
+ // ============================================================
160
+ // Run terminal state validation
161
+ if (currentRun && isRunTerminal(currentRun.status)) {
162
+ const runTerminalEvents = [
163
+ 'run_started',
164
+ 'run_completed',
165
+ 'run_failed',
166
+ ];
167
+ // Idempotent operation: run_cancelled on already cancelled run is allowed
168
+ if (data.eventType === 'run_cancelled' &&
169
+ currentRun.status === 'cancelled') {
170
+ // Return existing state (idempotent)
171
+ const event = {
172
+ ...data,
173
+ runId: effectiveRunId,
174
+ eventId,
175
+ createdAt: now,
176
+ specVersion: effectiveSpecVersion,
177
+ };
178
+ const compositeKey = `${effectiveRunId}-${eventId}`;
179
+ await writeJSON(taggedPath(basedir, 'events', compositeKey, tag), event);
180
+ const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;
181
+ return {
182
+ event: stripEventDataRefs(event, resolveData),
183
+ run: currentRun,
184
+ };
185
+ }
186
+ // For run_started on terminal runs, use RunExpiredError so the
187
+ // runtime knows to exit without retrying.
188
+ if (data.eventType === 'run_started') {
189
+ throw new RunExpiredError(`Workflow run "${effectiveRunId}" is already in terminal state "${currentRun.status}"`);
190
+ }
191
+ // Other run state transitions are not allowed on terminal runs
192
+ if (runTerminalEvents.includes(data.eventType) ||
193
+ data.eventType === 'run_cancelled') {
194
+ throw new EntityConflictError(`Cannot transition run from terminal state "${currentRun.status}"`);
195
+ }
196
+ // Creating new entities on terminal runs is not allowed
197
+ if (data.eventType === 'step_created' ||
198
+ data.eventType === 'hook_created' ||
199
+ data.eventType === 'wait_created') {
200
+ throw new EntityConflictError(`Cannot create new entities on run in terminal state "${currentRun.status}"`);
201
+ }
202
+ }
203
+ // Step-related event validation (ordering and terminal state)
204
+ // Store existingStep so we can reuse it later (avoid double read)
205
+ let validatedStep = null;
206
+ const stepEvents = [
207
+ 'step_started',
208
+ 'step_completed',
209
+ 'step_failed',
210
+ 'step_retrying',
211
+ ];
212
+ if (stepEvents.includes(data.eventType) && data.correlationId) {
213
+ const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;
214
+ validatedStep = await readJSONWithFallback(basedir, 'steps', stepCompositeKey, StepSchema, tag);
215
+ // Event ordering: step must exist before these events
216
+ if (!validatedStep) {
217
+ throw new WorkflowWorldError(`Step "${data.correlationId}" not found`);
218
+ }
219
+ // Step terminal state validation
220
+ if (isStepTerminal(validatedStep.status)) {
221
+ throw new EntityConflictError(`Cannot modify step in terminal state "${validatedStep.status}"`);
222
+ }
223
+ // On terminal runs: only allow completing/failing in-progress steps
224
+ if (currentRun && isRunTerminal(currentRun.status)) {
225
+ if (validatedStep.status !== 'running') {
226
+ throw new RunExpiredError(`Cannot modify non-running step on run in terminal state "${currentRun.status}"`);
227
+ }
228
+ }
229
+ }
230
+ // Hook-related event validation (ordering)
231
+ const hookEventsRequiringExistence = ['hook_disposed', 'hook_received'];
232
+ if (hookEventsRequiringExistence.includes(data.eventType) &&
233
+ data.correlationId) {
234
+ const existingHook = await readJSONWithFallback(basedir, 'hooks', data.correlationId, HookSchema, tag);
235
+ if (!existingHook) {
236
+ throw new HookNotFoundError(data.correlationId);
237
+ }
238
+ }
239
+ const event = {
240
+ ...data,
241
+ runId: effectiveRunId,
242
+ eventId,
243
+ createdAt: now,
244
+ specVersion: effectiveSpecVersion,
245
+ };
246
+ // Strip eventData from run_started — it belongs on run_created only.
247
+ if (data.eventType === 'run_started' && 'eventData' in event) {
248
+ delete event.eventData;
249
+ }
250
+ // Track entity created/updated for EventResult
251
+ let run;
252
+ let step;
253
+ let hook;
254
+ let wait;
255
+ // Create/update entity based on event type (event-sourced architecture)
256
+ // Run lifecycle events
257
+ if (data.eventType === 'run_created' && 'eventData' in data) {
258
+ const runData = data.eventData;
259
+ run = {
260
+ runId: effectiveRunId,
261
+ deploymentId: runData.deploymentId,
262
+ status: 'pending',
263
+ workflowName: runData.workflowName,
264
+ // Propagate specVersion from the event to the run entity
265
+ specVersion: effectiveSpecVersion,
266
+ executionContext: runData.executionContext,
267
+ input: runData.input,
268
+ output: undefined,
269
+ error: undefined,
270
+ startedAt: undefined,
271
+ completedAt: undefined,
272
+ createdAt: now,
273
+ updatedAt: now,
274
+ };
275
+ // Use writeExclusive (O_CREAT|O_EXCL) to atomically create the
276
+ // run entity file. This prevents a TOCTOU race with the resilient
277
+ // start path (run_started on non-existent run) that could result
278
+ // in duplicate run_created events in the event log.
279
+ const runPath = taggedPath(basedir, 'runs', effectiveRunId, tag);
280
+ const created = await writeExclusive(runPath, JSON.stringify(run, jsonReplacer, 2));
281
+ if (!created) {
282
+ throw new EntityConflictError(`Workflow run "${effectiveRunId}" already exists`);
283
+ }
284
+ }
285
+ else if (data.eventType === 'run_started') {
286
+ // Reuse currentRun from validation (already read above)
287
+ if (currentRun) {
288
+ // If already running, return the run without inserting a
289
+ // duplicate event. This makes run_started idempotent for
290
+ // concurrent invocations. We omit preloaded events here
291
+ // because this is a rare race-condition path — the runtime
292
+ // falls back to getAllWorkflowRunEvents().
293
+ if (currentRun.status === 'running') {
294
+ return { run: currentRun };
295
+ }
296
+ run = {
297
+ runId: currentRun.runId,
298
+ deploymentId: currentRun.deploymentId,
299
+ workflowName: currentRun.workflowName,
300
+ specVersion: currentRun.specVersion,
301
+ executionContext: currentRun.executionContext,
302
+ input: currentRun.input,
303
+ createdAt: currentRun.createdAt,
304
+ expiredAt: currentRun.expiredAt,
305
+ status: 'running',
306
+ output: undefined,
307
+ error: undefined,
308
+ completedAt: undefined,
309
+ startedAt: currentRun.startedAt ?? now,
310
+ updatedAt: now,
311
+ };
312
+ await writeJSON(taggedPath(basedir, 'runs', effectiveRunId, tag), run, { overwrite: true });
313
+ }
314
+ }
315
+ else if (data.eventType === 'run_completed' && 'eventData' in data) {
316
+ const completedData = data.eventData;
317
+ // Reuse currentRun from validation (already read above)
318
+ if (currentRun) {
319
+ run = {
320
+ runId: currentRun.runId,
321
+ deploymentId: currentRun.deploymentId,
322
+ workflowName: currentRun.workflowName,
323
+ specVersion: currentRun.specVersion,
324
+ executionContext: currentRun.executionContext,
325
+ input: currentRun.input,
326
+ createdAt: currentRun.createdAt,
327
+ expiredAt: currentRun.expiredAt,
328
+ startedAt: currentRun.startedAt,
329
+ status: 'completed',
330
+ output: completedData.output,
331
+ error: undefined,
332
+ completedAt: now,
333
+ updatedAt: now,
334
+ };
335
+ await writeJSON(taggedPath(basedir, 'runs', effectiveRunId, tag), run, { overwrite: true });
336
+ await Promise.all([
337
+ deleteAllHooksForRun(basedir, effectiveRunId),
338
+ deleteAllWaitsForRun(basedir, effectiveRunId),
339
+ ]);
340
+ }
341
+ }
342
+ else if (data.eventType === 'run_failed' && 'eventData' in data) {
343
+ const failedData = data.eventData;
344
+ // Reuse currentRun from validation (already read above)
345
+ if (currentRun) {
346
+ run = {
347
+ runId: currentRun.runId,
348
+ deploymentId: currentRun.deploymentId,
349
+ workflowName: currentRun.workflowName,
350
+ specVersion: currentRun.specVersion,
351
+ executionContext: currentRun.executionContext,
352
+ input: currentRun.input,
353
+ createdAt: currentRun.createdAt,
354
+ expiredAt: currentRun.expiredAt,
355
+ startedAt: currentRun.startedAt,
356
+ status: 'failed',
357
+ output: undefined,
358
+ error: {
359
+ message: typeof failedData.error === 'string'
360
+ ? failedData.error
361
+ : (failedData.error?.message ?? 'Unknown error'),
362
+ stack: failedData.error?.stack,
363
+ code: failedData.errorCode,
364
+ },
365
+ completedAt: now,
366
+ updatedAt: now,
367
+ };
368
+ await writeJSON(taggedPath(basedir, 'runs', effectiveRunId, tag), run, { overwrite: true });
369
+ await Promise.all([
370
+ deleteAllHooksForRun(basedir, effectiveRunId),
371
+ deleteAllWaitsForRun(basedir, effectiveRunId),
372
+ ]);
373
+ }
374
+ }
375
+ else if (data.eventType === 'run_cancelled') {
376
+ // Reuse currentRun from validation (already read above)
377
+ if (currentRun) {
378
+ run = {
379
+ runId: currentRun.runId,
380
+ deploymentId: currentRun.deploymentId,
381
+ workflowName: currentRun.workflowName,
382
+ specVersion: currentRun.specVersion,
383
+ executionContext: currentRun.executionContext,
384
+ input: currentRun.input,
385
+ createdAt: currentRun.createdAt,
386
+ expiredAt: currentRun.expiredAt,
387
+ startedAt: currentRun.startedAt,
388
+ status: 'cancelled',
389
+ output: undefined,
390
+ error: undefined,
391
+ completedAt: now,
392
+ updatedAt: now,
393
+ };
394
+ await writeJSON(taggedPath(basedir, 'runs', effectiveRunId, tag), run, { overwrite: true });
395
+ await Promise.all([
396
+ deleteAllHooksForRun(basedir, effectiveRunId),
397
+ deleteAllWaitsForRun(basedir, effectiveRunId),
398
+ ]);
399
+ }
400
+ }
401
+ else if (
402
+ // Step lifecycle events
403
+ data.eventType === 'step_created' &&
404
+ 'eventData' in data) {
405
+ // step_created: Creates step entity with status 'pending', attempt=0, createdAt set
406
+ const stepData = data.eventData;
407
+ step = {
408
+ runId: effectiveRunId,
409
+ stepId: data.correlationId,
410
+ stepName: stepData.stepName,
411
+ status: 'pending',
412
+ input: stepData.input,
413
+ output: undefined,
414
+ error: undefined,
415
+ attempt: 0,
416
+ startedAt: undefined,
417
+ completedAt: undefined,
418
+ createdAt: now,
419
+ updatedAt: now,
420
+ // Propagate specVersion from the event to the step entity
421
+ specVersion: effectiveSpecVersion,
422
+ };
423
+ const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;
424
+ await writeJSON(taggedPath(basedir, 'steps', stepCompositeKey, tag), step);
425
+ }
426
+ else if (data.eventType === 'step_started') {
427
+ // step_started: Increments attempt, sets status to 'running'
428
+ // Sets startedAt only on the first start (not updated on retries)
429
+ // Reuse validatedStep from validation (already read above)
430
+ if (validatedStep) {
431
+ // Check if retryAfter timestamp hasn't been reached yet
432
+ if (validatedStep.retryAfter &&
433
+ validatedStep.retryAfter.getTime() > Date.now()) {
434
+ throw new TooEarlyError(`Cannot start step "${data.correlationId}": retryAfter timestamp has not been reached yet`, {
435
+ retryAfter: Math.ceil((validatedStep.retryAfter.getTime() - Date.now()) / 1000),
436
+ });
437
+ }
438
+ // Best-effort guard: re-read the step entity to check if it
439
+ // reached terminal state between the validation read and now.
440
+ // This narrows the TOCTOU window but does not fully eliminate it
441
+ // (the local world is single-process / dev-only; the postgres
442
+ // world uses SQL-level atomic guards for production).
443
+ const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;
444
+ const freshStep = await readJSONWithFallback(basedir, 'steps', stepCompositeKey, StepSchema, tag);
445
+ if (freshStep && isStepTerminal(freshStep.status)) {
446
+ throw new EntityConflictError(`Cannot modify step in terminal state "${freshStep.status}"`);
447
+ }
448
+ step = {
449
+ ...validatedStep,
450
+ status: 'running',
451
+ // Only set startedAt on the first start
452
+ startedAt: validatedStep.startedAt ?? now,
453
+ // Increment attempt counter on every start
454
+ attempt: validatedStep.attempt + 1,
455
+ // Clear retryAfter now that the step has started
456
+ retryAfter: undefined,
457
+ updatedAt: now,
458
+ };
459
+ await writeJSON(taggedPath(basedir, 'steps', stepCompositeKey, tag), step, { overwrite: true });
460
+ }
461
+ }
462
+ else if (data.eventType === 'step_completed' && 'eventData' in data) {
463
+ // step_completed: Terminal state with output
464
+ // Uses writeExclusive on a lock file to atomically prevent concurrent
465
+ // invocations from both completing the same step (TOCTOU race).
466
+ const completedData = data.eventData;
467
+ if (validatedStep) {
468
+ const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;
469
+ const lockName = tag
470
+ ? `${stepCompositeKey}.terminal.${tag}`
471
+ : `${stepCompositeKey}.terminal`;
472
+ const terminalLockPath = resolveWithinBase(basedir, '.locks', 'steps', lockName);
473
+ const claimed = await writeExclusive(terminalLockPath, '');
474
+ if (!claimed) {
475
+ throw new EntityConflictError('Cannot modify step in terminal state');
476
+ }
477
+ step = {
478
+ ...validatedStep,
479
+ status: 'completed',
480
+ output: completedData.result,
481
+ completedAt: now,
482
+ updatedAt: now,
483
+ };
484
+ await writeJSON(taggedPath(basedir, 'steps', stepCompositeKey, tag), step, { overwrite: true });
485
+ }
486
+ }
487
+ else if (data.eventType === 'step_failed' && 'eventData' in data) {
488
+ // step_failed: Terminal state with error
489
+ // Uses writeExclusive on a lock file to atomically prevent concurrent
490
+ // invocations from both failing the same step (TOCTOU race).
491
+ const failedData = data.eventData;
492
+ if (validatedStep) {
493
+ const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;
494
+ const lockName = tag
495
+ ? `${stepCompositeKey}.terminal.${tag}`
496
+ : `${stepCompositeKey}.terminal`;
497
+ const terminalLockPath = resolveWithinBase(basedir, '.locks', 'steps', lockName);
498
+ const claimed = await writeExclusive(terminalLockPath, '');
499
+ if (!claimed) {
500
+ throw new EntityConflictError('Cannot modify step in terminal state');
501
+ }
502
+ const error = {
503
+ message: typeof failedData.error === 'string'
504
+ ? failedData.error
505
+ : (failedData.error?.message ?? 'Unknown error'),
506
+ stack: failedData.stack,
507
+ };
508
+ step = {
509
+ ...validatedStep,
510
+ status: 'failed',
511
+ error,
512
+ completedAt: now,
513
+ updatedAt: now,
514
+ };
515
+ await writeJSON(taggedPath(basedir, 'steps', stepCompositeKey, tag), step, { overwrite: true });
516
+ }
517
+ }
518
+ else if (data.eventType === 'step_retrying' && 'eventData' in data) {
519
+ // step_retrying: Sets status back to 'pending', records error
520
+ // Reuse validatedStep from validation (already read above)
521
+ const retryData = data.eventData;
522
+ if (validatedStep) {
523
+ const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;
524
+ step = {
525
+ ...validatedStep,
526
+ status: 'pending',
527
+ error: {
528
+ message: typeof retryData.error === 'string'
529
+ ? retryData.error
530
+ : (retryData.error?.message ?? 'Unknown error'),
531
+ stack: retryData.stack,
532
+ },
533
+ retryAfter: retryData.retryAfter,
534
+ updatedAt: now,
535
+ };
536
+ await writeJSON(taggedPath(basedir, 'steps', stepCompositeKey, tag), step, { overwrite: true });
537
+ }
538
+ }
539
+ else if (
540
+ // Hook lifecycle events
541
+ data.eventType === 'hook_created' &&
542
+ 'eventData' in data) {
543
+ const hookData = data.eventData;
544
+ // Atomically claim the token using an exclusive-create constraint file.
545
+ // This avoids the TOCTOU race of the previous read-all-then-check approach.
546
+ const constraintPath = path.join(basedir, 'hooks', 'tokens', `${hashToken(hookData.token)}.json`);
547
+ const tokenClaimed = await writeExclusive(constraintPath, JSON.stringify({
548
+ token: hookData.token,
549
+ hookId: data.correlationId,
550
+ runId: effectiveRunId,
551
+ }));
552
+ if (!tokenClaimed) {
553
+ // Create hook_conflict event instead of hook_created
554
+ // This allows the workflow to continue and fail gracefully when the hook is awaited
555
+ const conflictEvent = {
556
+ eventType: 'hook_conflict',
557
+ correlationId: data.correlationId,
558
+ eventData: {
559
+ token: hookData.token,
560
+ },
561
+ runId: effectiveRunId,
562
+ eventId,
563
+ createdAt: now,
564
+ specVersion: effectiveSpecVersion,
565
+ };
566
+ // Store the conflict event
567
+ const compositeKey = `${effectiveRunId}-${eventId}`;
568
+ await writeJSON(taggedPath(basedir, 'events', compositeKey, tag), conflictEvent);
569
+ const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;
570
+ const filteredEvent = stripEventDataRefs(conflictEvent, resolveData);
571
+ // Return EventResult with conflict event (no hook entity created)
572
+ return {
573
+ event: filteredEvent,
574
+ run,
575
+ step,
576
+ hook: undefined,
577
+ };
578
+ }
579
+ hook = {
580
+ runId: effectiveRunId,
581
+ hookId: data.correlationId,
582
+ token: hookData.token,
583
+ metadata: hookData.metadata,
584
+ ownerId: 'local-owner',
585
+ projectId: 'local-project',
586
+ environment: 'local',
587
+ createdAt: now,
588
+ // Propagate specVersion from the event to the hook entity
589
+ specVersion: effectiveSpecVersion,
590
+ isWebhook: hookData.isWebhook ?? false,
591
+ };
592
+ await writeJSON(taggedPath(basedir, 'hooks', data.correlationId, tag), hook);
593
+ }
594
+ else if (data.eventType === 'hook_disposed') {
595
+ // hook_disposed: Deletes hook entity, rejects duplicates.
596
+ // Uses writeExclusive on a lock file to atomically prevent concurrent
597
+ // invocations from both disposing the same hook (TOCTOU race).
598
+ const hookLockName = tag
599
+ ? `${data.correlationId}.disposed.${tag}`
600
+ : `${data.correlationId}.disposed`;
601
+ const lockPath = resolveWithinBase(basedir, '.locks', 'hooks', hookLockName);
602
+ const claimed = await writeExclusive(lockPath, '');
603
+ if (!claimed) {
604
+ throw new EntityConflictError(`Hook "${data.correlationId}" already disposed`);
605
+ }
606
+ // Read the hook to get its token before deleting
607
+ const hookPath = taggedPath(basedir, 'hooks', data.correlationId, tag);
608
+ const existingHook = await readJSONWithFallback(basedir, 'hooks', data.correlationId, HookSchema, tag);
609
+ if (existingHook) {
610
+ // Delete the token constraint file to free up the token for reuse
611
+ const disposedConstraintPath = path.join(basedir, 'hooks', 'tokens', `${hashToken(existingHook.token)}.json`);
612
+ await deleteJSON(disposedConstraintPath);
613
+ }
614
+ await deleteJSON(hookPath);
615
+ }
616
+ else if (data.eventType === 'wait_created' && 'eventData' in data) {
617
+ // wait_created: Creates wait entity with status 'waiting'
618
+ const waitData = data.eventData;
619
+ const waitCompositeKey = `${effectiveRunId}-${data.correlationId}`;
620
+ const existingWait = await readJSONWithFallback(basedir, 'waits', waitCompositeKey, WaitSchema, tag);
621
+ if (existingWait) {
622
+ throw new EntityConflictError(`Wait "${data.correlationId}" already exists`);
623
+ }
624
+ wait = {
625
+ waitId: waitCompositeKey,
626
+ runId: effectiveRunId,
627
+ status: 'waiting',
628
+ resumeAt: waitData.resumeAt,
629
+ completedAt: undefined,
630
+ createdAt: now,
631
+ updatedAt: now,
632
+ specVersion: effectiveSpecVersion,
633
+ };
634
+ await writeJSON(taggedPath(basedir, 'waits', waitCompositeKey, tag), wait);
635
+ }
636
+ else if (data.eventType === 'wait_completed') {
637
+ // wait_completed: Transitions wait to 'completed', rejects duplicates.
638
+ // Uses writeExclusive on a lock file to atomically prevent concurrent
639
+ // invocations from both completing the same wait (TOCTOU race).
640
+ const waitCompositeKey = `${effectiveRunId}-${data.correlationId}`;
641
+ const waitLockName = tag
642
+ ? `${waitCompositeKey}.completed.${tag}`
643
+ : `${waitCompositeKey}.completed`;
644
+ const lockPath = resolveWithinBase(basedir, '.locks', 'waits', waitLockName);
645
+ const claimed = await writeExclusive(lockPath, '');
646
+ if (!claimed) {
647
+ throw new EntityConflictError(`Wait "${data.correlationId}" already completed`);
648
+ }
649
+ const existingWait = await readJSONWithFallback(basedir, 'waits', waitCompositeKey, WaitSchema, tag);
650
+ if (!existingWait) {
651
+ // Clean up the lock file we just claimed — the wait doesn't exist
652
+ await fs.unlink(lockPath).catch(() => { });
653
+ throw new WorkflowWorldError(`Wait "${data.correlationId}" not found`);
654
+ }
655
+ // The lock file (writeExclusive above) already prevents concurrent
656
+ // completions — no additional status check needed.
657
+ wait = {
658
+ ...existingWait,
659
+ status: 'completed',
660
+ completedAt: now,
661
+ updatedAt: now,
662
+ };
663
+ await writeJSON(taggedPath(basedir, 'waits', waitCompositeKey, tag), wait, { overwrite: true });
664
+ }
665
+ // Note: hook_received events are stored in the event log but don't
666
+ // modify the Hook entity (which doesn't have a payload field)
667
+ // Store event using composite key {runId}-{eventId}
668
+ const compositeKey = `${effectiveRunId}-${eventId}`;
669
+ await writeJSON(taggedPath(basedir, 'events', compositeKey, tag), event);
670
+ const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;
671
+ const filteredEvent = stripEventDataRefs(event, resolveData);
672
+ // For run_started: include all events so the runtime can skip
673
+ // the initial events.list call and reduce TTFB.
674
+ let events;
675
+ if (data.eventType === 'run_started' && run) {
676
+ const allEvents = await paginatedFileSystemQuery({
677
+ directory: path.join(basedir, 'events'),
678
+ schema: EventSchema,
679
+ filePrefix: `${effectiveRunId}-`,
680
+ sortOrder: 'asc',
681
+ getCreatedAt: getObjectCreatedAt('evnt'),
682
+ getId: (e) => e.eventId,
683
+ });
684
+ events = allEvents.data;
685
+ }
686
+ // Return EventResult with event and any created/updated entity
687
+ return {
688
+ event: filteredEvent,
689
+ run,
690
+ step,
691
+ hook,
692
+ wait,
693
+ events,
694
+ };
695
+ },
696
+ async get(runId, eventId, params) {
697
+ assertSafeEntityId('runId', runId);
698
+ assertSafeEntityId('eventId', eventId);
699
+ const compositeKey = `${runId}-${eventId}`;
700
+ const event = await readJSONWithFallback(basedir, 'events', compositeKey, EventSchema, tag);
701
+ if (!event) {
702
+ throw new Error(`Event ${eventId} in run ${runId} not found`);
703
+ }
704
+ const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;
705
+ return stripEventDataRefs(event, resolveData);
706
+ },
707
+ async list(params) {
708
+ const { runId } = params;
709
+ assertSafeEntityId('runId', runId);
710
+ const resolveData = params.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;
711
+ const result = await paginatedFileSystemQuery({
712
+ directory: path.join(basedir, 'events'),
713
+ schema: EventSchema,
714
+ filePrefix: `${runId}-`,
715
+ // Events in chronological order (oldest first) by default,
716
+ // different from the default for other list calls.
717
+ sortOrder: params.pagination?.sortOrder ?? 'asc',
718
+ limit: params.pagination?.limit,
719
+ cursor: params.pagination?.cursor,
720
+ getCreatedAt: getObjectCreatedAt('evnt'),
721
+ getId: (event) => event.eventId,
722
+ });
723
+ // If resolveData is "none", remove eventData from events
724
+ if (resolveData === 'none') {
725
+ return {
726
+ ...result,
727
+ data: result.data.map((event) => stripEventDataRefs(event, resolveData)),
728
+ };
729
+ }
730
+ return result;
731
+ },
732
+ async listByCorrelationId(params) {
733
+ const correlationId = params.correlationId;
734
+ assertSafeEntityId('correlationId', correlationId);
735
+ const resolveData = params.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;
736
+ const result = await paginatedFileSystemQuery({
737
+ directory: path.join(basedir, 'events'),
738
+ schema: EventSchema,
739
+ // No filePrefix - search all events
740
+ filter: (event) => event.correlationId === correlationId,
741
+ // Events in chronological order (oldest first) by default,
742
+ // different from the default for other list calls.
743
+ sortOrder: params.pagination?.sortOrder ?? 'asc',
744
+ limit: params.pagination?.limit,
745
+ cursor: params.pagination?.cursor,
746
+ getCreatedAt: getObjectCreatedAt('evnt'),
747
+ getId: (event) => event.eventId,
748
+ });
749
+ // If resolveData is "none", remove eventData from events
750
+ if (resolveData === 'none') {
751
+ return {
752
+ ...result,
753
+ data: result.data.map((event) => stripEventDataRefs(event, resolveData)),
754
+ };
755
+ }
756
+ return result;
757
+ },
758
+ };
759
+ }
760
+ //# sourceMappingURL=events-storage.js.map