spur-board 0.43.0 → 0.44.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 { $ 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";
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,
@@ -9960,7 +10041,7 @@ function noRecipientEnd(n) {
9960
10041
  }
9961
10042
  /** A ring never carries comment or reason text: only where to look. */
9962
10043
  async function ringText(trx, n, task, ring) {
9963
- const suffix = `(N${String(n.id)}-${String(ring)})`;
10044
+ const suffix = ringMarker(n.id, ring);
9964
10045
  if (n.kind === "turn") return `${task.key} turn T${String(n.turn_id)}: check board inbox ${suffix}`;
9965
10046
  if (n.kind === "turn_reminder") return `${task.key} turn T${String(n.turn_id)} is still open: check board inbox ${suffix}`;
9966
10047
  const blockId = noticeBlockId(n);
@@ -9974,7 +10055,8 @@ function dueNotifications(db, at) {
9974
10055
  }
9975
10056
  /**
9976
10057
  * Reconciles due notifications in their own transaction. With none due it opens no transaction;
9977
- * a due notification waiting on a working recipient or an unsent ring still opens one.
10058
+ * a due notification waiting on a working recipient, an unsent ring or a ring still in the
10059
+ * recipient's Spur queue still opens one.
9978
10060
  */
9979
10061
  async function reconcileDueDoorbells(store, config, at) {
9980
10062
  if (await dueNotifications(store.db, at).select("notification.id").executeTakeFirst() === void 0) return;
@@ -10031,6 +10113,17 @@ async function reconcileDoorbells(trx, at, config) {
10031
10113
  });
10032
10114
  continue;
10033
10115
  }
10116
+ if (rings > 0 && earlierRingQueued(session, n.id, rings) && !await spurBlind$1(trx)) {
10117
+ const pauses = ringPauses(config);
10118
+ const deadline = Date.parse(n.next_at) + pauses.slice(rings).reduce((sum, pause) => sum + pause, 0);
10119
+ if (at.getTime() >= deadline) await endNotification(trx, n, task, {
10120
+ session: session.id,
10121
+ reason: UNANSWERED,
10122
+ at,
10123
+ config
10124
+ });
10125
+ continue;
10126
+ }
10034
10127
  const raised = await trx.selectFrom("operator_item").select((eb) => eb.fn.max("raise_no").as("series")).where("item_key", "=", exhaustedItemKey(n)).executeTakeFirst();
10035
10128
  const archived = await trx.selectFrom("event").select((eb) => eb.fn.countAll().as("count")).where("task_id", "=", n.task_id).where("kind", "=", "task_archived").executeTakeFirst();
10036
10129
  const killed = keepsRings ? await trx.selectFrom("outbox").select((eb) => eb.fn.countAll().as("count")).where("kind", "=", "doorbell").where("state", "=", "dead").where(sql`json_extract(payload, '$.notificationId')`, "=", n.id).executeTakeFirst() : void 0;
@@ -10049,15 +10142,33 @@ async function reconcileDoorbells(trx, at, config) {
10049
10142
  await trx.updateTable("notification").set({ last_outbox_id: outboxId }).where("id", "=", n.id).execute();
10050
10143
  }
10051
10144
  }
