@jive-sh/workflow-platform 0.5.2 → 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 (50) 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/project.js +0 -4
  9. package/dist/project.js.map +1 -1
  10. package/dist/queue-counts.js +7 -1
  11. package/dist/queue-counts.js.map +1 -1
  12. package/dist/spending-limit.js +87 -0
  13. package/dist/spending-limit.js.map +1 -0
  14. package/dist/steps.js +125 -14
  15. package/dist/steps.js.map +1 -1
  16. package/dist/storage/budgets.js +27 -2
  17. package/dist/storage/budgets.js.map +1 -1
  18. package/dist/storage/sqlite-store.js +13 -2
  19. package/dist/storage/sqlite-store.js.map +1 -1
  20. package/dist/storage/task-store.js +10 -1
  21. package/dist/storage/task-store.js.map +1 -1
  22. package/dist/tasks.js +35 -5
  23. package/dist/tasks.js.map +1 -1
  24. package/dist/views/format.js +2 -0
  25. package/dist/views/format.js.map +1 -1
  26. package/dist/views/runs-now.js +12 -0
  27. package/dist/views/runs-now.js.map +1 -1
  28. package/dist/views/workflows-view.js +9 -2
  29. package/dist/views/workflows-view.js.map +1 -1
  30. package/package.json +1 -1
  31. package/src/dashboard/dashboard.css +5 -0
  32. package/src/dashboard/queue-bar.tsx +5 -5
  33. package/src/dashboard/queue-table.ts +17 -3
  34. package/src/dashboard/spending-limit-control.tsx +50 -0
  35. package/src/dashboard/spending-words.ts +50 -0
  36. package/src/dashboard/workflow-dag.tsx +1 -1
  37. package/src/dashboard/workflow-drilldown.tsx +5 -5
  38. package/src/dashboard/workflows-dashboard.tsx +28 -3
  39. package/src/index.ts +13 -4
  40. package/src/project.ts +35 -0
  41. package/src/queue-counts.ts +8 -1
  42. package/src/spending-limit.ts +155 -0
  43. package/src/steps.ts +140 -19
  44. package/src/storage/budgets.ts +34 -2
  45. package/src/storage/sqlite-store.ts +14 -3
  46. package/src/storage/task-store.ts +17 -1
  47. package/src/tasks.ts +43 -5
  48. package/src/views/format.ts +3 -0
  49. package/src/views/runs-now.ts +4 -0
  50. package/src/views/workflows-view.ts +27 -4
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 {
@@ -75,6 +78,7 @@ const workflowRunsNow = <Phase extends string>(d: Declared<Phase>, runs: Readonl
75
78
  waitingAfter: waiting.length,
76
79
  waitingSince: waiting.length === 0 ? null : Math.min(...waiting),
77
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,
78
82
  };
79
83
  });
80
84
  return {
@@ -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({