@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/dist/tasks.js CHANGED
@@ -1,59 +1,61 @@
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
24
36
  * (`notesForAgent`). Where tasks live is the task store's business (`storage/task-store.ts`).
25
37
  */
26
38
  import { Data, Effect, pipe } from 'effect';
27
- export const BUCKETS = ['queued', 'running', 'waiting', 'stuck', 'held', 'done'];
28
- /** Each bucket in the page's words. */
29
- export const BUCKET_WORDS = {
30
- queued: 'queued', running: 'running', waiting: 'waiting', stuck: 'stuck', held: 'held', done: 'done',
31
- };
32
- /** The kinds only the engine writes. */
33
- export const ENGINE_NOTE_KINDS = ['outcome', 'reopened', 'new input', 'waits on', 'resumed', 'waiter resumed', 'released', 'held'];
34
- /**
35
- * 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
36
- * task reopened it, a workflow or step gave it new input, or the task it waited on finished, so what it needed has changed.
37
- */
38
- const OPENING_KINDS = ['reopened', 'new input', 'resumed'];
39
- /** Runs of one workflow on one item with no success after which it is stuck: it gets no agent again until released. */
40
- export const STUCK_AFTER_RUNS = 10;
41
- /** Returns to an earlier text after which a task is held from automatic edits. */
42
- export const HOLD_AFTER_RETURNS = 2;
43
- /** The lines its buckets put a task on in the workflow's list as the page draws it. */
44
- export const STUCK_LINE = `stuck: no success in over ${STUCK_AFTER_RUNS} runs`;
45
- export const HELD_LINE = 'held: undone and redone, or held by a step';
46
- export const REOPENED_LINE = 'reopened by another task, outside this phase\'s gap';
47
- export const WAITING_ON_A_TASK = { on: 'another task', label: 'waiting on another task' };
48
- export const WAITING_ON_INPUTS = { on: 'its inputs', label: 'waits for its inputs to change' };
49
- /** The outcome of a run that stood down for its workflow's budget: no agent was called, so it is no try. */
50
- export const STOOD_DOWN_OUTCOME = 'stood down';
39
+ import { MOVED_TO_FRONT, STATUS_KINDS, TRIES_START_AGAIN_KINDS } from './storage/task-store';
40
+ export { STOOD_DOWN_OUTCOME, TRIES_START_AGAIN_KINDS } from './storage/task-store';
41
+ export const TASK_STATUSES = ['queued', 'in progress', 'blocked', 'done'];
42
+ /** The kinds only the engine writes: a step's own note takes another. */
43
+ export const ENGINE_NOTE_KINDS = ['outcome', MOVED_TO_FRONT, ...Object.keys(STATUS_KINDS), 'waiter resumed'];
44
+ /** 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. */
45
+ export const BLOCK_AFTER_TRIES = 10;
46
+ /** Returns to an earlier text after which a Pick blocks a task as flipping between two versions. */
47
+ export const BLOCK_AFTER_RETURNS = 2;
48
+ /** The standard reasons a Pick blocks a task for, in the words its page shows. */
49
+ export const BLOCKED_NOTHING_NEW = 'nothing new since its last failed try';
50
+ export const BLOCKED_FLIPPING = 'it keeps flipping between two versions';
51
+ export const blockedAfterTries = (tries) => `${tries} failed tries`;
52
+ /** Why a task blocked for nothing new went back to its queue. */
53
+ export const UNBLOCKED_INPUTS_CHANGED = 'something new since its last failed try';
51
54
  /** A workflow's list of work: every item on its lines. */
52
55
  export const listOf = (work) => work.lines.flatMap((l) => l.items);
53
56
  export class TaskStoreError extends Data.TaggedError('TaskStoreError') {
54
57
  }
55
58
  const keyOf = (item) => item.toLowerCase();
56
- const sameTask = (a, b) => a.workflow === b.workflow && keyOf(a.item) === keyOf(b.item);
57
59
  // ---------------------------------------------------------------------------------------------------------------- pure
58
60
  /** The lines removed (`-`) and added (`+`), with 2 lines around each and `@@ line N` before each run. Pure. */
59
61
  export const lineDiff = (before, after) => {
@@ -95,24 +97,20 @@ export const lineDiff = (before, after) => {
95
97
  });
96
98
  return out.join('\n');
97
99
  };
