@jive-sh/workflow-platform 0.5.1 → 0.6.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 (54) hide show
  1. package/README.md +50 -5
  2. package/dist/dashboard/queue-table.js +10 -2
  3. package/dist/dashboard/queue-table.js.map +1 -1
  4. package/dist/dashboard/spending-words.js +32 -0
  5. package/dist/dashboard/spending-words.js.map +1 -0
  6. package/dist/index.js +13 -4
  7. package/dist/index.js.map +1 -1
  8. package/dist/pick-wakes.js +1 -0
  9. package/dist/pick-wakes.js.map +1 -1
  10. package/dist/project.js +0 -4
  11. package/dist/project.js.map +1 -1
  12. package/dist/queue-counts.js +7 -1
  13. package/dist/queue-counts.js.map +1 -1
  14. package/dist/spending-limit.js +87 -0
  15. package/dist/spending-limit.js.map +1 -0
  16. package/dist/steps.js +150 -17
  17. package/dist/steps.js.map +1 -1
  18. package/dist/storage/budgets.js +27 -2
  19. package/dist/storage/budgets.js.map +1 -1
  20. package/dist/storage/sqlite-store.js +14 -3
  21. package/dist/storage/sqlite-store.js.map +1 -1
  22. package/dist/storage/task-store.js +10 -1
  23. package/dist/storage/task-store.js.map +1 -1
  24. package/dist/tasks.js +35 -5
  25. package/dist/tasks.js.map +1 -1
  26. package/dist/views/format.js +2 -0
  27. package/dist/views/format.js.map +1 -1
  28. package/dist/views/runs-now.js +30 -2
  29. package/dist/views/runs-now.js.map +1 -1
  30. package/dist/views/workflows-view.js +9 -2
  31. package/dist/views/workflows-view.js.map +1 -1
  32. package/package.json +1 -1
  33. package/src/dashboard/dashboard.css +5 -0
  34. package/src/dashboard/queue-bar.tsx +5 -5
  35. package/src/dashboard/queue-table.ts +17 -3
  36. package/src/dashboard/spending-limit-control.tsx +50 -0
  37. package/src/dashboard/spending-words.ts +50 -0
  38. package/src/dashboard/workflow-dag.tsx +1 -1
  39. package/src/dashboard/workflow-drilldown.tsx +5 -5
  40. package/src/dashboard/workflows-dashboard.tsx +28 -3
  41. package/src/index.ts +13 -4
  42. package/src/pick-wakes.ts +3 -0
  43. package/src/project.ts +35 -0
  44. package/src/queue-counts.ts +8 -1
  45. package/src/spending-limit.ts +155 -0
  46. package/src/steps.ts +180 -30
  47. package/src/storage/budgets.ts +34 -2
  48. package/src/storage/sqlite-store.ts +15 -4
  49. package/src/storage/step-records.ts +2 -0
  50. package/src/storage/task-store.ts +17 -1
  51. package/src/tasks.ts +43 -5
  52. package/src/views/format.ts +3 -0
  53. package/src/views/runs-now.ts +21 -3
  54. package/src/views/workflows-view.ts +27 -4
