@shipfox/api-workflows 4.0.0 → 6.0.0

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 (277) hide show
  1. package/.turbo/turbo-build.log +4 -4
  2. package/CHANGELOG.md +104 -0
  3. package/dist/core/agent-defaults.d.ts +17 -0
  4. package/dist/core/agent-defaults.d.ts.map +1 -0
  5. package/dist/core/agent-defaults.js +21 -0
  6. package/dist/core/agent-defaults.js.map +1 -0
  7. package/dist/core/agent-tool-capability-warning.d.ts +4 -0
  8. package/dist/core/agent-tool-capability-warning.d.ts.map +1 -1
  9. package/dist/core/agent-tool-capability-warning.js +15 -17
  10. package/dist/core/agent-tool-capability-warning.js.map +1 -1
  11. package/dist/core/agent-tools.d.ts +11 -9
  12. package/dist/core/agent-tools.d.ts.map +1 -1
  13. package/dist/core/agent-tools.js +23 -18
  14. package/dist/core/agent-tools.js.map +1 -1
  15. package/dist/core/checkout.d.ts +21 -7
  16. package/dist/core/checkout.d.ts.map +1 -1
  17. package/dist/core/checkout.js +23 -11
  18. package/dist/core/checkout.js.map +1 -1
  19. package/dist/core/entities/workflow-run-attempt.d.ts +1 -1
  20. package/dist/core/entities/workflow-run-attempt.d.ts.map +1 -1
  21. package/dist/core/entities/workflow-run-attempt.js.map +1 -1
  22. package/dist/core/job-execution.d.ts +3 -1
  23. package/dist/core/job-execution.d.ts.map +1 -1
  24. package/dist/core/job-execution.js +14 -12
  25. package/dist/core/job-execution.js.map +1 -1
  26. package/dist/core/job-transition/derive-job-execution-outputs.d.ts +1 -1
  27. package/dist/core/job-transition/derive-job-execution-outputs.d.ts.map +1 -1
  28. package/dist/core/job-transition/derive-job-execution-outputs.js.map +1 -1
  29. package/dist/core/job-transition/derive-job-success.js +1 -1
  30. package/dist/core/job-transition/derive-job-success.js.map +1 -1
  31. package/dist/core/listener-execution-materialization.d.ts +3 -3
  32. package/dist/core/listener-execution-materialization.d.ts.map +1 -1
  33. package/dist/core/listener-execution-materialization.js +3 -4
  34. package/dist/core/listener-execution-materialization.js.map +1 -1
  35. package/dist/core/run-workflow.d.ts +12 -1
  36. package/dist/core/run-workflow.d.ts.map +1 -1
  37. package/dist/core/run-workflow.js +13 -8
  38. package/dist/core/run-workflow.js.map +1 -1
  39. package/dist/core/step-config/agent.d.ts +8 -8
  40. package/dist/core/step-config/agent.d.ts.map +1 -1
  41. package/dist/core/step-config/agent.js +12 -10
  42. package/dist/core/step-config/agent.js.map +1 -1
  43. package/dist/core/step-config/complete-step-dispatch-config.d.ts +4 -4
  44. package/dist/core/step-config/complete-step-dispatch-config.d.ts.map +1 -1
  45. package/dist/core/step-config/complete-step-dispatch-config.js +2 -2
  46. package/dist/core/step-config/complete-step-dispatch-config.js.map +1 -1
  47. package/dist/core/step-config/materialize-job-execution-steps.d.ts +3 -3
  48. package/dist/core/step-config/materialize-job-execution-steps.d.ts.map +1 -1
  49. package/dist/core/step-config/materialize-job-execution-steps.js +5 -6
  50. package/dist/core/step-config/materialize-job-execution-steps.js.map +1 -1
  51. package/dist/core/step-config/materialize-workflow-model.d.ts +3 -3
  52. package/dist/core/step-config/materialize-workflow-model.d.ts.map +1 -1
  53. package/dist/core/step-config/materialize-workflow-model.js +4 -4
  54. package/dist/core/step-config/materialize-workflow-model.js.map +1 -1
  55. package/dist/core/step-config/resolve-job-execution-name.d.ts +1 -1
  56. package/dist/core/step-config/resolve-job-execution-name.d.ts.map +1 -1
  57. package/dist/core/step-config/resolve-job-execution-name.js.map +1 -1
  58. package/dist/core/step-config/resolve-step-config.d.ts +4 -4
  59. package/dist/core/step-config/resolve-step-config.d.ts.map +1 -1
  60. package/dist/core/step-config/resolve-step-config.js +6 -6
  61. package/dist/core/step-config/resolve-step-config.js.map +1 -1
  62. package/dist/core/step-config/run.d.ts +1 -1
  63. package/dist/core/step-config/run.d.ts.map +1 -1
  64. package/dist/core/step-config/run.js.map +1 -1
  65. package/dist/core/workflow-run-creation.d.ts +3 -3
  66. package/dist/core/workflow-run-creation.d.ts.map +1 -1
  67. package/dist/core/workflow-run-creation.js +3 -4
  68. package/dist/core/workflow-run-creation.js.map +1 -1
  69. package/dist/db/db.d.ts +16 -4
  70. package/dist/db/db.d.ts.map +1 -1
  71. package/dist/db/job-listeners.d.ts +7 -1
  72. package/dist/db/job-listeners.d.ts.map +1 -1
  73. package/dist/db/job-listeners.js +10 -5
  74. package/dist/db/job-listeners.js.map +1 -1
  75. package/dist/db/runner-lease-table.d.ts +5 -5
  76. package/dist/db/runner-lease-table.d.ts.map +1 -1
  77. package/dist/db/runner-lease-table.js +3 -2
  78. package/dist/db/runner-lease-table.js.map +1 -1
  79. package/dist/db/schema/workflow-run-attempts.d.ts +9 -3
  80. package/dist/db/schema/workflow-run-attempts.d.ts.map +1 -1
  81. package/dist/db/schema/workflow-run-attempts.js +2 -1
  82. package/dist/db/schema/workflow-run-attempts.js.map +1 -1
  83. package/dist/db/schema/workflow-runs.js +1 -1
  84. package/dist/db/schema/workflow-runs.js.map +1 -1
  85. package/dist/db/workflow-runs/job-executions.d.ts +5 -0
  86. package/dist/db/workflow-runs/job-executions.d.ts.map +1 -1
  87. package/dist/db/workflow-runs/job-executions.js +14 -7
  88. package/dist/db/workflow-runs/job-executions.js.map +1 -1
  89. package/dist/db/workflow-runs/jobs.d.ts.map +1 -1
  90. package/dist/db/workflow-runs/jobs.js +3 -1
  91. package/dist/db/workflow-runs/jobs.js.map +1 -1
  92. package/dist/db/workflow-runs/run-create.d.ts +9 -2
  93. package/dist/db/workflow-runs/run-create.d.ts.map +1 -1
  94. package/dist/db/workflow-runs/run-create.js +12 -9
  95. package/dist/db/workflow-runs/run-create.js.map +1 -1
  96. package/dist/db/workflow-runs/run-rerun.d.ts.map +1 -1
  97. package/dist/db/workflow-runs/run-rerun.js +3 -1
  98. package/dist/db/workflow-runs/run-rerun.js.map +1 -1
  99. package/dist/index.d.ts +18 -4
  100. package/dist/index.d.ts.map +1 -1
  101. package/dist/index.js +61 -37
  102. package/dist/index.js.map +1 -1
  103. package/dist/presentation/dto/checkout-token.d.ts +14 -1
  104. package/dist/presentation/dto/checkout-token.d.ts.map +1 -1
  105. package/dist/presentation/dto/checkout-token.js.map +1 -1
  106. package/dist/presentation/index.d.ts +1 -1
  107. package/dist/presentation/index.d.ts.map +1 -1
  108. package/dist/presentation/index.js +1 -1
  109. package/dist/presentation/index.js.map +1 -1
  110. package/dist/presentation/inter-module.d.ts +18 -0
  111. package/dist/presentation/inter-module.d.ts.map +1 -0
  112. package/dist/presentation/inter-module.js +113 -0
  113. package/dist/presentation/inter-module.js.map +1 -0
  114. package/dist/presentation/routes/agent-runtime-config.d.ts +6 -1
  115. package/dist/presentation/routes/agent-runtime-config.d.ts.map +1 -1
  116. package/dist/presentation/routes/agent-runtime-config.js +59 -57
  117. package/dist/presentation/routes/agent-runtime-config.js.map +1 -1
  118. package/dist/presentation/routes/cancel-run.d.ts +2 -1
  119. package/dist/presentation/routes/cancel-run.d.ts.map +1 -1
  120. package/dist/presentation/routes/cancel-run.js +37 -34
  121. package/dist/presentation/routes/cancel-run.js.map +1 -1
  122. package/dist/presentation/routes/checkout-token.d.ts +8 -1
  123. package/dist/presentation/routes/checkout-token.d.ts.map +1 -1
  124. package/dist/presentation/routes/checkout-token.js +65 -47
  125. package/dist/presentation/routes/checkout-token.js.map +1 -1
  126. package/dist/presentation/routes/get-run-aggregates.d.ts +2 -1
  127. package/dist/presentation/routes/get-run-aggregates.d.ts.map +1 -1
  128. package/dist/presentation/routes/get-run-aggregates.js +44 -53
  129. package/dist/presentation/routes/get-run-aggregates.js.map +1 -1
  130. package/dist/presentation/routes/get-run.d.ts +2 -1
  131. package/dist/presentation/routes/get-run.d.ts.map +1 -1
  132. package/dist/presentation/routes/get-run.js +53 -50
  133. package/dist/presentation/routes/get-run.js.map +1 -1
  134. package/dist/presentation/routes/get-step-secrets.d.ts +3 -1
  135. package/dist/presentation/routes/get-step-secrets.d.ts.map +1 -1
  136. package/dist/presentation/routes/get-step-secrets.js +72 -68
  137. package/dist/presentation/routes/get-step-secrets.js.map +1 -1
  138. package/dist/presentation/routes/index.d.ts +19 -2
  139. package/dist/presentation/routes/index.d.ts.map +1 -1
  140. package/dist/presentation/routes/index.js +38 -30
  141. package/dist/presentation/routes/index.js.map +1 -1
  142. package/dist/presentation/routes/leased-step.d.ts +2 -0
  143. package/dist/presentation/routes/leased-step.d.ts.map +1 -1
  144. package/dist/presentation/routes/leased-step.js +1 -2
  145. package/dist/presentation/routes/leased-step.js.map +1 -1
  146. package/dist/presentation/routes/list-run-attempts.d.ts +2 -1
  147. package/dist/presentation/routes/list-run-attempts.d.ts.map +1 -1
  148. package/dist/presentation/routes/list-run-attempts.js +29 -26
  149. package/dist/presentation/routes/list-run-attempts.js.map +1 -1
  150. package/dist/presentation/routes/list-runs.d.ts +2 -1
  151. package/dist/presentation/routes/list-runs.d.ts.map +1 -1
  152. package/dist/presentation/routes/list-runs.js +51 -60
  153. package/dist/presentation/routes/list-runs.js.map +1 -1
  154. package/dist/presentation/routes/next-step.d.ts +10 -1
  155. package/dist/presentation/routes/next-step.d.ts.map +1 -1
  156. package/dist/presentation/routes/next-step.js +64 -50
  157. package/dist/presentation/routes/next-step.js.map +1 -1
  158. package/dist/presentation/routes/project-access.d.ts +10 -0
  159. package/dist/presentation/routes/project-access.d.ts.map +1 -0
  160. package/dist/presentation/routes/project-access.js +17 -0
  161. package/dist/presentation/routes/project-access.js.map +1 -0
  162. package/dist/presentation/routes/report-step.d.ts +2 -1
  163. package/dist/presentation/routes/report-step.d.ts.map +1 -1
  164. package/dist/presentation/routes/report-step.js +62 -61
  165. package/dist/presentation/routes/report-step.js.map +1 -1
  166. package/dist/presentation/routes/require-accessible-run.d.ts +3 -1
  167. package/dist/presentation/routes/require-accessible-run.d.ts.map +1 -1
  168. package/dist/presentation/routes/require-accessible-run.js +3 -6
  169. package/dist/presentation/routes/require-accessible-run.js.map +1 -1
  170. package/dist/presentation/routes/rerun-run.d.ts +2 -1
  171. package/dist/presentation/routes/rerun-run.d.ts.map +1 -1
  172. package/dist/presentation/routes/rerun-run.js +46 -43
  173. package/dist/presentation/routes/rerun-run.js.map +1 -1
  174. package/dist/temporal/activities/index.d.ts +44 -9
  175. package/dist/temporal/activities/index.d.ts.map +1 -1
  176. package/dist/temporal/activities/index.js +13 -9
  177. package/dist/temporal/activities/index.js.map +1 -1
  178. package/dist/temporal/activities/orchestration-activities.d.ts +20 -11
  179. package/dist/temporal/activities/orchestration-activities.d.ts.map +1 -1
  180. package/dist/temporal/activities/orchestration-activities.js +48 -33
  181. package/dist/temporal/activities/orchestration-activities.js.map +1 -1
  182. package/dist/tsconfig.test.tsbuildinfo +1 -1
  183. package/package.json +41 -44
  184. package/src/core/agent-defaults.test.ts +28 -0
  185. package/src/core/agent-defaults.ts +36 -0
  186. package/src/core/agent-tool-capability-warning.test.ts +36 -11
  187. package/src/core/agent-tool-capability-warning.ts +27 -25
  188. package/src/core/agent-tools.ts +33 -36
  189. package/src/core/checkout.test.ts +38 -25
  190. package/src/core/checkout.ts +41 -14
  191. package/src/core/entities/workflow-run-attempt.ts +1 -1
  192. package/src/core/job-execution.ts +19 -9
  193. package/src/core/job-transition/derive-job-execution-outputs.ts +1 -1
  194. package/src/core/job-transition/derive-job-success.ts +1 -1
  195. package/src/core/listener-execution-materialization.test.ts +4 -2
  196. package/src/core/listener-execution-materialization.ts +6 -9
  197. package/src/core/run-workflow.test.ts +43 -38
  198. package/src/core/run-workflow.ts +26 -9
  199. package/src/core/step-config/agent.ts +24 -26
  200. package/src/core/step-config/complete-step-dispatch-config.test.ts +22 -23
  201. package/src/core/step-config/complete-step-dispatch-config.ts +6 -6
  202. package/src/core/step-config/materialize-job-execution-steps.test.ts +34 -23
  203. package/src/core/step-config/materialize-job-execution-steps.ts +38 -39
  204. package/src/core/step-config/materialize-workflow-model.test.ts +94 -82
  205. package/src/core/step-config/materialize-workflow-model.ts +31 -29
  206. package/src/core/step-config/resolve-job-execution-name.ts +1 -1
  207. package/src/core/step-config/resolve-step-config.ts +11 -9
  208. package/src/core/step-config/run.ts +1 -1
  209. package/src/core/workflow-run-creation.test.ts +14 -10
  210. package/src/core/workflow-run-creation.ts +6 -9
  211. package/src/db/job-listeners.ts +20 -5
  212. package/src/db/runner-lease-table.ts +2 -2
  213. package/src/db/schema/workflow-run-attempts.ts +7 -3
  214. package/src/db/schema/workflow-runs.ts +1 -1
  215. package/src/db/workflow-runs/job-executions.ts +15 -1
  216. package/src/db/workflow-runs/jobs.ts +4 -1
  217. package/src/db/workflow-runs/run-create.test.ts +7 -1
  218. package/src/db/workflow-runs/run-create.ts +25 -15
  219. package/src/db/workflow-runs/run-rerun.test.ts +1 -1
  220. package/src/db/workflow-runs/run-rerun.ts +6 -3
  221. package/src/index.ts +75 -33
  222. package/src/presentation/dto/checkout-token.ts +7 -1
  223. package/src/presentation/index.ts +1 -1
  224. package/src/presentation/inter-module.test.ts +149 -0
  225. package/src/presentation/inter-module.ts +132 -0
  226. package/src/presentation/routes/agent-runtime-config.test.ts +53 -10
  227. package/src/presentation/routes/agent-runtime-config.ts +89 -64
  228. package/src/presentation/routes/cancel-run.test.ts +10 -20
  229. package/src/presentation/routes/cancel-run.ts +30 -27
  230. package/src/presentation/routes/checkout-token.test.ts +52 -33
  231. package/src/presentation/routes/checkout-token.ts +109 -49
  232. package/src/presentation/routes/get-run-aggregates.test.ts +13 -7
  233. package/src/presentation/routes/get-run-aggregates.ts +54 -57
  234. package/src/presentation/routes/get-run.test.ts +10 -18
  235. package/src/presentation/routes/get-run.ts +51 -48
  236. package/src/presentation/routes/get-step-secrets.test.ts +29 -7
  237. package/src/presentation/routes/get-step-secrets.ts +72 -61
  238. package/src/presentation/routes/index.test.ts +16 -1
  239. package/src/presentation/routes/index.ts +54 -29
  240. package/src/presentation/routes/leased-step.ts +3 -2
  241. package/src/presentation/routes/list-run-attempts.test.ts +9 -19
  242. package/src/presentation/routes/list-run-attempts.ts +21 -18
  243. package/src/presentation/routes/list-runs.test.ts +13 -7
  244. package/src/presentation/routes/list-runs.ts +64 -67
  245. package/src/presentation/routes/next-step.test.ts +30 -11
  246. package/src/presentation/routes/next-step.ts +68 -48
  247. package/src/presentation/routes/project-access.ts +16 -0
  248. package/src/presentation/routes/report-step.test.ts +18 -2
  249. package/src/presentation/routes/report-step.ts +51 -49
  250. package/src/presentation/routes/require-accessible-run.ts +5 -2
  251. package/src/presentation/routes/rerun-run.test.ts +9 -19
  252. package/src/presentation/routes/rerun-run.ts +39 -36
  253. package/src/temporal/activities/index.ts +32 -12
  254. package/src/temporal/activities/orchestration-activities.test.ts +10 -8
  255. package/src/temporal/activities/orchestration-activities.ts +74 -50
  256. package/src/temporal/workflows/job-execution-orchestration.test.ts +47 -2
  257. package/test/env.ts +1 -3
  258. package/test/factories/project.ts +10 -5
  259. package/test/factories/workflow-model.test.ts +5 -1
  260. package/test/factories/workflow-model.ts +1 -1
  261. package/test/factories/workflow-run.ts +1 -1
  262. package/test/fixtures/agent-inter-module.ts +27 -0
  263. package/test/fixtures/annotations-inter-module.ts +5 -0
  264. package/test/fixtures/auth-inter-module.ts +22 -0
  265. package/test/fixtures/lease-token.ts +2 -1
  266. package/test/fixtures/projects-inter-module.ts +8 -0
  267. package/test/fixtures/runners-inter-module.ts +52 -0
  268. package/test/fixtures/secrets-inter-module.ts +61 -0
  269. package/test/globalSetup.ts +11 -11
  270. package/tsconfig.build.tsbuildinfo +1 -1
  271. package/dist/core/source-control.d.ts +0 -5
  272. package/dist/core/source-control.d.ts.map +0 -1
  273. package/dist/core/source-control.js +0 -19
  274. package/dist/core/source-control.js.map +0 -1
  275. package/src/core/source-control.test.ts +0 -17
  276. package/src/core/source-control.ts +0 -22
  277. package/src/temporal/workflows/job-execution-orchestration-timeout.test.ts +0 -165