98
- const lastAt = (notes, test) => {
99
- for (let k = notes.length - 1; k >= 0; k -= 1)
100
- if (test(notes[k]))
101
- return notes[k].at;
102
- return null;
103
- };
104
- /** Notes after the task's last release. */
105
- const sinceRelease = (notes) => {
106
- const released = notes.map((n) => n.kind).lastIndexOf('released');
107
- return notes.slice(released + 1);
100
+ /** Notes after the task was last returned to its queue by a step or a person. */
101
+ const sinceReturned = (notes) => {
102
+ let returned = -1;
103
+ notes.forEach((n, k) => { if (TRIES_START_AGAIN_KINDS.includes(n.kind))
104
+ returned = k; });
105
+ return notes.slice(returned + 1);
108
106
  };
109
107
  /**
110
- * 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
111
- * order, each change's before and after, a change that changed nothing left out. Pure.
108
+ * 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
109
+ * queue: its texts in order, each change's before and after, a change that changed nothing left out. Pure.
112
110
  */
113
111
  export const returnsToEarlierText = (notes) => {
114
112
  const texts = [];
115
- for (const n of sinceRelease(notes)) {
113
+ for (const n of sinceReturned(notes)) {
116
114
  if (n.change === null)
117
115
  continue;
118
116
  for (const sha of [n.change.beforeSha, n.change.afterSha])
@@ -121,169 +119,71 @@ export const returnsToEarlierText = (notes) => {
121
119
  }
122
120
  return texts.filter((sha, i) => i >= 2 && texts[i - 2] === sha).length;
123
121
  };
124
- /** Whether a task's reopen or new input is still open: after its last finished outcome. Pure. */
125
- const openReopen = (notes) => {
126
- // By the notes' order, as `atFront`, not their times: two notes written in one millisecond tie on time.
127
- let opened = -1;
128
- let finished = -1;
129
- notes.forEach((n, k) => { if (OPENING_KINDS.includes(n.kind))
130
- opened = k; if (n.kind === 'outcome' && n.finished === true)
131
- finished = k; });
132
- return opened >= 0 && opened > finished;
133
- };
134
- /** Whether a task is at the front of its queue: reopened or given new input after its last run's outcome. Pure. */
135
- const atFront = (notes) => {
136
- let opened = -1;
137
- let tried = -1;
138
- notes.forEach((n, k) => { if (OPENING_KINDS.includes(n.kind))
139
- opened = k; if (n.kind === 'outcome')
140
- tried = k; });
141
- return opened > tried;
142
- };
143
- /** A task's newest outcome, and whether a note opened it again after it, by the notes' order. Pure. */
144
- const newestOutcome = (notes) => {
145
- let openedSince = false;
146
- for (let k = notes.length - 1; k >= 0; k -= 1) {
147
- const n = notes[k];
148
- if (OPENING_KINDS.includes(n.kind))
149
- openedSince = true;
150
- if (n.kind === 'outcome')
151
- return { outcome: n, openedSince };
152
- }
153
- return { outcome: null, openedSince };
154
- };
155
- /**
156
- * 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
157
- * it with. Never for a workflow that declares no task inputs. Pure.
158
- */
159
- const inputsUnchanged = (newest, inputs) => inputs !== undefined && newest.outcome !== null && !newest.openedSince && newest.outcome.inputs === inputs.fingerprint;
160
- /** Done: off its workflow's list, no run on it and no reopen open. Pure. */
161
- export const isDone = (facts, running) => !running && facts.listed === null && !openReopen(facts.notes);
162
- /** The other tasks this one waits on and has not been resumed from, oldest first. Pure. */
163
- export const openWaits = (notes) => {
164
- const open = [];
165
- for (const n of notes) {
166
- if (n.about === null)
167
- continue;
168
- if (n.kind === 'waits on' && !open.some((o) => sameTask(o, n.about)))
169
- open.push(n.about);
170
- if (n.kind === 'resumed') {
171
- const at = open.findIndex((o) => sameTask(o, n.about));
172
- if (at >= 0)
173
- open.splice(at, 1);
174
- }
175
- }
176
- return open;
177
- };
178
- /** 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. */
122
+ /** Fewer changes of its text than this cannot hold `BLOCK_AFTER_RETURNS` returns to an earlier one: its notes are not read. */
123
+ export const CHANGES_THAT_CAN_FLIP = BLOCK_AFTER_RETURNS + 1;
124
+ /** A task's status and why, from what its notes say and whether a run is on it. Pure. */
179
125
  export const summarize = (input) => {
180
- const { facts, running } = input;
181
- const notes = facts.notes;
182
- const reset = Math.max(lastAt(notes, (n) => n.kind === 'outcome' && n.finished === true) ?? -Infinity, lastAt(notes, (n) => n.kind === 'released' || OPENING_KINDS.includes(n.kind)) ?? -Infinity);
183
- const tried = notes.filter((n) => n.kind === 'outcome' && n.finished !== true && n.why !== STOOD_DOWN_OUTCOME && n.at > reset);
184
- const newest = tried[tried.length - 1];
185
- const reopened = openReopen(notes);
186
- const front = atFront(notes);
187
- const latest = newestOutcome(notes);
188
- // A stand-down is no try, and a finished task is done: neither waits on its inputs here.
189
- const unchanged = inputsUnchanged(latest, input.inputs) && latest.outcome.why !== STOOD_DOWN_OUTCOME && latest.outcome.finished !== true;
190
- 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 };
126
+ const { state, running } = input;
127
+ const base = {
128
+ id: state.id, ref: state.ref, tries: state.tries, since: state.since, listed: state.listed, noted: state,
129
+ movedToFront: state.front !== null,
130
+ returned: state.returned,
131
+ };
191
132
  if (running)
192
- return { ...base, bucket: 'running', why: 'a run is on it now' };
193
- if (isDone(facts, false))
194
- return { ...base, bucket: 'done', why: 'its workflow\'s list no longer holds it' };
195
- if (facts.listed?.kind === 'wait')
196
- return { ...base, bucket: 'waiting', why: `waits on ${facts.listed.on}: ${facts.listed.label}` };
197
- const waitingOn = openWaits(notes).filter((t) => !input.done(t));
198
- if (waitingOn.length > 0)
199
- return { ...base, bucket: 'waiting', why: `waits on ${waitingOn.map((t) => `${t.workflow} ${t.item}`).join(', ')}` };
200
- const held = sinceRelease(notes).filter((n) => n.kind === 'held');
201
- if (held.length > 0)
202
- return { ...base, bucket: 'held', why: held[held.length - 1].why };
203
- const returns = returnsToEarlierText(notes);
204
- if (returns >= HOLD_AFTER_RETURNS)
205
- 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` };
206
- if (tried.length > STUCK_AFTER_RUNS)
207
- return { ...base, bucket: 'stuck', why: `${tried.length} runs with no success since its last` };
208
- if (unchanged)
209
- return { ...base, bucket: 'waiting', why: `${WAITING_ON_INPUTS.label}: its last run (${latest.outcome.why}) left it with the inputs it has now` };
210
- const opening = [...notes].reverse().find((n) => OPENING_KINDS.includes(n.kind));
211
- 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` };
133
+ return { ...base, status: 'in progress', why: 'a run is on it now' };
134
+ if (state.listed?.kind === 'wait')
135
+ return { ...base, status: 'blocked', why: state.listed.label };
136
+ if (state.status === 'done')
137
+ return { ...base, status: 'done', why: state.why ?? 'its final check passed' };
138
+ if (state.status === 'blocked')
139
+ return { ...base, status: 'blocked', why: state.why ?? 'blocked by a step' };
140
+ 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}`;
141
+ return { ...base, status: 'queued', why: state.front === null ? said : `moved to the front by hand; ${said}` };
212
142
  };
213
143
  /**
214
- * 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
215
- * since; then every other, one its workflow lists last (`Listed.last`) after every one it does not, and within each, one not
216
- * tried since its last success before one tried, the oldest try first. Negative when `a` goes first; a task with no summary
217
- * is one never tried. Pure.
144
+ * THE ONE ORDER OF A QUEUE: first in, first out, by when each task entered it, after the tasks the reorder call moved to
145
+ * the front, the last moved first. Pure.
218
146
  */
219
- export const queueRank = (a, b) => {
220
- const group = (t) => {
221
- if (t?.urgent === true)
222
- return 0;
223
- if (t?.front === true)
224
- return 1;
225
- const last = t?.listed?.kind === 'line' && t.listed.last === true ? 2 : 0;
226
- return 2 + last + ((t?.tries ?? 0) === 0 ? 0 : 1);
227
- };
228
- const tried = (g) => g === 3 || g === 5;
229
- return group(a) - group(b) || (tried(group(a)) ? (a.lastTryAt ?? 0) - (b.lastTryAt ?? 0) : 0);
147
+ export const queueOrder = (tasks) => tasks.filter((t) => t.status === 'queued').sort((a, b) => (b.noted.front ?? 0) - (a.noted.front ?? 0) || a.since - b.since || a.noted.note - b.noted.note || a.id - b.id);
148
+ /**
149
+ * THE STANDARD REASON A PICK BLOCKS A QUEUED TASK FOR, none where none holds: `BLOCK_AFTER_TRIES` failed tries; or nothing
150
+ * new since its last failed try, where its workflow says what its tasks run on (`inputs`) and they are those its last
151
+ * failed run left it with. Flipping is read from its notes (`returnsToEarlierText`). Pure.
152
+ */
153
+ export const standardBlock = (task, inputs) => {
154
+ if (task.status !== 'queued')
155
+ return null;
156
+ if (task.tries >= BLOCK_AFTER_TRIES)
157
+ return blockedAfterTries(task.tries);
158
+ if (task.noted.kind === 'outcome' && inputs !== undefined && task.noted.inputs === inputs.fingerprint)
159
+ return BLOCKED_NOTHING_NEW;
160
+ return null;
230
161
  };
162
+ /** 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. */
163
+ export const blockLapsed = (task, inputs) => task.noted.status === 'blocked' && task.noted.why === BLOCKED_NOTHING_NEW && (inputs === undefined || inputs.fingerprint !== task.noted.inputs);
231
164
  /**
232
- * THE ORDER A PICK TAKES ITS CANDIDATES IN, given in the workflow's own order: none running, stuck, held or waiting on another
233
- * task (a candidate its workflow offers is work, whatever its last listing said), in the queue's one order (`queueRank`), one
234
- * reopened or given new input that the candidates do not hold built by `fromItem`; the workflow's own order within each
235
- * group. `alsoLeaveOut` names items the workflow knows are not to be taken. For a workflow whose Pick takes candidates of its
236
- * own; one whose Pick takes the head of its queue reads `queueOrder`. Pure.
165
+ * THE ORDER A PICK TAKES ITS OWN CANDIDATES IN, given in the workflow's own order: none blocked or in progress; those in
166
+ * its queue first, in the queue's order (`queueOrder`), then the rest in the workflow's own. A task a step or a person
167
+ * returned to the queue that the candidates do not hold is built by `fromItem`. `alsoLeaveOut` names items the workflow
168
+ * knows are not to be taken. For a workflow whose Pick takes candidates of its own; one whose Pick takes the head of its
169
+ * queue reads `queueOrder`. Pure.
237
170
  */
238
171
  export const inPickOrder = (input) => {
239
172
  const byItem = new Map(input.tasks.map((t) => [keyOf(t.ref.item), t]));
173
+ const place = new Map(queueOrder(input.tasks).map((t, i) => [keyOf(t.ref.item), i]));
240
174
  const leaveOut = new Set([...(input.alsoLeaveOut ?? [])].map(keyOf));
241
175
  const free = (item) => {
242
176
  const t = byItem.get(keyOf(item));
243
- return !leaveOut.has(keyOf(item)) && (t === undefined || t.bucket === 'queued' || t.bucket === 'done' || (t.bucket === 'waiting' && t.listed?.kind === 'wait'));
177
+ return !leaveOut.has(keyOf(item)) && (t === undefined || t.status === 'queued' || t.status === 'done');
244
178
  };
245
179
  const given = new Set(input.candidates.map((c) => keyOf(input.subjectOf(c))));
246
180
  const fromItem = input.fromItem;
247
181
  const built = fromItem === undefined ? [] : input.tasks
248
- .filter((t) => (t.reopened || t.front) && t.bucket === 'queued' && !given.has(keyOf(t.ref.item)) && free(t.ref.item))
182
+ .filter((t) => t.returned && t.status === 'queued' && !given.has(keyOf(t.ref.item)) && free(t.ref.item))
249
183
  .flatMap((t) => { const c = fromItem(t.ref.item); return c === null ? [] : [{ c, item: t.ref.item }]; });
250
184
  const open = [...input.candidates.filter((c) => free(input.subjectOf(c))).map((c) => ({ c, item: input.subjectOf(c) })), ...built]
251
- .map((o, i) => ({ c: o.c, i, t: byItem.get(keyOf(o.item)) }));
252
- return open.sort((a, b) => queueRank(a.t, b.t) || a.i - b.i).map((o) => o.c);
253
- };
254
- /**
255
- * A WORKFLOW'S QUEUE: its queued tasks, in the order its Pick takes them and a dashboard lists them: `queueRank`, then the
256
- * order its list gives (`Listed.position`), then the oldest task first. Pure.
257
- */
258
- export const queueOrder = (tasks) => {
259
- const position = (t) => (t.listed?.kind === 'line' && t.listed.position !== undefined ? t.listed.position : Number.MAX_SAFE_INTEGER);
260
- return tasks.filter((t) => t.bucket === 'queued').sort((a, b) => queueRank(a, b) || position(a) - position(b) || a.id - b.id);
261
- };
262
- /**
263
- * 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
264
- * 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.
265
- * Pure.
266
- */
267
- export const bucketView = (work, tasks) => {
268
- const byItem = new Map(tasks.map((t) => [keyOf(t.ref.item), t]));
269
- const bucketOfItem = (item) => byItem.get(keyOf(item))?.bucket ?? 'queued';
270
- const unchangedItem = (item) => byItem.get(keyOf(item))?.unchanged === true;
271
- const listed = work.lines.flatMap((l) => l.items);
272
- const moved = (bucket) => listed.filter((i) => bucketOfItem(i) === bucket);
273
- const onList = new Set([...listed, ...work.waits.flatMap((w) => w.items)].map(keyOf));
274
- const reopened = tasks.filter((t) => t.reopened && t.bucket !== 'done' && !onList.has(keyOf(t.ref.item))).map((t) => t.ref.item);
275
- const line = (label, items, outsideGap = false) => (items.length === 0 ? [] : [{ label, items, ...(outsideGap ? { outsideGap: true } : {}) }]);
276
- const stays = (i) => !['stuck', 'held', 'waiting'].includes(bucketOfItem(i));
277
- return {
278
- lines: [
279
- ...work.lines.map((l) => ({ ...l, items: l.items.filter(stays) })),
280
- ...line(STUCK_LINE, moved('stuck')), ...line(HELD_LINE, moved('held')), ...line(REOPENED_LINE, reopened, true),
281
- ],
282
- waits: [
283
- ...work.waits,
284
- ...[{ ...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),
285
- ],
286
- };
185
+ .map((o, i) => ({ c: o.c, i, at: place.get(keyOf(o.item)) ?? Number.MAX_SAFE_INTEGER }));
186
+ return open.sort((a, b) => a.at - b.at || a.i - b.i).map((o) => o.c);
287
187
  };
288
188
  /** A task's notes as its run's agent reads them: every note but an outcome, and its last 3 outcomes, newest last. Pure. */
289
189
  export const notesText = (notes, limit = 4000) => {
@@ -300,19 +200,36 @@ export const notesText = (notes, limit = 4000) => {
300
200
  }
301
201
  return kept.join('\n\n');
302
202
  };
303
- /** A workflow's tasks counted by bucket. Pure. */
304
- export const bucketCounts = (tasks) => Object.fromEntries(BUCKETS.map((b) => [b, tasks.filter((t) => t.bucket === b).length]));
203
+ /**
204
+ * WHY A WORKFLOW'S BLOCKED TASKS ARE BLOCKED, most tasks first: a count for each reason, so a page says the reason beside
205
+ * the number. Reasons that differ only by a count or by which task is waited on are one reason. Pure.
206
+ */
207
+ export const blockedReasons = (tasks) => {
208
+ const reason = (t) => (/^\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);
209
+ const counts = new Map();
210
+ for (const t of tasks)
211
+ if (t.status === 'blocked')
212
+ counts.set(reason(t), (counts.get(reason(t)) ?? 0) + 1);
213
+ return [...counts].map(([why, n]) => ({ why, tasks: n })).sort((a, b) => b.tasks - a.tasks || a.why.localeCompare(b.why));
214
+ };
215
+ /** A workflow's tasks counted by status: every status, a zero as much as any other, so they add up to its tasks. Pure. */
216
+ export const statusCounts = (tasks) => Object.fromEntries(TASK_STATUSES.map((s) => [s, tasks.filter((t) => t.status === s).length]));
305
217
  // -------------------------------------------------------------------------------------------------------------- stored
306
- /** The task queue of one project: its rules applied to its stored tasks, every write waking the Picks it can change. */
218
+ /** The task queue of one project: the rules above applied to its stored tasks, every write waking the Picks it can change. */
307
219
  export const makeTasks = (deps) => {
308
220
  const { store, wakes } = deps;
309
- /** Any note can change what its workflow's Pick can claim; the wake reaches it once this write has committed. */
221
+ /** A note can change what its workflow's Pick can claim; the wake reaches it once this write has committed, once per workflow. */
310
222
  const appended = (notes, ids) => {
311
- notes.forEach((n, k) => { if (ids[k] !== null)
312
- wakes.wakePicksOf(n.task.workflow, `a note on one of its tasks: ${n.kind}`); });
223
+ const woken = new Map();
224
+ notes.forEach((n, k) => { if (ids[k] !== null && !woken.has(n.task.workflow))
225
+ woken.set(n.task.workflow, n.kind); });
226
+ for (const [workflow, kind] of woken)
227
+ wakes.wakePicksOf(workflow, `a note on one of its tasks: ${kind}`);
313
228
  };
314
229
  /** A write a step asks for: it fails, typed, rather than going missing. */
315
230
  const inStore = (notes) => Effect.suspend(() => {
231
+ if (notes.length === 0)
232
+ return Effect.succeed([]);
316
233
  if (!store.writable())
317
234
  return Effect.fail(new TaskStoreError({ reason: 'no task store is open: a test names one' }));
318
235
  return pipe(store.append(notes), Effect.mapError((e) => new TaskStoreError({ reason: e.reason })), Effect.tap((ids) => Effect.sync(() => appended(notes, ids))));
@@ -337,36 +254,43 @@ export const makeTasks = (deps) => {
337
254
  /** A stored text a note's change names, checked against its hash. */
338
255
  const noteText = (sha) => 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)}` }) });
