@cloudhal/schedules 0.0.0-stage → 0.1.1

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 (51) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +103 -2
  3. package/dist/src/automation.d.ts +82 -0
  4. package/dist/src/automation.js +199 -0
  5. package/dist/src/budget-meter.d.ts +58 -0
  6. package/dist/src/budget-meter.js +130 -0
  7. package/dist/src/budget.d.ts +41 -0
  8. package/dist/src/budget.js +76 -0
  9. package/dist/src/builtins.d.ts +132 -0
  10. package/dist/src/builtins.js +473 -0
  11. package/dist/src/engine.d.ts +16 -0
  12. package/dist/src/engine.js +30 -0
  13. package/dist/src/errors.d.ts +22 -0
  14. package/dist/src/errors.js +56 -0
  15. package/dist/src/feed-check.d.ts +56 -0
  16. package/dist/src/feed-check.js +365 -0
  17. package/dist/src/findings.d.ts +185 -0
  18. package/dist/src/findings.js +287 -0
  19. package/dist/src/ids.d.ts +24 -0
  20. package/dist/src/ids.js +96 -0
  21. package/dist/src/index.d.ts +24 -0
  22. package/dist/src/index.js +24 -0
  23. package/dist/src/instant.d.ts +19 -0
  24. package/dist/src/instant.js +50 -0
  25. package/dist/src/notify.d.ts +50 -0
  26. package/dist/src/notify.js +60 -0
  27. package/dist/src/recurrence.d.ts +155 -0
  28. package/dist/src/recurrence.js +939 -0
  29. package/dist/src/release-when.d.ts +23 -0
  30. package/dist/src/release-when.js +55 -0
  31. package/dist/src/release.d.ts +198 -0
  32. package/dist/src/release.js +552 -0
  33. package/dist/src/scheduler.d.ts +490 -0
  34. package/dist/src/scheduler.js +1343 -0
  35. package/dist/src/sql/finish.d.ts +32 -0
  36. package/dist/src/sql/finish.js +103 -0
  37. package/dist/src/sql/index.d.ts +6 -0
  38. package/dist/src/sql/index.js +15 -0
  39. package/dist/src/sql/rows.d.ts +125 -0
  40. package/dist/src/sql/rows.js +297 -0
  41. package/dist/src/sql/store.d.ts +467 -0
  42. package/dist/src/sql/store.js +2166 -0
  43. package/dist/src/taint.d.ts +65 -0
  44. package/dist/src/taint.js +138 -0
  45. package/dist/src/text.d.ts +6 -0
  46. package/dist/src/text.js +25 -0
  47. package/dist/src/time-entry.d.ts +6 -0
  48. package/dist/src/time-entry.js +6 -0
  49. package/dist/src/time.d.ts +61 -0
  50. package/dist/src/time.js +140 -0
  51. package/package.json +69 -3
