@jive-sh/workflow-platform 0.6.3 → 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 (174) hide show
  1. package/README.md +66 -295
  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 -133
  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 -168
  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 -134
  64. package/dist/dashboard/drilldown.js +0 -16
  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/spending-words.js +0 -32
  71. package/dist/dashboard/spending-words.js.map +0 -1
  72. package/dist/failure.js +0 -35
  73. package/dist/failure.js.map +0 -1
  74. package/dist/keep-running.js +0 -77
  75. package/dist/keep-running.js.map +0 -1
  76. package/dist/outside-failure.js +0 -31
  77. package/dist/outside-failure.js.map +0 -1
  78. package/dist/pick-wakes.js +0 -125
  79. package/dist/pick-wakes.js.map +0 -1
  80. package/dist/project.js +0 -1
  81. package/dist/project.js.map +0 -1
  82. package/dist/queue-counts.js +0 -51
  83. package/dist/queue-counts.js.map +0 -1
  84. package/dist/reasons.js +0 -33
  85. package/dist/reasons.js.map +0 -1
  86. package/dist/spending-limit.js +0 -88
  87. package/dist/spending-limit.js.map +0 -1
  88. package/dist/step-files.js +0 -200
  89. package/dist/step-files.js.map +0 -1
  90. package/dist/step-meter.js +0 -97
  91. package/dist/step-meter.js.map +0 -1
  92. package/dist/step-usage.js +0 -19
  93. package/dist/step-usage.js.map +0 -1
  94. package/dist/steps.js +0 -920
  95. package/dist/steps.js.map +0 -1
  96. package/dist/storage/budgets.js +0 -85
  97. package/dist/storage/budgets.js.map +0 -1
  98. package/dist/storage/engine-records.js +0 -75
  99. package/dist/storage/engine-records.js.map +0 -1
  100. package/dist/storage/engine-storage.js +0 -67
  101. package/dist/storage/engine-storage.js.map +0 -1
  102. package/dist/storage/input-records.js +0 -12
  103. package/dist/storage/input-records.js.map +0 -1
  104. package/dist/storage/move-store.js +0 -251
  105. package/dist/storage/move-store.js.map +0 -1
  106. package/dist/storage/sqlite-store.js +0 -723
  107. package/dist/storage/sqlite-store.js.map +0 -1
  108. package/dist/storage/step-records.js +0 -11
  109. package/dist/storage/step-records.js.map +0 -1
  110. package/dist/storage/storage-error.js +0 -19
  111. package/dist/storage/storage-error.js.map +0 -1
  112. package/dist/storage/task-store.js +0 -24
  113. package/dist/storage/task-store.js.map +0 -1
  114. package/dist/tasks.js +0 -475
  115. package/dist/tasks.js.map +0 -1
  116. package/dist/views/format.js +0 -37
  117. package/dist/views/format.js.map +0 -1
  118. package/dist/views/runs-now.js +0 -75
  119. package/dist/views/runs-now.js.map +0 -1
  120. package/dist/views/step-funnel.js +0 -98
  121. package/dist/views/step-funnel.js.map +0 -1
  122. package/dist/views/step-graph.js +0 -34
  123. package/dist/views/step-graph.js.map +0 -1
  124. package/dist/views/workflow-flows.js +0 -53
  125. package/dist/views/workflow-flows.js.map +0 -1
  126. package/dist/views/workflows-view.js +0 -230
  127. package/dist/views/workflows-view.js.map +0 -1
  128. package/src/budget-states.ts +0 -55
  129. package/src/cpu-limit/limiter.ts +0 -935
  130. package/src/cpu-limit/use.ts +0 -166
  131. package/src/dashboard/agent-usage-line.tsx +0 -28
  132. package/src/dashboard/agent-usage.ts +0 -48
  133. package/src/dashboard/dashboard.css +0 -134
  134. package/src/dashboard/drilldown.ts +0 -43
  135. package/src/dashboard/index.tsx +0 -4
  136. package/src/dashboard/machine-controls.tsx +0 -53
  137. package/src/dashboard/queue-bar.tsx +0 -43
  138. package/src/dashboard/queue-chart.tsx +0 -150
  139. package/src/dashboard/queue-lines.ts +0 -87
  140. package/src/dashboard/queue-table.ts +0 -37
  141. package/src/dashboard/spending-limit-control.tsx +0 -50
  142. package/src/dashboard/spending-words.ts +0 -50
  143. package/src/dashboard/step-graph.tsx +0 -106
  144. package/src/dashboard/workflow-dag.tsx +0 -204
  145. package/src/dashboard/workflow-drilldown.tsx +0 -89
  146. package/src/dashboard/workflows-dashboard.tsx +0 -414
  147. package/src/failure.ts +0 -36
  148. package/src/keep-running.ts +0 -83
  149. package/src/outside-failure.ts +0 -39
  150. package/src/pick-wakes.ts +0 -182
  151. package/src/project.ts +0 -115
  152. package/src/queue-counts.ts +0 -64
  153. package/src/reasons.ts +0 -30
  154. package/src/spending-limit.ts +0 -156
  155. package/src/step-files.ts +0 -208
  156. package/src/step-meter.ts +0 -120
  157. package/src/step-usage.ts +0 -23
  158. package/src/steps.ts +0 -1239
  159. package/src/storage/budgets.ts +0 -113
  160. package/src/storage/engine-records.ts +0 -102
  161. package/src/storage/engine-storage.ts +0 -82
  162. package/src/storage/input-records.ts +0 -43
  163. package/src/storage/move-store.ts +0 -265
  164. package/src/storage/sqlite-store.ts +0 -829
  165. package/src/storage/step-records.ts +0 -306
  166. package/src/storage/storage-error.ts +0 -35
  167. package/src/storage/task-store.ts +0 -235
  168. package/src/tasks.ts +0 -561
  169. package/src/views/format.ts +0 -40
  170. package/src/views/runs-now.ts +0 -120
  171. package/src/views/step-funnel.ts +0 -163
  172. package/src/views/step-graph.ts +0 -68
  173. package/src/views/workflow-flows.ts +0 -97
  174. package/src/views/workflows-view.ts +0 -443
