@jive-sh/workflow-platform 0.3.3 → 0.5.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 (61) hide show
  1. package/README.md +68 -23
  2. package/dist/dashboard/agent-usage.js +25 -0
  3. package/dist/dashboard/agent-usage.js.map +1 -0
  4. package/dist/dashboard/drilldown.js +16 -0
  5. package/dist/dashboard/drilldown.js.map +1 -0
  6. package/dist/dashboard/queue-lines.js +44 -0
  7. package/dist/dashboard/queue-lines.js.map +1 -0
  8. package/dist/index.js +8 -6
  9. package/dist/index.js.map +1 -1
  10. package/dist/keep-running.js +1 -1
  11. package/dist/keep-running.js.map +1 -1
  12. package/dist/pick-wakes.js +4 -4
  13. package/dist/pick-wakes.js.map +1 -1
  14. package/dist/queue-counts.js +7 -9
  15. package/dist/queue-counts.js.map +1 -1
  16. package/dist/steps.js +157 -41
  17. package/dist/steps.js.map +1 -1
  18. package/dist/storage/sqlite-store.js +117 -38
  19. package/dist/storage/sqlite-store.js.map +1 -1
  20. package/dist/storage/task-store.js +14 -1
  21. package/dist/storage/task-store.js.map +1 -1
  22. package/dist/tasks.js +215 -267
  23. package/dist/tasks.js.map +1 -1
  24. package/dist/views/runs-now.js +3 -2
  25. package/dist/views/runs-now.js.map +1 -1
  26. package/dist/views/step-funnel.js +1 -1
  27. package/dist/views/step-funnel.js.map +1 -1
  28. package/dist/views/step-graph.js +1 -1
  29. package/dist/views/step-graph.js.map +1 -1
  30. package/dist/views/workflow-flows.js +2 -2
  31. package/dist/views/workflow-flows.js.map +1 -1
  32. package/dist/views/workflows-view.js +83 -17
  33. package/dist/views/workflows-view.js.map +1 -1
  34. package/package.json +1 -1
  35. package/src/dashboard/agent-usage-line.tsx +28 -0
  36. package/src/dashboard/agent-usage.ts +48 -0
  37. package/src/dashboard/dashboard.css +70 -29
  38. package/src/dashboard/drilldown.ts +43 -0
  39. package/src/dashboard/index.tsx +1 -0
  40. package/src/dashboard/machine-controls.tsx +53 -0
  41. package/src/dashboard/queue-bar.tsx +43 -0
  42. package/src/dashboard/queue-chart.tsx +89 -76
  43. package/src/dashboard/queue-lines.ts +87 -0
  44. package/src/dashboard/step-graph.tsx +18 -10
  45. package/src/dashboard/workflow-dag.tsx +31 -103
  46. package/src/dashboard/workflow-drilldown.tsx +89 -0
  47. package/src/dashboard/workflows-dashboard.tsx +117 -42
  48. package/src/index.ts +11 -9
  49. package/src/keep-running.ts +3 -3
  50. package/src/pick-wakes.ts +14 -9
  51. package/src/queue-counts.ts +10 -14
  52. package/src/steps.ts +213 -52
  53. package/src/storage/sqlite-store.ts +126 -39
  54. package/src/storage/step-records.ts +14 -3
  55. package/src/storage/task-store.ts +97 -22
  56. package/src/tasks.ts +235 -301
  57. package/src/views/runs-now.ts +5 -4
  58. package/src/views/step-funnel.ts +2 -2
  59. package/src/views/step-graph.ts +4 -4
  60. package/src/views/workflow-flows.ts +7 -7
  61. package/src/views/workflows-view.ts +117 -35
package/src/tasks.ts CHANGED
@@ -1,23 +1,35 @@
1
1
  /**
2
- * TASKS: ONE UNIQUE UNIT OF WORK, a workflow and its item, with its own append-only notes, and the bucket it stands in.
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
3
  *
4
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
5
  * different buckets on a workflow. The note belongs to a task and all tasks have their own append only notes log." The
6
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
7
  * `{ workflow, item }`, the item matched in any case.
8
8
  *
9
- * A WORKFLOW DECLARES ONLY its items (its list of work), each run's outcome (`defineWorkflow`'s `outcomes`), and when a
10
- * task waits on another (`reopen`). Every bucket is derived, never stored: from a task's notes, the line its workflow's list
11
- * last put it on, and the runs going now (`summarize`), in this order:
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?"):
12
11
  *
13
- * running a run of its workflow is on it;
14
- * done its workflow's list no longer holds it and no reopen is open;
15
- * waiting its list names it as waiting on something, or it waits on another task not yet done (`reopen`);
16
- * held `hold` held it, or its text went back to an earlier one `HOLD_AFTER_RETURNS` times, since its last release;
17
- * stuck run over `STUCK_AFTER_RUNS` times with no success since its last success, release or reopen;
18
- * waiting its last run, not a stand-down, left it with the inputs it has now (`TaskInputs`), and no note opened it since;
19
- * queued the rest, picked in `queueRank`'s order: a task the project marks urgent first, then one reopened or given new
20
- * input by another workflow or step, until a run has tried it with that input.
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`).
21
33
  *
22
34
  * NOTES ARE APPEND-ONLY. The engine appends every run's outcome, with its run, step and time ('outcome'), and its own kinds
23
35
  * below; a step or an agent appends its own through `appendTaskNote`. A run's agent is given its task's notes
@@ -29,104 +41,74 @@ import type { PickWakes } from './pick-wakes';
29
41
  import type { EngineRecords } from './storage/engine-records';
30
42
  import type { StepRecords } from './storage/step-records';
31
43
  import type { StorageError } from './storage/storage-error';
32
- import type { Listed, NewNote, NoteBy, TaskFacts, TaskNote, TaskRef, TaskStore } from './storage/task-store';
33
-
34
- export type { Listed, NoteBy, TaskFacts, TaskNote, TaskRef } from './storage/task-store';
35
-
36
- export const BUCKETS = ['queued', 'running', 'waiting', 'stuck', 'held', 'done'] as const;
37
- export type Bucket = (typeof BUCKETS)[number];
44
+ import { MOVED_TO_FRONT, STATUS_KINDS, TRIES_START_AGAIN_KINDS, type Listed, type NewNote, type NoteBy, type TaskNote, type TaskRef, type TaskState, type TaskStore } from './storage/task-store';
38
45
 
39
- /** Each bucket in the page's words. */
40
- export const BUCKET_WORDS: Readonly<Record<Bucket, string>> = {
41
- queued: 'queued', running: 'running', waiting: 'waiting', stuck: 'stuck', held: 'held', done: 'done',
42
- };
46
+ export { STOOD_DOWN_OUTCOME, TRIES_START_AGAIN_KINDS } from './storage/task-store';
47
+ export type { Listed, NoteBy, TaskNote, TaskRef, TaskState } from './storage/task-store';
43
48
 
