@jive-sh/workflow-platform 0.1.0 → 0.3.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 (40) hide show
  1. package/README.md +41 -15
  2. package/dist/cpu-limit/limiter.js +54 -11
  3. package/dist/cpu-limit/limiter.js.map +1 -1
  4. package/dist/index.js +44 -39
  5. package/dist/index.js.map +1 -1
  6. package/dist/keep-running.js +5 -5
  7. package/dist/keep-running.js.map +1 -1
  8. package/dist/pick-wakes.js +7 -1
  9. package/dist/pick-wakes.js.map +1 -1
  10. package/dist/queue-counts.js +47 -0
  11. package/dist/queue-counts.js.map +1 -0
  12. package/dist/steps.js +75 -18
  13. package/dist/steps.js.map +1 -1
  14. package/dist/storage/budgets.js +14 -0
  15. package/dist/storage/budgets.js.map +1 -1
  16. package/dist/storage/sqlite-store.js +68 -15
  17. package/dist/storage/sqlite-store.js.map +1 -1
  18. package/dist/views/workflow-flows.js +53 -0
  19. package/dist/views/workflow-flows.js.map +1 -0
  20. package/dist/views/workflows-view.js +81 -55
  21. package/dist/views/workflows-view.js.map +1 -1
  22. package/package.json +1 -1
  23. package/src/cpu-limit/limiter.ts +61 -11
  24. package/src/dashboard/dashboard.css +78 -0
  25. package/src/dashboard/index.tsx +3 -0
  26. package/src/dashboard/queue-chart.tsx +137 -0
  27. package/src/dashboard/step-graph.tsx +98 -0
  28. package/src/dashboard/workflow-dag.tsx +256 -0
  29. package/src/dashboard/workflows-dashboard.tsx +313 -0
  30. package/src/index.ts +46 -39
  31. package/src/keep-running.ts +5 -7
  32. package/src/pick-wakes.ts +9 -2
  33. package/src/queue-counts.ts +61 -0
  34. package/src/steps.ts +83 -26
  35. package/src/storage/budgets.ts +13 -0
  36. package/src/storage/sqlite-store.ts +82 -18
  37. package/src/storage/step-records.ts +6 -5
  38. package/src/storage/task-store.ts +32 -0
  39. package/src/views/workflow-flows.ts +97 -0
  40. package/src/views/workflows-view.ts +148 -82
@@ -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, NewNote, TaskFacts, TaskNote, TaskRef, TaskStore } from './task-store';
14
+ import type { Listed, ListedWait, NewInputFlow, NewNote, QueueCount, TaskFacts, TaskNote, TaskRef, TaskStore } from './task-store';
15
15
  import type { InputRecords, InputRun } from './input-records';
16
16
  import { storeCall, storeCalls } from './storage-error';
17
17
 
@@ -47,7 +47,8 @@ CREATE TABLE IF NOT EXISTS cleared_but_listed (
47
47
  );
48
48
  CREATE INDEX IF NOT EXISTS step_runs_by_start ON step_runs (started);
49
49
  CREATE INDEX IF NOT EXISTS step_runs_open ON step_runs (beat) WHERE ended IS NULL AND agent = 1;
50
- CREATE INDEX IF NOT EXISTS step_runs_by_run ON step_runs (run, id);`;
50
+ CREATE INDEX IF NOT EXISTS step_runs_by_run ON step_runs (run, id);
51
+ CREATE INDEX IF NOT EXISTS step_runs_by_workflow ON step_runs (workflow, started);`;
51
52
 
