@jive-sh/workflow-platform 0.6.3 → 1.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 (174) hide show
  1. package/README.md +66 -295
  2. package/component/_generated/api.ts +72 -0
  3. package/component/_generated/component.ts +621 -0
  4. package/component/_generated/dataModel.ts +60 -0
  5. package/component/_generated/server.ts +169 -0
  6. package/component/convex.config.ts +3 -0
  7. package/component/engine.ts +755 -0
  8. package/component/errors.ts +66 -0
  9. package/component/events.ts +17 -0
  10. package/component/notes.ts +13 -0
  11. package/component/places.ts +136 -0
  12. package/component/retention.ts +205 -0
  13. package/component/runEngine.ts +25 -0
  14. package/component/schema.ts +132 -0
  15. package/component/steps.ts +188 -0
  16. package/component/store.ts +512 -0
  17. package/component/tasks.ts +289 -0
  18. package/component/worker.ts +109 -0
  19. package/component/workflows.ts +83 -0
  20. package/dist/definition/agent-runner.js +9 -0
  21. package/dist/definition/agent-runner.js.map +1 -0
  22. package/dist/definition/file-store.js +9 -0
  23. package/dist/definition/file-store.js.map +1 -0
  24. package/dist/definition/program-build.js +10 -0
  25. package/dist/definition/program-build.js.map +1 -0
  26. package/dist/definition/step.js +1 -0
  27. package/dist/definition/step.js.map +1 -0
  28. package/dist/definition/task-schema.js +5 -0
  29. package/dist/definition/task-schema.js.map +1 -0
  30. package/dist/definition/tasks.js +9 -0
  31. package/dist/definition/tasks.js.map +1 -0
  32. package/dist/definition/workflow.js +111 -0
  33. package/dist/definition/workflow.js.map +1 -0
  34. package/dist/graph.js +301 -9
  35. package/dist/graph.js.map +1 -1
  36. package/dist/index.js +7 -133
  37. package/dist/index.js.map +1 -1
  38. package/package.json +9 -4
  39. package/src/definition/agent-runner.ts +59 -0
  40. package/src/definition/file-store.ts +20 -0
  41. package/src/definition/program-build.ts +30 -0
  42. package/src/definition/step.ts +106 -0
  43. package/src/definition/task-schema.ts +15 -0
  44. package/src/definition/tasks.ts +43 -0
  45. package/src/definition/workflow.ts +255 -0
  46. package/src/graph.ts +341 -19
  47. package/src/index.ts +8 -168
  48. package/worker/directory-file-store.ts +42 -0
  49. package/worker/index.ts +12 -0
  50. package/worker/platform-client.ts +138 -0
  51. package/worker/step-meter.ts +80 -0
  52. package/worker/worker-tasks.ts +27 -0
  53. package/worker/worker.test.ts +200 -0
  54. package/worker/worker.ts +240 -0
  55. package/dist/budget-states.js +0 -30
  56. package/dist/budget-states.js.map +0 -1
  57. package/dist/cpu-limit/limiter.js +0 -839
  58. package/dist/cpu-limit/limiter.js.map +0 -1
  59. package/dist/cpu-limit/use.js +0 -139
  60. package/dist/cpu-limit/use.js.map +0 -1
  61. package/dist/dashboard/agent-usage.js +0 -25
  62. package/dist/dashboard/agent-usage.js.map +0 -1
  63. package/dist/dashboard/dashboard.css +0 -134
  64. package/dist/dashboard/drilldown.js +0 -16
  65. package/dist/dashboard/drilldown.js.map +0 -1
  66. package/dist/dashboard/queue-lines.js +0 -44
  67. package/dist/dashboard/queue-lines.js.map +0 -1
  68. package/dist/dashboard/queue-table.js +0 -16
  69. package/dist/dashboard/queue-table.js.map +0 -1
  70. package/dist/dashboard/spending-words.js +0 -32
  71. package/dist/dashboard/spending-words.js.map +0 -1
  72. package/dist/failure.js +0 -35
  73. package/dist/failure.js.map +0 -1
  74. package/dist/keep-running.js +0 -77
  75. package/dist/keep-running.js.map +0 -1
  76. package/dist/outside-failure.js +0 -31
  77. package/dist/outside-failure.js.map +0 -1
  78. package/dist/pick-wakes.js +0 -125
  79. package/dist/pick-wakes.js.map +0 -1
  80. package/dist/project.js +0 -1
  81. package/dist/project.js.map +0 -1
  82. package/dist/queue-counts.js +0 -51
  83. package/dist/queue-counts.js.map +0 -1
  84. package/dist/reasons.js +0 -33
  85. package/dist/reasons.js.map +0 -1
  86. package/dist/spending-limit.js +0 -88
  87. package/dist/spending-limit.js.map +0 -1
  88. package/dist/step-files.js +0 -200
  89. package/dist/step-files.js.map +0 -1
  90. package/dist/step-meter.js +0 -97
  91. package/dist/step-meter.js.map +0 -1
  92. package/dist/step-usage.js +0 -19
  93. package/dist/step-usage.js.map +0 -1
  94. package/dist/steps.js +0 -920
  95. package/dist/steps.js.map +0 -1
  96. package/dist/storage/budgets.js +0 -85
  97. package/dist/storage/budgets.js.map +0 -1
  98. package/dist/storage/engine-records.js +0 -75
  99. package/dist/storage/engine-records.js.map +0 -1
  100. package/dist/storage/engine-storage.js +0 -67
  101. package/dist/storage/engine-storage.js.map +0 -1
  102. package/dist/storage/input-records.js +0 -12
  103. package/dist/storage/input-records.js.map +0 -1
  104. package/dist/storage/move-store.js +0 -251
  105. package/dist/storage/move-store.js.map +0 -1
  106. package/dist/storage/sqlite-store.js +0 -723
  107. package/dist/storage/sqlite-store.js.map +0 -1
  108. package/dist/storage/step-records.js +0 -11
  109. package/dist/storage/step-records.js.map +0 -1
  110. package/dist/storage/storage-error.js +0 -19
  111. package/dist/storage/storage-error.js.map +0 -1
  112. package/dist/storage/task-store.js +0 -24
  113. package/dist/storage/task-store.js.map +0 -1
  114. package/dist/tasks.js +0 -475
  115. package/dist/tasks.js.map +0 -1
  116. package/dist/views/format.js +0 -37
  117. package/dist/views/format.js.map +0 -1
  118. package/dist/views/runs-now.js +0 -75
  119. package/dist/views/runs-now.js.map +0 -1
  120. package/dist/views/step-funnel.js +0 -98
  121. package/dist/views/step-funnel.js.map +0 -1
  122. package/dist/views/step-graph.js +0 -34
  123. package/dist/views/step-graph.js.map +0 -1
  124. package/dist/views/workflow-flows.js +0 -53
  125. package/dist/views/workflow-flows.js.map +0 -1
  126. package/dist/views/workflows-view.js +0 -230
  127. package/dist/views/workflows-view.js.map +0 -1
  128. package/src/budget-states.ts +0 -55
  129. package/src/cpu-limit/limiter.ts +0 -935
  130. package/src/cpu-limit/use.ts +0 -166
  131. package/src/dashboard/agent-usage-line.tsx +0 -28
  132. package/src/dashboard/agent-usage.ts +0 -48
  133. package/src/dashboard/dashboard.css +0 -134
  134. package/src/dashboard/drilldown.ts +0 -43
  135. package/src/dashboard/index.tsx +0 -4
  136. package/src/dashboard/machine-controls.tsx +0 -53
  137. package/src/dashboard/queue-bar.tsx +0 -43
  138. package/src/dashboard/queue-chart.tsx +0 -150
  139. package/src/dashboard/queue-lines.ts +0 -87
  140. package/src/dashboard/queue-table.ts +0 -37
  141. package/src/dashboard/spending-limit-control.tsx +0 -50
  142. package/src/dashboard/spending-words.ts +0 -50
  143. package/src/dashboard/step-graph.tsx +0 -106
  144. package/src/dashboard/workflow-dag.tsx +0 -204
  145. package/src/dashboard/workflow-drilldown.tsx +0 -89
  146. package/src/dashboard/workflows-dashboard.tsx +0 -414
  147. package/src/failure.ts +0 -36
  148. package/src/keep-running.ts +0 -83
  149. package/src/outside-failure.ts +0 -39
  150. package/src/pick-wakes.ts +0 -182
  151. package/src/project.ts +0 -115
  152. package/src/queue-counts.ts +0 -64
  153. package/src/reasons.ts +0 -30
  154. package/src/spending-limit.ts +0 -156
  155. package/src/step-files.ts +0 -208
  156. package/src/step-meter.ts +0 -120
  157. package/src/step-usage.ts +0 -23
  158. package/src/steps.ts +0 -1239
  159. package/src/storage/budgets.ts +0 -113
  160. package/src/storage/engine-records.ts +0 -102
  161. package/src/storage/engine-storage.ts +0 -82
  162. package/src/storage/input-records.ts +0 -43
  163. package/src/storage/move-store.ts +0 -265
  164. package/src/storage/sqlite-store.ts +0 -829
  165. package/src/storage/step-records.ts +0 -306
  166. package/src/storage/storage-error.ts +0 -35
  167. package/src/storage/task-store.ts +0 -235
  168. package/src/tasks.ts +0 -561
  169. package/src/views/format.ts +0 -40
  170. package/src/views/runs-now.ts +0 -120
  171. package/src/views/step-funnel.ts +0 -163
  172. package/src/views/step-graph.ts +0 -68
  173. package/src/views/workflow-flows.ts +0 -97
  174. package/src/views/workflows-view.ts +0 -443