339
256
  /**
340
- * Another task's work is needed first: `task` goes back to queued, done or not, ahead of its workflow's other items, and
341
- * `waiting` waits on it until it finishes. Both get a note.
257
+ * PUTS A TASK BACK IN ITS QUEUE, done or blocked or not: it joins the back, and its count of failed tries starts again.
258
+ * `input` is new text for its next run, stored by hash and read with `noteText(note.inputSha)`.
259
+ */
260
+ const requeue = (input) => Effect.gen(function* () {
261
+ const inputSha = input.input === undefined ? undefined : yield* storeText(input.input, 'the input');
262
+ yield* inStore([{ task: input.task, by: input.by, kind: 'queued', why: input.why, ...(input.about === undefined ? {} : { about: input.about }), ...(inputSha === undefined ? {} : { inputSha }) }]);
263
+ });
264
+ /**
265
+ * 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
266
+ * puts it back (`requeue`). `inputs` is what it ran on when it was blocked, where the reason is that nothing is new.
267
+ */
268
+ const block = (input) => 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 }) }]));
269
+ /**
270
+ * Another task's work is needed first: `task` goes back to its queue, done or not, and `waiting` is blocked on it until it
271
+ * finishes, when it goes back to its own (`appendOutcome`). Both get a note.
342
272
  */
