spur-board 0.57.0 → 0.59.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/daemon.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { A as EVENT_KINDS, B as ringMarker, D as interactionRefSchema, E as inboundEventSchema, F as SESSION_STATUSES, G as actorIdSchema, H as ticketFactsSchema, I as isExternalAuthor, J as parseActorId, K as encodeActorId, L as parseRingMarker, M as PR_STATES, N as REVIEW_STATES, O as messageRefSchema, P as SESSION_HEALTH_STATES, Q as err, R as prFactsSchema, T as conversationRefSchema, U as JIRA_PROJECT_KEY, V as sessionFactsSchema, W as REF_NUMBER, X as taskKeySchema, Y as parseRef$1, Z as ERRORS, _ as buildCatalogSnapshot, a as requestHashOf, b as turnHandedSchema, c as tokenRequestStatusSchema, ct as configSchema, d as AdapterError, dt as COLUMN_IDS, f as batchSchema, ft as DISPATCHER_MODES, g as trackerSourceId, h as sourceCursorSchema, i as TOKEN_REQUEST_LIMITS, it as DEFAULT_LINK, j as eventPayloadSchemas, k as userIdSchema, l as BOARD_TICK_MS, lt as plainHttpAllowed, m as prSourceId, mt as TASK_HOLDS, n as doctorReportSchema, nt as successEnvelopeSchema, o as tokenRequestResultSchema, ot as DEFAULT_SLACK_COMMAND, p as entityRefSchema, pt as SLACK_BOT_SCOPES, q as errorCodeOf, s as tokenRequestSchema, st as RESERVED_PROJECT, t as assertNever, tt as ok, ut as requiredSecretKeys, v as roleCanUseOperation, w as SPACE_IDS, x as renderHttpProblem, y as OPERATIONS, z as prRefSchema } from "./chunk-CTXzapf8.mjs";
1
+ import { A as EVENT_KINDS, B as ringMarker, D as interactionRefSchema, E as inboundEventSchema, F as SESSION_STATUSES, G as actorIdSchema, H as ticketFactsSchema, I as isExternalAuthor, J as parseActorId, K as encodeActorId, L as parseRingMarker, M as PR_STATES, N as REVIEW_STATES, O as messageRefSchema, P as SESSION_HEALTH_STATES, R as prFactsSchema, T as conversationRefSchema, U as JIRA_PROJECT_KEY, V as sessionFactsSchema, W as REF_NUMBER, X as ERRORS, Y as parseRef$1, 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, pt as TASK_HOLDS, q as errorCodeOf, 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 prRefSchema } from "./chunk-ZywNbxbW.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";
@@ -478,6 +478,18 @@ function acknowledgeComment(revision, requested) {
478
478
  }
479
479
  //#endregion
480
480
  //#region ../core/src/app/authorize.ts
481
+ /** The target of an operation on a board project as a whole: no task, block or links. */
482
+ function projectTarget(project) {
483
+ return {
484
+ kind: "found",
485
+ value: {
486
+ project,
487
+ task: null,
488
+ block: null,
489
+ workers: []
490
+ }
491
+ };
492
+ }
481
493
  /** True for the operator token and for a session of a Spur project with the `operator` role. */