@@ -1,5 +1,7 @@
1
+ import { readPersistedWorkflowModel } from '@shipfox/api-definitions-dto';
1
2
  import { WORKFLOWS_JOB_ACTIVATED } from '@shipfox/api-workflows-dto';
2
3
  import { and, asc, count, eq, inArray, isNull, notInArray, sql } from 'drizzle-orm';
4
+ import { createAgentDefaultsResolver } from '#core/agent-defaults.js';
3
5
  import { loadAgentToolMaterializationContext } from '#core/agent-tools.js';
4
6
  import { isJobTerminal } from '#core/entities/job.js';
5
7
  import { deriveJobSuccess } from '#core/job-transition/index.js';
@@ -124,19 +126,22 @@ export async function drainListenerEventsIntoExecution(params) {
124
126
  }
125
127
  };
126
128
  const target = await loadListenerMaterializationTarget(params.jobId, tx);
129
+ const model = target.attempt.model === null ? null : readPersistedWorkflowModel(target.attempt.model);
127
130
  const agentToolContext = target.attempt.agentToolMaterialization === null ? await loadAgentToolMaterializationContext({
128
- model: target.attempt.model,
131
+ model,
129
132
  workspaceId: target.run.workspaceId,
130
- projectId: target.run.projectId
133
+ projectId: target.run.projectId,
134
+ integrations: params.integrations,
135
+ projects: params.projects
131
136
  }) : undefined;
