@open-mercato/core 0.6.7-develop.6580.1.39ab1d9e62 → 0.6.7-develop.6582.1.04cac61287

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 (29) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/sales/commands/documents.js +8 -4
  3. package/dist/modules/sales/commands/documents.js.map +2 -2
  4. package/dist/modules/sales/workflows.js +4 -0
  5. package/dist/modules/sales/workflows.js.map +2 -2
  6. package/dist/modules/workflows/api/instances/route.js +3 -1
  7. package/dist/modules/workflows/api/instances/route.js.map +2 -2
  8. package/dist/modules/workflows/lib/activity-executor.js +30 -2
  9. package/dist/modules/workflows/lib/activity-executor.js.map +2 -2
  10. package/dist/modules/workflows/lib/code-registry.js +10 -17
  11. package/dist/modules/workflows/lib/code-registry.js.map +2 -2
  12. package/dist/modules/workflows/lib/event-trigger-service.js +14 -2
  13. package/dist/modules/workflows/lib/event-trigger-service.js.map +2 -2
  14. package/dist/modules/workflows/lib/parallel-handler.js +10 -1
  15. package/dist/modules/workflows/lib/parallel-handler.js.map +2 -2
  16. package/dist/modules/workflows/lib/workflow-executor.js +13 -3
  17. package/dist/modules/workflows/lib/workflow-executor.js.map +2 -2
  18. package/dist/modules/workflows/lib/workflow-safe-commands.js +42 -0
  19. package/dist/modules/workflows/lib/workflow-safe-commands.js.map +7 -0
  20. package/package.json +7 -7
  21. package/src/modules/sales/commands/documents.ts +4 -0
  22. package/src/modules/sales/workflows.ts +5 -0
  23. package/src/modules/workflows/api/instances/route.ts +4 -2
  24. package/src/modules/workflows/lib/activity-executor.ts +47 -3
  25. package/src/modules/workflows/lib/code-registry.ts +16 -39
  26. package/src/modules/workflows/lib/event-trigger-service.ts +15 -2
  27. package/src/modules/workflows/lib/parallel-handler.ts +11 -1
  28. package/src/modules/workflows/lib/workflow-executor.ts +22 -3
  29. package/src/modules/workflows/lib/workflow-safe-commands.ts +48 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/workflows/lib/workflow-executor.ts"],
