@jive-sh/workflow-platform 0.3.3 → 0.4.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 (54) hide show
  1. package/README.md +64 -21
  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 -7
  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 +133 -30
  17. package/dist/steps.js.map +1 -1
  18. package/dist/storage/sqlite-store.js +115 -40
  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 +2 -1
  25. package/dist/views/runs-now.js.map +1 -1
  26. package/dist/views/workflows-view.js +74 -15
  27. package/dist/views/workflows-view.js.map +1 -1
  28. package/package.json +1 -1
  29. package/src/dashboard/agent-usage-line.tsx +28 -0
  30. package/src/dashboard/agent-usage.ts +48 -0
  31. package/src/dashboard/dashboard.css +57 -28
  32. package/src/dashboard/drilldown.ts +44 -0
  33. package/src/dashboard/index.tsx +1 -0
  34. package/src/dashboard/machine-controls.tsx +53 -0
  35. package/src/dashboard/queue-bar.tsx +43 -0
  36. package/src/dashboard/queue-chart.tsx +89 -76
  37. package/src/dashboard/queue-lines.ts +87 -0
  38. package/src/dashboard/workflow-drilldown.tsx +89 -0
  39. package/src/dashboard/workflows-dashboard.tsx +103 -37
  40. package/src/index.ts +11 -10
  41. package/src/keep-running.ts +3 -3
  42. package/src/pick-wakes.ts +14 -9
  43. package/src/queue-counts.ts +10 -14
  44. package/src/steps.ts +179 -42
  45. package/src/storage/sqlite-store.ts +123 -46
  46. package/src/storage/step-records.ts +14 -3
  47. package/src/storage/task-store.ts +88 -36
  48. package/src/tasks.ts +235 -301
  49. package/src/views/runs-now.ts +3 -2
  50. package/src/views/workflows-view.ts +102 -32
  51. package/dist/views/workflow-flows.js +0 -53
  52. package/dist/views/workflow-flows.js.map +0 -1
  53. package/src/dashboard/workflow-dag.tsx +0 -276
  54. package/src/views/workflow-flows.ts +0 -97
package/src/steps.ts CHANGED
@@ -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
  *
