@jive-sh/workflow-platform 0.3.2 → 0.4.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 (60) hide show
  1. package/README.md +64 -20
  2. package/dist/cpu-limit/limiter.js +5 -4
  3. package/dist/cpu-limit/limiter.js.map +1 -1
  4. package/dist/dashboard/agent-usage.js +25 -0
  5. package/dist/dashboard/agent-usage.js.map +1 -0
  6. package/dist/dashboard/drilldown.js +16 -0
  7. package/dist/dashboard/drilldown.js.map +1 -0
  8. package/dist/dashboard/queue-lines.js +44 -0
  9. package/dist/dashboard/queue-lines.js.map +1 -0
  10. package/dist/dashboard/queue-table.js +8 -0
  11. package/dist/dashboard/queue-table.js.map +1 -0
  12. package/dist/index.js +8 -7
  13. package/dist/index.js.map +1 -1
  14. package/dist/keep-running.js +1 -1
  15. package/dist/keep-running.js.map +1 -1
  16. package/dist/pick-wakes.js +4 -4
  17. package/dist/pick-wakes.js.map +1 -1
  18. package/dist/queue-counts.js +7 -9
  19. package/dist/queue-counts.js.map +1 -1
  20. package/dist/steps.js +133 -30
  21. package/dist/steps.js.map +1 -1
  22. package/dist/storage/sqlite-store.js +115 -40
  23. package/dist/storage/sqlite-store.js.map +1 -1
  24. package/dist/storage/task-store.js +14 -1
  25. package/dist/storage/task-store.js.map +1 -1
  26. package/dist/tasks.js +215 -267
  27. package/dist/tasks.js.map +1 -1
  28. package/dist/views/runs-now.js +2 -1
  29. package/dist/views/runs-now.js.map +1 -1
  30. package/dist/views/workflows-view.js +74 -15
  31. package/dist/views/workflows-view.js.map +1 -1
  32. package/package.json +1 -1
  33. package/src/cpu-limit/limiter.ts +8 -5
  34. package/src/dashboard/agent-usage-line.tsx +28 -0
  35. package/src/dashboard/agent-usage.ts +48 -0
  36. package/src/dashboard/dashboard.css +68 -29
  37. package/src/dashboard/drilldown.ts +44 -0
  38. package/src/dashboard/index.tsx +1 -0
  39. package/src/dashboard/machine-controls.tsx +53 -0
  40. package/src/dashboard/queue-bar.tsx +43 -0
  41. package/src/dashboard/queue-chart.tsx +89 -76
  42. package/src/dashboard/queue-lines.ts +87 -0
  43. package/src/dashboard/queue-table.ts +23 -0
  44. package/src/dashboard/workflow-drilldown.tsx +89 -0
  45. package/src/dashboard/workflows-dashboard.tsx +103 -37
  46. package/src/index.ts +11 -10
  47. package/src/keep-running.ts +3 -3
  48. package/src/pick-wakes.ts +14 -9
  49. package/src/queue-counts.ts +10 -14
  50. package/src/steps.ts +179 -42
  51. package/src/storage/sqlite-store.ts +123 -46
  52. package/src/storage/step-records.ts +14 -3
  53. package/src/storage/task-store.ts +88 -36
  54. package/src/tasks.ts +235 -301
  55. package/src/views/runs-now.ts +3 -2
  56. package/src/views/workflows-view.ts +102 -32
  57. package/dist/views/workflow-flows.js +0 -53
  58. package/dist/views/workflow-flows.js.map +0 -1
  59. package/src/dashboard/workflow-dag.tsx +0 -256
  60. package/src/views/workflow-flows.ts +0 -97
@@ -11,7 +11,7 @@ import {
11
11
  stepErrorKept, type FunnelStepRecord, type ItemCost, type ItemHistoryRow, type LastStepNow, type NewestStepRecord, type RunCost, type RunOutcomeRow, type StepEdgeTaken,
12
12
  type StepFileCount, type StepRecords, type StepRunRow, type UndeclaredWrites, type WorkStep, AGENT_LIVE_SECONDS,
13
13
  } from './step-records';
14
- import type { Listed, ListedWait, NewInputFlow, NewNote, QueueCount, TaskFacts, TaskNote, TaskRef, TaskStore } from './task-store';
14
+ import { LISTED_AGAIN, MOVED_TO_FRONT, STATUS_KINDS, STOOD_DOWN_OUTCOME, TRIES_START_AGAIN_KINDS, type Listed, type NewNote, type QueueCount, type TaskNote, type TaskRef, type TaskState, type TaskStore } from './task-store';
15
15
  import type { InputRecords, InputRun } from './input-records';
16
16
  import { storeCall, storeCalls } from './storage-error';
17
17
 