@@ -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 { LISTED_AGAIN, MOVED_TO_FRONT, STATUS_KINDS, STOOD_DOWN_OUTCOME, TRIES_START_AGAIN_KINDS, type Listed, type ListedWait, type NewNote, type QueueCount, type ReturnedBetween, type TaskNote, type TaskRef, type TaskState, type TaskStore } from './task-store';
14
+ import { AGENT_STEP_RAN, LISTED_AGAIN, MOVED_TO_FRONT, NEEDS_AN_AGENT, STATUS_KINDS, STOOD_DOWN_OUTCOME, TRIES_START_AGAIN_KINDS, type Listed, type ListedWait, type NewNote, type QueueCount, type ReturnedBetween, 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
 
@@ -291,12 +291,19 @@ const quoted = (kinds: ReadonlyArray<string>): string => kinds.map((k) => `'${k.
291
291
  const IS_STATUS_NOTE = `((n.kind = 'outcome' AND n.why <> '${STOOD_DOWN_OUTCOME}') OR n.kind IN (${quoted(Object.keys(STATUS_KINDS))}))`;
292
292
  /** A note after which a task's failed tries are counted again: its final check passing, or a return to its queue. */
293
293
  const STARTS_TRIES_AGAIN = `((n.kind = 'outcome' AND n.finished = 1) OR n.kind IN (${quoted(TRIES_START_AGAIN_KINDS)}))`;
294
+ /**
295
+ * A note `c` that clears task `t`'s `needs an agent` mark (`task-store.ts` `TaskState.needsAgent`): something new from outside
296
+ * its workflow (a return to its queue, a move to the front, any note by a person or by another workflow), an agent step that
297
+ * ran on it, or its final check passing.
298
+ */
299
+ const CLEARS_NEEDS_AN_AGENT = `(c.kind IN (${quoted([...TRIES_START_AGAIN_KINDS, MOVED_TO_FRONT, AGENT_STEP_RAN])}) OR (c.kind = 'outcome' AND c.finished = 1)
300
+ OR c.by_workflow IS NULL OR c.by_workflow <> t.workflow)`;
294
301
 
295
302
  interface StateRow {
296
303
  readonly id: number; readonly workflow: string; readonly item: string; readonly listed: string | null; readonly created_at: number;
297
304
  readonly note: number | null; readonly front: number | null; readonly kind: string | null; readonly why: string | null; readonly at: number | null;
298
305
  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;
306
+ readonly tries: number; readonly changes: number; readonly start_kind: string | null; readonly needs_agent: string | null;
300
307
  }
301
308
 
302
309
  /**
@@ -310,10 +317,13 @@ const statesWhere = (db: Database, where: string, params: ReadonlyArray<string |
310
317
  SELECT t.id AS id,
311
318
  (SELECT MAX(n.id) FROM task_notes n WHERE n.task = t.id AND ${IS_STATUS_NOTE}) AS note,
312
319
  (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
320
+ (SELECT MAX(n.id) FROM task_notes n WHERE n.task = t.id AND n.kind = '${MOVED_TO_FRONT}') AS front,
321
+ (SELECT MAX(n.id) FROM task_notes n WHERE n.task = t.id AND n.kind = '${NEEDS_AN_AGENT}') AS mark
314
322
  FROM tasks t WHERE ${where})
315
323
  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
324
  a.workflow AS about_workflow, a.item AS about_item,
325
+ CASE WHEN s.mark IS NULL OR EXISTS (SELECT 1 FROM task_notes c WHERE c.task = t.id AND c.id > s.mark AND ${CLEARS_NEEDS_AN_AGENT}) THEN NULL
326
+ ELSE (SELECT m.why FROM task_notes m WHERE m.id = s.mark) END AS needs_agent,
317
327
  (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
328
  (SELECT COUNT(*) FROM task_notes c WHERE c.task = t.id AND c.before_sha IS NOT NULL) AS changes,
319
329
  (SELECT k.kind FROM task_notes k WHERE k.id = s.start) AS start_kind
@@ -327,6 +337,7 @@ const statesWhere = (db: Database, where: string, params: ReadonlyArray<string |
327
337
  about: r.about_workflow === null || r.about_item === null ? null : { workflow: r.about_workflow, item: r.about_item },
328
338
  changes: r.changes,
329
339
  returned: r.start_kind !== null && TRIES_START_AGAIN_KINDS.includes(r.start_kind),
340
+ needsAgent: r.needs_agent,
330
341
  }));
331
342
 
332
343
  /**
@@ -661,7 +672,7 @@ export const sqliteStore = (options: {
661
672
  read((db) => (db.query('SELECT MIN(started) AS at FROM step_runs WHERE subject IS NOT NULL').get() as { at: number | null }).at, null),
662
673
  newestStepRecords: (runs) =>
663
674
  runs.length === 0 ? [] : read((db) => db.query(
664
- `SELECT s.run AS run, s.step AS step, s.agent AS agent, s.started AS started, s.ended AS ended, s.waiting AS waiting
675
+ `SELECT s.run AS run, s.step AS step, s.agent AS agent, s.started AS started, s.ended AS ended, s.waiting AS waiting, s.child_run AS childRun
665
676
  FROM step_runs s JOIN (SELECT value AS run FROM json_each(?1)) w ON w.run = s.run
666
677
  WHERE s.id = (SELECT MAX(id) FROM step_runs n WHERE n.run = s.run)`,
667
678
  ).all(JSON.stringify(runs)) as ReadonlyArray<NewestStepRecord>, []),
@@ -181,6 +181,8 @@ export interface NewestStepRecord {
181
181
  readonly ended: number | null;
182
182
  /** What an open step waits on, in its own words (a Pick with nothing it can claim); none while it works. */
183
183
  readonly waiting: string | null;
184
+ /** For a sub-workflow step: the run it started, whose own newest record says where the work is now; absent on any other. */
185
+ readonly childRun?: string | null;
184
186
  }
