spur-board 0.23.1 → 0.25.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 errorCodeOf, C as SESSION_STATUSES, D as ticketFactsSchema, E as sessionFactsSchema, G as SLACK_BOT_SCOPES, H as RESERVED_PROJECT, L as successEnvelopeSchema, M as parseRef$1, N as taskKeySchema, O as actorIdSchema, P as ERRORS, S as SESSION_HEALTH_STATES, T as prRefSchema, U as configSchema, V as DEFAULT_SLACK_COMMAND, W as requiredSecretKeys, _ 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, s as sourceCursorSchema, t as assertNever, u as OPERATIONS, v as messageRefSchema, w as prFactsSchema, x as eventPayloadSchemas, y as userIdSchema, z as DEFAULT_LINK } from "./src-C6fOCG5L.mjs";
1
+ import { A as errorCodeOf, C as SESSION_STATUSES, D as ticketFactsSchema, E as sessionFactsSchema, G as SLACK_BOT_SCOPES, H as RESERVED_PROJECT, L as successEnvelopeSchema, M as parseRef$1, N as taskKeySchema, O as actorIdSchema, P as ERRORS, S as SESSION_HEALTH_STATES, T as prRefSchema, U as configSchema, V as DEFAULT_SLACK_COMMAND, W as requiredSecretKeys, _ 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, s as sourceCursorSchema, t as assertNever, u as OPERATIONS, v as messageRefSchema, w as prFactsSchema, x as eventPayloadSchemas, y as userIdSchema, z as DEFAULT_LINK } from "./src-Ron2NABC.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";
@@ -279,12 +279,123 @@ function toJson(schema, value) {
279
279
  return JSON.stringify(schema.parse(value));
280
280
  }
281
281
  //#endregion
282
+ //#region ../core/src/domain/blocks/blocks.ts
283
+ var BlockRuleError = class extends Error {
284
+ code;
285
+ constructor(code, message) {
286
+ super(message);
287
+ this.code = code;
288
+ }
289
+ };
290
+ /** Roles survive a change in the session currently filling them. */
291
+ function blockAddressee(input) {
292
+ const { type, author, authorRole, column, orchestrator, curator = null, hasWorker } = input;
293
+ if (author === "system") return orchestrator !== null ? `orchestrator:${column}` : hasWorker ? "worker" : "operator";
294
+ if (type === "code") return "worker";
295
+ if (type === "dependency" || type === "external") return authorRole;
296
+ const parsed = parseActorId(author);
297
+ const asker = parsed?.actor === "agent" ? parsed.actorRef.project : null;
298
+ if (asker !== null && asker === curator) return "operator";
299
+ if (orchestrator === "operator") return "operator";
300
+ if (orchestrator !== null && asker !== orchestrator) return `orchestrator:${column}`;
301
+ return curator === null ? "operator" : "curator";
302
+ }
303
+ function orchestratorColumn(role) {
304
+ return role.slice(13);
305
+ }
306
+ /** A new role fails typecheck here; a new kind fails at each caller's `assertNever`. */
307
+ function parseAddressee(role) {
308
+ switch (role) {
309
+ case "operator":
310
+ case "curator":
311
+ case "worker": return { kind: role };
312
+ default: return {
313
+ kind: "orchestrator",
314
+ column: orchestratorColumn(role)
315
+ };
316
+ }
317
+ }
318
+ function requireOpen(block) {
319
+ if (block.state === "open") return;
320
+ throw new BlockRuleError("block_not_open", `Block was ${block.outcome ?? "unblocked"} by ${block.unblockedBy ?? "unknown"}.`);
321
+ }
322
+ /** Only a question stops at the curator; every other step goes straight to the operator. */
323
+ function nextAddressee(current, type, hasCurator) {
324
+ const addressee = parseAddressee(current);
325
+ switch (addressee.kind) {
326
+ case "orchestrator": return type === "needs_input" && hasCurator ? "curator" : "operator";
327
+ case "operator":
328
+ case "curator":
329
+ case "worker": return "operator";
330
+ default: return assertNever(addressee);
331
+ }
332
+ }
333
+ /** The steps a block took from `original` to `current`, or none if `current` is not on that path. */
334
+ function priorAddressees(original, current, type, hasCurator) {
335
+ const path = [];
336
+ let step = original;
337
+ while (step !== current) {
338
+ const next = nextAddressee(step, type, hasCurator);
339
+ if (next === step) return [];
340
+ path.push(step);
341
+ step = next;
342
+ }
343
+ return path;
344
+ }
345
+ function escalateBlock(block, hasCurator = false) {
346
+ requireOpen(block);
347
+ const addressee = nextAddressee(block.addressee, block.type, hasCurator);
348
+ return {
349
+ addressee,
350
+ changed: block.addressee !== addressee
351
+ };
352
+ }
353
+ function answerBlock(block) {
354
+ requireOpen(block);
355
+ if (block.type !== "needs_input") throw new BlockRuleError("wrong_block_type", "Only a question block can be answered.");
356
+ }
357
+ function closeBlock(block, input) {
358
+ requireOpen(block);
359
+ if (input.mode === "withdraw") {
360
+ if (block.type !== "needs_input" || block.author !== input.actor) throw new BlockRuleError("forbidden", "Only the question author can withdraw it.");
361
+ return {
362
+ outcome: "withdrawn",
363
+ outcomeReason: null
364
+ };
365
+ }
366
+ if (input.mode === "done") {
367
+ if (block.type !== "code") throw new BlockRuleError("wrong_block_type", "Done applies to a code block.");
368
+ return {
369
+ outcome: "done",
370
+ outcomeReason: input.ref ?? null
371
+ };
372
+ }
373
+ return {
374
+ outcome: "reason",
375
+ outcomeReason: input.reason
376
+ };
377
+ }
378
+ function editComment(revision, ackedRevision) {
379
+ return {
380
+ revision: revision + 1,
381
+ clarification: ackedRevision !== null
382
+ };
383
+ }
384
+ function acknowledgeComment(revision, requested) {
385
+ if (revision !== requested) throw new BlockRuleError("stale_comment_revision", `Comment revision is ${String(revision)}; requested ${String(requested)}.`);
386
+ return requested;
387
+ }
388
+ //#endregion
282
389
  //#region ../core/src/app/authorize.ts
283
390
  function operator(actor, config) {
284
391
  if (actor === "operator") return true;
285
392
  const parsed = parseActorId(actor);
286
393
  return parsed?.actor === "agent" && config.projects.some((project) => project.spurProjects.some((spur) => spur.name === parsed.actorRef.project && spur.role === "operator"));
287
394
  }
395
+ /** The Spur project that curates one board project, or null when it has none. */
396
+ function curatorProject(config, projectId) {
397
+ return config.projects.find((project) => project.id === projectId)?.spurProjects.find((spur) => spur.role === "curator")?.name ?? null;
398
+ }
288
399
  function worker(actor, target) {
289
400
  const parsed = parseActorId(actor);
290
401
  return parsed?.actor === "agent" && target.task !== null && target.workers.some((link) => link.session_id === parsed.actorRef.session && link.role === "worker" && link.banned === 0);
@@ -304,10 +415,14 @@ function matches(rule, actor, target, config) {
304
415
  case "column-orchestrator": return target.task !== null && orchestrator$1(actor, target, config, target.task.column);
305
416
  case "block-addressee": {
306
417
  if (target.block === null) return false;
307
- const role = target.block.addressee_role;
308
- if (role === "operator") return operator(actor, config);
309
- if (role === "worker") return worker(actor, target);
310
- return orchestrator$1(actor, target, config, role.slice(13));
418
+ const addressee = parseAddressee(target.block.addressee_role);
419
+ switch (addressee.kind) {
420
+ case "operator": return operator(actor, config);
421
+ case "curator": return parsed?.actor === "agent" && parsed.actorRef.project === curatorProject(config, target.project);
422
+ case "worker": return worker(actor, target);
423
+ case "orchestrator": return orchestrator$1(actor, target, config, addressee.column);
424
+ default: return assertNever(addressee);
425
+ }
311
426
  }
312
427
  case "block-author": return target.block?.author === actor;
313
428
  }
@@ -7794,6 +7909,18 @@ function taskUrl(task, config) {
7794
7909
  if (project?.tracker.type === "jira") return `${project.tracker.baseUrl.replace(/\/$/, "")}/browse/${task.key}`;
7795
7910
  return `https://github.com/${task.key.replace("#", "/issues/")}`;
7796
7911
  }
7912
+ const commandKeys = new AsyncLocalStorage();
7913
+ /**
7914
+ * Runs fn in the scope of one command: every event `emit` writes inside it carries `key` in
7915
+ * `request_id`. The innermost scope wins. Run only `trx` work inside it. Never trigger a job or
7916
+ * start detached work (timers, unawaited promises) in the scope: async context propagates into
7917
+ * it, and a scheduler job chains its next runs from that context, so a leaked `trigger()` would
7918
+ * stamp this key on every later scheduled run, not just one.
7919
+ */
7920
+ function withCommandKey(key, fn) {
7921
+ return commandKeys.run(key, fn);
7922
+ }
7923
+ /** The only writer of the journal; `request_id` is the key of the enclosing command, or null. */
7797
7924
  async function emit(trx, kind, project, taskId, at, payload, actor = "system") {
7798
7925
  const parsed = parseActorId(actor);
7799
7926
  if (parsed === null) throw new Error("Invalid journal actor");
@@ -7806,7 +7933,7 @@ async function emit(trx, kind, project, taskId, at, payload, actor = "system") {
7806
7933
  actor_ref: parsed.actor === "agent" ? JSON.stringify(parsed.actorRef) : null,
7807
7934
  payload: toJson(eventPayloadSchemas[kind], payload),
7808
7935
  v: 1,
7809
- request_id: null
7936
+ request_id: commandKeys.getStore() ?? null
7810
7937
  }).execute();
7811
7938
  }