52
53
  /**
53
54
  * TASKS AND THEIR NOTES (`tasks.ts`): one row per task, a workflow and its item, and its notes, which nothing updates or
@@ -145,6 +146,30 @@ CREATE TABLE IF NOT EXISTS input_runs (
145
146
  );
146
147
  CREATE INDEX IF NOT EXISTS input_runs_by_workflow ON input_runs (workflow, at);`;
147
148
 
149
+ /**
150
+ * EACH QUEUE'S COUNTS OVER TIME: a row where a workflow's tasks in one bucket changed, so a dashboard draws its history.
151
+ * Written when a queue may have changed (`queue-counts.ts`), only where a count moved.
152
+ */
153
+ const QUEUE_COUNTS_SCHEMA = `
154
+ CREATE TABLE IF NOT EXISTS queue_counts (
155
+ at REAL NOT NULL,
156
+ workflow TEXT NOT NULL,
157
+ bucket TEXT NOT NULL,
158
+ tasks INTEGER NOT NULL,
159
+ PRIMARY KEY (workflow, bucket, at)
160
+ );
161
+ CREATE INDEX IF NOT EXISTS queue_counts_by_at ON queue_counts (at);`;
162
+
163
+ /**
164
+ * Whether a records file has the schema this code reads: every table and index the newest change to it added. A project
165
+ * that applies the schema only when it must (a write takes the lock) asks this first.
166
+ */
167
+ export const stepRecordsSchemaApplied = (db: Database): boolean => {
168
+ const newest = ['step_runs', 'queue_counts', 'step_runs_by_workflow'];
169
+ const present = new Set((db.query('SELECT name FROM sqlite_master').all() as Array<{ name: string }>).map((r) => r.name));
170
+ return newest.every((name) => present.has(name));
171
+ };
172
+
148
173
  /** Brings a records file up to the schema this code reads, as a writer or a first reader finds it. */
