spur-board 0.10.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/daemon.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { A as parseActorId, B as RESERVED_PROJECT, C as prFactsSchema, D as actorIdSchema, E as ticketFactsSchema, H as requiredSecretKeys, I as successEnvelopeSchema, M as taskKeySchema, N as ERRORS, O as encodeActorId, S as SESSION_STATUSES, T as sessionFactsSchema, U as SLACK_BOT_SCOPES, V as configSchema, _ as messageRefSchema, a as entityRefSchema, b as eventPayloadSchemas, c as roleCanUseOperation, g as interactionRefSchema, h as inboundEventSchema, i as batchSchema, j as parseRef$1, k as errorCodeOf, l as OPERATIONS, m as conversationRefSchema, o as sourceCursorSchema, p as SPACE_IDS, r as AdapterError, s as buildCatalogSnapshot, t as BOARD_TICK_MS, u as renderHttpProblem, v as userIdSchema, w as prRefSchema, x as SESSION_HEALTH_STATES, y as EVENT_KINDS, z as DEFAULT_SLACK_COMMAND } from "./src-DyDmiehC.mjs";
1
+ import { A as parseActorId, B as RESERVED_PROJECT, C as prFactsSchema, D as actorIdSchema, E as ticketFactsSchema, H as requiredSecretKeys, I as successEnvelopeSchema, M as taskKeySchema, N as ERRORS, O as encodeActorId, S as SESSION_STATUSES, T as sessionFactsSchema, U as SLACK_BOT_SCOPES, V as configSchema, _ as messageRefSchema, a as entityRefSchema, b as eventPayloadSchemas, c as roleCanUseOperation, g as interactionRefSchema, h as inboundEventSchema, i as batchSchema, j as parseRef$1, k as errorCodeOf, l as OPERATIONS, m as conversationRefSchema, o as sourceCursorSchema, p as SPACE_IDS, r as AdapterError, s as buildCatalogSnapshot, t as BOARD_TICK_MS, u as renderHttpProblem, v as userIdSchema, w as prRefSchema, x as SESSION_HEALTH_STATES, y as EVENT_KINDS, z as DEFAULT_SLACK_COMMAND } from "./src-Dl5c0sRb.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";
@@ -8075,7 +8075,7 @@ async function restartNotification(trx, sourceKey, at) {
8075
8075
  }
8076
8076
  /** Reconcile due semantic notifications in the sender's claim transaction. */