185
187
 
186
188
  /** One step record of a run in a funnel's window, in the order written. */
@@ -76,9 +76,19 @@ export type Listed =
76
76
  */
77
77
  export type NotedStatus = 'queued' | 'blocked' | 'done' | 'removed';
78
78
 
79
+ /**
80
+ * THE KIND THE ENGINE WRITES WHEN A RUN ENDS AT AN AGENT STEP NO AGENT CAN BE HAD FOR (`steps.ts` `untilAgentSlot`): its task
81
+ * goes to the back of its queue, marked as needing an agent, with why in words. Alex, 2026-11-20: "if a workflow run is
82
+ * paused because it needs an agent it should probably go to the back of the queue and the task gets marked for needing an
83
+ * agent such that the workflow dequeuing logic can skip over functions which need an agent when the agentic budget is zero."
84
+ */
85
+ export const NEEDS_AN_AGENT = 'needs an agent';
86
+ /** The kind the engine writes on a marked task after an agent step ran on it: it may need no agent now, so the mark clears. */
87
+ export const AGENT_STEP_RAN = 'an agent step ran';
88
+
79
89
  /** 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
90
  export const STATUS_KINDS: Readonly<Record<string, NotedStatus>> = {
81
- queued: 'queued', unblocked: 'queued', 'listed again': 'queued', blocked: 'blocked', removed: 'removed',
91
+ queued: 'queued', unblocked: 'queued', 'listed again': 'queued', blocked: 'blocked', removed: 'removed', [NEEDS_AN_AGENT]: 'queued',
82
92
  // Kinds written before 2026-11-19, read as what they did: each put its task back in its queue, or held it out.
83
93
  reopened: 'queued', 'new input': 'queued', resumed: 'queued', released: 'queued', held: 'blocked', 'waits on': 'blocked',
84
94
  };
@@ -117,6 +127,12 @@ export interface TaskState {
117
127
  readonly returned: boolean;
118
128
  /** Notes on it that changed its text: what the flipping rule reads only where there are enough to flip. */
119
129
  readonly changes: number;
130
+ /**
131
+ * WHY IT NEEDS AN AGENT, from its newest `needs an agent` note, while that mark stands; none otherwise. Something new from
132
+ * outside its workflow clears it (a return to its queue, a move to the front, any note by a person or another workflow),
133
+ * and so do an agent step that ran on it and its final check passing (`AGENT_STEP_RAN`, a finished outcome).
134
+ */
135
+ readonly needsAgent: string | null;
120
136
  }
121
137
 
122
138
  /** How many of a workflow's tasks stood in one status from `at` on, unix seconds. */
package/src/tasks.ts CHANGED
@@ -41,16 +41,16 @@ import type { PickWakes } from './pick-wakes';
41
41
  import type { EngineRecords } from './storage/engine-records';
42
42
  import type { StepRecords } from './storage/step-records';
43
43
  import type { StorageError } from './storage/storage-error';
44
- import { MOVED_TO_FRONT, STATUS_KINDS, TRIES_START_AGAIN_KINDS, type Listed, type NewNote, type NoteBy, type TaskNote, type TaskRef, type TaskState, type TaskStore } from './storage/task-store';
44
+ import { AGENT_STEP_RAN, MOVED_TO_FRONT, NEEDS_AN_AGENT, STATUS_KINDS, TRIES_START_AGAIN_KINDS, type Listed, type NewNote, type NoteBy, type TaskNote, type TaskRef, type TaskState, type TaskStore } from './storage/task-store';
45
45
 
46
- export { STOOD_DOWN_OUTCOME, TRIES_START_AGAIN_KINDS } from './storage/task-store';
46
+ export { AGENT_STEP_RAN, NEEDS_AN_AGENT, STOOD_DOWN_OUTCOME, TRIES_START_AGAIN_KINDS } from './storage/task-store';
47
47
  export type { Listed, NoteBy, TaskNote, TaskRef, TaskState } from './storage/task-store';
48
48
 
49
49
  export const TASK_STATUSES = ['queued', 'in progress', 'blocked', 'done'] as const;
50
50
  export type TaskStatus = (typeof TASK_STATUSES)[number];
51
51
 
52
52
  /** The kinds only the engine writes: a step's own note takes another. */
53
- export const ENGINE_NOTE_KINDS: ReadonlyArray<string> = ['outcome', MOVED_TO_FRONT, ...Object.keys(STATUS_KINDS), 'waiter resumed'];
53
+ export const ENGINE_NOTE_KINDS: ReadonlyArray<string> = ['outcome', MOVED_TO_FRONT, AGENT_STEP_RAN, ...Object.keys(STATUS_KINDS), 'waiter resumed'];
54
54
 
