spur-board 0.82.0 → 0.83.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/daemon.mjs CHANGED
@@ -1,15 +1,15 @@
1
- import { $ as err, A as prSourceId, B as prFactsSchema, C as userIdSchema, D as AdapterError, E as eventPayloadSchemas, F as REVIEW_STATES, G as JIRA_PROJECT_KEY, H as ringMarker, I as SESSION_HEALTH_STATES, J as encodeActorId, K as REF_NUMBER, L as SESSION_STATUSES, M as sourceCursorSchema, N as trackerSourceId, O as batchSchema, P as PR_STATES, Q as ERRORS, R as isExternalAuthor, S as messageRefSchema, St as VIAS, T as GATE_REASONS, U as sessionFactsSchema, V as prRefSchema, W as ticketFactsSchema, X as parseActorId, Y as errorCodeOf, Z as parseRef$1, _t as COLUMN_IDS, a as requestHashOf, at as DEFAULT_LINK, b as inboundEventSchema, bt as SLACK_BOT_SCOPES, c as tokenRequestStatusSchema, d as buildCatalogSnapshot, dt as configBindings, f as roleCanUseOperation, ft as configSchema, gt as resolveWebOrigin, h as renderHttpProblem, ht as requiredSecretKeys, i as TOKEN_REQUEST_LIMITS, j as sessionTransitionSchema, k as entityRefSchema, l as BOARD_TICK_MS, lt as RESERVED_PROJECT, m as turnHandedSchema, mt as plainHttpAllowed, n as doctorReportSchema, nt as ok, o as tokenRequestResultSchema, p as OPERATIONS, pt as defaultAddressee, q as actorIdSchema, rt as successEnvelopeSchema, s as tokenRequestSchema, st as DEFAULT_SLACK_COMMAND, t as assertNever, ut as boardWideSpurProject, v as SPACE_IDS, vt as DISPATCHER_MODES, w as EVENT_KINDS, x as interactionRefSchema, xt as TASK_HOLDS, y as conversationRefSchema, yt as ITEM_KINDS, z as parseRingMarker } from "./chunk-DYe3fYra.mjs";
2
- import { t as apiBaseUrl } from "./chunk-DAMwWWmT.mjs";
1
+ import { $ as err, A as prSourceId, B as prFactsSchema, C as userIdSchema, D as AdapterError, E as eventPayloadSchemas, F as REVIEW_STATES, G as JIRA_PROJECT_KEY, H as ringMarker, I as SESSION_HEALTH_STATES, J as encodeActorId, K as REF_NUMBER, L as SESSION_STATUSES, M as sourceCursorSchema, N as trackerSourceId, O as batchSchema, P as PR_STATES, Q as ERRORS, R as isExternalAuthor, S as messageRefSchema, St as VIAS, T as GATE_REASONS, U as sessionFactsSchema, V as prRefSchema, W as ticketFactsSchema, X as parseActorId, Y as errorCodeOf, Z as parseRef$1, _t as COLUMN_IDS, a as requestHashOf, at as DEFAULT_LINK, b as inboundEventSchema, bt as SLACK_BOT_SCOPES, c as tokenRequestStatusSchema, d as buildCatalogSnapshot, dt as configBindings, f as roleCanUseOperation, ft as configSchema, gt as resolveWebOrigin, h as renderHttpProblem, ht as requiredSecretKeys, i as TOKEN_REQUEST_LIMITS, j as sessionTransitionSchema, k as entityRefSchema, l as BOARD_TICK_MS, lt as RESERVED_PROJECT, m as turnHandedSchema, mt as plainHttpAllowed, n as doctorReportSchema, nt as ok, o as tokenRequestResultSchema, p as OPERATIONS, pt as defaultAddressee, q as actorIdSchema, rt as successEnvelopeSchema, s as tokenRequestSchema, st as DEFAULT_SLACK_COMMAND, t as assertNever, ut as boardWideSpurProject, v as SPACE_IDS, vt as DISPATCHER_MODES, w as EVENT_KINDS, x as interactionRefSchema, xt as TASK_HOLDS, y as conversationRefSchema, yt as ITEM_KINDS, z as parseRingMarker } from "./chunk-B-1Dlzi3.mjs";
2
+ import { t as apiBaseUrl } from "./chunk-Bzb7aI8R.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import { createHash, randomUUID } from "node:crypto";
5
5
  import { chmodSync, closeSync, existsSync, fchmodSync, fstatSync, fsyncSync, ftruncateSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeSync } from "node:fs";
6
- import { homedir, hostname } from "node:os";
6
+ import { cpus, freemem, homedir, hostname, totalmem } from "node:os";
7
7
  import path, { basename, dirname, extname, isAbsolute, join, normalize, resolve } from "node:path";
8
8
  import { z } from "zod";
9
9
  import YAML from "yaml";
10
10
  import { spawn, spawnSync } from "node:child_process";
11
11
  import { parseEnv } from "node:util";
12
- import { lstat, readFile, readdir } from "node:fs/promises";
12
+ import { lstat, readFile, readdir, statfs } from "node:fs/promises";
13
13
  import Database from "better-sqlite3";
14
14
  import { Kysely, SqliteDialect, sql } from "kysely";
15
15
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -20,14 +20,14 @@ import { pino } from "pino";
20
20
  import { WebAPIHTTPError, WebAPIPlatformError, WebAPIRateLimitedError, WebClient } from "@slack/web-api";
21
21
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
22
22
  import { SocketModeClient } from "@slack/socket-mode";
23
- //#region \0rolldown/runtime.js
23
+ // \0rolldown/runtime.js
24
24
  var __create = Object.create;
25
25
  var __defProp = Object.defineProperty;
26
26
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
27
27
  var __getOwnPropNames = Object.getOwnPropertyNames;
28
28
  var __getProtoOf = Object.getPrototypeOf;
29
29
  var __hasOwnProp = Object.prototype.hasOwnProperty;
30
- var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
30
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod, mod.exports), cb = null), mod.exports);
31
31
  var __copyProps = (to, from, except, desc) => {
32
32
  if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
33
33
  key = keys[i];
@@ -38,21 +38,19 @@ var __copyProps = (to, from, except, desc) => {
38
38
  }
39
39
  return to;
40
40
  };
41
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
41
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
42
42
  value: mod,
43
43
  enumerable: true
44
44
  }) : target, mod));
45
45
  var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
46
- //#endregion
47
- //#region ../contracts/src/gateway/gateway.ts
46
+ // ../contracts/src/gateway/gateway.ts
48
47
  const PERSONA_ROLES = [
49
48
  "orchestrator",
50
49
  "curator",
51
50
  "worker",
52
51
  "board"
53
52
  ];
54
- //#endregion
55
- //#region ../core/src/store/copy.ts
53
+ // ../core/src/store/copy.ts
56
54
  /**
57
55
  * Opens a database read-write with no PRAGMA, migration or version check: the connection only
58
56
  * feeds a copy or checkpoints a WAL. Read-write, so SQLite replays a leftover `-wal`.
@@ -136,8 +134,7 @@ function copyDatabase(source, target, step = () => void 0) {
136
134
  step("rename");
137
135
  if (linked) rmSync(aside, { force: true });
138
136
  }
139
- //#endregion
140
- //#region ../core/src/store/migrate.ts
137
+ // ../core/src/store/migrate.ts
141
138
  /** The migration files that ship with this package. */
142
139
  const migrationsDir = new URL("./migrations/", import.meta.url);
143
140
  const FILE_NAME = /^(\d{4})_[a-z0-9_]+\.sql$/;
@@ -261,8 +258,7 @@ function migrate(db, migrations) {
261
258
  backup
262
259
  };
263
260
  }
264
- //#endregion
265
- //#region ../core/src/store/store.ts
261
+ // ../core/src/store/store.ts
266
262
  function connect(file) {
267
263
  return new Database(file, { timeout: 5e3 });
268
264
  }
@@ -328,8 +324,7 @@ function openStore(file) {
328
324
  close: () => db.destroy()
329
325
  };
330
326
  }
331
- //#endregion
332
- //#region ../core/src/store/json.ts
327
+ // ../core/src/store/json.ts
333
328
  /** Parses a JSON column and checks it against `schema`. Throws on bad JSON or a bad value. */
334
329
  function parseJson(schema, text) {
335
330
  return schema.parse(JSON.parse(text));
@@ -370,8 +365,7 @@ function warnSkippedOnce(warn) {
370
365
  seen.add(key);
371
366
  };
372
367
  }
