@jive-sh/workflow-platform 0.6.2 → 0.7.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 (89) hide show
  1. package/README.md +189 -42
  2. package/dist/budget-states.js +1 -1
  3. package/dist/budget-states.js.map +1 -1
  4. package/dist/dashboard/dashboard.css +42 -28
  5. package/dist/dashboard/drilldown.js +35 -4
  6. package/dist/dashboard/drilldown.js.map +1 -1
  7. package/dist/dashboard/run-doing-words.js +29 -0
  8. package/dist/dashboard/run-doing-words.js.map +1 -0
  9. package/dist/dashboard/setting-words.js +18 -0
  10. package/dist/dashboard/setting-words.js.map +1 -0
  11. package/dist/dashboard/spending-words.js +2 -10
  12. package/dist/dashboard/spending-words.js.map +1 -1
  13. package/dist/index.js +76 -13
  14. package/dist/index.js.map +1 -1
  15. package/dist/keep-running.js +4 -2
  16. package/dist/keep-running.js.map +1 -1
  17. package/dist/pick-wakes.js +2 -2
  18. package/dist/retention.js +59 -0
  19. package/dist/retention.js.map +1 -0
  20. package/dist/settings.js +88 -0
  21. package/dist/settings.js.map +1 -0
  22. package/dist/spending-limit.js +15 -21
  23. package/dist/spending-limit.js.map +1 -1
  24. package/dist/step-times.js +114 -0
  25. package/dist/step-times.js.map +1 -0
  26. package/dist/steps.js +399 -114
  27. package/dist/steps.js.map +1 -1
  28. package/dist/storage/agent-claims.js +3 -0
  29. package/dist/storage/agent-claims.js.map +1 -0
  30. package/dist/storage/budgets.js +40 -4
  31. package/dist/storage/budgets.js.map +1 -1
  32. package/dist/storage/engine-records.js +26 -10
  33. package/dist/storage/engine-records.js.map +1 -1
  34. package/dist/storage/sqlite-store.js +198 -20
  35. package/dist/storage/sqlite-store.js.map +1 -1
  36. package/dist/storage/task-store.js +11 -5
  37. package/dist/storage/task-store.js.map +1 -1
  38. package/dist/system-workflows.js +54 -0
  39. package/dist/system-workflows.js.map +1 -0
  40. package/dist/tasks.js +72 -29
  41. package/dist/tasks.js.map +1 -1
  42. package/dist/views/runs-now.js +80 -38
  43. package/dist/views/runs-now.js.map +1 -1
  44. package/dist/views/step-graph.js +6 -1
  45. package/dist/views/step-graph.js.map +1 -1
  46. package/dist/views/workflows-view.js +29 -23
  47. package/dist/views/workflows-view.js.map +1 -1
  48. package/package.json +1 -1
  49. package/src/budget-states.ts +2 -3
  50. package/src/dashboard/dashboard.css +42 -28
  51. package/src/dashboard/drilldown.ts +32 -5
  52. package/src/dashboard/index.tsx +1 -1
  53. package/src/dashboard/limits-and-runs.tsx +191 -0
  54. package/src/dashboard/queue-bar.tsx +30 -11
  55. package/src/dashboard/queue-chart.tsx +1 -2
  56. package/src/dashboard/run-doing-words.ts +41 -0
  57. package/src/dashboard/setting-words.ts +30 -0
  58. package/src/dashboard/spending-limit-control.tsx +5 -8
  59. package/src/dashboard/spending-words.ts +5 -23
  60. package/src/dashboard/time-distribution.tsx +61 -0
  61. package/src/dashboard/workflow-dag.tsx +247 -129
  62. package/src/dashboard/workflow-drilldown.tsx +13 -71
  63. package/src/dashboard/workflows-dashboard.tsx +345 -227
  64. package/src/index.ts +86 -16
  65. package/src/keep-running.ts +6 -4
  66. package/src/pick-wakes.ts +2 -2
  67. package/src/project.ts +12 -0
  68. package/src/retention.ts +90 -0
  69. package/src/settings.ts +171 -0
  70. package/src/spending-limit.ts +25 -42
  71. package/src/step-times.ts +151 -0
  72. package/src/steps.ts +512 -135
  73. package/src/storage/agent-claims.ts +63 -0
  74. package/src/storage/budgets.ts +43 -4
  75. package/src/storage/engine-records.ts +28 -11
  76. package/src/storage/sqlite-store.ts +225 -32
  77. package/src/storage/step-records.ts +59 -7
  78. package/src/storage/task-store.ts +29 -29
  79. package/src/system-workflows.ts +70 -0
  80. package/src/tasks.ts +69 -30
  81. package/src/views/runs-now.ts +119 -51
  82. package/src/views/step-graph.ts +11 -2
  83. package/src/views/workflows-view.ts +80 -39
  84. package/src/workflow-dag.test.tsx +89 -0
  85. package/src/workflow-page.test.tsx +170 -0
  86. package/dist/views/workflow-flows.js +0 -53
  87. package/dist/views/workflow-flows.js.map +0 -1
  88. package/src/dashboard/step-graph.tsx +0 -106
  89. package/src/views/workflow-flows.ts +0 -97
package/dist/steps.js CHANGED
@@ -1,13 +1,13 @@
1
1
  /**
2
2
  * THE ONE WAY TO DEFINE A WORKFLOW AND ITS STEPS.
3
3
  *
4
- * A workflow states its phase (where the project shows it), its steps and the item it works on, and each step states
4
+ * A workflow states its steps and the item it works on, and each step states
5
5
  * whether it needs an agent; nothing else defines a step. Every run of every step goes through the same code here, which
6
6
  * writes its one record (`storage/step-records.ts`): start, end, outcome, tokens, compiles, and a heartbeat while an agent
7
7
  * works. A dashboard derives all it says from those records and these declarations.
8
8
  *
9
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],
10
+ * export const MyWorkflow = defineWorkflow({ description: '...', at: import.meta.path, steps: () => [PICK],
11
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
12
  * ... yield* PICK.run(Effect.gen(...)); a repeating step gives its number: PICK.run(body, { call: 2 })
13
13
  *
@@ -25,7 +25,14 @@
25
25
  *
26
26
  * An agent call needs `AgentStep`, which only a step that runs agentically (`runs: 'agentic'`) provides, so it cannot compile anywhere else.
27
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
28
+ * A RUN CLAIMS ITS AGENTS FOR THE REST OF ITS RUN (`claimAgentsOrEnd`): a workflow with an agent step claims 1, or the
29
+ * number it declares (`agentsClaimed`), at a run's first agent step, against the agents' limit of the workflow at the top
30
+ * of the run, and holds it through every step until the run ends. A run that finds no claim free never waits: its task goes to the back of its
31
+ * queue, marked as needing an agent, and the run ends, so the next task can start. A sub-workflow step that keeps its agent
32
+ * until its run ends (`agentKeptUntilThisRunEnds`) has the claim its workflow's run takes held by the run of that step, so
33
+ * the step's next call finds it held, and no other run can take it between them.
34
+ *
35
+ * A RUN LIMIT ENDS THE RUNS PAST IT, NOT ONLY THE RUNS STARTED. Before each agent step, a run its workflow's budget has no
29
36
  * 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
37
  * 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
38
  * the same way. The step fails with `STOOD_DOWN`, and the run ends through its failure path, or through its normal one where
@@ -39,9 +46,11 @@
39
46
  * compiles, on its one record. A step working on items says which: `subject` names the run's one, `eachItem` gives a batch
40
47
  * step one record per item, and a step whose work no one item owns declares `shared` rather than dividing it up.
41
48
  */
49
+ import { createHash } from 'node:crypto';
50
+ import fs from 'node:fs';
42
51
  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';
52
+ import { Cause, Context, Data, Duration, Effect, Exit, pipe, Result, Schedule, Schema, Semaphore } from 'effect';
53
+ import { Activity, DurableClock, Workflow, WorkflowEngine } from 'effect/workflow';
45
54
  import { describeFailure, startAndEnd } from './failure';
46
55
  import { oneLine, standardReason } from './reasons';
47
56
  import { filesChanged } from './step-files';
@@ -49,7 +58,9 @@ import { edgeDeclared, RUN_ENDS, RUN_STARTS } from './graph';
49
58
  import { meterClosed, meterOpened, StepMeter } from './step-meter';
50
59
  import { runLimit } from './storage/budgets';
51
60
  import { AGENT_BEAT_MS, noSpend } from './storage/step-records';
52
- import { inPickOrder, listOf, queueOrder } from './tasks';
61
+ import { claimsCounting } from './storage/agent-claims';
62
+ import { checkedSettings, stepSetting } from './settings';
63
+ import { inPickOrder, listOf, queueOrder, STOOD_DOWN_OUTCOME } from './tasks';
53
64
  export { A_STEP_FAILS, edgeDeclared, isRetry, RUN_ENDS, RUN_STARTS } from './graph';
54
65
  /** Provided only inside a step that runs agentically; an agent call reports what it spent through it. */
