@jive-sh/workflow-platform 0.6.3 → 0.7.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 (89) hide show
  1. package/README.md +182 -42
  2. package/dist/budget-states.js +1 -1
  3. package/dist/budget-states.js.map +1 -1
  4. package/dist/dashboard/dashboard.css +42 -28
  5. package/dist/dashboard/drilldown.js +35 -4
  6. package/dist/dashboard/drilldown.js.map +1 -1
  7. package/dist/dashboard/run-doing-words.js +29 -0
  8. package/dist/dashboard/run-doing-words.js.map +1 -0
  9. package/dist/dashboard/setting-words.js +18 -0
  10. package/dist/dashboard/setting-words.js.map +1 -0
  11. package/dist/dashboard/spending-words.js +2 -10
  12. package/dist/dashboard/spending-words.js.map +1 -1
  13. package/dist/index.js +76 -13
  14. package/dist/index.js.map +1 -1
  15. package/dist/keep-running.js +4 -2
  16. package/dist/keep-running.js.map +1 -1
  17. package/dist/pick-wakes.js +2 -2
  18. package/dist/retention.js +59 -0
  19. package/dist/retention.js.map +1 -0
  20. package/dist/settings.js +88 -0
  21. package/dist/settings.js.map +1 -0
  22. package/dist/spending-limit.js +15 -21
  23. package/dist/spending-limit.js.map +1 -1
  24. package/dist/step-times.js +114 -0
  25. package/dist/step-times.js.map +1 -0
  26. package/dist/steps.js +399 -114
  27. package/dist/steps.js.map +1 -1
  28. package/dist/storage/agent-claims.js +3 -0
  29. package/dist/storage/agent-claims.js.map +1 -0
  30. package/dist/storage/budgets.js +40 -4
  31. package/dist/storage/budgets.js.map +1 -1
  32. package/dist/storage/engine-records.js +26 -10
  33. package/dist/storage/engine-records.js.map +1 -1
  34. package/dist/storage/sqlite-store.js +198 -20
  35. package/dist/storage/sqlite-store.js.map +1 -1
  36. package/dist/storage/task-store.js +11 -5
  37. package/dist/storage/task-store.js.map +1 -1
  38. package/dist/system-workflows.js +54 -0
  39. package/dist/system-workflows.js.map +1 -0
  40. package/dist/tasks.js +49 -24
  41. package/dist/tasks.js.map +1 -1
  42. package/dist/views/runs-now.js +80 -38
  43. package/dist/views/runs-now.js.map +1 -1
  44. package/dist/views/step-graph.js +6 -1
  45. package/dist/views/step-graph.js.map +1 -1
  46. package/dist/views/workflows-view.js +29 -23
  47. package/dist/views/workflows-view.js.map +1 -1
  48. package/package.json +1 -1
  49. package/src/budget-states.ts +2 -3
  50. package/src/dashboard/dashboard.css +42 -28
  51. package/src/dashboard/drilldown.ts +32 -5
  52. package/src/dashboard/index.tsx +1 -1
  53. package/src/dashboard/limits-and-runs.tsx +191 -0
  54. package/src/dashboard/queue-bar.tsx +30 -11
  55. package/src/dashboard/queue-chart.tsx +1 -2
  56. package/src/dashboard/run-doing-words.ts +41 -0
  57. package/src/dashboard/setting-words.ts +30 -0
  58. package/src/dashboard/spending-limit-control.tsx +5 -8
  59. package/src/dashboard/spending-words.ts +5 -23
  60. package/src/dashboard/time-distribution.tsx +61 -0
  61. package/src/dashboard/workflow-dag.tsx +247 -129
  62. package/src/dashboard/workflow-drilldown.tsx +13 -71
  63. package/src/dashboard/workflows-dashboard.tsx +345 -227
  64. package/src/index.ts +86 -16
  65. package/src/keep-running.ts +6 -4
  66. package/src/pick-wakes.ts +2 -2
  67. package/src/project.ts +12 -0
  68. package/src/retention.ts +90 -0
  69. package/src/settings.ts +171 -0
  70. package/src/spending-limit.ts +25 -42
  71. package/src/step-times.ts +151 -0
  72. package/src/steps.ts +512 -135
  73. package/src/storage/agent-claims.ts +63 -0
  74. package/src/storage/budgets.ts +43 -4
  75. package/src/storage/engine-records.ts +28 -11
  76. package/src/storage/sqlite-store.ts +225 -32
  77. package/src/storage/step-records.ts +59 -7
  78. package/src/storage/task-store.ts +29 -29
  79. package/src/system-workflows.ts +70 -0
  80. package/src/tasks.ts +49 -24
  81. package/src/views/runs-now.ts +119 -51
  82. package/src/views/step-graph.ts +11 -2
  83. package/src/views/workflows-view.ts +80 -39
  84. package/src/workflow-dag.test.tsx +89 -0
  85. package/src/workflow-page.test.tsx +170 -0
  86. package/dist/views/workflow-flows.js +0 -53
  87. package/dist/views/workflow-flows.js.map +0 -1
  88. package/src/dashboard/step-graph.tsx +0 -106
  89. package/src/views/workflow-flows.ts +0 -97
@@ -0,0 +1,63 @@
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));
@@ -2,10 +2,11 @@
2
2
  * EACH WORKFLOW'S TWO LIMITS, for a workflow with an agent step and a list of work (`steps.ts` `keptRunningByItsBudget`):
3
3
  *