149
174
  export const applyStepRecordsSchema = (db: Database): void => {
150
175
  db.exec(STEP_RUNS_SCHEMA);
@@ -177,6 +202,7 @@ export const applyStepRecordsSchema = (db: Database): void => {
177
202
  if (!noteColumns.includes('input_sha')) db.exec('ALTER TABLE task_notes ADD COLUMN input_sha TEXT');
178
203
  // On an outcome, the fingerprint of the task's inputs as its run left them (`tasks.ts` `TaskInputs`).
179
204
  if (!noteColumns.includes('inputs')) db.exec('ALTER TABLE task_notes ADD COLUMN inputs TEXT');
205
+ db.exec(QUEUE_COUNTS_SCHEMA);
180
206
  db.exec(RUN_OUTCOMES_VIEW);
181
207
  // After the columns it reads.
182
208
  db.exec(FUNCTION_COSTS_VIEW);
@@ -375,6 +401,18 @@ export const sqliteStore = (options: {
375
401
  }
376
402
  };
377
403
 
404
+ /**
405
+ * The runs whose first step started at or after `?1`, one workflow's (`?2`) where it is named: those with a record in the
406
+ * window and none before it, read by the records' start (`step_runs_by_start`, `step_runs_by_workflow`) and each run's
407
+ * own (`step_runs_by_run`). Grouping every record by run to find each one's first read the whole table: 0.5 s at 166,000
408
+ * records, in each of the five readings that used it (2026-11-17).
409
+ */
410
+ const runsBegunSince = (workflow: string | undefined): string =>
411
+ `SELECT DISTINCT b.run FROM step_runs b WHERE b.started >= ?1 ${workflow === undefined ? '' : 'AND b.workflow = ?2'}
412
+ AND NOT EXISTS (SELECT 1 FROM step_runs e WHERE e.run = b.run AND e.started < ?1)`;
413
+ /** The parameters of a reading over a window, one workflow's where it is named. */
414
+ const windowOf = (since: number, workflow: string | undefined): ReadonlyArray<number | string> => (workflow === undefined ? [since] : [since, workflow]);
415
+
378
416
  const stepRecords: StepRecords = storeCalls<StepRecords>('step records', {
379
417
  openStepRun: (r) => tryWrite((db) => {
380
418
  const now = Date.now() / 1000;
@@ -469,24 +507,24 @@ export const sqliteStore = (options: {
469
507
  const r = db.query('SELECT MAX(MAX(started, beat, COALESCE(ended, 0))) AS active, MAX(ended) AS ended FROM step_runs WHERE workflow = ?').get(workflow) as { active: number | null; ended: number | null };
470
508
  return { activeAt: r.active, endedAt: r.ended };
471
509
  }, { activeAt: null, endedAt: null }),
472
- runCostsSince: (since) =>
510
+ runCostsSince: (since, workflow) =>
473
511
  read((db) => (db.query(
474
512
  `SELECT workflow, run, MIN(started) AS started, MAX(COALESCE(ended, beat)) - MIN(started) AS seconds,
475
513
  SUM(fresh + cache_write + cache_read + output) AS tokens, COALESCE(SUM(cpu_seconds), 0) AS cpuSeconds,
476
514
  COALESCE(SUM(child_cpu_seconds), 0) AS childCpuSeconds, SUM(compiles) AS compiles, COALESCE(MAX(peak_memory_mb), 0) AS peakMemoryMb,
477
515
  SUM(ended IS NULL) > 0 AS going
478
- FROM step_runs WHERE run IN (SELECT run FROM step_runs GROUP BY run HAVING MIN(started) >= ?1)
516
+ FROM step_runs WHERE run IN (${runsBegunSince(workflow)})
479
517
  GROUP BY workflow, run ORDER BY started`,
480
- ).all(since) as ReadonlyArray<Omit<RunCost, 'going'> & { going: number }>).map((r) => ({ ...r, going: r.going === 1 })), []),
481
- stepRunsSince: (since) =>
518
+ ).all(...windowOf(since, workflow)) as ReadonlyArray<Omit<RunCost, 'going'> & { going: number }>).map((r) => ({ ...r, going: r.going === 1 })), []),
519
+ stepRunsSince: (since, workflow) =>
482
520
  read((db) => db.query(
483
521
  `SELECT workflow, run, step, MAX(agent) AS agent, COUNT(*) AS calls, COALESCE(SUM(ended IS NULL), 0) AS open,
484
522
  COALESCE(SUM(outcome = 'failure'), 0) AS failed, COALESCE(SUM((ended - started) * 1000), 0) AS ms,
485
523
  SUM(fresh) AS fresh, SUM(cache_write) AS cache_write, SUM(cache_read) AS cache_read, SUM(output) AS output, SUM(compiles) AS compiles, subject, SUM(requests) AS requests,
486
524
  COALESCE(SUM(cpu_seconds), 0) AS cpu_seconds, COALESCE(SUM(files_written), 0) AS files_written, COALESCE(MAX(peak_memory_mb), 0) AS peak_memory_mb,
487
525
  MIN(CASE WHEN ended IS NULL AND agent = 1 AND requests = 0 AND fresh + cache_write + cache_read = 0 AND beat >= ?2 AND waiting IS NULL THEN started END) AS no_usage_since
488
- FROM step_runs WHERE started >= ?1 GROUP BY workflow, run, step, subject`,
489
- ).all(since, Date.now() / 1000 - AGENT_LIVE_SECONDS) as ReadonlyArray<StepRunRow>, []),
526
+ FROM step_runs WHERE started >= ?1 ${workflow === undefined ? '' : 'AND workflow = ?3'} GROUP BY workflow, run, step, subject`,
527
+ ).all(since, Date.now() / 1000 - AGENT_LIVE_SECONDS, ...(workflow === undefined ? [] : [workflow])) as ReadonlyArray<StepRunRow>, []),
490
528
  agentModelsSince: (since) =>
491
529
  read((db) => db.query('SELECT model, COUNT(*) AS steps FROM step_runs WHERE started >= ? AND model IS NOT NULL GROUP BY model').all(since) as ReadonlyArray<{ model: string; steps: number }>, []),
492
530
  stepRunsBegin: () =>
@@ -496,8 +534,8 @@ export const sqliteStore = (options: {
496
534
  `SELECT workflow, run, MIN(started) AS started, SUM(fresh) AS fresh, SUM(cache_write) AS cacheWrite, SUM(cache_read) AS cacheRead, SUM(output) AS output, SUM(requests) AS requests
497
535
  FROM step_runs WHERE agent = 1 GROUP BY workflow, run`,
498
536
  ).all() as ReadonlyArray<{ workflow: string; run: string; started: number; fresh: number; cacheWrite: number; cacheRead: number; output: number; requests: number }>, []),
499
- runOutcomesSince: (since) =>
500
- read((db) => db.query('SELECT workflow, run, subject, outcome, finished, at FROM run_outcomes WHERE at >= ?').all(since) as ReadonlyArray<RunOutcomeRow>, []),
537
+ runOutcomesSince: (since, workflow) =>
538
+ read((db) => db.query(`SELECT workflow, run, subject, outcome, finished, at FROM run_outcomes WHERE at >= ?1 ${workflow === undefined ? '' : 'AND workflow = ?2'}`).all(...windowOf(since, workflow)) as ReadonlyArray<RunOutcomeRow>, []),
501
539
  undeclaredWritesSince: (since) =>
502
540
  read((db) => db.query('SELECT hour, folder, files FROM undeclared_writes WHERE hour >= ? ORDER BY hour').all(since) as ReadonlyArray<UndeclaredWrites>, []),
503
541
  itemCosts: ({ workflow, step, since, rank = 'tokens' }) =>
@@ -548,12 +586,12 @@ export const sqliteStore = (options: {
548
586
  FROM step_runs s JOIN (SELECT value AS run FROM json_each(?1)) w ON w.run = s.run
549
587
  WHERE s.id = (SELECT MAX(id) FROM step_runs n WHERE n.run = s.run)`,
550
588
  ).all(JSON.stringify(runs)) as ReadonlyArray<NewestStepRecord>, []),
551
- funnelRecordsSince: (since) =>
589
+ funnelRecordsSince: (since, workflow) =>
552
590
  read((db) => {
553
- const inWindow = 'SELECT run FROM step_runs GROUP BY run HAVING MIN(started) >= ?1';
591
+ const inWindow = runsBegunSince(workflow);
554
592
  return {
555
- records: db.query(`SELECT workflow, run, step, agent, started, ended, outcome, reason, error, scope FROM step_runs WHERE run IN (${inWindow}) ORDER BY id`).all(since) as ReadonlyArray<FunnelStepRecord>,
556
- outcomes: db.query(`SELECT workflow, run, subject, outcome, finished, at FROM run_outcomes WHERE run IN (${inWindow})`).all(since) as ReadonlyArray<RunOutcomeRow>,
593
+ records: db.query(`SELECT workflow, run, step, agent, started, ended, outcome, reason, error, scope FROM step_runs WHERE run IN (${inWindow}) ORDER BY id`).all(...windowOf(since, workflow)) as ReadonlyArray<FunnelStepRecord>,
594
+ outcomes: db.query(`SELECT workflow, run, subject, outcome, finished, at FROM run_outcomes WHERE run IN (${inWindow})`).all(...windowOf(since, workflow)) as ReadonlyArray<RunOutcomeRow>,
557
595
  };
558
596
  }, { records: [], outcomes: [] }),
559
597
  newestCallsByItem: (r) =>
@@ -563,19 +601,19 @@ export const sqliteStore = (options: {
563
601
  AND id = (SELECT MAX(t.id) FROM step_runs t WHERE t.workflow = ?1 AND lower(t.subject) = lower(s.subject) AND t.step IN (SELECT value FROM json_each(?2)) AND t.outcome = 'success')
564
602
  ORDER BY ended DESC`,
565
603
  ).all(r.workflow, JSON.stringify(r.steps)) as ReadonlyArray<{ subject: string; run: string; activity: string; ended: number }>, []),
566
- stepEdgesSince: (since) =>
604
+ stepEdgesSince: (since, workflow) =>
567
605
  read((db) => {
568
606
  const moves = `WITH r AS (
569
607
  SELECT id, workflow, run, step, started, outcome FROM step_runs
570
- WHERE run IN (SELECT DISTINCT run FROM step_runs WHERE started >= ?1) AND COALESCE(outcome, '') != 'interrupted'),
608
+ WHERE run IN (SELECT DISTINCT run FROM step_runs WHERE started >= ?1 ${workflow === undefined ? '' : 'AND workflow = ?2'}) AND COALESCE(outcome, '') != 'interrupted'),
571
609
  t AS (SELECT workflow, run, step, started, outcome,
572
610
  LAG(step) OVER w AS prev, LAG(outcome) OVER w AS prev_outcome, LEAD(step) OVER w AS next
573
611
  FROM r WINDOW w AS (PARTITION BY run ORDER BY id))`;
574
612
  const edges = (db.query(`${moves} SELECT workflow, prev AS "from", COALESCE(prev_outcome = 'failure', 0) AS fromFailed, step AS "to", COUNT(*) AS runs
575
- FROM t WHERE started >= ?1 GROUP BY 1, 2, 3, 4`).all(since) as ReadonlyArray<Omit<StepEdgeTaken, 'fromFailed'> & { fromFailed: number }>)
613
+ FROM t WHERE started >= ?1 GROUP BY 1, 2, 3, 4`).all(...windowOf(since, workflow)) as ReadonlyArray<Omit<StepEdgeTaken, 'fromFailed'> & { fromFailed: number }>)
576
614
  .map((e) => ({ ...e, fromFailed: e.fromFailed === 1 }));
