spur-board 0.62.1 → 0.63.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 EVENT_KINDS, B as ringMarker, D as interactionRefSchema, E as inboundEventSchema, F as SESSION_STATUSES, G as actorIdSchema, H as ticketFactsSchema, I as isExternalAuthor, J as parseActorId, K as encodeActorId, L as parseRingMarker, M as PR_STATES, N as REVIEW_STATES, O as messageRefSchema, P as SESSION_HEALTH_STATES, R as prFactsSchema, T as conversationRefSchema, U as JIRA_PROJECT_KEY, V as sessionFactsSchema, W as REF_NUMBER, X as ERRORS, Y as parseRef$1, Z as err, _ as buildCatalogSnapshot, a as requestHashOf, at as DEFAULT_SLACK_COMMAND, b as turnHandedSchema, c as tokenRequestStatusSchema, ct as plainHttpAllowed, d as AdapterError, dt as DISPATCHER_MODES, et as ok, f as batchSchema, ft as SLACK_BOT_SCOPES, g as trackerSourceId, h as sourceCursorSchema, i as TOKEN_REQUEST_LIMITS, j as eventPayloadSchemas, k as userIdSchema, l as BOARD_TICK_MS, lt as requiredSecretKeys, m as prSourceId, n as doctorReportSchema, o as tokenRequestResultSchema, ot as RESERVED_PROJECT, p as entityRefSchema, pt as TASK_HOLDS, q as errorCodeOf, rt as DEFAULT_LINK, s as tokenRequestSchema, st as configSchema, t as assertNever, tt as successEnvelopeSchema, ut as COLUMN_IDS, v as roleCanUseOperation, w as SPACE_IDS, x as renderHttpProblem, y as OPERATIONS, z as prRefSchema } from "./chunk-CzdGYlBy.mjs";
1
+ import { A as sessionTransitionSchema, B as prRefSchema, C as userIdSchema, D as batchSchema, E as AdapterError, F as SESSION_HEALTH_STATES, G as REF_NUMBER, H as sessionFactsSchema, I as SESSION_STATUSES, J as errorCodeOf, K as actorIdSchema, L as isExternalAuthor, M as trackerSourceId, N as PR_STATES, O as entityRefSchema, P as REVIEW_STATES, Q as err, R as parseRingMarker, S as messageRefSchema, T as eventPayloadSchemas, U as ticketFactsSchema, V as ringMarker, W as JIRA_PROJECT_KEY, X as parseRef$1, Y as parseActorId, Z as ERRORS, a as requestHashOf, b as inboundEventSchema, c as tokenRequestStatusSchema, ct as configSchema, d as buildCatalogSnapshot, dt as COLUMN_IDS, f as roleCanUseOperation, ft as DISPATCHER_MODES, h as renderHttpProblem, i as TOKEN_REQUEST_LIMITS, it as DEFAULT_LINK, j as sourceCursorSchema, k as prSourceId, l as BOARD_TICK_MS, lt as plainHttpAllowed, m as turnHandedSchema, mt as TASK_HOLDS, n as doctorReportSchema, nt as successEnvelopeSchema, o as tokenRequestResultSchema, ot as DEFAULT_SLACK_COMMAND, p as OPERATIONS, pt as SLACK_BOT_SCOPES, q as encodeActorId, s as tokenRequestSchema, st as RESERVED_PROJECT, t as assertNever, tt as ok, ut as requiredSecretKeys, v as SPACE_IDS, w as EVENT_KINDS, x as interactionRefSchema, y as conversationRefSchema, z as prFactsSchema } from "./chunk-BONq7Qxa.mjs";
2
2
  import { t as apiBaseUrl } from "./chunk-DAMwWWmT.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import { createHash, randomUUID } from "node:crypto";
@@ -9558,9 +9558,12 @@ function personaFor(config, subject, actor) {
9558
9558
  };
9559
9559
  const parsed = parseActorId(actor);
9560
9560
  if (parsed?.actor !== "agent") throw new Error("Invalid actor");
9561
+ const { project } = parsed.actorRef;
9562
+ const entry = config.projects.flatMap((p) => p.spurProjects).find((spur) => spur.name === project);
9561
9563
  return {
9562
- name: parsed.actorRef.project,
9563
- role: personaRole(authorRole(config, subject, actor))
9564
+ name: entry?.displayName ?? project,
9565
+ role: personaRole(authorRole(config, subject, actor)),
9566
+ ...entry?.icon === void 0 ? {} : { icon: entry.icon }
9564
9567
  };
9565
9568
  }
