@jive-sh/workflow-platform 0.3.3 → 0.5.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 (61) hide show
  1. package/README.md +68 -23
  2. package/dist/dashboard/agent-usage.js +25 -0
  3. package/dist/dashboard/agent-usage.js.map +1 -0
  4. package/dist/dashboard/drilldown.js +16 -0
  5. package/dist/dashboard/drilldown.js.map +1 -0
  6. package/dist/dashboard/queue-lines.js +44 -0
  7. package/dist/dashboard/queue-lines.js.map +1 -0
  8. package/dist/index.js +8 -6
  9. package/dist/index.js.map +1 -1
  10. package/dist/keep-running.js +1 -1
  11. package/dist/keep-running.js.map +1 -1
  12. package/dist/pick-wakes.js +4 -4
  13. package/dist/pick-wakes.js.map +1 -1
  14. package/dist/queue-counts.js +7 -9
  15. package/dist/queue-counts.js.map +1 -1
  16. package/dist/steps.js +157 -41
  17. package/dist/steps.js.map +1 -1
  18. package/dist/storage/sqlite-store.js +117 -38
  19. package/dist/storage/sqlite-store.js.map +1 -1
  20. package/dist/storage/task-store.js +14 -1
  21. package/dist/storage/task-store.js.map +1 -1
  22. package/dist/tasks.js +215 -267
  23. package/dist/tasks.js.map +1 -1
  24. package/dist/views/runs-now.js +3 -2
  25. package/dist/views/runs-now.js.map +1 -1
  26. package/dist/views/step-funnel.js +1 -1
  27. package/dist/views/step-funnel.js.map +1 -1
  28. package/dist/views/step-graph.js +1 -1
  29. package/dist/views/step-graph.js.map +1 -1
  30. package/dist/views/workflow-flows.js +2 -2
  31. package/dist/views/workflow-flows.js.map +1 -1
  32. package/dist/views/workflows-view.js +83 -17
  33. package/dist/views/workflows-view.js.map +1 -1
  34. package/package.json +1 -1
  35. package/src/dashboard/agent-usage-line.tsx +28 -0
  36. package/src/dashboard/agent-usage.ts +48 -0
  37. package/src/dashboard/dashboard.css +70 -29
  38. package/src/dashboard/drilldown.ts +43 -0
  39. package/src/dashboard/index.tsx +1 -0
  40. package/src/dashboard/machine-controls.tsx +53 -0
  41. package/src/dashboard/queue-bar.tsx +43 -0
  42. package/src/dashboard/queue-chart.tsx +89 -76
  43. package/src/dashboard/queue-lines.ts +87 -0
  44. package/src/dashboard/step-graph.tsx +18 -10
  45. package/src/dashboard/workflow-dag.tsx +31 -103
  46. package/src/dashboard/workflow-drilldown.tsx +89 -0
  47. package/src/dashboard/workflows-dashboard.tsx +117 -42
  48. package/src/index.ts +11 -9
  49. package/src/keep-running.ts +3 -3
  50. package/src/pick-wakes.ts +14 -9
  51. package/src/queue-counts.ts +10 -14
  52. package/src/steps.ts +213 -52
  53. package/src/storage/sqlite-store.ts +126 -39
  54. package/src/storage/step-records.ts +14 -3
  55. package/src/storage/task-store.ts +97 -22
  56. package/src/tasks.ts +235 -301
  57. package/src/views/runs-now.ts +5 -4
  58. package/src/views/step-funnel.ts +2 -2
  59. package/src/views/step-graph.ts +4 -4
  60. package/src/views/workflow-flows.ts +7 -7
  61. package/src/views/workflows-view.ts +117 -35
package/src/steps.ts CHANGED
@@ -6,7 +6,7 @@
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
- * const PICK = defineStep({ name: 'Pick', agent: false, description: '...', at: import.meta.path, success: Schema.Number });
9
+ * const PICK = defineStep({ name: 'Pick', runs: 'deterministic', description: '...', at: import.meta.path, success: Schema.Number });
10
10
  * export const MyWorkflow = defineWorkflow({ phase: 'main', 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 })
@@ -23,7 +23,7 @@
23
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
24
  * exact failure as its input; one that cannot be tested says why.
25
25
  *
26
- * An agent call needs `AgentStep`, which only an `agent: true` step provides, so it cannot compile anywhere else.
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
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
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
@@ -31,7 +31,7 @@
31
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
32
  * it asks `isStoodDown`.
33
33
  *
34
- * EVERY ITEM IS A TASK, in a bucket the engine keeps (`tasks.ts`). A Pick orders its own candidates through `pickOrder`, or
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
35
  * takes its queue's head; a Pick that finds nothing waits for an event that can change that (`picked`, `pick-wakes.ts`),
36
36
  * so a run never ends for want of an item.
37
37
  *
@@ -72,7 +72,7 @@ export interface ApiUsage {
72
72
  readonly output_tokens?: number | null;
73
73
  }
74
74
 