55
66
  export class AgentStep extends Context.Service()('AgentStep') {
@@ -70,13 +81,23 @@ export const HANDED_OVER = 'stood down: its process is handing its runs to the n
70
81
  */
71
82
  export const ABOVE_ENDED = 'stood down: the run above it has ended';
72
83
  /**
73
- * What an agent step of a run with a task fails with where no agent can be had (`untilAgentSlot`): its task went to the
74
- * back of its queue, marked as needing an agent, and the run gives its slot up untried.
84
+ * What a run fails with where it can claim no agent at its first agent step (`claimAgentsOrEnd`), or holds one that can no longer be
85
+ * used before its next agent call (`beforeAgentCall`): its task, where it has one, went to the back of its queue, marked
86
+ * as needing an agent, and the run gives its slot up.
87
+ */
88
+ export const NEEDS_AN_AGENT_STOOD_DOWN = 'stood down: no agent was free, so its task went to the back of its queue, marked as needing one';
89
+ /**
90
+ * What an agent step fails with where no model is set on it or on any workflow above it (`settings.ts`): a fault in the
91
+ * declarations, not in its item, so its run stands down untried, and its task is neither charged a failed try nor blocked.
92
+ * As a plain failure it blocked three Decompile tasks for good (2026-11-21, 22:13 to 22:35 UTC): their inputs never change
93
+ * when a model is set, so "nothing new since its last failed try" never lapsed.
75
94
  */
76
- 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';
77
- export const isStoodDown = (failure) => failure === STOOD_DOWN || failure === HANDED_OVER || failure === ABOVE_ENDED || failure === NEEDS_AN_AGENT_STOOD_DOWN;
95
+ export const NO_MODEL_STOOD_DOWN = 'stood down: no model is set on its agent step or on any workflow above it, so it took no agent';
96
+ export const isStoodDown = (failure) => failure === STOOD_DOWN || failure === HANDED_OVER || failure === ABOVE_ENDED || failure === NEEDS_AN_AGENT_STOOD_DOWN || failure === NO_MODEL_STOOD_DOWN;
78
97
  /** Why no agent can be had at an agents' limit of 0, in words. */
79
98
  export const AGENTS_LIMIT_ZERO = "its agents' limit is 0";
99
+ /** That every agent a limit allows is claimed, in words. Pure. */
100
+ const agentsInUse = (agents) => `its ${agents === 1 ? 'agent is' : `${agents} agents are`} in use`;
80
101
  /** 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. */
81
102
  export const surplusRun = (oldestFirst, run, budget) => oldestFirst.indexOf(run) >= budget;
82
103
  /**
@@ -95,7 +116,7 @@ export const STEP_KINDS = ['step', 'check', 'sub-workflow'];
95
116
  * for steps which use a separate classifier model".
96
117
  *
97
118
  * deterministic code only;
98
- * agentic an agent does it: it waits for one of its workflow's agents (`untilAgentSlot`);
119
+ * agentic an agent does it, on the agent its run claimed as it started (`claimAgentsOrEnd`);
99
120
  * classification a separate classifier model decides.
100
121
  *
101
122
  * A step or a check is any of the three. A sub-workflow step states none: its workflow's own steps state theirs.
@@ -109,6 +130,12 @@ export const ItemTest = Schema.Union([
109
130
  Schema.Struct({ result: Schema.Literal('fails'), failure: Schema.String }),
110
131
  Schema.Struct({ result: Schema.Literal('cannot'), why: Schema.String }),
111
132
  ]);
133
+ /**
134
+ * HOW MANY AGENTS A RUN OF A WORKFLOW CLAIMS FOR ITS WHOLE RUN: the number it declares, else 1 where it has an agent step of
135
+ * its own, else none. A workflow whose agent steps are all under its sub-workflow steps claims none itself: each of those
136
+ * workflows claims its own. Pure.
137
+ */
138
+ export const agentsClaimedBy = (d) => d.agentsClaimed ?? (d.steps().some((s) => s.runs === 'agentic') ? 1 : 0);
112
139
  /** A run not started: its workflow's run limit was reached. What a start that waits for its result fails with. */
113
140
  export class RunLimitReached extends Data.TaggedError('RunLimitReached') {
114
141
  }
@@ -125,11 +152,41 @@ export const hasAList = (d) => d.pending !== undefined || d.items !== undefined;
125
152
  export const stepUsesAnAgent = (s) => s.runs === 'agentic' || s.agentUnder?.() === true;
126
153
  /** Whether a workflow's budget rules it: a declared list, and an agent step of its own or under a sub-workflow step. Pure. */
127
154
  export const keptRunningByItsBudget = (d) => hasAList(d) && d.steps().some(stepUsesAnAgent);
155
+ /**
156
+ * The workflows a run of another starts as one of its steps (`defineSubWorkflow`): each of their runs is part of the run
157
+ * above it, which a count takes once, and they have no limit of their own. A step on its own trigger is not one. Pure.
158
+ */
159
+ export const startedAsSteps = (declared) => new Set(declared.flatMap((d) => d.steps().flatMap((s) => (s.workflow === undefined || s.runsOnItsOwnTrigger === true ? [] : [s.workflow]))));
160
+ /**
161
+ * Whether every step of a workflow is another workflow on its own trigger: it starts no run of its own, and its runs, agents
162
+ * and costs are its steps', added up. Pure.
163
+ */
164
+ export const isMadeOfWorkflows = (d) => {
165
+ const steps = d.steps();
166
+ return steps.length > 0 && steps.every((s) => s.runsOnItsOwnTrigger === true);
167
+ };
168
+ /**
169
+ * WHETHER A WORKFLOW'S TASKS ARE ITS RUNS, one task a run (`tasks.ts` `runStarted`): it works on no item, has runs of its
170
+ * own (it is not made of workflows), and runs on its own trigger, never as a step another workflow's run starts, whose
171
+ * tasks are that workflow's passing through it. Alex, 2026-11-21: "a workflow is a workflow". Pure.
172
+ */
173
+ export const tasksAreRuns = (d, declared) => d.item === null && !isMadeOfWorkflows(d) && !startedAsSteps(declared).has(d.name);
128
174
  const CurrentMeter = Context.Reference('CurrentStepMeter', { defaultValue: () => null });
129
175
  /** The definer of one project's workflows and steps, on its stores. */
130
176
  export const makeSteps = (deps) => {
131
177
  const { stepRecords: records, stepFiles } = deps;
132
178
  const DECLARED = new Map();
179
+ /** The platform's own workflows, by name (`system-workflows.ts`): defined before any of the app's. */
180
+ const SYSTEM = new Set();
181
+ /**
182
+ * AN APP CANNOT AMEND ONE OF THE PLATFORM'S OWN WORKFLOWS: a definition of the same name, or one holding it as a step,
183
+ * fails the app's start, naming what the app may set instead. Alex, 2026-11-22: "system workflows at the top level which
184
+ * can be configured but not amended without changing the platform itself".
185
+ */
186
+ const refuseSystem = (name, what) => {
187
+ if (SYSTEM.has(name))
188
+ throw new Error(`${name} is one of the platform's own workflows, so ${what}: its schedule and run limit are the app's to set, and its steps change only with the platform`);
189
+ };
133
190
  const PICKING = new Map();
134
191
  const RUN_ENDED = new Set();
135
192
  const undeclaredSaid = new Set();
@@ -160,6 +217,62 @@ export const makeSteps = (deps) => {
160
217
  const recordNow = (what, write) => { Effect.runFork(recorded(what, write)); };
161
218
  /** A file's path relative to the project's source root, from its absolute path. */
162
219
  const sourcePath = (absolute) => path.relative(deps.sourceRoot, absolute).split(path.sep).join('/');
220
+ /** Each file's code as this process loaded it (`codeOf`), by its absolute path. */
221
+ const CODE_OF_FILE = new Map();
222
+ /**
223
+ * A FILE'S CODE AS THIS PROCESS LOADED IT, read once, when the first definition naming it is made: its content's hash, and
224
+ * when it last changed. What a workflow's version is made of (`versionOf`). An unreadable file is code too: its hash says so.
225
+ */
226
+ const codeOf = (file) => {
227
+ const known = CODE_OF_FILE.get(file);
228
+ if (known !== undefined)
229
+ return known;
230
+ let code;
231
+ try {
232
+ code = { hash: createHash('sha256').update(fs.readFileSync(file)).digest('hex').slice(0, 16), changed: fs.statSync(file).mtimeMs / 1000 };
233
+ }
234
+ catch {
235
+ code = { hash: 'unreadable', changed: 0 };
236
+ }
237
+ CODE_OF_FILE.set(file, code);
238
+ return code;
239
+ };
240
+ /** Each step's code (`defineStep`): the file that defines it, and an agent step's prompt file. */
241
+ const STEP_CODE = new WeakMap();
242
+ /** Each workflow's own file's code (`defineWorkflow`). */
243
+ const WORKFLOW_CODE = new Map();
244
+ const VERSIONS = new Map();
245
+ /**
246
+ * A WORKFLOW'S VERSION, THE CODE LOADED NOW: a hash of its own file and each of its steps' files (an agent step's prompt
247
+ * included), in their order; a step that is a workflow counts by that workflow's version, never its files inlined. `since`
248
+ * is when the newest of those files last changed. Read once per process, after every workflow is defined: a version
249
+ * changes only with the code a process loads. Every step record of a run carries its run's version
250
+ * (`StepRecords.openStepRun`).
251
+ */
252
+ const versionOf = (workflow, under = new Set()) => {
253
+ const known = VERSIONS.get(workflow);
254
+ if (known !== undefined)
255
+ return known;
256
+ const d = DECLARED.get(workflow);
257
+ if (d === undefined || under.has(workflow))
258
+ return { version: 'undeclared', since: 0 };
259
+ const own = WORKFLOW_CODE.get(workflow) ?? { hash: 'unknown', changed: 0 };
260
+ let since = own.changed;
261
+ const parts = [own.hash, ...d.steps().map((s) => {
262
+ if (s.workflow !== undefined) {
263
+ const sub = versionOf(s.workflow, new Set([...under, workflow]));
264
+ since = Math.max(since, sub.since);
265
+ return `${s.name}>${sub.version}`;
266
+ }
267
+ const codes = STEP_CODE.get(s) ?? [];
268
+ for (const c of codes)
269
+ since = Math.max(since, c.changed);
270
+ return `${s.name}:${codes.map((c) => c.hash).join(',')}`;
271
+ })];
272
+ const version = { version: createHash('sha256').update(parts.join('\n')).digest('hex').slice(0, 12), since };
273
+ VERSIONS.set(workflow, version);
274
+ return version;
275
+ };
163
276
  /** The runs of these workflows not finished now, oldest first. */
164
277
  const runsOldestFirst = (workflows) => deps.engine.runsOldestFirst(workflows);
165
278
  /** The runs of a workflow not finished now, by the id its step records carry. */
@@ -204,14 +317,15 @@ export const makeSteps = (deps) => {
204
317
  return runs === null ? Effect.succeed(false) : Effect.map(runsOldestFirst([workflow]), (going) => surplusRun(going, run, runs));
205
318
  });
206
319
  /**
207
- * 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
208
- * slot, each until the next wake reads them again. Read as no limits, a store that failed would start agents at 0.
320
+ * LIMITS THAT CANNOT BE READ GIVE NO NEW AGENT: a run does not stand down and its Pick waits, each until the next wake reads
321
+ * them again, and a run that starts takes no claim and ends, saying why. Read as no limits, a store that failed would start
322
+ * agents at 0.
209
323
  */
210
324
  const unreadLimits = (workflow, held) => (e) => Effect.as(Effect.logError(`[budget] ${workflow}: its limits could not be read (${e.reason}); its runs wait`), held(e.reason));
211
325
  /**
212
326
  * 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
213
- * (`StepRecords.rootOfRun`). A workflow's limits govern every run under its runs, so a sub-workflow's agent step counts
214
- * against the agents' limit of the workflow at the top. Kept while the run goes: it never changes.
327
+ * (`StepRecords.rootOfRun`). A workflow's limits govern every run under its runs, so a sub-workflow's agent claim counts
328
+ * against the agents' limit of the workflow at the top (`claimAgentsOrEnd`). Kept while the run goes: it never changes.
215
329
  */
216
330
  const TOPS = new Map();
217
331
  /** Each workflow's start with no run limit asked, by name: what a sub-workflow step starts it by (`defineSubWorkflow`). */
@@ -226,26 +340,29 @@ export const makeSteps = (deps) => {
226
340
  return top;
227
341
  });
228
342
  };
