spur-board 0.16.2 → 0.17.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/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { G as SLACK_BOT_SCOPES, P as ERRORS, U as configSchema, W as requiredSecretKeys, l as roleCanUseOperation, r as SYSTEMD_SERVICE_SETTINGS, u as OPERATIONS } from "./src-ep5scuVt.mjs";
2
- import { a as errorExitCode, i as CliError, n as requestOperation, o as renderCliError, r as requestTokenEnrollment, s as escapeTerminalControls } from "./client-CwKmG23X.mjs";
3
- import { a as memoryVerdictCache, c as loadEnrollmentConfig, i as fileVerdictCache, l as readConfiguredPort, n as cliPackageVersion, o as configFile, s as loadClientConfig, t as checkCatalog, u as resolveDaemonAddress } from "./config-CXDupHSC.mjs";
1
+ import { G as SLACK_BOT_SCOPES, P as ERRORS, U as configSchema, W as requiredSecretKeys, l as roleCanUseOperation, r as SYSTEMD_SERVICE_SETTINGS, u as OPERATIONS } from "./src-vzl2nFf6.mjs";
2
+ import { a as errorExitCode, i as CliError, n as requestOperation, o as renderCliError, r as requestTokenEnrollment, s as escapeTerminalControls } from "./client-Swp5TBku.mjs";
3
+ import { a as memoryVerdictCache, c as loadEnrollmentConfig, i as fileVerdictCache, l as readConfiguredPort, n as cliPackageVersion, o as configFile, s as loadClientConfig, t as checkCatalog, u as resolveDaemonAddress } from "./config-C1ly8wCm.mjs";
4
4
  import { createHash, randomBytes, randomUUID } from "node:crypto";
5
5
  import { chmodSync, closeSync, constants, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, statSync, unlinkSync, writeFileSync } from "node:fs";
6
6
  import { homedir, hostname, userInfo } from "node:os";
@@ -1,4 +1,4 @@
1
- import { F as errorContextSchema, I as errorEnvelopeSchema, L as successEnvelopeSchema, P as ERRORS, f as renderJsonError } from "./src-ep5scuVt.mjs";
1
+ import { F as errorContextSchema, I as errorEnvelopeSchema, L as successEnvelopeSchema, P as ERRORS, f as renderJsonError } from "./src-vzl2nFf6.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { z } from "zod";
4
4
  import { request } from "node:http";
package/dist/client.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { n as requestOperation, r as requestTokenEnrollment, t as fetchCatalogVersion } from "./client-CwKmG23X.mjs";
1
+ import { n as requestOperation, r as requestTokenEnrollment, t as fetchCatalogVersion } from "./client-Swp5TBku.mjs";
2
2
  export { fetchCatalogVersion, requestOperation, requestTokenEnrollment };
@@ -1,5 +1,5 @@
1
- import { R as DEFAULT_HTTP_PORT, U as configSchema, c as buildCatalogSnapshot, u as OPERATIONS } from "./src-ep5scuVt.mjs";
2
- import { i as CliError, t as fetchCatalogVersion } from "./client-CwKmG23X.mjs";
1
+ import { R as DEFAULT_HTTP_PORT, U as configSchema, c as buildCatalogSnapshot, u as OPERATIONS } from "./src-vzl2nFf6.mjs";
2
+ import { i as CliError, t as fetchCatalogVersion } from "./client-Swp5TBku.mjs";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
5
5
  import { homedir } from "node:os";
package/dist/daemon.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { A as errorCodeOf, C as SESSION_STATUSES, D as ticketFactsSchema, E as sessionFactsSchema, G as SLACK_BOT_SCOPES, H as RESERVED_PROJECT, L as successEnvelopeSchema, M as parseRef$1, N as taskKeySchema, O as actorIdSchema, P as ERRORS, S as SESSION_HEALTH_STATES, T as prRefSchema, U as configSchema, V as DEFAULT_SLACK_COMMAND, W as requiredSecretKeys, _ as interactionRefSchema, a as batchSchema, b as EVENT_KINDS, c as buildCatalogSnapshot, d as renderHttpProblem, g as inboundEventSchema, h as conversationRefSchema, i as AdapterError, j as parseActorId, k as encodeActorId, l as roleCanUseOperation, m as SPACE_IDS, n as BOARD_TICK_MS, o as entityRefSchema, s as sourceCursorSchema, t as assertNever, u as OPERATIONS, v as messageRefSchema, w as prFactsSchema, x as eventPayloadSchemas, y as userIdSchema, z as DEFAULT_LINK } from "./src-ep5scuVt.mjs";
1
+ import { A as errorCodeOf, C as SESSION_STATUSES, D as ticketFactsSchema, E as sessionFactsSchema, G as SLACK_BOT_SCOPES, H as RESERVED_PROJECT, L as successEnvelopeSchema, M as parseRef$1, N as taskKeySchema, O as actorIdSchema, P as ERRORS, S as SESSION_HEALTH_STATES, T as prRefSchema, U as configSchema, V as DEFAULT_SLACK_COMMAND, W as requiredSecretKeys, _ as interactionRefSchema, a as batchSchema, b as EVENT_KINDS, c as buildCatalogSnapshot, d as renderHttpProblem, g as inboundEventSchema, h as conversationRefSchema, i as AdapterError, j as parseActorId, k as encodeActorId, l as roleCanUseOperation, m as SPACE_IDS, n as BOARD_TICK_MS, o as entityRefSchema, s as sourceCursorSchema, t as assertNever, u as OPERATIONS, v as messageRefSchema, w as prFactsSchema, x as eventPayloadSchemas, y as userIdSchema, z as DEFAULT_LINK } from "./src-vzl2nFf6.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { closeSync, existsSync, fstatSync, ftruncateSync, mkdirSync, openSync, readFileSync, readdirSync, writeSync } from "node:fs";
@@ -9050,6 +9050,50 @@ async function restartNotification(trx, sourceKey, at) {
9050
9050
  next_at: at.toISOString()
9051
9051
  }).where("source_key", "=", sourceKey).where("acked_at", "is", null).where("exhausted_at", "is not", null).returning("id").executeTakeFirst() === void 0) throw new CommandError("retry_not_applicable", "The doorbell was read or is still ringing; close the item instead.");