4
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`).
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.
9
10
  *
10
11
  * Alex, 2026-11-14: "there was supposed to be a number of runs concurrently allowed setting per workflow and also a number
11
12
  * of concurrent agents allowed per workflow setting". One number did both until 2026-11-12; until 2026-11-14 the default
@@ -17,6 +18,7 @@ import { Database } from 'bun:sqlite';
17
18
  import type { Effect } from 'effect';
18
19
  import fs from 'node:fs';
19
20
  import { storeCall, type StorageError } from './storage-error';
21
+ import { RUNTIME_SETTINGS, type RuntimeSettingName, type SettingLevel, type StoredSetting } from '../settings';
20
22
 
21
23
  export const WORKFLOW_BUDGETS_SQL = 'SELECT workflow, budget, runs, changed_at FROM workflow_budgets';
22
24
  export const WORKFLOW_BUDGET_SQL = 'SELECT budget, runs FROM workflow_budgets WHERE workflow = ?';
@@ -38,6 +40,30 @@ export const SPENDING_LIMIT_SQL = 'SELECT week_percent, changed_at FROM spending
38
40
  export const SET_SPENDING_LIMIT_SQL =
39
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';
40
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
+
41
67
  /** The spending limit as stored: the percent of the week at which agents stop, and when it was set, unix seconds. */
42
68
  export interface StoredSpendingLimit {
43
69
  readonly weekPercent: number;
@@ -66,6 +92,8 @@ export interface LimitStore {
66
92
  readonly storedLimits: () => Effect.Effect<ReadonlyMap<string, WorkflowLimits> | null, StorageError>;
67
93
  /** The spending limit as set; none where none was set or there is no store, which is the default. */
68
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>;
69
97
  }
70
98
 
71
99
  /**
@@ -98,6 +126,17 @@ export const sqliteBudgets = (options: { readonly file: () => string }): LimitSt
98
126
  db.close();
99
127
  }
100
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
+ }),
101
140
  spendingLimit: () => storeCall('limits: spendingLimit', () => {
102
141
  const file = options.file();
103
142
  if (!fs.existsSync(file)) return null;
@@ -11,7 +11,7 @@ import type { Effect } from 'effect';
11
11
  import fs from 'node:fs';
12
12
  import { storeCall, type StorageError } from './storage-error';
13
13
 
14
- /** A run the engine has not finished: asked for, with no reply yet. */
14
+ /** A run the engine has not finished: asked for, with no reply yet, or suspended (its reply `Suspended`, until it resumes). */
15
15
  export interface UnfinishedRun {
16
16
  readonly workflow: string;
17
17
  readonly run: string;
@@ -50,6 +50,9 @@ export const readEngineFile = <A>(file: string, read: (db: Database) => A): A |
50
50
  }
51
51
  };
52
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
+
53
56
  /**
54
57
  * THE INDEXES THE ENGINE'S QUERIES NEED, which its file does not have. Every poll, mailbox read and run count scanned all
55
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.
@@ -62,6 +65,8 @@ const ENGINE_INDEXES = [
62
65
  // The runs not finished, which every Pick, start and count reads. Without it each read walked all 82,738 run messages,
63
66
  // 250 ms, and a waiting Pick read it on every wake (2026-11-12).
64
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')}`,
65
70
  ];
66
71
 
67
72
  /** Makes them once the engine has made its tables; with them there, this writes nothing. */
@@ -77,26 +82,38 @@ export const ensureEngineIndexes = (file: string): void => {
77
82
  }
78
83
  };
79
84
 
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)`;
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')`;
83
100
 
84
101
  /** The engine's records in its SQLite file, at the file `file` names when each call is made. */
85
102
  export const sqliteEngineRecords = (options: { readonly file: () => string }): EngineRecords => ({
86
103
  unfinishedRuns: () => storeCall('engine records: unfinishedRuns', () =>
87
104
  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`,
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`,
91
108
  ).all() as Array<UnfinishedRun>) ?? []),
92
109
  runsOldestFirst: (workflows) => storeCall('engine records: runsOldestFirst', () =>
93
110
  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`,
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`,
97
114
  ).all(JSON.stringify(workflows.map(entityTypeOf))) as Array<{ id: string }>).map((r) => r.id)) ?? []),
98
115
  runningRuns: (workflow) => storeCall('engine records: runningRuns', () =>
99
116
  readEngineFile(options.file(), (db) => Number((db.query(
100
- `SELECT COUNT(*) AS n FROM cluster_messages m WHERE m.entity_type = ? AND ${UNFINISHED}`,
117
+ `SELECT COUNT(*) AS n FROM ${UNFINISHED_RUNS} u WHERE u.entity_type = ?`,
101
118
  ).get(entityTypeOf(workflow)) as { n: number }).n)) ?? 0),
102
119
  });
@@ -9,11 +9,12 @@ import fs from 'node:fs';
9
9
  import type { ProcessIdentity } from '../project';
10
10
  import {
11
11
  stepErrorKept, type FunnelStepRecord, type ItemCost, type ItemHistoryRow, type LastStepNow, type NewestStepRecord, type RunCost, type RunOutcomeRow, type StepEdgeTaken,
12
- type StepFileCount, type StepRecords, type StepRunRow, type UndeclaredWrites, type WorkStep, AGENT_LIVE_SECONDS,
12
+ type StepFileCount, type RecordsSelection, type StepRecords, type StepRunRow, type TimedPart, type TimedRecord, type UndeclaredWrites, type WorkStep, AGENT_LIVE_SECONDS,
13
13
  } from './step-records';
14
14
  import { OUTSIDE_FAILURE_PATTERNS } from '../outside-failure';
15
- import { AGENT_STEP_RAN, LISTED_AGAIN, MOVED_TO_FRONT, NEEDS_AN_AGENT, STATUS_KINDS, STOOD_DOWN_OUTCOME, TRIES_START_AGAIN_KINDS, type Listed, type ListedWait, type NewNote, type QueueCount, type ReturnedBetween, type TaskNote, type TaskRef, type TaskState, type TaskStore } from './task-store';
15
+ import { AGENT_STEP_RAN, AGENT_TAKEN, LISTED_AGAIN, MOVED_TO_FRONT, NEEDS_AN_AGENT, STATUS_KINDS, STOOD_DOWN_OUTCOME, TRIES_START_AGAIN_KINDS, UNBLOCKED_INPUTS_CHANGED, type Listed, type NewNote, type QueueCount, type TaskNote, type TaskRef, type TaskState, type TaskStore } from './task-store';
16
16
  import type { InputRecords, InputRun } from './input-records';
17
+ import type { AgentClaim, AgentClaims } from './agent-claims';
17
18
  import { storeCall, storeCalls } from './storage-error';
18
19
 