4
- "sourcesContent": ["/**\n * Workflows Module - Workflow Executor Service\n *\n * Main orchestrator for workflow execution. Handles workflow lifecycle:\n * - Starting workflow instances from definitions\n * - Executing workflow steps and transitions\n * - Completing workflows with final status\n * - Triggering compensation on failure\n *\n * Functional API (no classes) following Open Mercato conventions.\n */\n\nimport { EntityManager, LockMode } from '@mikro-orm/core'\nimport type { AwilixContainer } from 'awilix'\nimport {\n WorkflowDefinition,\n WorkflowInstance,\n WorkflowEvent,\n type WorkflowInstanceStatus,\n} from '../data/entities'\nimport { compensateWorkflow } from './compensation-handler'\nimport { findWorkflowDefinition, findDefinitionForInstance } from './find-definition'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('workflows')\n\n// ============================================================================\n// Types and Interfaces\n// ============================================================================\n\nexport interface StartWorkflowOptions {\n workflowId: string\n version?: number // Default to latest enabled version\n initialContext?: Record<string, any>\n correlationKey?: string\n metadata?: {\n entityType?: string\n entityId?: string\n initiatedBy?: string\n labels?: Record<string, string>\n }\n tenantId: string\n organizationId: string\n}\n\nexport interface ExecutionContext {\n userId?: string\n dryRun?: boolean\n timeout?: number\n}\n\nexport interface ExecutionResult {\n status: WorkflowInstanceStatus\n currentStep: string\n context: Record<string, any>\n events: WorkflowEventSummary[]\n errors?: string[]\n executionTime: number\n}\n\nexport interface WorkflowEventSummary {\n eventType: string\n occurredAt: Date\n data?: any\n}\n\nexport class WorkflowExecutionError extends Error {\n constructor(\n message: string,\n public code: string,\n public details?: any\n ) {\n super(message)\n this.name = 'WorkflowExecutionError'\n }\n}\n\n// ============================================================================\n// Main Orchestration Functions\n// ============================================================================\n\n/**\n * Start a new workflow instance from a definition\n *\n * @param em - Entity manager for database operations\n * @param options - Workflow start options\n * @returns Created workflow instance\n * @throws WorkflowExecutionError if definition not found or validation fails\n */\nexport async function startWorkflow(\n em: EntityManager,\n options: StartWorkflowOptions\n): Promise<WorkflowInstance> {\n const {\n workflowId,\n version,\n initialContext = {},\n correlationKey,\n metadata,\n tenantId,\n organizationId,\n } = options\n\n // Find workflow definition\n const definition = await findWorkflowDefinition(em, {\n workflowId,\n version,\n tenantId,\n organizationId,\n })\n\n if (!definition) {\n throw new WorkflowExecutionError(\n `Workflow definition not found: ${workflowId}${version ? ` v${version}` : ''}`,\n 'DEFINITION_NOT_FOUND',\n { workflowId, version }\n )\n }\n\n if (!definition.enabled) {\n throw new WorkflowExecutionError(\n `Workflow definition is disabled: ${workflowId}`,\n 'DEFINITION_DISABLED',\n { workflowId, version: definition.version }\n )\n }\n\n // Validate definition has required steps\n const { steps, transitions } = definition.definition\n if (!steps || steps.length < 2) {\n throw new WorkflowExecutionError(\n 'Workflow definition must have at least START and END steps',\n 'INVALID_DEFINITION',\n { workflowId, stepsCount: steps?.length || 0 }\n )\n }\n\n if (!transitions || transitions.length < 1) {\n throw new WorkflowExecutionError(\n 'Workflow definition must have at least one transition',\n 'INVALID_DEFINITION',\n { workflowId, transitionsCount: transitions?.length || 0 }\n )\n }\n\n // Find START step\n const startStep = steps.find((s: any) => s.stepType === 'START')\n if (!startStep) {\n throw new WorkflowExecutionError(\n 'Workflow definition must have a START step',\n 'INVALID_DEFINITION',\n { workflowId }\n )\n }\n\n // Validate START step pre-conditions if defined\n if (startStep.preConditions && startStep.preConditions.length > 0) {\n const { validateWorkflowStart } = await import('./start-validator')\n\n const validationResult = await validateWorkflowStart(em, {\n workflowId,\n version: definition.version,\n context: initialContext,\n tenantId,\n organizationId,\n })\n\n if (!validationResult.canStart) {\n throw new WorkflowExecutionError(\n `Workflow start pre-conditions failed: ${validationResult.errors.map(e => e.message).join('; ')}`,\n 'START_PRE_CONDITIONS_FAILED',\n {\n workflowId,\n errors: validationResult.errors,\n validatedRules: validationResult.validatedRules,\n }\n )\n }\n }\n\n // Create workflow instance\n const now = new Date()\n const instance = em.create(WorkflowInstance, {\n definitionId: definition.id,\n workflowId: definition.workflowId,\n version: definition.version,\n status: 'RUNNING',\n currentStepId: startStep.stepId,\n context: initialContext,\n correlationKey,\n metadata,\n startedAt: now,\n retryCount: 0,\n tenantId,\n organizationId,\n createdAt: now,\n updatedAt: now,\n })\n\n await em.persist(instance).flush()\n\n // Log WORKFLOW_STARTED event\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n eventType: 'WORKFLOW_STARTED',\n eventData: {\n workflowId: instance.workflowId,\n version: instance.version,\n startStepId: startStep.stepId,\n initialContext,\n metadata,\n },\n userId: metadata?.initiatedBy,\n tenantId,\n organizationId,\n })\n\n return instance\n}\n\n/**\n * Execute a workflow instance\n *\n * Main execution loop that processes steps and transitions until:\n * - Workflow completes (reaches END step)\n * - Workflow waits (USER_TASK, SIGNAL, TIMER)\n * - Workflow fails (error occurs)\n * - Timeout is reached\n *\n * @param em - Entity manager\n * @param container - DI container (for activity execution and other services)\n * @param instanceId - Workflow instance ID\n * @param context - Execution context (userId, dryRun, timeout)\n * @returns Execution result with status and events\n */\nexport async function executeWorkflow(\n em: EntityManager,\n container: AwilixContainer,\n instanceId: string,\n context?: ExecutionContext\n): Promise<ExecutionResult> {\n const startTime = Date.now()\n const transactionalEm = em as EntityManager & {\n transactional?: <TResult>(\n callback: (trx: EntityManager) => Promise<TResult>,\n ) => Promise<TResult>\n }\n\n const runExecution = async (trx: EntityManager): Promise<ExecutionResult> => {\n const events: WorkflowEventSummary[] = []\n const errors: string[] = []\n\n try {\n const instance = await getWorkflowInstanceForExecution(trx, instanceId)\n if (!instance) {\n throw new WorkflowExecutionError(\n `Workflow instance not found: ${instanceId}`,\n 'INSTANCE_NOT_FOUND',\n { instanceId }\n )\n }\n\n if (instance.status === 'COMPLETED') {\n return {\n status: 'COMPLETED',\n currentStep: instance.currentStepId,\n context: instance.context,\n events: [],\n executionTime: 0,\n }\n }\n\n if (instance.status === 'CANCELLED') {\n throw new WorkflowExecutionError(\n 'Cannot execute cancelled workflow',\n 'WORKFLOW_CANCELLED',\n { instanceId, status: instance.status }\n )\n }\n\n const definition = await findDefinitionForInstance(trx, instance)\n\n if (!definition) {\n throw new WorkflowExecutionError(\n `Workflow definition not found: ${instance.definitionId}`,\n 'DEFINITION_NOT_FOUND',\n { definitionId: instance.definitionId }\n )\n }\n\n const maxIterations = 100\n let iterations = 0\n\n while (iterations < maxIterations) {\n iterations++\n\n const currentInstance = await getWorkflowInstanceForExecution(trx, instanceId, { refresh: iterations > 1 })\n if (!currentInstance) {\n throw new WorkflowExecutionError(\n 'Instance not found during execution',\n 'INSTANCE_NOT_FOUND',\n { instanceId }\n )\n }\n\n // Parallel execution: while the instance is FORKED, drive the branches.\n if (currentInstance.status === 'FORKED') {\n const { advanceBranches } = await import('./parallel-handler')\n const branchResult = await advanceBranches(trx, container, currentInstance, definition, {\n userId: context?.userId,\n })\n\n if (branchResult.outcome === 'joined') {\n // Instance resumed at the post-join step; continue single-token.\n continue\n }\n\n if (branchResult.outcome === 'failed') {\n errors.push(branchResult.error || 'Parallel branch failed')\n await completeWorkflow(trx, container, instanceId, 'FAILED', {\n error: branchResult.error || 'Parallel branch failed',\n })\n return {\n status: 'FAILED',\n currentStep: currentInstance.currentStepId,\n context: currentInstance.context,\n events,\n errors,\n executionTime: Date.now() - startTime,\n }\n }\n\n // 'waiting' \u2014 all branches paused for external resume (task/signal/timer/async).\n return {\n status: 'RUNNING',\n currentStep: currentInstance.currentStepId,\n context: currentInstance.context,\n events,\n executionTime: Date.now() - startTime,\n }\n }\n\n const currentStep = definition.definition.steps.find(\n (s: any) => s.stepId === currentInstance.currentStepId\n )\n\n if (currentStep?.stepType === 'END') {\n await completeWorkflow(trx, container, instanceId, 'COMPLETED')\n events.push({\n eventType: 'WORKFLOW_COMPLETED',\n occurredAt: new Date(),\n })\n\n return {\n status: 'COMPLETED',\n currentStep: currentInstance.currentStepId,\n context: currentInstance.context,\n events,\n executionTime: Date.now() - startTime,\n }\n }\n\n if (\n currentStep?.stepType === 'USER_TASK' ||\n currentStep?.stepType === 'WAIT_FOR_SIGNAL' ||\n currentStep?.stepType === 'WAIT_FOR_TIMER'\n ) {\n return {\n status: 'RUNNING',\n currentStep: currentInstance.currentStepId,\n context: currentInstance.context,\n events,\n executionTime: Date.now() - startTime,\n }\n }\n\n const transitions = definition.definition.transitions.filter(\n (t: any) =>\n t.fromStepId === currentInstance.currentStepId &&\n t.trigger === 'auto'\n )\n\n if (transitions.length === 0) {\n return {\n status: 'RUNNING',\n currentStep: currentInstance.currentStepId,\n context: currentInstance.context,\n events,\n executionTime: Date.now() - startTime,\n }\n }\n\n const transitionHandler = await import('./transition-handler')\n const evalContext: any = {\n workflowContext: currentInstance.context,\n userId: context?.userId,\n }\n\n const validTransitions = await transitionHandler.findValidTransitions(\n trx,\n currentInstance,\n currentInstance.currentStepId!,\n evalContext\n )\n\n const validAutoTransitions = validTransitions.filter(\n (vt) => vt.isValid && vt.transition?.trigger === 'auto'\n )\n\n if (validAutoTransitions.length === 0) {\n return {\n status: 'RUNNING',\n currentStep: currentInstance.currentStepId,\n context: currentInstance.context,\n events,\n executionTime: Date.now() - startTime,\n }\n }\n\n const selectedTransition = validAutoTransitions[0].transition\n\n try {\n const transitionResult = await transitionHandler.executeTransition(\n trx,\n container,\n currentInstance,\n selectedTransition.fromStepId,\n selectedTransition.toStepId,\n evalContext\n )\n\n if (!transitionResult.success) {\n const rejectionMessage = transitionResult.error || 'Transition failed'\n logger.error('Transition rejected', {\n instanceId: currentInstance.id,\n workflowId: currentInstance.workflowId,\n fromStepId: currentInstance.currentStepId,\n toStepId: selectedTransition.toStepId,\n err: rejectionMessage,\n })\n errors.push(rejectionMessage)\n\n await completeWorkflow(trx, container, instanceId, 'FAILED', {\n error: rejectionMessage,\n })\n events.push({\n eventType: 'WORKFLOW_FAILED',\n occurredAt: new Date(),\n })\n\n return {\n status: 'FAILED',\n currentStep: currentInstance.currentStepId,\n context: currentInstance.context,\n events,\n errors,\n executionTime: Date.now() - startTime,\n }\n }\n\n events.push({\n eventType: 'TRANSITION_EXECUTED',\n occurredAt: new Date(),\n data: {\n fromStepId: selectedTransition.fromStepId,\n toStepId: selectedTransition.toStepId,\n transitionId: selectedTransition.transitionId,\n },\n })\n\n if (transitionResult.pausedForActivities) {\n await logWorkflowEvent(trx, {\n workflowInstanceId: currentInstance.id,\n eventType: 'WORKFLOW_WAITING_FOR_ACTIVITIES',\n eventData: {\n pendingActivities: transitionResult.activitiesExecuted?.filter(a => a.async),\n pausedAtTransition: {\n fromStepId: selectedTransition.fromStepId,\n toStepId: selectedTransition.toStepId,\n },\n },\n tenantId: currentInstance.tenantId,\n organizationId: currentInstance.organizationId,\n })\n\n events.push({\n eventType: 'WORKFLOW_WAITING_FOR_ACTIVITIES',\n occurredAt: new Date(),\n data: {\n pendingActivities: transitionResult.activitiesExecuted?.filter(a => a.async),\n },\n })\n\n return {\n status: 'WAITING_FOR_ACTIVITIES',\n currentStep: currentInstance.currentStepId,\n context: currentInstance.context,\n events,\n executionTime: Date.now() - startTime,\n }\n }\n\n await trx.flush()\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error)\n logger.error('Transition execution failed', {\n instanceId: currentInstance.id,\n workflowId: currentInstance.workflowId,\n fromStepId: currentInstance.currentStepId,\n toStepId: selectedTransition.toStepId,\n err: error,\n })\n errors.push(errorMessage)\n\n events.push({\n eventType: 'TRANSITION_FAILED',\n occurredAt: new Date(),\n data: {\n transitionId: selectedTransition.transitionId,\n error: errorMessage,\n },\n })\n\n await completeWorkflow(trx, container, instanceId, 'FAILED', {\n error: errorMessage,\n details: error instanceof WorkflowExecutionError ? error.details : undefined,\n })\n events.push({\n eventType: 'WORKFLOW_FAILED',\n occurredAt: new Date(),\n })\n\n return {\n status: 'FAILED',\n currentStep: currentInstance.currentStepId,\n context: currentInstance.context,\n events,\n errors,\n executionTime: Date.now() - startTime,\n }\n }\n }\n\n errors.push('Maximum execution iterations reached - possible infinite loop')\n return {\n status: 'RUNNING',\n currentStep: instance.currentStepId,\n context: instance.context,\n events,\n errors,\n executionTime: Date.now() - startTime,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error)\n logger.error('Execution failed', { instanceId, err: error })\n errors.push(errorMessage)\n\n try {\n const instance = await getWorkflowInstanceForExecution(trx, instanceId, { refresh: true })\n if (instance && instance.status === 'RUNNING') {\n instance.status = 'FAILED'\n instance.errorMessage = errorMessage\n instance.errorDetails = error instanceof WorkflowExecutionError ? error.details : undefined\n instance.updatedAt = new Date()\n await trx.flush()\n\n await logWorkflowEvent(trx, {\n workflowInstanceId: instanceId,\n eventType: 'WORKFLOW_FAILED',\n eventData: { error: errorMessage },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n }\n } catch (updateError) {\n logger.error('Failed to update instance with error state', { instanceId, err: updateError })\n }\n\n throw error\n }\n }\n\n return typeof transactionalEm.transactional === 'function'\n ? transactionalEm.transactional((trx) => runExecution(trx))\n : runExecution(em)\n}\n\n/**\n * Complete a workflow instance with final status\n *\n * @param em - Entity manager\n * @param container\n * @param instanceId - Workflow instance ID\n * @param status - Final status (COMPLETED, FAILED, CANCELLED)\n * @param result - Optional result data\n */\nexport async function completeWorkflow(\n em: EntityManager,\n container: AwilixContainer,\n instanceId: string,\n status: 'COMPLETED' | 'FAILED' | 'CANCELLED',\n result?: any\n): Promise<void> {\n const instance = await getWorkflowInstance(em, instanceId)\n if (!instance) {\n throw new WorkflowExecutionError(\n `Workflow instance not found: ${instanceId}`,\n 'INSTANCE_NOT_FOUND',\n { instanceId }\n )\n }\n\n // Trigger compensation if workflow failed and has compensatable activities (Phase 8.2)\n if (status === 'FAILED') {\n const definition = await findDefinitionForInstance(em, instance)\n\n if (definition && checkIfCompensationNeeded(definition)) {\n try {\n\n // Set error message before compensation\n if (result?.error) {\n instance.errorMessage = result.error\n instance.errorDetails = result.details\n await em.flush()\n }\n\n const compensationResult = await compensateWorkflow(\n em,\n container,\n instance,\n definition,\n {\n continueOnError: true // Best-effort compensation\n }\n )\n\n logger.info('Compensation finished', {\n status: compensationResult.status,\n compensatedActivities: compensationResult.compensatedActivities,\n totalActivities: compensationResult.totalActivities,\n })\n\n // Note: instance status already updated by compensateWorkflow\n // It will be COMPENSATED or remain FAILED\n return\n } catch (error: any) {\n logger.error('Compensation failed with exception', { err: error })\n // Continue to mark workflow as failed\n }\n }\n }\n\n // Original completion logic (no compensation needed or status is COMPLETED/CANCELLED)\n const now = new Date()\n instance.status = status\n instance.updatedAt = now\n\n switch (status) {\n case 'COMPLETED':\n instance.completedAt = now\n if (result) {\n instance.context = { ...instance.context, __result: result }\n }\n break\n\n case 'FAILED':\n instance.completedAt = now\n if (result?.error) {\n instance.errorMessage = result.error\n instance.errorDetails = result.details\n }\n break\n\n case 'CANCELLED':\n instance.cancelledAt = now\n break\n }\n\n await em.flush()\n\n // Log completion event\n const eventType =\n status === 'COMPLETED'\n ? 'WORKFLOW_COMPLETED'\n : status === 'FAILED'\n ? 'WORKFLOW_FAILED'\n : 'WORKFLOW_CANCELLED'\n\n await logWorkflowEvent(em, {\n workflowInstanceId: instanceId,\n eventType,\n eventData: result || {},\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n}\n\n/**\n * Resume workflow after async activities complete\n *\n * Called by the activity worker after all async activities finish execution.\n * Checks if all activities are done, merges outputs into context, and resumes execution.\n *\n * @param em - Entity manager\n * @param container - DI container\n * @param instanceId - Workflow instance ID\n */\nexport async function resumeWorkflowAfterActivities(\n em: EntityManager,\n container: AwilixContainer,\n instanceId: string,\n branchInstanceId?: string | null\n): Promise<void> {\n const transactionalEm = em as EntityManager & {\n transactional?: <TResult>(callback: (trx: EntityManager) => Promise<TResult>) => Promise<TResult>\n }\n\n // Branch-scoped async resume: the instance is FORKED and the branch (not the\n // instance) is WAITING_FOR_ACTIVITIES. Resume just that branch, then let the\n // interleaved loop continue. Missing branchInstanceId \u2192 legacy instance path.\n if (branchInstanceId) {\n const { resumeBranchAfterActivities } = await import('./parallel-handler')\n const branchResume = typeof transactionalEm.transactional === 'function'\n ? await transactionalEm.transactional((trx) => resumeBranchAfterActivities(trx, container, instanceId, branchInstanceId))\n : await resumeBranchAfterActivities(em, container, instanceId, branchInstanceId)\n if (branchResume.continueExecution) {\n await executeWorkflow(em, container, instanceId)\n }\n return\n }\n\n const runResume = async (trx: EntityManager): Promise<{ continueExecution: boolean }> => {\n const instance = await trx.findOne(WorkflowInstance, {\n id: instanceId,\n status: 'WAITING_FOR_ACTIVITIES',\n }, { lockMode: LockMode.PESSIMISTIC_WRITE })\n\n if (!instance) {\n throw new Error('Workflow instance not waiting for activities')\n }\n\n const pendingJobIds = (instance.context._pendingAsyncActivities as any[]) || []\n\n const completedActivities = await trx.count(WorkflowEvent, {\n workflowInstanceId: instanceId,\n eventType: 'ACTIVITY_COMPLETED',\n eventData: { async: true },\n })\n\n const failedActivities = await trx.count(WorkflowEvent, {\n workflowInstanceId: instanceId,\n eventType: 'ACTIVITY_FAILED',\n eventData: { async: true },\n })\n\n const totalProcessed = completedActivities + failedActivities\n\n if (totalProcessed < pendingJobIds.length) {\n throw new Error('Activities still pending')\n }\n\n if (failedActivities > 0) {\n const failedEvents = await trx.find(WorkflowEvent, {\n workflowInstanceId: instanceId,\n eventType: 'ACTIVITY_FAILED',\n eventData: { async: true },\n })\n\n instance.status = 'FAILED'\n instance.errorMessage = `${failedActivities} async activities failed`\n instance.errorDetails = {\n failedActivities: failedEvents.map(e => ({\n activityId: e.eventData.activityId,\n error: e.eventData.error,\n jobId: e.eventData.jobId,\n })),\n }\n await trx.flush()\n\n await logWorkflowEvent(trx, {\n workflowInstanceId: instanceId,\n eventType: 'WORKFLOW_FAILED',\n eventData: {\n reason: 'Async activities failed',\n failedActivities: instance.errorDetails.failedActivities,\n },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n\n return { continueExecution: false }\n }\n\n const completedEvents = await trx.find(WorkflowEvent, {\n workflowInstanceId: instanceId,\n eventType: 'ACTIVITY_COMPLETED',\n eventData: { async: true },\n })\n\n for (const event of completedEvents) {\n if (event.eventData.output) {\n instance.context = {\n ...instance.context,\n [`${event.eventData.activityId}_result`]: event.eventData.output,\n }\n }\n }\n\n delete instance.context._pendingAsyncActivities\n\n const pendingTransition = instance.pendingTransition\n\n if (!pendingTransition) {\n logger.warn('No pending transition found during resume')\n instance.status = 'RUNNING'\n await trx.flush()\n\n await logWorkflowEvent(trx, {\n workflowInstanceId: instanceId,\n eventType: 'WORKFLOW_RESUMED',\n eventData: {\n reason: 'All async activities completed',\n completedActivities: completedActivities,\n },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n\n return { continueExecution: true }\n }\n\n logger.debug('Completing pending transition', {\n toStepId: pendingTransition.toStepId,\n fromStepId: instance.currentStepId,\n })\n\n const definition = await findDefinitionForInstance(trx, instance)\n if (!definition) {\n throw new WorkflowExecutionError(\n `Workflow definition not found: ${instance.definitionId}`,\n 'DEFINITION_NOT_FOUND',\n { definitionId: instance.definitionId }\n )\n }\n\n const step = definition.definition.steps.find(s => s.stepId === pendingTransition.toStepId)\n\n instance.currentStepId = pendingTransition.toStepId\n instance.status = 'RUNNING'\n instance.pendingTransition = null\n instance.updatedAt = new Date()\n await trx.flush()\n\n await logWorkflowEvent(trx, {\n workflowInstanceId: instance.id,\n eventType: 'STEP_ENTERED',\n eventData: {\n stepId: pendingTransition.toStepId,\n stepName: step?.stepName,\n stepType: step?.stepType,\n },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n\n await logWorkflowEvent(trx, {\n workflowInstanceId: instanceId,\n eventType: 'WORKFLOW_RESUMED',\n eventData: {\n reason: 'Async activities completed, resuming pending transition',\n completedActivities: completedActivities,\n completedTransitionTo: pendingTransition.toStepId,\n },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n\n const { executeStep } = await import('./step-handler')\n await executeStep(\n trx,\n instance,\n pendingTransition.toStepId,\n {\n workflowContext: instance.context || {},\n userId: undefined,\n },\n container\n )\n\n return { continueExecution: true }\n }\n\n const resumeResult = typeof transactionalEm.transactional === 'function'\n ? await transactionalEm.transactional((trx) => runResume(trx))\n : await runResume(em)\n\n if (resumeResult.continueExecution) {\n await executeWorkflow(em, container, instanceId)\n }\n}\n\n/**\n * Check if workflow definition has any compensatable activities\n */\nfunction checkIfCompensationNeeded(definition: WorkflowDefinition): boolean {\n // Check if any activities have compensation defined\n for (const transition of definition.definition.transitions) {\n if (transition.activities) {\n for (const activity of transition.activities) {\n if (activity.compensation?.activityId) {\n return true\n }\n }\n }\n }\n\n // Check root-level activities (legacy)\n if (definition.definition.activities) {\n for (const activity of definition.definition.activities) {\n if (activity.compensation?.activityId) {\n return true\n }\n }\n }\n\n return false\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Get workflow instance by ID\n *\n * @param em - Entity manager\n * @param instanceId - Workflow instance ID\n * @returns Workflow instance or null if not found\n */\nexport async function getWorkflowInstance(\n em: EntityManager,\n instanceId: string\n): Promise<WorkflowInstance | null> {\n return em.findOne(WorkflowInstance, { id: instanceId })\n}\n\nasync function getWorkflowInstanceForExecution(\n em: EntityManager,\n instanceId: string,\n options?: { refresh?: boolean }\n): Promise<WorkflowInstance | null> {\n return em.findOne(\n WorkflowInstance,\n { id: instanceId },\n {\n lockMode: LockMode.PESSIMISTIC_WRITE,\n ...(options?.refresh ? { refresh: true } : {}),\n }\n )\n}\n\n/**\n * Update workflow context with new data\n *\n * @param em - Entity manager\n * @param instanceId - Workflow instance ID\n * @param updates - Context updates (merged with existing context)\n */\nexport async function updateWorkflowContext(\n em: EntityManager,\n instanceId: string,\n updates: Record<string, any>\n): Promise<void> {\n const instance = await getWorkflowInstance(em, instanceId)\n if (!instance) {\n throw new WorkflowExecutionError(\n `Workflow instance not found: ${instanceId}`,\n 'INSTANCE_NOT_FOUND',\n { instanceId }\n )\n }\n\n instance.context = {\n ...instance.context,\n ...updates,\n }\n instance.updatedAt = new Date()\n\n await em.flush()\n}\n\n// findWorkflowDefinition is imported from ./find-definition\n\n/**\n * Log workflow event to event sourcing table\n *\n * @param em - Entity manager\n * @param event - Event data\n */\nasync function logWorkflowEvent(\n em: EntityManager,\n event: {\n workflowInstanceId: string\n stepInstanceId?: string\n eventType: string\n eventData: any\n userId?: string\n tenantId: string\n organizationId: string\n }\n): Promise<WorkflowEvent> {\n const workflowEvent = em.create(WorkflowEvent, {\n ...event,\n occurredAt: new Date(),\n })\n\n await em.persist(workflowEvent).flush()\n return workflowEvent\n}\n"],
5
- "mappings": "AAYA,SAAwB,gBAAgB;AAExC;AAAA,EAEE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,0BAA0B;AACnC,SAAS,wBAAwB,iCAAiC;AAClE,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AA0ChC,MAAM,+BAA+B,MAAM;AAAA,EAChD,YACE,SACO,MACA,SACP;AACA,UAAM,OAAO;AAHN;AACA;AAGP,SAAK,OAAO;AAAA,EACd;AACF;AAcA,eAAsB,cACpB,IACA,SAC2B;AAC3B,QAAM;AAAA,IACJ;AAAA,IACA;AAAA,IACA,iBAAiB,CAAC;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAGJ,QAAM,aAAa,MAAM,uBAAuB,IAAI;AAAA,IAClD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AAED,MAAI,CAAC,YAAY;AACf,UAAM,IAAI;AAAA,MACR,kCAAkC,UAAU,GAAG,UAAU,KAAK,OAAO,KAAK,EAAE;AAAA,MAC5E;AAAA,MACA,EAAE,YAAY,QAAQ;AAAA,IACxB;AAAA,EACF;AAEA,MAAI,CAAC,WAAW,SAAS;AACvB,UAAM,IAAI;AAAA,MACR,oCAAoC,UAAU;AAAA,MAC9C;AAAA,MACA,EAAE,YAAY,SAAS,WAAW,QAAQ;AAAA,IAC5C;AAAA,EACF;AAGA,QAAM,EAAE,OAAO,YAAY,IAAI,WAAW;AAC1C,MAAI,CAAC,SAAS,MAAM,SAAS,GAAG;AAC9B,UAAM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AgB,GAAG,OAAO,eAAe;AAAA,IAC7C,GAAG;AAAA,IACH,YAAY,oBAAI,KAAK;AAAA,EACvB,CAAC;AAED,QAAM,GAAG,QAAQ,aAAa,EAAE,MAAM;AACtC,SAAO;AACT;",
4
+ "sourcesContent": ["/**\n * Workflows Module - Workflow Executor Service\n *\n * Main orchestrator for workflow execution. Handles workflow lifecycle:\n * - Starting workflow instances from definitions\n * - Executing workflow steps and transitions\n * - Completing workflows with final status\n * - Triggering compensation on failure\n *\n * Functional API (no classes) following Open Mercato conventions.\n */\n\nimport { EntityManager, LockMode } from '@mikro-orm/core'\nimport type { AwilixContainer } from 'awilix'\nimport {\n WorkflowDefinition,\n WorkflowInstance,\n WorkflowEvent,\n type WorkflowInstanceStatus,\n} from '../data/entities'\nimport { compensateWorkflow } from './compensation-handler'\nimport { findWorkflowDefinition, findDefinitionForInstance } from './find-definition'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('workflows')\n\n// ============================================================================\n// Types and Interfaces\n// ============================================================================\n\nexport interface StartWorkflowOptions {\n workflowId: string\n version?: number // Default to latest enabled version\n initialContext?: Record<string, any>\n correlationKey?: string\n metadata?: {\n entityType?: string\n entityId?: string\n initiatedBy?: string\n labels?: Record<string, string>\n }\n tenantId: string\n organizationId: string\n}\n\nexport interface ExecutionContext {\n userId?: string\n dryRun?: boolean\n timeout?: number\n}\n\nexport interface ExecutionResult {\n status: WorkflowInstanceStatus\n currentStep: string\n context: Record<string, any>\n events: WorkflowEventSummary[]\n errors?: string[]\n executionTime: number\n}\n\nexport interface WorkflowEventSummary {\n eventType: string\n occurredAt: Date\n data?: any\n}\n\nfunction normalizeWorkflowUserId(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const trimmed = value.trim()\n if (!trimmed || trimmed.startsWith('trigger:')) return null\n return trimmed\n}\n\nfunction resolveWorkflowExecutionUserId(\n context: ExecutionContext | undefined,\n instance: WorkflowInstance,\n): string | undefined {\n return (\n normalizeWorkflowUserId(context?.userId) ??\n normalizeWorkflowUserId(instance.metadata?.initiatedBy) ??\n undefined\n )\n}\n\nexport class WorkflowExecutionError extends Error {\n constructor(\n message: string,\n public code: string,\n public details?: any\n ) {\n super(message)\n this.name = 'WorkflowExecutionError'\n }\n}\n\n// ============================================================================\n// Main Orchestration Functions\n// ============================================================================\n\n/**\n * Start a new workflow instance from a definition\n *\n * @param em - Entity manager for database operations\n * @param options - Workflow start options\n * @returns Created workflow instance\n * @throws WorkflowExecutionError if definition not found or validation fails\n */\nexport async function startWorkflow(\n em: EntityManager,\n options: StartWorkflowOptions\n): Promise<WorkflowInstance> {\n const {\n workflowId,\n version,\n initialContext = {},\n correlationKey,\n metadata,\n tenantId,\n organizationId,\n } = options\n\n // Find workflow definition\n const definition = await findWorkflowDefinition(em, {\n workflowId,\n version,\n tenantId,\n organizationId,\n })\n\n if (!definition) {\n throw new WorkflowExecutionError(\n `Workflow definition not found: ${workflowId}${version ? ` v${version}` : ''}`,\n 'DEFINITION_NOT_FOUND',\n { workflowId, version }\n )\n }\n\n if (!definition.enabled) {\n throw new WorkflowExecutionError(\n `Workflow definition is disabled: ${workflowId}`,\n 'DEFINITION_DISABLED',\n { workflowId, version: definition.version }\n )\n }\n\n // Validate definition has required steps\n const { steps, transitions } = definition.definition\n if (!steps || steps.length < 2) {\n throw new WorkflowExecutionError(\n 'Workflow definition must have at least START and END steps',\n 'INVALID_DEFINITION',\n { workflowId, stepsCount: steps?.length || 0 }\n )\n }\n\n if (!transitions || transitions.length < 1) {\n throw new WorkflowExecutionError(\n 'Workflow definition must have at least one transition',\n 'INVALID_DEFINITION',\n { workflowId, transitionsCount: transitions?.length || 0 }\n )\n }\n\n // Find START step\n const startStep = steps.find((s: any) => s.stepType === 'START')\n if (!startStep) {\n throw new WorkflowExecutionError(\n 'Workflow definition must have a START step',\n 'INVALID_DEFINITION',\n { workflowId }\n )\n }\n\n // Validate START step pre-conditions if defined\n if (startStep.preConditions && startStep.preConditions.length > 0) {\n const { validateWorkflowStart } = await import('./start-validator')\n\n const validationResult = await validateWorkflowStart(em, {\n workflowId,\n version: definition.version,\n context: initialContext,\n tenantId,\n organizationId,\n })\n\n if (!validationResult.canStart) {\n throw new WorkflowExecutionError(\n `Workflow start pre-conditions failed: ${validationResult.errors.map(e => e.message).join('; ')}`,\n 'START_PRE_CONDITIONS_FAILED',\n {\n workflowId,\n errors: validationResult.errors,\n validatedRules: validationResult.validatedRules,\n }\n )\n }\n }\n\n // Create workflow instance\n const now = new Date()\n const instance = em.create(WorkflowInstance, {\n definitionId: definition.id,\n workflowId: definition.workflowId,\n version: definition.version,\n status: 'RUNNING',\n currentStepId: startStep.stepId,\n context: initialContext,\n correlationKey,\n metadata,\n startedAt: now,\n retryCount: 0,\n tenantId,\n organizationId,\n createdAt: now,\n updatedAt: now,\n })\n\n await em.persist(instance).flush()\n\n // Log WORKFLOW_STARTED event\n await logWorkflowEvent(em, {\n workflowInstanceId: instance.id,\n eventType: 'WORKFLOW_STARTED',\n eventData: {\n workflowId: instance.workflowId,\n version: instance.version,\n startStepId: startStep.stepId,\n initialContext,\n metadata,\n },\n userId: metadata?.initiatedBy,\n tenantId,\n organizationId,\n })\n\n return instance\n}\n\n/**\n * Execute a workflow instance\n *\n * Main execution loop that processes steps and transitions until:\n * - Workflow completes (reaches END step)\n * - Workflow waits (USER_TASK, SIGNAL, TIMER)\n * - Workflow fails (error occurs)\n * - Timeout is reached\n *\n * @param em - Entity manager\n * @param container - DI container (for activity execution and other services)\n * @param instanceId - Workflow instance ID\n * @param context - Execution context (userId, dryRun, timeout)\n * @returns Execution result with status and events\n */\nexport async function executeWorkflow(\n em: EntityManager,\n container: AwilixContainer,\n instanceId: string,\n context?: ExecutionContext\n): Promise<ExecutionResult> {\n const startTime = Date.now()\n const transactionalEm = em as EntityManager & {\n transactional?: <TResult>(\n callback: (trx: EntityManager) => Promise<TResult>,\n ) => Promise<TResult>\n }\n\n const runExecution = async (trx: EntityManager): Promise<ExecutionResult> => {\n const events: WorkflowEventSummary[] = []\n const errors: string[] = []\n\n try {\n const instance = await getWorkflowInstanceForExecution(trx, instanceId)\n if (!instance) {\n throw new WorkflowExecutionError(\n `Workflow instance not found: ${instanceId}`,\n 'INSTANCE_NOT_FOUND',\n { instanceId }\n )\n }\n\n if (instance.status === 'COMPLETED') {\n return {\n status: 'COMPLETED',\n currentStep: instance.currentStepId,\n context: instance.context,\n events: [],\n executionTime: 0,\n }\n }\n\n if (instance.status === 'CANCELLED') {\n throw new WorkflowExecutionError(\n 'Cannot execute cancelled workflow',\n 'WORKFLOW_CANCELLED',\n { instanceId, status: instance.status }\n )\n }\n\n const definition = await findDefinitionForInstance(trx, instance)\n\n if (!definition) {\n throw new WorkflowExecutionError(\n `Workflow definition not found: ${instance.definitionId}`,\n 'DEFINITION_NOT_FOUND',\n { definitionId: instance.definitionId }\n )\n }\n\n const maxIterations = 100\n let iterations = 0\n const executionUserId = resolveWorkflowExecutionUserId(context, instance)\n\n while (iterations < maxIterations) {\n iterations++\n\n const currentInstance = await getWorkflowInstanceForExecution(trx, instanceId, { refresh: iterations > 1 })\n if (!currentInstance) {\n throw new WorkflowExecutionError(\n 'Instance not found during execution',\n 'INSTANCE_NOT_FOUND',\n { instanceId }\n )\n }\n\n // Parallel execution: while the instance is FORKED, drive the branches.\n if (currentInstance.status === 'FORKED') {\n const { advanceBranches } = await import('./parallel-handler')\n const branchResult = await advanceBranches(trx, container, currentInstance, definition, {\n userId: executionUserId,\n })\n\n if (branchResult.outcome === 'joined') {\n // Instance resumed at the post-join step; continue single-token.\n continue\n }\n\n if (branchResult.outcome === 'failed') {\n errors.push(branchResult.error || 'Parallel branch failed')\n await completeWorkflow(trx, container, instanceId, 'FAILED', {\n error: branchResult.error || 'Parallel branch failed',\n })\n return {\n status: 'FAILED',\n currentStep: currentInstance.currentStepId,\n context: currentInstance.context,\n events,\n errors,\n executionTime: Date.now() - startTime,\n }\n }\n\n // 'waiting' \u2014 all branches paused for external resume (task/signal/timer/async).\n return {\n status: 'RUNNING',\n currentStep: currentInstance.currentStepId,\n context: currentInstance.context,\n events,\n executionTime: Date.now() - startTime,\n }\n }\n\n const currentStep = definition.definition.steps.find(\n (s: any) => s.stepId === currentInstance.currentStepId\n )\n\n if (currentStep?.stepType === 'END') {\n await completeWorkflow(trx, container, instanceId, 'COMPLETED')\n events.push({\n eventType: 'WORKFLOW_COMPLETED',\n occurredAt: new Date(),\n })\n\n return {\n status: 'COMPLETED',\n currentStep: currentInstance.currentStepId,\n context: currentInstance.context,\n events,\n executionTime: Date.now() - startTime,\n }\n }\n\n if (\n currentStep?.stepType === 'USER_TASK' ||\n currentStep?.stepType === 'WAIT_FOR_SIGNAL' ||\n currentStep?.stepType === 'WAIT_FOR_TIMER'\n ) {\n return {\n status: 'RUNNING',\n currentStep: currentInstance.currentStepId,\n context: currentInstance.context,\n events,\n executionTime: Date.now() - startTime,\n }\n }\n\n const transitions = definition.definition.transitions.filter(\n (t: any) =>\n t.fromStepId === currentInstance.currentStepId &&\n t.trigger === 'auto'\n )\n\n if (transitions.length === 0) {\n return {\n status: 'RUNNING',\n currentStep: currentInstance.currentStepId,\n context: currentInstance.context,\n events,\n executionTime: Date.now() - startTime,\n }\n }\n\n const transitionHandler = await import('./transition-handler')\n const evalContext: any = {\n workflowContext: currentInstance.context,\n userId: executionUserId,\n }\n\n const validTransitions = await transitionHandler.findValidTransitions(\n trx,\n currentInstance,\n currentInstance.currentStepId!,\n evalContext\n )\n\n const validAutoTransitions = validTransitions.filter(\n (vt) => vt.isValid && vt.transition?.trigger === 'auto'\n )\n\n if (validAutoTransitions.length === 0) {\n return {\n status: 'RUNNING',\n currentStep: currentInstance.currentStepId,\n context: currentInstance.context,\n events,\n executionTime: Date.now() - startTime,\n }\n }\n\n const selectedTransition = validAutoTransitions[0].transition\n\n try {\n const transitionResult = await transitionHandler.executeTransition(\n trx,\n container,\n currentInstance,\n selectedTransition.fromStepId,\n selectedTransition.toStepId,\n evalContext\n )\n\n if (!transitionResult.success) {\n const rejectionMessage = transitionResult.error || 'Transition failed'\n logger.error('Transition rejected', {\n instanceId: currentInstance.id,\n workflowId: currentInstance.workflowId,\n fromStepId: currentInstance.currentStepId,\n toStepId: selectedTransition.toStepId,\n err: rejectionMessage,\n })\n errors.push(rejectionMessage)\n\n await completeWorkflow(trx, container, instanceId, 'FAILED', {\n error: rejectionMessage,\n })\n events.push({\n eventType: 'WORKFLOW_FAILED',\n occurredAt: new Date(),\n })\n\n return {\n status: 'FAILED',\n currentStep: currentInstance.currentStepId,\n context: currentInstance.context,\n events,\n errors,\n executionTime: Date.now() - startTime,\n }\n }\n\n events.push({\n eventType: 'TRANSITION_EXECUTED',\n occurredAt: new Date(),\n data: {\n fromStepId: selectedTransition.fromStepId,\n toStepId: selectedTransition.toStepId,\n transitionId: selectedTransition.transitionId,\n },\n })\n\n if (transitionResult.pausedForActivities) {\n await logWorkflowEvent(trx, {\n workflowInstanceId: currentInstance.id,\n eventType: 'WORKFLOW_WAITING_FOR_ACTIVITIES',\n eventData: {\n pendingActivities: transitionResult.activitiesExecuted?.filter(a => a.async),\n pausedAtTransition: {\n fromStepId: selectedTransition.fromStepId,\n toStepId: selectedTransition.toStepId,\n },\n },\n tenantId: currentInstance.tenantId,\n organizationId: currentInstance.organizationId,\n })\n\n events.push({\n eventType: 'WORKFLOW_WAITING_FOR_ACTIVITIES',\n occurredAt: new Date(),\n data: {\n pendingActivities: transitionResult.activitiesExecuted?.filter(a => a.async),\n },\n })\n\n return {\n status: 'WAITING_FOR_ACTIVITIES',\n currentStep: currentInstance.currentStepId,\n context: currentInstance.context,\n events,\n executionTime: Date.now() - startTime,\n }\n }\n\n await trx.flush()\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error)\n logger.error('Transition execution failed', {\n instanceId: currentInstance.id,\n workflowId: currentInstance.workflowId,\n fromStepId: currentInstance.currentStepId,\n toStepId: selectedTransition.toStepId,\n err: error,\n })\n errors.push(errorMessage)\n\n events.push({\n eventType: 'TRANSITION_FAILED',\n occurredAt: new Date(),\n data: {\n transitionId: selectedTransition.transitionId,\n error: errorMessage,\n },\n })\n\n await completeWorkflow(trx, container, instanceId, 'FAILED', {\n error: errorMessage,\n details: error instanceof WorkflowExecutionError ? error.details : undefined,\n })\n events.push({\n eventType: 'WORKFLOW_FAILED',\n occurredAt: new Date(),\n })\n\n return {\n status: 'FAILED',\n currentStep: currentInstance.currentStepId,\n context: currentInstance.context,\n events,\n errors,\n executionTime: Date.now() - startTime,\n }\n }\n }\n\n errors.push('Maximum execution iterations reached - possible infinite loop')\n return {\n status: 'RUNNING',\n currentStep: instance.currentStepId,\n context: instance.context,\n events,\n errors,\n executionTime: Date.now() - startTime,\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error)\n logger.error('Execution failed', { instanceId, err: error })\n errors.push(errorMessage)\n\n try {\n const instance = await getWorkflowInstanceForExecution(trx, instanceId, { refresh: true })\n if (instance && instance.status === 'RUNNING') {\n instance.status = 'FAILED'\n instance.errorMessage = errorMessage\n instance.errorDetails = error instanceof WorkflowExecutionError ? error.details : undefined\n instance.updatedAt = new Date()\n await trx.flush()\n\n await logWorkflowEvent(trx, {\n workflowInstanceId: instanceId,\n eventType: 'WORKFLOW_FAILED',\n eventData: { error: errorMessage },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n }\n } catch (updateError) {\n logger.error('Failed to update instance with error state', { instanceId, err: updateError })\n }\n\n throw error\n }\n }\n\n return typeof transactionalEm.transactional === 'function'\n ? transactionalEm.transactional((trx) => runExecution(trx))\n : runExecution(em)\n}\n\n/**\n * Complete a workflow instance with final status\n *\n * @param em - Entity manager\n * @param container\n * @param instanceId - Workflow instance ID\n * @param status - Final status (COMPLETED, FAILED, CANCELLED)\n * @param result - Optional result data\n */\nexport async function completeWorkflow(\n em: EntityManager,\n container: AwilixContainer,\n instanceId: string,\n status: 'COMPLETED' | 'FAILED' | 'CANCELLED',\n result?: any\n): Promise<void> {\n const instance = await getWorkflowInstance(em, instanceId)\n if (!instance) {\n throw new WorkflowExecutionError(\n `Workflow instance not found: ${instanceId}`,\n 'INSTANCE_NOT_FOUND',\n { instanceId }\n )\n }\n\n // Trigger compensation if workflow failed and has compensatable activities (Phase 8.2)\n if (status === 'FAILED') {\n const definition = await findDefinitionForInstance(em, instance)\n\n if (definition && checkIfCompensationNeeded(definition)) {\n try {\n\n // Set error message before compensation\n if (result?.error) {\n instance.errorMessage = result.error\n instance.errorDetails = result.details\n await em.flush()\n }\n\n const compensationResult = await compensateWorkflow(\n em,\n container,\n instance,\n definition,\n {\n continueOnError: true // Best-effort compensation\n }\n )\n\n logger.info('Compensation finished', {\n status: compensationResult.status,\n compensatedActivities: compensationResult.compensatedActivities,\n totalActivities: compensationResult.totalActivities,\n })\n\n // Note: instance status already updated by compensateWorkflow\n // It will be COMPENSATED or remain FAILED\n return\n } catch (error: any) {\n logger.error('Compensation failed with exception', { err: error })\n // Continue to mark workflow as failed\n }\n }\n }\n\n // Original completion logic (no compensation needed or status is COMPLETED/CANCELLED)\n const now = new Date()\n instance.status = status\n instance.updatedAt = now\n\n switch (status) {\n case 'COMPLETED':\n instance.completedAt = now\n if (result) {\n instance.context = { ...instance.context, __result: result }\n }\n break\n\n case 'FAILED':\n instance.completedAt = now\n if (result?.error) {\n instance.errorMessage = result.error\n instance.errorDetails = result.details\n }\n break\n\n case 'CANCELLED':\n instance.cancelledAt = now\n break\n }\n\n await em.flush()\n\n // Log completion event\n const eventType =\n status === 'COMPLETED'\n ? 'WORKFLOW_COMPLETED'\n : status === 'FAILED'\n ? 'WORKFLOW_FAILED'\n : 'WORKFLOW_CANCELLED'\n\n await logWorkflowEvent(em, {\n workflowInstanceId: instanceId,\n eventType,\n eventData: result || {},\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n}\n\n/**\n * Resume workflow after async activities complete\n *\n * Called by the activity worker after all async activities finish execution.\n * Checks if all activities are done, merges outputs into context, and resumes execution.\n *\n * @param em - Entity manager\n * @param container - DI container\n * @param instanceId - Workflow instance ID\n */\nexport async function resumeWorkflowAfterActivities(\n em: EntityManager,\n container: AwilixContainer,\n instanceId: string,\n branchInstanceId?: string | null\n): Promise<void> {\n const transactionalEm = em as EntityManager & {\n transactional?: <TResult>(callback: (trx: EntityManager) => Promise<TResult>) => Promise<TResult>\n }\n\n // Branch-scoped async resume: the instance is FORKED and the branch (not the\n // instance) is WAITING_FOR_ACTIVITIES. Resume just that branch, then let the\n // interleaved loop continue. Missing branchInstanceId \u2192 legacy instance path.\n if (branchInstanceId) {\n const { resumeBranchAfterActivities } = await import('./parallel-handler')\n const branchResume = typeof transactionalEm.transactional === 'function'\n ? await transactionalEm.transactional((trx) => resumeBranchAfterActivities(trx, container, instanceId, branchInstanceId))\n : await resumeBranchAfterActivities(em, container, instanceId, branchInstanceId)\n if (branchResume.continueExecution) {\n await executeWorkflow(em, container, instanceId)\n }\n return\n }\n\n const runResume = async (trx: EntityManager): Promise<{ continueExecution: boolean }> => {\n const instance = await trx.findOne(WorkflowInstance, {\n id: instanceId,\n status: 'WAITING_FOR_ACTIVITIES',\n }, { lockMode: LockMode.PESSIMISTIC_WRITE })\n\n if (!instance) {\n throw new Error('Workflow instance not waiting for activities')\n }\n\n const pendingJobIds = (instance.context._pendingAsyncActivities as any[]) || []\n\n const completedActivities = await trx.count(WorkflowEvent, {\n workflowInstanceId: instanceId,\n eventType: 'ACTIVITY_COMPLETED',\n eventData: { async: true },\n })\n\n const failedActivities = await trx.count(WorkflowEvent, {\n workflowInstanceId: instanceId,\n eventType: 'ACTIVITY_FAILED',\n eventData: { async: true },\n })\n\n const totalProcessed = completedActivities + failedActivities\n\n if (totalProcessed < pendingJobIds.length) {\n throw new Error('Activities still pending')\n }\n\n if (failedActivities > 0) {\n const failedEvents = await trx.find(WorkflowEvent, {\n workflowInstanceId: instanceId,\n eventType: 'ACTIVITY_FAILED',\n eventData: { async: true },\n })\n\n instance.status = 'FAILED'\n instance.errorMessage = `${failedActivities} async activities failed`\n instance.errorDetails = {\n failedActivities: failedEvents.map(e => ({\n activityId: e.eventData.activityId,\n error: e.eventData.error,\n jobId: e.eventData.jobId,\n })),\n }\n await trx.flush()\n\n await logWorkflowEvent(trx, {\n workflowInstanceId: instanceId,\n eventType: 'WORKFLOW_FAILED',\n eventData: {\n reason: 'Async activities failed',\n failedActivities: instance.errorDetails.failedActivities,\n },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n\n return { continueExecution: false }\n }\n\n const completedEvents = await trx.find(WorkflowEvent, {\n workflowInstanceId: instanceId,\n eventType: 'ACTIVITY_COMPLETED',\n eventData: { async: true },\n })\n\n for (const event of completedEvents) {\n if (event.eventData.output) {\n instance.context = {\n ...instance.context,\n [`${event.eventData.activityId}_result`]: event.eventData.output,\n }\n }\n }\n\n delete instance.context._pendingAsyncActivities\n\n const pendingTransition = instance.pendingTransition\n\n if (!pendingTransition) {\n logger.warn('No pending transition found during resume')\n instance.status = 'RUNNING'\n await trx.flush()\n\n await logWorkflowEvent(trx, {\n workflowInstanceId: instanceId,\n eventType: 'WORKFLOW_RESUMED',\n eventData: {\n reason: 'All async activities completed',\n completedActivities: completedActivities,\n },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n\n return { continueExecution: true }\n }\n\n logger.debug('Completing pending transition', {\n toStepId: pendingTransition.toStepId,\n fromStepId: instance.currentStepId,\n })\n\n const definition = await findDefinitionForInstance(trx, instance)\n if (!definition) {\n throw new WorkflowExecutionError(\n `Workflow definition not found: ${instance.definitionId}`,\n 'DEFINITION_NOT_FOUND',\n { definitionId: instance.definitionId }\n )\n }\n\n const step = definition.definition.steps.find(s => s.stepId === pendingTransition.toStepId)\n\n instance.currentStepId = pendingTransition.toStepId\n instance.status = 'RUNNING'\n instance.pendingTransition = null\n instance.updatedAt = new Date()\n await trx.flush()\n\n await logWorkflowEvent(trx, {\n workflowInstanceId: instance.id,\n eventType: 'STEP_ENTERED',\n eventData: {\n stepId: pendingTransition.toStepId,\n stepName: step?.stepName,\n stepType: step?.stepType,\n },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n\n await logWorkflowEvent(trx, {\n workflowInstanceId: instanceId,\n eventType: 'WORKFLOW_RESUMED',\n eventData: {\n reason: 'Async activities completed, resuming pending transition',\n completedActivities: completedActivities,\n completedTransitionTo: pendingTransition.toStepId,\n },\n tenantId: instance.tenantId,\n organizationId: instance.organizationId,\n })\n\n const { executeStep } = await import('./step-handler')\n await executeStep(\n trx,\n instance,\n pendingTransition.toStepId,\n {\n workflowContext: instance.context || {},\n userId: resolveWorkflowExecutionUserId(undefined, instance),\n },\n container\n )\n\n return { continueExecution: true }\n }\n\n const resumeResult = typeof transactionalEm.transactional === 'function'\n ? await transactionalEm.transactional((trx) => runResume(trx))\n : await runResume(em)\n\n if (resumeResult.continueExecution) {\n await executeWorkflow(em, container, instanceId)\n }\n}\n\n/**\n * Check if workflow definition has any compensatable activities\n */\nfunction checkIfCompensationNeeded(definition: WorkflowDefinition): boolean {\n // Check if any activities have compensation defined\n for (const transition of definition.definition.transitions) {\n if (transition.activities) {\n for (const activity of transition.activities) {\n if (activity.compensation?.activityId) {\n return true\n }\n }\n }\n }\n\n // Check root-level activities (legacy)\n if (definition.definition.activities) {\n for (const activity of definition.definition.activities) {\n if (activity.compensation?.activityId) {\n return true\n }\n }\n }\n\n return false\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Get workflow instance by ID\n *\n * @param em - Entity manager\n * @param instanceId - Workflow instance ID\n * @returns Workflow instance or null if not found\n */\nexport async function getWorkflowInstance(\n em: EntityManager,\n instanceId: string\n): Promise<WorkflowInstance | null> {\n return em.findOne(WorkflowInstance, { id: instanceId })\n}\n\nasync function getWorkflowInstanceForExecution(\n em: EntityManager,\n instanceId: string,\n options?: { refresh?: boolean }\n): Promise<WorkflowInstance | null> {\n return em.findOne(\n WorkflowInstance,\n { id: instanceId },\n {\n lockMode: LockMode.PESSIMISTIC_WRITE,\n ...(options?.refresh ? { refresh: true } : {}),\n }\n )\n}\n\n/**\n * Update workflow context with new data\n *\n * @param em - Entity manager\n * @param instanceId - Workflow instance ID\n * @param updates - Context updates (merged with existing context)\n */\nexport async function updateWorkflowContext(\n em: EntityManager,\n instanceId: string,\n updates: Record<string, any>\n): Promise<void> {\n const instance = await getWorkflowInstance(em, instanceId)\n if (!instance) {\n throw new WorkflowExecutionError(\n `Workflow instance not found: ${instanceId}`,\n 'INSTANCE_NOT_FOUND',\n { instanceId }\n )\n }\n\n instance.context = {\n ...instance.context,\n ...updates,\n }\n instance.updatedAt = new Date()\n\n await em.flush()\n}\n\n// findWorkflowDefinition is imported from ./find-definition\n\n/**\n * Log workflow event to event sourcing table\n *\n * @param em - Entity manager\n * @param event - Event data\n */\nasync function logWorkflowEvent(\n em: EntityManager,\n event: {\n workflowInstanceId: string\n stepInstanceId?: string\n eventType: string\n eventData: any\n userId?: string\n tenantId: string\n organizationId: string\n }\n): Promise<WorkflowEvent> {\n const workflowEvent = em.create(WorkflowEvent, {\n ...event,\n occurredAt: new Date(),\n })\n\n await em.persist(workflowEvent).flush()\n return workflowEvent\n}\n"],
5
+ "mappings": "AAYA,SAAwB,gBAAgB;AAExC;AAAA,EAEE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,0BAA0B;AACnC,SAAS,wBAAwB,iCAAiC;AAClE,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AA0CvC,SAAS,wBAAwB,OAA+B;AAC9D,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,CAAC,WAAW,QAAQ,WAAW,UAAU,EAAG,QAAO;AACvD,SAAO;AACT;AAEA,SAAS,+BACP,SACA,UACoB;AACpB,SACE,wBAAwB,SAAS,MAAM,KACvC,wBAAwB,SAAS,UAAU,WAAW,KACtD;AAEJ;AAEO,MAAM,+BAA+B,MAAM;AAAA,EAChD,YACE,SACO,MACA,SACP;AACA,UAAM,OAAO;AAHN;AACA;AAGP,SAAK,OAAO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O;AAAA,MACT;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAaA,eAAsB,oBACpB,IACA,YACkC;AAClC,SAAO,GAAG,QAAQ,kBAAkB,EAAE,IAAI,WAAW,CAAC;AACxD;AAEA,eAAe,gCACb,IACA,YACA,SACkC;AAClC,SAAO,GAAG;AAAA,IACR;AAAA,IACA,EAAE,IAAI,WAAW;AAAA,IACjB;AAAA,MACE,UAAU,SAAS;AAAA,MACnB,GAAI,SAAS,UAAU,EAAE,SAAS,KAAK,IAAI,CAAC;AAAA,IAC9C;AAAA,EACF;AACF;AASA,eAAsB,sBACpB,IACA,YACA,SACe;AACf,QAAM,WAAW,MAAM,oBAAoB,IAAI,UAAU;AACzD,MAAI,CAAC,UAAU;AACb,UAAM,IAAI;AAAA,MACR,gCAAgC,UAAU;AAAA,MAC1C;AAAA,MACA,EAAE,WAAW;AAAA,IACf;AAAA,EACF;AAEA,WAAS,UAAU;AAAA,IACjB,GAAG,SAAS;AAAA,IACZ,GAAG;AAAA,EACL;AACA,WAAS,YAAY,oBAAI,KAAK;AAE9B,QAAM,GAAG,MAAM;AACjB;AAUA,eAAe,iBACb,IACA,OASwB;AACxB,QAAM,gBAAgB,GAAG,OAAO,eAAe;AAAA,IAC7C,GAAG;AAAA,IACH,YAAY,oBAAI,KAAK;AAAA,EACvB,CAAC;AAED,QAAM,GAAG,QAAQ,aAAa,EAAE,MAAM;AACtC,SAAO;AACT;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,42 @@
1
+ const workflowSafeCommands = /* @__PURE__ */ new Map();
2
+ function normalizeCommandId(commandId) {
3
+ if (typeof commandId !== "string") return null;
4
+ const trimmed = commandId.trim();
5
+ return trimmed.length > 0 ? trimmed : null;
6
+ }
7
+ function normalizeFeatures(features) {
8
+ const normalized = features.map((feature) => feature.trim()).filter((feature) => feature.length > 0);
9
+ if (normalized.length === 0) return null;
10
+ return normalized;
11
+ }
12
+ function registerWorkflowSafeCommands(commands) {
13
+ for (const command of commands) {
14
+ const commandId = normalizeCommandId(command.commandId);
15
+ const requiredFeatures = normalizeFeatures(command.requiredFeatures);
16
+ if (!commandId || !requiredFeatures) {
17
+ throw new Error("[internal] Workflow-safe commands require a commandId and requiredFeatures");
18
+ }
19
+ workflowSafeCommands.set(commandId, { commandId, requiredFeatures });
20
+ }
21
+ }
22
+ function getWorkflowSafeCommand(commandId) {
23
+ const normalized = normalizeCommandId(commandId);
24
+ if (!normalized) return null;
25
+ return workflowSafeCommands.get(normalized) ?? null;
26
+ }
27
+ function isWorkflowSafeCommandId(commandId) {
28
+ return getWorkflowSafeCommand(commandId) !== null;
29
+ }
30
+ function clearWorkflowSafeCommandsForTests() {
31
+ if (process.env.NODE_ENV !== "test") {
32
+ throw new Error("[internal] clearWorkflowSafeCommandsForTests is test-only");
33
+ }
34
+ workflowSafeCommands.clear();
35
+ }
36
+ export {
37
+ clearWorkflowSafeCommandsForTests,
38
+ getWorkflowSafeCommand,
39
+ isWorkflowSafeCommandId,
40
+ registerWorkflowSafeCommands
41
+ };
42
+ //# sourceMappingURL=workflow-safe-commands.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/workflows/lib/workflow-safe-commands.ts"],
4
+ "sourcesContent": ["export type WorkflowSafeCommandDefinition = {\n commandId: string\n requiredFeatures: readonly [string, ...string[]]\n}\n\nconst workflowSafeCommands = new Map<string, WorkflowSafeCommandDefinition>()\n\nfunction normalizeCommandId(commandId: unknown): string | null {\n if (typeof commandId !== 'string') return null\n const trimmed = commandId.trim()\n return trimmed.length > 0 ? trimmed : null\n}\n\nfunction normalizeFeatures(features: readonly string[]): [string, ...string[]] | null {\n const normalized = features\n .map((feature) => feature.trim())\n .filter((feature) => feature.length > 0)\n if (normalized.length === 0) return null\n return normalized as [string, ...string[]]\n}\n\nexport function registerWorkflowSafeCommands(commands: readonly WorkflowSafeCommandDefinition[]): void {\n for (const command of commands) {\n const commandId = normalizeCommandId(command.commandId)\n const requiredFeatures = normalizeFeatures(command.requiredFeatures)\n if (!commandId || !requiredFeatures) {\n throw new Error('[internal] Workflow-safe commands require a commandId and requiredFeatures')\n }\n workflowSafeCommands.set(commandId, { commandId, requiredFeatures })\n }\n}\n\nexport function getWorkflowSafeCommand(commandId: unknown): WorkflowSafeCommandDefinition | null {\n const normalized = normalizeCommandId(commandId)\n if (!normalized) return null\n return workflowSafeCommands.get(normalized) ?? null\n}\n\nexport function isWorkflowSafeCommandId(commandId: unknown): boolean {\n return getWorkflowSafeCommand(commandId) !== null\n}\n\nexport function clearWorkflowSafeCommandsForTests(): void {\n if (process.env.NODE_ENV !== 'test') {\n throw new Error('[internal] clearWorkflowSafeCommandsForTests is test-only')\n }\n workflowSafeCommands.clear()\n}\n"],
5
+ "mappings": "AAKA,MAAM,uBAAuB,oBAAI,IAA2C;AAE5E,SAAS,mBAAmB,WAAmC;AAC7D,MAAI,OAAO,cAAc,SAAU,QAAO;AAC1C,QAAM,UAAU,UAAU,KAAK;AAC/B,SAAO,QAAQ,SAAS,IAAI,UAAU;AACxC;AAEA,SAAS,kBAAkB,UAA2D;AACpF,QAAM,aAAa,SAChB,IAAI,CAAC,YAAY,QAAQ,KAAK,CAAC,EAC/B,OAAO,CAAC,YAAY,QAAQ,SAAS,CAAC;AACzC,MAAI,WAAW,WAAW,EAAG,QAAO;AACpC,SAAO;AACT;AAEO,SAAS,6BAA6B,UAA0D;AACrG,aAAW,WAAW,UAAU;AAC9B,UAAM,YAAY,mBAAmB,QAAQ,SAAS;AACtD,UAAM,mBAAmB,kBAAkB,QAAQ,gBAAgB;AACnE,QAAI,CAAC,aAAa,CAAC,kBAAkB;AACnC,YAAM,IAAI,MAAM,4EAA4E;AAAA,IAC9F;AACA,yBAAqB,IAAI,WAAW,EAAE,WAAW,iBAAiB,CAAC;AAAA,EACrE;AACF;AAEO,SAAS,uBAAuB,WAA0D;AAC/F,QAAM,aAAa,mBAAmB,SAAS;AAC/C,MAAI,CAAC,WAAY,QAAO;AACxB,SAAO,qBAAqB,IAAI,UAAU,KAAK;AACjD;AAEO,SAAS,wBAAwB,WAA6B;AACnE,SAAO,uBAAuB,SAAS,MAAM;AAC/C;AAEO,SAAS,oCAA0C;AACxD,MAAI,QAAQ,IAAI,aAAa,QAAQ;AACnC,UAAM,IAAI,MAAM,2DAA2D;AAAA,EAC7E;AACA,uBAAqB,MAAM;AAC7B;",
6
+ "names": []
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/core",
3
- "version": "0.6.7-develop.6580.1.39ab1d9e62",
3
+ "version": "0.6.7-develop.6582.1.04cac61287",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -253,16 +253,16 @@
253
253
  "zod": "^4.4.3"
