@niscorp/tide 0.1.11 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -7,14 +7,14 @@ var WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
7
7
  var HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
8
8
  var MMDD = /^(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/;
9
9
  var LOCAL_DATETIME = /^\d{4}-\d{2}-\d{2}T([01]\d|2[0-3]):[0-5]\d(:[0-5]\d)?$/;
10
- var knownZone = (tz) => {
10
+ var isKnownZone = (tz) => {
11
11
  try {
12
12
  return new Intl.DateTimeFormat("en-US", { timeZone: tz }).resolvedOptions().timeZone !== "";
13
13
  } catch {
14
14
  return false;
15
15
  }
16
16
  };
17
- var TimeZoneSchema = zod.z.string().refine(knownZone, { message: "not a time zone Intl knows" }).describe("IANA timezone name.");
17
+ var TimeZoneSchema = zod.z.string().refine(isKnownZone, { message: "not a time zone Intl knows" }).describe("IANA timezone name.");
18
18
  var ClockUnitSchema = zod.z.enum(["day", "week", "month", "year"]);
19
19
  var ClockRecurringSchema = zod.z.object({
20
20
  every: ClockUnitSchema.describe("The calendar period it repeats on. A repeating clock fires on every such period until the reflex is removed \u2014 only for a request that says it repeats."),
@@ -214,6 +214,119 @@ var draftSchemaOf = (choice = {}) => {
214
214
  };
215
215
  var ReflexDraftSchema = draftSchemaOf();
216
216
 
217
+ // src/engine/occurrence.ts
218
+ var DAY_MS = 864e5;
219
+ var MAX_DAYS_SCANNED = 3700;
220
+ var FORMATTERS = /* @__PURE__ */ new Map();
221
+ var formatterFor = (tz) => {
222
+ const cached = FORMATTERS.get(tz);
223
+ if (cached !== void 0) return cached;
224
+ const built = new Intl.DateTimeFormat("en-US", {
225
+ timeZone: tz,
226
+ hourCycle: "h23",
227
+ year: "numeric",
228
+ month: "2-digit",
229
+ day: "2-digit",
230
+ hour: "2-digit",
231
+ minute: "2-digit",
232
+ second: "2-digit"
233
+ });
234
+ FORMATTERS.set(tz, built);
235
+ return built;
236
+ };
237
+ var zonedParts = (instant, tz) => {
238
+ const parts = formatterFor(tz).formatToParts(new Date(instant));
239
+ const read = (type) => {
240
+ const found = parts.find((part) => part.type === type);
241
+ return found === void 0 ? 0 : Number(found.value);
242
+ };
243
+ return {
244
+ year: read("year"),
245
+ month: read("month"),
246
+ day: read("day"),
247
+ hour: read("hour"),
248
+ minute: read("minute"),
249
+ second: read("second")
250
+ };
251
+ };
252
+ var offsetAt = (instant, tz) => {
253
+ const parts = zonedParts(instant, tz);
254
+ const asIfUtc = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
255
+ return asIfUtc - Math.floor(instant / 1e3) * 1e3;
256
+ };
257
+ var rendersAs = (instant, tz, day, hour, minute) => {
258
+ const parts = zonedParts(instant, tz);
259
+ return parts.year === day.year && parts.month === day.month && parts.day === day.day && parts.hour === hour && parts.minute === minute;
260
+ };
261
+ var zonedToUtc = (day, hour, minute, tz) => {
262
+ const guess = Date.UTC(day.year, day.month - 1, day.day, hour, minute);
263
+ const before = offsetAt(guess - DAY_MS, tz);
264
+ const after = offsetAt(guess + DAY_MS, tz);
265
+ const candidates = before === after ? [guess - before] : [guess - before, guess - after];
266
+ const valid = candidates.filter((candidate) => rendersAs(candidate, tz, day, hour, minute));
267
+ return valid.length > 0 ? Math.min(...valid) : Math.max(...candidates);
268
+ };
269
+ var daysInMonth = (year, month) => new Date(Date.UTC(year, month, 0)).getUTCDate();
270
+ var weekdayOf = (day) => {
271
+ const index = new Date(Date.UTC(day.year, day.month - 1, day.day)).getUTCDay();
272
+ return WEEKDAYS[(index + 6) % 7] ?? "mon";
273
+ };
274
+ var splitInts = (value, separator) => value.split(separator).map((part) => Number(part));
275
+ var at2 = (values, index) => values[index] ?? 0;
276
+ var nextDay = (day) => {
277
+ const moved = new Date(Date.UTC(day.year, day.month - 1, day.day) + DAY_MS);
278
+ return { year: moved.getUTCFullYear(), month: moved.getUTCMonth() + 1, day: moved.getUTCDate() };
279
+ };
280
+ var ordinalOf = (day) => day.year * 1e4 + day.month * 100 + day.day;
281
+ var pad2 = (value) => String(value).padStart(2, "0");
282
+ var isDueOn = (clock, day) => {
283
+ if (clock.every === "day") return true;
284
+ if (clock.every === "week") return Array.isArray(clock.on) ? clock.on.some((one) => one === weekdayOf(day)) : weekdayOf(day) === clock.on;
285
+ if (clock.every === "month")
286
+ return typeof clock.on === "number" && day.day === Math.min(clock.on, daysInMonth(day.year, day.month));
287
+ if (typeof clock.on !== "string") return false;
288
+ const parts = splitInts(clock.on, "-");
289
+ const month = at2(parts, 0);
290
+ const dayOfMonth = at2(parts, 1);
291
+ return day.month === month && day.day === Math.min(dayOfMonth, daysInMonth(day.year, month));
292
+ };
293
+ var occurrenceKey = (clock, day) => {
294
+ if (clock.every === "year") return String(day.year);
295
+ if (clock.every === "month") return `${day.year}-${pad2(day.month)}`;
296
+ return `${day.year}-${pad2(day.month)}-${pad2(day.day)}`;
297
+ };
298
+ var occurrencesBetween = (clock, after, through, cap) => {
299
+ if (through <= after || cap <= 0) return [];
300
+ if (!isRecurring(clock)) {
301
+ const [date = "", time2 = ""] = clock.at.split("T");
302
+ const ymd = splitInts(date, "-");
303
+ const hms = splitInts(time2, ":");
304
+ const at = zonedToUtc({ year: at2(ymd, 0), month: at2(ymd, 1), day: at2(ymd, 2) }, at2(hms, 0), at2(hms, 1), clock.tz) + at2(hms, 2) * 1e3;
305
+ return at > after && at <= through ? [{ key: clock.at, at }] : [];
306
+ }
307
+ const time = splitInts(clock.at, ":");
308
+ const hour = at2(time, 0);
309
+ const minute = at2(time, 1);
310
+ const start = zonedParts(after, clock.tz);
311
+ const end = zonedParts(through, clock.tz);
312
+ const endOrdinal = ordinalOf(end);
313
+ const found = [];
314
+ let cursor = { year: start.year, month: start.month, day: start.day };
315
+ let scanned = 0;
316
+ while (ordinalOf(cursor) <= endOrdinal && scanned < MAX_DAYS_SCANNED) {
317
+ scanned += 1;
318
+ if (isDueOn(clock, cursor)) {
319
+ const at = zonedToUtc(cursor, hour, minute, clock.tz);
320
+ if (at > after && at <= through) {
321
+ found.push({ key: occurrenceKey(clock, cursor), at });
322
+ if (found.length >= cap) break;
323
+ }
324
+ }
325
+ cursor = nextDay(cursor);
326
+ }
327
+ return found;
328
+ };
329
+
217
330
  // src/errors.ts
218
331
  var TideError = class extends Error {
219
332
  code;
@@ -372,7 +485,11 @@ var findCycles = (reflexes, edges) => {
372
485
 
373
486
  // src/engine/admit.ts
374
487
  var idOf = (candidate) => typeof candidate === "object" && candidate !== null && "id" in candidate && typeof candidate.id === "string" ? candidate.id : void 0;
375
- var admitReflexes = (input, effectsOf, isolate) => {
488
+ var admitReflexes = ({
489
+ input,
490
+ effectsOf,
491
+ isolate
492
+ }) => {
376
493
  const parsed = [];
377
494
  const refused = [];
378
495
  const seen = /* @__PURE__ */ new Set();
@@ -406,120 +523,6 @@ var admitReflexes = (input, effectsOf, isolate) => {
406
523
  return { reflexes: kept, graph, refused };
407
524
  };
408
525
 
409
- // src/engine/occurrence.ts
410
- var HALF_DAY_MS = 432e5;
411
- var DAY_MS = 864e5;
412
- var MAX_DAYS_SCANNED = 3700;
413
- var FORMATTERS = /* @__PURE__ */ new Map();
414
- var formatterFor = (tz) => {
415
- const cached = FORMATTERS.get(tz);
416
- if (cached !== void 0) return cached;
417
- const built = new Intl.DateTimeFormat("en-US", {
418
- timeZone: tz,
419
- hourCycle: "h23",
420
- year: "numeric",
421
- month: "2-digit",
422
- day: "2-digit",
423
- hour: "2-digit",
424
- minute: "2-digit",
425
- second: "2-digit"
426
- });
427
- FORMATTERS.set(tz, built);
428
- return built;
429
- };
430
- var zonedParts = (instant, tz) => {
431
- const parts = formatterFor(tz).formatToParts(new Date(instant));
432
- const read = (type) => {
433
- const found = parts.find((part) => part.type === type);
434
- return found === void 0 ? 0 : Number(found.value);
435
- };
436
- return {
437
- year: read("year"),
438
- month: read("month"),
439
- day: read("day"),
440
- hour: read("hour"),
441
- minute: read("minute"),
442
- second: read("second")
443
- };
444
- };
445
- var offsetAt = (instant, tz) => {
446
- const parts = zonedParts(instant, tz);
447
- const asIfUtc = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
448
- return asIfUtc - Math.floor(instant / 1e3) * 1e3;
449
- };
450
- var rendersAs = (instant, tz, day, hour, minute) => {
451
- const parts = zonedParts(instant, tz);
452
- return parts.year === day.year && parts.month === day.month && parts.day === day.day && parts.hour === hour && parts.minute === minute;
453
- };
454
- var zonedToUtc = (day, hour, minute, tz) => {
455
- const guess = Date.UTC(day.year, day.month - 1, day.day, hour, minute);
456
- const before = offsetAt(guess - HALF_DAY_MS, tz);
457
- const after = offsetAt(guess + HALF_DAY_MS, tz);
458
- const candidates = before === after ? [guess - before] : [guess - before, guess - after];
459
- const valid = candidates.filter((candidate) => rendersAs(candidate, tz, day, hour, minute));
460
- return valid.length > 0 ? Math.min(...valid) : Math.max(...candidates);
461
- };
462
- var daysInMonth = (year, month) => new Date(Date.UTC(year, month, 0)).getUTCDate();
463
- var weekdayOf = (day) => {
464
- const index = new Date(Date.UTC(day.year, day.month - 1, day.day)).getUTCDay();
465
- return WEEKDAYS[(index + 6) % 7] ?? "mon";
466
- };
467
- var splitInts = (value, separator) => value.split(separator).map((part) => Number(part));
468
- var at2 = (values, index) => values[index] ?? 0;
469
- var nextDay = (day) => {
470
- const moved = new Date(Date.UTC(day.year, day.month - 1, day.day) + DAY_MS);
471
- return { year: moved.getUTCFullYear(), month: moved.getUTCMonth() + 1, day: moved.getUTCDate() };
472
- };
473
- var ordinalOf = (day) => day.year * 1e4 + day.month * 100 + day.day;
474
- var pad2 = (value) => String(value).padStart(2, "0");
475
- var isDueOn = (clock, day) => {
476
- if (clock.every === "day") return true;
477
- if (clock.every === "week") return Array.isArray(clock.on) ? clock.on.some((one) => one === weekdayOf(day)) : weekdayOf(day) === clock.on;
478
- if (clock.every === "month")
479
- return typeof clock.on === "number" && day.day === Math.min(clock.on, daysInMonth(day.year, day.month));
480
- if (typeof clock.on !== "string") return false;
481
- const parts = splitInts(clock.on, "-");
482
- const month = at2(parts, 0);
483
- const dayOfMonth = at2(parts, 1);
484
- return day.month === month && day.day === Math.min(dayOfMonth, daysInMonth(day.year, month));
485
- };
486
- var occurrenceKey = (clock, day) => {
487
- if (clock.every === "year") return String(day.year);
488
- if (clock.every === "month") return `${day.year}-${pad2(day.month)}`;
489
- return `${day.year}-${pad2(day.month)}-${pad2(day.day)}`;
490
- };
491
- var occurrencesBetween = (clock, after, through, cap) => {
492
- if (through <= after || cap <= 0) return [];
493
- if (!isRecurring(clock)) {
494
- const [date = "", time2 = ""] = clock.at.split("T");
495
- const ymd = splitInts(date, "-");
496
- const hms = splitInts(time2, ":");
497
- const at = zonedToUtc({ year: at2(ymd, 0), month: at2(ymd, 1), day: at2(ymd, 2) }, at2(hms, 0), at2(hms, 1), clock.tz) + at2(hms, 2) * 1e3;
498
- return at > after && at <= through ? [{ key: clock.at, at }] : [];
499
- }
500
- const time = splitInts(clock.at, ":");
501
- const hour = at2(time, 0);
502
- const minute = at2(time, 1);
503
- const start = zonedParts(after, clock.tz);
504
- const end = zonedParts(through, clock.tz);
505
- const endOrdinal = ordinalOf(end);
506
- const found = [];
507
- let cursor = { year: start.year, month: start.month, day: start.day };
508
- let scanned = 0;
509
- while (ordinalOf(cursor) <= endOrdinal && scanned < MAX_DAYS_SCANNED) {
510
- scanned += 1;
511
- if (isDueOn(clock, cursor)) {
512
- const at = zonedToUtc(cursor, hour, minute, clock.tz);
513
- if (at > after && at <= through) {
514
- found.push({ key: occurrenceKey(clock, cursor), at });
515
- if (found.length >= cap) break;
516
- }
517
- }
518
- cursor = nextDay(cursor);
519
- }
520
- return found;
521
- };
522
-
523
526
  // src/engine/match.ts
524
527
  var openRun = async (deps, loaded, input) => {
525
528
  const { reflex, version } = loaded;
@@ -569,8 +572,8 @@ var openRun = async (deps, loaded, input) => {
569
572
  var factAsRow = (fact) => ({ ...fact });
570
573
  var reflexMatchesFact = (loaded, fact) => {
571
574
  const { reflex } = loaded;
572
- if (fact.kind === "manual") return fact.target === reflex.id;
573
575
  if (fact.as !== reflex.as) return false;
576
+ if (fact.kind === "manual") return fact.target === reflex.id;
574
577
  if (!reflex.enabled) return false;
575
578
  if (fact.at < loaded.armedAt) return false;
576
579
  if (isManual(reflex.on)) return false;
@@ -585,13 +588,11 @@ var reflexMatchesFact = (loaded, fact) => {
585
588
  var matchFacts = async (deps, now, limit) => {
586
589
  const report = { factsMatched: 0, runsCreated: 0, parked: 0 };
587
590
  if (deps.reflexes().length === 0) return report;
588
- const due = await deps.store.query({
589
- table: "fact",
590
- where: { deliveredAt: { isNull: true }, parked: { isNull: true } },
591
- order: [{ by: "at" }],
592
- limit: limit * 4
593
- });
594
- for (const fact of due.filter((candidate) => (candidate.notBefore ?? candidate.at) <= now).slice(0, limit)) {
591
+ const waiting = { deliveredAt: { isNull: true }, parked: { isNull: true } };
592
+ const immediate = await deps.store.query({ table: "fact", where: { ...waiting, notBefore: { isNull: true }, at: { lte: now } }, order: [{ by: "at" }], limit });
593
+ const delayed = await deps.store.query({ table: "fact", where: { ...waiting, notBefore: { lte: now } }, order: [{ by: "at" }], limit });
594
+ const due = [...immediate, ...delayed].sort((left, right) => left.at - right.at).slice(0, limit);
595
+ for (const fact of due) {
595
596
  if (fact.depth > deps.maxChainDepth && fact.released !== true) {
596
597
  const reason = `chain depth ${fact.depth} exceeds maxChainDepth ${deps.maxChainDepth}`;
597
598
  await deps.store.cas("fact", fact.id, {}, { parked: reason });
@@ -685,127 +686,6 @@ var materializeClocks = async (deps, now) => {
685
686
  return report;
686
687
  };
687
688
 
688
- // src/engine/fanout.ts
689
- var collectRows = async (source, cap) => {
690
- const resolved = await source;
691
- const rows = [];
692
- if (Symbol.asyncIterator in Object(resolved)) {
693
- for await (const row of resolved) {
694
- rows.push(row);
695
- if (rows.length > cap) throw new TideError("duplicate_unit", `selection exceeded maxFanOut (${cap})`);
696
- }
697
- return rows;
698
- }
699
- for (const row of resolved) {
700
- rows.push(row);
701
- if (rows.length > cap) throw new TideError("duplicate_unit", `selection exceeded maxFanOut (${cap})`);
702
- }
703
- return rows;
704
- };
705
- var unitsFrom = (rows, unitKey, base, reflexId) => {
706
- const seen = /* @__PURE__ */ new Set();
707
- return rows.map((row) => {
708
- const raw = unitKey === void 0 ? void 0 : row[unitKey];
709
- const unit = raw === void 0 || raw === null ? "" : String(raw);
710
- if (seen.has(unit))
711
- throw new TideError("duplicate_unit", `${reflexId}: duplicate unit key "${unit}" \u2014 the selection's unitKey is not unique`);
712
- seen.add(unit);
713
- return { unit, env: { ...base, row } };
714
- });
715
- };
716
- var factRowsOf = async (deps, run) => {
717
- const ids = run.factIds ?? [];
718
- if (ids.length === 0) return [];
719
- return deps.store.query({ table: "fact", where: { id: { in: [...ids] } } });
720
- };
721
- var fanOut = async (deps, now, limit) => {
722
- let created = 0;
723
- const pending = await deps.store.query({
724
- table: "run",
725
- where: { state: "pending" },
726
- order: [{ by: "dueAt" }],
727
- limit
728
- });
729
- for (const run of pending) {
730
- const loaded = deps.find(run.reflexId);
731
- if (loaded === void 0) {
732
- await deps.store.cas("run", run.id, { state: "pending" }, { state: "skipped", settledAt: now, drained: true, note: "reflex is no longer loaded" });
733
- continue;
734
- }
735
- try {
736
- const facts = await factRowsOf(deps, run);
737
- const units = await unitsForRun(deps, loaded, shapeOf(run), facts, now);
738
- created += await commitFanout(deps, run, units.map((unit) => taskOf(unit, run, loaded, now)), units.length, now);
739
- } catch (error) {
740
- const reason = error instanceof Error ? error.message : String(error);
741
- if (isTideError(error)) {
742
- await deps.store.cas("run", run.id, { state: "pending" }, { state: "skipped", settledAt: now, drained: true, note: `fan-out refused: ${reason}` });
743
- deps.emit({ type: "run.skipped", reflexId: run.reflexId, reason });
744
- continue;
745
- }
746
- await deps.store.cas("run", run.id, { state: "pending" }, { note: `fan-out deferred: ${reason}` });
747
- deps.emit({ type: "run.deferred", reflexId: run.reflexId, runId: run.id, reason });
748
- }
749
- }
750
- return created;
751
- };
752
- var commitFanout = async (deps, run, tasks, selected, now) => deps.store.transact(async (tx) => {
753
- const claimed = await tx.cas("run", run.id, { state: "pending" }, { state: "fanned" });
754
- if (!claimed) return 0;
755
- let written = 0;
756
- for (const task of tasks) if (await tx.appendIfAbsent("task", task) !== void 0) written += 1;
757
- const settledNow = written === 0;
758
- await tx.cas(
759
- "run",
760
- run.id,
761
- {},
762
- {
763
- selected,
764
- total: written,
765
- state: settledNow ? "settled" : "fanned",
766
- settledAt: settledNow ? now : void 0
767
- }
768
- );
769
- return written;
770
- });
771
- var taskOf = (unit, run, loaded, now) => ({
772
- runId: run.id,
773
- reflexId: loaded.reflex.id,
774
- unit: unit.unit,
775
- cause: run.cause,
776
- env: unit.env,
777
- // Carried on the task: a swept run must not reset the chain ceiling.
778
- depth: run.depth,
779
- state: "pending",
780
- attempt: 0,
781
- claimedUntil: 0,
782
- notBefore: run.dueAt > now ? run.dueAt : now,
783
- createdAt: now
784
- });
785
- var shapeOf = (run) => ({ cause: run.cause, occurrence: run.occurrence, dueAt: run.dueAt });
786
- var unitsForRun = async (deps, loaded, run, facts, now) => {
787
- const { reflex } = loaded;
788
- const base = buildEnv({
789
- params: reflex.params,
790
- occurrence: run.occurrence === void 0 ? void 0 : { key: run.occurrence, at: run.dueAt },
791
- fact: facts.length === 1 ? { ...facts[0] } : void 0,
792
- facts: facts.length > 1 ? facts.map((fact) => ({ ...fact })) : void 0,
793
- now
794
- });
795
- const carried = facts.map((fact) => fact.row).filter((row) => row !== void 0);
796
- if (carried.length > 0 && reflex.select === void 0) return unitsFrom(carried, void 0, base, reflex.id);
797
- if (reflex.select === void 0) return [{ unit: "", env: base }];
798
- if (deps.select === void 0)
799
- throw new TideError("store", `${reflex.id} has a selection but no \`select\` seam is wired`);
800
- const query = evaluateTemplate(deps.transform, reflex.select.query, base);
801
- const rows = await collectRows(
802
- deps.select(query, { reflexId: reflex.id, now, actor: deps.actorFor(reflex.as), env: base }),
803
- deps.maxFanOut
804
- );
805
- if (reflex.select.mode === "batch") return [{ unit: "", env: { ...base, rows } }];
806
- return unitsFrom(rows, reflex.select.unitKey, base, reflex.id);
807
- };
808
-
809
689
  // src/engine/facts.ts
810
690
  var rootOf = async (store, cause) => {
811
691
  if (cause === void 0) return void 0;
@@ -859,6 +739,7 @@ var claimTasks = async (deps, now, limit, token) => {
859
739
  return deps.store.claim({
860
740
  table: "task",
861
741
  where: {
742
+ reflexId: { in: deps.reflexes().map((loaded) => loaded.reflex.id) },
862
743
  state: { in: ["pending", "retrying", "claimed"] },
863
744
  notBefore: { lte: now },
864
745
  claimedUntil: { lte: now }
@@ -871,7 +752,8 @@ var claimTasks = async (deps, now, limit, token) => {
871
752
  onePer: serialReflexIds.length === 0 ? void 0 : { column: "reflexId", held: { state: "claimed", claimedUntil: { gt: now } }, only: serialReflexIds }
872
753
  });
873
754
  };
874
- var executeTasks = async (deps, now, limit) => {
755
+ var leaseRenewed = async (deps, task, token, clock) => clock === void 0 || deps.store.cas("task", task.id, { token, attempt: task.attempt }, { claimedUntil: Math.max(task.claimedUntil, clock() + deps.leaseMs) });
756
+ var executeTasks = async (deps, now, limit, clock) => {
875
757
  const report = { executed: 0, succeeded: 0, failed: 0, retrying: 0, reclaimed: 0 };
876
758
  const lapsed = new Set(
877
759
  (await deps.store.query({
@@ -889,6 +771,7 @@ var executeTasks = async (deps, now, limit) => {
889
771
  }
890
772
  const loaded = deps.find(task.reflexId);
891
773
  if (loaded === void 0) continue;
774
+ if (!await leaseRenewed(deps, task, token, clock)) continue;
892
775
  const { reflex } = loaded;
893
776
  const registry = deps.effectsFor(reflex.as);
894
777
  const handler = registry[reflex.effect.name];
@@ -1015,29 +898,164 @@ var reopenTask = async (deps, taskId, now) => deps.store.transact(async (tx) =>
1015
898
  return true;
1016
899
  });
1017
900
  var settleRuns = async (deps, now) => {
1018
- const settled = await deps.store.claim({
901
+ const settled = await deps.store.query({
1019
902
  table: "run",
1020
903
  where: { state: "settled", drained: { ne: true } },
1021
904
  order: [{ by: "settledAt" }],
1022
- limit: 200,
1023
- set: { drained: true }
905
+ limit: 200
1024
906
  });
907
+ let drained = 0;
1025
908
  for (const run of settled) {
1026
- deps.emit({ type: "run.settled", run });
1027
- const admission = await admitFact(deps.store, {
1028
- kind: "run",
1029
- reflex: run.reflexId,
1030
- runId: run.id,
1031
- occurrence: run.occurrence,
1032
- stats: { total: run.total, done: run.done, failed: run.failed },
1033
- at: now,
1034
- depth: run.depth + 1,
1035
- cause: `run:${run.id}`,
1036
- as: run.as
1037
- }, deps.maxChainFacts);
909
+ const admission = await deps.store.transact(async (tx) => {
910
+ if (!await tx.cas("run", run.id, { state: "settled", drained: { ne: true } }, { drained: true })) return void 0;
911
+ return admitFact(tx, {
912
+ kind: "run",
913
+ reflex: run.reflexId,
914
+ runId: run.id,
915
+ occurrence: run.occurrence,
916
+ stats: { total: run.total, done: run.done, failed: run.failed },
917
+ at: now,
918
+ depth: run.depth + 1,
919
+ cause: `run:${run.id}`,
920
+ as: run.as
921
+ }, deps.maxChainFacts);
922
+ }).catch(() => void 0);
923
+ if (admission === void 0) continue;
924
+ drained += 1;
925
+ deps.emit({ type: "run.settled", run: { ...run, drained: true } });
1038
926
  announceFact(deps.emit, admission);
1039
927
  }
1040
- return settled.length;
928
+ return drained;
929
+ };
930
+
931
+ // src/engine/fanout.ts
932
+ var collectRows = async (source, cap) => {
933
+ const resolved = await source;
934
+ const rows = [];
935
+ if (Symbol.asyncIterator in Object(resolved)) {
936
+ for await (const row of resolved) {
937
+ rows.push(row);
938
+ if (rows.length > cap) throw new TideError("duplicate_unit", `selection exceeded maxFanOut (${cap})`);
939
+ }
940
+ return rows;
941
+ }
942
+ for (const row of resolved) {
943
+ rows.push(row);
944
+ if (rows.length > cap) throw new TideError("duplicate_unit", `selection exceeded maxFanOut (${cap})`);
945
+ }
946
+ return rows;
947
+ };
948
+ var unitsFrom = (rows, unitKey, base, reflexId) => {
949
+ const seen = /* @__PURE__ */ new Set();
950
+ return rows.map((row) => {
951
+ const raw = unitKey === void 0 ? void 0 : row[unitKey];
952
+ const unit = raw === void 0 || raw === null ? "" : String(raw);
953
+ if (seen.has(unit))
954
+ throw new TideError("duplicate_unit", `${reflexId}: duplicate unit key "${unit}" \u2014 the selection's unitKey is not unique`);
955
+ seen.add(unit);
956
+ return { unit, env: { ...base, row } };
957
+ });
958
+ };
959
+ var factRowsOf = async (deps, run) => {
960
+ const ids = run.factIds ?? [];
961
+ if (ids.length === 0) return [];
962
+ return deps.store.query({ table: "fact", where: { id: { in: [...ids] } } });
963
+ };
964
+ var fanOut = async (deps, now, limit) => {
965
+ let created = 0;
966
+ if (!deps.hasLoaded()) return created;
967
+ if (deps.deferred.size > 0) {
968
+ const still = await deps.store.query({ table: "run", where: { id: { in: [...deps.deferred.keys()] }, state: "pending" } });
969
+ const pendingIds = new Set(still.map((run) => run.id));
970
+ for (const runId of deps.deferred.keys()) if (!pendingIds.has(runId)) deps.deferred.delete(runId);
971
+ }
972
+ const waiting = new Set(
973
+ [...deps.deferred].filter(([, deferral]) => deferral.until > now && deps.find(deferral.reflexId) !== void 0).map(([runId]) => runId)
974
+ );
975
+ const page = await deps.store.query({ table: "run", where: { state: "pending" }, order: [{ by: "dueAt" }], limit: limit + waiting.size });
976
+ const pending = page.filter((run) => !waiting.has(run.id)).slice(0, limit);
977
+ for (const run of pending) {
978
+ const loaded = deps.find(run.reflexId);
979
+ if (loaded === void 0) {
980
+ await deps.store.cas("run", run.id, { state: "pending" }, { state: "skipped", settledAt: now, drained: true, note: "reflex is no longer loaded" });
981
+ continue;
982
+ }
983
+ try {
984
+ const facts = await factRowsOf(deps, run);
985
+ const units = await unitsForRun(deps, loaded, shapeOf(run), facts, now);
986
+ created += await commitFanout(deps, run, units.map((unit) => taskOf(unit, run, loaded, now)), units.length, now);
987
+ } catch (error) {
988
+ const reason = error instanceof Error ? error.message : String(error);
989
+ if (isTideError(error)) {
990
+ await deps.store.cas("run", run.id, { state: "pending" }, { state: "skipped", settledAt: now, drained: true, note: `fan-out refused: ${reason}` });
991
+ deps.emit({ type: "run.skipped", reflexId: run.reflexId, reason });
992
+ continue;
993
+ }
994
+ await deps.store.cas("run", run.id, { state: "pending" }, { note: `fan-out deferred: ${reason}` });
995
+ const count = (deps.deferred.get(run.id)?.count ?? 0) + 1;
996
+ const retry = loaded.reflex.policy.retry;
997
+ const wait = backoffFor(Math.min(count, retry?.max ?? 3), retry?.baseMs ?? 6e4, retry?.backoff ?? "exponential");
998
+ deps.deferred.set(run.id, { reflexId: run.reflexId, count, until: now + Math.min(wait, Number.MAX_SAFE_INTEGER) });
999
+ deps.emit({ type: "run.deferred", reflexId: run.reflexId, runId: run.id, reason });
1000
+ }
1001
+ }
1002
+ return created;
1003
+ };
1004
+ var commitFanout = async (deps, run, tasks, selected, now) => deps.store.transact(async (tx) => {
1005
+ const claimed = await tx.cas("run", run.id, { state: "pending" }, { state: "fanned" });
1006
+ if (!claimed) return 0;
1007
+ let written = 0;
1008
+ for (const task of tasks) if (await tx.appendIfAbsent("task", task) !== void 0) written += 1;
1009
+ const settledNow = written === 0;
1010
+ await tx.cas(
1011
+ "run",
1012
+ run.id,
1013
+ {},
1014
+ {
1015
+ selected,
1016
+ total: written,
1017
+ state: settledNow ? "settled" : "fanned",
1018
+ settledAt: settledNow ? now : void 0
1019
+ }
1020
+ );
1021
+ return written;
1022
+ });
1023
+ var taskOf = (unit, run, loaded, now) => ({
1024
+ runId: run.id,
1025
+ reflexId: loaded.reflex.id,
1026
+ unit: unit.unit,
1027
+ cause: run.cause,
1028
+ env: unit.env,
1029
+ // Carried on the task: a swept run must not reset the chain ceiling.
1030
+ depth: run.depth,
1031
+ state: "pending",
1032
+ attempt: 0,
1033
+ claimedUntil: 0,
1034
+ notBefore: run.dueAt > now ? run.dueAt : now,
1035
+ createdAt: now
1036
+ });
1037
+ var shapeOf = (run) => ({ cause: run.cause, occurrence: run.occurrence, dueAt: run.dueAt });
1038
+ var unitsForRun = async (deps, loaded, run, facts, now) => {
1039
+ const { reflex } = loaded;
1040
+ const base = buildEnv({
1041
+ params: reflex.params,
1042
+ occurrence: run.occurrence === void 0 ? void 0 : { key: run.occurrence, at: run.dueAt },
1043
+ fact: facts.length === 1 ? { ...facts[0] } : void 0,
1044
+ facts: facts.length > 1 ? facts.map((fact) => ({ ...fact })) : void 0,
1045
+ now
1046
+ });
1047
+ const carried = facts.map((fact) => fact.row).filter((row) => row !== void 0);
1048
+ if (carried.length > 0 && reflex.select === void 0) return unitsFrom(carried, void 0, base, reflex.id);
1049
+ if (reflex.select === void 0) return [{ unit: "", env: base }];
1050
+ if (deps.select === void 0)
1051
+ throw new TideError("store", `${reflex.id} has a selection but no \`select\` seam is wired`);
1052
+ const query = evaluateTemplate(deps.transform, reflex.select.query, base);
1053
+ const rows = await collectRows(
1054
+ deps.select(query, { reflexId: reflex.id, now, actor: deps.actorFor(reflex.as), env: base }),
1055
+ deps.maxFanOut
1056
+ );
1057
+ if (reflex.select.mode === "batch") return [{ unit: "", env: { ...base, rows } }];
1058
+ return unitsFrom(rows, reflex.select.unitKey, base, reflex.id);
1041
1059
  };
1042
1060
 
1043
1061
  // src/engine/advance.ts
@@ -1048,7 +1066,7 @@ var runAdvance = async (deps, options) => {
1048
1066
  const clocks = await materializeClocks(deps, now);
1049
1067
  const matched = await matchFacts(deps, now, limit);
1050
1068
  const tasksCreated = await fanOut(deps, now, limit);
1051
- const executed = await executeTasks(deps, now, limit);
1069
+ const executed = await executeTasks(deps, now, limit, options.clock);
1052
1070
  const runsSettled = await settleRuns(deps, now);
1053
1071
  return {
1054
1072
  now,
@@ -1091,19 +1109,20 @@ var nextDue = async (deps, now) => {
1091
1109
  consider(delayed?.notBefore);
1092
1110
  const [run] = await deps.store.query({ table: "run", where: { state: "pending" }, order: [{ by: "dueAt" }], limit: 1 });
1093
1111
  consider(run?.dueAt);
1112
+ const loaded = { in: deps.reflexes().map((entry) => entry.reflex.id) };
1094
1113
  const [waiting] = await deps.store.query({
1095
1114
  table: "task",
1096
- where: { state: { in: ["pending", "retrying"] } },
1115
+ where: { reflexId: loaded, state: { in: ["pending", "retrying"] } },
1097
1116
  order: [{ by: "notBefore" }],
1098
1117
  limit: 1
1099
1118
  });
1100
1119
  consider(waiting?.notBefore);
1101
- const [claimed] = await deps.store.query({ table: "task", where: { state: "claimed" }, order: [{ by: "claimedUntil" }], limit: 1 });
1120
+ const [claimed] = await deps.store.query({ table: "task", where: { reflexId: loaded, state: "claimed" }, order: [{ by: "claimedUntil" }], limit: 1 });
1102
1121
  consider(claimed?.claimedUntil);
1103
- for (const loaded of deps.reflexes()) {
1104
- const clock = clockOf(loaded.reflex.on);
1122
+ for (const loaded2 of deps.reflexes()) {
1123
+ const clock = clockOf(loaded2.reflex.on);
1105
1124
  if (clock !== void 0) {
1106
- const state = await stateOf(deps, loaded.reflex.id);
1125
+ const state = await stateOf(deps, loaded2.reflex.id);
1107
1126
  if (state?.materializedThrough === void 0) {
1108
1127
  consider(now);
1109
1128
  continue;
@@ -1184,6 +1203,20 @@ var DEFAULT_MAX_CHAIN_DEPTH = 24;
1184
1203
  var DEFAULT_MAX_CHAIN_FACTS = 1e4;
1185
1204
  var DEFAULT_MAX_FAN_OUT = 1e4;
1186
1205
  var DEFAULT_LEASE_MS = 3e5;
1206
+ var missingDateWarnings = (reflex) => {
1207
+ const clock = clockOf(reflex.on);
1208
+ if (clock === void 0 || isRecurring(clock)) return [];
1209
+ const named = clock.at.slice(0, 10);
1210
+ const [year = 0, month = 0, day = 0] = named.split("-").map(Number);
1211
+ const asWritten = /* @__PURE__ */ new Date(0);
1212
+ asWritten.setUTCFullYear(year, month - 1, day);
1213
+ if (asWritten.getUTCFullYear() === year && asWritten.getUTCMonth() === month - 1 && asWritten.getUTCDate() === day) return [];
1214
+ const [fires] = occurrencesBetween(clock, -Infinity, Infinity, 1);
1215
+ if (fires === void 0) return [];
1216
+ const local = zonedParts(fires.at, clock.tz);
1217
+ const on = [local.year, local.month, local.day].map((part, index) => String(part).padStart(index === 0 ? 4 : 2, "0")).join("-");
1218
+ return [`${reflex.id}: clock.at names ${named}, which does not exist \u2014 it fires on ${on}`];
1219
+ };
1187
1220
  var createTide = (config) => {
1188
1221
  const loaded = /* @__PURE__ */ new Map();
1189
1222
  let effectsCache;
@@ -1193,6 +1226,7 @@ var createTide = (config) => {
1193
1226
  return effectsCache;
1194
1227
  };
1195
1228
  let tokens = 0;
1229
+ let hasLoaded = false;
1196
1230
  const deps = {
1197
1231
  store: config.store,
1198
1232
  transform: config.transform,
@@ -1205,27 +1239,42 @@ var createTide = (config) => {
1205
1239
  leaseMs: config.leaseMs ?? DEFAULT_LEASE_MS,
1206
1240
  emit: config.onEvent ?? (() => void 0),
1207
1241
  reflexes: () => [...loaded.values()],
1242
+ hasLoaded: () => hasLoaded,
1208
1243
  find: (id) => loaded.get(id),
1209
1244
  nextToken: () => {
1210
1245
  tokens += 1;
1211
1246
  return `tok_${tokens.toString(36)}`;
1212
- }
1247
+ },
1248
+ deferred: /* @__PURE__ */ new Map()
1249
+ };
1250
+ const everLoaded = /* @__PURE__ */ new Set();
1251
+ let lastLoad = Promise.resolve();
1252
+ const load = (input, options) => {
1253
+ const turn = lastLoad.then(() => loadNow(input, options));
1254
+ lastLoad = turn.catch(() => void 0);
1255
+ return turn;
1213
1256
  };
1214
- const load = async (input, options) => {
1215
- const { reflexes: parsed, graph, refused } = admitReflexes(input, mergedEffects, options?.isolate === true);
1257
+ const loadNow = async (input, options) => {
1258
+ const { reflexes: parsed, graph, refused } = admitReflexes({ input, effectsOf: mergedEffects, isolate: options?.isolate === true });
1216
1259
  const previously = new Set(loaded.keys());
1217
1260
  const next = /* @__PURE__ */ new Map();
1218
1261
  for (const reflex of parsed) {
1219
1262
  const stored = await stateOf(deps, reflex.id);
1220
1263
  const armedAt = stored?.armedAt ?? options?.at ?? 0;
1221
1264
  if (stored === void 0) await config.store.appendIfAbsent("state", { reflexId: reflex.id, armedAt });
1222
- if (!previously.has(reflex.id) && stored?.materializedThrough !== void 0 && options?.at !== void 0)
1265
+ const entering = !previously.has(reflex.id) && (options?.resume !== true || everLoaded.has(reflex.id));
1266
+ if (entering && stored?.materializedThrough !== void 0 && options?.at !== void 0)
1223
1267
  await config.store.cas("state", reflex.id, {}, { materializedThrough: Math.max(stored.materializedThrough, options.at) });
1224
1268
  next.set(reflex.id, { reflex, version: versionOf(reflex), armedAt });
1225
1269
  }
1226
1270
  loaded.clear();
1227
1271
  for (const [id, entry] of next) loaded.set(id, entry);
1228
- return { loaded: parsed.length, cycles: graph.cycles, blind: graph.blind, warnings: graph.warnings, refused };
1272
+ for (const id of next.keys()) everLoaded.add(id);
1273
+ hasLoaded = true;
1274
+ const leaseWarnings = parsed.filter((reflex) => reflex.policy.timeoutMs >= deps.leaseMs).map(
1275
+ (reflex) => `${reflex.id}: timeoutMs ${reflex.policy.timeoutMs} is not shorter than leaseMs ${deps.leaseMs} \u2014 another instance may claim the task again while its effect still runs`
1276
+ );
1277
+ return { loaded: parsed.length, cycles: graph.cycles, blind: graph.blind, warnings: [...graph.warnings, ...leaseWarnings, ...parsed.flatMap(missingDateWarnings)], refused };
1229
1278
  };
1230
1279
  const mergedEffects = (parsed) => {
1231
1280
  if (typeof config.effects !== "function") return config.effects ?? {};
@@ -1250,6 +1299,7 @@ var createTide = (config) => {
1250
1299
  throw new TideError("invalid_fact", `fact did not parse: ${result.error.issues.map((i) => i.message).join("; ")}`, {
1251
1300
  issues: result.error.issues
1252
1301
  });
1302
+ if (result.data.kind === "run") throw new TideError("invalid_fact", "a run fact is minted by tide when a run settles; it is not ingested");
1253
1303
  if (!watchable(result.data)) return void 0;
1254
1304
  const admission = await admitFact(config.store, { ...result.data, cause: options?.cause, depth: options?.depth ?? 0, as: options?.as }, deps.maxChainFacts);
1255
1305
  announceFact(deps.emit, admission);
@@ -1309,13 +1359,12 @@ var createTide = (config) => {
1309
1359
  }),
1310
1360
  task: (id) => one("task", id),
1311
1361
  facts: async (filter) => {
1312
- const found = await config.store.query({
1313
- table: "fact",
1314
- order: [{ by: "at", dir: "desc" }],
1315
- limit: filter?.reflexId === void 0 ? filter?.limit : void 0
1316
- });
1317
- const matched = filter?.reflexId === void 0 ? found : found.filter((fact) => fact.reflex === filter.reflexId || fact.target === filter.reflexId);
1318
- return filter?.limit === void 0 ? matched : matched.slice(0, filter.limit);
1362
+ const newest = { order: [{ by: "at", dir: "desc" }], limit: filter?.limit };
1363
+ if (filter?.reflexId === void 0) return config.store.query({ table: "fact", ...newest });
1364
+ const minted = await config.store.query({ table: "fact", where: { reflex: filter.reflexId }, ...newest });
1365
+ const aimed = await config.store.query({ table: "fact", where: { target: filter.reflexId }, ...newest });
1366
+ const matched = [...new Map([...minted, ...aimed].map((fact) => [fact.id, fact])).values()].sort((left, right) => right.at - left.at);
1367
+ return filter.limit === void 0 ? matched : matched.slice(0, filter.limit);
1319
1368
  },
1320
1369
  fact: (id) => one("fact", id),
1321
1370
  causeChain,
@@ -1447,26 +1496,31 @@ var createMemoryStore = () => {
1447
1496
  spec.order
1448
1497
  );
1449
1498
  const taken = /* @__PURE__ */ new Set();
1450
- const restricted = new Set(spec.onePer?.only ?? []);
1499
+ const restricted = spec.onePer?.only ?? [];
1451
1500
  if (spec.onePer !== void 0) {
1452
1501
  for (const row of rowsOf(spec.table))
1453
1502
  if (matches(row, spec.onePer.held)) taken.add(String(row[spec.onePer.column]));
1454
1503
  }
1455
- const claimed = [];
1504
+ const groupOf = (row) => spec.onePer === void 0 ? void 0 : String(row[spec.onePer.column]);
1505
+ const chosen = [];
1506
+ for (const group of restricted) {
1507
+ if (chosen.length >= spec.limit) break;
1508
+ if (taken.has(group)) continue;
1509
+ const first = candidates.find((row) => groupOf(row) === group);
1510
+ if (first === void 0) continue;
1511
+ taken.add(group);
1512
+ chosen.push(first);
1513
+ }
1456
1514
  for (const row of candidates) {
1457
- if (claimed.length >= spec.limit) break;
1458
- if (spec.onePer !== void 0) {
1459
- const group = String(row[spec.onePer.column]);
1460
- if (restricted.has(group)) {
1461
- if (taken.has(group)) continue;
1462
- taken.add(group);
1463
- }
1464
- }
1515
+ if (chosen.length >= spec.limit) break;
1516
+ const group = groupOf(row);
1517
+ if (group === void 0 || !restricted.includes(group)) chosen.push(row);
1518
+ }
1519
+ return sorted(chosen, spec.order).map((row) => {
1465
1520
  const next = applied(row, spec.set);
1466
1521
  tables[spec.table].set(keyOf(spec.table, next), next);
1467
- claimed.push(next);
1468
- }
1469
- return claimed;
1522
+ return next;
1523
+ });
1470
1524
  };
1471
1525
  const cas = async (table, id, expect, set) => {
1472
1526
  const row = tables[table].get(id);
@@ -1528,7 +1582,7 @@ var createTideDriver = (config) => {
1528
1582
  let timer;
1529
1583
  const drain = async () => {
1530
1584
  for (let steps = 0; steps < MAX_STEPS_PER_DRAIN; steps += 1) {
1531
- const report = await tide.advance({ now: now() });
1585
+ const report = await tide.advance({ now: now(), clock: now });
1532
1586
  if (progressOf(report) === 0) return;
1533
1587
  }
1534
1588
  console.error(`[tide:driver] a drain exceeded ${MAX_STEPS_PER_DRAIN} steps \u2014 stopping this pass; the janitor will resume it`);