9052
9052
  }
9053
+ /**
9054
+ * Ends a ring Spur will not take (a permanent rejection, or no answer for the retry window): its
9055
+ * notification stops ringing, the operator gets an item and `doorbell_undelivered` is journalled.
9056
+ * The operator's Retry on the item restarts the series (`restartNotification`). An inbound author
9057
+ * ring has no notification: it ends like an author found unavailable at enqueue.
9058
+ */
9059
+ async function ringUndelivered(trx, input) {
9060
+ const { at, reason } = input;
9061
+ if (input.notificationId === void 0) {
9062
+ const task = await ringTask(trx, void 0, input.dedupeKey);
9063
+ if (task === void 0) return;
9064
+ await emit(trx, "doorbell_undelivered", task.project, task.id, at.toISOString(), {
9065
+ doorbell: input.dedupeKey,
9066
+ reason
9067
+ });
9068
+ await raiseItem(trx, {
9069
+ itemKey: `doorbell:unavailable:${input.dedupeKey}`,
9070
+ kind: "answer_author_unavailable",
9071
+ text: `Answer author unavailable: ${reason}`,
9072
+ url: taskUrl(task, input.config),
9073
+ taskId: task.id,
9074
+ blockId: null,
9075
+ at
9076
+ });
9077
+ return;
9078
+ }
9079
+ const n = await trx.selectFrom("notification").selectAll().where("id", "=", input.notificationId).executeTakeFirst();
9080
+ if (n === void 0 || n.acked_at !== null || n.exhausted_at !== null) return;
9081
+ const task = await trx.selectFrom("task").selectAll().where("id", "=", n.task_id).executeTakeFirstOrThrow();
9082
+ await trx.updateTable("notification").set({ exhausted_at: at.toISOString() }).where("id", "=", n.id).execute();
9083
+ await raiseItem(trx, {
9084
+ itemKey: exhaustedItemKey(n),
9085
+ kind: exhaustedItemKind(n),
9086
+ text: n.kind === "answer" ? `Answer to block B${String(n.block_id)} on ${task.key} was not delivered: ${reason}` : `worker ${input.session} did not get block B${String(n.block_id)} on ${task.key}: ${reason}`,
9087
+ url: taskUrl(task, input.config),
9088
+ taskId: task.id,
9089
+ blockId: n.block_id,
9090
+ at
9091
+ });
9092
+ await journal$2(trx, n, "doorbell_undelivered", {
9093
+ doorbell: `N${String(n.id)}`,
9094
+ reason
9095
+ }, at);
9096
+ }
9053
9097
  /** Reconcile due semantic notifications in the sender's claim transaction. */