@@ -0,0 +1,2166 @@
1
+ /**
2
+ * `SqlScheduleStore` — releases, automations, runs, system jobs, the heartbeat and per-site
3
+ * settings over `SqlDriver` (SQLite locally and on Node, D1 on Cloudflare) for the tables of
4
+ * migration `0017_schedules`. Worker-safe; it implements `SchedulerStore` for `runDue`.
5
+ *
6
+ * Writes are single statements or one atomic `batch()` (no interactive transactions, AGENTS.md
7
+ * rule 4). Every composite write is decided by one compare-and-swap, and the other statements of
8
+ * its batch carry the same decision:
9
+ * - **inserts** after a new release are guarded on the release's new content hash (`rl1:`);
10
+ * - **claims** store a fresh random lease token, and every later write of that run (finish,
11
+ * defer) is guarded on "the row still carries my token" — the token is unique per claim, so it
12
+ * plays the role of the new content hash, never `rev + 1`;
13
+ * - **dependent rows** (runs, a release's items) are written *before* the CAS statement in the same
14
+ * batch and guarded on exactly the CAS condition (pre-state and `rev`, or the token), which the
15
+ * earlier statements cannot change; if the CAS loses, none of them applies.
16
+ * - `release_items.held` is never guarded: it is recomputed from the release's state after every
17
+ * change (`HELD_SYNC`), so it is right whichever writer won.
18
+ *
19
+ * Every record written is checked with the precompiled contract validators (`assertValid`).
20
+ */
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+ import { assertValid } from "@cloudhal/core-contracts";
35
+
36
+ import {
37
+ assertAutomationTransition,
38
+ CONSECUTIVE_FAILURE_LIMIT,
39
+ firstRunFrom,
40
+ } from "../automation.js";
41
+ import { DEFAULT_DAILY_WRITE_CAP, utcDayStart } from "../budget.js";
42
+
43
+ import { ScheduleConflictError, ScheduleError } from "../errors.js";
44
+ import { newAutomationId, newReleaseId, runId } from "../ids.js";
45
+ import { DEFAULT_MIN_INTERVAL_MINUTES, presetOf, validateRecurrence } from "../recurrence.js";
46
+ import {
47
+ assertReleaseTransition,
48
+ HOLDING_STATES,
49
+ isTerminalRelease,
50
+ MAX_OPEN_RELEASES_PER_SITE,
51
+
52
+ releaseHash,
53
+ TERMINAL_RELEASE_STATES,
54
+ } from "../release.js";
55
+
56
+
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+ import { plainLine } from "../text.js";
68
+ import { canonicalInstant } from "../time.js";
69
+ import { releaseFinishStatements } from "./finish.js";
70
+ import {
71
+
72
+ cursorOf,
73
+
74
+ ITEMS_JSON,
75
+ itemsOf,
76
+
77
+
78
+
79
+ toAutomation,
80
+ toHeartbeat,
81
+ toRelease,
82
+ toRun,
83
+ toSystemJob,
84
+ } from "./rows.js";
85
+
86
+
87
+
88
+
89
+
90
+
91
+ /** Per-site schedule settings (§4.5, §5.1): outside the graph, so a rollback cannot un-pause a site. */
92
+
93
+
94
+  
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+ /** A release with what the store keeps beside the contract. */
108
+
109
+
110
+
111
+
112
+
113
+
114
+
115
+
116
+
117
+
118
+
119
+
120
+
121
+
122
+
123
+
124
+
125
+    
126
+
127
+
128
+
129
+
130
+
131
+
132
+
133
+
134
+
135
+
136
+
137
+
138
+
139
+
140
+
141
+
142
+
143
+
144
+
145
+
146
+
147
+
148
+
149
+  
150
+
151
+
152
+
153
+
154
+
155
+
156
+
157
+
158
+
159
+
160
+
161
+ const HOLDING_SQL = HOLDING_STATES.map((s) => `'${s}'`).join(", ");
162
+ const TERMINAL_SQL = TERMINAL_RELEASE_STATES.map((s) => `'${s}'`).join(", ");
163
+ /** `release_items.held` recomputed from the release's state (params: release id twice). */
164
+ const HELD_SYNC = `UPDATE release_items SET held = CASE WHEN (SELECT state FROM releases WHERE id = ?) IN (${HOLDING_SQL}) THEN 1 ELSE 0 END WHERE release_id = ?`;
165
+ const RELEASE_COLUMNS =
166
+ "id, site_id, title, state, hash, when_kind, execute_at, time_zone, local_time, approval, request_id, outcome, purge_plan, lease_token, lease_until, created_by, metadata, rev, created_at, updated_at";
167
+ const RUN_COLUMNS =
168
+ "id, site_id, subject_kind, subject_id, occurrence_at, state, outcome, trigger, attempt, lease_token, lease_until, window_opens, window_closes, started_at, ended_at, lateness_s, adjusted, usage, taint, summary, counts, findings, approval_ids, error, rev, created_at, updated_at";
169
+
170
+ const j = (v ) => (v === undefined || v === null ? null : JSON.stringify(v));
171
+
172
+ function whenColumns(when )
173
+
174
+
175
+
176
+
177
+ {
178
+ if (!when) return { when_kind: null, time_zone: null, local_time: null, at: null };
179
+ if (when.kind === "on-approval")
180
+ return { when_kind: "on-approval", time_zone: null, local_time: null, at: null };
181
+ return {
182
+ when_kind: "at",
183
+ time_zone: when.timeZone,
184
+ local_time: when.localTime ?? null,
185
+ at: canonicalInstant(when.at),
186
+ };
187
+ }
188
+
189
+ /** `when` with its instant in the canonical stored form (what a read gives back). */
190
+ function canonicalWhen(when ) {
191
+ return when.kind === "at" ? { ...when, at: canonicalInstant(when.at) } : when;
192
+ }
193
+
194
+ function itemsPayload(items ) {
195
+ return JSON.stringify(
196
+ items.map((p) => ({
197
+ n: p.item.nodeId,
198
+ o: p.item.kind,
199
+ k: p.item.nodeKind,
200
+ tr: p.item.kind === "set" ? p.item.target.rev : null,
201
+ th: p.item.kind === "set" ? p.item.target.hash : null,
202
+ br: p.item.base?.rev ?? null,
203
+ bh: p.item.base?.hash ?? null,
204
+ d: JSON.stringify([...p.deps]),
205
+ b: p.blobSha ?? null,
206
+ })),
207
+ );
208
+ }
209
+
210
+ /**
211
+ * Inserts a release's items, guarded on the release carrying its new content hash (AGENTS.md rule 4)
212
+ * and this write's `updated_at` (params: id, site, id, items, id, hash, stamp).
213
+ */
214
+ const INSERT_ITEMS = `INSERT INTO release_items (release_id, site_id, node_id, op, node_kind, target_rev, target_hash, base_rev, base_hash, deps, blob_sha, held)
215
+ SELECT ?, ?, json_extract(value, '$.n'), json_extract(value, '$.o'), json_extract(value, '$.k'), json_extract(value, '$.tr'),
216
+ json_extract(value, '$.th'), json_extract(value, '$.br'), json_extract(value, '$.bh'), json_extract(value, '$.d'), json_extract(value, '$.b'),
217
+ CASE WHEN (SELECT state FROM releases WHERE id = ?) IN (${HOLDING_SQL}) THEN 1 ELSE 0 END
218
+ FROM json_each(?) WHERE EXISTS (SELECT 1 FROM releases WHERE id = ? AND hash = ? AND updated_at = ?)`;
219
+
220
+ export class SqlScheduleStore {
221
+ #sql ;
222
+ #now ;
223
+
224
+ constructor(sql , options = {}) {
225
+ this.#sql = sql;
226
+ this.#now = options.now ?? (() => new Date());
227
+ }
228
+
229
+ #stamp() {
230
+ return this.#now().toISOString();
231
+ }
232
+
233
+ // ───────────────────────────── releases ─────────────────────────────
234
+
235
+ /** A new `draft` release with its pinned items (§6.1). Items are hashed into `rl1:`. */
236
+ async createRelease(input ) {
237
+ const open = await this.#sql.get (
238
+ `SELECT COUNT(*) AS n FROM releases WHERE site_id = ? AND state NOT IN (${TERMINAL_SQL})`,
239
+ [input.siteId],
240
+ );
241
+ if (Number(open?.n ?? 0) >= MAX_OPEN_RELEASES_PER_SITE)
242
+ throw new ScheduleError(
243
+ "too_many_releases",
244
+ `at most ${MAX_OPEN_RELEASES_PER_SITE} open releases per site`,
245
+ );
246
+ const now = this.#stamp();
247
+ const items = [...input.items].sort((a, b) =>
248
+ a.item.nodeId < b.item.nodeId ? -1 : a.item.nodeId > b.item.nodeId ? 1 : 0,
249
+ );
250
+ const release = {
251
+ schemaVersion: 1,
252
+ id: input.id ?? newReleaseId(),
253
+ siteId: input.siteId,
254
+ ...(input.title !== undefined ? { title: input.title } : {}),
255
+ items: items.map((i) => i.item) ,
256
+ ...(input.when ? { when: canonicalWhen(input.when) } : {}),
257
+ state: "draft",
258
+ hash: await releaseHash(
259
+ input.siteId,
260
+ items.map((i) => i.item),
261
+ ),
262
+ createdBy: input.createdBy,
263
+ createdAt: now,
264
+ updatedAt: now,
265
+ rev: 1,
266
+ ...(input.metadata ? { metadata: input.metadata } : {}),
267
+ };
268
+ if (new Set(release.items.map((i) => i.nodeId)).size !== release.items.length)
269
+ throw new ScheduleError("duplicate_item", "a node is in the release twice");
270
+ assertValid("release", release);
271
+ const w = whenColumns(release.when);
272
+ await this.#sql.batch([
273
+ {
274
+ sql: `INSERT INTO releases (${RELEASE_COLUMNS}) VALUES (?, ?, ?, 'draft', ?, ?, ?, ?, ?, NULL, NULL, NULL, ?, NULL, NULL, ?, ?, 1, ?, ?)`,
275
+ params: [
276
+ release.id,
277
+ release.siteId,
278
+ release.title ?? null,
279
+ release.hash,
280
+ w.when_kind,
281
+ w.at,
282
+ w.time_zone,
283
+ w.local_time,
284
+ j(input.purgePlan),
285
+ JSON.stringify(release.createdBy),
286
+ j(release.metadata),
287
+ now,
288
+ now,
289
+ ],
290
+ },
291
+ {
292
+ sql: INSERT_ITEMS,
293
+ params: [
294
+ release.id,
295
+ release.siteId,
296
+ release.id,
297
+ itemsPayload(items),
298
+ release.id,
299
+ release.hash,
300
+ now,
301
+ ],
302
+ },
303
+ ]);
304
+ return release;
305
+ }
306
+
307
+ async getReleaseRecord(siteId , id ) {
308
+ const row = await this.#sql.get (
309
+ `SELECT r.*, ${ITEMS_JSON} FROM releases r WHERE r.id = ? AND r.site_id = ?`,
310
+ [id, siteId],
311
+ );
312
+ return row ? this.#record(row) : undefined;
313
+ }
314
+
315
+ #record(row ) {
316
+ const items = itemsOf(row);
317
+ return {
318
+ release: toRelease(row, items),
319
+ items,
320
+ ...(row.execute_at ? { executeAt: row.execute_at } : {}),
321
+ ...(row.request_id ? { requestId: row.request_id } : {}),
322
+ ...(row.purge_plan ? { purgePlan: JSON.parse(row.purge_plan) } : {}),
323
+ ...(row.lease_token ? { leaseToken: row.lease_token } : {}),
324
+ ...(row.lease_until ? { leaseUntil: row.lease_until } : {}),
325
+ };
326
+ }
327
+
328
+ async getRelease(siteId , id ) {
329
+ return (await this.getReleaseRecord(siteId, id))?.release;
330
+ }
331
+
332
+ /** A site's releases in time order (undated drafts last), optionally by state. */
333
+ async listReleases(
334
+ siteId ,
335
+ options = {},
336
+ ) {
337
+ const limit = Math.min(Math.max(options.limit ?? 50, 1), 200);
338
+ const states = options.states ?? [];
339
+ const rows = await this.#sql.all (
340
+ `SELECT r.*, ${ITEMS_JSON} FROM releases r WHERE r.site_id = ?${
341
+ states.length > 0 ? ` AND r.state IN (${states.map(() => "?").join(", ")})` : ""
342
+ } ORDER BY r.execute_at IS NULL, r.execute_at, r.id LIMIT ?`,
343
+ [siteId, ...states, limit],
344
+ );
345
+ return rows.map((r) => toRelease(r, itemsOf(r)));
346
+ }
347
+
348
+ /**
349
+ * Moves a release between states (§5.2) with a compare-and-swap on `rev`. The scheduler's own
350
+ * transitions (claim, finish) go through the claim methods; `running` is never entered here.
351
+ */
352
+ async transitionRelease(siteId , id , change ) {
353
+ const rec = await this.getReleaseRecord(siteId, id);
354
+ if (!rec) throw new ScheduleError("not_found", `release ${id} not found`);
355
+ const from = rec.release.state;
356
+ if (rec.release.rev !== change.expectedRev) throw new ScheduleConflictError("release", id);
357
+ if (change.to === "running")
358
+ throw new ScheduleError("invalid_transition", "only the scheduler starts a release (claim)");
359
+ if (from === "running")
360
+ throw new ScheduleError(
361
+ "invalid_transition",
362
+ "a running release finishes on its own in seconds",
363
+ );
364
+ assertReleaseTransition(from, change.to);
365
+ const now = this.#stamp();
366
+ const { approval: _a, outcome: _o, when: _w, title: _t, ...rest } = rec.release;
367
+ const approval =
368
+ change.approval === undefined ? rec.release.approval : (change.approval ?? undefined);
369
+ const outcome =
370
+ change.outcome === undefined
371
+ ? isTerminalRelease(change.to)
372
+ ? rec.release.outcome
373
+ : undefined
374
+ : (change.outcome ?? undefined);
375
+ const when =
376
+ change.when === undefined
377
+ ? rec.release.when
378
+ : change.when
379
+ ? canonicalWhen(change.when)
380
+ : undefined;
381
+ const title = change.title === undefined ? rec.release.title : (change.title ?? undefined);
382
+ const next = {
383
+ ...rest,
384
+ ...(title !== undefined ? { title } : {}),
385
+ ...(when ? { when } : {}),
386
+ state: change.to,
387
+ ...(approval ? { approval } : {}),
388
+ ...(outcome ? { outcome } : {}),
389
+ rev: rec.release.rev + 1,
390
+ updatedAt: now,
391
+ };
392
+ if (next.state === "scheduled" && !next.approval)
393
+ throw new ScheduleError("invalid_transition", "a scheduled release needs an approval");
394
+ if (next.state === "scheduled" && !next.when)
395
+ throw new ScheduleError(
396
+ "invalid_transition",
397
+ "a scheduled release needs a time (or on-approval)",
398
+ );
399
+ if (isTerminalRelease(next.state) && next.outcome?.kind !== next.state)
400
+ throw new ScheduleError(
401
+ "invalid_transition",
402
+ `a ${next.state} release needs a matching outcome`,
403
+ );
404
+ assertValid("release", next);
405
+ const w = whenColumns(next.when);
406
+ // An on-approval release becomes due the moment it is scheduled.
407
+ const executeAt = w.at ?? (next.state === "scheduled" ? now : (rec.executeAt ?? null));
408
+ const requestId = change.requestId === undefined ? (rec.requestId ?? null) : change.requestId;
409
+ const [res] = await this.#sql.batch([
410
+ {
411
+ sql: `UPDATE releases SET title = ?, state = ?, when_kind = ?, execute_at = ?, time_zone = ?, local_time = ?, approval = ?, request_id = ?, outcome = ?, rev = rev + 1, updated_at = ?
412
+ WHERE id = ? AND site_id = ? AND rev = ? AND state = ?`,
413
+ params: [
414
+ next.title ?? null,
415
+ next.state,
416
+ w.when_kind,
417
+ executeAt,
418
+ w.time_zone,
419
+ w.local_time,
420
+ j(next.approval),
421
+ requestId,
422
+ j(next.outcome),
423
+ now,
424
+ id,
425
+ siteId,
426
+ change.expectedRev,
427
+ from,
428
+ ],
429
+ },
430
+ { sql: HELD_SYNC, params: [id, id] },
431
+ ]);
432
+ if ((res?.changes ?? 0) !== 1) throw new ScheduleConflictError("release", id);
433
+ return next;
434
+ }
435
+
436
+ /**
437
+ * Re-pins a release's items (§6.4 re-pin; "edit and re-approve"): a new `rl1:` hash, the approval
438
+ * voided. From `draft` or `conflict` the release becomes a `draft`; from `awaiting_approval` or
439
+ * `scheduled` it waits for approval again (S6).
440
+ */
441
+ async repinRelease(
442
+ siteId ,
443
+ id ,
444
+ input ,
445
+ ) {
446
+ const rec = await this.getReleaseRecord(siteId, id);
447
+ if (!rec) throw new ScheduleError("not_found", `release ${id} not found`);
448
+ if (rec.release.rev !== input.expectedRev) throw new ScheduleConflictError("release", id);
449
+ const from = rec.release.state;
450
+ const to =
451
+ from === "draft" || from === "conflict"
452
+ ? "draft"
453
+ : from === "awaiting_approval" || from === "scheduled"
454
+ ? "awaiting_approval"
455
+ : (() => {
456
+ throw new ScheduleError(
457
+ "invalid_transition",
458
+ `a ${from} release cannot be re-pinned`,
459
+ );
460
+ })();
461
+ const items = [...input.items].sort((a, b) =>
462
+ a.item.nodeId < b.item.nodeId ? -1 : a.item.nodeId > b.item.nodeId ? 1 : 0,
463
+ );
464
+ const hash = await releaseHash(
465
+ siteId,
466
+ items.map((i) => i.item),
467
+ );
468
+ const now = this.#stamp();
469
+ const { approval: _a, outcome: _o, ...rest } = rec.release;
470
+ const next = {
471
+ ...rest,
472
+ items: items.map((i) => i.item) ,
473
+ hash,
474
+ state: to,
475
+ rev: rec.release.rev + 1,
476
+ updatedAt: now,
477
+ };
478
+ assertValid("release", next);
479
+ const [res] = await this.#sql.batch([
480
+ {
481
+ sql: `UPDATE releases SET hash = ?, state = ?, approval = NULL, outcome = NULL, request_id = NULL, purge_plan = ?, rev = rev + 1, updated_at = ?
482
+ WHERE id = ? AND site_id = ? AND rev = ? AND state = ?`,
483
+ params: [
484
+ hash,
485
+ to,
486
+ j(input.purgePlan ?? rec.purgePlan),
487
+ now,
488
+ id,
489
+ siteId,
490
+ input.expectedRev,
491
+ from,
492
+ ],
493
+ },
494
+ // Guarded on the new content hash (AGENTS.md rule 4).
495
+ {
496
+ sql: "DELETE FROM release_items WHERE release_id = ? AND EXISTS (SELECT 1 FROM releases WHERE id = ? AND hash = ? AND updated_at = ?)",
497
+ params: [id, id, hash, now],
498
+ },
499
+ { sql: INSERT_ITEMS, params: [id, siteId, id, itemsPayload(items), id, hash, now] },
500
+ ]);
501
+ if ((res?.changes ?? 0) !== 1) throw new ScheduleConflictError("release", id);
502
+ return next;
503
+ }
504
+
505
+ /** Withdraws a release (`canceled`). A running release cannot be canceled (§8.5: 409). */
506
+ async cancelRelease(
507
+ siteId ,
508
+ id ,
509
+ input ,
510
+ ) {
511
+ return this.transitionRelease(siteId, id, {
512
+ expectedRev: input.expectedRev,
513
+ to: "canceled",
514
+ outcome: { kind: "canceled", at: this.#stamp(), by: input.by },
515
+ });
516
+ }
517
+
518
+ /** Nodes held by non-terminal releases (§6.2 locks and holds), node id → release ids. */
519
+ async heldNodes(siteId , nodeIds ) {
520
+ const ids = nodeIds ? [...new Set(nodeIds)] : undefined;
521
+ if (ids && ids.length === 0) return new Map();
522
+ const rows = await this.#sql.all (
523
+ `SELECT node_id, release_id FROM release_items WHERE site_id = ? AND held = 1${
524
+ ids ? ` AND node_id IN (SELECT value FROM json_each(?))` : ""
525
+ } ORDER BY node_id, release_id`,
526
+ ids ? [siteId, JSON.stringify(ids)] : [siteId],
527
+ );
528
+ const out = new Map ();
529
+ for (const r of rows) out.set(r.node_id, [...(out.get(r.node_id) ?? []), r.release_id]);
530
+ return out;
531
+ }
532
+
533
+ /** Nodes in two or more non-terminal releases (D15: flagged, not refused). */
534
+ async overlaps(siteId ) {
535
+ const rows = await this.#sql.all (
536
+ `SELECT i.node_id, json_group_array(i.release_id) AS ids FROM release_items i JOIN releases r ON r.id = i.release_id
537
+ WHERE i.site_id = ? AND r.state NOT IN (${TERMINAL_SQL}) GROUP BY i.node_id HAVING COUNT(*) > 1 ORDER BY i.node_id`,
538
+ [siteId],
539
+ );
540
+ return new Map(rows.map((r) => [r.node_id, (JSON.parse(r.ids) ).sort()]));
541
+ }
542
+
543
+ /**
544
+ * D5 for one site: releases still `awaiting_approval` at their time become `expired`
545
+ * (`unapproved`). Indexed by `releases_site`; the API calls it when it reads a site's schedule,
546
+ * so the tick never scans releases outside `releases_due`.
547
+ */
548
+ async expireOverdueApprovals(siteId , now ) {
549
+ const at = canonicalInstant(now);
550
+ const outcome = JSON.stringify({ kind: "expired", at, reason: "unapproved" });
551
+ const [, res] = await this.#sql.batch([
552
+ {
553
+ sql: `UPDATE release_items SET held = 0 WHERE site_id = ? AND release_id IN
554
+ (SELECT id FROM releases WHERE site_id = ? AND state = 'awaiting_approval' AND execute_at <= ?)`,
555
+ params: [siteId, siteId, at],
556
+ },
557
+ {
558
+ sql: `UPDATE releases SET state = 'expired', outcome = ?, rev = rev + 1, updated_at = ?
559
+ WHERE site_id = ? AND state = 'awaiting_approval' AND execute_at <= ?`,
560
+ params: [outcome, at, siteId, at],
561
+ },
562
+ ]);
563
+ return res?.changes ?? 0;
564
+ }
565
+
566
+ // ───────────────────────────── scheduler: releases ─────────────────────────────
567
+
568
+ async overview(_now ) {
569
+ const row = await this.#sql.get
570
+
571
+
572
+
573
+
574
+
575
+
576
+
577
+ (
578
+ `SELECT
579
+ (SELECT MIN(execute_at) FROM releases WHERE state = 'scheduled') AS next_release,
580
+ (SELECT MIN(next_run_at) FROM automations WHERE state = 'active') AS next_automation,
581
+ (SELECT MIN(next_run_at) FROM system_jobs) AS next_job,
582
+ (SELECT COUNT(*) FROM system_jobs) AS jobs,
583
+ (SELECT MIN(CASE WHEN state = 'ready' THEN window_closes ELSE lease_until END) FROM schedule_runs
584
+ WHERE state IN ('ready', 'running')) AS next_deadline,
585
+ h.at, h.trigger, h.next_wake_at, h.ran, h.more, h.lag_s
586
+ FROM (SELECT 1) LEFT JOIN scheduler_heartbeat h ON h.id = 1`,
587
+ );
588
+ const hb = toHeartbeat(row);
589
+ return {
590
+ ...(row?.next_release ? { nextReleaseAt: row.next_release } : {}),
591
+ ...(row?.next_automation ? { nextAutomationAt: row.next_automation } : {}),
592
+ ...(row?.next_job ? { nextSystemJobAt: row.next_job } : {}),
593
+ ...(row?.next_deadline ? { nextRunDeadline: row.next_deadline } : {}),
594
+ systemJobs: Number(row?.jobs ?? 0),
595
+ ...(hb ? { heartbeat: hb } : {}),
596
+ };
597
+ }
598
+
599
+ async dueReleases(now , limit ) {
600
+ const rows = await this.#sql.all (
601
+ `SELECT r.*, ${ITEMS_JSON}, COALESCE(s.paused, 0) AS site_paused FROM releases r
602
+ LEFT JOIN schedule_settings s ON s.site_id = r.site_id
603
+ WHERE r.state = 'scheduled' AND r.execute_at <= ? ORDER BY r.execute_at, r.id LIMIT ?`,
604
+ [now, limit],
605
+ );
606
+ return rows.map((row) => {
607
+ const items = itemsOf(row);
608
+ return {
609
+ release: toRelease(row, items),
610
+ items,
611
+ executeAt: String(row.execute_at),
612
+ sitePaused: Number(row.site_paused) === 1,
613
+ };
614
+ });
615
+ }
616
+
617
+ async expiredReleaseLeases(now , limit ) {
618
+ const rows = await this.#sql.all
619
+
620
+
621
+
622
+
623
+
624
+
625
+ (
626
+ `SELECT r.*, ${ITEMS_JSON}, COALESCE(s.paused, 0) AS site_paused, x.id AS run_id, x.attempt AS run_attempt, x.occurrence_at AS run_occurrence
627
+ FROM schedule_runs x JOIN releases r ON r.id = x.subject_id AND r.state = 'running' AND r.lease_token = x.lease_token
628
+ LEFT JOIN schedule_settings s ON s.site_id = r.site_id
629
+ WHERE x.state IN ('ready', 'running') AND x.subject_kind = 'release' AND x.lease_until <= ?
630
+ ORDER BY r.execute_at, r.id LIMIT ?`,
631
+ [now, limit],
632
+ );
633
+ return rows.map((row) => {
634
+ const items = itemsOf(row);
635
+ return {
636
+ release: toRelease(row, items),
637
+ items,
638
+ executeAt: String(row.execute_at),
639
+ sitePaused: Number(row.site_paused) === 1,
640
+ run: {
641
+ id: row.run_id,
642
+ attempt: Number(row.run_attempt),
643
+ leaseToken: String(row.lease_token),
644
+ occurrenceAt: row.run_occurrence,
645
+ },
646
+ };
647
+ });
648
+ }
649
+
650
+ async claimRelease(input ) {
651
+ const results = await this.#sql.batch([
652
+ {
653
+ // The claim (§8.5): CAS on rev and state, and no other release of the site under a live lease (D15).
654
+ sql: `UPDATE releases SET state = 'running', lease_token = ?, lease_until = ?, rev = rev + 1, updated_at = ?
655
+ WHERE id = ? AND site_id = ? AND rev = ? AND state = 'scheduled'
656
+ AND NOT EXISTS (SELECT 1 FROM releases o WHERE o.site_id = ? AND o.state = 'running' AND o.lease_until > ?)`,
657
+ params: [
658
+ input.token,
659
+ input.leaseUntil,
660
+ input.now,
661
+ input.releaseId,
662
+ input.siteId,
663
+ input.expectedRev,
664
+ input.siteId,
665
+ input.now,
666
+ ],
667
+ },
668
+ {
669
+ // The run row, keyed by the occurrence; guarded on our token (unique per claim).
670
+ sql: `INSERT INTO schedule_runs (${RUN_COLUMNS})
671
+ SELECT ?, ?, 'release', ?, ?, 'running', NULL, ?, 1, ?, ?, NULL, NULL, ?, NULL, ?, ?, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, ?, ?
672
+ WHERE EXISTS (SELECT 1 FROM releases WHERE id = ? AND lease_token = ?)
673
+ ON CONFLICT(id) DO UPDATE SET state = 'running', trigger = excluded.trigger, attempt = schedule_runs.attempt + 1,
674
+ lease_token = excluded.lease_token, lease_until = excluded.lease_until, started_at = excluded.started_at,
675
+ ended_at = NULL, lateness_s = excluded.lateness_s, adjusted = excluded.adjusted, error = NULL,
676
+ rev = schedule_runs.rev + 1, updated_at = excluded.updated_at`,
677
+ params: [
678
+ input.runId,
679
+ input.siteId,
680
+ input.releaseId,
681
+ canonicalInstant(input.executeAt),
682
+ input.trigger,
683
+ input.token,
684
+ input.leaseUntil,
685
+ input.now,
686
+ input.latenessSeconds,
687
+ input.adjusted ?? null,
688
+ input.now,
689
+ input.now,
690
+ input.releaseId,
691
+ input.token,
692
+ ],
693
+ },
694
+ ]);
695
+ return (results[0]?.changes ?? 0) === 1;
696
+ }
697
+
698
+ async reclaimRelease(input
699
+
700
+
701
+
702
+
703
+
704
+
705
+
706
+
707
+ ) {
708
+ const results = await this.#sql.batch([
709
+ {
710
+ sql: `UPDATE releases SET lease_token = ?, lease_until = ?, rev = rev + 1, updated_at = ?
711
+ WHERE id = ? AND state = 'running' AND lease_token = ? AND lease_until <= ?`,
712
+ params: [
713
+ input.token,
714
+ input.leaseUntil,
715
+ input.now,
716
+ input.releaseId,
717
+ input.oldToken,
718
+ input.now,
719
+ ],
720
+ },
721
+ {
722
+ sql: `UPDATE schedule_runs SET lease_token = ?, lease_until = ?, attempt = attempt + 1, trigger = ?, lateness_s = ?, error = NULL,
723
+ rev = rev + 1, updated_at = ? WHERE id = ? AND EXISTS (SELECT 1 FROM releases WHERE id = ? AND lease_token = ?)`,
724
+ params: [
725
+ input.token,
726
+ input.leaseUntil,
727
+ input.trigger,
728
+ input.latenessSeconds,
729
+ input.now,
730
+ input.runId,
731
+ input.releaseId,
732
+ input.token,
733
+ ],
734
+ },
735
+ ]);
736
+ return (results[0]?.changes ?? 0) === 1;
737
+ }
738
+
739
+ /**
740
+ * The statements that end a claimed release (§6.3 statements 5–7), each guarded on the lease
741
+ * token and, optionally, on `guard` — the site CAS of `publishRelease`, which appends these to its
742
+ * own batch (`EXISTS (SELECT 1 FROM nodes WHERE id = :site AND hash = :hash')`). The release row
743
+ * is updated last.
744
+ */
745
+ releaseFinishStatements(input
746
+
747
+
748
+
749
+
750
+
751
+
752
+
753
+ ) {
754
+ return releaseFinishStatements(input);
755
+ }
756
+
757
+ async finishRelease(input
758
+
759
+
760
+
761
+
762
+
763
+
764
+ ) {
765
+ const results = await this.#sql.batch(this.releaseFinishStatements(input));
766
+ return (results[results.length - 1]?.changes ?? 0) === 1;
767
+ }
768
+
769
+ async deferRelease(input
770
+
771
+
772
+
773
+
774
+
775
+
776
+ ) {
777
+ const results = await this.#sql.batch([
778
+ {
779
+ sql: `UPDATE schedule_runs SET lease_until = ?, error = ?, rev = rev + 1, updated_at = ?
780
+ WHERE id = ? AND lease_token = ? AND EXISTS (SELECT 1 FROM releases WHERE id = ? AND lease_token = ? AND state = 'running')`,
781
+ params: [
782
+ input.retryAt,
783
+ JSON.stringify({
784
+ code: "transient",
785
+ message: plainLine(input.error),
786
+ }),
787
+ input.now,
788
+ input.runId,
789
+ input.token,
790
+ input.releaseId,
791
+ input.token,
792
+ ],
793
+ },
794
+ {
795
+ sql: "UPDATE releases SET lease_until = ?, rev = rev + 1, updated_at = ? WHERE id = ? AND lease_token = ? AND state = 'running'",
796
+ params: [input.retryAt, input.now, input.releaseId, input.token],
797
+ },
798
+ ]);
799
+ return (results[1]?.changes ?? 0) === 1;
800
+ }
801
+
802
+ async settleRelease(input
803
+
804
+
805
+
806
+
807
+
808
+
809
+
810
+ ) {
811
+ const pre = "EXISTS (SELECT 1 FROM releases WHERE id = ? AND rev = ? AND state = 'scheduled')";
812
+ const statements = [];
813
+ if (input.outcome.kind === "missed") {
814
+ const id = await runId(input.releaseId, input.executeAt);
815
+ statements.push({
816
+ sql: `INSERT OR IGNORE INTO schedule_runs (${RUN_COLUMNS})
817
+ SELECT ?, ?, 'release', ?, ?, 'missed', NULL, ?, 1, NULL, NULL, NULL, NULL, NULL, ?, ?, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, ?, ?
818
+ WHERE ${pre}`,
819
+ params: [
820
+ id,
821
+ input.siteId,
822
+ input.releaseId,
823
+ canonicalInstant(input.executeAt),
824
+ input.trigger,
825
+ input.now,
826
+ input.outcome.latenessSeconds,
827
+ input.now,
828
+ input.now,
829
+ input.releaseId,
830
+ input.expectedRev,
831
+ ],
832
+ });
833
+ }
834
+ statements.push(
835
+ {
836
+ sql: `UPDATE release_items SET held = 0 WHERE release_id = ? AND ${pre}`,
837
+ params: [input.releaseId, input.releaseId, input.expectedRev],
838
+ },
839
+ {
840
+ sql: `UPDATE releases SET state = ?, outcome = ?, rev = rev + 1, updated_at = ? WHERE id = ? AND site_id = ? AND rev = ? AND state = 'scheduled'`,
841
+ params: [
842
+ input.outcome.kind,
843
+ JSON.stringify(input.outcome),
844
+ input.now,
845
+ input.releaseId,
846
+ input.siteId,
847
+ input.expectedRev,
848
+ ],
849
+ },
850
+ );
851
+ const results = await this.#sql.batch(statements);
852
+ return (results[results.length - 1]?.changes ?? 0) === 1;
853
+ }
854
+
855
+ /**
856
+ * "Publish now" (§5.2, §8.6): a person's manual run of a `scheduled`, `missed` or `expired`
857
+ * release. One batch, decided by the release CAS (`rev` and state, and no other release of the
858
+ * site running under a live lease, D15): the release becomes `running` with the person's
859
+ * approval and the time it actually runs, the run row is keyed by that instant (trigger
860
+ * `manual`), and the items are held again. False when the CAS lost.
861
+ */
862
+ async claimManualRun(input
863
+
864
+
865
+
866
+
867
+
868
+
869
+
870
+
871
+ ) {
872
+ const at = canonicalInstant(input.now);
873
+ const results = await this.#sql.batch([
874
+ {
875
+ sql: `UPDATE releases SET state = 'running', approval = ?, outcome = NULL, execute_at = ?, lease_token = ?, lease_until = ?, rev = rev + 1, updated_at = ?
876
+ WHERE id = ? AND site_id = ? AND rev = ? AND state IN ('scheduled', 'missed', 'expired')
877
+ AND NOT EXISTS (SELECT 1 FROM releases o WHERE o.site_id = ? AND o.state = 'running' AND o.lease_until > ?)`,
878
+ params: [
879
+ JSON.stringify(input.approval),
880
+ at,
881
+ input.token,
882
+ input.leaseUntil,
883
+ at,
884
+ input.releaseId,
885
+ input.siteId,
886
+ input.expectedRev,
887
+ input.siteId,
888
+ at,
889
+ ],
890
+ },
891
+ {
892
+ sql: `INSERT INTO schedule_runs (${RUN_COLUMNS})
893
+ SELECT ?, ?, 'release', ?, ?, 'running', NULL, 'manual', 1, ?, ?, NULL, NULL, ?, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, ?, ?
894
+ WHERE EXISTS (SELECT 1 FROM releases WHERE id = ? AND lease_token = ?)`,
895
+ params: [
896
+ input.runId,
897
+ input.siteId,
898
+ input.releaseId,
899
+ at,
900
+ input.token,
901
+ input.leaseUntil,
902
+ at,
903
+ at,
904
+ at,
905
+ input.releaseId,
906
+ input.token,
907
+ ],
908
+ },
909
+ { sql: HELD_SYNC, params: [input.releaseId, input.releaseId] },
910
+ ]);
911
+ return (results[0]?.changes ?? 0) === 1;
912
+ }
913
+
914
+ /**
915
+ * After a published release's purge (§6.3 "After the batch"): the outcome's `purge` becomes what
916
+ * actually happened (`deferred` when the shared budget was empty, `failed`).
917
+ */
918
+ async recordPurge(
919
+ id ,
920
+ purge ,
921
+ ) {
922
+ await this.#sql.run(
923
+ "UPDATE releases SET outcome = json_set(outcome, '$.purge', ?) WHERE id = ? AND state = 'published'",
924
+ [purge, id],
925
+ );
926
+ }
927
+
928
+ /** The purge plan computed when the release was pinned (§6.1 step 5), if any. */
929
+ async releasePurgePlan(id ) {
930
+ const row = await this.#sql.get (
931
+ "SELECT purge_plan FROM releases WHERE id = ?",
932
+ [id],
933
+ );
934
+ return row?.purge_plan ? (JSON.parse(row.purge_plan) ) : undefined;
935
+ }
936
+
937
+ async moveRelease(input
938
+
939
+
940
+
941
+
942
+
943
+ ) {
944
+ const res = await this.#sql.run(
945
+ `UPDATE releases SET execute_at = ?, rev = rev + 1, updated_at = ? WHERE id = ? AND site_id = ? AND rev = ? AND state = 'scheduled'`,
946
+ [canonicalInstant(input.at), input.now, input.releaseId, input.siteId, input.expectedRev],
947
+ );
948
+ return res.changes === 1;
949
+ }
950
+
951
+ // ───────────────────────────── automations ─────────────────────────────
952
+
953
+ /** A new `active` automation (people only, §11.2); its first run is the first occurrence from now. */
954
+ async createAutomation(input ) {
955
+ const now = this.#stamp();
956
+ validateRecurrence(input.recurrence, {
957
+ minIntervalMinutes: input.minIntervalMinutes ?? DEFAULT_MIN_INTERVAL_MINUTES,
958
+ });
959
+ const recurrence = {
960
+ start: input.recurrence.start,
961
+ timeZone: input.recurrence.timeZone,
962
+ ...(input.recurrence.rule !== undefined ? { rule: input.recurrence.rule } : {}),
963
+ preset: input.recurrence.preset ?? presetOf(input.recurrence.rule, input.recurrence.start),
964
+ };
965
+ const first = firstRunFrom(recurrence, now);
966
+ const automation = {
967
+ schemaVersion: 1,
968
+ id: input.id ?? newAutomationId(),
969
+ siteId: input.siteId,
970
+ name: input.name,
971
+ job: input.job,
972
+ recurrence,
973
+ state: first ? "active" : "ended",
974
+ consecutiveFailures: 0,
975
+ owner: input.owner,
976
+ ...(first ? { nextRunAt: first.at } : {}),
977
+ createdAt: now,
978
+ updatedAt: now,
979
+ rev: 1,
980
+ ...(input.metadata ? { metadata: input.metadata } : {}),
981
+ };
982
+ assertValid("automation", automation);
983
+ await this.#sql.run(
984
+ `INSERT INTO automations (id, site_id, name, job, key_id, start_local, time_zone, rule, preset, state, paused_reason, consecutive_failures,
985
+ owner_id, owner_name, next_run_at, cursor, lease_token, lease_until, metadata, rev, created_at, updated_at)
986
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, 0, ?, ?, ?, NULL, NULL, NULL, ?, 1, ?, ?)`,
987
+ [
988
+ automation.id,
989
+ automation.siteId,
990
+ automation.name,
991
+ JSON.stringify(automation.job),
992
+ automation.job.kind === "agent-task" ? automation.job.keyId : null,
993
+ recurrence.start,
994
+ recurrence.timeZone,
995
+ recurrence.rule ?? null,
996
+ recurrence.preset,
997
+ automation.state,
998
+ automation.owner.id,
999
+ automation.owner.name ?? null,
1000
+ automation.nextRunAt ?? null,
1001
+ j(automation.metadata),
1002
+ now,
1003
+ now,
1004
+ ],
1005
+ );
1006
+ return automation;
1007
+ }
1008
+
1009
+ async getAutomation(siteId , id ) {
1010
+ const row = await this.#sql.get (
1011
+ "SELECT * FROM automations WHERE id = ? AND site_id = ?",
1012
+ [id, siteId],
1013
+ );
1014
+ return row ? toAutomation(row) : undefined;
1015
+ }
1016
+
1017
+ async listAutomations(siteId ) {
1018
+ const rows = await this.#sql.all (
1019
+ "SELECT * FROM automations WHERE site_id = ? ORDER BY name, id",
1020
+ [siteId],
1021
+ );
1022
+ return rows.map(toAutomation);
1023
+ }
1024
+
1025
+ /**
1026
+ * Pause, resume, break or end an automation (§5.3) with a CAS on `rev`. Leaving `active` kills
1027
+ * its open runs; resuming resets the failure count and plans the next run from now.
1028
+ */
1029
+ async transitionAutomation(
1030
+ siteId ,
1031
+ id ,
1032
+ change
1033
+
1034
+
1035
+
1036
+ ,
1037
+ ) {
1038
+ const current = await this.getAutomation(siteId, id);
1039
+ if (!current) throw new ScheduleError("not_found", `automation ${id} not found`);
1040
+ if (current.rev !== change.expectedRev) throw new ScheduleConflictError("automation", id);
1041
+ assertAutomationTransition(current.state, change.to);
1042
+ const now = this.#stamp();
1043
+ const { pausedReason: _p, nextRunAt: _n, ...rest } = current;
1044
+ let nextRunAt = current.nextRunAt;
1045
+ let state = change.to;
1046
+ if (change.to === "active") {
1047
+ nextRunAt = firstRunFrom(current.recurrence, now)?.at;
1048
+ if (!nextRunAt) state = "ended";
1049
+ }
1050
+ if (state === "ended") nextRunAt = undefined;
1051
+ const pausedReason = state === "active" || state === "ended" ? undefined : change.pausedReason;
1052
+ if ((state === "paused" || state === "auto-paused" || state === "broken") && !pausedReason)
1053
+ throw new ScheduleError("invalid_transition", `a ${state} automation needs a pausedReason`);
1054
+ const next = {
1055
+ ...rest,
1056
+ state,
1057
+ ...(pausedReason ? { pausedReason } : {}),
1058
+ ...(change.to === "active" ? { consecutiveFailures: 0 } : {}),
1059
+ ...(nextRunAt ? { nextRunAt } : {}),
1060
+ rev: current.rev + 1,
1061
+ updatedAt: now,
1062
+ };
1063
+ assertValid("automation", next);
1064
+ const pre = "EXISTS (SELECT 1 FROM automations WHERE id = ? AND rev = ? AND state = ?)";
1065
+ const statements = [];
1066
+ if (current.state === "active" && state !== "active")
1067
+ statements.push({
1068
+ sql: `UPDATE schedule_runs SET state = 'killed', ended_at = ?, lease_until = NULL, rev = rev + 1, updated_at = ?
1069
+ WHERE subject_id = ? AND state IN ('due', 'ready', 'running') AND ${pre}`,
1070
+ params: [now, now, id, id, change.expectedRev, current.state],
1071
+ });
1072
+ statements.push({
1073
+ sql: `UPDATE automations SET state = ?, paused_reason = ?, consecutive_failures = ?, next_run_at = ?, cursor = CASE WHEN ? = 'active' THEN cursor ELSE NULL END,
1074
+ lease_token = NULL, lease_until = NULL, rev = rev + 1, updated_at = ? WHERE id = ? AND site_id = ? AND rev = ? AND state = ?`,
1075
+ params: [
1076
+ next.state,
1077
+ next.pausedReason ?? null,
1078
+ next.consecutiveFailures,
1079
+ next.nextRunAt ?? null,
1080
+ next.state,
1081
+ now,
1082
+ id,
1083
+ siteId,
1084
+ change.expectedRev,
1085
+ current.state,
1086
+ ],
1087
+ });
1088
+ const results = await this.#sql.batch(statements);
1089
+ if ((results[results.length - 1]?.changes ?? 0) !== 1)
1090
+ throw new ScheduleConflictError("automation", id);
1091
+ return next;
1092
+ }
1093
+
1094
+ // ───────────────────────────── scheduler: automations ─────────────────────────────
1095
+
1096
+ async dueAutomations(now , limit ) {
1097
+ const rows = await this.#sql.all (
1098
+ `SELECT a.*, COALESCE(s.paused, 0) AS site_paused FROM automations a LEFT JOIN schedule_settings s ON s.site_id = a.site_id
1099
+ WHERE a.state = 'active' AND a.next_run_at <= ? ORDER BY a.next_run_at, a.id LIMIT ?`,
1100
+ [now, limit],
1101
+ );
1102
+ return rows.map((row) => {
1103
+ const cursor = cursorOf(row);
1104
+ return {
1105
+ automation: toAutomation(row),
1106
+ sitePaused: Number(row.site_paused) === 1,
1107
+ ...(cursor ? { cursor } : {}),
1108
+ ...(row.lease_until ? { leaseUntil: row.lease_until } : {}),
1109
+ };
1110
+ });
1111
+ }
1112
+
1113
+ async claimBuiltinRun(input
1114
+
1115
+
1116
+
1117
+
1118
+
1119
+
1120
+
1121
+
1122
+
1123
+
1124
+
1125
+ ) {
1126
+ const a = input.automation;
1127
+ const cond =
1128
+ "id = ? AND rev = ? AND state = 'active' AND (lease_until IS NULL OR lease_until <= ?)";
1129
+ const condParams = [a.id, a.rev, input.now];
1130
+ const pre = `EXISTS (SELECT 1 FROM automations WHERE ${cond})`;
1131
+ const statements = [];
1132
+ if (input.coalesced)
1133
+ statements.push({
1134
+ sql: `INSERT OR IGNORE INTO schedule_runs (${RUN_COLUMNS})
1135
+ SELECT ?, ?, 'builtin', ?, ?, 'skipped', NULL, ?, 1, NULL, NULL, NULL, NULL, NULL, ?, NULL, NULL, NULL, NULL, NULL, ?, NULL, NULL, NULL, 1, ?, ?
1136
+ WHERE ${pre}`,
1137
+ params: [
1138
+ input.coalesced.runId,
1139
+ a.siteId,
1140
+ a.id,
1141
+ canonicalInstant(input.coalesced.occurrenceAt),
1142
+ input.trigger,
1143
+ input.now,
1144
+ JSON.stringify({ coalesced: input.coalesced.count }),
1145
+ input.now,
1146
+ input.now,
1147
+ ...condParams,
1148
+ ],
1149
+ });
1150
+ if (!input.continuing)
1151
+ statements.push({
1152
+ sql: `INSERT OR IGNORE INTO schedule_runs (${RUN_COLUMNS})
1153
+ SELECT ?, ?, 'builtin', ?, ?, 'running', NULL, ?, ?, NULL, NULL, NULL, NULL, ?, NULL, ?, ?, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, ?, ?
1154
+ WHERE ${pre}`,
1155
+ params: [
1156
+ input.runId,
1157
+ a.siteId,
1158
+ a.id,
1159
+ canonicalInstant(input.occurrence.at),
1160
+ input.trigger,
1161
+ input.attempt,
1162
+ input.now,
1163
+ input.latenessSeconds,
1164
+ input.occurrence.adjusted ?? null,
1165
+ input.now,
1166
+ input.now,
1167
+ ...condParams,
1168
+ ],
1169
+ });
1170
+ statements.push({
1171
+ sql: `UPDATE automations SET lease_token = ?, lease_until = ?, rev = rev + 1, updated_at = ? WHERE ${cond}`,
1172
+ params: [input.token, input.leaseUntil, input.now, ...condParams],
1173
+ });
1174
+ const results = await this.#sql.batch(statements);
1175
+ return (results[results.length - 1]?.changes ?? 0) === 1;
1176
+ }
1177
+
1178
+ async finishBuiltinRun(
1179
+ input ,
1180
+ ) {
1181
+ const a = input.automation;
1182
+ const owned = "EXISTS (SELECT 1 FROM automations WHERE id = ? AND lease_token = ?)";
1183
+ if (!input.step.done) {
1184
+ const cursor = input.step.cursor;
1185
+ if (!cursor.taint) {
1186
+ const res = await this.#sql.run(
1187
+ `UPDATE automations SET cursor = ?, lease_token = NULL, lease_until = NULL, rev = rev + 1, updated_at = ? WHERE id = ? AND lease_token = ?`,
1188
+ [JSON.stringify(cursor), input.now, a.id, input.token],
1189
+ );
1190
+ return res.changes === 1;
1191
+ }
1192
+ // A step that read untrusted text marks the running run at once (§11.4), not only at its end.
1193
+ const results = await this.#sql.batch([
1194
+ {
1195
+ sql: `UPDATE schedule_runs SET taint = COALESCE(taint, ?), rev = rev + 1, updated_at = ?
1196
+ WHERE id = ? AND state = 'running' AND ${owned}`,
1197
+ params: [JSON.stringify(cursor.taint), input.now, input.runId, a.id, input.token],
1198
+ },
1199
+ {
1200
+ sql: `UPDATE automations SET cursor = ?, lease_token = NULL, lease_until = NULL, rev = rev + 1, updated_at = ? WHERE id = ? AND lease_token = ?`,
1201
+ params: [JSON.stringify(cursor), input.now, a.id, input.token],
1202
+ },
1203
+ ]);
1204
+ return (results[1]?.changes ?? 0) === 1;
1205
+ }
1206
+ const step = input.step;
1207
+ const nextState = step.pause ? step.pause.state : step.nextRunAt ? "active" : "ended";
1208
+ const results = await this.#sql.batch([
1209
+ {
1210
+ sql: `UPDATE schedule_runs SET state = ?, outcome = ?, summary = ?, counts = ?, findings = ?, error = ?, taint = COALESCE(taint, ?), ended_at = ?, rev = rev + 1, updated_at = ?
1211
+ WHERE id = ? AND state = 'running' AND ${owned}`,
1212
+ params: [
1213
+ step.run.state,
1214
+ step.run.outcome ?? null,
1215
+ step.run.summary ?? null,
1216
+ j(step.run.counts),
1217
+ j(step.run.findings),
1218
+ j(step.run.error),
1219
+ j(step.run.taint),
1220
+ input.now,
1221
+ input.now,
1222
+ input.runId,
1223
+ a.id,
1224
+ input.token,
1225
+ ],
1226
+ },
1227
+ {
1228
+ // A person may have paused it meanwhile: only an `active` automation changes state here.
1229
+ sql: `UPDATE automations SET cursor = NULL, lease_token = NULL, lease_until = NULL, next_run_at = ?, consecutive_failures = ?,
1230
+ state = CASE WHEN state = 'active' THEN ? ELSE state END,
1231
+ paused_reason = CASE WHEN state = 'active' THEN ? ELSE paused_reason END,
1232
+ rev = rev + 1, updated_at = ? WHERE id = ? AND lease_token = ?`,
1233
+ params: [
1234
+ step.nextRunAt ?? null,
1235
+ step.consecutiveFailures,
1236
+ nextState,
1237
+ step.pause?.pausedReason ?? null,
1238
+ input.now,
1239
+ a.id,
1240
+ input.token,
1241
+ ],
1242
+ },
1243
+ ]);
1244
+ return (results[1]?.changes ?? 0) === 1;
1245
+ }
1246
+
1247
+ async recordAgentOccurrence(
1248
+ input ,
1249
+ ) {
1250
+ const a = input.automation;
1251
+ const cond = "id = ? AND rev = ? AND state = 'active' AND next_run_at = ?";
1252
+ const condParams = [a.id, a.rev, a.nextRunAt ?? null];
1253
+ const nextState = input.pause ? input.pause.state : input.nextRunAt ? "active" : "ended";
1254
+ const results = await this.#sql.batch([
1255
+ {
1256
+ sql: `INSERT OR IGNORE INTO schedule_runs (${RUN_COLUMNS})
1257
+ SELECT ?, ?, 'agent-task', ?, ?, ?, NULL, ?, 1, NULL, NULL, ?, ?, NULL, ?, ?, ?, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, ?, ?
1258
+ WHERE EXISTS (SELECT 1 FROM automations WHERE ${cond})`,
1259
+ params: [
1260
+ input.runId,
1261
+ a.siteId,
1262
+ a.id,
1263
+ canonicalInstant(input.occurrence.at),
1264
+ input.state,
1265
+ input.trigger,
1266
+ input.window.opensAt,
1267
+ input.window.closesAt,
1268
+ input.state === "missed" ? input.now : null,
1269
+ input.latenessSeconds,
1270
+ input.occurrence.adjusted ?? null,
1271
+ input.now,
1272
+ input.now,
1273
+ ...condParams,
1274
+ ],
1275
+ },
1276
+ {
1277
+ sql: `UPDATE automations SET next_run_at = ?, consecutive_failures = ?, state = ?, paused_reason = ?, rev = rev + 1, updated_at = ? WHERE ${cond}`,
1278
+ params: [
1279
+ input.nextRunAt ?? null,
1280
+ input.consecutiveFailures,
1281
+ nextState,
1282
+ input.pause?.pausedReason ?? null,
1283
+ input.now,
1284
+ ...condParams,
1285
+ ],
1286
+ },
1287
+ ]);
1288
+ return (results[1]?.changes ?? 0) === 1;
1289
+ }
1290
+
1291
+ /**
1292
+ * `begin_run` (§11.2; the MCP tool is rollout step 10): the occurrence's `ready` row becomes
1293
+ * `running` while its window is open; `endsAt` is the run's lease. False when the window is not
1294
+ * open or another call began it (one run per occurrence).
1295
+ */
1296
+ async beginAgentRun(input
1297
+
1298
+
1299
+
1300
+
1301
+ ) {
1302
+ const res = await this.#sql.run(
1303
+ `UPDATE schedule_runs SET state = 'running', started_at = ?, lease_until = ?, usage = ?, rev = rev + 1, updated_at = ?
1304
+ WHERE id = ? AND site_id = ? AND state = 'ready' AND window_opens <= ? AND window_closes > ?`,
1305
+ [
1306
+ input.now,
1307
+ input.endsAt,
1308
+ JSON.stringify({ toolCalls: 0, writes: 0, approvalRequests: 0 }),
1309
+ input.now,
1310
+ input.runId,
1311
+ input.siteId,
1312
+ input.now,
1313
+ input.now,
1314
+ ],
1315
+ );
1316
+ return res.changes === 1;
1317
+ }
1318
+
1319
+ /** `end_run` (§11.2): `succeeded` with the agent's summary; the failure count resets. */
1320
+ async endAgentRun(input
1321
+
1322
+
1323
+
1324
+
1325
+
1326
+
1327
+ ) {
1328
+ const results = await this.#sql.batch([
1329
+ {
1330
+ sql: `UPDATE automations SET consecutive_failures = 0, rev = rev + 1, updated_at = ?
1331
+ WHERE id = (SELECT subject_id FROM schedule_runs WHERE id = ? AND site_id = ? AND state = 'running' AND subject_kind = 'agent-task')`,
1332
+ params: [input.now, input.runId, input.siteId],
1333
+ },
1334
+ {
1335
+ sql: `UPDATE schedule_runs SET state = 'succeeded', outcome = ?, summary = ?, usage = COALESCE(?, usage), ended_at = ?, lease_until = NULL, rev = rev + 1, updated_at = ?
1336
+ WHERE id = ? AND site_id = ? AND state = 'running' AND subject_kind = 'agent-task'`,
1337
+ params: [
1338
+ input.outcome,
1339
+ input.summary ?? null,
1340
+ j(input.usage),
1341
+ input.now,
1342
+ input.now,
1343
+ input.runId,
1344
+ input.siteId,
1345
+ ],
1346
+ },
1347
+ ]);
1348
+ return (results[1]?.changes ?? 0) === 1;
1349
+ }
1350
+
1351
+ async closeExpiredRuns(now ) {
1352
+ const expired = `SELECT subject_id FROM schedule_runs WHERE state IN ('ready', 'running') AND subject_kind = 'agent-task'
1353
+ AND ((state = 'ready' AND window_closes <= ?) OR (state = 'running' AND lease_until <= ?))`;
1354
+ const results = await this.#sql.batch([
1355
+ {
1356
+ sql: `UPDATE automations SET consecutive_failures = consecutive_failures + 1, rev = rev + 1, updated_at = ? WHERE id IN (${expired})`,
1357
+ params: [now, now, now],
1358
+ },
1359
+ {
1360
+ sql: `UPDATE automations SET state = 'auto-paused', paused_reason = 'failures', rev = rev + 1, updated_at = ?
1361
+ WHERE state = 'active' AND consecutive_failures >= ? AND id IN (${expired})`,
1362
+ params: [now, CONSECUTIVE_FAILURE_LIMIT, now, now],
1363
+ },
1364
+ {
1365
+ sql: `UPDATE schedule_runs SET state = 'missed', ended_at = ?, rev = rev + 1, updated_at = ?
1366
+ WHERE state IN ('ready', 'running') AND state = 'ready' AND subject_kind = 'agent-task' AND window_closes <= ?`,
1367
+ params: [now, now, now],
1368
+ },
1369
+ {
1370
+ sql: `UPDATE schedule_runs SET state = 'failed', error = '{"code":"not_ended"}', ended_at = ?, lease_until = NULL, rev = rev + 1, updated_at = ?
1371
+ WHERE state IN ('ready', 'running') AND state = 'running' AND subject_kind = 'agent-task' AND lease_until <= ?`,
1372
+ params: [now, now, now],
1373
+ },
1374
+ ]);
1375
+ return { missed: results[2]?.changes ?? 0, failed: results[3]?.changes ?? 0 };
1376
+ }
1377
+
1378
+ // ───────────────────────────── runs ─────────────────────────────
1379
+
1380
+ async getRun(siteId , id ) {
1381
+ const row = await this.#sql.get (
1382
+ "SELECT * FROM schedule_runs WHERE id = ? AND site_id = ?",
1383
+ [id, siteId],
1384
+ );
1385
+ return row ? toRun(row) : undefined;
1386
+ }
1387
+
1388
+ /** Newest first; by subject and state when given. */
1389
+ async listRuns(siteId , query = {}) {
1390
+ const where = ["site_id = ?"];
1391
+ const params = [siteId];
1392
+ if (query.subjectId) {
1393
+ where.push("subject_id = ?");
1394
+ params.push(query.subjectId);
1395
+ }
1396
+ if (query.states && query.states.length > 0) {
1397
+ where.push(`state IN (${query.states.map(() => "?").join(", ")})`);
1398
+ params.push(...query.states);
1399
+ }
1400
+ if (query.before) {
1401
+ where.push("created_at < ?");
1402
+ params.push(query.before);
1403
+ }
1404
+ params.push(Math.min(Math.max(query.limit ?? 50, 1), 200));
1405
+ const rows = await this.#sql.all (
1406
+ `SELECT * FROM schedule_runs WHERE ${where.join(" AND ")} ORDER BY created_at DESC, occurrence_at DESC, id LIMIT ?`,
1407
+ params,
1408
+ );
1409
+ return rows.map(toRun);
1410
+ }
1411
+
1412
+ /** A run's findings (Studio only, ≤ 200). */
1413
+ async runFindings(siteId , id ) {
1414
+ const row = await this.#sql.get (
1415
+ "SELECT findings FROM schedule_runs WHERE id = ? AND site_id = ?",
1416
+ [id, siteId],
1417
+ );
1418
+ return row?.findings ? (JSON.parse(row.findings) ) : [];
1419
+ }
1420
+
1421
+ /** A run's usage, counted from audit and approval rows (§11.5; no counter columns). */
1422
+ async runUsage(siteId , runId ) {
1423
+ const row = await this.#sql.get (
1424
+ `SELECT (SELECT COUNT(*) FROM audit WHERE run_id = ?) AS calls,
1425
+ (SELECT COUNT(*) FROM audit WHERE run_id = ? AND snapshot_id IS NOT NULL) AS writes,
1426
+ (SELECT COUNT(*) FROM approvals WHERE site_id = ? AND run_id = ?) AS requests`,
1427
+ [runId, runId, siteId, runId],
1428
+ );
1429
+ return {
1430
+ toolCalls: Number(row?.calls ?? 0),
1431
+ writes: Number(row?.writes ?? 0),
1432
+ approvalRequests: Number(row?.requests ?? 0),
1433
+ };
1434
+ }
1435
+
1436
+ /** Automation mutations (audit rows with a snapshot) on the site since midnight UTC (§11.5). */
1437
+ async automationWritesToday(siteId , now ) {
1438
+ const row = await this.#sql.get (
1439
+ `SELECT COUNT(*) AS n FROM audit WHERE site_id = ? AND at >= ? AND automation_id IS NOT NULL AND snapshot_id IS NOT NULL`,
1440
+ [siteId, utcDayStart(now)],
1441
+ );
1442
+ return Number(row?.n ?? 0);
1443
+ }
1444
+
1445
+ // ───────────────────────────── settings and the kill switch ─────────────────────────────
1446
+
1447
+ async settings(siteId ) {
1448
+ const row = await this.#sql.get
1449
+
1450
+
1451
+
1452
+
1453
+
1454
+
1455
+
1456
+
1457
+ ("SELECT * FROM schedule_settings WHERE site_id = ?", [siteId]);
1458
+ if (!row) return { siteId, paused: false, dailyWriteCap: DEFAULT_DAILY_WRITE_CAP, rev: 0 };
1459
+ return {
1460
+ siteId,
1461
+ paused: Number(row.paused) === 1,
1462
+ ...(row.paused_by ? { pausedBy: JSON.parse(row.paused_by) } : {}),
1463
+ ...(row.paused_at ? { pausedAt: row.paused_at } : {}),
1464
+ ...(row.paused_reason ? { pausedReason: row.paused_reason } : {}),
1465
+ dailyWriteCap: Number(row.daily_write_cap),
1466
+ rev: Number(row.rev),
1467
+ updatedAt: row.updated_at,
1468
+ updatedBy: JSON.parse(row.updated_by) ,
1469
+ };
1470
+ }
1471
+
1472
+ /**
1473
+ * Changes the kill switch or the daily cap (CAS on `rev`; 0 = no row yet). Pausing pauses every
1474
+ * `active` automation of the site (`kill-switch`) and kills open automation runs; due releases
1475
+ * wait (and become `missed` after an hour). Resuming resumes exactly the automations the switch
1476
+ * paused, planned from now.
1477
+ */
1478
+ async putSettings(
1479
+ siteId ,
1480
+ input ,
1481
+ options ,
1482
+ ) {
1483
+ const current = await this.settings(siteId);
1484
+ if (current.rev !== options.expectedRev) throw new ScheduleConflictError("settings", siteId);
1485
+ const cap = input.dailyWriteCap ?? current.dailyWriteCap;
1486
+ if (!Number.isInteger(cap) || cap < 0 || cap > 100_000)
1487
+ throw new ScheduleError(
1488
+ "invalid_settings",
1489
+ "dailyWriteCap must be an integer from 0 to 100000",
1490
+ );
1491
+ const now = this.#stamp();
1492
+ const paused = input.paused ?? current.paused;
1493
+ const pausing = paused && !current.paused;
1494
+ const resuming = !paused && current.paused;
1495
+ const next = {
1496
+ siteId,
1497
+ paused,
1498
+ ...(paused
1499
+ ? pausing
1500
+ ? {
1501
+ pausedBy: options.by,
1502
+ pausedAt: now,
1503
+ ...(input.reason ? { pausedReason: input.reason.slice(0, 500) } : {}),
1504
+ }
1505
+ : {
1506
+ ...(current.pausedBy ? { pausedBy: current.pausedBy } : {}),
1507
+ ...(current.pausedAt ? { pausedAt: current.pausedAt } : {}),
1508
+ ...(current.pausedReason ? { pausedReason: current.pausedReason } : {}),
1509
+ }
1510
+ : {}),
1511
+ dailyWriteCap: cap,
1512
+ rev: current.rev + 1,
1513
+ updatedAt: now,
1514
+ updatedBy: options.by,
1515
+ };
1516
+ const pre =
1517
+ current.rev === 0
1518
+ ? "NOT EXISTS (SELECT 1 FROM schedule_settings WHERE site_id = ?)"
1519
+ : "EXISTS (SELECT 1 FROM schedule_settings WHERE site_id = ? AND rev = ?)";
1520
+ const preParams = current.rev === 0 ? [siteId] : [siteId, current.rev];
1521
+ const statements = [];
1522
+ if (pausing) {
1523
+ statements.push(
1524
+ {
1525
+ sql: `UPDATE schedule_runs SET state = 'killed', ended_at = ?, lease_until = NULL, rev = rev + 1, updated_at = ?
1526
+ WHERE site_id = ? AND subject_kind IN ('builtin', 'agent-task') AND state IN ('due', 'ready', 'running') AND ${pre}`,
1527
+ params: [now, now, siteId, ...preParams],
1528
+ },
1529
+ {
1530
+ sql: `UPDATE automations SET state = 'paused', paused_reason = 'kill-switch', cursor = NULL, lease_token = NULL, lease_until = NULL, rev = rev + 1, updated_at = ?
1531
+ WHERE site_id = ? AND state = 'active' AND ${pre}`,
1532
+ params: [now, siteId, ...preParams],
1533
+ },
1534
+ );
1535
+ }
1536
+ if (resuming) {
1537
+ const rows = await this.#sql.all (
1538
+ "SELECT * FROM automations WHERE site_id = ? AND state = 'paused' AND paused_reason = 'kill-switch'",
1539
+ [siteId],
1540
+ );
1541
+ for (const row of rows) {
1542
+ const a = toAutomation(row);
1543
+ const first = firstRunFrom(a.recurrence, now);
1544
+ statements.push({
1545
+ sql: `UPDATE automations SET state = ?, paused_reason = NULL, next_run_at = ?, rev = rev + 1, updated_at = ?
1546
+ WHERE id = ? AND state = 'paused' AND paused_reason = 'kill-switch' AND ${pre}`,
1547
+ params: [first ? "active" : "ended", first?.at ?? null, now, a.id, ...preParams],
1548
+ });
1549
+ }
1550
+ }
1551
+ statements.push(
1552
+ current.rev === 0
1553
+ ? {
1554
+ sql: `INSERT INTO schedule_settings (site_id, paused, paused_by, paused_at, paused_reason, daily_write_cap, rev, updated_at, updated_by)
1555
+ SELECT ?, ?, ?, ?, ?, ?, 1, ?, ? WHERE ${pre}`,
1556
+ params: [
1557
+ siteId,
1558
+ paused ? 1 : 0,
1559
+ j(next.pausedBy),
1560
+ next.pausedAt ?? null,
1561
+ next.pausedReason ?? null,
1562
+ cap,
1563
+ now,
1564
+ JSON.stringify(options.by),
1565
+ ...preParams,
1566
+ ],
1567
+ }
1568
+ : {
1569
+ sql: `UPDATE schedule_settings SET paused = ?, paused_by = ?, paused_at = ?, paused_reason = ?, daily_write_cap = ?, rev = rev + 1, updated_at = ?, updated_by = ?
1570
+ WHERE site_id = ? AND rev = ?`,
1571
+ params: [
1572
+ paused ? 1 : 0,
1573
+ j(next.pausedBy),
1574
+ next.pausedAt ?? null,
1575
+ next.pausedReason ?? null,
1576
+ cap,
1577
+ now,
1578
+ JSON.stringify(options.by),
1579
+ siteId,
1580
+ current.rev,
1581
+ ],
1582
+ },
1583
+ );
1584
+ const results = await this.#sql.batch(statements);
1585
+ if ((results[results.length - 1]?.changes ?? 0) !== 1)
1586
+ throw new ScheduleConflictError("settings", siteId);
1587
+ return next;
1588
+ }
1589
+
1590
+ // ───────────────────────────── system jobs and heartbeat ─────────────────────────────
1591
+
1592
+ async ensureSystemJobs(jobs ) {
1593
+ if (jobs.length === 0) return;
1594
+ await this.#sql.run(
1595
+ `INSERT OR IGNORE INTO system_jobs (name, next_run_at) SELECT json_extract(value, '$.name'), json_extract(value, '$.next') FROM json_each(?)`,
1596
+ [JSON.stringify(jobs.map((x) => ({ name: x.name, next: canonicalInstant(x.nextRunAt) })))],
1597
+ );
1598
+ }
1599
+
1600
+ async systemJobs() {
1601
+ return (await this.#sql.all ("SELECT * FROM system_jobs ORDER BY name")).map(
1602
+ toSystemJob,
1603
+ );
1604
+ }
1605
+
1606
+ async dueSystemJobs(now ) {
1607
+ const rows = await this.#sql.all (
1608
+ "SELECT * FROM system_jobs WHERE next_run_at <= ? AND (lease_until IS NULL OR lease_until <= ?) ORDER BY next_run_at, name",
1609
+ [now, now],
1610
+ );
1611
+ return rows.map(toSystemJob);
1612
+ }
1613
+
1614
+ async claimSystemJob(input
1615
+
1616
+
1617
+
1618
+
1619
+ ) {
1620
+ const res = await this.#sql.run(
1621
+ `UPDATE system_jobs SET lease_token = ?, lease_until = ?, last_run_at = ?
1622
+ WHERE name = ? AND next_run_at <= ? AND (lease_until IS NULL OR lease_until <= ?)`,
1623
+ [input.token, input.leaseUntil, input.now, input.name, input.now, input.now],
1624
+ );
1625
+ return res.changes === 1;
1626
+ }
1627
+
1628
+ async finishSystemJob(input
1629
+
1630
+
1631
+
1632
+
1633
+
1634
+
1635
+ ) {
1636
+ const res = await this.#sql.run(
1637
+ `UPDATE system_jobs SET next_run_at = ?, lease_token = NULL, lease_until = NULL,
1638
+ last_ok_at = CASE WHEN ? = 1 THEN ? ELSE last_ok_at END, last_error = ?
1639
+ WHERE name = ? AND lease_token = ?`,
1640
+ [
1641
+ canonicalInstant(input.nextRunAt),
1642
+ input.ok ? 1 : 0,
1643
+ input.now,
1644
+ input.ok ? null : (input.error ?? "error"),
1645
+ input.name,
1646
+ input.token,
1647
+ ],
1648
+ );
1649
+ return res.changes === 1;
1650
+ }
1651
+
1652
+ async heartbeat() {
1653
+ return toHeartbeat(
1654
+ await this.#sql.get ("SELECT * FROM scheduler_heartbeat WHERE id = 1"),
1655
+ );
1656
+ }
1657
+
1658
+ async writeHeartbeat(h ) {
1659
+ await this.#sql.run(
1660
+ `INSERT INTO scheduler_heartbeat (id, at, trigger, next_wake_at, ran, more, lag_s) VALUES (1, ?, ?, ?, ?, ?, ?)
1661
+ ON CONFLICT(id) DO UPDATE SET at = excluded.at, trigger = excluded.trigger, next_wake_at = excluded.next_wake_at,
1662
+ ran = excluded.ran, more = excluded.more, lag_s = excluded.lag_s`,
1663
+ [h.at, h.trigger, h.nextWakeAt, h.ran, h.more ? 1 : 0, h.lagSeconds ?? null],
1664
+ );
1665
+ }
1666
+
1667
+ // ───────────────────────────── policy and API (rollout steps 7–8) ─────────────────────────────
1668
+
1669
+ /** The automation an agent key belongs to (§11.2: one key, one automation). */
1670
+ async automationByKey(keyId ) {
1671
+ const row = await this.#sql.get ("SELECT * FROM automations WHERE key_id = ?", [
1672
+ keyId,
1673
+ ]);
1674
+ return row ? toAutomation(row) : undefined;
1675
+ }
1676
+
1677
+ /** The automation's run that is `running` and has not reached its end (`lease_until`). */
1678
+ async openAgentRun(
1679
+ siteId ,
1680
+ automationId ,
1681
+ now ,
1682
+ ) {
1683
+ const row = await this.#sql.get (
1684
+ `SELECT * FROM schedule_runs WHERE site_id = ? AND subject_id = ? AND subject_kind = 'agent-task' AND state = 'running' AND lease_until > ?
1685
+ ORDER BY occurrence_at DESC LIMIT 1`,
1686
+ [siteId, automationId, canonicalInstant(now)],
1687
+ );
1688
+ return row ? toRun(row) : undefined;
1689
+ }
1690
+
1691
+ /** The automation's `ready` run whose window is open at `now` (§8.6: begin_run's target). */
1692
+ async readyAgentRun(
1693
+ siteId ,
1694
+ automationId ,
1695
+ now ,
1696
+ ) {
1697
+ const at = canonicalInstant(now);
1698
+ const row = await this.#sql.get (
1699
+ `SELECT * FROM schedule_runs WHERE site_id = ? AND subject_id = ? AND subject_kind = 'agent-task' AND state = 'ready'
1700
+ AND window_opens <= ? AND window_closes > ? ORDER BY occurrence_at DESC LIMIT 1`,
1701
+ [siteId, automationId, at, at],
1702
+ );
1703
+ return row ? toRun(row) : undefined;
1704
+ }
1705
+
1706
+ /**
1707
+ * Opens an agent task's window now ("Run now", §13), as the occurrence `now` (to the minute) with
1708
+ * trigger `manual`. False when that occurrence already has a run.
1709
+ */
1710
+ async openManualWindow(input
1711
+
1712
+
1713
+
1714
+ ) {
1715
+ const a = input.automation;
1716
+ const occurrenceAt = canonicalInstant(Math.floor(Date.parse(input.now) / 60_000) * 60_000);
1717
+ const id = await runId(a.id, occurrenceAt);
1718
+ const res = await this.#sql.run(
1719
+ `INSERT OR IGNORE INTO schedule_runs (${RUN_COLUMNS})
1720
+ SELECT ?, ?, 'agent-task', ?, ?, 'ready', NULL, 'manual', 1, NULL, NULL, ?, ?, NULL, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, ?, ?
1721
+ WHERE EXISTS (SELECT 1 FROM automations WHERE id = ? AND site_id = ? AND state = 'active')`,
1722
+ [
1723
+ id,
1724
+ a.siteId,
1725
+ a.id,
1726
+ occurrenceAt,
1727
+ input.window.opensAt,
1728
+ input.window.closesAt,
1729
+ input.now,
1730
+ input.now,
1731
+ a.id,
1732
+ a.siteId,
1733
+ ],
1734
+ );
1735
+ return res.changes === 1 ? id : undefined;
1736
+ }
1737
+
1738
+ /**
1739
+ * What one call inside a run leaves on it (§11.4, §11.5): the taint (kept once set), the anomaly
1740
+ * counters (`counts`) and the usage so far. Only while the run is `running`.
1741
+ */
1742
+ async recordRunCall(
1743
+ siteId ,
1744
+ id ,
1745
+ input
1746
+
1747
+
1748
+
1749
+
1750
+ ,
1751
+ ) {
1752
+ const res = await this.#sql.run(
1753
+ `UPDATE schedule_runs SET taint = COALESCE(taint, ?), counts = COALESCE(?, counts), usage = COALESCE(?, usage), rev = rev + 1, updated_at = ?
1754
+ WHERE id = ? AND site_id = ? AND state = 'running'`,
1755
+ [j(input.taint), j(input.counts), j(input.usage), input.now, id, siteId],
1756
+ );
1757
+ return res.changes === 1;
1758
+ }
1759
+
1760
+ /**
1761
+ * Ends a running agent run other than by `end_run` (§11.4, §11.5): `budget-exceeded`, `killed`
1762
+ * (anomaly), or `failed`. The automation's own state changes through `transitionAutomation`.
1763
+ */
1764
+ async endAgentRunAs(
1765
+ siteId ,
1766
+ id ,
1767
+ input
1768
+
1769
+
1770
+
1771
+
1772
+ ,
1773
+ ) {
1774
+ const res = await this.#sql.run(
1775
+ `UPDATE schedule_runs SET state = ?, error = ?, usage = COALESCE(?, usage), ended_at = ?, lease_until = NULL, rev = rev + 1, updated_at = ?
1776
+ WHERE id = ? AND site_id = ? AND state = 'running' AND subject_kind = 'agent-task'`,
1777
+ [
1778
+ input.state,
1779
+ JSON.stringify({
1780
+ code: input.error.code,
1781
+ ...(input.error.message ? { message: plainLine(input.error.message) } : {}),
1782
+ }),
1783
+ j(input.usage),
1784
+ input.now,
1785
+ input.now,
1786
+ id,
1787
+ siteId,
1788
+ ],
1789
+ );
1790
+ return res.changes === 1;
1791
+ }
1792
+
1793
+ /**
1794
+ * Changes an automation's name, job settings or recurrence (people, §13 PATCH) with a CAS on
1795
+ * `rev`. The next run is planned again from `now` when the recurrence changes; an agent task's
1796
+ * key never changes here.
1797
+ */
1798
+ async updateAutomation(
1799
+ siteId ,
1800
+ id ,
1801
+ change
1802
+
1803
+
1804
+
1805
+
1806
+
1807
+
1808
+
1809
+ ,
1810
+ ) {
1811
+ const current = await this.getAutomation(siteId, id);
1812
+ if (!current) throw new ScheduleError("not_found", `automation ${id} not found`);
1813
+ if (current.rev !== change.expectedRev) throw new ScheduleConflictError("automation", id);
1814
+ if (change.job && change.job.kind !== current.job.kind)
1815
+ throw new ScheduleError("invalid_transition", "an automation's job kind cannot change");
1816
+ if (
1817
+ change.job?.kind === "agent-task" &&
1818
+ current.job.kind === "agent-task" &&
1819
+ change.job.keyId !== current.job.keyId
1820
+ )
1821
+ throw new ScheduleError("invalid_transition", "an agent task keeps its key");
1822
+ const now = this.#stamp();
1823
+ let recurrence = current.recurrence;
1824
+ let nextRunAt = current.nextRunAt;
1825
+ if (change.recurrence) {
1826
+ validateRecurrence(change.recurrence, {
1827
+ minIntervalMinutes: change.minIntervalMinutes ?? DEFAULT_MIN_INTERVAL_MINUTES,
1828
+ });
1829
+ recurrence = {
1830
+ start: change.recurrence.start,
1831
+ timeZone: change.recurrence.timeZone,
1832
+ ...(change.recurrence.rule !== undefined ? { rule: change.recurrence.rule } : {}),
1833
+ preset:
1834
+ change.recurrence.preset ?? presetOf(change.recurrence.rule, change.recurrence.start),
1835
+ };
1836
+ nextRunAt = firstRunFrom(recurrence, now)?.at;
1837
+ }
1838
+ const { nextRunAt: _n, pausedReason, ...rest } = current;
1839
+ const ended = change.recurrence !== undefined && nextRunAt === undefined;
1840
+ const state = ended && current.state === "active" ? "ended" : current.state;
1841
+ const next = {
1842
+ ...rest,
1843
+ ...(change.name !== undefined ? { name: change.name } : {}),
1844
+ ...(change.job ? { job: change.job } : {}),
1845
+ recurrence,
1846
+ state,
1847
+ ...(pausedReason && state !== "ended" ? { pausedReason } : {}),
1848
+ ...(nextRunAt && !ended ? { nextRunAt } : {}),
1849
+ rev: current.rev + 1,
1850
+ updatedAt: now,
1851
+ };
1852
+ assertValid("automation", next);
1853
+ const res = await this.#sql.run(
1854
+ `UPDATE automations SET name = ?, job = ?, start_local = ?, time_zone = ?, rule = ?, preset = ?, state = ?, paused_reason = ?, next_run_at = ?,
1855
+ cursor = CASE WHEN ? THEN NULL ELSE cursor END, rev = rev + 1, updated_at = ?
1856
+ WHERE id = ? AND site_id = ? AND rev = ?`,
1857
+ [
1858
+ next.name,
1859
+ JSON.stringify(next.job),
1860
+ next.recurrence.start,
1861
+ next.recurrence.timeZone,
1862
+ next.recurrence.rule ?? null,
1863
+ next.recurrence.preset,
1864
+ next.state,
1865
+ next.pausedReason ?? null,
1866
+ next.nextRunAt ?? null,
1867
+ change.recurrence ? 1 : 0,
1868
+ now,
1869
+ id,
1870
+ siteId,
1871
+ change.expectedRev,
1872
+ ],
1873
+ );
1874
+ if (res.changes !== 1) throw new ScheduleConflictError("automation", id);
1875
+ return next;
1876
+ }
1877
+
1878
+ /**
1879
+ * Deletes an automation (§11.8): its open runs are killed first, in the same batch; the run rows
1880
+ * stay for history (retention removes them), the audit rows always.
1881
+ */
1882
+ async deleteAutomation(siteId , id , expectedRev ) {
1883
+ const now = this.#stamp();
1884
+ const pre = "EXISTS (SELECT 1 FROM automations WHERE id = ? AND site_id = ? AND rev = ?)";
1885
+ const results = await this.#sql.batch([
1886
+ {
1887
+ sql: `UPDATE schedule_runs SET state = 'killed', ended_at = ?, lease_until = NULL, rev = rev + 1, updated_at = ?
1888
+ WHERE subject_id = ? AND state IN ('due', 'ready', 'running') AND ${pre}`,
1889
+ params: [now, now, id, id, siteId, expectedRev],
1890
+ },
1891
+ {
1892
+ sql: "DELETE FROM automations WHERE id = ? AND site_id = ? AND rev = ?",
1893
+ params: [id, siteId, expectedRev],
1894
+ },
1895
+ ]);
1896
+ if ((results[1]?.changes ?? 0) !== 1) {
1897
+ if (!(await this.getAutomation(siteId, id)))
1898
+ throw new ScheduleError("not_found", `automation ${id} not found`);
1899
+ throw new ScheduleConflictError("automation", id);
1900
+ }
1901
+ }
1902
+
1903
+ /** Renames a release (CAS on `rev`); the title is not in `rl1:`, so approvals stand. */
1904
+ async retitleRelease(
1905
+ siteId ,
1906
+ id ,
1907
+ input ,
1908
+ ) {
1909
+ const rec = await this.getReleaseRecord(siteId, id);
1910
+ if (!rec) throw new ScheduleError("not_found", `release ${id} not found`);
1911
+ if (rec.release.rev !== input.expectedRev) throw new ScheduleConflictError("release", id);
1912
+ const now = this.#stamp();
1913
+ const { title: _t, ...rest } = rec.release;
1914
+ const next = {
1915
+ ...rest,
1916
+ ...(input.title ? { title: plainLine(input.title, 200) } : {}),
1917
+ rev: rec.release.rev + 1,
1918
+ updatedAt: now,
1919
+ };
1920
+ assertValid("release", next);
1921
+ const res = await this.#sql.run(
1922
+ "UPDATE releases SET title = ?, rev = rev + 1, updated_at = ? WHERE id = ? AND site_id = ? AND rev = ?",
1923
+ [next.title ?? null, now, id, siteId, input.expectedRev],
1924
+ );
1925
+ if (res.changes !== 1) throw new ScheduleConflictError("release", id);
1926
+ return next;
1927
+ }
1928
+
1929
+ /** Lateness (seconds) of release runs that ended since `since`, ascending (`/api/scheduler` p50/p95). */
1930
+ async releaseLateness(since , limit = 2_000) {
1931
+ const rows = await this.#sql.all (
1932
+ `SELECT lateness_s FROM schedule_runs WHERE subject_kind = 'release' AND state = 'succeeded' AND lateness_s IS NOT NULL AND created_at >= ?
1933
+ ORDER BY lateness_s LIMIT ?`,
1934
+ [canonicalInstant(since), limit],
1935
+ );
1936
+ return rows.map((r) => Number(r.lateness_s));
1937
+ }
1938
+
1939
+ // ───────────────────────────── built-in jobs ─────────────────────────────
1940
+
1941
+ /**
1942
+ * "Run now" for a built-in (§13): a run for this minute (`trigger: manual`) and a cursor that
1943
+ * points at it, with `nextRunAt` moved to now so the next tick steps it; when the run ends the
1944
+ * automation returns to its scheduled `nextRunAt`. One batch, a CAS on `rev`; undefined when the
1945
+ * automation is not active, a run is in progress, or this minute already has a run.
1946
+ */
1947
+ async startBuiltinNow(input
1948
+
1949
+
1950
+ ) {
1951
+ const a = input.automation;
1952
+ if (a.job.kind !== "builtin") return undefined;
1953
+ const now = canonicalInstant(input.now);
1954
+ const occurrenceAt = canonicalInstant(Math.floor(Date.parse(now) / 60_000) * 60_000);
1955
+ const id = await runId(a.id, occurrenceAt);
1956
+ const cursor = {
1957
+ runId: id,
1958
+ occurrenceAt,
1959
+ attempt: 1,
1960
+ manual: a.nextRunAt ? { nextRunAt: a.nextRunAt } : {},
1961
+ };
1962
+ const results = await this.#sql.batch([
1963
+ {
1964
+ sql: `UPDATE automations SET cursor = ?, next_run_at = ?, lease_token = NULL, lease_until = NULL, rev = rev + 1, updated_at = ?
1965
+ WHERE id = ? AND site_id = ? AND rev = ? AND state = 'active' AND cursor IS NULL
1966
+ AND (lease_until IS NULL OR lease_until <= ?)
1967
+ AND NOT EXISTS (SELECT 1 FROM schedule_runs WHERE id = ?)`,
1968
+ params: [JSON.stringify(cursor), occurrenceAt, now, a.id, a.siteId, a.rev, now, id],
1969
+ },
1970
+ {
1971
+ sql: `INSERT OR IGNORE INTO schedule_runs (${RUN_COLUMNS})
1972
+ SELECT ?, ?, 'builtin', ?, ?, 'running', NULL, 'manual', 1, NULL, NULL, NULL, NULL, ?, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 1, ?, ?
1973
+ WHERE EXISTS (SELECT 1 FROM automations WHERE id = ? AND json_extract(cursor, '$.runId') = ?)`,
1974
+ params: [id, a.siteId, a.id, occurrenceAt, now, now, now, a.id, id],
1975
+ },
1976
+ ]);
1977
+ return (results[1]?.changes ?? 0) === 1 ? id : undefined;
1978
+ }
1979
+
1980
+ /**
1981
+ * One bounded `cleanup` step for a site (§11.1, one batch): runs older than 90 days (their
1982
+ * findings with them) and terminal releases older than 400 days, at most `limit` of each;
1983
+ * finding lists over 200 trimmed; leases left on rows that no longer need them cleared (expired
1984
+ * automation leases, terminal releases and runs); and stale open rows closed — agent windows that
1985
+ * closed over an hour ago (`missed`), claims never started for a day (`missed`), built-in runs no
1986
+ * cursor continues any more (`failed`, `abandoned`). A `running` release keeps its lease: the
1987
+ * tick recovers it (§6.3).
1988
+ */
1989
+ async cleanupSite(
1990
+ siteId ,
1991
+ now ,
1992
+ options = {},
1993
+ ) {
1994
+ const t = Date.parse(canonicalInstant(now));
1995
+ const at = canonicalInstant(t);
1996
+ const runCutoff = canonicalInstant(t - (options.runDays ?? 90) * 86_400_000);
1997
+ const releaseCutoff = canonicalInstant(t - (options.releaseDays ?? 400) * 86_400_000);
1998
+ const hourAgo = canonicalInstant(t - 3_600_000);
1999
+ const dayAgo = canonicalInstant(t - 86_400_000);
2000
+ const limit = options.limit ?? 200;
2001
+ const max = options.maxFindings ?? 200;
2002
+ const old = `SELECT id FROM releases WHERE site_id = ? AND state IN (${TERMINAL_SQL}) AND updated_at < ? ORDER BY updated_at LIMIT ?`;
2003
+ const r = await this.#sql.batch([
2004
+ {
2005
+ sql: `DELETE FROM schedule_runs WHERE id IN (SELECT id FROM schedule_runs WHERE site_id = ? AND created_at < ? AND state NOT IN ('due', 'ready', 'running') ORDER BY created_at LIMIT ?)`,
2006
+ params: [siteId, runCutoff, limit],
2007
+ },
2008
+ {
2009
+ sql: `DELETE FROM release_items WHERE release_id IN (${old})`,
2010
+ params: [siteId, releaseCutoff, limit],
2011
+ },
2012
+ { sql: `DELETE FROM releases WHERE id IN (${old})`, params: [siteId, releaseCutoff, limit] },
2013
+ {
2014
+ sql: `UPDATE schedule_runs SET findings = (SELECT json_group_array(json(value)) FROM (SELECT value FROM json_each(schedule_runs.findings) LIMIT ?))
2015
+ WHERE site_id = ? AND findings IS NOT NULL AND json_array_length(findings) > ?`,
2016
+ params: [max, siteId, max],
2017
+ },
2018
+ {
2019
+ sql: `UPDATE automations SET lease_token = NULL, lease_until = NULL WHERE site_id = ? AND lease_until IS NOT NULL AND lease_until <= ?`,
2020
+ params: [siteId, at],
2021
+ },
2022
+ {
2023
+ sql: `UPDATE releases SET lease_token = NULL, lease_until = NULL WHERE site_id = ? AND state IN (${TERMINAL_SQL}) AND (lease_token IS NOT NULL OR lease_until IS NOT NULL)`,
2024
+ params: [siteId],
2025
+ },
2026
+ {
2027
+ sql: `UPDATE schedule_runs SET lease_token = NULL, lease_until = NULL WHERE site_id = ? AND state NOT IN ('due', 'ready', 'running') AND (lease_token IS NOT NULL OR lease_until IS NOT NULL)`,
2028
+ params: [siteId],
2029
+ },
2030
+ {
2031
+ sql: `UPDATE schedule_runs SET state = 'missed', ended_at = ?, rev = rev + 1, updated_at = ?
2032
+ WHERE site_id = ? AND subject_kind = 'agent-task' AND state = 'ready' AND window_closes <= ?`,
2033
+ params: [at, at, siteId, hourAgo],
2034
+ },
2035
+ {
2036
+ sql: `UPDATE schedule_runs SET state = 'missed', ended_at = ?, lease_token = NULL, lease_until = NULL, rev = rev + 1, updated_at = ?
2037
+ WHERE site_id = ? AND state = 'due' AND created_at <= ?`,
2038
+ params: [at, at, siteId, dayAgo],
2039
+ },
2040
+ {
2041
+ sql: `UPDATE schedule_runs SET state = 'failed', error = '{"code":"abandoned"}', ended_at = ?, rev = rev + 1, updated_at = ?
2042
+ WHERE site_id = ? AND subject_kind = 'builtin' AND state = 'running' AND COALESCE(started_at, created_at) <= ?
2043
+ AND NOT EXISTS (SELECT 1 FROM automations a WHERE a.id = schedule_runs.subject_id AND a.cursor IS NOT NULL
2044
+ AND json_extract(a.cursor, '$.runId') = schedule_runs.id)`,
2045
+ params: [at, at, siteId, dayAgo],
2046
+ },
2047
+ ]);
2048
+ const n = (i ) => r[i]?.changes ?? 0;
2049
+ const counts = {
2050
+ "runs-deleted": n(0),
2051
+ "releases-deleted": n(2),
2052
+ "findings-trimmed": n(3),
2053
+ "leases-cleared": n(4) + n(5) + n(6),
2054
+ "stale-runs-closed": n(7) + n(8) + n(9),
2055
+ };
2056
+ return { counts, more: n(0) >= limit || n(2) >= limit };
2057
+ }
2058
+
2059
+ /**
2060
+ * The schedule side of the weekly digest (§11.1), three reads: releases that went live, are due
2061
+ * next week, or ended badly this week; nodes in two pending releases; and the latest finished
2062
+ * run of each other built-in automation of the site, with its counts.
2063
+ */
2064
+ async digestData(
2065
+ siteId ,
2066
+ automationId ,
2067
+ window ,
2068
+ )
2069
+
2070
+
2071
+
2072
+
2073
+
2074
+
2075
+
2076
+
2077
+
2078
+
2079
+
2080
+
2081
+
2082
+
2083
+
2084
+ {
2085
+ const rows = await this.#sql.all
2086
+
2087
+
2088
+
2089
+
2090
+
2091
+ (
2092
+ `SELECT id, title, state, section, at FROM (
2093
+ SELECT id, title, state,
2094
+ CASE WHEN state = 'published' AND updated_at >= ? THEN 'published'
2095
+ WHEN state IN ('scheduled', 'awaiting_approval') AND execute_at >= ? AND execute_at < ? THEN 'scheduled'
2096
+ WHEN state IN ('missed', 'conflict', 'failed', 'expired') AND updated_at >= ? THEN 'attention'
2097
+ END AS section,
2098
+ CASE WHEN state IN ('scheduled', 'awaiting_approval') THEN execute_at
2099
+ ELSE COALESCE(json_extract(outcome, '$.at'), updated_at) END AS at
2100
+ FROM releases WHERE site_id = ? AND (updated_at >= ? OR (state IN ('scheduled', 'awaiting_approval') AND execute_at < ?)))
2101
+ WHERE section IS NOT NULL ORDER BY at, id LIMIT 1000`,
2102
+ [window.from, window.now, window.to, window.from, siteId, window.from, window.to],
2103
+ );
2104
+ const overlaps = [...(await this.overlaps(siteId)).values()].filter((r) => r.length > 1).length;
2105
+ const runs = await this.#sql.all
2106
+
2107
+
2108
+
2109
+
2110
+
2111
+ (
2112
+ `SELECT a.id, a.name, json_extract(a.job, '$.builtin') AS job, r.counts, r.ended_at
2113
+ FROM automations a JOIN schedule_runs r ON r.id = (
2114
+ SELECT id FROM schedule_runs WHERE subject_id = a.id AND state = 'succeeded' ORDER BY occurrence_at DESC LIMIT 1)
2115
+ WHERE a.site_id = ? AND a.id <> ? AND json_extract(a.job, '$.kind') = 'builtin'
2116
+ ORDER BY a.name, a.id`,
2117
+ [siteId, automationId],
2118
+ );
2119
+ return {
2120
+ releases: rows.map((x) => ({
2121
+ id: x.id,
2122
+ ...(x.title ? { title: x.title } : {}),
2123
+ state: x.state,
2124
+ section: x.section,
2125
+ at: x.at,
2126
+ })),
2127
+ overlaps,
2128
+ automations: runs.map((x) => ({
2129
+ id: x.id,
2130
+ name: x.name,
2131
+ job: x.job ?? "builtin",
2132
+ counts: x.counts ? (JSON.parse(x.counts) ) : {},
2133
+ ...(x.ended_at ? { endedAt: x.ended_at } : {}),
2134
+ })),
2135
+ };
2136
+ }
2137
+
2138
+ // ───────────────────────────── retention ─────────────────────────────
2139
+
2140
+ /**
2141
+ * `schedules.retention` (§5.2, §11.1): runs older than 90 days and terminal releases older than
2142
+ * 400 days are deleted, at most `limit` of each per call (audit rows stay).
2143
+ */
2144
+ async applyRetention(
2145
+ now ,
2146
+ options = {},
2147
+ ) {
2148
+ const t = Date.parse(canonicalInstant(now));
2149
+ const runCutoff = canonicalInstant(t - (options.runDays ?? 90) * 86_400_000);
2150
+ const releaseCutoff = canonicalInstant(t - (options.releaseDays ?? 400) * 86_400_000);
2151
+ const limit = options.limit ?? 500;
2152
+ const old = `SELECT id FROM releases WHERE state IN (${TERMINAL_SQL}) AND updated_at < ? ORDER BY updated_at LIMIT ?`;
2153
+ const results = await this.#sql.batch([
2154
+ {
2155
+ sql: `DELETE FROM schedule_runs WHERE id IN (SELECT id FROM schedule_runs WHERE created_at < ? AND state NOT IN ('due', 'ready', 'running') ORDER BY created_at LIMIT ?)`,
2156
+ params: [runCutoff, limit],
2157
+ },
2158
+ {
2159
+ sql: `DELETE FROM release_items WHERE release_id IN (${old})`,
2160
+ params: [releaseCutoff, limit],
2161
+ },
2162
+ { sql: `DELETE FROM releases WHERE id IN (${old})`, params: [releaseCutoff, limit] },
2163
+ ]);
2164
+ return { runs: results[0]?.changes ?? 0, releases: results[2]?.changes ?? 0 };
2165
+ }
2166
+ }