19
20
  const STEP_RUNS_SCHEMA = `
@@ -89,7 +90,52 @@ CREATE INDEX IF NOT EXISTS task_notes_by_kind ON task_notes (kind, at);
89
90
  CREATE INDEX IF NOT EXISTS task_notes_by_about ON task_notes (about) WHERE about IS NOT NULL;
90
91
  CREATE UNIQUE INDEX IF NOT EXISTS task_notes_one_outcome_per_run ON task_notes (task, by_run) WHERE kind = 'outcome';
91
92
  CREATE TRIGGER IF NOT EXISTS task_notes_append_only_update BEFORE UPDATE ON task_notes BEGIN SELECT RAISE(ABORT, 'task notes are append-only'); END;
92
- CREATE TRIGGER IF NOT EXISTS task_notes_append_only_delete BEFORE DELETE ON task_notes BEGIN SELECT RAISE(ABORT, 'task notes are append-only'); END;`;
93
+ CREATE TRIGGER IF NOT EXISTS task_notes_go_only_with_their_task BEFORE DELETE ON task_notes
94
+ WHEN EXISTS (SELECT 1 FROM tasks t WHERE t.id = OLD.task) BEGIN SELECT RAISE(ABORT, 'task notes are append-only'); END;
95
+ CREATE TRIGGER IF NOT EXISTS tasks_take_their_notes AFTER DELETE ON tasks BEGIN DELETE FROM task_notes WHERE task = OLD.id; END;`;
96
+
97
+ /**
98
+ * A NOTE IS DELETED ONLY WITH ITS TASK, which only retention deletes (`TaskStore.deleteRunTasksEndedBefore`): the notes
99
+ * stay append-only while their task is there. The guard this replaces refused every delete.
100
+ */
101
+ const NOTES_GUARD_REPLACED = 'task_notes_append_only_delete';
102
+
103
+ /**
104
+ * WHICH VERSION A RECORD FROM BEFORE VERSIONS WERE KEPT COUNTS AS (Alex, 2026-11-21: "just treat them all as the initial
105
+ * version"): its workflow's first recorded version, the version of its earliest record that has one. Each fill is
106
+ * recorded here: the workflow, the version given, how many records took it, and when. A workflow with no versioned record
107
+ * yet keeps its records unversioned until its first is written, and they take that one (`openStepRun`).
108
+ */
109
+ const VERSION_BACKFILLS_SCHEMA = `
110
+ CREATE TABLE IF NOT EXISTS version_backfills (
111
+ workflow TEXT NOT NULL,
112
+ version TEXT NOT NULL,
113
+ records INTEGER NOT NULL,
114
+ at REAL NOT NULL,
115
+ PRIMARY KEY (workflow, at)
116
+ );`;
117
+
118
+ /**
119
+ * GIVES EVERY UNVERSIONED RECORD ITS WORKFLOW'S FIRST RECORDED VERSION, `workflow`'s alone where it is named, and records
120
+ * each fill (`version_backfills`). Repeatable: a record that has a version is never changed. Returns the records filled.
121
+ */
122
+ export const fillUnversionedRecords = (db: Database, workflow?: string): number => {
123
+ const unversioned = (workflow === undefined
124
+ ? db.query('SELECT DISTINCT workflow FROM step_runs WHERE version IS NULL').all()
125
+ : db.query('SELECT workflow FROM step_runs WHERE workflow = ? AND version IS NULL LIMIT 1').all(workflow)) as ReadonlyArray<{ workflow: string }>;
126
+ const firstVersion = db.query('SELECT version FROM step_runs WHERE workflow = ? AND version IS NOT NULL ORDER BY id LIMIT 1');
127
+ const fill = db.query('UPDATE step_runs SET version = ? WHERE workflow = ? AND version IS NULL');
128
+ const record = db.query('INSERT OR REPLACE INTO version_backfills (workflow, version, records, at) VALUES (?, ?, ?, ?)');
129
+ return unversioned.reduce((filled, { workflow: w }) => {
130
+ const first = firstVersion.get(w) as { version: string } | null;
131
+ if (first === null) return filled;
132
+ return filled + db.transaction(() => {
133
+ const n = fill.run(first.version, w).changes;
134
+ if (n > 0) record.run(w, first.version, n, Date.now() / 1000);
135
+ return n;
136
+ })();
137
+ }, 0);
138
+ };
93
139
 
94
140
  /** Every run's outcome on its item, as the step records and the page read it: the outcome notes of every task. */
95
141
  const RUN_OUTCOMES_VIEW = `
@@ -161,12 +207,40 @@ CREATE TABLE IF NOT EXISTS queue_counts (
161
207
  );