@@ -89,15 +89,42 @@ 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;
96
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 plain code;
107
+ * agent calls an agent;
108
+ * check decides whether the work passes;
109
+ * sub-workflow a workflow used as a step of another workflow (`StepDeclaration.workflow` names it).
110
+ */
111
+ export const STEP_KINDS = ['step', 'agent', 'check', 'sub-workflow'] as const;
112
+ export type StepKind = (typeof STEP_KINDS)[number];
113
+
114
+ /** A step's kind, from its declaration: an agent step is an agent, the kind it states otherwise, and plain code with none. Pure. */
115
+ export const stepKindOf = (s: Pick<StepDeclaration, 'agent' | 'test' | 'kind'>): StepKind =>
116
+ s.agent ? 'agent' : s.kind ?? (s.test === true ? 'check' : 'step');
117
+
97
118
  export interface StepDeclaration {
98
119
  readonly name: string;
99
120
  /** Whether this step needs an agent. */
100
121
  readonly agent: boolean;
122
+ /** What it is where it is neither an agent nor plain code (`stepKindOf`). */
123
+ readonly kind?: 'check' | 'sub-workflow';
124
+ /** For a sub-workflow step: the workflow it runs, by name. */
125
+ readonly workflow?: string;
126
+ /** For a sub-workflow step: whether its workflow has an agent step, at any depth under it. */
127
+ readonly agentUnder?: () => boolean;
101
128
  /** Whether this is the no-agent test an item goes through before any agent sees it. */
102
129
  readonly test?: boolean;
103
130
  /** One line on what it does, for its hover. */
@@ -129,6 +156,11 @@ export interface RunOutcome {
129
156
  readonly outcome: string;
130
157
  /** Whether this ended the item's work: recovered, provided, fixed. */
131
158
  readonly finished: boolean;
159
+ /**
160
+ * 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
161
+ * the queue (`tasks.ts` `requeue`). Absent, it goes back to the queue.
162
+ */
163
+ readonly blocked?: string;
132
164
  }
133
165
 
134
166
  /** The check a workflow's finished items must pass, in plain words, and whether an outcome reached it. */
@@ -176,16 +208,16 @@ export interface WorkflowDeclaration<Phase extends string = string, R = never> {
176
208
  readonly gate: WorkflowGate | null;
177
209
  /** Starts one run, for the trigger alone. */
178
210
  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. */
211
+ /**
212
+ * ITS LIST, in one of two kinds (`TaskStore.recordListing`). `pending`: its work left; an item that leaves it without a
213
+ * passing final check is no longer its task, and a done one it lists again goes back to its queue. `items`: every item
214
+ * 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
215
+ * and a list runs only on its list.
216
+ */
180
217
  readonly pending?: () => Effect.Effect<PendingWork, unknown, R>;
218
+ readonly items?: () => Effect.Effect<ReadonlyArray<string>, unknown, R>;
181
219
  /** Its Pick takes the first task of its queue it can claim (`tasks.ts` `queueOrder`), so a dashboard lists that queue. */
182
220
  readonly picksQueueHead?: true;
183
- /**
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.
187
- */
188
- readonly fedBy?: ReadonlyArray<string>;
189
221
  /** Its step graph (`StepEdge`); none until it declares one. */
190
222
  readonly graph?: () => ReadonlyArray<StepEdge>;
191
223
  /** What it runs on (`WorkflowInputs`); none until it declares them, and it runs whenever its trigger says. */
@@ -211,12 +243,18 @@ const REFUSED_SAID_EVERY_MS = 10 * 60 * 1000;
211
243
  * A WORKFLOW'S RUN LIMIT, whatever starts it: for one its budget keeps going, its run limit or its agents' limit
212
244
  * (`runLimit`); for any other its run limit, none meaning no limit. 0 starts nothing new. Pure.
213
245
  */
214
- export const runLimitOf = (d: Pick<WorkflowDeclaration<string, unknown>, 'pending' | 'steps'>, limits: WorkflowLimits): number | null =>
246
+ export const runLimitOf = (d: Pick<WorkflowDeclaration<string, unknown>, 'pending' | 'items' | 'steps'>, limits: WorkflowLimits): number | null =>
215
247
  keptRunningByItsBudget(d) ? runLimit(limits) : limits.runs;
216
248
 
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);
249
+ /** Whether a workflow declares a list, of either kind: it has tasks and a queue. Pure. */
250
+ export const hasAList = (d: Pick<WorkflowDeclaration<string, unknown>, 'pending' | 'items'>): boolean => d.pending !== undefined || d.items !== undefined;
251
+
252
+ /** Whether a step uses an agent: it is an agent step, or a sub-workflow step whose workflow has one at any depth. Pure. */
253
+ export const stepUsesAnAgent = (s: Pick<StepDeclaration, 'agent' | 'agentUnder'>): boolean => s.agent || s.agentUnder?.() === true;
254
+
255
+ /** Whether a workflow's budget rules it: a declared list, and an agent step of its own or under a sub-workflow step. Pure. */
256
+ export const keptRunningByItsBudget = (d: Pick<WorkflowDeclaration<string, unknown>, 'pending' | 'items' | 'steps'>): boolean =>
257
+ hasAList(d) && d.steps().some(stepUsesAnAgent);
220
258
 
221
259
 
222
260
  /** An unfinished run of a workflow with an agent step. */
@@ -358,26 +396,46 @@ export const makeSteps = <Phase extends string, R>(deps: {
358
396
  const unreadLimits = <A>(workflow: string, held: (why: string) => A) => (e: StorageError): Effect.Effect<A> =>
359
397
  Effect.as(Effect.logError(`[budget] ${workflow}: its limits could not be read (${e.reason}); its runs wait`), held(e.reason));
360
398
 
399
+ /**
400
+ * 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
401
+ * (`StepRecords.rootOfRun`). A workflow's limits govern every run under its runs, so a sub-workflow's agent step counts
402
+ * against the agents' limit of the workflow at the top. Kept while the run goes: it never changes.
403
+ */
404
+ const TOPS = new Map<string, { readonly run: string; readonly workflow: string }>();
405
+ const topOf = (workflow: string, run: string): Effect.Effect<{ readonly run: string; readonly workflow: string }, StorageError> => {
406
+ const known = TOPS.get(run);
407
+ if (known !== undefined) return Effect.succeed(known);
408
+ return Effect.map(records.rootOfRun(run), (root) => {
409
+ const top = root ?? { run, workflow };
410
+ TOPS.set(run, top);
411
+ return top;
412
+ });
413
+ };
414
+
361
415
  const AgentBudgets = Context.Reference<AgentBudgetRules>('AgentBudgets', {
362
416
  defaultValue: () => ({
363
417
  // 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))),
418
+ // listed is not counted. A run a sub-workflow step started stands down with the run at its top.
419
+ standsDown: (workflow, run) => pipe(
420
+ topOf(workflow, run),
421
+ Effect.flatMap((top) => Effect.zipWith(pastItsRunLimit(workflow, run), top.run === run ? Effect.succeed(false) : pastItsRunLimit(top.workflow, top.run), (own, above) => own || above)),
422
+ Effect.catchTag('StorageError', unreadLimits(workflow, () => false)),
423
+ ),
366
424
  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.
425
+ // The other runs of the workflow at its top that an agent works for, a waiting one not counted, against that
426
+ // 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
427
  agentSlot: (workflow, run) => pipe(
370
- limitsOf(workflow),
371
- Effect.flatMap((w): Effect.Effect<{ readonly free: true } | { readonly free: false; readonly why: string }, StorageError> => {
428
+ topOf(workflow, run),
429
+ Effect.flatMap((top) => Effect.flatMap(limitsOf(top.workflow), (w): Effect.Effect<{ readonly free: true } | { readonly free: false; readonly why: string }, StorageError> => {
372
430
  const agents = w === null ? null : w.agents;
373
431
  if (agents === null) return Effect.succeed({ free: true });
374
432
  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 }) => {
433
+ return Effect.map(Effect.all({ runs: runsOldestFirst([top.workflow]), inAgentStep: records.runsInAgentStep(top.workflow) }), ({ runs, inAgentStep }) => {
376
434
  const going = new Set(runs);
377
- const busy = inAgentStep.filter((r) => r !== run && going.has(r)).length;
435
+ const busy = inAgentStep.filter((r) => r !== top.run && going.has(r)).length;
378
436
  return busy < agents ? { free: true } : { free: false, why: `waits for an agent: ${busy} of its ${agents} in use` };
379
437
  });
380
- }),
438
+ })),
381
439
  Effect.catchTag('StorageError', unreadLimits(workflow, (why) => ({ free: false as const, why: `waits for an agent: its limits could not be read (${why})` }))),
382
440
  ),
383
441
  }),
@@ -391,9 +449,11 @@ export const makeSteps = <Phase extends string, R>(deps: {
391
449
  const untilAgentSlot = (instance: { readonly workflow: { readonly _tag: string }; readonly executionId: string }, record: () => number | null) => Effect.gen(function* () {
392
450
  const rules = yield* AgentBudgets;
393
451
  const workflow = instance.workflow._tag;
452
+ // 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.
453
+ const heardOn = (yield* Effect.orElseSucceed(topOf(workflow, instance.executionId), () => ({ run: instance.executionId, workflow }))).workflow;
394
454
  let waited = false;
395
455
  for (;;) {
396
- const wakes = deps.wakes.pickWakesSoFar(workflow);
456
+ const wakes = deps.wakes.pickWakesSoFar(heardOn);
397
457
  if (yield* rules.standsDown(workflow, instance.executionId)) return yield* Effect.fail(STOOD_DOWN);
398
458
  const slot = yield* rules.agentSlot(workflow, instance.executionId);
399
459
  const id = record();
@@ -406,7 +466,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
406
466
  }
407
467
  if (id !== null) yield* recorded('say what it waits on', records.setStepWaiting({ id, waiting: slot.why }));
408
468
  waited = true;
409
- yield* deps.wakes.untilPickWoken({ workflow, after: wakes });
469
+ if ((yield* deps.wakes.untilPickWoken({ workflow: heardOn, after: wakes })) === 'released') return yield* Effect.fail(HANDED_OVER);
410
470
  }
411
471
  });
412
472
 
@@ -428,7 +488,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
428
488
  });
429
489
 
430
490
  /** 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>) =>
491
+ 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
492
  Effect.flatMap(WorkflowEngine.WorkflowInstance, (instance) => {
433
493
  // A call's running sum is by request; its final figures replace it. `settled` is what finished calls reported.
434
494
  const settled = noSpend();
@@ -464,7 +524,9 @@ export const makeSteps = <Phase extends string, R>(deps: {
464
524
  return Effect.acquireUseRelease(
465
525
  Effect.flatMap(Effect.gen(function* () {
466
526
  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 }));
527
+ // 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.
528
+ const id = yield* recorded('open its record', records.openStepRun({ workflow: instance.workflow._tag, run: instance.executionId, step: step.name, call, agent: step.agent, subject, ...(childRun === null ? {} : { resume: true as const }) }));
529
+ if (id !== null && childRun !== null) yield* recorded('name the run it started', records.setStepChild({ id, childRun }));
468
530
  const beat = step.agent && id !== null ? setInterval(() => recordNow('its heartbeat', records.beatStepRun(id)), AGENT_BEAT_MS) : null;
469
531
  recordId = id;
470
532
  meter = new StepMeter(id, step.agent, step.writes ?? [], null);
@@ -503,7 +565,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
503
565
  ({ id, beat }, exit) => Effect.gen(function* () {
504
566
  if (beat !== null) clearInterval(beat);
505
567
  // 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');
568
+ if (step.agent) deps.wakes.wakePicksOf(TOPS.get(instance.executionId)?.workflow ?? instance.workflow._tag, 'an agent step ended');
507
569
  // An interrupted step is no move: the run does it again.
508
570
  if (Exit.isSuccess(exit) || !Cause.hasInterrupts(exit.cause)) lastStepRan.set(instance.executionId, { step: step.name, failed: !Exit.isSuccess(exit) });
509
571
  meterClosed(meter);
@@ -515,6 +577,8 @@ export const makeSteps = <Phase extends string, R>(deps: {
515
577
  const idleBatch = step.perItem === true && Exit.isSuccess(exit) && used.childCpuSeconds === 0 && used.compiles === 0;
516
578
  const scope: StepScope = meter.items > 0 ? 'functions' : step.shared === true ? 'shared' : idleBatch ? 'none due' : subjectOf !== undefined && Exit.isSuccess(exit) && named === null ? 'nothing' : 'undeclared';
517
579
  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 }));
580
+ // A sub-workflow step whose run is suspended until its workflow ends is still in that step: its record stays open.
581
+ else if (Cause.hasInterrupts(exit.cause) && childRun !== null && instance.suspended) yield* Effect.void;
518
582
  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
583
  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
584
  }),
@@ -567,7 +631,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
567
631
  deps.tasks.taskSummaries({ workflow }),
568
632
  Effect.map((tasks) => `${queueOrder(tasks).length} queued${queueOrder(tasks).length === 0 ? '' : ', none it can claim now'}`),
569
633
  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`),
634
+ 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
635
  );
572
636
 
573
637
  /**
@@ -598,7 +662,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
598
662
  }
599
663
  if (record !== null) yield* recorded('say what it waits on', records.setStepWaiting({ id: record, waiting: yield* nothingToClaim(workflow) }));
600
664
  waited = true;
601
- yield* deps.wakes.untilPickWoken({ workflow, after: wakes });
665
+ if ((yield* deps.wakes.untilPickWoken({ workflow, after: wakes })) === 'released') return yield* Effect.fail(HANDED_OVER);
602
666
  }
603
667
  });
604
668
 
@@ -616,6 +680,8 @@ export const makeSteps = <Phase extends string, R>(deps: {
616
680
  readonly subject?: (a: A) => string | null;
617
681
  /** For an agent step with tools: the paths, from the project's root, it may change (`step-files.ts`). */
618
682
  readonly mayWrite?: ReadonlyArray<string>;
683
+ /** What it is where it is neither an agent step nor plain code: a check decides whether the work passes (`StepKind`). */
684
+ readonly kind?: 'check';
619
685
  /** Marks the no-agent test an item goes through first. Use `defineItemTest` where the step only tests. */
620
686
  readonly test?: true;
621
687
  /** Its work is shared across items (a whole-tree build): no item is charged, and a page says so. */
@@ -635,7 +701,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
635
701
  }) => {
636
702
  const writes = [...(d.mayWrite ?? []), ...(d.writes ?? [])];
637
703
  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 }),
