alepha 0.20.1 → 0.20.2

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 (232) hide show
  1. package/dist/api/files/index.js +2 -1
  2. package/dist/api/files/index.js.map +1 -1
  3. package/dist/api/jobs/index.browser.js +64 -148
  4. package/dist/api/jobs/index.browser.js.map +1 -1
  5. package/dist/api/jobs/index.d.ts +371 -573
  6. package/dist/api/jobs/index.d.ts.map +1 -1
  7. package/dist/api/jobs/index.js +605 -1012
  8. package/dist/api/jobs/index.js.map +1 -1
  9. package/dist/api/notifications/index.d.ts +78 -17
  10. package/dist/api/notifications/index.d.ts.map +1 -1
  11. package/dist/api/notifications/index.js +90 -23
  12. package/dist/api/notifications/index.js.map +1 -1
  13. package/dist/api/payments/index.d.ts +2 -1
  14. package/dist/api/payments/index.d.ts.map +1 -1
  15. package/dist/api/payments/index.js +4 -2
  16. package/dist/api/payments/index.js.map +1 -1
  17. package/dist/api/users/index.d.ts +34 -31
  18. package/dist/api/users/index.d.ts.map +1 -1
  19. package/dist/api/users/index.js +13 -7
  20. package/dist/api/users/index.js.map +1 -1
  21. package/dist/api/verifications/index.js +2 -1
  22. package/dist/api/verifications/index.js.map +1 -1
  23. package/dist/cli/core/index.d.ts +8 -34
  24. package/dist/cli/core/index.d.ts.map +1 -1
  25. package/dist/cli/core/index.js +43 -232
  26. package/dist/cli/core/index.js.map +1 -1
  27. package/dist/cli/platform/index.d.ts +36 -11
  28. package/dist/cli/platform/index.d.ts.map +1 -1
  29. package/dist/cli/platform/index.js +93 -27
  30. package/dist/cli/platform/index.js.map +1 -1
  31. package/dist/command/index.d.ts +1 -1
  32. package/dist/core/index.browser.js +6 -0
  33. package/dist/core/index.browser.js.map +1 -1
  34. package/dist/core/index.d.ts +6 -0
  35. package/dist/core/index.d.ts.map +1 -1
  36. package/dist/core/index.js +6 -0
  37. package/dist/core/index.js.map +1 -1
  38. package/dist/core/index.native.js +6 -0
  39. package/dist/core/index.native.js.map +1 -1
  40. package/dist/core/index.workerd.js +6 -0
  41. package/dist/core/index.workerd.js.map +1 -1
  42. package/dist/react/form/index.d.ts +60 -1
  43. package/dist/react/form/index.d.ts.map +1 -1
  44. package/dist/react/form/index.js +86 -1
  45. package/dist/react/form/index.js.map +1 -1
  46. package/dist/react/head/index.browser.js +16 -1
  47. package/dist/react/head/index.browser.js.map +1 -1
  48. package/dist/react/head/index.d.ts +6 -0
  49. package/dist/react/head/index.d.ts.map +1 -1
  50. package/dist/react/head/index.js +16 -1
  51. package/dist/react/head/index.js.map +1 -1
  52. package/dist/react/router/index.browser.js +0 -10
  53. package/dist/react/router/index.browser.js.map +1 -1
  54. package/dist/react/router/index.d.ts +35 -12
  55. package/dist/react/router/index.d.ts.map +1 -1
  56. package/dist/react/router/index.js +0 -10
  57. package/dist/react/router/index.js.map +1 -1
  58. package/dist/react/ui/index.d.ts +124 -0
  59. package/dist/react/ui/index.d.ts.map +1 -0
  60. package/dist/react/ui/index.js +206 -0
  61. package/dist/react/ui/index.js.map +1 -0
  62. package/dist/router/index.d.ts +13 -13
  63. package/dist/router/index.d.ts.map +1 -1
  64. package/dist/router/index.js +45 -32
  65. package/dist/router/index.js.map +1 -1
  66. package/dist/system/index.d.ts.map +1 -1
  67. package/dist/system/index.js +1 -0
  68. package/dist/system/index.js.map +1 -1
  69. package/dist/topic/core/index.js +1 -1
  70. package/dist/topic/core/index.js.map +1 -1
  71. package/package.json +6 -23
  72. package/src/api/files/jobs/FileJobs.ts +2 -1
  73. package/src/api/jobs/__tests__/$job.spec.ts +316 -2867
  74. package/src/api/jobs/controllers/AdminJobController.ts +29 -138
  75. package/src/api/jobs/entities/jobExecutionEntity.ts +27 -19
  76. package/src/api/jobs/index.browser.ts +5 -7
  77. package/src/api/jobs/index.ts +23 -51
  78. package/src/api/jobs/primitives/$job.ts +66 -58
  79. package/src/api/jobs/providers/JobProvider.ts +561 -566
  80. package/src/api/jobs/providers/JobQueueProvider.ts +18 -19
  81. package/src/api/jobs/schemas/jobConfigAtom.ts +20 -23
  82. package/src/api/jobs/schemas/jobExecutionQuerySchema.ts +3 -27
  83. package/src/api/jobs/schemas/jobExecutionResourceSchema.ts +5 -7
  84. package/src/api/jobs/schemas/jobRegistrationSchema.ts +7 -4
  85. package/src/api/jobs/schemas/triggerJobSchema.ts +0 -1
  86. package/src/api/jobs/services/JobService.ts +90 -483
  87. package/src/api/notifications/controllers/AdminNotificationController.ts +19 -12
  88. package/src/api/notifications/index.ts +7 -4
  89. package/src/api/notifications/jobs/NotificationJobs.ts +83 -12
  90. package/src/api/payments/services/PaymentService.ts +4 -2
  91. package/src/api/users/__tests__/UserJobs.spec.ts +10 -49
  92. package/src/api/users/audits/UserAudits.ts +3 -1
  93. package/src/api/users/buckets/UserBuckets.ts +2 -1
  94. package/src/api/users/index.ts +1 -4
  95. package/src/api/users/jobs/UserJobs.ts +5 -4
  96. package/src/api/verifications/jobs/VerificationJobs.ts +2 -1
  97. package/src/cli/core/__tests__/init.spec.ts +1 -1
  98. package/src/cli/core/commands/init.ts +0 -12
  99. package/src/cli/core/services/PackageManagerUtils.ts +2 -9
  100. package/src/cli/core/services/ProjectScaffolder.ts +17 -65
  101. package/src/cli/core/templates/agentMd.ts +2 -8
  102. package/src/cli/core/templates/apiIndexTs.ts +4 -18
  103. package/src/cli/core/templates/mainCss.ts +1 -36
  104. package/src/cli/core/templates/vitestConfigTs.ts +17 -0
  105. package/src/cli/core/templates/webAppRouterTs.ts +2 -85
  106. package/src/cli/platform/__tests__/CloudflareAdapter.spec.ts +22 -71
  107. package/src/cli/platform/adapters/CloudflareAdapter.ts +12 -11
  108. package/src/cli/platform/atoms/platformOptions.ts +9 -0
  109. package/src/cli/platform/schemas/cloudflare.ts +3 -2
  110. package/src/cli/platform/services/CloudflareApi.ts +164 -25
  111. package/src/cli/platform/services/WranglerApi.ts +0 -17
  112. package/src/core/Alepha.ts +9 -0
  113. package/src/react/form/index.ts +2 -0
  114. package/src/react/form/services/parseField.ts +163 -0
  115. package/src/react/form/services/prettyName.ts +19 -0
  116. package/src/react/head/providers/BrowserHeadProvider.ts +31 -10
  117. package/src/react/router/primitives/$page.ts +35 -12
  118. package/src/react/ui/atoms/uiAtom.ts +28 -0
  119. package/src/react/ui/components/ColorScheme.tsx +36 -0
  120. package/src/react/ui/hooks/useColorMode.ts +49 -0
  121. package/src/react/ui/hooks/useSidebarState.ts +26 -0
  122. package/src/react/ui/hooks/useTheme.ts +22 -0
  123. package/src/react/ui/index.ts +35 -0
  124. package/src/react/ui/services/UiPersistence.ts +41 -0
  125. package/src/router/TemplatedPathParser.ts +50 -51
  126. package/src/router/__tests__/RouterProvider.spec.ts +62 -0
  127. package/src/router/__tests__/TemplatedPathParser.spec.ts +18 -0
  128. package/src/router/providers/RouterProvider.ts +10 -5
  129. package/src/system/providers/NodeShellProvider.ts +1 -0
  130. package/src/topic/core/providers/TopicProvider.ts +1 -1
  131. package/dist/api/invitations/index.d.ts +0 -790
  132. package/dist/api/invitations/index.d.ts.map +0 -1
  133. package/dist/api/invitations/index.js +0 -662
  134. package/dist/api/invitations/index.js.map +0 -1
  135. package/dist/api/issues/index.d.ts +0 -810
  136. package/dist/api/issues/index.d.ts.map +0 -1
  137. package/dist/api/issues/index.js +0 -444
  138. package/dist/api/issues/index.js.map +0 -1
  139. package/dist/api/subscriptions/index.d.ts +0 -1692
  140. package/dist/api/subscriptions/index.d.ts.map +0 -1
  141. package/dist/api/subscriptions/index.js +0 -1867
  142. package/dist/api/subscriptions/index.js.map +0 -1
  143. package/dist/api/workflows/index.browser.js +0 -246
  144. package/dist/api/workflows/index.browser.js.map +0 -1
  145. package/dist/api/workflows/index.d.ts +0 -1618
  146. package/dist/api/workflows/index.d.ts.map +0 -1
  147. package/dist/api/workflows/index.js +0 -1495
  148. package/dist/api/workflows/index.js.map +0 -1
  149. package/src/api/invitations/__tests__/InvitationService.spec.ts +0 -439
  150. package/src/api/invitations/controllers/AdminInvitationController.ts +0 -86
  151. package/src/api/invitations/controllers/InvitationController.ts +0 -84
  152. package/src/api/invitations/entities/invitations.ts +0 -33
  153. package/src/api/invitations/index.ts +0 -58
  154. package/src/api/invitations/jobs/InvitationJobs.ts +0 -37
  155. package/src/api/invitations/providers/InvitationProvider.ts +0 -45
  156. package/src/api/invitations/schemas/createInvitationSchema.ts +0 -12
  157. package/src/api/invitations/schemas/invitationConfigAtom.ts +0 -20
  158. package/src/api/invitations/schemas/invitationQuerySchema.ts +0 -15
  159. package/src/api/invitations/schemas/invitationResourceSchema.ts +0 -6
  160. package/src/api/invitations/schemas/invitationWithResourceInfoSchema.ts +0 -22
  161. package/src/api/invitations/schemas/myInvitationsQuerySchema.ts +0 -10
  162. package/src/api/invitations/services/InvitationService.ts +0 -556
  163. package/src/api/issues/__tests__/IssueService.spec.ts +0 -263
  164. package/src/api/issues/controllers/AdminIssueController.ts +0 -149
  165. package/src/api/issues/controllers/IssueController.ts +0 -44
  166. package/src/api/issues/entities/issues.ts +0 -49
  167. package/src/api/issues/index.ts +0 -50
  168. package/src/api/issues/schemas/createIssueSchema.ts +0 -13
  169. package/src/api/issues/schemas/issueConfigAtom.ts +0 -13
  170. package/src/api/issues/schemas/issueQuerySchema.ts +0 -18
  171. package/src/api/issues/schemas/issueResourceSchema.ts +0 -6
  172. package/src/api/issues/schemas/myIssueQuerySchema.ts +0 -10
  173. package/src/api/issues/schemas/updateIssueSchema.ts +0 -13
  174. package/src/api/issues/services/IssueService.ts +0 -264
  175. package/src/api/jobs/__tests__/$job-middleware.spec.ts +0 -126
  176. package/src/api/jobs/__tests__/JobService.spec.ts +0 -31
  177. package/src/api/jobs/entities/jobExecutionLogEntity.ts +0 -13
  178. package/src/api/jobs/schemas/jobActivitySchema.ts +0 -15
  179. package/src/api/jobs/schemas/jobCronInfoSchema.ts +0 -22
  180. package/src/api/jobs/schemas/jobExecutionDetailResourceSchema.ts +0 -20
  181. package/src/api/jobs/schemas/jobFailureSchema.ts +0 -9
  182. package/src/api/jobs/schemas/jobQueueDepthSchema.ts +0 -14
  183. package/src/api/jobs/schemas/jobStatsSchema.ts +0 -14
  184. package/src/api/jobs/services/JobService-tests.ts +0 -157
  185. package/src/api/subscriptions/__tests__/BillingService.spec.ts +0 -218
  186. package/src/api/subscriptions/__tests__/SubscriptionService.spec.ts +0 -278
  187. package/src/api/subscriptions/controllers/AdminSubscriptionController.ts +0 -212
  188. package/src/api/subscriptions/controllers/SubscriptionController.ts +0 -189
  189. package/src/api/subscriptions/entities/subscriptionEvents.ts +0 -54
  190. package/src/api/subscriptions/entities/subscriptions.ts +0 -68
  191. package/src/api/subscriptions/index.ts +0 -133
  192. package/src/api/subscriptions/jobs/SubscriptionJobs.ts +0 -382
  193. package/src/api/subscriptions/middleware/$requireLimit.ts +0 -50
  194. package/src/api/subscriptions/middleware/$requirePlan.ts +0 -49
  195. package/src/api/subscriptions/notifications/SubscriptionNotifications.ts +0 -110
  196. package/src/api/subscriptions/schemas/cancelSubscriptionSchema.ts +0 -8
  197. package/src/api/subscriptions/schemas/changePlanSchema.ts +0 -9
  198. package/src/api/subscriptions/schemas/createSubscriptionSchema.ts +0 -11
  199. package/src/api/subscriptions/schemas/entitlementsSchema.ts +0 -21
  200. package/src/api/subscriptions/schemas/mrrSchema.ts +0 -13
  201. package/src/api/subscriptions/schemas/planDefinitionSchema.ts +0 -71
  202. package/src/api/subscriptions/schemas/planResourceSchema.ts +0 -25
  203. package/src/api/subscriptions/schemas/subscriptionEventResourceSchema.ts +0 -8
  204. package/src/api/subscriptions/schemas/subscriptionQuerySchema.ts +0 -19
  205. package/src/api/subscriptions/schemas/subscriptionResourceSchema.ts +0 -6
  206. package/src/api/subscriptions/schemas/subscriptionSettingsSchema.ts +0 -32
  207. package/src/api/subscriptions/schemas/subscriptionStatsSchema.ts +0 -23
  208. package/src/api/subscriptions/services/BillingService.ts +0 -437
  209. package/src/api/subscriptions/services/SubscriptionConfig.ts +0 -56
  210. package/src/api/subscriptions/services/SubscriptionService.ts +0 -867
  211. package/src/api/subscriptions/services/UsageService.ts +0 -118
  212. package/src/api/workflows/__tests__/$workflow.spec.ts +0 -616
  213. package/src/api/workflows/controllers/AdminWorkflowController.ts +0 -191
  214. package/src/api/workflows/entities/workflowExecutions.ts +0 -74
  215. package/src/api/workflows/entities/workflowStepExecutions.ts +0 -74
  216. package/src/api/workflows/entities/workflowStepLogs.ts +0 -13
  217. package/src/api/workflows/index.browser.ts +0 -22
  218. package/src/api/workflows/index.ts +0 -115
  219. package/src/api/workflows/jobs/WorkflowJobs.ts +0 -77
  220. package/src/api/workflows/primitives/$workflow.ts +0 -202
  221. package/src/api/workflows/providers/WorkflowProvider.ts +0 -1284
  222. package/src/api/workflows/schemas/workflowActivitySchema.ts +0 -15
  223. package/src/api/workflows/schemas/workflowConfigAtom.ts +0 -51
  224. package/src/api/workflows/schemas/workflowExecutionDetailSchema.ts +0 -18
  225. package/src/api/workflows/schemas/workflowExecutionQuerySchema.ts +0 -26
  226. package/src/api/workflows/schemas/workflowExecutionResourceSchema.ts +0 -30
  227. package/src/api/workflows/schemas/workflowRegistrationSchema.ts +0 -26
  228. package/src/api/workflows/schemas/workflowStatsSchema.ts +0 -16
  229. package/src/api/workflows/schemas/workflowStepExecutionResourceSchema.ts +0 -15
  230. package/src/api/workflows/services/WorkflowService.ts +0 -382
  231. package/src/cli/core/templates/apiAppSecurityTs.ts +0 -43
  232. package/src/cli/core/templates/webAdminDashboardTsx.ts +0 -17
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/api/workflows/schemas/workflowActivitySchema.ts","../../../src/api/workflows/entities/workflowExecutions.ts","../../../src/api/workflows/schemas/workflowExecutionResourceSchema.ts","../../../src/api/workflows/entities/workflowStepExecutions.ts","../../../src/api/workflows/schemas/workflowStepExecutionResourceSchema.ts","../../../src/api/workflows/schemas/workflowExecutionDetailSchema.ts","../../../src/api/workflows/schemas/workflowExecutionQuerySchema.ts","../../../src/api/workflows/schemas/workflowRegistrationSchema.ts","../../../src/api/workflows/schemas/workflowStatsSchema.ts","../../../src/api/workflows/entities/workflowStepLogs.ts","../../../src/api/workflows/schemas/workflowConfigAtom.ts","../../../src/api/workflows/providers/WorkflowProvider.ts","../../../src/api/workflows/services/WorkflowService.ts","../../../src/api/workflows/controllers/AdminWorkflowController.ts","../../../src/api/workflows/jobs/WorkflowJobs.ts","../../../src/api/workflows/primitives/$workflow.ts","../../../src/api/workflows/index.ts"],"sourcesContent":["import { type Static, t } from \"alepha\";\n\nexport const workflowActivityPointSchema = t.object({\n date: t.text(),\n completed: t.integer(),\n failed: t.integer(),\n});\n\nexport type WorkflowActivityPoint = Static<typeof workflowActivityPointSchema>;\n\nexport const workflowActivityQuerySchema = t.object({\n days: t.optional(t.integer({ minimum: 1, maximum: 90 })),\n});\n\nexport type WorkflowActivityQuery = Static<typeof workflowActivityQuerySchema>;\n","import { type Static, t } from \"alepha\";\nimport { $entity, db, sql } from \"alepha/orm\";\n\nexport const workflowExecutions = $entity({\n name: \"workflow_executions\",\n schema: t.object({\n id: db.primaryKey(t.uuid()),\n createdAt: db.createdAt(),\n updatedAt: db.updatedAt(),\n\n workflowName: t.text(),\n tags: t.optional(t.array(t.text())),\n\n payload: t.optional(t.record(t.text(), t.any())),\n\n status: db.default(\n t.enum([\n \"pending\",\n \"running\",\n \"waiting_for_signal\",\n \"completed\",\n \"failed\",\n \"timed_out\",\n \"compensating\",\n \"compensated\",\n \"compensation_failed\",\n \"cancelled\",\n ]),\n \"pending\",\n ),\n currentStep: t.optional(t.text()),\n\n startedAt: t.optional(t.datetime()),\n completedAt: t.optional(t.datetime()),\n deadlineAt: t.optional(t.datetime()),\n\n error: t.optional(t.text()),\n errorStep: t.optional(t.text()),\n\n triggeredBy: t.optional(t.text()),\n triggeredByName: t.optional(t.text()),\n cancelledBy: t.optional(t.text()),\n cancelledByName: t.optional(t.text()),\n\n key: t.optional(t.nullable(t.text())),\n\n priority: db.default(t.integer({ minimum: 0, maximum: 3 }), 2),\n }),\n indexes: [\n { columns: [\"workflowName\", \"status\"] },\n { columns: [\"workflowName\", \"status\", \"createdAt\"] },\n {\n columns: [\"workflowName\", \"key\"],\n unique: true,\n where: sql`status NOT IN ('completed', 'failed', 'compensated', 'compensation_failed', 'cancelled')`,\n },\n { columns: [\"status\", \"deadlineAt\"] },\n { columns: [\"completedAt\"] },\n ],\n});\n\nexport type WorkflowExecutionEntity = Static<typeof workflowExecutions.schema>;\n\nexport type WorkflowStatus =\n | \"pending\"\n | \"running\"\n | \"waiting_for_signal\"\n | \"completed\"\n | \"failed\"\n | \"timed_out\"\n | \"compensating\"\n | \"compensated\"\n | \"compensation_failed\"\n | \"cancelled\";\n","import { type Static, t } from \"alepha\";\nimport { workflowExecutions } from \"../entities/workflowExecutions.ts\";\n\nexport const workflowExecutionCanSchema = t.object({\n retry: t.boolean(),\n cancel: t.boolean(),\n compensate: t.boolean(),\n restart: t.boolean(),\n signal: t.optional(\n t.object({\n stepName: t.text(),\n schema: t.optional(t.any()),\n }),\n ),\n});\n\nexport type WorkflowExecutionCan = Static<typeof workflowExecutionCanSchema>;\n\nexport const workflowExecutionResourceSchema = t.extend(\n workflowExecutions.schema,\n { can: workflowExecutionCanSchema },\n {\n title: \"WorkflowExecutionResource\",\n description: \"A workflow execution resource.\",\n },\n);\n\nexport type WorkflowExecutionResource = Static<\n typeof workflowExecutionResourceSchema\n>;\n","import { type Static, t } from \"alepha\";\nimport { $entity, db } from \"alepha/orm\";\nimport { workflowExecutions } from \"./workflowExecutions.ts\";\n\nexport const workflowStepExecutions = $entity({\n name: \"workflow_step_executions\",\n schema: t.object({\n id: db.primaryKey(t.uuid()),\n createdAt: db.createdAt(),\n updatedAt: db.updatedAt(),\n\n workflowExecutionId: db.ref(t.uuid(), () => workflowExecutions.cols.id, {\n onDelete: \"cascade\",\n }),\n\n stepName: t.text(),\n stepIndex: t.integer(),\n stepType: db.default(t.enum([\"handler\", \"signal\", \"parallel\"]), \"handler\"),\n\n parentStepId: t.optional(t.uuid()),\n branchName: t.optional(t.text()),\n\n status: db.default(\n t.enum([\n \"pending\",\n \"running\",\n \"completed\",\n \"failed\",\n \"skipped\",\n \"waiting\",\n \"compensating\",\n \"compensated\",\n \"compensation_failed\",\n \"cancelled\",\n ]),\n \"pending\",\n ),\n attempt: db.default(t.integer(), 0),\n maxAttempts: db.default(t.integer(), 1),\n\n result: t.optional(t.record(t.text(), t.any())),\n error: t.optional(t.text()),\n\n startedAt: t.optional(t.datetime()),\n completedAt: t.optional(t.datetime()),\n deadlineAt: t.optional(t.datetime()),\n\n signalPayload: t.optional(t.record(t.text(), t.any())),\n signalledBy: t.optional(t.text()),\n signalledAt: t.optional(t.datetime()),\n }),\n indexes: [\n { columns: [\"workflowExecutionId\", \"stepName\"] },\n { columns: [\"workflowExecutionId\", \"stepIndex\"] },\n { columns: [\"workflowExecutionId\", \"status\"] },\n { columns: [\"status\", \"deadlineAt\"] },\n ],\n});\n\nexport type WorkflowStepExecutionEntity = Static<\n typeof workflowStepExecutions.schema\n>;\n\nexport type WorkflowStepStatus =\n | \"pending\"\n | \"running\"\n | \"completed\"\n | \"failed\"\n | \"skipped\"\n | \"waiting\"\n | \"compensating\"\n | \"compensated\"\n | \"compensation_failed\"\n | \"cancelled\";\n","import { type Static, t } from \"alepha\";\nimport { workflowStepExecutions } from \"../entities/workflowStepExecutions.ts\";\n\nexport const workflowStepExecutionResourceSchema = t.extend(\n workflowStepExecutions.schema,\n {},\n {\n title: \"WorkflowStepExecutionResource\",\n description: \"A workflow step execution resource.\",\n },\n);\n\nexport type WorkflowStepExecutionResource = Static<\n typeof workflowStepExecutionResourceSchema\n>;\n","import { type Static, t } from \"alepha\";\nimport { workflowExecutionResourceSchema } from \"./workflowExecutionResourceSchema.ts\";\nimport { workflowStepExecutionResourceSchema } from \"./workflowStepExecutionResourceSchema.ts\";\n\nexport const workflowExecutionDetailSchema = t.extend(\n workflowExecutionResourceSchema,\n {\n steps: t.array(workflowStepExecutionResourceSchema),\n },\n {\n title: \"WorkflowExecutionDetail\",\n description: \"A workflow execution with step details.\",\n },\n);\n\nexport type WorkflowExecutionDetail = Static<\n typeof workflowExecutionDetailSchema\n>;\n","import { type Static, t } from \"alepha\";\nimport { pageQuerySchema } from \"alepha/orm\";\n\nexport const workflowExecutionQuerySchema = t.extend(pageQuerySchema, {\n workflow: t.optional(t.text({ description: \"Filter by workflow name\" })),\n status: t.optional(\n t.enum([\n \"pending\",\n \"running\",\n \"waiting_for_signal\",\n \"completed\",\n \"failed\",\n \"timed_out\",\n \"compensating\",\n \"compensated\",\n \"compensation_failed\",\n \"cancelled\",\n ]),\n ),\n from: t.optional(t.datetime({ description: \"From date (ISO)\" })),\n to: t.optional(t.datetime({ description: \"To date (ISO)\" })),\n});\n\nexport type WorkflowExecutionQuery = Static<\n typeof workflowExecutionQuerySchema\n>;\n","import { type Static, t } from \"alepha\";\n\nexport const workflowRegistrationSchema = t.object({\n name: t.text(),\n stepCount: t.integer(),\n steps: t.array(\n t.object({\n name: t.text(),\n type: t.enum([\"handler\", \"signal\", \"parallel\"]),\n hasCompensate: t.boolean(),\n hasRetry: t.boolean(),\n timeout: t.optional(t.text()),\n }),\n ),\n onError: t.enum([\"compensate\", \"fail\"]),\n timeout: t.optional(t.text()),\n priority: t.text(),\n tags: t.optional(t.array(t.text())),\n paused: t.boolean(),\n running: t.integer(),\n pending: t.integer(),\n waiting: t.integer(),\n failed: t.integer(),\n});\n\nexport type WorkflowRegistration = Static<typeof workflowRegistrationSchema>;\n","import { type Static, t } from \"alepha\";\n\nexport const workflowStatsSchema = t.object({\n registered: t.integer(),\n running: t.integer(),\n pending: t.integer(),\n waiting: t.integer(),\n completed: t.integer(),\n failed: t.integer(),\n compensated: t.integer(),\n compensationFailed: t.integer(),\n cancelled: t.integer(),\n timedOut: t.integer(),\n});\n\nexport type WorkflowStats = Static<typeof workflowStatsSchema>;\n","import { type Static, t } from \"alepha\";\nimport { logEntrySchema } from \"alepha/logger\";\nimport { $entity, db } from \"alepha/orm\";\n\nexport const workflowStepLogs = $entity({\n name: \"workflow_step_logs\",\n schema: t.object({\n id: db.primaryKey(t.uuid()),\n logs: t.array(logEntrySchema),\n }),\n});\n\nexport type WorkflowStepLogEntity = Static<typeof workflowStepLogs.schema>;\n","import { $atom, type Static, t } from \"alepha\";\n\nexport const workflowConfig = $atom({\n name: \"alepha.workflows\",\n description: \"Configuration for the workflow engine.\",\n schema: t.object({\n defaultStepTimeout: t.integer({\n description:\n \"Default step timeout (ms). Used when no per-step timeout is set.\",\n }),\n retentionDays: t.integer({\n description: \"Days to keep completed/failed workflow executions.\",\n }),\n recovery: t.object({\n staleThreshold: t.integer({\n description: \"Running step age (ms) before assumed crashed.\",\n }),\n }),\n maxConcurrentWorkflows: t.integer({\n description: \"Max concurrent running instances per workflow name.\",\n }),\n maxStepsPerWorkflow: t.integer({\n description: \"Safety limit on step count.\",\n }),\n drainTimeout: t.integer({\n description: \"Max time (ms) to wait for in-flight steps during shutdown.\",\n }),\n logMaxEntries: t.integer({\n description: \"Max log entries captured per step execution.\",\n }),\n }),\n default: {\n defaultStepTimeout: 300_000,\n retentionDays: 30,\n recovery: {\n staleThreshold: 1_800_000,\n },\n maxConcurrentWorkflows: 50,\n maxStepsPerWorkflow: 100,\n drainTimeout: 30_000,\n logMaxEntries: 100,\n },\n});\n\nexport type WorkflowConfig = Static<typeof workflowConfig.schema>;\n\ndeclare module \"alepha\" {\n interface State {\n [workflowConfig.key]: WorkflowConfig;\n }\n}\n","import {\n $hook,\n $inject,\n $state,\n Alepha,\n AlephaError,\n type Static,\n type TSchema,\n} from \"alepha\";\nimport { DateTimeProvider } from \"alepha/datetime\";\nimport { LockProvider } from \"alepha/lock\";\nimport type { LogEntry } from \"alepha/logger\";\nimport { $logger } from \"alepha/logger\";\nimport { $repository } from \"alepha/orm\";\nimport {\n type WorkflowExecutionEntity,\n type WorkflowStatus,\n workflowExecutions,\n} from \"../entities/workflowExecutions.ts\";\nimport {\n type WorkflowStepExecutionEntity,\n workflowStepExecutions,\n} from \"../entities/workflowStepExecutions.ts\";\nimport { workflowStepLogs } from \"../entities/workflowStepLogs.ts\";\nimport type {\n HandlerStep,\n WorkflowPrimitive,\n WorkflowPrimitiveOptions,\n WorkflowRetryBackoff,\n WorkflowRetryOptions,\n WorkflowStartOptions,\n} from \"../primitives/$workflow.ts\";\nimport { workflowConfig } from \"../schemas/workflowConfigAtom.ts\";\n\n// -----------------------------------------------------------------------------------------------------------------\n\nconst PRIORITY_MAP: Record<string, number> = {\n critical: 0,\n high: 1,\n normal: 2,\n low: 3,\n};\n\ninterface WorkflowRegistration {\n name: string;\n options: WorkflowPrimitiveOptions;\n}\n\nexport interface CancelOptions {\n compensate?: boolean;\n cancelledBy?: string;\n cancelledByName?: string;\n}\n\n// -----------------------------------------------------------------------------------------------------------------\n\nexport class WorkflowProvider {\n protected readonly alepha = $inject(Alepha);\n protected readonly dt = $inject(DateTimeProvider);\n protected readonly lockProvider = $inject(LockProvider);\n protected readonly config = $state(workflowConfig);\n protected readonly log = $logger();\n protected readonly executions = $repository(workflowExecutions);\n protected readonly stepExecutions = $repository(workflowStepExecutions);\n protected readonly stepLogs = $repository(workflowStepLogs);\n\n protected readonly workflows = new Map<string, WorkflowRegistration>();\n protected readonly pausedWorkflows = new Set<string>();\n protected readonly inFlight = new Set<Promise<void>>();\n protected readonly abortControllers = new Map<string, AbortController>();\n protected readonly logs = new Map<string, LogEntry[]>();\n protected stopping = false;\n\n /**\n * When set, step dispatches go through a queue.\n * Set by WorkflowJobs on start.\n */\n public stepDispatch:\n | ((\n workflowId: string,\n stepName: string,\n priority: number,\n ) => Promise<void>)\n | null = null;\n\n // --- Registration ---\n\n public register(primitive: WorkflowPrimitive<any>): void {\n if (this.workflows.has(primitive.name)) {\n throw new AlephaError(`Workflow already registered: ${primitive.name}`);\n }\n this.workflows.set(primitive.name, {\n name: primitive.name,\n options: primitive.options,\n });\n this.log.debug(`Registered workflow '${primitive.name}'`, {\n steps: primitive.options.steps.length,\n });\n }\n\n public getRegisteredWorkflows(): Map<string, WorkflowRegistration> {\n return this.workflows;\n }\n\n // --- Start ---\n\n public async start(\n workflowName: string,\n payload: unknown,\n options?: WorkflowStartOptions,\n ): Promise<string> {\n const registration = this.getRegistration(workflowName);\n const opts = registration.options;\n\n // Validate payload\n const validated = this.alepha.codec.validate(opts.schema, payload);\n\n const priority =\n PRIORITY_MAP[options?.priority ?? opts.priority ?? \"normal\"];\n const status: WorkflowStatus = options?.delay ? \"pending\" : \"running\";\n\n // Compute deadline\n let deadlineAt: string | undefined;\n if (opts.timeout) {\n deadlineAt = this.dt\n .now()\n .add(this.dt.duration(opts.timeout))\n .toISOString();\n }\n\n // Keyed deduplication\n if (options?.key) {\n const existing = await this.executions.findMany({\n where: {\n workflowName: { eq: workflowName },\n key: { eq: options.key },\n status: {\n inArray: [\n \"pending\",\n \"running\",\n \"waiting_for_signal\",\n \"compensating\",\n ],\n },\n },\n limit: 1,\n });\n if (existing.length > 0) {\n return existing[0].id;\n }\n }\n\n // Create workflow execution\n const execution = await this.executions.create({\n workflowName,\n payload: validated as Record<string, unknown>,\n status,\n priority,\n deadlineAt,\n key: options?.key,\n triggeredBy: options?.triggeredBy,\n triggeredByName: options?.triggeredByName,\n tags: options?.tags ?? opts.tags,\n startedAt: status === \"running\" ? this.dt.nowISOString() : undefined,\n });\n\n // Create step execution records\n for (let i = 0; i < opts.steps.length; i++) {\n const step = opts.steps[i];\n const retryOpts = step.retry;\n await this.stepExecutions.create({\n workflowExecutionId: execution.id,\n stepName: step.name,\n stepIndex: i,\n stepType: step.type ?? \"handler\",\n status: \"pending\",\n maxAttempts: (retryOpts?.retries ?? 0) + 1,\n });\n }\n\n this.log.info(`Started workflow '${workflowName}'`, {\n workflowId: execution.id,\n steps: opts.steps.length,\n });\n\n await this.alepha.events.emit(\n \"workflow:started\",\n {\n workflowName,\n workflowId: execution.id,\n },\n { catch: true },\n );\n\n // Dispatch first step\n if (status === \"running\" && !this.stopping) {\n const firstStep = opts.steps[0];\n if (firstStep) {\n await this.dispatchStep(execution.id, firstStep.name, priority);\n } else {\n // No steps — complete immediately\n await this.executions.updateById(execution.id, {\n status: \"completed\",\n completedAt: this.dt.nowISOString(),\n });\n }\n }\n\n return execution.id;\n }\n\n // --- Process Step ---\n\n public async processStep(\n workflowId: string,\n stepName: string,\n ): Promise<void> {\n const promise = this.processStepInner(workflowId, stepName);\n this.inFlight.add(promise);\n try {\n await promise;\n } finally {\n this.inFlight.delete(promise);\n }\n }\n\n protected async processStepInner(\n workflowId: string,\n stepName: string,\n ): Promise<void> {\n // Acquire workflow-level lock\n const lockKey = `workflow:${workflowId}`;\n const lockValue = `${crypto.randomUUID()},${this.dt.nowISOString()}`;\n const lockResult = await this.lockProvider.set(\n lockKey,\n lockValue,\n true,\n 600_000,\n );\n const [lockId] = lockResult.split(\",\");\n if (lockId !== lockValue.split(\",\")[0]) {\n this.log.debug(\n `Workflow ${workflowId} locked by another worker, skipping`,\n );\n return;\n }\n\n try {\n const workflow = await this.executions.findById(workflowId);\n if (!workflow) return;\n\n if (workflow.status !== \"running\" && workflow.status !== \"pending\") {\n return;\n }\n\n // Transition pending → running if needed\n if (workflow.status === \"pending\") {\n await this.executions.updateById(workflowId, {\n status: \"running\",\n startedAt: this.dt.nowISOString(),\n });\n }\n\n const registration = this.getRegistration(workflow.workflowName);\n const stepDef = registration.options.steps.find(\n (s) => s.name === stepName,\n );\n if (!stepDef) return;\n\n const stepExec = await this.findStepExecution(workflowId, stepName);\n if (!stepExec) return;\n\n if (stepExec.status !== \"pending\") return;\n\n // Check when() condition\n if (stepDef.when) {\n const results = await this.assembleResults(workflowId);\n const shouldRun = await stepDef.when({\n payload: workflow.payload as Static<TSchema>,\n results,\n });\n if (!shouldRun) {\n await this.stepExecutions.updateById(stepExec.id, {\n status: \"skipped\",\n completedAt: this.dt.nowISOString(),\n });\n await this.alepha.events.emit(\n \"workflow:step:skipped\",\n {\n workflowName: workflow.workflowName,\n workflowId,\n stepName,\n },\n { catch: true },\n );\n await this.advance(workflowId);\n return;\n }\n }\n\n // Handler step execution\n await this.executeHandlerStep(workflow, stepExec, stepDef as HandlerStep);\n } finally {\n await this.lockProvider.del(lockKey);\n }\n }\n\n protected async executeHandlerStep(\n workflow: WorkflowExecutionEntity,\n stepExec: WorkflowStepExecutionEntity,\n stepDef: HandlerStep,\n ): Promise<void> {\n const workflowId = workflow.id;\n const stepName = stepExec.stepName;\n\n // Claim step\n await this.stepExecutions.updateById(stepExec.id, {\n status: \"running\",\n attempt: stepExec.attempt + 1,\n startedAt: this.dt.nowISOString(),\n });\n\n await this.executions.updateById(workflowId, {\n currentStep: stepName,\n });\n\n await this.alepha.events.emit(\n \"workflow:step:begin\",\n {\n workflowName: workflow.workflowName,\n workflowId,\n stepName,\n },\n { catch: true },\n );\n\n // Set up abort controller\n const abortController = new AbortController();\n const abortKey = `${workflowId}:${stepName}`;\n this.abortControllers.set(abortKey, abortController);\n\n // Set up timeout\n const timeoutMs = stepDef.timeout\n ? this.dt.duration(stepDef.timeout).as(\"milliseconds\")\n : this.config.defaultStepTimeout;\n const timeoutId = setTimeout(() => abortController.abort(), timeoutMs);\n\n // Capture logs\n const context = this.alepha.context.createContextId();\n this.logs.set(context, []);\n\n try {\n await this.alepha.context.run(\n async () => {\n const results = await this.assembleResults(workflowId);\n\n const handlerResult = await stepDef.handler({\n payload: workflow.payload as Static<TSchema>,\n results,\n context: {\n workflowId,\n executionId: stepExec.id,\n stepName,\n attempt: stepExec.attempt + 1,\n },\n signal: abortController.signal,\n });\n\n // Success\n await this.stepExecutions.updateById(stepExec.id, {\n status: \"completed\",\n result:\n handlerResult != null\n ? (handlerResult as Record<string, unknown>)\n : undefined,\n completedAt: this.dt.nowISOString(),\n });\n\n await this.writeLogs(stepExec.id, context);\n\n this.log.info(`Workflow step '${stepName}' completed`, {\n workflowId,\n });\n\n await this.alepha.events.emit(\n \"workflow:step:completed\",\n {\n workflowName: workflow.workflowName,\n workflowId,\n stepName,\n result: handlerResult,\n },\n { catch: true },\n );\n\n // Advance to next step\n await this.advance(workflowId);\n },\n { context },\n );\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n\n await this.writeLogs(stepExec.id, context);\n\n if (abortController.signal.aborted) {\n // Timeout — treat as failure\n await this.handleStepFailure(\n workflow,\n stepExec,\n stepDef,\n new Error(\"Step timed out\"),\n context,\n );\n } else {\n await this.handleStepFailure(workflow, stepExec, stepDef, err, context);\n }\n } finally {\n clearTimeout(timeoutId);\n this.abortControllers.delete(abortKey);\n this.logs.delete(context);\n }\n }\n\n protected async handleStepFailure(\n workflow: WorkflowExecutionEntity,\n stepExec: WorkflowStepExecutionEntity,\n stepDef: HandlerStep,\n error: Error,\n _context: string,\n ): Promise<void> {\n const retryOpts = stepDef.retry;\n const canRetry =\n retryOpts &&\n stepExec.attempt + 1 < stepExec.maxAttempts &&\n (retryOpts.when ? retryOpts.when(error) : true);\n\n if (canRetry) {\n const nextScheduledAt = this.computeBackoff(\n retryOpts,\n stepExec.attempt + 1,\n );\n\n this.log.info(\n `Workflow step '${stepExec.stepName}' failed, scheduling retry`,\n { workflowId: workflow.id, error: error.message },\n );\n\n await this.stepExecutions.updateById(stepExec.id, {\n status: \"pending\",\n error: error.message,\n deadlineAt: nextScheduledAt,\n });\n\n // Schedule retry after backoff\n const delayMs = Math.max(\n 0,\n new Date(nextScheduledAt).getTime() - this.dt.nowMillis(),\n );\n this.dt.createTimeout(\n () =>\n void this.dispatchStep(\n workflow.id,\n stepExec.stepName,\n workflow.priority,\n ),\n delayMs,\n );\n } else {\n // Step exhausted — mark failed\n this.log.info(`Workflow step '${stepExec.stepName}' failed permanently`, {\n workflowId: workflow.id,\n error: error.message,\n });\n\n await this.stepExecutions.updateById(stepExec.id, {\n status: \"failed\",\n error: error.message,\n completedAt: this.dt.nowISOString(),\n });\n\n await this.alepha.events.emit(\n \"workflow:step:failed\",\n {\n workflowName: workflow.workflowName,\n workflowId: workflow.id,\n stepName: stepExec.stepName,\n error,\n },\n { catch: true },\n );\n\n // Determine error strategy\n const registration = this.getRegistration(workflow.workflowName);\n const onError = registration.options.onError ?? \"compensate\";\n\n if (onError === \"compensate\") {\n await this.compensate(workflow.id, {\n failedStep: stepExec.stepName,\n error,\n });\n } else {\n await this.executions.updateById(workflow.id, {\n status: \"failed\",\n error: error.message,\n errorStep: stepExec.stepName,\n completedAt: this.dt.nowISOString(),\n });\n\n await this.alepha.events.emit(\n \"workflow:failed\",\n {\n workflowName: workflow.workflowName,\n workflowId: workflow.id,\n error,\n stepName: stepExec.stepName,\n },\n { catch: true },\n );\n }\n }\n }\n\n // --- Advance ---\n\n protected async advance(workflowId: string): Promise<void> {\n const workflow = await this.executions.findById(workflowId);\n if (!workflow || workflow.status !== \"running\") return;\n\n const registration = this.getRegistration(workflow.workflowName);\n\n // Find next pending step by index\n const steps = await this.stepExecutions.findMany({\n where: { workflowExecutionId: { eq: workflowId } },\n orderBy: { column: \"stepIndex\", direction: \"asc\" },\n });\n\n const nextStep = steps.find((s) => s.status === \"pending\");\n\n if (nextStep) {\n await this.executions.updateById(workflowId, {\n currentStep: nextStep.stepName,\n });\n await this.dispatchStep(workflowId, nextStep.stepName, workflow.priority);\n } else {\n // All steps done\n await this.executions.updateById(workflowId, {\n status: \"completed\",\n currentStep: undefined,\n completedAt: this.dt.nowISOString(),\n key: null,\n });\n\n this.log.info(`Workflow '${workflow.workflowName}' completed`, {\n workflowId,\n });\n\n await this.alepha.events.emit(\n \"workflow:completed\",\n {\n workflowName: workflow.workflowName,\n workflowId,\n },\n { catch: true },\n );\n }\n }\n\n // --- Compensate ---\n\n public async compensate(\n workflowId: string,\n context?: { failedStep?: string; error?: Error },\n ): Promise<void> {\n const workflow = await this.executions.findById(workflowId);\n if (!workflow) throw new AlephaError(`Workflow not found: ${workflowId}`);\n\n const registration = this.getRegistration(workflow.workflowName);\n\n await this.executions.updateById(workflowId, {\n status: \"compensating\",\n error: context?.error?.message,\n errorStep: context?.failedStep,\n });\n\n await this.alepha.events.emit(\n \"workflow:compensating\",\n {\n workflowName: workflow.workflowName,\n workflowId,\n stepName: context?.failedStep ?? \"\",\n },\n { catch: true },\n );\n\n // Get completed steps in reverse order\n const completedSteps = await this.stepExecutions.findMany({\n where: {\n workflowExecutionId: { eq: workflowId },\n status: { eq: \"completed\" },\n },\n orderBy: { column: \"stepIndex\", direction: \"desc\" },\n });\n\n const results = await this.assembleResults(workflowId);\n\n for (const stepExec of completedSteps) {\n const stepDef = registration.options.steps.find(\n (s) => s.name === stepExec.stepName,\n );\n if (!stepDef?.compensate) continue;\n\n await this.stepExecutions.updateById(stepExec.id, {\n status: \"compensating\",\n });\n\n try {\n await stepDef.compensate({\n payload: workflow.payload as Static<TSchema>,\n result: stepExec.result,\n results,\n context: {\n workflowId,\n executionId: stepExec.id,\n stepName: stepExec.stepName,\n error: context?.error ?? new Error(\"Compensation triggered\"),\n },\n });\n\n await this.stepExecutions.updateById(stepExec.id, {\n status: \"compensated\",\n completedAt: this.dt.nowISOString(),\n });\n } catch (compError) {\n const err =\n compError instanceof Error ? compError : new Error(String(compError));\n\n this.log.error(`Compensation failed for step '${stepExec.stepName}'`, {\n workflowId,\n error: err.message,\n });\n\n await this.stepExecutions.updateById(stepExec.id, {\n status: \"compensation_failed\",\n error: err.message,\n });\n\n await this.executions.updateById(workflowId, {\n status: \"compensation_failed\",\n completedAt: this.dt.nowISOString(),\n key: null,\n });\n\n await this.alepha.events.emit(\n \"workflow:compensation:failed\",\n {\n workflowName: workflow.workflowName,\n workflowId,\n stepName: stepExec.stepName,\n error: err,\n },\n { catch: true },\n );\n\n return;\n }\n }\n\n // All compensations succeeded\n await this.executions.updateById(workflowId, {\n status: \"compensated\",\n completedAt: this.dt.nowISOString(),\n key: null,\n });\n\n this.log.info(`Workflow '${workflow.workflowName}' compensated`, {\n workflowId,\n });\n\n await this.alepha.events.emit(\n \"workflow:compensated\",\n {\n workflowName: workflow.workflowName,\n workflowId,\n },\n { catch: true },\n );\n }\n\n // --- Cancel ---\n\n public async cancel(\n workflowId: string,\n options?: CancelOptions,\n ): Promise<void> {\n const workflow = await this.executions.findById(workflowId);\n if (!workflow) throw new AlephaError(`Workflow not found: ${workflowId}`);\n\n if (\n workflow.status !== \"pending\" &&\n workflow.status !== \"running\" &&\n workflow.status !== \"waiting_for_signal\"\n ) {\n throw new AlephaError(\n `Cannot cancel workflow in '${workflow.status}' status`,\n );\n }\n\n // Abort any running step\n for (const [key, controller] of this.abortControllers) {\n if (key.startsWith(`${workflowId}:`)) {\n controller.abort();\n }\n }\n\n // Cancel all pending/waiting steps\n const pendingSteps = await this.stepExecutions.findMany({\n where: {\n workflowExecutionId: { eq: workflowId },\n status: { inArray: [\"pending\", \"waiting\"] },\n },\n });\n for (const step of pendingSteps) {\n await this.stepExecutions.updateById(step.id, { status: \"cancelled\" });\n }\n\n if (options?.compensate) {\n await this.compensate(workflowId, {\n error: new Error(\"Cancelled with compensation\"),\n });\n // After compensation, mark as cancelled (override compensated status)\n await this.executions.updateById(workflowId, {\n status: \"cancelled\",\n cancelledBy: options?.cancelledBy,\n cancelledByName: options?.cancelledByName,\n });\n } else {\n await this.executions.updateById(workflowId, {\n status: \"cancelled\",\n cancelledBy: options?.cancelledBy,\n cancelledByName: options?.cancelledByName,\n completedAt: this.dt.nowISOString(),\n key: null,\n });\n }\n\n this.log.info(`Workflow cancelled`, { workflowId });\n\n await this.alepha.events.emit(\n \"workflow:cancelled\",\n {\n workflowName: workflow.workflowName,\n workflowId,\n },\n { catch: true },\n );\n }\n\n // --- Signal ---\n\n /**\n * Send a signal to a waiting workflow step.\n */\n public async signal(\n workflowId: string,\n stepName: string,\n payload?: unknown,\n signalledBy?: string,\n ): Promise<void> {\n const workflow = await this.executions.findById(workflowId);\n if (!workflow) throw new AlephaError(`Workflow not found: ${workflowId}`);\n\n if (workflow.status !== \"waiting_for_signal\") {\n throw new AlephaError(\n `Cannot signal workflow in '${workflow.status}' status`,\n );\n }\n\n const stepExec = await this.findStepExecution(workflowId, stepName);\n if (!stepExec) {\n throw new AlephaError(\n `Step '${stepName}' not found on workflow ${workflowId}`,\n );\n }\n\n if (stepExec.status !== \"waiting\") {\n throw new AlephaError(\n `Step '${stepName}' is in '${stepExec.status}' status, expected 'waiting'`,\n );\n }\n\n await this.stepExecutions.updateById(stepExec.id, {\n status: \"completed\",\n signalPayload:\n payload != null ? (payload as Record<string, unknown>) : undefined,\n signalledBy,\n signalledAt: this.dt.nowISOString(),\n completedAt: this.dt.nowISOString(),\n });\n\n // Resume workflow\n await this.executions.updateById(workflowId, {\n status: \"running\",\n });\n\n this.log.info(`Workflow signalled step '${stepName}'`, { workflowId });\n\n // Advance to next step\n await this.advance(workflowId);\n }\n\n // --- Retry ---\n\n public async retry(workflowId: string): Promise<void> {\n const workflow = await this.executions.findById(workflowId);\n if (!workflow) throw new AlephaError(`Workflow not found: ${workflowId}`);\n\n if (workflow.status !== \"failed\" && workflow.status !== \"timed_out\") {\n throw new AlephaError(\n `Cannot retry workflow in '${workflow.status}' status. Use restart() for compensated workflows.`,\n );\n }\n\n // Find the failed step\n const failedStep = await this.stepExecutions.findMany({\n where: {\n workflowExecutionId: { eq: workflowId },\n status: { eq: \"failed\" },\n },\n limit: 1,\n });\n\n if (failedStep.length === 0) {\n throw new AlephaError(\"No failed step found to retry\");\n }\n\n // Reset the failed step\n await this.stepExecutions.updateById(failedStep[0].id, {\n status: \"pending\",\n error: undefined,\n startedAt: undefined,\n completedAt: undefined,\n });\n\n // Resume workflow\n await this.executions.updateById(workflowId, {\n status: \"running\",\n error: undefined,\n errorStep: undefined,\n completedAt: undefined,\n });\n\n await this.dispatchStep(\n workflowId,\n failedStep[0].stepName,\n workflow.priority,\n );\n }\n\n // --- Restart ---\n\n public async restart(workflowId: string): Promise<string> {\n const workflow = await this.executions.findById(workflowId);\n if (!workflow) throw new AlephaError(`Workflow not found: ${workflowId}`);\n\n if (\n workflow.status !== \"compensated\" &&\n workflow.status !== \"compensation_failed\" &&\n workflow.status !== \"failed\"\n ) {\n throw new AlephaError(\n `Cannot restart workflow in '${workflow.status}' status`,\n );\n }\n\n return this.start(workflow.workflowName, workflow.payload);\n }\n\n // --- Query ---\n\n public async getExecution(workflowId: string) {\n const workflow = await this.executions.findById(workflowId);\n if (!workflow) throw new AlephaError(`Workflow not found: ${workflowId}`);\n\n const steps = await this.stepExecutions.findMany({\n where: { workflowExecutionId: { eq: workflowId } },\n orderBy: { column: \"stepIndex\", direction: \"asc\" },\n });\n\n return { ...workflow, steps };\n }\n\n // --- Pause / Resume ---\n\n public pauseWorkflow(name: string): void {\n this.getRegistration(name);\n this.pausedWorkflows.add(name);\n this.log.info(`Paused workflow '${name}'`);\n }\n\n public async resumeWorkflow(name: string): Promise<void> {\n this.getRegistration(name);\n this.pausedWorkflows.delete(name);\n this.log.info(`Resumed workflow '${name}'`);\n }\n\n public isWorkflowPaused(name: string): boolean {\n return this.pausedWorkflows.has(name);\n }\n\n public getPausedWorkflows(): string[] {\n return [...this.pausedWorkflows];\n }\n\n // --- Internal dispatch ---\n\n protected async dispatchStep(\n workflowId: string,\n stepName: string,\n priority: number,\n ): Promise<void> {\n if (this.stopping) return;\n\n if (this.stepDispatch) {\n await this.stepDispatch(workflowId, stepName, priority);\n } else {\n await this.processStep(workflowId, stepName);\n }\n }\n\n // --- Helpers ---\n\n protected async assembleResults(\n workflowId: string,\n ): Promise<Record<string, unknown>> {\n const completed = await this.stepExecutions.findMany({\n where: {\n workflowExecutionId: { eq: workflowId },\n status: { eq: \"completed\" },\n },\n orderBy: { column: \"stepIndex\", direction: \"asc\" },\n });\n const results: Record<string, unknown> = {};\n for (const step of completed) {\n if (step.result) results[step.stepName] = step.result;\n }\n return results;\n }\n\n protected async findStepExecution(\n workflowId: string,\n stepName: string,\n ): Promise<WorkflowStepExecutionEntity | undefined> {\n const rows = await this.stepExecutions.findMany({\n where: {\n workflowExecutionId: { eq: workflowId },\n stepName: { eq: stepName },\n },\n limit: 1,\n });\n return rows[0];\n }\n\n protected computeBackoff(\n retryOpts: WorkflowRetryOptions,\n attempt: number,\n ): string {\n const now = this.dt.now();\n\n if (!retryOpts.backoff) {\n return now.add(1, \"second\").toISOString();\n }\n\n if (Array.isArray(retryOpts.backoff)) {\n const delay = this.dt.duration(retryOpts.backoff);\n return now.add(delay).toISOString();\n }\n\n const backoff = retryOpts.backoff as WorkflowRetryBackoff;\n const initial = this.dt.duration(backoff.initial).as(\"milliseconds\");\n const factor = backoff.factor ?? 2;\n let delayMs = initial * factor ** (attempt - 1);\n\n if (backoff.max) {\n const maxMs = this.dt.duration(backoff.max).as(\"milliseconds\");\n delayMs = Math.min(delayMs, maxMs);\n }\n\n if (backoff.jitter) {\n delayMs = delayMs * (0.75 + Math.random() * 0.5);\n }\n\n return now.add(delayMs, \"millisecond\").toISOString();\n }\n\n protected async writeLogs(\n stepExecutionId: string,\n context: string,\n ): Promise<void> {\n const entries = this.logs.get(context);\n if (!entries || entries.length === 0) return;\n\n const maxEntries = this.config.logMaxEntries;\n if (maxEntries === 0) return;\n\n let logs = entries;\n if (logs.length > maxEntries) {\n logs = logs.slice(0, maxEntries);\n logs.push({\n level: \"WARN\",\n message: `Log entries truncated at ${maxEntries}`,\n timestamp: this.dt.nowMillis(),\n service: \"alepha.workflows\",\n module: \"WorkflowProvider\",\n } as LogEntry);\n }\n\n try {\n await this.stepLogs.create({ id: stepExecutionId, logs });\n } catch {\n this.log.warn(`Failed to write logs for step ${stepExecutionId}`);\n }\n }\n\n protected getRegistration(name: string): WorkflowRegistration {\n const reg = this.workflows.get(name);\n if (!reg) throw new AlephaError(`Workflow not registered: ${name}`);\n return reg;\n }\n\n // --- Sweeps ---\n\n public async recoverySweep(): Promise<void> {\n if (this.stopping) return;\n\n const lockValue = `${crypto.randomUUID()},${this.dt.nowISOString()}`;\n const result = await this.lockProvider.set(\n \"_alepha:workflows:recovery-lock\",\n lockValue,\n true,\n 300_000,\n );\n if (result.split(\",\")[0] !== lockValue.split(\",\")[0]) return;\n\n try {\n const staleThreshold = this.dt\n .now()\n .subtract(this.config.recovery.staleThreshold, \"millisecond\")\n .toISOString();\n\n // Find stale running steps\n const staleSteps = await this.stepExecutions.findMany({\n where: {\n status: { eq: \"running\" },\n startedAt: { lte: staleThreshold },\n },\n });\n\n for (const step of staleSteps) {\n if (\n this.abortControllers.has(\n `${step.workflowExecutionId}:${step.stepName}`,\n )\n ) {\n continue;\n }\n\n this.log.warn(\n `Recovery sweep: marking stale step '${step.stepName}' as failed`,\n { workflowId: step.workflowExecutionId },\n );\n\n await this.stepExecutions.updateById(step.id, {\n status: \"failed\",\n error: \"Step assumed crashed (recovered by sweep)\",\n completedAt: this.dt.nowISOString(),\n });\n\n const workflow = await this.executions.findById(\n step.workflowExecutionId,\n );\n if (!workflow) continue;\n\n const registration = this.workflows.get(workflow.workflowName);\n if (!registration) continue;\n\n const onError = registration.options.onError ?? \"compensate\";\n if (onError === \"compensate\") {\n await this.compensate(workflow.id, {\n failedStep: step.stepName,\n error: new Error(\"Step assumed crashed\"),\n });\n } else {\n await this.executions.updateById(workflow.id, {\n status: \"failed\",\n error: \"Step assumed crashed\",\n errorStep: step.stepName,\n completedAt: this.dt.nowISOString(),\n });\n }\n }\n\n // Find inconsistent workflows (running but no active steps)\n const runningWorkflows = await this.executions.findMany({\n where: { status: { eq: \"running\" } },\n });\n\n for (const wf of runningWorkflows) {\n const activeSteps = await this.stepExecutions.findMany({\n where: {\n workflowExecutionId: { eq: wf.id },\n status: { inArray: [\"running\", \"pending\"] },\n },\n limit: 1,\n });\n\n if (activeSteps.length === 0) {\n this.log.warn(\"Recovery sweep: re-advancing inconsistent workflow\", {\n workflowId: wf.id,\n });\n await this.advance(wf.id);\n }\n }\n } catch (e) {\n this.log.error(\"Recovery sweep failed\", { error: e });\n } finally {\n await this.lockProvider.del(\"_alepha:workflows:recovery-lock\");\n }\n }\n\n public async timeoutSweep(): Promise<void> {\n if (this.stopping) return;\n\n const lockValue = `${crypto.randomUUID()},${this.dt.nowISOString()}`;\n const result = await this.lockProvider.set(\n \"_alepha:workflows:timeout-lock\",\n lockValue,\n true,\n 60_000,\n );\n if (result.split(\",\")[0] !== lockValue.split(\",\")[0]) return;\n\n try {\n const now = this.dt.nowISOString();\n\n // Workflow-level timeouts\n const timedOutWorkflows = await this.executions.findMany({\n where: {\n status: { inArray: [\"running\", \"waiting_for_signal\"] },\n deadlineAt: { lte: now },\n },\n });\n\n for (const wf of timedOutWorkflows) {\n this.log.warn(`Timeout sweep: workflow timed out`, {\n workflowId: wf.id,\n });\n\n // Abort any running step\n for (const [key, controller] of this.abortControllers) {\n if (key.startsWith(`${wf.id}:`)) controller.abort();\n }\n\n // Mark running steps as failed\n await this.stepExecutions.updateMany(\n {\n workflowExecutionId: { eq: wf.id },\n status: { inArray: [\"running\", \"waiting\"] },\n },\n {\n status: \"failed\",\n error: \"Workflow timed out\",\n completedAt: now,\n },\n );\n\n await this.executions.updateById(wf.id, {\n status: \"timed_out\",\n completedAt: now,\n });\n\n await this.alepha.events.emit(\n \"workflow:timed_out\",\n {\n workflowName: wf.workflowName,\n workflowId: wf.id,\n },\n { catch: true },\n );\n\n const reg = this.workflows.get(wf.workflowName);\n if (reg?.options.onError === \"compensate\") {\n await this.compensate(wf.id, {\n error: new Error(\"Workflow timed out\"),\n });\n }\n }\n } catch (e) {\n this.log.error(\"Timeout sweep failed\", { error: e });\n } finally {\n await this.lockProvider.del(\"_alepha:workflows:timeout-lock\");\n }\n }\n\n public async purge(): Promise<void> {\n if (this.stopping) return;\n try {\n const cutoff = this.dt\n .now()\n .subtract(this.config.retentionDays, \"day\")\n .toISOString();\n\n const terminalStatuses: WorkflowStatus[] = [\n \"completed\",\n \"failed\",\n \"compensated\",\n \"compensation_failed\",\n \"cancelled\",\n \"timed_out\",\n ];\n\n const old = await this.executions.findMany({\n where: {\n status: { inArray: terminalStatuses },\n completedAt: { lte: cutoff },\n },\n });\n\n if (old.length > 0) {\n const ids = old.map((e) => e.id);\n // Step logs and step executions cascade-delete with the workflow\n await this.executions.deleteMany({ id: { inArray: ids } });\n this.log.info(`Purge: deleted ${ids.length} old workflow executions`);\n }\n } catch (e) {\n this.log.error(\"Purge failed\", { error: e });\n }\n }\n\n // --- Lifecycle ---\n\n protected readonly onStart = $hook({\n on: \"start\",\n handler: async () => {\n this.log.info(\"Workflow engine OK\", {\n dispatch: this.stepDispatch ? \"queue\" : \"inline\",\n workflows: this.workflows.size,\n });\n\n // Log capture listener\n this.alepha.events.on(\"log\", ({ entry }) => {\n const ctx = entry.context;\n if (!ctx) return;\n const entries = this.logs.get(ctx);\n if (!entries) return;\n entries.push(entry);\n });\n },\n });\n\n protected readonly onStop = $hook({\n on: \"stop\",\n handler: async () => {\n this.stopping = true;\n\n if (this.inFlight.size > 0) {\n this.log.info(`Draining ${this.inFlight.size} in-flight step(s)...`);\n await Promise.race([\n Promise.allSettled([...this.inFlight]),\n this.dt.wait([this.config.drainTimeout, \"millisecond\"]),\n ]);\n }\n\n if (this.abortControllers.size > 0) {\n this.log.warn(\n `Aborting ${this.abortControllers.size} remaining step(s)`,\n );\n for (const controller of this.abortControllers.values()) {\n controller.abort();\n }\n }\n },\n });\n}\n","import { $inject, Alepha, t } from \"alepha\";\nimport { DateTimeProvider } from \"alepha/datetime\";\nimport { $logger } from \"alepha/logger\";\nimport { $repository, DatabaseProvider, sql } from \"alepha/orm\";\nimport { NotFoundError } from \"alepha/server\";\nimport type { WorkflowExecutionEntity } from \"../entities/workflowExecutions.ts\";\nimport { workflowExecutions } from \"../entities/workflowExecutions.ts\";\nimport { workflowStepExecutions } from \"../entities/workflowStepExecutions.ts\";\nimport { WorkflowProvider } from \"../providers/WorkflowProvider.ts\";\nimport type { WorkflowActivityPoint } from \"../schemas/workflowActivitySchema.ts\";\nimport type { WorkflowExecutionQuery } from \"../schemas/workflowExecutionQuerySchema.ts\";\nimport type { WorkflowExecutionCan } from \"../schemas/workflowExecutionResourceSchema.ts\";\nimport type { WorkflowRegistration } from \"../schemas/workflowRegistrationSchema.ts\";\nimport type { WorkflowStats } from \"../schemas/workflowStatsSchema.ts\";\n\n// -----------------------------------------------------------------------------------------------------------------\n\nexport class WorkflowService {\n protected readonly alepha = $inject(Alepha);\n protected readonly dt = $inject(DateTimeProvider);\n protected readonly log = $logger();\n protected readonly workflowProvider = $inject(WorkflowProvider);\n protected readonly database = $inject(DatabaseProvider);\n protected readonly executions = $repository(workflowExecutions);\n protected readonly stepExecutions = $repository(workflowStepExecutions);\n\n /**\n * Compute available actions for a workflow execution based on its status.\n */\n protected computeCan(\n status: string,\n signalStepName?: string,\n ): WorkflowExecutionCan {\n return {\n retry: status === \"failed\" || status === \"timed_out\",\n cancel:\n status === \"pending\" ||\n status === \"running\" ||\n status === \"waiting_for_signal\",\n compensate: status === \"failed\" || status === \"timed_out\",\n restart:\n status === \"failed\" ||\n status === \"compensated\" ||\n status === \"compensation_failed\",\n signal: signalStepName ? { stepName: signalStepName } : undefined,\n };\n }\n\n /**\n * Convert an ISO date string to the raw SQL parameter format\n * expected by the current database dialect.\n *\n * - PostgreSQL: ISO string (timestamp comparison)\n * - SQLite: epoch milliseconds (integer comparison)\n */\n protected toRawDate(iso: string): string | number {\n return this.database.dialect === \"sqlite\" ? new Date(iso).getTime() : iso;\n }\n\n /**\n * Get aggregate stats for the workflow engine.\n */\n public async getStats(days?: number): Promise<WorkflowStats> {\n const workflows = this.workflowProvider.getRegisteredWorkflows();\n const periodAgo = this.toRawDate(\n this.dt\n .now()\n .subtract(days ?? 1, \"day\")\n .toISOString(),\n );\n\n const rows = await this.executions.query(\n (e) => sql`\n SELECT\n COUNT(*) FILTER (WHERE ${e.status} = 'running') AS running,\n COUNT(*) FILTER (WHERE ${e.status} = 'pending') AS pending,\n COUNT(*) FILTER (WHERE ${e.status} = 'waiting_for_signal') AS waiting,\n COUNT(*) FILTER (WHERE ${e.status} = 'completed' AND ${e.completedAt} >= ${periodAgo}) AS completed,\n COUNT(*) FILTER (WHERE ${e.status} = 'failed' AND ${e.completedAt} >= ${periodAgo}) AS failed,\n COUNT(*) FILTER (WHERE ${e.status} = 'compensated' AND ${e.completedAt} >= ${periodAgo}) AS compensated,\n COUNT(*) FILTER (WHERE ${e.status} = 'compensation_failed' AND ${e.completedAt} >= ${periodAgo}) AS compensation_failed,\n COUNT(*) FILTER (WHERE ${e.status} = 'cancelled' AND ${e.completedAt} >= ${periodAgo}) AS cancelled,\n COUNT(*) FILTER (WHERE ${e.status} = 'timed_out' AND ${e.completedAt} >= ${periodAgo}) AS timed_out\n FROM ${e}\n `,\n t.object({\n running: t.string(),\n pending: t.string(),\n waiting: t.string(),\n completed: t.string(),\n failed: t.string(),\n compensated: t.string(),\n compensation_failed: t.string(),\n cancelled: t.string(),\n timed_out: t.string(),\n }),\n );\n\n const row = rows[0];\n return {\n registered: workflows.size,\n running: Number(row.running),\n pending: Number(row.pending),\n waiting: Number(row.waiting),\n completed: Number(row.completed),\n failed: Number(row.failed),\n compensated: Number(row.compensated),\n compensationFailed: Number(row.compensation_failed),\n cancelled: Number(row.cancelled),\n timedOut: Number(row.timed_out),\n };\n }\n\n /**\n * Get the full workflow registry with live counts.\n */\n public async getRegistry(): Promise<WorkflowRegistration[]> {\n const workflows = this.workflowProvider.getRegisteredWorkflows();\n const names = [...workflows.keys()];\n\n // Get live counts per workflow name\n const countRows =\n names.length > 0\n ? await this.executions.query(\n (e) => sql`\n SELECT\n ${e.workflowName} AS workflow_name,\n COUNT(*) FILTER (WHERE ${e.status} = 'running') AS running,\n COUNT(*) FILTER (WHERE ${e.status} = 'pending') AS pending,\n COUNT(*) FILTER (WHERE ${e.status} = 'waiting_for_signal') AS waiting,\n COUNT(*) FILTER (WHERE ${e.status} = 'failed') AS failed\n FROM ${e}\n WHERE ${e.workflowName} IN (${sql.join(\n names.map((n) => sql`${n}`),\n sql`, `,\n )})\n GROUP BY ${e.workflowName}\n `,\n t.object({\n workflow_name: t.string(),\n running: t.string(),\n pending: t.string(),\n waiting: t.string(),\n failed: t.string(),\n }),\n )\n : [];\n\n const countsByName = new Map(countRows.map((r) => [r.workflow_name, r]));\n\n const result: WorkflowRegistration[] = [];\n\n for (const [name, reg] of workflows) {\n const opts = reg.options;\n const counts = countsByName.get(name);\n\n result.push({\n name,\n stepCount: opts.steps.length,\n steps: opts.steps.map((step) => ({\n name: step.name,\n type: step.type ?? \"handler\",\n hasCompensate: Boolean(step.compensate),\n hasRetry: Boolean(step.retry),\n timeout: step.timeout ? String(step.timeout) : undefined,\n })),\n onError: opts.onError ?? \"compensate\",\n timeout: opts.timeout ? String(opts.timeout) : undefined,\n priority: opts.priority ?? \"normal\",\n tags: opts.tags,\n paused: this.workflowProvider.isWorkflowPaused(name),\n running: Number(counts?.running ?? 0),\n pending: Number(counts?.pending ?? 0),\n waiting: Number(counts?.waiting ?? 0),\n failed: Number(counts?.failed ?? 0),\n });\n }\n\n return result;\n }\n\n /**\n * Paginated query for workflow executions.\n */\n public async findExecutions(query: WorkflowExecutionQuery = {}) {\n query.sort ??= \"-createdAt\";\n\n const where = this.executions.createQueryWhere();\n\n if (query.workflow) {\n where.workflowName = { eq: query.workflow };\n }\n\n if (query.status) {\n where.status = { eq: query.status };\n }\n\n if (query.from) {\n where.createdAt = { gte: query.from };\n }\n\n if (query.to) {\n where.createdAt = {\n ...(where.createdAt as object),\n lte: query.to,\n };\n }\n\n const page = await this.executions.paginate(\n query,\n { where },\n { count: true },\n );\n return {\n ...page,\n content: page.content.map((exec: WorkflowExecutionEntity) => ({\n ...exec,\n can: this.computeCan(exec.status),\n })),\n };\n }\n\n /**\n * Get a single workflow execution with step details.\n */\n public async getExecution(id: string) {\n const execution = await this.executions.findById(id);\n if (!execution) {\n throw new NotFoundError(`Workflow execution not found: ${id}`);\n }\n\n const steps = await this.stepExecutions.findMany({\n where: { workflowExecutionId: { eq: id } },\n orderBy: { column: \"stepIndex\", direction: \"asc\" },\n });\n\n // Determine signal step name if workflow is waiting\n let signalStepName: string | undefined;\n if (execution.status === \"waiting_for_signal\") {\n const waitingStep = steps.find((s) => s.status === \"waiting\");\n if (waitingStep) {\n signalStepName = waitingStep.stepName;\n }\n }\n\n return {\n ...execution,\n can: this.computeCan(execution.status, signalStepName),\n steps,\n };\n }\n\n /**\n * Get daily activity (completed/failed) over a date range.\n */\n public async getActivity(days = 14): Promise<WorkflowActivityPoint[]> {\n const rows = await this.executions.query(\n (e) => sql`\n WITH date_series AS (\n SELECT generate_series(\n CURRENT_DATE - ${days - 1}::int,\n CURRENT_DATE,\n '1 day'::interval\n )::date AS date\n )\n SELECT\n ds.date::text AS date,\n COALESCE(COUNT(*) FILTER (WHERE ${e.status} = 'completed'), 0) AS completed,\n COALESCE(COUNT(*) FILTER (WHERE ${e.status} = 'failed'), 0) AS failed\n FROM date_series ds\n LEFT JOIN ${e} ON DATE(${e.completedAt}) = ds.date\n AND ${e.status} IN ('completed', 'failed')\n GROUP BY ds.date\n ORDER BY ds.date ASC\n `,\n t.object({\n date: t.string(),\n completed: t.string(),\n failed: t.string(),\n }),\n );\n\n return rows.map((row) => ({\n date: row.date,\n completed: Number(row.completed),\n failed: Number(row.failed),\n }));\n }\n\n /**\n * Start a new workflow execution by name.\n */\n public async triggerWorkflow(\n name: string,\n payload?: Record<string, unknown>,\n options?: {\n key?: string;\n tags?: string[];\n triggeredBy?: string;\n triggeredByName?: string;\n },\n ): Promise<{ id: string }> {\n this.log.info(`Triggering workflow '${name}'`, {\n triggeredBy: options?.triggeredByName ?? options?.triggeredBy,\n });\n\n const id = await this.workflowProvider.start(name, payload ?? {}, {\n key: options?.key,\n tags: options?.tags,\n triggeredBy: options?.triggeredBy,\n triggeredByName: options?.triggeredByName,\n });\n\n return { id };\n }\n\n /**\n * Cancel a running workflow execution.\n */\n public async cancelExecution(\n id: string,\n context?: {\n compensate?: boolean;\n cancelledBy?: string;\n cancelledByName?: string;\n },\n ): Promise<{ ok: boolean }> {\n this.log.info(`Cancelling workflow execution ${id}`, {\n cancelledBy: context?.cancelledByName ?? context?.cancelledBy,\n });\n\n await this.workflowProvider.cancel(id, {\n compensate: context?.compensate,\n cancelledBy: context?.cancelledBy,\n cancelledByName: context?.cancelledByName,\n });\n return { ok: true };\n }\n\n /**\n * Retry a failed/timed-out workflow from the failed step.\n */\n public async retryExecution(id: string): Promise<{ ok: boolean }> {\n this.log.info(`Retrying workflow execution ${id}`);\n await this.workflowProvider.retry(id);\n return { ok: true };\n }\n\n /**\n * Restart a terminal workflow as a new execution.\n */\n public async restartExecution(id: string): Promise<{ id: string }> {\n this.log.info(`Restarting workflow execution ${id}`);\n const newId = await this.workflowProvider.restart(id);\n return { id: newId };\n }\n\n /**\n * Trigger compensation on a failed/timed-out workflow.\n */\n public async compensateExecution(id: string): Promise<{ ok: boolean }> {\n this.log.info(`Compensating workflow execution ${id}`);\n await this.workflowProvider.compensate(id);\n return { ok: true };\n }\n\n /**\n * Send a signal to a waiting workflow step.\n */\n public async signalExecution(\n id: string,\n stepName: string,\n payload?: Record<string, unknown>,\n signalledBy?: string,\n ): Promise<{ ok: boolean }> {\n this.log.info(`Signalling workflow execution ${id} step '${stepName}'`, {\n signalledBy,\n });\n await this.workflowProvider.signal(id, stepName, payload);\n return { ok: true };\n }\n}\n","import { $inject, t } from \"alepha\";\nimport { $secure } from \"alepha/security\";\nimport { $action, okSchema } from \"alepha/server\";\nimport {\n workflowActivityPointSchema,\n workflowActivityQuerySchema,\n} from \"../schemas/workflowActivitySchema.ts\";\nimport { workflowExecutionDetailSchema } from \"../schemas/workflowExecutionDetailSchema.ts\";\nimport { workflowExecutionQuerySchema } from \"../schemas/workflowExecutionQuerySchema.ts\";\nimport { workflowExecutionResourceSchema } from \"../schemas/workflowExecutionResourceSchema.ts\";\nimport { workflowRegistrationSchema } from \"../schemas/workflowRegistrationSchema.ts\";\nimport { workflowStatsSchema } from \"../schemas/workflowStatsSchema.ts\";\nimport { WorkflowService } from \"../services/WorkflowService.ts\";\n\nexport class AdminWorkflowController {\n protected readonly url: string = \"/workflows\";\n protected readonly group: string = \"admin:workflows\";\n protected readonly workflowService = $inject(WorkflowService);\n\n public readonly getRegistry = $action({\n path: this.url,\n group: this.group,\n use: [$secure({ permissions: [\"admin:workflow:read\"] })],\n schema: {\n response: t.array(workflowRegistrationSchema),\n },\n handler: () => this.workflowService.getRegistry(),\n });\n\n public readonly getStats = $action({\n path: `${this.url}/stats`,\n group: this.group,\n use: [$secure({ permissions: [\"admin:workflow:read\"] })],\n schema: {\n query: workflowActivityQuerySchema,\n response: workflowStatsSchema,\n },\n handler: ({ query }) => this.workflowService.getStats(query.days),\n });\n\n public readonly getActivity = $action({\n path: `${this.url}/activity`,\n group: this.group,\n use: [$secure({ permissions: [\"admin:workflow:read\"] })],\n schema: {\n query: workflowActivityQuerySchema,\n response: t.array(workflowActivityPointSchema),\n },\n handler: ({ query }) => this.workflowService.getActivity(query.days),\n });\n\n public readonly findExecutions = $action({\n path: `${this.url}/executions`,\n group: this.group,\n use: [$secure({ permissions: [\"admin:workflow:read\"] })],\n schema: {\n query: workflowExecutionQuerySchema,\n response: t.page(workflowExecutionResourceSchema),\n },\n handler: ({ query }) => this.workflowService.findExecutions(query),\n });\n\n public readonly getExecution = $action({\n path: `${this.url}/executions/:id`,\n group: this.group,\n use: [$secure({ permissions: [\"admin:workflow:read\"] })],\n schema: {\n params: t.object({\n id: t.uuid(),\n }),\n response: workflowExecutionDetailSchema,\n },\n handler: ({ params }) => this.workflowService.getExecution(params.id),\n });\n\n public readonly startWorkflow = $action({\n method: \"POST\",\n path: `${this.url}/start`,\n group: this.group,\n use: [$secure({ permissions: [\"admin:workflow:create\"] })],\n schema: {\n body: t.object({\n name: t.text(),\n payload: t.optional(t.record(t.text(), t.any())),\n key: t.optional(t.text()),\n tags: t.optional(t.array(t.text())),\n }),\n response: t.object({ id: t.uuid() }),\n },\n handler: async ({ body, user }) => {\n return this.workflowService.triggerWorkflow(body.name, body.payload, {\n key: body.key,\n tags: body.tags,\n triggeredBy: user?.id,\n triggeredByName: user?.name,\n });\n },\n });\n\n public readonly signalStep = $action({\n method: \"POST\",\n path: `${this.url}/executions/:id/signal`,\n group: this.group,\n use: [$secure({ permissions: [\"admin:workflow:update\"] })],\n schema: {\n params: t.object({\n id: t.uuid(),\n }),\n body: t.object({\n stepName: t.text(),\n payload: t.optional(t.record(t.text(), t.any())),\n }),\n response: okSchema,\n },\n handler: async ({ params, body, user }) => {\n return this.workflowService.signalExecution(\n params.id,\n body.stepName,\n body.payload,\n user?.id,\n );\n },\n });\n\n public readonly cancelExecution = $action({\n method: \"POST\",\n path: `${this.url}/executions/:id/cancel`,\n group: this.group,\n use: [$secure({ permissions: [\"admin:workflow:update\"] })],\n schema: {\n params: t.object({\n id: t.uuid(),\n }),\n response: okSchema,\n },\n handler: async ({ params, user }) => {\n return this.workflowService.cancelExecution(params.id, {\n cancelledBy: user?.id,\n cancelledByName: user?.name,\n });\n },\n });\n\n public readonly retryExecution = $action({\n method: \"POST\",\n path: `${this.url}/executions/:id/retry`,\n group: this.group,\n use: [$secure({ permissions: [\"admin:workflow:update\"] })],\n schema: {\n params: t.object({\n id: t.uuid(),\n }),\n response: okSchema,\n },\n handler: async ({ params }) => {\n return this.workflowService.retryExecution(params.id);\n },\n });\n\n public readonly restartExecution = $action({\n method: \"POST\",\n path: `${this.url}/executions/:id/restart`,\n group: this.group,\n use: [$secure({ permissions: [\"admin:workflow:create\"] })],\n schema: {\n params: t.object({\n id: t.uuid(),\n }),\n response: t.object({ id: t.uuid() }),\n },\n handler: async ({ params }) => {\n return this.workflowService.restartExecution(params.id);\n },\n });\n\n public readonly compensateExecution = $action({\n method: \"POST\",\n path: `${this.url}/executions/:id/compensate`,\n group: this.group,\n use: [$secure({ permissions: [\"admin:workflow:update\"] })],\n schema: {\n params: t.object({\n id: t.uuid(),\n }),\n response: okSchema,\n },\n handler: async ({ params }) => {\n return this.workflowService.compensateExecution(params.id);\n },\n });\n}\n","import { $hook, $inject, t } from \"alepha\";\nimport { $job } from \"alepha/api/jobs\";\nimport { WorkflowProvider } from \"../providers/WorkflowProvider.ts\";\n\n// -----------------------------------------------------------------------------------------------------------------\n\nexport class WorkflowJobs {\n protected readonly workflowProvider = $inject(WorkflowProvider);\n\n protected readonly dispatchStep = $job({\n schema: t.object({\n workflowId: t.uuid(),\n stepName: t.text(),\n }),\n retry: { retries: 2, backoff: [1, \"second\"] },\n timeout: [10, \"minute\"],\n concurrency: 10,\n handler: async ({ items }) => {\n for (const item of items) {\n await this.workflowProvider.processStep(\n item.payload.workflowId,\n item.payload.stepName,\n );\n }\n },\n });\n\n protected readonly timeoutSweep = $job({\n cron: \"* * * * *\",\n lock: true,\n handler: async () => {\n await this.workflowProvider.timeoutSweep();\n },\n });\n\n protected readonly purge = $job({\n cron: \"0 3 * * *\",\n lock: true,\n handler: async () => {\n await this.workflowProvider.purge();\n },\n });\n\n protected readonly recoverySweep = $job({\n cron: \"*/5 * * * *\",\n lock: true,\n handler: async () => {\n await this.workflowProvider.recoverySweep();\n },\n });\n\n protected readonly onStart = $hook({\n on: \"start\",\n handler: async () => {\n // Wire up queue dispatch\n this.workflowProvider.stepDispatch = async (\n workflowId,\n stepName,\n priority,\n ) => {\n const priorityMap: Record<\n number,\n \"critical\" | \"high\" | \"normal\" | \"low\"\n > = {\n 0: \"critical\",\n 1: \"high\",\n 2: \"normal\",\n 3: \"low\",\n };\n await this.dispatchStep.push(\n { workflowId, stepName },\n { priority: priorityMap[priority] ?? \"normal\" },\n );\n };\n },\n });\n}\n","import {\n $inject,\n createPrimitive,\n KIND,\n Primitive,\n type Static,\n type TSchema,\n} from \"alepha\";\nimport type { DurationLike } from \"alepha/datetime\";\nimport { WorkflowProvider } from \"../providers/WorkflowProvider.ts\";\n\n// -----------------------------------------------------------------------------------------------------------------\n\nexport type WorkflowPriority = \"critical\" | \"high\" | \"normal\" | \"low\";\n\nexport interface WorkflowRetryOptions {\n retries: number;\n backoff?: DurationLike | WorkflowRetryBackoff;\n when?: (error: Error) => boolean;\n}\n\nexport interface WorkflowRetryBackoff {\n initial: DurationLike;\n factor?: number;\n max?: DurationLike;\n jitter?: boolean;\n}\n\n// -----------------------------------------------------------------------------------------------------------------\n\nexport interface StepHandlerArgs<TInput extends TSchema = TSchema> {\n payload: Static<TInput>;\n results: Record<string, unknown>;\n context: {\n workflowId: string;\n executionId: string;\n stepName: string;\n attempt: number;\n };\n signal: AbortSignal;\n}\n\nexport interface StepCompensateArgs<TInput extends TSchema = TSchema> {\n payload: Static<TInput>;\n result: unknown;\n results: Record<string, unknown>;\n context: {\n workflowId: string;\n executionId: string;\n stepName: string;\n error: Error;\n };\n}\n\nexport interface StepConditionArgs<TInput extends TSchema = TSchema> {\n payload: Static<TInput>;\n results: Record<string, unknown>;\n}\n\n// -----------------------------------------------------------------------------------------------------------------\n\nexport interface HandlerStep<TInput extends TSchema = TSchema> {\n name: string;\n type?: \"handler\";\n handler: (args: StepHandlerArgs<TInput>) => Promise<unknown>;\n compensate?: (args: StepCompensateArgs<TInput>) => Promise<void>;\n retry?: WorkflowRetryOptions;\n timeout?: DurationLike;\n when?: (args: StepConditionArgs<TInput>) => boolean | Promise<boolean>;\n}\n\nexport type WorkflowStep<TInput extends TSchema = TSchema> =\n HandlerStep<TInput>;\n\n// -----------------------------------------------------------------------------------------------------------------\n\nexport interface WorkflowPrimitiveOptions<TInput extends TSchema = TSchema> {\n /**\n * TypeBox schema for the workflow input payload.\n */\n schema: TInput;\n\n /**\n * Ordered list of steps. Executed sequentially.\n */\n steps: Array<WorkflowStep<TInput>>;\n\n /**\n * Error strategy.\n * - \"compensate\": Run compensate functions in reverse order (saga pattern).\n * - \"fail\": Mark workflow as failed, no compensation.\n * @default \"compensate\"\n */\n onError?: \"compensate\" | \"fail\";\n\n /**\n * Maximum total duration for the entire workflow.\n */\n timeout?: DurationLike;\n\n /**\n * Priority for the workflow's job dispatches.\n * @default \"normal\"\n */\n priority?: WorkflowPriority;\n\n /**\n * Tags for filtering/grouping in admin UI.\n */\n tags?: string[];\n}\n\n// -----------------------------------------------------------------------------------------------------------------\n\nexport interface WorkflowStartOptions {\n key?: string;\n priority?: WorkflowPriority;\n delay?: DurationLike;\n triggeredBy?: string;\n triggeredByName?: string;\n tags?: string[];\n}\n\n// -----------------------------------------------------------------------------------------------------------------\n\nexport class WorkflowPrimitive<\n TInput extends TSchema = TSchema,\n> extends Primitive<WorkflowPrimitiveOptions<TInput>> {\n protected readonly workflowProvider = $inject(WorkflowProvider);\n\n public get name(): string {\n return `${this.config.service.name}.${this.config.propertyKey}`;\n }\n\n protected onInit() {\n this.workflowProvider.register(this);\n }\n\n /**\n * Start a new workflow execution.\n */\n public async start(\n payload: Static<TInput>,\n options?: WorkflowStartOptions,\n ): Promise<string> {\n return this.workflowProvider.start(this.name, payload, options);\n }\n\n /**\n * Send a signal to a waiting step on a specific execution.\n */\n public async signal(\n executionId: string,\n stepName: string,\n payload?: unknown,\n ): Promise<void> {\n return this.workflowProvider.signal(executionId, stepName, payload);\n }\n\n /**\n * Cancel a running execution.\n */\n public async cancel(\n executionId: string,\n options?: { compensate?: boolean },\n ): Promise<void> {\n return this.workflowProvider.cancel(executionId, {\n compensate: options?.compensate,\n });\n }\n\n /**\n * Retry a failed/timed-out execution from the failed step.\n */\n public async retry(executionId: string): Promise<void> {\n return this.workflowProvider.retry(executionId);\n }\n\n /**\n * Restart a terminal execution from the beginning (new execution).\n */\n public async restart(executionId: string): Promise<string> {\n return this.workflowProvider.restart(executionId);\n }\n\n /**\n * Get the status of an execution.\n */\n public async status(executionId: string) {\n return this.workflowProvider.getExecution(executionId);\n }\n}\n\n// -----------------------------------------------------------------------------------------------------------------\n\nexport const $workflow = <TInput extends TSchema>(\n options: WorkflowPrimitiveOptions<TInput>,\n) => {\n return createPrimitive(WorkflowPrimitive<TInput>, options);\n};\n\n$workflow[KIND] = WorkflowPrimitive;\n","import { $module } from \"alepha\";\nimport { AlephaApiJobs } from \"alepha/api/jobs\";\nimport { AlephaLock } from \"alepha/lock\";\nimport { AdminWorkflowController } from \"./controllers/AdminWorkflowController.ts\";\nimport { WorkflowJobs } from \"./jobs/WorkflowJobs.ts\";\nimport { $workflow } from \"./primitives/$workflow.ts\";\nimport { WorkflowProvider } from \"./providers/WorkflowProvider.ts\";\nimport { WorkflowService } from \"./services/WorkflowService.ts\";\n\n// -----------------------------------------------------------------------------------------------------------------\n\nexport * from \"./controllers/AdminWorkflowController.ts\";\nexport * from \"./entities/workflowExecutions.ts\";\nexport * from \"./entities/workflowStepExecutions.ts\";\nexport * from \"./entities/workflowStepLogs.ts\";\nexport * from \"./primitives/$workflow.ts\";\nexport * from \"./providers/WorkflowProvider.ts\";\nexport * from \"./schemas/workflowActivitySchema.ts\";\nexport * from \"./schemas/workflowConfigAtom.ts\";\nexport * from \"./schemas/workflowExecutionDetailSchema.ts\";\nexport * from \"./schemas/workflowExecutionQuerySchema.ts\";\nexport * from \"./schemas/workflowExecutionResourceSchema.ts\";\nexport * from \"./schemas/workflowRegistrationSchema.ts\";\nexport * from \"./schemas/workflowStatsSchema.ts\";\nexport * from \"./schemas/workflowStepExecutionResourceSchema.ts\";\nexport * from \"./services/WorkflowService.ts\";\n\n// -----------------------------------------------------------------------------------------------------------------\n\ndeclare module \"alepha\" {\n interface Hooks {\n \"workflow:started\": { workflowName: string; workflowId: string };\n \"workflow:step:begin\": {\n workflowName: string;\n workflowId: string;\n stepName: string;\n };\n \"workflow:step:completed\": {\n workflowName: string;\n workflowId: string;\n stepName: string;\n result: unknown;\n };\n \"workflow:step:failed\": {\n workflowName: string;\n workflowId: string;\n stepName: string;\n error: Error;\n };\n \"workflow:step:skipped\": {\n workflowName: string;\n workflowId: string;\n stepName: string;\n };\n \"workflow:signal:received\": {\n workflowName: string;\n workflowId: string;\n stepName: string;\n payload: unknown;\n };\n \"workflow:signal:timeout\": {\n workflowName: string;\n workflowId: string;\n stepName: string;\n };\n \"workflow:completed\": { workflowName: string; workflowId: string };\n \"workflow:failed\": {\n workflowName: string;\n workflowId: string;\n error: Error;\n stepName: string;\n };\n \"workflow:compensating\": {\n workflowName: string;\n workflowId: string;\n stepName: string;\n };\n \"workflow:compensated\": { workflowName: string; workflowId: string };\n \"workflow:compensation:failed\": {\n workflowName: string;\n workflowId: string;\n stepName: string;\n error: Error;\n };\n \"workflow:cancelled\": { workflowName: string; workflowId: string };\n \"workflow:timed_out\": { workflowName: string; workflowId: string };\n }\n}\n\n// -----------------------------------------------------------------------------------------------------------------\n\n/**\n * Durable workflow engine for long-running business processes.\n *\n * **Features:**\n * - Declarative, multi-step workflows with typed payloads\n * - Saga-pattern compensation for failure recovery\n * - Per-step retry with exponential backoff\n * - Workflow-level timeout and cancellation\n * - Deduplication via unique keys\n * - Per-execution log capture\n *\n * @module alepha.api.workflows\n */\nexport const AlephaApiWorkflows = $module({\n name: \"alepha.api.workflows\",\n primitives: [$workflow],\n services: [\n WorkflowProvider,\n WorkflowService,\n WorkflowJobs,\n AdminWorkflowController,\n ],\n imports: [AlephaApiJobs, AlephaLock],\n});\n"],"mappings":";;;;;;;;;AAEA,MAAa,8BAA8B,EAAE,OAAO;CAClD,MAAM,EAAE,MAAM;CACd,WAAW,EAAE,SAAS;CACtB,QAAQ,EAAE,SAAS;CACpB,CAAC;AAIF,MAAa,8BAA8B,EAAE,OAAO,EAClD,MAAM,EAAE,SAAS,EAAE,QAAQ;CAAE,SAAS;CAAG,SAAS;CAAI,CAAC,CAAC,EACzD,CAAC;;;ACTF,MAAa,qBAAqB,QAAQ;CACxC,MAAM;CACN,QAAQ,EAAE,OAAO;EACf,IAAI,GAAG,WAAW,EAAE,MAAM,CAAC;EAC3B,WAAW,GAAG,WAAW;EACzB,WAAW,GAAG,WAAW;EAEzB,cAAc,EAAE,MAAM;EACtB,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;EAEnC,SAAS,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,KAAK,CAAC,CAAC;EAEhD,QAAQ,GAAG,QACT,EAAE,KAAK;GACL;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACA;GACD,CAAC,EACF,UACD;EACD,aAAa,EAAE,SAAS,EAAE,MAAM,CAAC;EAEjC,WAAW,EAAE,SAAS,EAAE,UAAU,CAAC;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