@workflow/world-local 5.0.0-beta.5 → 5.0.0-beta.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.
@@ -1 +1 @@
1
- {"version":3,"file":"events-storage.d.ts","sourceRoot":"","sources":["../../src/storage/events-storage.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAMV,OAAO,EAGR,MAAM,iBAAiB,CAAC;AAyGzB;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,MAAM,EACf,GAAG,CAAC,EAAE,MAAM,GACX,OAAO,CAAC,QAAQ,CAAC,CAwjCnB"}
1
+ {"version":3,"file":"events-storage.d.ts","sourceRoot":"","sources":["../../src/storage/events-storage.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAMV,OAAO,EAGR,MAAM,iBAAiB,CAAC;AAyGzB;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,MAAM,EACf,GAAG,CAAC,EAAE,MAAM,GACX,OAAO,CAAC,QAAQ,CAAC,CA+jCnB"}
@@ -765,19 +765,24 @@ export function createEventsStorage(basedir, tag) {
765
765
  await writeJSON(taggedPath(basedir, 'events', compositeKey, tag), event);
766
766
  const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;
767
767
  const filteredEvent = stripEventDataRefs(event, resolveData);
768
- // For run_started: include all events so the runtime can skip
769
- // the initial events.list call and reduce TTFB.
768
+ // For run_started: preload one page of events so the runtime can skip
769
+ // the initial events.list call when hasMore is false.
770
770
  let events;
771
+ let cursor;
772
+ let hasMore;
771
773
  if (data.eventType === 'run_started' && run) {
772
774
  const allEvents = await paginatedFileSystemQuery({
773
775
  directory: path.join(basedir, 'events'),
774
776
  schema: EventSchema,
775
777
  filePrefix: `${effectiveRunId}-`,
776
778
  sortOrder: 'asc',
779
+ limit: 1000,
777
780
  getCreatedAt: getObjectCreatedAt('evnt'),
778
781
  getId: (e) => e.eventId,
779
782
  });
780
783
  events = allEvents.data;
784
+ cursor = allEvents.cursor;
785
+ hasMore = allEvents.hasMore;
781
786
  }
782
787
  // Return EventResult with event and any created/updated entity
783
788
  return {
@@ -787,6 +792,8 @@ export function createEventsStorage(basedir, tag) {
787
792
  hook,
788
793
  wait,
789
794
  events,
795
+ cursor,
796
+ hasMore,
790
797
  };
791
798
  } // end createImpl
792
799
  },
@@ -1 +1 @@
1
- {"version":3,"file":"events-storage.js","sourceRoot":"","sources":["../../src/storage/events-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAClC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB,eAAe,EACf,oBAAoB,EACpB,aAAa,EACb,wBAAwB,EACxB,kBAAkB,GACnB,MAAM,kBAAkB,CAAC;AAW1B,OAAO,EACL,WAAW,EACX,UAAU,EACV,mBAAmB,EACnB,kBAAkB,EAClB,oBAAoB,EACpB,UAAU,EACV,qBAAqB,EACrB,UAAU,EACV,iBAAiB,GAClB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EACL,kBAAkB,EAClB,UAAU,EACV,YAAY,EACZ,aAAa,EACb,wBAAwB,EACxB,QAAQ,EACR,oBAAoB,EACpB,iBAAiB,EACjB,UAAU,EACV,cAAc,EACd,SAAS,GACV,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC5E,OAAO,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAC;AAEhD;;;;;;;;;;;GAWG;AACH,MAAM,SAAS,GAAG,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,EAAE,MAAM,CAAC,UAAU,EAAE,KAAK;gBAC/B,MAAM,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM;gBACjC,YAAY,EAAE,kBAAkB,CAAC,MAAM,CAAC;gBACxC,KAAK,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO;aAChC,CAAC,CAAC;YAEH,yDAAyD;YACzD,IAAI,WAAW,KAAK,MAAM,EAAE,CAAC;gBAC3B,OAAO;oBACL,GAAG,MAAM;oBACT,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAC9B,kBAAkB,CAAC,KAAK,EAAE,WAAW,CAAC,CACvC;iBACF,CAAC;YACJ,CAAC;YAED,OAAO,MAAM,CAAC;QAChB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport {\n EntityConflictError,\n HookNotFoundError,\n RunExpiredError,\n RunNotSupportedError,\n TooEarlyError,\n WorkflowRunNotFoundError,\n WorkflowWorldError,\n} from '@workflow/errors';\nimport type {\n Event,\n EventResult,\n Hook,\n SerializedData,\n Step,\n Storage,\n Wait,\n WorkflowRun,\n} from '@workflow/world';\nimport {\n EventSchema,\n HookSchema,\n isLegacySpecVersion,\n requiresNewerWorld,\n SPEC_VERSION_CURRENT,\n StepSchema,\n validateUlidTimestamp,\n WaitSchema,\n WorkflowRunSchema,\n} from '@workflow/world';\nimport { z } from 'zod';\nimport { DEFAULT_RESOLVE_DATA_OPTION } from '../config.js';\nimport {\n assertSafeEntityId,\n deleteJSON,\n jsonReplacer,\n listJSONFiles,\n paginatedFileSystemQuery,\n readJSON,\n readJSONWithFallback,\n resolveWithinBase,\n taggedPath,\n writeExclusive,\n writeJSON,\n} from '../fs.js';\nimport { stripEventDataRefs } from './filters.js';\nimport { getObjectCreatedAt, hashToken, monotonicUlid } from './helpers.js';\nimport { deleteAllHooksForRun } from './hooks-storage.js';\nimport { handleLegacyEvent } from './legacy.js';\n\n/**\n * Per-step in-process async mutex. Serializes concurrent `events.create` calls\n * that target the same step, so that the \"check terminal state, then write step\n * entity + event\" sequence is atomic. Without this, two concurrent step_started\n * calls can both pass the not-terminal check and both write step_started events\n * — or a step_started can land in the log after step_completed has already\n * written, producing unconsumed events on replay.\n *\n * Duplicate step_started events for a non-terminal step are still allowed\n * (retries legitimately re-start a step), only writes to an already-terminal\n * step are rejected.\n */\nconst stepLocks = new Map<string, Promise<unknown>>();\n\nconst HookTokenClaimSchema = z.object({\n runId: z.string(),\n});\n\nasync function readHookTokenClaim(\n constraintPath: string\n): Promise<z.infer<typeof HookTokenClaimSchema> | null> {\n try {\n return await readJSON(constraintPath, HookTokenClaimSchema);\n } catch (error) {\n if (error instanceof SyntaxError || error instanceof z.ZodError) {\n return null;\n }\n throw error;\n }\n}\n\nfunction withStepLock<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const prev = stepLocks.get(key);\n const taskBox: { task?: Promise<T> } = {};\n const task = (async () => {\n if (prev) {\n // Wait for the previous task to settle; don't inherit its errors.\n await prev.catch(() => undefined);\n }\n try {\n return await fn();\n } finally {\n if (stepLocks.get(key) === taskBox.task) {\n stepLocks.delete(key);\n }\n }\n })();\n taskBox.task = task;\n stepLocks.set(key, task);\n return task;\n}\n\n/**\n * Helper function to delete all waits associated with a workflow run.\n * Called when a run reaches a terminal state.\n */\nasync function deleteAllWaitsForRun(\n basedir: string,\n runId: string\n): Promise<void> {\n const waitsDir = path.join(basedir, 'waits');\n const files = await listJSONFiles(waitsDir);\n\n for (const file of files) {\n // fileIds may contain tag suffixes (e.g., \"wrun_ABC-corrId.vitest-0\")\n // but startsWith still matches correctly since the tag is a suffix.\n if (file.startsWith(`${runId}-`)) {\n const waitPath = path.join(waitsDir, `${file}.json`);\n await deleteJSON(waitPath);\n }\n }\n}\n\n/**\n * Creates the events storage implementation using the filesystem.\n * Implements the Storage['events'] interface with create, list, and listByCorrelationId operations.\n */\nexport function createEventsStorage(\n basedir: string,\n tag?: string\n): Storage['events'] {\n return {\n async create(runId, data, params): Promise<EventResult> {\n // Validate request-supplied IDs before they're concatenated into\n // filesystem paths. This is the primary defense against path traversal\n // attacks where a client supplies runId / correlationId values like\n // \"../../../package\" to read or write files outside the storage root.\n // Run before taking the per-step mutex so malformed inputs fail fast.\n if (runId != null && runId !== '') {\n assertSafeEntityId('runId', runId);\n }\n if (\n 'correlationId' in data &&\n typeof data.correlationId === 'string' &&\n data.correlationId.length > 0\n ) {\n assertSafeEntityId('correlationId', data.correlationId);\n }\n\n // Step lifecycle events are serialized per-step via an in-process mutex\n // so that the \"check state, then write\" sequence in step_started /\n // step_completed / step_failed / step_retrying is atomic. step_created\n // is also serialized so duplicate-create races don't leave extra\n // step_created events in the log.\n const isStepEvent =\n data.eventType === 'step_created' ||\n data.eventType === 'step_started' ||\n data.eventType === 'step_completed' ||\n data.eventType === 'step_failed' ||\n data.eventType === 'step_retrying';\n if (isStepEvent && runId && data.correlationId) {\n const lockKey = tag\n ? `${runId}-${data.correlationId}.${tag}`\n : `${runId}-${data.correlationId}`;\n return withStepLock(lockKey, () => createImpl());\n }\n return createImpl();\n\n async function createImpl(): Promise<EventResult> {\n const eventId = `evnt_${monotonicUlid()}`;\n const now = new Date();\n\n // For run_created events, use client-provided runId or generate one server-side\n let effectiveRunId: string;\n if (data.eventType === 'run_created' && (!runId || runId === '')) {\n effectiveRunId = `wrun_${monotonicUlid()}`;\n } else if (!runId) {\n throw new Error('runId is required for non-run_created events');\n } else {\n effectiveRunId = runId;\n }\n\n // Validate client-provided runId timestamp is within acceptable threshold\n if (data.eventType === 'run_created' && runId && runId !== '') {\n const validationError = validateUlidTimestamp(\n effectiveRunId,\n 'wrun_'\n );\n if (validationError) {\n throw new WorkflowWorldError(validationError);\n }\n }\n\n // specVersion is always sent by the runtime, but we provide a fallback for safety\n const effectiveSpecVersion = data.specVersion ?? SPEC_VERSION_CURRENT;\n\n // Helper to check if run is in terminal state\n const isRunTerminal = (status: string) =>\n ['completed', 'failed', 'cancelled'].includes(status);\n\n // Helper to check if step is in terminal state\n const isStepTerminal = (status: string) =>\n ['completed', 'failed', 'cancelled'].includes(status);\n\n // Get current run state for validation (if not creating a new run)\n // Skip run validation for step_completed and step_retrying - they only operate\n // on running steps, and running steps are always allowed to modify regardless\n // of run state. This optimization saves filesystem reads per step event.\n let currentRun: WorkflowRun | null = null;\n const skipRunValidationEvents = ['step_completed', 'step_retrying'];\n if (\n data.eventType !== 'run_created' &&\n !skipRunValidationEvents.includes(data.eventType)\n ) {\n currentRun = await readJSONWithFallback(\n basedir,\n 'runs',\n effectiveRunId,\n WorkflowRunSchema,\n tag\n );\n\n // Resilient start: run_started on non-existent run with eventData\n // creates the run first, so the queue can bootstrap a run that\n // failed to create during start().\n if (\n data.eventType === 'run_started' &&\n !currentRun &&\n 'eventData' in data &&\n data.eventData\n ) {\n const runInputData = data.eventData as {\n deploymentId?: string;\n workflowName?: string;\n input?: any;\n executionContext?: Record<string, any>;\n };\n if (\n runInputData.deploymentId &&\n runInputData.workflowName &&\n runInputData.input !== undefined\n ) {\n // Atomically try to create the run entity. writeExclusive\n // uses O_CREAT|O_EXCL so only the first writer wins,\n // preventing a TOCTOU race where a concurrent run_created\n // from start() could overwrite a run that was already\n // transitioned to 'running'.\n const createdRun: WorkflowRun = {\n runId: effectiveRunId,\n deploymentId: runInputData.deploymentId,\n status: 'pending',\n workflowName: runInputData.workflowName,\n specVersion: effectiveSpecVersion,\n executionContext: runInputData.executionContext,\n input: runInputData.input,\n output: undefined,\n error: undefined,\n startedAt: undefined,\n completedAt: undefined,\n createdAt: now,\n updatedAt: now,\n };\n const runPath = taggedPath(basedir, 'runs', effectiveRunId, tag);\n const created = await writeExclusive(\n runPath,\n JSON.stringify(createdRun, jsonReplacer)\n );\n\n if (created) {\n // We created the run — also write the run_created event.\n const runCreatedEventId = `evnt_${monotonicUlid()}`;\n const runCreatedEvent: Event = {\n eventType: 'run_created',\n runId: effectiveRunId,\n eventId: runCreatedEventId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n eventData: {\n deploymentId: runInputData.deploymentId,\n workflowName: runInputData.workflowName,\n input: runInputData.input,\n executionContext: runInputData.executionContext,\n },\n };\n const createdCompositeKey = `${effectiveRunId}-${runCreatedEventId}`;\n await writeJSON(\n taggedPath(basedir, 'events', createdCompositeKey, tag),\n runCreatedEvent\n );\n currentRun = createdRun;\n } else {\n // Run already exists (concurrent run_created won the\n // race). Re-read it so downstream logic sees the real state.\n currentRun = await readJSONWithFallback(\n basedir,\n 'runs',\n effectiveRunId,\n WorkflowRunSchema,\n tag\n );\n }\n }\n }\n }\n\n // run_failed on a non-existent run is rejected to match the\n // postgres and vercel worlds, which both surface this as a\n // WorkflowRunNotFoundError rather than silently persisting an\n // event for a run that was never created.\n if (data.eventType === 'run_failed' && !currentRun) {\n throw new WorkflowRunNotFoundError(effectiveRunId);\n }\n\n // ============================================================\n // VERSION COMPATIBILITY: Check run spec version\n // ============================================================\n // For events that have fetched the run, check version compatibility.\n // Skip for run_created (no existing run) and runtime events (step_completed, step_retrying).\n if (currentRun) {\n // Check if run requires a newer world version\n if (requiresNewerWorld(currentRun.specVersion)) {\n throw new RunNotSupportedError(\n currentRun.specVersion!,\n SPEC_VERSION_CURRENT\n );\n }\n\n // Route to legacy handler for pre-event-sourcing runs\n if (isLegacySpecVersion(currentRun.specVersion)) {\n return handleLegacyEvent(\n basedir,\n effectiveRunId,\n data,\n currentRun,\n params\n );\n }\n }\n\n // ============================================================\n // VALIDATION: Terminal state and event ordering checks\n // ============================================================\n\n // Run terminal state validation\n if (currentRun && isRunTerminal(currentRun.status)) {\n const runTerminalEvents = [\n 'run_started',\n 'run_completed',\n 'run_failed',\n ];\n\n // Idempotent operation: run_cancelled on already cancelled run is allowed\n if (\n data.eventType === 'run_cancelled' &&\n currentRun.status === 'cancelled'\n ) {\n // Return existing state (idempotent)\n const event: Event = {\n ...data,\n runId: effectiveRunId,\n eventId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n };\n const compositeKey = `${effectiveRunId}-${eventId}`;\n await writeJSON(\n taggedPath(basedir, 'events', compositeKey, tag),\n event\n );\n const resolveData =\n params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n return {\n event: stripEventDataRefs(event, resolveData),\n run: currentRun,\n };\n }\n\n // For run_started on terminal runs, use RunExpiredError so the\n // runtime knows to exit without retrying.\n if (data.eventType === 'run_started') {\n throw new RunExpiredError(\n `Workflow run \"${effectiveRunId}\" is already in terminal state \"${currentRun.status}\"`\n );\n }\n\n // Other run state transitions are not allowed on terminal runs\n if (\n runTerminalEvents.includes(data.eventType) ||\n data.eventType === 'run_cancelled'\n ) {\n throw new EntityConflictError(\n `Cannot transition run from terminal state \"${currentRun.status}\"`\n );\n }\n\n // Creating new entities on terminal runs is not allowed\n if (\n data.eventType === 'step_created' ||\n data.eventType === 'hook_created' ||\n data.eventType === 'wait_created'\n ) {\n throw new EntityConflictError(\n `Cannot create new entities on run in terminal state \"${currentRun.status}\"`\n );\n }\n }\n\n // Step-related event validation (ordering and terminal state)\n // Store existingStep so we can reuse it later (avoid double read)\n let validatedStep: Step | null = null;\n const stepEvents = [\n 'step_started',\n 'step_completed',\n 'step_failed',\n 'step_retrying',\n ];\n if (stepEvents.includes(data.eventType) && data.correlationId) {\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n validatedStep = await readJSONWithFallback(\n basedir,\n 'steps',\n stepCompositeKey,\n StepSchema,\n tag\n );\n\n // Event ordering: step must exist before these events\n if (!validatedStep) {\n throw new WorkflowWorldError(\n `Step \"${data.correlationId}\" not found`\n );\n }\n\n // Step terminal state validation\n if (isStepTerminal(validatedStep.status)) {\n throw new EntityConflictError(\n `Cannot modify step in terminal state \"${validatedStep.status}\"`\n );\n }\n\n // On terminal runs: only allow completing/failing in-progress steps\n if (currentRun && isRunTerminal(currentRun.status)) {\n if (validatedStep.status !== 'running') {\n throw new RunExpiredError(\n `Cannot modify non-running step on run in terminal state \"${currentRun.status}\"`\n );\n }\n }\n }\n\n // Hook-related event validation (ordering)\n const hookEventsRequiringExistence = ['hook_disposed', 'hook_received'];\n if (\n hookEventsRequiringExistence.includes(data.eventType) &&\n data.correlationId\n ) {\n const existingHook = await readJSONWithFallback(\n basedir,\n 'hooks',\n data.correlationId,\n HookSchema,\n tag\n );\n\n if (!existingHook) {\n throw new HookNotFoundError(data.correlationId);\n }\n }\n const event: Event = {\n ...data,\n runId: effectiveRunId,\n eventId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n };\n // Strip eventData from run_started — it belongs on run_created only.\n if (data.eventType === 'run_started' && 'eventData' in event) {\n delete (event as any).eventData;\n }\n\n // Track entity created/updated for EventResult\n let run: WorkflowRun | undefined;\n let step: Step | undefined;\n let hook: Hook | undefined;\n let wait: Wait | undefined;\n\n // Create/update entity based on event type (event-sourced architecture)\n // Run lifecycle events\n if (data.eventType === 'run_created' && 'eventData' in data) {\n const runData = data.eventData as {\n deploymentId: string;\n workflowName: string;\n input: SerializedData;\n executionContext?: Record<string, any>;\n };\n run = {\n runId: effectiveRunId,\n deploymentId: runData.deploymentId,\n status: 'pending',\n workflowName: runData.workflowName,\n // Propagate specVersion from the event to the run entity\n specVersion: effectiveSpecVersion,\n executionContext: runData.executionContext,\n input: runData.input,\n output: undefined,\n error: undefined,\n startedAt: undefined,\n completedAt: undefined,\n createdAt: now,\n updatedAt: now,\n };\n // Use writeExclusive (O_CREAT|O_EXCL) to atomically create the\n // run entity file. This prevents a TOCTOU race with the resilient\n // start path (run_started on non-existent run) that could result\n // in duplicate run_created events in the event log.\n const runPath = taggedPath(basedir, 'runs', effectiveRunId, tag);\n const created = await writeExclusive(\n runPath,\n JSON.stringify(run, jsonReplacer, 2)\n );\n if (!created) {\n throw new EntityConflictError(\n `Workflow run \"${effectiveRunId}\" already exists`\n );\n }\n } else if (data.eventType === 'run_started') {\n // Reuse currentRun from validation (already read above)\n if (currentRun) {\n // If already running, return the run without inserting a\n // duplicate event. This makes run_started idempotent for\n // concurrent invocations. We omit preloaded events here\n // because this is a rare race-condition path — the runtime\n // falls back to loadWorkflowRunEvents().\n if (currentRun.status === 'running') {\n return { run: currentRun };\n }\n\n run = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n status: 'running',\n output: undefined,\n error: undefined,\n completedAt: undefined,\n startedAt: currentRun.startedAt ?? now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'runs', effectiveRunId, tag),\n run,\n { overwrite: true }\n );\n }\n } else if (data.eventType === 'run_completed' && 'eventData' in data) {\n const completedData = data.eventData as { output?: any };\n // Reuse currentRun from validation (already read above)\n if (currentRun) {\n run = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n startedAt: currentRun.startedAt,\n status: 'completed',\n output: completedData.output,\n error: undefined,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'runs', effectiveRunId, tag),\n run,\n { overwrite: true }\n );\n await Promise.all([\n deleteAllHooksForRun(basedir, effectiveRunId),\n deleteAllWaitsForRun(basedir, effectiveRunId),\n ]);\n }\n } else if (data.eventType === 'run_failed' && 'eventData' in data) {\n const failedData = data.eventData as {\n error: unknown;\n errorCode?: string;\n };\n // Reuse currentRun from validation (already read above)\n if (currentRun) {\n // The error field is SerializedData (Uint8Array) produced by\n // dehydrateRunError. We store it verbatim — consumers hydrate it\n // via hydrateRunError to reconstruct the original thrown value.\n run = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n startedAt: currentRun.startedAt,\n status: 'failed',\n output: undefined,\n error: failedData.error as Uint8Array,\n errorCode: failedData.errorCode,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'runs', effectiveRunId, tag),\n run,\n { overwrite: true }\n );\n await Promise.all([\n deleteAllHooksForRun(basedir, effectiveRunId),\n deleteAllWaitsForRun(basedir, effectiveRunId),\n ]);\n }\n } else if (data.eventType === 'run_cancelled') {\n // Reuse currentRun from validation (already read above)\n if (currentRun) {\n run = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n startedAt: currentRun.startedAt,\n status: 'cancelled',\n output: undefined,\n error: undefined,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'runs', effectiveRunId, tag),\n run,\n { overwrite: true }\n );\n await Promise.all([\n deleteAllHooksForRun(basedir, effectiveRunId),\n deleteAllWaitsForRun(basedir, effectiveRunId),\n ]);\n }\n } else if (\n // Step lifecycle events\n data.eventType === 'step_created' &&\n 'eventData' in data\n ) {\n // step_created: Creates step entity with status 'pending', attempt=0, createdAt set.\n // Two concurrent invocations with identical correlationIds (e.g. the\n // snapshot runtime's deterministic correlationIds across replays)\n // must be deduped — otherwise both writes succeed and the event log\n // ends up with duplicate step_created entries. The outer\n // withStepLock mutex serializes within a single process; this\n // O_CREAT|O_EXCL constraint file additionally protects against\n // cross-process races (two pnpm workers, redelivered queue\n // messages, etc.). The loser throws EntityConflictError so the\n // runtime's existing catch path can swallow it and avoid\n // double-queuing the step.\n const stepCreatedLockName = tag\n ? `${effectiveRunId}-${data.correlationId}.created.${tag}`\n : `${effectiveRunId}-${data.correlationId}.created`;\n const stepCreatedLockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'steps',\n stepCreatedLockName\n );\n const stepCreatedClaimed = await writeExclusive(\n stepCreatedLockPath,\n ''\n );\n if (!stepCreatedClaimed) {\n throw new EntityConflictError(\n `Step \"${data.correlationId}\" already created`\n );\n }\n const stepData = data.eventData as {\n stepName: string;\n input: any;\n };\n step = {\n runId: effectiveRunId,\n stepId: data.correlationId,\n stepName: stepData.stepName,\n status: 'pending',\n input: stepData.input,\n output: undefined,\n error: undefined,\n attempt: 0,\n startedAt: undefined,\n completedAt: undefined,\n createdAt: now,\n updatedAt: now,\n // Propagate specVersion from the event to the step entity\n specVersion: effectiveSpecVersion,\n };\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step\n );\n } else if (data.eventType === 'step_started') {\n // step_started: Increments attempt, sets status to 'running'\n // Sets startedAt only on the first start (not updated on retries)\n // Reuse validatedStep from validation (already read above)\n if (validatedStep) {\n // Check if retryAfter timestamp hasn't been reached yet\n if (\n validatedStep.retryAfter &&\n validatedStep.retryAfter.getTime() > Date.now()\n ) {\n throw new TooEarlyError(\n `Cannot start step \"${data.correlationId}\": retryAfter timestamp has not been reached yet`,\n {\n retryAfter: Math.ceil(\n (validatedStep.retryAfter.getTime() - Date.now()) / 1000\n ),\n }\n );\n }\n\n // Best-effort guard: re-read the step entity to check if it\n // reached terminal state between the validation read and now.\n // This narrows the TOCTOU window but does not fully eliminate it\n // (the local world is single-process / dev-only; the postgres\n // world uses SQL-level atomic guards for production).\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const freshStep = await readJSONWithFallback(\n basedir,\n 'steps',\n stepCompositeKey,\n StepSchema,\n tag\n );\n if (freshStep && isStepTerminal(freshStep.status)) {\n throw new EntityConflictError(\n `Cannot modify step in terminal state \"${freshStep.status}\"`\n );\n }\n\n step = {\n ...validatedStep,\n status: 'running',\n // Only set startedAt on the first start\n startedAt: validatedStep.startedAt ?? now,\n // Increment attempt counter on every start\n attempt: validatedStep.attempt + 1,\n // Clear retryAfter now that the step has started\n retryAfter: undefined,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step,\n { overwrite: true }\n );\n }\n } else if (data.eventType === 'step_completed' && 'eventData' in data) {\n // step_completed: Terminal state with output\n // Uses writeExclusive on a lock file to atomically prevent concurrent\n // invocations from both completing the same step (TOCTOU race).\n const completedData = data.eventData as { result: any };\n if (validatedStep) {\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const lockName = tag\n ? `${stepCompositeKey}.terminal.${tag}`\n : `${stepCompositeKey}.terminal`;\n const terminalLockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'steps',\n lockName\n );\n const claimed = await writeExclusive(terminalLockPath, '');\n if (!claimed) {\n throw new EntityConflictError(\n 'Cannot modify step in terminal state'\n );\n }\n step = {\n ...validatedStep,\n status: 'completed',\n output: completedData.result,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step,\n { overwrite: true }\n );\n }\n } else if (data.eventType === 'step_failed' && 'eventData' in data) {\n // step_failed: Terminal state with error\n // Uses writeExclusive on a lock file to atomically prevent concurrent\n // invocations from both failing the same step (TOCTOU race).\n const failedData = data.eventData as {\n error: unknown;\n };\n if (validatedStep) {\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const lockName = tag\n ? `${stepCompositeKey}.terminal.${tag}`\n : `${stepCompositeKey}.terminal`;\n const terminalLockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'steps',\n lockName\n );\n const claimed = await writeExclusive(terminalLockPath, '');\n if (!claimed) {\n throw new EntityConflictError(\n 'Cannot modify step in terminal state'\n );\n }\n // The error field is SerializedData (Uint8Array) produced by\n // dehydrateStepError. We store it verbatim — consumers hydrate it\n // via hydrateStepError to reconstruct the original thrown value.\n step = {\n ...validatedStep,\n status: 'failed',\n error: failedData.error as Uint8Array,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step,\n { overwrite: true }\n );\n }\n } else if (data.eventType === 'step_retrying' && 'eventData' in data) {\n // step_retrying: Sets status back to 'pending', records error\n // Reuse validatedStep from validation (already read above)\n const retryData = data.eventData as {\n error: unknown;\n retryAfter?: Date;\n };\n if (validatedStep) {\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n step = {\n ...validatedStep,\n status: 'pending',\n error: retryData.error as Uint8Array,\n retryAfter: retryData.retryAfter,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step,\n { overwrite: true }\n );\n }\n } else if (\n // Hook lifecycle events\n data.eventType === 'hook_created' &&\n 'eventData' in data\n ) {\n const hookData = data.eventData as {\n token: string;\n metadata?: any;\n isWebhook?: boolean;\n isSystem?: boolean;\n };\n\n // Atomically claim the token using an exclusive-create constraint file.\n // This avoids the TOCTOU race of the previous read-all-then-check approach.\n const constraintPath = path.join(\n basedir,\n 'hooks',\n 'tokens',\n `${hashToken(hookData.token)}.json`\n );\n const tokenClaimed = await writeExclusive(\n constraintPath,\n JSON.stringify({\n token: hookData.token,\n hookId: data.correlationId,\n runId: effectiveRunId,\n })\n );\n\n if (!tokenClaimed) {\n const existingClaim = await readHookTokenClaim(constraintPath);\n\n // Create hook_conflict event instead of hook_created\n // This allows the workflow to continue and fail gracefully when the hook is awaited\n const conflictEvent: Event = {\n eventType: 'hook_conflict',\n correlationId: data.correlationId,\n eventData: {\n token: hookData.token,\n ...(existingClaim\n ? { conflictingRunId: existingClaim.runId }\n : {}),\n },\n runId: effectiveRunId,\n eventId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n };\n\n // Store the conflict event\n const compositeKey = `${effectiveRunId}-${eventId}`;\n await writeJSON(\n taggedPath(basedir, 'events', compositeKey, tag),\n conflictEvent\n );\n\n const resolveData =\n params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const filteredEvent = stripEventDataRefs(\n conflictEvent,\n resolveData\n );\n\n // Return EventResult with conflict event (no hook entity created)\n return {\n event: filteredEvent,\n run,\n step,\n hook: undefined,\n };\n }\n\n hook = {\n runId: effectiveRunId,\n hookId: data.correlationId,\n token: hookData.token,\n metadata: hookData.metadata,\n ownerId: 'local-owner',\n projectId: 'local-project',\n environment: 'local',\n createdAt: now,\n // Propagate specVersion from the event to the hook entity\n specVersion: effectiveSpecVersion,\n isWebhook: hookData.isWebhook ?? false,\n isSystem: hookData.isSystem ?? false,\n };\n await writeJSON(\n taggedPath(basedir, 'hooks', data.correlationId, tag),\n hook\n );\n } else if (data.eventType === 'hook_disposed') {\n // hook_disposed: Deletes hook entity, rejects duplicates.\n // Uses writeExclusive on a lock file to atomically prevent concurrent\n // invocations from both disposing the same hook (TOCTOU race).\n const hookLockName = tag\n ? `${data.correlationId}.disposed.${tag}`\n : `${data.correlationId}.disposed`;\n const lockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'hooks',\n hookLockName\n );\n const claimed = await writeExclusive(lockPath, '');\n if (!claimed) {\n throw new EntityConflictError(\n `Hook \"${data.correlationId}\" already disposed`\n );\n }\n // Read the hook to get its token before deleting\n const hookPath = taggedPath(\n basedir,\n 'hooks',\n data.correlationId,\n tag\n );\n const existingHook = await readJSONWithFallback(\n basedir,\n 'hooks',\n data.correlationId,\n HookSchema,\n tag\n );\n if (existingHook) {\n // Delete the token constraint file to free up the token for reuse\n const disposedConstraintPath = path.join(\n basedir,\n 'hooks',\n 'tokens',\n `${hashToken(existingHook.token)}.json`\n );\n await deleteJSON(disposedConstraintPath);\n }\n await deleteJSON(hookPath);\n } else if (data.eventType === 'wait_created' && 'eventData' in data) {\n // wait_created: Creates wait entity with status 'waiting'.\n // Atomic claim on a per-(runId, correlationId) constraint file\n // ensures duplicate wait_created from concurrent invocations\n // surfaces as EntityConflictError (replaces a prior TOCTOU\n // read-then-check that could let both writers through).\n const waitCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const waitCreatedLockName = tag\n ? `${waitCompositeKey}.created.${tag}`\n : `${waitCompositeKey}.created`;\n const waitCreatedLockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'waits',\n waitCreatedLockName\n );\n const waitCreatedClaimed = await writeExclusive(\n waitCreatedLockPath,\n ''\n );\n if (!waitCreatedClaimed) {\n throw new EntityConflictError(\n `Wait \"${data.correlationId}\" already exists`\n );\n }\n const waitData = data.eventData as {\n resumeAt?: Date;\n };\n wait = {\n waitId: waitCompositeKey,\n runId: effectiveRunId,\n status: 'waiting',\n resumeAt: waitData.resumeAt,\n completedAt: undefined,\n createdAt: now,\n updatedAt: now,\n specVersion: effectiveSpecVersion,\n };\n await writeJSON(\n taggedPath(basedir, 'waits', waitCompositeKey, tag),\n wait\n );\n } else if (data.eventType === 'wait_completed') {\n // wait_completed: Transitions wait to 'completed', rejects duplicates.\n // Uses writeExclusive on a lock file to atomically prevent concurrent\n // invocations from both completing the same wait (TOCTOU race).\n const waitCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const waitLockName = tag\n ? `${waitCompositeKey}.completed.${tag}`\n : `${waitCompositeKey}.completed`;\n const lockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'waits',\n waitLockName\n );\n const claimed = await writeExclusive(lockPath, '');\n if (!claimed) {\n throw new EntityConflictError(\n `Wait \"${data.correlationId}\" already completed`\n );\n }\n const existingWait = await readJSONWithFallback(\n basedir,\n 'waits',\n waitCompositeKey,\n WaitSchema,\n tag\n );\n if (!existingWait) {\n // Clean up the lock file we just claimed — the wait doesn't exist\n await fs.unlink(lockPath).catch(() => {});\n throw new WorkflowWorldError(\n `Wait \"${data.correlationId}\" not found`\n );\n }\n // The lock file (writeExclusive above) already prevents concurrent\n // completions — no additional status check needed.\n wait = {\n ...existingWait,\n status: 'completed',\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'waits', waitCompositeKey, tag),\n wait,\n { overwrite: true }\n );\n }\n // Note: hook_received events are stored in the event log but don't\n // modify the Hook entity (which doesn't have a payload field)\n\n // Store event using composite key {runId}-{eventId}\n const compositeKey = `${effectiveRunId}-${eventId}`;\n await writeJSON(\n taggedPath(basedir, 'events', compositeKey, tag),\n event\n );\n\n const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const filteredEvent = stripEventDataRefs(event, resolveData);\n\n // For run_started: include all events so the runtime can skip\n // the initial events.list call and reduce TTFB.\n let events: Event[] | undefined;\n if (data.eventType === 'run_started' && run) {\n const allEvents = await paginatedFileSystemQuery({\n directory: path.join(basedir, 'events'),\n schema: EventSchema,\n filePrefix: `${effectiveRunId}-`,\n sortOrder: 'asc',\n getCreatedAt: getObjectCreatedAt('evnt'),\n getId: (e) => e.eventId,\n });\n events = allEvents.data;\n }\n\n // Return EventResult with event and any created/updated entity\n return {\n event: filteredEvent,\n run,\n step,\n hook,\n wait,\n events,\n };\n } // end createImpl\n },\n\n async get(runId, eventId, params) {\n assertSafeEntityId('runId', runId);\n assertSafeEntityId('eventId', eventId);\n const compositeKey = `${runId}-${eventId}`;\n const event = await readJSONWithFallback(\n basedir,\n 'events',\n compositeKey,\n EventSchema,\n tag\n );\n if (!event) {\n throw new Error(`Event ${eventId} in run ${runId} not found`);\n }\n const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n return stripEventDataRefs(event, resolveData);\n },\n\n async list(params) {\n const { runId } = params;\n assertSafeEntityId('runId', runId);\n const resolveData = params.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const result = await paginatedFileSystemQuery({\n directory: path.join(basedir, 'events'),\n schema: EventSchema,\n filePrefix: `${runId}-`,\n // Events in chronological order (oldest first) by default,\n // different from the default for other list calls.\n sortOrder: params.pagination?.sortOrder ?? 'asc',\n limit: params.pagination?.limit,\n cursor: params.pagination?.cursor,\n getCreatedAt: getObjectCreatedAt('evnt'),\n getId: (event) => event.eventId,\n });\n\n // If resolveData is \"none\", remove eventData from events\n if (resolveData === 'none') {\n return {\n ...result,\n data: result.data.map((event) =>\n stripEventDataRefs(event, resolveData)\n ),\n };\n }\n\n return result;\n },\n\n async listByCorrelationId(params) {\n const correlationId = params.correlationId;\n assertSafeEntityId('correlationId', correlationId);\n const resolveData = params.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const result = await paginatedFileSystemQuery({\n directory: path.join(basedir, 'events'),\n schema: EventSchema,\n // No filePrefix - search all events\n filter: (event) => event.correlationId === correlationId,\n // Events in chronological order (oldest first) by default,\n // different from the default for other list calls.\n sortOrder: params.pagination?.sortOrder ?? 'asc',\n limit: params.pagination?.limit,\n cursor: params.pagination?.cursor,\n getCreatedAt: getObjectCreatedAt('evnt'),\n getId: (event) => event.eventId,\n });\n\n // If resolveData is \"none\", remove eventData from events\n if (resolveData === 'none') {\n return {\n ...result,\n data: result.data.map((event) =>\n stripEventDataRefs(event, resolveData)\n ),\n };\n }\n\n return result;\n },\n };\n}\n"]}
1
+ {"version":3,"file":"events-storage.js","sourceRoot":"","sources":["../../src/storage/events-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAClC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EACL,mBAAmB,EACnB,iBAAiB,EACjB,eAAe,EACf,oBAAoB,EACpB,aAAa,EACb,wBAAwB,EACxB,kBAAkB,GACnB,MAAM,kBAAkB,CAAC;AAW1B,OAAO,EACL,WAAW,EACX,UAAU,EACV,mBAAmB,EACnB,kBAAkB,EAClB,oBAAoB,EACpB,UAAU,EACV,qBAAqB,EACrB,UAAU,EACV,iBAAiB,GAClB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EACL,kBAAkB,EAClB,UAAU,EACV,YAAY,EACZ,aAAa,EACb,wBAAwB,EACxB,QAAQ,EACR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CAAC;QAED,KAAK,CAAC,mBAAmB,CAAC,MAAM;YAC9B,MAAM,aAAa,GAAG,MAAM,CAAC,aAAa,CAAC;YAC3C,kBAAkB,CAAC,eAAe,EAAE,aAAa,CAAC,CAAC;YACnD,MAAM,WAAW,GAAG,MAAM,CAAC,WAAW,IAAI,2BAA2B,CAAC;YACtE,MAAM,MAAM,GAAG,MAAM,wBAAwB,CAAC;gBAC5C,SAAS,EAAE,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,QAAQ,CAAC;gBACvC,MAAM,EAAE,WAAW;gBACnB,oCAAoC;gBACpC,MAAM,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,aAAa,KAAK,aAAa;gBACxD,2DAA2D;gBAC3D,mDAAmD;gBACnD,SAAS,EAAE,MAAM,CAAC,UAAU,EAAE,SAAS,IAAI,KAAK;gBAChD,KAAK,EAAE,MAAM,CAAC,UAAU,EAAE,KAAK;gBAC/B,MAAM,EAAE,MAAM,CAAC,UAAU,EAAE,MAAM;gBACjC,YAAY,EAAE,kBAAkB,CAAC,MAAM,CAAC;gBACxC,KAAK,EAAE,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO;aAChC,CAAC,CAAC;YAEH,yDAAyD;YACzD,IAAI,WAAW,KAAK,MAAM,EAAE,CAAC;gBAC3B,OAAO;oBACL,GAAG,MAAM;oBACT,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAC9B,kBAAkB,CAAC,KAAK,EAAE,WAAW,CAAC,CACvC;iBACF,CAAC;YACJ,CAAC;YAED,OAAO,MAAM,CAAC;QAChB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import fs from 'node:fs/promises';\nimport path from 'node:path';\nimport {\n EntityConflictError,\n HookNotFoundError,\n RunExpiredError,\n RunNotSupportedError,\n TooEarlyError,\n WorkflowRunNotFoundError,\n WorkflowWorldError,\n} from '@workflow/errors';\nimport type {\n Event,\n EventResult,\n Hook,\n SerializedData,\n Step,\n Storage,\n Wait,\n WorkflowRun,\n} from '@workflow/world';\nimport {\n EventSchema,\n HookSchema,\n isLegacySpecVersion,\n requiresNewerWorld,\n SPEC_VERSION_CURRENT,\n StepSchema,\n validateUlidTimestamp,\n WaitSchema,\n WorkflowRunSchema,\n} from '@workflow/world';\nimport { z } from 'zod';\nimport { DEFAULT_RESOLVE_DATA_OPTION } from '../config.js';\nimport {\n assertSafeEntityId,\n deleteJSON,\n jsonReplacer,\n listJSONFiles,\n paginatedFileSystemQuery,\n readJSON,\n readJSONWithFallback,\n resolveWithinBase,\n taggedPath,\n writeExclusive,\n writeJSON,\n} from '../fs.js';\nimport { stripEventDataRefs } from './filters.js';\nimport { getObjectCreatedAt, hashToken, monotonicUlid } from './helpers.js';\nimport { deleteAllHooksForRun } from './hooks-storage.js';\nimport { handleLegacyEvent } from './legacy.js';\n\n/**\n * Per-step in-process async mutex. Serializes concurrent `events.create` calls\n * that target the same step, so that the \"check terminal state, then write step\n * entity + event\" sequence is atomic. Without this, two concurrent step_started\n * calls can both pass the not-terminal check and both write step_started events\n * — or a step_started can land in the log after step_completed has already\n * written, producing unconsumed events on replay.\n *\n * Duplicate step_started events for a non-terminal step are still allowed\n * (retries legitimately re-start a step), only writes to an already-terminal\n * step are rejected.\n */\nconst stepLocks = new Map<string, Promise<unknown>>();\n\nconst HookTokenClaimSchema = z.object({\n runId: z.string(),\n});\n\nasync function readHookTokenClaim(\n constraintPath: string\n): Promise<z.infer<typeof HookTokenClaimSchema> | null> {\n try {\n return await readJSON(constraintPath, HookTokenClaimSchema);\n } catch (error) {\n if (error instanceof SyntaxError || error instanceof z.ZodError) {\n return null;\n }\n throw error;\n }\n}\n\nfunction withStepLock<T>(key: string, fn: () => Promise<T>): Promise<T> {\n const prev = stepLocks.get(key);\n const taskBox: { task?: Promise<T> } = {};\n const task = (async () => {\n if (prev) {\n // Wait for the previous task to settle; don't inherit its errors.\n await prev.catch(() => undefined);\n }\n try {\n return await fn();\n } finally {\n if (stepLocks.get(key) === taskBox.task) {\n stepLocks.delete(key);\n }\n }\n })();\n taskBox.task = task;\n stepLocks.set(key, task);\n return task;\n}\n\n/**\n * Helper function to delete all waits associated with a workflow run.\n * Called when a run reaches a terminal state.\n */\nasync function deleteAllWaitsForRun(\n basedir: string,\n runId: string\n): Promise<void> {\n const waitsDir = path.join(basedir, 'waits');\n const files = await listJSONFiles(waitsDir);\n\n for (const file of files) {\n // fileIds may contain tag suffixes (e.g., \"wrun_ABC-corrId.vitest-0\")\n // but startsWith still matches correctly since the tag is a suffix.\n if (file.startsWith(`${runId}-`)) {\n const waitPath = path.join(waitsDir, `${file}.json`);\n await deleteJSON(waitPath);\n }\n }\n}\n\n/**\n * Creates the events storage implementation using the filesystem.\n * Implements the Storage['events'] interface with create, list, and listByCorrelationId operations.\n */\nexport function createEventsStorage(\n basedir: string,\n tag?: string\n): Storage['events'] {\n return {\n async create(runId, data, params): Promise<EventResult> {\n // Validate request-supplied IDs before they're concatenated into\n // filesystem paths. This is the primary defense against path traversal\n // attacks where a client supplies runId / correlationId values like\n // \"../../../package\" to read or write files outside the storage root.\n // Run before taking the per-step mutex so malformed inputs fail fast.\n if (runId != null && runId !== '') {\n assertSafeEntityId('runId', runId);\n }\n if (\n 'correlationId' in data &&\n typeof data.correlationId === 'string' &&\n data.correlationId.length > 0\n ) {\n assertSafeEntityId('correlationId', data.correlationId);\n }\n\n // Step lifecycle events are serialized per-step via an in-process mutex\n // so that the \"check state, then write\" sequence in step_started /\n // step_completed / step_failed / step_retrying is atomic. step_created\n // is also serialized so duplicate-create races don't leave extra\n // step_created events in the log.\n const isStepEvent =\n data.eventType === 'step_created' ||\n data.eventType === 'step_started' ||\n data.eventType === 'step_completed' ||\n data.eventType === 'step_failed' ||\n data.eventType === 'step_retrying';\n if (isStepEvent && runId && data.correlationId) {\n const lockKey = tag\n ? `${runId}-${data.correlationId}.${tag}`\n : `${runId}-${data.correlationId}`;\n return withStepLock(lockKey, () => createImpl());\n }\n return createImpl();\n\n async function createImpl(): Promise<EventResult> {\n const eventId = `evnt_${monotonicUlid()}`;\n const now = new Date();\n\n // For run_created events, use client-provided runId or generate one server-side\n let effectiveRunId: string;\n if (data.eventType === 'run_created' && (!runId || runId === '')) {\n effectiveRunId = `wrun_${monotonicUlid()}`;\n } else if (!runId) {\n throw new Error('runId is required for non-run_created events');\n } else {\n effectiveRunId = runId;\n }\n\n // Validate client-provided runId timestamp is within acceptable threshold\n if (data.eventType === 'run_created' && runId && runId !== '') {\n const validationError = validateUlidTimestamp(\n effectiveRunId,\n 'wrun_'\n );\n if (validationError) {\n throw new WorkflowWorldError(validationError);\n }\n }\n\n // specVersion is always sent by the runtime, but we provide a fallback for safety\n const effectiveSpecVersion = data.specVersion ?? SPEC_VERSION_CURRENT;\n\n // Helper to check if run is in terminal state\n const isRunTerminal = (status: string) =>\n ['completed', 'failed', 'cancelled'].includes(status);\n\n // Helper to check if step is in terminal state\n const isStepTerminal = (status: string) =>\n ['completed', 'failed', 'cancelled'].includes(status);\n\n // Get current run state for validation (if not creating a new run)\n // Skip run validation for step_completed and step_retrying - they only operate\n // on running steps, and running steps are always allowed to modify regardless\n // of run state. This optimization saves filesystem reads per step event.\n let currentRun: WorkflowRun | null = null;\n const skipRunValidationEvents = ['step_completed', 'step_retrying'];\n if (\n data.eventType !== 'run_created' &&\n !skipRunValidationEvents.includes(data.eventType)\n ) {\n currentRun = await readJSONWithFallback(\n basedir,\n 'runs',\n effectiveRunId,\n WorkflowRunSchema,\n tag\n );\n\n // Resilient start: run_started on non-existent run with eventData\n // creates the run first, so the queue can bootstrap a run that\n // failed to create during start().\n if (\n data.eventType === 'run_started' &&\n !currentRun &&\n 'eventData' in data &&\n data.eventData\n ) {\n const runInputData = data.eventData as {\n deploymentId?: string;\n workflowName?: string;\n input?: any;\n executionContext?: Record<string, any>;\n };\n if (\n runInputData.deploymentId &&\n runInputData.workflowName &&\n runInputData.input !== undefined\n ) {\n // Atomically try to create the run entity. writeExclusive\n // uses O_CREAT|O_EXCL so only the first writer wins,\n // preventing a TOCTOU race where a concurrent run_created\n // from start() could overwrite a run that was already\n // transitioned to 'running'.\n const createdRun: WorkflowRun = {\n runId: effectiveRunId,\n deploymentId: runInputData.deploymentId,\n status: 'pending',\n workflowName: runInputData.workflowName,\n specVersion: effectiveSpecVersion,\n executionContext: runInputData.executionContext,\n input: runInputData.input,\n output: undefined,\n error: undefined,\n startedAt: undefined,\n completedAt: undefined,\n createdAt: now,\n updatedAt: now,\n };\n const runPath = taggedPath(basedir, 'runs', effectiveRunId, tag);\n const created = await writeExclusive(\n runPath,\n JSON.stringify(createdRun, jsonReplacer)\n );\n\n if (created) {\n // We created the run — also write the run_created event.\n const runCreatedEventId = `evnt_${monotonicUlid()}`;\n const runCreatedEvent: Event = {\n eventType: 'run_created',\n runId: effectiveRunId,\n eventId: runCreatedEventId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n eventData: {\n deploymentId: runInputData.deploymentId,\n workflowName: runInputData.workflowName,\n input: runInputData.input,\n executionContext: runInputData.executionContext,\n },\n };\n const createdCompositeKey = `${effectiveRunId}-${runCreatedEventId}`;\n await writeJSON(\n taggedPath(basedir, 'events', createdCompositeKey, tag),\n runCreatedEvent\n );\n currentRun = createdRun;\n } else {\n // Run already exists (concurrent run_created won the\n // race). Re-read it so downstream logic sees the real state.\n currentRun = await readJSONWithFallback(\n basedir,\n 'runs',\n effectiveRunId,\n WorkflowRunSchema,\n tag\n );\n }\n }\n }\n }\n\n // run_failed on a non-existent run is rejected to match the\n // postgres and vercel worlds, which both surface this as a\n // WorkflowRunNotFoundError rather than silently persisting an\n // event for a run that was never created.\n if (data.eventType === 'run_failed' && !currentRun) {\n throw new WorkflowRunNotFoundError(effectiveRunId);\n }\n\n // ============================================================\n // VERSION COMPATIBILITY: Check run spec version\n // ============================================================\n // For events that have fetched the run, check version compatibility.\n // Skip for run_created (no existing run) and runtime events (step_completed, step_retrying).\n if (currentRun) {\n // Check if run requires a newer world version\n if (requiresNewerWorld(currentRun.specVersion)) {\n throw new RunNotSupportedError(\n currentRun.specVersion!,\n SPEC_VERSION_CURRENT\n );\n }\n\n // Route to legacy handler for pre-event-sourcing runs\n if (isLegacySpecVersion(currentRun.specVersion)) {\n return handleLegacyEvent(\n basedir,\n effectiveRunId,\n data,\n currentRun,\n params\n );\n }\n }\n\n // ============================================================\n // VALIDATION: Terminal state and event ordering checks\n // ============================================================\n\n // Run terminal state validation\n if (currentRun && isRunTerminal(currentRun.status)) {\n const runTerminalEvents = [\n 'run_started',\n 'run_completed',\n 'run_failed',\n ];\n\n // Idempotent operation: run_cancelled on already cancelled run is allowed\n if (\n data.eventType === 'run_cancelled' &&\n currentRun.status === 'cancelled'\n ) {\n // Return existing state (idempotent)\n const event: Event = {\n ...data,\n runId: effectiveRunId,\n eventId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n };\n const compositeKey = `${effectiveRunId}-${eventId}`;\n await writeJSON(\n taggedPath(basedir, 'events', compositeKey, tag),\n event\n );\n const resolveData =\n params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n return {\n event: stripEventDataRefs(event, resolveData),\n run: currentRun,\n };\n }\n\n // For run_started on terminal runs, use RunExpiredError so the\n // runtime knows to exit without retrying.\n if (data.eventType === 'run_started') {\n throw new RunExpiredError(\n `Workflow run \"${effectiveRunId}\" is already in terminal state \"${currentRun.status}\"`\n );\n }\n\n // Other run state transitions are not allowed on terminal runs\n if (\n runTerminalEvents.includes(data.eventType) ||\n data.eventType === 'run_cancelled'\n ) {\n throw new EntityConflictError(\n `Cannot transition run from terminal state \"${currentRun.status}\"`\n );\n }\n\n // Creating new entities on terminal runs is not allowed\n if (\n data.eventType === 'step_created' ||\n data.eventType === 'hook_created' ||\n data.eventType === 'wait_created'\n ) {\n throw new EntityConflictError(\n `Cannot create new entities on run in terminal state \"${currentRun.status}\"`\n );\n }\n }\n\n // Step-related event validation (ordering and terminal state)\n // Store existingStep so we can reuse it later (avoid double read)\n let validatedStep: Step | null = null;\n const stepEvents = [\n 'step_started',\n 'step_completed',\n 'step_failed',\n 'step_retrying',\n ];\n if (stepEvents.includes(data.eventType) && data.correlationId) {\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n validatedStep = await readJSONWithFallback(\n basedir,\n 'steps',\n stepCompositeKey,\n StepSchema,\n tag\n );\n\n // Event ordering: step must exist before these events\n if (!validatedStep) {\n throw new WorkflowWorldError(\n `Step \"${data.correlationId}\" not found`\n );\n }\n\n // Step terminal state validation\n if (isStepTerminal(validatedStep.status)) {\n throw new EntityConflictError(\n `Cannot modify step in terminal state \"${validatedStep.status}\"`\n );\n }\n\n // On terminal runs: only allow completing/failing in-progress steps\n if (currentRun && isRunTerminal(currentRun.status)) {\n if (validatedStep.status !== 'running') {\n throw new RunExpiredError(\n `Cannot modify non-running step on run in terminal state \"${currentRun.status}\"`\n );\n }\n }\n }\n\n // Hook-related event validation (ordering)\n const hookEventsRequiringExistence = ['hook_disposed', 'hook_received'];\n if (\n hookEventsRequiringExistence.includes(data.eventType) &&\n data.correlationId\n ) {\n const existingHook = await readJSONWithFallback(\n basedir,\n 'hooks',\n data.correlationId,\n HookSchema,\n tag\n );\n\n if (!existingHook) {\n throw new HookNotFoundError(data.correlationId);\n }\n }\n const event: Event = {\n ...data,\n runId: effectiveRunId,\n eventId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n };\n // Strip eventData from run_started — it belongs on run_created only.\n if (data.eventType === 'run_started' && 'eventData' in event) {\n delete (event as any).eventData;\n }\n\n // Track entity created/updated for EventResult\n let run: WorkflowRun | undefined;\n let step: Step | undefined;\n let hook: Hook | undefined;\n let wait: Wait | undefined;\n\n // Create/update entity based on event type (event-sourced architecture)\n // Run lifecycle events\n if (data.eventType === 'run_created' && 'eventData' in data) {\n const runData = data.eventData as {\n deploymentId: string;\n workflowName: string;\n input: SerializedData;\n executionContext?: Record<string, any>;\n };\n run = {\n runId: effectiveRunId,\n deploymentId: runData.deploymentId,\n status: 'pending',\n workflowName: runData.workflowName,\n // Propagate specVersion from the event to the run entity\n specVersion: effectiveSpecVersion,\n executionContext: runData.executionContext,\n input: runData.input,\n output: undefined,\n error: undefined,\n startedAt: undefined,\n completedAt: undefined,\n createdAt: now,\n updatedAt: now,\n };\n // Use writeExclusive (O_CREAT|O_EXCL) to atomically create the\n // run entity file. This prevents a TOCTOU race with the resilient\n // start path (run_started on non-existent run) that could result\n // in duplicate run_created events in the event log.\n const runPath = taggedPath(basedir, 'runs', effectiveRunId, tag);\n const created = await writeExclusive(\n runPath,\n JSON.stringify(run, jsonReplacer, 2)\n );\n if (!created) {\n throw new EntityConflictError(\n `Workflow run \"${effectiveRunId}\" already exists`\n );\n }\n } else if (data.eventType === 'run_started') {\n // Reuse currentRun from validation (already read above)\n if (currentRun) {\n // If already running, return the run without inserting a\n // duplicate event. This makes run_started idempotent for\n // concurrent invocations. We omit preloaded events here\n // because this is a rare race-condition path — the runtime\n // falls back to loadWorkflowRunEvents().\n if (currentRun.status === 'running') {\n return { run: currentRun };\n }\n\n run = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n status: 'running',\n output: undefined,\n error: undefined,\n completedAt: undefined,\n startedAt: currentRun.startedAt ?? now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'runs', effectiveRunId, tag),\n run,\n { overwrite: true }\n );\n }\n } else if (data.eventType === 'run_completed' && 'eventData' in data) {\n const completedData = data.eventData as { output?: any };\n // Reuse currentRun from validation (already read above)\n if (currentRun) {\n run = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n startedAt: currentRun.startedAt,\n status: 'completed',\n output: completedData.output,\n error: undefined,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'runs', effectiveRunId, tag),\n run,\n { overwrite: true }\n );\n await Promise.all([\n deleteAllHooksForRun(basedir, effectiveRunId),\n deleteAllWaitsForRun(basedir, effectiveRunId),\n ]);\n }\n } else if (data.eventType === 'run_failed' && 'eventData' in data) {\n const failedData = data.eventData as {\n error: unknown;\n errorCode?: string;\n };\n // Reuse currentRun from validation (already read above)\n if (currentRun) {\n // The error field is SerializedData (Uint8Array) produced by\n // dehydrateRunError. We store it verbatim — consumers hydrate it\n // via hydrateRunError to reconstruct the original thrown value.\n run = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n startedAt: currentRun.startedAt,\n status: 'failed',\n output: undefined,\n error: failedData.error as Uint8Array,\n errorCode: failedData.errorCode,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'runs', effectiveRunId, tag),\n run,\n { overwrite: true }\n );\n await Promise.all([\n deleteAllHooksForRun(basedir, effectiveRunId),\n deleteAllWaitsForRun(basedir, effectiveRunId),\n ]);\n }\n } else if (data.eventType === 'run_cancelled') {\n // Reuse currentRun from validation (already read above)\n if (currentRun) {\n run = {\n runId: currentRun.runId,\n deploymentId: currentRun.deploymentId,\n workflowName: currentRun.workflowName,\n specVersion: currentRun.specVersion,\n executionContext: currentRun.executionContext,\n input: currentRun.input,\n createdAt: currentRun.createdAt,\n expiredAt: currentRun.expiredAt,\n startedAt: currentRun.startedAt,\n status: 'cancelled',\n output: undefined,\n error: undefined,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'runs', effectiveRunId, tag),\n run,\n { overwrite: true }\n );\n await Promise.all([\n deleteAllHooksForRun(basedir, effectiveRunId),\n deleteAllWaitsForRun(basedir, effectiveRunId),\n ]);\n }\n } else if (\n // Step lifecycle events\n data.eventType === 'step_created' &&\n 'eventData' in data\n ) {\n // step_created: Creates step entity with status 'pending', attempt=0, createdAt set.\n // Two concurrent invocations with identical correlationIds (e.g. the\n // snapshot runtime's deterministic correlationIds across replays)\n // must be deduped — otherwise both writes succeed and the event log\n // ends up with duplicate step_created entries. The outer\n // withStepLock mutex serializes within a single process; this\n // O_CREAT|O_EXCL constraint file additionally protects against\n // cross-process races (two pnpm workers, redelivered queue\n // messages, etc.). The loser throws EntityConflictError so the\n // runtime's existing catch path can swallow it and avoid\n // double-queuing the step.\n const stepCreatedLockName = tag\n ? `${effectiveRunId}-${data.correlationId}.created.${tag}`\n : `${effectiveRunId}-${data.correlationId}.created`;\n const stepCreatedLockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'steps',\n stepCreatedLockName\n );\n const stepCreatedClaimed = await writeExclusive(\n stepCreatedLockPath,\n ''\n );\n if (!stepCreatedClaimed) {\n throw new EntityConflictError(\n `Step \"${data.correlationId}\" already created`\n );\n }\n const stepData = data.eventData as {\n stepName: string;\n input: any;\n };\n step = {\n runId: effectiveRunId,\n stepId: data.correlationId,\n stepName: stepData.stepName,\n status: 'pending',\n input: stepData.input,\n output: undefined,\n error: undefined,\n attempt: 0,\n startedAt: undefined,\n completedAt: undefined,\n createdAt: now,\n updatedAt: now,\n // Propagate specVersion from the event to the step entity\n specVersion: effectiveSpecVersion,\n };\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step\n );\n } else if (data.eventType === 'step_started') {\n // step_started: Increments attempt, sets status to 'running'\n // Sets startedAt only on the first start (not updated on retries)\n // Reuse validatedStep from validation (already read above)\n if (validatedStep) {\n // Check if retryAfter timestamp hasn't been reached yet\n if (\n validatedStep.retryAfter &&\n validatedStep.retryAfter.getTime() > Date.now()\n ) {\n throw new TooEarlyError(\n `Cannot start step \"${data.correlationId}\": retryAfter timestamp has not been reached yet`,\n {\n retryAfter: Math.ceil(\n (validatedStep.retryAfter.getTime() - Date.now()) / 1000\n ),\n }\n );\n }\n\n // Best-effort guard: re-read the step entity to check if it\n // reached terminal state between the validation read and now.\n // This narrows the TOCTOU window but does not fully eliminate it\n // (the local world is single-process / dev-only; the postgres\n // world uses SQL-level atomic guards for production).\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const freshStep = await readJSONWithFallback(\n basedir,\n 'steps',\n stepCompositeKey,\n StepSchema,\n tag\n );\n if (freshStep && isStepTerminal(freshStep.status)) {\n throw new EntityConflictError(\n `Cannot modify step in terminal state \"${freshStep.status}\"`\n );\n }\n\n step = {\n ...validatedStep,\n status: 'running',\n // Only set startedAt on the first start\n startedAt: validatedStep.startedAt ?? now,\n // Increment attempt counter on every start\n attempt: validatedStep.attempt + 1,\n // Clear retryAfter now that the step has started\n retryAfter: undefined,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step,\n { overwrite: true }\n );\n }\n } else if (data.eventType === 'step_completed' && 'eventData' in data) {\n // step_completed: Terminal state with output\n // Uses writeExclusive on a lock file to atomically prevent concurrent\n // invocations from both completing the same step (TOCTOU race).\n const completedData = data.eventData as { result: any };\n if (validatedStep) {\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const lockName = tag\n ? `${stepCompositeKey}.terminal.${tag}`\n : `${stepCompositeKey}.terminal`;\n const terminalLockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'steps',\n lockName\n );\n const claimed = await writeExclusive(terminalLockPath, '');\n if (!claimed) {\n throw new EntityConflictError(\n 'Cannot modify step in terminal state'\n );\n }\n step = {\n ...validatedStep,\n status: 'completed',\n output: completedData.result,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step,\n { overwrite: true }\n );\n }\n } else if (data.eventType === 'step_failed' && 'eventData' in data) {\n // step_failed: Terminal state with error\n // Uses writeExclusive on a lock file to atomically prevent concurrent\n // invocations from both failing the same step (TOCTOU race).\n const failedData = data.eventData as {\n error: unknown;\n };\n if (validatedStep) {\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const lockName = tag\n ? `${stepCompositeKey}.terminal.${tag}`\n : `${stepCompositeKey}.terminal`;\n const terminalLockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'steps',\n lockName\n );\n const claimed = await writeExclusive(terminalLockPath, '');\n if (!claimed) {\n throw new EntityConflictError(\n 'Cannot modify step in terminal state'\n );\n }\n // The error field is SerializedData (Uint8Array) produced by\n // dehydrateStepError. We store it verbatim — consumers hydrate it\n // via hydrateStepError to reconstruct the original thrown value.\n step = {\n ...validatedStep,\n status: 'failed',\n error: failedData.error as Uint8Array,\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step,\n { overwrite: true }\n );\n }\n } else if (data.eventType === 'step_retrying' && 'eventData' in data) {\n // step_retrying: Sets status back to 'pending', records error\n // Reuse validatedStep from validation (already read above)\n const retryData = data.eventData as {\n error: unknown;\n retryAfter?: Date;\n };\n if (validatedStep) {\n const stepCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n step = {\n ...validatedStep,\n status: 'pending',\n error: retryData.error as Uint8Array,\n retryAfter: retryData.retryAfter,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'steps', stepCompositeKey, tag),\n step,\n { overwrite: true }\n );\n }\n } else if (\n // Hook lifecycle events\n data.eventType === 'hook_created' &&\n 'eventData' in data\n ) {\n const hookData = data.eventData as {\n token: string;\n metadata?: any;\n isWebhook?: boolean;\n isSystem?: boolean;\n };\n\n // Atomically claim the token using an exclusive-create constraint file.\n // This avoids the TOCTOU race of the previous read-all-then-check approach.\n const constraintPath = path.join(\n basedir,\n 'hooks',\n 'tokens',\n `${hashToken(hookData.token)}.json`\n );\n const tokenClaimed = await writeExclusive(\n constraintPath,\n JSON.stringify({\n token: hookData.token,\n hookId: data.correlationId,\n runId: effectiveRunId,\n })\n );\n\n if (!tokenClaimed) {\n const existingClaim = await readHookTokenClaim(constraintPath);\n\n // Create hook_conflict event instead of hook_created\n // This allows the workflow to continue and fail gracefully when the hook is awaited\n const conflictEvent: Event = {\n eventType: 'hook_conflict',\n correlationId: data.correlationId,\n eventData: {\n token: hookData.token,\n ...(existingClaim\n ? { conflictingRunId: existingClaim.runId }\n : {}),\n },\n runId: effectiveRunId,\n eventId,\n createdAt: now,\n specVersion: effectiveSpecVersion,\n };\n\n // Store the conflict event\n const compositeKey = `${effectiveRunId}-${eventId}`;\n await writeJSON(\n taggedPath(basedir, 'events', compositeKey, tag),\n conflictEvent\n );\n\n const resolveData =\n params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const filteredEvent = stripEventDataRefs(\n conflictEvent,\n resolveData\n );\n\n // Return EventResult with conflict event (no hook entity created)\n return {\n event: filteredEvent,\n run,\n step,\n hook: undefined,\n };\n }\n\n hook = {\n runId: effectiveRunId,\n hookId: data.correlationId,\n token: hookData.token,\n metadata: hookData.metadata,\n ownerId: 'local-owner',\n projectId: 'local-project',\n environment: 'local',\n createdAt: now,\n // Propagate specVersion from the event to the hook entity\n specVersion: effectiveSpecVersion,\n isWebhook: hookData.isWebhook ?? false,\n isSystem: hookData.isSystem ?? false,\n };\n await writeJSON(\n taggedPath(basedir, 'hooks', data.correlationId, tag),\n hook\n );\n } else if (data.eventType === 'hook_disposed') {\n // hook_disposed: Deletes hook entity, rejects duplicates.\n // Uses writeExclusive on a lock file to atomically prevent concurrent\n // invocations from both disposing the same hook (TOCTOU race).\n const hookLockName = tag\n ? `${data.correlationId}.disposed.${tag}`\n : `${data.correlationId}.disposed`;\n const lockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'hooks',\n hookLockName\n );\n const claimed = await writeExclusive(lockPath, '');\n if (!claimed) {\n throw new EntityConflictError(\n `Hook \"${data.correlationId}\" already disposed`\n );\n }\n // Read the hook to get its token before deleting\n const hookPath = taggedPath(\n basedir,\n 'hooks',\n data.correlationId,\n tag\n );\n const existingHook = await readJSONWithFallback(\n basedir,\n 'hooks',\n data.correlationId,\n HookSchema,\n tag\n );\n if (existingHook) {\n // Delete the token constraint file to free up the token for reuse\n const disposedConstraintPath = path.join(\n basedir,\n 'hooks',\n 'tokens',\n `${hashToken(existingHook.token)}.json`\n );\n await deleteJSON(disposedConstraintPath);\n }\n await deleteJSON(hookPath);\n } else if (data.eventType === 'wait_created' && 'eventData' in data) {\n // wait_created: Creates wait entity with status 'waiting'.\n // Atomic claim on a per-(runId, correlationId) constraint file\n // ensures duplicate wait_created from concurrent invocations\n // surfaces as EntityConflictError (replaces a prior TOCTOU\n // read-then-check that could let both writers through).\n const waitCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const waitCreatedLockName = tag\n ? `${waitCompositeKey}.created.${tag}`\n : `${waitCompositeKey}.created`;\n const waitCreatedLockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'waits',\n waitCreatedLockName\n );\n const waitCreatedClaimed = await writeExclusive(\n waitCreatedLockPath,\n ''\n );\n if (!waitCreatedClaimed) {\n throw new EntityConflictError(\n `Wait \"${data.correlationId}\" already exists`\n );\n }\n const waitData = data.eventData as {\n resumeAt?: Date;\n };\n wait = {\n waitId: waitCompositeKey,\n runId: effectiveRunId,\n status: 'waiting',\n resumeAt: waitData.resumeAt,\n completedAt: undefined,\n createdAt: now,\n updatedAt: now,\n specVersion: effectiveSpecVersion,\n };\n await writeJSON(\n taggedPath(basedir, 'waits', waitCompositeKey, tag),\n wait\n );\n } else if (data.eventType === 'wait_completed') {\n // wait_completed: Transitions wait to 'completed', rejects duplicates.\n // Uses writeExclusive on a lock file to atomically prevent concurrent\n // invocations from both completing the same wait (TOCTOU race).\n const waitCompositeKey = `${effectiveRunId}-${data.correlationId}`;\n const waitLockName = tag\n ? `${waitCompositeKey}.completed.${tag}`\n : `${waitCompositeKey}.completed`;\n const lockPath = resolveWithinBase(\n basedir,\n '.locks',\n 'waits',\n waitLockName\n );\n const claimed = await writeExclusive(lockPath, '');\n if (!claimed) {\n throw new EntityConflictError(\n `Wait \"${data.correlationId}\" already completed`\n );\n }\n const existingWait = await readJSONWithFallback(\n basedir,\n 'waits',\n waitCompositeKey,\n WaitSchema,\n tag\n );\n if (!existingWait) {\n // Clean up the lock file we just claimed — the wait doesn't exist\n await fs.unlink(lockPath).catch(() => {});\n throw new WorkflowWorldError(\n `Wait \"${data.correlationId}\" not found`\n );\n }\n // The lock file (writeExclusive above) already prevents concurrent\n // completions — no additional status check needed.\n wait = {\n ...existingWait,\n status: 'completed',\n completedAt: now,\n updatedAt: now,\n };\n await writeJSON(\n taggedPath(basedir, 'waits', waitCompositeKey, tag),\n wait,\n { overwrite: true }\n );\n }\n // Note: hook_received events are stored in the event log but don't\n // modify the Hook entity (which doesn't have a payload field)\n\n // Store event using composite key {runId}-{eventId}\n const compositeKey = `${effectiveRunId}-${eventId}`;\n await writeJSON(\n taggedPath(basedir, 'events', compositeKey, tag),\n event\n );\n\n const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const filteredEvent = stripEventDataRefs(event, resolveData);\n\n // For run_started: preload one page of events so the runtime can skip\n // the initial events.list call when hasMore is false.\n let events: Event[] | undefined;\n let cursor: string | null | undefined;\n let hasMore: boolean | undefined;\n if (data.eventType === 'run_started' && run) {\n const allEvents = await paginatedFileSystemQuery({\n directory: path.join(basedir, 'events'),\n schema: EventSchema,\n filePrefix: `${effectiveRunId}-`,\n sortOrder: 'asc',\n limit: 1000,\n getCreatedAt: getObjectCreatedAt('evnt'),\n getId: (e) => e.eventId,\n });\n events = allEvents.data;\n cursor = allEvents.cursor;\n hasMore = allEvents.hasMore;\n }\n\n // Return EventResult with event and any created/updated entity\n return {\n event: filteredEvent,\n run,\n step,\n hook,\n wait,\n events,\n cursor,\n hasMore,\n };\n } // end createImpl\n },\n\n async get(runId, eventId, params) {\n assertSafeEntityId('runId', runId);\n assertSafeEntityId('eventId', eventId);\n const compositeKey = `${runId}-${eventId}`;\n const event = await readJSONWithFallback(\n basedir,\n 'events',\n compositeKey,\n EventSchema,\n tag\n );\n if (!event) {\n throw new Error(`Event ${eventId} in run ${runId} not found`);\n }\n const resolveData = params?.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n return stripEventDataRefs(event, resolveData);\n },\n\n async list(params) {\n const { runId } = params;\n assertSafeEntityId('runId', runId);\n const resolveData = params.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const result = await paginatedFileSystemQuery({\n directory: path.join(basedir, 'events'),\n schema: EventSchema,\n filePrefix: `${runId}-`,\n // Events in chronological order (oldest first) by default,\n // different from the default for other list calls.\n sortOrder: params.pagination?.sortOrder ?? 'asc',\n limit: params.pagination?.limit,\n cursor: params.pagination?.cursor,\n getCreatedAt: getObjectCreatedAt('evnt'),\n getId: (event) => event.eventId,\n });\n\n // If resolveData is \"none\", remove eventData from events\n if (resolveData === 'none') {\n return {\n ...result,\n data: result.data.map((event) =>\n stripEventDataRefs(event, resolveData)\n ),\n };\n }\n\n return result;\n },\n\n async listByCorrelationId(params) {\n const correlationId = params.correlationId;\n assertSafeEntityId('correlationId', correlationId);\n const resolveData = params.resolveData ?? DEFAULT_RESOLVE_DATA_OPTION;\n const result = await paginatedFileSystemQuery({\n directory: path.join(basedir, 'events'),\n schema: EventSchema,\n // No filePrefix - search all events\n filter: (event) => event.correlationId === correlationId,\n // Events in chronological order (oldest first) by default,\n // different from the default for other list calls.\n sortOrder: params.pagination?.sortOrder ?? 'asc',\n limit: params.pagination?.limit,\n cursor: params.pagination?.cursor,\n getCreatedAt: getObjectCreatedAt('evnt'),\n getId: (event) => event.eventId,\n });\n\n // If resolveData is \"none\", remove eventData from events\n if (resolveData === 'none') {\n return {\n ...result,\n data: result.data.map((event) =>\n stripEventDataRefs(event, resolveData)\n ),\n };\n }\n\n return result;\n },\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@workflow/world-local",
3
- "version": "5.0.0-beta.5",
3
+ "version": "5.0.0-beta.6",
4
4
  "description": "Local development World implementation for Workflow SDK",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -28,9 +28,9 @@
28
28
  "ulid": "~3.0.1",
29
29
  "undici": "7.22.0",
30
30
  "zod": "4.3.6",
31
+ "@workflow/errors": "5.0.0-beta.4",
31
32
  "@workflow/utils": "5.0.0-beta.2",
32
- "@workflow/errors": "5.0.0-beta.3",
33
- "@workflow/world": "5.0.0-beta.3"
33
+ "@workflow/world": "5.0.0-beta.4"
34
34
  },
35
35
  "devDependencies": {
36
36
  "@opentelemetry/api": "1.9.0",