@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
package/src/tasks.ts DELETED
@@ -1,561 +0,0 @@
1
- /**
2
- * TASKS: ONE UNIQUE UNIT OF WORK, a workflow and its item, with its own append-only notes, and the status it stands in.
3
- *
4
- * Alex, 2026-11-06: "we should be thinking about a job or a task as a unique unit of work and many of these are assigned to
5
- * different buckets on a workflow. The note belongs to a task and all tasks have their own append only notes log." The
6
- * engine creates a task the first time a workflow lists, picks or records an item, and gives it a stable id; a reference is
7
- * `{ workflow, item }`, the item matched in any case.
8
- *
9
- * FOUR STATUSES (Alex, 2026-11-19: "idk why we need to differentiate between queued and waiting or between held and stuck.
10
- * if we're 'waiting' on feedback from something else, shouldn't that just mean a step in the workflow?"):
11
- *
12
- * queued ready for a run;
13
- * in progress a run of its workflow is on it;
14
- * blocked a step decided no run should start on it, with the reason in words;
15
- * done its workflow's final check passed.
16
- *
17
- * A STATUS IS READ FROM THE TASK'S NOTES, and nothing stores a second copy (`storage/task-store.ts` `TaskState`): the
18
- * newest of a run's outcome (finished: done; otherwise back to queued), a `blocked` note and a return to the queue
19
- * (`queued`, `unblocked`, `listed again`) decides it, and a run on it now makes it in progress. Its workflow's list can name
20
- * it as one no run should start on, with the reason: that blocks it while the list says so.
21
- *
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
- * 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
25
- * given, until a run takes them. There is no other ordering rule.
26
- *
27
- * 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
28
- * one of the steps?"). A Pick reads its queue through `settleQueue`, which blocks each queued task one of the standard
29
- * reasons holds for and returns each blocked task whose reason has lapsed to the queue; a workflow's own step blocks with
30
- * `block`, or says so with its run's outcome (`RunOutcome.blocked`). The standard reasons: `BLOCK_AFTER_TRIES` failed
31
- * tries; it keeps flipping between two versions; nothing new since its last failed try. A page only counts what the notes
32
- * say (`taskSummaries`).
33
- *
34
- * NOTES ARE APPEND-ONLY. The engine appends every run's outcome, with its run, step and time ('outcome'), and its own kinds
35
- * below; a step or an agent appends its own through `appendTaskNote`. A run's agent is given its task's notes
36
- * (`notesForAgent`). Where tasks live is the task store's business (`storage/task-store.ts`).
37
- */
38
- import { Data, Effect, pipe } from 'effect';
39
- import type { TextStore } from './project';
40
- import type { PickWakes } from './pick-wakes';
41
- import type { EngineRecords } from './storage/engine-records';
42
- import type { StepRecords } from './storage/step-records';
43
- 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';
45
-
46
- export { AGENT_STEP_RAN, NEEDS_AN_AGENT, STOOD_DOWN_OUTCOME, TRIES_START_AGAIN_KINDS } from './storage/task-store';
47
- export type { Listed, NoteBy, TaskNote, TaskRef, TaskState } from './storage/task-store';
48
-
49
- export const TASK_STATUSES = ['queued', 'in progress', 'blocked', 'done'] as const;
50
- export type TaskStatus = (typeof TASK_STATUSES)[number];
51
-
52
- /** 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'];
54
-
55
- /** 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
- export const BLOCK_AFTER_TRIES = 10;
57
- /** Returns to an earlier text after which a Pick blocks a task as flipping between two versions. */
58
- export const BLOCK_AFTER_RETURNS = 2;
59
-
60
- /** The standard reasons a Pick blocks a task for, in the words its page shows. */
61
- export const BLOCKED_NOTHING_NEW = 'nothing new since its last failed try';
62
- export const BLOCKED_FLIPPING = 'it keeps flipping between two versions';
63
- 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';
66
- /**
67
- * 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
- * of run (0.6.2, a run an outside service failed). Its count stands, so the next failed try that brings it to
69
- * `BLOCK_AFTER_TRIES` blocks it again.
70
- */
71
- export const UNBLOCKED_FEWER_TRIES = `fewer than ${BLOCK_AFTER_TRIES} failed tries count now`;
72
-
73
- /**
74
- * WHAT A TASK RUNS ON NOW, as its workflow reads it (`WorkflowDeclaration.taskInputs`). Each outcome records the fingerprint
75
- * its run left the task with, so a Pick can tell a task nothing new has reached since its last failed try.
76
- */
77
- export interface TaskInputs {
78
- /** Of everything a run reads for the task: its text, its stored result, the versions of the checks it must pass. */
79
- readonly fingerprint: string;
80
- }
81
-
82
- /**
83
- * A WORKFLOW'S LIST OF WORK, as one definition. Each line is a group of its list's items; `waits` are items it says no run
84
- * should start on, each group with the reason (`label`) and what it waits for (`on`): those are blocked with that reason
85
- * while the list says so.
86
- */
87
- export interface PendingWork {
88
- readonly lines: ReadonlyArray<{ readonly label: string; readonly items: ReadonlyArray<string>; readonly title?: string; readonly outsideGap?: true }>;
89
- readonly waits: ReadonlyArray<{ readonly on: string; readonly label: string; readonly items: ReadonlyArray<string> }>;
90
- }
91
-
92
- /** A workflow's list of work: every item on its lines. */
93
- export const listOf = (work: PendingWork): ReadonlyArray<string> => work.lines.flatMap((l) => l.items);
94
-
95
- /** A task and the status it is in now. */
96
- export interface TaskSummary {
97
- readonly id: number;
98
- readonly ref: TaskRef;
99
- readonly status: TaskStatus;
100
- /** Why it is in that status, in words: for a blocked task, the reason its page shows beside it. */
101
- readonly why: string;
102
- /** Failed tries since its count last started again, a run that stood down left out. */
103
- readonly tries: number;
104
- /** When it came to the status its notes leave it in, unix seconds. */
105
- readonly since: number;
106
- /** Whether the reorder call moved it to the front of its queue, and no run has taken it since. */
107
- readonly movedToFront: boolean;
108
- /** Whether a step or a person put it back in its queue (`requeue`, `reopen`), and its final check has not passed since. */
109
- readonly returned: boolean;
110
- /**
111
- * 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.
113
- */
114
- readonly needsAgent: string | null;
115
- readonly listed: Listed | null;
116
- /** What its notes say, for the rules that read them (`standardBlock`). */
117
- readonly noted: TaskState;
118
- }
119
-
120
- export class TaskStoreError extends Data.TaggedError('TaskStoreError')<{ readonly reason: string }> {}
121
-
122
- const keyOf = (item: string) => item.toLowerCase();
123
-
124
- // ---------------------------------------------------------------------------------------------------------------- pure
125
-
126
- /** The lines removed (`-`) and added (`+`), with 2 lines around each and `@@ line N` before each run. Pure. */
127
- export const lineDiff = (before: string, after: string): string => {
128
- if (before === after) return '';
129
- const a = before.split('\n');
130
- const b = after.split('\n');
131
- const common: number[][] = Array.from({ length: a.length + 1 }, () => new Array<number>(b.length + 1).fill(0));
132
- for (let i = a.length - 1; i >= 0; i -= 1) {
133
- for (let j = b.length - 1; j >= 0; j -= 1) common[i]![j] = a[i] === b[j] ? common[i + 1]![j + 1]! + 1 : Math.max(common[i + 1]![j]!, common[i]![j + 1]!);
134
- }
135
- const ops: Array<{ readonly mark: ' ' | '-' | '+'; readonly text: string; readonly line: number }> = [];
136
- let i = 0;
137
- let j = 0;
138
- while (i < a.length || j < b.length) {
139
- if (i < a.length && j < b.length && a[i] === b[j]) { ops.push({ mark: ' ', text: a[i]!, line: i + 1 }); i += 1; j += 1; }
140
- else if (i < a.length && (j === b.length || common[i + 1]![j]! >= common[i]![j + 1]!)) { ops.push({ mark: '-', text: a[i]!, line: i + 1 }); i += 1; }
141
- else { ops.push({ mark: '+', text: b[j]!, line: i + 1 }); j += 1; }
142
- }
143
- const near = ops.map((_, k) => ops.slice(Math.max(0, k - 2), k + 3).some((o) => o.mark !== ' '));
144
- const out: string[] = [];
145
- ops.forEach((o, k) => {
146
- if (!near[k]) return;
147
- if (k === 0 || !near[k - 1]) out.push(`@@ line ${o.line}`);
148
- out.push(`${o.mark}${o.text}`);
149
- });
150
- return out.join('\n');
151
- };
152
-
153
- /** Notes after the task was last returned to its queue by a step or a person. */
154
- const sinceReturned = (notes: ReadonlyArray<TaskNote>): ReadonlyArray<TaskNote> => {
155
- let returned = -1;
156
- notes.forEach((n, k) => { if (TRIES_START_AGAIN_KINDS.includes(n.kind)) returned = k; });
157
- return notes.slice(returned + 1);
158
- };
159
-
160
- /**
161
- * How often a task's text went back to the text it had two changes earlier (A→B→A), since it was last returned to its
162
- * queue: its texts in order, each change's before and after, a change that changed nothing left out. Pure.
163
- */
164
- export const returnsToEarlierText = (notes: ReadonlyArray<TaskNote>): number => {
165
- const texts: string[] = [];
166
- for (const n of sinceReturned(notes)) {
167
- if (n.change === null) continue;
168
- for (const sha of [n.change.beforeSha, n.change.afterSha]) if (texts[texts.length - 1] !== sha) texts.push(sha);
169
- }
170
- return texts.filter((sha, i) => i >= 2 && texts[i - 2] === sha).length;
171
- };
172
-
173
- /** Fewer changes of its text than this cannot hold `BLOCK_AFTER_RETURNS` returns to an earlier one: its notes are not read. */
174
- export const CHANGES_THAT_CAN_FLIP = BLOCK_AFTER_RETURNS + 1;
175
-
176
- /** A task's status and why, from what its notes say and whether a run is on it. Pure. */
177
- export const summarize = (input: { readonly state: TaskState; readonly running: boolean }): TaskSummary => {
178
- const { state, running } = input;
179
- const base = {
180
- id: state.id, ref: state.ref, tries: state.tries, since: state.since, listed: state.listed, noted: state,
181
- movedToFront: state.front !== null,
182
- returned: state.returned,
183
- needsAgent: state.needsAgent,
184
- };
185
- if (running) return { ...base, status: 'in progress', why: 'a run is on it now' };
186
- if (state.listed?.kind === 'wait') return { ...base, status: 'blocked', why: state.listed.label };
187
- if (state.status === 'done') return { ...base, status: 'done', why: state.why ?? 'its final check passed' };
188
- if (state.status === 'blocked') return { ...base, status: 'blocked', why: state.why ?? 'blocked by a step' };
189
- 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.
191
- const marked = state.needsAgent === null || state.kind === NEEDS_AN_AGENT ? said : `${said}; ${NEEDS_AN_AGENT}: ${state.needsAgent}`;
192
- return { ...base, status: 'queued', why: state.front === null ? marked : `moved to the front by hand; ${marked}` };
193
- };
194
-
195
- /** How many of a workflow's queued tasks need an agent, for one reason each, most tasks first. Pure. */
196
- export const needsAgentReasons = (tasks: ReadonlyArray<TaskSummary>): ReadonlyArray<BlockedReason> => {
197
- const counts = new Map<string, number>();
198
- for (const t of tasks) if (t.status === 'queued' && t.needsAgent !== null) counts.set(t.needsAgent, (counts.get(t.needsAgent) ?? 0) + 1);
199
- return [...counts].map(([why, n]) => ({ why, tasks: n })).sort((a, b) => b.tasks - a.tasks || a.why.localeCompare(b.why));
200
- };
201
-
202
- /**
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.
205
- */
206
- export const queueOrder = (tasks: ReadonlyArray<TaskSummary>): ReadonlyArray<TaskSummary> =>
207
- 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);
209
-
210
- /**
211
- * THE STANDARD REASON A PICK BLOCKS A QUEUED TASK FOR, none where none holds: `BLOCK_AFTER_TRIES` failed tries; or nothing
212
- * new since its last failed try, where its workflow says what its tasks run on (`inputs`) and they are those its last
213
- * failed run left it with. Flipping is read from its notes (`returnsToEarlierText`). Pure.
214
- */
215
- export const standardBlock = (task: TaskSummary, inputs: TaskInputs | undefined): string | null => {
216
- if (task.status !== 'queued') return null;
217
- if (task.tries >= BLOCK_AFTER_TRIES) return blockedAfterTries(task.tries);
218
- if (task.noted.kind === 'outcome' && inputs !== undefined && task.noted.inputs === inputs.fingerprint) return BLOCKED_NOTHING_NEW;
219
- return null;
220
- };
221
-
222
- /** Why a Pick passes over a task nothing new has reached since its last run, while no agent can be had. */
223
- export const NOTHING_NEW_SINCE_ITS_LAST_RUN = 'nothing new since its last run, which no agent could finish';
224
-
225
- /**
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
227
- * (`TaskSummary.needsAgent`), or nothing new has reached it since its last run (its inputs now are those its newest run's
228
- * outcome recorded, and no note has brought it new input since: `TaskState.lastRunInputs`). A run on it could only repeat
229
- * the steps that need no agent on what they already ran on, and stop at its agent step again. A task whose workflow
230
- * declares no inputs, or whose last run recorded none, is taken. Pure.
231
- */
232
- export const passedOverWithoutAnAgent = (task: TaskSummary, inputs: TaskInputs | undefined): string | null => {
233
- if (task.status !== 'queued') return null;
234
- if (task.needsAgent !== null) return task.needsAgent;
235
- if (inputs !== undefined && task.noted.lastRunInputs !== null && task.noted.lastRunInputs === inputs.fingerprint) return NOTHING_NEW_SINCE_ITS_LAST_RUN;
236
- return null;
237
- };
238
-
239
- /**
240
- * Why a blocked task's reason has lapsed, none where it still holds: it was blocked for nothing new, and its inputs now are
241
- * not those it was blocked with; or for its failed tries, and fewer than `BLOCK_AFTER_TRIES` count now. Pure.
242
- */
243
- export const blockLapsed = (task: TaskSummary, inputs: TaskInputs | undefined): string | null => {
244
- if (task.noted.status !== 'blocked') return null;
245
- if (task.noted.why === BLOCKED_NOTHING_NEW && (inputs === undefined || inputs.fingerprint !== task.noted.inputs)) return UNBLOCKED_INPUTS_CHANGED;
246
- if (task.noted.why !== null && /^\d+ failed tries$/.test(task.noted.why) && task.tries < BLOCK_AFTER_TRIES) return UNBLOCKED_FEWER_TRIES;
247
- return null;
248
- };
249
-
250
- /**
251
- * THE ORDER A PICK TAKES ITS OWN CANDIDATES IN, given in the workflow's own order: none blocked or in progress; those in
252
- * its queue first, in the queue's order (`queueOrder`), then the rest in the workflow's own. A task a step or a person
253
- * returned to the queue that the candidates do not hold is built by `fromItem`. `alsoLeaveOut` names items the workflow
254
- * knows are not to be taken. For a workflow whose Pick takes candidates of its own; one whose Pick takes the head of its
255
- * queue reads `queueOrder`. Pure.
256
- */
257
- export const inPickOrder = <C>(input: {
258
- readonly candidates: ReadonlyArray<C>;
259
- readonly subjectOf: (c: C) => string;
260
- readonly tasks: ReadonlyArray<TaskSummary>;
261
- readonly fromItem?: (item: string) => C | null;
262
- readonly alsoLeaveOut?: ReadonlySet<string>;
263
- }): ReadonlyArray<C> => {
264
- const byItem = new Map(input.tasks.map((t) => [keyOf(t.ref.item), t]));
265
- const place = new Map(queueOrder(input.tasks).map((t, i) => [keyOf(t.ref.item), i]));
266
- const leaveOut = new Set([...(input.alsoLeaveOut ?? [])].map(keyOf));
267
- const free = (item: string) => {
268
- const t = byItem.get(keyOf(item));
269
- return !leaveOut.has(keyOf(item)) && (t === undefined || t.status === 'queued' || t.status === 'done');
270
- };
271
- const given = new Set(input.candidates.map((c) => keyOf(input.subjectOf(c))));
272
- const fromItem = input.fromItem;
273
- const built = fromItem === undefined ? [] : input.tasks
274
- .filter((t) => t.returned && t.status === 'queued' && !given.has(keyOf(t.ref.item)) && free(t.ref.item))
275
- .flatMap((t) => { const c = fromItem(t.ref.item); return c === null ? [] : [{ c, item: t.ref.item }]; });
276
- const open = [...input.candidates.filter((c) => free(input.subjectOf(c))).map((c) => ({ c, item: input.subjectOf(c) })), ...built]
277
- .map((o, i) => ({ c: o.c, i, at: place.get(keyOf(o.item)) ?? Number.MAX_SAFE_INTEGER }));
278
- return open.sort((a, b) => a.at - b.at || a.i - b.i).map((o) => o.c);
279
- };
280
-
281
- /** A task's notes as its run's agent reads them: every note but an outcome, and its last 3 outcomes, newest last. Pure. */
282
- export const notesText = (notes: ReadonlyArray<TaskNote>, limit = 4000): string => {
283
- const outcomes = notes.filter((n) => n.kind === 'outcome').slice(-3).map((n) => n.id);
284
- const lines = notes.filter((n) => n.kind !== 'outcome' || outcomes.includes(n.id)).map((n) => [
285
- `${new Date(n.at * 1000).toISOString().slice(0, 16).replace('T', ' ')} UTC, ${n.by.workflow ?? 'by hand'}${n.by.run === null ? '' : ` (run ${n.by.run}${n.by.step === null ? '' : `, step ${n.by.step}`})`}: ${n.kind}${n.about === null ? '' : ` (${n.about.workflow} ${n.about.item})`}. ${n.why}`,
286
- ...(n.change === null || n.change.diff === '' ? [] : ['```diff', n.change.diff, '```']),
287
- ].join('\n'));
288
- const kept: string[] = [];
289
- let size = 0;
290
- for (let k = lines.length - 1; k >= 0 && size + lines[k]!.length <= limit; k -= 1) { kept.unshift(lines[k]!); size += lines[k]!.length + 2; }
291
- return kept.join('\n\n');
292
- };
293
-
294
- /** How many of a workflow's tasks are blocked for one reason. */
295
- export interface BlockedReason {
296
- readonly why: string;
297
- readonly tasks: number;
298
- }
299
-
300
- /**
301
- * WHY A WORKFLOW'S BLOCKED TASKS ARE BLOCKED, most tasks first: a count for each reason, so a page says the reason beside
302
- * the number. Reasons that differ only by a count or by which task is waited on are one reason. Pure.
303
- */
304
- export const blockedReasons = (tasks: ReadonlyArray<TaskSummary>): ReadonlyArray<BlockedReason> => {
305
- const reason = (t: TaskSummary) => (/^\d+ failed tries$/.test(t.why) ? `${BLOCK_AFTER_TRIES} or more failed tries` : t.noted.about !== null && t.noted.status === 'blocked' ? `waits on a task of ${t.noted.about.workflow}` : t.why);
306
- const counts = new Map<string, number>();
307
- for (const t of tasks) if (t.status === 'blocked') counts.set(reason(t), (counts.get(reason(t)) ?? 0) + 1);
308
- return [...counts].map(([why, n]) => ({ why, tasks: n })).sort((a, b) => b.tasks - a.tasks || a.why.localeCompare(b.why));
309
- };
310
-
311
- /** A workflow's tasks counted by status: every status, a zero as much as any other, so they add up to its tasks. Pure. */
312
- export const statusCounts = (tasks: ReadonlyArray<TaskSummary>): Readonly<Record<TaskStatus, number>> =>
313
- Object.fromEntries(TASK_STATUSES.map((s) => [s, tasks.filter((t) => t.status === s).length])) as Record<TaskStatus, number>;
314
-
315
- // -------------------------------------------------------------------------------------------------------------- stored
316
-
317
- /** The task queue of one project: the rules above applied to its stored tasks, every write waking the Picks it can change. */
318
- export const makeTasks = (deps: {
319
- readonly store: TaskStore;
320
- readonly engine: EngineRecords;
321
- readonly stepRecords: StepRecords;
322
- readonly wakes: PickWakes;
323
- readonly texts: TextStore;
324
- }) => {
325
- const { store, wakes } = deps;
326
-
327
- /** A note can change what its workflow's Pick can claim; the wake reaches it once this write has committed, once per workflow. */
328
- const appended = (notes: ReadonlyArray<NewNote>, ids: ReadonlyArray<number | null>): void => {
329
- const woken = new Map<string, string>();
330
- notes.forEach((n, k) => { if (ids[k] !== null && !woken.has(n.task.workflow)) woken.set(n.task.workflow, n.kind); });
331
- for (const [workflow, kind] of woken) wakes.wakePicksOf(workflow, `a note on one of its tasks: ${kind}`);
332
- };
333
-
334
- /** A write a step asks for: it fails, typed, rather than going missing. */
335
- const inStore = (notes: ReadonlyArray<NewNote>): Effect.Effect<ReadonlyArray<number | null>, TaskStoreError> => Effect.suspend(() => {
336
- if (notes.length === 0) return Effect.succeed([]);
337
- if (!store.writable()) return Effect.fail(new TaskStoreError({ reason: 'no task store is open: a test names one' }));
338
- return pipe(
339
- store.append(notes),
340
- Effect.mapError((e) => new TaskStoreError({ reason: e.reason })),
341
- Effect.tap((ids) => Effect.sync(() => appended(notes, ids))),
342
- );
343
- });
344
-
345
- /** A write the engine makes as a run ends or a list is read: it never fails what it records, and says when it could not. */
346
- const engineWrite = <A>(what: string, write: Effect.Effect<A, StorageError>): Effect.Effect<A | null> =>
347
- !store.writable() ? Effect.succeed(null) : Effect.catchTag(write, 'StorageError', (e) => Effect.as(Effect.logError(`[tasks] ${what}: ${e.reason}`), null));
348
-
349
- const storeText = (text: string, what: string): Effect.Effect<string, TaskStoreError> =>
350
- Effect.try({ try: () => deps.texts.write(text), catch: (e) => new TaskStoreError({ reason: `${what} could not be stored: ${e instanceof Error ? e.message : String(e)}` }) });
351
-
352
- /** Appends a note of a step's or an agent's own. A change stores both texts by hash, with the diff between them. */
353
- const appendTaskNote = (input: {
354
- readonly task: TaskRef;
355
- readonly by: NoteBy;
356
- readonly kind: string;
357
- readonly why: string;
358
- readonly about?: TaskRef;
359
- readonly aboutSha?: string;
360
- readonly change?: { readonly before: string; readonly after: string; readonly flags: string };
361
- }): Effect.Effect<TaskNote, TaskStoreError> => Effect.gen(function* () {
362
- if (ENGINE_NOTE_KINDS.includes(input.kind)) return yield* Effect.fail(new TaskStoreError({ reason: `'${input.kind}' is a kind only the engine writes` }));
363
- const change = input.change === undefined ? undefined : {
364
- beforeSha: yield* storeText(input.change.before, 'the texts'), afterSha: yield* storeText(input.change.after, 'the texts'), flags: input.change.flags, diff: lineDiff(input.change.before, input.change.after),
365
- };
366
- const now = Date.now() / 1000;
367
- const note: NewNote = { task: input.task, by: input.by, kind: input.kind, why: input.why, ...(input.about === undefined ? {} : { about: input.about }), ...(input.aboutSha === undefined ? {} : { aboutSha: input.aboutSha }), ...(change === undefined ? {} : { change }) };
368
- const [id] = yield* inStore([note]);
369
- return {
370
- id: id ?? 0, task: input.task, at: now, kind: input.kind, by: input.by, why: input.why, about: input.about ?? null, aboutSha: input.aboutSha ?? null, finished: null, inputSha: null, inputs: null, change: change ?? null,
371
- };
372
- });
373
-
374
- /** A stored text a note's change names, checked against its hash. */
375
- const noteText = (sha: string): Effect.Effect<string, TaskStoreError> =>
376
- Effect.try({ try: () => deps.texts.read(sha), catch: (e) => new TaskStoreError({ reason: `text ${sha} could not be read: ${e instanceof Error ? e.message : String(e)}` }) });
377
-
378
- /**
379
- * PUTS A TASK BACK IN ITS QUEUE, done or blocked or not: it joins the back, and its count of failed tries starts again.
380
- * `input` is new text for its next run, stored by hash and read with `noteText(note.inputSha)`.
381
- */
382
- const requeue = (input: { readonly task: TaskRef; readonly by: NoteBy; readonly why: string; readonly input?: string; readonly about?: TaskRef }): Effect.Effect<void, TaskStoreError> =>
383
- Effect.gen(function* () {
384
- const inputSha = input.input === undefined ? undefined : yield* storeText(input.input, 'the input');
385
- yield* inStore([{ task: input.task, by: input.by, kind: 'queued', why: input.why, ...(input.about === undefined ? {} : { about: input.about }), ...(inputSha === undefined ? {} : { inputSha }) }]);
386
- });
387
-
388
- /**
389
- * BLOCKS A TASK: a step's decision that no run should start on it, with the reason in words, until a step or a person
390
- * puts it back (`requeue`). `inputs` is what it ran on when it was blocked, where the reason is that nothing is new.
391
- */
392
- const block = (input: { readonly task: TaskRef; readonly by: NoteBy; readonly why: string; readonly about?: TaskRef; readonly inputs?: string }): Effect.Effect<void, TaskStoreError> =>
393
- Effect.asVoid(inStore([{ task: input.task, by: input.by, kind: 'blocked', why: input.why, ...(input.about === undefined ? {} : { about: input.about }), ...(input.inputs === undefined ? {} : { inputs: input.inputs }) }]));
394
-
395
- /**
396
- * Another task's work is needed first: `task` goes back to its queue, done or not, and `waiting` is blocked on it until it
397
- * finishes, when it goes back to its own (`appendOutcome`). Both get a note.
398
- */
399
- const reopen = (input: { readonly task: TaskRef; readonly waiting: TaskRef; readonly by: NoteBy; readonly why: string }): Effect.Effect<void, TaskStoreError> =>
400
- Effect.asVoid(inStore([
401
- { task: input.task, by: input.by, kind: 'queued', why: input.why, about: input.waiting },
402
- { task: input.waiting, by: input.by, kind: 'blocked', why: `waits on ${input.task.workflow} ${input.task.item}: ${input.why}`, about: input.task },
403
- ]));
404
-
405
- /**
406
- * THE ESCAPE HATCH: moves tasks of one workflow to the front of its queue, in the order given, ahead of every task moved
407
- * before. Each keeps its place there until a run takes it. An item that is no task of the workflow now is named, not made.
408
- */
409
- const moveToFront = (input: { readonly workflow: string; readonly items: ReadonlyArray<string>; readonly by: NoteBy; readonly why: string }): Effect.Effect<{ readonly moved: ReadonlyArray<string>; readonly notItsTasks: ReadonlyArray<string> }, TaskStoreError> =>
410
- Effect.gen(function* () {
411
- const states = yield* Effect.mapError(store.statesOf(input.workflow), (e) => new TaskStoreError({ reason: e.reason }));
412
- const own = new Map(states.map((s) => [keyOf(s.ref.item), s.ref.item]));
413
- const named = [...new Map(input.items.map((item) => [keyOf(item), item])).values()];
414
- const moved = named.flatMap((item) => { const stored = own.get(keyOf(item)); return stored === undefined ? [] : [stored]; });
415
- // The last note written is the first in the queue, so they are written last first.
416
- yield* inStore([...moved].reverse().map((item) => ({ task: { workflow: input.workflow, item }, by: input.by, kind: MOVED_TO_FRONT, why: input.why })));
417
- return { moved, notItsTasks: named.filter((item) => !own.has(keyOf(item))) };
418
- });
419
-
420
- /**
421
- * WHAT BECAME OF ONE ITEM WHEN ITS RUN ENDED, on its task, with the run and the step it ended on. `blocked` is why the
422
- * run's step blocked it, where it did. One that finished the task returns every task blocked waiting on it to its queue.
423
- * Run again on a resume, it keeps the first.
424
- */
425
- const appendOutcome = (r: { readonly workflow: string; readonly run: string; readonly subject: string | null; readonly outcome: string; readonly finished: boolean; readonly inputs: string | null; readonly blocked: string | null }): Effect.Effect<void> => Effect.gen(function* () {
426
- const item = r.subject ?? (yield* engineWrite(`the item of run ${r.run}`, deps.stepRecords.subjectOfRun(r.run)));
427
- if (item === null) return;
428
- const task = { workflow: r.workflow, item };
429
- const by = { workflow: r.workflow, run: r.run, step: (yield* engineWrite(`the step of run ${r.run}`, deps.stepRecords.stepOfRun(r.run)))?.step ?? null };
430
- const done = yield* engineWrite(`outcome of run ${r.run}`, store.appendOutcome({
431
- task, by, why: r.outcome, finished: r.finished, inputs: r.inputs, blocked: r.blocked,
432
- resumedWhy: () => `${r.workflow} ${item} finished (${r.outcome}), so this goes back to its queue`,
433
- }));
434
- if (done === null || !done.appended) return;
435
- wakes.wakePicksOf(r.workflow, 'a note on one of its tasks: outcome');
436
- for (const w of done.resumed) wakes.wakePicksOf(w.workflow, 'a note on one of its tasks: queued');
437
- });
438
-
439
- /**
440
- * WHERE A WORKFLOW'S LIST PUTS EACH OF ITS ITEMS NOW: the engine's one reading of it, which makes its tasks
441
- * (`TaskStore.recordListing`, where the two kinds of list are written down). `everyItem`: the list is every item it has,
442
- * done or not; otherwise only its work left.
443
- */
444
- const recordListing = (input: { readonly workflow: string; readonly work: PendingWork; readonly everyItem: boolean; readonly readAt?: number }): Effect.Effect<void> => Effect.gen(function* () {
445
- const at = new Map<string, { readonly item: string; readonly listed: Listed }>();
446
- for (const l of input.work.lines) for (const item of l.items) at.set(keyOf(item), { item, listed: { kind: 'line', label: l.label } });
447
- for (const w of input.work.waits) for (const item of w.items) at.set(keyOf(item), { item, listed: { kind: 'wait', label: w.label, on: w.on } });
448
- const recorded = yield* engineWrite(`the list of ${input.workflow}`, store.recordListing({
449
- workflow: input.workflow, listed: [...at.values()], everyItem: input.everyItem, readAt: input.readAt ?? Date.now() / 1000, by: { workflow: input.workflow, run: null, step: null },
450
- }));
451
- // An item new to the list, or listed again, is work its Pick may claim; the list read again with the same items wakes nothing.
452
- if (recorded?.fresh === true) wakes.wakePicksOf(input.workflow, 'an item new to its list');
453
- });
454
-
455
- /** The items each workflow's unfinished runs are on now, lower case; a run named in `excludingRun` is left out. */
456
- const itemsRunningNow = (excludingRun?: string): Effect.Effect<ReadonlyMap<string, ReadonlySet<string>>, StorageError> =>
457
- Effect.gen(function* () {
458
- const out = new Map<string, Set<string>>();
459
- for (const r of yield* deps.engine.unfinishedRuns()) {
460
- if (r.run === excludingRun) continue;
461
- 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)));
464
- }
465
- return out;
466
- });
467
-
468
- /**
469
- * EACH TASK'S INPUTS AS ITS WORKFLOW LAST READ THEM (`steps.ts` `readTaskInputs`, at each Pick), by item in lower case:
470
- * what `settleQueue` blocks a task with nothing new by.
471
- */
472
- const inputsRead = new Map<string, ReadonlyMap<string, TaskInputs>>();
473
- const recordTaskInputs = (workflow: string, inputs: ReadonlyMap<string, TaskInputs>): void => { inputsRead.set(workflow, inputs); };
474
- /** Why its Pick passes over a task while no agent can be had (`passedOverWithoutAnAgent`), by its inputs as its workflow last read them. */
475
- const passedOverNow = (task: TaskSummary): string | null => passedOverWithoutAnAgent(task, inputsRead.get(task.ref.workflow)?.get(keyOf(task.ref.item)));
476
-
477
- /** Every task of a workflow and the status it is in now. `running` is for a test. */
478
- const taskSummaries = (input: { readonly workflow: string; readonly excludingRun?: string; readonly running?: ReadonlyMap<string, ReadonlySet<string>> }): Effect.Effect<ReadonlyArray<TaskSummary>, StorageError> => Effect.gen(function* () {
479
- const states = yield* store.statesOf(input.workflow);
480
- const running = (input.running ?? (yield* itemsRunningNow(input.excludingRun))).get(input.workflow);
481
- return states.map((state) => summarize({ state, running: running?.has(keyOf(state.ref.item)) === true }));
482
- });
483
-
484
- /**
485
- * THE STANDARD BLOCKING, RUN BY THE STEP THAT PICKS, before it reads its queue: each queued task a standard reason holds
486
- * for is blocked with it (`standardBlock`, and flipping, read from the notes of a task with enough changes to flip), and
487
- * each blocked task whose reason has lapsed goes back to the queue (`blockLapsed`). `by` is the Pick. Returns the
488
- * workflow's tasks as that leaves them, another run's left in progress and `excludingRun`'s own free.
489
- */
490
- const settleQueue = (input: { readonly workflow: string; readonly by: NoteBy; readonly excludingRun?: string }): Effect.Effect<ReadonlyArray<TaskSummary>, StorageError> => Effect.gen(function* () {
491
- const tasks = yield* taskSummaries({ workflow: input.workflow, ...(input.excludingRun === undefined ? {} : { excludingRun: input.excludingRun }) });
492
- if (!store.writable()) return tasks;
493
- const inputs = inputsRead.get(input.workflow);
494
- const notes: NewNote[] = [];
495
- const settled: TaskSummary[] = [];
496
- for (const t of tasks) {
497
- const own = inputs?.get(keyOf(t.ref.item));
498
- if (t.status === 'queued') {
499
- const flips = t.noted.changes < CHANGES_THAT_CAN_FLIP ? 0 : returnsToEarlierText(yield* store.notes(t.ref));
500
- const why = flips >= BLOCK_AFTER_RETURNS ? BLOCKED_FLIPPING : standardBlock(t, own);
501
- if (why !== null) {
502
- notes.push({ task: t.ref, by: input.by, kind: 'blocked', why, ...(t.noted.inputs === null ? {} : { inputs: t.noted.inputs }) });
503
- settled.push({ ...t, status: 'blocked', why });
504
- continue;
505
- }
506
- }
507
- const lapsed = t.status === 'blocked' ? blockLapsed(t, own) : null;
508
- if (lapsed !== null) {
509
- notes.push({ task: t.ref, by: input.by, kind: 'unblocked', why: lapsed });
510
- settled.push({ ...t, status: 'queued', why: lapsed, since: Date.now() / 1000 });
511
- continue;
512
- }
513
- settled.push(t);
514
- }
515
- if (notes.length === 0) return tasks;
516
- const written = yield* Effect.result(store.append(notes));
517
- // Unwritten, nothing was settled: the tasks stand as they were read, and the next Pick tries again.
518
- if (written._tag === 'Failure') return yield* Effect.as(Effect.logError(`[tasks] ${input.workflow}: its queue could not be settled: ${written.failure.reason}`), tasks);
519
- return settled;
520
- });
521
-
522
- /** One task's status now, and why; a task no workflow has named yet is queued. */
523
- 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 };
525
- return summarize({ state, running: (yield* itemsRunningNow()).get(task.workflow)?.has(keyOf(task.item)) === true });
526
- });
527
-
528
- /** What a run's agent is told of its own task: its notes, as `notesText` words them; empty with none, or with no store. */
529
- const notesForAgent = (task: TaskRef): Effect.Effect<string, StorageError> => (store.writable() ? Effect.map(store.notes(task), (notes) => notesText(notes)) : Effect.succeed(''));
530
-
531
- /**
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.
535
- */
536
- const markNeedsAgent = (input: { readonly task: TaskRef; readonly by: NoteBy; readonly why: string }): Effect.Effect<boolean> =>
537
- 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);
538
-
539
- /**
540
- * Whether a task is one its workflow's Pick reads: on its list, or returned to its queue by a step or a person. A mark on
541
- * any other is on a task no Pick passes over.
542
- */
543
- const readByItsPick = (task: TaskRef): Effect.Effect<boolean, StorageError> =>
544
- Effect.map(store.state(task), (s) => s !== null && s.status !== 'removed' && (s.listed !== null || s.returned));
545
-
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* () {
548
- const state = yield* engineWrite(`the state of ${input.task.workflow} ${input.task.item}`, store.state(input.task));
549
- 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` }]));
551
- });
552
-
553
- return {
554
- appendTaskNote, noteText, requeue, block, reopen, moveToFront, appendOutcome, recordListing, recordTaskInputs,
555
- taskNotes: store.notes, taskIdOf: store.taskId, itemsRunningNow, taskSummaries, settleQueue, statusOf, notesForAgent,
556
- markNeedsAgent, readByItsPick, agentStepRan, passedOverNow,
557
- };
558
- };
559
-
560
- export type Tasks = ReturnType<typeof makeTasks>;
561
-
@@ -1,40 +0,0 @@
1
- /** HOW THE DASHBOARD WRITES FIGURES AND TIMES. Pure, so it is tested alone; no figure is written two ways. */
2
-
3
- /** A duration in the largest units that keep it short: "42 s", "3 min 5 s", "2 h 4 min". */
4
- export const duration = (seconds: number): string => {
5
- if (seconds < 60) return `${Math.round(seconds)} s`;
6
- const minutes = Math.floor(seconds / 60);
7
- if (minutes < 60) return `${minutes} min ${Math.round(seconds - minutes * 60)} s`;
8
- const hours = Math.floor(minutes / 60);
9
- return `${hours} h ${minutes - hours * 60} min`;
10
- };
11
-
12
- /** A count in thousands or millions past 10,000: "9,812", "48k", "3.1M". */
13
- export const compact = (n: number): string => {
14
- if (n < 10_000) return Math.round(n).toLocaleString('en-US');
15
- if (n < 1_000_000) return `${Math.round(n / 1000)}k`;
16
- return `${(n / 1_000_000).toFixed(1)}M`;
17
- };
18
-
19
- /** A percent to one place, cut rather than rounded, so 94.96 never reads as 95: "94.9%", "89%". */
20
- export const percentCut = (percent: number): string => `${Math.floor(percent * 10) / 10}%`;
21
-
22
- const pad = (n: number) => String(n).padStart(2, '0');
23
-
24
- /** A time as the clock on this device shows it, with the date when it is not today: "5:04 AM", "Nov 11, 5:04 AM". */
25
- export const localTime = (unixSeconds: number, now: number = Date.now() / 1000): string => {
26
- const at = new Date(unixSeconds * 1000);
27
- const today = new Date(now * 1000);
28
- const time = at.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' });
29
- return at.toDateString() === today.toDateString() ? time : `${at.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}, ${time}`;
30
- };
31
-
32
- /** A time with how long ago it was beside it: "5:04 AM · 12 min ago". */
33
- export const whenAgo = (unixSeconds: number, now: number = Date.now() / 1000): string =>
34
- `${localTime(unixSeconds, now)} · ${duration(Math.max(0, now - unixSeconds))} ago`;
35
-
36
- /** A 24-hour clock time, for a window's start: "05:04". */
37
- export const clockTime = (unixSeconds: number): string => {
38
- const at = new Date(unixSeconds * 1000);
39
- return `${pad(at.getHours())}:${pad(at.getMinutes())}`;
40
- };