75
- /** Provided only inside an `agent: true` step; an agent call reports what it spent through it. */
75
+ /** Provided only inside a step that runs agentically; an agent call reports what it spent through it. */
76
76
  export class AgentStep extends Context.Service<AgentStep, {
77
77
  /** A request's usage so far, by the message it belongs to, as it arrives: the step's record shows it at once. */
78
78
  readonly usage: (message: string, model: string | null, usage: ApiUsage) => void;
@@ -89,15 +89,54 @@ export const CLEARED_BY_TEST = 'cleared by its test, no agent';
89
89
 
90
90
  /** What an agent step fails with when its run is one too many for its workflow's budget. Stored as the step's result. */
91
91
  export const STOOD_DOWN = 'stood down: its workflow has more runs going than its budget';
92
- export const isStoodDown = (failure: unknown): boolean => failure === STOOD_DOWN;
92
+ /**
93
+ * What a step waiting for work or for an agent fails with when its process hands its runs to the next one
94
+ * (`pick-wakes.ts` `releaseWaiting`): its run stands down untried, and the next process starts one.
95
+ */
96
+ export const HANDED_OVER = 'stood down: its process is handing its runs to the next';
97
+ export const isStoodDown = (failure: unknown): boolean => failure === STOOD_DOWN || failure === HANDED_OVER;
93
98
 
94
99
  /** 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. */
95
100
  export const surplusRun = (oldestFirst: ReadonlyArray<string>, run: string, budget: number): boolean => oldestFirst.indexOf(run) >= budget;
101
+ /**
102
+ /**
103
+ * 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,
104
+ * like a sub workflow."
105
+ *
106
+ * step does part of the work;
107
+ * check decides whether the work passes;
108
+ * sub-workflow a workflow used as a step of another workflow (`StepDeclaration.workflow` names it).
109
+ */
110
+ export const STEP_KINDS = ['step', 'check', 'sub-workflow'] as const;
111
+ export type StepKind = (typeof STEP_KINDS)[number];
112
+
113
+ /**
114
+ * 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
115
+ * should be labeled as one of the following 'deterministic', 'agentic' or 'classification' where that third option allows
116
+ * for steps which use a separate classifier model".
117
+ *
118
+ * deterministic code only;
119
+ * agentic an agent does it: it waits for one of its workflow's agents (`untilAgentSlot`);
120
+ * classification a separate classifier model decides.
121
+ *
122
+ * A step or a check is any of the three. A sub-workflow step states none: its workflow's own steps state theirs.
123
+ */
124
+ export const STEP_RUNS = ['deterministic', 'agentic', 'classification'] as const;
125
+ export type StepRuns = (typeof STEP_RUNS)[number];
126
+
127
+ /** A step's kind, from its declaration: the kind it states, a check where it is its workflow's test, a step otherwise. Pure. */
128
+ export const stepKindOf = (s: Pick<StepDeclaration, 'test' | 'kind'>): StepKind => s.kind ?? (s.test === true ? 'check' : 'step');
96
129
 
97
130
  export interface StepDeclaration {
98
131
  readonly name: string;
99
- /** Whether this step needs an agent. */
100
- readonly agent: boolean;
132
+ /** How it runs; none for a sub-workflow step. */
133
+ readonly runs: StepRuns | null;
134
+ /** What it is where it is not a plain step (`stepKindOf`). */
135
+ readonly kind?: 'check' | 'sub-workflow';
136
+ /** For a sub-workflow step: the workflow it runs, by name. */
137
+ readonly workflow?: string;
138
+ /** For a sub-workflow step: whether its workflow has an agent step, at any depth under it. */
139
+ readonly agentUnder?: () => boolean;
101
140
  /** Whether this is the no-agent test an item goes through before any agent sees it. */
102
141
  readonly test?: boolean;
103
142
  /** One line on what it does, for its hover. */
@@ -129,6 +168,11 @@ export interface RunOutcome {
129
168
  readonly outcome: string;
130
169
  /** Whether this ended the item's work: recovered, provided, fixed. */
131
170
  readonly finished: boolean;
171
+ /**
172
+ * 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
173
+ * the queue (`tasks.ts` `requeue`). Absent, it goes back to the queue.
174
+ */
175
+ readonly blocked?: string;
132
176
  }
133
177
 
134
178
  /** The check a workflow's finished items must pass, in plain words, and whether an outcome reached it. */
@@ -176,14 +220,19 @@ export interface WorkflowDeclaration<Phase extends string = string, R = never> {
176
220
  readonly gate: WorkflowGate | null;
177
221
  /** Starts one run, for the trigger alone. */
178
222
  readonly start: (run: string) => Effect.Effect<unknown, unknown, WorkflowEngine.WorkflowEngine>;
179
- /** Its work now. A workflow with an agent step and a list runs only on this. */
223
+ /**
224
+ * ITS LIST, in one of two kinds (`TaskStore.recordListing`). `pending`: its work left; an item that leaves it without a
225
+ * passing final check is no longer its task, and a done one it lists again goes back to its queue. `items`: every item
226
+ * 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
227
+ * and a list runs only on its list.
228
+ */
180
229
  readonly pending?: () => Effect.Effect<PendingWork, unknown, R>;
230
+ readonly items?: () => Effect.Effect<ReadonlyArray<string>, unknown, R>;
181
231
  /** Its Pick takes the first task of its queue it can claim (`tasks.ts` `queueOrder`), so a dashboard lists that queue. */
182
232
  readonly picksQueueHead?: true;
183
233
  /**
184
- * The workflows whose results it works on: what its list of work (`pending`) is made from, or what its inputs (`inputs`)
185
- * read. The dashboard draws each as an edge into it, and a workflow that gives one upstream of it new input
186
- * (`giveNewInput`) is sending work back. None where it works on no other workflow's results.
234
+ * The workflows whose results become its tasks: the arrows of the project's map (`views/workflow-flows.ts`). A workflow
235
+ * used as a step of another needs none: it is drawn inside that one.
187
236
  */
188
237
  readonly fedBy?: ReadonlyArray<string>;
189
238
  /** Its step graph (`StepEdge`); none until it declares one. */
@@ -211,12 +260,18 @@ const REFUSED_SAID_EVERY_MS = 10 * 60 * 1000;
211
260
  * A WORKFLOW'S RUN LIMIT, whatever starts it: for one its budget keeps going, its run limit or its agents' limit
212
261
  * (`runLimit`); for any other its run limit, none meaning no limit. 0 starts nothing new. Pure.
213
262
  */
214
- export const runLimitOf = (d: Pick<WorkflowDeclaration<string, unknown>, 'pending' | 'steps'>, limits: WorkflowLimits): number | null =>
263
+ export const runLimitOf = (d: Pick<WorkflowDeclaration<string, unknown>, 'pending' | 'items' | 'steps'>, limits: WorkflowLimits): number | null =>
215
264
  keptRunningByItsBudget(d) ? runLimit(limits) : limits.runs;
216
265
 
217
- /** Whether a workflow's budget rules it: an agent step and a declared list of work. Pure. */
218
- export const keptRunningByItsBudget = (d: Pick<WorkflowDeclaration<string, unknown>, 'pending' | 'steps'>): boolean =>
219
- d.pending !== undefined && d.steps().some((s) => s.agent);
266
+ /** Whether a workflow declares a list, of either kind: it has tasks and a queue. Pure. */
267
+ export const hasAList = (d: Pick<WorkflowDeclaration<string, unknown>, 'pending' | 'items'>): boolean => d.pending !== undefined || d.items !== undefined;
268
+
269
+ /** Whether a step uses an agent: it is an agent step, or a sub-workflow step whose workflow has one at any depth. Pure. */
270
+ export const stepUsesAnAgent = (s: Pick<StepDeclaration, 'runs' | 'agentUnder'>): boolean => s.runs === 'agentic' || s.agentUnder?.() === true;
271
+
272
+ /** Whether a workflow's budget rules it: a declared list, and an agent step of its own or under a sub-workflow step. Pure. */
273
+ export const keptRunningByItsBudget = (d: Pick<WorkflowDeclaration<string, unknown>, 'pending' | 'items' | 'steps'>): boolean =>
274
+ hasAList(d) && d.steps().some(stepUsesAnAgent);
220
275
 
221
276
 
222
277
  /** An unfinished run of a workflow with an agent step. */
@@ -358,26 +413,46 @@ export const makeSteps = <Phase extends string, R>(deps: {
358
413
  const unreadLimits = <A>(workflow: string, held: (why: string) => A) => (e: StorageError): Effect.Effect<A> =>
359
414
  Effect.as(Effect.logError(`[budget] ${workflow}: its limits could not be read (${e.reason}); its runs wait`), held(e.reason));
360
415
 
416
+ /**
417
+ * 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
418
+ * (`StepRecords.rootOfRun`). A workflow's limits govern every run under its runs, so a sub-workflow's agent step counts
419
+ * against the agents' limit of the workflow at the top. Kept while the run goes: it never changes.
420
+ */
421
+ const TOPS = new Map<string, { readonly run: string; readonly workflow: string }>();
422
+ const topOf = (workflow: string, run: string): Effect.Effect<{ readonly run: string; readonly workflow: string }, StorageError> => {
423
+ const known = TOPS.get(run);
424
+ if (known !== undefined) return Effect.succeed(known);
425
+ return Effect.map(records.rootOfRun(run), (root) => {
426
+ const top = root ?? { run, workflow };
427
+ TOPS.set(run, top);
428
+ return top;
429
+ });
430
+ };
431
+
361
432
  const AgentBudgets = Context.Reference<AgentBudgetRules>('AgentBudgets', {
362
433
  defaultValue: () => ({
363
434
  // Among its workflow's unfinished runs, oldest first, the run is past those its run limit keeps (`runLimit`). A run not
364
- // listed is not counted.
365
- standsDown: (workflow, run) => pipe(pastItsRunLimit(workflow, run), Effect.catchTag('StorageError', unreadLimits(workflow, () => false))),
435
+ // listed is not counted. A run a sub-workflow step started stands down with the run at its top.
436
+ standsDown: (workflow, run) => pipe(
437
+ topOf(workflow, run),
438
+ Effect.flatMap((top) => Effect.zipWith(pastItsRunLimit(workflow, run), top.run === run ? Effect.succeed(false) : pastItsRunLimit(top.workflow, top.run), (own, above) => own || above)),
439
+ Effect.catchTag('StorageError', unreadLimits(workflow, () => false)),
440
+ ),
366
441
  waitsForWork: (workflow, run) => pipe(pastItsRunLimit(workflow, run), Effect.map((past) => !past), Effect.catchTag('StorageError', unreadLimits(workflow, () => true))),
367
- // Its other runs in an agent step, a waiting one not counted, against its agents' limit: at 0 none is ever free, and its
368
- // runs wait at their first agent step until the limit is raised.
442
+ // The other runs of the workflow at its top that an agent works for, a waiting one not counted, against that
443
+ // workflow's agents' limit: at 0 none is ever free, and its runs wait at their first agent step until the limit is raised.
369
444
  agentSlot: (workflow, run) => pipe(
370
- limitsOf(workflow),
371
- Effect.flatMap((w): Effect.Effect<{ readonly free: true } | { readonly free: false; readonly why: string }, StorageError> => {
445
+ topOf(workflow, run),
446
+ Effect.flatMap((top) => Effect.flatMap(limitsOf(top.workflow), (w): Effect.Effect<{ readonly free: true } | { readonly free: false; readonly why: string }, StorageError> => {
372
447
  const agents = w === null ? null : w.agents;
373
448
  if (agents === null) return Effect.succeed({ free: true });
374
449
  if (agents === 0) return Effect.succeed({ free: false, why: 'waits for an agent: its agents\x27 limit is 0' });
375
- return Effect.map(Effect.all({ runs: runsOldestFirst([workflow]), inAgentStep: records.runsInAgentStep(workflow) }), ({ runs, inAgentStep }) => {
450
+ return Effect.map(Effect.all({ runs: runsOldestFirst([top.workflow]), inAgentStep: records.runsInAgentStep(top.workflow) }), ({ runs, inAgentStep }) => {
376
451
  const going = new Set(runs);
377
- const busy = inAgentStep.filter((r) => r !== run && going.has(r)).length;
452
+ const busy = inAgentStep.filter((r) => r !== top.run && going.has(r)).length;
378
453
  return busy < agents ? { free: true } : { free: false, why: `waits for an agent: ${busy} of its ${agents} in use` };
379
454
  });
380
- }),
455
+ })),
381
456
  Effect.catchTag('StorageError', unreadLimits(workflow, (why) => ({ free: false as const, why: `waits for an agent: its limits could not be read (${why})` }))),
382
457
  ),
383
458
  }),
@@ -391,9 +466,11 @@ export const makeSteps = <Phase extends string, R>(deps: {
391
466
  const untilAgentSlot = (instance: { readonly workflow: { readonly _tag: string }; readonly executionId: string }, record: () => number | null) => Effect.gen(function* () {
392
467
  const rules = yield* AgentBudgets;
393
468
  const workflow = instance.workflow._tag;
469
+ // 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.
470
+ const heardOn = (yield* Effect.orElseSucceed(topOf(workflow, instance.executionId), () => ({ run: instance.executionId, workflow }))).workflow;
394
471
  let waited = false;
395
472
  for (;;) {
396
- const wakes = deps.wakes.pickWakesSoFar(workflow);
473
+ const wakes = deps.wakes.pickWakesSoFar(heardOn);
397
474
  if (yield* rules.standsDown(workflow, instance.executionId)) return yield* Effect.fail(STOOD_DOWN);
398
475
  const slot = yield* rules.agentSlot(workflow, instance.executionId);
399
476
  const id = record();
@@ -406,7 +483,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
406
483
  }
407
484
  if (id !== null) yield* recorded('say what it waits on', records.setStepWaiting({ id, waiting: slot.why }));
408
485
  waited = true;
409
- yield* deps.wakes.untilPickWoken({ workflow, after: wakes });
486
+ if ((yield* deps.wakes.untilPickWoken({ workflow: heardOn, after: wakes })) === 'released') return yield* Effect.fail(HANDED_OVER);
410
487
  }
411
488
  });
412
489
 
@@ -428,7 +505,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
428
505
  });
429
506
 
430
507
  /** Runs `execute` as this step of the workflow it is in, and writes its record. */
431
- 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>) =>
508
+ 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) =>
432
509
  Effect.flatMap(WorkflowEngine.WorkflowInstance, (instance) => {
433
510
  // A call's running sum is by request; its final figures replace it. `settled` is what finished calls reported.
434
511
  const settled = noSpend();
@@ -460,14 +537,16 @@ export const makeSteps = <Phase extends string, R>(deps: {
460
537
  const toolInputs: string[] = [];
461
538
  let before: TreeHashes | null = null;
462
539
  let recordId: number | null = null;
463
- let meter = new StepMeter(null, step.agent, [], null);
540
+ let meter = new StepMeter(null, (step.runs === 'agentic'), [], null);
464
541
  return Effect.acquireUseRelease(
465
542
  Effect.flatMap(Effect.gen(function* () {
466
543
  yield* checkEdge(instance.workflow._tag, instance.executionId, step.name);
467
- const id = yield* recorded('open its record', records.openStepRun({ workflow: instance.workflow._tag, run: instance.executionId, step: step.name, call, agent: step.agent, subject }));
468
- const beat = step.agent && id !== null ? setInterval(() => recordNow('its heartbeat', records.beatStepRun(id)), AGENT_BEAT_MS) : null;
544
+ // 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.
545
+ 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 }) }));
546
+ if (id !== null && childRun !== null) yield* recorded('name the run it started', records.setStepChild({ id, childRun }));
547
+ const beat = (step.runs === 'agentic') && id !== null ? setInterval(() => recordNow('its heartbeat', records.beatStepRun(id)), AGENT_BEAT_MS) : null;
469
548
  recordId = id;
470
- meter = new StepMeter(id, step.agent, step.writes ?? [], null);
549
+ meter = new StepMeter(id, (step.runs === 'agentic'), step.writes ?? [], null);
471
550
  meterOpened(meter);
472
551
  return { id, beat };
473
552
  }), (opened) => (mayWrite === undefined
@@ -481,7 +560,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
481
560
  return opened;
482
561
  }))),
483
562
  () => pipe(
484
- step.agent ? Effect.andThen(untilAgentSlot(instance, () => recordId), execute) : execute,
563
+ (step.runs === 'agentic') ? Effect.andThen(untilAgentSlot(instance, () => recordId), execute) : execute,
485
564
  // What it changed, on its record, and a change it named outside where it may write refuses the step.
486
565
  Effect.tap(() => Effect.suspend(() => {
487
566
  const earlier = before;
@@ -498,12 +577,12 @@ export const makeSteps = <Phase extends string, R>(deps: {
498
577
  })),
499
578
  Effect.provideService(CurrentMeter, meter),
500
579
  Effect.provideService(deps.CurrentStepUsage, meter),
501
- step.agent ? 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,
580
+ (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,
502
581
  ) as Effect.Effect<A, E, Exclude<R2, AgentStep>>,
503
582
  ({ id, beat }, exit) => Effect.gen(function* () {
504
583
  if (beat !== null) clearInterval(beat);
505
584
  // Its agent slot is free for its workflow's next run waiting on one.
506
- if (step.agent) deps.wakes.wakePicksOf(instance.workflow._tag, 'an agent step ended');
585
+ if ((step.runs === 'agentic')) deps.wakes.wakePicksOf(TOPS.get(instance.executionId)?.workflow ?? instance.workflow._tag, 'an agent step ended');
507
586
  // An interrupted step is no move: the run does it again.
508
587
  if (Exit.isSuccess(exit) || !Cause.hasInterrupts(exit.cause)) lastStepRan.set(instance.executionId, { step: step.name, failed: !Exit.isSuccess(exit) });
509
588
  meterClosed(meter);
@@ -515,6 +594,8 @@ export const makeSteps = <Phase extends string, R>(deps: {
515
594
  const idleBatch = step.perItem === true && Exit.isSuccess(exit) && used.childCpuSeconds === 0 && used.compiles === 0;
516
595
  const scope: StepScope = meter.items > 0 ? 'functions' : step.shared === true ? 'shared' : idleBatch ? 'none due' : subjectOf !== undefined && Exit.isSuccess(exit) && named === null ? 'nothing' : 'undeclared';
517
596
  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 }));
597
+ // A sub-workflow step whose run is suspended until its workflow ends is still in that step: its record stays open.
598
+ else if (Cause.hasInterrupts(exit.cause) && childRun !== null && instance.suspended) yield* Effect.void;
518
599
  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 }));
519
600
  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 }));
520
601
  }),