132
- const materialized = materializeListenerExecution({
133
- model: target.attempt.model,
137
+ const materialized = await materializeListenerExecution({
138
+ model,
134
139
  run: toWorkflowRun(target.run),
135
140
  job: toJob(target.job),
136
141
  sequence: params.expectedSequence,
137
142
  triggerEvents: listenerTriggerEvents(bufferedEvents),
138
143
  priorExecutions: target.priorExecutions,
139
- resolveAgentDefaults: params.resolveAgentDefaults,
144
+ resolveAgentDefaults: params.resolveAgentDefaults ?? (params.agent ? createAgentDefaultsResolver(params.agent, target.run.workspaceId) : undefined),
140
145
  agentToolContext,
141
146
  agentToolSnapshot: target.attempt.agentToolMaterialization
142
147
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/db/job-listeners.ts"],"sourcesContent":["import type {AgentDefaultsResolver} from '@shipfox/api-agent/core/resolve-agent-config';\nimport {\n WORKFLOWS_JOB_ACTIVATED,\n type WorkflowsJobActivatedEventDto,\n} from '@shipfox/api-workflows-dto';\nimport {and, asc, count, eq, inArray, isNull, notInArray, sql} from 'drizzle-orm';\nimport {loadAgentToolMaterializationContext} from '#core/agent-tools.js';\nimport {isJobTerminal, type JobStatus, type ResolutionReason} from '#core/entities/job.js';\nimport type {JobExecutionStatus, WorkflowExecutionEvent} from '#core/entities/job-execution.js';\nimport {type DeriveJobSuccessResult, deriveJobSuccess} from '#core/job-transition/index.js';\nimport {\n type MaterializedListenerExecution,\n materializeListenerExecution,\n} from '#core/listener-execution-materialization.js';\nimport {\n applyListenerFilterSnapshots,\n assembleListenerSnapshotContext,\n type ListenerTriggerWithSnapshot,\n planListenerFilterSnapshots,\n} from '#core/step-config/assemble-run-context.js';\nimport {\n recordListenerEventsCoalesced,\n recordWorkflowJobExecutionStatusChanged,\n recordWorkflowListenerResolved,\n} from '#metrics/instance.js';\nimport {db, type Tx} from './db.js';\nimport {writeWorkflowsOutboxEvent} from './outbox-writes.js';\nimport {type JobExecutionDb, jobExecutions, toJobExecution} from './schema/job-executions.js';\nimport {type JobListenerEventDb, jobListenerEvents} from './schema/job-listener-events.js';\nimport {jobs, toJob} from './schema/jobs.js';\nimport {steps} from './schema/steps.js';\nimport {workflowRunAttempts} from './schema/workflow-run-attempts.js';\nimport {toWorkflowRun, workflowRuns} from './schema/workflow-runs.js';\nimport {\n bulkUpdateStepStatuses,\n getDirectDependencyJobContexts,\n updateJobStatusAtVersion,\n} from './workflow-runs.js';\n\nconst TERMINAL_EXECUTION_STATUSES: JobExecutionStatus[] = ['succeeded', 'failed', 'cancelled'];\nconst MAX_LISTENER_RESOLUTION_ATTEMPTS = 3;\n\nexport interface ActivateJobListenerParams {\n jobId: string;\n expectedVersion: number;\n}\n\nexport interface ActivateJobListenerResult {\n status: 'running' | 'terminal';\n jobStatus: JobStatus;\n jobVersion: number;\n executionCount: number;\n}\n\ntype JobActivatedListenerMatcher = Extract<\n WorkflowsJobActivatedEventDto,\n {mode: 'listening'}\n>['on'][number] &\n ListenerTriggerWithSnapshot;\n\nfunction applyActivatedListenerFilterSnapshots(\n plans: Parameters<typeof applyListenerFilterSnapshots>[0],\n context: Parameters<typeof applyListenerFilterSnapshots>[1],\n): JobActivatedListenerMatcher[] {\n return applyListenerFilterSnapshots(plans, context);\n}\n\nexport async function activateJobListener(\n params: ActivateJobListenerParams,\n): Promise<ActivateJobListenerResult> {\n return await db().transaction(async (tx) => {\n const [target] = await tx\n .select({job: jobs, run: workflowRuns})\n .from(jobs)\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(eq(jobs.id, params.jobId))\n .limit(1)\n .for('update');\n if (!target) throw new Error(`Job not found: ${params.jobId}`);\n\n const [{value: executionCount} = {value: 0}] = await tx\n .select({value: count()})\n .from(jobExecutions)\n .where(eq(jobExecutions.jobId, params.jobId));\n\n if (['succeeded', 'failed', 'cancelled', 'skipped'].includes(target.job.status)) {\n return {\n status: 'terminal',\n jobStatus: target.job.status,\n jobVersion: target.job.version,\n executionCount,\n };\n }\n\n let job = toJob(target.job);\n if (target.job.status === 'pending') {\n const updated = await updateJobStatusAtVersion(tx, {\n jobId: params.jobId,\n status: 'running',\n expectedVersion: params.expectedVersion,\n });\n if (!updated) {\n const [existing] = await tx.select().from(jobs).where(eq(jobs.id, params.jobId)).limit(1);\n if (existing?.status !== 'running') {\n throw new Error(\n `Optimistic lock failure activating listener job ${params.jobId} version ${params.expectedVersion}`,\n );\n }\n job = toJob(existing);\n } else {\n job = updated.job;\n }\n }\n\n const listenerRows = await tx\n .update(jobs)\n .set({listenerStatus: 'listening', updatedAt: new Date()})\n .where(and(eq(jobs.id, params.jobId), eq(jobs.listenerStatus, 'inactive')))\n .returning();\n\n if (listenerRows[0]) {\n const matchers = {\n on: target.job.listeningOn ?? [],\n until: target.job.listeningUntil ?? null,\n };\n const snapshotPlan = planListenerFilterSnapshots(matchers);\n const dependencyJobs =\n snapshotPlan.jobKeys.size === 0\n ? []\n : await getDirectDependencyJobContexts(params.jobId, tx);\n const snapshotContext = assembleListenerSnapshotContext({\n job: toJob(target.job),\n run: toWorkflowRun(target.run),\n triggerPayload: target.run.triggerPayload,\n inputs: target.run.inputs,\n plan: snapshotPlan,\n dependencyJobs,\n });\n\n await writeWorkflowsOutboxEvent(tx, {\n type: WORKFLOWS_JOB_ACTIVATED,\n payload: {\n jobId: params.jobId,\n workflowRunId: target.run.id,\n workspaceId: target.run.workspaceId,\n mode: 'listening',\n on: applyActivatedListenerFilterSnapshots(snapshotPlan.on, snapshotContext),\n until:\n matchers.until === null\n ? null\n : applyActivatedListenerFilterSnapshots(snapshotPlan.until, snapshotContext),\n },\n });\n }\n\n return {status: 'running', jobStatus: job.status, jobVersion: job.version, executionCount};\n });\n}\n\nexport type DrainListenerEventsResult =\n | {\n kind: 'execution';\n jobExecutionId: string;\n executionVersion: number;\n sequence: number;\n requiredLabels: string[];\n status: JobExecutionStatus;\n }\n | {kind: 'resolve-requested'}\n | {kind: 'empty'};\n\nexport interface DrainListenerEventsParams {\n jobId: string;\n expectedSequence: number;\n maxSize?: number | undefined;\n resolveAgentDefaults?: AgentDefaultsResolver | undefined;\n}\n\nexport async function drainListenerEventsIntoExecution(\n params: DrainListenerEventsParams,\n): Promise<DrainListenerEventsResult> {\n const drained = await db().transaction(async (tx) => {\n const existing = await findExistingExecution(params, tx);\n if (existing) return {result: existing};\n\n const resolveRequested = await hasPendingResolveEvent(params.jobId, tx);\n if (resolveRequested) return {result: {kind: 'resolve-requested' as const}};\n\n const bufferedEvents = await lockBufferedFireEvents(params, tx);\n if (bufferedEvents.length === 0) return {result: {kind: 'empty' as const}};\n\n const target = await loadListenerMaterializationTarget(params.jobId, tx);\n const agentToolContext =\n target.attempt.agentToolMaterialization === null\n ? await loadAgentToolMaterializationContext({\n model: target.attempt.model,\n workspaceId: target.run.workspaceId,\n projectId: target.run.projectId,\n })\n : undefined;\n const materialized = materializeListenerExecution({\n model: target.attempt.model,\n run: toWorkflowRun(target.run),\n job: toJob(target.job),\n sequence: params.expectedSequence,\n triggerEvents: listenerTriggerEvents(bufferedEvents),\n priorExecutions: target.priorExecutions,\n resolveAgentDefaults: params.resolveAgentDefaults,\n agentToolContext,\n agentToolSnapshot: target.attempt.agentToolMaterialization,\n });\n const execution = await persistMaterializedListenerExecution(tx, {\n jobId: params.jobId,\n sequence: params.expectedSequence,\n bufferedEventIds: bufferedEvents.map((event) => event.id),\n materialized,\n });\n\n if (materialized.status === 'failed') {\n recordWorkflowJobExecutionStatusChanged(materialized.status);\n }\n\n return {\n result: drainExecutionResult(execution),\n batchSize: bufferedEvents.length,\n };\n });\n\n if (drained.result.kind === 'execution' && drained.batchSize !== undefined) {\n recordListenerEventsCoalesced(drained.batchSize);\n }\n\n return drained.result;\n}\n\nexport interface ListenerBufferPeek {\n fireCount: number;\n resolvePending: boolean;\n oldestAgeMs: number;\n newestAgeMs: number;\n}\n\nexport async function peekListenerBuffer(params: {jobId: string}): Promise<ListenerBufferPeek> {\n const [row] = await db()\n .select({\n fireCount: sql<number>`count(*) filter (where ${jobListenerEvents.disposition} = 'fire')::integer`,\n resolvePending: sql<boolean>`coalesce(bool_or(${jobListenerEvents.disposition} = 'resolve'), false)`,\n oldestAgeMs: sql<number>`coalesce(floor(extract(epoch from (statement_timestamp() - min(${jobListenerEvents.receivedAt}) filter (where ${jobListenerEvents.disposition} = 'fire'))) * 1000), 0)::integer`,\n newestAgeMs: sql<number>`coalesce(floor(extract(epoch from (statement_timestamp() - max(${jobListenerEvents.receivedAt}) filter (where ${jobListenerEvents.disposition} = 'fire'))) * 1000), 0)::integer`,\n })\n .from(jobListenerEvents)\n .where(\n and(\n eq(jobListenerEvents.jobId, params.jobId),\n isNull(jobListenerEvents.consumedByExecutionId),\n ),\n );\n\n return {\n fireCount: row?.fireCount ?? 0,\n resolvePending: row?.resolvePending ?? false,\n oldestAgeMs: row?.oldestAgeMs ?? 0,\n newestAgeMs: row?.newestAgeMs ?? 0,\n };\n}\n\nexport async function resolveJobListener(params: {\n jobId: string;\n reason: ResolutionReason;\n}): Promise<{status: 'succeeded' | 'failed'; jobVersion: number}> {\n let result: ApplyJobListenerResolutionResult | undefined;\n for (let attempt = 0; attempt < MAX_LISTENER_RESOLUTION_ATTEMPTS; attempt += 1) {\n const decision = await deriveJobListenerResolutionDecision(params.jobId);\n result = await applyJobListenerResolution(params, decision);\n if (result.kind === 'applied') break;\n }\n\n if (result?.kind !== 'applied') {\n throw new Error(`Optimistic lock failure resolving listener job ${params.jobId}`);\n }\n\n if (result.changed) recordWorkflowListenerResolved(params.reason);\n return {status: result.status, jobVersion: result.jobVersion};\n}\n\ntype JobListenerResolutionDecision = DeriveJobSuccessResult & {\n expectedVersion: number;\n};\n\ntype ApplyJobListenerResolutionResult =\n | {\n kind: 'applied';\n status: 'succeeded' | 'failed';\n jobVersion: number;\n changed: boolean;\n }\n | {kind: 'stale'};\n\nasync function deriveJobListenerResolutionDecision(\n jobId: string,\n): Promise<JobListenerResolutionDecision> {\n const [jobRow] = await db().select().from(jobs).where(eq(jobs.id, jobId)).limit(1);\n if (!jobRow) throw new Error(`Job not found: ${jobId}`);\n\n const [executionRows, dependencyJobs] = await Promise.all([\n db()\n .select()\n .from(jobExecutions)\n .where(eq(jobExecutions.jobId, jobId))\n .orderBy(asc(jobExecutions.sequence), asc(jobExecutions.id)),\n getDirectDependencyJobContexts(jobId),\n ]);\n return {\n expectedVersion: jobRow.version,\n ...deriveJobSuccess({\n success: jobRow.success,\n executions: executionRows.map(toJobExecution),\n jobs: dependencyJobs,\n }),\n };\n}\n\nasync function applyJobListenerResolution(\n params: {\n jobId: string;\n reason: ResolutionReason;\n },\n decision: JobListenerResolutionDecision,\n): Promise<ApplyJobListenerResolutionResult> {\n return await db().transaction(async (tx) => {\n const [jobRow] = await tx\n .select()\n .from(jobs)\n .where(eq(jobs.id, params.jobId))\n .limit(1)\n .for('update');\n if (!jobRow) throw new Error(`Job not found: ${params.jobId}`);\n\n if (jobRow.version !== decision.expectedVersion && !isJobTerminal(jobRow.status)) {\n return {kind: 'stale' as const};\n }\n\n const listenerRows = await tx\n .update(jobs)\n .set({\n listenerStatus: 'resolved',\n resolutionReason: params.reason,\n updatedAt: new Date(),\n })\n .where(and(eq(jobs.id, params.jobId), notInArray(jobs.listenerStatus, ['resolved'])))\n .returning({id: jobs.id});\n\n const updated = await updateJobStatusAtVersion(tx, {\n jobId: params.jobId,\n status: decision.status,\n expectedVersion: decision.expectedVersion,\n statusReason: decision.statusReason,\n evaluationTrace: decision.trace,\n });\n const job = updated?.job ?? toJob(jobRow);\n const resolvedStatus: 'succeeded' | 'failed' =\n job.status === 'succeeded' ? 'succeeded' : 'failed';\n return {\n kind: 'applied' as const,\n status: resolvedStatus,\n jobVersion: job.version,\n changed: listenerRows.length > 0 || updated?.changed === true,\n };\n });\n}\n\nexport async function settleListenerJobExecution(params: {\n jobExecutionId: string;\n status: Extract<JobExecutionStatus, 'failed' | 'cancelled'>;\n}): Promise<void> {\n const changed = await db().transaction(async (tx) => {\n const [execution] = await tx\n .update(jobExecutions)\n .set({\n status: params.status,\n statusReason: params.status === 'failed' ? 'step_failed' : 'run_cancelled',\n version: sql`${jobExecutions.version} + 1`,\n updatedAt: new Date(),\n finishedAt: sql`now()`,\n })\n .where(\n and(\n eq(jobExecutions.id, params.jobExecutionId),\n notInArray(jobExecutions.status, TERMINAL_EXECUTION_STATUSES),\n ),\n )\n .returning();\n if (!execution) return false;\n await bulkUpdateStepStatuses(\n {jobExecutionId: params.jobExecutionId, status: params.status},\n tx,\n );\n return true;\n });\n\n if (changed) {\n recordWorkflowJobExecutionStatusChanged(params.status);\n }\n}\n\nexport async function countActiveListeners(): Promise<number> {\n const [row] = await db()\n .select({value: count()})\n .from(jobs)\n .where(eq(jobs.listenerStatus, 'listening'));\n return row?.value ?? 0;\n}\n\nasync function findExistingExecution(\n params: DrainListenerEventsParams,\n tx: Tx,\n): Promise<Extract<DrainListenerEventsResult, {kind: 'execution'}> | undefined> {\n const [existing] = await tx\n .select()\n .from(jobExecutions)\n .where(\n and(\n eq(jobExecutions.jobId, params.jobId),\n eq(jobExecutions.sequence, params.expectedSequence),\n ),\n )\n .limit(1);\n if (!existing) return undefined;\n return drainExecutionResult(existing);\n}\n\nasync function hasPendingResolveEvent(jobId: string, tx: Tx): Promise<boolean> {\n const [resolveEvent] = await tx\n .select({id: jobListenerEvents.id})\n .from(jobListenerEvents)\n .where(\n and(\n eq(jobListenerEvents.jobId, jobId),\n eq(jobListenerEvents.disposition, 'resolve'),\n isNull(jobListenerEvents.consumedByExecutionId),\n ),\n )\n .orderBy(asc(jobListenerEvents.receivedAt), asc(jobListenerEvents.id))\n .limit(1)\n .for('update');\n return resolveEvent !== undefined;\n}\n\nasync function lockBufferedFireEvents(\n params: DrainListenerEventsParams,\n tx: Tx,\n): Promise<JobListenerEventDb[]> {\n const bufferedQuery = tx\n .select()\n .from(jobListenerEvents)\n .where(\n and(\n eq(jobListenerEvents.jobId, params.jobId),\n eq(jobListenerEvents.disposition, 'fire'),\n isNull(jobListenerEvents.consumedByExecutionId),\n ),\n )\n .orderBy(asc(jobListenerEvents.receivedAt), asc(jobListenerEvents.id));\n return await (params.maxSize === undefined\n ? bufferedQuery\n : bufferedQuery.limit(params.maxSize)\n ).for('update');\n}\n\nfunction listenerTriggerEvents(\n bufferedEvents: readonly JobListenerEventDb[],\n): WorkflowExecutionEvent[] {\n return bufferedEvents.map((event) => ({\n source: event.source,\n event: event.event,\n delivery_id: event.deliveryId,\n received_at: event.receivedAt.toISOString(),\n data: event.payload,\n }));\n}\n\nasync function persistMaterializedListenerExecution(\n tx: Tx,\n params: {\n readonly jobId: string;\n readonly sequence: number;\n readonly bufferedEventIds: readonly string[];\n readonly materialized: MaterializedListenerExecution;\n },\n): Promise<JobExecutionDb> {\n const [execution] = await tx\n .insert(jobExecutions)\n .values({\n jobId: params.jobId,\n sequence: params.sequence,\n name: params.materialized.name,\n runner: params.materialized.runner.length === 0 ? null : [...params.materialized.runner],\n status: params.materialized.status,\n statusReason: params.materialized.statusReason,\n triggerEvents: [...params.materialized.triggerEvents],\n evaluationTrace: params.materialized.evaluationTrace,\n ...(params.materialized.status === 'failed' ? {finishedAt: sql`now()`} : {}),\n })\n .returning();\n if (!execution) throw new Error('Insert returned no rows');\n\n await tx\n .update(jobListenerEvents)\n .set({consumedByExecutionId: execution.id})\n .where(inArray(jobListenerEvents.id, [...params.bufferedEventIds]));\n\n if (params.materialized.status === 'pending' && params.materialized.steps.length > 0) {\n await tx.insert(steps).values(\n params.materialized.steps.map((step) => ({\n jobExecutionId: execution.id,\n key: step.key,\n name: step.name,\n sourceLocation: step.sourceLocation,\n status: step.status,\n type: step.type,\n config: step.config,\n configPlan: step.configPlan ?? null,\n authoredConfig: step.authoredConfig,\n condition: step.condition ?? null,\n position: step.position,\n })),\n );\n }\n\n return execution;\n}\n\nfunction drainExecutionResult(\n execution: JobExecutionDb,\n): Extract<DrainListenerEventsResult, {kind: 'execution'}> {\n return {\n kind: 'execution',\n jobExecutionId: execution.id,\n executionVersion: execution.version,\n sequence: execution.sequence,\n requiredLabels: execution.runner ?? [],\n status: execution.status,\n };\n}\n\nasync function loadListenerMaterializationTarget(jobId: string, tx: Tx) {\n const [target] = await tx\n .select({job: jobs, attempt: workflowRunAttempts, run: workflowRuns})\n .from(jobs)\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(eq(jobs.id, jobId))\n .limit(1)\n .for('update');\n if (!target) throw new Error(`Job not found: ${jobId}`);\n\n const priorExecutions = await tx\n .select()\n .from(jobExecutions)\n .where(eq(jobExecutions.jobId, jobId))\n .orderBy(asc(jobExecutions.sequence), asc(jobExecutions.id));\n return {...target, priorExecutions: priorExecutions.map(toJobExecution)};\n}\n"],"names":["WORKFLOWS_JOB_ACTIVATED","and","asc","count","eq","inArray","isNull","notInArray","sql","loadAgentToolMaterializationContext","isJobTerminal","deriveJobSuccess","materializeListenerExecution","applyListenerFilterSnapshots","assembleListenerSnapshotContext","planListenerFilterSnapshots","recordListenerEventsCoalesced","recordWorkflowJobExecutionStatusChanged","recordWorkflowListenerResolved","db","writeWorkflowsOutboxEvent","jobExecutions","toJobExecution","jobListenerEvents","jobs","toJob","steps","workflowRunAttempts","toWorkflowRun","workflowRuns","bulkUpdateStepStatuses","getDirectDependencyJobContexts","updateJobStatusAtVersion","TERMINAL_EXECUTION_STATUSES","MAX_LISTENER_RESOLUTION_ATTEMPTS","applyActivatedListenerFilterSnapshots","plans","context","activateJobListener","params","transaction","tx","target","select","job","run","from","innerJoin","workflowRunAttemptId","id","workflowRunId","where","jobId","limit","for","Error","value","executionCount","includes","status","jobStatus","jobVersion","version","updated","expectedVersion","existing","listenerRows","update","set","listenerStatus","updatedAt","Date","returning","matchers","on","listeningOn","until","listeningUntil","snapshotPlan","dependencyJobs","jobKeys","size","snapshotContext","triggerPayload","inputs","plan","type","payload","workspaceId","mode","drainListenerEventsIntoExecution","drained","findExistingExecution","result","resolveRequested","hasPendingResolveEvent","kind","bufferedEvents","lockBufferedFireEvents","length","loadListenerMaterializationTarget","agentToolContext","attempt","agentToolMaterialization","model","projectId","undefined","materialized","sequence","expectedSequence","triggerEvents","listenerTriggerEvents","priorExecutions","resolveAgentDefaults","agentToolSnapshot","execution","persistMaterializedListenerExecution","bufferedEventIds","map","event","drainExecutionResult","batchSize","peekListenerBuffer","row","fireCount","disposition","resolvePending","oldestAgeMs","receivedAt","newestAgeMs","consumedByExecutionId","resolveJobListener","decision","deriveJobListenerResolutionDecision","applyJobListenerResolution","changed","reason","jobRow","executionRows","Promise","all","orderBy","success","executions","resolutionReason","statusReason","evaluationTrace","trace","resolvedStatus","settleListenerJobExecution","finishedAt","jobExecutionId","countActiveListeners","resolveEvent","bufferedQuery","maxSize","source","delivery_id","deliveryId","received_at","toISOString","data","insert","values","name","runner","step","key","sourceLocation","config","configPlan","authoredConfig","condition","position","executionVersion","requiredLabels"],"mappings":"AACA,SACEA,uBAAuB,QAElB,6BAA6B;AACpC,SAAQC,GAAG,EAAEC,GAAG,EAAEC,KAAK,EAAEC,EAAE,EAAEC,OAAO,EAAEC,MAAM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type {AgentInterModuleClient} from '@shipfox/api-agent-dto/inter-module';\nimport {readPersistedWorkflowModel} from '@shipfox/api-definitions-dto';\nimport type {IntegrationsModuleClient} from '@shipfox/api-integration-core-dto';\nimport type {ProjectsModuleClient} from '@shipfox/api-projects-dto';\nimport {\n WORKFLOWS_JOB_ACTIVATED,\n type WorkflowsJobActivatedEventDto,\n} from '@shipfox/api-workflows-dto';\nimport {and, asc, count, eq, inArray, isNull, notInArray, sql} from 'drizzle-orm';\nimport {type AgentDefaultsResolver, createAgentDefaultsResolver} from '#core/agent-defaults.js';\nimport {loadAgentToolMaterializationContext} from '#core/agent-tools.js';\nimport {isJobTerminal, type JobStatus, type ResolutionReason} from '#core/entities/job.js';\nimport type {JobExecutionStatus, WorkflowExecutionEvent} from '#core/entities/job-execution.js';\nimport {type DeriveJobSuccessResult, deriveJobSuccess} from '#core/job-transition/index.js';\nimport {\n type MaterializedListenerExecution,\n materializeListenerExecution,\n} from '#core/listener-execution-materialization.js';\nimport {\n applyListenerFilterSnapshots,\n assembleListenerSnapshotContext,\n type ListenerTriggerWithSnapshot,\n planListenerFilterSnapshots,\n} from '#core/step-config/assemble-run-context.js';\nimport {\n recordListenerEventsCoalesced,\n recordWorkflowJobExecutionStatusChanged,\n recordWorkflowListenerResolved,\n} from '#metrics/instance.js';\nimport {db, type Tx} from './db.js';\nimport {writeWorkflowsOutboxEvent} from './outbox-writes.js';\nimport {type JobExecutionDb, jobExecutions, toJobExecution} from './schema/job-executions.js';\nimport {type JobListenerEventDb, jobListenerEvents} from './schema/job-listener-events.js';\nimport {jobs, toJob} from './schema/jobs.js';\nimport {steps} from './schema/steps.js';\nimport {workflowRunAttempts} from './schema/workflow-run-attempts.js';\nimport {toWorkflowRun, workflowRuns} from './schema/workflow-runs.js';\nimport {\n bulkUpdateStepStatuses,\n getDirectDependencyJobContexts,\n updateJobStatusAtVersion,\n} from './workflow-runs.js';\n\nconst TERMINAL_EXECUTION_STATUSES: JobExecutionStatus[] = ['succeeded', 'failed', 'cancelled'];\nconst MAX_LISTENER_RESOLUTION_ATTEMPTS = 3;\n\nexport interface ActivateJobListenerParams {\n jobId: string;\n expectedVersion: number;\n}\n\nexport interface ActivateJobListenerResult {\n status: 'running' | 'terminal';\n jobStatus: JobStatus;\n jobVersion: number;\n executionCount: number;\n}\n\ntype JobActivatedListenerMatcher = Extract<\n WorkflowsJobActivatedEventDto,\n {mode: 'listening'}\n>['on'][number] &\n ListenerTriggerWithSnapshot;\n\nfunction applyActivatedListenerFilterSnapshots(\n plans: Parameters<typeof applyListenerFilterSnapshots>[0],\n context: Parameters<typeof applyListenerFilterSnapshots>[1],\n): JobActivatedListenerMatcher[] {\n return applyListenerFilterSnapshots(plans, context);\n}\n\nexport async function activateJobListener(\n params: ActivateJobListenerParams,\n): Promise<ActivateJobListenerResult> {\n return await db().transaction(async (tx) => {\n const [target] = await tx\n .select({job: jobs, run: workflowRuns})\n .from(jobs)\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(eq(jobs.id, params.jobId))\n .limit(1)\n .for('update');\n if (!target) throw new Error(`Job not found: ${params.jobId}`);\n\n const [{value: executionCount} = {value: 0}] = await tx\n .select({value: count()})\n .from(jobExecutions)\n .where(eq(jobExecutions.jobId, params.jobId));\n\n if (['succeeded', 'failed', 'cancelled', 'skipped'].includes(target.job.status)) {\n return {\n status: 'terminal',\n jobStatus: target.job.status,\n jobVersion: target.job.version,\n executionCount,\n };\n }\n\n let job = toJob(target.job);\n if (target.job.status === 'pending') {\n const updated = await updateJobStatusAtVersion(tx, {\n jobId: params.jobId,\n status: 'running',\n expectedVersion: params.expectedVersion,\n });\n if (!updated) {\n const [existing] = await tx.select().from(jobs).where(eq(jobs.id, params.jobId)).limit(1);\n if (existing?.status !== 'running') {\n throw new Error(\n `Optimistic lock failure activating listener job ${params.jobId} version ${params.expectedVersion}`,\n );\n }\n job = toJob(existing);\n } else {\n job = updated.job;\n }\n }\n\n const listenerRows = await tx\n .update(jobs)\n .set({listenerStatus: 'listening', updatedAt: new Date()})\n .where(and(eq(jobs.id, params.jobId), eq(jobs.listenerStatus, 'inactive')))\n .returning();\n\n if (listenerRows[0]) {\n const matchers = {\n on: target.job.listeningOn ?? [],\n until: target.job.listeningUntil ?? null,\n };\n const snapshotPlan = planListenerFilterSnapshots(matchers);\n const dependencyJobs =\n snapshotPlan.jobKeys.size === 0\n ? []\n : await getDirectDependencyJobContexts(params.jobId, tx);\n const snapshotContext = assembleListenerSnapshotContext({\n job: toJob(target.job),\n run: toWorkflowRun(target.run),\n triggerPayload: target.run.triggerPayload,\n inputs: target.run.inputs,\n plan: snapshotPlan,\n dependencyJobs,\n });\n\n await writeWorkflowsOutboxEvent(tx, {\n type: WORKFLOWS_JOB_ACTIVATED,\n payload: {\n jobId: params.jobId,\n workflowRunId: target.run.id,\n workspaceId: target.run.workspaceId,\n mode: 'listening',\n on: applyActivatedListenerFilterSnapshots(snapshotPlan.on, snapshotContext),\n until:\n matchers.until === null\n ? null\n : applyActivatedListenerFilterSnapshots(snapshotPlan.until, snapshotContext),\n },\n });\n }\n\n return {status: 'running', jobStatus: job.status, jobVersion: job.version, executionCount};\n });\n}\n\nexport type DrainListenerEventsResult =\n | {\n kind: 'execution';\n jobExecutionId: string;\n executionVersion: number;\n sequence: number;\n requiredLabels: string[];\n status: JobExecutionStatus;\n }\n | {kind: 'resolve-requested'}\n | {kind: 'empty'};\n\nexport interface DrainListenerEventsParams {\n jobId: string;\n expectedSequence: number;\n maxSize?: number | undefined;\n integrations?: IntegrationsModuleClient | undefined;\n projects?: ProjectsModuleClient | undefined;\n resolveAgentDefaults?: AgentDefaultsResolver | undefined;\n agent?: AgentInterModuleClient | undefined;\n}\n\nexport async function drainListenerEventsIntoExecution(\n params: DrainListenerEventsParams,\n): Promise<DrainListenerEventsResult> {\n const drained = await db().transaction(async (tx) => {\n const existing = await findExistingExecution(params, tx);\n if (existing) return {result: existing};\n\n const resolveRequested = await hasPendingResolveEvent(params.jobId, tx);\n if (resolveRequested) return {result: {kind: 'resolve-requested' as const}};\n\n const bufferedEvents = await lockBufferedFireEvents(params, tx);\n if (bufferedEvents.length === 0) return {result: {kind: 'empty' as const}};\n\n const target = await loadListenerMaterializationTarget(params.jobId, tx);\n const model =\n target.attempt.model === null ? null : readPersistedWorkflowModel(target.attempt.model);\n const agentToolContext =\n target.attempt.agentToolMaterialization === null\n ? await loadAgentToolMaterializationContext({\n model,\n workspaceId: target.run.workspaceId,\n projectId: target.run.projectId,\n integrations: params.integrations,\n projects: params.projects,\n })\n : undefined;\n const materialized = await materializeListenerExecution({\n model,\n run: toWorkflowRun(target.run),\n job: toJob(target.job),\n sequence: params.expectedSequence,\n triggerEvents: listenerTriggerEvents(bufferedEvents),\n priorExecutions: target.priorExecutions,\n resolveAgentDefaults:\n params.resolveAgentDefaults ??\n (params.agent\n ? createAgentDefaultsResolver(params.agent, target.run.workspaceId)\n : undefined),\n agentToolContext,\n agentToolSnapshot: target.attempt.agentToolMaterialization,\n });\n const execution = await persistMaterializedListenerExecution(tx, {\n jobId: params.jobId,\n sequence: params.expectedSequence,\n bufferedEventIds: bufferedEvents.map((event) => event.id),\n materialized,\n });\n\n if (materialized.status === 'failed') {\n recordWorkflowJobExecutionStatusChanged(materialized.status);\n }\n\n return {\n result: drainExecutionResult(execution),\n batchSize: bufferedEvents.length,\n };\n });\n\n if (drained.result.kind === 'execution' && drained.batchSize !== undefined) {\n recordListenerEventsCoalesced(drained.batchSize);\n }\n\n return drained.result;\n}\n\nexport interface ListenerBufferPeek {\n fireCount: number;\n resolvePending: boolean;\n oldestAgeMs: number;\n newestAgeMs: number;\n}\n\nexport async function peekListenerBuffer(params: {jobId: string}): Promise<ListenerBufferPeek> {\n const [row] = await db()\n .select({\n fireCount: sql<number>`count(*) filter (where ${jobListenerEvents.disposition} = 'fire')::integer`,\n resolvePending: sql<boolean>`coalesce(bool_or(${jobListenerEvents.disposition} = 'resolve'), false)`,\n oldestAgeMs: sql<number>`coalesce(floor(extract(epoch from (statement_timestamp() - min(${jobListenerEvents.receivedAt}) filter (where ${jobListenerEvents.disposition} = 'fire'))) * 1000), 0)::integer`,\n newestAgeMs: sql<number>`coalesce(floor(extract(epoch from (statement_timestamp() - max(${jobListenerEvents.receivedAt}) filter (where ${jobListenerEvents.disposition} = 'fire'))) * 1000), 0)::integer`,\n })\n .from(jobListenerEvents)\n .where(\n and(\n eq(jobListenerEvents.jobId, params.jobId),\n isNull(jobListenerEvents.consumedByExecutionId),\n ),\n );\n\n return {\n fireCount: row?.fireCount ?? 0,\n resolvePending: row?.resolvePending ?? false,\n oldestAgeMs: row?.oldestAgeMs ?? 0,\n newestAgeMs: row?.newestAgeMs ?? 0,\n };\n}\n\nexport async function resolveJobListener(params: {\n jobId: string;\n reason: ResolutionReason;\n}): Promise<{status: 'succeeded' | 'failed'; jobVersion: number}> {\n let result: ApplyJobListenerResolutionResult | undefined;\n for (let attempt = 0; attempt < MAX_LISTENER_RESOLUTION_ATTEMPTS; attempt += 1) {\n const decision = await deriveJobListenerResolutionDecision(params.jobId);\n result = await applyJobListenerResolution(params, decision);\n if (result.kind === 'applied') break;\n }\n\n if (result?.kind !== 'applied') {\n throw new Error(`Optimistic lock failure resolving listener job ${params.jobId}`);\n }\n\n if (result.changed) recordWorkflowListenerResolved(params.reason);\n return {status: result.status, jobVersion: result.jobVersion};\n}\n\ntype JobListenerResolutionDecision = DeriveJobSuccessResult & {\n expectedVersion: number;\n};\n\ntype ApplyJobListenerResolutionResult =\n | {\n kind: 'applied';\n status: 'succeeded' | 'failed';\n jobVersion: number;\n changed: boolean;\n }\n | {kind: 'stale'};\n\nasync function deriveJobListenerResolutionDecision(\n jobId: string,\n): Promise<JobListenerResolutionDecision> {\n const [jobRow] = await db().select().from(jobs).where(eq(jobs.id, jobId)).limit(1);\n if (!jobRow) throw new Error(`Job not found: ${jobId}`);\n\n const [executionRows, dependencyJobs] = await Promise.all([\n db()\n .select()\n .from(jobExecutions)\n .where(eq(jobExecutions.jobId, jobId))\n .orderBy(asc(jobExecutions.sequence), asc(jobExecutions.id)),\n getDirectDependencyJobContexts(jobId),\n ]);\n return {\n expectedVersion: jobRow.version,\n ...deriveJobSuccess({\n success: jobRow.success,\n executions: executionRows.map(toJobExecution),\n jobs: dependencyJobs,\n }),\n };\n}\n\nasync function applyJobListenerResolution(\n params: {\n jobId: string;\n reason: ResolutionReason;\n },\n decision: JobListenerResolutionDecision,\n): Promise<ApplyJobListenerResolutionResult> {\n return await db().transaction(async (tx) => {\n const [jobRow] = await tx\n .select()\n .from(jobs)\n .where(eq(jobs.id, params.jobId))\n .limit(1)\n .for('update');\n if (!jobRow) throw new Error(`Job not found: ${params.jobId}`);\n\n if (jobRow.version !== decision.expectedVersion && !isJobTerminal(jobRow.status)) {\n return {kind: 'stale' as const};\n }\n\n const listenerRows = await tx\n .update(jobs)\n .set({\n listenerStatus: 'resolved',\n resolutionReason: params.reason,\n updatedAt: new Date(),\n })\n .where(and(eq(jobs.id, params.jobId), notInArray(jobs.listenerStatus, ['resolved'])))\n .returning({id: jobs.id});\n\n const updated = await updateJobStatusAtVersion(tx, {\n jobId: params.jobId,\n status: decision.status,\n expectedVersion: decision.expectedVersion,\n statusReason: decision.statusReason,\n evaluationTrace: decision.trace,\n });\n const job = updated?.job ?? toJob(jobRow);\n const resolvedStatus: 'succeeded' | 'failed' =\n job.status === 'succeeded' ? 'succeeded' : 'failed';\n return {\n kind: 'applied' as const,\n status: resolvedStatus,\n jobVersion: job.version,\n changed: listenerRows.length > 0 || updated?.changed === true,\n };\n });\n}\n\nexport async function settleListenerJobExecution(params: {\n jobExecutionId: string;\n status: Extract<JobExecutionStatus, 'failed' | 'cancelled'>;\n}): Promise<void> {\n const changed = await db().transaction(async (tx) => {\n const [execution] = await tx\n .update(jobExecutions)\n .set({\n status: params.status,\n statusReason: params.status === 'failed' ? 'step_failed' : 'run_cancelled',\n version: sql`${jobExecutions.version} + 1`,\n updatedAt: new Date(),\n finishedAt: sql`now()`,\n })\n .where(\n and(\n eq(jobExecutions.id, params.jobExecutionId),\n notInArray(jobExecutions.status, TERMINAL_EXECUTION_STATUSES),\n ),\n )\n .returning();\n if (!execution) return false;\n await bulkUpdateStepStatuses(\n {jobExecutionId: params.jobExecutionId, status: params.status},\n tx,\n );\n return true;\n });\n\n if (changed) {\n recordWorkflowJobExecutionStatusChanged(params.status);\n }\n}\n\nexport async function countActiveListeners(): Promise<number> {\n const [row] = await db()\n .select({value: count()})\n .from(jobs)\n .where(eq(jobs.listenerStatus, 'listening'));\n return row?.value ?? 0;\n}\n\nasync function findExistingExecution(\n params: DrainListenerEventsParams,\n tx: Tx,\n): Promise<Extract<DrainListenerEventsResult, {kind: 'execution'}> | undefined> {\n const [existing] = await tx\n .select()\n .from(jobExecutions)\n .where(\n and(\n eq(jobExecutions.jobId, params.jobId),\n eq(jobExecutions.sequence, params.expectedSequence),\n ),\n )\n .limit(1);\n if (!existing) return undefined;\n return drainExecutionResult(existing);\n}\n\nasync function hasPendingResolveEvent(jobId: string, tx: Tx): Promise<boolean> {\n const [resolveEvent] = await tx\n .select({id: jobListenerEvents.id})\n .from(jobListenerEvents)\n .where(\n and(\n eq(jobListenerEvents.jobId, jobId),\n eq(jobListenerEvents.disposition, 'resolve'),\n isNull(jobListenerEvents.consumedByExecutionId),\n ),\n )\n .orderBy(asc(jobListenerEvents.receivedAt), asc(jobListenerEvents.id))\n .limit(1)\n .for('update');\n return resolveEvent !== undefined;\n}\n\nasync function lockBufferedFireEvents(\n params: DrainListenerEventsParams,\n tx: Tx,\n): Promise<JobListenerEventDb[]> {\n const bufferedQuery = tx\n .select()\n .from(jobListenerEvents)\n .where(\n and(\n eq(jobListenerEvents.jobId, params.jobId),\n eq(jobListenerEvents.disposition, 'fire'),\n isNull(jobListenerEvents.consumedByExecutionId),\n ),\n )\n .orderBy(asc(jobListenerEvents.receivedAt), asc(jobListenerEvents.id));\n return await (params.maxSize === undefined\n ? bufferedQuery\n : bufferedQuery.limit(params.maxSize)\n ).for('update');\n}\n\nfunction listenerTriggerEvents(\n bufferedEvents: readonly JobListenerEventDb[],\n): WorkflowExecutionEvent[] {\n return bufferedEvents.map((event) => ({\n source: event.source,\n event: event.event,\n delivery_id: event.deliveryId,\n received_at: event.receivedAt.toISOString(),\n data: event.payload,\n }));\n}\n\nasync function persistMaterializedListenerExecution(\n tx: Tx,\n params: {\n readonly jobId: string;\n readonly sequence: number;\n readonly bufferedEventIds: readonly string[];\n readonly materialized: MaterializedListenerExecution;\n },\n): Promise<JobExecutionDb> {\n const [execution] = await tx\n .insert(jobExecutions)\n .values({\n jobId: params.jobId,\n sequence: params.sequence,\n name: params.materialized.name,\n runner: params.materialized.runner.length === 0 ? null : [...params.materialized.runner],\n status: params.materialized.status,\n statusReason: params.materialized.statusReason,\n triggerEvents: [...params.materialized.triggerEvents],\n evaluationTrace: params.materialized.evaluationTrace,\n ...(params.materialized.status === 'failed' ? {finishedAt: sql`now()`} : {}),\n })\n .returning();\n if (!execution) throw new Error('Insert returned no rows');\n\n await tx\n .update(jobListenerEvents)\n .set({consumedByExecutionId: execution.id})\n .where(inArray(jobListenerEvents.id, [...params.bufferedEventIds]));\n\n if (params.materialized.status === 'pending' && params.materialized.steps.length > 0) {\n await tx.insert(steps).values(\n params.materialized.steps.map((step) => ({\n jobExecutionId: execution.id,\n key: step.key,\n name: step.name,\n sourceLocation: step.sourceLocation,\n status: step.status,\n type: step.type,\n config: step.config,\n configPlan: step.configPlan ?? null,\n authoredConfig: step.authoredConfig,\n condition: step.condition ?? null,\n position: step.position,\n })),\n );\n }\n\n return execution;\n}\n\nfunction drainExecutionResult(\n execution: JobExecutionDb,\n): Extract<DrainListenerEventsResult, {kind: 'execution'}> {\n return {\n kind: 'execution',\n jobExecutionId: execution.id,\n executionVersion: execution.version,\n sequence: execution.sequence,\n requiredLabels: execution.runner ?? [],\n status: execution.status,\n };\n}\n\nasync function loadListenerMaterializationTarget(jobId: string, tx: Tx) {\n const [target] = await tx\n .select({job: jobs, attempt: workflowRunAttempts, run: workflowRuns})\n .from(jobs)\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(eq(jobs.id, jobId))\n .limit(1)\n .for('update');\n if (!target) throw new Error(`Job not found: ${jobId}`);\n\n const priorExecutions = await tx\n .select()\n .from(jobExecutions)\n .where(eq(jobExecutions.jobId, jobId))\n .orderBy(asc(jobExecutions.sequence), asc(jobExecutions.id));\n return {...target, priorExecutions: priorExecutions.map(toJobExecution)};\n}\n"],"names":["readPersistedWorkflowModel","WORKFLOWS_JOB_ACTIVATED","and","asc","count","eq","inArray","isNull","notInArray","sql","createAgentDefaultsResolver","loadAgentToolMaterializationContext","isJobTerminal","deriveJobSuccess","materializeListenerExecution","applyListenerFilterSnapshots","assembleListenerSnapshotContext","planListenerFilterSnapshots","recordListenerEventsCoalesced","recordWorkflowJobExecutionStatusChanged","recordWorkflowListenerResolved","db","writeWorkflowsOutboxEvent","jobExecutions","toJobExecution","jobListenerEvents","jobs","toJob","steps","workflowRunAttempts","toWorkflowRun","workflowRuns","bulkUpdateStepStatuses","getDirectDependencyJobContexts","updateJobStatusAtVersion","TERMINAL_EXECUTION_STATUSES","MAX_LISTENER_RESOLUTION_ATTEMPTS","applyActivatedListenerFilterSnapshots","plans","context","activateJobListener","params","transaction","tx","target","select","job","run","from","innerJoin","workflowRunAttemptId","id","workflowRunId","where","jobId","limit","for","Error","value","executionCount","includes","status","jobStatus","jobVersion","version","updated","expectedVersion","existing","listenerRows","update","set","listenerStatus","updatedAt","Date","returning","matchers","on","listeningOn","until","listeningUntil","snapshotPlan","dependencyJobs","jobKeys","size","snapshotContext","triggerPayload","inputs","plan","type","payload","workspaceId","mode","drainListenerEventsIntoExecution","drained","findExistingExecution","result","resolveRequested","hasPendingResolveEvent","kind","bufferedEvents","lockBufferedFireEvents","length","loadListenerMaterializationTarget","model","attempt","agentToolContext","agentToolMaterialization","projectId","integrations","projects","undefined","materialized","sequence","expectedSequence","triggerEvents","listenerTriggerEvents","priorExecutions","resolveAgentDefaults","agent","agentToolSnapshot","execution","persistMaterializedListenerExecution","bufferedEventIds","map","event","drainExecutionResult","batchSize","peekListenerBuffer","row","fireCount","disposition","resolvePending","oldestAgeMs","receivedAt","newestAgeMs","consumedByExecutionId","resolveJobListener","decision","deriveJobListenerResolutionDecision","applyJobListenerResolution","changed","reason","jobRow","executionRows","Promise","all","orderBy","success","executions","resolutionReason","statusReason","evaluationTrace","trace","resolvedStatus","settleListenerJobExecution","finishedAt","jobExecutionId","countActiveListeners","resolveEvent","bufferedQuery","maxSize","source","delivery_id","deliveryId","received_at","toISOString","data","insert","values","name","runner","step","key","sourceLocation","config","configPlan","authoredConfig","condition","position","executionVersion","requiredLabels"],"mappings":"AACA,SAAQA,0BAA0B,QAAO,+BAA+B;AAGxE,SACEC,uBAAuB,QAElB,6BAA6B;AACpC,SAAQC,GAAG,EAAEC,GAAG,EAAEC,KAAK,EAAEC,EAAE,EAAEC,OAAO,EAAEC,MAAM,EAAEC,UAAU,EAAEC,GAAG,QAAO,cAAc;AAClF,SAAoCC,2BAA2B,QAAO,0BAA0B;AAChG,SAAQC,mCAAmC,QAAO,uBAAuB;AACzE,SAAQC,aAAa,QAA8C,wBAAwB;AAE3F,SAAqCC,gBAAgB,QAAO,gCAAgC;AAC5F,SAEEC,4BAA4B,QACvB,8CAA8C;AACrD,SACEC,4BAA4B,EAC5BC,+BAA+B,EAE/BC,2BAA2B,QACtB,4CAA4C;AACnD,SACEC,6BAA6B,EAC7BC,uCAAuC,EACvCC,8BAA8B,QACzB,uBAAuB;AAC9B,SAAQC,EAAE,QAAgB,UAAU;AACpC,SAAQC,yBAAyB,QAAO,qBAAqB;AAC7D,SAA6BC,aAAa,EAAEC,cAAc,QAAO,6BAA6B;AAC9F,SAAiCC,iBAAiB,QAAO,kCAA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,kBAAkB3D,UAAUxD,OAAO;QACnCgD,UAAUQ,UAAUR,QAAQ;QAC5BoE,gBAAgB5D,UAAUkD,MAAM,IAAI,EAAE;QACtC7G,QAAQ2D,UAAU3D,MAAM;IAC1B;AACF;AAEA,eAAeyC,kCAAkChD,KAAa,EAAEX,EAAM;IACpE,MAAM,CAACC,OAAO,GAAG,MAAMD,GACpBE,MAAM,CAAC;QAACC,KAAKpB;QAAM8E,SAAS3E;QAAqBkB,KAAKhB;IAAY,GAClEiB,IAAI,CAACtB,MACLuB,SAAS,CAACpB,qBAAqBxB,GAAGqB,KAAKwB,oBAAoB,EAAErB,oBAAoBsB,EAAE,GACnFF,SAAS,CAAClB,cAAc1B,GAAGwB,oBAAoBuB,aAAa,EAAErB,aAAaoB,EAAE,GAC7EE,KAAK,CAAChD,GAAGqB,KAAKyB,EAAE,EAAEG,QAClBC,KAAK,CAAC,GACNC,GAAG,CAAC;IACP,IAAI,CAACZ,QAAQ,MAAM,IAAIa,MAAM,CAAC,eAAe,EAAEH,OAAO;IAEtD,MAAM8D,kBAAkB,MAAMzE,GAC3BE,MAAM,GACNG,IAAI,CAACzB,eACL8B,KAAK,CAAChD,GAAGkB,cAAc+B,KAAK,EAAEA,QAC9B4F,OAAO,CAAC/I,IAAIoB,cAAcyF,QAAQ,GAAG7G,IAAIoB,cAAc4B,EAAE;IAC5D,OAAO;QAAC,GAAGP,MAAM;QAAEwE,iBAAiBA,gBAAgBO,GAAG,CAACnG;IAAe;AACzE"}
@@ -1,5 +1,5 @@
1
1
  export declare const runnerSessionScopeEnum: import("drizzle-orm/pg-core").PgEnum<["workspace"]>;
2
- export declare const runnerSessionRegistrationTokenKindEnum: import("drizzle-orm/pg-core").PgEnum<["manual", "ephemeral"]>;
2
+ export declare const runnerSessionRegistrationTokenKindEnum: import("drizzle-orm/pg-core").PgEnum<["manual", "ephemeral", "activation"]>;
3
3
  export declare const runnerSessions: import("drizzle-orm/pg-core").PgTableWithColumns<{
4
4
  name: "runner_sessions";
5
5
  schema: undefined;
@@ -77,14 +77,14 @@ export declare const runnerSessions: import("drizzle-orm/pg-core").PgTableWithCo
77
77
  tableName: "runner_sessions";
78
78
  dataType: "string";
79
79
  columnType: "PgEnumColumn";
80
- data: "manual" | "ephemeral";
80
+ data: "manual" | "ephemeral" | "activation";
81
81
  driverParam: string;
82
82
  notNull: true;
83
83
  hasDefault: false;
84
84
  isPrimaryKey: false;
85
85
  isAutoincrement: false;
86
86
  hasRuntimeDefault: false;
87
- enumValues: ["manual", "ephemeral"];
87
+ enumValues: ["manual", "ephemeral", "activation"];
88
88
  baseColumn: never;
89
89
  identity: undefined;
90
90
  generated: undefined;
@@ -106,8 +106,8 @@ export declare const runnerSessions: import("drizzle-orm/pg-core").PgTableWithCo
106
106
  identity: undefined;
107
107
  generated: undefined;
108
108
  }, {}, {}>;
109
- provisionedRunnerId: import("drizzle-orm/pg-core").PgColumn<{
110
- name: "provisioned_runner_id";
109
+ providerRunnerId: import("drizzle-orm/pg-core").PgColumn<{
110
+ name: "provider_runner_id";
111
111
  tableName: "runner_sessions";
112
112
  dataType: "string";
113
113
  columnType: "PgText";
@@ -1 +1 @@
1
- {"version":3,"file":"runner-lease-table.d.ts","sourceRoot":"","sources":["../../src/db/runner-lease-table.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,sBAAsB,qDAAwD,CAAC;AAC5F,eAAO,MAAM,sCAAsC,+DAGlD,CAAC;AAEF,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAczB,CAAC;AAEH,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAW/B,CAAC"}
1
+ {"version":3,"file":"runner-lease-table.d.ts","sourceRoot":"","sources":["../../src/db/runner-lease-table.ts"],"names":[],"mappings":"AAKA,eAAO,MAAM,sBAAsB,qDAAwD,CAAC;AAC5F,eAAO,MAAM,sCAAsC,6EAGlD,CAAC;AAEF,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAczB,CAAC;AAEH,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAW/B,CAAC"}
@@ -6,7 +6,8 @@ export const runnerSessionScopeEnum = pgEnum('runners_runner_session_scope', [
6
6
  ]);
7
7
  export const runnerSessionRegistrationTokenKindEnum = pgEnum('runners_runner_session_registration_token_kind', [
8
8
  'manual',
9
- 'ephemeral'
9
+ 'ephemeral',
10
+ 'activation'
10
11
  ]);
11
12
  export const runnerSessions = pgTable('runner_sessions', {
12
13
  id: uuidv7PrimaryKey(),
@@ -15,7 +16,7 @@ export const runnerSessions = pgTable('runner_sessions', {
15
16
  registrationTokenId: uuid('registration_token_id').notNull(),
16
17
  registrationTokenKind: runnerSessionRegistrationTokenKindEnum('registration_token_kind').notNull(),
17
18
  provisionerId: uuid('provisioner_id'),
18
- provisionedRunnerId: text('provisioned_runner_id'),
19
+ providerRunnerId: text('provider_runner_id'),
19
20
  labels: text('labels').array().notNull(),
20
21
  maxClaims: integer('max_claims'),
21
22
  claimsUsed: integer('claims_used').notNull().default(0),
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/db/runner-lease-table.ts"],"sourcesContent":["import {uuidv7PrimaryKey} from '@shipfox/node-drizzle';\nimport {integer, pgEnum, pgTableCreator, text, timestamp, uuid} from 'drizzle-orm/pg-core';\n\nconst pgTable = pgTableCreator((name) => `runners_${name}`);\n\nexport const runnerSessionScopeEnum = pgEnum('runners_runner_session_scope', ['workspace']);\nexport const runnerSessionRegistrationTokenKindEnum = pgEnum(\n 'runners_runner_session_registration_token_kind',\n ['manual', 'ephemeral'],\n);\n\nexport const runnerSessions = pgTable('runner_sessions', {\n id: uuidv7PrimaryKey(),\n workspaceId: uuid('workspace_id').notNull(),\n scope: runnerSessionScopeEnum('scope').notNull().default('workspace'),\n registrationTokenId: uuid('registration_token_id').notNull(),\n registrationTokenKind:\n runnerSessionRegistrationTokenKindEnum('registration_token_kind').notNull(),\n provisionerId: uuid('provisioner_id'),\n provisionedRunnerId: text('provisioned_runner_id'),\n labels: text('labels').array().notNull(),\n maxClaims: integer('max_claims'),\n claimsUsed: integer('claims_used').notNull().default(0),\n createdAt: timestamp('created_at', {withTimezone: true}).notNull().defaultNow(),\n updatedAt: timestamp('updated_at', {withTimezone: true}).notNull().defaultNow(),\n});\n\nexport const runningJobExecutions = pgTable('running_jobs', {\n id: uuidv7PrimaryKey(),\n workspaceId: uuid('workspace_id').notNull(),\n workflowRunId: uuid('workflow_run_id').notNull(),\n workflowRunAttemptId: uuid('workflow_run_attempt_id').notNull(),\n jobId: uuid('job_id').notNull(),\n jobExecutionId: uuid('job_execution_id').notNull(),\n projectId: uuid('project_id').notNull(),\n runnerSessionId: uuid('runner_session_id').notNull(),\n requiredLabels: text('required_labels').array().notNull(),\n runnerLabels: text('runner_labels').array().notNull(),\n});\n"],"names":["uuidv7PrimaryKey","integer","pgEnum","pgTableCreator","text","timestamp","uuid","pgTable","name","runnerSessionScopeEnum","runnerSessionRegistrationTokenKindEnum","runnerSessions","id","workspaceId","notNull","scope","default","registrationTokenId","registrationTokenKind","provisionerId","provisionedRunnerId","labels","array","maxClaims","claimsUsed","createdAt","withTimezone","defaultNow","updatedAt","runningJobExecutions","workflowRunId","workflowRunAttemptId","jobId","jobExecutionId","projectId","runnerSessionId","requiredLabels","runnerLabels"],"mappings":"AAAA,SAAQA,gBAAgB,QAAO,wBAAwB;AACvD,SAAQC,OAAO,EAAEC,MAAM,EAAEC,cAAc,EAAEC,IAAI,EAAEC,SAAS,EAAEC,IAAI,QAAO,sBAAsB;AAE3F,MAAMC,UAAUJ,eAAe,CAACK,OAAS,CAAC,QAAQ,EAAEA,MAAM;AAE1D,OAAO,MAAMC,yBAAyBP,OAAO,gCAAgC;IAAC;CAAY,EAAE;AAC5F,OAAO,MAAMQ,yCAAyCR,OACpD,kDACA;IAAC;IAAU;CAAY,EACvB;AAEF,OAAO,MAAMS,iBAAiBJ,QAAQ,mBAAmB;IACvDK,IAAIZ;IACJa,aAAaP,KAAK,gBAAgBQ,OAAO;IACzCC,OAAON,uBAAuB,SAASK,OAAO,GAAGE,OAAO,CAAC;IACzDC,qBAAqBX,KAAK,yBAAyBQ,OAAO;IAC1DI,uBACER,uCAAuC,2BAA2BI,OAAO;IAC3EK,eAAeb,KAAK;IACpBc,qBAAqBhB,KAAK;IAC1BiB,QAAQjB,KAAK,UAAUkB,KAAK,GAAGR,OAAO;IACtCS,WAAWtB,QAAQ;IACnBuB,YAAYvB,QAAQ,eAAea,OAAO,GAAGE,OAAO,CAAC;IACrDS,WAAWpB,UAAU,cAAc;QAACqB,cAAc;IAAI,GAAGZ,OAAO,GAAGa,UAAU;IAC7EC,WAAWvB,UAAU,cAAc;QAACqB,cAAc;IAAI,GAAGZ,OAAO,GAAGa,UAAU;AAC/E,GAAG;AAEH,OAAO,MAAME,uBAAuBtB,QAAQ,gBAAgB;IAC1DK,IAAIZ;IACJa,aAAaP,KAAK,gBAAgBQ,OAAO;IACzCgB,eAAexB,KAAK,mBAAmBQ,OAAO;IAC9CiB,sBAAsBzB,KAAK,2BAA2BQ,OAAO;IAC7DkB,OAAO1B,KAAK,UAAUQ,OAAO;IAC7BmB,gBAAgB3B,KAAK,oBAAoBQ,OAAO;IAChDoB,WAAW5B,KAAK,cAAcQ,OAAO;IACrCqB,iBAAiB7B,KAAK,qBAAqBQ,OAAO;IAClDsB,gBAAgBhC,KAAK,mBAAmBkB,KAAK,GAAGR,OAAO;IACvDuB,cAAcjC,KAAK,iBAAiBkB,KAAK,GAAGR,OAAO;AACrD,GAAG"}
1
+ {"version":3,"sources":["../../src/db/runner-lease-table.ts"],"sourcesContent":["import {uuidv7PrimaryKey} from '@shipfox/node-drizzle';\nimport {integer, pgEnum, pgTableCreator, text, timestamp, uuid} from 'drizzle-orm/pg-core';\n\nconst pgTable = pgTableCreator((name) => `runners_${name}`);\n\nexport const runnerSessionScopeEnum = pgEnum('runners_runner_session_scope', ['workspace']);\nexport const runnerSessionRegistrationTokenKindEnum = pgEnum(\n 'runners_runner_session_registration_token_kind',\n ['manual', 'ephemeral', 'activation'],\n);\n\nexport const runnerSessions = pgTable('runner_sessions', {\n id: uuidv7PrimaryKey(),\n workspaceId: uuid('workspace_id').notNull(),\n scope: runnerSessionScopeEnum('scope').notNull().default('workspace'),\n registrationTokenId: uuid('registration_token_id').notNull(),\n registrationTokenKind:\n runnerSessionRegistrationTokenKindEnum('registration_token_kind').notNull(),\n provisionerId: uuid('provisioner_id'),\n providerRunnerId: text('provider_runner_id'),\n labels: text('labels').array().notNull(),\n maxClaims: integer('max_claims'),\n claimsUsed: integer('claims_used').notNull().default(0),\n createdAt: timestamp('created_at', {withTimezone: true}).notNull().defaultNow(),\n updatedAt: timestamp('updated_at', {withTimezone: true}).notNull().defaultNow(),\n});\n\nexport const runningJobExecutions = pgTable('running_jobs', {\n id: uuidv7PrimaryKey(),\n workspaceId: uuid('workspace_id').notNull(),\n workflowRunId: uuid('workflow_run_id').notNull(),\n workflowRunAttemptId: uuid('workflow_run_attempt_id').notNull(),\n jobId: uuid('job_id').notNull(),\n jobExecutionId: uuid('job_execution_id').notNull(),\n projectId: uuid('project_id').notNull(),\n runnerSessionId: uuid('runner_session_id').notNull(),\n requiredLabels: text('required_labels').array().notNull(),\n runnerLabels: text('runner_labels').array().notNull(),\n});\n"],"names":["uuidv7PrimaryKey","integer","pgEnum","pgTableCreator","text","timestamp","uuid","pgTable","name","runnerSessionScopeEnum","runnerSessionRegistrationTokenKindEnum","runnerSessions","id","workspaceId","notNull","scope","default","registrationTokenId","registrationTokenKind","provisionerId","providerRunnerId","labels","array","maxClaims","claimsUsed","createdAt","withTimezone","defaultNow","updatedAt","runningJobExecutions","workflowRunId","workflowRunAttemptId","jobId","jobExecutionId","projectId","runnerSessionId","requiredLabels","runnerLabels"],"mappings":"AAAA,SAAQA,gBAAgB,QAAO,wBAAwB;AACvD,SAAQC,OAAO,EAAEC,MAAM,EAAEC,cAAc,EAAEC,IAAI,EAAEC,SAAS,EAAEC,IAAI,QAAO,sBAAsB;AAE3F,MAAMC,UAAUJ,eAAe,CAACK,OAAS,CAAC,QAAQ,EAAEA,MAAM;AAE1D,OAAO,MAAMC,yBAAyBP,OAAO,gCAAgC;IAAC;CAAY,EAAE;AAC5F,OAAO,MAAMQ,yCAAyCR,OACpD,kDACA;IAAC;IAAU;IAAa;CAAa,EACrC;AAEF,OAAO,MAAMS,iBAAiBJ,QAAQ,mBAAmB;IACvDK,IAAIZ;IACJa,aAAaP,KAAK,gBAAgBQ,OAAO;IACzCC,OAAON,uBAAuB,SAASK,OAAO,GAAGE,OAAO,CAAC;IACzDC,qBAAqBX,KAAK,yBAAyBQ,OAAO;IAC1DI,uBACER,uCAAuC,2BAA2BI,OAAO;IAC3EK,eAAeb,KAAK;IACpBc,kBAAkBhB,KAAK;IACvBiB,QAAQjB,KAAK,UAAUkB,KAAK,GAAGR,OAAO;IACtCS,WAAWtB,QAAQ;IACnBuB,YAAYvB,QAAQ,eAAea,OAAO,GAAGE,OAAO,CAAC;IACrDS,WAAWpB,UAAU,cAAc;QAACqB,cAAc;IAAI,GAAGZ,OAAO,GAAGa,UAAU;IAC7EC,WAAWvB,UAAU,cAAc;QAACqB,cAAc;IAAI,GAAGZ,OAAO,GAAGa,UAAU;AAC/E,GAAG;AAEH,OAAO,MAAME,uBAAuBtB,QAAQ,gBAAgB;IAC1DK,IAAIZ;IACJa,aAAaP,KAAK,gBAAgBQ,OAAO;IACzCgB,eAAexB,KAAK,mBAAmBQ,OAAO;IAC9CiB,sBAAsBzB,KAAK,2BAA2BQ,OAAO;IAC7DkB,OAAO1B,KAAK,UAAUQ,OAAO;IAC7BmB,gBAAgB3B,KAAK,oBAAoBQ,OAAO;IAChDoB,WAAW5B,KAAK,cAAcQ,OAAO;IACrCqB,iBAAiB7B,KAAK,qBAAqBQ,OAAO;IAClDsB,gBAAgBhC,KAAK,mBAAmBkB,KAAK,GAAGR,OAAO;IACvDuB,cAAcjC,KAAK,iBAAiBkB,KAAK,GAAGR,OAAO;AACrD,GAAG"}
@@ -1,4 +1,4 @@
1
- import type { WorkflowModel } from '@shipfox/api-definitions';
1
+ import { type WorkflowModel } from '@shipfox/api-definitions-dto';
2
2
  import type { AgentToolMaterializationSnapshot } from '#core/agent-tools.js';
3
3
  import type { WorkflowRunAttempt } from '#core/entities/workflow-run-attempt.js';
4
4
  export declare const workflowRunAttempts: import("drizzle-orm/pg-core").PgTableWithColumns<{
@@ -112,7 +112,10 @@ export declare const workflowRunAttempts: import("drizzle-orm/pg-core").PgTableW
112
112
  tableName: "workflow_run_attempts";
113
113
  dataType: "json";
114
114
  columnType: "PgJsonb";
115
- data: WorkflowModel;
115
+ data: WorkflowModel | {
116
+ version: 1;
117
+ model: WorkflowModel;
118
+ };
116
119
  driverParam: unknown;
117
120
  notNull: false;
118
121
  hasDefault: false;
@@ -124,7 +127,10 @@ export declare const workflowRunAttempts: import("drizzle-orm/pg-core").PgTableW
124
127
  identity: undefined;
125
128
  generated: undefined;
126
129
  }, {}, {
127
- $type: WorkflowModel;
130
+ $type: WorkflowModel | {
131
+ version: 1;
132
+ model: WorkflowModel;
133
+ };
128
134
  }>;
129
135
  agentToolMaterialization: import("drizzle-orm/pg-core").PgColumn<{
130
136
  name: "agent_tool_materialization";
@@ -1 +1 @@
1
- {"version":3,"file":"workflow-run-attempts.d.ts","sourceRoot":"","sources":["../../../src/db/schema/workflow-run-attempts.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,aAAa,EAAC,MAAM,0BAA0B,CAAC;AAI5D,OAAO,KAAK,EAAC,gCAAgC,EAAC,MAAM,sBAAsB,CAAC;AAC3E,OAAO,KAAK,EAAC,kBAAkB,EAAC,MAAM,wCAAwC,CAAC;AAI/E,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA4B/B,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG,OAAO,mBAAmB,CAAC,YAAY,CAAC;AAC3E,MAAM,MAAM,0BAA0B,GAAG,OAAO,mBAAmB,CAAC,YAAY,CAAC;AAEjF,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,oBAAoB,GAAG,kBAAkB,CAgBlF"}
1
+ {"version":3,"file":"workflow-run-attempts.d.ts","sourceRoot":"","sources":["../../../src/db/schema/workflow-run-attempts.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,aAAa,EAEnB,MAAM,8BAA8B,CAAC;AAItC,OAAO,KAAK,EAAC,gCAAgC,EAAC,MAAM,sBAAsB,CAAC;AAC3E,OAAO,KAAK,EAAC,kBAAkB,EAAC,MAAM,wCAAwC,CAAC;AAI/E,eAAO,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA4B/B,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG,OAAO,mBAAmB,CAAC,YAAY,CAAC;AAC3E,MAAM,MAAM,0BAA0B,GAAG,OAAO,mBAAmB,CAAC,YAAY,CAAC;AAEjF,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,oBAAoB,GAAG,kBAAkB,CAgBlF"}
@@ -1,3 +1,4 @@
1
+ import { readPersistedWorkflowModel } from '@shipfox/api-definitions-dto';
1
2
  import { uuidv7PrimaryKey } from '@shipfox/node-drizzle';
2
3
  import { sql } from 'drizzle-orm';
3
4
  import { check, integer, jsonb, timestamp, uniqueIndex, uuid } from 'drizzle-orm/pg-core';
@@ -40,7 +41,7 @@ export function toWorkflowRunAttempt(row) {
40
41
  status: row.status,
41
42
  rerunMode: row.rerunMode ?? null,
42
43
  rerunByUserId: row.rerunByUserId,
43
- model: row.model ?? null,
44
+ model: row.model === null ? null : readPersistedWorkflowModel(row.model),
44
45
  agentToolMaterialization: row.agentToolMaterialization ?? null,
45
46
  version: row.version,
46
47
  createdAt: row.createdAt,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/db/schema/workflow-run-attempts.ts"],"sourcesContent":["import type {WorkflowModel} from '@shipfox/api-definitions';\nimport {uuidv7PrimaryKey} from '@shipfox/node-drizzle';\nimport {sql} from 'drizzle-orm';\nimport {check, integer, jsonb, timestamp, uniqueIndex, uuid} from 'drizzle-orm/pg-core';\nimport type {AgentToolMaterializationSnapshot} from '#core/agent-tools.js';\nimport type {WorkflowRunAttempt} from '#core/entities/workflow-run-attempt.js';\nimport {pgTable} from './common.js';\nimport {workflowRunRerunModeEnum, workflowRunStatusEnum, workflowRuns} from './workflow-runs.js';\n\nexport const workflowRunAttempts = pgTable(\n 'workflow_run_attempts',\n {\n id: uuidv7PrimaryKey(),\n workflowRunId: uuid('workflow_run_id')\n .notNull()\n .references(() => workflowRuns.id, {onDelete: 'cascade'}),\n attempt: integer('attempt').notNull(),\n status: workflowRunStatusEnum('status').notNull().default('pending'),\n rerunMode: workflowRunRerunModeEnum('rerun_mode'),\n rerunByUserId: uuid('rerun_by_user_id'),\n model: jsonb('model').$type<WorkflowModel>(),\n agentToolMaterialization: jsonb(\n 'agent_tool_materialization',\n ).$type<AgentToolMaterializationSnapshot>(),\n version: integer('version').notNull().default(1),\n createdAt: timestamp('created_at', {withTimezone: true}).notNull().defaultNow(),\n updatedAt: timestamp('updated_at', {withTimezone: true}).notNull().defaultNow(),\n startedAt: timestamp('started_at', {withTimezone: true}),\n finishedAt: timestamp('finished_at', {withTimezone: true}),\n },\n (table) => [\n uniqueIndex('workflows_wra_workflow_run_attempt_unique').on(table.workflowRunId, table.attempt),\n check('workflows_wra_attempt_positive_ck', sql`${table.attempt} > 0`),\n uniqueIndex('workflows_wra_one_active_attempt_unique')\n .on(table.workflowRunId)\n .where(sql`${table.status} in ('pending', 'running')`),\n ],\n);\n\nexport type WorkflowRunAttemptDb = typeof workflowRunAttempts.$inferSelect;\nexport type WorkflowRunAttemptCreateDb = typeof workflowRunAttempts.$inferInsert;\n\nexport function toWorkflowRunAttempt(row: WorkflowRunAttemptDb): WorkflowRunAttempt {\n return {\n id: row.id,\n workflowRunId: row.workflowRunId,\n attempt: row.attempt,\n status: row.status,\n rerunMode: row.rerunMode ?? null,\n rerunByUserId: row.rerunByUserId,\n model: row.model ?? null,\n agentToolMaterialization: row.agentToolMaterialization ?? null,\n version: row.version,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n startedAt: row.startedAt,\n finishedAt: row.finishedAt,\n };\n}\n"],"names":["uuidv7PrimaryKey","sql","check","integer","jsonb","timestamp","uniqueIndex","uuid","pgTable","workflowRunRerunModeEnum","workflowRunStatusEnum","workflowRuns","workflowRunAttempts","id","workflowRunId","notNull","references","onDelete","attempt","status","default","rerunMode","rerunByUserId","model","$type","agentToolMaterialization","version","createdAt","withTimezone","defaultNow","updatedAt","startedAt","finishedAt","table","on","where","toWorkflowRunAttempt","row"],"mappings":"AACA,SAAQA,gBAAgB,QAAO,wBAAwB;AACvD,SAAQC,GAAG,QAAO,cAAc;AAChC,SAAQC,KAAK,EAAEC,OAAO,EAAEC,KAAK,EAAEC,SAAS,EAAEC,WAAW,EAAEC,IAAI,QAAO,sBAAsB;AAGxF,SAAQC,OAAO,QAAO,cAAc;AACpC,SAAQC,wBAAwB,EAAEC,qBAAqB,EAAEC,YAAY,QAAO,qBAAqB;AAEjG,OAAO,MAAMC,sBAAsBJ,QACjC,yBACA;IACEK,IAAIb;IACJc,eAAeP,KAAK,mBACjBQ,OAAO,GACPC,UAAU,CAAC,IAAML,aAAaE,EAAE,EAAE;QAACI,UAAU;IAAS;IACzDC,SAASf,QAAQ,WAAWY,OAAO;IACnCI,QAAQT,sBAAsB,UAAUK,OAAO,GAAGK,OAAO,CAAC;IAC1DC,WAAWZ,yBAAyB;IACpCa,eAAef,KAAK;IACpBgB,OAAOnB,MAAM,SAASoB,KAAK;IAC3BC,0BAA0BrB,MACxB,8BACAoB,KAAK;IACPE,SAASvB,QAAQ,WAAWY,OAAO,GAAGK,OAAO,CAAC;IAC9CO,WAAWtB,UAAU,cAAc;QAACuB,cAAc;IAAI,GAAGb,OAAO,GAAGc,UAAU;IAC7EC,WAAWzB,UAAU,cAAc;QAACuB,cAAc;IAAI,GAAGb,OAAO,GAAGc,UAAU;IAC7EE,WAAW1B,UAAU,cAAc;QAACuB,cAAc;IAAI;IACtDI,YAAY3B,UAAU,eAAe;QAACuB,cAAc;IAAI;AAC1D,GACA,CAACK,QAAU;QACT3B,YAAY,6CAA6C4B,EAAE,CAACD,MAAMnB,aAAa,EAAEmB,MAAMf,OAAO;QAC9FhB,MAAM,qCAAqCD,GAAG,CAAC,EAAEgC,MAAMf,OAAO,CAAC,IAAI,CAAC;QACpEZ,YAAY,2CACT4B,EAAE,CAACD,MAAMnB,aAAa,EACtBqB,KAAK,CAAClC,GAAG,CAAC,EAAEgC,MAAMd,MAAM,CAAC,0BAA0B,CAAC;KACxD,EACD;AAKF,OAAO,SAASiB,qBAAqBC,GAAyB;IAC5D,OAAO;QACLxB,IAAIwB,IAAIxB,EAAE;QACVC,eAAeuB,IAAIvB,aAAa;QAChCI,SAASmB,IAAInB,OAAO;QACpBC,QAAQkB,IAAIlB,MAAM;QAClBE,WAAWgB,IAAIhB,SAAS,IAAI;QAC5BC,eAAee,IAAIf,aAAa;QAChCC,OAAOc,IAAId,KAAK,IAAI;QACpBE,0BAA0BY,IAAIZ,wBAAwB,IAAI;QAC1DC,SAASW,IAAIX,OAAO;QACpBC,WAAWU,IAAIV,SAAS;QACxBG,WAAWO,IAAIP,SAAS;QACxBC,WAAWM,IAAIN,SAAS;QACxBC,YAAYK,IAAIL,UAAU;IAC5B;AACF"}
1
+ {"version":3,"sources":["../../../src/db/schema/workflow-run-attempts.ts"],"sourcesContent":["import {\n readPersistedWorkflowModel,\n type WorkflowModel,\n type WorkflowModelSnapshot,\n} from '@shipfox/api-definitions-dto';\nimport {uuidv7PrimaryKey} from '@shipfox/node-drizzle';\nimport {sql} from 'drizzle-orm';\nimport {check, integer, jsonb, timestamp, uniqueIndex, uuid} from 'drizzle-orm/pg-core';\nimport type {AgentToolMaterializationSnapshot} from '#core/agent-tools.js';\nimport type {WorkflowRunAttempt} from '#core/entities/workflow-run-attempt.js';\nimport {pgTable} from './common.js';\nimport {workflowRunRerunModeEnum, workflowRunStatusEnum, workflowRuns} from './workflow-runs.js';\n\nexport const workflowRunAttempts = pgTable(\n 'workflow_run_attempts',\n {\n id: uuidv7PrimaryKey(),\n workflowRunId: uuid('workflow_run_id')\n .notNull()\n .references(() => workflowRuns.id, {onDelete: 'cascade'}),\n attempt: integer('attempt').notNull(),\n status: workflowRunStatusEnum('status').notNull().default('pending'),\n rerunMode: workflowRunRerunModeEnum('rerun_mode'),\n rerunByUserId: uuid('rerun_by_user_id'),\n model: jsonb('model').$type<WorkflowModel | WorkflowModelSnapshot>(),\n agentToolMaterialization: jsonb(\n 'agent_tool_materialization',\n ).$type<AgentToolMaterializationSnapshot>(),\n version: integer('version').notNull().default(1),\n createdAt: timestamp('created_at', {withTimezone: true}).notNull().defaultNow(),\n updatedAt: timestamp('updated_at', {withTimezone: true}).notNull().defaultNow(),\n startedAt: timestamp('started_at', {withTimezone: true}),\n finishedAt: timestamp('finished_at', {withTimezone: true}),\n },\n (table) => [\n uniqueIndex('workflows_wra_workflow_run_attempt_unique').on(table.workflowRunId, table.attempt),\n check('workflows_wra_attempt_positive_ck', sql`${table.attempt} > 0`),\n uniqueIndex('workflows_wra_one_active_attempt_unique')\n .on(table.workflowRunId)\n .where(sql`${table.status} in ('pending', 'running')`),\n ],\n);\n\nexport type WorkflowRunAttemptDb = typeof workflowRunAttempts.$inferSelect;\nexport type WorkflowRunAttemptCreateDb = typeof workflowRunAttempts.$inferInsert;\n\nexport function toWorkflowRunAttempt(row: WorkflowRunAttemptDb): WorkflowRunAttempt {\n return {\n id: row.id,\n workflowRunId: row.workflowRunId,\n attempt: row.attempt,\n status: row.status,\n rerunMode: row.rerunMode ?? null,\n rerunByUserId: row.rerunByUserId,\n model: row.model === null ? null : readPersistedWorkflowModel(row.model),\n agentToolMaterialization: row.agentToolMaterialization ?? null,\n version: row.version,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n startedAt: row.startedAt,\n finishedAt: row.finishedAt,\n };\n}\n"],"names":["readPersistedWorkflowModel","uuidv7PrimaryKey","sql","check","integer","jsonb","timestamp","uniqueIndex","uuid","pgTable","workflowRunRerunModeEnum","workflowRunStatusEnum","workflowRuns","workflowRunAttempts","id","workflowRunId","notNull","references","onDelete","attempt","status","default","rerunMode","rerunByUserId","model","$type","agentToolMaterialization","version","createdAt","withTimezone","defaultNow","updatedAt","startedAt","finishedAt","table","on","where","toWorkflowRunAttempt","row"],"mappings":"AAAA,SACEA,0BAA0B,QAGrB,+BAA+B;AACtC,SAAQC,gBAAgB,QAAO,wBAAwB;AACvD,SAAQC,GAAG,QAAO,cAAc;AAChC,SAAQC,KAAK,EAAEC,OAAO,EAAEC,KAAK,EAAEC,SAAS,EAAEC,WAAW,EAAEC,IAAI,QAAO,sBAAsB;AAGxF,SAAQC,OAAO,QAAO,cAAc;AACpC,SAAQC,wBAAwB,EAAEC,qBAAqB,EAAEC,YAAY,QAAO,qBAAqB;AAEjG,OAAO,MAAMC,sBAAsBJ,QACjC,yBACA;IACEK,IAAIb;IACJc,eAAeP,KAAK,mBACjBQ,OAAO,GACPC,UAAU,CAAC,IAAML,aAAaE,EAAE,EAAE;QAACI,UAAU;IAAS;IACzDC,SAASf,QAAQ,WAAWY,OAAO;IACnCI,QAAQT,sBAAsB,UAAUK,OAAO,GAAGK,OAAO,CAAC;IAC1DC,WAAWZ,yBAAyB;IACpCa,eAAef,KAAK;IACpBgB,OAAOnB,MAAM,SAASoB,KAAK;IAC3BC,0BAA0BrB,MACxB,8BACAoB,KAAK;IACPE,SAASvB,QAAQ,WAAWY,OAAO,GAAGK,OAAO,CAAC;IAC9CO,WAAWtB,UAAU,cAAc;QAACuB,cAAc;IAAI,GAAGb,OAAO,GAAGc,UAAU;IAC7EC,WAAWzB,UAAU,cAAc;QAACuB,cAAc;IAAI,GAAGb,OAAO,GAAGc,UAAU;IAC7EE,WAAW1B,UAAU,cAAc;QAACuB,cAAc;IAAI;IACtDI,YAAY3B,UAAU,eAAe;QAACuB,cAAc;IAAI;AAC1D,GACA,CAACK,QAAU;QACT3B,YAAY,6CAA6C4B,EAAE,CAACD,MAAMnB,aAAa,EAAEmB,MAAMf,OAAO;QAC9FhB,MAAM,qCAAqCD,GAAG,CAAC,EAAEgC,MAAMf,OAAO,CAAC,IAAI,CAAC;QACpEZ,YAAY,2CACT4B,EAAE,CAACD,MAAMnB,aAAa,EACtBqB,KAAK,CAAClC,GAAG,CAAC,EAAEgC,MAAMd,MAAM,CAAC,0BAA0B,CAAC;KACxD,EACD;AAKF,OAAO,SAASiB,qBAAqBC,GAAyB;IAC5D,OAAO;QACLxB,IAAIwB,IAAIxB,EAAE;QACVC,eAAeuB,IAAIvB,aAAa;QAChCI,SAASmB,IAAInB,OAAO;QACpBC,QAAQkB,IAAIlB,MAAM;QAClBE,WAAWgB,IAAIhB,SAAS,IAAI;QAC5BC,eAAee,IAAIf,aAAa;QAChCC,OAAOc,IAAId,KAAK,KAAK,OAAO,OAAOxB,2BAA2BsC,IAAId,KAAK;QACvEE,0BAA0BY,IAAIZ,wBAAwB,IAAI;QAC1DC,SAASW,IAAIX,OAAO;QACpBC,WAAWU,IAAIV,SAAS;QACxBG,WAAWO,IAAIP,SAAS;QACxBC,WAAWM,IAAIN,SAAS;QACxBC,YAAYK,IAAIL,UAAU;IAC5B;AACF"}
@@ -1,4 +1,4 @@
1
- import { DEFAULT_RUN_TIMEOUT_MS } from '@shipfox/api-definitions';
1
+ import { DEFAULT_RUN_TIMEOUT_MS } from '@shipfox/api-definitions-dto';
2
2
  import { uuidv7PrimaryKey } from '@shipfox/node-drizzle';
3
3
  import { sql } from 'drizzle-orm';
4
4
  import { bigint, check, index, integer, jsonb, pgEnum, text, timestamp, uniqueIndex, uuid } from 'drizzle-orm/pg-core';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/db/schema/workflow-runs.ts"],"sourcesContent":["import {DEFAULT_RUN_TIMEOUT_MS} from '@shipfox/api-definitions';\nimport {uuidv7PrimaryKey} from '@shipfox/node-drizzle';\nimport {sql} from 'drizzle-orm';\nimport {\n bigint,\n check,\n index,\n integer,\n jsonb,\n pgEnum,\n text,\n timestamp,\n uniqueIndex,\n uuid,\n} from 'drizzle-orm/pg-core';\nimport type {\n TriggerPayload,\n WorkflowRun,\n WorkflowSourceSnapshot,\n} from '#core/entities/workflow-run.js';\nimport {pgTable} from './common.js';\n\nexport const workflowRunStatusEnum = pgEnum('workflows_run_status', [\n 'pending',\n 'running',\n 'succeeded',\n 'failed',\n 'cancelled',\n]);\n\nexport const workflowRunRerunModeEnum = pgEnum('workflows_rerun_mode', ['all', 'failed']);\n\nexport const workflowRuns = pgTable(\n 'workflow_runs',\n {\n id: uuidv7PrimaryKey(),\n workspaceId: uuid('workspace_id').notNull(),\n projectId: uuid('project_id').notNull(),\n definitionId: uuid('definition_id').notNull(),\n name: text('name').notNull(),\n status: workflowRunStatusEnum('status').notNull().default('pending'),\n currentAttempt: integer('current_attempt').notNull().default(1),\n triggerProvider: text('trigger_provider'),\n triggerSource: text('trigger_source').notNull(),\n triggerEvent: text('trigger_event').notNull(),\n triggerPayload: jsonb('trigger_payload').notNull().$type<TriggerPayload>(),\n inputs: jsonb('inputs').$type<Record<string, unknown>>(),\n sourceSnapshot: jsonb('source_snapshot').$type<WorkflowSourceSnapshot>(),\n triggerIdempotencyKey: text('trigger_idempotency_key'),\n timeoutMs: bigint('timeout_ms', {mode: 'number'}).notNull().default(DEFAULT_RUN_TIMEOUT_MS),\n version: integer('version').notNull().default(1),\n createdAt: timestamp('created_at', {withTimezone: true}).notNull().defaultNow(),\n updatedAt: timestamp('updated_at', {withTimezone: true}).notNull().defaultNow(),\n startedAt: timestamp('started_at', {withTimezone: true}),\n finishedAt: timestamp('finished_at', {withTimezone: true}),\n },\n (table) => [\n uniqueIndex('workflows_wr_trigger_idempotency_key_unique').on(table.triggerIdempotencyKey),\n index('workflows_wr_project_created_id_idx').on(table.projectId, table.createdAt, table.id),\n index('workflows_wr_project_status_created_id_idx').on(\n table.projectId,\n table.status,\n table.createdAt,\n table.id,\n ),\n index('workflows_wr_project_definition_created_id_idx').on(\n table.projectId,\n table.definitionId,\n table.createdAt,\n table.id,\n ),\n index('workflows_wr_project_trigger_created_id_idx').on(\n table.projectId,\n table.triggerSource,\n table.createdAt,\n table.id,\n ),\n // Partial index backing the running-runs depth gauge, which counts on every\n // Prometheus scrape. Indexes only active rows so the count stays cheap as the\n // historical table grows.\n index('workflows_wr_running_idx').on(table.status).where(sql`${table.status} = 'running'`),\n check('workflows_wr_current_attempt_positive_ck', sql`${table.currentAttempt} > 0`),\n ],\n);\n\nexport type WorkflowRunDb = typeof workflowRuns.$inferSelect;\nexport type WorkflowRunCreateDb = typeof workflowRuns.$inferInsert;\n\nexport function toWorkflowRun(row: WorkflowRunDb): WorkflowRun {\n return {\n id: row.id,\n workspaceId: row.workspaceId,\n projectId: row.projectId,\n definitionId: row.definitionId,\n name: row.name,\n status: row.status,\n currentAttempt: row.currentAttempt,\n triggerProvider: row.triggerProvider,\n triggerSource: row.triggerSource,\n triggerEvent: row.triggerEvent,\n triggerPayload: row.triggerPayload as TriggerPayload,\n inputs: row.inputs ?? null,\n sourceSnapshot: row.sourceSnapshot ?? null,\n triggerIdempotencyKey: row.triggerIdempotencyKey,\n timeoutMs: row.timeoutMs,\n version: row.version,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n startedAt: row.startedAt,\n finishedAt: row.finishedAt,\n };\n}\n"],"names":["DEFAULT_RUN_TIMEOUT_MS","uuidv7PrimaryKey","sql","bigint","check","index","integer","jsonb","pgEnum","text","timestamp","uniqueIndex","uuid","pgTable","workflowRunStatusEnum","workflowRunRerunModeEnum","workflowRuns","id","workspaceId","notNull","projectId","definitionId","name","status","default","currentAttempt","triggerProvider","triggerSource","triggerEvent","triggerPayload","$type","inputs","sourceSnapshot","triggerIdempotencyKey","timeoutMs","mode","version","createdAt","withTimezone","defaultNow","updatedAt","startedAt","finishedAt","table","on","where","toWorkflowRun","row"],"mappings":"AAAA,SAAQA,sBAAsB,QAAO,2BAA2B;AAChE,SAAQC,gBAAgB,QAAO,wBAAwB;AACvD,SAAQC,GAAG,QAAO,cAAc;AAChC,SACEC,MAAM,EACNC,KAAK,EACLC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,MAAM,EACNC,IAAI,EACJC,SAAS,EACTC,WAAW,EACXC,IAAI,QACC,sBAAsB;AAM7B,SAAQC,OAAO,QAAO,cAAc;AAEpC,OAAO,MAAMC,wBAAwBN,OAAO,wBAAwB;IAClE;IACA;IACA;IACA;IACA;CACD,EAAE;AAEH,OAAO,MAAMO,2BAA2BP,OAAO,wBAAwB;IAAC;IAAO;CAAS,EAAE;AAE1F,OAAO,MAAMQ,eAAeH,QAC1B,iBACA;IACEI,IAAIhB;IACJiB,aAAaN,KAAK,gBAAgBO,OAAO;IACzCC,WAAWR,KAAK,cAAcO,OAAO;IACrCE,cAAcT,KAAK,iBAAiBO,OAAO;IAC3CG,MAAMb,KAAK,QAAQU,OAAO;IAC1BI,QAAQT,sBAAsB,UAAUK,OAAO,GAAGK,OAAO,CAAC;IAC1DC,gBAAgBnB,QAAQ,mBAAmBa,OAAO,GAAGK,OAAO,CAAC;IAC7DE,iBAAiBjB,KAAK;IACtBkB,eAAelB,KAAK,kBAAkBU,OAAO;IAC7CS,cAAcnB,KAAK,iBAAiBU,OAAO;IAC3CU,gBAAgBtB,MAAM,mBAAmBY,OAAO,GAAGW,KAAK;IACxDC,QAAQxB,MAAM,UAAUuB,KAAK;IAC7BE,gBAAgBzB,MAAM,mBAAmBuB,KAAK;IAC9CG,uBAA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OAAO;QACL9B,IAAI8B,IAAI9B,EAAE;QACVC,aAAa6B,IAAI7B,WAAW;QAC5BE,WAAW2B,IAAI3B,SAAS;QACxBC,cAAc0B,IAAI1B,YAAY;QAC9BC,MAAMyB,IAAIzB,IAAI;QACdC,QAAQwB,IAAIxB,MAAM;QAClBE,gBAAgBsB,IAAItB,cAAc;QAClCC,iBAAiBqB,IAAIrB,eAAe;QACpCC,eAAeoB,IAAIpB,aAAa;QAChCC,cAAcmB,IAAInB,YAAY;QAC9BC,gBAAgBkB,IAAIlB,cAAc;QAClCE,QAAQgB,IAAIhB,MAAM,IAAI;QACtBC,gBAAgBe,IAAIf,cAAc,IAAI;QACtCC,uBAAuBc,IAAId,qBAAqB;QAChDC,WAAWa,IAAIb,SAAS;QACxBE,SAASW,IAAIX,OAAO;QACpBC,WAAWU,IAAIV,SAAS;QACxBG,WAAWO,IAAIP,SAAS;QACxBC,WAAWM,IAAIN,SAAS;QACxBC,YAAYK,IAAIL,UAAU;IAC5B;AACF"}
1
+ {"version":3,"sources":["../../../src/db/schema/workflow-runs.ts"],"sourcesContent":["import {DEFAULT_RUN_TIMEOUT_MS} from '@shipfox/api-definitions-dto';\nimport {uuidv7PrimaryKey} from '@shipfox/node-drizzle';\nimport {sql} from 'drizzle-orm';\nimport {\n bigint,\n check,\n index,\n integer,\n jsonb,\n pgEnum,\n text,\n timestamp,\n uniqueIndex,\n uuid,\n} from 'drizzle-orm/pg-core';\nimport type {\n TriggerPayload,\n WorkflowRun,\n WorkflowSourceSnapshot,\n} from '#core/entities/workflow-run.js';\nimport {pgTable} from './common.js';\n\nexport const workflowRunStatusEnum = pgEnum('workflows_run_status', [\n 'pending',\n 'running',\n 'succeeded',\n 'failed',\n 'cancelled',\n]);\n\nexport const workflowRunRerunModeEnum = pgEnum('workflows_rerun_mode', ['all', 'failed']);\n\nexport const workflowRuns = pgTable(\n 'workflow_runs',\n {\n id: uuidv7PrimaryKey(),\n workspaceId: uuid('workspace_id').notNull(),\n projectId: uuid('project_id').notNull(),\n definitionId: uuid('definition_id').notNull(),\n name: text('name').notNull(),\n status: workflowRunStatusEnum('status').notNull().default('pending'),\n currentAttempt: integer('current_attempt').notNull().default(1),\n triggerProvider: text('trigger_provider'),\n triggerSource: text('trigger_source').notNull(),\n triggerEvent: text('trigger_event').notNull(),\n triggerPayload: jsonb('trigger_payload').notNull().$type<TriggerPayload>(),\n inputs: jsonb('inputs').$type<Record<string, unknown>>(),\n sourceSnapshot: jsonb('source_snapshot').$type<WorkflowSourceSnapshot>(),\n triggerIdempotencyKey: text('trigger_idempotency_key'),\n timeoutMs: bigint('timeout_ms', {mode: 'number'}).notNull().default(DEFAULT_RUN_TIMEOUT_MS),\n version: integer('version').notNull().default(1),\n createdAt: timestamp('created_at', {withTimezone: true}).notNull().defaultNow(),\n updatedAt: timestamp('updated_at', {withTimezone: true}).notNull().defaultNow(),\n startedAt: timestamp('started_at', {withTimezone: true}),\n finishedAt: timestamp('finished_at', {withTimezone: true}),\n },\n (table) => [\n uniqueIndex('workflows_wr_trigger_idempotency_key_unique').on(table.triggerIdempotencyKey),\n index('workflows_wr_project_created_id_idx').on(table.projectId, table.createdAt, table.id),\n index('workflows_wr_project_status_created_id_idx').on(\n table.projectId,\n table.status,\n table.createdAt,\n table.id,\n ),\n index('workflows_wr_project_definition_created_id_idx').on(\n table.projectId,\n table.definitionId,\n table.createdAt,\n table.id,\n ),\n index('workflows_wr_project_trigger_created_id_idx').on(\n table.projectId,\n table.triggerSource,\n table.createdAt,\n table.id,\n ),\n // Partial index backing the running-runs depth gauge, which counts on every\n // Prometheus scrape. Indexes only active rows so the count stays cheap as the\n // historical table grows.\n index('workflows_wr_running_idx').on(table.status).where(sql`${table.status} = 'running'`),\n check('workflows_wr_current_attempt_positive_ck', sql`${table.currentAttempt} > 0`),\n ],\n);\n\nexport type WorkflowRunDb = typeof workflowRuns.$inferSelect;\nexport type WorkflowRunCreateDb = typeof workflowRuns.$inferInsert;\n\nexport function toWorkflowRun(row: WorkflowRunDb): WorkflowRun {\n return {\n id: row.id,\n workspaceId: row.workspaceId,\n projectId: row.projectId,\n definitionId: row.definitionId,\n name: row.name,\n status: row.status,\n currentAttempt: row.currentAttempt,\n triggerProvider: row.triggerProvider,\n triggerSource: row.triggerSource,\n triggerEvent: row.triggerEvent,\n triggerPayload: row.triggerPayload as TriggerPayload,\n inputs: row.inputs ?? null,\n sourceSnapshot: row.sourceSnapshot ?? null,\n triggerIdempotencyKey: row.triggerIdempotencyKey,\n timeoutMs: row.timeoutMs,\n version: row.version,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n startedAt: row.startedAt,\n finishedAt: row.finishedAt,\n };\n}\n"],"names":["DEFAULT_RUN_TIMEOUT_MS","uuidv7PrimaryKey","sql","bigint","check","index","integer","jsonb","pgEnum","text","timestamp","uniqueIndex","uuid","pgTable","workflowRunStatusEnum","workflowRunRerunModeEnum","workflowRuns","id","workspaceId","notNull","projectId","definitionId","name","status","default","currentAttempt","triggerProvider","triggerSource","triggerEvent","triggerPayload","$type","inputs","sourceSnapshot","triggerIdempotencyKey","timeoutMs","mode","version","createdAt","withTimezone","defaultNow","updatedAt","startedAt","finishedAt","table","on","where","toWorkflowRun","row"],"mappings":"AAAA,SAAQA,sBAAsB,QAAO,+BAA+B;AACpE,SAAQC,gBAAgB,QAAO,wBAAwB;AACvD,SAAQC,GAAG,QAAO,cAAc;AAChC,SACEC,MAAM,EACNC,KAAK,EACLC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,MAAM,EACNC,IAAI,EACJC,SAAS,EACTC,WAAW,EACXC,IAAI,QACC,sBAAsB;AAM7B,SAAQC,OAAO,QAAO,cAAc;AAEpC,OAAO,MAAMC,wBAAwBN,OAAO,wBAAwB;IAClE;IACA;IACA;IACA;IACA;CACD,EAAE;AAEH,OAAO,MAAMO,2BAA2BP,OAAO,wBAAwB;IAAC;IAAO;CAAS,EAAE;AAE1F,OAAO,MAAMQ,eAAeH,QAC1B,iBACA;IACEI,IAAIh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E,CACxDD,MAAMvB,SAAS,EACfuB,MAAMtB,YAAY,EAClBsB,MAAMN,SAAS,EACfM,MAAM1B,EAAE;QAEVZ,MAAM,+CAA+CuC,EAAE,CACrDD,MAAMvB,SAAS,EACfuB,MAAMhB,aAAa,EACnBgB,MAAMN,SAAS,EACfM,MAAM1B,EAAE;QAEV,4EAA4E;QAC5E,8EAA8E;QAC9E,0BAA0B;QAC1BZ,MAAM,4BAA4BuC,EAAE,CAACD,MAAMpB,MAAM,EAAEsB,KAAK,CAAC3C,GAAG,CAAC,EAAEyC,MAAMpB,MAAM,CAAC,YAAY,CAAC;QACzFnB,MAAM,4CAA4CF,GAAG,CAAC,EAAEyC,MAAMlB,cAAc,CAAC,IAAI,CAAC;KACnF,EACD;AAKF,OAAO,SAASqB,cAAcC,GAAkB;IAC9C,OAAO;QACL9B,IAAI8B,IAAI9B,EAAE;QACVC,aAAa6B,IAAI7B,WAAW;QAC5BE,WAAW2B,IAAI3B,SAAS;QACxBC,cAAc0B,IAAI1B,YAAY;QAC9BC,MAAMyB,IAAIzB,IAAI;QACdC,QAAQwB,IAAIxB,MAAM;QAClBE,gBAAgBsB,IAAItB,cAAc;QAClCC,iBAAiBqB,IAAIrB,eAAe;QACpCC,eAAeoB,IAAIpB,aAAa;QAChCC,cAAcmB,IAAInB,YAAY;QAC9BC,gBAAgBkB,IAAIlB,cAAc;QAClCE,QAAQgB,IAAIhB,MAAM,IAAI;QACtBC,gBAAgBe,IAAIf,cAAc,IAAI;QACtCC,uBAAuBc,IAAId,qBAAqB;QAChDC,WAAWa,IAAIb,SAAS;QACxBE,SAASW,IAAIX,OAAO;QACpBC,WAAWU,IAAIV,SAAS;QACxBG,WAAWO,IAAIP,SAAS;QACxBC,WAAWM,IAAIN,SAAS;QACxBC,YAAYK,IAAIL,UAAU;IAC5B;AACF"}
@@ -1,3 +1,4 @@
1
+ import type { SecretsInterModuleClient } from '@shipfox/api-secrets-dto/inter-module';
1
2
  import type { JobStatusReason } from '#core/entities/job.js';
2
3
  import type { JobExecution, JobExecutionStatus } from '#core/entities/job-execution.js';
3
4
  import type { RuntimeCompletionStatus } from '#core/workflow-scheduling/runtime-dag.js';
@@ -18,12 +19,14 @@ export interface UpdateJobExecutionStatusAtVersionParams {
18
19
  expectedVersion: number;
19
20
  statusReason?: JobStatusReason | null | undefined;
20
21
  markTimedOut?: boolean;
22
+ secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;
21
23
  }
22
24
  export interface UpdateJobExecutionStatusParams {
23
25
  jobExecutionId: string;
24
26
  status: JobExecutionStatus;
25
27
  expectedVersion: number;
26
28
  statusReason?: JobStatusReason | null | undefined;
29
+ secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;
27
30
  }
28
31
  export declare function updateJobExecutionStatus(params: UpdateJobExecutionStatusParams): Promise<JobExecution>;
29
32
  export declare function recordJobExecutionQueuedAt(params: {
@@ -38,10 +41,12 @@ export declare function failJobExecutionAsTimedOut(params: {
38
41
  jobExecutionId: string;
39
42
  workflowRunAttemptId: string;
40
43
  expectedVersion: number;
44
+ secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;
41
45
  }): Promise<JobExecution>;
42
46
  export declare function resolveJobExecutionAfterLeaseExpiry(params: {
43
47
  jobExecutionId: string;
44
48
  expectedVersion: number;
49
+ secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;
45
50
  }): Promise<{
46
51
  status: RuntimeCompletionStatus;
47
52
  executionVersion: number;
@@ -1 +1 @@
1
- {"version":3,"file":"job-executions.d.ts","sourceRoot":"","sources":["../../../src/db/workflow-runs/job-executions.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAC,eAAe,EAAC,MAAM,uBAAuB,CAAC;AAC3D,OAAO,KAAK,EAAC,YAAY,EAAE,kBAAkB,EAAC,MAAM,iCAAiC,CAAC;AAItF,OAAO,KAAK,EAAC,uBAAuB,EAAC,MAAM,0CAA0C,CAAC;AA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ED,wBAAsB,wBAAwB,CAC5C,MAAM,EAAE,8BAA8B,GACrC,OAAO,CAAC,YAAY,CAAC,CAkCvB;AAED,wBAAsB,0BAA0B,CAAC,MAAM,EAAE;IACvD,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,EAAE,IAAI,CAAC;CAChB,GAAG,OAAO,CAAC,IAAI,CAAC,CAQhB;AAED,wBAAsB,2BAA2B,CAAC,MAAM,EAAE;IACxD,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,IAAI,CAAC;CACjB,GAAG,OAAO,CAAC,IAAI,CAAC,CAQhB;AAED,wBAAsB,0BAA0B,CAAC,MAAM,EAAE;IACvD,cAAc,EAAE,MAAM,CAAC;IACvB,oBAAoB,EAAE,MAAM,CAAC;IAC7B,eAAe,EAAE,MAAM,CAAC;IACxB,OAAO,CAAC,EAAE,IAAI,CAAC,wBAAwB,EAAE,yBAAyB,CAAC,GAAG,SAAS,CAAC;CACjF,GAAG,OAAO,CAAC,YAAY,CAAC,CA+CxB;AAED,wBAAsB,mCAAmC,CAAC,MAAM,EAAE;IAChE,cAAc,EAAE,MAAM,CAAC;IACvB,eAAe,EAAE,MAAM,CAAC;IACxB,OAAO,CAAC,EAAE,IAAI,CAAC,wBAAwB,EAAE,yBAAyB,CAAC,GAAG,SAAS,CAAC;CACjF,GAAG,OAAO,CAAC;IAAC,MAAM,EAAE,uBAAuB,CAAC;IAAC,gBAAgB,EAAE,MAAM,CAAA;CAAC,CAAC,CAyDvE"}
@@ -1,3 +1,4 @@
1
+ import { readPersistedWorkflowModel } from '@shipfox/api-definitions-dto';
1
2
  import { WORKFLOWS_JOB_EXECUTION_TIMED_OUT } from '@shipfox/api-workflows-dto';
2
3
  import { and, asc, desc, eq, isNull, notInArray, sql } from 'drizzle-orm';
3
4
  import { InterpolationUnresolvableError, JobNotFoundError } from '#core/errors.js';
@@ -56,7 +57,7 @@ async function resolveJobExecutionOutputs(tx, params) {
56
57
  run: workflowRuns
57
58
  }).from(jobExecutions).innerJoin(jobs, eq(jobExecutions.jobId, jobs.id)).innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id)).innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id)).where(eq(jobExecutions.id, params.jobExecutionId)).limit(1);
58
59
  if (!target) throw new JobNotFoundError(params.jobExecutionId);
59
- const model = target.attempt.model;
60
+ const model = target.attempt.model === null ? null : readPersistedWorkflowModel(target.attempt.model);
60
61
  if (!model) return null;
61
62
  const modelJob = model.jobs.find((job)=>job.key === target.job.key);
62
63
  if (!modelJob || modelJob.outputs === undefined) return null;
@@ -87,7 +88,8 @@ async function resolveJobExecutionOutputs(tx, params) {
87
88
  ],
88
89
  workspaceId: target.run.workspaceId,
89
90
  projectId: target.run.projectId,
90
- definitionId: target.run.definitionId
91
+ definitionId: target.run.definitionId,
92
+ secrets: params.secrets
91
93
  })
92
94
  });
93
95
  }
@@ -103,7 +105,8 @@ async function updateJobExecutionStatusAtVersion(tx, params) {
103
105
  outputs = await resolveJobExecutionOutputs(tx, {
104
106
  jobExecutionId: params.jobExecutionId,
105
107
  status,
106
- statusReason
108
+ statusReason,
109
+ secrets: params.secrets
107
110
  });
108
111
  } catch (error) {
109
112
  if (!(error instanceof InterpolationUnresolvableError)) throw error;
@@ -142,7 +145,8 @@ export async function updateJobExecutionStatus(params) {
142
145
  jobExecutionId: params.jobExecutionId,
143
146
  status: params.status,
144
147
  expectedVersion: params.expectedVersion,
145
- statusReason
148
+ statusReason,
149
+ secrets: params.secrets
146
150
  }),
147
151
  fetchFn: async ()=>{
148
152
  const row = (await tx.select().from(jobExecutions).where(eq(jobExecutions.id, params.jobExecutionId)).limit(1))[0];
@@ -182,7 +186,8 @@ export async function failJobExecutionAsTimedOut(params) {
182
186
  status: 'failed',
183
187
  expectedVersion: params.expectedVersion,
184
188
  statusReason: 'timed_out',
185
- markTimedOut: true
189
+ markTimedOut: true,
190
+ secrets: params.secrets
186
191
  }),
187
192
  fetchFn: async ()=>{
188
193
  const row = (await tx.select().from(jobExecutions).where(eq(jobExecutions.id, params.jobExecutionId)).limit(1))[0];
@@ -226,7 +231,8 @@ export async function resolveJobExecutionAfterLeaseExpiry(params) {
226
231
  jobExecutionId: params.jobExecutionId,
227
232
  status,
228
233
  expectedVersion: params.expectedVersion,
229
- statusReason: statusReasonForStepCompletion(status)
234
+ statusReason: statusReasonForStepCompletion(status),
235
+ secrets: params.secrets
230
236
  });
231
237
  changedJobExecution = updated?.changed ? updated.execution : null;
232
238
  } else {
@@ -234,7 +240,8 @@ export async function resolveJobExecutionAfterLeaseExpiry(params) {
234
240
  jobExecutionId: params.jobExecutionId,
235
241
  status: 'failed',
236
242
  expectedVersion: params.expectedVersion,
237
- statusReason: 'runner_lost'
243
+ statusReason: 'runner_lost',
244
+ secrets: params.secrets
238
245
  });
239
246
  if (updated?.changed) {
240
247
  changedJobExecution = updated.execution;