44
- /** The kinds only the engine writes. */
45
- export const ENGINE_NOTE_KINDS = ['outcome', 'reopened', 'new input', 'waits on', 'resumed', 'waiter resumed', 'released', 'held'] as const;
49
+ export const TASK_STATUSES = ['queued', 'in progress', 'blocked', 'done'] as const;
50
+ export type TaskStatus = (typeof TASK_STATUSES)[number];
46
51
 
47
- /**
48
- * The kinds that open a task again and put it at the front of its workflow's queue, its count of runs started again: another
49
- * task reopened it, a workflow or step gave it new input, or the task it waited on finished, so what it needed has changed.
50
- */
51
- const OPENING_KINDS: ReadonlyArray<string> = ['reopened', 'new input', 'resumed'];
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, ...Object.keys(STATUS_KINDS), 'waiter resumed'];
52
54
 
53
- /** Runs of one workflow on one item with no success after which it is stuck: it gets no agent again until released. */
54
- export const STUCK_AFTER_RUNS = 10;
55
- /** Returns to an earlier text after which a task is held from automatic edits. */
56
- export const HOLD_AFTER_RETURNS = 2;
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;
57
59
 
58
- /** The lines its buckets put a task on in the workflow's list as the page draws it. */
59
- export const STUCK_LINE = `stuck: no success in over ${STUCK_AFTER_RUNS} runs`;
60
- export const HELD_LINE = 'held: undone and redone, or held by a step';
61
- export const REOPENED_LINE = 'reopened by another task, outside this phase\'s gap';
62
- export const WAITING_ON_A_TASK = { on: 'another task', label: 'waiting on another task' } as const;
63
- export const WAITING_ON_INPUTS = { on: 'its inputs', label: 'waits for its inputs to change' } as const;
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';
64
66
 
65
67
  /**
66
68
  * WHAT A TASK RUNS ON NOW, as its workflow reads it (`WorkflowDeclaration.taskInputs`). Each outcome records the fingerprint
67
- * its run left the task with, so a task is not run again until its inputs or its notes change.
69
+ * its run left the task with, so a Pick can tell a task nothing new has reached since its last failed try.
68
70
  */
69
71
  export interface TaskInputs {
70
72
  /** Of everything a run reads for the task: its text, its stored result, the versions of the checks it must pass. */
71
73
  readonly fingerprint: string;
72
74
  }
73
75
 
74
- /** The outcome of a run that stood down for its workflow's budget: no agent was called, so it is no try. */
75
- export const STOOD_DOWN_OUTCOME = 'stood down';
76
-
77
76
  /**
78
- * WHAT A WORKFLOW HAS TO DO, as one definition, and what a dashboard draws for it. Each line is a group of its list's items,
79
- * and its items are the workflow's list: the trigger starts runs on exactly them and Pick takes from them. Alex, 2026-11-04:
80
- * "it's totally unintuitive that you're displaying these numbers as gaps in the phase, then they don't count as work to be
81
- * done".
82
- *
83
- * The one way off a list: an item that truly waits on a person's decision or on another job is a `waits` line naming what it
84
- * waits for. Running out of tries, or an agent saying it cannot, is neither: the item stays, and its failures go to the next
85
- * try.
77
+ * 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
78
+ * should start on, each group with the reason (`label`) and what it waits for (`on`): those are blocked with that reason
79
+ * while the list says so.
86
80
  */
87
81
  export interface PendingWork {
88
- /** `outsideGap`: a line of tasks its workflow does not list, reopened by another task, not counted in its phase's gap. */
89
82
  readonly lines: ReadonlyArray<{ readonly label: string; readonly items: ReadonlyArray<string>; readonly title?: string; readonly outsideGap?: true }>;
90
83
  readonly waits: ReadonlyArray<{ readonly on: string; readonly label: string; readonly items: ReadonlyArray<string> }>;
91
- /** Items its queue takes after every other it lists (`queueRank`). */
92
- readonly last?: ReadonlyArray<string>;
93
84
  }
94
85
 
95
86
  /** A workflow's list of work: every item on its lines. */
96
87
  export const listOf = (work: PendingWork): ReadonlyArray<string> => work.lines.flatMap((l) => l.items);
97
88
 
98
- /** A task and the bucket it is in now. */
89
+ /** A task and the status it is in now. */
99
90
  export interface TaskSummary {
100
91
  readonly id: number;
101
92
  readonly ref: TaskRef;
102
- readonly bucket: Bucket;
103
- /** Why it is in that bucket, in words. */
93
+ readonly status: TaskStatus;
94
+ /** Why it is in that status, in words: for a blocked task, the reason its page shows beside it. */
104
95
  readonly why: string;
105
- /** Runs since its last success, release or reopen, a run that stood down for its budget left out. */
96
+ /** Failed tries since its count last started again, a run that stood down left out. */
106
97
  readonly tries: number;
107
- readonly lastTryAt: number | null;
108
- readonly lastOutcome: string | null;
109
- /** Whether another task reopened it, or a workflow or step gave it new input, and it has not finished since. */
110
- readonly reopened: boolean;
111
- /** Whether it goes to the front of its workflow's queue: reopened or given new input, and no run has tried it since. */
112
- readonly front: boolean;
113
- /** Whether the project's rule marks it urgent (`TaskRules.urgent`): first in the queue. */
114
- readonly urgent: boolean;
115
- /** Whether its last run, not a stand-down, left it with the inputs it has now, and no note opened it since: it waits for them to change. */
116
- readonly unchanged: boolean;
98
+ /** When it came to the status its notes leave it in, unix seconds. */
99
+ readonly since: number;
100
+ /** Whether the reorder call moved it to the front of its queue, and no run has taken it since. */
101
+ readonly movedToFront: boolean;
102
+ /** Whether a step or a person put it back in its queue (`requeue`, `reopen`), and its final check has not passed since. */
103
+ readonly returned: boolean;
117
104
  readonly listed: Listed | null;
118
- }
119
-
120
- /** What a project adds to the queue's rules. */
121
- export interface TaskRules {
122
- /** A task its notes make urgent, which its queue takes before every other. */
123
- readonly urgent: (notes: ReadonlyArray<TaskNote>) => boolean;
105
+ /** What its notes say, for the rules that read them (`standardBlock`). */
106
+ readonly noted: TaskState;
124
107
  }
125
108
 
126
109
  export class TaskStoreError extends Data.TaggedError('TaskStoreError')<{ readonly reason: string }> {}
127
110
 
128
111
  const keyOf = (item: string) => item.toLowerCase();
129
- const sameTask = (a: TaskRef, b: TaskRef) => a.workflow === b.workflow && keyOf(a.item) === keyOf(b.item);
130
112
 
131
113
  // ---------------------------------------------------------------------------------------------------------------- pure
132
114
 
@@ -157,137 +139,75 @@ export const lineDiff = (before: string, after: string): string => {
157
139
  return out.join('\n');
158
140
  };
159
141
 
