@cloudhal/schedules 0.6.1 → 0.6.3

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.
@@ -0,0 +1,1472 @@
1
+ /**
2
+ * Shared suites (RFC-0008 §16, §17), run from vitest files against better-sqlite3 and Miniflare D1
3
+ * like the storage, analytics and comments suites:
4
+ *
5
+ * - `describeScheduleStoreConformance` — `SqlScheduleStore`: releases (create, the `rl1:` hash,
6
+ * transitions with CAS, re-pin, cancel, holds and overlaps, lazy expiry), automations (create,
7
+ * pause/resume with CAS), settings and the kill switch, usage counted from audit rows, system
8
+ * jobs, the heartbeat and retention. Every record read back is checked against its contract.
9
+ * - `describeSchedulerConformance` — `runDue` over the real store with fake work seams: releases on
10
+ * time and never early (S2), at most one effect under concurrent ticks on two stores sharing one
11
+ * database (S3), conflicts (S4), the hour limit and retries (S8), lease expiry and recovery, the
12
+ * kill switch, one release at a time per site in time order (D15), built-in steps and agent-task
13
+ * windows, watermarks, the heartbeat, and the statement count of every path within the Workers
14
+ * Free `TickBudget` (S17).
15
+ */
16
+
17
+ import { isValid } from "@cloudhal/core-contracts";
18
+
19
+ import { afterAll, beforeEach, describe, expect, it } from "vitest";
20
+ import { TICK_BUDGETS, TickMeter } from "./budget-meter.js";
21
+ import { ScheduleConflictError, ScheduleError } from "./errors.js";
22
+ import { newLeaseToken, runId } from "./ids.js";
23
+
24
+ import { presetRule } from "./recurrence.js";
25
+ import { releaseHash } from "./release.js";
26
+ import {
27
+
28
+
29
+
30
+ hourlyAt,
31
+
32
+
33
+
34
+
35
+ runDue,
36
+
37
+
38
+ } from "./scheduler.js";
39
+ import { SqlScheduleStore } from "./sql/store.js";
40
+
41
+
42
+
43
+
44
+
45
+
46
+
47
+
48
+
49
+ /** A driver that counts statements: every read, every write and every statement of a batch. */
50
+
51
+
52
+
53
+
54
+
55
+ export function countingDriver(inner ) {
56
+ const statements = [];
57
+ const note = (sql , params ) =>
58
+ statements.push({ sql, ...(params ? { params } : {}) });
59
+ return {
60
+ name: `counting(${inner.name})`,
61
+ statements,
62
+ get: (sql, params) => {
63
+ note(sql, params);
64
+ return inner.get(sql, params);
65
+ },
66
+ all: (sql, params) => {
67
+ note(sql, params);
68
+ return inner.all(sql, params);
69
+ },
70
+ run: (sql , params ) => {
71
+ note(sql, params);
72
+ return inner.run(sql, params);
73
+ },
74
+ batch: (list) => {
75
+ statements.push(...list);
76
+ return inner.batch(list);
77
+ },
78
+ exec: (sql) => inner.exec(sql),
79
+ close: () => inner.close(),
80
+ reset() {
81
+ statements.length = 0;
82
+ },
83
+ };
84
+ }
85
+
86
+ /** A `ReleaseExecutor` stand-in (the seam `publishRelease` fills in rollout step 5). */
87
+
88
+
89
+
90
+
91
+
92
+ export function fakeReleaseExecutor(
93
+ behavior ,
94
+ cost = 0,
95
+ ) {
96
+ const calls = [];
97
+ const fake = {
98
+ cost,
99
+ calls,
100
+ behavior:
101
+ behavior ??
102
+ ((i) => ({
103
+ kind: "published",
104
+ snapshotId: `snap_${i.run.id.slice(4, 24)}`,
105
+ baseSnapshotId: "snap_BASE000001",
106
+ purge: "tags",
107
+ committed: false,
108
+ })),
109
+ async execute(input) {
110
+ calls.push(input);
111
+ return fake.behavior(input);
112
+ },
113
+ };
114
+ return fake;
115
+ }
116
+
117
+ export function expectContractRelease(r ) {
118
+ expect(isValid("release", r), JSON.stringify(r)).toBe(true);
119
+ }
120
+ export function expectContractAutomation(a ) {
121
+ expect(isValid("automation", a), JSON.stringify(a)).toBe(true);
122
+ }
123
+ export function expectContractRun(r ) {
124
+ expect(isValid("schedule-run", r), JSON.stringify(r)).toBe(true);
125
+ }
126
+
127
+ const SITE = "site_conform01";
128
+ const OTHER_SITE = "site_conform02";
129
+ const T0 = "2026-10-12T10:00:00.000Z";
130
+ /** 09:00 in Istanbul on 2 November 2026. */
131
+ const T = "2026-11-02T06:00:00.000Z";
132
+ const TZ = "Europe/Istanbul";
133
+ const EDITOR = { kind: "human", id: "user_editor01", name: "Ayşe" };
134
+ const AGENT = { kind: "agent", id: "agent_desk0001", name: "Desk" };
135
+ const h = (c ) => c.repeat(64);
136
+ const plus = (at , ms ) => new Date(Date.parse(at) + ms).toISOString();
137
+ const MIN = 60_000;
138
+
139
+ function pinned(nodes , rev = 2) {
140
+ return nodes.map((nodeId, i) => ({
141
+ item: {
142
+ kind: "set",
143
+ nodeId,
144
+ nodeKind: "contentEntry",
145
+ target: { rev, hash: h(String((i + rev) % 10)) },
146
+ base: { rev: rev - 1, hash: h("a") },
147
+ },
148
+ deps: ["term_conform01"],
149
+ }));
150
+ }
151
+
152
+
153
+
154
+
155
+
156
+
157
+
158
+
159
+
160
+ async function count(
161
+ sql ,
162
+ table ,
163
+ where = "1 = 1",
164
+ params = [],
165
+ ) {
166
+ const r = await sql.get (
167
+ `SELECT COUNT(*) AS n FROM ${table} WHERE ${where}`,
168
+ params,
169
+ );
170
+ return Number(r?.n ?? 0);
171
+ }
172
+
173
+ async function setup(factory ) {
174
+ const sql = await factory.create();
175
+ const clock = { now: T0 };
176
+ return {
177
+ sql,
178
+ peer: factory.peer ? factory.peer(sql) : sql,
179
+ clock,
180
+ store: new SqlScheduleStore(sql, { now: () => new Date(clock.now) }),
181
+ exec: fakeReleaseExecutor(),
182
+ };
183
+ }
184
+
185
+ async function scheduledRelease(
186
+ ctx ,
187
+ o
188
+
189
+
190
+
191
+
192
+
193
+ = {},
194
+ ) {
195
+ const r = await ctx.store.createRelease({
196
+ siteId: o.siteId ?? SITE,
197
+ items: pinned(o.nodes ?? ["entry_conform01"]),
198
+ createdBy: AGENT,
199
+ title: "Election results",
200
+ });
201
+ return ctx.store.transitionRelease(r.siteId, r.id, {
202
+ expectedRev: r.rev,
203
+ to: "scheduled",
204
+ when: {
205
+ kind: "at",
206
+ at: o.at ?? T,
207
+ timeZone: TZ,
208
+ ...(o.localTime ? { localTime: o.localTime } : {}),
209
+ },
210
+ approval: o.approval ?? { kind: "person", by: { id: "user_editor01", name: "Ayşe" }, at: T0 },
211
+ });
212
+ }
213
+
214
+ /** One tick at `at`, metered with `budget` (Workers Free by default) over `driver`. */
215
+ async function tick(
216
+ ctx ,
217
+ at ,
218
+ o
219
+
220
+
221
+
222
+ = {},
223
+ ) {
224
+ const { driver, budget, withDriver, ...rest } = o;
225
+ const b = budget ?? TICK_BUDGETS.free;
226
+ const meter = new TickMeter(b, () => 0);
227
+ const metered = meter.wrap(driver ?? ctx.sql);
228
+ withDriver?.(metered);
229
+ const store = new SqlScheduleStore(metered, { now: () => new Date(at) });
230
+ return runDue(new Date(at), {
231
+ store,
232
+ meter,
233
+ trigger: "cron",
234
+ budget: b,
235
+ releases: ctx.exec,
236
+ wake: "minute",
237
+ ...rest,
238
+ });
239
+ }
240
+
241
+ function code(e ) {
242
+ return e instanceof ScheduleError
243
+ ? e.code
244
+ : e instanceof ScheduleConflictError
245
+ ? "conflict"
246
+ : undefined;
247
+ }
248
+
249
+ export function describeScheduleStoreConformance(
250
+ label ,
251
+ factory ,
252
+ ) {
253
+ describe(`schedule store conformance: ${label}`, { timeout: 120_000 }, () => {
254
+ let ctx ;
255
+ beforeEach(async () => {
256
+ ctx = await setup(factory);
257
+ });
258
+ afterAll(async () => {
259
+ await ctx?.sql.close();
260
+ await factory.dispose?.();
261
+ });
262
+
263
+ it("creates a draft release with its pinned items and the rl1: hash; reads it back as the contract", async () => {
264
+ const items = pinned(["entry_conform02", "entry_conform01"]);
265
+ const r = await ctx.store.createRelease({
266
+ siteId: SITE,
267
+ items,
268
+ createdBy: AGENT,
269
+ title: "Two articles",
270
+ });
271
+ expectContractRelease(r);
272
+ expect(r.state).toBe("draft");
273
+ expect(r.hash).toBe(
274
+ await releaseHash(
275
+ SITE,
276
+ items.map((i) => i.item),
277
+ ),
278
+ );
279
+ const rec = await ctx.store.getReleaseRecord(SITE, r.id);
280
+ expect(rec?.release).toEqual(r);
281
+ expect(rec?.items.map((i) => [i.item.nodeId, i.deps, i.held])).toEqual([
282
+ ["entry_conform01", ["term_conform01"], false],
283
+ ["entry_conform02", ["term_conform01"], false],
284
+ ]);
285
+ expect(await ctx.store.getRelease(OTHER_SITE, r.id)).toBeUndefined();
286
+ });
287
+
288
+ it("transitions with CAS: scheduled holds the nodes; stale revs and illegal moves are refused", async () => {
289
+ const r = await scheduledRelease(ctx);
290
+ expectContractRelease(r);
291
+ expect(r.state).toBe("scheduled");
292
+ expect([...(await ctx.store.heldNodes(SITE))]).toEqual([["entry_conform01", [r.id]]]);
293
+ await expect(
294
+ ctx.store.transitionRelease(SITE, r.id, { expectedRev: r.rev - 1, to: "draft" }),
295
+ ).rejects.toBeInstanceOf(ScheduleConflictError);
296
+ await expect(
297
+ ctx.store.transitionRelease(SITE, r.id, {
298
+ expectedRev: r.rev,
299
+ to: "published",
300
+ outcome: { kind: "missed", at: T, latenessSeconds: 0 },
301
+ }),
302
+ ).rejects.toBeInstanceOf(ScheduleError);
303
+ // A person moves it and keeps the approval (D4).
304
+ const moved = await ctx.store.transitionRelease(SITE, r.id, {
305
+ expectedRev: r.rev,
306
+ to: "scheduled",
307
+ when: { kind: "at", at: plus(T, 60 * MIN), timeZone: TZ },
308
+ });
309
+ expect(moved.approval).toEqual(r.approval);
310
+ expect(moved.hash).toBe(r.hash);
311
+ const canceled = await ctx.store.cancelRelease(SITE, r.id, {
312
+ expectedRev: moved.rev,
313
+ by: EDITOR,
314
+ });
315
+ expect(canceled.outcome).toMatchObject({ kind: "canceled", by: EDITOR });
316
+ expectContractRelease((await ctx.store.getRelease(SITE, r.id)) );
317
+ expect((await ctx.store.heldNodes(SITE)).size).toBe(0);
318
+ // Scheduled needs an approval.
319
+ const d = await ctx.store.createRelease({
320
+ siteId: SITE,
321
+ items: pinned(["entry_conform03"]),
322
+ createdBy: AGENT,
323
+ });
324
+ let err ;
325
+ try {
326
+ await ctx.store.transitionRelease(SITE, d.id, {
327
+ expectedRev: d.rev,
328
+ to: "scheduled",
329
+ when: { kind: "on-approval" },
330
+ });
331
+ } catch (e) {
332
+ err = e;
333
+ }
334
+ expect(code(err)).toBe("invalid_transition");
335
+ });
336
+
337
+ it("re-pinning changes the hash and voids the approval (S6); a lost CAS changes no item", async () => {
338
+ const r = await scheduledRelease(ctx, { nodes: ["entry_conform01", "entry_conform02"] });
339
+ const items = pinned(["entry_conform01"], 5);
340
+ const re = await ctx.store.repinRelease(SITE, r.id, { expectedRev: r.rev, items });
341
+ expect(re.state).toBe("awaiting_approval");
342
+ expect(re.approval).toBeUndefined();
343
+ expect(re.hash).not.toBe(r.hash);
344
+ expect(re.hash).toBe(
345
+ await releaseHash(
346
+ SITE,
347
+ items.map((i) => i.item),
348
+ ),
349
+ );
350
+ const rec = await ctx.store.getReleaseRecord(SITE, r.id);
351
+ expect(rec?.items.map((i) => [i.item.nodeId, i.held])).toEqual([["entry_conform01", true]]);
352
+ expectContractRelease(rec?.release );
353
+ await expect(
354
+ ctx.store.repinRelease(SITE, r.id, {
355
+ expectedRev: r.rev,
356
+ items: pinned(["entry_conform09"], 7),
357
+ }),
358
+ ).rejects.toBeInstanceOf(ScheduleConflictError);
359
+ expect(
360
+ (await ctx.store.getReleaseRecord(SITE, r.id))?.items.map((i) => i.item.nodeId),
361
+ ).toEqual(["entry_conform01"]);
362
+ });
363
+
364
+ it("flags a node in two pending releases (D15) and expires unapproved releases at their time (D5)", async () => {
365
+ const a = await scheduledRelease(ctx, { nodes: ["entry_conform01"] });
366
+ const b = await ctx.store.createRelease({
367
+ siteId: SITE,
368
+ items: pinned(["entry_conform01", "entry_conform02"]),
369
+ createdBy: AGENT,
370
+ });
371
+ expect([...(await ctx.store.overlaps(SITE))]).toEqual([
372
+ ["entry_conform01", [a.id, b.id].sort()],
373
+ ]);
374
+ const waiting = await ctx.store.transitionRelease(SITE, b.id, {
375
+ expectedRev: b.rev,
376
+ to: "awaiting_approval",
377
+ when: { kind: "at", at: T, timeZone: TZ },
378
+ requestId: "apr_conform01",
379
+ });
380
+ expect(waiting.state).toBe("awaiting_approval");
381
+ expect(await ctx.store.expireOverdueApprovals(SITE, plus(T, -MIN))).toBe(0);
382
+ expect(await ctx.store.expireOverdueApprovals(SITE, T)).toBe(1);
383
+ const expired = (await ctx.store.getRelease(SITE, b.id)) ;
384
+ expect(expired.state).toBe("expired");
385
+ expect(expired.outcome).toEqual({ kind: "expired", at: T, reason: "unapproved" });
386
+ expectContractRelease(expired);
387
+ expect([...(await ctx.store.heldNodes(SITE))]).toEqual([["entry_conform01", [a.id]]]);
388
+ expect(
389
+ (await ctx.store.listReleases(SITE, { states: ["expired"] })).map((r) => r.id),
390
+ ).toEqual([b.id]);
391
+ });
392
+
393
+ it("automations: created with their first run; pause/resume with CAS; too-frequent rules refused", async () => {
394
+ const a = await ctx.store.createAutomation({
395
+ siteId: SITE,
396
+ name: "Hourly broken-link sweep",
397
+ job: { kind: "builtin", builtin: "broken-links" },
398
+ recurrence: {
399
+ start: "2026-10-12T10:17",
400
+ timeZone: "UTC",
401
+ rule: presetRule("hourly", "2026-10-12T10:17"),
402
+ },
403
+ owner: { id: "user_editor01", name: "Ayşe" },
404
+ });
405
+ expectContractAutomation(a);
406
+ expect(a).toMatchObject({
407
+ state: "active",
408
+ nextRunAt: "2026-10-12T10:17:00.000Z",
409
+ recurrence: { preset: "hourly" },
410
+ });
411
+ ctx.clock.now = "2026-10-12T12:30:00.000Z";
412
+ const paused = await ctx.store.transitionAutomation(SITE, a.id, {
413
+ expectedRev: a.rev,
414
+ to: "paused",
415
+ pausedReason: "person",
416
+ });
417
+ expect(paused.pausedReason).toBe("person");
418
+ await expect(
419
+ ctx.store.transitionAutomation(SITE, a.id, { expectedRev: a.rev, to: "active" }),
420
+ ).rejects.toBeInstanceOf(ScheduleConflictError);
421
+ const resumed = await ctx.store.transitionAutomation(SITE, a.id, {
422
+ expectedRev: paused.rev,
423
+ to: "active",
424
+ });
425
+ expect(resumed).toMatchObject({
426
+ state: "active",
427
+ nextRunAt: "2026-10-12T13:17:00.000Z",
428
+ consecutiveFailures: 0,
429
+ });
430
+ expectContractAutomation((await ctx.store.getAutomation(SITE, a.id)) );
431
+ let err ;
432
+ try {
433
+ await ctx.store.createAutomation({
434
+ siteId: SITE,
435
+ name: "Too often",
436
+ job: { kind: "builtin", builtin: "feed-check" },
437
+ recurrence: {
438
+ start: "2026-10-12T10:00",
439
+ timeZone: "UTC",
440
+ rule: "FREQ=DAILY;BYMINUTE=0,30",
441
+ },
442
+ owner: { id: "user_editor01" },
443
+ });
444
+ } catch (e) {
445
+ err = e;
446
+ }
447
+ expect(code(err)).toBe("rule_too_frequent");
448
+ });
449
+
450
+ it("the kill switch pauses active automations and kills their open runs; resuming restores exactly those", async () => {
451
+ const mk = (name ) =>
452
+ ctx.store.createAutomation({
453
+ siteId: SITE,
454
+ name,
455
+ job: {
456
+ kind: "agent-task",
457
+ keyId: `key_${name}`,
458
+ instructions: "Triage new comments",
459
+ modeCap: "edits",
460
+ readsUntrustedText: true,
461
+ windowMinutes: 30,
462
+ budget: { maxToolCalls: 50, maxWrites: 0, maxApprovalRequests: 0, maxMinutes: 15 },
463
+ },
464
+ recurrence: {
465
+ start: "2026-10-12T10:07",
466
+ timeZone: "UTC",
467
+ rule: presetRule("hourly", "2026-10-12T10:07"),
468
+ },
469
+ owner: { id: "user_editor01" },
470
+ });
471
+ const a = await mk("triage1");
472
+ const b = await mk("triage2");
473
+ await ctx.store.transitionAutomation(SITE, b.id, {
474
+ expectedRev: b.rev,
475
+ to: "paused",
476
+ pausedReason: "person",
477
+ });
478
+ await tick(ctx, "2026-10-12T10:07:30.000Z");
479
+ expect(
480
+ await count(ctx.sql, "schedule_runs", "subject_id = ? AND state = 'ready'", [a.id]),
481
+ ).toBe(1);
482
+ const s = await ctx.store.putSettings(
483
+ SITE,
484
+ { paused: true, reason: "incident" },
485
+ { expectedRev: 0, by: EDITOR },
486
+ );
487
+ expect(s).toMatchObject({ paused: true, rev: 1, pausedBy: EDITOR, pausedReason: "incident" });
488
+ expect((await ctx.store.getAutomation(SITE, a.id))?.pausedReason).toBe("kill-switch");
489
+ expect(
490
+ await count(ctx.sql, "schedule_runs", "subject_id = ? AND state = 'killed'", [a.id]),
491
+ ).toBe(1);
492
+ await expect(
493
+ ctx.store.putSettings(SITE, { paused: false }, { expectedRev: 0, by: EDITOR }),
494
+ ).rejects.toBeInstanceOf(ScheduleConflictError);
495
+ ctx.clock.now = "2026-10-12T11:30:00.000Z";
496
+ await ctx.store.putSettings(SITE, { paused: false }, { expectedRev: 1, by: EDITOR });
497
+ expect(await ctx.store.getAutomation(SITE, a.id)).toMatchObject({
498
+ state: "active",
499
+ nextRunAt: "2026-10-12T12:07:00.000Z",
500
+ });
501
+ expect(await ctx.store.getAutomation(SITE, b.id)).toMatchObject({
502
+ state: "paused",
503
+ pausedReason: "person",
504
+ });
505
+ expect(await ctx.store.settings(OTHER_SITE)).toEqual({
506
+ siteId: OTHER_SITE,
507
+ paused: false,
508
+ dailyWriteCap: 200,
509
+ rev: 0,
510
+ });
511
+ });
512
+
513
+ it("usage and the daily cap are counted from audit and approval rows (no counters)", async () => {
514
+ const audit = (
515
+ site ,
516
+ run ,
517
+ aut ,
518
+ snap ,
519
+ at ,
520
+ ) => ({
521
+ sql: "INSERT INTO audit (at, actor_kind, actor_id, site_id, tool, decision, snapshot_id, run_id, automation_id) VALUES (?, 'agent', 'agent_desk0001', ?, 'update_entry', 'allow', ?, ?, ?)",
522
+ params: [at, site, snap, run, aut],
523
+ });
524
+ await ctx.sql.batch([
525
+ audit(SITE, "run_conform0001", "aut_conform01", null, "2026-10-12T09:00:00Z"),
526
+ audit(SITE, "run_conform0001", "aut_conform01", "snap_conform01", "2026-10-12T09:01:00Z"),
527
+ audit(SITE, "run_conform0002", "aut_conform01", "snap_conform02", "2026-10-11T23:59:59Z"),
528
+ audit(SITE, null, null, "snap_conform03", "2026-10-12T09:02:00Z"),
529
+ {
530
+ sql: "INSERT INTO approvals (id, site_id, tool, args_hash, actor_kind, actor_id, prompt, state_hash, status, created_at, expires_at, run_id) VALUES ('apr_conform01', ?, 'schedule_release', 'x', 'agent', 'agent_desk0001', 'p', 's', 'pending', 't', 't', 'run_conform0001')",
531
+ params: [SITE],
532
+ },
533
+ ]);
534
+ expect(await ctx.store.runUsage(SITE, "run_conform0001")).toEqual({
535
+ toolCalls: 2,
536
+ writes: 1,
537
+ approvalRequests: 1,
538
+ });
539
+ expect(await ctx.store.automationWritesToday(SITE, "2026-10-12T12:00:00Z")).toBe(1);
540
+ });
541
+
542
+ it("system jobs: registered once, claimed once, watermark moved; an expired lease is taken over", async () => {
543
+ await ctx.store.ensureSystemJobs([
544
+ { name: "comments.hourly", nextRunAt: "2026-10-12T10:17:00Z" },
545
+ ]);
546
+ await ctx.store.ensureSystemJobs([
547
+ { name: "comments.hourly", nextRunAt: "2026-10-12T23:17:00Z" },
548
+ ]);
549
+ expect(await ctx.store.systemJobs()).toEqual([
550
+ { name: "comments.hourly", nextRunAt: "2026-10-12T10:17:00.000Z" },
551
+ ]);
552
+ const now = "2026-10-12T10:17:05.000Z";
553
+ expect(await ctx.store.dueSystemJobs(now)).toHaveLength(1);
554
+ const t1 = newLeaseToken();
555
+ expect(
556
+ await ctx.store.claimSystemJob({
557
+ name: "comments.hourly",
558
+ token: t1,
559
+ now,
560
+ leaseUntil: plus(now, 10 * MIN),
561
+ }),
562
+ ).toBe(true);
563
+ expect(
564
+ await ctx.store.claimSystemJob({
565
+ name: "comments.hourly",
566
+ token: newLeaseToken(),
567
+ now,
568
+ leaseUntil: plus(now, 10 * MIN),
569
+ }),
570
+ ).toBe(false);
571
+ expect(await ctx.store.dueSystemJobs(now)).toHaveLength(0);
572
+ // The lease expires: another tick takes over; the first can no longer finish.
573
+ const later = plus(now, 11 * MIN);
574
+ const t2 = newLeaseToken();
575
+ expect(
576
+ await ctx.store.claimSystemJob({
577
+ name: "comments.hourly",
578
+ token: t2,
579
+ now: later,
580
+ leaseUntil: plus(later, 10 * MIN),
581
+ }),
582
+ ).toBe(true);
583
+ expect(
584
+ await ctx.store.finishSystemJob({
585
+ name: "comments.hourly",
586
+ token: t1,
587
+ now: later,
588
+ ok: true,
589
+ nextRunAt: "2026-10-12T11:17:00Z",
590
+ }),
591
+ ).toBe(false);
592
+ expect(
593
+ await ctx.store.finishSystemJob({
594
+ name: "comments.hourly",
595
+ token: t2,
596
+ now: later,
597
+ ok: true,
598
+ nextRunAt: "2026-10-12T11:17:00Z",
599
+ }),
600
+ ).toBe(true);
601
+ expect((await ctx.store.systemJobs())[0]).toEqual({
602
+ name: "comments.hourly",
603
+ nextRunAt: "2026-10-12T11:17:00.000Z",
604
+ lastRunAt: later,
605
+ lastOkAt: later,
606
+ });
607
+ });
608
+
609
+ it("the heartbeat is one row, upserted", async () => {
610
+ expect(await ctx.store.heartbeat()).toBeUndefined();
611
+ await ctx.store.writeHeartbeat({
612
+ at: T0,
613
+ trigger: "cron",
614
+ nextWakeAt: plus(T0, 5 * MIN),
615
+ ran: 0,
616
+ more: false,
617
+ });
618
+ await ctx.store.writeHeartbeat({
619
+ at: plus(T0, MIN),
620
+ trigger: "alarm",
621
+ nextWakeAt: plus(T0, 6 * MIN),
622
+ ran: 2,
623
+ more: true,
624
+ lagSeconds: 3,
625
+ });
626
+ expect(await ctx.store.heartbeat()).toEqual({
627
+ at: plus(T0, MIN),
628
+ trigger: "alarm",
629
+ nextWakeAt: plus(T0, 6 * MIN),
630
+ ran: 2,
631
+ more: true,
632
+ lagSeconds: 3,
633
+ });
634
+ expect(await count(ctx.sql, "scheduler_heartbeat")).toBe(1);
635
+ });
636
+
637
+ it("retention deletes old runs and old terminal releases only", async () => {
638
+ const r = await scheduledRelease(ctx);
639
+ await tick(ctx, T);
640
+ const keep = await scheduledRelease(ctx, {
641
+ nodes: ["entry_conform05"],
642
+ at: plus(T, 400 * 86_400_000),
643
+ });
644
+ expect((await ctx.store.getRelease(SITE, r.id))?.state).toBe("published");
645
+ expect(await ctx.store.applyRetention(plus(T, 89 * 86_400_000))).toEqual({
646
+ runs: 0,
647
+ releases: 0,
648
+ });
649
+ expect(await ctx.store.applyRetention(plus(T, 91 * 86_400_000))).toEqual({
650
+ runs: 1,
651
+ releases: 0,
652
+ });
653
+ expect(await ctx.store.applyRetention(plus(T, 401 * 86_400_000))).toEqual({
654
+ runs: 0,
655
+ releases: 1,
656
+ });
657
+ expect(await ctx.store.getRelease(SITE, r.id)).toBeUndefined();
658
+ expect(await count(ctx.sql, "release_items", "release_id = ?", [r.id])).toBe(0);
659
+ expect(await ctx.store.getRelease(SITE, keep.id)).toBeDefined();
660
+ });
661
+ });
662
+ }
663
+
664
+ /** Statement counts measured per path (filled while the scheduler suite runs; see the README). */
665
+ export const MEASURED_STATEMENTS = {};
666
+
667
+ export function describeSchedulerConformance(label , factory ) {
668
+ describe(`scheduler conformance (runDue): ${label}`, { timeout: 120_000 }, () => {
669
+ let ctx ;
670
+ beforeEach(async () => {
671
+ ctx = await setup(factory);
672
+ });
673
+ afterAll(async () => {
674
+ await ctx?.sql.close();
675
+ await factory.dispose?.();
676
+ });
677
+ const measure = (path , report ) => {
678
+ expect(report.statements, path).toBeLessThanOrEqual(TICK_BUDGETS.free.maxQueries);
679
+ MEASURED_STATEMENTS[path] = report.statements ?? -1;
680
+ return report.statements;
681
+ };
682
+
683
+ it("an idle tick is one read, plus the heartbeat every fifth minute (S17)", async () => {
684
+ expect(measure("idle tick, heartbeat due", await tick(ctx, T0))).toBe(2);
685
+ expect(measure("idle tick", await tick(ctx, plus(T0, MIN)))).toBe(1);
686
+ expect(await tick(ctx, plus(T0, 5 * MIN))).toMatchObject({
687
+ statements: 2,
688
+ ran: 0,
689
+ more: false,
690
+ });
691
+ expect(await ctx.store.heartbeat()).toMatchObject({
692
+ at: plus(T0, 5 * MIN),
693
+ trigger: "cron",
694
+ nextWakeAt: plus(T0, 10 * MIN),
695
+ });
696
+ });
697
+
698
+ it("publishes a release at its time and never before (S2); records the run", async () => {
699
+ const r = await scheduledRelease(ctx);
700
+ expect((await tick(ctx, plus(T, -1000))).ran).toBe(0);
701
+ expect(ctx.exec.calls).toHaveLength(0);
702
+ const report = await tick(ctx, plus(T, 41_000));
703
+ expect(measure("release published (executor not committing)", report)).toBe(9);
704
+ expect(report).toMatchObject({ ran: 1, late: 0, failed: 0, more: false });
705
+ expect(ctx.exec.calls).toHaveLength(1);
706
+ expect(ctx.exec.calls[0]).toMatchObject({
707
+ executeAt: T,
708
+ latenessSeconds: 41,
709
+ run: { attempt: 1, recovering: false },
710
+ });
711
+ const done = (await ctx.store.getRelease(SITE, r.id)) ;
712
+ expectContractRelease(done);
713
+ const run = await runId(r.id, T);
714
+ expect(done).toMatchObject({
715
+ state: "published",
716
+ outcome: { kind: "published", runId: run, latenessSeconds: 41, purge: "tags" },
717
+ });
718
+ const runs = await ctx.store.listRuns(SITE, { subjectId: r.id });
719
+ expect(runs).toHaveLength(1);
720
+ expectContractRun(runs[0] );
721
+ expect(runs[0]).toMatchObject({
722
+ id: run,
723
+ state: "succeeded",
724
+ outcome: "did-work",
725
+ trigger: "cron",
726
+ attempt: 1,
727
+ latenessSeconds: 41,
728
+ });
729
+ expect((await ctx.store.heldNodes(SITE)).size).toBe(0);
730
+ expect((await tick(ctx, plus(T, 2 * MIN))).ran).toBe(0);
731
+ expect(ctx.exec.calls).toHaveLength(1);
732
+ });
733
+
734
+ it("an executor that commits its own batch costs its reads and statements, within 40", async () => {
735
+ await scheduledRelease(ctx);
736
+ let sql = ctx.sql;
737
+ ctx.exec = fakeReleaseExecutor(async (i) => {
738
+ // What publishRelease will do (§6.3): four reads, then one batch — statements 1–4 and 8 of
739
+ // its own, statements 5–7 from the store, guarded on the site CAS.
740
+ const store = new SqlScheduleStore(sql);
741
+ await sql.get("SELECT 1");
742
+ await sql.get("SELECT 1");
743
+ await sql.get("SELECT 1");
744
+ await sql.get("SELECT 1");
745
+ await sql.batch([
746
+ { sql: "SELECT 1" },
747
+ { sql: "SELECT 1" },
748
+ { sql: "SELECT 1" },
749
+ { sql: "SELECT 1" },
750
+ { sql: "SELECT 1" },
751
+ ...store.releaseFinishStatements({
752
+ releaseId: i.release.id,
753
+ runId: i.run.id,
754
+ token: i.run.leaseToken,
755
+ now: i.now.toISOString(),
756
+ latenessSeconds: i.latenessSeconds,
757
+ finish: {
758
+ state: "published",
759
+ outcome: {
760
+ kind: "published",
761
+ runId: i.run.id,
762
+ at: i.now.toISOString(),
763
+ snapshotId: "snap_conform01",
764
+ baseSnapshotId: "snap_conform00",
765
+ latenessSeconds: i.latenessSeconds,
766
+ purge: "tags",
767
+ },
768
+ },
769
+ guard: { sql: "EXISTS (SELECT 1 FROM releases WHERE id = ?)", params: [i.release.id] },
770
+ }),
771
+ ]);
772
+ return {
773
+ kind: "published",
774
+ snapshotId: "snap_conform01",
775
+ baseSnapshotId: "snap_conform00",
776
+ purge: "tags",
777
+ committed: true,
778
+ };
779
+ }, 12);
780
+ // In production the executor's store runs over the tick's metered driver, as here.
781
+ const report = await tick(ctx, T, { withDriver: (d) => (sql = d) });
782
+ expect(report.ran).toBe(1);
783
+ expect(
784
+ measure("release published (publishRelease shape: 4 reads + 8-statement batch)", report),
785
+ ).toBe(18);
786
+ expect((await ctx.store.listRuns(SITE))[0]).toMatchObject({
787
+ state: "succeeded",
788
+ outcome: "did-work",
789
+ });
790
+ expect(
791
+ (await ctx.store.getRelease(SITE, (await ctx.store.listReleases(SITE))[0]?.id ))
792
+ ?.state,
793
+ ).toBe("published");
794
+ });
795
+
796
+ it("S3: two ticks on two stores over one database produce one effect", async () => {
797
+ const r = await scheduledRelease(ctx);
798
+ const [a, b] = await Promise.all([tick(ctx, T), tick(ctx, T, { driver: ctx.peer })]);
799
+ expect(a.ran + b.ran).toBe(1);
800
+ expect(ctx.exec.calls).toHaveLength(1);
801
+ expect(await count(ctx.sql, "schedule_runs", "subject_id = ?", [r.id])).toBe(1);
802
+ expect((await ctx.store.getRelease(SITE, r.id))?.state).toBe("published");
803
+ // Racing claims directly: exactly one wins.
804
+ const r2 = await scheduledRelease(ctx, { nodes: ["entry_conform07"], at: plus(T, MIN) });
805
+ const run = await runId(r2.id, plus(T, MIN));
806
+ const claim = (store ) =>
807
+ store.claimRelease({
808
+ siteId: SITE,
809
+ releaseId: r2.id,
810
+ expectedRev: r2.rev,
811
+ executeAt: plus(T, MIN),
812
+ runId: run,
813
+ token: newLeaseToken(),
814
+ now: plus(T, MIN),
815
+ leaseUntil: plus(T, 11 * MIN),
816
+ trigger: "cron",
817
+ latenessSeconds: 0,
818
+ });
819
+ const wins = await Promise.all([claim(ctx.store), claim(new SqlScheduleStore(ctx.peer))]);
820
+ expect(wins.filter(Boolean)).toHaveLength(1);
821
+ });
822
+
823
+ it("D15: one release at a time per site, in time order, even across concurrent ticks", async () => {
824
+ const first = await scheduledRelease(ctx, { nodes: ["entry_conform01"], at: T });
825
+ const second = await scheduledRelease(ctx, { nodes: ["entry_conform02"], at: plus(T, MIN) });
826
+ const other = await scheduledRelease(ctx, {
827
+ siteId: OTHER_SITE,
828
+ nodes: ["entry_conform03"],
829
+ at: T,
830
+ });
831
+ let running = 0;
832
+ let maxRunning = 0;
833
+ const order = [];
834
+ const runningInDb = [];
835
+ ctx.exec.behavior = async (i) => {
836
+ if (i.release.siteId === SITE) {
837
+ running++;
838
+ maxRunning = Math.max(maxRunning, running);
839
+ runningInDb.push(
840
+ await count(ctx.sql, "releases", "site_id = ? AND state = 'running'", [SITE]),
841
+ );
842
+ }
843
+ order.push(i.release.id);
844
+ await new Promise((resolve) => setTimeout(resolve, 5));
845
+ if (i.release.siteId === SITE) running--;
846
+ return {
847
+ kind: "published",
848
+ snapshotId: "snap_conform01",
849
+ baseSnapshotId: "snap_conform00",
850
+ purge: "none",
851
+ committed: false,
852
+ };
853
+ };
854
+ const paid = TICK_BUDGETS.paid;
855
+ await Promise.all([
856
+ tick(ctx, plus(T, 2 * MIN), { budget: paid }),
857
+ tick(ctx, plus(T, 2 * MIN), { budget: paid, driver: ctx.peer }),
858
+ ]);
859
+ await tick(ctx, plus(T, 3 * MIN), { budget: paid });
860
+ expect(maxRunning).toBe(1);
861
+ expect(runningInDb).toEqual([1, 1]);
862
+ expect(order.filter((id) => id !== other.id)).toEqual([first.id, second.id]);
863
+ for (const id of [first.id, second.id])
864
+ expect((await ctx.store.getRelease(SITE, id))?.state).toBe("published");
865
+ expect((await ctx.store.getRelease(OTHER_SITE, other.id))?.state).toBe("published");
866
+ });
867
+
868
+ it("S8: more than an hour late is missed, never published; within the hour it runs late", async () => {
869
+ const late = await scheduledRelease(ctx, { nodes: ["entry_conform01"], at: T });
870
+ const ok = await scheduledRelease(ctx, { nodes: ["entry_conform02"], at: plus(T, 30 * MIN) });
871
+ const report = await tick(ctx, plus(T, 61 * MIN));
872
+ expect(report).toMatchObject({ ran: 1, late: 2 });
873
+ const missed = (await ctx.store.getRelease(SITE, late.id)) ;
874
+ expectContractRelease(missed);
875
+ expect(missed).toMatchObject({
876
+ state: "missed",
877
+ outcome: { kind: "missed", latenessSeconds: 3660 },
878
+ });
879
+ expect((await ctx.store.listRuns(SITE, { subjectId: late.id }))[0]).toMatchObject({
880
+ state: "missed",
881
+ latenessSeconds: 3660,
882
+ });
883
+ expect(ctx.exec.calls.map((c) => c.release.id)).toEqual([ok.id]);
884
+ expect((await ctx.store.getRelease(SITE, ok.id))?.state).toBe("published");
885
+ const m = await scheduledRelease(ctx, { nodes: ["entry_conform04"], at: plus(T, 2 * MIN) });
886
+ ctx.exec.calls.length = 0;
887
+ expect(measure("release missed", await tick(ctx, plus(T, 63 * MIN)))).toBe(7);
888
+ expect((await ctx.store.getRelease(SITE, m.id))?.state).toBe("missed");
889
+ });
890
+
891
+ it("never early: a wall-clock release whose instant moved later waits for it (tzdata)", async () => {
892
+ // Stored at 05:00Z by older rules; today's tzdata puts 09:00 Istanbul at 06:00Z.
893
+ const r = await scheduledRelease(ctx, {
894
+ at: "2026-11-02T05:00:00.000Z",
895
+ localTime: "2026-11-02T09:00",
896
+ });
897
+ await tick(ctx, "2026-11-02T05:00:30.000Z");
898
+ expect(ctx.exec.calls).toHaveLength(0);
899
+ const moved = (await ctx.store.getRelease(SITE, r.id)) ;
900
+ expect(moved.state).toBe("scheduled");
901
+ expect(moved.when).toEqual({
902
+ kind: "at",
903
+ at: T,
904
+ timeZone: TZ,
905
+ localTime: "2026-11-02T09:00",
906
+ });
907
+ await tick(ctx, plus(T, 5000));
908
+ expect(ctx.exec.calls).toHaveLength(1);
909
+ });
910
+
911
+ it("expires releases whose approval is gone, lapsed or no longer matches the items", async () => {
912
+ const auto = await scheduledRelease(ctx, {
913
+ nodes: ["entry_conform01"],
914
+ approval: {
915
+ kind: "auto",
916
+ by: AGENT,
917
+ keyId: "key_conform01",
918
+ at: T0,
919
+ windowEnds: plus(T, -MIN),
920
+ },
921
+ });
922
+ const lost = await scheduledRelease(ctx, { nodes: ["entry_conform02"] });
923
+ const tampered = await scheduledRelease(ctx, { nodes: ["entry_conform03"] });
924
+ await ctx.sql.run("UPDATE release_items SET target_hash = ? WHERE release_id = ?", [
925
+ h("e"),
926
+ tampered.id,
927
+ ]);
928
+ await tick(ctx, T, {
929
+ budget: TICK_BUDGETS.paid,
930
+ checkApproval: (rel) =>
931
+ rel.id === lost.id ? { ok: false, reason: "approval_lost" } : { ok: true },
932
+ });
933
+ expect(ctx.exec.calls).toHaveLength(0);
934
+ for (const [id, reason] of [
935
+ [auto.id, "auto_window_ended"],
936
+ [lost.id, "approval_lost"],
937
+ [tampered.id, "approval_lost"],
938
+ ] ) {
939
+ const r = (await ctx.store.getRelease(SITE, id)) ;
940
+ expectContractRelease(r);
941
+ expect(r).toMatchObject({ state: "expired", outcome: { kind: "expired", reason } });
942
+ }
943
+ });
944
+
945
+ it("S4: a conflict holds the release with the changed nodes; a failure records its code", async () => {
946
+ const c = await scheduledRelease(ctx, { nodes: ["entry_conform01"] });
947
+ const f = await scheduledRelease(ctx, { nodes: ["entry_conform02"], at: plus(T, MIN) });
948
+ ctx.exec.behavior = (i) =>
949
+ i.release.id === c.id
950
+ ? {
951
+ kind: "conflict",
952
+ conflicts: [
953
+ {
954
+ nodeId: "entry_conform01",
955
+ expected: { rev: 1, hash: h("a") },
956
+ found: { rev: 3, hash: h("f") },
957
+ },
958
+ ],
959
+ }
960
+ : {
961
+ kind: "failed",
962
+ code: "dependency_missing",
963
+ message: "entry_conform02 needs term_conform01",
964
+ };
965
+ const report = await tick(ctx, plus(T, MIN), { budget: TICK_BUDGETS.paid });
966
+ expect(report.failed).toBe(1);
967
+ const conflict = (await ctx.store.getRelease(SITE, c.id)) ;
968
+ expectContractRelease(conflict);
969
+ expect(conflict.outcome).toMatchObject({
970
+ kind: "conflict",
971
+ conflicts: [{ nodeId: "entry_conform01" }],
972
+ });
973
+ expect((await ctx.store.listRuns(SITE, { subjectId: c.id }))[0]).toMatchObject({
974
+ state: "failed",
975
+ error: { code: "conflict" },
976
+ });
977
+ const failed = (await ctx.store.getRelease(SITE, f.id)) ;
978
+ expect(failed.outcome).toMatchObject({ kind: "failed", code: "dependency_missing" });
979
+ expect((await ctx.store.heldNodes(SITE)).size).toBe(0);
980
+ });
981
+
982
+ it("transient errors retry with back-off inside the hour; then the release is missed", async () => {
983
+ const r = await scheduledRelease(ctx);
984
+ let fail = 1;
985
+ ctx.exec.behavior = () =>
986
+ fail-- > 0
987
+ ? { kind: "retry", error: "D1_ERROR: network\nconnection lost" }
988
+ : {
989
+ kind: "published",
990
+ snapshotId: "snap_conform01",
991
+ baseSnapshotId: "snap_conform00",
992
+ purge: "tags",
993
+ committed: false,
994
+ };
995
+ await tick(ctx, T);
996
+ expect((await ctx.store.listRuns(SITE, { subjectId: r.id }))[0]).toMatchObject({
997
+ state: "running",
998
+ error: { code: "transient" },
999
+ });
1000
+ await tick(ctx, plus(T, 10_000));
1001
+ expect(ctx.exec.calls).toHaveLength(1);
1002
+ const report = await tick(ctx, plus(T, 31_000));
1003
+ expect(measure("release recovered after a transient error", report)).toBe(13);
1004
+ expect(ctx.exec.calls[1]).toMatchObject({ run: { attempt: 2, recovering: true } });
1005
+ expect((await ctx.store.getRelease(SITE, r.id))?.state).toBe("published");
1006
+ expectContractRun((await ctx.store.listRuns(SITE, { subjectId: r.id }))[0] );
1007
+ // Always transient: missed once retrying would pass the hour.
1008
+ const r2 = await scheduledRelease(ctx, { nodes: ["entry_conform02"], at: plus(T, 2 * MIN) });
1009
+ ctx.exec.behavior = () => ({ kind: "retry", error: "timeout" });
1010
+ await tick(ctx, plus(T, 61 * MIN + 30_000));
1011
+ expect((await ctx.store.getRelease(SITE, r2.id))?.state).toBe("running");
1012
+ await tick(ctx, plus(T, 63 * MIN));
1013
+ expect((await ctx.store.getRelease(SITE, r2.id))?.state).toBe("missed");
1014
+ });
1015
+
1016
+ it("a claim left by a crashed tick is recovered after its lease; past the hour it is missed", async () => {
1017
+ const r = await scheduledRelease(ctx);
1018
+ const run = await runId(r.id, T);
1019
+ expect(
1020
+ await ctx.store.claimRelease({
1021
+ siteId: SITE,
1022
+ releaseId: r.id,
1023
+ expectedRev: r.rev,
1024
+ executeAt: T,
1025
+ runId: run,
1026
+ token: newLeaseToken(),
1027
+ now: T,
1028
+ leaseUntil: plus(T, 10 * MIN),
1029
+ trigger: "alarm",
1030
+ latenessSeconds: 0,
1031
+ }),
1032
+ ).toBe(true);
1033
+ await tick(ctx, plus(T, 5 * MIN));
1034
+ expect(ctx.exec.calls).toHaveLength(0);
1035
+ const report = await tick(ctx, plus(T, 10 * MIN));
1036
+ expect(measure("release recovered after an expired lease", report)).toBe(13);
1037
+ expect(ctx.exec.calls[0]).toMatchObject({ run: { id: run, attempt: 2, recovering: true } });
1038
+ expect((await ctx.store.getRelease(SITE, r.id))?.state).toBe("published");
1039
+ const r2 = await scheduledRelease(ctx, { nodes: ["entry_conform02"], at: plus(T, MIN) });
1040
+ await ctx.store.claimRelease({
1041
+ siteId: SITE,
1042
+ releaseId: r2.id,
1043
+ expectedRev: r2.rev,
1044
+ executeAt: plus(T, MIN),
1045
+ runId: await runId(r2.id, plus(T, MIN)),
1046
+ token: newLeaseToken(),
1047
+ now: plus(T, MIN),
1048
+ leaseUntil: plus(T, 11 * MIN),
1049
+ trigger: "cron",
1050
+ latenessSeconds: 0,
1051
+ });
1052
+ await tick(ctx, plus(T, 62 * MIN));
1053
+ expect(ctx.exec.calls).toHaveLength(1);
1054
+ expect((await ctx.store.getRelease(SITE, r2.id))?.state).toBe("missed");
1055
+ });
1056
+
1057
+ it("the kill switch holds due releases; resumed within the hour they run, after it they are missed", async () => {
1058
+ const a = await scheduledRelease(ctx, { nodes: ["entry_conform01"] });
1059
+ await ctx.store.putSettings(SITE, { paused: true }, { expectedRev: 0, by: EDITOR });
1060
+ await tick(ctx, T);
1061
+ expect(ctx.exec.calls).toHaveLength(0);
1062
+ await ctx.store.putSettings(SITE, { paused: false }, { expectedRev: 1, by: EDITOR });
1063
+ await tick(ctx, plus(T, 30 * MIN));
1064
+ expect((await ctx.store.getRelease(SITE, a.id))?.state).toBe("published");
1065
+ const b = await scheduledRelease(ctx, { nodes: ["entry_conform02"], at: plus(T, 31 * MIN) });
1066
+ await ctx.store.putSettings(SITE, { paused: true }, { expectedRev: 2, by: EDITOR });
1067
+ await tick(ctx, plus(T, 60 * MIN));
1068
+ await tick(ctx, plus(T, 92 * MIN));
1069
+ expect((await ctx.store.getRelease(SITE, b.id))?.state).toBe("missed");
1070
+ expect(ctx.exec.calls).toHaveLength(1);
1071
+ });
1072
+
1073
+ it("a tick that cannot afford a release claims nothing and reports more", async () => {
1074
+ const r = await scheduledRelease(ctx);
1075
+ const report = await tick(ctx, T, {
1076
+ budget: { maxQueries: 4, maxReleases: 1, deadlineMs: 8000 },
1077
+ });
1078
+ expect(report.more).toBe(true);
1079
+ expect(report.statements).toBeLessThanOrEqual(4);
1080
+ expect((await ctx.store.getRelease(SITE, r.id))?.state).toBe("scheduled");
1081
+ expect(report.nextWakeAt).toBe(plus(T, 1000));
1082
+ });
1083
+
1084
+ it("built-in jobs: one bounded step per tick, the latest occurrence after downtime, three failures pause", async () => {
1085
+ const steps = [];
1086
+ let script = [
1087
+ {
1088
+ done: true,
1089
+ outcome: "did-work",
1090
+ counts: { "broken-links": 2 },
1091
+ summary: "2 broken links",
1092
+ findings: [{ path: "/a" }],
1093
+ },
1094
+ ];
1095
+ const builtins = {
1096
+ cost: 0,
1097
+ async step(input) {
1098
+ steps.push(input);
1099
+ const next = script.shift() ?? { done: true };
1100
+ if (next instanceof Error) throw next;
1101
+ return next;
1102
+ },
1103
+ };
1104
+ const a = await ctx.store.createAutomation({
1105
+ siteId: SITE,
1106
+ name: "Hourly broken-link sweep",
1107
+ job: { kind: "builtin", builtin: "broken-links" },
1108
+ recurrence: {
1109
+ start: "2026-10-12T10:17",
1110
+ timeZone: "UTC",
1111
+ rule: presetRule("hourly", "2026-10-12T10:17"),
1112
+ },
1113
+ owner: { id: "user_editor01" },
1114
+ });
1115
+ expect((await tick(ctx, "2026-10-12T10:16:00.000Z", { builtins })).ran).toBe(0);
1116
+ const r1 = await tick(ctx, "2026-10-12T10:17:20.000Z", { builtins });
1117
+ expect(measure("built-in step (done)", r1)).toBe(8);
1118
+ expect(r1.ran).toBe(1);
1119
+ const run1 = await runId(a.id, "2026-10-12T10:17:00.000Z");
1120
+ const got = (await ctx.store.getRun(SITE, run1)) ;
1121
+ expectContractRun(got);
1122
+ expect(got).toMatchObject({
1123
+ state: "succeeded",
1124
+ outcome: "did-work",
1125
+ counts: { "broken-links": 2 },
1126
+ summary: "2 broken links",
1127
+ latenessSeconds: 20,
1128
+ subject: { kind: "automation", job: "builtin" },
1129
+ });
1130
+ expect(await ctx.store.runFindings(SITE, run1)).toEqual([{ path: "/a" }]);
1131
+ expect(await ctx.store.getAutomation(SITE, a.id)).toMatchObject({
1132
+ nextRunAt: "2026-10-12T11:17:00.000Z",
1133
+ consecutiveFailures: 0,
1134
+ });
1135
+ // Five hours down: one skipped row for 11:17–14:17, one run at 15:17.
1136
+ script = [
1137
+ { done: false, position: { offset: 200 } },
1138
+ { done: true, outcome: "nothing-to-do" },
1139
+ ];
1140
+ const r2 = await tick(ctx, "2026-10-12T15:20:00.000Z", { builtins });
1141
+ expect(measure("built-in step (more to do) with coalesced occurrences", r2)).toBe(8);
1142
+ const skipped = (await ctx.store.getRun(
1143
+ SITE,
1144
+ await runId(a.id, "2026-10-12T11:17:00.000Z"),
1145
+ )) ;
1146
+ expectContractRun(skipped);
1147
+ expect(skipped).toMatchObject({ state: "skipped", counts: { coalesced: 4 } });
1148
+ const run2 = await runId(a.id, "2026-10-12T15:17:00.000Z");
1149
+ expect(await ctx.store.getRun(SITE, run2)).toMatchObject({ state: "running" });
1150
+ // The next tick continues the same run from its position.
1151
+ await tick(ctx, "2026-10-12T15:21:00.000Z", { builtins });
1152
+ expect(steps[steps.length - 1]).toMatchObject({
1153
+ run: { id: run2 },
1154
+ position: { offset: 200 },
1155
+ });
1156
+ expect(await ctx.store.getRun(SITE, run2)).toMatchObject({
1157
+ state: "succeeded",
1158
+ outcome: "nothing-to-do",
1159
+ });
1160
+ expect(await count(ctx.sql, "schedule_runs", "subject_id = ?", [a.id])).toBe(3);
1161
+ // Three failures in a row pause it.
1162
+ script = [new Error("boom\u0007"), new Error("boom"), new Error("boom")];
1163
+ for (const at of [
1164
+ "2026-10-12T16:17:01.000Z",
1165
+ "2026-10-12T17:17:01.000Z",
1166
+ "2026-10-12T18:17:01.000Z",
1167
+ ])
1168
+ await tick(ctx, at, { builtins });
1169
+ const paused = (await ctx.store.getAutomation(SITE, a.id)) ;
1170
+ expectContractAutomation(paused);
1171
+ expect(paused).toMatchObject({
1172
+ state: "auto-paused",
1173
+ pausedReason: "failures",
1174
+ consecutiveFailures: 3,
1175
+ });
1176
+ const failed = (await ctx.store.getRun(
1177
+ SITE,
1178
+ await runId(a.id, "2026-10-12T16:17:00.000Z"),
1179
+ )) ;
1180
+ expectContractRun(failed);
1181
+ expect(failed.error).toEqual({ code: "job_error", message: "boom " });
1182
+ });
1183
+
1184
+ it("built-in runs (step 9): taint marked as it happens, statements accounted, notifications after the end, Run now", async () => {
1185
+ const notices = [];
1186
+ const notify = { notify: async (n) => void notices.push(n) };
1187
+ let script = [];
1188
+ let metered ;
1189
+ const builtins = {
1190
+ cost: 2,
1191
+ costOf: () => 2,
1192
+ async step() {
1193
+ // a step's own statements count into the run's accounting
1194
+ await metered?.get("SELECT 1");
1195
+ await metered?.get("SELECT 1");
1196
+ const next = script.shift() ?? { done: true };
1197
+ if (next instanceof Error) throw next;
1198
+ return next;
1199
+ },
1200
+ };
1201
+ const go = (at ) =>
1202
+ tick(ctx, at, { builtins, notify, withDriver: (d) => (metered = d) });
1203
+ const a = await ctx.store.createAutomation({
1204
+ siteId: SITE,
1205
+ name: "Feed check",
1206
+ job: { kind: "builtin", builtin: "feed-check" },
1207
+ recurrence: {
1208
+ start: "2026-10-12T10:17",
1209
+ timeZone: "UTC",
1210
+ rule: presetRule("hourly", "2026-10-12T10:17"),
1211
+ },
1212
+ owner: { id: "user_editor01" },
1213
+ });
1214
+ const run = await runId(a.id, "2026-10-12T10:17:00.000Z");
1215
+ script = [
1216
+ {
1217
+ done: false,
1218
+ position: { phase: "sitemap" },
1219
+ taint: { at: "2026-10-12T10:17:05.000Z", tool: "feed_check" },
1220
+ },
1221
+ {
1222
+ done: true,
1223
+ outcome: "did-work",
1224
+ counts: { "feed-gated-node": 1 },
1225
+ summary: "1 problem",
1226
+ notify: [
1227
+ {
1228
+ id: `automation-findings:${run}`,
1229
+ kind: "automation-findings",
1230
+ siteId: SITE,
1231
+ automationId: a.id,
1232
+ automationName: a.name,
1233
+ runId: run,
1234
+ recipients: ["user_editor01"],
1235
+ at: "2026-10-12T10:18:05.000Z",
1236
+ },
1237
+ ],
1238
+ },
1239
+ ];
1240
+ const first = await go("2026-10-12T10:17:05.000Z");
1241
+ expect(measure("built-in step that taints (more to do)", first)).toBe(10);
1242
+ // the running run carries the taint at once (§11.4), the cursor the accounting
1243
+ expect(await ctx.store.getRun(SITE, run)).toMatchObject({
1244
+ state: "running",
1245
+ taint: { at: "2026-10-12T10:17:05.000Z", tool: "feed_check" },
1246
+ });
1247
+ expect(notices).toHaveLength(0);
1248
+ await go("2026-10-12T10:18:05.000Z");
1249
+ const done = (await ctx.store.getRun(SITE, run)) ;
1250
+ expectContractRun(done);
1251
+ expect(done).toMatchObject({
1252
+ state: "succeeded",
1253
+ taint: { tool: "feed_check" },
1254
+ counts: { steps: 2, statements: 4, "feed-gated-node": 1 },
1255
+ });
1256
+ expect(notices.map((n) => n.id)).toEqual([`automation-findings:${run}`]);
1257
+ // a failure notifies; the third in a row pauses and says so
1258
+ script = [new Error("down"), new Error("down"), new Error("down")];
1259
+ for (const at of [
1260
+ "2026-10-12T11:17:01.000Z",
1261
+ "2026-10-12T12:17:01.000Z",
1262
+ "2026-10-12T13:17:01.000Z",
1263
+ ])
1264
+ await go(at);
1265
+ expect(notices.map((n) => n.kind)).toEqual([
1266
+ "automation-findings",
1267
+ "automation-failed",
1268
+ "automation-failed",
1269
+ "automation-failed",
1270
+ "automation-paused",
1271
+ ]);
1272
+ // Run now (§13): a manual run for this minute, stepped by the next tick; then back on schedule
1273
+ const b = await ctx.store.createAutomation({
1274
+ siteId: SITE,
1275
+ name: "Digest",
1276
+ job: { kind: "builtin", builtin: "weekly-digest" },
1277
+ recurrence: {
1278
+ start: "2026-10-12T20:07",
1279
+ timeZone: "UTC",
1280
+ rule: presetRule("daily", "2026-10-12T20:07"),
1281
+ },
1282
+ owner: { id: "user_editor01" },
1283
+ });
1284
+ const manual = await ctx.store.startBuiltinNow({
1285
+ automation: b,
1286
+ now: "2026-10-12T14:00:30.000Z",
1287
+ });
1288
+ expect(manual).toBe(await runId(b.id, "2026-10-12T14:00:00.000Z"));
1289
+ expect(
1290
+ await ctx.store.startBuiltinNow({ automation: b, now: "2026-10-12T14:00:40.000Z" }),
1291
+ ).toBeUndefined();
1292
+ script = [{ done: true, outcome: "did-work" }];
1293
+ await go("2026-10-12T14:01:00.000Z");
1294
+ expect(await ctx.store.getRun(SITE, manual )).toMatchObject({
1295
+ state: "succeeded",
1296
+ trigger: "manual",
1297
+ });
1298
+ expect(await ctx.store.getAutomation(SITE, b.id)).toMatchObject({
1299
+ state: "active",
1300
+ nextRunAt: "2026-10-12T20:07:00.000Z",
1301
+ });
1302
+ });
1303
+
1304
+ it("agent tasks: windows recorded at the occurrence, begun once, closed as missed or failed", async () => {
1305
+ const a = await ctx.store.createAutomation({
1306
+ siteId: SITE,
1307
+ name: "Hourly comment triage",
1308
+ job: {
1309
+ kind: "agent-task",
1310
+ keyId: "key_conform01",
1311
+ instructions: "Label new comments",
1312
+ modeCap: "edits",
1313
+ readsUntrustedText: true,
1314
+ windowMinutes: 30,
1315
+ budget: { maxToolCalls: 50, maxWrites: 0, maxApprovalRequests: 0, maxMinutes: 15 },
1316
+ },
1317
+ recurrence: {
1318
+ start: "2026-10-12T10:07",
1319
+ timeZone: "UTC",
1320
+ rule: presetRule("hourly", "2026-10-12T10:07"),
1321
+ },
1322
+ owner: { id: "user_editor01" },
1323
+ });
1324
+ const r1 = await tick(ctx, "2026-10-12T10:07:10.000Z", { automationsEnabled: true });
1325
+ expect(measure("agent-task occurrence recorded", r1)).toBe(6);
1326
+ const run1 = await runId(a.id, "2026-10-12T10:07:00.000Z");
1327
+ const ready = (await ctx.store.getRun(SITE, run1)) ;
1328
+ expectContractRun(ready);
1329
+ expect(ready).toMatchObject({
1330
+ state: "ready",
1331
+ window: { opensAt: "2026-10-12T10:07:00.000Z", closesAt: "2026-10-12T10:37:00.000Z" },
1332
+ });
1333
+ expect((await ctx.store.getAutomation(SITE, a.id))?.nextRunAt).toBe(
1334
+ "2026-10-12T11:07:00.000Z",
1335
+ );
1336
+ expect(
1337
+ await ctx.store.beginAgentRun({
1338
+ siteId: SITE,
1339
+ runId: run1,
1340
+ now: "2026-10-12T10:10:00.000Z",
1341
+ endsAt: "2026-10-12T10:25:00.000Z",
1342
+ }),
1343
+ ).toBe(true);
1344
+ expect(
1345
+ await ctx.store.beginAgentRun({
1346
+ siteId: SITE,
1347
+ runId: run1,
1348
+ now: "2026-10-12T10:11:00.000Z",
1349
+ endsAt: "2026-10-12T10:26:00.000Z",
1350
+ }),
1351
+ ).toBe(false);
1352
+ expect(
1353
+ await ctx.store.endAgentRun({
1354
+ siteId: SITE,
1355
+ runId: run1,
1356
+ now: "2026-10-12T10:20:00.000Z",
1357
+ summary: "Labelled 4 comments",
1358
+ outcome: "did-work",
1359
+ }),
1360
+ ).toBe(true);
1361
+ expectContractRun((await ctx.store.getRun(SITE, run1)) );
1362
+ // 11:07 opens; nobody begins; the window closes → missed, a failure counted.
1363
+ await tick(ctx, "2026-10-12T11:07:05.000Z");
1364
+ const closing = await tick(ctx, "2026-10-12T11:37:05.000Z");
1365
+ expect(measure("agent-task window closed", closing)).toBe(8);
1366
+ expect(
1367
+ await ctx.store.getRun(SITE, await runId(a.id, "2026-10-12T11:07:00.000Z")),
1368
+ ).toMatchObject({ state: "missed" });
1369
+ expect((await ctx.store.getAutomation(SITE, a.id))?.consecutiveFailures).toBe(1);
1370
+ // 12:07 begun but never ended → failed at its end.
1371
+ await tick(ctx, "2026-10-12T12:07:05.000Z");
1372
+ const run3 = await runId(a.id, "2026-10-12T12:07:00.000Z");
1373
+ await ctx.store.beginAgentRun({
1374
+ siteId: SITE,
1375
+ runId: run3,
1376
+ now: "2026-10-12T12:08:00.000Z",
1377
+ endsAt: "2026-10-12T12:20:00.000Z",
1378
+ });
1379
+ await tick(ctx, "2026-10-12T12:21:00.000Z");
1380
+ const failed = (await ctx.store.getRun(SITE, run3)) ;
1381
+ expectContractRun(failed);
1382
+ expect(failed).toMatchObject({ state: "failed", error: { code: "not_ended" } });
1383
+ expect((await ctx.store.getAutomation(SITE, a.id))?.consecutiveFailures).toBe(2);
1384
+ // Downtime: only the latest window is recorded (already closed → missed); the third failure pauses.
1385
+ await tick(ctx, "2026-10-12T16:40:00.000Z");
1386
+ expect(await count(ctx.sql, "schedule_runs", "subject_id = ?", [a.id])).toBe(4);
1387
+ expect(await ctx.store.getAutomation(SITE, a.id)).toMatchObject({
1388
+ state: "auto-paused",
1389
+ pausedReason: "failures",
1390
+ });
1391
+ // CLOUDHAL_AUTOMATIONS=off: nothing happens for automations.
1392
+ const b = await ctx.store.createAutomation({
1393
+ siteId: OTHER_SITE,
1394
+ name: "Another",
1395
+ job: {
1396
+ kind: "agent-task",
1397
+ keyId: "key_conform02",
1398
+ instructions: "x",
1399
+ modeCap: "plan",
1400
+ readsUntrustedText: false,
1401
+ windowMinutes: 5,
1402
+ budget: { maxToolCalls: 1, maxWrites: 0, maxApprovalRequests: 0, maxMinutes: 1 },
1403
+ },
1404
+ recurrence: { start: "2026-10-12T17:00", timeZone: "UTC" },
1405
+ owner: { id: "user_editor01" },
1406
+ });
1407
+ await tick(ctx, "2026-10-12T17:00:30.000Z", { automationsEnabled: false });
1408
+ expect(await count(ctx.sql, "schedule_runs", "subject_id = ?", [b.id])).toBe(0);
1409
+ });
1410
+
1411
+ it("system jobs run behind their watermark, once across concurrent ticks", async () => {
1412
+ let runs = 0;
1413
+ let fail = false;
1414
+ const job = {
1415
+ name: "comments.hourly",
1416
+ cost: 2,
1417
+ next: hourlyAt(17),
1418
+ async run() {
1419
+ runs++;
1420
+ await new Promise((resolve) => setTimeout(resolve, 2));
1421
+ if (fail) throw new Error("rollup failed");
1422
+ },
1423
+ };
1424
+ const first = await tick(ctx, "2026-10-12T10:00:00.000Z", { systemJobs: [job] });
1425
+ expect(measure("first tick registering system jobs", first)).toBe(3);
1426
+ expect(runs).toBe(0);
1427
+ expect((await ctx.store.systemJobs())[0]?.nextRunAt).toBe("2026-10-12T10:17:00.000Z");
1428
+ const due = await tick(ctx, "2026-10-12T10:17:05.000Z", { systemJobs: [job] });
1429
+ expect(measure("system job run", due)).toBe(6);
1430
+ expect(runs).toBe(1);
1431
+ expect((await ctx.store.systemJobs())[0]).toMatchObject({
1432
+ nextRunAt: "2026-10-12T11:17:00.000Z",
1433
+ lastOkAt: "2026-10-12T10:17:05.000Z",
1434
+ });
1435
+ await Promise.all([
1436
+ tick(ctx, "2026-10-12T11:17:05.000Z", { systemJobs: [job] }),
1437
+ tick(ctx, "2026-10-12T11:17:05.000Z", { systemJobs: [job], driver: ctx.peer }),
1438
+ ]);
1439
+ expect(runs).toBe(2);
1440
+ fail = true;
1441
+ const failed = await tick(ctx, "2026-10-12T14:20:00.000Z", { systemJobs: [job] });
1442
+ expect(failed.failed).toBe(1);
1443
+ expect((await ctx.store.systemJobs())[0]).toMatchObject({
1444
+ nextRunAt: "2026-10-12T15:17:00.000Z",
1445
+ lastError: "rollup failed",
1446
+ });
1447
+ });
1448
+
1449
+ it("the heartbeat records the tick and the next wake; work forces a write", async () => {
1450
+ await tick(ctx, T0, { trigger: "alarm", wake: "computed" });
1451
+ expect(await ctx.store.heartbeat()).toMatchObject({
1452
+ at: T0,
1453
+ trigger: "alarm",
1454
+ nextWakeAt: plus(T0, 5 * MIN),
1455
+ ran: 0,
1456
+ });
1457
+ await scheduledRelease(ctx, { at: plus(T0, 2 * MIN) });
1458
+ const report = await tick(ctx, plus(T0, 2 * MIN + 1000), {
1459
+ trigger: "alarm",
1460
+ wake: "computed",
1461
+ });
1462
+ expect(report.ran).toBe(1);
1463
+ expect(await ctx.store.heartbeat()).toMatchObject({
1464
+ at: plus(T0, 2 * MIN + 1000),
1465
+ trigger: "alarm",
1466
+ ran: 1,
1467
+ more: false,
1468
+ lagSeconds: 1,
1469
+ });
1470
+ });
1471
+ });
1472
+ }