254
254
  },
255
255
  "peerDependencies": {
256
- "@open-mercato/ai-assistant": "0.6.7-develop.6580.1.39ab1d9e62",
257
- "@open-mercato/shared": "0.6.7-develop.6580.1.39ab1d9e62",
258
- "@open-mercato/ui": "0.6.7-develop.6580.1.39ab1d9e62",
256
+ "@open-mercato/ai-assistant": "0.6.7-develop.6582.1.04cac61287",
257
+ "@open-mercato/shared": "0.6.7-develop.6582.1.04cac61287",
258
+ "@open-mercato/ui": "0.6.7-develop.6582.1.04cac61287",
259
259
  "react": "^19.0.0",
260
260
  "react-dom": "^19.0.0"
261
261
  },
262
262
  "devDependencies": {
263
- "@open-mercato/ai-assistant": "0.6.7-develop.6580.1.39ab1d9e62",
264
- "@open-mercato/shared": "0.6.7-develop.6580.1.39ab1d9e62",
265
- "@open-mercato/ui": "0.6.7-develop.6580.1.39ab1d9e62",
263
+ "@open-mercato/ai-assistant": "0.6.7-develop.6582.1.04cac61287",
264
+ "@open-mercato/shared": "0.6.7-develop.6582.1.04cac61287",
265
+ "@open-mercato/ui": "0.6.7-develop.6582.1.04cac61287",
266
266
  "@testing-library/dom": "^10.4.1",
267
267
  "@testing-library/jest-dom": "^6.9.1",
268
268
  "@testing-library/react": "^16.3.1",
@@ -151,6 +151,7 @@ const orderCrudEvents: CrudEventsConfig<SalesOrder> = {
151
151
  id: ctx.identifiers.id,
152
152
  organizationId: ctx.identifiers.organizationId,
153
153
  tenantId: ctx.identifiers.tenantId,
154
+ userId: ctx.actorUserId ?? null,
154
155
  }),