160
- const lastAt = (notes: ReadonlyArray<TaskNote>, test: (n: TaskNote) => boolean): number | null => {
161
- for (let k = notes.length - 1; k >= 0; k -= 1) if (test(notes[k]!)) return notes[k]!.at;
162
- return null;
163
- };
164
-
165
- /** Notes after the task's last release. */
166
- const sinceRelease = (notes: ReadonlyArray<TaskNote>): ReadonlyArray<TaskNote> => {
167
- const released = notes.map((n) => n.kind).lastIndexOf('released');
168
- return notes.slice(released + 1);
142
+ /** Notes after the task was last returned to its queue by a step or a person. */
143
+ const sinceReturned = (notes: ReadonlyArray<TaskNote>): ReadonlyArray<TaskNote> => {
144
+ let returned = -1;
145
+ notes.forEach((n, k) => { if (TRIES_START_AGAIN_KINDS.includes(n.kind)) returned = k; });
146
+ return notes.slice(returned + 1);
169
147
  };
170
148
 
171
149
  /**
172
- * How often a task's text went back to the text it had two changes earlier (A→B→A), since its last release: its texts in
173
- * order, each change's before and after, a change that changed nothing left out. Pure.
150
+ * 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
151
+ * queue: its texts in order, each change's before and after, a change that changed nothing left out. Pure.
174
152
  */
175
153
  export const returnsToEarlierText = (notes: ReadonlyArray<TaskNote>): number => {
176
154
  const texts: string[] = [];
177
- for (const n of sinceRelease(notes)) {
155
+ for (const n of sinceReturned(notes)) {
178
156
  if (n.change === null) continue;
179
157
  for (const sha of [n.change.beforeSha, n.change.afterSha]) if (texts[texts.length - 1] !== sha) texts.push(sha);
180
158
  }
181
159
  return texts.filter((sha, i) => i >= 2 && texts[i - 2] === sha).length;
182
160
  };
183
161
 
184
- /** Whether a task's reopen or new input is still open: after its last finished outcome. Pure. */
185
- const openReopen = (notes: ReadonlyArray<TaskNote>): boolean => {
186
- // By the notes' order, as `atFront`, not their times: two notes written in one millisecond tie on time.
187
- let opened = -1;
188
- let finished = -1;
189
- notes.forEach((n, k) => { if (OPENING_KINDS.includes(n.kind)) opened = k; if (n.kind === 'outcome' && n.finished === true) finished = k; });
190
- return opened >= 0 && opened > finished;
191
- };
192
-
193
- /** Whether a task is at the front of its queue: reopened or given new input after its last run's outcome. Pure. */
194
- const atFront = (notes: ReadonlyArray<TaskNote>): boolean => {
195
- let opened = -1;
196
- let tried = -1;
197
- notes.forEach((n, k) => { if (OPENING_KINDS.includes(n.kind)) opened = k; if (n.kind === 'outcome') tried = k; });
198
- return opened > tried;
199
- };
162
+ /** Fewer changes of its text than this cannot hold `BLOCK_AFTER_RETURNS` returns to an earlier one: its notes are not read. */
163
+ export const CHANGES_THAT_CAN_FLIP = BLOCK_AFTER_RETURNS + 1;
200
164
 
201
- /** A task's newest outcome, and whether a note opened it again after it, by the notes' order. Pure. */
202
- const newestOutcome = (notes: ReadonlyArray<TaskNote>): { readonly outcome: TaskNote | null; readonly openedSince: boolean } => {
203
- let openedSince = false;
204
- for (let k = notes.length - 1; k >= 0; k -= 1) {
205
- const n = notes[k]!;
206
- if (OPENING_KINDS.includes(n.kind)) openedSince = true;
207
- if (n.kind === 'outcome') return { outcome: n, openedSince };
208
- }
209
- return { outcome: null, openedSince };
165
+ /** A task's status and why, from what its notes say and whether a run is on it. Pure. */
166
+ export const summarize = (input: { readonly state: TaskState; readonly running: boolean }): TaskSummary => {
167
+ const { state, running } = input;
168
+ const base = {
169
+ id: state.id, ref: state.ref, tries: state.tries, since: state.since, listed: state.listed, noted: state,
170
+ movedToFront: state.front !== null,
171
+ returned: state.returned,
172
+ };
173
+ if (running) return { ...base, status: 'in progress', why: 'a run is on it now' };
174
+ if (state.listed?.kind === 'wait') return { ...base, status: 'blocked', why: state.listed.label };
175
+ if (state.status === 'done') return { ...base, status: 'done', why: state.why ?? 'its final check passed' };
176
+ if (state.status === 'blocked') return { ...base, status: 'blocked', why: state.why ?? 'blocked by a step' };
177
+ 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}`;
178
+ return { ...base, status: 'queued', why: state.front === null ? said : `moved to the front by hand; ${said}` };
210
179
  };
211
180
 
212
181
  /**
213
- * Whether its newest outcome left the task as it found it: no note opened it since, and its inputs now are those its run took
214
- * it with. Never for a workflow that declares no task inputs. Pure.
182
+ * THE ONE ORDER OF A QUEUE: first in, first out, by when each task entered it, after the tasks the reorder call moved to
183
+ * the front, the last moved first. Pure.
215
184
  */
216
- const inputsUnchanged = (newest: ReturnType<typeof newestOutcome>, inputs: TaskInputs | undefined): boolean =>
217
- inputs !== undefined && newest.outcome !== null && !newest.openedSince && newest.outcome.inputs === inputs.fingerprint;
218
-
219
- /** Done: off its workflow's list, no run on it and no reopen open. Pure. */
220
- export const isDone = (facts: Pick<TaskFacts, 'listed' | 'notes'>, running: boolean): boolean =>
221
- !running && facts.listed === null && !openReopen(facts.notes);
222
-
223
- /** The other tasks this one waits on and has not been resumed from, oldest first. Pure. */
224
- export const openWaits = (notes: ReadonlyArray<TaskNote>): ReadonlyArray<TaskRef> => {
225
- const open: TaskRef[] = [];
226
- for (const n of notes) {
227
- if (n.about === null) continue;
228
- if (n.kind === 'waits on' && !open.some((o) => sameTask(o, n.about!))) open.push(n.about);
229
- if (n.kind === 'resumed') {
230
- const at = open.findIndex((o) => sameTask(o, n.about!));
231
- if (at >= 0) open.splice(at, 1);
232
- }
233
- }
234
- return open;
235
- };
236
-
237
- /** A task's bucket and why, from its facts, whether a run is on it, and whether each task it waits on is done. Pure. */
238
- export const summarize = (input: { readonly facts: TaskFacts; readonly running: boolean; readonly done: (task: TaskRef) => boolean; readonly rules: TaskRules; readonly inputs?: TaskInputs }): TaskSummary => {
239
- const { facts, running } = input;
240
- const notes = facts.notes;
241
- const reset = Math.max(
242
- lastAt(notes, (n) => n.kind === 'outcome' && n.finished === true) ?? -Infinity,
243
- lastAt(notes, (n) => n.kind === 'released' || OPENING_KINDS.includes(n.kind)) ?? -Infinity,
244
- );
245
- const tried = notes.filter((n) => n.kind === 'outcome' && n.finished !== true && n.why !== STOOD_DOWN_OUTCOME && n.at > reset);
246
- const newest = tried[tried.length - 1];
247
- const reopened = openReopen(notes);
248
- const front = atFront(notes);
249
- const latest = newestOutcome(notes);
250
- // A stand-down is no try, and a finished task is done: neither waits on its inputs here.
251
- const unchanged = inputsUnchanged(latest, input.inputs) && latest.outcome!.why !== STOOD_DOWN_OUTCOME && latest.outcome!.finished !== true;
252
- const base = { id: facts.id, ref: facts.ref, tries: tried.length, lastTryAt: newest?.at ?? null, lastOutcome: newest?.why ?? null, reopened, front, urgent: input.rules.urgent(notes), unchanged, listed: facts.listed };
253
- if (running) return { ...base, bucket: 'running', why: 'a run is on it now' };
254
- if (isDone(facts, false)) return { ...base, bucket: 'done', why: 'its workflow\'s list no longer holds it' };
255
- if (facts.listed?.kind === 'wait') return { ...base, bucket: 'waiting', why: `waits on ${facts.listed.on}: ${facts.listed.label}` };
256
- const waitingOn = openWaits(notes).filter((t) => !input.done(t));
257
- if (waitingOn.length > 0) return { ...base, bucket: 'waiting', why: `waits on ${waitingOn.map((t) => `${t.workflow} ${t.item}`).join(', ')}` };
258
- const held = sinceRelease(notes).filter((n) => n.kind === 'held');
259
- if (held.length > 0) return { ...base, bucket: 'held', why: held[held.length - 1]!.why };
260
- const returns = returnsToEarlierText(notes);
261
- if (returns >= HOLD_AFTER_RETURNS) return { ...base, bucket: 'held', why: `its text went back to an earlier one ${returns} times (A→B→A); nothing changes it until it is released` };
262
- if (tried.length > STUCK_AFTER_RUNS) return { ...base, bucket: 'stuck', why: `${tried.length} runs with no success since its last` };
263
- if (unchanged) return { ...base, bucket: 'waiting', why: `${WAITING_ON_INPUTS.label}: its last run (${latest.outcome!.why}) left it with the inputs it has now` };
264
- const opening = [...notes].reverse().find((n) => OPENING_KINDS.includes(n.kind));
265
- return { ...base, bucket: 'queued', why: front && opening !== undefined ? `front of the queue, ${opening.kind}: ${opening.why}` : reopened ? 'reopened by another task' : tried.length === 0 ? 'not tried yet' : `tried ${tried.length} times` };
266
- };
185
+ export const queueOrder = (tasks: ReadonlyArray<TaskSummary>): ReadonlyArray<TaskSummary> =>
186
+ tasks.filter((t) => t.status === 'queued').sort((a, b) =>
187
+ (b.noted.front ?? 0) - (a.noted.front ?? 0) || a.since - b.since || a.noted.note - b.noted.note || a.id - b.id);
267
188
 
268
189
  /**
269
- * THE ONE ORDER OF A QUEUE, before the workflow's own: an urgent task; then a task reopened or given new input and not tried
270
- * since; then every other, one its workflow lists last (`Listed.last`) after every one it does not, and within each, one not
271
- * tried since its last success before one tried, the oldest try first. Negative when `a` goes first; a task with no summary
272
- * is one never tried. Pure.
190
+ * THE STANDARD REASON A PICK BLOCKS A QUEUED TASK FOR, none where none holds: `BLOCK_AFTER_TRIES` failed tries; or nothing
191
+ * new since its last failed try, where its workflow says what its tasks run on (`inputs`) and they are those its last
192
+ * failed run left it with. Flipping is read from its notes (`returnsToEarlierText`). Pure.
273
193
  */
274
- export const queueRank = (a: TaskSummary | undefined, b: TaskSummary | undefined): number => {
275
- const group = (t: TaskSummary | undefined) => {
276
- if (t?.urgent === true) return 0;
277
- if (t?.front === true) return 1;
278
- const last = t?.listed?.kind === 'line' && t.listed.last === true ? 2 : 0;
279
- return 2 + last + ((t?.tries ?? 0) === 0 ? 0 : 1);
280
- };
281
- const tried = (g: number) => g === 3 || g === 5;
282
- return group(a) - group(b) || (tried(group(a)) ? (a!.lastTryAt ?? 0) - (b!.lastTryAt ?? 0) : 0);
194
+ export const standardBlock = (task: TaskSummary, inputs: TaskInputs | undefined): string | null => {
195
+ if (task.status !== 'queued') return null;
196
+ if (task.tries >= BLOCK_AFTER_TRIES) return blockedAfterTries(task.tries);
197
+ if (task.noted.kind === 'outcome' && inputs !== undefined && task.noted.inputs === inputs.fingerprint) return BLOCKED_NOTHING_NEW;
198
+ return null;
283
199
  };
284
200
 
201
+ /** Whether a blocked task's reason has lapsed: it was blocked for nothing new, and its inputs now are not those it was blocked with. Pure. */
202
+ export const blockLapsed = (task: TaskSummary, inputs: TaskInputs | undefined): boolean =>
203
+ task.noted.status === 'blocked' && task.noted.why === BLOCKED_NOTHING_NEW && (inputs === undefined || inputs.fingerprint !== task.noted.inputs);
204
+
285
205
  /**
286
- * THE ORDER A PICK TAKES ITS CANDIDATES IN, given in the workflow's own order: none running, stuck, held or waiting on another
287
- * task (a candidate its workflow offers is work, whatever its last listing said), in the queue's one order (`queueRank`), one
288
- * reopened or given new input that the candidates do not hold built by `fromItem`; the workflow's own order within each
289
- * group. `alsoLeaveOut` names items the workflow knows are not to be taken. For a workflow whose Pick takes candidates of its
290
- * own; one whose Pick takes the head of its queue reads `queueOrder`. Pure.
206
+ * THE ORDER A PICK TAKES ITS OWN CANDIDATES IN, given in the workflow's own order: none blocked or in progress; those in
207
+ * its queue first, in the queue's order (`queueOrder`), then the rest in the workflow's own. A task a step or a person
208
+ * returned to the queue that the candidates do not hold is built by `fromItem`. `alsoLeaveOut` names items the workflow
209
+ * knows are not to be taken. For a workflow whose Pick takes candidates of its own; one whose Pick takes the head of its
210
+ * queue reads `queueOrder`. Pure.
291
211
  */
292
212
  export const inPickOrder = <C>(input: {
293
213
  readonly candidates: ReadonlyArray<C>;
@@ -297,55 +217,20 @@ export const inPickOrder = <C>(input: {
297
217
  readonly alsoLeaveOut?: ReadonlySet<string>;
298
218
  }): ReadonlyArray<C> => {
299
219
  const byItem = new Map(input.tasks.map((t) => [keyOf(t.ref.item), t]));
220
+ const place = new Map(queueOrder(input.tasks).map((t, i) => [keyOf(t.ref.item), i]));
300
221
  const leaveOut = new Set([...(input.alsoLeaveOut ?? [])].map(keyOf));
301
222
  const free = (item: string) => {
302
223
  const t = byItem.get(keyOf(item));
303
- return !leaveOut.has(keyOf(item)) && (t === undefined || t.bucket === 'queued' || t.bucket === 'done' || (t.bucket === 'waiting' && t.listed?.kind === 'wait'));
224
+ return !leaveOut.has(keyOf(item)) && (t === undefined || t.status === 'queued' || t.status === 'done');
304
225
  };
305
226
  const given = new Set(input.candidates.map((c) => keyOf(input.subjectOf(c))));
306
227
  const fromItem = input.fromItem;
307
228
  const built = fromItem === undefined ? [] : input.tasks
308
- .filter((t) => (t.reopened || t.front) && t.bucket === 'queued' && !given.has(keyOf(t.ref.item)) && free(t.ref.item))
229
+ .filter((t) => t.returned && t.status === 'queued' && !given.has(keyOf(t.ref.item)) && free(t.ref.item))
309
230
  .flatMap((t) => { const c = fromItem(t.ref.item); return c === null ? [] : [{ c, item: t.ref.item }]; });
310
231
  const open = [...input.candidates.filter((c) => free(input.subjectOf(c))).map((c) => ({ c, item: input.subjectOf(c) })), ...built]
311
- .map((o, i) => ({ c: o.c, i, t: byItem.get(keyOf(o.item)) }));
312
- return open.sort((a, b) => queueRank(a.t, b.t) || a.i - b.i).map((o) => o.c);
313
- };
314
-
315
- /**
316
- * A WORKFLOW'S QUEUE: its queued tasks, in the order its Pick takes them and a dashboard lists them: `queueRank`, then the
317
- * order its list gives (`Listed.position`), then the oldest task first. Pure.
318
- */
319
- export const queueOrder = (tasks: ReadonlyArray<TaskSummary>): ReadonlyArray<TaskSummary> => {
320
- const position = (t: TaskSummary) => (t.listed?.kind === 'line' && t.listed.position !== undefined ? t.listed.position : Number.MAX_SAFE_INTEGER);
321
- return tasks.filter((t) => t.bucket === 'queued').sort((a, b) => queueRank(a, b) || position(a) - position(b) || a.id - b.id);
322
- };
323
-
324
- /**
325
- * A WORKFLOW'S LIST AS ITS BUCKETS DRAW IT: the same items, a stuck or a held one on a line of its own and one waiting on a
326
- * task among the waits, so its gaps still equal its list; a reopened task the list does not hold on a line outside the gap.
327
- * Pure.
328
- */
329
- export const bucketView = (work: PendingWork, tasks: ReadonlyArray<TaskSummary>): PendingWork => {
330
- const byItem = new Map(tasks.map((t) => [keyOf(t.ref.item), t]));
331
- const bucketOfItem = (item: string) => byItem.get(keyOf(item))?.bucket ?? 'queued';
332
- const unchangedItem = (item: string) => byItem.get(keyOf(item))?.unchanged === true;
333
- const listed = work.lines.flatMap((l) => l.items);
334
- const moved = (bucket: Bucket) => listed.filter((i) => bucketOfItem(i) === bucket);
335
- const onList = new Set([...listed, ...work.waits.flatMap((w) => w.items)].map(keyOf));
336
- const reopened = tasks.filter((t) => t.reopened && t.bucket !== 'done' && !onList.has(keyOf(t.ref.item))).map((t) => t.ref.item);
337
- const line = (label: string, items: ReadonlyArray<string>, outsideGap = false) => (items.length === 0 ? [] : [{ label, items, ...(outsideGap ? { outsideGap: true as const } : {}) }]);
338
- const stays = (i: string) => !['stuck', 'held', 'waiting'].includes(bucketOfItem(i));
339
- return {
340
- lines: [
341
- ...work.lines.map((l) => ({ ...l, items: l.items.filter(stays) })),
342
- ...line(STUCK_LINE, moved('stuck')), ...line(HELD_LINE, moved('held')), ...line(REOPENED_LINE, reopened, true),
343
- ],
344
- waits: [
345
- ...work.waits,
346
- ...[{ ...WAITING_ON_A_TASK, items: moved('waiting').filter((i) => !unchangedItem(i)) }, { ...WAITING_ON_INPUTS, items: moved('waiting').filter(unchangedItem) }].filter((w) => w.items.length > 0),
347
- ],
348
- };
232
+ .map((o, i) => ({ c: o.c, i, at: place.get(keyOf(o.item)) ?? Number.MAX_SAFE_INTEGER }));
233
+ return open.sort((a, b) => a.at - b.at || a.i - b.i).map((o) => o.c);
349
234
  };
350
235
 
351
236
  /** A task's notes as its run's agent reads them: every note but an outcome, and its last 3 outcomes, newest last. Pure. */
@@ -361,30 +246,49 @@ export const notesText = (notes: ReadonlyArray<TaskNote>, limit = 4000): string
361
246
  return kept.join('\n\n');
362
247
  };
363
248
 
364
- /** A workflow's tasks counted by bucket. Pure. */
365
- export const bucketCounts = (tasks: ReadonlyArray<TaskSummary>): Readonly<Record<Bucket, number>> =>
366
- Object.fromEntries(BUCKETS.map((b) => [b, tasks.filter((t) => t.bucket === b).length])) as Record<Bucket, number>;
249
+ /** How many of a workflow's tasks are blocked for one reason. */
250
+ export interface BlockedReason {
251
+ readonly why: string;
252
+ readonly tasks: number;
253
+ }
254
+
255
+ /**
256
+ * WHY A WORKFLOW'S BLOCKED TASKS ARE BLOCKED, most tasks first: a count for each reason, so a page says the reason beside
257
+ * the number. Reasons that differ only by a count or by which task is waited on are one reason. Pure.
258
+ */
259
+ export const blockedReasons = (tasks: ReadonlyArray<TaskSummary>): ReadonlyArray<BlockedReason> => {
260
+ 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);
261
+ const counts = new Map<string, number>();
262
+ for (const t of tasks) if (t.status === 'blocked') counts.set(reason(t), (counts.get(reason(t)) ?? 0) + 1);
263
+ return [...counts].map(([why, n]) => ({ why, tasks: n })).sort((a, b) => b.tasks - a.tasks || a.why.localeCompare(b.why));
264
+ };
265
+
266
+ /** A workflow's tasks counted by status: every status, a zero as much as any other, so they add up to its tasks. Pure. */
267
+ export const statusCounts = (tasks: ReadonlyArray<TaskSummary>): Readonly<Record<TaskStatus, number>> =>
268
+ Object.fromEntries(TASK_STATUSES.map((s) => [s, tasks.filter((t) => t.status === s).length])) as Record<TaskStatus, number>;
367
269
 
368
270
  // -------------------------------------------------------------------------------------------------------------- stored
369
271
 
370
- /** The task queue of one project: its rules applied to its stored tasks, every write waking the Picks it can change. */
272
+ /** The task queue of one project: the rules above applied to its stored tasks, every write waking the Picks it can change. */
371
273
  export const makeTasks = (deps: {
372
274
  readonly store: TaskStore;
373
275
  readonly engine: EngineRecords;
374
276
  readonly stepRecords: StepRecords;
375
277
  readonly wakes: PickWakes;
376
278
  readonly texts: TextStore;
377
- readonly rules: TaskRules;
378
279
  }) => {
379
280
  const { store, wakes } = deps;
380
281
 
381
- /** Any note can change what its workflow's Pick can claim; the wake reaches it once this write has committed. */
282
+ /** A note can change what its workflow's Pick can claim; the wake reaches it once this write has committed, once per workflow. */
382
283
  const appended = (notes: ReadonlyArray<NewNote>, ids: ReadonlyArray<number | null>): void => {
383
- notes.forEach((n, k) => { if (ids[k] !== null) wakes.wakePicksOf(n.task.workflow, `a note on one of its tasks: ${n.kind}`); });
284
+ const woken = new Map<string, string>();
285
+ notes.forEach((n, k) => { if (ids[k] !== null && !woken.has(n.task.workflow)) woken.set(n.task.workflow, n.kind); });
286
+ for (const [workflow, kind] of woken) wakes.wakePicksOf(workflow, `a note on one of its tasks: ${kind}`);
384
287
  };
385
288
 
386
289
  /** A write a step asks for: it fails, typed, rather than going missing. */
387
290
  const inStore = (notes: ReadonlyArray<NewNote>): Effect.Effect<ReadonlyArray<number | null>, TaskStoreError> => Effect.suspend(() => {
291
+ if (notes.length === 0) return Effect.succeed([]);
388
292
  if (!store.writable()) return Effect.fail(new TaskStoreError({ reason: 'no task store is open: a test names one' }));
389
293
  return pipe(
390
294
  store.append(notes),
@@ -410,7 +314,7 @@ export const makeTasks = (deps: {
410
314
  readonly aboutSha?: string;
411
315
  readonly change?: { readonly before: string; readonly after: string; readonly flags: string };
412
316
  }): Effect.Effect<TaskNote, TaskStoreError> => Effect.gen(function* () {
413
- if ((ENGINE_NOTE_KINDS as ReadonlyArray<string>).includes(input.kind)) return yield* Effect.fail(new TaskStoreError({ reason: `'${input.kind}' is a kind only the engine writes` }));
317
+ if (ENGINE_NOTE_KINDS.includes(input.kind)) return yield* Effect.fail(new TaskStoreError({ reason: `'${input.kind}' is a kind only the engine writes` }));
414
318
  const change = input.change === undefined ? undefined : {
415
319
  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),
416
320
  };
@@ -427,69 +331,80 @@ export const makeTasks = (deps: {
427
331
  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)}` }) });