373
- //#endregion
374
- //#region ../core/src/domain/blocks/blocks.ts
368
+ // ../core/src/domain/blocks/blocks.ts
375
369
  var BlockRuleError = class extends Error {
376
370
  code;
377
371
  constructor(code, message) {
@@ -483,8 +477,7 @@ function acknowledgeComment(revision, requested) {
483
477
  if (revision !== requested) throw new BlockRuleError("stale_comment_revision", `Comment revision is ${String(revision)}; requested ${String(requested)}.`);
484
478
  return requested;
485
479
  }
486
- //#endregion
487
- //#region ../core/src/app/authorize.ts
480
+ // ../core/src/app/authorize.ts
488
481
  /** The target of an operation on a board project as a whole: no task, block or links. */
489
482
  function projectTarget(project) {
490
483
  return {
@@ -590,8 +583,7 @@ function authorize(grants, actor, state) {
590
583
  hint
591
584
  };
592
585
  }
593
- //#endregion
594
- //#region ../../node_modules/.pnpm/boundary@2.0.0/node_modules/boundary/lib/index.js
586
+ // ../../node_modules/.pnpm/boundary@2.0.0/node_modules/boundary/lib/index.js
595
587
  var require_lib = /* @__PURE__ */ __commonJSMin(((exports) => {
596
588
  Object.defineProperty(exports, "__esModule", { value: true });
597
589
  exports.binarySearch = exports.upperBound = exports.lowerBound = exports.compare = void 0;
@@ -634,8 +626,7 @@ var require_lib = /* @__PURE__ */ __commonJSMin(((exports) => {
634
626
  }
635
627
  exports.binarySearch = binarySearch;
636
628
  }));
637
- //#endregion
638
- //#region ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/helper/invariant.js
629
+ // ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/helper/invariant.js
639
630
  var import_structured_source = (/* @__PURE__ */ __commonJSMin(((exports) => {
640
631
  Object.defineProperty(exports, "__esModule", { value: true });
641
632
  exports.StructuredSource = void 0;
@@ -715,8 +706,7 @@ var import_structured_source = (/* @__PURE__ */ __commonJSMin(((exports) => {
715
706
  function invariant(condition, message) {
716
707
  if (!condition) throw new Error(message);
717
708
  }
718
- //#endregion
719
- //#region ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/SecretLintSourceCodeImpl.js
709
+ // ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/SecretLintSourceCodeImpl.js
720
710
  /**
721
711
  * This class represent of source code.
722
712
  */
@@ -803,8 +793,7 @@ var SecretLintSourceCodeImpl = class {
803
793
  };
804
794
  }
805
795
  };
806
- //#endregion
807
- //#region ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/helper/promise-event-emitter.js
796
+ // ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/helper/promise-event-emitter.js
808
797
  var EventEmitter = class {
809
798
  #listeners = /* @__PURE__ */ new Map();
810
799
  on(type, listener) {
@@ -851,8 +840,7 @@ var PromiseEventEmitter = class {
851
840
  return Promise.all(promises);
852
841
  }
853
842
  };
854
- //#endregion
855
- //#region ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/helper/SecretLintRuleMessageTranslator.js
843
+ // ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/helper/SecretLintRuleMessageTranslator.js
856
844
  /**
857
845
  * Default locale that is also fallback locale.
858
846
  */
@@ -902,8 +890,7 @@ const createTranslator = (messages, options) => {
902
890
  };
903
891
  };
904
892
  };
905
- //#endregion
906
- //#region ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/RuleContext.js
893
+ // ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/RuleContext.js
907
894
  const createContextEvents = () => {
908
895
  const contextEvents = new EventEmitter();
909
896
  const REPORT_SYMBOL = Symbol("report");
@@ -982,8 +969,7 @@ const createRuleContext = ({ ruleId, ruleParentId, meta, severity, sourceCode, c
982
969
  }
983
970
  };
984
971
  };
985
- //#endregion
986
- //#region ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/SecretLintRuleImpl.js
972
+ // ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/SecretLintRuleImpl.js
987
973
  var SecretLintRule = class {
988
974
  ruleReportHandle;
989
975
  ruleCreator;
@@ -1016,8 +1002,7 @@ var SecretLintRule = class {
1016
1002
  return file(source);
1017
1003
  }
1018
1004
  };
1019
- //#endregion
1020
- //#region ../../node_modules/.pnpm/@secretlint+profiler@13.1.0/node_modules/@secretlint/profiler/module/index.js
1005
+ // ../../node_modules/.pnpm/@secretlint+profiler@13.1.0/node_modules/@secretlint/profiler/module/index.js
1021
1006
  var SecretLintProfiler = class {
1022
1007
  perf;
1023
1008
  PerformanceObserver;
@@ -1104,8 +1089,7 @@ var SecretLintProfiler = class {
1104
1089
  return this.measures;
1105
1090
  }
1106
1091
  };
1107
- //#endregion
1108
- //#region ../../node_modules/.pnpm/@secretlint+profiler@13.1.0/node_modules/@secretlint/profiler/module/node.js
1092
+ // ../../node_modules/.pnpm/@secretlint+profiler@13.1.0/node_modules/@secretlint/profiler/module/node.js
1109
1093
  var NullPerformanceObserver = class {
1110
1094
  disconnect() {}
1111
1095
  observe(_options) {}
@@ -1114,8 +1098,7 @@ const secretLintProfiler = new SecretLintProfiler({
1114
1098
  perf: perf_hooks.performance,
1115
1099
  PerformanceObserver: perf_hooks.PerformanceObserver ? perf_hooks.PerformanceObserver : NullPerformanceObserver
1116
1100
  });
1117
- //#endregion
1118
- //#region ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/RunningEvents.js
1101
+ // ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/RunningEvents.js
1119
1102
  const createRunningEvents = () => {
1120
1103
  const contextEvents = new PromiseEventEmitter();
1121
1104
  const registerSet = /* @__PURE__ */ new Set();
@@ -1168,8 +1151,7 @@ Duplicated rule.id is something wrong in .secretlintrc.
1168
1151
  }
1169
1152
  };
1170
1153
  };
1171
- //#endregion
1172
- //#region ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/RulePresetContext.js
1154
+ // ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/RulePresetContext.js
1173
1155
  /**
1174
1156
  * Create a context for Rule Preset
1175
1157
  */
@@ -1216,8 +1198,7 @@ const createRulePresetContext = ({ configRulePreset, sourceCode, runningEvents,
1216
1198
  }
1217
1199
  };
1218
1200
  };
1219
- //#endregion
1220
- //#region ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/messages/filter-ignored-process.js
1201
+ // ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/messages/filter-ignored-process.js
1221
1202
  /**
1222
1203
  * the `index` is in the `range` and return true.
1223
1204
  * @param {Number} index
@@ -1245,8 +1226,7 @@ function filterIgnoredMessages(options) {
1245
1226
  });
1246
1227
  });
1247
1228
  }
1248
- //#endregion
1249
- //#region ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/messages/MessageProcessManager.js
1229
+ // ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/messages/MessageProcessManager.js
1250
1230
  const createMessageProcessor = (processors) => {
1251
1231
  return {
1252
1232
  /**
@@ -1260,8 +1240,7 @@ process(messages) {
1260
1240
  }, originalMessages);
1261
1241
  } };
1262
1242
  };
1263
- //#endregion
1264
- //#region ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/messages/filter-duplicated-process.js
1243
+ // ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/messages/filter-duplicated-process.js
1265
1244
  /**
1266
1245
  * equal message
1267
1246
  */
@@ -1278,8 +1257,7 @@ function filterDuplicatedMessages(messages = []) {
1278
1257
  });
1279
1258
  });
1280
1259
  }
1281
- //#endregion
1282
- //#region ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/messages/sort-messages-process.js
1260
+ // ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/messages/sort-messages-process.js
1283
1261
  /**
1284
1262
  * sort messages by line and column
1285
1263
  */
@@ -1290,8 +1268,7 @@ function sortMessagesByLocation(messages) {
1290
1268
  else return startIndexDiff;
1291
1269
  });
1292
1270
  }
1293
- //#endregion
1294
- //#region ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/messages/filter-message-id.js
1271
+ // ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/messages/filter-message-id.js
1295
1272
  const filterByAllowMessageIds = (messages, allowMessageIds) => {
1296
1273
  const disabledSet = new Set(allowMessageIds.map((allowMessage) => {
1297
1274
  return `${allowMessage.ruleId}--${allowMessage.messageId}`;
@@ -1300,8 +1277,7 @@ const filterByAllowMessageIds = (messages, allowMessageIds) => {
1300
1277
  return !disabledSet.has(`${message.ruleId}--${message.messageId}`);
1301
1278
  });
1302
1279
  };
1303
- //#endregion
1304
- //#region ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/messages/filter-mask-secrets.js
1280
+ // ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/messages/filter-mask-secrets.js
1305
1281
  const deepMask = (object, handler) => {
1306
1282
  for (const key of Object.keys(object)) if (typeof object[key] === "object" && object[key] !== null) object[key] = deepMask(object[key], handler);
1307
1283
  else if (typeof object[key] === "string") object[key] = handler(object[key]);
@@ -1349,8 +1325,7 @@ const filterMaskSecretsData = (messages = []) => {
1349
1325
  };
1350
1326
  });
1351
1327
  };
1352
- //#endregion
1353
- //#region ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/messages/index.js
1328
+ // ../../node_modules/.pnpm/@secretlint+core@13.1.0_supports-color@7.2.0/node_modules/@secretlint/core/module/messages/index.js
1354
1329
  /**
1355
1330
  * Post cleanup messages
1356
1331
  * - filter ignored range
@@ -1361,11 +1336,12 @@ const filterMaskSecretsData = (messages = []) => {
1361
1336
  * @param options
1362
1337
  */
1363
1338
  const cleanupMessages = (options) => {
1364
- const reportedMessagesWithoutAllowMessageIds = filterByAllowMessageIds(filterIgnoredMessages(options), options.allowMessageIds);
1365
- return sortMessagesByLocation(createMessageProcessor(options.maskSecrets ? [filterDuplicatedMessages, filterMaskSecretsData] : [filterDuplicatedMessages]).process(reportedMessagesWithoutAllowMessageIds));
1339
+ const reportedMessages = filterIgnoredMessages(options);
1340
+ const reportedMessagesWithoutAllowMessageIds = filterByAllowMessageIds(reportedMessages, options.allowMessageIds);
1341
+ const filters = options.maskSecrets ? [filterDuplicatedMessages, filterMaskSecretsData] : [filterDuplicatedMessages];
1342
+ return sortMessagesByLocation(createMessageProcessor(filters).process(reportedMessagesWithoutAllowMessageIds));
1366
1343
  };
1367
- //#endregion
1368
- //#region ../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js
1344
+ // ../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js
1369
1345
  var require_ms = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1370
1346
  /**
1371
1347
  * Helpers.
@@ -1482,8 +1458,7 @@ var require_ms = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1482
1458
  return Math.round(ms / n) + " " + name + (isPlural ? "s" : "");
1483
1459
  }
1484
1460
  }));
1485
- //#endregion
1486
- //#region ../../node_modules/.pnpm/debug@4.4.3_supports-color@7.2.0/node_modules/debug/src/common.js
1461
+ // ../../node_modules/.pnpm/debug@4.4.3_supports-color@7.2.0/node_modules/debug/src/common.js
1487
1462
  var require_common = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1488
1463
  /**
1489
1464
  * This is the common logic for both the Node.js and web browser
@@ -1622,15 +1597,16 @@ var require_common = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1622
1597
  let templateIndex = 0;
1623
1598
  let starIndex = -1;
1624
1599
  let matchIndex = 0;
1625
- while (searchIndex < search.length) if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) if (template[templateIndex] === "*") {
1626
- starIndex = templateIndex;
1627
- matchIndex = searchIndex;
1628
- templateIndex++;
1629
- } else {
1630
- searchIndex++;
1631
- templateIndex++;
1632
- }
1633
- else if (starIndex !== -1) {
1600
+ while (searchIndex < search.length) if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === "*")) {
1601
+ if (template[templateIndex] === "*") {
1602
+ starIndex = templateIndex;
1603
+ matchIndex = searchIndex;
1604
+ templateIndex++;
1605
+ } else {
1606
+ searchIndex++;
1607
+ templateIndex++;
1608
+ }
1609
+ } else if (starIndex !== -1) {
1634
1610
  templateIndex = starIndex + 1;
1635
1611
  matchIndex++;
1636
1612
  searchIndex = matchIndex;
@@ -1684,8 +1660,7 @@ var require_common = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1684
1660
  }
1685
1661
  module.exports = setup;
1686
1662
  }));
1687
- //#endregion
1688
- //#region ../../node_modules/.pnpm/debug@4.4.3_supports-color@7.2.0/node_modules/debug/src/browser.js
1663
+ // ../../node_modules/.pnpm/debug@4.4.3_supports-color@7.2.0/node_modules/debug/src/browser.js
1689
1664
  var require_browser = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1690
1665
  /**
1691
1666
  * This is the web browser implementation of `debug()`.
@@ -1880,8 +1855,7 @@ var require_browser = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1880
1855
  }
1881
1856
  };
1882
1857
  }));
1883
- //#endregion
1884
- //#region ../../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js
1858
+ // ../../node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js
1885
1859
  var require_has_flag = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1886
1860
  module.exports = (flag, argv = process.argv) => {
1887
1861
  const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
@@ -1890,19 +1864,20 @@ var require_has_flag = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1890
1864
  return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
1891
1865
  };
1892
1866
  }));
1893
- //#endregion
1894
- //#region ../../node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js
1867
+ // ../../node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js
1895
1868
  var require_supports_color = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1896
1869
  const os = __require("os");
1897
- const tty$1 = __require("tty");
1870
+ const tty = __require("tty");
1898
1871
  const hasFlag = require_has_flag();
1899
1872
  const { env } = process;
1900
1873
  let forceColor;
1901
1874
  if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) forceColor = 0;
1902
1875
  else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) forceColor = 1;
1903
- if ("FORCE_COLOR" in env) if (env.FORCE_COLOR === "true") forceColor = 1;
1904
- else if (env.FORCE_COLOR === "false") forceColor = 0;
1905
- else forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
1876
+ if ("FORCE_COLOR" in env) {
1877
+ if (env.FORCE_COLOR === "true") forceColor = 1;
1878
+ else if (env.FORCE_COLOR === "false") forceColor = 0;
1879
+ else forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3);
1880
+ }
1906
1881
  function translateLevel(level) {
1907
1882
  if (level === 0) return false;
1908
1883
  return {
@@ -1954,12 +1929,11 @@ var require_supports_color = /* @__PURE__ */ __commonJSMin(((exports, module) =>
1954
1929
  }
1955
1930
  module.exports = {
1956
1931
  supportsColor: getSupportLevel,
1957
- stdout: translateLevel(supportsColor(true, tty$1.isatty(1))),
1958
- stderr: translateLevel(supportsColor(true, tty$1.isatty(2)))
1932
+ stdout: translateLevel(supportsColor(true, tty.isatty(1))),
1933
+ stderr: translateLevel(supportsColor(true, tty.isatty(2)))
1959
1934
  };
1960
1935
  }));
1961
- //#endregion
1962
- //#region ../../node_modules/.pnpm/debug@4.4.3_supports-color@7.2.0/node_modules/debug/src/node.js
1936
+ // ../../node_modules/.pnpm/debug@4.4.3_supports-color@7.2.0/node_modules/debug/src/node.js
1963
1937
  var require_node = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1964
1938
  /**
1965
1939
  * Module dependencies.
@@ -2288,8 +2262,7 @@ const registerRule = ({ sourceCode, config, descriptorRule, contextEvents, runni
2288
2262
  }
2289
2263
  throw new Error(`Unknown descriptor type: ${descriptorRule}`);
2290
2264
  };
2291
- //#endregion
2292
- //#region ../../node_modules/.pnpm/@secretlint+secretlint-rule-preset-recommend@13.1.0/node_modules/@secretlint/secretlint-rule-preset-recommend/module/index.js
2265
+ // ../../node_modules/.pnpm/@secretlint+secretlint-rule-preset-recommend@13.1.0/node_modules/@secretlint/secretlint-rule-preset-recommend/module/index.js
2293
2266
  var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
2294
2267
  var regexpStringMatcher = {};
2295
2268
  /**
@@ -2310,7 +2283,7 @@ function requireLodash_uniq() {
2310
2283
  /** Used to stand-in for `undefined` hash values. */
2311
2284
  var HASH_UNDEFINED = "__lodash_hash_undefined__";
2312
2285
  /** Used as references for various `Number` constants. */
2313
- var INFINITY = Infinity;
2286
+ var INFINITY = 1 / 0;
2314
2287
  /** `Object#toString` result references. */
2315
2288
  var funcTag = "[object Function]", genTag = "[object GeneratorFunction]";
2316
2289
  /**
@@ -3022,7 +2995,7 @@ function requireLodash_uniqwith() {
3022
2995
  /** Used to stand-in for `undefined` hash values. */
3023
2996
  var HASH_UNDEFINED = "__lodash_hash_undefined__";
3024
2997
  /** Used as references for various `Number` constants. */
3025
- var INFINITY = Infinity;
2998
+ var INFINITY = 1 / 0;
3026
2999
  /** `Object#toString` result references. */
3027
3000
  var funcTag = "[object Function]", genTag = "[object GeneratorFunction]";
3028
3001
  /**
@@ -3750,8 +3723,6 @@ function requireLodash_sortby() {
3750
3723
  if (hasRequiredLodash_sortby) return lodash_sortby.exports;
3751
3724
  hasRequiredLodash_sortby = 1;
3752
3725
  (function(module, exports) {
3753
- /** Used as the size to enable large array optimizations. */
3754
- var LARGE_ARRAY_SIZE = 200;
3755
3726
  /** Used as the `TypeError` message for "Functions" methods. */
3756
3727
  var FUNC_ERROR_TEXT = "Expected a function";
3757
3728
  /** Used to stand-in for `undefined` hash values. */
@@ -4004,9 +3975,9 @@ function requireLodash_sortby() {
4004
3975
  /** Built-in value references. */
4005
3976
  var Symbol = root.Symbol, Uint8Array = root.Uint8Array, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : void 0;
4006
3977
  var nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max;
4007
- var DataView = getNative(root, "DataView"), Map = getNative(root, "Map"), Promise = getNative(root, "Promise"), Set = getNative(root, "Set"), WeakMap = getNative(root, "WeakMap"), nativeCreate = getNative(Object, "create");
3978
+ var DataView = getNative(root, "DataView"), Map = getNative(root, "Map"), Promise$1 = getNative(root, "Promise"), Set = getNative(root, "Set"), WeakMap = getNative(root, "WeakMap"), nativeCreate = getNative(Object, "create");
4008
3979
  /** Used to detect maps, sets, and weakmaps. */
4009
- var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap);
3980
+ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise$1), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap);
4010
3981
  /** Used to convert symbols to primitives and strings. */
4011
3982
  var symbolProto = Symbol ? Symbol.prototype : void 0, symbolValueOf = symbolProto ? symbolProto.valueOf : void 0, symbolToString = symbolProto ? symbolProto.toString : void 0;
4012
3983
  /**
@@ -4379,7 +4350,7 @@ function requireLodash_sortby() {
4379
4350
  var cache = this.__data__;
4380
4351
  if (cache instanceof ListCache) {
4381
4352
  var pairs = cache.__data__;
4382
- if (!Map || pairs.length < LARGE_ARRAY_SIZE - 1) {
4353
+ if (!Map || pairs.length < 199) {
4383
4354
  pairs.push([key, value]);
4384
4355
  return this;
4385
4356
  }
@@ -5042,7 +5013,7 @@ function requireLodash_sortby() {
5042
5013
  * @returns {string} Returns the `toStringTag`.
5043
5014
  */