9054
9098
  async function reconcileDoorbells(trx, at, config) {
9055
9099
  const due = await trx.selectFrom("notification").innerJoin("task", "task.id", "notification.task_id").selectAll("notification").where("task.membership", "!=", "archived").where("notification.acked_at", "is", null).where("notification.exhausted_at", "is", null).where("notification.next_at", "<=", at.toISOString()).orderBy("notification.id").execute();
@@ -9719,7 +9763,7 @@ async function archiveTask(trx, input) {
9719
9763
  await trx.updateTable("outbox").set({
9720
9764
  state: "dead",
9721
9765
  last_error: "superseded"
9722
- }).where("kind", "=", "doorbell").where("state", "in", ["pending", "post_failed"]).where("uncertain", "=", 0).where((eb) => eb.or([eb("id", "in", eb.selectFrom("notification").select("last_outbox_id").where("task_id", "=", task.id).where("last_outbox_id", "is not", null)), ...comments.map((comment) => eb("dedupe_key", "like", `doorbell:comment:${String(comment.id)}:%`))])).execute();
9766
+ }).where("kind", "=", "doorbell").where("state", "in", ["pending", "post_failed"]).where((eb) => eb.or([eb("id", "in", eb.selectFrom("notification").select("last_outbox_id").where("task_id", "=", task.id).where("last_outbox_id", "is not", null)), ...comments.map((comment) => eb("dedupe_key", "like", `doorbell:comment:${String(comment.id)}:%`))])).execute();
9723
9767
  await trx.updateTable("task").set({
9724
9768
  membership: "archived",
9725
9769
  archive_reason: reason,
@@ -9844,6 +9888,13 @@ function orderItems(items) {
9844
9888
  }
9845
9889
  //#endregion
9846
9890
  //#region ../core/src/app/sender.ts
9891
+ /**
9892
+ * Spur refused a doorbell for good (a permanent 4xx): the sender stops ringing and ends the ring
9893
+ * instead of retrying it. Any other error from `send` is retried.
9894
+ */
9895
+ var SpurRejectedError = class extends Error {
9896
+ name = "SpurRejectedError";
9897
+ };
9847
9898
  /** 1 msg/s per space: a platform limit, not an operator setting. */
9848
9899
  const SPACE_INTERVAL_MS = 1e3;
9849
9900
  const RETRY_WINDOW_MS = 30 * 6e4;
@@ -9966,6 +10017,28 @@ async function requeuePostFailed(trx, ids, nowIso) {
9966
10017
  }
9967
10018
  return failed.length;
9968
10019
  }
10020
+ /**
10021
+ * Returns every `in_flight` row to `pending`: one whose send never started gives its attempt
10022
+ * back; one whose send started may be out, so it goes again at once as uncertain. Its comment
10023
+ * goes back to `pending`. Only a crash or a failed earlier tick leaves a row `in_flight`.
10024
+ */
10025
+ async function releaseOrphans(trx, nowIso) {
10026
+ const rows = await trx.selectFrom("outbox").select(["kind", "payload"]).where("state", "=", "in_flight").execute();
10027
+ if (rows.length === 0) return;
10028
+ await trx.updateTable("outbox").set((eb) => ({
10029
+ state: "pending",
10030
+ attempts: eb("attempts", "-", 1)
10031
+ })).where("state", "=", "in_flight").where("attempt_started", "=", 0).execute();
10032
+ await trx.updateTable("outbox").set({
10033
+ state: "pending",
10034
+ uncertain: 1,
10035
+ next_at: nowIso
10036
+ }).where("state", "=", "in_flight").where("attempt_started", "=", 1).execute();
10037
+ for (const row of rows) {
10038
+ const body = parseBody(row);
10039
+ if (typeof body !== "string") await setComment(trx, body, { delivery_state: "pending" });
10040
+ }
10041
+ }
9969
10042
  function backoff(attempts) {
9970
10043
  return Math.min(1e3 * 2 ** Math.max(attempts - 1, 0), MAX_BACKOFF_MS$1);
9971
10044
  }
@@ -10044,11 +10117,13 @@ function createSender(options) {
10044
10117
  await trx.updateTable("outbox").set({ first_attempt_at: null }).where("state", "in", ["pending", "in_flight"]).where("kind", "in", kinds).execute();
10045
10118
  }
10046
10119
  /**
10047
- * tx 1: cancels stale rows, raises down-health and claims at most one due row per lane.
10120
+ * tx 1: returns rows a failed tick left in flight, cancels stale rows, raises down-health and
10121
+ * claims at most one due row per lane.
10048
10122
  * `ranThreshold` says the outage's down rows were written; the caller records that after commit.
10049
10123
  */
10050
10124
  async function claim(trx, at) {
10051
10125
  const nowIso = new Date(at).toISOString();
10126
+ await releaseOrphans(trx, nowIso);
10052
10127
  await reconcileDoorbells(trx, new Date(at), options.config);
10053
10128
  const rows = await trx.selectFrom("outbox").selectAll().where("state", "in", ["pending", "post_failed"]).orderBy("id").execute();
10054
10129
  const bodies = /* @__PURE__ */ new Map();
@@ -10160,7 +10235,7 @@ function createSender(options) {
10160
10235
  };
10161
10236
  }
10162
10237
  }
10163
- if (c.body.kind === "doorbell" && !c.maybeSent && (await ringTask(trx, c.body.payload.notificationId, c.key))?.membership === "archived") {
10238
+ if (c.body.kind === "doorbell" && (await ringTask(trx, c.body.payload.notificationId, c.key))?.membership === "archived") {
10164
10239
  await kill(trx, [c.id], "superseded");
10165
10240
  return {
10166
10241
  at,
@@ -10254,12 +10329,17 @@ function createSender(options) {
10254
10329
  error: null
10255
10330
  };
10256
10331
  } catch (error) {
10332
+ const message = error instanceof Error ? error.message : String(error);
10333
+ if (error instanceof SpurRejectedError) return {
10334
+ outcome: { status: "rejected" },
10335
+ error: message
10336
+ };
10257
10337
  return {
10258
10338
  outcome: {
10259
10339
  status: "retry",
10260
10340
  uncertain: true
10261
10341
  },
10262
- error: error instanceof Error ? error.message : String(error)
10342
+ error: message
10263
10343
  };
10264
10344
  }
10265
10345
  }
@@ -10275,6 +10355,19 @@ function createSender(options) {
10275
10355
  }).execute();
10276
10356
  await setComment(trx, body, { delivery_state: "post_failed" });
