@jive-sh/workflow-platform 0.6.3 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/README.md +66 -295
  2. package/component/_generated/api.ts +72 -0
  3. package/component/_generated/component.ts +621 -0
  4. package/component/_generated/dataModel.ts +60 -0
  5. package/component/_generated/server.ts +169 -0
  6. package/component/convex.config.ts +3 -0
  7. package/component/engine.ts +755 -0
  8. package/component/errors.ts +66 -0
  9. package/component/events.ts +17 -0
  10. package/component/notes.ts +13 -0
  11. package/component/places.ts +136 -0
  12. package/component/retention.ts +205 -0
  13. package/component/runEngine.ts +25 -0
  14. package/component/schema.ts +132 -0
  15. package/component/steps.ts +188 -0
  16. package/component/store.ts +512 -0
  17. package/component/tasks.ts +289 -0
  18. package/component/worker.ts +109 -0
  19. package/component/workflows.ts +83 -0
  20. package/dist/definition/agent-runner.js +9 -0
  21. package/dist/definition/agent-runner.js.map +1 -0
  22. package/dist/definition/file-store.js +9 -0
  23. package/dist/definition/file-store.js.map +1 -0
  24. package/dist/definition/program-build.js +10 -0
  25. package/dist/definition/program-build.js.map +1 -0
  26. package/dist/definition/step.js +1 -0
  27. package/dist/definition/step.js.map +1 -0
  28. package/dist/definition/task-schema.js +5 -0
  29. package/dist/definition/task-schema.js.map +1 -0
  30. package/dist/definition/tasks.js +9 -0
  31. package/dist/definition/tasks.js.map +1 -0
  32. package/dist/definition/workflow.js +111 -0
  33. package/dist/definition/workflow.js.map +1 -0
  34. package/dist/graph.js +301 -9
  35. package/dist/graph.js.map +1 -1
  36. package/dist/index.js +7 -133
  37. package/dist/index.js.map +1 -1
  38. package/package.json +9 -4
  39. package/src/definition/agent-runner.ts +59 -0
  40. package/src/definition/file-store.ts +20 -0
  41. package/src/definition/program-build.ts +30 -0
  42. package/src/definition/step.ts +106 -0
  43. package/src/definition/task-schema.ts +15 -0
  44. package/src/definition/tasks.ts +43 -0
  45. package/src/definition/workflow.ts +255 -0
  46. package/src/graph.ts +341 -19
  47. package/src/index.ts +8 -168
  48. package/worker/directory-file-store.ts +42 -0
  49. package/worker/index.ts +12 -0
  50. package/worker/platform-client.ts +138 -0
  51. package/worker/step-meter.ts +80 -0
  52. package/worker/worker-tasks.ts +27 -0
  53. package/worker/worker.test.ts +200 -0
  54. package/worker/worker.ts +240 -0
  55. package/dist/budget-states.js +0 -30
  56. package/dist/budget-states.js.map +0 -1
  57. package/dist/cpu-limit/limiter.js +0 -839
  58. package/dist/cpu-limit/limiter.js.map +0 -1
  59. package/dist/cpu-limit/use.js +0 -139
  60. package/dist/cpu-limit/use.js.map +0 -1
  61. package/dist/dashboard/agent-usage.js +0 -25
  62. package/dist/dashboard/agent-usage.js.map +0 -1
  63. package/dist/dashboard/dashboard.css +0 -134
  64. package/dist/dashboard/drilldown.js +0 -16
  65. package/dist/dashboard/drilldown.js.map +0 -1
  66. package/dist/dashboard/queue-lines.js +0 -44
  67. package/dist/dashboard/queue-lines.js.map +0 -1
  68. package/dist/dashboard/queue-table.js +0 -16
  69. package/dist/dashboard/queue-table.js.map +0 -1
  70. package/dist/dashboard/spending-words.js +0 -32
  71. package/dist/dashboard/spending-words.js.map +0 -1
  72. package/dist/failure.js +0 -35
  73. package/dist/failure.js.map +0 -1
  74. package/dist/keep-running.js +0 -77
  75. package/dist/keep-running.js.map +0 -1
  76. package/dist/outside-failure.js +0 -31
  77. package/dist/outside-failure.js.map +0 -1
  78. package/dist/pick-wakes.js +0 -125
  79. package/dist/pick-wakes.js.map +0 -1
  80. package/dist/project.js +0 -1
  81. package/dist/project.js.map +0 -1
  82. package/dist/queue-counts.js +0 -51
  83. package/dist/queue-counts.js.map +0 -1
  84. package/dist/reasons.js +0 -33
  85. package/dist/reasons.js.map +0 -1
  86. package/dist/spending-limit.js +0 -88
  87. package/dist/spending-limit.js.map +0 -1
  88. package/dist/step-files.js +0 -200
  89. package/dist/step-files.js.map +0 -1
  90. package/dist/step-meter.js +0 -97
  91. package/dist/step-meter.js.map +0 -1
  92. package/dist/step-usage.js +0 -19
  93. package/dist/step-usage.js.map +0 -1
  94. package/dist/steps.js +0 -920
  95. package/dist/steps.js.map +0 -1
  96. package/dist/storage/budgets.js +0 -85
  97. package/dist/storage/budgets.js.map +0 -1
  98. package/dist/storage/engine-records.js +0 -75
  99. package/dist/storage/engine-records.js.map +0 -1
  100. package/dist/storage/engine-storage.js +0 -67
  101. package/dist/storage/engine-storage.js.map +0 -1
  102. package/dist/storage/input-records.js +0 -12
  103. package/dist/storage/input-records.js.map +0 -1
  104. package/dist/storage/move-store.js +0 -251
  105. package/dist/storage/move-store.js.map +0 -1
  106. package/dist/storage/sqlite-store.js +0 -723
  107. package/dist/storage/sqlite-store.js.map +0 -1
  108. package/dist/storage/step-records.js +0 -11
  109. package/dist/storage/step-records.js.map +0 -1
  110. package/dist/storage/storage-error.js +0 -19
  111. package/dist/storage/storage-error.js.map +0 -1
  112. package/dist/storage/task-store.js +0 -24
  113. package/dist/storage/task-store.js.map +0 -1
  114. package/dist/tasks.js +0 -475
  115. package/dist/tasks.js.map +0 -1
  116. package/dist/views/format.js +0 -37
  117. package/dist/views/format.js.map +0 -1
  118. package/dist/views/runs-now.js +0 -75
  119. package/dist/views/runs-now.js.map +0 -1
  120. package/dist/views/step-funnel.js +0 -98
  121. package/dist/views/step-funnel.js.map +0 -1
  122. package/dist/views/step-graph.js +0 -34
  123. package/dist/views/step-graph.js.map +0 -1
  124. package/dist/views/workflow-flows.js +0 -53
  125. package/dist/views/workflow-flows.js.map +0 -1
  126. package/dist/views/workflows-view.js +0 -230
  127. package/dist/views/workflows-view.js.map +0 -1
  128. package/src/budget-states.ts +0 -55
  129. package/src/cpu-limit/limiter.ts +0 -935
  130. package/src/cpu-limit/use.ts +0 -166
  131. package/src/dashboard/agent-usage-line.tsx +0 -28
  132. package/src/dashboard/agent-usage.ts +0 -48
  133. package/src/dashboard/dashboard.css +0 -134
  134. package/src/dashboard/drilldown.ts +0 -43
  135. package/src/dashboard/index.tsx +0 -4
  136. package/src/dashboard/machine-controls.tsx +0 -53
  137. package/src/dashboard/queue-bar.tsx +0 -43
  138. package/src/dashboard/queue-chart.tsx +0 -150
  139. package/src/dashboard/queue-lines.ts +0 -87
  140. package/src/dashboard/queue-table.ts +0 -37
  141. package/src/dashboard/spending-limit-control.tsx +0 -50
  142. package/src/dashboard/spending-words.ts +0 -50
  143. package/src/dashboard/step-graph.tsx +0 -106
  144. package/src/dashboard/workflow-dag.tsx +0 -204
  145. package/src/dashboard/workflow-drilldown.tsx +0 -89
  146. package/src/dashboard/workflows-dashboard.tsx +0 -414
  147. package/src/failure.ts +0 -36
  148. package/src/keep-running.ts +0 -83
  149. package/src/outside-failure.ts +0 -39
  150. package/src/pick-wakes.ts +0 -182
  151. package/src/project.ts +0 -115
  152. package/src/queue-counts.ts +0 -64
  153. package/src/reasons.ts +0 -30
  154. package/src/spending-limit.ts +0 -156
  155. package/src/step-files.ts +0 -208
  156. package/src/step-meter.ts +0 -120
  157. package/src/step-usage.ts +0 -23
  158. package/src/steps.ts +0 -1239
  159. package/src/storage/budgets.ts +0 -113
  160. package/src/storage/engine-records.ts +0 -102
  161. package/src/storage/engine-storage.ts +0 -82
  162. package/src/storage/input-records.ts +0 -43
  163. package/src/storage/move-store.ts +0 -265
  164. package/src/storage/sqlite-store.ts +0 -829
  165. package/src/storage/step-records.ts +0 -306
  166. package/src/storage/storage-error.ts +0 -35
  167. package/src/storage/task-store.ts +0 -235
  168. package/src/tasks.ts +0 -561
  169. package/src/views/format.ts +0 -40
  170. package/src/views/runs-now.ts +0 -120
  171. package/src/views/step-funnel.ts +0 -163
  172. package/src/views/step-graph.ts +0 -68
  173. package/src/views/workflow-flows.ts +0 -97
  174. package/src/views/workflows-view.ts +0 -443