343
+ /**
344
+ * THE AGENT CLAIMS THAT COUNT NOW, every workflow's: open, with the run at the top of each unfinished in the engine
345
+ * (`storage/agent-claims.ts` `claimsCounting`). The runs holding an agent, as a page shows them.
346
+ */
347
+ const agentClaimsNow = () => Effect.map(Effect.all({ open: deps.claims.openAgentClaims(), live: deps.engine.unfinishedRuns() }), ({ open, live }) => claimsCounting(open, new Set(live.map((u) => u.run))));
348
+ /** How many agents the runs under `workflow`'s runs claim now, the claim of the run `besides` left out. */
349
+ const agentsClaimedAgainst = (r) => Effect.map(Effect.all({ open: deps.claims.openAgentClaims(), live: runsOldestFirst([r.workflow]) }), ({ open, live }) => claimsCounting(open.filter((c) => c.top.workflow === r.workflow && c.run !== r.besides), new Set(live)).reduce((n, c) => n + c.agents, 0));
229
350
  const AgentBudgets = Context.Reference('AgentBudgets', {
230
351
  defaultValue: () => ({
231
352
  // Among its workflow's unfinished runs, oldest first, the run is past those its run limit keeps (`runLimit`). A run not
232
353
  // listed is not counted. A run a sub-workflow step started stands down with the run at its top.
233
354
  standsDown: (workflow, run) => pipe(topOf(workflow, run), Effect.flatMap((top) => Effect.zipWith(pastItsRunLimit(workflow, run), top.run === run ? Effect.succeed(false) : pastItsRunLimit(top.workflow, top.run), (own, above) => own || above)), Effect.catchTag('StorageError', unreadLimits(workflow, () => false))),
234
355
  waitsForWork: (workflow, run) => pipe(pastItsRunLimit(workflow, run), Effect.map((past) => !past), Effect.catchTag('StorageError', unreadLimits(workflow, () => true))),
235
- // The other runs of the workflow at its top that an agent works for, a waiting one not counted, against that
236
- // workflow's agents' limit: at 0 none is ever free, which no agent ending changes.
237
- agentSlot: (workflow, run) => pipe(topOf(workflow, run), Effect.flatMap((top) => Effect.flatMap(limitsOf(top.workflow), (w) => {
356
+ // The agents the other runs under the workflow at its top claim (`agentsClaimedAgainst`), against that workflow's
357
+ // agents' limit: at 0 none is ever free, which no claim ending changes.
358
+ agentSlot: (workflow, run) => pipe(run === null ? Effect.succeed({ run: null, workflow }) : topOf(workflow, run), Effect.flatMap((top) => Effect.flatMap(limitsOf(top.workflow), (w) => {
238
359
  const agents = w === null ? null : w.agents;
239
360
  if (agents === null)
240
361
  return Effect.succeed({ free: true });
241
362
  if (agents === 0)
242
- return Effect.succeed({ free: false, why: `waits for an agent: ${AGENTS_LIMIT_ZERO}`, unavailable: AGENTS_LIMIT_ZERO });
243
- return Effect.map(Effect.all({ runs: runsOldestFirst([top.workflow]), inAgentStep: records.runsInAgentStep(top.workflow) }), ({ runs, inAgentStep }) => {
244
- const going = new Set(runs);
245
- const busy = inAgentStep.filter((r) => r !== top.run && going.has(r)).length;
246
- return busy < agents ? { free: true } : { free: false, why: `waits for an agent: ${busy} of its ${agents} in use`, unavailable: null };
247
- });
248
- })), Effect.catchTag('StorageError', unreadLimits(workflow, (why) => ({ free: false, why: `waits for an agent: its limits could not be read (${why})`, unavailable: null })))),
363
+ return Effect.succeed({ free: false, why: AGENTS_LIMIT_ZERO, unavailable: AGENTS_LIMIT_ZERO, inUse: null });
364
+ return Effect.map(agentsClaimedAgainst({ workflow: top.workflow, besides: run }), (held) => (held < agents ? { free: true, limit: agents } : { free: false, why: agentsInUse(agents), unavailable: null, inUse: agentsInUse(agents) }));
365
+ })), Effect.catchTag('StorageError', unreadLimits(workflow, (why) => ({ free: false, why: `its limits could not be read (${why})`, unavailable: null, inUse: null })))),
249
366
  }),
250
367
  });
251
368
  /** 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. */