577
615
  const lasts = (db.query(`${moves} SELECT workflow, run, step, COALESCE(outcome = 'failure', 0) AS failed FROM t WHERE next IS NULL`)
578
- .all(since) as ReadonlyArray<Omit<LastStepNow, 'failed'> & { failed: number }>).map((l) => ({ ...l, failed: l.failed === 1 }));
616
+ .all(...windowOf(since, workflow)) as ReadonlyArray<Omit<LastStepNow, 'failed'> & { failed: number }>).map((l) => ({ ...l, failed: l.failed === 1 }));
579
617
  return { edges, lasts };
580
618
  }, { edges: [], lasts: [] }),
581
619
  });
@@ -637,6 +675,32 @@ export const sqliteStore = (options: {
637
675
  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), [])),
638
676
  taskId: (task) => storeCall('tasks: taskId', () =>
639
677
  read((db) => (db.query('SELECT id FROM tasks WHERE workflow = ? AND item_key = ?').get(task.workflow, keyOf(task.item)) as { id: number } | null)?.id ?? null, null)),
678
+ recordQueueCounts: ({ at, counts }) => storeCall('tasks: recordQueueCounts', () => {
679
+ if (counts.length === 0) return;
680
+ tryWrite((db) => db.transaction(() => {
681
+ const last = db.query('SELECT tasks FROM queue_counts WHERE workflow = ? AND bucket = ? ORDER BY at DESC LIMIT 1');
682
+ const insert = db.query('INSERT OR REPLACE INTO queue_counts (at, workflow, bucket, tasks) VALUES (?, ?, ?, ?)');
683
+ for (const c of counts) {
684
+ if ((last.get(c.workflow, c.bucket) as { tasks: number } | null)?.tasks !== c.tasks) insert.run(at, c.workflow, c.bucket, c.tasks);
685
+ }
686
+ }).immediate());
687
+ }),
688
+ queueCountsSince: (since) => storeCall('tasks: queueCountsSince', () =>
689
+ read((db) => db.query(
690
+ `SELECT at, workflow, bucket, tasks FROM queue_counts q
691
+ 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)
692
+ ORDER BY at`,
693
+ ).all(since) as ReadonlyArray<QueueCount>, [])),
694
+ newInputFlows: () => storeCall('tasks: newInputFlows', () =>
695
+ read((db) => db.query(
696
+ `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
697
+ 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`,
698
+ ).all() as ReadonlyArray<NewInputFlow>, [])),
699
+ listedWaits: () => storeCall('tasks: listedWaits', () =>
700
+ read((db) => db.query(
701
+ `SELECT workflow, json_extract(listed, '$.on') AS "on", json_extract(listed, '$.label') AS label, COUNT(*) AS tasks FROM tasks
702
+ WHERE listed IS NOT NULL AND json_extract(listed, '$.kind') = 'wait' GROUP BY 1, 2, 3 ORDER BY 1, 2, 3`,
703
+ ).all() as ReadonlyArray<ListedWait>, [])),
640
704
  writable: () => options.file() !== null,