5044
5015
  var getTag = baseGetTag;
5045
- if (DataView && getTag(new DataView(/* @__PURE__ */ new ArrayBuffer(1))) != dataViewTag || Map && getTag(new Map()) != mapTag || Promise && getTag(Promise.resolve()) != promiseTag || Set && getTag(new Set()) != setTag || WeakMap && getTag(new WeakMap()) != weakMapTag) getTag = function(value) {
5016
+ if (DataView && getTag(new DataView(/* @__PURE__ */ new ArrayBuffer(1))) != dataViewTag || Map && getTag(new Map()) != mapTag || Promise$1 && getTag(Promise$1.resolve()) != promiseTag || Set && getTag(new Set()) != setTag || WeakMap && getTag(new WeakMap()) != weakMapTag) getTag = function(value) {
5046
5017
  var result = objectToString.call(value), Ctor = result == objectTag ? value.constructor : void 0, ctorString = Ctor ? toSource(Ctor) : void 0;
5047
5018
  if (ctorString) switch (ctorString) {
5048
5019
  case dataViewCtorString: return dataViewTag;
@@ -7863,8 +7834,7 @@ const creator = {
7863
7834
  });
7864
7835
  }
7865
7836
  };
7866
- //#endregion
7867
- //#region ../core/src/app/secrets.ts
7837
+ // ../core/src/app/secrets.ts
7868
7838
  const MAX_STRINGS = 4096;
7869
7839
  const MAX_PASSES = 32;
7870
7840
  const receipts = new AsyncLocalStorage();
@@ -8021,8 +7991,7 @@ async function scanTransaction(store, config, fn) {
8021
7991
  }
8022
7992
  throw new Error("Gateway secret scan replay limit exceeded");
8023
7993
  }
8024
- //#endregion
8025
- //#region ../core/src/app/board-utils.ts
7994
+ // ../core/src/app/board-utils.ts
8026
7995
  /** Whether a ticket status is done: a Jira done status, or a closed GitHub Issue. */
8027
7996
  function ticketDone(project, status) {
8028
7997
  return project.tracker.type === "jira" ? project.tracker.doneStatuses.includes(status) : status === "closed";
@@ -8293,8 +8262,7 @@ function linkView(link) {
8293
8262
  role: link.role
8294
8263
  };
8295
8264
  }
8296
- //#endregion
8297
- //#region ../core/src/app/denied-event.ts
8265
+ // ../core/src/app/denied-event.ts
8298
8266
  /**
8299
8267
  * The journal project of a denial with no resolved target, in order: the configured project
8300
8268
  * the input's `task` key or `project` names; else the only configured project listing the agent
@@ -8327,8 +8295,7 @@ async function writeDeniedEvent(trx, denial) {
8327
8295
  reason: "Caller does not match the operation grants."
8328
8296
  }, actor);
8329
8297
  }
8330
- //#endregion
8331
- //#region ../core/src/app/commands.ts
8298
+ // ../core/src/app/commands.ts
8332
8299
  const DAY_MS$2 = 864e5;
8333
8300
  const TASKLESS = [
8334
8301
  "task.add",
@@ -8494,8 +8461,7 @@ async function purgeExpiredCommands(store, clock, retentionDays) {
8494
8461
  await trx.deleteFrom("command").where("at", "<", cutoff).execute();
8495
8462
  });
8496
8463
  }
8497
- //#endregion
8498
- //#region ../core/src/app/queries.ts
8464
+ // ../core/src/app/queries.ts
8499
8465
  /** Authorize a catalog query against current state before reading its result. */
8500
8466
  function createQuery(deps) {
8501
8467
  const { store, clock, config } = deps;
@@ -8547,8 +8513,7 @@ function createQuery(deps) {
8547
8513
  return result.value;
8548
8514
  };
8549
8515
  }
8550
- //#endregion
8551
- //#region ../core/src/app/operations.ts
8516
+ // ../core/src/app/operations.ts
8552
8517
  /** One app-layer dispatch for local HTTP and gateway interactions. */
8553
8518
  async function dispatchOperation(deps, id, input, actor, key) {
8554
8519
  const operation = OPERATIONS.find((entry) => entry.id === id);
@@ -8556,8 +8521,7 @@ async function dispatchOperation(deps, id, input, actor, key) {
8556
8521
  if (operation === void 0 || handler === void 0 || handler.id !== id) throw new CommandError("not_implemented", `Operation ${id} is not available in this daemon build. Ask the operator to update the daemon.`);
8557
8522
  return operation.kind === "query" ? createQuery(deps)(handler, input, actor) : createApply(deps)(handler, input, actor, key);
8558
8523
  }
8559
- //#endregion
8560
- //#region ../core/src/app/subject.ts
8524
+ // ../core/src/app/subject.ts
8561
8525
  function taskSubject(task) {
8562
8526
  return {
8563
8527
  project: task.project,
@@ -8586,8 +8550,7 @@ async function blockSubject(trx, block) {
8586
8550
  if (block.project === null) throw new Error("Block has neither a task nor a project");
8587
8551
  return projectSubject(block.project);
8588
8552
  }
8589
- //#endregion
8590
- //#region ../core/src/domain/fromYou.ts
8553
+ // ../core/src/domain/fromYou.ts
8591
8554
  const ITEM_POLICY = {
8592
8555
  token_request: {
8593
8556
  retry: "none",
@@ -8789,8 +8752,7 @@ function fingerprint(candidate) {
8789
8752
  function orderItems(items) {
8790
8753
  return [...items].sort((left, right) => left.priority - right.priority || left.key.localeCompare(right.key));
8791
8754
  }
8792
- //#endregion
8793
- //#region ../core/src/app/item-raise.ts
8755
+ // ../core/src/app/item-raise.ts
8794
8756
  /** Display label of a feed line with no task; not part of the line's identity. */
8795
8757
  const TASKLESS_FEED_KEY = "spur-board";
8796
8758
  /** Link of an item with no task to open. */
@@ -8868,8 +8830,7 @@ async function raiseItemWith(trx, input, writeLine) {
8868
8830
  }
8869
8831
  return item;
8870
8832
  }
8871
- //#endregion
8872
- //#region ../core/src/app/outbox.ts
8833
+ // ../core/src/app/outbox.ts
8873
8834
  const OUTBOX_KINDS = [
8874
8835
  "conversation.open",
8875
8836
  "conversation.reply",
@@ -9597,8 +9558,7 @@ async function enqueueConversationNotice(trx, input) {
9597
9558
  at: input.at
9598
9559
  });
9599
9560
  }
9600
- //#endregion
9601
- //#region ../core/src/app/block-thread.ts
9561
+ // ../core/src/app/block-thread.ts
9602
9562
  function orchestrator(config, task) {
9603
9563
  const name = config.projects.find((project) => project.id === task.project)?.columns.find((column) => column.id === task.column)?.orchestrator;
9604
9564
  return name === void 0 || name === "none" ? null : name;
@@ -9659,8 +9619,7 @@ async function queueBlockOpen(trx, subject, block, ctx, config) {
9659
9619
  at: new Date(ctx.at)
9660
9620
  });
9661
9621
  }
9662
- //#endregion
9663
- //#region ../core/src/app/feed.ts
9622
+ // ../core/src/app/feed.ts
9664
9623
  /** The struck summary is capped so the edit stays one message part. */
9665
9624
  const MAX_SUMMARY = 500;
9666
9625
  /**
@@ -9881,8 +9840,7 @@ function tokenCardBody(card, config) {
9881
9840
  ]
9882
9841
  }];
9883
9842
  }
9884
- //#endregion
9885
- //#region ../core/src/app/doorbells.ts
9843
+ // ../core/src/app/doorbells.ts
9886
9844
  const UNANSWERED = "unanswered";
9887
9845
  async function journal$2(trx, notification, kind, payload, at) {
9888
9846
  await emit(trx, kind, await noticeProject(trx, notification), notification.task_id, at.toISOString(), payload);
@@ -10666,8 +10624,7 @@ async function closeOwnedNotifications(trx, kind, ownerId, at, actor) {
10666
10624
  if (item !== void 0) await clearItem(trx, item.id, at, actor);
10667
10625
  }
10668
10626
  }
10669
- //#endregion
10670
- //#region ../core/src/app/skill-reload.ts
10627
+ // ../core/src/app/skill-reload.ts
10671
10628
  /** An installed spur-board version: strict semver with an optional prerelease. */
10672
10629
  const SKILL_VERSION = z.string().max(64).regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/);
10673
10630
  /** Session ids a caller already holds, checked as the session part of an agent actor ID. */
@@ -10733,9 +10690,8 @@ async function skillReloads(db, version, sessions) {
10733
10690
  }];
10734
10691
  }).sort((left, right) => left.id < right.id ? -1 : left.id > right.id ? 1 : 0);
10735
10692
  }
10736
- //#endregion
10737
- //#region ../core/src/app/tokens.ts
10738
- const REQUEST_LIFETIME_MS = 900 * 1e3;
10693
+ // ../core/src/app/tokens.ts
10694
+ const REQUEST_LIFETIME_MS = 9e5;
10739
10695
  const MAX_PENDING_REQUESTS = 10;
10740
10696
  /** Days an expired or denied request stays after its decision before the daily purge drops it. */
10741
10697
  const TOKEN_REQUEST_RETENTION_DAYS = 7;
@@ -10759,7 +10715,7 @@ const LIST_TEXT = 2800;
10759
10715
  /** Kept for the `N more` line. */
10760
10716
  const LIST_MORE = 40;
10761
10717
  /** An approved token's last use is written at most once per token per this interval. */
10762
- const TOKEN_USE_INTERVAL_MS = 5 * 6e4;
10718
+ const TOKEN_USE_INTERVAL_MS = 3e5;
10763
10719
  /** The longest attention line; the doctor fix limit is the same. */
10764
10720
  const ATTENTION_LINE_MAX = 300;
10765
10721
  /** The Revoke button of the token approved through item `itemId`, on its card or in a list. */
@@ -11106,8 +11062,7 @@ function tokenAttentionLine(attention, unusedAfterDays) {
11106
11062
  }
11107
11063
  return `${head}: ${String(total)} not named`;
11108
11064
  }
11109
- //#endregion
11110
- //#region ../core/src/api/ops-route.ts
11065
+ // ../core/src/api/ops-route.ts
11111
11066
  function inputBody(body) {
11112
11067
  if (body === null || typeof body !== "object" || Array.isArray(body)) throw new CommandError("usage", "Send a JSON object with input and optional key.");
11113
11068
  const record = body;
@@ -11168,8 +11123,7 @@ function createOpsRoute(app, options, callers = /* @__PURE__ */ new WeakMap()) {
11168
11123
  }));
11169
11124
  });
11170
11125
  }
11171
- //#endregion
11172
- //#region ../core/src/api/identity.ts
11126
+ // ../core/src/api/identity.ts
11173
11127
  function sessionActor(project, session, config) {
11174
11128
  const actor = actorIdSchema.safeParse(`agent:${project}/${session}`);
11175
11129
  if (!actor.success) throw new CommandError("forbidden", "Invalid session identity.");
@@ -11216,8 +11170,7 @@ async function identifyCaller(ports, headers) {
11216
11170
  }
11217
11171
  throw new CommandError("forbidden", "A session or accepted token is required.");
11218
11172
  }
11219
- //#endregion
11220
- //#region ../core/src/api/server.ts
11173
+ // ../core/src/api/server.ts
11221
11174
  const tokenStatusSchema = z.strictObject({ hash: tokenRequestSchema.shape.hash });
11222
11175
  const skillReloadSchema = z.strictObject({ version: SKILL_VERSION });
11223
11176
  const skillReloadsSchema = z.strictObject({
@@ -11369,8 +11322,7 @@ function listenApiServer(app, port) {
11369
11322
  port
11370
11323
  });
11371
11324
  }
11372
- //#endregion
11373
- //#region ../core/src/app/turns.ts
11325
+ // ../core/src/app/turns.ts
11374
11326
  const handedSchema = z.array(turnHandedSchema);
11375
11327
  const turnItemKey = (turnId) => `turn:${String(turnId)}`;
11376
11328
  const turnRef = (turnId) => `T${String(turnId)}`;
@@ -11764,8 +11716,7 @@ function handedOn(row, ref) {
11764
11716
  if (row.repo?.toLowerCase() !== repo || row.number !== ref.number) return [];
11765
11717
  return turnHanded(row).filter((entry) => entry.repo.toLowerCase() === repo && entry.number === ref.number);
11766
11718
  }
11767
- //#endregion
11768
- //#region ../core/src/app/blocks.ts
11719
+ // ../core/src/app/blocks.ts
11769
11720
  const idNumber = (id) => Number(id.slice(1));
11770
11721
  const blockId$1 = (id) => `B${String(id)}`;
11771
11722
  const commentId = (id) => `C${String(id)}`;
@@ -12466,9 +12417,11 @@ function createBlockMutations(config) {
12466
12417
  if (block !== void 0 && block.task_id !== task.id) throw new CommandError("not_found", "Block does not belong to this task.");
12467
12418
  const subject = taskSubject(task);
12468
12419
  let addressee = "worker";
12469
- if (block !== void 0) if (ctx.actor !== block.author) addressee = authorRole(config, subject, block.author);
12470
- else if (block.outcome === "done" && block.unblocked_by !== null && block.unblocked_by !== block.author) addressee = authorRole(config, subject, block.unblocked_by);
12471
- else addressee = block.addressee_role;
12420
+ if (block !== void 0) {
12421
+ if (ctx.actor !== block.author) addressee = authorRole(config, subject, block.author);
12422
+ else if (block.outcome === "done" && block.unblocked_by !== null && block.unblocked_by !== block.author) addressee = authorRole(config, subject, block.unblocked_by);
12423
+ else addressee = block.addressee_role;
12424
+ }
12472
12425
  return { comment: commentView(await addComment(trx, subject, block, input.text, ctx, addressee, config), subject) };
12473
12426
  }
