spur-board 0.43.1 → 0.44.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/daemon.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as COLUMN_IDS, A as ringMarker, B as err, C as REVIEW_STATES, D as parseRingMarker, E as isExternalAuthor, F as errorCodeOf, I as parseActorId, J as DEFAULT_SLACK_COMMAND, K as DEFAULT_LINK, L as parseRef$1, M as ticketFactsSchema, N as actorIdSchema, O as prFactsSchema, P as encodeActorId, Q as requiredSecretKeys, R as taskKeySchema, S as eventPayloadSchemas, T as SESSION_STATUSES, U as ok, W as successEnvelopeSchema, X as configSchema, Y as RESERVED_PROJECT, Z as plainHttpAllowed, _ as inboundEventSchema, a as batchSchema, b as userIdSchema, c as buildCatalogSnapshot, d as turnHandedSchema, et as DISPATCHER_MODES, f as renderHttpProblem, g as conversationRefSchema, h as SPACE_IDS, i as AdapterError, j as sessionFactsSchema, k as prRefSchema, l as roleCanUseOperation, n as BOARD_TICK_MS, o as entityRefSchema, s as sourceCursorSchema, t as assertNever, tt as SLACK_BOT_SCOPES, u as OPERATIONS, v as interactionRefSchema, w as SESSION_HEALTH_STATES, x as EVENT_KINDS, y as messageRefSchema, z as ERRORS } from "./src-DlZuREcB.mjs";
1
+ import { $ as COLUMN_IDS, A as ringMarker, B as err, C as REVIEW_STATES, D as parseRingMarker, E as isExternalAuthor, F as errorCodeOf, I as parseActorId, J as DEFAULT_SLACK_COMMAND, K as DEFAULT_LINK, L as parseRef$1, M as ticketFactsSchema, N as actorIdSchema, O as prFactsSchema, P as encodeActorId, Q as requiredSecretKeys, R as taskKeySchema, S as eventPayloadSchemas, T as SESSION_STATUSES, U as ok, W as successEnvelopeSchema, X as configSchema, Y as RESERVED_PROJECT, Z as plainHttpAllowed, _ as inboundEventSchema, a as batchSchema, b as userIdSchema, c as buildCatalogSnapshot, d as turnHandedSchema, et as DISPATCHER_MODES, f as renderHttpProblem, g as conversationRefSchema, h as SPACE_IDS, i as AdapterError, j as sessionFactsSchema, k as prRefSchema, l as roleCanUseOperation, n as BOARD_TICK_MS, o as entityRefSchema, s as sourceCursorSchema, t as assertNever, tt as SLACK_BOT_SCOPES, u as OPERATIONS, v as interactionRefSchema, w as SESSION_HEALTH_STATES, x as EVENT_KINDS, y as messageRefSchema, z as ERRORS } from "./src-HVASmsVd.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";
@@ -8042,6 +8042,87 @@ async function emit(trx, kind, project, taskId, at, payload, actor = "system") {
8042
8042
  request_id: commandKeys.getStore() ?? null
8043
8043
  }).execute();
8044
8044
  }