8077
8077
  async function reconcileDoorbells(trx, at, config) {
8078
- const due = await trx.selectFrom("notification").selectAll().where("acked_at", "is", null).where("exhausted_at", "is", null).where("next_at", "<=", at.toISOString()).orderBy("id").execute();
8078
+ 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();
8079
8079
  for (const n of due) {
8080
8080
  const session = await selectNotificationRecipient(trx, n);
8081
8081
  if (session === void 0) {
@@ -8126,6 +8126,7 @@ async function reconcileDoorbells(trx, at, config) {
8126
8126
  continue;
8127
8127
  }
8128
8128
  const raised = await trx.selectFrom("operator_item").select((eb) => eb.fn.max("raise_no").as("series")).where("item_key", "=", itemKey).executeTakeFirst();
8129
+ const archived = await trx.selectFrom("event").select((eb) => eb.fn.countAll().as("count")).where("task_id", "=", n.task_id).where("kind", "=", "task_archived").executeTakeFirst();
8129
8130
  const ring = rings + 1;
8130
8131
  const text = `${task.key} block B${String(n.block_id)}: check board inbox (N${String(n.id)}-${String(ring)})`;
8131
8132
  const outboxId = await enqueueDoorbell(trx, {
@@ -8134,7 +8135,8 @@ async function reconcileDoorbells(trx, at, config) {
8134
8135
  session: session.id,
8135
8136
  text,
8136
8137
  at,
8137
- series: raised?.series ?? 0
8138
+ series: raised?.series ?? 0,
8139
+ archives: archived?.count ?? 0
8138
8140
  });
8139
8141
  await trx.updateTable("notification").set({ last_outbox_id: outboxId }).where("id", "=", n.id).execute();
8140
8142
  }
@@ -8166,6 +8168,17 @@ async function ringStillCurrent(trx, notificationId, sessionId) {
8166
8168
  if (session?.id !== sessionId) return "dead";
8167
8169
  return session.state === "working" ? "defer" : "send";
8168
8170
  }
8171
+ /**
8172
+ * The task of a ring: through its notification, or for an inbound author ring (no notification)
8173
+ * through the comment in its `doorbell:comment:<id>:` key. Archive kills only unclaimed rings;
8174
+ * the sender drops a claimed one of an archived task before its send starts.
8175
+ */
8176
+ async function ringTask(trx, notificationId, dedupeKey) {
8177
+ const commentId = /^doorbell:comment:(\d+):/.exec(dedupeKey)?.[1];
8178
+ if (notificationId === void 0 && commentId === void 0) return void 0;
8179
+ const owner = notificationId !== void 0 ? trx.selectFrom("notification").select("task_id").where("id", "=", notificationId) : trx.selectFrom("comment").select("task_id").where("id", "=", Number(commentId));
8180
+ return trx.selectFrom("task").selectAll().where("id", "in", owner).executeTakeFirst();
8181
+ }
8169
8182
  /** Stop notifications acknowledged by the addressed session. */
8170
8183
  async function acknowledgeNotification(trx, input) {
8171
8184
  let query = trx.selectFrom("notification").selectAll().where("acked_at", "is", null);
@@ -8315,13 +8328,15 @@ function renderBody(key, text) {
8315
8328
  }
8316
8329
  /**
8317
8330
  * A distinct semantic ring. Transport retries reuse this row and its text. A restarted series
8318
- * (`series` > 0) gets its own keys; the first series keeps the unsuffixed key.
8331
+ * (`series` > 0) and a ring after the task was archived (`archives` > 0) get their own keys, so a
8332
+ * ring cancelled by an archive does not block its replacement; unsuffixed keys stay as before.
8319
8333
  */
8320
8334
  async function enqueueDoorbell(trx, input) {
8321
8335
  const series = input.series ?? 0;
8336
+ const archives = input.archives ?? 0;
8322
8337
  const row = await insertOutbox(trx, {
8323
8338
  kind: "doorbell",
8324
- dedupeKey: `doorbell:${String(input.notificationId)}:${input.session}:${String(input.ring)}${series > 0 ? `:s${String(series)}` : ""}`,
8339
+ dedupeKey: `doorbell:${String(input.notificationId)}:${input.session}:${String(input.ring)}${series > 0 ? `:s${String(series)}` : ""}${archives > 0 ? `:a${String(archives)}` : ""}`,
8325
8340
  payload: {
8326
8341
  notificationId: input.notificationId,
8327
8342
  ring: input.ring,
@@ -8575,7 +8590,7 @@ async function enqueueConversationClose(trx, input) {
8575
8590
  const conversations = await trx.selectFrom("conversation").select("ref").where("block_id", "=", input.blockId).execute();
8576
8591
  const payload = {
8577
8592
  key: block.key,
8578
- text: `resolved: ${input.outcome} (${input.actor})`,
8593
+ text: `resolved: ${input.outcome === "archived" ? "task archived" : input.outcome} (${input.actor})`,
8579
8594
  persona: {
8580
8595
  name: "board",
8581
8596
  role: "board"
@@ -9394,7 +9409,8 @@ async function openBlock(trx, task, type, reason, ctx, config) {
9394
9409
  await registerBlockNotification(trx, row, new Date(ctx.at));
9395
9410
  return row;
9396
9411
  }
9397
- async function close(trx, task, block, ctx, outcome, outcomeReason) {
9412
+ /** Unblocks one block with its journal entry, thread close, doorbell close and item clears. */
9413
+ async function closeOpenBlock(trx, task, block, ctx, outcome, outcomeReason) {
9398
9414
  const updated = await trx.updateTable("block").set({
9399
9415
  state: "unblocked",
9400
9416
  outcome,
@@ -9438,7 +9454,7 @@ async function recordInboundBlockMessage(trx, input) {
9438
9454
  conversationRef: input.conversationRef,
9439
9455
  messageRef: input.messageRef
9440
9456
  }),
9441
- block: answered ? await close(trx, task, block, ctx, "done", null) : block,
9457
+ block: answered ? await closeOpenBlock(trx, task, block, ctx, "done", null) : block,
9442
9458
  task,
9443
9459
  answered,
9444
9460
  workerAuthor: authorRole(input.config, task, block.author) === "worker"
@@ -9562,7 +9578,7 @@ function createBlockMutations(config) {
9562
9578
  });
9563
9579
  const comment = await addComment(trx, task, block, input.text, ctx, authorRole(config, task, block.author), config);
9564
9580
  return {
9565
- block: blockView(await close(trx, task, block, ctx, "done", null), task),
9581
+ block: blockView(await closeOpenBlock(trx, task, block, ctx, "done", null), task),
9566
9582
  comment: commentView(comment, task)
9567
9583
  };
9568
9584
  }
@@ -9585,7 +9601,7 @@ function createBlockMutations(config) {
9585
9601
  actor: ctx.actor
9586
9602
  }));
9587
9603
  if (input.mode === "withdraw") await addComment(trx, task, block, input.answer, ctx, block.addressee_role, config);
9588
- return { block: blockView(await close(trx, task, block, ctx, decision.outcome, decision.outcomeReason), task) };
9604
+ return { block: blockView(await closeOpenBlock(trx, task, block, ctx, decision.outcome, decision.outcomeReason), task) };
9589
9605
  }
9590
9606
  },
9591
9607
  add: {
@@ -9662,31 +9678,39 @@ function createBlockMutations(config) {
9662
9678
  }
9663
9679
  return { acked: input.entries.map(({ id }) => id) };
9664
9680
  }
9665
- },
9666
- archive: {
9667
- id: "task.archive",
9668
- resolveTargets: (trx, input) => taskTarget(trx, input.task),
9669
- async run(trx, input, ctx) {
9670
- const task = found(await taskByKey$1(trx, input.task));
9671
- active(task);
9672
- const blocks = await trx.selectFrom("block").selectAll().where("task_id", "=", task.id).where("state", "=", "open").execute();
9673
- for (const block of blocks) await close(trx, task, block, ctx, "archived", null);
9674
- const updated = await trx.updateTable("task").set({
9675
- membership: "archived",
9676
- archive_reason: "manual"
9677
- }).where("id", "=", task.id).returningAll().executeTakeFirstOrThrow();
9678
- await journal$1(trx, task, ctx, "task_archived", { reason: "manual" });
9679
- return { task: {
9680
- key: updated.key,
9681
- project: updated.project,
9682
- column: updated.column,
9683
- membership: updated.membership
9684
- } };
9685
- }
9686
9681
  }
9687
9682
  };
9688
9683
  }
9689
9684
  //#endregion
9685
+ //#region ../core/src/app/archive.ts
9686
+ /**
9687
+ * Takes a task off the board in the caller's transaction: closes its open blocks with outcome
9688
+ * `archived`, clears its board-derived items, cancels its unsent doorbells and journals
9689
+ * `task_archived`. Callers set their own extra columns (manual flags, the Done slot).
9690
+ */
9691
+ async function archiveTask(trx, input) {
9692
+ const { task, reason, actor, at } = input;
9693
+ const ctx = {
9694
+ actor,
9695
+ at
9696
+ };
9697
+ const blocks = await trx.selectFrom("block").selectAll().where("task_id", "=", task.id).where("state", "=", "open").orderBy("id").execute();
9698
+ for (const block of blocks) await closeOpenBlock(trx, task, block, ctx, "archived", null);
9699
+ 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();
9700
+ for (const item of items) await clearItem(trx, item.id, new Date(at), actor);
9701
+ const comments = await trx.selectFrom("comment").select("id").where("task_id", "=", task.id).execute();
9702
+ await trx.updateTable("outbox").set({
9703
+ state: "dead",
9704
+ last_error: "superseded"
9705
+ }).where("kind", "=", "doorbell").where("state", "in", ["pending", "post_failed"]).where("uncertain", "=", 0).where((eb) => eb.or([eb("id", "in", eb.selectFrom("notification").select("last_outbox_id").where("task_id", "=", task.id).where("last_outbox_id", "is not", null)), ...comments.map((comment) => eb("dedupe_key", "like", `doorbell:comment:${String(comment.id)}:%`))])).execute();
9706
+ await trx.updateTable("task").set({
9707
+ membership: "archived",
9708
+ archive_reason: reason,
9709
+ last_change_at: at
9710
+ }).where("id", "=", task.id).execute();
9711
+ await emit(trx, "task_archived", task.project, task.id, at, { reason }, actor);
9712
+ }
9713
+ //#endregion
9690
9714
  //#region ../core/src/app/membership.ts
9691
9715
  function canonicalKey(config, key) {
9692
9716
  const parsed = parseRef$1(key, "task");
@@ -9770,13 +9794,15 @@ function createMembershipMutations(config) {
9770
9794
  if (task === void 0) throw new CommandError("not_found", "Check the task key.");
9771
9795
  if (task.membership === "archived") throw new CommandError("task_archived", "Task is archived.");
9772
9796
  await trx.updateTable("task").set({
9773
- membership: "archived",
9774
- archive_reason: "manual",
9775
9797
  manual_include: 0,
9776
- manual_exclude: 1,
9777
- last_change_at: ctx.at
9798
+ manual_exclude: 1
9778
9799
  }).where("id", "=", task.id).execute();
9779
- await emit(trx, "task_archived", task.project, task.id, ctx.at, { reason: "manual" }, "operator");
9800
+ await archiveTask(trx, {
9801
+ task,
9802
+ reason: "manual",
9803
+ actor: ctx.actor,
9804
+ at: ctx.at
9805
+ });
9780
9806
  return { task: {
9781
9807
  ...taskView(task),
9782
9808
  membership: "archived"
@@ -10117,6 +10143,14 @@ function createSender(options) {
10117
10143
  };
10118
10144
  }
10119
10145
  }
10146
+ if (c.body.kind === "doorbell" && !c.maybeSent && (await ringTask(trx, c.body.payload.notificationId, c.key))?.membership === "archived") {
10147
+ await kill(trx, [c.id], "superseded");
10148
+ return {
10149
+ at,
10150
+ firstDeliveryAt: null,
10151
+ skip: true
10152
+ };
10153
+ }
10120
10154
  if (c.body.kind === "doorbell" && c.body.payload.notificationId !== void 0) {
10121
10155
  const status = await ringStillCurrent(trx, c.body.payload.notificationId, c.body.payload.session);
10122
10156
  if (status === "dead") {
@@ -10247,12 +10281,13 @@ function createSender(options) {
10247
10281
  }).execute();
10248
10282
  if (body.kind === "conversation.open" || body.kind === "feed.line") {
10249
10283
  const isBlock = body.kind === "conversation.open";
10250
- const taskId = isBlock ? body.payload.taskId : body.payload.taskId ?? null;
10251
10284
  const closedBlock = isBlock ? await trx.selectFrom("block").select([
10285
+ "task_id",
10252
10286
  "state",
10253
10287
  "unblocked_at",
10254
10288
  "created_at"
10255
10289
  ]).where("id", "=", body.payload.blockId).executeTakeFirstOrThrow() : void 0;
10290
+ const taskId = closedBlock?.task_id ?? body.payload.taskId ?? null;
10256
10291
  await trx.insertInto("conversation").values({
10257
10292
  ref: conversation,
10258
10293
  gateway: gatewayKind,
@@ -10411,6 +10446,20 @@ async function loadItem(trx, id) {
10411
10446
  task: item.task_id === null ? void 0 : await trx.selectFrom("task").selectAll().where("id", "=", item.task_id).executeTakeFirstOrThrow()
10412
10447
  };
10413
10448
  }
10449
+ /** The task a `delivery:<outbox id>` item's row belongs to; the item itself has no task. */
10450
+ async function deliveryTask(trx, item) {
10451
+ if (!item.item_key.startsWith("delivery:")) return void 0;
10452
+ const row = await trx.selectFrom("outbox").select([
10453
+ "kind",
10454
+ "dedupe_key",
10455
+ "payload"
10456
+ ]).where("id", "=", Number(item.item_key.slice(9))).executeTakeFirst();
10457
+ if (row === void 0) return void 0;
10458
+ const payload = JSON.parse(row.payload);
10459
+ if (typeof payload.taskId === "number") return trx.selectFrom("task").selectAll().where("id", "=", payload.taskId).executeTakeFirst();
10460
+ if (row.kind !== "doorbell") return void 0;
10461
+ return ringTask(trx, typeof payload.notificationId === "number" ? payload.notificationId : void 0, row.dedupe_key);
10462
+ }
10414
10463
  function view(item, task) {
10415
10464
  return { item: {
10416
10465
  id: `I${String(item.id)}`,
@@ -10453,7 +10502,7 @@ function createItemMutations(deps) {
10453
10502
  resolveTargets: () => Promise.resolve([]),
10454
10503
  async run(trx, input, ctx) {
10455
10504
  const { item, task } = await loadItem(trx, input.item);
10456
- if (task?.membership === "archived") throw new CommandError("task_archived", "Add the task again before retrying its item.");
10505
+ if ((task ?? await deliveryTask(trx, item))?.membership === "archived") throw new CommandError("task_archived", "Add the task again before retrying its item.");
10457
10506
  if (item.cleared_at !== null) throw notApplicable("The item is already cleared.");
10458
10507
  if (item.kind === "transport_health") {
10459
10508
  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.");
@@ -11127,13 +11176,13 @@ async function reconcileMembership(trx, config, completeSince, at) {
11127
11176
  const complete = completeSince.get(source);
11128
11177
  return blind.has(source) || complete === void 0 || complete <= (task.last_change_at ?? task.created_at);
11129
11178
  })) continue;
11130
- await trx.updateTable("task").set({
11131
- membership: "archived",
11132
- archive_reason: "out_of_filter",
11133
- last_change_at: at
11134
- }).where("id", "=", task.id).execute();
11135
11179
  if (task.membership === "out_of_filter") await emit(trx, "flag_cleared", task.project, task.id, at, { flag: "out_of_filter" });
11136
- await emit(trx, "task_archived", task.project, task.id, at, { reason: "out_of_filter" });
11180
+ await archiveTask(trx, {
11181
+ task,
11182
+ reason: "out_of_filter",
11183
+ actor: "system",
11184
+ at
11185
+ });
11137
11186
  }
11138
11187
  }
11139
11188
  }
@@ -11417,6 +11466,10 @@ function refKey(ref) {
11417
11466
  function projectForSource(config, source) {
11418
11467
  return config.projects.find((project) => source === trackerSource(project) || project.repos.some((repo) => source === `github:${project.id}:${repo.toLowerCase()}`));
11419
11468
  }
11469
+ /** A closed issue of a GitHub Issues tracker, which lists only open issues. */
11470
+ function closedIssue(project, status) {
11471
+ return project.tracker.type === "github-issues" && status === "closed";
11472
+ }
11420
11473
  async function updateTerminal(trx, config, taskId, at, completeSince, blind) {
11421
11474
  const task = await trx.selectFrom("task").selectAll().where("id", "=", taskId).executeTakeFirstOrThrow();
11422
11475
  const project = config.projects.find((entry) => entry.id === task.project);
@@ -11454,6 +11507,27 @@ async function sourceState(trx, source, state, observedAt, cursor) {
11454
11507
  gone: toJson(z.array(entityRefSchema), [...state.gone])
11455
11508
  }))).execute();
11456
11509
  }
11510
+ /**
11511
+ * A merged pending key's open blocks were raised for the same ticket: they move to the surviving
11512
+ * task with what keeps them going (comments, threads, doorbells, items and undelivered rows).
11513
+ * Closed blocks and the journal stay with the archived row as its history.
11514
+ */
11515
+ async function moveOpenWork(trx, from, to) {
11516
+ const blocks = await trx.selectFrom("block").select("id").where("task_id", "=", from).where("state", "=", "open").execute();
11517
+ if (blocks.length === 0) return;
11518
+ const ids = blocks.map((block) => block.id);
11519
+ await trx.updateTable("block").set({ task_id: to }).where("id", "in", ids).execute();
11520
+ for (const table of [
11521
+ "comment",
11522
+ "conversation",
11523
+ "notification",
11524
+ "operator_item"
11525
+ ]) await trx.updateTable(table).set({ task_id: to }).where("block_id", "in", ids).execute();
11526
+ const keys = ids.flatMap((id) => [`operator-block:${String(id)}`, `block:${String(id)}`]);
11527
+ await trx.updateTable("operator_item").set({ task_id: to }).where("task_id", "=", from).where("item_key", "in", keys).execute();
11528
+ const itemKeys = (await trx.selectFrom("operator_item").select("item_key").where("task_id", "=", to).where((eb) => eb.or([eb("block_id", "in", ids), eb("item_key", "in", keys)])).execute()).map((item) => item.item_key);
11529
+ await trx.updateTable("outbox").set({ payload: sql`json_set(payload, '$.taskId', ${to})` }).where("state", "not in", ["done", "dead"]).where(sql`json_extract(payload, '$.taskId')`, "=", from).where((eb) => eb.or([eb(sql`json_extract(payload, '$.blockId')`, "in", ids), ...itemKeys.length === 0 ? [] : [eb(sql`json_extract(payload, '$.itemKey')`, "in", itemKeys)]])).execute();
11530
+ }
11457
11531
  async function ticket(trx, config, fact, at, source) {
11458
11532
  if (fact.trackerId !== source) throw new Error("Ticket from an unconfigured tracker");
11459
11533
  await trx.deleteFrom("source_miss").where("source", "=", source).where("ref_key", "=", `ticket:${source}:${fact.key}`).execute();
@@ -11472,6 +11546,7 @@ async function ticket(trx, config, fact, at, source) {
11472
11546
  archive_reason: "manual"
11473
11547
  }).where("id", "=", pending.id).execute();
11474
11548
  await emit(trx, "task_archived", pending.project, pending.id, at, { reason: "manual" });
11549
+ await moveOpenWork(trx, pending.id, task.id);
11475
11550
  await trx.updateTable("task").set({
11476
11551
  key: fact.key,
11477
11552
  manual_include: pending.manual_include,
@@ -11484,7 +11559,7 @@ async function ticket(trx, config, fact, at, source) {
11484
11559
  if (task === void 0) task = pending;
11485
11560
  if (task?.manual_exclude === 1) return;
11486
11561
  if (task === void 0) {
11487
- if (!fact.inFilter) return;
11562
+ if (!fact.inFilter || closedIssue(project, fact.status)) return;
11488
11563
  task = await trx.insertInto("task").values({
11489
11564
  project: project.id,
11490
11565
  tracker_kind: project.tracker.type,
@@ -11780,8 +11855,10 @@ function createObservationCore(deps) {
11780
11855
  "task.manual_include",
11781
11856
  "ticket_snapshot.detail"
11782
11857
  ]).where("project", "=", project.id).where("membership", "!=", "archived").execute()).flatMap((task) => {
11783
- const outside = task.detail === null ? false : !parseJson(ticketFactsSchema, task.detail).inFilter;
11784
- return task.manual_include === 1 || outside ? [{
11858
+ const detail = task.detail === null ? null : parseJson(ticketFactsSchema, task.detail);
11859
+ const outside = detail !== null && !detail.inFilter;
11860
+ const openIssue = project.tracker.type === "github-issues" && detail !== null && !closedIssue(project, detail.status);
11861
+ return task.manual_include === 1 || outside || openIssue ? [{
11785
11862
  kind: "ticket",
11786
11863
  trackerId: source,
11787
11864
  ...task.tracker_id === null ? {} : { id: task.tracker_id },
@@ -11881,12 +11958,14 @@ function createObservationCore(deps) {
11881
11958
  "ticket_snapshot.task_id",
11882
11959
  "ticket_snapshot.detail",
11883
11960
  "task.tracker_id",
11884
- "task.key"
11961
+ "task.key",
11962
+ "task.membership"
11885
11963
  ]).where("task.project", "=", project.id).where("task.manual_include", "=", 0).where("task.manual_exclude", "=", 0).execute();
11886
11964
  for (const row of rows) {
11965
+ if (project.tracker.type === "github-issues" && row.membership === "archived") continue;
11887
11966
  if (unresolved.has(row.key) || row.tracker_id !== null && (seen.has(row.tracker_id) || unresolved.has(row.tracker_id))) continue;
11888
11967
  const fact = parseJson(ticketFactsSchema, row.detail);
11889
- if (!fact.inFilter) continue;
11968
+ if (!fact.inFilter || closedIssue(project, fact.status)) continue;
11890
11969
  const outside = {
11891
11970
  ...fact,
11892
11971
  inFilter: false
@@ -11996,13 +12075,13 @@ async function tickBoard(deps) {
11996
12075
  const complete = completeSince.get(source);
11997
12076
  return blind.has(source) || complete === void 0 || complete <= (task.last_change_at ?? task.created_at);
11998
12077
  })) continue;
11999
- await trx.updateTable("task").set({
12000
- membership: "archived",
12001
- archive_reason: "done",
12002
- archive_slot_at: slot,
12003
- last_change_at: at
12004
- }).where("id", "=", task.id).execute();
12005
- await emit(trx, "task_archived", task.project, task.id, at, { reason: "done" });
12078
+ await trx.updateTable("task").set({ archive_slot_at: slot }).where("id", "=", task.id).execute();
12079
+ await archiveTask(trx, {
12080
+ task,
12081
+ reason: "done",
12082
+ actor: "system",
12083
+ at
12084
+ });
12006
12085
  }
12007
12086
  await reconcileItems(trx, config, now, completeSince.has("spur"));
12008
12087
  });
@@ -13119,6 +13198,18 @@ function acquireLock(file) {
13119
13198
  throw new Error(`flock failed to lock ${file} (status ${String(result.status)}): ${stderr || "no output"}`);
13120
13199
  }
13121
13200
  //#endregion
13201
+ //#region ../adapters/src/runner/wire.ts
13202
+ /**
13203
+ * Returns the parsed value or throws a transient `AdapterError` naming the first failing path
13204
+ * (`<label> at <dot.path>`). `at` prefixes the path when the value sits inside a larger
13205
+ * response. The error carries no cause, so no raw wire value reaches logs or smoke output.
13206
+ */
13207
+ function parseWire(schema, value, label, at = []) {
13208
+ const parsed = schema.safeParse(value);
13209
+ if (parsed.success) return parsed.data;
13210
+ throw new AdapterError("transient", `${label} at ${[...at, ...parsed.error.issues[0]?.path ?? []].map(String).join(".") || "(root)"}`);
13211
+ }
13212
+ //#endregion
13122
13213
  //#region ../adapters/src/runner/http.ts
13123
13214
  /** Classifies a failed response; `now` is the current time in epoch milliseconds. */
13124
13215
  function classifyHttpFailure(failure, now) {
@@ -13142,26 +13233,35 @@ function retryAt(headers, now) {
13142
13233
  }
13143
13234
  //#endregion
13144
13235
  //#region ../adapters/src/github/client.ts
13236
+ const MALFORMED$2 = "Malformed GitHub response";
13237
+ const graphErrorWire = z.object({
13238
+ message: z.string(),
13239
+ path: z.array(z.union([z.string(), z.number()])).optional(),
13240
+ type: z.string().optional()
13241
+ });
13242
+ const envelopeWire = z.object({
13243
+ errors: z.array(graphErrorWire).optional(),
13244
+ data: z.unknown()
13245
+ });
13246
+ const dataWire = z.looseObject({ rateLimit: z.object({
13247
+ remaining: z.int().nonnegative(),
13248
+ resetAt: z.string()
13249
+ }) });
13250
+ const pageInfoWire = z.object({
13251
+ hasNextPage: z.boolean(),
13252
+ endCursor: z.string().nullable()
13253
+ });
13254
+ function connectionWire(node) {
13255
+ return z.object({
13256
+ nodes: z.array(node),
13257
+ pageInfo: pageInfoWire
13258
+ });
13259
+ }
13145
13260
  function teamNameScopeDenied(error, query) {
13146
13261
  if (error.type !== "INSUFFICIENT_SCOPES" || !query.includes("... on Team { name }")) return false;
13147
13262
  if (error.path !== void 0) return error.path.includes("reviewRequests") && error.path.includes("requestedReviewer") && error.path.at(-1) === "name";
13148
13263
  return /\bname\b/i.test(error.message) && /\bread:(?:org|discussion)\b/i.test(error.message);
13149
13264
  }
13150
- function record$2(value) {
13151
- if (value === null || typeof value !== "object" || Array.isArray(value)) throw new AdapterError("transient", "Malformed GitHub response");
13152
- return value;
13153
- }
13154
- function list(value) {
13155
- if (!Array.isArray(value)) throw new AdapterError("transient", "Malformed GitHub connection");
13156
- return value;
13157
- }
13158
- function connectionNodes(value) {
13159
- return list(record$2(value).nodes).map(record$2);
13160
- }
13161
- function string$4(value) {
13162
- if (typeof value !== "string") throw new AdapterError("transient", "Malformed GitHub field");
13163
- return value;
13164
- }
13165
13265
  const prFields = (number) => `id number url title updatedAt state isDraft mergeable mergeStateStatus
13166
13266
  author { login } headRefName headRefOid
13167
13267
  statusCheckRollup { contexts(first: 100) { nodes {
@@ -13217,49 +13317,42 @@ var GithubClient = class {
13217
13317
  headers: response.headers,
13218
13318
  body: await response.text()
13219
13319
  }, Date.now());
13220
- let wire;
13320
+ let body;
13221
13321
  try {
13222
- wire = record$2(await response.json());
13322
+ body = await response.json();
13223
13323
  } catch (cause) {
13224
- throw new AdapterError("transient", "Malformed GitHub response", { cause });
13324
+ throw new AdapterError("transient", MALFORMED$2, { cause });
13225
13325
  }
13226
- const errors = wire.errors === void 0 ? [] : list(wire.errors).map((e) => {
13227
- const item = record$2(e);
13228
- return {
13229
- message: string$4(item.message),
13230
- ...typeof item.type === "string" ? { type: item.type } : {},
13231
- ...Array.isArray(item.path) ? { path: item.path.filter((p) => typeof p === "string" || typeof p === "number") } : {}
13232
- };
13233
- });
13326
+ const wire = parseWire(envelopeWire, body, MALFORMED$2);
13327
+ const errors = wire.errors ?? [];
13234
13328
  if (errors.some((error) => error.type === "RATE_LIMITED" || /rate limit/i.test(error.message))) throw classifyHttpFailure({
13235
13329
  status: 429,
13236
13330
  headers: response.headers
13237
13331
  }, Date.now());
13238
13332
  if (errors.some((error) => teamNameScopeDenied(error, query))) throw new AdapterError("auth", "GitHub token needs read:org for team review requests");
13239
13333
  if (errors.some((error) => error.type === "INSUFFICIENT_SCOPES")) throw new AdapterError("auth", "GitHub token lacks a required GraphQL read scope");
13240
- const data = record$2(wire.data);
13241
- const rate = record$2(data.rateLimit);
13242
- const remaining = rate.remaining;
13243
- if (typeof remaining !== "number" || !Number.isInteger(remaining) || remaining < 0) throw new AdapterError("transient", "Malformed GitHub budget");
13334
+ const data = parseWire(dataWire, wire.data, MALFORMED$2, ["data"]);
13244
13335
  return {
13245
13336
  data,
13246
13337
  errors,
13247
- budget: {
13248
- remaining,
13249
- resetAt: string$4(rate.resetAt)
13250
- }
13338
+ budget: data.rateLimit
13251
13339
  };
13252
13340
  }
13253
13341
  };
13254
13342
  //#endregion
13255
13343
  //#region ../adapters/src/github/discovery.ts
13344
+ const timestamp$1 = z.string().min(1).refine((value) => !Number.isNaN(Date.parse(value)));
13345
+ const discoveryNodeWire = z.object({
13346
+ number: z.int().positive(),
13347
+ updatedAt: timestamp$1,
13348
+ author: z.object({ login: z.string() }).nullable()
13349
+ });
13350
+ const baselineNodeWire = z.object({ updatedAt: timestamp$1 });
13256
13351
  function latestUpdatedAt(nodes, previous) {
13257
13352
  let high = previous;
13258
13353
  for (const node of nodes) {
13259
- const updated = sourceCursorSchema.parse(string$4(node.updatedAt));
13260
- const updatedMs = Date.parse(updated);
13261
- if (Number.isNaN(updatedMs)) throw new Error("Malformed GitHub updatedAt");
13262
- if (high === void 0 || updatedMs > Date.parse(high)) high = updated;
13354
+ const updated = sourceCursorSchema.parse(node.updatedAt);
13355
+ if (high === void 0 || Date.parse(updated) > Date.parse(high)) high = updated;
13263
13356
  }
13264
13357
  return high;
13265
13358
  }
@@ -13268,15 +13361,12 @@ function discover(nodes, previous, login) {
13268
13361
  let high = previous;
13269
13362
  const numbers = /* @__PURE__ */ new Set();
13270
13363
  for (const node of nodes) {
13271
- const updated = sourceCursorSchema.parse(string$4(node.updatedAt));
13364
+ const updated = sourceCursorSchema.parse(node.updatedAt);
13272
13365
  const updatedMs = Date.parse(updated);
13273
- if (Number.isNaN(updatedMs)) throw new Error("Malformed GitHub updatedAt");
13274
13366
  if (high === void 0 || updatedMs > Date.parse(high)) high = updated;
13275
13367
  if (previous !== void 0 && updatedMs < Date.parse(previous)) continue;
13276
- const author = record$2(node.author);
13277
- if (typeof author.login !== "string" || author.login.toLowerCase() !== login.toLowerCase()) continue;
13278
- const number = node.number;
13279
- if (typeof number === "number" && Number.isInteger(number) && number > 0) numbers.add(number);
13368
+ if (node.author?.login.toLowerCase() !== login.toLowerCase()) continue;
13369
+ numbers.add(node.number);
13280
13370
  }
13281
13371
  return {
13282
13372
  numbers: [...numbers],
@@ -13285,35 +13375,79 @@ function discover(nodes, previous, login) {
13285
13375
  }
13286
13376
  /** Pages are sorted newest first; older nodes end the scan, while ties must be revisited. */
13287
13377
  function pastCursor(nodes, previous) {
13288
- if (previous === void 0 || nodes.length === 0) return false;
13289
- const oldest = nodes[nodes.length - 1];
13290
- const updatedMs = Date.parse(string$4(oldest?.updatedAt));
13291
- if (Number.isNaN(updatedMs)) throw new Error("Malformed GitHub updatedAt");
13292
- return updatedMs < Date.parse(previous);
13378
+ const oldest = nodes.at(-1);
13379
+ if (previous === void 0 || oldest === void 0) return false;
13380
+ return Date.parse(oldest.updatedAt) < Date.parse(previous);
13293
13381
  }
13294
13382
  function nextPage(connection) {
13295
- const info = record$2(record$2(connection).pageInfo);
13296
- if (info.hasNextPage === false) return void 0;
13297
- if (info.hasNextPage !== true || typeof info.endCursor !== "string" || info.endCursor.length === 0) throw new Error("Malformed GitHub pagination");
13298
- return string$4(info.endCursor);
13383
+ const { hasNextPage, endCursor } = connection.pageInfo;
13384
+ if (!hasNextPage) return void 0;
13385
+ if (!endCursor) throw new Error("Malformed GitHub pagination");
13386
+ return endCursor;
13299
13387
  }
13300
13388
  //#endregion
13301
13389
  //#region ../adapters/src/github/prBatch.ts
13302
- function lower(value) {
13303
- return string$4(value).toLowerCase();
13304
- }
13305
- function optionalLogin(value) {
13306
- if (value === null || value === void 0) return void 0;
13307
- const login = record$2(value).login;
13308
- return typeof login === "string" ? login : void 0;
13309
- }
13390
+ const KEPT_REVIEWS = [
13391
+ "approved",
13392
+ "changes_requested",
13393
+ "dismissed"
13394
+ ];
13395
+ const actor = z.object({ login: z.string().optional() }).nullish();
13396
+ const checkRunWire = z.object({
13397
+ __typename: z.literal("CheckRun"),
13398
+ name: z.string(),
13399
+ status: z.string(),
13400
+ conclusion: z.string().nullable(),
13401
+ startedAt: z.string().nullish(),
13402
+ completedAt: z.string().nullable(),
13403
+ checkSuite: z.object({ createdAt: z.string() }).nullish(),
13404
+ isRequired: z.boolean().nullish()
13405
+ }).refine((run) => run.status !== "COMPLETED" || run.conclusion !== null, { path: ["conclusion"] });
13406
+ const statusContextWire = z.object({
13407
+ __typename: z.literal("StatusContext"),
13408
+ context: z.string(),
13409
+ state: z.string(),
13410
+ createdAt: z.string(),
13411
+ isRequired: z.boolean().nullish()
13412
+ });
13413
+ const contextWire = z.discriminatedUnion("__typename", [checkRunWire, statusContextWire]);
13414
+ const reviewWire = z.object({
13415
+ author: actor,
13416
+ state: z.string(),
13417
+ commit: z.object({ oid: z.string() }).nullable(),
13418
+ submittedAt: z.string().nullish()
13419
+ }).refine((review) => review.commit !== null || !review.author?.login || review.submittedAt == null || !KEPT_REVIEWS.includes(review.state.toLowerCase()), { path: ["commit"] });
13420
+ const nodes = (node) => z.object({ nodes: z.array(node) });
13421
+ const prWire = z.object({
13422
+ number: z.number(),
13423
+ url: z.string(),
13424
+ title: z.string(),
13425
+ updatedAt: z.string(),
13426
+ state: z.string(),
13427
+ isDraft: z.boolean(),
13428
+ mergeable: z.string(),
13429
+ mergeStateStatus: z.string(),
13430
+ author: actor,
13431
+ headRefName: z.string(),
13432
+ headRefOid: z.string(),
13433
+ statusCheckRollup: z.object({ contexts: nodes(contextWire) }).nullish(),
13434
+ reviews: nodes(reviewWire),
13435
+ reviewThreads: nodes(z.object({ isResolved: z.boolean() })),
13436
+ reviewRequests: nodes(z.object({
13437
+ requestedReviewer: z.object({
13438
+ login: z.string().nullish(),
13439
+ name: z.string().nullish()
13440
+ }),
13441
+ asCodeOwner: z.boolean()
13442
+ }))
13443
+ });
13310
13444
  function checkState(node) {
13311
13445
  if (node.__typename === "StatusContext") {
13312
- const state = lower(node.state);
13446
+ const state = node.state.toLowerCase();
13313
13447
  return state === "success" ? "success" : state === "pending" ? "pending" : state === "expected" ? "expected" : "failure";
13314
13448
  }
13315
13449
  if (node.status !== "COMPLETED") return "pending";
13316
- const value = lower(node.conclusion);
13450
+ const value = node.conclusion?.toLowerCase();
13317
13451
  return [
13318
13452
  "success",
13319
13453
  "neutral",
@@ -13328,11 +13462,10 @@ function checkState(node) {
13328
13462
  function latestChecks(nodes) {
13329
13463
  const latest = /* @__PURE__ */ new Map();
13330
13464
  for (const node of nodes) {
13331
- const name = string$4(node.__typename === "StatusContext" ? node.context : node.name);
13332
- const completedAt = node.__typename === "StatusContext" ? null : node.completedAt === null ? null : string$4(node.completedAt);
13333
- const startedAt = node.startedAt;
13334
- const suite = node.checkSuite;
13335
- const at = node.__typename === "StatusContext" ? string$4(node.createdAt) : typeof startedAt === "string" ? startedAt : suite === null || suite === void 0 ? completedAt ?? "" : string$4(record$2(suite).createdAt);
13465
+ const status = node.__typename === "StatusContext";
13466
+ const name = status ? node.context : node.name;
13467
+ const completedAt = status ? null : node.completedAt;
13468
+ const at = status ? node.createdAt : node.startedAt ?? node.checkSuite?.createdAt ?? completedAt ?? "";
13336
13469
  const old = latest.get(name);
13337
13470
  if (old !== void 0 && old.at > at) continue;
13338
13471
  latest.set(name, {
@@ -13354,19 +13487,15 @@ function latestChecks(nodes) {
13354
13487
  function latestReviews(nodes) {
13355
13488
  const latest = /* @__PURE__ */ new Map();
13356
13489
  for (const node of nodes) {
13357
- const reviewer = optionalLogin(node.author);
13358
- if (!reviewer || node.submittedAt === null || node.submittedAt === void 0) continue;
13359
- const state = lower(node.state);
13360
- if (![
13361
- "approved",
13362
- "changes_requested",
13363
- "dismissed"
13364
- ].includes(state)) continue;
13490
+ const reviewer = node.author?.login;
13491
+ if (!reviewer || node.submittedAt == null || node.commit === null) continue;
13492
+ const state = node.state.toLowerCase();
13493
+ if (!KEPT_REVIEWS.includes(state)) continue;
13365
13494
  const review = {
13366
13495
  reviewer,
13367
13496
  state,
13368
- commitSha: string$4(record$2(node.commit).oid),
13369
- submittedAt: string$4(node.submittedAt)
13497
+ commitSha: node.commit.oid,
13498
+ submittedAt: node.submittedAt
13370
13499
  };
13371
13500
  const old = latest.get(reviewer);
13372
13501
  if (old === void 0 || old.submittedAt <= review.submittedAt) latest.set(reviewer, review);
@@ -13383,13 +13512,12 @@ function ticketKeys(title, branch, prefixes) {
13383
13512
  }
13384
13513
  return [...keys];
13385
13514
  }
13386
- function normalizePr(repo, wire, prefixes) {
13387
- const rollupValue = wire.statusCheckRollup;
13388
- const rollup = rollupValue === null || rollupValue === void 0 ? null : record$2(rollupValue);
13389
- const checks = latestChecks(rollup === null ? [] : connectionNodes(record$2(rollup).contexts));
13515
+ function normalizePr(repo, value, prefixes) {
13516
+ const wire = parseWire(prWire, value, "Malformed GitHub PR response");
13517
+ const checks = latestChecks(wire.statusCheckRollup?.contexts.nodes ?? []);
13390
13518
  const state = wire.state === "MERGED" ? "merged" : wire.state === "CLOSED" ? "closed" : "open";
13391
13519
  const mergeable = wire.mergeable === "MERGEABLE" ? "mergeable" : wire.mergeable === "CONFLICTING" ? "conflicting" : "unknown";
13392
- const rawMerge = lower(wire.mergeStateStatus);
13520
+ const rawMerge = wire.mergeStateStatus.toLowerCase();
13393
13521
  const mergeState = [
13394
13522
  "behind",
13395
13523
  "blocked",
@@ -13399,14 +13527,14 @@ function normalizePr(repo, wire, prefixes) {
13399
13527
  "has_hooks",
13400
13528
  "unstable"
13401
13529
  ].includes(rawMerge) ? rawMerge : "unknown";
13402
- const title = string$4(wire.title);
13403
- const headBranch = string$4(wire.headRefName);
13530
+ const title = wire.title;
13531
+ const headBranch = wire.headRefName;
13404
13532
  const facts = {
13405
13533
  repo,
13406
13534
  number: wire.number,
13407
13535
  url: wire.url,
13408
13536
  title,
13409
- author: optionalLogin(wire.author),
13537
+ author: wire.author?.login,
13410
13538
  headSha: wire.headRefOid,
13411
13539
  headBranch,
13412
13540
  state,
@@ -13414,15 +13542,12 @@ function normalizePr(repo, wire, prefixes) {
13414
13542
  mergeable,
13415
13543
  mergeState,
13416
13544
  ...checks,
13417
- reviews: latestReviews(connectionNodes(wire.reviews)),
13418
- reviewThreads: connectionNodes(wire.reviewThreads).map((node) => ({ resolved: node.isResolved })),
13419
- reviewRequests: connectionNodes(wire.reviewRequests).map((node) => {
13420
- const reviewer = record$2(node.requestedReviewer);
13421
- return {
13422
- reviewer: reviewer.login ?? reviewer.name,
13423
- asCodeOwner: node.asCodeOwner
13424
- };
13425
- }),
13545
+ reviews: latestReviews(wire.reviews.nodes),
13546
+ reviewThreads: wire.reviewThreads.nodes.map((node) => ({ resolved: node.isResolved })),
13547
+ reviewRequests: wire.reviewRequests.nodes.map((node) => ({
13548
+ reviewer: node.requestedReviewer.login ?? node.requestedReviewer.name,
13549
+ asCodeOwner: node.asCodeOwner
13550
+ })),
13426
13551
  ticketKeys: ticketKeys(title, headBranch, prefixes),
13427
13552
  updatedAt: wire.updatedAt
13428
13553
  };
@@ -13432,6 +13557,18 @@ function normalizePr(repo, wire, prefixes) {
13432
13557
  }
13433
13558
  //#endregion
13434
13559
  //#region ../adapters/src/github/index.ts
13560
+ const MALFORMED$1 = "Malformed GitHub response";
13561
+ const discoveryRootWire = z.object({ pullRequests: connectionWire(discoveryNodeWire) });
13562
+ const baselineRootWire = z.object({ mergedBaseline: z.object({ nodes: z.array(baselineNodeWire) }) });
13563
+ const pagingWire = connectionWire(z.unknown());
13564
+ const prPagingWire = z.looseObject({
13565
+ reviews: pagingWire,
13566
+ reviewThreads: pagingWire,
13567
+ reviewRequests: pagingWire,
13568
+ statusCheckRollup: z.object({ contexts: pagingWire }).nullish()
13569
+ });
13570
+ const aliasWire = z.object({ pullRequest: prPagingWire.nullish() }).nullish();
13571
+ const pageRootWire = z.object({ pullRequest: prPagingWire.partial() });
13435
13572
  function sourceId(project, repo) {
13436
13573
  return `github:${project}:${repo.toLowerCase()}`;
13437
13574
  }
@@ -13481,27 +13618,30 @@ function rejectUnscoped(errors, roots) {
13481
13618
  function status(error) {
13482
13619
  return error.type === "NOT_FOUND" ? "not_found" : "no_access";
13483
13620
  }
13484
- function aliasPr(data, alias) {
13485
- const value = data[alias];
13486
- return value === null || value === void 0 ? null : nested(data, alias, "pullRequest");
13621
+ function connectionOf(pr, field) {
13622
+ return field === "contexts" ? pr.statusCheckRollup?.contexts : pr[field];
13487
13623
  }
13488
- function nested(value, ...path) {
13489
- let current = value;
13490
- for (const field of path) current = record$2(current)[field];
13491
- return current;
13492
- }
13493
- function contexts(pr) {
13494
- const value = pr.statusCheckRollup;
13495
- return value === null || value === void 0 ? void 0 : record$2(record$2(value).contexts);
13624
+ function withConnection(pr, field, connection) {
13625
+ return field === "contexts" ? {
13626
+ ...pr,
13627
+ statusCheckRollup: {
13628
+ ...pr.statusCheckRollup,
13629
+ contexts: connection
13630
+ }
13631
+ } : {
13632
+ ...pr,
13633
+ [field]: connection
13634
+ };
13496
13635
  }
13497
- async function fullPr(client, pr, owner, name, number, signal, budget) {
13636
+ async function fullPr(client, first, owner, name, number, signal, budget) {
13637
+ let pr = first;
13498
13638
  for (const field of [
13499
13639
  "reviews",
13500
13640
  "reviewThreads",
13501
13641
  "reviewRequests",
13502
13642
  "contexts"
13503
13643
  ]) {
13504
- const target = field === "contexts" ? contexts(pr) : record$2(pr[field]);
13644
+ let target = connectionOf(pr, field);
13505
13645
  if (target === void 0) continue;
13506
13646
  let cursor = nextPage(target);
13507
13647
  const seen = /* @__PURE__ */ new Set();
@@ -13518,12 +13658,14 @@ async function fullPr(client, pr, owner, name, number, signal, budget) {
13518
13658
  rejectUnscoped(response.errors, ["repository"]);
13519
13659
  requireCheckAccess(response.errors);
13520
13660
  if (response.errors.length > 0) return void 0;
13521
- const pagePr = record$2(nested(response.data, "repository", "pullRequest"));
13522
- const page = field === "contexts" ? contexts(pagePr) : record$2(pagePr[field]);
13661
+ const page = connectionOf(parseWire(pageRootWire, response.data.repository, MALFORMED$1, ["data", "repository"]).pullRequest, field);
13523
13662
  if (page === void 0) throw new AdapterError("transient", "Malformed GitHub pagination");
13524
- list(target.nodes).push(...list(page.nodes));
13663
+ target = {
13664
+ nodes: [...target.nodes, ...page.nodes],
13665
+ pageInfo: page.pageInfo
13666
+ };
13667
+ pr = withConnection(pr, field, target);
13525
13668
  cursor = nextPage(page);
13526
- target.pageInfo = page.pageInfo ?? null;
13527
13669
  }
13528
13670
  }
13529
13671
  return pr;
@@ -13547,8 +13689,8 @@ async function pollRepository({ id, repo, login, prefixes, client, ctx }) {
13547
13689
  const entities = [];
13548
13690
  const items = [];
13549
13691
  let discoveryOk = scoped(response.errors, "repository").length === 0;
13550
- const first = discoveryOk ? nested(response.data, "repository", "pullRequests") : void 0;
13551
- const nodes = first === void 0 ? [] : connectionNodes(first);
13692
+ const first = discoveryOk ? parseWire(discoveryRootWire, response.data.repository, MALFORMED$1, ["data", "repository"]).pullRequests : void 0;
13693
+ const nodes = first === void 0 ? [] : [...first.nodes];
13552
13694
  let cursor = first === void 0 || pastCursor(nodes, ctx.cursor) ? void 0 : nextPage(first);
13553
13695
  const seenPages = /* @__PURE__ */ new Set();
13554
13696
  while (cursor !== void 0 && discoveryOk) {
@@ -13565,15 +13707,14 @@ async function pollRepository({ id, repo, login, prefixes, client, ctx }) {
13565
13707
  discoveryOk = false;
13566
13708
  break;
13567
13709
  }
13568
- const connection = nested(page.data, "repository", "pullRequests");
13569
- const pageNodes = connectionNodes(connection);
13570
- nodes.push(...pageNodes);
13571
- cursor = pastCursor(pageNodes, ctx.cursor) ? void 0 : nextPage(connection);
13710
+ const connection = parseWire(discoveryRootWire, page.data.repository, MALFORMED$1, ["data", "repository"]).pullRequests;
13711
+ nodes.push(...connection.nodes);
13712
+ cursor = pastCursor(connection.nodes, ctx.cursor) ? void 0 : nextPage(connection);
13572
13713
  }
13573
13714
  if (!discoveryOk) complete = false;
13574
13715
  const found = discover(nodes, ctx.cursor, login);
13575
- const bootstrapCursor = bootstrap && discoveryOk ? latestUpdatedAt(connectionNodes(nested(response.data, "repository", "mergedBaseline")), found.cursor) ?? sourceCursorSchema.parse("1970-01-01T00:00:00.000Z") : void 0;
13576
- const process = async (number, wire, errors, ref) => {
13716
+ const bootstrapCursor = bootstrap && discoveryOk ? latestUpdatedAt(parseWire(baselineRootWire, response.data.repository, MALFORMED$1, ["data", "repository"]).mergedBaseline.nodes, found.cursor) ?? sourceCursorSchema.parse("1970-01-01T00:00:00.000Z") : void 0;
13717
+ const process = async (number, alias, data, errors, ref) => {
13577
13718
  requireCheckAccess(errors);
13578
13719
  const error = errors[0];
13579
13720
  if (error !== void 0) {
@@ -13585,6 +13726,7 @@ async function pollRepository({ id, repo, login, prefixes, client, ctx }) {
13585
13726
  });
13586
13727
  return false;
13587
13728
  }
13729
+ const wire = parseWire(aliasWire, data[alias], MALFORMED$1, ["data", alias])?.pullRequest;
13588
13730
  if (wire === null || wire === void 0) {
13589
13731
  if (ref) entities.push({
13590
13732
  ref,
@@ -13593,7 +13735,7 @@ async function pollRepository({ id, repo, login, prefixes, client, ctx }) {
13593
13735
  else complete = false;
13594
13736
  return false;
13595
13737
  }
13596
- const full = await fullPr(client, record$2(wire), owner, name, number, ctx.signal, (next) => {
13738
+ const full = await fullPr(client, wire, owner, name, number, ctx.signal, (next) => {
13597
13739
  budget = next;
13598
13740
  });
13599
13741
  if (full === void 0) {
@@ -13619,7 +13761,7 @@ async function pollRepository({ id, repo, login, prefixes, client, ctx }) {
13619
13761
  for (const [i, number] of numbers.entries()) {
13620
13762
  const alias = `pr${String(i)}`;
13621
13763
  const errors = scoped(response.errors, alias);
13622
- if (!await process(number, aliasPr(response.data, alias), errors, byNumber.get(number)) && found.numbers.includes(number)) discoveredOk = false;
13764
+ if (!await process(number, alias, response.data, errors, byNumber.get(number)) && found.numbers.includes(number)) discoveredOk = false;
13623
13765
  }
13624
13766
  const discovered = found.numbers.filter((number) => !byNumber.has(number));
13625
13767
  for (let offset = 0; offset < discovered.length; offset += 50) {
@@ -13632,7 +13774,7 @@ async function pollRepository({ id, repo, login, prefixes, client, ctx }) {
13632
13774
  rejectUnscoped(detail.errors, chunk.map((_, i) => `pr${String(i)}`));
13633
13775
  for (const [i, number] of chunk.entries()) {
13634
13776
  const alias = `pr${String(i)}`;
13635
- if (!await process(number, aliasPr(detail.data, alias), scoped(detail.errors, alias))) discoveredOk = false;
13777
+ if (!await process(number, alias, detail.data, scoped(detail.errors, alias))) discoveredOk = false;
13636
13778
  }
13637
13779
  }
13638
13780
  if (ctx.signal.aborted) throw new AdapterError("transient", "GitHub poll aborted");
@@ -13656,54 +13798,52 @@ var GithubIssuesHttpError = class extends AdapterError {
13656
13798
  this.status = status;
13657
13799
  }
13658
13800
  };
13659
- function object$3(value) {
13660
- if (value !== null && typeof value === "object" && !Array.isArray(value)) return value;
13661
- throw new AdapterError("transient", "Malformed GitHub issue response");
13662
- }
13663
- function string$3(value) {
13664
- if (typeof value === "string" && value.length > 0) return value;
13665
- throw new AdapterError("transient", "Malformed GitHub issue response");
13666
- }
13667
- function number(value) {
13668
- if (typeof value === "number" && Number.isSafeInteger(value) && value > 0) return value;
13669
- throw new AdapterError("transient", "Malformed GitHub issue response");
13670
- }
13801
+ const MALFORMED = "Malformed GitHub issue response";
13802
+ const text$2 = z.string().min(1);
13803
+ const issueWire$1 = z.object({
13804
+ node_id: text$2,
13805
+ number: z.int().positive(),
13806
+ title: text$2,
13807
+ state: text$2,
13808
+ html_url: text$2,
13809
+ updated_at: text$2.refine((value) => !Number.isNaN(Date.parse(value))),
13810
+ labels: z.array(z.object({ name: text$2 })),
13811
+ assignee: z.object({ login: text$2 }).nullish(),
13812
+ milestone: z.object({ title: text$2 }).nullish(),
13813
+ pull_request: z.unknown().optional()
13814
+ });
13815
+ const milestoneWire = z.object({
13816
+ title: z.string(),
13817
+ number: z.int().positive()
13818
+ });
13671
13819
  function issueNumber(ref, repo) {
13672
13820
  const match = /^(.+)#([1-9]\d*)$/.exec(ref.key);
13673
13821
  if (match?.[1]?.toLowerCase() !== repo.toLowerCase()) throw new AdapterError("config", "Requested issue is outside its configured repository");
13674
- return number(Number(match[2]));
13675
- }
13676
- function normalize(value, trackerId, repo, inFilter) {
13677
- const issue = object$3(value);
13678
- if (issue["pull_request"] !== void 0) throw new AdapterError("transient", "A pull request cannot be a tracker ticket");
13679
- const updatedAt = new Date(string$3(issue["updated_at"]));
13680
- if (Number.isNaN(updatedAt.getTime())) throw new AdapterError("transient", "Malformed GitHub issue timestamp");
13681
- const labels = issue["labels"];
13682
- if (!Array.isArray(labels)) throw new AdapterError("transient", "Malformed GitHub issue labels");
13683
- const assignee = issue["assignee"] == null ? null : string$3(object$3(issue["assignee"])["login"]);
13684
- const milestone = issue["milestone"] == null ? null : string$3(object$3(issue["milestone"])["title"]);
13822
+ const value = Number(match[2]);
13823
+ if (!Number.isSafeInteger(value) || value <= 0) throw new AdapterError("transient", MALFORMED);
13824
+ return value;
13825
+ }
13826
+ function normalize(issue, trackerId, repo, inFilter) {
13827
+ if (issue.pull_request !== void 0) throw new AdapterError("transient", "A pull request cannot be a tracker ticket");
13685
13828
  return {
13686
13829
  trackerId,
13687
- id: string$3(issue["node_id"]),
13688
- key: `${repo}#${String(number(issue["number"]))}`,
13689
- title: string$3(issue["title"]),
13690
- status: string$3(issue["state"]),
13691
- assignee,
13692
- sprint: milestone,
13693
- labels: labels.map((label) => string$3(object$3(label)["name"])),
13830
+ id: issue.node_id,
13831
+ key: `${repo}#${String(issue.number)}`,
13832
+ title: issue.title,
13833
+ status: issue.state,
13834
+ assignee: issue.assignee?.login ?? null,
13835
+ sprint: issue.milestone?.title ?? null,
13836
+ labels: issue.labels.map((label) => label.name),
13694
13837
  inFilter,
13695
- url: string$3(issue["html_url"]),
13696
- updatedAt: updatedAt.toISOString()
13838
+ url: issue.html_url,
13839
+ updatedAt: new Date(issue.updated_at).toISOString()
13697
13840
  };
13698
13841
  }
13699
13842
  function matchesFilter(issue, tracker) {
13700
- if (tracker.label !== void 0) {
13701
- const labels = issue["labels"];
13702
- return Array.isArray(labels) && labels.some((label) => object$3(label)["name"] === tracker.label);
13703
- }
13704
- return issue["milestone"] != null && object$3(issue["milestone"])["title"] === tracker.milestone;
13843
+ if (tracker.label !== void 0) return issue.labels.some((label) => label.name === tracker.label);
13844
+ return issue.milestone?.title === tracker.milestone;
13705
13845
  }
13706
- /** Lists tracker issues and resolves manually included keys outside the filter. */
13846
+ /** Lists open filter issues and resolves requested tickets missing from that listing. */
13707
13847
  function createGithubIssuesAdapter(options) {
13708
13848
  const transport = options.fetch ?? fetch;
13709
13849
  const [owner, name] = options.tracker.repo.split("/");
@@ -13771,8 +13911,7 @@ function createGithubIssuesAdapter(options) {
13771
13911
  };
13772
13912
  throw error;
13773
13913
  }
13774
- if (!Array.isArray(page.value)) throw new AdapterError("transient", "Malformed GitHub issue listing");
13775
- results.push(...page.value);
13914
+ results.push(...parseWire(z.array(z.unknown()), page.value, "Malformed GitHub issue listing"));
13776
13915
  next = page.next;
13777
13916
  }
13778
13917
  return {
@@ -13789,9 +13928,9 @@ function createGithubIssuesAdapter(options) {
13789
13928
  if (error instanceof GithubIssuesHttpError && error.status === 404) throw new AdapterError("config", "GitHub Issues repository is unavailable");
13790
13929
  throw error;
13791
13930
  }
13792
- const match = milestones.map(object$3).find((entry) => entry["title"] === options.tracker.milestone);
13931
+ const match = parseWire(z.array(milestoneWire), milestones, MALFORMED).find((entry) => entry.title === options.tracker.milestone);
13793
13932
  if (match === void 0) throw new AdapterError("config", "Configured GitHub milestone is missing");
13794
- return number(match["number"]);
13933
+ return match.number;
13795
13934
  }
13796
13935
  return {
13797
13936
  id: options.id,
@@ -13800,7 +13939,7 @@ function createGithubIssuesAdapter(options) {
13800
13939
  const observedAt = (/* @__PURE__ */ new Date()).toISOString();
13801
13940
  const milestone = await milestoneNumber(ctx.signal);
13802
13941
  const filter = new URL(`${root}/issues`);
13803
- filter.searchParams.set("state", "all");
13942
+ filter.searchParams.set("state", "open");
13804
13943
  filter.searchParams.set("per_page", "100");
13805
13944
  if (options.tracker.label !== void 0) filter.searchParams.set("labels", options.tracker.label);
13806
13945
  if (milestone !== void 0) filter.searchParams.set("milestone", String(milestone));
@@ -13817,10 +13956,9 @@ function createGithubIssuesAdapter(options) {
13817
13956
  }
13818
13957
  const facts = /* @__PURE__ */ new Map();
13819
13958
  for (const value of listed) {
13820
- const issue = object$3(value);
13821
- if (issue["pull_request"] !== void 0) continue;
13822
- const fact = normalize(issue, options.id, options.tracker.repo, true);
13823
- facts.set(number(issue["number"]), fact);
13959
+ const issue = parseWire(issueWire$1, value, MALFORMED);
13960
+ if (issue.pull_request !== void 0) continue;
13961
+ facts.set(issue.number, normalize(issue, options.id, options.tracker.repo, true));
13824
13962
  }
13825
13963
  const entities = [];
13826
13964
  for (const ref of ctx.observe.tickets) {
@@ -13828,8 +13966,8 @@ function createGithubIssuesAdapter(options) {
13828
13966
  const issueNo = issueNumber(ref, options.tracker.repo);
13829
13967
  let fact = facts.get(issueNo);
13830
13968
  if (fact === void 0) try {
13831
- const detail = object$3((await request(`${root}/issues/${String(issueNo)}`, ctx.signal)).value);
13832
- if (detail["pull_request"] !== void 0) {
13969
+ const detail = parseWire(issueWire$1, (await request(`${root}/issues/${String(issueNo)}`, ctx.signal)).value, MALFORMED);
13970
+ if (detail.pull_request !== void 0) {
13833
13971
  entities.push({
13834
13972
  ref,
13835
13973
  status: "not_found"
@@ -13839,7 +13977,7 @@ function createGithubIssuesAdapter(options) {
13839
13977
  fact = normalize(detail, options.id, options.tracker.repo, matchesFilter(detail, options.tracker));
13840
13978
  facts.set(issueNo, fact);
13841
13979
  } catch (error) {
13842
- if (error instanceof GithubIssuesHttpError && error.status === 404) {
13980
+ if (error instanceof GithubIssuesHttpError && (error.status === 404 || error.status === 410)) {
13843
13981
  entities.push({
13844
13982
  ref,
13845
13983
  status: "not_found"
@@ -13882,6 +14020,37 @@ const MAX_GET_SEARCH_URL_LENGTH = 2e3;
13882
14020
  const OUTSIDE_BATCH_SIZE = 50;
13883
14021
  const FALLBACK_REQUEST_LIMIT = 100;
13884
14022
  const SPRINT_SCHEMA = "com.pyxis.greenhopper.jira:gh-sprint";
14023
+ const INVALID = "Invalid Jira response";
14024
+ const text$1 = z.string().min(1);
14025
+ const timestamp = text$1.refine((value) => !Number.isNaN(Date.parse(value)));
14026
+ const statusesWire = z.array(z.object({ statuses: z.array(z.object({ name: text$1 })) }));
14027
+ const fieldWire = z.object({
14028
+ id: text$1,
14029
+ schema: z.object({ custom: z.string().optional() }).nullish()
14030
+ });
14031
+ const issueWire = z.object({
14032
+ id: text$1,
14033
+ key: text$1,
14034
+ fields: z.looseObject({
14035
+ summary: text$1,
14036
+ status: z.object({ name: text$1 }),
14037
+ assignee: z.object({
14038
+ accountId: z.string().nullish(),
14039
+ displayName: z.string().nullish()
14040
+ }).refine((assignee) => (assignee.accountId ?? assignee.displayName ?? "").length > 0, { path: ["accountId"] }).nullish(),
14041
+ labels: z.array(text$1),
14042
+ updated: timestamp
14043
+ })
14044
+ });
14045
+ const searchPageWire = z.object({
14046
+ issues: z.array(issueWire),
14047
+ nextPageToken: z.string().nullish(),
14048
+ isLast: z.boolean().optional()
14049
+ });
14050
+ const sprintWire = z.array(z.union([z.string(), z.object({
14051
+ name: z.string().optional(),
14052
+ state: z.string().optional()
14053
+ })])).nullish();
13885
14054
  var JiraHttpError = class extends AdapterError {
13886
14055
  status;
13887
14056
  constructor(status, failure) {
@@ -13889,18 +14058,6 @@ var JiraHttpError = class extends AdapterError {
13889
14058
  this.status = status;
13890
14059
  }
13891
14060
  };
13892
- function object$2(value) {
13893
- if (value !== null && typeof value === "object" && !Array.isArray(value)) return value;
13894
- throw new AdapterError("transient", "Invalid Jira response");
13895
- }
13896
- function string$2(value) {
13897
- if (typeof value === "string" && value.length > 0) return value;
13898
- throw new AdapterError("transient", "Invalid Jira response");
13899
- }
13900
- function array(value) {
13901
- if (Array.isArray(value)) return value;
13902
- throw new AdapterError("transient", "Invalid Jira response");
13903
- }
13904
14061
  function keyQuery(refs) {
13905
14062
  return `key in (${refs.map((ref) => `"${ref.key.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"")}"`).join(", ")})`;
13906
14063
  }
@@ -13924,51 +14081,34 @@ function membershipQuery(jql, refs) {
13924
14081
  return `(${jql.trim()}) AND ${keyQuery(refs)}`;
13925
14082
  }
13926
14083
  function sprintName(value) {
13927
- if (!Array.isArray(value)) return null;
13928
- const sprints = value.map((entry) => {
13929
- if (typeof entry === "string") return {
13930
- state: /(?:^|,)state=([^,\]]+)/i.exec(entry)?.[1]?.toLowerCase(),
13931
- name: /(?:^|,)name=(.*?)(?:,goal=|,startDate=|,endDate=|\]$)/i.exec(entry)?.[1]
13932
- };
13933
- if (entry !== null && typeof entry === "object" && !Array.isArray(entry)) {
13934
- const sprint = entry;
13935
- return {
13936
- state: sprint["state"],
13937
- name: sprint["name"]
13938
- };
13939
- }
14084
+ const sprints = (value ?? []).map((entry) => {
14085
+ if (typeof entry !== "string") return entry;
13940
14086
  return {
13941
- state: void 0,
13942
- name: void 0
14087
+ state: /(?:^|,)state=([^,\]]+)/i.exec(entry)?.[1],
14088
+ name: /(?:^|,)name=(.*?)(?:,goal=|,startDate=|,endDate=|\]$)/i.exec(entry)?.[1]
13943
14089
  };
13944
14090
  });
13945
14091
  for (const state of ["active", "future"]) {
13946
- const selected = sprints.find((sprint) => typeof sprint.state === "string" && sprint.state.toLowerCase() === state && typeof sprint.name === "string" && sprint.name.length > 0);
13947
- if (typeof selected?.name === "string") return selected.name;
14092
+ const selected = sprints.find((sprint) => sprint.state?.toLowerCase() === state && (sprint.name?.length ?? 0) > 0);
14093
+ if (selected?.name !== void 0) return selected.name;
13948
14094
  }
13949
14095
  return null;
13950
14096
  }
13951
- function issueFacts(value, trackerId, baseUrl, sprintField, inFilter) {
13952
- const issue = object$2(value);
13953
- const fields = object$2(issue["fields"]);
13954
- const status = object$2(fields["status"]);
13955
- const assignee = fields["assignee"] == null ? null : object$2(fields["assignee"]);
13956
- const key = string$2(issue["key"]);
13957
- const updated = string$2(fields["updated"]);
13958
- const updatedAt = new Date(updated);
13959
- if (Number.isNaN(updatedAt.getTime())) throw new AdapterError("transient", "Invalid Jira response");
14097
+ function issueFacts(issue, trackerId, baseUrl, sprintField, inFilter) {
14098
+ const { fields, key } = issue;
14099
+ const assignee = fields.assignee ?? null;
13960
14100
  return {
13961
14101
  trackerId,
13962
- id: string$2(issue["id"]),
14102
+ id: issue.id,
13963
14103
  key,
13964
- title: string$2(fields["summary"]),
13965
- status: string$2(status["name"]),
13966
- assignee: assignee === null ? null : string$2(assignee["accountId"] ?? assignee["displayName"]),
13967
- sprint: sprintField === null ? null : sprintName(fields[sprintField]),
13968
- labels: array(fields["labels"]).map(string$2),
14104
+ title: fields.summary,
14105
+ status: fields.status.name,
14106
+ assignee: assignee === null ? null : assignee.accountId ?? assignee.displayName ?? null,
14107
+ sprint: sprintField === null ? null : sprintName(parseWire(sprintWire, fields[sprintField], INVALID, ["fields", sprintField])),
14108
+ labels: fields.labels,
13969
14109
  inFilter,
13970
14110
  url: new URL(`/browse/${encodeURIComponent(key)}`, baseUrl).toString(),
13971
- updatedAt: updatedAt.toISOString()
14111
+ updatedAt: new Date(fields.updated).toISOString()
13972
14112
  };
13973
14113
  }
13974
14114
  /** Creates one Jira source. Credentials and transport come from the eventual runtime caller. */
@@ -14001,7 +14141,7 @@ function createJiraAdapter(options) {
14001
14141
  try {
14002
14142
  return await response.json();
14003
14143
  } catch {
14004
- throw new AdapterError("transient", "Invalid Jira response");
14144
+ throw new AdapterError("transient", INVALID);
14005
14145
  }
14006
14146
  }
14007
14147
  async function validate(tracker, signal) {
@@ -14014,20 +14154,12 @@ function createJiraAdapter(options) {
14014
14154
  if (error instanceof JiraHttpError && error.status === 404) throw new AdapterError("config", `Unknown Jira project key ${key}`);
14015
14155
  throw error;
14016
14156
  }
14017
- const names = new Set(array(result).flatMap((entry) => array(object$2(entry)["statuses"]).map((status) => string$2(object$2(status)["name"]))));
14157
+ const names = new Set(parseWire(statusesWire, result, INVALID).flatMap((entry) => entry.statuses.map((status) => status.name)));
14018
14158
  for (const name of [...tracker.doneStatuses, ...tracker.readyStatuses]) if (!names.has(name)) throw new AdapterError("config", `Unknown Jira status ${name} in project ${key}`);
14019
14159
  }
14020
14160
  }
14021
14161
  async function findSprintField(tracker, signal) {
14022
- const fields = array(await request(tracker.baseUrl, "/rest/api/3/field", signal));
14023
- for (const field of fields) {
14024
- const entry = object$2(field);
14025
- const schema = entry["schema"];
14026
- if (schema !== null && typeof schema === "object" && !Array.isArray(schema)) {
14027
- if (schema["custom"] === SPRINT_SCHEMA) return string$2(entry["id"]);
14028
- }
14029
- }
14030
- return null;
14162
+ return parseWire(z.array(fieldWire), await request(tracker.baseUrl, "/rest/api/3/field", signal), INVALID).find((field) => field.schema?.custom === SPRINT_SCHEMA)?.id ?? null;
14031
14163
  }
14032
14164
  async function search(tracker, signal, jql, sprintField, beforePage) {
14033
14165
  const issues = [];
@@ -14056,17 +14188,17 @@ function createJiraAdapter(options) {
14056
14188
  ...token === void 0 ? {} : { nextPageToken: token }
14057
14189
  }).toString()}` : "/rest/api/3/search/jql";
14058
14190
  if (options.searchMethod === "GET" && new URL(path, tracker.baseUrl).href.length > MAX_GET_SEARCH_URL_LENGTH) throw new AdapterError("config", `Jira GET search URL is too long (over ${String(MAX_GET_SEARCH_URL_LENGTH)} characters)`);
14059
- const result = object$2(await request(tracker.baseUrl, path, signal, options.searchMethod === "GET" ? void 0 : body));
14060
- issues.push(...array(result["issues"]));
14061
- const next = result["nextPageToken"];
14191
+ const result = parseWire(searchPageWire, await request(tracker.baseUrl, path, signal, options.searchMethod === "GET" ? void 0 : body), INVALID);
14192
+ issues.push(...result.issues);
14193
+ const next = result.nextPageToken;
14062
14194
  if (next == null || next === "") {
14063
- if (result["isLast"] === false) throw new AdapterError("transient", "Jira search omitted its next page token");
14195
+ if (result.isLast === false) throw new AdapterError("transient", "Jira search omitted its next page token");
14064
14196
  return {
14065
14197
  issues,
14066
14198
  complete: true
14067
14199
  };
14068
14200
  }
14069
- token = string$2(next);
14201
+ token = next;
14070
14202
  if (seen.has(token)) throw new AdapterError("transient", "Jira search repeated a page token");
14071
14203
  seen.add(token);
14072
14204
  }
@@ -14078,8 +14210,8 @@ function createJiraAdapter(options) {
14078
14210
  async function fetchById(tracker, ref, signal, beforeRequest) {
14079
14211
  try {
14080
14212
  beforeRequest();
14081
- const issue = object$2(await request(tracker.baseUrl, `/rest/api/3/issue/${encodeURIComponent(ref.id)}`, signal));
14082
- if (string$2(issue["id"]) !== ref.id) throw new AdapterError("transient", "Jira returned a different ticket id");
14213
+ const issue = parseWire(issueWire, await request(tracker.baseUrl, `/rest/api/3/issue/${encodeURIComponent(ref.id)}`, signal), INVALID);
14214
+ if (issue.id !== ref.id) throw new AdapterError("transient", "Jira returned a different ticket id");
14083
14215
  return issue;
14084
14216
  } catch (error) {
14085
14217
  if (error instanceof JiraHttpError && (error.status === 404 || error.status === 403 && error.kind === "auth")) return null;
@@ -14104,8 +14236,8 @@ function createJiraAdapter(options) {
14104
14236
  }
14105
14237
  async function fetchPending(tracker, ref, signal) {
14106
14238
  try {
14107
- const issue = object$2(await request(tracker.baseUrl, `/rest/api/3/issue/${encodeURIComponent(ref.key)}`, signal));
14108
- if (string$2(issue["key"]) !== ref.key) throw new AdapterError("transient", "Jira returned a different ticket key");
14239
+ const issue = parseWire(issueWire, await request(tracker.baseUrl, `/rest/api/3/issue/${encodeURIComponent(ref.key)}`, signal), INVALID);
14240
+ if (issue.key !== ref.key) throw new AdapterError("transient", "Jira returned a different ticket key");
14109
14241
  return {
14110
14242
  status: "ok",
14111
14243
  issue
@@ -14156,7 +14288,7 @@ function createJiraAdapter(options) {
14156
14288
  if (issue === null) return [];
14157
14289
  const current = await search(tracker, ctx.signal, membershipQuery(tracker.jql, [{
14158
14290
  ...ref,
14159
- key: string$2(issue["key"])
14291
+ key: issue.key
14160
14292
  }]), sprintField, countFallbackRequest);
14161
14293
  if (!current.complete) throw new AdapterError("transient", "Jira membership search reached its page limit");
14162
14294
  return current.issues;
@@ -14658,7 +14790,7 @@ function createSpurAdapter(options) {
14658
14790
  status: listResponse.status,
14659
14791
  headers: listResponse.headers
14660
14792
  }, Date.now());
14661
- const listed = z.array(sessionWire).parse(listBody);
14793
+ const listed = parseWire(z.array(sessionWire), listBody, "Invalid Spur response");
14662
14794
  const byId = new Map(listed.map((wire) => [wire.id, wire]));
14663
14795
  const detail = /* @__PURE__ */ new Map();
14664
14796
  for (const ref of ctx.observe.sessions) {
@@ -14672,7 +14804,7 @@ function createSpurAdapter(options) {
14672
14804
  status: response.status,
14673
14805
  headers: response.headers
14674
14806
  }, Date.now());
14675
- const wire = sessionWire.parse(body);
14807
+ const wire = parseWire(sessionWire, body, "Invalid Spur response");
14676
14808
  if (wire.id !== ref.id) throw new AdapterError("transient", "Unresolved Spur session detail");
14677
14809
  detail.set(ref.id, wire);
14678
14810
  }