spur-board 0.16.1 → 0.17.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,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";
@@ -7612,10 +7612,17 @@ async function redactPrivateReply(body) {
7612
7612
  };
7613
7613
  }));
7614
7614
  }
7615
+ const NO_SCAN = "Gateway outbox requires a secret scan transaction";
7616
+ /** The config of the running scan transaction; gateway producers read task links from it. */
7617
+ function scanConfig() {
7618
+ const context = receipts.getStore();
7619
+ if (context === void 0) throw new Error(NO_SCAN);
7620
+ return context.config;
7621
+ }
7615
7622
  /** Used by the common outbox insertion point before it issues SQL. */
7616
7623
  function checkGatewayStrings(strings) {
7617
7624
  const context = receipts.getStore();
7618
- if (context === void 0) throw new Error("Gateway outbox requires a secret scan transaction");
7625
+ if (context === void 0) throw new Error(NO_SCAN);
7619
7626
  const { known, unseen } = context;
7620
7627
  for (const value of strings) if (!known.has(value)) unseen.add(value);
7621
7628
  if (unseen.size > 0) return SCAN_PENDING;
@@ -7626,10 +7633,11 @@ function checkGatewayStrings(strings) {
7626
7633
  return null;
7627
7634
  }
7628
7635
  /** Replays database-only work after scanning exact strings outside the write transaction. */
7629
- async function scanTransaction(store, fn) {
7636
+ async function scanTransaction(store, config, fn) {
7630
7637
  const known = /* @__PURE__ */ new Map();
7631
7638
  for (let pass = 0; pass < MAX_PASSES; pass += 1) {
7632
7639
  const context = {
7640
+ config,
7633
7641
  known,
7634
7642
  unseen: /* @__PURE__ */ new Set()
7635
7643
  };
@@ -7683,6 +7691,16 @@ function projectForKey(config, key) {
7683
7691
  });
7684
7692
  return matched.length === 1 ? matched[0] ?? null : null;
7685
7693
  }
7694
+ /** The tracker page of a task: GitHub issue, Jira issue, or a GitHub fallback by key. */
7695
+ function taskUrl(task, config) {
7696
+ if (task.tracker_kind === "github-issues") {
7697
+ const match = /^(.+)#(\d+)$/.exec(task.key);
7698
+ if (match?.[1] !== void 0 && match[2] !== void 0) return `https://github.com/${match[1]}/issues/${match[2]}`;
7699
+ }
7700
+ const project = config.projects.find((p) => p.id === task.project);
7701
+ if (project?.tracker.type === "jira") return `${project.tracker.baseUrl.replace(/\/$/, "")}/browse/${task.key}`;
7702
+ return `https://github.com/${task.key.replace("#", "/issues/")}`;
7703
+ }
7686
7704
  async function emit(trx, kind, project, taskId, at, payload, actor = "system") {
7687
7705
  const parsed = parseActorId(actor);
7688
7706
  if (parsed === null) throw new Error("Invalid journal actor");
@@ -7843,7 +7861,7 @@ function createApply(deps) {
7843
7861
  const commandKey = key ?? randomUUID();
7844
7862
  let deniedHint;
7845
7863
  const at = new Date(clock.now()).toISOString();
7846
- const result = await scanTransaction(store, (trx) => replayOperation(trx, {
7864
+ const result = await scanTransaction(store, config, (trx) => replayOperation(trx, {
7847
7865
  actor,
7848
7866
  key: commandKey,
7849
7867
  operation: entry.id,
@@ -7898,7 +7916,7 @@ function commandRetention(deps) {
7898
7916
  let running = Promise.resolve();
7899
7917
  const run = async () => {
7900
7918
  const cutoff = (/* @__PURE__ */ new Date(clock.now() - retentionDays * DAY_MS)).toISOString();
7901
- await scanTransaction(store, async (trx) => {
7919
+ await store.transaction(async (trx) => {
7902
7920
  await trx.deleteFrom("command").where("at", "<", cutoff).execute();
7903
7921
  });
7904
7922
  };
@@ -7970,251 +7988,103 @@ async function dispatchOperation(deps, id, input, actor, key) {
7970
7988
  return operation.kind === "query" ? createQuery(deps)(handler, input, actor) : createApply(deps)(handler, input, actor, key);
7971
7989
  }
7972
7990
  //#endregion
7973
- //#region ../core/src/app/doorbells.ts
7974
- const DEFAULT_PAUSES = [
7975
- 12e4,
7976
- 3e5,
7977
- 9e5
7978
- ];
7979
- async function journal$3(trx, notification, kind, payload, at) {
7980
- const task = await trx.selectFrom("task").select("project").where("id", "=", notification.task_id).executeTakeFirstOrThrow();
7991
+ //#region ../core/src/app/item-raise.ts
7992
+ const NO_FEED = /* @__PURE__ */ new Set([
7993
+ "post_failed",
7994
+ "answer_undelivered",
7995
+ "transport_health"
7996
+ ]);
7997
+ async function journal$3(trx, item, kind, at, rule, actor = "system") {
7998
+ const parsed = parseActorId(actor);
7999
+ if (parsed === null) throw new Error("Invalid journal actor");
8000
+ const task = item.task_id === null ? void 0 : await trx.selectFrom("task").select(["project"]).where("id", "=", item.task_id).executeTakeFirstOrThrow();
7981
8001
  await trx.insertInto("event").values({
7982
8002
  at: at.toISOString(),
7983
- project: task.project,
7984
- task_id: notification.task_id,
8003
+ project: task?.project ?? "_board",
8004
+ task_id: item.task_id,
7985
8005
  kind,
7986
- actor: "system",
7987
- actor_ref: null,
7988
- payload: toJson(eventPayloadSchemas[kind], payload),
8006
+ actor: parsed.actor,
8007
+ actor_ref: parsed.actor === "agent" ? JSON.stringify(parsed.actorRef) : null,
8008
+ payload: toJson(eventPayloadSchemas[kind], {
8009
+ item: `I${String(item.id)}`,
8010
+ ...kind === "from_you_raised" && rule !== void 0 ? { rule } : {}
8011
+ }),
7989
8012
  v: 1,
7990
8013
  request_id: null
7991
8014
  }).execute();
7992
8015
  }
7993
- /** Register a worker-addressed block without manufacturing a comment. */
7994
- async function registerBlockNotification(trx, block, at) {
7995
- if (block.addressee_role !== "worker") return;
7996
- await trx.insertInto("notification").values({
7997
- source_key: `block:${String(block.id)}:worker`,
7998
- kind: "block",
7999
- task_id: block.task_id,
8000
- block_id: block.id,
8001
- comment_id: null,
8002
- revision: null,
8003
- role: "worker",
8004
- author_session: null,
8005
- recipient_session: null,
8006
- next_at: at.toISOString(),
8007
- last_outbox_id: null,
8008
- acked_at: null,
8009
- exhausted_at: null,
8010
- created_at: at.toISOString()
8011
- }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
8012
- }
8013
- /** Register an answer or clarification for the original author and its task role. */
8014
- async function registerAnswerNotification(trx, input) {
8015
- if (input.authorRole !== "worker") return;
8016
- const parsed = parseActorId(input.block.author);
8017
- if (parsed?.actor !== "agent") return;
8018
- await trx.insertInto("notification").values({
8019
- source_key: `comment:${String(input.commentId)}:${String(input.revision)}`,
8020
- kind: "answer",
8021
- task_id: input.block.task_id,
8022
- block_id: input.block.id,
8023
- comment_id: input.commentId,
8024
- revision: input.revision,
8025
- role: "worker",
8026
- author_session: parsed.actorRef.session,
8027
- recipient_session: null,
8028
- next_at: input.at.toISOString(),
8029
- last_outbox_id: null,
8030
- acked_at: null,
8031
- exhausted_at: null,
8032
- created_at: input.at.toISOString()
8033
- }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
8034
- }
8035
- async function liveSession(trx, id) {
8036
- const row = await trx.selectFrom("session_snapshot").selectAll().where("id", "=", id).executeTakeFirst();
8037
- return row?.ended_at === null && row.state !== "killed" && row.state !== "stopped" ? row : void 0;
8038
- }
8039
- /** Select the current live recipient for a semantic notification. */
8040
- async function selectNotificationRecipient(trx, n) {
8041
- if (n.author_session !== null) {
8042
- const author = await liveSession(trx, n.author_session);
8043
- if (author !== void 0) return author;
8044
- }
8045
- const links = await trx.selectFrom("link").select("session_id").where("task_id", "=", n.task_id).where("entity", "=", "session").where("role", "=", n.role === "worker" ? "worker" : "orchestrator").where("banned", "=", 0).orderBy("created_at", "desc").execute();
8046
- for (const link of links) {
8047
- if (link.session_id === null) continue;
8048
- const session = await liveSession(trx, link.session_id);
8049
- if (session !== void 0) return session;
8050
- }
8051
- }
8052
- function taskUrl(task, config) {
8053
- if (task.tracker_kind === "github-issues") {
8054
- const match = /^(.+)#(\d+)$/.exec(task.key);
8055
- if (match?.[1] !== void 0 && match[2] !== void 0) return `https://github.com/${match[1]}/issues/${match[2]}`;
8056
- }
8057
- const project = config?.projects.find((p) => p.id === task.project);
8058
- if (project?.tracker.type === "jira") return `${project.tracker.baseUrl.replace(/\/$/, "")}/browse/${task.key}`;
8059
- return `https://github.com/${task.key.replace("#", "/issues/")}`;
8060
- }
8061
- /** The operator item kind raised when a notification's rings are exhausted. */
8062
- function exhaustedItemKind(n) {
8063
- return n.kind === "answer" ? "answer_undelivered" : "worker_not_reading";
8064
- }
8065
- /** The operator item key raised when a notification's rings are exhausted. */
8066
- function exhaustedItemKey(n) {
8067
- return `${exhaustedItemKind(n)}:${n.source_key}`;
8016
+ /** Kinds whose item has a retry action besides `delivery:<id>` (see `items.ts`). */
8017
+ const RETRY_KINDS = /* @__PURE__ */ new Set([
8018
+ "answer_undelivered",
8019
+ "worker_not_reading",
8020
+ "inbound_failure"
8021
+ ]);
8022
+ /** Every item line gets Close, after Retry when its kind has a retry action. */
8023
+ function itemActions(item) {
8024
+ const id = String(item.id);
8025
+ const close = {
8026
+ id: `item:${id}:close`,
8027
+ label: "Close"
8028
+ };
8029
+ if (item.kind === "token_request") return [
8030
+ {
8031
+ id: `token:${id}:approve`,
8032
+ label: "Approve"
8033
+ },
8034
+ {
8035
+ id: `token:${id}:deny`,
8036
+ label: "Deny"
8037
+ },
8038
+ close
8039
+ ];
8040
+ return item.item_key.startsWith("delivery:") || RETRY_KINDS.has(item.kind) ? [{
8041
+ id: `item:${id}:retry`,
8042
+ label: "Retry"
8043
+ }, close] : [close];
8068
8044
  }
8069
8045
  /**
8070
- * Restart an exhausted, unacknowledged ring series at `at`. The recipient and last row stay, so
8071
- * the next reconcile rings the same session under the next series key.
8046
+ * Raise one item generation; `writeLine` enqueues its feed line. A repeated raise of an active
8047
+ * key is idempotent.
8072
8048
  */
8073
- async function restartNotification(trx, sourceKey, at) {
8074
- if (await trx.updateTable("notification").set({
8075
- rings: 0,
8076
- exhausted_at: null,
8077
- next_at: at.toISOString()
8078
- }).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.");
8079
- }
8080
- /** Reconcile due semantic notifications in the sender's claim transaction. */
8081
- async function reconcileDoorbells(trx, at, config) {
8082
- 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();
8083
- for (const n of due) {
8084
- const session = await selectNotificationRecipient(trx, n);
8085
- if (session === void 0) {
8086
- if (n.recipient_session !== null) await trx.updateTable("notification").set({
8087
- recipient_session: null,
8088
- rings: 0,
8089
- last_outbox_id: null
8090
- }).where("id", "=", n.id).execute();
8091
- continue;
8092
- }
8093
- if (session.state === "working") continue;
8094
- let rings = n.rings;
8095
- let lastOutbox = n.last_outbox_id;
8096
- if (session.id !== n.recipient_session) {
8097
- if (lastOutbox !== null) await trx.updateTable("outbox").set({
8098
- state: "dead",
8099
- last_error: "recipient changed"
8100
- }).where("id", "=", lastOutbox).where("state", "=", "pending").execute();
8101
- rings = 0;
8102
- lastOutbox = null;
8103
- await trx.updateTable("notification").set({
8104
- recipient_session: session.id,
8105
- rings: 0,
8106
- last_outbox_id: null
8107
- }).where("id", "=", n.id).execute();
8108
- }
8109
- if (lastOutbox !== null) {
8110
- const row = await trx.selectFrom("outbox").select("state").where("id", "=", lastOutbox).executeTakeFirst();
8111
- if (row?.state === "pending" || row?.state === "in_flight") continue;
8112
- }
8113
- const task = await trx.selectFrom("task").selectAll().where("id", "=", n.task_id).executeTakeFirstOrThrow();
8114
- const itemKey = exhaustedItemKey(n);
8115
- if (rings >= 3) {
8116
- await raiseItem(trx, {
8117
- itemKey,
8118
- kind: exhaustedItemKind(n),
8119
- text: n.kind === "answer" ? `Answer to block B${String(n.block_id)} on ${task.key} was not read` : `worker ${session.id} is not reading block B${String(n.block_id)} on ${task.key}`,
8120
- url: taskUrl(task, config),
8121
- taskId: task.id,
8122
- blockId: n.block_id,
8123
- at
8124
- });
8125
- await trx.updateTable("notification").set({ exhausted_at: at.toISOString() }).where("id", "=", n.id).execute();
8126
- await journal$3(trx, n, "doorbell_undelivered", {
8127
- doorbell: `N${String(n.id)}`,
8128
- reason: "unanswered"
8129
- }, at);
8130
- continue;
8131
- }
8132
- const raised = await trx.selectFrom("operator_item").select((eb) => eb.fn.max("raise_no").as("series")).where("item_key", "=", itemKey).executeTakeFirst();
8133
- const archived = await trx.selectFrom("event").select((eb) => eb.fn.countAll().as("count")).where("task_id", "=", n.task_id).where("kind", "=", "task_archived").executeTakeFirst();
8134
- const ring = rings + 1;
8135
- const text = `${task.key} block B${String(n.block_id)}: check board inbox (N${String(n.id)}-${String(ring)})`;
8136
- const outboxId = await enqueueDoorbell(trx, {
8137
- notificationId: n.id,
8138
- ring,
8139
- session: session.id,
8140
- text,
8141
- at,
8142
- series: raised?.series ?? 0,
8143
- archives: archived?.count ?? 0
8049
+ async function raiseItemWith(trx, input, writeLine) {
8050
+ const active = await trx.selectFrom("operator_item").selectAll().where("item_key", "=", input.itemKey).where("cleared_at", "is", null).executeTakeFirst();
8051
+ if (active !== void 0) return active;
8052
+ const previous = await trx.selectFrom("operator_item").select("raise_no").where("item_key", "=", input.itemKey).orderBy("raise_no", "desc").executeTakeFirst();
8053
+ let item = await trx.insertInto("operator_item").values({
8054
+ item_key: input.itemKey,
8055
+ raise_no: (previous?.raise_no ?? 0) + 1,
8056
+ kind: input.kind,
8057
+ text: input.text,
8058
+ url: input.url,
8059
+ task_id: input.taskId,
8060
+ block_id: input.blockId,
8061
+ raised_at: input.at.toISOString(),
8062
+ cleared_at: null,
8063
+ line_outbox_id: null,
8064
+ fingerprint: input.fingerprint ?? null,
8065
+ fact_at: input.factAt ?? null,
8066
+ source: input.source ?? null,
8067
+ priority: input.priority ?? null,
8068
+ inbound_event_json: null
8069
+ }).returningAll().executeTakeFirstOrThrow();
8070
+ await journal$3(trx, item, "from_you_raised", input.at, input.rule);
8071
+ if (!NO_FEED.has(item.kind) && !input.suppressFeed) {
8072
+ const key = (item.task_id === null ? null : await trx.selectFrom("task").select("key").where("id", "=", item.task_id).executeTakeFirstOrThrow())?.key ?? "spur-board";
8073
+ const line = await writeLine(trx, {
8074
+ itemId: item.id,
8075
+ itemKey: item.item_key,
8076
+ raise: item.raise_no,
8077
+ key,
8078
+ text: item.text,
8079
+ title: `${key}: ${item.text}`,
8080
+ url: item.url,
8081
+ taskId: item.task_id,
8082
+ actions: itemActions(item),
8083
+ at: input.at
8144
8084
  });
8145
- await trx.updateTable("notification").set({ last_outbox_id: outboxId }).where("id", "=", n.id).execute();
8146
- }
8147
- }
8148
- /** Count one confirmed Spur send, regardless of transport attempts for its outbox row. */
8149
- async function recordRingDelivery(trx, notificationId, ring, session, at, config) {
8150
- const n = await trx.selectFrom("notification").selectAll().where("id", "=", notificationId).executeTakeFirst();
8151
- if (n === void 0 || n.acked_at !== null || n.recipient_session !== session || n.rings >= ring) return;
8152
- const pauses = config ? [
8153
- config.doorbells.firstRetryMs,
8154
- config.doorbells.secondRetryMs,
8155
- config.doorbells.unansweredAfterMs
8156
- ] : DEFAULT_PAUSES;
8157
- await trx.updateTable("notification").set({
8158
- rings: ring,
8159
- next_at: new Date(at.getTime() + (pauses[ring - 1] ?? 0)).toISOString()
8160
- }).where("id", "=", notificationId).execute();
8161
- await journal$3(trx, n, "doorbell_rung", {
8162
- doorbell: `N${String(n.id)}`,
8163
- addressee: n.role,
8164
- attempt: ring
8165
- }, at);
8166
- }
8167
- /** Confirm that a queued ring still belongs to a live, idle, unread recipient. */
8168
- async function ringStillCurrent(trx, notificationId, sessionId) {
8169
- const n = await trx.selectFrom("notification").selectAll().where("id", "=", notificationId).executeTakeFirst();
8170
- if (n === void 0 || n.acked_at !== null || n.exhausted_at !== null || n.recipient_session !== sessionId) return "dead";
8171
- const session = await selectNotificationRecipient(trx, n);
8172
- if (session?.id !== sessionId) return "dead";
8173
- return session.state === "working" ? "defer" : "send";
8174
- }
8175
- /**
8176
- * The task of a ring: through its notification, or for an inbound author ring (no notification)
8177
- * through the comment in its `doorbell:comment:<id>:` key. Archive kills only unclaimed rings;
8178
- * the sender drops a claimed one of an archived task before its send starts.
8179
- */
8180
- async function ringTask(trx, notificationId, dedupeKey) {
8181
- const commentId = /^doorbell:comment:(\d+):/.exec(dedupeKey)?.[1];
8182
- if (notificationId === void 0 && commentId === void 0) return void 0;
8183
- const owner = notificationId !== void 0 ? trx.selectFrom("notification").select("task_id").where("id", "=", notificationId) : trx.selectFrom("comment").select("task_id").where("id", "=", Number(commentId));
8184
- return trx.selectFrom("task").selectAll().where("id", "in", owner).executeTakeFirst();
8185
- }
8186
- /** Stop notifications acknowledged by the addressed session. */
8187
- async function acknowledgeNotification(trx, input) {
8188
- let query = trx.selectFrom("notification").selectAll().where("acked_at", "is", null);
8189
- if (input.blockId !== void 0) query = query.where("block_id", "=", input.blockId).where("kind", "=", "block");
8190
- else if (input.commentId !== void 0) query = query.where("comment_id", "=", input.commentId).where("kind", "=", "answer");
8191
- else return false;
8192
- const notices = await query.orderBy("id", "desc").execute();
8193
- const n = notices[0];
8194
- if (n === void 0) return false;
8195
- if (!await notificationAddressedTo(trx, n, input.actor)) throw new CommandError("forbidden", "Only the addressed task role can acknowledge.");
8196
- for (const notice of notices) {
8197
- await trx.updateTable("notification").set({ acked_at: input.at.toISOString() }).where("id", "=", notice.id).execute();
8198
- await journal$3(trx, notice, "doorbell_read", { doorbell: `N${String(notice.id)}` }, input.at);
8199
- const item = await trx.selectFrom("operator_item").select("id").where("item_key", "=", exhaustedItemKey(notice)).where("cleared_at", "is", null).executeTakeFirst();
8200
- if (item !== void 0) await clearItem(trx, item.id, input.at);
8201
- }
8202
- return true;
8203
- }
8204
- /** Use the same current recipient rule when listing and acknowledging an inbox notice. */
8205
- async function notificationAddressedTo(trx, n, actor) {
8206
- const parsed = parseActorId(actor);
8207
- if (parsed?.actor !== "agent") return false;
8208
- const linked = await trx.selectFrom("link").select("id").where("task_id", "=", n.task_id).where("entity", "=", "session").where("role", "=", "worker").where("banned", "=", 0).where("session_id", "=", parsed.actorRef.session).executeTakeFirst();
8209
- const selectedIsLive = n.recipient_session !== null && await liveSession(trx, n.recipient_session) !== void 0;
8210
- return n.recipient_session === null ? parsed.actorRef.session === n.author_session || linked !== void 0 : selectedIsLive ? parsed.actorRef.session === n.recipient_session : (await selectNotificationRecipient(trx, n))?.id === parsed.actorRef.session;
8211
- }
8212
- async function closeBlockNotification(trx, blockId, at) {
8213
- const closed = await trx.updateTable("notification").set({ acked_at: at.toISOString() }).where("block_id", "=", blockId).where("kind", "=", "block").where("acked_at", "is", null).returning(["kind", "source_key"]).execute();
8214
- for (const row of closed) {
8215
- const item = await trx.selectFrom("operator_item").select("id").where("item_key", "=", exhaustedItemKey(row)).where("cleared_at", "is", null).executeTakeFirst();
8216
- if (item !== void 0) await clearItem(trx, item.id, at);
8085
+ if (line !== null) item = await trx.updateTable("operator_item").set({ line_outbox_id: line }).where("id", "=", item.id).returningAll().executeTakeFirstOrThrow();
8217
8086
  }
8087
+ return item;
8218
8088
  }
8219
8089
  //#endregion
8220
8090
  //#region ../core/src/app/outbox.ts
@@ -8432,17 +8302,17 @@ async function blockPost(trx, row, payload, rule) {
8432
8302
  const taskId = "taskId" in payload && typeof payload.taskId === "number" ? payload.taskId : null;
8433
8303
  const blockId = "blockId" in payload && typeof payload.blockId === "number" ? payload.blockId : null;
8434
8304
  const task = taskId === null ? null : await trx.selectFrom("task").selectAll().where("id", "=", taskId).executeTakeFirstOrThrow();
8435
- await raiseItem(trx, {
8305
+ await raiseItemWith(trx, {
8436
8306
  itemKey: `secret-post:${createHash("sha256").update(row.dedupeKey).digest("hex")}`,
8437
8307
  kind: "post_blocked",
8438
8308
  text: `text on ${safeKey} not sent: looks like a secret (${rule}), read \`board task ${safeKey}\``,
8439
- url: task === null ? "" : taskUrl(task),
8309
+ url: task === null ? "" : taskUrl(task, scanConfig()),
8440
8310
  taskId,
8441
8311
  blockId,
8442
8312
  at: row.at,
8443
8313
  rule,
8444
8314
  source: row.kind
8445
- });
8315
+ }, enqueueFeedLine);
8446
8316
  }
8447
8317
  /**
8448
8318
  * Scans a stored gateway row's payload again before it is resent, with the rules used at
@@ -8642,102 +8512,10 @@ async function enqueueInboundDoorbell(trx, input) {
8642
8512
  });
8643
8513
  }
8644
8514
  //#endregion
8645
- //#region ../core/src/app/feed.ts
8646
- const NO_FEED = /* @__PURE__ */ new Set([
8647
- "post_failed",
8648
- "answer_undelivered",
8649
- "transport_health"
8650
- ]);
8651
- /** Display label of a feed line with no task; not part of the line's identity. */
8652
- const TASKLESS_FEED_KEY = "spur-board";
8653
- async function journal$2(trx, item, kind, at, rule, actor = "system") {
8654
- const parsed = parseActorId(actor);
8655
- if (parsed === null) throw new Error("Invalid journal actor");
8656
- const task = item.task_id === null ? void 0 : await trx.selectFrom("task").select(["project"]).where("id", "=", item.task_id).executeTakeFirstOrThrow();
8657
- await trx.insertInto("event").values({
8658
- at: at.toISOString(),
8659
- project: task?.project ?? "_board",
8660
- task_id: item.task_id,
8661
- kind,
8662
- actor: parsed.actor,
8663
- actor_ref: parsed.actor === "agent" ? JSON.stringify(parsed.actorRef) : null,
8664
- payload: toJson(eventPayloadSchemas[kind], {
8665
- item: `I${String(item.id)}`,
8666
- ...kind === "from_you_raised" && rule !== void 0 ? { rule } : {}
8667
- }),
8668
- v: 1,
8669
- request_id: null
8670
- }).execute();
8671
- }
8672
- /** Kinds whose item has a retry action besides `delivery:<id>` (see `items.ts`). */
8673
- const RETRY_KINDS = /* @__PURE__ */ new Set([
8674
- "answer_undelivered",
8675
- "worker_not_reading",
8676
- "inbound_failure"
8677
- ]);
8678
- /** Every item line gets Close, after Retry when its kind has a retry action. */
8679
- function itemActions(item) {
8680
- const id = String(item.id);
8681
- const close = {
8682
- id: `item:${id}:close`,
8683
- label: "Close"
8684
- };
8685
- if (item.kind === "token_request") return [
8686
- {
8687
- id: `token:${id}:approve`,
8688
- label: "Approve"
8689
- },
8690
- {
8691
- id: `token:${id}:deny`,
8692
- label: "Deny"
8693
- },
8694
- close
8695
- ];
8696
- return item.item_key.startsWith("delivery:") || RETRY_KINDS.has(item.kind) ? [{
8697
- id: `item:${id}:retry`,
8698
- label: "Retry"
8699
- }, close] : [close];
8700
- }
8701
- /** Raise one item generation. A repeated raise of an active key is idempotent. */
8702
- async function raiseItem(trx, input) {
8703
- const active = await trx.selectFrom("operator_item").selectAll().where("item_key", "=", input.itemKey).where("cleared_at", "is", null).executeTakeFirst();
8704
- if (active !== void 0) return active;
8705
- const previous = await trx.selectFrom("operator_item").select("raise_no").where("item_key", "=", input.itemKey).orderBy("raise_no", "desc").executeTakeFirst();
8706
- let item = await trx.insertInto("operator_item").values({
8707
- item_key: input.itemKey,
8708
- raise_no: (previous?.raise_no ?? 0) + 1,
8709
- kind: input.kind,
8710
- text: input.text,
8711
- url: input.url,
8712
- task_id: input.taskId,
8713
- block_id: input.blockId,
8714
- raised_at: input.at.toISOString(),
8715
- cleared_at: null,
8716
- line_outbox_id: null,
8717
- fingerprint: input.fingerprint ?? null,
8718
- fact_at: input.factAt ?? null,
8719
- source: input.source ?? null,
8720
- priority: input.priority ?? null,
8721
- inbound_event_json: null
8722
- }).returningAll().executeTakeFirstOrThrow();
8723
- await journal$2(trx, item, "from_you_raised", input.at, input.rule);
8724
- if (!NO_FEED.has(item.kind) && !input.suppressFeed) {
8725
- const key = (item.task_id === null ? null : await trx.selectFrom("task").select("key").where("id", "=", item.task_id).executeTakeFirstOrThrow())?.key ?? TASKLESS_FEED_KEY;
8726
- const line = await enqueueFeedLine(trx, {
8727
- itemId: item.id,
8728
- itemKey: item.item_key,
8729
- raise: item.raise_no,
8730
- key,
8731
- text: item.text,
8732
- title: `${key}: ${item.text}`,
8733
- url: item.url,
8734
- taskId: item.task_id,
8735
- actions: itemActions(item),
8736
- at: input.at
8737
- });
8738
- if (line !== null) item = await trx.updateTable("operator_item").set({ line_outbox_id: line }).where("id", "=", item.id).returningAll().executeTakeFirstOrThrow();
8739
- }
8740
- return item;
8515
+ //#region ../core/src/app/feed.ts
8516
+ /** Raise one item generation. A repeated raise of an active key is idempotent. */
8517
+ async function raiseItem(trx, input) {
8518
+ return raiseItemWith(trx, input, enqueueFeedLine);
8741
8519
  }
8742
8520
  /**
8743
8521
  * Clear an item once; the edit waits for its line and is cancelled with a stale pending line.
@@ -8746,14 +8524,14 @@ async function raiseItem(trx, input) {
8746
8524
  async function clearItem(trx, itemId, at, actor = "system") {
8747
8525
  if ((await trx.selectFrom("operator_item").selectAll().where("id", "=", itemId).executeTakeFirstOrThrow()).cleared_at !== null) return;
8748
8526
  const item = await trx.updateTable("operator_item").set({ cleared_at: at.toISOString() }).where("id", "=", itemId).returningAll().executeTakeFirstOrThrow();
8749
- await journal$2(trx, item, "from_you_cleared", at, void 0, actor);
8527
+ await journal$3(trx, item, "from_you_cleared", at, void 0, actor);
8750
8528
  if (item.line_outbox_id === null) return;
8751
8529
  const task = item.task_id === null ? null : await trx.selectFrom("task").select("key").where("id", "=", item.task_id).executeTakeFirstOrThrow();
8752
8530
  await enqueueFeedEdit(trx, {
8753
8531
  itemKey: item.item_key,
8754
8532
  raise: item.raise_no,
8755
8533
  lineId: item.line_outbox_id,
8756
- key: task?.key ?? TASKLESS_FEED_KEY,
8534
+ key: task?.key ?? "spur-board",
8757
8535
  taskId: item.task_id,
8758
8536
  at
8759
8537
  });
@@ -8788,10 +8566,10 @@ async function expireToken(trx, row, at) {
8788
8566
  await clearItem(trx, row.item_id, at);
8789
8567
  }
8790
8568
  /** Register a hash and its approval item together. The raw file secret never reaches this app. */
8791
- async function requestToken(store, input, at) {
8569
+ async function requestToken(store, config, input, at) {
8792
8570
  if (!/^[0-9a-f]{64}$/.test(input.hash) || input.name.trim() === "" || input.folder.trim() === "") throw new CommandError("usage", "Provide a name, folder and SHA-256 token hash.");
8793
8571
  const expiresAt = new Date(at.getTime() + REQUEST_LIFETIME_MS).toISOString();
8794
- return scanTransaction(store, async (trx) => {
8572
+ return scanTransaction(store, config, async (trx) => {
8795
8573
  const existing = await trx.selectFrom("operator_token").selectAll().where("name", "=", input.name).executeTakeFirst();
8796
8574
  const status = existing === void 0 ? void 0 : effectiveStatus(existing, at);
8797
8575
  if (status === "pending" || status === "approved" || status === "revoked") throw new CommandError("usage", `Token name ${input.name} is taken; choose another name (see \`board token list\`).`);
@@ -8854,10 +8632,10 @@ async function decideTokenInTransaction(trx, itemId, decision, at) {
8854
8632
  };
8855
8633
  }
8856
8634
  /** Clear unreviewed requests even when no approval button is pressed. */
8857
- async function expirePendingTokens(store, at) {
8635
+ async function expirePendingTokens(store, config, at) {
8858
8636
  const expiresAt = at.toISOString();
8859
8637
  if (await store.db.selectFrom("operator_token").select("id").where("status", "=", "pending").where("expires_at", "<=", expiresAt).executeTakeFirst() === void 0) return 0;
8860
- return scanTransaction(store, async (trx) => {
8638
+ return scanTransaction(store, config, async (trx) => {
8861
8639
  const rows = await trx.selectFrom("operator_token").select([
8862
8640
  "id",
8863
8641
  "name",
@@ -9071,7 +8849,7 @@ async function createApiServer(options) {
9071
8849
  if (!options.ready()) throw new CommandError("starting", "Wait until the daemon is ready.");
9072
8850
  const parsed = tokenRequestSchema.safeParse(request.body);
9073
8851
  if (!parsed.success) throw new CommandError("usage", "Provide a name, folder, host and token hash.");
9074
- const result = await requestToken(options.store, parsed.data, new Date(options.clock.now()));
8852
+ const result = await requestToken(options.store, options.config, parsed.data, new Date(options.clock.now()));
9075
8853
  return reply.send(successEnvelopeSchema.parse({
9076
8854
  ok: true,
9077
8855
  requestId: request.id,
@@ -9179,6 +8957,239 @@ function acknowledgeComment(revision, requested) {
9179
8957
  return requested;
9180
8958
  }
9181
8959
  //#endregion
8960
+ //#region ../core/src/app/doorbells.ts
8961
+ async function journal$2(trx, notification, kind, payload, at) {
8962
+ const task = await trx.selectFrom("task").select("project").where("id", "=", notification.task_id).executeTakeFirstOrThrow();
8963
+ await trx.insertInto("event").values({
8964
+ at: at.toISOString(),
8965
+ project: task.project,
8966
+ task_id: notification.task_id,
8967
+ kind,
8968
+ actor: "system",
8969
+ actor_ref: null,
8970
+ payload: toJson(eventPayloadSchemas[kind], payload),
8971
+ v: 1,
8972
+ request_id: null
8973
+ }).execute();
8974
+ }
8975
+ /** Register a worker-addressed block without manufacturing a comment. */
8976
+ async function registerBlockNotification(trx, block, at) {
8977
+ if (block.addressee_role !== "worker") return;
8978
+ await trx.insertInto("notification").values({
8979
+ source_key: `block:${String(block.id)}:worker`,
8980
+ kind: "block",
8981
+ task_id: block.task_id,
8982
+ block_id: block.id,
8983
+ comment_id: null,
8984
+ revision: null,
8985
+ role: "worker",
8986
+ author_session: null,
8987
+ recipient_session: null,
8988
+ next_at: at.toISOString(),
8989
+ last_outbox_id: null,
8990
+ acked_at: null,
8991
+ exhausted_at: null,
8992
+ created_at: at.toISOString()
8993
+ }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
8994
+ }
8995
+ /** Register an answer or clarification for the original author and its task role. */
8996
+ async function registerAnswerNotification(trx, input) {
8997
+ if (input.authorRole !== "worker") return;
8998
+ const parsed = parseActorId(input.block.author);
8999
+ if (parsed?.actor !== "agent") return;
9000
+ await trx.insertInto("notification").values({
9001
+ source_key: `comment:${String(input.commentId)}:${String(input.revision)}`,
9002
+ kind: "answer",
9003
+ task_id: input.block.task_id,
9004
+ block_id: input.block.id,
9005
+ comment_id: input.commentId,
9006
+ revision: input.revision,
9007
+ role: "worker",
9008
+ author_session: parsed.actorRef.session,
9009
+ recipient_session: null,
9010
+ next_at: input.at.toISOString(),
9011
+ last_outbox_id: null,
9012
+ acked_at: null,
9013
+ exhausted_at: null,
9014
+ created_at: input.at.toISOString()
9015
+ }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
9016
+ }
9017
+ async function liveSession(trx, id) {
9018
+ const row = await trx.selectFrom("session_snapshot").selectAll().where("id", "=", id).executeTakeFirst();
9019
+ return row?.ended_at === null && row.state !== "killed" && row.state !== "stopped" ? row : void 0;
9020
+ }
9021
+ /** Select the current live recipient for a semantic notification. */
9022
+ async function selectNotificationRecipient(trx, n) {
9023
+ if (n.author_session !== null) {
9024
+ const author = await liveSession(trx, n.author_session);
9025
+ if (author !== void 0) return author;
9026
+ }
9027
+ const links = await trx.selectFrom("link").select("session_id").where("task_id", "=", n.task_id).where("entity", "=", "session").where("role", "=", n.role === "worker" ? "worker" : "orchestrator").where("banned", "=", 0).orderBy("created_at", "desc").execute();
9028
+ for (const link of links) {
9029
+ if (link.session_id === null) continue;
9030
+ const session = await liveSession(trx, link.session_id);
9031
+ if (session !== void 0) return session;
9032
+ }
9033
+ }
9034
+ /** The operator item kind raised when a notification's rings are exhausted. */
9035
+ function exhaustedItemKind(n) {
9036
+ return n.kind === "answer" ? "answer_undelivered" : "worker_not_reading";
9037
+ }
9038
+ /** The operator item key raised when a notification's rings are exhausted. */
9039
+ function exhaustedItemKey(n) {
9040
+ return `${exhaustedItemKind(n)}:${n.source_key}`;
9041
+ }
9042
+ /**
9043
+ * Restart an exhausted, unacknowledged ring series at `at`. The recipient and last row stay, so
9044
+ * the next reconcile rings the same session under the next series key.
9045
+ */
9046
+ async function restartNotification(trx, sourceKey, at) {
9047
+ if (await trx.updateTable("notification").set({
9048
+ rings: 0,
9049
+ exhausted_at: null,
9050
+ next_at: at.toISOString()
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
+ }
9053
+ /** Reconcile due semantic notifications in the sender's claim transaction. */
9054
+ async function reconcileDoorbells(trx, at, config) {
9055
+ 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();
9056
+ for (const n of due) {
9057
+ const session = await selectNotificationRecipient(trx, n);
9058
+ if (session === void 0) {
9059
+ if (n.recipient_session !== null) await trx.updateTable("notification").set({
9060
+ recipient_session: null,
9061
+ rings: 0,
9062
+ last_outbox_id: null
9063
+ }).where("id", "=", n.id).execute();
9064
+ continue;
9065
+ }
9066
+ if (session.state === "working") continue;
9067
+ let rings = n.rings;
9068
+ let lastOutbox = n.last_outbox_id;
9069
+ if (session.id !== n.recipient_session) {
9070
+ if (lastOutbox !== null) await trx.updateTable("outbox").set({
9071
+ state: "dead",
9072
+ last_error: "recipient changed"
9073
+ }).where("id", "=", lastOutbox).where("state", "=", "pending").execute();
9074
+ rings = 0;
9075
+ lastOutbox = null;
9076
+ await trx.updateTable("notification").set({
9077
+ recipient_session: session.id,
9078
+ rings: 0,
9079
+ last_outbox_id: null
9080
+ }).where("id", "=", n.id).execute();
9081
+ }
9082
+ if (lastOutbox !== null) {
9083
+ const row = await trx.selectFrom("outbox").select("state").where("id", "=", lastOutbox).executeTakeFirst();
9084
+ if (row?.state === "pending" || row?.state === "in_flight") continue;
9085
+ }
9086
+ const task = await trx.selectFrom("task").selectAll().where("id", "=", n.task_id).executeTakeFirstOrThrow();
9087
+ const itemKey = exhaustedItemKey(n);
9088
+ if (rings >= 3) {
9089
+ await raiseItem(trx, {
9090
+ itemKey,
9091
+ kind: exhaustedItemKind(n),
9092
+ text: n.kind === "answer" ? `Answer to block B${String(n.block_id)} on ${task.key} was not read` : `worker ${session.id} is not reading block B${String(n.block_id)} on ${task.key}`,
9093
+ url: taskUrl(task, config),
9094
+ taskId: task.id,
9095
+ blockId: n.block_id,
9096
+ at
9097
+ });
9098
+ await trx.updateTable("notification").set({ exhausted_at: at.toISOString() }).where("id", "=", n.id).execute();
9099
+ await journal$2(trx, n, "doorbell_undelivered", {
9100
+ doorbell: `N${String(n.id)}`,
9101
+ reason: "unanswered"
9102
+ }, at);
9103
+ continue;
9104
+ }
9105
+ const raised = await trx.selectFrom("operator_item").select((eb) => eb.fn.max("raise_no").as("series")).where("item_key", "=", itemKey).executeTakeFirst();
9106
+ const archived = await trx.selectFrom("event").select((eb) => eb.fn.countAll().as("count")).where("task_id", "=", n.task_id).where("kind", "=", "task_archived").executeTakeFirst();
9107
+ const ring = rings + 1;
9108
+ const text = `${task.key} block B${String(n.block_id)}: check board inbox (N${String(n.id)}-${String(ring)})`;
9109
+ const outboxId = await enqueueDoorbell(trx, {
9110
+ notificationId: n.id,
9111
+ ring,
9112
+ session: session.id,
9113
+ text,
9114
+ at,
9115
+ series: raised?.series ?? 0,
9116
+ archives: archived?.count ?? 0
9117
+ });
9118
+ await trx.updateTable("notification").set({ last_outbox_id: outboxId }).where("id", "=", n.id).execute();
9119
+ }
9120
+ }
9121
+ /** Count one confirmed Spur send, regardless of transport attempts for its outbox row. */
9122
+ async function recordRingDelivery(trx, notificationId, ring, session, at, config) {
9123
+ const n = await trx.selectFrom("notification").selectAll().where("id", "=", notificationId).executeTakeFirst();
9124
+ if (n === void 0 || n.acked_at !== null || n.recipient_session !== session || n.rings >= ring) return;
9125
+ const pauses = [
9126
+ config.doorbells.firstRetryMs,
9127
+ config.doorbells.secondRetryMs,
9128
+ config.doorbells.unansweredAfterMs
9129
+ ];
9130
+ await trx.updateTable("notification").set({
9131
+ rings: ring,
9132
+ next_at: new Date(at.getTime() + (pauses[ring - 1] ?? 0)).toISOString()
9133
+ }).where("id", "=", notificationId).execute();
9134
+ await journal$2(trx, n, "doorbell_rung", {
9135
+ doorbell: `N${String(n.id)}`,
9136
+ addressee: n.role,
9137
+ attempt: ring
9138
+ }, at);
9139
+ }
9140
+ /** Confirm that a queued ring still belongs to a live, idle, unread recipient. */
9141
+ async function ringStillCurrent(trx, notificationId, sessionId) {
9142
+ const n = await trx.selectFrom("notification").selectAll().where("id", "=", notificationId).executeTakeFirst();
9143
+ if (n === void 0 || n.acked_at !== null || n.exhausted_at !== null || n.recipient_session !== sessionId) return "dead";
9144
+ const session = await selectNotificationRecipient(trx, n);
9145
+ if (session?.id !== sessionId) return "dead";
9146
+ return session.state === "working" ? "defer" : "send";
9147
+ }
9148
+ /**
9149
+ * The task of a ring: through its notification, or for an inbound author ring (no notification)
9150
+ * through the comment in its `doorbell:comment:<id>:` key. Archive kills only unclaimed rings;
9151
+ * the sender drops a claimed one of an archived task before its send starts.
9152
+ */
9153
+ async function ringTask(trx, notificationId, dedupeKey) {
9154
+ const commentId = /^doorbell:comment:(\d+):/.exec(dedupeKey)?.[1];
9155
+ if (notificationId === void 0 && commentId === void 0) return void 0;
9156
+ const owner = notificationId !== void 0 ? trx.selectFrom("notification").select("task_id").where("id", "=", notificationId) : trx.selectFrom("comment").select("task_id").where("id", "=", Number(commentId));
9157
+ return trx.selectFrom("task").selectAll().where("id", "in", owner).executeTakeFirst();
9158
+ }
9159
+ /** Stop notifications acknowledged by the addressed session. */
9160
+ async function acknowledgeNotification(trx, input) {
9161
+ let query = trx.selectFrom("notification").selectAll().where("acked_at", "is", null);
9162
+ if (input.blockId !== void 0) query = query.where("block_id", "=", input.blockId).where("kind", "=", "block");
9163
+ else if (input.commentId !== void 0) query = query.where("comment_id", "=", input.commentId).where("kind", "=", "answer");
9164
+ else return false;
9165
+ const notices = await query.orderBy("id", "desc").execute();
9166
+ const n = notices[0];
9167
+ if (n === void 0) return false;
9168
+ if (!await notificationAddressedTo(trx, n, input.actor)) throw new CommandError("forbidden", "Only the addressed task role can acknowledge.");
9169
+ for (const notice of notices) {
9170
+ await trx.updateTable("notification").set({ acked_at: input.at.toISOString() }).where("id", "=", notice.id).execute();
9171
+ await journal$2(trx, notice, "doorbell_read", { doorbell: `N${String(notice.id)}` }, input.at);
9172
+ const item = await trx.selectFrom("operator_item").select("id").where("item_key", "=", exhaustedItemKey(notice)).where("cleared_at", "is", null).executeTakeFirst();
9173
+ if (item !== void 0) await clearItem(trx, item.id, input.at);
9174
+ }
9175
+ return true;
9176
+ }
9177
+ /** Use the same current recipient rule when listing and acknowledging an inbox notice. */
9178
+ async function notificationAddressedTo(trx, n, actor) {
9179
+ const parsed = parseActorId(actor);
9180
+ if (parsed?.actor !== "agent") return false;
9181
+ const linked = await trx.selectFrom("link").select("id").where("task_id", "=", n.task_id).where("entity", "=", "session").where("role", "=", "worker").where("banned", "=", 0).where("session_id", "=", parsed.actorRef.session).executeTakeFirst();
9182
+ const selectedIsLive = n.recipient_session !== null && await liveSession(trx, n.recipient_session) !== void 0;
9183
+ return n.recipient_session === null ? parsed.actorRef.session === n.author_session || linked !== void 0 : selectedIsLive ? parsed.actorRef.session === n.recipient_session : (await selectNotificationRecipient(trx, n))?.id === parsed.actorRef.session;
9184
+ }
9185
+ async function closeBlockNotification(trx, blockId, at) {
9186
+ const closed = await trx.updateTable("notification").set({ acked_at: at.toISOString() }).where("block_id", "=", blockId).where("kind", "=", "block").where("acked_at", "is", null).returning(["kind", "source_key"]).execute();
9187
+ for (const row of closed) {
9188
+ const item = await trx.selectFrom("operator_item").select("id").where("item_key", "=", exhaustedItemKey(row)).where("cleared_at", "is", null).executeTakeFirst();
9189
+ if (item !== void 0) await clearItem(trx, item.id, at);
9190
+ }
9191
+ }
9192
+ //#endregion
9182
9193
  //#region ../core/src/app/blocks.ts
9183
9194
  const actorRefSchema$1 = z.strictObject({
9184
9195
  project: z.string().min(1),
@@ -10370,28 +10381,28 @@ function createSender(options) {
10370
10381
  async function runTick(signal) {
10371
10382
  if (signal?.aborted) return;
10372
10383
  const claimedAt = now().getTime();
10373
- const { claims, ranThreshold } = await scanTransaction(store, (trx) => claim(trx, claimedAt));
10384
+ const { claims, ranThreshold } = await scanTransaction(store, options.config, (trx) => claim(trx, claimedAt));
10374
10385
  if (ranThreshold) downRecorded = true;
10375
10386
  for (const [i, c] of claims.entries()) {
10376
10387
  if (signal?.aborted) {
10377
10388
  const ids = claims.slice(i).map((c) => c.id);
10378
- await scanTransaction(store, (trx) => trx.updateTable("outbox").set((eb) => ({
10389
+ await scanTransaction(store, options.config, (trx) => trx.updateTable("outbox").set((eb) => ({
10379
10390
  state: "pending",
10380
10391
  attempts: eb("attempts", "-", 1)
10381
10392
  })).where("id", "in", ids).where("state", "=", "in_flight").execute());
10382
10393
  return;
10383
10394
  }
10384
- const started = await scanTransaction(store, (trx) => start(trx, c));
10395
+ const started = await scanTransaction(store, options.config, (trx) => start(trx, c));
10385
10396
  if (started.skip) continue;
10386
10397
  const { outcome, error } = await attempt(c, started.firstDeliveryAt);
10387
10398
  const at = now().getTime();
10388
- await scanTransaction(store, (trx) => record(trx, c, outcome, error, at, started.at));
10399
+ await scanTransaction(store, options.config, (trx) => record(trx, c, outcome, error, at, started.at));
10389
10400
  }
10390
10401
  }
10391
10402
  return {
10392
10403
  async recover() {
10393
10404
  const nowIso = now().toISOString();
10394
- const failed = await scanTransaction(store, async (trx) => {
10405
+ const failed = await scanTransaction(store, options.config, async (trx) => {
10395
10406
  const rows = await trx.selectFrom("outbox").select([
10396
10407
  "id",
10397
10408
  "kind",
@@ -10415,7 +10426,7 @@ function createSender(options) {
10415
10426
  });
10416
10427
  for (let i = 0; i < failed.length; i += RECOVER_BATCH) {
10417
10428
  const batch = failed.slice(i, i + RECOVER_BATCH);
10418
- await scanTransaction(store, (trx) => requeuePostFailed(trx, batch, nowIso));
10429
+ await scanTransaction(store, options.config, (trx) => requeuePostFailed(trx, batch, nowIso));
10419
10430
  }
10420
10431
  },
10421
10432
  tick(signal) {
@@ -10432,7 +10443,7 @@ function createSender(options) {
10432
10443
  downSince = void 0;
10433
10444
  downRecorded = false;
10434
10445
  if (gateway === void 0) return;
10435
- await scanTransaction(store, async (trx) => {
10446
+ await scanTransaction(store, options.config, async (trx) => {
10436
10447
  if ((await trx.deleteFrom("transport_health").where("gateway", "=", gatewayKind).where("reason", "=", "down").returning("space").execute()).length > 0) await syncTransportItem(trx, gatewayKind, at);
10437
10448
  });
10438
10449
  });
@@ -12014,7 +12025,7 @@ function createObservationCore(deps) {
12014
12025
  },
12015
12026
  async observe(source, observation) {
12016
12027
  const { batch } = observation;
12017
- await scanTransaction(store, async (trx) => {
12028
+ await scanTransaction(store, config, async (trx) => {
12018
12029
  await sourceState(trx, source, observation.state, batch.observedAt, batch.cursor);
12019
12030
  for (const outcome of observation.outcomes) {
12020
12031
  const answer = batch.entities.find((entity) => refKey(entity.ref) === refKey(outcome.ref));
@@ -12119,13 +12130,13 @@ function createObservationCore(deps) {
12119
12130
  if (observation.effectiveComplete) completeSince.set(source, batch.observedAt);
12120
12131
  },
12121
12132
  reportSourceState(source, state) {
12122
- return scanTransaction(store, async (trx) => {
12133
+ return scanTransaction(store, config, async (trx) => {
12123
12134
  await sourceState(trx, source, state);
12124
12135
  await reconcileItems(trx, config, clock.now(), completeSince.has("spur"));
12125
12136
  });
12126
12137
  },
12127
12138
  notice(kind, value) {
12128
- return scanTransaction(store, async (trx) => {
12139
+ return scanTransaction(store, config, async (trx) => {
12129
12140
  const key = `spur-notice:${kind}:${value}`;
12130
12141
  if (await trx.selectFrom("meta").select("key").where("key", "=", key).executeTakeFirst() !== void 0) return;
12131
12142
  await trx.insertInto("meta").values({
@@ -12184,7 +12195,7 @@ async function tickBoard(deps) {
12184
12195
  const now = clock.now();
12185
12196
  const at = new Date(now).toISOString();
12186
12197
  const slot = new Date(lastArchiveSlot(now, config)).toISOString();
12187
- await scanTransaction(store, async (trx) => {
12198
+ await scanTransaction(store, config, async (trx) => {
12188
12199
  const sourceStates = await trx.selectFrom("source_state").select(["source", "blind_reason"]).execute();
12189
12200
  const blind = new Set(sourceStates.filter((source) => source.blind_reason !== null).map((source) => source.source));
12190
12201
  const tasks = await trx.selectFrom("task").selectAll().where("membership", "!=", "archived").execute();
@@ -12766,7 +12777,7 @@ function createInbound(input) {
12766
12777
  });
12767
12778
  }
12768
12779
  async function recordFailure(event, error, at) {
12769
- await scanTransaction(store, async (trx) => {
12780
+ await scanTransaction(store, config, async (trx) => {
12770
12781
  const context = await taskContext(trx, event, gateway.kind);
12771
12782
  await journal(trx, {
12772
12783
  kind: "inbound_failed",
@@ -12797,7 +12808,7 @@ function createInbound(input) {
12797
12808
  let response = "not allowed";
12798
12809
  if (event.sourceSpace === "feed") try {
12799
12810
  const at = new Date(clock.now()).toISOString();
12800
- response = (await scanTransaction(store, (trx) => decideToken(trx, event.dedupeKey, token, at)))?.response ?? "not available yet";
12811
+ response = (await scanTransaction(store, config, (trx) => decideToken(trx, event.dedupeKey, token, at)))?.response ?? "not available yet";
12801
12812
  } catch (error) {
12802
12813
  if (!(error instanceof CommandError)) await recordFailure(event, error, new Date(clock.now()).toISOString());
12803
12814
  response = error instanceof CommandError ? error.hint : "not available yet";
@@ -12845,7 +12856,7 @@ function createInbound(input) {
12845
12856
  const at = new Date(clock.now()).toISOString();
12846
12857
  const actor = event.kind === "message_deleted" || event.author === config.operator.slack ? "operator" : "system";
12847
12858
  try {
12848
- const result = await scanTransaction(store, (trx) => replayOperation(trx, {
12859
+ const result = await scanTransaction(store, config, (trx) => replayOperation(trx, {
12849
12860
  actor,
12850
12861
  key: event.dedupeKey,
12851
12862
  operation: operationId(event),
@@ -12863,7 +12874,7 @@ function createInbound(input) {
12863
12874
  }
12864
12875
  async function applyGap(event) {
12865
12876
  const at = new Date(clock.now()).toISOString();
12866
- await scanTransaction(store, async (trx) => {
12877
+ await scanTransaction(store, config, async (trx) => {
12867
12878
  const context = await taskContext(trx, event, gateway.kind);
12868
12879
  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();
12869
12880
  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();
@@ -12916,7 +12927,7 @@ function createInbound(input) {
12916
12927
  retryStored(itemId) {
12917
12928
  return serial(async () => {
12918
12929
  const at = new Date(clock.now()).toISOString();
12919
- await scanTransaction(store, async (trx) => {
12930
+ await scanTransaction(store, config, async (trx) => {
12920
12931
  await reapply(trx, itemId, at);
12921
12932
  await clearItem(trx, itemId, new Date(at));
12922
12933
  });
@@ -13381,11 +13392,12 @@ function connectionWire(node) {
13381
13392
  pageInfo: pageInfoWire
13382
13393
  });
13383
13394
  }
13384
- function teamNameScopeDenied(error, query) {
13385
- if (error.type !== "INSUFFICIENT_SCOPES" || !query.includes("... on Team { name }")) return false;
13386
- if (error.path !== void 0) return error.path.includes("reviewRequests") && error.path.includes("requestedReviewer") && error.path.at(-1) === "name";
13387
- return /\bname\b/i.test(error.message) && /\bread:(?:org|discussion)\b/i.test(error.message);
13395
+ function teamScopeDenied(error, query) {
13396
+ if (error.type !== "INSUFFICIENT_SCOPES" || !query.includes("... on Team { slug }")) return false;
13397
+ if (error.path !== void 0) return error.path.includes("reviewRequests") && error.path.includes("requestedReviewer") && error.path.at(-1) === "slug";
13398
+ return /\b(?:slug|name)\b/i.test(error.message) && /\bread:(?:org|discussion)\b/i.test(error.message);
13388
13399
  }
13400
+ const REVIEWER_FIELDS = "requestedReviewer { __typename ... on Bot { login } ... on Mannequin { login } ... on User { login } ... on Team { slug } ... on EnterpriseTeam { slug } } asCodeOwner";
13389
13401
  const CLOSING_FIELDS = "nodes { number repository { nameWithOwner } } pageInfo { hasNextPage endCursor }";
13390
13402
  const prFields = (number, closing = false) => `id number url title updatedAt state isDraft mergeable mergeStateStatus
13391
13403
  author { login } headRefName headRefOid
@@ -13395,7 +13407,7 @@ const prFields = (number, closing = false) => `id number url title updatedAt sta
13395
13407
  } pageInfo { hasNextPage endCursor } } }
13396
13408
  reviews(first: 100) { nodes { author { login } state commit { oid } submittedAt } pageInfo { hasNextPage endCursor } }
13397
13409
  reviewThreads(first: 100) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
13398
- reviewRequests(first: 100) { nodes { requestedReviewer { ... on User { login } ... on Team { name } } asCodeOwner } pageInfo { hasNextPage endCursor } }${closing ? `\n closingIssuesReferences(first: 100) { ${CLOSING_FIELDS} }` : ""}`;
13410
+ reviewRequests(first: 100) { nodes { ${REVIEWER_FIELDS} } pageInfo { hasNextPage endCursor } }${closing ? `\n closingIssuesReferences(first: 100) { ${CLOSING_FIELDS} }` : ""}`;
13399
13411
  const DISCOVERY_FIELDS = `nodes { number updatedAt author { login } state } pageInfo { hasNextPage endCursor }`;
13400
13412
  function aliases(numbers, closing = false) {
13401
13413
  return numbers.map((number, i) => `pr${String(i)}: repository(owner: $owner, name: $repo) { pullRequest(number: ${String(number)}) { ${prFields(number, closing)} } }`).join("\n");
@@ -13408,7 +13420,7 @@ function detailQuery(numbers, closing = false) {
13408
13420
  }
13409
13421
  function pageQuery(connection, bootstrap = false) {
13410
13422
  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} } } }`;
13411
- 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 } }`} } } }`;
13423
+ 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 } }`} } } }`;
13412
13424
  }
13413
13425
  var GithubClient = class {
13414
13426
  token;
@@ -13454,7 +13466,7 @@ var GithubClient = class {
13454
13466
  status: 429,
13455
13467
  headers: response.headers
13456
13468
  }, Date.now());
13457
- if (errors.some((error) => teamNameScopeDenied(error, query))) throw new AdapterError("auth", "GitHub token needs read:org for team review requests");
13469
+ if (errors.some((error) => teamScopeDenied(error, query))) throw new AdapterError("auth", "GitHub token needs read:org for team review requests");
13458
13470
  if (errors.some((error) => error.type === "INSUFFICIENT_SCOPES")) throw new AdapterError("auth", "GitHub token lacks a required GraphQL read scope");
13459
13471
  const data = parseWire(dataWire, wire.data, MALFORMED$3, ["data"]);
13460
13472
  return {
@@ -13543,6 +13555,21 @@ const reviewWire = z.object({
13543
13555
  submittedAt: z.string().nullish()
13544
13556
  }).refine((review) => review.commit !== null || !review.author?.login || review.submittedAt == null || !KEPT_REVIEWS.includes(review.state.toLowerCase()), { path: ["commit"] });
13545
13557
  const nodes = (node) => z.object({ nodes: z.array(node) });
13558
+ const loginReviewer = (type) => z.object({
13559
+ __typename: z.literal(type),
13560
+ login: z.string()
13561
+ });
13562
+ const slugReviewer = (type) => z.object({
13563
+ __typename: z.literal(type),
13564
+ slug: z.string()
13565
+ });
13566
+ const reviewerWire = z.discriminatedUnion("__typename", [
13567
+ loginReviewer("User"),
13568
+ loginReviewer("Mannequin"),
13569
+ loginReviewer("Bot"),
13570
+ slugReviewer("Team"),
13571
+ slugReviewer("EnterpriseTeam")
13572
+ ]).nullable();
13546
13573
  const closingWire = z.object({ nodes: z.array(z.object({
13547
13574
  number: z.int().positive(),
13548
13575
  repository: z.object({ nameWithOwner: z.string() }).nullish()
@@ -13563,10 +13590,7 @@ const prWire = z.object({
13563
13590
  reviews: nodes(reviewWire),
13564
13591
  reviewThreads: nodes(z.object({ isResolved: z.boolean() })),
13565
13592
  reviewRequests: nodes(z.object({
13566
- requestedReviewer: z.object({
13567
- login: z.string().nullish(),
13568
- name: z.string().nullish()
13569
- }),
13593
+ requestedReviewer: reviewerWire,
13570
13594
  asCodeOwner: z.boolean()
13571
13595
  })),
13572
13596
  closingIssuesReferences: closingWire
@@ -13739,6 +13763,25 @@ function prKeys(rule, title, branch, refs) {
13739
13763
  default: return assertNever(rule);
13740
13764
  }
13741
13765
  }
13766
+ function reviewer(wire) {
13767
+ switch (wire.__typename) {
13768
+ case "User":
13769
+ case "Mannequin": return {
13770
+ kind: "user",
13771
+ id: wire.login
13772
+ };
13773
+ case "Bot": return {
13774
+ kind: "bot",
13775
+ id: wire.login
13776
+ };
13777
+ case "Team":
13778
+ case "EnterpriseTeam": return {
13779
+ kind: "team",
13780
+ id: wire.slug
13781
+ };
13782
+ default: return assertNever(wire);
13783
+ }
13784
+ }
13742
13785
  function normalizePr(repo, value, rule) {
13743
13786
  const wire = parseWire(prWire, value, "Malformed GitHub PR response");
13744
13787
  const checks = latestChecks(wire.statusCheckRollup?.contexts.nodes ?? []);
@@ -13771,10 +13814,10 @@ function normalizePr(repo, value, rule) {
13771
13814
  ...checks,
13772
13815
  reviews: latestReviews(wire.reviews.nodes),
13773
13816
  reviewThreads: wire.reviewThreads.nodes.map((node) => ({ resolved: node.isResolved })),
13774
- reviewRequests: wire.reviewRequests.nodes.map((node) => ({
13775
- reviewer: node.requestedReviewer.login ?? node.requestedReviewer.name,
13776
- asCodeOwner: node.asCodeOwner
13777
- })),
13817
+ reviewRequests: wire.reviewRequests.nodes.flatMap(({ requestedReviewer, asCodeOwner }) => requestedReviewer === null ? [] : [{
13818
+ ...reviewer(requestedReviewer),
13819
+ asCodeOwner
13820
+ }]),
13778
13821
  ticketKeys: prKeys(rule, title, headBranch, closingRefs(wire.closingIssuesReferences)),
13779
13822
  updatedAt: wire.updatedAt
13780
13823
  };
@@ -13864,6 +13907,22 @@ function withConnection(pr, field, connection) {
13864
13907
  [field]: connection
13865
13908
  };
13866
13909
  }
13910
+ function content(read) {
13911
+ try {
13912
+ return read();
13913
+ } catch (error) {
13914
+ if (error instanceof AdapterError) return error;
13915
+ throw error;
13916
+ }
13917
+ }
13918
+ const malformedPaging = () => ({
13919
+ status: "malformed",
13920
+ error: new AdapterError("transient", "Malformed GitHub pagination")
13921
+ });
13922
+ function pageCursor(connection) {
13923
+ const { hasNextPage, endCursor } = connection.pageInfo;
13924
+ return hasNextPage && !endCursor ? null : nextPage(connection);
13925
+ }
13867
13926
  async function fullPr(client, first, owner, name, number, signal, budget) {
13868
13927
  let pr = first;
13869
13928
  for (const field of [
@@ -13875,10 +13934,11 @@ async function fullPr(client, first, owner, name, number, signal, budget) {
13875
13934
  ]) {
13876
13935
  let target = connectionOf(pr, field);
13877
13936
  if (target === void 0) continue;
13878
- let cursor = nextPage(target);
13937
+ let cursor = pageCursor(target);
13938
+ if (cursor === null) return malformedPaging();
13879
13939
  const seen = /* @__PURE__ */ new Set();
13880
13940
  while (cursor !== void 0) {
13881
- if (seen.has(cursor)) throw new AdapterError("transient", "Malformed GitHub pagination");
13941
+ if (seen.has(cursor)) return malformedPaging();
13882
13942
  seen.add(cursor);
13883
13943
  const response = await client.query(pageQuery(field), {
13884
13944
  owner,
@@ -13890,19 +13950,28 @@ async function fullPr(client, first, owner, name, number, signal, budget) {
13890
13950
  rejectUnscoped(response.errors, ["repository"]);
13891
13951
  requireCheckAccess(response.errors);
13892
13952
  const denied = response.errors.some(deniedReference);
13893
- if (withoutDeniedReferences(response.errors).length > 0) return void 0;
13894
- const page = connectionOf(parseWire(pageRootWire, response.data.repository, MALFORMED$2, ["data", "repository"]).pullRequest, field);
13953
+ if (withoutDeniedReferences(response.errors).length > 0) return { status: "denied" };
13954
+ const root = content(() => parseWire(pageRootWire, response.data.repository, MALFORMED$2, ["data", "repository"]));
13955
+ if (root instanceof AdapterError) return {
13956
+ status: "malformed",
13957
+ error: root
13958
+ };
13959
+ const page = connectionOf(root.pullRequest, field);
13895
13960
  if (page === void 0 && denied && field === "closingIssuesReferences") break;
13896
- if (page === void 0) throw new AdapterError("transient", "Malformed GitHub pagination");
13961
+ if (page === void 0) return malformedPaging();
13897
13962
  target = {
13898
13963
  nodes: [...target.nodes, ...page.nodes],
13899
13964
  pageInfo: page.pageInfo
13900
13965
  };
13901
13966
  pr = withConnection(pr, field, target);
13902
- cursor = nextPage(page);
13967
+ cursor = pageCursor(page);
13968
+ if (cursor === null) return malformedPaging();
13903
13969
  }
13904
13970
  }
13905
- return pr;
13971
+ return {
13972
+ status: "ok",
13973
+ pr
13974
+ };
13906
13975
  }
13907
13976
  async function pollRepository({ id, repo, login, keys, client, ctx }) {
13908
13977
  const observedAt = sourceCursorSchema.parse((/* @__PURE__ */ new Date()).toISOString());
@@ -13949,6 +14018,20 @@ async function pollRepository({ id, repo, login, keys, client, ctx }) {
13949
14018
  if (!discoveryOk) complete = false;
13950
14019
  const found = discover(nodes, ctx.cursor, login);
13951
14020
  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;
14021
+ let parseError;
14022
+ let parseFailedRefs = 0;
14023
+ const malformed = (error, ref) => {
14024
+ parseError ??= error;
14025
+ complete = false;
14026
+ if (ref) {
14027
+ entities.push({
14028
+ ref,
14029
+ status: "no_access"
14030
+ });
14031
+ parseFailedRefs += 1;
14032
+ }
14033
+ return false;
14034
+ };
13952
14035
  const process = async (number, alias, data, scopedErrors, ref) => {
13953
14036
  const errors = withoutDeniedReferences(scopedErrors);
13954
14037
  requireCheckAccess(errors);
@@ -13962,7 +14045,9 @@ async function pollRepository({ id, repo, login, keys, client, ctx }) {
13962
14045
  });
13963
14046
  return false;
13964
14047
  }
13965
- const wire = parseWire(aliasWire, data[alias], MALFORMED$2, ["data", alias])?.pullRequest;
14048
+ const root = content(() => parseWire(aliasWire, data[alias], MALFORMED$2, ["data", alias]));
14049
+ if (root instanceof AdapterError) return malformed(root, ref);
14050
+ const wire = root?.pullRequest;
13966
14051
  if (wire === null || wire === void 0) {
13967
14052
  if (ref) entities.push({
13968
14053
  ref,
@@ -13974,7 +14059,7 @@ async function pollRepository({ id, repo, login, keys, client, ctx }) {
13974
14059
  const full = await fullPr(client, wire, owner, name, number, ctx.signal, (next) => {
13975
14060
  budget = next;
13976
14061
  });
13977
- if (full === void 0) {
14062
+ if (full.status === "denied") {
13978
14063
  complete = false;
13979
14064
  if (ref) entities.push({
13980
14065
  ref,
@@ -13982,7 +14067,9 @@ async function pollRepository({ id, repo, login, keys, client, ctx }) {
13982
14067
  });
13983
14068
  return false;
13984
14069
  }
13985
- const facts = normalizePr(ref?.repo ?? repo, full, keys);
14070
+ if (full.status === "malformed") return malformed(full.error, ref);
14071
+ const facts = content(() => normalizePr(ref?.repo ?? repo, full.pr, keys));
14072
+ if (facts instanceof AdapterError) return malformed(facts, ref);
13986
14073
  items.push({
13987
14074
  kind: "pr",
13988
14075
  facts
@@ -14014,6 +14101,7 @@ async function pollRepository({ id, repo, login, keys, client, ctx }) {
14014
14101
  }
14015
14102
  }
14016
14103
  if (ctx.signal.aborted) throw new AdapterError("transient", "GitHub poll aborted");
14104
+ if (parseError !== void 0 && items.length === 0 && entities.length === parseFailedRefs) throw parseError;
14017
14105
  const nextCursor = bootstrap ? bootstrapCursor : found.cursor;
14018
14106
  return {
14019
14107
  source: id,
@@ -16410,7 +16498,7 @@ const GITHUB_PROBE = `query DoctorGithubPermissions($owner: String!, $repo: Stri
16410
16498
  pullRequests(first: 10, states: [OPEN], orderBy: {field: UPDATED_AT, direction: DESC}) {
16411
16499
  nodes {
16412
16500
  statusCheckRollup { contexts(first: 100) { nodes { ... on CheckRun { name } } } }
16413
- reviewRequests(first: 100) { nodes { requestedReviewer { ... on Team { name } } } }
16501
+ reviewRequests(first: 100) { nodes { requestedReviewer { ... on Team { slug } } } }
16414
16502
  }
16415
16503
  }
16416
16504
  defaultBranchRef { target { ... on Commit {
@@ -16427,7 +16515,7 @@ function scopedGithubError(value) {
16427
16515
  if (!Array.isArray(path)) return null;
16428
16516
  const fields = path.filter((part) => typeof part === "string");
16429
16517
  if (error?.["type"] === "FORBIDDEN" && fields.includes("statusCheckRollup") && fields.includes("contexts")) return GITHUB_CHECKS_FIX;
16430
- if (error?.["type"] === "INSUFFICIENT_SCOPES" && fields.includes("reviewRequests") && fields.includes("requestedReviewer") && fields.includes("name")) return GITHUB_TEAMS_FIX;
16518
+ if (error?.["type"] === "INSUFFICIENT_SCOPES" && fields.includes("reviewRequests") && fields.includes("requestedReviewer") && fields.includes("slug")) return GITHUB_TEAMS_FIX;
16431
16519
  return null;
16432
16520
  }
16433
16521
  async function deadlineCall(ctx, name, failure, call) {
@@ -16900,7 +16988,7 @@ function createOutboxModule(ctx, gateway, options = {}) {
16900
16988
  const tick = () => {
16901
16989
  if (stopped || signal?.aborted) return active;
16902
16990
  active = active.then(() => ctx.logCall("outbox.tick", async () => {
16903
- await expirePendingTokens(ctx.store, new Date(ctx.clock.now()));
16991
+ await expirePendingTokens(ctx.store, ctx.config, new Date(ctx.clock.now()));
16904
16992
  if (!signal?.aborted) await sender.tick(signal);
16905
16993
  })).catch(() => void 0);
16906
16994
  return active;