@jive-sh/workflow-platform 0.6.3 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +182 -42
  2. package/dist/budget-states.js +1 -1
  3. package/dist/budget-states.js.map +1 -1
  4. package/dist/dashboard/dashboard.css +42 -28
  5. package/dist/dashboard/drilldown.js +35 -4
  6. package/dist/dashboard/drilldown.js.map +1 -1
  7. package/dist/dashboard/run-doing-words.js +29 -0
  8. package/dist/dashboard/run-doing-words.js.map +1 -0
  9. package/dist/dashboard/setting-words.js +18 -0
  10. package/dist/dashboard/setting-words.js.map +1 -0
  11. package/dist/dashboard/spending-words.js +2 -10
  12. package/dist/dashboard/spending-words.js.map +1 -1
  13. package/dist/index.js +76 -13
  14. package/dist/index.js.map +1 -1
  15. package/dist/keep-running.js +4 -2
  16. package/dist/keep-running.js.map +1 -1
  17. package/dist/pick-wakes.js +2 -2
  18. package/dist/retention.js +59 -0
  19. package/dist/retention.js.map +1 -0
  20. package/dist/settings.js +88 -0
  21. package/dist/settings.js.map +1 -0
  22. package/dist/spending-limit.js +15 -21
  23. package/dist/spending-limit.js.map +1 -1
  24. package/dist/step-times.js +114 -0
  25. package/dist/step-times.js.map +1 -0
  26. package/dist/steps.js +399 -114
  27. package/dist/steps.js.map +1 -1
  28. package/dist/storage/agent-claims.js +3 -0
  29. package/dist/storage/agent-claims.js.map +1 -0
  30. package/dist/storage/budgets.js +40 -4
  31. package/dist/storage/budgets.js.map +1 -1
  32. package/dist/storage/engine-records.js +26 -10
  33. package/dist/storage/engine-records.js.map +1 -1
  34. package/dist/storage/sqlite-store.js +198 -20
  35. package/dist/storage/sqlite-store.js.map +1 -1
  36. package/dist/storage/task-store.js +11 -5
  37. package/dist/storage/task-store.js.map +1 -1
  38. package/dist/system-workflows.js +54 -0
  39. package/dist/system-workflows.js.map +1 -0
  40. package/dist/tasks.js +49 -24
  41. package/dist/tasks.js.map +1 -1
  42. package/dist/views/runs-now.js +80 -38
  43. package/dist/views/runs-now.js.map +1 -1
  44. package/dist/views/step-graph.js +6 -1
  45. package/dist/views/step-graph.js.map +1 -1
  46. package/dist/views/workflows-view.js +29 -23
  47. package/dist/views/workflows-view.js.map +1 -1
  48. package/package.json +1 -1
  49. package/src/budget-states.ts +2 -3
  50. package/src/dashboard/dashboard.css +42 -28
  51. package/src/dashboard/drilldown.ts +32 -5
  52. package/src/dashboard/index.tsx +1 -1
  53. package/src/dashboard/limits-and-runs.tsx +191 -0
  54. package/src/dashboard/queue-bar.tsx +30 -11
  55. package/src/dashboard/queue-chart.tsx +1 -2
  56. package/src/dashboard/run-doing-words.ts +41 -0
  57. package/src/dashboard/setting-words.ts +30 -0
  58. package/src/dashboard/spending-limit-control.tsx +5 -8
  59. package/src/dashboard/spending-words.ts +5 -23
  60. package/src/dashboard/time-distribution.tsx +61 -0
  61. package/src/dashboard/workflow-dag.tsx +247 -129
  62. package/src/dashboard/workflow-drilldown.tsx +13 -71
  63. package/src/dashboard/workflows-dashboard.tsx +345 -227
  64. package/src/index.ts +86 -16
  65. package/src/keep-running.ts +6 -4
  66. package/src/pick-wakes.ts +2 -2
  67. package/src/project.ts +12 -0
  68. package/src/retention.ts +90 -0
  69. package/src/settings.ts +171 -0
  70. package/src/spending-limit.ts +25 -42
  71. package/src/step-times.ts +151 -0
  72. package/src/steps.ts +512 -135
  73. package/src/storage/agent-claims.ts +63 -0
  74. package/src/storage/budgets.ts +43 -4
  75. package/src/storage/engine-records.ts +28 -11
  76. package/src/storage/sqlite-store.ts +225 -32
  77. package/src/storage/step-records.ts +59 -7
  78. package/src/storage/task-store.ts +29 -29
  79. package/src/system-workflows.ts +70 -0
  80. package/src/tasks.ts +49 -24
  81. package/src/views/runs-now.ts +119 -51
  82. package/src/views/step-graph.ts +11 -2
  83. package/src/views/workflows-view.ts +80 -39
  84. package/src/workflow-dag.test.tsx +89 -0
  85. package/src/workflow-page.test.tsx +170 -0
  86. package/dist/views/workflow-flows.js +0 -53
  87. package/dist/views/workflow-flows.js.map +0 -1
  88. package/src/dashboard/step-graph.tsx +0 -106
  89. package/src/views/workflow-flows.ts +0 -97
@@ -209,6 +209,15 @@ export interface StepEdgeTaken {
209
209
  readonly runs: number;
210
210
  }
211
211
 