@@ -567,7 +648,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
567
648
  deps.tasks.taskSummaries({ workflow }),
568
649
  Effect.map((tasks) => `${queueOrder(tasks).length} queued${queueOrder(tasks).length === 0 ? '' : ', none it can claim now'}`),
569
650
  Effect.catchTag('StorageError', (e) => Effect.succeed(`its tasks could not be read: ${e.reason}`)),
570
- Effect.map((queued) => `no task it can claim (${queued}); it waits for new input, a reopen, a release, a run ending or a limit change`),
651
+ 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`),
571
652
  );
572
653
 
573
654
  /**
@@ -598,14 +679,15 @@ export const makeSteps = <Phase extends string, R>(deps: {
598
679
  }
599
680
  if (record !== null) yield* recorded('say what it waits on', records.setStepWaiting({ id: record, waiting: yield* nothingToClaim(workflow) }));
600
681
  waited = true;
601
- yield* deps.wakes.untilPickWoken({ workflow, after: wakes });
682
+ if ((yield* deps.wakes.untilPickWoken({ workflow, after: wakes })) === 'released') return yield* Effect.fail(HANDED_OVER);
602
683
  }
603
684
  });
604
685
 
605
686
  /** A step: its declaration, and `run`, the only way to run it. */
606
687
  const defineStep = <A>(d: {
607
688
  readonly name: string;
608
- readonly agent: boolean;
689
+ /** How it runs (`StepRuns`). */
690
+ readonly runs: StepRuns;
609
691
  readonly description: string;
610
692
  /** `import.meta.path`, for its link. */
611
693
  readonly at: string;
@@ -616,6 +698,8 @@ export const makeSteps = <Phase extends string, R>(deps: {
616
698
  readonly subject?: (a: A) => string | null;
617
699
  /** For an agent step with tools: the paths, from the project's root, it may change (`step-files.ts`). */
618
700
  readonly mayWrite?: ReadonlyArray<string>;
701
+ /** A check decides whether the work passes (`StepKind`); absent, a plain step. */
702
+ readonly kind?: 'check';
619
703
  /** Marks the no-agent test an item goes through first. Use `defineItemTest` where the step only tests. */
620
704
  readonly test?: true;
621
705
  /** Its work is shared across items (a whole-tree build): no item is charged, and a page says so. */
@@ -635,7 +719,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
635
719
  }) => {
636
720
  const writes = [...(d.mayWrite ?? []), ...(d.writes ?? [])];
637
721
  const declaration: StepDeclaration = {
638
- name: d.name, agent: d.agent, description: d.description, ...(d.test === undefined ? {} : { test: true }), ...(d.shared === undefined ? {} : { shared: true }), ...(d.perItem === undefined ? {} : { perItem: true }), ...(d.picked === undefined ? {} : { picks: true }),
722
+ 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 }),
639
723
  ...(writes.length === 0 ? {} : { writes }),
640
724
  source: d.prompt ?? { path: sourcePath(d.at), anchor: `'${d.name}'` },
641
725
  };
@@ -647,7 +731,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
647
731
  success: d.success,
648
732
  error: Schema.String,
649
733
  execute: pipe(
650
- standDownIfSurplus({ agent: d.agent, picks: d.picked !== undefined }),
734
+ standDownIfSurplus({ agent: d.runs === 'agentic', picks: d.picked !== undefined }),
651
735
  Effect.andThen(measured(declaration, options?.call ?? null, options?.subject ?? null, d.subject, d.reason, d.mayWrite, d.picked === undefined ? execute : untilPicked(d.picked, execute))),
652
736
  Effect.retry({ while: deps.isTransientFailure, times: 10, schedule: Schedule.spaced('3 seconds') }),
653
737
  Effect.mapError(describeFailure),
@@ -677,10 +761,72 @@ export const makeSteps = <Phase extends string, R>(deps: {
677
761
 
678
762
  /** The no-agent test step of a workflow, before its first agent step. */
679
763
  const defineItemTest = (d: { readonly description: string; readonly at: string }) => {
680
- const step = defineStep({ name: 'Test', agent: false, test: true, description: d.description, at: d.at, prompt: { path: sourcePath(d.at), anchor: 'defineItemTest(' }, success: ItemTest });
764
+ const step = defineStep({ name: 'Test', runs: 'deterministic', test: true, description: d.description, at: d.at, prompt: { path: sourcePath(d.at), anchor: 'defineItemTest(' }, success: ItemTest });
681
765
  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) };
682
766
  };
683
767
 
768
+ /** The sub-workflows whose agent steps are being asked for now: a workflow that used itself as a step would ask for ever. */
769
+ const askingForAgents = new Set<string>();
770
+
771
+ /**
772
+ * A SUB-WORKFLOW STEP: a workflow used as a step of another. Alex, 2026-11-19: "decompile is itself a workflow composed of
773
+ * other workflows. the long term goal of Jive is to be workflows all the way down".
774
+ *
775
+ * Running it starts `workflow` as a run of its own on `payload` and waits for it: the engine suspends the run above until
776
+ * it ends, across restarts, and then runs this step again, which reads the result. The step keeps ONE record in the
777
+ * workflow above, open while its workflow runs and naming that run, so:
778
+ *
779
+ * the page shows the run above in this step, and the workflow's own view shows its steps and what they cost;
780
+ * the workflow's steps work on the item the run above works on, with no code naming it (`StepRecords.openStepRun`);
781
+ * its agent steps count against the agents' limit of the workflow at the top, and stand down with its run (`topOf`).
782
+ *
783
+ * Its own run limit applies as to any start: at 0 the step fails, saying so, and the workflow above decides what follows.
784
+ */
785
+ const defineSubWorkflow = <P, A, R2>(d: {
786
+ /** The workflow, as `defineWorkflow` gave it: define it above the workflow that uses it. */
787
+ readonly workflow: { readonly _tag: string; readonly execute: (payload: P) => Effect.Effect<unknown, unknown, R2>; readonly executionId: (payload: P) => Effect.Effect<string> };
788
+ /** Its name as a step, where the workflow above calls it something else. */
789
+ readonly as?: string;
790
+ /** `import.meta.path`, for its link where its workflow is not defined yet. */
791
+ readonly at: string;
792
+ readonly success: Schema.Codec<A, unknown>;
793
+ }) => {
794
+ const child = d.workflow._tag;
795
+ // What its workflow gave is what the step declares, or the step fails saying so: no result is taken on trust.
796
+ const isDeclared = Schema.is(d.success);
797
+ 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`));
798
+ const name = d.as ?? child;
799
+ const declaration: StepDeclaration = {
800
+ name, runs: null, kind: 'sub-workflow', workflow: child,
801
+ description: DECLARED.get(child)?.description ?? `Runs ${child}.`,
802
+ source: DECLARED.get(child)?.source ?? { path: sourcePath(d.at), anchor: `'${child}'` },
803
+ agentUnder: () => {
804
+ if (askingForAgents.has(child)) return false;
805
+ askingForAgents.add(child);
806
+ try {
807
+ return DECLARED.get(child)?.steps().some(stepUsesAnAgent) === true;
808
+ } finally {
809
+ askingForAgents.delete(child);
810
+ }
811
+ },
812
+ };
813
+ return {
814
+ ...declaration,
815
+ run: (payload: P, options?: { readonly call?: number }) =>
816
+ Activity.make({
817
+ name: options?.call === undefined ? name : `${name} ${options.call}`,
818
+ success: d.success,
819
+ error: Schema.String,
820
+ execute: pipe(
821
+ standDownIfSurplus({ agent: false, picks: false }),
822
+ Effect.andThen(Effect.flatMap(d.workflow.executionId(payload), (childRun) =>
823
+ measured(declaration, options?.call ?? null, null, undefined, undefined, undefined, Effect.flatMap(d.workflow.execute(payload), given), childRun))),
824
+ Effect.mapError(describeFailure),
825
+ ),
826
+ }),
827
+ };
828
+ };
829
+
684
830
  /** Every workflow defined so far, in the order defined. */
