@jive-sh/workflow-platform 0.2.0 → 0.3.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.
@@ -0,0 +1,313 @@
1
+ 'use client';
2
+
3
+ /**
4
+ * THE GENERIC VIEW OF A PROJECT'S WORKFLOWS: each queue over time, and every workflow a box on one map, with its queue, its
5
+ * runs now and its limits. An opened workflow shows its steps (what each cost and where its runs are now, what a waiting
6
+ * one waits on), its step graph with the window's runs on each edge, and where its runs stopped and why. It reads the
7
+ * platform's two readings (`views/workflows-view.ts`: every workflow at each poll, one workflow's figures when it is
8
+ * opened) and runs now (`views/runs-now.ts`); a project plugs its own panels in around it (`header`, `panels`,
9
+ * `phaseSummary`). Uses React and the layout library the map names, which the host page brings.
10
+ */
11
+ import { Fragment, useEffect, useState, type ReactNode } from 'react';
12
+ import type { PhaseRunsNow, StepRunsNow, WorkflowRunsNow } from '../views/runs-now';
13
+ import type { StepFunnel } from '../views/step-funnel';
14
+ import type { WorkflowGraph } from '../views/step-graph';
15
+ import type { SourceLink, StepCost, WorkflowFigures, WorkflowView, WorkflowsView } from '../views/workflows-view';
16
+ import { compact, duration, localTime, whenAgo } from '../views/format';
17
+ import { QueueChart } from './queue-chart';
18
+ import { StepGraph } from './step-graph';
19
+ import { WorkflowDag } from './workflow-dag';
20
+
21
+ /** What the page is given at each poll, all of it read at the request: every workflow, and where runs are now. */
22
+ export interface WorkflowsPageData {
23
+ readonly view: WorkflowsView;
24
+ readonly runsNow: ReadonlyArray<PhaseRunsNow>;
25
+ /** The one CPU limit and the newest reading of what the project used (`CpuLimit`). */
26
+ readonly cpu: { readonly limit: number; readonly use: { readonly at: number; readonly cores: number; readonly held: number; readonly waiting: number } | null };
27
+ }
28
+
29
+ type WorkflowLimits = NonNullable<WorkflowView['limits']>;
30
+
31
+ /** Which of a workflow's two limits a control sets. */
32
+ export type LimitName = 'runs' | 'agents';
33
+
34
+ /** Stores one of a workflow's limits: a whole number, or none for the run limit's default (its agents' limit). The project's own route. */
35
+ export type SetLimit = (r: { readonly workflow: string; readonly limit: LimitName; readonly value: number | null }) => Promise<void>;
36
+
37
+ /** Where the project stands against its one CPU limit, in words. */
38
+ const cpuLine = (cpu: WorkflowsPageData['cpu'], now: number): string =>
39
+ cpu.use === null
40
+ ? `CPU limit: ${cpu.limit} cores; no reading of what the project uses yet.`
41
+ : `CPU: the project used ${cpu.use.cores.toFixed(1)} of its ${cpu.limit}-core limit at ${whenAgo(cpu.use.at, now)}; ${cpu.use.held} slot${cpu.use.held === 1 ? '' : 's'} held, ${cpu.use.waiting} waiting.`;
42
+
43
+ export interface WorkflowsDashboardProps {
44
+ readonly data: WorkflowsPageData | null;
45
+ /** Why the data could not be read, if it could not; the last data read stays shown. */
46
+ readonly error: string | null;
47
+ /** Where one workflow's figures are read from when it is opened (`WorkflowFigures`): the project's route for them. */
48
+ readonly figuresUrl: (workflow: string) => string;
49
+ /** Where a definition's link goes: the project's source viewer. */
50
+ readonly sourceHref: (source: SourceLink) => string;
51
+ /** The project's own lines above everything: its title, its status. */
52
+ readonly header?: ReactNode;
53
+ /** The project's own panels, between the header and the workflows. */
54
+ readonly panels?: ReactNode;
55
+ /** The project's name for one phase, in its own words; the phase's key where it gives none. */
56
+ readonly phaseLabel?: (phase: string) => string;
57
+ /** The project's figures for one phase, on its heading line. */
58
+ readonly phaseSummary?: (phase: string) => ReactNode;
59
+ /** How the page sets a limit; with none the limits show without controls. */
60
+ readonly setLimit?: SetLimit;
61
+ }
62
+
63
+ /** Polls a JSON route one request at a time, the next asked for when this one has answered. */
64
+ export const usePolledJson = <A,>(url: string, everyMs: number): { readonly data: A | null; readonly error: string | null } => {
65
+ const [data, setData] = useState<A | null>(null);
66
+ const [error, setError] = useState<string | null>(null);
67
+ useEffect(() => {
68
+ let alive = true;
69
+ let next: ReturnType<typeof setTimeout> | undefined;
70
+ const tick = async () => {
71
+ try {
72
+ const r = await fetch(url, { cache: 'no-store' });
73
+ if (!r.ok) throw new Error(`${r.status} ${(await r.text()).slice(0, 200)}`);
74
+ const body = (await r.json()) as A;
75
+ if (alive) { setData(body); setError(null); }
76
+ } catch (e) {
77
+ if (alive) setError(e instanceof Error ? e.message : String(e));
78
+ }
79
+ if (alive) next = setTimeout(() => void tick(), everyMs);
80
+ };
81
+ void tick();
82
+ return () => { alive = false; clearTimeout(next); };
83
+ }, [url, everyMs]);
84
+ return { data, error };
85
+ };
86
+
87
+ const costCells = (c: StepCost | null, agent: boolean): ReactNode => (
88
+ <>
89
+ <td className="wp-r">{c === null ? '' : c.calls.toLocaleString('en-US')}</td>
90
+ <td className={c !== null && c.failed > 0 ? 'wp-r wp-bad' : 'wp-r'}>{c === null || c.failed === 0 ? '' : c.failed.toLocaleString('en-US')}</td>
91
+ <td className="wp-r">{c === null ? '' : duration(c.seconds)}</td>
92
+ <td className="wp-r">{c === null || !agent ? '' : `${compact(c.inputTokens)} / ${compact(c.outputTokens)}`}</td>
93
+ <td className="wp-r">{c === null ? '' : duration(c.cpuSeconds)}</td>
94
+ <td className="wp-r">{c === null || c.items === 0 ? '' : c.items.toLocaleString('en-US')}</td>
95
+ </>
96
+ );
97
+
98
+ /** Where a step's runs are now, in words: "2 in it", "1 waiting after it since 5:04 AM · 3 min ago". */
99
+ const nowCell = (s: StepRunsNow | undefined, now: number): string => {
100
+ if (s === undefined) return '';
101
+ const parts = [
102
+ ...(s.inStep > 0 ? [`${s.inStep} in it`] : []),
103
+ ...(s.waitingAfter > 0 ? [`${s.waitingAfter} after it${s.waitingSince === null ? '' : `, since ${whenAgo(s.waitingSince, now)}`}`] : []),
104
+ ];
105
+ return parts.join(', ');
106
+ };
107
+
108
+ function StepsTable({ workflow, usesAgents, runs, now }: { readonly workflow: WorkflowFigures; readonly usesAgents: boolean; readonly runs: WorkflowRunsNow | undefined; readonly now: number }) {
109
+ const runsOf = (step: string) => runs?.steps.find((s) => s.step === step);
110
+ return (
111
+ <div className="wp-tablewrap"><table className="wp-table">
112
+ <thead>
113
+ <tr>
114
+ <th>step</th><th title="Uses an agent">agent</th><th>runs now</th>
115
+ <th className="wp-r">calls</th><th className="wp-r">failed</th><th className="wp-r">time</th>
116
+ <th className="wp-r" title="Input tokens, fresh and cached / output tokens">tokens in / out</th>
117
+ <th className="wp-r" title="Its own and its processes' CPU">CPU</th><th className="wp-r">items</th>
118
+ <th title="How its records ended, commonest first; the rest in the hover">ended</th>
119
+ </tr>
120
+ </thead>
121
+ <tbody>
122
+ {workflow.steps.map((s) => {
123
+ const at = runsOf(s.name);
124
+ return (
125
+ <Fragment key={s.name}>
126
+ <tr>
127
+ <td title={s.description} className={s.declared ? '' : 'wp-bad'}>{s.name}{s.declared ? '' : ' (not declared)'}</td>
128
+ <td>{s.agent ? '✓' : ''}</td>
129
+ <td className="wp-mut">{nowCell(at, now)}</td>
130
+ {costCells(s.cost, s.agent)}
131
+ <td className="wp-mut" title={s.endings.map((e) => `${e.records} ${e.outcome}: ${e.reason}`).join('\n')}>{s.endings.length === 0 ? '' : `${s.endings[0]!.reason} (${s.endings[0]!.records})`}</td>
132
+ </tr>
133
+ {at?.waitingOn === null || at?.waitingOn === undefined ? null : (
134
+ <tr><td /><td /><td colSpan={8} className="wp-mut">waits: {at.waitingOn}</td></tr>
135
+ )}
136
+ </Fragment>
137
+ );
138
+ })}
139
+ <tr className="wp-total">
140
+ <td>total</td><td /><td className="wp-mut">{runs === undefined || runs.runs === 0 ? '' : `${runs.runs} run${runs.runs === 1 ? '' : 's'}`}</td>
141
+ {costCells(workflow.total, usesAgents)}
142
+ <td />
143
+ </tr>
144
+ </tbody>
145
+ </table></div>
146
+ );
147
+ }
148
+
149
+ function FunnelTable({ funnel }: { readonly funnel: StepFunnel }) {
150
+ if (funnel.runs === 0) return <p className="wp-line wp-mut">No run began since {localTime(funnel.since)}.</p>;
151
+ return (
152
+ <>
153
+ <p className="wp-line">
154
+ {funnel.runs.toLocaleString('en-US')} run{funnel.runs === 1 ? '' : 's'} began since {localTime(funnel.since)}, {funnel.going.toLocaleString('en-US')} still going.
155
+ </p>
156
+ <div className="wp-tablewrap"><table className="wp-table">
157
+ <thead><tr><th>step</th><th className="wp-r">reached</th><th className="wp-r">stopped here</th><th className="wp-r">finished here</th><th className="wp-r">median time</th></tr></thead>
158
+ <tbody>
159
+ {funnel.steps.map((s) => (
160
+ <tr key={s.step} className={s.noneGotPast ? 'wp-bad' : ''}>
161
+ <td>{s.step}{s.noneGotPast ? ' (none got past)' : ''}</td>
162
+ <td className="wp-r">{s.reached.toLocaleString('en-US')}</td>
163
+ <td className="wp-r">{s.stopped === 0 ? '' : s.stopped.toLocaleString('en-US')}</td>
164
+ <td className="wp-r">{s.finished === 0 ? '' : s.finished.toLocaleString('en-US')}</td>
165
+ <td className="wp-r">{s.medianSeconds === null ? '' : duration(s.medianSeconds)}</td>
166
+ </tr>
167
+ ))}
168
+ </tbody>
169
+ </table></div>
170
+ {funnel.mostStopped === null ? null : (
171
+ <p className="wp-line">
172
+ Most stopped at {funnel.mostStopped.step} ({funnel.mostStopped.stopped.toLocaleString('en-US')}):{' '}
173
+ {funnel.mostStopped.reasons.map((r) => `${r.reason} (${r.runs})`).join('; ')}
174
+ {funnel.mostStopped.otherRuns > 0 ? `; ${funnel.mostStopped.otherRuns} for other reasons` : ''}.
175
+ </p>
176
+ )}
177
+ </>
178
+ );
179
+ }
180
+
181
+ /** A figure to two places, or "none" where there was nothing to divide by. */
182
+ const per = (n: number | null): string => (n === null ? 'none' : n === 0 ? '0' : n < 0.01 ? n.toPrecision(2) : n.toFixed(n >= 10 ? 0 : 2));
183
+
184
+ /** What its runs finished over the window, per run, per million tokens and per compile, with the window before beside it. */
185
+ const yieldLine = (w: WorkflowFigures, finishedWord: string | null): string => {
186
+ const { now, before } = w.yields;
187
+ const word = finishedWord ?? 'finished';
188
+ const trend = now.finished === before.finished ? 'the same as' : now.finished > before.finished ? 'up from' : 'down from';
189
+ return `${now.finished.toLocaleString('en-US')} ${word} in ${now.runs.toLocaleString('en-US')} runs, ${trend} ${before.finished.toLocaleString('en-US')} in the ${before.runs.toLocaleString('en-US')} before: `
190
+ + `${per(now.perRun)} a run, ${per(now.perMillionTokens)} per million tokens, ${per(now.perCompile)} a compile (before: ${per(before.perRun)}, ${per(before.perMillionTokens)}, ${per(before.perCompile)}).`;
191
+ };
192
+
193
+ /** What a run of it costs: the median run's time, tokens, CPU (its processes' part) and compiles, and its costliest run. */
194
+ const runCostLine = (w: WorkflowFigures): string => {
195
+ const c = w.runCosts;
196
+ if (c.median === null) return 'No run ended in the window.';
197
+ const tokens = c.median.tokens === 0 ? '' : `, ${compact(c.median.tokens)} tokens`;
198
+ const compiles = c.median.compiles === 0 ? '' : `, ${compact(c.median.compiles)} compiles`;
199
+ const costliest = c.costliest === null ? '' : `; costliest ${duration(c.costliest.cpuSeconds)} of CPU, started ${localTime(c.costliest.started)}`;
200
+ return `A run costs ${duration(c.median.seconds)}${tokens}, ${duration(c.median.cpuSeconds)} of CPU (${duration(c.median.childCpuSeconds)} in its processes)${compiles}, the median of ${c.runs.toLocaleString('en-US')} runs${costliest}.`;
201
+ };
202
+
203
+ /** What each limit sets, said on its control. */
204
+ const LIMIT_WORDS: Readonly<Record<LimitName, { readonly unit: (n: number) => string; readonly says: string }>> = {
205
+ runs: { unit: (n) => `run${n === 1 ? '' : 's'}`, says: 'Run limit: how many runs of it may go at once, however they start; at 0 none starts. With none set: its agents\' limit where it has one, else no limit.' },
206
+ agents: { unit: (n) => `agent${n === 1 ? '' : 's'}`, says: 'Agents\' limit: how many of its runs may be in an agent step at once. A run at an agent step with none free waits there; at 0 none goes past its first agent step.' },
207
+ };
208
+
209
+ /**
210
+ * ONE LIMIT AND ITS BUTTONS. A click shows at once, as asked, until the page's next reading says the same; a failed one says
211
+ * why. A run limit set can go back to its default.
212
+ */
213
+ function LimitControl({ workflow, limit, value, isDefault, setLimit }: { readonly workflow: string; readonly limit: LimitName; readonly value: number | null; readonly isDefault: boolean; readonly setLimit: SetLimit | undefined }) {
214
+ const [asked, setAsked] = useState<{ readonly value: number | null } | null>(null);
215
+ const [failed, setFailed] = useState<string | null>(null);
216
+ useEffect(() => {
217
+ if (asked !== null && (asked.value === null ? isDefault : asked.value === value && !isDefault)) setAsked(null);
218
+ }, [asked, value, isDefault]);
219
+ const words = LIMIT_WORDS[limit];
220
+ const shown = asked === null || asked.value === null ? value : asked.value;
221
+ const set = (next: number | null) => {
222
+ if (setLimit === undefined) return;
223
+ setAsked({ value: next });
224
+ setFailed(null);
225
+ setLimit({ workflow, limit, value: next }).catch((e: unknown) => { setAsked(null); setFailed(e instanceof Error ? e.message : String(e)); });
226
+ };
227
+ return (
228
+ <span className="wp-limit" title={words.says} onClick={(e) => e.preventDefault()}>
229
+ {setLimit === undefined ? null : <button type="button" aria-label={`Lower the ${limit === 'runs' ? 'run limit' : 'agents\' limit'} of ${workflow}`} disabled={shown === 0} onClick={() => set(shown === null ? 0 : shown - 1)}>−</button>}
230
+ <span className={shown === 0 ? 'wp-bad' : 'wp-mut'}>{shown === null ? 'runs: no limit' : `${shown} ${words.unit(shown)}`}{limit === 'runs' && isDefault && shown !== null && asked === null ? ' (default)' : ''}</span>
231
+ {setLimit === undefined ? null : <button type="button" aria-label={`Raise the ${limit === 'runs' ? 'run limit' : 'agents\' limit'} of ${workflow}`} onClick={() => set(shown === null ? 1 : shown + 1)}>+</button>}
232
+ {setLimit === undefined || limit !== 'runs' || isDefault ? null : <button type="button" aria-label={`Put the run limit of ${workflow} back to its default`} onClick={() => set(null)}>default</button>}
233
+ {failed === null ? null : <span className="wp-bad">not saved: {failed}</span>}
234
+ </span>
235
+ );
236
+ }
237
+
238
+ /** A workflow's runs and agents now, and its limits with their controls: what its node shows below its queue. */
239
+ function WorkflowStatus({ workflow, runs, limits, setLimit }: { readonly workflow: WorkflowView; readonly runs: WorkflowRunsNow | undefined; readonly limits: WorkflowLimits | null; readonly setLimit: SetLimit | undefined }) {
240
+ const going = runs?.runs ?? 0;
241
+ return (
242
+ <>
243
+ <span className={going === 0 ? 'wp-mut' : ''}>{going === 0 ? 'no run going' : `${going} run${going === 1 ? '' : 's'} going`}</span>
244
+ {workflow.usesAgents ? <span className="wp-count" title="Its runs in an agent step now">{runs?.onAgents ?? 0} on agents</span> : null}
245
+ {limits === null ? null : (
246
+ <>
247
+ <LimitControl workflow={workflow.name} limit="runs" value={limits.runs} isDefault={!limits.runsSet} setLimit={setLimit} />
248
+ {limits.agents === null ? null : <LimitControl workflow={workflow.name} limit="agents" value={limits.agents} isDefault={false} setLimit={setLimit} />}
249
+ </>
250
+ )}
251
+ </>
252
+ );
253
+ }
254
+
255
+ /** How often an open workflow's figures are read again. */
256
+ const FIGURES_EVERY_MS = 15_000;
257
+
258
+ /**
259
+ * An open workflow: what it gave and cost, its steps, its step graph and where its runs stopped, read from its own records
260
+ * while it is open. The figures of the workflow opened before it are never shown under this one's name.
261
+ */
262
+ function WorkflowDetail({ workflow, runs, now, figuresUrl }: { readonly workflow: WorkflowView; readonly runs: WorkflowRunsNow | undefined; readonly now: number; readonly figuresUrl: (workflow: string) => string }) {
263
+ const read = usePolledJson<WorkflowFigures>(figuresUrl(workflow.name), FIGURES_EVERY_MS);
264
+ const figures = read.data !== null && read.data.workflow === workflow.name ? read.data : null;
265
+ return (
266
+ <>
267
+ <h3 className="wp-h3">{workflow.name}: its steps</h3>
268
+ {figures === null ? <p className={read.error === null ? 'wp-line wp-mut' : 'wp-line wp-bad'}>{read.error === null ? 'Reading its figures…' : `Its figures could not be read: ${read.error}`}</p> : (
269
+ <>
270
+ <p className="wp-line wp-mut">Its figures over the last {figures.hours} h, read {whenAgo(figures.at, now)}.</p>
271
+ {workflow.item === null ? null : <p className="wp-line">{yieldLine(figures, workflow.finishedWord)}</p>}
272
+ <p className="wp-line">{runCostLine(figures)}</p>
273
+ <StepsTable workflow={figures} usesAgents={workflow.usesAgents} runs={runs} now={now} />
274
+ <h4 className="wp-h4">Step graph</h4>
275
+ <StepGraph graph={figures.graph} />
276
+ <h4 className="wp-h4">Where runs stopped</h4>
277
+ <FunnelTable funnel={figures.funnel} />
278
+ </>
279
+ )}
280
+ </>
281
+ );
282
+ }
283
+
284
+ export function WorkflowsDashboard({ data, error, figuresUrl, sourceHref, header, panels, phaseLabel, phaseSummary, setLimit }: WorkflowsDashboardProps) {
285
+ const now = Date.now() / 1000;
286
+ return (
287
+ <div className="wp-page">
288
+ {header}
289
+ <p className={error === null ? 'wp-line wp-mut' : 'wp-line wp-bad'}>
290
+ {error !== null ? `The workflows could not be read: ${error}` : data === null ? 'Reading the workflows…' : `Read from the records ${whenAgo(data.view.at, now)}.`}
291
+ </p>
292
+ {data === null ? null : <p className={data.cpu.use !== null && data.cpu.use.cores > data.cpu.limit ? 'wp-line wp-bad' : 'wp-line'}>{cpuLine(data.cpu, now)}</p>}
293
+ {panels}
294
+ {data === null ? null : <QueueChart view={data.view} />}
295
+ {data === null ? null : (() => {
296
+ const runsOf = (w: WorkflowView) => data.runsNow.find((p) => p.phase === w.phase)?.workflows.find((r) => r.workflow === w.name);
297
+ return (
298
+ <WorkflowDag
299
+ view={data.view}
300
+ phaseLabel={(phase) => (phaseLabel === undefined ? phase : phaseLabel(phase))}
301
+ phaseLine={(phase) => {
302
+ const p = data.runsNow.find((r) => r.phase === phase);
303
+ return <>{p === undefined ? 0 : p.runs} running, {p === undefined ? 0 : p.onAgents} on agents{phaseSummary === undefined ? null : <> · {phaseSummary(phase)}</>}</>;
304
+ }}
305
+ nodeStatus={(w) => <WorkflowStatus workflow={w} runs={runsOf(w)} limits={w.limits} setLimit={setLimit} />}
306
+ nodeHref={(w) => sourceHref(w.source)}
307
+ detail={(w) => <WorkflowDetail workflow={w} runs={runsOf(w)} now={now} figuresUrl={figuresUrl} />}
308
+ />
309
+ );
310
+ })()}
311
+ </div>
312
+ );
313
+ }
package/src/index.ts CHANGED
@@ -15,7 +15,8 @@ import { makeStepFiles } from './step-files';
15
15
  import { makeStepUsage } from './step-usage';
