spur-board 0.54.1 → 0.55.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { $ as errorEnvelopeSchema, Q as errorContextSchema, S as renderJsonError, X as ERRORS, c as tokenRequestStatusSchema, o as tokenRequestResultSchema, tt as successEnvelopeSchema } from "./chunk-C0avjvF7.mjs";
1
+ import { $ as errorContextSchema, S as renderJsonError, Z as ERRORS, c as tokenRequestStatusSchema, et as errorEnvelopeSchema, nt as successEnvelopeSchema, o as tokenRequestResultSchema } from "./chunk-DsCpUW6q.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { z } from "zod";
4
4
  import { request } from "node:http";
@@ -148,6 +148,7 @@ const TASK_HOLDS = [
148
148
  "pr_snapshot_missing",
149
149
  "github_blind",
150
150
  "spur_blind",
151
+ "ticket_unconfirmed",
151
152
  "cycle_limit",
152
153
  "work_not_started"
153
154
  ];
@@ -1182,6 +1183,7 @@ const prFactsSchema = z.strictObject({
1182
1183
  ticketKeys: z.array(taskKeySchema).describe("Ticket keys found in the head branch name and the title."),
1183
1184
  updatedAt: at$2.describe("When the pull request last changed."),
1184
1185
  mergedAt: at$2.optional().describe("When the pull request merged; absent while it is not merged and in facts stored by an earlier version."),
1186
+ closedAt: at$2.optional().describe("When the pull request closed without merge; absent while it is not closed and in facts stored by an earlier version."),
1185
1187
  feedback: z.array(feedbackSchema).optional().describe("Comments and submitted reviews on the pull request, oldest first, without their text."),
1186
1188
  feedbackComplete: z.boolean().optional().describe("Whether feedback holds every comment back to the last one handed over, or to the start of the pull request; missing reads as incomplete.")
1187
1189
  }).describe("Facts about one pull request.");