685
831
  const declaredWorkflows = (): ReadonlyArray<Declaration> => [...DECLARED.values()];
686
832
 
@@ -705,10 +851,17 @@ export const makeSteps = <Phase extends string, R>(deps: {
705
851
  return byItem;
706
852
  });
707
853
 
708
- /** A WORKFLOW'S QUEUE AS ITS PICK TAKES IT (`tasks.ts` `queueOrder`), its tasks' inputs read first: another run's tasks left out. */
854
+ /** The step a Pick's notes are written by: every Pick is the step that reads its queue. */
855
+ const pickedBy = (input: { readonly workflow: string; readonly run: string }) => ({ workflow: input.workflow, run: input.run, step: 'Pick' });
856
+
857
+ /**
858
+ * A WORKFLOW'S QUEUE AS ITS PICK TAKES IT: first in, first out (`tasks.ts` `queueOrder`), another run's tasks left out.
859
+ * The Pick first reads what its tasks run on and settles its queue (`tasks.ts` `settleQueue`): a task a standard reason
860
+ * holds for is blocked, and a blocked one whose reason lapsed is back in the queue.
861
+ */
709
862
  const queueNow = (input: { readonly workflow: string; readonly run: string }): Effect.Effect<ReadonlyArray<TaskSummary>, unknown, R> => Effect.gen(function* () {
710
863
  yield* readTaskInputs(input.workflow);
711
- return queueOrder(yield* deps.tasks.taskSummaries({ workflow: input.workflow, excludingRun: input.run }));
864
+ return queueOrder(yield* deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }));
712
865
  });
