@jive-sh/workflow-platform 0.7.0 → 1.0.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 (195) hide show
  1. package/README.md +66 -435
  2. package/component/_generated/api.ts +72 -0
  3. package/component/_generated/component.ts +621 -0
  4. package/component/_generated/dataModel.ts +60 -0
  5. package/component/_generated/server.ts +169 -0
  6. package/component/convex.config.ts +3 -0
  7. package/component/engine.ts +755 -0
  8. package/component/errors.ts +66 -0
  9. package/component/events.ts +17 -0
  10. package/component/notes.ts +13 -0
  11. package/component/places.ts +136 -0
  12. package/component/retention.ts +205 -0
  13. package/component/runEngine.ts +25 -0
  14. package/component/schema.ts +132 -0
  15. package/component/steps.ts +188 -0
  16. package/component/store.ts +512 -0
  17. package/component/tasks.ts +289 -0
  18. package/component/worker.ts +109 -0
  19. package/component/workflows.ts +83 -0
  20. package/dist/definition/agent-runner.js +9 -0
  21. package/dist/definition/agent-runner.js.map +1 -0
  22. package/dist/definition/file-store.js +9 -0
  23. package/dist/definition/file-store.js.map +1 -0
  24. package/dist/definition/program-build.js +10 -0
  25. package/dist/definition/program-build.js.map +1 -0
  26. package/dist/definition/step.js +1 -0
  27. package/dist/definition/step.js.map +1 -0
  28. package/dist/definition/task-schema.js +5 -0
  29. package/dist/definition/task-schema.js.map +1 -0
  30. package/dist/definition/tasks.js +9 -0
  31. package/dist/definition/tasks.js.map +1 -0
  32. package/dist/definition/workflow.js +111 -0
  33. package/dist/definition/workflow.js.map +1 -0
  34. package/dist/graph.js +301 -9
  35. package/dist/graph.js.map +1 -1
  36. package/dist/index.js +7 -196
  37. package/dist/index.js.map +1 -1
  38. package/package.json +9 -4
  39. package/src/definition/agent-runner.ts +59 -0
  40. package/src/definition/file-store.ts +20 -0
  41. package/src/definition/program-build.ts +30 -0
  42. package/src/definition/step.ts +106 -0
  43. package/src/definition/task-schema.ts +15 -0
  44. package/src/definition/tasks.ts +43 -0
  45. package/src/definition/workflow.ts +255 -0
  46. package/src/graph.ts +341 -19
  47. package/src/index.ts +8 -238
  48. package/worker/directory-file-store.ts +42 -0
  49. package/worker/index.ts +12 -0
  50. package/worker/platform-client.ts +138 -0
  51. package/worker/step-meter.ts +80 -0
  52. package/worker/worker-tasks.ts +27 -0
  53. package/worker/worker.test.ts +200 -0
  54. package/worker/worker.ts +240 -0
  55. package/dist/budget-states.js +0 -30
  56. package/dist/budget-states.js.map +0 -1
  57. package/dist/cpu-limit/limiter.js +0 -839
  58. package/dist/cpu-limit/limiter.js.map +0 -1
  59. package/dist/cpu-limit/use.js +0 -139
  60. package/dist/cpu-limit/use.js.map +0 -1
  61. package/dist/dashboard/agent-usage.js +0 -25
  62. package/dist/dashboard/agent-usage.js.map +0 -1
  63. package/dist/dashboard/dashboard.css +0 -148
  64. package/dist/dashboard/drilldown.js +0 -47
  65. package/dist/dashboard/drilldown.js.map +0 -1
  66. package/dist/dashboard/queue-lines.js +0 -44
  67. package/dist/dashboard/queue-lines.js.map +0 -1
  68. package/dist/dashboard/queue-table.js +0 -16
  69. package/dist/dashboard/queue-table.js.map +0 -1
  70. package/dist/dashboard/run-doing-words.js +0 -29
  71. package/dist/dashboard/run-doing-words.js.map +0 -1
  72. package/dist/dashboard/setting-words.js +0 -18
  73. package/dist/dashboard/setting-words.js.map +0 -1
  74. package/dist/dashboard/spending-words.js +0 -24
  75. package/dist/dashboard/spending-words.js.map +0 -1
  76. package/dist/failure.js +0 -35
  77. package/dist/failure.js.map +0 -1
  78. package/dist/keep-running.js +0 -79
  79. package/dist/keep-running.js.map +0 -1
  80. package/dist/outside-failure.js +0 -31
  81. package/dist/outside-failure.js.map +0 -1
  82. package/dist/pick-wakes.js +0 -125
  83. package/dist/pick-wakes.js.map +0 -1
  84. package/dist/project.js +0 -1
  85. package/dist/project.js.map +0 -1
  86. package/dist/queue-counts.js +0 -51
  87. package/dist/queue-counts.js.map +0 -1
  88. package/dist/reasons.js +0 -33
  89. package/dist/reasons.js.map +0 -1
  90. package/dist/retention.js +0 -59
  91. package/dist/retention.js.map +0 -1
  92. package/dist/settings.js +0 -88
  93. package/dist/settings.js.map +0 -1
  94. package/dist/spending-limit.js +0 -82
  95. package/dist/spending-limit.js.map +0 -1
  96. package/dist/step-files.js +0 -200
  97. package/dist/step-files.js.map +0 -1
  98. package/dist/step-meter.js +0 -97
  99. package/dist/step-meter.js.map +0 -1
  100. package/dist/step-times.js +0 -114
  101. package/dist/step-times.js.map +0 -1
  102. package/dist/step-usage.js +0 -19
  103. package/dist/step-usage.js.map +0 -1
  104. package/dist/steps.js +0 -1205
  105. package/dist/steps.js.map +0 -1
  106. package/dist/storage/agent-claims.js +0 -3
  107. package/dist/storage/agent-claims.js.map +0 -1
  108. package/dist/storage/budgets.js +0 -121
  109. package/dist/storage/budgets.js.map +0 -1
  110. package/dist/storage/engine-records.js +0 -91
  111. package/dist/storage/engine-records.js.map +0 -1
  112. package/dist/storage/engine-storage.js +0 -67
  113. package/dist/storage/engine-storage.js.map +0 -1
  114. package/dist/storage/input-records.js +0 -12
  115. package/dist/storage/input-records.js.map +0 -1
  116. package/dist/storage/move-store.js +0 -251
  117. package/dist/storage/move-store.js.map +0 -1
  118. package/dist/storage/sqlite-store.js +0 -901
  119. package/dist/storage/sqlite-store.js.map +0 -1
  120. package/dist/storage/step-records.js +0 -11
  121. package/dist/storage/step-records.js.map +0 -1
  122. package/dist/storage/storage-error.js +0 -19
  123. package/dist/storage/storage-error.js.map +0 -1
  124. package/dist/storage/task-store.js +0 -30
  125. package/dist/storage/task-store.js.map +0 -1
  126. package/dist/system-workflows.js +0 -54
  127. package/dist/system-workflows.js.map +0 -1
  128. package/dist/tasks.js +0 -500
  129. package/dist/tasks.js.map +0 -1
  130. package/dist/views/format.js +0 -37
  131. package/dist/views/format.js.map +0 -1
  132. package/dist/views/runs-now.js +0 -117
  133. package/dist/views/runs-now.js.map +0 -1
  134. package/dist/views/step-funnel.js +0 -98
  135. package/dist/views/step-funnel.js.map +0 -1
  136. package/dist/views/step-graph.js +0 -39
  137. package/dist/views/step-graph.js.map +0 -1
  138. package/dist/views/workflows-view.js +0 -236
  139. package/dist/views/workflows-view.js.map +0 -1
  140. package/src/budget-states.ts +0 -54
  141. package/src/cpu-limit/limiter.ts +0 -935
  142. package/src/cpu-limit/use.ts +0 -166
  143. package/src/dashboard/agent-usage-line.tsx +0 -28
  144. package/src/dashboard/agent-usage.ts +0 -48
  145. package/src/dashboard/dashboard.css +0 -148
  146. package/src/dashboard/drilldown.ts +0 -70
  147. package/src/dashboard/index.tsx +0 -4
  148. package/src/dashboard/limits-and-runs.tsx +0 -191
  149. package/src/dashboard/machine-controls.tsx +0 -53
  150. package/src/dashboard/queue-bar.tsx +0 -62
  151. package/src/dashboard/queue-chart.tsx +0 -149
  152. package/src/dashboard/queue-lines.ts +0 -87
  153. package/src/dashboard/queue-table.ts +0 -37
  154. package/src/dashboard/run-doing-words.ts +0 -41
  155. package/src/dashboard/setting-words.ts +0 -30
  156. package/src/dashboard/spending-limit-control.tsx +0 -47
  157. package/src/dashboard/spending-words.ts +0 -32
  158. package/src/dashboard/time-distribution.tsx +0 -61
  159. package/src/dashboard/workflow-dag.tsx +0 -322
  160. package/src/dashboard/workflow-drilldown.tsx +0 -31
  161. package/src/dashboard/workflows-dashboard.tsx +0 -532
  162. package/src/failure.ts +0 -36
  163. package/src/keep-running.ts +0 -85
  164. package/src/outside-failure.ts +0 -39
  165. package/src/pick-wakes.ts +0 -182
  166. package/src/project.ts +0 -127
  167. package/src/queue-counts.ts +0 -64
  168. package/src/reasons.ts +0 -30
  169. package/src/retention.ts +0 -90
  170. package/src/settings.ts +0 -171
  171. package/src/spending-limit.ts +0 -139
  172. package/src/step-files.ts +0 -208
  173. package/src/step-meter.ts +0 -120
  174. package/src/step-times.ts +0 -151
  175. package/src/step-usage.ts +0 -23
  176. package/src/steps.ts +0 -1616
  177. package/src/storage/agent-claims.ts +0 -63
  178. package/src/storage/budgets.ts +0 -152
  179. package/src/storage/engine-records.ts +0 -119
  180. package/src/storage/engine-storage.ts +0 -82
  181. package/src/storage/input-records.ts +0 -43
  182. package/src/storage/move-store.ts +0 -265
  183. package/src/storage/sqlite-store.ts +0 -1022
  184. package/src/storage/step-records.ts +0 -358
  185. package/src/storage/storage-error.ts +0 -35
  186. package/src/storage/task-store.ts +0 -235
  187. package/src/system-workflows.ts +0 -70
  188. package/src/tasks.ts +0 -586
  189. package/src/views/format.ts +0 -40
  190. package/src/views/runs-now.ts +0 -188
  191. package/src/views/step-funnel.ts +0 -163
  192. package/src/views/step-graph.ts +0 -77
  193. package/src/views/workflows-view.ts +0 -484
  194. package/src/workflow-dag.test.tsx +0 -89
  195. package/src/workflow-page.test.tsx +0 -170