55
55
  /** Failed tries of one workflow on one item after which a Pick blocks it: it gets no run again until someone returns it to the queue. */
56
56
  export const BLOCK_AFTER_TRIES = 10;
@@ -101,6 +101,11 @@ export interface TaskSummary {
101
101
  readonly movedToFront: boolean;
102
102
  /** Whether a step or a person put it back in its queue (`requeue`, `reopen`), and its final check has not passed since. */
103
103
  readonly returned: boolean;
104
+ /**
105
+ * Why it needs an agent, in words, while it is marked so (`TaskState.needsAgent`): its Pick passes over it while no agent
106
+ * is available to its workflow. None otherwise.
107
+ */
108
+ readonly needsAgent: string | null;
104
109
  readonly listed: Listed | null;
105
110
  /** What its notes say, for the rules that read them (`standardBlock`). */
106
111
  readonly noted: TaskState;
@@ -169,13 +174,23 @@ export const summarize = (input: { readonly state: TaskState; readonly running:
169
174
  id: state.id, ref: state.ref, tries: state.tries, since: state.since, listed: state.listed, noted: state,
170
175
  movedToFront: state.front !== null,
171
176
  returned: state.returned,
177
+ needsAgent: state.needsAgent,
172
178
  };
173
179
  if (running) return { ...base, status: 'in progress', why: 'a run is on it now' };
174
180
  if (state.listed?.kind === 'wait') return { ...base, status: 'blocked', why: state.listed.label };
175
181
  if (state.status === 'done') return { ...base, status: 'done', why: state.why ?? 'its final check passed' };
176
182
  if (state.status === 'blocked') return { ...base, status: 'blocked', why: state.why ?? 'blocked by a step' };
177
183
  const said = state.kind === null ? 'not tried yet' : state.kind === 'outcome' ? `tried ${state.tries} time${state.tries === 1 ? '' : 's'}; the last: ${state.why}` : `${state.kind}: ${state.why}`;
178
- return { ...base, status: 'queued', why: state.front === null ? said : `moved to the front by hand; ${said}` };
184
+ // A mark a later note of its own workflow left standing is said too: its Pick passes over it while no agent is available.
185
+ const marked = state.needsAgent === null || state.kind === NEEDS_AN_AGENT ? said : `${said}; ${NEEDS_AN_AGENT}: ${state.needsAgent}`;
186
+ return { ...base, status: 'queued', why: state.front === null ? marked : `moved to the front by hand; ${marked}` };
187
+ };
188
+
189
+ /** How many of a workflow's queued tasks need an agent, for one reason each, most tasks first. Pure. */
190
+ export const needsAgentReasons = (tasks: ReadonlyArray<TaskSummary>): ReadonlyArray<BlockedReason> => {
191
+ const counts = new Map<string, number>();
192
+ for (const t of tasks) if (t.status === 'queued' && t.needsAgent !== null) counts.set(t.needsAgent, (counts.get(t.needsAgent) ?? 0) + 1);
193
+ return [...counts].map(([why, n]) => ({ why, tasks: n })).sort((a, b) => b.tasks - a.tasks || a.why.localeCompare(b.why));
179
194
  };
180
195
 
181
196
  /**
@@ -473,16 +488,39 @@ export const makeTasks = (deps: {
473
488
 
474
489
  /** One task's status now, and why; a task no workflow has named yet is queued. */
475
490
  const statusOf = (task: TaskRef): Effect.Effect<TaskSummary, StorageError> => Effect.gen(function* () {
476
- const state = (yield* store.state(task)) ?? { id: 0, ref: task, listed: null, status: 'queued' as const, why: null, kind: null, since: Date.now() / 1000, note: 0, front: null, tries: 0, inputs: null, about: null, changes: 0, returned: false };
491
+ const state = (yield* store.state(task)) ?? { id: 0, ref: task, listed: null, status: 'queued' as const, why: null, kind: null, since: Date.now() / 1000, note: 0, front: null, tries: 0, inputs: null, about: null, changes: 0, returned: false, needsAgent: null };
477
492
  return summarize({ state, running: (yield* itemsRunningNow()).get(task.workflow)?.has(keyOf(task.item)) === true });
478
493
  });
479
494
 
480
495
  /** What a run's agent is told of its own task: its notes, as `notesText` words them; empty with none, or with no store. */
481
496
  const notesForAgent = (task: TaskRef): Effect.Effect<string, StorageError> => (store.writable() ? Effect.map(store.notes(task), (notes) => notesText(notes)) : Effect.succeed(''));
482
497
 
498
+ /**
499
+ * MARKS A TASK AS NEEDING AN AGENT, by the run that stopped at an agent step no agent could be had for (`steps.ts`
500
+ * `untilAgentSlot`): the note puts it at the back of its queue, and its Pick passes over it while no agent is available.
501
+ * Whether it was written: with no store, or a write that failed, the run waits at its step as before.
502
+ */
503
+ const markNeedsAgent = (input: { readonly task: TaskRef; readonly by: NoteBy; readonly why: string }): Effect.Effect<boolean> =>
504
+ Effect.map(engineWrite(`the mark that ${input.task.workflow} ${input.task.item} needs an agent`, store.append([{ task: input.task, by: input.by, kind: NEEDS_AN_AGENT, why: input.why }])), (ids) => ids !== null);
505
+
506
+ /**
507
+ * Whether a task is one its workflow's Pick reads: on its list, or returned to its queue by a step or a person. A mark on
508
+ * any other is on a task no Pick passes over.
509
+ */
510
+ const readByItsPick = (task: TaskRef): Effect.Effect<boolean, StorageError> =>
511
+ Effect.map(store.state(task), (s) => s !== null && s.status !== 'removed' && (s.listed !== null || s.returned));
512
+
513
+ /** After an agent step ran on a task marked as needing an agent: the mark clears, since it may need none now. */
514
+ const agentStepRan = (input: { readonly task: TaskRef; readonly by: NoteBy }): Effect.Effect<void> => Effect.gen(function* () {
515
+ const state = yield* engineWrite(`the state of ${input.task.workflow} ${input.task.item}`, store.state(input.task));
516
+ if (state === null || state.needsAgent === null) return;
517
+ yield* engineWrite(`the end of the mark on ${input.task.workflow} ${input.task.item}`, store.append([{ task: input.task, by: input.by, kind: AGENT_STEP_RAN, why: `${input.by.step ?? 'an agent step'} ran on it, so it may need no agent now` }]));
518
+ });
519
+
483
520
  return {
484
521
  appendTaskNote, noteText, requeue, block, reopen, moveToFront, appendOutcome, recordListing, recordTaskInputs,
485
522
  taskNotes: store.notes, taskIdOf: store.taskId, itemsRunningNow, taskSummaries, settleQueue, statusOf, notesForAgent,
523
+ markNeedsAgent, readByItsPick, agentStepRan,
486
524
  };
487
525
  };