9566
9569
  async function queueBlockOpen(trx, subject, block, ctx, config) {
@@ -14225,15 +14228,16 @@ function workStarted(input) {
14225
14228
  return input.openPr || !input.reopened && workerLive;
14226
14229
  }
14227
14230
  /**
14228
- * What holds the dispatcher on the task now: a blind GitHub stops it, a blind Spur defers a
14229
- * worker's turn, an active cycle-limit or course-check item stops every turn and move right, and
14230
- * To Do and Ready for Dev wait for the work to start. The last is judged at the task's column,
14231
- * while `dispatch` judges it at each column the cascade reaches.
14231
+ * What holds the dispatcher on the task now: a blind GitHub or a pending submit stops it, a blind
14232
+ * Spur defers a worker's turn, an active cycle-limit or course-check item stops every turn and
14233
+ * move right, and To Do and Ready for Dev wait for the work to start. The last is judged at the
14234
+ * task's column, while `dispatch` judges it at each column the cascade reaches.
14232
14235
  */
14233
14236
  function dispatchHolds(input) {
14234
14237
  const holds = [];
14235
14238
  if (input.githubBlind) holds.push("github_blind");
14236
14239
  if (input.spurBlind) holds.push("spur_blind");
14240
+ if (input.submitPending) holds.push("submit_pending");
14237
14241
  if (input.cycleHeld) holds.push("cycle_limit");
14238
14242
  if ((input.column === "todo" || input.column === "ready-for-dev") && !workStarted(input)) holds.push("work_not_started");
14239
14243
  return holds;
@@ -14245,13 +14249,14 @@ function dispatchHolds(input) {
14245
14249
  */
14246
14250
  function dispatch(input) {
14247
14251
  const moves = [];
14248
- if (input.githubBlind) return {
14252
+ if (input.githubBlind || input.submitPending) return {
14249
14253
  moves,
14250
14254
  turn: null
14251
14255
  };
14252
14256
  const { project, reopened, cycleHeld } = input;
14253
14257
  const workerLive = input.liveWorker && !input.spurBlind;
14254
14258
  const started = workStarted(input);
14259
+ const handsBack = input.submitFailed && input.turn.visit !== "unclosed";
14255
14260
  let { column, facts, turn } = input;
14256
14261
  const move = (to, reason, gate) => {
14257
14262
  moves.push({
@@ -14320,7 +14325,7 @@ function dispatch(input) {
14320
14325
  }
14321
14326
  const executor = orchestratorOf(project, column);
14322
14327
  if (column === "external-review" && executor === "none") return result(null);
14323
- if (reasons.includes("pr_closed")) return result(null);
14328
+ if (reasons.includes("pr_closed") && !handsBack) return result(null);
14324
14329
  switch (turn.visit) {
14325
14330
  case "none": return result({
14326
14331
  column,
@@ -14622,7 +14627,8 @@ function evaluateSessionHealth(input) {
14622
14627
  statuses.push({
14623
14628
  taskId: session.taskId,
14624
14629
  sessionId: session.id,
14625
- kind: "rate_limited"
14630
+ kind: "rate_limited",
14631
+ ...session.rateLimitResetAt === void 0 ? {} : { rateLimitResetAt: session.rateLimitResetAt }
14626
14632
  });
14627
14633
  continue;
14628
14634
  }
@@ -15124,22 +15130,25 @@ const MARK_COLUMNS = ["review", "product-review"];
15124
15130
  const indexOf = (column) => COLUMN_IDS.indexOf(column);
15125
15131
  /**
15126
15132
  * Sets `voided_at` on the unvoided submits of `columns`. Review and product-review marks are
15127
- * not voided by a move; a new PR head voids them (`voidMarksOffHead`).
15133
+ * not voided by a move; a new PR head voids them (`voidMarksOffHead`). A pending submit is never
15134
+ * voided here: it settles only when its hand-back turn opens, as confirmed, or as superseded by
15135
+ * a merge (`readPendingSubmit`), and counts as no mark until then.
15128
15136
  */
15129
15137
  async function voidColumns(trx, taskId, columns, at) {
15130
15138
  const voided = columns.filter((column) => !MARK_COLUMNS.includes(column));
15131
15139
  if (voided.length === 0) return;
15132
- await trx.updateTable("submission").set({ voided_at: at.toISOString() }).where("task_id", "=", taskId).where("voided_at", "is", null).where("column", "in", voided).execute();
15140
+ await trx.updateTable("submission").set({ voided_at: at.toISOString() }).where("task_id", "=", taskId).where("voided_at", "is", null).where("pending_until", "is", null).where("column", "in", voided).execute();
15133
15141
  }
15134
15142
  /**
15135
15143
  * Sets `voided_at` on the unvoided Review and Product Review marks of PR `repo#number` that are
15136
15144
  * not on `head`, for the PR's new head: a mark lasts only while its head stays the PR's head, so
15137
15145
  * a head that comes back to an earlier commit needs fresh marks. Marks made before submissions
15138
- * recorded their PR count for the tasks linked to the PR.
15146
+ * recorded their PR count for the tasks linked to the PR. A pending mark is left to the
15147
+ * dispatcher, which hands it back with the new head (`readPendingSubmit`).
15139
15148
  */
15140
15149
  async function voidMarksOffHead(trx, input) {
15141
15150
  const repo = input.repo.toLowerCase();
15142
- await trx.updateTable("submission").set({ voided_at: input.at }).where("voided_at", "is", null).where("column", "in", MARK_COLUMNS).where(sql`lower(commit_sha) != ${input.head.toLowerCase()}`).where((eb) => eb.or([eb.and([eb(sql`lower(pr_repo)`, "=", repo), eb("pr_number", "=", input.number)]), eb.and([eb("pr_repo", "is", null), eb("task_id", "in", eb.selectFrom("link").select("task_id").where("entity", "=", "pr").where(sql`lower(repo) = ${repo}`).where("number", "=", input.number))])])).execute();
15151
+ await trx.updateTable("submission").set({ voided_at: input.at }).where("voided_at", "is", null).where("column", "in", MARK_COLUMNS).where("pending_until", "is", null).where(sql`lower(commit_sha) != ${input.head.toLowerCase()}`).where((eb) => eb.or([eb.and([eb(sql`lower(pr_repo)`, "=", repo), eb("pr_number", "=", input.number)]), eb.and([eb("pr_repo", "is", null), eb("task_id", "in", eb.selectFrom("link").select("task_id").where("entity", "=", "pr").where(sql`lower(repo) = ${repo}`).where("number", "=", input.number))])])).execute();
15143
15152
  }
15144
15153
  /** Voids the submits of `to` and every column right of it, as a left move does. */
15145
15154
  async function voidSubmits(trx, taskId, to, at) {
@@ -15418,11 +15427,115 @@ function handedOf(pr, entry) {
15418
15427
  postedAt: entry.postedAt
15419
15428
  };
15420
15429
  }
15430
+ /** The clock passed `until` and a complete poll of each of `repos` started at or after it. */
15431
+ function pastBound(project, until, input, repos) {
15432
+ const bound = Date.parse(until);
15433
+ if (input.at.getTime() < bound) return false;
15434
+ return repos.every((repo) => {
15435
+ const since = input.complete.get(prSourceId(project.id, repo));
15436
+ return since !== void 0 && Date.parse(since) >= bound;
15437
+ });
15438
+ }
15439
+ /**
15440
+ * The newest unvoided pending submit of the task's current visit in `on` mode, settled from
15441
+ * stored facts (`settlePending`). With `carry` (no turn yet in the current visit), the task's
15442
+ * newest submission from an earlier visit counts too, but only once it failed or was superseded:
15443
+ * a left move whose
15444
+ * turn was deferred or held still hands the failure back with the turn it opens later. Such a
15445
+ * row never confirms or holds the task here.
15446
+ */
15447
+ async function readPendingSubmit(trx, task, project, input) {
15448
+ const current = await trx.selectFrom("submission").select([
15449
+ "id",
15450
+ "commit_sha",
15451
+ "author",
15452
+ "submitted_at",
15453
+ "pending_until"
15454
+ ]).where("task_id", "=", task.id).where("column", "=", task.column).where("epoch", "=", task.column_epoch).where("voided_at", "is", null).where("pending_until", "is not", null).orderBy("id", "desc").executeTakeFirst();
15455
+ if (current?.pending_until != null) return settlePending(trx, {
15456
+ ...current,
15457
+ pending_until: current.pending_until
15458
+ }, project, input);
15459
+ if (!input.carry) return void 0;
15460
+ const newest = await trx.selectFrom("submission").select([
15461
+ "id",
15462
+ "commit_sha",
15463
+ "author",
15464
+ "submitted_at",
15465
+ "pending_until",
15466
+ "voided_at"
15467
+ ]).where("task_id", "=", task.id).orderBy("id", "desc").executeTakeFirst();
15468
+ if (newest?.pending_until == null || newest.voided_at !== null) return void 0;
15469
+ const settled = await settlePending(trx, {
15470
+ ...newest,
15471
+ pending_until: newest.pending_until
15472
+ }, project, input);
15473
+ return settled.state === "failed" || settled.state === "superseded" ? settled : void 0;
15474
+ }
15475
+ /**
15476
+ * Settles a pending submit from stored facts: the linked PR's snapshot observed at or after the
15477
+ * submit decides it, and so does a merged one observed before; a closed one observed before fails
15478
+ * it, and no PR linked fails it, only once the bound passed and a complete poll of the PR's repo,
15479
+ * or of every project repo, started at or after the bound. Nothing settles while GitHub is blind.
15480
+ */
15481
+ async function settlePending(trx, row, project, input) {
15482
+ const sha = row.commit_sha.toLowerCase();
15483
+ const pending = {
15484
+ id: row.id,
15485
+ sha,
15486
+ until: row.pending_until,
15487
+ state: "pending"
15488
+ };
15489
+ if (input.githubBlind) return pending;
15490
+ const { link } = input;
15491
+ if (link !== null) {
15492
+ const snap = await trx.selectFrom("pr_snapshot").select([
15493
+ "head_sha",
15494
+ "state",
15495
+ "observed_at"
15496
+ ]).where(sql`lower(repo) = ${link.repo.toLowerCase()}`).where("number", "=", link.number).executeTakeFirst();
15497
+ if (snap === void 0) return pending;
15498
+ const stale = Date.parse(snap.observed_at) < Date.parse(row.submitted_at);
15499
+ if (snap.state === "open" && stale) return pending;
15500
+ if (snap.state === "closed") {
15501
+ if (stale && !pastBound(project, row.pending_until, input, [link.repo])) return pending;
15502
+ return {
15503
+ ...pending,
15504
+ state: "failed",
15505
+ failure: `PR ${link.repo}#${String(link.number)} closed`
15506
+ };
15507
+ }
15508
+ if (snap.head_sha.toLowerCase() === sha) return {
15509
+ ...pending,
15510
+ state: "confirmed",
15511
+ pr: link
15512
+ };
15513
+ if (snap.state === "merged") return {
15514
+ ...pending,
15515
+ state: "superseded",
15516
+ head: snap.head_sha.toLowerCase()
15517
+ };
15518
+ return {
15519
+ ...pending,
15520
+ state: "failed",
15521
+ failure: `head moved to ${snap.head_sha.toLowerCase().slice(0, 7)}`
15522
+ };
15523
+ }
15524
+ if (!pastBound(project, row.pending_until, input, project.repos)) return pending;
15525
+ const parsed = parseActorId(row.author);
15526
+ const session = parsed?.actor === "agent" ? parsed.actorRef.session : void 0;
15527
+ const branch = session === void 0 ? void 0 : (await trx.selectFrom("session_snapshot").select("branch").where("id", "=", session).executeTakeFirst())?.branch;
15528
+ return {
15529
+ ...pending,
15530
+ state: "failed",
15531
+ failure: branch == null ? "no PR found" : `no PR found for ${branch}`
15532
+ };
15533
+ }
15421
15534
  /**
15422
15535
  * The dispatcher input of one task, or null when a stored snapshot is missing or unreadable. It
15423
15536
  * only reads.
15424
15537
  */
15425
- async function readInput(trx, task, project, mode, blind, config) {
15538
+ async function readInput(trx, task, project, mode, blind, config, clock) {
15426
15539
  const readPr = async (ref) => parsePr((await trx.selectFrom("pr_snapshot").select("detail").where(sql`lower(repo) = ${ref.repo.toLowerCase()}`).where("number", "=", ref.number).executeTakeFirst())?.detail);
15427
15540
  const link = await taskPr(trx, task.id);
15428
15541
  let pr = null;
@@ -15457,7 +15570,19 @@ async function readInput(trx, task, project, mode, blind, config) {
15457
15570
  }
15458
15571
  if (mergedOpen !== void 0) pr = null;
15459
15572
  const githubBlind = (pr === null ? project.repos : [pr.repo]).some((repo) => blind(prSourceId(project.id, repo)));
15460
- const marks = (await trx.selectFrom("submission").select(["column", "commit_sha"]).where("task_id", "=", task.id).where("voided_at", "is", null).orderBy("id").execute()).map((row) => {
15573
+ const last = mode === "shadow" ? void 0 : await trx.selectFrom("turn").selectAll().where("task_id", "=", task.id).where("column", "=", task.column).where("epoch", "=", task.column_epoch).orderBy("seq", "desc").executeTakeFirst();
15574
+ const pending = mode === "on" ? await readPendingSubmit(trx, task, project, {
15575
+ link,
15576
+ githubBlind,
15577
+ ...clock,
15578
+ carry: last === void 0
15579
+ }) : void 0;
15580
+ const marks = (await trx.selectFrom("submission").select([
15581
+ "id",
15582
+ "column",
15583
+ "commit_sha",
15584
+ "pending_until"
15585
+ ]).where("task_id", "=", task.id).where("voided_at", "is", null).orderBy("id").execute()).filter((row) => row.pending_until === null || pending?.state === "confirmed" && row.id === pending.id).map((row) => {
15461
15586
  const headSha = row.commit_sha.toLowerCase();
15462
15587
  return row.column === "review" || row.column === "product-review" ? {
15463
15588
  kind: "mark",
@@ -15472,7 +15597,6 @@ async function readInput(trx, task, project, mode, blind, config) {
15472
15597
  const unhandled = pr === null ? [] : await unhandledFeedback(trx, task, project, pr);
15473
15598
  const handed = pr?.feedbackComplete === true ? unhandled : [];
15474
15599
  const column = mode === "shadow" ? task.shadow_column ?? task.column : task.column;
15475
- const last = mode === "shadow" ? void 0 : await trx.selectFrom("turn").selectAll().where("task_id", "=", task.id).where("column", "=", task.column).where("epoch", "=", task.column_epoch).orderBy("seq", "desc").executeTakeFirst();
15476
15600
  const unclosed = last?.closed_at === null ? last : void 0;
15477
15601
  const held = mode === "on" && await trx.selectFrom("operator_item").select("id").where((eb) => eb.or([eb("item_key", "like", `${cycleKeyPrefix(task.id)}%`), eb("item_key", "like", `${courseKeyPrefix(task.id)}%`)])).where("cleared_at", "is", null).executeTakeFirst() !== void 0;
15478
15602
  return {
@@ -15495,6 +15619,8 @@ async function readInput(trx, task, project, mode, blind, config) {
15495
15619
  spurBlind: blind("spur"),
15496
15620
  liveWorker: await linkedSession(trx, task.id, "worker") !== void 0,
15497
15621
  cycleHeld: held,
15622
+ submitPending: pending?.state === "pending",
15623
+ submitFailed: pending?.state === "failed",
15498
15624
  turn: {
15499
15625
  visit: last === void 0 ? "none" : unclosed !== void 0 ? "unclosed" : last.closed_reason === "submitted" ? "submitted" : "none",
15500
15626
  open: unclosed?.acked_at != null,
@@ -15505,7 +15631,8 @@ async function readInput(trx, task, project, mode, blind, config) {
15505
15631
  handed,
15506
15632
  unclosed,
15507
15633
  mergedOpen,
15508
- ticketUnconfirmed
15634
+ ticketUnconfirmed,
15635
+ pending
15509
15636
  };
15510
15637
  }
15511
15638
  async function applyShadow(trx, task, project, result, at) {
@@ -15526,6 +15653,11 @@ async function applyShadow(trx, task, project, result, at) {
15526
15653
  }
15527
15654
  async function applyOn(trx, task, read, result, ctx) {
15528
15655
  const { at, config } = ctx;
15656
+ const failed = read.pending?.state === "failed" ? read.pending : void 0;
15657
+ const voidFailed = async () => {
15658
+ if (failed === void 0) return;
15659
+ await trx.updateTable("submission").set({ voided_at: at.toISOString() }).where("id", "=", failed.id).execute();
15660
+ };
15529
15661
  let current = task;
15530
15662
  for (const move of result.moves) {
15531
15663
  if (indexOf(move.to) < indexOf(move.from)) {
@@ -15560,6 +15692,8 @@ async function applyOn(trx, task, read, result, ctx) {
15560
15692
  const turn = result.turn;
15561
15693
  if (turn === null) return;
15562
15694
  if (result.voids !== void 0) await voidColumns(trx, current.id, [result.voids], at);
15695
+ const handedBack = turn.kind === "after_submit" || turn.kind === "entry" ? failed : void 0;
15696
+ if (handedBack !== void 0) await voidFailed();
15563
15697
  const replaced = turn.kind === "reroute" ? read.unclosed : void 0;
15564
15698
  if (replaced !== void 0) await closeTurns(trx, {
15565
15699
  taskId: current.id,
@@ -15568,15 +15702,36 @@ async function applyOn(trx, task, read, result, ctx) {
15568
15702
  });
15569
15703
  const carried = replaced === void 0 ? [] : turnHanded(replaced);
15570
15704
  const handed = [...carried, ...read.handed.filter((entry) => !carried.some((old) => sameHanded(old, entry)))];
15705
+ const reason = read.mergedOpen === void 0 || turn.kind === "reroute" ? turnReason(turn, replaced?.reason) : `${turnReason(turn)} (PR ${read.mergedOpen.repo}#${String(read.mergedOpen.number)} merged, ticket still open)`;
15571
15706
  await openTurn(trx, {
15572
15707
  task: current,
15573
- reason: read.mergedOpen === void 0 || turn.kind === "reroute" ? turnReason(turn, replaced?.reason) : `${turnReason(turn)} (PR ${read.mergedOpen.repo}#${String(read.mergedOpen.number)} merged, ticket still open)`,
15708
+ reason: handedBack === void 0 ? reason : `${reason} (submit of ${handedBack.sha.slice(0, 7)}: ${handedBack.failure})`,
15574
15709
  handed: current.column === "dev" ? handed : [],
15575
15710
  at,
15576
15711
  config
15577
15712
  });
15578
15713
  }
15579
15714
  /**
15715
+ * Voids a pending submit whose PR merged at another head and journals it; it opens no turn, as
15716
+ * the merge decides the task (a ticket left open sends it back to Dev on its own).
15717
+ */
15718
+ async function supersedeSubmit(trx, task, pending, at) {
15719
+ const row = await trx.updateTable("submission").set({ voided_at: at.toISOString() }).where("id", "=", pending.id).returning("column").executeTakeFirstOrThrow();
15720
+ await emit(trx, "task_submitted", task.project, task.id, at.toISOString(), {
15721
+ column: row.column,
15722
+ sha: pending.sha,
15723
+ supersededByMerge: pending.head
15724
+ });
15725
+ }
15726
+ /** Counts a pending submit a poll confirmed: from its receipt time, on the linked PR. */
15727
+ async function confirmSubmit(trx, pending) {
15728
+ await trx.updateTable("submission").set((eb) => ({
15729
+ pending_until: null,
15730
+ pr_repo: eb.fn.coalesce("pr_repo", eb.val(pending.pr.repo)),
15731
+ pr_number: eb.fn.coalesce("pr_number", eb.val(pending.pr.number))
15732
+ })).where("id", "=", pending.id).execute();
15733
+ }
15734
+ /**
15580
15735
  * Re-evaluates the gates of each task and applies the cascade: in `on` mode it moves the column
15581
15736
  * and opens turns, in `shadow` it moves only the shadow column. Archived tasks and tasks of
15582
15737
  * unconfigured projects are skipped; a task with a missing or unreadable snapshot is held.
@@ -15590,8 +15745,11 @@ async function dispatchTasks(trx, taskIds, ctx) {
15590
15745
  const project = ctx.config.projects.find((entry) => entry.id === task.project);
15591
15746
  if (project === void 0) continue;
15592
15747
  const mode = project.dispatcher.mode;
15593
- const read = await readInput(trx, task, project, mode, blind, ctx.config);
15594
- if (read === null || read.ticketUnconfirmed) continue;
15748
+ const read = await readInput(trx, task, project, mode, blind, ctx.config, ctx);
15749
+ if (read === null) continue;
15750
+ if (read.pending?.state === "superseded") await supersedeSubmit(trx, task, read.pending, ctx.at);
15751
+ if (read.ticketUnconfirmed) continue;
15752
+ if (read.pending?.state === "confirmed") await confirmSubmit(trx, read.pending);
15595
15753
  const result = dispatch(read.input);
15596
15754
  if (mode === "shadow") await applyShadow(trx, task, project, result, ctx.at);
15597
15755
  else await applyOn(trx, task, read, result, ctx);
@@ -15616,6 +15774,18 @@ async function dispatchJournaled(trx, ctx) {
15616
15774
  }).onConflict((oc) => oc.column("key").doUpdateSet({ value })).execute();
15617
15775
  }
15618
15776
  /**
15777
+ * Evaluates the tasks of `on`-mode projects whose current visit has an unvoided pending submit:
15778
+ * its bound passes and a poll confirms it without a journal entry. A still-pending task gets no
15779
+ * write.
15780
+ */
15781
+ async function dispatchPendingSubmits(trx, ctx) {
15782
+ const projects = ctx.config.projects.filter((project) => project.dispatcher.mode === "on").map((project) => project.id);
15783
+ if (projects.length === 0) return;
15784
+ const tasks = await trx.selectFrom("task").innerJoin("submission", (join) => join.onRef("submission.task_id", "=", "task.id").onRef("submission.column", "=", "task.column").onRef("submission.epoch", "=", "task.column_epoch")).select("task.id").distinct().where("task.project", "in", projects).where("task.membership", "!=", "archived").where("submission.voided_at", "is", null).where("submission.pending_until", "is not", null).execute();
15785
+ if (tasks.length === 0) return;
15786
+ await dispatchTasks(trx, tasks.map((task) => task.id), ctx);
15787
+ }
15788
+ /**
15619
15789
  * Evaluates every non-archived task of the source's project, or of every project for `spur`: on
15620
15790
  * the source's first complete poll since start and when it recovers from blindness.
15621
15791
  */
@@ -15668,6 +15838,21 @@ async function taskTurns(trx, task, detail) {
15668
15838
  };
15669
15839
  }
15670
15840
  //#endregion
15841
+ //#region ../core/src/app/task-sessions.ts
15842
+ /** Current facts of the effective session links that task.get exposes. */
15843
+ async function taskSessions(trx, taskId) {
15844
+ return (await trx.selectFrom("link").innerJoin("session_snapshot", "session_snapshot.id", "link.session_id").select("session_snapshot.detail").where("link.task_id", "=", taskId).where("link.entity", "=", "session").where("link.banned", "=", 0).orderBy("link.id").execute()).map((row) => {
15845
+ const facts = parseJson(sessionFactsSchema, row.detail);
15846
+ return {
15847
+ ...facts,
15848
+ links: Object.entries(facts.links).map(([label, url]) => ({
15849
+ label,
15850
+ url
15851
+ }))
15852
+ };
15853
+ });
15854
+ }
15855
+ //#endregion
15671
15856
  //#region ../core/src/app/task-queries.ts
15672
15857
  /** How many of the last moves `task.get --why` shows. */
15673
15858
  const WHY_MOVES = 5;
@@ -15742,12 +15927,19 @@ function shadowSummary(kind, payloadText) {
15742
15927
  return null;
15743
15928
  }
15744
15929
  }
15745
- /** The summary of a submit whose head the board's newest poll confirmed. */
15930
+ /**
15931
+ * The summary of a submit whose head the board's newest poll confirmed, that waits for one, or
15932
+ * that a merge at another head superseded.
15933
+ */
15746
15934
  function submitSummary(kind, payloadText) {
15747
15935
  if (kind !== "task_submitted") return null;
15748
15936
  try {
15749
15937
  const payload = eventPayloadSchemas[kind].safeParse(JSON.parse(payloadText));
15750
- return payload.success && payload.data.confirmedByPoll === true ? "Turn submitted on the head of the last poll" : null;
15938
+ if (!payload.success) return null;
15939
+ const merged = payload.data.supersededByMerge;
15940
+ if (merged !== void 0) return `Submit of ${payload.data.sha.slice(0, 7)} superseded: PR merged at ${merged.slice(0, 7)}`;
15941
+ if (payload.data.pending === true) return "Turn submitted, pending confirmation";
15942
+ return payload.data.confirmedByPoll === true ? "Turn submitted on the head of the last poll" : null;
15751
15943
  } catch {
15752
15944
  return null;
15753
15945
  }
@@ -15786,7 +15978,7 @@ function turnView(turn, key) {
15786
15978
  };
15787
15979
  }
15788
15980
  function createTaskQueries(deps) {
15789
- const { config, completeSince } = deps;
15981
+ const { config, clock, completeSince } = deps;
15790
15982
  const taskKey = (key) => {
15791
15983
  const parsed = parseRef$1(key, "task");
15792
15984
  return parsed.ok && parsed.value.kind === "task" && parsed.value.form === "github-short" ? canonicalKey(config, key).key : key;
@@ -15816,7 +16008,10 @@ function createTaskQueries(deps) {
15816
16008
  const read = await readInput(trx, {
15817
16009
  ...task,
15818
16010
  column
15819
- }, project, mode, await blindSources(trx, completeSince), config);
16011
+ }, project, mode, await blindSources(trx, completeSince), config, {
16012
+ at: new Date(clock.now()),
16013
+ complete: completeSince
16014
+ });
15820
16015
  if (read === null) return {
15821
16016
  ...shared,
15822
16017
  dispatcher: mode,
@@ -15835,11 +16030,17 @@ function createTaskQueries(deps) {
15835
16030
  }));
15836
16031
  const holds = [...dispatchHolds(read.input), ...read.ticketUnconfirmed ? ["ticket_unconfirmed"] : []].sort((left, right) => TASK_HOLDS.indexOf(left) - TASK_HOLDS.indexOf(right));
15837
16032
  const heldBy = holds.includes("cycle_limit") ? await holdBlocks(trx, task.id) : [];
16033
+ const pending = read.pending?.state === "pending" ? read.pending : void 0;
15838
16034
  return {
15839
16035
  ...shared,
15840
16036
  dispatcher: mode,
15841
16037
  holds,
15842
16038
  ...heldBy.length === 0 ? {} : { heldBy },
16039
+ ...pending === void 0 ? {} : { pendingSubmit: {
16040
+ sha: pending.sha,
16041
+ until: pending.until,
16042
+ text: `submit pending confirmation of ${pending.sha.slice(0, 7)}`
16043
+ } },
15843
16044
  gates,
15844
16045
  checksWaivedBy,
15845
16046
  ...waiting.length === 0 ? {} : { waiting }
@@ -15871,6 +16072,7 @@ function createTaskQueries(deps) {
15871
16072
  ]);
15872
16073
  const subject = taskSubject(task);
15873
16074
  return {
16075
+ sessions: await taskSessions(trx, task.id),
15874
16076
  task: taskView(task),
15875
16077
  ...await taskTurns(trx, task, input.detail === true),
15876
16078
  links: links.map(({ state, ...link }) => {
@@ -16105,25 +16307,37 @@ function pollErrorHint(error, pr) {
16105
16307
  function pollMayConfirm(error) {
16106
16308
  return error.kind === "timeout" || error.kind === "failed" && (error.adapterKind === "transient" || error.adapterKind === "unexpected" || error.adapterKind === "throttled");
16107
16309
  }
16310
+ /** A failed poll that waiting can fix, beyond `pollMayConfirm`: a stale source, a stopped poller. */
16311
+ function submitAgain(error) {
16312
+ return error.kind === "blind" && error.reason === "stale" || error.kind === "stopped";
16313
+ }
16108
16314
  /**
16109
16315
  * How the PR head behind a submit is confirmed: `live` by this call's poll, `poll` by the
16110
16316
  * board's newest poll when GitHub did not answer. Throws `head_mismatch` when the confirmed head
16111
- * is not `sha`, `github_unavailable` when nothing confirms it.
16317
+ * is not `sha`, `github_unavailable` when nothing confirms it. With `allowPending` (turn
16318
+ * submits), a result a later poll can settle is `pending` instead of `github_unavailable`.
16112
16319
  */
16113
16320
  function confirmHead(input) {
16114
- const { prepared, pr, sha, snapshot, completeAt } = input;
16321
+ const { prepared, pr, sha, snapshot, completeAt, allowPending } = input;
16115
16322
  const label = `${pr.repo}#${String(pr.number)}`;
16116
16323
  const unavailable = (hint) => new CommandError("github_unavailable", hint);
16117
- if (prepared?.kind !== "polled" || prepared.repo !== pr.repo.toLowerCase() || prepared.number !== pr.number) throw unavailable(`The board did not poll ${label} for this call; submit again.`);
16324
+ const waitable = (hint) => {
16325
+ if (allowPending) return "pending";
16326
+ throw unavailable(hint);
16327
+ };
16328
+ if (prepared?.kind !== "polled" || prepared.repo !== pr.repo.toLowerCase() || prepared.number !== pr.number) return waitable(`The board did not poll ${label} for this call; submit again.`);
16118
16329
  const { result } = prepared;
16119
16330
  if (result === null) throw unavailable(`This daemon runs no GitHub poller; ${noRepeat("check the daemon")}`);
16120
16331
  if (!result.ok) {
16121
16332
  const hint = pollErrorHint(result.error, label);
16122
- if (!pollMayConfirm(result.error)) throw unavailable(hint);
16123
- if (completeAt === void 0) throw unavailable(`${hint} The board has had no complete GitHub poll since it started.`);
16124
- if (snapshot === void 0) throw unavailable(`${hint} The board has not seen the head of ${label} yet.`);
16125
- if (Date.parse(snapshot.observed_at) < Date.parse(completeAt)) throw unavailable(`${hint} The board last saw head ${snapshot.head_sha} at ${snapshot.observed_at}, before its last complete GitHub poll.`);
16126
- if (snapshot.head_sha.toLowerCase() !== sha) throw unavailable(`${hint} Its last poll saw head ${snapshot.head_sha}.`);
16333
+ if (!pollMayConfirm(result.error)) {
16334
+ if (submitAgain(result.error)) return waitable(hint);
16335
+ throw unavailable(hint);
16336
+ }
16337
+ if (completeAt === void 0) return waitable(`${hint} The board has had no complete GitHub poll since it started.`);
16338
+ if (snapshot === void 0) return waitable(`${hint} The board has not seen the head of ${label} yet.`);
16339
+ if (Date.parse(snapshot.observed_at) < Date.parse(completeAt)) return waitable(`${hint} The board last saw head ${snapshot.head_sha} at ${snapshot.observed_at}, before its last complete GitHub poll.`);
16340
+ if (snapshot.head_sha.toLowerCase() !== sha) return waitable(`${hint} Its last poll saw head ${snapshot.head_sha}.`);
16127
16341
  return "poll";
16128
16342
  }
16129
16343
  if (result.value.status !== "ok") throw unavailable(`GitHub answered ${result.value.status} for ${label}; ${noRepeat("check the board's GitHub access")}`);
@@ -16149,20 +16363,26 @@ async function pollTaskPr(db, task, poll) {
16149
16363
  }
16150
16364
  /**
16151
16365
  * Records the submit of `sha` for the task's `column` visit `epoch` and says how its head was
16152
- * confirmed (`confirmHead`). Throws `head_mismatch` or `github_unavailable` otherwise.
16366
+ * confirmed (`confirmHead`). Throws `head_mismatch` or `github_unavailable` otherwise. With
16367
+ * `pendingMs` (turn submits: the project's `submitConfirmMs`), a task with no PR or a head a later
16368
+ * poll can confirm records a pending row with `pending_until = at + pendingMs`.
16153
16369
  */
16154
- async function insertSubmission(trx, input, ctx, completeSince) {
16370
+ async function insertSubmission(trx, input, ctx, completeSince, pendingMs) {
16155
16371
  const { task, column, epoch, sha } = input;
16156
16372
  const pr = await taskPr(trx, task.id);
16157
- if (pr === null) throw new CommandError("head_mismatch", "The task has no active pull request; ask the operator to link it with `board link`, then submit its head.");
16158
- const snapshot = await trx.selectFrom("pr_snapshot").select(["head_sha", "observed_at"]).where(sql`lower(repo) = ${pr.repo.toLowerCase()}`).where("number", "=", pr.number).executeTakeFirst();
16159
- const confirmed = confirmHead({
16160
- prepared: ctx.prepared,
16161
- pr,
16162
- sha,
16163
- snapshot,
16164
- completeAt: completeSince.get(prSourceId(task.project, pr.repo))
16165
- });
16373
+ if (pr === null && pendingMs === void 0) throw new CommandError("head_mismatch", "The task has no active pull request; ask the operator to link it with `board link`, then submit its head.");
16374
+ let confirmed = "pending";
16375
+ if (pr !== null) {
16376
+ const snapshot = await trx.selectFrom("pr_snapshot").select(["head_sha", "observed_at"]).where(sql`lower(repo) = ${pr.repo.toLowerCase()}`).where("number", "=", pr.number).executeTakeFirst();
16377
+ confirmed = confirmHead({
16378
+ prepared: ctx.prepared,
16379
+ pr,
16380
+ sha,
16381
+ snapshot,
16382
+ completeAt: completeSince.get(prSourceId(task.project, pr.repo)),
16383
+ allowPending: pendingMs !== void 0
16384
+ });
16385
+ }
16166
16386
  await trx.insertInto("submission").values({
16167
16387
  task_id: task.id,
16168
16388
  column,
@@ -16171,13 +16391,18 @@ async function insertSubmission(trx, input, ctx, completeSince) {
16171
16391
  author: ctx.actor,
16172
16392
  submitted_at: ctx.at,
16173
16393
  note: null,
16174
- pr_repo: pr.repo,
16175
- pr_number: pr.number
16394
+ pr_repo: pr?.repo ?? null,
16395
+ pr_number: pr?.number ?? null,
16396
+ pending_until: confirmed === "pending" && pendingMs !== void 0 ? new Date(Date.parse(ctx.at) + pendingMs).toISOString() : null
16176
16397
  }).execute();
16177
16398
  return confirmed;
16178
16399
  }
16179
- /** The `task_submitted` payload mark of a head confirmed by the board's last poll. */
16180
- const confirmation = (confirmed) => confirmed === "poll" ? { confirmedByPoll: true } : {};
16400
+ /** The `task_submitted` payload mark of a head confirmed by the board's last poll, or pending. */
16401
+ const CONFIRMATION = {
16402
+ live: {},
16403
+ poll: { confirmedByPoll: true },
16404
+ pending: { pending: true }
16405
+ };
16181
16406
  /**
16182
16407
  * The executor's submit and return of a turn it took, the turnless shadow submit, and the
16183
16408
  * operator's column correction.
@@ -16208,12 +16433,13 @@ function createTurnMutations(deps) {
16208
16433
  await emit(trx, "task_submitted", task.project, task.id, ctx.at, {
16209
16434
  column,
16210
16435
  sha: input.sha,
16211
- ...confirmation(confirmed)
16436
+ ...CONFIRMATION[confirmed]
16212
16437
  }, ctx.actor);
16213
16438
  return {
16214
16439
  task: taskView(await dispatched(trx, task.id, ctx.at)),
16215
16440
  turn: null,
16216
- sha: input.sha
16441
+ sha: input.sha,
16442
+ status: "confirmed"
16217
16443
  };
16218
16444
  }
16219
16445
  return {
@@ -16240,7 +16466,7 @@ function createTurnMutations(deps) {
16240
16466
  column: turn.column,
16241
16467
  epoch: turn.epoch,
16242
16468
  sha: input.sha
16243
- }, ctx, completeSince);
16469
+ }, ctx, completeSince, config.projects.find((entry) => entry.id === task.project)?.dispatcher.submitConfirmMs);
16244
16470
  await closeTurns(trx, {
16245
16471
  taskId: task.id,
16246
16472
  reason: "submitted",
@@ -16250,12 +16476,13 @@ function createTurnMutations(deps) {
16250
16476
  turn: input.turn,
16251
16477
  column: turn.column,
16252
16478
  sha: input.sha,
16253
- ...confirmation(confirmed)
16479
+ ...CONFIRMATION[confirmed]
16254
16480
  }, ctx.actor);
16255
16481
  return {
16256
16482
  task: taskView(await dispatched(trx, task.id, ctx.at)),
16257
16483
  turn: input.turn,
16258
- sha: input.sha
16484
+ sha: input.sha,
16485
+ status: confirmed === "pending" ? "pending" : "confirmed"
16259
16486
  };
16260
16487
  }
16261
16488
  },
@@ -16330,6 +16557,7 @@ function createOperationRegistry(deps) {
16330
16557
  const blocks = createBlockMutations(config);
16331
16558
  const taskQueries = createTaskQueries({
16332
16559
  config,
16560
+ clock,
16333
16561
  completeSince,
16334
16562
  prPoller: deps.prPoller
16335
16563
  });
@@ -16873,7 +17101,47 @@ function branchHasKey(branch, key) {
16873
17101
  }
16874
17102
  /** The Jira task key at the end of a session's `/browse/` link. */
16875
17103
  const BROWSE_KEY = new RegExp(`/browse/(${JIRA_PROJECT_KEY}-${REF_NUMBER})$`);
16876
- async function session(trx, config, fact, at, source, ambiguousBranches) {
17104
+ /** Parse a published task URL without deciding whether that task is currently known. */
17105
+ function sessionTaskKey(url) {
17106
+ const candidate = BROWSE_KEY.exec(url)?.[1] ?? /\/issues\/([1-9]\d*)$/.exec(url)?.[1];
17107
+ return candidate === void 0 ? void 0 : url.includes("/issues/") ? `${new URL(url).pathname.split("/").slice(1, 3).join("/")}#${candidate}` : candidate;
17108
+ }
17109
+ /** Select one explicit label before resolving its task; unknown selections never fall through. */
17110
+ async function resolveSessionLabels(trx, config, links) {
17111
+ let key;
17112
+ let role;
17113
+ for (const label of ["board-worker", "board-other"]) {
17114
+ const url = links[label];
17115
+ if (url === void 0) continue;
17116
+ key = sessionTaskKey(url);
17117
+ role = label === "board-worker" ? "worker" : "other";
17118
+ if (key !== void 0) break;
17119
+ }
17120
+ const task = key === void 0 || projectForKey(config, key) === null ? void 0 : await trx.selectFrom("task").selectAll().where("key", "=", key).executeTakeFirst();
17121
+ return {
17122
+ key,
17123
+ role,
17124
+ task
17125
+ };
17126
+ }
17127
+ /** History is journaled without changing snapshots, links or task change times. */
17128
+ async function sessionTransition(trx, config, edge) {
17129
+ const projects = config.projects.filter((project) => project.spurProjects.some((spur) => spur.name === edge.spurProject));
17130
+ const { task } = await resolveSessionLabels(trx, config, edge.links);
17131
+ if (task !== void 0) await emit(trx, "session_state_changed", task.project, task.id, edge.at, {
17132
+ session: edge.session,
17133
+ from: edge.from,
17134
+ to: edge.to,
17135
+ transition: edge
17136
+ });
17137
+ else for (const project of projects) await emit(trx, "session_state_changed", project.id, null, edge.at, {
17138
+ session: edge.session,
17139
+ from: edge.from,
17140
+ to: edge.to,
17141
+ transition: edge
17142
+ });
17143
+ }
17144
+ async function session(trx, config, fact, at, source, ambiguousBranches, feedEnabled) {
16877
17145
  const old = await trx.selectFrom("session_snapshot").selectAll().where("id", "=", fact.id).executeTakeFirst();
16878
17146
  const previous = old === void 0 ? null : parseJson(sessionFactsSchema, old.detail);
16879
17147
  const changed = previous === null || JSON.stringify(previous) !== JSON.stringify(fact);
@@ -16926,16 +17194,9 @@ async function session(trx, config, fact, at, source, ambiguousBranches) {
16926
17194
  });
16927
17195
  }
16928
17196
  }
16929
- let key;
16930
- let role;
16931
- for (const label of ["board-worker", "board-other"]) {
16932
- const url = fact.links[label];
16933
- if (url === void 0) continue;
16934
- const candidate = BROWSE_KEY.exec(url)?.[1] ?? /\/issues\/([1-9]\d*)$/.exec(url)?.[1];
16935
- key = candidate === void 0 ? void 0 : url.includes("/issues/") ? `${new URL(url).pathname.split("/").slice(1, 3).join("/")}#${candidate}` : candidate;
16936
- role = label === "board-worker" && !orchestrator ? "worker" : "other";
16937
- if (key !== void 0) break;
16938
- }
17197
+ const explicit = await resolveSessionLabels(trx, config, fact.links);
17198
+ let key = explicit.key;
17199
+ let role = orchestrator && explicit.role === "worker" ? "other" : explicit.role;
16939
17200
  let prOnlyKey;
16940
17201
  if (key === void 0 && fact.pr !== null) {
16941
17202
  const linked = await trx.selectFrom("link").innerJoin("task", "task.id", "link.task_id").leftJoin("pr_snapshot", (join) => join.on(sql`lower(pr_snapshot.repo) = lower(link.repo)`).onRef("pr_snapshot.number", "=", "link.number")).select([
@@ -16964,8 +17225,8 @@ async function session(trx, config, fact, at, source, ambiguousBranches) {
16964
17225
  key = prOnlyKey;
16965
17226
  role = "other";
16966
17227
  }
16967
- if (key !== void 0 && projectForKey(config, key) !== null) {
16968
- const task = await trx.selectFrom("task").selectAll().where("key", "=", key).executeTakeFirst();
17228
+ if (key !== void 0) {
17229
+ const task = explicit.key !== void 0 ? explicit.task : projectForKey(config, key) === null ? void 0 : await trx.selectFrom("task").selectAll().where("key", "=", key).executeTakeFirst();
16969
17230
  if (task !== void 0) {
16970
17231
  if (await trx.selectFrom("link").selectAll().where("entity", "=", "session").where("session_id", "=", fact.id).where("task_id", "=", task.id).executeTakeFirst() === void 0) {
16971
17232
  const worker = await trx.selectFrom("link").selectAll().where("task_id", "=", task.id).where("entity", "=", "session").where("role", "=", "worker").where("banned", "=", 0).executeTakeFirst();
@@ -16998,7 +17259,7 @@ async function session(trx, config, fact, at, source, ambiguousBranches) {
16998
17259
  const links = await trx.selectFrom("link").select(["task_id"]).where("entity", "=", "session").where("session_id", "=", fact.id).execute();
16999
17260
  for (const link of links) {
17000
17261
  const task = await trx.selectFrom("task").selectAll().where("id", "=", link.task_id).executeTakeFirstOrThrow();
17001
- if (previous?.lifecycle !== fact.lifecycle && previous !== null) await emit(trx, "session_state_changed", task.project, task.id, at, {
17262
+ if (!feedEnabled && previous?.lifecycle !== fact.lifecycle && previous !== null) await emit(trx, "session_state_changed", task.project, task.id, at, {
17002
17263
  session: fact.id,
17003
17264
  from: previous.lifecycle,
17004
17265
  to: fact.lifecycle
@@ -17224,7 +17485,8 @@ function createObservationCore(deps) {
17224
17485
  else if (item.kind === "pr") {
17225
17486
  await pr(trx, config, item.facts, batch.observedAt, source);
17226
17487
  await holdContinuation(trx, source, item);
17227
- } else await session(trx, config, item.facts, batch.observedAt, source, ambiguous);
17488
+ } else await session(trx, config, item.facts, batch.observedAt, source, ambiguous, batch.sessionTransitions !== void 0);
17489
+ for (const edge of batch.sessionTransitions ?? []) await sessionTransition(trx, config, edge);
17228
17490
  const linked = (await linkedPrs(trx, source)).map(refKey);
17229
17491
  await trx.deleteFrom("pr_continuation").where("source", "=", source).$if(linked.length > 0, (query) => query.where("ref_key", "not in", linked)).execute();
17230
17492
  for (const entity of batch.entities) {
@@ -17420,6 +17682,11 @@ async function tickBoard(deps) {
17420
17682
  at: new Date(now),
17421
17683
  complete: completeSince
17422
17684
  });
17685
+ await dispatchPendingSubmits(trx, {
17686
+ config,
17687
+ at: new Date(now),
17688
+ complete: completeSince
17689
+ });
17423
17690
  await remindStuckTurns(trx, config, new Date(now));
17424
17691
  await reconcileItems(trx, config, now, completeSince.has("spur"), deps.warnSkipped);
17425
17692
  });
@@ -21380,6 +21647,7 @@ const sessionWire = z.object({
21380
21647
  branch: z.string().nullable().optional(),
21381
21648
  status: z.string().min(1),
21382
21649
  state: z.string().min(1),
21650
+ rateLimitResetAt: z.iso.datetime().optional(),
21383
21651
  lastActivityAt: z.iso.datetime().nullable().optional(),
21384
21652
  slots: z.object({ links: z.array(z.object({
21385
21653
  label: z.string().min(1),
@@ -21387,6 +21655,26 @@ const sessionWire = z.object({
21387
21655
  })).optional() }).optional(),
21388
21656
  queuedMessages: z.object({ messages: z.array(z.string()) }).optional()
21389
21657
  });
21658
+ const transitionWire = z.object({
21659
+ cursor: z.string().min(1),
21660
+ sessionId: z.string().min(1),
21661
+ project: z.string().min(1),
21662
+ at: z.iso.datetime(),
21663
+ links: z.array(z.object({
21664
+ label: z.string().min(1),
21665
+ url: z.url()
21666
+ })),
21667
+ kind: z.enum(["status", "state"]),
21668
+ from: z.string().min(1).nullable(),
21669
+ to: z.string().min(1),
21670
+ rateLimitResetAt: z.iso.datetime().optional()
21671
+ });
21672
+ const transitionsWire = z.object({
21673
+ entries: z.array(transitionWire).max(1e3),
21674
+ nextCursor: sourceCursorSchema,
21675
+ hasMore: z.boolean()
21676
+ });
21677
+ const foreignCursorWire = z.object({ error: z.literal("Invalid or foreign transitions cursor") });
21390
21678
  /** The board rings a session's queue still holds, sorted and deduped; other queued text is dropped. */
21391
21679
  function queuedBoardRings(wire) {
21392
21680
  const rings = /* @__PURE__ */ new Map();
@@ -21422,7 +21710,7 @@ function createSpurAdapter(options) {
21422
21710
  }, REQUEST_TIMEOUT_MS);
21423
21711
  try {
21424
21712
  const response = await fetchImpl(new URL(path, base), { signal: controller.signal });
21425
- if (!response.ok) return { response };
21713
+ if (!response.ok && response.status !== 410 && response.status !== 400) return { response };
21426
21714
  try {
21427
21715
  return {
21428
21716
  response,
@@ -21493,6 +21781,7 @@ function createSpurAdapter(options) {
21493
21781
  lifecycle: wire.status,
21494
21782
  health: state.stable,
21495
21783
  healthSince: state.since,
21784
+ ...wire.state === "rate_limited" && state.stable === "rate_limited" && wire.rateLimitResetAt !== void 0 ? { rateLimitResetAt: wire.rateLimitResetAt } : {},
21496
21785
  lastActivityAt: wire.lastActivityAt ?? null,
21497
21786
  endedAt: endReason === null ? null : observedAt,
21498
21787
  endReason,
@@ -21504,6 +21793,49 @@ function createSpurAdapter(options) {
21504
21793
  intervalMs: options.intervalMs,
21505
21794
  async poll(ctx) {
21506
21795
  const observedAt = new Date(options.now()).toISOString();
21796
+ let cursor = ctx.cursor;
21797
+ const sessionTransitions = [];
21798
+ const positions = /* @__PURE__ */ new Set();
21799
+ for (let page = 0; page < 4; page++) {
21800
+ const query = new URLSearchParams({
21801
+ limit: "1000",
21802
+ kinds: "status,state"
21803
+ });
21804
+ if (cursor !== void 0) query.set("since", cursor);
21805
+ const { response, body } = await request(`sessions/transitions?${query.toString()}`, ctx.signal);
21806
+ if (page === 0 && cursor !== void 0 && response.status === 400 && foreignCursorWire.safeParse(body).success) {
21807
+ cursor = void 0;
21808
+ continue;
21809
+ }
21810
+ if (response.status === 410) {
21811
+ cursor = parseWire(z.object({ latestCursor: sourceCursorSchema }), body, "Invalid Spur expired cursor").latestCursor;
21812
+ sessionTransitions.length = 0;
21813
+ break;
21814
+ }
21815
+ if (!response.ok) throw classifyHttpFailure({
21816
+ status: response.status,
21817
+ headers: response.headers
21818
+ }, options.now());
21819
+ const feed = parseWire(transitionsWire, body, "Invalid Spur transitions");
21820
+ for (const entry of feed.entries) {
21821
+ if (positions.has(entry.cursor) || entry.cursor === cursor) throw new AdapterError("transient", "Repeated Spur transition position");
21822
+ positions.add(entry.cursor);
21823
+ sessionTransitions.push(sessionTransitionSchema.parse({
21824
+ position: entry.cursor,
21825
+ session: entry.sessionId,
21826
+ spurProject: entry.project,
21827
+ at: entry.at,
21828
+ links: Object.fromEntries(entry.links.map(({ label, url }) => [label, url])),
21829
+ dimension: entry.kind === "status" ? "lifecycle" : "health",
21830
+ from: entry.from,
21831
+ to: entry.to,
21832
+ ...entry.rateLimitResetAt === void 0 ? {} : { rateLimitResetAt: entry.rateLimitResetAt }
21833
+ }));
21834
+ }
21835
+ if (feed.hasMore && (feed.nextCursor === cursor || feed.entries.length === 0)) throw new AdapterError("transient", "Spur transitions made no progress");
21836
+ cursor = feed.nextCursor;
21837
+ if (!feed.hasMore) break;
21838
+ }
21507
21839
  const { response: listResponse, body: listBody } = await request("sessions", ctx.signal);
21508
21840
  if (!listResponse.ok) throw classifyHttpFailure({
21509
21841
  status: listResponse.status,
@@ -21566,7 +21898,9 @@ function createSpurAdapter(options) {
21566
21898
  entities: ctx.observe.sessions.map((ref) => ({
21567
21899
  ref,
21568
21900
  status: byId.has(ref.id) || detail.get(ref.id) !== null ? "ok" : "not_found"
21569
- }))
21901
+ })),
21902
+ sessionTransitions,
21903
+ ...cursor === void 0 ? {} : { cursor }
21570
21904
  };
21571
21905
  if (restartNotice) await options.onNotice?.(restartNotice);
21572
21906
  for (const wire of [...listed, ...detail.values()]) {