@@ -1,63 +0,0 @@
1
- /**
2
- * THE AGENT CLAIMS: one record per run that claims agents (`steps.ts` `agentsClaimedBy`), written only by the step definer
3
- * at the run's first agent step and as the run ends. Alex, 2026-11-22: "a subworkflow write C claims one on decompiles
4
- * agents so while that task's own workflow is doing all these different things, some are agentic steps and deterministic
5
- * steps but as that's going on decompile is down one agent."
6
- *
7
- * A claim counts against the agents' limit of the workflow at the top of its run (`top`): Write C's against Decompile's. It
8
- * holds from its start to its end, every step of its run between, and through a handover or a crash: an interrupted run
9
- * resumes and keeps it. It counts only while the run at its top is unfinished in the engine, so a claim whose end was
10
- * never written (a write that failed) stops counting when that run ends, and nothing sweeps the table to recover it.
11
- *
12
- * An interface, as the step records are (`step-records.ts`): `sqlite-store.ts` keeps them in the project's one database,
13
- * in `agent_claims`.
14
- */
15
- import type { Effect } from 'effect';
16
- import type { StorageError } from './storage-error';
17
-
18
- /** A run and its workflow. */
19
- export interface RunOf {
20
- readonly run: string;
21
- readonly workflow: string;
22
- }
23
-
24
- /** One claim as stored. */
25
- export interface AgentClaim {
26
- readonly run: string;
27
- readonly workflow: string;
28
- /** The run at the top of its run, whose workflow's agents' limit it counts against. */
29
- readonly top: RunOf;
30
- /** How many agents it claims. */
31
- readonly agents: number;
32
- /** When it started, unix seconds. */
33
- readonly started: number;
34
- /** When it ended, unix seconds; none while it holds. */
35
- readonly ended: number | null;
36
- /** How its run ended: `success`, `failure`; none while it holds. */
37
- readonly outcome: string | null;
38
- }
39
-
40
- /** What taking a claim gave: it was taken, or the limit had no room for it; or nothing was written, with no store. */
41
- export type ClaimTaken = 'taken' | 'no room' | 'not recorded';
42
-
43
- export interface AgentClaims {
44
- /**
45
- * TAKES A CLAIM FOR `run`, IN ONE STATEMENT, where the claims held against `top.workflow` leave room for `agents` more
46
- * under `limit`: the open claims whose top run is one of `liveTopRuns` (the engine's unfinished runs of that workflow),
47
- * this run's own left out. With no limit (`null`) it is always taken. Two processes taking at once cannot both fit in
48
- * the last place.
49
- */
50
- readonly takeAgentClaim: (r: { readonly run: string; readonly workflow: string; readonly top: RunOf; readonly agents: number; readonly limit: number | null; readonly liveTopRuns: ReadonlyArray<string> }) => Effect.Effect<ClaimTaken, StorageError>;
51
- /** Whether `run`, or a run above it (one whose sub-workflow step started it, at any depth), holds a claim now. */
52
- readonly claimHeldAtOrAbove: (run: string) => Effect.Effect<boolean, StorageError>;
53
- /** Ends every claim `run` holds, with how its run ended: the claims it ended, each with its top. */
54
- readonly endAgentClaims: (r: { readonly run: string; readonly outcome: string }) => Effect.Effect<ReadonlyArray<AgentClaim>, StorageError>;
55
- /** Every claim not ended, oldest first; whether each still counts is its top run's (`AgentClaims` above). */
56
- readonly openAgentClaims: () => Effect.Effect<ReadonlyArray<AgentClaim>, StorageError>;
57
- /** Every claim that started since `since`, or is still open, oldest first: what a time chart draws. */
58
- readonly agentClaimsSince: (since: number) => Effect.Effect<ReadonlyArray<AgentClaim>, StorageError>;
59
- }
60
-
61
- /** The claims that count now: open, with their top run unfinished in the engine (`live`). Pure. */
62
- export const claimsCounting = (open: ReadonlyArray<AgentClaim>, live: ReadonlySet<string>): ReadonlyArray<AgentClaim> =>
63
- open.filter((c) => c.ended === null && live.has(c.top.run));
@@ -1,152 +0,0 @@
1
- /**
2
- * EACH WORKFLOW'S TWO LIMITS, for a workflow with an agent step and a list of work (`steps.ts` `keptRunningByItsBudget`):
3
- *
4
- * runs how many runs it keeps going, and nothing else does. None stored means the default: its agents' limit.
5
- * agents how many of its runs may be in an agent step at once: its budget, as its owner sets it. A run with a task whose
6
- * first agent call finds them all in use ends there, its task marked as needing an agent, at the back of its
7
- * queue (`steps.ts` `untilAgentSlot`); a run past its first agent call, or with no task, waits for one, no CPU
8
- * used. 0 is the owner's decision and no fault: nothing gets past a first agent step, and a run with a task
9
- * ends there the same way.
10
- *
11
- * Alex, 2026-11-14: "there was supposed to be a number of runs concurrently allowed setting per workflow and also a number
12
- * of concurrent agents allowed per workflow setting". One number did both until 2026-11-12; until 2026-11-14 the default
13
- * run limit was one at 0 agents for a workflow whose Pick takes its queue's head, which tested and gave back a task each run. `LimitStore` is what the platform reads;
14
- * `sqliteBudgets` reads the `workflow_budgets` table of the project's file, which the project writes through the
15
- * statements below.
16
- */
17
- import { Database } from 'bun:sqlite';
18
- import type { Effect } from 'effect';
19
- import fs from 'node:fs';
20
- import { storeCall, type StorageError } from './storage-error';
21
- import { RUNTIME_SETTINGS, type RuntimeSettingName, type SettingLevel, type StoredSetting } from '../settings';
22
-
23
- export const WORKFLOW_BUDGETS_SQL = 'SELECT workflow, budget, runs, changed_at FROM workflow_budgets';
24
- export const WORKFLOW_BUDGET_SQL = 'SELECT budget, runs FROM workflow_budgets WHERE workflow = ?';
25
- /** Sets a workflow's agents' limit, keeping its run limit. */
26
- export const SET_WORKFLOW_BUDGET_SQL =
27
- 'INSERT INTO workflow_budgets(workflow, budget, changed_at) VALUES (?, ?, ?) ON CONFLICT(workflow) DO UPDATE SET budget = excluded.budget, changed_at = excluded.changed_at';
28
- /** Sets a workflow's run limit, none for the default, keeping its agents' limit. */
29
- export const SET_WORKFLOW_RUNS_SQL =
30
- 'INSERT INTO workflow_budgets(workflow, budget, runs, changed_at) VALUES (?, 0, ?, ?) ON CONFLICT(workflow) DO UPDATE SET runs = excluded.runs, changed_at = excluded.changed_at';
31
-
32
- /**
33
- * THE ONE SPENDING LIMIT (`spending-limit.ts`): a table of one row beside `workflow_budgets`, since it is the account's and
34
- * no workflow's: `spending_limit(id INTEGER PRIMARY KEY CHECK (id = 1), week_percent INTEGER NOT NULL, changed_at REAL NOT
35
- * NULL)`. None stored is the default. As with `workflow_budgets`, the project makes the table and writes it through the
36
- * statement below.
37
- */
38
- export const SPENDING_LIMIT_SQL = 'SELECT week_percent, changed_at FROM spending_limit WHERE id = 1';
39
- /** Sets the spending limit: the percent of the week at which agents stop. */
40
- export const SET_SPENDING_LIMIT_SQL =
41
- 'INSERT INTO spending_limit(id, week_percent, changed_at) VALUES (1, ?, ?) ON CONFLICT(id) DO UPDATE SET week_percent = excluded.week_percent, changed_at = excluded.changed_at';
42
-
43
- /**
44
- * THE RETENTION SETTINGS SET WHILE THE APP RUNS (`settings.ts` `StoredSetting`): a table beside `workflow_budgets`, one row
45
- * a level and setting, `workflow_settings(workflow TEXT NOT NULL, step TEXT NOT NULL, setting TEXT NOT NULL, value REAL,
46
- * changed_at REAL NOT NULL, PRIMARY KEY (workflow, step, setting))`. The app's level is `workflow = ''` and a workflow's
47
- * `step = ''`, names no workflow or step has. A value of NULL puts its level back to the code's value, as a run limit
48
- * of NULL puts it back to its default; `changed_at` is when it was last set. As with `workflow_budgets`, the project makes
49
- * the table and writes it through the statement below.
50
- */
51
- export const WORKFLOW_SETTINGS_SQL = 'SELECT workflow, step, setting, value, changed_at FROM workflow_settings';
52
- /** Sets one setting at one level (`settingRow`): a value, or none for the code's. */
53
- export const SET_WORKFLOW_SETTING_SQL =
54
- 'INSERT INTO workflow_settings(workflow, step, setting, value, changed_at) VALUES (?, ?, ?, ?, ?) ON CONFLICT(workflow, step, setting) DO UPDATE SET value = excluded.value, changed_at = excluded.changed_at';
55
-
56
- /** A level as the table keys it. Pure. */
57
- export const settingRow = (level: SettingLevel): { readonly workflow: string; readonly step: string } =>
58
- level.kind === 'app' ? { workflow: '', step: '' } : level.kind === 'workflow' ? { workflow: level.workflow, step: '' } : { workflow: level.workflow, step: level.step };
59
-
60
- /** A row as the setting it stores; none for a setting no page sets (a row a newer version wrote). Pure. */
61
- const storedOf = (r: { readonly workflow: string; readonly step: string; readonly setting: string; readonly value: number | null; readonly changed_at: number }): StoredSetting | null => {
62
- if (!(RUNTIME_SETTINGS as ReadonlyArray<string>).includes(r.setting)) return null;
63
- const level: SettingLevel = r.workflow === '' ? { kind: 'app' } : r.step === '' ? { kind: 'workflow', workflow: r.workflow } : { kind: 'step', workflow: r.workflow, step: r.step };
64
- return { level, name: r.setting as RuntimeSettingName, value: r.value, changedAt: r.changed_at };
65
- };
66
-
67
- /** The spending limit as stored: the percent of the week at which agents stop, and when it was set, unix seconds. */
68
- export interface StoredSpendingLimit {
69
- readonly weekPercent: number;
70
- readonly changedAt: number;
71
- }
72
-
73
- export interface WorkflowBudgetRow {
74
- readonly workflow: string;
75
- /** The agents' limit. */
76
- readonly budget: number;
77
- /** The run limit; none for the default. */
78
- readonly runs: number | null;
79
- readonly changed_at: number;
80
- }
81
-
82
- /** A workflow's limits as stored: its agents', and its runs', none for the default. */
83
- export interface WorkflowLimits {
84
- readonly agents: number;
85
- readonly runs: number | null;
86
- }
87
-
88
- export interface LimitStore {
89
- /** A workflow's limits: 0 agents with none stored, and none where there is no store to read (a test). */
90
- readonly limitsOf: (workflow: string) => Effect.Effect<WorkflowLimits | null, StorageError>;
91
- /** Every stored workflow's limits, by name, in one read: one with none stored is absent. None where there is no store. */
92
- readonly storedLimits: () => Effect.Effect<ReadonlyMap<string, WorkflowLimits> | null, StorageError>;
93
- /** The spending limit as set; none where none was set or there is no store, which is the default. */
94
- readonly spendingLimit: () => Effect.Effect<StoredSpendingLimit | null, StorageError>;
95
- /** Every retention setting set while the app runs; none stored is empty, and so is no store. */
96
- readonly storedSettings: () => Effect.Effect<ReadonlyArray<StoredSetting>, StorageError>;
97
- }
98
-
99
- /**
100
- * HOW MANY RUNS OF A WORKFLOW ARE KEPT GOING: its run limit, or with none stored its agents' limit. The run limit alone says
101
- * how many runs exist; the agents' limit alone says how many of them may be in an agent step (`steps.ts` `agentSlot`). Pure.
102
- */
103
- export const runLimit = (limits: WorkflowLimits): number => (limits.runs !== null ? limits.runs : limits.agents);
104
-
105
- export const sqliteBudgets = (options: { readonly file: () => string }): LimitStore => ({
106
- limitsOf: (workflow) => storeCall('limits: limitsOf', () => {
107
- const file = options.file();
108
- if (!fs.existsSync(file)) return null;
109
- const db = new Database(file, { readonly: true });
110
- try {
111
- if (db.query(`SELECT 1 FROM sqlite_master WHERE name = 'workflow_budgets'`).get() === null) return null;
112
- const row = db.query(WORKFLOW_BUDGET_SQL).get(workflow) as { budget: number; runs: number | null } | null;
113
- return row === null ? { agents: 0, runs: null } : { agents: row.budget, runs: row.runs };
114
- } finally {
115
- db.close();
116
- }
117
- }),
118
- storedLimits: () => storeCall('limits: storedLimits', () => {
119
- const file = options.file();
120
- if (!fs.existsSync(file)) return null;
121
- const db = new Database(file, { readonly: true });
122
- try {
123
- if (db.query(`SELECT 1 FROM sqlite_master WHERE name = 'workflow_budgets'`).get() === null) return null;
124
- return new Map((db.query(WORKFLOW_BUDGETS_SQL).all() as ReadonlyArray<WorkflowBudgetRow>).map((r) => [r.workflow, { agents: r.budget, runs: r.runs }]));
125
- } finally {
126
- db.close();
127
- }
128
- }),
129
- storedSettings: () => storeCall('limits: storedSettings', () => {
130
- const file = options.file();
131
- if (!fs.existsSync(file)) return [];
132
- const db = new Database(file, { readonly: true });
133
- try {
134
- if (db.query(`SELECT 1 FROM sqlite_master WHERE name = 'workflow_settings'`).get() === null) return [];
135
- return (db.query(WORKFLOW_SETTINGS_SQL).all() as ReadonlyArray<Parameters<typeof storedOf>[0]>).flatMap((r) => { const s = storedOf(r); return s === null ? [] : [s]; });
136
- } finally {
137
- db.close();
138
- }
139
- }),
140
- spendingLimit: () => storeCall('limits: spendingLimit', () => {
141
- const file = options.file();
142
- if (!fs.existsSync(file)) return null;
143
- const db = new Database(file, { readonly: true });
144
- try {
145
- if (db.query(`SELECT 1 FROM sqlite_master WHERE name = 'spending_limit'`).get() === null) return null;
146
- const row = db.query(SPENDING_LIMIT_SQL).get() as { week_percent: number; changed_at: number } | null;
147
- return row === null ? null : { weekPercent: row.week_percent, changedAt: row.changed_at };
148
- } finally {
149
- db.close();
150
- }
151
- }),
152
- });
@@ -1,119 +0,0 @@
1
- /**
2
- * WHAT THE WORKFLOW ENGINE ITSELF RECORDS: which runs are not finished. effect/cluster stores each workflow run and each
3
- * step (an activity) as a `cluster_messages` row and its result as a `cluster_replies` row; a reply sets its request's
4
- * `processed` in the statement that stores it (`SqlMessageStorage` `saveReply`). Their ids are snowflakes, which carry the
5
- * millisecond they were made in.
6
- *
7
- * `EngineRecords` is what the platform asks of them; `sqliteEngineRecords` reads them from the engine's SQLite file.
8
- */
9
- import { Database } from 'bun:sqlite';
10
- import type { Effect } from 'effect';
11
- import fs from 'node:fs';
12
- import { storeCall, type StorageError } from './storage-error';
13
-
14
- /** A run the engine has not finished: asked for, with no reply yet, or suspended (its reply `Suspended`, until it resumes). */
15
- export interface UnfinishedRun {
16
- readonly workflow: string;
17
- readonly run: string;
18
- }
19
-
20
- export interface EngineRecords {
21
- /** Every unfinished run of every workflow, oldest first: what "going now" means. */
22
- readonly unfinishedRuns: () => Effect.Effect<ReadonlyArray<UnfinishedRun>, StorageError>;
23
- /** The unfinished runs of these workflows, oldest first. */
24
- readonly runsOldestFirst: (workflows: ReadonlyArray<string>) => Effect.Effect<ReadonlyArray<string>, StorageError>;
25
- /** How many runs of a workflow are not finished now. */
26
- readonly runningRuns: (workflow: string) => Effect.Effect<number, StorageError>;
27
- }
28
-
29
- /** The engine's entity type for a workflow, as it names its messages. */
30
- export const entityTypeOf = (workflowName: string) => `Workflow/${workflowName}`;
31
-
32
- /** effect/cluster's snowflake epoch (`Snowflake.constEpochMillis`), 2025-01-01. */
33
- const SNOWFLAKE_EPOCH_MS = Date.UTC(2025, 0, 1);
34
-
35
- /** The SQL for a snowflake id's millisecond, for a column `col`. */
36
- export const millis = (col: string) => `((${col} >> 22) + ${SNOWFLAKE_EPOCH_MS})`;
37
-
38
- /** The SQL's millisecond bound for a window starting at unix second `since`. */
39
- export const sinceMillis = (since: number) => Math.floor(since * 1000);
40
-
41
- /** Reads the engine's records, read-only, from its own file. None before the engine has created the file and its tables. */
42
- export const readEngineFile = <A>(file: string, read: (db: Database) => A): A | null => {
43
- if (!fs.existsSync(file)) return null;
44
- const db = new Database(file, { readonly: true });
45
- try {
46
- const ready = db.query(`SELECT 1 AS present FROM sqlite_master WHERE name = 'cluster_replies'`).get() !== null;
47
- return ready ? read(db) : null;
48
- } finally {
49
- db.close();
50
- }
51
- };
52
-
53
- /** The SQL condition for a reply, its payload in column `payload`, that says its run is suspended: `Success` with a `Suspended` result. */
54
- const suspendedReply = (payload: string) => `json_extract(${payload}, '$.value._tag') = 'Suspended'`;
55
-
56
- /**
57
- * THE INDEXES THE ENGINE'S QUERIES NEED, which its file does not have. Every poll, mailbox read and run count scanned all
58
- * 62,000 messages, 16 to 38 ms each, about 30 times a minute (2026-11-04). Partial, so each stays the size of the few it is for.
59
- */
60
- const ENGINE_INDEXES = [
61
- 'CREATE INDEX IF NOT EXISTS cluster_messages_undelivered ON cluster_messages (shard_id, entity_type, entity_id) WHERE processed = 0',
62
- 'CREATE INDEX IF NOT EXISTS cluster_messages_by_workflow ON cluster_messages (entity_type, tag, request_id)',
63
- // A reply marks its request processed by this column: up to 213 ms a reply, unindexed, on 2026-11-04.
64
- 'CREATE INDEX IF NOT EXISTS cluster_messages_by_request ON cluster_messages (request_id)',
65
- // The runs not finished, which every Pick, start and count reads. Without it each read walked all 82,738 run messages,
66
- // 250 ms, and a waiting Pick read it on every wake (2026-11-12).
67
- "CREATE INDEX IF NOT EXISTS cluster_messages_unfinished_runs ON cluster_messages (entity_type, request_id) WHERE tag = 'run' AND processed = 0",
68
- // The runs suspended, the other half of those not finished: 2 of the 222,092 replies, one of them a run's (2026-11-21).
69
- `CREATE INDEX IF NOT EXISTS cluster_replies_suspended ON cluster_replies (request_id) WHERE ${suspendedReply('payload')}`,
70
- ];
71
-
72
- /** Makes them once the engine has made its tables; with them there, this writes nothing. */
73
- export const ensureEngineIndexes = (file: string): void => {
74
- if (!fs.existsSync(file)) return;
75
- const db = new Database(file);
76
- try {
77
- db.exec('PRAGMA busy_timeout = 1000');
78
- if (db.query(`SELECT 1 FROM sqlite_master WHERE name = 'cluster_messages'`).get() === null) return;
79
- for (const statement of ENGINE_INDEXES) db.exec(statement);
80
- } finally {
81
- db.close();
82
- }
83
- };
84
-
85
- /**
86
- * THE RUNS NOT FINISHED, as a table of their run messages (`entity_type`, `entity_id`, `request_id`): each with no reply, and
87
- * each whose reply is `Suspended`. A suspended run is not finished: the engine stores that reply as it suspends (a durable
88
- * clock or deferred it waits on, a handover, `steps.ts` `handedOverBeforeStep`), and deletes it as the run resumes
89
- * (`ClusterWorkflowEngine` `resume`). Read as finished, a run handed over at a reload had "ended", so the runs its
90
- * sub-workflow steps started stood down and its run limit let more start (2026-11-21). Each half has the terms of its
91
- * partial index, so the read uses it. The suspended half reads its index first (`CROSS JOIN` keeps that order): read from
92
- * the messages first, it walked every run message of the workflows asked about, 64 ms for all of them (2026-11-21).
93
- */
94
- const UNFINISHED_RUNS = `(
95
- SELECT m.entity_type, m.entity_id, m.request_id FROM cluster_messages m
96
- WHERE m.tag = 'run' AND m.processed = 0 AND NOT EXISTS (SELECT 1 FROM cluster_replies p WHERE p.request_id = m.request_id)
97
- UNION ALL
98
- SELECT m.entity_type, m.entity_id, m.request_id FROM cluster_replies s CROSS JOIN cluster_messages m ON m.request_id = s.request_id
99
- WHERE ${suspendedReply('s.payload')} AND m.tag = 'run')`;
100
-
101
- /** The engine's records in its SQLite file, at the file `file` names when each call is made. */
102
- export const sqliteEngineRecords = (options: { readonly file: () => string }): EngineRecords => ({
103
- unfinishedRuns: () => storeCall('engine records: unfinishedRuns', () =>
104
- readEngineFile(options.file(), (db) => db.query(
105
- `SELECT substr(u.entity_type, ${entityTypeOf('').length + 1}) AS workflow, u.entity_id AS run FROM ${UNFINISHED_RUNS} u
106
- WHERE u.entity_type GLOB '${entityTypeOf('')}*'
107
- ORDER BY u.request_id`,
108
- ).all() as Array<UnfinishedRun>) ?? []),
109
- runsOldestFirst: (workflows) => storeCall('engine records: runsOldestFirst', () =>
110
- readEngineFile(options.file(), (db) => (db.query(
111
- `SELECT u.entity_id AS id FROM ${UNFINISHED_RUNS} u
112
- WHERE u.entity_type IN (SELECT value FROM json_each(?))
113
- ORDER BY u.request_id`,
114
- ).all(JSON.stringify(workflows.map(entityTypeOf))) as Array<{ id: string }>).map((r) => r.id)) ?? []),
115
- runningRuns: (workflow) => storeCall('engine records: runningRuns', () =>
116
- readEngineFile(options.file(), (db) => Number((db.query(
117
- `SELECT COUNT(*) AS n FROM ${UNFINISHED_RUNS} u WHERE u.entity_type = ?`,
118
- ).get(entityTypeOf(workflow)) as { n: number }).n)) ?? 0),
119
- });
@@ -1,82 +0,0 @@
1
- /**
2
- * THE ENGINE'S STORAGE, IN THE PROJECT'S ONE DATABASE, NEVER WAITING INSIDE SQLITE: effect/cluster's SQL message and runner
3
- * storage, each call tried again every 20 ms while yielding when it meets a held lock, on a client that waits 0 ms.
4
- *
5
- * Why: the engine ran in the project's database once, and on 2026-11-01 from 05:38 to 05:52 UTC every writer in every
6
- * process failed. A connection waiting inside SQLite holds its thread, and the transaction that thread holds on another
7
- * connection of the same file can then never finish (`STORAGE.md`). The engine's own client waited (`busyTimeout`), so it
8
- * kept a file of its own. Here no call waits inside SQLite: one that meets the lock fails at once and is tried again from
9
- * the Effect scheduler, so whatever this thread holds can finish meanwhile. Retrying a whole call is safe: a call that
10
- * meets the lock has written nothing, since every engine transaction takes the lock at its start (`BEGIN IMMEDIATE`).
11
- *
12
- * The same as `SingleRunner.layer` (`effect/cluster`) but for the two storages.
13
- */
14
- import { Cause, Effect, Exit, Layer, Schedule } from 'effect';
15
- import { MessageStorage, RunnerHealth, Runners, RunnerStorage, Sharding, ShardingConfig, Snowflake, SqlMessageStorage, SqlRunnerStorage } from 'effect/cluster';
16
-
17
- /** A held lock, anywhere in a failure's chain of causes. */
18
- export const isHeldLock = (failure: unknown): boolean => {
19
- const seen = new Set<unknown>();
20
- const look = (e: unknown): boolean => {
21
- if (e === null || e === undefined || seen.has(e)) return false;
22
- seen.add(e);
23
- if (typeof e === 'string') return /database is locked|SQLITE_BUSY/i.test(e);
24
- if (typeof e !== 'object') return false;
25
- const o = e as { readonly message?: unknown; readonly code?: unknown; readonly cause?: unknown; readonly reason?: unknown };
26
- return look(o.message) || look(o.code) || look(o.reason) || look(o.cause) || /database is locked|SQLITE_BUSY/i.test(String(e));
27
- };
28
- return look(failure);
29
- };
30
-
31
- /** An effect tried again every 20 ms for up to 30 s while it meets a held lock. */
32
- export const retryHeldLock = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
33
- Effect.retry(effect, { while: isHeldLock, times: 1500, schedule: Schedule.spaced('20 millis') });
34
-
35
- /**
36
- * The same for a storage's construction, whose migrations meet the lock as a defect (effect/cluster runs them `orDie`):
37
- * tried again while its failure or defect is a held lock.
38
- */
39
- const retryHeldLockAtStart = <A, E, R>(effect: Effect.Effect<A, E, R>, triesLeft = 1500): Effect.Effect<A, E, R> =>
40
- Effect.flatMap(Effect.exit(effect), (exit) => {
41
- if (Exit.isSuccess(exit)) return Effect.succeed(exit.value);
42
- if (triesLeft > 0 && isHeldLock(Cause.squash(exit.cause))) return Effect.andThen(Effect.sleep('20 millis'), retryHeldLockAtStart(effect, triesLeft - 1));
43
- return Effect.failCause(exit.cause);
44
- });
45
-
46
- /**
47
- * A storage whose every call, an effect or a function returning one, is tried again while it meets a held lock: each call a
48
- * span (`<storage>.<call>`) over all its tries, so a trace shows how long a call waited on the lock.
49
- */
50
- const retrying = <S extends object>(storage: S, spanPrefix: string): S =>
51
- Object.fromEntries(Object.entries(storage).map(([name, member]) => {
52
- const traced = <A, E, R>(call: Effect.Effect<A, E, R>) => Effect.withSpan(retryHeldLock(call), `${spanPrefix}.${name}`);
53
- if (Effect.isEffect(member)) return [name, traced(member)];
54
- if (typeof member === 'function') {
55
- return [name, (...args: Array<unknown>) => {
56
- const out = (member as (...a: Array<unknown>) => unknown).apply(storage, args);
57
- return Effect.isEffect(out) ? traced(out) : out;
58
- }];
59
- }
60
- return [name, member];
61
- })) as S;
62
-
63
- /** The message storage: effect/cluster's SQL one, its migrations included, with every call retried on a held lock. */
64
- export const lockRetryingMessageStorage = Layer.effect(
65
- MessageStorage.MessageStorage,
66
- Effect.flatMap(retryHeldLockAtStart(SqlMessageStorage.makeEncoded()), (encoded) => MessageStorage.makeEncoded(retrying(encoded, 'MessageStorage'))),
67
- ).pipe(Layer.provide(Snowflake.layerGenerator));
68
-
69
- /** The runner storage, the same way. */
70
- export const lockRetryingRunnerStorage = Layer.effect(
71
- RunnerStorage.RunnerStorage,
72
- Effect.map(retryHeldLockAtStart(SqlRunnerStorage.make({})), (storage) => RunnerStorage.RunnerStorage.of(retrying(storage, 'RunnerStorage'))),
73
- );
74
-
75
- /** One process's runner on these two storages: `SingleRunner.layer` with `runnerStorage: 'sql'`, but never waiting. */
76
- export const lockRetryingSingleRunner = (shardingConfig: Partial<ShardingConfig.ShardingConfig['Service']>) =>
77
- Sharding.layer.pipe(
78
- Layer.provideMerge(Runners.layerNoop),
79
- Layer.provideMerge(lockRetryingMessageStorage),
80
- Layer.provide([Layer.orDie(lockRetryingRunnerStorage), RunnerHealth.layerNoop]),
81
- Layer.provide(ShardingConfig.layerFromEnv(shardingConfig)),
82
- );
@@ -1,43 +0,0 @@
1
- /**
2
- * WHAT EACH RUN RAN ON: the fingerprint of the inputs a workflow declares (`steps.ts` `inputs`), taken when its trigger
3
- * started the run, and how the run ended. A trigger starts a run only when the fingerprint differs from the last successful
4
- * run's, and that run's result stands for the inputs it ran on (`resultFor`). Stored by the store beside the step records.
5
- */
6
- import type { Effect } from 'effect';
7
- import type { StorageError } from './storage-error';
8
-
9
- export type InputRunOutcome = 'running' | 'success' | 'failure' | 'interrupted';
10
-
11
- export interface InputRun {
12
- readonly workflow: string;
13
- /** The inputs' fingerprint. */
14
- readonly inputs: string;
15
- readonly run: string;
16
- /** When it started, unix seconds. */
17
- readonly at: number;
18
- readonly outcome: InputRunOutcome;
19
- /** Its result, JSON, once it succeeded. */
20
- readonly result: string | null;
21
- }
22
-
23
- export interface InputRecords {
24
- /** A run the trigger started on these inputs. */
25
- readonly recordStart: (r: { readonly workflow: string; readonly inputs: string; readonly run: string }) => Effect.Effect<void, StorageError>;
26
- /** How a run with recorded inputs ended; a run with none recorded is no input run, and nothing is written. */
27
- readonly recordEnd: (r: { readonly run: string; readonly outcome: Exclude<InputRunOutcome, 'running'>; readonly result: string | null }) => Effect.Effect<void, StorageError>;
28
- /** A workflow's newest successful run: what its inputs were and what it gave. */
29
- readonly lastSuccess: (workflow: string) => Effect.Effect<InputRun | null, StorageError>;
30
- /** Every input run since a time, oldest first: what the test of unchanged re-runs reads. */
31
- readonly runsSince: (since: number) => Effect.Effect<ReadonlyArray<InputRun>, StorageError>;
32
- }
33
-
34
- /** Runs that succeeded on the same inputs as the workflow's success before them: work done twice. Pure. */
35
- export const rerunsOnUnchangedInputs = (runs: ReadonlyArray<InputRun>): ReadonlyArray<InputRun> => {
36
- const last = new Map<string, string>();
37
- return runs.filter((r) => {
38
- if (r.outcome !== 'success') return false;
39
- const again = last.get(r.workflow) === r.inputs;
40
- last.set(r.workflow, r.inputs);
41
- return again;
42
- });
43
- };