212
+ /**
213
+ * WHICH RECORDS RETENTION DELETES IN ONE CALL (`retention.ts`): one step's of a workflow, a workflow's other steps' (those no
214
+ * longer declared included), or those of every workflow not named (none declared now).
215
+ */
216
+ export type RecordsSelection =
217
+ | { readonly workflow: string; readonly step: string }
218
+ | { readonly workflow: string; readonly stepsOtherThan: ReadonlyArray<string> }
219
+ | { readonly workflowsOtherThan: ReadonlyArray<string> };
220
+
212
221
  /** A run's last step so far, for its runs that worked in the window. */
213
222
  export interface LastStepNow {
214
223
  readonly workflow: string;
@@ -222,13 +231,17 @@ export interface StepRecords {
222
231
  /**
223
232
  * Opens a step's record. It works on what `subject` names, else on what the run last worked on, else on what the run
224
233
  * that started it as a sub-workflow works on. `resume`: the run's open record of this step and call is taken up again
225
- * where there is one (a sub-workflow step, run again when its workflow has ended). Null where nothing is written.
234
+ * where there is one (a sub-workflow step, run again when its workflow has ended). `version` is its workflow's version now
235
+ * (`steps.ts` `versionOf`); the record takes its run's, the version on the run's first record, so a run resumed under newer
236
+ * code keeps the version it started on. Null where nothing is written.
226
237
  */
227
- readonly openStepRun: (r: { readonly workflow: string; readonly run: string; readonly step: string; readonly call: number | null; readonly agent: boolean; readonly subject: string | null; readonly resume?: true }) => Effect.Effect<number | null, StorageError>;
238
+ readonly openStepRun: (r: { readonly workflow: string; readonly run: string; readonly step: string; readonly call: number | null; readonly agent: boolean; readonly subject: string | null; readonly version: string; readonly resume?: true }) => Effect.Effect<number | null, StorageError>;
228
239
  /** The run a sub-workflow step started, on that step's open record: what ties a run to the run above it. */
229
240
  readonly setStepChild: (r: { readonly id: number; readonly childRun: string }) => Effect.Effect<void, StorageError>;
230
241
  /** The run at the top of the runs that started this one as a sub-workflow, with its workflow; none for a run nothing started so. */
231
242
  readonly rootOfRun: (run: string) => Effect.Effect<{ readonly run: string; readonly workflow: string } | null, StorageError>;
243
+ /** The run whose sub-workflow step started this one, with its workflow and that step's name; none for a run nothing started so. */
244
+ readonly parentOfRun: (run: string) => Effect.Effect<{ readonly run: string; readonly workflow: string; readonly step: string } | null, StorageError>;
232
245
  readonly beatStepRun: (id: number) => Effect.Effect<void, StorageError>;
233
246
  /** What an agent step has spent so far, on its open record, as each usage arrives. */
234
247
  readonly updateStepSpend: (r: { readonly id: number; readonly spend: StepSpend; readonly model: string | null }) => Effect.Effect<void, StorageError>;
@@ -253,17 +266,19 @@ export interface StepRecords {
253
266
  * owners were kept is closed only if it was opened before `serviceStartedAt`. Returns how many it closed.
254
267
  */
255
268
  readonly closeStepRunsLeftOpen: (serviceStartedAt: number) => Effect.Effect<number, StorageError>;
269
+ /**
270
+ * DELETES THE RECORDS `select` NAMES OF RUNS THAT ENDED BEFORE `before`, each batch record's parts with it: a record goes
271
+ * once every record of its run has ended before then, its run is none of `keepRuns` (the engine's runs not finished),
272
+ * and it is not of one of the `keepNewest` newest runs of its step (by when each started there), however old: a project that
273
+ * finished or stalled keeps each step's last runs. Retention's one delete (`retention.ts`). How many records and parts went.
274
+ */
275
+ readonly deleteRecordsOfRunsEndedBefore: (r: { readonly select: RecordsSelection; readonly before: number; readonly keepRuns: ReadonlyArray<string>; readonly keepNewest: number }) => Effect.Effect<{ readonly records: number; readonly parts: number }, StorageError>;
256
276
 
257
277
  // ------------------------------------------------------------------ read
258
278
  /** The file record of a run's newest try at a step. */
259
279
  readonly stepFilesOf: (r: { readonly run: string; readonly step: string }) => Effect.Effect<string | null, StorageError>;
260
280
  /** The step a run did last, and whether it failed; none before its first. A step a restart interrupted is not one. */
261
281
  readonly lastStepOf: (run: string) => Effect.Effect<{ readonly step: string; readonly failed: boolean; readonly owner: ProcessIdentity | null } | null, StorageError>;
262
- /**
263
- * The runs of a workflow an agent works for now: each with an agent step's record open and not waiting, its own or that
264
- * of a run under it (one a sub-workflow step of it started, at any depth). The agents it has in use.
265
- */
266
- readonly runsInAgentStep: (workflow: string) => Effect.Effect<ReadonlyArray<string>, StorageError>;
267
282
  /** The step a run is on now, and what it works on. */
268
283
  readonly stepOfRun: (run: string) => Effect.Effect<{ readonly step: string; readonly subject: string | null; readonly started: number } | null, StorageError>;
269
284
  /** The run's newest named item. */
@@ -303,4 +318,41 @@ export interface StepRecords {
303
318
  readonly newestCallsByItem: (r: { readonly workflow: string; readonly steps: ReadonlyArray<string> }) => Effect.Effect<ReadonlyArray<{ readonly subject: string; readonly run: string; readonly activity: string; readonly ended: number }>, StorageError>;
304
319
  /** Every step-to-step move in the window, by workflow, and each run's last step. Interrupted records are not moves. */
305
320
  readonly stepEdgesSince: (since: number, workflow?: string) => Effect.Effect<{ readonly edges: ReadonlyArray<StepEdgeTaken>; readonly lasts: ReadonlyArray<LastStepNow> }, StorageError>;
321
+ // ------------------------------------------------------------------ read for each step's time distribution (`step-times.ts`)
322
+ /**
323
+ * Every record of one version of a workflow up to `newestId`, the newest record of any when it was read, through their
324
+ * index (`step_runs_by_version`), with each batch record's parts: `recordsSince` reads on from `newestId`, so none is missed.
325
+ */
326
+ readonly versionRecords: (r: { readonly workflow: string; readonly version: string }) => Effect.Effect<TimedRecords & { readonly newestId: number }, StorageError>;
327
+ /** Every record written after record `after` (by id, so only new ones are read), and these records again by id, with parts. */
328
+ readonly recordsSince: (r: { readonly after: number; readonly again: ReadonlyArray<number> }) => Effect.Effect<TimedRecords, StorageError>;
329
+ /** The version of a workflow other than `version` whose newest record is newest, and when that was; none where it has none. */
330
+ readonly previousVersion: (r: { readonly workflow: string; readonly version: string }) => Effect.Effect<{ readonly version: string; readonly at: number } | null, StorageError>;
331
+ }
332
+
333
+ /** A step record as its time distribution reads it. */
334
+ export interface TimedRecord {
335
+ readonly id: number;
336
+ readonly workflow: string;
337
+ readonly version: string | null;
338
+ readonly run: string;
339
+ readonly step: string;
340
+ readonly subject: string | null;
341
+ readonly started: number;
342
+ readonly ended: number | null;
343
+ /** 'functions' for a batch record, whose items' parts are its `TimedPart`s. */
344
+ readonly scope: string | null;
345
+ }
346
+
347
+ /** One item's part of a batch record (`step_functions`). */
348
+ export interface TimedPart {
349
+ readonly stepRun: number;
350
+ readonly subject: string;
351
+ readonly started: number;
352
+ readonly ended: number | null;
353
+ }
354
+
355
+ export interface TimedRecords {
356
+ readonly records: ReadonlyArray<TimedRecord>;
357
+ readonly parts: ReadonlyArray<TimedPart>;
306
358
  }
@@ -77,13 +77,17 @@ export type Listed =
77
77
  export type NotedStatus = 'queued' | 'blocked' | 'done' | 'removed';
78
78
 
79
79
  /**
80
- * THE KIND THE ENGINE WRITES WHEN A RUN ENDS AT AN AGENT STEP NO AGENT CAN BE HAD FOR (`steps.ts` `untilAgentSlot`): its task
81
- * goes to the back of its queue, marked as needing an agent, with why in words. Alex, 2026-11-20: "if a workflow run is
82
- * paused because it needs an agent it should probably go to the back of the queue and the task gets marked for needing an
83
- * agent such that the workflow dequeuing logic can skip over functions which need an agent when the agentic budget is zero."
80
+ * THE KIND THE ENGINE WRITES WHEN A RUN ON A TASK FINDS NO AGENT IT CAN CLAIM (`steps.ts` `claimAgentsOrEnd`), or holds one
81
+ * while the agents can no longer be had (`beforeAgentCall`): its task goes to the back of its queue, marked as needing an
82
+ * agent, with why in words, and the run ends. Alex, 2026-11-20: "if a workflow run is paused because it needs an agent it
83
+ * should probably go to the back of the queue and the task gets marked for needing an agent such that the workflow
84
+ * dequeuing logic can skip over functions which need an agent when the agentic budget is zero." And 2026-11-21, of runs
85
+ * waiting for agents in use: "we mark the task as needing an agent and put it back so the next one can start."
84
86
  */
85
87
  export const NEEDS_AN_AGENT = 'needs an agent';
86
- /** The kind the engine writes on a marked task after an agent step ran on it: it may need no agent now, so the mark clears. */
88
+ /** The kind the engine writes on a marked task once a run on it took an agent: its mark has done its work, so it clears. */
89
+ export const AGENT_TAKEN = 'a run took an agent for it';
90
+ /** What cleared a mark until 2026-11-22, when an agent took an agent step rather than a run claiming one: read on old notes. */
87
91
  export const AGENT_STEP_RAN = 'an agent step ran';
88
92
 
89
93
  /** The note kinds a status is read from, and what each leaves a task as. A run that stood down wrote no such note. */
@@ -100,6 +104,8 @@ export const STOOD_DOWN_OUTCOME = 'stood down';
100
104
  export const LISTED_AGAIN = 'listed again';
101
105
  /** The kind the reorder call writes: its task goes ahead of the queue until a run takes it. */
102
106
  export const MOVED_TO_FRONT = 'moved to front';
107
+ /** Why a task blocked for nothing new went back to its queue: the lapse of that block (`tasks.ts` `blockLapsed`). */
108
+ export const UNBLOCKED_INPUTS_CHANGED = 'something new since its last failed try';
103
109
 
104
110
  /** A task as its queue reads it, from one query: no note is read in code. */
105
111
  export interface TaskState {
@@ -115,6 +121,16 @@ export interface TaskState {
115
121
  readonly since: number;
116
122
  /** That note's id: what orders two tasks of one moment. 0 with none. */
117
123
  readonly note: number;
124
+ /**
125
+ * ITS PLACE IN ITS QUEUE: when it entered it, unix seconds, and that note's id (0 with none), what `tasks.ts` `queueOrder`
126
+ * sorts by. The note that put it there, or when it was made; a block for nothing new and that block's lapse are no
127
+ * entry, so a task whose block lapsed is back at the place it held before it, and a blocked task holds that place for
128
+ * when it lapses.
129
+ *
130
+ * Why (2026-11-21): a lapse counted as entering the queue, so the 112 Decompile tasks a new answer revision reached went
131
+ * from the places their last failed tries gave them, some days old, to the back of 803 queued, about 85 hours away.
132
+ */
133
+ readonly entered: { readonly at: number; readonly note: number };
118
134
  /** The id of its `moved to front` note written since it came to that status; none otherwise. */
119
135
  readonly front: number | null;
120
136
  /** Failed tries since its count last started again. */
@@ -130,7 +146,7 @@ export interface TaskState {
130
146
  /**
131
147
  * WHY IT NEEDS AN AGENT, from its newest `needs an agent` note, while that mark stands; none otherwise. Something new from
132
148
  * outside its workflow clears it (a return to its queue, a move to the front, any note by a person or another workflow),
133
- * and so do an agent step that ran on it and its final check passing (`AGENT_STEP_RAN`, a finished outcome).
149
+ * and so do a run on it that took an agent and its final check passing (`AGENT_TAKEN`, a finished outcome).
134
150
  */
135
151
  readonly needsAgent: string | null;
136
152
  /**
@@ -150,25 +166,6 @@ export interface QueueCount {
150
166
  readonly tasks: number;
151
167
  }
152
168
 
153
- /**
154
- * Tasks of one workflow that a step of another returned to their queue (`tasks.ts` `requeue`, `reopen`): how many notes,
155
- * the last when.
156
- */
157
- export interface ReturnedBetween {
158
- readonly from: string;
159
- readonly to: string;
160
- readonly notes: number;
161
- readonly last: number;
162
- }
163
-
164
- /** A workflow's tasks its list last put on one wait, by what they wait on and the list's words for it. */
165
- export interface ListedWait {
166
- readonly workflow: string;
167
- readonly on: string;
168
- readonly label: string;
169
- readonly tasks: number;
170
- }
171
-
172
169
  /** What a reading of a workflow's list changed. */
173
170
  export interface ListingRecorded {
174
171
  /** Whether it put any task in the queue: one new to the list, or one it lists again. */
@@ -226,10 +223,13 @@ export interface TaskStore {
226
223
  readonly recordQueueCounts: (r: { readonly at: number; readonly counts: ReadonlyArray<Omit<QueueCount, 'at'>> }) => Effect.Effect<void, StorageError>;
227
224
  /** Each count recorded since `since`, and for each queue and status the last recorded before it, oldest first. */
228
225
  readonly queueCountsSince: (since: number) => Effect.Effect<ReadonlyArray<QueueCount>, StorageError>;
229
- /** Every workflow a step of which returned another's tasks to their queue, by the two. */
230
- readonly returnedBetween: () => Effect.Effect<ReadonlyArray<ReturnedBetween>, StorageError>;
231
- /** Every wait a workflow's list puts its tasks on now, with how many. */
232
- readonly listedWaits: () => Effect.Effect<ReadonlyArray<ListedWait>, StorageError>;
233
226
  /** Whether the store can be written: false in a test that named no store. */
234
227
  readonly writable: () => boolean;
228
+ /**
229
+ * DELETES A WORKFLOW'S TASKS THAT ARE ITS RUNS (`steps.ts` `tasksAreRuns`), with their notes, where the task's newest note is
230
+ * before `before`, its item (its run) is none of `keepItems`, it is none of the workflow's `keepNewest` newest such tasks,
231
+ * and no other task's note names it. Only for such a workflow:
232
+ * an item's task is the work's state, never deleted by retention (`retention.ts`). How many tasks and notes went.
233
+ */
234
+ readonly deleteRunTasksEndedBefore: (r: { readonly workflow: string; readonly before: number; readonly keepItems: ReadonlyArray<string>; readonly keepNewest: number }) => Effect.Effect<{ readonly tasks: number; readonly notes: number }, StorageError>;
235
235
  }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * THE PLATFORM'S OWN WORKFLOWS, which every app built on it has and none defines. Alex, 2026-11-22: "retention is supposed
3
+ * to be configurable at the platform layer and something configurable for all tasks. not a bespoke workflow that every
4
+ * implementation must define. perhaps there can be some notion of system workflows at the top level which can be
5
+ * configured but not amended without changing the platform itself".
6
+ *
7
+ * `createWorkflowPlatform` defines each before any of the app's, so each is declared, measured, queued and shown like any
8
+ * other workflow (`steps.ts`), at the top level, and marked as the platform's (`WorkflowDeclaration.system`). What the app
9
+ * sets of one is its schedule (`WorkflowProject.systemSchedules`), its run limit (the limits table, as for any workflow)
10
+ * and the settings it inherits from the app (`WorkflowProject.settings`). What it cannot do is define a workflow of its
11
+ * name or hold it as a step (`steps.ts` `refuseSystem`): changing its steps is changing the platform.
12
+ *
13
+ * The app's engine runs each one's layer (`SystemWorkflows.layer`) and its scheduler starts each one's run on its
14
+ * schedule (`SystemWorkflows.workflows`), as it starts any workflow of its own on a timer.
15
+ *
16
+ * Retention every hour, deletes each finished run's step records once past what its steps keep (`retention.ts`).
17
+ */
18
+ import { Effect, Layer, Schema } from 'effect';
19
+ import type { Retention, RetentionPass } from './retention';
20
+ import type { makeSteps } from './steps';
21
+
22
+ /** Each of the platform's own workflows, by name, and how often it runs where the app sets nothing: its first run after the app's start, then every `everySeconds`. */
23
+ export const SYSTEM_WORKFLOW_SCHEDULES = {
24
+ Retention: { everySeconds: 3600, firstAfterSeconds: 300 },
25
+ } as const;
26
+
27
+ export type SystemWorkflowName = keyof typeof SYSTEM_WORKFLOW_SCHEDULES;
28
+
29
+ /** What an app sets of a system workflow's schedule (`WorkflowProject.systemSchedules`). */
30
+ export interface SystemSchedule {
31
+ readonly everySeconds: number;
32
+ }
33
+
34
+ /** One pass of retention as its step's result (`RetentionPass`). */
35
+ const RetentionPassResult = Schema.Struct({ records: Schema.Number, parts: Schema.Number, runTasks: Schema.Number, runTaskNotes: Schema.Number });
36
+
37
+ /** What a pass deleted, in the words its step record keeps as its reason. Pure. */
38
+ export const retentionPassWords = (p: RetentionPass): string => {
39
+ const n = (x: number, one: string, many: string) => `${x.toLocaleString('en-US')} ${x === 1 ? one : many}`;
40
+ return `deleted ${n(p.records, 'step record', 'step records')}, ${n(p.parts, 'per-item part', 'per-item parts')} of them, and ${n(p.runTasks, 'task that was a run', 'tasks that were runs')} with ${n(p.runTaskNotes, 'note', 'notes')}`;
41
+ };
42
+
43
+ /** A schedule as the app set it, checked where it enters: a whole number of seconds, at least one. */
44
+ const checkedEvery = (name: SystemWorkflowName, set: SystemSchedule | undefined): number => {
45
+ if (set === undefined) return SYSTEM_WORKFLOW_SCHEDULES[name].everySeconds;
46
+ if (!(Number.isInteger(set.everySeconds) && set.everySeconds >= 1)) throw new Error(`${name}: its schedule must be a whole number of seconds, at least 1, not ${set.everySeconds}`);
47
+ return set.everySeconds;
48
+ };
49
+
50
+ /** The platform's own workflows, defined on one app's platform. */
51
+ export const makeSystemWorkflows = <R>(deps: {
52
+ readonly define: ReturnType<typeof makeSteps<R>>['oneStepSystemWorkflow'];
53
+ readonly retention: Retention;
54
+ readonly schedules: Readonly<Partial<Record<SystemWorkflowName, SystemSchedule>>> | undefined;
55
+ }) => {
56
+ const unknown = Object.keys(deps.schedules ?? {}).filter((name) => !(name in SYSTEM_WORKFLOW_SCHEDULES));
57
+ if (unknown.length > 0) throw new Error(`the app sets a schedule for ${unknown.join(', ')}, which is none of the platform's own workflows (${Object.keys(SYSTEM_WORKFLOW_SCHEDULES).join(', ')})`);
58
+ const retention = deps.define({
59
+ at: import.meta.path,
60
+ description: "Every hour: each finished run's step records deleted once past the days its steps keep them, set on the app, a workflow or a step; and the tasks that were those runs.",
61
+ stepDescription: "Deletes each finished run's step records past its retention, a chunk a transaction, and says how many went.",
62
+ reason: retentionPassWords,
63
+ }, 'Retention', 'Prune', RetentionPassResult, Effect.suspend(() => deps.retention.prune(Date.now() / 1000)));
64
+ const workflows = [
65
+ { name: retention.name, everySeconds: checkedEvery('Retention', deps.schedules?.Retention), firstAfterSeconds: SYSTEM_WORKFLOW_SCHEDULES.Retention.firstAfterSeconds, run: retention.run, start: retention.start },
66
+ ] as const;
67
+ return { workflows, layer: Layer.mergeAll(retention.layer) };
68
+ };
69
+
70
+ export type SystemWorkflows = ReturnType<typeof makeSystemWorkflows<unknown>>;
package/src/tasks.ts CHANGED
@@ -21,7 +21,8 @@
21
21
  *
22
22
  * THE QUEUE IS FIRST IN, FIRST OUT, with one escape hatch (Alex, 2026-11-19: "the queue should essentially be fifo with an
23
23
  * escape hatch api to reorder work on a queue manually"). A task's place is when it entered the queue: the time of the note
24
- * that put it there, or when it was made. `moveToFront` is the escape hatch: the tasks it names go first, in the order
24
+ * that put it there, or when it was made (`TaskState.entered`). A block for nothing new is no leaving it: when the block
25
+ * lapses, the task is back at the place it held. `moveToFront` is the escape hatch: the tasks it names go first, in the order
25
26
  * given, until a run takes them. There is no other ordering rule.
26
27
  *
27
28
  * BLOCKING IS A STEP'S LOGIC (Alex, 2026-11-19, of not retrying a task nothing new has reached: "why can't that be logic in
@@ -31,6 +32,12 @@
31
32
  * tries; it keeps flipping between two versions; nothing new since its last failed try. A page only counts what the notes
32
33
  * say (`taskSummaries`).
33
34
  *
35
+ * A WORKFLOW THAT WORKS ON NO ITEM HAS ONE TASK A RUN, where it runs on its own trigger and has runs of its own (`steps.ts`
36
+ * `tasksAreRuns`; Alex, 2026-11-21: "a workflow is a workflow"): its item is the run's id, made as the run starts
37
+ * (`runStarted`), in progress while it goes, done when it succeeds, blocked when it fails or stands down, with why. A trigger
38
+ * whose start its run limit refuses leaves no run waiting, so none is queued: its next turn tries again. One that runs as a
39
+ * step of another's run has no tasks of its own: they are that workflow's, passing through it.
40
+ *
34
41
  * NOTES ARE APPEND-ONLY. The engine appends every run's outcome, with its run, step and time ('outcome'), and its own kinds
35
42
  * below; a step or an agent appends its own through `appendTaskNote`. A run's agent is given its task's notes
36
43
  * (`notesForAgent`). Where tasks live is the task store's business (`storage/task-store.ts`).
@@ -41,16 +48,16 @@ import type { PickWakes } from './pick-wakes';
41
48
  import type { EngineRecords } from './storage/engine-records';
42
49
  import type { StepRecords } from './storage/step-records';
43
50
  import type { StorageError } from './storage/storage-error';
44
- import { AGENT_STEP_RAN, MOVED_TO_FRONT, NEEDS_AN_AGENT, STATUS_KINDS, TRIES_START_AGAIN_KINDS, type Listed, type NewNote, type NoteBy, type TaskNote, type TaskRef, type TaskState, type TaskStore } from './storage/task-store';
51
+ import { AGENT_STEP_RAN, AGENT_TAKEN, MOVED_TO_FRONT, NEEDS_AN_AGENT, STATUS_KINDS, TRIES_START_AGAIN_KINDS, UNBLOCKED_INPUTS_CHANGED, type Listed, type NewNote, type NoteBy, type TaskNote, type TaskRef, type TaskState, type TaskStore } from './storage/task-store';
45
52
 
46
- export { AGENT_STEP_RAN, NEEDS_AN_AGENT, STOOD_DOWN_OUTCOME, TRIES_START_AGAIN_KINDS } from './storage/task-store';
53
+ export { AGENT_STEP_RAN, AGENT_TAKEN, NEEDS_AN_AGENT, STOOD_DOWN_OUTCOME, TRIES_START_AGAIN_KINDS } from './storage/task-store';
47
54
  export type { Listed, NoteBy, TaskNote, TaskRef, TaskState } from './storage/task-store';
48
55
 
49
56
  export const TASK_STATUSES = ['queued', 'in progress', 'blocked', 'done'] as const;
50
57
  export type TaskStatus = (typeof TASK_STATUSES)[number];
51
58
 
52
59
  /** The kinds only the engine writes: a step's own note takes another. */
53
- export const ENGINE_NOTE_KINDS: ReadonlyArray<string> = ['outcome', MOVED_TO_FRONT, AGENT_STEP_RAN, ...Object.keys(STATUS_KINDS), 'waiter resumed'];
60
+ export const ENGINE_NOTE_KINDS: ReadonlyArray<string> = ['outcome', MOVED_TO_FRONT, AGENT_TAKEN, AGENT_STEP_RAN, ...Object.keys(STATUS_KINDS), 'waiter resumed'];
54
61
 
55
62
  /** Failed tries of one workflow on one item after which a Pick blocks it: it gets no run again until someone returns it to the queue. */
56
63
  export const BLOCK_AFTER_TRIES = 10;
@@ -61,8 +68,7 @@ export const BLOCK_AFTER_RETURNS = 2;
61
68
  export const BLOCKED_NOTHING_NEW = 'nothing new since its last failed try';
62
69
  export const BLOCKED_FLIPPING = 'it keeps flipping between two versions';
63
70
  export const blockedAfterTries = (tries: number): string => `${tries} failed tries`;
64
- /** Why a task blocked for nothing new went back to its queue. */
65
- export const UNBLOCKED_INPUTS_CHANGED = 'something new since its last failed try';
71
+ export { UNBLOCKED_INPUTS_CHANGED };
66
72
  /**
67
73
  * Why a task blocked for its failed tries went back to its queue: fewer count now, as when a release stops counting a kind
68
74
  * of run (0.6.2, a run an outside service failed). Its count stands, so the next failed try that brings it to
@@ -109,7 +115,7 @@ export interface TaskSummary {
109
115
  readonly returned: boolean;
110
116
  /**
111
117
  * Why it needs an agent, in words, while it is marked so (`TaskState.needsAgent`): its Pick passes over it while no agent
112
- * is available to its workflow. None otherwise.
118
+ * is free for its workflow. None otherwise.
113
119
  */
114
120
  readonly needsAgent: string | null;
115
121
  readonly listed: Listed | null;
@@ -187,7 +193,7 @@ export const summarize = (input: { readonly state: TaskState; readonly running:
187
193
  if (state.status === 'done') return { ...base, status: 'done', why: state.why ?? 'its final check passed' };
188
194
  if (state.status === 'blocked') return { ...base, status: 'blocked', why: state.why ?? 'blocked by a step' };
189
195
  const said = state.kind === null ? 'not tried yet' : state.kind === 'outcome' ? `tried ${state.tries} time${state.tries === 1 ? '' : 's'}; the last: ${state.why}` : `${state.kind}: ${state.why}`;
190
- // A mark a later note of its own workflow left standing is said too: its Pick passes over it while no agent is available.
196
+ // A mark a later note of its own workflow left standing is said too: its Pick passes over it while no agent is free.
191
197
  const marked = state.needsAgent === null || state.kind === NEEDS_AN_AGENT ? said : `${said}; ${NEEDS_AN_AGENT}: ${state.needsAgent}`;
192
198
  return { ...base, status: 'queued', why: state.front === null ? marked : `moved to the front by hand; ${marked}` };
193
199
  };
@@ -200,12 +206,12 @@ export const needsAgentReasons = (tasks: ReadonlyArray<TaskSummary>): ReadonlyAr
200
206
  };
201
207
 
202
208
  /**
203
- * THE ONE ORDER OF A QUEUE: first in, first out, by when each task entered it, after the tasks the reorder call moved to
204
- * the front, the last moved first. Pure.
209
+ * THE ONE ORDER OF A QUEUE: first in, first out, by when each task entered it (`TaskState.entered`), after the tasks the
210
+ * reorder call moved to the front, the last moved first. Pure.
205
211
  */
206
212
  export const queueOrder = (tasks: ReadonlyArray<TaskSummary>): ReadonlyArray<TaskSummary> =>
207
213
  tasks.filter((t) => t.status === 'queued').sort((a, b) =>
208
- (b.noted.front ?? 0) - (a.noted.front ?? 0) || a.since - b.since || a.noted.note - b.noted.note || a.id - b.id);
214
+ (b.noted.front ?? 0) - (a.noted.front ?? 0) || a.noted.entered.at - b.noted.entered.at || a.noted.entered.note - b.noted.entered.note || a.id - b.id);
209
215
 
210
216
  /**
211
217
  * THE STANDARD REASON A PICK BLOCKS A QUEUED TASK FOR, none where none holds: `BLOCK_AFTER_TRIES` failed tries; or nothing
@@ -219,11 +225,12 @@ export const standardBlock = (task: TaskSummary, inputs: TaskInputs | undefined)
219
225
  return null;
220
226
  };
221
227
 
222
- /** Why a Pick passes over a task nothing new has reached since its last run, while no agent can be had. */
228
+ /** Why a Pick passes over a task nothing new has reached since its last run, while no agent is free. */
223
229
  export const NOTHING_NEW_SINCE_ITS_LAST_RUN = 'nothing new since its last run, which no agent could finish';
224
230
 
225
231
  /**
226
- * WHY A PICK PASSES OVER A QUEUED TASK WHILE NO AGENT CAN BE HAD, none where it takes it: it is marked as needing an agent
232
+ * WHY A PICK PASSES OVER A QUEUED TASK WHILE NO AGENT IS FREE (`steps.ts` `whyNoAgentIsFree`: none can be had, or every one
233
+ * is in use), none where it takes it: it is marked as needing an agent
227
234
  * (`TaskSummary.needsAgent`), or nothing new has reached it since its last run (its inputs now are those its newest run's
228
235
  * outcome recorded, and no note has brought it new input since: `TaskState.lastRunInputs`). A run on it could only repeat
229
236
  * the steps that need no agent on what they already ran on, and stop at its agent step again. A task whose workflow
@@ -452,19 +459,36 @@ export const makeTasks = (deps: {
452
459
  if (recorded?.fresh === true) wakes.wakePicksOf(input.workflow, 'an item new to its list');
453
460
  });
454
461
 
455
- /** The items each workflow's unfinished runs are on now, lower case; a run named in `excludingRun` is left out. */
462
+ /**
463
+ * The items each workflow's unfinished runs are on now, lower case; a run named in `excludingRun` is left out. Each run's
464
+ * own id is among them too: the item of a run's own task (`runStarted`), which no other workflow names.
465
+ */
456
466
  const itemsRunningNow = (excludingRun?: string): Effect.Effect<ReadonlyMap<string, ReadonlySet<string>>, StorageError> =>
457
467
  Effect.gen(function* () {
458
468
  const out = new Map<string, Set<string>>();
459
469
  for (const r of yield* deps.engine.unfinishedRuns()) {
460
470
  if (r.run === excludingRun) continue;
471
+ const items = out.get(r.workflow) ?? new Set<string>();
472
+ out.set(r.workflow, items.add(keyOf(r.run)));
461
473
  const subject = yield* deps.stepRecords.subjectOfRun(r.run);
462
- if (subject === null) continue;
463
- out.set(r.workflow, (out.get(r.workflow) ?? new Set()).add(keyOf(subject)));
474
+ if (subject !== null) items.add(keyOf(subject));
464
475
  }
465
476
  return out;
466
477
  });
467
478
 
479
+ /**
480
+ * A RUN'S OWN TASK, for a workflow whose tasks are its runs (`steps.ts` `tasksAreRuns`): made as its trigger starts the run,
481
+ * its item the run's id, with a `queued` note, so it is its workflow's task (`TaskState.returned`) and in progress while
482
+ * the run is going. Its outcome makes it done, or blocked with why (`appendOutcome`). A run resumed after a restart starts
483
+ * again here and finds its task made. It wakes no Pick: no Pick claims a run's own task (the engine has its queue counted).
484
+ */
485
+ const runStarted = (r: { readonly workflow: string; readonly run: string }): Effect.Effect<void> => Effect.gen(function* () {
486
+ const task = { workflow: r.workflow, item: r.run };
487
+ const made = yield* engineWrite(`the task of run ${r.run}`, store.taskId(task));
488
+ if (made !== null) return;
489
+ yield* engineWrite(`the task of run ${r.run}`, store.append([{ task, by: { workflow: r.workflow, run: r.run, step: null }, kind: 'queued', why: 'its trigger started a run' }]));
490
+ });
491
+
468
492
  /**
469
493
  * EACH TASK'S INPUTS AS ITS WORKFLOW LAST READ THEM (`steps.ts` `readTaskInputs`, at each Pick), by item in lower case:
470
494
  * what `settleQueue` blocks a task with nothing new by.
@@ -507,6 +531,7 @@ export const makeTasks = (deps: {
507
531
  const lapsed = t.status === 'blocked' ? blockLapsed(t, own) : null;
508
532
  if (lapsed !== null) {
509
533
  notes.push({ task: t.ref, by: input.by, kind: 'unblocked', why: lapsed });
534
+ // A lapsed block for nothing new keeps the place it held: `entered` passes over its note (`sqlite-store.ts`).
510
535
  settled.push({ ...t, status: 'queued', why: lapsed, since: Date.now() / 1000 });
511
536
  continue;
512
537
  }
@@ -521,7 +546,7 @@ export const makeTasks = (deps: {
521
546
 
522
547
  /** One task's status now, and why; a task no workflow has named yet is queued. */
523
548
  const statusOf = (task: TaskRef): Effect.Effect<TaskSummary, StorageError> => Effect.gen(function* () {
524
- const state = (yield* store.state(task)) ?? { id: 0, ref: task, listed: null, status: 'queued' as const, why: null, kind: null, since: Date.now() / 1000, note: 0, front: null, tries: 0, inputs: null, about: null, changes: 0, returned: false, needsAgent: null, lastRunInputs: null };
549
+ const state = (yield* store.state(task)) ?? { id: 0, ref: task, listed: null, status: 'queued' as const, why: null, kind: null, since: Date.now() / 1000, note: 0, entered: { at: Date.now() / 1000, note: 0 }, front: null, tries: 0, inputs: null, about: null, changes: 0, returned: false, needsAgent: null, lastRunInputs: null };
525
550
  return summarize({ state, running: (yield* itemsRunningNow()).get(task.workflow)?.has(keyOf(task.item)) === true });
526
551
  });
527
552
 
@@ -529,9 +554,9 @@ export const makeTasks = (deps: {
529
554
  const notesForAgent = (task: TaskRef): Effect.Effect<string, StorageError> => (store.writable() ? Effect.map(store.notes(task), (notes) => notesText(notes)) : Effect.succeed(''));
530
555
 
531
556
  /**
532
- * MARKS A TASK AS NEEDING AN AGENT, by the run that stopped at an agent step no agent could be had for (`steps.ts`
533
- * `untilAgentSlot`): the note puts it at the back of its queue, and its Pick passes over it while no agent is available.
534
- * Whether it was written: with no store, or a write that failed, the run waits at its step as before.
557
+ * MARKS A TASK AS NEEDING AN AGENT, by the run on it that found no agent it could claim, or could no longer use the one it
558
+ * held (`steps.ts` `claimAgentsOrEnd`, `beforeAgentCall`): the note puts it at the back of its queue, and its Pick passes
559
+ * over it while no agent is free. Whether it was written: with no store, or a write that failed, the run ends all the same.
535
560
  */
536
561
  const markNeedsAgent = (input: { readonly task: TaskRef; readonly by: NoteBy; readonly why: string }): Effect.Effect<boolean> =>
537
562
  Effect.map(engineWrite(`the mark that ${input.task.workflow} ${input.task.item} needs an agent`, store.append([{ task: input.task, by: input.by, kind: NEEDS_AN_AGENT, why: input.why }])), (ids) => ids !== null);
@@ -543,17 +568,17 @@ export const makeTasks = (deps: {
543
568
  const readByItsPick = (task: TaskRef): Effect.Effect<boolean, StorageError> =>
544
569
  Effect.map(store.state(task), (s) => s !== null && s.status !== 'removed' && (s.listed !== null || s.returned));
545
570
 
546
- /** After an agent step ran on a task marked as needing an agent: the mark clears, since it may need none now. */
547
- const agentStepRan = (input: { readonly task: TaskRef; readonly by: NoteBy }): Effect.Effect<void> => Effect.gen(function* () {
571
+ /** After a run on a task marked as needing an agent took an agent for it: the mark has done its work, and clears. */
572
+ const agentTaken = (input: { readonly task: TaskRef; readonly by: NoteBy }): Effect.Effect<void> => Effect.gen(function* () {
548
573
  const state = yield* engineWrite(`the state of ${input.task.workflow} ${input.task.item}`, store.state(input.task));
549
574
  if (state === null || state.needsAgent === null) return;
550
- yield* engineWrite(`the end of the mark on ${input.task.workflow} ${input.task.item}`, store.append([{ task: input.task, by: input.by, kind: AGENT_STEP_RAN, why: `${input.by.step ?? 'an agent step'} ran on it, so it may need no agent now` }]));
575
+ yield* engineWrite(`the end of the mark on ${input.task.workflow} ${input.task.item}`, store.append([{ task: input.task, by: input.by, kind: AGENT_TAKEN, why: `${input.by.step ?? 'a run'} took an agent for it` }]));
551
576
  });
552
577
 
553
578
  return {
554
579
  appendTaskNote, noteText, requeue, block, reopen, moveToFront, appendOutcome, recordListing, recordTaskInputs,
555
580
  taskNotes: store.notes, taskIdOf: store.taskId, itemsRunningNow, taskSummaries, settleQueue, statusOf, notesForAgent,
556
- markNeedsAgent, readByItsPick, agentStepRan, passedOverNow,
581
+ markNeedsAgent, readByItsPick, agentTaken, passedOverNow, runStarted,
557
582
  };
558
583
  };
559
584