162
208
  CREATE INDEX IF NOT EXISTS queue_counts_by_at ON queue_counts (at);`;
163
209
 
210
+ /**
211
+ * EACH RUN'S CLAIM ON ITS TOP WORKFLOW'S AGENTS (`agent-claims.ts`): taken as the run starts, ended as it ends. `top_run`
212
+ * and `top_workflow` are the run at the top of its run, whose agents' limit it counts against.
213
+ */
214
+ const AGENT_CLAIMS_SCHEMA = `
215
+ CREATE TABLE IF NOT EXISTS agent_claims (
216
+ id INTEGER PRIMARY KEY,
217
+ run TEXT NOT NULL,
218
+ workflow TEXT NOT NULL,
219
+ top_run TEXT NOT NULL,
220
+ top_workflow TEXT NOT NULL,
221
+ agents INTEGER NOT NULL,
222
+ started REAL NOT NULL,
223
+ ended REAL,
224
+ outcome TEXT
225
+ );
226
+ CREATE INDEX IF NOT EXISTS agent_claims_open ON agent_claims (top_workflow) WHERE ended IS NULL;
227
+ CREATE INDEX IF NOT EXISTS agent_claims_by_run ON agent_claims (run);
228
+ CREATE INDEX IF NOT EXISTS agent_claims_by_start ON agent_claims (started);`;
229
+
230
+ /** A claim's row as `agent_claims` holds it. */
231
+ interface ClaimRow {
232
+ readonly run: string; readonly workflow: string; readonly top_run: string; readonly top_workflow: string;
233
+ readonly agents: number; readonly started: number; readonly ended: number | null; readonly outcome: string | null;
234
+ }
235
+ const CLAIM_COLUMNS = 'run, workflow, top_run, top_workflow, agents, started, ended, outcome';
236
+ const claimOf = (r: ClaimRow): AgentClaim => ({ run: r.run, workflow: r.workflow, top: { run: r.top_run, workflow: r.top_workflow }, agents: r.agents, started: r.started, ended: r.ended, outcome: r.outcome });
237
+
164
238
  /**
165
239
  * Whether a records file has the schema this code reads: every table and index the newest change to it added. A project
166
240
  * that applies the schema only when it must (a write takes the lock) asks this first.
167
241
  */
168
242
  export const stepRecordsSchemaApplied = (db: Database): boolean => {
169
- const newest = ['step_runs', 'queue_counts', 'step_runs_by_workflow', 'step_runs_by_child'];
243
+ const newest = ['step_runs', 'queue_counts', 'agent_claims_by_start', 'step_runs_by_workflow', 'step_runs_by_child', 'step_runs_by_version', 'version_backfills', 'task_notes_go_only_with_their_task', 'tasks_take_their_notes'];
170
244
  const present = new Set((db.query('SELECT name FROM sqlite_master').all() as Array<{ name: string }>).map((r) => r.name));
171
245
  return newest.every((name) => present.has(name));
172
246
  };
@@ -196,10 +270,14 @@ export const applyStepRecordsSchema = (db: Database): void => {
196
270
  if (!columns.includes('reason')) db.exec('ALTER TABLE step_runs ADD COLUMN reason TEXT');
197
271
  // The run a sub-workflow step started (`steps.ts` `defineSubWorkflow`): what ties that run to the run above it.
198
272
  if (!columns.includes('child_run')) db.exec('ALTER TABLE step_runs ADD COLUMN child_run TEXT');
273
+ // The version of its workflow its run started on (`steps.ts` `versionOf`): what each step's time distribution is read by.
274
+ if (!columns.includes('version')) db.exec('ALTER TABLE step_runs ADD COLUMN version TEXT');
275
+ db.exec('CREATE INDEX IF NOT EXISTS step_runs_by_version ON step_runs (workflow, version, step)');
199
276
  db.exec('CREATE INDEX IF NOT EXISTS step_runs_by_child ON step_runs (child_run) WHERE child_run IS NOT NULL');
200
277
  db.exec(STEP_ITEMS_SCHEMA);
201
278
  db.exec(UNDECLARED_WRITES_SCHEMA);
202
279
  db.exec(INPUT_RUNS_SCHEMA);
280
+ if (db.query(`SELECT 1 FROM sqlite_master WHERE type = 'trigger' AND name = ?`).get(NOTES_GUARD_REPLACED) !== null) db.exec(`DROP TRIGGER ${NOTES_GUARD_REPLACED}`);
203
281
  db.exec(TASKS_SCHEMA);
204
282
  // New input another workflow or step gave a task, stored by hash (`tasks.ts` `giveNewInput`).
205
283
  const noteColumns = (db.query('PRAGMA table_info(task_notes)').all() as Array<{ name: string }>).map((c) => c.name);
@@ -207,10 +285,13 @@ export const applyStepRecordsSchema = (db: Database): void => {
207
285
  // On an outcome, the fingerprint of the task's inputs as its run left them (`tasks.ts` `TaskInputs`).
208
286
  if (!noteColumns.includes('inputs')) db.exec('ALTER TABLE task_notes ADD COLUMN inputs TEXT');
209
287
  db.exec(QUEUE_COUNTS_SCHEMA);
288
+ db.exec(AGENT_CLAIMS_SCHEMA);
210
289
  db.exec(RUN_OUTCOMES_VIEW);
211
290
  // After the columns it reads.
212
291
  db.exec(FUNCTION_COSTS_VIEW);
213
292
  db.exec('CREATE INDEX IF NOT EXISTS step_runs_by_subject ON step_runs (subject)');
293
+ db.exec(VERSION_BACKFILLS_SCHEMA);
294
+ fillUnversionedRecords(db);
214
295
  };
215
296
 
216
297
  const isoTime = (seconds: number): string => new Date(seconds * 1000).toISOString();
@@ -267,6 +348,27 @@ export const closeStepRunsOfEndedProcesses = (
267
348
 
268
349
  const keyOf = (item: string) => item.toLowerCase();
269
350
 
351
+ /** Rows retention deletes a transaction, so no writer waits on it for long. */
352
+ const RETENTION_CHUNK = 5_000;
353
+
354
+ /** A records selection (`RecordsSelection`) as SQL over `step_runs` aliased `s`, its parameters numbered from `first` on. Pure. */
355
+ const selectionSql = (select: RecordsSelection, first: number): { readonly where: string; readonly params: ReadonlyArray<string> } =>
356
+ 'step' in select ? { where: `s.workflow = ?${first} AND s.step = ?${first + 1}`, params: [select.workflow, select.step] }
357
+ : 'stepsOtherThan' in select ? { where: `s.workflow = ?${first} AND s.step NOT IN (SELECT value FROM json_each(?${first + 1}))`, params: [select.workflow, JSON.stringify(select.stepsOtherThan)] }
358
+ : { where: `s.workflow NOT IN (SELECT value FROM json_each(?${first}))`, params: [JSON.stringify(select.workflowsOtherThan)] };
359
+
360
+ /** Deletes, a chunk a transaction, the rows whose ids `next` gives until it gives fewer than a chunk; `remove` deletes one chunk's and counts it. */
361
+ const inChunks = <C extends Record<string, number>>(db: Database, r: { readonly next: () => ReadonlyArray<number>; readonly remove: (ids: string) => C; readonly none: C }): C => {
362
+ let total = r.none;
363
+ for (;;) {
364
+ const ids = r.next();
365
+ if (ids.length === 0) return total;
366
+ const gone = db.transaction(() => r.remove(JSON.stringify(ids)))();
367
+ total = Object.fromEntries(Object.entries(total).map(([k, v]) => [k, v + (gone[k] ?? 0)])) as C;
368
+ if (ids.length < RETENTION_CHUNK) return total;
369
+ }
370
+ };
371
+
270
372
  interface NoteRow {
271
373
  readonly id: number; readonly task_id: number; readonly at: number; readonly kind: string; readonly why: string;
272
374
  readonly workflow: string; readonly item: string;
@@ -287,6 +389,16 @@ const noteOf = (r: NoteRow): TaskNote => ({
287
389
  change: r.before_sha === null || r.after_sha === null ? null : { beforeSha: r.before_sha, afterSha: r.after_sha, flags: r.flags ?? '', diff: r.diff ?? '' },
288
390
  });
289
391
 
392
+ /** What a step's time distribution reads of a record (`TimedRecord`). */
393
+ const TIMED_COLUMNS = 'id, workflow, version, run, step, subject, started, ended, scope';
394
+ /** Ids in lists short enough for one statement's parameters. */
395
+ const chunked = (ids: ReadonlyArray<number>): ReadonlyArray<ReadonlyArray<number>> =>
396
+ Array.from({ length: Math.ceil(ids.length / 500) }, (_, i) => ids.slice(i * 500, i * 500 + 500));
397
+ /** The parts of each batch record among `records` (`step_functions`), through their index by record. */
398
+ const partsOf = (db: Database, records: ReadonlyArray<TimedRecord>): ReadonlyArray<TimedPart> =>
399
+ chunked(records.filter((r) => r.scope === 'functions').map((r) => r.id)).flatMap((ids) =>
400
+ db.query(`SELECT step_run AS stepRun, subject, started, ended FROM step_functions WHERE step_run IN (${ids.map(() => '?').join(', ')})`).all(...ids) as ReadonlyArray<TimedPart>);
401
+
290
402
  const quoted = (kinds: ReadonlyArray<string>): string => kinds.map((k) => `'${k.replace(/'/g, "''")}'`).join(', ');