155
156
  };
156
157
 
@@ -162,6 +163,7 @@ const quoteCrudEvents: CrudEventsConfig<SalesQuote> = {
162
163
  id: ctx.identifiers.id,
163
164
  organizationId: ctx.identifiers.organizationId,
164
165
  tenantId: ctx.identifiers.tenantId,
166
+ userId: ctx.actorUserId ?? null,
165
167
  }),
166
168
  };
167
169
 
@@ -4766,6 +4768,7 @@ const createQuoteCommand: CommandHandler<
4766
4768
  },
4767
4769
  events: quoteCrudEvents,
4768
4770
  indexer: { entityType: E.sales.sales_quote },
4771
+ actorUserId: ctx.auth?.sub ?? null,
4769
4772
  });
4770
4773
 
4771
4774
  // Invalidate cache
@@ -5773,6 +5776,7 @@ const createOrderCommand: CommandHandler<
5773
5776
  },
5774
5777
  events: orderCrudEvents,
5775
5778
  indexer: { entityType: E.sales.sales_order },
5779
+ actorUserId: ctx.auth?.sub ?? null,
5776
5780
  });
5777
5781
 
5778
5782
  // Invalidate cache
@@ -5,6 +5,11 @@
5
5
  */
6
6
 
7
7
  import { defineWorkflow, createWorkflowsModuleConfig } from '@open-mercato/shared/modules/workflows'