428
332
 
429
333
  /**
430
- * Another task's work is needed first: `task` goes back to queued, done or not, ahead of its workflow's other items, and
431
- * `waiting` waits on it until it finishes. Both get a note.
334
+ * PUTS A TASK BACK IN ITS QUEUE, done or blocked or not: it joins the back, and its count of failed tries starts again.
335
+ * `input` is new text for its next run, stored by hash and read with `noteText(note.inputSha)`.
336
+ */
337
+ const requeue = (input: { readonly task: TaskRef; readonly by: NoteBy; readonly why: string; readonly input?: string; readonly about?: TaskRef }): Effect.Effect<void, TaskStoreError> =>
338
+ Effect.gen(function* () {
339
+ const inputSha = input.input === undefined ? undefined : yield* storeText(input.input, 'the input');
340
+ yield* inStore([{ task: input.task, by: input.by, kind: 'queued', why: input.why, ...(input.about === undefined ? {} : { about: input.about }), ...(inputSha === undefined ? {} : { inputSha }) }]);
341
+ });
342
+
343
+ /**
344
+ * 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
345
+ * puts it back (`requeue`). `inputs` is what it ran on when it was blocked, where the reason is that nothing is new.
346
+ */
347
+ const block = (input: { readonly task: TaskRef; readonly by: NoteBy; readonly why: string; readonly about?: TaskRef; readonly inputs?: string }): Effect.Effect<void, TaskStoreError> =>
348
+ 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 }) }]));
349
+
350
+ /**
351
+ * Another task's work is needed first: `task` goes back to its queue, done or not, and `waiting` is blocked on it until it
352
+ * finishes, when it goes back to its own (`appendOutcome`). Both get a note.
432
353
  */