12474
12427
  };
@@ -12620,8 +12573,7 @@ function createBlockMutations(config) {
12620
12573
  }
12621
12574
  };
12622
12575
  }
12623
- //#endregion
12624
- //#region ../core/src/app/pr-associations.ts
12576
+ // ../core/src/app/pr-associations.ts
12625
12577
  const prPollingSchema = z.strictObject({
12626
12578
  state: z.enum(["merged", "closed"]),
12627
12579
  headSha: prFactsSchema.shape.headSha,
@@ -12742,8 +12694,7 @@ async function reconcileTaskPrs(trx, config, taskId, at) {
12742
12694
  }, at);
12743
12695
  }
12744
12696
  }
12745
- //#endregion
12746
- //#region ../core/src/app/archive.ts
12697
+ // ../core/src/app/archive.ts
12747
12698
  /**
12748
12699
  * Takes a task off the board in the caller's transaction: closes its open blocks with outcome
12749
12700
  * `archived` and its unclosed turns, clears its board-derived items, cancels its unsent doorbells
@@ -12776,8 +12727,7 @@ async function archiveTask(trx, input) {
12776
12727
  }).where("id", "=", task.id).execute();
12777
12728
  await emit(trx, "task_archived", task.project, task.id, at, { reason }, actor);
12778
12729
  }
12779
- //#endregion
12780
- //#region ../core/src/app/membership.ts
12730
+ // ../core/src/app/membership.ts
12781
12731
  function canonicalKey(config, key) {
12782
12732
  const parsed = parseRef$1(key, "task");
12783
12733
  if (!parsed.ok || parsed.value.kind !== "task") throw new CommandError("not_found", "Check the tracker task key.");
@@ -12886,8 +12836,7 @@ function createMembershipMutations(config) {
12886
12836
  }
12887
12837
  };
12888
12838
  }
12889
- //#endregion
12890
- //#region ../core/src/app/conversations.ts
12839
+ // ../core/src/app/conversations.ts
12891
12840
  /**
12892
12841
  * The only writer of conversation rows. A block thread takes its task, state and start from the
12893
12842
  * block row, never from an outbox payload: a key merge moves the block but leaves delivered rows.
@@ -12982,15 +12931,14 @@ async function advanceConversationCursor(trx, conversation, message, at) {
12982
12931
  }
12983
12932
  /** Distinct block conversations to pass to recovery, with seven days of closed history. */
12984
12933
  async function conversationsForRecovery(trx, gateway, now) {
12985
- const cutoff = (/* @__PURE__ */ new Date(now.getTime() - 7 * 864e5)).toISOString();
12934
+ const cutoff = (/* @__PURE__ */ new Date(now.getTime() - 6048e5)).toISOString();
12986
12935
  const rows = await trx.selectFrom("conversation").selectAll().where("gateway", "=", gateway).where("purpose", "=", "block").where((eb) => eb.or([eb("state", "=", "open"), eb("closed_at", ">=", cutoff)])).orderBy("created_at").execute();
12987
12936
  return {
12988
12937
  rows,
12989
12938
  since: rows[0] === void 0 ? now : new Date(rows[0].created_at)
12990
12939
  };
12991
12940
  }
12992
- //#endregion
12993
- //#region ../core/src/app/sender.ts
12941
+ // ../core/src/app/sender.ts
12994
12942
  /**
12995
12943
  * Spur refused a doorbell for good (a permanent 4xx): the sender stops ringing and ends the ring
12996
12944
  * instead of retrying it. Any other error from `send` is retried.
@@ -13000,8 +12948,8 @@ var SpurRejectedError = class extends Error {
13000
12948
  };
13001
12949
  /** 1 msg/s per space: a platform limit, not an operator setting. */
13002
12950
  const SPACE_INTERVAL_MS = 1e3;
13003
- const RETRY_WINDOW_MS = 30 * 6e4;
13004
- const DOWN_THRESHOLD_MS = 5 * 6e4;
12951
+ const RETRY_WINDOW_MS = 18e5;
12952
+ const DOWN_THRESHOLD_MS = 3e5;
13005
12953
  const HEALTH_PROBE_MS = 6e4;
13006
12954
  const MAX_BACKOFF_MS$1 = 6e4;
13007
12955
  /** post_failed rows rescanned per `recover()` transaction: far below the scan's string limit. */
@@ -13631,8 +13579,7 @@ function createSender(options) {
13631
13579
  }
13632
13580
  };
13633
13581
  }
13634
- //#endregion
13635
- //#region ../core/src/app/items.ts
13582
+ // ../core/src/app/items.ts
13636
13583
  async function loadItem(trx, id) {
13637
13584
  const item = await trx.selectFrom("operator_item").selectAll().where("id", "=", Number(id.slice(1))).executeTakeFirst();
13638
13585
  if (item === void 0) throw new CommandError("not_found", "Check the item ID.");
@@ -13796,8 +13743,7 @@ function createItemMutations(deps) {
13796
13743
  }
13797
13744
  };
13798
13745
  }
13799
- //#endregion
13800
- //#region ../core/src/app/pr-refresh.ts
13746
+ // ../core/src/app/pr-refresh.ts
13801
13747
  /** Shared by explicit task reads and manual PR links; one deadline covers every distinct PR. */
13802
13748
  async function refreshPrs(config, projectId, refs, poll) {
13803
13749
  if (refs.length === 0) return;
@@ -13827,8 +13773,7 @@ async function refreshPrs(config, projectId, refs, poll) {
13827
13773
  }
13828
13774
  }
13829
13775
  }
13830
- //#endregion
13831
- //#region ../core/src/app/links.ts
13776
+ // ../core/src/app/links.ts
13832
13777
  function prIdentity(url) {
13833
13778
  const parsed = new URL(url);
13834
13779
  const match = /^\/([^/]+)\/([^/]+)\/pull\/([1-9]\d*)\/?$/.exec(parsed.pathname);
@@ -14048,10 +13993,9 @@ function createLinkMutations(config, deps = {}) {
14048
13993
  }
14049
13994
  };
14050
13995
  }
14051
- //#endregion
14052
- //#region ../core/src/app/operator-inbox.ts
13996
+ // ../core/src/app/operator-inbox.ts
14053
13997
  /** How far back `handled` reaches, and how many entries it keeps. */
14054
- const HANDLED_WINDOW_MS = 1440 * 60 * 1e3;
13998
+ const HANDLED_WINDOW_MS = 864e5;
14055
13999
  const HANDLED_MAX = 20;
14056
14000
  /** What a failure item asks the operator to check; a `source:` item gets its own text. */
