@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
package/src/graph.ts CHANGED
@@ -1,25 +1,347 @@
1
+ import { Option } from "effect"
2
+ import { type Infer, v } from "convex/values"
3
+
4
+ /**
5
+ * The serializable form of one workflow: what the compiler emits and what the Convex component stores and runs.
6
+ * Every place a task can be is derived from it: a line, a step, or an end state.
7
+ */
8
+
9
+ export const stepKindValidator = v.union(v.literal("code"), v.literal("agent"), v.literal("workflow"))
10
+ export type StepKind = Infer<typeof stepKindValidator>
11
+
12
+ export const eventValidator = v.union(
13
+ v.object({ id: v.string(), kind: v.literal("task") }),
14
+ /**
15
+ * A change of `field` starts a flow for the task. With `resumes`, it instead moves the task's flow waiting at that end
16
+ * state onto this event's line: an end state that names why a task stopped (it waits for a name) is left when what it
17
+ * waited for changes.
18
+ */
19
+ v.object({ id: v.string(), kind: v.literal("change"), field: v.string(), resumes: v.optional(v.string()) }),
20
+ /**
21
+ * A turn every `everyMs`: a task with `fields`, what the workflow's task schema decodes from `{}`. `fieldsProblem` says
22
+ * why the schema cannot, and a graph with one is refused.
23
+ */
24
+ v.object({ id: v.string(), kind: v.literal("timer"), everyMs: v.number(), fields: v.optional(v.any()), fieldsProblem: v.optional(v.string()) }),
25
+ v.object({ id: v.string(), kind: v.literal("request") }),
26
+ /**
27
+ * A declared item list: a sync step (`syncs` naming this event) reads the list, and each item it has no task for
28
+ * becomes a task arriving here, keyed by the string field `key`. A task whose item left the list before it ended ends in
29
+ * `leftAs`, saying so; one that left and is listed again goes back on this event's line.
30
+ */
31
+ v.object({ id: v.string(), kind: v.literal("list"), key: v.string(), leftAs: v.string() }),
32
+ )
33
+ export type GraphEvent = Infer<typeof eventValidator>
34
+
35
+ export const subWorkflowValidator = v.object({
36
+ name: v.string(),
37
+ /** One task of the sub-workflow per entry of this list field of the task; absent means one task with the same fields. */
38
+ each: v.optional(v.string()),
39
+ /** When a sub-workflow task ends in `endState`, its fields are appended to the list field `into` of this task. */
40
+ collect: v.optional(v.object({ endState: v.string(), into: v.string() })),
41
+ })
42
+ export type SubWorkflow = Infer<typeof subWorkflowValidator>
43
+
1
44
  /**
2
- * A WORKFLOW'S STEP GRAPH, declared beside its steps: each edge a step that can follow another, with when it does in plain
3
- * words. Alex, 2026-11-12: "In a generic workflow dashboard, it should be clear what the DAG of steps is." A dashboard draws
4
- * it from this alone; a run that takes an edge its workflow did not declare fails in tests, and live it is said once.
5
- * Dependency-free, so a page can import it.
45
+ * How a code or agent step treats a failed run: the task goes back to the front of its queue, and no worker takes it
46
+ * again until `delayMs` has passed. After `limit` failed runs in a row it leaves the step through `giveUp`, one of the
47
+ * step's own end states, with why as a task note. A step with none is tried again at once, however often it fails.
6
48
  */