291
403
  /** A note a task's status is read from (`task-store.ts` `STATUS_KINDS`): an outcome of a run that did not stand down, or one of the kinds. */
292
404
  const IS_STATUS_NOTE = `((n.kind = 'outcome' AND n.why <> '${STOOD_DOWN_OUTCOME}') OR n.kind IN (${quoted(Object.keys(STATUS_KINDS))}))`;
@@ -296,16 +408,24 @@ const IS_OUTSIDE_FAILURE = `(${OUTSIDE_FAILURE_PATTERNS.map((p) => `o.why LIKE '
296
408
  const STARTS_TRIES_AGAIN = `((n.kind = 'outcome' AND n.finished = 1) OR n.kind IN (${quoted(TRIES_START_AGAIN_KINDS)}))`;
297
409
  /**
298
410
  * A note `c` that clears task `t`'s `needs an agent` mark (`task-store.ts` `TaskState.needsAgent`): something new from outside
299
- * its workflow (a return to its queue, a move to the front, any note by a person or by another workflow), an agent step that
300
- * ran on it, or its final check passing.
411
+ * its workflow (a return to its queue, a move to the front, any note by a person or by another workflow), a run on it
412
+ * that took an agent (an agent step that ran on it, on notes written before 2026-11-22), or its final check passing.
301
413
  */