16
16
  import { keptRunningByItsBudget, makeSteps, runLimitOf } from './steps';
17
17
  import { makeTasks, type TaskRules } from './tasks';
18
- import { buildWorkflowsView, type WorkflowsView, type WorkflowView } from './views/workflows-view';
18
+ import { buildWorkflowFigures, buildWorkflowsView, type WorkflowFigures, type WorkflowsView, type WorkflowView } from './views/workflows-view';
19
+ import { makeQueueCounts } from './queue-counts';
19
20
  import { sqliteBudgets, type LimitStore } from './storage/budgets';
20
21
  import { sqliteEngineRecords, type EngineRecords } from './storage/engine-records';
21
22
  import { sqliteStore } from './storage/sqlite-store';
@@ -28,6 +29,7 @@ export * from './project';
28
29
  export * from './budget-states';
29
30
  export * from './keep-running';
30
31
  export * from './pick-wakes';
32
+ export * from './queue-counts';
31
33
  export * from './step-files';
32
34
  export * from './step-meter';
33
35
  export * from './steps';
@@ -102,60 +104,53 @@ export const createWorkflowPlatform = <Phase extends string, R>(input: {
102
104
  const steps = makeSteps<Phase, R>({
103
105
  sourceRoot: project.sourceRoot, stepRecords: storage.stepRecords, engine: storage.engine, tasks, wakes, budgets: storage.budgets, stepFiles,
104
106
  CurrentStepUsage: stepUsage.CurrentStepUsage, isTransientFailure: project.isTransientFailure, thisProcess: project.processes.thisProcess, inputs: storage.inputs,
107
+ queueChanged: (workflow) => queueCounts.changed(workflow),
108
+ });
109
+ const queueCounts = makeQueueCounts<R>({
110
+ store: storage.tasks, tasks, wakes, readTaskInputs: steps.readTaskInputs,
111
+ withQueues: () => steps.declaredWorkflows().filter((d) => d.item !== null).map((d) => d.name),
105
112
  });
106
113
  /**
107
- * Every workflow as a dashboard shows it, over the `hours` before `now` (`views/workflows-view.ts`). `phases` is the order the
108
- * project's page shows them in; `pausedOf`, why a workflow is paused, none while it is not.
109
- */
110
- /**
111
- * A workflow's limits now, as stored. Every workflow has a run limit (`steps.ts` `runLimitOf`), none meaning no limit;
112
- * only one its budget keeps going has an agents' limit. None where no store is read (a test).
114
+ * Every workflow's limits now, by name, in one read: what a page's controls show. Every workflow has a run limit
115
+ * (`steps.ts` `runLimitOf`), none meaning no limit; only one its budget keeps going has an agents' limit. Empty where no
116
+ * store is read (a test).
113
117
  */
114
- const limitsOf = (name: string): Effect.Effect<WorkflowView['limits'], StorageError> => {
115
- const d = steps.declaredWorkflows().find((w) => w.name === name);
116
- if (d === undefined) return Effect.succeed(null);
117
- return Effect.map(storage.budgets.limitsOf(name), (limits) => (limits === null ? null : {
118
- agents: keptRunningByItsBudget(d) ? limits.agents : null, runs: runLimitOf(d, limits), runsSet: limits.runs !== null,
119
- }));
120
- };
121
-
122
- /** Every limited workflow's two limits now, by name: what a page's controls show, read at each request. */
123
118
  const limitsNow = (): Effect.Effect<Readonly<Record<string, NonNullable<WorkflowView['limits']>>>, StorageError> =>
124
- Effect.map(
125
- Effect.forEach(steps.declaredWorkflows(), (d) => Effect.map(limitsOf(d.name), (limits) => ({ name: d.name, limits }))),
126
- (all) => Object.fromEntries(all.flatMap((w) => (w.limits === null ? [] : [[w.name, w.limits] as const]))),
127
- );
119
+ Effect.map(storage.budgets.storedLimits(), (stored) => (stored === null ? {} : Object.fromEntries(steps.declaredWorkflows().map((d) => {
120
+ const limits = stored.get(d.name) ?? { agents: 0, runs: null };
121
+ return [d.name, { agents: keptRunningByItsBudget(d) ? limits.agents : null, runs: runLimitOf(d, limits), runsSet: limits.runs !== null }] as const;
122
+ }))));
128
123
 
129
- const view = (r: { readonly now: number; readonly hours: number; readonly phases: ReadonlyArray<string>; readonly pausedOf: (workflow: string) => string | null }): Effect.Effect<WorkflowsView, StorageError> => Effect.gen(function* () {
124
+ /** Each source file's text, read again only when the file changed: a page's links name the line a definition is on now. */
125
+ const texts = new Map<string, { readonly changed: number; readonly text: string } | null>();
126
+ const locate = (s: { readonly path: string; readonly anchor: string }): number | null => {
127
+ const file = path.join(project.sourceRoot, s.path);
128
+ try {
129
+ const changed = fs.statSync(file).mtimeMs;
130
+ if (texts.get(s.path)?.changed !== changed) texts.set(s.path, { changed, text: fs.readFileSync(file, 'utf8') });
131
+ } catch {
132
+ texts.set(s.path, null);
133
+ }
134
+ const text = texts.get(s.path)?.text;
135
+ const at = text === undefined ? -1 : text.indexOf(s.anchor);
136
+ return text === undefined || at < 0 ? null : text.slice(0, at).split('\n').length;
137
+ };
138
+
139
+ /**
140
+ * Every workflow as a dashboard shows it before one is opened, read now (`views/workflows-view.ts` `buildWorkflowsView`).
141
+ * `phases` is the order the project's page shows them in.
142
+ */
143
+ const view = (r: { readonly now: number; readonly phases: ReadonlyArray<string> }): Effect.Effect<WorkflowsView, StorageError> => Effect.gen(function* () {
130
144
  const limits = yield* limitsNow();
131
- const declared = steps.declaredWorkflows();
132
- // Each file read once for the whole view.
133
- const texts = new Map<string, string | null>();
134
- const textOf = (file: string): string | null => {
135
- if (!texts.has(file)) {
136
- try { texts.set(file, fs.readFileSync(path.join(project.sourceRoot, file), 'utf8')); } catch { texts.set(file, null); }
137
- }
138
- return texts.get(file) ?? null;
139
- };
140
- const built = yield* buildWorkflowsView({
141
- declared, phases: r.phases, now: r.now, hours: r.hours,
142
- records: storage.stepRecords, engine: storage.engine, tasks, taskStore: storage.tasks,
143
- locate: (s) => {
144
- const text = textOf(s.path);
145
- const at = text === null ? -1 : text.indexOf(s.anchor);
146
- return text === null || at < 0 ? null : text.slice(0, at).split('\n').length;
147
- },
148
- limitsOf: (name) => limits[name] ?? null,
149
- pausedOf: r.pausedOf,
150
- });
151
- // EACH QUEUE'S HISTORY, recorded here since the view counts every queue anyway: a row only where a count moved.
152
- yield* storage.tasks.recordQueueCounts({
153
- at: r.now,
154
- counts: built.groups.flatMap((g) => g.workflows.flatMap((w) => (w.queue === null ? [] : Object.entries(w.queue).map(([bucket, n]) => ({ workflow: w.name, bucket, tasks: n }))))),
155
- });
156
- return built;
145
+ return yield* buildWorkflowsView({ declared: steps.declaredWorkflows(), phases: r.phases, now: r.now, taskStore: storage.tasks, locate, limitsOf: (name) => limits[name] ?? null });
157
146
  });
158
- return { project, storage, wakes, stepFiles, stepUsage, tasks, steps, view, limitsNow };
147
+
148
+ /** One workflow's figures over the `hours` before `now`, read from its own records (`buildWorkflowFigures`); none for one not declared. */
149
+ const figures = (r: { readonly workflow: string; readonly now: number; readonly hours: number }): Effect.Effect<WorkflowFigures | null, StorageError> => {
150
+ const declaration = steps.declaredWorkflows().find((d) => d.name === r.workflow);
151
+ return declaration === undefined ? Effect.succeed(null) : buildWorkflowFigures({ declaration, now: r.now, hours: r.hours, records: storage.stepRecords, engine: storage.engine, locate });
152
+ };
153
+ return { project, storage, wakes, stepFiles, stepUsage, tasks, steps, view, figures, limitsNow, queueCounts };
159
154
  };
160
155
 
161
156
  export type WorkflowPlatform<Phase extends string, R> = ReturnType<typeof createWorkflowPlatform<Phase, R>>;
@@ -7,7 +7,7 @@
7
7
  * one trigger, with no code of its own: each turn it starts as many runs as the workflow's run limit keeps (`runLimit`) above
8
8
  * the runs going, as soon as a run ends and otherwise on a fallback timer. There is no sharing between workflows, no order,
9
9
  * no cap per item and no check of usage: a run with nothing to pick waits for an item (`steps.ts` `untilPicked`), and the
10
- * stuck bucket and the queue's order keep a run off what it cannot finish. A pause holds one workflow.
10
+ * stuck bucket and the queue's order keep a run off what it cannot finish. A run limit of 0 holds one workflow.
11
11
  */
12
12
  import { keptRunningByItsBudget, type WorkflowDeclaration } from './steps';
13
13
  import { runLimit, type WorkflowLimits } from './storage/budgets';
@@ -24,22 +24,20 @@ export const budgetedWorkflows = <D extends Pick<WorkflowDeclaration<string, unk
24
24
  declared.filter(keptRunningByItsBudget);
25
25
 
26
26
  /**
27
- * How many runs of one workflow to start now: the runs its run limit keeps above the runs going, and none while it is
28
- * paused. Its agents' limit plays no part: at 0 agents its runs wait at their first agent step. Pure.
27
+ * How many runs of one workflow to start now: the runs its run limit keeps above the runs going. Its agents' limit plays
28
+ * no part: at 0 agents its runs wait at their first agent step. Pure.
29
29
  */
30
- export const runsToStart = (w: { readonly kept: number; readonly running: number; readonly paused: boolean }): number =>
31
- w.paused ? 0 : Math.max(w.kept - w.running, 0);
30
+ export const runsToStart = (w: { readonly kept: number; readonly running: number }): number => Math.max(w.kept - w.running, 0);
32
31
 
33
32
  /** One turn's plan: for each budgeted workflow, the runs going and how many to start. Pure but for the reads it is given. */
34
33
  export const planRunStarts = <D extends Pick<WorkflowDeclaration<string, unknown>, 'name' | 'pending' | 'steps'>>(input: {
35
34
  readonly declared: ReadonlyArray<D>;
36
35
  readonly limitsOf: (workflow: string) => WorkflowLimits;
37
- readonly paused: (workflow: string) => boolean;
38
36
  readonly runningRuns: (workflow: string) => number;
39
37
  }): ReadonlyArray<{ readonly declaration: D; readonly running: number; readonly start: number }> =>
40
38
  budgetedWorkflows(input.declared).map((d) => {
41
39
  const running = input.runningRuns(d.name);
42
- return { declaration: d, running, start: runsToStart({ kept: runLimit(input.limitsOf(d.name)), running, paused: input.paused(d.name) }) };
40
+ return { declaration: d, running, start: runsToStart({ kept: runLimit(input.limitsOf(d.name)), running }) };
43
41
  });
44
42
 
45
43
  /**
package/src/pick-wakes.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * WHAT WAKES A PICK THAT FOUND NOTHING IT CAN CLAIM (`steps.ts` `untilPicked`), never a timer. A wake is any event that can
3
3
  * change what a Pick can claim: a note on one of its workflow's tasks (new input, a reopen, a release, a hold, an outcome:
4
- * `tasks.ts`), an item new to its list (`recordListing`), its limits or pause set (which also has the run planner plan
4
+ * `tasks.ts`), an item new to its list (`recordListing`), its limits set (which also has the run planner plan
5
5
  * again: `runPlanChanged`), or one of its runs ending, which lets that run's
6
6
  * claim go. A claim held outside its workflow's runs ending, or a lease running out, wakes nothing: the next of these events
7
7
  * re-checks it. Before 2026-11-11 a Pick with nothing picked again each minute, and at budget 0 it ended its run at once:
@@ -37,12 +37,14 @@ export interface PickWakes {
37
37
  /** Something every workflow's Picks can claim may have changed (every budget was set). */
38
38
  readonly wakeEveryPick: (source: string) => void;
39
39
  /**
40
- * A workflow's limits or its pause were set (every workflow's, when `workflow` is none): its Picks are woken, and the run
40
+ * A workflow's limits were set (every workflow's, when `workflow` is none): its Picks are woken, and the run
41
41
  * planner (`keep-running.ts`), told through `onRunPlanChanged` in the process it runs in, plans its runs again at once.
42
42
  */
43
43
  readonly runPlanChanged: (r: { readonly workflow: string | null; readonly source: string }) => void;
44
44
  /** Calls `listener` on each `runPlanChanged` that reaches this process, raised here or relayed. */
45
45
  readonly onRunPlanChanged: (listener: (workflow: string | null) => void) => void;
46
+ /** Calls `listener` on each wake that reaches this process, raised here or relayed: what else follows a queue's changes (`queue-counts.ts`). */
47
+ readonly onWake: (listener: (wake: Wake) => void) => void;
46
48
  /** Waits until a wake reaches this workflow after `after` wakes; at once when one already has. */
47
49
  readonly untilPickWoken: (r: { readonly workflow: string; readonly after: number }) => Effect.Effect<void>;
48
50
  /** A waiting Pick picked again after a wake: `ms` is how long that pick took. */
@@ -102,9 +104,11 @@ export const makePickWakes = (): PickWakes => {
102
104
 
103
105
  let relay: ((wake: Wake) => void) | null = null;
104
106
  const runPlanListeners = new Set<(workflow: string | null) => void>();
107
+ const wakeListeners = new Set<(wake: Wake) => void>();
105
108
  let released = false;
106
109
 
107
110
  const wakeHere = (w: Wake): void => {
111
+ for (const listener of wakeListeners) queueMicrotask(() => listener(w));
108
112
  if (w.runPlan === true) for (const listener of runPlanListeners) queueMicrotask(() => listener(w.workflow));
109
113
  if (w.workflow === null) {
110
114
  wakesOfEvery += 1;
@@ -131,6 +135,9 @@ export const makePickWakes = (): PickWakes => {
131
135
  onRunPlanChanged: (listener) => {
132
136
  runPlanListeners.add(listener);
133
137
  },
138
+ onWake: (listener) => {
139
+ wakeListeners.add(listener);
140
+ },
134
141
  relayTo: (send) => {
135
142
  relay = send;
136
143
  },
@@ -0,0 +1,61 @@
1
+ /**
2
+ * EACH QUEUE'S COUNTS, RECORDED WHEN ITS QUEUE MAY HAVE CHANGED (`queue_counts`), so a page reads the newest row and never
3
+ * counts. A workflow's tasks by bucket are worked out from every task's notes (`tasks.ts` `summarize`): 0.7 s for a
4
+ * project's 20,000 tasks on a busy machine, too long for a page load, and until 2026-11-17 a job did it every 5 minutes for
5
+ * a stored page. Here it is done once per change, in the one process that runs the project's workflows, which is also the
6
+ * one that has read each task's inputs as its Pick reads them, so the page and the Pick put a task in the same bucket.
7
+ *
8
+ * WHAT COUNTS AS A CHANGE: every wake of a workflow's Picks (`pick-wakes.ts`: a note on one of its tasks, an item new to
9
+ * its list, one of its runs ending, a limit set), and a Pick claiming an item (`changed`). Every change within
10
+ * `COUNT_AFTER_MS` of the first is one count, taken at its end, so 25 short runs ending a minute cost 12 counts and each
11
+ * change shows within 5 seconds. A row is written only where a count moved.
12
+ */
13
+ import { Effect } from 'effect';
14
+ import type { PickWakes } from './pick-wakes';
15
+ import type { StorageError } from './storage/storage-error';
16
+ import type { TaskStore } from './storage/task-store';
17
+ import { bucketCounts, type Tasks } from './tasks';
18
+
19
+ /** How long after a queue's first change it is counted: every change in that time is in the one count. */
20
+ export const COUNT_AFTER_MS = 5_000;
21
+
22
+ export const makeQueueCounts = <R>(deps: {
23
+ readonly store: Pick<TaskStore, 'recordQueueCounts'>;
24
+ readonly tasks: Pick<Tasks, 'taskSummaries'>;
25
+ readonly wakes: Pick<PickWakes, 'onWake'>;
26
+ /** The workflows that have a queue, now. */
27
+ readonly withQueues: () => ReadonlyArray<string>;
28
+ /** Reads a workflow's tasks' inputs where it declares them (`steps.ts` `readTaskInputs`), as its Pick does before it reads its queue. */
29
+ readonly readTaskInputs: (workflow: string) => Effect.Effect<unknown, unknown, R>;
30
+ /** `COUNT_AFTER_MS` where absent; a test names a shorter one. */
31
+ readonly countAfterMs?: number;
32
+ }) => {
33
+ /** Counts one workflow's queue now and records it. Its inputs unread, it is counted with those last read, and that is said. */
34
+ const count = (workflow: string): Effect.Effect<void, StorageError, R> => Effect.gen(function* () {
35
+ yield* Effect.catch(deps.readTaskInputs(workflow), (e) => Effect.logError(`[queue counts] ${workflow}: its tasks' inputs could not be read, so it is counted with those last read: ${String(e)}`));
36
+ const counts = bucketCounts(yield* deps.tasks.taskSummaries({ workflow }));
37
+ yield* deps.store.recordQueueCounts({ at: Date.now() / 1000, counts: Object.entries(counts).map(([bucket, tasks]) => ({ workflow, bucket, tasks })) });
38
+ });
39
+
40
+ let countSoon: (workflow: string) => void = () => undefined;
41
+
42
+ /**
43
+ * Starts recording: for the one process that runs the project's workflows, which gives `run`, how it runs an effect of
44
+ * theirs. Every queue is counted once at the start, then each on its changes.
45
+ */
46
+ const record = (run: (count: Effect.Effect<void, StorageError, R>) => Promise<void>): void => {
47
+ const due = new Set<string>();
48
+ countSoon = (workflow) => {
49
+ if (due.has(workflow) || !deps.withQueues().includes(workflow)) return;
50
+ due.add(workflow);
51
+ setTimeout(() => {
52
+ due.delete(workflow);
53
+ void run(count(workflow)).catch((e: unknown) => console.error(`[queue counts] ${workflow}: not counted: ${e instanceof Error ? e.message : String(e)}`));
54
+ }, deps.countAfterMs ?? COUNT_AFTER_MS).unref?.();
55
+ };
56
+ deps.wakes.onWake((wake) => { for (const workflow of wake.workflow === null ? deps.withQueues() : [wake.workflow]) countSoon(workflow); });
57
+ for (const workflow of deps.withQueues()) countSoon(workflow);
58
+ };
59
+
60
+ return { count, record, changed: (workflow: string): void => countSoon(workflow) };
61
+ };