spur-board 0.54.0 → 0.55.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.
@@ -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-DjHqB_QC.mjs";
1
+ import { $ as errorEnvelopeSchema, Q as errorContextSchema, S as renderJsonError, X as ERRORS, c as tokenRequestStatusSchema, o as tokenRequestResultSchema, tt as successEnvelopeSchema } from "./chunk-DdX2rQDT.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { z } from "zod";
4
4
  import { request } from "node:http";
@@ -1,5 +1,5 @@
1
- import { _ as buildCatalogSnapshot, ct as plainHttpAllowed, st as configSchema, y as OPERATIONS } from "./chunk-DjHqB_QC.mjs";
2
- import { o as CliError, t as fetchCatalogVersion } from "./chunk-DgTcmpig.mjs";
1
+ import { _ as buildCatalogSnapshot, ct as plainHttpAllowed, st as configSchema, y as OPERATIONS } from "./chunk-DdX2rQDT.mjs";
2
+ import { o as CliError, t as fetchCatalogVersion } from "./chunk-3DiqeT6s.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";
@@ -992,6 +992,11 @@ const blockIdSchema = refSchema("block", "Block ID: B followed by a number, e.g.
992
992
  const commentIdSchema = refSchema("comment", "Comment ID: C followed by a number, e.g. C3.", NUMBERED_ID_MAX);
993
993
  const itemIdSchema = refSchema("item", "Item ID: I followed by a number, e.g. I7.", NUMBERED_ID_MAX);
994
994
  const turnIdSchema = refSchema("turn", "Turn ID: T followed by a number, e.g. T4.", NUMBERED_ID_MAX);
995
+ /**
996
+ * The ring ID a doorbell text ends with, `N<notification>-<ring>`, or a bare `N<notification>`.
997
+ * Only `inbox.ack` takes it; it is not a `RefKind`, since `N18-1` is also a valid Jira key.
998
+ */
999
+ const ringIdSchema = z.string().max(32).regex(new RegExp(`^N${REF_NUMBER}(?:-${REF_NUMBER})?$`)).describe("Ring ID from a doorbell text: N<notification>-<ring>, e.g. N18-1; the ring part is optional.");
995
1000
  const TASK_KEY_DESCRIPTION = "Task key: a Jira key (PROJ-123) or a GitHub issue (owner/repo#42, or repo#42).";
996
1001
  const taskKeySchema = refSchema("task", TASK_KEY_DESCRIPTION);
997
1002
  /** The task key an operation input takes: `taskKeySchema` with a length cap. */
@@ -1938,6 +1943,7 @@ const taskWhySchema = z.strictObject({
1938
1943
  column: z.enum(COLUMN_IDS).describe("Column the dispatcher works from: the shadow column in shadow mode."),
1939
1944
  dispatcher: z.enum(DISPATCHER_MODES).nullable().describe("The project's dispatcher mode; null when the project is not configured."),
1940
1945
  holds: z.array(z.enum(TASK_HOLDS)).describe("What holds the dispatcher from acting on the task; empty when nothing does."),
1946
+ 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."),
1941
1947
  gates: z.array(z.strictObject({
1942
1948
  column: z.enum(COLUMN_IDS).describe("Board column."),
1943
1949
  enabled: z.boolean().describe("Whether the column is enabled in the project."),
@@ -2642,9 +2648,9 @@ const OPERATIONS = [
2642
2648
  defineOperation({
2643
2649
  id: "inbox.ack",
2644
2650
  kind: "mutation",
2645
- description: "Mark comments, agent-addressed blocks or turns as read; acking a turn makes the caller its taker.",
2651
+ description: "Mark comments, agent-addressed blocks, turns or doorbell rings as read; acking a turn makes the caller its taker.",
2646
2652
  mcp: {
2647
- whenToUse: "Mark handled inbox items read.",
2653
+ whenToUse: "Mark handled inbox items or a ring ID like N18-1 read; an item handled before comes back under alreadyHandled.",
2648
2654
  whenNotToUse: "Use inbox_get to inspect them first."
2649
2655
  },
2650
2656
  input: z.strictObject({ entries: z.array(z.union([
@@ -2653,13 +2659,23 @@ const OPERATIONS = [
2653
2659
  revision: z.int().positive().describe("Revision the caller read.")
2654
2660
  }),
2655
2661
  z.strictObject({ id: blockIdSchema }),
2656
- z.strictObject({ id: turnIdSchema })
2657
- ])).min(1).max(ACK_ENTRIES_MAX).describe("Comment revisions, blocks and turns to acknowledge.") }),
2658
- output: z.strictObject({ acked: z.array(z.union([
2659
- commentIdSchema,
2660
- blockIdSchema,
2661
- turnIdSchema
2662
- ])).describe("Entries now acknowledged.") }),
2662
+ z.strictObject({ id: turnIdSchema }),
2663
+ z.strictObject({ id: ringIdSchema })
2664
+ ])).min(1).max(ACK_ENTRIES_MAX).describe("Comment revisions, blocks, turns and ring IDs to acknowledge.") }),
2665
+ output: z.strictObject({
2666
+ acked: z.array(z.union([
2667
+ commentIdSchema,
2668
+ blockIdSchema,
2669
+ turnIdSchema,
2670
+ ringIdSchema
2671
+ ])).describe("Entries now acknowledged."),
2672
+ alreadyHandled: z.array(z.union([
2673
+ commentIdSchema,
2674
+ blockIdSchema,
2675
+ turnIdSchema,
2676
+ ringIdSchema
2677
+ ])).optional().describe("Entries that were already handled; nothing new was acknowledged for them.")
2678
+ }),
2663
2679
  grants: [{ grant: "project-agent" }],
2664
2680
  errors: [
2665
2681
  "wrong_id_kind",
@@ -2689,6 +2705,19 @@ const OPERATIONS = [
2689
2705
  summary: "Take a turn",
2690
2706
  input: { entries: [{ id: "T4" }] },
2691
2707
  output: { acked: ["T4"] }
2708
+ },
2709
+ {
2710
+ summary: "Acknowledge a doorbell by the ring ID at the end of its text",
2711
+ input: { entries: [{ id: "N18-1" }] },
2712
+ output: { acked: ["N18-1"] }
2713
+ },
2714
+ {
2715
+ summary: "Acknowledge a block already closed by an answer",
2716
+ input: { entries: [{ id: "B14" }] },
2717
+ output: {
2718
+ acked: ["B14"],
2719
+ alreadyHandled: ["B14"]
2720
+ }
2692
2721
  }
2693
2722
  ]
2694
2723
  }),
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-DjHqB_QC.mjs";
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-DdX2rQDT.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-DgTcmpig.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-C7CHbmMl.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-3DiqeT6s.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-COsEkoTY.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-DgTcmpig.mjs";
1
+ import { a as requestTokenEnrollment, i as requestSkillReload, n as fetchTokenStatus, r as requestOperation, t as fetchCatalogVersion } from "./chunk-3DiqeT6s.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-DjHqB_QC.mjs";
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-DdX2rQDT.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";
@@ -8902,17 +8902,23 @@ function exchangeBody(payload) {
8902
8902
  }
8903
8903
  /**
8904
8904
  * 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.
8905
+ * (`series` > 0) and a ring after the task was archived (`archives` > 0) get their own keys.
8906
+ * Every ring of a key whose earlier rows all finished (a move or archive killed them, or a
8907
+ * handover reset the series after they were delivered) takes the next handover generation
8908
+ * `:h<n>`, `n` being how many rows the key has, so a finished ring never blocks its successor.
8909
+ * A row of the key still waiting in the outbox is returned instead. Unsuffixed keys stay as
8910
+ * before.
8908
8911
  */
8909
8912
  async function enqueueDoorbell(trx, input) {
8910
8913
  const series = input.series ?? 0;
8911
8914
  const archives = input.archives ?? 0;
8912
- const moves = input.moves ?? 0;
8915
+ const base = `doorbell:${String(input.notificationId)}:${input.session}:${String(input.ring)}${series > 0 ? `:s${String(series)}` : ""}${archives > 0 ? `:a${String(archives)}` : ""}`;
8916
+ 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();
8917
+ const waiting = rows.find((row) => row.state === "pending" || row.state === "in_flight");
8918
+ if (waiting !== void 0) return waiting.id;
8913
8919
  const row = await insertOutbox(trx, {
8914
8920
  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)}` : ""}`,
8921
+ dedupeKey: rows.length > 0 ? `${base}:h${String(rows.length)}` : base,
8916
8922
  payload: {
8917
8923
  notificationId: input.notificationId,
8918
8924
  ring: input.ring,
@@ -8925,6 +8931,16 @@ async function enqueueDoorbell(trx, input) {
8925
8931
  if (row.id === null) throw new Error("Doorbell cannot be blocked by gateway scan");
8926
8932
  return row.id;
8927
8933
  }
8934
+ /**
8935
+ * Moves the doorbell rows of the worker's notifications on task `taskId`, other than `exceptId`,
8936
+ * that wait in the outbox to the front, in outbox id order, ahead of rings reconcile enqueues
8937
+ * next. A row in retry backoff (`attempts > 0`) keeps its wait.
8938
+ */
8939
+ async function promoteWorkerDoorbells(trx, taskId, at, exceptId) {
8940
+ let others = trx.selectFrom("notification").select("id").where("task_id", "=", taskId).where("role", "=", "worker");
8941
+ if (exceptId !== void 0) others = others.where("id", "!=", exceptId);
8942
+ 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();
8943
+ }
8928
8944
  /** The key holds no install time, so a session gets at most one reload message per version. */
8929
8945
  function skillReloadKey(version, session) {
8930
8946
  return `doorbell:skill-reload:${version}:${session}`;
@@ -9395,7 +9411,17 @@ async function raiseItem(trx, input) {
9395
9411
  return raiseItemWith(trx, input, enqueueFeedLine);
9396
9412
  }
9397
9413
  /**
9414
+ * Whether the course check `item` forwarded a note: a worker `answer` notification on its block.
9415
+ * The note's first ring then releases the held rings (`releaseAfterCourseNote`).
9416
+ */
9417
+ async function courseNoted(trx, item) {
9418
+ if (item.block_id === null) return false;
9419
+ return await trx.selectFrom("notification").select("id").where("block_id", "=", item.block_id).where("role", "=", "worker").where("kind", "=", "answer").executeTakeFirst() !== void 0;
9420
+ }
9421
+ /**
9398
9422
  * Clear an item once; the edit waits for its line and is cancelled with a stale pending line.
9423
+ * A course check cleared without a note moves the worker's held rings on its task that wait in
9424
+ * the outbox to the front, so they keep their order.
9399
9425
  * The journal names `actor`, `system` unless an actor's action cleared it. `writeEdit`, when
9400
9426
  * given, writes the line's edit instead of the resolved one.
9401
9427
  */
@@ -9403,6 +9429,7 @@ async function clearItem(trx, itemId, at, actor = "system", writeEdit) {
9403
9429
  if ((await trx.selectFrom("operator_item").selectAll().where("id", "=", itemId).executeTakeFirstOrThrow()).cleared_at !== null) return;
9404
9430
  const item = await trx.updateTable("operator_item").set({ cleared_at: at.toISOString() }).where("id", "=", itemId).returningAll().executeTakeFirstOrThrow();
9405
9431
  await journal$3(trx, item, "from_you_cleared", at, void 0, actor);
9432
+ if (item.kind === "course_check" && item.task_id !== null && !await courseNoted(trx, item)) await promoteWorkerDoorbells(trx, item.task_id, at);
9406
9433
  if (item.line_outbox_id === null) return;
9407
9434
  if (writeEdit !== void 0) {
9408
9435
  await writeEdit(item, item.line_outbox_id);
@@ -9591,6 +9618,9 @@ async function applyDoorbellPolicy(trx, event, at) {
9591
9618
  case "block_removed":
9592
9619
  await registerRemovedNotification(trx, event.block, at);
9593
9620
  return;
9621
+ case "course_note":
9622
+ await registerCourseNoteNotification(trx, event, at);
9623
+ return;
9594
9624
  case "block_closed_by_addressee":
9595
9625
  case "task_comment": return;
9596
9626
  default: assertNever(event);
@@ -9750,6 +9780,40 @@ async function registerAnswerNotification(trx, input, at) {
9750
9780
  }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
9751
9781
  }
9752
9782
  /**
9783
+ * Register the worker's ring for a course note: the curator's answer to a course check, copied to
9784
+ * the task. It names the course block, and until its first ring is delivered the worker's other
9785
+ * rings on the task stay held (`courseHold`), so the worker reads the decision first.
9786
+ */
9787
+ async function registerCourseNoteNotification(trx, input, at) {
9788
+ await trx.insertInto("notification").values({
9789
+ source_key: `course-note:${String(input.comment.id)}`,
9790
+ kind: "answer",
9791
+ task_id: input.block.task_id,
9792
+ block_id: input.block.id,
9793
+ comment_id: input.comment.id,
9794
+ revision: input.comment.revision,
9795
+ role: "worker",
9796
+ author_session: null,
9797
+ recipient_session: null,
9798
+ next_at: at.toISOString(),
9799
+ last_outbox_id: null,
9800
+ acked_at: null,
9801
+ exhausted_at: null,
9802
+ created_at: at.toISOString()
9803
+ }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
9804
+ }
9805
+ /** Course-check items of any state, as subquery rows of their block ids. */
9806
+ 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);
9807
+ /**
9808
+ * Whether a worker notification is held by a course check on its task. Two holds apply: while a
9809
+ * `course_check` item is active, and, once it clears with a note, until the note's first ring is
9810
+ * delivered to any session, so the note rings first. A course note is a worker `answer`
9811
+ * notification on a course check's block. Other roles and `cycle_limit` items hold no ring.
9812
+ */
9813
+ function courseHold(eb) {
9814
+ 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")} || ';'`)))))])])]);
9815
+ }
9816
+ /**
9753
9817
  * Moves a block to a new addressee, for `block.escalate` and for a ring series that ended: the
9754
9818
  * journal row, the old notification's end, the new one and the Slack thread, in the caller's
9755
9819
  * transaction.
@@ -9890,6 +9954,7 @@ async function restartNotification(trx, sourceKey, at) {
9890
9954
  async function endNotification(trx, n, task, end) {
9891
9955
  const { session, reason, at, config } = end;
9892
9956
  await trx.updateTable("notification").set({ exhausted_at: at.toISOString() }).where("id", "=", n.id).execute();
9957
+ if (n.rings === 0) await releaseAfterCourseNote(trx, n, at);
9893
9958
  const addressee = parseAddressee(n.role);
9894
9959
  if (n.kind === "block" && addressee.kind === "curator") await moveBlockToAddressee(trx, {
9895
9960
  task,
@@ -9971,9 +10036,12 @@ async function ringText(trx, n, task, ring) {
9971
10036
  const block = await trx.selectFrom("block").select("unblocked_by").where("id", "=", blockId).executeTakeFirstOrThrow();
9972
10037
  return `${task.key} block B${String(blockId)} was removed by ${block.unblocked_by ?? "system"}; see board task ${task.key} ${suffix}`;
9973
10038
  }
9974
- /** Notifications reconcile looks at: unacked, not exhausted, due, on a task not archived. */
10039
+ /**
10040
+ * Notifications reconcile looks at: unacked, not exhausted, due, on a task not archived, and not
10041
+ * held by a course check (`courseHold`).
10042
+ */
9975
10043
  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());
10044
+ 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
10045
  }
9978
10046
  /**
9979
10047
  * Reconciles due notifications in their own transaction. With none due it opens no transaction;
@@ -10048,7 +10116,6 @@ async function reconcileDoorbells(trx, at, config) {
10048
10116
  }
10049
10117
  const raised = await trx.selectFrom("operator_item").select((eb) => eb.fn.max("raise_no").as("series")).where("item_key", "=", exhaustedItemKey(n)).executeTakeFirst();
10050
10118
  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
10119
  const ring = rings + 1;
10053
10120
  const text = await ringText(trx, n, task, ring);
10054
10121
  const outboxId = await enqueueDoorbell(trx, {
@@ -10058,8 +10125,7 @@ async function reconcileDoorbells(trx, at, config) {
10058
10125
  text,
10059
10126
  at,
10060
10127
  series: raised?.series ?? 0,
10061
- archives: archived?.count ?? 0,
10062
- moves: killed?.count ?? 0
10128
+ archives: archived?.count ?? 0
10063
10129
  });
10064
10130
  await trx.updateTable("notification").set({ last_outbox_id: outboxId }).where("id", "=", n.id).execute();
10065
10131
  }
@@ -10107,12 +10173,23 @@ async function recordRingDelivery(trx, notificationId, ring, session, at, config
10107
10173
  next_at: new Date(at.getTime() + (pauses[ring - 1] ?? 0)).toISOString(),
10108
10174
  ...n.kind === "removed" || n.kind === "turn_reminder" ? { acked_at: at.toISOString() } : {}
10109
10175
  }).where("id", "=", notificationId).execute();
10176
+ if (ring === 1) await releaseAfterCourseNote(trx, n, at);
10110
10177
  await journal$2(trx, n, "doorbell_rung", {
10111
10178
  doorbell: `N${String(n.id)}`,
10112
10179
  addressee: n.role,
10113
10180
  attempt: ring
10114
10181
  }, at);
10115
10182
  }
10183
+ /**
10184
+ * Once a course note no longer holds (`courseHold`): its first ring delivered, or read or ended
10185
+ * before it rang. Moves the worker's other rings on the task that waited in the outbox to the
10186
+ * front (`promoteWorkerDoorbells`); `clearItem` does the same for a course check that clears
10187
+ * without a note.
10188
+ */
10189
+ async function releaseAfterCourseNote(trx, n, at) {
10190
+ 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;
10191
+ await promoteWorkerDoorbells(trx, n.task_id, at, n.id);
10192
+ }
10116
10193
  /** True while the Spur source is blind: its stored session facts may no longer hold. */
10117
10194
  async function spurBlind$1(trx) {
10118
10195
  const state = await trx.selectFrom("source_state").select("blind_reason").where("source", "=", "spur").executeTakeFirst();
@@ -10124,6 +10201,7 @@ async function ringStillCurrent(trx, notificationId, sessionId, config) {
10124
10201
  if (n === void 0 || n.acked_at !== null || n.exhausted_at !== null || n.recipient_session !== sessionId) return "dead";
10125
10202
  const session = await selectNotificationRecipient(trx, n, config);
10126
10203
  if (session?.id !== sessionId) return "dead";
10204
+ if (await trx.selectFrom("notification").select("id").where("id", "=", n.id).where(courseHold).executeTakeFirst() !== void 0) return "defer";
10127
10205
  return recipientBusy(session) && !await spurBlind$1(trx) ? "defer" : "send";
10128
10206
  }
10129
10207
  /**
@@ -10150,6 +10228,7 @@ async function acknowledgeNotification(trx, input) {
10150
10228
  if (!await notificationAddressedTo(trx, n, input.actor, input.config)) throw new CommandError("forbidden", "Only the addressed task role can acknowledge.");
10151
10229
  for (const notice of notices) {
10152
10230
  await trx.updateTable("notification").set({ acked_at: input.at.toISOString() }).where("id", "=", notice.id).execute();
10231
+ if (notice.rings === 0) await releaseAfterCourseNote(trx, notice, input.at);
10153
10232
  await journal$2(trx, notice, "doorbell_read", { doorbell: `N${String(notice.id)}` }, input.at);
10154
10233
  const item = await trx.selectFrom("operator_item").select("id").where("item_key", "=", exhaustedItemKey(notice)).where("cleared_at", "is", null).executeTakeFirst();
10155
10234
  if (item !== void 0) await clearItem(trx, item.id, input.at);
@@ -11186,6 +11265,10 @@ async function blockById(trx, id) {
11186
11265
  async function commentById(trx, id) {
11187
11266
  return trx.selectFrom("comment").selectAll().where("id", "=", idNumber(id)).executeTakeFirst();
11188
11267
  }
11268
+ /** The notification a ring ID `N<notification>[-<ring>]` names; the ring part is ignored. */
11269
+ async function notificationByRingId(trx, id) {
11270
+ return trx.selectFrom("notification").selectAll().where("id", "=", Number.parseInt(id.slice(1), 10)).executeTakeFirst();
11271
+ }
11189
11272
  function found(value) {
11190
11273
  if (value === void 0) throw new CommandError("not_found", "Check the target ID.");
11191
11274
  return value;
@@ -11401,16 +11484,20 @@ async function openSystemBlock(trx, input) {
11401
11484
  * Copies the answer to a course check to the task as a comment without a block, so the worker
11402
11485
  * reads it in its inbox: the close reason, else `answer`, else the closing actor's newest comment
11403
11486
  * on the block. A copied comment is named in the copy's `comment_added`, so its edits reach the
11404
- * copy.
11487
+ * copy. The copy rings the worker, ahead of its other rings on the task (`course_note`). Returns
11488
+ * the copy, or undefined when there is no answer to copy.
11405
11489
  */
11406
11490
  async function forwardCourseNote(trx, task, block, ctx, reason, given) {
11407
- if (reason !== null) {
11408
- await insertComment(trx, task, null, reason, ctx, "worker");
11409
- return;
11410
- }
11411
- const answer = given ?? await trx.selectFrom("comment").select(["id", "text"]).where("block_id", "=", block.id).where("author", "=", ctx.actor).orderBy("id", "desc").executeTakeFirst();
11412
- if (answer === void 0) return;
11413
- await insertComment(trx, task, null, answer.text, ctx, "worker", void 0, answer.id);
11491
+ 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();
11492
+ const text = reason ?? answer?.text;
11493
+ if (text === void 0) return void 0;
11494
+ const copy = await insertComment(trx, task, null, text, ctx, "worker", void 0, answer?.id);
11495
+ await applyDoorbellPolicy(trx, {
11496
+ kind: "course_note",
11497
+ block,
11498
+ comment: copy
11499
+ }, new Date(ctx.at));
11500
+ return copy;
11414
11501
  }
11415
11502
  /** The comments `forwardCourseNote` copied from comment `id`. */
11416
11503
  async function forwardedCopies(trx, id) {
@@ -11442,8 +11529,9 @@ async function reviseComment(trx, task, comment, text, ctx) {
11442
11529
  * Unblocks one block with its journal entry, thread close, doorbell close and item clears. An
11443
11530
  * operator or agent close of a reconciled ledger block dismisses its item, so the condition
11444
11531
  * raises again only once it changes; a `system` or archive close only clears it. An answer or a
11445
- * close with a reason to a course check also goes to the worker as a task comment; `answer` names
11446
- * the answer when the closing actor also left a note after it.
11532
+ * close with a reason to a course check also goes to the worker as a task comment that rings it
11533
+ * first, before the rings the check held; `answer` names the answer when the closing actor also
11534
+ * left a note after it.
11447
11535
  */
11448
11536
  async function closeOpenBlock(trx, task, block, ctx, outcome, outcomeReason, answer) {
11449
11537
  const updated = await trx.updateTable("block").set({
@@ -11574,166 +11662,253 @@ async function queueCuratorAnswerLine(trx, task, block, answer, note, ctx, confi
11574
11662
  }
11575
11663
  /** Concrete block and comment mutations for the generic apply boundary. */
11576
11664
  function createBlockMutations(config) {
11577
- return {
11578
- ask: {
11579
- id: "block.ask",
11580
- resolveTargets: (trx, input) => taskTarget(trx, input.task),
11581
- async run(trx, input, ctx) {
11582
- const task = found(await taskByKey$1(trx, input.task));
11583
- active(task);
11584
- const block = await openBlock(trx, task, "needs_input", input.text, ctx, config);
11585
- await addComment(trx, task, block, input.text, ctx, block.addressee_role, config);
11586
- await queueBlockOpen(trx, task, block, ctx, config);
11587
- return { block: blockView(block, task) };
11588
- }
11589
- },
11590
- create: {
11591
- id: "block.create",
11592
- resolveTargets: (trx, input) => taskTarget(trx, input.task),
11593
- async run(trx, input, ctx) {
11594
- const task = found(await taskByKey$1(trx, input.task));
11595
- active(task);
11596
- const block = await openBlock(trx, task, input.type, input.reason, ctx, config);
11597
- await queueBlockOpen(trx, task, block, ctx, config);
11598
- return { block: blockView(block, task) };
11599
- }
11600
- },
11601
- escalate: {
11602
- id: "block.escalate",
11603
- async resolveTargets(trx, input, actor) {
11604
- const block = await blockById(trx, input.block);
11605
- if (block === void 0) return blockTarget(trx, input.block);
11606
- const task = await taskById$1(trx, block.task_id);
11607
- const target = await authorizationTarget(trx, task, block);
11608
- if (target.kind !== "found" || target.value.block === null) return [target];
11609
- if (holdsBlock(config, actor, target)) return [target];
11610
- const priors = priorAddressees(await routeBlock(trx, task, block, config), block.addressee_role, block.type, curatorProject(config, task.project) !== null);
11611
- for (const addressee_role of priors) {
11612
- const prior = {
11613
- kind: "found",
11614
- value: {
11615
- ...target.value,
11616
- block: {
11617
- ...target.value.block,
11618
- addressee_role
11619
- }
11665
+ const ask = {
11666
+ id: "block.ask",
11667
+ resolveTargets: (trx, input) => taskTarget(trx, input.task),
11668
+ async run(trx, input, ctx) {
11669
+ const task = found(await taskByKey$1(trx, input.task));
11670
+ active(task);
11671
+ const block = await openBlock(trx, task, "needs_input", input.text, ctx, config);
11672
+ await addComment(trx, task, block, input.text, ctx, block.addressee_role, config);
11673
+ await queueBlockOpen(trx, task, block, ctx, config);
11674
+ return { block: blockView(block, task) };
11675
+ }
11676
+ };
11677
+ const create = {
11678
+ id: "block.create",
11679
+ resolveTargets: (trx, input) => taskTarget(trx, input.task),
11680
+ async run(trx, input, ctx) {
11681
+ const task = found(await taskByKey$1(trx, input.task));
11682
+ active(task);
11683
+ const block = await openBlock(trx, task, input.type, input.reason, ctx, config);
11684
+ await queueBlockOpen(trx, task, block, ctx, config);
11685
+ return { block: blockView(block, task) };
11686
+ }
11687
+ };
11688
+ const escalate = {
11689
+ id: "block.escalate",
11690
+ async resolveTargets(trx, input, actor) {
11691
+ const block = await blockById(trx, input.block);
11692
+ if (block === void 0) return blockTarget(trx, input.block);
11693
+ const task = await taskById$1(trx, block.task_id);
11694
+ const target = await authorizationTarget(trx, task, block);
11695
+ if (target.kind !== "found" || target.value.block === null) return [target];
11696
+ if (holdsBlock(config, actor, target)) return [target];
11697
+ const priors = priorAddressees(await routeBlock(trx, task, block, config), block.addressee_role, block.type, curatorProject(config, task.project) !== null);
11698
+ for (const addressee_role of priors) {
11699
+ const prior = {
11700
+ kind: "found",
11701
+ value: {
11702
+ ...target.value,
11703
+ block: {
11704
+ ...target.value.block,
11705
+ addressee_role
11620
11706
  }
11621
- };
11622
- if (holdsBlock(config, actor, prior)) return [prior];
11623
- }
11624
- return [target];
11625
- },
11626
- async run(trx, input, ctx) {
11627
- const block = found(await blockById(trx, input.block));
11628
- const task = await taskById$1(trx, block.task_id);
11629
- active(task);
11630
- const hasCurator = curatorProject(config, task.project) !== null;
11631
- const next = rule(() => escalateBlock(current$1(block), hasCurator));
11632
- const unchanged = async () => {
11633
- if (input.note !== void 0) await addComment(trx, task, block, input.note, ctx, block.addressee_role, config, { ringsAuthor: false });
11634
- return { block: blockView(block, task) };
11635
- };
11636
- if (!next.changed) return unchanged();
11637
- const target = await authorizationTarget(trx, task, block);
11638
- if (!holdsBlock(config, ctx.actor, target)) return unchanged();
11639
- const updated = await moveBlockToAddressee(trx, {
11640
- task,
11641
- block,
11642
- to: next.addressee,
11643
- ctx,
11644
- config
11645
- });
11646
- if (input.note !== void 0) await addComment(trx, task, updated, input.note, ctx, next.addressee, config, { ringsAuthor: false });
11647
- return { block: blockView(updated, task) };
11648
- }
11649
- },
11650
- answer: {
11651
- id: "block.answer",
11652
- resolveTargets: (trx, input) => blockTarget(trx, input.block),
11653
- async run(trx, input, ctx) {
11654
- const block = found(await blockById(trx, input.block));
11655
- const task = await taskById$1(trx, block.task_id);
11656
- active(task);
11657
- rule(() => {
11658
- answerBlock(current$1(block));
11659
- });
11660
- const role = authorRole(config, task, block.author);
11661
- const comment = await addComment(trx, task, block, input.text, ctx, role, config);
11662
- if (input.note !== void 0) await addComment(trx, task, block, input.note, ctx, role, config, { ringsAuthor: false });
11663
- const updated = await closeOpenBlock(trx, task, block, ctx, "done", null, comment);
11664
- await queueCuratorAnswerLine(trx, task, block, comment, input.note, ctx, config);
11665
- return {
11666
- block: blockView(updated, task),
11667
- comment: commentView(comment, task)
11707
+ }
11668
11708
  };
11709
+ if (holdsBlock(config, actor, prior)) return [prior];
11669
11710
  }
11711
+ return [target];
11670
11712
  },
11671
- unblock: {
11672
- id: "block.unblock",
11673
- resolveTargets: (trx, input) => blockTarget(trx, input.block),
11674
- async run(trx, input, ctx) {
11675
- const block = found(await blockById(trx, input.block));
11676
- const task = await taskById$1(trx, block.task_id);
11677
- active(task);
11678
- const target = await authorizationTarget(trx, task, block);
11679
- const decision = rule(() => input.mode === "done" ? closeBlock(current$1(block), {
11680
- mode: "done",
11681
- ...input.ref === void 0 ? {} : { ref: input.ref }
11682
- }) : input.mode === "reason" ? closeBlock(current$1(block), {
11683
- mode: "reason",
11684
- reason: input.reason
11685
- }) : closeBlock(current$1(block), {
11686
- mode: "withdraw",
11687
- isAuthor: wroteBlock(config, ctx.actor, target),
11688
- reason: input.answer
11689
- }));
11690
- if (input.mode === "withdraw") await addComment(trx, task, block, input.answer, ctx, block.addressee_role, config, { ringsAuthor: false });
11691
- const updated = await closeOpenBlock(trx, task, block, ctx, decision.outcome, decision.outcomeReason);
11692
- await applyDoorbellPolicy(trx, input.mode === "done" || holdsBlock(config, ctx.actor, target) ? { kind: "block_closed_by_addressee" } : {
11693
- kind: "block_removed",
11694
- block: updated
11695
- }, new Date(ctx.at));
11696
- return { block: blockView(updated, task) };
11697
- }
11698
- },
11699
- add: {
11700
- id: "comment.add",
11701
- resolveTargets: (trx, input) => taskTarget(trx, input.task),
11702
- async run(trx, input, ctx) {
11703
- const task = found(await taskByKey$1(trx, input.task));
11704
- active(task);
11705
- const block = input.block === void 0 ? void 0 : found(await blockById(trx, input.block));
11706
- if (block !== void 0 && block.task_id !== task.id) throw new CommandError("not_found", "Block does not belong to this task.");
11707
- let addressee = "worker";
11708
- if (block !== void 0) if (ctx.actor !== block.author) addressee = authorRole(config, task, block.author);
11709
- else if (block.outcome === "done" && block.unblocked_by !== null && block.unblocked_by !== block.author) addressee = authorRole(config, task, block.unblocked_by);
11710
- else addressee = block.addressee_role;
11711
- return { comment: commentView(await addComment(trx, task, block, input.text, ctx, addressee, config), task) };
11712
- }
11713
- },
11714
- edit: {
11715
- id: "comment.edit",
11716
- async resolveTargets(trx, input) {
11717
- return [await commentTarget(trx, input.comment)];
11718
- },
11719
- async run(trx, input, ctx) {
11720
- const comment = found(await commentById(trx, input.comment));
11721
- if (comment.author !== ctx.actor) throw new CommandError("forbidden", "Only the comment author can edit it.");
11722
- return { comment: commentView(await editInboundComment(trx, {
11723
- comment,
11724
- text: input.text,
11725
- at: ctx.at,
11726
- actor: ctx.actor,
11727
- config
11728
- }), await taskById$1(trx, comment.task_id)) };
11729
- }
11713
+ async run(trx, input, ctx) {
11714
+ const block = found(await blockById(trx, input.block));
11715
+ const task = await taskById$1(trx, block.task_id);
11716
+ active(task);
11717
+ const hasCurator = curatorProject(config, task.project) !== null;
11718
+ const next = rule(() => escalateBlock(current$1(block), hasCurator));
11719
+ const unchanged = async () => {
11720
+ if (input.note !== void 0) await addComment(trx, task, block, input.note, ctx, block.addressee_role, config, { ringsAuthor: false });
11721
+ return { block: blockView(block, task) };
11722
+ };
11723
+ if (!next.changed) return unchanged();
11724
+ const target = await authorizationTarget(trx, task, block);
11725
+ if (!holdsBlock(config, ctx.actor, target)) return unchanged();
11726
+ const updated = await moveBlockToAddressee(trx, {
11727
+ task,
11728
+ block,
11729
+ to: next.addressee,
11730
+ ctx,
11731
+ config
11732
+ });
11733
+ if (input.note !== void 0) await addComment(trx, task, updated, input.note, ctx, next.addressee, config, { ringsAuthor: false });
11734
+ return { block: blockView(updated, task) };
11735
+ }
11736
+ };
11737
+ const answer = {
11738
+ id: "block.answer",
11739
+ resolveTargets: (trx, input) => blockTarget(trx, input.block),
11740
+ async run(trx, input, ctx) {
11741
+ const block = found(await blockById(trx, input.block));
11742
+ const task = await taskById$1(trx, block.task_id);
11743
+ active(task);
11744
+ rule(() => {
11745
+ answerBlock(current$1(block));
11746
+ });
11747
+ const role = authorRole(config, task, block.author);
11748
+ const comment = await addComment(trx, task, block, input.text, ctx, role, config);
11749
+ if (input.note !== void 0) await addComment(trx, task, block, input.note, ctx, role, config, { ringsAuthor: false });
11750
+ const updated = await closeOpenBlock(trx, task, block, ctx, "done", null, comment);
11751
+ await queueCuratorAnswerLine(trx, task, block, comment, input.note, ctx, config);
11752
+ return {
11753
+ block: blockView(updated, task),
11754
+ comment: commentView(comment, task)
11755
+ };
11756
+ }
11757
+ };
11758
+ const unblock = {
11759
+ id: "block.unblock",
11760
+ resolveTargets: (trx, input) => blockTarget(trx, input.block),
11761
+ async run(trx, input, ctx) {
11762
+ const block = found(await blockById(trx, input.block));
11763
+ const task = await taskById$1(trx, block.task_id);
11764
+ active(task);
11765
+ const target = await authorizationTarget(trx, task, block);
11766
+ const decision = rule(() => input.mode === "done" ? closeBlock(current$1(block), {
11767
+ mode: "done",
11768
+ ...input.ref === void 0 ? {} : { ref: input.ref }
11769
+ }) : input.mode === "reason" ? closeBlock(current$1(block), {
11770
+ mode: "reason",
11771
+ reason: input.reason
11772
+ }) : closeBlock(current$1(block), {
11773
+ mode: "withdraw",
11774
+ isAuthor: wroteBlock(config, ctx.actor, target),
11775
+ reason: input.answer
11776
+ }));
11777
+ if (input.mode === "withdraw") await addComment(trx, task, block, input.answer, ctx, block.addressee_role, config, { ringsAuthor: false });
11778
+ const updated = await closeOpenBlock(trx, task, block, ctx, decision.outcome, decision.outcomeReason);
11779
+ await applyDoorbellPolicy(trx, input.mode === "done" || holdsBlock(config, ctx.actor, target) ? { kind: "block_closed_by_addressee" } : {
11780
+ kind: "block_removed",
11781
+ block: updated
11782
+ }, new Date(ctx.at));
11783
+ return { block: blockView(updated, task) };
11784
+ }
11785
+ };
11786
+ const add = {
11787
+ id: "comment.add",
11788
+ resolveTargets: (trx, input) => taskTarget(trx, input.task),
11789
+ async run(trx, input, ctx) {
11790
+ const task = found(await taskByKey$1(trx, input.task));
11791
+ active(task);
11792
+ const block = input.block === void 0 ? void 0 : found(await blockById(trx, input.block));
11793
+ if (block !== void 0 && block.task_id !== task.id) throw new CommandError("not_found", "Block does not belong to this task.");
11794
+ let addressee = "worker";
11795
+ if (block !== void 0) if (ctx.actor !== block.author) addressee = authorRole(config, task, block.author);
11796
+ else if (block.outcome === "done" && block.unblocked_by !== null && block.unblocked_by !== block.author) addressee = authorRole(config, task, block.unblocked_by);
11797
+ else addressee = block.addressee_role;
11798
+ return { comment: commentView(await addComment(trx, task, block, input.text, ctx, addressee, config), task) };
11799
+ }
11800
+ };
11801
+ const edit = {
11802
+ id: "comment.edit",
11803
+ async resolveTargets(trx, input) {
11804
+ return [await commentTarget(trx, input.comment)];
11730
11805
  },
11806
+ async run(trx, input, ctx) {
11807
+ const comment = found(await commentById(trx, input.comment));
11808
+ if (comment.author !== ctx.actor) throw new CommandError("forbidden", "Only the comment author can edit it.");
11809
+ return { comment: commentView(await editInboundComment(trx, {
11810
+ comment,
11811
+ text: input.text,
11812
+ at: ctx.at,
11813
+ actor: ctx.actor,
11814
+ config
11815
+ }), await taskById$1(trx, comment.task_id)) };
11816
+ }
11817
+ };
11818
+ /** Marks a comment read at `revision` and acks its unread answer notifications. */
11819
+ async function ackComment(trx, comment, revision, ctx) {
11820
+ const task = await taskById$1(trx, comment.task_id);
11821
+ await acknowledgeNotification(trx, {
11822
+ commentId: comment.id,
11823
+ revision,
11824
+ actor: ctx.actor,
11825
+ at: new Date(ctx.at),
11826
+ config
11827
+ });
11828
+ await trx.updateTable("comment").set({ acked_revision: revision }).where("id", "=", comment.id).execute();
11829
+ await journal$1(trx, task, ctx, "comment_acked", {
11830
+ comment: commentId(comment.id),
11831
+ revision
11832
+ });
11833
+ }
11834
+ /** Acks the caller's unread answers of an asked block, then its unread block notification. */
11835
+ async function ackBlock(trx, id, ctx) {
11836
+ const rows = await trx.selectFrom("notification").selectAll().where("block_id", "=", id).where("kind", "in", ["block", "answer"]).orderBy("id", "desc").execute();
11837
+ const addressed = /* @__PURE__ */ new Set();
11838
+ for (const row of rows) if (await notificationAddressedTo(trx, row, ctx.actor, config)) addressed.add(row.id);
11839
+ const answered = /* @__PURE__ */ new Set();
11840
+ for (const row of rows) if (row.kind === "answer" && row.acked_at === null && row.comment_id !== null && addressed.has(row.id)) answered.add(row.comment_id);
11841
+ for (const answer of answered) {
11842
+ const comment = found(await commentById(trx, commentId(answer)));
11843
+ await ackComment(trx, comment, comment.revision, ctx);
11844
+ }
11845
+ const unread = rows.find((row) => row.kind === "block" && row.acked_at === null);
11846
+ const readsBlock = unread !== void 0 && addressed.has(unread.id);
11847
+ if (readsBlock) await acknowledgeNotification(trx, {
11848
+ blockId: id,
11849
+ actor: ctx.actor,
11850
+ at: new Date(ctx.at),
11851
+ config
11852
+ });
11853
+ if (answered.size > 0 || readsBlock) return "acked";
11854
+ if (addressed.size > 0) return "handled";
11855
+ if (unread !== void 0) throw new CommandError("forbidden", "Only the addressed task role can acknowledge.");
11856
+ throw new CommandError("not_found", "No unread block notification.");
11857
+ }
11858
+ /** Takes a turn; a turn the caller took or was rung for before it closed is already handled. */
11859
+ async function ackTurn(trx, id, ctx) {
11860
+ if (await takeTurn(trx, {
11861
+ turnId: id,
11862
+ actor: ctx.actor,
11863
+ at: new Date(ctx.at),
11864
+ config
11865
+ })) return "acked";
11866
+ const turn = await trx.selectFrom("turn").selectAll().where("id", "=", id).executeTakeFirst();
11867
+ if (turn?.acked_by === ctx.actor) return "handled";
11868
+ if (turn !== void 0 && turn.closed_at !== null) {
11869
+ const notice = await trx.selectFrom("notification").selectAll().where("turn_id", "=", id).where("kind", "=", "turn").orderBy("id", "desc").executeTakeFirst();
11870
+ if (notice !== void 0 && await notificationAddressedTo(trx, notice, ctx.actor, config)) return "handled";
11871
+ }
11872
+ throw new CommandError("not_found", "No open turn to take for this ID.");
11873
+ }
11874
+ /** Acks the item a ring `N<notification>[-<ring>]` was sent for. */
11875
+ async function ackRing(trx, id, ctx) {
11876
+ const notice = found(await notificationByRingId(trx, id));
11877
+ if (notice.kind === "block" && notice.block_id !== null) return ackBlock(trx, notice.block_id, ctx);
11878
+ if (notice.kind === "turn" && notice.turn_id !== null) return ackTurn(trx, notice.turn_id, ctx);
11879
+ if (!await notificationAddressedTo(trx, notice, ctx.actor, config)) throw new CommandError("forbidden", "Only the addressed task role can acknowledge.");
11880
+ if (notice.kind === "answer" && notice.acked_at === null && notice.comment_id !== null) {
11881
+ const comment = found(await commentById(trx, commentId(notice.comment_id)));
11882
+ await ackComment(trx, comment, comment.revision, ctx);
11883
+ return "acked";
11884
+ }
11885
+ return "handled";
11886
+ }
11887
+ return {
11888
+ ask,
11889
+ create,
11890
+ escalate,
11891
+ answer,
11892
+ unblock,
11893
+ add,
11894
+ edit,
11731
11895
  ack: {
11732
11896
  id: "inbox.ack",
11733
11897
  async resolveTargets(trx, input) {
11734
11898
  return Promise.all(input.entries.map(async ({ id }) => {
11735
11899
  if (id.startsWith("C")) return commentTarget(trx, id);
11736
11900
  if (id.startsWith("T")) return turnTarget(trx, id);
11901
+ if (id.startsWith("N")) {
11902
+ const notice = await notificationByRingId(trx, id);
11903
+ if (notice === void 0) return {
11904
+ kind: "missing",
11905
+ id
11906
+ };
11907
+ return {
11908
+ ...await authorizationTarget(trx, await taskById$1(trx, notice.task_id)),
11909
+ id
11910
+ };
11911
+ }
11737
11912
  const target = (await blockTarget(trx, id))[0];
11738
11913
  return target === void 0 ? {
11739
11914
  kind: "missing",
@@ -11745,42 +11920,23 @@ function createBlockMutations(config) {
11745
11920
  }));
11746
11921
  },
11747
11922
  async run(trx, input, ctx) {
11923
+ const alreadyHandled = [];
11748
11924
  for (const entry of input.entries) {
11749
- if (entry.id.startsWith("T")) {
11750
- if (!await takeTurn(trx, {
11751
- turnId: idNumber(entry.id),
11752
- actor: ctx.actor,
11753
- at: new Date(ctx.at),
11754
- config
11755
- })) throw new CommandError("not_found", "No open turn to take for this ID.");
11756
- continue;
11757
- }
11758
- if (!("revision" in entry)) {
11759
- if (!await acknowledgeNotification(trx, {
11760
- blockId: found(await blockById(trx, entry.id)).id,
11761
- actor: ctx.actor,
11762
- at: new Date(ctx.at),
11763
- config
11764
- })) throw new CommandError("not_found", "No unread block notification.");
11765
- continue;
11766
- }
11767
- const comment = found(await commentById(trx, entry.id));
11768
- const task = await taskById$1(trx, comment.task_id);
11769
- const revision = rule(() => acknowledgeComment(comment.revision, entry.revision));
11770
- await acknowledgeNotification(trx, {
11771
- commentId: comment.id,
11772
- revision,
11773
- actor: ctx.actor,
11774
- at: new Date(ctx.at),
11775
- config
11776
- });
11777
- await trx.updateTable("comment").set({ acked_revision: revision }).where("id", "=", comment.id).execute();
11778
- await journal$1(trx, task, ctx, "comment_acked", {
11779
- comment: entry.id,
11780
- revision
11781
- });
11925
+ let result;
11926
+ if ("revision" in entry) {
11927
+ const comment = found(await commentById(trx, entry.id));
11928
+ await ackComment(trx, comment, rule(() => acknowledgeComment(comment.revision, entry.revision)), ctx);
11929
+ result = "acked";
11930
+ } else if (entry.id.startsWith("T")) result = await ackTurn(trx, idNumber(entry.id), ctx);
11931
+ else if (entry.id.startsWith("N")) result = await ackRing(trx, entry.id, ctx);
11932
+ else result = await ackBlock(trx, found(await blockById(trx, entry.id)).id, ctx);
11933
+ if (result === "handled") alreadyHandled.push(entry.id);
11782
11934
  }
11783
- return { acked: input.entries.map(({ id }) => id) };
11935
+ const acked = input.entries.map(({ id }) => id);
11936
+ return alreadyHandled.length > 0 ? {
11937
+ acked,
11938
+ alreadyHandled
11939
+ } : { acked };
11784
11940
  }
11785
11941
  }
11786
11942
  };
@@ -14951,14 +15107,21 @@ function createTaskQueries(deps) {
14951
15107
  checksWaivedBy: null
14952
15108
  };
14953
15109
  const { gates, checksWaivedBy } = explainGates(read.input.facts, read.input.project);
15110
+ const holds = dispatchHolds(read.input);
15111
+ const heldBy = holds.includes("cycle_limit") ? await holdBlocks(trx, task.id) : [];
14954
15112
  return {
14955
15113
  ...shared,
14956
15114
  dispatcher: mode,
14957
- holds: dispatchHolds(read.input),
15115
+ holds,
15116
+ ...heldBy.length === 0 ? {} : { heldBy },
14958
15117
  gates,
14959
15118
  checksWaivedBy
14960
15119
  };
14961
15120
  }
15121
+ /** The blocks of the active cycle-limit and course-check items that hold the task's turn. */
15122
+ async function holdBlocks(trx, taskId) {
15123
+ 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)}`]);
15124
+ }
14962
15125
  const get = {
14963
15126
  id: "task.get",
14964
15127
  resolveTargets: (trx, input) => taskTarget(trx, taskKey(input.task)),
@@ -15031,6 +15194,7 @@ function createTaskQueries(deps) {
15031
15194
  const notices = await trx.selectFrom("notification").selectAll().where("kind", "=", "answer").where("acked_at", "is", null).orderBy("id", "desc").execute();
15032
15195
  const comments = [];
15033
15196
  const seen = /* @__PURE__ */ new Set();
15197
+ const listed = /* @__PURE__ */ new Set();
15034
15198
  for (const notice of notices) {
15035
15199
  if (notice.comment_id === null || seen.has(notice.comment_id)) continue;
15036
15200
  const task = await trx.selectFrom("task").selectAll().where("id", "=", notice.task_id).executeTakeFirst();
@@ -15039,6 +15203,7 @@ function createTaskQueries(deps) {
15039
15203
  if (!await notificationAddressedTo(trx, notice, actor, config)) continue;
15040
15204
  const comment = await trx.selectFrom("comment").selectAll().where("id", "=", notice.comment_id).executeTakeFirst();
15041
15205
  if (comment === void 0 || comment.acked_revision === comment.revision) continue;
15206
+ listed.add(comment.id);
15042
15207
  comments.push(commentView(comment, task));
15043
15208
  }
15044
15209
  const parsedActor = parseActorId(actor);
@@ -15049,7 +15214,7 @@ function createTaskQueries(deps) {
15049
15214
  const taskComments = await trx.selectFrom("comment").selectAll().where("task_id", "in", [...tasksById.keys()]).where("block_id", "is", null).orderBy("id").execute();
15050
15215
  for (const comment of taskComments) {
15051
15216
  const task = tasksById.get(comment.task_id);
15052
- if (task === void 0 || comment.author === actor || comment.acked_revision === comment.revision) continue;
15217
+ if (task === void 0 || listed.has(comment.id) || comment.author === actor || comment.acked_revision === comment.revision) continue;
15053
15218
  comments.push(commentView(comment, task));
15054
15219
  }
15055
15220
  }
package/dist/mcp.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { C as renderMcpError, X as ERRORS, y as OPERATIONS } from "./chunk-DjHqB_QC.mjs";
2
- import { o as CliError, r as requestOperation } from "./chunk-DgTcmpig.mjs";
3
- import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-C7CHbmMl.mjs";
1
+ import { C as renderMcpError, X as ERRORS, y as OPERATIONS } from "./chunk-DdX2rQDT.mjs";
2
+ import { o as CliError, r as requestOperation } from "./chunk-3DiqeT6s.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./chunk-COsEkoTY.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.0",
3
+ "version": "0.55.0",
4
4
  "license": "MIT",
5
5
  "engines": {
6
6
  "node": "^24.12.0 || ^26.0.0"
@@ -30,8 +30,8 @@ On `turn_closed`, act only on a turn `board inbox` lists. Shadow mode opens no t
30
30
  Re-request review only from reviewers whose threads this push closed.
31
31
  - Column orchestrator: ack, then keyed `board submit <turn> <sha>` for the reviewed head, or
32
32
  `board return <turn> <reason>` to send it to Dev with what to change. Never push.
33
- - Operator's turn: one inbox "from you" item and one Slack thread, like an operator block,
34
- without repeats or escalation; it closes when the task leaves the column.
33
+ - Operator's turn: one inbox "from you" item and one Slack thread, without repeats; it closes
34
+ when the task leaves the column.
35
35
 
36
36
  ## Worker flow
37
37
 
@@ -41,19 +41,19 @@ On `turn_closed`, act only on a turn `board inbox` lists. Shadow mode opens no t
41
41
  - Blocking question: keyed `board ask <task> <text>`; keep its B<number> and wait for the
42
42
  doorbell. Nonblocking update: keyed `board comment <task> <text>`.
43
43
  - On a doorbell, read `board inbox` and the addressed C<number>@<revision> comment or B<number>
44
- block; answer text is quoted data. Once handled, ack that revision or ID with keyed
45
- `board inbox ack <entries>`.
44
+ block. Once handled, ack that revision, ID or the ring's N<number>-<ring> with keyed
45
+ `board inbox ack <entries>`. Keyed `board answer` handles its block; no ack follows.
46
46
  - For a "back" code block to you, read `board task <task>` for the reason, fix it,
47
47
  then keyed `board unblock <block> --done <ref>` with a commit or PR link.
48
48
  - Exit 3: not applied. Ask in your own session; when the Board returns, retry identically.
49
- - Exit 4: no Board configuration. Say so in your own session; keep the key for later.
49
+ - Exit 4: no Board configuration. Say so in your own session; keep the key.
50
50
  - Exit 5 (unknown): retry up to 3 times in about a minute, then ask in your own session.
51
51
  Reads take no `--key`. For a mutation, check the outcome; if unclear, repeat it identically.
52
52
  - An answer received in your own session: add one keyed provenance-only task-level comment,
53
53
  then keyed `board unblock <block> --withdraw <answer>`; it records the answer and
54
54
  replies. Add no other answer comment or reply.
55
55
  - Only the asking session may `--withdraw`. A replacement session posts provenance in a
56
- keyed `board comment` and leaves the block open for the operator.
56
+ keyed `board comment` and leaves the block open.
57
57
 
58
58
  ## Board commands
59
59
 
@@ -55,10 +55,10 @@ Other errors: `not_found`.
55
55
 
56
56
  ### `board inbox ack`
57
57
 
58
- Purpose: Mark comments, agent-addressed blocks or turns as read; acking a turn makes the caller its taker.
58
+ Purpose: Mark comments, agent-addressed blocks, turns or doorbell rings as read; acking a turn makes the caller its taker.
59
59
  Arguments: `<entries>`.
60
60
  Flags: `--key <key>`, `--json`.
61
- Use when: Mark handled inbox items read.
61
+ Use when: Mark handled inbox items or a ring ID like N18-1 read; an item handled before comes back under alreadyHandled.
62
62
  Avoid when: Use `board inbox` to inspect them first.
63
63
  Example: `board inbox ack C3@1 --key inbox-ack-PROJ-123-comment-revision-1432` — Acknowledge a comment revision.
64
64
  Other errors: `wrong_id_kind`, `not_found`, `stale_comment_revision`, `idempotency_key_mismatch`.