641
705
  };
642
706
 
@@ -262,15 +262,16 @@ export interface StepRecords {
262
262
  readonly newestRun: (workflow: string) => Effect.Effect<{ readonly endedAt: number; readonly spent: boolean } | null, StorageError>;
263
263
  /** A workflow's newest step activity (a start, heartbeat or end) and newest step end. */
264
264
  readonly newestStepActivity: (workflow: string) => Effect.Effect<{ readonly activeAt: number | null; readonly endedAt: number | null }, StorageError>;
265
- readonly stepRunsSince: (since: number) => Effect.Effect<ReadonlyArray<StepRunRow>, StorageError>;
265
+ /** Each run's records since `since`, added up by step and subject. With `workflow`, here and below, only that workflow's. */
266
+ readonly stepRunsSince: (since: number, workflow?: string) => Effect.Effect<ReadonlyArray<StepRunRow>, StorageError>;
266
267
  /** What each run that began since `since` cost, all its steps added up, its processes' CPU included. */
267
- readonly runCostsSince: (since: number) => Effect.Effect<ReadonlyArray<RunCost>, StorageError>;
268
+ readonly runCostsSince: (since: number, workflow?: string) => Effect.Effect<ReadonlyArray<RunCost>, StorageError>;
268
269
  readonly agentModelsSince: (since: number) => Effect.Effect<ReadonlyArray<{ readonly model: string; readonly steps: number }>, StorageError>;
269
270
  /** When records begin; none before the first. */
270
271
  readonly stepRunsBegin: () => Effect.Effect<number | null, StorageError>;
271
272
  /** Every run with an agent step, all time: when it started and what its agent steps spent. */
272
273
  readonly agentRunsEver: () => Effect.Effect<ReadonlyArray<{ readonly workflow: string; readonly run: string; readonly started: number; readonly fresh: number; readonly cacheWrite: number; readonly cacheRead: number; readonly output: number; readonly requests: number }>, StorageError>;
273
- readonly runOutcomesSince: (since: number) => Effect.Effect<ReadonlyArray<RunOutcomeRow>, StorageError>;
274
+ readonly runOutcomesSince: (since: number, workflow?: string) => Effect.Effect<ReadonlyArray<RunOutcomeRow>, StorageError>;
274
275
  readonly undeclaredWritesSince: (since: number) => Effect.Effect<ReadonlyArray<UndeclaredWrites>, StorageError>;
275
276
  readonly itemCosts: (r: { readonly workflow: string; readonly step: string | null; readonly since: number; readonly rank?: ItemRank }) => Effect.Effect<ReadonlyArray<ItemCost>, StorageError>;
276
277
  /** What a workflow's steps declared as shared cost since `since`: charged to no item. */
@@ -284,9 +285,9 @@ export interface StepRecords {
284
285
  /** The newest record of each run named. */
285
286
  readonly newestStepRecords: (runs: ReadonlyArray<string>) => Effect.Effect<ReadonlyArray<NewestStepRecord>, StorageError>;
286
287
  /** Every record of every run whose first step started at or after `since`, and those runs' item outcomes. */
287
- readonly funnelRecordsSince: (since: number) => Effect.Effect<{ readonly records: ReadonlyArray<FunnelStepRecord>; readonly outcomes: ReadonlyArray<RunOutcomeRow> }, StorageError>;
288
+ readonly funnelRecordsSince: (since: number, workflow?: string) => Effect.Effect<{ readonly records: ReadonlyArray<FunnelStepRecord>; readonly outcomes: ReadonlyArray<RunOutcomeRow> }, StorageError>;
288
289
  /** Each item's newest successful call of these steps of a workflow, newest first. */
289
290
  readonly newestCallsByItem: (r: { readonly workflow: string; readonly steps: ReadonlyArray<string> }) => Effect.Effect<ReadonlyArray<{ readonly subject: string; readonly run: string; readonly activity: string; readonly ended: number }>, StorageError>;
290
291
  /** Every step-to-step move in the window, by workflow, and each run's last step. Interrupted records are not moves. */
291
- readonly stepEdgesSince: (since: number) => Effect.Effect<{ readonly edges: ReadonlyArray<StepEdgeTaken>; readonly lasts: ReadonlyArray<LastStepNow> }, StorageError>;
292
+ readonly stepEdgesSince: (since: number, workflow?: string) => Effect.Effect<{ readonly edges: ReadonlyArray<StepEdgeTaken>; readonly lasts: ReadonlyArray<LastStepNow> }, StorageError>;
292
293
  }
@@ -76,6 +76,30 @@ export interface TaskFacts {
76
76
  readonly notes: ReadonlyArray<TaskNote>;
77
77
  }
78
78
 
79
+ /** How many of a workflow's tasks stood in one bucket from `at` on, unix seconds. */
80
+ export interface QueueCount {
81
+ readonly at: number;
82
+ readonly workflow: string;
83
+ readonly bucket: string;
84
+ readonly tasks: number;
85
+ }
86
+
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;
101
+ }
102
+
79
103
  export interface TaskStore {
80
104
  /**
81
105
  * Appends notes in one transaction, in order; each one's id, or null for an outcome a run already has (a resumed run ends
@@ -100,6 +124,14 @@ export interface TaskStore {
100
124
  readonly notes: (task: TaskRef) => Effect.Effect<ReadonlyArray<TaskNote>, StorageError>;
101
125
  /** A task's stable id; null for one no workflow has named yet. */
102
126
  readonly taskId: (task: TaskRef) => Effect.Effect<number | null, StorageError>;
127
+ /** Records each queue's counts as they are `at`, a count only where it differs from the last recorded for it. */
128
+ 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. */
130
+ 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>;
103
135
  /** Whether the store can be written: false in a test that named no store. */
104
136
  readonly writable: () => boolean;
105
137
  }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * WHERE WORK FLOWS BETWEEN WORKFLOWS: the edges of a project's DAG of workflows, and each workflow's place in its pipeline.
