spur-board 0.33.0 → 0.34.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { G as configSchema, K as requiredSecretKeys, P as ERRORS, l as roleCanUseOperation, q as SLACK_BOT_SCOPES, r as SYSTEMD_SERVICE_SETTINGS, u as OPERATIONS } from "./src-8BDCEAvV.mjs";
2
- import { a as errorExitCode, i as CliError, n as requestOperation, o as renderCliError, r as requestTokenEnrollment, s as escapeTerminalControls } from "./client-uUHdF1cr.mjs";
3
- import { a as memoryVerdictCache, c as loadClientConfig, d as resolveDaemonAddress, i as fileVerdictCache, l as loadEnrollmentConfig, n as cliPackageVersion, o as configFile, s as dataDirectory, t as checkCatalog, u as readConfiguredPort } from "./config-wjhrCN29.mjs";
1
+ import { F as ERRORS, J as SLACK_BOT_SCOPES, K as configSchema, l as roleCanUseOperation, q as requiredSecretKeys, r as SYSTEMD_SERVICE_SETTINGS, u as OPERATIONS } from "./src-B2L79Nf9.mjs";
2
+ import { a as errorExitCode, i as CliError, n as requestOperation, o as renderCliError, r as requestTokenEnrollment, s as escapeTerminalControls } from "./client-dHOLiNKd.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, d as resolveDaemonAddress, i as fileVerdictCache, l as loadEnrollmentConfig, n as cliPackageVersion, o as configFile, s as dataDirectory, t as checkCatalog, u as readConfiguredPort } from "./config-BsZv50VN.mjs";
4
4
  import { createHash, randomBytes, randomUUID } from "node:crypto";