@@ -1943,6 +1945,7 @@ const taskWhySchema = z.strictObject({
1943
1945
  column: z.enum(COLUMN_IDS).describe("Column the dispatcher works from: the shadow column in shadow mode."),
1944
1946
  dispatcher: z.enum(DISPATCHER_MODES).nullable().describe("The project's dispatcher mode; null when the project is not configured."),
1945
1947
  holds: z.array(z.enum(TASK_HOLDS)).describe("What holds the dispatcher from acting on the task; empty when nothing does."),
1948
+ heldBy: z.array(blockIdSchema).min(1).optional().describe("Blocks of the open cycle-limit or course-check items holding the task; absent when none does."),
1946
1949
  gates: z.array(z.strictObject({
1947
1950
  column: z.enum(COLUMN_IDS).describe("Board column."),
1948
1951
  enabled: z.boolean().describe("Whether the column is enabled in the project."),
@@ -1978,7 +1981,8 @@ const linkViewSchema = z.strictObject({
1978
1981
  "worker",
1979
1982
  "other",
1980
1983
  "orchestrator"
1981
- ]).nullable().describe("Session role; null for a pull request or ticket.")
1984
+ ]).nullable().describe("Session role; null for a pull request or ticket."),
1985
+ state: z.enum(PR_STATES).optional().describe("Pull request state as last observed; absent for a session or ticket and for a pull request not observed yet. Only task.get sets it.")
1982
1986
  }).describe("An effective link to a task.");
1983
1987
  const detailOnly = "Present only with detail.";
1984
1988
  const count = (what) => z.int().min(0).describe(what);
@@ -3874,4 +3878,4 @@ function assertNever(value) {
3874
3878
  throw new Error(`Unexpected value: ${JSON.stringify(value)}`);
3875
3879
  }
3876
3880
  //#endregion
3877
- export { errorEnvelopeSchema as $, EVENT_KINDS as A, sessionFactsSchema as B, renderMcpError as C, interactionRefSchema as D, inboundEventSchema as E, isExternalAuthor as F, encodeActorId as G, JIRA_PROJECT_KEY as H, parseRingMarker as I, parseRef as J, errorCodeOf as K, prFactsSchema as L, REVIEW_STATES as M, SESSION_HEALTH_STATES as N, messageRefSchema as O, SESSION_STATUSES as P, errorContextSchema as Q, prRefSchema as R, renderJsonError as S, conversationRefSchema as T, REF_NUMBER as U, ticketFactsSchema as V, actorIdSchema as W, ERRORS as X, taskKeySchema as Y, err as Z, buildCatalogSnapshot as _, requestHashOf as a, DEFAULT_SLACK_COMMAND as at, turnHandedSchema as b, tokenRequestStatusSchema as c, plainHttpAllowed as ct, AdapterError as d, DISPATCHER_MODES as dt, ok as et, batchSchema as f, SLACK_BOT_SCOPES as ft, trackerSourceId as g, sourceCursorSchema as h, TOKEN_REQUEST_LIMITS as i, DEFAULT_SLACK_APP_NAME as it, eventPayloadSchemas as j, userIdSchema as k, BOARD_TICK_MS as l, requiredSecretKeys as lt, prSourceId as m, doctorReportSchema as n, DEFAULT_HTTP_PORT as nt, tokenRequestResultSchema as o, RESERVED_PROJECT as ot, entityRefSchema as p, parseActorId as q, remoteDoctorReportSchema as r, DEFAULT_LINK as rt, tokenRequestSchema as s, configSchema as st, assertNever as t, successEnvelopeSchema as tt, SYSTEMD_SERVICE_SETTINGS as u, COLUMN_IDS as ut, roleCanUseOperation as v, SPACE_IDS as w, renderHttpProblem as x, OPERATIONS as y, ringMarker as z };
3881
+ export { errorContextSchema as $, EVENT_KINDS as A, ringMarker as B, renderMcpError as C, interactionRefSchema as D, inboundEventSchema as E, SESSION_STATUSES as F, actorIdSchema as G, ticketFactsSchema as H, isExternalAuthor as I, parseActorId as J, encodeActorId as K, parseRingMarker as L, PR_STATES as M, REVIEW_STATES as N, messageRefSchema as O, SESSION_HEALTH_STATES as P, err as Q, prFactsSchema as R, renderJsonError as S, conversationRefSchema as T, JIRA_PROJECT_KEY as U, sessionFactsSchema as V, REF_NUMBER as W, taskKeySchema as X, parseRef as Y, ERRORS as Z, buildCatalogSnapshot as _, requestHashOf as a, DEFAULT_SLACK_APP_NAME as at, turnHandedSchema as b, tokenRequestStatusSchema as c, configSchema as ct, AdapterError as d, COLUMN_IDS as dt, errorEnvelopeSchema as et, batchSchema as f, DISPATCHER_MODES as ft, trackerSourceId as g, sourceCursorSchema as h, TOKEN_REQUEST_LIMITS as i, DEFAULT_LINK as it, eventPayloadSchemas as j, userIdSchema as k, BOARD_TICK_MS as l, plainHttpAllowed as lt, prSourceId as m, TASK_HOLDS as mt, doctorReportSchema as n, successEnvelopeSchema as nt, tokenRequestResultSchema as o, DEFAULT_SLACK_COMMAND as ot, entityRefSchema as p, SLACK_BOT_SCOPES as pt, errorCodeOf as q, remoteDoctorReportSchema as r, DEFAULT_HTTP_PORT as rt, tokenRequestSchema as s, RESERVED_PROJECT as st, assertNever as t, ok as tt, SYSTEMD_SERVICE_SETTINGS as u, requiredSecretKeys as ut, roleCanUseOperation as v, SPACE_IDS as w, renderHttpProblem as x, OPERATIONS as y, prRefSchema as z };
@@ -1,5 +1,5 @@
1
- import { _ as buildCatalogSnapshot, ct as plainHttpAllowed, st as configSchema, y as OPERATIONS } from "./chunk-C0avjvF7.mjs";
2
- import { o as CliError, t as fetchCatalogVersion } from "./chunk-Dd1yi1dh.mjs";
1
+ import { _ as buildCatalogSnapshot, ct as configSchema, lt as plainHttpAllowed, y as OPERATIONS } from "./chunk-DsCpUW6q.mjs";
2
+ import { o as CliError, t as fetchCatalogVersion } from "./chunk-B2jz795d.mjs";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
5
5
  import { homedir } from "node:os";
package/dist/cli.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import { W as actorIdSchema, X as ERRORS, a as requestHashOf, ft as SLACK_BOT_SCOPES, lt as requiredSecretKeys, r as remoteDoctorReportSchema, st as configSchema, tt as successEnvelopeSchema, u as SYSTEMD_SERVICE_SETTINGS, v as roleCanUseOperation, y as OPERATIONS } from "./chunk-C0avjvF7.mjs";
1
+ import { G as actorIdSchema, Z as ERRORS, a as requestHashOf, ct as configSchema, nt as successEnvelopeSchema, pt as SLACK_BOT_SCOPES, r as remoteDoctorReportSchema, u as SYSTEMD_SERVICE_SETTINGS, ut as requiredSecretKeys, v as roleCanUseOperation, y as OPERATIONS } from "./chunk-DsCpUW6q.mjs";
2
2
  import { t as apiBaseUrl } from "./chunk-DAMwWWmT.mjs";
3
- import { a as requestTokenEnrollment, c as renderCliError, i as requestSkillReload, l as escapeTerminalControls, n as fetchTokenStatus, o as CliError, r as requestOperation, s as errorExitCode } from "./chunk-Dd1yi1dh.mjs";
4
- import { a as memoryVerdictCache, c as loadClientConfig, d as resolveDaemonAddress, f as tokenInFolder, i as fileVerdictCache, l as loadEnrollmentConfig, n as cliPackageVersion, o as configFile, s as dataDirectory, t as checkCatalog, u as readConfiguredPort } from "./chunk-CaWf-PGm.mjs";
3
+ import { a as requestTokenEnrollment, c as renderCliError, i as requestSkillReload, l as escapeTerminalControls, n as fetchTokenStatus, o as CliError, r as requestOperation, s as errorExitCode } from "./chunk-B2jz795d.mjs";
4
+ import { a as memoryVerdictCache, c as loadClientConfig, d as resolveDaemonAddress, f as tokenInFolder, i as fileVerdictCache, l as loadEnrollmentConfig, n as cliPackageVersion, o as configFile, s as dataDirectory, t as checkCatalog, u as readConfiguredPort } from "./chunk-hS9wN0vI.mjs";
5
5
  import { createHash, randomBytes, randomUUID } from "node:crypto";
6
6
  import { accessSync, chmodSync, closeSync, constants, cpSync, existsSync, ftruncateSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
7
7
  import { homedir, hostname, userInfo } from "node:os";
package/dist/client.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { a as requestTokenEnrollment, i as requestSkillReload, n as fetchTokenStatus, r as requestOperation, t as fetchCatalogVersion } from "./chunk-Dd1yi1dh.mjs";
1
+ import { a as requestTokenEnrollment, i as requestSkillReload, n as fetchTokenStatus, r as requestOperation, t as fetchCatalogVersion } from "./chunk-B2jz795d.mjs";
2
2
  export { fetchCatalogVersion, fetchTokenStatus, requestOperation, requestSkillReload, requestTokenEnrollment };
package/dist/daemon.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { A as EVENT_KINDS, B as sessionFactsSchema, D as interactionRefSchema, E as inboundEventSchema, F as isExternalAuthor, G as encodeActorId, H as JIRA_PROJECT_KEY, I as parseRingMarker, J as parseRef$1, K as errorCodeOf, L as prFactsSchema, M as REVIEW_STATES, N as SESSION_HEALTH_STATES, O as messageRefSchema, P as SESSION_STATUSES, R as prRefSchema, T as conversationRefSchema, U as REF_NUMBER, V as ticketFactsSchema, W as actorIdSchema, X as ERRORS, Y as taskKeySchema, Z as err, _ as buildCatalogSnapshot, a as requestHashOf, at as DEFAULT_SLACK_COMMAND, b as turnHandedSchema, c as tokenRequestStatusSchema, ct as plainHttpAllowed, d as AdapterError, dt as DISPATCHER_MODES, et as ok, f as batchSchema, ft as SLACK_BOT_SCOPES, g as trackerSourceId, h as sourceCursorSchema, i as TOKEN_REQUEST_LIMITS, j as eventPayloadSchemas, k as userIdSchema, l as BOARD_TICK_MS, lt as requiredSecretKeys, m as prSourceId, n as doctorReportSchema, o as tokenRequestResultSchema, ot as RESERVED_PROJECT, p as entityRefSchema, q as parseActorId, rt as DEFAULT_LINK, s as tokenRequestSchema, st as configSchema, t as assertNever, tt as successEnvelopeSchema, ut as COLUMN_IDS, v as roleCanUseOperation, w as SPACE_IDS, x as renderHttpProblem, y as OPERATIONS, z as ringMarker } from "./chunk-C0avjvF7.mjs";
1
+ import { A as EVENT_KINDS, B as ringMarker, D as interactionRefSchema, E as inboundEventSchema, F as SESSION_STATUSES, G as actorIdSchema, H as ticketFactsSchema, I as isExternalAuthor, J as parseActorId, K as encodeActorId, L as parseRingMarker, M as PR_STATES, N as REVIEW_STATES, O as messageRefSchema, P as SESSION_HEALTH_STATES, Q as err, R as prFactsSchema, T as conversationRefSchema, U as JIRA_PROJECT_KEY, V as sessionFactsSchema, W as REF_NUMBER, X as taskKeySchema, Y as parseRef$1, Z as ERRORS, _ as buildCatalogSnapshot, a as requestHashOf, b as turnHandedSchema, c as tokenRequestStatusSchema, ct as configSchema, d as AdapterError, dt as COLUMN_IDS, f as batchSchema, ft as DISPATCHER_MODES, g as trackerSourceId, h as sourceCursorSchema, i as TOKEN_REQUEST_LIMITS, it as DEFAULT_LINK, j as eventPayloadSchemas, k as userIdSchema, l as BOARD_TICK_MS, lt as plainHttpAllowed, m as prSourceId, mt as TASK_HOLDS, n as doctorReportSchema, nt as successEnvelopeSchema, o as tokenRequestResultSchema, ot as DEFAULT_SLACK_COMMAND, p as entityRefSchema, pt as SLACK_BOT_SCOPES, q as errorCodeOf, s as tokenRequestSchema, st as RESERVED_PROJECT, t as assertNever, tt as ok, ut as requiredSecretKeys, v as roleCanUseOperation, w as SPACE_IDS, x as renderHttpProblem, y as OPERATIONS, z as prRefSchema } from "./chunk-DsCpUW6q.mjs";
2
2
  import { t as apiBaseUrl } from "./chunk-DAMwWWmT.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import { createHash, randomUUID } from "node:crypto";
@@ -7994,6 +7994,26 @@ function ticketDone(project, status) {
7994
7994
  return project.tracker.type === "jira" ? project.tracker.doneStatuses.includes(status) : status === "closed";
7995
7995
  }
7996
7996
  /**
7997
+ * How the ticket of a task stands after its PR merged at `mergedAt`: `done`; `open` once the
7998
+ * tracker saw it open at least one tracker interval after the merge, in the filter or fetched by
7999
+ * key for a hand-added task; else `unconfirmed`, since the close a merge triggers may not be
8000
+ * polled yet and a ticket dropped from the filter keeps a stale status.
8001
+ */
8002
+ function mergedTicket(project, config, ticket, manualInclude, mergedAt) {
8003
+ if (ticket === void 0) return "unconfirmed";
8004
+ if (ticketDone(project, ticket.status)) return "done";
8005
+ let inFilter;
8006
+ try {
8007
+ const parsed = ticketFactsSchema.safeParse(JSON.parse(ticket.detail));
8008
+ if (!parsed.success) return "unconfirmed";
8009
+ inFilter = parsed.data.inFilter;
8010
+ } catch {
8011
+ return "unconfirmed";
8012
+ }
8013
+ const { intervalMs } = project.tracker.type === "jira" ? config.adapters.jira : config.adapters.githubIssues;
8014
+ return (inFilter || manualInclude) && Date.parse(ticket.observed_at) >= Date.parse(mergedAt) + intervalMs ? "open" : "unconfirmed";
8015
+ }
8016
+ /**
7997
8017
  * Whether a PR link counts past the task's reopen floor: an open link, or a link not hidden by a
7998
8018
  * reopen. For a query over `link`. Written so a link without a marker counts: the negated form
7999
8019
  * is NULL there and would drop it.
@@ -8015,6 +8035,17 @@ async function taskPr(db, taskId) {
8015
8035
  open: link.pr_open === 1
8016
8036
  };
8017
8037
  }
8038
+ /**
8039
+ * The task's newest merged PR: the newest active unbanned link past the reopen floor whose PR is
8040
+ * seen merged. Completes a task whose follow-up PR closed unmerged after an earlier merge.
8041
+ */
8042
+ async function taskMergedPr(db, taskId) {
8043
+ const link = await db.selectFrom("link").innerJoin("pr_snapshot", (join) => join.on(sql`lower(pr_snapshot.repo) = lower(link.repo)`).onRef("pr_snapshot.number", "=", "link.number")).select(["link.repo", "link.number"]).where("link.task_id", "=", taskId).where("link.entity", "=", "pr").where("link.pr_state", "=", "active").where("link.banned", "=", 0).where("pr_snapshot.state", "=", "merged").where(pastReopenFloor).orderBy("link.id", "desc").executeTakeFirst();
8044
+ return link?.repo == null || link.number === null ? null : {
8045
+ repo: link.repo,
8046
+ number: link.number
8047
+ };
8048
+ }
8018
8049
  /** A PR snapshot's facts, or null when the detail is missing or unreadable. */
8019
8050
  function parsePr(detail) {
8020
8051
  if (detail === void 0) return null;
@@ -8902,17 +8933,23 @@ function exchangeBody(payload) {
8902
8933
  }
8903
8934
  /**
8904
8935
  * A distinct semantic ring. Transport retries reuse this row and its text. A restarted series
8905
- * (`series` > 0), a ring after the task was archived (`archives` > 0) and a ring after a move
8906
- * killed an earlier one (`moves` > 0) get their own keys, so a cancelled ring does not block its
8907
- * replacement; unsuffixed keys stay as before.
8936
+ * (`series` > 0) and a ring after the task was archived (`archives` > 0) get their own keys.
8937
+ * Every ring of a key whose earlier rows all finished (a move or archive killed them, or a
8938
+ * handover reset the series after they were delivered) takes the next handover generation
8939
+ * `:h<n>`, `n` being how many rows the key has, so a finished ring never blocks its successor.
8940
+ * A row of the key still waiting in the outbox is returned instead. Unsuffixed keys stay as
8941
+ * before.
8908
8942
  */
8909
8943
  async function enqueueDoorbell(trx, input) {
8910
8944
  const series = input.series ?? 0;
8911
8945
  const archives = input.archives ?? 0;
8912
- const moves = input.moves ?? 0;
8946
+ const base = `doorbell:${String(input.notificationId)}:${input.session}:${String(input.ring)}${series > 0 ? `:s${String(series)}` : ""}${archives > 0 ? `:a${String(archives)}` : ""}`;
8947
+ const rows = await trx.selectFrom("outbox").select(["id", "state"]).where((eb) => eb.or([eb("dedupe_key", "=", base), eb.and([eb("dedupe_key", ">", `${base}:h`), eb("dedupe_key", "<", `${base}:i`)])])).execute();
8948
+ const waiting = rows.find((row) => row.state === "pending" || row.state === "in_flight");
8949
+ if (waiting !== void 0) return waiting.id;
8913
8950
  const row = await insertOutbox(trx, {
8914
8951
  kind: "doorbell",
8915
- dedupeKey: `doorbell:${String(input.notificationId)}:${input.session}:${String(input.ring)}${series > 0 ? `:s${String(series)}` : ""}${archives > 0 ? `:a${String(archives)}` : ""}${moves > 0 ? `:m${String(moves)}` : ""}`,
8952
+ dedupeKey: rows.length > 0 ? `${base}:h${String(rows.length)}` : base,
8916
8953
  payload: {
8917
8954
  notificationId: input.notificationId,
8918
8955
  ring: input.ring,
@@ -8925,6 +8962,16 @@ async function enqueueDoorbell(trx, input) {
8925
8962
  if (row.id === null) throw new Error("Doorbell cannot be blocked by gateway scan");
8926
8963
  return row.id;
8927
8964
  }
8965
+ /**
8966
+ * Moves the doorbell rows of the worker's notifications on task `taskId`, other than `exceptId`,
8967
+ * that wait in the outbox to the front, in outbox id order, ahead of rings reconcile enqueues
8968
+ * next. A row in retry backoff (`attempts > 0`) keeps its wait.
8969
+ */
8970
+ async function promoteWorkerDoorbells(trx, taskId, at, exceptId) {
8971
+ let others = trx.selectFrom("notification").select("id").where("task_id", "=", taskId).where("role", "=", "worker");
8972
+ if (exceptId !== void 0) others = others.where("id", "!=", exceptId);
8973
+ await trx.updateTable("outbox").set({ next_at: at.toISOString() }).where("kind", "=", "doorbell").where("state", "=", "pending").where("attempts", "=", 0).where(sql`json_extract(payload, '$.notificationId')`, "in", others).execute();
8974
+ }
8928
8975
  /** The key holds no install time, so a session gets at most one reload message per version. */
8929
8976
  function skillReloadKey(version, session) {
8930
8977
  return `doorbell:skill-reload:${version}:${session}`;
@@ -9395,7 +9442,17 @@ async function raiseItem(trx, input) {
9395
9442
  return raiseItemWith(trx, input, enqueueFeedLine);
9396
9443
  }
9397
9444
  /**
9445
+ * Whether the course check `item` forwarded a note: a worker `answer` notification on its block.
9446
+ * The note's first ring then releases the held rings (`releaseAfterCourseNote`).
9447
+ */
9448
+ async function courseNoted(trx, item) {
9449
+ if (item.block_id === null) return false;
9450
+ return await trx.selectFrom("notification").select("id").where("block_id", "=", item.block_id).where("role", "=", "worker").where("kind", "=", "answer").executeTakeFirst() !== void 0;
9451
+ }
9452
+ /**
9398
9453
  * Clear an item once; the edit waits for its line and is cancelled with a stale pending line.
9454
+ * A course check cleared without a note moves the worker's held rings on its task that wait in
9455
+ * the outbox to the front, so they keep their order.
9399
9456
  * The journal names `actor`, `system` unless an actor's action cleared it. `writeEdit`, when
9400
9457
  * given, writes the line's edit instead of the resolved one.
9401
9458
  */
@@ -9403,6 +9460,7 @@ async function clearItem(trx, itemId, at, actor = "system", writeEdit) {
9403
9460
  if ((await trx.selectFrom("operator_item").selectAll().where("id", "=", itemId).executeTakeFirstOrThrow()).cleared_at !== null) return;
9404
9461
  const item = await trx.updateTable("operator_item").set({ cleared_at: at.toISOString() }).where("id", "=", itemId).returningAll().executeTakeFirstOrThrow();
9405
9462
  await journal$3(trx, item, "from_you_cleared", at, void 0, actor);
9463
+ if (item.kind === "course_check" && item.task_id !== null && !await courseNoted(trx, item)) await promoteWorkerDoorbells(trx, item.task_id, at);
9406
9464
  if (item.line_outbox_id === null) return;
9407
9465
  if (writeEdit !== void 0) {
9408
9466
  await writeEdit(item, item.line_outbox_id);
@@ -9591,6 +9649,9 @@ async function applyDoorbellPolicy(trx, event, at) {
9591
9649
  case "block_removed":
9592
9650
  await registerRemovedNotification(trx, event.block, at);
9593
9651
  return;
9652
+ case "course_note":
9653
+ await registerCourseNoteNotification(trx, event, at);
9654
+ return;
9594
9655
  case "block_closed_by_addressee":
9595
9656
  case "task_comment": return;
9596
9657
  default: assertNever(event);
@@ -9750,6 +9811,40 @@ async function registerAnswerNotification(trx, input, at) {
9750
9811
  }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
9751
9812
  }
9752
9813
  /**
9814
+ * Register the worker's ring for a course note: the curator's answer to a course check, copied to
9815
+ * the task. It names the course block, and until its first ring is delivered the worker's other
9816
+ * rings on the task stay held (`courseHold`), so the worker reads the decision first.
9817
+ */
9818
+ async function registerCourseNoteNotification(trx, input, at) {
9819
+ await trx.insertInto("notification").values({
9820
+ source_key: `course-note:${String(input.comment.id)}`,
9821
+ kind: "answer",
9822
+ task_id: input.block.task_id,
9823
+ block_id: input.block.id,
9824
+ comment_id: input.comment.id,
9825
+ revision: input.comment.revision,
9826
+ role: "worker",
9827
+ author_session: null,
9828
+ recipient_session: null,
9829
+ next_at: at.toISOString(),
9830
+ last_outbox_id: null,
9831
+ acked_at: null,
9832
+ exhausted_at: null,
9833
+ created_at: at.toISOString()
9834
+ }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
9835
+ }
9836
+ /** Course-check items of any state, as subquery rows of their block ids. */
9837
+ const courseBlocks = (eb) => eb.selectFrom("operator_item").select("operator_item.block_id").where("operator_item.kind", "=", "course_check").where("operator_item.block_id", "is not", null);
9838
+ /**
9839
+ * Whether a worker notification is held by a course check on its task. Two holds apply: while a
9840
+ * `course_check` item is active, and, once it clears with a note, until the note's first ring is
9841
+ * delivered to any session, so the note rings first. A course note is a worker `answer`
9842
+ * notification on a course check's block. Other roles and `cycle_limit` items hold no ring.
9843
+ */
9844
+ function courseHold(eb) {
9845
+ return eb.and([eb("notification.role", "=", "worker"), eb.or([eb.exists(eb.selectFrom("operator_item").select("operator_item.id").where("operator_item.kind", "=", "course_check").whereRef("operator_item.task_id", "=", "notification.task_id").where("operator_item.cleared_at", "is", null)), eb.and([eb.not(eb.and([eb("notification.kind", "=", "answer"), eb("notification.block_id", "in", courseBlocks(eb))])), eb.exists(eb.selectFrom("notification as note").select("note.id").whereRef("note.task_id", "=", "notification.task_id").where("note.role", "=", "worker").where("note.kind", "=", "answer").where("note.block_id", "in", courseBlocks(eb)).where("note.rings", "=", 0).where("note.acked_at", "is", null).where("note.exhausted_at", "is", null).where((inner) => inner.not(inner.exists(inner.selectFrom("outbox").select("outbox.id").where(sql`+outbox.state`, "=", "done").where("outbox.dedupe_key", ">", sql`'doorbell:' || ${sql.ref("note.id")} || ':'`).where("outbox.dedupe_key", "<", sql`'doorbell:' || ${sql.ref("note.id")} || ';'`)))))])])]);
9846
+ }
9847
+ /**
9753
9848
  * Moves a block to a new addressee, for `block.escalate` and for a ring series that ended: the
9754
9849
  * journal row, the old notification's end, the new one and the Slack thread, in the caller's
9755
9850
  * transaction.
@@ -9890,6 +9985,7 @@ async function restartNotification(trx, sourceKey, at) {
9890
9985
  async function endNotification(trx, n, task, end) {
9891
9986
  const { session, reason, at, config } = end;
9892
9987
  await trx.updateTable("notification").set({ exhausted_at: at.toISOString() }).where("id", "=", n.id).execute();
9988
+ if (n.rings === 0) await releaseAfterCourseNote(trx, n, at);
9893
9989
  const addressee = parseAddressee(n.role);
9894
9990
  if (n.kind === "block" && addressee.kind === "curator") await moveBlockToAddressee(trx, {
9895
9991
  task,
@@ -9971,9 +10067,12 @@ async function ringText(trx, n, task, ring) {
9971
10067
  const block = await trx.selectFrom("block").select("unblocked_by").where("id", "=", blockId).executeTakeFirstOrThrow();
9972
10068
  return `${task.key} block B${String(blockId)} was removed by ${block.unblocked_by ?? "system"}; see board task ${task.key} ${suffix}`;
9973
10069
  }
9974
- /** Notifications reconcile looks at: unacked, not exhausted, due, on a task not archived. */
10070
+ /**
10071
+ * Notifications reconcile looks at: unacked, not exhausted, due, on a task not archived, and not
10072
+ * held by a course check (`courseHold`).
10073
+ */
9975
10074
  function dueNotifications(db, at) {
9976
- return db.selectFrom("notification").innerJoin("task", "task.id", "notification.task_id").where("task.membership", "!=", "archived").where("notification.acked_at", "is", null).where("notification.exhausted_at", "is", null).where("notification.next_at", "<=", at.toISOString());
10075
+ return db.selectFrom("notification").innerJoin("task", "task.id", "notification.task_id").where("task.membership", "!=", "archived").where("notification.acked_at", "is", null).where("notification.exhausted_at", "is", null).where("notification.next_at", "<=", at.toISOString()).where((eb) => eb.not(courseHold(eb)));
9977
10076
  }
9978
10077
  /**
9979
10078
  * Reconciles due notifications in their own transaction. With none due it opens no transaction;
@@ -10048,7 +10147,6 @@ async function reconcileDoorbells(trx, at, config) {
10048
10147
  }
10049
10148
  const raised = await trx.selectFrom("operator_item").select((eb) => eb.fn.max("raise_no").as("series")).where("item_key", "=", exhaustedItemKey(n)).executeTakeFirst();
10050
10149
  const archived = await trx.selectFrom("event").select((eb) => eb.fn.countAll().as("count")).where("task_id", "=", n.task_id).where("kind", "=", "task_archived").executeTakeFirst();
10051
- 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;
10052
10150
  const ring = rings + 1;
10053
10151
  const text = await ringText(trx, n, task, ring);
10054
10152
  const outboxId = await enqueueDoorbell(trx, {
@@ -10058,8 +10156,7 @@ async function reconcileDoorbells(trx, at, config) {
10058
10156
  text,
10059
10157
  at,
10060
10158
  series: raised?.series ?? 0,
10061
- archives: archived?.count ?? 0,
10062
- moves: killed?.count ?? 0
10159
+ archives: archived?.count ?? 0
10063
10160
  });
10064
10161
  await trx.updateTable("notification").set({ last_outbox_id: outboxId }).where("id", "=", n.id).execute();
10065
10162
  }
@@ -10107,12 +10204,23 @@ async function recordRingDelivery(trx, notificationId, ring, session, at, config
10107
10204
  next_at: new Date(at.getTime() + (pauses[ring - 1] ?? 0)).toISOString(),
10108
10205
  ...n.kind === "removed" || n.kind === "turn_reminder" ? { acked_at: at.toISOString() } : {}
10109
10206
  }).where("id", "=", notificationId).execute();
10207
+ if (ring === 1) await releaseAfterCourseNote(trx, n, at);
10110
10208
  await journal$2(trx, n, "doorbell_rung", {
10111
10209
  doorbell: `N${String(n.id)}`,
10112
10210
  addressee: n.role,
10113
10211
  attempt: ring
10114
10212
  }, at);
10115
10213
  }
10214
+ /**
10215
+ * Once a course note no longer holds (`courseHold`): its first ring delivered, or read or ended
10216
+ * before it rang. Moves the worker's other rings on the task that waited in the outbox to the
10217
+ * front (`promoteWorkerDoorbells`); `clearItem` does the same for a course check that clears
10218
+ * without a note.
10219
+ */
10220
+ async function releaseAfterCourseNote(trx, n, at) {
10221
+ if (await trx.selectFrom("notification").select("id").where("id", "=", n.id).where("role", "=", "worker").where("kind", "=", "answer").where((eb) => eb("block_id", "in", courseBlocks(eb))).executeTakeFirst() === void 0) return;
10222
+ await promoteWorkerDoorbells(trx, n.task_id, at, n.id);
10223
+ }
10116
10224
  /** True while the Spur source is blind: its stored session facts may no longer hold. */
10117
10225
  async function spurBlind$1(trx) {
10118
10226
  const state = await trx.selectFrom("source_state").select("blind_reason").where("source", "=", "spur").executeTakeFirst();
@@ -10124,6 +10232,7 @@ async function ringStillCurrent(trx, notificationId, sessionId, config) {
10124
10232
  if (n === void 0 || n.acked_at !== null || n.exhausted_at !== null || n.recipient_session !== sessionId) return "dead";
10125
10233
  const session = await selectNotificationRecipient(trx, n, config);
10126
10234
  if (session?.id !== sessionId) return "dead";
10235
+ if (await trx.selectFrom("notification").select("id").where("id", "=", n.id).where(courseHold).executeTakeFirst() !== void 0) return "defer";
10127
10236
  return recipientBusy(session) && !await spurBlind$1(trx) ? "defer" : "send";
10128
10237
  }
10129
10238
  /**
@@ -10150,6 +10259,7 @@ async function acknowledgeNotification(trx, input) {
10150
10259
  if (!await notificationAddressedTo(trx, n, input.actor, input.config)) throw new CommandError("forbidden", "Only the addressed task role can acknowledge.");
10151
10260
  for (const notice of notices) {
10152
10261
  await trx.updateTable("notification").set({ acked_at: input.at.toISOString() }).where("id", "=", notice.id).execute();
10262
+ if (notice.rings === 0) await releaseAfterCourseNote(trx, notice, input.at);
10153
10263
  await journal$2(trx, notice, "doorbell_read", { doorbell: `N${String(notice.id)}` }, input.at);
10154
10264
  const item = await trx.selectFrom("operator_item").select("id").where("item_key", "=", exhaustedItemKey(notice)).where("cleared_at", "is", null).executeTakeFirst();
10155
10265
  if (item !== void 0) await clearItem(trx, item.id, input.at);
@@ -11405,16 +11515,20 @@ async function openSystemBlock(trx, input) {
11405
11515
  * Copies the answer to a course check to the task as a comment without a block, so the worker
11406
11516
  * reads it in its inbox: the close reason, else `answer`, else the closing actor's newest comment
11407
11517
  * on the block. A copied comment is named in the copy's `comment_added`, so its edits reach the
11408
- * copy.
11518
+ * copy. The copy rings the worker, ahead of its other rings on the task (`course_note`). Returns
11519
+ * the copy, or undefined when there is no answer to copy.
11409
11520
  */
11410
11521
  async function forwardCourseNote(trx, task, block, ctx, reason, given) {
11411
- if (reason !== null) {
11412
- await insertComment(trx, task, null, reason, ctx, "worker");
11413
- return;
11414
- }
11415
- const answer = given ?? await trx.selectFrom("comment").select(["id", "text"]).where("block_id", "=", block.id).where("author", "=", ctx.actor).orderBy("id", "desc").executeTakeFirst();
11416
- if (answer === void 0) return;
11417
- await insertComment(trx, task, null, answer.text, ctx, "worker", void 0, answer.id);
11522
+ const answer = reason !== null ? void 0 : given ?? await trx.selectFrom("comment").select(["id", "text"]).where("block_id", "=", block.id).where("author", "=", ctx.actor).orderBy("id", "desc").executeTakeFirst();
11523
+ const text = reason ?? answer?.text;
11524
+ if (text === void 0) return void 0;
11525
+ const copy = await insertComment(trx, task, null, text, ctx, "worker", void 0, answer?.id);
11526
+ await applyDoorbellPolicy(trx, {
11527
+ kind: "course_note",
11528
+ block,
11529
+ comment: copy
11530
+ }, new Date(ctx.at));
11531
+ return copy;
11418
11532
  }
11419
11533
  /** The comments `forwardCourseNote` copied from comment `id`. */
11420
11534
  async function forwardedCopies(trx, id) {
@@ -11446,8 +11560,9 @@ async function reviseComment(trx, task, comment, text, ctx) {
11446
11560
  * Unblocks one block with its journal entry, thread close, doorbell close and item clears. An
11447
11561
  * operator or agent close of a reconciled ledger block dismisses its item, so the condition
11448
11562
  * raises again only once it changes; a `system` or archive close only clears it. An answer or a
11449
- * close with a reason to a course check also goes to the worker as a task comment; `answer` names
11450
- * the answer when the closing actor also left a note after it.
11563
+ * close with a reason to a course check also goes to the worker as a task comment that rings it
11564
+ * first, before the rings the check held; `answer` names the answer when the closing actor also
11565
+ * left a note after it.
11451
11566
  */
11452
11567
  async function closeOpenBlock(trx, task, block, ctx, outcome, outcomeReason, answer) {
11453
11568
  const updated = await trx.updateTable("block").set({
@@ -12893,7 +13008,7 @@ async function existingLink(trx, taskId, input, ticket) {
12893
13008
  async function sessionRole(trx, taskId) {
12894
13009
  return await trx.selectFrom("link").select("id").where("task_id", "=", taskId).where("entity", "=", "session").where("role", "=", "worker").where("banned", "=", 0).executeTakeFirst() === void 0 ? "worker" : "other";
12895
13010
  }
12896
- async function prConflict(trx, taskId, repo, number, open) {
13011
+ async function prConflict(trx, taskId, repo, number, open, doneTicket) {
12897
13012
  const links = await trx.selectFrom("link").leftJoin("pr_snapshot", (join) => join.on(sql`lower(pr_snapshot.repo) = lower(link.repo)`).onRef("pr_snapshot.number", "=", "link.number")).select([
12898
13013
  "link.repo",
12899
13014
  "link.number",
@@ -12904,7 +13019,7 @@ async function prConflict(trx, taskId, repo, number, open) {
12904
13019
  for (const link of links) {
12905
13020
  if (link.repo?.toLowerCase() === repo && link.number === number) continue;
12906
13021
  const blocking = `${link.repo ?? ""}#${String(link.number ?? "")}`;
12907
- if (link.state === "merged") throw new CommandError("link_conflict", `${blocking} is merged; manual PR replacement is not allowed.`);
13022
+ if (link.state === "merged" && doneTicket) throw new CommandError("link_conflict", `${blocking} is merged; manual PR replacement is not allowed.`);
12908
13023
  if (open && link.pr_state === "active" && link.pr_open === 1) throw new CommandError("link_conflict", `${blocking} is already the open PR for this task.`);
12909
13024
  }
12910
13025
  }
@@ -12919,7 +13034,12 @@ async function run(trx, input, ctx, config, remove) {
12919
13034
  const pr = input.mode === "pr" ? prIdentity(input.pr) : null;
12920
13035
  const facts = pr === null ? null : await snapshot(trx, pr.repo, pr.number);
12921
13036
  const open = facts?.state !== "closed" && facts?.state !== "merged";
12922
- if (!remove && pr !== null) await prConflict(trx, task.id, pr.repo, pr.number, open);
13037
+ if (!remove && pr !== null) {
13038
+ const project = config.projects.find((entry) => entry.id === task.project);
13039
+ const status = await trx.selectFrom("ticket_snapshot").select("status").where("task_id", "=", task.id).executeTakeFirst();
13040
+ const doneTicket = project !== void 0 && status !== void 0 && ticketDone(project, status.status);
13041
+ await prConflict(trx, task.id, pr.repo, pr.number, open, doneTicket);
13042
+ }
12923
13043
  if (remove) {
12924
13044
  if (current?.banned === 1) return {
12925
13045
  task: key,
@@ -14088,11 +14208,30 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped) {
14088
14208
  prCompleteAt: prCompleteAt(config.projects.find((entry) => entry.id === task.project), sourceById),
14089
14209
  turnSessions: []
14090
14210
  };
14211
+ const tickets = await trx.selectFrom("ticket_snapshot").select([
14212
+ "task_id",
14213
+ "status",
14214
+ "detail",
14215
+ "source",
14216
+ "observed_at"
14217
+ ]).execute();
14218
+ const mergedAt = /* @__PURE__ */ new Map();
14091
14219
  for (const pr of prs) {
14092
14220
  const state = taskPrs[String(pr.task_id)];
14093
14221
  if (state === void 0) continue;
14094
14222
  if (pr.state === "open") state.hasOpenPr = true;
14095
- if (pr.state === "merged") state.hasMergedPr = true;
14223
+ if (pr.state !== "merged") continue;
14224
+ const facts = parsePr(pr.detail ?? void 0);
14225
+ const at = facts === null ? null : facts.mergedAt ?? facts.updatedAt;
14226
+ const newest = mergedAt.get(pr.task_id) ?? null;
14227
+ if (newest === null || at !== null && Date.parse(at) >= Date.parse(newest)) mergedAt.set(pr.task_id, at);
14228
+ }
14229
+ for (const [taskId, at] of mergedAt) {
14230
+ const state = taskPrs[String(taskId)];
14231
+ const task = taskById.get(taskId);
14232
+ if (state === void 0 || task === void 0) continue;
14233
+ const project = config.projects.find((entry) => entry.id === task.project);
14234
+ state.hasMergedPr = at === null || project === void 0 || mergedTicket(project, config, tickets.find((entry) => entry.task_id === taskId), task.manual_include === 1, at) !== "open";
14096
14235
  }
14097
14236
  const workerTurns = await trx.selectFrom("turn").select(["task_id", "acked_by"]).where("role", "=", "worker").where("closed_at", "is", null).where("acked_at", "is not", null).execute();
14098
14237
  for (const turn of workerTurns) {
@@ -14103,13 +14242,18 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped) {
14103
14242
  for (const task of tasks) {
14104
14243
  const state = taskPrs[String(task.id)];
14105
14244
  if (state === void 0 || state.hasOpenPr || state.hasMergedPr) continue;
14106
- const closed = prs.filter((pr) => pr.task_id === task.id && pr.state === "closed").map((pr) => ({
14107
- ...pr,
14108
- ref: `${pr.repo ?? ""}#${String(pr.number)}`
14109
- })).sort((left, right) => left.ref.localeCompare(right.ref));
14245
+ const mergedSince = Date.parse(mergedAt.get(task.id) ?? "");
14246
+ const closed = prs.filter((pr) => pr.task_id === task.id && pr.state === "closed").map((pr) => {
14247
+ const facts = pr.detail === null ? null : parseJson(prFactsSchema, pr.detail);
14248
+ return {
14249
+ ...pr,
14250
+ ref: `${pr.repo ?? ""}#${String(pr.number)}`,
14251
+ closedAt: facts === null ? NaN : Date.parse(facts.closedAt ?? facts.updatedAt)
14252
+ };
14253
+ }).filter((pr) => !(pr.closedAt < mergedSince)).sort((left, right) => left.ref.localeCompare(right.ref));
14110
14254
  const first = closed[0];
14111
14255
  if (first === void 0) continue;
14112
- const closedAt = Math.max(...closed.map((pr) => pr.detail === null ? NaN : Date.parse(parseJson(prFactsSchema, pr.detail).updatedAt)));
14256
+ const closedAt = Math.max(...closed.map((pr) => pr.closedAt));
14113
14257
  const key = `pr-closed:${String(task.id)}`;
14114
14258
  if (state.prCompleteAt === null || !(state.prCompleteAt >= closedAt)) {
14115
14259
  heldKeys.push(key);
@@ -14127,12 +14271,6 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped) {
14127
14271
  revision: refs.join(",")
14128
14272
  });
14129
14273
  }
14130
- const tickets = await trx.selectFrom("ticket_snapshot").select([
14131
- "task_id",
14132
- "status",
14133
- "detail",
14134
- "source"
14135
- ]).execute();
14136
14274
  for (const task of tasks) {
14137
14275
  const state = taskPrs[String(task.id)];
14138
14276
  const project = config.projects.find((entry) => entry.id === task.project);
@@ -14655,13 +14793,40 @@ function handedOf(pr, entry) {
14655
14793
  * The dispatcher input of one task, or null when a stored snapshot is missing or unreadable. It
14656
14794
  * only reads.
14657
14795
  */
14658
- async function readInput(trx, task, project, mode, blind) {
14796
+ async function readInput(trx, task, project, mode, blind, config) {
14797
+ const readPr = async (ref) => parsePr((await trx.selectFrom("pr_snapshot").select("detail").where(sql`lower(repo) = ${ref.repo.toLowerCase()}`).where("number", "=", ref.number).executeTakeFirst())?.detail);
14659
14798
  const link = await taskPr(trx, task.id);
14660
14799
  let pr = null;
14661
14800
  if (link !== null) {
14662
- pr = parsePr((await trx.selectFrom("pr_snapshot").select("detail").where(sql`lower(repo) = ${link.repo.toLowerCase()}`).where("number", "=", link.number).executeTakeFirst())?.detail);
14801
+ pr = await readPr(link);
14663
14802
  if (pr === null) return null;
14664
14803
  }
14804
+ const readTicket = () => trx.selectFrom("ticket_snapshot").select([
14805
+ "status",
14806
+ "detail",
14807
+ "observed_at"
14808
+ ]).where("task_id", "=", task.id).executeTakeFirst();
14809
+ if (pr !== null && pr.state !== "merged") {
14810
+ const merged = await taskMergedPr(trx, task.id);
14811
+ if (merged !== null) {
14812
+ const ticket = await readTicket();
14813
+ if (pr.state === "closed" && link?.open !== true || ticket !== void 0 && ticketDone(project, ticket.status)) {
14814
+ pr = await readPr(merged);
14815
+ if (pr === null) return null;
14816
+ }
14817
+ }
14818
+ }
14819
+ let mergedOpen;
14820
+ let ticketUnconfirmed = false;
14821
+ if (pr?.state === "merged") {
14822
+ const judged = mergedTicket(project, config, await readTicket(), task.manual_include === 1, pr.mergedAt ?? pr.updatedAt);
14823
+ if (judged === "open") mergedOpen = {
14824
+ repo: pr.repo,
14825
+ number: pr.number
14826
+ };
14827
+ ticketUnconfirmed = judged === "unconfirmed";
14828
+ }
14829
+ if (mergedOpen !== void 0) pr = null;
14665
14830
  const githubBlind = (pr === null ? project.repos : [pr.repo]).some((repo) => blind(prSourceId(project.id, repo)));
14666
14831
  const marks = (await trx.selectFrom("submission").select(["column", "commit_sha"]).where("task_id", "=", task.id).where("voided_at", "is", null).orderBy("id").execute()).map((row) => {
14667
14832
  const headSha = row.commit_sha.toLowerCase();
@@ -14695,7 +14860,7 @@ async function readInput(trx, task, project, mode, blind) {
14695
14860
  unhandledExternalComments: unhandled.length,
14696
14861
  marks
14697
14862
  },
14698
- reopened: await trx.selectFrom("link").select("id").where("task_id", "=", task.id).where("reopen_hidden_at", "is not", null).executeTakeFirst() !== void 0,
14863
+ reopened: mergedOpen === void 0 && await trx.selectFrom("link").select("id").where("task_id", "=", task.id).where("reopen_hidden_at", "is not", null).executeTakeFirst() !== void 0,
14699
14864
  openPr: link?.open === true,
14700
14865
  githubBlind,
14701
14866
  spurBlind: blind("spur"),
@@ -14708,7 +14873,9 @@ async function readInput(trx, task, project, mode, blind) {
14708
14873
  }
14709
14874
  },
14710
14875
  handed,
14711
- unclosed
14876
+ unclosed,
14877
+ mergedOpen,
14878
+ ticketUnconfirmed
14712
14879
  };
14713
14880
  }
14714
14881
  async function applyShadow(trx, task, project, result, at) {
@@ -14773,7 +14940,7 @@ async function applyOn(trx, task, read, result, ctx) {
14773
14940
  const handed = [...carried, ...read.handed.filter((entry) => !carried.some((old) => sameHanded(old, entry)))];
14774
14941
  await openTurn(trx, {
14775
14942
  task: current,
14776
- reason: turnReason(turn, replaced?.reason),
14943
+ reason: read.mergedOpen === void 0 || turn.kind === "reroute" ? turnReason(turn, replaced?.reason) : `${turnReason(turn)} (PR ${read.mergedOpen.repo}#${String(read.mergedOpen.number)} merged, ticket still open)`,
14777
14944
  handed: current.column === "dev" ? handed : [],
14778
14945
  at,
14779
14946
  config
@@ -14793,8 +14960,8 @@ async function dispatchTasks(trx, taskIds, ctx) {
14793
14960
  const project = ctx.config.projects.find((entry) => entry.id === task.project);
14794
14961
  if (project === void 0) continue;
14795
14962
  const mode = project.dispatcher.mode;
14796
- const read = await readInput(trx, task, project, mode, blind);
14797
- if (read === null) continue;
14963
+ const read = await readInput(trx, task, project, mode, blind, ctx.config);
14964
+ if (read === null || read.ticketUnconfirmed) continue;
14798
14965
  const result = dispatch(read.input);
14799
14966
  if (mode === "shadow") await applyShadow(trx, task, project, result, ctx.at);
14800
14967
  else await applyOn(trx, task, read, result, ctx);
@@ -14827,6 +14994,16 @@ async function dispatchSource(trx, source, ctx) {
14827
14994
  if (projects.length === 0) return;
14828
14995
  await dispatchTasks(trx, (await trx.selectFrom("task").select("id").where("project", "in", projects).where("membership", "!=", "archived").execute()).map((task) => task.id), ctx);
14829
14996
  }
14997
+ /**
14998
+ * Evaluates the tasks of a tracker source's project that are out of Done and whose PR merged:
14999
+ * a poll that only refreshes an unchanged open ticket journals nothing, yet can confirm it open
15000
+ * past the merge.
15001
+ */
15002
+ async function dispatchMergedTickets(trx, source, ctx) {
15003
+ const project = ctx.config.projects.find((entry) => trackerSourceId(entry) === source);
15004
+ if (project === void 0) return;
15005
+ await dispatchTasks(trx, (await trx.selectFrom("task").innerJoin("link", "link.task_id", "task.id").innerJoin("pr_snapshot", (join) => join.on(sql`lower(pr_snapshot.repo) = lower(link.repo)`).onRef("pr_snapshot.number", "=", "link.number")).select("task.id").distinct().where("task.project", "=", project.id).where("task.membership", "!=", "archived").where((eb) => eb.or([eb("task.column", "!=", "done"), eb("task.shadow_column", "!=", "done")])).where("link.entity", "=", "pr").where("link.pr_state", "=", "active").where("link.banned", "=", 0).where("pr_snapshot.state", "=", "merged").execute()).map((task) => task.id), ctx);
15006
+ }
14830
15007
  //#endregion
14831
15008
  //#region ../core/src/app/task-turns.ts
14832
15009
  /** How many closed turns `task.get --detail` shows. */
@@ -15014,7 +15191,7 @@ function createTaskQueries(deps) {
15014
15191
  const read = await readInput(trx, {
15015
15192
  ...task,
15016
15193
  column
15017
- }, project, mode, await blindSources(trx, completeSince));
15194
+ }, project, mode, await blindSources(trx, completeSince), config);
15018
15195
  if (read === null) return {
15019
15196
  ...shared,
15020
15197
  dispatcher: mode,
@@ -15023,14 +15200,21 @@ function createTaskQueries(deps) {
15023
15200
  checksWaivedBy: null
15024
15201
  };
15025
15202
  const { gates, checksWaivedBy } = explainGates(read.input.facts, read.input.project);
15203
+ const holds = [...dispatchHolds(read.input), ...read.ticketUnconfirmed ? ["ticket_unconfirmed"] : []].sort((left, right) => TASK_HOLDS.indexOf(left) - TASK_HOLDS.indexOf(right));
15204
+ const heldBy = holds.includes("cycle_limit") ? await holdBlocks(trx, task.id) : [];
15026
15205
  return {
15027
15206
  ...shared,
15028
15207
  dispatcher: mode,
15029
- holds: dispatchHolds(read.input),
15208
+ holds,
15209
+ ...heldBy.length === 0 ? {} : { heldBy },
15030
15210
  gates,
15031
15211
  checksWaivedBy
15032
15212
  };
15033
15213
  }
15214
+ /** The blocks of the active cycle-limit and course-check items that hold the task's turn. */
15215
+ async function holdBlocks(trx, taskId) {
15216
+ return (await trx.selectFrom("operator_item").select("block_id").where((eb) => eb.or([eb("item_key", "like", `${cycleKeyPrefix(taskId)}%`), eb("item_key", "like", `${courseKeyPrefix(taskId)}%`)])).where("cleared_at", "is", null).where("block_id", "is not", null).orderBy("id").execute()).flatMap((item) => item.block_id === null ? [] : [`B${String(item.block_id)}`]);
15217
+ }
15034
15218
  const get = {
15035
15219
  id: "task.get",
15036
15220
  resolveTargets: (trx, input) => taskTarget(trx, taskKey(input.task)),
@@ -15039,12 +15223,18 @@ function createTaskQueries(deps) {
15039
15223
  const [blocks, comments, links] = await Promise.all([
15040
15224
  trx.selectFrom("block").selectAll().where("task_id", "=", task.id).orderBy("id").execute(),
15041
15225
  trx.selectFrom("comment").selectAll().where("task_id", "=", task.id).orderBy("id").execute(),
15042
- trx.selectFrom("link").selectAll().where("task_id", "=", task.id).where("banned", "=", 0).orderBy("id").execute()
15226
+ trx.selectFrom("link").leftJoin("pr_snapshot", (join) => join.on(sql`lower(pr_snapshot.repo) = lower(link.repo)`).onRef("pr_snapshot.number", "=", "link.number")).selectAll("link").select("pr_snapshot.state").where("link.task_id", "=", task.id).where("link.banned", "=", 0).orderBy("link.id").execute()
15043
15227
  ]);
15044
15228
  return {
15045
15229
  task: taskView(task),
15046
15230
  ...await taskTurns(trx, task, input.detail === true),
15047
- links: links.map(linkView),
15231
+ links: links.map(({ state, ...link }) => {
15232
+ const observed = PR_STATES.find((value) => value === state);
15233
+ return {
15234
+ ...linkView(link),
15235
+ ...observed === void 0 ? {} : { state: observed }
15236
+ };
15237
+ }),
15048
15238
  blocks: blocks.map((block) => blockView(block, task)),
15049
15239
  comments: comments.map((comment) => commentView(comment, task)),
15050
15240
  ...input.why === true ? { why: await why(trx, task) } : {}
@@ -15103,6 +15293,7 @@ function createTaskQueries(deps) {
15103
15293
  const notices = await trx.selectFrom("notification").selectAll().where("kind", "=", "answer").where("acked_at", "is", null).orderBy("id", "desc").execute();
15104
15294
  const comments = [];
15105
15295
  const seen = /* @__PURE__ */ new Set();
15296
+ const listed = /* @__PURE__ */ new Set();
15106
15297
  for (const notice of notices) {
15107
15298
  if (notice.comment_id === null || seen.has(notice.comment_id)) continue;
15108
15299
  const task = await trx.selectFrom("task").selectAll().where("id", "=", notice.task_id).executeTakeFirst();
@@ -15111,6 +15302,7 @@ function createTaskQueries(deps) {
15111
15302
  if (!await notificationAddressedTo(trx, notice, actor, config)) continue;
15112
15303
  const comment = await trx.selectFrom("comment").selectAll().where("id", "=", notice.comment_id).executeTakeFirst();
15113
15304
  if (comment === void 0 || comment.acked_revision === comment.revision) continue;
15305
+ listed.add(comment.id);
15114
15306
  comments.push(commentView(comment, task));
15115
15307
  }
15116
15308
  const parsedActor = parseActorId(actor);
@@ -15121,7 +15313,7 @@ function createTaskQueries(deps) {
15121
15313
  const taskComments = await trx.selectFrom("comment").selectAll().where("task_id", "in", [...tasksById.keys()]).where("block_id", "is", null).orderBy("id").execute();
15122
15314
  for (const comment of taskComments) {
15123
15315
  const task = tasksById.get(comment.task_id);
15124
- if (task === void 0 || comment.author === actor || comment.acked_revision === comment.revision) continue;
15316
+ if (task === void 0 || listed.has(comment.id) || comment.author === actor || comment.acked_revision === comment.revision) continue;
15125
15317
  comments.push(commentView(comment, task));
15126
15318
  }
15127
15319
  }
@@ -15459,7 +15651,7 @@ function createTurnMutations(deps) {
15459
15651
  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(", ")}.`);
15460
15652
  const pr = await taskPr(trx, task.id);
15461
15653
  if (pr !== null) {
15462
- 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>\`.`);
15654
+ 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)}`} sets the task's column: Done once its ticket is done, Dev while it stays open; unlink it first with \`board unlink ${task.key} --pr https://github.com/${pr.repo}/pull/${String(pr.number)} --reason <text>\`.`);
15463
15655
  }
15464
15656
  const corrected = await correctColumn(trx, {
15465
15657
  taskId: task.id,
@@ -15705,7 +15897,7 @@ async function updateTerminal(trx, config, taskId, at, completeSince, blind) {
15705
15897
  const complete = completeSince.get(source);
15706
15898
  return !blind.has(source) && complete !== void 0 && complete > (task.last_change_at ?? task.created_at);
15707
15899
  });
15708
- const terminal = !hasOpen && (merged || doneTicket && githubComplete);
15900
+ const terminal = !hasOpen && doneTicket && (merged || githubComplete);
15709
15901
  await trx.updateTable("task").set({ terminal_at: terminal ? task.terminal_at ?? (merged ? at : task.last_change_at ?? at) : null }).where("id", "=", taskId).execute();
15710
15902
  }
15711
15903
  async function blindReason(trx, source) {
@@ -16374,6 +16566,7 @@ function createObservationCore(deps) {
16374
16566
  };
16375
16567
  const recovered = wasBlind !== null && observation.state.blind === void 0;
16376
16568
  if (observation.effectiveComplete && !completeSince.has(source) || recovered) await dispatchSource(trx, source, dispatchContext);
16569
+ await dispatchMergedTickets(trx, source, dispatchContext);
16377
16570
  await dispatchJournaled(trx, dispatchContext);
16378
16571
  await reconcileItems(trx, config, now, currentComplete.has("spur"), warnSkipped);
16379
16572
  if (deps.productVersion !== void 0) await enqueueLiveAfterFirstPoll(trx, {
@@ -16589,6 +16782,7 @@ function commandReply(id, value, input) {
16589
16782
  body: [
16590
16783
  line(`Task ${result.task.key}: ${result.task.column} (${result.task.membership})`),
16591
16784
  turnLine(result.turn),
16785
+ ...result.links.flatMap((link) => link.kind === "pr" ? [line(`Pull request ${link.ref}: ${link.state ?? "not observed yet"}`)] : []),
16592
16786
  ...result.blocks.flatMap((block) => [line(`Block ${block.id} (${block.state}, ${block.type}):`), quote(block.reason)]),
16593
16787
  ...result.comments.flatMap((comment) => [line(`Comment ${comment.id} by ${comment.author}:`), quote(comment.text)])
16594
16788
  ]
@@ -17857,7 +18051,7 @@ const REVIEWER_FIELDS = "requestedReviewer { __typename ... on Bot { login } ...
17857
18051
  const REVIEW_FIELDS = "id author { __typename login } state commit { oid } submittedAt";
17858
18052
  const COMMENT_FIELDS = "nodes { id author { __typename login } createdAt } pageInfo { hasPreviousPage startCursor }";
17859
18053
  const CLOSING_FIELDS = "nodes { number repository { nameWithOwner } } pageInfo { hasNextPage endCursor }";
17860
- const prFields = (number, closing = false) => `id number url title updatedAt mergedAt state isDraft mergeable mergeStateStatus
18054
+ const prFields = (number, closing = false) => `id number url title updatedAt mergedAt closedAt state isDraft mergeable mergeStateStatus
17861
18055
  author { login } headRefName headRefOid
17862
18056
  statusCheckRollup { contexts(first: 100) { nodes {
17863
18057
  ... on CheckRun { __typename name status conclusion startedAt completedAt checkSuite { createdAt } isRequired(pullRequestNumber: ${String(number)}) }
@@ -18076,6 +18270,7 @@ const prWire = z.object({
18076
18270
  title: z.string(),
18077
18271
  updatedAt: z.string(),
18078
18272
  mergedAt: z.string().nullable(),
18273
+ closedAt: z.string().nullable(),
18079
18274
  state: z.string(),
18080
18275
  isDraft: z.boolean(),
18081
18276
  mergeable: z.string(),
@@ -18356,6 +18551,7 @@ function normalizePr(repo, value, rule, feedbackComplete, held = []) {
18356
18551
  ticketKeys: prKeys(rule, title, headBranch, closingRefs(wire.closingIssuesReferences)),
18357
18552
  updatedAt: wire.updatedAt,
18358
18553
  ...state === "merged" && wire.mergedAt !== null ? { mergedAt: wire.mergedAt } : {},
18554
+ ...state === "closed" && wire.closedAt !== null ? { closedAt: wire.closedAt } : {},
18359
18555
  feedback: feedbackOf(wire.reviews.nodes, wire.comments.nodes, held),
18360
18556
  feedbackComplete
18361
18557
  };
package/dist/mcp.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { C as renderMcpError, X as ERRORS, y as OPERATIONS } from "./chunk-C0avjvF7.mjs";
2
- import { o as CliError, r as requestOperation } from "./chunk-Dd1yi1dh.mjs";
3
- import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-CaWf-PGm.mjs";
1
+ import { C as renderMcpError, Z as ERRORS, y as OPERATIONS } from "./chunk-DsCpUW6q.mjs";
2
+ import { o as CliError, r as requestOperation } from "./chunk-B2jz795d.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-hS9wN0vI.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { z } from "zod";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spur-board",
3
- "version": "0.54.1",
3
+ "version": "0.55.1",
4
4
  "license": "MIT",
5
5
  "engines": {
6
6
  "node": "^24.12.0 || ^26.0.0"