spur-board 0.40.2 → 0.42.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 encodeActorId, B as successEnvelopeSchema, C as SESSION_HEALTH_STATES, D as sessionFactsSchema, E as prRefSchema, F as ERRORS, G as RESERVED_PROJECT, H as DEFAULT_LINK, I as err, J as requiredSecretKeys, K as configSchema, M as parseActorId, N as parseRef$1, O as ticketFactsSchema, P as taskKeySchema, S as eventPayloadSchemas, T as prFactsSchema, W as DEFAULT_SLACK_COMMAND, Y as SLACK_BOT_SCOPES, _ as inboundEventSchema, a as batchSchema, b as userIdSchema, c as buildCatalogSnapshot, d as turnHandedSchema, f as renderHttpProblem, g as conversationRefSchema, h as SPACE_IDS, i as AdapterError, j as errorCodeOf, k as actorIdSchema, l as roleCanUseOperation, n as BOARD_TICK_MS, o as entityRefSchema, q as plainHttpAllowed, s as sourceCursorSchema, t as assertNever, u as OPERATIONS, v as interactionRefSchema, w as SESSION_STATUSES, x as EVENT_KINDS, y as messageRefSchema, z as ok } from "./src-C-HpKSEK.mjs";
1
+ import { $ as SLACK_BOT_SCOPES, A as ticketFactsSchema, C as REVIEW_STATES, D as prFactsSchema, E as isExternalAuthor, F as parseRef$1, H as successEnvelopeSchema, I as taskKeySchema, J as configSchema, K as DEFAULT_SLACK_COMMAND, L as ERRORS, M as encodeActorId, N as errorCodeOf, O as prRefSchema, P as parseActorId, Q as DISPATCHER_MODES, R as err, S as eventPayloadSchemas, T as SESSION_STATUSES, V as ok, W as DEFAULT_LINK, X as requiredSecretKeys, Y as plainHttpAllowed, Z as COLUMN_IDS, _ as inboundEventSchema, a as batchSchema, b as userIdSchema, c as buildCatalogSnapshot, d as turnHandedSchema, f as renderHttpProblem, g as conversationRefSchema, h as SPACE_IDS, i as AdapterError, j as actorIdSchema, k as sessionFactsSchema, l as roleCanUseOperation, n as BOARD_TICK_MS, o as entityRefSchema, q as RESERVED_PROJECT, s as sourceCursorSchema, t as assertNever, u as OPERATIONS, v as interactionRefSchema, w as SESSION_HEALTH_STATES, x as EVENT_KINDS, y as messageRefSchema } from "./src-Dk-_gP9r.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { chmodSync, closeSync, existsSync, fchmodSync, fstatSync, fsyncSync, ftruncateSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeSync } from "node:fs";
@@ -7959,6 +7959,28 @@ function trackerSource(project) {
7959
7959
  function ticketDone(project, status) {
7960
7960
  return project.tracker.type === "jira" ? project.tracker.doneStatuses.includes(status) : status === "closed";
7961
7961
  }
7962
+ /**
7963
+ * Whether a PR link counts past the task's reopen floor: an open link, or a link not hidden by a
7964
+ * reopen. For a query over `link`. Written so a link without a marker counts: the negated form
7965
+ * is NULL there and would drop it.
7966
+ */
7967
+ const pastReopenFloor = sql`(link.pr_open = 1 OR link.reopen_hidden_at IS NULL)`;
7968
+ /**
7969
+ * The task's PR: the open active unbanned link past the reopen floor, else the newest active
7970
+ * unbanned one past it.
7971
+ */
7972
+ async function taskPr(db, taskId) {
7973
+ const link = await db.selectFrom("link").select([
7974
+ "link.repo",
7975
+ "link.number",
7976
+ "link.pr_open"
7977
+ ]).where("link.task_id", "=", taskId).where("link.entity", "=", "pr").where("link.pr_state", "=", "active").where("link.banned", "=", 0).where("link.repo", "is not", null).where("link.number", "is not", null).where(pastReopenFloor).orderBy("link.pr_open", "desc").orderBy("link.id", "desc").executeTakeFirst();
7978
+ return link?.repo == null || link.number === null ? null : {
7979
+ repo: link.repo,
7980
+ number: link.number,
7981
+ open: link.pr_open === 1
7982
+ };
7983
+ }
7962
7984
  /** The project whose tracker or repo source wrote an observation. */
7963
7985
  function projectForSource(config, source) {
7964
7986
  return config.projects.find((project) => source === trackerSource(project) || project.repos.some((repo) => source === `github:${project.id}:${repo.toLowerCase()}`));
@@ -9592,6 +9614,29 @@ async function registerBlockNotification(trx, block, at) {
9592
9614
  }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
9593
9615
  }
9594
9616
  /**
9617
+ * Register an agent executor's turn. Core opens a turn, so no session authored it: the worker
9618
+ * or column orchestrator the board selects is rung.
9619
+ */
9620
+ async function registerTurnNotification(trx, turn, at) {
9621
+ await trx.insertInto("notification").values({
9622
+ source_key: `turn:${String(turn.id)}:${turn.role}`,
9623
+ kind: "turn",
9624
+ task_id: turn.task_id,
9625
+ block_id: null,
9626
+ turn_id: turn.id,
9627
+ comment_id: null,
9628
+ revision: null,
9629
+ role: turn.role,
9630
+ author_session: null,
9631
+ recipient_session: null,
9632
+ next_at: at.toISOString(),
9633
+ last_outbox_id: null,
9634
+ acked_at: null,
9635
+ exhausted_at: null,
9636
+ created_at: at.toISOString()
9637
+ }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
9638
+ }
9639
+ /**
9595
9640
  * The key of the reminder to `session` about a turn it took at `takenAt`. The take time names the
9596
9641
  * ownership episode, so a session that loses the turn and takes it again gets a new reminder.
9597
9642
  */
@@ -10108,6 +10153,15 @@ async function closeOwnedNotifications(trx, kind, ownerId, at) {
10108
10153
  //#region ../core/src/app/turns.ts
10109
10154
  const handedSchema = z.array(turnHandedSchema);
10110
10155
  const turnItemKey = (turnId) => `turn:${String(turnId)}`;
10156
+ /**
10157
+ * Who executes a column's turn: its orchestrator project, the operator, or for a column with
10158
+ * no orchestrator the live worker, else the operator.
10159
+ */
10160
+ function turnExecutor(column, columnOrchestrator, hasLiveWorker) {
10161
+ if (columnOrchestrator === "operator") return "operator";
10162
+ if (columnOrchestrator === "none") return hasLiveWorker ? "worker" : "operator";
10163
+ return `orchestrator:${column}`;
10164
+ }
10111
10165
  /** The feedback a stored turn handed over. */
10112
10166
  function turnHanded(turn) {
10113
10167
  return parseJson(handedSchema, turn.handed);
@@ -10117,6 +10171,53 @@ async function turnNotification(trx, turnId) {
10117
10171
  return trx.selectFrom("notification").selectAll().where("turn_id", "=", turnId).where("kind", "=", "turn").orderBy("id", "desc").executeTakeFirst();
10118
10172
  }
10119
10173
  /**
10174
+ * Opens a turn for the executor of the task's current column. The unclosed turn of the same
10175
+ * visit is returned unchanged; an unclosed turn of an earlier visit is closed as moved first.
10176
+ * An agent executor gets a ringing notification, the operator one `turn` item.
10177
+ */
10178
+ async function openTurn(trx, input) {
10179
+ const { task, reason, handed, at, config } = input;
10180
+ const unclosed = await trx.selectFrom("turn").selectAll().where("task_id", "=", task.id).where("closed_at", "is", null).executeTakeFirst();
10181
+ if (unclosed?.column === task.column && unclosed.epoch === task.column_epoch) return unclosed;
10182
+ if (unclosed !== void 0) await closeTurns(trx, {
10183
+ taskId: task.id,
10184
+ reason: "moved",
10185
+ at
10186
+ });
10187
+ const orchestrator = config.projects.find((project) => project.id === task.project)?.columns.find((column) => column.id === task.column)?.orchestrator ?? "none";
10188
+ const hasLiveWorker = orchestrator === "none" && await linkedSession(trx, task.id, "worker") !== void 0;
10189
+ const role = turnExecutor(task.column, orchestrator, hasLiveWorker);
10190
+ const pr = await taskPr(trx, task.id);
10191
+ const snapshot = pr === null ? void 0 : await trx.selectFrom("pr_snapshot").select("head_sha").where(sql`lower(repo) = ${pr.repo.toLowerCase()}`).where("number", "=", pr.number).executeTakeFirst();
10192
+ const last = await trx.selectFrom("turn").select((eb) => eb.fn.max("seq").as("seq")).where("task_id", "=", task.id).where("column", "=", task.column).where("epoch", "=", task.column_epoch).executeTakeFirst();
10193
+ const turn = await trx.insertInto("turn").values({
10194
+ task_id: task.id,
10195
+ column: task.column,
10196
+ epoch: task.column_epoch,
10197
+ seq: (last?.seq ?? 0) + 1,
10198
+ role,
10199
+ reason,
10200
+ handed: toJson(handedSchema, [...handed]),
10201
+ acked_by: null,
10202
+ acked_at: null,
10203
+ closed_at: null,
10204
+ closed_reason: null,
10205
+ created_at: at.toISOString(),
10206
+ head_sha: snapshot?.head_sha.toLowerCase() ?? null
10207
+ }).returningAll().executeTakeFirstOrThrow();
10208
+ if (role === "operator") await raiseItem(trx, {
10209
+ itemKey: turnItemKey(turn.id),
10210
+ kind: "turn",
10211
+ text: `turn T${String(turn.id)} on ${task.key}: ${reason}`,
10212
+ url: taskUrl(task, config),
10213
+ taskId: task.id,
10214
+ blockId: null,
10215
+ at
10216
+ });
10217
+ else await registerTurnNotification(trx, turn, at);
10218
+ return turn;
10219
+ }
10220
+ /**
10120
10221
  * Takes a turn for `actor`. False for a missing, closed, operator or taken worker turn. An
10121
10222
  * untaken turn needs its unread notification addressed to the actor; a taken orchestrator turn
10122
10223
  * may be taken over by whoever its notification is now addressed to. Others get `forbidden`.
@@ -10956,6 +11057,7 @@ function createMembershipMutations(config) {
10956
11057
  archive_reason: null,
10957
11058
  last_change_at: ctx.at
10958
11059
  }).where("id", "=", task.id).execute();
11060
+ if (task.membership === "archived") await emit(trx, "task_added", project.id, task.id, ctx.at, { column: task.column }, "operator");
10959
11061
  task = await trx.selectFrom("task").selectAll().where("id", "=", task.id).executeTakeFirstOrThrow();
10960
11062
  }
10961
11063
  return { task: taskView(task) };
@@ -11796,7 +11898,7 @@ async function prConflict(trx, taskId, repo, number, open) {
11796
11898
  "link.pr_state",
11797
11899
  "link.pr_open",
11798
11900
  "pr_snapshot.state"
11799
- ]).where("link.task_id", "=", taskId).where("link.entity", "=", "pr").where("link.banned", "=", 0).execute();
11901
+ ]).where("link.task_id", "=", taskId).where("link.entity", "=", "pr").where("link.banned", "=", 0).where(pastReopenFloor).execute();
11800
11902
  for (const link of links) {
11801
11903
  if (link.repo?.toLowerCase() === repo && link.number === number) continue;
11802
11904
  const blocking = `${link.repo ?? ""}#${String(link.number ?? "")}`;
@@ -12173,6 +12275,8 @@ const EVENT_SUMMARIES = {
12173
12275
  task_archived: "Task archived",
12174
12276
  task_submitted: "Turn submitted",
12175
12277
  task_moved: "Task moved",
12278
+ task_shadow_moved: "Shadow move",
12279
+ dispatcher_mode_changed: "Dispatcher mode changed",
12176
12280
  block_opened: "Block opened",
12177
12281
  block_escalated: "Block escalated",
12178
12282
  block_unblocked: "Block unblocked",
@@ -12304,6 +12408,7 @@ function createTaskQueries(config) {
12304
12408
  addressee: turn.role,
12305
12409
  reason: turn.reason,
12306
12410
  handed: turnHanded(turn),
12411
+ head: turn.head_sha,
12307
12412
  at: turn.created_at,
12308
12413
  taken: turn.acked_by === null || turn.acked_at === null ? null : {
12309
12414
  by: turn.acked_by,
@@ -12371,372 +12476,299 @@ function createTaskQueries(config) {
12371
12476
  };
12372
12477
  }
12373
12478
  //#endregion
12374
- //#region ../core/src/app/turn-commands.ts
12375
- /** How long `task.submit` waits for its on-demand PR poll; the CLI gives up at 30 s. */
12376
- const SUBMIT_POLL_TIMEOUT_MS = 1e4;
12377
- /** Columns a task returns to Dev from: right of Dev, before the terminal Done. */
12378
- const RETURNABLE = [
12379
- "review",
12380
- "product-review",
12381
- "external-review",
12382
- "qa",
12383
- "ready-to-merge"
12384
- ];
12385
- const turnNumber = (id) => Number(id.slice(1));
12386
- const turnLabel = (id) => `T${String(id)}`;
12387
- async function turnById(db, id) {
12388
- return db.selectFrom("turn").selectAll().where("id", "=", turnNumber(id)).executeTakeFirst();
12389
- }
12390
- async function taskById(db, id) {
12391
- return db.selectFrom("task").selectAll().where("id", "=", id).executeTakeFirstOrThrow();
12479
+ //#region ../core/src/domain/gates.ts
12480
+ /**
12481
+ * The hold-only reasons: a fact is not known yet, and waiting resolves it. See `GateResult` for
12482
+ * the caller rule.
12483
+ */
12484
+ const HOLD_ONLY = /* @__PURE__ */ new Set([
12485
+ "mergeable_unknown",
12486
+ "checks_pending",
12487
+ "comment_history_incomplete"
12488
+ ]);
12489
+ /** Neutral passes like success. Skipped is red: a skipped required check reports no more. */
12490
+ const VERDICT = {
12491
+ success: "green",
12492
+ neutral: "green",
12493
+ expected: "pending",
12494
+ pending: "pending",
12495
+ skipped: "red",
12496
+ failure: "red",
12497
+ error: "red",
12498
+ cancelled: "red",
12499
+ timed_out: "red",
12500
+ action_required: "red",
12501
+ stale: "red"
12502
+ };
12503
+ /**
12504
+ * Whether `reposWithoutCi` passes Dev's check condition: the PR is open, its repo is listed in any
12505
+ * letter case, and its head has no checks at all. A list of only skipped checks does not count.
12506
+ */
12507
+ function noCiWaives(pr, project) {
12508
+ if (pr === null || pr.state !== "open") return false;
12509
+ if (pr.checks.length > 0 || pr.requiredChecks.length > 0) return false;
12510
+ const repo = pr.repo.toLowerCase();
12511
+ return project.reposWithoutCi.some((listed) => listed.toLowerCase() === repo);
12392
12512
  }
12393
- /** Authorizes against the turn's own column, so a late call on an old turn is `turn_closed`. */
12394
- async function turnVisitTarget(db, id) {
12395
- const turn = await turnById(db, id);
12396
- if (turn === void 0) return [{
12397
- kind: "missing",
12398
- id
12399
- }];
12400
- return [{
12401
- ...await authorizationTarget(db, {
12402
- ...await taskById(db, turn.task_id),
12403
- column: turn.column
12404
- }),
12405
- id
12406
- }];
12513
+ /**
12514
+ * The verdict over the required checks on head, or, when none is required, over every check on
12515
+ * head except skipped ones. No check gives pending, and red wins over pending. `waived` (from
12516
+ * `noCiWaives`, so the head has no checks) gives green.
12517
+ */
12518
+ function checksVerdict(pr, waived) {
12519
+ if (waived) return "green";
12520
+ const verdicts = (pr.requiredChecks.length > 0 ? pr.requiredChecks : pr.checks.filter((check) => check.state !== "skipped")).map((check) => VERDICT[check.state]);
12521
+ if (verdicts.includes("red")) return "red";
12522
+ if (verdicts.length === 0 || verdicts.includes("pending")) return "pending";
12523
+ return "green";
12407
12524
  }
12408
- /** The task's PR: the open active unbanned link, else the newest active unbanned one. */
12409
- async function taskPr(db, taskId) {
12410
- const link = await db.selectFrom("link").select(["repo", "number"]).where("task_id", "=", taskId).where("entity", "=", "pr").where("pr_state", "=", "active").where("banned", "=", 0).where("repo", "is not", null).where("number", "is not", null).orderBy("pr_open", "desc").orderBy("id", "desc").executeTakeFirst();
12411
- return link?.repo == null || link.number === null ? null : {
12412
- repo: link.repo,
12413
- number: link.number
12414
- };
12525
+ function orchestratorOf$1(column, columns) {
12526
+ return columns.find((c) => c.id === column)?.orchestrator;
12415
12527
  }
12416
- /** True when the turn is the current visit's, still unclosed. */
12417
- function current(turn, task) {
12418
- return turn.closed_at === null && turn.column === task.column && turn.epoch === task.column_epoch;
12528
+ /**
12529
+ * Whether the column's executor is done on the current head: a submit or mark in the column is on
12530
+ * head. A column without an orchestrator is executed by the worker, so any worker submit on head
12531
+ * (a submit in a column without an orchestrator) also counts there.
12532
+ */
12533
+ function executorDone(column, facts, columns) {
12534
+ const head = facts.pr?.headSha;
12535
+ if (head === void 0) return false;
12536
+ const onHead = facts.marks.filter((mark) => mark.headSha === head);
12537
+ if (onHead.some((mark) => mark.column === column)) return true;
12538
+ if (orchestratorOf$1(column, columns) !== "none") return false;
12539
+ return onHead.some((mark) => mark.kind === "submit" && orchestratorOf$1(mark.column, columns) === "none");
12540
+ }
12541
+ function devReasons(facts, columns, waived) {
12542
+ const { pr } = facts;
12543
+ if (pr === null) return ["no_pr"];
12544
+ if (pr.state === "closed") return ["pr_closed"];
12545
+ const reasons = [];
12546
+ if (pr.draft) reasons.push("pr_draft");
12547
+ const verdict = checksVerdict(pr, waived);
12548
+ if (verdict === "red") reasons.push("checks_red");
12549
+ if (verdict === "pending") reasons.push("checks_pending");
12550
+ if (pr.mergeable === "conflicting") reasons.push("conflict");
12551
+ if (pr.mergeable === "unknown") reasons.push("mergeable_unknown");
12552
+ if (facts.unhandledExternalComments > 0) reasons.push("external_comments");
12553
+ if (facts.commentHistory === "incomplete") reasons.push("comment_history_incomplete");
12554
+ if (!executorDone("dev", facts, columns)) reasons.push("no_submit_on_head");
12555
+ return reasons;
12556
+ }
12557
+ /** The failing reasons of one column's exit condition; it does not depend on the column asked. */
12558
+ function columnCondition(column, facts, columns, waived) {
12559
+ switch (column) {
12560
+ case "todo":
12561
+ case "ready-for-dev":
12562
+ case "done": return [];
12563
+ case "dev": return devReasons(facts, columns, waived);
12564
+ case "review":
12565
+ case "product-review": return executorDone(column, facts, columns) ? [] : ["no_review_on_head"];
12566
+ case "external-review": return facts.externalReviewApproved ? [] : ["not_approved"];
12567
+ case "qa": return executorDone(column, facts, columns) ? [] : ["no_submit_on_head"];
12568
+ case "ready-to-merge": return facts.pr?.state === "merged" ? [] : ["not_merged"];
12569
+ default: return assertNever(column);
12570
+ }
12419
12571
  }
12420
- /** The refusals both operations share, in order: archived, closed, not the taker. */
12421
- async function takenTurn(trx, id, ctx) {
12422
- const turn = await turnById(trx, id);
12423
- if (turn === void 0) throw new CommandError("not_found", "Check the turn ID.");
12424
- const task = await taskById(trx, turn.task_id);
12425
- if (task.membership === "archived") throw new CommandError("task_archived", "Add the task again before changing it.");
12426
- if (!current(turn, task)) throw new CommandError("turn_closed", `Turn ${id} is closed; read your open turns with \`board inbox\`.`);
12427
- if (turn.acked_by === null || turn.acked_by !== ctx.actor) throw new CommandError("not_turn_taker", turn.acked_by === null ? `Take turn ${id} with \`board inbox ack ${id}\` first.` : `Turn ${id} was taken by another session; only that session can submit or return it.`);
12572
+ /**
12573
+ * Evaluates the exit conditions of every enabled column from To Do up to and including `column`,
12574
+ * and returns the leftmost one that fails. A column absent from the project's columns or disabled
12575
+ * passes through. A merged pull request passes every column. Once Dev is evaluated with its check
12576
+ * condition passed by `reposWithoutCi`, the result carries `checksWaivedBy`.
12577
+ */
12578
+ function evaluateGate(column, facts, project) {
12579
+ if (facts.pr?.state === "merged") return { ok: true };
12580
+ const waived = noCiWaives(facts.pr, project);
12581
+ let marker = {};
12582
+ for (const id of COLUMN_IDS.slice(0, COLUMN_IDS.indexOf(column) + 1)) {
12583
+ if (project.columns.find((c) => c.id === id)?.enabled !== true) continue;
12584
+ if (id === "dev" && waived) marker = { checksWaivedBy: "reposWithoutCi" };
12585
+ const [first, ...rest] = columnCondition(id, facts, project.columns, waived);
12586
+ if (first !== void 0) return {
12587
+ ok: false,
12588
+ column: id,
12589
+ reasons: [first, ...rest],
12590
+ ...marker
12591
+ };
12592
+ }
12428
12593
  return {
12429
- turn,
12430
- task
12594
+ ok: true,
12595
+ ...marker
12431
12596
  };
12432
12597
  }
12433
- function pollErrorHint(error, pr) {
12434
- switch (error.kind) {
12435
- case "timeout": return `GitHub did not answer for ${pr} within ${String(SUBMIT_POLL_TIMEOUT_MS / 1e3)} s; wait, then submit again.`;
12436
- case "blind": return `The board cannot read ${pr} (${error.reason}); ask the operator to fix the GitHub access, then submit again.`;
12437
- case "failed": return error.retryAt === void 0 ? `The GitHub poll of ${pr} failed (${error.adapterKind}); wait, then submit again.` : `GitHub is throttled until ${error.retryAt}; submit again after that.`;
12438
- case "stopped": return "The GitHub poller is not running; submit again once the daemon is up.";
12439
- case "unknown_source": return `The repo of ${pr} is not in the project's repos; ask the operator to add it to the config.`;
12440
- case "unsupported": return "This daemon cannot poll a pull request on demand; ask the operator to update the daemon.";
12598
+ /** A return counts toward the column's cycle limit when one of its causes counts. */
12599
+ const COUNTED = {
12600
+ executor: true,
12601
+ changes_requested: true,
12602
+ external_comments: true,
12603
+ conflict: false,
12604
+ checks_red: false,
12605
+ draft: false
12606
+ };
12607
+ /**
12608
+ * Counts the returns from `column` since its last limit reset, once per return with a counted
12609
+ * cause. `events` are in the order they happened.
12610
+ */
12611
+ function countCycles(events, column, limit) {
12612
+ let count = 0;
12613
+ for (const event of events) {
12614
+ if (event.column !== column) continue;
12615
+ if (event.kind === "limit_reset") count = 0;
12616
+ else if (event.causes.some((cause) => COUNTED[cause])) count += 1;
12441
12617
  }
12618
+ return {
12619
+ count,
12620
+ limitReached: count >= limit
12621
+ };
12442
12622
  }
12443
- /** Throws `github_unavailable` unless `prepared` is a successful poll of this PR. */
12444
- function confirmPolled(prepared, pr) {
12445
- const label = `${pr.repo}#${String(pr.number)}`;
12446
- const unavailable = (hint) => new CommandError("github_unavailable", hint);
12447
- 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.`);
12448
- const { result } = prepared;
12449
- if (result === null) throw unavailable("This daemon runs no GitHub poller; ask the operator to check the daemon.");
12450
- if (!result.ok) throw unavailable(pollErrorHint(result.error, label));
12451
- if (result.value.status !== "ok") throw unavailable(`GitHub answered ${result.value.status} for ${label}; ask the operator to check the board's GitHub access.`);
12623
+ //#endregion
12624
+ //#region ../core/src/domain/dispatch.ts
12625
+ /** No rule cycles, so a real cascade ends long before this; the bound is a guard. */
12626
+ const STEP_BOUND = 2 * COLUMN_IDS.length;
12627
+ const NO_TURN = {
12628
+ visit: "none",
12629
+ open: false,
12630
+ operatorUntaken: false
12631
+ };
12632
+ const indexOf$1 = (column) => COLUMN_IDS.indexOf(column);
12633
+ function orchestratorOf(project, column) {
12634
+ return project.columns.find((c) => c.id === column)?.orchestrator ?? "none";
12452
12635
  }
12453
- /** Moves the task back to Dev as a new visit and closes its turn. */
12454
- async function moveTaskLeft(trx, task, turn, block, ctx) {
12455
- const moved = await trx.updateTable("task").set({
12456
- column: "dev",
12457
- column_epoch: task.column_epoch + 1,
12458
- left_moves: task.left_moves + 1,
12459
- last_change_at: ctx.at
12460
- }).where("id", "=", task.id).returningAll().executeTakeFirstOrThrow();
12461
- await closeTurns(trx, {
12462
- taskId: task.id,
12463
- reason: "moved",
12464
- at: new Date(ctx.at)
12465
- });
12466
- await emit(trx, "task_moved", task.project, task.id, ctx.at, {
12467
- from: task.column,
12468
- to: "dev",
12469
- turn: turnLabel(turn.id),
12470
- block: `B${String(block.id)}`
12471
- }, ctx.actor);
12472
- return moved;
12636
+ /** The next enabled column of the project right of `column`, if any. */
12637
+ function nextColumn(project, column) {
12638
+ return project.columns.find((c) => c.enabled && indexOf$1(c.id) > indexOf$1(column))?.id;
12473
12639
  }
12474
- /** The executor's submit and return of a turn it took. */
12475
- function createTurnMutations(deps) {
12476
- const { config, prPoller } = deps;
12477
- return {
12478
- submit: {
12479
- id: "task.submit",
12480
- resolveTargets: (trx, input) => turnVisitTarget(trx, input.turn),
12481
- async prepare(db, input, actor) {
12482
- const turn = await turnById(db, input.turn);
12483
- if (turn?.acked_by !== actor) return { kind: "skipped" };
12484
- const task = await taskById(db, turn.task_id);
12485
- if (task.membership === "archived" || !current(turn, task)) return { kind: "skipped" };
12486
- const pr = await taskPr(db, task.id);
12487
- if (pr === null) return { kind: "skipped" };
12488
- const repo = pr.repo.toLowerCase();
12489
- const poll = prPoller?.();
12490
- const result = poll === void 0 ? null : await poll(`github:${task.project}:${repo}`, {
12491
- kind: "pr",
12492
- repo: pr.repo,
12493
- number: pr.number
12494
- }, { timeoutMs: SUBMIT_POLL_TIMEOUT_MS });
12495
- return {
12496
- kind: "polled",
12497
- repo,
12498
- number: pr.number,
12499
- result
12500
- };
12501
- },
12502
- async run(trx, input, ctx) {
12503
- const { turn, task } = await takenTurn(trx, input.turn, ctx);
12504
- const pr = await taskPr(trx, task.id);
12505
- 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.");
12506
- confirmPolled(ctx.prepared, pr);
12507
- const snapshot = await trx.selectFrom("pr_snapshot").select("head_sha").where(sql`lower(repo) = ${pr.repo.toLowerCase()}`).where("number", "=", pr.number).executeTakeFirst();
12508
- if (snapshot?.head_sha.toLowerCase() !== input.sha) throw new CommandError("head_mismatch", `The head of ${pr.repo}#${String(pr.number)} is ${snapshot?.head_sha ?? "unknown"}; push the commit, then submit the head.`);
12509
- await trx.insertInto("submission").values({
12510
- task_id: task.id,
12511
- column: turn.column,
12512
- epoch: turn.epoch,
12513
- commit_sha: input.sha,
12514
- author: ctx.actor,
12515
- submitted_at: ctx.at,
12516
- note: null
12517
- }).execute();
12518
- await closeTurns(trx, {
12519
- taskId: task.id,
12520
- reason: "submitted",
12521
- at: new Date(ctx.at)
12522
- });
12523
- await emit(trx, "task_submitted", task.project, task.id, ctx.at, {
12524
- turn: input.turn,
12525
- column: turn.column,
12526
- sha: input.sha
12527
- }, ctx.actor);
12528
- return {
12529
- task: taskView(task),
12530
- turn: input.turn,
12531
- sha: input.sha
12532
- };
12533
- }
12534
- },
12535
- return: {
12536
- id: "task.return",
12537
- resolveTargets: (trx, input) => turnVisitTarget(trx, input.turn),
12538
- async run(trx, input, ctx) {
12539
- const { turn, task } = await takenTurn(trx, input.turn, ctx);
12540
- if (!RETURNABLE.includes(task.column)) throw new CommandError("return_not_allowed", `The task is in ${task.column}; only a task right of Dev returns to Dev.`);
12541
- const block = await openBlock(trx, task, "code", input.reason, ctx, config);
12542
- await queueBlockOpen(trx, task, block, ctx, config);
12543
- const moved = await moveTaskLeft(trx, task, turn, block, ctx);
12544
- return {
12545
- task: taskView(moved),
12546
- block: blockView(block, moved)
12547
- };
12640
+ /** A left move to `to` voids the submits of `to` and right of it; marks stay. */
12641
+ function dropSubmits(marks, to) {
12642
+ return marks.filter((mark) => mark.kind === "mark" || indexOf$1(mark.column) < indexOf$1(to));
12643
+ }
12644
+ /**
12645
+ * Runs the dispatcher cascade from the task's column: each step moves the task or ends with at
12646
+ * most one turn for its column. A turn whose executor is the worker (a column with orchestrator
12647
+ * `none`) is deferred while Spur is blind.
12648
+ */
12649
+ function dispatch(input) {
12650
+ const moves = [];
12651
+ if (input.githubBlind) return {
12652
+ moves,
12653
+ turn: null
12654
+ };
12655
+ const { project, reopened, cycleHeld } = input;
12656
+ const workerLive = input.liveWorker && !input.spurBlind;
12657
+ const workStarted = input.openPr || !reopened && workerLive;
12658
+ let { column, facts, turn } = input;
12659
+ const move = (to, reason, gate) => {
12660
+ moves.push({
12661
+ from: column,
12662
+ to,
12663
+ reason,
12664
+ ...gate === void 0 ? {} : { gate }
12665
+ });
12666
+ if (indexOf$1(to) < indexOf$1(column)) facts = {
12667
+ ...facts,
12668
+ marks: dropSubmits(facts.marks, to)
12669
+ };
12670
+ column = to;
12671
+ turn = NO_TURN;
12672
+ };
12673
+ const result = (next) => {
12674
+ const deferred = next !== null && input.spurBlind && orchestratorOf(project, next.column) === "none";
12675
+ const opened = cycleHeld || deferred ? null : next;
12676
+ const handsOver = opened?.column === "dev" && facts.commentHistory === "complete" && facts.unhandledExternalComments > 0;
12677
+ return opened !== null && (opened.kind === "after_submit" || handsOver) ? {
12678
+ moves,
12679
+ turn: opened,
12680
+ voids: opened.column
12681
+ } : {
12682
+ moves,
12683
+ turn: opened
12684
+ };
12685
+ };
12686
+ for (let step = 0; step < STEP_BOUND; step++) {
12687
+ const merged = facts.pr?.state === "merged";
12688
+ if (column === "done") {
12689
+ if (reopened && !merged) {
12690
+ move("todo", "ticket_reopened");
12691
+ continue;
12548
12692
  }
12693
+ if (turn.visit !== "none") return result(null);
12694
+ const executor = orchestratorOf(project, "done");
12695
+ return result((executor === "none" ? workerLive : executor !== "operator") ? {
12696
+ column,
12697
+ reasons: [],
12698
+ kind: "wrap_up"
12699
+ } : null);
12700
+ }
12701
+ if (merged) {
12702
+ move("done", "merged");
12703
+ continue;
12549
12704
  }
12550
- };
12551
- }
12552
- //#endregion
12553
- //#region ../core/src/app/registry.ts
12554
- const catalog = await buildCatalogSnapshot(OPERATIONS);
12555
- /** Concrete handlers shared by the daemon's HTTP and inbound transports. */
12556
- function createOperationRegistry(deps) {
12557
- const { config, clock, completeSince, gateways } = deps;
12558
- const items = createItemMutations(deps);
12559
- const membership = createMembershipMutations(config);
12560
- const links = createLinkMutations(config);
12561
- const blocks = createBlockMutations(config);
12562
- const taskQueries = createTaskQueries(config);
12563
- const turns = createTurnMutations({
12564
- config,
12565
- prPoller: deps.prPoller
12566
- });
12567
- return {
12568
- "schema.get": {
12569
- id: "schema.get",
12570
- resolveTargets() {
12571
- return Promise.resolve([]);
12572
- },
12573
- run(_trx, input) {
12574
- const role = input.role;
12575
- return Promise.resolve({
12576
- version: catalog.version,
12577
- operations: catalog.operations.filter((operation) => role === void 0 || roleCanUseOperation(operation, role)).map((operation) => ({
12578
- id: operation.id,
12579
- kind: operation.kind,
12580
- description: operation.description,
12581
- grants: operation.grants === "any" ? "any" : operation.grants.map((rule) => ({
12582
- grant: rule.grant,
12583
- ...rule.mode === void 0 ? {} : { mode: rule.mode },
12584
- ...rule.blockTypes === void 0 ? {} : { blockTypes: [...rule.blockTypes] }
12585
- })),
12586
- errors: [...operation.errors],
12587
- cli: {
12588
- ...operation.cli,
12589
- args: [...operation.cli.args],
12590
- modes: operation.cli.modes?.map((mode) => ({ ...mode })) ?? null
12591
- },
12592
- mcp: { ...operation.mcp },
12593
- inputSchema: operation.input,
12594
- outputSchema: operation.output
12595
- }))
12596
- });
12597
- }
12598
- },
12599
- "status.get": {
12600
- id: "status.get",
12601
- resolveTargets(_trx, input, actor) {
12602
- return Promise.resolve(projectTargets(config, input.project, actor));
12603
- },
12604
- run(trx, input, actor) {
12605
- return getStatus({
12606
- store: { db: trx },
12607
- config,
12608
- clock,
12609
- completeSince,
12610
- gateways
12611
- }, {
12612
- project: input.project,
12613
- visibleProjects: visibleProjects(config, actor),
12614
- includeBoardItems: authorize([{ grant: "operator" }], actor, {
12615
- config,
12616
- target: { kind: "missing" }
12617
- }).status === "allowed",
12618
- detail: input.detail
12619
- });
12620
- }
12621
- },
12622
- "task.get": taskQueries.get,
12623
- "task.history": taskQueries.history,
12624
- "inbox.get": taskQueries.inbox,
12625
- "token.list": tokenListQuery(clock),
12626
- "token.revoke": tokenRevokeMutation,
12627
- "task.add": membership.add,
12628
- "task.archive": membership.archive,
12629
- "link.add": links.add,
12630
- "link.remove": links.remove,
12631
- "block.ask": blocks.ask,
12632
- "block.create": blocks.create,
12633
- "block.escalate": blocks.escalate,
12634
- "block.answer": blocks.answer,
12635
- "block.unblock": blocks.unblock,
12636
- "comment.add": blocks.add,
12637
- "comment.edit": blocks.edit,
12638
- "inbox.ack": blocks.ack,
12639
- "item.retry": items.retry,
12640
- "item.close": items.close,
12641
- "task.submit": turns.submit,
12642
- "task.return": turns.return
12643
- };
12644
- }
12645
- //#endregion
12646
- //#region ../core/src/app/doctor.ts
12647
- const LIVE_VERSION_KEY = "doctor_live_version";
12648
- /** Configured adapter IDs, including repos used by more than one project. */
12649
- function doctorSources(config) {
12650
- return /* @__PURE__ */ new Set(["spur", ...config.projects.flatMap((project) => [trackerSource(project), ...project.repos.map((repo) => `github:${project.id}:${repo.toLowerCase()}`)])]);
12651
- }
12652
- /**
12653
- * True once every configured source that is not blind has had a complete poll in this process.
12654
- * A blind source never completes, so it is left out rather than holding the answer false.
12655
- */
12656
- async function firstPollDone(db, config, completeSince) {
12657
- const states = await db.selectFrom("source_state").select("source").where("blind_reason", "is not", null).execute();
12658
- const blind = new Set(states.map((state) => state.source));
12659
- return [...doctorSources(config)].every((source) => blind.has(source) || completeSince.has(source));
12660
- }
12661
- /**
12662
- * The curator of each board project and the live session its curator blocks ring, in config
12663
- * order. It asks the doorbells for their choice rather than keeping a copy, so the doctor cannot
12664
- * name one session while the rings go to another.
12665
- */
12666
- async function curatorSessions(db, config) {
12667
- const entries = [];
12668
- for (const project of config.projects) entries.push({
12669
- project: project.id,
12670
- curator: curatorProject(config, project.id),
12671
- session: (await curatorSession(db, config, project.id))?.id ?? null
12672
- });
12673
- return entries;
12674
- }
12675
- /**
12676
- * Called from an accepted observation's transaction after board and item reconciliation.
12677
- * The version marker and feed row share that transaction with the source-state update.
12678
- */
12679
- async function enqueueLiveAfterFirstPoll(trx, input) {
12680
- if ([...doctorSources(input.config)].some((source) => !input.completeSince.has(source) || input.blind.has(source))) return;
12681
- const value = JSON.stringify(input.productVersion);
12682
- if ((await trx.selectFrom("meta").select("value").where("key", "=", LIVE_VERSION_KEY).executeTakeFirst())?.value === value) return;
12683
- const tasks = await trx.selectFrom("task").select(sql`count(*)`.as("count")).where("membership", "!=", "archived").executeTakeFirstOrThrow();
12684
- const items = await trx.selectFrom("operator_item").select(sql`count(*)`.as("count")).where("cleared_at", "is", null).where("line_outbox_id", "is not", null).executeTakeFirstOrThrow();
12685
- const text = `spur-board is live: ${String(tasks.count)} tasks, ${String(items.count)} for you`;
12686
- await enqueueLiveFeedLine(trx, {
12687
- version: input.productVersion,
12688
- text,
12689
- at: new Date(input.at)
12690
- });
12691
- await trx.insertInto("meta").values({
12692
- key: LIVE_VERSION_KEY,
12693
- value
12694
- }).onConflict((oc) => oc.column("key").doUpdateSet({ value })).execute();
12695
- }
12696
- //#endregion
12697
- //#region ../core/src/app/membership-rules.ts
12698
- /** Run-local completeness is the only evidence allowed to authorize filter absence. */
12699
- async function reconcileMembership(trx, config, completeSince, at) {
12700
- const states = await trx.selectFrom("source_state").select(["source", "blind_reason"]).execute();
12701
- const blind = new Set(states.filter((state) => state.blind_reason !== null).map((state) => state.source));
12702
- const tasks = await trx.selectFrom("task").selectAll().where("membership", "!=", "archived").execute();
12703
- for (const task of tasks) {
12704
- if (task.manual_include === 1 || task.manual_exclude === 1) continue;
12705
- const project = config.projects.find((entry) => entry.id === task.project);
12706
- if (project === void 0) continue;
12707
- const ticket = await trx.selectFrom("ticket_snapshot").selectAll().where("task_id", "=", task.id).executeTakeFirst();
12708
- if (ticket === void 0) continue;
12709
- if (JSON.parse(ticket.detail).inFilter === true) continue;
12710
- const links = await trx.selectFrom("link").selectAll().where("task_id", "=", task.id).where("banned", "=", 0).execute();
12711
- let retained = false;
12712
- for (const link of links) if (link.entity === "pr" && link.repo !== null && link.number !== null) {
12713
- if ((await trx.selectFrom("pr_snapshot").select("state").where(sql`lower(repo) = ${link.repo.toLowerCase()}`).where("number", "=", link.number).executeTakeFirst())?.state === "open") retained = true;
12714
- } else if (link.entity === "session" && link.session_id !== null) {
12715
- if ((await trx.selectFrom("session_snapshot").select("ended_at").where("id", "=", link.session_id).executeTakeFirst())?.ended_at === null) retained = true;
12716
- }
12717
- if (retained) {
12718
- if (task.membership !== "out_of_filter") {
12719
- await trx.updateTable("task").set({ membership: "out_of_filter" }).where("id", "=", task.id).execute();
12720
- await emit(trx, "flag_raised", task.project, task.id, at, { flag: "out_of_filter" });
12721
- }
12722
- } else {
12723
- if ([
12724
- "spur",
12725
- trackerSource(project),
12726
- ...project.repos.map((repo) => `github:${project.id}:${repo.toLowerCase()}`)
12727
- ].some((source) => {
12728
- const complete = completeSince.get(source);
12729
- return blind.has(source) || complete === void 0 || complete <= (task.last_change_at ?? task.created_at);
12730
- })) continue;
12731
- if (task.membership === "out_of_filter") await emit(trx, "flag_cleared", task.project, task.id, at, { flag: "out_of_filter" });
12732
- await archiveTask(trx, {
12733
- task,
12734
- reason: "out_of_filter",
12735
- actor: "system",
12736
- at
12737
- });
12738
- }
12739
- }
12705
+ if (reopened && facts.pr === null && column !== "todo") {
12706
+ move("todo", "ticket_reopened");
12707
+ continue;
12708
+ }
12709
+ const gate = evaluateGate(column, facts, project);
12710
+ if (gate.ok) {
12711
+ if ((column === "todo" || column === "ready-for-dev") && !workStarted) return result(null);
12712
+ const next = nextColumn(project, column);
12713
+ if (cycleHeld || next === void 0 || next === "done") return result(null);
12714
+ move(next, "gate_passed");
12715
+ continue;
12716
+ }
12717
+ const reasons = [...gate.reasons];
12718
+ if (gate.column !== column) {
12719
+ if (cycleHeld || turn.open || reasons.every((reason) => HOLD_ONLY.has(reason))) return result(null);
12720
+ move(gate.column, "gate_broken", reasons);
12721
+ continue;
12722
+ }
12723
+ const executor = orchestratorOf(project, column);
12724
+ if (column === "external-review" && executor === "none") return result(null);
12725
+ if (reasons.includes("pr_closed")) return result(null);
12726
+ switch (turn.visit) {
12727
+ case "none": return result({
12728
+ column,
12729
+ reasons,
12730
+ kind: "entry"
12731
+ });
12732
+ case "unclosed": return result(turn.operatorUntaken && executor === "none" && workerLive ? {
12733
+ column,
12734
+ reasons,
12735
+ kind: "reroute"
12736
+ } : null);
12737
+ case "submitted": return result(reasons.some((reason) => !HOLD_ONLY.has(reason)) ? {
12738
+ column,
12739
+ reasons,
12740
+ kind: "after_submit"
12741
+ } : null);
12742
+ }
12743
+ }
12744
+ return result(null);
12745
+ }
12746
+ const CAUSE_OF = {
12747
+ checks_red: "checks_red",
12748
+ conflict: "conflict",
12749
+ pr_draft: "draft",
12750
+ external_comments: "external_comments"
12751
+ };
12752
+ /**
12753
+ * The cycle causes of a return to Dev: `executor` when the column executor returned it with a
12754
+ * block, then one cause per gate reason that maps to one. Other reasons give no cause.
12755
+ */
12756
+ function returnCauses(gate, byExecutor) {
12757
+ const causes = byExecutor ? ["executor"] : [];
12758
+ for (const reason of gate) {
12759
+ const cause = CAUSE_OF[reason];
12760
+ if (cause !== void 0 && !causes.includes(cause)) causes.push(cause);
12761
+ }
12762
+ return causes;
12763
+ }
12764
+ /**
12765
+ * The reason text of a new turn: `<column>: <reason>, <reason>`, or `done: wrap up`. A reroute
12766
+ * keeps the reason of the operator turn it replaces, given as `rerouted`.
12767
+ */
12768
+ function turnReason(turn, rerouted) {
12769
+ if (turn.kind === "wrap_up") return "done: wrap up";
12770
+ if (turn.kind === "reroute" && rerouted !== void 0) return rerouted;
12771
+ return `${turn.column}: ${turn.reasons.join(", ")}`;
12740
12772
  }
12741
12773
  //#endregion
12742
12774
  //#region ../core/src/domain/health.ts
@@ -12964,7 +12996,7 @@ async function reconcileItems(trx, config, now, spurComplete) {
12964
12996
  "pr_snapshot.state",
12965
12997
  "pr_snapshot.source",
12966
12998
  "pr_snapshot.observed_at"
12967
- ]).where("link.entity", "=", "pr").where("link.banned", "=", 0).execute();
12999
+ ]).where("link.entity", "=", "pr").where("link.banned", "=", 0).where(pastReopenFloor).execute();
12968
13000
  const taskPrs = {};
12969
13001
  for (const task of tasks) taskPrs[String(task.id)] = {
12970
13002
  hasOpenPr: false,
@@ -13159,53 +13191,949 @@ async function reconcileItems(trx, config, now, spurComplete) {
13159
13191
  }
13160
13192
  }
13161
13193
  /**
13162
- * Raises a ledger item with the operator block it stands for. An active item of the key is
13163
- * returned as it is, so a repeated raise opens no second block.
13194
+ * Raises a ledger item with the operator block it stands for. An active item of the key is
13195
+ * returned as it is, so a repeated raise opens no second block.
13196
+ */
13197
+ async function raiseAnomaly(trx, config, task, input) {
13198
+ const active = await trx.selectFrom("operator_item").selectAll().where("item_key", "=", input.itemKey).where("cleared_at", "is", null).executeTakeFirst();
13199
+ if (active !== void 0) return active;
13200
+ const prefix = `${task.key}: `;
13201
+ const block = await openSystemBlock(trx, {
13202
+ task,
13203
+ reason: input.text.startsWith(prefix) ? input.text.slice(prefix.length) : input.text,
13204
+ at: input.at.toISOString(),
13205
+ config
13206
+ });
13207
+ return raiseItem(trx, {
13208
+ ...input,
13209
+ taskId: task.id,
13210
+ blockId: block.id
13211
+ });
13212
+ }
13213
+ /** Clears a reconciled item; a ledger item's open block is withdrawn by the board first. */
13214
+ async function clearReconciled(trx, item, at) {
13215
+ if (item.block_id !== null) {
13216
+ const ctx = {
13217
+ actor: "system",
13218
+ at: at.toISOString()
13219
+ };
13220
+ await closeBlockIfOpen(trx, item.block_id, ctx, "withdrawn", "condition ended");
13221
+ }
13222
+ await clearItem(trx, item.id, at);
13223
+ }
13224
+ /**
13225
+ * Raises the cycle-limit block of a task's column, once while it is open. The operator's close
13226
+ * of the block or its item is the reset: a later call opens a new block.
13227
+ */
13228
+ async function raiseCycleLimit(trx, input) {
13229
+ const { task, column, at, config } = input;
13230
+ return raiseAnomaly(trx, config, task, {
13231
+ itemKey: `cycle-limit:${String(task.id)}:${column}`,
13232
+ kind: "cycle_limit",
13233
+ text: `${task.key}: reached the cycle limit in ${column}`,
13234
+ url: taskUrl(task, config),
13235
+ at
13236
+ });
13237
+ }
13238
+ /**
13239
+ * The Spur-derived anomaly keys a blind Spur holds open: a health flag of a session still linked
13240
+ * to its task, and a stuck turn `quietTurns` still lists, so a removed worker holder's link ends
13241
+ * the hold by the same rule that keeps its block closed after Spur recovers.
13242
+ */
13243
+ async function blindHeldKeys(trx, subjects) {
13244
+ const held = /* @__PURE__ */ new Set();
13245
+ for (const subject of subjects) for (const kind of ANOMALY_FLAGS) held.add(healthKey(Number(subject.taskId), {
13246
+ taskId: subject.taskId,
13247
+ sessionId: subject.id,
13248
+ kind
13249
+ }));
13250
+ for (const { turn } of await quietTurns(trx)) held.add(`stuck-turn:${String(turn.id)}`);
13251
+ return held;
13252
+ }
13253
+ function healthKey(taskId, flag) {
13254
+ return `health:${String(taskId)}:${flag.sessionId}:${flag.kind}`;
13255
+ }
13256
+ //#endregion
13257
+ //#region ../core/src/app/dispatch.ts
13258
+ const CURSOR_KEY = "dispatcher_cursor";
13259
+ const modeKey = (project) => `dispatcher_mode:${project}`;
13260
+ const cursorSchema = z.int().min(0);
13261
+ const modeSchema = z.enum(DISPATCHER_MODES);
13262
+ /** Columns whose submissions are marks: they last for their head across visits. */
13263
+ const MARK_COLUMNS = ["review", "product-review"];
13264
+ const indexOf = (column) => COLUMN_IDS.indexOf(column);
13265
+ const cycleKeyPrefix = (taskId) => `cycle-limit:${String(taskId)}:`;
13266
+ /** A reopened ticket or a mode switch moves a task left without counting a return. */
13267
+ const uncounted = (reason) => reason === "ticket_reopened" || reason === "mode_changed";
13268
+ /**
13269
+ * Sets `voided_at` on the unvoided submits of `columns`. Review and product-review marks are
13270
+ * never voided.
13271
+ */
13272
+ async function voidColumns(trx, taskId, columns, at) {
13273
+ const voided = columns.filter((column) => !MARK_COLUMNS.includes(column));
13274
+ if (voided.length === 0) return;
13275
+ await trx.updateTable("submission").set({ voided_at: at.toISOString() }).where("task_id", "=", taskId).where("voided_at", "is", null).where("column", "in", voided).execute();
13276
+ }
13277
+ /** Voids the submits of `to` and every column right of it, as a left move does. */
13278
+ async function voidSubmits(trx, taskId, to, at) {
13279
+ await voidColumns(trx, taskId, COLUMN_IDS.filter((column) => indexOf(column) >= indexOf(to)), at);
13280
+ }
13281
+ /** Whether the returns from `column` since its last limit reset reach the column's limit. */
13282
+ async function cycleLimitReached(trx, taskId, column, limit) {
13283
+ const prefix = cycleKeyPrefix(taskId);
13284
+ const items = await trx.selectFrom("operator_item").select(["id", "item_key"]).where("item_key", "like", `${prefix}%`).execute();
13285
+ const itemColumn = new Map(items.map((item) => [`I${String(item.id)}`, item.item_key.slice(prefix.length)]));
13286
+ const rows = await trx.selectFrom("event").select(["kind", "payload"]).where("task_id", "=", taskId).where("kind", "in", ["task_moved", "from_you_cleared"]).orderBy("id").execute();
13287
+ const events = [];
13288
+ for (const row of rows) {
13289
+ if (row.kind === "from_you_cleared") {
13290
+ const cleared = eventPayloadSchemas.from_you_cleared.safeParse(JSON.parse(row.payload));
13291
+ const of = cleared.success ? itemColumn.get(cleared.data.item) : void 0;
13292
+ if (of !== void 0 && COLUMN_IDS.includes(of)) events.push({
13293
+ kind: "limit_reset",
13294
+ column: of
13295
+ });
13296
+ continue;
13297
+ }
13298
+ const moved = eventPayloadSchemas.task_moved.safeParse(JSON.parse(row.payload));
13299
+ if (!moved.success) continue;
13300
+ const { from, to, reason, gate, block } = moved.data;
13301
+ if (indexOf(to) >= indexOf(from) || uncounted(reason)) continue;
13302
+ const [first, ...rest] = returnCauses(gate ?? [], block !== void 0);
13303
+ if (first !== void 0) events.push({
13304
+ kind: "return",
13305
+ column: from,
13306
+ causes: [first, ...rest]
13307
+ });
13308
+ }
13309
+ return countCycles(events, column, limit).limitReached;
13310
+ }
13311
+ /**
13312
+ * Moves a task left to `to` as a new visit: bumps `column_epoch` and `left_moves`, voids the
13313
+ * submits of `to` and right of it, closes its turns and journals `task_moved`. In `on` mode a
13314
+ * counted return that reaches the column's cycle limit raises its cycle-limit block, and
13315
+ * `limitReached` tells the dispatcher to stop the cascade.
13316
+ */
13317
+ async function moveLeft(trx, input) {
13318
+ const { task, to, at, actor, config, turn, block, reason, gate } = input;
13319
+ const moved = await trx.updateTable("task").set({
13320
+ column: to,
13321
+ column_epoch: task.column_epoch + 1,
13322
+ left_moves: task.left_moves + 1,
13323
+ last_change_at: at.toISOString()
13324
+ }).where("id", "=", task.id).returningAll().executeTakeFirstOrThrow();
13325
+ await voidSubmits(trx, task.id, to, at);
13326
+ await closeTurns(trx, {
13327
+ taskId: task.id,
13328
+ reason: "moved",
13329
+ at
13330
+ });
13331
+ await emit(trx, "task_moved", task.project, task.id, at.toISOString(), {
13332
+ from: task.column,
13333
+ to,
13334
+ ...turn === void 0 ? {} : { turn },
13335
+ ...block === void 0 ? {} : { block },
13336
+ ...reason === void 0 ? {} : { reason },
13337
+ ...gate === void 0 ? {} : { gate: [...gate] }
13338
+ }, actor);
13339
+ const project = config.projects.find((entry) => entry.id === task.project);
13340
+ const limit = project?.columns.find((column) => column.id === task.column)?.cycleLimit;
13341
+ if (project?.dispatcher.mode !== "on" || limit === void 0 || uncounted(reason) || !await cycleLimitReached(trx, task.id, task.column, limit)) return {
13342
+ task: moved,
13343
+ limitReached: false
13344
+ };
13345
+ await raiseCycleLimit(trx, {
13346
+ task: moved,
13347
+ column: task.column,
13348
+ at,
13349
+ config
13350
+ });
13351
+ return {
13352
+ task: moved,
13353
+ limitReached: true
13354
+ };
13355
+ }
13356
+ /**
13357
+ * Applies a changed dispatcher mode of each project, as stored in `meta`. A first run only stores
13358
+ * the mode. A switch to `on` copies each task's shadow column into its column as a new visit; a
13359
+ * switch to `shadow` closes the project's unclosed turns. Either switch then clears the shadow
13360
+ * column and journals `dispatcher_mode_changed`.
13361
+ */
13362
+ async function syncModes(trx, config, at) {
13363
+ for (const project of config.projects) {
13364
+ const mode = project.dispatcher.mode;
13365
+ const row = await trx.selectFrom("meta").select("value").where("key", "=", modeKey(project.id)).executeTakeFirst();
13366
+ const stored = row === void 0 ? void 0 : parseJson(modeSchema, row.value);
13367
+ if (stored === mode) continue;
13368
+ await trx.insertInto("meta").values({
13369
+ key: modeKey(project.id),
13370
+ value: toJson(modeSchema, mode)
13371
+ }).onConflict((oc) => oc.column("key").doUpdateSet({ value: toJson(modeSchema, mode) })).execute();
13372
+ if (stored === void 0) continue;
13373
+ if (mode === "on") {
13374
+ const tasks = await trx.selectFrom("task").selectAll().where("project", "=", project.id).where("membership", "!=", "archived").where("shadow_column", "is not", null).whereRef("shadow_column", "!=", "column").orderBy("id").execute();
13375
+ for (const task of tasks) {
13376
+ if (task.shadow_column === null) continue;
13377
+ await trx.updateTable("task").set({
13378
+ column: task.shadow_column,
13379
+ column_epoch: task.column_epoch + 1,
13380
+ last_change_at: at.toISOString()
13381
+ }).where("id", "=", task.id).execute();
13382
+ await closeTurns(trx, {
13383
+ taskId: task.id,
13384
+ reason: "moved",
13385
+ at
13386
+ });
13387
+ await emit(trx, "task_moved", task.project, task.id, at.toISOString(), {
13388
+ from: task.column,
13389
+ to: task.shadow_column,
13390
+ reason: "mode_changed"
13391
+ });
13392
+ }
13393
+ } else {
13394
+ const open = await trx.selectFrom("turn").innerJoin("task", "task.id", "turn.task_id").select("turn.task_id").distinct().where("task.project", "=", project.id).where("turn.closed_at", "is", null).orderBy("turn.task_id").execute();
13395
+ for (const { task_id } of open) await closeTurns(trx, {
13396
+ taskId: task_id,
13397
+ reason: "moved",
13398
+ at
13399
+ });
13400
+ }
13401
+ await trx.updateTable("task").set({ shadow_column: null }).where("project", "=", project.id).where("shadow_column", "is not", null).execute();
13402
+ await emit(trx, "dispatcher_mode_changed", project.id, null, at.toISOString(), {
13403
+ from: stored,
13404
+ to: mode
13405
+ });
13406
+ }
13407
+ }
13408
+ /** A source has no fresh view while it reports blind or has had no complete poll since start. */
13409
+ async function blindSources(trx, complete) {
13410
+ const states = await trx.selectFrom("source_state").select(["source", "blind_reason"]).execute();
13411
+ const blind = new Set(states.filter((state) => state.blind_reason !== null).map((state) => state.source));
13412
+ return (source) => blind.has(source) || !complete.has(source);
13413
+ }
13414
+ function parsePr(detail) {
13415
+ if (detail === void 0) return null;
13416
+ try {
13417
+ const parsed = prFactsSchema.safeParse(JSON.parse(detail));
13418
+ return parsed.success ? parsed.data : null;
13419
+ } catch {
13420
+ return null;
13421
+ }
13422
+ }
13423
+ /** Whether the external reviewers approved: one approval, and no changes requested by one. */
13424
+ function externalApproval(pr, agentLogin) {
13425
+ const external = (login) => login.toLowerCase() !== agentLogin.toLowerCase() && !(pr.feedback ?? []).some((entry) => entry.author?.type === "bot" && entry.author.login.toLowerCase() === login.toLowerCase());
13426
+ const reviews = pr.reviews.filter((review) => external(review.reviewer));
13427
+ return reviews.some((review) => review.state === "approved") && !reviews.some((review) => review.state === "changes_requested");
13428
+ }
13429
+ /**
13430
+ * The external feedback nobody handled yet. An approval review is not a comment: an entry is one
13431
+ * by its own state, or, in a snapshot written before entries had one, when it matches the
13432
+ * reviewer's latest approval. An entry is handled once a turn handed it over, or an older one, or
13433
+ * once a handling submission (`handlingSubmits`) on this PR was made at or after it.
13434
+ */
13435
+ async function unhandledFeedback(trx, task, project, pr) {
13436
+ const approvals = pr.reviews.filter((review) => review.state === "approved");
13437
+ const entries = (pr.feedback ?? []).filter((entry) => isExternalAuthor(entry, project.operatorGithubLogin) && !(entry.kind === "review" && (entry.state === void 0 ? approvals.some((review) => review.reviewer.toLowerCase() === entry.author?.login.toLowerCase() && Date.parse(review.submittedAt) === Date.parse(entry.postedAt)) : entry.state === "approved")));
13438
+ const submitted = (await handlingSubmits(trx, [task.id], [project])).filter((row) => submittedOn(row, pr));
13439
+ const newest = Math.max(...submitted.map((row) => Date.parse(row.submitted_at)));
13440
+ const [cursor] = await turnFeedbackCursors(trx, [{
13441
+ kind: "pr",
13442
+ repo: pr.repo,
13443
+ number: pr.number
13444
+ }]);
13445
+ return entries.filter((entry) => !(Date.parse(entry.postedAt) <= newest) && (cursor === void 0 || isNewer(entry, cursor))).map((entry) => handedOf(pr, entry));
13446
+ }
13447
+ /**
13448
+ * The submissions of `taskIds` that handle the external feedback posted before them on the PR
13449
+ * they were made on (`submittedOn`): those in Dev, whatever its orchestrator, or in another
13450
+ * worker column. In `on` mode only a turnless
13451
+ * (shadow) submit counts, since a turn records what it handed over: a turned submit closes its
13452
+ * turn `submitted` at the same instant in the same column visit, and a shadow submit has no turn.
13453
+ */
13454
+ async function handlingSubmits(db, taskIds, projects) {
13455
+ const columns = projects.flatMap((project) => handlingColumns(project).map((column) => ({
13456
+ project,
13457
+ column
13458
+ })));
13459
+ if (taskIds.length === 0 || columns.length === 0) return [];
13460
+ return (await db.selectFrom("submission").innerJoin("task", "task.id", "submission.task_id").select([
13461
+ "submission.task_id",
13462
+ "task.project",
13463
+ "submission.column",
13464
+ "submission.submitted_at",
13465
+ "submission.pr_repo",
13466
+ "submission.pr_number",
13467
+ sql`exists (select 1 from turn where turn.task_id = submission.task_id and turn."column" = submission."column" and turn.epoch = submission.epoch and turn.closed_reason = 'submitted' and turn.closed_at = submission.submitted_at)`.as("turned")
13468
+ ]).where("submission.task_id", "in", taskIds).execute()).filter((row) => columns.some(({ project, column }) => project.id === row.project && column === row.column && (project.dispatcher.mode === "shadow" || row.turned === 0)));
13469
+ }
13470
+ /** Whether a submission was checked against `pr`; one recorded without its PR is on none. */
13471
+ function submittedOn(row, pr) {
13472
+ return row.pr_repo?.toLowerCase() === pr.repo.toLowerCase() && row.pr_number === pr.number;
13473
+ }
13474
+ /** The columns whose submission handles the external feedback posted before it. */
13475
+ function handlingColumns(project) {
13476
+ return project.columns.filter((column) => column.id === "dev" || column.orchestrator === "none").map((column) => column.id);
13477
+ }
13478
+ /**
13479
+ * Per requested PR, the feedback cursor for the GitHub poll: the newer of the newest entry a turn
13480
+ * handed over and the time-only cursor at its task's newest handling submission on that PR
13481
+ * (`handlingSubmits`), the cutoff of `unhandledFeedback`. No real entry has the empty id, so the
13482
+ * adapter reads back to the first comment older than that time.
13483
+ */
13484
+ async function pollFeedbackCursors(db, config, prs) {
13485
+ const cursors = await turnFeedbackCursors(db, prs);
13486
+ if (prs.length === 0) return cursors;
13487
+ const links = await db.selectFrom("link").select([
13488
+ "task_id",
13489
+ "repo",
13490
+ "number"
13491
+ ]).where("entity", "=", "pr").where("banned", "=", 0).where(sql`lower(repo)`, "in", prs.map((pr) => pr.repo.toLowerCase())).execute();
13492
+ const submitted = await handlingSubmits(db, [...new Set(links.map((link) => link.task_id))], config.projects);
13493
+ const merged = [];
13494
+ for (const ref of prs) {
13495
+ let best = cursors.find((cursor) => cursor.ref.number === ref.number && cursor.ref.repo.toLowerCase() === ref.repo.toLowerCase());
13496
+ for (const link of links) {
13497
+ if (link.repo?.toLowerCase() !== ref.repo.toLowerCase() || link.number !== ref.number) continue;
13498
+ for (const row of submitted) {
13499
+ if (row.task_id !== link.task_id || !submittedOn(row, ref)) continue;
13500
+ const cursor = {
13501
+ ref,
13502
+ id: "",
13503
+ postedAt: row.submitted_at
13504
+ };
13505
+ if (best === void 0 || isNewer(cursor, best)) best = cursor;
13506
+ }
13507
+ }
13508
+ if (best !== void 0) merged.push(best);
13509
+ }
13510
+ return merged;
13511
+ }
13512
+ function handedOf(pr, entry) {
13513
+ return {
13514
+ repo: pr.repo,
13515
+ number: pr.number,
13516
+ kind: entry.kind,
13517
+ id: entry.id,
13518
+ postedAt: entry.postedAt
13519
+ };
13520
+ }
13521
+ /** The dispatcher input of one task, or null when a stored snapshot is missing or unreadable. */
13522
+ async function readInput(trx, task, project, mode, blind) {
13523
+ const link = await taskPr(trx, task.id);
13524
+ let pr = null;
13525
+ if (link !== null) {
13526
+ pr = parsePr((await trx.selectFrom("pr_snapshot").select("detail").where(sql`lower(repo) = ${link.repo.toLowerCase()}`).where("number", "=", link.number).executeTakeFirst())?.detail);
13527
+ if (pr === null) return null;
13528
+ }
13529
+ const githubBlind = (pr === null ? project.repos : [pr.repo]).some((repo) => blind(`github:${project.id}:${repo.toLowerCase()}`));
13530
+ 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) => {
13531
+ const headSha = row.commit_sha.toLowerCase();
13532
+ return row.column === "review" || row.column === "product-review" ? {
13533
+ kind: "mark",
13534
+ column: row.column,
13535
+ headSha
13536
+ } : {
13537
+ kind: "submit",
13538
+ column: row.column,
13539
+ headSha
13540
+ };
13541
+ });
13542
+ const unhandled = pr === null ? [] : await unhandledFeedback(trx, task, project, pr);
13543
+ const handed = pr?.feedbackComplete === true ? unhandled : [];
13544
+ const column = mode === "shadow" ? task.shadow_column ?? task.column : task.column;
13545
+ 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();
13546
+ const unclosed = last?.closed_at === null ? last : void 0;
13547
+ const held = mode === "on" && await trx.selectFrom("operator_item").select("id").where("item_key", "like", `${cycleKeyPrefix(task.id)}%`).where("cleared_at", "is", null).executeTakeFirst() !== void 0;
13548
+ return {
13549
+ input: {
13550
+ column,
13551
+ project: {
13552
+ columns: project.columns,
13553
+ reposWithoutCi: project.reposWithoutCi
13554
+ },
13555
+ facts: {
13556
+ pr,
13557
+ externalReviewApproved: pr !== null && externalApproval(pr, project.operatorGithubLogin),
13558
+ commentHistory: pr?.feedbackComplete === true ? "complete" : "incomplete",
13559
+ unhandledExternalComments: unhandled.length,
13560
+ marks
13561
+ },
13562
+ reopened: await trx.selectFrom("link").select("id").where("task_id", "=", task.id).where("reopen_hidden_at", "is not", null).executeTakeFirst() !== void 0,
13563
+ openPr: link?.open === true,
13564
+ githubBlind,
13565
+ spurBlind: blind("spur"),
13566
+ liveWorker: await linkedSession(trx, task.id, "worker") !== void 0,
13567
+ cycleHeld: held,
13568
+ turn: {
13569
+ visit: last === void 0 ? "none" : unclosed !== void 0 ? "unclosed" : last.closed_reason === "submitted" ? "submitted" : "none",
13570
+ open: unclosed?.acked_at != null,
13571
+ operatorUntaken: unclosed?.role === "operator" && unclosed.acked_at === null
13572
+ }
13573
+ },
13574
+ handed,
13575
+ unclosed
13576
+ };
13577
+ }
13578
+ async function applyShadow(trx, task, result, at) {
13579
+ const last = result.moves.at(-1);
13580
+ if (last === void 0) return;
13581
+ for (const move of result.moves) {
13582
+ if (indexOf(move.to) < indexOf(move.from)) await voidSubmits(trx, task.id, move.to, at);
13583
+ await emit(trx, "task_shadow_moved", task.project, task.id, at.toISOString(), {
13584
+ from: move.from,
13585
+ to: move.to,
13586
+ reason: move.reason,
13587
+ ...move.gate === void 0 ? {} : { gate: [...move.gate] }
13588
+ });
13589
+ }
13590
+ await trx.updateTable("task").set({ shadow_column: last.to }).where("id", "=", task.id).execute();
13591
+ }
13592
+ async function applyOn(trx, task, read, result, ctx) {
13593
+ const { at, config } = ctx;
13594
+ let current = task;
13595
+ for (const move of result.moves) {
13596
+ if (indexOf(move.to) < indexOf(move.from)) {
13597
+ const left = await moveLeft(trx, {
13598
+ task: current,
13599
+ to: move.to,
13600
+ at,
13601
+ actor: "system",
13602
+ config,
13603
+ reason: move.reason,
13604
+ ...move.gate === void 0 ? {} : { gate: move.gate }
13605
+ });
13606
+ current = left.task;
13607
+ if (left.limitReached) return;
13608
+ continue;
13609
+ }
13610
+ current = await trx.updateTable("task").set({
13611
+ column: move.to,
13612
+ last_change_at: at.toISOString()
13613
+ }).where("id", "=", current.id).returningAll().executeTakeFirstOrThrow();
13614
+ await closeTurns(trx, {
13615
+ taskId: current.id,
13616
+ reason: "moved",
13617
+ at
13618
+ });
13619
+ await emit(trx, "task_moved", current.project, current.id, at.toISOString(), {
13620
+ from: move.from,
13621
+ to: move.to,
13622
+ reason: move.reason
13623
+ });
13624
+ }
13625
+ const turn = result.turn;
13626
+ if (turn === null) return;
13627
+ if (result.voids !== void 0) await voidColumns(trx, current.id, [result.voids], at);
13628
+ const replaced = turn.kind === "reroute" ? read.unclosed : void 0;
13629
+ if (replaced !== void 0) await closeTurns(trx, {
13630
+ taskId: current.id,
13631
+ reason: "rerouted",
13632
+ at
13633
+ });
13634
+ const carried = replaced === void 0 ? [] : turnHanded(replaced);
13635
+ const handed = [...carried, ...read.handed.filter((entry) => !carried.some((old) => old.repo.toLowerCase() === entry.repo.toLowerCase() && old.number === entry.number && old.kind === entry.kind && old.id === entry.id))];
13636
+ await openTurn(trx, {
13637
+ task: current,
13638
+ reason: turnReason(turn, replaced?.reason),
13639
+ handed: current.column === "dev" ? handed : [],
13640
+ at,
13641
+ config
13642
+ });
13643
+ }
13644
+ /**
13645
+ * Re-evaluates the gates of each task and applies the cascade: in `on` mode it moves the column
13646
+ * and opens turns, in `shadow` it moves only the shadow column. Archived tasks and tasks of
13647
+ * unconfigured projects are skipped; a task with a missing or unreadable snapshot is held.
13648
+ */
13649
+ async function dispatchTasks(trx, taskIds, ctx) {
13650
+ await syncModes(trx, ctx.config, ctx.at);
13651
+ const blind = await blindSources(trx, ctx.complete);
13652
+ for (const id of [...new Set(taskIds)].sort((left, right) => left - right)) {
13653
+ const task = await trx.selectFrom("task").selectAll().where("id", "=", id).executeTakeFirst();
13654
+ if (task === void 0 || task.membership === "archived") continue;
13655
+ const project = ctx.config.projects.find((entry) => entry.id === task.project);
13656
+ if (project === void 0) continue;
13657
+ const mode = project.dispatcher.mode;
13658
+ const read = await readInput(trx, task, project, mode, blind);
13659
+ if (read === null) continue;
13660
+ const result = dispatch(read.input);
13661
+ if (mode === "shadow") await applyShadow(trx, task, result, ctx.at);
13662
+ else await applyOn(trx, task, read, result, ctx);
13663
+ }
13664
+ }
13665
+ /**
13666
+ * Evaluates every task journaled since the stored cursor, then moves the cursor past the newest
13667
+ * event, the dispatcher's own included. Nothing is written without a new event.
13668
+ */
13669
+ async function dispatchJournaled(trx, ctx) {
13670
+ await syncModes(trx, ctx.config, ctx.at);
13671
+ const row = await trx.selectFrom("meta").select("value").where("key", "=", CURSOR_KEY).executeTakeFirst();
13672
+ const cursor = row === void 0 ? 0 : parseJson(cursorSchema, row.value);
13673
+ const newest = await trx.selectFrom("event").select((eb) => eb.fn.max("id").as("id")).executeTakeFirst();
13674
+ if (newest?.id == null || newest.id <= cursor) return;
13675
+ await dispatchTasks(trx, (await trx.selectFrom("event").select("task_id").distinct().where("id", ">", cursor).where("task_id", "is not", null).execute()).flatMap((task) => task.task_id === null ? [] : [task.task_id]), ctx);
13676
+ const after = await trx.selectFrom("event").select((eb) => eb.fn.max("id").as("id")).executeTakeFirstOrThrow();
13677
+ const value = toJson(cursorSchema, Math.max(after.id, newest.id));
13678
+ await trx.insertInto("meta").values({
13679
+ key: CURSOR_KEY,
13680
+ value
13681
+ }).onConflict((oc) => oc.column("key").doUpdateSet({ value })).execute();
13682
+ }
13683
+ /**
13684
+ * Evaluates every non-archived task of the source's project, or of every project for `spur`: on
13685
+ * the source's first complete poll since start and when it recovers from blindness.
13686
+ */
13687
+ async function dispatchSource(trx, source, ctx) {
13688
+ const projects = source === "spur" ? ctx.config.projects.map((project) => project.id) : [projectForSource(ctx.config, source)?.id].flatMap((id) => id === void 0 ? [] : [id]);
13689
+ if (projects.length === 0) return;
13690
+ await dispatchTasks(trx, (await trx.selectFrom("task").select("id").where("project", "in", projects).where("membership", "!=", "archived").execute()).map((task) => task.id), ctx);
13691
+ }
13692
+ //#endregion
13693
+ //#region ../core/src/app/turn-commands.ts
13694
+ /** How long `task.submit` waits for its on-demand PR poll; the CLI gives up at 30 s. */
13695
+ const SUBMIT_POLL_TIMEOUT_MS = 1e4;
13696
+ /** Columns a task returns to Dev from: right of Dev, before the terminal Done. */
13697
+ const RETURNABLE = [
13698
+ "review",
13699
+ "product-review",
13700
+ "external-review",
13701
+ "qa",
13702
+ "ready-to-merge"
13703
+ ];
13704
+ const turnNumber = (id) => Number(id.slice(1));
13705
+ const turnLabel = (id) => `T${String(id)}`;
13706
+ async function turnById(db, id) {
13707
+ return db.selectFrom("turn").selectAll().where("id", "=", turnNumber(id)).executeTakeFirst();
13708
+ }
13709
+ async function taskById(db, id) {
13710
+ return db.selectFrom("task").selectAll().where("id", "=", id).executeTakeFirstOrThrow();
13711
+ }
13712
+ const isTurnId = (id) => parseRef$1(id, "turn").ok;
13713
+ /** Authorizes against the turn's own column, so a late call on an old turn is `turn_closed`. */
13714
+ async function turnVisitTarget(db, id) {
13715
+ const turn = await turnById(db, id);
13716
+ if (turn === void 0) return [{
13717
+ kind: "missing",
13718
+ id
13719
+ }];
13720
+ return [{
13721
+ ...await authorizationTarget(db, {
13722
+ ...await taskById(db, turn.task_id),
13723
+ column: turn.column
13724
+ }),
13725
+ id
13726
+ }];
13727
+ }
13728
+ /**
13729
+ * The task a submit names by its key, a short `repo#N` form read as `task.get` reads it. A key is
13730
+ * taken only while the task's project dispatcher is in shadow mode; otherwise `wrong_id_kind`.
13731
+ */
13732
+ async function shadowTask(db, key, config) {
13733
+ const parsed = parseRef$1(key, "task");
13734
+ const stored = parsed.ok && parsed.value.kind === "task" && parsed.value.form === "github-short" ? canonicalKey(config, key).key : key;
13735
+ const task = await db.selectFrom("task").selectAll().where("key", "=", stored).executeTakeFirst();
13736
+ if (task === void 0) return void 0;
13737
+ if (config.projects.find((entry) => entry.id === task.project)?.dispatcher.mode !== "shadow") throw new CommandError("wrong_id_kind", "Submit the turn ID from `board inbox`; the project's dispatcher is on.");
13738
+ return task;
13739
+ }
13740
+ const shadowColumn = (task) => task.shadow_column ?? task.column;
13741
+ /** Authorizes a shadow submit against the task at its shadow column. */
13742
+ async function shadowTarget(db, key, config) {
13743
+ const task = await shadowTask(db, key, config);
13744
+ if (task === void 0) return [{
13745
+ kind: "missing",
13746
+ id: key
13747
+ }];
13748
+ return [{
13749
+ ...await authorizationTarget(db, {
13750
+ ...task,
13751
+ column: shadowColumn(task)
13752
+ }),
13753
+ id: key
13754
+ }];
13755
+ }
13756
+ /**
13757
+ * Whether `actor` executes the task's shadow column: a worker session linked to the task for a
13758
+ * column without an orchestrator, a session of the orchestrator project otherwise. The operator
13759
+ * executes no shadow column.
13760
+ */
13761
+ async function executesShadowColumn(db, task, actor, config) {
13762
+ const parsed = parseActorId(actor);
13763
+ if (parsed?.actor !== "agent") return false;
13764
+ const orchestrator = config.projects.find((project) => project.id === task.project)?.columns.find((column) => column.id === shadowColumn(task))?.orchestrator ?? "none";
13765
+ if (orchestrator === "operator") return false;
13766
+ if (orchestrator !== "none") return parsed.actorRef.project === orchestrator;
13767
+ return await db.selectFrom("link").select("id").where("task_id", "=", task.id).where("entity", "=", "session").where("role", "=", "worker").where("banned", "=", 0).where("session_id", "=", parsed.actorRef.session).executeTakeFirst() !== void 0;
13768
+ }
13769
+ /** True when the turn is the current visit's, still unclosed. */
13770
+ function current(turn, task) {
13771
+ return turn.closed_at === null && turn.column === task.column && turn.epoch === task.column_epoch;
13772
+ }
13773
+ /** The refusals both operations share, in order: archived, closed, not the taker. */
13774
+ async function takenTurn(trx, id, ctx) {
13775
+ const turn = await turnById(trx, id);
13776
+ if (turn === void 0) throw new CommandError("not_found", "Check the turn ID.");
13777
+ const task = await taskById(trx, turn.task_id);
13778
+ if (task.membership === "archived") throw new CommandError("task_archived", "Add the task again before changing it.");
13779
+ if (!current(turn, task)) throw new CommandError("turn_closed", `Turn ${id} is closed; read your open turns with \`board inbox\`.`);
13780
+ if (turn.acked_by === null || turn.acked_by !== ctx.actor) throw new CommandError("not_turn_taker", turn.acked_by === null ? `Take turn ${id} with \`board inbox ack ${id}\` first.` : `Turn ${id} was taken by another session; only that session can submit or return it.`);
13781
+ return {
13782
+ turn,
13783
+ task
13784
+ };
13785
+ }
13786
+ function pollErrorHint(error, pr) {
13787
+ switch (error.kind) {
13788
+ case "timeout": return `GitHub did not answer for ${pr} within ${String(SUBMIT_POLL_TIMEOUT_MS / 1e3)} s; wait, then submit again.`;
13789
+ case "blind": return `The board cannot read ${pr} (${error.reason}); ask the operator to fix the GitHub access, then submit again.`;
13790
+ case "failed": return error.retryAt === void 0 ? `The GitHub poll of ${pr} failed (${error.adapterKind}); wait, then submit again.` : `GitHub is throttled until ${error.retryAt}; submit again after that.`;
13791
+ case "stopped": return "The GitHub poller is not running; submit again once the daemon is up.";
13792
+ case "unknown_source": return `The repo of ${pr} is not in the project's repos; ask the operator to add it to the config.`;
13793
+ case "unsupported": return "This daemon cannot poll a pull request on demand; ask the operator to update the daemon.";
13794
+ }
13795
+ }
13796
+ /** Throws `github_unavailable` unless `prepared` is a successful poll of this PR. */
13797
+ function confirmPolled(prepared, pr) {
13798
+ const label = `${pr.repo}#${String(pr.number)}`;
13799
+ const unavailable = (hint) => new CommandError("github_unavailable", hint);
13800
+ 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.`);
13801
+ const { result } = prepared;
13802
+ if (result === null) throw unavailable("This daemon runs no GitHub poller; ask the operator to check the daemon.");
13803
+ if (!result.ok) throw unavailable(pollErrorHint(result.error, label));
13804
+ if (result.value.status !== "ok") throw unavailable(`GitHub answered ${result.value.status} for ${label}; ask the operator to check the board's GitHub access.`);
13805
+ }
13806
+ /** Polls the task's PR on demand for a submit; `skipped` when the task has none. */
13807
+ async function pollTaskPr(db, task, poll) {
13808
+ const pr = await taskPr(db, task.id);
13809
+ if (pr === null) return { kind: "skipped" };
13810
+ const repo = pr.repo.toLowerCase();
13811
+ const result = poll === void 0 ? null : await poll(`github:${task.project}:${repo}`, {
13812
+ kind: "pr",
13813
+ repo: pr.repo,
13814
+ number: pr.number
13815
+ }, { timeoutMs: SUBMIT_POLL_TIMEOUT_MS });
13816
+ return {
13817
+ kind: "polled",
13818
+ repo,
13819
+ number: pr.number,
13820
+ result
13821
+ };
13822
+ }
13823
+ /**
13824
+ * Records the submit of `sha` for the task's `column` visit `epoch`. Throws `head_mismatch` or
13825
+ * `github_unavailable` unless `sha` is the freshly polled PR head.
13826
+ */
13827
+ async function insertSubmission(trx, input, ctx) {
13828
+ const { task, column, epoch, sha } = input;
13829
+ const pr = await taskPr(trx, task.id);
13830
+ 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.");
13831
+ confirmPolled(ctx.prepared, pr);
13832
+ const snapshot = await trx.selectFrom("pr_snapshot").select("head_sha").where(sql`lower(repo) = ${pr.repo.toLowerCase()}`).where("number", "=", pr.number).executeTakeFirst();
13833
+ if (snapshot?.head_sha.toLowerCase() !== sha) throw new CommandError("head_mismatch", `The head of ${pr.repo}#${String(pr.number)} is ${snapshot?.head_sha ?? "unknown"}; push the commit, then submit the head.`);
13834
+ await trx.insertInto("submission").values({
13835
+ task_id: task.id,
13836
+ column,
13837
+ epoch,
13838
+ commit_sha: sha,
13839
+ author: ctx.actor,
13840
+ submitted_at: ctx.at,
13841
+ note: null,
13842
+ pr_repo: pr.repo,
13843
+ pr_number: pr.number
13844
+ }).execute();
13845
+ }
13846
+ /** The executor's submit and return of a turn it took, and the turnless shadow submit. */
13847
+ function createTurnMutations(deps) {
13848
+ const { config, prPoller, completeSince } = deps;
13849
+ /** Dispatches the task after the command's change and returns its fresh row. */
13850
+ async function dispatched(trx, taskId, at) {
13851
+ await dispatchTasks(trx, [taskId], {
13852
+ config,
13853
+ at: new Date(at),
13854
+ complete: completeSince
13855
+ });
13856
+ return taskById(trx, taskId);
13857
+ }
13858
+ async function submitShadow(trx, input, ctx) {
13859
+ const task = await shadowTask(trx, input.turn, config);
13860
+ if (task === void 0) throw new CommandError("not_found", "Check the task key.");
13861
+ if (task.membership === "archived") throw new CommandError("task_archived", "Add the task again before changing it.");
13862
+ const column = shadowColumn(task);
13863
+ if (!await executesShadowColumn(trx, task, ctx.actor, config)) throw new CommandError("forbidden", `Only the executor of ${column} submits this task while the dispatcher is in shadow mode.`);
13864
+ await insertSubmission(trx, {
13865
+ task,
13866
+ column,
13867
+ epoch: task.column_epoch,
13868
+ sha: input.sha
13869
+ }, ctx);
13870
+ await emit(trx, "task_submitted", task.project, task.id, ctx.at, {
13871
+ column,
13872
+ sha: input.sha
13873
+ }, ctx.actor);
13874
+ return {
13875
+ task: taskView(await dispatched(trx, task.id, ctx.at)),
13876
+ turn: null,
13877
+ sha: input.sha
13878
+ };
13879
+ }
13880
+ return {
13881
+ submit: {
13882
+ id: "task.submit",
13883
+ resolveTargets: (trx, input) => isTurnId(input.turn) ? turnVisitTarget(trx, input.turn) : shadowTarget(trx, input.turn, config),
13884
+ async prepare(db, input, actor) {
13885
+ if (!isTurnId(input.turn)) {
13886
+ const task = await shadowTask(db, input.turn, config);
13887
+ if (task === void 0 || task.membership === "archived" || !await executesShadowColumn(db, task, actor, config)) return { kind: "skipped" };
13888
+ return pollTaskPr(db, task, prPoller?.());
13889
+ }
13890
+ const turn = await turnById(db, input.turn);
13891
+ if (turn?.acked_by !== actor) return { kind: "skipped" };
13892
+ const task = await taskById(db, turn.task_id);
13893
+ if (task.membership === "archived" || !current(turn, task)) return { kind: "skipped" };
13894
+ return pollTaskPr(db, task, prPoller?.());
13895
+ },
13896
+ async run(trx, input, ctx) {
13897
+ if (!isTurnId(input.turn)) return submitShadow(trx, input, ctx);
13898
+ const { turn, task } = await takenTurn(trx, input.turn, ctx);
13899
+ await insertSubmission(trx, {
13900
+ task,
13901
+ column: turn.column,
13902
+ epoch: turn.epoch,
13903
+ sha: input.sha
13904
+ }, ctx);
13905
+ await closeTurns(trx, {
13906
+ taskId: task.id,
13907
+ reason: "submitted",
13908
+ at: new Date(ctx.at)
13909
+ });
13910
+ await emit(trx, "task_submitted", task.project, task.id, ctx.at, {
13911
+ turn: input.turn,
13912
+ column: turn.column,
13913
+ sha: input.sha
13914
+ }, ctx.actor);
13915
+ return {
13916
+ task: taskView(await dispatched(trx, task.id, ctx.at)),
13917
+ turn: input.turn,
13918
+ sha: input.sha
13919
+ };
13920
+ }
13921
+ },
13922
+ return: {
13923
+ id: "task.return",
13924
+ resolveTargets: (trx, input) => turnVisitTarget(trx, input.turn),
13925
+ async run(trx, input, ctx) {
13926
+ const { turn, task } = await takenTurn(trx, input.turn, ctx);
13927
+ if (!RETURNABLE.includes(task.column)) throw new CommandError("return_not_allowed", `The task is in ${task.column}; only a task right of Dev returns to Dev.`);
13928
+ const block = await openBlock(trx, task, "code", input.reason, ctx, config);
13929
+ await queueBlockOpen(trx, task, block, ctx, config);
13930
+ await moveLeft(trx, {
13931
+ task,
13932
+ to: "dev",
13933
+ at: new Date(ctx.at),
13934
+ actor: ctx.actor,
13935
+ config,
13936
+ turn: turnLabel(turn.id),
13937
+ block: `B${String(block.id)}`
13938
+ });
13939
+ const moved = await dispatched(trx, task.id, ctx.at);
13940
+ return {
13941
+ task: taskView(moved),
13942
+ block: blockView(block, moved)
13943
+ };
13944
+ }
13945
+ }
13946
+ };
13947
+ }
13948
+ //#endregion
13949
+ //#region ../core/src/app/registry.ts
13950
+ const catalog = await buildCatalogSnapshot(OPERATIONS);
13951
+ /** Concrete handlers shared by the daemon's HTTP and inbound transports. */
13952
+ function createOperationRegistry(deps) {
13953
+ const { config, clock, completeSince, gateways } = deps;
13954
+ const items = createItemMutations(deps);
13955
+ const membership = createMembershipMutations(config);
13956
+ const links = createLinkMutations(config);
13957
+ const blocks = createBlockMutations(config);
13958
+ const taskQueries = createTaskQueries(config);
13959
+ const turns = createTurnMutations({
13960
+ config,
13961
+ prPoller: deps.prPoller,
13962
+ completeSince
13963
+ });
13964
+ return {
13965
+ "schema.get": {
13966
+ id: "schema.get",
13967
+ resolveTargets() {
13968
+ return Promise.resolve([]);
13969
+ },
13970
+ run(_trx, input) {
13971
+ const role = input.role;
13972
+ return Promise.resolve({
13973
+ version: catalog.version,
13974
+ operations: catalog.operations.filter((operation) => role === void 0 || roleCanUseOperation(operation, role)).map((operation) => ({
13975
+ id: operation.id,
13976
+ kind: operation.kind,
13977
+ description: operation.description,
13978
+ grants: operation.grants === "any" ? "any" : operation.grants.map((rule) => ({
13979
+ grant: rule.grant,
13980
+ ...rule.mode === void 0 ? {} : { mode: rule.mode },
13981
+ ...rule.blockTypes === void 0 ? {} : { blockTypes: [...rule.blockTypes] }
13982
+ })),
13983
+ errors: [...operation.errors],
13984
+ cli: {
13985
+ ...operation.cli,
13986
+ args: [...operation.cli.args],
13987
+ modes: operation.cli.modes?.map((mode) => ({ ...mode })) ?? null
13988
+ },
13989
+ mcp: { ...operation.mcp },
13990
+ inputSchema: operation.input,
13991
+ outputSchema: operation.output
13992
+ }))
13993
+ });
13994
+ }
13995
+ },
13996
+ "status.get": {
13997
+ id: "status.get",
13998
+ resolveTargets(_trx, input, actor) {
13999
+ return Promise.resolve(projectTargets(config, input.project, actor));
14000
+ },
14001
+ run(trx, input, actor) {
14002
+ return getStatus({
14003
+ store: { db: trx },
14004
+ config,
14005
+ clock,
14006
+ completeSince,
14007
+ gateways
14008
+ }, {
14009
+ project: input.project,
14010
+ visibleProjects: visibleProjects(config, actor),
14011
+ includeBoardItems: authorize([{ grant: "operator" }], actor, {
14012
+ config,
14013
+ target: { kind: "missing" }
14014
+ }).status === "allowed",
14015
+ detail: input.detail
14016
+ });
14017
+ }
14018
+ },
14019
+ "task.get": taskQueries.get,
14020
+ "task.history": taskQueries.history,
14021
+ "inbox.get": taskQueries.inbox,
14022
+ "token.list": tokenListQuery(clock),
14023
+ "token.revoke": tokenRevokeMutation,
14024
+ "task.add": membership.add,
14025
+ "task.archive": membership.archive,
14026
+ "link.add": links.add,
14027
+ "link.remove": links.remove,
14028
+ "block.ask": blocks.ask,
14029
+ "block.create": blocks.create,
14030
+ "block.escalate": blocks.escalate,
14031
+ "block.answer": blocks.answer,
14032
+ "block.unblock": blocks.unblock,
14033
+ "comment.add": blocks.add,
14034
+ "comment.edit": blocks.edit,
14035
+ "inbox.ack": blocks.ack,
14036
+ "item.retry": items.retry,
14037
+ "item.close": items.close,
14038
+ "task.submit": turns.submit,
14039
+ "task.return": turns.return
14040
+ };
14041
+ }
14042
+ //#endregion
14043
+ //#region ../core/src/app/doctor.ts
14044
+ const LIVE_VERSION_KEY = "doctor_live_version";
14045
+ /** Configured adapter IDs, including repos used by more than one project. */
14046
+ function doctorSources(config) {
14047
+ return /* @__PURE__ */ new Set(["spur", ...config.projects.flatMap((project) => [trackerSource(project), ...project.repos.map((repo) => `github:${project.id}:${repo.toLowerCase()}`)])]);
14048
+ }
14049
+ /**
14050
+ * True once every configured source that is not blind has had a complete poll in this process.
14051
+ * A blind source never completes, so it is left out rather than holding the answer false.
13164
14052
  */
13165
- async function raiseAnomaly(trx, config, task, input) {
13166
- const active = await trx.selectFrom("operator_item").selectAll().where("item_key", "=", input.itemKey).where("cleared_at", "is", null).executeTakeFirst();
13167
- if (active !== void 0) return active;
13168
- const prefix = `${task.key}: `;
13169
- const block = await openSystemBlock(trx, {
13170
- task,
13171
- reason: input.text.startsWith(prefix) ? input.text.slice(prefix.length) : input.text,
13172
- at: input.at.toISOString(),
13173
- config
13174
- });
13175
- return raiseItem(trx, {
13176
- ...input,
13177
- taskId: task.id,
13178
- blockId: block.id
13179
- });
14053
+ async function firstPollDone(db, config, completeSince) {
14054
+ const states = await db.selectFrom("source_state").select("source").where("blind_reason", "is not", null).execute();
14055
+ const blind = new Set(states.map((state) => state.source));
14056
+ return [...doctorSources(config)].every((source) => blind.has(source) || completeSince.has(source));
13180
14057
  }
13181
- /** Clears a reconciled item; a ledger item's open block is withdrawn by the board first. */
13182
- async function clearReconciled(trx, item, at) {
13183
- if (item.block_id !== null) {
13184
- const ctx = {
13185
- actor: "system",
13186
- at: at.toISOString()
13187
- };
13188
- await closeBlockIfOpen(trx, item.block_id, ctx, "withdrawn", "condition ended");
13189
- }
13190
- await clearItem(trx, item.id, at);
14058
+ /**
14059
+ * The curator of each board project and the live session its curator blocks ring, in config
14060
+ * order. It asks the doorbells for their choice rather than keeping a copy, so the doctor cannot
14061
+ * name one session while the rings go to another.
14062
+ */
14063
+ async function curatorSessions(db, config) {
14064
+ const entries = [];
14065
+ for (const project of config.projects) entries.push({
14066
+ project: project.id,
14067
+ curator: curatorProject(config, project.id),
14068
+ session: (await curatorSession(db, config, project.id))?.id ?? null
14069
+ });
14070
+ return entries;
13191
14071
  }
13192
14072
  /**
13193
- * The Spur-derived anomaly keys a blind Spur holds open: a health flag of a session still linked
13194
- * to its task, and a stuck turn `quietTurns` still lists, so a removed worker holder's link ends
13195
- * the hold by the same rule that keeps its block closed after Spur recovers.
14073
+ * Called from an accepted observation's transaction after board and item reconciliation.
14074
+ * The version marker and feed row share that transaction with the source-state update.
13196
14075
  */
13197
- async function blindHeldKeys(trx, subjects) {
13198
- const held = /* @__PURE__ */ new Set();
13199
- for (const subject of subjects) for (const kind of ANOMALY_FLAGS) held.add(healthKey(Number(subject.taskId), {
13200
- taskId: subject.taskId,
13201
- sessionId: subject.id,
13202
- kind
13203
- }));
13204
- for (const { turn } of await quietTurns(trx)) held.add(`stuck-turn:${String(turn.id)}`);
13205
- return held;
14076
+ async function enqueueLiveAfterFirstPoll(trx, input) {
14077
+ if ([...doctorSources(input.config)].some((source) => !input.completeSince.has(source) || input.blind.has(source))) return;
14078
+ const value = JSON.stringify(input.productVersion);
14079
+ if ((await trx.selectFrom("meta").select("value").where("key", "=", LIVE_VERSION_KEY).executeTakeFirst())?.value === value) return;
14080
+ const tasks = await trx.selectFrom("task").select(sql`count(*)`.as("count")).where("membership", "!=", "archived").executeTakeFirstOrThrow();
14081
+ const items = await trx.selectFrom("operator_item").select(sql`count(*)`.as("count")).where("cleared_at", "is", null).where("line_outbox_id", "is not", null).executeTakeFirstOrThrow();
14082
+ const text = `spur-board is live: ${String(tasks.count)} tasks, ${String(items.count)} for you`;
14083
+ await enqueueLiveFeedLine(trx, {
14084
+ version: input.productVersion,
14085
+ text,
14086
+ at: new Date(input.at)
14087
+ });
14088
+ await trx.insertInto("meta").values({
14089
+ key: LIVE_VERSION_KEY,
14090
+ value
14091
+ }).onConflict((oc) => oc.column("key").doUpdateSet({ value })).execute();
13206
14092
  }
13207
- function healthKey(taskId, flag) {
13208
- return `health:${String(taskId)}:${flag.sessionId}:${flag.kind}`;
14093
+ //#endregion
14094
+ //#region ../core/src/app/membership-rules.ts
14095
+ /** Run-local completeness is the only evidence allowed to authorize filter absence. */
14096
+ async function reconcileMembership(trx, config, completeSince, at) {
14097
+ const states = await trx.selectFrom("source_state").select(["source", "blind_reason"]).execute();
14098
+ const blind = new Set(states.filter((state) => state.blind_reason !== null).map((state) => state.source));
14099
+ const tasks = await trx.selectFrom("task").selectAll().where("membership", "!=", "archived").execute();
14100
+ for (const task of tasks) {
14101
+ if (task.manual_include === 1 || task.manual_exclude === 1) continue;
14102
+ const project = config.projects.find((entry) => entry.id === task.project);
14103
+ if (project === void 0) continue;
14104
+ const ticket = await trx.selectFrom("ticket_snapshot").selectAll().where("task_id", "=", task.id).executeTakeFirst();
14105
+ if (ticket === void 0) continue;
14106
+ if (JSON.parse(ticket.detail).inFilter === true) continue;
14107
+ const links = await trx.selectFrom("link").selectAll().where("task_id", "=", task.id).where("banned", "=", 0).execute();
14108
+ let retained = false;
14109
+ for (const link of links) if (link.entity === "pr" && link.repo !== null && link.number !== null) {
14110
+ if ((await trx.selectFrom("pr_snapshot").select("state").where(sql`lower(repo) = ${link.repo.toLowerCase()}`).where("number", "=", link.number).executeTakeFirst())?.state === "open") retained = true;
14111
+ } else if (link.entity === "session" && link.session_id !== null) {
14112
+ if ((await trx.selectFrom("session_snapshot").select("ended_at").where("id", "=", link.session_id).executeTakeFirst())?.ended_at === null) retained = true;
14113
+ }
14114
+ if (retained) {
14115
+ if (task.membership !== "out_of_filter") {
14116
+ await trx.updateTable("task").set({ membership: "out_of_filter" }).where("id", "=", task.id).execute();
14117
+ await emit(trx, "flag_raised", task.project, task.id, at, { flag: "out_of_filter" });
14118
+ }
14119
+ } else {
14120
+ if ([
14121
+ "spur",
14122
+ trackerSource(project),
14123
+ ...project.repos.map((repo) => `github:${project.id}:${repo.toLowerCase()}`)
14124
+ ].some((source) => {
14125
+ const complete = completeSince.get(source);
14126
+ return blind.has(source) || complete === void 0 || complete <= (task.last_change_at ?? task.created_at);
14127
+ })) continue;
14128
+ if (task.membership === "out_of_filter") await emit(trx, "flag_cleared", task.project, task.id, at, { flag: "out_of_filter" });
14129
+ await archiveTask(trx, {
14130
+ task,
14131
+ reason: "out_of_filter",
14132
+ actor: "system",
14133
+ at
14134
+ });
14135
+ }
14136
+ }
13209
14137
  }
13210
14138
  //#endregion
13211
14139
  //#region ../core/src/app/observe.ts
@@ -13225,7 +14153,7 @@ async function updateTerminal(trx, config, taskId, at, completeSince, blind) {
13225
14153
  const project = config.projects.find((entry) => entry.id === task.project);
13226
14154
  if (project === void 0) return;
13227
14155
  const ticket = await trx.selectFrom("ticket_snapshot").select("status").where("task_id", "=", taskId).executeTakeFirst();
13228
- const linked = await trx.selectFrom("link").innerJoin("pr_snapshot", (join) => join.on(sql`lower(pr_snapshot.repo) = lower(link.repo)`).onRef("pr_snapshot.number", "=", "link.number")).select("pr_snapshot.state").where("link.task_id", "=", taskId).where("link.entity", "=", "pr").where("link.banned", "=", 0).execute();
14156
+ const linked = await trx.selectFrom("link").innerJoin("pr_snapshot", (join) => join.on(sql`lower(pr_snapshot.repo) = lower(link.repo)`).onRef("pr_snapshot.number", "=", "link.number")).select("pr_snapshot.state").where("link.task_id", "=", taskId).where("link.entity", "=", "pr").where("link.banned", "=", 0).where(pastReopenFloor).execute();
13229
14157
  const hasOpen = linked.some((pr) => pr.state === "open");
13230
14158
  const merged = linked.some((pr) => pr.state === "merged");
13231
14159
  const doneTicket = ticket !== void 0 && ticketDone(project, ticket.status);
@@ -13237,6 +14165,9 @@ async function updateTerminal(trx, config, taskId, at, completeSince, blind) {
13237
14165
  const terminal = !hasOpen && (merged || doneTicket && githubComplete);
13238
14166
  await trx.updateTable("task").set({ terminal_at: terminal ? task.terminal_at ?? (merged ? at : task.last_change_at ?? at) : null }).where("id", "=", taskId).execute();
13239
14167
  }
14168
+ async function blindReason(trx, source) {
14169
+ return (await trx.selectFrom("source_state").select("blind_reason").where("source", "=", source).executeTakeFirst())?.blind_reason ?? null;
14170
+ }
13240
14171
  async function sourceState(trx, source, state, observedAt, cursor) {
13241
14172
  await trx.insertInto("source_state").values({
13242
14173
  source,
@@ -13278,6 +14209,56 @@ async function moveOpenWork(trx, from, to) {
13278
14209
  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);
13279
14210
  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();
13280
14211
  }
14212
+ /**
14213
+ * A ticket reopened: the task keeps the time (`reopened_at`, read by `pr` for a PR it links later),
14214
+ * and its PR links not seen merged or closed yet wait for their merge (`reopen_pending_at`, read
14215
+ * by `applyPendingReopen`), since GitHub may have merged one before the reopen while the board
14216
+ * still holds an open snapshot. Then `hideMergedLinks` runs.
14217
+ */
14218
+ async function setReopenFloor(trx, taskId, at) {
14219
+ await trx.updateTable("task").set({ reopened_at: at }).where("id", "=", taskId).execute();
14220
+ const unseen = await trx.selectFrom("link").leftJoin("pr_snapshot", (join) => join.on(sql`lower(pr_snapshot.repo) = lower(link.repo)`).onRef("pr_snapshot.number", "=", "link.number")).select("link.id").where("link.task_id", "=", taskId).where("link.entity", "=", "pr").where("link.banned", "=", 0).where((eb) => eb.or([eb("pr_snapshot.state", "is", null), eb("pr_snapshot.state", "=", "open")])).execute();
14221
+ if (unseen.length > 0) await trx.updateTable("link").set({ reopen_pending_at: at }).where("id", "in", unseen.map((link) => link.id)).execute();
14222
+ await hideMergedLinks(trx, taskId, at);
14223
+ }
14224
+ /**
14225
+ * A PR link seen merged or closed after a reopen stops waiting. Its merge counts as made before
14226
+ * the reopen when the PR's `mergedAt` is before the time the board observed the reopen; a tie
14227
+ * counts the merge. Facts without `mergedAt`, stored by an earlier version, fall back to
14228
+ * `updatedAt`, never earlier than the merge, so a later edit makes the merge count. Then the reopen hides this link only: another link
14229
+ * of the task that already counts, such as a follow-up merged after the reopen, keeps counting.
14230
+ */
14231
+ /** The PR was merged before `reopenedAt`; a tie counts the merge. */
14232
+ function mergedBefore(fact, reopenedAt) {
14233
+ return fact.state === "merged" && reopenedAt !== null && Date.parse(fact.mergedAt ?? fact.updatedAt) < Date.parse(reopenedAt);
14234
+ }
14235
+ async function applyPendingReopen(trx, fact, at) {
14236
+ if (fact.state === "open") return;
14237
+ const pending = await trx.selectFrom("link").select(["id", "reopen_pending_at"]).where("entity", "=", "pr").where(sql`lower(repo) = ${fact.repo.toLowerCase()}`).where("number", "=", fact.number).where("reopen_pending_at", "is not", null).execute();
14238
+ for (const link of pending) {
14239
+ const before = mergedBefore(fact, link.reopen_pending_at);
14240
+ await trx.updateTable("link").set({
14241
+ reopen_pending_at: null,
14242
+ ...before ? { reopen_hidden_at: at } : {}
14243
+ }).where("id", "=", link.id).execute();
14244
+ }
14245
+ }
14246
+ /**
14247
+ * A ticket reopened after a merge: the task's PR links that are closed or merged now are hidden
14248
+ * at `at`. They stay in its history, and only the other links decide its state from now on. A
14249
+ * hidden link stays hidden. Nothing without a merged PR link that still counts.
14250
+ */
14251
+ async function hideMergedLinks(trx, taskId, at) {
14252
+ const links = await trx.selectFrom("link").leftJoin("pr_snapshot", (join) => join.on(sql`lower(pr_snapshot.repo) = lower(link.repo)`).onRef("pr_snapshot.number", "=", "link.number")).select([
14253
+ "link.id",
14254
+ "link.banned",
14255
+ "link.pr_open",
14256
+ "pr_snapshot.state"
14257
+ ]).where("link.task_id", "=", taskId).where("link.entity", "=", "pr").where(pastReopenFloor).execute();
14258
+ if (!links.some((link) => link.banned === 0 && link.state === "merged")) return;
14259
+ const hidden = links.filter((link) => link.pr_open !== 1 || link.state === "merged").map((link) => link.id);
14260
+ await trx.updateTable("link").set({ reopen_hidden_at: at }).where("id", "in", hidden).execute();
14261
+ }
13281
14262
  async function ticket(trx, config, fact, at, source) {
13282
14263
  if (fact.trackerId !== source) throw new Error("Ticket from an unconfigured tracker");
13283
14264
  await trx.deleteFrom("source_miss").where("source", "=", source).where("ref_key", "=", `ticket:${source}:${fact.key}`).execute();
@@ -13354,10 +14335,13 @@ async function ticket(trx, config, fact, at, source) {
13354
14335
  source,
13355
14336
  observed_at: at
13356
14337
  })).execute();
13357
- if (previousFact?.status !== fact.status) await emit(trx, "ticket_status_changed", project.id, task.id, at, {
13358
- from: previousFact?.status ?? null,
13359
- to: fact.status
13360
- });
14338
+ if (previousFact?.status !== fact.status) {
14339
+ await emit(trx, "ticket_status_changed", project.id, task.id, at, {
14340
+ from: previousFact?.status ?? null,
14341
+ to: fact.status
14342
+ });
14343
+ if (previousFact !== null && ticketDone(project, previousFact.status) && !ticketDone(project, fact.status)) await setReopenFloor(trx, task.id, at);
14344
+ }
13361
14345
  await emit(trx, "ticket_facts_changed", project.id, task.id, at, { facts: fact });
13362
14346
  await trx.updateTable("task").set({ last_change_at: at }).where("id", "=", task.id).execute();
13363
14347
  } else await trx.updateTable("ticket_snapshot").set({ observed_at: at }).where("task_id", "=", task.id).execute();
@@ -13417,7 +14401,8 @@ async function pr(trx, config, fact, at, source) {
13417
14401
  banned: 0,
13418
14402
  created_at: at,
13419
14403
  ticket_key: null,
13420
- pr_open: fact.state === "open" ? 1 : 0
14404
+ pr_open: fact.state === "open" ? 1 : 0,
14405
+ reopen_hidden_at: mergedBefore(fact, task.reopened_at) ? at : null
13421
14406
  }).execute();
13422
14407
  await emit(trx, "link_added", task.project, task.id, at, {
13423
14408
  entity: "pr",
@@ -13436,6 +14421,7 @@ async function pr(trx, config, fact, at, source) {
13436
14421
  "source",
13437
14422
  "banned"
13438
14423
  ]).where("entity", "=", "pr").where(sql`lower(repo) = ${fact.repo.toLowerCase()}`).where("number", "=", fact.number).execute();
14424
+ if (fact.state === "open" && linkedPrs.length > 0) await trx.updateTable("link").set({ reopen_hidden_at: null }).where("id", "in", linkedPrs.map((link) => link.id)).where("reopen_hidden_at", "is not", null).execute();
13439
14425
  for (const link of linkedPrs) {
13440
14426
  if (fact.state !== "open" || link.banned === 1) {
13441
14427
  await trx.updateTable("link").set({ pr_open: fact.state === "open" ? 1 : 0 }).where("id", "=", link.id).execute();
@@ -13454,6 +14440,7 @@ async function pr(trx, config, fact, at, source) {
13454
14440
  }).where("id", "=", link.id).execute();
13455
14441
  else await trx.updateTable("link").set({ pr_open: 1 }).where("id", "=", link.id).execute();
13456
14442
  }
14443
+ await applyPendingReopen(trx, fact, at);
13457
14444
  if (!changed) return;
13458
14445
  const links = await trx.selectFrom("link").select(["task_id"]).where("entity", "=", "pr").where(sql`lower(repo) = ${fact.repo.toLowerCase()}`).where("number", "=", fact.number).execute();
13459
14446
  for (const link of links) {
@@ -13660,7 +14647,7 @@ function createObservationCore(deps) {
13660
14647
  }
13661
14648
  const misses = await store.db.selectFrom("source_miss").selectAll().where("source", "=", source).execute();
13662
14649
  const requested = [...new Map(prs.map((ref) => [refKey(ref), ref])).values()];
13663
- const feedbackCursors = await turnFeedbackCursors(store.db, requested);
14650
+ const feedbackCursors = await pollFeedbackCursors(store.db, config, requested);
13664
14651
  return {
13665
14652
  observe: {
13666
14653
  prs: requested,
@@ -13682,6 +14669,7 @@ function createObservationCore(deps) {
13682
14669
  const { batch } = observation;
13683
14670
  const now = clock.now();
13684
14671
  await scanTransaction(store, config, async (trx) => {
14672
+ const wasBlind = await blindReason(trx, source);
13685
14673
  await sourceState(trx, source, observation.state, batch.observedAt, batch.cursor);
13686
14674
  for (const outcome of observation.outcomes) {
13687
14675
  const answer = batch.entities.find((entity) => refKey(entity.ref) === refKey(outcome.ref));
@@ -13774,6 +14762,14 @@ function createObservationCore(deps) {
13774
14762
  const activeTasks = await trx.selectFrom("task").select("id").where("membership", "!=", "archived").execute();
13775
14763
  for (const task of activeTasks) await updateTerminal(trx, config, task.id, batch.observedAt, currentComplete, blind);
13776
14764
  await reconcileMembership(trx, config, currentComplete, batch.observedAt);
14765
+ const dispatchContext = {
14766
+ config,
14767
+ at: new Date(batch.observedAt),
14768
+ complete: currentComplete
14769
+ };
14770
+ const recovered = wasBlind !== null && observation.state.blind === void 0;
14771
+ if (observation.effectiveComplete && !completeSince.has(source) || recovered) await dispatchSource(trx, source, dispatchContext);
14772
+ await dispatchJournaled(trx, dispatchContext);
13777
14773
  await reconcileItems(trx, config, now, currentComplete.has("spur"));
13778
14774
  if (deps.productVersion !== void 0) await enqueueLiveAfterFirstPoll(trx, {
13779
14775
  config,
@@ -13788,7 +14784,13 @@ function createObservationCore(deps) {
13788
14784
  reportSourceState(source, state) {
13789
14785
  const now = clock.now();
13790
14786
  return scanTransaction(store, config, async (trx) => {
14787
+ const wasBlind = await blindReason(trx, source);
13791
14788
  await sourceState(trx, source, state);
14789
+ if (wasBlind !== null && state.blind === void 0) await dispatchSource(trx, source, {
14790
+ config,
14791
+ at: new Date(now),
14792
+ complete: completeSince
14793
+ });
13792
14794
  await reconcileItems(trx, config, now, completeSince.has("spur"));
13793
14795
  });
13794
14796
  },
@@ -13880,6 +14882,11 @@ async function tickBoard(deps) {
13880
14882
  at
13881
14883
  });
13882
14884
  }
14885
+ await dispatchJournaled(trx, {
14886
+ config,
14887
+ at: new Date(now),
14888
+ complete: completeSince
14889
+ });
13883
14890
  await remindStuckTurns(trx, config, new Date(now));
13884
14891
  await reconcileItems(trx, config, now, completeSince.has("spur"));
13885
14892
  });
@@ -15063,7 +16070,7 @@ const REVIEWER_FIELDS = "requestedReviewer { __typename ... on Bot { login } ...
15063
16070
  const REVIEW_FIELDS = "id author { __typename login } state commit { oid } submittedAt";
15064
16071
  const COMMENT_FIELDS = "nodes { id author { __typename login } createdAt } pageInfo { hasPreviousPage startCursor }";
15065
16072
  const CLOSING_FIELDS = "nodes { number repository { nameWithOwner } } pageInfo { hasNextPage endCursor }";
15066
- const prFields = (number, closing = false) => `id number url title updatedAt state isDraft mergeable mergeStateStatus
16073
+ const prFields = (number, closing = false) => `id number url title updatedAt mergedAt state isDraft mergeable mergeStateStatus
15067
16074
  author { login } headRefName headRefOid
15068
16075
  statusCheckRollup { contexts(first: 100) { nodes {
15069
16076
  ... on CheckRun { __typename name status conclusion startedAt completedAt checkSuite { createdAt } isRequired(pullRequestNumber: ${String(number)}) }
@@ -15263,6 +16270,7 @@ const prWire = z.object({
15263
16270
  url: z.string(),
15264
16271
  title: z.string(),
15265
16272
  updatedAt: z.string(),
16273
+ mergedAt: z.string().nullable(),
15266
16274
  state: z.string(),
15267
16275
  isDraft: z.boolean(),
15268
16276
  mergeable: z.string(),
@@ -15407,11 +16415,13 @@ function feedbackOf(reviews, comments) {
15407
16415
  });
15408
16416
  for (const node of reviews) {
15409
16417
  if (node.submittedAt == null) continue;
16418
+ const state = REVIEW_STATES.find((known) => known === node.state.toLowerCase());
15410
16419
  add({
15411
16420
  kind: "review",
15412
16421
  id: node.id,
15413
16422
  author: feedbackAuthor(node.author),
15414
- postedAt: node.submittedAt
16423
+ postedAt: node.submittedAt,
16424
+ ...state === void 0 ? {} : { state }
15415
16425
  });
15416
16426
  }
15417
16427
  const tie = (entry) => `${entry.id}\u0000${entry.kind}`;
@@ -15535,6 +16545,7 @@ function normalizePr(repo, value, rule, feedbackComplete) {
15535
16545
  }]),
15536
16546
  ticketKeys: prKeys(rule, title, headBranch, closingRefs(wire.closingIssuesReferences)),
15537
16547
  updatedAt: wire.updatedAt,
16548
+ ...state === "merged" && wire.mergedAt !== null ? { mergedAt: wire.mergedAt } : {},
15538
16549
  feedback: feedbackOf(wire.reviews.nodes, wire.comments.nodes),
15539
16550
  feedbackComplete
15540
16551
  };