5
5
  import { accessSync, chmodSync, closeSync, constants, cpSync, existsSync, ftruncateSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
6
6
  import { homedir, hostname, userInfo } from "node:os";
@@ -1,4 +1,4 @@
1
- import { I as errorContextSchema, L as errorEnvelopeSchema, P as ERRORS, f as renderJsonError, z as successEnvelopeSchema } from "./src-8BDCEAvV.mjs";
1
+ import { B as successEnvelopeSchema, F as ERRORS, L as errorContextSchema, R as errorEnvelopeSchema, p as renderJsonError } from "./src-B2L79Nf9.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { z } from "zod";
4
4
  import { request } from "node:http";
package/dist/client.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { n as requestOperation, r as requestTokenEnrollment, t as fetchCatalogVersion } from "./client-uUHdF1cr.mjs";
1
+ import { n as requestOperation, r as requestTokenEnrollment, t as fetchCatalogVersion } from "./client-dHOLiNKd.mjs";
2
2
  export { fetchCatalogVersion, requestOperation, requestTokenEnrollment };
@@ -1,5 +1,5 @@
1
- import { G as configSchema, c as buildCatalogSnapshot, u as OPERATIONS } from "./src-8BDCEAvV.mjs";
2
- import { i as CliError, t as fetchCatalogVersion } from "./client-uUHdF1cr.mjs";
1
+ import { K as configSchema, c as buildCatalogSnapshot, u as OPERATIONS } from "./src-B2L79Nf9.mjs";
2
+ import { i as CliError, t as fetchCatalogVersion } from "./client-dHOLiNKd.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/daemon.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { A as errorCodeOf, C as SESSION_STATUSES, D as ticketFactsSchema, E as sessionFactsSchema, F as err, G as configSchema, K as requiredSecretKeys, M as parseRef$1, N as taskKeySchema, O as actorIdSchema, P as ERRORS, R as ok, S as SESSION_HEALTH_STATES, T as prRefSchema, U as DEFAULT_SLACK_COMMAND, V as DEFAULT_LINK, W as RESERVED_PROJECT, _ as interactionRefSchema, a as batchSchema, b as EVENT_KINDS, c as buildCatalogSnapshot, d as renderHttpProblem, g as inboundEventSchema, h as conversationRefSchema, i as AdapterError, j as parseActorId, k as encodeActorId, l as roleCanUseOperation, m as SPACE_IDS, n as BOARD_TICK_MS, o as entityRefSchema, q as SLACK_BOT_SCOPES, s as sourceCursorSchema, t as assertNever, u as OPERATIONS, v as messageRefSchema, w as prFactsSchema, x as eventPayloadSchemas, y as userIdSchema, z as successEnvelopeSchema } from "./src-8BDCEAvV.mjs";
1
+ import { A as encodeActorId, B as successEnvelopeSchema, C as SESSION_HEALTH_STATES, D as sessionFactsSchema, E as prRefSchema, F as ERRORS, G as RESERVED_PROJECT, H as DEFAULT_LINK, I as err, J as SLACK_BOT_SCOPES, K as configSchema, M as parseActorId, N as parseRef$1, O as ticketFactsSchema, P as taskKeySchema, S as eventPayloadSchemas, T as prFactsSchema, W as DEFAULT_SLACK_COMMAND, _ as inboundEventSchema, a as batchSchema, b as userIdSchema, c as buildCatalogSnapshot, d as turnHandedSchema, f as renderHttpProblem, g as conversationRefSchema, h as SPACE_IDS, i as AdapterError, j as errorCodeOf, k as actorIdSchema, l as roleCanUseOperation, n as BOARD_TICK_MS, o as entityRefSchema, q as requiredSecretKeys, s as sourceCursorSchema, t as assertNever, u as OPERATIONS, v as interactionRefSchema, w as SESSION_STATUSES, x as EVENT_KINDS, y as messageRefSchema, z as ok } from "./src-B2L79Nf9.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { closeSync, existsSync, fstatSync, fsyncSync, ftruncateSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeSync } from "node:fs";
@@ -8210,7 +8210,8 @@ const ITEM_KINDS = [
8210
8210
  "inbound_failure",
8211
8211
  "inbound_gap",
8212
8212
  "board_observation",
8213
- "worker_ended"
8213
+ "worker_ended",
8214
+ "turn"
8214
8215
  ];
8215
8216
  const ITEM_POLICY = {
8216
8217
  token_request: {
@@ -8289,6 +8290,14 @@ const ITEM_POLICY = {
8289
8290
  priority: 4,
8290
8291
  buttons: "item",
8291
8292
  reconciled: true
8293
+ },
8294
+ /** A turn whose executor is the operator; `closeTurns` clears it. */
8295
+ turn: {
8296
+ retry: "none",
8297
+ feed: true,
8298
+ priority: 4,
8299
+ buttons: "item",
8300
+ reconciled: false
8292
8301
  }
8293
8302
  };
8294
8303
  /** Guards a stored kind: the column is free text and old or hand-written rows may hold others. */
@@ -9406,6 +9415,15 @@ async function registerBlockNotification(trx, block, at) {
9406
9415
  created_at: at.toISOString()
9407
9416
  }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
9408
9417
  }
9418
+ /** The block of a block-owned notification; the store CHECK gives every non-turn kind one. */
9419
+ function noticeBlockId(n) {
9420
+ if (n.block_id === null) throw new Error(`notification of kind ${n.kind} has no block`);
9421
+ return n.block_id;
9422
+ }
9423
+ /** What a notification is about, as the operator item names it. */
9424
+ function noticeRef(n, task) {
9425
+ return n.kind === "turn" ? `turn T${String(n.turn_id)} on ${task.key}` : `block B${String(noticeBlockId(n))} on ${task.key}`;
9426
+ }
9409
9427
  /** Register a one-ring notice that a block its addressee held was closed by someone else. */
9410
9428
  async function registerRemovedNotification(trx, block, at) {
9411
9429
  if (block.addressee_role === "operator") return;
@@ -9589,7 +9607,7 @@ async function endNotification(trx, n, task, end) {
9589
9607
  const addressee = parseAddressee(n.role);
9590
9608
  if (n.kind === "block" && addressee.kind === "curator") await moveBlockToAddressee(trx, {
9591
9609
  task,
9592
- block: await trx.selectFrom("block").selectAll().where("id", "=", n.block_id).executeTakeFirstOrThrow(),
9610
+ block: await trx.selectFrom("block").selectAll().where("id", "=", noticeBlockId(n)).executeTakeFirstOrThrow(),
9593
9611
  to: "operator",
9594
9612
  reason,
9595
9613
  ctx: {
@@ -9599,7 +9617,7 @@ async function endNotification(trx, n, task, end) {
9599
9617
  config
9600
9618
  });
9601
9619
  else if (n.kind !== "removed" && session !== null) {
9602
- const blockRef = `block B${String(n.block_id)} on ${task.key}`;
9620
+ const blockRef = noticeRef(n, task);
9603
9621
  const answer = `Answer to ${blockRef} was not`;
9604
9622
  const holder = `${addressee.kind} ${session}`;
9605
9623
  await raiseItem(trx, {
@@ -9660,9 +9678,11 @@ function noRecipientEnd(n) {
9660
9678
  /** A ring never carries comment or reason text: only where to look. */
9661
9679
  async function ringText(trx, n, task, ring) {
9662
9680
  const suffix = `(N${String(n.id)}-${String(ring)})`;
9663
- if (n.kind !== "removed") return `${task.key} block B${String(n.block_id)}: check board inbox ${suffix}`;
9664
- const block = await trx.selectFrom("block").select("unblocked_by").where("id", "=", n.block_id).executeTakeFirstOrThrow();
9665
- return `${task.key} block B${String(n.block_id)} was removed by ${block.unblocked_by ?? "system"}; see board task ${task.key} ${suffix}`;
9681
+ if (n.kind === "turn") return `${task.key} turn T${String(n.turn_id)}: check board inbox ${suffix}`;
9682
+ const blockId = noticeBlockId(n);
9683
+ if (n.kind !== "removed") return `${task.key} block B${String(blockId)}: check board inbox ${suffix}`;
9684
+ const block = await trx.selectFrom("block").select("unblocked_by").where("id", "=", blockId).executeTakeFirstOrThrow();
9685
+ return `${task.key} block B${String(blockId)} was removed by ${block.unblocked_by ?? "system"}; see board task ${task.key} ${suffix}`;
9666
9686
  }
9667
9687
  /** Notifications reconcile looks at: unacked, not exhausted, due, on a task not archived. */
9668
9688
  function dueNotifications(db, at) {
@@ -9789,6 +9809,7 @@ async function acknowledgeNotification(trx, input) {
9789
9809
  let query = trx.selectFrom("notification").selectAll().where("acked_at", "is", null);
9790
9810
  if (input.blockId !== void 0) query = query.where("block_id", "=", input.blockId).where("kind", "=", "block");
9791
9811
  else if (input.commentId !== void 0) query = query.where("comment_id", "=", input.commentId).where("kind", "=", "answer");
9812
+ else if (input.turnId !== void 0) query = query.where("turn_id", "=", input.turnId).where("kind", "=", "turn");
9792
9813
  else return false;
9793
9814
  const notices = await query.orderBy("id", "desc").execute();
9794
9815
  const n = notices[0];
@@ -9828,13 +9849,111 @@ async function workerNotificationAddressedTo(trx, n, session, config) {
9828
9849
  return await liveSession(trx, n.recipient_session) !== void 0 ? session === n.recipient_session : (await selectNotificationRecipient(trx, n, config))?.id === session;
9829
9850
  }
9830
9851
  async function closeBlockNotification(trx, blockId, at) {
9831
- const closed = await trx.updateTable("notification").set({ acked_at: at.toISOString() }).where("block_id", "=", blockId).where("kind", "=", "block").where("acked_at", "is", null).returning(["kind", "source_key"]).execute();
9852
+ await closeOwnedNotifications(trx, "block", blockId, at);
9853
+ }
9854
+ /** Ends a turn's ring series for good: acked, and its exhaustion item cleared by the system. */
9855
+ async function closeTurnNotification(trx, turnId, at) {
9856
+ await closeOwnedNotifications(trx, "turn", turnId, at);
9857
+ }
9858
+ async function closeOwnedNotifications(trx, kind, ownerId, at) {
9859
+ const closed = await trx.updateTable("notification").set({ acked_at: at.toISOString() }).where(kind === "block" ? "block_id" : "turn_id", "=", ownerId).where("kind", "=", kind).where("acked_at", "is", null).returning(["kind", "source_key"]).execute();
9832
9860
  for (const row of closed) {
9833
9861
  const item = await trx.selectFrom("operator_item").select("id").where("item_key", "=", exhaustedItemKey(row)).where("cleared_at", "is", null).executeTakeFirst();
9834
9862
  if (item !== void 0) await clearItem(trx, item.id, at);
9835
9863
  }
9836
9864
  }
9837
9865
  //#endregion
9866
+ //#region ../core/src/app/turns.ts
9867
+ const handedSchema = z.array(turnHandedSchema);
9868
+ const turnItemKey = (turnId) => `turn:${String(turnId)}`;
9869
+ /** The feedback a stored turn handed over. */
9870
+ function turnHanded(turn) {
9871
+ return parseJson(handedSchema, turn.handed);
9872
+ }
9873
+ /** The newest notification of a turn; an operator turn has none. */
9874
+ async function turnNotification(trx, turnId) {
9875
+ return trx.selectFrom("notification").selectAll().where("turn_id", "=", turnId).where("kind", "=", "turn").orderBy("id", "desc").executeTakeFirst();
9876
+ }
9877
+ /**
9878
+ * Takes a turn for `actor`. False for a missing, closed, operator or taken worker turn. An
9879
+ * untaken turn needs its unread notification addressed to the actor; a taken orchestrator turn
9880
+ * may be taken over by whoever its notification is now addressed to. Others get `forbidden`.
9881
+ */
9882
+ async function takeTurn(trx, input) {
9883
+ const { turnId, actor, at, config } = input;
9884
+ const turn = await trx.selectFrom("turn").selectAll().where("id", "=", turnId).executeTakeFirst();
9885
+ if (turn === void 0 || turn.closed_at !== null || turn.role === "operator") return false;
9886
+ if (turn.acked_at === null) {
9887
+ if (!await acknowledgeNotification(trx, {
9888
+ turnId,
9889
+ actor,
9890
+ at,
9891
+ config
9892
+ })) return false;
9893
+ } else {
9894
+ if (parseAddressee(turn.role).kind !== "orchestrator") return false;
9895
+ const notice = await turnNotification(trx, turnId);
9896
+ if (notice === void 0 || !await notificationAddressedTo(trx, notice, actor, config)) throw new CommandError("forbidden", "Only the addressed task role can take this turn.");
9897
+ }
9898
+ await trx.updateTable("turn").set({
9899
+ acked_by: actor,
9900
+ acked_at: at.toISOString()
9901
+ }).where("id", "=", turnId).execute();
9902
+ return true;
9903
+ }
9904
+ /**
9905
+ * Closes every unclosed turn of a task: its rings stop and its items end as "condition ended".
9906
+ * A ring already queued is dropped by the sender (`ringStillCurrent`).
9907
+ */
9908
+ async function closeTurns(trx, input) {
9909
+ const { taskId, reason, at } = input;
9910
+ const closed = await trx.updateTable("turn").set({
9911
+ closed_at: at.toISOString(),
9912
+ closed_reason: reason
9913
+ }).where("task_id", "=", taskId).where("closed_at", "is", null).returning("id").execute();
9914
+ for (const { id } of closed) {
9915
+ await closeTurnNotification(trx, id, at);
9916
+ const item = await trx.selectFrom("operator_item").select("id").where("item_key", "=", turnItemKey(id)).where("cleared_at", "is", null).executeTakeFirst();
9917
+ if (item !== void 0) await clearItem(trx, item.id, at);
9918
+ }
9919
+ }
9920
+ /** Whether `left` is newer than `right` by `postedAt` instant, then by id. Compared, not subtracted. */
9921
+ function isNewer(left, right) {
9922
+ const a = Date.parse(left.postedAt);
9923
+ const b = Date.parse(right.postedAt);
9924
+ return a !== b ? a > b : left.id > right.id;
9925
+ }
9926
+ /**
9927
+ * Per requested PR, the newest feedback any turn of its linked tasks handed over, acked or not,
9928
+ * closed or not, so the cursor never moves back. A PR with none gets no entry.
9929
+ */
9930
+ async function turnFeedbackCursors(db, prs) {
9931
+ if (prs.length === 0) return [];
9932
+ const rows = await db.selectFrom("turn").innerJoin("link", "link.task_id", "turn.task_id").select([
9933
+ "link.repo",
9934
+ "link.number",
9935
+ "turn.handed"
9936
+ ]).where("link.entity", "=", "pr").where("link.banned", "=", 0).where(sql`lower(link.repo)`, "in", prs.map((pr) => pr.repo.toLowerCase())).execute();
9937
+ const cursors = [];
9938
+ for (const ref of prs) {
9939
+ const repo = ref.repo.toLowerCase();
9940
+ let best;
9941
+ for (const row of rows) {
9942
+ if (row.repo?.toLowerCase() !== repo || row.number !== ref.number) continue;
9943
+ for (const entry of turnHanded(row)) {
9944
+ if (entry.repo.toLowerCase() !== repo || entry.number !== ref.number) continue;
9945
+ if (best === void 0 || isNewer(entry, best)) best = entry;
9946
+ }
9947
+ }
9948
+ if (best !== void 0) cursors.push({
9949
+ ref,
9950
+ id: best.id,
9951
+ postedAt: best.postedAt
9952
+ });
9953
+ }
9954
+ return cursors;
9955
+ }
9956
+ //#endregion
9838
9957
  //#region ../core/src/app/blocks.ts
9839
9958
  const idNumber = (id) => Number(id.slice(1));
9840
9959
  const blockId$1 = (id) => `B${String(id)}`;
@@ -9897,6 +10016,17 @@ async function blockTarget(trx, id) {
9897
10016
  const block = await blockById(trx, id);
9898
10017
  return [await authorizationTarget(trx, block === void 0 ? void 0 : await taskById(trx, block.task_id), block)];
9899
10018
  }
10019
+ async function turnTarget(trx, id) {
10020
+ const turn = await trx.selectFrom("turn").select("task_id").where("id", "=", idNumber(id)).executeTakeFirst();
10021
+ if (turn === void 0) return {
10022
+ kind: "missing",
10023
+ id
10024
+ };
10025
+ return {
10026
+ ...await authorizationTarget(trx, await taskById(trx, turn.task_id)),
10027
+ id
10028
+ };
10029
+ }
9900
10030
  async function commentTarget(trx, id) {
9901
10031
  const comment = await commentById(trx, id);
9902
10032
  return {
@@ -10301,10 +10431,7 @@ function createBlockMutations(config) {
10301
10431
  async resolveTargets(trx, input) {
10302
10432
  return Promise.all(input.entries.map(async ({ id }) => {
10303
10433
  if (id.startsWith("C")) return commentTarget(trx, id);
10304
- if (id.startsWith("T")) return {
10305
- kind: "missing",
10306
- id
10307
- };
10434
+ if (id.startsWith("T")) return turnTarget(trx, id);
10308
10435
  const target = (await blockTarget(trx, id))[0];
10309
10436
  return target === void 0 ? {
10310
10437
  kind: "missing",
@@ -10317,6 +10444,15 @@ function createBlockMutations(config) {
10317
10444
  },
10318
10445
  async run(trx, input, ctx) {
10319
10446
  for (const entry of input.entries) {
10447
+ if (entry.id.startsWith("T")) {
10448
+ if (!await takeTurn(trx, {
10449
+ turnId: idNumber(entry.id),
10450
+ actor: ctx.actor,
10451
+ at: new Date(ctx.at),
10452
+ config
10453
+ })) throw new CommandError("not_found", "No open turn to take for this ID.");
10454
+ continue;
10455
+ }
10320
10456
  if (!("revision" in entry)) {
10321
10457
  if (!await acknowledgeNotification(trx, {
10322
10458
  blockId: found(await blockById(trx, entry.id)).id,
@@ -10351,8 +10487,8 @@ function createBlockMutations(config) {
10351
10487
  //#region ../core/src/app/archive.ts
10352
10488
  /**
10353
10489
  * Takes a task off the board in the caller's transaction: closes its open blocks with outcome
10354
- * `archived`, clears its board-derived items, cancels its unsent doorbells and journals
10355
- * `task_archived`. Callers set their own extra columns (manual flags, the Done slot).
10490
+ * `archived` and its unclosed turns, clears its board-derived items, cancels its unsent doorbells
10491
+ * and journals `task_archived`. Callers set their own extra columns (manual flags, the Done slot).
10356
10492
  */
10357
10493
  async function archiveTask(trx, input) {
10358
10494
  const { task, reason, actor, at } = input;
@@ -10362,6 +10498,11 @@ async function archiveTask(trx, input) {
10362
10498
  };
10363
10499
  const blocks = await trx.selectFrom("block").selectAll().where("task_id", "=", task.id).where("state", "=", "open").orderBy("id").execute();
10364
10500
  for (const block of blocks) await closeOpenBlock(trx, task, block, ctx, "archived", null);
10501
+ await closeTurns(trx, {
10502
+ taskId: task.id,
10503
+ reason: "archived",
10504
+ at: new Date(at)
10505
+ });
10365
10506
  const items = await trx.selectFrom("operator_item").select("id").where("kind", "in", RECONCILED_KINDS).where("task_id", "=", task.id).where("cleared_at", "is", null).orderBy("id").execute();
10366
10507
  for (const item of items) await clearItem(trx, item.id, new Date(at), actor);
10367
10508
  const comments = await trx.selectFrom("comment").select("id").where("task_id", "=", task.id).execute();
@@ -11736,50 +11877,82 @@ function createTaskQueries(config) {
11736
11877
  const parsed = parseRef$1(key, "task");
11737
11878
  return parsed.ok && parsed.value.kind === "task" && parsed.value.form === "github-short" ? canonicalKey(config, key).key : key;
11738
11879
  };
11739
- return {
11740
- get: {
11741
- id: "task.get",
11742
- resolveTargets: (trx, input) => taskTarget(trx, taskKey(input.task)),
11743
- async run(trx, input) {
11744
- const task = await taskByKey(trx, taskKey(input.task));
11745
- const [blocks, comments, links] = await Promise.all([
11746
- trx.selectFrom("block").selectAll().where("task_id", "=", task.id).orderBy("id").execute(),
11747
- trx.selectFrom("comment").selectAll().where("task_id", "=", task.id).orderBy("id").execute(),
11748
- trx.selectFrom("link").selectAll().where("task_id", "=", task.id).where("banned", "=", 0).orderBy("id").execute()
11749
- ]);
11750
- return {
11751
- task: taskView(task),
11752
- links: links.map(linkView),
11753
- blocks: blocks.map((block) => blockView(block, task)),
11754
- comments: comments.map((comment) => commentView(comment, task))
11755
- };
11756
- }
11757
- },
11758
- history: {
11759
- id: "task.history",
11760
- resolveTargets: (trx, input) => taskTarget(trx, taskKey(input.task)),
11761
- async run(trx, input) {
11762
- const task = await taskByKey(trx, taskKey(input.task));
11763
- const events = (await trx.selectFrom("event").selectAll().where("task_id", "=", task.id).orderBy("id").execute()).flatMap((row) => {
11764
- const kind = EVENT_KINDS.find((candidate) => candidate === row.kind);
11765
- if (kind === void 0) return [];
11766
- const actorRef = row.actor_ref === null ? void 0 : parseJson(actorRefSchema, row.actor_ref);
11767
- return [{
11768
- at: row.at,
11769
- kind,
11770
- actor: encodeActorId({
11771
- actor: row.actor,
11772
- actorRef
11773
- }),
11774
- summary: linkSummary(kind, row.payload) ?? EVENT_SUMMARIES[kind]
11775
- }];
11776
- });
11777
- return {
11778
- task: taskView(task),
11779
- events
11780
- };
11880
+ const get = {
11881
+ id: "task.get",
11882
+ resolveTargets: (trx, input) => taskTarget(trx, taskKey(input.task)),
11883
+ async run(trx, input) {
11884
+ const task = await taskByKey(trx, taskKey(input.task));
11885
+ const [blocks, comments, links] = await Promise.all([
11886
+ trx.selectFrom("block").selectAll().where("task_id", "=", task.id).orderBy("id").execute(),
11887
+ trx.selectFrom("comment").selectAll().where("task_id", "=", task.id).orderBy("id").execute(),
11888
+ trx.selectFrom("link").selectAll().where("task_id", "=", task.id).where("banned", "=", 0).orderBy("id").execute()
11889
+ ]);
11890
+ return {
11891
+ task: taskView(task),
11892
+ links: links.map(linkView),
11893
+ blocks: blocks.map((block) => blockView(block, task)),
11894
+ comments: comments.map((comment) => commentView(comment, task))
11895
+ };
11896
+ }
11897
+ };
11898
+ const history = {
11899
+ id: "task.history",
11900
+ resolveTargets: (trx, input) => taskTarget(trx, taskKey(input.task)),
11901
+ async run(trx, input) {
11902
+ const task = await taskByKey(trx, taskKey(input.task));
11903
+ const events = (await trx.selectFrom("event").selectAll().where("task_id", "=", task.id).orderBy("id").execute()).flatMap((row) => {
11904
+ const kind = EVENT_KINDS.find((candidate) => candidate === row.kind);
11905
+ if (kind === void 0) return [];
11906
+ const actorRef = row.actor_ref === null ? void 0 : parseJson(actorRefSchema, row.actor_ref);
11907
+ return [{
11908
+ at: row.at,
11909
+ kind,
11910
+ actor: encodeActorId({
11911
+ actor: row.actor,
11912
+ actorRef
11913
+ }),
11914
+ summary: linkSummary(kind, row.payload) ?? EVENT_SUMMARIES[kind]
11915
+ }];
11916
+ });
11917
+ return {
11918
+ task: taskView(task),
11919
+ events
11920
+ };
11921
+ }
11922
+ };
11923
+ /**
11924
+ * Unclosed agent turns the caller may take or has taken: an untaken one addressed to it, one it
11925
+ * took, and a taken orchestrator turn it may take over. At most one per task.
11926
+ */
11927
+ async function inboxTurns(trx, projects, actor) {
11928
+ if (parseActorId(actor)?.actor !== "agent" || projects.size === 0) return [];
11929
+ const rows = await trx.selectFrom("turn").innerJoin("task", "task.id", "turn.task_id").selectAll("turn").select("task.key").where("task.project", "in", [...projects]).where("turn.closed_at", "is", null).where("turn.role", "!=", "operator").orderBy("turn.id").execute();
11930
+ const turns = [];
11931
+ for (const turn of rows) {
11932
+ if (turn.acked_by !== actor) {
11933
+ const notice = await turnNotification(trx, turn.id);
11934
+ const mayTake = turn.acked_at === null ? notice?.acked_at === null : turn.role.startsWith("orchestrator:");
11935
+ if (notice === void 0 || !mayTake || !await notificationAddressedTo(trx, notice, actor, config)) continue;
11781
11936
  }
11782
- },
11937
+ turns.push({
11938
+ id: `T${String(turn.id)}`,
11939
+ task: turn.key,
11940
+ column: turn.column,
11941
+ addressee: turn.role,
11942
+ reason: turn.reason,
11943
+ handed: turnHanded(turn),
11944
+ at: turn.created_at,
11945
+ taken: turn.acked_by === null || turn.acked_at === null ? null : {
11946
+ by: turn.acked_by,
11947
+ at: turn.acked_at
11948
+ }
11949
+ });
11950
+ }
11951
+ return turns;
11952
+ }
11953
+ return {
11954
+ get,
11955
+ history,
11783
11956
  inbox: {
11784
11957
  id: "inbox.get",
11785
11958
  resolveTargets(_trx, input, actor) {
@@ -11828,7 +12001,7 @@ function createTaskQueries(config) {
11828
12001
  return {
11829
12002
  comments,
11830
12003
  blocks,
11831
- turns: []
12004
+ turns: await inboxTurns(trx, projects, actor)
11832
12005
  };
11833
12006
  }
11834
12007
  }
@@ -11960,7 +12133,7 @@ async function enqueueLiveAfterFirstPoll(trx, input) {
11960
12133
  const value = JSON.stringify(input.productVersion);
11961
12134
  if ((await trx.selectFrom("meta").select("value").where("key", "=", LIVE_VERSION_KEY).executeTakeFirst())?.value === value) return;
11962
12135
  const tasks = await trx.selectFrom("task").select(sql`count(*)`.as("count")).where("membership", "!=", "archived").executeTakeFirstOrThrow();
11963
- const items = await trx.selectFrom("operator_item").select(sql`count(*)`.as("count")).where("cleared_at", "is", null).executeTakeFirstOrThrow();
12136
+ const items = await trx.selectFrom("operator_item").select(sql`count(*)`.as("count")).where("cleared_at", "is", null).where("line_outbox_id", "is not", null).executeTakeFirstOrThrow();
11964
12137
  const text = `spur-board is live: ${String(tasks.count)} tasks, ${String(items.count)} for you`;
11965
12138
  await enqueueLiveFeedLine(trx, {
11966
12139
  version: input.productVersion,
@@ -12397,6 +12570,11 @@ async function ticket(trx, config, fact, at, source) {
12397
12570
  archive_reason: "manual"
12398
12571
  }).where("id", "=", pending.id).execute();
12399
12572
  await emit(trx, "task_archived", pending.project, pending.id, at, { reason: "manual" });
12573
+ await closeTurns(trx, {
12574
+ taskId: pending.id,
12575
+ reason: "archived",
12576
+ at: new Date(at)
12577
+ });
12400
12578
  await moveOpenWork(trx, pending.id, task.id);
12401
12579
  await trx.updateTable("task").set({
12402
12580
  key: fact.key,
@@ -12755,9 +12933,11 @@ function createObservationCore(deps) {
12755
12933
  })));
12756
12934
  }
12757
12935
  const misses = await store.db.selectFrom("source_miss").selectAll().where("source", "=", source).execute();
12936
+ const requested = [...new Map(prs.map((ref) => [refKey(ref), ref])).values()];
12937
+ const feedbackCursors = await turnFeedbackCursors(store.db, requested);
12758
12938
  return {
12759
12939
  observe: {
12760
- prs: [...new Map(prs.map((ref) => [refKey(ref), ref])).values()],
12940
+ prs: requested,
12761
12941
  tickets,
12762
12942
  sessions: [...new Map(sessions.map((ref) => [refKey(ref), ref])).values()]
12763
12943
  },
@@ -12768,7 +12948,8 @@ function createObservationCore(deps) {
12768
12948
  ref,
12769
12949
  count: row.misses
12770
12950
  }];
12771
- })
12951
+ }),
12952
+ ...feedbackCursors.length === 0 ? {} : { feedbackCursors }
12772
12953
  };
12773
12954
  },
12774
12955
  async observe(source, observation) {
@@ -13073,8 +13254,8 @@ function commandReply(id, value, input) {
13073
13254
  cliHint: `board ${operation.cli.command}`,
13074
13255
  body: [
13075
13256
  line(`Board status: ${String(status.tasks.length)} tasks, ${String(status.items.length)} items needing attention.`),
13076
- ...status.tasks.map((task) => line(`${task.key}: ${task.column} (${task.membership})`)),
13077
13257
  ...status.items.map((item) => line(`${item.key}: ${item.summary}`)),
13258
+ ...status.tasks.map((task) => line(`${task.key}: ${task.column} (${task.membership})`)),
13078
13259
  line(`Unlinked: ${String(status.unlinkedPrs.length)} pull requests, ${String(status.unlinkedSessions.length)} sessions${status.hiddenUnlinkedPrs + status.hiddenUnlinkedSessions === 0 ? "" : `; ${String(status.hiddenUnlinkedPrs)} pull requests and ${String(status.hiddenUnlinkedSessions)} sessions finished over 7 days ago are hidden`}.`),
13079
13260
  ...status.sources.map((source) => line(`${source.source}: ${source.blindReason !== null ? `blind (${source.blindReason})` : source.warmingUp ? "warming up" : source.stale ? "stale" : "current"}`)),
13080
13261
  ...status.warmingUp ? [line("Sources are warming up.")] : [],
package/dist/mcp.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { P as ERRORS, p as renderMcpError, u as OPERATIONS } from "./src-8BDCEAvV.mjs";
2
- import { i as CliError, n as requestOperation } from "./client-uUHdF1cr.mjs";
3
- import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./config-wjhrCN29.mjs";
1
+ import { F as ERRORS, m as renderMcpError, u as OPERATIONS } from "./src-B2L79Nf9.mjs";
2
+ import { i as CliError, n as requestOperation } from "./client-dHOLiNKd.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./config-BsZv50VN.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { z } from "zod";
@@ -0,0 +1,66 @@
1
+ -- A turn hands a task's current column visit to its executor. `seq` counts the turns of one
2
+ -- visit; a task has at most one unclosed turn. `handed` is JSON checked by zod.
3
+ CREATE TABLE turn (
4
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
5
+ task_id INTEGER NOT NULL REFERENCES task (id),
6
+ "column" TEXT NOT NULL,
7
+ epoch INTEGER NOT NULL,
8
+ seq INTEGER NOT NULL,
9
+ role TEXT NOT NULL,
10
+ reason TEXT NOT NULL,
11
+ handed TEXT NOT NULL,
12
+ acked_by TEXT,
13
+ acked_at TEXT,
14
+ closed_at TEXT,
15
+ closed_reason TEXT,
16
+ created_at TEXT NOT NULL,
17
+ UNIQUE (task_id, "column", epoch, seq),
18
+ CHECK ((acked_at IS NULL) = (acked_by IS NULL)),
19
+ CHECK ((closed_at IS NULL) = (closed_reason IS NULL))
20
+ ) STRICT;
21
+
22
+ CREATE UNIQUE INDEX turn_one_unclosed ON turn (task_id) WHERE closed_at IS NULL;
23
+
24
+ -- A notification belongs to a block or, for kind `turn`, to a turn. Keep every id, and keep the
25
+ -- sequence: outbox payloads name notification ids above the largest one still stored.
26
+ CREATE TABLE notification_new (
27
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
28
+ source_key TEXT NOT NULL UNIQUE,
29
+ kind TEXT NOT NULL,
30
+ task_id INTEGER NOT NULL REFERENCES task (id),
31
+ block_id INTEGER REFERENCES block (id),
32
+ comment_id INTEGER REFERENCES comment (id),
33
+ revision INTEGER,
34
+ role TEXT NOT NULL,
35
+ author_session TEXT,
36
+ recipient_session TEXT,
37
+ rings INTEGER NOT NULL DEFAULT 0,
38
+ next_at TEXT NOT NULL,
39
+ last_outbox_id INTEGER REFERENCES outbox (id),
40
+ acked_at TEXT,
41
+ created_at TEXT NOT NULL,
42
+ exhausted_at TEXT,
43
+ turn_id INTEGER REFERENCES turn (id),
44
+ CHECK (kind <> 'turn' OR (turn_id IS NOT NULL AND block_id IS NULL)),
45
+ CHECK (kind = 'turn' OR (block_id IS NOT NULL AND turn_id IS NULL))
46
+ ) STRICT;
47
+
48
+ INSERT INTO notification_new (id, source_key, kind, task_id, block_id, comment_id, revision, role,
49
+ author_session, recipient_session, rings, next_at, last_outbox_id, acked_at, created_at,
50
+ exhausted_at, turn_id)
51
+ SELECT id, source_key, kind, task_id, block_id, comment_id, revision, role, author_session,
52
+ recipient_session, rings, next_at, last_outbox_id, acked_at, created_at, exhausted_at, NULL
53
+ FROM notification;
54
+
55
+ INSERT INTO sqlite_sequence (name, seq)
56
+ SELECT 'notification_new', 0
57
+ WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = 'notification_new');
58
+ UPDATE sqlite_sequence
59
+ SET seq = max(seq, coalesce((SELECT seq FROM sqlite_sequence WHERE name = 'notification'), 0))
60
+ WHERE name = 'notification_new';
61
+
62
+ DROP TABLE notification;
63
+ ALTER TABLE notification_new RENAME TO notification;
64
+ CREATE INDEX notification_due ON notification (acked_at, next_at);
65
+ CREATE INDEX notification_block ON notification (block_id, id);
66
+ CREATE INDEX notification_turn ON notification (turn_id, id);
@@ -3055,4 +3055,4 @@ function assertNever(value) {
3055
3055
  throw new Error(`Unexpected value: ${JSON.stringify(value)}`);
3056
3056
  }
3057
3057
  //#endregion
3058
- export { errorCodeOf as A, DEFAULT_HTTP_PORT as B, SESSION_STATUSES as C, ticketFactsSchema as D, sessionFactsSchema as E, err as F, configSchema as G, DEFAULT_SLACK_APP_NAME as H, errorContextSchema as I, requiredSecretKeys as K, errorEnvelopeSchema as L, parseRef as M, taskKeySchema as N, actorIdSchema as O, ERRORS as P, ok as R, SESSION_HEALTH_STATES as S, prRefSchema as T, DEFAULT_SLACK_COMMAND as U, DEFAULT_LINK as V, RESERVED_PROJECT as W, interactionRefSchema as _, batchSchema as a, EVENT_KINDS as b, buildCatalogSnapshot as c, renderHttpProblem as d, renderJsonError as f, inboundEventSchema as g, conversationRefSchema as h, AdapterError as i, parseActorId as j, encodeActorId as k, roleCanUseOperation as l, SPACE_IDS as m, BOARD_TICK_MS as n, entityRefSchema as o, renderMcpError as p, SLACK_BOT_SCOPES as q, SYSTEMD_SERVICE_SETTINGS as r, sourceCursorSchema as s, assertNever as t, OPERATIONS as u, messageRefSchema as v, prFactsSchema as w, eventPayloadSchemas as x, userIdSchema as y, successEnvelopeSchema as z };
3058
+ export { encodeActorId as A, successEnvelopeSchema as B, SESSION_HEALTH_STATES as C, sessionFactsSchema as D, prRefSchema as E, ERRORS as F, RESERVED_PROJECT as G, DEFAULT_LINK as H, err as I, SLACK_BOT_SCOPES as J, configSchema as K, errorContextSchema as L, parseActorId as M, parseRef as N, ticketFactsSchema as O, taskKeySchema as P, errorEnvelopeSchema as R, eventPayloadSchemas as S, prFactsSchema as T, DEFAULT_SLACK_APP_NAME as U, DEFAULT_HTTP_PORT as V, DEFAULT_SLACK_COMMAND as W, inboundEventSchema as _, batchSchema as a, userIdSchema as b, buildCatalogSnapshot as c, turnHandedSchema as d, renderHttpProblem as f, conversationRefSchema as g, SPACE_IDS as h, AdapterError as i, errorCodeOf as j, actorIdSchema as k, roleCanUseOperation as l, renderMcpError as m, BOARD_TICK_MS as n, entityRefSchema as o, renderJsonError as p, requiredSecretKeys as q, SYSTEMD_SERVICE_SETTINGS as r, sourceCursorSchema as s, assertNever as t, OPERATIONS as u, interactionRefSchema as v, SESSION_STATUSES as w, EVENT_KINDS as x, messageRefSchema as y, ok as z };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spur-board",
3
- "version": "0.33.0",
3
+ "version": "0.34.1",
4
4
  "license": "MIT",
5
5
  "engines": {
6
6
  "node": "^24.12.0 || ^26.0.0"