spur-board 0.43.1 → 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 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: [
@@ -19048,9 +19441,13 @@ function parseCommand(text, commandName) {
19048
19441
  input: {}
19049
19442
  };
19050
19443
  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;
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;
19053
19449
  const input = {};
19450
+ if (flagged) input[optional] = true;
19054
19451
  if (!pattern.every((piece, index) => {
19055
19452
  const value = parts[index];
19056
19453
  if (value === void 0) return false;