433
354
  const reopen = (input: { readonly task: TaskRef; readonly waiting: TaskRef; readonly by: NoteBy; readonly why: string }): Effect.Effect<void, TaskStoreError> =>
434
355
  Effect.asVoid(inStore([
435
- { task: input.task, by: input.by, kind: 'reopened', why: input.why, about: input.waiting },
436
- { task: input.waiting, by: input.by, kind: 'waits on', why: input.why, about: input.task },
356
+ { task: input.task, by: input.by, kind: 'queued', why: input.why, about: input.waiting },
357
+ { task: input.waiting, by: input.by, kind: 'blocked', why: `waits on ${input.task.workflow} ${input.task.item}: ${input.why}`, about: input.task },
437
358
  ]));
438
359
 
439
360
  /**
440
- * NEW INPUT FOR A TASK, FROM ANOTHER WORKFLOW OR STEP: it goes to the front of its workflow's queue, done or not, until a run
441
- * has tried it, and its count of runs starts again. `input` is stored by hash and read with `noteText(note.inputSha)`.
361
+ * THE ESCAPE HATCH: moves tasks of one workflow to the front of its queue, in the order given, ahead of every task moved
362
+ * 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.
442
363
  */
443
- const giveNewInput = (input: { readonly task: TaskRef; readonly by: NoteBy; readonly why: string; readonly input?: string; readonly about?: TaskRef }): Effect.Effect<void, TaskStoreError> =>
364
+ 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> =>
444
365
  Effect.gen(function* () {
445
- const inputSha = input.input === undefined ? undefined : yield* storeText(input.input, 'the input');
446
- yield* inStore([{ task: input.task, by: input.by, kind: 'new input', why: input.why, ...(input.about === undefined ? {} : { about: input.about }), ...(inputSha === undefined ? {} : { inputSha }) }]);
366
+ const states = yield* Effect.mapError(store.statesOf(input.workflow), (e) => new TaskStoreError({ reason: e.reason }));
367
+ const own = new Map(states.map((s) => [keyOf(s.ref.item), s.ref.item]));
368
+ const named = [...new Map(input.items.map((item) => [keyOf(item), item])).values()];
369
+ const moved = named.flatMap((item) => { const stored = own.get(keyOf(item)); return stored === undefined ? [] : [stored]; });
370
+ // The last note written is the first in the queue, so they are written last first.
371
+ yield* inStore([...moved].reverse().map((item) => ({ task: { workflow: input.workflow, item }, by: input.by, kind: MOVED_TO_FRONT, why: input.why })));
372
+ return { moved, notItsTasks: named.filter((item) => !own.has(keyOf(item))) };
447
373
  });
