spur-board 0.21.1 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/daemon.mjs +307 -224
  2. package/package.json +3 -3
package/dist/daemon.mjs CHANGED
@@ -7720,9 +7720,11 @@ function checkGatewayStrings(strings) {
7720
7720
  }
7721
7721
  /**
7722
7722
  * Replays database-only work after scanning exact strings outside the write transaction.
7723
- * `fn` must build the same gateway strings on every pass: read a time that lands in one, such as
7724
- * an outbox payload, before the call, as a time read inside `fn` makes a new string each pass and
7725
- * the replay never ends. A time kept only in the database may be read inside.
7723
+ * `fn` must build the same gateway strings on every pass. Read a time that lands in one, such as
7724
+ * an outbox payload, before the call, or capture it once on the first pass, after the write lock,
7725
+ * and reuse it on every replay, as `runTick` in `sender.ts` does with the send-time token expiry.
7726
+ * A fresh time read on each pass makes a new string each pass and the replay never ends. A time
7727
+ * kept only in the database may be read inside.
7726
7728
  */
7727
7729
  async function scanTransaction(store, config, fn) {
7728
7730
  const known = /* @__PURE__ */ new Map();
@@ -7874,7 +7876,7 @@ async function writeDeniedEvent(trx, denial) {
7874
7876
  }
7875
7877
  //#endregion
7876
7878
  //#region ../core/src/app/commands.ts
7877
- const DAY_MS = 864e5;
7879
+ const DAY_MS$1 = 864e5;
7878
7880
  const TASKLESS = [
7879
7881
  "task.add",
7880
7882
  "item.retry",
@@ -7997,32 +7999,12 @@ function createApply(deps) {
7997
7999
  return result;
7998
8000
  };
7999
8001
  }
8000
- /**
8001
- * Purges expired command keys once at `start`, then every `DAY_MS`. A failed first purge
8002
- * rejects `start`; a failed daily purge goes to `onError`. `stop` waits for a running purge.
8003
- */
8004
- function commandRetention(deps) {
8005
- const { store, clock, retentionDays, onError } = deps;
8006
- let timer;
8007
- let running = Promise.resolve();
8008
- const run = async () => {
8009
- const cutoff = (/* @__PURE__ */ new Date(clock.now() - retentionDays * DAY_MS)).toISOString();
8010
- await store.transaction(async (trx) => {
8011
- await trx.deleteFrom("command").where("at", "<", cutoff).execute();
8012
- });
8013
- };
8014
- return {
8015
- async start() {
8016
- await run();
8017
- timer = setInterval(() => {
8018
- running = run().catch(onError);
8019
- }, DAY_MS);
8020
- },
8021
- async stop() {
8022
- clearInterval(timer);
8023
- await running;
8024
- }
8025
- };
8002
+ /** Deletes command keys older than `retentionDays`; a key exactly at the cutoff stays. */
8003
+ async function purgeExpiredCommands(store, clock, retentionDays) {
8004
+ const cutoff = (/* @__PURE__ */ new Date(clock.now() - retentionDays * DAY_MS$1)).toISOString();
8005
+ await store.transaction(async (trx) => {
8006
+ await trx.deleteFrom("command").where("at", "<", cutoff).execute();
8007
+ });
8026
8008
  }
8027
8009
  //#endregion
8028
8010
  //#region ../core/src/app/queries.ts
@@ -8738,6 +8720,18 @@ async function expireToken(trx, row, at) {
8738
8720
  await journalToken(trx, "token_expired", row.name, at);
8739
8721
  await clearItem(trx, row.item_id, at);
8740
8722
  }
8723
+ /**
8724
+ * Lapses the pending request whose approval item is `itemId` once it has expired at `at`. The
8725
+ * sender calls it before posting the approval line, so a late or failing sweep cannot post it.
8726
+ */
8727
+ async function expireTokenOfItem(trx, itemId, at) {
8728
+ const row = await trx.selectFrom("operator_token").select([
8729
+ "id",
8730
+ "name",
8731
+ "item_id"
8732
+ ]).where("item_id", "=", itemId).where("status", "=", "pending").where("expires_at", "<=", at.toISOString()).executeTakeFirst();
8733
+ if (row !== void 0) await expireToken(trx, row, at);
8734
+ }
8741
8735
  /** Register a hash and its approval item together. The raw file secret never reaches this app. */
8742
8736
  async function requestToken(store, config, input, at) {
8743
8737
  if (!/^[0-9a-f]{64}$/.test(input.hash) || input.name.trim() === "" || input.folder.trim() === "") throw new CommandError("usage", "Provide a name, folder and SHA-256 token hash.");
@@ -9231,8 +9225,9 @@ async function restartNotification(trx, sourceKey, at) {
9231
9225
  /**
9232
9226
  * Ends a ring Spur will not take (a permanent rejection, or no answer for the retry window): its
9233
9227
  * notification stops ringing, the operator gets an item and `doorbell_undelivered` is journalled.
9234
- * The operator's Retry on the item restarts the series (`restartNotification`). An inbound author
9235
- * ring has no notification: it ends like an author found unavailable at enqueue.
9228
+ * The operator's Retry on the item restarts the series (`restartNotification`). A ring that is no
9229
+ * longer its notification's last row (the recipient changed while it was in flight) ends alone. An
9230
+ * inbound author ring has no notification: it ends like an author found unavailable at enqueue.
9236
9231
  */
9237
9232
  async function ringUndelivered(trx, input) {
9238
9233
  const { at, reason } = input;
@@ -9255,7 +9250,7 @@ async function ringUndelivered(trx, input) {
9255
9250
  return;
9256
9251
  }
9257
9252
  const n = await trx.selectFrom("notification").selectAll().where("id", "=", input.notificationId).executeTakeFirst();
9258
- if (n === void 0 || n.acked_at !== null || n.exhausted_at !== null) return;
9253
+ if (n === void 0 || n.acked_at !== null || n.exhausted_at !== null || n.last_outbox_id !== input.outboxId) return;
9259
9254
  const task = await trx.selectFrom("task").selectAll().where("id", "=", n.task_id).executeTakeFirstOrThrow();
9260
9255
  await trx.updateTable("notification").set({ exhausted_at: at.toISOString() }).where("id", "=", n.id).execute();
9261
9256
  await raiseItem(trx, {
@@ -9272,9 +9267,21 @@ async function ringUndelivered(trx, input) {
9272
9267
  reason
9273
9268
  }, at);
9274
9269
  }
9275
- /** Reconcile due semantic notifications in the sender's claim transaction. */
9270
+ /** Notifications reconcile looks at: unacked, not exhausted, due, on a task not archived. */
9271
+ function dueNotifications(db, at) {
9272
+ return db.selectFrom("notification").innerJoin("task", "task.id", "notification.task_id").where("task.membership", "!=", "archived").where("notification.acked_at", "is", null).where("notification.exhausted_at", "is", null).where("notification.next_at", "<=", at.toISOString());
9273
+ }
9274
+ /**
9275
+ * Reconciles due notifications in their own transaction. With none due it opens no transaction;
9276
+ * a due notification waiting on a working recipient or an unsent ring still opens one.
9277
+ */
9278
+ async function reconcileDueDoorbells(store, config, at) {
9279
+ if (await dueNotifications(store.db, at).select("notification.id").executeTakeFirst() === void 0) return;
9280
+ await scanTransaction(store, config, (trx) => reconcileDoorbells(trx, at, config));
9281
+ }
9282
+ /** Reconcile due semantic notifications in the caller's transaction. */
9276
9283
  async function reconcileDoorbells(trx, at, config) {
9277
- const due = await trx.selectFrom("notification").innerJoin("task", "task.id", "notification.task_id").selectAll("notification").where("task.membership", "!=", "archived").where("notification.acked_at", "is", null).where("notification.exhausted_at", "is", null).where("notification.next_at", "<=", at.toISOString()).orderBy("notification.id").execute();
9284
+ const due = await dueNotifications(trx, at).selectAll("notification").orderBy("notification.id").execute();
9278
9285
  for (const n of due) {
9279
9286
  const session = await selectNotificationRecipient(trx, n);
9280
9287
  if (session === void 0) {
@@ -10302,7 +10309,6 @@ function createSender(options) {
10302
10309
  async function claim(trx, at) {
10303
10310
  const nowIso = new Date(at).toISOString();
10304
10311
  await releaseOrphans(trx, nowIso);
10305
- await reconcileDoorbells(trx, new Date(at), options.config);
10306
10312
  const rows = await trx.selectFrom("outbox").selectAll().where("state", "in", ["pending", "post_failed"]).orderBy("id").execute();
10307
10313
  const bodies = /* @__PURE__ */ new Map();
10308
10314
  for (const row of rows) {
@@ -10396,11 +10402,15 @@ function createSender(options) {
10396
10402
  * Stamps the start of a send, just before its IO: the row's retry window if none is open and,
10397
10403
  * for a space, the slot of the next send and, under a health row, the probe clock. A slow
10398
10404
  * earlier send in the tick does not age them. The clock is read here, once the write lock is
10399
- * held, so waiting for the lock does not age them either. Returns the stamp.
10405
+ * held, so waiting for the lock does not age them either. Returns the stamp. `expiredAt` is
10406
+ * read once, on the first pass after the lock is held, and reused on replays: token expiry
10407
+ * writes it into a feed edit, a gateway string, so a fresh read per pass would change it on
10408
+ * every scan replay, and a read before the lock would miss a request that lapses meanwhile.
10400
10409
  */
10401
- async function start(trx, c) {
10410
+ async function start(trx, c, expiredAt) {
10402
10411
  const at = now().getTime();
10403
10412
  const sentAtIso = new Date(at).toISOString();
10413
+ if (c.body.kind === "feed.line" && c.body.payload.itemId !== void 0) await expireTokenOfItem(trx, c.body.payload.itemId, expiredAt);
10404
10414
  if (c.body.kind === "feed.line" && c.body.payload.itemId !== void 0 && !c.maybeSent) {
10405
10415
  const item = await trx.selectFrom("operator_item").select("cleared_at").where("id", "=", c.body.payload.itemId).executeTakeFirst();
10406
10416
  if (item !== void 0 && item.cleared_at !== null) {
@@ -10543,6 +10553,7 @@ function createSender(options) {
10543
10553
  if (body.kind !== "doorbell") return;
10544
10554
  await ringUndelivered(trx, {
10545
10555
  notificationId: body.payload.notificationId,
10556
+ outboxId: c.id,
10546
10557
  dedupeKey: c.key,
10547
10558
  session: body.payload.session,
10548
10559
  reason,
@@ -10669,7 +10680,8 @@ function createSender(options) {
10669
10680
  })).where("id", "in", ids).where("state", "=", "in_flight").execute());
10670
10681
  return;
10671
10682
  }
10672
- const started = await scanTransaction(store, options.config, (trx) => start(trx, c));
10683
+ let expiredAt;
10684
+ const started = await scanTransaction(store, options.config, (trx) => start(trx, c, expiredAt ??= now()));
10673
10685
  if (started.skip) continue;
10674
10686
  const { outcome, error } = await attempt(c, started.firstDeliveryAt);
10675
10687
  const at = now().getTime();
@@ -12466,10 +12478,23 @@ function createObservationCore(deps) {
12466
12478
  };
12467
12479
  }
12468
12480
  //#endregion
12469
- //#region ../core/src/app/tick.ts
12470
- function lastArchiveSlot(now, config) {
12481
+ //#region ../core/src/domain/slot.ts
12482
+ const WEEKDAYS = [
12483
+ "sunday",
12484
+ "monday",
12485
+ "tuesday",
12486
+ "wednesday",
12487
+ "thursday",
12488
+ "friday",
12489
+ "saturday"
12490
+ ];
12491
+ /**
12492
+ * The UTC instant of local midnight on the latest `weekday` at or before `now` in `tz`.
12493
+ * A day that starts at `now` counts as today.
12494
+ */
12495
+ function lastLocalSlot(now, tz, weekday) {
12471
12496
  const formatter = new Intl.DateTimeFormat("en-US", {
12472
- timeZone: config.digest.tz,
12497
+ timeZone: tz,
12473
12498
  year: "numeric",
12474
12499
  month: "2-digit",
12475
12500
  day: "2-digit"
@@ -12484,15 +12509,7 @@ function lastArchiveSlot(now, config) {
12484
12509
  };
12485
12510
  const [year = 0, month = 0, day = 0] = localDate(now).split("-").map(Number);
12486
12511
  const localMidnight = Date.UTC(year, month - 1, day);
12487
- const targetUtcDate = localMidnight - (new Date(localMidnight).getUTCDay() - [
12488
- "sunday",
12489
- "monday",
12490
- "tuesday",
12491
- "wednesday",
12492
- "thursday",
12493
- "friday",
12494
- "saturday"
12495
- ].indexOf(config.archive.doneWeekday) + 7) % 7 * 864e5;
12512
+ const targetUtcDate = localMidnight - (new Date(localMidnight).getUTCDay() - WEEKDAYS.indexOf(weekday) + 7) % 7 * 864e5;
12496
12513
  const targetDate = new Date(targetUtcDate).toISOString().slice(0, 10);
12497
12514
  let lower = targetUtcDate - 2 * 864e5;
12498
12515
  let upper = targetUtcDate + 2 * 864e5;
@@ -12503,12 +12520,14 @@ function lastArchiveSlot(now, config) {
12503
12520
  }
12504
12521
  return lower;
12505
12522
  }
12523
+ //#endregion
12524
+ //#region ../core/src/app/tick.ts
12506
12525
  /** One board tick, including an archive slot missed during downtime. */
12507
12526
  async function tickBoard(deps) {
12508
12527
  const { store, config, clock, completeSince } = deps;
12509
12528
  const now = clock.now();
12510
12529
  const at = new Date(now).toISOString();
12511
- const slot = new Date(lastArchiveSlot(now, config)).toISOString();
12530
+ const slot = new Date(lastLocalSlot(now, config.digest.tz, config.archive.doneWeekday)).toISOString();
12512
12531
  await scanTransaction(store, config, async (trx) => {
12513
12532
  const sourceStates = await trx.selectFrom("source_state").select(["source", "blind_reason"]).execute();
12514
12533
  const blind = new Set(sourceStates.filter((source) => source.blind_reason !== null).map((source) => source.source));
@@ -13535,6 +13554,7 @@ async function runDaemon(deps) {
13535
13554
  code = 1;
13536
13555
  } finally {
13537
13556
  lock.release();
13557
+ clearTimeout(timer);
13538
13558
  finish(code);
13539
13559
  }
13540
13560
  }
@@ -13742,9 +13762,11 @@ function pageQuery(connection, bootstrap = false) {
13742
13762
  }
13743
13763
  var GithubClient = class {
13744
13764
  token;
13765
+ now;
13745
13766
  fetcher;
13746
- constructor(token, fetcher = fetch) {
13767
+ constructor(token, now, fetcher = fetch) {
13747
13768
  this.token = token;
13769
+ this.now = now;
13748
13770
  this.fetcher = fetcher;
13749
13771
  }
13750
13772
  async query(query, variables, signal) {
@@ -13771,7 +13793,7 @@ var GithubClient = class {
13771
13793
  status: response.status,
13772
13794
  headers: response.headers,
13773
13795
  body: await response.text()
13774
- }, Date.now());
13796
+ }, this.now());
13775
13797
  let body;
13776
13798
  try {
13777
13799
  body = await response.json();
@@ -13783,7 +13805,7 @@ var GithubClient = class {
13783
13805
  if (errors.some((error) => error.type === "RATE_LIMITED" || /rate limit/i.test(error.message))) throw classifyHttpFailure({
13784
13806
  status: 429,
13785
13807
  headers: response.headers
13786
- }, Date.now());
13808
+ }, this.now());
13787
13809
  if (errors.some((error) => teamScopeDenied(error, query))) throw new AdapterError("auth", "GitHub token needs read:org for team review requests");
13788
13810
  if (errors.some((error) => error.type === "INSUFFICIENT_SCOPES")) throw new AdapterError("auth", "GitHub token lacks a required GraphQL read scope");
13789
13811
  const data = parseWire(dataWire, wire.data, MALFORMED$3, ["data"]);
@@ -14170,7 +14192,7 @@ function githubSources(config, options) {
14170
14192
  if (seen.has(normalized)) throw new AdapterError("config", "Duplicate GitHub repository in project");
14171
14193
  seen.add(normalized);
14172
14194
  const id = sourceId(project.id, repo);
14173
- const client = new GithubClient(options.token, options.fetch);
14195
+ const client = new GithubClient(options.token, options.now, options.fetch);
14174
14196
  const keys = projectKeyRule(project.tracker, project.link, repo);
14175
14197
  sources.push({
14176
14198
  repo,
@@ -14184,6 +14206,7 @@ function githubSources(config, options) {
14184
14206
  login: project.operatorGithubLogin,
14185
14207
  keys,
14186
14208
  client,
14209
+ now: options.now,
14187
14210
  ctx
14188
14211
  })
14189
14212
  }
@@ -14291,8 +14314,8 @@ async function fullPr(client, first, owner, name, number, signal, budget) {
14291
14314
  pr
14292
14315
  };
14293
14316
  }
14294
- async function pollRepository({ id, repo, login, keys, client, ctx }) {
14295
- const observedAt = sourceCursorSchema.parse((/* @__PURE__ */ new Date()).toISOString());
14317
+ async function pollRepository({ id, repo, login, keys, client, now, ctx }) {
14318
+ const observedAt = sourceCursorSchema.parse(new Date(now()).toISOString());
14296
14319
  const bootstrap = ctx.cursor === void 0;
14297
14320
  const [owner, name] = repo.split("/");
14298
14321
  if (!owner || !name) throw new AdapterError("config", "Invalid repository");
@@ -14516,7 +14539,7 @@ function createGithubIssuesAdapter(options) {
14516
14539
  status: response.status,
14517
14540
  headers: response.headers,
14518
14541
  body: await response.text()
14519
- }, Date.now());
14542
+ }, options.now());
14520
14543
  throw new GithubIssuesHttpError(response.status, failure);
14521
14544
  }
14522
14545
  let value;
@@ -14603,7 +14626,7 @@ function createGithubIssuesAdapter(options) {
14603
14626
  id: options.id,
14604
14627
  intervalMs: options.intervalMs,
14605
14628
  async poll(ctx) {
14606
- const observedAt = (/* @__PURE__ */ new Date()).toISOString();
14629
+ const observedAt = new Date(options.now()).toISOString();
14607
14630
  const milestone = await milestoneNumber(ctx.signal);
14608
14631
  const filter = new URL(`${root}/issues`);
14609
14632
  filter.searchParams.set("state", "open");
@@ -14804,7 +14827,7 @@ function createJiraAdapter(options) {
14804
14827
  if (!response.ok) throw new JiraHttpError(response.status, classifyHttpFailure({
14805
14828
  status: response.status,
14806
14829
  headers: response.headers
14807
- }, Date.now()));
14830
+ }, options.now()));
14808
14831
  try {
14809
14832
  return await response.json();
14810
14833
  } catch {
@@ -14924,7 +14947,7 @@ function createJiraAdapter(options) {
14924
14947
  if (fallbackRequests >= FALLBACK_REQUEST_LIMIT) throw new AdapterError("transient", "Jira key lookup fallback request limit reached");
14925
14948
  fallbackRequests += 1;
14926
14949
  };
14927
- const observedAt = (/* @__PURE__ */ new Date()).toISOString();
14950
+ const observedAt = new Date(options.now()).toISOString();
14928
14951
  const tracker = options.tracker();
14929
14952
  await validate(tracker, ctx.signal);
14930
14953
  const sprintField = await findSprintField(tracker, ctx.signal);
@@ -15107,7 +15130,7 @@ function applyEntityOutcomes(input) {
15107
15130
  //#endregion
15108
15131
  //#region ../adapters/src/runner/runner.ts
15109
15132
  function startRunner(options) {
15110
- const startedAt = (options.now ?? Date.now)();
15133
+ const startedAt = options.now();
15111
15134
  const sources = options.entries.map((entry) => runSource(entry, options, startedAt));
15112
15135
  return {
15113
15136
  firstAttempts: Promise.all(sources.map(async (source) => ({
@@ -15122,7 +15145,7 @@ function startRunner(options) {
15122
15145
  function runSource(entry, options, runnerStartMs) {
15123
15146
  const { adapter, reserveRemaining } = entry;
15124
15147
  const { core, config } = options;
15125
- const now = options.now ?? Date.now;
15148
+ const { now } = options;
15126
15149
  const source = adapter.id;
15127
15150
  const { intervalMs } = adapter;
15128
15151
  const { staleMultiplier } = config.thresholds;
@@ -15479,12 +15502,12 @@ function createSpurAdapter(options) {
15479
15502
  id: "spur",
15480
15503
  intervalMs: options.intervalMs,
15481
15504
  async poll(ctx) {
15482
- const observedAt = (/* @__PURE__ */ new Date()).toISOString();
15505
+ const observedAt = new Date(options.now()).toISOString();
15483
15506
  const { response: listResponse, body: listBody } = await request("sessions", ctx.signal);
15484
15507
  if (!listResponse.ok) throw classifyHttpFailure({
15485
15508
  status: listResponse.status,
15486
15509
  headers: listResponse.headers
15487
- }, Date.now());
15510
+ }, options.now());
15488
15511
  const listed = parseWire(z.array(sessionWire), listBody, "Invalid Spur response");
15489
15512
  const byId = new Map(listed.map((wire) => [wire.id, wire]));
15490
15513
  const detail = /* @__PURE__ */ new Map();
@@ -15498,7 +15521,7 @@ function createSpurAdapter(options) {
15498
15521
  if (!response.ok) throw classifyHttpFailure({
15499
15522
  status: response.status,
15500
15523
  headers: response.headers
15501
- }, Date.now());
15524
+ }, options.now());
15502
15525
  const wire = parseWire(sessionWire, body, "Invalid Spur response");
15503
15526
  if (wire.id !== ref.id) throw new AdapterError("transient", "Unresolved Spur session detail");
15504
15527
  detail.set(ref.id, wire);
@@ -15591,12 +15614,12 @@ function sampleQuery(closing) {
15591
15614
  * reference is dropped, as the poller does; any other GraphQL error rejects with a transient
15592
15615
  * `AdapterError`.
15593
15616
  */
15594
- async function sampleLinkRules({ repo, login, tracker, link }, { token, fetch: fetcher, signal }) {
15617
+ async function sampleLinkRules({ repo, login, tracker, link }, { token, now, fetch: fetcher, signal }) {
15595
15618
  const [owner, name] = repo.split("/");
15596
15619
  if (!owner || !name) throw new AdapterError("config", "Invalid repository");
15597
15620
  const rule = projectKeyRule(tracker, link, repo);
15598
15621
  const closing = rule.type === "issues" && rule.sources.includes("closing");
15599
- const response = await new GithubClient(token, fetcher).query(sampleQuery(closing), {
15622
+ const response = await new GithubClient(token, now, fetcher).query(sampleQuery(closing), {
15600
15623
  owner,
15601
15624
  repo: name
15602
15625
  }, signal);
@@ -15622,7 +15645,7 @@ function blindSource(id, intervalMs, message) {
15622
15645
  };
15623
15646
  }
15624
15647
  /** Starts polling each configured source. */
15625
- function startAdapters(config, core, options = {}) {
15648
+ function startAdapters(config, core, options) {
15626
15649
  const secrets = options.secrets ?? {};
15627
15650
  const githubToken = secrets["GITHUB_TOKEN"];
15628
15651
  const entries = [];
@@ -15638,6 +15661,7 @@ function startAdapters(config, core, options = {}) {
15638
15661
  email,
15639
15662
  token
15640
15663
  },
15664
+ now: options.now,
15641
15665
  intervalMs: config.adapters.jira.intervalMs,
15642
15666
  ...options.fetch === void 0 ? {} : { fetch: options.fetch },
15643
15667
  warn: options.warn ?? (() => void 0),
@@ -15649,12 +15673,14 @@ function startAdapters(config, core, options = {}) {
15649
15673
  id,
15650
15674
  tracker: project.tracker,
15651
15675
  token: githubToken,
15676
+ now: options.now,
15652
15677
  intervalMs: config.adapters.github.intervalMs,
15653
15678
  ...options.fetch === void 0 ? {} : { fetch: options.fetch }
15654
15679
  }) : blindSource(id, config.adapters.github.intervalMs, "GitHub credential is missing") });
15655
15680
  }
15656
15681
  if (githubToken) entries.push(...githubSources(config, {
15657
15682
  token: githubToken,
15683
+ now: options.now,
15658
15684
  ...options.fetch === void 0 ? {} : { fetch: options.fetch }
15659
15685
  }).map(({ adapter, reserveRemaining, repo }) => ({
15660
15686
  adapter,
@@ -15668,6 +15694,7 @@ function startAdapters(config, core, options = {}) {
15668
15694
  baseUrl: config.adapters.spur.baseUrl,
15669
15695
  intervalMs: config.adapters.spur.intervalMs,
15670
15696
  flipSmoothingMs: config.health.flipSmoothingMs,
15697
+ now: options.now,
15671
15698
  ...options.fetch === void 0 ? {} : { fetch: options.fetch },
15672
15699
  onNotice: (notice) => {
15673
15700
  const pending = Promise.resolve().then(() => options.onSpurNotice?.(notice));
@@ -15678,7 +15705,7 @@ function startAdapters(config, core, options = {}) {
15678
15705
  }) }],
15679
15706
  core,
15680
15707
  config,
15681
- ...options.now === void 0 ? {} : { now: options.now },
15708
+ now: options.now,
15682
15709
  ...options.oneShot === void 0 ? {} : { oneShot: options.oneShot },
15683
15710
  onFailure: options.onPollFailure
15684
15711
  });
@@ -16469,9 +16496,19 @@ function record(value) {
16469
16496
  function string(value) {
16470
16497
  return typeof value === "string" ? value : void 0;
16471
16498
  }
16499
+ /** Milliseconds of a Slack ts, read from its digits so float error cannot shift the millisecond. */
16500
+ function tsMillis(ts) {
16501
+ const [seconds = "", fraction = ""] = ts.split(".");
16502
+ if (!/^\d+$/.test(seconds) || !/^\d*$/.test(fraction)) return NaN;
16503
+ return Number(seconds) * 1e3 + Number(fraction.padEnd(3, "0").slice(0, 3));
16504
+ }
16505
+ /**
16506
+ * The bounds are clock readings in whole milliseconds, so a message counts by its millisecond:
16507
+ * one posted later within the millisecond `until` was read in is still inside the window.
16508
+ */
16472
16509
  function inInterval(ts, from, until) {
16473
16510
  if (ts === void 0) return false;
16474
- const at = Number(ts) * 1e3;
16511
+ const at = tsMillis(ts);
16475
16512
  return Number.isFinite(at) && at >= from && at <= until;
16476
16513
  }
16477
16514
  async function readThread(client, channel, threadTs) {
@@ -16494,8 +16531,8 @@ function gap(conversation) {
16494
16531
  };
16495
16532
  }
16496
16533
  /** A scan is driven solely by its request; the core owns cursors and deduplication. */
16497
- async function* recoverThreads(client, request, botIdentity) {
16498
- const until = Date.now();
16534
+ async function* recoverThreads(client, request, botIdentity, now) {
16535
+ const until = now();
16499
16536
  const from = request.since.getTime();
16500
16537
  if (!Number.isFinite(from) || from > until) return;
16501
16538
  const bot = await botIdentity();
@@ -16694,7 +16731,7 @@ function createSlackGateway(config) {
16694
16731
  return {
16695
16732
  ...delivery,
16696
16733
  ...socket,
16697
- recover: (request) => recoverThreads(api, request, botIdentity),
16734
+ recover: (request) => recoverThreads(api, request, botIdentity, config.now),
16698
16735
  async respond(interaction, text, options) {
16699
16736
  const addressed = parseInteractionRef(interaction);
16700
16737
  const rendered = renderResponse(text, options.cliHint);
@@ -16721,8 +16758,67 @@ function createSlackGateway(config) {
16721
16758
  };
16722
16759
  }
16723
16760
  //#endregion
16761
+ //#region ../daemon/src/scheduler.ts
16762
+ /**
16763
+ * One recurring job: a `setTimeout` chain armed `intervalMs` plus under `jitterMs` after each
16764
+ * timer run settles. Runs never overlap; `trigger` queues behind the active run. A failed run goes
16765
+ * to `onError`, except a failed `first: 'await'` run, which rejects `start` and arms no timer. A
16766
+ * failing `onError` is dropped, so the chain keeps running.
16767
+ * `stop` clears the timer and awaits the active run; after it, and once the start signal aborts,
16768
+ * nothing new runs. Uses the global timers so `vi.useFakeTimers` controls it.
16769
+ */
16770
+ function createJob(options) {
16771
+ const { run, intervalMs, jitterMs = 0, first = "background", onError } = options;
16772
+ let timer;
16773
+ let active = Promise.resolve();
16774
+ let stopped = false;
16775
+ let signal;
16776
+ const idle = () => stopped || signal === void 0 || signal.aborted;
16777
+ const enqueue = () => {
16778
+ if (idle()) return active;
16779
+ active = active.then(async () => {
16780
+ if (signal !== void 0 && !idle()) await run(signal);
16781
+ }).catch(async (err) => {
16782
+ await onError(err);
16783
+ }).catch(() => void 0);
16784
+ return active;
16785
+ };
16786
+ const schedule = () => {
16787
+ if (idle()) return;
16788
+ const delay = intervalMs + Math.floor(Math.random() * jitterMs);
16789
+ timer = setTimeout(() => {
16790
+ timer = void 0;
16791
+ enqueue().then(schedule);
16792
+ }, delay);
16793
+ };
16794
+ return {
16795
+ async start(startSignal) {
16796
+ signal = startSignal;
16797
+ if (first === "background") {
16798
+ enqueue().then(schedule);
16799
+ return;
16800
+ }
16801
+ if (idle()) return;
16802
+ const firstRun = run(startSignal);
16803
+ active = firstRun.then(() => void 0, () => void 0);
16804
+ await firstRun;
16805
+ schedule();
16806
+ },
16807
+ async stop() {
16808
+ stopped = true;
16809
+ clearTimeout(timer);
16810
+ await active;
16811
+ },
16812
+ trigger: enqueue,
16813
+ settled: () => active
16814
+ };
16815
+ }
16816
+ //#endregion
16724
16817
  //#region ../daemon/src/board-modules.ts
16725
- /** Compose the board's timer and adapter runner without adding lifecycle state to main. */
16818
+ /**
16819
+ * Compose the board's timer and adapter runner without adding lifecycle state to main. `tick`
16820
+ * runs the board-core job once more behind its active run and resolves when that run settles.
16821
+ */
16726
16822
  function createBoardModules(ctxFor, options = {}) {
16727
16823
  const coreCtx = ctxFor("board-core");
16728
16824
  const adapterCtx = ctxFor("board-adapters");
@@ -16731,79 +16827,64 @@ function createBoardModules(ctxFor, options = {}) {
16731
16827
  config: coreCtx.config,
16732
16828
  clock: coreCtx.clock
16733
16829
  });
16734
- let timer;
16735
- let active = Promise.resolve();
16736
- let stopped = false;
16737
- let signal;
16738
16830
  const tick = options.tick ?? tickBoard;
16739
- const schedule = () => {
16740
- if (stopped || signal?.aborted) return;
16741
- timer = setTimeout(() => {
16742
- timer = void 0;
16743
- runTick();
16744
- }, BOARD_TICK_MS);
16745
- };
16746
- const runTick = () => {
16747
- if (stopped || signal?.aborted) return;
16748
- active = Promise.resolve().then(() => tick({
16749
- store: coreCtx.store,
16750
- config: coreCtx.config,
16751
- clock: coreCtx.clock,
16752
- completeSince: core.completeSince
16753
- })).then(() => options.onTick?.()).catch((err) => {
16831
+ const boardCore = createJob({
16832
+ run: async () => {
16833
+ await tick({
16834
+ store: coreCtx.store,
16835
+ config: coreCtx.config,
16836
+ clock: coreCtx.clock,
16837
+ completeSince: core.completeSince
16838
+ });
16839
+ options.onTick?.();
16840
+ },
16841
+ intervalMs: BOARD_TICK_MS,
16842
+ onError: (err) => {
16754
16843
  coreCtx.log.error({ err }, "board tick failed");
16755
- }).finally(schedule);
16756
- };
16757
- let runner;
16758
- return [{
16759
- name: "board-core",
16760
- stopStage: "final",
16761
- module: {
16762
- start(startSignal) {
16763
- signal = startSignal;
16764
- runTick();
16765
- return Promise.resolve();
16766
- },
16767
- async stop() {
16768
- stopped = true;
16769
- if (timer !== void 0) clearTimeout(timer);
16770
- await active;
16771
- }
16772
16844
  }
16773
- }, {
16774
- name: "board-adapters",
16775
- stopStage: "pollers",
16776
- module: {
16777
- async start(startSignal) {
16778
- const adapterOptions = {
16779
- secrets: adapterCtx.secrets,
16780
- now: () => adapterCtx.clock.now(),
16781
- fetch: (url, init) => adapterCtx.logCall("adapter.fetch", () => fetch(url, init)),
16782
- warn: (message) => {
16783
- adapterCtx.log.warn({ message }, "adapter warning");
16784
- },
16785
- onPollFailure: ({ source, step, kind, error, issues }) => {
16786
- adapterCtx.log.warn({
16787
- source,
16788
- step,
16789
- kind,
16790
- err: error,
16791
- ...issues === void 0 ? {} : { issues }
16792
- }, "adapter poll failed");
16793
- },
16794
- onSpurNotice: async (notice) => {
16795
- if (notice.kind === "restart") adapterCtx.log.info("spur restarted");
16796
- else await core.notice(notice.kind, notice.value);
16797
- }
16798
- };
16799
- runner = (options.startAdapters ?? startAdapters)(adapterCtx.config, core, adapterOptions);
16800
- if (startSignal.aborted) await runner.stop();
16801
- },
16802
- async stop() {
16803
- await runner?.stop();
16845
+ });
16846
+ let runner;
16847
+ return {
16848
+ entries: [{
16849
+ name: "board-core",
16850
+ stopStage: "final",
16851
+ module: boardCore
16852
+ }, {
16853
+ name: "board-adapters",
16854
+ stopStage: "pollers",
16855
+ module: {
16856
+ async start(startSignal) {
16857
+ const adapterOptions = {
16858
+ secrets: adapterCtx.secrets,
16859
+ now: () => adapterCtx.clock.now(),
16860
+ fetch: (url, init) => adapterCtx.logCall("adapter.fetch", () => fetch(url, init)),
16861
+ warn: (message) => {
16862
+ adapterCtx.log.warn({ message }, "adapter warning");
16863
+ },
16864
+ onPollFailure: ({ source, step, kind, error, issues }) => {
16865
+ adapterCtx.log.warn({
16866
+ source,
16867
+ step,
16868
+ kind,
16869
+ err: error,
16870
+ ...issues === void 0 ? {} : { issues }
16871
+ }, "adapter poll failed");
16872
+ },
16873
+ onSpurNotice: async (notice) => {
16874
+ if (notice.kind === "restart") adapterCtx.log.info("spur restarted");
16875
+ else await core.notice(notice.kind, notice.value);
16876
+ }
16877
+ };
16878
+ runner = (options.startAdapters ?? startAdapters)(adapterCtx.config, core, adapterOptions);
16879
+ if (startSignal.aborted) await runner.stop();
16880
+ },
16881
+ async stop() {
16882
+ await runner?.stop();
16883
+ }
16804
16884
  }
16805
- }
16806
- }];
16885
+ }],
16886
+ tick: () => boardCore.trigger()
16887
+ };
16807
16888
  }
16808
16889
  //#endregion
16809
16890
  //#region ../daemon/src/spur-port.ts
@@ -16864,7 +16945,7 @@ function createSpurPort(options) {
16864
16945
  }
16865
16946
  //#endregion
16866
16947
  //#region ../daemon/src/doctor.ts
16867
- const TIMEOUT_MS = 5e3;
16948
+ const DEADLINE_MS = 5e3;
16868
16949
  const SPUR_PROBE_SESSION = "spur-board-doctor-probe";
16869
16950
  const SPUR_SEND_UNREACHABLE_FIX = "Start Spur or correct adapters.spur.baseUrl in config.yaml, then restart the service; the daemon sends doorbells to that Spur API.";
16870
16951
  const SPUR_SEND_FIX = "The Spur API at adapters.spur.baseUrl did not accept a doorbell send; update Spur or point adapters.spur.baseUrl at the Spur daemon.";
@@ -16901,11 +16982,11 @@ function scopedGithubError(value) {
16901
16982
  if (error?.["type"] === "INSUFFICIENT_SCOPES" && fields.includes("reviewRequests") && fields.includes("requestedReviewer") && fields.includes("slug")) return GITHUB_TEAMS_FIX;
16902
16983
  return null;
16903
16984
  }
16904
- async function deadlineCall(ctx, name, failure, call) {
16985
+ async function deadlineCall(ctx, deadlineMs, name, failure, call) {
16905
16986
  const controller = new AbortController();
16906
16987
  const deadline = setTimeout(() => {
16907
16988
  controller.abort();
16908
- }, TIMEOUT_MS);
16989
+ }, deadlineMs);
16909
16990
  const aborted = new Promise((_resolve, reject) => {
16910
16991
  controller.signal.addEventListener("abort", () => {
16911
16992
  reject(/* @__PURE__ */ new Error(`${failure}: timed out`));
@@ -16925,10 +17006,10 @@ async function deadlineCall(ctx, name, failure, call) {
16925
17006
  clearTimeout(deadline);
16926
17007
  }
16927
17008
  }
16928
- async function githubGraphql(ctx, fetcher, token, repo) {
17009
+ async function githubGraphql(ctx, fetcher, deadlineMs, token, repo) {
16929
17010
  const [owner, name] = repo.split("/");
16930
17011
  if (!owner || !name) return null;
16931
- return deadlineCall(ctx, "doctor.github", "GitHub doctor probe failed", async (signal) => {
17012
+ return deadlineCall(ctx, deadlineMs, "doctor.github", "GitHub doctor probe failed", async (signal) => {
16932
17013
  const response = await fetcher("https://api.github.com/graphql", {
16933
17014
  method: "POST",
16934
17015
  headers: {
@@ -16956,19 +17037,20 @@ const BRANCH_MAX = 40;
16956
17037
  const NAMED_PRS = 3;
16957
17038
  const LINK_RULES_TAIL = "Change projects[].link to the repo's branch and PR title rules.";
16958
17039
  const LINK_RULES_TOKEN_FIX = "Add GITHUB_TOKEN to secrets.env, then rerun board doctor to compare projects[].link with recent PRs.";
16959
- function sampleProject(ctx, fetcher, token, project, repo) {
16960
- return deadlineCall(ctx, "doctor.link_rules", "GitHub link sample failed", (signal) => sampleLinkRules({
17040
+ function sampleProject(ctx, fetcher, deadlineMs, token, project, repo) {
17041
+ return deadlineCall(ctx, deadlineMs, "doctor.link_rules", "GitHub link sample failed", (signal) => sampleLinkRules({
16961
17042
  repo,
16962
17043
  login: project.operatorGithubLogin,
16963
17044
  tracker: project.tracker,
16964
17045
  link: project.link
16965
17046
  }, {
16966
17047
  token,
17048
+ now: () => ctx.clock.now(),
16967
17049
  fetch: fetcher,
16968
17050
  signal
16969
17051
  }));
16970
17052
  }
16971
- function sampleLinks(ctx, fetcher, token) {
17053
+ function sampleLinks(ctx, fetcher, deadlineMs, token) {
16972
17054
  const projects = ctx.config.projects.flatMap((project) => project.tracker.type === "github-issues" ? [{
16973
17055
  project,
16974
17056
  repo: project.tracker.repo
@@ -16983,7 +17065,7 @@ function sampleLinks(ctx, fetcher, token) {
16983
17065
  project,
16984
17066
  repo,
16985
17067
  polled,
16986
- sample: await sampleProject(ctx, fetcher, token, project, repo)
17068
+ sample: await sampleProject(ctx, fetcher, deadlineMs, token, project, repo)
16987
17069
  } : {
16988
17070
  project,
16989
17071
  repo,
@@ -17060,11 +17142,11 @@ function warning(id, fix) {
17060
17142
  fix
17061
17143
  };
17062
17144
  }
17063
- async function request(ctx, fetcher, id, url, init = {}) {
17145
+ async function request(ctx, fetcher, deadlineMs, id, url, init = {}) {
17064
17146
  try {
17065
17147
  return await ctx.logCall(`doctor.${id}`, () => fetcher(url, {
17066
17148
  ...init,
17067
- signal: AbortSignal.timeout(TIMEOUT_MS)
17149
+ signal: AbortSignal.timeout(deadlineMs)
17068
17150
  }));
17069
17151
  } catch {
17070
17152
  return null;
@@ -17091,12 +17173,12 @@ async function slackMember(response) {
17091
17173
  }
17092
17174
  }
17093
17175
  /** Bounded daemon-side checks; no response body or exception text leaves this module. */
17094
- async function runDaemonDoctor(ctx, productVersion, fetcher = fetch) {
17176
+ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch, { deadlineMs = DEADLINE_MS } = {}) {
17095
17177
  const { config, secrets } = ctx;
17096
17178
  const checks = [];
17097
17179
  const jiraTrackers = config.projects.flatMap((project) => project.tracker.type === "jira" ? [project.tracker] : []);
17098
17180
  const slackConfigured = Boolean(config.slack.channels.feed || config.slack.channels.orchestrators);
17099
- const linkSamples = sampleLinks(ctx, fetcher, secrets["GITHUB_TOKEN"]);
17181
+ const linkSamples = sampleLinks(ctx, fetcher, deadlineMs, secrets["GITHUB_TOKEN"]);
17100
17182
  const missing = requiredSecretKeys(config).filter((name) => !secrets[name]);
17101
17183
  checks.push(check("secrets", missing.length === 0, `Add ${missing.join(", ")} to the private secrets.env file.`));
17102
17184
  const jiraEmail = secrets["JIRA_EMAIL"];
@@ -17105,7 +17187,7 @@ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch) {
17105
17187
  if (jiraTrackers.length > 0 && jiraEmail && jiraToken) {
17106
17188
  const credentials = Buffer.from(`${jiraEmail}:${jiraToken}`).toString("base64");
17107
17189
  jiraOk = (await Promise.all(jiraTrackers.map(async (tracker) => {
17108
- return (await request(ctx, fetcher, "jira", new URL("/rest/api/3/myself", tracker.baseUrl), { headers: {
17190
+ return (await request(ctx, fetcher, deadlineMs, "jira", new URL("/rest/api/3/myself", tracker.baseUrl), { headers: {
17109
17191
  Authorization: `Basic ${credentials}`,
17110
17192
  Accept: "application/json"
17111
17193
  } }))?.ok === true;
@@ -17115,12 +17197,12 @@ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch) {
17115
17197
  const githubToken = secrets["GITHUB_TOKEN"];
17116
17198
  const githubRepos = new Set(config.projects.flatMap((project) => project.repos));
17117
17199
  const githubFailure = (githubToken === void 0 ? [GITHUB_FIX] : await Promise.all([...githubRepos].map(async (repo) => {
17118
- const response = await request(ctx, fetcher, "github", `https://api.github.com/repos/${repo}`, { headers: {
17200
+ const response = await request(ctx, fetcher, deadlineMs, "github", `https://api.github.com/repos/${repo}`, { headers: {
17119
17201
  Authorization: `Bearer ${githubToken}`,
17120
17202
  Accept: "application/vnd.github+json"
17121
17203
  } });
17122
17204
  if (response?.ok !== true) return GITHUB_FIX;
17123
- const probe = await githubGraphql(ctx, fetcher, githubToken, repo);
17205
+ const probe = await githubGraphql(ctx, fetcher, deadlineMs, githubToken, repo);
17124
17206
  if (probe?.response.ok !== true) return GITHUB_FIX;
17125
17207
  const payload = object(probe.body);
17126
17208
  const errors = payload?.["errors"];
@@ -17139,7 +17221,7 @@ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch) {
17139
17221
  checks.push(check("github.credentials", githubFailure === null, githubFailure ?? GITHUB_FIX));
17140
17222
  checks.push(linkRulesCheck(await linkSamples));
17141
17223
  const probe = spurSendRequest(config.adapters.spur.baseUrl, SPUR_PROBE_SESSION, "spur-board doctor probe");
17142
- const [spur, spurSend] = await Promise.all([request(ctx, fetcher, "spur", new URL("sessions", `${config.adapters.spur.baseUrl.replace(/\/$/, "")}/`)), request(ctx, fetcher, "spur.send", probe.url, probe.init)]);
17224
+ const [spur, spurSend] = await Promise.all([request(ctx, fetcher, deadlineMs, "spur", new URL("sessions", `${config.adapters.spur.baseUrl.replace(/\/$/, "")}/`)), request(ctx, fetcher, deadlineMs, "spur.send", probe.url, probe.init)]);
17143
17225
  checks.push(check("spur.api", spur?.ok === true, "Start or correct the configured Spur API."));
17144
17226
  const spurSendOk = spurSend?.status === 404 && ((await spurErrorText(spurSend))?.startsWith("Session not found") ?? false);
17145
17227
  if (spurSend !== null && spurSend.status !== 404) await spurSend.body?.cancel().catch(() => void 0);
@@ -17149,7 +17231,7 @@ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch) {
17149
17231
  const botToken = secrets["SLACK_BOT_TOKEN"];
17150
17232
  const slackHeaders = botToken ? { Authorization: `Bearer ${botToken}` } : {};
17151
17233
  const slackBase = `${(secrets["SLACK_API_URL"] || "https://slack.com/api/").replace(/\/$/, "")}/`;
17152
- const auth = botToken ? await request(ctx, fetcher, "slack.auth", new URL("auth.test", slackBase), {
17234
+ const auth = botToken ? await request(ctx, fetcher, deadlineMs, "slack.auth", new URL("auth.test", slackBase), {
17153
17235
  method: "POST",
17154
17236
  headers: slackHeaders
17155
17237
  }) : null;
@@ -17158,13 +17240,13 @@ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch) {
17158
17240
  const missingScopes = SLACK_BOT_SCOPES.filter((scope) => !granted.has(scope));
17159
17241
  checks.push(check("slack.auth", authorized && missingScopes.length === 0, authorized ? `Add ${missingScopes.join(", ")} to the Slack app and reinstall it.` : "Check the Slack bot token."));
17160
17242
  for (const [id, channel] of [["slack.orchestrators_member", config.slack.channels.orchestrators], ["slack.feed_member", config.slack.channels.feed]]) {
17161
- const response = botToken && channel ? await request(ctx, fetcher, id, new URL(`conversations.info?channel=${encodeURIComponent(channel)}`, slackBase), { headers: slackHeaders }) : null;
17243
+ const response = botToken && channel ? await request(ctx, fetcher, deadlineMs, id, new URL(`conversations.info?channel=${encodeURIComponent(channel)}`, slackBase), { headers: slackHeaders }) : null;
17162
17244
  checks.push(check(id, await slackMember(response), "Invite the bot to the configured channel ID."));
17163
17245
  }
17164
17246
  const configToken = secrets["SLACK_APP_CONFIG_TOKEN"];
17165
17247
  if (!configToken || !config.slack.appId) checks.push(warning("slack.command", "Verify the installed Slack slash command against slack.command manually, or provide SLACK_APP_CONFIG_TOKEN and slack.appId."));
17166
17248
  else {
17167
- const response = await request(ctx, fetcher, "slack.command", new URL("apps.manifest.export", slackBase), {
17249
+ const response = await request(ctx, fetcher, deadlineMs, "slack.command", new URL("apps.manifest.export", slackBase), {
17168
17250
  method: "POST",
17169
17251
  headers: {
17170
17252
  Authorization: `Bearer ${configToken}`,
@@ -17271,36 +17353,20 @@ function createInboundModule(ctx, gateway, registry = {}) {
17271
17353
  clock: ctx.clock,
17272
17354
  registry
17273
17355
  });
17274
- let timer;
17275
- let active = Promise.resolve();
17276
- let stopped = false;
17277
- let signal;
17278
- const schedule = () => {
17279
- if (stopped || signal?.aborted) return;
17280
- timer = setTimeout(() => {
17281
- timer = void 0;
17282
- tick();
17283
- }, RECOVERY_MS);
17284
- };
17285
- const tick = () => {
17286
- if (stopped || signal?.aborted) return;
17287
- active = ctx.logCall("inbound.recover", () => inbound.recover()).catch((err) => {
17356
+ const recovery = createJob({
17357
+ run: () => ctx.logCall("inbound.recover", () => inbound.recover()),
17358
+ intervalMs: RECOVERY_MS,
17359
+ onError: (err) => {
17288
17360
  ctx.log.error({ err }, "inbound recovery failed");
17289
- }).finally(schedule);
17290
- };
17361
+ }
17362
+ });
17291
17363
  return {
17292
17364
  sink: (event) => inbound.sink(event),
17293
17365
  reapply: inbound.reapply,
17294
- awaitRecovery: () => active,
17295
- start(startSignal) {
17296
- signal = startSignal;
17297
- tick();
17298
- return Promise.resolve();
17299
- },
17366
+ awaitRecovery: () => recovery.settled(),
17367
+ start: (signal) => recovery.start(signal),
17300
17368
  async stop() {
17301
- stopped = true;
17302
- if (timer !== void 0) clearTimeout(timer);
17303
- await active;
17369
+ await recovery.stop();
17304
17370
  await inbound.stop();
17305
17371
  }
17306
17372
  };
@@ -17345,8 +17411,8 @@ function slackSettings(config, secrets) {
17345
17411
  };
17346
17412
  }
17347
17413
  /**
17348
- * Own the timer and wait for the last queued sender tick and connection update before the store
17349
- * closes.
17414
+ * Own the outbox, token-expiry and doorbell jobs, each logging its own failure, and wait for
17415
+ * their active runs and every queued connection update before the store closes.
17350
17416
  */
17351
17417
  function createOutboxModule(ctx, gateway, options = {}) {
17352
17418
  const spur = options.spur ?? createSpurPort({ baseUrl: ctx.config.adapters.spur.baseUrl });
@@ -17357,40 +17423,51 @@ function createOutboxModule(ctx, gateway, options = {}) {
17357
17423
  spur: { send: (session, text) => ctx.logCall("spur.send", () => spur.send(session, text)) },
17358
17424
  now: () => new Date(ctx.clock.now())
17359
17425
  });
17360
- let timer;
17361
- let active = Promise.resolve();
17426
+ const every = {
17427
+ intervalMs: options.tickMs ?? TICK_MS,
17428
+ jitterMs: options.jitterMs ?? TICK_JITTER_MS
17429
+ };
17430
+ const outbox = createJob({
17431
+ ...every,
17432
+ run: (signal) => ctx.logCall("outbox.tick", () => sender.tick(signal)),
17433
+ onError: () => void 0
17434
+ });
17435
+ const tokens = createJob({
17436
+ ...every,
17437
+ run: () => expirePendingTokens(ctx.store, ctx.config, new Date(ctx.clock.now())),
17438
+ onError: (err) => {
17439
+ ctx.log.error({ err }, "token expiry failed");
17440
+ }
17441
+ });
17442
+ const doorbells = createJob({
17443
+ ...every,
17444
+ run: () => reconcileDueDoorbells(ctx.store, ctx.config, new Date(ctx.clock.now())),
17445
+ onError: (err) => {
17446
+ ctx.log.error({ err }, "doorbell reconcile failed");
17447
+ }
17448
+ });
17449
+ const jobs = [
17450
+ tokens,
17451
+ doorbells,
17452
+ outbox
17453
+ ];
17362
17454
  let updating = Promise.resolve();
17363
17455
  let stopped = false;
17364
- let signal;
17365
- const schedule = () => {
17366
- if (stopped || signal?.aborted) return;
17367
- timer = setTimeout(() => {
17368
- timer = void 0;
17369
- tick().then(schedule);
17370
- }, TICK_MS + Math.floor(Math.random() * TICK_JITTER_MS));
17371
- };
17372
- const tick = () => {
17373
- if (stopped || signal?.aborted) return active;
17374
- active = active.then(() => ctx.logCall("outbox.tick", async () => {
17375
- await expirePendingTokens(ctx.store, ctx.config, new Date(ctx.clock.now()));
17376
- if (!signal?.aborted) await sender.tick(signal);
17377
- })).catch(() => void 0);
17378
- return active;
17379
- };
17380
17456
  return {
17381
- async start(startSignal) {
17382
- signal = startSignal;
17457
+ async start(signal) {
17383
17458
  await sender.recover();
17384
17459
  if (signal.aborted) return;
17385
- tick().then(schedule);
17460
+ await Promise.all(jobs.map((job) => job.start(signal)));
17386
17461
  },
17387
17462
  async stop() {
17388
17463
  stopped = true;
17389
- if (timer !== void 0) clearTimeout(timer);
17390
- await active;
17464
+ await Promise.all(jobs.map((job) => job.stop()));
17391
17465
  await updating;
17392
17466
  },
17393
- pulse: tick,
17467
+ async pulse() {
17468
+ await doorbells.trigger();
17469
+ await outbox.trigger();
17470
+ },
17394
17471
  connection(state) {
17395
17472
  if (stopped) return Promise.resolve();
17396
17473
  const update = sender.recordConnection(state, new Date(ctx.clock.now())).catch((err) => {
@@ -17507,6 +17584,7 @@ function createSystemdModule(notifier) {
17507
17584
  }
17508
17585
  //#endregion
17509
17586
  //#region ../daemon/src/composition.ts
17587
+ const DAY_MS = 864e5;
17510
17588
  /** The production module graph, with replaceable external ports for in-process tests. */
17511
17589
  function createDaemonModules(ctxFor, ports = {}) {
17512
17590
  const board = ctxFor("board-core");
@@ -17518,7 +17596,10 @@ function createDaemonModules(ctxFor, ports = {}) {
17518
17596
  });
17519
17597
  const ctx = ctxFor("gateway-slack");
17520
17598
  const settings = slackSettings(ctx.config, ctx.secrets);
17521
- const gateway = ports.gateway ?? (settings === null ? void 0 : createSlackGateway(settings));
17599
+ const gateway = ports.gateway ?? (settings === null ? void 0 : createSlackGateway({
17600
+ ...settings,
17601
+ now: () => ctx.clock.now()
17602
+ }));
17522
17603
  const registry = createOperationRegistry({
17523
17604
  config: board.config,
17524
17605
  clock: board.clock,
@@ -17537,23 +17618,24 @@ function createDaemonModules(ctxFor, ports = {}) {
17537
17618
  const entries = [{
17538
17619
  name: "commands",
17539
17620
  stopStage: "final",
17540
- module: commandRetention({
17541
- store: commands.store,
17542
- clock: commands.clock,
17543
- retentionDays: commands.config.commands.retentionDays,
17621
+ module: createJob({
17622
+ run: () => purgeExpiredCommands(commands.store, commands.clock, commands.config.commands.retentionDays),
17623
+ intervalMs: DAY_MS,
17624
+ first: "await",
17544
17625
  onError: (err) => {
17545
17626
  commands.log.error({ err }, "command purge failed");
17546
17627
  }
17547
17628
  })
17548
17629
  }];
17549
- entries.push(...createBoardModules(ctxFor, {
17630
+ const boardModules = createBoardModules(ctxFor, {
17550
17631
  core,
17551
17632
  ...ports.startAdapters === void 0 ? {} : { startAdapters: ports.startAdapters },
17552
17633
  ...ports.tick === void 0 ? {} : { tick: ports.tick },
17553
17634
  onTick: () => {
17554
17635
  notifier.watchdog();
17555
17636
  }
17556
- }));
17637
+ });
17638
+ entries.push(...boardModules.entries);
17557
17639
  const inbound = gateway === void 0 || ports.gateway === void 0 && settings?.appToken === void 0 ? void 0 : createInboundModule(ctxFor("inbound"), gateway, registry);
17558
17640
  if (settings !== null && inbound === void 0) ctx.log.info("Slack inbound disabled: SLACK_APP_TOKEN is absent");
17559
17641
  const outbox = createOutboxModule(ctxFor("outbox"), gateway, ports.spur === void 0 ? {} : { spur: ports.spur });
@@ -17603,7 +17685,8 @@ function createDaemonModules(ctxFor, ports = {}) {
17603
17685
  return {
17604
17686
  entries,
17605
17687
  inbound,
17606
- outbox
17688
+ outbox,
17689
+ tick: boardModules.tick
17607
17690
  };
17608
17691
  }
17609
17692
  //#endregion
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spur-board",
3
- "version": "0.21.1",
3
+ "version": "0.23.0",
4
4
  "license": "MIT",
5
5
  "engines": {
6
6
  "node": "^24.12.0 || ^26.0.0"
@@ -26,8 +26,8 @@
26
26
  "@commander-js/extra-typings": "^15.0.0",
27
27
  "@modelcontextprotocol/server": "^2.4.0",
28
28
  "commander": "^15.0.0",
29
- "@slack/socket-mode": "3.1.0",
30
- "@slack/web-api": "8.2.0",
29
+ "@slack/socket-mode": "3.1.1",
30
+ "@slack/web-api": "8.3.0",
31
31
  "better-sqlite3": "^13.0.3",
32
32
  "fastify": "^5.12.2",
33
33
  "kysely": "^0.29.7",