713
866
 
714
867
  /** A workflow: what it states about itself, then `Workflow.make`'s own name and options. */
@@ -720,9 +873,14 @@ export const makeSteps = <Phase extends string, R>(deps: {
720
873
  /** Its steps, in order; a function so they can be defined below it. */
721
874
  readonly steps: () => ReadonlyArray<StepDeclaration>;
722
875
  readonly pending?: () => Effect.Effect<PendingWork, unknown, R>;
876
+ /** Every item it has a task for, done or not (`WorkflowDeclaration.items`), in place of `pending`. */
877
+ readonly items?: () => Effect.Effect<ReadonlyArray<string>, unknown, R>;
723
878
  readonly picksQueueHead?: true;
724
- /** The workflows whose results it works on (`WorkflowDeclaration.fedBy`). */
725
- readonly fedBy?: ReadonlyArray<string>;
879
+ /**
880
+ * The workflows whose results become its tasks: the arrows of the project's map (`views/workflow-flows.ts`). A workflow
881
+ * used as a step of another needs none: it is drawn inside that one.
882
+ */
883
+ readonly fedBy?: ReadonlyArray<string>;
726
884
  /** Its step graph: which step can follow which, and when. */
727
885
  readonly graph?: () => ReadonlyArray<StepEdge>;
728
886
  /** What it runs on: its trigger starts a run only when they changed (`runIfInputsChanged`). */
@@ -743,7 +901,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
743
901
  let refusedSaidAt = 0;
744
902
  const startAllowed = (payload: object): Effect.Effect<{ readonly allowed: true } | { readonly allowed: false; readonly limit: number }> => Effect.gen(function* () {
745
903
  const limits = yield* deps.budgets.limitsOf(name);
746
- const limit = limits === null ? null : runLimitOf({ pending: d.pending, steps: d.steps }, limits);
904
+ const limit = limits === null ? null : runLimitOf({ pending: d.pending, items: d.items, steps: d.steps }, limits);
747
905
  if (limit === null) return { allowed: true } as const;
748
906
  const going = (yield* deps.engine.unfinishedRuns()).filter((u) => u.workflow === name).map((u) => u.run);
749
907
  if (going.length < limit) return { allowed: true } as const;
@@ -760,6 +918,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
760
918
  ...(d.graph === undefined ? {} : { graph: d.graph }),
761
919
  source: { path: sourcePath(d.at), anchor: `'${name}'` },
762
920
  ...(d.pending === undefined ? {} : { pending: d.pending }),
921
+ ...(d.items === undefined ? {} : { items: d.items }),
763
922
  ...(d.picksQueueHead === undefined ? {} : { picksQueueHead: d.picksQueueHead }),
764
923
  ...(d.fedBy === undefined ? {} : { fedBy: d.fedBy }),
765
924
  ...(d.inputs === undefined ? {} : { inputs: d.inputs }),
@@ -789,12 +948,12 @@ export const makeSteps = <Phase extends string, R>(deps: {
789
948
  };
790
949
  if (!interrupted && d.item !== null) {
791
950
  if (Exit.isSuccess(exit)) {
792
- 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) });
951
+ 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 });
793
952
  } else {
794
953
  // With its cause, as its step's record has it: a bare "failed" sent whoever read it to the records for why.
795
954
  const failure = Cause.squash(exit.cause);
796
955
  const outcome = isStoodDown(failure) ? 'stood down' : `failed: ${startAndEnd(describeFailure(failure), { cap: 1000, end: 400, what: 'the failure' })}`;
797
- yield* deps.tasks.appendOutcome({ workflow: name, run: executionId, subject: null, outcome, finished: false, inputs: inputsLeft(null) });
956
+ yield* deps.tasks.appendOutcome({ workflow: name, run: executionId, subject: null, outcome, finished: false, inputs: inputsLeft(null), blocked: null });
798
957
  }
799
958
  }