488
526
 
@@ -16,6 +16,9 @@ export const compact = (n: number): string => {
16
16
  return `${(n / 1_000_000).toFixed(1)}M`;
17
17
  };
18
18
 
19
+ /** A percent to one place, cut rather than rounded, so 94.96 never reads as 95: "94.9%", "89%". */
20
+ export const percentCut = (percent: number): string => `${Math.floor(percent * 10) / 10}%`;
21
+
19
22
  const pad = (n: number) => String(n).padStart(2, '0');
20
23
 
21
24
  /** A time as the clock on this device shows it, with the date when it is not today: "5:04 AM", "Nov 11, 5:04 AM". */
@@ -8,6 +8,7 @@
8
8
  * while the step it is in is an agent step and that step's record is still open; between steps it waits after the step
9
9
  * it last ended, and uses no agent.
10
10
  */
11
+ import { isSpendingLimitWait } from '../spending-limit';
11
12
  import type { UnfinishedRun } from '../storage/engine-records';
12
13
  import type { NewestStepRecord } from '../storage/step-records';
13
14
  import type { StepDeclaration } from '../steps';
@@ -23,6 +24,8 @@ export interface StepRunsNow {
23
24
  readonly waitingSince: number | null;
24
25
  /** What a run in it waits on, in the step's own words (a Pick with nothing it can claim); none while each works. */
25
26
  readonly waitingOn: string | null;
27
+ /** Runs in it that the spending limit holds before their agent call (`spending-limit.ts`). */
28
+ readonly heldBySpendingLimit: number;
26
29
  }
27
30
 