448
374
 
449
- /** Holds a task from automatic work until it is released. */
450
- const hold = (input: { readonly task: TaskRef; readonly by: NoteBy; readonly why: string }): Effect.Effect<void, TaskStoreError> =>
451
- Effect.asVoid(inStore([{ task: input.task, by: input.by, kind: 'held', why: input.why }]));
452
-
453
- /** Takes a task out of the stuck or held bucket: its count of runs starts again from now. False where nothing could be written. */
454
- const releaseTask = (input: { readonly task: TaskRef; readonly why: string }): Effect.Effect<boolean> => {
455
- const note: NewNote = { task: input.task, by: { workflow: null, run: null, step: null }, kind: 'released', why: input.why };
456
- return Effect.map(engineWrite(`release ${input.task.workflow} ${input.task.item}`, store.append([note])), (ids) => {
457
- if (ids === null) return false;
458
- appended([note], ids);
459
- return true;
460
- });
461
- };
462
-
463
375
  /**
464
- * WHAT BECAME OF ONE ITEM WHEN ITS RUN ENDED, on its task, with the run and the step it ended on. One that finished the task
465
- * resumes every task waiting on it, with a note on both. Run again on a resume, it keeps the first.
376
+ * 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
377
+ * run's step blocked it, where it did. One that finished the task returns every task blocked waiting on it to its queue.
378
+ * Run again on a resume, it keeps the first.
466
379
  */
