@niscorp/tide 0.1.12 → 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
@@ -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;
@@ -410,120 +523,6 @@ var admitReflexes = ({
410
523
  return { reflexes: kept, graph, refused };
411
524
  };
412
525
 
413
- // src/engine/occurrence.ts
414
- var HALF_DAY_MS = 432e5;
415
- var DAY_MS = 864e5;
416
- var MAX_DAYS_SCANNED = 3700;
417
- var FORMATTERS = /* @__PURE__ */ new Map();
418
- var formatterFor = (tz) => {
419
- const cached = FORMATTERS.get(tz);
420
- if (cached !== void 0) return cached;
421
- const built = new Intl.DateTimeFormat("en-US", {
422
- timeZone: tz,
423
- hourCycle: "h23",
424
- year: "numeric",
425
- month: "2-digit",
426
- day: "2-digit",
427
- hour: "2-digit",
428
- minute: "2-digit",
429
- second: "2-digit"
430
- });
431
- FORMATTERS.set(tz, built);
432
- return built;
433
- };
434
- var zonedParts = (instant, tz) => {
435
- const parts = formatterFor(tz).formatToParts(new Date(instant));
436
- const read = (type) => {
437
- const found = parts.find((part) => part.type === type);
438
- return found === void 0 ? 0 : Number(found.value);
439
- };
440
- return {
441
- year: read("year"),
442
- month: read("month"),
443
- day: read("day"),
444
- hour: read("hour"),
445
- minute: read("minute"),
446
- second: read("second")
447
- };
448
- };
449
- var offsetAt = (instant, tz) => {
450
- const parts = zonedParts(instant, tz);
451
- const asIfUtc = Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour, parts.minute, parts.second);
452
- return asIfUtc - Math.floor(instant / 1e3) * 1e3;
453
- };
454
- var rendersAs = (instant, tz, day, hour, minute) => {
455
- const parts = zonedParts(instant, tz);
456
- return parts.year === day.year && parts.month === day.month && parts.day === day.day && parts.hour === hour && parts.minute === minute;
457
- };
458
- var zonedToUtc = (day, hour, minute, tz) => {
459
- const guess = Date.UTC(day.year, day.month - 1, day.day, hour, minute);
460
- const before = offsetAt(guess - HALF_DAY_MS, tz);
461
- const after = offsetAt(guess + HALF_DAY_MS, tz);
462
- const candidates = before === after ? [guess - before] : [guess - before, guess - after];
463
- const valid = candidates.filter((candidate) => rendersAs(candidate, tz, day, hour, minute));
464
- return valid.length > 0 ? Math.min(...valid) : Math.max(...candidates);
465
- };
466
- var daysInMonth = (year, month) => new Date(Date.UTC(year, month, 0)).getUTCDate();
467
- var weekdayOf = (day) => {
468
- const index = new Date(Date.UTC(day.year, day.month - 1, day.day)).getUTCDay();
469
- return WEEKDAYS[(index + 6) % 7] ?? "mon";
470
- };
471
- var splitInts = (value, separator) => value.split(separator).map((part) => Number(part));
472
- var at2 = (values, index) => values[index] ?? 0;
473
- var nextDay = (day) => {
474
- const moved = new Date(Date.UTC(day.year, day.month - 1, day.day) + DAY_MS);
475
- return { year: moved.getUTCFullYear(), month: moved.getUTCMonth() + 1, day: moved.getUTCDate() };
476
- };
477
- var ordinalOf = (day) => day.year * 1e4 + day.month * 100 + day.day;
478
- var pad2 = (value) => String(value).padStart(2, "0");
479
- var isDueOn = (clock, day) => {
480
- if (clock.every === "day") return true;
481
- if (clock.every === "week") return Array.isArray(clock.on) ? clock.on.some((one) => one === weekdayOf(day)) : weekdayOf(day) === clock.on;
482
- if (clock.every === "month")
483
- return typeof clock.on === "number" && day.day === Math.min(clock.on, daysInMonth(day.year, day.month));
484
- if (typeof clock.on !== "string") return false;
485
- const parts = splitInts(clock.on, "-");
486
- const month = at2(parts, 0);
487
- const dayOfMonth = at2(parts, 1);
488
- return day.month === month && day.day === Math.min(dayOfMonth, daysInMonth(day.year, month));
489
- };
490
- var occurrenceKey = (clock, day) => {
491
- if (clock.every === "year") return String(day.year);
492
- if (clock.every === "month") return `${day.year}-${pad2(day.month)}`;
493
- return `${day.year}-${pad2(day.month)}-${pad2(day.day)}`;
494
- };
495
- var occurrencesBetween = (clock, after, through, cap) => {
496
- if (through <= after || cap <= 0) return [];
497
- if (!isRecurring(clock)) {
498
- const [date = "", time2 = ""] = clock.at.split("T");
499
- const ymd = splitInts(date, "-");
500
- const hms = splitInts(time2, ":");
501
- 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;
502
- return at > after && at <= through ? [{ key: clock.at, at }] : [];
503
- }
504
- const time = splitInts(clock.at, ":");
505
- const hour = at2(time, 0);
506
- const minute = at2(time, 1);
507
- const start = zonedParts(after, clock.tz);
508
- const end = zonedParts(through, clock.tz);
509
- const endOrdinal = ordinalOf(end);
510
- const found = [];
511
- let cursor = { year: start.year, month: start.month, day: start.day };
512
- let scanned = 0;
513
- while (ordinalOf(cursor) <= endOrdinal && scanned < MAX_DAYS_SCANNED) {
514
- scanned += 1;
515
- if (isDueOn(clock, cursor)) {
516
- const at = zonedToUtc(cursor, hour, minute, clock.tz);
517
- if (at > after && at <= through) {
518
- found.push({ key: occurrenceKey(clock, cursor), at });
519
- if (found.length >= cap) break;
520
- }
521
- }
522
- cursor = nextDay(cursor);
523
- }
524
- return found;
525
- };
526
-
527
526
  // src/engine/match.ts