@@ -165,7 +165,7 @@ CREATE INDEX IF NOT EXISTS queue_counts_by_at ON queue_counts (at);`;
165
165
  * that applies the schema only when it must (a write takes the lock) asks this first.
166
166
  */
167
167
  export const stepRecordsSchemaApplied = (db: Database): boolean => {
168
- const newest = ['step_runs', 'queue_counts', 'step_runs_by_workflow'];
168
+ const newest = ['step_runs', 'queue_counts', 'step_runs_by_workflow', 'step_runs_by_child'];
169
169
  const present = new Set((db.query('SELECT name FROM sqlite_master').all() as Array<{ name: string }>).map((r) => r.name));
170
170
  return newest.every((name) => present.has(name));
171
171
  };
@@ -193,6 +193,9 @@ export const applyStepRecordsSchema = (db: Database): void => {
193
193
  if (!columns.includes('owner_started_at')) db.exec('ALTER TABLE step_runs ADD COLUMN owner_started_at REAL');
194
194
  // Why it ended as it did, in a line (`steps.ts` `reasonOf`): what the platform counts outcomes by.
195
195
  if (!columns.includes('reason')) db.exec('ALTER TABLE step_runs ADD COLUMN reason TEXT');
196
+ // The run a sub-workflow step started (`steps.ts` `defineSubWorkflow`): what ties that run to the run above it.
197
+ if (!columns.includes('child_run')) db.exec('ALTER TABLE step_runs ADD COLUMN child_run TEXT');
198
+ db.exec('CREATE INDEX IF NOT EXISTS step_runs_by_child ON step_runs (child_run) WHERE child_run IS NOT NULL');
196
199
  db.exec(STEP_ITEMS_SCHEMA);
197
200
  db.exec(UNDECLARED_WRITES_SCHEMA);
198
201
  db.exec(INPUT_RUNS_SCHEMA);
@@ -283,6 +286,56 @@ const noteOf = (r: NoteRow): TaskNote => ({
283
286
  change: r.before_sha === null || r.after_sha === null ? null : { beforeSha: r.before_sha, afterSha: r.after_sha, flags: r.flags ?? '', diff: r.diff ?? '' },
284
287
  });
285
288
 
289
+ const quoted = (kinds: ReadonlyArray<string>): string => kinds.map((k) => `'${k.replace(/'/g, "''")}'`).join(', ');
290
+ /** A note a task's status is read from (`task-store.ts` `STATUS_KINDS`): an outcome of a run that did not stand down, or one of the kinds. */
291
+ const IS_STATUS_NOTE = `((n.kind = 'outcome' AND n.why <> '${STOOD_DOWN_OUTCOME}') OR n.kind IN (${quoted(Object.keys(STATUS_KINDS))}))`;
292
+ /** A note after which a task's failed tries are counted again: its final check passing, or a return to its queue. */
293
+ const STARTS_TRIES_AGAIN = `((n.kind = 'outcome' AND n.finished = 1) OR n.kind IN (${quoted(TRIES_START_AGAIN_KINDS)}))`;
294
+
295
+ interface StateRow {
296
+ readonly id: number; readonly workflow: string; readonly item: string; readonly listed: string | null; readonly created_at: number;
297
+ readonly note: number | null; readonly front: number | null; readonly kind: string | null; readonly why: string | null; readonly at: number | null;
298
+ readonly finished: number | null; readonly inputs: string | null; readonly about_workflow: string | null; readonly about_item: string | null;
299
+ readonly tries: number; readonly changes: number; readonly start_kind: string | null;
300
+ }
301
+
302
+ /**
303
+ * EVERY TASK MATCHING `where` AS ITS NOTES LEAVE IT, in one query: its newest status note, its failed tries since they last
304
+ * started again, and whether the reorder call moved it since. Nothing stores a status; it is read from the notes each time
305
+ * (0.3 s for a project's 20,000 tasks and 55,000 notes, 2026-11-19).
306
+ */
307
+ const statesWhere = (db: Database, where: string, params: ReadonlyArray<string | number>): ReadonlyArray<TaskState> =>
308
+ (db.query(`
309
+ WITH s AS (
310
+ SELECT t.id AS id,
311
+ (SELECT MAX(n.id) FROM task_notes n WHERE n.task = t.id AND ${IS_STATUS_NOTE}) AS note,
312
+ (SELECT MAX(n.id) FROM task_notes n WHERE n.task = t.id AND ${STARTS_TRIES_AGAIN}) AS start,
313
+ (SELECT MAX(n.id) FROM task_notes n WHERE n.task = t.id AND n.kind = '${MOVED_TO_FRONT}') AS front
314
+ FROM tasks t WHERE ${where})
315
+ SELECT t.id, t.workflow, t.item, t.listed, t.created_at, s.note, s.front, n.kind, n.why, n.at, n.finished, n.inputs,
316
+ a.workflow AS about_workflow, a.item AS about_item,
317
+ (SELECT COUNT(*) FROM task_notes o WHERE o.task = t.id AND o.kind = 'outcome' AND o.finished = 0 AND o.why <> '${STOOD_DOWN_OUTCOME}' AND o.id > COALESCE(s.start, 0)) AS tries,
318
+ (SELECT COUNT(*) FROM task_notes c WHERE c.task = t.id AND c.before_sha IS NOT NULL) AS changes,
319
+ (SELECT k.kind FROM task_notes k WHERE k.id = s.start) AS start_kind
320
+ FROM s JOIN tasks t ON t.id = s.id LEFT JOIN task_notes n ON n.id = s.note LEFT JOIN tasks a ON a.id = n.about
321
+ ORDER BY t.id`).all(...params) as ReadonlyArray<StateRow>).map((r): TaskState => ({
322
+ id: r.id, ref: { workflow: r.workflow, item: r.item }, listed: r.listed === null ? null : (JSON.parse(r.listed) as Listed),
323
+ status: r.kind === null ? 'queued' : r.kind === 'outcome' ? (r.finished === 1 ? 'done' : 'queued') : STATUS_KINDS[r.kind]!,
324
+ why: r.why, kind: r.kind, since: r.at ?? r.created_at, note: r.note ?? 0,
325
+ front: r.front !== null && r.front > (r.note ?? 0) ? r.front : null,
326
+ tries: r.tries, inputs: r.inputs,
327
+ about: r.about_workflow === null || r.about_item === null ? null : { workflow: r.about_workflow, item: r.about_item },
328
+ changes: r.changes,
329
+ returned: r.start_kind !== null && TRIES_START_AGAIN_KINDS.includes(r.start_kind),
330
+ }));
331
+
332
+ /**
333
+ * WHETHER A TASK IS ITS WORKFLOW'S NOW: on its list; or done; or put back in its queue by a step or a person and not
334
+ * finished since (a task another needs redone is work whatever its list says). Never one `removed`.
335
+ */
336
+ const isItsWorkflowsNow = (s: TaskState): boolean =>
337
+ s.status !== 'removed' && (s.listed !== null || s.status === 'done' || s.returned);
338
+
286
339
  /** A task's id, made the first time it is named. */