3
+ * Built from what the platform knows and nothing written for the page:
4
+ *
5
+ * feeds a workflow declares the other among those whose results it works on (`fedBy`);
6
+ * sends back a workflow gave new input (`giveNewInput`) to a task of one that is upstream of it, through feeds;
7
+ * gives input it gave new input to a task of one that is not upstream of it, and no feed is declared between them;
8
+ * waits on its list puts tasks on a wait that names another workflow (`PendingWork.waits`), not the one that feeds it:
9
+ * the list's own words say why (`why`).
10
+ *
11
+ * Its place: its stage (the project's phases, in order), then how many feeds lead into it within its stage. Pure.
12
+ */
13
+ import type { ListedWait, NewInputFlow } from '../storage/task-store';
14
+
15
+ export type FlowKind = 'feeds' | 'sends back' | 'gives input' | 'waits on';
16
+
17
+ /** One edge: work going from one workflow to another. */
18
+ export interface WorkflowFlow {
19
+ readonly from: string;
20
+ readonly to: string;
21
+ readonly kind: FlowKind;
22
+ /** Whether a declaration says it (`fedBy`); a recorded one only is not declared. */
23
+ readonly declared: boolean;
24
+ /** The new-input notes recorded along it, and the last one's time; 0 and none where none was recorded. */
25
+ readonly notes: number;
26
+ readonly last: number | null;
27
+ /** Along a `waits on` edge: the tasks waiting, and the list's words for the wait; 0 and none on any other. */
28
+ readonly waiting: number;
29
+ readonly why: string | null;
30
+ }
31
+
32
+ /** A workflow's place in its pipeline: its stage's index, then its depth within the stage through feeds. */
33
+ export interface PipelinePlace {
34
+ readonly workflow: string;
35
+ readonly stage: number;
36
+ readonly depth: number;
37
+ }
38
+
39
+ /** Whether `to` reaches `from` through `feeds`: work goes from `to`, by way of others, to `from`. */
40
+ const reaches = (feeds: ReadonlyArray<{ readonly from: string; readonly to: string }>, start: string, target: string): boolean => {
41
+ const seen = new Set<string>([start]);
42
+ const next = [start];
43
+ while (next.length > 0) {
44
+ const at = next.pop()!;
45
+ for (const f of feeds) {
46
+ if (f.from !== at || seen.has(f.to)) continue;
47
+ if (f.to === target) return true;
48
+ seen.add(f.to);
49
+ next.push(f.to);
50
+ }
51
+ }
52
+ return false;
53
+ };
54
+
55
+ export const workflowFlows = (input: {
56
+ readonly declared: ReadonlyArray<{ readonly name: string; readonly fedBy?: ReadonlyArray<string> }>;
57
+ readonly newInputs: ReadonlyArray<NewInputFlow>;
58
+ readonly waits: ReadonlyArray<ListedWait>;
59
+ }): ReadonlyArray<WorkflowFlow> => {
60
+ const names = new Set(input.declared.map((d) => d.name));
61
+ const recorded = (from: string, to: string) => input.newInputs.find((n) => n.from === from && n.to === to);
62
+ const feeds = input.declared.flatMap((d) => (d.fedBy ?? []).filter((f) => names.has(f) && f !== d.name).map((f) => ({ from: f, to: d.name })));
63
+ const declaredFlows: ReadonlyArray<WorkflowFlow> = feeds.map((f) => {
64
+ const r = recorded(f.from, f.to);
65
+ return { from: f.from, to: f.to, kind: 'feeds', declared: true, notes: r?.notes ?? 0, last: r?.last ?? null, waiting: 0, why: null };
66
+ });
67
+ const recordedOnly: ReadonlyArray<WorkflowFlow> = input.newInputs
68
+ .filter((n) => names.has(n.from) && names.has(n.to) && !feeds.some((f) => f.from === n.from && f.to === n.to))
69
+ .map((n) => ({ from: n.from, to: n.to, kind: reaches(feeds, n.to, n.from) ? 'sends back' : 'gives input', declared: false, notes: n.notes, last: n.last, waiting: 0, why: null }));
70
+ // A wait on the workflow that feeds it is that feed's work still to come, drawn as the feed; one on another is an edge.
71
+ const waitedOn: ReadonlyArray<WorkflowFlow> = input.waits
72
+ .filter((w) => names.has(w.on) && w.on !== w.workflow && !feeds.some((f) => f.from === w.on && f.to === w.workflow))
73
+ .map((w) => ({ from: w.workflow, to: w.on, kind: 'waits on', declared: false, notes: 0, last: null, waiting: w.tasks, why: w.label }));
74
+ return [...declaredFlows, ...recordedOnly, ...waitedOn];
75
+ };
76
+
77
+ /** Each workflow's place: its stage by `stageOf` in `stages`' order (one not among them after them), then its depth there. */
78
+ export const pipelinePlaces = (input: {
79
+ readonly workflows: ReadonlyArray<{ readonly name: string; readonly stage: string }>;
80
+ readonly stages: ReadonlyArray<string>;
81
+ readonly flows: ReadonlyArray<WorkflowFlow>;
82
+ }): ReadonlyArray<PipelinePlace> => {
83
+ const stageIndex = (s: string) => (input.stages.includes(s) ? input.stages.indexOf(s) : input.stages.length);
84
+ const stageOf = new Map(input.workflows.map((w) => [w.name, stageIndex(w.stage)]));
85
+ // Forward work only: feeds, and input given to one not upstream. A send-back points against the pipeline.
86
+ const forward = input.flows.filter((f) => f.kind !== 'sends back');
87
+ const depth = new Map<string, number>();
88
+ const depthOf = (name: string, path: ReadonlySet<string>): number => {
89
+ const known = depth.get(name);
90
+ if (known !== undefined) return known;
91
+ const into = forward.filter((f) => f.to === name && !path.has(f.from) && stageOf.get(f.from) === stageOf.get(name));
92
+ const d = into.length === 0 ? 0 : Math.max(...into.map((f) => depthOf(f.from, new Set([...path, name])) + 1));
93
+ depth.set(name, d);
94
+ return d;
95
+ };
96
+ return input.workflows.map((w) => ({ workflow: w.name, stage: stageIndex(w.stage), depth: depthOf(w.name, new Set()) }));
97
+ };