spur-board 0.52.1 → 0.53.1

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,4 +1,5 @@
1
- import { $ as configSchema, A as parseRingMarker, B as parseRef$1, C as userIdSchema, D as SESSION_HEALTH_STATES, E as REVIEW_STATES, F as ticketFactsSchema, H as ERRORS, I as actorIdSchema, K as ok, L as encodeActorId, M as prRefSchema, N as ringMarker, O as SESSION_STATUSES, P as sessionFactsSchema, Q as RESERVED_PROJECT, R as errorCodeOf, S as messageRefSchema, T as eventPayloadSchemas, U as err, V as taskKeySchema, Y as DEFAULT_LINK, Z as DEFAULT_SLACK_COMMAND, a as BOARD_TICK_MS, b as inboundEventSchema, c as batchSchema, d as buildCatalogSnapshot, et as plainHttpAllowed, f as roleCanUseOperation, h as renderHttpProblem, i as tokenRequestSchema, it as SLACK_BOT_SCOPES, j as prFactsSchema, k as isExternalAuthor, l as entityRefSchema, m as turnHandedSchema, n as TOKEN_REQUEST_LIMITS, nt as COLUMN_IDS, p as OPERATIONS, q as successEnvelopeSchema, r as requestHashOf, rt as DISPATCHER_MODES, s as AdapterError, t as assertNever, tt as requiredSecretKeys, u as sourceCursorSchema, v as SPACE_IDS, w as EVENT_KINDS, x as interactionRefSchema, y as conversationRefSchema, z as parseActorId } from "./src-Dy1XbpPP.mjs";
1
+ import { A as EVENT_KINDS, B as sessionFactsSchema, D as interactionRefSchema, E as inboundEventSchema, F as isExternalAuthor, G as encodeActorId, H as JIRA_PROJECT_KEY, I as parseRingMarker, J as parseRef$1, K as errorCodeOf, L as prFactsSchema, M as REVIEW_STATES, N as SESSION_HEALTH_STATES, O as messageRefSchema, P as SESSION_STATUSES, R as prRefSchema, T as conversationRefSchema, U as REF_NUMBER, V as ticketFactsSchema, W as actorIdSchema, X as ERRORS, Y as taskKeySchema, Z as err, _ as buildCatalogSnapshot, a as requestHashOf, at as DEFAULT_SLACK_COMMAND, b as turnHandedSchema, c as tokenRequestStatusSchema, ct as plainHttpAllowed, d as AdapterError, dt as DISPATCHER_MODES, et as ok, f as batchSchema, ft as SLACK_BOT_SCOPES, g as trackerSourceId, h as sourceCursorSchema, i as TOKEN_REQUEST_LIMITS, j as eventPayloadSchemas, k as userIdSchema, l as BOARD_TICK_MS, lt as requiredSecretKeys, m as prSourceId, n as doctorReportSchema, o as tokenRequestResultSchema, ot as RESERVED_PROJECT, p as entityRefSchema, q as parseActorId, rt as DEFAULT_LINK, s as tokenRequestSchema, st as configSchema, t as assertNever, tt as successEnvelopeSchema, ut as COLUMN_IDS, v as roleCanUseOperation, w as SPACE_IDS, x as renderHttpProblem, y as OPERATIONS, z as ringMarker } from "./chunk-DyHtyPom.mjs";
2
+ import { t as apiBaseUrl } from "./chunk-DAMwWWmT.mjs";
2
3
  import { createRequire } from "node:module";
3
4
  import { createHash, randomUUID } from "node:crypto";
4
5
  import { chmodSync, closeSync, existsSync, fchmodSync, fstatSync, fsyncSync, ftruncateSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeSync } from "node:fs";
