@shipfox/api-workflows 13.1.0 → 15.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 (94) hide show
  1. package/.turbo/turbo-build.log +4 -4
  2. package/CHANGELOG.md +61 -0
  3. package/README.md +12 -5
  4. package/dist/core/checkout.d.ts +4 -2
  5. package/dist/core/checkout.d.ts.map +1 -1
  6. package/dist/core/checkout.js +7 -2
  7. package/dist/core/checkout.js.map +1 -1
  8. package/dist/core/entities/job.d.ts +1 -1
  9. package/dist/core/entities/job.d.ts.map +1 -1
  10. package/dist/core/entities/job.js.map +1 -1
  11. package/dist/core/entities/workflow-run.d.ts +25 -6
  12. package/dist/core/entities/workflow-run.d.ts.map +1 -1
  13. package/dist/core/entities/workflow-run.js.map +1 -1
  14. package/dist/core/index.d.ts +2 -2
  15. package/dist/core/index.d.ts.map +1 -1
  16. package/dist/core/index.js +1 -1
  17. package/dist/core/index.js.map +1 -1
  18. package/dist/core/run-workflow.d.ts +26 -1
  19. package/dist/core/run-workflow.d.ts.map +1 -1
  20. package/dist/core/run-workflow.js +27 -1
  21. package/dist/core/run-workflow.js.map +1 -1
  22. package/dist/db/db.d.ts +72 -0
  23. package/dist/db/db.d.ts.map +1 -1
  24. package/dist/db/schema/workflow-runs.d.ts +45 -1
  25. package/dist/db/schema/workflow-runs.d.ts.map +1 -1
  26. package/dist/db/schema/workflow-runs.js +42 -1
  27. package/dist/db/schema/workflow-runs.js.map +1 -1
  28. package/dist/db/workflow-runs/jobs.d.ts +3 -1
  29. package/dist/db/workflow-runs/jobs.d.ts.map +1 -1
  30. package/dist/db/workflow-runs/jobs.js +12 -3
  31. package/dist/db/workflow-runs/jobs.js.map +1 -1
  32. package/dist/db/workflow-runs/queries.d.ts +3 -2
  33. package/dist/db/workflow-runs/queries.d.ts.map +1 -1
  34. package/dist/db/workflow-runs/queries.js +3 -0
  35. package/dist/db/workflow-runs/queries.js.map +1 -1
  36. package/dist/db/workflow-runs/run-create.d.ts +4 -1
  37. package/dist/db/workflow-runs/run-create.d.ts.map +1 -1
  38. package/dist/db/workflow-runs/run-create.js +14 -1
  39. package/dist/db/workflow-runs/run-create.js.map +1 -1
  40. package/dist/presentation/dto/workflow-run.d.ts.map +1 -1
  41. package/dist/presentation/dto/workflow-run.js +14 -0
  42. package/dist/presentation/dto/workflow-run.js.map +1 -1
  43. package/dist/presentation/inter-module.d.ts +1 -0
  44. package/dist/presentation/inter-module.d.ts.map +1 -1
  45. package/dist/presentation/inter-module.js +41 -4
  46. package/dist/presentation/inter-module.js.map +1 -1
  47. package/dist/presentation/routes/checkout-token.d.ts.map +1 -1
  48. package/dist/presentation/routes/checkout-token.js +2 -1
  49. package/dist/presentation/routes/checkout-token.js.map +1 -1
  50. package/dist/presentation/routes/get-run-aggregates.d.ts.map +1 -1
  51. package/dist/presentation/routes/get-run-aggregates.js +2 -1
  52. package/dist/presentation/routes/get-run-aggregates.js.map +1 -1
  53. package/dist/presentation/routes/leased-step.d.ts +3 -1
  54. package/dist/presentation/routes/leased-step.d.ts.map +1 -1
  55. package/dist/presentation/routes/leased-step.js +2 -1
  56. package/dist/presentation/routes/leased-step.js.map +1 -1
  57. package/dist/presentation/routes/list-runs.d.ts.map +1 -1
  58. package/dist/presentation/routes/list-runs.js +2 -1
  59. package/dist/presentation/routes/list-runs.js.map +1 -1
  60. package/dist/presentation/routes/project-access.d.ts +1 -0
  61. package/dist/presentation/routes/project-access.d.ts.map +1 -1
  62. package/dist/tsconfig.test.tsbuildinfo +1 -1
  63. package/drizzle/0004_dev_run_origin.sql +12 -0
  64. package/drizzle/meta/0004_snapshot.json +1773 -0
  65. package/drizzle/meta/_journal.json +7 -0
  66. package/package.json +16 -16
  67. package/src/core/checkout.test.ts +198 -1
  68. package/src/core/checkout.ts +18 -5
  69. package/src/core/entities/job.ts +1 -1
  70. package/src/core/entities/workflow-run.ts +26 -6
  71. package/src/core/index.ts +2 -2
  72. package/src/core/job-transition/decide-job-activation.test.ts +2 -0
  73. package/src/core/run-workflow.test.ts +151 -3
  74. package/src/core/run-workflow.ts +59 -3
  75. package/src/core/workflow-run-creation.test.ts +2 -0
  76. package/src/db/job-listeners.test.ts +17 -0
  77. package/src/db/schema/workflow-runs.ts +58 -0
  78. package/src/db/workflow-runs/jobs.ts +17 -3
  79. package/src/db/workflow-runs/queries.ts +6 -1
  80. package/src/db/workflow-runs/run-create.test.ts +87 -0
  81. package/src/db/workflow-runs/run-create.ts +23 -1
  82. package/src/presentation/dto/workflow-run.ts +23 -1
  83. package/src/presentation/inter-module.test.ts +131 -1
  84. package/src/presentation/inter-module.ts +48 -3
  85. package/src/presentation/routes/checkout-token.test.ts +45 -0
  86. package/src/presentation/routes/checkout-token.ts +2 -1
  87. package/src/presentation/routes/get-run-aggregates.test.ts +56 -0
  88. package/src/presentation/routes/get-run-aggregates.ts +2 -0
  89. package/src/presentation/routes/get-step-secrets.test.ts +1 -0
  90. package/src/presentation/routes/leased-step.ts +7 -1
  91. package/src/presentation/routes/list-runs.test.ts +152 -0
  92. package/src/presentation/routes/list-runs.ts +2 -0
  93. package/test/factories/workflow-run.ts +2 -0
  94. package/tsconfig.build.tsbuildinfo +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/db/workflow-runs/queries.ts"],"sourcesContent":["import {WORKFLOW_RUN_JOB_PREVIEW_LIMIT} from '@shipfox/api-workflows-dto';\nimport {\n paginateTimestampIdRows,\n type TimestampIdCursor,\n timestampIdCursorWhere,\n} from '@shipfox/node-drizzle';\nimport {and, asc, count, desc, eq, gte, lte, type SQL, sql} from 'drizzle-orm';\nimport type {JobMode, JobStatus, ListenerStatus} from '#core/entities/job.js';\nimport type {JobExecutionStatus} from '#core/entities/job-execution.js';\nimport type {\n JobExecutionDetail,\n StepDetail,\n WorkflowJobDetail,\n WorkflowRun,\n WorkflowRunDetail,\n WorkflowRunStatus,\n} from '#core/entities/workflow-run.js';\nimport {db} from '../db.js';\nimport {jobExecutions, toJobExecution} from '../schema/job-executions.js';\nimport {jobs, toJob} from '../schema/jobs.js';\nimport {stepAttempts, toStepAttempt} from '../schema/step-attempts.js';\nimport {steps, toStep} from '../schema/steps.js';\nimport {toWorkflowRunAttempt, workflowRunAttempts} from '../schema/workflow-run-attempts.js';\nimport {toWorkflowRun, workflowRuns} from '../schema/workflow-runs.js';\n\nexport type WorkflowRunCursor = TimestampIdCursor;\n\nexport interface WorkflowRunFilters {\n status?: WorkflowRunStatus | undefined;\n definitionId?: string | undefined;\n triggerSource?: string | undefined;\n createdFrom?: Date | undefined;\n createdTo?: Date | undefined;\n}\n\nexport interface ListWorkflowRunsParams {\n projectId: string;\n limit: number;\n cursor?: WorkflowRunCursor | undefined;\n filters?: WorkflowRunFilters | undefined;\n includeTotal?: boolean | undefined;\n}\n\nexport interface ListWorkflowRunsResult {\n runs: WorkflowRun[];\n nextCursor: WorkflowRunCursor | null;\n filteredTotalCount: number | null;\n}\n\n/** A run-list job glyph: enough to draw and label it, none of its steps. */\nexport interface WorkflowRunJobSummary {\n id: string;\n key: string;\n name: string | null;\n status: JobStatus;\n mode: JobMode;\n listenerStatus: ListenerStatus;\n executionStatus: JobExecutionStatus | null;\n position: number;\n}\n\nexport interface WorkflowRunAggregates {\n status: Array<{value: WorkflowRunStatus; count: number}>;\n triggerSource: Array<{value: string; count: number}>;\n workflow: Array<{value: string; count: number}>;\n}\n\nexport interface WorkflowJobExecutionDepth {\n runningRuns: number;\n runningJobExecutions: number;\n}\n\nexport interface WorkflowJobExecutionDepthParams {\n workspaceId?: string;\n}\n\nexport async function getWorkflowRunById(id: string): Promise<WorkflowRun | undefined> {\n const rows = await db().select().from(workflowRuns).where(eq(workflowRuns.id, id)).limit(1);\n const row = rows[0];\n if (!row) return undefined;\n return toWorkflowRun(row);\n}\n\nexport async function getWorkflowRunByAttemptId(\n workflowRunAttemptId: string,\n): Promise<WorkflowRun | undefined> {\n const rows = await db()\n .select({run: workflowRuns})\n .from(workflowRunAttempts)\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(eq(workflowRunAttempts.id, workflowRunAttemptId))\n .limit(1);\n const row = rows[0];\n return row ? toWorkflowRun(row.run) : undefined;\n}\n\nexport async function getWorkflowRunAttemptById(workflowRunAttemptId: string) {\n const rows = await db()\n .select()\n .from(workflowRunAttempts)\n .where(eq(workflowRunAttempts.id, workflowRunAttemptId))\n .limit(1);\n const row = rows[0];\n return row ? toWorkflowRunAttempt(row) : undefined;\n}\n\nexport async function listRunAttempts(params: {workflowRunId: string; projectId: string}) {\n return (\n await db()\n .select({\n attempt: workflowRunAttempts,\n })\n .from(workflowRunAttempts)\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(\n and(\n eq(workflowRunAttempts.workflowRunId, params.workflowRunId),\n eq(workflowRuns.projectId, params.projectId),\n ),\n )\n .orderBy(asc(workflowRunAttempts.attempt))\n ).map((row) => toWorkflowRunAttempt(row.attempt));\n}\n\nexport async function getLatestAttempt(params: {\n workflowRunId: string;\n projectId: string;\n}): Promise<number> {\n const [row] = await db()\n .select({value: sql<number>`coalesce(max(${workflowRunAttempts.attempt}), 1)`})\n .from(workflowRunAttempts)\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(\n and(\n eq(workflowRunAttempts.workflowRunId, params.workflowRunId),\n eq(workflowRuns.projectId, params.projectId),\n ),\n )\n .limit(1);\n\n return Number(row?.value ?? 1);\n}\n\nexport function buildWorkflowRunListConditions(params: {\n projectId: string;\n filters?: WorkflowRunFilters | undefined;\n cursor?: WorkflowRunCursor | undefined;\n omit?: 'status' | 'definitionId' | 'triggerSource' | undefined;\n}): SQL[] {\n const filters = params.filters;\n const conditions: SQL[] = [eq(workflowRuns.projectId, params.projectId)];\n const cursorCondition = timestampIdCursorWhere({\n timestampColumn: workflowRuns.createdAt,\n idColumn: workflowRuns.id,\n cursor: params.cursor,\n });\n if (cursorCondition) conditions.push(cursorCondition);\n if (filters?.status && params.omit !== 'status') {\n conditions.push(eq(workflowRuns.status, filters.status));\n }\n if (filters?.definitionId && params.omit !== 'definitionId') {\n conditions.push(eq(workflowRuns.definitionId, filters.definitionId));\n }\n if (filters?.triggerSource && params.omit !== 'triggerSource') {\n conditions.push(eq(workflowRuns.triggerSource, filters.triggerSource));\n }\n if (filters?.createdFrom) {\n conditions.push(gte(workflowRuns.createdAt, filters.createdFrom));\n }\n if (filters?.createdTo) {\n conditions.push(lte(workflowRuns.createdAt, filters.createdTo));\n }\n return conditions;\n}\n\nexport async function listWorkflowRuns(\n params: ListWorkflowRunsParams,\n): Promise<ListWorkflowRunsResult> {\n const conditions = buildWorkflowRunListConditions(params);\n const rows = await db()\n .select()\n .from(workflowRuns)\n .where(and(...conditions))\n .orderBy(desc(workflowRuns.createdAt), desc(workflowRuns.id))\n .limit(params.limit + 1);\n\n let totalCount: number | null = null;\n if (params.includeTotal) {\n const [{value} = {value: 0}] = await db()\n .select({value: count()})\n .from(workflowRuns)\n .where(\n and(\n ...buildWorkflowRunListConditions({projectId: params.projectId, filters: params.filters}),\n ),\n );\n totalCount = value;\n }\n\n const page = paginateTimestampIdRows({rows, limit: params.limit, timestampKey: 'createdAt'});\n\n return {\n runs: page.pageRows.map(toWorkflowRun),\n nextCursor: page.nextCursor,\n filteredTotalCount: totalCount,\n };\n}\n\n/** The run whose jobs to fetch, pinned to the attempt the caller already read. */\nexport interface WorkflowRunJobSummaryTarget {\n id: string;\n currentAttempt: number;\n}\n\n/**\n * A page row's jobs: a bounded slice to draw, totals describing all of them, and whether any\n * execution has reached a runner.\n *\n * The preview is what a row can show; `statusCounts` is what it can say. Keeping the counts\n * server-side is what lets a row report a failure that sits past the preview. Counts use the\n * display status derived from the job verdict, listener state, and selected execution state;\n * the row keeps the verdict and evidence separate so the client can apply the same display\n * rule as run detail.\n */\nexport interface WorkflowRunJobsSummary {\n preview: WorkflowRunJobSummary[];\n statusCounts: WorkflowRunJobStatusCount[];\n rawStatusCounts: WorkflowRunJobRawStatusCount[];\n hasStartedJobExecution: boolean;\n}\n\nexport interface WorkflowRunJobStatusCount {\n status: JobStatus | 'listening';\n count: number;\n}\n\nexport interface WorkflowRunJobRawStatusCount {\n status: JobStatus;\n count: number;\n}\n\n/**\n * Jobs for a page of runs, keyed by run id.\n *\n * Issued once per page rather than once per run: the run list is the one surface that needs\n * every run's jobs at once, and a per-row query would put 50 round trips behind it.\n *\n * Both reads are bounded by the page, not by workflow size. A workflow has no job limit and\n * this list polls while runs are active, so returning every job of every row would let one\n * large workflow decide how much the endpoint moves every four seconds. The preview is cut\n * per run in the database, and everything past it is described by a grouped count instead.\n *\n * The attempt comes from the caller's own read rather than from a second look at\n * `current_attempt`. Re-reading it here would let a re-run landing between the queries pair\n * attempt 1's run metadata with attempt 2's jobs, and the row would report a status its strip\n * contradicts.\n *\n * The reads share one repeatable-read snapshot. They describe the same jobs and executions at\n * the same instant, and the strip combines them into a single glyph row, so under the default\n * read-committed isolation a job settling between the statements would draw a pending glyph\n * beside a summary counting it as failed. Sequential inside one transaction is the cost of\n * that; at a four-second poll the extra round trip does not register.\n */\nexport async function listWorkflowRunJobSummaries(\n runs: readonly WorkflowRunJobSummaryTarget[],\n): Promise<Map<string, WorkflowRunJobsSummary>> {\n const summaries = new Map<string, WorkflowRunJobsSummary>();\n if (runs.length === 0) return summaries;\n\n // A row-constructor IN over (run, attempt) so each pair is one lookup on the unique index\n // that already covers those two columns.\n const attemptPairs = sql.join(\n runs.map((run) => sql`(${run.id}::uuid, ${run.currentAttempt})`),\n sql`, `,\n );\n const attemptFilter = sql`(${workflowRunAttempts.workflowRunId}, ${workflowRunAttempts.attempt}) in (${attemptPairs})`;\n\n const {previewRows, countRows} = await db().transaction(\n async (tx) => {\n // Pick the execution the detail view would display once per job before either list\n // statement touches it. The existing (job_id, sequence) index supports the latest\n // execution ordering, while the status-first expression preserves the rule that an\n // active execution wins over a newer completed retry.\n const selectedExecution = tx.$with('selected_execution').as(\n tx\n .selectDistinctOn([jobExecutions.jobId], {\n jobId: jobExecutions.jobId,\n executionStatus: sql<JobExecutionStatus>`${jobExecutions.status}`.as(\n 'execution_status',\n ),\n })\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .where(attemptFilter)\n .orderBy(\n asc(jobExecutions.jobId),\n sql`case when ${jobExecutions.status} = 'running' then 0 else 1 end`,\n desc(jobExecutions.sequence),\n desc(jobExecutions.id),\n ),\n );\n\n const ranked = tx\n .with(selectedExecution)\n .select({\n workflowRunId: workflowRunAttempts.workflowRunId,\n id: jobs.id,\n key: jobs.key,\n name: jobs.name,\n status: jobs.status,\n mode: jobs.mode,\n listenerStatus: jobs.listenerStatus,\n executionStatus: selectedExecution.executionStatus,\n position: jobs.position,\n jobRank:\n sql<number>`row_number() over (partition by ${workflowRunAttempts.workflowRunId} order by ${jobs.position} asc, ${jobs.id} asc)`.as(\n 'job_rank',\n ),\n })\n .from(jobs)\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .leftJoin(selectedExecution, eq(selectedExecution.jobId, jobs.id))\n .where(attemptFilter)\n .as('ranked');\n // Correlated per job rather than a grouped scan of `job_executions`: an aggregate over the\n // whole table cannot have the page's filter pushed into it, so it would read every execution\n // ever recorded on each poll and grow with history rather than with the page.\n const hasStartedJobExecution = sql<boolean>`bool_or(exists (\n select 1\n from ${jobExecutions}\n where ${jobExecutions.jobId} = ${jobs.id} and ${jobExecutions.startedAt} is not null\n ))`;\n\n const executionDisplayStatus = sql<JobExecutionStatus | null>`\n ${selectedExecution.executionStatus}\n `;\n const displayStatus = sql<WorkflowRunJobStatusCount['status']>`\n case\n when ${jobs.status} in ('succeeded', 'failed', 'cancelled', 'skipped') then ${jobs.status}::text\n when ${jobs.mode} = 'listening' and ${jobs.listenerStatus} = 'listening' then 'listening'\n when ${executionDisplayStatus} is not null then ${executionDisplayStatus}::text\n else 'pending'\n end\n `;\n return {\n previewRows: await tx\n .select({\n workflowRunId: ranked.workflowRunId,\n id: ranked.id,\n key: ranked.key,\n name: ranked.name,\n status: ranked.status,\n mode: ranked.mode,\n listenerStatus: ranked.listenerStatus,\n executionStatus: ranked.executionStatus,\n position: ranked.position,\n })\n .from(ranked)\n .where(lte(ranked.jobRank, WORKFLOW_RUN_JOB_PREVIEW_LIMIT))\n .orderBy(asc(ranked.workflowRunId), asc(ranked.position), asc(ranked.id)),\n countRows: await tx\n .with(selectedExecution)\n .select({\n workflowRunId: workflowRunAttempts.workflowRunId,\n rawStatus: jobs.status,\n status: displayStatus,\n count: count(),\n hasStartedJobExecution,\n })\n .from(jobs)\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .leftJoin(selectedExecution, eq(selectedExecution.jobId, jobs.id))\n .where(attemptFilter)\n .groupBy(workflowRunAttempts.workflowRunId, jobs.status, displayStatus),\n };\n },\n {isolationLevel: 'repeatable read', accessMode: 'read only'},\n );\n\n for (const {workflowRunId, ...summary} of previewRows) {\n summaryFor(summaries, workflowRunId).preview.push(summary);\n }\n for (const {\n workflowRunId,\n rawStatus,\n status,\n count: statusCount,\n hasStartedJobExecution,\n } of countRows) {\n const summary = summaryFor(summaries, workflowRunId);\n appendStatusCount(summary.rawStatusCounts, rawStatus, statusCount);\n appendStatusCount(summary.statusCounts, status, statusCount);\n // One row per (run, verdict, display status), so the run's answer is the OR of its groups.\n summary.hasStartedJobExecution ||= hasStartedJobExecution;\n }\n\n return summaries;\n}\n\nfunction summaryFor(\n summaries: Map<string, WorkflowRunJobsSummary>,\n workflowRunId: string,\n): WorkflowRunJobsSummary {\n const existing = summaries.get(workflowRunId);\n if (existing) return existing;\n const created: WorkflowRunJobsSummary = {\n preview: [],\n statusCounts: [],\n rawStatusCounts: [],\n hasStartedJobExecution: false,\n };\n summaries.set(workflowRunId, created);\n return created;\n}\n\nfunction appendStatusCount<T extends string>(\n counts: Array<{status: T; count: number}>,\n status: T,\n count: number,\n): void {\n const existing = counts.find((entry) => entry.status === status);\n if (existing) {\n existing.count += count;\n } else {\n counts.push({status, count});\n }\n}\n\nexport async function listWorkflowRunsByProject(projectId: string): Promise<WorkflowRun[]> {\n const result = await listWorkflowRuns({projectId, limit: 100});\n return result.runs;\n}\n\nexport async function getWorkflowRunAggregates(params: {\n projectId: string;\n filters?: WorkflowRunFilters | undefined;\n}): Promise<WorkflowRunAggregates> {\n const [statusRows, triggerRows, workflowRows] = await Promise.all([\n db()\n .select({value: workflowRuns.status, count: count()})\n .from(workflowRuns)\n .where(\n and(\n ...buildWorkflowRunListConditions({\n projectId: params.projectId,\n filters: params.filters,\n omit: 'status',\n }),\n ),\n )\n .groupBy(workflowRuns.status),\n db()\n .select({value: workflowRuns.triggerSource, count: count()})\n .from(workflowRuns)\n .where(\n and(\n ...buildWorkflowRunListConditions({\n projectId: params.projectId,\n filters: params.filters,\n omit: 'triggerSource',\n }),\n ),\n )\n .groupBy(workflowRuns.triggerSource),\n db()\n .select({value: workflowRuns.definitionId, count: count()})\n .from(workflowRuns)\n .where(\n and(\n ...buildWorkflowRunListConditions({\n projectId: params.projectId,\n filters: params.filters,\n omit: 'definitionId',\n }),\n ),\n )\n .groupBy(workflowRuns.definitionId),\n ]);\n\n return {\n status: statusRows,\n triggerSource: triggerRows,\n workflow: workflowRows,\n };\n}\n\nexport async function getWorkflowJobExecutionDepth(\n params: WorkflowJobExecutionDepthParams = {},\n): Promise<WorkflowJobExecutionDepth> {\n const runConditions = [eq(workflowRuns.status, 'running')];\n const jobConditions = [eq(jobExecutions.status, 'running')];\n if (params.workspaceId) {\n runConditions.push(eq(workflowRuns.workspaceId, params.workspaceId));\n jobConditions.push(eq(workflowRuns.workspaceId, params.workspaceId));\n }\n\n const [runRows, jobRows] = await Promise.all([\n db()\n .select({value: count()})\n .from(workflowRuns)\n .where(and(...runConditions)),\n db()\n .select({value: count()})\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(and(...jobConditions)),\n ]);\n\n return {\n runningRuns: runRows[0]?.value ?? 0,\n runningJobExecutions: jobRows[0]?.value ?? 0,\n };\n}\n\nexport async function getWorkflowRunDetail(\n workflowRunId: string,\n attempt?: number | undefined,\n): Promise<WorkflowRunDetail | undefined> {\n const [target] = await db()\n .select({run: workflowRuns, attempt: workflowRunAttempts})\n .from(workflowRuns)\n .innerJoin(\n workflowRunAttempts,\n and(\n eq(workflowRunAttempts.workflowRunId, workflowRuns.id),\n eq(workflowRunAttempts.attempt, attempt ?? workflowRuns.currentAttempt),\n ),\n )\n .where(eq(workflowRuns.id, workflowRunId))\n .limit(1);\n if (!target) return undefined;\n\n const latestAttempt = await getLatestAttempt({\n workflowRunId: target.run.id,\n projectId: target.run.projectId,\n });\n\n const rows = await db()\n .select({\n run: workflowRuns,\n job: jobs,\n jobExecution: jobExecutions,\n step: steps,\n stepAttempt: stepAttempts,\n })\n .from(workflowRuns)\n .innerJoin(workflowRunAttempts, eq(workflowRunAttempts.id, target.attempt.id))\n .leftJoin(jobs, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .leftJoin(jobExecutions, eq(jobExecutions.jobId, jobs.id))\n .leftJoin(steps, eq(steps.jobExecutionId, jobExecutions.id))\n .leftJoin(stepAttempts, eq(stepAttempts.stepId, steps.id))\n .where(eq(workflowRuns.id, workflowRunId))\n .orderBy(\n asc(jobs.position),\n asc(jobs.id),\n asc(jobExecutions.sequence),\n asc(jobExecutions.id),\n asc(steps.position),\n asc(steps.id),\n asc(stepAttempts.executionOrder),\n asc(stepAttempts.id),\n );\n\n return hydrateWorkflowRunDetail(rows, target.attempt, latestAttempt);\n}\n\nexport async function getJobExecutionDetail(\n jobExecutionId: string,\n): Promise<JobExecutionDetail | undefined> {\n const rows = await db()\n .select({\n job: jobs,\n jobExecution: jobExecutions,\n step: steps,\n stepAttempt: stepAttempts,\n })\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .leftJoin(steps, eq(steps.jobExecutionId, jobExecutions.id))\n .leftJoin(stepAttempts, eq(stepAttempts.stepId, steps.id))\n .where(eq(jobExecutions.id, jobExecutionId))\n .orderBy(\n asc(steps.position),\n asc(steps.id),\n asc(stepAttempts.executionOrder),\n asc(stepAttempts.id),\n );\n\n const first = rows[0];\n if (!first) return undefined;\n\n const detail: JobExecutionDetail = {\n ...toJobExecution(first.jobExecution, first.job.name ?? first.job.key),\n steps: [],\n };\n const stepById = new Map<string, StepDetail>();\n for (const row of rows) {\n if (row.step) {\n const step = getOrCreateStepDetail(stepById, detail.steps, row.step);\n if (row.stepAttempt) {\n step.attempts.push(toStepAttempt(row.stepAttempt));\n }\n }\n }\n\n return detail;\n}\n\nfunction hydrateWorkflowRunDetail(\n rows: {\n run: typeof workflowRuns.$inferSelect;\n job: typeof jobs.$inferSelect | null;\n jobExecution: typeof jobExecutions.$inferSelect | null;\n step: typeof steps.$inferSelect | null;\n stepAttempt: typeof stepAttempts.$inferSelect | null;\n }[],\n attempt: typeof workflowRunAttempts.$inferSelect,\n latestAttempt: number,\n): WorkflowRunDetail | undefined {\n const first = rows[0];\n if (!first) return undefined;\n\n const detail: WorkflowRunDetail = {\n ...toWorkflowRun(first.run),\n runAttempt: toWorkflowRunAttempt(attempt),\n latestAttempt,\n jobs: [],\n // Read off the same rows the executions come from, so the flag cannot contradict them.\n hasStartedJobExecution: rows.some((row) => row.jobExecution?.startedAt != null),\n };\n const jobById = new Map<string, WorkflowJobDetail>();\n const jobExecutionById = new Map<string, JobExecutionDetail>();\n const stepById = new Map<string, StepDetail>();\n\n for (const row of rows) {\n if (!row.job) continue;\n let job = jobById.get(row.job.id);\n if (!job) {\n job = {...toJob(row.job), jobExecutions: []};\n jobById.set(row.job.id, job);\n detail.jobs.push(job);\n }\n\n if (!row.jobExecution) continue;\n let jobExecution = jobExecutionById.get(row.jobExecution.id);\n if (!jobExecution) {\n jobExecution = {\n ...toJobExecution(row.jobExecution, row.job.name ?? row.job.key),\n steps: [],\n };\n jobExecutionById.set(row.jobExecution.id, jobExecution);\n job.jobExecutions.push(jobExecution);\n }\n\n if (!row.step) continue;\n const step = getOrCreateStepDetail(stepById, jobExecution.steps, row.step);\n if (row.stepAttempt) {\n step.attempts.push(toStepAttempt(row.stepAttempt));\n }\n }\n\n return detail;\n}\n\nfunction getOrCreateStepDetail(\n stepById: Map<string, StepDetail>,\n target: StepDetail[],\n row: typeof steps.$inferSelect,\n): StepDetail {\n let step = stepById.get(row.id);\n if (!step) {\n step = {...toStep(row), attempts: []};\n stepById.set(row.id, step);\n target.push(step);\n }\n return step;\n}\n"],"names":["WORKFLOW_RUN_JOB_PREVIEW_LIMIT","paginateTimestampIdRows","timestampIdCursorWhere","and","asc","count","desc","eq","gte","lte","sql","db","jobExecutions","toJobExecution","jobs","toJob","stepAttempts","toStepAttempt","steps","toStep","toWorkflowRunAttempt","workflowRunAttempts","toWorkflowRun","workflowRuns","getWorkflowRunById","id","rows","select","from","where","limit","row","undefined","getWorkflowRunByAttemptId","workflowRunAttemptId","run","innerJoin","workflowRunId","getWorkflowRunAttemptById","listRunAttempts","params","attempt","projectId","orderBy","map","getLatestAttempt","value","Number","buildWorkflowRunListConditions","filters","conditions","cursorCondition","timestampColumn","createdAt","idColumn","cursor","push","status","omit","definitionId","triggerSource","createdFrom","createdTo","listWorkflowRuns","totalCount","includeTotal","page","timestampKey","runs","pageRows","nextCursor","filteredTotalCount","listWorkflowRunJobSummaries","summaries","Map","length","attemptPairs","join","currentAttempt","attemptFilter","previewRows","countRows","transaction","tx","selectedExecution","$with","as","selectDistinctOn","jobId","executionStatus","sequence","ranked","with","key","name","mode","listenerStatus","position","jobRank","leftJoin","hasStartedJobExecution","startedAt","executionDisplayStatus","displayStatus","rawStatus","groupBy","isolationLevel","accessMode","summary","summaryFor","preview","statusCount","appendStatusCount","rawStatusCounts","statusCounts","existing","get","created","set","counts","find","entry","listWorkflowRunsByProject","result","getWorkflowRunAggregates","statusRows","triggerRows","workflowRows","Promise","all","workflow","getWorkflowJobExecutionDepth","runConditions","jobConditions","workspaceId","runRows","jobRows","runningRuns","runningJobExecutions","getWorkflowRunDetail","target","latestAttempt","job","jobExecution","step","stepAttempt","jobExecutionId","stepId","executionOrder","hydrateWorkflowRunDetail","getJobExecutionDetail","first","detail","stepById","getOrCreateStepDetail","attempts","runAttempt","some","jobById","jobExecutionById"],"mappings":"AAAA,SAAQA,8BAA8B,QAAO,6BAA6B;AAC1E,SACEC,uBAAuB,EAEvBC,sBAAsB,QACjB,wBAAwB;AAC/B,SAAQC,GAAG,EAAEC,GAAG,EAAEC,KAAK,EAAEC,IAAI,EAAEC,EAAE,EAAEC,GAAG,EAAEC,GAAG,EAAYC,GAAG,QAAO,cAAc;AAW/E,SAAQC,EAAE,QAAO,WAAW;AAC5B,SAAQC,aAAa,EAAEC,cAAc,QAAO,8BAA8B;AAC1E,SAAQC,IAAI,EAAEC,KAAK,QAAO,oBAAoB;AAC9C,SAAQC,YAAY,EAAEC,aAAa,QAAO,6BAA6B;AACvE,SAAQC,KAAK,EAAEC,MAAM,QAAO,qBAAqB;AACjD,SAAQC,oBAAoB,EAAEC,mBAAmB,QAAO,qCAAqC;AAC7F,SAAQC,aAAa,EAAEC,YAAY,QAAO,6BAA6B;AAqDvE,OAAO,eAAeC,mBAAmBC,EAAU;IACjD,MAAMC,OAAO,MAAMf,KAAKgB,MAAM,GAAGC,IAAI,CAACL,cAAcM,KAAK,CAACtB,GAAGgB,aAAaE,EAAE,EAAEA,KAAKK,KAAK,CAAC;IACzF,MAAMC,MAAML,IAAI,C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I,eAAekB,IAAIgH,YAAY,EAAEhH,IAAI+G,GAAG,CAAChD,IAAI,IAAI/D,IAAI+G,GAAG,CAACjD,GAAG,CAAC;gBAChE3E,OAAO,EAAE;YACX;YACA6I,iBAAiBzC,GAAG,CAACvF,IAAIgH,YAAY,CAACtH,EAAE,EAAEsH;YAC1CD,IAAIlI,aAAa,CAAC4C,IAAI,CAACuF;QACzB;QAEA,IAAI,CAAChH,IAAIiH,IAAI,EAAE;QACf,MAAMA,OAAOU,sBAAsBD,UAAUV,aAAa7H,KAAK,EAAEa,IAAIiH,IAAI;QACzE,IAAIjH,IAAIkH,WAAW,EAAE;YACnBD,KAAKW,QAAQ,CAACnG,IAAI,CAACvC,cAAcc,IAAIkH,WAAW;QAClD;IACF;IAEA,OAAOO;AACT;AAEA,SAASE,sBACPD,QAAiC,EACjCb,MAAoB,EACpB7G,GAA8B;IAE9B,IAAIiH,OAAOS,SAASrC,GAAG,CAACrF,IAAIN,EAAE;IAC9B,IAAI,CAACuH,MAAM;QACTA,OAAO;YAAC,GAAG7H,OAAOY,IAAI;YAAE4H,UAAU,EAAE;QAAA;QACpCF,SAASnC,GAAG,CAACvF,IAAIN,EAAE,EAAEuH;QACrBJ,OAAOpF,IAAI,CAACwF;IACd;IACA,OAAOA;AACT"}
1
+ {"version":3,"sources":["../../../src/db/workflow-runs/queries.ts"],"sourcesContent":["import {WORKFLOW_RUN_JOB_PREVIEW_LIMIT} from '@shipfox/api-workflows-dto';\nimport {\n paginateTimestampIdRows,\n type TimestampIdCursor,\n timestampIdCursorWhere,\n} from '@shipfox/node-drizzle';\nimport {and, asc, count, desc, eq, gte, lte, type SQL, sql} from 'drizzle-orm';\nimport type {JobMode, JobStatus, ListenerStatus} from '#core/entities/job.js';\nimport type {JobExecutionStatus} from '#core/entities/job-execution.js';\nimport type {\n JobExecutionDetail,\n StepDetail,\n WorkflowJobDetail,\n WorkflowRun,\n WorkflowRunDetail,\n WorkflowRunOrigin,\n WorkflowRunStatus,\n} from '#core/entities/workflow-run.js';\nimport {db} from '../db.js';\nimport {jobExecutions, toJobExecution} from '../schema/job-executions.js';\nimport {jobs, toJob} from '../schema/jobs.js';\nimport {stepAttempts, toStepAttempt} from '../schema/step-attempts.js';\nimport {steps, toStep} from '../schema/steps.js';\nimport {toWorkflowRunAttempt, workflowRunAttempts} from '../schema/workflow-run-attempts.js';\nimport {toWorkflowRun, workflowRuns} from '../schema/workflow-runs.js';\n\nexport type WorkflowRunCursor = TimestampIdCursor;\n\nexport interface WorkflowRunFilters {\n status?: WorkflowRunStatus | undefined;\n definitionId?: string | undefined;\n triggerSource?: string | undefined;\n origin?: WorkflowRunOrigin | undefined;\n createdFrom?: Date | undefined;\n createdTo?: Date | undefined;\n}\n\nexport interface ListWorkflowRunsParams {\n projectId: string;\n limit: number;\n cursor?: WorkflowRunCursor | undefined;\n filters?: WorkflowRunFilters | undefined;\n includeTotal?: boolean | undefined;\n}\n\nexport interface ListWorkflowRunsResult {\n runs: WorkflowRun[];\n nextCursor: WorkflowRunCursor | null;\n filteredTotalCount: number | null;\n}\n\n/** A run-list job glyph: enough to draw and label it, none of its steps. */\nexport interface WorkflowRunJobSummary {\n id: string;\n key: string;\n name: string | null;\n status: JobStatus;\n mode: JobMode;\n listenerStatus: ListenerStatus;\n executionStatus: JobExecutionStatus | null;\n position: number;\n}\n\nexport interface WorkflowRunAggregates {\n status: Array<{value: WorkflowRunStatus; count: number}>;\n triggerSource: Array<{value: string; count: number}>;\n workflow: Array<{value: string; count: number}>;\n}\n\nexport interface WorkflowJobExecutionDepth {\n runningRuns: number;\n runningJobExecutions: number;\n}\n\nexport interface WorkflowJobExecutionDepthParams {\n workspaceId?: string;\n}\n\nexport async function getWorkflowRunById(id: string): Promise<WorkflowRun | undefined> {\n const rows = await db().select().from(workflowRuns).where(eq(workflowRuns.id, id)).limit(1);\n const row = rows[0];\n if (!row) return undefined;\n return toWorkflowRun(row);\n}\n\nexport async function getWorkflowRunByAttemptId(\n workflowRunAttemptId: string,\n): Promise<WorkflowRun | undefined> {\n const rows = await db()\n .select({run: workflowRuns})\n .from(workflowRunAttempts)\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(eq(workflowRunAttempts.id, workflowRunAttemptId))\n .limit(1);\n const row = rows[0];\n return row ? toWorkflowRun(row.run) : undefined;\n}\n\nexport async function getWorkflowRunAttemptById(workflowRunAttemptId: string) {\n const rows = await db()\n .select()\n .from(workflowRunAttempts)\n .where(eq(workflowRunAttempts.id, workflowRunAttemptId))\n .limit(1);\n const row = rows[0];\n return row ? toWorkflowRunAttempt(row) : undefined;\n}\n\nexport async function listRunAttempts(params: {workflowRunId: string; projectId: string}) {\n return (\n await db()\n .select({\n attempt: workflowRunAttempts,\n })\n .from(workflowRunAttempts)\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(\n and(\n eq(workflowRunAttempts.workflowRunId, params.workflowRunId),\n eq(workflowRuns.projectId, params.projectId),\n ),\n )\n .orderBy(asc(workflowRunAttempts.attempt))\n ).map((row) => toWorkflowRunAttempt(row.attempt));\n}\n\nexport async function getLatestAttempt(params: {\n workflowRunId: string;\n projectId: string;\n}): Promise<number> {\n const [row] = await db()\n .select({value: sql<number>`coalesce(max(${workflowRunAttempts.attempt}), 1)`})\n .from(workflowRunAttempts)\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(\n and(\n eq(workflowRunAttempts.workflowRunId, params.workflowRunId),\n eq(workflowRuns.projectId, params.projectId),\n ),\n )\n .limit(1);\n\n return Number(row?.value ?? 1);\n}\n\nexport function buildWorkflowRunListConditions(params: {\n projectId: string;\n filters?: WorkflowRunFilters | undefined;\n cursor?: WorkflowRunCursor | undefined;\n omit?: 'status' | 'definitionId' | 'triggerSource' | 'origin' | undefined;\n}): SQL[] {\n const filters = params.filters;\n const conditions: SQL[] = [eq(workflowRuns.projectId, params.projectId)];\n const cursorCondition = timestampIdCursorWhere({\n timestampColumn: workflowRuns.createdAt,\n idColumn: workflowRuns.id,\n cursor: params.cursor,\n });\n if (cursorCondition) conditions.push(cursorCondition);\n if (filters?.status && params.omit !== 'status') {\n conditions.push(eq(workflowRuns.status, filters.status));\n }\n if (filters?.definitionId && params.omit !== 'definitionId') {\n conditions.push(eq(workflowRuns.definitionId, filters.definitionId));\n }\n if (filters?.triggerSource && params.omit !== 'triggerSource') {\n conditions.push(eq(workflowRuns.triggerSource, filters.triggerSource));\n }\n if (filters?.origin && params.omit !== 'origin') {\n conditions.push(eq(workflowRuns.origin, filters.origin));\n }\n if (filters?.createdFrom) {\n conditions.push(gte(workflowRuns.createdAt, filters.createdFrom));\n }\n if (filters?.createdTo) {\n conditions.push(lte(workflowRuns.createdAt, filters.createdTo));\n }\n return conditions;\n}\n\nexport async function listWorkflowRuns(\n params: ListWorkflowRunsParams,\n): Promise<ListWorkflowRunsResult> {\n const conditions = buildWorkflowRunListConditions(params);\n const rows = await db()\n .select()\n .from(workflowRuns)\n .where(and(...conditions))\n .orderBy(desc(workflowRuns.createdAt), desc(workflowRuns.id))\n .limit(params.limit + 1);\n\n let totalCount: number | null = null;\n if (params.includeTotal) {\n const [{value} = {value: 0}] = await db()\n .select({value: count()})\n .from(workflowRuns)\n .where(\n and(\n ...buildWorkflowRunListConditions({projectId: params.projectId, filters: params.filters}),\n ),\n );\n totalCount = value;\n }\n\n const page = paginateTimestampIdRows({rows, limit: params.limit, timestampKey: 'createdAt'});\n\n return {\n runs: page.pageRows.map(toWorkflowRun),\n nextCursor: page.nextCursor,\n filteredTotalCount: totalCount,\n };\n}\n\n/** The run whose jobs to fetch, pinned to the attempt the caller already read. */\nexport interface WorkflowRunJobSummaryTarget {\n id: string;\n currentAttempt: number;\n}\n\n/**\n * A page row's jobs: a bounded slice to draw, totals describing all of them, and whether any\n * execution has reached a runner.\n *\n * The preview is what a row can show; `statusCounts` is what it can say. Keeping the counts\n * server-side is what lets a row report a failure that sits past the preview. Counts use the\n * display status derived from the job verdict, listener state, and selected execution state;\n * the row keeps the verdict and evidence separate so the client can apply the same display\n * rule as run detail.\n */\nexport interface WorkflowRunJobsSummary {\n preview: WorkflowRunJobSummary[];\n statusCounts: WorkflowRunJobStatusCount[];\n rawStatusCounts: WorkflowRunJobRawStatusCount[];\n hasStartedJobExecution: boolean;\n}\n\nexport interface WorkflowRunJobStatusCount {\n status: JobStatus | 'listening';\n count: number;\n}\n\nexport interface WorkflowRunJobRawStatusCount {\n status: JobStatus;\n count: number;\n}\n\n/**\n * Jobs for a page of runs, keyed by run id.\n *\n * Issued once per page rather than once per run: the run list is the one surface that needs\n * every run's jobs at once, and a per-row query would put 50 round trips behind it.\n *\n * Both reads are bounded by the page, not by workflow size. A workflow has no job limit and\n * this list polls while runs are active, so returning every job of every row would let one\n * large workflow decide how much the endpoint moves every four seconds. The preview is cut\n * per run in the database, and everything past it is described by a grouped count instead.\n *\n * The attempt comes from the caller's own read rather than from a second look at\n * `current_attempt`. Re-reading it here would let a re-run landing between the queries pair\n * attempt 1's run metadata with attempt 2's jobs, and the row would report a status its strip\n * contradicts.\n *\n * The reads share one repeatable-read snapshot. They describe the same jobs and executions at\n * the same instant, and the strip combines them into a single glyph row, so under the default\n * read-committed isolation a job settling between the statements would draw a pending glyph\n * beside a summary counting it as failed. Sequential inside one transaction is the cost of\n * that; at a four-second poll the extra round trip does not register.\n */\nexport async function listWorkflowRunJobSummaries(\n runs: readonly WorkflowRunJobSummaryTarget[],\n): Promise<Map<string, WorkflowRunJobsSummary>> {\n const summaries = new Map<string, WorkflowRunJobsSummary>();\n if (runs.length === 0) return summaries;\n\n // A row-constructor IN over (run, attempt) so each pair is one lookup on the unique index\n // that already covers those two columns.\n const attemptPairs = sql.join(\n runs.map((run) => sql`(${run.id}::uuid, ${run.currentAttempt})`),\n sql`, `,\n );\n const attemptFilter = sql`(${workflowRunAttempts.workflowRunId}, ${workflowRunAttempts.attempt}) in (${attemptPairs})`;\n\n const {previewRows, countRows} = await db().transaction(\n async (tx) => {\n // Pick the execution the detail view would display once per job before either list\n // statement touches it. The existing (job_id, sequence) index supports the latest\n // execution ordering, while the status-first expression preserves the rule that an\n // active execution wins over a newer completed retry.\n const selectedExecution = tx.$with('selected_execution').as(\n tx\n .selectDistinctOn([jobExecutions.jobId], {\n jobId: jobExecutions.jobId,\n executionStatus: sql<JobExecutionStatus>`${jobExecutions.status}`.as(\n 'execution_status',\n ),\n })\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .where(attemptFilter)\n .orderBy(\n asc(jobExecutions.jobId),\n sql`case when ${jobExecutions.status} = 'running' then 0 else 1 end`,\n desc(jobExecutions.sequence),\n desc(jobExecutions.id),\n ),\n );\n\n const ranked = tx\n .with(selectedExecution)\n .select({\n workflowRunId: workflowRunAttempts.workflowRunId,\n id: jobs.id,\n key: jobs.key,\n name: jobs.name,\n status: jobs.status,\n mode: jobs.mode,\n listenerStatus: jobs.listenerStatus,\n executionStatus: selectedExecution.executionStatus,\n position: jobs.position,\n jobRank:\n sql<number>`row_number() over (partition by ${workflowRunAttempts.workflowRunId} order by ${jobs.position} asc, ${jobs.id} asc)`.as(\n 'job_rank',\n ),\n })\n .from(jobs)\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .leftJoin(selectedExecution, eq(selectedExecution.jobId, jobs.id))\n .where(attemptFilter)\n .as('ranked');\n // Correlated per job rather than a grouped scan of `job_executions`: an aggregate over the\n // whole table cannot have the page's filter pushed into it, so it would read every execution\n // ever recorded on each poll and grow with history rather than with the page.\n const hasStartedJobExecution = sql<boolean>`bool_or(exists (\n select 1\n from ${jobExecutions}\n where ${jobExecutions.jobId} = ${jobs.id} and ${jobExecutions.startedAt} is not null\n ))`;\n\n const executionDisplayStatus = sql<JobExecutionStatus | null>`\n ${selectedExecution.executionStatus}\n `;\n const displayStatus = sql<WorkflowRunJobStatusCount['status']>`\n case\n when ${jobs.status} in ('succeeded', 'failed', 'cancelled', 'skipped') then ${jobs.status}::text\n when ${jobs.mode} = 'listening' and ${jobs.listenerStatus} = 'listening' then 'listening'\n when ${executionDisplayStatus} is not null then ${executionDisplayStatus}::text\n else 'pending'\n end\n `;\n return {\n previewRows: await tx\n .select({\n workflowRunId: ranked.workflowRunId,\n id: ranked.id,\n key: ranked.key,\n name: ranked.name,\n status: ranked.status,\n mode: ranked.mode,\n listenerStatus: ranked.listenerStatus,\n executionStatus: ranked.executionStatus,\n position: ranked.position,\n })\n .from(ranked)\n .where(lte(ranked.jobRank, WORKFLOW_RUN_JOB_PREVIEW_LIMIT))\n .orderBy(asc(ranked.workflowRunId), asc(ranked.position), asc(ranked.id)),\n countRows: await tx\n .with(selectedExecution)\n .select({\n workflowRunId: workflowRunAttempts.workflowRunId,\n rawStatus: jobs.status,\n status: displayStatus,\n count: count(),\n hasStartedJobExecution,\n })\n .from(jobs)\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .leftJoin(selectedExecution, eq(selectedExecution.jobId, jobs.id))\n .where(attemptFilter)\n .groupBy(workflowRunAttempts.workflowRunId, jobs.status, displayStatus),\n };\n },\n {isolationLevel: 'repeatable read', accessMode: 'read only'},\n );\n\n for (const {workflowRunId, ...summary} of previewRows) {\n summaryFor(summaries, workflowRunId).preview.push(summary);\n }\n for (const {\n workflowRunId,\n rawStatus,\n status,\n count: statusCount,\n hasStartedJobExecution,\n } of countRows) {\n const summary = summaryFor(summaries, workflowRunId);\n appendStatusCount(summary.rawStatusCounts, rawStatus, statusCount);\n appendStatusCount(summary.statusCounts, status, statusCount);\n // One row per (run, verdict, display status), so the run's answer is the OR of its groups.\n summary.hasStartedJobExecution ||= hasStartedJobExecution;\n }\n\n return summaries;\n}\n\nfunction summaryFor(\n summaries: Map<string, WorkflowRunJobsSummary>,\n workflowRunId: string,\n): WorkflowRunJobsSummary {\n const existing = summaries.get(workflowRunId);\n if (existing) return existing;\n const created: WorkflowRunJobsSummary = {\n preview: [],\n statusCounts: [],\n rawStatusCounts: [],\n hasStartedJobExecution: false,\n };\n summaries.set(workflowRunId, created);\n return created;\n}\n\nfunction appendStatusCount<T extends string>(\n counts: Array<{status: T; count: number}>,\n status: T,\n count: number,\n): void {\n const existing = counts.find((entry) => entry.status === status);\n if (existing) {\n existing.count += count;\n } else {\n counts.push({status, count});\n }\n}\n\nexport async function listWorkflowRunsByProject(projectId: string): Promise<WorkflowRun[]> {\n const result = await listWorkflowRuns({projectId, limit: 100});\n return result.runs;\n}\n\nexport async function getWorkflowRunAggregates(params: {\n projectId: string;\n filters?: WorkflowRunFilters | undefined;\n}): Promise<WorkflowRunAggregates> {\n const [statusRows, triggerRows, workflowRows] = await Promise.all([\n db()\n .select({value: workflowRuns.status, count: count()})\n .from(workflowRuns)\n .where(\n and(\n ...buildWorkflowRunListConditions({\n projectId: params.projectId,\n filters: params.filters,\n omit: 'status',\n }),\n ),\n )\n .groupBy(workflowRuns.status),\n db()\n .select({value: workflowRuns.triggerSource, count: count()})\n .from(workflowRuns)\n .where(\n and(\n ...buildWorkflowRunListConditions({\n projectId: params.projectId,\n filters: params.filters,\n omit: 'triggerSource',\n }),\n ),\n )\n .groupBy(workflowRuns.triggerSource),\n db()\n .select({value: workflowRuns.definitionId, count: count()})\n .from(workflowRuns)\n .where(\n and(\n ...buildWorkflowRunListConditions({\n projectId: params.projectId,\n filters: params.filters,\n omit: 'definitionId',\n }),\n ),\n )\n .groupBy(workflowRuns.definitionId),\n ]);\n\n return {\n status: statusRows,\n triggerSource: triggerRows,\n workflow: workflowRows,\n };\n}\n\nexport async function getWorkflowJobExecutionDepth(\n params: WorkflowJobExecutionDepthParams = {},\n): Promise<WorkflowJobExecutionDepth> {\n const runConditions = [eq(workflowRuns.status, 'running')];\n const jobConditions = [eq(jobExecutions.status, 'running')];\n if (params.workspaceId) {\n runConditions.push(eq(workflowRuns.workspaceId, params.workspaceId));\n jobConditions.push(eq(workflowRuns.workspaceId, params.workspaceId));\n }\n\n const [runRows, jobRows] = await Promise.all([\n db()\n .select({value: count()})\n .from(workflowRuns)\n .where(and(...runConditions)),\n db()\n .select({value: count()})\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .where(and(...jobConditions)),\n ]);\n\n return {\n runningRuns: runRows[0]?.value ?? 0,\n runningJobExecutions: jobRows[0]?.value ?? 0,\n };\n}\n\nexport async function getWorkflowRunDetail(\n workflowRunId: string,\n attempt?: number | undefined,\n): Promise<WorkflowRunDetail | undefined> {\n const [target] = await db()\n .select({run: workflowRuns, attempt: workflowRunAttempts})\n .from(workflowRuns)\n .innerJoin(\n workflowRunAttempts,\n and(\n eq(workflowRunAttempts.workflowRunId, workflowRuns.id),\n eq(workflowRunAttempts.attempt, attempt ?? workflowRuns.currentAttempt),\n ),\n )\n .where(eq(workflowRuns.id, workflowRunId))\n .limit(1);\n if (!target) return undefined;\n\n const latestAttempt = await getLatestAttempt({\n workflowRunId: target.run.id,\n projectId: target.run.projectId,\n });\n\n const rows = await db()\n .select({\n run: workflowRuns,\n job: jobs,\n jobExecution: jobExecutions,\n step: steps,\n stepAttempt: stepAttempts,\n })\n .from(workflowRuns)\n .innerJoin(workflowRunAttempts, eq(workflowRunAttempts.id, target.attempt.id))\n .leftJoin(jobs, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .leftJoin(jobExecutions, eq(jobExecutions.jobId, jobs.id))\n .leftJoin(steps, eq(steps.jobExecutionId, jobExecutions.id))\n .leftJoin(stepAttempts, eq(stepAttempts.stepId, steps.id))\n .where(eq(workflowRuns.id, workflowRunId))\n .orderBy(\n asc(jobs.position),\n asc(jobs.id),\n asc(jobExecutions.sequence),\n asc(jobExecutions.id),\n asc(steps.position),\n asc(steps.id),\n asc(stepAttempts.executionOrder),\n asc(stepAttempts.id),\n );\n\n return hydrateWorkflowRunDetail(rows, target.attempt, latestAttempt);\n}\n\nexport async function getJobExecutionDetail(\n jobExecutionId: string,\n): Promise<JobExecutionDetail | undefined> {\n const rows = await db()\n .select({\n job: jobs,\n jobExecution: jobExecutions,\n step: steps,\n stepAttempt: stepAttempts,\n })\n .from(jobExecutions)\n .innerJoin(jobs, eq(jobExecutions.jobId, jobs.id))\n .innerJoin(workflowRunAttempts, eq(jobs.workflowRunAttemptId, workflowRunAttempts.id))\n .innerJoin(workflowRuns, eq(workflowRunAttempts.workflowRunId, workflowRuns.id))\n .leftJoin(steps, eq(steps.jobExecutionId, jobExecutions.id))\n .leftJoin(stepAttempts, eq(stepAttempts.stepId, steps.id))\n .where(eq(jobExecutions.id, jobExecutionId))\n .orderBy(\n asc(steps.position),\n asc(steps.id),\n asc(stepAttempts.executionOrder),\n asc(stepAttempts.id),\n );\n\n const first = rows[0];\n if (!first) return undefined;\n\n const detail: JobExecutionDetail = {\n ...toJobExecution(first.jobExecution, first.job.name ?? first.job.key),\n steps: [],\n };\n const stepById = new Map<string, StepDetail>();\n for (const row of rows) {\n if (row.step) {\n const step = getOrCreateStepDetail(stepById, detail.steps, row.step);\n if (row.stepAttempt) {\n step.attempts.push(toStepAttempt(row.stepAttempt));\n }\n }\n }\n\n return detail;\n}\n\nfunction hydrateWorkflowRunDetail(\n rows: {\n run: typeof workflowRuns.$inferSelect;\n job: typeof jobs.$inferSelect | null;\n jobExecution: typeof jobExecutions.$inferSelect | null;\n step: typeof steps.$inferSelect | null;\n stepAttempt: typeof stepAttempts.$inferSelect | null;\n }[],\n attempt: typeof workflowRunAttempts.$inferSelect,\n latestAttempt: number,\n): WorkflowRunDetail | undefined {\n const first = rows[0];\n if (!first) return undefined;\n\n const detail: WorkflowRunDetail = {\n ...toWorkflowRun(first.run),\n runAttempt: toWorkflowRunAttempt(attempt),\n latestAttempt,\n jobs: [],\n // Read off the same rows the executions come from, so the flag cannot contradict them.\n hasStartedJobExecution: rows.some((row) => row.jobExecution?.startedAt != null),\n };\n const jobById = new Map<string, WorkflowJobDetail>();\n const jobExecutionById = new Map<string, JobExecutionDetail>();\n const stepById = new Map<string, StepDetail>();\n\n for (const row of rows) {\n if (!row.job) continue;\n let job = jobById.get(row.job.id);\n if (!job) {\n job = {...toJob(row.job), jobExecutions: []};\n jobById.set(row.job.id, job);\n detail.jobs.push(job);\n }\n\n if (!row.jobExecution) continue;\n let jobExecution = jobExecutionById.get(row.jobExecution.id);\n if (!jobExecution) {\n jobExecution = {\n ...toJobExecution(row.jobExecution, row.job.name ?? row.job.key),\n steps: [],\n };\n jobExecutionById.set(row.jobExecution.id, jobExecution);\n job.jobExecutions.push(jobExecution);\n }\n\n if (!row.step) continue;\n const step = getOrCreateStepDetail(stepById, jobExecution.steps, row.step);\n if (row.stepAttempt) {\n step.attempts.push(toStepAttempt(row.stepAttempt));\n }\n }\n\n return detail;\n}\n\nfunction getOrCreateStepDetail(\n stepById: Map<string, StepDetail>,\n target: StepDetail[],\n row: typeof steps.$inferSelect,\n): StepDetail {\n let step = stepById.get(row.id);\n if (!step) {\n step = {...toStep(row), attempts: []};\n stepById.set(row.id, step);\n target.push(step);\n }\n return step;\n}\n"],"names":["WORKFLOW_RUN_JOB_PREVIEW_LIMIT","paginateTimestampIdRows","timestampIdCursorWhere","and","asc","count","desc","eq","gte","lte","sql","db","jobExecutions","toJobExecution","jobs","toJob","stepAttempts","toStepAttempt","steps","toStep","toWorkflowRunAttempt","workflowRunAttempts","toWorkflowRun","workflowRuns","getWorkflowRunById","id","rows","select","from","where","limit","row","undefined","getWorkflowRunByAttemptId","workflowRunAttemptId","run","innerJoin","workflowRunId","getWorkflowRunAttemptById","listRunAttempts","params","attempt","projectId","orderBy","map","getLatestAttempt","value","Number","buildWorkflowRunListConditions","filters","conditions","cursorCondition","timestampColumn","createdAt","idColumn","cursor","push","status","omit","definitionId","triggerSource","origin","createdFrom","createdTo","listWorkflowRuns","totalCount","includeTotal","page","timestampKey","runs","pageRows","nextCursor","filteredTotalCount","listWorkflowRunJobSummaries","summaries","Map","length","attemptPairs","join","currentAttempt","attemptFilter","previewRows","countRows","transaction","tx","selectedExecution","$with","as","selectDistinctOn","jobId","executionStatus","sequence","ranked","with","key","name","mode","listenerStatus","position","jobRank","leftJoin","hasStartedJobExecution","startedAt","executionDisplayStatus","displayStatus","rawStatus","groupBy","isolationLevel","accessMode","summary","summaryFor","preview","statusCount","appendStatusCount","rawStatusCounts","statusCounts","existing","get","created","set","counts","find","entry","listWorkflowRunsByProject","result","getWorkflowRunAggregates","statusRows","triggerRows","workflowRows","Promise","all","workflow","getWorkflowJobExecutionDepth","runConditions","jobConditions","workspaceId","runRows","jobRows","runningRuns","runningJobExecutions","getWorkflowRunDetail","target","latestAttempt","job","jobExecution","step","stepAttempt","jobExecutionId","stepId","executionOrder","hydrateWorkflowRunDetail","getJobExecutionDetail","first","detail","stepById","getOrCreateStepDetail","attempts","runAttempt","some","jobById","jobExecutionById"],"mappings":"AAAA,SAAQA,8BAA8B,QAAO,6BAA6B;AAC1E,SACEC,uBAAuB,EAEvBC,sBAAsB,QACjB,wBAAwB;AAC/B,SAAQC,GAAG,EAAEC,GAAG,EAAEC,KAAK,EAAEC,IAAI,EAAEC,EAAE,EAAEC,GAAG,EAAEC,GAAG,EAAYC,GAAG,QAAO,cAAc;AAY/E,SAAQC,EAAE,QAAO,WAAW;AAC5B,SAAQC,aAAa,EAAEC,cAAc,QAAO,8BAA8B;AAC1E,SAAQC,IAAI,EAAEC,KAAK,QAAO,oBAAoB;AAC9C,SAAQC,YAAY,EAAEC,aAAa,QAAO,6BAA6B;AACvE,SAAQC,KAAK,EAAEC,MAAM,QAAO,qBAAqB;AACjD,SAAQC,oBAAoB,EAAEC,mBAAmB,QAAO,qCAAqC;AAC7F,SAAQC,aAAa,EAAEC,YAAY,QAAO,6BAA6B;AAsDvE,OAAO,eAAeC,mBAAmBC,EAA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CmJ,QAAQxC,GAAG,CAACxF,IAAIgH,GAAG,CAACtH,EAAE,EAAEsH;YACxBU,OAAO3I,IAAI,CAAC0C,IAAI,CAACuF;QACnB;QAEA,IAAI,CAAChH,IAAIiH,YAAY,EAAE;QACvB,IAAIA,eAAegB,iBAAiB3C,GAAG,CAACtF,IAAIiH,YAAY,CAACvH,EAAE;QAC3D,IAAI,CAACuH,cAAc;YACjBA,eAAe;gBACb,GAAGnI,eAAekB,IAAIiH,YAAY,EAAEjH,IAAIgH,GAAG,CAAChD,IAAI,IAAIhE,IAAIgH,GAAG,CAACjD,GAAG,CAAC;gBAChE5E,OAAO,EAAE;YACX;YACA8I,iBAAiBzC,GAAG,CAACxF,IAAIiH,YAAY,CAACvH,EAAE,EAAEuH;YAC1CD,IAAInI,aAAa,CAAC4C,IAAI,CAACwF;QACzB;QAEA,IAAI,CAACjH,IAAIkH,IAAI,EAAE;QACf,MAAMA,OAAOU,sBAAsBD,UAAUV,aAAa9H,KAAK,EAAEa,IAAIkH,IAAI;QACzE,IAAIlH,IAAImH,WAAW,EAAE;YACnBD,KAAKW,QAAQ,CAACpG,IAAI,CAACvC,cAAcc,IAAImH,WAAW;QAClD;IACF;IAEA,OAAOO;AACT;AAEA,SAASE,sBACPD,QAAiC,EACjCb,MAAoB,EACpB9G,GAA8B;IAE9B,IAAIkH,OAAOS,SAASrC,GAAG,CAACtF,IAAIN,EAAE;IAC9B,IAAI,CAACwH,MAAM;QACTA,OAAO;YAAC,GAAG9H,OAAOY,IAAI;YAAE6H,UAAU,EAAE;QAAA;QACpCF,SAASnC,GAAG,CAACxF,IAAIN,EAAE,EAAEwH;QACrBJ,OAAOrF,IAAI,CAACyF;IACd;IACA,OAAOA;AACT"}
@@ -3,7 +3,7 @@ import type { IntegrationsModuleClient } from '@shipfox/api-integration-core-dto
3
3
  import type { ProjectsModuleClient } from '@shipfox/api-projects-dto/inter-module';
4
4
  import type { SecretsInterModuleClient } from '@shipfox/api-secrets-dto/inter-module';
5
5
  import type { AgentDefaultsResolver } from '#core/agent-defaults.js';
6
- import type { TriggerPayload, WorkflowRun, WorkflowSourceSnapshot } from '#core/entities/workflow-run.js';
6
+ import type { TriggerPayload, WorkflowRun, WorkflowRunDevSource, WorkflowRunOrigin, WorkflowSourceSnapshot } from '#core/entities/workflow-run.js';
7
7
  import { InterpolationUnresolvableError } from '#core/errors.js';
8
8
  export type WorkflowModelJob = WorkflowModel['jobs'][number];
9
9
  export interface ReferencedVariable {
@@ -23,6 +23,9 @@ export interface CreateWorkflowRunParams {
23
23
  inputs?: Record<string, unknown> | undefined;
24
24
  sourceSnapshot?: WorkflowSourceSnapshot | null | undefined;
25
25
  triggerIdempotencyKey?: string | undefined;
26
+ /** Run provenance. Defaults to a synced run with no dev source. */
27
+ origin?: WorkflowRunOrigin | undefined;
28
+ devSource?: WorkflowRunDevSource | null | undefined;
26
29
  resolveAgentDefaults?: AgentDefaultsResolver | undefined;
27
30
  secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;
28
31
  integrations?: IntegrationsModuleClient | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"run-create.d.ts","sourceRoot":"","sources":["../../../src/db/workflow-runs/run-create.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,aAAa,EACnB,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAC,wBAAwB,EAAC,MAAM,gDAAgD,CAAC;AAC7F,OAAO,KAAK,EAAC,oBAAoB,EAAC,MAAM,wCAAwC,CAAC;AACjF,OAAO,KAAK,EAAC,wBAAwB,EAAC,MAAM,uCAAuC,CAAC;AAQpF,OAAO,KAAK,EAAC,qBAAqB,EAAC,MAAM,yBAAyB,CAAC;AAKnE,OAAO,KAAK,EACV,cAAc,EACd,WAAW,EACX,sBAAsB,EACvB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAC,8BAA8B,EAAC,MAAM,iBAAiB,CAAC;AAoB/D,MAAM,MAAM,gBAAgB,GAAG,aAAa,C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C,EAAE,IAAI,CAAC,wBAAwB,EAAE,yBAAyB,CAAC,GAAG,SAAS,CAAC;CAC1F,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAAC,CAkC9C"}
@@ -66,7 +66,9 @@ export async function createWorkflowRun(params) {
66
66
  triggerReference,
67
67
  inputs: params.inputs ?? null,
68
68
  sourceSnapshot: params.sourceSnapshot ?? null,
69
- triggerIdempotencyKey: params.triggerIdempotencyKey ?? null
69
+ triggerIdempotencyKey: params.triggerIdempotencyKey ?? null,
70
+ origin: params.origin ?? 'synced',
71
+ devSource: params.devSource === undefined || params.devSource === null ? null : toWorkflowRunDevSourceDb(params.devSource)
70
72
  }).onConflictDoNothing({
71
73
  target: workflowRuns.triggerIdempotencyKey
72
74
  }).returning();
@@ -193,6 +195,17 @@ async function allocateWorkflowRunNumber(tx, definitionId) {
193
195
  if (!counterRow) throw new Error('Run counter allocation returned no rows');
194
196
  return counterRow.number;
195
197
  }
198
+ // The run entity carries camelCase dev-source fields while the persisted jsonb uses
199
+ // snake_case keys, so the write boundary maps explicitly rather than spreading.
200
+ function toWorkflowRunDevSourceDb(source) {
201
+ return {
202
+ ref: source.ref,
203
+ commit: source.commit,
204
+ config_path: source.configPath,
205
+ initiated_by_user_id: source.initiatedByUserId,
206
+ replay_of_event_id: source.replayOfEventId
207
+ };
208
+ }
196
209
  export async function loadReferencedVariables(params) {
197
210
  const references = referencedVariables(params.model, params.jobs ?? params.model.jobs);
198
211
  const keys = [
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/db/workflow-runs/run-create.ts"],"sourcesContent":["import {\n createWorkflowModelSnapshot,\n WORKFLOW_MODEL_CHECKOUT_TARGET_FIELDS,\n type WorkflowModel,\n} from '@shipfox/api-definitions-dto';\nimport type {IntegrationsModuleClient} from '@shipfox/api-integration-core-dto/inter-module';\nimport type {ProjectsModuleClient} from '@shipfox/api-projects-dto/inter-module';\nimport type {SecretsInterModuleClient} from '@shipfox/api-secrets-dto/inter-module';\nimport {\n analyzeContextKeyAccess,\n type ResolvedFieldSegment,\n type WorkflowExpression,\n} from '@shipfox/expression';\nimport {logger} from '@shipfox/node-opentelemetry';\nimport {eq, sql} from 'drizzle-orm';\nimport type {AgentDefaultsResolver} from '#core/agent-defaults.js';\nimport {\n createAgentToolMaterializationSnapshot,\n loadAgentToolMaterializationContext,\n} from '#core/agent-tools.js';\nimport type {\n TriggerPayload,\n WorkflowRun,\n WorkflowSourceSnapshot,\n} from '#core/entities/workflow-run.js';\nimport {InterpolationUnresolvableError} from '#core/errors.js';\nimport {resolveWorkflowRunTriggerReference} from '#core/resolve-trigger-reference.js';\nimport {assembleCreationContext} from '#core/step-config/assemble-run-context.js';\nimport type {MaterializedWorkflowJob} from '#core/step-config/materialize-workflow-model.js';\nimport type {WorkflowStepTemplateDiagnostic} from '#core/step-config/resolve-step-config.js';\nimport {resolveWorkflowRunName} from '#core/step-config/resolve-workflow-run-name.js';\nimport {\n deriveInitialJobExecutionPlan,\n materializeWorkflowRunJobs,\n} from '#core/workflow-run-creation.js';\nimport {\n recordWorkflowDisplayNameResolutionDegraded,\n recordWorkflowRunCreated,\n} from '#metrics/instance.js';\nimport {db, type Tx} from '../db.js';\nimport {workflowRunAttempts} from '../schema/workflow-run-attempts.js';\nimport {workflowRunCounters} from '../schema/workflow-run-counters.js';\nimport {toWorkflowRun, workflowRuns} from '../schema/workflow-runs.js';\nimport {type MaterializedRunGraphJob, persistMaterializedRunGraph} from './run-graph.js';\n\nexport type WorkflowModelJob = WorkflowModel['jobs'][number];\n\nexport interface ReferencedVariable {\n readonly key: string;\n readonly field: InterpolationUnresolvableError['field'];\n readonly source: string;\n readonly envKey?: string | undefined;\n}\n\nexport interface CreateWorkflowRunParams {\n workspaceId: string;\n projectId: string;\n definitionId: string;\n name?: string | undefined;\n model: WorkflowModel;\n triggerPayload: TriggerPayload;\n triggerConnectionId?: string | undefined;\n inputs?: Record<string, unknown> | undefined;\n sourceSnapshot?: WorkflowSourceSnapshot | null | undefined;\n triggerIdempotencyKey?: string | undefined;\n resolveAgentDefaults?: AgentDefaultsResolver | undefined;\n secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;\n integrations?: IntegrationsModuleClient | undefined;\n projects?: ProjectsModuleClient | undefined;\n}\n\nexport async function createWorkflowRun(params: CreateWorkflowRunParams): Promise<WorkflowRun> {\n const triggerReference = await resolveWorkflowRunTriggerReference({\n workspaceId: params.workspaceId,\n triggerConnectionId: params.triggerConnectionId,\n triggerPayload: params.triggerPayload,\n integrations: params.integrations,\n projects: params.projects,\n });\n const staticName = params.name ?? params.model.name;\n const agentToolContext =\n params.integrations === undefined\n ? undefined\n : await loadAgentToolMaterializationContext({\n model: params.model,\n workspaceId: params.workspaceId,\n projectId: params.projectId,\n integrations: params.integrations,\n projects: params.projects,\n });\n const agentToolMaterialization = createAgentToolMaterializationSnapshot({\n model: params.model,\n context: agentToolContext,\n });\n const result = await db().transaction(async (tx) => {\n // Serialize idempotent trigger resolution separately from per-definition number\n // allocation so a replay never consumes a number, including when two deliveries\n // race before either run is visible.\n if (params.triggerIdempotencyKey) {\n await tx.execute(\n sql`select pg_advisory_xact_lock(hashtext(${params.triggerIdempotencyKey}))`,\n );\n const existing = await tx\n .select()\n .from(workflowRuns)\n .where(eq(workflowRuns.triggerIdempotencyKey, params.triggerIdempotencyKey))\n .limit(1);\n const existingRow = existing[0];\n if (existingRow) return {run: toWorkflowRun(existingRow), created: false};\n }\n\n // Keep allocation on the existing transaction so a trigger burst cannot pin\n // every pool connection and then wait for a second connection per run.\n const number = await allocateWorkflowRunNumber(tx, params.definitionId);\n\n const insertResult = await tx\n .insert(workflowRuns)\n .values({\n workspaceId: params.workspaceId,\n projectId: params.projectId,\n definitionId: params.definitionId,\n number,\n name: null,\n workflowName: staticName,\n status: 'pending',\n currentAttempt: 1,\n triggerProvider: params.triggerPayload.provider ?? null,\n triggerSource: params.triggerPayload.source,\n triggerEvent: params.triggerPayload.event,\n triggerPayload: params.triggerPayload,\n triggerReference,\n inputs: params.inputs ?? null,\n sourceSnapshot: params.sourceSnapshot ?? null,\n triggerIdempotencyKey: params.triggerIdempotencyKey ?? null,\n })\n .onConflictDoNothing({target: workflowRuns.triggerIdempotencyKey})\n .returning();\n\n const runRow = insertResult[0];\n if (!runRow) {\n // Conflict path: skip jobs/steps/outbox so the first insert keeps ownership of side effects.\n if (!params.triggerIdempotencyKey) {\n throw new Error('Insert returned no rows');\n }\n const existing = await tx\n .select()\n .from(workflowRuns)\n .where(eq(workflowRuns.triggerIdempotencyKey, params.triggerIdempotencyKey))\n .limit(1);\n const existingRow = existing[0];\n if (!existingRow) {\n throw new Error(\n `Idempotency conflict but existing run missing for key ${params.triggerIdempotencyKey}`,\n );\n }\n return {run: toWorkflowRun(existingRow), created: false};\n }\n\n // Resolving run-creation templates and predicates here gives them a stable variable snapshot\n // and interpolation access to the inserted run id. Run-name resolution is display-only and\n // persists only a resolved override. If resolution fails, the transaction rolls back the run,\n // jobs, steps, and outbox event together. Listening steps are resolved later when a job\n // execution is created.\n const provisionalRun = toWorkflowRun(runRow);\n const oneShotJobs = params.model.jobs.filter((job) => job.mode !== 'listening');\n const vars = await loadReferencedVariables({\n model: params.model,\n jobs: oneShotJobs,\n workspaceId: params.workspaceId,\n projectId: params.projectId,\n definitionId: params.definitionId,\n secrets: params.secrets,\n });\n const runNameResolution = resolveWorkflowRunName({\n runName: params.model.runName,\n context: assembleCreationContext({\n run: provisionalRun,\n triggerPayload: params.triggerPayload,\n inputs: params.inputs ?? null,\n vars,\n }).values,\n });\n const [resolvedRunRow] = await tx\n .update(workflowRuns)\n .set({name: runNameResolution.value, updatedAt: new Date()})\n .where(eq(workflowRuns.id, provisionalRun.id))\n .returning();\n if (!resolvedRunRow)\n throw new Error(`Workflow run missing after name resolution: ${runRow.id}`);\n const run = toWorkflowRun(resolvedRunRow);\n const [attemptRow] = await tx\n .insert(workflowRunAttempts)\n .values({\n workflowRunId: runRow.id,\n attempt: 1,\n status: 'pending',\n model: createWorkflowModelSnapshot(params.model),\n vars,\n agentToolMaterialization,\n })\n .returning();\n if (!attemptRow) throw new Error('Insert returned no rows');\n\n const materializedJobs = await materializeWorkflowRunJobs({\n run,\n model: params.model,\n triggerPayload: params.triggerPayload,\n inputs: params.inputs ?? null,\n vars,\n resolveAgentDefaults: params.resolveAgentDefaults,\n definitionId: params.definitionId,\n agentToolContext,\n agentToolSnapshot: agentToolMaterialization,\n });\n\n const graphJobs = materializeRunGraphJobs({\n params,\n run,\n vars,\n materializedJobs,\n });\n await persistMaterializedRunGraph(tx, {\n run,\n workflowRunAttempt: attemptRow,\n materializedJobs: graphJobs,\n });\n\n logTemplateDiagnostics({\n workflowRunId: runRow.id,\n diagnostics: materializedJobs.flatMap((job) =>\n job.steps.flatMap((step) =>\n (step.diagnostics ?? []).map((diagnostic) => ({\n jobKey: job.key,\n stepName: step.name,\n ...diagnostic,\n })),\n ),\n ),\n });\n\n return {\n run,\n created: true,\n nameDegradation: runNameResolution.degradation,\n };\n });\n\n if (result.created && result.nameDegradation !== undefined) {\n recordWorkflowDisplayNameResolutionDegraded('workflow.run_name', result.nameDegradation.cause);\n logger().warn(\n {\n workflowRunId: result.run.id,\n definitionId: result.run.definitionId,\n field: 'workflow.run_name',\n cause: result.nameDegradation.cause,\n ...(result.nameDegradation.expression === undefined\n ? {}\n : {expression: result.nameDegradation.expression.slice(0, 256)}),\n },\n 'Workflow run name resolution degraded to the static workflow name',\n );\n }\n\n if (result.created) {\n recordWorkflowRunCreated(result.run.triggerPayload.provider ?? result.run.triggerSource);\n }\n\n return result.run;\n}\n\nasync function allocateWorkflowRunNumber(tx: Tx, definitionId: string): Promise<number> {\n const [counterRow] = await tx\n .insert(workflowRunCounters)\n .values({definitionId, nextNumber: 2})\n .onConflictDoUpdate({\n target: workflowRunCounters.definitionId,\n set: {nextNumber: sql`${workflowRunCounters.nextNumber} + 1`},\n })\n .returning({number: sql<number>`${workflowRunCounters.nextNumber} - 1`});\n if (!counterRow) throw new Error('Run counter allocation returned no rows');\n return counterRow.number;\n}\n\nexport async function loadReferencedVariables(params: {\n readonly model: WorkflowModel;\n readonly jobs?: readonly WorkflowModelJob[] | undefined;\n readonly workspaceId: string;\n readonly projectId: string;\n readonly definitionId: string;\n readonly secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;\n}): Promise<Record<string, string> | undefined> {\n const references = referencedVariables(params.model, params.jobs ?? params.model.jobs);\n const keys = [...new Set(references.map((reference) => reference.key))].sort();\n if (keys.length === 0) return undefined;\n\n const requiresSecrets = (reference: ReferencedVariable) =>\n reference.field !== 'job.execution_name' && reference.field !== 'workflow.run_name';\n const requiredReferences = references.filter(requiresSecrets);\n const requiredKeys = new Set(requiredReferences.map((reference) => reference.key));\n if (!params.secrets) {\n if (requiredKeys.size === 0) return undefined;\n throw new Error('Secrets client is not configured.');\n }\n const {values: vars} = await params.secrets.getVariablesByNamespace({\n workspaceId: params.workspaceId,\n projectId: params.projectId,\n namespace: '',\n });\n const missingKey = [...requiredKeys].find((key) => !(key in vars));\n if (missingKey !== undefined) {\n const reference = requiredReferences.find((candidate) => candidate.key === missingKey);\n throw new InterpolationUnresolvableError(params.definitionId, {\n field: reference?.field ?? 'env',\n source: reference?.source ?? `vars.${missingKey}`,\n ...(reference?.envKey === undefined ? {} : {envKey: reference.envKey}),\n });\n }\n\n const referencedVars: Record<string, string> = {};\n for (const key of keys) {\n const value = vars[key];\n if (value !== undefined) referencedVars[key] = value;\n }\n return referencedVars;\n}\n\nfunction materializeRunGraphJobs(params: {\n readonly params: CreateWorkflowRunParams;\n readonly run: WorkflowRun;\n readonly vars: Record<string, string> | undefined;\n readonly materializedJobs: readonly MaterializedWorkflowJob[];\n}): readonly MaterializedRunGraphJob[] {\n return params.materializedJobs.map((job, jobIndex) => ({\n job: {\n key: job.key,\n mode: job.mode,\n name: job.name ?? null,\n status: 'pending' as const,\n checkoutPersistCredentials: job.checkout.persistCredentials,\n checkoutPermissionsContents: job.checkout.permissions.contents,\n success: job.success ?? null,\n executionTimeoutMs: job.executionTimeoutMs ?? null,\n listeningTimeoutMs: job.listening?.timeoutMs ?? null,\n maxExecutions: job.listening?.maxExecutions ?? null,\n onResolve: job.listening?.onResolve ?? null,\n batchDebounceMs: job.listening?.batch?.debounceMs ?? null,\n batchMaxSize: job.listening?.batch?.maxSize ?? null,\n batchMaxWaitMs: job.listening?.batch?.maxWaitMs ?? null,\n listeningOn: job.listening?.on ? [...job.listening.on] : null,\n listeningUntil: job.listening?.until ? [...job.listening.until] : null,\n dependencies: [...job.dependencies],\n runner: job.runner.length === 0 ? null : [...job.runner],\n position: job.position,\n },\n createExecution: (jobRow) => {\n if (jobRow.mode === 'listening') return undefined;\n\n const fallbackName = jobRow.name ?? jobRow.key;\n const modelJob = params.params.model.jobs[jobIndex];\n if (!modelJob) return undefined;\n const executionPlan = deriveInitialJobExecutionPlan({\n run: params.run,\n modelJob,\n job,\n jobId: jobRow.id,\n sequence: 1,\n fallbackName,\n triggerPayload: params.params.triggerPayload,\n inputs: params.params.inputs ?? null,\n vars: params.vars,\n });\n\n return {\n sequence: 1,\n // Persist only the resolved override. The core entity supplies the\n // static job name/key when this is null.\n name: executionPlan.nameOverride,\n runner: [...executionPlan.runner],\n status: 'pending' as const,\n evaluationTrace:\n executionPlan.evaluationTrace?.length === 0 ? null : executionPlan.evaluationTrace,\n };\n },\n createSteps: () =>\n job.steps.map((step) => ({\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 condition: step.condition ?? null,\n configPlan: step.configPlan ?? null,\n authoredConfig: step.authoredConfig,\n position: step.position,\n })),\n }));\n}\n\nfunction referencedVariables(\n model: WorkflowModel,\n jobs: readonly WorkflowModelJob[],\n): readonly ReferencedVariable[] {\n const references: ReferencedVariable[] = [];\n\n for (const job of model.jobs) {\n collectPredicateVariableReferences(job.if, references);\n collectPredicateVariableReferences(job.success, references);\n\n for (const trigger of [...(job.listening?.on ?? []), ...(job.listening?.until ?? [])]) {\n collectPredicateVariableReferences(trigger.filter, references);\n }\n\n for (const step of job.steps) {\n collectPredicateVariableReferences(step.if, references);\n collectPredicateVariableReferences(step.gate?.success, references);\n }\n }\n\n collectFieldVariableReferences(model.runName, references, {field: 'workflow.run_name'});\n\n if (jobs.length > 0) {\n collectTemplateVariableReferences(model.templates?.env, references);\n }\n\n for (const job of jobs) {\n collectFieldVariableReferences(job.executionName, references, {field: 'job.execution_name'});\n for (const template of job.runnerTemplates ?? []) {\n collectFieldVariableReferences(template, references, {field: 'job.runner'});\n }\n collectTemplateVariableReferences(job.outputs, references, {field: 'job.outputs'});\n collectTemplateVariableReferences(job.templates?.env, references);\n\n for (const step of job.steps) {\n collectFieldVariableReferences(step.templates?.name, references, {field: 'step.name'});\n collectFieldVariableReferences(step.templates?.workingDirectory, references, {\n field: 'step.working_directory',\n });\n if (step.kind === 'run') {\n collectFieldVariableReferences(step.templates?.command, references, {field: 'run'});\n collectTemplateVariableReferences(step.templates?.env, references);\n } else if (step.kind === 'agent') {\n collectFieldVariableReferences(step.templates?.prompt, references, {field: 'agent.prompt'});\n collectFieldVariableReferences(step.templates?.model, references, {field: 'agent.model'});\n collectFieldVariableReferences(step.templates?.provider, references, {\n field: 'agent.provider',\n });\n } else if (step.kind === 'checkout') {\n for (const [key, field] of WORKFLOW_MODEL_CHECKOUT_TARGET_FIELDS) {\n collectFieldVariableReferences(step.checkout.templates?.[key], references, {field});\n }\n }\n }\n }\n\n return references;\n}\n\nfunction collectPredicateVariableReferences(\n expression: WorkflowExpression | string | undefined,\n references: ReferencedVariable[],\n): void {\n if (expression === undefined) return;\n\n const keyAccess = analyzeContextKeyAccess(expression);\n for (const reference of keyAccess.references) {\n if (reference.root !== 'vars') continue;\n references.push({\n key: reference.key,\n field: 'env',\n source: typeof expression === 'string' ? expression : expression.source,\n });\n }\n}\n\nfunction collectTemplateVariableReferences(\n templates: Readonly<Record<string, readonly ResolvedFieldSegment[]>> | undefined,\n references: ReferencedVariable[],\n source?: {\n readonly field: InterpolationUnresolvableError['field'];\n },\n): void {\n for (const [envKey, template] of Object.entries(templates ?? {})) {\n collectFieldVariableReferences(\n template,\n references,\n source === undefined ? {field: 'env', envKey} : source,\n );\n }\n}\n\nfunction collectFieldVariableReferences(\n template: readonly ResolvedFieldSegment[] | undefined,\n references: ReferencedVariable[],\n source: {\n readonly field: InterpolationUnresolvableError['field'];\n readonly envKey?: string | undefined;\n },\n): void {\n for (const segment of template ?? []) {\n if (segment.kind === 'literal') continue;\n const keyAccess = analyzeContextKeyAccess(segment.expression);\n for (const reference of keyAccess.references) {\n if (reference.root !== 'vars') continue;\n references.push({\n key: reference.key,\n field: source.field,\n source: segment.expression.source,\n envKey: source.envKey,\n });\n }\n }\n}\n\nfunction logTemplateDiagnostics(params: {\n readonly workflowRunId: string;\n readonly diagnostics: readonly (WorkflowStepTemplateDiagnostic & {\n readonly jobKey: string;\n readonly stepName: string;\n })[];\n}): void {\n if (params.diagnostics.length === 0) return;\n\n logger().warn(\n {workflowRunId: params.workflowRunId, diagnostics: params.diagnostics},\n 'Workflow interpolation resolved with diagnostics',\n );\n}\n"],"names":["createWorkflowModelSnapshot","WORKFLOW_MODEL_CHECKOUT_TARGET_FIELDS","analyzeContextKeyAccess","logger","eq","sql","createAgentToolMaterializationSnapshot","loadAgentToolMaterializationContext","InterpolationUnresolvableError","resolveWorkflowRunTriggerReference","assembleCreationContext","resolveWorkflowRunName","deriveInitialJobExecutionPlan","materializeWorkflowRunJobs","recordWorkflowDisplayNameResolutionDegraded","recordWorkflowRunCreated","db","workflowRunAttempts","workflowRunCounters","toWorkflowRun","workflowRuns","persistMaterializedRunGraph","createWorkflowRun","params","triggerReference","workspaceId","triggerConnectionId","triggerPayload","integrations","projects","staticName","name","model","agentToolContext","undefined","projectId","agentToolMaterialization","context","result","transaction","tx","triggerIdempotencyKey","execute","existing","select","from","where","limit","existingRow","run","created","number","allocateWorkflowRunNumber","definitionId","insertResult","insert","values","workflowName","status","currentAttempt","triggerProvider","provider","triggerSource","source","triggerEvent","event","inputs","sourceSnapshot","onConflictDoNothing","target","returning","runRow","Error","provisionalRun","oneShotJobs","jobs","filter","job","mode","vars","loadReferencedVariables","secrets","runNameResolution","runName","resolvedRunRow","update","set","value","updatedAt","Date","id","attemptRow","workflowRunId","attempt","materializedJobs","resolveAgentDefaults","agentToolSnapshot","graphJobs","materializeRunGraphJobs","workflowRunAttempt","logTemplateDiagnostics","diagnostics","flatMap","steps","step","map","diagnostic","jobKey","key","stepName","nameDegradation","degradation","cause","warn","field","expression","slice","counterRow","nextNumber","onConflictDoUpdate","references","referencedVariables","keys","Set","reference","sort","length","requiresSecrets","requiredReferences","requiredKeys","size","getVariablesByNamespace","namespace","missingKey","find","candidate","envKey","referencedVars","jobIndex","checkoutPersistCredentials","checkout","persistCredentials","checkoutPermissionsContents","permissions","contents","success","executionTimeoutMs","listeningTimeoutMs","listening","timeoutMs","maxExecutions","onResolve","batchDebounceMs","batch","debounceMs","batchMaxSize","maxSize","batchMaxWaitMs","maxWaitMs","listeningOn","on","listeningUntil","until","dependencies","runner","position","createExecution","jobRow","fallbackName","modelJob","executionPlan","jobId","sequence","nameOverride","evaluationTrace","createSteps","sourceLocation","type","config","condition","configPlan","authoredConfig","collectPredicateVariableReferences","if","trigger","gate","collectFieldVariableReferences","collectTemplateVariableReferences","templates","env","executionName","template","runnerTemplates","outputs","workingDirectory","kind","command","prompt","keyAccess","root","push","Object","entries","segment"],"mappings":"AAAA,SACEA,2BAA2B,EAC3BC,qCAAqC,QAEhC,+BAA+B;AAItC,SACEC,uBAAuB,QAGlB,sBAAsB;AAC7B,SAAQC,MAAM,QAAO,8BAA8B;AACnD,SAAQC,EAAE,EAAEC,GAAG,QAAO,cAAc;AAEpC,SACEC,sCAAsC,EACtCC,mCAAmC,QAC9B,uBAAuB;AAM9B,SAAQC,8BAA8B,QAAO,kBAAkB;AAC/D,SAAQC,kCAAkC,QAAO,qCAAqC;AACtF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AC;gBACd5F,KAAKgB,UAAUhB,GAAG;gBAClBM,OAAOnD,OAAOmD,KAAK;gBACnBnD,QAAQ4I,QAAQxF,UAAU,CAACpD,MAAM;gBACjCyE,QAAQzE,OAAOyE,MAAM;YACvB;QACF;IACF;AACF;AAEA,SAASpC,uBAAuB7E,MAM/B;IACC,IAAIA,OAAO8E,WAAW,CAACyB,MAAM,KAAK,GAAG;IAErC3H,SAAS8G,IAAI,CACX;QAACrB,eAAerE,OAAOqE,aAAa;QAAES,aAAa9E,OAAO8E,WAAW;IAAA,GACrE;AAEJ"}
1
+ {"version":3,"sources":["../../../src/db/workflow-runs/run-create.ts"],"sourcesContent":["import {\n createWorkflowModelSnapshot,\n WORKFLOW_MODEL_CHECKOUT_TARGET_FIELDS,\n type WorkflowModel,\n} from '@shipfox/api-definitions-dto';\nimport type {IntegrationsModuleClient} from '@shipfox/api-integration-core-dto/inter-module';\nimport type {ProjectsModuleClient} from '@shipfox/api-projects-dto/inter-module';\nimport type {SecretsInterModuleClient} from '@shipfox/api-secrets-dto/inter-module';\nimport {\n analyzeContextKeyAccess,\n type ResolvedFieldSegment,\n type WorkflowExpression,\n} from '@shipfox/expression';\nimport {logger} from '@shipfox/node-opentelemetry';\nimport {eq, sql} from 'drizzle-orm';\nimport type {AgentDefaultsResolver} from '#core/agent-defaults.js';\nimport {\n createAgentToolMaterializationSnapshot,\n loadAgentToolMaterializationContext,\n} from '#core/agent-tools.js';\nimport type {\n TriggerPayload,\n WorkflowRun,\n WorkflowRunDevSource,\n WorkflowRunOrigin,\n WorkflowSourceSnapshot,\n} from '#core/entities/workflow-run.js';\nimport {InterpolationUnresolvableError} from '#core/errors.js';\nimport {resolveWorkflowRunTriggerReference} from '#core/resolve-trigger-reference.js';\nimport {assembleCreationContext} from '#core/step-config/assemble-run-context.js';\nimport type {MaterializedWorkflowJob} from '#core/step-config/materialize-workflow-model.js';\nimport type {WorkflowStepTemplateDiagnostic} from '#core/step-config/resolve-step-config.js';\nimport {resolveWorkflowRunName} from '#core/step-config/resolve-workflow-run-name.js';\nimport {\n deriveInitialJobExecutionPlan,\n materializeWorkflowRunJobs,\n} from '#core/workflow-run-creation.js';\nimport {\n recordWorkflowDisplayNameResolutionDegraded,\n recordWorkflowRunCreated,\n} from '#metrics/instance.js';\nimport {db, type Tx} from '../db.js';\nimport {workflowRunAttempts} from '../schema/workflow-run-attempts.js';\nimport {workflowRunCounters} from '../schema/workflow-run-counters.js';\nimport {toWorkflowRun, type WorkflowRunDevSourceDb, workflowRuns} from '../schema/workflow-runs.js';\nimport {type MaterializedRunGraphJob, persistMaterializedRunGraph} from './run-graph.js';\n\nexport type WorkflowModelJob = WorkflowModel['jobs'][number];\n\nexport interface ReferencedVariable {\n readonly key: string;\n readonly field: InterpolationUnresolvableError['field'];\n readonly source: string;\n readonly envKey?: string | undefined;\n}\n\nexport interface CreateWorkflowRunParams {\n workspaceId: string;\n projectId: string;\n definitionId: string;\n name?: string | undefined;\n model: WorkflowModel;\n triggerPayload: TriggerPayload;\n triggerConnectionId?: string | undefined;\n inputs?: Record<string, unknown> | undefined;\n sourceSnapshot?: WorkflowSourceSnapshot | null | undefined;\n triggerIdempotencyKey?: string | undefined;\n /** Run provenance. Defaults to a synced run with no dev source. */\n origin?: WorkflowRunOrigin | undefined;\n devSource?: WorkflowRunDevSource | null | undefined;\n resolveAgentDefaults?: AgentDefaultsResolver | undefined;\n secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;\n integrations?: IntegrationsModuleClient | undefined;\n projects?: ProjectsModuleClient | undefined;\n}\n\nexport async function createWorkflowRun(params: CreateWorkflowRunParams): Promise<WorkflowRun> {\n const triggerReference = await resolveWorkflowRunTriggerReference({\n workspaceId: params.workspaceId,\n triggerConnectionId: params.triggerConnectionId,\n triggerPayload: params.triggerPayload,\n integrations: params.integrations,\n projects: params.projects,\n });\n const staticName = params.name ?? params.model.name;\n const agentToolContext =\n params.integrations === undefined\n ? undefined\n : await loadAgentToolMaterializationContext({\n model: params.model,\n workspaceId: params.workspaceId,\n projectId: params.projectId,\n integrations: params.integrations,\n projects: params.projects,\n });\n const agentToolMaterialization = createAgentToolMaterializationSnapshot({\n model: params.model,\n context: agentToolContext,\n });\n const result = await db().transaction(async (tx) => {\n // Serialize idempotent trigger resolution separately from per-definition number\n // allocation so a replay never consumes a number, including when two deliveries\n // race before either run is visible.\n if (params.triggerIdempotencyKey) {\n await tx.execute(\n sql`select pg_advisory_xact_lock(hashtext(${params.triggerIdempotencyKey}))`,\n );\n const existing = await tx\n .select()\n .from(workflowRuns)\n .where(eq(workflowRuns.triggerIdempotencyKey, params.triggerIdempotencyKey))\n .limit(1);\n const existingRow = existing[0];\n if (existingRow) return {run: toWorkflowRun(existingRow), created: false};\n }\n\n // Keep allocation on the existing transaction so a trigger burst cannot pin\n // every pool connection and then wait for a second connection per run.\n const number = await allocateWorkflowRunNumber(tx, params.definitionId);\n\n const insertResult = await tx\n .insert(workflowRuns)\n .values({\n workspaceId: params.workspaceId,\n projectId: params.projectId,\n definitionId: params.definitionId,\n number,\n name: null,\n workflowName: staticName,\n status: 'pending',\n currentAttempt: 1,\n triggerProvider: params.triggerPayload.provider ?? null,\n triggerSource: params.triggerPayload.source,\n triggerEvent: params.triggerPayload.event,\n triggerPayload: params.triggerPayload,\n triggerReference,\n inputs: params.inputs ?? null,\n sourceSnapshot: params.sourceSnapshot ?? null,\n triggerIdempotencyKey: params.triggerIdempotencyKey ?? null,\n origin: params.origin ?? 'synced',\n devSource:\n params.devSource === undefined || params.devSource === null\n ? null\n : toWorkflowRunDevSourceDb(params.devSource),\n })\n .onConflictDoNothing({target: workflowRuns.triggerIdempotencyKey})\n .returning();\n\n const runRow = insertResult[0];\n if (!runRow) {\n // Conflict path: skip jobs/steps/outbox so the first insert keeps ownership of side effects.\n if (!params.triggerIdempotencyKey) {\n throw new Error('Insert returned no rows');\n }\n const existing = await tx\n .select()\n .from(workflowRuns)\n .where(eq(workflowRuns.triggerIdempotencyKey, params.triggerIdempotencyKey))\n .limit(1);\n const existingRow = existing[0];\n if (!existingRow) {\n throw new Error(\n `Idempotency conflict but existing run missing for key ${params.triggerIdempotencyKey}`,\n );\n }\n return {run: toWorkflowRun(existingRow), created: false};\n }\n\n // Resolving run-creation templates and predicates here gives them a stable variable snapshot\n // and interpolation access to the inserted run id. Run-name resolution is display-only and\n // persists only a resolved override. If resolution fails, the transaction rolls back the run,\n // jobs, steps, and outbox event together. Listening steps are resolved later when a job\n // execution is created.\n const provisionalRun = toWorkflowRun(runRow);\n const oneShotJobs = params.model.jobs.filter((job) => job.mode !== 'listening');\n const vars = await loadReferencedVariables({\n model: params.model,\n jobs: oneShotJobs,\n workspaceId: params.workspaceId,\n projectId: params.projectId,\n definitionId: params.definitionId,\n secrets: params.secrets,\n });\n const runNameResolution = resolveWorkflowRunName({\n runName: params.model.runName,\n context: assembleCreationContext({\n run: provisionalRun,\n triggerPayload: params.triggerPayload,\n inputs: params.inputs ?? null,\n vars,\n }).values,\n });\n const [resolvedRunRow] = await tx\n .update(workflowRuns)\n .set({name: runNameResolution.value, updatedAt: new Date()})\n .where(eq(workflowRuns.id, provisionalRun.id))\n .returning();\n if (!resolvedRunRow)\n throw new Error(`Workflow run missing after name resolution: ${runRow.id}`);\n const run = toWorkflowRun(resolvedRunRow);\n const [attemptRow] = await tx\n .insert(workflowRunAttempts)\n .values({\n workflowRunId: runRow.id,\n attempt: 1,\n status: 'pending',\n model: createWorkflowModelSnapshot(params.model),\n vars,\n agentToolMaterialization,\n })\n .returning();\n if (!attemptRow) throw new Error('Insert returned no rows');\n\n const materializedJobs = await materializeWorkflowRunJobs({\n run,\n model: params.model,\n triggerPayload: params.triggerPayload,\n inputs: params.inputs ?? null,\n vars,\n resolveAgentDefaults: params.resolveAgentDefaults,\n definitionId: params.definitionId,\n agentToolContext,\n agentToolSnapshot: agentToolMaterialization,\n });\n\n const graphJobs = materializeRunGraphJobs({\n params,\n run,\n vars,\n materializedJobs,\n });\n await persistMaterializedRunGraph(tx, {\n run,\n workflowRunAttempt: attemptRow,\n materializedJobs: graphJobs,\n });\n\n logTemplateDiagnostics({\n workflowRunId: runRow.id,\n diagnostics: materializedJobs.flatMap((job) =>\n job.steps.flatMap((step) =>\n (step.diagnostics ?? []).map((diagnostic) => ({\n jobKey: job.key,\n stepName: step.name,\n ...diagnostic,\n })),\n ),\n ),\n });\n\n return {\n run,\n created: true,\n nameDegradation: runNameResolution.degradation,\n };\n });\n\n if (result.created && result.nameDegradation !== undefined) {\n recordWorkflowDisplayNameResolutionDegraded('workflow.run_name', result.nameDegradation.cause);\n logger().warn(\n {\n workflowRunId: result.run.id,\n definitionId: result.run.definitionId,\n field: 'workflow.run_name',\n cause: result.nameDegradation.cause,\n ...(result.nameDegradation.expression === undefined\n ? {}\n : {expression: result.nameDegradation.expression.slice(0, 256)}),\n },\n 'Workflow run name resolution degraded to the static workflow name',\n );\n }\n\n if (result.created) {\n recordWorkflowRunCreated(result.run.triggerPayload.provider ?? result.run.triggerSource);\n }\n\n return result.run;\n}\n\nasync function allocateWorkflowRunNumber(tx: Tx, definitionId: string): Promise<number> {\n const [counterRow] = await tx\n .insert(workflowRunCounters)\n .values({definitionId, nextNumber: 2})\n .onConflictDoUpdate({\n target: workflowRunCounters.definitionId,\n set: {nextNumber: sql`${workflowRunCounters.nextNumber} + 1`},\n })\n .returning({number: sql<number>`${workflowRunCounters.nextNumber} - 1`});\n if (!counterRow) throw new Error('Run counter allocation returned no rows');\n return counterRow.number;\n}\n\n// The run entity carries camelCase dev-source fields while the persisted jsonb uses\n// snake_case keys, so the write boundary maps explicitly rather than spreading.\nfunction toWorkflowRunDevSourceDb(source: WorkflowRunDevSource): WorkflowRunDevSourceDb {\n return {\n ref: source.ref,\n commit: source.commit,\n config_path: source.configPath,\n initiated_by_user_id: source.initiatedByUserId,\n replay_of_event_id: source.replayOfEventId,\n };\n}\n\nexport async function loadReferencedVariables(params: {\n readonly model: WorkflowModel;\n readonly jobs?: readonly WorkflowModelJob[] | undefined;\n readonly workspaceId: string;\n readonly projectId: string;\n readonly definitionId: string;\n readonly secrets?: Pick<SecretsInterModuleClient, 'getVariablesByNamespace'> | undefined;\n}): Promise<Record<string, string> | undefined> {\n const references = referencedVariables(params.model, params.jobs ?? params.model.jobs);\n const keys = [...new Set(references.map((reference) => reference.key))].sort();\n if (keys.length === 0) return undefined;\n\n const requiresSecrets = (reference: ReferencedVariable) =>\n reference.field !== 'job.execution_name' && reference.field !== 'workflow.run_name';\n const requiredReferences = references.filter(requiresSecrets);\n const requiredKeys = new Set(requiredReferences.map((reference) => reference.key));\n if (!params.secrets) {\n if (requiredKeys.size === 0) return undefined;\n throw new Error('Secrets client is not configured.');\n }\n const {values: vars} = await params.secrets.getVariablesByNamespace({\n workspaceId: params.workspaceId,\n projectId: params.projectId,\n namespace: '',\n });\n const missingKey = [...requiredKeys].find((key) => !(key in vars));\n if (missingKey !== undefined) {\n const reference = requiredReferences.find((candidate) => candidate.key === missingKey);\n throw new InterpolationUnresolvableError(params.definitionId, {\n field: reference?.field ?? 'env',\n source: reference?.source ?? `vars.${missingKey}`,\n ...(reference?.envKey === undefined ? {} : {envKey: reference.envKey}),\n });\n }\n\n const referencedVars: Record<string, string> = {};\n for (const key of keys) {\n const value = vars[key];\n if (value !== undefined) referencedVars[key] = value;\n }\n return referencedVars;\n}\n\nfunction materializeRunGraphJobs(params: {\n readonly params: CreateWorkflowRunParams;\n readonly run: WorkflowRun;\n readonly vars: Record<string, string> | undefined;\n readonly materializedJobs: readonly MaterializedWorkflowJob[];\n}): readonly MaterializedRunGraphJob[] {\n return params.materializedJobs.map((job, jobIndex) => ({\n job: {\n key: job.key,\n mode: job.mode,\n name: job.name ?? null,\n status: 'pending' as const,\n checkoutPersistCredentials: job.checkout.persistCredentials,\n checkoutPermissionsContents: job.checkout.permissions.contents,\n success: job.success ?? null,\n executionTimeoutMs: job.executionTimeoutMs ?? null,\n listeningTimeoutMs: job.listening?.timeoutMs ?? null,\n maxExecutions: job.listening?.maxExecutions ?? null,\n onResolve: job.listening?.onResolve ?? null,\n batchDebounceMs: job.listening?.batch?.debounceMs ?? null,\n batchMaxSize: job.listening?.batch?.maxSize ?? null,\n batchMaxWaitMs: job.listening?.batch?.maxWaitMs ?? null,\n listeningOn: job.listening?.on ? [...job.listening.on] : null,\n listeningUntil: job.listening?.until ? [...job.listening.until] : null,\n dependencies: [...job.dependencies],\n runner: job.runner.length === 0 ? null : [...job.runner],\n position: job.position,\n },\n createExecution: (jobRow) => {\n if (jobRow.mode === 'listening') return undefined;\n\n const fallbackName = jobRow.name ?? jobRow.key;\n const modelJob = params.params.model.jobs[jobIndex];\n if (!modelJob) return undefined;\n const executionPlan = deriveInitialJobExecutionPlan({\n run: params.run,\n modelJob,\n job,\n jobId: jobRow.id,\n sequence: 1,\n fallbackName,\n triggerPayload: params.params.triggerPayload,\n inputs: params.params.inputs ?? null,\n vars: params.vars,\n });\n\n return {\n sequence: 1,\n // Persist only the resolved override. The core entity supplies the\n // static job name/key when this is null.\n name: executionPlan.nameOverride,\n runner: [...executionPlan.runner],\n status: 'pending' as const,\n evaluationTrace:\n executionPlan.evaluationTrace?.length === 0 ? null : executionPlan.evaluationTrace,\n };\n },\n createSteps: () =>\n job.steps.map((step) => ({\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 condition: step.condition ?? null,\n configPlan: step.configPlan ?? null,\n authoredConfig: step.authoredConfig,\n position: step.position,\n })),\n }));\n}\n\nfunction referencedVariables(\n model: WorkflowModel,\n jobs: readonly WorkflowModelJob[],\n): readonly ReferencedVariable[] {\n const references: ReferencedVariable[] = [];\n\n for (const job of model.jobs) {\n collectPredicateVariableReferences(job.if, references);\n collectPredicateVariableReferences(job.success, references);\n\n for (const trigger of [...(job.listening?.on ?? []), ...(job.listening?.until ?? [])]) {\n collectPredicateVariableReferences(trigger.filter, references);\n }\n\n for (const step of job.steps) {\n collectPredicateVariableReferences(step.if, references);\n collectPredicateVariableReferences(step.gate?.success, references);\n }\n }\n\n collectFieldVariableReferences(model.runName, references, {field: 'workflow.run_name'});\n\n if (jobs.length > 0) {\n collectTemplateVariableReferences(model.templates?.env, references);\n }\n\n for (const job of jobs) {\n collectFieldVariableReferences(job.executionName, references, {field: 'job.execution_name'});\n for (const template of job.runnerTemplates ?? []) {\n collectFieldVariableReferences(template, references, {field: 'job.runner'});\n }\n collectTemplateVariableReferences(job.outputs, references, {field: 'job.outputs'});\n collectTemplateVariableReferences(job.templates?.env, references);\n\n for (const step of job.steps) {\n collectFieldVariableReferences(step.templates?.name, references, {field: 'step.name'});\n collectFieldVariableReferences(step.templates?.workingDirectory, references, {\n field: 'step.working_directory',\n });\n if (step.kind === 'run') {\n collectFieldVariableReferences(step.templates?.command, references, {field: 'run'});\n collectTemplateVariableReferences(step.templates?.env, references);\n } else if (step.kind === 'agent') {\n collectFieldVariableReferences(step.templates?.prompt, references, {field: 'agent.prompt'});\n collectFieldVariableReferences(step.templates?.model, references, {field: 'agent.model'});\n collectFieldVariableReferences(step.templates?.provider, references, {\n field: 'agent.provider',\n });\n } else if (step.kind === 'checkout') {\n for (const [key, field] of WORKFLOW_MODEL_CHECKOUT_TARGET_FIELDS) {\n collectFieldVariableReferences(step.checkout.templates?.[key], references, {field});\n }\n }\n }\n }\n\n return references;\n}\n\nfunction collectPredicateVariableReferences(\n expression: WorkflowExpression | string | undefined,\n references: ReferencedVariable[],\n): void {\n if (expression === undefined) return;\n\n const keyAccess = analyzeContextKeyAccess(expression);\n for (const reference of keyAccess.references) {\n if (reference.root !== 'vars') continue;\n references.push({\n key: reference.key,\n field: 'env',\n source: typeof expression === 'string' ? expression : expression.source,\n });\n }\n}\n\nfunction collectTemplateVariableReferences(\n templates: Readonly<Record<string, readonly ResolvedFieldSegment[]>> | undefined,\n references: ReferencedVariable[],\n source?: {\n readonly field: InterpolationUnresolvableError['field'];\n },\n): void {\n for (const [envKey, template] of Object.entries(templates ?? {})) {\n collectFieldVariableReferences(\n template,\n references,\n source === undefined ? {field: 'env', envKey} : source,\n );\n }\n}\n\nfunction collectFieldVariableReferences(\n template: readonly ResolvedFieldSegment[] | undefined,\n references: ReferencedVariable[],\n source: {\n readonly field: InterpolationUnresolvableError['field'];\n readonly envKey?: string | undefined;\n },\n): void {\n for (const segment of template ?? []) {\n if (segment.kind === 'literal') continue;\n const keyAccess = analyzeContextKeyAccess(segment.expression);\n for (const reference of keyAccess.references) {\n if (reference.root !== 'vars') continue;\n references.push({\n key: reference.key,\n field: source.field,\n source: segment.expression.source,\n envKey: source.envKey,\n });\n }\n }\n}\n\nfunction logTemplateDiagnostics(params: {\n readonly workflowRunId: string;\n readonly diagnostics: readonly (WorkflowStepTemplateDiagnostic & {\n readonly jobKey: string;\n readonly stepName: string;\n })[];\n}): void {\n if (params.diagnostics.length === 0) return;\n\n logger().warn(\n {workflowRunId: params.workflowRunId, diagnostics: params.diagnostics},\n 'Workflow interpolation resolved with diagnostics',\n );\n}\n"],"names":["createWorkflowModelSnapshot","WORKFLOW_MODEL_CHECKOUT_TARGET_FIELDS","analyzeContextKeyAccess","logger","eq","sql","createAgentToolMaterializationSnapshot","loadAgentToolMaterializationContext","InterpolationUnresolvableError","resolveWorkflowRunTriggerReference","assembleCreationContext","resolveWorkflowRunName","deriveInitialJobExecutionPlan","materializeWorkflowRunJobs","recordWorkflowDisplayNameResolutionDegraded","recordWorkflowRunCreated","db","workflowRunAttempts","workflowRunCounters","toWorkflowRun","workflowRuns","persistMaterializedRunGraph","createWorkflowRun","params","triggerReference","workspaceId","triggerConnectionId","triggerPayload","integrations","projects","staticName","name","model","agentToolContext","undefined","projectId","agentToolMaterialization","context","result","transaction","tx","triggerIdempotencyKey","execute","existing","select","from","where","limit","existingRow","run","created","number","allocateWorkflowRunNumber","definitionId","insertResult","insert","values","workflowName","status","currentAttempt","triggerProvider","provider","triggerSource","source","triggerEvent","event","inputs","sourceSnapshot","origin","devSource","toWorkflowRunDevSourceDb","onConflictDoNothing","target","returning","runRow","Error","provisionalRun","oneShotJobs","jobs","filter","job","mode","vars","loadReferencedVariables","secrets","runNameResolution","runName","resolvedRunRow","update","set","value","updatedAt","Date","id","attemptRow","workflowRunId","attempt","materializedJobs","resolveAgentDefaults","agentToolSnapshot","graphJobs","materializeRunGraphJobs","workflowRunAttempt","logTemplateDiagnostics","diagnostics","flatMap","steps","step","map","diagnostic","jobKey","key","stepName","nameDegradation","degradation","cause","warn","field","expression","slice","counterRow","nextNumber","onConflictDoUpdate","ref","commit","config_path","configPath","initiated_by_user_id","initiatedByUserId","replay_of_event_id","replayOfEventId","references","referencedVariables","keys","Set","reference","sort","length","requiresSecrets","requiredReferences","requiredKeys","size","getVariablesByNamespace","namespace","missingKey","find","candidate","envKey","referencedVars","jobIndex","checkoutPersistCredentials","checkout","persistCredentials","checkoutPermissionsContents","permissions","contents","success","executionTimeoutMs","listeningTimeoutMs","listening","timeoutMs","maxExecutions","onResolve","batchDebounceMs","batch","debounceMs","batchMaxSize","maxSize","batchMaxWaitMs","maxWaitMs","listeningOn","on","listeningUntil","until","dependencies","runner","position","createExecution","jobRow","fallbackName","modelJob","executionPlan","jobId","sequence","nameOverride","evaluationTrace","createSteps","sourceLocation","type","config","condition","configPlan","authoredConfig","collectPredicateVariableReferences","if","trigger","gate","collectFieldVariableReferences","collectTemplateVariableReferences","templates","env","executionName","template","runnerTemplates","outputs","workingDirectory","kind","command","prompt","keyAccess","root","push","Object","entries","segment"],"mappings":"AAAA,SACEA,2BAA2B,EAC3BC,qCAAqC,QAEhC,+BAA+B;AAItC,SACEC,uBAAuB,QAGlB,sBAAsB;AAC7B,SAAQC,MAAM,QAAO,8BAA8B;AACnD,SAAQC,EAAE,EAAEC,GAAG,QAAO,cAAc;AAEpC,SACEC,sCAAsC,EACtCC,mCAAmC,QAC9B,uBAAuB;AAQ9B,SAAQC,8BAA8B,QAAO,kBAAkB;AAC/D,SAAQC,kCAAkC,QAAO,qCAAqC;AACtF,SAAQC,uBAAuB,QAAO,4CAA4C;AAGlF,SAAQC,s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BAAmC,GACxC,sBAAsB,CAiBxB;AAgBD,wBAAgB,eAAe,CAAC,OAAO,EAAE,kBAAkB,GAAG,qBAAqB,CAWlF"}
1
+ {"version":3,"file":"workflow-run.d.ts","sourceRoot":"","sources":["../../../src/presentation/dto/workflow-run.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,qBAAqB,EAErB,cAAc,EACd,sBAAsB,EAEvB,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EACV,WAAW,EAGZ,MAAM,gCAAgC,CAAC;AACxC,OAAO,KAAK,EAAC,kBAAkB,EAAC,MAAM,wCAAwC,CAAC;AAC/E,OAAO,KAAK,EAAC,sBAAsB,EAAC,MAAM,cAAc,CAAC;AAEzD,wBAAgB,QAAQ,CAAC,GAAG,EAAE,WAAW,EAAE,aAAa,SAAqB,GAAG,cAAc,CAyB7F;AASD,wBAAgB,gBAAgB,CAC9B,GAAG,EAAE,WAAW,EAChB,IAAI,GAAE,sBAAmC,GACxC,sBAAsB,CAiBxB;AA+BD,wBAAgB,eAAe,CAAC,OAAO,EAAE,kBAAkB,GAAG,qBAAqB,CAWlF"}
@@ -7,6 +7,8 @@ export function toRunDto(run, latestAttempt = run.currentAttempt) {
7
7
  name: run.name,
8
8
  workflow_name: run.workflowName,
9
9
  status: run.status,
10
+ origin: run.origin,
11
+ dev_source: toDevSourceDto(run.devSource),
10
12
  current_attempt: run.currentAttempt,
11
13
  latest_attempt: latestAttempt,
12
14
  trigger_provider: run.triggerProvider,
@@ -63,6 +65,18 @@ function toTriggerReferenceDto(reference) {
63
65
  actor: reference.actor ?? null
64
66
  };
65
67
  }
68
+ // The persisted dev source uses camelCase field names while the API contract is snake_case,
69
+ // so each field is mapped explicitly rather than spread onto the response.
70
+ function toDevSourceDto(devSource) {
71
+ if (!devSource) return null;
72
+ return {
73
+ ref: devSource.ref,
74
+ commit: devSource.commit,
75
+ config_path: devSource.configPath,
76
+ initiated_by_user_id: devSource.initiatedByUserId,
77
+ replay_of_event_id: devSource.replayOfEventId
78
+ };
79
+ }
66
80
  export function toRunAttemptDto(attempt) {
67
81
  return {
68
82
  id: attempt.id,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/presentation/dto/workflow-run.ts"],"sourcesContent":["import type {\n WorkflowRunAttemptDto,\n WorkflowRunDto,\n WorkflowRunListItemDto,\n WorkflowRunTriggerReferenceDto,\n} from '@shipfox/api-workflows-dto';\nimport type {WorkflowRun, WorkflowRunTriggerReference} from '#core/entities/workflow-run.js';\nimport type {WorkflowRunAttempt} from '#core/entities/workflow-run-attempt.js';\nimport type {WorkflowRunJobsSummary} from '#db/index.js';\n\nexport function toRunDto(run: WorkflowRun, latestAttempt = run.currentAttempt): WorkflowRunDto {\n return {\n id: run.id,\n project_id: run.projectId,\n definition_id: run.definitionId,\n number: run.number,\n name: run.name,\n workflow_name: run.workflowName,\n status: run.status,\n current_attempt: run.currentAttempt,\n latest_attempt: latestAttempt,\n trigger_provider: run.triggerProvider,\n trigger_source: run.triggerSource,\n trigger_event: run.triggerEvent,\n trigger_payload: run.triggerPayload,\n trigger_reference: toTriggerReferenceDto(run.triggerReference),\n inputs: run.inputs,\n source_snapshot: run.sourceSnapshot,\n created_at: run.createdAt.toISOString(),\n updated_at: run.updatedAt.toISOString(),\n started_at: run.startedAt?.toISOString() ?? null,\n finished_at: run.finishedAt?.toISOString() ?? null,\n };\n}\n\nconst EMPTY_JOBS: WorkflowRunJobsSummary = {\n preview: [],\n statusCounts: [],\n rawStatusCounts: [],\n hasStartedJobExecution: false,\n};\n\nexport function toRunListItemDto(\n run: WorkflowRun,\n jobs: WorkflowRunJobsSummary = EMPTY_JOBS,\n): WorkflowRunListItemDto {\n return {\n ...toRunDto(run),\n jobs: jobs.preview.map((job) => ({\n id: job.id,\n key: job.key,\n name: job.name,\n status: job.status,\n mode: job.mode,\n listener_status: job.listenerStatus,\n execution_status: job.executionStatus,\n position: job.position,\n })),\n job_status_counts: jobs.rawStatusCounts.map(({status, count}) => ({status, count})),\n job_display_status_counts: jobs.statusCounts.map(({status, count}) => ({status, count})),\n has_started_job_execution: jobs.hasStartedJobExecution,\n };\n}\n\n// The persisted reference predates `actor` and carries an internal project id the client has\n// no use for, so each field is read defensively rather than spread onto the response.\nfunction toTriggerReferenceDto(\n reference: WorkflowRunTriggerReference | null | undefined,\n): WorkflowRunTriggerReferenceDto | null {\n if (!reference) return null;\n return {\n repository: reference.repository ?? null,\n ref: reference.ref ?? null,\n commit: reference.commit ?? null,\n actor: reference.actor ?? null,\n };\n}\n\nexport function toRunAttemptDto(attempt: WorkflowRunAttempt): WorkflowRunAttemptDto {\n return {\n id: attempt.id,\n workflow_run_id: attempt.workflowRunId,\n attempt: attempt.attempt,\n status: attempt.status,\n created_at: attempt.createdAt.toISOString(),\n started_at: attempt.startedAt?.toISOString() ?? null,\n finished_at: attempt.finishedAt?.toISOString() ?? null,\n rerun_mode: attempt.rerunMode,\n };\n}\n"],"names":["toRunDto","run","latestAttempt","currentAttempt","id","project_id","projectId","definition_id","definitionId","number","name","workflow_name","workflowName","status","current_attempt","latest_attempt","trigger_provider","triggerProvider","trigger_source","triggerSource","trigger_event","triggerEvent","trigger_payload","triggerPayload","trigger_reference","toTriggerReferenceDto","triggerReference","inputs","source_snapshot","sourceSnapshot","created_at","createdAt","toISOString","updated_at","updatedAt","started_at","startedAt","finished_at","finishedAt","EMPTY_JOBS","preview","statusCounts","rawStatusCounts","hasStartedJobExecution","toRunListItemDto","jobs","map","job","key","mode","listener_status","listenerStatus","execution_status","executionStatus","position","job_status_counts","count","job_display_status_counts","has_started_job_execution","reference","repository","ref","commit","actor","toRunAttemptDto","attempt","workflow_run_id","workflowRunId","rerun_mode","rerunMode"],"mappings":"AAUA,OAAO,SAASA,SAASC,GAAgB,EAAEC,gBAAgBD,IAAIE,cAAc;IAC3E,OAAO;QACLC,IAAIH,IAAIG,EAAE;QACVC,YAAYJ,IAAIK,SAAS;QACzBC,eAAeN,IAAIO,YAAY;QAC/BC,QAAQR,IAAIQ,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J,YAAY,CAACK,GAAG,CAAC,CAAC,EAACjC,MAAM,EAAE2C,KAAK,EAAC,GAAM,CAAA;gBAAC3C;gBAAQ2C;YAAK,CAAA;QACrFE,2BAA2Bb,KAAKF,sBAAsB;IACxD;AACF;AAEA,6FAA6F;AAC7F,sFAAsF;AACtF,SAASlB,sBACPkC,SAAyD;IAEzD,IAAI,CAACA,WAAW,OAAO;IACvB,OAAO;QACLC,YAAYD,UAAUC,UAAU,IAAI;QACpCC,KAAKF,UAAUE,GAAG,IAAI;QACtBC,QAAQH,UAAUG,MAAM,IAAI;QAC5BC,OAAOJ,UAAUI,KAAK,IAAI;IAC5B;AACF;AAEA,OAAO,SAASC,gBAAgBC,OAA2B;IACzD,OAAO;QACL7D,IAAI6D,QAAQ7D,EAAE;QACd8D,iBAAiBD,QAAQE,aAAa;QACtCF,SAASA,QAAQA,OAAO;QACxBpD,QAAQoD,QAAQpD,MAAM;QACtBiB,YAAYmC,QAAQlC,SAAS,CAACC,WAAW;QACzCG,YAAY8B,QAAQ7B,SAAS,EAAEJ,iBAAiB;QAChDK,aAAa4B,QAAQ3B,UAAU,EAAEN,iBAAiB;QAClDoC,YAAYH,QAAQI,SAAS;IAC/B;AACF"}
1
+ {"version":3,"sources":["../../../src/presentation/dto/workflow-run.ts"],"sourcesContent":["import type {\n WorkflowRunAttemptDto,\n WorkflowRunDevSourceDto,\n WorkflowRunDto,\n WorkflowRunListItemDto,\n WorkflowRunTriggerReferenceDto,\n} from '@shipfox/api-workflows-dto';\nimport type {\n WorkflowRun,\n WorkflowRunDevSource,\n WorkflowRunTriggerReference,\n} from '#core/entities/workflow-run.js';\nimport type {WorkflowRunAttempt} from '#core/entities/workflow-run-attempt.js';\nimport type {WorkflowRunJobsSummary} from '#db/index.js';\n\nexport function toRunDto(run: WorkflowRun, latestAttempt = run.currentAttempt): WorkflowRunDto {\n return {\n id: run.id,\n project_id: run.projectId,\n definition_id: run.definitionId,\n number: run.number,\n name: run.name,\n workflow_name: run.workflowName,\n status: run.status,\n origin: run.origin,\n dev_source: toDevSourceDto(run.devSource),\n current_attempt: run.currentAttempt,\n latest_attempt: latestAttempt,\n trigger_provider: run.triggerProvider,\n trigger_source: run.triggerSource,\n trigger_event: run.triggerEvent,\n trigger_payload: run.triggerPayload,\n trigger_reference: toTriggerReferenceDto(run.triggerReference),\n inputs: run.inputs,\n source_snapshot: run.sourceSnapshot,\n created_at: run.createdAt.toISOString(),\n updated_at: run.updatedAt.toISOString(),\n started_at: run.startedAt?.toISOString() ?? null,\n finished_at: run.finishedAt?.toISOString() ?? null,\n };\n}\n\nconst EMPTY_JOBS: WorkflowRunJobsSummary = {\n preview: [],\n statusCounts: [],\n rawStatusCounts: [],\n hasStartedJobExecution: false,\n};\n\nexport function toRunListItemDto(\n run: WorkflowRun,\n jobs: WorkflowRunJobsSummary = EMPTY_JOBS,\n): WorkflowRunListItemDto {\n return {\n ...toRunDto(run),\n jobs: jobs.preview.map((job) => ({\n id: job.id,\n key: job.key,\n name: job.name,\n status: job.status,\n mode: job.mode,\n listener_status: job.listenerStatus,\n execution_status: job.executionStatus,\n position: job.position,\n })),\n job_status_counts: jobs.rawStatusCounts.map(({status, count}) => ({status, count})),\n job_display_status_counts: jobs.statusCounts.map(({status, count}) => ({status, count})),\n has_started_job_execution: jobs.hasStartedJobExecution,\n };\n}\n\n// The persisted reference predates `actor` and carries an internal project id the client has\n// no use for, so each field is read defensively rather than spread onto the response.\nfunction toTriggerReferenceDto(\n reference: WorkflowRunTriggerReference | null | undefined,\n): WorkflowRunTriggerReferenceDto | null {\n if (!reference) return null;\n return {\n repository: reference.repository ?? null,\n ref: reference.ref ?? null,\n commit: reference.commit ?? null,\n actor: reference.actor ?? null,\n };\n}\n\n// The persisted dev source uses camelCase field names while the API contract is snake_case,\n// so each field is mapped explicitly rather than spread onto the response.\nfunction toDevSourceDto(\n devSource: WorkflowRunDevSource | null | undefined,\n): WorkflowRunDevSourceDto | null {\n if (!devSource) return null;\n return {\n ref: devSource.ref,\n commit: devSource.commit,\n config_path: devSource.configPath,\n initiated_by_user_id: devSource.initiatedByUserId,\n replay_of_event_id: devSource.replayOfEventId,\n };\n}\n\nexport function toRunAttemptDto(attempt: WorkflowRunAttempt): WorkflowRunAttemptDto {\n return {\n id: attempt.id,\n workflow_run_id: attempt.workflowRunId,\n attempt: attempt.attempt,\n status: attempt.status,\n created_at: attempt.createdAt.toISOString(),\n started_at: attempt.startedAt?.toISOString() ?? null,\n finished_at: attempt.finishedAt?.toISOString() ?? null,\n rerun_mode: attempt.rerunMode,\n };\n}\n"],"names":["toRunDto","run","latestAttempt","currentAttempt","id","project_id","projectId","definition_id","definitionId","number","name","workflow_name","workflowName","status","origin","dev_source","toDevSourceDto","devSource","current_attempt","latest_attempt","trigger_provider","triggerProvider","trigger_source","triggerSource","trigger_event","triggerEvent","trigger_payload","triggerPayload","trigger_reference","toTriggerReferenceDto","triggerReference","inputs","source_snapshot","sourceSnapshot","created_at","createdAt","toISOString","updated_at","updatedAt","started_at","startedAt","finished_at","finishedAt","EMPTY_JOBS","preview","statusCounts","rawStatusCounts","hasStartedJobExecution","toRunListItemDto","jobs","map","job","key","mode","listener_status","listenerStatus","execution_status","executionStatus","position","job_status_counts","count","job_display_status_counts","has_started_job_execution","reference","repository","ref","commit","actor","config_path","configPath","initiated_by_user_id","initiatedByUserId","replay_of_event_id","replayOfEventId","toRunAttemptDto","attempt","workflow_run_id","workflowRunId","rerun_mode","rerunMode"],"mappings":"AAeA,OAAO,SAASA,SAASC,GAAgB,EAAEC,gBAAgBD,IAAIE,cAAc;IAC3E,OAAO;QACLC,IAAIH,IAAIG,EAAE;QACVC,YAAYJ,IAAIK,SAAS;QACzBC,eAAeN,IAAIO,YAAY;QAC/BC,QAAQR,IAAIQ,MAAM;QAClBC,MAAMT,IAAIS,IAAI;QACdC,eAAeV,IAAIW,YAAY;QAC/BC,QAAQZ,IAAIY,MAAM;QAClBC,QAAQb,IAAIa,MAAM;QAClBC,YAAYC,eAAef,IAAIgB,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AA;gBAAC/C;gBAAQ+C;YAAK,CAAA;QACrFE,2BAA2Bb,KAAKF,sBAAsB;IACxD;AACF;AAEA,6FAA6F;AAC7F,sFAAsF;AACtF,SAASlB,sBACPkC,SAAyD;IAEzD,IAAI,CAACA,WAAW,OAAO;IACvB,OAAO;QACLC,YAAYD,UAAUC,UAAU,IAAI;QACpCC,KAAKF,UAAUE,GAAG,IAAI;QACtBC,QAAQH,UAAUG,MAAM,IAAI;QAC5BC,OAAOJ,UAAUI,KAAK,IAAI;IAC5B;AACF;AAEA,4FAA4F;AAC5F,2EAA2E;AAC3E,SAASnD,eACPC,SAAkD;IAElD,IAAI,CAACA,WAAW,OAAO;IACvB,OAAO;QACLgD,KAAKhD,UAAUgD,GAAG;QAClBC,QAAQjD,UAAUiD,MAAM;QACxBE,aAAanD,UAAUoD,UAAU;QACjCC,sBAAsBrD,UAAUsD,iBAAiB;QACjDC,oBAAoBvD,UAAUwD,eAAe;IAC/C;AACF;AAEA,OAAO,SAASC,gBAAgBC,OAA2B;IACzD,OAAO;QACLvE,IAAIuE,QAAQvE,EAAE;QACdwE,iBAAiBD,QAAQE,aAAa;QACtCF,SAASA,QAAQA,OAAO;QACxB9D,QAAQ8D,QAAQ9D,MAAM;QACtBqB,YAAYyC,QAAQxC,SAAS,CAACC,WAAW;QACzCG,YAAYoC,QAAQnC,SAAS,EAAEJ,iBAAiB;QAChDK,aAAakC,QAAQjC,UAAU,EAAEN,iBAAiB;QAClD0C,YAAYH,QAAQI,SAAS;IAC/B;AACF"}
@@ -17,4 +17,5 @@ export declare function createWorkflowsInterModulePresentation(params: {
17
17
  projects: ProjectsModuleClient;
18
18
  }): InterModulePresentation<typeof workflowsInterModuleContract>;
19
19
  export declare function toStartRunKnownError(error: unknown, definitionId: string): unknown;
20
+ export declare function toStartDevRunKnownError(error: unknown): unknown;
20
21
  //# sourceMappingURL=inter-module.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"inter-module.d.ts","sourceRoot":"","sources":["../../src/presentation/inter-module.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,sBAAsB,EAAC,MAAM,qCAAqC,CAAC;AAChF,OAAO,KAAK,EAAC,4BAA4B,EAAC,MAAM,2CAA2C,CAAC;AAC5F,OAAO,KAAK,EAAC,wBAAwB,EAAC,MAAM,gDAAgD,CAAC;AAC7F,OAAO,KAAK,EAAC,oBAAoB,EAAC,MAAM,wCAAwC,CAAC;AACjF,OAAO,KAAK,EAAC,wBAAwB,EAAC,MAAM,uCAAuC,CAAC;AACpF,OAAO,KAAK,EAAC,wBAAwB,EAAC,MAAM,uCAAuC,CAAC;AACpF,OAAO,EAAC,4BAA4B,EAAC,MAAM,yCAAyC,CAAC;AACrF,OAAO,KAAK,EAAC,2BAA2B,EAAC,MAAM,0CAA0C,CAAC;AAC1F,OAAO,EAIL,KAAK,uBAAuB,EAC7B,MAAM,uBAAuB,CAAC;AA0B/B,wBAAgB,sCAAsC,CAAC,MAAM,EAAE;IAC7D,KAAK,EAAE,sBAAsB,CAAC;IAC9B,WAAW,EAAE,4BAA4B,CAAC;IAC1C,UAAU,EAAE,2BAA2B,CAAC;IACxC,OAAO,EAAE,IAAI,CAAC,wBAAwB,EAAE,yBAAyB,CAAC,CAAC;IACnE,OAAO,EAAE,wBAAwB,CAAC;IAClC,YAAY,EAAE,wBAAwB,CAAC;IACvC,QAAQ,EAAE,oBAAoB,CAAC;CAChC,GAAG,uBAAuB,CAAC,OAAO,4BAA4B,CAAC,CA4G/D;AAED,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,GAAG,OAAO,CAgClF"}
1
+ {"version":3,"file":"inter-module.d.ts","sourceRoot":"","sources":["../../src/presentation/inter-module.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAC,sBAAsB,EAAC,MAAM,qCAAqC,CAAC;AAChF,OAAO,KAAK,EAAC,4BAA4B,EAAC,MAAM,2CAA2C,CAAC;AAC5F,OAAO,KAAK,EAA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