800
959
  // What it ran on gave this result, which stands until its inputs change. Only a run its trigger started on its
@@ -807,6 +966,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
807
966
  }), 'StorageError', (e) => Effect.logError(`[inputs] ${name} run ${executionId}: its end could not be recorded: ${e.reason}`));
808
967
  }
809
968
  lastStepRan.delete(executionId);
969
+ TOPS.delete(executionId);
810
970
  runEnded();
811
971
  // Its claim and its item are free now for its workflow's other runs, once the engine has stored its end. Only its
812
972
  // own: about 25 short runs end a minute, and waking every Pick on each re-read every task twice each time.
@@ -842,11 +1002,12 @@ export const makeSteps = <Phase extends string, R>(deps: {
842
1002
  new Set(subjects.flatMap((subject) => (subject === null ? [] : [subject.toLowerCase()])))));
843
1003
 
844
1004
  /**
845
- * The candidates of this run's Pick in the order it takes them (`tasks.ts` `inPickOrder`), from the tasks now: only queued
846
- * ones, another run's left out. `fromItem` builds a candidate for a task another task reopened that the candidates do not hold.
1005
+ * The candidates of this run's Pick in the order it takes them (`tasks.ts` `inPickOrder`), its queue settled first as
1006
+ * `queueNow` settles it: none blocked, another run's left out. `fromItem` builds a candidate for a task a step or a person
1007
+ * returned to the queue that the candidates do not hold.
847
1008
  */