14057
14001
  const CHECK_HINTS = {
@@ -14241,8 +14185,114 @@ function blockRows(trx) {
14241
14185
  function turnRows(trx) {
14242
14186
  return trx.selectFrom("turn").innerJoin("task", "task.id", "turn.task_id").selectAll("turn").select(taskColumns).where("turn.role", "=", "operator");
14243
14187
  }
14244
- //#endregion
14245
- //#region ../core/src/app/status-views.ts
14188
+ // ../core/src/app/status-services.ts
14189
+ /** The daemon row is degraded after this long without a completed board tick. */
14190
+ const DAEMON_STALL_MS = 2 * BOARD_TICK_MS;
14191
+ /** Service of each source id prefix; sources with any other prefix get no services row. */
14192
+ const SOURCE_SERVICES = {
14193
+ github: "github",
14194
+ "github-issues": "github",
14195
+ spur: "spur",
14196
+ jira: "jira"
14197
+ };
14198
+ const STATE_RANK = {
14199
+ healthy: 0,
14200
+ degraded: 1,
14201
+ failing: 2
14202
+ };
14203
+ /** The latest or oldest of `values`, or null when any is null. */
14204
+ function pickTime(values, pick) {
14205
+ let chosen = null;
14206
+ for (const value of values) {
14207
+ if (value === null) return null;
14208
+ if (chosen === null || Date.parse(value) > Date.parse(chosen) === (pick === "latest")) chosen = value;
14209
+ }
14210
+ return chosen;
14211
+ }
14212
+ /** One source's health: failing when blind, degraded while not fully usable, else healthy. */
14213
+ function sourceHealth(source, config, now) {
14214
+ if (source.blindReason !== null) {
14215
+ const message = source.message === null ? "" : `: ${source.message}`;
14216
+ return {
14217
+ state: "failing",
14218
+ reason: `${source.source} blind (${source.blindReason})${message}`
14219
+ };
14220
+ }
14221
+ const degraded = (reason) => ({
14222
+ state: "degraded",
14223
+ reason
14224
+ });
14225
+ if (source.lastCompleteAt === null) return degraded(`${source.source} ${source.warmingUp ? "warming up" : "never completed"}`);
14226
+ if (source.stale) return degraded(`${source.source} stale`);
14227
+ if (source.warmingUp) return degraded(`${source.source} warming up`);
14228
+ const { budget } = source;
14229
+ if (source.source.startsWith("github") && budget !== null && budget.remaining < config.github.reserveRemaining && Date.parse(budget.resetAt) > now) return degraded(`${source.source} waits for its rate budget until ${budget.resetAt}`);
14230
+ return {
14231
+ state: "healthy",
14232
+ reason: null
14233
+ };
14234
+ }
14235
+ /**
14236
+ * One health row per service: the daemon, each gateway (board-wide), then github, spur and jira
14237
+ * rolled up from the given sources only.
14238
+ */
14239
+ function services(input) {
14240
+ const { config, now, daemon } = input;
14241
+ const lastTick = daemon.lastDispatchAt ?? daemon.startedAt;
14242
+ const stalled = now - Date.parse(lastTick) > DAEMON_STALL_MS;
14243
+ const rows = [{
14244
+ service: "daemon",
14245
+ state: stalled ? "degraded" : "healthy",
14246
+ since: stalled ? null : daemon.startedAt,
14247
+ lastGoodAt: daemon.lastDispatchAt,
14248
+ reason: stalled ? `no board tick completed since ${lastTick}` : null
14249
+ }];
14250
+ for (const gateway of input.transport) {
14251
+ const ended = input.outageEnds.get(gateway.gateway);
14252
+ rows.push(gateway.state === "down" ? {
14253
+ service: gateway.gateway,
14254
+ state: "failing",
14255
+ since: gateway.since,
14256
+ lastGoodAt: null,
14257
+ reason: gateway.reason
14258
+ } : {
14259
+ service: gateway.gateway,
14260
+ state: "healthy",
14261
+ since: ended !== void 0 && Date.parse(ended) > Date.parse(daemon.startedAt) ? ended : daemon.startedAt,
14262
+ lastGoodAt: null,
14263
+ reason: null
14264
+ });
14265
+ }
14266
+ for (const service of [
14267
+ "github",
14268
+ "spur",
14269
+ "jira"
14270
+ ]) {
14271
+ const members = input.sources.filter((source) => SOURCE_SERVICES[source.source.split(":")[0] ?? ""] === service);
14272
+ if (members.length === 0) continue;
14273
+ const worst = members.map((source) => sourceHealth(source, config, now)).reduce((a, b) => STATE_RANK[b.state] > STATE_RANK[a.state] ? b : a);
14274
+ rows.push({
14275
+ service,
14276
+ state: worst.state,
14277
+ since: worst.state === "healthy" ? pickTime(members.map((source) => source.healthySince), "latest") : null,
14278
+ lastGoodAt: pickTime(members.map((source) => source.observedAt), "oldest"),
14279
+ reason: worst.reason
14280
+ });
14281
+ }
14282
+ return rows;
14283
+ }
14284
+ /** End of each gateway's last recorded outage: the clear time of its newest transport item. */
14285
+ async function readOutageEnds(db) {
14286
+ const items = await db.selectFrom("operator_item").select(["item_key", "cleared_at"]).where("item_key", "like", "transport:%").orderBy("raise_no").execute();
14287
+ const outageEnds = /* @__PURE__ */ new Map();
14288
+ for (const item of items) {
14289
+ const gateway = item.item_key.slice(10);
14290
+ if (item.cleared_at === null) outageEnds.delete(gateway);
14291
+ else outageEnds.set(gateway, item.cleared_at);
14292
+ }
14293
+ return outageEnds;
14294
+ }
14295
+ // ../core/src/app/status-views.ts
14246
14296
  /** Factual PR rollup; the caller owns snapshot freshness and all reads. */
14247
14297
  function summarizePr(fact, factAt, unconfirmed) {
14248
14298
  const checks = fact.requiredChecks.length > 0 ? fact.requiredChecks : fact.checks;
@@ -14357,8 +14407,7 @@ async function readStatusBlocks(db, projectIds) {
14357
14407
  }
14358
14408
  return blocks;
14359
14409
  }
14360
- //#endregion
14361
- //#region ../core/src/app/status.ts
14410
+ // ../core/src/app/status.ts
14362
14411
  function sessionView(fact) {
14363
14412
  return {
14364
14413
  ...fact,
@@ -14409,7 +14458,7 @@ function issuesRepo(project) {
14409
14458
  return project?.tracker.type === "github-issues" ? project.tracker.repo.toLowerCase() : null;
14410
14459
  }
14411
14460
  /** Unlinked PRs and sessions finished longer ago than this are counted, not listed. */
14412
- const UNLINKED_WINDOW_MS = 10080 * 60 * 1e3;
14461
+ const UNLINKED_WINDOW_MS = 6048e5;
14413
14462
  function interval(config, source) {
14414
14463
  if (source === "spur") return config.adapters.spur.intervalMs;
14415
14464
  if (source.startsWith("jira:")) return config.adapters.jira.intervalMs;
@@ -14600,6 +14649,7 @@ async function getStatus(deps, options = {}) {
14600
14649
  resetAt: row.budget_reset_at
14601
14650
  } : null,
14602
14651
  stale: last === null || clock.now() - Date.parse(last) > config.thresholds.staleMultiplier * interval(config, source),
14652
+ healthySince: deps.healthySince?.get(source) ?? null,
14603
14653
  warmingUp: !completeSince.has(source)
14604
14654
  };
14605
14655
  });
@@ -14656,6 +14706,15 @@ async function getStatus(deps, options = {}) {
14656
14706
  warmingUp: sources.some((source) => source.warmingUp),
14657
14707
  spurUnavailable: spur?.blind_reason === null || spur === void 0 ? null : `Spur unavailable: ${spur.blind_message ?? spur.blind_reason}`,
14658
14708
  hostLoad: host?.value !== void 0 && host.value !== "null" ? "Host under load" : null,
14709
+ host: deps.host ?? null,
14710
+ services: services({
14711
+ config,
14712
+ now: clock.now(),
14713
+ daemon,
14714
+ transport,
14715
+ outageEnds: await readOutageEnds(store.db),
14716
+ sources
14717
+ }),
14659
14718
  transport,
14660
14719
  sources,
14661
14720
  tasks,
@@ -14914,8 +14973,7 @@ function countCycles(events, column, limit) {
14914
14973
  limitReached: count >= limit
14915
14974
  };
14916
14975
  }
14917
- //#endregion
14918
- //#region ../core/src/domain/dispatch.ts
14976
+ // ../core/src/domain/dispatch.ts
14919
14977
  /** No rule cycles, so a real cascade ends long before this; the bound is a guard. */
14920
14978
  const STEP_BOUND = 2 * COLUMN_IDS.length;
14921
14979
  const NO_TURN = {
@@ -15098,8 +15156,7 @@ function turnReason(turn, rerouted) {
15098
15156
  if (turn.kind === "reroute" && rerouted !== void 0) return rerouted;
15099
15157
  return `${turn.column}: ${turn.reasons.join(", ")}`;
15100
15158
  }
15101
- //#endregion
15102
- //#region ../core/src/app/course-check.ts
15159
+ // ../core/src/app/course-check.ts
15103
15160
  /** The longest text of one open finding in the course check's question. */
15104
15161
  const MAX_FINDING = 300;
15105
15162
  const cycleKeyPrefix = (taskId) => `cycle-limit:${String(taskId)}:`;
@@ -15281,8 +15338,7 @@ async function shadowCourseCheck(trx, taskId, move, project) {
15281
15338
  const after = countCycles([...past, current], move.from, every).count;
15282
15339
  return after > before && after % every === 0;
15283
15340
  }
15284
- //#endregion
15285
- //#region ../core/src/domain/health.ts
15341
+ // ../core/src/domain/health.ts
15286
15342
  const ENDED_WORKER_KINDS = {
15287
15343
  complete: "worker_completed",
15288
15344
  kill: "worker_killed",
@@ -15386,8 +15442,7 @@ function evaluateSessionHealth(input) {
15386
15442
  function prsPolledSince(task, since) {
15387
15443
  return task.prCompleteAt !== null && task.prCompleteAt >= Date.parse(since);
15388
15444
  }
15389
- //#endregion
15390
- //#region ../core/src/app/fromYou.ts
15445
+ // ../core/src/app/fromYou.ts
15391
15446
  const episodeSchema = z.object({ startedAt: z.number() }).nullable();
15392
15447
  const stallEpisodeSchema = z.object({
15393
15448
  session: z.string().nullable(),
@@ -15996,8 +16051,7 @@ async function observeTurnEpisode(trx, turnId, fact) {
15996
16051
  function healthKey(taskId, flag) {
15997
16052
  return `health:${String(taskId)}:${flag.sessionId}:${flag.kind}`;
15998
16053
  }
15999
- //#endregion
16000
- //#region ../core/src/app/dispatch.ts
16054
+ // ../core/src/app/dispatch.ts
16001
16055
  const CURSOR_KEY = "dispatcher_cursor";
16002
16056
  const modeKey = (project) => `dispatcher_mode:${project}`;
16003
16057
  const cursorSchema = z.int().min(0);
@@ -16703,8 +16757,7 @@ async function dispatchMergedTickets(trx, source, ctx) {
16703
16757
  if (project === void 0) return;
16704
16758
  await dispatchTasks(trx, (await trx.selectFrom("task").innerJoin("link", "link.task_id", "task.id").innerJoin("pr_snapshot", (join) => join.on(sql`lower(pr_snapshot.repo) = lower(link.repo)`).onRef("pr_snapshot.number", "=", "link.number")).select("task.id").distinct().where("task.project", "=", project.id).where("task.membership", "!=", "archived").where((eb) => eb.or([eb("task.column", "!=", "done"), eb("task.shadow_column", "!=", "done")])).where("link.entity", "=", "pr").where("link.pr_state", "=", "active").where("link.banned", "=", 0).where("pr_snapshot.state", "=", "merged").execute()).map((task) => task.id), ctx);
16705
16759
  }
16706
- //#endregion
16707
- //#region ../core/src/app/task-turns.ts
16760
+ // ../core/src/app/task-turns.ts
16708
16761
  /** How many closed turns `task.get --detail` shows. */
16709
16762
  const DETAIL_TURNS = 5;
16710
16763
  async function taskTurnView(trx, turn) {
@@ -16765,8 +16818,7 @@ function turnSummary(kind, payloadText) {
16765
16818
  return null;
16766
16819
  }
16767
16820
  }
16768
- //#endregion
16769
- //#region ../core/src/app/task-sessions.ts
16821
+ // ../core/src/app/task-sessions.ts
16770
16822
  /** Current facts of the effective session links that task.get exposes. */
16771
16823
  async function taskSessions(trx, taskId) {
16772
16824
  return (await trx.selectFrom("link").innerJoin("session_snapshot", "session_snapshot.id", "link.session_id").select("session_snapshot.detail").where("link.task_id", "=", taskId).where("link.entity", "=", "session").where("link.banned", "=", 0).orderBy("link.id").execute()).map((row) => {
@@ -16780,8 +16832,7 @@ async function taskSessions(trx, taskId) {
16780
16832
  };
16781
16833
  });
16782
16834
  }
16783
- //#endregion
16784
- //#region ../core/src/app/turn-view.ts
16835
+ // ../core/src/app/turn-view.ts
16785
16836
  /**
16786
16837
  * The unresolved review threads a Dev turn lists, read live from the task's PR snapshot: only on a
16787
16838
  * project requiring resolved threads and an open PR, and only threads with an id and a link (facts
@@ -16822,8 +16873,7 @@ async function turnView(trx, turn, task, project) {
16822
16873
  ...threads === void 0 ? {} : { threads }
16823
16874
  };
16824
16875
  }
16825
- //#endregion
16826
- //#region ../core/src/app/task-queries.ts
16876
+ // ../core/src/app/task-queries.ts
16827
16877
  /** How many of the last moves `task.get --why` shows. */
16828
16878
  const WHY_MOVES = 5;
16829
16879
  /** The fact each hold-only gate reason waits for, as `--why` names it. */
@@ -17155,8 +17205,7 @@ function createTaskQueries(deps) {
17155
17205
  }
17156
17206
  };
17157
17207
  }
17158
- //#endregion
17159
- //#region ../core/src/app/turn-commands.ts
17208
+ // ../core/src/app/turn-commands.ts
17160
17209
  /** How long `task.submit` waits for its on-demand PR poll; the CLI gives up at 30 s. */
17161
17210
  const SUBMIT_POLL_TIMEOUT_MS = 1e4;
17162
17211
  /** Columns a task returns to Dev from: right of Dev, before the terminal Done. */
@@ -17515,8 +17564,7 @@ function createTurnMutations(deps) {
17515
17564
  }
17516
17565
  };
17517
17566
  }
17518
- //#endregion
17519
- //#region ../core/src/app/registry.ts
17567
+ // ../core/src/app/registry.ts
17520
17568
  const catalog = await buildCatalogSnapshot(OPERATIONS);
17521
17569
  /** Concrete handlers shared by the daemon's HTTP and inbound transports. */
17522
17570
  function createOperationRegistry(deps) {
@@ -17588,7 +17636,9 @@ function createOperationRegistry(deps) {
17588
17636
  version: productVersion,
17589
17637
  startedAt,
17590
17638
  lastDispatchAt: lastDispatchAt()
17591
- }
17639
+ },
17640
+ healthySince: deps.healthySince,
17641
+ host: deps.hostMetrics?.()
17592
17642
  }, {
17593
17643
  project: input.project,
17594
17644
  visibleProjects: visibleProjects(config, actor),
@@ -17667,8 +17717,7 @@ function createOperationRegistry(deps) {
17667
17717
  "task.move": turns.move
17668
17718
  };
17669
17719
  }
17670
- //#endregion
17671
- //#region ../core/src/app/doctor.ts
17720
+ // ../core/src/app/doctor.ts
17672
17721
  const LIVE_VERSION_KEY = "doctor_live_version";
17673
17722
  /** Configured adapter IDs, including repos used by more than one project. */
17674
17723
  function doctorSources(config) {
@@ -17733,8 +17782,7 @@ async function enqueueLiveAfterFirstPoll(trx, input) {
17733
17782
  value
17734
17783
  }).onConflict((oc) => oc.column("key").doUpdateSet({ value })).execute();
17735
17784
  }
17736
- //#endregion
17737
- //#region ../core/src/app/membership-rules.ts
17785
+ // ../core/src/app/membership-rules.ts
17738
17786
  /** Run-local completeness is the only evidence allowed to authorize filter absence. */
17739
17787
  async function reconcileMembership(trx, config, completeSince, at, warnSkipped) {
17740
17788
  const states = await trx.selectFrom("source_state").select(["source", "blind_reason"]).execute();
@@ -17781,8 +17829,7 @@ async function reconcileMembership(trx, config, completeSince, at, warnSkipped)
17781
17829
  }
17782
17830
  }
17783
17831
  }
17784
- //#endregion
17785
- //#region ../core/src/app/observe.ts
17832
+ // ../core/src/app/observe.ts
17786
17833
  function refKey(ref) {
17787
17834
  switch (ref.kind) {
17788
17835
  case "pr": return `pr:${ref.repo.toLowerCase()}#${String(ref.number)}`;
@@ -18013,7 +18060,7 @@ async function pr(trx, config, fact, at, source) {
18013
18060
  })).execute();
18014
18061
  const old = await trx.selectFrom("pr_snapshot").selectAll().where(sql`lower(repo) = ${fact.repo.toLowerCase()}`).where("number", "=", fact.number).executeTakeFirst();
18015
18062
  const previous = old === void 0 ? null : parseJson(prFactsSchema, old.detail);
18016
- const recheckAt = fact.state === "closed" ? new Date(Date.parse(at) + 360 * 6e4).toISOString() : null;
18063
+ const recheckAt = fact.state === "closed" ? new Date(Date.parse(at) + 216e5).toISOString() : null;
18017
18064
  if (old !== void 0 && previous !== null && old.source !== source) await savePrPolling(trx, old.source, previous, old.closed_recheck_at, true);
18018
18065
  await savePrPolling(trx, source, fact, recheckAt);
18019
18066
  const changed = previous === null || JSON.stringify(previous) !== JSON.stringify(fact);
@@ -18237,8 +18284,10 @@ async function session(trx, config, fact, at, source, ambiguousBranches, feedEna
18237
18284
  "pr_snapshot.head_branch"
18238
18285
  ]).where("link.entity", "=", "pr").where(sql`lower(link.repo) = ${fact.pr.repo.toLowerCase()}`).where("link.number", "=", fact.pr.number).where("link.banned", "=", 0).executeTakeFirst();
18239
18286
  const project = config.projects.find((entry) => entry.id === linked?.project);
18240
- if (linked !== void 0 && project?.spurProjects.some((spur) => spur.name === fact.spurProject && spur.role === "worker")) if (fact.branch !== null && linked.head_branch === fact.branch) key = linked.key;
18241
- else prOnlyKey = linked.key;
18287
+ if (linked !== void 0 && project?.spurProjects.some((spur) => spur.name === fact.spurProject && spur.role === "worker")) {
18288
+ if (fact.branch !== null && linked.head_branch === fact.branch) key = linked.key;
18289
+ else prOnlyKey = linked.key;
18290
+ }
18242
18291
  }