10052
- /** Count one confirmed Spur send, regardless of transport attempts for its outbox row. */
10053
- async function recordRingDelivery(trx, notificationId, ring, session, at, config) {
10054
- const n = await trx.selectFrom("notification").selectAll().where("id", "=", notificationId).executeTakeFirst();
10055
- if (n === void 0 || n.acked_at !== null && n.kind !== "turn_reminder" || n.recipient_session !== session || n.rings >= ring) return;
10056
- const pauses = [
10145
+ /** The pause after each delivered ring of a series: before ring 2, before ring 3, then the end. */
10146
+ function ringPauses(config) {
10147
+ return [
10057
10148
  config.doorbells.firstRetryMs,
10058
10149
  config.doorbells.secondRetryMs,
10059
10150
  config.doorbells.unansweredAfterMs
10060
10151
  ];
10152
+ }
10153
+ /**
10154
+ * Whether the session's facts list a ring of this series, up to `rings`, still in its Spur queue.
10155
+ * A detail that does not parse, or one without a queue, holds nothing.
10156
+ */
10157
+ function earlierRingQueued(session, notificationId, rings) {
10158
+ let detail;
10159
+ try {
10160
+ detail = JSON.parse(session.detail);
10161
+ } catch {
10162
+ return false;
10163
+ }
10164
+ const fact = sessionFactsSchema.safeParse(detail);
10165
+ return fact.success && (fact.data.queuedRings ?? []).some((queued) => queued.notification === notificationId && queued.ring <= rings);
10166
+ }
10167
+ /** Count one confirmed Spur send, regardless of transport attempts for its outbox row. */
10168
+ async function recordRingDelivery(trx, notificationId, ring, session, at, config) {
10169
+ const n = await trx.selectFrom("notification").selectAll().where("id", "=", notificationId).executeTakeFirst();
10170
+ if (n === void 0 || n.acked_at !== null && n.kind !== "turn_reminder" || n.recipient_session !== session || n.rings >= ring) return;
10171
+ const pauses = ringPauses(config);
10061
10172
  await trx.updateTable("notification").set({
10062
10173
  rings: ring,
10063
10174
  next_at: new Date(at.getTime() + (pauses[ring - 1] ?? 0)).toISOString(),
@@ -10069,6 +10180,11 @@ async function recordRingDelivery(trx, notificationId, ring, session, at, config
10069
10180
  attempt: ring
10070
10181
  }, at);
10071
10182
  }
10183
+ /** True while the Spur source is blind: its stored session facts may no longer hold. */
10184
+ async function spurBlind$1(trx) {
10185
+ const state = await trx.selectFrom("source_state").select("blind_reason").where("source", "=", "spur").executeTakeFirst();
10186
+ return state !== void 0 && state.blind_reason !== null;
10187
+ }
10072
10188
  /** Confirm that a queued ring still belongs to a live, idle, unread recipient. */
10073
10189
  async function ringStillCurrent(trx, notificationId, sessionId, config) {
10074
10190
  const n = await trx.selectFrom("notification").selectAll().where("id", "=", notificationId).executeTakeFirst();
@@ -10362,6 +10478,8 @@ async function ringDue(trx, notificationId, config, at) {
10362
10478
  const quiet = (await quietTurns(trx)).find((entry) => entry.reminder?.id === notificationId);
10363
10479
  return quiet !== void 0 && !quiet.ended && quiet.quietSince !== null && at.getTime() >= Date.parse(quiet.quietSince) + stuckTurnAfterMs(config);
10364
10480
  }
10481
+ /** Close reasons of a turn whose untaken feedback goes back to a later turn. */
10482
+ const recalled = /* @__PURE__ */ new Set(["corrected", "rerouted"]);
10365
10483
  /** Whether `left` is newer than `right` by `postedAt` instant, then by id. Compared, not subtracted. */
10366
10484
  function isNewer(left, right) {
10367
10485
  const a = Date.parse(left.postedAt);
@@ -10369,26 +10487,21 @@ function isNewer(left, right) {
10369
10487
  return a !== b ? a > b : left.id > right.id;
10370
10488
  }
10371
10489
  /**
10372
- * Per requested PR, the newest feedback any turn of its linked tasks handed over, acked or not,
10373
- * 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.
10374
10495
  */
10375
- async function turnFeedbackCursors(db, prs) {
10496
+ async function turnFeedbackCursors(db, prs, count) {
10376
10497
  if (prs.length === 0) return [];
10377
- const rows = await db.selectFrom("turn").innerJoin("link", "link.task_id", "turn.task_id").select([
10378
- "link.repo",
10379
- "link.number",
10380
- "turn.handed"
10381
- ]).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);
10382
10499
  const cursors = [];
10383
10500
  for (const ref of prs) {
10384
- const repo = ref.repo.toLowerCase();
10385
10501
  let best;
10386
10502
  for (const row of rows) {
10387
- if (row.repo?.toLowerCase() !== repo || row.number !== ref.number) continue;
10388
- for (const entry of turnHanded(row)) {
10389
- if (entry.repo.toLowerCase() !== repo || entry.number !== ref.number) continue;
10390
- if (best === void 0 || isNewer(entry, best)) best = entry;
10391
- }
10503
+ if (count === "handled" && isRecalled(row)) continue;
10504
+ for (const entry of handedOn(row, ref)) if (best === void 0 || isNewer(entry, best)) best = entry;
10392
10505
  }
10393
10506
  if (best !== void 0) cursors.push({
10394
10507
  ref,
@@ -10398,6 +10511,43 @@ async function turnFeedbackCursors(db, prs) {
10398
10511
  }
10399
10512
  return cursors;
10400
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
+ }
10401
10551
  //#endregion
10402
10552
  //#region ../core/src/app/blocks.ts
10403
10553
  const idNumber = (id) => Number(id.slice(1));
@@ -12252,230 +12402,6 @@ async function getStatus(deps, options = {}) {
12252
12402
  };
12253
12403
  }
12254
12404
  //#endregion
12255
- //#region ../core/src/app/task-queries.ts
12256
- const actorRefSchema = z.strictObject({
12257
- project: z.string().min(1),
12258
- session: z.string().min(1)
12259
- });
12260
- const EVENT_SUMMARIES = {
12261
- head_moved: "Pull request head moved",
12262
- pr_facts_changed: "Pull request facts changed",
12263
- checks_changed: "Checks changed",
12264
- review_submitted: "Review submitted",
12265
- mergeable_changed: "Mergeability changed",
12266
- pr_state_changed: "Pull request state changed",
12267
- ticket_status_changed: "Ticket status changed",
12268
- ticket_facts_changed: "Ticket facts changed",
12269
- session_state_changed: "Session state changed",
12270
- session_facts_changed: "Session facts changed",
12271
- spur_unknown_state: "Unknown session state observed",
12272
- link_added: "Link added",
12273
- link_removed: "Link removed",
12274
- task_added: "Task added",
12275
- task_archived: "Task archived",
12276
- task_submitted: "Turn submitted",
12277
- task_moved: "Task moved",
12278
- task_shadow_moved: "Shadow move",
12279
- dispatcher_mode_changed: "Dispatcher mode changed",
12280
- block_opened: "Block opened",
12281
- block_escalated: "Block escalated",
12282
- block_unblocked: "Block unblocked",
12283
- comment_added: "Comment added",
12284
- comment_edited: "Comment edited",
12285
- comment_deleted: "Comment deleted",
12286
- comment_acked: "Comment acknowledged",
12287
- doorbell_rung: "Doorbell rung",
12288
- doorbell_read: "Doorbell read",
12289
- doorbell_undelivered: "Doorbell delivery exhausted",
12290
- inbound_failed: "Inbound message failed",
12291
- inbound_skipped: "Inbound message skipped",
12292
- from_you_raised: "Operator item raised",
12293
- from_you_cleared: "Operator item cleared",
12294
- flag_raised: "Flag raised",
12295
- flag_cleared: "Flag cleared",
12296
- operation_denied: "Operation denied",
12297
- token_requested: "Token requested",
12298
- token_approved: "Token approved",
12299
- token_denied: "Token denied",
12300
- token_expired: "Token expired",
12301
- token_revoked: "Token revoked"
12302
- };
12303
- function linkSummary(kind, payloadText) {
12304
- if (kind !== "link_added" && kind !== "link_removed") return null;
12305
- try {
12306
- const payload = eventPayloadSchemas[kind].safeParse(JSON.parse(payloadText));
12307
- if (!payload.success) return null;
12308
- const target = payload.data.entity === "pr" ? `${payload.data.repo}#${String(payload.data.pr)}` : payload.data.entity === "session" ? payload.data.session : payload.data.ticket;
12309
- return `${kind === "link_added" ? "Link added" : "Link removed"}: ${payload.data.entity} ${target}${payload.data.reason === void 0 ? "" : ` — ${payload.data.reason}`}`;
12310
- } catch {
12311
- return null;
12312
- }
12313
- }
12314
- function projectTarget(project) {
12315
- return {
12316
- kind: "found",
12317
- value: {
12318
- project,
12319
- task: null,
12320
- block: null,
12321
- workers: []
12322
- }
12323
- };
12324
- }
12325
- function visibleProjects(config, actor) {
12326
- return new Set(config.projects.filter((project) => authorize([{ grant: "operator" }, { grant: "project-agent" }], actor, {
12327
- config,
12328
- target: projectTarget(project.id)
12329
- }).status === "allowed").map((project) => project.id));
12330
- }
12331
- function projectTargets(config, project, actor) {
12332
- if (project !== void 0) return config.projects.some((entry) => entry.id === project) ? [projectTarget(project)] : [{ kind: "missing" }];
12333
- const visible = visibleProjects(config, actor);
12334
- const projects = config.projects.filter((entry) => visible.has(entry.id));
12335
- return projects.length === 0 ? [{ kind: "missing" }] : projects.map((entry) => projectTarget(entry.id));
12336
- }
12337
- async function taskByKey(trx, key) {
12338
- const task = await trx.selectFrom("task").selectAll().where("key", "=", key).executeTakeFirst();
12339
- if (task === void 0) throw new CommandError("not_found", "Check the task key.");
12340
- return task;
12341
- }
12342
- function createTaskQueries(config) {
12343
- const taskKey = (key) => {
12344
- const parsed = parseRef$1(key, "task");
12345
- return parsed.ok && parsed.value.kind === "task" && parsed.value.form === "github-short" ? canonicalKey(config, key).key : key;
12346
- };
12347
- const get = {
12348
- id: "task.get",
12349
- resolveTargets: (trx, input) => taskTarget(trx, taskKey(input.task)),
12350
- async run(trx, input) {
12351
- const task = await taskByKey(trx, taskKey(input.task));
12352
- const [blocks, comments, links] = await Promise.all([
12353
- trx.selectFrom("block").selectAll().where("task_id", "=", task.id).orderBy("id").execute(),
12354
- trx.selectFrom("comment").selectAll().where("task_id", "=", task.id).orderBy("id").execute(),
12355
- trx.selectFrom("link").selectAll().where("task_id", "=", task.id).where("banned", "=", 0).orderBy("id").execute()
12356
- ]);
12357
- return {
12358
- task: taskView(task),
12359
- links: links.map(linkView),
12360
- blocks: blocks.map((block) => blockView(block, task)),
12361
- comments: comments.map((comment) => commentView(comment, task))
12362
- };
12363
- }
12364
- };
12365
- const history = {
12366
- id: "task.history",
12367
- resolveTargets: (trx, input) => taskTarget(trx, taskKey(input.task)),
12368
- async run(trx, input) {
12369
- const task = await taskByKey(trx, taskKey(input.task));
12370
- const events = (await trx.selectFrom("event").selectAll().where("task_id", "=", task.id).orderBy("id").execute()).flatMap((row) => {
12371
- const kind = EVENT_KINDS.find((candidate) => candidate === row.kind);
12372
- if (kind === void 0) return [];
12373
- const actorRef = row.actor_ref === null ? void 0 : parseJson(actorRefSchema, row.actor_ref);
12374
- return [{
12375
- at: row.at,
12376
- kind,
12377
- actor: encodeActorId({
12378
- actor: row.actor,
12379
- actorRef
12380
- }),
12381
- summary: linkSummary(kind, row.payload) ?? EVENT_SUMMARIES[kind]
12382
- }];
12383
- });
12384
- return {
12385
- task: taskView(task),
12386
- events
12387
- };
12388
- }
12389
- };
12390
- /**
12391
- * Unclosed agent turns the caller may take or has taken: an untaken one addressed to it, one it
12392
- * took, and a taken orchestrator turn it may take over. At most one per task.
12393
- */
12394
- async function inboxTurns(trx, projects, actor) {
12395
- if (parseActorId(actor)?.actor !== "agent" || projects.size === 0) return [];
12396
- 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();
12397
- const turns = [];
12398
- for (const turn of rows) {
12399
- if (turn.acked_by !== actor) {
12400
- const notice = await turnNotification(trx, turn.id);
12401
- const mayTake = turn.acked_at === null ? notice?.acked_at === null : turn.role.startsWith("orchestrator:");
12402
- if (notice === void 0 || !mayTake || !await notificationAddressedTo(trx, notice, actor, config)) continue;
12403
- }
12404
- turns.push({
12405
- id: `T${String(turn.id)}`,
12406
- task: turn.key,
12407
- column: turn.column,
12408
- addressee: turn.role,
12409
- reason: turn.reason,
12410
- handed: turnHanded(turn),
12411
- head: turn.head_sha,
12412
- at: turn.created_at,
12413
- taken: turn.acked_by === null || turn.acked_at === null ? null : {
12414
- by: turn.acked_by,
12415
- at: turn.acked_at
12416
- }
12417
- });
12418
- }
12419
- return turns;
12420
- }
12421
- return {
12422
- get,
12423
- history,
12424
- inbox: {
12425
- id: "inbox.get",
12426
- resolveTargets(_trx, input, actor) {
12427
- return Promise.resolve(projectTargets(config, input.project, actor));
12428
- },
12429
- async run(trx, input, actor) {
12430
- const projects = input.project === void 0 ? visibleProjects(config, actor) : /* @__PURE__ */ new Set([input.project]);
12431
- const notices = await trx.selectFrom("notification").selectAll().where("kind", "=", "answer").where("acked_at", "is", null).orderBy("id", "desc").execute();
12432
- const comments = [];
12433
- const seen = /* @__PURE__ */ new Set();
12434
- for (const notice of notices) {
12435
- if (notice.comment_id === null || seen.has(notice.comment_id)) continue;
12436
- const task = await trx.selectFrom("task").selectAll().where("id", "=", notice.task_id).executeTakeFirst();
12437
- if (task === void 0 || !projects.has(task.project)) continue;
12438
- seen.add(notice.comment_id);
12439
- if (!await notificationAddressedTo(trx, notice, actor, config)) continue;
12440
- const comment = await trx.selectFrom("comment").selectAll().where("id", "=", notice.comment_id).executeTakeFirst();
12441
- if (comment === void 0 || comment.acked_revision === comment.revision) continue;
12442
- comments.push(commentView(comment, task));
12443
- }
12444
- const parsedActor = parseActorId(actor);
12445
- if (parsedActor?.actor === "agent") {
12446
- 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();
12447
- const tasksById = new Map(linkedTasks.map((task) => [task.id, task]));
12448
- if (tasksById.size > 0) {
12449
- const taskComments = await trx.selectFrom("comment").selectAll().where("task_id", "in", [...tasksById.keys()]).where("block_id", "is", null).orderBy("id").execute();
12450
- for (const comment of taskComments) {
12451
- const task = tasksById.get(comment.task_id);
12452
- if (task === void 0 || comment.author === actor || comment.acked_revision === comment.revision) continue;
12453
- comments.push(commentView(comment, task));
12454
- }
12455
- }
12456
- }
12457
- comments.sort((left, right) => Number(left.id.slice(1)) - Number(right.id.slice(1)));
12458
- const rows = await trx.selectFrom("block").selectAll().where("state", "=", "open").orderBy("id").execute();
12459
- const blocks = [];
12460
- for (const block of rows) {
12461
- const task = await trx.selectFrom("task").selectAll().where("id", "=", block.task_id).executeTakeFirst();
12462
- if (task === void 0 || !projects.has(task.project)) continue;
12463
- if (authorize([{ grant: "block-addressee" }], actor, {
12464
- config,
12465
- target: await authorizationTarget(trx, task, block)
12466
- }).status !== "allowed") continue;
12467
- blocks.push(blockView(block, task));
12468
- }
12469
- return {
12470
- comments,
12471
- blocks,
12472
- turns: await inboxTurns(trx, projects, actor)
12473
- };
12474
- }
12475
- }
12476
- };
12477
- }
12478
- //#endregion
12479
12405
  //#region ../core/src/domain/gates.ts
12480
12406
  /**
12481
12407
  * The hold-only reasons: a fact is not known yet, and waiting resolves it. See `GateResult` for
@@ -12595,6 +12521,85 @@ function evaluateGate(column, facts, project) {
12595
12521
  ...marker
12596
12522
  };
12597
12523
  }
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
+ }
12598
12603
  /** A return counts toward the column's cycle limit when one of its causes counts. */
12599
12604
  const COUNTED = {
12600
12605
  executor: true,
@@ -12641,6 +12646,25 @@ function nextColumn(project, column) {
12641
12646
  function dropSubmits(marks, to) {
12642
12647
  return marks.filter((mark) => mark.kind === "mark" || indexOf$1(mark.column) < indexOf$1(to));
12643
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
+ }
12644
12668
  /**
12645
12669
  * Runs the dispatcher cascade from the task's column: each step moves the task or ends with at
12646
12670
  * most one turn for its column. A turn whose executor is the worker (a column with orchestrator
@@ -12654,7 +12678,7 @@ function dispatch(input) {
12654
12678
  };
12655
12679
  const { project, reopened, cycleHeld } = input;
12656
12680
  const workerLive = input.liveWorker && !input.spurBlind;
12657
- const workStarted = input.openPr || !reopened && workerLive;
12681
+ const started = workStarted(input);
12658
12682
  let { column, facts, turn } = input;
12659
12683
  const move = (to, reason, gate) => {
12660
12684
  moves.push({
@@ -12708,7 +12732,7 @@ function dispatch(input) {
12708
12732
  }
12709
12733
  const gate = evaluateGate(column, facts, project);
12710
12734
  if (gate.ok) {
12711
- if ((column === "todo" || column === "ready-for-dev") && !workStarted) return result(null);
12735
+ if ((column === "todo" || column === "ready-for-dev") && !started) return result(null);
12712
12736
  const next = nextColumn(project, column);
12713
12737
  if (cycleHeld || next === void 0 || next === "done") return result(null);
12714
12738
  move(next, "gate_passed");
@@ -13405,6 +13429,48 @@ async function syncModes(trx, config, at) {
13405
13429
  });
13406
13430
  }
13407
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
+ }
13408
13474
  /** A source has no fresh view while it reports blind or has had no complete poll since start. */
13409
13475
  async function blindSources(trx, complete) {
13410
13476
  const states = await trx.selectFrom("source_state").select(["source", "blind_reason"]).execute();
@@ -13429,8 +13495,10 @@ function externalApproval(pr, agentLogin) {
13429
13495
  /**
13430
13496
  * The external feedback nobody handled yet. An approval review is not a comment: an entry is one
13431
13497
  * 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.
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`).
13434
13502
  */
13435
13503
  async function unhandledFeedback(trx, task, project, pr) {
13436
13504
  const approvals = pr.reviews.filter((review) => review.state === "approved");
@@ -13441,8 +13509,13 @@ async function unhandledFeedback(trx, task, project, pr) {
13441
13509
  kind: "pr",
13442
13510
  repo: pr.repo,
13443
13511
  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));
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)));
13446
13519
  }
13447
13520
  /**
13448
13521
  * The submissions of `taskIds` that handle the external feedback posted before them on the PR
@@ -13482,7 +13555,7 @@ function handlingColumns(project) {
13482
13555
  * adapter reads back to the first comment older than that time.
13483
13556
  */
13484
13557
  async function pollFeedbackCursors(db, config, prs) {
13485
- const cursors = await turnFeedbackCursors(db, prs);
13558
+ const cursors = await turnFeedbackCursors(db, prs, "polled");
13486
13559
  if (prs.length === 0) return cursors;
13487
13560
  const links = await db.selectFrom("link").select([
13488
13561
  "task_id",
@@ -13518,7 +13591,10 @@ function handedOf(pr, entry) {
13518
13591
  postedAt: entry.postedAt
13519
13592
  };
13520
13593
  }
13521
- /** 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
+ */
13522
13598
  async function readInput(trx, task, project, mode, blind) {
13523
13599
  const link = await taskPr(trx, task.id);
13524
13600
  let pr = null;
@@ -13632,7 +13708,7 @@ async function applyOn(trx, task, read, result, ctx) {
13632
13708
  at
13633
13709
  });
13634
13710
  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))];
13711
+ const handed = [...carried, ...read.handed.filter((entry) => !carried.some((old) => sameHanded(old, entry)))];
13636
13712
  await openTurn(trx, {
13637
13713
  task: current,
13638
13714
  reason: turnReason(turn, replaced?.reason),
@@ -13690,6 +13766,273 @@ async function dispatchSource(trx, source, ctx) {
13690
13766
  await dispatchTasks(trx, (await trx.selectFrom("task").select("id").where("project", "in", projects).where("membership", "!=", "archived").execute()).map((task) => task.id), ctx);
13691
13767
  }
13692
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
13693
14036
  //#region ../core/src/app/turn-commands.ts
13694
14037
  /** How long `task.submit` waits for its on-demand PR poll; the CLI gives up at 30 s. */
13695
14038
  const SUBMIT_POLL_TIMEOUT_MS = 1e4;
@@ -13726,12 +14069,19 @@ async function turnVisitTarget(db, id) {
13726
14069
  }];
13727
14070
  }
13728
14071
  /**
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`.
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.
13731
14074
  */
13732
- async function shadowTask(db, key, config) {
14075
+ function storedKey(config, key) {
13733
14076
  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;
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);
13735
14085
  const task = await db.selectFrom("task").selectAll().where("key", "=", stored).executeTakeFirst();
13736
14086
  if (task === void 0) return void 0;
13737
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.");
@@ -13843,7 +14193,10 @@ async function insertSubmission(trx, input, ctx) {
13843
14193
  pr_number: pr.number
13844
14194
  }).execute();
13845
14195
  }
13846
- /** 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
+ */
13847
14200
  function createTurnMutations(deps) {
13848
14201
  const { config, prPoller, completeSince } = deps;
13849
14202
  /** Dispatches the task after the command's change and returns its fresh row. */
@@ -13942,6 +14295,39 @@ function createTurnMutations(deps) {
13942
14295
  block: blockView(block, moved)
13943
14296
  };
13944
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
+ }
13945
14331
  }
13946
14332
  };
13947
14333
  }
@@ -13955,7 +14341,10 @@ function createOperationRegistry(deps) {
13955
14341
  const membership = createMembershipMutations(config);
13956
14342
  const links = createLinkMutations(config);
13957
14343
  const blocks = createBlockMutations(config);
13958
- const taskQueries = createTaskQueries(config);
14344
+ const taskQueries = createTaskQueries({
14345
+ config,
14346
+ completeSince
14347
+ });
13959
14348
  const turns = createTurnMutations({
13960
14349
  config,
13961
14350
  prPoller: deps.prPoller,
@@ -14036,7 +14425,8 @@ function createOperationRegistry(deps) {
14036
14425
  "item.retry": items.retry,
14037
14426
  "item.close": items.close,
14038
14427
  "task.submit": turns.submit,
14039
- "task.return": turns.return
14428
+ "task.return": turns.return,
14429
+ "task.move": turns.move
14040
14430
  };
14041
14431
  }
14042
14432
  //#endregion
@@ -14978,6 +15368,40 @@ function quote(text) {
14978
15368
  }]
14979
15369
  };
14980
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
+ }
14981
15405
  /** A compact Slack view of the same validated catalog output used by CLI and MCP. */
14982
15406
  function commandReply(id, value, input) {
14983
15407
  if (id === "status.get") {
@@ -15003,6 +15427,10 @@ function commandReply(id, value, input) {
15003
15427
  if (operation === void 0) throw new Error("task.get is missing from the catalog");
15004
15428
  const result = operation.output.parse(value);
15005
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
+ };
15006
15434
  return {
15007
15435
  cliHint: `board ${operation.cli.command} ${request.task}`,
15008
15436
  body: [
@@ -18107,8 +18535,18 @@ const sessionWire = z.object({
18107
18535
  slots: z.object({ links: z.array(z.object({
18108
18536
  label: z.string().min(1),
18109
18537
  url: z.url()
18110
- })).optional() }).optional()
18538
+ })).optional() }).optional(),
18539
+ queuedMessages: z.object({ messages: z.array(z.string()) }).optional()
18111
18540
  });