@@ -262,7 +379,7 @@ export const makeSteps = (deps) => {
262
379
  * ends, the next takes the same work and ends the same way. Fix conflicts' runs named conflicts while its list named
263
380
  * 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,
264
381
  * 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
265
- * run waits for an agent as a run with no task does. A task whose state cannot be read is marked as before.
382
+ * run ends unmarked, as a run with no task does. A task whose state cannot be read is marked as before.
266
383
  */
267
384
  const markedAsNeedingAnAgent = (top, step, why) => Effect.flatMap(taskOfTop(top), (task) => {
268
385
  if (task === null)
@@ -270,7 +387,7 @@ export const makeSteps = (deps) => {
270
387
  return Effect.flatMap(Effect.orElseSucceed(deps.tasks.readByItsPick(task), () => true), (read) => {
271
388
  if (read)
272
389
  return deps.tasks.markNeedsAgent({ task, by: { workflow: top.workflow, run: top.run, step }, why });
273
- 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`;
390
+ 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 ends unmarked`;
274
391
  if (process.env.NODE_ENV === 'test')
275
392
  return Effect.die(new Error(fault));
276
393
  if (!offItsListSaid.has(`${top.workflow}\n${task.item}`)) {
@@ -281,64 +398,126 @@ export const makeSteps = (deps) => {
281
398
  });
282
399
  });
283
400
  /**
284
- * WHY NO AGENT CAN BE HAD FOR A WORKFLOW'S RUNS NOW, in words; none where one can: the spending limit holds, or its
285
- * agents' limit is 0. While it says so, its Pick passes over its tasks marked as needing an agent, and those with nothing
286
- * new since their last run (`queueNow`, `pickOrder`, `tasks.ts` `passedOverWithoutAnAgent`), and takes them in their
287
- * queue's order again once an agent can be had. A limit that cannot be read passes over none.
401
+ * WHY NO AGENT CAN BE HAD FOR A WORKFLOW'S RUNS NOW, until a limit or a reading changes, in words; none where one can: the
402
+ * spending limit holds, or its agents' limit is 0. While it says so and its Pick would pass over every task in its queue,
403
+ * no run of it starts, and a Pick that finds nothing ends its run (`whyNoRunCanTakeWork`).
288
404
  */
289
405
  const agentsUnavailable = (workflow) => Effect.gen(function* () {
290
406
  const held = yield* deps.spendingHoldsAgents();
291
- if (held !== null && held.unavailable !== null)
292
- return held.unavailable;
407
+ if (held !== null)
408
+ return held;
293
409
  const limits = yield* Effect.orElseSucceed(limitsOf(workflow), () => null);
294
410
  return limits !== null && limits.agents === 0 ? AGENTS_LIMIT_ZERO : null;
295
411
  });
412
+ /** Whether a run of a workflow may claim an agent now (`AgentSlot`): the spending limit first, then its top workflow's agents. */
413
+ const agentSlotNow = (workflow, run) => Effect.gen(function* () {
414
+ const held = yield* deps.spendingHoldsAgents();
415
+ if (held !== null)
416
+ return { free: false, why: held, unavailable: held, inUse: null };
417
+ return yield* (yield* AgentBudgets).agentSlot(workflow, run);
418
+ });
296
419
  /**
297
- * AN AGENT STEP TAKES AN AGENT SLOT FIRST: with its workflow's agents' limit in use by its other runs it waits, its record
298
- * saying so, until an agent step ends or a limit changes (`pick-wakes.ts`), and never polls. Its record starts again when
299
- * it has a slot, since the wait was no work. A limit lowered meanwhile to 0 agents, or below its run, stands it down.
300
- * While the spending limit holds (`spending-limit.ts`) every agent step waits the same way, in every workflow, until a
301
- * reading below it or a new limit wakes it.
302
- *
303
- * 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
304
- * holds): it marks its task as needing an agent, which puts it at the back of its queue (`tasks.ts` `markNeedsAgent`),
305
- * and ends, giving its run slot to work that needs none. Its Pick passes over such tasks while no agent is available
306
- * (`agentsUnavailable`). Waiting, a few such runs filled every run slot of Decompile and nothing behind them moved
307
- * (2026-11-20). A run with no task, or one waiting for an agent another run holds, still waits here.
420
+ * WHY NO AGENT IS FREE FOR A WORKFLOW'S PICK NOW, in words; none where one is, or its limits could not be read: none can be
421
+ * had (`agentsUnavailable`), or every agent its agents' limit allows is claimed. While it says so, its Pick passes over its
422
+ * tasks marked as needing an agent, and those with nothing new since their last run (`queueNow`, `pickOrder`, `tasks.ts`
423
+ * `passedOverWithoutAnAgent`): a run on one would only find no agent to claim again. It takes them in their queue's order
424
+ * once an agent is free, woken by a claim ending (`endClaims`). Taken while every agent was claimed, a marked task would be
425
+ * picked, marked and put back again at once, as Fix conflicts' 3 tasks were 907 times in 75 minutes (2026-11-20).
426
+ */
427
+ const whyNoAgentIsFree = (workflow) => Effect.map(agentSlotNow(workflow, null), (slot) => (slot.free ? null : slot.unavailable !== null ? slot.unavailable : slot.inUse));
428
+ /** One claim taken at a time per top workflow in this process; the store's statement keeps processes apart (`takeAgentClaim`). */
429
+ const CLAIMING = new Map();
430
+ /**
431
+ * A RUN THAT CAN HAVE NO AGENT ENDS, AND NEVER WAITS: it marks its task as needing an agent, which puts it at the back of
432
+ * its queue (`tasks.ts` `markNeedsAgent`), and fails with `NEEDS_AN_AGENT_STOOD_DOWN`, giving its run slot to the next
433
+ * task. A run with no task, or no store to mark it in, ends the same way, and its next trigger tries again. Waiting, a few
434
+ * such runs filled every run slot of Decompile and nothing behind them moved: at 0 agents on 2026-11-20, and on 2026-11-21
435
+ * with 4 runs allowed and 1 agent, 3 runs waited inside Write C for hours. Alex, 2026-11-22: "i thought that if agent limit
436
+ * is 1 and 1 task is currently using the agent on a step, then the running task that gets blocked on needing an agent is
437
+ * marked as needing an agent then stopped and moved back to the queue's end".
438
+ */
439
+ const endForWantOfAnAgent = (r) => Effect.flatMap(markedAsNeedingAnAgent(r.top, r.step, r.why), (marked) => {
440
+ console.log(`[agents] ${r.workflow} run ${r.run} ended at ${r.step}: no agent was free (${r.why}); ${marked ? 'its task goes to the back of its queue, marked as needing one' : 'it has no task to mark, and its next trigger tries again'}`);
441
+ return Effect.fail(NEEDS_AN_AGENT_STOOD_DOWN);
442
+ });
443
+ /**
444
+ * THE RUN A CLAIM IS TAKEN FOR: the run itself, or, where a sub-workflow step that keeps its agent until its run ends
445
+ * started it (`StepDeclaration.agentKeptUntilThisRunEnds`), the run of that step, whose end ends the claim (`endClaims`).
446
+ * Where the run above cannot be read, the claim is the run's own, and that is said: it ends with the run, as before.
447
+ */
448
+ const claimHolder = (workflow, run) => pipe(records.parentOfRun(run), Effect.map((parent) => {
449
+ const keeps = parent !== null && DECLARED.get(parent.workflow)?.steps().some((s) => s.name === parent.step && s.agentKeptUntilThisRunEnds === true) === true;
450
+ return keeps ? { run: parent.run, workflow: parent.workflow } : { run, workflow };
451
+ }), Effect.catchTag('StorageError', (e) => Effect.as(Effect.logError(`[agents] ${workflow} run ${run}: the run above it could not be read, so its agent claim is its own and ends with it: ${e.reason}`), { run, workflow })));
452
+ /**
453
+ * A RUN CLAIMS ITS AGENTS AS IT STARTS, AND HOLDS THEM UNTIL IT ENDS. Alex, 2026-11-22: "i think we should think about a
454
+ * workflow having a number of agents it claims. so a subworkflow write C claims one on decompiles agents so while that
455
+ * task's own workflow is doing all these different things, some are agentic steps and deterministic steps but as that's
456
+ * going on decompile is down one agent."
308
457
  *
309
- * A step that gets past it took an agent, and clears its task's mark when it ends (`measured`, `agentStepRan`).
458
+ * A run of a workflow that claims agents (`agentsClaimedBy`) takes its claim at its first agent step, against the agents'
459
+ * limit of the workflow at the top of its run (`topOf`): Write C's against Decompile's. Its steps before it (a Pick, a
460
+ * Test with no agent) run with none, so a run at an agents' limit of 0 still finishes what needs no agent, and reaches its
461
+ * agent step with its task named, to mark. From then it holds the claim through every step, agent and deterministic, and
462
+ * through a handover or a restart, until it ends (`endClaims`). A workflow with no agent step of its own that declares
463
+ * agents claims as it starts. Its agent steps never wait
464
+ * for, or take, an agent of their own. A run resumed, or replayed by the engine, keeps the claim it holds; a run under a
465
+ * run that holds one takes none. With no claim free it ends (`endForWantOfAnAgent`). Where the claim is taken, a mark on
466
+ * its task as needing an agent has done its work and clears (`tasks.ts` `agentTaken`). A run that a sub-workflow step
467
+ * keeping its agent started (`agentKeptUntilThisRunEnds`) takes the claim for the run of that step (`claimHolder`), which
468
+ * holds it until it ends: that step's next call finds it held, and takes none.
310
469
  */
311
- const untilAgentSlot = (instance, step, record) => Effect.gen(function* () {
312
- const rules = yield* AgentBudgets;
470
+ const claimAgentsOrEnd = (workflow, run, step) => Effect.gen(function* () {
471
+ const d = DECLARED.get(workflow);
472
+ const agents = d === undefined ? 0 : agentsClaimedBy(d);
473
+ if (agents === 0)
474
+ return;
475
+ // A read that fails takes no second claim: the run goes on as one that holds its own, and that is said.
476
+ const held = yield* Effect.catchTag(deps.claims.claimHeldAtOrAbove(run), 'StorageError', (e) => Effect.as(Effect.logError(`[agents] ${workflow} run ${run}: whether it holds an agent claim could not be read, so it goes on as one that does: ${e.reason}`), true));
477
+ if (held)
478
+ return;
479
+ const top = yield* Effect.orElseSucceed(topOf(workflow, run), () => ({ run, workflow }));
480
+ const lock = CLAIMING.get(top.workflow) ?? Semaphore.makeUnsafe(1);
481
+ CLAIMING.set(top.workflow, lock);
482
+ const why = yield* lock.withPermits(1)(Effect.gen(function* () {
483
+ const slot = yield* agentSlotNow(workflow, run);
484
+ if (!slot.free)
485
+ return slot.unavailable ?? slot.inUse ?? slot.why;
486
+ const limit = slot.limit ?? null;
487
+ const live = yield* Effect.orElseSucceed(runsOldestFirst([top.workflow]), () => [top.run]);
488
+ const holder = yield* claimHolder(workflow, run);
489
+ const taken = yield* Effect.catchTag(deps.claims.takeAgentClaim({ ...holder, top, agents, limit, liveTopRuns: live }), 'StorageError', (e) => Effect.as(Effect.logError(`[agents] ${workflow} run ${run}: its agent claim could not be recorded, so it goes on unrecorded: ${e.reason}`), 'not recorded'));
490
+ return taken === 'no room' ? agentsInUse(limit ?? agents) : null;
491
+ }));
492
+ if (why !== null)
493
+ return yield* endForWantOfAnAgent({ top, workflow, run, step, why });
494
+ const task = yield* taskOfTop(top);
495
+ if (task !== null)
496
+ yield* deps.tasks.agentTaken({ task, by: { workflow: top.workflow, run: top.run, step } });
497
+ });
498
+ /**
499
+ * BEFORE EACH AGENT CALL, A RUN THAT HOLDS ITS CLAIM ENDS WHERE NO AGENT CAN BE HAD NOW: the spending limit holds, or its
500
+ * top workflow's agents' limit was set to 0 (`AgentSlot` `unavailable`). The call before it finished; this one is not made,
501
+ * and the run gives its task back as one that could claim none (`endForWantOfAnAgent`). Every agent merely claimed ends no
502
+ * run, its own claim among them, and nor does a limit lowered to above 0: the claims held keep their agents to their ends.
503
+ */
504
+ const beforeAgentCall = (instance, step) => Effect.gen(function* () {
313
505
  const workflow = instance.workflow._tag;
314
- // 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.
315
506
  const top = yield* Effect.orElseSucceed(topOf(workflow, instance.executionId), () => ({ run: instance.executionId, workflow }));
316
- const heardOn = top.workflow;
317
- let waited = false;
318
- for (;;) {
319
- const wakes = deps.wakes.pickWakesSoFar(heardOn);
320
- if (yield* rules.standsDown(workflow, instance.executionId))
321
- return yield* Effect.fail(STOOD_DOWN);
322
- const spendingHeld = yield* deps.spendingHoldsAgents();
323
- const slot = spendingHeld !== null ? { free: false, why: spendingHeld.why, unavailable: spendingHeld.unavailable } : yield* rules.agentSlot(workflow, instance.executionId);
324
- const id = record();
325
- if (slot.free) {
326
- if (waited && id !== null) {
327
- yield* recorded('end its wait', records.setStepWaiting({ id, waiting: null }));
328
- yield* recorded('start its record again', records.restartStepRun(id));
329
- }
330
- return;
331
- }
332
- if (slot.unavailable !== null && (yield* markedAsNeedingAnAgent(top, step, slot.unavailable))) {
333
- 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`);
334
- return yield* Effect.fail(NEEDS_AN_AGENT_STOOD_DOWN);
335
- }
336
- if (id !== null)
337
- yield* recorded('say what it waits on', records.setStepWaiting({ id, waiting: slot.why }));
338
- waited = true;
339
- if ((yield* deps.wakes.untilPickWoken({ workflow: heardOn, after: wakes })) === 'released')
340
- return yield* Effect.fail(HANDED_OVER);
341
- }
507
+ const slot = yield* agentSlotNow(workflow, instance.executionId);
508
+ if (!slot.free && slot.unavailable !== null)
509
+ return yield* endForWantOfAnAgent({ top, workflow, run: instance.executionId, step, why: slot.unavailable });
510
+ });
511
+ /**
512
+ * A RUN'S CLAIMS END WITH IT, whatever its outcome, and its top workflow's Picks are woken: a task they pass over as needing
513
+ * an agent can be taken now. An interrupted run keeps them: it resumes, in this process or the next.
514
+ */
515
+ const endClaims = (run, exit) => Effect.gen(function* () {
516
+ if (!Exit.isSuccess(exit) && Cause.hasInterrupts(exit.cause))
517
+ return;
518
+ const ended = yield* recorded('end its agent claims', deps.claims.endAgentClaims({ run, outcome: Exit.isSuccess(exit) ? 'success' : 'failure' }));
519
+ for (const top of new Set((ended ?? []).map((c) => c.top.workflow)))
520
+ deps.wakes.wakePicksOf(top, 'an agent claim ended');
342
521
  });
343
522
  /**
344
523
  * 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
@@ -372,6 +551,10 @@ export const makeSteps = (deps) => {
372
551
  const last = read.success;
373
552
  if (edgeDeclared(graph, last, step))
374
553
  return;
554
+ // A sub-workflow step run again as its workflow ends, after its run above was suspended, takes its own open record up
555
+ // again (`defineSubWorkflow`): that is no move. Read as one, every such resume of Decompile's Write C was said to be undeclared.
556
+ if (last !== null && !last.failed && last.step === step && DECLARED.get(workflow)?.steps().some((s) => s.name === step && s.kind === 'sub-workflow') === true)
557
+ return;
375
558
  const move = `${workflow}: ${last === null ? RUN_STARTS : `${last.step}${last.failed ? ' (failed)' : ''}`} to ${step}`;
376
559
  if (process.env.NODE_ENV === 'test')
377
560
  throw new Error(`a run took an edge its workflow does not declare: ${move}`);
@@ -420,13 +603,13 @@ export const makeSteps = (deps) => {
420
603
  let before = null;
421
604
  let recordId = null;
422
605
  let meter = new StepMeter(null, (step.runs === 'agentic'), [], null);
423
- /** Whether this agent step took an agent: past its slot, its task's mark as needing one clears when it ends. */
424
- let tookAnAgent = false;
606
+ // Its model, where it runs on one: its own, or what its workflows above or the app set (`settings.ts`), in code alone.
607
+ const model = step.runs === 'agentic' ? stepSetting({ declared: [...DECLARED.values()], app: deps.appSettings, stored: [] }, { workflow: instance.workflow._tag, step: step.name, name: 'model' }).value : null;
425
608
  return Effect.acquireUseRelease(Effect.flatMap(Effect.gen(function* () {
426
609
  yield* checkEdge(instance.workflow._tag, instance.executionId, step.name);
427
610
  yield* checkItem(instance.workflow._tag, instance.executionId, step.name, subject);
428
611
  // 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.
429
- 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 }) }));
612
+ 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, version: versionOf(instance.workflow._tag).version, ...(childRun === null ? {} : { resume: true }) }));
430
613
  if (id !== null && childRun !== null)
431
614
  yield* recorded('name the run it started', records.setStepChild({ id, childRun }));
432
615
  const beat = (step.runs === 'agentic') && id !== null ? setInterval(() => recordNow('its heartbeat', records.beatStepRun(id)), AGENT_BEAT_MS) : null;
@@ -444,7 +627,10 @@ export const makeSteps = (deps) => {
444
627
  }), (hashes) => {
445
628
  before = hashes;
446
629
  return opened;
447
- }))), () => pipe((step.runs === 'agentic') ? Effect.andThen(untilAgentSlot(instance, step.name, () => recordId), Effect.andThen(Effect.sync(() => { tookAnAgent = true; }), execute)) : execute,
630
+ }))), () => pipe(
631
+ // An agent step with no model set on it or above it stands down before it takes an agent (`NO_MODEL_STOOD_DOWN`).
632
+ (step.runs === 'agentic') && model === null ? Effect.andThen(Effect.logError(`[settings] ${instance.workflow._tag}: its agent step ${step.name} has no model set on it or on any workflow above it: set one with \`model\``), Effect.fail(NO_MODEL_STOOD_DOWN))
633
+ : (step.runs === 'agentic') ? Effect.andThen(claimAgentsOrEnd(instance.workflow._tag, instance.executionId, step.name), Effect.andThen(beforeAgentCall(instance, step.name), execute)) : execute,
448
634
  // What it changed, on its record, and a change it named outside where it may write refuses the step.
449
635
  Effect.tap(() => Effect.suspend(() => {
450
636
  const earlier = before;
@@ -462,20 +648,10 @@ export const makeSteps = (deps) => {
462
648
  stepFiles.undoFiles(snapshot, files.refused);
463
649
  return files.refused.length === 0 ? yield* Effect.void : yield* Effect.fail(`refused: it changed ${files.refused.join(', ')}, outside ${mayWrite.join(', ') || 'nothing it may write'}`);
464
650
  }));
465
- })), Effect.provideService(CurrentMeter, meter), Effect.provideService(deps.CurrentStepUsage, meter), (step.runs === 'agentic') ? Effect.provideService(AgentStep, { usage, report, touched: (inputs) => { toolInputs.push(...inputs); }, waiting: (why) => { if (recordId !== null)
651
+ })), Effect.provideService(CurrentMeter, meter), Effect.provideService(deps.CurrentStepUsage, meter), (step.runs === 'agentic' && model !== null) ? Effect.provideService(AgentStep, { usage, report, model, touched: (inputs) => { toolInputs.push(...inputs); }, waiting: (why) => { if (recordId !== null)
466
652
  recordNow('say what it waits on', records.setStepWaiting({ id: recordId, waiting: why })); } }) : (e) => e), ({ id, beat }, exit) => Effect.gen(function* () {
467
653
  if (beat !== null)
468
654
  clearInterval(beat);
469
- // An agent step that ran on a task marked as needing an agent clears the mark: it may need none now.
470
- if (tookAnAgent && (Exit.isSuccess(exit) || !Cause.hasInterrupts(exit.cause))) {
471
- const top = TOPS.get(instance.executionId) ?? { run: instance.executionId, workflow: instance.workflow._tag };
472
- const task = yield* taskOfTop(top);
473
- if (task !== null)
474
- yield* deps.tasks.agentStepRan({ task, by: { workflow: top.workflow, run: top.run, step: step.name } });
475
- }
476
- // Its agent slot is free for its workflow's next run waiting on one.
477
- if ((step.runs === 'agentic'))
478
- deps.wakes.wakePicksOf(TOPS.get(instance.executionId)?.workflow ?? instance.workflow._tag, 'an agent step ended');
479
655
  // An interrupted step is no move: the run does it again.
480
656
  if (Exit.isSuccess(exit) || !Cause.hasInterrupts(exit.cause))
481
657
  lastStepRan.set(instance.executionId, { step: step.name, failed: !Exit.isSuccess(exit) });
@@ -544,6 +720,22 @@ export const makeSteps = (deps) => {
544
720
  return Effect.fail(STOOD_DOWN);
545
721
  }));
546
722
  })));
723
+ /**
724
+ * A RUN STARTS NO STEP IN A PROCESS HANDING ITS RUNS TO THE NEXT (`pick-wakes.ts` `releaseWaiting`): it suspends on a
725
+ * durable clock, which the process that takes its shard next delivers, and that process replays it from its records and
726
+ * runs the step. A step already running finishes where it is, an agent's call included. Left to the engine, the run was
727
+ * abandoned without a reply, and the wake its sub-workflow step's workflow had sent it waited on that reply for ever: the
728
+ * run's entity, and its shard, stayed in the old process until it was killed. Four runs of Decompile sat between steps so
729
+ * for 13 minutes after the reload at 22:10 UTC on 2026-11-21 (`handover.test.ts`). The clock's name is this process's, so
730
+ * a later handover at the same step suspends the run again. What it gives keeps the activity's name, which a workflow's
731
+ * graph may name the step by.
732
+ */
733
+ const handedOverBeforeStep = (activity) => Object.assign(Effect.andThen(Effect.suspend(() => {
734
+ if (!deps.wakes.handingOver())
735
+ return Effect.void;
736
+ const self = deps.thisProcess();
737
+ return Effect.flatMap(WorkflowEngine.WorkflowInstance, (instance) => Effect.andThen(Effect.sync(() => console.log(`[handover] ${instance.workflow._tag} run ${instance.executionId} suspended before ${activity.name}: the next process runs it`)), DurableClock.sleep({ name: `handed over by pid ${self.pid} started at ${self.startedAt}, before ${activity.name}`, duration: Duration.seconds(1), inMemoryThreshold: Duration.zero })));
738
+ }), activity), { name: activity.name });
547
739
  /** One run of a workflow picks at a time: its choice is on its step record before the next reads what is taken. */
548
740
  const pickingOneAtATime = (workflow, pick) => {
549
741
  const lock = PICKING.get(workflow) ?? Semaphore.makeUnsafe(1);
@@ -555,7 +747,7 @@ export const makeSteps = (deps) => {
555
747
  const queued = queueOrder(tasks);
556
748
  const needAnAgent = queued.filter((t) => deps.tasks.passedOverNow(t) !== null).length;
557
749
  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`}`;
558
- }), Effect.catchTag('StorageError', (e) => Effect.succeed(`its tasks could not be read: ${e.reason}`)), 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`));
750
+ }), Effect.catchTag('StorageError', (e) => Effect.succeed(`its tasks could not be read: ${e.reason}`)), Effect.map((queued) => `no task it can claim (${queued}); it waits for a task returned to its queue, a new item, an agent claim ending, a run ending or a limit change`));
559
751
  /**
560
752
  * A PICK THAT FINDS NOTHING IT CAN CLAIM WAITS FOR AN EVENT THAT CAN CHANGE THAT (`pick-wakes.ts`), and never polls: one
561
753
  * open record, its `waiting` saying on what, and no new record while nothing changes. The run keeps its place in its
@@ -599,21 +791,27 @@ export const makeSteps = (deps) => {
599
791
  });
600
792
  /** A step: its declaration, and `run`, the only way to run it. */
601
793
  const defineStep = (d) => {
794
+ if (d.model !== undefined && d.runs !== 'agentic')
795
+ throw new Error(`${d.name} sets a model, and runs ${d.runs}: only an agent step runs on a model`);
602
796
  const writes = [...(d.mayWrite ?? []), ...(d.writes ?? [])];
603
797
  const declaration = {
604
798
  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 }),
605
799
  ...(writes.length === 0 ? {} : { writes }),
800
+ ...checkedSettings({ what: d.name, retentionDays: d.retentionDays, keepAtLeastRuns: d.keepAtLeastRuns, model: d.model }),
606
801
  source: d.prompt ?? { path: sourcePath(d.at), anchor: `'${d.name}'` },
607
802
  };
608
- return {
803
+ const step = {
609
804
  ...declaration,
610
- run: (execute, options) => Activity.make({
805
+ run: (execute, options) => handedOverBeforeStep(Activity.make({
611
806
  name: options?.call === undefined ? d.name : `${d.name} ${options.call}`,
612
807
  success: d.success,
613
808
  error: Schema.String,
614
809
  execute: pipe(standDownIfSurplus({ agent: d.runs === 'agentic', picks: d.picked !== undefined }), Effect.andThen(measured(declaration, options?.call ?? null, options?.subject ?? null, d.subject, d.reason, d.mayWrite, d.picked === undefined ? execute : untilPicked(d.picked, execute))), Effect.retry({ while: deps.isTransientFailure, times: 10, schedule: Schedule.spaced('3 seconds') }), Effect.mapError(describeFailure)),
615
- }),
810
+ })),
616
811
  };
812
+ // Its code as loaded now, for its workflow's version (`versionOf`): its file, and an agent step's prompt file.
813
+ STEP_CODE.set(step, [codeOf(d.at), ...(d.prompt === undefined ? [] : [codeOf(path.join(deps.sourceRoot, d.prompt.path))])]);
814
+ return step;
617
815
  };
618
816
  /**
619
817
  * "CLEARED" MEANS OFF THE LIST, by construction: a pass counts only if the list the workflow shows and Pick takes from no
@@ -653,13 +851,14 @@ export const makeSteps = (deps) => {
653
851
  *
654
852
  * the page shows the run above in this step, and the workflow's own view shows its steps and what they cost;
655
853
  * the workflow's steps work on the item the run above works on, with no code naming it (`StepRecords.openStepRun`);
656
- * its agent steps count against the agents' limit of the workflow at the top, and stand down with its run (`topOf`).
854
+ * its agent claim counts against the agents' limit of the workflow at the top, and its steps stand down with its run (`topOf`).
657
855
  *
658
856
  * 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
659
857
  * limit on a workflow used only as a step would fail the steps of runs already going.
660
858
  */
661
859
  const defineSubWorkflow = (d) => {
662
860
  const child = d.workflow._tag;
861
+ refuseSystem(child, 'no workflow of the app has it as a step');
663
862
  // What its workflow gave is what the step declares, or the step fails saying so: no result is taken on trust.
664
863
  const isDeclared = Schema.is(d.success);
665
864
  const given = (result) => (isDeclared(result) ? Effect.succeed(result) : Effect.fail(`${child} gave a result that is not what this step declares`));
@@ -676,6 +875,8 @@ export const makeSteps = (deps) => {
676
875
  const startedAndWaitedFor = (payload) => pipe(startAsAStep(payload), Effect.sandbox, Effect.catch((cause) => Effect.flatMap(WorkflowEngine.WorkflowInstance, (instance) => (Cause.hasInterruptsOnly(cause) && !instance.suspended && deps.wakes.handingOver() ? Workflow.suspend(instance) : Effect.failCause(cause)))));
677
876
  const declaration = {
678
877
  name, runs: null, kind: 'sub-workflow', workflow: child,
878
+ ...(d.agentKeptUntilThisRunEnds === true ? { agentKeptUntilThisRunEnds: true } : {}),
879
+ ...checkedSettings({ what: name, retentionDays: d.retentionDays, keepAtLeastRuns: d.keepAtLeastRuns, model: d.model }),
679
880
  description: DECLARED.get(child)?.description ?? `Runs ${child}.`,
680
881
  source: DECLARED.get(child)?.source ?? { path: sourcePath(d.at), anchor: `'${child}'` },
681
882
  agentUnder: () => {
@@ -692,14 +893,53 @@ export const makeSteps = (deps) => {
692
893
  };
693
894
  return {
694
895
  ...declaration,
695
- run: (payload, options) => Activity.make({
896
+ run: (payload, options) => handedOverBeforeStep(Activity.make({
696
897
  name: options?.call === undefined ? name : `${name} ${options.call}`,
697
898
  success: d.success,
698
899
  error: Schema.String,
699
900
  execute: pipe(standDownIfSurplus({ agent: false, picks: false }), Effect.andThen(Effect.flatMap(d.workflow.executionId(payload), (childRun) => measured(declaration, options?.call ?? null, null, undefined, undefined, undefined, Effect.flatMap(startedAndWaitedFor(payload), given), childRun))), Effect.mapError(describeFailure)),
700
- }),
901
+ })),
701
902
  };
702
903
  };
904
+ /**
905
+ * A STEP THAT IS ANOTHER WORKFLOW, ON ITS OWN TRIGGER. Alex, 2026-11-21: "just one fucking workflow that has steps some
906
+ * of which can be other workflows". A workflow whose steps are workflows that start themselves (on their queues, their
907
+ * inputs, a timer) holds them as any workflow holds its steps: the project's top, and each part of it, is one. No run of
908
+ * it starts them, so it has no runs of its own: its runs, agents and costs are theirs, added up (`isMadeOfWorkflows`).
909
+ * Define `workflow` before the workflow that has it as a step.
910
+ */
911
+ const defineWorkflowStep = (workflow) => {
912
+ refuseSystem(workflow, 'no workflow of the app has it as a step');
913
+ const d = DECLARED.get(workflow);
914
+ if (d === undefined)
915
+ throw new Error(`${workflow} is a step of a workflow defined before it: define ${workflow} first`);
916
+ return { name: workflow, runs: null, kind: 'sub-workflow', workflow, runsOnItsOwnTrigger: true, description: d.description, source: d.source, agentUnder: () => d.steps().some(stepUsesAnAgent) };
917
+ };
918
+ /** A workflow and every workflow under it, through each step that is a workflow. */
919
+ const withWorkflowsUnder = (name, seen = new Set()) => {
920
+ if (seen.has(name))
921
+ return seen;
922
+ seen.add(name);
923
+ for (const s of DECLARED.get(name)?.steps() ?? [])
924
+ if (s.workflow !== undefined)
925
+ withWorkflowsUnder(s.workflow, seen);
926
+ return seen;
927
+ };
928
+ /**
929
+ * THE STEP GRAPH OF A WORKFLOW MADE OF WORKFLOWS, from what feeds what (`WorkflowDeclaration.fedBy`): a step follows each
930
+ * of its fellow steps whose results become its tasks, at any depth under each; one none of them feeds is where work
931
+ * enters it, and one that feeds none of them is where its work leaves. The feeds are declared once, on the workflow fed.
932
+ */
933
+ const graphOfFeeds = (steps) => {
934
+ const under = new Map(steps.map((s) => [s, withWorkflowsUnder(s)]));
935
+ const feeds = (from, to) => from !== to && [...under.get(to)].some((w) => (DECLARED.get(w)?.fedBy ?? []).some((f) => under.get(from).has(f)));
936
+ const edges = steps.flatMap((to) => steps.filter((from) => feeds(from, to)).map((from) => ({ from, to, when: `its results become ${to}'s tasks` })));
937
+ return [
938
+ ...steps.filter((s) => !edges.some((e) => e.to === s)).map((s) => ({ from: RUN_STARTS, to: s, when: 'on its own trigger' })),
939
+ ...edges,
940
+ ...steps.filter((s) => !edges.some((e) => e.from === s)).map((s) => ({ from: s, to: RUN_ENDS, when: 'what it finishes leaves here' })),
941
+ ];
942
+ };
703
943
  /** Every workflow defined so far, in the order defined. */