8
+ import { registerWorkflowSafeCommands } from '@open-mercato/core/modules/workflows/lib/workflow-safe-commands'
9
+
10
+ registerWorkflowSafeCommands([
11
+ { commandId: 'sales.orders.update', requiredFeatures: ['sales.orders.manage'] },
12
+ ])
8
13
 
9
14
  const orderApproval = defineWorkflow({
10
15
  workflowId: 'sales.order-approval',
@@ -196,7 +196,7 @@ export async function POST(request: NextRequest) {
196
196
 
197
197
  const input: StartWorkflowApiInput = validation.data
198
198
 
199
- // User-started instances must always record the authenticated caller.
199
+ // Server-authoritative actor; do not trust client-supplied metadata.initiatedBy.
200
200
  const metadata = {
201
201
  ...input.metadata,
202
202
  initiatedBy: auth.sub,
@@ -220,7 +220,9 @@ export async function POST(request: NextRequest) {
220
220
  // Create new container and EM for background execution
221
221
  const bgContainer = await createRequestContainer()
222
222
  const bgEm = bgContainer.resolve('em')
223
- await workflowExecutor.executeWorkflow(bgEm, bgContainer, instance.id)
223
+ await workflowExecutor.executeWorkflow(bgEm, bgContainer, instance.id, {
224
+ userId: auth.sub,
225
+ })
224
226
  } catch (error) {
225
227
  logger.error('Background workflow execution error', { err: error })
226
228
  }
@@ -22,10 +22,12 @@ import {
22
22
  type HostLookup,
23
23
  } from '@open-mercato/shared/lib/url-safety'
24
24
  import { parseBooleanWithDefault } from '@open-mercato/shared/lib/boolean'
25
+ import { hasAllFeatures } from '@open-mercato/shared/security/features'
25
26
  import { callWebhookConfigSchema } from '../data/validators'
26
27
  import { WorkflowActivityJob, WORKFLOW_ACTIVITIES_QUEUE_NAME } from './activity-queue-types'
27
28
  import { logWorkflowEvent } from './event-logger'
28
29
  import { parseDuration } from './duration'
30
+ import { getWorkflowSafeCommand } from './workflow-safe-commands'
29
31
 
30
32
  export { isPrivateUrl } from '@open-mercato/shared/lib/network'
31
33
  import { createLogger } from '@open-mercato/shared/lib/logger'
@@ -127,6 +129,30 @@ export interface ActivityContext {
127
129
  userId?: string
128
130
  }
129
131
 
132
+ type RbacFeatureResolver = {
133
+ getGrantedFeatures: (
134
+ userId: string,
135
+ opts: { tenantId: string | null; organizationId: string | null }
136
+ ) => Promise<string[]>
137
+ }
138
+
139
+ async function resolveWorkflowUserFeatures(
140
+ container: AwilixContainer,
141
+ userId: string,
142
+ tenantId: string | null,
143
+ organizationId: string | null
144
+ ): Promise<string[]> {
145
+ try {
146
+ const rbac = container.resolve('rbacService') as RbacFeatureResolver | undefined
147
+ if (rbac?.getGrantedFeatures) {
148
+ return await rbac.getGrantedFeatures(userId, { tenantId, organizationId })
149
+ }
150
+ } catch {
151
+ // Fail closed below when the workflow executor cannot prove the actor's grants.
152
+ }
153
+ return []
154
+ }
155
+
130
156
  export interface ActivityExecutionResult {
131
157
  activityId: string
132
158
  activityName?: string
@@ -606,10 +632,30 @@ export async function executeUpdateEntity(
606
632
  throw new Error('UPDATE_ENTITY requires "commandId" field (e.g., "sales.documents.update")')
607
633
  }
608
634
 
635
+ const workflowSafeCommand = getWorkflowSafeCommand(commandId)
636
+ if (!workflowSafeCommand) {
637
+ throw new Error('UPDATE_ENTITY command is not allowed')
638
+ }
639
+
609
640
  if (!input || typeof input !== 'object') {
610
641
  throw new Error('UPDATE_ENTITY requires "input" object with entity data')
611
642
  }
612
643
 
644
+ const actorUserId = typeof context.userId === 'string' ? context.userId.trim() : ''
645
+ if (!actorUserId) {
646
+ throw new Error('UPDATE_ENTITY requires an authenticated workflow user')
647
+ }
648
+
649
+ const userFeatures = await resolveWorkflowUserFeatures(
650
+ container,
651
+ actorUserId,
652
+ context.workflowInstance.tenantId,
653
+ context.workflowInstance.organizationId
654
+ )
655
+ if (!hasAllFeatures(userFeatures, workflowSafeCommand.requiredFeatures)) {
656
+ throw new Error('UPDATE_ENTITY command is not authorized')
657
+ }
658
+
613
659
  // Resolve CommandBus from container
614
660
  const commandBus = container.resolve('commandBus') as any
615
661
 
@@ -636,12 +682,10 @@ export async function executeUpdateEntity(
636
682
  }
637
683
 
638
684
  // Build synthetic CommandRuntimeContext for workflow execution
639
- // Use nil UUID for system actions when no user context is available
640
- const SYSTEM_USER_ID = '00000000-0000-0000-0000-000000000000'
641
685
  const ctx = {
642
686
  container,
643
687
  auth: {
644
- sub: context.userId || SYSTEM_USER_ID,
688
+ sub: actorUserId,
645
689
  tenantId: context.workflowInstance.tenantId,
646
690
  orgId: context.workflowInstance.organizationId,
647
691
  isSuperAdmin: false,
@@ -1,24 +1,33 @@
1
1
  /**
2
- * In-Memory Code Workflow Registry
2
+ * Code Workflow Registry (validating bridge)
3
3
  *
4
- * Stores code-based workflow definitions populated at bootstrap from
5
- * the generated workflows.generated.ts. Definitions live purely in memory —
6
- * no DB row is created until a user customizes the definition.
4
+ * The registry store itself lives in `@open-mercato/shared` so all bootstrap
5
+ * contexts (Next.js app, CLI, `mercato workers`) share one process-wide map —
6
+ * see `@open-mercato/shared/modules/workflows/code-registry`. This module
7
+ * keeps the workflows engine's import path stable and adds Zod validation on
8
+ * top of the raw registration used by the shared bootstrap factory.
7
9
  */
8
10
 
9
11
  import type { CodeWorkflowDefinition } from '@open-mercato/shared/modules/workflows'
12
+ import { registerCodeWorkflowEntries } from '@open-mercato/shared/modules/workflows/code-registry'
10
13
  import { workflowDefinitionDataSchema } from '../data/validators'
11
14
  import { createLogger } from '@open-mercato/shared/lib/logger'
12
15
 
13
16
  const logger = createLogger('workflows')
14
17
 
15
- const codeWorkflowRegistry = new Map<string, CodeWorkflowDefinition>()
18
+ export {
19
+ getCodeWorkflow,
20
+ getAllCodeWorkflows,
21
+ isCodeWorkflow,
22
+ clearCodeWorkflowRegistry,
23
+ } from '@open-mercato/shared/modules/workflows/code-registry'
16
24
 
17
25
  /**
18
26
  * Register code-based workflow definitions at bootstrap time.
19
27
  * Validates each definition against the Zod schema and warns on failures.
20
28
  */
21
29
  export function registerCodeWorkflows(workflows: CodeWorkflowDefinition[]): void {
30
+ const valid: CodeWorkflowDefinition[] = []
22
31
  for (const wf of workflows) {
23
32
  const validation = workflowDefinitionDataSchema.safeParse(wf.definition)
24
33
  if (!validation.success) {
@@ -28,39 +37,7 @@ export function registerCodeWorkflows(workflows: CodeWorkflowDefinition[]): void
28
37
  })
29
38
  continue
30
39
  }
31
-
32
- if (codeWorkflowRegistry.has(wf.workflowId)) {
33
- logger.warn('Duplicate code workflow ID — overwriting', { workflowId: wf.workflowId, moduleId: wf.moduleId })
34
- }
35
-
36
- codeWorkflowRegistry.set(wf.workflowId, wf)
40
+ valid.push(wf)
37
41
  }
38
- }
39
-
40
- /**
41
- * Get a single code workflow definition by workflowId.
42
- */
43
- export function getCodeWorkflow(workflowId: string): CodeWorkflowDefinition | undefined {
44
- return codeWorkflowRegistry.get(workflowId)
45
- }
46
-
47
- /**
48
- * Get all registered code workflow definitions.
49
- */
50
- export function getAllCodeWorkflows(): CodeWorkflowDefinition[] {
51
- return Array.from(codeWorkflowRegistry.values())
52
- }
53
-
54
- /**
55
- * Check if a workflowId is a code-based definition.
56
- */
57
- export function isCodeWorkflow(workflowId: string): boolean {
58
- return codeWorkflowRegistry.has(workflowId)
59
- }
60
-
61
- /**
62
- * Clear the registry (for testing).
63
- */
64
- export function clearCodeWorkflowRegistry(): void {
65
- codeWorkflowRegistry.clear()
42
+ registerCodeWorkflowEntries(valid)
66
43
  }
@@ -72,6 +72,13 @@ interface CachedTriggers {
72
72
  // Cache TTL: 5 minutes
73
73
  const TRIGGER_CACHE_TTL = 5 * 60 * 1000
74
74
 
75
+ function readEventActorUserId(payload: Record<string, unknown>): string | null {
76
+ const candidate = payload.userId ?? payload.actorUserId
77
+ if (typeof candidate !== 'string') return null
78
+ const trimmed = candidate.trim()
79
+ return trimmed.length > 0 && !trimmed.startsWith('trigger:') ? trimmed : null
80
+ }
81
+
75
82
  // ============================================================================
76
83
  // Pattern Matching
77
84
  // ============================================================================
@@ -616,6 +623,7 @@ export async function processEventTriggers(
616
623
  // Extract entity info from payload for metadata
617
624
  const payloadId = context.payload?.id as string | undefined
618
625
  const payloadEntityType = context.payload?.entityType as string | undefined
626
+ const actorUserId = readEventActorUserId(context.payload)
619
627
 
620
628
  // Include event metadata and payload in context
621
629
  const initialContext = {
@@ -639,7 +647,7 @@ export async function processEventTriggers(
639
647
  version: trigger.workflowVersion,
640
648
  initialContext,
641
649
  metadata: {
642
- initiatedBy: `trigger:${trigger.id}`,
650
+ initiatedBy: actorUserId ?? `trigger:${trigger.id}`,
643
651
  // Include entityId and entityType for widget discovery
644
652
  entityId: payloadId,
645
653
  entityType: payloadEntityType || trigger.config?.entityType,
@@ -661,7 +669,12 @@ export async function processEventTriggers(
661
669
  })
662
670
 
663
671
  // Execute workflow asynchronously (don't wait)
664
- executeWorkflow(em.fork(), container, instance.id).catch(err => {
672
+ executeWorkflow(
673
+ em.fork(),
674
+ container,
675
+ instance.id,
676
+ actorUserId ? { userId: actorUserId } : undefined
677
+ ).catch(err => {
665
678
  logger.error('Error executing workflow', { instanceId: instance.id, err })
666
679
  })
667
680
 
@@ -104,6 +104,13 @@ interface ParallelContext {
104
104
  userId?: string
105
105
  }
106
106
 
107
+ function normalizeWorkflowUserId(value: unknown): string | null {
108
+ if (typeof value !== 'string') return null
109
+ const trimmed = value.trim()
110
+ if (!trimmed || trimmed.startsWith('trigger:')) return null
111
+ return trimmed
112
+ }
113
+
107
114
  function getNestedValue(obj: any, path: string): any {
108
115
  return path.split('.').reduce((current, key) => (current == null ? undefined : current[key]), obj)
109
116
  }
@@ -251,7 +258,10 @@ export async function resumeBranchAfterActivities(
251
258
  em,
252
259
  instance,
253
260
  pending.toStepId,
254
- { workflowContext: { ...(instance.context || {}), ...(branch.contextNamespace || {}) } },
261
+ {
262
+ workflowContext: { ...(instance.context || {}), ...(branch.contextNamespace || {}) },
263
+ userId: normalizeWorkflowUserId(instance.metadata?.initiatedBy) ?? undefined,
264
+ },
255
265
  container,
256
266
  branch,
257
267
  )