18243
18292
  if (key === void 0 && fact.branch !== null) {
18244
18293
  const tasks = await trx.selectFrom("task").selectAll().where("membership", "!=", "archived").execute();
@@ -18372,9 +18421,11 @@ async function recordUsage(trx, source, usage, now) {
18372
18421
  function createObservationCore(deps) {
18373
18422
  const { store, config, clock } = deps;
18374
18423
  const completeSince = /* @__PURE__ */ new Map();
18424
+ const healthySince = /* @__PURE__ */ new Map();
18375
18425
  const warnSkipped = warnSkippedOnce(deps.warn);
18376
18426
  return {
18377
18427
  completeSince,
18428
+ healthySince,
18378
18429
  warnSkipped,
18379
18430
  async context(source) {
18380
18431
  const state = await store.db.selectFrom("source_state").selectAll().where("source", "=", source).executeTakeFirst();
@@ -18476,7 +18527,7 @@ function createObservationCore(deps) {
18476
18527
  await recordUsage(trx, source, batch.usage, now);
18477
18528
  for (const probe of batch.prProbes ?? []) {
18478
18529
  if (probe.status !== "closed") continue;
18479
- const recheckAt = new Date(Date.parse(batch.observedAt) + 360 * 6e4).toISOString();
18530
+ const recheckAt = new Date(Date.parse(batch.observedAt) + 216e5).toISOString();
18480
18531
  const row = await trx.selectFrom("pr_snapshot").selectAll().where(sql`lower(repo) = ${probe.ref.repo.toLowerCase()}`).where("number", "=", probe.ref.number).where("state", "=", "closed").executeTakeFirst();
18481
18532
  if (row === void 0) continue;
18482
18533
  const saved = await trx.selectFrom("meta").select("value").where("key", "=", prPollingKey(source, probe.ref)).executeTakeFirst();
@@ -18608,10 +18659,12 @@ function createObservationCore(deps) {
18608
18659
  });
18609
18660
  });
18610
18661
  if (observation.effectiveComplete) completeSince.set(source, batch.observedAt);
18662
+ if (observation.state.blind !== void 0) healthySince.delete(source);
18663
+ else if (!healthySince.has(source)) healthySince.set(source, batch.observedAt);
18611
18664
  },
18612
- reportSourceState(source, state, usage) {
18665
+ async reportSourceState(source, state, usage) {
18613
18666
  const now = clock.now();
18614
- return scanTransaction(store, config, async (trx) => {
18667
+ await scanTransaction(store, config, async (trx) => {
18615
18668
  const wasBlind = await blindReason(trx, source);
18616
18669
  await sourceState(trx, source, state);
18617
18670
  await recordUsage(trx, source, usage, now);
@@ -18622,6 +18675,7 @@ function createObservationCore(deps) {
18622
18675
  });
18623
18676
  await reconcileItems(trx, config, now, completeSince.has("spur"), warnSkipped);
18624
18677
  });
18678
+ if (state.blind !== void 0) healthySince.delete(source);
18625
18679
  },
18626
18680
  notice(kind, value) {
18627
18681
  const at = new Date(clock.now()).toISOString();
@@ -18640,8 +18694,7 @@ function createObservationCore(deps) {
18640
18694
  }
18641
18695
  };
18642
18696
  }
18643
- //#endregion
18644
- //#region ../core/src/domain/slot.ts
18697
+ // ../core/src/domain/slot.ts
18645
18698
  const WEEKDAYS = [
18646
18699
  "sunday",
18647
18700
  "monday",
@@ -18674,8 +18727,8 @@ function lastLocalSlot(now, tz, weekday) {
18674
18727
  const localMidnight = Date.UTC(year, month - 1, day);
18675
18728
  const targetUtcDate = localMidnight - (new Date(localMidnight).getUTCDay() - WEEKDAYS.indexOf(weekday) + 7) % 7 * 864e5;
18676
18729
  const targetDate = new Date(targetUtcDate).toISOString().slice(0, 10);
18677
- let lower = targetUtcDate - 2 * 864e5;
18678
- let upper = targetUtcDate + 2 * 864e5;
18730
+ let lower = targetUtcDate - 1728e5;
18731
+ let upper = targetUtcDate + 1728e5;
18679
18732
  while (lower < upper) {
18680
18733
  const middle = Math.floor((lower + upper) / 2);
18681
18734
  if (localDate(middle) < targetDate) lower = middle + 1;
@@ -18683,8 +18736,7 @@ function lastLocalSlot(now, tz, weekday) {
18683
18736
  }
18684
18737
  return lower;
18685
18738
  }
18686
- //#endregion
18687
- //#region ../core/src/app/tick.ts
18739
+ // ../core/src/app/tick.ts
18688
18740
  /** One board tick, including an archive slot missed during downtime. */
18689
18741
  async function tickBoard(deps) {
18690
18742
  const { store, config, clock, completeSince } = deps;
@@ -18726,8 +18778,7 @@ async function tickBoard(deps) {
18726
18778
  await reconcileItems(trx, config, now, completeSince.has("spur"), deps.warnSkipped);
18727
18779
  });
18728
18780
  }
18729
- //#endregion
18730
- //#region ../core/src/app/command-replies.ts
18781
+ // ../core/src/app/command-replies.ts
18731
18782
  function line(text) {
18732
18783
  return {
18733
18784
  kind: "paragraph",
@@ -18835,8 +18886,7 @@ function commandReply(id, value, input) {
18835
18886
  body: [line(`Task ${history.task.key} history:`), ...history.events.map((event) => line(`${event.at}: ${event.summary} (${event.kind})`))]
18836
18887
  };
18837
18888
  }
18838
- //#endregion
18839
- //#region ../core/src/app/operator-conversation.ts
18889
+ // ../core/src/app/operator-conversation.ts
18840
18890
  function addressOperatorMessage(text, config) {
18841
18891
  const spurByShortName = /* @__PURE__ */ new Map();
18842
18892
  for (const project of config.projects) for (const spur of project.spurProjects) if (spur.shortName !== void 0) spurByShortName.set(spur.shortName, spur.name);
@@ -18918,8 +18968,7 @@ async function openOperatorConversation(trx, input) {
18918
18968
  if (conversation !== void 0) await advanceConversationCursor(trx, conversation, input.message, input.at);
18919
18969
  return true;
18920
18970
  }
18921
- //#endregion
18922
- //#region ../core/src/app/inbound.ts
18971
+ // ../core/src/app/inbound.ts
18923
18972
  const resultSchema = z.strictObject({
18924
18973
  status: z.enum([
18925
18974
  "applied",
@@ -19702,8 +19751,7 @@ function createInbound(input) {
19702
19751
  reapply
19703
19752
  };
19704
19753
  }
19705
- //#endregion
19706
- //#region ../core/src/api/sse.ts
19754
+ // ../core/src/api/sse.ts
19707
19755
  const POLL_MS = 300;
19708
19756
  const HEARTBEAT_MS = 15e3;
19709
19757
  const STATUS_MS = 3e4;
@@ -19964,8 +20012,7 @@ function installEventStream(app, options) {
19964
20012
  return reply.header("content-type", "text/event-stream").header("cache-control", "no-cache").header("x-accel-buffering", "no").send(pass);
19965
20013
  });
19966
20014
  }
19967
- //#endregion
19968
- //#region ../core/src/api/web-server.ts
20015
+ // ../core/src/api/web-server.ts
19969
20016
  const mime = {
19970
20017
  ".html": "text/html; charset=utf-8",
19971
20018
  ".js": "text/javascript; charset=utf-8",
@@ -20111,8 +20158,7 @@ async function createWebServer(options) {
20111
20158
  });
20112
20159
  return app;
20113
20160
  }
20114
- //#endregion
20115
- //#region ../daemon/src/config.ts
20161
+ // ../daemon/src/config.ts
20116
20162
  /** A config or secrets file the daemon cannot use. The message is meant for the operator. */
20117
20163
  var ConfigError = class extends Error {
20118
20164
  name = "ConfigError";
@@ -20208,8 +20254,7 @@ function loadConfig(paths) {
20208
20254
  secrets: readSecrets(paths.secretsFile)
20209
20255
  };
20210
20256
  }
20211
- //#endregion
20212
- //#region ../daemon/src/logger.ts
20257
+ // ../daemon/src/logger.ts
20213
20258
  const REDACTED = "[Redacted]";
20214
20259
  const MIN_SECRET_LENGTH = 8;
20215
20260
  const CREDENTIAL_KEY = /^(?:proxy-)?authorization$|^(?:set-)?cookie$|token$|password$|secret$|api[-_]?key$/i;
@@ -20276,8 +20321,7 @@ async function logCall(log, clock, call, fn) {
20276
20321
  throw err;
20277
20322
  }
20278
20323
  }
20279
- //#endregion
20280
- //#region ../daemon/src/lifecycle.ts
20324
+ // ../daemon/src/lifecycle.ts
20281
20325
  /**
20282
20326
  * Shutdown order after the shared signal aborts ("stop accepting"): pollers, then the outbox,
20283
20327
  * then everything else (HTTP close, gateways, core). Modules within a stage stop in parallel.
@@ -20456,8 +20500,7 @@ async function runDaemon(deps) {
20456
20500
  return;
20457
20501
  }
20458
20502
  }
20459
- //#endregion
20460
- //#region ../daemon/src/lock.ts
20503
+ // ../daemon/src/lock.ts
20461
20504
  /** Another process holds the lock. `pid` is null when the file holds no readable PID yet. */
20462
20505
  var LockHeldError = class extends Error {
20463
20506
  name = "LockHeldError";
@@ -20509,8 +20552,7 @@ function acquireLock(file) {
20509
20552
  const stderr = result.stderr.toString().trim();
20510
20553
  throw new Error(`flock failed to lock ${file} (status ${String(result.status)}): ${stderr || "no output"}`);
20511
20554
  }
20512
- //#endregion
20513
- //#region ../adapters/src/runner/wire.ts
20555
+ // ../adapters/src/runner/wire.ts
20514
20556
  /**
20515
20557
  * Returns the parsed value or throws a transient `AdapterError` naming the first failing path
20516
20558
  * (`<label> at <dot.path>`). `at` prefixes the path when the value sits inside a larger
@@ -20519,10 +20561,10 @@ function acquireLock(file) {
20519
20561
  function parseWire(schema, value, label, at = []) {
20520
20562
  const parsed = schema.safeParse(value);
20521
20563
  if (parsed.success) return parsed.data;
20522
- throw new AdapterError("transient", `${label} at ${[...at, ...parsed.error.issues[0]?.path ?? []].map(String).join(".") || "(root)"}`);
20564
+ const path = [...at, ...parsed.error.issues[0]?.path ?? []].map(String).join(".");
20565
+ throw new AdapterError("transient", `${label} at ${path || "(root)"}`);
20523
20566
  }
20524
- //#endregion
20525
- //#region ../adapters/src/runner/http.ts
20567
+ // ../adapters/src/runner/http.ts
20526
20568
  /** Classifies a failed response; `now` is the current time in epoch milliseconds. */
20527
20569
  function classifyHttpFailure(failure, now) {
20528
20570
  const { status, headers } = failure;
@@ -20563,8 +20605,7 @@ async function withTimeout(signal, message, work) {
20563
20605
  clearTimeout(handle);
20564
20606
  }
20565
20607
  }
20566
- //#endregion
20567
- //#region ../adapters/src/github/client.ts
20608
+ // ../adapters/src/github/client.ts
20568
20609
  const MALFORMED$3 = "Malformed GitHub response";
20569
20610
  const graphErrorWire = z.object({
20570
20611
  message: z.string(),
@@ -20723,8 +20764,7 @@ var GithubClient = class {
20723
20764
  };
20724
20765
  }
20725
20766
  };
20726
- //#endregion
20727
- //#region ../adapters/src/github/discovery.ts
20767
+ // ../adapters/src/github/discovery.ts
20728
20768
  const timestamp$1 = z.string().min(1).refine((value) => !Number.isNaN(Date.parse(value)));
20729
20769
  const discoveryNodeWire = z.object({
20730
20770
  number: z.int().positive(),
@@ -20773,8 +20813,7 @@ function nextPage(connection) {
20773
20813
  if (!endCursor) throw new Error("Malformed GitHub pagination");
20774
20814
  return endCursor;
20775
20815
  }
20776
- //#endregion
20777
- //#region ../adapters/src/github/feedbackLinks.ts
20816
+ // ../adapters/src/github/feedbackLinks.ts
20778
20817
  const threadCommentWire = z.object({
20779
20818
  id: z.string().min(1),
20780
20819
  url: z.string().optional(),
@@ -20814,8 +20853,7 @@ function inlineComments(threads) {
20814
20853
  }
20815
20854
  return byReview;
20816
20855
  }
20817
- //#endregion
20818
- //#region ../adapters/src/github/prBatch.ts
20856
+ // ../adapters/src/github/prBatch.ts
20819
20857
  const KEPT_REVIEWS = [
20820
20858
  "approved",
20821
20859
  "changes_requested",
@@ -21276,8 +21314,7 @@ function reusable(cached, entry, cursorKey, now) {
21276
21314
  if (entry.open && (entry.rollup !== null && entry.rollup !== "SUCCESS" || !entry.green)) return;
21277
21315
  return cached.facts;
21278
21316
  }
21279
- //#endregion
21280
- //#region ../adapters/src/github/index.ts
21317
+ // ../adapters/src/github/index.ts
21281
21318
  const MALFORMED$2 = "Malformed GitHub response";
21282
21319
  const discoveryRootWire = z.object({ pullRequests: connectionWire(discoveryNodeWire) });
21283
21320
  const baselineRootWire = z.object({ mergedBaseline: z.object({ nodes: z.array(baselineNodeWire) }) });
@@ -21959,8 +21996,7 @@ async function pollOnePr({ id, repo, keys, client, now, ref, ctx, cache }) {
21959
21996
  ...acc.budget === void 0 ? {} : { budget: acc.budget }
21960
21997
  };
21961
21998
  }
21962
- //#endregion
21963
- //#region ../adapters/src/github/issues.ts
21999
+ // ../adapters/src/github/issues.ts
21964
22000
  var GithubIssuesHttpError = class extends AdapterError {
21965
22001
  status;
21966
22002
  constructor(status, failure) {
@@ -22241,8 +22277,7 @@ function createGithubIssuesAdapter(options) {
22241
22277
  }
22242
22278
  };
22243
22279
  }
22244
- //#endregion
22245
- //#region ../adapters/src/jira/jira.ts
22280
+ // ../adapters/src/jira/jira.ts
22246
22281
  const SEARCH_PAGE_LIMIT = 20;
22247
22282
  const MAX_GET_SEARCH_URL_LENGTH = 2e3;
22248
22283
  const OUTSIDE_BATCH_SIZE = 50;
@@ -22561,8 +22596,7 @@ function createJiraAdapter(options) {
22561
22596
  }
22562
22597
  };
22563
22598
  }
22564
- //#endregion
22565
- //#region ../adapters/src/runner/policy.ts
22599
+ // ../adapters/src/runner/policy.ts
22566
22600
  /** The longest wait between two failed polls, unless the interval itself is longer. */
22567
22601
  const MAX_BACKOFF_MS = 9e5;
22568
22602
  /** Shortens a delay by up to 10 percent, so sources do not poll in lockstep. */
@@ -22673,8 +22707,7 @@ function applyEntityOutcomes(input) {
22673
22707
  complete
22674
22708
  };
22675
22709
  }
22676
- //#endregion
22677
- //#region ../adapters/src/runner/runner.ts
22710
+ // ../adapters/src/runner/runner.ts
22678
22711
  function answersProbes(context, batch) {
22679
22712
  const probes = batch.prProbes ?? [];
22680
22713
  const key = (ref) => `${ref.repo.toLowerCase()}#${String(ref.number)}`;
@@ -22799,14 +22832,14 @@ function runSource(entry, options, runnerStartMs) {
22799
22832
  /** Drain synchronously on abort, before the adapter unwinds or stop waits for reports. */
22800
22833
  async function readSource(read, signal) {
22801
22834
  const takeUsage = adapter.takeUsage?.bind(adapter);
22802
- if (takeUsage === void 0) return untilAborted$1(read(), signal);
22835
+ if (takeUsage === void 0) return untilAborted$2(read(), signal);
22803
22836
  const onAbort = () => {
22804
22837
  const usage = takeUsage();
22805
22838
  if (usage !== void 0) report(usage, true);
22806
22839
  };
22807
22840
  signal.addEventListener("abort", onAbort, { once: true });
22808
22841
  try {
22809
- return await untilAborted$1(read(), signal);
22842
+ return await untilAborted$2(read(), signal);
22810
22843
  } finally {
22811
22844
  signal.removeEventListener("abort", onAbort);
22812
22845
  }
@@ -22990,7 +23023,7 @@ function runSource(entry, options, runnerStartMs) {
22990
23023
  let usage;
22991
23024
  let step = "context";
22992
23025
  try {
22993
- const received = await untilAborted$1(core.context(source), abort.signal);
23026
+ const received = await untilAborted$2(core.context(source), abort.signal);
22994
23027
  if (aborted() || received === void 0) return err(stoppedError);
22995
23028
  const own = ({ ref: held }) => held.number === ref.number && held.repo.toLowerCase() === ref.repo.toLowerCase();
22996
23029
  const feedbackCursors = received.feedbackCursors?.filter(own) ?? [];
@@ -23172,7 +23205,7 @@ function demandValue(batch, observedAt) {
23172
23205
  * for an adapter that ignores its signal. A late result or rejection is dropped. The abort
23173
23206
  * listener is removed once either side settles, so a retained signal holds nothing.
23174
23207
  */
23175
- function untilAborted$1(work, signal) {
23208
+ function untilAborted$2(work, signal) {
23176
23209
  let settle = () => void 0;
23177
23210
  const abortion = new Promise((resolve) => {
23178
23211
  settle = resolve;
@@ -23188,8 +23221,7 @@ function untilAborted$1(work, signal) {
23188
23221
  function iso$1(ms) {
23189
23222
  return new Date(ms).toISOString();
23190
23223
  }
23191
- //#endregion
23192
- //#region ../adapters/src/spur/spur.ts
23224
+ // ../adapters/src/spur/spur.ts
23193
23225
  const REQUEST_TIMEOUT_MS = 5e3;
23194
23226
  const sessionWire = z.object({
23195
23227
  id: z.string().min(1),
@@ -23476,8 +23508,7 @@ function createSpurAdapter(options) {
23476
23508
  }
23477
23509
  };
23478
23510
  }
23479
- //#endregion
23480
- //#region ../adapters/src/github/linkSample.ts
23511
+ // ../adapters/src/github/linkSample.ts
23481
23512
  const MALFORMED = "Malformed GitHub response";
23482
23513
  /** PRs read per sample; the operator's PRs among them are matched. */
23483
23514
  const SCANNED = 50;
@@ -23520,8 +23551,7 @@ async function sampleLinkRules({ repo, login, tracker, link }, { token, now, fet
23520
23551
  }))
23521
23552
  };
23522
23553
  }
23523
- //#endregion
23524
- //#region ../adapters/src/index.ts
23554
+ // ../adapters/src/index.ts
23525
23555
  function blindSource(id, intervalMs, message) {
23526
23556
  return {
23527
23557
  id,
@@ -23607,8 +23637,7 @@ function startAdapters(config, core, options) {
23607
23637
  }
23608
23638
  };
23609
23639
  }
23610
- //#endregion
23611
- //#region ../gateway-slack/src/wire.ts
23640
+ // ../gateway-slack/src/wire.ts
23612
23641
  /**
23613
23642
  * Readers for untrusted Slack payloads. Each keeps the string semantics its callers had:
23614
23643
  * `textOf` rejects `''`, while `messageTs` accepts it, so a ref anchor of `''` still matches.
@@ -23633,8 +23662,7 @@ function fieldsOf(value) {
23633
23662
  function itemsOf(value) {
23634
23663
  return itemsWire.safeParse(value).data ?? null;
23635
23664
  }
23636
- //#endregion
23637
- //#region ../gateway-slack/src/api.ts
23665
+ // ../gateway-slack/src/api.ts
23638
23666
  var IncompleteHistoryError = class extends Error {};
23639
23667
  /**
23640
23668
  * Read every page. An incomplete response is unknown, never an empty history. Once `signal`
@@ -23759,8 +23787,7 @@ function apiFailure(error) {
23759
23787
  function isAlreadyReacted(error) {
23760
23788
  return error instanceof WebAPIPlatformError && error.data.error === "already_reacted";
23761
23789
  }
23762
- //#endregion
23763
- //#region ../gateway-slack/src/ref.ts
23790
+ // ../gateway-slack/src/ref.ts
23764
23791
  const slackRefWire = z.object({
23765
23792
  channel: z.string(),
23766
23793
  ts: z.string(),
@@ -23787,8 +23814,7 @@ function parseRef(value) {
23787
23814
  return null;
23788
23815
  }
23789
23816
  }
23790
- //#endregion
23791
- //#region ../gateway-slack/src/render.ts
23817
+ // ../gateway-slack/src/render.ts
23792
23818
  /** Slack section mrkdwn is capped at 3000 characters; leave room for formatting. */
23793
23819
  const MAX_PART_TEXT = 2900;
23794
23820
  /** Slack allows at most 10 elements in one context block. */
@@ -23925,7 +23951,7 @@ function splitContext(body) {
23925
23951
  context: []
23926
23952
  };
23927
23953
  const context = body.slice(end).map((block) => block.kind === "context" ? joined(block.children.map(inline), "") : escapeText("")).filter((text) => text.length > 0);
23928
- const bounded = [...context.slice(0, MAX_CONTEXT_ELEMENTS - 1), ...context.length >= MAX_CONTEXT_ELEMENTS ? [joined(context.slice(MAX_CONTEXT_ELEMENTS - 1), "\n")] : []];
23954
+ const bounded = [...context.slice(0, 9), ...context.length >= MAX_CONTEXT_ELEMENTS ? [joined(context.slice(9), "\n")] : []];
23929
23955
  if (bounded.some((text) => text.length > 2900)) return {
23930
23956
  body,
23931
23957
  context: []
@@ -24094,8 +24120,7 @@ function messageBlocks(text, marker, actions = [], originKey, context = []) {
24094
24120
  });
24095
24121
  return blocks;
24096
24122
  }
24097
- //#endregion
24098
- //#region ../gateway-slack/src/deliver.ts
24123
+ // ../gateway-slack/src/deliver.ts
24099
24124
  function messageMarker(message) {
24100
24125
  return markerFromBlocks(fieldsOf(message)?.blocks);
24101
24126
  }
@@ -24271,8 +24296,7 @@ function createDeliveryGateway(client, channels) {
24271
24296
  deliver
24272
24297
  };
24273
24298
  }
24274
- //#endregion
24275
- //#region ../gateway-slack/src/commands.ts
24299
+ // ../gateway-slack/src/commands.ts
24276
24300
  /** The catalog's slash bindings are the parser and help text's single source. */
24277
24301
  function descriptors(commandName) {
24278
24302
  return OPERATIONS.filter((operation) => operation.kind === "query" && operation.slack?.kind === "slash-command").map((operation) => ({
@@ -24321,8 +24345,7 @@ function parseCommand(text, commandName) {
24321
24345
  }
24322
24346
  return usage();
24323
24347
  }
24324
- //#endregion
24325
- //#region ../gateway-slack/src/normalize.ts
24348
+ // ../gateway-slack/src/normalize.ts
24326
24349
  function iso(ts) {
24327
24350
  const at = /* @__PURE__ */ new Date(Number(ts) * 1e3);
24328
24351
  return Number.isFinite(at.getTime()) ? at.toISOString() : void 0;
@@ -24500,8 +24523,7 @@ function normalizeInteraction(type, payload, channels, root, commandName = DEFAU
24500
24523
  ...originKey === void 0 ? {} : { originKey }
24501
24524
  }];
24502
24525
  }
24503
- //#endregion
24504
- //#region ../gateway-slack/src/recover.ts
24526
+ // ../gateway-slack/src/recover.ts
24505
24527
  /** Milliseconds of a Slack ts, read from its digits so float error cannot shift the millisecond. */
24506
24528
  function tsMillis(ts) {
24507
24529
  const [seconds = "", fraction = ""] = ts.split(".");
@@ -24521,18 +24543,18 @@ function inInterval(ts, from, until) {
24521
24543
  const READ_WAIT_BUDGET_MS = 1e4;
24522
24544
  /** Least budget one retry costs, so a `Retry-After: 0` cannot retry forever. */
24523
24545
  const MIN_RETRY_CHARGE_MS = 1e3;
24524
- const ABORTED = Symbol("aborted");
24546
+ const ABORTED$1 = Symbol("aborted");
24525
24547
  /**
24526
24548
  * Settles with `promise`, or with `ABORTED` once `signal` aborts. The SDK call cannot be
24527
24549
  * cancelled, so a losing read is left to its own timeout and its outcome is dropped.
24528
24550
  */
24529
- function untilAborted(promise, signal) {
24551
+ function untilAborted$1(promise, signal) {
24530
24552
  if (signal === void 0) return promise;
24531
24553
  promise.catch(() => {});
24532
- if (signal.aborted) return Promise.resolve(ABORTED);
24554
+ if (signal.aborted) return Promise.resolve(ABORTED$1);
24533
24555
  const abort = Promise.withResolvers();
24534
24556
  const onAbort = () => {
24535
- abort.resolve(ABORTED);
24557
+ abort.resolve(ABORTED$1);
24536
24558
  };
24537
24559
  signal.addEventListener("abort", onAbort, { once: true });
24538
24560
  return Promise.race([promise, abort.promise]).finally(() => {
@@ -24547,9 +24569,9 @@ function untilAborted(promise, signal) {
24547
24569
  async function readThread(client, channel, threadTs, signal) {
24548
24570
  let budget = READ_WAIT_BUDGET_MS;
24549
24571
  for (;;) {
24550
- if (signal?.aborted === true) return ABORTED;
24572
+ if (signal?.aborted === true) return ABORTED$1;
24551
24573
  try {
24552
- return await untilAborted(readMessages(client, {
24574
+ return await untilAborted$1(readMessages(client, {
24553
24575
  channel,
24554
24576
  threadTs,
24555
24577
  signal
@@ -24578,8 +24600,8 @@ async function* recoverThreads(client, request, botIdentity, now, channels) {
24578
24600
  const from = request.since.getTime();
24579
24601
  if (!Number.isFinite(from) || from > until) return;
24580
24602
  const signal = request.signal;
24581
- const bot = await untilAborted(botIdentity(), signal);
24582
- if (bot === ABORTED) return;
24603
+ const bot = await untilAborted$1(botIdentity(), signal);
24604
+ if (bot === ABORTED$1) return;
24583
24605
  for (const conversation of request.conversations) {
24584
24606
  if (signal?.aborted === true) return;
24585
24607
  const addressed = parseRef(conversation.ref);
@@ -24598,7 +24620,7 @@ async function* recoverThreads(client, request, botIdentity, now, channels) {
24598
24620
  }
24599
24621
  throw error;
24600
24622
  }
24601
- if (history === ABORTED) return;
24623
+ if (history === ABORTED$1) return;
24602
24624
  const root = history.find((message) => messageTs(message) === addressed.threadTs);
24603
24625
  if (root === void 0) {
24604
24626
  yield gap(conversation.ref);
@@ -24627,8 +24649,7 @@ async function* recoverThreads(client, request, botIdentity, now, channels) {
24627
24649
  }
24628
24650
  }
24629
24651
  }
24630
- //#endregion
24631
- //#region ../gateway-slack/src/socket.ts
24652
+ // ../gateway-slack/src/socket.ts
24632
24653
  async function rootFor(client, channel, threadTs) {
24633
24654
  const root = (await client.conversations.replies({
24634
24655
  channel,
@@ -24750,8 +24771,7 @@ function createSocket(api, config, botIdentity) {
24750
24771
  }
24751
24772
  };
24752
24773
  }
24753
- //#endregion
24754
- //#region ../gateway-slack/src/index.ts
24774
+ // ../gateway-slack/src/index.ts
24755
24775
  /** Create a Slack gateway. Socket Mode is opt-in until the daemon has a real inbound sink. */
24756
24776
  function createSlackGateway(config) {
24757
24777
  const api = createApi(config);
@@ -24800,8 +24820,7 @@ function createSlackGateway(config) {
24800
24820
  }
24801
24821
  };
24802
24822
  }
24803
- //#endregion
24804
- //#region ../daemon/src/scheduler.ts
24823
+ // ../daemon/src/scheduler.ts
24805
24824
  /**
24806
24825
  * One recurring job: a `setTimeout` chain armed `intervalMs` plus under `jitterMs` after each
24807
24826
  * timer run settles. Runs never overlap; `trigger` queues behind the active run. A failed run goes
@@ -24856,8 +24875,7 @@ function createJob(options) {
24856
24875
  settled: () => active
24857
24876
  };
24858
24877
  }
24859
- //#endregion
24860
- //#region ../daemon/src/board-modules.ts
24878
+ // ../daemon/src/board-modules.ts
24861
24879
  /**
24862
24880
  * Compose the board's timer and adapter runner without adding lifecycle state to main. `tick`
24863
24881
  * runs the board-core job once more behind its active run and resolves when that run settles.
@@ -24950,8 +24968,137 @@ function createBoardModules(ctxFor, options = {}) {
24950
24968
  pollPr
24951
24969
  };
24952
24970
  }
24953
- //#endregion
24954
- //#region ../daemon/src/spur-port.ts
24971
+ // ../daemon/src/host-metrics.ts
24972
+ /** Reads the host through `node:os` and `statfs(dataDir)`; `disk` rejects without `dataDir`. */
24973
+ function createHostProbe(dataDir) {
24974
+ return {
24975
+ cpuTimes() {
24976
+ let idle = 0;
24977
+ let total = 0;
24978
+ for (const { times } of cpus()) {
24979
+ idle += times.idle;
24980
+ total += times.user + times.nice + times.sys + times.idle + times.irq;
24981
+ }
24982
+ return {
24983
+ idle,
24984
+ total
24985
+ };
24986
+ },
24987
+ memory: () => ({
24988
+ totalBytes: totalmem(),
24989
+ availableBytes: freemem()
24990
+ }),
24991
+ async disk() {
24992
+ if (dataDir === void 0) throw new Error("No data directory to measure");
24993
+ const { blocks, bfree, bavail, bsize } = await statfs(dataDir);
24994
+ return {
24995
+ blocks,
24996
+ bfree,
24997
+ bavail,
24998
+ bsize
24999
+ };
25000
+ }
25001
+ };
25002
+ }
25003
+ const HOST_SAMPLE_MS = 3e4;
25004
+ const ABORTED = Symbol("aborted");
25005
+ /** One decimal, kept within 0..100. */
25006
+ function percent(value) {
25007
+ return Math.min(100, Math.max(0, Math.round(value * 10) / 10));
25008
+ }
25009
+ /**
25010
+ * Settles with the promise's outcome, or with `ABORTED` once `signal` aborts. It always handles
25011
+ * the promise, so an abandoned read that rejects later is no unhandled rejection.
25012
+ */
25013
+ function untilAborted(promise, signal) {
25014
+ return new Promise((resolve) => {
25015
+ const onAbort = () => {
25016
+ resolve(ABORTED);
25017
+ };
25018
+ signal.addEventListener("abort", onAbort, { once: true });
25019
+ if (signal.aborted) onAbort();
25020
+ promise.then((value) => {
25021
+ resolve({ value });
25022
+ }, (error) => {
25023
+ resolve({ error });
25024
+ }).finally(() => {
25025
+ signal.removeEventListener("abort", onAbort);
25026
+ });
25027
+ });
25028
+ }
25029
+ /**
25030
+ * Samples the host every `intervalMs` (first run in the background) and keeps the last sample;
25031
+ * `read` never samples. A metric whose read fails is null, with one warning per metric. Stop
25032
+ * aborts a pending disk read instead of waiting for it, and that run writes nothing.
25033
+ */
25034
+ function createHostSampler(options) {
25035
+ const { probe, clock, log, intervalMs = HOST_SAMPLE_MS } = options;
25036
+ let last = null;
25037
+ let previousCpu;
25038
+ const warned = /* @__PURE__ */ new Set();
25039
+ const failed = (metric, err) => {
25040
+ if (warned.has(metric)) return;
25041
+ warned.add(metric);
25042
+ log.warn({ err }, `host ${metric} unreadable`);
25043
+ };
25044
+ const attempt = (metric, read) => {
25045
+ try {
25046
+ return read();
25047
+ } catch (err) {
25048
+ failed(metric, err);
25049
+ return null;
25050
+ }
25051
+ };
25052
+ const sample = async (signal) => {
25053
+ if (signal.aborted) return;
25054
+ const sampledAt = new Date(clock.now()).toISOString();
25055
+ const cpu = attempt("cpu", () => probe.cpuTimes());
25056
+ const before = previousCpu;
25057
+ previousCpu = cpu ?? void 0;
25058
+ const cpuPercent = cpu === null || before === void 0 || cpu.total <= before.total ? null : percent(100 * (1 - (cpu.idle - before.idle) / (cpu.total - before.total)));
25059
+ const mem = attempt("memory", () => probe.memory());
25060
+ const read = await untilAborted((async () => probe.disk())(), signal);
25061
+ if (read === ABORTED) return;
25062
+ if ("error" in read) failed("disk", read.error);
25063
+ const fs = "value" in read ? read.value : null;
25064
+ const used = fs === null ? 0 : (fs.blocks - fs.bfree) * fs.bsize;
25065
+ const available = fs === null ? 0 : fs.bavail * fs.bsize;
25066
+ last = {
25067
+ sampledAt,
25068
+ cpuPercent,
25069
+ memory: mem === null ? null : {
25070
+ totalBytes: mem.totalBytes,
25071
+ availableBytes: mem.availableBytes,
25072
+ usedPercent: mem.totalBytes > 0 ? percent(100 * (mem.totalBytes - mem.availableBytes) / mem.totalBytes) : 0
25073
+ },
25074
+ disk: fs === null ? null : {
25075
+ totalBytes: fs.blocks * fs.bsize,
25076
+ availableBytes: available,
25077
+ usedPercent: used + available > 0 ? percent(100 * used / (used + available)) : 0
25078
+ }
25079
+ };
25080
+ };
25081
+ const own = new AbortController();
25082
+ const job = createJob({
25083
+ run: (signal) => sample(AbortSignal.any([signal, own.signal])),
25084
+ intervalMs,
25085
+ first: "background",
25086
+ onError: (err) => {
25087
+ log.error({ err }, "host sample failed");
25088
+ }
25089
+ });
25090
+ return {
25091
+ module: {
25092
+ start: (signal) => job.start(signal),
25093
+ async stop() {
25094
+ own.abort();
25095
+ await job.stop();
25096
+ }
25097
+ },
25098
+ read: () => last
25099
+ };
25100
+ }
25101
+ // ../daemon/src/spur-port.ts
24955
25102
  const SEND_TIMEOUT_MS = 8e3;
24956
25103
  const ERROR_TEXT_LIMIT = 200;
24957
25104
  /** 4xx statuses Spur may answer for a passing state; every other 4xx ends the ring. */
@@ -25007,8 +25154,7 @@ function createSpurPort(options) {
25007
25154
  throw new Error(message);
25008
25155
  } };
25009
25156
  }
25010
- //#endregion
25011
- //#region ../daemon/src/doctor.ts
25157
+ // ../daemon/src/doctor.ts
25012
25158
  const DEADLINE_MS = 5e3;
25013
25159
  const SPUR_PROBE_SESSION = "spur-board-doctor-probe";
25014
25160
  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.";
@@ -25393,7 +25539,8 @@ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch, { deadlineM
25393
25539
  else {
25394
25540
  const botToken = secrets["SLACK_BOT_TOKEN"];
25395
25541
  const slackHeaders = botToken ? { Authorization: `Bearer ${botToken}` } : {};
25396
- const slackBase = apiBaseUrl(secrets["SLACK_API_URL"] || "https://slack.com/api/");
25542
+ const slackApi = secrets["SLACK_API_URL"] || "https://slack.com/api/";
25543
+ const slackBase = apiBaseUrl(slackApi);
25397
25544
  const auth = botToken ? await request(ctx, fetcher, deadlineMs, "slack.auth", new URL("auth.test", slackBase), {
25398
25545
  method: "POST",
25399
25546
  headers: slackHeaders
@@ -25439,8 +25586,7 @@ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch, { deadlineM
25439
25586
  checks
25440
25587
  };
25441
25588
  }
25442
- //#endregion
25443
- //#region ../daemon/src/http-module.ts
25589
+ // ../daemon/src/http-module.ts
25444
25590
  const SESSION_TIMEOUT_MS = 5e3;
25445
25591
  const sessionDetailWire = z.object({
25446
25592
  id: z.string(),
@@ -25586,9 +25732,8 @@ function createWebModule(ctx, options) {
25586
25732
  }
25587
25733
  };
25588
25734
  }
25589
- //#endregion
25590
- //#region ../daemon/src/inbound-module.ts
25591
- const RECOVERY_MS = 5 * 6e4;
25735
+ // ../daemon/src/inbound-module.ts
25736
+ const RECOVERY_MS = 3e5;
25592
25737
  /** Owns inbound recovery scheduling and waits for every accepted event on stop. */
25593
25738
  function createInboundModule(ctx, gateway, registry = {}) {
25594
25739
  const inbound = createInbound({
@@ -25621,8 +25766,7 @@ function createInboundModule(ctx, gateway, registry = {}) {
25621
25766
  }
25622
25767
  };
25623
25768
  }
25624
- //#endregion
25625
- //#region ../daemon/src/outbox-module.ts
25769
+ // ../daemon/src/outbox-module.ts
25626
25770
  const TICK_MS = 1e3;
25627
25771
  const TICK_JITTER_MS = 100;
25628
25772
  const DELIVERY_REQUEST_TIMEOUT_MS = 8e3;
@@ -25729,8 +25873,7 @@ function createOutboxModule(ctx, gateway, options = {}) {
25729
25873
  }
25730
25874
  };
25731
25875
  }
25732
- //#endregion
25733
- //#region ../daemon/src/systemd.ts
25876
+ // ../daemon/src/systemd.ts
25734
25877
  /**
25735
25878
  * systemd readiness and watchdog notifications for `Type=notify` units.
25736
25879
  *
@@ -25833,8 +25976,7 @@ function createSystemdModule(notifier) {
25833
25976
  }
25834
25977
  };
25835
25978
  }
25836
- //#endregion
25837
- //#region ../daemon/src/composition.ts
25979
+ // ../daemon/src/composition.ts
25838
25980
  const DAY_MS = 864e5;
25839
25981
  /** The production module graph, with replaceable external ports for in-process tests. */
25840
25982
  function createDaemonModules(ctxFor, ports = {}) {
@@ -25857,12 +25999,20 @@ function createDaemonModules(ctxFor, ports = {}) {
25857
25999
  ctx.log.error({ err }, work === "connection" ? "slack connection event failed" : "slack envelope failed");
25858
26000
  }
25859
26001
  }));
26002
+ const hostCtx = ctxFor("host-metrics");
26003
+ const host = createHostSampler({
26004
+ probe: ports.hostProbe ?? createHostProbe(ports.dataDir),
26005
+ clock: hostCtx.clock,
26006
+ log: hostCtx.log
26007
+ });
25860
26008
  let webPort;
25861
26009
  let lastDispatchAt = null;
25862
26010
  const registry = createOperationRegistry({
25863
26011
  config: board.config,
25864
26012
  clock: board.clock,
25865
26013
  completeSince: core.completeSince,
26014
+ healthySince: core.healthySince,
26015
+ hostMetrics: () => host.read(),
25866
26016
  gateways: gateway === void 0 ? [] : [gateway.kind],
25867
26017
  reapplyInbound: () => inbound?.reapply,
25868
26018
  prPoller: () => boardModules.pollPr,
@@ -25879,29 +26029,37 @@ function createDaemonModules(ctxFor, ports = {}) {
25879
26029
  });
25880
26030
  const commands = ctxFor("commands");
25881
26031
  const tokenRequests = ctxFor("token-requests");
25882
- const entries = [{
25883
- name: "commands",
25884
- stopStage: "final",
25885
- module: createJob({
25886
- run: () => purgeExpiredCommands(commands.store, commands.clock, commands.config.commands.retentionDays),
25887
- intervalMs: DAY_MS,
25888
- first: "await",
25889
- onError: (err) => {
25890
- commands.log.error({ err }, "command purge failed");
25891
- }
25892
- })
25893
- }, {
25894
- name: "token-requests",
25895
- stopStage: "final",
25896
- module: createJob({
25897
- run: () => purgeEndedTokenRequests(tokenRequests.store, new Date(tokenRequests.clock.now())),
25898
- intervalMs: DAY_MS,
25899
- first: "background",
25900
- onError: (err) => {
25901
- tokenRequests.log.error({ err }, "token request purge failed");
25902
- }
25903
- })
25904
- }];
26032
+ const entries = [
26033
+ {
26034
+ name: "commands",
26035
+ stopStage: "final",
26036
+ module: createJob({
26037
+ run: () => purgeExpiredCommands(commands.store, commands.clock, commands.config.commands.retentionDays),
26038
+ intervalMs: DAY_MS,
26039
+ first: "await",
26040
+ onError: (err) => {
26041
+ commands.log.error({ err }, "command purge failed");
26042
+ }
26043
+ })
26044
+ },
26045
+ {
26046
+ name: "token-requests",
26047
+ stopStage: "final",
26048
+ module: createJob({
26049
+ run: () => purgeEndedTokenRequests(tokenRequests.store, new Date(tokenRequests.clock.now())),
26050
+ intervalMs: DAY_MS,
26051
+ first: "background",
26052
+ onError: (err) => {
26053
+ tokenRequests.log.error({ err }, "token request purge failed");
26054
+ }
26055
+ })
26056
+ },
26057
+ {
26058
+ name: "host-metrics",
26059
+ stopStage: "pollers",
26060
+ module: host.module
26061
+ }
26062
+ ];
25905
26063
  const boardModules = createBoardModules(ctxFor, {
25906
26064
  core,
25907
26065
  ...ports.startAdapters === void 0 ? {} : { startAdapters: ports.startAdapters },
@@ -25991,8 +26149,7 @@ const itemInput = z.object({ item: z.string() });
25991
26149
  function isItemInput(input) {
25992
26150
  return itemInput.safeParse(input).success;
25993
26151
  }
25994
- //#endregion
25995
- //#region ../daemon/src/main.ts
26152
+ // ../daemon/src/main.ts
25996
26153
  const KEEPALIVE_MS = 36e5;
25997
26154
  const packedManifestWire = z.object({ name: z.literal("spur-board") });
25998
26155
  const versionWire = z.object({ version: z.string() });
@@ -26030,8 +26187,9 @@ function processPort() {
26030
26187
  async function main() {
26031
26188
  setInterval(() => void 0, KEEPALIVE_MS);
26032
26189
  const productVersion = publishedVersion();
26190
+ const paths = resolvePaths(process.env, homedir());
26033
26191
  await runDaemon({
26034
- paths: resolvePaths(process.env, homedir()),
26192
+ paths,
26035
26193
  acquireLock,
26036
26194
  loadConfig: (paths) => {
26037
26195
  const loaded = loadConfig(paths);
@@ -26041,6 +26199,7 @@ async function main() {
26041
26199
  openStore,
26042
26200
  modules: (ctxFor) => createDaemonModules(ctxFor, {
26043
26201
  productVersion,
26202
+ dataDir: dirname(paths.dbFile),
26044
26203
  systemd: {
26045
26204
  env: process.env,
26046
26205
  pid: process.pid
@@ -26090,5 +26249,4 @@ function copyDatabaseMain(args, env = process.env, home = homedir(), writeErr =
26090
26249
  }
26091
26250
  }
26092
26251
  if (import.meta.main) main();
26093
- //#endregion
26094
26252
  export { copyDatabaseMain, main, publishedVersion };