302
- const CLEARS_NEEDS_AN_AGENT = `(c.kind IN (${quoted([...TRIES_START_AGAIN_KINDS, MOVED_TO_FRONT, AGENT_STEP_RAN])}) OR (c.kind = 'outcome' AND c.finished = 1)
414
+ const CLEARS_NEEDS_AN_AGENT = `(c.kind IN (${quoted([...TRIES_START_AGAIN_KINDS, MOVED_TO_FRONT, AGENT_TAKEN, AGENT_STEP_RAN])}) OR (c.kind = 'outcome' AND c.finished = 1)
303
415
  OR c.by_workflow IS NULL OR c.by_workflow <> t.workflow)`;
304
416
 
417
+ /**
418
+ * A status note `n` that put its task in its queue (`TaskState.entered`): any but a block and a lapsed block's return, so
419
+ * a task whose block for nothing new lapsed keeps the place it held before it.
420
+ */
421
+ const ENTERS_THE_QUEUE = `(${IS_STATUS_NOTE} AND n.kind NOT IN (${quoted(Object.keys(STATUS_KINDS).filter((k) => STATUS_KINDS[k] === 'blocked'))})
422
+ AND NOT (n.kind = 'unblocked' AND n.why = '${UNBLOCKED_INPUTS_CHANGED}'))`;
423
+
305
424
  interface StateRow {
306
425
  readonly id: number; readonly workflow: string; readonly item: string; readonly listed: string | null; readonly created_at: number;
307
426
  readonly note: number | null; readonly front: number | null; readonly kind: string | null; readonly why: string | null; readonly at: number | null;
308
427
  readonly finished: number | null; readonly inputs: string | null; readonly about_workflow: string | null; readonly about_item: string | null;
428
+ readonly entered: number | null; readonly entered_at: number | null;
309
429
  readonly tries: number; readonly changes: number; readonly start_kind: string | null; readonly needs_agent: string | null; readonly last_run_inputs: string | null;
310
430
  }
311
431
 
@@ -320,11 +440,12 @@ const statesWhere = (db: Database, where: string, params: ReadonlyArray<string |
320
440
  SELECT t.id AS id,
321
441
  (SELECT MAX(n.id) FROM task_notes n WHERE n.task = t.id AND ${IS_STATUS_NOTE}) AS note,
322
442
  (SELECT MAX(n.id) FROM task_notes n WHERE n.task = t.id AND ${STARTS_TRIES_AGAIN}) AS start,
443
+ (SELECT MAX(n.id) FROM task_notes n WHERE n.task = t.id AND ${ENTERS_THE_QUEUE}) AS entered,
323
444
  (SELECT MAX(n.id) FROM task_notes n WHERE n.task = t.id AND n.kind = '${MOVED_TO_FRONT}') AS front,
324
445
  (SELECT MAX(n.id) FROM task_notes n WHERE n.task = t.id AND n.kind = '${NEEDS_AN_AGENT}') AS mark,
325
446
  (SELECT MAX(n.id) FROM task_notes n WHERE n.task = t.id AND n.kind = 'outcome') AS last_run
326
447
  FROM tasks t WHERE ${where})
327
- SELECT t.id, t.workflow, t.item, t.listed, t.created_at, s.note, s.front, n.kind, n.why, n.at, n.finished, n.inputs,
448
+ SELECT t.id, t.workflow, t.item, t.listed, t.created_at, s.note, s.front, s.entered, (SELECT e.at FROM task_notes e WHERE e.id = s.entered) AS entered_at, n.kind, n.why, n.at, n.finished, n.inputs,
328
449
  a.workflow AS about_workflow, a.item AS about_item,
329
450
  CASE WHEN s.mark IS NULL OR EXISTS (SELECT 1 FROM task_notes c WHERE c.task = t.id AND c.id > s.mark AND ${CLEARS_NEEDS_AN_AGENT}) THEN NULL
330
451
  ELSE (SELECT m.why FROM task_notes m WHERE m.id = s.mark) END AS needs_agent,
@@ -338,6 +459,7 @@ const statesWhere = (db: Database, where: string, params: ReadonlyArray<string |
338
459
  id: r.id, ref: { workflow: r.workflow, item: r.item }, listed: r.listed === null ? null : (JSON.parse(r.listed) as Listed),
339
460
  status: r.kind === null ? 'queued' : r.kind === 'outcome' ? (r.finished === 1 ? 'done' : 'queued') : STATUS_KINDS[r.kind]!,
340
461
  why: r.why, kind: r.kind, since: r.at ?? r.created_at, note: r.note ?? 0,
462
+ entered: { at: r.entered_at ?? r.created_at, note: r.entered ?? 0 },
341
463
  front: r.front !== null && r.front > (r.note ?? 0) ? r.front : null,
342
464
  tries: r.tries, inputs: r.inputs,
343
465
  about: r.about_workflow === null || r.about_item === null ? null : { workflow: r.about_workflow, item: r.about_item },
@@ -389,9 +511,11 @@ export const sqliteStore = (options: {
389
511
  * its exported records when it is missing, and would see a file this made as present.
390
512
  */
391
513
  readonly creates?: (file: string) => boolean;
392
- }): { readonly stepRecords: StepRecords; readonly tasks: TaskStore; readonly inputs: InputRecords } => {
514
+ }): { readonly stepRecords: StepRecords; readonly tasks: TaskStore; readonly inputs: InputRecords; readonly claims: AgentClaims } => {
393
515
  const writers = new Map<string, Database>();
394
516
  const migrated = new Set<string>();
517
+ /** The workflows whose unversioned records this process has filled (`fillUnversionedRecords`). */
518
+ const filledFor = new Set<string>();
395
519
  const movedInto = new Set<string>();
396
520
  /** When each file was last found not yet moved into: read again only after `NOT_MOVED_READ_AGAIN_MS`. */
397
521
  const notMovedAt = new Map<string, number>();
@@ -498,9 +622,22 @@ export const sqliteStore = (options: {
498
622
  ?? (db.query('SELECT subject FROM step_runs WHERE child_run = ? AND subject IS NOT NULL ORDER BY id DESC LIMIT 1').get(r.run) as { subject: string } | null)?.subject
499
623
  ?? null;
500
624
  const owner = ownerOfNewRecords();
501
- return Number(db.query(
502
- 'INSERT INTO step_runs (workflow, run, step, call, agent, started, beat, subject, owner_pid, owner_started_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
503
- ).run(r.workflow, r.run, r.step, r.call, r.agent ? 1 : 0, now, now, inherited, owner === null ? null : owner.pid, owner === null ? null : owner.startedAt).lastInsertRowid);
625
+ const id = Number(db.query(
626
+ // Its run's version, from the run's first record: a run resumed under newer code keeps the version it started on.
627
+ 'INSERT INTO step_runs (workflow, run, step, call, agent, started, beat, subject, owner_pid, owner_started_at, version) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, COALESCE((SELECT v.version FROM step_runs v WHERE v.run = ? AND v.version IS NOT NULL ORDER BY v.id LIMIT 1), ?))',
628
+ ).run(r.workflow, r.run, r.step, r.call, r.agent ? 1 : 0, now, now, inherited, owner === null ? null : owner.pid, owner === null ? null : owner.startedAt, r.run, r.version).lastInsertRowid);
629
+ // Its workflow's records from before versions were kept take its first recorded version, which it may have just
630
+ // written: once a process, after its first record of the workflow (`fillUnversionedRecords`). A fill that meets a held
631
+ // lock is tried again at the workflow's next record, never by failing this one: retried, the record would be written twice.
632
+ if (!filledFor.has(r.workflow)) {
633
+ try {
634
+ fillUnversionedRecords(db, r.workflow);
635
+ filledFor.add(r.workflow);
636
+ } catch {
637
+ // Tried again at the next record.
638
+ }
639
+ }
640
+ return id;
504
641
  }),
505
642
  beatStepRun: (id) => {
506
643
  tryWrite((db) => db.query('UPDATE step_runs SET beat = ? WHERE id = ?').run(Date.now() / 1000, id));
@@ -553,6 +690,26 @@ export const sqliteStore = (options: {
553
690
  }
554
691
  })());
555
692
  },
693
+ deleteRecordsOfRunsEndedBefore: ({ select, before, keepRuns, keepNewest }) => tryWrite((db) => {
694
+ const { where, params } = selectionSql(select, 4);
695
+ // Each step's newest runs, by when each started there, read once before any delete: each record of them stays. A run
696
+ // is one text of its workflow, step and run, a unit separator between, which no name holds.
697
+ const mine = selectionSql(select, 1);
698
+ const newest = (db.query(`SELECT k FROM (SELECT s.workflow || char(31) || s.step || char(31) || s.run AS k, ROW_NUMBER() OVER (PARTITION BY s.workflow, s.step ORDER BY MAX(s.started) DESC) AS n
699
+ FROM step_runs s WHERE ${mine.where} GROUP BY s.workflow, s.step, s.run) WHERE n <= ${Math.max(0, Math.floor(keepNewest))}`).all(...mine.params) as ReadonlyArray<{ k: string }>).map((x) => x.k);
700
+ // A record of a run any record of which is open, or ended since `before`, stays: retention takes whole ended runs.
701
+ const candidates = db.query(`SELECT s.id FROM step_runs s WHERE s.started < ?1 AND s.ended IS NOT NULL AND ${where}
702
+ AND s.run NOT IN (SELECT value FROM json_each(?2))
703
+ AND s.workflow || char(31) || s.step || char(31) || s.run NOT IN (SELECT value FROM json_each(?3))
704
+ AND NOT EXISTS (SELECT 1 FROM step_runs o WHERE o.run = s.run AND (o.ended IS NULL OR o.ended >= ?1)) LIMIT ${RETENTION_CHUNK}`);
705
+ const parts = db.query('DELETE FROM step_functions WHERE step_run IN (SELECT value FROM json_each(?))');
706
+ const records = db.query('DELETE FROM step_runs WHERE id IN (SELECT value FROM json_each(?))');
707
+ return inChunks(db, {
708
+ next: () => (candidates.all(before, JSON.stringify(keepRuns), JSON.stringify(newest), ...params) as ReadonlyArray<{ id: number }>).map((x) => x.id),
709
+ remove: (ids) => ({ parts: parts.run(ids).changes, records: records.run(ids).changes }),
710
+ none: { records: 0, parts: 0 },
711
+ });
712
+ }) ?? { records: 0, parts: 0 },
556
713
  closeStepRunsLeftOpen: (serviceStartedAt) =>
557
714
  tryWrite((db) => closeStepRunsOfEndedProcesses(db, { self: options.processes.thisProcess(), serviceStartedAt, isAlive: options.processes.isAlive })) ?? 0,
558
715
 
@@ -574,15 +731,9 @@ export const sqliteStore = (options: {
574
731
  UNION SELECT p.run, p.workflow, u.depth + 1 FROM up u JOIN step_runs p ON p.child_run = u.run WHERE u.depth < 32)
575
732
  SELECT run, workflow FROM up ORDER BY depth DESC LIMIT 1`,