18541
+ /** The board rings a session's queue still holds, sorted and deduped; other queued text is dropped. */
18542
+ function queuedBoardRings(wire) {
18543
+ const rings = /* @__PURE__ */ new Map();
18544
+ for (const message of wire.queuedMessages?.messages ?? []) {
18545
+ const parsed = parseRingMarker(message);
18546
+ if (parsed) rings.set(`${String(parsed.notification)}-${String(parsed.ring)}`, parsed);
18547
+ }
18548
+ return [...rings.values()].sort((a, b) => a.notification - b.notification || a.ring - b.ring);
18549
+ }
18112
18550
  /** A single Spur source. State is scoped to this adapter instance, never shared across daemons. */
18113
18551
  function createSpurAdapter(options) {
18114
18552
  const base = new URL(`${options.baseUrl.replace(/\/$/, "")}/`);
@@ -18196,6 +18634,7 @@ function createSpurAdapter(options) {
18196
18634
  if (parsed.success) pr = parsed.data;
18197
18635
  }
18198
18636
  }
18637
+ const queuedRings = queuedBoardRings(wire);
18199
18638
  return sessionFactsSchema.parse({
18200
18639
  id: wire.id,
18201
18640
  spurProject: wire.project,
@@ -18207,7 +18646,8 @@ function createSpurAdapter(options) {
18207
18646
  healthSince: state.since,
18208
18647
  lastActivityAt: wire.lastActivityAt ?? null,
18209
18648
  endedAt: endReason === null ? null : observedAt,
18210
- endReason
18649
+ endReason,
18650
+ ...queuedRings.length > 0 ? { queuedRings } : {}
18211
18651
  });
18212
18652
  }
18213
18653
  return {
@@ -19001,9 +19441,13 @@ function parseCommand(text, commandName) {
19001
19441
  input: {}
19002
19442
  };
19003
19443
  for (const { operation, usage: form } of descriptors(commandName)) {
19004
- const pattern = form.slice(commandName.length).trim().split(/\s+/);
19005
- if (pattern.length !== parts.length) continue;
19444
+ const pieces = form.slice(commandName.length).trim().split(/\s+/);
19445
+ const optional = /^\[(\w+)\]$/.exec(pieces.at(-1) ?? "")?.[1];
19446
+ const pattern = optional === void 0 ? pieces : pieces.slice(0, -1);
19447
+ const flagged = optional !== void 0 && parts.length === pattern.length + 1;
19448
+ if (flagged ? parts.at(-1) !== optional : pattern.length !== parts.length) continue;
19006
19449
  const input = {};
19450
+ if (flagged) input[optional] = true;
19007
19451
  if (!pattern.every((piece, index) => {
19008
19452
  const value = parts[index];
19009
19453
  if (value === void 0) return false;