7812
7939
  function taskView(task) {
@@ -7826,10 +7953,6 @@ function linkView(link) {
7826
7953
  }
7827
7954
  //#endregion
7828
7955
  //#region ../core/src/app/denied-event.ts
7829
- const actorRefSchema$2 = z.strictObject({
7830
- project: z.string().min(1),
7831
- session: z.string().min(1)
7832
- });
7833
7956
  /**
7834
7957
  * The journal project of a denial with no resolved target, in order: the configured project
7835
7958
  * the input's `task` key or `project` names; else the only configured project listing the agent
@@ -7857,22 +7980,10 @@ function deniedProject(config, actor, input) {
7857
7980
  /** Persist an authorization refusal through the caller's transaction. */
7858
7981
  async function writeDeniedEvent(trx, denial) {
7859
7982
  const { config, actor, operation, input, target, at } = denial;
7860
- const parsed = parseActorId(actor);
7861
- if (parsed === null) throw new Error("Invalid actor");
7862
- await trx.insertInto("event").values({
7863
- at,
7864
- project: target.kind === "found" ? target.value.project : deniedProject(config, actor, input),
7865
- task_id: target.kind === "found" ? target.value.task?.id ?? null : null,
7866
- kind: "operation_denied",
7867
- actor: parsed.actor,
7868
- actor_ref: parsed.actor === "agent" ? toJson(actorRefSchema$2, parsed.actorRef) : null,
7869
- payload: toJson(eventPayloadSchemas.operation_denied, {
7870
- operation,
7871
- reason: "Caller does not match the operation grants."
7872
- }),
7873
- v: 1,
7874
- request_id: null
7875
- }).execute();
7983
+ await emit(trx, "operation_denied", target.kind === "found" ? target.value.project : deniedProject(config, actor, input), target.kind === "found" ? target.value.task?.id ?? null : null, at, {
7984
+ operation,
7985
+ reason: "Caller does not match the operation grants."
7986
+ }, actor);
7876
7987
  }
7877
7988
  //#endregion
7878
7989
  //#region ../core/src/app/commands.ts
@@ -7920,7 +8031,7 @@ async function replayOperation(trx, input) {
7920
8031
  if (row.operation !== input.operation || row.fingerprint !== hash) throw new CommandError("idempotency_key_mismatch", "Use the original input or a new key.");
7921
8032
  return parseJson(input.output, row.result);
7922
8033
  }
7923
- const value = await input.run();
8034
+ const value = await withCommandKey(input.key, input.run);
7924
8035
  if (value === void 0) return void 0;
7925
8036
  const resultText = toJson(input.output, value);
7926
8037
  await trx.insertInto("command").values({
@@ -8068,23 +8179,10 @@ const NO_FEED = /* @__PURE__ */ new Set([
8068
8179
  "transport_health"
8069
8180
  ]);
8070
8181
  async function journal$3(trx, item, kind, at, rule, actor = "system") {
8071
- const parsed = parseActorId(actor);
8072
- if (parsed === null) throw new Error("Invalid journal actor");
8073
- const task = item.task_id === null ? void 0 : await trx.selectFrom("task").select(["project"]).where("id", "=", item.task_id).executeTakeFirstOrThrow();
8074
- await trx.insertInto("event").values({
8075
- at: at.toISOString(),
8076
- project: task?.project ?? "_board",
8077
- task_id: item.task_id,
8078
- kind,
8079
- actor: parsed.actor,
8080
- actor_ref: parsed.actor === "agent" ? JSON.stringify(parsed.actorRef) : null,
8081
- payload: toJson(eventPayloadSchemas[kind], {
8082
- item: `I${String(item.id)}`,
8083
- ...kind === "from_you_raised" && rule !== void 0 ? { rule } : {}
8084
- }),
8085
- v: 1,
8086
- request_id: null
8087
- }).execute();
8182
+ 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(), {
8183
+ item: `I${String(item.id)}`,
8184
+ ...kind === "from_you_raised" && rule !== void 0 ? { rule } : {}
8185
+ }, actor);
8088
8186
  }
8089
8187
  /** Kinds whose item has a retry action besides `delivery:<id>` (see `items.ts`). */
8090
8188
  const RETRY_KINDS = /* @__PURE__ */ new Set([
@@ -8284,15 +8382,17 @@ function renderBody(key, text) {
8284
8382
  }
8285
8383
  /**
8286
8384
  * A distinct semantic ring. Transport retries reuse this row and its text. A restarted series
8287
- * (`series` > 0) and a ring after the task was archived (`archives` > 0) get their own keys, so a
8288
- * ring cancelled by an archive does not block its replacement; unsuffixed keys stay as before.
8385
+ * (`series` > 0), a ring after the task was archived (`archives` > 0) and a ring after a move
8386
+ * killed an earlier one (`moves` > 0) get their own keys, so a cancelled ring does not block its
8387
+ * replacement; unsuffixed keys stay as before.
8289
8388
  */
8290
8389
  async function enqueueDoorbell(trx, input) {
8291
8390
  const series = input.series ?? 0;
8292
8391
  const archives = input.archives ?? 0;
8392
+ const moves = input.moves ?? 0;
8293
8393
  const row = await insertOutbox(trx, {
8294
8394
  kind: "doorbell",
8295
- dedupeKey: `doorbell:${String(input.notificationId)}:${input.session}:${String(input.ring)}${series > 0 ? `:s${String(series)}` : ""}${archives > 0 ? `:a${String(archives)}` : ""}`,
8395
+ dedupeKey: `doorbell:${String(input.notificationId)}:${input.session}:${String(input.ring)}${series > 0 ? `:s${String(series)}` : ""}${archives > 0 ? `:a${String(archives)}` : ""}${moves > 0 ? `:m${String(moves)}` : ""}`,
8296
8396
  payload: {
8297
8397
  notificationId: input.notificationId,
8298
8398
  ring: input.ring,
@@ -8586,18 +8686,6 @@ async function enqueueConversationClose(trx, input) {
8586
8686
  closed_at: input.at.toISOString()
8587
8687
  }).where("block_id", "=", input.blockId).where("state", "=", "open").execute();
8588
8688
  }
8589
- async function enqueueInboundDoorbell(trx, input) {
8590
- await insertOutbox(trx, {
8591
- kind: "doorbell",
8592
- dedupeKey: input.key,
8593
- payload: {
8594
- session: input.session,
8595
- text: input.text
8596
- },
8597
- parent: null,
8598
- at: input.at
8599
- });
8600
- }
8601
8689
  //#endregion
8602
8690
  //#region ../core/src/app/feed.ts
8603
8691
  /** The struck summary is capped so the edit stays one message part. */
@@ -8699,17 +8787,7 @@ function effectiveStatus(row, at) {
8699
8787
  return row.status === "pending" && row.expires_at <= at.toISOString() ? "expired" : row.status;
8700
8788
  }
8701
8789
  async function journalToken(trx, kind, name, at) {
8702
- await trx.insertInto("event").values({
8703
- at: at.toISOString(),
8704
- project: RESERVED_PROJECT,
8705
- task_id: null,
8706
- kind,
8707
- actor: kind === "token_approved" || kind === "token_denied" || kind === "token_revoked" ? "operator" : "system",
8708
- actor_ref: null,
8709
- payload: toJson(eventPayloadSchemas[kind], { name }),
8710
- v: 1,
8711
- request_id: null
8712
- }).execute();
8790
+ await emit(trx, kind, RESERVED_PROJECT, null, at.toISOString(), { name }, kind === "token_approved" || kind === "token_denied" || kind === "token_revoked" ? "operator" : "system");
8713
8791
  }
8714
8792
  /** Lapse one pending request: journal it once and clear its approval item. */
8715
8793
  async function expireToken(trx, row, at) {
@@ -9062,99 +9140,121 @@ function listenApiServer(app, port) {
9062
9140
  });
9063
9141
  }
9064
9142
  //#endregion
9065
- //#region ../core/src/domain/blocks/blocks.ts
9066
- var BlockRuleError = class extends Error {
9067
- code;
9068
- constructor(code, message) {
9069
- super(message);
9070
- this.code = code;
9071
- }
9072
- };
9073
- /** Roles survive a change in the session currently filling them. */
9074
- function blockAddressee(input) {
9075
- const { type, author, authorRole, column, orchestrator, hasWorker } = input;
9076
- if (author === "system") return orchestrator !== null ? `orchestrator:${column}` : hasWorker ? "worker" : "operator";
9077
- if (type === "code") return "worker";
9078
- if (type === "dependency" || type === "external") return authorRole;
9079
- if (orchestrator === null) return "operator";
9080
- if (orchestrator === "operator") return "operator";
9081
- const parsed = parseActorId(author);
9082
- if (parsed?.actor === "agent" && parsed.actorRef.project === orchestrator) return "operator";
9083
- return `orchestrator:${column}`;
9084
- }
9085
- function requireOpen(block) {
9086
- if (block.state === "open") return;
9087
- throw new BlockRuleError("block_not_open", `Block was ${block.outcome ?? "unblocked"} by ${block.unblockedBy ?? "unknown"}.`);
9088
- }
9089
- function escalateBlock(block) {
9090
- requireOpen(block);
9091
- return {
9092
- addressee: "operator",
9093
- changed: block.addressee !== "operator"
9094
- };
9143
+ //#region ../core/src/app/block-thread.ts
9144
+ function orchestrator(config, task) {
9145
+ const name = config.projects.find((project) => project.id === task.project)?.columns.find((column) => column.id === task.column)?.orchestrator;
9146
+ return name === void 0 || name === "none" ? null : name;
9095
9147
  }
9096
- function answerBlock(block) {
9097
- requireOpen(block);
9098
- if (block.type !== "needs_input") throw new BlockRuleError("wrong_block_type", "Only a question block can be answered.");
9148
+ function authorRole(config, task, actor) {
9149
+ if (actor === "operator") return "operator";
9150
+ const parsed = parseActorId(actor);
9151
+ if (parsed?.actor === "agent" && config.projects.some((project) => project.spurProjects.some((spur) => spur.name === parsed.actorRef.project && spur.role === "operator"))) return "operator";
9152
+ if (parsed?.actor !== "agent") return "worker";
9153
+ if (parsed.actorRef.project === orchestrator(config, task)) return `orchestrator:${task.column}`;
9154
+ return parsed.actorRef.project === curatorProject(config, task.project) ? "curator" : "worker";
9099
9155
  }
9100
- function closeBlock(block, input) {
9101
- requireOpen(block);
9102
- if (input.mode === "withdraw") {
9103
- if (block.type !== "needs_input" || block.author !== input.actor) throw new BlockRuleError("forbidden", "Only the question author can withdraw it.");
9104
- return {
9105
- outcome: "withdrawn",
9106
- outcomeReason: null
9107
- };
9156
+ function personaRole(role) {
9157
+ const addressee = parseAddressee(role);
9158
+ switch (addressee.kind) {
9159
+ case "operator": return "board";
9160
+ case "worker": return "worker";
9161
+ case "curator":
9162
+ case "orchestrator": return "orchestrator";
9163
+ default: return assertNever(addressee);
9108
9164
  }
9109
- if (input.mode === "done") {
9110
- if (block.type !== "code") throw new BlockRuleError("wrong_block_type", "Done applies to a code block.");
9111
- return {
9112
- outcome: "done",
9113
- outcomeReason: input.ref ?? null
9114
- };
9115
- }
9116
- return {
9117
- outcome: "reason",
9118
- outcomeReason: input.reason
9119
- };
9120
9165
  }
9121
- function editComment(revision, ackedRevision) {
9166
+ function personaFor(config, task, actor) {
9167
+ if (actor === "system") return {
9168
+ name: "board",
9169
+ role: "board"
9170
+ };
9171
+ if (actor === "operator") return {
9172
+ name: "operator",
9173
+ role: "board"
9174
+ };
9175
+ const parsed = parseActorId(actor);
9176
+ if (parsed?.actor !== "agent") throw new Error("Invalid actor");
9122
9177
  return {
9123
- revision: revision + 1,
9124
- clarification: ackedRevision !== null
9178
+ name: parsed.actorRef.project,
9179
+ role: personaRole(authorRole(config, task, actor))
9125
9180
  };
9126
9181
  }
9127
- function acknowledgeComment(revision, requested) {
9128
- if (revision !== requested) throw new BlockRuleError("stale_comment_revision", `Comment revision is ${String(revision)}; requested ${String(requested)}.`);
9129
- return requested;
9182
+ async function queueBlockOpen(trx, task, block, ctx, config) {
9183
+ if (authorRole(config, task, block.author) === "operator") return;
9184
+ const comments = await trx.selectFrom("comment").select(["id", "author"]).where("block_id", "=", block.id).orderBy("id").execute();
9185
+ if (await enqueueConversationOpen(trx, {
9186
+ blockId: block.id,
9187
+ commentId: comments[0]?.id ?? null,
9188
+ persona: personaFor(config, task, comments[0]?.author ?? block.author),
9189
+ at: new Date(ctx.at)
9190
+ }) === null) return;
9191
+ for (const comment of comments.slice(1)) await enqueueConversationReply(trx, {
9192
+ commentId: comment.id,
9193
+ persona: personaFor(config, task, comment.author),
9194
+ at: new Date(ctx.at)
9195
+ });
9130
9196
  }
9131
9197
  //#endregion
9132
9198
  //#region ../core/src/app/doorbells.ts
9199
+ const UNANSWERED = "unanswered";
9133
9200
  async function journal$2(trx, notification, kind, payload, at) {
9134
- const task = await trx.selectFrom("task").select("project").where("id", "=", notification.task_id).executeTakeFirstOrThrow();
9135
- await trx.insertInto("event").values({
9136
- at: at.toISOString(),
9137
- project: task.project,
9138
- task_id: notification.task_id,
9139
- kind,
9140
- actor: "system",
9141
- actor_ref: null,
9142
- payload: toJson(eventPayloadSchemas[kind], payload),
9143
- v: 1,
9144
- request_id: null
9145
- }).execute();
9201
+ await emit(trx, kind, (await trx.selectFrom("task").select("project").where("id", "=", notification.task_id).executeTakeFirstOrThrow()).project, notification.task_id, at.toISOString(), payload);
9202
+ }
9203
+ /**
9204
+ * The one rule for who a board event rings. A doorbell means someone is waiting for your action,
9205
+ * so a party that caused the event, or that the Slack thread already reaches, gets no row.
9206
+ */
9207
+ async function applyDoorbellPolicy(trx, event, at) {
9208
+ switch (event.kind) {
9209
+ case "block_opened":
9210
+ if (!(parseActorId(event.block.author)?.actor === "agent" && event.block.addressee_role === event.authorRole)) await registerBlockNotification(trx, event.block, at);
9211
+ return;
9212
+ case "block_escalated":
9213
+ await closeBlockNotification(trx, event.block.id, at);
9214
+ await registerBlockNotification(trx, event.block, at);
9215
+ return;
9216
+ case "answer":
9217
+ await registerAnswerNotification(trx, event, at);
9218
+ return;
9219
+ case "block_removed":
9220
+ await registerRemovedNotification(trx, event.block, at);
9221
+ return;
9222
+ case "block_closed_by_addressee":
9223
+ case "task_comment": return;
9224
+ default: assertNever(event);
9225
+ }
9146
9226
  }
9147
- /** Register a worker-addressed block without manufacturing a comment. */
9227
+ /** Register a block for its agent addressee; the Slack thread carries an operator's. */
9148
9228
  async function registerBlockNotification(trx, block, at) {
9149
- if (block.addressee_role !== "worker") return;
9229
+ if (block.addressee_role === "operator") return;
9150
9230
  await trx.insertInto("notification").values({
9151
- source_key: `block:${String(block.id)}:worker`,
9231
+ source_key: `block:${String(block.id)}:${block.addressee_role}`,
9152
9232
  kind: "block",
9153
9233
  task_id: block.task_id,
9154
9234
  block_id: block.id,
9155
9235
  comment_id: null,
9156
9236
  revision: null,
9157
- role: "worker",
9237
+ role: block.addressee_role,
9238
+ author_session: null,
9239
+ recipient_session: null,
9240
+ next_at: at.toISOString(),
9241
+ last_outbox_id: null,
9242
+ acked_at: null,
9243
+ exhausted_at: null,
9244
+ created_at: at.toISOString()
9245
+ }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
9246
+ }
9247
+ /** Register a one-ring notice that a block its addressee held was closed by someone else. */
9248
+ async function registerRemovedNotification(trx, block, at) {
9249
+ if (block.addressee_role === "operator") return;
9250
+ await trx.insertInto("notification").values({
9251
+ source_key: `removed:${String(block.id)}`,
9252
+ kind: "removed",
9253
+ task_id: block.task_id,
9254
+ block_id: block.id,
9255
+ comment_id: null,
9256
+ revision: null,
9257
+ role: block.addressee_role,
9158
9258
  author_session: null,
9159
9259
  recipient_session: null,
9160
9260
  next_at: at.toISOString(),
@@ -9164,11 +9264,12 @@ async function registerBlockNotification(trx, block, at) {
9164
9264
  created_at: at.toISOString()
9165
9265
  }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
9166
9266
  }
9167
- /** Register an answer or clarification for the original author and its task role. */
9168
- async function registerAnswerNotification(trx, input) {
9169
- if (input.authorRole !== "worker") return;
9267
+ /** Register an answer or clarification for the question's author, unless the author wrote it. */
9268
+ async function registerAnswerNotification(trx, input, at) {
9170
9269
  const parsed = parseActorId(input.block.author);
9171
- if (parsed?.actor !== "agent") return;
9270
+ if (parsed?.actor !== "agent" || input.actor === input.block.author) return;
9271
+ const actor = parseActorId(input.actor);
9272
+ if (resolvedByProject(input.authorRole) && actor?.actor === "agent" && actor.actorRef.project === parsed.actorRef.project) return;
9172
9273
  await trx.insertInto("notification").values({
9173
9274
  source_key: `comment:${String(input.commentId)}:${String(input.revision)}`,
9174
9275
  kind: "answer",
@@ -9176,33 +9277,110 @@ async function registerAnswerNotification(trx, input) {
9176
9277
  block_id: input.block.id,
9177
9278
  comment_id: input.commentId,
9178
9279
  revision: input.revision,
9179
- role: "worker",
9280
+ role: input.authorRole,
9180
9281
  author_session: parsed.actorRef.session,
9181
9282
  recipient_session: null,
9182
- next_at: input.at.toISOString(),
9283
+ next_at: at.toISOString(),
9183
9284
  last_outbox_id: null,
9184
9285
  acked_at: null,
9185
9286
  exhausted_at: null,
9186
- created_at: input.at.toISOString()
9287
+ created_at: at.toISOString()
9187
9288
  }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
9188
9289
  }
9290
+ /**
9291
+ * Moves a block to a new addressee, for `block.escalate` and for a ring series that ended: the
9292
+ * journal row, the old notification's end, the new one and the Slack thread, in the caller's
9293
+ * transaction.
9294
+ */
9295
+ async function moveBlockToAddressee(trx, input) {
9296
+ const { task, block, to, reason, ctx, config } = input;
9297
+ const updated = await trx.updateTable("block").set({ addressee_role: to }).where("id", "=", block.id).returningAll().executeTakeFirstOrThrow();
9298
+ await emit(trx, "block_escalated", task.project, task.id, ctx.at, {
9299
+ block: `B${String(block.id)}`,
9300
+ from: block.addressee_role,
9301
+ to,
9302
+ ...reason === void 0 ? {} : { reason }
9303
+ }, ctx.actor);
9304
+ await applyDoorbellPolicy(trx, {
9305
+ kind: "block_escalated",
9306
+ block: updated
9307
+ }, new Date(ctx.at));
9308
+ await queueBlockOpen(trx, task, updated, ctx, config);
9309
+ return updated;
9310
+ }
9311
+ async function sessionById(trx, id) {
9312
+ return trx.selectFrom("session_snapshot").selectAll().where("id", "=", id).executeTakeFirst();
9313
+ }
9189
9314
  async function liveSession(trx, id) {
9190
- const row = await trx.selectFrom("session_snapshot").selectAll().where("id", "=", id).executeTakeFirst();
9315
+ const row = await sessionById(trx, id);
9191
9316
  return row?.ended_at === null && row.state !== "killed" && row.state !== "stopped" ? row : void 0;
9192
9317
  }
9193
- /** Select the current live recipient for a semantic notification. */
9194
- async function selectNotificationRecipient(trx, n) {
9195
- if (n.author_session !== null) {
9196
- const author = await liveSession(trx, n.author_session);
9197
- if (author !== void 0) return author;
9198
- }
9199
- const links = await trx.selectFrom("link").select("session_id").where("task_id", "=", n.task_id).where("entity", "=", "session").where("role", "=", n.role === "worker" ? "worker" : "orchestrator").where("banned", "=", 0).orderBy("created_at", "desc").execute();
9318
+ /** Spur lifecycle states of a session that can no longer read a ring. */
9319
+ const FINISHED_STATES = [
9320
+ "killed",
9321
+ "stopped",
9322
+ "errored",
9323
+ "completed"
9324
+ ];
9325
+ /** Stricter than `liveSession`: a role resolved by Spur project must also be in Spur's list. */
9326
+ function liveInProject(session) {
9327
+ return session.ended_at === null && session.absent_since === null && !FINISHED_STATES.includes(session.state);
9328
+ }
9329
+ /** Roles whose recipient is any session of a configured Spur project, not one linked session. */
9330
+ function resolvedByProject(role) {
9331
+ const { kind } = parseAddressee(role);
9332
+ return kind === "curator" || kind === "orchestrator";
9333
+ }
9334
+ /** Orders later times first and missing times last. */
9335
+ function laterFirst(left, right) {
9336
+ if (left === right) return 0;
9337
+ if (left === null) return 1;
9338
+ if (right === null) return -1;
9339
+ return right - left;
9340
+ }
9341
+ /** The newest live session of a Spur project, then the most recently active, then by id. */
9342
+ async function bestProjectSession(trx, project) {
9343
+ if (project === null) return void 0;
9344
+ const rows = await trx.selectFrom("session_snapshot").selectAll().select(sql`json_extract(detail, '$.lastActivityAt')`.as("last_activity")).where("spur_project", "=", project).where("ended_at", "is", null).where("absent_since", "is", null).where("state", "not in", FINISHED_STATES).execute();
9345
+ const activity = (value) => value === null ? null : Date.parse(value);
9346
+ return rows.sort((left, right) => laterFirst(Date.parse(left.first_seen), Date.parse(right.first_seen)) || laterFirst(activity(left.last_activity), activity(right.last_activity)) || (left.id < right.id ? -1 : 1))[0];
9347
+ }
9348
+ /** The newest live session linked to a task in a role. */
9349
+ async function linkedSession(trx, taskId, role) {
9350
+ 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();
9200
9351
  for (const link of links) {
9201
9352
  if (link.session_id === null) continue;
9202
9353
  const session = await liveSession(trx, link.session_id);
9203
9354
  if (session !== void 0) return session;
9204
9355
  }
9205
9356
  }
9357
+ async function taskProject(trx, taskId) {
9358
+ return (await trx.selectFrom("task").select("project").where("id", "=", taskId).executeTakeFirstOrThrow()).project;
9359
+ }
9360
+ /** The Spur project orchestrating a column; null when no agent project does. */
9361
+ function columnOrchestratorProject(config, projectId, column) {
9362
+ const name = config.projects.find((project) => project.id === projectId)?.columns.find((entry) => entry.id === column)?.orchestrator;
9363
+ return name === void 0 || name === "none" || name === "operator" ? null : name;
9364
+ }
9365
+ /** Select the current live recipient for a semantic notification. */
9366
+ async function selectNotificationRecipient(trx, n, config) {
9367
+ const addressee = parseAddressee(n.role);
9368
+ switch (addressee.kind) {
9369
+ case "curator": return bestProjectSession(trx, curatorProject(config, await taskProject(trx, n.task_id)));
9370
+ case "orchestrator": {
9371
+ const author = n.author_session === null ? void 0 : await sessionById(trx, n.author_session);
9372
+ if (author !== void 0 && liveInProject(author)) return author;
9373
+ return await linkedSession(trx, n.task_id, "orchestrator") ?? bestProjectSession(trx, columnOrchestratorProject(config, await taskProject(trx, n.task_id), addressee.column));
9374
+ }
9375
+ case "worker":
9376
+ case "operator": {
9377
+ const author = n.author_session === null ? void 0 : await liveSession(trx, n.author_session);
9378
+ if (author !== void 0 || addressee.kind === "operator") return author;
9379
+ return linkedSession(trx, n.task_id, "worker");
9380
+ }
9381
+ default: return assertNever(addressee);
9382
+ }
9383
+ }
9206
9384
  /** The operator item kind raised when a notification's rings are exhausted. */
9207
9385
  function exhaustedItemKind(n) {
9208
9386
  return n.kind === "answer" ? "answer_undelivered" : "worker_not_reading";
@@ -9223,11 +9401,49 @@ async function restartNotification(trx, sourceKey, at) {
9223
9401
  }).where("source_key", "=", sourceKey).where("acked_at", "is", null).where("exhausted_at", "is not", null).returning("id").executeTakeFirst() === void 0) throw new CommandError("retry_not_applicable", "The doorbell was read or is still ringing; close the item instead.");
9224
9402
  }
9225
9403
  /**
9226
- * Ends a ring Spur will not take (a permanent rejection, or no answer for the retry window): its
9227
- * notification stops ringing, the operator gets an item and `doorbell_undelivered` is journalled.
9228
- * The operator's Retry on the item restarts the series (`restartNotification`). A ring that is no
9229
- * longer its notification's last row (the recipient changed while it was in flight) ends alone. An
9230
- * inbound author ring has no notification: it ends like an author found unavailable at enqueue.
9404
+ * Ends a notification's ring series. A curator block moves to the operator; a removal or a ring
9405
+ * with no session to name ends alone; anything else raises the operator item, whose Retry restarts
9406
+ * the series (`restartNotification`). Every end journals `doorbell_undelivered`.
9407
+ */
9408
+ async function endNotification(trx, n, task, end) {
9409
+ const { session, reason, at, config } = end;
9410
+ await trx.updateTable("notification").set({ exhausted_at: at.toISOString() }).where("id", "=", n.id).execute();
9411
+ const addressee = parseAddressee(n.role);
9412
+ if (n.kind === "block" && addressee.kind === "curator") await moveBlockToAddressee(trx, {
9413
+ task,
9414
+ block: await trx.selectFrom("block").selectAll().where("id", "=", n.block_id).executeTakeFirstOrThrow(),
9415
+ to: "operator",
9416
+ reason,
9417
+ ctx: {
9418
+ actor: "system",
9419
+ at: at.toISOString()
9420
+ },
9421
+ config
9422
+ });
9423
+ else if (n.kind !== "removed" && session !== null) {
9424
+ const blockRef = `block B${String(n.block_id)} on ${task.key}`;
9425
+ const answer = `Answer to ${blockRef} was not`;
9426
+ const holder = `${addressee.kind} ${session}`;
9427
+ await raiseItem(trx, {
9428
+ itemKey: exhaustedItemKey(n),
9429
+ kind: exhaustedItemKind(n),
9430
+ 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}`,
9431
+ url: taskUrl(task, config),
9432
+ taskId: task.id,
9433
+ blockId: n.block_id,
9434
+ at
9435
+ });
9436
+ }
9437
+ await journal$2(trx, n, "doorbell_undelivered", {
9438
+ doorbell: `N${String(n.id)}`,
9439
+ reason
9440
+ }, at);
9441
+ }
9442
+ /**
9443
+ * Ends a ring Spur will not take (a permanent rejection, or no answer for the retry window). A
9444
+ * ring that is no longer its notification's last row (the recipient changed while it was in
9445
+ * flight) ends alone. An inbound author ring has no notification: it ends like an author found
9446
+ * unavailable at enqueue.
9231
9447
  */
9232
9448
  async function ringUndelivered(trx, input) {
9233
9449
  const { at, reason } = input;
@@ -9251,21 +9467,24 @@ async function ringUndelivered(trx, input) {
9251
9467
  }
9252
9468
  const n = await trx.selectFrom("notification").selectAll().where("id", "=", input.notificationId).executeTakeFirst();
9253
9469
  if (n === void 0 || n.acked_at !== null || n.exhausted_at !== null || n.last_outbox_id !== input.outboxId) return;
9254
- const task = await trx.selectFrom("task").selectAll().where("id", "=", n.task_id).executeTakeFirstOrThrow();
9255
- await trx.updateTable("notification").set({ exhausted_at: at.toISOString() }).where("id", "=", n.id).execute();
9256
- await raiseItem(trx, {
9257
- itemKey: exhaustedItemKey(n),
9258
- kind: exhaustedItemKind(n),
9259
- text: n.kind === "answer" ? `Answer to block B${String(n.block_id)} on ${task.key} was not delivered: ${reason}` : `worker ${input.session} did not get block B${String(n.block_id)} on ${task.key}: ${reason}`,
9260
- url: taskUrl(task, input.config),
9261
- taskId: task.id,
9262
- blockId: n.block_id,
9263
- at
9470
+ await endNotification(trx, n, await trx.selectFrom("task").selectAll().where("id", "=", n.task_id).executeTakeFirstOrThrow(), {
9471
+ session: input.session,
9472
+ reason,
9473
+ at,
9474
+ config: input.config
9264
9475
  });
9265
- await journal$2(trx, n, "doorbell_undelivered", {
9266
- doorbell: `N${String(n.id)}`,
9267
- reason
9268
- }, at);
9476
+ }
9477
+ /** Why a notification with no recipient ends now, or null when it stays due for a next session. */
9478
+ function noRecipientEnd(n) {
9479
+ if (n.kind === "removed" || n.kind === "answer" && n.role === "operator") return "no live addressee";
9480
+ return n.kind === "block" && n.role === "curator" ? "no live curator session" : null;
9481
+ }
9482
+ /** A ring never carries comment or reason text: only where to look. */
9483
+ async function ringText(trx, n, task, ring) {
9484
+ const suffix = `(N${String(n.id)}-${String(ring)})`;
9485
+ if (n.kind !== "removed") return `${task.key} block B${String(n.block_id)}: check board inbox ${suffix}`;
9486
+ const block = await trx.selectFrom("block").select("unblocked_by").where("id", "=", n.block_id).executeTakeFirstOrThrow();
9487
+ return `${task.key} block B${String(n.block_id)} was removed by ${block.unblocked_by ?? "system"}; see board task ${task.key} ${suffix}`;
9269
9488
  }
9270
9489
  /** Notifications reconcile looks at: unacked, not exhausted, due, on a task not archived. */
9271
9490
  function dueNotifications(db, at) {
@@ -9283,11 +9502,19 @@ async function reconcileDueDoorbells(store, config, at) {
9283
9502
  async function reconcileDoorbells(trx, at, config) {
9284
9503
  const due = await dueNotifications(trx, at).selectAll("notification").orderBy("notification.id").execute();
9285
9504
  for (const n of due) {
9286
- const session = await selectNotificationRecipient(trx, n);
9505
+ const session = await selectNotificationRecipient(trx, n, config);
9506
+ const keepsRings = resolvedByProject(n.role);
9287
9507
  if (session === void 0) {
9288
- if (n.recipient_session !== null) await trx.updateTable("notification").set({
9508
+ const reason = noRecipientEnd(n);
9509
+ if (reason !== null) await endNotification(trx, n, await trx.selectFrom("task").selectAll().where("id", "=", n.task_id).executeTakeFirstOrThrow(), {
9510
+ session: null,
9511
+ reason,
9512
+ at,
9513
+ config
9514
+ });
9515
+ else if (n.recipient_session !== null) await trx.updateTable("notification").set({
9289
9516
  recipient_session: null,
9290
- rings: 0,
9517
+ rings: keepsRings ? n.rings : 0,
9291
9518
  last_outbox_id: null
9292
9519
  }).where("id", "=", n.id).execute();
9293
9520
  continue;
@@ -9300,11 +9527,11 @@ async function reconcileDoorbells(trx, at, config) {
9300
9527
  state: "dead",
9301
9528
  last_error: "recipient changed"
9302
9529
  }).where("id", "=", lastOutbox).where("state", "=", "pending").execute();
9303
- rings = 0;
9530
+ if (!keepsRings) rings = 0;
9304
9531
  lastOutbox = null;
9305
9532
  await trx.updateTable("notification").set({
9306
9533
  recipient_session: session.id,
9307
- rings: 0,
9534
+ rings,
9308
9535
  last_outbox_id: null
9309
9536
  }).where("id", "=", n.id).execute();
9310
9537
  }
@@ -9313,28 +9540,20 @@ async function reconcileDoorbells(trx, at, config) {
9313
9540
  if (row?.state === "pending" || row?.state === "in_flight") continue;
9314
9541
  }
9315
9542
  const task = await trx.selectFrom("task").selectAll().where("id", "=", n.task_id).executeTakeFirstOrThrow();
9316
- const itemKey = exhaustedItemKey(n);
9317
9543
  if (rings >= 3) {
9318
- await raiseItem(trx, {
9319
- itemKey,
9320
- kind: exhaustedItemKind(n),
9321
- text: n.kind === "answer" ? `Answer to block B${String(n.block_id)} on ${task.key} was not read` : `worker ${session.id} is not reading block B${String(n.block_id)} on ${task.key}`,
9322
- url: taskUrl(task, config),
9323
- taskId: task.id,
9324
- blockId: n.block_id,
9325
- at
9544
+ await endNotification(trx, n, task, {
9545
+ session: session.id,
9546
+ reason: UNANSWERED,
9547
+ at,
9548
+ config
9326
9549
  });
9327
- await trx.updateTable("notification").set({ exhausted_at: at.toISOString() }).where("id", "=", n.id).execute();
9328
- await journal$2(trx, n, "doorbell_undelivered", {
9329
- doorbell: `N${String(n.id)}`,
9330
- reason: "unanswered"
9331
- }, at);
9332
9550
  continue;
9333
9551
  }
9334
- const raised = await trx.selectFrom("operator_item").select((eb) => eb.fn.max("raise_no").as("series")).where("item_key", "=", itemKey).executeTakeFirst();
9552
+ const raised = await trx.selectFrom("operator_item").select((eb) => eb.fn.max("raise_no").as("series")).where("item_key", "=", exhaustedItemKey(n)).executeTakeFirst();
9335
9553
  const archived = await trx.selectFrom("event").select((eb) => eb.fn.countAll().as("count")).where("task_id", "=", n.task_id).where("kind", "=", "task_archived").executeTakeFirst();
9554
+ const killed = keepsRings ? await trx.selectFrom("outbox").select((eb) => eb.fn.countAll().as("count")).where("kind", "=", "doorbell").where("state", "=", "dead").where(sql`json_extract(payload, '$.notificationId')`, "=", n.id).executeTakeFirst() : void 0;
9336
9555
  const ring = rings + 1;
9337
- const text = `${task.key} block B${String(n.block_id)}: check board inbox (N${String(n.id)}-${String(ring)})`;
9556
+ const text = await ringText(trx, n, task, ring);
9338
9557
  const outboxId = await enqueueDoorbell(trx, {
9339
9558
  notificationId: n.id,
9340
9559
  ring,
@@ -9342,7 +9561,8 @@ async function reconcileDoorbells(trx, at, config) {
9342
9561
  text,
9343
9562
  at,
9344
9563
  series: raised?.series ?? 0,
9345
- archives: archived?.count ?? 0
9564
+ archives: archived?.count ?? 0,
9565
+ moves: killed?.count ?? 0
9346
9566
  });
9347
9567
  await trx.updateTable("notification").set({ last_outbox_id: outboxId }).where("id", "=", n.id).execute();
9348
9568
  }
@@ -9358,7 +9578,8 @@ async function recordRingDelivery(trx, notificationId, ring, session, at, config
9358
9578
  ];
9359
9579
  await trx.updateTable("notification").set({
9360
9580
  rings: ring,
9361
- next_at: new Date(at.getTime() + (pauses[ring - 1] ?? 0)).toISOString()
9581
+ next_at: new Date(at.getTime() + (pauses[ring - 1] ?? 0)).toISOString(),
9582
+ ...n.kind === "removed" ? { acked_at: at.toISOString() } : {}
9362
9583
  }).where("id", "=", notificationId).execute();
9363
9584
  await journal$2(trx, n, "doorbell_rung", {
9364
9585
  doorbell: `N${String(n.id)}`,
@@ -9367,10 +9588,10 @@ async function recordRingDelivery(trx, notificationId, ring, session, at, config
9367
9588
  }, at);
9368
9589
  }
9369
9590
  /** Confirm that a queued ring still belongs to a live, idle, unread recipient. */
9370
- async function ringStillCurrent(trx, notificationId, sessionId) {
9591
+ async function ringStillCurrent(trx, notificationId, sessionId, config) {
9371
9592
  const n = await trx.selectFrom("notification").selectAll().where("id", "=", notificationId).executeTakeFirst();
9372
9593
  if (n === void 0 || n.acked_at !== null || n.exhausted_at !== null || n.recipient_session !== sessionId) return "dead";
9373
- const session = await selectNotificationRecipient(trx, n);
9594
+ const session = await selectNotificationRecipient(trx, n, config);
9374
9595
  if (session?.id !== sessionId) return "dead";
9375
9596
  return session.state === "working" ? "defer" : "send";
9376
9597
  }
@@ -9394,7 +9615,7 @@ async function acknowledgeNotification(trx, input) {
9394
9615
  const notices = await query.orderBy("id", "desc").execute();
9395
9616
  const n = notices[0];
9396
9617
  if (n === void 0) return false;
9397
- if (!await notificationAddressedTo(trx, n, input.actor)) throw new CommandError("forbidden", "Only the addressed task role can acknowledge.");
9618
+ if (!await notificationAddressedTo(trx, n, input.actor, input.config)) throw new CommandError("forbidden", "Only the addressed task role can acknowledge.");
9398
9619
  for (const notice of notices) {
9399
9620
  await trx.updateTable("notification").set({ acked_at: input.at.toISOString() }).where("id", "=", notice.id).execute();
9400
9621
  await journal$2(trx, notice, "doorbell_read", { doorbell: `N${String(notice.id)}` }, input.at);
@@ -9403,13 +9624,30 @@ async function acknowledgeNotification(trx, input) {
9403
9624
  }
9404
9625
  return true;
9405
9626
  }
9406
- /** Use the same current recipient rule when listing and acknowledging an inbox notice. */
9407
- async function notificationAddressedTo(trx, n, actor) {
9627
+ /** Decides who may list and acknowledge an inbox notice, by the role it is addressed to. */
9628
+ async function notificationAddressedTo(trx, n, actor, config) {
9408
9629
  const parsed = parseActorId(actor);
9409
9630
  if (parsed?.actor !== "agent") return false;
9410
- const linked = await trx.selectFrom("link").select("id").where("task_id", "=", n.task_id).where("entity", "=", "session").where("role", "=", "worker").where("banned", "=", 0).where("session_id", "=", parsed.actorRef.session).executeTakeFirst();
9411
- const selectedIsLive = n.recipient_session !== null && await liveSession(trx, n.recipient_session) !== void 0;
9412
- return n.recipient_session === null ? parsed.actorRef.session === n.author_session || linked !== void 0 : selectedIsLive ? parsed.actorRef.session === n.recipient_session : (await selectNotificationRecipient(trx, n))?.id === parsed.actorRef.session;
9631
+ const { project, session } = parsed.actorRef;
9632
+ const addressee = parseAddressee(n.role);
9633
+ switch (addressee.kind) {
9634
+ case "curator": return project === curatorProject(config, await taskProject(trx, n.task_id));
9635
+ case "orchestrator": return project === columnOrchestratorProject(config, await taskProject(trx, n.task_id), addressee.column) || await hasLiveLink(trx, n.task_id, "orchestrator", session);
9636
+ case "operator": return session === n.author_session;
9637
+ case "worker": return workerNotificationAddressedTo(trx, n, session, config);
9638
+ default: return assertNever(addressee);
9639
+ }
9640
+ }
9641
+ async function sessionLink(trx, taskId, role, session) {
9642
+ return trx.selectFrom("link").select("id").where("task_id", "=", taskId).where("entity", "=", "session").where("role", "=", role).where("banned", "=", 0).where("session_id", "=", session).executeTakeFirst();
9643
+ }
9644
+ async function hasLiveLink(trx, taskId, role, session) {
9645
+ return await sessionLink(trx, taskId, role, session) !== void 0 && await liveSession(trx, session) !== void 0;
9646
+ }
9647
+ /** The selected worker while it lives; before the first ring, the author or a linked worker. */
9648
+ async function workerNotificationAddressedTo(trx, n, session, config) {
9649
+ if (n.recipient_session === null) return session === n.author_session || await sessionLink(trx, n.task_id, "worker", session) !== void 0;
9650
+ return await liveSession(trx, n.recipient_session) !== void 0 ? session === n.recipient_session : (await selectNotificationRecipient(trx, n, config))?.id === session;
9413
9651
  }
9414
9652
  async function closeBlockNotification(trx, blockId, at) {
9415
9653
  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();
@@ -9420,10 +9658,6 @@ async function closeBlockNotification(trx, blockId, at) {
9420
9658
  }
9421
9659
  //#endregion
9422
9660
  //#region ../core/src/app/blocks.ts
9423
- const actorRefSchema$1 = z.strictObject({
9424
- project: z.string().min(1),
9425
- session: z.string().min(1)
9426
- });
9427
9661
  const idNumber = (id) => Number(id.slice(1));
9428
9662
  const blockId$1 = (id) => `B${String(id)}`;
9429
9663
  const commentId = (id) => `C${String(id)}`;
@@ -9532,65 +9766,28 @@ function commentView(comment, task) {
9532
9766
  };
9533
9767
  }
9534
9768
  async function journal$1(trx, task, ctx, kind, payload) {
9535
- const actor = parseActorId(ctx.actor);
9536
- if (actor === null) throw new Error("Invalid actor");
9537
- await trx.insertInto("event").values({
9538
- at: ctx.at,
9539
- project: task.project,
9540
- task_id: task.id,
9541
- kind,
9542
- actor: actor.actor,
9543
- actor_ref: actor.actor === "agent" ? toJson(actorRefSchema$1, actor.actorRef) : null,
9544
- payload: toJson(eventPayloadSchemas[kind], payload),
9545
- v: 1,
9546
- request_id: null
9547
- }).execute();
9548
- }
9549
- function orchestrator(config, task) {
9550
- const name = config.projects.find((project) => project.id === task.project)?.columns.find((column) => column.id === task.column)?.orchestrator;
9551
- return name === void 0 || name === "none" ? null : name;
9552
- }
9553
- function authorRole(config, task, actor) {
9554
- if (actor === "operator") return "operator";
9555
- const parsed = parseActorId(actor);
9556
- if (parsed?.actor === "agent" && config.projects.some((project) => project.spurProjects.some((spur) => spur.name === parsed.actorRef.project && spur.role === "operator"))) return "operator";
9557
- const configured = orchestrator(config, task);
9558
- return parsed?.actor === "agent" && parsed.actorRef.project === configured ? `orchestrator:${task.column}` : "worker";
9769
+ await emit(trx, kind, task.project, task.id, ctx.at, payload, ctx.actor);
9559
9770
  }
9560
- function personaFor(config, task, actor) {
9561
- if (actor === "system") return {
9562
- name: "board",
9563
- role: "board"
9564
- };
9565
- if (actor === "operator") return {
9566
- name: "operator",
9567
- role: "board"
9568
- };
9569
- const parsed = parseActorId(actor);
9570
- if (parsed?.actor !== "agent") throw new Error("Invalid actor");
9571
- const role = authorRole(config, task, actor);
9572
- return {
9573
- name: parsed.actorRef.project,
9574
- role: role === "operator" ? "board" : role === "worker" ? "worker" : "orchestrator"
9575
- };
9771
+ async function hasWorker(trx, task) {
9772
+ return await trx.selectFrom("link").select("id").where("task_id", "=", task.id).where("entity", "=", "session").where("role", "=", "worker").where("banned", "=", 0).executeTakeFirst() !== void 0;
9576
9773
  }
9577
- async function queueBlockOpen(trx, task, block, ctx, config) {
9578
- if (authorRole(config, task, block.author) === "operator") return;
9579
- const comments = await trx.selectFrom("comment").select(["id", "author"]).where("block_id", "=", block.id).orderBy("id").execute();
9580
- if (await enqueueConversationOpen(trx, {
9581
- blockId: block.id,
9582
- commentId: comments[0]?.id ?? null,
9583
- persona: personaFor(config, task, comments[0]?.author ?? block.author),
9584
- at: new Date(ctx.at)
9585
- }) === null) return;
9586
- for (const comment of comments.slice(1)) await enqueueConversationReply(trx, {
9587
- commentId: comment.id,
9588
- persona: personaFor(config, task, comment.author),
9589
- at: new Date(ctx.at)
9774
+ /** The addressee a block gets from current config and links. */
9775
+ async function routeBlock(trx, task, block, config) {
9776
+ return blockAddressee({
9777
+ type: block.type,
9778
+ author: block.author,
9779
+ authorRole: authorRole(config, task, block.author),
9780
+ column: task.column,
9781
+ orchestrator: orchestrator(config, task),
9782
+ curator: curatorProject(config, task.project),
9783
+ hasWorker: await hasWorker(trx, task)
9590
9784
  });
9591
9785
  }
9592
- async function hasWorker(trx, task) {
9593
- return await trx.selectFrom("link").select("id").where("task_id", "=", task.id).where("entity", "=", "session").where("role", "=", "worker").where("banned", "=", 0).executeTakeFirst() !== void 0;
9786
+ function holdsBlock(config, actor, target) {
9787
+ return authorize([{ grant: "block-addressee" }], actor, {
9788
+ config,
9789
+ target
9790
+ }).status === "allowed";
9594
9791
  }
9595
9792
  async function addComment(trx, task, block, text, ctx, addressee, config, source) {
9596
9793
  const row = await trx.insertInto("comment").values({
@@ -9609,13 +9806,14 @@ async function addComment(trx, task, block, text, ctx, addressee, config, source
9609
9806
  comment: commentId(row.id),
9610
9807
  addressee
9611
9808
  });
9612
- if (block !== void 0 && source === void 0 && ctx.actor !== block.author) await registerAnswerNotification(trx, {
9809
+ await applyDoorbellPolicy(trx, block === void 0 ? { kind: "task_comment" } : {
9810
+ kind: "answer",
9613
9811
  block,
9614
9812
  commentId: row.id,
9615
9813
  revision: row.revision,
9616
9814
  authorRole: authorRole(config, task, block.author),
9617
- at: new Date(ctx.at)
9618
- });
9815
+ actor: ctx.actor
9816
+ }, new Date(ctx.at));
9619
9817
  if (block !== void 0 && source === void 0) await enqueueConversationReply(trx, {
9620
9818
  commentId: row.id,
9621
9819
  persona: personaFor(config, task, ctx.actor),
@@ -9624,14 +9822,10 @@ async function addComment(trx, task, block, text, ctx, addressee, config, source
9624
9822
  return row;
9625
9823
  }
9626
9824
  async function openBlock(trx, task, type, reason, ctx, config) {
9627
- const addressee = blockAddressee({
9825
+ const addressee = await routeBlock(trx, task, {
9628
9826
  type,
9629
- author: ctx.actor,
9630
- authorRole: authorRole(config, task, ctx.actor),
9631
- column: task.column,
9632
- orchestrator: orchestrator(config, task),
9633
- hasWorker: await hasWorker(trx, task)
9634
- });
9827
+ author: ctx.actor
9828
+ }, config);
9635
9829
  const row = await trx.insertInto("block").values({
9636
9830
  task_id: task.id,
9637
9831
  type,
@@ -9652,7 +9846,11 @@ async function openBlock(trx, task, type, reason, ctx, config) {
9652
9846
  type,
9653
9847
  addressee
9654
9848
  });
9655
- await registerBlockNotification(trx, row, new Date(ctx.at));
9849
+ await applyDoorbellPolicy(trx, {
9850
+ kind: "block_opened",
9851
+ block: row,
9852
+ authorRole: authorRole(config, task, ctx.actor)
9853
+ }, new Date(ctx.at));
9656
9854
  return row;
9657
9855
  }
9658
9856
  /** Unblocks one block with its journal entry, thread close, doorbell close and item clears. */
@@ -9703,7 +9901,7 @@ async function recordInboundBlockMessage(trx, input) {
9703
9901
  block: answered ? await closeOpenBlock(trx, task, block, ctx, "done", null) : block,
9704
9902
  task,
9705
9903
  answered,
9706
- workerAuthor: authorRole(input.config, task, block.author) === "worker"
9904
+ authorRole: authorRole(input.config, task, block.author)
9707
9905
  };
9708
9906
  }
9709
9907
  /** Uses the same revision and acknowledgment rule as the catalog comment.edit mutation. */
@@ -9726,13 +9924,14 @@ async function editInboundComment(trx, input) {
9726
9924
  });
9727
9925
  if (next.clarification && updated.block_id !== null) {
9728
9926
  const block = await trx.selectFrom("block").selectAll().where("id", "=", updated.block_id).executeTakeFirstOrThrow();
9729
- if (input.actor !== block.author) await registerAnswerNotification(trx, {
9927
+ await applyDoorbellPolicy(trx, {
9928
+ kind: "answer",
9730
9929
  block,
9731
9930
  commentId: updated.id,
9732
9931
  revision: updated.revision,
9733
9932
  authorRole: authorRole(input.config, task, block.author),
9734
- at: new Date(input.at)
9735
- });
9933
+ actor: input.actor
9934
+ }, new Date(input.at));
9736
9935
  }
9737
9936
  return updated;
9738
9937
  }
@@ -9766,50 +9965,43 @@ function createBlockMutations(config) {
9766
9965
  id: "block.escalate",
9767
9966
  async resolveTargets(trx, input, actor) {
9768
9967
  const block = await blockById(trx, input.block);
9769
- if (block === void 0 || block.addressee_role !== "operator") return blockTarget(trx, input.block);
9968
+ if (block === void 0) return blockTarget(trx, input.block);
9770
9969
  const task = await taskById(trx, block.task_id);
9771
9970
  const target = await authorizationTarget(trx, task, block);
9772
9971
  if (target.kind !== "found" || target.value.block === null) return [target];
9773
- const original = blockAddressee({
9774
- type: block.type,
9775
- author: block.author,
9776
- authorRole: authorRole(config, task, block.author),
9777
- column: task.column,
9778
- orchestrator: orchestrator(config, task),
9779
- hasWorker: block.author === "system" && await hasWorker(trx, task)
9780
- });
9781
- if (original === "operator") return [target];
9782
- const originalTarget = {
9783
- kind: "found",
9784
- value: {
9785
- ...target.value,
9786
- block: {
9787
- ...target.value.block,
9788
- addressee_role: original
9972
+ if (holdsBlock(config, actor, target)) return [target];
9973
+ const priors = priorAddressees(await routeBlock(trx, task, block, config), block.addressee_role, block.type, curatorProject(config, task.project) !== null);
9974
+ for (const addressee_role of priors) {
9975
+ const prior = {
9976
+ kind: "found",
9977
+ value: {
9978
+ ...target.value,
9979
+ block: {
9980
+ ...target.value.block,
9981
+ addressee_role
9982
+ }
9789
9983
  }
9790
- }
9791
- };
9792
- return [authorize([{ grant: "block-addressee" }], actor, {
9793
- config,
9794
- target: originalTarget
9795
- }).status === "allowed" ? originalTarget : target];
9984
+ };
9985
+ if (holdsBlock(config, actor, prior)) return [prior];
9986
+ }
9987
+ return [target];
9796
9988
  },
9797
9989
  async run(trx, input, ctx) {
9798
9990
  const block = found(await blockById(trx, input.block));
9799
9991
  const task = await taskById(trx, block.task_id);
9800
9992
  active(task);
9801
- const next = rule(() => escalateBlock(current(block)));
9993
+ const hasCurator = curatorProject(config, task.project) !== null;
9994
+ const next = rule(() => escalateBlock(current(block), hasCurator));
9802
9995
  if (!next.changed) return { block: blockView(block, task) };
9803
- const updated = await trx.updateTable("block").set({ addressee_role: next.addressee }).where("id", "=", block.id).returningAll().executeTakeFirstOrThrow();
9804
- await journal$1(trx, task, ctx, "block_escalated", {
9805
- block: input.block,
9806
- from: block.addressee_role,
9807
- to: next.addressee
9808
- });
9809
- await closeBlockNotification(trx, block.id, new Date(ctx.at));
9810
- await queueBlockOpen(trx, task, updated, ctx, config);
9811
- await registerBlockNotification(trx, updated, new Date(ctx.at));
9812
- return { block: blockView(updated, task) };
9996
+ const target = await authorizationTarget(trx, task, block);
9997
+ if (!holdsBlock(config, ctx.actor, target)) return { block: blockView(block, task) };
9998
+ return { block: blockView(await moveBlockToAddressee(trx, {
9999
+ task,
10000
+ block,
10001
+ to: next.addressee,
10002
+ ctx,
10003
+ config
10004
+ }), task) };
9813
10005
  }
9814
10006
  },
9815
10007
  answer: {
@@ -9847,7 +10039,12 @@ function createBlockMutations(config) {
9847
10039
  actor: ctx.actor
9848
10040
  }));
9849
10041
  if (input.mode === "withdraw") await addComment(trx, task, block, input.answer, ctx, block.addressee_role, config);
9850
- return { block: blockView(await closeOpenBlock(trx, task, block, ctx, decision.outcome, decision.outcomeReason), task) };
10042
+ const updated = await closeOpenBlock(trx, task, block, ctx, decision.outcome, decision.outcomeReason);
10043
+ await applyDoorbellPolicy(trx, input.mode === "done" || holdsBlock(config, ctx.actor, await authorizationTarget(trx, task, block)) ? { kind: "block_closed_by_addressee" } : {
10044
+ kind: "block_removed",
10045
+ block: updated
10046
+ }, new Date(ctx.at));
10047
+ return { block: blockView(updated, task) };
9851
10048
  }
9852
10049
  },
9853
10050
  add: {
@@ -9903,7 +10100,8 @@ function createBlockMutations(config) {
9903
10100
  if (!await acknowledgeNotification(trx, {
9904
10101
  blockId: found(await blockById(trx, entry.id)).id,
9905
10102
  actor: ctx.actor,
9906
- at: new Date(ctx.at)
10103
+ at: new Date(ctx.at),
10104
+ config
9907
10105
  })) throw new CommandError("not_found", "No unread block notification.");
9908
10106
  continue;
9909
10107
  }
@@ -9914,7 +10112,8 @@ function createBlockMutations(config) {
9914
10112
  commentId: comment.id,
9915
10113
  revision,
9916
10114
  actor: ctx.actor,
9917
- at: new Date(ctx.at)
10115
+ at: new Date(ctx.at),
10116
+ config
9918
10117
  });
9919
10118
  await trx.updateTable("comment").set({ acked_revision: revision }).where("id", "=", comment.id).execute();
9920
10119
  await journal$1(trx, task, ctx, "comment_acked", {
@@ -10432,7 +10631,7 @@ function createSender(options) {
10432
10631
  };
10433
10632
  }
10434
10633
  if (c.body.kind === "doorbell" && c.body.payload.notificationId !== void 0) {
10435
- const status = await ringStillCurrent(trx, c.body.payload.notificationId, c.body.payload.session);
10634
+ const status = await ringStillCurrent(trx, c.body.payload.notificationId, c.body.payload.session, options.config);
10436
10635
  if (status === "dead") {
10437
10636
  await kill(trx, [c.id], "notification no longer current");
10438
10637
  return {
@@ -11391,7 +11590,7 @@ function createTaskQueries(config) {
11391
11590
  const task = await trx.selectFrom("task").selectAll().where("id", "=", notice.task_id).executeTakeFirst();
11392
11591
  if (task === void 0 || !projects.has(task.project)) continue;
11393
11592
  seen.add(notice.comment_id);
11394
- if (!await notificationAddressedTo(trx, notice, actor)) continue;
11593
+ if (!await notificationAddressedTo(trx, notice, actor, config)) continue;
11395
11594
  const comment = await trx.selectFrom("comment").selectAll().where("id", "=", notice.comment_id).executeTakeFirst();
11396
11595
  if (comment === void 0 || comment.acked_revision === comment.revision) continue;
11397
11596
  comments.push(commentView(comment, task));
@@ -12329,6 +12528,14 @@ function createObservationCore(deps) {
12329
12528
  kind: "session",
12330
12529
  id: link.session_id
12331
12530
  }]) : [];
12531
+ const curators = config.projects.flatMap((project) => project.spurProjects.filter((spur) => spur.role === "curator").map((spur) => spur.name));
12532
+ if (source === "spur" && curators.length > 0) {
12533
+ const rows = await store.db.selectFrom("session_snapshot").select("id").where("spur_project", "in", curators).where("ended_at", "is", null).execute();
12534
+ sessions.push(...rows.map((row) => ({
12535
+ kind: "session",
12536
+ id: row.id
12537
+ })));
12538
+ }
12332
12539
  const misses = await store.db.selectFrom("source_miss").selectAll().where("source", "=", source).execute();
12333
12540
  return {
12334
12541
  observe: {
@@ -12701,20 +12908,7 @@ function plain(text) {
12701
12908
  }];
12702
12909
  }
12703
12910
  async function journal(trx, input) {
12704
- const actor = parseActorId(input.actor);
12705
- if (actor === null) throw new Error("Invalid journal actor");
12706
- const schema = eventPayloadSchemas[input.kind];
12707
- await trx.insertInto("event").values({
12708
- at: input.at,
12709
- project: input.project,
12710
- task_id: input.taskId,
12711
- kind: input.kind,
12712
- actor: actor.actor,
12713
- actor_ref: actor.actor === "agent" ? JSON.stringify(actor.actorRef) : null,
12714
- payload: toJson(z.unknown(), schema.parse(input.payload)),
12715
- v: 1,
12716
- request_id: null
12717
- }).execute();
12911
+ await emit(trx, input.kind, input.project, input.taskId, input.at, input.payload, input.actor);
12718
12912
  }
12719
12913
  async function taskContext(trx, event, gateway) {
12720
12914
  if (!("conversation" in event) || event.conversation === void 0) return {
@@ -12785,34 +12979,16 @@ async function skip(trx, input) {
12785
12979
  async function linkedComment(trx, event) {
12786
12980
  return trx.selectFrom("comment").selectAll().where("conversation_ref", "=", event.conversation).where("message_ref", "=", event.message).executeTakeFirst();
12787
12981
  }
12982
+ /** The answer's notification is already registered; this raises the item when nobody can read it. */
12788
12983
  async function ringAuthor(trx, input) {
12789
12984
  const key = `doorbell:comment:${String(input.comment.id)}:revision:${String(input.comment.revision)}`;
12790
12985
  const parsed = parseActorId(input.block.author);
12791
- if (parsed?.actor === "agent") if (input.workerAuthor) {
12792
- const recipient = await selectNotificationRecipient(trx, {
12986
+ if (parsed?.actor === "agent") {
12987
+ if (await selectNotificationRecipient(trx, {
12793
12988
  task_id: input.task.id,
12794
- role: "worker",
12989
+ role: input.authorRole,
12795
12990
  author_session: parsed.actorRef.session
12796
- });
12797
- await registerAnswerNotification(trx, {
12798
- block: input.block,
12799
- commentId: input.comment.id,
12800
- revision: input.comment.revision,
12801
- authorRole: "worker",
12802
- at: new Date(input.at)
12803
- });
12804
- if (recipient !== void 0) return;
12805
- } else {
12806
- const session = await trx.selectFrom("session_snapshot").select(["id", "ended_at"]).where("id", "=", parsed.actorRef.session).executeTakeFirst();
12807
- if (session !== void 0 && session.ended_at === null) {
12808
- await enqueueInboundDoorbell(trx, {
12809
- key,
12810
- session: session.id,
12811
- text: `Answer for ${input.task.key} block B${String(input.block.id)}; read board task ${input.task.key}`,
12812
- at: new Date(input.at)
12813
- });
12814
- return;
12815
- }
12991
+ }, input.config) !== void 0) return;
12816
12992
  }
12817
12993
  await journal(trx, {
12818
12994
  kind: "doorbell_undelivered",
@@ -12884,8 +13060,9 @@ function createInbound(input) {
12884
13060
  block: recorded.block,
12885
13061
  task: recorded.task,
12886
13062
  comment: recorded.comment,
12887
- workerAuthor: recorded.workerAuthor,
12888
- at
13063
+ authorRole: recorded.authorRole,
13064
+ at,
13065
+ config
12889
13066
  });
12890
13067
  return { status: "applied" };
12891
13068
  }
@@ -13114,7 +13291,7 @@ function createInbound(input) {
13114
13291
  });
13115
13292
  }
13116
13293
  async function recordFailure(event, error, at) {
13117
- await scanTransaction(store, config, async (trx) => {
13294
+ await withCommandKey(event.dedupeKey, () => scanTransaction(store, config, async (trx) => {
13118
13295
  const context = await taskContext(trx, event, gateway.kind);
13119
13296
  await journal(trx, {
13120
13297
  kind: "inbound_failed",
@@ -13137,7 +13314,7 @@ function createInbound(input) {
13137
13314
  at,
13138
13315
  retry: true
13139
13316
  });
13140
- });
13317
+ }));
13141
13318
  }
13142
13319
  async function dispatchInteraction(event) {
13143
13320
  const token = event.kind === "action" ? tokenAction(event) : null;
@@ -16924,7 +17101,7 @@ function createSpurPort(options) {
16924
17101
  const { url, init } = spurSendRequest(options.baseUrl, session, text);
16925
17102
  let response;
16926
17103
  try {
16927
- response = await fetch(url, {
17104
+ response = await (options.fetch ?? fetch)(url, {
16928
17105
  ...init,
16929
17106
  signal: AbortSignal.timeout(options.timeoutMs ?? SEND_TIMEOUT_MS)
16930
17107
  });