576
733
  ).get(run) as { run: string; workflow: string } | null, null),
577
- runsInAgentStep: (workflow) =>
578
- // Each open agent step, then the run that started its run as a sub-workflow, and so on up: every one of them that is a
579
- // run of this workflow has an agent working for it.
580
- read((db) => (db.query(
581
- `WITH RECURSIVE up(run, depth) AS (
582
- SELECT s.run, 0 FROM step_runs s WHERE s.ended IS NULL AND s.agent = 1 AND s.waiting IS NULL
583
- UNION SELECT p.run, u.depth + 1 FROM up u JOIN step_runs p ON p.child_run = u.run WHERE u.depth < 32)
584
- SELECT DISTINCT u.run AS run FROM up u WHERE EXISTS (SELECT 1 FROM step_runs r WHERE r.run = u.run AND r.workflow = ?)`,
585
- ).all(workflow) as ReadonlyArray<{ run: string }>).map((r) => r.run), []),
734
+ parentOfRun: (run) =>
735
+ read((db) => db.query('SELECT run, workflow, step FROM step_runs WHERE child_run = ? ORDER BY id DESC LIMIT 1')
736
+ .get(run) as { run: string; workflow: string; step: string } | null, null),
586
737
  stepOfRun: (run) =>
587
738
  read((db) => db.query('SELECT step, subject, (SELECT MIN(started) FROM step_runs s WHERE s.run = ?1) AS started FROM step_runs WHERE run = ?1 ORDER BY id DESC LIMIT 1').get(run) as { step: string; subject: string | null; started: number } | null, null),
588
739
  subjectOfRun: (run) =>
@@ -713,6 +864,23 @@ export const sqliteStore = (options: {
713
864
  .all(...windowOf(since, workflow)) as ReadonlyArray<Omit<LastStepNow, 'failed'> & { failed: number }>).map((l) => ({ ...l, failed: l.failed === 1 }));
714
865
  return { edges, lasts };
715
866
  }, { edges: [], lasts: [] }),
867
+ versionRecords: ({ workflow, version }) =>
868
+ read((db) => {
869
+ // The newest id first, and the version's records up to it: a record written between the two is read from it on.
870
+ const newestId = (db.query('SELECT COALESCE(MAX(id), 0) AS id FROM step_runs').get() as { id: number }).id;
871
+ const records = db.query(`SELECT ${TIMED_COLUMNS} FROM step_runs WHERE workflow = ? AND version = ? AND id <= ? ORDER BY id`).all(workflow, version, newestId) as ReadonlyArray<TimedRecord>;
872
+ return { records, parts: partsOf(db, records), newestId };
873
+ }, { records: [], parts: [], newestId: 0 }),
874
+ recordsSince: ({ after, again }) =>
875
+ read((db) => {
876
+ const fresh = db.query(`SELECT ${TIMED_COLUMNS} FROM step_runs WHERE id > ? ORDER BY id`).all(after) as ReadonlyArray<TimedRecord>;
877
+ const reread = chunked(again).flatMap((ids) => db.query(`SELECT ${TIMED_COLUMNS} FROM step_runs WHERE id IN (${ids.map(() => '?').join(', ')})`).all(...ids) as ReadonlyArray<TimedRecord>);
878
+ const records = [...reread, ...fresh];
879
+ return { records, parts: partsOf(db, records) };
880
+ }, { records: [], parts: [] }),
881
+ previousVersion: ({ workflow, version }) =>
882
+ read((db) => (db.query(`SELECT version, MAX(started) AS at FROM step_runs WHERE workflow = ? AND version IS NOT NULL AND version <> ? GROUP BY version ORDER BY at DESC LIMIT 1`)
883
+ .get(workflow, version) as { version: string; at: number } | null), null),
716
884
  });
717
885
 
718
886
  /** A write in one transaction; it throws, for the caller to say what it could not record. */