@@ -1,113 +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 at an agent step
6
- * whose agents are all in use waits there for one (`steps.ts` `agentSlot`), its task kept and no CPU used.
7
- * 0 is the owner's decision and no fault: nothing gets past a first agent step, and a run with a task ends there,
8
- * its task marked as needing an agent (`steps.ts` `untilAgentSlot`).
9
- *
10
- * Alex, 2026-11-14: "there was supposed to be a number of runs concurrently allowed setting per workflow and also a number
11
- * of concurrent agents allowed per workflow setting". One number did both until 2026-11-12; until 2026-11-14 the default
12
- * 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;
13
- * `sqliteBudgets` reads the `workflow_budgets` table of the project's file, which the project writes through the
14
- * statements below.
15
- */
16
- import { Database } from 'bun:sqlite';
17
- import type { Effect } from 'effect';
18
- import fs from 'node:fs';
19
- import { storeCall, type StorageError } from './storage-error';
20
-
21
- export const WORKFLOW_BUDGETS_SQL = 'SELECT workflow, budget, runs, changed_at FROM workflow_budgets';
22
- export const WORKFLOW_BUDGET_SQL = 'SELECT budget, runs FROM workflow_budgets WHERE workflow = ?';
23
- /** Sets a workflow's agents' limit, keeping its run limit. */
24
- export const SET_WORKFLOW_BUDGET_SQL =
25
- 'INSERT INTO workflow_budgets(workflow, budget, changed_at) VALUES (?, ?, ?) ON CONFLICT(workflow) DO UPDATE SET budget = excluded.budget, changed_at = excluded.changed_at';
26
- /** Sets a workflow's run limit, none for the default, keeping its agents' limit. */
27
- export const SET_WORKFLOW_RUNS_SQL =
28
- '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';
29
-
30
- /**
31
- * THE ONE SPENDING LIMIT (`spending-limit.ts`): a table of one row beside `workflow_budgets`, since it is the account's and
32
- * no workflow's: `spending_limit(id INTEGER PRIMARY KEY CHECK (id = 1), week_percent INTEGER NOT NULL, changed_at REAL NOT
33
- * NULL)`. None stored is the default. As with `workflow_budgets`, the project makes the table and writes it through the
34
- * statement below.
35
- */
36
- export const SPENDING_LIMIT_SQL = 'SELECT week_percent, changed_at FROM spending_limit WHERE id = 1';
37
- /** Sets the spending limit: the percent of the week at which agents stop. */
38
- export const SET_SPENDING_LIMIT_SQL =
39
- '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';
40
-
41
- /** The spending limit as stored: the percent of the week at which agents stop, and when it was set, unix seconds. */
42
- export interface StoredSpendingLimit {
43
- readonly weekPercent: number;
44
- readonly changedAt: number;
45
- }
46
-
47
- export interface WorkflowBudgetRow {
48
- readonly workflow: string;
49
- /** The agents' limit. */
50
- readonly budget: number;
51
- /** The run limit; none for the default. */
52
- readonly runs: number | null;
53
- readonly changed_at: number;
54
- }
55
-
56
- /** A workflow's limits as stored: its agents', and its runs', none for the default. */
57
- export interface WorkflowLimits {
58
- readonly agents: number;
59
- readonly runs: number | null;
60
- }
61
-
62
- export interface LimitStore {
63
- /** A workflow's limits: 0 agents with none stored, and none where there is no store to read (a test). */
64
- readonly limitsOf: (workflow: string) => Effect.Effect<WorkflowLimits | null, StorageError>;
65
- /** Every stored workflow's limits, by name, in one read: one with none stored is absent. None where there is no store. */
66
- readonly storedLimits: () => Effect.Effect<ReadonlyMap<string, WorkflowLimits> | null, StorageError>;
67
- /** The spending limit as set; none where none was set or there is no store, which is the default. */
68
- readonly spendingLimit: () => Effect.Effect<StoredSpendingLimit | null, StorageError>;
69
- }
70
-
71
- /**
72
- * HOW MANY RUNS OF A WORKFLOW ARE KEPT GOING: its run limit, or with none stored its agents' limit. The run limit alone says
73
- * how many runs exist; the agents' limit alone says how many of them may be in an agent step (`steps.ts` `agentSlot`). Pure.
74
- */
75
- export const runLimit = (limits: WorkflowLimits): number => (limits.runs !== null ? limits.runs : limits.agents);
76
-
77
- export const sqliteBudgets = (options: { readonly file: () => string }): LimitStore => ({
78
- limitsOf: (workflow) => storeCall('limits: limitsOf', () => {
79
- const file = options.file();
80
- if (!fs.existsSync(file)) return null;
81
- const db = new Database(file, { readonly: true });
82
- try {
83
- if (db.query(`SELECT 1 FROM sqlite_master WHERE name = 'workflow_budgets'`).get() === null) return null;
84
- const row = db.query(WORKFLOW_BUDGET_SQL).get(workflow) as { budget: number; runs: number | null } | null;
85
- return row === null ? { agents: 0, runs: null } : { agents: row.budget, runs: row.runs };
86
- } finally {
87
- db.close();
88
- }
89
- }),
90
- storedLimits: () => storeCall('limits: storedLimits', () => {
91
- const file = options.file();
92
- if (!fs.existsSync(file)) return null;
93
- const db = new Database(file, { readonly: true });
94
- try {
95
- if (db.query(`SELECT 1 FROM sqlite_master WHERE name = 'workflow_budgets'`).get() === null) return null;
96
- return new Map((db.query(WORKFLOW_BUDGETS_SQL).all() as ReadonlyArray<WorkflowBudgetRow>).map((r) => [r.workflow, { agents: r.budget, runs: r.runs }]));
97
- } finally {
98
- db.close();
99
- }
100
- }),
101
- spendingLimit: () => storeCall('limits: spendingLimit', () => {
102
- const file = options.file();
103
- if (!fs.existsSync(file)) return null;
104
- const db = new Database(file, { readonly: true });
105
- try {
106
- if (db.query(`SELECT 1 FROM sqlite_master WHERE name = 'spending_limit'`).get() === null) return null;
107
- const row = db.query(SPENDING_LIMIT_SQL).get() as { week_percent: number; changed_at: number } | null;
108
- return row === null ? null : { weekPercent: row.week_percent, changedAt: row.changed_at };
109
- } finally {
110
- db.close();
111
- }
112
- }),
113
- });
@@ -1,102 +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. */
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
- /**
54
- * THE INDEXES THE ENGINE'S QUERIES NEED, which its file does not have. Every poll, mailbox read and run count scanned all
55
- * 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.
56
- */
57
- const ENGINE_INDEXES = [
58
- 'CREATE INDEX IF NOT EXISTS cluster_messages_undelivered ON cluster_messages (shard_id, entity_type, entity_id) WHERE processed = 0',
59
- 'CREATE INDEX IF NOT EXISTS cluster_messages_by_workflow ON cluster_messages (entity_type, tag, request_id)',
60
- // A reply marks its request processed by this column: up to 213 ms a reply, unindexed, on 2026-11-04.
61
- 'CREATE INDEX IF NOT EXISTS cluster_messages_by_request ON cluster_messages (request_id)',
62
- // The runs not finished, which every Pick, start and count reads. Without it each read walked all 82,738 run messages,
63
- // 250 ms, and a waiting Pick read it on every wake (2026-11-12).
64
- "CREATE INDEX IF NOT EXISTS cluster_messages_unfinished_runs ON cluster_messages (entity_type, request_id) WHERE tag = 'run' AND processed = 0",
65
- ];
66
-
67
- /** Makes them once the engine has made its tables; with them there, this writes nothing. */
68
- export const ensureEngineIndexes = (file: string): void => {
69
- if (!fs.existsSync(file)) return;
70
- const db = new Database(file);
71
- try {
72
- db.exec('PRAGMA busy_timeout = 1000');
73
- if (db.query(`SELECT 1 FROM sqlite_master WHERE name = 'cluster_messages'`).get() === null) return;
74
- for (const statement of ENGINE_INDEXES) db.exec(statement);
75
- } finally {
76
- db.close();
77
- }
78
- };
79
-
80
- /** The SQL condition for a run message with no reply: the partial index's terms, so the read uses it. */
81
- const UNFINISHED = `m.tag = 'run' AND m.processed = 0
82
- AND NOT EXISTS (SELECT 1 FROM cluster_replies p WHERE p.request_id = m.request_id)`;
83
-
84
- /** The engine's records in its SQLite file, at the file `file` names when each call is made. */
85
- export const sqliteEngineRecords = (options: { readonly file: () => string }): EngineRecords => ({
86
- unfinishedRuns: () => storeCall('engine records: unfinishedRuns', () =>
87
- readEngineFile(options.file(), (db) => db.query(
88
- `SELECT substr(m.entity_type, ${entityTypeOf('').length + 1}) AS workflow, m.entity_id AS run FROM cluster_messages m
89
- WHERE m.entity_type GLOB '${entityTypeOf('')}*' AND ${UNFINISHED}
90
- ORDER BY m.request_id`,
91
- ).all() as Array<UnfinishedRun>) ?? []),
92
- runsOldestFirst: (workflows) => storeCall('engine records: runsOldestFirst', () =>
93
- readEngineFile(options.file(), (db) => (db.query(
94
- `SELECT m.entity_id AS id FROM cluster_messages m
95
- WHERE m.entity_type IN (SELECT value FROM json_each(?)) AND ${UNFINISHED}
96
- ORDER BY m.request_id`,
97
- ).all(JSON.stringify(workflows.map(entityTypeOf))) as Array<{ id: string }>).map((r) => r.id)) ?? []),
98
- runningRuns: (workflow) => storeCall('engine records: runningRuns', () =>
99
- readEngineFile(options.file(), (db) => Number((db.query(
100
- `SELECT COUNT(*) AS n FROM cluster_messages m WHERE m.entity_type = ? AND ${UNFINISHED}`,
101
- ).get(entityTypeOf(workflow)) as { n: number }).n)) ?? 0),
102
- });
@@ -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
- };
@@ -1,265 +0,0 @@
1
- /**
2
- * THE STEP RECORDS AND TASKS MOVE INTO THE PROJECT'S ONE DATABASE, LIVE, from the file they had of their own. Alex,
3
- * 2026-11-14: "the workflow platform should only have 1 [database]"; the design is `STORAGE.md`.
4
- *
5
- * Every process opens the new file. The first open copies the old file's rows across, highest ids first, so the new
6
- * file's next id is above every old one from its first chunk on and a row written meanwhile never takes an old row's id;
7
- * each chunk is a transaction of its own, so no writer waits on the copy for long, and copying again changes nothing.
8
- * A process still on the old code (a runner draining for up to 600 s) keeps writing the old file: `catchUpMove` copies
9
- * what it wrote after, with new ids, and the rows it closed after the copy. Once the old file has been quiet for
10
- * `QUIET_BEFORE_RENAME_SECONDS`, it is caught up once more and renamed `.moved`, never deleted.
11
- */
12
- import { Database } from 'bun:sqlite';
13
- import fs from 'node:fs';
14
- import { applyStepRecordsSchema } from './sqlite-store';
15
-
16
- /** Rows copied per transaction: a chunk of step records is tens of milliseconds. */
17
- const CHUNK = 5_000;
18
-
19
- /** How long the old file must go unwritten before it is renamed: past any old runner's 600 s handover. */
20
- export const QUIET_BEFORE_RENAME_SECONDS = 20 * 60;
21
-
22
- const MOVES_SCHEMA = `
23
- CREATE TABLE IF NOT EXISTS store_moves (
24
- from_file TEXT PRIMARY KEY,
25
- copied_at REAL NOT NULL,
26
- step_runs_max INTEGER NOT NULL,
27
- step_items_max INTEGER NOT NULL,
28
- tasks_max INTEGER NOT NULL,
29
- notes_max INTEGER NOT NULL,
30
- renamed_at REAL
31
- );`;
32
-
33
- /** The tables moved, in the order a row's references are copied before it. */
34
- const MOVED: ReadonlyArray<{ readonly table: string; readonly key: string | null }> = [
35
- { table: 'step_runs', key: 'id' },
36
- { table: 'step_functions', key: 'id' },
37
- { table: 'tasks', key: 'id' },
38
- { table: 'task_notes', key: 'id' },
39
- { table: 'input_runs', key: null },
40
- { table: 'cleared_but_listed', key: null },
41
- { table: 'undeclared_writes', key: null },
42
- ];
43
-
44
- const columnsOf = (db: Database, table: string): ReadonlyArray<string> =>
45
- (db.query(`SELECT name FROM pragma_table_info(?, 'main')`).all(table) as Array<{ name: string }>).map((c) => c.name);
46
-
47
- const oldColumns = (db: Database, table: string): ReadonlyArray<string> =>
48
- (db.query(`PRAGMA old.table_info(${table})`).all() as Array<{ name: string }>).map((c) => c.name);
49
-
50
- /** The columns both files have, as `a, b, c`: the old file may predate a column. */
51
- const shared = (db: Database, table: string): string => {
52
- const old = new Set(oldColumns(db, table));
53
- return columnsOf(db, table).filter((c) => old.has(c)).map((c) => `"${c}"`).join(', ');
54
- };
55
-
56
- const maxOf = (db: Database, schema: 'main' | 'old', table: string): number =>
57
- (db.query(`SELECT COALESCE(MAX(id), 0) AS n FROM ${schema}.${table}`).get() as { n: number }).n;
58
-
59
- const withOld = <A>(db: Database, from: string, go: () => A): A => {
60
- db.exec(`ATTACH DATABASE '${from.replaceAll("'", "''")}' AS old`);
61
- try {
62
- return go();
63
- } finally {
64
- db.exec('DETACH DATABASE old');
65
- }
66
- };
67
-
68
- const recorded = (db: Database, from: string) =>
69
- db.query('SELECT copied_at, step_runs_max, step_items_max, tasks_max, notes_max, renamed_at FROM store_moves WHERE from_file = ?').get(from) as
70
- | { copied_at: number; step_runs_max: number; step_items_max: number; tasks_max: number; notes_max: number; renamed_at: number | null }
71
- | null;
72
-
73
- /**
74
- * The first copy, on a writer's first open of the new file: a no-op once recorded, or with no old file. `db` has the
75
- * platform's tables; the caller retries a lock it meets.
76
- */
77
- export const copyOldStore = (db: Database, from: string): void => {
78
- db.exec(MOVES_SCHEMA);
79
- if (!fs.existsSync(from) || recorded(db, from) !== null) return;
80
- withOld(db, from, () => {
81
- const max = { step_runs: maxOf(db, 'old', 'step_runs'), step_functions: maxOf(db, 'old', 'step_functions'), tasks: maxOf(db, 'old', 'tasks'), task_notes: maxOf(db, 'old', 'task_notes') };
82
- for (const { table, key } of MOVED) {
83
- const columns = shared(db, table);
84
- if (key === null) {
85
- db.transaction(() => db.exec(`INSERT OR IGNORE INTO main.${table} (${columns}) SELECT ${columns} FROM old.${table}`))();
86
- continue;
87
- }
88
- // Highest first, up to the highest when the copy began: the first chunk puts the new file's next id above every old
89
- // one, and a row the old code writes meanwhile is the catch-up's, with a new id.
90
- for (let below = max[table as keyof typeof max] + 1; ;) {
91
- const n = db.transaction(() => {
92
- const rows = db.query(`SELECT ${key} AS k FROM old.${table} WHERE ${key} < ? ORDER BY ${key} DESC LIMIT ${CHUNK}`).all(below) as Array<{ k: number }>;
93
- if (rows.length === 0) return { n: 0, low: below };
94
- const low = rows[rows.length - 1]!.k;
95
- db.query(`INSERT OR IGNORE INTO main.${table} (${columns}) SELECT ${columns} FROM old.${table} WHERE ${key} >= ? AND ${key} < ?`).run(low, below);
96
- return { n: rows.length, low };
97
- })();
98
- if (n.n === 0) break;
99
- below = n.low;
100
- }
101
- }
102
- db.query('INSERT OR IGNORE INTO store_moves (from_file, copied_at, step_runs_max, step_items_max, tasks_max, notes_max) VALUES (?, ?, ?, ?, ?, ?)')
103
- .run(from, Date.now() / 1000, max.step_runs, max.step_functions, max.tasks, max.task_notes);
104
- });
105
- };
106
-
107
- /** What a catch-up copied, and whether it renamed the old file. */
108
- export interface CatchUp {
109
- readonly stepRuns: number;
110
- readonly closed: number;
111
- readonly tasks: number;
112
- readonly notes: number;
113
- readonly renamed: boolean;
114
- }
115
-
116
- /**
117
- * WHAT THE OLD CODE WROTE AFTER THE COPY: its new rows, with new ids and their references mapped (a step record's items,
118
- * a note's task), and the records it closed. Run while the old file may still be written; once it has been quiet long
119
- * enough, the last catch-up renames it. A no-op before the first copy and after the rename.
120
- */
121
- export const catchUpMove = (db: Database, from: string, now: number): CatchUp | null => {
122
- db.exec(MOVES_SCHEMA);
123
- const was = recorded(db, from);
124
- if (was === null || was.renamed_at !== null || !fs.existsSync(from)) return null;
125
- // Quiet means no row came across for that long: the old file's times say nothing, since opening it to read changes them.
126
- const done = withOld(db, from, () => db.transaction(() => {
127
- const runColumns = shared(db, 'step_runs').split(', ').filter((c) => c !== '"id"').join(', ');
128
- // Records the old code opened after the copy: new ids, each old id's new one kept for its items.
129
- const late = db.query(`SELECT id FROM old.step_runs WHERE id > ? ORDER BY id`).all(was.step_runs_max) as Array<{ id: number }>;
130
- const newIds = new Map<number, number>();
131
- for (const r of late) {
132
- const inserted = db.query(`INSERT INTO main.step_runs (${runColumns}) SELECT ${runColumns} FROM old.step_runs WHERE id = ?`).run(r.id);
133
- newIds.set(r.id, Number(inserted.lastInsertRowid));
134
- }
135
- const itemColumns = shared(db, 'step_functions').split(', ').filter((c) => c !== '"id"' && c !== '"step_run"').join(', ');
136
- for (const [oldId, newId] of newIds) {
137
- db.query(`INSERT INTO main.step_functions (step_run, ${itemColumns}) SELECT ?, ${itemColumns} FROM old.step_functions WHERE step_run = ?`).run(newId, oldId);
138
- }
139
- // Records copied open that the old code closed after: their ends.
140
- const closedColumns = ['ended', 'outcome', 'error', 'reason', 'fresh', 'cache_write', 'cache_read', 'output', 'compiles', 'requests', 'model', 'subject', 'files', 'scope', 'cpu_seconds', 'child_cpu_seconds', 'own_cpu_seconds', 'peak_memory_mb', 'files_written', 'beat', 'waiting']
141
- .filter((c) => shared(db, 'step_runs').includes(`"${c}"`));
142
- const closed = db.query(
143
- `UPDATE main.step_runs SET (${closedColumns.join(', ')}) = (SELECT ${closedColumns.join(', ')} FROM old.step_runs o WHERE o.id = main.step_runs.id)
144
- WHERE ended IS NULL AND id <= ? AND id IN (SELECT id FROM old.step_runs WHERE ended IS NOT NULL AND id <= ?)`,
145
- ).run(was.step_runs_max, was.step_runs_max).changes;
146
- // Tasks by their workflow and item, and notes with their tasks mapped the same way; an outcome already moved is kept once.
147
- const tasks = db.query(
148
- `INSERT OR IGNORE INTO main.tasks (workflow, item, item_key, created_at, listed, listed_at)
149
- SELECT workflow, item, item_key, created_at, listed, listed_at FROM old.tasks WHERE id > ?`,
150
- ).run(was.tasks_max).changes;
151
- const noteColumns = shared(db, 'task_notes').split(', ').filter((c) => !['"id"', '"task"', '"about"'].includes(c));
152
- const notes = db.query(
153
- `INSERT OR IGNORE INTO main.task_notes (task, about, ${noteColumns.join(', ')})
154
- SELECT (SELECT m.id FROM main.tasks m WHERE m.workflow = t.workflow AND m.item_key = t.item_key),
155
- (SELECT m.id FROM main.tasks m JOIN old.tasks a ON a.workflow = m.workflow AND a.item_key = m.item_key WHERE a.id = n.about),
156
- ${noteColumns.map((c) => `n.${c}`).join(', ')}
157
- FROM old.task_notes n JOIN old.tasks t ON t.id = n.task WHERE n.id > ? ORDER BY n.id`,
158
- ).run(was.notes_max).changes;
159
- for (const table of ['input_runs', 'cleared_but_listed']) {
160
- const columns = shared(db, table);
161
- db.exec(`INSERT OR REPLACE INTO main.${table} (${columns}) SELECT ${columns} FROM old.${table}`);
162
- }
163
- const writes = shared(db, 'undeclared_writes');
164
- db.exec(`INSERT OR IGNORE INTO main.undeclared_writes (${writes}) SELECT ${writes} FROM old.undeclared_writes`);
165
- const changed = late.length + closed + tasks + notes > 0;
166
- const quiet = !changed && now - was.copied_at >= QUIET_BEFORE_RENAME_SECONDS;
167
- db.query('UPDATE store_moves SET step_runs_max = (SELECT COALESCE(MAX(id), 0) FROM old.step_runs), tasks_max = (SELECT COALESCE(MAX(id), 0) FROM old.tasks), notes_max = (SELECT COALESCE(MAX(id), 0) FROM old.task_notes), copied_at = ?, renamed_at = ? WHERE from_file = ?')
168
- .run(changed ? now : was.copied_at, quiet ? now : null, from);
169
- return { stepRuns: late.length, closed, tasks, notes, quiet };
170
- })());
171
- const quiet = done.quiet;
172
- if (quiet) for (const f of [from, `${from}-wal`, `${from}-shm`]) if (fs.existsSync(f)) fs.renameSync(f, `${f}.moved`);
173
- return { stepRuns: done.stepRuns, closed: done.closed, tasks: done.tasks, notes: done.notes, renamed: quiet };
174
- };
175
-
176
- /**
177
- * The move, as the project's job runner makes it once at its start, before any turn: the first copy, then a catch-up.
178
- * Every process reads and writes the old file until the copy is recorded in `file` (`sqliteStore` `movedFrom`). A
179
- * held lock throws, for the caller to retry; copying again changes nothing.
180
- */
181
- export const moveRecordsInto = (r: { readonly file: string; readonly from: string; readonly now: number }): CatchUp | null => {
182
- if (!fs.existsSync(r.from) || !fs.existsSync(r.file)) return null;
183
- const db = new Database(r.file);
184
- try {
185
- db.exec('PRAGMA busy_timeout = 0');
186
- applyStepRecordsSchema(db);
187
- copyOldStore(db, r.from);
188
- return catchUpMove(db, r.from, r.now);
189
- } finally {
190
- db.close();
191
- }
192
- };
193
-
194
- /**
195
- * WHETHER THE ENGINE'S OLD FILE IS FREE TO MOVE: no runner but `self` holds a shard lock there refreshed in the last
196
- * minute. A runner refreshes its locks every few seconds while its engine lives and releases them when it hands its work
197
- * over, so the old runner's engine has stopped writing once this is true.
198
- */
199
- export const engineFileFree = (r: { readonly from: string; readonly self: string }): boolean => {
200
- if (!fs.existsSync(r.from)) return true;
201
- const db = new Database(r.from, { readonly: true });
202
- try {
203
- if (db.query(`SELECT 1 FROM sqlite_master WHERE name = 'cluster_locks'`).get() === null) return true;
204
- const held = db.query(`SELECT COUNT(*) AS n FROM cluster_locks WHERE address <> ? AND acquired_at > datetime('now', '-60 seconds')`).get(r.self) as { n: number };
205
- return held.n === 0;
206
- } finally {
207
- db.close();
208
- }
209
- };
210
-
211
- /** The engine's tables, every row; its locks and runners are this moment's only, and start clean. */
212
- const ENGINE_RUNTIME_TABLES = new Set(['cluster_locks', 'cluster_runners']);
213
-
214
- /**
215
- * THE ENGINE'S RECORDS MOVE INTO THE PROJECT'S ONE DATABASE, once its old file is free (\`engineFileFree\`): its tables
216
- * made from the old file's own definitions, every row copied by rowid in chunks, so no writer waits on the copy for long,
217
- * its indexes, and the move recorded; then the old file is renamed \`.moved\`, never deleted. A held lock throws, for the
218
- * caller to retry; copying again changes nothing. What it copied.
219
- */
220
- export const moveEngineInto = (r: { readonly file: string; readonly from: string; readonly now: number }): { readonly tables: number; readonly rows: number } | null => {
221
- if (!fs.existsSync(r.from) || !fs.existsSync(r.file)) return null;
222
- const db = new Database(r.file);
223
- let rows = 0;
224
- let tables = 0;
225
- try {
226
- db.exec('PRAGMA busy_timeout = 0');
227
- db.exec(MOVES_SCHEMA);
228
- if (recorded(db, r.from) !== null) return null;
229
- withOld(db, r.from, () => {
230
- const objects = db.query(`SELECT type, name, sql FROM old.sqlite_master WHERE name LIKE 'cluster_%' AND sql IS NOT NULL ORDER BY type DESC`).all() as Array<{ type: string; name: string; sql: string }>;
231
- for (const o of objects.filter((x) => x.type === 'table')) {
232
- db.exec(o.sql.replace(/^CREATE TABLE\s+(?:IF NOT EXISTS\s+)?/i, 'CREATE TABLE IF NOT EXISTS '));
233
- tables += 1;
234
- if (ENGINE_RUNTIME_TABLES.has(o.name)) continue;
235
- // Each chunk the rows after the last rowid already copied, the ids never leaving SQLite: the engine's are snowflakes
236
- // (2.5e17 on 2026-11-17), sparse and past a JavaScript number's exact range. A try again after a held lock starts
237
- // where the last stopped.
238
- const copy = db.query(`INSERT OR IGNORE INTO main."${o.name}" SELECT * FROM old."${o.name}"
239
- WHERE (SELECT MAX(rowid) FROM main."${o.name}") IS NULL OR rowid > (SELECT MAX(rowid) FROM main."${o.name}") ORDER BY rowid LIMIT ${CHUNK}`);
240
- for (;;) {
241
- const copied = db.transaction(() => copy.run().changes)();
242
- if (copied === 0) break;
243
- rows += copied;
244
- }
245
- }
246
- for (const o of objects.filter((x) => x.type === 'index')) db.exec(o.sql.replace(/^CREATE (UNIQUE )?INDEX\s+(?:IF NOT EXISTS\s+)?/i, 'CREATE $1INDEX IF NOT EXISTS '));
247
- });
248
- db.query('INSERT OR IGNORE INTO store_moves (from_file, copied_at, step_runs_max, step_items_max, tasks_max, notes_max, renamed_at) VALUES (?, ?, 0, 0, 0, 0, ?)').run(r.from, r.now, r.now);
249
- } finally {
250
- db.close();
251
- }
252
- for (const f of [r.from, `${r.from}-wal`, `${r.from}-shm`]) if (fs.existsSync(f)) fs.renameSync(f, `${f}.moved`);
253
- return { tables, rows };
254
- };
255
-
256
- /** Whether a file's records moved into \`file\`: its move is recorded there. */
257
- export const movedInto = (r: { readonly file: string; readonly from: string }): boolean => {
258
- if (!fs.existsSync(r.file)) return false;
259
- const db = new Database(r.file, { readonly: true });
260
- try {
261
- return db.query(`SELECT 1 FROM sqlite_master WHERE name = 'store_moves'`).get() !== null && db.query('SELECT 1 FROM store_moves WHERE from_file = ?').get(r.from) !== null;
262
- } finally {
263
- db.close();
264
- }
265
- };