28
31
  export interface WorkflowRunsNow {
@@ -44,7 +47,7 @@ export interface PhaseRunsNow<Phase extends string = string> {
44
47
  readonly workflows: ReadonlyArray<WorkflowRunsNow>;
45
48
  }
46
49
 
47
- type Declared<Phase extends string> = { readonly name: string; readonly phase: Phase; readonly steps: () => ReadonlyArray<Pick<StepDeclaration, 'name' | 'runs'>> };
50
+ type Declared<Phase extends string> = { readonly name: string; readonly phase: Phase; readonly steps: () => ReadonlyArray<Pick<StepDeclaration, 'name' | 'runs' | 'workflow'>> };
48
51
 
49
52
  const sum = <T>(xs: ReadonlyArray<T>, f: (x: T) => number) => xs.reduce((a, x) => a + f(x), 0);
50
53
 
@@ -53,6 +56,16 @@ const workflowRunsNow = <Phase extends string>(d: Declared<Phase>, runs: Readonl
53
56
  const r = newest.get(run);
54
57
  return r === undefined ? [] : [r];
55
58
  });
59
+ /**
60
+ * Whether a run is on an agent now: its open step is an agent's and waits on none, or it is a sub-workflow step whose own
61
+ * run is. A run inside a sub-workflow's agent step read as on no agent, on the page of the workflow above (2026-11-19).
62
+ */
63
+ const onAnAgent = (r: NewestStepRecord, depth = 0): boolean => {
64
+ if (r.ended !== null) return false;
65
+ if (r.agent === 1) return r.waiting === null;
66
+ const under = r.childRun === undefined || r.childRun === null || depth > 8 ? undefined : newest.get(r.childRun);
67
+ return under !== undefined && onAnAgent(under, depth + 1);
68
+ };
56
69
  const declared = d.steps().map((s) => ({ name: s.name, agent: s.runs === 'agentic' }));
57
70
  const undeclared = [...new Set(records.map((r) => r.step))].filter((name) => !declared.some((s) => s.name === name))
58
71
  .map((name) => ({ name, agent: records.some((r) => r.step === name && r.agent === 1) }));
@@ -65,13 +78,14 @@ const workflowRunsNow = <Phase extends string>(d: Declared<Phase>, runs: Readonl
65
78
  waitingAfter: waiting.length,
66
79
  waitingSince: waiting.length === 0 ? null : Math.min(...waiting),
67
80
  waitingOn: on.find((r) => r.ended === null && r.waiting !== null)?.waiting ?? null,
81
+ heldBySpendingLimit: on.filter((r) => r.ended === null && r.waiting !== null && isSpendingLimitWait(r.waiting)).length,
68
82
  };
69
83
  });
70
84
  return {
71
85
  workflow: d.name,
72
86
  runs: runs.length,
73
87
  // A run waiting at an agent step for a free agent (its record says what it waits on) is on no agent.
74
- onAgents: steps.filter((s) => s.agent).reduce((n, s) => n + records.filter((r) => r.step === s.step && r.ended === null && r.waiting === null).length, 0),
88
+ onAgents: records.filter((r) => onAnAgent(r)).length,
75
89
  notStarted: runs.length - records.length,
76
90
  steps,
77
91
  };