704
+ name: d.name, agent: d.agent, 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
705
  ...(writes.length === 0 ? {} : { writes }),
640
706
  source: d.prompt ?? { path: sourcePath(d.at), anchor: `'${d.name}'` },
641
707
  };
@@ -681,6 +747,68 @@ export const makeSteps = <Phase extends string, R>(deps: {
681
747
  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
748
  };
683
749
 
750
+ /** The sub-workflows whose agent steps are being asked for now: a workflow that used itself as a step would ask for ever. */
751
+ const askingForAgents = new Set<string>();
752
+
753
+ /**
754
+ * A SUB-WORKFLOW STEP: a workflow used as a step of another. Alex, 2026-11-19: "decompile is itself a workflow composed of
755
+ * other workflows. the long term goal of Jive is to be workflows all the way down".
756
+ *
757
+ * Running it starts `workflow` as a run of its own on `payload` and waits for it: the engine suspends the run above until
758
+ * it ends, across restarts, and then runs this step again, which reads the result. The step keeps ONE record in the
759
+ * workflow above, open while its workflow runs and naming that run, so:
760
+ *
761
+ * the page shows the run above in this step, and the workflow's own view shows its steps and what they cost;
762
+ * the workflow's steps work on the item the run above works on, with no code naming it (`StepRecords.openStepRun`);
763
+ * its agent steps count against the agents' limit of the workflow at the top, and stand down with its run (`topOf`).
764
+ *
765
+ * Its own run limit applies as to any start: at 0 the step fails, saying so, and the workflow above decides what follows.
766
+ */
767
+ const defineSubWorkflow = <P, A, R2>(d: {
768
+ /** The workflow, as `defineWorkflow` gave it: define it above the workflow that uses it. */
769
+ readonly workflow: { readonly _tag: string; readonly execute: (payload: P) => Effect.Effect<unknown, unknown, R2>; readonly executionId: (payload: P) => Effect.Effect<string> };
770
+ /** Its name as a step, where the workflow above calls it something else. */
771
+ readonly as?: string;
772
+ /** `import.meta.path`, for its link where its workflow is not defined yet. */
773
+ readonly at: string;
774
+ readonly success: Schema.Codec<A, unknown>;
775
+ }) => {
776
+ const child = d.workflow._tag;
777
+ // What its workflow gave is what the step declares, or the step fails saying so: no result is taken on trust.
778
+ const isDeclared = Schema.is(d.success);
779
+ 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`));
780
+ const name = d.as ?? child;
781
+ const declaration: StepDeclaration = {
782
+ name, agent: false, kind: 'sub-workflow', workflow: child,
783
+ description: DECLARED.get(child)?.description ?? `Runs ${child}.`,
784
+ source: DECLARED.get(child)?.source ?? { path: sourcePath(d.at), anchor: `'${child}'` },
785
+ agentUnder: () => {
786
+ if (askingForAgents.has(child)) return false;
787
+ askingForAgents.add(child);
788
+ try {
789
+ return DECLARED.get(child)?.steps().some(stepUsesAnAgent) === true;
790
+ } finally {
791
+ askingForAgents.delete(child);
792
+ }
793
+ },
794
+ };
795
+ return {
796
+ ...declaration,
797
+ run: (payload: P, options?: { readonly call?: number }) =>
798
+ Activity.make({
799
+ name: options?.call === undefined ? name : `${name} ${options.call}`,
800
+ success: d.success,
801
+ error: Schema.String,
802
+ execute: pipe(
803
+ standDownIfSurplus({ agent: false, picks: false }),
804
+ Effect.andThen(Effect.flatMap(d.workflow.executionId(payload), (childRun) =>
805
+ measured(declaration, options?.call ?? null, null, undefined, undefined, undefined, Effect.flatMap(d.workflow.execute(payload), given), childRun))),
806
+ Effect.mapError(describeFailure),
807
+ ),
808
+ }),
809
+ };
810
+ };
811
+
684
812
  /** Every workflow defined so far, in the order defined. */
685
813
  const declaredWorkflows = (): ReadonlyArray<Declaration> => [...DECLARED.values()];
686
814
 
@@ -705,10 +833,17 @@ export const makeSteps = <Phase extends string, R>(deps: {
705
833
  return byItem;
706
834
  });
707
835
 
708
- /** A WORKFLOW'S QUEUE AS ITS PICK TAKES IT (`tasks.ts` `queueOrder`), its tasks' inputs read first: another run's tasks left out. */
836
+ /** The step a Pick's notes are written by: every Pick is the step that reads its queue. */
837
+ const pickedBy = (input: { readonly workflow: string; readonly run: string }) => ({ workflow: input.workflow, run: input.run, step: 'Pick' });
838
+
839
+ /**
840
+ * A WORKFLOW'S QUEUE AS ITS PICK TAKES IT: first in, first out (`tasks.ts` `queueOrder`), another run's tasks left out.
841
+ * The Pick first reads what its tasks run on and settles its queue (`tasks.ts` `settleQueue`): a task a standard reason
842
+ * holds for is blocked, and a blocked one whose reason lapsed is back in the queue.
843
+ */
709
844
  const queueNow = (input: { readonly workflow: string; readonly run: string }): Effect.Effect<ReadonlyArray<TaskSummary>, unknown, R> => Effect.gen(function* () {
710
845
  yield* readTaskInputs(input.workflow);
711
- return queueOrder(yield* deps.tasks.taskSummaries({ workflow: input.workflow, excludingRun: input.run }));
846
+ return queueOrder(yield* deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }));
712
847
  });
713
848
 
714
849
  /** A workflow: what it states about itself, then `Workflow.make`'s own name and options. */
@@ -720,9 +855,9 @@ export const makeSteps = <Phase extends string, R>(deps: {
720
855
  /** Its steps, in order; a function so they can be defined below it. */
721
856
  readonly steps: () => ReadonlyArray<StepDeclaration>;
722
857
  readonly pending?: () => Effect.Effect<PendingWork, unknown, R>;
858
+ /** Every item it has a task for, done or not (`WorkflowDeclaration.items`), in place of `pending`. */
859
+ readonly items?: () => Effect.Effect<ReadonlyArray<string>, unknown, R>;
723
860
  readonly picksQueueHead?: true;
724
- /** The workflows whose results it works on (`WorkflowDeclaration.fedBy`). */
725
- readonly fedBy?: ReadonlyArray<string>;
726
861
  /** Its step graph: which step can follow which, and when. */
727
862
  readonly graph?: () => ReadonlyArray<StepEdge>;
728
863
  /** What it runs on: its trigger starts a run only when they changed (`runIfInputsChanged`). */
@@ -743,7 +878,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
743
878
  let refusedSaidAt = 0;
744
879
  const startAllowed = (payload: object): Effect.Effect<{ readonly allowed: true } | { readonly allowed: false; readonly limit: number }> => Effect.gen(function* () {
745
880
  const limits = yield* deps.budgets.limitsOf(name);
746
- const limit = limits === null ? null : runLimitOf({ pending: d.pending, steps: d.steps }, limits);
881
+ const limit = limits === null ? null : runLimitOf({ pending: d.pending, items: d.items, steps: d.steps }, limits);
747
882
  if (limit === null) return { allowed: true } as const;
748
883
  const going = (yield* deps.engine.unfinishedRuns()).filter((u) => u.workflow === name).map((u) => u.run);
749
884
  if (going.length < limit) return { allowed: true } as const;
@@ -760,8 +895,8 @@ export const makeSteps = <Phase extends string, R>(deps: {
760
895
  ...(d.graph === undefined ? {} : { graph: d.graph }),
761
896
  source: { path: sourcePath(d.at), anchor: `'${name}'` },
762
897
  ...(d.pending === undefined ? {} : { pending: d.pending }),
898
+ ...(d.items === undefined ? {} : { items: d.items }),
763
899
  ...(d.picksQueueHead === undefined ? {} : { picksQueueHead: d.picksQueueHead }),
764
- ...(d.fedBy === undefined ? {} : { fedBy: d.fedBy }),
765
900
  ...(d.inputs === undefined ? {} : { inputs: d.inputs }),
766
901
  ...(d.taskInputs === undefined ? {} : { taskInputs: d.taskInputs }),
767
902
  item: d.item,
@@ -789,12 +924,12 @@ export const makeSteps = <Phase extends string, R>(deps: {
789
924
  };
790
925
  if (!interrupted && d.item !== null) {
791
926
  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) });
927
+ 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
928
  } else {
794
929
  // With its cause, as its step's record has it: a bare "failed" sent whoever read it to the records for why.
795
930
  const failure = Cause.squash(exit.cause);
796
931
  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) });
932
+ yield* deps.tasks.appendOutcome({ workflow: name, run: executionId, subject: null, outcome, finished: false, inputs: inputsLeft(null), blocked: null });
798
933
  }
799
934
  }
800
935
  // What it ran on gave this result, which stands until its inputs change. Only a run its trigger started on its
@@ -807,6 +942,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
807
942
  }), 'StorageError', (e) => Effect.logError(`[inputs] ${name} run ${executionId}: its end could not be recorded: ${e.reason}`));
808
943
  }
809
944
  lastStepRan.delete(executionId);
945
+ TOPS.delete(executionId);
810
946
  runEnded();
811
947
  // Its claim and its item are free now for its workflow's other runs, once the engine has stored its end. Only its
812
948
  // own: about 25 short runs end a minute, and waking every Pick on each re-read every task twice each time.
@@ -842,11 +978,12 @@ export const makeSteps = <Phase extends string, R>(deps: {
842
978
  new Set(subjects.flatMap((subject) => (subject === null ? [] : [subject.toLowerCase()])))));
843
979
 
844
980
  /**
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.
981
+ * The candidates of this run's Pick in the order it takes them (`tasks.ts` `inPickOrder`), its queue settled first as
982
+ * `queueNow` settles it: none blocked, another run's left out. `fromItem` builds a candidate for a task a step or a person
983
+ * returned to the queue that the candidates do not hold.
847
984
  */
848
985
  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) =>
986
+ Effect.map(deps.tasks.settleQueue({ workflow: input.workflow, excludingRun: input.run, by: pickedBy(input) }), (tasks) =>
850
987
  inPickOrder({ candidates: input.candidates, subjectOf: input.subjectOf, tasks, ...(input.fromItem === undefined ? {} : { fromItem: input.fromItem }) }));
851
988
 
852
989
  /**
@@ -875,7 +1012,7 @@ export const makeSteps = <Phase extends string, R>(deps: {
875
1012
  };
876
1013
 
877
1014
  return {
878
- defineStep, defineItemTest, defineWorkflow, oneStepWorkflow, declaredWorkflows, onRunEnded,
1015
+ defineStep, defineItemTest, defineSubWorkflow, defineWorkflow, oneStepWorkflow, declaredWorkflows, onRunEnded,
879
1016
  eachItem, undoAgentStep, AgentBudgets, pickingOneAtATime, pickOrder, itemsOfOtherRuns,
880
1017
  runsOldestFirst, runningRunIds, runningRuns, sourcePath, runIfInputsChanged, queueNow, readTaskInputs,
881
1018
  };