704
944
  const declaredWorkflows = () => [...DECLARED.values()];
705
945
  /** Calls `listener` shortly after any run ends, when the engine has stored its end. */
@@ -732,8 +972,8 @@ export const makeSteps = (deps) => {
732
972
  const queueNow = (input) => Effect.gen(function* () {
733
973
  yield* readTaskInputs(input.workflow);
734
974
  const queue = queueOrder(yield* deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }));
735
- // While no agent can be had, a task marked as needing one is passed over (`agentsUnavailable`).
736
- return (yield* agentsUnavailable(input.workflow)) === null ? queue : queue.filter((t) => deps.tasks.passedOverNow(t) === null);
975
+ // While no agent is free, a task marked as needing one is passed over (`whyNoAgentIsFree`).
976
+ return (yield* whyNoAgentIsFree(input.workflow)) === null ? queue : queue.filter((t) => deps.tasks.passedOverNow(t) === null);
737
977
  });
738
978
  /**
739
979
  * WHY NO RUN OF A WORKFLOW CAN TAKE WORK NOW, none where one can: no agent can be had for it (`agentsUnavailable`), and
@@ -742,7 +982,9 @@ export const makeSteps = (deps) => {
742
982
  * as running: its trigger starts none (`keep-running.ts` `planRunStarts`), and a Pick that found nothing ends its run
743
983
  * rather than wait (`untilPicked`). An agent to be had (a limit lifted, the spending limit no longer holding), a mark
744
984
  * 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
745
- * step needs none. Read where it cannot be, it says nothing, and runs start and wait as before.
985
+ * step needs none. Read where it cannot be, it says nothing, and runs start and wait as before. Every agent merely in use
986
+ * is not this: one frees when a run holding one ends, so runs start and do their work with no agent, a run that reaches
987
+ * its agent step with none free gives its task back, and a Pick with nothing it can take waits for a claim to end.
746
988
  */
