spur-board 0.52.1 → 0.53.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,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;
@@ -16015,12 +16053,14 @@ async function holdContinuation(trx, source, item) {
16015
16053
  function createObservationCore(deps) {
16016
16054
  const { store, config, clock } = deps;
16017
16055
  const completeSince = /* @__PURE__ */ new Map();
16056
+ const warnSkipped = warnSkippedOnce(deps.warn);
16018
16057
  return {
16019
16058
  completeSince,
16059
+ warnSkipped,
16020
16060
  async context(source) {
16021
16061
  const state = await store.db.selectFrom("source_state").selectAll().where("source", "=", source).executeTakeFirst();
16022
16062
  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([
16063
+ const tickets = project !== void 0 && source === trackerSourceId(project) ? (await store.db.selectFrom("task").leftJoin("ticket_snapshot", "ticket_snapshot.task_id", "task.id").select([
16024
16064
  "task.key",
16025
16065
  "task.tracker_id",
16026
16066
  "task.manual_include",
@@ -16135,7 +16175,7 @@ function createObservationCore(deps) {
16135
16175
  }
16136
16176
  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
16177
  if (observation.effectiveComplete) {
16138
- const project = config.projects.find((entry) => trackerSource(entry) === source);
16178
+ const project = config.projects.find((entry) => trackerSourceId(entry) === source);
16139
16179
  if (project !== void 0) {
16140
16180
  const seen = new Set(batch.items.flatMap((item) => item.kind === "ticket" && item.facts.inFilter ? [item.facts.id] : []));
16141
16181
  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 +16210,7 @@ function createObservationCore(deps) {
16170
16210
  const blind = new Set(states.filter((state) => state.blind_reason !== null).map((state) => state.source));
16171
16211
  const activeTasks = await trx.selectFrom("task").select("id").where("membership", "!=", "archived").execute();
16172
16212
  for (const task of activeTasks) await updateTerminal(trx, config, task.id, batch.observedAt, currentComplete, blind);
16173
- await reconcileMembership(trx, config, currentComplete, batch.observedAt);
16213
+ await reconcileMembership(trx, config, currentComplete, batch.observedAt, warnSkipped);
16174
16214
  const dispatchContext = {
16175
16215
  config,
16176
16216
  at: new Date(batch.observedAt),
@@ -16179,7 +16219,7 @@ function createObservationCore(deps) {
16179
16219
  const recovered = wasBlind !== null && observation.state.blind === void 0;
16180
16220
  if (observation.effectiveComplete && !completeSince.has(source) || recovered) await dispatchSource(trx, source, dispatchContext);
16181
16221
  await dispatchJournaled(trx, dispatchContext);
16182
- await reconcileItems(trx, config, now, currentComplete.has("spur"));
16222
+ await reconcileItems(trx, config, now, currentComplete.has("spur"), warnSkipped);
16183
16223
  if (deps.productVersion !== void 0) await enqueueLiveAfterFirstPoll(trx, {
16184
16224
  config,
16185
16225
  productVersion: deps.productVersion,
@@ -16200,7 +16240,7 @@ function createObservationCore(deps) {
16200
16240
  at: new Date(now),
16201
16241
  complete: completeSince
16202
16242
  });
16203
- await reconcileItems(trx, config, now, completeSince.has("spur"));
16243
+ await reconcileItems(trx, config, now, completeSince.has("spur"), warnSkipped);
16204
16244
  });
16205
16245
  },
16206
16246
  notice(kind, value) {
@@ -16279,7 +16319,7 @@ async function tickBoard(deps) {
16279
16319
  if (task.terminal_at === null || task.terminal_at > slot || task.archive_slot_at === slot) continue;
16280
16320
  const project = config.projects.find((entry) => entry.id === task.project);
16281
16321
  if (project === void 0 || project.repos.some((repo) => {
16282
- const source = `github:${project.id}:${repo.toLowerCase()}`;
16322
+ const source = prSourceId(project.id, repo);
16283
16323
  const complete = completeSince.get(source);
16284
16324
  return blind.has(source) || complete === void 0 || complete <= (task.last_change_at ?? task.created_at);
16285
16325
  })) continue;
@@ -16297,7 +16337,7 @@ async function tickBoard(deps) {
16297
16337
  complete: completeSince
16298
16338
  });
16299
16339
  await remindStuckTurns(trx, config, new Date(now));
16300
- await reconcileItems(trx, config, now, completeSince.has("spur"));
16340
+ await reconcileItems(trx, config, now, completeSince.has("spur"), deps.warnSkipped);
16301
16341
  });
16302
16342
  }
16303
16343
  //#endregion
@@ -16549,6 +16589,7 @@ function first(set) {
16549
16589
  }
16550
16590
  function createInbound(input) {
16551
16591
  const { store, gateway, config } = input;
16592
+ const warnSkipped = warnSkippedOnce(input.warn);
16552
16593
  const clock = input.clock ?? { now: () => Date.now() };
16553
16594
  const registry = input.registry ?? {};
16554
16595
  let running = Promise.resolve();
@@ -16565,7 +16606,8 @@ function createInbound(input) {
16565
16606
  ref: event.conversation,
16566
16607
  ...event.originKey === void 0 ? {} : { originKey: event.originKey },
16567
16608
  rootMessage: event.rootMessage,
16568
- at
16609
+ at,
16610
+ warnSkipped
16569
16611
  });
16570
16612
  if (resolved?.registered && resolved.conversation.state === "closed") {
16571
16613
  const block = await trx.selectFrom("block").select(["outcome", "unblocked_by"]).where("id", "=", resolved.conversation.block_id ?? -1).executeTakeFirst();
@@ -16644,7 +16686,7 @@ function createInbound(input) {
16644
16686
  async function reapply(trx, itemId, at) {
16645
16687
  const item = await trx.selectFrom("operator_item").selectAll().where("id", "=", itemId).executeTakeFirst();
16646
16688
  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));
16689
+ const event = parseJson(inboundEventSchema, item.inbound_event_json);
16648
16690
  if (event.kind === "gap" || event.kind === "connection") throw new CommandError("retry_not_applicable", "This event cannot be retried.");
16649
16691
  if (event.kind === "command" || event.kind === "action") {
16650
16692
  await reapplyInteraction(trx, event, at);
@@ -16972,8 +17014,10 @@ function createInbound(input) {
16972
17014
  await scanTransaction(store, config, async (trx) => {
16973
17015
  const context = await taskContext(trx, event, gateway.kind);
16974
17016
  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);
17017
+ 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();
17018
+ const parsed = opened?.external_ref === null || opened?.external_ref === void 0 ? void 0 : deliveredRefSchema.safeParse(JSON.parse(opened.external_ref));
17019
+ if (opened !== void 0 && parsed?.success === false) warnSkipped("outbox", "external_ref", opened.id, parsed.error);
17020
+ const ref = parsed?.data;
16977
17021
  await raiseInboundItem(trx, {
16978
17022
  sourceKey: `inbound:gap:${createHash("sha256").update(JSON.stringify([gateway.kind, event.conversation ?? null])).digest("hex")}`,
16979
17023
  title: "repeat your answer",
@@ -17623,7 +17667,7 @@ const graphErrorWire = z.object({
17623
17667
  function deniedReference(error) {
17624
17668
  return (error.type === "FORBIDDEN" || error.type === "NOT_FOUND") && error.path?.includes("closingIssuesReferences") === true;
17625
17669
  }
17626
- const envelopeWire = z.object({
17670
+ const graphEnvelopeWire = z.object({
17627
17671
  errors: z.array(graphErrorWire).optional(),
17628
17672
  data: z.unknown()
17629
17673
  });
@@ -17641,6 +17685,7 @@ function connectionWire(node) {
17641
17685
  pageInfo: pageInfoWire
17642
17686
  });
17643
17687
  }
17688
+ /** Whether `error` denies a requested team's slug in `query`, which must select it. */
17644
17689
  function teamScopeDenied(error, query) {
17645
17690
  if (error.type !== "INSUFFICIENT_SCOPES" || !query.includes("... on Team { slug }")) return false;
17646
17691
  if (error.path !== void 0) return error.path.includes("reviewRequests") && error.path.includes("requestedReviewer") && error.path.at(-1) === "slug";
@@ -17680,6 +17725,23 @@ function pageQuery(connection, bootstrap = false) {
17680
17725
  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
17726
  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
17727
  }
17728
+ /**
17729
+ * The failure that GraphQL `errors` mean for the whole request, in rule order: a rate limit is
17730
+ * `throttled`, a denied team slug or any missing scope is `auth`. Null when no rule applies.
17731
+ */
17732
+ function graphqlFailure(errors, query, headers, now) {
17733
+ if (errors.some((error) => error.type === "RATE_LIMITED" || /rate limit/i.test(error.message))) return classifyHttpFailure({
17734
+ status: 429,
17735
+ headers
17736
+ }, now);
17737
+ if (errors.some((error) => teamScopeDenied(error, query))) return new AdapterError("auth", "GitHub token needs read:org for team review requests");
17738
+ if (errors.some((error) => error.type === "INSUFFICIENT_SCOPES")) return new AdapterError("auth", "GitHub token lacks a required GraphQL read scope");
17739
+ return null;
17740
+ }
17741
+ /** Whether the token was denied the check runs of a status rollup. */
17742
+ function checkAccessDenied(errors) {
17743
+ return errors.some((error) => error.type === "FORBIDDEN" && error.path?.includes("statusCheckRollup") === true && error.path.includes("contexts"));
17744
+ }
17683
17745
  var GithubClient = class {
17684
17746
  token;
17685
17747
  now;
@@ -17726,14 +17788,10 @@ var GithubClient = class {
17726
17788
  body
17727
17789
  };
17728
17790
  });
17729
- const wire = parseWire(envelopeWire, body, MALFORMED$3);
17791
+ const wire = parseWire(graphEnvelopeWire, body, MALFORMED$3);
17730
17792
  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");
17793
+ const failure = graphqlFailure(errors, query, response.headers, this.now());
17794
+ if (failure !== null) throw failure;
17737
17795
  const data = parseWire(dataWire, wire.data, MALFORMED$3, ["data"]);
17738
17796
  return {
17739
17797
  data,
@@ -18016,10 +18074,11 @@ function feedbackOf(reviews, comments, held) {
18016
18074
  function ticketKeys(title, branch, prefixes) {
18017
18075
  return scanKeys(`${title} ${branch}`, prefixes);
18018
18076
  }
18077
+ const SCANNED_KEY = new RegExp(`(?<![A-Za-z0-9_])(${JIRA_PROJECT_KEY})-(${REF_NUMBER})(?![A-Za-z0-9_])`, "gi");
18019
18078
  function scanKeys(text, prefixes) {
18020
18079
  const keys = /* @__PURE__ */ new Set();
18021
18080
  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)) {
18081
+ for (const match of text.matchAll(SCANNED_KEY)) {
18023
18082
  const prefix = match[1]?.toUpperCase();
18024
18083
  const number = match[2];
18025
18084
  if (prefix !== void 0 && number !== void 0 && allowed.has(prefix)) keys.add(`${prefix}-${number}`);
@@ -18047,7 +18106,7 @@ function issueKeys(title, branch, refs, rule) {
18047
18106
  }
18048
18107
  return [];
18049
18108
  }
18050
- const JIRA_KEY = /^([A-Z][A-Z0-9_]*)-[1-9][0-9]*$/;
18109
+ const JIRA_KEY = new RegExp(`^(${JIRA_PROJECT_KEY})-${REF_NUMBER}$`);
18051
18110
  function matchedKey(text, pattern, prefixes) {
18052
18111
  if (text.length > MAX_MATCHED_LENGTH) return [];
18053
18112
  const key = pattern.exec(text)?.[1]?.toUpperCase();
@@ -18239,9 +18298,6 @@ const FEEDBACK_PAGES = 3;
18239
18298
  const INDEX_CHUNK = 50;
18240
18299
  const DETAIL_CHUNK = 10;
18241
18300
  const MAX_FAILED_REQUESTS = 8;
18242
- function sourceId(project, repo) {
18243
- return `github:${project}:${repo.toLowerCase()}`;
18244
- }
18245
18301
  function githubSources(config, options) {
18246
18302
  const sources = [];
18247
18303
  for (const project of config.projects) {
@@ -18250,7 +18306,7 @@ function githubSources(config, options) {
18250
18306
  const normalized = repo.toLowerCase();
18251
18307
  if (seen.has(normalized)) throw new AdapterError("config", "Duplicate GitHub repository in project");
18252
18308
  seen.add(normalized);
18253
- const id = sourceId(project.id, repo);
18309
+ const id = prSourceId(project.id, repo);
18254
18310
  const client = new GithubClient(options.token, options.now, options.fetch);
18255
18311
  const keys = projectKeyRule(project.tracker, project.link, repo);
18256
18312
  const cache = /* @__PURE__ */ new Map();
@@ -18290,9 +18346,6 @@ function githubSources(config, options) {
18290
18346
  function scoped(errors, root) {
18291
18347
  return errors.filter((error) => error.path?.[0] === root);
18292
18348
  }
18293
- function checkAccessDenied(errors) {
18294
- return errors.some((error) => error.type === "FORBIDDEN" && error.path?.includes("statusCheckRollup") === true && error.path.includes("contexts"));
18295
- }
18296
18349
  function requireCheckAccess(errors) {
18297
18350
  if (checkAccessDenied(errors)) throw new AdapterError("auth", "GitHub token lacks Checks read permission");
18298
18351
  }
@@ -19995,7 +20048,7 @@ function queuedBoardRings(wire) {
19995
20048
  }
19996
20049
  /** A single Spur source. State is scoped to this adapter instance, never shared across daemons. */
19997
20050
  function createSpurAdapter(options) {
19998
- const base = new URL(`${options.baseUrl.replace(/\/$/, "")}/`);
20051
+ const base = apiBaseUrl(options.baseUrl);
19999
20052
  const fetchImpl = options.fetch ?? fetch;
20000
20053
  let health = /* @__PURE__ */ new Map();
20001
20054
  let instanceId;
@@ -20249,7 +20302,7 @@ function startAdapters(config, core, options) {
20249
20302
  const entries = [];
20250
20303
  for (const project of config.projects) if (project.tracker.type === "jira") {
20251
20304
  const tracker = project.tracker;
20252
- const id = `jira:${project.id}`;
20305
+ const id = trackerSourceId(project);
20253
20306
  const email = secrets["JIRA_EMAIL"];
20254
20307
  const token = secrets["JIRA_API_TOKEN"];
20255
20308
  entries.push({ adapter: email && token ? createJiraAdapter({
@@ -20266,7 +20319,7 @@ function startAdapters(config, core, options) {
20266
20319
  ...options.jiraSearchMethod === void 0 ? {} : { searchMethod: options.jiraSearchMethod }
20267
20320
  }) : blindSource(id, config.adapters.jira.intervalMs, "Jira credential is missing") });
20268
20321
  } else {
20269
- const id = `github-issues:${project.id}:${project.tracker.repo.toLowerCase()}`;
20322
+ const id = trackerSourceId(project);
20270
20323
  const intervalMs = config.adapters.githubIssues.intervalMs;
20271
20324
  entries.push({
20272
20325
  adapter: githubToken ? createGithubIssuesAdapter({
@@ -20289,7 +20342,7 @@ function startAdapters(config, core, options) {
20289
20342
  reserveRemaining,
20290
20343
  repo
20291
20344
  })));
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") });
20345
+ 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
20346
  const notices = /* @__PURE__ */ new Set();
20294
20347
  const runner = startRunner({
20295
20348
  entries: [...entries, { adapter: createSpurAdapter({
@@ -20321,11 +20374,34 @@ function startAdapters(config, core, options) {
20321
20374
  };
20322
20375
  }
20323
20376
  //#endregion
20377
+ //#region ../gateway-slack/src/wire.ts
20378
+ /**
20379
+ * Readers for untrusted Slack payloads. Each keeps the string semantics its callers had:
20380
+ * `textOf` rejects `''`, while `messageTs` accepts it, so a ref anchor of `''` still matches.
20381
+ */
20382
+ const fieldsWire = z.record(z.string(), z.unknown());
20383
+ const itemsWire = z.array(z.unknown());
20384
+ const textWire = z.string().min(1);
20385
+ const messageTsWire = z.object({ ts: z.string() });
20386
+ /** A non-empty string, else undefined. */
20387
+ function textOf(value) {
20388
+ return textWire.safeParse(value).data;
20389
+ }
20390
+ /** The `ts` string of a message, `''` included, else undefined. */
20391
+ function messageTs(value) {
20392
+ return messageTsWire.safeParse(value).data?.ts;
20393
+ }
20394
+ /** A plain object's fields, else null; arrays are not objects here. */
20395
+ function fieldsOf(value) {
20396
+ return fieldsWire.safeParse(value).data ?? null;
20397
+ }
20398
+ /** An array's items, else null. */
20399
+ function itemsOf(value) {
20400
+ return itemsWire.safeParse(value).data ?? null;
20401
+ }
20402
+ //#endregion
20324
20403
  //#region ../gateway-slack/src/api.ts
20325
20404
  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
20405
  /**
20330
20406
  * Read every page. An incomplete response is unknown, never an empty history. Once `signal`
20331
20407
  * aborts, no further page is requested.
@@ -20352,8 +20428,9 @@ async function readMessages(client, query) {
20352
20428
  ...cursor === void 0 ? {} : { cursor },
20353
20429
  ...latest === void 0 ? {} : { latest }
20354
20430
  });
20355
- if (!Array.isArray(page.messages)) throw new IncompleteHistoryError("missing messages");
20356
- found.push(...page.messages);
20431
+ const messages = itemsOf(page.messages);
20432
+ if (messages === null) throw new IncompleteHistoryError("missing messages");
20433
+ found.push(...messages);
20357
20434
  const nextCursor = page.response_metadata?.next_cursor;
20358
20435
  if (nextCursor) {
20359
20436
  const key = `cursor:${nextCursor}`;
@@ -20364,7 +20441,7 @@ async function readMessages(client, query) {
20364
20441
  continue;
20365
20442
  }
20366
20443
  if (!page.has_more) return found;
20367
- const lastTs = messageTs$1(page.messages.at(-1));
20444
+ const lastTs = messageTs(messages.at(-1));
20368
20445
  if (lastTs === void 0) throw new IncompleteHistoryError("missing pagination timestamp");
20369
20446
  const key = `latest:${lastTs}`;
20370
20447
  if (seen.has(key)) throw new IncompleteHistoryError("repeated page");
@@ -20450,6 +20527,11 @@ function isAlreadyReacted(error) {
20450
20527
  }
20451
20528
  //#endregion
20452
20529
  //#region ../gateway-slack/src/ref.ts
20530
+ const slackRefWire = z.object({
20531
+ channel: z.string(),
20532
+ ts: z.string(),
20533
+ threadTs: z.string()
20534
+ });
20453
20535
  function conversationRef(channel, ts) {
20454
20536
  return conversationRefSchema.parse(JSON.stringify({
20455
20537
  channel,
@@ -20466,16 +20548,7 @@ function messageRef(channel, ts, threadTs) {
20466
20548
  }
20467
20549
  function parseRef(value) {
20468
20550
  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
- };
20551
+ return slackRefWire.safeParse(JSON.parse(value)).data ?? null;
20479
20552
  } catch {
20480
20553
  return null;
20481
20554
  }
@@ -20511,13 +20584,17 @@ function markerId(key) {
20511
20584
  function originMarkerId(key) {
20512
20585
  return blockId(ORIGIN_PREFIX, key);
20513
20586
  }
20587
+ const blockIdWire = z.object({ block_id: z.string() });
20588
+ /** The string `block_id` of each block, in order; anything that is not a block list has none. */
20589
+ function blockIds(blocks) {
20590
+ return (itemsOf(blocks) ?? []).flatMap((block) => {
20591
+ const id = blockIdWire.safeParse(block).data?.block_id;
20592
+ return id === void 0 ? [] : [id];
20593
+ });
20594
+ }
20514
20595
  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;
20596
+ for (const id of blockIds(blocks)) {
20597
+ if (!id.startsWith(MARKER_PREFIX)) continue;
20521
20598
  try {
20522
20599
  return decodeURIComponent(id.slice(5));
20523
20600
  } catch {
@@ -20527,12 +20604,8 @@ function markerFromBlocks(blocks) {
20527
20604
  }
20528
20605
  /** The first part of a multipart root also carries the unsuffixed delivery key. */
20529
20606
  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;
20607
+ for (const id of blockIds(blocks)) {
20608
+ if (!id.startsWith(ORIGIN_PREFIX)) continue;
20536
20609
  try {
20537
20610
  return decodeURIComponent(id.slice(12));
20538
20611
  } catch {
@@ -20747,12 +20820,8 @@ function messageBlocks(text, marker, actions = [], originKey, context = []) {
20747
20820
  }
20748
20821
  //#endregion
20749
20822
  //#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
20823
  function messageMarker(message) {
20754
- if (typeof message !== "object" || message === null || !("blocks" in message)) return void 0;
20755
- return markerFromBlocks(message.blocks);
20824
+ return markerFromBlocks(fieldsOf(message)?.blocks);
20756
20825
  }
20757
20826
  function oldest(at) {
20758
20827
  if (at === void 0 || !Number.isFinite(at.getTime())) return void 0;
@@ -20976,12 +21045,6 @@ function parseCommand(text, commandName) {
20976
21045
  }
20977
21046
  //#endregion
20978
21047
  //#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
21048
  function iso(ts) {
20986
21049
  const at = /* @__PURE__ */ new Date(Number(ts) * 1e3);
20987
21050
  return Number.isFinite(at.getTime()) ? at.toISOString() : void 0;
@@ -21005,10 +21068,10 @@ function interactionRef(channel, user, triggerId) {
21005
21068
  }
21006
21069
  function parseInteractionRef(value) {
21007
21070
  try {
21008
- const parsed = record$1(JSON.parse(value));
21071
+ const parsed = fieldsOf(JSON.parse(value));
21009
21072
  if (parsed === null) return null;
21010
- const channel = string$1(parsed.channel);
21011
- const user = string$1(parsed.user);
21073
+ const channel = textOf(parsed.channel);
21074
+ const user = textOf(parsed.user);
21012
21075
  return channel === void 0 || user === void 0 ? null : {
21013
21076
  channel,
21014
21077
  user
@@ -21018,19 +21081,19 @@ function parseInteractionRef(value) {
21018
21081
  }
21019
21082
  }
21020
21083
  function rootKey(context) {
21021
- return originKeyFromBlocks(record$1(context.root)?.blocks);
21084
+ return originKeyFromBlocks(fieldsOf(context.root)?.blocks);
21022
21085
  }
21023
21086
  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;
21087
+ return message.subtype === "bot_message" || bot.botId !== void 0 && message.bot_id === bot.botId || textOf(message.user) === bot.userId;
21025
21088
  }
21026
21089
  function text(value) {
21027
21090
  return typeof value === "string" ? value : void 0;
21028
21091
  }
21029
21092
  function messageBase(message, context) {
21030
- const ts = string$1(message.ts);
21031
- const user = string$1(message.user);
21093
+ const ts = textOf(message.ts);
21094
+ const user = textOf(message.user);
21032
21095
  if (ts === void 0 || user === void 0 || own(message, context.bot)) return null;
21033
- const threadTs = string$1(message.thread_ts) ?? context.rootTs ?? ts;
21096
+ const threadTs = textOf(message.thread_ts) ?? context.rootTs ?? ts;
21034
21097
  const originKey = rootKey(context);
21035
21098
  return {
21036
21099
  ts,
@@ -21041,15 +21104,15 @@ function messageBase(message, context) {
21041
21104
  }
21042
21105
  /** The same message mapper is used for Socket Mode payloads and thread-history records. */
21043
21106
  function normalizeMessage(channel, payload, context) {
21044
- const source = record$1(payload);
21107
+ const source = fieldsOf(payload);
21045
21108
  if (source === null) return [];
21046
21109
  if (source.subtype === "message_deleted") {
21047
- const deletedTs = string$1(source.deleted_ts);
21048
- const previous = record$1(source.previous_message);
21110
+ const deletedTs = textOf(source.deleted_ts);
21111
+ const previous = fieldsOf(source.previous_message);
21049
21112
  if (own(source, context.bot) || previous !== null && own(previous, context.bot)) return [];
21050
- const priorThreadTs = string$1(previous?.thread_ts);
21113
+ const priorThreadTs = textOf(previous?.thread_ts);
21051
21114
  const priorOriginKey = originKeyFromBlocks(previous?.blocks);
21052
- const rootIsDeleted = deletedTs !== void 0 && string$1(previous?.ts) === deletedTs && (priorThreadTs === deletedTs || priorThreadTs === void 0 && priorOriginKey !== void 0);
21115
+ const rootIsDeleted = deletedTs !== void 0 && textOf(previous?.ts) === deletedTs && (priorThreadTs === deletedTs || priorThreadTs === void 0 && priorOriginKey !== void 0);
21053
21116
  const threadTs = priorThreadTs ?? (rootIsDeleted ? deletedTs : void 0);
21054
21117
  if (deletedTs === void 0 || threadTs === void 0) return [{
21055
21118
  kind: "gap",
@@ -21067,12 +21130,12 @@ function normalizeMessage(channel, payload, context) {
21067
21130
  }];
21068
21131
  }
21069
21132
  const changed = source.subtype === "message_changed";
21070
- const message = changed ? record$1(source.message) : source;
21133
+ const message = changed ? fieldsOf(source.message) : source;
21071
21134
  if (message === null) return [];
21072
21135
  const base = messageBase(message, context);
21073
21136
  const body = text(message.text);
21074
21137
  if (base === null || body === void 0) return [];
21075
- const editedTs = string$1(record$1(message.edited)?.ts);
21138
+ const editedTs = textOf(fieldsOf(message.edited)?.ts);
21076
21139
  const editAt = editedTs === void 0 ? void 0 : iso(editedTs);
21077
21140
  const eventBase = {
21078
21141
  conversation: conversationRef(channel, base.threadTs),
@@ -21110,17 +21173,17 @@ function normalizeMessage(channel, payload, context) {
21110
21173
  }
21111
21174
  /** Actions and commands share the same stable trigger identity as their Slack retry. */
21112
21175
  function normalizeInteraction(type, payload, channels, root, commandName = DEFAULT_SLACK_COMMAND) {
21113
- const body = record$1(payload);
21176
+ const body = fieldsOf(payload);
21114
21177
  if (body === null) return [];
21115
- const triggerId = string$1(body.trigger_id);
21178
+ const triggerId = textOf(body.trigger_id);
21116
21179
  if (triggerId === void 0) return [];
21117
- const user = string$1(record$1(body.user)?.id) ?? string$1(body.user_id);
21180
+ const user = textOf(fieldsOf(body.user)?.id) ?? textOf(body.user_id);
21118
21181
  if (user === void 0) return [];
21119
21182
  const author = userIdSchema.parse(user);
21120
21183
  if (type === "slash_commands") {
21121
- const name = string$1(body.command);
21184
+ const name = textOf(body.command);
21122
21185
  if (name === void 0) return [];
21123
- const channel = string$1(body.channel_id);
21186
+ const channel = textOf(body.channel_id);
21124
21187
  if (channel === void 0) return [];
21125
21188
  return [{
21126
21189
  kind: "command",
@@ -21135,14 +21198,13 @@ function normalizeInteraction(type, payload, channels, root, commandName = DEFAU
21135
21198
  }];
21136
21199
  }
21137
21200
  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);
21201
+ const channel = textOf(fieldsOf(body.channel)?.id);
21202
+ const message = fieldsOf(body.message);
21203
+ const ts = textOf(message?.ts);
21204
+ const threadTs = textOf(message?.thread_ts) ?? ts;
21205
+ const actionId = textOf(fieldsOf(itemsOf(body.actions)?.[0])?.action_id);
21144
21206
  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);
21207
+ const originKey = originKeyFromBlocks(root === void 0 ? message?.blocks : fieldsOf(root)?.blocks);
21146
21208
  return [{
21147
21209
  kind: "action",
21148
21210
  dedupeKey: `slack:${triggerId}`,
@@ -21159,12 +21221,6 @@ function normalizeInteraction(type, payload, channels, root, commandName = DEFAU
21159
21221
  }
21160
21222
  //#endregion
21161
21223
  //#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
21224
  /** Milliseconds of a Slack ts, read from its digits so float error cannot shift the millisecond. */
21169
21225
  function tsMillis(ts) {
21170
21226
  const [seconds = "", fraction = ""] = ts.split(".");
@@ -21262,16 +21318,16 @@ async function* recoverThreads(client, request, botIdentity, now) {
21262
21318
  throw error;
21263
21319
  }
21264
21320
  if (history === ABORTED) return;
21265
- const root = history.find((message) => string(record(message)?.ts) === addressed.threadTs);
21321
+ const root = history.find((message) => messageTs(message) === addressed.threadTs);
21266
21322
  if (root === void 0) {
21267
21323
  yield gap(conversation.ref);
21268
21324
  continue;
21269
21325
  }
21270
21326
  const after = conversation.after === void 0 ? null : parseRef(conversation.after);
21271
21327
  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);
21328
+ 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
21329
  for (const message of history) {
21274
- const source = record(message);
21330
+ const source = fieldsOf(message);
21275
21331
  if (source === null) continue;
21276
21332
  const events = normalizeMessage(addressed.channel, source, {
21277
21333
  bot,
@@ -21282,21 +21338,15 @@ async function* recoverThreads(client, request, botIdentity, now) {
21282
21338
  const ts = parseRef(event.message)?.ts;
21283
21339
  if (inInterval(ts, from, until) && (anchor === void 0 || Number(ts) > Number(anchor))) yield event;
21284
21340
  } else if (event.kind === "message_edited") {
21285
- if (inInterval(string(record(source.edited)?.ts), from, until)) yield event;
21341
+ if (inInterval(messageTs(source.edited), from, until)) yield event;
21286
21342
  } else if (event.kind === "message_deleted") {
21287
- if (inInterval(string(source.event_ts), from, until)) yield event;
21343
+ if (inInterval(z.string().safeParse(source.event_ts).data, from, until)) yield event;
21288
21344
  }
21289
21345
  }
21290
21346
  }
21291
21347
  }
21292
21348
  //#endregion
21293
21349
  //#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
21350
  async function rootFor(client, channel, threadTs) {
21301
21351
  const root = (await client.conversations.replies({
21302
21352
  channel,
@@ -21323,25 +21373,25 @@ function createSocket(api, config, botIdentity) {
21323
21373
  }
21324
21374
  async function handle(envelope) {
21325
21375
  if (stopping || sink === void 0) return;
21326
- const type = value(envelope.type);
21327
- const body = object$1(envelope.body);
21376
+ const type = textOf(envelope.type);
21377
+ const body = fieldsOf(envelope.body);
21328
21378
  if (type === void 0 || body === null) return;
21329
21379
  let events = [];
21330
21380
  if (type === "events_api") {
21331
- const event = object$1(body.event);
21332
- const eventType = value(event?.type);
21333
- const channel = value(event?.channel);
21381
+ const event = fieldsOf(body.event);
21382
+ const eventType = textOf(event?.type);
21383
+ const channel = textOf(event?.channel);
21334
21384
  if (event !== null && channel !== void 0 && (eventType === "message" || eventType === "app_mention")) {
21335
21385
  const bot = await botIdentity();
21336
21386
  const message = eventType === "app_mention" ? {
21337
21387
  ...event,
21338
21388
  type: "message"
21339
21389
  } : 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);
21390
+ const nested = fieldsOf(message.message);
21391
+ const previous = fieldsOf(message.previous_message);
21392
+ const threadTs = textOf(message.thread_ts) ?? textOf(nested?.thread_ts) ?? textOf(previous?.thread_ts);
21393
+ const messageTs = textOf(message.ts) ?? textOf(nested?.ts);
21394
+ const deletedRoot = message.subtype === "message_deleted" && threadTs === textOf(message.deleted_ts);
21345
21395
  events = normalizeMessage(channel, message, {
21346
21396
  bot,
21347
21397
  root: threadTs === void 0 || threadTs === messageTs || deletedRoot ? message : await rootFor(api, channel, threadTs),
@@ -21349,10 +21399,10 @@ function createSocket(api, config, botIdentity) {
21349
21399
  });
21350
21400
  }
21351
21401
  } 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;
21402
+ const actionMessage = fieldsOf(body.message);
21403
+ const channel = textOf(fieldsOf(body.channel)?.id);
21404
+ const ts = textOf(actionMessage?.ts);
21405
+ const threadTs = textOf(actionMessage?.thread_ts) ?? ts;
21356
21406
  const root = channel !== void 0 && threadTs !== void 0 && threadTs !== ts ? await rootFor(api, channel, threadTs) : actionMessage;
21357
21407
  events = normalizeInteraction(type, body, config.channels, root);
21358
21408
  } else if (type === "slash_commands") events = normalizeInteraction(type, body, config.channels, void 0, config.command);
@@ -21536,7 +21586,10 @@ function createBoardModules(ctxFor, options = {}) {
21536
21586
  const core = options.core ?? createObservationCore({
21537
21587
  store: coreCtx.store,
21538
21588
  config: coreCtx.config,
21539
- clock: coreCtx.clock
21589
+ clock: coreCtx.clock,
21590
+ warn: (fields, message) => {
21591
+ coreCtx.log.warn(fields, message);
21592
+ }
21540
21593
  });
21541
21594
  const tick = options.tick ?? tickBoard;
21542
21595
  const boardCore = createJob({
@@ -21545,7 +21598,8 @@ function createBoardModules(ctxFor, options = {}) {
21545
21598
  store: coreCtx.store,
21546
21599
  config: coreCtx.config,
21547
21600
  clock: coreCtx.clock,
21548
- completeSince: core.completeSince
21601
+ completeSince: core.completeSince,
21602
+ warnSkipped: core.warnSkipped
21549
21603
  });
21550
21604
  options.onTick?.();
21551
21605
  },
@@ -21623,10 +21677,11 @@ const RETRYABLE_4XX = /* @__PURE__ */ new Set([
21623
21677
  425,
21624
21678
  429
21625
21679
  ]);
21680
+ const spurErrorWire = z.object({ error: z.string() });
21626
21681
  /** The request Spur's own `spur send` makes; the doctor probe sends the same one. */
21627
21682
  function spurSendRequest(baseUrl, session, text) {
21628
21683
  return {
21629
- url: new URL(`sessions/${encodeURIComponent(session)}/send`, new URL(`${baseUrl.replace(/\/$/, "")}/`)),
21684
+ url: new URL(`sessions/${encodeURIComponent(session)}/send`, apiBaseUrl(baseUrl)),
21630
21685
  init: {
21631
21686
  method: "POST",
21632
21687
  headers: { "Content-Type": "application/json" },
@@ -21637,9 +21692,8 @@ function spurSendRequest(baseUrl, session, text) {
21637
21692
  /** The `error` string of a Spur error body, cut to a bounded length; null when unreadable. */
21638
21693
  async function spurErrorText(response) {
21639
21694
  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;
21695
+ const parsed = spurErrorWire.safeParse(await response.json());
21696
+ return parsed.success ? parsed.data.error.slice(0, ERROR_TEXT_LIMIT) : null;
21643
21697
  } catch {
21644
21698
  return null;
21645
21699
  }
@@ -21678,6 +21732,7 @@ const SPUR_SEND_FIX = "The Spur API at adapters.spur.baseUrl did not accept a do
21678
21732
  const GITHUB_FIX = "Check the GitHub token and repository access.";
21679
21733
  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
21734
  const GITHUB_TEAMS_FIX = "Use a classic GitHub personal access token with the repo and read:org scopes to read requested review teams.";
21735
+ const GITHUB_THROTTLED_FIX = "GitHub is rate limiting this token, so access was not checked; rerun board doctor after the limit resets.";
21681
21736
  const GITHUB_ORG_READ_SCOPES = /* @__PURE__ */ new Set([
21682
21737
  "read:org",
21683
21738
  "write:org",
@@ -21696,18 +21751,6 @@ const GITHUB_PROBE = `query DoctorGithubPermissions($owner: String!, $repo: Stri
21696
21751
  } } }
21697
21752
  }
21698
21753
  }`;
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
21754
  async function deadlineCall(ctx, deadlineMs, name, failure, call) {
21712
21755
  const controller = new AbortController();
21713
21756
  const deadline = setTimeout(() => {
@@ -21732,33 +21775,90 @@ async function deadlineCall(ctx, deadlineMs, name, failure, call) {
21732
21775
  clearTimeout(deadline);
21733
21776
  }
21734
21777
  }
21735
- async function githubGraphql(ctx, fetcher, deadlineMs, token, repo) {
21736
- const [owner, name] = repo.split("/");
21737
- if (!owner || !name) return null;
21778
+ function githubCall(ctx, deadlineMs, send, json) {
21738
21779
  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
- });
21780
+ const response = await send(signal);
21781
+ if (response.ok) return {
21782
+ response,
21783
+ failure: null,
21784
+ body: json ? await response.json() : null
21785
+ };
21786
+ const body = await response.text().catch(() => void 0);
21755
21787
  return {
21756
21788
  response,
21757
- body: response.ok ? await response.json() : null
21789
+ failure: classifyHttpFailure({
21790
+ status: response.status,
21791
+ headers: response.headers,
21792
+ body
21793
+ }, ctx.clock.now()),
21794
+ body: null
21758
21795
  };
21759
21796
  });
21760
21797
  }
21761
- const FIX_MAX = 300;
21798
+ function githubHeaders(token) {
21799
+ return {
21800
+ Authorization: `Bearer ${token}`,
21801
+ Accept: "application/vnd.github+json"
21802
+ };
21803
+ }
21804
+ function githubGraphql(ctx, fetcher, deadlineMs, token, repo) {
21805
+ const [owner, name] = repo.split("/");
21806
+ if (!owner || !name) return Promise.resolve(null);
21807
+ return githubCall(ctx, deadlineMs, (signal) => fetcher("https://api.github.com/graphql", {
21808
+ method: "POST",
21809
+ headers: {
21810
+ ...githubHeaders(token),
21811
+ "Content-Type": "application/json"
21812
+ },
21813
+ body: JSON.stringify({
21814
+ query: GITHUB_PROBE,
21815
+ variables: {
21816
+ owner,
21817
+ repo: name
21818
+ }
21819
+ }),
21820
+ signal
21821
+ }), true);
21822
+ }
21823
+ const githubFail = (fix) => ({
21824
+ status: "fail",
21825
+ fix
21826
+ });
21827
+ const githubHttpFinding = (failure) => failure.kind === "throttled" ? {
21828
+ status: "warning",
21829
+ fix: GITHUB_THROTTLED_FIX
21830
+ } : githubFail(GITHUB_FIX);
21831
+ const githubDataWire = z.object({ repository: z.object({ pullRequests: z.object({ nodes: z.array(z.unknown()) }) }) });
21832
+ async function githubRepoFinding(ctx, fetcher, deadlineMs, token, repo) {
21833
+ const rest = await githubCall(ctx, deadlineMs, (signal) => fetcher(`https://api.github.com/repos/${repo}`, {
21834
+ headers: githubHeaders(token),
21835
+ signal
21836
+ }), false);
21837
+ if (rest === null) return githubFail(GITHUB_FIX);
21838
+ if (rest.failure !== null) return githubHttpFinding(rest.failure);
21839
+ const probe = await githubGraphql(ctx, fetcher, deadlineMs, token, repo);
21840
+ if (probe === null) return githubFail(GITHUB_FIX);
21841
+ if (probe.failure !== null) return githubHttpFinding(probe.failure);
21842
+ const envelope = graphEnvelopeWire.safeParse(probe.body);
21843
+ if (!envelope.success) return githubFail(GITHUB_FIX);
21844
+ const errors = envelope.data.errors ?? [];
21845
+ const failure = graphqlFailure(errors, GITHUB_PROBE, probe.response.headers, ctx.clock.now());
21846
+ if (failure?.kind === "throttled") return githubHttpFinding(failure);
21847
+ if (failure !== null) return githubFail(errors.some((error) => teamScopeDenied(error, GITHUB_PROBE)) ? GITHUB_TEAMS_FIX : GITHUB_FIX);
21848
+ if (checkAccessDenied(errors)) return githubFail(GITHUB_CHECKS_FIX);
21849
+ if (errors.length > 0) return githubFail(GITHUB_FIX);
21850
+ if (!githubDataWire.safeParse(envelope.data.data).success) return githubFail(GITHUB_FIX);
21851
+ const scopes = rest.response.headers.get("x-oauth-scopes");
21852
+ if (scopes !== null && !scopes.split(",").some((scope) => GITHUB_ORG_READ_SCOPES.has(scope.trim()))) return githubFail(GITHUB_TEAMS_FIX);
21853
+ return null;
21854
+ }
21855
+ function githubCheck(findings) {
21856
+ const id = "github.credentials";
21857
+ const failed = findings.find((finding) => finding?.status === "fail");
21858
+ if (failed) return check(id, false, failed.fix);
21859
+ const throttled = findings.find((finding) => finding?.status === "warning");
21860
+ return throttled ? warning(id, throttled.fix) : check(id, true, GITHUB_FIX);
21861
+ }
21762
21862
  const BRANCH_MAX = 40;
21763
21863
  const NAMED_PRS = 3;
21764
21864
  const LINK_RULES_TAIL = "Change projects[].link to the repo's branch and PR title rules.";
@@ -21830,12 +21930,12 @@ function linkSegment(outcome) {
21830
21930
  function fitFix(segments, tail, fallback) {
21831
21931
  for (const branches of [true, false]) {
21832
21932
  const full = `${segments.map((segment) => segment.text(branches)).join(". ")}.${tail}`;
21833
- if (full.length <= FIX_MAX) return full;
21933
+ if (full.length <= 300) return full;
21834
21934
  }
21835
21935
  const texts = segments.map((segment) => segment.text(false));
21836
21936
  for (let kept = texts.length - 1; kept > 0; kept -= 1) {
21837
21937
  const text = `${texts.slice(0, kept).join(". ")}; and ${String(texts.length - kept)} more projects.${tail}`;
21838
- if (text.length <= FIX_MAX) return text;
21938
+ if (text.length <= 300) return text;
21839
21939
  }
21840
21940
  return fallback;
21841
21941
  }
@@ -21919,24 +22019,23 @@ async function request(ctx, fetcher, deadlineMs, id, url, init = {}) {
21919
22019
  return null;
21920
22020
  }
21921
22021
  }
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;
22022
+ const slackOkWire = z.object({ ok: z.literal(true) });
22023
+ const slackMemberWire = z.object({
22024
+ ok: z.literal(true),
22025
+ channel: z.object({ is_member: z.literal(true) })
22026
+ });
22027
+ const slackManifestWire = z.object({
22028
+ ok: z.literal(true),
22029
+ manifest: z.object({ features: z.object({ slash_commands: z.array(z.unknown()) }) })
22030
+ });
22031
+ const slashCommandWire = z.object({ command: z.string() });
22032
+ async function slackBody(response, wire) {
22033
+ if (response === null || !response.ok) return null;
21933
22034
  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;
22035
+ const parsed = wire.safeParse(await response.json());
22036
+ return parsed.success ? parsed.data : null;
21938
22037
  } catch {
21939
- return false;
22038
+ return null;
21940
22039
  }
21941
22040
  }
21942
22041
  /** Bounded daemon-side checks; no response body or exception text leaves this module. */
@@ -21963,32 +22062,11 @@ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch, { deadlineM
21963
22062
  checks.push(check("jira.credentials", jiraOk, "Check the Jira account, API token, and project access."));
21964
22063
  const githubToken = secrets["GITHUB_TOKEN"];
21965
22064
  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));
22065
+ const githubFindings = githubToken === void 0 ? [githubFail(GITHUB_FIX)] : await Promise.all([...githubRepos].map((repo) => githubRepoFinding(ctx, fetcher, deadlineMs, githubToken, repo)));
22066
+ checks.push(githubCheck(githubFindings));
21989
22067
  checks.push(linkRulesCheck(await linkSamples));
21990
22068
  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)]);
22069
+ 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
22070
  checks.push(check("spur.api", spur?.ok === true, "Start or correct the configured Spur API."));
21993
22071
  const spurSendOk = spurSend?.status === 404 && ((await spurErrorText(spurSend))?.startsWith("Session not found") ?? false);
21994
22072
  if (spurSend !== null && spurSend.status !== 404) await spurSend.body?.cancel().catch(() => void 0);
@@ -21997,40 +22075,33 @@ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch, { deadlineM
21997
22075
  else {
21998
22076
  const botToken = secrets["SLACK_BOT_TOKEN"];
21999
22077
  const slackHeaders = botToken ? { Authorization: `Bearer ${botToken}` } : {};
22000
- const slackBase = `${(secrets["SLACK_API_URL"] || "https://slack.com/api/").replace(/\/$/, "")}/`;
22078
+ const slackBase = apiBaseUrl(secrets["SLACK_API_URL"] || "https://slack.com/api/");
22001
22079
  const auth = botToken ? await request(ctx, fetcher, deadlineMs, "slack.auth", new URL("auth.test", slackBase), {
22002
22080
  method: "POST",
22003
22081
  headers: slackHeaders
22004
22082
  }) : null;
22005
- const authorized = await slackOk(auth);
22083
+ const authorized = await slackBody(auth, slackOkWire) !== null;
22006
22084
  const granted = new Set(auth?.headers.get("x-oauth-scopes")?.split(",").map((scope) => scope.trim()).filter(Boolean) ?? []);
22007
22085
  const missingScopes = SLACK_BOT_SCOPES.filter((scope) => !granted.has(scope));
22008
22086
  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
22087
  for (const [id, channel] of [["slack.orchestrators_member", config.slack.channels.orchestrators], ["slack.feed_member", config.slack.channels.feed]]) {
22010
22088
  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."));
22089
+ checks.push(check(id, await slackBody(response, slackMemberWire) !== null, "Invite the bot to the configured channel ID."));
22012
22090
  }
22013
22091
  const configToken = secrets["SLACK_APP_CONFIG_TOKEN"];
22014
22092
  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
22093
  else {
22016
- const response = await request(ctx, fetcher, deadlineMs, "slack.command", new URL("apps.manifest.export", slackBase), {
22094
+ const commands = (await slackBody(await request(ctx, fetcher, deadlineMs, "slack.command", new URL("apps.manifest.export", slackBase), {
22017
22095
  method: "POST",
22018
22096
  headers: {
22019
22097
  Authorization: `Bearer ${configToken}`,
22020
22098
  "Content-Type": "application/json"
22021
22099
  },
22022
22100
  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 {}
22101
+ }), slackManifestWire))?.manifest.features.slash_commands.flatMap((entry) => {
22102
+ const parsed = slashCommandWire.safeParse(entry);
22103
+ return parsed.success ? [parsed.data.command] : [];
22104
+ }) ?? null;
22034
22105
  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
22106
  }
22036
22107
  }
@@ -22047,19 +22118,21 @@ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch, { deadlineM
22047
22118
  //#endregion
22048
22119
  //#region ../daemon/src/http-module.ts
22049
22120
  const SESSION_TIMEOUT_MS = 5e3;
22121
+ const sessionDetailWire = z.object({
22122
+ id: z.string(),
22123
+ project: z.string().min(1),
22124
+ status: z.enum(SESSION_STATUSES)
22125
+ });
22050
22126
  /** Fetch one session after a snapshot miss; 404 is a confirmed unknown session. */
22051
22127
  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) });
22128
+ const response = await fetcher(new URL(`sessions/${encodeURIComponent(id)}`, apiBaseUrl(baseUrl)), { signal: AbortSignal.timeout(SESSION_TIMEOUT_MS) });
22054
22129
  if (response.status === 404) return null;
22055
22130
  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");
22131
+ const detail = sessionDetailWire.safeParse(await response.json());
22132
+ if (!detail.success || detail.data.id !== id) throw new Error("Invalid session detail response");
22060
22133
  return {
22061
- project: record["project"],
22062
- status: record["status"]
22134
+ project: detail.data.project,
22135
+ status: detail.data.status
22063
22136
  };
22064
22137
  }
22065
22138
  /** Start and close the API as a daemon module, with runtime ports from its context. */
@@ -22131,7 +22204,10 @@ function createInboundModule(ctx, gateway, registry = {}) {
22131
22204
  gateway,
22132
22205
  config: ctx.config,
22133
22206
  clock: ctx.clock,
22134
- registry
22207
+ registry,
22208
+ warn: (fields, message) => {
22209
+ ctx.log.warn(fields, message);
22210
+ }
22135
22211
  });
22136
22212
  const recovery = createJob({
22137
22213
  run: () => ctx.logCall("inbound.recover", () => inbound.recover()),
@@ -22375,6 +22451,9 @@ function createDaemonModules(ctxFor, ports = {}) {
22375
22451
  store: board.store,
22376
22452
  config: board.config,
22377
22453
  clock: board.clock,
22454
+ warn: (fields, message) => {
22455
+ board.log.warn(fields, message);
22456
+ },
22378
22457
  ...ports.productVersion === void 0 ? {} : { productVersion: ports.productVersion }
22379
22458
  });
22380
22459
  const ctx = ctxFor("gateway-slack");
@@ -22489,20 +22568,24 @@ function createDaemonModules(ctxFor, ports = {}) {
22489
22568
  tick: boardModules.tick
22490
22569
  };
22491
22570
  }
22571
+ const itemInput = z.object({ item: z.string() });
22492
22572
  function isItemInput(input) {
22493
- return typeof input === "object" && input !== null && "item" in input && typeof input.item === "string";
22573
+ return itemInput.safeParse(input).success;
22494
22574
  }
22495
22575
  //#endregion
22496
22576
  //#region ../daemon/src/main.ts
22497
22577
  const KEEPALIVE_MS = 36e5;
22578
+ const packedManifestWire = z.object({ name: z.literal("spur-board") });
22579
+ const versionWire = z.object({ version: z.string() });
22498
22580
  /** Resolve the publishable package, both from source and from the packed daemon. */
22499
22581
  function publishedVersion() {
22500
22582
  const packed = new URL("../package.json", import.meta.url);
22501
22583
  const source = new URL("../../cli/package.json", import.meta.url);
22502
22584
  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;
22585
+ const manifest = packedManifestWire.safeParse(packedManifest).success ? packedManifest : JSON.parse(readFileSync(source, "utf8"));
22586
+ const parsed = versionWire.safeParse(manifest);
22587
+ if (!parsed.success) throw new Error("Invalid spur-board package version.");
22588
+ return parsed.data.version;
22506
22589
  }
22507
22590
  /** The real process. Handlers are attached when runDaemon registers them, not before. */
22508
22591
  function processPort() {