528
527
  var openRun = async (deps, loaded, input) => {
529
528
  const { reflex, version } = loaded;
@@ -573,8 +572,8 @@ var openRun = async (deps, loaded, input) => {
573
572
  var factAsRow = (fact) => ({ ...fact });
574
573
  var reflexMatchesFact = (loaded, fact) => {
575
574
  const { reflex } = loaded;
576
- if (fact.kind === "manual") return fact.target === reflex.id;
577
575
  if (fact.as !== reflex.as) return false;
576
+ if (fact.kind === "manual") return fact.target === reflex.id;
578
577
  if (!reflex.enabled) return false;
579
578
  if (fact.at < loaded.armedAt) return false;
580
579
  if (isManual(reflex.on)) return false;
@@ -589,13 +588,11 @@ var reflexMatchesFact = (loaded, fact) => {
589
588
  var matchFacts = async (deps, now, limit) => {
590
589
  const report = { factsMatched: 0, runsCreated: 0, parked: 0 };
591
590
  if (deps.reflexes().length === 0) return report;
592
- const due = await deps.store.query({
593
- table: "fact",
594
- where: { deliveredAt: { isNull: true }, parked: { isNull: true } },
595
- order: [{ by: "at" }],
596
- limit: limit * 4
597
- });
598
- 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) {
599
596
  if (fact.depth > deps.maxChainDepth && fact.released !== true) {
600
597
  const reason = `chain depth ${fact.depth} exceeds maxChainDepth ${deps.maxChainDepth}`;
601
598
  await deps.store.cas("fact", fact.id, {}, { parked: reason });
@@ -689,127 +686,6 @@ var materializeClocks = async (deps, now) => {
689
686
  return report;
690
687
  };
691
688
 
692
- // src/engine/fanout.ts
693
- var collectRows = async (source, cap) => {
694
- const resolved = await source;
695
- const rows = [];
696
- if (Symbol.asyncIterator in Object(resolved)) {
697
- for await (const row of resolved) {
698
- rows.push(row);
699
- if (rows.length > cap) throw new TideError("duplicate_unit", `selection exceeded maxFanOut (${cap})`);
700
- }
701
- return rows;
702
- }
703
- for (const row of resolved) {
704
- rows.push(row);
705
- if (rows.length > cap) throw new TideError("duplicate_unit", `selection exceeded maxFanOut (${cap})`);
706
- }
707
- return rows;
708
- };
709
- var unitsFrom = (rows, unitKey, base, reflexId) => {
710
- const seen = /* @__PURE__ */ new Set();
711
- return rows.map((row) => {
712
- const raw = unitKey === void 0 ? void 0 : row[unitKey];
713
- const unit = raw === void 0 || raw === null ? "" : String(raw);
714
- if (seen.has(unit))
715
- throw new TideError("duplicate_unit", `${reflexId}: duplicate unit key "${unit}" \u2014 the selection's unitKey is not unique`);
716
- seen.add(unit);
717
- return { unit, env: { ...base, row } };
718
- });
719
- };
720
- var factRowsOf = async (deps, run) => {
721
- const ids = run.factIds ?? [];
722
- if (ids.length === 0) return [];
723
- return deps.store.query({ table: "fact", where: { id: { in: [...ids] } } });
724
- };
725
- var fanOut = async (deps, now, limit) => {
726
- let created = 0;
727
- const pending = await deps.store.query({
728
- table: "run",
729
- where: { state: "pending" },
730
- order: [{ by: "dueAt" }],
731
- limit
732
- });
733
- for (const run of pending) {
734
- const loaded = deps.find(run.reflexId);
735
- if (loaded === void 0) {
736
- await deps.store.cas("run", run.id, { state: "pending" }, { state: "skipped", settledAt: now, drained: true, note: "reflex is no longer loaded" });
737
- continue;
738
- }
739
- try {
740
- const facts = await factRowsOf(deps, run);
741
- const units = await unitsForRun(deps, loaded, shapeOf(run), facts, now);
742
- created += await commitFanout(deps, run, units.map((unit) => taskOf(unit, run, loaded, now)), units.length, now);
743
- } catch (error) {
744
- const reason = error instanceof Error ? error.message : String(error);
745
- if (isTideError(error)) {
746
- await deps.store.cas("run", run.id, { state: "pending" }, { state: "skipped", settledAt: now, drained: true, note: `fan-out refused: ${reason}` });
747
- deps.emit({ type: "run.skipped", reflexId: run.reflexId, reason });
748
- continue;
749
- }
750
- await deps.store.cas("run", run.id, { state: "pending" }, { note: `fan-out deferred: ${reason}` });
751
- deps.emit({ type: "run.deferred", reflexId: run.reflexId, runId: run.id, reason });
752
- }
753
- }
754
- return created;
755
- };
756
- var commitFanout = async (deps, run, tasks, selected, now) => deps.store.transact(async (tx) => {
757
- const claimed = await tx.cas("run", run.id, { state: "pending" }, { state: "fanned" });
758
- if (!claimed) return 0;
759
- let written = 0;
760
- for (const task of tasks) if (await tx.appendIfAbsent("task", task) !== void 0) written += 1;
761
- const settledNow = written === 0;
762
- await tx.cas(
763
- "run",
764
- run.id,
765
- {},
766
- {
767
- selected,
768
- total: written,
769
- state: settledNow ? "settled" : "fanned",
770
- settledAt: settledNow ? now : void 0
771
- }
772
- );
773
- return written;
774
- });
775
- var taskOf = (unit, run, loaded, now) => ({
776
- runId: run.id,
777
- reflexId: loaded.reflex.id,
778
- unit: unit.unit,
779
- cause: run.cause,
780
- env: unit.env,
781
- // Carried on the task: a swept run must not reset the chain ceiling.
782
- depth: run.depth,
783
- state: "pending",
784
- attempt: 0,
785
- claimedUntil: 0,
786
- notBefore: run.dueAt > now ? run.dueAt : now,
787
- createdAt: now
788
- });
789
- var shapeOf = (run) => ({ cause: run.cause, occurrence: run.occurrence, dueAt: run.dueAt });
790
- var unitsForRun = async (deps, loaded, run, facts, now) => {
791
- const { reflex } = loaded;
792
- const base = buildEnv({
793
- params: reflex.params,
794
- occurrence: run.occurrence === void 0 ? void 0 : { key: run.occurrence, at: run.dueAt },
795
- fact: facts.length === 1 ? { ...facts[0] } : void 0,
796
- facts: facts.length > 1 ? facts.map((fact) => ({ ...fact })) : void 0,
797
- now
798
- });
799
- const carried = facts.map((fact) => fact.row).filter((row) => row !== void 0);
800
- if (carried.length > 0 && reflex.select === void 0) return unitsFrom(carried, void 0, base, reflex.id);
801
- if (reflex.select === void 0) return [{ unit: "", env: base }];
802
- if (deps.select === void 0)
803
- throw new TideError("store", `${reflex.id} has a selection but no \`select\` seam is wired`);
804
- const query = evaluateTemplate(deps.transform, reflex.select.query, base);
805
- const rows = await collectRows(
806
- deps.select(query, { reflexId: reflex.id, now, actor: deps.actorFor(reflex.as), env: base }),
807
- deps.maxFanOut
808
- );
809
- if (reflex.select.mode === "batch") return [{ unit: "", env: { ...base, rows } }];
810
- return unitsFrom(rows, reflex.select.unitKey, base, reflex.id);
811
- };
812
-
813
689
  // src/engine/facts.ts
814
690
  var rootOf = async (store, cause) => {
815
691
  if (cause === void 0) return void 0;
@@ -863,6 +739,7 @@ var claimTasks = async (deps, now, limit, token) => {
863
739
  return deps.store.claim({
864
740
  table: "task",
865
741
  where: {
742
+ reflexId: { in: deps.reflexes().map((loaded) => loaded.reflex.id) },
866
743
  state: { in: ["pending", "retrying", "claimed"] },
867
744
  notBefore: { lte: now },
868
745
  claimedUntil: { lte: now }
@@ -875,7 +752,8 @@ var claimTasks = async (deps, now, limit, token) => {
875
752
  onePer: serialReflexIds.length === 0 ? void 0 : { column: "reflexId", held: { state: "claimed", claimedUntil: { gt: now } }, only: serialReflexIds }
876
753
  });
877
754
  };
878
- 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) => {
879
757
  const report = { executed: 0, succeeded: 0, failed: 0, retrying: 0, reclaimed: 0 };
880
758
  const lapsed = new Set(
881
759
  (await deps.store.query({
@@ -893,6 +771,7 @@ var executeTasks = async (deps, now, limit) => {
893
771
  }
894
772
  const loaded = deps.find(task.reflexId);
895
773
  if (loaded === void 0) continue;
774
+ if (!await leaseRenewed(deps, task, token, clock)) continue;
896
775
  const { reflex } = loaded;
897
776
  const registry = deps.effectsFor(reflex.as);
898
777
  const handler = registry[reflex.effect.name];
@@ -1019,29 +898,164 @@ var reopenTask = async (deps, taskId, now) => deps.store.transact(async (tx) =>
1019
898
  return true;
1020
899
  });
1021
900
  var settleRuns = async (deps, now) => {
1022
- const settled = await deps.store.claim({
901
+ const settled = await deps.store.query({
1023
902
  table: "run",
1024
903
  where: { state: "settled", drained: { ne: true } },
1025
904
  order: [{ by: "settledAt" }],
1026
- limit: 200,
1027
- set: { drained: true }
905
+ limit: 200
1028
906
  });
907
+ let drained = 0;
1029
908
  for (const run of settled) {
1030
- deps.emit({ type: "run.settled", run });
1031
- const admission = await admitFact(deps.store, {
1032
- kind: "run",
1033
- reflex: run.reflexId,
1034
- runId: run.id,
1035
- occurrence: run.occurrence,
1036
- stats: { total: run.total, done: run.done, failed: run.failed },
1037
- at: now,
1038
- depth: run.depth + 1,
1039
- cause: `run:${run.id}`,
1040
- as: run.as
1041
- }, 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 } });
1042
926
  announceFact(deps.emit, admission);
1043
927
  }
1044
- 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);
1045
1059
  };
1046
1060
 
1047
1061
  // src/engine/advance.ts
@@ -1052,7 +1066,7 @@ var runAdvance = async (deps, options) => {
1052
1066
  const clocks = await materializeClocks(deps, now);
1053
1067
  const matched = await matchFacts(deps, now, limit);
1054
1068
  const tasksCreated = await fanOut(deps, now, limit);
1055
- const executed = await executeTasks(deps, now, limit);
1069
+ const executed = await executeTasks(deps, now, limit, options.clock);
1056
1070
  const runsSettled = await settleRuns(deps, now);
1057
1071
  return {
1058
1072
  now,
@@ -1095,19 +1109,20 @@ var nextDue = async (deps, now) => {
1095
1109
  consider(delayed?.notBefore);
1096
1110
  const [run] = await deps.store.query({ table: "run", where: { state: "pending" }, order: [{ by: "dueAt" }], limit: 1 });
1097
1111
  consider(run?.dueAt);
1112
+ const loaded = { in: deps.reflexes().map((entry) => entry.reflex.id) };
1098
1113
  const [waiting] = await deps.store.query({
1099
1114
  table: "task",
1100
- where: { state: { in: ["pending", "retrying"] } },
1115
+ where: { reflexId: loaded, state: { in: ["pending", "retrying"] } },
1101
1116
  order: [{ by: "notBefore" }],
1102
1117
  limit: 1
1103
1118
  });
1104
1119
  consider(waiting?.notBefore);
1105
- 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 });
1106
1121
  consider(claimed?.claimedUntil);
1107
- for (const loaded of deps.reflexes()) {
1108
- const clock = clockOf(loaded.reflex.on);
1122
+ for (const loaded2 of deps.reflexes()) {
1123
+ const clock = clockOf(loaded2.reflex.on);
1109
1124
  if (clock !== void 0) {
1110
- const state = await stateOf(deps, loaded.reflex.id);
1125
+ const state = await stateOf(deps, loaded2.reflex.id);
1111
1126
  if (state?.materializedThrough === void 0) {
1112
1127
  consider(now);
1113
1128
  continue;
@@ -1188,6 +1203,20 @@ var DEFAULT_MAX_CHAIN_DEPTH = 24;
1188
1203
  var DEFAULT_MAX_CHAIN_FACTS = 1e4;
1189
1204
  var DEFAULT_MAX_FAN_OUT = 1e4;
1190
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
+ };
1191
1220
  var createTide = (config) => {
1192
1221
  const loaded = /* @__PURE__ */ new Map();
1193
1222
  let effectsCache;
@@ -1197,6 +1226,7 @@ var createTide = (config) => {
1197
1226
  return effectsCache;
1198
1227
  };
1199
1228
  let tokens = 0;
1229
+ let hasLoaded = false;
1200
1230
  const deps = {
1201
1231
  store: config.store,
1202
1232
  transform: config.transform,
@@ -1209,13 +1239,22 @@ var createTide = (config) => {
1209
1239
  leaseMs: config.leaseMs ?? DEFAULT_LEASE_MS,
1210
1240
  emit: config.onEvent ?? (() => void 0),
1211
1241
  reflexes: () => [...loaded.values()],
1242
+ hasLoaded: () => hasLoaded,
1212
1243
  find: (id) => loaded.get(id),
1213
1244
  nextToken: () => {
1214
1245
  tokens += 1;
1215
1246
  return `tok_${tokens.toString(36)}`;
1216
- }
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;
1217
1256
  };
1218
- const load = async (input, options) => {
1257
+ const loadNow = async (input, options) => {
1219
1258
  const { reflexes: parsed, graph, refused } = admitReflexes({ input, effectsOf: mergedEffects, isolate: options?.isolate === true });
1220
1259
  const previously = new Set(loaded.keys());
1221
1260
  const next = /* @__PURE__ */ new Map();
@@ -1223,13 +1262,19 @@ var createTide = (config) => {
1223
1262
  const stored = await stateOf(deps, reflex.id);
1224
1263
  const armedAt = stored?.armedAt ?? options?.at ?? 0;
1225
1264
  if (stored === void 0) await config.store.appendIfAbsent("state", { reflexId: reflex.id, armedAt });
1226
- 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)
1227
1267
  await config.store.cas("state", reflex.id, {}, { materializedThrough: Math.max(stored.materializedThrough, options.at) });
1228
1268
  next.set(reflex.id, { reflex, version: versionOf(reflex), armedAt });
1229
1269
  }
1230
1270
  loaded.clear();
1231
1271
  for (const [id, entry] of next) loaded.set(id, entry);
1232
- 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 };
1233
1278
  };
1234
1279
  const mergedEffects = (parsed) => {
1235
1280
  if (typeof config.effects !== "function") return config.effects ?? {};
@@ -1254,6 +1299,7 @@ var createTide = (config) => {
1254
1299
  throw new TideError("invalid_fact", `fact did not parse: ${result.error.issues.map((i) => i.message).join("; ")}`, {
1255
1300
  issues: result.error.issues
1256
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");
1257
1303
  if (!watchable(result.data)) return void 0;
1258
1304
  const admission = await admitFact(config.store, { ...result.data, cause: options?.cause, depth: options?.depth ?? 0, as: options?.as }, deps.maxChainFacts);
1259
1305
  announceFact(deps.emit, admission);
@@ -1313,13 +1359,12 @@ var createTide = (config) => {
1313
1359
  }),
1314
1360
  task: (id) => one("task", id),
1315
1361
  facts: async (filter) => {
1316
- const found = await config.store.query({
1317
- table: "fact",
1318
- order: [{ by: "at", dir: "desc" }],
1319
- limit: filter?.reflexId === void 0 ? filter?.limit : void 0
1320
- });
1321
- const matched = filter?.reflexId === void 0 ? found : found.filter((fact) => fact.reflex === filter.reflexId || fact.target === filter.reflexId);
1322
- 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);
1323
1368
  },
1324
1369
  fact: (id) => one("fact", id),
1325
1370
  causeChain,
@@ -1451,26 +1496,31 @@ var createMemoryStore = () => {
1451
1496
  spec.order
1452
1497
  );
1453
1498
  const taken = /* @__PURE__ */ new Set();
1454
- const restricted = new Set(spec.onePer?.only ?? []);
1499
+ const restricted = spec.onePer?.only ?? [];
1455
1500
  if (spec.onePer !== void 0) {
1456
1501
  for (const row of rowsOf(spec.table))
1457
1502
  if (matches(row, spec.onePer.held)) taken.add(String(row[spec.onePer.column]));
1458
1503
  }
1459
- 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
+ }
1460
1514
  for (const row of candidates) {
1461
- if (claimed.length >= spec.limit) break;
1462
- if (spec.onePer !== void 0) {
1463
- const group = String(row[spec.onePer.column]);
1464
- if (restricted.has(group)) {
1465
- if (taken.has(group)) continue;
1466
- taken.add(group);
1467
- }
1468
- }
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) => {
1469
1520
  const next = applied(row, spec.set);
1470
1521
  tables[spec.table].set(keyOf(spec.table, next), next);
1471
- claimed.push(next);
1472
- }
1473
- return claimed;
1522
+ return next;
1523
+ });
1474
1524
  };
1475
1525
  const cas = async (table, id, expect, set) => {
1476
1526
  const row = tables[table].get(id);
@@ -1532,7 +1582,7 @@ var createTideDriver = (config) => {
1532
1582
  let timer;
1533
1583
  const drain = async () => {
1534
1584
  for (let steps = 0; steps < MAX_STEPS_PER_DRAIN; steps += 1) {
1535
- const report = await tide.advance({ now: now() });
1585
+ const report = await tide.advance({ now: now(), clock: now });
1536
1586
  if (progressOf(report) === 0) return;
1537
1587
  }
1538
1588
  console.error(`[tide:driver] a drain exceeded ${MAX_STEPS_PER_DRAIN} steps \u2014 stopping this pass; the janitor will resume it`);