467
- const appendOutcome = (r: { readonly workflow: string; readonly run: string; readonly subject: string | null; readonly outcome: string; readonly finished: boolean; readonly inputs: string | null }): Effect.Effect<void> => Effect.gen(function* () {
380
+ 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* () {
468
381
  const item = r.subject ?? (yield* engineWrite(`the item of run ${r.run}`, deps.stepRecords.subjectOfRun(r.run)));
469
382
  if (item === null) return;
470
383
  const task = { workflow: r.workflow, item };
471
384
  const by = { workflow: r.workflow, run: r.run, step: (yield* engineWrite(`the step of run ${r.run}`, deps.stepRecords.stepOfRun(r.run)))?.step ?? null };
472
385
  const done = yield* engineWrite(`outcome of run ${r.run}`, store.appendOutcome({
473
- task, by, why: r.outcome, finished: r.finished, inputs: r.inputs,
474
- resumedWhy: (w) => ({ resumed: `${r.workflow} ${item} finished (${r.outcome}), so this goes back to queued`, waiterResumed: `${w.workflow} ${w.item} waited on this, and goes back to queued` }),
386
+ task, by, why: r.outcome, finished: r.finished, inputs: r.inputs, blocked: r.blocked,
387
+ resumedWhy: () => `${r.workflow} ${item} finished (${r.outcome}), so this goes back to its queue`,
475
388
  }));
476
389
  if (done === null || !done.appended) return;
477
390
  wakes.wakePicksOf(r.workflow, 'a note on one of its tasks: outcome');
478
- for (const w of done.resumed) wakes.wakePicksOf(w.workflow, 'a note on one of its tasks: resumed');
391
+ for (const w of done.resumed) wakes.wakePicksOf(w.workflow, 'a note on one of its tasks: queued');
479
392
  });
480
393
 
481
- /** Where a workflow's list puts each of its items now: the engine's one reading of it, which makes its tasks. */
482
- const recordListing = (workflow: string, work: PendingWork): Effect.Effect<void> => Effect.gen(function* () {
394
+ /**
395
+ * WHERE A WORKFLOW'S LIST PUTS EACH OF ITS ITEMS NOW: the engine's one reading of it, which makes its tasks
396
+ * (`TaskStore.recordListing`, where the two kinds of list are written down). `everyItem`: the list is every item it has,
397
+ * done or not; otherwise only its work left.
398
+ */
399
+ const recordListing = (input: { readonly workflow: string; readonly work: PendingWork; readonly everyItem: boolean; readonly readAt?: number }): Effect.Effect<void> => Effect.gen(function* () {
483
400
  const at = new Map<string, { readonly item: string; readonly listed: Listed }>();
484
- const last = new Set((work.last ?? []).map(keyOf));
485
- let position = 0;
486
- for (const l of work.lines) {
487
- for (const item of l.items) at.set(keyOf(item), { item, listed: { kind: 'line', label: l.label, position: position++, ...(last.has(keyOf(item)) ? { last: true as const } : {}) } });
488
- }
489
- for (const w of work.waits) for (const item of w.items) at.set(keyOf(item), { item, listed: { kind: 'wait', label: w.label, on: w.on } });
490
- const fresh = yield* engineWrite(`the list of ${workflow}`, store.recordListing({ workflow, listed: [...at.values()] }));
491
- // An item new to the list is work its Pick may claim; the list read again with the same items wakes nothing.
492
- if (fresh === true) wakes.wakePicksOf(workflow, 'an item new to its list');
401
+ for (const l of input.work.lines) for (const item of l.items) at.set(keyOf(item), { item, listed: { kind: 'line', label: l.label } });
402
+ 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 } });
403
+ const recorded = yield* engineWrite(`the list of ${input.workflow}`, store.recordListing({
404
+ workflow: input.workflow, listed: [...at.values()], everyItem: input.everyItem, readAt: input.readAt ?? Date.now() / 1000, by: { workflow: input.workflow, run: null, step: null },
405
+ }));
406
+ // 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.
407
+ if (recorded?.fresh === true) wakes.wakePicksOf(input.workflow, 'an item new to its list');
493
408
  });
494
409
 
495
410
  /** The items each workflow's unfinished runs are on now, lower case; a run named in `excludingRun` is left out. */
@@ -505,52 +420,71 @@ export const makeTasks = (deps: {
505
420
  return out;
506
421
  });
507
422
 
508
- const summarizeAll = (facts: ReadonlyArray<TaskFacts>, running: ReadonlyMap<string, ReadonlySet<string>>, inputs?: ReadonlyMap<string, TaskInputs>): Effect.Effect<ReadonlyArray<TaskSummary>, StorageError> => Effect.gen(function* () {
509
- const waitedOn = [...new Map(facts.flatMap((f) => openWaits(f.notes)).map((t) => [`${t.workflow}\0${keyOf(t.item)}`, t])).values()];
510
- const others = (yield* Effect.forEach(waitedOn, (t) => store.task(t))).flatMap((f) => (f === null ? [] : [f]));
511
- const isRunning = (ref: TaskRef) => running.get(ref.workflow)?.has(keyOf(ref.item)) === true;
512
- const done = (t: TaskRef) => {
513
- const f = others.find((o) => sameTask(o.ref, t));
514
- return f === undefined || isDone(f, isRunning(t));
515
- };
516
- return facts.map((f) => {
517
- const own = inputs?.get(keyOf(f.ref.item));
518
- return summarize({ facts: f, running: isRunning(f.ref), done, rules: deps.rules, ...(own === undefined ? {} : { inputs: own }) });
519
- });
520
- });
521
-
522
423
  /**
523
- * EACH TASK'S INPUTS AS ITS WORKFLOW LAST READ THEM (`steps.ts` `queueNow`, at each Pick and each reading of its list), by
524
- * item in lower case: what every summary of its tasks is made with, so a page and a Pick put a task in one bucket.
424
+ * EACH TASK'S INPUTS AS ITS WORKFLOW LAST READ THEM (`steps.ts` `readTaskInputs`, at each Pick), by item in lower case:
425
+ * what `settleQueue` blocks a task with nothing new by.
525
426
  */