7
- export interface StepEdge {
8
- readonly from: string;
9
- readonly to: string;
10
- /** When a run takes it, in plain words: "the test proves it", "not proven, an agent budget left". */
11
- readonly when: string;
49
+ export const retriesValidator = v.object({ limit: v.number(), delayMs: v.number(), giveUp: v.string() })
50
+ export type Retries = Infer<typeof retriesValidator>
51
+
52
+ /**
53
+ * What a code or agent step's code may use, as its definition declares it: the services the worker gives its runs (by
54
+ * key), and the workflows whose tasks it may read through `Tasks` and write through `others`.
55
+ */
56
+ export const stepAccessValidator = v.object({
57
+ services: v.array(v.string()),
58
+ tasks: v.optional(v.object({ read: v.array(v.string()), write: v.array(v.string()) })),
59
+ })
60
+ export type StepAccessGraph = Infer<typeof stepAccessValidator>
61
+
62
+ /**
63
+ * How long a workflow keeps its records, set on the workflow and overridden on a step. A step run of a task that has
64
+ * ended goes once it ended more than `days` ago, unless it is one of its step's newest `keepAtLeastRuns`; a turn task (one
65
+ * a timer made) goes the same way, its runs and notes with it, unless it is one of the newest that many at its end state.
66
+ * An item's task, made by a request, a list or `createTask`, is the work's state, not its history, and never goes. Alex,
67
+ * 2026-11-21: "time based retention is a good idea. it should be configurable at the highest level with allowed step
68
+ * level overrides ... i think 7 days sounds reasonable"; 2026-11-22: "10k runs".
69
+ */
70
+ export const retentionValidator = v.object({ days: v.optional(v.number()), keepAtLeastRuns: v.optional(v.number()) })
71
+ export type Retention = Infer<typeof retentionValidator>
72
+ export const defaultRetention = { days: 7, keepAtLeastRuns: 10_000 } as const
73
+
74
+ /** What a step keeps: its own setting, else its workflow's, else the platform's. */
75
+ export const retentionOf = (graph: WorkflowGraph, step: string | null): { readonly days: number; readonly keepAtLeastRuns: number } => {
76
+ const own = step === null ? undefined : graph.steps.find((candidate) => candidate.id === step)?.retention
77
+ return {
78
+ days: own?.days ?? graph.retention?.days ?? defaultRetention.days,
79
+ keepAtLeastRuns: own?.keepAtLeastRuns ?? graph.retention?.keepAtLeastRuns ?? defaultRetention.keepAtLeastRuns,
80
+ }
12
81
  }
13
82
 
14
- /** The ends of a graph: before a run's first step and after its last. */
15
- export const RUN_STARTS = 'run starts';
16
- export const RUN_ENDS = 'run ends';
17
- /** An edge from any step, taken when that step fails. */
18
- export const A_STEP_FAILS = 'a step fails';
83
+ export const stepValidator = v.object({
84
+ id: v.string(),
85
+ kind: stepKindValidator,
86
+ endStates: v.array(v.string()),
87
+ /** What this step's records keep, over its workflow's (`retentionOf`). */
88
+ retention: v.optional(retentionValidator),
89
+ /** Set on every code and agent step; nothing listed grants nothing. */
90
+ access: v.optional(stepAccessValidator),
91
+ workflow: v.optional(subWorkflowValidator),
92
+ retries: v.optional(retriesValidator),
93
+ /**
94
+ * An inputs gate (`inputsChanged`): its runs record a fingerprint, and each run is given the newest one whose turn
95
+ * settled it, meaning its task ended in one of these workflow end states. A turn that saw changed inputs and then failed
96
+ * settles nothing, so the next one sees the change again.
97
+ */
98
+ inputsSettledBy: v.optional(v.array(v.string())),
99
+ /** A code step that reads a declared item list: the id of the `list` event whose tasks its runs keep in step with it. */
100
+ syncs: v.optional(v.string()),
101
+ })
102
+ export type GraphStep = Infer<typeof stepValidator>
103
+
104
+ export const lineStartValidator = v.union(
105
+ v.object({ event: v.string() }),
106
+ v.object({ step: v.string(), endState: v.string() }),
107
+ /** A step consuming one of the workflow's end states: tasks that reach that end state wait there as a queue. */
108
+ v.object({ end: v.string() }),
109
+ )
110
+ export type LineStart = Infer<typeof lineStartValidator>
111
+
112
+ export const lineEndValidator = v.union(v.object({ step: v.string() }), v.object({ end: v.string() }))
113
+ export type LineEnd = Infer<typeof lineEndValidator>
114
+
115
+ export const lineValidator = v.object({ id: v.string(), from: lineStartValidator, to: lineEndValidator })
116
+ export type GraphLine = Infer<typeof lineValidator>
117
+
118
+ export const budgetsValidator = v.object({ agents: v.number(), cpu: v.number() })
119
+ export type Budgets = Infer<typeof budgetsValidator>
120
+
121
+
122
+ export const graphValidator = v.object({
123
+ name: v.string(),
124
+ endStates: v.array(v.string()),
125
+ events: v.array(eventValidator),
126
+ steps: v.array(stepValidator),
127
+ lines: v.array(lineValidator),
128
+ /** Defaults only: a registered workflow keeps the budgets it was given with `setBudgets`. */
129
+ budgets: budgetsValidator,
130
+ /** What the workflow's records keep, unless a step sets its own (`retentionOf`). */
131
+ retention: v.optional(retentionValidator),
132
+ /**
133
+ * At most `limit` of its tasks in progress at once: past the line an event put them on, and not yet ended. With
134
+ * `per`, the limit holds for each value of that field instead, so a workflow with `{ limit: 1, per: "function" }` is a
135
+ * lock on each function, held from its first step to its end by whichever workflow's task (through a sub-workflow
136
+ * step) got there first. A budget counts running steps; this counts tasks, so it holds across several steps.
137
+ */
138
+ inProgress: v.optional(v.object({ limit: v.number(), per: v.optional(v.string()) })),
139
+ })
140
+ export type WorkflowGraph = Infer<typeof graphValidator>
141
+
142
+ export const taskFileValidator = v.object({ name: v.string(), ref: v.string() })
143
+ export type TaskFile = Infer<typeof taskFileValidator>
144
+
145
+ /** Which budget a step takes one unit of while a task is in it. A sub-workflow step takes none: its tasks use the sub-workflow's budgets. */
146
+ export const budgetOfStepKind = (kind: StepKind): keyof Budgets | "none" =>
147
+ kind === "agent" ? "agents" : kind === "code" ? "cpu" : "none"
148
+
149
+ export const lineIdOf = (line: { readonly from: LineStart; readonly to: LineEnd }): string => {
150
+ const from = "event" in line.from
151
+ ? `event.${line.from.event}`
152
+ : "step" in line.from
153
+ ? `step.${line.from.step}.${line.from.endState}`
154
+ : `end.${line.from.end}`
155
+ const to = "step" in line.to ? `step.${line.to.step}` : `end.${line.to.end}`
156
+ return `${from}>${to}`
157
+ }
158
+
159
+ /** The place a task waits after travelling a line: the line itself, or the end state it leads to. */
160
+ export const placeAtEndOf = (line: GraphLine) => ("end" in line.to ? `end:${line.to.end}` : `line:${line.id}`)
161
+
162
+ /** A line out of an end state makes that end state the queue in front of its step. */
163
+ export const placeAtStartOf = (line: GraphLine) => ("end" in line.from ? `end:${line.from.end}` : `line:${line.id}`)
164
+
165
+ export const endStateOfPlace = (place: string): Option.Option<string> =>
166
+ place.startsWith("end:") ? Option.some(place.slice("end:".length)) : Option.none()
167
+
168
+ export const stepOfPlace = (place: string): Option.Option<string> =>
169
+ place.startsWith("step:") ? Option.some(place.slice("step:".length)) : Option.none()
19
170
 
20
- /** A step done again after it failed (its own retry, as on a locked database) is that step still, not a move. */
21
- export const isRetry = (last: { readonly step: string; readonly failed: boolean } | null, to: string): boolean => last !== null && last.failed && last.step === to;
171
+ export const sameStart = (a: LineStart, b: LineStart) =>
172
+ ("event" in a && "event" in b && a.event === b.event) ||
173
+ ("step" in a && "step" in b && a.step === b.step && a.endState === b.endState) ||
174
+ ("end" in a && "end" in b && a.end === b.end)
175
+
176
+ export const lineFrom = (graph: WorkflowGraph, start: LineStart): Option.Option<GraphLine> =>
177
+ Option.fromNullishOr(graph.lines.find((line) => sameStart(line.from, start)))
178
+
179
+ export const inputPlacesOf = (graph: WorkflowGraph, step: string): ReadonlyArray<string> =>
180
+ graph.lines.filter((line) => "step" in line.to && line.to.step === step).map(placeAtStartOf)
181
+
182
+ /** Events that bring a new task into the workflow; a change event starts a flow for a task already in it. */
183
+ export const createsTasks = (event: GraphEvent) => event.kind !== "change"
184
+
185
+ /** Every structural problem in a graph, so a broken definition is refused at registration, not mid-run. */
186
+ export const problemsOf = (graph: WorkflowGraph): ReadonlyArray<string> => {
187
+ const problems: Array<string> = []
188
+ const steps = new Map(graph.steps.map((step) => [step.id, step]))
189
+ const events = new Map(graph.events.map((event) => [event.id, event]))
190
+ if (steps.size !== graph.steps.length) problems.push("two steps share an id")
191
+ if (events.size !== graph.events.length) problems.push("two events share an id")
192
+ const ends = new Set(graph.endStates)
193
+ const starts: Array<LineStart> = []
194
+ for (const line of graph.lines) {
195
+ if (line.id !== lineIdOf(line)) problems.push(`line ${line.id} should have id ${lineIdOf(line)}`)
196
+ if (starts.some((start) => sameStart(start, line.from))) problems.push(`two lines leave ${lineIdOf(line).split(">")[0]}`)
197
+ starts.push(line.from)
198
+ if ("event" in line.from && !events.has(line.from.event)) problems.push(`line ${line.id} leaves unknown event ${line.from.event}`)
199
+ if ("step" in line.from) {
200
+ const step = steps.get(line.from.step)
201
+ if (step === undefined) problems.push(`line ${line.id} leaves unknown step ${line.from.step}`)
202
+ else if (!step.endStates.includes(line.from.endState)) problems.push(`line ${line.id} leaves unknown end state ${line.from.endState} of ${step.id}`)
203
+ }
204
+ if ("end" in line.from && !ends.has(line.from.end)) problems.push(`line ${line.id} leaves unknown workflow end state ${line.from.end}`)
205
+ if ("step" in line.to && !steps.has(line.to.step)) problems.push(`line ${line.id} enters unknown step ${line.to.step}`)
206
+ if ("end" in line.to && !ends.has(line.to.end)) problems.push(`line ${line.id} enters unknown workflow end state ${line.to.end}`)
207
+ }
208
+ for (const event of graph.events) {
209
+ if (Option.isNone(lineFrom(graph, { event: event.id }))) problems.push(`event ${event.id} has no line out of it`)
210
+ if (event.kind === "change" && event.resumes !== undefined && !ends.has(event.resumes)) problems.push(`event ${event.id} resumes unknown end state ${event.resumes}`)
211
+ if (event.kind === "timer" && event.fieldsProblem !== undefined) problems.push(`timer event ${event.id} cannot start a turn: ${event.fieldsProblem}`)
212
+ if (event.kind === "timer" && event.fieldsProblem === undefined && event.fields === undefined) problems.push(`timer event ${event.id} has no fields for its turn task`)
213
+ if (event.kind === "list" && !ends.has(event.leftAs)) problems.push(`event ${event.id} ends a task that left its list in ${event.leftAs}, which is not an end state of the workflow`)
214
+ if (event.kind === "list" && !graph.steps.some((step) => step.syncs === event.id)) problems.push(`list event ${event.id} has no step that syncs it`)
215
+ }
216
+ for (const step of graph.steps) {
217
+ if ((step.kind === "workflow") !== (step.workflow !== undefined)) problems.push(`step ${step.id} must name a sub-workflow exactly when its kind is workflow`)
218
+ if (step.kind === "workflow" && step.access !== undefined) problems.push(`step ${step.id} is a sub-workflow step, whose code runs in its own workflow, so it declares no access`)
219
+ for (const workflow of [...(step.access?.tasks?.read ?? []), ...(step.access?.tasks?.write ?? [])]) {
220
+ if (workflow.length === 0) problems.push(`step ${step.id} names a workflow with no name in its access`)
221
+ }
222
+ for (const end of step.inputsSettledBy ?? []) {
223
+ if (!ends.has(end)) problems.push(`step ${step.id} settles its inputs by ${end}, which is not an end state of the workflow`)
224
+ }
225
+ if (step.inputsSettledBy !== undefined && step.inputsSettledBy.length === 0) problems.push(`step ${step.id} names no end state that settles its inputs`)
226
+ if (step.syncs !== undefined) {
227
+ if (events.get(step.syncs)?.kind !== "list") problems.push(`step ${step.id} syncs ${step.syncs}, which is not a list event of the workflow`)
228
+ if (step.kind !== "code") problems.push(`step ${step.id} syncs a list, which only a code step does`)
229
+ }
230
+ if (step.retries !== undefined) {
231
+ if (step.kind === "workflow") problems.push(`step ${step.id} is a sub-workflow step, which has no runs to retry`)
232
+ if (!Number.isInteger(step.retries.limit) || step.retries.limit < 1) problems.push(`step ${step.id} retries a run at least once`)
233
+ if (step.retries.delayMs < 0) problems.push(`step ${step.id} waits no less than 0 ms between tries`)
234
+ if (!step.endStates.includes(step.retries.giveUp)) problems.push(`step ${step.id} gives up through ${step.retries.giveUp}, which is not one of its end states`)
235
+ }
236
+ for (const endState of step.endStates) {
237
+ if (Option.isNone(lineFrom(graph, { step: step.id, endState }))) problems.push(`end state ${endState} of step ${step.id} has nowhere to go`)
238
+ }
239
+ if (inputPlacesOf(graph, step.id).length === 0) problems.push(`step ${step.id} has no line into it`)
240
+ }
241
+ if (graph.inProgress !== undefined && !(Number.isInteger(graph.inProgress.limit) && graph.inProgress.limit >= 1)) problems.push("the workflow lets at least one task be in progress at once")
242
+ for (const [who, retention] of [["the workflow", graph.retention] as const, ...graph.steps.map((step) => [`step ${step.id}`, step.retention] as const)]) {
243
+ if (retention?.days !== undefined && !(retention.days >= 0)) problems.push(`${who} keeps its records no fewer than 0 days`)
244
+ // A gate reads its newest settled run, so every step keeps at least its newest one.
245
+ if (retention?.keepAtLeastRuns !== undefined && !(Number.isInteger(retention.keepAtLeastRuns) && retention.keepAtLeastRuns >= 1)) problems.push(`${who} keeps at least its newest run`)
246
+ }
247
+ return problems
248
+ }
249
+
250
+
251
+ /** The end state of a step making one sub-workflow task per list entry, reached once every one of them has ended. */
252
+ export const everySubWorkflowTaskEnded = "ended"
253
+
254
+ /**
255
+ * One thing a step, or a call that sent the task back, said about a task, at the time it was said. `step` is absent on a
256
+ * note no step wrote, such as the reason a task was requeued. `workflow` names the task's workflow, which differs from
257
+ * the reader's for a note on a parent task.
258
+ */
259
+ export const taskNoteValidator = v.object({ workflow: v.string(), step: v.optional(v.string()), note: v.string(), at: v.number() })
260
+ export type TaskNote = Infer<typeof taskNoteValidator>
261
+
262
+ /**
263
+ * Where a sub-workflow task came from: the parent workflow, the sub-workflow step and the parent task that started it,
264
+ * the parent's flow waiting in that step, and the list entry it is for.
265
+ */
266
+ export const parentRefValidator = v.object({ workflow: v.string(), step: v.string(), task: v.string(), flow: v.string(), entryIndex: v.number() })
267
+ export type ParentRef = Infer<typeof parentRefValidator>
268
+
269
+ /**
270
+ * The workforce mutations (Convex function handles) a workflow component schedules to reach another workflow's
271
+ * component: one creates sub-workflow tasks, the other tells a parent that one of them ended.
272
+ */
273
+ export const workforceHooksValidator = v.object({ startSubWorkflowTasks: v.string(), subWorkflowTaskEnded: v.string() })
274
+ export type WorkforceHooks = Infer<typeof workforceHooksValidator>
275
+
276
+ /**
277
+ * What one step run spent and used, as the worker measured it; the old platform's step records keep the same figures.
278
+ * Input tokens are split by how the provider prices them; `requests` counts the API calls an agent made, and `costUsd`
279
+ * is what those calls cost in US dollars, as the organization's agent runner reports it.
280
+ */
281
+ export const stepSpendValidator = v.object({
282
+ fresh: v.number(),
283
+ cacheWrite: v.number(),
284
+ cacheRead: v.number(),
285
+ output: v.number(),
286
+ requests: v.number(),
287
+ costUsd: v.number(),
288
+ compiles: v.number(),
289
+ })
290
+ export type StepSpend = Infer<typeof stepSpendValidator>
291
+ export const noSpend: StepSpend = { fresh: 0, cacheWrite: 0, cacheRead: 0, output: 0, requests: 0, costUsd: 0, compiles: 0 }
292
+
293
+ export const stepUsedValidator = v.object({
294
+ /** CPU of the worker process's own work while the step ran. */
295
+ ownCpuSeconds: v.number(),
296
+ /** CPU of processes the step started, as the step reports it. */
297
+ childCpuSeconds: v.number(),
298
+ peakMemoryMb: v.number(),
299
+ filesWritten: v.number(),
300
+ })
301
+ export type StepUsed = Infer<typeof stepUsedValidator>
302
+ export const nothingUsed: StepUsed = { ownCpuSeconds: 0, childCpuSeconds: 0, peakMemoryMb: 0, filesWritten: 0 }
303
+
304
+ /** A worker's measurements of one step run, sent with its end state or its failure. */
305
+ export const stepMeasurementsValidator = v.object({
306
+ spend: stepSpendValidator,
307
+ used: stepUsedValidator,
308
+ /** The agent (provider and model) that ran an agent step; absent for a step that ran no agent. */
309
+ agent: v.optional(v.string()),
310
+ /** Names of the files the step wrote. */
311
+ files: v.array(v.string()),
312
+ /** The transcripts of the agent runs the step made, kept through the organization's `FileStore`. */
313
+ transcripts: v.array(taskFileValidator),
314
+ /** What the step read of its inputs, as one fingerprint, for the next run of the step to compare (`inputsChanged`). */
315
+ fingerprint: v.optional(v.string()),
316
+ })
317
+ export type StepMeasurements = Infer<typeof stepMeasurementsValidator>
318
+
319
+ /** A failed step's error as its record keeps it: 8,000 characters, the start and the end of a longer one. */
320
+ export const errorKept = (error: string): string =>
321
+ error.length <= 8000 ? error : `${error.slice(0, 5000)}\n… ${error.length - 8000} characters of the error left out …\n${error.slice(-3000)}`
322
+
323
+ /** A short fingerprint of a graph, recorded on every step run so a record says which version of its workflow ran. */
324
+ export const versionOf = (graph: WorkflowGraph): string => {
325
+ let hash = 0x811c9dc5
326
+ for (const character of JSON.stringify(graph)) {
327
+ hash ^= character.charCodeAt(0)
328
+ hash = Math.imul(hash, 0x01000193) >>> 0
329
+ }
330
+ return hash.toString(16).padStart(8, "0")
331
+ }
332
+
333
+ /**
334
+ * One place of a workflow's diagram, as the renderer names it: a line by its id, a step by its id, an end state by its
335
+ * name. `inFrontOf` names a step and means its whole queue: every task waiting on any line into it.
336
+ */
337
+ export const placeRefValidator = v.union(
338
+ v.object({ line: v.string() }),
339
+ v.object({ step: v.string() }),
340
+ v.object({ end: v.string() }),
341
+ v.object({ inFrontOf: v.string() }),
342
+ )
343
+ export type PlaceRef = Infer<typeof placeRefValidator>
22
344
 
23
- /** Whether `graph` has the move from a run's last step (none before its first) to `to`. Pure. */
24
- export const edgeDeclared = (graph: ReadonlyArray<StepEdge>, last: { readonly step: string; readonly failed: boolean } | null, to: string): boolean =>
25
- isRetry(last, to) || graph.some((e) => e.to === to && (last === null ? e.from === RUN_STARTS : e.from === last.step || (last.failed && e.from === A_STEP_FAILS)));
345
+ /** A write to another task (`others`) a run made that was not applied: the task, its workflow, and why, in words. */
346
+ export const skippedOtherValidator = v.object({ workflow: v.string(), task: v.string(), reason: v.string() })
347
+ export type SkippedOther = Infer<typeof skippedOtherValidator>
package/src/index.ts CHANGED
@@ -1,168 +1,8 @@
1
- /**
2
- * @jive-sh/workflow-platform: durable workflows on effect/workflow, measured step by step.
3
- *
4
- * A project builds one platform with `createWorkflowPlatform(project, storage)`: its facts (`project.ts`) and where its
5
- * records live (`storage/`). The platform gives it the one way to define workflows and steps, the task queue, waiting
6
- * Picks and the trigger's plan.
7
- */
8
- import { Effect } from 'effect';
9
- import fs from 'node:fs';
10
- import path from 'node:path';
11
- import type { StorageError } from './storage/storage-error';
12
- import type { WorkflowProject } from './project';
13
- import { makePickWakes } from './pick-wakes';
14
- import { makeStepFiles } from './step-files';
15
- import { makeStepUsage } from './step-usage';
16
- import { keptRunningByItsBudget, makeSteps, runLimitOf } from './steps';
17
- import { blockedReasons, makeTasks, needsAgentReasons } from './tasks';
18
- import { buildWorkflowFigures, buildWorkflowsView, type WorkflowFigures, type WorkflowsView, type WorkflowView } from './views/workflows-view';
19
- import { makeQueueCounts } from './queue-counts';
20
- import { makeSpendingLimit } from './spending-limit';
21
- import { sqliteBudgets, type LimitStore } from './storage/budgets';
22
- import { sqliteEngineRecords, type EngineRecords } from './storage/engine-records';
23
- import { sqliteStore } from './storage/sqlite-store';
24
- import type { StepRecords } from './storage/step-records';
25
- import type { TaskStore } from './storage/task-store';
26
- import type { InputRecords } from './storage/input-records';
27
-
28
- export * from './failure';
29
- export * from './outside-failure';
30
- export * from './project';
31
- export * from './budget-states';
32
- export * from './keep-running';
33
- export * from './pick-wakes';
34
- export * from './queue-counts';
35
- export * from './spending-limit';
36
- export * from './step-files';
37
- export * from './step-meter';
38
- export * from './steps';
39
- export * from './tasks';
40
- export * from './cpu-limit/use';
41
- export * from './cpu-limit/limiter';
42
- export * from './storage/budgets';
43
- export * from './storage/engine-records';
44
- export * from './storage/sqlite-store';
45
- export * from './storage/step-records';
46
- export * from './storage/input-records';
47
- export * from './storage/storage-error';
48
- export * from './storage/move-store';
49
- export * from './storage/engine-storage';
50
- export * from './graph';
51
- export * from './reasons';
52
- export * from './views/runs-now';
53
- export * from './views/step-funnel';
54
- export * from './views/step-graph';
55
- export * from './views/workflows-view';
56
- export * from './views/workflow-flows';
57
- export type { NewNote, TaskStore, TextChange } from './storage/task-store';
58
- export type { AgentUsage, UsageLimit } from './dashboard/agent-usage';
59
-
60
- /** Where a project's records live: each store an interface, so another database can stand behind any of them. */
61
- export interface WorkflowStorage {
62
- readonly stepRecords: StepRecords;
63
- readonly tasks: TaskStore;
64
- readonly inputs: InputRecords;
65
- readonly engine: EngineRecords;
66
- readonly budgets: LimitStore;
67
- }
68
-
69
- /**
70
- * The storage as SQLite files: the platform's one database (step records, tasks, input runs, the limits, and the schema the
71
- * project declares beside them), and the engine's own (`STORAGE.md` says why the engine keeps a file of its own). A test
72
- * may name other files for each.
73
- */
74
- export const sqliteStorage = (options: {
75
- readonly stepRecordsFile: () => string | null;
76
- readonly engineFile: () => string;
77
- readonly budgetsFile: () => string;
78
- readonly processes: WorkflowProject['processes'];
79
- /** The file the step records had of their own, read until they have moved (`storage/move-store.ts`). */
80
- readonly movedFrom?: () => string | null;
81
- /** Whether the store makes a missing file; the project's boot makes its own database (`sqliteStore` `creates`). */
82
- readonly creates?: (file: string) => boolean;
83
- }): WorkflowStorage => {
84
- const store = sqliteStore({ file: options.stepRecordsFile, processes: options.processes, ...(options.movedFrom === undefined ? {} : { movedFrom: options.movedFrom }), ...(options.creates === undefined ? {} : { creates: options.creates }) });
85
- return {
86
- stepRecords: store.stepRecords,
87
- tasks: store.tasks,
88
- inputs: store.inputs,
89
- engine: sqliteEngineRecords({ file: options.engineFile }),
90
- budgets: sqliteBudgets({ file: options.budgetsFile }),
91
- };
92
- };
93
-
94
- /**
95
- * ONE PROJECT'S PLATFORM. `Phase` is where the project shows a workflow; `R` what its workflows' lists of work run under.
96
- */
97
- export const createWorkflowPlatform = <Phase extends string, R>(input: {
98
- readonly project: WorkflowProject;
99
- readonly storage: WorkflowStorage;
100
- }) => {
101
- const { project, storage } = input;
102
- const wakes = makePickWakes();
103
- const stepFiles = makeStepFiles({ tree: project.tree, runLightNow: project.runLightNow });
104
- const stepUsage = makeStepUsage({ variable: project.stepRecordVariable, addStepCompile: (record) => { Effect.runFork(Effect.catchTag(storage.stepRecords.addStepCompile(record), 'StorageError', (e) => Effect.logError(`[step-runs] a compile of step record ${record}: ${e.reason}`))); } });
105
- const tasks = makeTasks({ store: storage.tasks, engine: storage.engine, stepRecords: storage.stepRecords, wakes, texts: project.texts });
106
- const spending = makeSpendingLimit({ store: storage.budgets, usage: project.weekUsage === undefined ? null : project.weekUsage, wakes });
107
- const steps = makeSteps<Phase, R>({
108
- sourceRoot: project.sourceRoot, stepRecords: storage.stepRecords, engine: storage.engine, tasks, wakes, budgets: storage.budgets, stepFiles,
109
- CurrentStepUsage: stepUsage.CurrentStepUsage, isTransientFailure: project.isTransientFailure, thisProcess: project.processes.thisProcess, inputs: storage.inputs,
110
- queueChanged: (workflow) => queueCounts.changed(workflow),
111
- spendingHoldsAgents: spending.holdsAgents,
112
- });
113
- const queueCounts = makeQueueCounts({
114
- store: storage.tasks, tasks, wakes,
115
- withQueues: () => steps.declaredWorkflows().filter((d) => d.item !== null).map((d) => d.name),
116
- });
117
- /**
118
- * Every workflow's limits now, by name, in one read: what a page's controls show. Every workflow has a run limit
119
- * (`steps.ts` `runLimitOf`), none meaning no limit; only one its budget keeps going has an agents' limit. Empty where no
120
- * store is read (a test).
121
- */
122
- const limitsNow = (): Effect.Effect<Readonly<Record<string, NonNullable<WorkflowView['limits']>>>, StorageError> =>
123
- Effect.map(storage.budgets.storedLimits(), (stored) => (stored === null ? {} : Object.fromEntries(steps.declaredWorkflows().map((d) => {
124
- const limits = stored.get(d.name) ?? { agents: 0, runs: null };
125
- return [d.name, { agents: keptRunningByItsBudget(d) ? limits.agents : null, runs: runLimitOf(d, limits), runsSet: limits.runs !== null }] as const;
126
- }))));
127
-
128
- /** Each source file's text, read again only when the file changed: a page's links name the line a definition is on now. */
129
- const texts = new Map<string, { readonly changed: number; readonly text: string } | null>();
130
- const locate = (s: { readonly path: string; readonly anchor: string }): number | null => {
131
- const file = path.join(project.sourceRoot, s.path);
132
- try {
133
- const changed = fs.statSync(file).mtimeMs;
134
- if (texts.get(s.path)?.changed !== changed) texts.set(s.path, { changed, text: fs.readFileSync(file, 'utf8') });
135
- } catch {
136
- texts.set(s.path, null);
137
- }
138
- const text = texts.get(s.path)?.text;
139
- const at = text === undefined ? -1 : text.indexOf(s.anchor);
140
- return text === undefined || at < 0 ? null : text.slice(0, at).split('\n').length;
141
- };
142
-
143
- /**
144
- * Every workflow as a dashboard shows it before one is opened, read now (`views/workflows-view.ts` `buildWorkflowsView`).
145
- * `phases` is the order the project's page shows them in.
146
- */
147
- const view = (r: { readonly now: number; readonly phases: ReadonlyArray<string>; readonly top: { readonly name: string; readonly description: string } }): Effect.Effect<WorkflowsView, StorageError> => Effect.gen(function* () {
148
- const limits = yield* limitsNow();
149
- return yield* buildWorkflowsView({ declared: steps.declaredWorkflows(), phases: r.phases, top: r.top, now: r.now, taskStore: storage.tasks, locate, limitsOf: (name) => limits[name] ?? null, spending: yield* spending.state(r.now) });
150
- });
151
-
152
- /** One workflow's figures over the `hours` before `now`, read from its own records (`buildWorkflowFigures`); none for one not declared. */
153
- const figures = (r: { readonly workflow: string; readonly now: number; readonly hours: number }): Effect.Effect<WorkflowFigures | null, StorageError> => {
154
- const declaration = steps.declaredWorkflows().find((d) => d.name === r.workflow);
155
- return declaration === undefined ? Effect.succeed(null) : buildWorkflowFigures({
156
- declaration, now: r.now, hours: r.hours, records: storage.stepRecords, engine: storage.engine, locate,
157
- reasons: declaration.item === null
158
- ? Effect.succeed({ blocked: [], needingAnAgent: { reasons: [], passedOverBecause: null } })
159
- : Effect.map(Effect.all({ summaries: tasks.taskSummaries({ workflow: r.workflow }), unavailable: steps.agentsUnavailable(r.workflow) }), ({ summaries, unavailable }) => ({
160
- blocked: blockedReasons(summaries),
161
- needingAnAgent: { reasons: needsAgentReasons(summaries), passedOverBecause: unavailable },
162
- })),
163
- });
164
- };
165
- return { project, storage, wakes, stepFiles, stepUsage, tasks, steps, view, figures, limitsNow, queueCounts, spending };
166
- };
167
-
168
- export type WorkflowPlatform<Phase extends string, R> = ReturnType<typeof createWorkflowPlatform<Phase, R>>;
1
+ export * as AgentRunner from "./definition/agent-runner"
2
+ export * as FileStore from "./definition/file-store"
3
+ export * as ProgramBuild from "./definition/program-build"
4
+ export * as Tasks from "./definition/tasks"
5
+ export * as TaskSchema from "./definition/task-schema"
6
+ export * as Workflow from "./definition/workflow"
7
+ export type * from "./definition/step"
8
+ export * from "./graph"
@@ -0,0 +1,42 @@
1
+ import { createHash } from "node:crypto"
2
+ import { Effect, FileSystem, Layer, Path, pipe } from "effect"
3
+ import { FileStore, FileStoreError, type IFileStore } from "../src/definition/file-store"
4
+ import type { TaskFile } from "../src/graph"
5
+
6
+ /** A file store in a directory every worker can reach. A file's reference is `<sha-256 of its bytes>/<name>`, so equal files are stored once. */
7
+ export class DirectoryFileStore implements IFileStore {
8
+ constructor(
9
+ private readonly fileSystem: FileSystem.FileSystem,
10
+ private readonly path: Path.Path,
11
+ private readonly root: string,
12
+ ) {}
13
+
14
+ *write(input: { readonly name: string; readonly bytes: Uint8Array }) {
15
+ const ref = `${createHash("sha256").update(input.bytes).digest("hex")}/${this.path.basename(input.name)}`
16
+ const target = this.path.join(this.root, ref)
17
+ yield* pipe(
18
+ this.fileSystem.makeDirectory(this.path.dirname(target), { recursive: true }),
19
+ Effect.andThen(this.fileSystem.writeFile(target, input.bytes)),
20
+ Effect.mapError((cause) => new FileStoreError({ file: input.name, cause })),
21
+ )
22
+ const file: TaskFile = { name: input.name, ref }
23
+ return file
24
+ }
25
+
26
+ *read(file: TaskFile) {
27
+ return yield* pipe(
28
+ this.fileSystem.readFile(this.path.join(this.root, file.ref)),
29
+ Effect.mapError((cause) => new FileStoreError({ file: file.name, cause })),
30
+ )
31
+ }
32
+ }
33
+
34
+ /** The directory file store as the `FileStore` an organization gives its workers; a relative root is resolved against the worker's working directory. */
35
+ export const directoryFileStoreLayer = (root: string): Layer.Layer<FileStore, never, FileSystem.FileSystem | Path.Path> =>
36
+ Layer.effect(
37
+ FileStore,
38
+ Effect.gen(function* () {
39
+ const path = yield* Path.Path
40
+ return new DirectoryFileStore(yield* FileSystem.FileSystem, path, path.resolve(root))
41
+ }),
42
+ )
@@ -0,0 +1,12 @@
1
+ export { DirectoryFileStore, directoryFileStoreLayer } from "./directory-file-store"
2
+ export {
3
+ ConvexWorkflowPlatformClient,
4
+ type IWorkflowPlatformClient,
5
+ PlatformCallFailed,
6
+ type CompleteInput,
7
+ type ReportedOtherWrite,
8
+ type TakenStep,
9
+ type WorkerFunctions,
10
+ WorkflowPlatformClient,
11
+ } from "./platform-client"
12
+ export { type ServicesOfWorkflows, WorkerLacksService, type WorkerOptions, type WorkerServices, type WorkResult, workForever, workOnce, workUntilIdle } from "./worker"