343
273
  const reopen = (input) => Effect.asVoid(inStore([
344
- { task: input.task, by: input.by, kind: 'reopened', why: input.why, about: input.waiting },
345
- { task: input.waiting, by: input.by, kind: 'waits on', why: input.why, about: input.task },
274
+ { task: input.task, by: input.by, kind: 'queued', why: input.why, about: input.waiting },
275
+ { task: input.waiting, by: input.by, kind: 'blocked', why: `waits on ${input.task.workflow} ${input.task.item}: ${input.why}`, about: input.task },
346
276
  ]));
347
277
  /**
348
- * 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
349
- * has tried it, and its count of runs starts again. `input` is stored by hash and read with `noteText(note.inputSha)`.
278
+ * THE ESCAPE HATCH: moves tasks of one workflow to the front of its queue, in the order given, ahead of every task moved
279
+ * 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.
350
280
  */
351
- const giveNewInput = (input) => Effect.gen(function* () {
352
- const inputSha = input.input === undefined ? undefined : yield* storeText(input.input, 'the input');
353
- yield* inStore([{ task: input.task, by: input.by, kind: 'new input', why: input.why, ...(input.about === undefined ? {} : { about: input.about }), ...(inputSha === undefined ? {} : { inputSha }) }]);
281
+ const moveToFront = (input) => Effect.gen(function* () {
282
+ const states = yield* Effect.mapError(store.statesOf(input.workflow), (e) => new TaskStoreError({ reason: e.reason }));
283
+ const own = new Map(states.map((s) => [keyOf(s.ref.item), s.ref.item]));
284
+ const named = [...new Map(input.items.map((item) => [keyOf(item), item])).values()];
285
+ const moved = named.flatMap((item) => { const stored = own.get(keyOf(item)); return stored === undefined ? [] : [stored]; });
286
+ // The last note written is the first in the queue, so they are written last first.
287
+ yield* inStore([...moved].reverse().map((item) => ({ task: { workflow: input.workflow, item }, by: input.by, kind: MOVED_TO_FRONT, why: input.why })));
288
+ return { moved, notItsTasks: named.filter((item) => !own.has(keyOf(item))) };
354
289
  });
355
- /** Holds a task from automatic work until it is released. */
356
- const hold = (input) => Effect.asVoid(inStore([{ task: input.task, by: input.by, kind: 'held', why: input.why }]));
357
- /** Takes a task out of the stuck or held bucket: its count of runs starts again from now. False where nothing could be written. */
358
- const releaseTask = (input) => {
359
- const note = { task: input.task, by: { workflow: null, run: null, step: null }, kind: 'released', why: input.why };
360
- return Effect.map(engineWrite(`release ${input.task.workflow} ${input.task.item}`, store.append([note])), (ids) => {
361
- if (ids === null)
362
- return false;
363
- appended([note], ids);
364
- return true;
365
- });
366
- };
367
290
  /**
368
- * 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
369
- * resumes every task waiting on it, with a note on both. Run again on a resume, it keeps the first.
291
+ * 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
292
+ * run's step blocked it, where it did. One that finished the task returns every task blocked waiting on it to its queue.
293
+ * Run again on a resume, it keeps the first.
370
294
  */
371
295
  const appendOutcome = (r) => Effect.gen(function* () {
372
296
  const item = r.subject ?? (yield* engineWrite(`the item of run ${r.run}`, deps.stepRecords.subjectOfRun(r.run)));
@@ -375,31 +299,34 @@ export const makeTasks = (deps) => {
375
299
  const task = { workflow: r.workflow, item };
376
300
  const by = { workflow: r.workflow, run: r.run, step: (yield* engineWrite(`the step of run ${r.run}`, deps.stepRecords.stepOfRun(r.run)))?.step ?? null };
377
301
  const done = yield* engineWrite(`outcome of run ${r.run}`, store.appendOutcome({
378
- task, by, why: r.outcome, finished: r.finished, inputs: r.inputs,
379
- 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` }),
302
+ task, by, why: r.outcome, finished: r.finished, inputs: r.inputs, blocked: r.blocked,
303
+ resumedWhy: () => `${r.workflow} ${item} finished (${r.outcome}), so this goes back to its queue`,
380
304
  }));
381
305
  if (done === null || !done.appended)
382
306
  return;
383
307
  wakes.wakePicksOf(r.workflow, 'a note on one of its tasks: outcome');
384
308
  for (const w of done.resumed)
385
- wakes.wakePicksOf(w.workflow, 'a note on one of its tasks: resumed');
309
+ wakes.wakePicksOf(w.workflow, 'a note on one of its tasks: queued');
386
310
  });
387
- /** Where a workflow's list puts each of its items now: the engine's one reading of it, which makes its tasks. */
388
- const recordListing = (workflow, work) => Effect.gen(function* () {
311
+ /**
312
+ * WHERE A WORKFLOW'S LIST PUTS EACH OF ITS ITEMS NOW: the engine's one reading of it, which makes its tasks
313
+ * (`TaskStore.recordListing`, where the two kinds of list are written down). `everyItem`: the list is every item it has,
314
+ * done or not; otherwise only its work left.
315
+ */
316
+ const recordListing = (input) => Effect.gen(function* () {
389
317
  const at = new Map();
390
- const last = new Set((work.last ?? []).map(keyOf));
391
- let position = 0;
392
- for (const l of work.lines) {
318
+ for (const l of input.work.lines)
393
319
  for (const item of l.items)
394
- at.set(keyOf(item), { item, listed: { kind: 'line', label: l.label, position: position++, ...(last.has(keyOf(item)) ? { last: true } : {}) } });
395
- }
396
- for (const w of work.waits)
320
+ at.set(keyOf(item), { item, listed: { kind: 'line', label: l.label } });
321
+ for (const w of input.work.waits)
397
322
  for (const item of w.items)
398
323
  at.set(keyOf(item), { item, listed: { kind: 'wait', label: w.label, on: w.on } });
399
- const fresh = yield* engineWrite(`the list of ${workflow}`, store.recordListing({ workflow, listed: [...at.values()] }));
400
- // An item new to the list is work its Pick may claim; the list read again with the same items wakes nothing.
401
- if (fresh === true)
402
- wakes.wakePicksOf(workflow, 'an item new to its list');
324
+ const recorded = yield* engineWrite(`the list of ${input.workflow}`, store.recordListing({
325
+ workflow: input.workflow, listed: [...at.values()], everyItem: input.everyItem, readAt: input.readAt ?? Date.now() / 1000, by: { workflow: input.workflow, run: null, step: null },
326
+ }));
327
+ // 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.
328
+ if (recorded?.fresh === true)
329
+ wakes.wakePicksOf(input.workflow, 'an item new to its list');
403
330
  });
404
331
  /** The items each workflow's unfinished runs are on now, lower case; a run named in `excludingRun` is left out. */
405
332
  const itemsRunningNow = (excludingRun) => Effect.gen(function* () {
@@ -414,46 +341,67 @@ export const makeTasks = (deps) => {
414
341
  }
415
342
  return out;
416
343
  });
417
- const summarizeAll = (facts, running, inputs) => Effect.gen(function* () {
418
- const waitedOn = [...new Map(facts.flatMap((f) => openWaits(f.notes)).map((t) => [`${t.workflow}\0${keyOf(t.item)}`, t])).values()];
419
- const others = (yield* Effect.forEach(waitedOn, (t) => store.task(t))).flatMap((f) => (f === null ? [] : [f]));
420
- const isRunning = (ref) => running.get(ref.workflow)?.has(keyOf(ref.item)) === true;
421
- const done = (t) => {
422
- const f = others.find((o) => sameTask(o.ref, t));
423
- return f === undefined || isDone(f, isRunning(t));
424
- };
425
- return facts.map((f) => {
426
- const own = inputs?.get(keyOf(f.ref.item));
427
- return summarize({ facts: f, running: isRunning(f.ref), done, rules: deps.rules, ...(own === undefined ? {} : { inputs: own }) });
428
- });
429
- });
430
344
  /**
431
- * EACH TASK'S INPUTS AS ITS WORKFLOW LAST READ THEM (`steps.ts` `queueNow`, at each Pick and each reading of its list), by
432
- * 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.
345
+ * EACH TASK'S INPUTS AS ITS WORKFLOW LAST READ THEM (`steps.ts` `readTaskInputs`, at each Pick), by item in lower case:
346
+ * what `settleQueue` blocks a task with nothing new by.
433
347
  */
434
348
  const inputsRead = new Map();
435
349
  const recordTaskInputs = (workflow, inputs) => { inputsRead.set(workflow, inputs); };
350
+ /** Every task of a workflow and the status it is in now. `running` is for a test. */
351
+ const taskSummaries = (input) => Effect.gen(function* () {
352
+ const states = yield* store.statesOf(input.workflow);
353
+ const running = (input.running ?? (yield* itemsRunningNow(input.excludingRun))).get(input.workflow);
354
+ return states.map((state) => summarize({ state, running: running?.has(keyOf(state.ref.item)) === true }));
355
+ });
436
356
  /**
437
- * Every task of a workflow and the bucket it is in now, with its inputs as last read (`recordTaskInputs`). `running` is for
438
- * a test.
357
+ * THE STANDARD BLOCKING, RUN BY THE STEP THAT PICKS, before it reads its queue: each queued task a standard reason holds
358
+ * for is blocked with it (`standardBlock`, and flipping, read from the notes of a task with enough changes to flip), and
359
+ * each blocked task whose reason has lapsed goes back to the queue (`blockLapsed`). `by` is the Pick. Returns the
360
+ * workflow's tasks as that leaves them, another run's left in progress and `excludingRun`'s own free.
439
361
  */
440
- const taskSummaries = (input) => Effect.gen(function* () {
441
- const facts = yield* store.tasksOf(input.workflow);
442
- const running = input.running ?? (yield* itemsRunningNow(input.excludingRun));
443
- return yield* summarizeAll(facts, running, inputsRead.get(input.workflow));
362
+ const settleQueue = (input) => Effect.gen(function* () {
363
+ const tasks = yield* taskSummaries({ workflow: input.workflow, ...(input.excludingRun === undefined ? {} : { excludingRun: input.excludingRun }) });
364
+ if (!store.writable())
365
+ return tasks;
366
+ const inputs = inputsRead.get(input.workflow);
367
+ const notes = [];
368
+ const settled = [];
369
+ for (const t of tasks) {
370
+ const own = inputs?.get(keyOf(t.ref.item));
371
+ if (t.status === 'queued') {
372
+ const flips = t.noted.changes < CHANGES_THAT_CAN_FLIP ? 0 : returnsToEarlierText(yield* store.notes(t.ref));
373
+ const why = flips >= BLOCK_AFTER_RETURNS ? BLOCKED_FLIPPING : standardBlock(t, own);
374
+ if (why !== null) {
375
+ notes.push({ task: t.ref, by: input.by, kind: 'blocked', why, ...(t.noted.inputs === null ? {} : { inputs: t.noted.inputs }) });
376
+ settled.push({ ...t, status: 'blocked', why });
377
+ continue;
378
+ }
379
+ }
380
+ if (t.status === 'blocked' && blockLapsed(t, own)) {
381
+ notes.push({ task: t.ref, by: input.by, kind: 'unblocked', why: UNBLOCKED_INPUTS_CHANGED });
382
+ settled.push({ ...t, status: 'queued', why: UNBLOCKED_INPUTS_CHANGED, since: Date.now() / 1000 });
383
+ continue;
384
+ }
385
+ settled.push(t);
386
+ }
387
+ if (notes.length === 0)
388
+ return tasks;
389
+ const written = yield* Effect.result(store.append(notes));
390
+ // Unwritten, nothing was settled: the tasks stand as they were read, and the next Pick tries again.
391
+ if (written._tag === 'Failure')
392
+ return yield* Effect.as(Effect.logError(`[tasks] ${input.workflow}: its queue could not be settled: ${written.failure.reason}`), tasks);
393
+ return settled;
444
394
  });
445
- /** One task's bucket now, and why; a task no workflow has named yet is queued. */
446
- const bucketOf = (task) => Effect.gen(function* () {
447
- const facts = yield* store.task(task);
448
- const summary = facts === null ? undefined : (yield* summarizeAll([facts], yield* itemsRunningNow(), inputsRead.get(task.workflow)))[0];
449
- return summary
450
- ?? { 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 };
395
+ /** One task's status now, and why; a task no workflow has named yet is queued. */
396
+ const statusOf = (task) => Effect.gen(function* () {
397
+ const state = (yield* store.state(task)) ?? { id: 0, ref: task, listed: null, status: 'queued', why: null, kind: null, since: Date.now() / 1000, note: 0, front: null, tries: 0, inputs: null, about: null, changes: 0, returned: false };
398
+ return summarize({ state, running: (yield* itemsRunningNow()).get(task.workflow)?.has(keyOf(task.item)) === true });
451
399
  });
452
400
  /** What a run's agent is told of its own task: its notes, as `notesText` words them; empty with none, or with no store. */
453
401
  const notesForAgent = (task) => (store.writable() ? Effect.map(store.notes(task), (notes) => notesText(notes)) : Effect.succeed(''));
454
402
  return {
455
- appendTaskNote, noteText, reopen, giveNewInput, hold, releaseTask, appendOutcome, recordListing, recordTaskInputs,
456
- taskNotes: store.notes, taskIdOf: store.taskId, itemsRunningNow, taskSummaries, bucketOf, notesForAgent,
403
+ appendTaskNote, noteText, requeue, block, reopen, moveToFront, appendOutcome, recordListing, recordTaskInputs,
404
+ taskNotes: store.notes, taskIdOf: store.taskId, itemsRunningNow, taskSummaries, settleQueue, statusOf, notesForAgent,
457
405
  };
458
406
  };
459
407
  //# sourceMappingURL=tasks.js.map