848
1009
  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> =>
849
- Effect.map(deps.tasks.taskSummaries({ workflow: input.workflow, excludingRun: input.run }), (tasks) =>
1010
+ Effect.map(deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }), (tasks) =>
850
1011
  inPickOrder({ candidates: input.candidates, subjectOf: input.subjectOf, tasks, ...(input.fromItem === undefined ? {} : { fromItem: input.fromItem }) }));
851
1012
 
852
1013
  /**
@@ -858,7 +1019,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
858
1019
  states: { readonly phase: Phase; readonly description: string; readonly stepDescription: string; readonly at: string; readonly writes?: ReadonlyArray<string>; readonly inputs?: WorkflowInputs<R> },
859
1020
  name: string, step: string, success: Schema.Codec<A, unknown>, execute: Effect.Effect<A, E, R2>,
860
1021
  ) => {
861
- const theStep = defineStep({ name: step, agent: false, shared: true, description: states.stepDescription, at: states.at, success, ...(states.writes === undefined ? {} : { writes: states.writes }) });
1022
+ const theStep = defineStep({ name: step, runs: 'deterministic', shared: true, description: states.stepDescription, at: states.at, success, ...(states.writes === undefined ? {} : { writes: states.writes }) });
862
1023
  const workflow = defineWorkflow({ phase: states.phase, description: states.description, at: states.at, steps: () => [theStep], item: null, ...(states.inputs === undefined ? {} : { inputs: states.inputs }),
863
1024
  graph: () => [{ from: RUN_STARTS, to: step, when: 'each turn' }, { from: step, to: RUN_ENDS, when: 'always' }] })(name, {
864
1025
  payload: { turn: Schema.Number },
@@ -875,7 +1036,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
875
1036
  };
876
1037
 
877
1038
  return {
878
- defineStep, defineItemTest, defineWorkflow, oneStepWorkflow, declaredWorkflows, onRunEnded,
1039
+ defineStep, defineItemTest, defineSubWorkflow, defineWorkflow, oneStepWorkflow, declaredWorkflows, onRunEnded,
879
1040
  eachItem, undoAgentStep, AgentBudgets, pickingOneAtATime, pickOrder, itemsOfOtherRuns,
880
1041
  runsOldestFirst, runningRunIds, runningRuns, sourcePath, runIfInputsChanged, queueNow, readTaskInputs,
881
1042
  };