@@ -797,17 +965,21 @@ export const sqliteStore = (options: {
797
965
  WHERE at >= ?1 OR at = (SELECT MAX(p.at) FROM queue_counts p WHERE p.workflow = q.workflow AND p.bucket = q.bucket AND p.at < ?1)
798
966
  ORDER BY at`,
799
967
  ).all(since) as ReadonlyArray<QueueCount>, [])),
800
- returnedBetween: () => storeCall('tasks: returnedBetween', () =>
801
- read((db) => db.query(
802
- `SELECT n.by_workflow AS "from", t.workflow AS "to", COUNT(*) AS notes, MAX(n.at) AS last FROM task_notes n JOIN tasks t ON t.id = n.task
803
- WHERE n.kind IN (${TRIES_START_AGAIN_KINDS.map((k) => `'${k}'`).join(', ')}) AND n.by_workflow IS NOT NULL AND n.by_workflow <> t.workflow GROUP BY 1, 2 ORDER BY 1, 2`,
804
- ).all() as ReadonlyArray<ReturnedBetween>, [])),
805
- listedWaits: () => storeCall('tasks: listedWaits', () =>
806
- read((db) => db.query(
807
- `SELECT workflow, json_extract(listed, '$.on') AS "on", json_extract(listed, '$.label') AS label, COUNT(*) AS tasks FROM tasks
808
- WHERE listed IS NOT NULL AND json_extract(listed, '$.kind') = 'wait' GROUP BY 1, 2, 3 ORDER BY 1, 2, 3`,
809
- ).all() as ReadonlyArray<ListedWait>, [])),
810
968
  writable: () => options.file() !== null,
969
+ deleteRunTasksEndedBefore: ({ workflow, before, keepItems, keepNewest }) => storeCall('tasks: deleteRunTasksEndedBefore', () => tryWrite((db) => {
970
+ const candidates = db.query(`SELECT t.id FROM tasks t WHERE t.workflow = ?1 AND t.created_at < ?2 AND t.item NOT IN (SELECT value FROM json_each(?3))
971
+ AND NOT EXISTS (SELECT 1 FROM task_notes n WHERE n.task = t.id AND n.at >= ?2)
972
+ AND NOT EXISTS (SELECT 1 FROM task_notes a WHERE a.about = t.id AND a.task <> t.id)
973
+ AND t.id NOT IN (SELECT n.id FROM tasks n WHERE n.workflow = ?1 ORDER BY n.created_at DESC, n.id DESC LIMIT ${Math.max(0, Math.floor(keepNewest))}) LIMIT ${RETENTION_CHUNK}`);
974
+ const notes = db.query('SELECT COUNT(*) AS n FROM task_notes WHERE task IN (SELECT value FROM json_each(?))');
975
+ // Its notes go with it (`tasks_take_their_notes`).
976
+ const tasks = db.query('DELETE FROM tasks WHERE id IN (SELECT value FROM json_each(?))');
977
+ return inChunks(db, {
978
+ next: () => (candidates.all(workflow, before, JSON.stringify(keepItems)) as ReadonlyArray<{ id: number }>).map((x) => x.id),
979
+ remove: (ids) => ({ notes: (notes.get(ids) as { n: number }).n, tasks: tasks.run(ids).changes }),
980
+ none: { tasks: 0, notes: 0 },
981
+ });
982
+ }) ?? { tasks: 0, notes: 0 }),
811
983
  };
812
984
 
813
985
  const inputs: InputRecords = {
@@ -825,5 +997,26 @@ export const sqliteStore = (options: {
825
997
  read((db) => db.query('SELECT workflow, inputs, run, at, outcome, result FROM input_runs WHERE at >= ? ORDER BY at').all(since) as ReadonlyArray<InputRun>, [])),
826
998
  };
827
999
 
828
- return { stepRecords, tasks, inputs };
1000
+ const claims: AgentClaims = storeCalls<AgentClaims>('agent claims', {
1001
+ // One statement, so the count and the insert see the same claims: two processes taking at once cannot both fit.
1002
+ takeAgentClaim: (r) => tryWrite((db) => (db.query(
1003
+ `INSERT INTO agent_claims (run, workflow, top_run, top_workflow, agents, started)
1004
+ SELECT ?1, ?2, ?3, ?4, ?5, ?6
1005
+ WHERE ?7 IS NULL OR ?5 + COALESCE((SELECT SUM(c.agents) FROM agent_claims c
1006
+ WHERE c.ended IS NULL AND c.top_workflow = ?4 AND c.run <> ?1 AND c.top_run IN (SELECT value FROM json_each(?8))), 0) <= ?7`,
1007
+ ).run(r.run, r.workflow, r.top.run, r.top.workflow, r.agents, Date.now() / 1000, r.limit, JSON.stringify(r.liveTopRuns)).changes === 1 ? 'taken' : 'no room')) ?? 'not recorded',
1008
+ claimHeldAtOrAbove: (run) =>
1009
+ read((db) => (db.query(
1010
+ `WITH RECURSIVE up(run, depth) AS (
1011
+ SELECT ?1, 0
1012
+ UNION SELECT p.run, u.depth + 1 FROM up u JOIN step_runs p ON p.child_run = u.run WHERE u.depth < 32)
1013
+ SELECT EXISTS (SELECT 1 FROM up u JOIN agent_claims c ON c.run = u.run WHERE c.ended IS NULL) AS held`,
1014
+ ).get(run) as { held: number }).held === 1, false),
1015
+ endAgentClaims: (r) => tryWrite((db) => (db.query(`UPDATE agent_claims SET ended = ?, outcome = ? WHERE run = ? AND ended IS NULL RETURNING ${CLAIM_COLUMNS}`)
1016
+ .all(Date.now() / 1000, r.outcome, r.run) as ReadonlyArray<ClaimRow>).map(claimOf)) ?? [],
1017
+ openAgentClaims: () => read((db) => (db.query(`SELECT ${CLAIM_COLUMNS} FROM agent_claims WHERE ended IS NULL ORDER BY id`).all() as ReadonlyArray<ClaimRow>).map(claimOf), []),
1018
+ agentClaimsSince: (since) => read((db) => (db.query(`SELECT ${CLAIM_COLUMNS} FROM agent_claims WHERE started >= ? OR ended IS NULL ORDER BY id`).all(since) as ReadonlyArray<ClaimRow>).map(claimOf), []),
1019
+ });
1020
+
1021
+ return { stepRecords, tasks, inputs, claims };
829
1022
  };