10277
10357
  };
10358
+ /** Kills a ring Spur will not take and ends its notification. */
10359
+ const endRing = async (reason) => {
10360
+ await kill(trx, [c.id], reason);
10361
+ if (body.kind !== "doorbell") return;
10362
+ await ringUndelivered(trx, {
10363
+ notificationId: body.payload.notificationId,
10364
+ dedupeKey: c.key,
10365
+ session: body.payload.session,
10366
+ reason,
10367
+ at: new Date(at),
10368
+ config: options.config
10369
+ });
10370
+ };
10278
10371
  switch (outcome.status) {
10279
10372
  case "sent":
10280
10373
  await row.set({
@@ -10349,6 +10442,7 @@ function createSender(options) {
10349
10442
  uncertain,
10350
10443
  last_error: lastError
10351
10444
  });
10445
+ if (space === null && at - firstAt >= RETRY_WINDOW_MS) return endRing(`no answer from Spur for 30 min: ${lastError}`);
10352
10446
  await row.set({
10353
10447
  state: "pending",
10354
10448
  uncertain,
@@ -10359,6 +10453,7 @@ function createSender(options) {
10359
10453
  await setComment(trx, body, { delivery_state: "pending" });
10360
10454
  return;
10361
10455
  }
10456
+ case "rejected": return endRing(error ?? "rejected by Spur");
10362
10457
  case "failed":
10363
10458
  if (outcome.scope === "message" || space === null) return postFailed({ last_error: outcome.reason });
10364
10459
  if ((await trx.insertInto("transport_health").values({
@@ -10403,26 +10498,8 @@ function createSender(options) {
10403
10498
  async recover() {
10404
10499
  const nowIso = now().toISOString();
10405
10500
  const failed = await scanTransaction(store, options.config, async (trx) => {
10406
- const rows = await trx.selectFrom("outbox").select([
10407
- "id",
10408
- "kind",
10409
- "payload",
10410
- "state"
10411
- ]).where("state", "in", ["in_flight", "post_failed"]).execute();
10412
- await trx.updateTable("outbox").set((eb) => ({
10413
- state: "pending",
10414
- attempts: eb("attempts", "-", 1)
10415
- })).where("state", "=", "in_flight").where("attempt_started", "=", 0).execute();
10416
- await trx.updateTable("outbox").set({
10417
- state: "pending",
10418
- uncertain: 1,
10419
- next_at: nowIso
10420
- }).where("state", "=", "in_flight").where("attempt_started", "=", 1).execute();
10421
- for (const row of rows.filter((candidate) => candidate.state === "in_flight")) {
10422
- const body = parseBody(row);
10423
- if (typeof body !== "string") await setComment(trx, body, { delivery_state: "pending" });
10424
- }
10425
- return rows.filter((row) => row.state === "post_failed").map((row) => row.id);
10501
+ await releaseOrphans(trx, nowIso);
10502
+ return (await trx.selectFrom("outbox").select("id").where("state", "=", "post_failed").execute()).map((row) => row.id);
10426
10503
  });
10427
10504
  for (let i = 0; i < failed.length; i += RECOVER_BATCH) {
10428
10505
  const batch = failed.slice(i, i + RECOVER_BATCH);
@@ -13392,11 +13469,12 @@ function connectionWire(node) {
13392
13469
  pageInfo: pageInfoWire
13393
13470
  });
13394
13471
  }
13395
- function teamNameScopeDenied(error, query) {
13396
- if (error.type !== "INSUFFICIENT_SCOPES" || !query.includes("... on Team { name }")) return false;
13397
- if (error.path !== void 0) return error.path.includes("reviewRequests") && error.path.includes("requestedReviewer") && error.path.at(-1) === "name";
13398
- return /\bname\b/i.test(error.message) && /\bread:(?:org|discussion)\b/i.test(error.message);
13472
+ function teamScopeDenied(error, query) {
13473
+ if (error.type !== "INSUFFICIENT_SCOPES" || !query.includes("... on Team { slug }")) return false;
13474
+ if (error.path !== void 0) return error.path.includes("reviewRequests") && error.path.includes("requestedReviewer") && error.path.at(-1) === "slug";
13475
+ return /\b(?:slug|name)\b/i.test(error.message) && /\bread:(?:org|discussion)\b/i.test(error.message);
13399
13476
  }
13477
+ const REVIEWER_FIELDS = "requestedReviewer { __typename ... on Bot { login } ... on Mannequin { login } ... on User { login } ... on Team { slug } ... on EnterpriseTeam { slug } } asCodeOwner";
13400
13478
  const CLOSING_FIELDS = "nodes { number repository { nameWithOwner } } pageInfo { hasNextPage endCursor }";
13401
13479
  const prFields = (number, closing = false) => `id number url title updatedAt state isDraft mergeable mergeStateStatus
13402
13480
  author { login } headRefName headRefOid
@@ -13406,7 +13484,7 @@ const prFields = (number, closing = false) => `id number url title updatedAt sta
13406
13484
  } pageInfo { hasNextPage endCursor } } }
13407
13485
  reviews(first: 100) { nodes { author { login } state commit { oid } submittedAt } pageInfo { hasNextPage endCursor } }
13408
13486
  reviewThreads(first: 100) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
13409
- reviewRequests(first: 100) { nodes { requestedReviewer { ... on User { login } ... on Team { name } } asCodeOwner } pageInfo { hasNextPage endCursor } }${closing ? `\n closingIssuesReferences(first: 100) { ${CLOSING_FIELDS} }` : ""}`;
13487
+ reviewRequests(first: 100) { nodes { ${REVIEWER_FIELDS} } pageInfo { hasNextPage endCursor } }${closing ? `\n closingIssuesReferences(first: 100) { ${CLOSING_FIELDS} }` : ""}`;
13410
13488
  const DISCOVERY_FIELDS = `nodes { number updatedAt author { login } state } pageInfo { hasNextPage endCursor }`;
13411
13489
  function aliases(numbers, closing = false) {
13412
13490
  return numbers.map((number, i) => `pr${String(i)}: repository(owner: $owner, name: $repo) { pullRequest(number: ${String(number)}) { ${prFields(number, closing)} } }`).join("\n");
@@ -13419,7 +13497,7 @@ function detailQuery(numbers, closing = false) {
13419
13497
  }
13420
13498
  function pageQuery(connection, bootstrap = false) {
13421
13499
  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: [${bootstrap ? "OPEN" : "OPEN, MERGED"}], orderBy: {field: UPDATED_AT, direction: DESC}) { ${DISCOVERY_FIELDS} } } }`;
13422
- 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" ? "author { login } state commit { oid } submittedAt" : connection === "reviewThreads" ? "isResolved" : "requestedReviewer { ... on User { login } ... on Team { name } } asCodeOwner"} } pageInfo { hasNextPage endCursor } }`} } } }`;
13500
+ 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" ? "author { login } state commit { oid } submittedAt" : connection === "reviewThreads" ? "isResolved" : REVIEWER_FIELDS} } pageInfo { hasNextPage endCursor } }`} } } }`;
13423
13501
  }
13424
13502
  var GithubClient = class {
13425
13503
  token;
@@ -13465,7 +13543,7 @@ var GithubClient = class {
13465
13543
  status: 429,
13466
13544
  headers: response.headers
13467
13545
  }, Date.now());
13468
- if (errors.some((error) => teamNameScopeDenied(error, query))) throw new AdapterError("auth", "GitHub token needs read:org for team review requests");
13546
+ if (errors.some((error) => teamScopeDenied(error, query))) throw new AdapterError("auth", "GitHub token needs read:org for team review requests");
13469
13547
  if (errors.some((error) => error.type === "INSUFFICIENT_SCOPES")) throw new AdapterError("auth", "GitHub token lacks a required GraphQL read scope");
13470
13548
  const data = parseWire(dataWire, wire.data, MALFORMED$3, ["data"]);
13471
13549
  return {
@@ -13554,6 +13632,21 @@ const reviewWire = z.object({
13554
13632
  submittedAt: z.string().nullish()
13555
13633
  }).refine((review) => review.commit !== null || !review.author?.login || review.submittedAt == null || !KEPT_REVIEWS.includes(review.state.toLowerCase()), { path: ["commit"] });
13556
13634
  const nodes = (node) => z.object({ nodes: z.array(node) });
13635
+ const loginReviewer = (type) => z.object({
13636
+ __typename: z.literal(type),
13637
+ login: z.string()
13638
+ });
13639
+ const slugReviewer = (type) => z.object({
13640
+ __typename: z.literal(type),
13641
+ slug: z.string()
13642
+ });
13643
+ const reviewerWire = z.discriminatedUnion("__typename", [
13644
+ loginReviewer("User"),
13645
+ loginReviewer("Mannequin"),
13646
+ loginReviewer("Bot"),
13647
+ slugReviewer("Team"),
13648
+ slugReviewer("EnterpriseTeam")
13649
+ ]).nullable();
13557
13650
  const closingWire = z.object({ nodes: z.array(z.object({
13558
13651
  number: z.int().positive(),
13559
13652
  repository: z.object({ nameWithOwner: z.string() }).nullish()
@@ -13574,10 +13667,7 @@ const prWire = z.object({
13574
13667
  reviews: nodes(reviewWire),
13575
13668
  reviewThreads: nodes(z.object({ isResolved: z.boolean() })),
13576
13669
  reviewRequests: nodes(z.object({
13577
- requestedReviewer: z.object({
13578
- login: z.string().nullish(),
13579
- name: z.string().nullish()
13580
- }),
13670
+ requestedReviewer: reviewerWire,
13581
13671
  asCodeOwner: z.boolean()
13582
13672
  })),
13583
13673
  closingIssuesReferences: closingWire
@@ -13750,6 +13840,25 @@ function prKeys(rule, title, branch, refs) {
13750
13840
  default: return assertNever(rule);
13751
13841
  }
13752
13842
  }
13843
+ function reviewer(wire) {
13844
+ switch (wire.__typename) {
13845
+ case "User":
13846
+ case "Mannequin": return {
13847
+ kind: "user",
13848
+ id: wire.login
13849
+ };
13850
+ case "Bot": return {
13851
+ kind: "bot",
13852
+ id: wire.login
13853
+ };
13854
+ case "Team":
13855
+ case "EnterpriseTeam": return {
13856
+ kind: "team",
13857
+ id: wire.slug
13858
+ };
13859
+ default: return assertNever(wire);
13860
+ }
13861
+ }
13753
13862
  function normalizePr(repo, value, rule) {
13754
13863
  const wire = parseWire(prWire, value, "Malformed GitHub PR response");
13755
13864
  const checks = latestChecks(wire.statusCheckRollup?.contexts.nodes ?? []);
@@ -13782,10 +13891,10 @@ function normalizePr(repo, value, rule) {
13782
13891
  ...checks,
13783
13892
  reviews: latestReviews(wire.reviews.nodes),
13784
13893
  reviewThreads: wire.reviewThreads.nodes.map((node) => ({ resolved: node.isResolved })),
13785
- reviewRequests: wire.reviewRequests.nodes.map((node) => ({
13786
- reviewer: node.requestedReviewer.login ?? node.requestedReviewer.name,
13787
- asCodeOwner: node.asCodeOwner
13788
- })),
13894
+ reviewRequests: wire.reviewRequests.nodes.flatMap(({ requestedReviewer, asCodeOwner }) => requestedReviewer === null ? [] : [{
13895
+ ...reviewer(requestedReviewer),
13896
+ asCodeOwner
13897
+ }]),
13789
13898
  ticketKeys: prKeys(rule, title, headBranch, closingRefs(wire.closingIssuesReferences)),
13790
13899
  updatedAt: wire.updatedAt
13791
13900
  };
@@ -13875,6 +13984,22 @@ function withConnection(pr, field, connection) {
13875
13984
  [field]: connection
13876
13985
  };
13877
13986
  }
13987
+ function content(read) {
13988
+ try {
13989
+ return read();
13990
+ } catch (error) {
13991
+ if (error instanceof AdapterError) return error;
13992
+ throw error;
13993
+ }
13994
+ }
13995
+ const malformedPaging = () => ({
13996
+ status: "malformed",
13997
+ error: new AdapterError("transient", "Malformed GitHub pagination")
13998
+ });
13999
+ function pageCursor(connection) {
14000
+ const { hasNextPage, endCursor } = connection.pageInfo;
14001
+ return hasNextPage && !endCursor ? null : nextPage(connection);
14002
+ }
13878
14003
  async function fullPr(client, first, owner, name, number, signal, budget) {
13879
14004
  let pr = first;
13880
14005
  for (const field of [
@@ -13886,10 +14011,11 @@ async function fullPr(client, first, owner, name, number, signal, budget) {
13886
14011
  ]) {
13887
14012
  let target = connectionOf(pr, field);
13888
14013
  if (target === void 0) continue;
13889
- let cursor = nextPage(target);
14014
+ let cursor = pageCursor(target);
14015
+ if (cursor === null) return malformedPaging();
13890
14016
  const seen = /* @__PURE__ */ new Set();
13891
14017
  while (cursor !== void 0) {
13892
- if (seen.has(cursor)) throw new AdapterError("transient", "Malformed GitHub pagination");
14018
+ if (seen.has(cursor)) return malformedPaging();
13893
14019
  seen.add(cursor);
13894
14020
  const response = await client.query(pageQuery(field), {
13895
14021
  owner,
@@ -13901,19 +14027,28 @@ async function fullPr(client, first, owner, name, number, signal, budget) {
13901
14027
  rejectUnscoped(response.errors, ["repository"]);
13902
14028
  requireCheckAccess(response.errors);
13903
14029
  const denied = response.errors.some(deniedReference);
13904
- if (withoutDeniedReferences(response.errors).length > 0) return void 0;
13905
- const page = connectionOf(parseWire(pageRootWire, response.data.repository, MALFORMED$2, ["data", "repository"]).pullRequest, field);
14030
+ if (withoutDeniedReferences(response.errors).length > 0) return { status: "denied" };
14031
+ const root = content(() => parseWire(pageRootWire, response.data.repository, MALFORMED$2, ["data", "repository"]));
14032
+ if (root instanceof AdapterError) return {
14033
+ status: "malformed",
14034
+ error: root
14035
+ };
14036
+ const page = connectionOf(root.pullRequest, field);
13906
14037
  if (page === void 0 && denied && field === "closingIssuesReferences") break;
13907
- if (page === void 0) throw new AdapterError("transient", "Malformed GitHub pagination");
14038
+ if (page === void 0) return malformedPaging();
13908
14039
  target = {
13909
14040
  nodes: [...target.nodes, ...page.nodes],
13910
14041
  pageInfo: page.pageInfo
13911
14042
  };
13912
14043
  pr = withConnection(pr, field, target);
13913
- cursor = nextPage(page);
14044
+ cursor = pageCursor(page);
14045
+ if (cursor === null) return malformedPaging();
13914
14046
  }
13915
14047
  }
13916
- return pr;
14048
+ return {
14049
+ status: "ok",
14050
+ pr
14051
+ };
13917
14052
  }
13918
14053
  async function pollRepository({ id, repo, login, keys, client, ctx }) {
13919
14054
  const observedAt = sourceCursorSchema.parse((/* @__PURE__ */ new Date()).toISOString());
@@ -13960,6 +14095,20 @@ async function pollRepository({ id, repo, login, keys, client, ctx }) {
13960
14095
  if (!discoveryOk) complete = false;
13961
14096
  const found = discover(nodes, ctx.cursor, login);
13962
14097
  const bootstrapCursor = bootstrap && discoveryOk ? latestUpdatedAt(parseWire(baselineRootWire, response.data.repository, MALFORMED$2, ["data", "repository"]).mergedBaseline.nodes, found.cursor) ?? sourceCursorSchema.parse("1970-01-01T00:00:00.000Z") : void 0;
14098
+ let parseError;
14099
+ let parseFailedRefs = 0;
14100
+ const malformed = (error, ref) => {
14101
+ parseError ??= error;
14102
+ complete = false;
14103
+ if (ref) {
14104
+ entities.push({
14105
+ ref,
14106
+ status: "no_access"
14107
+ });
14108
+ parseFailedRefs += 1;
14109
+ }
14110
+ return false;
14111
+ };
13963
14112
  const process = async (number, alias, data, scopedErrors, ref) => {
13964
14113
  const errors = withoutDeniedReferences(scopedErrors);
13965
14114
  requireCheckAccess(errors);
@@ -13973,7 +14122,9 @@ async function pollRepository({ id, repo, login, keys, client, ctx }) {
13973
14122
  });
13974
14123
  return false;
13975
14124
  }
13976
- const wire = parseWire(aliasWire, data[alias], MALFORMED$2, ["data", alias])?.pullRequest;
14125
+ const root = content(() => parseWire(aliasWire, data[alias], MALFORMED$2, ["data", alias]));
14126
+ if (root instanceof AdapterError) return malformed(root, ref);
14127
+ const wire = root?.pullRequest;
13977
14128
  if (wire === null || wire === void 0) {
13978
14129
  if (ref) entities.push({
13979
14130
  ref,
@@ -13985,7 +14136,7 @@ async function pollRepository({ id, repo, login, keys, client, ctx }) {
13985
14136
  const full = await fullPr(client, wire, owner, name, number, ctx.signal, (next) => {
13986
14137
  budget = next;
13987
14138
  });
13988
- if (full === void 0) {
14139
+ if (full.status === "denied") {
13989
14140
  complete = false;
13990
14141
  if (ref) entities.push({
13991
14142
  ref,
@@ -13993,7 +14144,9 @@ async function pollRepository({ id, repo, login, keys, client, ctx }) {
13993
14144
  });
13994
14145
  return false;
13995
14146
  }
13996
- const facts = normalizePr(ref?.repo ?? repo, full, keys);
14147
+ if (full.status === "malformed") return malformed(full.error, ref);
14148
+ const facts = content(() => normalizePr(ref?.repo ?? repo, full.pr, keys));
14149
+ if (facts instanceof AdapterError) return malformed(facts, ref);
13997
14150
  items.push({
13998
14151
  kind: "pr",
13999
14152
  facts
@@ -14025,6 +14178,7 @@ async function pollRepository({ id, repo, login, keys, client, ctx }) {
14025
14178
  }
14026
14179
  }
14027
14180
  if (ctx.signal.aborted) throw new AdapterError("transient", "GitHub poll aborted");
14181
+ if (parseError !== void 0 && items.length === 0 && entities.length === parseFailedRefs) throw parseError;
14028
14182
  const nextCursor = bootstrap ? bootstrapCursor : found.cursor;
14029
14183
  return {
14030
14184
  source: id,
@@ -15775,10 +15929,14 @@ function createDeliveryGateway(client, channels) {
15775
15929
  };
15776
15930
  } catch (error) {
15777
15931
  const result = apiFailure(error);
15778
- return result.status === "retry" && confirmed ? {
15932
+ if (!confirmed) return result;
15933
+ return result.status === "retry" ? {
15779
15934
  ...result,
15780
15935
  uncertain: true
15781
- } : result;
15936
+ } : {
15937
+ status: "retry",
15938
+ uncertain: true
15939
+ };
15782
15940
  }
15783
15941
  }
15784
15942
  return {
@@ -16359,6 +16517,13 @@ function createBoardModules(ctxFor, options = {}) {
16359
16517
  //#region ../daemon/src/spur-port.ts
16360
16518
  const SEND_TIMEOUT_MS = 8e3;
16361
16519
  const ERROR_TEXT_LIMIT = 200;
16520
+ /** 4xx statuses Spur may answer for a passing state; every other 4xx ends the ring. */
16521
+ const RETRYABLE_4XX = /* @__PURE__ */ new Set([
16522
+ 408,
16523
+ 409,
16524
+ 425,
16525
+ 429
16526
+ ]);
16362
16527
  /** The request Spur's own `spur send` makes; the doctor probe sends the same one. */
16363
16528
  function spurSendRequest(baseUrl, session, text) {
16364
16529
  return {
@@ -16399,7 +16564,10 @@ function createSpurPort(options) {
16399
16564
  return;
16400
16565
  }
16401
16566
  const error = await spurErrorText(response);
16402
- throw new Error(`Spur send failed with HTTP ${String(response.status)}${error === null ? "" : `: ${error}`}`);
16567
+ const { status } = response;
16568
+ const message = `Spur send failed with HTTP ${String(status)}${error === null ? "" : `: ${error}`}`;
16569
+ if (status >= 400 && status < 500 && !RETRYABLE_4XX.has(status)) throw new SpurRejectedError(message);
16570
+ throw new Error(message);
16403
16571
  } };
16404
16572
  }
16405
16573
  //#endregion
@@ -16421,7 +16589,7 @@ const GITHUB_PROBE = `query DoctorGithubPermissions($owner: String!, $repo: Stri
16421
16589
  pullRequests(first: 10, states: [OPEN], orderBy: {field: UPDATED_AT, direction: DESC}) {
16422
16590
  nodes {
16423
16591
  statusCheckRollup { contexts(first: 100) { nodes { ... on CheckRun { name } } } }
16424
- reviewRequests(first: 100) { nodes { requestedReviewer { ... on Team { name } } } }
16592
+ reviewRequests(first: 100) { nodes { requestedReviewer { ... on Team { slug } } } }
16425
16593
  }
16426
16594
  }
16427
16595
  defaultBranchRef { target { ... on Commit {
@@ -16438,7 +16606,7 @@ function scopedGithubError(value) {
16438
16606
  if (!Array.isArray(path)) return null;
16439
16607
  const fields = path.filter((part) => typeof part === "string");
16440
16608
  if (error?.["type"] === "FORBIDDEN" && fields.includes("statusCheckRollup") && fields.includes("contexts")) return GITHUB_CHECKS_FIX;
16441
- if (error?.["type"] === "INSUFFICIENT_SCOPES" && fields.includes("reviewRequests") && fields.includes("requestedReviewer") && fields.includes("name")) return GITHUB_TEAMS_FIX;
16609
+ if (error?.["type"] === "INSUFFICIENT_SCOPES" && fields.includes("reviewRequests") && fields.includes("requestedReviewer") && fields.includes("slug")) return GITHUB_TEAMS_FIX;
16442
16610
  return null;
16443
16611
  }
16444
16612
  async function deadlineCall(ctx, name, failure, call) {
package/dist/mcp.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { P as ERRORS, p as renderMcpError, u as OPERATIONS } from "./src-ep5scuVt.mjs";
2
- import { i as CliError, n as requestOperation } from "./client-CwKmG23X.mjs";
3
- import { a as memoryVerdictCache, r as compareCatalogs, s as loadClientConfig, t as checkCatalog } from "./config-CXDupHSC.mjs";
1
+ import { P as ERRORS, p as renderMcpError, u as OPERATIONS } from "./src-vzl2nFf6.mjs";
2
+ import { i as CliError, n as requestOperation } from "./client-Swp5TBku.mjs";
3
+ import { a as memoryVerdictCache, r as compareCatalogs, s as loadClientConfig, t as checkCatalog } from "./config-C1ly8wCm.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { z } from "zod";
@@ -841,6 +841,11 @@ const REVIEW_STATES = [
841
841
  "commented",
842
842
  "dismissed"
843
843
  ];
844
+ const REVIEWER_KINDS = [
845
+ "user",
846
+ "team",
847
+ "bot"
848
+ ];
844
849
  /** Spur session lifecycle values known today. */
845
850
  const SESSION_STATUSES = [
846
851
  "spawning",
@@ -899,8 +904,15 @@ const prFactsSchema = z.strictObject({
899
904
  })).describe("The latest review of each reviewer, with the commit it was given on."),
900
905
  reviewThreads: z.array(z.strictObject({ resolved: z.boolean().describe("Whether the review thread is resolved.") })).describe("Review threads on the pull request."),
901
906
  reviewRequests: z.array(z.strictObject({
902
- reviewer: z.string().min(1).describe("Login or team name asked to review."),
907
+ kind: z.enum(REVIEWER_KINDS).optional().describe("Kind of reviewer asked to review."),
908
+ id: z.string().min(1).optional().describe("Login of the user or bot, or the slug of the team."),
909
+ reviewer: z.string().min(1).optional().describe("Login or team name as stored by an earlier version; new facts use kind and id."),
903
910
  asCodeOwner: z.boolean().describe("Whether the review was requested because the reviewer owns changed code.")
911
+ }).superRefine((request, ctx) => {
912
+ if (!(request.reviewer === void 0 ? request.kind !== void 0 && request.id !== void 0 : request.kind === void 0 && request.id === void 0)) ctx.addIssue({
913
+ code: "custom",
914
+ message: "Set kind and id, or reviewer alone"
915
+ });
904
916
  })).describe("Pending review requests."),
905
917
  ticketKeys: z.array(taskKeySchema).describe("Ticket keys found in the head branch name and the title."),
906
918
  updatedAt: at$2.describe("When the pull request last changed.")
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spur-board",
3
- "version": "0.16.2",
3
+ "version": "0.17.1",
4
4
  "license": "MIT",
5
5
  "engines": {
6
6
  "node": "^24.12.0 || ^26.0.0"