@@ -0,0 +1,512 @@
1
+ import { Context, Effect, Option, pipe } from "effect"
2
+ import type { FunctionHandle } from "convex/server"
3
+ import {
4
+ type Budgets,
5
+ errorKept,
6
+ nothingUsed,
7
+ noSpend,
8
+ type ParentRef,
9
+ type SkippedOther,
10
+ type StepMeasurements,
11
+ type TaskFile,
12
+ type TaskNote,
13
+ versionOf,
14
+ type WorkflowGraph,
15
+ type WorkforceHooks,
16
+ } from "../src/graph"
17
+ import { internal } from "./_generated/api"
18
+ import { notesOf } from "./notes"
19
+
20
+ /** How often a registered workflow's retention pass runs (`retention.ts`). */
21
+ export const PRUNE_EVERY_MS = 24 * 60 * 60 * 1000
22
+ import type { Doc, Id, TableNames } from "./_generated/dataModel"
23
+ import type { MutationCtx } from "./_generated/server"
24
+
25
+ export type WorkflowRow = Doc<"workflows">
26
+ export type TaskRow = Doc<"tasks">
27
+ export type FlowRow = Doc<"flows">
28
+ export type StepRunRow = Doc<"stepRuns">
29
+ export type BudgetName = StepRunRow["budget"]
30
+ export type SubWorkflowTaskRow = Doc<"subWorkflowTasks">
31
+
32
+ /**
33
+ * The component's tables, as the state transitions the engine makes. The one place Convex's promise API is
34
+ * crossed; everything above it is Effect.
35
+ */
36
+ export interface IWorkflowStore {
37
+ readonly now: number
38
+ getWorkflow(name: string): Effect.fn.Return<Option.Option<WorkflowRow>>
39
+ insertWorkflow(input: { readonly graph: WorkflowGraph; readonly hooks: Option.Option<WorkforceHooks> }): Effect.fn.Return<WorkflowRow>
40
+ replaceGraph(input: { readonly workflow: WorkflowRow; readonly graph: WorkflowGraph; readonly hooks: Option.Option<WorkforceHooks> }): Effect.fn.Return<WorkflowRow>
41
+ setBudgets(input: { readonly workflow: WorkflowRow; readonly budgets: Budgets }): Effect.fn.Return<void>
42
+ startTimers(input: { readonly workflow: WorkflowRow }): Effect.fn.Return<void>
43
+ /** Schedules a timer's next tick in its workflow's current generation, writing nothing, so a tick never contends with a call on its workflow. */
44
+ rescheduleTimer(input: { readonly workflow: WorkflowRow; readonly event: string; readonly everyMs: number }): Effect.fn.Return<void>
45
+
46
+ getTask(id: Id<"tasks">): Effect.fn.Return<Option.Option<TaskRow>>
47
+ insertTask(input: {
48
+ readonly workflow: string
49
+ readonly fields: unknown
50
+ readonly files: ReadonlyArray<TaskFile>
51
+ readonly parent: Option.Option<ParentRef>
52
+ readonly listedAs: Option.Option<{ readonly event: string; readonly key: string }>
53
+ }): Effect.fn.Return<TaskRow>
54
+ /** Marks a list task whose item left the list after it ended, or clears the mark when its item comes back. */
55
+ setLeftWhileEnded(input: { readonly task: Id<"tasks">; readonly left: boolean }): Effect.fn.Return<void>
56
+ /** Every task a list event made, whatever became of it. */
57
+ listedTasksOf(input: { readonly workflow: string; readonly event: string }): Effect.fn.Return<ReadonlyArray<TaskRow>>
58
+ setTaskData(input: { readonly task: Id<"tasks">; readonly fields: unknown; readonly files: ReadonlyArray<TaskFile> }): Effect.fn.Return<void>
59
+ markTaskEnded(input: { readonly task: Id<"tasks">; readonly endState: string }): Effect.fn.Return<void>
60
+ /** The task left the end state it had ended in: a change event resumed it. */
61
+ markTaskResumed(task: Id<"tasks">): Effect.fn.Return<void>
62
+ insertSubWorkflowTask(input: { readonly flow: Id<"flows">; readonly entryIndex: number; readonly workflow: string }): Effect.fn.Return<void>
63
+ setSubWorkflowTask(input: { readonly flow: Id<"flows">; readonly entryIndex: number; readonly task: string }): Effect.fn.Return<void>
64
+ markSubWorkflowTaskEnded(input: { readonly flow: Id<"flows">; readonly entryIndex: number; readonly endState: string }): Effect.fn.Return<void>
65
+ subWorkflowTasksOf(flow: Id<"flows">): Effect.fn.Return<ReadonlyArray<SubWorkflowTaskRow>>
66
+ /** Forgets the sub-workflow tasks a flow waited on, once it leaves their step, so its next sub-workflow step starts with none. */
67
+ clearSubWorkflowTasks(flow: Id<"flows">): Effect.fn.Return<void>
68
+ /** Runs a workforce hook right after this transaction commits, so another workflow component is never entered mid-transaction. */
69
+ scheduleHook(input: { readonly hook: string; readonly args: Record<string, unknown> }): Effect.fn.Return<void>
70
+
71
+ insertFlow(input: { readonly workflow: string; readonly task: Id<"tasks">; readonly startedBy: string; readonly place: string }): Effect.fn.Return<FlowRow>
72
+ getFlow(id: Id<"flows">): Effect.fn.Return<Option.Option<FlowRow>>
73
+ /** Moves a flow to a place. `notBefore` keeps workers from taking it until then; any other move clears it. */
74
+ moveFlow(input: { readonly flow: Id<"flows">; readonly place: string; readonly enteredAt: number; readonly notBefore?: number }): Effect.fn.Return<FlowRow>
75
+ headOf(input: { readonly workflow: string; readonly place: string }): Effect.fn.Return<Option.Option<FlowRow>>
76
+ /** The first `upTo` flows waiting at a place that a worker may take now, oldest first. */
77
+ headsOf(input: { readonly workflow: string; readonly place: string; readonly upTo: number }): Effect.fn.Return<ReadonlyArray<FlowRow>>
78
+ /** The flow that has waited longest at a place, whatever its retry delay. */
79
+ firstAt(input: { readonly workflow: string; readonly place: string }): Effect.fn.Return<Option.Option<FlowRow>>
80
+ /** Every flow at a place. */
81
+ flowsAt(input: { readonly workflow: string; readonly place: string }): Effect.fn.Return<ReadonlyArray<FlowRow>>
82
+ flowsOfTaskStartedBy(input: { readonly task: Id<"tasks">; readonly startedBy: string }): Effect.fn.Return<ReadonlyArray<FlowRow>>
83
+ flowsOfTask(task: Id<"tasks">): Effect.fn.Return<ReadonlyArray<FlowRow>>
84
+ flowsOfWorkflow(workflow: string): Effect.fn.Return<ReadonlyArray<FlowRow>>
85
+
86
+ /** Counts running step runs up to `upTo`, so a full budget is known without reading every run. */
87
+ countRunning(input: { readonly workflow: string; readonly budget: BudgetName; readonly upTo: number }): Effect.fn.Return<number>
88
+ insertStepRun(input: {
89
+ readonly flow: FlowRow
90
+ readonly step: string
91
+ readonly version: string
92
+ readonly budget: BudgetName
93
+ readonly worker: Option.Option<string>
94
+ readonly leaseMs: Option.Option<number>
95
+ }): Effect.fn.Return<StepRunRow>
96
+ getStepRun(id: Id<"stepRuns">): Effect.fn.Return<Option.Option<StepRunRow>>
97
+ runningStepRunOf(flow: Id<"flows">): Effect.fn.Return<Option.Option<StepRunRow>>
98
+ /** Writes to other tasks the run made that were not applied, each with why. */
99
+ recordSkippedOthers(input: { readonly run: Id<"stepRuns">; readonly skipped: ReadonlyArray<SkippedOther> }): Effect.fn.Return<void>
100
+ finishStepRun(input: {
101
+ readonly run: Id<"stepRuns">
102
+ readonly status: "ended" | "failed"
103
+ readonly endState: Option.Option<string>
104
+ readonly error: Option.Option<string>
105
+ readonly measurements: Option.Option<StepMeasurements>
106
+ readonly note: Option.Option<string>
107
+ }): Effect.fn.Return<void>
108
+ extendLease(input: { readonly run: Id<"stepRuns">; readonly leaseMs: number }): Effect.fn.Return<void>
109
+ leaseExpiryOf(run: Id<"stepRuns">): Effect.fn.Return<Option.Option<number>>
110
+ scheduleLeaseCheck(input: { readonly run: Id<"stepRuns">; readonly at: number }): Effect.fn.Return<void>
111
+ stepRunsOfTask(task: Id<"tasks">): Effect.fn.Return<ReadonlyArray<StepRunRow>>
112
+ /** Keeps a note about a task that no step wrote, such as why a call sent it back. */
113
+ insertTaskNote(input: { readonly task: Id<"tasks">; readonly note: string }): Effect.fn.Return<void>
114
+ /** Everything said about a task, oldest first: its step runs' notes and the notes calls left. */
115
+ notesOfTask(task: TaskRow): Effect.fn.Return<ReadonlyArray<TaskNote>>
116
+ /**
117
+ * The inputs fingerprint an inputs gate settled last: the newest finished run of the step whose task ended in one of
118
+ * `settledBy`, across all its tasks.
119
+ */
120
+ lastFingerprintOf(input: { readonly workflow: string; readonly step: string; readonly settledBy: ReadonlyArray<string> }): Effect.fn.Return<Option.Option<string>>
121
+ /** Deletes a workflow with every task, flow and step record it has; its timer ticks stop when they find it gone. */
122
+ deleteWorkflow(workflow: WorkflowRow): Effect.fn.Return<void>
123
+ }
124
+
125
+ export class WorkflowStore extends Context.Service<WorkflowStore, IWorkflowStore>()("WorkflowStore") {}
126
+
127
+ export class ConvexWorkflowStore implements IWorkflowStore {
128
+ /** Convex fixes the clock for the whole mutation, so every place a task enters in it shares this time. */
129
+ readonly now = Date.now()
130
+
131
+ constructor(private readonly ctx: MutationCtx) {}
132
+
133
+ /** Reads back a row this transaction just wrote; its absence would be a Convex defect, not an expected error. */
134
+ private reload<Table extends TableNames>(id: Id<Table>, what: string) {
135
+ return pipe(
136
+ Effect.promise(() => this.ctx.db.get(id)),
137
+ Effect.flatMap((row) => (row === null ? Effect.die(new Error(`${what} ${id} vanished inside its own transaction`)) : Effect.succeed(row))),
138
+ )
139
+ }
140
+
141
+ *getWorkflow(name: string) {
142
+ const row = yield* Effect.promise(() => this.ctx.db.query("workflows").withIndex("by_name", (q) => q.eq("name", name)).unique())
143
+ return Option.fromNullishOr(row)
144
+ }
145
+
146
+ *insertWorkflow(input: { readonly graph: WorkflowGraph; readonly hooks: Option.Option<WorkforceHooks> }) {
147
+ const id = yield* Effect.promise(() =>
148
+ this.ctx.db.insert("workflows", {
149
+ name: input.graph.name,
150
+ graph: input.graph,
151
+ budgets: input.graph.budgets,
152
+ timerGeneration: 0,
153
+ version: versionOf(input.graph),
154
+ ...(Option.isSome(input.hooks) ? { hooks: input.hooks.value } : {}),
155
+ }),
156
+ )
157
+ return yield* this.reload(id, "workflow")
158
+ }
159
+
160
+ *replaceGraph(input: { readonly workflow: WorkflowRow; readonly graph: WorkflowGraph; readonly hooks: Option.Option<WorkforceHooks> }) {
161
+ const hooks = Option.getOrUndefined(input.hooks)
162
+ const version = versionOf(input.graph)
163
+ yield* Effect.promise(() => this.ctx.db.patch(input.workflow._id, { graph: input.graph, hooks, version }))
164
+ // A workflow registered outside a workforce keeps no hooks.
165
+ const { hooks: _replaced, ...rest } = input.workflow
166
+ const replaced: WorkflowRow = { ...rest, graph: input.graph, version, ...(hooks !== undefined ? { hooks } : {}) }
167
+ return replaced
168
+ }
169
+
170
+ *setBudgets(input: { readonly workflow: WorkflowRow; readonly budgets: Budgets }) {
171
+ yield* Effect.promise(() => this.ctx.db.patch(input.workflow._id, { budgets: input.budgets }))
172
+ }
173
+
174
+ *startTimers(input: { readonly workflow: WorkflowRow }) {
175
+ // A new generation: every tick still scheduled under the last one stops when it fires (`Engine.timerFired`).
176
+ const timerGeneration = this.now
177
+ for (const event of input.workflow.graph.events) {
178
+ if (event.kind !== "timer") continue
179
+ yield* Effect.promise(() =>
180
+ this.ctx.scheduler.runAfter(event.everyMs, internal.events.timerTick, { workflow: input.workflow.name, event: event.id, generation: timerGeneration }),
181
+ )
182
+ }
183
+ if (input.workflow.pruning !== undefined) yield* Effect.promise(() => this.ctx.scheduler.cancel(input.workflow.pruning!))
184
+ const pruning = yield* Effect.promise(() => this.ctx.scheduler.runAfter(PRUNE_EVERY_MS, internal.retention.scheduledPass, { workflow: input.workflow.name }))
185
+ yield* Effect.promise(() => this.ctx.db.patch(input.workflow._id, { timerGeneration, pruning }))
186
+ }
187
+
188
+ *rescheduleTimer(input: { readonly workflow: WorkflowRow; readonly event: string; readonly everyMs: number }) {
189
+ yield* Effect.promise(() =>
190
+ this.ctx.scheduler.runAfter(input.everyMs, internal.events.timerTick, { workflow: input.workflow.name, event: input.event, generation: input.workflow.timerGeneration }),
191
+ )
192
+ }
193
+
194
+ *getTask(id: Id<"tasks">) {
195
+ return Option.fromNullishOr(yield* Effect.promise(() => this.ctx.db.get(id)))
196
+ }
197
+
198
+ *insertTask(input: {
199
+ readonly workflow: string
200
+ readonly fields: unknown
201
+ readonly files: ReadonlyArray<TaskFile>
202
+ readonly parent: Option.Option<ParentRef>
203
+ readonly listedAs: Option.Option<{ readonly event: string; readonly key: string }>
204
+ }) {
205
+ const id = yield* Effect.promise(() =>
206
+ this.ctx.db.insert("tasks", {
207
+ workflow: input.workflow,
208
+ fields: input.fields,
209
+ files: [...input.files],
210
+ ...(Option.isSome(input.parent) ? { parent: input.parent.value } : {}),
211
+ ...(Option.isSome(input.listedAs) ? { listedAs: { ...input.listedAs.value } } : {}),
212
+ }),
213
+ )
214
+ return yield* this.reload(id, "task")
215
+ }
216
+
217
+ *setLeftWhileEnded(input: { readonly task: Id<"tasks">; readonly left: boolean }) {
218
+ const task = yield* Effect.promise(() => this.ctx.db.get(input.task))
219
+ if (task?.listedAs === undefined) return
220
+ yield* Effect.promise(() =>
221
+ this.ctx.db.patch(input.task, { listedAs: { event: task.listedAs!.event, key: task.listedAs!.key, ...(input.left ? { leftWhileEnded: true } : {}) } }),
222
+ )
223
+ }
224
+
225
+ *listedTasksOf(input: { readonly workflow: string; readonly event: string }) {
226
+ return yield* Effect.promise(() =>
227
+ this.ctx.db.query("tasks").withIndex("by_listed", (q) => q.eq("workflow", input.workflow).eq("listedAs.event", input.event)).collect(),
228
+ )
229
+ }
230
+
231
+ *setTaskData(input: { readonly task: Id<"tasks">; readonly fields: unknown; readonly files: ReadonlyArray<TaskFile> }) {
232
+ yield* Effect.promise(() => this.ctx.db.patch(input.task, { fields: input.fields, files: [...input.files] }))
233
+ }
234
+
235
+ *markTaskEnded(input: { readonly task: Id<"tasks">; readonly endState: string }) {
236
+ yield* Effect.promise(() => this.ctx.db.patch(input.task, { endedAs: input.endState }))
237
+ }
238
+
239
+ *markTaskResumed(task: Id<"tasks">) {
240
+ yield* Effect.promise(() => this.ctx.db.patch(task, { endedAs: undefined }))
241
+ }
242
+
243
+ *insertSubWorkflowTask(input: { readonly flow: Id<"flows">; readonly entryIndex: number; readonly workflow: string }) {
244
+ yield* Effect.promise(() => this.ctx.db.insert("subWorkflowTasks", input))
245
+ }
246
+
247
+ private *subWorkflowTaskFor(input: { readonly flow: Id<"flows">; readonly entryIndex: number }) {
248
+ const row = yield* Effect.promise(() =>
249
+ this.ctx.db.query("subWorkflowTasks").withIndex("by_flow_entry", (q) => q.eq("flow", input.flow).eq("entryIndex", input.entryIndex)).unique(),
250
+ )
251
+ if (row === null) return yield* Effect.die(new Error(`flow ${input.flow} waits on no sub-workflow task for entry ${input.entryIndex}`))
252
+ return row
253
+ }
254
+
255
+ *setSubWorkflowTask(input: { readonly flow: Id<"flows">; readonly entryIndex: number; readonly task: string }) {
256
+ const row = yield* this.subWorkflowTaskFor(input)
257
+ yield* Effect.promise(() => this.ctx.db.patch(row._id, { task: input.task }))
258
+ }
259
+
260
+ *markSubWorkflowTaskEnded(input: { readonly flow: Id<"flows">; readonly entryIndex: number; readonly endState: string }) {
261
+ const row = yield* this.subWorkflowTaskFor(input)
262
+ yield* Effect.promise(() => this.ctx.db.patch(row._id, { endedAs: input.endState }))
263
+ }
264
+
265
+ *subWorkflowTasksOf(flow: Id<"flows">) {
266
+ return yield* Effect.promise(() => this.ctx.db.query("subWorkflowTasks").withIndex("by_flow_entry", (q) => q.eq("flow", flow)).collect())
267
+ }
268
+
269
+ *clearSubWorkflowTasks(flow: Id<"flows">) {
270
+ for (const row of yield* this.subWorkflowTasksOf(flow)) yield* Effect.promise(() => this.ctx.db.delete(row._id))
271
+ }
272
+
273
+ *scheduleHook(input: { readonly hook: string; readonly args: Record<string, unknown> }) {
274
+ // A hook is a function handle the workforce created at registration; Convex stores it as a plain string.
275
+ const handle = input.hook as FunctionHandle<"mutation">
276
+ yield* Effect.promise(() => this.ctx.scheduler.runAfter(0, handle, input.args))
277
+ }
278
+
279
+ *insertFlow(input: { readonly workflow: string; readonly task: Id<"tasks">; readonly startedBy: string; readonly place: string }) {
280
+ const id = yield* Effect.promise(() => this.ctx.db.insert("flows", { ...input, enteredAt: this.now }))
281
+ return yield* this.reload(id, "flow")
282
+ }
283
+
284
+ *getFlow(id: Id<"flows">) {
285
+ return Option.fromNullishOr(yield* Effect.promise(() => this.ctx.db.get(id)))
286
+ }
287
+
288
+ *moveFlow(input: { readonly flow: Id<"flows">; readonly place: string; readonly enteredAt: number; readonly notBefore?: number }) {
289
+ yield* Effect.promise(() => this.ctx.db.patch(input.flow, { place: input.place, enteredAt: input.enteredAt, notBefore: input.notBefore }))
290
+ return yield* this.reload(input.flow, "flow")
291
+ }
292
+
293
+ /** The flow that has waited longest at a place and may be taken now: a flow a failed run delayed is passed over until its time. */
294
+ *headOf(input: { readonly workflow: string; readonly place: string }) {
295
+ const now = this.now
296
+ const head = yield* Effect.promise(async () => {
297
+ const queue = this.ctx.db
298
+ .query("flows")
299
+ .withIndex("by_workflow_place_entered", (q) => q.eq("workflow", input.workflow).eq("place", input.place))
300
+ .order("asc")
301
+ for await (const flow of queue) if (flow.notBefore === undefined || flow.notBefore <= now) return flow
302
+ return null
303
+ })
304
+ return Option.fromNullishOr(head)
305
+ }
306
+
307
+ *headsOf(input: { readonly workflow: string; readonly place: string; readonly upTo: number }) {
308
+ const now = this.now
309
+ return yield* Effect.promise(async () => {
310
+ const heads: Array<FlowRow> = []
311
+ const queue = this.ctx.db
312
+ .query("flows")
313
+ .withIndex("by_workflow_place_entered", (q) => q.eq("workflow", input.workflow).eq("place", input.place))
314
+ .order("asc")
315
+ for await (const flow of queue) {
316
+ if (flow.notBefore !== undefined && flow.notBefore > now) continue
317
+ heads.push(flow)
318
+ if (heads.length >= input.upTo) break
319
+ }
320
+ return heads
321
+ })
322
+ }
323
+
324
+ *firstAt(input: { readonly workflow: string; readonly place: string }) {
325
+ return Option.fromNullishOr(
326
+ yield* Effect.promise(() =>
327
+ this.ctx.db.query("flows").withIndex("by_workflow_place_entered", (q) => q.eq("workflow", input.workflow).eq("place", input.place)).first(),
328
+ ),
329
+ )
330
+ }
331
+
332
+ *flowsAt(input: { readonly workflow: string; readonly place: string }) {
333
+ return yield* Effect.promise(() =>
334
+ this.ctx.db.query("flows").withIndex("by_workflow_place_entered", (q) => q.eq("workflow", input.workflow).eq("place", input.place)).collect(),
335
+ )
336
+ }
337
+
338
+ *flowsOfTaskStartedBy(input: { readonly task: Id<"tasks">; readonly startedBy: string }) {
339
+ return yield* Effect.promise(() =>
340
+ this.ctx.db.query("flows").withIndex("by_task_started_by", (q) => q.eq("task", input.task).eq("startedBy", input.startedBy)).collect(),
341
+ )
342
+ }
343
+
344
+ *flowsOfTask(task: Id<"tasks">) {
345
+ return yield* Effect.promise(() => this.ctx.db.query("flows").withIndex("by_task_started_by", (q) => q.eq("task", task)).collect())
346
+ }
347
+
348
+ *flowsOfWorkflow(workflow: string) {
349
+ return yield* Effect.promise(() =>
350
+ this.ctx.db.query("flows").withIndex("by_workflow_place_entered", (q) => q.eq("workflow", workflow)).collect(),
351
+ )
352
+ }
353
+
354
+ *countRunning(input: { readonly workflow: string; readonly budget: BudgetName; readonly upTo: number }) {
355
+ const running = yield* Effect.promise(() =>
356
+ this.ctx.db
357
+ .query("stepRuns")
358
+ .withIndex("by_workflow_budget_status", (q) => q.eq("workflow", input.workflow).eq("budget", input.budget).eq("status", "running"))
359
+ .take(input.upTo),
360
+ )
361
+ return running.length
362
+ }
363
+
364
+ *insertStepRun(input: {
365
+ readonly flow: FlowRow
366
+ readonly step: string
367
+ readonly version: string
368
+ readonly budget: BudgetName
369
+ readonly worker: Option.Option<string>
370
+ readonly leaseMs: Option.Option<number>
371
+ }) {
372
+ const earlier = yield* Effect.promise(() => this.ctx.db.query("stepRuns").withIndex("by_task", (q) => q.eq("task", input.flow.task)).collect())
373
+ const id = yield* Effect.promise(() =>
374
+ this.ctx.db.insert("stepRuns", {
375
+ workflow: input.flow.workflow,
376
+ task: input.flow.task,
377
+ flow: input.flow._id,
378
+ step: input.step,
379
+ budget: input.budget,
380
+ status: "running",
381
+ startedAt: this.now,
382
+ takenFrom: { place: input.flow.place, enteredAt: input.flow.enteredAt },
383
+ version: input.version,
384
+ call: earlier.filter((run) => run.step === input.step).length + 1,
385
+ spend: noSpend,
386
+ used: nothingUsed,
387
+ files: [],
388
+ transcripts: [],
389
+ ...(Option.isSome(input.worker) ? { worker: input.worker.value } : {}),
390
+ }),
391
+ )
392
+ if (Option.isSome(input.leaseMs)) {
393
+ const expiresAt = this.now + input.leaseMs.value
394
+ yield* Effect.promise(() => this.ctx.db.insert("leases", { run: id, expiresAt, heartbeatAt: this.now }))
395
+ }
396
+ return yield* this.reload(id, "step run")
397
+ }
398
+
399
+ *getStepRun(id: Id<"stepRuns">) {
400
+ return Option.fromNullishOr(yield* Effect.promise(() => this.ctx.db.get(id)))
401
+ }
402
+
403
+ *runningStepRunOf(flow: Id<"flows">) {
404
+ const run = yield* Effect.promise(() =>
405
+ this.ctx.db.query("stepRuns").withIndex("by_flow_status", (q) => q.eq("flow", flow).eq("status", "running")).unique(),
406
+ )
407
+ return Option.fromNullishOr(run)
408
+ }
409
+
410
+ *recordSkippedOthers(input: { readonly run: Id<"stepRuns">; readonly skipped: ReadonlyArray<SkippedOther> }) {
411
+ yield* Effect.promise(() => this.ctx.db.patch(input.run, { skippedOthers: [...input.skipped] }))
412
+ }
413
+
414
+ *finishStepRun(input: {
415
+ readonly run: Id<"stepRuns">
416
+ readonly status: "ended" | "failed"
417
+ readonly endState: Option.Option<string>
418
+ readonly error: Option.Option<string>
419
+ readonly measurements: Option.Option<StepMeasurements>
420
+ readonly note: Option.Option<string>
421
+ }) {
422
+ yield* Effect.promise(() =>
423
+ this.ctx.db.patch(input.run, {
424
+ status: input.status,
425
+ endedAt: this.now,
426
+ ...(Option.isSome(input.endState) ? { endState: input.endState.value } : {}),
427
+ ...(Option.isSome(input.error) ? { error: errorKept(input.error.value) } : {}),
428
+ ...(Option.isSome(input.note) ? { note: input.note.value } : {}),
429
+ ...(Option.isSome(input.measurements)
430
+ ? {
431
+ spend: input.measurements.value.spend,
432
+ used: input.measurements.value.used,
433
+ files: input.measurements.value.files,
434
+ transcripts: input.measurements.value.transcripts,
435
+ ...(input.measurements.value.fingerprint !== undefined ? { fingerprint: input.measurements.value.fingerprint } : {}),
436
+ ...(input.measurements.value.agent !== undefined ? { agent: input.measurements.value.agent } : {}),
437
+ }
438
+ : {}),
439
+ }),
440
+ )
441
+ const lease = yield* this.leaseOf(input.run)
442
+ if (lease !== null) yield* Effect.promise(() => this.ctx.db.delete(lease._id))
443
+ }
444
+
445
+ private *leaseOf(run: Id<"stepRuns">) {
446
+ return yield* Effect.promise(() => this.ctx.db.query("leases").withIndex("by_run", (q) => q.eq("run", run)).unique())
447
+ }
448
+
449
+ *leaseExpiryOf(run: Id<"stepRuns">) {
450
+ const lease = yield* this.leaseOf(run)
451
+ return Option.map(Option.fromNullishOr(lease), (row) => row.expiresAt)
452
+ }
453
+
454
+ *extendLease(input: { readonly run: Id<"stepRuns">; readonly leaseMs: number }) {
455
+ const lease = yield* this.leaseOf(input.run)
456
+ if (lease !== null) yield* Effect.promise(() => this.ctx.db.patch(lease._id, { expiresAt: this.now + input.leaseMs, heartbeatAt: this.now }))
457
+ }
458
+
459
+ *scheduleLeaseCheck(input: { readonly run: Id<"stepRuns">; readonly at: number }) {
460
+ yield* Effect.promise(() => this.ctx.scheduler.runAt(input.at, internal.worker.expireLease, { run: input.run }))
461
+ }
462
+
463
+ *stepRunsOfTask(task: Id<"tasks">) {
464
+ return yield* Effect.promise(() => this.ctx.db.query("stepRuns").withIndex("by_task", (q) => q.eq("task", task)).collect())
465
+ }
466
+
467
+ *insertTaskNote(input: { readonly task: Id<"tasks">; readonly note: string }) {
468
+ yield* Effect.promise(() => this.ctx.db.insert("taskNotes", { task: input.task, note: input.note, at: this.now }))
469
+ }
470
+
471
+ *lastFingerprintOf(input: { readonly workflow: string; readonly step: string; readonly settledBy: ReadonlyArray<string> }) {
472
+ const fingerprint = yield* Effect.promise(async () => {
473
+ const runs = this.ctx.db
474
+ .query("stepRuns")
475
+ .withIndex("by_workflow_step_started", (q) => q.eq("workflow", input.workflow).eq("step", input.step))
476
+ .order("desc")
477
+ for await (const run of runs) {
478
+ if (run.status !== "ended" || run.fingerprint === undefined) continue
479
+ const task = await this.ctx.db.get(run.task)
480
+ if (task?.endedAs !== undefined && input.settledBy.includes(task.endedAs)) return run.fingerprint
481
+ }
482
+ return null
483
+ })
484
+ return Option.fromNullishOr(fingerprint)
485
+ }
486
+
487
+ *notesOfTask(task: TaskRow) {
488
+ const runs = yield* this.stepRunsOfTask(task._id)
489
+ const left = yield* Effect.promise(() => this.ctx.db.query("taskNotes").withIndex("by_task", (q) => q.eq("task", task._id)).collect())
490
+ return notesOf({ task, runs, left })
491
+ }
492
+
493
+ *deleteWorkflow(workflow: WorkflowRow) {
494
+ if (workflow.pruning !== undefined) yield* Effect.promise(() => this.ctx.scheduler.cancel(workflow.pruning!))
495
+ const name = workflow.name
496
+ const runs = yield* Effect.promise(() => this.ctx.db.query("stepRuns").withIndex("by_workflow_budget_status", (q) => q.eq("workflow", name)).collect())
497
+ const flows = yield* Effect.promise(() => this.ctx.db.query("flows").withIndex("by_workflow_place_entered", (q) => q.eq("workflow", name)).collect())
498
+ const tasks = yield* Effect.promise(() => this.ctx.db.query("tasks").withIndex("by_workflow", (q) => q.eq("workflow", name)).collect())
499
+ for (const run of runs) {
500
+ const lease = yield* this.leaseOf(run._id)
501
+ if (lease !== null) yield* Effect.promise(() => this.ctx.db.delete(lease._id))
502
+ }
503
+ for (const flow of flows) yield* this.clearSubWorkflowTasks(flow._id)
504
+ for (const task of tasks) {
505
+ for (const note of yield* Effect.promise(() => this.ctx.db.query("taskNotes").withIndex("by_task", (q) => q.eq("task", task._id)).collect())) {
506
+ yield* Effect.promise(() => this.ctx.db.delete(note._id))
507
+ }
508
+ }
509
+ for (const row of [...runs, ...flows, ...tasks]) yield* Effect.promise(() => this.ctx.db.delete(row._id))
510
+ yield* Effect.promise(() => this.ctx.db.delete(workflow._id))
511
+ }
512
+ }