@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/steps.ts DELETED
@@ -1,1239 +0,0 @@
1
- /**
2
- * THE ONE WAY TO DEFINE A WORKFLOW AND ITS STEPS.
3
- *
4
- * A workflow states its phase (where the project shows it), its steps and the item it works on, and each step states
5
- * whether it needs an agent; nothing else defines a step. Every run of every step goes through the same code here, which
6
- * writes its one record (`storage/step-records.ts`): start, end, outcome, tokens, compiles, and a heartbeat while an agent
7
- * works. A dashboard derives all it says from those records and these declarations.
8
- *
9
- * const PICK = defineStep({ name: 'Pick', runs: 'deterministic', description: '...', at: import.meta.path, success: Schema.Number });
10
- * export const MyWorkflow = defineWorkflow({ phase: 'main', description: '...', at: import.meta.path, steps: () => [PICK],
11
- * graph: () => [{ from: RUN_STARTS, to: PICK.name, when: 'each run' }, { from: PICK.name, to: RUN_ENDS, when: 'always' }] })('My workflow', { payload, success, error, idempotencyKey });
12
- * ... yield* PICK.run(Effect.gen(...)); a repeating step gives its number: PICK.run(body, { call: 2 })
13
- *
14
- * Its `graph` says which step can follow which, and when, in plain words (`StepEdge`): a dashboard draws it, and a run that
15
- * takes an edge it does not declare fails in tests.
16
- *
17
- * A step can name the run's item from its result (`subject`), usually at Pick, and later steps inherit it. When the run
18
- * ends the definer records each item's real outcome (`outcomes`). A workflow with an agent step and a list of work needs no
19
- * trigger: the trigger (`keep-running.ts`) keeps its budget's number of runs of it going, so its payload is `{ run }`.
20
- *
21
- * AN ITEM IS TESTED BEFORE AN AGENT SEES IT. Alex, 2026-11-04: "work in the queue should probably undergo an initial round
22
- * of testing before the work gets handed to an agent". A no-agent test step (`defineItemTest`) comes before a workflow's
23
- * first agent step: an item that passes now is finished, with no agent and no tokens; one that fails gives the agent the
24
- * exact failure as its input; one that cannot be tested says why.
25
- *
26
- * An agent call needs `AgentStep`, which only a step that runs agentically (`runs: 'agentic'`) provides, so it cannot compile anywhere else.
27
- *
28
- * A BUDGET LIMITS THE AGENTS WORKING, NOT ONLY THE RUNS STARTED. Before each agent step, a run its workflow's budget has no
29
- * room for ends: oldest runs keep their places, so with 10 going and a budget of 5 exactly the newest 5 end, and no two runs
30
- * have to agree on anything. No agent call is cut off. The check is part of the step's activity, so a resumed run decides
31
- * the same way. The step fails with `STOOD_DOWN`, and the run ends through its failure path, or through its normal one where
32
- * it asks `isStoodDown`.
33
- *
34
- * EVERY ITEM IS A TASK, in one of four statuses read from its notes (`tasks.ts`). A Pick orders its own candidates through `pickOrder`, or
35
- * takes its queue's head; a Pick that finds nothing waits for an event that can change that (`picked`, `pick-wakes.ts`),
36
- * so a run never ends for want of an item.
37
- *
38
- * WHAT A STEP USES IS MEASURED, never reported (`step-meter.ts`): time, tokens, CPU, peak memory, files written and
39
- * compiles, on its one record. A step working on items says which: `subject` names the run's one, `eachItem` gives a batch
40
- * step one record per item, and a step whose work no one item owns declares `shared` rather than dividing it up.
41
- */
42
- import path from 'node:path';
43
- import { Cause, Context, Data, Effect, Exit, pipe, Result, Schedule, Schema, Semaphore } from 'effect';
44
- import { Activity, Workflow, WorkflowEngine } from 'effect/workflow';
45
- import { describeFailure, startAndEnd } from './failure';
46
- import { oneLine, standardReason } from './reasons';
47
- import type { ProcessIdentity, UsageSink } from './project';
48
- import type { PickWakes } from './pick-wakes';
49
- import { filesChanged, type StepFiles, type TreeHashes, type Undone } from './step-files';
50
- import { edgeDeclared, RUN_ENDS, RUN_STARTS, type StepEdge } from './graph';
51
- import { meterClosed, meterOpened, StepMeter } from './step-meter';
52
- import { runLimit, type LimitStore, type WorkflowLimits } from './storage/budgets';
53
- import type { EngineRecords } from './storage/engine-records';
54
- import { AGENT_BEAT_MS, noSpend, type StepRecords, type StepScope, type StepSpend } from './storage/step-records';
55
- import type { InputRecords } from './storage/input-records';
56
- import type { StorageError } from './storage/storage-error';
57
- import type { SpendingHold } from './spending-limit';
58
- import { inPickOrder, listOf, queueOrder, type PendingWork, type TaskInputs, type TaskRef, type Tasks, type TaskSummary } from './tasks';
59
-
60
- export { A_STEP_FAILS, edgeDeclared, isRetry, RUN_ENDS, RUN_STARTS, type StepEdge } from './graph';
61
-
62
- /** Where a workflow or step is defined, for its link: a file relative to the project's source root, and a text on the line. */
63
- export interface SourceRef {
64
- readonly path: string;
65
- readonly anchor: string;
66
- }
67
-
68
- /** A request's usage as the model's API reports it. */
69
- export interface ApiUsage {
70
- readonly input_tokens?: number | null;
71
- readonly cache_read_input_tokens?: number | null;
72
- readonly cache_creation_input_tokens?: number | null;
73
- readonly output_tokens?: number | null;
74
- }
75
-
76
- /** Provided only inside a step that runs agentically; an agent call reports what it spent through it. */
77
- export class AgentStep extends Context.Service<AgentStep, {
78
- /** A request's usage so far, by the message it belongs to, as it arrives: the step's record shows it at once. */
79
- readonly usage: (message: string, model: string | null, usage: ApiUsage) => void;
80
- /** A finished call's final figures, which replace its running sum. */
81
- readonly report: (spent: Partial<StepSpend>) => void;
82
- /** What the agent asked its tools to do, which attributes the files it changed. */
83
- readonly touched: (toolInputs: ReadonlyArray<string>) => void;
84
- /** What the step waits on that is not its agent, on its record; null once it no longer waits. */
85
- readonly waiting: (why: string | null) => void;
86
- }>()('AgentStep') {}
87
-
88
- /** The outcome of an item its test passed: finished, with no agent. */
89
- export const CLEARED_BY_TEST = 'cleared by its test, no agent';
90
-
91
- /** What an agent step fails with when its run is one too many for its workflow's budget. Stored as the step's result. */
92
- export const STOOD_DOWN = 'stood down: its workflow has more runs going than its budget';
93
- /**
94
- * What a step waiting for work or for an agent fails with when its process hands its runs to the next one
95
- * (`pick-wakes.ts` `releaseWaiting`): its run stands down untried, and the next process starts one.
96
- */
97
- export const HANDED_OVER = 'stood down: its process is handing its runs to the next';
98
- /**
99
- * What a step of a run a sub-workflow step started fails with once the run above it has ended: nothing is left to read its
100
- * result, so it does no more work. Two runs of Write C went on writing, an agent each, for ten minutes after the runs of
101
- * Decompile above them had failed (2026-11-19).
102
- */
103
- export const ABOVE_ENDED = 'stood down: the run above it has ended';
104
- /**
105
- * What an agent step of a run with a task fails with where no agent can be had (`untilAgentSlot`): its task went to the
106
- * back of its queue, marked as needing an agent, and the run gives its slot up untried.
107
- */
108
- export const NEEDS_AN_AGENT_STOOD_DOWN = 'stood down: no agent can be had, so its task went to the back of its queue, marked as needing one';
109
- export const isStoodDown = (failure: unknown): boolean =>
110
- failure === STOOD_DOWN || failure === HANDED_OVER || failure === ABOVE_ENDED || failure === NEEDS_AN_AGENT_STOOD_DOWN;
111
-
112
- /** Why no agent can be had at an agents' limit of 0, in words. */
113
- export const AGENTS_LIMIT_ZERO = "its agents' limit is 0";
114
-
115
- /**
116
- * Whether an agent step may take an agent now. Where not, `why` is what its record says, and `unavailable`, in words, is why
117
- * none can be had until a limit or a reading changes (an agents' limit of 0, the spending limit); none where one may free
118
- * when another run's agent step ends, or the limits could not be read.
119
- */
120
- export type AgentSlot = { readonly free: true } | { readonly free: false; readonly why: string; readonly unavailable: string | null };
121
-
122
- /** Whether a run is surplus: it is past the budget in the workflow's runs, oldest first. A run not listed is not counted. Pure. */
123
- export const surplusRun = (oldestFirst: ReadonlyArray<string>, run: string, budget: number): boolean => oldestFirst.indexOf(run) >= budget;
124
- /**
125
- /**
126
- * WHAT A STEP IS, as a page says it in words. Alex, 2026-11-19: "there are different kinds of workflow steps. like a check,
127
- * like a sub workflow."
128
- *
129
- * step does part of the work;
130
- * check decides whether the work passes;
131
- * sub-workflow a workflow used as a step of another workflow (`StepDeclaration.workflow` names it).
132
- */
133
- export const STEP_KINDS = ['step', 'check', 'sub-workflow'] as const;
134
- export type StepKind = (typeof STEP_KINDS)[number];
135
-
136
- /**
137
- * HOW A STEP RUNS, a separate question from what it is. Alex, 2026-11-19: "rather than 'no ai' or 'agent' I think a step
138
- * should be labeled as one of the following 'deterministic', 'agentic' or 'classification' where that third option allows
139
- * for steps which use a separate classifier model".
140
- *
141
- * deterministic code only;
142
- * agentic an agent does it: it waits for one of its workflow's agents (`untilAgentSlot`);
143
- * classification a separate classifier model decides.
144
- *
145
- * A step or a check is any of the three. A sub-workflow step states none: its workflow's own steps state theirs.
146
- */
147
- export const STEP_RUNS = ['deterministic', 'agentic', 'classification'] as const;
148
- export type StepRuns = (typeof STEP_RUNS)[number];
149
-
150
- /** A step's kind, from its declaration: the kind it states, a check where it is its workflow's test, a step otherwise. Pure. */
151
- export const stepKindOf = (s: Pick<StepDeclaration, 'test' | 'kind'>): StepKind => s.kind ?? (s.test === true ? 'check' : 'step');
152
-
153
- export interface StepDeclaration {
154
- readonly name: string;
155
- /** How it runs; none for a sub-workflow step. */
156
- readonly runs: StepRuns | null;
157
- /** What it is where it is not a plain step (`stepKindOf`). */
158
- readonly kind?: 'check' | 'sub-workflow';
159
- /** For a sub-workflow step: the workflow it runs, by name. */
160
- readonly workflow?: string;
161
- /** For a sub-workflow step: whether its workflow has an agent step, at any depth under it. */
162
- readonly agentUnder?: () => boolean;
163
- /** Whether this is the no-agent test an item goes through before any agent sees it. */
164
- readonly test?: boolean;
165
- /** One line on what it does, for its hover. */
166
- readonly description: string;
167
- /** Its link: the agent's prompt file, or the line that defines it. */
168
- readonly source: SourceRef;
169
- /** Whether its work is shared across items, so no item is charged for it. */
170
- readonly shared?: boolean;
171
- /** Whether it is a batch, with one record per item. */
172
- readonly perItem?: boolean;
173
- /** Whether it picks its run's work, waiting while there is none. */
174
- readonly picks?: boolean;
175
- /** Whether its result names the item its run works on (`subject`), which later steps inherit. */
176
- readonly namesItem?: boolean;
177
- /** The paths, from the project's root, whose changed files are counted to it: where it may write and where it writes. */
178
- readonly writes?: ReadonlyArray<string>;
179
- }
180
-
181
- /** What the test said of an item: it passes now, the exact failure the agent gets, or why it cannot be tested. */
182
- export const ItemTest = Schema.Union([
183
- Schema.Struct({ result: Schema.Literal('passes'), detail: Schema.String }),
184
- Schema.Struct({ result: Schema.Literal('fails'), failure: Schema.String }),
185
- Schema.Struct({ result: Schema.Literal('cannot'), why: Schema.String }),
186
- ]);
187
- export type ItemTest = typeof ItemTest.Type;
188
-
189
- /** What became of one item when its run ended. */
190
- export interface RunOutcome {
191
- /** The run's own item when absent. */
192
- readonly subject?: string;
193
- readonly outcome: string;
194
- /** Whether this ended the item's work: recovered, provided, fixed. */
195
- readonly finished: boolean;
196
- /**
197
- * Why the run's step blocked the item, where it did: no run starts on it again until a step or a person returns it to
198
- * the queue (`tasks.ts` `requeue`). Absent, it goes back to the queue.
199
- */
200
- readonly blocked?: string;
201
- }
202
-
203
- /** The check a workflow's finished items must pass, in plain words, and whether an outcome reached it. */
204
- export interface WorkflowGate {
205
- readonly says: string;
206
- readonly judged: (outcome: string) => boolean;
207
- }
208
-
209
- /** What a workflow works on: one item per run or several, or, stated, none. */
210
- export type WorkflowItem<Result> =
211
- | { readonly item: null }
212
- | {
213
- /** Its name for one, as a page says it: "function", "Windows call". */
214
- readonly item: string;
215
- /** A page's word for a finished one: "recovered", "provided", "fixed". */
216
- readonly finishedWord: string;
217
- /** From the run's result, each item's real outcome. */
218
- readonly outcomes: (result: Result) => ReadonlyArray<RunOutcome>;
219
- /** What accuracy means for it: the gate, and which outcomes that gate judged. A finished item is one that passed. */
220
- readonly gate?: WorkflowGate;
221
- };
222
-
223
- /**
224
- * WHAT A WORKFLOW RUNS ON, so it runs only when that changed. Alex approved it on 2026-11-12: "a workflow declares its
225
- * inputs and runs only when they change; each result is stored under its inputs and reused. A timer is only a fallback
226
- * check for changes." `read` gives a fingerprint of everything its result depends on, cheap to take; the trigger starts a
227
- * run only when it differs from its last successful run's (`runIfInputsChanged`).
228
- */
229
- export interface WorkflowInputs<R> {
230
- /** What its inputs are, in plain words, for its page. */
231
- readonly says: string;
232
- readonly read: () => Effect.Effect<string, unknown, R>;
233
- }
234
-
235
- /** A workflow as it states itself. `Phase` is where the project shows it; `R` what its list of work runs under. */
236
- export interface WorkflowDeclaration<Phase extends string = string, R = never> {
237
- readonly name: string;
238
- readonly phase: Phase;
239
- readonly description: string;
240
- readonly source: SourceRef;
241
- readonly steps: () => ReadonlyArray<StepDeclaration>;
242
- /** The item it works on and the word for a finished one; none where it works on no single item. */
243
- readonly item: string | null;
244
- readonly finishedWord: string | null;
245
- readonly gate: WorkflowGate | null;
246
- /** Starts one run, for the trigger alone. */
247
- readonly start: (run: string) => Effect.Effect<unknown, unknown, WorkflowEngine.WorkflowEngine>;
248
- /**
249
- * ITS LIST, in one of two kinds (`TaskStore.recordListing`). `pending`: its work left; an item that leaves it without a
250
- * passing final check is no longer its task, and a done one it lists again goes back to its queue. `items`: every item
251
- * it has a task for, done or not; its tasks' statuses move only by its runs and by calls. A workflow with an agent step
252
- * and a list runs only on its list.
253
- */
254
- readonly pending?: () => Effect.Effect<PendingWork, unknown, R>;
255
- readonly items?: () => Effect.Effect<ReadonlyArray<string>, unknown, R>;
256
- /** Its Pick takes the first task of its queue it can claim (`tasks.ts` `queueOrder`), so a dashboard lists that queue. */
257
- readonly picksQueueHead?: true;
258
- /**
259
- * The workflows whose results become its tasks: the arrows of the project's map (`views/workflow-flows.ts`). A workflow
260
- * used as a step of another needs none: it is drawn inside that one.
261
- */
262
- readonly fedBy?: ReadonlyArray<string>;
263
- /** Its step graph (`StepEdge`); none until it declares one. */
264
- readonly graph?: () => ReadonlyArray<StepEdge>;
265
- /** What it runs on (`WorkflowInputs`); none until it declares them, and it runs whenever its trigger says. */
266
- readonly inputs?: WorkflowInputs<R>;
267
- /**
268
- * What each of its tasks runs on now, by item (`TaskInputs`): a task whose last run left it with these, and no note since,
269
- * is not run again. None, and every task is run again.
270
- */
271
- readonly taskInputs?: () => Effect.Effect<ReadonlyMap<string, TaskInputs>, unknown, R>;
272
- /** Starts a run on `payload`, waiting for it to end or not. */
273
- readonly startOn: (payload: object, options: { readonly wait: boolean }) => Effect.Effect<void, unknown, WorkflowEngine.WorkflowEngine>;
274
- /** The engine's id for the run on `payload`: what its step records and its end carry. */
275
- readonly executionIdOf: (payload: object) => Effect.Effect<string>;
276
- }
277
-
278
- /** A run not started: its workflow's run limit was reached. What a start that waits for its result fails with. */
279
- export class RunLimitReached extends Data.TaggedError('RunLimitReached')<{ readonly workflow: string; readonly limit: number }> {}
280
-
281
- /** How often a workflow's refused starts are said, at most: a timer at 0 would say it every turn. */
282
- const REFUSED_SAID_EVERY_MS = 10 * 60 * 1000;
283
-
284
- /**
285
- * A WORKFLOW'S RUN LIMIT, whatever starts it: for one its budget keeps going, its run limit or its agents' limit
286
- * (`runLimit`); for any other its run limit, none meaning no limit. 0 starts nothing new. Pure.
287
- */
288
- export const runLimitOf = (d: Pick<WorkflowDeclaration<string, unknown>, 'pending' | 'items' | 'steps'>, limits: WorkflowLimits): number | null =>
289
- keptRunningByItsBudget(d) ? runLimit(limits) : limits.runs;
290
-
291
- /** Whether a workflow declares a list, of either kind: it has tasks and a queue. Pure. */
292
- export const hasAList = (d: Pick<WorkflowDeclaration<string, unknown>, 'pending' | 'items'>): boolean => d.pending !== undefined || d.items !== undefined;
293
-
294
- /** Whether a step uses an agent: it is an agent step, or a sub-workflow step whose workflow has one at any depth. Pure. */
295
- export const stepUsesAnAgent = (s: Pick<StepDeclaration, 'runs' | 'agentUnder'>): boolean => s.runs === 'agentic' || s.agentUnder?.() === true;
296
-
297
- /** Whether a workflow's budget rules it: a declared list, and an agent step of its own or under a sub-workflow step. Pure. */
298
- export const keptRunningByItsBudget = (d: Pick<WorkflowDeclaration<string, unknown>, 'pending' | 'items' | 'steps'>): boolean =>
299
- hasAList(d) && d.steps().some(stepUsesAnAgent);
300
-
301
-
302
- /** An unfinished run of a workflow with an agent step. */
303
- export interface AssignedRun<Phase extends string = string> {
304
- readonly workflow: string;
305
- readonly phase: Phase | 'upkeep';
306
- readonly run: string;
307
- readonly step: string;
308
- readonly subject: string | null;
309
- /** When it started, unix seconds. */
310
- readonly started: number;
311
- }
312
-
313
- const CurrentMeter = Context.Reference<StepMeter | null>('CurrentStepMeter', { defaultValue: () => null });
314
-
315
- /**
316
- * Whether this run stands down before its next agent call, whether its Pick, finding nothing, waits for work, and whether an
317
- * agent slot is free for it now.
318
- */
319
- export interface AgentBudgetRules {
320
- readonly standsDown: (workflow: string, run: string) => Effect.Effect<boolean>;
321
- readonly waitsForWork: (workflow: string, run: string) => Effect.Effect<boolean>;
322
- /** Its workflow's other runs in an agent step now are fewer than its agents' limit; why not, when they are not. */
323
- readonly agentSlot: (workflow: string, run: string) => Effect.Effect<AgentSlot>;
324
- }
325
-
326
- /** A workflow: what it states about itself, then `Workflow.make`'s own name and options. */
327
- type WorkflowBody = (payload: object, executionId: string) => Effect.Effect<unknown, unknown, unknown>;
328
- interface RunnableWorkflow {
329
- readonly execute: (payload: object, options?: { readonly discard: true }) => Effect.Effect<unknown, unknown, WorkflowEngine.WorkflowEngine>;
330
- readonly executionId: (payload: object) => Effect.Effect<string>;
331
- readonly toLayer: (execute: WorkflowBody) => unknown;
332
- }
333
-
334
- /** The definer of one project's workflows and steps, on its stores. */
335
- export const makeSteps = <Phase extends string, R>(deps: {
336
- readonly sourceRoot: string;
337
- readonly stepRecords: StepRecords;
338
- readonly engine: EngineRecords;
339
- readonly tasks: Tasks;
340
- readonly wakes: PickWakes;
341
- readonly budgets: LimitStore;
342
- readonly stepFiles: StepFiles;
343
- readonly CurrentStepUsage: Context.Reference<UsageSink | null>;
344
- readonly isTransientFailure: (failure: unknown) => boolean;
345
- /** This process, to tell its own records from another's. */
346
- readonly thisProcess: () => ProcessIdentity;
347
- readonly inputs: InputRecords;
348
- /** A workflow's queue changed with no wake of its Picks: one of them claimed an item (`queue-counts.ts`). */
349
- readonly queueChanged: (workflow: string) => void;
350
- /** What the spending limit does to an agent step now; none while it holds nothing (`spending-limit.ts`). */
351
- readonly spendingHoldsAgents: () => Effect.Effect<SpendingHold | null>;
352
- }) => {
353
- const { stepRecords: records, stepFiles } = deps;
354
- type Declaration = WorkflowDeclaration<Phase, R>;
355
- const DECLARED = new Map<string, Declaration>();
356
- const PICKING = new Map<string, Semaphore.Semaphore>();
357
- const RUN_ENDED = new Set<() => void>();
358
- const undeclaredSaid = new Set<string>();
359
- /** Each workflow's run items a mark was refused for, said once (`markedAsNeedingAnAgent`). */
360
- const offItsListSaid = new Set<string>();
361
- /**
362
- * EACH RUN'S LAST STEP, as this process ran it, until the run ends. A run resumed from another process has none here, and
363
- * the records of that process say; a record this process wrote for a run that has ended is no step of this one. Read from
364
- * the records alone, a test that names no records file saw every step as a run's first, and two tests reusing a run's id
365
- * saw the other's last step.
366
- */
367
- const lastStepRan = new Map<string, { readonly step: string; readonly failed: boolean }>();
368
- const lastStepBefore = (run: string): Effect.Effect<{ readonly step: string; readonly failed: boolean } | null, StorageError> => {
369
- const ran = lastStepRan.get(run);
370
- if (ran !== undefined) return Effect.succeed(ran);
371
- return Effect.map(records.lastStepOf(run), (recorded) => {
372
- const self = deps.thisProcess();
373
- return recorded === null || (recorded.owner !== null && recorded.owner.pid === self.pid && recorded.owner.startedAt === self.startedAt) ? null : recorded;
374
- });
375
- };
376
-
377
- /**
378
- * A RECORD FAILING TO WRITE NEVER FAILS THE STEP IT MEASURES: what the store could not write is said, and the step goes
379
- * on with none (`null`).
380
- */
381
- const recorded = <A>(what: string, write: Effect.Effect<A, StorageError>): Effect.Effect<A | null> =>
382
- Effect.catchTag(write, 'StorageError', (e) => Effect.as(Effect.logError(`[step-runs] ${what}: ${e.reason}`), null));
383
- /** The same from a callback outside any effect (a heartbeat, usage as it arrives): run at once, never waited for. */
384
- const recordNow = (what: string, write: Effect.Effect<unknown, StorageError>): void => { Effect.runFork(recorded(what, write)); };
385
-
386
- /** A file's path relative to the project's source root, from its absolute path. */
387
- const sourcePath = (absolute: string) => path.relative(deps.sourceRoot, absolute).split(path.sep).join('/');
388
-
389
- /** The runs of these workflows not finished now, oldest first. */
390
- const runsOldestFirst = (workflows: ReadonlyArray<string>): Effect.Effect<ReadonlyArray<string>, StorageError> => deps.engine.runsOldestFirst(workflows);
391
- /** The runs of a workflow not finished now, by the id its step records carry. */
392
- const runningRunIds = (workflow: string): Effect.Effect<ReadonlyArray<string>, StorageError> => deps.engine.runsOldestFirst([workflow]);
393
- /** Runs of a workflow not finished now. */
394
- const runningRuns = (workflow: string): Effect.Effect<number, StorageError> => deps.engine.runningRuns(workflow);
395
-
396
- /**
397
- * One item's part of a batch step: its own record under the step's, with its own time and CPU, and what it used added to
398
- * the step's. Outside a step it just runs the work.
399
- */
400
- const eachItem = <A, E, R2>(subject: string, work: Effect.Effect<A, E, R2>): Effect.Effect<A, E, R2> =>
401
- Effect.flatMap(CurrentMeter, (step) => {
402
- if (step === null) return work;
403
- return Effect.acquireUseRelease(
404
- Effect.gen(function* () {
405
- const id = step.record === null ? null : yield* recorded('open an item', records.openStepItem({ stepRun: step.record, subject }));
406
- const meter = new StepMeter(step.record, false, step.writes, step);
407
- meterOpened(meter);
408
- return { id, meter };
409
- }),
410
- ({ meter }) => pipe(work, Effect.provideService(deps.CurrentStepUsage, meter)),
411
- ({ id, meter }, exit) => Effect.gen(function* () {
412
- meterClosed(meter);
413
- if (id !== null) yield* recorded('close an item', records.closeStepItem({ id, outcome: Exit.isSuccess(exit) ? 'success' : Cause.hasInterrupts(exit.cause) ? 'interrupted' : 'failure', used: meter.used() }));
414
- }),
415
- );
416
- });
417
-
418
- /**
419
- * Whether this run should stand down before its next agent call, and whether its Pick, finding nothing it can claim, waits
420
- * for work rather than ending its run. A test supplies others.
421
- */
422
- /**
423
- * A declared workflow's limits: its run limit (`runLimitOf`, none for no limit), and its agents' limit where its budget
424
- * keeps it going (none for any other). None for one not declared, or with no store to read.
425
- */
426
- const limitsOf = (workflow: string): Effect.Effect<{ readonly runs: number | null; readonly agents: number | null } | null, StorageError> => {
427
- const d = DECLARED.get(workflow);
428
- if (d === undefined) return Effect.succeed(null);
429
- return Effect.map(deps.budgets.limitsOf(workflow), (limits) => (limits === null ? null : { runs: runLimitOf(d, limits), agents: keptRunningByItsBudget(d) ? limits.agents : null }));
430
- };
431
- /** Whether a run is past the runs its workflow's run limit keeps, oldest first; never where it has no run limit. */
432
- const pastItsRunLimit = (workflow: string, run: string): Effect.Effect<boolean, StorageError> =>
433
- Effect.flatMap(limitsOf(workflow), (w) => {
434
- const runs = w === null ? null : w.runs;
435
- return runs === null ? Effect.succeed(false) : Effect.map(runsOldestFirst([workflow]), (going) => surplusRun(going, run, runs));
436
- });
437
-
438
- /**
439
- * LIMITS THAT CANNOT BE READ HOLD THE RUN WHERE IT IS: it does not stand down, its Pick waits, and its agent step waits for a
440
- * slot, each until the next wake reads them again. Read as no limits, a store that failed would start agents at 0.
441
- */
442
- const unreadLimits = <A>(workflow: string, held: (why: string) => A) => (e: StorageError): Effect.Effect<A> =>
443
- Effect.as(Effect.logError(`[budget] ${workflow}: its limits could not be read (${e.reason}); its runs wait`), held(e.reason));
444
-
445
- /**
446
- * THE RUN AT THE TOP OF A RUN: itself, or, for a run a sub-workflow step started, the run at the top of those above it
447
- * (`StepRecords.rootOfRun`). A workflow's limits govern every run under its runs, so a sub-workflow's agent step counts
448
- * against the agents' limit of the workflow at the top. Kept while the run goes: it never changes.
449
- */
450
- const TOPS = new Map<string, { readonly run: string; readonly workflow: string }>();
451
- /** Each workflow's start with no run limit asked, by name: what a sub-workflow step starts it by (`defineSubWorkflow`). */
452
- const STARTS_AS_A_STEP = new Map<string, (payload: unknown) => Effect.Effect<unknown, unknown, unknown>>();
453
- const topOf = (workflow: string, run: string): Effect.Effect<{ readonly run: string; readonly workflow: string }, StorageError> => {
454
- const known = TOPS.get(run);
455
- if (known !== undefined) return Effect.succeed(known);
456
- return Effect.map(records.rootOfRun(run), (root) => {
457
- const top = root ?? { run, workflow };
458
- TOPS.set(run, top);
459
- return top;
460
- });
461
- };
462
-
463
- const AgentBudgets = Context.Reference<AgentBudgetRules>('AgentBudgets', {
464
- defaultValue: () => ({
465
- // Among its workflow's unfinished runs, oldest first, the run is past those its run limit keeps (`runLimit`). A run not
466
- // listed is not counted. A run a sub-workflow step started stands down with the run at its top.
467
- standsDown: (workflow, run) => pipe(
468
- topOf(workflow, run),
469
- Effect.flatMap((top) => Effect.zipWith(pastItsRunLimit(workflow, run), top.run === run ? Effect.succeed(false) : pastItsRunLimit(top.workflow, top.run), (own, above) => own || above)),
470
- Effect.catchTag('StorageError', unreadLimits(workflow, () => false)),
471
- ),
472
- waitsForWork: (workflow, run) => pipe(pastItsRunLimit(workflow, run), Effect.map((past) => !past), Effect.catchTag('StorageError', unreadLimits(workflow, () => true))),
473
- // The other runs of the workflow at its top that an agent works for, a waiting one not counted, against that
474
- // workflow's agents' limit: at 0 none is ever free, which no agent ending changes.
475
- agentSlot: (workflow, run) => pipe(
476
- topOf(workflow, run),
477
- Effect.flatMap((top) => Effect.flatMap(limitsOf(top.workflow), (w): Effect.Effect<AgentSlot, StorageError> => {
478
- const agents = w === null ? null : w.agents;
479
- if (agents === null) return Effect.succeed({ free: true });
480
- if (agents === 0) return Effect.succeed({ free: false, why: `waits for an agent: ${AGENTS_LIMIT_ZERO}`, unavailable: AGENTS_LIMIT_ZERO });
481
- return Effect.map(Effect.all({ runs: runsOldestFirst([top.workflow]), inAgentStep: records.runsInAgentStep(top.workflow) }), ({ runs, inAgentStep }): AgentSlot => {
482
- const going = new Set(runs);
483
- const busy = inAgentStep.filter((r) => r !== top.run && going.has(r)).length;
484
- return busy < agents ? { free: true } : { free: false, why: `waits for an agent: ${busy} of its ${agents} in use`, unavailable: null };
485
- });
486
- })),
487
- Effect.catchTag('StorageError', unreadLimits(workflow, (why): AgentSlot => ({ free: false, why: `waits for an agent: its limits could not be read (${why})`, unavailable: null }))),
488
- ),
489
- }),
490
- });
491
-
492
- /** The task a run at the top works on: its workflow's, where that workflow has a list, on the run's item; none otherwise. */
493
- const taskOfTop = (top: { readonly run: string; readonly workflow: string }): Effect.Effect<TaskRef | null> => {
494
- const d = DECLARED.get(top.workflow);
495
- if (d === undefined || !hasAList(d)) return Effect.succeed(null);
496
- return Effect.map(Effect.orElseSucceed(records.subjectOfRun(top.run), () => null), (item) => (item === null ? null : { workflow: top.workflow, item }));
497
- };
498
-
499
- /**
500
- * Marks the task of the run at the top as needing an agent; whether it was marked (a run with no task, or no store, is not).
501
- *
502
- * ONLY A TASK ITS PICK READS IS MARKED (`tasks.ts` `readByItsPick`). A mark on any other passes over nothing: the run
503
- * ends, the next takes the same work and ends the same way. Fix conflicts' runs named conflicts while its list named
504
- * functions, and it took the same 3 names 907 times in 75 minutes (2026-11-20). Such a run is a fault in its workflow,
505
- * which names its run's item differently from its list: in a test it fails the run, and live it is said once, and the
506
- * run waits for an agent as a run with no task does. A task whose state cannot be read is marked as before.
507
- */
508
- const markedAsNeedingAnAgent = (top: { readonly run: string; readonly workflow: string }, step: string, why: string): Effect.Effect<boolean> =>
509
- Effect.flatMap(taskOfTop(top), (task) => {
510
- if (task === null) return Effect.succeed(false);
511
- return Effect.flatMap(Effect.orElseSucceed(deps.tasks.readByItsPick(task), () => true), (read) => {
512
- if (read) return deps.tasks.markNeedsAgent({ task, by: { workflow: top.workflow, run: top.run, step }, why });
513
- const fault = `${top.workflow}: its run ${top.run} works on ${task.item}, which is not a task its Pick reads (not on its list, nor returned to its queue), so a mark at ${step} would pass over nothing; it waits for an agent instead`;
514
- if (process.env.NODE_ENV === 'test') return Effect.die(new Error(fault));
515
- if (!offItsListSaid.has(`${top.workflow}\n${task.item}`)) {
516
- offItsListSaid.add(`${top.workflow}\n${task.item}`);
517
- console.error(`[agents] ${fault}`);
518
- }
519
- return Effect.succeed(false);
520
- });
521
- });
522
-
523
- /**
524
- * WHY NO AGENT CAN BE HAD FOR A WORKFLOW'S RUNS NOW, in words; none where one can: the spending limit holds, or its
525
- * agents' limit is 0. While it says so, its Pick passes over its tasks marked as needing an agent, and those with nothing
526
- * new since their last run (`queueNow`, `pickOrder`, `tasks.ts` `passedOverWithoutAnAgent`), and takes them in their
527
- * queue's order again once an agent can be had. A limit that cannot be read passes over none.
528
- */
529
- const agentsUnavailable = (workflow: string): Effect.Effect<string | null> => Effect.gen(function* () {
530
- const held = yield* deps.spendingHoldsAgents();
531
- if (held !== null && held.unavailable !== null) return held.unavailable;
532
- const limits = yield* Effect.orElseSucceed(limitsOf(workflow), () => null);
533
- return limits !== null && limits.agents === 0 ? AGENTS_LIMIT_ZERO : null;
534
- });
535
-
536
- /**
537
- * AN AGENT STEP TAKES AN AGENT SLOT FIRST: with its workflow's agents' limit in use by its other runs it waits, its record
538
- * saying so, until an agent step ends or a limit changes (`pick-wakes.ts`), and never polls. Its record starts again when
539
- * it has a slot, since the wait was no work. A limit lowered meanwhile to 0 agents, or below its run, stands it down.
540
- * While the spending limit holds (`spending-limit.ts`) every agent step waits the same way, in every workflow, until a
541
- * reading below it or a new limit wakes it.
542
- *
543
- * A RUN WITH A TASK DOES NOT WAIT WHERE NO AGENT CAN BE HAD (its workflow's agents' limit is 0, or the spending limit
544
- * holds): it marks its task as needing an agent, which puts it at the back of its queue (`tasks.ts` `markNeedsAgent`),
545
- * and ends, giving its run slot to work that needs none. Its Pick passes over such tasks while no agent is available
546
- * (`agentsUnavailable`). Waiting, a few such runs filled every run slot of Decompile and nothing behind them moved
547
- * (2026-11-20). A run with no task, or one waiting for an agent another run holds, still waits here.
548
- *
549
- * A step that gets past it took an agent, and clears its task's mark when it ends (`measured`, `agentStepRan`).
550
- */
551
- const untilAgentSlot = (instance: { readonly workflow: { readonly _tag: string }; readonly executionId: string }, step: string, record: () => number | null) => Effect.gen(function* () {
552
- const rules = yield* AgentBudgets;
553
- const workflow = instance.workflow._tag;
554
- // An agent is freed, and a limit set, on the workflow at the top of this run: its wakes are the ones this wait hears.
555
- const top = yield* Effect.orElseSucceed(topOf(workflow, instance.executionId), () => ({ run: instance.executionId, workflow }));
556
- const heardOn = top.workflow;
557
- let waited = false;
558
- for (;;) {
559
- const wakes = deps.wakes.pickWakesSoFar(heardOn);
560
- if (yield* rules.standsDown(workflow, instance.executionId)) return yield* Effect.fail(STOOD_DOWN);
561
- const spendingHeld = yield* deps.spendingHoldsAgents();
562
- const slot: AgentSlot = spendingHeld !== null ? { free: false, why: spendingHeld.why, unavailable: spendingHeld.unavailable } : yield* rules.agentSlot(workflow, instance.executionId);
563
- const id = record();
564
- if (slot.free) {
565
- if (waited && id !== null) {
566
- yield* recorded('end its wait', records.setStepWaiting({ id, waiting: null }));
567
- yield* recorded('start its record again', records.restartStepRun(id));
568
- }
569
- return;
570
- }
571
- if (slot.unavailable !== null && (yield* markedAsNeedingAnAgent(top, step, slot.unavailable))) {
572
- console.log(`[agents] ${workflow} run ${instance.executionId} ended at its agent step: no agent can be had (${slot.unavailable}); its task goes to the back of its queue, marked as needing one`);
573
- return yield* Effect.fail(NEEDS_AN_AGENT_STOOD_DOWN);
574
- }
575
- if (id !== null) yield* recorded('say what it waits on', records.setStepWaiting({ id, waiting: slot.why }));
576
- waited = true;
577
- if ((yield* deps.wakes.untilPickWoken({ workflow: heardOn, after: wakes })) === 'released') return yield* Effect.fail(HANDED_OVER);
578
- }
579
- });
580
-
581
- /**
582
- * A RUN OF A WORKFLOW WITH A LIST WORKS ON ONE OF ITS TASKS: the item its Pick named, which every later step inherits. A
583
- * step naming another is the fault `markedAsNeedingAnAgent` guards against, caught where it is made: in tests it fails
584
- * the run; live, it is said once.
585
- */
586
- const checkItem = (workflow: string, run: string, step: string, item: string | null): Effect.Effect<void> => Effect.gen(function* () {
587
- const d = DECLARED.get(workflow);
588
- if (item === null || d === undefined || !hasAList(d)) return;
589
- const named = yield* Effect.orElseSucceed(records.subjectOfRun(run), () => null);
590
- if (named === null || named.toLowerCase() === item.toLowerCase()) return;
591
- const fault = `${workflow}: its step ${step} names ${item}, while its run works on ${named}: a run of a workflow with a list works on one of its tasks`;
592
- if (process.env.NODE_ENV === 'test') throw new Error(fault);
593
- if (!undeclaredSaid.has(fault)) {
594
- undeclaredSaid.add(fault);
595
- console.error(`[steps] ${fault}`);
596
- }
597
- });
598
-
599
- /** Checks the move to `step` against its workflow's graph: in tests an undeclared one fails the run; live, it is said once. */
600
- const checkEdge = (workflow: string, run: string, step: string): Effect.Effect<void> => Effect.gen(function* () {
601
- const graph = DECLARED.get(workflow)?.graph?.();
602
- if (graph === undefined) return;
603
- const read = yield* Effect.result(lastStepBefore(run));
604
- // With its last step unread, the move cannot be checked; it is said, and the step goes on.
605
- if (Result.isFailure(read)) return yield* Effect.logError(`[steps] ${workflow}: the move to ${step} was not checked: ${read.failure.reason}`);
606
- const last = read.success;
607
- if (edgeDeclared(graph, last, step)) return;
608
- const move = `${workflow}: ${last === null ? RUN_STARTS : `${last.step}${last.failed ? ' (failed)' : ''}`} to ${step}`;
609
- if (process.env.NODE_ENV === 'test') throw new Error(`a run took an edge its workflow does not declare: ${move}`);
610
- if (!undeclaredSaid.has(move)) {
611
- undeclaredSaid.add(move);
612
- console.error(`[steps] a run took an edge its workflow does not declare: ${move}`);
613
- }
614
- });
615
-
616
- /** Runs `execute` as this step of the workflow it is in, and writes its record. */
617
- const measured = <A, E, R2>(step: StepDeclaration, call: number | null, subject: string | null, subjectOf: ((a: A) => string | null) | undefined, reasonOf: ((a: A) => string | null) | undefined, mayWrite: ReadonlyArray<string> | undefined, execute: Effect.Effect<A, E, R2>, childRun: string | null = null) =>
618
- Effect.flatMap(WorkflowEngine.WorkflowInstance, (instance) => {
619
- // A call's running sum is by request; its final figures replace it. `settled` is what finished calls reported.
620
- const settled = noSpend();
621
- const running = new Map<string, StepSpend>();
622
- const spendNow = (): StepSpend => {
623
- const out = { ...settled };
624
- for (const r of running.values()) {
625
- out.fresh += r.fresh; out.cacheWrite += r.cacheWrite; out.cacheRead += r.cacheRead; out.output += r.output; out.requests += 1;
626
- }
627
- return out;
628
- };
629
- const usage = (message: string, model: string | null, u: ApiUsage) => {
630
- const was = running.get(message) ?? noSpend();
631
- running.set(message, {
632
- ...was,
633
- fresh: u.input_tokens ?? was.fresh,
634
- cacheRead: u.cache_read_input_tokens ?? was.cacheRead,
635
- cacheWrite: u.cache_creation_input_tokens ?? was.cacheWrite,
636
- output: u.output_tokens ?? was.output,
637
- });
638
- if (recordId !== null) recordNow('its spend so far', records.updateStepSpend({ id: recordId, spend: spendNow(), model }));
639
- };
640
- const report = (spent: Partial<StepSpend>) => {
641
- const requests = running.size;
642
- running.clear();
643
- for (const [k, v] of Object.entries(spent)) settled[k as keyof StepSpend] += v ?? 0;
644
- if (spent.requests === undefined) settled.requests += requests;
645
- };
646
- const toolInputs: string[] = [];
647
- let before: TreeHashes | null = null;
648
- let recordId: number | null = null;
649
- let meter = new StepMeter(null, (step.runs === 'agentic'), [], null);
650
- /** Whether this agent step took an agent: past its slot, its task's mark as needing one clears when it ends. */
651
- let tookAnAgent = false;
652
- return Effect.acquireUseRelease(
653
- Effect.flatMap(Effect.gen(function* () {
654
- yield* checkEdge(instance.workflow._tag, instance.executionId, step.name);
655
- yield* checkItem(instance.workflow._tag, instance.executionId, step.name, subject);
656
- // A sub-workflow step is run again when its workflow has ended: it takes its open record up again, and names the run it started.
657
- const id = yield* recorded('open its record', records.openStepRun({ workflow: instance.workflow._tag, run: instance.executionId, step: step.name, call, agent: (step.runs === 'agentic'), subject, ...(childRun === null ? {} : { resume: true as const }) }));
658
- if (id !== null && childRun !== null) yield* recorded('name the run it started', records.setStepChild({ id, childRun }));
659
- const beat = (step.runs === 'agentic') && id !== null ? setInterval(() => recordNow('its heartbeat', records.beatStepRun(id)), AGENT_BEAT_MS) : null;
660
- recordId = id;
661
- meter = new StepMeter(id, (step.runs === 'agentic'), step.writes ?? [], null);
662
- meterOpened(meter);
663
- return { id, beat };
664
- }), (opened) => (mayWrite === undefined
665
- ? Effect.succeed(opened)
666
- : Effect.map(Effect.promise(async () => {
667
- const hashes = await stepFiles.treeHashes();
668
- if (opened.id !== null) await stepFiles.snapshotTree(stepFiles.snapshotOf(opened.id), hashes);
669
- return hashes;
670
- }), (hashes) => {
671
- before = hashes;
672
- return opened;
673
- }))),
674
- () => pipe(
675
- (step.runs === 'agentic') ? Effect.andThen(untilAgentSlot(instance, step.name, () => recordId), Effect.andThen(Effect.sync(() => { tookAnAgent = true; }), execute)) : execute,
676
- // What it changed, on its record, and a change it named outside where it may write refuses the step.
677
- Effect.tap(() => Effect.suspend(() => {
678
- const earlier = before;
679
- if (earlier === null || mayWrite === undefined) return Effect.void;
680
- return Effect.flatMap(Effect.promise(() => stepFiles.treeHashes()), (after) => Effect.gen(function* () {
681
- const files = filesChanged(earlier, after, mayWrite, toolInputs);
682
- const snapshot = recordId === null ? null : stepFiles.snapshotOf(recordId);
683
- if (snapshot !== null) stepFiles.keepWhatItChanged(snapshot, files.attributed);
684
- if (recordId !== null) yield* recorded('the files it changed', records.recordStepFiles({ id: recordId, files: JSON.stringify({ ...files, snapshot }) }));
685
- // Refused here means undone here: a change that stayed would make the refusal decorative.
686
- if (snapshot !== null) stepFiles.undoFiles(snapshot, files.refused);
687
- return files.refused.length === 0 ? yield* Effect.void : yield* Effect.fail(`refused: it changed ${files.refused.join(', ')}, outside ${mayWrite.join(', ') || 'nothing it may write'}` as never);
688
- }));
689
- })),
690
- Effect.provideService(CurrentMeter, meter),
691
- Effect.provideService(deps.CurrentStepUsage, meter),
692
- (step.runs === 'agentic') ? Effect.provideService(AgentStep, { usage, report, touched: (inputs) => { toolInputs.push(...inputs); }, waiting: (why) => { if (recordId !== null) recordNow('say what it waits on', records.setStepWaiting({ id: recordId, waiting: why })); } }) : (e) => e,
693
- ) as Effect.Effect<A, E, Exclude<R2, AgentStep>>,
694
- ({ id, beat }, exit) => Effect.gen(function* () {
695
- if (beat !== null) clearInterval(beat);
696
- // An agent step that ran on a task marked as needing an agent clears the mark: it may need none now.
697
- if (tookAnAgent && (Exit.isSuccess(exit) || !Cause.hasInterrupts(exit.cause))) {
698
- const top = TOPS.get(instance.executionId) ?? { run: instance.executionId, workflow: instance.workflow._tag };
699
- const task = yield* taskOfTop(top);
700
- if (task !== null) yield* deps.tasks.agentStepRan({ task, by: { workflow: top.workflow, run: top.run, step: step.name } });
701
- }
702
- // Its agent slot is free for its workflow's next run waiting on one.
703
- if ((step.runs === 'agentic')) deps.wakes.wakePicksOf(TOPS.get(instance.executionId)?.workflow ?? instance.workflow._tag, 'an agent step ended');
704
- // An interrupted step is no move: the run does it again.
705
- if (Exit.isSuccess(exit) || !Cause.hasInterrupts(exit.cause)) lastStepRan.set(instance.executionId, { step: step.name, failed: !Exit.isSuccess(exit) });
706
- meterClosed(meter);
707
- if (id === null) return;
708
- const spend = spendNow();
709
- const used = meter.used();
710
- const named = Exit.isSuccess(exit) ? subjectOf?.(exit.value) ?? null : null;
711
- yield* checkItem(instance.workflow._tag, instance.executionId, step.name, named);
712
- // A batch that started no process and recorded no item had none to do; one that worked outside `eachItem` stays undeclared.
713
- const idleBatch = step.perItem === true && Exit.isSuccess(exit) && used.childCpuSeconds === 0 && used.compiles === 0;
714
- const scope: StepScope = meter.items > 0 ? 'functions' : step.shared === true ? 'shared' : idleBatch ? 'none due' : subjectOf !== undefined && Exit.isSuccess(exit) && named === null ? 'nothing' : 'undeclared';
715
- if (Exit.isSuccess(exit)) yield* recorded('close its record', records.closeStepRun({ id, outcome: 'success', reason: (reasonOf ?? standardReason)(exit.value), error: null, spend, subject: named, used, scope }));
716
- // A sub-workflow step whose run is suspended until its workflow ends is still in that step: its record stays open.
717
- else if (Cause.hasInterrupts(exit.cause) && childRun !== null && instance.suspended) yield* Effect.void;
718
- else if (Cause.hasInterrupts(exit.cause)) yield* recorded('close its record', records.closeStepRun({ id, outcome: 'interrupted', reason: 'interrupted', error: null, spend, subject: null, used, scope }));
719
- else yield* recorded('close its record', records.closeStepRun({ id, outcome: 'failure', reason: oneLine(describeFailure(Cause.squash(exit.cause))), error: describeFailure(Cause.squash(exit.cause)), spend, subject: null, used, scope }));
720
- }),
721
- );
722
- });
723
-
724
- /**
725
- * TAKES BACK WHAT THIS RUN'S AGENT STEP CHANGED, from that step's record: the one way a refused change leaves the tree. Run
726
- * it as a step of its own, then rebuild, or the tree still holds what was refused.
727
- */
728
- const undoAgentStep = (stepName: string): Effect.Effect<Undone, StorageError, WorkflowEngine.WorkflowInstance> =>
729
- Effect.flatMap(WorkflowEngine.WorkflowInstance, (instance) => Effect.map(records.stepFilesOf({ run: instance.executionId, step: stepName }), (record) => {
730
- if (record === null) return { restored: [], conflicts: [] };
731
- const { snapshot, attributed } = JSON.parse(record) as { readonly snapshot: string | null; readonly attributed?: ReadonlyArray<string> };
732
- return snapshot === null ? { restored: [], conflicts: [] } : stepFiles.undoFiles(snapshot, attributed ?? []);
733
- }));
734
-
735
- /**
736
- * A RUN PAST ITS WORKFLOW'S RUN LIMIT ENDS BEFORE IT TAKES ON MORE WORK, inside the step's activity. It fails with
737
- * `STOOD_DOWN`. At a run limit of 0 every run is past it, so each run already going ends this way.
738
- *
739
- * A workflow its budget keeps going before an agent step, and nowhere else: a run past its limit still picks and
740
- * (`keptRunningByItsBudget`) tests with no agent, so an item its test clears is finished at no cost, and its
741
- * Pick ends its run where it finds nothing (`untilPicked`).
742
- * Any other workflow before a Pick, before an agent step, and before the first step this process runs
743
- * of it (a run the engine resumed after a restart): nothing else would end its run.
744
- *
745
- * A step between those goes on, so what an agent step just made is still checked and recorded.
746
- */
747
- const standDownIfSurplus = (step: { readonly agent: boolean; readonly picks: boolean }) => Effect.flatMap(WorkflowEngine.WorkflowInstance, (instance) =>
748
- // A run a sub-workflow step started is its top run's work: its steps stand down as that run's own would, by that
749
- // workflow's budget. Asked of its own, a step with no agent stood the run above down where that run's own never would.
750
- Effect.flatMap(Effect.orElseSucceed(topOf(instance.workflow._tag, instance.executionId), () => ({ run: instance.executionId, workflow: instance.workflow._tag })), (top) => Effect.flatMap(
751
- // IT ENDS WITH THE RUN ABOVE IT. Once that run has ended (failed, or stopped), no step of this one starts: its result
752
- // would be read by nothing. A read of the engine's records that fails stops no step.
753
- top.run === instance.executionId ? Effect.succeed(false) : Effect.orElseSucceed(Effect.map(runsOldestFirst([top.workflow]), (unfinished) => !unfinished.includes(top.run)), () => false),
754
- (aboveEnded) => {
755
- if (aboveEnded) {
756
- console.log(`[run limit] ${instance.workflow._tag} run ${instance.executionId} stood down: the ${top.workflow} run above it, ${top.run}, has ended`);
757
- return Effect.fail(ABOVE_ENDED);
758
- }
759
- const declared = DECLARED.get(top.workflow);
760
- const budgetKeepsIt = declared !== undefined && keptRunningByItsBudget(declared);
761
- if (!step.agent && (budgetKeepsIt || (!step.picks && lastStepRan.has(instance.executionId)))) return Effect.void;
762
- return Effect.flatMap(AgentBudgets, (budgets) => Effect.flatMap(budgets.standsDown(instance.workflow._tag, instance.executionId), (surplus) => {
763
- if (!surplus) return Effect.void;
764
- console.log(`[run limit] ${instance.workflow._tag} run ${instance.executionId} stood down: its workflow has more runs going than its run limit`);
765
- return Effect.fail(STOOD_DOWN);
766
- }));
767
- },
768
- )));
769
-
770
- /** One run of a workflow picks at a time: its choice is on its step record before the next reads what is taken. */
771
- const pickingOneAtATime = <A, E, R2>(workflow: string, pick: Effect.Effect<A, E, R2>): Effect.Effect<A, E, R2> => {
772
- const lock = PICKING.get(workflow) ?? Semaphore.makeUnsafe(1);
773
- PICKING.set(workflow, lock);
774
- return lock.withPermits(1)(pick);
775
- };
776
-
777
- /** Why a Pick waits, on its open record: its queued tasks, none of which it can claim now, and what wakes it. */
778
- const nothingToClaim = (workflow: string): Effect.Effect<string> => pipe(
779
- deps.tasks.taskSummaries({ workflow }),
780
- Effect.map((tasks) => {
781
- const queued = queueOrder(tasks);
782
- const needAnAgent = queued.filter((t) => deps.tasks.passedOverNow(t) !== null).length;
783
- return `${queued.length} queued${queued.length === 0 ? '' : ', none it can claim now'}${needAnAgent === 0 ? '' : `, ${needAnAgent} of them passed over as needing an agent or with nothing new since their last run`}`;
784
- }),
785
- Effect.catchTag('StorageError', (e) => Effect.succeed(`its tasks could not be read: ${e.reason}`)),
786
- Effect.map((queued) => `no task it can claim (${queued}); it waits for a task returned to its queue, a new item, a run ending or a limit change`),
787
- );
788
-
789
- /**
790
- * A PICK THAT FINDS NOTHING IT CAN CLAIM WAITS FOR AN EVENT THAT CAN CHANGE THAT (`pick-wakes.ts`), and never polls: one
791
- * open record, its `waiting` saying on what, and no new record while nothing changes. The run keeps its place in its
792
- * workflow's count, and its record starts again when it found an item, since the wait was no work. It ends with nothing
793
- * when its run is past the runs its run limit keeps (`runLimit`), or when no agent can be had and nothing in its queue
794
- * can be taken without one (`whyNoRunCanTakeWork`): kept waiting there, 4 Decompile runs held their run slots for 51
795
- * minutes on 2026-11-20 with each of its 751 queued tasks marked, and showed as running.
796
- */
797
- const untilPicked = <A, E, R2>(picked: (a: A) => boolean, pick: Effect.Effect<A, E, R2>) => Effect.gen(function* () {
798
- const instance = yield* WorkflowEngine.WorkflowInstance;
799
- const workflow = instance.workflow._tag;
800
- const budgets = yield* AgentBudgets;
801
- const meter = yield* CurrentMeter;
802
- const record = meter?.record ?? null;
803
- let waited = false;
804
- for (;;) {
805
- const wakes = deps.wakes.pickWakesSoFar(workflow);
806
- const began = performance.now();
807
- const found = yield* pickingOneAtATime(workflow, pick);
808
- if (waited) deps.wakes.countRePick(workflow, performance.now() - began);
809
- // With no agent to be had and nothing it can take, it ends rather than wait (`whyNoRunCanTakeWork`).
810
- const noWork = picked(found) ? null : yield* noWorkByInputsLastRead(workflow);
811
- if (noWork !== null) console.log(`[agents] ${workflow} run ${instance.executionId} ended at its Pick: ${noWork}`);
812
- if (picked(found) || noWork !== null || !(yield* budgets.waitsForWork(workflow, instance.executionId))) {
813
- if (picked(found)) deps.queueChanged(workflow);
814
- if (waited && record !== null) {
815
- yield* recorded('end its wait', records.setStepWaiting({ id: record, waiting: null }));
816
- yield* recorded('start its record again', records.restartStepRun(record));
817
- }
818
- return found;
819
- }
820
- if (record !== null) yield* recorded('say what it waits on', records.setStepWaiting({ id: record, waiting: yield* nothingToClaim(workflow) }));
821
- waited = true;
822
- if ((yield* deps.wakes.untilPickWoken({ workflow, after: wakes })) === 'released') return yield* Effect.fail(HANDED_OVER);
823
- }
824
- });
825
-
826
- /** A step: its declaration, and `run`, the only way to run it. */
827
- const defineStep = <A>(d: {
828
- readonly name: string;
829
- /** How it runs (`StepRuns`). */
830
- readonly runs: StepRuns;
831
- readonly description: string;
832
- /** `import.meta.path`, for its link. */
833
- readonly at: string;
834
- /** The agent's prompt file, for its link. */
835
- readonly prompt?: SourceRef;
836
- readonly success: Schema.Codec<A, unknown>;
837
- /** The item this step's result says the run works on; later steps inherit it. */
838
- readonly subject?: (a: A) => string | null;
839
- /** For an agent step with tools: the paths, from the project's root, it may change (`step-files.ts`). */
840
- readonly mayWrite?: ReadonlyArray<string>;
841
- /** A check decides whether the work passes (`StepKind`); absent, a plain step. */
842
- readonly kind?: 'check';
843
- /** Marks the no-agent test an item goes through first. Use `defineItemTest` where the step only tests. */
844
- readonly test?: true;
845
- /** Its work is shared across items (a whole-tree build): no item is charged, and a page says so. */
846
- readonly shared?: true;
847
- /** A batch: it works on several items, each in `eachItem`. */
848
- readonly perItem?: true;
849
- /** The paths, from the project's root, it writes: files changed there are counted to it. */
850
- readonly writes?: ReadonlyArray<string>;
851
- /**
852
- * Marks the step that picks the run's work, and says from its result whether it found any. It runs one pick of its
853
- * workflow at a time, and with nothing found it waits for an event that can change that (`pick-wakes.ts`), until it finds
854
- * some or its run is past those its budget keeps.
855
- */
856
- readonly picked?: (a: A) => boolean;
857
- /** Why it ended as it did, from its result, in a line: what its outcomes are counted by. `standardReason` where absent. */
858
- readonly reason?: (a: A) => string | null;
859
- }) => {
860
- const writes = [...(d.mayWrite ?? []), ...(d.writes ?? [])];
861
- const declaration: StepDeclaration = {
862
- name: d.name, runs: d.runs, description: d.description, ...(d.kind === undefined ? {} : { kind: d.kind }), ...(d.test === undefined ? {} : { test: true }), ...(d.shared === undefined ? {} : { shared: true }), ...(d.perItem === undefined ? {} : { perItem: true }), ...(d.picked === undefined ? {} : { picks: true }), ...(d.subject === undefined ? {} : { namesItem: true }),
863
- ...(writes.length === 0 ? {} : { writes }),
864
- source: d.prompt ?? { path: sourcePath(d.at), anchor: `'${d.name}'` },
865
- };
866
- return {
867
- ...declaration,
868
- run: <E, R2>(execute: Effect.Effect<A, E, R2>, options?: { readonly call?: number; readonly subject?: string }) =>
869
- Activity.make({
870
- name: options?.call === undefined ? d.name : `${d.name} ${options.call}`,
871
- success: d.success,
872
- error: Schema.String,
873
- execute: pipe(
874
- standDownIfSurplus({ agent: d.runs === 'agentic', picks: d.picked !== undefined }),
875
- Effect.andThen(measured(declaration, options?.call ?? null, options?.subject ?? null, d.subject, d.reason, d.mayWrite, d.picked === undefined ? execute : untilPicked(d.picked, execute))),
876
- Effect.retry({ while: deps.isTransientFailure, times: 10, schedule: Schedule.spaced('3 seconds') }),
877
- Effect.mapError(describeFailure),
878
- ),
879
- }),
880
- };
881
- };
882
-
883
- /**
884
- * "CLEARED" MEANS OFF THE LIST, by construction: a pass counts only if the list the workflow shows and Pick takes from no
885
- * longer holds the item. One still on it is a fault, recorded and named, and its agent starts, told so.
886
- */
887
- const heldToItsList = <E, R2>(test: Effect.Effect<ItemTest, E, R2>, subject: string | null) => Effect.gen(function* () {
888
- const said = yield* test;
889
- if (said.result !== 'passes') return said;
890
- const instance = yield* WorkflowEngine.WorkflowInstance;
891
- const workflow = instance.workflow._tag;
892
- const item = subject ?? (yield* recorded('read its item', records.subjectOfRun(instance.executionId)));
893
- const pending = DECLARED.get(workflow)?.pending;
894
- if (item === null || pending === undefined) return said;
895
- // Only a workflow with a list comes here, and those run under what its list reads.
896
- const work = yield* Effect.exit(pending() as Effect.Effect<PendingWork, unknown>);
897
- if (!Exit.isSuccess(work) || !listOf(work.value).some((i) => i.toLowerCase() === item.toLowerCase())) return said;
898
- yield* recorded('a pass its list still holds', records.recordClearedButListed({ workflow, run: instance.executionId, item, said: said.detail }));
899
- return { result: 'cannot' as const, why: `its test passed (${said.detail}), and it is still on this workflow's list, so it has not cleared` };
900
- });
901
-
902
- /** The no-agent test step of a workflow, before its first agent step. */
903
- const defineItemTest = (d: { readonly description: string; readonly at: string }) => {
904
- const step = defineStep({ name: 'Test', runs: 'deterministic', test: true, description: d.description, at: d.at, prompt: { path: sourcePath(d.at), anchor: 'defineItemTest(' }, success: ItemTest });
905
- return { ...step, run: <E, R2>(test: Effect.Effect<ItemTest, E, R2>, options?: { readonly call?: number; readonly subject?: string }) => step.run(heldToItsList(test, options?.subject ?? null), options) };
906
- };
907
-
908
- /** The sub-workflows whose agent steps are being asked for now: a workflow that used itself as a step would ask for ever. */
909
- const askingForAgents = new Set<string>();
910
-
911
- /**
912
- * A SUB-WORKFLOW STEP: a workflow used as a step of another. Alex, 2026-11-19: "decompile is itself a workflow composed of
913
- * other workflows. the long term goal of Jive is to be workflows all the way down".
914
- *
915
- * Running it starts `workflow` as a run of its own on `payload` and waits for it: the engine suspends the run above until
916
- * it ends, across restarts, and then runs this step again, which reads the result. The step keeps ONE record in the
917
- * workflow above, open while its workflow runs and naming that run, so:
918
- *
919
- * the page shows the run above in this step, and the workflow's own view shows its steps and what they cost;
920
- * the workflow's steps work on the item the run above works on, with no code naming it (`StepRecords.openStepRun`);
921
- * its agent steps count against the agents' limit of the workflow at the top, and stand down with its run (`topOf`).
922
- *
923
- * Its start is the step's, so no run limit of its own gates it: the run above is the one a limit lets start or not, and a
924
- * limit on a workflow used only as a step would fail the steps of runs already going.
925
- */
926
- const defineSubWorkflow = <P, A, R2>(d: {
927
- /** The workflow, as `defineWorkflow` gave it: define it above the workflow that uses it. */
928
- readonly workflow: { readonly _tag: string; readonly execute: (payload: P) => Effect.Effect<unknown, unknown, R2>; readonly executionId: (payload: P) => Effect.Effect<string> };
929
- /** Its name as a step, where the workflow above calls it something else. */
930
- readonly as?: string;
931
- /** `import.meta.path`, for its link where its workflow is not defined yet. */
932
- readonly at: string;
933
- readonly success: Schema.Codec<A, unknown>;
934
- }) => {
935
- const child = d.workflow._tag;
936
- // What its workflow gave is what the step declares, or the step fails saying so: no result is taken on trust.
937
- const isDeclared = Schema.is(d.success);
938
- const given = (result: unknown): Effect.Effect<A, string> => (isDeclared(result) ? Effect.succeed(result) : Effect.fail(`${child} gave a result that is not what this step declares`));
939
- const name = d.as ?? child;
940
- const startAsAStep = (payload: P): Effect.Effect<unknown, unknown, R2> => ((STARTS_AS_A_STEP.get(child) ?? d.workflow.execute) as (payload: P) => Effect.Effect<unknown, unknown, R2>)(payload);
941
- /**
942
- * ITS WORKFLOW STARTED, AND WAITED FOR. In a process handing its runs to the next, the wait is cut: its workflow's run
943
- * has gone to the next process, which this one's engine can no longer reach, so the call is interrupted. Left to the
944
- * engine's activity, that interrupt was tried again 10 times and then failed the run above, while its workflow went on
945
- * in the next process with a result nothing would read: two runs of Decompile ended so on 2026-11-19, their agents
946
- * still writing. The run above is suspended instead, as it is whenever its workflow has not ended: the next process
947
- * resumes it when that workflow ends, this step runs again there and reads the result, and its record stays the one.
948
- */
949
- const startedAndWaitedFor = (payload: P): Effect.Effect<unknown, unknown, R2 | WorkflowEngine.WorkflowInstance> => pipe(
950
- startAsAStep(payload),
951
- Effect.sandbox,
952
- Effect.catch((cause) => Effect.flatMap(WorkflowEngine.WorkflowInstance, (instance) =>
953
- (Cause.hasInterruptsOnly(cause) && !instance.suspended && deps.wakes.handingOver() ? Workflow.suspend(instance) : Effect.failCause(cause)))),
954
- );
955
- const declaration: StepDeclaration = {
956
- name, runs: null, kind: 'sub-workflow', workflow: child,
957
- description: DECLARED.get(child)?.description ?? `Runs ${child}.`,
958
- source: DECLARED.get(child)?.source ?? { path: sourcePath(d.at), anchor: `'${child}'` },
959
- agentUnder: () => {
960
- if (askingForAgents.has(child)) return false;
961
- askingForAgents.add(child);
962
- try {
963
- return DECLARED.get(child)?.steps().some(stepUsesAnAgent) === true;
964
- } finally {
965
- askingForAgents.delete(child);
966
- }
967
- },
968
- };
969
- return {
970
- ...declaration,
971
- run: (payload: P, options?: { readonly call?: number }) =>
972
- Activity.make({
973
- name: options?.call === undefined ? name : `${name} ${options.call}`,
974
- success: d.success,
975
- error: Schema.String,
976
- execute: pipe(
977
- standDownIfSurplus({ agent: false, picks: false }),
978
- Effect.andThen(Effect.flatMap(d.workflow.executionId(payload), (childRun) =>
979
- measured(declaration, options?.call ?? null, null, undefined, undefined, undefined, Effect.flatMap(startedAndWaitedFor(payload), given), childRun))),
980
- Effect.mapError(describeFailure),
981
- ),
982
- }),
983
- };
984
- };
985
-
986
- /** Every workflow defined so far, in the order defined. */
987
- const declaredWorkflows = (): ReadonlyArray<Declaration> => [...DECLARED.values()];
988
-
989
- /** Calls `listener` shortly after any run ends, when the engine has stored its end. */
990
- const onRunEnded = (listener: () => void): void => {
991
- RUN_ENDED.add(listener);
992
- };
993
-
994
- const runEnded = () => {
995
- for (const after of [1000, 5000]) {
996
- for (const listener of RUN_ENDED) setTimeout(listener, after);
997
- }
998
- };
999
-
1000
- /** A workflow's tasks' inputs now (`WorkflowDeclaration.taskInputs`), recorded for every summary of its tasks; none for one that declares none. */
1001
- const readTaskInputs = (workflow: string): Effect.Effect<ReadonlyMap<string, TaskInputs> | null, unknown, R> => Effect.gen(function* () {
1002
- const d = DECLARED.get(workflow);
1003
- if (d?.taskInputs === undefined) return null;
1004
- const read = yield* d.taskInputs();
1005
- const byItem = new Map([...read].map(([item, inputs]) => [item.toLowerCase(), inputs] as const));
1006
- deps.tasks.recordTaskInputs(workflow, byItem);
1007
- return byItem;
1008
- });
1009
-
1010
- /** The step a Pick's notes are written by: every Pick is the step that reads its queue. */
1011
- const pickedBy = (input: { readonly workflow: string; readonly run: string }) => ({ workflow: input.workflow, run: input.run, step: 'Pick' });
1012
-
1013
- /**
1014
- * A WORKFLOW'S QUEUE AS ITS PICK TAKES IT: first in, first out (`tasks.ts` `queueOrder`), another run's tasks left out.
1015
- * The Pick first reads what its tasks run on and settles its queue (`tasks.ts` `settleQueue`): a task a standard reason
1016
- * holds for is blocked, and a blocked one whose reason lapsed is back in the queue.
1017
- */
1018
- const queueNow = (input: { readonly workflow: string; readonly run: string }): Effect.Effect<ReadonlyArray<TaskSummary>, unknown, R> => Effect.gen(function* () {
1019
- yield* readTaskInputs(input.workflow);
1020
- const queue = queueOrder(yield* deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }));
1021
- // While no agent can be had, a task marked as needing one is passed over (`agentsUnavailable`).
1022
- return (yield* agentsUnavailable(input.workflow)) === null ? queue : queue.filter((t) => deps.tasks.passedOverNow(t) === null);
1023
- });
1024
-
1025
- /**
1026
- * WHY NO RUN OF A WORKFLOW CAN TAKE WORK NOW, none where one can: no agent can be had for it (`agentsUnavailable`), and
1027
- * every task in its queue is one its Pick passes over meanwhile, marked as needing an agent or with nothing new since its
1028
- * last run (`tasks.ts` `passedOverWithoutAnAgent`), or its queue is empty. Then a run would only hold a run slot and show
1029
- * as running: its trigger starts none (`keep-running.ts` `planRunStarts`), and a Pick that found nothing ends its run
1030
- * rather than wait (`untilPicked`). An agent to be had (a limit lifted, the spending limit no longer holding), a mark
1031
- * cleared, new input or a new item lets runs start again. Only a workflow with a list and an agent step: one with no agent
1032
- * step needs none. Read where it cannot be, it says nothing, and runs start and wait as before.
1033
- */
1034
- const whyNoRunCanTakeWork = (workflow: string): Effect.Effect<string | null, never, R> => Effect.gen(function* () {
1035
- // Its tasks' inputs, a read of every task's, are read again only where the inputs its last Pick read leave no work.
1036
- if ((yield* noWorkByInputsLastRead(workflow)) === null) return null;
1037
- yield* Effect.orElseSucceed(readTaskInputs(workflow), () => null);
1038
- return yield* noWorkByInputsLastRead(workflow);
1039
- });
1040
-
1041
- /** `whyNoRunCanTakeWork` by its tasks' inputs as its last Pick read them: what a Pick that just read them asks. */
1042
- const noWorkByInputsLastRead = (workflow: string): Effect.Effect<string | null> => pipe(
1043
- Effect.gen(function* () {
1044
- const d = DECLARED.get(workflow);
1045
- if (d === undefined || !keptRunningByItsBudget(d)) return null;
1046
- const unavailable = yield* agentsUnavailable(workflow);
1047
- if (unavailable === null) return null;
1048
- const queued = queueOrder(yield* deps.tasks.taskSummaries({ workflow }));
1049
- if (queued.some((t) => deps.tasks.passedOverNow(t) === null)) return null;
1050
- return `no agent can be had (${unavailable}), and ${queued.length === 0 ? 'its queue is empty' : `each of its ${queued.length} queued tasks needs one or has nothing new since its last run`}`;
1051
- }),
1052
- Effect.orElseSucceed(() => null),
1053
- );
1054
-
1055
- /** A workflow: what it states about itself, then `Workflow.make`'s own name and options. */
1056
- const defineWorkflow =<Result = never>(d: {
1057
- readonly phase: Phase;
1058
- readonly description: string;
1059
- /** `import.meta.path`, for its link. */
1060
- readonly at: string;
1061
- /** Its steps, in order; a function so they can be defined below it. */
1062
- readonly steps: () => ReadonlyArray<StepDeclaration>;
1063
- readonly pending?: () => Effect.Effect<PendingWork, unknown, R>;
1064
- /** Every item it has a task for, done or not (`WorkflowDeclaration.items`), in place of `pending`. */
1065
- readonly items?: () => Effect.Effect<ReadonlyArray<string>, unknown, R>;
1066
- readonly picksQueueHead?: true;
1067
- /**
1068
- * The workflows whose results become its tasks: the arrows of the project's map (`views/workflow-flows.ts`). A workflow
1069
- * used as a step of another needs none: it is drawn inside that one.
1070
- */
1071
- readonly fedBy?: ReadonlyArray<string>;
1072
- /** Its step graph: which step can follow which, and when. */
1073
- readonly graph?: () => ReadonlyArray<StepEdge>;
1074
- /** What it runs on: its trigger starts a run only when they changed (`runIfInputsChanged`). */
1075
- readonly inputs?: WorkflowInputs<R>;
1076
- /** What each of its tasks runs on (`WorkflowDeclaration.taskInputs`); its Pick reads its queue with them (`queueNow`). */
1077
- readonly taskInputs?: () => Effect.Effect<ReadonlyMap<string, TaskInputs>, unknown, R>;
1078
- } & WorkflowItem<Result>): typeof Workflow.make =>
1079
- ((name: string, options: Parameters<typeof Workflow.make>[1]) => {
1080
- // The one place a workflow's own types do not matter: every workflow passes through here the same way.
1081
- const workflow: RunnableWorkflow = Workflow.make(name, options) as RunnableWorkflow;
1082
- /**
1083
- * EVERY START OF IT, WHATEVER CALLS IT (a timer, its inputs changing, its queue, a request), PASSES ITS RUN LIMIT: a new
1084
- * run starts only while fewer of its runs are going than its limit. One already going, by the same execution id, is
1085
- * joined as before. A start refused for the limit starts nothing: one that discards its run gets its id back, one that
1086
- * waits for its result fails with `RunLimitReached`. Where the limit cannot be read, the run starts, and that is said.
1087
- */
1088
- const execute = workflow.execute.bind(workflow);
1089
- let refusedSaidAt = 0;
1090
- const startAllowed = (payload: object): Effect.Effect<{ readonly allowed: true } | { readonly allowed: false; readonly limit: number }> => Effect.gen(function* () {
1091
- const limits = yield* deps.budgets.limitsOf(name);
1092
- const limit = limits === null ? null : runLimitOf(d, limits);
1093
- if (limit === null) return { allowed: true } as const;
1094
- const going = (yield* deps.engine.unfinishedRuns()).filter((u) => u.workflow === name).map((u) => u.run);
1095
- if (going.length < limit) return { allowed: true } as const;
1096
- const id = yield* workflow.executionId(payload);
1097
- return going.includes(id) ? { allowed: true } as const : { allowed: false, limit } as const;
1098
- }).pipe(Effect.catchTag('StorageError', (e) => Effect.as(Effect.logError(`[run limit] ${name}: its limit could not be read, so the run starts: ${e.reason}`), { allowed: true } as const)));
1099
- const gatedExecute: RunnableWorkflow['execute'] = (payload, startOptions) => Effect.flatMap(startAllowed(payload), (gate) => {
1100
- if (gate.allowed) return startOptions === undefined ? execute(payload) : execute(payload, startOptions);
1101
- const say = Date.now() - refusedSaidAt < REFUSED_SAID_EVERY_MS ? Effect.void : Effect.sync(() => { refusedSaidAt = Date.now(); console.log(`[run limit] ${name}: not started, its run limit of ${gate.limit} is reached`); });
1102
- return Effect.andThen(say, startOptions?.discard === true ? workflow.executionId(payload) : Effect.fail(new RunLimitReached({ workflow: name, limit: gate.limit })));
1103
- });
1104
- DECLARED.set(name, {
1105
- name, phase: d.phase, description: d.description, steps: d.steps,
1106
- ...(d.graph === undefined ? {} : { graph: d.graph }),
1107
- source: { path: sourcePath(d.at), anchor: `'${name}'` },
1108
- ...(d.pending === undefined ? {} : { pending: d.pending }),
1109
- ...(d.items === undefined ? {} : { items: d.items }),
1110
- ...(d.picksQueueHead === undefined ? {} : { picksQueueHead: d.picksQueueHead }),
1111
- ...(d.fedBy === undefined ? {} : { fedBy: d.fedBy }),
1112
- ...(d.inputs === undefined ? {} : { inputs: d.inputs }),
1113
- ...(d.taskInputs === undefined ? {} : { taskInputs: d.taskInputs }),
1114
- item: d.item,
1115
- finishedWord: d.item === null ? null : d.finishedWord,
1116
- gate: d.item === null ? null : (d.gate ?? null),
1117
- start: (run) => gatedExecute({ run }, { discard: true }),
1118
- startOn: (payload, options) => Effect.asVoid(options.wait ? gatedExecute(payload) : gatedExecute(payload, { discard: true })),
1119
- executionIdOf: (payload) => workflow.executionId(payload),
1120
- });
1121
- const toLayer = workflow.toLayer.bind(workflow);
1122
- // Its start as a step of another workflow, which no run limit of its own gates (`defineSubWorkflow`).
1123
- STARTS_AS_A_STEP.set(name, execute as (payload: unknown) => Effect.Effect<unknown, unknown, unknown>);
1124
- Object.assign(workflow, { execute: gatedExecute });
1125
- // Every run of every workflow ends here: its items' outcomes are recorded, and the next run can start at once.
1126
- return Object.assign(workflow, {
1127
- toLayer: (execute: WorkflowBody) =>
1128
- toLayer((payload, executionId) => Effect.onExit(execute(payload, executionId), (exit) => Effect.flatMap(
1129
- // ITS TASK'S INPUTS AS THE RUN LEFT THEM go on its outcome: a run that changed what it ran on (a Test's trials)
1130
- // left nothing new for the next. Taken when it picked, 490 Tests ran on 107 functions in 41 minutes (2026-11-14).
1131
- !Exit.isSuccess(exit) && Cause.hasInterrupts(exit.cause) || d.item === null ? Effect.succeed(null) : Effect.orElseSucceed(readTaskInputs(name), () => null),
1132
- (leftWith) => Effect.gen(function* () {
1133
- const interrupted = !Exit.isSuccess(exit) && Cause.hasInterrupts(exit.cause);
1134
- const runItem = yield* recorded('read its item', records.subjectOfRun(executionId));
1135
- const inputsLeft = (subject: string | null): string | null => {
1136
- const item = subject ?? runItem;
1137
- return item === null ? null : leftWith?.get(item.toLowerCase())?.fingerprint ?? null;
1138
- };
1139
- if (!interrupted && d.item !== null) {
1140
- if (Exit.isSuccess(exit)) {
1141
- for (const o of d.outcomes(exit.value as Result)) yield* deps.tasks.appendOutcome({ workflow: name, run: executionId, subject: o.subject ?? null, outcome: o.outcome, finished: o.finished || o.outcome === CLEARED_BY_TEST, inputs: inputsLeft(o.subject ?? null), blocked: o.blocked ?? null });
1142
- } else {
1143
- // With its cause, as its step's record has it: a bare "failed" sent whoever read it to the records for why.
1144
- const failure = Cause.squash(exit.cause);
1145
- const outcome = isStoodDown(failure) ? 'stood down' : `failed: ${startAndEnd(describeFailure(failure), { cap: 1000, end: 400, what: 'the failure' })}`;
1146
- yield* deps.tasks.appendOutcome({ workflow: name, run: executionId, subject: null, outcome, finished: false, inputs: inputsLeft(null), blocked: null });
1147
- }
1148
- }
1149
- // What it ran on gave this result, which stands until its inputs change. Only a run its trigger started on its
1150
- // inputs has a record to end.
1151
- if (d.inputs !== undefined) {
1152
- yield* Effect.catchTag(deps.inputs.recordEnd({
1153
- run: executionId,
1154
- outcome: Exit.isSuccess(exit) ? 'success' : Cause.hasInterrupts(exit.cause) ? 'interrupted' : 'failure',
1155
- result: Exit.isSuccess(exit) ? JSON.stringify(exit.value) ?? null : null,
1156
- }), 'StorageError', (e) => Effect.logError(`[inputs] ${name} run ${executionId}: its end could not be recorded: ${e.reason}`));
1157
- }
1158
- lastStepRan.delete(executionId);
1159
- TOPS.delete(executionId);
1160
- runEnded();
1161
- // Its claim and its item are free now for its workflow's other runs, once the engine has stored its end. Only its
1162
- // own: about 25 short runs end a minute, and waking every Pick on each re-read every task twice each time.
1163
- setTimeout(() => deps.wakes.wakePicksOf(name, 'one of its runs ended'), 1000);
1164
- })))),
1165
- });
1166
- }) as typeof Workflow.make;
1167
-
1168
- /**
1169
- * RUNS A WORKFLOW ON `payload` ONLY WHEN ITS INPUTS CHANGED since its last successful run: it reads their fingerprint, and
1170
- * when it is that run's, the result that run stored stands and nothing starts. Otherwise the run starts, recorded with the
1171
- * fingerprint it ran on before it starts, so its end finds the record. A workflow that declares no inputs runs each time.
1172
- * `wait` waits for the run to end.
1173
- */
1174
- const runIfInputsChanged = (r: { readonly workflow: string; readonly payload: object; readonly wait: boolean }): Effect.Effect<'started' | 'unchanged', unknown, R | WorkflowEngine.WorkflowEngine> =>
1175
- Effect.gen(function* () {
1176
- const d = DECLARED.get(r.workflow);
1177
- if (d === undefined) return yield* Effect.fail(`no workflow ${r.workflow} is declared`);
1178
- if (d.inputs !== undefined) {
1179
- const inputs = yield* d.inputs.read();
1180
- const last = yield* deps.inputs.lastSuccess(r.workflow);
1181
- if (last !== null && last.inputs === inputs) return 'unchanged' as const;
1182
- const run = yield* d.executionIdOf(r.payload);
1183
- yield* deps.inputs.recordStart({ workflow: r.workflow, inputs, run });
1184
- }
1185
- yield* d.startOn(r.payload, { wait: r.wait });
1186
- return 'started' as const;
1187
- });
1188
-
1189
- /** The items a workflow's other unfinished runs are on, lower case, so a budget above 1 never puts two agents on one. */
1190
- const itemsOfOtherRuns = (workflow: string, run: string): Effect.Effect<ReadonlySet<string>, StorageError> =>
1191
- Effect.flatMap(runningRunIds(workflow), (runs) => Effect.map(Effect.forEach(runs.filter((r) => r !== run), (r) => records.subjectOfRun(r)), (subjects) =>
1192
- new Set(subjects.flatMap((subject) => (subject === null ? [] : [subject.toLowerCase()])))));
1193
-
1194
- /**
1195
- * The candidates of this run's Pick in the order it takes them (`tasks.ts` `inPickOrder`), its queue settled first as
1196
- * `queueNow` settles it: none blocked, another run's left out. `fromItem` builds a candidate for a task a step or a person
1197
- * returned to the queue that the candidates do not hold.
1198
- */
1199
- const pickOrder = <C>(input: { readonly workflow: string; readonly run: string; readonly candidates: ReadonlyArray<C>; readonly subjectOf: (c: C) => string; readonly fromItem?: (item: string) => C | null }): Effect.Effect<ReadonlyArray<C>, StorageError> =>
1200
- Effect.map(Effect.all({ tasks: deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }), unavailable: agentsUnavailable(input.workflow) }), ({ tasks, unavailable }) =>
1201
- inPickOrder({
1202
- candidates: input.candidates, subjectOf: input.subjectOf, tasks, ...(input.fromItem === undefined ? {} : { fromItem: input.fromItem }),
1203
- // While no agent can be had, a task marked as needing one is passed over (`agentsUnavailable`).
1204
- ...(unavailable === null ? {} : { alsoLeaveOut: new Set(tasks.filter((t) => deps.tasks.passedOverNow(t) !== null).map((t) => t.ref.item)) }),
1205
- }));
1206
-
1207
- /**
1208
- * A workflow of one code step, run each turn of its trigger: `run` waits for the run to finish (a heavy one, in line with
1209
- * the other heavy jobs), `start` leaves it to the engine.
1210
- */
1211
- const oneStepWorkflow = <A, E, R2>(
1212
- // One step of the project's code: no agent, and no single item.
1213
- states: { readonly phase: Phase; readonly description: string; readonly stepDescription: string; readonly at: string; readonly writes?: ReadonlyArray<string>; readonly inputs?: WorkflowInputs<R> },
1214
- name: string, step: string, success: Schema.Codec<A, unknown>, execute: Effect.Effect<A, E, R2>,
1215
- ) => {
1216
- const theStep = defineStep({ name: step, runs: 'deterministic', shared: true, description: states.stepDescription, at: states.at, success, ...(states.writes === undefined ? {} : { writes: states.writes }) });
1217
- const workflow = defineWorkflow({ phase: states.phase, description: states.description, at: states.at, steps: () => [theStep], item: null, ...(states.inputs === undefined ? {} : { inputs: states.inputs }),
1218
- graph: () => [{ from: RUN_STARTS, to: step, when: 'each turn' }, { from: step, to: RUN_ENDS, when: 'always' }] })(name, {
1219
- payload: { turn: Schema.Number },
1220
- idempotencyKey: ({ turn }) => String(turn),
1221
- success,
1222
- error: Schema.String,
1223
- });
1224
- return {
1225
- name, step, workflow, layer: workflow.toLayer(() => theStep.run(execute)),
1226
- // Each turn of its trigger starts a run only when its inputs changed, where it declares them (`runIfInputsChanged`).
1227
- run: (turn: number) => Effect.asVoid(runIfInputsChanged({ workflow: name, payload: { turn }, wait: true })),
1228
- start: (turn: number) => Effect.asVoid(runIfInputsChanged({ workflow: name, payload: { turn }, wait: false })),
1229
- };
1230
- };
1231
-
1232
- return {
1233
- defineStep, defineItemTest, defineSubWorkflow, defineWorkflow, oneStepWorkflow, declaredWorkflows, onRunEnded,
1234
- eachItem, undoAgentStep, AgentBudgets, pickingOneAtATime, pickOrder, itemsOfOtherRuns,
1235
- runsOldestFirst, runningRunIds, runningRuns, sourcePath, runIfInputsChanged, queueNow, readTaskInputs, agentsUnavailable, whyNoRunCanTakeWork,
1236
- };
1237
- };
1238
-
1239
- export type Steps<Phase extends string, R> = ReturnType<typeof makeSteps<Phase, R>>;