747
989
  const whyNoRunCanTakeWork = (workflow) => Effect.gen(function* () {
748
990
  // Its tasks' inputs, a read of every task's, are read again only where the inputs its last Pick read leave no work.
@@ -764,8 +1006,18 @@ export const makeSteps = (deps) => {
764
1006
  return null;
765
1007
  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`}`;
766
1008
  }), Effect.orElseSucceed(() => null));
767
- /** A workflow: what it states about itself, then `Workflow.make`'s own name and options. */
768
- const defineWorkflow = (d) => ((name, options) => {
1009
+ /**
1010
+ * A workflow: what it states about itself, then `Workflow.make`'s own name and options. `system` is the platform defining
1011
+ * one of its own (`system-workflows.ts`); an app's definition of one of those names is refused (`refuseSystem`).
1012
+ */
1013
+ const defineWorkflowAs = (system) => (d) => ((name, options) => {
1014
+ if (!system)
1015
+ refuseSystem(name, 'the app defines no workflow of its name');
1016
+ if (d.agentsClaimed !== undefined && !(Number.isInteger(d.agentsClaimed) && d.agentsClaimed >= 1))
1017
+ throw new Error(`${name} claims ${d.agentsClaimed} agents: a workflow claims a whole number of them, 1 or more, or states none`);
1018
+ // A main step is one of a workflow made of workflows, whose steps (`defineWorkflowStep`) are defined before it, so read now.
1019
+ if (d.mainStep !== undefined && !(isMadeOfWorkflows(d) && d.steps().some((s) => s.name === d.mainStep)))
1020
+ throw new Error(`${name}'s main step ${d.mainStep} is not one of its steps, each a workflow on its own trigger`);
769
1021
  // The one place a workflow's own types do not matter: every workflow passes through here the same way.
770
1022
  const workflow = Workflow.make(name, options);
771
1023
  /**
@@ -793,34 +1045,52 @@ export const makeSteps = (deps) => {
793
1045
  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`); });
794
1046
  return Effect.andThen(say, startOptions?.discard === true ? workflow.executionId(payload) : Effect.fail(new RunLimitReached({ workflow: name, limit: gate.limit })));
795
1047
  });
1048
+ WORKFLOW_CODE.set(name, codeOf(d.at));
796
1049
  DECLARED.set(name, {
797
- name, phase: d.phase, description: d.description, steps: d.steps,
1050
+ name, description: d.description, steps: d.steps,
798
1051
  ...(d.graph === undefined ? {} : { graph: d.graph }),
799
1052
  source: { path: sourcePath(d.at), anchor: `'${name}'` },
800
1053
  ...(d.pending === undefined ? {} : { pending: d.pending }),
801
1054
  ...(d.items === undefined ? {} : { items: d.items }),
802
1055
  ...(d.picksQueueHead === undefined ? {} : { picksQueueHead: d.picksQueueHead }),
803
1056
  ...(d.fedBy === undefined ? {} : { fedBy: d.fedBy }),
1057
+ ...(d.mainStep === undefined ? {} : { mainStep: d.mainStep }),
804
1058
  ...(d.inputs === undefined ? {} : { inputs: d.inputs }),
805
1059
  ...(d.taskInputs === undefined ? {} : { taskInputs: d.taskInputs }),
1060
+ ...checkedSettings({ what: name, retentionDays: d.retentionDays, keepAtLeastRuns: d.keepAtLeastRuns, model: d.model }),
806
1061
  item: d.item,
807
1062
  finishedWord: d.item === null ? null : d.finishedWord,
808
1063
  gate: d.item === null ? null : (d.gate ?? null),
809
1064
  start: (run) => gatedExecute({ run }, { discard: true }),
810
1065
  startOn: (payload, options) => Effect.asVoid(options.wait ? gatedExecute(payload) : gatedExecute(payload, { discard: true })),
811
1066
  executionIdOf: (payload) => workflow.executionId(payload),
1067
+ ...(system ? { system: true } : {}),
1068
+ ...(d.agentsClaimed === undefined ? {} : { agentsClaimed: d.agentsClaimed }),
812
1069
  });
1070
+ if (system)
1071
+ SYSTEM.add(name);
813
1072
  const toLayer = workflow.toLayer.bind(workflow);
814
1073
  // Its start as a step of another workflow, which no run limit of its own gates (`defineSubWorkflow`).
815
1074
  STARTS_AS_A_STEP.set(name, execute);
816
1075
  Object.assign(workflow, { execute: gatedExecute });
817
- // Every run of every workflow ends here: its items' outcomes are recorded, and the next run can start at once.
1076
+ // Read when a run starts or ends, once every workflow is declared: whether this one's tasks are its runs.
1077
+ const runsAreTasks = () => { const me = DECLARED.get(name); return me !== undefined && tasksAreRuns(me, [...DECLARED.values()]); };
1078
+ // A run claims at its first agent step (`measured`); one with no agent step of its own that declares agents claims as it starts.
1079
+ const claimsAsItStarts = () => { const me = DECLARED.get(name); return me !== undefined && agentsClaimedBy(me) > 0 && !me.steps().some((s) => s.runs === 'agentic'); };
1080
+ // Every run of every workflow ends here: its items' outcomes are recorded, and the next run can start at once. A
1081
+ // workflow whose tasks are its runs gets its run's task as the run starts, and its outcome as it ends. A run of one
1082
+ // that claims agents takes its claim at its first agent step, or here where it has none, and ends it as it ends
1083
+ // (`claimAgentsOrEnd`, `endClaims`).
818
1084
  return Object.assign(workflow, {
819
- toLayer: (execute) => toLayer((payload, executionId) => Effect.onExit(execute(payload, executionId), (exit) => Effect.flatMap(
1085
+ toLayer: (execute) => toLayer((payload, executionId) => Effect.andThen(runsAreTasks() ? Effect.tap(deps.tasks.runStarted({ workflow: name, run: executionId }), () => Effect.sync(() => deps.queueChanged(name))) : Effect.void, Effect.onExit(Effect.andThen(claimsAsItStarts() ? claimAgentsOrEnd(name, executionId, name) : Effect.void, Effect.suspend(() => execute(payload, executionId))), (exit) => Effect.flatMap(
820
1086
  // 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)
821
1087
  // left nothing new for the next. Taken when it picked, 490 Tests ran on 107 functions in 41 minutes (2026-11-14).
822
1088
  !Exit.isSuccess(exit) && Cause.hasInterrupts(exit.cause) || d.item === null ? Effect.succeed(null) : Effect.orElseSucceed(readTaskInputs(name), () => null), (leftWith) => Effect.gen(function* () {
823
1089
  const interrupted = !Exit.isSuccess(exit) && Cause.hasInterrupts(exit.cause);
1090
+ const me = DECLARED.get(name);
1091
+ // Its own claim, or one a sub-workflow step of it took for it (`agentKeptUntilThisRunEnds`), ends with it.
1092
+ if (me !== undefined && (agentsClaimedBy(me) > 0 || me.steps().some((s) => s.agentKeptUntilThisRunEnds === true)))
1093
+ yield* endClaims(executionId, exit);
824
1094
  const runItem = yield* recorded('read its item', records.subjectOfRun(executionId));
825
1095
  const inputsLeft = (subject) => {
826
1096
  const item = subject ?? runItem;
@@ -838,6 +1108,17 @@ export const makeSteps = (deps) => {
838
1108
  yield* deps.tasks.appendOutcome({ workflow: name, run: executionId, subject: null, outcome, finished: false, inputs: inputsLeft(null), blocked: null });
839
1109
  }
840
1110
  }
1111
+ // A RUN'S OWN TASK: done when it succeeds; blocked when it fails or stands down, with why in words the page
1112
+ // counts by (the step it failed at, or the stand-down's reason), the failure itself on the outcome note.
1113
+ if (!interrupted && runsAreTasks()) {
1114
+ const failure = Exit.isSuccess(exit) ? null : Cause.squash(exit.cause);
1115
+ const stoodDown = failure !== null && isStoodDown(failure);
1116
+ yield* deps.tasks.appendOutcome({
1117
+ workflow: name, run: executionId, subject: executionId, finished: failure === null, inputs: null,
1118
+ outcome: failure === null ? 'succeeded' : stoodDown ? STOOD_DOWN_OUTCOME : `failed: ${startAndEnd(describeFailure(failure), { cap: 1000, end: 400, what: 'the failure' })}`,
1119
+ blocked: failure === null ? null : stoodDown ? String(failure) : `failed at ${lastStepRan.get(executionId)?.step ?? 'its first step'}`,
1120
+ });
1121
+ }
841
1122
  // What it ran on gave this result, which stands until its inputs change. Only a run its trigger started on its
842
1123
  // inputs has a record to end.
843
1124
  if (d.inputs !== undefined) {
@@ -853,9 +1134,10 @@ export const makeSteps = (deps) => {
853
1134
  // Its claim and its item are free now for its workflow's other runs, once the engine has stored its end. Only its
854
1135
  // own: about 25 short runs end a minute, and waking every Pick on each re-read every task twice each time.
855
1136
  setTimeout(() => deps.wakes.wakePicksOf(name, 'one of its runs ended'), 1000);
856
- })))),
1137
+ }))))),
857
1138
  });
858
1139
  });
1140
+ const defineWorkflow = defineWorkflowAs(false);
859
1141
  /**
860
1142
  * RUNS A WORKFLOW ON `payload` ONLY WHEN ITS INPUTS CHANGED since its last successful run: it reads their fingerprint, and
861
1143
  * when it is that run's, the result that run stored stands and nothing starts. Otherwise the run starts, recorded with the
@@ -884,20 +1166,20 @@ export const makeSteps = (deps) => {
884
1166
  * `queueNow` settles it: none blocked, another run's left out. `fromItem` builds a candidate for a task a step or a person
885
1167
  * returned to the queue that the candidates do not hold.
886
1168
  */
887
- const pickOrder = (input) => Effect.map(Effect.all({ tasks: deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }), unavailable: agentsUnavailable(input.workflow) }), ({ tasks, unavailable }) => inPickOrder({
1169
+ const pickOrder = (input) => Effect.map(Effect.all({ tasks: deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }), noAgentFree: whyNoAgentIsFree(input.workflow) }), ({ tasks, noAgentFree }) => inPickOrder({
888
1170
  candidates: input.candidates, subjectOf: input.subjectOf, tasks, ...(input.fromItem === undefined ? {} : { fromItem: input.fromItem }),
889
- // While no agent can be had, a task marked as needing one is passed over (`agentsUnavailable`).
890
- ...(unavailable === null ? {} : { alsoLeaveOut: new Set(tasks.filter((t) => deps.tasks.passedOverNow(t) !== null).map((t) => t.ref.item)) }),
1171
+ // While no agent is free, a task marked as needing one is passed over (`whyNoAgentIsFree`).
1172
+ ...(noAgentFree === null ? {} : { alsoLeaveOut: new Set(tasks.filter((t) => deps.tasks.passedOverNow(t) !== null).map((t) => t.ref.item)) }),
891
1173
  }));
892
1174
  /**
893
1175
  * 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
894
1176
  * the other heavy jobs), `start` leaves it to the engine.
895
1177
  */
896
- const oneStepWorkflow = (
897
- // One step of the project's code: no agent, and no single item.
1178
+ const oneStepWorkflowAs = (system) => (
1179
+ // One step of the project's code: no agent, and no single item. `reason` is what its record says it did (`defineStep`).
898
1180
  states, name, step, success, execute) => {
899
- const theStep = defineStep({ name: step, runs: 'deterministic', shared: true, description: states.stepDescription, at: states.at, success, ...(states.writes === undefined ? {} : { writes: states.writes }) });
900
- const workflow = defineWorkflow({ phase: states.phase, description: states.description, at: states.at, steps: () => [theStep], item: null, ...(states.inputs === undefined ? {} : { inputs: states.inputs }),
1181
+ const theStep = defineStep({ name: step, runs: 'deterministic', shared: true, description: states.stepDescription, at: states.at, success, ...(states.writes === undefined ? {} : { writes: states.writes }), ...(states.reason === undefined ? {} : { reason: states.reason }) });
1182
+ const workflow = defineWorkflowAs(system)({ description: states.description, at: states.at, steps: () => [theStep], item: null, ...(states.inputs === undefined ? {} : { inputs: states.inputs }),
901
1183
  graph: () => [{ from: RUN_STARTS, to: step, when: 'each turn' }, { from: step, to: RUN_ENDS, when: 'always' }] })(name, {
902
1184
  payload: { turn: Schema.Number },
903
1185
  idempotencyKey: ({ turn }) => String(turn),
@@ -911,10 +1193,13 @@ export const makeSteps = (deps) => {
911
1193
  start: (turn) => Effect.asVoid(runIfInputsChanged({ workflow: name, payload: { turn }, wait: false })),
912
1194
  };
913
1195
  };
1196
+ const oneStepWorkflow = oneStepWorkflowAs(false);
914
1197
  return {
915
- defineStep, defineItemTest, defineSubWorkflow, defineWorkflow, oneStepWorkflow, declaredWorkflows, onRunEnded,
1198
+ defineStep, defineItemTest, defineSubWorkflow, defineWorkflowStep, graphOfFeeds, defineWorkflow, oneStepWorkflow, declaredWorkflows, onRunEnded,
916
1199
  eachItem, undoAgentStep, AgentBudgets, pickingOneAtATime, pickOrder, itemsOfOtherRuns,
917
- runsOldestFirst, runningRunIds, runningRuns, sourcePath, runIfInputsChanged, queueNow, readTaskInputs, agentsUnavailable, whyNoRunCanTakeWork,
1200
+ runsOldestFirst, runningRunIds, runningRuns, sourcePath, runIfInputsChanged, queueNow, readTaskInputs, whyNoAgentIsFree, whyNoRunCanTakeWork, versionOf, agentClaimsNow,
1201
+ /** The platform's own one-step workflows are defined by this (`system-workflows.ts`); `createWorkflowPlatform` keeps it from the app. */
1202
+ oneStepSystemWorkflow: oneStepWorkflowAs(true),
918
1203
  };
919
1204
  };
920
1205
  //# sourceMappingURL=steps.js.map