@@ -336,6 +337,38 @@ function parseJson(schema, text) {
336
337
  function toJson(schema, value) {
337
338
  return JSON.stringify(schema.parse(value));
338
339
  }
340
+ /**
341
+ * Builds a reporter that calls `warn` once per table, column and row for its own lifetime, so
342
+ * repeated ticks and transaction replays log one line. Without `warn` it reports nothing. A `warn`
343
+ * that throws is swallowed, so reporting never fails the caller's transaction.
344
+ */
345
+ function warnSkippedOnce(warn) {
346
+ const seen = /* @__PURE__ */ new Set();
347
+ return (table, column, row, error) => {
348
+ if (warn === void 0) return;
349
+ const key = JSON.stringify([
350
+ table,
351
+ column,
352
+ String(row)
353
+ ]);
354
+ if (seen.has(key)) return;
355
+ const fields = {
356
+ table,
357
+ column,
358
+ row: String(row),
359
+ issues: error.issues.map((issue) => ({
360
+ path: issue.path.map(String).join("."),
361
+ code: issue.code
362
+ }))
363
+ };
364
+ try {
365
+ warn(fields, "stored JSON does not match its schema");
366
+ } catch {
367
+ return;
368
+ }
369
+ seen.add(key);
370
+ };
371
+ }
339
372
  //#endregion
340
373
  //#region ../core/src/domain/blocks/blocks.ts
341
374
  var BlockRuleError = class extends Error {
@@ -7956,9 +7989,6 @@ async function scanTransaction(store, config, fn) {
7956
7989
  }
7957
7990
  //#endregion
7958
7991
  //#region ../core/src/app/board-utils.ts
7959
- function trackerSource(project) {
7960
- return project.tracker.type === "jira" ? `jira:${project.id}` : `github-issues:${project.id}:${project.tracker.repo.toLowerCase()}`;
7961
- }
7962
7992
  /** Whether a ticket status is done: a Jira done status, or a closed GitHub Issue. */
7963
7993
  function ticketDone(project, status) {
7964
7994
  return project.tracker.type === "jira" ? project.tracker.doneStatuses.includes(status) : status === "closed";
@@ -7997,7 +8027,7 @@ function parsePr(detail) {
7997
8027
  }
7998
8028
  /** The project whose tracker or repo source wrote an observation. */
7999
8029
  function projectForSource(config, source) {
8000
- return config.projects.find((project) => source === trackerSource(project) || project.repos.some((repo) => source === `github:${project.id}:${repo.toLowerCase()}`));
8030
+ return config.projects.find((project) => source === trackerSourceId(project) || project.repos.some((repo) => source === prSourceId(project.id, repo)));
8001
8031
  }
8002
8032
  /** The one project whose tracker takes `key` by its form: Jira for `ABC-1`, GitHub for `#`. */
8003
8033
  function projectForKey(config, key) {
@@ -10652,19 +10682,6 @@ async function identifyCaller(ports, headers) {
10652
10682
  }
10653
10683
  //#endregion
10654
10684
  //#region ../core/src/api/server.ts
10655
- const doctorReportSchema = z.strictObject({
10656
- version: z.string().min(1).max(50),
10657
- checks: z.array(z.strictObject({
10658
- id: z.string().regex(/^[a-z][a-z._]+$/).max(60),
10659
- status: z.enum([
10660
- "pass",
10661
- "fail",
10662
- "warning"
10663
- ]),
10664
- blocking: z.boolean(),
10665
- fix: z.string().max(300).nullable()
10666
- })).max(30)
10667
- });
10668
10685
  const tokenStatusSchema = z.strictObject({ hash: tokenRequestSchema.shape.hash });
10669
10686
  const skillReloadSchema = z.strictObject({ version: SKILL_VERSION });
10670
10687
  const skillReloadsSchema = z.strictObject({
@@ -10778,7 +10795,7 @@ async function createApiServer(options) {
10778
10795
  return reply.send(successEnvelopeSchema.parse({
10779
10796
  ok: true,
10780
10797
  requestId: request.id,
10781
- value: result
10798
+ value: tokenRequestResultSchema.parse(result)
10782
10799
  }));
10783
10800
  });
10784
10801
  /** The hash travels in the body because request logs record the URL. */
@@ -10790,7 +10807,7 @@ async function createApiServer(options) {
10790
10807
  return reply.send(successEnvelopeSchema.parse({
10791
10808
  ok: true,
10792
10809
  requestId: request.id,
10793
- value: { status }
10810
+ value: tokenRequestStatusSchema.parse({ status })
10794
10811
  }));
10795
10812
  });
10796
10813
  /** Anonymous: the message is fixed and goes at most once per session for the running version. */
@@ -11961,13 +11978,18 @@ async function resolveBlockConversation(trx, input) {
11961
11978
  registered: false
11962
11979
  };
11963
11980
  if (input.originKey === void 0) return void 0;
11964
- const opened = await trx.selectFrom("outbox").select(["payload"]).where("kind", "=", "conversation.open").where("dedupe_key", "=", input.originKey).executeTakeFirst();
11981
+ const opened = await trx.selectFrom("outbox").select(["id", "payload"]).where("kind", "=", "conversation.open").where("dedupe_key", "=", input.originKey).executeTakeFirst();
11965
11982
  if (opened === void 0) return void 0;
11983
+ const payload = JSON.parse(opened.payload);
11966
11984
  const parsed = outboxBodySchema.safeParse({
11967
11985
  kind: "conversation.open",
11968
- payload: JSON.parse(opened.payload)
11986
+ payload
11969
11987
  });
11970
- if (!parsed.success || parsed.data.kind !== "conversation.open") return void 0;
11988
+ if (!parsed.success) {
11989
+ input.warnSkipped?.("outbox", "payload", opened.id, parsed.error);
11990
+ return;
11991
+ }
11992
+ if (parsed.data.kind !== "conversation.open") return void 0;
11971
11993
  const row = await insertConversation(trx, {
11972
11994
  gateway: input.gateway,
11973
11995
  ref: input.ref,
@@ -12021,9 +12043,10 @@ const MAX_BACKOFF_MS$1 = 6e4;
12021
12043
  const RECOVER_BATCH = 100;
12022
12044
  function parseBody(row) {
12023
12045
  try {
12046
+ const payload = JSON.parse(row.payload);
12024
12047
  const parsed = outboxBodySchema.safeParse({
12025
12048
  kind: row.kind,
12026
- payload: JSON.parse(row.payload)
12049
+ payload
12027
12050
  });
12028
12051
  return parsed.success ? parsed.data : `invalid payload: ${parsed.error.message}`;
12029
12052
  } catch (error) {
@@ -12653,6 +12676,11 @@ async function loadItem(trx, id) {
12653
12676
  task: item.task_id === null ? void 0 : await trx.selectFrom("task").selectAll().where("id", "=", item.task_id).executeTakeFirstOrThrow()
12654
12677
  };
12655
12678
  }
12679
+ /** The ids a delivery payload may carry; each payload kind has its own full schema. */
12680
+ const deliveryPayloadSchema = z.object({
12681
+ taskId: z.unknown().optional(),
12682
+ notificationId: z.unknown().optional()
12683
+ });
12656
12684
  /** The task a `delivery:<outbox id>` item's row belongs to; the item itself has no task. */
12657
12685
  async function deliveryTask(trx, item) {
12658
12686
  if (item.kind !== "post_failed") return void 0;
@@ -12662,7 +12690,7 @@ async function deliveryTask(trx, item) {
12662
12690
  "payload"
12663
12691
  ]).where("id", "=", Number(item.item_key.slice(9))).executeTakeFirst();
12664
12692
  if (row === void 0) return void 0;
12665
- const payload = JSON.parse(row.payload);
12693
+ const payload = parseJson(deliveryPayloadSchema, row.payload);
12666
12694
  if (typeof payload.taskId === "number") return trx.selectFrom("task").selectAll().where("id", "=", payload.taskId).executeTakeFirst();
12667
12695
  if (row.kind !== "doorbell") return void 0;
12668
12696
  return ringTask(trx, typeof payload.notificationId === "number" ? payload.notificationId : void 0, row.dedupe_key);
@@ -13112,7 +13140,7 @@ async function getStatus(deps, options = {}) {
13112
13140
  };
13113
13141
  });
13114
13142
  const sourceRows = await store.db.selectFrom("source_state").selectAll().execute();
13115
- const required = /* @__PURE__ */ new Set(["spur", ...projects.flatMap((project) => [trackerSource(project), ...project.repos.map((repo) => `github:${project.id}:${repo.toLowerCase()}`)])]);
13143
+ const required = /* @__PURE__ */ new Set(["spur", ...projects.flatMap((project) => [trackerSourceId(project), ...project.repos.map((repo) => prSourceId(project.id, repo))])]);
13116
13144
  const sourceById = new Map(sourceRows.map((row) => [row.source, row]));
13117
13145
  const sources = [...required].map((source) => {
13118
13146
  const row = sourceById.get(source);
@@ -13862,7 +13890,7 @@ const ANOMALY_FLAGS = /* @__PURE__ */ new Set([
13862
13890
  "worker_lost"
13863
13891
  ]);
13864
13892
  /** Reconciles every item in the caller's observation or tick transaction. */
13865
- async function reconcileItems(trx, config, now, spurComplete) {
13893
+ async function reconcileItems(trx, config, now, spurComplete, warnSkipped) {
13866
13894
  const candidates = [];
13867
13895
  const sources = await trx.selectFrom("source_state").selectAll().execute();
13868
13896
  const sourceById = new Map(sources.map((state) => [state.source, state]));
@@ -13884,8 +13912,13 @@ async function reconcileItems(trx, config, now, spurComplete) {
13884
13912
  const misses = await trx.selectFrom("source_miss").selectAll().execute();
13885
13913
  for (const miss of misses) {
13886
13914
  if (miss.gone !== 1) continue;
13887
- const ref = JSON.parse(miss.ref);
13888
- if (ref.kind === "pr" && ref.repo !== void 0 && ref.number !== void 0) {
13915
+ const parsed = entityRefSchema.safeParse(JSON.parse(miss.ref));
13916
+ if (!parsed.success) {
13917
+ warnSkipped?.("source_miss", "ref", `${miss.source} ${miss.ref_key}`, parsed.error);
13918
+ continue;
13919
+ }
13920
+ const ref = parsed.data;
13921
+ if (ref.kind === "pr") {
13889
13922
  const links = await trx.selectFrom("link").select("task_id").where("entity", "=", "pr").where(sql`lower(repo) = ${ref.repo.toLowerCase()}`).where("number", "=", ref.number).execute();
13890
13923
  for (const link of links) {
13891
13924
  const task = taskById.get(link.task_id);
@@ -14017,7 +14050,7 @@ async function reconcileItems(trx, config, now, spurComplete) {
14017
14050
  taskId: task.id,
14018
14051
  summary: `${task.key}: linked pull request ${refs.join(", ")} closed without merge, no open PR`,
14019
14052
  factAt: first.observed_at,
14020
- source: `github:${task.project}:${(first.repo ?? "").toLowerCase()}`,
14053
+ source: prSourceId(task.project, first.repo ?? ""),
14021
14054
  priority: 4,
14022
14055
  revision: refs.join(",")
14023
14056
  });
@@ -14182,7 +14215,7 @@ function prCompleteAt(project, sourceById) {
14182
14215
  if (project === void 0) return null;
14183
14216
  let oldest = Infinity;
14184
14217
  for (const repo of project.repos) {
14185
- const source = sourceById.get(`github:${project.id}:${repo.toLowerCase()}`);
14218
+ const source = sourceById.get(prSourceId(project.id, repo));
14186
14219
  if (source === void 0 || source.blind_reason !== null || source.last_complete_at === null) return null;
14187
14220
  oldest = Math.min(oldest, Date.parse(source.last_complete_at));
14188
14221
  }
@@ -14555,7 +14588,7 @@ async function readInput(trx, task, project, mode, blind) {
14555
14588
  pr = parsePr((await trx.selectFrom("pr_snapshot").select("detail").where(sql`lower(repo) = ${link.repo.toLowerCase()}`).where("number", "=", link.number).executeTakeFirst())?.detail);
14556
14589
  if (pr === null) return null;
14557
14590
  }
14558
- const githubBlind = (pr === null ? project.repos : [pr.repo]).some((repo) => blind(`github:${project.id}:${repo.toLowerCase()}`));
14591
+ const githubBlind = (pr === null ? project.repos : [pr.repo]).some((repo) => blind(prSourceId(project.id, repo)));
14559
14592
  const marks = (await trx.selectFrom("submission").select(["column", "commit_sha"]).where("task_id", "=", task.id).where("voided_at", "is", null).orderBy("id").execute()).map((row) => {
14560
14593
  const headSha = row.commit_sha.toLowerCase();
14561
14594
  return row.column === "review" || row.column === "product-review" ? {
@@ -15123,7 +15156,7 @@ async function pollTaskPr(db, task, poll) {
15123
15156
  const pr = await taskPr(db, task.id);
15124
15157
  if (pr === null) return { kind: "skipped" };
15125
15158
  const repo = pr.repo.toLowerCase();
15126
- const result = poll === void 0 ? null : await poll(`github:${task.project}:${repo}`, {
15159
+ const result = poll === void 0 ? null : await poll(prSourceId(task.project, repo), {
15127
15160
  kind: "pr",
15128
15161
  repo: pr.repo,
15129
15162
  number: pr.number
@@ -15399,7 +15432,7 @@ function createOperationRegistry(deps) {
15399
15432
  const LIVE_VERSION_KEY = "doctor_live_version";
15400
15433
  /** Configured adapter IDs, including repos used by more than one project. */
15401
15434
  function doctorSources(config) {
15402
- return /* @__PURE__ */ new Set(["spur", ...config.projects.flatMap((project) => [trackerSource(project), ...project.repos.map((repo) => `github:${project.id}:${repo.toLowerCase()}`)])]);
15435
+ return /* @__PURE__ */ new Set(["spur", ...config.projects.flatMap((project) => [trackerSourceId(project), ...project.repos.map((repo) => prSourceId(project.id, repo))])]);
15403
15436
  }
15404
15437
  /**
15405
15438
  * True once every configured source that is not blind has had a complete poll in this process.
@@ -15448,7 +15481,7 @@ async function enqueueLiveAfterFirstPoll(trx, input) {
15448
15481
  //#endregion
15449
15482
  //#region ../core/src/app/membership-rules.ts
15450
15483
  /** Run-local completeness is the only evidence allowed to authorize filter absence. */
15451
- async function reconcileMembership(trx, config, completeSince, at) {
15484
+ async function reconcileMembership(trx, config, completeSince, at, warnSkipped) {
15452
15485
  const states = await trx.selectFrom("source_state").select(["source", "blind_reason"]).execute();
15453
15486
  const blind = new Set(states.filter((state) => state.blind_reason !== null).map((state) => state.source));
15454
15487
  const tasks = await trx.selectFrom("task").selectAll().where("membership", "!=", "archived").execute();
@@ -15458,7 +15491,10 @@ async function reconcileMembership(trx, config, completeSince, at) {
15458
15491
  if (project === void 0) continue;
15459
15492
  const ticket = await trx.selectFrom("ticket_snapshot").selectAll().where("task_id", "=", task.id).executeTakeFirst();
15460
15493
  if (ticket === void 0) continue;
15461
- if (JSON.parse(ticket.detail).inFilter === true) continue;
15494
+ const detail = JSON.parse(ticket.detail);
15495
+ const facts = ticketFactsSchema.safeParse(detail);
15496
+ if (!facts.success) warnSkipped?.("ticket_snapshot", "detail", ticket.task_id, facts.error);
15497
+ if (facts.success ? facts.data.inFilter : typeof detail === "object" && detail !== null && "inFilter" in detail && detail.inFilter === true) continue;
15462
15498
  const links = await trx.selectFrom("link").selectAll().where("task_id", "=", task.id).where("banned", "=", 0).execute();
15463
15499
  let retained = false;
15464
15500
  for (const link of links) if (link.entity === "pr" && link.repo !== null && link.number !== null) {
@@ -15474,8 +15510,8 @@ async function reconcileMembership(trx, config, completeSince, at) {
15474
15510
  } else {
15475
15511
  if ([
15476
15512
  "spur",
15477
- trackerSource(project),
15478
- ...project.repos.map((repo) => `github:${project.id}:${repo.toLowerCase()}`)
15513
+ trackerSourceId(project),
15514
+ ...project.repos.map((repo) => prSourceId(project.id, repo))
15479
15515
  ].some((source) => {
15480
15516
  const complete = completeSince.get(source);
15481
15517
  return blind.has(source) || complete === void 0 || complete <= (task.last_change_at ?? task.created_at);
@@ -15513,7 +15549,7 @@ async function updateTerminal(trx, config, taskId, at, completeSince, blind) {
15513
15549
  const merged = linked.some((pr) => pr.state === "merged");
15514
15550
  const doneTicket = ticket !== void 0 && ticketDone(project, ticket.status);
15515
15551
  const githubComplete = project.repos.every((repo) => {
15516
- const source = `github:${project.id}:${repo.toLowerCase()}`;
15552
+ const source = prSourceId(project.id, repo);
15517
15553
  const complete = completeSince.get(source);
15518
15554
  return !blind.has(source) && complete !== void 0 && complete > (task.last_change_at ?? task.created_at);
15519
15555
  });
@@ -15617,7 +15653,7 @@ async function hideMergedLinks(trx, taskId, at) {
15617
15653
  async function ticket(trx, config, fact, at, source) {
15618
15654
  if (fact.trackerId !== source) throw new Error("Ticket from an unconfigured tracker");
15619
15655
  await trx.deleteFrom("source_miss").where("source", "=", source).where("ref_key", "=", `ticket:${source}:${fact.key}`).execute();
15620
- const project = config.projects.find((entry) => trackerSource(entry) === source);
15656
+ const project = config.projects.find((entry) => trackerSourceId(entry) === source);
15621
15657
  if (project === void 0) throw new Error("Ticket from an unconfigured tracker");
15622
15658
  let task = await trx.selectFrom("task").selectAll().where("project", "=", project.id).where("tracker_kind", "=", project.tracker.type).where("tracker_id", "=", fact.id).executeTakeFirst();
15623
15659
  const pending = await trx.selectFrom("task").selectAll().where("project", "=", project.id).where("key", "=", fact.key).executeTakeFirst();
@@ -15844,6 +15880,8 @@ function branchHasKey(branch, key) {
15844
15880
  for (let index = text.indexOf(needle); index !== -1; index = text.indexOf(needle, index + 1)) if (!/[a-z0-9]/.test(text[index - 1] ?? "") && !/[0-9]/.test(text[index + needle.length] ?? "")) return true;
15845
15881
  return false;
15846
15882
  }
15883
+ /** The Jira task key at the end of a session's `/browse/` link. */
15884
+ const BROWSE_KEY = new RegExp(`/browse/(${JIRA_PROJECT_KEY}-${REF_NUMBER})$`);
15847
15885
  async function session(trx, config, fact, at, source, ambiguousBranches) {
15848
15886
  const old = await trx.selectFrom("session_snapshot").selectAll().where("id", "=", fact.id).executeTakeFirst();
15849
15887
  const previous = old === void 0 ? null : parseJson(sessionFactsSchema, old.detail);
@@ -15881,7 +15919,7 @@ async function session(trx, config, fact, at, source, ambiguousBranches) {
15881
15919
  for (const label of ["board-worker", "board-other"]) {
15882
15920
  const url = fact.links[label];
15883
15921
  if (url === void 0) continue;
15884
- const candidate = /\/browse\/([A-Za-z][A-Za-z0-9_]*-[1-9]\d*)$/.exec(url)?.[1] ?? /\/issues\/([1-9]\d*)$/.exec(url)?.[1];
15922
+ const candidate = BROWSE_KEY.exec(url)?.[1] ?? /\/issues\/([1-9]\d*)$/.exec(url)?.[1];
15885
15923
  key = candidate === void 0 ? void 0 : url.includes("/issues/") ? `${new URL(url).pathname.split("/").slice(1, 3).join("/")}#${candidate}` : candidate;
15886
15924
  role = label === "board-worker" ? "worker" : "other";
15887
15925
  if (key !== void 0) break;
@@ -15957,11 +15995,15 @@ async function session(trx, config, fact, at, source, ambiguousBranches) {
15957
15995
  await trx.updateTable("task").set({ last_change_at: at }).where("id", "=", task.id).execute();
15958
15996
  }
15959
15997
  }
15960
- /** The PRs of a GitHub source's repo that still have an unbanned link, one per ref key. */
15998
+ /**
15999
+ * The PRs of a GitHub source's repo that still have an unbanned link to a task that is not
16000
+ * archived, one per ref key. A PR linked only to archived tasks is not polled; restoring the
16001
+ * task brings it back on the next poll. `out_of_filter` tasks keep their PRs.
16002
+ */
15961
16003
  async function linkedPrs(db, source) {
15962
16004
  if (!source.startsWith("github:")) return [];
15963
16005
  const repo = source.slice(source.lastIndexOf(":") + 1);
15964
- const prs = (await db.selectFrom("link").select(["repo", "number"]).where("entity", "=", "pr").where(sql`lower(repo) = ${repo.toLowerCase()}`).where("banned", "=", 0).execute()).flatMap((link) => link.repo === null || link.number === null ? [] : [{
16006
+ const prs = (await db.selectFrom("link").innerJoin("task", "task.id", "link.task_id").select(["link.repo", "link.number"]).where("link.entity", "=", "pr").where(sql`lower(link.repo) = ${repo.toLowerCase()}`).where("link.banned", "=", 0).where("task.membership", "!=", "archived").execute()).flatMap((link) => link.repo === null || link.number === null ? [] : [{
15965
16007
  kind: "pr",
15966
16008
  repo: link.repo,
15967
16009
  number: link.number
@@ -16015,12 +16057,14 @@ async function holdContinuation(trx, source, item) {
16015
16057
  function createObservationCore(deps) {
16016
16058
  const { store, config, clock } = deps;
16017
16059
  const completeSince = /* @__PURE__ */ new Map();
16060
+ const warnSkipped = warnSkippedOnce(deps.warn);
16018
16061
  return {
16019
16062
  completeSince,
16063
+ warnSkipped,
16020
16064
  async context(source) {
16021
16065
  const state = await store.db.selectFrom("source_state").selectAll().where("source", "=", source).executeTakeFirst();
16022
16066
  const project = projectForSource(config, source);
16023
- const tickets = project !== void 0 && source === trackerSource(project) ? (await store.db.selectFrom("task").leftJoin("ticket_snapshot", "ticket_snapshot.task_id", "task.id").select([
16067
+ const tickets = project !== void 0 && source === trackerSourceId(project) ? (await store.db.selectFrom("task").leftJoin("ticket_snapshot", "ticket_snapshot.task_id", "task.id").select([
16024
16068
  "task.key",
16025
16069
  "task.tracker_id",
16026
16070
  "task.manual_include",
@@ -16135,7 +16179,7 @@ function createObservationCore(deps) {
16135
16179
  }
16136
16180
  if (observation.effectiveComplete) await trx.updateTable("session_snapshot").set({ absent_since: batch.observedAt }).where("source", "=", source).where("absent_since", "is", null).where("last_seen", "<", batch.observedAt).execute();
16137
16181
  if (observation.effectiveComplete) {
16138
- const project = config.projects.find((entry) => trackerSource(entry) === source);
16182
+ const project = config.projects.find((entry) => trackerSourceId(entry) === source);
16139
16183
  if (project !== void 0) {
16140
16184
  const seen = new Set(batch.items.flatMap((item) => item.kind === "ticket" && item.facts.inFilter ? [item.facts.id] : []));
16141
16185
  const unresolved = new Set(batch.entities.flatMap((entity) => entity.ref.kind === "ticket" && entity.status !== "ok" && !observation.outcomes.some((outcome) => refKey(outcome.ref) === refKey(entity.ref) && outcome.gone) ? [entity.ref.id ?? entity.ref.key] : []));
@@ -16170,7 +16214,7 @@ function createObservationCore(deps) {
16170
16214
  const blind = new Set(states.filter((state) => state.blind_reason !== null).map((state) => state.source));
16171
16215
  const activeTasks = await trx.selectFrom("task").select("id").where("membership", "!=", "archived").execute();
16172
16216
  for (const task of activeTasks) await updateTerminal(trx, config, task.id, batch.observedAt, currentComplete, blind);
16173
- await reconcileMembership(trx, config, currentComplete, batch.observedAt);
16217
+ await reconcileMembership(trx, config, currentComplete, batch.observedAt, warnSkipped);
16174
16218
  const dispatchContext = {
16175
16219
  config,
16176
16220
  at: new Date(batch.observedAt),
@@ -16179,7 +16223,7 @@ function createObservationCore(deps) {
16179
16223
  const recovered = wasBlind !== null && observation.state.blind === void 0;
16180
16224
  if (observation.effectiveComplete && !completeSince.has(source) || recovered) await dispatchSource(trx, source, dispatchContext);
16181
16225
  await dispatchJournaled(trx, dispatchContext);
16182
- await reconcileItems(trx, config, now, currentComplete.has("spur"));
16226
+ await reconcileItems(trx, config, now, currentComplete.has("spur"), warnSkipped);
16183
16227
  if (deps.productVersion !== void 0) await enqueueLiveAfterFirstPoll(trx, {
16184
16228
  config,
16185
16229
  productVersion: deps.productVersion,
@@ -16200,7 +16244,7 @@ function createObservationCore(deps) {
16200
16244
  at: new Date(now),
16201
16245
  complete: completeSince
16202
16246
  });
16203
- await reconcileItems(trx, config, now, completeSince.has("spur"));
16247
+ await reconcileItems(trx, config, now, completeSince.has("spur"), warnSkipped);
16204
16248
  });
16205
16249
  },
16206
16250
  notice(kind, value) {
@@ -16279,7 +16323,7 @@ async function tickBoard(deps) {
16279
16323
  if (task.terminal_at === null || task.terminal_at > slot || task.archive_slot_at === slot) continue;
16280
16324
  const project = config.projects.find((entry) => entry.id === task.project);
16281
16325
  if (project === void 0 || project.repos.some((repo) => {
16282
- const source = `github:${project.id}:${repo.toLowerCase()}`;
16326
+ const source = prSourceId(project.id, repo);
16283
16327
  const complete = completeSince.get(source);
16284
16328
  return blind.has(source) || complete === void 0 || complete <= (task.last_change_at ?? task.created_at);
16285
16329
  })) continue;
@@ -16297,7 +16341,7 @@ async function tickBoard(deps) {
16297
16341
  complete: completeSince
16298
16342
  });
16299
16343
  await remindStuckTurns(trx, config, new Date(now));
16300
- await reconcileItems(trx, config, now, completeSince.has("spur"));
16344
+ await reconcileItems(trx, config, now, completeSince.has("spur"), deps.warnSkipped);
16301
16345
  });
16302
16346
  }
16303
16347
  //#endregion
@@ -16549,6 +16593,7 @@ function first(set) {
16549
16593
  }
16550
16594
  function createInbound(input) {
16551
16595
  const { store, gateway, config } = input;
16596
+ const warnSkipped = warnSkippedOnce(input.warn);
16552
16597
  const clock = input.clock ?? { now: () => Date.now() };
16553
16598
  const registry = input.registry ?? {};
16554
16599
  let running = Promise.resolve();
@@ -16565,7 +16610,8 @@ function createInbound(input) {
16565
16610
  ref: event.conversation,
16566
16611
  ...event.originKey === void 0 ? {} : { originKey: event.originKey },
16567
16612
  rootMessage: event.rootMessage,
16568
- at
16613
+ at,
16614
+ warnSkipped
16569
16615
  });
16570
16616
  if (resolved?.registered && resolved.conversation.state === "closed") {
16571
16617
  const block = await trx.selectFrom("block").select(["outcome", "unblocked_by"]).where("id", "=", resolved.conversation.block_id ?? -1).executeTakeFirst();
@@ -16644,7 +16690,7 @@ function createInbound(input) {
16644
16690
  async function reapply(trx, itemId, at) {
16645
16691
  const item = await trx.selectFrom("operator_item").selectAll().where("id", "=", itemId).executeTakeFirst();
16646
16692
  if (item === void 0 || item.cleared_at !== null || item.inbound_event_json === null) throw new CommandError("retry_not_applicable", "This item has no stored event to retry.");
16647
- const event = inboundEventSchema.parse(JSON.parse(item.inbound_event_json));
16693
+ const event = parseJson(inboundEventSchema, item.inbound_event_json);
16648
16694
  if (event.kind === "gap" || event.kind === "connection") throw new CommandError("retry_not_applicable", "This event cannot be retried.");
16649
16695
  if (event.kind === "command" || event.kind === "action") {
16650
16696
  await reapplyInteraction(trx, event, at);
@@ -16972,8 +17018,10 @@ function createInbound(input) {
16972
17018
  await scanTransaction(store, config, async (trx) => {
16973
17019
  const context = await taskContext(trx, event, gateway.kind);
16974
17020
  const conversation = event.conversation === void 0 ? void 0 : await trx.selectFrom("conversation").select(["root_message_ref"]).where("gateway", "=", gateway.kind).where("ref", "=", event.conversation).executeTakeFirst();
16975
- const opened = conversation === void 0 ? void 0 : await trx.selectFrom("outbox").select("external_ref").where("kind", "=", "conversation.open").where("state", "=", "done").where(sql`json_extract(external_ref, '$.message')`, "=", conversation.root_message_ref).orderBy("id", "desc").executeTakeFirst();
16976
- const ref = opened?.external_ref === null || opened?.external_ref === void 0 ? void 0 : JSON.parse(opened.external_ref);
17021
+ const opened = conversation === void 0 ? void 0 : await trx.selectFrom("outbox").select(["id", "external_ref"]).where("kind", "=", "conversation.open").where("state", "=", "done").where(sql`json_extract(external_ref, '$.message')`, "=", conversation.root_message_ref).orderBy("id", "desc").executeTakeFirst();
17022
+ const parsed = opened?.external_ref === null || opened?.external_ref === void 0 ? void 0 : deliveredRefSchema.safeParse(JSON.parse(opened.external_ref));
17023
+ if (opened !== void 0 && parsed?.success === false) warnSkipped("outbox", "external_ref", opened.id, parsed.error);
17024
+ const ref = parsed?.data;
16977
17025
  await raiseInboundItem(trx, {
16978
17026
  sourceKey: `inbound:gap:${createHash("sha256").update(JSON.stringify([gateway.kind, event.conversation ?? null])).digest("hex")}`,
16979
17027
  title: "repeat your answer",
@@ -17623,7 +17671,7 @@ const graphErrorWire = z.object({
17623
17671
  function deniedReference(error) {
17624
17672
  return (error.type === "FORBIDDEN" || error.type === "NOT_FOUND") && error.path?.includes("closingIssuesReferences") === true;
17625
17673
  }
17626
- const envelopeWire = z.object({
17674
+ const graphEnvelopeWire = z.object({
17627
17675
  errors: z.array(graphErrorWire).optional(),
17628
17676
  data: z.unknown()
17629
17677
  });
@@ -17641,6 +17689,7 @@ function connectionWire(node) {
17641
17689
  pageInfo: pageInfoWire
17642
17690
  });
17643
17691
  }
17692
+ /** Whether `error` denies a requested team's slug in `query`, which must select it. */
17644
17693
  function teamScopeDenied(error, query) {
17645
17694
  if (error.type !== "INSUFFICIENT_SCOPES" || !query.includes("... on Team { slug }")) return false;
17646
17695
  if (error.path !== void 0) return error.path.includes("reviewRequests") && error.path.includes("requestedReviewer") && error.path.at(-1) === "slug";
@@ -17680,6 +17729,23 @@ function pageQuery(connection, bootstrap = false) {
17680
17729
  if (connection === "pullRequests") return `query DiscoveryPage($owner: String!, $repo: String!, $after: String!) { rateLimit { remaining resetAt } repository(owner: $owner, name: $repo) { pullRequests(first: 100, after: $after, states: [${discoveryStates(bootstrap)}], orderBy: {field: UPDATED_AT, direction: DESC}) { ${DISCOVERY_FIELDS} } } }`;
17681
17730
  return `query PrPage($owner: String!, $repo: String!, $number: Int!, $after: String!) { rateLimit { remaining resetAt } repository(owner: $owner, name: $repo) { pullRequest(number: $number) { ${connection === "closingIssuesReferences" ? `closingIssuesReferences(first: 100, after: $after) { ${CLOSING_FIELDS} }` : connection === "contexts" ? `statusCheckRollup { contexts(first: 100, after: $after) { nodes { ... on CheckRun { __typename name status conclusion startedAt completedAt checkSuite { createdAt } isRequired(pullRequestNumber: $number) } ... on StatusContext { __typename context state createdAt isRequired(pullRequestNumber: $number) } } pageInfo { hasNextPage endCursor } } }` : `${connection}(first: 100, after: $after) { nodes { ${connection === "reviews" ? REVIEW_FIELDS : connection === "reviewThreads" ? "isResolved" : REVIEWER_FIELDS} } pageInfo { hasNextPage endCursor } }`} } } }`;
17682
17731
  }
17732
+ /**
17733
+ * The failure that GraphQL `errors` mean for the whole request, in rule order: a rate limit is
17734
+ * `throttled`, a denied team slug or any missing scope is `auth`. Null when no rule applies.
17735
+ */
17736
+ function graphqlFailure(errors, query, headers, now) {
17737
+ if (errors.some((error) => error.type === "RATE_LIMITED" || /rate limit/i.test(error.message))) return classifyHttpFailure({
17738
+ status: 429,
17739
+ headers
17740
+ }, now);
17741
+ if (errors.some((error) => teamScopeDenied(error, query))) return new AdapterError("auth", "GitHub token needs read:org for team review requests");
17742
+ if (errors.some((error) => error.type === "INSUFFICIENT_SCOPES")) return new AdapterError("auth", "GitHub token lacks a required GraphQL read scope");
17743
+ return null;
17744
+ }
17745
+ /** Whether the token was denied the check runs of a status rollup. */
17746
+ function checkAccessDenied(errors) {
17747
+ return errors.some((error) => error.type === "FORBIDDEN" && error.path?.includes("statusCheckRollup") === true && error.path.includes("contexts"));
17748
+ }
17683
17749
  var GithubClient = class {
17684
17750
  token;
17685
17751
  now;
@@ -17726,14 +17792,10 @@ var GithubClient = class {
17726
17792
  body
17727
17793
  };
17728
17794
  });
17729
- const wire = parseWire(envelopeWire, body, MALFORMED$3);
17795
+ const wire = parseWire(graphEnvelopeWire, body, MALFORMED$3);
17730
17796
  const errors = wire.errors ?? [];
17731
- if (errors.some((error) => error.type === "RATE_LIMITED" || /rate limit/i.test(error.message))) throw classifyHttpFailure({
17732
- status: 429,
17733
- headers: response.headers
17734
- }, this.now());
17735
- if (errors.some((error) => teamScopeDenied(error, query))) throw new AdapterError("auth", "GitHub token needs read:org for team review requests");
17736
- if (errors.some((error) => error.type === "INSUFFICIENT_SCOPES")) throw new AdapterError("auth", "GitHub token lacks a required GraphQL read scope");
17797
+ const failure = graphqlFailure(errors, query, response.headers, this.now());
17798
+ if (failure !== null) throw failure;
17737
17799
  const data = parseWire(dataWire, wire.data, MALFORMED$3, ["data"]);
17738
17800
  return {
17739
17801
  data,
@@ -18016,10 +18078,11 @@ function feedbackOf(reviews, comments, held) {
18016
18078
  function ticketKeys(title, branch, prefixes) {
18017
18079
  return scanKeys(`${title} ${branch}`, prefixes);
18018
18080
  }
18081
+ const SCANNED_KEY = new RegExp(`(?<![A-Za-z0-9_])(${JIRA_PROJECT_KEY})-(${REF_NUMBER})(?![A-Za-z0-9_])`, "gi");
18019
18082
  function scanKeys(text, prefixes) {
18020
18083
  const keys = /* @__PURE__ */ new Set();
18021
18084
  const allowed = new Set(prefixes);
18022
- for (const match of text.matchAll(/(?<![A-Za-z0-9_])([A-Z][A-Z0-9_]*)-([1-9][0-9]*)(?![A-Za-z0-9_])/gi)) {
18085
+ for (const match of text.matchAll(SCANNED_KEY)) {
18023
18086
  const prefix = match[1]?.toUpperCase();
18024
18087
  const number = match[2];
18025
18088
  if (prefix !== void 0 && number !== void 0 && allowed.has(prefix)) keys.add(`${prefix}-${number}`);
@@ -18047,7 +18110,7 @@ function issueKeys(title, branch, refs, rule) {
18047
18110
  }
18048
18111
  return [];
18049
18112
  }
18050
- const JIRA_KEY = /^([A-Z][A-Z0-9_]*)-[1-9][0-9]*$/;
18113
+ const JIRA_KEY = new RegExp(`^(${JIRA_PROJECT_KEY})-${REF_NUMBER}$`);
18051
18114
  function matchedKey(text, pattern, prefixes) {
18052
18115
  if (text.length > MAX_MATCHED_LENGTH) return [];
18053
18116
  const key = pattern.exec(text)?.[1]?.toUpperCase();
@@ -18239,9 +18302,6 @@ const FEEDBACK_PAGES = 3;
18239
18302
  const INDEX_CHUNK = 50;
18240
18303
  const DETAIL_CHUNK = 10;
18241
18304
  const MAX_FAILED_REQUESTS = 8;
18242
- function sourceId(project, repo) {
18243
- return `github:${project}:${repo.toLowerCase()}`;
18244
- }
18245
18305
  function githubSources(config, options) {
18246
18306
  const sources = [];
18247
18307
  for (const project of config.projects) {
@@ -18250,7 +18310,7 @@ function githubSources(config, options) {
18250
18310
  const normalized = repo.toLowerCase();
18251
18311
  if (seen.has(normalized)) throw new AdapterError("config", "Duplicate GitHub repository in project");
18252
18312
  seen.add(normalized);
18253
- const id = sourceId(project.id, repo);
18313
+ const id = prSourceId(project.id, repo);
18254
18314
  const client = new GithubClient(options.token, options.now, options.fetch);
18255
18315
  const keys = projectKeyRule(project.tracker, project.link, repo);
18256
18316
  const cache = /* @__PURE__ */ new Map();
@@ -18290,9 +18350,6 @@ function githubSources(config, options) {
18290
18350
  function scoped(errors, root) {
18291
18351
  return errors.filter((error) => error.path?.[0] === root);
18292
18352
  }
18293
- function checkAccessDenied(errors) {
18294
- return errors.some((error) => error.type === "FORBIDDEN" && error.path?.includes("statusCheckRollup") === true && error.path.includes("contexts"));
18295
- }
18296
18353
  function requireCheckAccess(errors) {
18297
18354
  if (checkAccessDenied(errors)) throw new AdapterError("auth", "GitHub token lacks Checks read permission");
18298
18355
  }
@@ -18691,9 +18748,7 @@ async function pollRepository({ id, repo, login, keys, client, now, ctx, reserve
18691
18748
  if (!owner || !name) throw new AdapterError("config", "Invalid repository");
18692
18749
  const requested = ctx.observe.prs.filter((ref) => ref.repo.toLowerCase() === repo.toLowerCase());
18693
18750
  const byNumber = new Map(requested.map((ref) => [ref.number, ref]));
18694
- const numbers = [...byNumber.keys()];
18695
18751
  const closing = closingSelected(keys);
18696
- for (const number of cache.keys()) if (!byNumber.has(number)) cache.delete(number);
18697
18752
  const acc = accumulator(true);
18698
18753
  const requests = {
18699
18754
  failed: 0,
@@ -18710,18 +18765,21 @@ async function pollRepository({ id, repo, login, keys, client, now, ctx, reserve
18710
18765
  const discovery = await readDiscovery(request, acc, ctx, login);
18711
18766
  if (!discovery.ok) acc.complete = false;
18712
18767
  const { found } = discovery;
18768
+ const numbers = [...byNumber.keys(), ...found.numbers.filter((number) => !byNumber.has(number) && cache.has(number))];
18769
+ const fresh = found.numbers.filter((number) => !byNumber.has(number) && !cache.has(number));
18770
+ for (const number of cache.keys()) if (!byNumber.has(number) && discovery.ok && !found.numbers.includes(number)) cache.delete(number);
18713
18771
  const entries = await readIndex(request, acc, numbers);
18714
18772
  const cursorKey = (number) => JSON.stringify([entryFor(ctx.feedbackCursors, repo, number) ?? "none", entryFor(ctx.continuations, repo, number) ?? "none"]);
18715
18773
  const changed = [];
18716
18774
  for (const number of numbers) {
18717
18775
  const facts = reusable(cache.get(number), entries.get(number), cursorKey(number), now());
18718
18776
  const ref = byNumber.get(number);
18719
- if (facts !== void 0 && ref !== void 0) {
18777
+ if (facts !== void 0) {
18720
18778
  acc.items.push({
18721
18779
  kind: "pr",
18722
18780
  facts
18723
18781
  });
18724
- acc.entities.push({
18782
+ if (ref !== void 0) acc.entities.push({
18725
18783
  ref,
18726
18784
  status: "ok"
18727
18785
  });
@@ -18753,8 +18811,9 @@ async function pollRepository({ id, repo, login, keys, client, now, ctx, reserve
18753
18811
  if (found.numbers.includes(number)) discoveredOk = false;
18754
18812
  }
18755
18813
  };
18756
- const discovered = found.numbers.filter((number) => !byNumber.has(number));
18757
- for (const chunk of [...chunks(changed, DETAIL_CHUNK), ...chunks(discovered, DETAIL_CHUNK)]) {
18814
+ const discovered = [...changed.filter((number) => !byNumber.has(number)), ...fresh];
18815
+ const changedRequested = changed.filter((number) => byNumber.has(number));
18816
+ for (const chunk of [...chunks(changedRequested, DETAIL_CHUNK), ...chunks(discovered, DETAIL_CHUNK)]) {
18758
18817
  if (acc.budget !== void 0 && acc.budget.remaining < reserveRemaining) {
18759
18818
  unread(chunk);
18760
18819
  continue;
@@ -18776,9 +18835,8 @@ async function pollRepository({ id, repo, login, keys, client, now, ctx, reserve
18776
18835
  if (found.numbers.includes(number)) discoveredOk = false;
18777
18836
  continue;
18778
18837
  }
18779
- const entry = entries.get(number);
18780
- if (entry !== void 0) cache.set(number, {
18781
- fingerprint: entry.fingerprint,
18838
+ cache.set(number, {
18839
+ fingerprint: entries.get(number)?.fingerprint ?? null,
18782
18840
  facts,
18783
18841
  cursorKey: cursorKey(number),
18784
18842
  readAt: now()
@@ -19995,7 +20053,7 @@ function queuedBoardRings(wire) {
19995
20053
  }
19996
20054
  /** A single Spur source. State is scoped to this adapter instance, never shared across daemons. */
19997
20055
  function createSpurAdapter(options) {
19998
- const base = new URL(`${options.baseUrl.replace(/\/$/, "")}/`);
20056
+ const base = apiBaseUrl(options.baseUrl);
19999
20057
  const fetchImpl = options.fetch ?? fetch;
20000
20058
  let health = /* @__PURE__ */ new Map();
20001
20059
  let instanceId;
@@ -20249,7 +20307,7 @@ function startAdapters(config, core, options) {
20249
20307
  const entries = [];
20250
20308
  for (const project of config.projects) if (project.tracker.type === "jira") {
20251
20309
  const tracker = project.tracker;
20252
- const id = `jira:${project.id}`;
20310
+ const id = trackerSourceId(project);
20253
20311
  const email = secrets["JIRA_EMAIL"];
20254
20312
  const token = secrets["JIRA_API_TOKEN"];
20255
20313
  entries.push({ adapter: email && token ? createJiraAdapter({
@@ -20266,7 +20324,7 @@ function startAdapters(config, core, options) {
20266
20324
  ...options.jiraSearchMethod === void 0 ? {} : { searchMethod: options.jiraSearchMethod }
20267
20325
  }) : blindSource(id, config.adapters.jira.intervalMs, "Jira credential is missing") });
20268
20326
  } else {
20269
- const id = `github-issues:${project.id}:${project.tracker.repo.toLowerCase()}`;
20327
+ const id = trackerSourceId(project);
20270
20328
  const intervalMs = config.adapters.githubIssues.intervalMs;
20271
20329
  entries.push({
20272
20330
  adapter: githubToken ? createGithubIssuesAdapter({
@@ -20289,7 +20347,7 @@ function startAdapters(config, core, options) {
20289
20347
  reserveRemaining,
20290
20348
  repo
20291
20349
  })));
20292
- else for (const project of config.projects) for (const repo of project.repos) entries.push({ adapter: blindSource(`github:${project.id}:${repo.toLowerCase()}`, config.adapters.github.intervalMs, "GitHub credential is missing") });
20350
+ else for (const project of config.projects) for (const repo of project.repos) entries.push({ adapter: blindSource(prSourceId(project.id, repo), config.adapters.github.intervalMs, "GitHub credential is missing") });
20293
20351
  const notices = /* @__PURE__ */ new Set();
20294
20352
  const runner = startRunner({
20295
20353
  entries: [...entries, { adapter: createSpurAdapter({
@@ -20321,11 +20379,34 @@ function startAdapters(config, core, options) {
20321
20379
  };
20322
20380
  }
20323
20381
  //#endregion
20382
+ //#region ../gateway-slack/src/wire.ts
20383
+ /**
20384
+ * Readers for untrusted Slack payloads. Each keeps the string semantics its callers had:
20385
+ * `textOf` rejects `''`, while `messageTs` accepts it, so a ref anchor of `''` still matches.
20386
+ */
20387
+ const fieldsWire = z.record(z.string(), z.unknown());
20388
+ const itemsWire = z.array(z.unknown());
20389
+ const textWire = z.string().min(1);
20390
+ const messageTsWire = z.object({ ts: z.string() });
20391
+ /** A non-empty string, else undefined. */
20392
+ function textOf(value) {
20393
+ return textWire.safeParse(value).data;
20394
+ }
20395
+ /** The `ts` string of a message, `''` included, else undefined. */
20396
+ function messageTs(value) {
20397
+ return messageTsWire.safeParse(value).data?.ts;
20398
+ }
20399
+ /** A plain object's fields, else null; arrays are not objects here. */
20400
+ function fieldsOf(value) {
20401
+ return fieldsWire.safeParse(value).data ?? null;
20402
+ }
20403
+ /** An array's items, else null. */
20404
+ function itemsOf(value) {
20405
+ return itemsWire.safeParse(value).data ?? null;
20406
+ }
20407
+ //#endregion
20324
20408
  //#region ../gateway-slack/src/api.ts
20325
20409
  var IncompleteHistoryError = class extends Error {};
20326
- function messageTs$1(message) {
20327
- return typeof message === "object" && message !== null && "ts" in message && typeof message.ts === "string" ? message.ts : void 0;
20328
- }
20329
20410
  /**
20330
20411
  * Read every page. An incomplete response is unknown, never an empty history. Once `signal`
20331
20412
  * aborts, no further page is requested.
@@ -20352,8 +20433,9 @@ async function readMessages(client, query) {
20352
20433
  ...cursor === void 0 ? {} : { cursor },
20353
20434
  ...latest === void 0 ? {} : { latest }
20354
20435
  });
20355
- if (!Array.isArray(page.messages)) throw new IncompleteHistoryError("missing messages");
20356
- found.push(...page.messages);
20436
+ const messages = itemsOf(page.messages);
20437
+ if (messages === null) throw new IncompleteHistoryError("missing messages");
20438
+ found.push(...messages);
20357
20439
  const nextCursor = page.response_metadata?.next_cursor;
20358
20440
  if (nextCursor) {
20359
20441
  const key = `cursor:${nextCursor}`;
@@ -20364,7 +20446,7 @@ async function readMessages(client, query) {
20364
20446
  continue;
20365
20447
  }
20366
20448
  if (!page.has_more) return found;
20367
- const lastTs = messageTs$1(page.messages.at(-1));
20449
+ const lastTs = messageTs(messages.at(-1));
20368
20450
  if (lastTs === void 0) throw new IncompleteHistoryError("missing pagination timestamp");
20369
20451
  const key = `latest:${lastTs}`;
20370
20452
  if (seen.has(key)) throw new IncompleteHistoryError("repeated page");
@@ -20450,6 +20532,11 @@ function isAlreadyReacted(error) {
20450
20532
  }
20451
20533
  //#endregion
20452
20534
  //#region ../gateway-slack/src/ref.ts
20535
+ const slackRefWire = z.object({
20536
+ channel: z.string(),
20537
+ ts: z.string(),
20538
+ threadTs: z.string()
20539
+ });
20453
20540
  function conversationRef(channel, ts) {
20454
20541
  return conversationRefSchema.parse(JSON.stringify({
20455
20542
  channel,
@@ -20466,16 +20553,7 @@ function messageRef(channel, ts, threadTs) {
20466
20553
  }
20467
20554
  function parseRef(value) {
20468
20555
  try {
20469
- const parsed = JSON.parse(value);
20470
- if (typeof parsed !== "object" || parsed === null) return null;
20471
- if (!("channel" in parsed) || typeof parsed.channel !== "string") return null;
20472
- if (!("ts" in parsed) || typeof parsed.ts !== "string") return null;
20473
- if (!("threadTs" in parsed) || typeof parsed.threadTs !== "string") return null;
20474
- return {
20475
- channel: parsed.channel,
20476
- ts: parsed.ts,
20477
- threadTs: parsed.threadTs
20478
- };
20556
+ return slackRefWire.safeParse(JSON.parse(value)).data ?? null;
20479
20557
  } catch {
20480
20558
  return null;
20481
20559
  }
@@ -20511,13 +20589,17 @@ function markerId(key) {
20511
20589
  function originMarkerId(key) {
20512
20590
  return blockId(ORIGIN_PREFIX, key);
20513
20591
  }
20592
+ const blockIdWire = z.object({ block_id: z.string() });
20593
+ /** The string `block_id` of each block, in order; anything that is not a block list has none. */
20594
+ function blockIds(blocks) {
20595
+ return (itemsOf(blocks) ?? []).flatMap((block) => {
20596
+ const id = blockIdWire.safeParse(block).data?.block_id;
20597
+ return id === void 0 ? [] : [id];
20598
+ });
20599
+ }
20514
20600
  function markerFromBlocks(blocks) {
20515
- if (!Array.isArray(blocks)) return void 0;
20516
- const values = blocks;
20517
- for (const block of values) {
20518
- if (typeof block !== "object" || block === null || !("block_id" in block)) continue;
20519
- const id = block.block_id;
20520
- if (typeof id !== "string" || !id.startsWith(MARKER_PREFIX)) continue;
20601
+ for (const id of blockIds(blocks)) {
20602
+ if (!id.startsWith(MARKER_PREFIX)) continue;
20521
20603
  try {
20522
20604
  return decodeURIComponent(id.slice(5));
20523
20605
  } catch {
@@ -20527,12 +20609,8 @@ function markerFromBlocks(blocks) {
20527
20609
  }
20528
20610
  /** The first part of a multipart root also carries the unsuffixed delivery key. */
20529
20611
  function originKeyFromBlocks(blocks) {
20530
- if (!Array.isArray(blocks)) return void 0;
20531
- const values = blocks;
20532
- for (const block of values) {
20533
- if (typeof block !== "object" || block === null || !("block_id" in block)) continue;
20534
- const id = block.block_id;
20535
- if (typeof id !== "string" || !id.startsWith(ORIGIN_PREFIX)) continue;
20612
+ for (const id of blockIds(blocks)) {
20613
+ if (!id.startsWith(ORIGIN_PREFIX)) continue;
20536
20614
  try {
20537
20615
  return decodeURIComponent(id.slice(12));
20538
20616
  } catch {
@@ -20747,12 +20825,8 @@ function messageBlocks(text, marker, actions = [], originKey, context = []) {
20747
20825
  }
20748
20826
  //#endregion
20749
20827
  //#region ../gateway-slack/src/deliver.ts
20750
- function messageTs(message) {
20751
- return typeof message === "object" && message !== null && "ts" in message && typeof message.ts === "string" ? message.ts : void 0;
20752
- }
20753
20828
  function messageMarker(message) {
20754
- if (typeof message !== "object" || message === null || !("blocks" in message)) return void 0;
20755
- return markerFromBlocks(message.blocks);
20829
+ return markerFromBlocks(fieldsOf(message)?.blocks);
20756
20830
  }
20757
20831
  function oldest(at) {
20758
20832
  if (at === void 0 || !Number.isFinite(at.getTime())) return void 0;
@@ -20976,12 +21050,6 @@ function parseCommand(text, commandName) {
20976
21050
  }
20977
21051
  //#endregion
20978
21052
  //#region ../gateway-slack/src/normalize.ts
20979
- function record$1(value) {
20980
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
20981
- }
20982
- function string$1(value) {
20983
- return typeof value === "string" && value.length > 0 ? value : void 0;
20984
- }
20985
21053
  function iso(ts) {
20986
21054
  const at = /* @__PURE__ */ new Date(Number(ts) * 1e3);
20987
21055
  return Number.isFinite(at.getTime()) ? at.toISOString() : void 0;
@@ -21005,10 +21073,10 @@ function interactionRef(channel, user, triggerId) {
21005
21073
  }
21006
21074
  function parseInteractionRef(value) {
21007
21075
  try {
21008
- const parsed = record$1(JSON.parse(value));
21076
+ const parsed = fieldsOf(JSON.parse(value));
21009
21077
  if (parsed === null) return null;
21010
- const channel = string$1(parsed.channel);
21011
- const user = string$1(parsed.user);
21078
+ const channel = textOf(parsed.channel);
21079
+ const user = textOf(parsed.user);
21012
21080
  return channel === void 0 || user === void 0 ? null : {
21013
21081
  channel,
21014
21082
  user
@@ -21018,19 +21086,19 @@ function parseInteractionRef(value) {
21018
21086
  }
21019
21087
  }
21020
21088
  function rootKey(context) {
21021
- return originKeyFromBlocks(record$1(context.root)?.blocks);
21089
+ return originKeyFromBlocks(fieldsOf(context.root)?.blocks);
21022
21090
  }
21023
21091
  function own(message, bot) {
21024
- return message.subtype === "bot_message" || bot.botId !== void 0 && message.bot_id === bot.botId || string$1(message.user) === bot.userId;
21092
+ return message.subtype === "bot_message" || bot.botId !== void 0 && message.bot_id === bot.botId || textOf(message.user) === bot.userId;
21025
21093
  }
21026
21094
  function text(value) {
21027
21095
  return typeof value === "string" ? value : void 0;
21028
21096
  }
21029
21097
  function messageBase(message, context) {
21030
- const ts = string$1(message.ts);
21031
- const user = string$1(message.user);
21098
+ const ts = textOf(message.ts);
21099
+ const user = textOf(message.user);
21032
21100
  if (ts === void 0 || user === void 0 || own(message, context.bot)) return null;
21033
- const threadTs = string$1(message.thread_ts) ?? context.rootTs ?? ts;
21101
+ const threadTs = textOf(message.thread_ts) ?? context.rootTs ?? ts;
21034
21102
  const originKey = rootKey(context);
21035
21103
  return {
21036
21104
  ts,
@@ -21041,15 +21109,15 @@ function messageBase(message, context) {
21041
21109
  }
21042
21110
  /** The same message mapper is used for Socket Mode payloads and thread-history records. */
21043
21111
  function normalizeMessage(channel, payload, context) {
21044
- const source = record$1(payload);
21112
+ const source = fieldsOf(payload);
21045
21113
  if (source === null) return [];
21046
21114
  if (source.subtype === "message_deleted") {
21047
- const deletedTs = string$1(source.deleted_ts);
21048
- const previous = record$1(source.previous_message);
21115
+ const deletedTs = textOf(source.deleted_ts);
21116
+ const previous = fieldsOf(source.previous_message);
21049
21117
  if (own(source, context.bot) || previous !== null && own(previous, context.bot)) return [];
21050
- const priorThreadTs = string$1(previous?.thread_ts);
21118
+ const priorThreadTs = textOf(previous?.thread_ts);
21051
21119
  const priorOriginKey = originKeyFromBlocks(previous?.blocks);
21052
- const rootIsDeleted = deletedTs !== void 0 && string$1(previous?.ts) === deletedTs && (priorThreadTs === deletedTs || priorThreadTs === void 0 && priorOriginKey !== void 0);
21120
+ const rootIsDeleted = deletedTs !== void 0 && textOf(previous?.ts) === deletedTs && (priorThreadTs === deletedTs || priorThreadTs === void 0 && priorOriginKey !== void 0);
21053
21121
  const threadTs = priorThreadTs ?? (rootIsDeleted ? deletedTs : void 0);
21054
21122
  if (deletedTs === void 0 || threadTs === void 0) return [{
21055
21123
  kind: "gap",
@@ -21067,12 +21135,12 @@ function normalizeMessage(channel, payload, context) {
21067
21135
  }];
21068
21136
  }
21069
21137
  const changed = source.subtype === "message_changed";
21070
- const message = changed ? record$1(source.message) : source;
21138
+ const message = changed ? fieldsOf(source.message) : source;
21071
21139
  if (message === null) return [];
21072
21140
  const base = messageBase(message, context);
21073
21141
  const body = text(message.text);
21074
21142
  if (base === null || body === void 0) return [];
21075
- const editedTs = string$1(record$1(message.edited)?.ts);
21143
+ const editedTs = textOf(fieldsOf(message.edited)?.ts);
21076
21144
  const editAt = editedTs === void 0 ? void 0 : iso(editedTs);
21077
21145
  const eventBase = {
21078
21146
  conversation: conversationRef(channel, base.threadTs),
@@ -21110,17 +21178,17 @@ function normalizeMessage(channel, payload, context) {
21110
21178
  }
21111
21179
  /** Actions and commands share the same stable trigger identity as their Slack retry. */
21112
21180
  function normalizeInteraction(type, payload, channels, root, commandName = DEFAULT_SLACK_COMMAND) {
21113
- const body = record$1(payload);
21181
+ const body = fieldsOf(payload);
21114
21182
  if (body === null) return [];
21115
- const triggerId = string$1(body.trigger_id);
21183
+ const triggerId = textOf(body.trigger_id);
21116
21184
  if (triggerId === void 0) return [];
21117
- const user = string$1(record$1(body.user)?.id) ?? string$1(body.user_id);
21185
+ const user = textOf(fieldsOf(body.user)?.id) ?? textOf(body.user_id);
21118
21186
  if (user === void 0) return [];
21119
21187
  const author = userIdSchema.parse(user);
21120
21188
  if (type === "slash_commands") {
21121
- const name = string$1(body.command);
21189
+ const name = textOf(body.command);
21122
21190
  if (name === void 0) return [];
21123
- const channel = string$1(body.channel_id);
21191
+ const channel = textOf(body.channel_id);
21124
21192
  if (channel === void 0) return [];
21125
21193
  return [{
21126
21194
  kind: "command",
@@ -21135,14 +21203,13 @@ function normalizeInteraction(type, payload, channels, root, commandName = DEFAU
21135
21203
  }];
21136
21204
  }
21137
21205
  if (type !== "interactive" && type !== "block_actions") return [];
21138
- const channel = string$1(record$1(body.channel)?.id);
21139
- const message = record$1(body.message);
21140
- const ts = string$1(message?.ts);
21141
- const threadTs = string$1(message?.thread_ts) ?? ts;
21142
- const actions = body.actions;
21143
- const actionId = string$1((Array.isArray(actions) ? record$1(actions[0]) : null)?.action_id);
21206
+ const channel = textOf(fieldsOf(body.channel)?.id);
21207
+ const message = fieldsOf(body.message);
21208
+ const ts = textOf(message?.ts);
21209
+ const threadTs = textOf(message?.thread_ts) ?? ts;
21210
+ const actionId = textOf(fieldsOf(itemsOf(body.actions)?.[0])?.action_id);
21144
21211
  if (channel === void 0 || ts === void 0 || threadTs === void 0 || actionId === void 0) return [];
21145
- const originKey = originKeyFromBlocks(root === void 0 ? message?.blocks : record$1(root)?.blocks);
21212
+ const originKey = originKeyFromBlocks(root === void 0 ? message?.blocks : fieldsOf(root)?.blocks);
21146
21213
  return [{
21147
21214
  kind: "action",
21148
21215
  dedupeKey: `slack:${triggerId}`,
@@ -21159,12 +21226,6 @@ function normalizeInteraction(type, payload, channels, root, commandName = DEFAU
21159
21226
  }
21160
21227
  //#endregion
21161
21228
  //#region ../gateway-slack/src/recover.ts
21162
- function record(value) {
21163
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
21164
- }
21165
- function string(value) {
21166
- return typeof value === "string" ? value : void 0;
21167
- }
21168
21229
  /** Milliseconds of a Slack ts, read from its digits so float error cannot shift the millisecond. */
21169
21230
  function tsMillis(ts) {
21170
21231
  const [seconds = "", fraction = ""] = ts.split(".");
@@ -21262,16 +21323,16 @@ async function* recoverThreads(client, request, botIdentity, now) {
21262
21323
  throw error;
21263
21324
  }
21264
21325
  if (history === ABORTED) return;
21265
- const root = history.find((message) => string(record(message)?.ts) === addressed.threadTs);
21326
+ const root = history.find((message) => messageTs(message) === addressed.threadTs);
21266
21327
  if (root === void 0) {
21267
21328
  yield gap(conversation.ref);
21268
21329
  continue;
21269
21330
  }
21270
21331
  const after = conversation.after === void 0 ? null : parseRef(conversation.after);
21271
21332
  const anchor = after?.ts;
21272
- if (conversation.after !== void 0 && (after === null || after.channel !== addressed.channel || after.threadTs !== addressed.threadTs || !history.some((message) => string(record(message)?.ts) === anchor))) yield gap(conversation.ref);
21333
+ if (conversation.after !== void 0 && (after === null || after.channel !== addressed.channel || after.threadTs !== addressed.threadTs || !history.some((message) => messageTs(message) === anchor))) yield gap(conversation.ref);
21273
21334
  for (const message of history) {
21274
- const source = record(message);
21335
+ const source = fieldsOf(message);
21275
21336
  if (source === null) continue;
21276
21337
  const events = normalizeMessage(addressed.channel, source, {
21277
21338
  bot,
@@ -21282,21 +21343,15 @@ async function* recoverThreads(client, request, botIdentity, now) {
21282
21343
  const ts = parseRef(event.message)?.ts;
21283
21344
  if (inInterval(ts, from, until) && (anchor === void 0 || Number(ts) > Number(anchor))) yield event;
21284
21345
  } else if (event.kind === "message_edited") {
21285
- if (inInterval(string(record(source.edited)?.ts), from, until)) yield event;
21346
+ if (inInterval(messageTs(source.edited), from, until)) yield event;
21286
21347
  } else if (event.kind === "message_deleted") {
21287
- if (inInterval(string(source.event_ts), from, until)) yield event;
21348
+ if (inInterval(z.string().safeParse(source.event_ts).data, from, until)) yield event;
21288
21349
  }
21289
21350
  }
21290
21351
  }
21291
21352
  }
21292
21353
  //#endregion
21293
21354
  //#region ../gateway-slack/src/socket.ts
21294
- function object$1(value) {
21295
- return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
21296
- }
21297
- function value(value) {
21298
- return typeof value === "string" && value.length > 0 ? value : void 0;
21299
- }
21300
21355
  async function rootFor(client, channel, threadTs) {
21301
21356
  const root = (await client.conversations.replies({
21302
21357
  channel,
@@ -21323,25 +21378,25 @@ function createSocket(api, config, botIdentity) {
21323
21378
  }
21324
21379
  async function handle(envelope) {
21325
21380
  if (stopping || sink === void 0) return;
21326
- const type = value(envelope.type);
21327
- const body = object$1(envelope.body);
21381
+ const type = textOf(envelope.type);
21382
+ const body = fieldsOf(envelope.body);
21328
21383
  if (type === void 0 || body === null) return;
21329
21384
  let events = [];
21330
21385
  if (type === "events_api") {
21331
- const event = object$1(body.event);
21332
- const eventType = value(event?.type);
21333
- const channel = value(event?.channel);
21386
+ const event = fieldsOf(body.event);
21387
+ const eventType = textOf(event?.type);
21388
+ const channel = textOf(event?.channel);
21334
21389
  if (event !== null && channel !== void 0 && (eventType === "message" || eventType === "app_mention")) {
21335
21390
  const bot = await botIdentity();
21336
21391
  const message = eventType === "app_mention" ? {
21337
21392
  ...event,
21338
21393
  type: "message"
21339
21394
  } : event;
21340
- const nested = object$1(message.message);
21341
- const previous = object$1(message.previous_message);
21342
- const threadTs = value(message.thread_ts) ?? value(nested?.thread_ts) ?? value(previous?.thread_ts);
21343
- const messageTs = value(message.ts) ?? value(nested?.ts);
21344
- const deletedRoot = message.subtype === "message_deleted" && threadTs === value(message.deleted_ts);
21395
+ const nested = fieldsOf(message.message);
21396
+ const previous = fieldsOf(message.previous_message);
21397
+ const threadTs = textOf(message.thread_ts) ?? textOf(nested?.thread_ts) ?? textOf(previous?.thread_ts);
21398
+ const messageTs = textOf(message.ts) ?? textOf(nested?.ts);
21399
+ const deletedRoot = message.subtype === "message_deleted" && threadTs === textOf(message.deleted_ts);
21345
21400
  events = normalizeMessage(channel, message, {
21346
21401
  bot,
21347
21402
  root: threadTs === void 0 || threadTs === messageTs || deletedRoot ? message : await rootFor(api, channel, threadTs),
@@ -21349,10 +21404,10 @@ function createSocket(api, config, botIdentity) {
21349
21404
  });
21350
21405
  }
21351
21406
  } else if (type === "interactive" || type === "block_actions") {
21352
- const actionMessage = object$1(body.message);
21353
- const channel = value(object$1(body.channel)?.id);
21354
- const ts = value(actionMessage?.ts);
21355
- const threadTs = value(actionMessage?.thread_ts) ?? ts;
21407
+ const actionMessage = fieldsOf(body.message);
21408
+ const channel = textOf(fieldsOf(body.channel)?.id);
21409
+ const ts = textOf(actionMessage?.ts);
21410
+ const threadTs = textOf(actionMessage?.thread_ts) ?? ts;
21356
21411
  const root = channel !== void 0 && threadTs !== void 0 && threadTs !== ts ? await rootFor(api, channel, threadTs) : actionMessage;
21357
21412
  events = normalizeInteraction(type, body, config.channels, root);
21358
21413
  } else if (type === "slash_commands") events = normalizeInteraction(type, body, config.channels, void 0, config.command);
@@ -21536,7 +21591,10 @@ function createBoardModules(ctxFor, options = {}) {
21536
21591
  const core = options.core ?? createObservationCore({
21537
21592
  store: coreCtx.store,
21538
21593
  config: coreCtx.config,
21539
- clock: coreCtx.clock
21594
+ clock: coreCtx.clock,
21595
+ warn: (fields, message) => {
21596
+ coreCtx.log.warn(fields, message);
21597
+ }
21540
21598
  });
21541
21599
  const tick = options.tick ?? tickBoard;
21542
21600
  const boardCore = createJob({
@@ -21545,7 +21603,8 @@ function createBoardModules(ctxFor, options = {}) {
21545
21603
  store: coreCtx.store,
21546
21604
  config: coreCtx.config,
21547
21605
  clock: coreCtx.clock,
21548
- completeSince: core.completeSince
21606
+ completeSince: core.completeSince,
21607
+ warnSkipped: core.warnSkipped
21549
21608
  });
21550
21609
  options.onTick?.();
21551
21610
  },
@@ -21623,10 +21682,11 @@ const RETRYABLE_4XX = /* @__PURE__ */ new Set([
21623
21682
  425,
21624
21683
  429
21625
21684
  ]);
21685
+ const spurErrorWire = z.object({ error: z.string() });
21626
21686
  /** The request Spur's own `spur send` makes; the doctor probe sends the same one. */
21627
21687
  function spurSendRequest(baseUrl, session, text) {
21628
21688
  return {
21629
- url: new URL(`sessions/${encodeURIComponent(session)}/send`, new URL(`${baseUrl.replace(/\/$/, "")}/`)),
21689
+ url: new URL(`sessions/${encodeURIComponent(session)}/send`, apiBaseUrl(baseUrl)),
21630
21690
  init: {
21631
21691
  method: "POST",
21632
21692
  headers: { "Content-Type": "application/json" },
@@ -21637,9 +21697,8 @@ function spurSendRequest(baseUrl, session, text) {
21637
21697
  /** The `error` string of a Spur error body, cut to a bounded length; null when unreadable. */
21638
21698
  async function spurErrorText(response) {
21639
21699
  try {
21640
- const value = await response.json();
21641
- if (value === null || typeof value !== "object" || !("error" in value)) return null;
21642
- return typeof value.error === "string" ? value.error.slice(0, ERROR_TEXT_LIMIT) : null;
21700
+ const parsed = spurErrorWire.safeParse(await response.json());
21701
+ return parsed.success ? parsed.data.error.slice(0, ERROR_TEXT_LIMIT) : null;
21643
21702
  } catch {
21644
21703
  return null;
21645
21704
  }
@@ -21678,6 +21737,7 @@ const SPUR_SEND_FIX = "The Spur API at adapters.spur.baseUrl did not accept a do
21678
21737
  const GITHUB_FIX = "Check the GitHub token and repository access.";
21679
21738
  const GITHUB_CHECKS_FIX = "Use a classic GitHub personal access token with the repo scope, authorized for organization SSO where required, to read check runs.";
21680
21739
  const GITHUB_TEAMS_FIX = "Use a classic GitHub personal access token with the repo and read:org scopes to read requested review teams.";
21740
+ const GITHUB_THROTTLED_FIX = "GitHub is rate limiting this token, so access was not checked; rerun board doctor after the limit resets.";
21681
21741
  const GITHUB_ORG_READ_SCOPES = /* @__PURE__ */ new Set([
21682
21742
  "read:org",
21683
21743
  "write:org",
@@ -21696,18 +21756,6 @@ const GITHUB_PROBE = `query DoctorGithubPermissions($owner: String!, $repo: Stri
21696
21756
  } } }
21697
21757
  }
21698
21758
  }`;
21699
- function object(value) {
21700
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
21701
- }
21702
- function scopedGithubError(value) {
21703
- const error = object(value);
21704
- const path = error?.["path"];
21705
- if (!Array.isArray(path)) return null;
21706
- const fields = path.filter((part) => typeof part === "string");
21707
- if (error?.["type"] === "FORBIDDEN" && fields.includes("statusCheckRollup") && fields.includes("contexts")) return GITHUB_CHECKS_FIX;
21708
- if (error?.["type"] === "INSUFFICIENT_SCOPES" && fields.includes("reviewRequests") && fields.includes("requestedReviewer") && fields.includes("slug")) return GITHUB_TEAMS_FIX;
21709
- return null;
21710
- }
21711
21759
  async function deadlineCall(ctx, deadlineMs, name, failure, call) {
21712
21760
  const controller = new AbortController();
21713
21761
  const deadline = setTimeout(() => {
@@ -21732,33 +21780,90 @@ async function deadlineCall(ctx, deadlineMs, name, failure, call) {
21732
21780
  clearTimeout(deadline);
21733
21781
  }
21734
21782
  }
21735
- async function githubGraphql(ctx, fetcher, deadlineMs, token, repo) {
21736
- const [owner, name] = repo.split("/");
21737
- if (!owner || !name) return null;
21783
+ function githubCall(ctx, deadlineMs, send, json) {
21738
21784
  return deadlineCall(ctx, deadlineMs, "doctor.github", "GitHub doctor probe failed", async (signal) => {
21739
- const response = await fetcher("https://api.github.com/graphql", {
21740
- method: "POST",
21741
- headers: {
21742
- Authorization: `Bearer ${token}`,
21743
- Accept: "application/vnd.github+json",
21744
- "Content-Type": "application/json"
21745
- },
21746
- body: JSON.stringify({
21747
- query: GITHUB_PROBE,
21748
- variables: {
21749
- owner,
21750
- repo: name
21751
- }
21752
- }),
21753
- signal
21754
- });
21785
+ const response = await send(signal);
21786
+ if (response.ok) return {
21787
+ response,
21788
+ failure: null,
21789
+ body: json ? await response.json() : null
21790
+ };
21791
+ const body = await response.text().catch(() => void 0);
21755
21792
  return {
21756
21793
  response,
21757
- body: response.ok ? await response.json() : null
21794
+ failure: classifyHttpFailure({
21795
+ status: response.status,
21796
+ headers: response.headers,
21797
+ body
21798
+ }, ctx.clock.now()),
21799
+ body: null
21758
21800
  };
21759
21801
  });
21760
21802
  }
21761
- const FIX_MAX = 300;
21803
+ function githubHeaders(token) {
21804
+ return {
21805
+ Authorization: `Bearer ${token}`,
21806
+ Accept: "application/vnd.github+json"
21807
+ };
21808
+ }
21809
+ function githubGraphql(ctx, fetcher, deadlineMs, token, repo) {
21810
+ const [owner, name] = repo.split("/");
21811
+ if (!owner || !name) return Promise.resolve(null);
21812
+ return githubCall(ctx, deadlineMs, (signal) => fetcher("https://api.github.com/graphql", {
21813
+ method: "POST",
21814
+ headers: {
21815
+ ...githubHeaders(token),
21816
+ "Content-Type": "application/json"
21817
+ },
21818
+ body: JSON.stringify({
21819
+ query: GITHUB_PROBE,
21820
+ variables: {
21821
+ owner,
21822
+ repo: name
21823
+ }
21824
+ }),
21825
+ signal
21826
+ }), true);
21827
+ }
21828
+ const githubFail = (fix) => ({
21829
+ status: "fail",
21830
+ fix
21831
+ });
21832
+ const githubHttpFinding = (failure) => failure.kind === "throttled" ? {
21833
+ status: "warning",
21834
+ fix: GITHUB_THROTTLED_FIX
21835
+ } : githubFail(GITHUB_FIX);
21836
+ const githubDataWire = z.object({ repository: z.object({ pullRequests: z.object({ nodes: z.array(z.unknown()) }) }) });
21837
+ async function githubRepoFinding(ctx, fetcher, deadlineMs, token, repo) {
21838
+ const rest = await githubCall(ctx, deadlineMs, (signal) => fetcher(`https://api.github.com/repos/${repo}`, {
21839
+ headers: githubHeaders(token),
21840
+ signal
21841
+ }), false);
21842
+ if (rest === null) return githubFail(GITHUB_FIX);
21843
+ if (rest.failure !== null) return githubHttpFinding(rest.failure);
21844
+ const probe = await githubGraphql(ctx, fetcher, deadlineMs, token, repo);
21845
+ if (probe === null) return githubFail(GITHUB_FIX);
21846
+ if (probe.failure !== null) return githubHttpFinding(probe.failure);
21847
+ const envelope = graphEnvelopeWire.safeParse(probe.body);
21848
+ if (!envelope.success) return githubFail(GITHUB_FIX);
21849
+ const errors = envelope.data.errors ?? [];
21850
+ const failure = graphqlFailure(errors, GITHUB_PROBE, probe.response.headers, ctx.clock.now());
21851
+ if (failure?.kind === "throttled") return githubHttpFinding(failure);
21852
+ if (failure !== null) return githubFail(errors.some((error) => teamScopeDenied(error, GITHUB_PROBE)) ? GITHUB_TEAMS_FIX : GITHUB_FIX);
21853
+ if (checkAccessDenied(errors)) return githubFail(GITHUB_CHECKS_FIX);
21854
+ if (errors.length > 0) return githubFail(GITHUB_FIX);
21855
+ if (!githubDataWire.safeParse(envelope.data.data).success) return githubFail(GITHUB_FIX);
21856
+ const scopes = rest.response.headers.get("x-oauth-scopes");
21857
+ if (scopes !== null && !scopes.split(",").some((scope) => GITHUB_ORG_READ_SCOPES.has(scope.trim()))) return githubFail(GITHUB_TEAMS_FIX);
21858
+ return null;
21859
+ }
21860
+ function githubCheck(findings) {
21861
+ const id = "github.credentials";
21862
+ const failed = findings.find((finding) => finding?.status === "fail");
21863
+ if (failed) return check(id, false, failed.fix);
21864
+ const throttled = findings.find((finding) => finding?.status === "warning");
21865
+ return throttled ? warning(id, throttled.fix) : check(id, true, GITHUB_FIX);
21866
+ }
21762
21867
  const BRANCH_MAX = 40;
21763
21868
  const NAMED_PRS = 3;
21764
21869
  const LINK_RULES_TAIL = "Change projects[].link to the repo's branch and PR title rules.";
@@ -21830,12 +21935,12 @@ function linkSegment(outcome) {
21830
21935
  function fitFix(segments, tail, fallback) {
21831
21936
  for (const branches of [true, false]) {
21832
21937
  const full = `${segments.map((segment) => segment.text(branches)).join(". ")}.${tail}`;
21833
- if (full.length <= FIX_MAX) return full;
21938
+ if (full.length <= 300) return full;
21834
21939
  }
21835
21940
  const texts = segments.map((segment) => segment.text(false));
21836
21941
  for (let kept = texts.length - 1; kept > 0; kept -= 1) {
21837
21942
  const text = `${texts.slice(0, kept).join(". ")}; and ${String(texts.length - kept)} more projects.${tail}`;
21838
- if (text.length <= FIX_MAX) return text;
21943
+ if (text.length <= 300) return text;
21839
21944
  }
21840
21945
  return fallback;
21841
21946
  }
@@ -21919,24 +22024,23 @@ async function request(ctx, fetcher, deadlineMs, id, url, init = {}) {
21919
22024
  return null;
21920
22025
  }
21921
22026
  }
21922
- async function slackOk(response) {
21923
- if (response === null || !response.ok) return false;
21924
- try {
21925
- const value = await response.json();
21926
- return value !== null && typeof value === "object" && "ok" in value && value.ok === true;
21927
- } catch {
21928
- return false;
21929
- }
21930
- }
21931
- async function slackMember(response) {
21932
- if (response === null || !response.ok) return false;
22027
+ const slackOkWire = z.object({ ok: z.literal(true) });
22028
+ const slackMemberWire = z.object({
22029
+ ok: z.literal(true),
22030
+ channel: z.object({ is_member: z.literal(true) })
22031
+ });
22032
+ const slackManifestWire = z.object({
22033
+ ok: z.literal(true),
22034
+ manifest: z.object({ features: z.object({ slash_commands: z.array(z.unknown()) }) })
22035
+ });
22036
+ const slashCommandWire = z.object({ command: z.string() });
22037
+ async function slackBody(response, wire) {
22038
+ if (response === null || !response.ok) return null;
21933
22039
  try {
21934
- const value = await response.json();
21935
- if (value === null || typeof value !== "object" || !("ok" in value) || value.ok !== true) return false;
21936
- const channel = "channel" in value ? value.channel : void 0;
21937
- return channel !== null && typeof channel === "object" && "is_member" in channel && channel.is_member === true;
22040
+ const parsed = wire.safeParse(await response.json());
22041
+ return parsed.success ? parsed.data : null;
21938
22042
  } catch {
21939
- return false;
22043
+ return null;
21940
22044
  }
21941
22045
  }
21942
22046
  /** Bounded daemon-side checks; no response body or exception text leaves this module. */
@@ -21963,32 +22067,11 @@ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch, { deadlineM
21963
22067
  checks.push(check("jira.credentials", jiraOk, "Check the Jira account, API token, and project access."));
21964
22068
  const githubToken = secrets["GITHUB_TOKEN"];
21965
22069
  const githubRepos = new Set(config.projects.flatMap((project) => project.repos));
21966
- const githubFailure = (githubToken === void 0 ? [GITHUB_FIX] : await Promise.all([...githubRepos].map(async (repo) => {
21967
- const response = await request(ctx, fetcher, deadlineMs, "github", `https://api.github.com/repos/${repo}`, { headers: {
21968
- Authorization: `Bearer ${githubToken}`,
21969
- Accept: "application/vnd.github+json"
21970
- } });
21971
- if (response?.ok !== true) return GITHUB_FIX;
21972
- const probe = await githubGraphql(ctx, fetcher, deadlineMs, githubToken, repo);
21973
- if (probe?.response.ok !== true) return GITHUB_FIX;
21974
- const payload = object(probe.body);
21975
- const errors = payload?.["errors"];
21976
- if (errors !== void 0) {
21977
- if (!Array.isArray(errors)) return GITHUB_FIX;
21978
- const scoped = errors.map(scopedGithubError).find((fix) => fix !== null);
21979
- if (scoped) return scoped;
21980
- if (errors.length > 0) return GITHUB_FIX;
21981
- }
21982
- const pullRequests = object(object(object(payload?.["data"])?.["repository"])?.["pullRequests"]);
21983
- if (!Array.isArray(pullRequests?.["nodes"])) return GITHUB_FIX;
21984
- const scopes = response.headers.get("x-oauth-scopes");
21985
- if (scopes !== null && !scopes.split(",").some((scope) => GITHUB_ORG_READ_SCOPES.has(scope.trim()))) return GITHUB_TEAMS_FIX;
21986
- return null;
21987
- }))).find((failure) => failure !== null) ?? null;
21988
- checks.push(check("github.credentials", githubFailure === null, githubFailure ?? GITHUB_FIX));
22070
+ const githubFindings = githubToken === void 0 ? [githubFail(GITHUB_FIX)] : await Promise.all([...githubRepos].map((repo) => githubRepoFinding(ctx, fetcher, deadlineMs, githubToken, repo)));
22071
+ checks.push(githubCheck(githubFindings));
21989
22072
  checks.push(linkRulesCheck(await linkSamples));
21990
22073
  const probe = spurSendRequest(config.adapters.spur.baseUrl, SPUR_PROBE_SESSION, "spur-board doctor probe");
21991
- const [spur, spurSend] = await Promise.all([request(ctx, fetcher, deadlineMs, "spur", new URL("sessions", `${config.adapters.spur.baseUrl.replace(/\/$/, "")}/`)), request(ctx, fetcher, deadlineMs, "spur.send", probe.url, probe.init)]);
22074
+ const [spur, spurSend] = await Promise.all([request(ctx, fetcher, deadlineMs, "spur", new URL("sessions", apiBaseUrl(config.adapters.spur.baseUrl))), request(ctx, fetcher, deadlineMs, "spur.send", probe.url, probe.init)]);
21992
22075
  checks.push(check("spur.api", spur?.ok === true, "Start or correct the configured Spur API."));
21993
22076
  const spurSendOk = spurSend?.status === 404 && ((await spurErrorText(spurSend))?.startsWith("Session not found") ?? false);
21994
22077
  if (spurSend !== null && spurSend.status !== 404) await spurSend.body?.cancel().catch(() => void 0);
@@ -21997,40 +22080,33 @@ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch, { deadlineM
21997
22080
  else {
21998
22081
  const botToken = secrets["SLACK_BOT_TOKEN"];
21999
22082
  const slackHeaders = botToken ? { Authorization: `Bearer ${botToken}` } : {};
22000
- const slackBase = `${(secrets["SLACK_API_URL"] || "https://slack.com/api/").replace(/\/$/, "")}/`;
22083
+ const slackBase = apiBaseUrl(secrets["SLACK_API_URL"] || "https://slack.com/api/");
22001
22084
  const auth = botToken ? await request(ctx, fetcher, deadlineMs, "slack.auth", new URL("auth.test", slackBase), {
22002
22085
  method: "POST",
22003
22086
  headers: slackHeaders
22004
22087
  }) : null;
22005
- const authorized = await slackOk(auth);
22088
+ const authorized = await slackBody(auth, slackOkWire) !== null;
22006
22089
  const granted = new Set(auth?.headers.get("x-oauth-scopes")?.split(",").map((scope) => scope.trim()).filter(Boolean) ?? []);
22007
22090
  const missingScopes = SLACK_BOT_SCOPES.filter((scope) => !granted.has(scope));
22008
22091
  checks.push(check("slack.auth", authorized && missingScopes.length === 0, authorized ? `Add ${missingScopes.join(", ")} to the Slack app and reinstall it.` : "Check the Slack bot token."));
22009
22092
  for (const [id, channel] of [["slack.orchestrators_member", config.slack.channels.orchestrators], ["slack.feed_member", config.slack.channels.feed]]) {
22010
22093
  const response = botToken && channel ? await request(ctx, fetcher, deadlineMs, id, new URL(`conversations.info?channel=${encodeURIComponent(channel)}`, slackBase), { headers: slackHeaders }) : null;
22011
- checks.push(check(id, await slackMember(response), "Invite the bot to the configured channel ID."));
22094
+ checks.push(check(id, await slackBody(response, slackMemberWire) !== null, "Invite the bot to the configured channel ID."));
22012
22095
  }
22013
22096
  const configToken = secrets["SLACK_APP_CONFIG_TOKEN"];
22014
22097
  if (!configToken || !config.slack.appId) checks.push(warning("slack.command", "Verify the installed Slack slash command against slack.command manually, or provide SLACK_APP_CONFIG_TOKEN and slack.appId."));
22015
22098
  else {
22016
- const response = await request(ctx, fetcher, deadlineMs, "slack.command", new URL("apps.manifest.export", slackBase), {
22099
+ const commands = (await slackBody(await request(ctx, fetcher, deadlineMs, "slack.command", new URL("apps.manifest.export", slackBase), {
22017
22100
  method: "POST",
22018
22101
  headers: {
22019
22102
  Authorization: `Bearer ${configToken}`,
22020
22103
  "Content-Type": "application/json"
22021
22104
  },
22022
22105
  body: JSON.stringify({ app_id: config.slack.appId })
22023
- });
22024
- let commands = null;
22025
- if (response?.ok) try {
22026
- const body = await response.json();
22027
- if (body && typeof body === "object" && "ok" in body && body.ok === true) {
22028
- const manifest = "manifest" in body ? body.manifest : void 0;
22029
- const features = manifest && typeof manifest === "object" && "features" in manifest ? manifest.features : void 0;
22030
- const slash = features && typeof features === "object" && "slash_commands" in features ? features.slash_commands : void 0;
22031
- if (Array.isArray(slash)) commands = slash.flatMap((entry) => entry && typeof entry === "object" && "command" in entry && typeof entry.command === "string" ? [entry.command] : []);
22032
- }
22033
- } catch {}
22106
+ }), slackManifestWire))?.manifest.features.slash_commands.flatMap((entry) => {
22107
+ const parsed = slashCommandWire.safeParse(entry);
22108
+ return parsed.success ? [parsed.data.command] : [];
22109
+ }) ?? null;
22034
22110
  checks.push(commands === null ? warning("slack.command", "Refresh the Slack app configuration token and verify the installed slash command manually.") : check("slack.command", commands.includes(config.slack.command), "Change the installed Slack slash command to match slack.command in config.yaml."));
22035
22111
  }
22036
22112
  }
@@ -22047,19 +22123,21 @@ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch, { deadlineM
22047
22123
  //#endregion
22048
22124
  //#region ../daemon/src/http-module.ts
22049
22125
  const SESSION_TIMEOUT_MS = 5e3;
22126
+ const sessionDetailWire = z.object({
22127
+ id: z.string(),
22128
+ project: z.string().min(1),
22129
+ status: z.enum(SESSION_STATUSES)
22130
+ });
22050
22131
  /** Fetch one session after a snapshot miss; 404 is a confirmed unknown session. */
22051
22132
  async function lookupLiveSession(baseUrl, id, fetcher = fetch) {
22052
- const base = new URL(`${baseUrl.replace(/\/$/, "")}/`);
22053
- const response = await fetcher(new URL(`sessions/${encodeURIComponent(id)}`, base), { signal: AbortSignal.timeout(SESSION_TIMEOUT_MS) });
22133
+ const response = await fetcher(new URL(`sessions/${encodeURIComponent(id)}`, apiBaseUrl(baseUrl)), { signal: AbortSignal.timeout(SESSION_TIMEOUT_MS) });
22054
22134
  if (response.status === 404) return null;
22055
22135
  if (!response.ok) throw new Error(`Session lookup failed with HTTP ${String(response.status)}`);
22056
- const body = await response.json();
22057
- if (body === null || typeof body !== "object" || Array.isArray(body)) throw new Error("Invalid session detail response");
22058
- const record = body;
22059
- if (record["id"] !== id || typeof record["project"] !== "string" || record["project"].length === 0 || typeof record["status"] !== "string" || !SESSION_STATUSES.some((status) => status === record["status"])) throw new Error("Invalid session detail response");
22136
+ const detail = sessionDetailWire.safeParse(await response.json());
22137
+ if (!detail.success || detail.data.id !== id) throw new Error("Invalid session detail response");
22060
22138
  return {
22061
- project: record["project"],
22062
- status: record["status"]
22139
+ project: detail.data.project,
22140
+ status: detail.data.status
22063
22141
  };
22064
22142
  }
22065
22143
  /** Start and close the API as a daemon module, with runtime ports from its context. */
@@ -22131,7 +22209,10 @@ function createInboundModule(ctx, gateway, registry = {}) {
22131
22209
  gateway,
22132
22210
  config: ctx.config,
22133
22211
  clock: ctx.clock,
22134
- registry
22212
+ registry,
22213
+ warn: (fields, message) => {
22214
+ ctx.log.warn(fields, message);
22215
+ }
22135
22216
  });
22136
22217
  const recovery = createJob({
22137
22218
  run: () => ctx.logCall("inbound.recover", () => inbound.recover()),
@@ -22375,6 +22456,9 @@ function createDaemonModules(ctxFor, ports = {}) {
22375
22456
  store: board.store,
22376
22457
  config: board.config,
22377
22458
  clock: board.clock,
22459
+ warn: (fields, message) => {
22460
+ board.log.warn(fields, message);
22461
+ },
22378
22462
  ...ports.productVersion === void 0 ? {} : { productVersion: ports.productVersion }
22379
22463
  });
22380
22464
  const ctx = ctxFor("gateway-slack");
@@ -22489,20 +22573,24 @@ function createDaemonModules(ctxFor, ports = {}) {
22489
22573
  tick: boardModules.tick
22490
22574
  };
22491
22575
  }
22576
+ const itemInput = z.object({ item: z.string() });
22492
22577
  function isItemInput(input) {
22493
- return typeof input === "object" && input !== null && "item" in input && typeof input.item === "string";
22578
+ return itemInput.safeParse(input).success;
22494
22579
  }
22495
22580
  //#endregion
22496
22581
  //#region ../daemon/src/main.ts
22497
22582
  const KEEPALIVE_MS = 36e5;
22583
+ const packedManifestWire = z.object({ name: z.literal("spur-board") });
22584
+ const versionWire = z.object({ version: z.string() });
22498
22585
  /** Resolve the publishable package, both from source and from the packed daemon. */
22499
22586
  function publishedVersion() {
22500
22587
  const packed = new URL("../package.json", import.meta.url);
22501
22588
  const source = new URL("../../cli/package.json", import.meta.url);
22502
22589
  const packedManifest = existsSync(packed) ? JSON.parse(readFileSync(packed, "utf8")) : null;
22503
- const manifest = packedManifest !== null && typeof packedManifest === "object" && "name" in packedManifest && packedManifest.name === "spur-board" ? packedManifest : JSON.parse(readFileSync(source, "utf8"));
22504
- if (manifest === null || typeof manifest !== "object" || !("version" in manifest) || typeof manifest.version !== "string") throw new Error("Invalid spur-board package version.");
22505
- return manifest.version;
22590
+ const manifest = packedManifestWire.safeParse(packedManifest).success ? packedManifest : JSON.parse(readFileSync(source, "utf8"));
22591
+ const parsed = versionWire.safeParse(manifest);
22592
+ if (!parsed.success) throw new Error("Invalid spur-board package version.");
22593
+ return parsed.data.version;
22506
22594
  }
22507
22595
  /** The real process. Handlers are attached when runDaemon registers them, not before. */
22508
22596
  function processPort() {