spur-board 0.28.0 → 0.30.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-29M9Njzi.mjs";
1
+ import { A as errorCodeOf, C as SESSION_STATUSES, D as ticketFactsSchema, E as sessionFactsSchema, F as err, G as configSchema, K as requiredSecretKeys, M as parseRef$1, N as taskKeySchema, O as actorIdSchema, P as ERRORS, R as ok, S as SESSION_HEALTH_STATES, T as prRefSchema, U as DEFAULT_SLACK_COMMAND, V as DEFAULT_LINK, W as RESERVED_PROJECT, _ 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, q as SLACK_BOT_SCOPES, s as sourceCursorSchema, t as assertNever, u as OPERATIONS, v as messageRefSchema, w as prFactsSchema, x as eventPayloadSchemas, y as userIdSchema, z as successEnvelopeSchema } from "./src-B63VaSzU.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { closeSync, existsSync, fstatSync, fsyncSync, ftruncateSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeSync } from "node:fs";
@@ -43,6 +43,7 @@ var __require = /* #__PURE__ */ (() => createRequire(import.meta.url))();
43
43
  //#region ../contracts/src/gateway/gateway.ts
44
44
  const PERSONA_ROLES = [
45
45
  "orchestrator",
46
+ "curator",
46
47
  "worker",
47
48
  "board"
48
49
  ];
@@ -8190,32 +8191,137 @@ async function dispatchOperation(deps, id, input, actor, key) {
8190
8191
  return operation.kind === "query" ? createQuery(deps)(handler, input, actor) : createApply(deps)(handler, input, actor, key);
8191
8192
  }
8192
8193
  //#endregion
8193
- //#region ../core/src/app/item-raise.ts
8194
- const NO_FEED = /* @__PURE__ */ new Set([
8194
+ //#region ../core/src/domain/fromYou.ts
8195
+ /** Every operator item kind; `ITEM_POLICY` must give each one a policy. */
8196
+ const ITEM_KINDS = [
8197
+ "token_request",
8198
+ "post_blocked",
8195
8199
  "post_failed",
8200
+ "transport_health",
8196
8201
  "answer_undelivered",
8197
- "transport_health"
8198
- ]);
8202
+ "worker_not_reading",
8203
+ "answer_author_unavailable",
8204
+ "inbound_failure",
8205
+ "inbound_gap",
8206
+ "board_observation",
8207
+ "worker_ended"
8208
+ ];
8209
+ const ITEM_POLICY = {
8210
+ token_request: {
8211
+ retry: "none",
8212
+ feed: true,
8213
+ priority: 4,
8214
+ buttons: "approve_deny",
8215
+ reconciled: false
8216
+ },
8217
+ post_blocked: {
8218
+ retry: "never_sent",
8219
+ feed: true,
8220
+ priority: 4,
8221
+ buttons: "item",
8222
+ reconciled: false
8223
+ },
8224
+ post_failed: {
8225
+ retry: "requeue_post",
8226
+ feed: false,
8227
+ priority: 1,
8228
+ buttons: "item",
8229
+ reconciled: true
8230
+ },
8231
+ transport_health: {
8232
+ retry: "probe_transport",
8233
+ feed: false,
8234
+ priority: 1,
8235
+ buttons: "item",
8236
+ reconciled: false
8237
+ },
8238
+ answer_undelivered: {
8239
+ retry: "restart_ring",
8240
+ feed: false,
8241
+ priority: 4,
8242
+ buttons: "item",
8243
+ reconciled: false
8244
+ },
8245
+ worker_not_reading: {
8246
+ retry: "restart_ring",
8247
+ feed: true,
8248
+ priority: 4,
8249
+ buttons: "item",
8250
+ reconciled: false
8251
+ },
8252
+ answer_author_unavailable: {
8253
+ retry: "none",
8254
+ feed: true,
8255
+ priority: 4,
8256
+ buttons: "item",
8257
+ reconciled: false
8258
+ },
8259
+ inbound_failure: {
8260
+ retry: "reapply_inbound",
8261
+ feed: true,
8262
+ priority: 4,
8263
+ buttons: "item",
8264
+ reconciled: false
8265
+ },
8266
+ inbound_gap: {
8267
+ retry: "none",
8268
+ feed: true,
8269
+ priority: 4,
8270
+ buttons: "item",
8271
+ reconciled: false
8272
+ },
8273
+ board_observation: {
8274
+ retry: "none",
8275
+ feed: true,
8276
+ priority: 4,
8277
+ buttons: "item",
8278
+ reconciled: true
8279
+ },
8280
+ worker_ended: {
8281
+ retry: "none",
8282
+ feed: false,
8283
+ priority: 4,
8284
+ buttons: "item",
8285
+ reconciled: true
8286
+ }
8287
+ };
8288
+ /** Guards a stored kind: the column is free text and old or hand-written rows may hold others. */
8289
+ function isItemKind(kind) {
8290
+ return Object.hasOwn(ITEM_POLICY, kind);
8291
+ }
8292
+ /** Whether the kind's feed line and status entry offer Retry. */
8293
+ function hasRetryButton(kind) {
8294
+ const retry = ITEM_POLICY[kind].retry;
8295
+ return retry === "requeue_post" || retry === "restart_ring" || retry === "reapply_inbound" || retry === "probe_transport";
8296
+ }
8297
+ /** The kinds `reconcileItems` owns: it clears an active one whose candidate is gone. */
8298
+ const RECONCILED_KINDS = ITEM_KINDS.filter((kind) => ITEM_POLICY[kind].reconciled);
8299
+ function fingerprint(candidate) {
8300
+ return createHash("sha256").update(JSON.stringify([
8301
+ candidate.key,
8302
+ candidate.summary,
8303
+ candidate.source,
8304
+ candidate.revision ?? null
8305
+ ])).digest("hex");
8306
+ }
8307
+ /** Stable ordering within priority, then by item identity. */
8308
+ function orderItems(items) {
8309
+ return [...items].sort((left, right) => left.priority - right.priority || left.key.localeCompare(right.key));
8310
+ }
8199
8311
  async function journal$3(trx, item, kind, at, rule, actor = "system") {
8200
8312
  await emit(trx, kind, (item.task_id === null ? void 0 : await trx.selectFrom("task").select(["project"]).where("id", "=", item.task_id).executeTakeFirstOrThrow())?.project ?? "_board", item.task_id, at.toISOString(), {
8201
8313
  item: `I${String(item.id)}`,
8202
8314
  ...kind === "from_you_raised" && rule !== void 0 ? { rule } : {}
8203
8315
  }, actor);
8204
8316
  }
8205
- /** Kinds whose item has a retry action besides `delivery:<id>` (see `items.ts`). */
8206
- const RETRY_KINDS = /* @__PURE__ */ new Set([
8207
- "answer_undelivered",
8208
- "worker_not_reading",
8209
- "inbound_failure"
8210
- ]);
8211
8317
  /** Every item line gets Close, after Retry when its kind has a retry action. */