526
427
  const inputsRead = new Map<string, ReadonlyMap<string, TaskInputs>>();
527
428
  const recordTaskInputs = (workflow: string, inputs: ReadonlyMap<string, TaskInputs>): void => { inputsRead.set(workflow, inputs); };
528
429
 
430
+ /** Every task of a workflow and the status it is in now. `running` is for a test. */
431
+ const taskSummaries = (input: { readonly workflow: string; readonly excludingRun?: string; readonly running?: ReadonlyMap<string, ReadonlySet<string>> }): Effect.Effect<ReadonlyArray<TaskSummary>, StorageError> => Effect.gen(function* () {
432
+ const states = yield* store.statesOf(input.workflow);
433
+ const running = (input.running ?? (yield* itemsRunningNow(input.excludingRun))).get(input.workflow);
434
+ return states.map((state) => summarize({ state, running: running?.has(keyOf(state.ref.item)) === true }));
435
+ });
436
+
529
437
  /**
530
- * Every task of a workflow and the bucket it is in now, with its inputs as last read (`recordTaskInputs`). `running` is for
531
- * a test.
438
+ * THE STANDARD BLOCKING, RUN BY THE STEP THAT PICKS, before it reads its queue: each queued task a standard reason holds
439
+ * for is blocked with it (`standardBlock`, and flipping, read from the notes of a task with enough changes to flip), and
440
+ * each blocked task whose reason has lapsed goes back to the queue (`blockLapsed`). `by` is the Pick. Returns the
441
+ * workflow's tasks as that leaves them, another run's left in progress and `excludingRun`'s own free.
532
442
  */
533
- const taskSummaries = (input: { readonly workflow: string; readonly excludingRun?: string; readonly running?: ReadonlyMap<string, ReadonlySet<string>> }): Effect.Effect<ReadonlyArray<TaskSummary>, StorageError> => Effect.gen(function* () {
534
- const facts = yield* store.tasksOf(input.workflow);
535
- const running = input.running ?? (yield* itemsRunningNow(input.excludingRun));
536
- return yield* summarizeAll(facts, running, inputsRead.get(input.workflow));
443
+ const settleQueue = (input: { readonly workflow: string; readonly by: NoteBy; readonly excludingRun?: string }): Effect.Effect<ReadonlyArray<TaskSummary>, StorageError> => Effect.gen(function* () {
444
+ const tasks = yield* taskSummaries({ workflow: input.workflow, ...(input.excludingRun === undefined ? {} : { excludingRun: input.excludingRun }) });
445
+ if (!store.writable()) return tasks;
446
+ const inputs = inputsRead.get(input.workflow);
447
+ const notes: NewNote[] = [];
448
+ const settled: TaskSummary[] = [];
449
+ for (const t of tasks) {
450
+ const own = inputs?.get(keyOf(t.ref.item));
451
+ if (t.status === 'queued') {
452
+ const flips = t.noted.changes < CHANGES_THAT_CAN_FLIP ? 0 : returnsToEarlierText(yield* store.notes(t.ref));
453
+ const why = flips >= BLOCK_AFTER_RETURNS ? BLOCKED_FLIPPING : standardBlock(t, own);
454
+ if (why !== null) {
455
+ notes.push({ task: t.ref, by: input.by, kind: 'blocked', why, ...(t.noted.inputs === null ? {} : { inputs: t.noted.inputs }) });
456
+ settled.push({ ...t, status: 'blocked', why });
457
+ continue;
458
+ }
459
+ }
460
+ if (t.status === 'blocked' && blockLapsed(t, own)) {
461
+ notes.push({ task: t.ref, by: input.by, kind: 'unblocked', why: UNBLOCKED_INPUTS_CHANGED });
462
+ settled.push({ ...t, status: 'queued', why: UNBLOCKED_INPUTS_CHANGED, since: Date.now() / 1000 });
463
+ continue;
464
+ }
465
+ settled.push(t);
466
+ }
467
+ if (notes.length === 0) return tasks;
468
+ const written = yield* Effect.result(store.append(notes));
469
+ // Unwritten, nothing was settled: the tasks stand as they were read, and the next Pick tries again.
470
+ if (written._tag === 'Failure') return yield* Effect.as(Effect.logError(`[tasks] ${input.workflow}: its queue could not be settled: ${written.failure.reason}`), tasks);
471
+ return settled;
537
472
  });
538
473
 
539
- /** One task's bucket now, and why; a task no workflow has named yet is queued. */
540
- const bucketOf = (task: TaskRef): Effect.Effect<TaskSummary, StorageError> => Effect.gen(function* () {
541
- const facts = yield* store.task(task);
542
- const summary = facts === null ? undefined : (yield* summarizeAll([facts], yield* itemsRunningNow(), inputsRead.get(task.workflow)))[0];
543
- return summary
544
- ?? { id: 0, ref: task, bucket: 'queued', why: 'no workflow has named it yet', tries: 0, lastTryAt: null, lastOutcome: null, reopened: false, front: false, urgent: false, unchanged: false, listed: null };
474
+ /** One task's status now, and why; a task no workflow has named yet is queued. */
475
+ const statusOf = (task: TaskRef): Effect.Effect<TaskSummary, StorageError> => Effect.gen(function* () {
476
+ 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 };
477
+ return summarize({ state, running: (yield* itemsRunningNow()).get(task.workflow)?.has(keyOf(task.item)) === true });
545
478
  });
546
479
 
547
480
  /** What a run's agent is told of its own task: its notes, as `notesText` words them; empty with none, or with no store. */
548
481
  const notesForAgent = (task: TaskRef): Effect.Effect<string, StorageError> => (store.writable() ? Effect.map(store.notes(task), (notes) => notesText(notes)) : Effect.succeed(''));
549
482
 
550
483
  return {
551
- appendTaskNote, noteText, reopen, giveNewInput, hold, releaseTask, appendOutcome, recordListing, recordTaskInputs,
552
- taskNotes: store.notes, taskIdOf: store.taskId, itemsRunningNow, taskSummaries, bucketOf, notesForAgent,
484
+ appendTaskNote, noteText, requeue, block, reopen, moveToFront, appendOutcome, recordListing, recordTaskInputs,
485
+ taskNotes: store.notes, taskIdOf: store.taskId, itemsRunningNow, taskSummaries, settleQueue, statusOf, notesForAgent,
553
486
  };
554
487
  };
555
488
 
556
489
  export type Tasks = ReturnType<typeof makeTasks>;
490
+