8045
+ const actorRefSchema = z.strictObject({
8046
+ project: z.string().min(1),
8047
+ session: z.string().min(1)
8048
+ });
8049
+ /** The actor ID of a journal row. */
8050
+ function eventActor(row) {
8051
+ const actorRef = row.actor_ref === null ? void 0 : parseJson(actorRefSchema, row.actor_ref);
8052
+ return encodeActorId({
8053
+ actor: row.actor,
8054
+ actorRef
8055
+ });
8056
+ }
8057
+ const MOVE_KINDS = [
8058
+ "task_moved",
8059
+ "task_shadow_moved",
8060
+ "task_corrected"
8061
+ ];
8062
+ function moveView(row) {
8063
+ const base = {
8064
+ at: row.at,
8065
+ actor: eventActor(row)
8066
+ };
8067
+ const payload = JSON.parse(row.payload);
8068
+ if (row.kind === "task_corrected") {
8069
+ const parsed = eventPayloadSchemas.task_corrected.safeParse(payload);
8070
+ if (!parsed.success) return null;
8071
+ const { from, to, reason } = parsed.data;
8072
+ return {
8073
+ ...base,
8074
+ kind: row.kind,
8075
+ from,
8076
+ to,
8077
+ reason: "corrected",
8078
+ gate: [],
8079
+ text: reason
8080
+ };
8081
+ }
8082
+ if (row.kind === "task_shadow_moved") {
8083
+ const parsed = eventPayloadSchemas.task_shadow_moved.safeParse(payload);
8084
+ if (!parsed.success) return null;
8085
+ const { from, to, reason, gate } = parsed.data;
8086
+ return {
8087
+ ...base,
8088
+ kind: row.kind,
8089
+ from,
8090
+ to,
8091
+ reason,
8092
+ gate: gate ?? [],
8093
+ text: null
8094
+ };
8095
+ }
8096
+ const parsed = eventPayloadSchemas.task_moved.safeParse(payload);
8097
+ if (!parsed.success) return null;
8098
+ const { from, to, reason, gate, block } = parsed.data;
8099
+ if (reason === void 0) return block === void 0 ? null : {
8100
+ ...base,
8101
+ kind: "task_moved",
8102
+ from,
8103
+ to,
8104
+ reason: "returned",
8105
+ gate: [],
8106
+ text: block
8107
+ };
8108
+ return {
8109
+ ...base,
8110
+ kind: "task_moved",
8111
+ from,
8112
+ to,
8113
+ reason,
8114
+ gate: gate ?? [],
8115
+ text: null
8116
+ };
8117
+ }
8118
+ /**
8119
+ * The task's column moves, oldest first: those journaled after event `after`, or the newest
8120
+ * `limit`.
8121
+ */
8122
+ async function moveViews(db, taskId, options) {
8123
+ const query = db.selectFrom("event").selectAll().where("task_id", "=", taskId).where("kind", "in", MOVE_KINDS);
8124
+ return ("after" in options ? await query.where("id", ">", options.after).orderBy("id").execute() : (await query.orderBy("id", "desc").limit(options.limit).execute()).reverse()).flatMap((row) => moveView(row) ?? []);
8125
+ }
8045
8126
  function taskView(task) {
8046
8127
  return {
8047
8128
  key: task.key,
@@ -10397,6 +10478,8 @@ async function ringDue(trx, notificationId, config, at) {
10397
10478
  const quiet = (await quietTurns(trx)).find((entry) => entry.reminder?.id === notificationId);
10398
10479
  return quiet !== void 0 && !quiet.ended && quiet.quietSince !== null && at.getTime() >= Date.parse(quiet.quietSince) + stuckTurnAfterMs(config);
10399
10480
  }
10481
+ /** Close reasons of a turn whose untaken feedback goes back to a later turn. */
10482
+ const recalled = /* @__PURE__ */ new Set(["corrected", "rerouted"]);
10400
10483
  /** Whether `left` is newer than `right` by `postedAt` instant, then by id. Compared, not subtracted. */
10401
10484
  function isNewer(left, right) {
10402
10485
  const a = Date.parse(left.postedAt);
@@ -10404,26 +10487,21 @@ function isNewer(left, right) {
10404
10487
  return a !== b ? a > b : left.id > right.id;
10405
10488
  }
10406
10489
  /**
10407
- * Per requested PR, the newest feedback any turn of its linked tasks handed over, acked or not,
10408
- * closed or not, so the cursor never moves back. A PR with none gets no entry.
10490
+ * Per requested PR, the newest feedback a turn of its linked tasks handed over, acked or not,
10491
+ * closed or not. A PR with none gets no entry. `handled` leaves out a turn a correction or a
10492
+ * reroute closed before anyone took it: no executor received its feedback, so after a correction
10493
+ * it counts as unhandled again and the next Dev turn hands it over, and a reroute's replacement
10494
+ * turn handed it over too. `polled` counts every turn, so the poll cursor never moves back.
10409
10495
  */
10410
- async function turnFeedbackCursors(db, prs) {
10496
+ async function turnFeedbackCursors(db, prs, count) {
10411
10497
  if (prs.length === 0) return [];
10412
- const rows = await db.selectFrom("turn").innerJoin("link", "link.task_id", "turn.task_id").select([
10413
- "link.repo",
10414
- "link.number",
10415
- "turn.handed"
10416
- ]).where("link.entity", "=", "pr").where("link.banned", "=", 0).where(sql`lower(link.repo)`, "in", prs.map((pr) => pr.repo.toLowerCase())).execute();
10498
+ const rows = await prTurns(db, prs);
10417
10499
  const cursors = [];
10418
10500
  for (const ref of prs) {
10419
- const repo = ref.repo.toLowerCase();
10420
10501
  let best;
10421
10502
  for (const row of rows) {
10422
- if (row.repo?.toLowerCase() !== repo || row.number !== ref.number) continue;
10423
- for (const entry of turnHanded(row)) {
10424
- if (entry.repo.toLowerCase() !== repo || entry.number !== ref.number) continue;
10425
- if (best === void 0 || isNewer(entry, best)) best = entry;
10426
- }
10503
+ if (count === "handled" && isRecalled(row)) continue;
10504
+ for (const entry of handedOn(row, ref)) if (best === void 0 || isNewer(entry, best)) best = entry;
10427
10505
  }
10428
10506
  if (best !== void 0) cursors.push({
10429
10507
  ref,
@@ -10433,6 +10511,43 @@ async function turnFeedbackCursors(db, prs) {
10433
10511
  }
10434
10512
  return cursors;
10435
10513
  }
10514
+ /**
10515
+ * The feedback on `ref` that the turns `turnFeedbackCursors` leaves out of `handled` handed over,
10516
+ * oldest first and once each. A later poll may have dropped these entries from the PR snapshot,
10517
+ * and the poll cursor, which still counts those turns, never pages back to them.
10518
+ */
10519
+ async function recalledFeedback(db, ref) {
10520
+ const entries = [];
10521
+ for (const row of await prTurns(db, [ref])) {
10522
+ if (!isRecalled(row)) continue;
10523
+ for (const entry of handedOn(row, ref)) if (!entries.some((old) => sameHanded(old, entry))) entries.push(entry);
10524
+ }
10525
+ return entries.sort((left, right) => isNewer(left, right) ? 1 : -1);
10526
+ }
10527
+ /** Whether two handed entries are the same feedback on the same PR. */
10528
+ function sameHanded(left, right) {
10529
+ return left.repo.toLowerCase() === right.repo.toLowerCase() && left.number === right.number && left.kind === right.kind && left.id === right.id;
10530
+ }
10531
+ /** The turns of the tasks linked to `prs`, with the link they were found by. */
10532
+ function prTurns(db, prs) {
10533
+ return db.selectFrom("turn").innerJoin("link", "link.task_id", "turn.task_id").select([
10534
+ "link.repo",
10535
+ "link.number",
10536
+ "turn.handed",
10537
+ "turn.acked_at",
10538
+ "turn.closed_reason"
10539
+ ]).where("link.entity", "=", "pr").where("link.banned", "=", 0).where(sql`lower(link.repo)`, "in", prs.map((pr) => pr.repo.toLowerCase())).execute();
10540
+ }
10541
+ /** Whether a correction or a reroute closed the turn before anyone took it. */
10542
+ function isRecalled(row) {
10543
+ return row.acked_at === null && recalled.has(row.closed_reason);
10544
+ }
10545
+ /** The entries on `ref` that the turn handed over, when it was found through `ref`'s link. */
10546
+ function handedOn(row, ref) {
10547
+ const repo = ref.repo.toLowerCase();
10548
+ if (row.repo?.toLowerCase() !== repo || row.number !== ref.number) return [];
10549
+ return turnHanded(row).filter((entry) => entry.repo.toLowerCase() === repo && entry.number === ref.number);
10550
+ }
10436
10551
  //#endregion
10437
10552
  //#region ../core/src/app/blocks.ts
10438
10553
  const idNumber = (id) => Number(id.slice(1));
@@ -12287,230 +12402,6 @@ async function getStatus(deps, options = {}) {
12287
12402
  };
12288
12403
  }
12289
12404
  //#endregion
12290
- //#region ../core/src/app/task-queries.ts
12291
- const actorRefSchema = z.strictObject({
12292
- project: z.string().min(1),
12293
- session: z.string().min(1)
12294
- });
12295
- const EVENT_SUMMARIES = {
12296
- head_moved: "Pull request head moved",
12297
- pr_facts_changed: "Pull request facts changed",
12298
- checks_changed: "Checks changed",
12299
- review_submitted: "Review submitted",
12300
- mergeable_changed: "Mergeability changed",
12301
- pr_state_changed: "Pull request state changed",
12302
- ticket_status_changed: "Ticket status changed",
12303
- ticket_facts_changed: "Ticket facts changed",
12304
- session_state_changed: "Session state changed",
12305
- session_facts_changed: "Session facts changed",
12306
- spur_unknown_state: "Unknown session state observed",
12307
- link_added: "Link added",
12308
- link_removed: "Link removed",
12309
- task_added: "Task added",
12310
- task_archived: "Task archived",
12311
- task_submitted: "Turn submitted",
12312
- task_moved: "Task moved",
12313
- task_shadow_moved: "Shadow move",
12314
- dispatcher_mode_changed: "Dispatcher mode changed",
12315
- block_opened: "Block opened",
12316
- block_escalated: "Block escalated",
12317
- block_unblocked: "Block unblocked",
12318
- comment_added: "Comment added",
12319
- comment_edited: "Comment edited",
12320
- comment_deleted: "Comment deleted",
12321
- comment_acked: "Comment acknowledged",
12322
- doorbell_rung: "Doorbell rung",
12323
- doorbell_read: "Doorbell read",
12324
- doorbell_undelivered: "Doorbell delivery exhausted",
12325
- inbound_failed: "Inbound message failed",
12326
- inbound_skipped: "Inbound message skipped",
12327
- from_you_raised: "Operator item raised",
12328
- from_you_cleared: "Operator item cleared",
12329
- flag_raised: "Flag raised",
12330
- flag_cleared: "Flag cleared",
12331
- operation_denied: "Operation denied",
12332
- token_requested: "Token requested",
12333
- token_approved: "Token approved",
12334
- token_denied: "Token denied",
12335
- token_expired: "Token expired",
12336
- token_revoked: "Token revoked"
12337
- };
12338
- function linkSummary(kind, payloadText) {
12339
- if (kind !== "link_added" && kind !== "link_removed") return null;
12340
- try {
12341
- const payload = eventPayloadSchemas[kind].safeParse(JSON.parse(payloadText));
12342
- if (!payload.success) return null;
12343
- const target = payload.data.entity === "pr" ? `${payload.data.repo}#${String(payload.data.pr)}` : payload.data.entity === "session" ? payload.data.session : payload.data.ticket;
12344
- return `${kind === "link_added" ? "Link added" : "Link removed"}: ${payload.data.entity} ${target}${payload.data.reason === void 0 ? "" : ` — ${payload.data.reason}`}`;
12345
- } catch {
12346
- return null;
12347
- }
12348
- }
12349
- function projectTarget(project) {
12350
- return {
12351
- kind: "found",
12352
- value: {
12353
- project,
12354
- task: null,
12355
- block: null,
12356
- workers: []
12357
- }
12358
- };
12359
- }
12360
- function visibleProjects(config, actor) {
12361
- return new Set(config.projects.filter((project) => authorize([{ grant: "operator" }, { grant: "project-agent" }], actor, {
12362
- config,
12363
- target: projectTarget(project.id)
12364
- }).status === "allowed").map((project) => project.id));
12365
- }
12366
- function projectTargets(config, project, actor) {
12367
- if (project !== void 0) return config.projects.some((entry) => entry.id === project) ? [projectTarget(project)] : [{ kind: "missing" }];
12368
- const visible = visibleProjects(config, actor);
12369
- const projects = config.projects.filter((entry) => visible.has(entry.id));
12370
- return projects.length === 0 ? [{ kind: "missing" }] : projects.map((entry) => projectTarget(entry.id));
12371
- }
12372
- async function taskByKey(trx, key) {
12373
- const task = await trx.selectFrom("task").selectAll().where("key", "=", key).executeTakeFirst();
12374
- if (task === void 0) throw new CommandError("not_found", "Check the task key.");
12375
- return task;
12376
- }
12377
- function createTaskQueries(config) {
12378
- const taskKey = (key) => {
12379
- const parsed = parseRef$1(key, "task");
12380
- return parsed.ok && parsed.value.kind === "task" && parsed.value.form === "github-short" ? canonicalKey(config, key).key : key;
12381
- };
12382
- const get = {
12383
- id: "task.get",
12384
- resolveTargets: (trx, input) => taskTarget(trx, taskKey(input.task)),
12385
- async run(trx, input) {
12386
- const task = await taskByKey(trx, taskKey(input.task));
12387
- const [blocks, comments, links] = await Promise.all([
12388
- trx.selectFrom("block").selectAll().where("task_id", "=", task.id).orderBy("id").execute(),
12389
- trx.selectFrom("comment").selectAll().where("task_id", "=", task.id).orderBy("id").execute(),
12390
- trx.selectFrom("link").selectAll().where("task_id", "=", task.id).where("banned", "=", 0).orderBy("id").execute()
12391
- ]);
12392
- return {
12393
- task: taskView(task),
12394
- links: links.map(linkView),
12395
- blocks: blocks.map((block) => blockView(block, task)),
12396
- comments: comments.map((comment) => commentView(comment, task))
12397
- };
12398
- }
12399
- };
12400
- const history = {
12401
- id: "task.history",
12402
- resolveTargets: (trx, input) => taskTarget(trx, taskKey(input.task)),
12403
- async run(trx, input) {
12404
- const task = await taskByKey(trx, taskKey(input.task));
12405
- const events = (await trx.selectFrom("event").selectAll().where("task_id", "=", task.id).orderBy("id").execute()).flatMap((row) => {
12406
- const kind = EVENT_KINDS.find((candidate) => candidate === row.kind);
12407
- if (kind === void 0) return [];
12408
- const actorRef = row.actor_ref === null ? void 0 : parseJson(actorRefSchema, row.actor_ref);
12409
- return [{
12410
- at: row.at,
12411
- kind,
12412
- actor: encodeActorId({
12413
- actor: row.actor,
12414
- actorRef
12415
- }),
12416
- summary: linkSummary(kind, row.payload) ?? EVENT_SUMMARIES[kind]
12417
- }];
12418
- });
12419
- return {
12420
- task: taskView(task),
12421
- events
12422
- };
12423
- }
12424
- };
12425
- /**
12426
- * Unclosed agent turns the caller may take or has taken: an untaken one addressed to it, one it
12427
- * took, and a taken orchestrator turn it may take over. At most one per task.
12428
- */
12429
- async function inboxTurns(trx, projects, actor) {
12430
- if (parseActorId(actor)?.actor !== "agent" || projects.size === 0) return [];
12431
- const rows = await trx.selectFrom("turn").innerJoin("task", "task.id", "turn.task_id").selectAll("turn").select("task.key").where("task.project", "in", [...projects]).where("turn.closed_at", "is", null).where("turn.role", "!=", "operator").orderBy("turn.id").execute();
12432
- const turns = [];
12433
- for (const turn of rows) {
12434
- if (turn.acked_by !== actor) {
12435
- const notice = await turnNotification(trx, turn.id);
12436
- const mayTake = turn.acked_at === null ? notice?.acked_at === null : turn.role.startsWith("orchestrator:");
12437
- if (notice === void 0 || !mayTake || !await notificationAddressedTo(trx, notice, actor, config)) continue;
12438
- }
12439
- turns.push({
12440
- id: `T${String(turn.id)}`,
12441
- task: turn.key,
12442
- column: turn.column,
12443
- addressee: turn.role,
12444
- reason: turn.reason,
12445
- handed: turnHanded(turn),
12446
- head: turn.head_sha,
12447
- at: turn.created_at,
12448
- taken: turn.acked_by === null || turn.acked_at === null ? null : {
12449
- by: turn.acked_by,
12450
- at: turn.acked_at
12451
- }
12452
- });
12453
- }
12454
- return turns;
12455
- }
12456
- return {
12457
- get,
12458
- history,
12459
- inbox: {
12460
- id: "inbox.get",
12461
- resolveTargets(_trx, input, actor) {
12462
- return Promise.resolve(projectTargets(config, input.project, actor));
12463
- },
12464
- async run(trx, input, actor) {
12465
- const projects = input.project === void 0 ? visibleProjects(config, actor) : /* @__PURE__ */ new Set([input.project]);
12466
- const notices = await trx.selectFrom("notification").selectAll().where("kind", "=", "answer").where("acked_at", "is", null).orderBy("id", "desc").execute();
12467
- const comments = [];
12468
- const seen = /* @__PURE__ */ new Set();
12469
- for (const notice of notices) {
12470
- if (notice.comment_id === null || seen.has(notice.comment_id)) continue;
12471
- const task = await trx.selectFrom("task").selectAll().where("id", "=", notice.task_id).executeTakeFirst();
12472
- if (task === void 0 || !projects.has(task.project)) continue;
12473
- seen.add(notice.comment_id);
12474
- if (!await notificationAddressedTo(trx, notice, actor, config)) continue;
12475
- const comment = await trx.selectFrom("comment").selectAll().where("id", "=", notice.comment_id).executeTakeFirst();
12476
- if (comment === void 0 || comment.acked_revision === comment.revision) continue;
12477
- comments.push(commentView(comment, task));
12478
- }
12479
- const parsedActor = parseActorId(actor);
12480
- if (parsedActor?.actor === "agent") {
12481
- const linkedTasks = await trx.selectFrom("task").innerJoin("link", "link.task_id", "task.id").selectAll("task").where("task.project", "in", [...projects]).where("link.entity", "=", "session").where("link.role", "=", "worker").where("link.banned", "=", 0).where("link.session_id", "=", parsedActor.actorRef.session).execute();
12482
- const tasksById = new Map(linkedTasks.map((task) => [task.id, task]));
12483
- if (tasksById.size > 0) {
12484
- const taskComments = await trx.selectFrom("comment").selectAll().where("task_id", "in", [...tasksById.keys()]).where("block_id", "is", null).orderBy("id").execute();
12485
- for (const comment of taskComments) {
12486
- const task = tasksById.get(comment.task_id);
12487
- if (task === void 0 || comment.author === actor || comment.acked_revision === comment.revision) continue;
12488
- comments.push(commentView(comment, task));
12489
- }
12490
- }
12491
- }
12492
- comments.sort((left, right) => Number(left.id.slice(1)) - Number(right.id.slice(1)));
12493
- const rows = await trx.selectFrom("block").selectAll().where("state", "=", "open").orderBy("id").execute();
12494
- const blocks = [];
12495
- for (const block of rows) {
12496
- const task = await trx.selectFrom("task").selectAll().where("id", "=", block.task_id).executeTakeFirst();
12497
- if (task === void 0 || !projects.has(task.project)) continue;
12498
- if (authorize([{ grant: "block-addressee" }], actor, {
12499
- config,
12500
- target: await authorizationTarget(trx, task, block)
12501
- }).status !== "allowed") continue;
12502
- blocks.push(blockView(block, task));
12503
- }
12504
- return {
12505
- comments,
12506
- blocks,
12507
- turns: await inboxTurns(trx, projects, actor)
12508
- };
12509
- }
12510
- }
12511
- };
12512
- }
12513
- //#endregion
12514
12405
  //#region ../core/src/domain/gates.ts
12515
12406
  /**
12516
12407
  * The hold-only reasons: a fact is not known yet, and waiting resolves it. See `GateResult` for
@@ -12630,8 +12521,87 @@ function evaluateGate(column, facts, project) {
12630
12521
  ...marker
12631
12522
  };
12632
12523
  }
12633
- /** A return counts toward the column's cycle limit when one of its causes counts. */
12634
- const COUNTED = {
12524
+ /** The exit conditions of each column, in the order the gates report their reasons. */
12525
+ const COLUMN_CONDITIONS = {
12526
+ todo: [],
12527
+ "ready-for-dev": [],
12528
+ dev: [
12529
+ "pr_open",
12530
+ "not_draft",
12531
+ "checks_green",
12532
+ "no_conflict",
12533
+ "external_comments_handled",
12534
+ "comment_history_read",
12535
+ "submit_on_head"
12536
+ ],
12537
+ review: ["review_on_head"],
12538
+ "product-review": ["review_on_head"],
12539
+ "external-review": ["approved"],
12540
+ qa: ["submit_on_head"],
12541
+ "ready-to-merge": ["merged"],
12542
+ done: []
12543
+ };
12544
+ /** The condition each gate reason fails. */
12545
+ const CONDITION_OF = {
12546
+ no_pr: "pr_open",
12547
+ pr_closed: "pr_open",
12548
+ pr_draft: "not_draft",
12549
+ checks_red: "checks_green",
12550
+ checks_pending: "checks_green",
12551
+ conflict: "no_conflict",
12552
+ mergeable_unknown: "no_conflict",
12553
+ external_comments: "external_comments_handled",
12554
+ comment_history_incomplete: "comment_history_read",
12555
+ no_submit_on_head: "submit_on_head",
12556
+ no_review_on_head: "review_on_head",
12557
+ not_approved: "approved",
12558
+ not_merged: "merged"
12559
+ };
12560
+ /** Reasons that stop Dev's evaluation: the rest of its conditions are not checked. */
12561
+ const STOPS_DEV = /* @__PURE__ */ new Set(["no_pr", "pr_closed"]);
12562
+ /**
12563
+ * Every column's own exit conditions with their state, and where its cumulative gate blocks, as
12564
+ * `evaluateGate` decides it for each column. A merged pull request passes every column and every
12565
+ * condition. `checksWaivedBy` is the marker `evaluateGate('done')` carries, or null.
12566
+ */
12567
+ function explainGates(facts, project) {
12568
+ const merged = facts.pr?.state === "merged";
12569
+ const waived = noCiWaives(facts.pr, project);
12570
+ let blockedIn = null;
12571
+ let checksWaivedBy = null;
12572
+ return {
12573
+ gates: COLUMN_IDS.map((column) => {
12574
+ const enabled = project.columns.find((c) => c.id === column)?.enabled === true;
12575
+ const reasons = merged ? [] : columnCondition(column, facts, project.columns, waived);
12576
+ if (enabled && !merged && column === "dev" && waived) checksWaivedBy = "reposWithoutCi";
12577
+ if (enabled && blockedIn === null && reasons.length > 0) blockedIn = column;
12578
+ const stopped = reasons.some((reason) => STOPS_DEV.has(reason));
12579
+ const conditions = COLUMN_CONDITIONS[column].map((condition) => {
12580
+ const reason = reasons.find((r) => CONDITION_OF[r] === condition) ?? null;
12581
+ if (reason === null) return {
12582
+ condition,
12583
+ state: stopped ? "unchecked" : "met",
12584
+ reason: null
12585
+ };
12586
+ return {
12587
+ condition,
12588
+ state: HOLD_ONLY.has(reason) ? "waiting" : "failed",
12589
+ reason
12590
+ };
12591
+ });
12592
+ return {
12593
+ column,
12594
+ enabled,
12595
+ ok: reasons.length === 0,
12596
+ blockedIn,
12597
+ conditions
12598
+ };
12599
+ }),
12600
+ checksWaivedBy
12601
+ };
12602
+ }
12603
+ /** A return counts toward the column's cycle limit when one of its causes counts. */
12604
+ const COUNTED = {
12635
12605
  executor: true,
12636
12606
  changes_requested: true,
12637
12607
  external_comments: true,
@@ -12676,6 +12646,25 @@ function nextColumn(project, column) {
12676
12646
  function dropSubmits(marks, to) {
12677
12647
  return marks.filter((mark) => mark.kind === "mark" || indexOf$1(mark.column) < indexOf$1(to));
12678
12648
  }
12649
+ /** Whether work on the task started: it has an open PR, or a live worker and no reopen. */
12650
+ function workStarted(input) {
12651
+ const workerLive = input.liveWorker && !input.spurBlind;
12652
+ return input.openPr || !input.reopened && workerLive;
12653
+ }
12654
+ /**
12655
+ * What holds the dispatcher on the task now: a blind GitHub stops it, a blind Spur defers a
12656
+ * worker's turn, an active cycle-limit item stops every turn and move right, and To Do and Ready
12657
+ * for Dev wait for the work to start. The last is judged at the task's column, while `dispatch`
12658
+ * judges it at each column the cascade reaches.
12659
+ */
12660
+ function dispatchHolds(input) {
12661
+ const holds = [];
12662
+ if (input.githubBlind) holds.push("github_blind");
12663
+ if (input.spurBlind) holds.push("spur_blind");
12664
+ if (input.cycleHeld) holds.push("cycle_limit");
12665
+ if ((input.column === "todo" || input.column === "ready-for-dev") && !workStarted(input)) holds.push("work_not_started");
12666
+ return holds;
12667
+ }
12679
12668
  /**
12680
12669
  * Runs the dispatcher cascade from the task's column: each step moves the task or ends with at
12681
12670
  * most one turn for its column. A turn whose executor is the worker (a column with orchestrator
@@ -12689,7 +12678,7 @@ function dispatch(input) {
12689
12678
  };
12690
12679
  const { project, reopened, cycleHeld } = input;
12691
12680
  const workerLive = input.liveWorker && !input.spurBlind;
12692
- const workStarted = input.openPr || !reopened && workerLive;
12681
+ const started = workStarted(input);
12693
12682
  let { column, facts, turn } = input;
12694
12683
  const move = (to, reason, gate) => {
12695
12684
  moves.push({
@@ -12743,7 +12732,7 @@ function dispatch(input) {
12743
12732
  }
12744
12733
  const gate = evaluateGate(column, facts, project);
12745
12734
  if (gate.ok) {
12746
- if ((column === "todo" || column === "ready-for-dev") && !workStarted) return result(null);
12735
+ if ((column === "todo" || column === "ready-for-dev") && !started) return result(null);
12747
12736
  const next = nextColumn(project, column);
12748
12737
  if (cycleHeld || next === void 0 || next === "done") return result(null);
12749
12738
  move(next, "gate_passed");
@@ -13440,6 +13429,48 @@ async function syncModes(trx, config, at) {
13440
13429
  });
13441
13430
  }
13442
13431
  }
13432
+ /**
13433
+ * The operator's correction of a task's column to `to`, as a new visit of `to`. It first applies
13434
+ * a pending dispatcher mode switch, so the switch cannot overwrite the correction. In `on` mode it
13435
+ * sets the column and bumps `column_epoch`, voids the submits of `to` and right of it, closes the
13436
+ * task's turns as `corrected` and journals `task_corrected`; in shadow mode it sets only the shadow
13437
+ * column. The feedback a closed untaken turn handed over counts as unhandled again
13438
+ * (`turnFeedbackCursors`), so the next Dev turn hands it over, whenever it opens. It is
13439
+ * not a dispatcher move: no `task_moved`, no `left_moves` and no cycle count. The caller settles
13440
+ * the task with a dispatcher pass after it. `from` is the column the dispatcher worked from, and
13441
+ * `eventId` the id of the `task_corrected` event.
13442
+ */
13443
+ async function correctColumn(trx, input) {
13444
+ const { taskId, to, at, actor, reason, config } = input;
13445
+ await syncModes(trx, config, at);
13446
+ const task = await trx.selectFrom("task").selectAll().where("id", "=", taskId).executeTakeFirstOrThrow();
13447
+ const shadow = config.projects.find((project) => project.id === task.project)?.dispatcher.mode === "shadow";
13448
+ const from = task.shadow_column ?? task.column;
13449
+ await trx.updateTable("task").set(shadow ? {
13450
+ shadow_column: to,
13451
+ last_change_at: at.toISOString()
13452
+ } : {
13453
+ column: to,
13454
+ column_epoch: task.column_epoch + 1,
13455
+ last_change_at: at.toISOString()
13456
+ }).where("id", "=", task.id).execute();
13457
+ await voidSubmits(trx, task.id, to, at);
13458
+ if (!shadow) await closeTurns(trx, {
13459
+ taskId: task.id,
13460
+ reason: "corrected",
13461
+ at
13462
+ });
13463
+ await emit(trx, "task_corrected", task.project, task.id, at.toISOString(), {
13464
+ from,
13465
+ to,
13466
+ reason,
13467
+ shadow
13468
+ }, actor);
13469
+ return {
13470
+ from,
13471
+ eventId: (await trx.selectFrom("event").select("id").where("task_id", "=", task.id).orderBy("id", "desc").executeTakeFirstOrThrow()).id
13472
+ };
13473
+ }
13443
13474
  /** A source has no fresh view while it reports blind or has had no complete poll since start. */
13444
13475
  async function blindSources(trx, complete) {
13445
13476
  const states = await trx.selectFrom("source_state").select(["source", "blind_reason"]).execute();
@@ -13464,8 +13495,10 @@ function externalApproval(pr, agentLogin) {
13464
13495
  /**
13465
13496
  * The external feedback nobody handled yet. An approval review is not a comment: an entry is one
13466
13497
  * by its own state, or, in a snapshot written before entries had one, when it matches the
13467
- * reviewer's latest approval. An entry is handled once a turn handed it over, or an older one, or
13468
- * once a handling submission (`handlingSubmits`) on this PR was made at or after it.
13498
+ * reviewer's latest approval. An entry is handled once a turn handed it over, or an older one,
13499
+ * unless a correction or a reroute closed that turn untaken, or once a handling submission
13500
+ * (`handlingSubmits`) on this PR was made at or after it. The entries such an untaken turn handed
13501
+ * over come from the turn when a later poll dropped them from the snapshot (`recalledFeedback`).
13469
13502
  */
13470
13503
  async function unhandledFeedback(trx, task, project, pr) {
13471
13504
  const approvals = pr.reviews.filter((review) => review.state === "approved");
@@ -13476,8 +13509,13 @@ async function unhandledFeedback(trx, task, project, pr) {
13476
13509
  kind: "pr",
13477
13510
  repo: pr.repo,
13478
13511
  number: pr.number
13479
- }]);
13480
- return entries.filter((entry) => !(Date.parse(entry.postedAt) <= newest) && (cursor === void 0 || isNewer(entry, cursor))).map((entry) => handedOf(pr, entry));
13512
+ }], "handled");
13513
+ const fromSnapshot = entries.map((entry) => handedOf(pr, entry));
13514
+ return [...(await recalledFeedback(trx, {
13515
+ kind: "pr",
13516
+ repo: pr.repo,
13517
+ number: pr.number
13518
+ })).filter((entry) => !fromSnapshot.some((old) => sameHanded(old, entry))), ...fromSnapshot].filter((entry) => !(Date.parse(entry.postedAt) <= newest) && (cursor === void 0 || isNewer(entry, cursor)));
13481
13519
  }
13482
13520
  /**
13483
13521
  * The submissions of `taskIds` that handle the external feedback posted before them on the PR
@@ -13517,7 +13555,7 @@ function handlingColumns(project) {
13517
13555
  * adapter reads back to the first comment older than that time.
13518
13556
  */
13519
13557
  async function pollFeedbackCursors(db, config, prs) {
13520
- const cursors = await turnFeedbackCursors(db, prs);
13558
+ const cursors = await turnFeedbackCursors(db, prs, "polled");
13521
13559
  if (prs.length === 0) return cursors;
13522
13560
  const links = await db.selectFrom("link").select([
13523
13561
  "task_id",
@@ -13553,7 +13591,10 @@ function handedOf(pr, entry) {
13553
13591
  postedAt: entry.postedAt
13554
13592
  };
13555
13593
  }
13556
- /** The dispatcher input of one task, or null when a stored snapshot is missing or unreadable. */
13594
+ /**
13595
+ * The dispatcher input of one task, or null when a stored snapshot is missing or unreadable. It
13596
+ * only reads.
13597
+ */
13557
13598
  async function readInput(trx, task, project, mode, blind) {
13558
13599
  const link = await taskPr(trx, task.id);
13559
13600
  let pr = null;
@@ -13667,7 +13708,7 @@ async function applyOn(trx, task, read, result, ctx) {
13667
13708
  at
13668
13709
  });
13669
13710
  const carried = replaced === void 0 ? [] : turnHanded(replaced);
13670
- 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))];
13711
+ const handed = [...carried, ...read.handed.filter((entry) => !carried.some((old) => sameHanded(old, entry)))];
13671
13712
  await openTurn(trx, {
13672
13713
  task: current,
13673
13714
  reason: turnReason(turn, replaced?.reason),
@@ -13725,6 +13766,273 @@ async function dispatchSource(trx, source, ctx) {
13725
13766
  await dispatchTasks(trx, (await trx.selectFrom("task").select("id").where("project", "in", projects).where("membership", "!=", "archived").execute()).map((task) => task.id), ctx);
13726
13767
  }
13727
13768
  //#endregion
13769
+ //#region ../core/src/app/task-queries.ts
13770
+ /** How many of the last moves `task.get --why` shows. */
13771
+ const WHY_MOVES = 5;
13772
+ const EVENT_SUMMARIES = {
13773
+ head_moved: "Pull request head moved",
13774
+ pr_facts_changed: "Pull request facts changed",
13775
+ checks_changed: "Checks changed",
13776
+ review_submitted: "Review submitted",
13777
+ mergeable_changed: "Mergeability changed",
13778
+ pr_state_changed: "Pull request state changed",
13779
+ ticket_status_changed: "Ticket status changed",
13780
+ ticket_facts_changed: "Ticket facts changed",
13781
+ session_state_changed: "Session state changed",
13782
+ session_facts_changed: "Session facts changed",
13783
+ spur_unknown_state: "Unknown session state observed",
13784
+ link_added: "Link added",
13785
+ link_removed: "Link removed",
13786
+ task_added: "Task added",
13787
+ task_archived: "Task archived",
13788
+ task_submitted: "Turn submitted",
13789
+ task_moved: "Task moved",
13790
+ task_shadow_moved: "Shadow move",
13791
+ task_corrected: "Column corrected by the operator",
13792
+ dispatcher_mode_changed: "Dispatcher mode changed",
13793
+ block_opened: "Block opened",
13794
+ block_escalated: "Block escalated",
13795
+ block_unblocked: "Block unblocked",
13796
+ comment_added: "Comment added",
13797
+ comment_edited: "Comment edited",
13798
+ comment_deleted: "Comment deleted",
13799
+ comment_acked: "Comment acknowledged",
13800
+ doorbell_rung: "Doorbell rung",
13801
+ doorbell_read: "Doorbell read",
13802
+ doorbell_undelivered: "Doorbell delivery exhausted",
13803
+ inbound_failed: "Inbound message failed",
13804
+ inbound_skipped: "Inbound message skipped",
13805
+ from_you_raised: "Operator item raised",
13806
+ from_you_cleared: "Operator item cleared",
13807
+ flag_raised: "Flag raised",
13808
+ flag_cleared: "Flag cleared",
13809
+ operation_denied: "Operation denied",
13810
+ token_requested: "Token requested",
13811
+ token_approved: "Token approved",
13812
+ token_denied: "Token denied",
13813
+ token_expired: "Token expired",
13814
+ token_revoked: "Token revoked"
13815
+ };
13816
+ function linkSummary(kind, payloadText) {
13817
+ if (kind !== "link_added" && kind !== "link_removed") return null;
13818
+ try {
13819
+ const payload = eventPayloadSchemas[kind].safeParse(JSON.parse(payloadText));
13820
+ if (!payload.success) return null;
13821
+ const target = payload.data.entity === "pr" ? `${payload.data.repo}#${String(payload.data.pr)}` : payload.data.entity === "session" ? payload.data.session : payload.data.ticket;
13822
+ return `${kind === "link_added" ? "Link added" : "Link removed"}: ${payload.data.entity} ${target}${payload.data.reason === void 0 ? "" : ` — ${payload.data.reason}`}`;
13823
+ } catch {
13824
+ return null;
13825
+ }
13826
+ }
13827
+ function projectTarget(project) {
13828
+ return {
13829
+ kind: "found",
13830
+ value: {
13831
+ project,
13832
+ task: null,
13833
+ block: null,
13834
+ workers: []
13835
+ }
13836
+ };
13837
+ }
13838
+ function visibleProjects(config, actor) {
13839
+ return new Set(config.projects.filter((project) => authorize([{ grant: "operator" }, { grant: "project-agent" }], actor, {
13840
+ config,
13841
+ target: projectTarget(project.id)
13842
+ }).status === "allowed").map((project) => project.id));
13843
+ }
13844
+ function projectTargets(config, project, actor) {
13845
+ if (project !== void 0) return config.projects.some((entry) => entry.id === project) ? [projectTarget(project)] : [{ kind: "missing" }];
13846
+ const visible = visibleProjects(config, actor);
13847
+ const projects = config.projects.filter((entry) => visible.has(entry.id));
13848
+ return projects.length === 0 ? [{ kind: "missing" }] : projects.map((entry) => projectTarget(entry.id));
13849
+ }
13850
+ async function taskByKey(trx, key) {
13851
+ const task = await trx.selectFrom("task").selectAll().where("key", "=", key).executeTakeFirst();
13852
+ if (task === void 0) throw new CommandError("not_found", "Check the task key.");
13853
+ return task;
13854
+ }
13855
+ function turnView(turn, key) {
13856
+ return {
13857
+ id: `T${String(turn.id)}`,
13858
+ task: key,
13859
+ column: turn.column,
13860
+ addressee: turn.role,
13861
+ reason: turn.reason,
13862
+ handed: turnHanded(turn),
13863
+ head: turn.head_sha,
13864
+ at: turn.created_at,
13865
+ taken: turn.acked_by === null || turn.acked_at === null ? null : {
13866
+ by: turn.acked_by,
13867
+ at: turn.acked_at
13868
+ }
13869
+ };
13870
+ }
13871
+ function createTaskQueries(deps) {
13872
+ const { config, completeSince } = deps;
13873
+ const taskKey = (key) => {
13874
+ const parsed = parseRef$1(key, "task");
13875
+ return parsed.ok && parsed.value.kind === "task" && parsed.value.form === "github-short" ? canonicalKey(config, key).key : key;
13876
+ };
13877
+ /**
13878
+ * Why the task is where it is, read as the next dispatcher pass will see it: from the column it
13879
+ * works from (the shadow column, which only shadow mode sets) and with the configured mode. It
13880
+ * only reads; a pending mode switch is left to the dispatcher.
13881
+ */
13882
+ async function why(trx, task) {
13883
+ const column = task.shadow_column ?? task.column;
13884
+ const open = await trx.selectFrom("turn").selectAll().where("task_id", "=", task.id).where("closed_at", "is", null).orderBy("id", "desc").executeTakeFirst();
13885
+ const shared = {
13886
+ column,
13887
+ turn: open === void 0 ? null : turnView(open, task.key),
13888
+ moves: await moveViews(trx, task.id, { limit: WHY_MOVES })
13889
+ };
13890
+ const project = config.projects.find((entry) => entry.id === task.project);
13891
+ if (project === void 0) return {
13892
+ ...shared,
13893
+ dispatcher: null,
13894
+ holds: [],
13895
+ gates: [],
13896
+ checksWaivedBy: null
13897
+ };
13898
+ const mode = project.dispatcher.mode;
13899
+ const read = await readInput(trx, {
13900
+ ...task,
13901
+ column
13902
+ }, project, mode, await blindSources(trx, completeSince));
13903
+ if (read === null) return {
13904
+ ...shared,
13905
+ dispatcher: mode,
13906
+ holds: ["pr_snapshot_missing"],
13907
+ gates: [],
13908
+ checksWaivedBy: null
13909
+ };
13910
+ const { gates, checksWaivedBy } = explainGates(read.input.facts, read.input.project);
13911
+ return {
13912
+ ...shared,
13913
+ dispatcher: mode,
13914
+ holds: dispatchHolds(read.input),
13915
+ gates,
13916
+ checksWaivedBy
13917
+ };
13918
+ }
13919
+ const get = {
13920
+ id: "task.get",
13921
+ resolveTargets: (trx, input) => taskTarget(trx, taskKey(input.task)),
13922
+ async run(trx, input) {
13923
+ const task = await taskByKey(trx, taskKey(input.task));
13924
+ const [blocks, comments, links] = await Promise.all([
13925
+ trx.selectFrom("block").selectAll().where("task_id", "=", task.id).orderBy("id").execute(),
13926
+ trx.selectFrom("comment").selectAll().where("task_id", "=", task.id).orderBy("id").execute(),
13927
+ trx.selectFrom("link").selectAll().where("task_id", "=", task.id).where("banned", "=", 0).orderBy("id").execute()
13928
+ ]);
13929
+ return {
13930
+ task: taskView(task),
13931
+ links: links.map(linkView),
13932
+ blocks: blocks.map((block) => blockView(block, task)),
13933
+ comments: comments.map((comment) => commentView(comment, task)),
13934
+ ...input.why === true ? { why: await why(trx, task) } : {}
13935
+ };
13936
+ }
13937
+ };
13938
+ const history = {
13939
+ id: "task.history",
13940
+ resolveTargets: (trx, input) => taskTarget(trx, taskKey(input.task)),
13941
+ async run(trx, input) {
13942
+ const task = await taskByKey(trx, taskKey(input.task));
13943
+ const events = (await trx.selectFrom("event").selectAll().where("task_id", "=", task.id).orderBy("id").execute()).flatMap((row) => {
13944
+ const kind = EVENT_KINDS.find((candidate) => candidate === row.kind);
13945
+ if (kind === void 0) return [];
13946
+ return [{
13947
+ at: row.at,
13948
+ kind,
13949
+ actor: eventActor(row),
13950
+ summary: linkSummary(kind, row.payload) ?? EVENT_SUMMARIES[kind]
13951
+ }];
13952
+ });
13953
+ return {
13954
+ task: taskView(task),
13955
+ events
13956
+ };
13957
+ }
13958
+ };
13959
+ /**
13960
+ * Unclosed agent turns the caller may take or has taken: an untaken one addressed to it, one it
13961
+ * took, and a taken orchestrator turn it may take over. At most one per task.
13962
+ */
13963
+ async function inboxTurns(trx, projects, actor) {
13964
+ if (parseActorId(actor)?.actor !== "agent" || projects.size === 0) return [];
13965
+ const rows = await trx.selectFrom("turn").innerJoin("task", "task.id", "turn.task_id").selectAll("turn").select("task.key").where("task.project", "in", [...projects]).where("turn.closed_at", "is", null).where("turn.role", "!=", "operator").orderBy("turn.id").execute();
13966
+ const turns = [];
13967
+ for (const turn of rows) {
13968
+ if (turn.acked_by !== actor) {
13969
+ const notice = await turnNotification(trx, turn.id);
13970
+ const mayTake = turn.acked_at === null ? notice?.acked_at === null : turn.role.startsWith("orchestrator:");
13971
+ if (notice === void 0 || !mayTake || !await notificationAddressedTo(trx, notice, actor, config)) continue;
13972
+ }
13973
+ turns.push(turnView(turn, turn.key));
13974
+ }
13975
+ return turns;
13976
+ }
13977
+ return {
13978
+ get,
13979
+ history,
13980
+ inbox: {
13981
+ id: "inbox.get",
13982
+ resolveTargets(_trx, input, actor) {
13983
+ return Promise.resolve(projectTargets(config, input.project, actor));
13984
+ },
13985
+ async run(trx, input, actor) {
13986
+ const projects = input.project === void 0 ? visibleProjects(config, actor) : /* @__PURE__ */ new Set([input.project]);
13987
+ const notices = await trx.selectFrom("notification").selectAll().where("kind", "=", "answer").where("acked_at", "is", null).orderBy("id", "desc").execute();
13988
+ const comments = [];
13989
+ const seen = /* @__PURE__ */ new Set();
13990
+ for (const notice of notices) {
13991
+ if (notice.comment_id === null || seen.has(notice.comment_id)) continue;
13992
+ const task = await trx.selectFrom("task").selectAll().where("id", "=", notice.task_id).executeTakeFirst();
13993
+ if (task === void 0 || !projects.has(task.project)) continue;
13994
+ seen.add(notice.comment_id);
13995
+ if (!await notificationAddressedTo(trx, notice, actor, config)) continue;
13996
+ const comment = await trx.selectFrom("comment").selectAll().where("id", "=", notice.comment_id).executeTakeFirst();
13997
+ if (comment === void 0 || comment.acked_revision === comment.revision) continue;
13998
+ comments.push(commentView(comment, task));
13999
+ }
14000
+ const parsedActor = parseActorId(actor);
14001
+ if (parsedActor?.actor === "agent") {
14002
+ const linkedTasks = await trx.selectFrom("task").innerJoin("link", "link.task_id", "task.id").selectAll("task").where("task.project", "in", [...projects]).where("link.entity", "=", "session").where("link.role", "=", "worker").where("link.banned", "=", 0).where("link.session_id", "=", parsedActor.actorRef.session).execute();
14003
+ const tasksById = new Map(linkedTasks.map((task) => [task.id, task]));
14004
+ if (tasksById.size > 0) {
14005
+ const taskComments = await trx.selectFrom("comment").selectAll().where("task_id", "in", [...tasksById.keys()]).where("block_id", "is", null).orderBy("id").execute();
14006
+ for (const comment of taskComments) {
14007
+ const task = tasksById.get(comment.task_id);
14008
+ if (task === void 0 || comment.author === actor || comment.acked_revision === comment.revision) continue;
14009
+ comments.push(commentView(comment, task));
14010
+ }
14011
+ }
14012
+ }
14013
+ comments.sort((left, right) => Number(left.id.slice(1)) - Number(right.id.slice(1)));
14014
+ const rows = await trx.selectFrom("block").selectAll().where("state", "=", "open").orderBy("id").execute();
14015
+ const blocks = [];
14016
+ for (const block of rows) {
14017
+ const task = await trx.selectFrom("task").selectAll().where("id", "=", block.task_id).executeTakeFirst();
14018
+ if (task === void 0 || !projects.has(task.project)) continue;
14019
+ const target = await authorizationTarget(trx, task, block);
14020
+ if (authorize([{ grant: "block-addressee" }], actor, {
14021
+ config,
14022
+ target
14023
+ }).status !== "allowed") continue;
14024
+ blocks.push(blockView(block, task));
14025
+ }
14026
+ return {
14027
+ comments,
14028
+ blocks,
14029
+ turns: await inboxTurns(trx, projects, actor)
14030
+ };
14031
+ }
14032
+ }
14033
+ };
14034
+ }
14035
+ //#endregion
13728
14036
  //#region ../core/src/app/turn-commands.ts
13729
14037
  /** How long `task.submit` waits for its on-demand PR poll; the CLI gives up at 30 s. */
13730
14038
  const SUBMIT_POLL_TIMEOUT_MS = 1e4;
@@ -13761,12 +14069,19 @@ async function turnVisitTarget(db, id) {
13761
14069
  }];
13762
14070
  }
13763
14071
  /**
13764
- * The task a submit names by its key, a short `repo#N` form read as `task.get` reads it. A key is
13765
- * taken only while the task's project dispatcher is in shadow mode; otherwise `wrong_id_kind`.
14072
+ * The stored key a task key names, read as `task.get` reads it: only the short `repo#N` form needs
14073
+ * a configured project, so a task whose project left the config is still found by its full key.
13766
14074
  */
13767
- async function shadowTask(db, key, config) {
14075
+ function storedKey(config, key) {
13768
14076
  const parsed = parseRef$1(key, "task");
13769
- const stored = parsed.ok && parsed.value.kind === "task" && parsed.value.form === "github-short" ? canonicalKey(config, key).key : key;
14077
+ return parsed.ok && parsed.value.kind === "task" && parsed.value.form === "github-short" ? canonicalKey(config, key).key : key;
14078
+ }
14079
+ /**
14080
+ * The task a submit names by its key. A key is taken only while the task's project dispatcher is
14081
+ * in shadow mode; otherwise `wrong_id_kind`.
14082
+ */
14083
+ async function shadowTask(db, key, config) {
14084
+ const stored = storedKey(config, key);
13770
14085
  const task = await db.selectFrom("task").selectAll().where("key", "=", stored).executeTakeFirst();
13771
14086
  if (task === void 0) return void 0;
13772
14087
  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.");
@@ -13878,7 +14193,10 @@ async function insertSubmission(trx, input, ctx) {
13878
14193
  pr_number: pr.number
13879
14194
  }).execute();
13880
14195
  }
13881
- /** The executor's submit and return of a turn it took, and the turnless shadow submit. */
14196
+ /**
14197
+ * The executor's submit and return of a turn it took, the turnless shadow submit, and the
14198
+ * operator's column correction.
14199
+ */
13882
14200
  function createTurnMutations(deps) {
13883
14201
  const { config, prPoller, completeSince } = deps;
13884
14202
  /** Dispatches the task after the command's change and returns its fresh row. */
@@ -13977,6 +14295,39 @@ function createTurnMutations(deps) {
13977
14295
  block: blockView(block, moved)
13978
14296
  };
13979
14297
  }
14298
+ },
14299
+ move: {
14300
+ id: "task.move",
14301
+ resolveTargets: (trx, input) => taskTarget(trx, storedKey(config, input.task)),
14302
+ async run(trx, input, ctx) {
14303
+ const key = storedKey(config, input.task);
14304
+ const task = await trx.selectFrom("task").selectAll().where("key", "=", key).executeTakeFirst();
14305
+ if (task === void 0) throw new CommandError("not_found", "Check the task key.");
14306
+ if (task.membership === "archived") throw new CommandError("task_archived", "Add the task again before changing it.");
14307
+ const project = config.projects.find((entry) => entry.id === task.project);
14308
+ if (project === void 0) throw new CommandError("move_not_allowed", `Project ${task.project} is not in the config; add it before correcting its tasks.`);
14309
+ if (!project.columns.some((column) => column.id === input.column && column.enabled)) throw new CommandError("move_not_allowed", `Column ${input.column} is not enabled in project ${project.id}; pick one of ${project.columns.filter((column) => column.enabled && column.id !== "done").map((column) => column.id).join(", ")}.`);
14310
+ const pr = await taskPr(trx, task.id);
14311
+ if (pr !== null) {
14312
+ if ((await trx.selectFrom("pr_snapshot").select("state").where(sql`lower(repo) = ${pr.repo.toLowerCase()}`).where("number", "=", pr.number).executeTakeFirst())?.state === "merged") throw new CommandError("move_not_allowed", `Merged pull request ${`${pr.repo}#${String(pr.number)}`} keeps the task in Done; unlink it first with \`board unlink ${task.key} --pr https://github.com/${pr.repo}/pull/${String(pr.number)} --reason <text>\`.`);
14313
+ }
14314
+ const corrected = await correctColumn(trx, {
14315
+ taskId: task.id,
14316
+ to: input.column,
14317
+ at: new Date(ctx.at),
14318
+ actor: ctx.actor,
14319
+ reason: input.reason,
14320
+ config
14321
+ });
14322
+ const settled = await dispatched(trx, task.id, ctx.at);
14323
+ return {
14324
+ task: taskView(settled),
14325
+ from: corrected.from,
14326
+ to: input.column,
14327
+ column: shadowColumn(settled),
14328
+ settled: await moveViews(trx, task.id, { after: corrected.eventId })
14329
+ };
14330
+ }
13980
14331
  }
13981
14332
  };
13982
14333
  }
@@ -13990,7 +14341,10 @@ function createOperationRegistry(deps) {
13990
14341
  const membership = createMembershipMutations(config);
13991
14342
  const links = createLinkMutations(config);
13992
14343
  const blocks = createBlockMutations(config);
13993
- const taskQueries = createTaskQueries(config);
14344
+ const taskQueries = createTaskQueries({
14345
+ config,
14346
+ completeSince
14347
+ });
13994
14348
  const turns = createTurnMutations({
13995
14349
  config,
13996
14350
  prPoller: deps.prPoller,
@@ -14071,7 +14425,8 @@ function createOperationRegistry(deps) {
14071
14425
  "item.retry": items.retry,
14072
14426
  "item.close": items.close,
14073
14427
  "task.submit": turns.submit,
14074
- "task.return": turns.return
14428
+ "task.return": turns.return,
14429
+ "task.move": turns.move
14075
14430
  };
14076
14431
  }
14077
14432
  //#endregion
@@ -15013,6 +15368,40 @@ function quote(text) {
15013
15368
  }]
15014
15369
  };
15015
15370
  }
15371
+ /** Failed and waiting conditions lead a column's line; unchecked and met follow. */
15372
+ const STATE_ORDER = {
15373
+ failed: 0,
15374
+ waiting: 0,
15375
+ unchecked: 1,
15376
+ met: 2
15377
+ };
15378
+ /**
15379
+ * The why reply: the column and holds, every condition of each enabled column whose own gate
15380
+ * fails, the enabled columns whose gate passes, the waiver, the open turn, the open blocks and the
15381
+ * last moves. Agent and operator text is quoted.
15382
+ */
15383
+ function whyLines(key, why, blocks) {
15384
+ const mode = why.dispatcher === null ? " (project not configured)" : why.dispatcher === "shadow" ? " (shadow)" : "";
15385
+ const here = why.gates.find((gate) => gate.column === why.column);
15386
+ const passing = why.gates.filter((gate) => gate.enabled && gate.ok).map((gate) => gate.column);
15387
+ const turn = why.turn;
15388
+ return [
15389
+ line(`Task ${key} is in ${why.column}${mode}.`),
15390
+ ...why.holds.length === 0 ? [] : [line(`Held: ${why.holds.join(", ")}.`)],
15391
+ ...why.gates.filter((gate) => gate.enabled && !gate.ok).map((gate) => line(`${gate.column}: ${gate.conditions.toSorted((a, b) => STATE_ORDER[a.state] - STATE_ORDER[b.state]).map((condition) => `${condition.condition} ${condition.state}${condition.reason === null ? "" : ` (${condition.reason})`}`).join(", ")}`)),
15392
+ ...passing.length === 0 ? [] : [line(`Gates passing: ${passing.join(", ")}.`)],
15393
+ ...here === void 0 ? [] : [line(here.blockedIn === null ? `The ${why.column} gate passes.` : `The ${why.column} gate is blocked at ${here.blockedIn}.`)],
15394
+ ...why.checksWaivedBy === null ? [] : [line(`Dev checks are waived by ${why.checksWaivedBy}.`)],
15395
+ line(turn === null ? "No open turn." : `Turn ${turn.id} (${turn.column}, ${turn.addressee}): ${turn.taken === null ? "not taken" : `taken by ${turn.taken.by}`}.`),
15396
+ ...blocks.filter((block) => block.state === "open").flatMap((block) => [line(`Open block ${block.id} (${block.type}):`), quote(block.reason)]),
15397
+ ...why.moves.flatMap((move) => {
15398
+ const gate = move.gate.length === 0 ? "" : `: ${move.gate.join(", ")}`;
15399
+ const text = move.reason === "returned" && move.text !== null ? ` ${move.text}` : "";
15400
+ const moved = line(`${move.at}: ${move.from} to ${move.to} (${move.reason}${text}${gate})`);
15401
+ return move.reason === "corrected" && move.text !== null ? [moved, quote(move.text)] : [moved];
15402
+ })
15403
+ ];
15404
+ }
15016
15405
  /** A compact Slack view of the same validated catalog output used by CLI and MCP. */
15017
15406
  function commandReply(id, value, input) {
15018
15407
  if (id === "status.get") {
@@ -15038,6 +15427,10 @@ function commandReply(id, value, input) {
15038
15427
  if (operation === void 0) throw new Error("task.get is missing from the catalog");
15039
15428
  const result = operation.output.parse(value);
15040
15429
  const request = operation.input.parse(input);
15430
+ if (request.why === true && result.why !== void 0) return {
15431
+ cliHint: `board ${operation.cli.command} ${request.task} --why`,
15432
+ body: whyLines(result.task.key, result.why, result.blocks)
15433
+ };
15041
15434
  return {
15042
15435
  cliHint: `board ${operation.cli.command} ${request.task}`,
15043
15436
  body: [
@@ -16116,14 +16509,18 @@ const prFields = (number, closing = false) => `id number url title updatedAt mer
16116
16509
  reviewThreads(first: 100) { nodes { isResolved } pageInfo { hasNextPage endCursor } }
16117
16510
  reviewRequests(first: 100) { nodes { ${REVIEWER_FIELDS} } pageInfo { hasNextPage endCursor } }${closing ? `\n closingIssuesReferences(first: 100) { ${CLOSING_FIELDS} }` : ""}`;
16118
16511
  const DISCOVERY_FIELDS = `nodes { number updatedAt author { login } state } pageInfo { hasNextPage endCursor }`;
16119
- function aliases(numbers, closing = false) {
16120
- return numbers.map((number, i) => `pr${String(i)}: repository(owner: $owner, name: $repo) { pullRequest(number: ${String(number)}) { ${prFields(number, closing)} } }`).join("\n");
16512
+ const INDEX_FIELDS = `number updatedAt state isDraft mergeable mergeStateStatus headRefOid statusCheckRollup { state contexts(first: 100) { totalCount nodes { ... on CheckRun { __typename name status conclusion completedAt } ... on StatusContext { __typename context state } } } } reviews(first: 100) { totalCount nodes { id state } } reviewThreads(first: 100) { totalCount nodes { isResolved } } reviewRequests(first: 100) { totalCount nodes { ${REVIEWER_FIELDS} } } comments(last: 1) { totalCount nodes { id } }`;
16513
+ function aliases(numbers, fields) {
16514
+ return numbers.map((number, i) => `pr${String(i)}: repository(owner: $owner, name: $repo) { pullRequest(number: ${String(number)}) { ${fields(number)} } }`).join("\n");
16121
16515
  }
16122
- function initialQuery(numbers, bootstrap = false, closing = false) {
16123
- return `query PrBatch($owner: String!, $repo: String!) { rateLimit { remaining resetAt } repository(owner: $owner, name: $repo) { pullRequests(first: 100, states: [${bootstrap ? "OPEN" : "OPEN, MERGED"}], orderBy: {field: UPDATED_AT, direction: DESC}) { ${DISCOVERY_FIELDS} }${bootstrap ? " mergedBaseline: pullRequests(first: 1, states: [MERGED], orderBy: {field: UPDATED_AT, direction: DESC}) { nodes { updatedAt } }" : ""} } ${aliases(numbers, closing)} }`;
16516
+ function discoveryQuery(bootstrap = false) {
16517
+ return `query PrBatch($owner: String!, $repo: String!) { rateLimit { remaining resetAt } repository(owner: $owner, name: $repo) { pullRequests(first: 100, states: [${bootstrap ? "OPEN" : "OPEN, MERGED"}], orderBy: {field: UPDATED_AT, direction: DESC}) { ${DISCOVERY_FIELDS} }${bootstrap ? " mergedBaseline: pullRequests(first: 1, states: [MERGED], orderBy: {field: UPDATED_AT, direction: DESC}) { nodes { updatedAt } }" : ""} } }`;
16518
+ }
16519
+ function indexQuery(numbers) {
16520
+ return `query PrIndex($owner: String!, $repo: String!) { rateLimit { remaining resetAt } ${aliases(numbers, () => INDEX_FIELDS)} }`;
16124
16521
  }
16125
16522
  function detailQuery(numbers, closing = false) {
16126
- return `query PrDetails($owner: String!, $repo: String!) { rateLimit { remaining resetAt } ${aliases(numbers, closing)} }`;
16523
+ return `query PrDetails($owner: String!, $repo: String!) { rateLimit { remaining resetAt } ${aliases(numbers, (number) => prFields(number, closing))} }`;
16127
16524
  }
16128
16525
  function pageQuery(connection, bootstrap = false) {
16129
16526
  if (connection === "comments") return `query PrPage($owner: String!, $repo: String!, $number: Int!, $before: String!) { rateLimit { remaining resetAt } repository(owner: $owner, name: $repo) { pullRequest(number: $number) { comments(last: 100, before: $before) { ${COMMENT_FIELDS} } } } }`;
@@ -16588,6 +16985,75 @@ function normalizePr(repo, value, rule, feedbackComplete) {
16588
16985
  if (!parsed.success) throw new AdapterError("transient", "Malformed GitHub PR facts", { cause: parsed.error });
16589
16986
  return parsed.data;
16590
16987
  }
16988
+ const counted = (node) => z.object({
16989
+ totalCount: z.int().nonnegative(),
16990
+ nodes: z.array(node)
16991
+ });
16992
+ const indexAliasWire = z.object({ pullRequest: z.object({
16993
+ number: z.int().positive(),
16994
+ updatedAt: z.string(),
16995
+ state: z.string(),
16996
+ isDraft: z.boolean(),
16997
+ mergeable: z.string(),
16998
+ mergeStateStatus: z.string(),
16999
+ headRefOid: z.string(),
17000
+ statusCheckRollup: z.object({
17001
+ state: z.string(),
17002
+ contexts: counted(z.union([z.object({
17003
+ __typename: z.literal("CheckRun"),
17004
+ name: z.string(),
17005
+ status: z.string(),
17006
+ conclusion: z.string().nullable(),
17007
+ completedAt: z.string().nullable()
17008
+ }), z.object({
17009
+ __typename: z.literal("StatusContext"),
17010
+ context: z.string(),
17011
+ state: z.string()
17012
+ })]))
17013
+ }).nullable(),
17014
+ reviews: counted(z.object({
17015
+ id: z.string(),
17016
+ state: z.string()
17017
+ })),
17018
+ reviewThreads: counted(z.object({ isResolved: z.boolean() })),
17019
+ reviewRequests: counted(z.object({
17020
+ requestedReviewer: z.object({
17021
+ __typename: z.string(),
17022
+ login: z.string().optional(),
17023
+ slug: z.string().optional()
17024
+ }).nullable(),
17025
+ asCodeOwner: z.boolean()
17026
+ })),
17027
+ comments: counted(z.object({ id: z.string() }))
17028
+ }) });
17029
+ /** Reads one index alias; a shape that does not parse means the PR is read in full. */
17030
+ function indexEntry(alias) {
17031
+ const parsed = indexAliasWire.safeParse(alias);
17032
+ if (!parsed.success) return void 0;
17033
+ const pr = parsed.data.pullRequest;
17034
+ const whole = (conn) => conn.nodes.length >= conn.totalCount;
17035
+ return {
17036
+ fingerprint: JSON.stringify(pr),
17037
+ open: pr.state !== "MERGED" && pr.state !== "CLOSED",
17038
+ rollup: pr.statusCheckRollup?.state ?? null,
17039
+ green: (pr.statusCheckRollup?.contexts.nodes ?? []).every((node) => node.__typename === "StatusContext" ? node.state === "SUCCESS" : node.status === "COMPLETED" && (node.conclusion === "SUCCESS" || node.conclusion === "NEUTRAL")),
17040
+ complete: (pr.statusCheckRollup === null || whole(pr.statusCheckRollup.contexts)) && whole(pr.reviews) && whole(pr.reviewThreads) && whole(pr.reviewRequests)
17041
+ };
17042
+ }
17043
+ /**
17044
+ * The cached facts when the index shows the PR unchanged since its last full read and lists
17045
+ * every check, review, review thread and review request. An open PR is reused only with no
17046
+ * rollup or a `SUCCESS` one and every listed check green: a rollup that stays failed or pending
17047
+ * can hide a check that finished since, and a skipped check can turn required unseen.
17048
+ */
17049
+ function reusable(cached, entry, cursorKey, now) {
17050
+ if (cached === void 0 || entry === void 0) return void 0;
17051
+ if (cached.fingerprint !== entry.fingerprint || cached.cursorKey !== cursorKey) return void 0;
17052
+ if (!cached.facts.feedbackComplete || !entry.complete) return void 0;
17053
+ if (now - cached.readAt >= (entry.open ? 9e5 : 216e5)) return void 0;
17054
+ if (entry.open && (entry.rollup !== null && entry.rollup !== "SUCCESS" || !entry.green)) return;
17055
+ return cached.facts;
17056
+ }
16591
17057
  //#endregion
16592
17058
  //#region ../adapters/src/github/index.ts
16593
17059
  const MALFORMED$2 = "Malformed GitHub response";
@@ -16613,6 +17079,9 @@ const aliasWire = z.object({ pullRequest: prPagingWire.nullish() }).nullish();
16613
17079
  const pageRootWire = z.object({ pullRequest: prPagingWire.partial() });
16614
17080
  const commentsRootWire = z.object({ pullRequest: z.object({ comments: backPagingWire }) });
16615
17081
  const FEEDBACK_PAGES = 3;
17082
+ const INDEX_CHUNK = 50;
17083
+ const DETAIL_CHUNK = 10;
17084
+ const MAX_FAILED_REQUESTS = 8;
16616
17085
  function sourceId(project, repo) {
16617
17086
  return `github:${project}:${repo.toLowerCase()}`;
16618
17087
  }
@@ -16627,6 +17096,7 @@ function githubSources(config, options) {
16627
17096
  const id = sourceId(project.id, repo);
16628
17097
  const client = new GithubClient(options.token, options.now, options.fetch);
16629
17098
  const keys = projectKeyRule(project.tracker, project.link, repo);
17099
+ const cache = /* @__PURE__ */ new Map();
16630
17100
  sources.push({
16631
17101
  repo,
16632
17102
  reserveRemaining: config.github.reserveRemaining,
@@ -16640,7 +17110,9 @@ function githubSources(config, options) {
16640
17110
  keys,
16641
17111
  client,
16642
17112
  now: options.now,
16643
- ctx
17113
+ ctx,
17114
+ reserveRemaining: config.github.reserveRemaining,
17115
+ cache
16644
17116
  }),
16645
17117
  pollPr: (ref, ctx) => pollOnePr({
16646
17118
  id,
@@ -16649,7 +17121,8 @@ function githubSources(config, options) {
16649
17121
  client,
16650
17122
  now: options.now,
16651
17123
  ref,
16652
- signal: ctx.signal
17124
+ signal: ctx.signal,
17125
+ cache
16653
17126
  })
16654
17127
  }
16655
17128
  });
@@ -16666,8 +17139,11 @@ function checkAccessDenied(errors) {
16666
17139
  function requireCheckAccess(errors) {
16667
17140
  if (checkAccessDenied(errors)) throw new AdapterError("auth", "GitHub token lacks Checks read permission");
16668
17141
  }
17142
+ function unscoped(errors, roots) {
17143
+ return errors.some((error) => error.path === void 0 || !roots.includes(String(error.path[0])));
17144
+ }
16669
17145
  function rejectUnscoped(errors, roots) {
16670
- if (errors.some((error) => error.path === void 0 || !roots.includes(String(error.path[0])))) throw new AdapterError("transient", "Unscoped GitHub GraphQL error");
17146
+ if (unscoped(errors, roots)) throw new AdapterError("transient", "Unscoped GitHub GraphQL error");
16671
17147
  }
16672
17148
  function status(error) {
16673
17149
  return error.type === "NOT_FOUND" ? "not_found" : "no_access";
@@ -16826,7 +17302,6 @@ function malformed(acc, error, ref) {
16826
17302
  });
16827
17303
  acc.parseFailedRefs += 1;
16828
17304
  }
16829
- return false;
16830
17305
  }
16831
17306
  async function processPr(scope, acc, number, alias, data, scopedErrors, ref) {
16832
17307
  const errors = withoutDeniedReferences(scopedErrors);
@@ -16839,10 +17314,13 @@ async function processPr(scope, acc, number, alias, data, scopedErrors, ref) {
16839
17314
  ref,
16840
17315
  status: direct ? status(error) : "no_access"
16841
17316
  });
16842
- return false;
17317
+ return;
16843
17318
  }
16844
17319
  const root = content(() => parseWire(aliasWire, data[alias], MALFORMED$2, ["data", alias]));
16845
- if (root instanceof AdapterError) return malformed(acc, root, ref);
17320
+ if (root instanceof AdapterError) {
17321
+ malformed(acc, root, ref);
17322
+ return;
17323
+ }
16846
17324
  const wire = root?.pullRequest;
16847
17325
  if (wire === null || wire === void 0) {
16848
17326
  if (ref) acc.entities.push({
@@ -16850,7 +17328,7 @@ async function processPr(scope, acc, number, alias, data, scopedErrors, ref) {
16850
17328
  status: "not_found"
16851
17329
  });
16852
17330
  else acc.complete = false;
16853
- return false;
17331
+ return;
16854
17332
  }
16855
17333
  const report = (next) => {
16856
17334
  acc.budget = next;
@@ -16862,10 +17340,13 @@ async function processPr(scope, acc, number, alias, data, scopedErrors, ref) {
16862
17340
  ref,
16863
17341
  status: "no_access"
16864
17342
  });
16865
- return false;
17343
+ return;
17344
+ }
17345
+ if (full.status === "malformed") {
17346
+ malformed(acc, full.error, ref);
17347
+ return;
16866
17348
  }
16867
- if (full.status === "malformed") return malformed(acc, full.error, ref);
16868
- const cursor = scope.feedbackCursors?.find((entry) => entry.ref.number === number && entry.ref.repo.toLowerCase() === scope.repo.toLowerCase());
17349
+ const cursor = feedbackCursor(scope.feedbackCursors, scope.repo, number);
16869
17350
  const feedback = await readFeedback(scope.client, full.pr.comments, scope.owner, scope.name, number, cursor, scope.signal, report);
16870
17351
  const pr = {
16871
17352
  ...full.pr,
@@ -16875,7 +17356,10 @@ async function processPr(scope, acc, number, alias, data, scopedErrors, ref) {
16875
17356
  }
16876
17357
  };
16877
17358
  const facts = content(() => normalizePr(ref?.repo ?? scope.repo, pr, scope.keys, feedback.complete));
16878
- if (facts instanceof AdapterError) return malformed(acc, facts, ref);
17359
+ if (facts instanceof AdapterError) {
17360
+ malformed(acc, facts, ref);
17361
+ return;
17362
+ }
16879
17363
  acc.items.push({
16880
17364
  kind: "pr",
16881
17365
  facts
@@ -16884,7 +17368,10 @@ async function processPr(scope, acc, number, alias, data, scopedErrors, ref) {
16884
17368
  ref,
16885
17369
  status: "ok"
16886
17370
  });
16887
- return true;
17371
+ return facts;
17372
+ }
17373
+ function feedbackCursor(cursors, repo, number) {
17374
+ return cursors?.find((entry) => entry.ref.number === number && entry.ref.repo.toLowerCase() === repo.toLowerCase());
16888
17375
  }
16889
17376
  function closingSelected(keys) {
16890
17377
  return keys.type === "issues" && keys.sources.includes("closing");
@@ -16892,48 +17379,156 @@ function closingSelected(keys) {
16892
17379
  function rethrowLoneParseFailure(acc) {
16893
17380
  if (acc.parseError !== void 0 && acc.items.length === 0 && acc.entities.length === acc.parseFailedRefs) throw acc.parseError;
16894
17381
  }
16895
- async function pollRepository({ id, repo, login, keys, client, now, ctx }) {
16896
- const observedAt = sourceCursorSchema.parse(new Date(now()).toISOString());
17382
+ /**
17383
+ * Sends one request. A transient failure (5xx, a cut-off body, a timeout) is counted and returns
17384
+ * undefined; an abort, `throttled`, `auth`, `config` or any other error rejects the poll.
17385
+ */
17386
+ async function attempt(scope, query, variables = {}) {
17387
+ const { requests, signal } = scope;
17388
+ const aborted = () => signal.aborted;
17389
+ if (aborted()) throw new AdapterError("transient", "GitHub poll aborted");
17390
+ try {
17391
+ const response = await scope.client.query(query, {
17392
+ owner: scope.owner,
17393
+ repo: scope.name,
17394
+ ...variables
17395
+ }, signal);
17396
+ requests.succeeded += 1;
17397
+ return response;
17398
+ } catch (error) {
17399
+ if (aborted() || !(error instanceof AdapterError) || error.kind !== "transient") throw error;
17400
+ requests.failed += 1;
17401
+ requests.firstError ??= error;
17402
+ return;
17403
+ }
17404
+ }
17405
+ /**
17406
+ * Sends one chunk of aliases. A transient failure resends the chunk as two halves, depth first,
17407
+ * down to one PR; once the poll has `MAX_FAILED_REQUESTS` failures nothing more is sent.
17408
+ */
17409
+ async function sendChunk(scope, numbers, build) {
17410
+ if (scope.requests.failed >= MAX_FAILED_REQUESTS) return [{
17411
+ numbers,
17412
+ response: void 0
17413
+ }];
17414
+ const response = await attempt(scope, build(numbers));
17415
+ if (response !== void 0 || numbers.length === 1) return [{
17416
+ numbers,
17417
+ response
17418
+ }];
17419
+ const half = Math.ceil(numbers.length / 2);
17420
+ return [...await sendChunk(scope, numbers.slice(0, half), build), ...await sendChunk(scope, numbers.slice(half), build)];
17421
+ }
17422
+ function chunks(numbers, size) {
17423
+ const out = [];
17424
+ for (let offset = 0; offset < numbers.length; offset += size) out.push(numbers.slice(offset, offset + size));
17425
+ return out;
17426
+ }
17427
+ const aliasesOf = (numbers) => numbers.map((_, i) => `pr${String(i)}`);
17428
+ /** Lists the repository's PRs since the cursor; a transient failure leaves `ok` false. */
17429
+ async function readDiscovery(scope, acc, ctx, login) {
16897
17430
  const bootstrap = ctx.cursor === void 0;
16898
- const [owner, name] = repo.split("/");
16899
- if (!owner || !name) throw new AdapterError("config", "Invalid repository");
16900
- const requested = ctx.observe.prs.filter((ref) => ref.repo.toLowerCase() === repo.toLowerCase());
16901
- const byNumber = new Map(requested.map((ref) => [ref.number, ref]));
16902
- const numbers = [...byNumber.keys()];
16903
- const closing = closingSelected(keys);
16904
- const response = await client.query(initialQuery(numbers, bootstrap, closing), {
16905
- owner,
16906
- repo: name
16907
- }, ctx.signal);
16908
- const acc = accumulator(true, response.budget);
16909
- const roots = ["repository", ...numbers.map((_, i) => `pr${String(i)}`)];
16910
- rejectUnscoped(response.errors, roots);
16911
- let discoveryOk = scoped(response.errors, "repository").length === 0;
16912
- const first = discoveryOk ? parseWire(discoveryRootWire, response.data.repository, MALFORMED$2, ["data", "repository"]).pullRequests : void 0;
17431
+ const response = await attempt(scope, discoveryQuery(bootstrap));
17432
+ if (response === void 0) return {
17433
+ ok: false,
17434
+ found: discover([], ctx.cursor, login),
17435
+ bootstrapCursor: void 0
17436
+ };
17437
+ acc.budget = response.budget;
17438
+ rejectUnscoped(response.errors, ["repository"]);
17439
+ let ok = scoped(response.errors, "repository").length === 0;
17440
+ const first = ok ? parseWire(discoveryRootWire, response.data.repository, MALFORMED$2, ["data", "repository"]).pullRequests : void 0;
16913
17441
  const nodes = first === void 0 ? [] : [...first.nodes];
16914
17442
  let cursor = first === void 0 || pastCursor(nodes, ctx.cursor) ? void 0 : nextPage(first);
16915
17443
  const seenPages = /* @__PURE__ */ new Set();
16916
- while (cursor !== void 0 && discoveryOk) {
17444
+ while (cursor !== void 0 && ok) {
16917
17445
  if (seenPages.has(cursor)) throw new AdapterError("transient", "Malformed GitHub pagination");
16918
17446
  seenPages.add(cursor);
16919
- const page = await client.query(pageQuery("pullRequests", bootstrap), {
16920
- owner,
16921
- repo: name,
16922
- after: cursor
16923
- }, ctx.signal);
17447
+ const page = await attempt(scope, pageQuery("pullRequests", bootstrap), { after: cursor });
17448
+ if (page === void 0) {
17449
+ ok = false;
17450
+ break;
17451
+ }
16924
17452
  acc.budget = page.budget;
16925
17453
  rejectUnscoped(page.errors, ["repository"]);
16926
17454
  if (page.errors.length > 0) {
16927
- discoveryOk = false;
17455
+ ok = false;
16928
17456
  break;
16929
17457
  }
16930
17458
  const connection = parseWire(discoveryRootWire, page.data.repository, MALFORMED$2, ["data", "repository"]).pullRequests;
16931
17459
  nodes.push(...connection.nodes);
16932
17460
  cursor = pastCursor(connection.nodes, ctx.cursor) ? void 0 : nextPage(connection);
16933
17461
  }
16934
- if (!discoveryOk) acc.complete = false;
16935
17462
  const found = discover(nodes, ctx.cursor, login);
16936
- const bootstrapCursor = bootstrap && discoveryOk ? latestUpdatedAt(parseWire(baselineRootWire, response.data.repository, MALFORMED$2, ["data", "repository"]).mergedBaseline.nodes, found.cursor) ?? sourceCursorSchema.parse("1970-01-01T00:00:00.000Z") : void 0;
17463
+ const bootstrapCursor = bootstrap && ok ? latestUpdatedAt(parseWire(baselineRootWire, response.data.repository, MALFORMED$2, ["data", "repository"]).mergedBaseline.nodes, found.cursor) ?? sourceCursorSchema.parse("1970-01-01T00:00:00.000Z") : void 0;
17464
+ return {
17465
+ ok,
17466
+ found,
17467
+ bootstrapCursor
17468
+ };
17469
+ }
17470
+ /** Reads the light index of `numbers`; a PR left out of the map is read in full. */
17471
+ async function readIndex(scope, acc, numbers) {
17472
+ const entries = /* @__PURE__ */ new Map();
17473
+ for (const chunk of chunks(numbers, INDEX_CHUNK)) for (const { numbers: sent, response } of await sendChunk(scope, chunk, indexQuery)) {
17474
+ if (response === void 0) continue;
17475
+ acc.budget = response.budget;
17476
+ if (unscoped(response.errors, aliasesOf(sent))) continue;
17477
+ for (const [i, number] of sent.entries()) {
17478
+ const alias = `pr${String(i)}`;
17479
+ if (scoped(response.errors, alias).length > 0) continue;
17480
+ const entry = indexEntry(response.data[alias]);
17481
+ if (entry !== void 0) entries.set(number, entry);
17482
+ }
17483
+ }
17484
+ return entries;
17485
+ }
17486
+ async function pollRepository({ id, repo, login, keys, client, now, ctx, reserveRemaining, cache }) {
17487
+ const observedAt = sourceCursorSchema.parse(new Date(now()).toISOString());
17488
+ const bootstrap = ctx.cursor === void 0;
17489
+ const [owner, name] = repo.split("/");
17490
+ if (!owner || !name) throw new AdapterError("config", "Invalid repository");
17491
+ const requested = ctx.observe.prs.filter((ref) => ref.repo.toLowerCase() === repo.toLowerCase());
17492
+ const byNumber = new Map(requested.map((ref) => [ref.number, ref]));
17493
+ const numbers = [...byNumber.keys()];
17494
+ const closing = closingSelected(keys);
17495
+ for (const number of cache.keys()) if (!byNumber.has(number)) cache.delete(number);
17496
+ const acc = accumulator(true);
17497
+ const requests = {
17498
+ failed: 0,
17499
+ succeeded: 0,
17500
+ firstError: void 0
17501
+ };
17502
+ const request = {
17503
+ client,
17504
+ owner,
17505
+ name,
17506
+ signal: ctx.signal,
17507
+ requests
17508
+ };
17509
+ const discovery = await readDiscovery(request, acc, ctx, login);
17510
+ if (!discovery.ok) acc.complete = false;
17511
+ const { found } = discovery;
17512
+ const entries = await readIndex(request, acc, numbers);
17513
+ const cursorKey = (number) => JSON.stringify(feedbackCursor(ctx.feedbackCursors, repo, number) ?? "none");
17514
+ const changed = [];
17515
+ for (const number of numbers) {
17516
+ const facts = reusable(cache.get(number), entries.get(number), cursorKey(number), now());
17517
+ const ref = byNumber.get(number);
17518
+ if (facts !== void 0 && ref !== void 0) {
17519
+ acc.items.push({
17520
+ kind: "pr",
17521
+ facts
17522
+ });
17523
+ acc.entities.push({
17524
+ ref,
17525
+ status: "ok"
17526
+ });
17527
+ continue;
17528
+ }
17529
+ cache.delete(number);
17530
+ changed.push(number);
17531
+ }
16937
17532
  const scope = {
16938
17533
  client,
16939
17534
  repo,
@@ -16944,42 +17539,69 @@ async function pollRepository({ id, repo, login, keys, client, now, ctx }) {
16944
17539
  ...ctx.feedbackCursors === void 0 ? {} : { feedbackCursors: ctx.feedbackCursors }
16945
17540
  };
16946
17541
  let discoveredOk = true;
16947
- for (const [i, number] of numbers.entries()) {
16948
- const alias = `pr${String(i)}`;
16949
- const errors = scoped(response.errors, alias);
16950
- if (!await processPr(scope, acc, number, alias, response.data, errors, byNumber.get(number)) && found.numbers.includes(number)) discoveredOk = false;
16951
- }
17542
+ const unread = (chunk) => {
17543
+ acc.complete = false;
17544
+ for (const number of chunk) {
17545
+ const ref = byNumber.get(number);
17546
+ if (ref) acc.entities.push({
17547
+ ref,
17548
+ status: "no_access"
17549
+ });
17550
+ if (found.numbers.includes(number)) discoveredOk = false;
17551
+ }
17552
+ };
16952
17553
  const discovered = found.numbers.filter((number) => !byNumber.has(number));
16953
- for (let offset = 0; offset < discovered.length; offset += 50) {
16954
- const chunk = discovered.slice(offset, offset + 50);
16955
- const detail = await client.query(detailQuery(chunk, closing), {
16956
- owner,
16957
- repo: name
16958
- }, ctx.signal);
16959
- acc.budget = detail.budget;
16960
- rejectUnscoped(detail.errors, chunk.map((_, i) => `pr${String(i)}`));
16961
- for (const [i, number] of chunk.entries()) {
16962
- const alias = `pr${String(i)}`;
16963
- if (!await processPr(scope, acc, number, alias, detail.data, scoped(detail.errors, alias))) discoveredOk = false;
17554
+ for (const chunk of [...chunks(changed, DETAIL_CHUNK), ...chunks(discovered, DETAIL_CHUNK)]) {
17555
+ if (acc.budget !== void 0 && acc.budget.remaining < reserveRemaining) {
17556
+ unread(chunk);
17557
+ continue;
17558
+ }
17559
+ const segments = await sendChunk(request, chunk, (sent) => detailQuery(sent, closing));
17560
+ for (const { response } of segments) if (response !== void 0) acc.budget = response.budget;
17561
+ for (const { numbers: sent, response } of segments) {
17562
+ if (response === void 0) {
17563
+ unread(sent);
17564
+ continue;
17565
+ }
17566
+ rejectUnscoped(response.errors, aliasesOf(sent));
17567
+ for (const [i, number] of sent.entries()) {
17568
+ const alias = `pr${String(i)}`;
17569
+ const ref = byNumber.get(number);
17570
+ const errors = scoped(response.errors, alias);
17571
+ const facts = await processPr(scope, acc, number, alias, response.data, errors, ref);
17572
+ if (facts === void 0) {
17573
+ if (found.numbers.includes(number)) discoveredOk = false;
17574
+ continue;
17575
+ }
17576
+ const entry = entries.get(number);
17577
+ if (entry !== void 0) cache.set(number, {
17578
+ fingerprint: entry.fingerprint,
17579
+ facts,
17580
+ cursorKey: cursorKey(number),
17581
+ readAt: now()
17582
+ });
17583
+ }
16964
17584
  }
16965
17585
  }
16966
17586
  if (ctx.signal.aborted) throw new AdapterError("transient", "GitHub poll aborted");
17587
+ if (requests.firstError !== void 0 && requests.succeeded === 0) throw requests.firstError;
16967
17588
  rethrowLoneParseFailure(acc);
16968
- const nextCursor = bootstrap ? bootstrapCursor : found.cursor;
17589
+ const nextCursor = bootstrap ? discovery.bootstrapCursor : found.cursor;
16969
17590
  return {
16970
17591
  source: id,
16971
17592
  observedAt,
16972
17593
  complete: acc.complete,
16973
17594
  items: acc.items,
16974
17595
  entities: acc.entities,
16975
- ...discoveryOk && discoveredOk ? nextCursor === void 0 ? {} : { cursor: nextCursor } : ctx.cursor === void 0 ? {} : { cursor: ctx.cursor },
16976
- budget: acc.budget
17596
+ ...discovery.ok && discoveredOk ? nextCursor === void 0 ? {} : { cursor: nextCursor } : ctx.cursor === void 0 ? {} : { cursor: ctx.cursor },
17597
+ ...acc.budget === void 0 ? {} : { budget: acc.budget }
16977
17598
  };
16978
17599
  }
16979
- async function pollOnePr({ id, repo, keys, client, now, ref, signal }) {
17600
+ async function pollOnePr({ id, repo, keys, client, now, ref, signal, cache }) {
16980
17601
  const observedAt = new Date(now()).toISOString();
16981
17602
  const [owner, name] = repo.split("/");
16982
17603
  if (!owner || !name) throw new AdapterError("config", "Invalid repository");
17604
+ cache.delete(ref.number);
16983
17605
  const response = await client.query(detailQuery([ref.number], closingSelected(keys)), {
16984
17606
  owner,
16985
17607
  repo: name
@@ -17002,7 +17624,7 @@ async function pollOnePr({ id, repo, keys, client, now, ref, signal }) {
17002
17624
  complete: false,
17003
17625
  items: acc.items,
17004
17626
  entities: acc.entities,
17005
- budget: acc.budget
17627
+ ...acc.budget === void 0 ? {} : { budget: acc.budget }
17006
17628
  };
17007
17629
  }
17008
17630
  //#endregion
@@ -19048,9 +19670,13 @@ function parseCommand(text, commandName) {
19048
19670
  input: {}
19049
19671
  };
19050
19672
  for (const { operation, usage: form } of descriptors(commandName)) {
19051
- const pattern = form.slice(commandName.length).trim().split(/\s+/);
19052
- if (pattern.length !== parts.length) continue;
19673
+ const pieces = form.slice(commandName.length).trim().split(/\s+/);
19674
+ const optional = /^\[(\w+)\]$/.exec(pieces.at(-1) ?? "")?.[1];
19675
+ const pattern = optional === void 0 ? pieces : pieces.slice(0, -1);
19676
+ const flagged = optional !== void 0 && parts.length === pattern.length + 1;
19677
+ if (flagged ? parts.at(-1) !== optional : pattern.length !== parts.length) continue;
19053
19678
  const input = {};
19679
+ if (flagged) input[optional] = true;
19054
19680
  if (!pattern.every((piece, index) => {
19055
19681
  const value = parts[index];
19056
19682
  if (value === void 0) return false;