482
494
  function isOperator(actor, config) {
483
495
  if (actor === "operator") return true;
@@ -8469,6 +8481,36 @@ async function dispatchOperation(deps, id, input, actor, key) {
8469
8481
  return operation.kind === "query" ? createQuery(deps)(handler, input, actor) : createApply(deps)(handler, input, actor, key);
8470
8482
  }
8471
8483
  //#endregion
8484
+ //#region ../core/src/app/subject.ts
8485
+ function taskSubject(task) {
8486
+ return {
8487
+ project: task.project,
8488
+ task,
8489
+ key: task.key
8490
+ };
8491
+ }
8492
+ function projectSubject(project) {
8493
+ return {
8494
+ project,
8495
+ task: null,
8496
+ key: `${project} (project)`
8497
+ };
8498
+ }
8499
+ /** The subject of a row with a task or a block; a block without a task has a project. */
8500
+ async function rowSubject(trx, row) {
8501
+ if (row.task_id !== null) return taskSubject(await trx.selectFrom("task").selectAll().where("id", "=", row.task_id).executeTakeFirstOrThrow());
8502
+ if (row.block_id === null) throw new Error("Row has neither a task nor a block");
8503
+ return blockSubject(trx, await trx.selectFrom("block").select(["task_id", "project"]).where("id", "=", row.block_id).executeTakeFirstOrThrow());
8504
+ }
8505
+ async function blockSubject(trx, block) {
8506
+ if (block.task_id !== null) return rowSubject(trx, {
8507
+ task_id: block.task_id,
8508
+ block_id: null
8509
+ });
8510
+ if (block.project === null) throw new Error("Block has neither a task nor a project");
8511
+ return projectSubject(block.project);
8512
+ }
8513
+ //#endregion
8472
8514
  //#region ../core/src/domain/fromYou.ts
8473
8515
  /** Every operator item kind; `ITEM_POLICY` must give each one a policy. */
8474
8516
  const ITEM_KINDS = [
@@ -8646,6 +8688,8 @@ function orderItems(items) {
8646
8688
  //#region ../core/src/app/item-raise.ts
8647
8689
  /** Display label of a feed line with no task; not part of the line's identity. */
8648
8690
  const TASKLESS_FEED_KEY = "spur-board";
8691
+ /** Link of an item with no task to open. */
8692
+ const TASKLESS_ITEM_URL = "https://github.com";
8649
8693
  async function journal$3(trx, item, kind, at, rule, actor = "system") {
8650
8694
  await emit(trx, kind, (item.task_id === null ? void 0 : await trx.selectFrom("task").select(["project"]).where("id", "=", item.task_id).executeTakeFirstOrThrow())?.project ?? "_board", item.task_id, at.toISOString(), {
8651
8695
  item: `I${String(item.id)}`,
@@ -8754,10 +8798,12 @@ const persona = z.strictObject({
8754
8798
  });
8755
8799
  const id = z.int().positive();
8756
8800
  const closePayload = z.strictObject({
8757
- key: taskKeySchema,
8801
+ /** The task key, or `<project> (project)` for a project-level block. */
8802
+ key: z.string().min(1),
8758
8803
  text: z.string(),
8759
8804
  persona,
8760
- taskId: id,
8805
+ /** Null for a project-level block. */
8806
+ taskId: id.nullable(),
8761
8807
  blockId: id,
8762
8808
  commentId: id.nullable(),
8763
8809
  targetConversation: conversationRefSchema.optional()
@@ -9254,22 +9300,23 @@ async function markCommentPending(trx, commentId) {
9254
9300
  * for every new block. The text is the comment's when given, else the block's reason.
9255
9301
  */
9256
9302
  async function enqueueConversationOpen(trx, input) {
9257
- const block = await trx.selectFrom("block").innerJoin("task", "task.id", "block.task_id").select([
9258
- "block.id",
9259
- "block.reason",
9260
- "block.author",
9261
- "block.addressee_role",
9262
- "task.id as taskId",
9263
- "task.key"
9264
- ]).where("block.id", "=", input.blockId).executeTakeFirstOrThrow();
9303
+ const block = await trx.selectFrom("block").select([
9304
+ "id",
9305
+ "reason",
9306
+ "author",
9307
+ "addressee_role",
9308
+ "task_id",
9309
+ "project"
9310
+ ]).where("id", "=", input.blockId).executeTakeFirstOrThrow();
9265
9311
  if (block.addressee_role !== "operator" || block.author === "operator") return null;
9312
+ const { key } = await blockSubject(trx, block);
9266
9313
  const comment = input.commentId === null ? void 0 : await trx.selectFrom("comment").select("text").where("id", "=", input.commentId).executeTakeFirstOrThrow();
9267
9314
  const payload = {
9268
- key: block.key,
9269
- title: `${block.key} ${block.reason}`,
9315
+ key,
9316
+ title: `${key} ${block.reason}`,
9270
9317
  text: comment?.text ?? block.reason,
9271
9318
  persona: input.persona,
9272
- taskId: block.taskId,
9319
+ taskId: block.task_id,
9273
9320
  blockId: block.id,
9274
9321
  commentId: input.commentId
9275
9322
  };
@@ -9289,13 +9336,12 @@ async function enqueueConversationOpen(trx, input) {
9289
9336
  * nothing when there is no such row or it is dead: a dead thread takes no more replies.
9290
9337
  */
9291
9338
  async function enqueueConversationReply(trx, input) {
9292
- const comment = await trx.selectFrom("comment").innerJoin("task", "task.id", "comment.task_id").select([
9293
- "comment.id",
9294
- "comment.text",
9295
- "comment.block_id",
9296
- "task.id as taskId",
9297
- "task.key"
9298
- ]).where("comment.id", "=", input.commentId).executeTakeFirstOrThrow();
9339
+ const comment = await trx.selectFrom("comment").select([
9340
+ "id",
9341
+ "text",
9342
+ "block_id",
9343
+ "task_id"
9344
+ ]).where("id", "=", input.commentId).executeTakeFirstOrThrow();
9299
9345
  const blockId = comment.block_id;
9300
9346
  if (blockId === null) return null;
9301
9347
  const tail = await trx.selectFrom("outbox").select(["id", "state"]).where("kind", "in", [
@@ -9305,10 +9351,10 @@ async function enqueueConversationReply(trx, input) {
9305
9351
  ]).where(sql`json_extract(payload, '$.blockId')`, "=", blockId).orderBy("id", "desc").limit(1).executeTakeFirst();
9306
9352
  if (tail === void 0 || tail.state === "dead") return null;
9307
9353
  const payload = {
9308
- key: comment.key,
9354
+ key: (await rowSubject(trx, comment)).key,
9309
9355
  text: comment.text,
9310
9356
  persona: input.persona,
9311
- taskId: comment.taskId,
9357
+ taskId: comment.task_id,
9312
9358
  blockId,
9313
9359
  commentId: comment.id
9314
9360
  };
@@ -9324,23 +9370,23 @@ async function enqueueConversationReply(trx, input) {
9324
9370
  }
9325
9371
  /** Queues a close for every registered thread and for an open whose result is still unknown. */
9326
9372
  async function enqueueConversationClose(trx, input) {
9327
- const block = await trx.selectFrom("block").innerJoin("task", "task.id", "block.task_id").select([
9328
- "task.id as taskId",
9329
- "task.key",
9330
- "block.id"
9331
- ]).where("block.id", "=", input.blockId).executeTakeFirstOrThrow();
9373
+ const block = await trx.selectFrom("block").select([
9374
+ "id",
9375
+ "task_id",
9376
+ "project"
9377
+ ]).where("id", "=", input.blockId).executeTakeFirstOrThrow();
9332
9378
  const tail = await trx.selectFrom("outbox").select(["id", "state"]).where("kind", "in", ["conversation.open", "conversation.reply"]).where(sql`json_extract(payload, '$.blockId')`, "=", input.blockId).orderBy("id", "desc").executeTakeFirst();
9333
9379
  const open = await trx.selectFrom("outbox").select(["id", "state"]).where("kind", "=", "conversation.open").where(sql`json_extract(payload, '$.blockId')`, "=", input.blockId).executeTakeFirst();
9334
9380
  const parent = tail?.state === "dead" ? null : tail?.id ?? null;
9335
9381
  const conversations = await trx.selectFrom("conversation").select("ref").where("block_id", "=", input.blockId).execute();
9336
9382
  const payload = {
9337
- key: block.key,
9383
+ key: (await blockSubject(trx, block)).key,
9338
9384
  text: `resolved: ${input.outcome === "archived" ? "task archived" : input.outcome} (${input.actor})`,
9339
9385
  persona: {
9340
9386
  name: "board",
9341
9387
  role: "board"
9342
9388
  },
9343
- taskId: block.taskId,
9389
+ taskId: block.task_id,
9344
9390
  blockId: block.id,
9345
9391
  commentId: null
9346
9392
  };
@@ -9376,13 +9422,18 @@ function orchestrator(config, task) {
9376
9422
  const name = config.projects.find((project) => project.id === task.project)?.columns.find((column) => column.id === task.column)?.orchestrator;
9377
9423
  return name === void 0 || name === "none" ? null : name;
9378
9424
  }
9379
- function authorRole(config, task, actor) {
9425
+ /**
9426
+ * The role an actor speaks for on a block's subject. On a project-level block, which has no
9427
+ * column, an agent is the curator or a worker.
9428
+ */
9429
+ function authorRole(config, subject, actor) {
9380
9430
  if (actor === "operator") return "operator";
9381
9431
  const parsed = parseActorId(actor);
9382
9432
  if (parsed?.actor === "agent" && config.projects.some((project) => project.spurProjects.some((spur) => spur.name === parsed.actorRef.project && spur.role === "operator"))) return "operator";
9383
9433
  if (parsed?.actor !== "agent") return "worker";
9384
- if (parsed.actorRef.project === orchestrator(config, task)) return `orchestrator:${task.column}`;
9385
- return parsed.actorRef.project === curatorProject(config, task.project) ? "curator" : "worker";
9434
+ const { task } = subject;
9435
+ if (task !== null && parsed.actorRef.project === orchestrator(config, task)) return `orchestrator:${task.column}`;
9436
+ return parsed.actorRef.project === curatorProject(config, subject.project) ? "curator" : "worker";
9386
9437
  }
9387
9438
  function personaRole(role) {
9388
9439
  const addressee = parseAddressee(role);
@@ -9394,7 +9445,7 @@ function personaRole(role) {
9394
9445
  default: return assertNever(addressee);
9395
9446
  }
9396
9447
  }
9397
- function personaFor(config, task, actor) {
9448
+ function personaFor(config, subject, actor) {
9398
9449
  if (actor === "system") return {
9399
9450
  name: "board",
9400
9451
  role: "board"
@@ -9407,21 +9458,21 @@ function personaFor(config, task, actor) {
9407
9458
  if (parsed?.actor !== "agent") throw new Error("Invalid actor");
9408
9459
  return {
9409
9460
  name: parsed.actorRef.project,
9410
- role: personaRole(authorRole(config, task, actor))
9461
+ role: personaRole(authorRole(config, subject, actor))
9411
9462
  };
9412
9463
  }
9413
- async function queueBlockOpen(trx, task, block, ctx, config) {
9414
- if (authorRole(config, task, block.author) === "operator") return;
9464
+ async function queueBlockOpen(trx, subject, block, ctx, config) {
9465
+ if (authorRole(config, subject, block.author) === "operator") return;
9415
9466
  const comments = await trx.selectFrom("comment").select(["id", "author"]).where("block_id", "=", block.id).orderBy("id").execute();
9416
9467
  if (await enqueueConversationOpen(trx, {
9417
9468
  blockId: block.id,
9418
9469
  commentId: comments[0]?.id ?? null,
9419
- persona: personaFor(config, task, comments[0]?.author ?? block.author),
9470
+ persona: personaFor(config, subject, comments[0]?.author ?? block.author),
9420
9471
  at: new Date(ctx.at)
9421
9472
  }) === null) return;
9422
9473
  for (const comment of comments.slice(1)) await enqueueConversationReply(trx, {
9423
9474
  commentId: comment.id,
9424
- persona: personaFor(config, task, comment.author),
9475
+ persona: personaFor(config, subject, comment.author),
9425
9476
  at: new Date(ctx.at)
9426
9477
  });
9427
9478
  }
@@ -9628,7 +9679,7 @@ function tokenCardBody(card, config) {
9628
9679
  //#region ../core/src/app/doorbells.ts
9629
9680
  const UNANSWERED = "unanswered";
9630
9681
  async function journal$2(trx, notification, kind, payload, at) {
9631
- await emit(trx, kind, (await trx.selectFrom("task").select("project").where("id", "=", notification.task_id).executeTakeFirstOrThrow()).project, notification.task_id, at.toISOString(), payload);
9682
+ await emit(trx, kind, await noticeProject(trx, notification), notification.task_id, at.toISOString(), payload);
9632
9683
  }
9633
9684
  /**
9634
9685
  * The one rule for who a board event rings. A doorbell means someone is waiting for your action,
@@ -9764,8 +9815,8 @@ function noticeBlockId(n) {
9764
9815
  return n.block_id;
9765
9816
  }
9766
9817
  /** What a notification is about, as the operator item names it. */
9767
- function noticeRef(n, task) {
9768
- return isTurnKind(n.kind) ? `turn T${String(n.turn_id)} on ${task.key}` : `block B${String(noticeBlockId(n))} on ${task.key}`;
9818
+ function noticeRef(n, subject) {
9819
+ return isTurnKind(n.kind) ? `turn T${String(n.turn_id)} on ${subject.key}` : `block B${String(noticeBlockId(n))} on ${subject.key}`;
9769
9820
  }
9770
9821
  /** Register a one-ring notice that a block its addressee held was closed by someone else. */
9771
9822
  async function registerRemovedNotification(trx, block, at) {
@@ -9862,7 +9913,7 @@ async function moveBlockToAddressee(trx, input) {
9862
9913
  kind: "block_escalated",
9863
9914
  block: updated
9864
9915
  }, new Date(ctx.at));
9865
- await queueBlockOpen(trx, task, updated, ctx, config);
9916
+ await queueBlockOpen(trx, taskSubject(task), updated, ctx, config);
9866
9917
  return updated;
9867
9918
  }
9868
9919
  async function sessionById(trx, id) {
@@ -9918,8 +9969,9 @@ async function bestProjectSession(trx, project) {
9918
9969
  async function curatorSession(trx, config, projectId) {
9919
9970
  return bestProjectSession(trx, curatorProject(config, projectId));
9920
9971
  }
9921
- /** The newest live session linked to a task in a role. */
9972
+ /** The newest live session linked to a task in a role; a project-level notice has no links. */
9922
9973
  async function linkedSession(trx, taskId, role) {
9974
+ if (taskId === null) return void 0;
9923
9975
  const links = await trx.selectFrom("link").select("session_id").where("task_id", "=", taskId).where("entity", "=", "session").where("role", "=", role).where("banned", "=", 0).orderBy("created_at", "desc").execute();
9924
9976
  for (const link of links) {
9925
9977
  if (link.session_id === null) continue;
@@ -9927,8 +9979,12 @@ async function linkedSession(trx, taskId, role) {
9927
9979
  if (session !== void 0) return session;
9928
9980
  }
9929
9981
  }
9930
- async function taskProject(trx, taskId) {
9931
- return (await trx.selectFrom("task").select("project").where("id", "=", taskId).executeTakeFirstOrThrow()).project;
9982
+ /** The board project of a notification: its task's, else its project-level block's. */
9983
+ async function noticeProject(trx, n) {
9984
+ return (await rowSubject(trx, {
9985
+ task_id: n.task_id,
9986
+ block_id: n.block_id ?? null
9987
+ })).project;
9932
9988
  }
9933
9989
  /** The Spur project orchestrating a column; null when no agent project does. */
9934
9990
  function columnOrchestratorProject(config, projectId, column) {
@@ -9943,11 +9999,11 @@ async function selectNotificationRecipient(trx, n, config) {
9943
9999
  if (n.kind === "turn_reminder") return n.author_session === null ? void 0 : liveSession(trx, n.author_session);
9944
10000
  const addressee = parseAddressee(n.role);
9945
10001
  switch (addressee.kind) {
9946
- case "curator": return curatorSession(trx, config, await taskProject(trx, n.task_id));
10002
+ case "curator": return curatorSession(trx, config, await noticeProject(trx, n));
9947
10003
  case "orchestrator": {
9948
10004
  const author = n.author_session === null ? void 0 : await sessionById(trx, n.author_session);
9949
10005
  if (author !== void 0 && liveInProject(author)) return author;
9950
- return await linkedSession(trx, n.task_id, "orchestrator") ?? bestProjectSession(trx, columnOrchestratorProject(config, await taskProject(trx, n.task_id), addressee.column));
10006
+ return await linkedSession(trx, n.task_id, "orchestrator") ?? bestProjectSession(trx, columnOrchestratorProject(config, await noticeProject(trx, n), addressee.column));
9951
10007
  }
9952
10008
  case "worker":
9953
10009
  case "operator": {
@@ -9983,12 +10039,13 @@ async function restartNotification(trx, sourceKey, at) {
9983
10039
  * session to name ends alone; anything else raises the operator item, whose Retry restarts the
9984
10040
  * series (`restartNotification`). Every end journals `doorbell_undelivered`.
9985
10041
  */
9986
- async function endNotification(trx, n, task, end) {
10042
+ async function endNotification(trx, n, subject, end) {
9987
10043
  const { session, reason, at, config } = end;
9988
10044
  await trx.updateTable("notification").set({ exhausted_at: at.toISOString() }).where("id", "=", n.id).execute();
9989
10045
  if (n.rings === 0) await releaseAfterCourseNote(trx, n, at);
9990
10046
  const addressee = parseAddressee(n.role);
9991
- if (n.kind === "block" && (addressee.kind === "curator" || session === null)) await moveBlockToAddressee(trx, {
10047
+ const { task } = subject;
10048
+ if (n.kind === "block" && task !== null && (addressee.kind === "curator" || session === null)) await moveBlockToAddressee(trx, {
9992
10049
  task,
9993
10050
  block: await trx.selectFrom("block").selectAll().where("id", "=", noticeBlockId(n)).executeTakeFirstOrThrow(),
9994
10051
  to: "operator",
@@ -10000,15 +10057,15 @@ async function endNotification(trx, n, task, end) {
10000
10057
  config
10001
10058
  });
10002
10059
  else if (n.kind !== "removed" && n.kind !== "turn_reminder" && session !== null) {
10003
- const blockRef = noticeRef(n, task);
10060
+ const blockRef = noticeRef(n, subject);
10004
10061
  const answer = `Answer to ${blockRef} was not`;
10005
10062
  const holder = `${addressee.kind} ${session}`;
10006
10063
  await raiseItem(trx, {
10007
10064
  itemKey: exhaustedItemKey(n),
10008
10065
  kind: exhaustedItemKind(n),
10009
10066
  text: reason === UNANSWERED ? n.kind === "answer" ? `${answer} read` : `${holder} is not reading ${blockRef}` : n.kind === "answer" ? `${answer} delivered: ${reason}` : `${holder} did not get ${blockRef}: ${reason}`,
10010
- url: taskUrl(task, config),
10011
- taskId: task.id,
10067
+ url: task === null ? TASKLESS_ITEM_URL : taskUrl(task, config),
10068
+ taskId: task?.id ?? null,
10012
10069
  blockId: n.block_id,
10013
10070
  at
10014
10071
  });
@@ -10046,7 +10103,7 @@ async function ringUndelivered(trx, input) {
10046
10103
  }
10047
10104
  const n = await trx.selectFrom("notification").selectAll().where("id", "=", input.notificationId).executeTakeFirst();
10048
10105
  if (n === void 0 || n.acked_at !== null || n.exhausted_at !== null || n.last_outbox_id !== input.outboxId) return;
10049
- await endNotification(trx, n, await trx.selectFrom("task").selectAll().where("id", "=", n.task_id).executeTakeFirstOrThrow(), {
10106
+ await endNotification(trx, n, await rowSubject(trx, n), {
10050
10107
  session: input.session,
10051
10108
  reason,
10052
10109
  at,
@@ -10056,31 +10113,32 @@ async function ringUndelivered(trx, input) {
10056
10113
  /**
10057
10114
  * Why a notification with no recipient ends now, or null when it stays due for a next session. A
10058
10115
  * curator block, and an orchestrator block of a course check, end with `session: null`, which
10059
- * `endNotification` turns into a move to the operator.
10116
+ * `endNotification` turns into a move to the operator. A worker's answer on a project-level block
10117
+ * goes only to the session that asked.
10060
10118
  */
10061
10119
  async function noRecipientEnd(trx, n) {
10062
- if (n.kind === "removed" || n.kind === "turn_reminder" || n.kind === "answer" && n.role === "operator") return "no live addressee";
10120
+ if (n.kind === "removed" || n.kind === "turn_reminder" || n.kind === "answer" && n.role === "operator" || n.kind === "answer" && n.role === "worker" && n.task_id === null) return "no live addressee";
10063
10121
  if (n.kind !== "block") return null;
10064
10122
  if (n.role === "curator") return "no live curator session";
10065
10123
  if (parseAddressee(n.role).kind !== "orchestrator") return null;
10066
10124
  return await trx.selectFrom("operator_item").select("id").where("kind", "=", "course_check").where("block_id", "=", noticeBlockId(n)).executeTakeFirst() === void 0 ? null : "no live orchestrator session";
10067
10125
  }
10068
10126
  /** A ring never carries comment or reason text: only where to look. */
10069
- async function ringText(trx, n, task, ring) {
10127
+ async function ringText(trx, n, { key }, ring) {
10070
10128
  const suffix = ringMarker(n.id, ring);
10071
- if (n.kind === "turn") return `${task.key} turn T${String(n.turn_id)}: check board inbox ${suffix}`;
10072
- if (n.kind === "turn_reminder") return `${task.key} turn T${String(n.turn_id)} is still open: check board inbox ${suffix}`;
10129
+ if (n.kind === "turn") return `${key} turn T${String(n.turn_id)}: check board inbox ${suffix}`;
10130
+ if (n.kind === "turn_reminder") return `${key} turn T${String(n.turn_id)} is still open: check board inbox ${suffix}`;
10073
10131
  const blockId = noticeBlockId(n);
10074
- if (n.kind !== "removed") return `${task.key} block B${String(blockId)}: check board inbox ${suffix}`;
10132
+ if (n.kind !== "removed") return `${key} block B${String(blockId)}: check board inbox ${suffix}`;
10075
10133
  const block = await trx.selectFrom("block").select("unblocked_by").where("id", "=", blockId).executeTakeFirstOrThrow();
10076
- return `${task.key} block B${String(blockId)} was removed by ${block.unblocked_by ?? "system"}; see board task ${task.key} ${suffix}`;
10134
+ return `${key} block B${String(blockId)} was removed by ${block.unblocked_by ?? "system"}; see board task ${key} ${suffix}`;
10077
10135
  }
10078
10136
  /**
10079
- * Notifications reconcile looks at: unacked, not exhausted, due, on a task not archived, and not
10080
- * held by a course check (`courseHold`).
10137
+ * Notifications reconcile looks at: unacked, not exhausted, due, on a task not archived or on a
10138
+ * project-level block, and not held by a course check (`courseHold`).
10081
10139
  */
10082
10140
  function dueNotifications(db, at) {
10083
- 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)));
10141
+ return db.selectFrom("notification").leftJoin("task", "task.id", "notification.task_id").where((eb) => eb.or([eb("task.id", "is", null), eb("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)));
10084
10142
  }
10085
10143
  /**
10086
10144
  * Reconciles due notifications in their own transaction. With none due it opens no transaction;
@@ -10099,7 +10157,7 @@ async function reconcileDoorbells(trx, at, config) {
10099
10157
  const keepsRings = resolvedByProject(n.role);
10100
10158
  if (session === void 0) {
10101
10159
  const reason = await noRecipientEnd(trx, n);
10102
- if (reason !== null) await endNotification(trx, n, await trx.selectFrom("task").selectAll().where("id", "=", n.task_id).executeTakeFirstOrThrow(), {
10160
+ if (reason !== null) await endNotification(trx, n, await rowSubject(trx, n), {
10103
10161
  session: null,
10104
10162
  reason,
10105
10163
  at,
@@ -10132,9 +10190,9 @@ async function reconcileDoorbells(trx, at, config) {
10132
10190
  const row = await trx.selectFrom("outbox").select("state").where("id", "=", lastOutbox).executeTakeFirst();
10133
10191
  if (row?.state === "pending" || row?.state === "in_flight") continue;
10134
10192
  }
10135
- const task = await trx.selectFrom("task").selectAll().where("id", "=", n.task_id).executeTakeFirstOrThrow();
10193
+ const subject = await rowSubject(trx, n);
10136
10194
  if (rings >= 3) {
10137
- await endNotification(trx, n, task, {
10195
+ await endNotification(trx, n, subject, {
10138
10196
  session: session.id,
10139
10197
  reason: UNANSWERED,
10140
10198
  at,
@@ -10145,7 +10203,7 @@ async function reconcileDoorbells(trx, at, config) {
10145
10203
  if (rings > 0 && earlierRingQueued(session, n.id, rings) && !await spurBlind$1(trx)) {
10146
10204
  const pauses = ringPauses(config);
10147
10205
  const deadline = Date.parse(n.next_at) + pauses.slice(rings).reduce((sum, pause) => sum + pause, 0);
10148
- if (at.getTime() >= deadline) await endNotification(trx, n, task, {
10206
+ if (at.getTime() >= deadline) await endNotification(trx, n, subject, {
10149
10207
  session: session.id,
10150
10208
  reason: UNANSWERED,
10151
10209
  at,
@@ -10154,9 +10212,9 @@ async function reconcileDoorbells(trx, at, config) {
10154
10212
  continue;
10155
10213
  }
10156
10214
  const raised = await trx.selectFrom("operator_item").select((eb) => eb.fn.max("raise_no").as("series")).where("item_key", "=", exhaustedItemKey(n)).executeTakeFirst();
10157
- const archived = await trx.selectFrom("event").select((eb) => eb.fn.countAll().as("count")).where("task_id", "=", n.task_id).where("kind", "=", "task_archived").executeTakeFirst();
10215
+ const archived = n.task_id === null ? void 0 : await trx.selectFrom("event").select((eb) => eb.fn.countAll().as("count")).where("task_id", "=", n.task_id).where("kind", "=", "task_archived").executeTakeFirst();
10158
10216
  const ring = rings + 1;
10159
- const text = await ringText(trx, n, task, ring);
10217
+ const text = await ringText(trx, n, subject, ring);
10160
10218
  const outboxId = await enqueueDoorbell(trx, {
10161
10219
  notificationId: n.id,
10162
10220
  ring,
@@ -10226,7 +10284,7 @@ async function recordRingDelivery(trx, notificationId, ring, session, at, config
10226
10284
  * without a note.
10227
10285
  */
10228
10286
  async function releaseAfterCourseNote(trx, n, at) {
10229
- 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;
10287
+ 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 || n.task_id === null) return;
10230
10288
  await promoteWorkerDoorbells(trx, n.task_id, at, n.id);
10231
10289
  }
10232
10290
  /** True while the Spur source is blind: its stored session facts may no longer hold. */
@@ -10281,14 +10339,15 @@ async function notificationAddressedTo(trx, n, actor, config) {
10281
10339
  const { project, session } = parsed.actorRef;
10282
10340
  const addressee = parseAddressee(n.role);
10283
10341
  switch (addressee.kind) {
10284
- case "curator": return project === curatorProject(config, await taskProject(trx, n.task_id));
10285
- case "orchestrator": return project === columnOrchestratorProject(config, await taskProject(trx, n.task_id), addressee.column) || await hasLiveLink(trx, n.task_id, "orchestrator", session);
10342
+ case "curator": return project === curatorProject(config, await noticeProject(trx, n));
10343
+ case "orchestrator": return project === columnOrchestratorProject(config, await noticeProject(trx, n), addressee.column) || await hasLiveLink(trx, n.task_id, "orchestrator", session);
10286
10344
  case "operator": return session === n.author_session;
10287
10345
  case "worker": return workerNotificationAddressedTo(trx, n, session, config);
10288
10346
  default: return assertNever(addressee);
10289
10347
  }
10290
10348
  }
10291
10349
  async function sessionLink(trx, taskId, role, session) {
10350
+ if (taskId === null) return void 0;
10292
10351
  return trx.selectFrom("link").select("id").where("task_id", "=", taskId).where("entity", "=", "session").where("role", "=", role).where("banned", "=", 0).where("session_id", "=", session).executeTakeFirst();
10293
10352
  }
10294
10353
  async function hasLiveLink(trx, taskId, role, session) {
@@ -10296,8 +10355,9 @@ async function hasLiveLink(trx, taskId, role, session) {
10296
10355
  }
10297
10356
  /** The selected worker while it lives; before the first ring, the author or a linked worker. */
10298
10357
  async function workerNotificationAddressedTo(trx, n, session, config) {
10358
+ if (n.kind === "turn" && await sessionLink(trx, n.task_id, "worker", session) === void 0) return false;
10299
10359
  if (n.recipient_session === null) return session === n.author_session || await sessionLink(trx, n.task_id, "worker", session) !== void 0;
10300
- return await liveSession(trx, n.recipient_session) !== void 0 ? session === n.recipient_session : (await selectNotificationRecipient(trx, n, config))?.id === session;
10360
+ return (n.kind !== "turn" || await sessionLink(trx, n.task_id, "worker", n.recipient_session) !== void 0) && await liveSession(trx, n.recipient_session) !== void 0 ? session === n.recipient_session : (await selectNotificationRecipient(trx, n, config))?.id === session;
10301
10361
  }
10302
10362
  /** Ends a block's ring series; its exhaustion item is cleared by `actor`, who closed the block. */
10303
10363
  async function closeBlockNotification(trx, blockId, at, actor) {
@@ -11110,6 +11170,35 @@ async function closeTurns(trx, input) {
11110
11170
  if (item !== void 0) await clearItem(trx, item.id, at);
11111
11171
  }
11112
11172
  }
11173
+ /** Reroutes a worker turn whose holder or unread recipient was demoted from worker. */
11174
+ async function rerouteDemotedWorkerTurn(trx, input) {
11175
+ const { taskId, sessionId, at, config } = input;
11176
+ const turn = await trx.selectFrom("turn").selectAll().where("task_id", "=", taskId).where("role", "=", "worker").where("closed_at", "is", null).executeTakeFirst();
11177
+ if (turn === void 0) return false;
11178
+ if (turn.acked_by !== null) {
11179
+ const holder = parseActorId(turn.acked_by);
11180
+ if (holder?.actor !== "agent" || holder.actorRef.session !== sessionId) return false;
11181
+ } else {
11182
+ const notice = await turnNotification(trx, turn.id);
11183
+ if (notice !== void 0 && notice.recipient_session !== null) {
11184
+ if (notice.recipient_session !== sessionId) return false;
11185
+ } else if (await linkedSession(trx, taskId, "worker") !== void 0) return false;
11186
+ }
11187
+ const task = await trx.selectFrom("task").selectAll().where("id", "=", taskId).executeTakeFirstOrThrow();
11188
+ await closeTurns(trx, {
11189
+ taskId,
11190
+ reason: "rerouted",
11191
+ at
11192
+ });
11193
+ await openTurn(trx, {
11194
+ task,
11195
+ reason: turn.reason,
11196
+ handed: turnHanded(turn),
11197
+ at,
11198
+ config
11199
+ });
11200
+ return true;
11201
+ }
11113
11202
  /** How long the holder of a taken turn may sit quiet before it is reminded, then flagged. */
11114
11203
  function stuckTurnAfterMs(config) {
11115
11204
  return config.health.idleInDevAfterMs;
@@ -11315,9 +11404,11 @@ function found(value) {
11315
11404
  function active(task) {
11316
11405
  if (task.membership === "archived") throw new CommandError("task_archived", "Add the task again before changing it.");
11317
11406
  }
11318
- async function authorizationTarget(trx, task, block) {
11319
- if (task === void 0) return { kind: "missing" };
11320
- const workers = await trx.selectFrom("link").select([
11407
+ /** The authorization target of a subject; a project-level block has no task and no links. */
11408
+ async function subjectTarget(trx, subject, block) {
11409
+ if (subject === void 0) return { kind: "missing" };
11410
+ const { task } = subject;
11411
+ const workers = task === null ? [] : await trx.selectFrom("link").select([
11321
11412
  "session_id",
11322
11413
  "role",
11323
11414
  "banned"
@@ -11325,8 +11416,8 @@ async function authorizationTarget(trx, task, block) {
11325
11416
  return {
11326
11417
  kind: "found",
11327
11418
  value: {
11328
- project: task.project,
11329
- task: {
11419
+ project: subject.project,
11420
+ task: task === null ? null : {
11330
11421
  id: task.id,
11331
11422
  column: task.column
11332
11423
  },
@@ -11339,12 +11430,15 @@ async function authorizationTarget(trx, task, block) {
11339
11430
  }
11340
11431
  };
11341
11432
  }
11433
+ async function authorizationTarget(trx, task, block) {
11434
+ return subjectTarget(trx, task === void 0 ? void 0 : taskSubject(task), block);
11435
+ }
11342
11436
  async function taskTarget(trx, key) {
11343
11437
  return [await authorizationTarget(trx, await taskByKey$1(trx, key))];
11344
11438
  }
11345
11439
  async function blockTarget(trx, id) {
11346
11440
  const block = await blockById(trx, id);
11347
- return [await authorizationTarget(trx, block === void 0 ? void 0 : await taskById$1(trx, block.task_id), block)];
11441
+ return [await subjectTarget(trx, block === void 0 ? void 0 : await blockSubject(trx, block), block)];
11348
11442
  }
11349
11443
  async function turnTarget(trx, id) {
11350
11444
  const turn = await trx.selectFrom("turn").select("task_id").where("id", "=", idNumber(id)).executeTakeFirst();
@@ -11360,7 +11454,7 @@ async function turnTarget(trx, id) {
11360
11454
  async function commentTarget(trx, id) {
11361
11455
  const comment = await commentById(trx, id);
11362
11456
  return {
11363
- ...await authorizationTarget(trx, comment === void 0 ? void 0 : await taskById$1(trx, comment.task_id)),
11457
+ ...await subjectTarget(trx, comment === void 0 ? void 0 : await rowSubject(trx, comment)),
11364
11458
  id
11365
11459
  };
11366
11460
  }
@@ -11374,10 +11468,11 @@ function current$1(block) {
11374
11468
  addressee: block.addressee_role
11375
11469
  };
11376
11470
  }
11377
- function blockView(block, task) {
11471
+ function blockView(block, subject) {
11378
11472
  return {
11379
11473
  id: blockId$1(block.id),
11380
- task: task.key,
11474
+ task: subject.task?.key ?? null,
11475
+ ...subject.task === null ? { project: subject.project } : {},
11381
11476
  type: block.type,
11382
11477
  state: block.state,
11383
11478
  author: block.author,
@@ -11390,10 +11485,10 @@ function blockView(block, task) {
11390
11485
  unblockedAt: block.unblocked_at
11391
11486
  };
11392
11487
  }
11393
- function commentView(comment, task) {
11488
+ function commentView(comment, subject) {
11394
11489
  return {
11395
11490
  id: commentId(comment.id),
11396
- task: task.key,
11491
+ task: subject.task?.key ?? null,
11397
11492
  block: comment.block_id === null ? null : blockId$1(comment.block_id),
11398
11493
  author: comment.author,
11399
11494
  at: comment.created_at,
@@ -11403,8 +11498,8 @@ function commentView(comment, task) {
11403
11498
  untrusted: true
11404
11499
  };
11405
11500
  }
11406
- async function journal$1(trx, task, ctx, kind, payload) {
11407
- await emit(trx, kind, task.project, task.id, ctx.at, payload, ctx.actor);
11501
+ async function journal$1(trx, subject, ctx, kind, payload) {
11502
+ await emit(trx, kind, subject.project, subject.task?.id ?? null, ctx.at, payload, ctx.actor);
11408
11503
  }
11409
11504
  async function hasWorker(trx, task) {
11410
11505
  return await trx.selectFrom("link").select("id").where("task_id", "=", task.id).where("entity", "=", "session").where("role", "=", "worker").where("banned", "=", 0).executeTakeFirst() !== void 0;
@@ -11414,7 +11509,7 @@ async function routeBlock(trx, task, block, config) {
11414
11509
  return blockAddressee({
11415
11510
  type: block.type,
11416
11511
  author: block.author,
11417
- authorRole: authorRole(config, task, block.author),
11512
+ authorRole: authorRole(config, taskSubject(task), block.author),
11418
11513
  column: task.column,
11419
11514
  orchestrator: orchestrator(config, task),
11420
11515
  curator: curatorProject(config, task.project),
@@ -11434,9 +11529,9 @@ function wroteBlock(config, actor, target) {
11434
11529
  }).status === "allowed";
11435
11530
  }
11436
11531
  /** Inserts a comment row and journals `comment_added`; it rings and posts nothing. */
11437
- async function insertComment(trx, task, blockId, text, ctx, addressee, source, forwardedFrom) {
11532
+ async function insertComment(trx, subject, blockId, text, ctx, addressee, source, forwardedFrom) {
11438
11533
  const row = await trx.insertInto("comment").values({
11439
- task_id: task.id,
11534
+ task_id: subject.task?.id ?? null,
11440
11535
  block_id: blockId,
11441
11536
  author: ctx.actor,
11442
11537
  text,
@@ -11447,38 +11542,41 @@ async function insertComment(trx, task, blockId, text, ctx, addressee, source, f
11447
11542
  created_at: ctx.at,
11448
11543
  delivery_state: null
11449
11544
  }).returningAll().executeTakeFirstOrThrow();
11450
- await journal$1(trx, task, ctx, "comment_added", {
11545
+ await journal$1(trx, subject, ctx, "comment_added", {
11451
11546
  comment: commentId(row.id),
11452
11547
  addressee,
11453
11548
  ...forwardedFrom === void 0 ? {} : { forwardedFrom: commentId(forwardedFrom) }
11454
11549
  });
11455
11550
  return row;
11456
11551
  }
11457
- async function addComment(trx, task, block, text, ctx, addressee, config, options = {}) {
11552
+ async function addComment(trx, subject, block, text, ctx, addressee, config, options = {}) {
11458
11553
  const { source, ringsAuthor = true } = options;
11459
- const row = await insertComment(trx, task, block?.id ?? null, text, ctx, addressee, source);
11554
+ const row = await insertComment(trx, subject, block?.id ?? null, text, ctx, addressee, source);
11460
11555
  if (ringsAuthor) await applyDoorbellPolicy(trx, block === void 0 ? { kind: "task_comment" } : {
11461
11556
  kind: "answer",
11462
11557
  block,
11463
11558
  commentId: row.id,
11464
11559
  revision: row.revision,
11465
- authorRole: authorRole(config, task, block.author),
11560
+ authorRole: authorRole(config, subject, block.author),
11466
11561
  actor: ctx.actor
11467
11562
  }, new Date(ctx.at));
11468
11563
  if (block !== void 0 && source === void 0) await enqueueConversationReply(trx, {
11469
11564
  commentId: row.id,
11470
- persona: personaFor(config, task, ctx.actor),
11565
+ persona: personaFor(config, subject, ctx.actor),
11471
11566
  at: new Date(ctx.at)
11472
11567
  });
11473
11568
  return row;
11474
11569
  }
11475
- async function openBlock(trx, task, type, reason, ctx, config, addressee) {
11476
- addressee ??= await routeBlock(trx, task, {
11570
+ /** Opens a block; a project-level block, which has no task to route by, goes to the operator. */
11571
+ async function openBlock(trx, subject, type, reason, ctx, config, addressee) {
11572
+ const { task } = subject;
11573
+ addressee ??= task === null ? "operator" : await routeBlock(trx, task, {
11477
11574
  type,
11478
11575
  author: ctx.actor
11479
11576
  }, config);
11480
11577
  const row = await trx.insertInto("block").values({
11481
- task_id: task.id,
11578
+ task_id: task?.id ?? null,
11579
+ project: task === null ? subject.project : null,
11482
11580
  type,
11483
11581
  reason,
11484
11582
  author: ctx.actor,
@@ -11492,7 +11590,7 @@ async function openBlock(trx, task, type, reason, ctx, config, addressee) {
11492
11590
  unblocked_at: null,
11493
11591
  created_at: ctx.at
11494
11592
  }).returningAll().executeTakeFirstOrThrow();
11495
- await journal$1(trx, task, ctx, "block_opened", {
11593
+ await journal$1(trx, subject, ctx, "block_opened", {
11496
11594
  block: blockId$1(row.id),
11497
11595
  type,
11498
11596
  addressee
@@ -11500,7 +11598,7 @@ async function openBlock(trx, task, type, reason, ctx, config, addressee) {
11500
11598
  await applyDoorbellPolicy(trx, {
11501
11599
  kind: "block_opened",
11502
11600
  block: row,
11503
- authorRole: authorRole(config, task, ctx.actor)
11601
+ authorRole: authorRole(config, subject, ctx.actor)
11504
11602
  }, new Date(ctx.at));
11505
11603
  return row;
11506
11604
  }
@@ -11515,8 +11613,9 @@ async function openSystemBlock(trx, input) {
11515
11613
  actor: "system",
11516
11614
  at
11517
11615
  };
11518
- const block = await openBlock(trx, task, "needs_input", reason, ctx, config, addressee);
11519
- await queueBlockOpen(trx, task, block, ctx, config);
11616
+ const subject = taskSubject(task);
11617
+ const block = await openBlock(trx, subject, "needs_input", reason, ctx, config, addressee);
11618
+ await queueBlockOpen(trx, subject, block, ctx, config);
11520
11619
  return block;
11521
11620
  }
11522
11621
  /**
@@ -11530,7 +11629,7 @@ async function forwardCourseNote(trx, task, block, ctx, reason, given) {
11530
11629
  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();
11531
11630
  const text = reason ?? answer?.text;
11532
11631
  if (text === void 0) return void 0;
11533
- const copy = await insertComment(trx, task, null, text, ctx, "worker", void 0, answer?.id);
11632
+ const copy = await insertComment(trx, taskSubject(task), null, text, ctx, "worker", void 0, answer?.id);
11534
11633
  await applyDoorbellPolicy(trx, {
11535
11634
  kind: "course_note",
11536
11635
  block,
@@ -11548,13 +11647,13 @@ async function forwardedCopies(trx, id) {
11548
11647
  return trx.selectFrom("comment").selectAll().where("id", "in", ids).execute();
11549
11648
  }
11550
11649
  /** Writes an edit to one comment by the acknowledgment rule, with its `comment_edited`. */
11551
- async function reviseComment(trx, task, comment, text, ctx) {
11650
+ async function reviseComment(trx, subject, comment, text, ctx) {
11552
11651
  const next = editComment(comment.revision, comment.acked_revision);
11553
11652
  const updated = await trx.updateTable("comment").set({
11554
11653
  text,
11555
11654
  revision: next.revision
11556
11655
  }).where("id", "=", comment.id).returningAll().executeTakeFirstOrThrow();
11557
- await journal$1(trx, task, ctx, "comment_edited", {
11656
+ await journal$1(trx, subject, ctx, "comment_edited", {
11558
11657
  comment: commentId(comment.id),
11559
11658
  revision: next.revision,
11560
11659
  clarification: next.clarification
@@ -11572,7 +11671,7 @@ async function reviseComment(trx, task, comment, text, ctx) {
11572
11671
  * first, before the rings the check held; `answer` names the answer when the closing actor also
11573
11672
  * left a note after it.
11574
11673
  */
11575
- async function closeOpenBlock(trx, task, block, ctx, outcome, outcomeReason, answer) {
11674
+ async function closeOpenBlock(trx, subject, block, ctx, outcome, outcomeReason, answer) {
11576
11675
  const updated = await trx.updateTable("block").set({
11577
11676
  state: "unblocked",
11578
11677
  outcome,
@@ -11580,7 +11679,7 @@ async function closeOpenBlock(trx, task, block, ctx, outcome, outcomeReason, ans
11580
11679
  unblocked_by: ctx.actor,
11581
11680
  unblocked_at: ctx.at
11582
11681
  }).where("id", "=", block.id).returningAll().executeTakeFirstOrThrow();
11583
- await journal$1(trx, task, ctx, "block_unblocked", {
11682
+ await journal$1(trx, subject, ctx, "block_unblocked", {
11584
11683
  block: blockId$1(block.id),
11585
11684
  outcome,
11586
11685
  ...outcomeReason === null ? {} : { reason: outcomeReason }
@@ -11593,7 +11692,7 @@ async function closeOpenBlock(trx, task, block, ctx, outcome, outcomeReason, ans
11593
11692
  });
11594
11693
  await closeBlockNotification(trx, block.id, new Date(ctx.at), ctx.actor);
11595
11694
  const items = await trx.selectFrom("operator_item").selectAll().where("kind", "in", ["post_blocked", ...BLOCK_ITEM_KINDS]).where("block_id", "=", block.id).where("cleared_at", "is", null).execute();
11596
- if (ctx.actor !== "system" && (outcome === "done" || outcome === "reason") && items.some((item) => item.kind === "course_check")) await forwardCourseNote(trx, task, block, ctx, outcome === "reason" ? outcomeReason : null, answer);
11695
+ if (subject.task !== null && ctx.actor !== "system" && (outcome === "done" || outcome === "reason") && items.some((item) => item.kind === "course_check")) await forwardCourseNote(trx, subject.task, block, ctx, outcome === "reason" ? outcomeReason : null, answer);
11597
11696
  for (const item of items) if (item.kind === "post_blocked") await clearItem(trx, item.id, new Date(ctx.at), ctx.actor);
11598
11697
  else if (ctx.actor !== "system" && outcome !== "archived" && isItemKind(item.kind) && ITEM_POLICY[item.kind].reconciled) await dismissItem(trx, item, ctx.actor, new Date(ctx.at));
11599
11698
  else await clearItem(trx, item.id, new Date(ctx.at), ctx.actor);
@@ -11603,45 +11702,45 @@ async function closeOpenBlock(trx, task, block, ctx, outcome, outcomeReason, ans
11603
11702
  async function closeBlockIfOpen(trx, blockId, ctx, outcome, outcomeReason) {
11604
11703
  const block = await trx.selectFrom("block").selectAll().where("id", "=", blockId).where("state", "=", "open").executeTakeFirst();
11605
11704
  if (block === void 0) return;
11606
- await closeOpenBlock(trx, await trx.selectFrom("task").selectAll().where("id", "=", block.task_id).executeTakeFirstOrThrow(), block, ctx, outcome, outcomeReason);
11705
+ await closeOpenBlock(trx, await blockSubject(trx, block), block, ctx, outcome, outcomeReason);
11607
11706
  }
11608
11707
  /** Applies an operator message to the block selected by its conversation, without echoing it. */
11609
11708
  async function recordInboundBlockMessage(trx, input) {
11610
11709
  const block = await trx.selectFrom("block").selectAll().where("id", "=", input.blockId).executeTakeFirstOrThrow();
11611
- const task = await taskById$1(trx, block.task_id);
11710
+ const subject = await blockSubject(trx, block);
11612
11711
  const ctx = {
11613
11712
  actor: "operator",
11614
11713
  at: input.at
11615
11714
  };
11616
11715
  const answered = block.state === "open";
11617
11716
  if (answered) {
11618
- active(task);
11717
+ if (subject.task !== null) active(subject.task);
11619
11718
  rule(() => {
11620
11719
  answerBlock(current$1(block));
11621
11720
  });
11622
11721
  }
11623
11722
  return {
11624
- comment: await addComment(trx, task, block, input.text, ctx, authorRole(input.config, task, block.author), input.config, { source: {
11723
+ comment: await addComment(trx, subject, block, input.text, ctx, authorRole(input.config, subject, block.author), input.config, { source: {
11625
11724
  conversationRef: input.conversationRef,
11626
11725
  messageRef: input.messageRef
11627
11726
  } }),
11628
- block: answered ? await closeOpenBlock(trx, task, block, ctx, "done", null) : block,
11629
- task,
11727
+ block: answered ? await closeOpenBlock(trx, subject, block, ctx, "done", null) : block,
11728
+ subject,
11630
11729
  answered,
11631
- authorRole: authorRole(input.config, task, block.author)
11730
+ authorRole: authorRole(input.config, subject, block.author)
11632
11731
  };
11633
11732
  }
11634
11733
  /** Uses the same revision and acknowledgment rule as the catalog comment.edit mutation. */
11635
11734
  async function editInboundComment(trx, input) {
11636
- const task = await taskById$1(trx, input.comment.task_id);
11637
- active(task);
11735
+ const subject = await rowSubject(trx, input.comment);
11736
+ if (subject.task !== null) active(subject.task);
11638
11737
  if (input.comment.author !== input.actor) throw new CommandError("forbidden", "Only the comment author can edit it.");
11639
11738
  const ctx = {
11640
11739
  actor: input.actor,
11641
11740
  at: input.at
11642
11741
  };
11643
- const { updated, clarification } = await reviseComment(trx, task, input.comment, input.text, ctx);
11644
- for (const copy of await forwardedCopies(trx, input.comment.id)) await reviseComment(trx, task, copy, input.text, ctx);
11742
+ const { updated, clarification } = await reviseComment(trx, subject, input.comment, input.text, ctx);
11743
+ for (const copy of await forwardedCopies(trx, input.comment.id)) await reviseComment(trx, subject, copy, input.text, ctx);
11645
11744
  const answered = await trx.selectFrom("notification").select("id").where("kind", "=", "answer").where("comment_id", "=", updated.id).executeTakeFirst();
11646
11745
  if (clarification && updated.block_id !== null && answered !== void 0) {
11647
11746
  const block = await trx.selectFrom("block").selectAll().where("id", "=", updated.block_id).executeTakeFirstOrThrow();
@@ -11650,7 +11749,7 @@ async function editInboundComment(trx, input) {
11650
11749
  block,
11651
11750
  commentId: updated.id,
11652
11751
  revision: updated.revision,
11653
- authorRole: authorRole(input.config, task, block.author),
11752
+ authorRole: authorRole(input.config, subject, block.author),
11654
11753
  actor: input.actor
11655
11754
  }, new Date(input.at));
11656
11755
  }
@@ -11672,7 +11771,7 @@ async function ticketTitle(trx, task) {
11672
11771
  /** Posts a curator's answer to the feed; an operator answer is already on the board. */
11673
11772
  async function queueCuratorAnswerLine(trx, task, block, answer, note, ctx, config) {
11674
11773
  if (parseAddressee(block.addressee_role).kind !== "curator") return;
11675
- if (authorRole(config, task, ctx.actor) === "operator") return;
11774
+ if (authorRole(config, taskSubject(task), ctx.actor) === "operator") return;
11676
11775
  const curator = parseActorId(ctx.actor);
11677
11776
  if (curator?.actor !== "agent") return;
11678
11777
  const asker = parseActorId(block.author);
@@ -11701,16 +11800,20 @@ async function queueCuratorAnswerLine(trx, task, block, answer, note, ctx, confi
11701
11800
  }
11702
11801
  /** Concrete block and comment mutations for the generic apply boundary. */
11703
11802
  function createBlockMutations(config) {
11803
+ /** Opens a question block on a subject with the text as its first comment. */
11804
+ async function askOn(trx, subject, text, ctx) {
11805
+ const block = await openBlock(trx, subject, "needs_input", text, ctx, config);
11806
+ await addComment(trx, subject, block, text, ctx, block.addressee_role, config);
11807
+ await queueBlockOpen(trx, subject, block, ctx, config);
11808
+ return { block: blockView(block, subject) };
11809
+ }
11704
11810
  const ask = {
11705
11811
  id: "block.ask",
11706
11812
  resolveTargets: (trx, input) => taskTarget(trx, input.task),
11707
11813
  async run(trx, input, ctx) {
11708
11814
  const task = found(await taskByKey$1(trx, input.task));
11709
11815
  active(task);
11710
- const block = await openBlock(trx, task, "needs_input", input.text, ctx, config);
11711
- await addComment(trx, task, block, input.text, ctx, block.addressee_role, config);
11712
- await queueBlockOpen(trx, task, block, ctx, config);
11713
- return { block: blockView(block, task) };
11816
+ return askOn(trx, taskSubject(task), input.text, ctx);
11714
11817
  }
11715
11818
  };
11716
11819
  const create = {
@@ -11719,9 +11822,10 @@ function createBlockMutations(config) {
11719
11822
  async run(trx, input, ctx) {
11720
11823
  const task = found(await taskByKey$1(trx, input.task));
11721
11824
  active(task);
11722
- const block = await openBlock(trx, task, input.type, input.reason, ctx, config);
11723
- await queueBlockOpen(trx, task, block, ctx, config);
11724
- return { block: blockView(block, task) };
11825
+ const subject = taskSubject(task);
11826
+ const block = await openBlock(trx, subject, input.type, input.reason, ctx, config);
11827
+ await queueBlockOpen(trx, subject, block, ctx, config);
11828
+ return { block: blockView(block, subject) };
11725
11829
  }
11726
11830
  };
11727
11831
  const escalate = {
@@ -11729,10 +11833,12 @@ function createBlockMutations(config) {
11729
11833
  async resolveTargets(trx, input, actor) {
11730
11834
  const block = await blockById(trx, input.block);
11731
11835
  if (block === void 0) return blockTarget(trx, input.block);
11732
- const task = await taskById$1(trx, block.task_id);
11733
- const target = await authorizationTarget(trx, task, block);
11836
+ const subject = await blockSubject(trx, block);
11837
+ const target = await subjectTarget(trx, subject, block);
11734
11838
  if (target.kind !== "found" || target.value.block === null) return [target];
11735
11839
  if (holdsBlock(config, actor, target)) return [target];
11840
+ const { task } = subject;
11841
+ if (task === null) return [target];
11736
11842
  const priors = priorAddressees(await routeBlock(trx, task, block, config), block.addressee_role, block.type, curatorProject(config, task.project) !== null);
11737
11843
  for (const addressee_role of priors) {
11738
11844
  const prior = {
@@ -11751,16 +11857,17 @@ function createBlockMutations(config) {
11751
11857
  },
11752
11858
  async run(trx, input, ctx) {
11753
11859
  const block = found(await blockById(trx, input.block));
11754
- const task = await taskById$1(trx, block.task_id);
11755
- active(task);
11756
- const hasCurator = curatorProject(config, task.project) !== null;
11860
+ const subject = await blockSubject(trx, block);
11861
+ const { task } = subject;
11862
+ if (task !== null) active(task);
11863
+ const hasCurator = curatorProject(config, subject.project) !== null;
11757
11864
  const next = rule(() => escalateBlock(current$1(block), hasCurator));
11758
11865
  const unchanged = async () => {
11759
- if (input.note !== void 0) await addComment(trx, task, block, input.note, ctx, block.addressee_role, config, { ringsAuthor: false });
11760
- return { block: blockView(block, task) };
11866
+ if (input.note !== void 0) await addComment(trx, subject, block, input.note, ctx, block.addressee_role, config, { ringsAuthor: false });
11867
+ return { block: blockView(block, subject) };
11761
11868
  };
11762
- if (!next.changed) return unchanged();
11763
- const target = await authorizationTarget(trx, task, block);
11869
+ if (!next.changed || task === null) return unchanged();
11870
+ const target = await subjectTarget(trx, subject, block);
11764
11871
  if (!holdsBlock(config, ctx.actor, target)) return unchanged();
11765
11872
  const updated = await moveBlockToAddressee(trx, {
11766
11873
  task,
@@ -11769,8 +11876,8 @@ function createBlockMutations(config) {
11769
11876
  ctx,
11770
11877
  config
11771
11878
  });
11772
- if (input.note !== void 0) await addComment(trx, task, updated, input.note, ctx, next.addressee, config, { ringsAuthor: false });
11773
- return { block: blockView(updated, task) };
11879
+ if (input.note !== void 0) await addComment(trx, subject, updated, input.note, ctx, next.addressee, config, { ringsAuthor: false });
11880
+ return { block: blockView(updated, subject) };
11774
11881
  }
11775
11882
  };
11776
11883
  const answer = {
@@ -11778,19 +11885,20 @@ function createBlockMutations(config) {
11778
11885
  resolveTargets: (trx, input) => blockTarget(trx, input.block),
11779
11886
  async run(trx, input, ctx) {
11780
11887
  const block = found(await blockById(trx, input.block));
11781
- const task = await taskById$1(trx, block.task_id);
11782
- active(task);
11888
+ const subject = await blockSubject(trx, block);
11889
+ const { task } = subject;
11890
+ if (task !== null) active(task);
11783
11891
  rule(() => {
11784
11892
  answerBlock(current$1(block));
11785
11893
  });
11786
- const role = authorRole(config, task, block.author);
11787
- const comment = await addComment(trx, task, block, input.text, ctx, role, config);
11788
- if (input.note !== void 0) await addComment(trx, task, block, input.note, ctx, role, config, { ringsAuthor: false });
11789
- const updated = await closeOpenBlock(trx, task, block, ctx, "done", null, comment);
11790
- await queueCuratorAnswerLine(trx, task, block, comment, input.note, ctx, config);
11894
+ const role = authorRole(config, subject, block.author);
11895
+ const comment = await addComment(trx, subject, block, input.text, ctx, role, config);
11896
+ if (input.note !== void 0) await addComment(trx, subject, block, input.note, ctx, role, config, { ringsAuthor: false });
11897
+ const updated = await closeOpenBlock(trx, subject, block, ctx, "done", null, comment);
11898
+ if (task !== null) await queueCuratorAnswerLine(trx, task, block, comment, input.note, ctx, config);
11791
11899
  return {
11792
- block: blockView(updated, task),
11793
- comment: commentView(comment, task)
11900
+ block: blockView(updated, subject),
11901
+ comment: commentView(comment, subject)
11794
11902
  };
11795
11903
  }
11796
11904
  };
@@ -11799,9 +11907,9 @@ function createBlockMutations(config) {
11799
11907
  resolveTargets: (trx, input) => blockTarget(trx, input.block),
11800
11908
  async run(trx, input, ctx) {
11801
11909
  const block = found(await blockById(trx, input.block));
11802
- const task = await taskById$1(trx, block.task_id);
11803
- active(task);
11804
- const target = await authorizationTarget(trx, task, block);
11910
+ const subject = await blockSubject(trx, block);
11911
+ if (subject.task !== null) active(subject.task);
11912
+ const target = await subjectTarget(trx, subject, block);
11805
11913
  const decision = rule(() => input.mode === "done" ? closeBlock(current$1(block), {
11806
11914
  mode: "done",
11807
11915
  ...input.ref === void 0 ? {} : { ref: input.ref }
@@ -11813,13 +11921,13 @@ function createBlockMutations(config) {
11813
11921
  isAuthor: wroteBlock(config, ctx.actor, target),
11814
11922
  reason: input.answer
11815
11923
  }));
11816
- if (input.mode === "withdraw") await addComment(trx, task, block, input.answer, ctx, block.addressee_role, config, { ringsAuthor: false });
11817
- const updated = await closeOpenBlock(trx, task, block, ctx, decision.outcome, decision.outcomeReason);
11924
+ if (input.mode === "withdraw") await addComment(trx, subject, block, input.answer, ctx, block.addressee_role, config, { ringsAuthor: false });
11925
+ const updated = await closeOpenBlock(trx, subject, block, ctx, decision.outcome, decision.outcomeReason);
11818
11926
  await applyDoorbellPolicy(trx, input.mode === "done" || holdsBlock(config, ctx.actor, target) ? { kind: "block_closed_by_addressee" } : {
11819
11927
  kind: "block_removed",
11820
11928
  block: updated
11821
11929
  }, new Date(ctx.at));
11822
- return { block: blockView(updated, task) };
11930
+ return { block: blockView(updated, subject) };
11823
11931
  }
11824
11932
  };
11825
11933
  const add = {
@@ -11830,11 +11938,12 @@ function createBlockMutations(config) {
11830
11938
  active(task);
11831
11939
  const block = input.block === void 0 ? void 0 : found(await blockById(trx, input.block));
11832
11940
  if (block !== void 0 && block.task_id !== task.id) throw new CommandError("not_found", "Block does not belong to this task.");
11941
+ const subject = taskSubject(task);
11833
11942
  let addressee = "worker";
11834
- if (block !== void 0) if (ctx.actor !== block.author) addressee = authorRole(config, task, block.author);
11835
- else if (block.outcome === "done" && block.unblocked_by !== null && block.unblocked_by !== block.author) addressee = authorRole(config, task, block.unblocked_by);
11943
+ if (block !== void 0) if (ctx.actor !== block.author) addressee = authorRole(config, subject, block.author);
11944
+ else if (block.outcome === "done" && block.unblocked_by !== null && block.unblocked_by !== block.author) addressee = authorRole(config, subject, block.unblocked_by);
11836
11945
  else addressee = block.addressee_role;
11837
- return { comment: commentView(await addComment(trx, task, block, input.text, ctx, addressee, config), task) };
11946
+ return { comment: commentView(await addComment(trx, subject, block, input.text, ctx, addressee, config), subject) };
11838
11947
  }
11839
11948
  };
11840
11949
  const edit = {
@@ -11851,12 +11960,12 @@ function createBlockMutations(config) {
11851
11960
  at: ctx.at,
11852
11961
  actor: ctx.actor,
11853
11962
  config
11854
- }), await taskById$1(trx, comment.task_id)) };
11963
+ }), await rowSubject(trx, comment)) };
11855
11964
  }
11856
11965
  };
11857
11966
  /** Marks a comment read at `revision` and acks its unread answer notifications. */
11858
11967
  async function ackComment(trx, comment, revision, ctx) {
11859
- const task = await taskById$1(trx, comment.task_id);
11968
+ const subject = await rowSubject(trx, comment);
11860
11969
  await acknowledgeNotification(trx, {
11861
11970
  commentId: comment.id,
11862
11971
  revision,
@@ -11865,7 +11974,7 @@ function createBlockMutations(config) {
11865
11974
  config
11866
11975
  });
11867
11976
  await trx.updateTable("comment").set({ acked_revision: revision }).where("id", "=", comment.id).execute();
11868
- await journal$1(trx, task, ctx, "comment_acked", {
11977
+ await journal$1(trx, subject, ctx, "comment_acked", {
11869
11978
  comment: commentId(comment.id),
11870
11979
  revision
11871
11980
  });
@@ -11944,7 +12053,7 @@ function createBlockMutations(config) {
11944
12053
  id
11945
12054
  };
11946
12055
  return {
11947
- ...await authorizationTarget(trx, await taskById$1(trx, notice.task_id)),
12056
+ ...await subjectTarget(trx, await rowSubject(trx, notice)),
11948
12057
  id
11949
12058
  };
11950
12059
  }
@@ -11977,6 +12086,11 @@ function createBlockMutations(config) {
11977
12086
  alreadyHandled
11978
12087
  } : { acked };
11979
12088
  }
12089
+ },
12090
+ projectAsk: {
12091
+ id: "project.ask",
12092
+ resolveTargets: (_trx, input) => Promise.resolve([config.projects.some((project) => project.id === input.project) ? projectTarget(input.project) : { kind: "missing" }]),
12093
+ run: (trx, input, ctx) => askOn(trx, projectSubject(input.project), input.text, ctx)
11980
12094
  }
11981
12095
  };
11982
12096
  }
@@ -11994,7 +12108,7 @@ async function archiveTask(trx, input) {
11994
12108
  at
11995
12109
  };
11996
12110
  const blocks = await trx.selectFrom("block").selectAll().where("task_id", "=", task.id).where("state", "=", "open").orderBy("id").execute();
11997
- for (const block of blocks) await closeOpenBlock(trx, task, block, ctx, "archived", null);
12111
+ for (const block of blocks) await closeOpenBlock(trx, taskSubject(task), block, ctx, "archived", null);
11998
12112
  await closeTurns(trx, {
11999
12113
  taskId: task.id,
12000
12114
  reason: "archived",
@@ -13088,12 +13202,31 @@ async function run(trx, input, ctx, config, remove) {
13088
13202
  target
13089
13203
  };
13090
13204
  }
13205
+ const session = input.mode === "session" ? await sessionSnapshot(trx, input.session) : null;
13206
+ const orchestrator = session !== null && config.projects.some((project) => project.spurProjects.some((spur) => spur.name === session.spurProject && spur.role === "orchestrator"));
13207
+ if (orchestrator && current !== void 0 && (current.role === "worker" || current.role === "other")) {
13208
+ const demoted = current.role === "worker";
13209
+ if (demoted) await trx.updateTable("link").set({ role: "other" }).where("id", "=", current.id).execute();
13210
+ const rerouted = await rerouteDemotedWorkerTurn(trx, {
13211
+ taskId: task.id,
13212
+ sessionId: session.id,
13213
+ at: new Date(ctx.at),
13214
+ config
13215
+ });
13216
+ if (demoted || rerouted) await emit(trx, "link_added", task.project, task.id, ctx.at, {
13217
+ entity: "session",
13218
+ session: session.id,
13219
+ role: "other",
13220
+ source: current.source,
13221
+ facts: session,
13222
+ reason: "Configured orchestrator sessions cannot be task workers."
13223
+ }, ctx.actor);
13224
+ }
13091
13225
  if (current?.banned === 0 && current.source === "manual" && (input.mode !== "pr" || current.pr_state === "active")) return {
13092
13226
  task: key,
13093
13227
  target
13094
13228
  };
13095
- const role = input.mode === "session" ? current?.role ?? await sessionRole(trx, task.id) : null;
13096
- const session = input.mode === "session" ? await sessionSnapshot(trx, input.session) : null;
13229
+ const role = input.mode === "session" ? orchestrator ? "other" : current?.role ?? await sessionRole(trx, task.id) : null;
13097
13230
  if (current === void 0) await trx.insertInto("link").values({
13098
13231
  task_id: task.id,
13099
13232
  entity: input.mode,
@@ -13111,6 +13244,7 @@ async function run(trx, input, ctx, config, remove) {
13111
13244
  else await trx.updateTable("link").set({
13112
13245
  source: "manual",
13113
13246
  banned: 0,
13247
+ ...input.mode === "session" ? { role } : {},
13114
13248
  ...pr === null ? {} : {
13115
13249
  pr_state: "active",
13116
13250
  pr_open: open ? 1 : 0
@@ -13227,6 +13361,12 @@ async function getStatus(deps, options = {}) {
13227
13361
  const rows = await store.db.selectFrom("task").selectAll().where("membership", "!=", "archived").execute();
13228
13362
  const blockRows = await store.db.selectFrom("block").select(["task_id", (eb) => eb.fn.countAll().as("open")]).where("state", "=", "open").groupBy("task_id").execute();
13229
13363
  const openBlocks = new Map(blockRows.map((row) => [row.task_id, row.open]));
13364
+ const projectBlockRows = await store.db.selectFrom("block").select(["project", (eb) => eb.fn.countAll().as("open")]).where("state", "=", "open").where("task_id", "is", null).groupBy("project").execute();
13365
+ const openProjectBlocks = new Map(projectBlockRows.map((row) => [row.project, row.open]));
13366
+ const projectBlocks = projects.map((project) => ({
13367
+ project: project.id,
13368
+ openBlocks: openProjectBlocks.get(project.id) ?? 0
13369
+ }));
13230
13370
  const tasks = [];
13231
13371
  for (const task of rows) {
13232
13372
  if (!projectIds.has(task.project)) continue;
@@ -13402,6 +13542,7 @@ async function getStatus(deps, options = {}) {
13402
13542
  transport,
13403
13543
  sources,
13404
13544
  tasks,
13545
+ projectBlocks,
13405
13546
  unlinkedPrs,
13406
13547
  unlinkedSessions,
13407
13548
  hiddenUnlinkedPrs: prRows.length - unlinkedPrs.length,
@@ -14164,14 +14305,20 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped) {
14164
14305
  const blockedIds = new Set(blockedRoots.map((item) => item.block_id));
14165
14306
  const ledgerRoots = await trx.selectFrom("operator_item").select("block_id").where("kind", "in", BLOCK_ITEM_KINDS).where("cleared_at", "is", null).execute();
14166
14307
  const ledgerIds = new Set(ledgerRoots.map((item) => item.block_id));
14167
- for (const block of blocks) {
14308
+ const subjectOf = (block) => {
14309
+ if (block.task_id === null) return block.project === null ? void 0 : projectSubject(block.project);
14168
14310
  const task = taskById.get(block.task_id);
14169
- if (task === void 0 || ledgerIds.has(block.id)) continue;
14311
+ return task === void 0 ? void 0 : taskSubject(task);
14312
+ };
14313
+ for (const block of blocks) {
14314
+ const subject = subjectOf(block);
14315
+ if (subject === void 0 || ledgerIds.has(block.id)) continue;
14316
+ const taskId = subject.task?.id ?? null;
14170
14317
  if (block.addressee_role === "operator" && block.author !== "operator" && !blockedIds.has(block.id)) candidates.push({
14171
14318
  key: `operator-block:${String(block.id)}`,
14172
14319
  kind: "board_observation",
14173
- taskId: task.id,
14174
- summary: `${task.key}: ${block.reason}`,
14320
+ taskId,
14321
+ summary: `${subject.key}: ${block.reason}`,
14175
14322
  factAt: block.created_at,
14176
14323
  source: null,
14177
14324
  priority: 0
@@ -14179,8 +14326,8 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped) {
14179
14326
  if (now - Date.parse(block.created_at) >= config.thresholds.blockOpenMs) candidates.push({
14180
14327
  key: `block:${String(block.id)}`,
14181
14328
  kind: "board_observation",
14182
- taskId: task.id,
14183
- summary: `${task.key}: block has been open for more than a day`,
14329
+ taskId,
14330
+ summary: `${subject.key}: block has been open for more than a day`,
14184
14331
  factAt: block.created_at,
14185
14332
  source: null,
14186
14333
  priority: 3
@@ -14421,7 +14568,7 @@ async function reconcileItems(trx, config, now, spurComplete, warnSkipped) {
14421
14568
  itemKey: candidate.key,
14422
14569
  kind: candidate.kind,
14423
14570
  text: candidate.summary,
14424
- url: task === null || task === void 0 ? "https://github.com" : taskUrl(task, config),
14571
+ url: task === null || task === void 0 ? TASKLESS_ITEM_URL : taskUrl(task, config),
14425
14572
  at: new Date(now),
14426
14573
  fingerprint: hash,
14427
14574
  factAt: candidate.factAt,
@@ -15152,17 +15299,6 @@ function submitSummary(kind, payloadText) {
15152
15299
  return null;
15153
15300
  }
15154
15301
  }
15155
- function projectTarget(project) {
15156
- return {
15157
- kind: "found",
15158
- value: {
15159
- project,
15160
- task: null,
15161
- block: null,
15162
- workers: []
15163
- }
15164
- };
15165
- }
15166
15302
  function visibleProjects(config, actor) {
15167
15303
  return new Set(config.projects.filter((project) => authorize([{ grant: "operator" }, { grant: "project-agent" }], actor, {
15168
15304
  config,
@@ -15270,6 +15406,7 @@ function createTaskQueries(deps) {
15270
15406
  trx.selectFrom("comment").selectAll().where("task_id", "=", task.id).orderBy("id").execute(),
15271
15407
  trx.selectFrom("link").leftJoin("pr_snapshot", (join) => join.on(sql`lower(pr_snapshot.repo) = lower(link.repo)`).onRef("pr_snapshot.number", "=", "link.number")).selectAll("link").select("pr_snapshot.state").where("link.task_id", "=", task.id).where("link.banned", "=", 0).orderBy("link.id").execute()
15272
15408
  ]);
15409
+ const subject = taskSubject(task);
15273
15410
  return {
15274
15411
  task: taskView(task),
15275
15412
  ...await taskTurns(trx, task, input.detail === true),
@@ -15280,8 +15417,8 @@ function createTaskQueries(deps) {
15280
15417
  ...observed === void 0 ? {} : { state: observed }
15281
15418
  };
15282
15419
  }),
15283
- blocks: blocks.map((block) => blockView(block, task)),
15284
- comments: comments.map((comment) => commentView(comment, task)),
15420
+ blocks: blocks.map((block) => blockView(block, subject)),
15421
+ comments: comments.map((comment) => commentView(comment, subject)),
15285
15422
  ...input.why === true ? { why: await why(trx, task) } : {}
15286
15423
  };
15287
15424
  }
@@ -15341,14 +15478,14 @@ function createTaskQueries(deps) {
15341
15478
  const listed = /* @__PURE__ */ new Set();
15342
15479
  for (const notice of notices) {
15343
15480
  if (notice.comment_id === null || seen.has(notice.comment_id)) continue;
15344
- const task = await trx.selectFrom("task").selectAll().where("id", "=", notice.task_id).executeTakeFirst();
15345
- if (task === void 0 || !projects.has(task.project)) continue;
15481
+ const subject = await rowSubject(trx, notice);
15482
+ if (!projects.has(subject.project)) continue;
15346
15483
  seen.add(notice.comment_id);
15347
15484
  if (!await notificationAddressedTo(trx, notice, actor, config)) continue;
15348
15485
  const comment = await trx.selectFrom("comment").selectAll().where("id", "=", notice.comment_id).executeTakeFirst();
15349
15486
  if (comment === void 0 || comment.acked_revision === comment.revision) continue;
15350
15487
  listed.add(comment.id);
15351
- comments.push(commentView(comment, task));
15488
+ comments.push(commentView(comment, subject));
15352
15489
  }
15353
15490
  const parsedActor = parseActorId(actor);
15354
15491
  if (parsedActor?.actor === "agent") {
@@ -15357,9 +15494,9 @@ function createTaskQueries(deps) {
15357
15494
  if (tasksById.size > 0) {
15358
15495
  const taskComments = await trx.selectFrom("comment").selectAll().where("task_id", "in", [...tasksById.keys()]).where("block_id", "is", null).orderBy("id").execute();
15359
15496
  for (const comment of taskComments) {
15360
- const task = tasksById.get(comment.task_id);
15497
+ const task = comment.task_id === null ? void 0 : tasksById.get(comment.task_id);
15361
15498
  if (task === void 0 || listed.has(comment.id) || comment.author === actor || comment.acked_revision === comment.revision) continue;
15362
- comments.push(commentView(comment, task));
15499
+ comments.push(commentView(comment, taskSubject(task)));
15363
15500
  }
15364
15501
  }
15365
15502
  }
@@ -15367,14 +15504,14 @@ function createTaskQueries(deps) {
15367
15504
  const rows = await trx.selectFrom("block").selectAll().where("state", "=", "open").orderBy("id").execute();
15368
15505
  const blocks = [];
15369
15506
  for (const block of rows) {
15370
- const task = await trx.selectFrom("task").selectAll().where("id", "=", block.task_id).executeTakeFirst();
15371
- if (task === void 0 || !projects.has(task.project)) continue;
15372
- const target = await authorizationTarget(trx, task, block);
15507
+ const subject = await blockSubject(trx, block);
15508
+ if (!projects.has(subject.project)) continue;
15509
+ const target = await subjectTarget(trx, subject, block);
15373
15510
  if (authorize([{ grant: "block-addressee" }], actor, {
15374
15511
  config,
15375
15512
  target
15376
15513
  }).status !== "allowed") continue;
15377
- blocks.push(blockView(block, task));
15514
+ blocks.push(blockView(block, subject));
15378
15515
  }
15379
15516
  return {
15380
15517
  comments,
@@ -15665,8 +15802,8 @@ function createTurnMutations(deps) {
15665
15802
  async run(trx, input, ctx) {
15666
15803
  const { turn, task } = await takenTurn(trx, input.turn, ctx);
15667
15804
  if (!RETURNABLE.includes(task.column)) throw new CommandError("return_not_allowed", `The task is in ${task.column}; only a task right of Dev returns to Dev.`);
15668
- const block = await openBlock(trx, task, "code", input.reason, ctx, config);
15669
- await queueBlockOpen(trx, task, block, ctx, config);
15805
+ const block = await openBlock(trx, taskSubject(task), "code", input.reason, ctx, config);
15806
+ await queueBlockOpen(trx, taskSubject(task), block, ctx, config);
15670
15807
  await moveLeft(trx, {
15671
15808
  task,
15672
15809
  to: "dev",
@@ -15679,7 +15816,7 @@ function createTurnMutations(deps) {
15679
15816
  const moved = await dispatched(trx, task.id, ctx.at);
15680
15817
  return {
15681
15818
  task: taskView(moved),
15682
- block: blockView(block, moved)
15819
+ block: blockView(block, taskSubject(moved))
15683
15820
  };
15684
15821
  }
15685
15822
  },
@@ -15809,6 +15946,7 @@ function createOperationRegistry(deps) {
15809
15946
  "comment.add": blocks.add,
15810
15947
  "comment.edit": blocks.edit,
15811
15948
  "inbox.ack": blocks.ack,
15949
+ "project.ask": blocks.projectAsk,
15812
15950
  "item.retry": items.retry,
15813
15951
  "item.close": items.close,
15814
15952
  "task.submit": turns.submit,
@@ -15846,6 +15984,17 @@ async function curatorSessions(db, config) {
15846
15984
  });
15847
15985
  return entries;
15848
15986
  }
15987
+ /** Configured orchestrators and the same live session selected for their rings. */
15988
+ async function orchestratorSessions(db, config) {
15989
+ const entries = [];
15990
+ for (const project of config.projects) for (const spur of project.spurProjects.filter((entry) => entry.role === "orchestrator")) entries.push({
15991
+ project: project.id,
15992
+ orchestrator: spur.name,
15993
+ session: (await bestProjectSession(db, spur.name))?.id ?? null,
15994
+ columns: project.columns.filter((column) => column.orchestrator !== "none" && column.orchestrator !== "operator" && column.orchestrator === spur.name).map((column) => column.id)
15995
+ });
15996
+ return entries;
15997
+ }
15849
15998
  /**
15850
15999
  * Called from an accepted observation's transaction after board and item reconciliation.
15851
16000
  * The version marker and feed row share that transaction with the source-state update.
@@ -16309,6 +16458,27 @@ async function session(trx, config, fact, at, source, ambiguousBranches) {
16309
16458
  observed_at: at,
16310
16459
  absent_since: null
16311
16460
  })).execute();
16461
+ const orchestrator = config.projects.some((project) => project.spurProjects.some((spur) => spur.name === fact.spurProject && spur.role === "orchestrator"));
16462
+ if (orchestrator) {
16463
+ const demoted = await trx.updateTable("link").set({ role: "other" }).where("entity", "=", "session").where("session_id", "=", fact.id).where("role", "=", "worker").returning(["task_id", "source"]).execute();
16464
+ const linked = await trx.selectFrom("link").select(["task_id", "source"]).where("entity", "=", "session").where("session_id", "=", fact.id).where("role", "=", "other").execute();
16465
+ for (const link of linked) {
16466
+ if (!await rerouteDemotedWorkerTurn(trx, {
16467
+ taskId: link.task_id,
16468
+ sessionId: fact.id,
16469
+ at: new Date(at),
16470
+ config
16471
+ }) && !demoted.some((entry) => entry.task_id === link.task_id)) continue;
16472
+ await emit(trx, "link_added", (await trx.selectFrom("task").select("project").where("id", "=", link.task_id).executeTakeFirstOrThrow()).project, link.task_id, at, {
16473
+ entity: "session",
16474
+ session: fact.id,
16475
+ role: "other",
16476
+ source: link.source,
16477
+ facts: fact,
16478
+ reason: "Configured orchestrator sessions cannot be task workers."
16479
+ });
16480
+ }
16481
+ }
16312
16482
  let key;
16313
16483
  let role;
16314
16484
  for (const label of ["board-worker", "board-other"]) {
@@ -16316,7 +16486,7 @@ async function session(trx, config, fact, at, source, ambiguousBranches) {
16316
16486
  if (url === void 0) continue;
16317
16487
  const candidate = BROWSE_KEY.exec(url)?.[1] ?? /\/issues\/([1-9]\d*)$/.exec(url)?.[1];
16318
16488
  key = candidate === void 0 ? void 0 : url.includes("/issues/") ? `${new URL(url).pathname.split("/").slice(1, 3).join("/")}#${candidate}` : candidate;
16319
- role = label === "board-worker" ? "worker" : "other";
16489
+ role = label === "board-worker" && !orchestrator ? "worker" : "other";
16320
16490
  if (key !== void 0) break;
16321
16491
  }
16322
16492
  let prOnlyKey;
@@ -16480,7 +16650,7 @@ function createObservationCore(deps) {
16480
16650
  kind: "session",
16481
16651
  id: link.session_id
16482
16652
  }]) : [];
16483
- const curators = config.projects.flatMap((project) => project.spurProjects.filter((spur) => spur.role === "curator").map((spur) => spur.name));
16653
+ const curators = config.projects.flatMap((project) => project.spurProjects.filter((spur) => spur.role === "curator" || spur.role === "orchestrator").map((spur) => spur.name));
16484
16654
  if (source === "spur" && curators.length > 0) {
16485
16655
  const rows = await store.db.selectFrom("session_snapshot").select("id").where("spur_project", "in", curators).where("ended_at", "is", null).execute();
16486
16656
  sessions.push(...rows.map((row) => ({
@@ -16876,7 +17046,7 @@ async function taskContext(trx, event, gateway) {
16876
17046
  taskId: null,
16877
17047
  project: null
16878
17048
  };
16879
- const row = await trx.selectFrom("conversation").leftJoin("task", "task.id", "conversation.task_id").select(["conversation.task_id as taskId", "task.project"]).where("conversation.gateway", "=", gateway).where("conversation.ref", "=", event.conversation).executeTakeFirst();
17049
+ const row = await trx.selectFrom("conversation").leftJoin("task", "task.id", "conversation.task_id").leftJoin("block", "block.id", "conversation.block_id").select((eb) => ["conversation.task_id as taskId", eb.fn.coalesce("task.project", "block.project").as("project")]).where("conversation.gateway", "=", gateway).where("conversation.ref", "=", event.conversation).executeTakeFirst();
16880
17050
  return {
16881
17051
  taskId: row?.taskId ?? null,
16882
17052
  project: row?.project ?? null
@@ -16947,7 +17117,7 @@ async function alreadyApplied(trx, event) {
16947
17117
  if (event.kind !== "message_edited" && event.kind !== "message_deleted") return false;
16948
17118
  const comment = await linkedComment(trx, event);
16949
17119
  if (comment === void 0 || comment.author !== "operator") return false;
16950
- const rows = await trx.selectFrom("event").select(["kind", "at"]).where("task_id", "=", comment.task_id).where("kind", "in", ["comment_deleted", "comment_edited"]).where(sql`json_extract(payload, '$.comment')`, "=", `C${String(comment.id)}`).execute();
17120
+ const rows = await trx.selectFrom("event").select(["kind", "at"]).where((eb) => comment.task_id === null ? eb("task_id", "is", null) : eb("task_id", "=", comment.task_id)).where("kind", "in", ["comment_deleted", "comment_edited"]).where(sql`json_extract(payload, '$.comment')`, "=", `C${String(comment.id)}`).execute();
16951
17121
  if (rows.some((row) => row.kind === "comment_deleted")) return true;
16952
17122
  if (event.kind === "message_deleted") return false;
16953
17123
  const editedAt = Date.parse(event.at);
@@ -16966,7 +17136,8 @@ async function ringAuthor(trx, input) {
16966
17136
  const parsed = parseActorId(input.block.author);
16967
17137
  if (parsed?.actor === "agent") {
16968
17138
  if (await selectNotificationRecipient(trx, {
16969
- task_id: input.task.id,
17139
+ task_id: input.subject.task?.id ?? null,
17140
+ block_id: input.block.id,
16970
17141
  role: input.authorRole,
16971
17142
  author_session: parsed.actorRef.session
16972
17143
  }, input.config) !== void 0) return;
@@ -16978,8 +17149,8 @@ async function ringAuthor(trx, input) {
16978
17149
  reason: parsed?.actor !== "agent" ? "author is not an agent" : "author session is unavailable"
16979
17150
  },
16980
17151
  actor: "system",
16981
- taskId: input.task.id,
16982
- project: input.task.project,
17152
+ taskId: input.subject.task?.id ?? null,
17153
+ project: input.subject.project,
16983
17154
  at: input.at
16984
17155
  });
16985
17156
  await raiseInboundItem(trx, {
@@ -16987,7 +17158,7 @@ async function ringAuthor(trx, input) {
16987
17158
  title: "Answer author unavailable",
16988
17159
  sourceUrl: input.event.sourceUrl,
16989
17160
  event: input.event,
16990
- taskId: input.task.id,
17161
+ taskId: input.subject.task?.id ?? null,
16991
17162
  at: input.at,
16992
17163
  retry: false
16993
17164
  });
@@ -17051,7 +17222,7 @@ function createInbound(input) {
17051
17222
  await ringAuthor(trx, {
17052
17223
  event,
17053
17224
  block: recorded.block,
17054
- task: recorded.task,
17225
+ subject: recorded.subject,
17055
17226
  comment: recorded.comment,
17056
17227
  authorRole: recorded.authorRole,
17057
17228
  at,
@@ -17077,7 +17248,7 @@ function createInbound(input) {
17077
17248
  });
17078
17249
  return { status: "applied" };
17079
17250
  }
17080
- const task = await trx.selectFrom("task").selectAll().where("id", "=", comment.task_id).executeTakeFirstOrThrow();
17251
+ const subject = await rowSubject(trx, comment);
17081
17252
  await journal(trx, {
17082
17253
  kind: "comment_deleted",
17083
17254
  payload: {
@@ -17085,8 +17256,8 @@ function createInbound(input) {
17085
17256
  normalizedEvent: event
17086
17257
  },
17087
17258
  actor: "operator",
17088
- taskId: task.id,
17089
- project: task.project,
17259
+ taskId: comment.task_id,
17260
+ project: subject.project,
17090
17261
  at
17091
17262
  });
17092
17263
  return { status: "applied" };
@@ -22451,6 +22622,21 @@ function curatorSessionsCheck(entries) {
22451
22622
  };
22452
22623
  return warning(id, fitFix([...segments.filter((entry) => entry.problem), ...segments.filter((entry) => !entry.problem)], ` ${CURATOR_TAIL}`, `${String(missing)} curators have no live session. Start a Spur session of each.`));
22453
22624
  }
22625
+ function orchestratorSessionsCheck(entries) {
22626
+ const segments = entries.map(({ project, orchestrator, session, columns }) => ({
22627
+ problem: session === null || columns.length === 0,
22628
+ unmatched: false,
22629
+ text: () => `${project}: orchestrator ${orchestrator}, ${session === null ? "no live session" : `session ${session}`}, ${columns.length === 0 ? "unused by columns" : `columns ${columns.join(", ")}`}`
22630
+ }));
22631
+ const problems = segments.filter((entry) => entry.problem);
22632
+ const fix = fitFix([...problems, ...segments.filter((entry) => !entry.problem)], problems.length === 0 ? "" : " Assign a column and start a live session for each orchestrator.", `${String(entries.length)} orchestrators; ${String(problems.length)} need a column or live session.`);
22633
+ return problems.length === 0 ? {
22634
+ id: "orchestrator.sessions",
22635
+ status: "pass",
22636
+ blocking: false,
22637
+ fix
22638
+ } : warning("orchestrator.sessions", fix);
22639
+ }
22454
22640
  function check(id, ok, fix) {
22455
22641
  return {
22456
22642
  id,
@@ -22591,6 +22777,7 @@ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch, { deadlineM
22591
22777
  checks.push(check("operator.path", operatorProject || token !== void 0, "Configure a Spur project with the operator role or approve a named operator token."));
22592
22778
  checks.push(await operatorTokensCheck(ctx, config));
22593
22779
  checks.push(curatorSessionsCheck(await curatorSessions(ctx.store.db, config)));
22780
+ checks.push(orchestratorSessionsCheck(await orchestratorSessions(ctx.store.db, config)));
22594
22781
  return {
22595
22782
  version: productVersion,
22596
22783
  checks