@@ -90,6 +104,7 @@ export const runsNow = <Phase extends string>(input: {
90
104
  }): ReadonlyArray<PhaseRunsNow<Phase>> => {
91
105
  const newest = new Map(input.newest.map((r) => [r.run, r]));
92
106
  const names = new Set(input.declared.map((d) => d.name));
107
+ const asAStep = new Set(input.declared.flatMap((d) => d.steps().flatMap((s) => (s.workflow === undefined ? [] : [s.workflow]))));
93
108
  const all: ReadonlyArray<Declared<Phase>> = [
94
109
  ...input.declared,
95
110
  ...[...new Set(input.unfinished.map((u) => u.workflow))].filter((w) => !names.has(w)).map((name): Declared<Phase> => ({ name, phase: input.undefinedPhase, steps: () => [] })),
@@ -97,6 +112,9 @@ export const runsNow = <Phase extends string>(input: {
97
112
  return input.phases.map((phase): PhaseRunsNow<Phase> => {
98
113
  const workflows = all.filter((d) => d.phase === phase)
99
114
  .map((d) => workflowRunsNow(d, input.unfinished.filter((u) => u.workflow === d.name).map((u) => u.run), newest));
100
- return { phase, runs: sum(workflows, (w) => w.runs), onAgents: sum(workflows, (w) => w.onAgents), workflows };
115
+ // A phase's runs and agents are those of its workflows that start by themselves: a sub-workflow's run is part of the run
116
+ // above it, which already counts once.
117
+ const own = workflows.filter((w) => !asAStep.has(w.workflow));
118
+ return { phase, runs: sum(own, (w) => w.runs), onAgents: sum(own, (w) => w.onAgents), workflows };
101
119
  });
102
120
  };
@@ -20,6 +20,8 @@ export interface SourceLink extends SourceRef {
20
20
  }
21
21
  import { Effect } from 'effect';
22
22
  import type { StorageError } from '../storage/storage-error';
23
+ import type { SpendingLimitState } from '../spending-limit';
24
+ import { QUEUED_NEEDING_AN_AGENT } from '../queue-counts';
23
25
  import type { EngineRecords } from '../storage/engine-records';
24
26
  import type { FunnelStepRecord, RunCost, RunOutcomeRow, StepRecords, StepRunRow } from '../storage/step-records';
25
27
  import { TASK_STATUSES, type BlockedReason, type TaskStatus } from '../tasks';
@@ -191,6 +193,11 @@ export interface WorkflowView {
191
193
  readonly limits: { readonly agents: number | null; readonly runs: number | null; readonly runsSet: boolean } | null;
192
194
  /** Its tasks by status, as last counted (`queue-counts.ts`); none for a workflow with no item. */
193
195
  readonly queue: Readonly<Record<TaskStatus, number>> | null;
196
+ /**
197
+ * How many of its queued tasks are marked as needing an agent, as last counted (`queue-counts.ts`, `QUEUED_NEEDING_AN_AGENT`);
198
+ * none for a workflow with no item or no agent step, where no task can be marked.
199
+ */
200
+ readonly queuedNeedingAnAgent: number | null;
194
201
  /** Its place among the project's workflows: what the map lays it out by (`workflow-flows.ts`). */
195
202
  readonly place: PipelinePlace;
196
203
  /** What starts its runs. */
@@ -207,6 +214,8 @@ export interface WorkflowsView {
207
214
  readonly queueHistory: ReadonlyArray<QueueCount>;
208
215
  /** Where work goes between the top workflow's steps: the map's arrows (`workflow-flows.ts`). */
209
216
  readonly flows: ReadonlyArray<WorkflowFlow>;
217
+ /** The spending limit against the newest reading of the week (`spending-limit.ts`); none for a project that reads no week. */
218
+ readonly spending: SpendingLimitState | null;
210
219
  }
211
220
 
212
221
  /** One workflow's figures over a window, read from its own records when it is opened. */
@@ -227,6 +236,11 @@ export interface WorkflowFigures {
227
236
  readonly yields: { readonly now: Yield; readonly before: Yield };
228
237
  /** Why its blocked tasks are blocked now: a count for each reason, most tasks first (`tasks.ts` `blockedReasons`). */
229
238
  readonly blocked: ReadonlyArray<BlockedReason>;
239
+ /**
240
+ * Its queued tasks marked as needing an agent, a count for each reason (`tasks.ts` `needsAgentReasons`), and whether its
241
+ * Pick passes over them now because no agent can be had, with why in words; none while one can.
242
+ */
243
+ readonly needingAnAgent: { readonly reasons: ReadonlyArray<BlockedReason>; readonly passedOverBecause: string | null };
230
244
  }
231
245
 
232
246
  const NO_COST: StepCost = { calls: 0, failed: 0, open: 0, seconds: 0, inputTokens: 0, outputTokens: 0, cpuSeconds: 0, compiles: 0, items: 0 };
@@ -296,6 +310,10 @@ export const historyByStatus = (recorded: ReadonlyArray<QueueCount>): ReadonlyAr
296
310
  return out;
297
311
  };
298
312
 
313
+ /** Each queue's newest count of queued tasks marked as needing an agent, from the recorded counts (oldest first). Pure. */
314
+ export const queuedNeedingAnAgentNow = (recorded: ReadonlyArray<QueueCount>): ReadonlyMap<string, number> =>
315
+ new Map(recorded.filter((row) => row.bucket === QUEUED_NEEDING_AN_AGENT).map((row) => [row.workflow, row.tasks]));
316
+
299
317
  /** Each queue's newest count from its history by status (`historyByStatus`), a status never counted at 0. Pure. */
300
318
  export const queuesNow = (history: ReadonlyArray<QueueCount>): ReadonlyMap<string, Readonly<Record<TaskStatus, number>>> => {
301
319
  const queues = new Map<string, Record<TaskStatus, number>>();
@@ -324,13 +342,16 @@ export const buildWorkflowsView = (input: {
324
342
  readonly limitsOf: (workflow: string) => WorkflowView['limits'];
325
343
  /** The project's top workflow, in its own words, until it declares one. */
326
344
  readonly top: { readonly name: string; readonly description: string };
345
+ readonly spending: SpendingLimitState | null;
327
346
  }): Effect.Effect<WorkflowsView, StorageError> => Effect.gen(function* () {
328
347
  const stepSummary = (s: StepDeclaration): StepSummary => ({ name: s.name, kind: stepKindOf(s), runs: s.runs, description: s.description, workflow: s.workflow ?? null });
329
348
  // Until the project declares its top workflow, its steps are every workflow no other workflow uses as a step.
330
349
  const usedAsAStep = new Set(input.declared.flatMap((d) => d.steps().flatMap((s) => (s.workflow === undefined ? [] : [s.workflow]))));
331
350
  const phases = [...input.phases, ...[...new Set(input.declared.map((d) => d.phase))].filter((p) => !input.phases.includes(p))];
332
- const queueHistory = historyByStatus(yield* input.taskStore.queueCountsSince(input.now - QUEUE_HISTORY_DAYS * 86_400));
351
+ const recordedCounts = yield* input.taskStore.queueCountsSince(input.now - QUEUE_HISTORY_DAYS * 86_400);
352
+ const queueHistory = historyByStatus(recordedCounts);
333
353
  const queues = queuesNow(queueHistory);
354
+ const needingAnAgent = queuedNeedingAnAgentNow(recordedCounts);
334
355
  // The map is of the top workflow's steps: a workflow used as a step of another is drawn inside that one, not here.
335
356
  const onTheMap = input.declared.filter((d) => !usedAsAStep.has(d.name));
336
357
  const flows = workflowFlows({ declared: onTheMap, returned: yield* input.taskStore.returnedBetween(), waits: yield* input.taskStore.listedWaits() });
@@ -343,6 +364,7 @@ export const buildWorkflowsView = (input: {
343
364
  limits: usedAsAStep.has(d.name) ? null : input.limitsOf(d.name),
344
365
  place: places.get(d.name)!,
345
366
  queue: d.item === null ? null : queues.get(d.name) ?? noTasks(),
367
+ queuedNeedingAnAgent: d.item === null || !d.steps().some(stepUsesAnAgent) ? null : needingAnAgent.get(d.name) ?? 0,
346
368
  startsOn: usedAsAStep.has(d.name) ? { kind: 'a step', of: input.declared.filter((p) => p.steps().some((s) => s.workflow === d.name)).map((p) => p.name) }
347
369
  : d.pending !== undefined || d.items !== undefined ? { kind: 'queue' } : d.inputs !== undefined ? { kind: 'inputs', says: d.inputs.says } : { kind: 'timer or request' },
348
370
  });
@@ -356,6 +378,7 @@ export const buildWorkflowsView = (input: {
356
378
  groups: phases.map((phase) => ({ phase, workflows: input.declared.filter((d) => d.phase === phase).map(workflowView) })).filter((g) => g.workflows.length > 0),
357
379
  queueHistory,
358
380
  flows,
381
+ spending: input.spending,
359
382
  };
360
383
  });
361
384
 
@@ -370,8 +393,8 @@ export const buildWorkflowFigures = (input: {
370
393
  readonly hours: number;
371
394
  readonly records: StepRecords;
372
395
  readonly engine: EngineRecords;
373
- /** Why its blocked tasks are blocked now, read from its tasks. */
374
- readonly blocked: Effect.Effect<ReadonlyArray<BlockedReason>, StorageError>;
396
+ /** Why its blocked tasks are blocked now, and its queued tasks marked as needing an agent, read from its tasks. */
397
+ readonly reasons: Effect.Effect<Pick<WorkflowFigures, 'blocked' | 'needingAnAgent'>, StorageError>;
375
398
  /** The line a definition's text is on now. */
376
399
  readonly locate: (source: SourceRef) => number | null;
377
400
  }): Effect.Effect<WorkflowFigures, StorageError> => Effect.gen(function* () {
@@ -408,7 +431,7 @@ export const buildWorkflowFigures = (input: {
408
431
  graph: workflowGraphs({ declared: [d], taken: moves.edges, lasts: moves.lasts, going })[0]!,
409
432
  funnel,
410
433
  runCosts: runCostsOf(runCosts),
411
- blocked: yield* input.blocked,
434
+ ...(yield* input.reasons),
412
435
  yields: {
413
436
  now: yieldOf({ runs: funnel.runs, finished: finished(finishedNow), tokens: costNow.inputTokens + costNow.outputTokens, compiles: costNow.compiles }),
414
437
  before: yieldOf({