8212
- function itemActions(item) {
8213
- const id = String(item.id);
8318
+ function itemActions(itemId, kind) {
8319
+ const id = String(itemId);
8214
8320
  const close = {
8215
8321
  id: `item:${id}:close`,
8216
8322
  label: "Close"
8217
8323
  };
8218
- if (item.kind === "token_request") return [
8324
+ if (ITEM_POLICY[kind].buttons === "approve_deny") return [
8219
8325
  {
8220
8326
  id: `token:${id}:approve`,
8221
8327
  label: "Approve"
@@ -8226,7 +8332,7 @@ function itemActions(item) {
8226
8332
  },
8227
8333
  close
8228
8334
  ];
8229
- return item.item_key.startsWith("delivery:") || RETRY_KINDS.has(item.kind) ? [{
8335
+ return hasRetryButton(kind) ? [{
8230
8336
  id: `item:${id}:retry`,
8231
8337
  label: "Retry"
8232
8338
  }, close] : [close];
@@ -8253,11 +8359,11 @@ async function raiseItemWith(trx, input, writeLine) {
8253
8359
  fingerprint: input.fingerprint ?? null,
8254
8360
  fact_at: input.factAt ?? null,
8255
8361
  source: input.source ?? null,
8256
- priority: input.priority ?? null,
8362
+ priority: input.priority ?? ITEM_POLICY[input.kind].priority,
8257
8363
  inbound_event_json: null
8258
8364
  }).returningAll().executeTakeFirstOrThrow();
8259
8365
  await journal$3(trx, item, "from_you_raised", input.at, input.rule);
8260
- if (!NO_FEED.has(item.kind) && !input.suppressFeed) {
8366
+ if (ITEM_POLICY[input.kind].feed) {
8261
8367
  const key = (item.task_id === null ? null : await trx.selectFrom("task").select("key").where("id", "=", item.task_id).executeTakeFirstOrThrow())?.key ?? "spur-board";
8262
8368
  const line = await writeLine(trx, {
8263
8369
  itemId: item.id,
@@ -8268,7 +8374,7 @@ async function raiseItemWith(trx, input, writeLine) {
8268
8374
  title: `${key}: ${item.text}`,
8269
8375
  url: item.url,
8270
8376
  taskId: item.task_id,
8271
- actions: itemActions(item),
8377
+ actions: itemActions(item.id, input.kind),
8272
8378
  at: input.at
8273
8379
  });
8274
8380
  if (line !== null) item = await trx.updateTable("operator_item").set({ line_outbox_id: line }).where("id", "=", item.id).returningAll().executeTakeFirstOrThrow();
@@ -10193,7 +10299,7 @@ async function archiveTask(trx, input) {
10193
10299
  };
10194
10300
  const blocks = await trx.selectFrom("block").selectAll().where("task_id", "=", task.id).where("state", "=", "open").orderBy("id").execute();
10195
10301
  for (const block of blocks) await closeOpenBlock(trx, task, block, ctx, "archived", null);
10196
- const items = await trx.selectFrom("operator_item").select("id").where("kind", "=", "board_observation").where("task_id", "=", task.id).where("cleared_at", "is", null).orderBy("id").execute();
10302
+ const items = await trx.selectFrom("operator_item").select("id").where("kind", "in", RECONCILED_KINDS).where("task_id", "=", task.id).where("cleared_at", "is", null).orderBy("id").execute();
10197
10303
  for (const item of items) await clearItem(trx, item.id, new Date(at), actor);
10198
10304
  const comments = await trx.selectFrom("comment").select("id").where("task_id", "=", task.id).execute();
10199
10305
  await trx.updateTable("outbox").set({
@@ -10309,20 +10415,6 @@ function createMembershipMutations(config) {
10309
10415
  };
10310
10416
  }
10311
10417
  //#endregion
10312
- //#region ../core/src/domain/fromYou.ts
10313
- function fingerprint(candidate) {
10314
- return createHash("sha256").update(JSON.stringify([
10315
- candidate.key,
10316
- candidate.summary,
10317
- candidate.source,
10318
- candidate.revision ?? null
10319
- ])).digest("hex");
10320
- }
10321
- /** Stable ordering within priority, then by item identity. */
10322
- function orderItems(items) {
10323
- return [...items].sort((left, right) => left.priority - right.priority || left.key.localeCompare(right.key));
10324
- }
10325
- //#endregion
10326
10418
  //#region ../core/src/app/sender.ts
10327
10419
  /**
10328
10420
  * Spur refused a doorbell for good (a permanent 4xx): the sender stops ringing and ends the ring
@@ -10383,8 +10475,6 @@ async function syncTransportItem(trx, gateway, at) {
10383
10475
  url: "",
10384
10476
  taskId: null,
10385
10477
  blockId: null,
10386
- priority: 1,
10387
- suppressFeed: true,
10388
10478
  at
10389
10479
  });
10390
10480
  if (item.text !== text) await trx.updateTable("operator_item").set({ text }).where("id", "=", item.id).execute();
@@ -10976,7 +11066,6 @@ function createSender(options) {
10976
11066
  }
10977
11067
  //#endregion
10978
11068
  //#region ../core/src/app/items.ts
10979
- const DOORBELL_ITEM = /^(?:answer_undelivered|worker_not_reading):(.+)$/;
10980
11069
  async function loadItem(trx, id) {
10981
11070
  const item = await trx.selectFrom("operator_item").selectAll().where("id", "=", Number(id.slice(1))).executeTakeFirst();
10982
11071
  if (item === void 0) throw new CommandError("not_found", "Check the item ID.");
@@ -10987,7 +11076,7 @@ async function loadItem(trx, id) {
10987
11076
  }
10988
11077
  /** The task a `delivery:<outbox id>` item's row belongs to; the item itself has no task. */
10989
11078
  async function deliveryTask(trx, item) {
10990
- if (!item.item_key.startsWith("delivery:")) return void 0;
11079
+ if (item.kind !== "post_failed") return void 0;
10991
11080
  const row = await trx.selectFrom("outbox").select([
10992
11081
  "kind",
10993
11082
  "dedupe_key",
@@ -11015,25 +11104,34 @@ function notApplicable(hint) {
11015
11104
  * except a retry on a transport item, which the sender clears when the transport is back.
11016
11105
  */
11017
11106
  function createItemMutations(deps) {
11107
+ /** Runs the retry behind the item's kind; false when the item must stay raised. */
11018
11108
  async function retryAction(trx, item, at) {
11019
11109
  const closeHint = `close it with \`board item close I${String(item.id)}\`.`;
11020
- if (item.item_key.startsWith("delivery:")) {
11021
- if (await requeuePostFailed(trx, [Number(item.item_key.slice(9))], at) === 0) throw notApplicable("The delivery is no longer failed.");
11022
- return;
11023
- }
11024
- const doorbell = DOORBELL_ITEM.exec(item.item_key);
11025
- if (doorbell?.[1] !== void 0) {
11026
- await restartNotification(trx, doorbell[1], new Date(at));
11027
- return;
11028
- }
11029
- if (item.kind === "inbound_failure") {
11030
- const reapply = deps.reapplyInbound?.();
11031
- if (reapply === void 0) throw notApplicable("Slack inbound is not running; close the item instead.");
11032
- await reapply(trx, item.id, at);
11033
- return;
11110
+ const noAction = notApplicable(`This item has no retry action; ${closeHint}`);
11111
+ const action = isItemKind(item.kind) ? ITEM_POLICY[item.kind].retry : "none";
11112
+ switch (action) {
11113
+ case "requeue_post":
11114
+ if (await requeuePostFailed(trx, [Number(item.item_key.slice(9))], at) === 0) throw notApplicable("The delivery is no longer failed.");
11115
+ return true;
11116
+ case "restart_ring": {
11117
+ const prefix = `${item.kind}:`;
11118
+ if (!item.item_key.startsWith(prefix) || item.item_key.length === prefix.length) throw noAction;
11119
+ await restartNotification(trx, item.item_key.slice(prefix.length), new Date(at));
11120
+ return true;
11121
+ }
11122
+ case "reapply_inbound": {
11123
+ const reapply = deps.reapplyInbound?.();
11124
+ if (reapply === void 0) throw notApplicable("Slack inbound is not running; close the item instead.");
11125
+ await reapply(trx, item.id, at);
11126
+ return true;
11127
+ }
11128
+ case "probe_transport":
11129
+ if (await retryTransport(trx, item.item_key.slice(10), at) === 0) throw notApplicable("No transport outage is recorded; the item clears on its own.");
11130
+ return false;
11131
+ case "never_sent": throw notApplicable(`The blocked text is never sent; ${closeHint}`);
11132
+ case "none": throw noAction;
11133
+ default: return assertNever(action);
11034
11134
  }
11035
- if (item.kind === "post_blocked") throw notApplicable(`The blocked text is never sent; ${closeHint}`);
11036
- throw notApplicable(`This item has no retry action; ${closeHint}`);
11037
11135
  }
11038
11136
  return {
11039
11137
  retry: {
@@ -11043,12 +11141,7 @@ function createItemMutations(deps) {
11043
11141
  const { item, task } = await loadItem(trx, input.item);
11044
11142
  if ((task ?? await deliveryTask(trx, item))?.membership === "archived") throw new CommandError("task_archived", "Add the task again before retrying its item.");
11045
11143
  if (item.cleared_at !== null) throw notApplicable("The item is already cleared.");
11046
- if (item.kind === "transport_health") {
11047
- if (await retryTransport(trx, item.item_key.slice(10), ctx.at) === 0) throw notApplicable("No transport outage is recorded; the item clears on its own.");
11048
- return view(item, task);
11049
- }
11050
- await retryAction(trx, item, ctx.at);
11051
- await clearItem(trx, item.id, new Date(ctx.at), ctx.actor);
11144
+ if (await retryAction(trx, item, ctx.at)) await clearItem(trx, item.id, new Date(ctx.at), ctx.actor);
11052
11145
  return view(item, task);
11053
11146
  }
11054
11147
  },
@@ -11060,11 +11153,8 @@ function createItemMutations(deps) {
11060
11153
  if (item.cleared_at === null) {
11061
11154
  const hash = item.fingerprint ?? fingerprint({
11062
11155
  key: item.item_key,
11063
- taskId: item.task_id,
11064
11156
  summary: item.text,
11065
- factAt: item.fact_at,
11066
11157
  source: item.source,
11067
- priority: item.priority ?? 0,
11068
11158
  revision: null
11069
11159
  });
11070
11160
  await trx.insertInto("dismissal").values({
@@ -11077,7 +11167,7 @@ function createItemMutations(deps) {
11077
11167
  dismissed_by: ctx.actor,
11078
11168
  dismissed_at: ctx.at
11079
11169
  })).execute();
11080
- if (item.item_key.startsWith("delivery:")) await trx.updateTable("outbox").set({
11170
+ if (item.kind === "post_failed") await trx.updateTable("outbox").set({
11081
11171
  state: "dead",
11082
11172
  last_error: `closed by ${ctx.actor} (I${String(item.id)})`
11083
11173
  }).where("id", "=", Number(item.item_key.slice(9))).where("state", "=", "post_failed").execute();
@@ -11965,8 +12055,10 @@ async function reconcileItems(trx, config, now, spurComplete) {
11965
12055
  const sourceById = new Map(sources.map((state) => [state.source, state]));
11966
12056
  for (const source of sources) {
11967
12057
  if (source.blind_reason === null) continue;
12058
+ if (source.blind_reason === "stale" && source.source !== "spur") continue;
11968
12059
  candidates.push({
11969
12060
  key: `source:${source.source}`,
12061
+ kind: "board_observation",
11970
12062
  taskId: null,
11971
12063
  summary: `${source.source}: ${source.blind_message ?? source.blind_reason}`,
11972
12064
  factAt: source.observed_at,
@@ -11978,7 +12070,7 @@ async function reconcileItems(trx, config, now, spurComplete) {
11978
12070
  const taskById = new Map(tasks.map((task) => [task.id, task]));
11979
12071
  const misses = await trx.selectFrom("source_miss").selectAll().execute();
11980
12072
  for (const miss of misses) {
11981
- if (miss.outcome !== "not_found" && miss.outcome !== "no_access" && miss.gone !== 1) continue;
12073
+ if (miss.gone !== 1) continue;
11982
12074
  const ref = JSON.parse(miss.ref);
11983
12075
  if (ref.kind === "pr" && ref.repo !== void 0 && ref.number !== void 0) {
11984
12076
  const links = await trx.selectFrom("link").select("task_id").where("entity", "=", "pr").where(sql`lower(repo) = ${ref.repo.toLowerCase()}`).where("number", "=", ref.number).execute();
@@ -11987,6 +12079,7 @@ async function reconcileItems(trx, config, now, spurComplete) {
11987
12079
  if (task === void 0) continue;
11988
12080
  candidates.push({
11989
12081
  key: `pr-outcome:${String(task.id)}:${ref.repo}#${String(ref.number)}`,
12082
+ kind: "board_observation",
11990
12083
  taskId: task.id,
11991
12084
  summary: `${task.key}: linked pull request ${miss.outcome ?? "gone"}`,
11992
12085
  factAt: sourceById.get(miss.source)?.observed_at ?? null,
@@ -11997,10 +12090,11 @@ async function reconcileItems(trx, config, now, spurComplete) {
11997
12090
  continue;
11998
12091
  }
11999
12092
  if (ref.kind !== "ticket") continue;
12000
- const task = tasks.find((entry) => entry.key === ref.key && (entry.manual_include === 1 || miss.outcome === "no_access" || miss.gone === 1));
12093
+ const task = tasks.find((entry) => entry.key === ref.key);
12001
12094
  if (task === void 0) continue;
12002
12095
  candidates.push({
12003
12096
  key: `lookup:${String(task.id)}`,
12097
+ kind: "board_observation",
12004
12098
  taskId: task.id,
12005
12099
  summary: `${task.key}: tracker returned ${miss.outcome ?? "gone"}`,
12006
12100
  factAt: sourceById.get(miss.source)?.observed_at ?? null,
@@ -12010,6 +12104,7 @@ async function reconcileItems(trx, config, now, spurComplete) {
12010
12104
  }
12011
12105
  for (const task of tasks) if (task.membership === "out_of_filter") candidates.push({
12012
12106
  key: `filter:${String(task.id)}`,
12107
+ kind: "board_observation",
12013
12108
  taskId: task.id,
12014
12109
  summary: `${task.key} left the tracker filter while work is still linked`,
12015
12110
  factAt: task.last_change_at,
@@ -12024,6 +12119,7 @@ async function reconcileItems(trx, config, now, spurComplete) {
12024
12119
  if (task === void 0) continue;
12025
12120
  if (block.addressee_role === "operator" && block.author !== "operator" && !blockedIds.has(block.id)) candidates.push({
12026
12121
  key: `operator-block:${String(block.id)}`,
12122
+ kind: "board_observation",
12027
12123
  taskId: task.id,
12028
12124
  summary: `${task.key}: ${block.reason}`,
12029
12125
  factAt: block.created_at,
@@ -12032,6 +12128,7 @@ async function reconcileItems(trx, config, now, spurComplete) {
12032
12128
  });
12033
12129
  if (now - Date.parse(block.created_at) >= config.thresholds.blockOpenMs) candidates.push({
12034
12130
  key: `block:${String(block.id)}`,
12131
+ kind: "board_observation",
12035
12132
  taskId: task.id,
12036
12133
  summary: `${task.key}: block has been open for more than a day`,
12037
12134
  factAt: block.created_at,
@@ -12042,12 +12139,12 @@ async function reconcileItems(trx, config, now, spurComplete) {
12042
12139
  const failedDeliveries = await trx.selectFrom("outbox").select(["id", "kind"]).where("state", "=", "post_failed").execute();
12043
12140
  for (const delivery of failedDeliveries) candidates.push({
12044
12141
  key: `delivery:${String(delivery.id)}`,
12142
+ kind: "post_failed",
12045
12143
  taskId: null,
12046
12144
  summary: `Delivery failed: ${delivery.kind}`,
12047
12145
  factAt: null,
12048
12146
  source: null,
12049
- priority: 1,
12050
- suppressFeed: delivery.kind === "feed.line" || delivery.kind === "feed.line.edit"
12147
+ priority: ITEM_POLICY.post_failed.priority
12051
12148
  });
12052
12149
  const subjects = (await trx.selectFrom("link").innerJoin("session_snapshot", "session_snapshot.id", "link.session_id").select([
12053
12150
  "link.task_id",
@@ -12090,15 +12187,6 @@ async function reconcileItems(trx, config, now, spurComplete) {
12090
12187
  key: "host_load_episode",
12091
12188
  value: toJson(episodeSchema, health.episode)
12092
12189
  }).onConflict((oc) => oc.column("key").doUpdateSet({ value: toJson(episodeSchema, health.episode) })).execute();
12093
- if (health.hostLoad !== null) candidates.push({
12094
- key: "host-load",
12095
- taskId: null,
12096
- summary: "Host under load",
12097
- factAt: health.episode === null ? null : new Date(health.episode.startedAt).toISOString(),
12098
- source: "spur",
12099
- priority: 4,
12100
- revision: health.episode === null ? null : String(health.episode.startedAt)
12101
- });
12102
12190
  for (const flag of health.flags) {
12103
12191
  const task = taskById.get(Number(flag.taskId));
12104
12192
  if (task === void 0) continue;
@@ -12106,13 +12194,13 @@ async function reconcileItems(trx, config, now, spurComplete) {
12106
12194
  const endedLabel = ENDED_WORKER_LABELS[flag.kind];
12107
12195
  candidates.push({
12108
12196
  key: healthKey(task.id, flag),
12197
+ kind: flag.kind === "worker_completed" || flag.kind === "worker_killed" ? "worker_ended" : "board_observation",
12109
12198
  taskId: task.id,
12110
12199
  summary: `${task.key}: ${endedLabel ?? flag.kind.replaceAll("_", " ")} (${flag.sessionId})`,
12111
12200
  factAt: fact?.healthSince ?? null,
12112
12201
  source: "spur",
12113
12202
  priority: 4,
12114
- revision: endedLabel === void 0 ? fact?.healthSince ?? null : fact?.endedAt ?? null,
12115
- suppressFeed: flag.kind === "worker_completed" || flag.kind === "worker_killed"
12203
+ revision: endedLabel === void 0 ? fact?.healthSince ?? null : fact?.endedAt ?? null
12116
12204
  });
12117
12205
  }
12118
12206
  const ordered = orderItems(candidates);
@@ -12121,15 +12209,16 @@ async function reconcileItems(trx, config, now, spurComplete) {
12121
12209
  const task = taskById.get(Number(flag.taskId));
12122
12210
  if (task !== void 0) seen.add(healthKey(task.id, flag));
12123
12211
  }
12124
- const existing = await trx.selectFrom("operator_item").selectAll().where("kind", "=", "board_observation").where("cleared_at", "is", null).execute();
12212
+ const existing = await trx.selectFrom("operator_item").selectAll().where("kind", "in", RECONCILED_KINDS).where("cleared_at", "is", null).execute();
12125
12213
  for (const item of existing) if (!seen.has(item.item_key)) await clearItem(trx, item.id, new Date(now));
12126
12214
  for (const candidate of ordered) {
12127
12215
  const hash = fingerprint(candidate);
12128
12216
  const old = existing.find((item) => item.item_key === candidate.key);
12129
12217
  const dismissal = await trx.selectFrom("dismissal").select("fingerprint").where("item_key", "=", candidate.key).executeTakeFirst();
12130
- if (old !== void 0 && (dismissal?.fingerprint === hash || old.fingerprint !== hash)) await clearItem(trx, old.id, new Date(now));
12218
+ const kept = old !== void 0 && old.fingerprint === hash && old.kind === candidate.kind;
12219
+ if (old !== void 0 && (dismissal?.fingerprint === hash || !kept)) await clearItem(trx, old.id, new Date(now));
12131
12220
  if (dismissal?.fingerprint === hash) continue;
12132
- if (old !== void 0 && old.fingerprint === hash) {
12221
+ if (kept) {
12133
12222
  if (old.fact_at !== candidate.factAt || old.source !== candidate.source) await trx.updateTable("operator_item").set({
12134
12223
  fact_at: candidate.factAt,
12135
12224
  source: candidate.source
@@ -12139,7 +12228,7 @@ async function reconcileItems(trx, config, now, spurComplete) {
12139
12228
  const task = candidate.taskId === null ? null : taskById.get(candidate.taskId);
12140
12229
  await raiseItem(trx, {
12141
12230
  itemKey: candidate.key,
12142
- kind: "board_observation",
12231
+ kind: candidate.kind,
12143
12232
  text: candidate.summary,
12144
12233
  url: task === null || task === void 0 ? "https://github.com" : taskUrl(task, config),
12145
12234
  taskId: candidate.taskId,
@@ -12148,8 +12237,7 @@ async function reconcileItems(trx, config, now, spurComplete) {
12148
12237
  fingerprint: hash,
12149
12238
  factAt: candidate.factAt,
12150
12239
  source: candidate.source,
12151
- priority: candidate.priority,
12152
- suppressFeed: candidate.suppressFeed ?? false
12240
+ priority: candidate.priority
12153
12241
  });
12154
12242
  }
12155
12243
  }
@@ -13979,6 +14067,8 @@ function teamScopeDenied(error, query) {
13979
14067
  return /\b(?:slug|name)\b/i.test(error.message) && /\bread:(?:org|discussion)\b/i.test(error.message);
13980
14068
  }
13981
14069
  const REVIEWER_FIELDS = "requestedReviewer { __typename ... on Bot { login } ... on Mannequin { login } ... on User { login } ... on Team { slug } ... on EnterpriseTeam { slug } } asCodeOwner";
14070
+ const REVIEW_FIELDS = "id author { __typename login } state commit { oid } submittedAt";
14071
+ const COMMENT_FIELDS = "nodes { id author { __typename login } createdAt } pageInfo { hasPreviousPage startCursor }";
13982
14072
  const CLOSING_FIELDS = "nodes { number repository { nameWithOwner } } pageInfo { hasNextPage endCursor }";
13983
14073
  const prFields = (number, closing = false) => `id number url title updatedAt state isDraft mergeable mergeStateStatus
13984
14074
  author { login } headRefName headRefOid
@@ -13986,7 +14076,8 @@ const prFields = (number, closing = false) => `id number url title updatedAt sta
13986
14076
  ... on CheckRun { __typename name status conclusion startedAt completedAt checkSuite { createdAt } isRequired(pullRequestNumber: ${String(number)}) }
13987
14077
  ... on StatusContext { __typename context state createdAt isRequired(pullRequestNumber: ${String(number)}) }
13988
14078
  } pageInfo { hasNextPage endCursor } } }
13989
- reviews(first: 100) { nodes { author { login } state commit { oid } submittedAt } pageInfo { hasNextPage endCursor } }
14079
+ reviews(first: 100) { nodes { ${REVIEW_FIELDS} } pageInfo { hasNextPage endCursor } }
14080
+ comments(last: 100) { ${COMMENT_FIELDS} }
13990
14081
  reviewThreads(first: 100) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
13991
14082
  reviewRequests(first: 100) { nodes { ${REVIEWER_FIELDS} } pageInfo { hasNextPage endCursor } }${closing ? `\n closingIssuesReferences(first: 100) { ${CLOSING_FIELDS} }` : ""}`;
13992
14083
  const DISCOVERY_FIELDS = `nodes { number updatedAt author { login } state } pageInfo { hasNextPage endCursor }`;
@@ -14000,8 +14091,9 @@ function detailQuery(numbers, closing = false) {
14000
14091
  return `query PrDetails($owner: String!, $repo: String!) { rateLimit { remaining resetAt } ${aliases(numbers, closing)} }`;
14001
14092
  }
14002
14093
  function pageQuery(connection, bootstrap = false) {
14094
+ if (connection === "comments") return `query PrPage($owner: String!, $repo: String!, $number: Int!, $before: String!) { rateLimit { remaining resetAt } repository(owner: $owner, name: $repo) { pullRequest(number: $number) { comments(last: 100, before: $before) { ${COMMENT_FIELDS} } } } }`;
14003
14095
  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} } } }`;
14004
- 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 } }`} } } }`;
14096
+ return `query PrPage($owner: String!, $repo: String!, $number: Int!, $after: String!) { rateLimit { remaining resetAt } repository(owner: $owner, name: $repo) { pullRequest(number: $number) { ${connection === "closingIssuesReferences" ? `closingIssuesReferences(first: 100, after: $after) { ${CLOSING_FIELDS} }` : connection === "contexts" ? `statusCheckRollup { contexts(first: 100, after: $after) { nodes { ... on CheckRun { __typename name status conclusion startedAt completedAt checkSuite { createdAt } isRequired(pullRequestNumber: $number) } ... on StatusContext { __typename context state createdAt isRequired(pullRequestNumber: $number) } } pageInfo { hasNextPage endCursor } } }` : `${connection}(first: 100, after: $after) { nodes { ${connection === "reviews" ? REVIEW_FIELDS : connection === "reviewThreads" ? "isResolved" : REVIEWER_FIELDS} } pageInfo { hasNextPage endCursor } }`} } } }`;
14005
14097
  }
14006
14098
  var GithubClient = class {
14007
14099
  token;
@@ -14113,6 +14205,10 @@ const KEPT_REVIEWS = [
14113
14205
  "dismissed"
14114
14206
  ];
14115
14207
  const actor = z.object({ login: z.string().optional() }).nullish();
14208
+ const typedActor = z.object({
14209
+ __typename: z.string(),
14210
+ login: z.string().min(1)
14211
+ }).nullable();
14116
14212
  const checkRunWire = z.object({
14117
14213
  __typename: z.literal("CheckRun"),
14118
14214
  name: z.string(),
@@ -14132,12 +14228,18 @@ const statusContextWire = z.object({
14132
14228
  });
14133
14229
  const contextWire = z.discriminatedUnion("__typename", [checkRunWire, statusContextWire]);
14134
14230
  const reviewWire = z.object({
14135
- author: actor,
14231
+ id: z.string().min(1),
14232
+ author: typedActor,
14136
14233
  state: z.string(),
14137
14234
  commit: z.object({ oid: z.string() }).nullable(),
14138
14235
  submittedAt: z.string().nullish()
14139
14236
  }).refine((review) => review.commit !== null || !review.author?.login || review.submittedAt == null || !KEPT_REVIEWS.includes(review.state.toLowerCase()), { path: ["commit"] });
14140
14237
  const nodes = (node) => z.object({ nodes: z.array(node) });
14238
+ const commentWire = z.object({
14239
+ id: z.string().min(1),
14240
+ author: typedActor,
14241
+ createdAt: z.iso.datetime()
14242
+ });
14141
14243
  const loginReviewer = (type) => z.object({
14142
14244
  __typename: z.literal(type),
14143
14245
  login: z.string()
@@ -14171,6 +14273,7 @@ const prWire = z.object({
14171
14273
  headRefOid: z.string(),
14172
14274
  statusCheckRollup: z.object({ contexts: nodes(contextWire) }).nullish(),
14173
14275
  reviews: nodes(reviewWire),
14276
+ comments: nodes(commentWire),
14174
14277
  reviewThreads: nodes(z.object({ isResolved: z.boolean() })),
14175
14278
  reviewRequests: nodes(z.object({
14176
14279
  requestedReviewer: reviewerWire,
@@ -14286,6 +14389,35 @@ function latestReviews(nodes) {
14286
14389
  }
14287
14390
  return [...latest.values()].sort((a, b) => a.reviewer.localeCompare(b.reviewer));
14288
14391
  }
14392
+ function feedbackAuthor(wire) {
14393
+ return wire === null ? null : {
14394
+ login: wire.login,
14395
+ type: wire.__typename === "Bot" ? "bot" : "user"
14396
+ };
14397
+ }
14398
+ function feedbackOf(reviews, comments) {
14399
+ const entries = /* @__PURE__ */ new Map();
14400
+ const add = (entry) => {
14401
+ entries.set(`${entry.kind}:${entry.id}`, entry);
14402
+ };
14403
+ for (const node of comments) add({
14404
+ kind: "comment",
14405
+ id: node.id,
14406
+ author: feedbackAuthor(node.author),
14407
+ postedAt: node.createdAt
14408
+ });
14409
+ for (const node of reviews) {
14410
+ if (node.submittedAt == null) continue;
14411
+ add({
14412
+ kind: "review",
14413
+ id: node.id,
14414
+ author: feedbackAuthor(node.author),
14415
+ postedAt: node.submittedAt
14416
+ });
14417
+ }
14418
+ const tie = (entry) => `${entry.id}\u0000${entry.kind}`;
14419
+ return [...entries.values()].sort((a, b) => Date.parse(a.postedAt) - Date.parse(b.postedAt) || (tie(a) < tie(b) ? -1 : tie(a) > tie(b) ? 1 : 0));
14420
+ }
14289
14421
  function ticketKeys(title, branch, prefixes) {
14290
14422
  return scanKeys(`${title} ${branch}`, prefixes);
14291
14423
  }
@@ -14365,7 +14497,8 @@ function reviewer(wire) {
14365
14497
  default: return assertNever(wire);
14366
14498
  }
14367
14499
  }
14368
- function normalizePr(repo, value, rule) {
14500
+ /** `feedbackComplete` says whether the comments in `value` reach back to the cursor or start. */
14501
+ function normalizePr(repo, value, rule, feedbackComplete) {
14369
14502
  const wire = parseWire(prWire, value, "Malformed GitHub PR response");
14370
14503
  const checks = latestChecks(wire.statusCheckRollup?.contexts.nodes ?? []);
14371
14504
  const state = wire.state === "MERGED" ? "merged" : wire.state === "CLOSED" ? "closed" : "open";
@@ -14402,7 +14535,9 @@ function normalizePr(repo, value, rule) {
14402
14535
  asCodeOwner
14403
14536
  }]),
14404
14537
  ticketKeys: prKeys(rule, title, headBranch, closingRefs(wire.closingIssuesReferences)),
14405
- updatedAt: wire.updatedAt
14538
+ updatedAt: wire.updatedAt,
14539
+ feedback: feedbackOf(wire.reviews.nodes, wire.comments.nodes),
14540
+ feedbackComplete
14406
14541
  };
14407
14542
  const parsed = prFactsSchema.safeParse(facts);
14408
14543
  if (!parsed.success) throw new AdapterError("transient", "Malformed GitHub PR facts", { cause: parsed.error });
@@ -14414,8 +14549,16 @@ const MALFORMED$2 = "Malformed GitHub response";
14414
14549
  const discoveryRootWire = z.object({ pullRequests: connectionWire(discoveryNodeWire) });
14415
14550
  const baselineRootWire = z.object({ mergedBaseline: z.object({ nodes: z.array(baselineNodeWire) }) });
14416
14551
  const pagingWire = connectionWire(z.unknown());
14552
+ const backPagingWire = z.object({
14553
+ nodes: z.array(commentWire),
14554
+ pageInfo: z.object({
14555
+ hasPreviousPage: z.boolean(),
14556
+ startCursor: z.string().nullable()
14557
+ })
14558
+ });
14417
14559
  const prPagingWire = z.looseObject({
14418
14560
  reviews: pagingWire,
14561
+ comments: backPagingWire,
14419
14562
  reviewThreads: pagingWire,
14420
14563
  reviewRequests: pagingWire,
14421
14564
  statusCheckRollup: z.object({ contexts: pagingWire }).nullish(),
@@ -14423,6 +14566,8 @@ const prPagingWire = z.looseObject({
14423
14566
  });
14424
14567
  const aliasWire = z.object({ pullRequest: prPagingWire.nullish() }).nullish();
14425
14568
  const pageRootWire = z.object({ pullRequest: prPagingWire.partial() });
14569
+ const commentsRootWire = z.object({ pullRequest: z.object({ comments: backPagingWire }) });
14570
+ const FEEDBACK_PAGES = 3;
14426
14571
  function sourceId(project, repo) {
14427
14572
  return `github:${project}:${repo.toLowerCase()}`;
14428
14573
  }
@@ -14451,6 +14596,15 @@ function githubSources(config, options) {
14451
14596
  client,
14452
14597
  now: options.now,
14453
14598
  ctx
14599
+ }),
14600
+ pollPr: (ref, ctx) => pollOnePr({
14601
+ id,
14602
+ repo,
14603
+ keys,
14604
+ client,
14605
+ now: options.now,
14606
+ ref,
14607
+ signal: ctx.signal
14454
14608
  })
14455
14609
  }
14456
14610
  });
@@ -14557,6 +14711,142 @@ async function fullPr(client, first, owner, name, number, signal, budget) {
14557
14711
  pr
14558
14712
  };
14559
14713
  }
14714
+ function reachesCursor(nodes, cursor) {
14715
+ if (cursor === void 0) return false;
14716
+ const postedAt = Date.parse(cursor.postedAt);
14717
+ return nodes.some((node) => node.id === cursor.id || Date.parse(node.createdAt) < postedAt);
14718
+ }
14719
+ /**
14720
+ * Reads comments back from `first` to `cursor`, or to the start of the PR, within
14721
+ * `FEEDBACK_PAGES`. A transient failure keeps the comments read so far as incomplete; every
14722
+ * other failure, and any failure after an abort, rejects the poll.
14723
+ */
14724
+ async function readFeedback(client, first, owner, name, number, cursor, signal, budget) {
14725
+ let nodes = first.nodes;
14726
+ let page = first;
14727
+ const seen = /* @__PURE__ */ new Set();
14728
+ try {
14729
+ for (let pages = 1; page.pageInfo.hasPreviousPage && !reachesCursor(page.nodes, cursor); pages += 1) {
14730
+ const before = page.pageInfo.startCursor;
14731
+ if (!before || seen.has(before) || pages >= FEEDBACK_PAGES) return {
14732
+ nodes,
14733
+ complete: false
14734
+ };
14735
+ seen.add(before);
14736
+ const response = await client.query(pageQuery("comments"), {
14737
+ owner,
14738
+ repo: name,
14739
+ number,
14740
+ before
14741
+ }, signal);
14742
+ budget(response.budget);
14743
+ rejectUnscoped(response.errors, ["repository"]);
14744
+ if (response.errors.length > 0) return {
14745
+ nodes,
14746
+ complete: false
14747
+ };
14748
+ page = parseWire(commentsRootWire, response.data.repository, MALFORMED$2, ["data", "repository"]).pullRequest.comments;
14749
+ nodes = [...page.nodes, ...nodes];
14750
+ }
14751
+ return {
14752
+ nodes,
14753
+ complete: true
14754
+ };
14755
+ } catch (error) {
14756
+ if (signal.aborted) throw error;
14757
+ if (error instanceof AdapterError && error.kind === "transient") return {
14758
+ nodes,
14759
+ complete: false
14760
+ };
14761
+ throw error;
14762
+ }
14763
+ }
14764
+ function accumulator(complete, budget) {
14765
+ return {
14766
+ complete,
14767
+ entities: [],
14768
+ items: [],
14769
+ budget,
14770
+ parseError: void 0,
14771
+ parseFailedRefs: 0
14772
+ };
14773
+ }
14774
+ function malformed(acc, error, ref) {
14775
+ acc.parseError ??= error;
14776
+ acc.complete = false;
14777
+ if (ref) {
14778
+ acc.entities.push({
14779
+ ref,
14780
+ status: "no_access"
14781
+ });
14782
+ acc.parseFailedRefs += 1;
14783
+ }
14784
+ return false;
14785
+ }
14786
+ async function processPr(scope, acc, number, alias, data, scopedErrors, ref) {
14787
+ const errors = withoutDeniedReferences(scopedErrors);
14788
+ requireCheckAccess(errors);
14789
+ const error = errors[0];
14790
+ if (error !== void 0) {
14791
+ const direct = error.path === void 0 || error.path.length <= 2;
14792
+ if (!ref || !direct || error.type !== "NOT_FOUND" && error.type !== "FORBIDDEN") acc.complete = false;
14793
+ if (ref) acc.entities.push({
14794
+ ref,
14795
+ status: direct ? status(error) : "no_access"
14796
+ });
14797
+ return false;
14798
+ }
14799
+ const root = content(() => parseWire(aliasWire, data[alias], MALFORMED$2, ["data", alias]));
14800
+ if (root instanceof AdapterError) return malformed(acc, root, ref);
14801
+ const wire = root?.pullRequest;
14802
+ if (wire === null || wire === void 0) {
14803
+ if (ref) acc.entities.push({
14804
+ ref,
14805
+ status: "not_found"
14806
+ });
14807
+ else acc.complete = false;
14808
+ return false;
14809
+ }
14810
+ const report = (next) => {
14811
+ acc.budget = next;
14812
+ };
14813
+ const full = await fullPr(scope.client, wire, scope.owner, scope.name, number, scope.signal, report);
14814
+ if (full.status === "denied") {
14815
+ acc.complete = false;
14816
+ if (ref) acc.entities.push({
14817
+ ref,
14818
+ status: "no_access"
14819
+ });
14820
+ return false;
14821
+ }
14822
+ if (full.status === "malformed") return malformed(acc, full.error, ref);
14823
+ const cursor = scope.feedbackCursors?.find((entry) => entry.ref.number === number && entry.ref.repo.toLowerCase() === scope.repo.toLowerCase());
14824
+ const feedback = await readFeedback(scope.client, full.pr.comments, scope.owner, scope.name, number, cursor, scope.signal, report);
14825
+ const pr = {
14826
+ ...full.pr,
14827
+ comments: {
14828
+ ...full.pr.comments,
14829
+ nodes: feedback.nodes
14830
+ }
14831
+ };
14832
+ const facts = content(() => normalizePr(ref?.repo ?? scope.repo, pr, scope.keys, feedback.complete));
14833
+ if (facts instanceof AdapterError) return malformed(acc, facts, ref);
14834
+ acc.items.push({
14835
+ kind: "pr",
14836
+ facts
14837
+ });
14838
+ if (ref) acc.entities.push({
14839
+ ref,
14840
+ status: "ok"
14841
+ });
14842
+ return true;
14843
+ }
14844
+ function closingSelected(keys) {
14845
+ return keys.type === "issues" && keys.sources.includes("closing");
14846
+ }
14847
+ function rethrowLoneParseFailure(acc) {
14848
+ if (acc.parseError !== void 0 && acc.items.length === 0 && acc.entities.length === acc.parseFailedRefs) throw acc.parseError;
14849
+ }
14560
14850
  async function pollRepository({ id, repo, login, keys, client, now, ctx }) {
14561
14851
  const observedAt = sourceCursorSchema.parse(new Date(now()).toISOString());
14562
14852
  const bootstrap = ctx.cursor === void 0;
@@ -14565,17 +14855,14 @@ async function pollRepository({ id, repo, login, keys, client, now, ctx }) {
14565
14855
  const requested = ctx.observe.prs.filter((ref) => ref.repo.toLowerCase() === repo.toLowerCase());
14566
14856
  const byNumber = new Map(requested.map((ref) => [ref.number, ref]));
14567
14857
  const numbers = [...byNumber.keys()];
14568
- const closing = keys.type === "issues" && keys.sources.includes("closing");
14858
+ const closing = closingSelected(keys);
14569
14859
  const response = await client.query(initialQuery(numbers, bootstrap, closing), {
14570
14860
  owner,
14571
14861
  repo: name
14572
14862
  }, ctx.signal);
14573
- let budget = response.budget;
14574
- let complete = true;
14863
+ const acc = accumulator(true, response.budget);
14575
14864
  const roots = ["repository", ...numbers.map((_, i) => `pr${String(i)}`)];
14576
14865
  rejectUnscoped(response.errors, roots);
14577
- const entities = [];
14578
- const items = [];
14579
14866
  let discoveryOk = scoped(response.errors, "repository").length === 0;
14580
14867
  const first = discoveryOk ? parseWire(discoveryRootWire, response.data.repository, MALFORMED$2, ["data", "repository"]).pullRequests : void 0;
14581
14868
  const nodes = first === void 0 ? [] : [...first.nodes];
@@ -14589,7 +14876,7 @@ async function pollRepository({ id, repo, login, keys, client, now, ctx }) {
14589
14876
  repo: name,
14590
14877
  after: cursor
14591
14878
  }, ctx.signal);
14592
- budget = page.budget;
14879
+ acc.budget = page.budget;
14593
14880
  rejectUnscoped(page.errors, ["repository"]);
14594
14881
  if (page.errors.length > 0) {
14595
14882
  discoveryOk = false;
@@ -14599,76 +14886,23 @@ async function pollRepository({ id, repo, login, keys, client, now, ctx }) {
14599
14886
  nodes.push(...connection.nodes);
14600
14887
  cursor = pastCursor(connection.nodes, ctx.cursor) ? void 0 : nextPage(connection);
14601
14888
  }
14602
- if (!discoveryOk) complete = false;
14889
+ if (!discoveryOk) acc.complete = false;
14603
14890
  const found = discover(nodes, ctx.cursor, login);
14604
14891
  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;
14605
- let parseError;
14606
- let parseFailedRefs = 0;
14607
- const malformed = (error, ref) => {
14608
- parseError ??= error;
14609
- complete = false;
14610
- if (ref) {
14611
- entities.push({
14612
- ref,
14613
- status: "no_access"
14614
- });
14615
- parseFailedRefs += 1;
14616
- }
14617
- return false;
14618
- };
14619
- const process = async (number, alias, data, scopedErrors, ref) => {
14620
- const errors = withoutDeniedReferences(scopedErrors);
14621
- requireCheckAccess(errors);
14622
- const error = errors[0];
14623
- if (error !== void 0) {
14624
- const direct = error.path === void 0 || error.path.length <= 2;
14625
- if (!ref || !direct || error.type !== "NOT_FOUND" && error.type !== "FORBIDDEN") complete = false;
14626
- if (ref) entities.push({
14627
- ref,
14628
- status: direct ? status(error) : "no_access"
14629
- });
14630
- return false;
14631
- }
14632
- const root = content(() => parseWire(aliasWire, data[alias], MALFORMED$2, ["data", alias]));
14633
- if (root instanceof AdapterError) return malformed(root, ref);
14634
- const wire = root?.pullRequest;
14635
- if (wire === null || wire === void 0) {
14636
- if (ref) entities.push({
14637
- ref,
14638
- status: "not_found"
14639
- });
14640
- else complete = false;
14641
- return false;
14642
- }
14643
- const full = await fullPr(client, wire, owner, name, number, ctx.signal, (next) => {
14644
- budget = next;
14645
- });
14646
- if (full.status === "denied") {
14647
- complete = false;
14648
- if (ref) entities.push({
14649
- ref,
14650
- status: "no_access"
14651
- });
14652
- return false;
14653
- }
14654
- if (full.status === "malformed") return malformed(full.error, ref);
14655
- const facts = content(() => normalizePr(ref?.repo ?? repo, full.pr, keys));
14656
- if (facts instanceof AdapterError) return malformed(facts, ref);
14657
- items.push({
14658
- kind: "pr",
14659
- facts
14660
- });
14661
- if (ref) entities.push({
14662
- ref,
14663
- status: "ok"
14664
- });
14665
- return true;
14892
+ const scope = {
14893
+ client,
14894
+ repo,
14895
+ owner,
14896
+ name,
14897
+ keys,
14898
+ signal: ctx.signal,
14899
+ ...ctx.feedbackCursors === void 0 ? {} : { feedbackCursors: ctx.feedbackCursors }
14666
14900
  };
14667
14901
  let discoveredOk = true;
14668
14902
  for (const [i, number] of numbers.entries()) {
14669
14903
  const alias = `pr${String(i)}`;
14670
14904
  const errors = scoped(response.errors, alias);
14671
- if (!await process(number, alias, response.data, errors, byNumber.get(number)) && found.numbers.includes(number)) discoveredOk = false;
14905
+ if (!await processPr(scope, acc, number, alias, response.data, errors, byNumber.get(number)) && found.numbers.includes(number)) discoveredOk = false;
14672
14906
  }
14673
14907
  const discovered = found.numbers.filter((number) => !byNumber.has(number));
14674
14908
  for (let offset = 0; offset < discovered.length; offset += 50) {
@@ -14677,24 +14911,53 @@ async function pollRepository({ id, repo, login, keys, client, now, ctx }) {
14677
14911
  owner,
14678
14912
  repo: name
14679
14913
  }, ctx.signal);
14680
- budget = detail.budget;
14914
+ acc.budget = detail.budget;
14681
14915
  rejectUnscoped(detail.errors, chunk.map((_, i) => `pr${String(i)}`));
14682
14916
  for (const [i, number] of chunk.entries()) {
14683
14917
  const alias = `pr${String(i)}`;
14684
- if (!await process(number, alias, detail.data, scoped(detail.errors, alias))) discoveredOk = false;
14918
+ if (!await processPr(scope, acc, number, alias, detail.data, scoped(detail.errors, alias))) discoveredOk = false;
14685
14919
  }
14686
14920
  }
14687
14921
  if (ctx.signal.aborted) throw new AdapterError("transient", "GitHub poll aborted");
14688
- if (parseError !== void 0 && items.length === 0 && entities.length === parseFailedRefs) throw parseError;
14922
+ rethrowLoneParseFailure(acc);
14689
14923
  const nextCursor = bootstrap ? bootstrapCursor : found.cursor;
14690
14924
  return {
14691
14925
  source: id,
14692
14926
  observedAt,
14693
- complete,
14694
- items,
14695
- entities,
14927
+ complete: acc.complete,
14928
+ items: acc.items,
14929
+ entities: acc.entities,
14696
14930
  ...discoveryOk && discoveredOk ? nextCursor === void 0 ? {} : { cursor: nextCursor } : ctx.cursor === void 0 ? {} : { cursor: ctx.cursor },
14697
- budget
14931
+ budget: acc.budget
14932
+ };
14933
+ }
14934
+ async function pollOnePr({ id, repo, keys, client, now, ref, signal }) {
14935
+ const observedAt = new Date(now()).toISOString();
14936
+ const [owner, name] = repo.split("/");
14937
+ if (!owner || !name) throw new AdapterError("config", "Invalid repository");
14938
+ const response = await client.query(detailQuery([ref.number], closingSelected(keys)), {
14939
+ owner,
14940
+ repo: name
14941
+ }, signal);
14942
+ rejectUnscoped(response.errors, ["pr0"]);
14943
+ const acc = accumulator(false, response.budget);
14944
+ await processPr({
14945
+ client,
14946
+ repo,
14947
+ owner,
14948
+ name,
14949
+ keys,
14950
+ signal
14951
+ }, acc, ref.number, "pr0", response.data, scoped(response.errors, "pr0"), ref);
14952
+ if (signal.aborted) throw new AdapterError("transient", "GitHub poll aborted");
14953
+ rethrowLoneParseFailure(acc);
14954
+ return {
14955
+ source: id,
14956
+ observedAt,
14957
+ complete: false,
14958
+ items: acc.items,
14959
+ entities: acc.entities,
14960
+ budget: acc.budget
14698
14961
  };
14699
14962
  }
14700
14963
  //#endregion
@@ -15278,6 +15541,12 @@ function budgetPause(budget, reserveRemaining, intervalMs, now) {
15278
15541
  if (budget.remaining >= reserveRemaining) return void 0;
15279
15542
  return Math.max(Date.parse(budget.resetAt) - now, intervalMs);
15280
15543
  }
15544
+ /** When a `throttled` error lets the source be called again; undefined without a valid time. */
15545
+ function throttledRetryAt(error) {
15546
+ if (!(error instanceof AdapterError) || error.kind !== "throttled") return void 0;
15547
+ const retryAt = error.retryAt?.getTime();
15548
+ return retryAt === void 0 || Number.isNaN(retryAt) ? void 0 : retryAt;
15549
+ }
15281
15550
  /** The wait before the next poll and the new failure count. */
15282
15551
  function nextDelay(input) {
15283
15552
  const { outcome, intervalMs, failures, now } = input;
@@ -15291,8 +15560,8 @@ function nextDelay(input) {
15291
15560
  delayMs: jitter(input.authRetryMs),
15292
15561
  failures
15293
15562
  };
15294
- const retryAt = error.retryAt?.getTime();
15295
- if (error.kind === "throttled" && retryAt !== void 0 && !Number.isNaN(retryAt)) return {
15563
+ const retryAt = throttledRetryAt(error);
15564
+ if (retryAt !== void 0) return {
15296
15565
  delayMs: Math.max(retryAt - now, intervalMs),
15297
15566
  failures
15298
15567
  };
@@ -15375,16 +15644,30 @@ function applyEntityOutcomes(input) {
15375
15644
  function startRunner(options) {
15376
15645
  const startedAt = options.now();
15377
15646
  const sources = options.entries.map((entry) => runSource(entry, options, startedAt));
15647
+ const byId = new Map(sources.map((source) => [source.id, source]));
15378
15648
  return {
15379
15649
  firstAttempts: Promise.all(sources.map(async (source) => ({
15380
15650
  source: source.id,
15381
15651
  outcome: await source.firstAttempt
15382
15652
  }))),
15653
+ pollPr(source, ref, { timeoutMs }) {
15654
+ const found = byId.get(source);
15655
+ if (found === void 0) return Promise.resolve(err({
15656
+ kind: "unknown_source",
15657
+ message: `No source with id ${source}`
15658
+ }));
15659
+ return found.pollPr(ref, timeoutMs);
15660
+ },
15383
15661
  async stop() {
15384
15662
  await Promise.all(sources.map((source) => source.stop()));
15385
15663
  }
15386
15664
  };
15387
15665
  }
15666
+ const noop = () => void 0;
15667
+ const stoppedError = {
15668
+ kind: "stopped",
15669
+ message: "The adapter runner is stopping"
15670
+ };
15388
15671
  function runSource(entry, options, runnerStartMs) {
15389
15672
  const { adapter, reserveRemaining } = entry;
15390
15673
  const { core, config } = options;
@@ -15415,9 +15698,14 @@ function runSource(entry, options, runnerStartMs) {
15415
15698
  let counts = /* @__PURE__ */ new Map();
15416
15699
  let hydrated = false;
15417
15700
  let gone = [];
15418
- /** Set while a poll is in flight. */
15701
+ /** Set while a regular poll is in flight. */
15419
15702
  let controller;
15420
- let current = Promise.resolve();
15703
+ /** Unsettled on-demand requests; each entry resolves its request as stopped unless observing. */
15704
+ const pending = /* @__PURE__ */ new Set();
15705
+ /** Until when a regular throttled failure forbids calling the source. */
15706
+ let throttledUntilMs;
15707
+ /** Tail of the single-flight chain: regular polls and on-demand requests, one at a time. */
15708
+ let chain = Promise.resolve();
15421
15709
  let pollTimer;
15422
15710
  let deadlineTimer;
15423
15711
  let hardBoundTimer;
@@ -15467,14 +15755,21 @@ function runSource(entry, options, runnerStartMs) {
15467
15755
  hardBoundTimer = void 0;
15468
15756
  report();
15469
15757
  }
15758
+ /** Runs `task` after every task queued before it has settled. */
15759
+ function run(task) {
15760
+ const result = chain.then(task);
15761
+ chain = result.then(noop, noop);
15762
+ return result;
15763
+ }
15470
15764
  function schedule(delayMs) {
15471
15765
  if (stopping) return;
15472
15766
  pollTimer = setTimeout(() => {
15473
15767
  pollTimer = void 0;
15474
- current = poll().then(() => void 0);
15768
+ run(poll);
15475
15769
  }, delayMs);
15476
15770
  }
15477
15771
  async function poll() {
15772
+ if (stopping) return;
15478
15773
  const abort = new AbortController();
15479
15774
  const aborted = () => abort.signal.aborted;
15480
15775
  controller = abort;
@@ -15581,17 +15876,136 @@ function runSource(entry, options, runnerStartMs) {
15581
15876
  now: now()
15582
15877
  });
15583
15878
  failures = delay.failures;
15879
+ throttledUntilMs = outcome.kind === "failed" ? throttledRetryAt(outcome.error) : void 0;
15584
15880
  if (!options.oneShot) armDeadline();
15585
15881
  await report();
15586
15882
  if (!options.oneShot) schedule(delay.delayMs);
15587
15883
  return outcome;
15588
15884
  }
15885
+ /** One on-demand request at its turn on the chain; `live` is false once its caller left. */
15886
+ async function demandTurn(ref, abort, live, observing) {
15887
+ if (stopping) return err(stoppedError);
15888
+ if (!live()) return;
15889
+ const startMs = now();
15890
+ const blind = state().blind;
15891
+ if (blind !== void 0) return err({
15892
+ kind: "blind",
15893
+ reason: blind.reason,
15894
+ message: blind.message
15895
+ });
15896
+ if (adapter.pollPr === void 0) return err({
15897
+ kind: "unsupported",
15898
+ message: "The source does not poll one PR on demand"
15899
+ });
15900
+ if (throttledUntilMs !== void 0 && startMs < throttledUntilMs) return err({
15901
+ kind: "failed",
15902
+ adapterKind: "throttled",
15903
+ retryAt: iso$1(throttledUntilMs),
15904
+ message: "The source is throttled until retryAt"
15905
+ });
15906
+ const aborted = () => abort.signal.aborted;
15907
+ let step = "poll";
15908
+ try {
15909
+ const batch = await untilAborted(adapter.pollPr(ref, { signal: abort.signal }), abort.signal);
15910
+ if (aborted()) return err(stoppedError);
15911
+ step = "batch";
15912
+ const observedAt = iso$1(startMs);
15913
+ const parsed = batchSchema.safeParse({
15914
+ ...batch,
15915
+ observedAt
15916
+ });
15917
+ const value = parsed.success ? demandValue(parsed.data, observedAt) : void 0;
15918
+ const invalid = !parsed.success ? void 0 : parsed.data.source !== source ? "names another source" : !answersRequest({
15919
+ prs: [ref],
15920
+ tickets: [],
15921
+ sessions: []
15922
+ }, parsed.data.entities) ? "does not answer the request" : parsed.data.complete ? "is marked complete" : parsed.data.cursor !== void 0 ? "carries a cursor" : value === void 0 ? "carries another item" : void 0;
15923
+ if (!parsed.success || invalid !== void 0 || value === void 0) {
15924
+ const error = new AdapterError("transient", `Invalid batch: ${invalid ?? "fails the batch schema"}`);
15925
+ fail("batch", error, parsed.error?.issues.map((issue) => ({
15926
+ path: issue.path.map(String).join("."),
15927
+ code: issue.code,
15928
+ message: issue.message
15929
+ })));
15930
+ return err({
15931
+ kind: "failed",
15932
+ adapterKind: "transient",
15933
+ message: error.message
15934
+ });
15935
+ }
15936
+ step = "observe";
15937
+ const accepted = reports.then(async () => {
15938
+ if (!live()) return;
15939
+ if (stopping) return err(stoppedError);
15940
+ observing();
15941
+ const committed = state();
15942
+ await core.observe(source, {
15943
+ batch: parsed.data,
15944
+ effectiveComplete: false,
15945
+ state: committed,
15946
+ outcomes: []
15947
+ });
15948
+ lastReported = JSON.stringify(committed);
15949
+ return ok(value);
15950
+ });
15951
+ reports = accepted.then(noop, noop);
15952
+ return await accepted;
15953
+ } catch (error) {
15954
+ if (aborted()) return err(stoppedError);
15955
+ fail(step, error);
15956
+ const retryAt = throttledRetryAt(error);
15957
+ return err({
15958
+ kind: "failed",
15959
+ adapterKind: error instanceof AdapterError ? error.kind : "unexpected",
15960
+ ...retryAt === void 0 ? {} : { retryAt: iso$1(retryAt) },
15961
+ message: error instanceof AdapterError ? error.message : `The ${step} step failed`
15962
+ });
15963
+ }
15964
+ }
15965
+ function pollPr(ref, timeoutMs) {
15966
+ if (entry.repo !== void 0 && ref.repo.toLowerCase() !== entry.repo.toLowerCase()) return Promise.resolve(err({
15967
+ kind: "unknown_source",
15968
+ message: `The source does not own ${ref.repo}`
15969
+ }));
15970
+ if (stopping) return Promise.resolve(err(stoppedError));
15971
+ return new Promise((resolve) => {
15972
+ const abort = new AbortController();
15973
+ let settled = false;
15974
+ let observing = false;
15975
+ const settle = (result) => {
15976
+ if (settled) return;
15977
+ settled = true;
15978
+ clearTimeout(timer);
15979
+ pending.delete(cancel);
15980
+ resolve(result);
15981
+ };
15982
+ const cancel = () => {
15983
+ if (observing) return;
15984
+ settle(err(stoppedError));
15985
+ abort.abort();
15986
+ };
15987
+ pending.add(cancel);
15988
+ const timer = setTimeout(() => {
15989
+ if (observing) return;
15990
+ settle(err({
15991
+ kind: "timeout",
15992
+ message: "The on-demand poll timed out"
15993
+ }));
15994
+ abort.abort();
15995
+ }, timeoutMs);
15996
+ run(async () => {
15997
+ const result = await demandTurn(ref, abort, () => !settled, () => {
15998
+ observing = true;
15999
+ });
16000
+ if (result !== void 0) settle(result);
16001
+ });
16002
+ });
16003
+ }
15589
16004
  if (!options.oneShot) armDeadline();
15590
- const firstAttempt = poll();
15591
- current = firstAttempt.then(() => void 0);
15592
16005
  return {
15593
16006
  id: source,
15594
- firstAttempt,
16007
+ firstAttempt: run(poll),
16008
+ pollPr,
15595
16009
  async stop() {
15596
16010
  stopping = true;
15597
16011
  clearTimeout(pollTimer);
@@ -15599,11 +16013,27 @@ function runSource(entry, options, runnerStartMs) {
15599
16013
  clearTimeout(hardBoundTimer);
15600
16014
  pollTimer = deadlineTimer = hardBoundTimer = void 0;
15601
16015
  controller?.abort();
15602
- await current;
16016
+ for (const cancel of [...pending]) cancel();
16017
+ await chain;
15603
16018
  await reports;
15604
16019
  }
15605
16020
  };
15606
16021
  }
16022
+ /** The answer of an A9 batch: its one entity and at most that PR's own item; else undefined. */
16023
+ function demandValue(batch, observedAt) {
16024
+ const [entity] = batch.entities;
16025
+ const [item, ...rest] = batch.items;
16026
+ if (entity === void 0) return void 0;
16027
+ if (entity.status !== "ok") return item === void 0 ? {
16028
+ status: entity.status,
16029
+ observedAt
16030
+ } : void 0;
16031
+ return item?.kind === "pr" && rest.length === 0 ? {
16032
+ status: "ok",
16033
+ facts: item.facts,
16034
+ observedAt
16035
+ } : void 0;
16036
+ }
15607
16037
  /**
15608
16038
  * Settles with `work`, or with undefined as soon as `signal` aborts, so `stop()` never waits
15609
16039
  * for an adapter that ignores its signal. A late result or rejection is dropped. The abort
@@ -15954,6 +16384,7 @@ function startAdapters(config, core, options) {
15954
16384
  });
15955
16385
  return {
15956
16386
  firstAttempts: runner.firstAttempts,
16387
+ pollPr: runner.pollPr,
15957
16388
  async stop() {
15958
16389
  await runner.stop();
15959
16390
  await Promise.allSettled([...notices]);
@@ -16123,6 +16554,7 @@ const MARKER_PREFIX = "spur:";
16123
16554
  const ORIGIN_PREFIX = "spur-origin:";
16124
16555
  const roleIcons = {
16125
16556
  orchestrator: ":compass:",
16557
+ curator: ":classical_building:",
16126
16558
  worker: ":hammer:",
16127
16559
  board: ":clipboard:"
16128
16560
  };