@@ -1,443 +0,0 @@
1
- /**
2
- * A PROJECT'S WORKFLOWS AS ITS DASHBOARD SHOWS THEM, READ FROM THE RECORDS AT EACH REQUEST, in two readings:
3
- *
4
- * every workflow what it is, its steps with their kinds, its limits, and its tasks by status with their history
5
- * (`buildWorkflowsView`): what a page shows before a workflow is opened, a few small readings.
6
- * one workflow its steps and their cost over a window, its step graph with the window's runs on it, and where its
7
- * runs stopped and why (`buildWorkflowFigures`): read from its own records when a page opens it.
8
- *
9
- * Built whole and stored by a job every 5 minutes, the two were one view: 5.7 s of reading on a busy machine, 4.4 s of it
10
- * three scans of every step record for figures only an opened workflow shows, and a page up to 5 minutes old (2026-11-17).
11
- * Built from the declarations and the stores alone, so any project's workflows read the same; a project adds its own
12
- * panels beside it. Where its runs are now (`runs-now.ts`) is read at each request too.
13
- */
14
- import { stepKindOf, stepUsesAnAgent, type SourceRef, type StepDeclaration, type StepKind, type StepRuns, type WorkflowDeclaration } from '../steps';
15
- import { pipelinePlaces, workflowFlows, type PipelinePlace, type WorkflowFlow } from './workflow-flows';
16
-
17
- /** A definition's link: its file and text, and the line that text is on now; none when the text is no longer in the file. */
18
- export interface SourceLink extends SourceRef {
19
- readonly line: number | null;
20
- }
21
- import { Effect } from 'effect';
22
- import type { StorageError } from '../storage/storage-error';
23
- import type { SpendingLimitState } from '../spending-limit';
24
- import { QUEUED_NEEDING_AN_AGENT } from '../queue-counts';
25
- import type { EngineRecords } from '../storage/engine-records';
26
- import type { FunnelStepRecord, RunCost, RunOutcomeRow, StepRecords, StepRunRow } from '../storage/step-records';
27
- import { TASK_STATUSES, type BlockedReason, type TaskStatus } from '../tasks';
28
- import type { QueueCount, TaskStore } from '../storage/task-store';
29
- import { stepFunnel, type StepFunnel } from './step-funnel';
30
- import { workflowGraphs, type WorkflowGraph } from './step-graph';
31
-
32
- /**
33
- * WHAT STARTS ITS RUNS, from its declaration: its queue (a list of work, its runs kept going while it has some), its inputs
34
- * changing (`inputs`, in its own words), or neither, a timer or a request.
35
- */
36
- export type StartsOn =
37
- | { readonly kind: 'queue' }
38
- | { readonly kind: 'inputs'; readonly says: string }
39
- | { readonly kind: 'timer or request' }
40
- /** It runs only as a step of the workflows named (`defineSubWorkflow`). */
41
- | { readonly kind: 'a step'; readonly of: ReadonlyArray<string> };
42
-
43
- /** How long the queues' history reaches back. */
44
- export const QUEUE_HISTORY_DAYS = 7;
45
-
46
- /** What one step of a workflow cost over the window, from its records: none for a step with no record in it. */
47
- export interface StepCost {
48
- /** Its records in the window: one per call. */
49
- readonly calls: number;
50
- readonly failed: number;
51
- /** Calls still going. */
52
- readonly open: number;
53
- readonly seconds: number;
54
- /** Input tokens, fresh and cached. */
55
- readonly inputTokens: number;
56
- readonly outputTokens: number;
57
- readonly cpuSeconds: number;
58
- readonly compiles: number;
59
- /** Items it worked on, by the records' subjects. */
60
- readonly items: number;
61
- }
62
-
63
- export interface StepView {
64
- readonly name: string;
65
- /** How it runs (`StepRuns`); none for a sub-workflow step, and for one no longer declared that no agent ran. */
66
- readonly runs: StepRuns | null;
67
- readonly description: string;
68
- readonly source: SourceLink;
69
- /** Whether its declaration lists it; a step only the records name is no longer declared. */
70
- readonly declared: boolean;
71
- readonly cost: StepCost | null;
72
- /** How its records in the window ended and why (`reasons.ts`), commonest first, the rest added up as one. */
73
- readonly endings: ReadonlyArray<StepEnding>;
74
- }
75
-
76
- /** How many of a step's records ended one way, for one reason. */
77
- export interface StepEnding {
78
- readonly outcome: string;
79
- readonly reason: string;
80
- readonly records: number;
81
- }
82
-
83
- /** What a workflow's runs gave over a window: items finished, and per run, per million tokens and per compile. */
84
- export interface Yield {
85
- readonly runs: number;
86
- readonly finished: number;
87
- readonly tokens: number;
88
- readonly compiles: number;
89
- /** None where it had no run, token or compile to divide by. */
90
- readonly perRun: number | null;
91
- readonly perMillionTokens: number | null;
92
- readonly perCompile: number | null;
93
- }
94
-
95
- /** What a run of a workflow costs, from its ended runs in the window. */
96
- export interface RunCosts {
97
- /** Its runs that ended in the window. */
98
- readonly runs: number;
99
- /** The median run's cost, figure by figure; none with no run. */
100
- readonly median: { readonly seconds: number; readonly tokens: number; readonly cpuSeconds: number; readonly childCpuSeconds: number; readonly compiles: number } | null;
101
- /** Its costliest run by CPU, its processes' included. */
102
- readonly costliest: Pick<RunCost, 'run' | 'started' | 'seconds' | 'tokens' | 'cpuSeconds' | 'compiles'> | null;
103
- }
104
-
105
- const medianOf = (xs: ReadonlyArray<number>): number => {
106
- const sorted = [...xs].sort((a, b) => a - b);
107
- const mid = Math.floor(sorted.length / 2);
108
- return sorted.length % 2 === 1 ? sorted[mid]! : (sorted[mid - 1]! + sorted[mid]!) / 2;
109
- };
110
-
111
- /** A workflow's ended runs as their costs: the median run, figure by figure, and the costliest. Pure. */
112
- export const runCostsOf = (costs: ReadonlyArray<RunCost>): RunCosts => {
113
- const ended = costs.filter((c) => !c.going);
114
- if (ended.length === 0) return { runs: 0, median: null, costliest: null };
115
- const costliest = ended.reduce((a, b) => (b.cpuSeconds > a.cpuSeconds ? b : a));
116
- return {
117
- runs: ended.length,
118
- median: {
119
- seconds: medianOf(ended.map((c) => c.seconds)), tokens: medianOf(ended.map((c) => c.tokens)), cpuSeconds: medianOf(ended.map((c) => c.cpuSeconds)),
120
- childCpuSeconds: medianOf(ended.map((c) => c.childCpuSeconds)), compiles: medianOf(ended.map((c) => c.compiles)),
121
- },
122
- costliest: { run: costliest.run, started: costliest.started, seconds: costliest.seconds, tokens: costliest.tokens, cpuSeconds: costliest.cpuSeconds, compiles: costliest.compiles },
123
- };
124
- };
125
-
126
- /** Endings listed per step; the rest are added up as one. */
127
- export const ENDINGS_LISTED = 4;
128
-
129
- /** A step's records as their endings, commonest first. Pure. */
130
- export const endingsOf = (records: ReadonlyArray<Pick<FunnelStepRecord, 'outcome' | 'reason'>>): ReadonlyArray<StepEnding> => {
131
- const counts = new Map<string, StepEnding>();
132
- for (const r of records) {
133
- const outcome = r.outcome ?? 'going';
134
- const reason = r.reason ?? (r.outcome === null ? 'still going' : 'no reason recorded');
135
- const key = `${outcome}\u0000${reason}`;
136
- const was = counts.get(key);
137
- counts.set(key, { outcome, reason, records: (was?.records ?? 0) + 1 });
138
- }
139
- const all = [...counts.values()].sort((a, b) => b.records - a.records || a.reason.localeCompare(b.reason));
140
- const rest = all.slice(ENDINGS_LISTED).reduce((n, e) => n + e.records, 0);
141
- return [...all.slice(0, ENDINGS_LISTED), ...(rest === 0 ? [] : [{ outcome: 'other', reason: `${all.length - ENDINGS_LISTED} other endings`, records: rest }])];
142
- };
143
-
144
- /** A window's yield from its counts. Pure. */
145
- export const yieldOf = (r: { readonly runs: number; readonly finished: number; readonly tokens: number; readonly compiles: number }): Yield => ({
146
- ...r,
147
- perRun: r.runs === 0 ? null : r.finished / r.runs,
148
- perMillionTokens: r.tokens === 0 ? null : (r.finished * 1_000_000) / r.tokens,
149
- perCompile: r.compiles === 0 ? null : r.finished / r.compiles,
150
- });
151
-
152
- /**
153
- * A step as a workflow's own view lists it: its kind in words (`steps.ts` `StepKind`), and for a sub-workflow the workflow
154
- * it opens.
155
- */
156
- export interface StepSummary {
157
- readonly name: string;
158
- readonly kind: StepKind;
159
- /** How it runs; none for a sub-workflow step, whose own steps say theirs. */
160
- readonly runs: StepRuns | null;
161
- readonly description: string;
162
- /** For a sub-workflow: the workflow it runs, by name; none for any other kind. */
163
- readonly workflow: string | null;
164
- }
165
-
166
- /**
167
- * THE TOP OF A PROJECT IS ONE WORKFLOW (Alex, 2026-11-19: "decompiling an entire game is in itself a workflow"): what a page
168
- * enters at. Its steps are sub-workflows, and each opens that workflow's own view.
169
- */
170
- export interface TopWorkflowView {
171
- readonly name: string;
172
- readonly description: string;
173
- readonly steps: ReadonlyArray<StepSummary>;
174
- }
175
-
176
- /** A workflow as a page shows it before it is opened: what it is, its steps, its limits and its queue. */
177
- export interface WorkflowView {
178
- readonly name: string;
179
- /** Its own steps, in order, each with its kind. */
180
- readonly steps: ReadonlyArray<StepSummary>;
181
- readonly phase: string;
182
- readonly description: string;
183
- readonly source: SourceLink;
184
- /** Its word for one item, none where it works on no single item. */
185
- readonly item: string | null;
186
- readonly finishedWord: string | null;
187
- readonly usesAgents: boolean;
188
- /**
189
- * Its limits: how many runs of it may go at once (`runs`, none for no limit; `runsSet` false where that is the default),
190
- * and, for a workflow its budget keeps going, how many of its runs may be in an agent step at once (`agents`, none for
191
- * any other). None where no store is read.
192
- */
193
- readonly limits: { readonly agents: number | null; readonly runs: number | null; readonly runsSet: boolean } | null;
194
- /** Its tasks by status, as last counted (`queue-counts.ts`); none for a workflow with no item. */
195
- readonly queue: Readonly<Record<TaskStatus, number>> | null;
196
- /**
197
- * How many of its queued tasks are marked as needing an agent, as last counted (`queue-counts.ts`, `QUEUED_NEEDING_AN_AGENT`);
198
- * none for a workflow with no item or no agent step, where no task can be marked.
199
- */
200
- readonly queuedNeedingAnAgent: number | null;
201
- /** Its place among the project's workflows: what the map lays it out by (`workflow-flows.ts`). */
202
- readonly place: PipelinePlace;
203
- /** What starts its runs. */
204
- readonly startsOn: StartsOn;
205
- }
206
-
207
- /** Every workflow, read at the request: nothing here is stored for the page. */
208
- export interface WorkflowsView {
209
- /** When it was read, unix seconds. */
210
- readonly at: number;
211
- readonly top: TopWorkflowView;
212
- readonly groups: ReadonlyArray<{ readonly phase: string; readonly workflows: ReadonlyArray<WorkflowView> }>;
213
- /** Each queue's counts by status over the last `QUEUE_HISTORY_DAYS` (`historyByStatus`), a row where one changed, oldest first. */
214
- readonly queueHistory: ReadonlyArray<QueueCount>;
215
- /** Where work goes between the top workflow's steps: the map's arrows (`workflow-flows.ts`). */
216
- readonly flows: ReadonlyArray<WorkflowFlow>;
217
- /** The spending limit against the newest reading of the week (`spending-limit.ts`); none for a project that reads no week. */
218
- readonly spending: SpendingLimitState | null;
219
- }
220
-
221
- /** One workflow's figures over a window, read from its own records when it is opened. */
222
- export interface WorkflowFigures {
223
- readonly workflow: string;
224
- /** When it was read, unix seconds, and the window: the `hours` before it. */
225
- readonly at: number;
226
- readonly hours: number;
227
- readonly since: number;
228
- readonly steps: ReadonlyArray<StepView>;
229
- /** Its steps' costs added up. */
230
- readonly total: StepCost;
231
- readonly graph: WorkflowGraph;
232
- readonly funnel: StepFunnel;
233
- /** What a run of it costs, its processes included. */
234
- readonly runCosts: RunCosts;
235
- /** What its runs gave in the window, and in the window before it: the trend. */
236
- readonly yields: { readonly now: Yield; readonly before: Yield };
237
- /** Why its blocked tasks are blocked now: a count for each reason, most tasks first (`tasks.ts` `blockedReasons`). */
238
- readonly blocked: ReadonlyArray<BlockedReason>;
239
- /**
240
- * Its queued tasks marked as needing an agent, a count for each reason (`tasks.ts` `needsAgentReasons`), and whether its
241
- * Pick passes over them now because no agent can be had, with why in words; none while one can.
242
- */
243
- readonly needingAnAgent: { readonly reasons: ReadonlyArray<BlockedReason>; readonly passedOverBecause: string | null };
244
- }
245
-
246
- const NO_COST: StepCost = { calls: 0, failed: 0, open: 0, seconds: 0, inputTokens: 0, outputTokens: 0, cpuSeconds: 0, compiles: 0, items: 0 };
247
-
248
- const addCosts = (a: StepCost, b: StepCost): StepCost => ({
249
- calls: a.calls + b.calls, failed: a.failed + b.failed, open: a.open + b.open, seconds: a.seconds + b.seconds,
250
- inputTokens: a.inputTokens + b.inputTokens, outputTokens: a.outputTokens + b.outputTokens, cpuSeconds: a.cpuSeconds + b.cpuSeconds,
251
- compiles: a.compiles + b.compiles, items: a.items + b.items,
252
- });
253
-
254
- /** One step's rows (one per run, step and subject) as its cost. Pure. */
255
- export const costOf = (rows: ReadonlyArray<StepRunRow>): StepCost | null =>
256
- rows.length === 0 ? null : {
257
- calls: rows.reduce((n, r) => n + r.calls, 0),
258
- failed: rows.reduce((n, r) => n + r.failed, 0),
259
- open: rows.reduce((n, r) => n + r.open, 0),
260
- seconds: rows.reduce((n, r) => n + r.ms, 0) / 1000,
261
- inputTokens: rows.reduce((n, r) => n + (r.fresh ?? 0) + (r.cache_write ?? 0) + (r.cache_read ?? 0), 0),
262
- outputTokens: rows.reduce((n, r) => n + (r.output ?? 0), 0),
263
- cpuSeconds: rows.reduce((n, r) => n + r.cpu_seconds, 0),
264
- compiles: rows.reduce((n, r) => n + (r.compiles ?? 0), 0),
265
- items: new Set(rows.flatMap((r) => (r.subject === null ? [] : [r.subject.toLowerCase()]))).size,
266
- };
267
-
268
- type Declared = Pick<WorkflowDeclaration<string, unknown>, 'name' | 'phase' | 'description' | 'source' | 'item' | 'finishedWord' | 'graph' | 'fedBy' | 'pending' | 'items' | 'inputs'> & {
269
- readonly steps: () => ReadonlyArray<StepDeclaration>;
270
- };
271
-
272
- const noTasks = (): Record<TaskStatus, number> => Object.fromEntries(TASK_STATUSES.map((s) => [s, 0])) as Record<TaskStatus, number>;
273
-
274
- /**
275
- * The names a count was recorded under before 2026-11-19, when a task stood in one of six buckets, and the status each is
276
- * part of now. `queued` and `done` kept their names.
277
- */
278
- const RECORDED_BEFORE: Readonly<Record<string, TaskStatus>> = { running: 'in progress', waiting: 'blocked', stuck: 'blocked', held: 'blocked' };
279
-
280
- /**
281
- * THE RECORDED COUNTS (`queueCountsSince`, oldest first) AS THE FOUR STATUSES: a row for each status of each workflow where
282
- * its count moved. A count recorded under an older name is part of its status until the workflow has a count under the
283
- * four, which replaces it; one recorded under an older name after that (by code still running as the newer began) is
284
- * not read. Pure.
285
- */
286
- export const historyByStatus = (recorded: ReadonlyArray<QueueCount>): ReadonlyArray<QueueCount> => {
287
- const raw = new Map<string, Map<string, number>>();
288
- const countedByStatus = new Set<string>();
289
- const last = new Map<string, number>();
290
- const out: QueueCount[] = [];
291
- recorded.forEach((row, i) => {
292
- const counts = raw.get(row.workflow) ?? new Map<string, number>();
293
- raw.set(row.workflow, counts);
294
- const olderName = RECORDED_BEFORE[row.bucket] !== undefined;
295
- if (!olderName && (row.bucket === 'in progress' || row.bucket === 'blocked') && !countedByStatus.has(row.workflow)) {
296
- countedByStatus.add(row.workflow);
297
- for (const older of Object.keys(RECORDED_BEFORE)) counts.delete(older);
298
- }
299
- if (!(olderName && countedByStatus.has(row.workflow))) counts.set(row.bucket, row.tasks);
300
- // Every row of one moment is one count of the workflow: its statuses are read once all of them are in.
301
- const next = recorded[i + 1];
302
- if (next !== undefined && next.workflow === row.workflow && next.at === row.at) return;
303
- for (const status of TASK_STATUSES) {
304
- const tasks = [...counts].reduce((sum, [name, n]) => sum + (name === status || RECORDED_BEFORE[name] === status ? n : 0), 0);
305
- const key = `${row.workflow}\u0000${status}`;
306
- if (last.get(key) !== tasks) out.push({ at: row.at, workflow: row.workflow, bucket: status, tasks });
307
- last.set(key, tasks);
308
- }
309
- });
310
- return out;
311
- };
312
-
313
- /** Each queue's newest count of queued tasks marked as needing an agent, from the recorded counts (oldest first). Pure. */
314
- export const queuedNeedingAnAgentNow = (recorded: ReadonlyArray<QueueCount>): ReadonlyMap<string, number> =>
315
- new Map(recorded.filter((row) => row.bucket === QUEUED_NEEDING_AN_AGENT).map((row) => [row.workflow, row.tasks]));
316
-
317
- /** Each queue's newest count from its history by status (`historyByStatus`), a status never counted at 0. Pure. */
318
- export const queuesNow = (history: ReadonlyArray<QueueCount>): ReadonlyMap<string, Readonly<Record<TaskStatus, number>>> => {
319
- const queues = new Map<string, Record<TaskStatus, number>>();
320
- for (const row of history) {
321
- const queue = queues.get(row.workflow) ?? noTasks();
322
- if ((TASK_STATUSES as ReadonlyArray<string>).includes(row.bucket)) queue[row.bucket as TaskStatus] = row.tasks;
323
- queues.set(row.workflow, queue);
324
- }
325
- return queues;
326
- };
327
-
328
- /**
329
- * EVERY WORKFLOW AS A PAGE SHOWS IT BEFORE ONE IS OPENED, READ AT THE REQUEST: the declarations, the limits, each queue's
330
- * counts as last counted and their history. A few small readings of the store, so a
331
- * page load needs no stored copy of it. `limitsOf` is none where no store is read.
332
- */
333
- export const buildWorkflowsView = (input: {
334
- readonly declared: ReadonlyArray<Declared>;
335
- /** The project's phases, in the order its page shows them; a workflow of another phase follows them. */
336
- readonly phases: ReadonlyArray<string>;
337
- readonly now: number;
338
- /** The queues' history, from the task store. */
339
- readonly taskStore: Pick<TaskStore, 'queueCountsSince' | 'returnedBetween' | 'listedWaits'>;
340
- /** The line a definition's text is on now. */
341
- readonly locate: (source: SourceRef) => number | null;
342
- readonly limitsOf: (workflow: string) => WorkflowView['limits'];
343
- /** The project's top workflow, in its own words, until it declares one. */
344
- readonly top: { readonly name: string; readonly description: string };
345
- readonly spending: SpendingLimitState | null;
346
- }): Effect.Effect<WorkflowsView, StorageError> => Effect.gen(function* () {
347
- const stepSummary = (s: StepDeclaration): StepSummary => ({ name: s.name, kind: stepKindOf(s), runs: s.runs, description: s.description, workflow: s.workflow ?? null });
348
- // Until the project declares its top workflow, its steps are every workflow no other workflow uses as a step.
349
- const usedAsAStep = new Set(input.declared.flatMap((d) => d.steps().flatMap((s) => (s.workflow === undefined ? [] : [s.workflow]))));
350
- const phases = [...input.phases, ...[...new Set(input.declared.map((d) => d.phase))].filter((p) => !input.phases.includes(p))];
351
- const recordedCounts = yield* input.taskStore.queueCountsSince(input.now - QUEUE_HISTORY_DAYS * 86_400);
352
- const queueHistory = historyByStatus(recordedCounts);
353
- const queues = queuesNow(queueHistory);
354
- const needingAnAgent = queuedNeedingAnAgentNow(recordedCounts);
355
- // The map is of the top workflow's steps: a workflow used as a step of another is drawn inside that one, not here.
356
- const onTheMap = input.declared.filter((d) => !usedAsAStep.has(d.name));
357
- const flows = workflowFlows({ declared: onTheMap, returned: yield* input.taskStore.returnedBetween(), waits: yield* input.taskStore.listedWaits() });
358
- const places = new Map(pipelinePlaces({ workflows: input.declared.map((d) => ({ name: d.name, stage: d.phase })), stages: phases, flows }).map((p) => [p.workflow, p]));
359
- const workflowView = (d: Declared): WorkflowView => ({
360
- name: d.name, steps: d.steps().map(stepSummary),
361
- phase: d.phase, description: d.description, source: { ...d.source, line: input.locate(d.source) }, item: d.item, finishedWord: d.finishedWord,
362
- usesAgents: d.steps().some(stepUsesAnAgent),
363
- // A workflow used as a step has no limit of its own to show: its starts are its parent's steps (`defineSubWorkflow`).
364
- limits: usedAsAStep.has(d.name) ? null : input.limitsOf(d.name),
365
- place: places.get(d.name)!,
366
- queue: d.item === null ? null : queues.get(d.name) ?? noTasks(),
367
- queuedNeedingAnAgent: d.item === null || !d.steps().some(stepUsesAnAgent) ? null : needingAnAgent.get(d.name) ?? 0,
368
- startsOn: usedAsAStep.has(d.name) ? { kind: 'a step', of: input.declared.filter((p) => p.steps().some((s) => s.workflow === d.name)).map((p) => p.name) }
369
- : d.pending !== undefined || d.items !== undefined ? { kind: 'queue' } : d.inputs !== undefined ? { kind: 'inputs', says: d.inputs.says } : { kind: 'timer or request' },
370
- });
371
- const inPageOrder = phases.flatMap((phase) => input.declared.filter((d) => d.phase === phase));
372
- return {
373
- at: input.now,
374
- top: {
375
- ...input.top,
376
- steps: inPageOrder.filter((d) => !usedAsAStep.has(d.name)).map((d): StepSummary => ({ name: d.name, kind: 'sub-workflow', runs: null, description: d.description, workflow: d.name })),
377
- },
378
- groups: phases.map((phase) => ({ phase, workflows: input.declared.filter((d) => d.phase === phase).map(workflowView) })).filter((g) => g.workflows.length > 0),
379
- queueHistory,
380
- flows,
381
- spending: input.spending,
382
- };
383
- });
384
-
385
- /**
386
- * ONE WORKFLOW'S FIGURES OVER THE `hours` BEFORE `now`, READ FROM ITS OWN RECORDS when a page opens it: each step's cost and
387
- * endings, its step graph with the runs on each edge, where its runs stopped, what a run costs, and what its runs gave
388
- * against the window before.
389
- */
390
- export const buildWorkflowFigures = (input: {
391
- readonly declaration: Declared;
392
- readonly now: number;
393
- readonly hours: number;
394
- readonly records: StepRecords;
395
- readonly engine: EngineRecords;
396
- /** Why its blocked tasks are blocked now, and its queued tasks marked as needing an agent, read from its tasks. */
397
- readonly reasons: Effect.Effect<Pick<WorkflowFigures, 'blocked' | 'needingAnAgent'>, StorageError>;
398
- /** The line a definition's text is on now. */
399
- readonly locate: (source: SourceRef) => number | null;
400
- }): Effect.Effect<WorkflowFigures, StorageError> => Effect.gen(function* () {
401
- const d = input.declaration;
402
- const since = input.now - input.hours * 3600;
403
- const before = since - input.hours * 3600;
404
- const own = yield* input.records.stepRunsSince(since, d.name);
405
- // The window before, for the trend: its records are those since its start, less the window's own.
406
- const ownBoth = yield* input.records.stepRunsSince(before, d.name);
407
- const funnelRecords = yield* input.records.funnelRecordsSince(since, d.name);
408
- const funnelBoth = yield* input.records.funnelRecordsSince(before, d.name);
409
- const finishedNow = yield* input.records.runOutcomesSince(since, d.name);
410
- const finishedBoth = yield* input.records.runOutcomesSince(before, d.name);
411
- const runCosts = yield* input.records.runCostsSince(since, d.name);
412
- const moves = yield* input.records.stepEdgesSince(since, d.name);
413
- const going = new Set((yield* input.engine.unfinishedRuns()).map((u) => u.run));
414
- const link = (s: SourceRef): SourceLink => ({ ...s, line: input.locate(s) });
415
-
416
- const declaredSteps = d.steps();
417
- const onlyInRecords = [...new Set(own.map((r) => r.step))].filter((s) => !declaredSteps.some((x) => x.name === s));
418
- const steps: ReadonlyArray<StepView> = [
419
- ...declaredSteps.map((s) => ({ name: s.name, runs: s.runs, description: s.description, source: link(s.source), declared: true, cost: costOf(own.filter((r) => r.step === s.name)), endings: endingsOf(funnelRecords.records.filter((r) => r.step === s.name)) })),
420
- ...onlyInRecords.map((name) => ({ name, runs: own.some((r) => r.step === name && r.agent === 1) ? 'agentic' as const : null, description: 'no longer declared', source: link(d.source), declared: false, cost: costOf(own.filter((r) => r.step === name)), endings: endingsOf(funnelRecords.records.filter((r) => r.step === name)) })),
421
- ];
422
- const funnel = stepFunnel({ declaration: d, records: funnelRecords.records, outcomes: funnelRecords.outcomes, unfinished: going, hours: input.hours, since, now: input.now });
423
- const funnelBefore = stepFunnel({ declaration: d, records: funnelBoth.records, outcomes: funnelBoth.outcomes, unfinished: going, hours: input.hours, since: before, now: since });
424
- const costNow = costOf(own) ?? NO_COST;
425
- const costBoth = costOf(ownBoth) ?? NO_COST;
426
- const finished = (outcomes: ReadonlyArray<RunOutcomeRow>) => outcomes.filter((o) => o.finished === 1).length;
427
- return {
428
- workflow: d.name, at: input.now, hours: input.hours, since,
429
- steps,
430
- total: steps.reduce((t, s) => (s.cost === null ? t : addCosts(t, s.cost)), NO_COST),
431
- graph: workflowGraphs({ declared: [d], taken: moves.edges, lasts: moves.lasts, going })[0]!,
432
- funnel,
433
- runCosts: runCostsOf(runCosts),
434
- ...(yield* input.reasons),
435
- yields: {
436
- now: yieldOf({ runs: funnel.runs, finished: finished(finishedNow), tokens: costNow.inputTokens + costNow.outputTokens, compiles: costNow.compiles }),
437
- before: yieldOf({
438
- runs: funnelBefore.runs, finished: finished(finishedBoth) - finished(finishedNow),
439
- tokens: costBoth.inputTokens + costBoth.outputTokens - (costNow.inputTokens + costNow.outputTokens), compiles: costBoth.compiles - costNow.compiles,
440
- }),
441
- },
442
- };
443
- });