287
340
  const taskIdIn = (db: Database, task: TaskRef, now: number): number => {
288
341
  db.query('INSERT OR IGNORE INTO tasks (workflow, item, item_key, created_at) VALUES (?, ?, ?, ?)').run(task.workflow, task.item, keyOf(task.item), now);
@@ -417,7 +470,15 @@ export const sqliteStore = (options: {
417
470
  const stepRecords: StepRecords = storeCalls<StepRecords>('step records', {
418
471
  openStepRun: (r) => tryWrite((db) => {
419
472
  const now = Date.now() / 1000;
420
- const inherited = r.subject ?? (db.query('SELECT subject FROM step_runs WHERE run = ? AND subject IS NOT NULL ORDER BY id DESC LIMIT 1').get(r.run) as { subject: string } | null)?.subject ?? null;
473
+ if (r.resume === true) {
474
+ const open = db.query('SELECT id FROM step_runs WHERE run = ? AND step = ? AND call IS ? AND ended IS NULL ORDER BY id DESC LIMIT 1').get(r.run, r.step, r.call) as { id: number } | null;
475
+ if (open !== null) return open.id;
476
+ }
477
+ // What it works on: named, or what its run last worked on, or what the step that started its run as a sub-workflow works on.
478
+ const inherited = r.subject
479
+ ?? (db.query('SELECT subject FROM step_runs WHERE run = ? AND subject IS NOT NULL ORDER BY id DESC LIMIT 1').get(r.run) as { subject: string } | null)?.subject
480
+ ?? (db.query('SELECT subject FROM step_runs WHERE child_run = ? AND subject IS NOT NULL ORDER BY id DESC LIMIT 1').get(r.run) as { subject: string } | null)?.subject
481
+ ?? null;
421
482
  const owner = ownerOfNewRecords();
422
483
  return Number(db.query(
423
484
  'INSERT INTO step_runs (workflow, run, step, call, agent, started, beat, subject, owner_pid, owner_started_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
@@ -485,8 +546,25 @@ export const sqliteStore = (options: {
485
546
  .get(run) as { step: string; outcome: string | null; owner_pid: number | null; owner_started_at: number | null } | null;
486
547
  return r === null ? null : { step: r.step, failed: r.outcome === 'failure', owner: r.owner_pid === null || r.owner_started_at === null ? null : { pid: r.owner_pid, startedAt: r.owner_started_at } };
487
548
  }),
549
+ setStepChild: (r) => {
550
+ tryWrite((db) => db.query('UPDATE step_runs SET child_run = ? WHERE id = ?').run(r.childRun, r.id));
551
+ },
552
+ rootOfRun: (run) =>
553
+ read((db) => db.query(
554
+ `WITH RECURSIVE up(run, workflow, depth) AS (
555
+ SELECT p.run, p.workflow, 1 FROM step_runs p WHERE p.child_run = ?1
556
+ UNION SELECT p.run, p.workflow, u.depth + 1 FROM up u JOIN step_runs p ON p.child_run = u.run WHERE u.depth < 32)
557
+ SELECT run, workflow FROM up ORDER BY depth DESC LIMIT 1`,
558
+ ).get(run) as { run: string; workflow: string } | null, null),
488
559
  runsInAgentStep: (workflow) =>
489
- read((db) => (db.query('SELECT DISTINCT run FROM step_runs WHERE ended IS NULL AND agent = 1 AND waiting IS NULL AND workflow = ?').all(workflow) as ReadonlyArray<{ run: string }>).map((r) => r.run), []),
560
+ // Each open agent step, then the run that started its run as a sub-workflow, and so on up: every one of them that is a
561
+ // run of this workflow has an agent working for it.
562
+ read((db) => (db.query(
563
+ `WITH RECURSIVE up(run, depth) AS (
564
+ SELECT s.run, 0 FROM step_runs s WHERE s.ended IS NULL AND s.agent = 1 AND s.waiting IS NULL
565
+ UNION SELECT p.run, u.depth + 1 FROM up u JOIN step_runs p ON p.child_run = u.run WHERE u.depth < 32)
566
+ SELECT DISTINCT u.run AS run FROM up u WHERE EXISTS (SELECT 1 FROM step_runs r WHERE r.run = u.run AND r.workflow = ?)`,
567
+ ).all(workflow) as ReadonlyArray<{ run: string }>).map((r) => r.run), []),
490
568
  stepOfRun: (run) =>
491
569
  read((db) => db.query('SELECT step, subject, (SELECT MIN(started) FROM step_runs s WHERE s.run = ?1) AS started FROM step_runs WHERE run = ?1 ORDER BY id DESC LIMIT 1').get(run) as { step: string; subject: string | null; started: number } | null, null),
492
570
  subjectOfRun: (run) =>
@@ -619,19 +697,6 @@ export const sqliteStore = (options: {
619
697
  }, { edges: [], lasts: [] }),
620
698
  });
621
699
 
622
- /** The tasks matching `where`, each with its notes. */
623
- const factsWhere = (where: string, params: ReadonlyArray<string | number>): ReadonlyArray<TaskFacts> =>
624
- read((db) => {
625
- const tasks = db.query(`SELECT id, workflow, item, listed FROM tasks t WHERE ${where}`).all(...params) as ReadonlyArray<{ id: number; workflow: string; item: string; listed: string | null }>;
626
- if (tasks.length === 0) return [];
627
- const notes = new Map<number, TaskNote[]>();
628
- for (const r of db.query(`${NOTE_SELECT} WHERE n.task IN (SELECT id FROM tasks t WHERE ${where}) ORDER BY n.id`).all(...params) as ReadonlyArray<NoteRow>) {
629
- const list = notes.get(r.task_id);
630
- if (list === undefined) notes.set(r.task_id, [noteOf(r)]); else list.push(noteOf(r));
631
- }
632
- return tasks.map((t) => ({ id: t.id, ref: { workflow: t.workflow, item: t.item }, listed: t.listed === null ? null : (JSON.parse(t.listed) as Listed), notes: notes.get(t.id) ?? [] }));
633
- }, []);
634
-
635
700
  /** A write in one transaction; it throws, for the caller to say what it could not record. */
636
701
  const inTransaction = <A>(write: (db: Database) => A): A => {
637
702
  const db = writer();
@@ -647,31 +712,53 @@ export const sqliteStore = (options: {
647
712
  appendOutcome: (r) => storeCall('tasks: appendOutcome', () => inTransaction((db) => {
648
713
  const now = Date.now() / 1000;
649
714
  if (appendIn(db, { task: r.task, by: r.by, kind: 'outcome', why: r.why, finished: r.finished, ...(r.inputs === null ? {} : { inputs: r.inputs }) }, now) === null) return { appended: false, resumed: [] };
715
+ if (r.blocked !== null) appendIn(db, { task: r.task, by: r.by, kind: 'blocked', why: r.blocked, ...(r.inputs === null ? {} : { inputs: r.inputs }) }, now);
650
716
  if (!r.finished) return { appended: true, resumed: [] };
717
+ // Every task whose block, still in force, waits on this one goes back to its queue.
651
718
  const id = taskIdIn(db, r.task, now);
652
- const waiters = db.query(
653
- `SELECT DISTINCT w.workflow AS workflow, w.item AS item FROM task_notes n JOIN tasks w ON w.id = n.task
654
- WHERE n.kind = 'waits on' AND n.about = ?1
655
- AND NOT EXISTS (SELECT 1 FROM task_notes r WHERE r.task = n.task AND r.kind = 'resumed' AND r.about = ?1 AND r.id > n.id)`,
656
- ).all(id) as ReadonlyArray<TaskRef>;
657
- for (const w of waiters) {
658
- const why = r.resumedWhy(w);
659
- appendIn(db, { task: w, by: r.by, kind: 'resumed', why: why.resumed, about: r.task }, now);
660
- appendIn(db, { task: r.task, by: r.by, kind: 'waiter resumed', why: why.waiterResumed, about: w }, now);
661
- }
719
+ const waiters = statesWhere(db, `t.id IN (SELECT n.task FROM task_notes n WHERE n.about = ?)`, [id])
720
+ .filter((w) => w.status === 'blocked' && w.about !== null && w.about.workflow === r.task.workflow && keyOf(w.about.item) === keyOf(r.task.item))
721
+ .map((w) => w.ref);
722
+ for (const w of waiters) appendIn(db, { task: w, by: r.by, kind: 'queued', why: r.resumedWhy(w), about: r.task }, now);
662
723
  return { appended: true, resumed: waiters };
663
724
  })),
664
- recordListing: ({ workflow, listed }) => storeCall('tasks: recordListing', () => inTransaction((db) => {
725
+ recordListing: ({ workflow, listed, everyItem, readAt, by }) => storeCall('tasks: recordListing', () => inTransaction((db) => {
665
726
  const now = Date.now() / 1000;
666
- const wasListed = new Set((db.query('SELECT item_key FROM tasks WHERE workflow = ? AND listed IS NOT NULL').all(workflow) as Array<{ item_key: string }>).map((r) => r.item_key));
667
- const fresh = listed.some((l) => !wasListed.has(keyOf(l.item)));
668
- db.query('UPDATE tasks SET listed = NULL WHERE workflow = ? AND listed IS NOT NULL').run(workflow);
669
- const set = db.query('UPDATE tasks SET listed = ?, listed_at = ? WHERE id = ?');
670
- for (const l of listed) set.run(JSON.stringify(l.listed), now, taskIdIn(db, { workflow, item: l.item }, now));
671
- return fresh;
727
+ const before = new Map(statesWhere(db, 't.workflow = ?', [workflow]).map((s) => [keyOf(s.ref.item), s]));
728
+ const setListed = db.query('UPDATE tasks SET listed = ?, listed_at = ? WHERE id = ?');
729
+ const listedNow = new Set<string>();
730
+ let fresh = false;
731
+ for (const l of listed) {
732
+ const key = keyOf(l.item);
733
+ if (listedNow.has(key)) continue;
734
+ listedNow.add(key);
735
+ const was = before.get(key);
736
+ const text = JSON.stringify(l.listed);
737
+ if (was === undefined) {
738
+ setListed.run(text, now, taskIdIn(db, { workflow, item: l.item }, now));
739
+ fresh = true;
740
+ continue;
741
+ }
742
+ const wasGone = !isItsWorkflowsNow(was);
743
+ // A list read before the task finished still held it: only one read since says it is work again.
744
+ const workAgain = !everyItem && was.status === 'done' && l.listed.kind === 'line' && was.since < readAt;
745
+ if (wasGone || workAgain) {
746
+ appendIn(db, { task: was.ref, by, kind: LISTED_AGAIN, why: wasGone ? 'its workflow lists it again' : 'its workflow lists it as work again' }, now);
747
+ fresh = true;
748
+ }
749
+ if (was.listed === null || JSON.stringify(was.listed) !== text) setListed.run(text, now, was.id);
750
+ }
751
+ const clearListed = db.query('UPDATE tasks SET listed = NULL WHERE id = ?');
752
+ for (const [key, was] of before) {
753
+ if (listedNow.has(key)) continue;
754
+ if (was.listed !== null) clearListed.run(was.id);
755
+ if (everyItem && was.status === 'done') appendIn(db, { task: was.ref, by, kind: 'removed', why: 'its workflow no longer has this item' }, now);
756
+ }
757
+ return { fresh };
672
758
  })),
673
- tasksOf: (workflow) => storeCall('tasks: tasksOf', () => factsWhere('t.workflow = ?', [workflow])),
674
- task: (task) => storeCall('tasks: task', () => factsWhere('t.workflow = ? AND t.item_key = ?', [task.workflow, keyOf(task.item)])[0] ?? null),
759
+ statesOf: (workflow) => storeCall('tasks: statesOf', () =>
760
+ read((db) => statesWhere(db, 't.workflow = ?', [workflow]).filter(isItsWorkflowsNow), [])),
761
+ state: (task) => storeCall('tasks: state', () => read((db) => statesWhere(db, 't.workflow = ? AND t.item_key = ?', [task.workflow, keyOf(task.item)])[0] ?? null, null)),
675
762
  notes: (task) => storeCall('tasks: notes', () =>
676
763
  read((db) => (db.query(`${NOTE_SELECT} WHERE t.workflow = ? AND t.item_key = ? ORDER BY n.id`).all(task.workflow, keyOf(task.item)) as ReadonlyArray<NoteRow>).map(noteOf), [])),
677
764
  taskId: (task) => storeCall('tasks: taskId', () =>
@@ -692,16 +779,6 @@ export const sqliteStore = (options: {
692
779
  WHERE at >= ?1 OR at = (SELECT MAX(p.at) FROM queue_counts p WHERE p.workflow = q.workflow AND p.bucket = q.bucket AND p.at < ?1)
693
780
  ORDER BY at`,
694
781
  ).all(since) as ReadonlyArray<QueueCount>, [])),
695
- newInputFlows: () => storeCall('tasks: newInputFlows', () =>
696
- read((db) => db.query(
697
- `SELECT n.by_workflow AS "from", t.workflow AS "to", COUNT(*) AS notes, MAX(n.at) AS last FROM task_notes n JOIN tasks t ON t.id = n.task
698
- WHERE n.kind = 'new input' AND n.by_workflow IS NOT NULL AND n.by_workflow <> t.workflow GROUP BY 1, 2 ORDER BY 1, 2`,
699
- ).all() as ReadonlyArray<NewInputFlow>, [])),
700
- listedWaits: () => storeCall('tasks: listedWaits', () =>
701
- read((db) => db.query(
702
- `SELECT workflow, json_extract(listed, '$.on') AS "on", json_extract(listed, '$.label') AS label, COUNT(*) AS tasks FROM tasks
703
- WHERE listed IS NOT NULL AND json_extract(listed, '$.kind') = 'wait' GROUP BY 1, 2, 3 ORDER BY 1, 2, 3`,
704
- ).all() as ReadonlyArray<ListedWait>, [])),
705
782
  writable: () => options.file() !== null,
706
783
  };
707
784
 
@@ -217,8 +217,16 @@ export interface LastStepNow {
217
217
 
218
218
  export interface StepRecords {
219
219
  // ------------------------------------------------------------------ written by the step definer
220
- /** Opens a step's record. It works on what `subject` names, else on what the run last worked on. Null where nothing is written. */
221
- readonly openStepRun: (r: { readonly workflow: string; readonly run: string; readonly step: string; readonly call: number | null; readonly agent: boolean; readonly subject: string | null }) => Effect.Effect<number | null, StorageError>;
220
+ /**
221
+ * Opens a step's record. It works on what `subject` names, else on what the run last worked on, else on what the run
222
+ * that started it as a sub-workflow works on. `resume`: the run's open record of this step and call is taken up again
223
+ * where there is one (a sub-workflow step, run again when its workflow has ended). Null where nothing is written.
224
+ */
225
+ readonly openStepRun: (r: { readonly workflow: string; readonly run: string; readonly step: string; readonly call: number | null; readonly agent: boolean; readonly subject: string | null; readonly resume?: true }) => Effect.Effect<number | null, StorageError>;
226
+ /** The run a sub-workflow step started, on that step's open record: what ties a run to the run above it. */
227
+ readonly setStepChild: (r: { readonly id: number; readonly childRun: string }) => Effect.Effect<void, StorageError>;
228
+ /** The run at the top of the runs that started this one as a sub-workflow, with its workflow; none for a run nothing started so. */
229
+ readonly rootOfRun: (run: string) => Effect.Effect<{ readonly run: string; readonly workflow: string } | null, StorageError>;
222
230
  readonly beatStepRun: (id: number) => Effect.Effect<void, StorageError>;
223
231
  /** What an agent step has spent so far, on its open record, as each usage arrives. */
224
232
  readonly updateStepSpend: (r: { readonly id: number; readonly spend: StepSpend; readonly model: string | null }) => Effect.Effect<void, StorageError>;
@@ -249,7 +257,10 @@ export interface StepRecords {
249
257
  readonly stepFilesOf: (r: { readonly run: string; readonly step: string }) => Effect.Effect<string | null, StorageError>;
250
258
  /** The step a run did last, and whether it failed; none before its first. A step a restart interrupted is not one. */
251
259
  readonly lastStepOf: (run: string) => Effect.Effect<{ readonly step: string; readonly failed: boolean; readonly owner: ProcessIdentity | null } | null, StorageError>;
252
- /** The runs of a workflow with an agent step's record open now: the agents it has in use. */
260
+ /**
261
+ * The runs of a workflow an agent works for now: each with an agent step's record open and not waiting, its own or that
262
+ * of a run under it (one a sub-workflow step of it started, at any depth). The agents it has in use.
263
+ */
253
264
  readonly runsInAgentStep: (workflow: string) => Effect.Effect<ReadonlyArray<string>, StorageError>;
254
265
  /** The step a run is on now, and what it works on. */
255
266
  readonly stepOfRun: (run: string) => Effect.Effect<{ readonly step: string; readonly subject: string | null; readonly started: number } | null, StorageError>;
@@ -62,21 +62,64 @@ export interface NewNote {
62
62
  readonly change?: TextChange;
63
63
  }
64
64
 
65
- /** Where a workflow's list last put a task: on one of its lines, or waiting on something it names. */
65
+ /**
66
+ * Where a workflow's list last put a task: on one of its lines, or among the items it says no run should start on, with
67
+ * the reason (`label`) and what it waits for (`on`).
68
+ */
66
69
  export type Listed =
67
- /** `position`: its place in the whole list, across its lines; `last`: its workflow's queue takes it after every other. */
68
- | { readonly kind: 'line'; readonly label: string; readonly position?: number; readonly last?: true }
70
+ | { readonly kind: 'line'; readonly label: string }
69
71
  | { readonly kind: 'wait'; readonly label: string; readonly on: string };
70
72
 
71
- /** A task as stored: its notes oldest first, and where its list last put it, none when off the list. */
72
- export interface TaskFacts {
73
+ /**
74
+ * WHERE A TASK'S NOTES LEAVE IT (`tasks.ts`, where the rule is written down): the newest of its outcomes, its blocks and
75
+ * its returns to the queue decides. `removed`: its workflow no longer has the item.
76
+ */
77
+ export type NotedStatus = 'queued' | 'blocked' | 'done' | 'removed';
78
+
79
+ /** The note kinds a status is read from, and what each leaves a task as. A run that stood down wrote no such note. */
80
+ export const STATUS_KINDS: Readonly<Record<string, NotedStatus>> = {
81
+ queued: 'queued', unblocked: 'queued', 'listed again': 'queued', blocked: 'blocked', removed: 'removed',
82
+ // Kinds written before 2026-11-19, read as what they did: each put its task back in its queue, or held it out.
83
+ reopened: 'queued', 'new input': 'queued', resumed: 'queued', released: 'queued', held: 'blocked', 'waits on': 'blocked',
84
+ };
85
+ /** The kinds after which a task's count of failed tries starts again: every return to the queue but a lapsed block's. */
86
+ export const TRIES_START_AGAIN_KINDS: ReadonlyArray<string> = ['queued', 'reopened', 'new input', 'resumed', 'released'];
87
+ /** The outcome of a run that stood down for its workflow's limits: no agent was called, so it is no try and no status. */
88
+ export const STOOD_DOWN_OUTCOME = 'stood down';
89
+ /** The kind a reading of its workflow's list writes on a task it holds again: back in its queue, its failed tries still counted. */
90
+ export const LISTED_AGAIN = 'listed again';
91
+ /** The kind the reorder call writes: its task goes ahead of the queue until a run takes it. */
92
+ export const MOVED_TO_FRONT = 'moved to front';
93
+
94
+ /** A task as its queue reads it, from one query: no note is read in code. */
95
+ export interface TaskState {
73
96
  readonly id: number;
74
97
  readonly ref: TaskRef;
75
98
  readonly listed: Listed | null;
76
- readonly notes: ReadonlyArray<TaskNote>;
99
+ readonly status: NotedStatus;
100
+ /** Why, in the words of the note that left it there; none for a task no note has moved. */
101
+ readonly why: string | null;
102
+ /** The kind of that note; none for a task no note has moved. */
103
+ readonly kind: string | null;
104
+ /** When it came to that status, unix seconds: its note's time, or when it was made. */
105
+ readonly since: number;
106
+ /** That note's id: what orders two tasks of one moment. 0 with none. */
107
+ readonly note: number;
108
+ /** The id of its `moved to front` note written since it came to that status; none otherwise. */
109
+ readonly front: number | null;
110
+ /** Failed tries since its count last started again. */
111
+ readonly tries: number;
112
+ /** The fingerprint of its inputs that note recorded (an outcome's, a block's); none where it recorded none. */
113
+ readonly inputs: string | null;
114
+ /** The other task that note is about: the one a blocked task waits on. */
115
+ readonly about: TaskRef | null;
116
+ /** Whether a step or a person put it back in its queue (`TRIES_START_AGAIN_KINDS`), and its final check has not passed since. */
117
+ readonly returned: boolean;
118
+ /** Notes on it that changed its text: what the flipping rule reads only where there are enough to flip. */
119
+ readonly changes: number;
77
120
  }
78
121
 
79
- /** How many of a workflow's tasks stood in one bucket from `at` on, unix seconds. */
122
+ /** How many of a workflow's tasks stood in one status from `at` on, unix seconds. */
80
123
  export interface QueueCount {
81
124
  readonly at: number;
82
125
  readonly workflow: string;
@@ -84,20 +127,10 @@ export interface QueueCount {
84
127
  readonly tasks: number;
85
128
  }
86
129
 
87
- /** New input one workflow's runs gave another workflow's tasks (`tasks.ts` `giveNewInput`): how many notes, the last when. */
88
- export interface NewInputFlow {
89
- readonly from: string;
90
- readonly to: string;
91
- readonly notes: number;
92
- readonly last: number;
93
- }
94
-
95
- /** A workflow's tasks its list last put on one wait, by what they wait on and the list's words for it. */
96
- export interface ListedWait {
97
- readonly workflow: string;
98
- readonly on: string;
99
- readonly label: string;
100
- readonly tasks: number;
130
+ /** What a reading of a workflow's list changed. */
131
+ export interface ListingRecorded {
132
+ /** Whether it put any task in the queue: one new to the list, or one it lists again. */
133
+ readonly fresh: boolean;
101
134
  }
102
135
 
103
136
  export interface TaskStore {
@@ -107,31 +140,50 @@ export interface TaskStore {
107
140
  */
108
141
  readonly append: (notes: ReadonlyArray<NewNote>) => Effect.Effect<ReadonlyArray<number | null>, StorageError>;
109
142
  /**
110
- * In one transaction: appends a run's outcome on its task and, when it is new and finished, a 'resumed' note on every task
111
- * waiting on it and a 'waiter resumed' note on it for each. Returns whether the outcome was new and the tasks resumed.
143
+ * In one transaction: appends a run's outcome on its task; where the run's step blocked it, a `blocked` note after it;
144
+ * and, when the outcome is new and finished, a `queued` note on every task blocked waiting on it. Returns whether the
145
+ * outcome was new and the tasks returned to their queues.
146
+ */
147
+ readonly appendOutcome: (r: {
148
+ readonly task: TaskRef; readonly by: NoteBy; readonly why: string; readonly finished: boolean; readonly inputs: string | null;
149
+ /** Why the run's step blocked the task, where it did. */
150
+ readonly blocked: string | null;
151
+ readonly resumedWhy: (waiter: TaskRef) => string;
152
+ }) => Effect.Effect<{ readonly appended: boolean; readonly resumed: ReadonlyArray<TaskRef> }, StorageError>;
153
+ /**
154
+ * WHERE A WORKFLOW'S LIST PUTS EACH OF ITS ITEMS NOW, replacing the last listing in one transaction. `everyItem` says
155
+ * which kind of list it is (`steps.ts` `WorkflowDeclaration`):
156
+ *
157
+ * every item (`items`) a task is made for each; one whose item left the list gets a `removed` note, and one listed
158
+ * again a `listed again` note, which puts it in the queue. No status moves otherwise.
159
+ * work left (`pending`) an item off the list is its workflow's task only while it is done, or once a step or a
160
+ * person has put it back in the queue, until it finishes. One listed again after
161
+ * it left, or listed as work while done (by a list read after it finished), gets a
162
+ * `listed again` note, which puts it in the queue.
112
163
  */
113
- readonly appendOutcome: (r: { readonly task: TaskRef; readonly by: NoteBy; readonly why: string; readonly finished: boolean; readonly inputs: string | null; readonly resumedWhy: (waiter: TaskRef) => { readonly resumed: string; readonly waiterResumed: string } }) => Effect.Effect<{ readonly appended: boolean; readonly resumed: ReadonlyArray<TaskRef> }, StorageError>;
164
+ readonly recordListing: (r: {
165
+ readonly workflow: string; readonly listed: ReadonlyArray<{ readonly item: string; readonly listed: Listed }>;
166
+ readonly everyItem: boolean;
167
+ /** When the list was read, unix seconds. */
168
+ readonly readAt: number;
169
+ readonly by: NoteBy;
170
+ }) => Effect.Effect<ListingRecorded, StorageError>;
114
171
  /**
115
- * Where a workflow's list puts each of its items now, replacing the last listing in one transaction. Returns whether any
116
- * item was not listed before, which is new work for its Pick.
172
+ * A workflow's tasks as their notes leave them. Only those that are its own now: on its list; or done; or put back in its
173
+ * queue by a step or a person and not finished since, whatever its list says; never one
174
+ * `removed`.
117
175
  */
118
- readonly recordListing: (r: { readonly workflow: string; readonly listed: ReadonlyArray<{ readonly item: string; readonly listed: Listed }> }) => Effect.Effect<boolean, StorageError>;
119
- /** A workflow's tasks, each with its notes; none before the store has any. */
120
- readonly tasksOf: (workflow: string) => Effect.Effect<ReadonlyArray<TaskFacts>, StorageError>;
121
- /** One task with its notes; none for a task no workflow has named. */
122
- readonly task: (task: TaskRef) => Effect.Effect<TaskFacts | null, StorageError>;
176
+ readonly statesOf: (workflow: string) => Effect.Effect<ReadonlyArray<TaskState>, StorageError>;
177
+ /** One task as its notes leave it, its workflow's own now or not; none for a task no workflow has named. */
178
+ readonly state: (task: TaskRef) => Effect.Effect<TaskState | null, StorageError>;
123
179
  /** A task's notes, oldest first. */
124
180
  readonly notes: (task: TaskRef) => Effect.Effect<ReadonlyArray<TaskNote>, StorageError>;
125
181
  /** A task's stable id; null for one no workflow has named yet. */
126
182
  readonly taskId: (task: TaskRef) => Effect.Effect<number | null, StorageError>;
127
183
  /** Records each queue's counts as they are `at`, a count only where it differs from the last recorded for it. */
128
184
  readonly recordQueueCounts: (r: { readonly at: number; readonly counts: ReadonlyArray<Omit<QueueCount, 'at'>> }) => Effect.Effect<void, StorageError>;
129
- /** Each count recorded since `since`, and for each queue and bucket the last recorded before it, oldest first. */
185
+ /** Each count recorded since `since`, and for each queue and status the last recorded before it, oldest first. */
130
186
  readonly queueCountsSince: (since: number) => Effect.Effect<ReadonlyArray<QueueCount>, StorageError>;
131
- /** Every workflow that gave another's tasks new input, by the two. */
132
- readonly newInputFlows: () => Effect.Effect<ReadonlyArray<NewInputFlow>, StorageError>;
133
- /** Every wait a workflow's list puts its tasks on now, with how many. */
134
- readonly listedWaits: () => Effect.Effect<ReadonlyArray<ListedWait>, StorageError>;
135
187
  /** Whether the store can be written: false in a test that named no store. */
136
188
  readonly writable: () => boolean;
137
189
  }