spur-board 0.16.0 → 0.16.2

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.
Files changed (2) hide show
  1. package/dist/daemon.mjs +403 -385
  2. package/package.json +1 -1
package/dist/daemon.mjs CHANGED
@@ -7612,10 +7612,17 @@ async function redactPrivateReply(body) {
7612
7612
  };
7613
7613
  }));
7614
7614
  }
7615
+ const NO_SCAN = "Gateway outbox requires a secret scan transaction";
7616
+ /** The config of the running scan transaction; gateway producers read task links from it. */
7617
+ function scanConfig() {
7618
+ const context = receipts.getStore();
7619
+ if (context === void 0) throw new Error(NO_SCAN);
7620
+ return context.config;
7621
+ }
7615
7622
  /** Used by the common outbox insertion point before it issues SQL. */
7616
7623
  function checkGatewayStrings(strings) {
7617
7624
  const context = receipts.getStore();
7618
- if (context === void 0) throw new Error("Gateway outbox requires a secret scan transaction");
7625
+ if (context === void 0) throw new Error(NO_SCAN);
7619
7626
  const { known, unseen } = context;
7620
7627
  for (const value of strings) if (!known.has(value)) unseen.add(value);
7621
7628
  if (unseen.size > 0) return SCAN_PENDING;
@@ -7626,10 +7633,11 @@ function checkGatewayStrings(strings) {
7626
7633
  return null;
7627
7634
  }
7628
7635
  /** Replays database-only work after scanning exact strings outside the write transaction. */
7629
- async function scanTransaction(store, fn) {
7636
+ async function scanTransaction(store, config, fn) {
7630
7637
  const known = /* @__PURE__ */ new Map();
7631
7638
  for (let pass = 0; pass < MAX_PASSES; pass += 1) {
7632
7639
  const context = {
7640
+ config,
7633
7641
  known,
7634
7642
  unseen: /* @__PURE__ */ new Set()
7635
7643
  };
@@ -7683,6 +7691,16 @@ function projectForKey(config, key) {
7683
7691
  });
7684
7692
  return matched.length === 1 ? matched[0] ?? null : null;
7685
7693
  }
7694
+ /** The tracker page of a task: GitHub issue, Jira issue, or a GitHub fallback by key. */
7695
+ function taskUrl(task, config) {
7696
+ if (task.tracker_kind === "github-issues") {
7697
+ const match = /^(.+)#(\d+)$/.exec(task.key);
7698
+ if (match?.[1] !== void 0 && match[2] !== void 0) return `https://github.com/${match[1]}/issues/${match[2]}`;
7699
+ }
7700
+ const project = config.projects.find((p) => p.id === task.project);
7701
+ if (project?.tracker.type === "jira") return `${project.tracker.baseUrl.replace(/\/$/, "")}/browse/${task.key}`;
7702
+ return `https://github.com/${task.key.replace("#", "/issues/")}`;
7703
+ }
7686
7704
  async function emit(trx, kind, project, taskId, at, payload, actor = "system") {
7687
7705
  const parsed = parseActorId(actor);
7688
7706
  if (parsed === null) throw new Error("Invalid journal actor");
@@ -7843,7 +7861,7 @@ function createApply(deps) {
7843
7861
  const commandKey = key ?? randomUUID();
7844
7862
  let deniedHint;
7845
7863
  const at = new Date(clock.now()).toISOString();
7846
- const result = await scanTransaction(store, (trx) => replayOperation(trx, {
7864
+ const result = await scanTransaction(store, config, (trx) => replayOperation(trx, {
7847
7865
  actor,
7848
7866
  key: commandKey,
7849
7867
  operation: entry.id,
@@ -7898,7 +7916,7 @@ function commandRetention(deps) {
7898
7916
  let running = Promise.resolve();
7899
7917
  const run = async () => {
7900
7918
  const cutoff = (/* @__PURE__ */ new Date(clock.now() - retentionDays * DAY_MS)).toISOString();
7901
- await scanTransaction(store, async (trx) => {
7919
+ await store.transaction(async (trx) => {
7902
7920
  await trx.deleteFrom("command").where("at", "<", cutoff).execute();
7903
7921
  });
7904
7922
  };
@@ -7970,251 +7988,103 @@ async function dispatchOperation(deps, id, input, actor, key) {
7970
7988
  return operation.kind === "query" ? createQuery(deps)(handler, input, actor) : createApply(deps)(handler, input, actor, key);
7971
7989
  }
7972
7990
  //#endregion
7973
- //#region ../core/src/app/doorbells.ts
7974
- const DEFAULT_PAUSES = [
7975
- 12e4,
7976
- 3e5,
7977
- 9e5
7978
- ];
7979
- async function journal$3(trx, notification, kind, payload, at) {
7980
- const task = await trx.selectFrom("task").select("project").where("id", "=", notification.task_id).executeTakeFirstOrThrow();
7991
+ //#region ../core/src/app/item-raise.ts
7992
+ const NO_FEED = /* @__PURE__ */ new Set([
7993
+ "post_failed",
7994
+ "answer_undelivered",
7995
+ "transport_health"
7996
+ ]);
7997
+ async function journal$3(trx, item, kind, at, rule, actor = "system") {
7998
+ const parsed = parseActorId(actor);
7999
+ if (parsed === null) throw new Error("Invalid journal actor");
8000
+ const task = item.task_id === null ? void 0 : await trx.selectFrom("task").select(["project"]).where("id", "=", item.task_id).executeTakeFirstOrThrow();
7981
8001
  await trx.insertInto("event").values({
7982
8002
  at: at.toISOString(),
7983
- project: task.project,
7984
- task_id: notification.task_id,
8003
+ project: task?.project ?? "_board",
8004
+ task_id: item.task_id,
7985
8005
  kind,
7986
- actor: "system",
7987
- actor_ref: null,
7988
- payload: toJson(eventPayloadSchemas[kind], payload),
8006
+ actor: parsed.actor,
8007
+ actor_ref: parsed.actor === "agent" ? JSON.stringify(parsed.actorRef) : null,
8008
+ payload: toJson(eventPayloadSchemas[kind], {
8009
+ item: `I${String(item.id)}`,
8010
+ ...kind === "from_you_raised" && rule !== void 0 ? { rule } : {}
8011
+ }),
7989
8012
  v: 1,
7990
8013
  request_id: null
7991
8014
  }).execute();
7992
8015
  }
7993
- /** Register a worker-addressed block without manufacturing a comment. */
7994
- async function registerBlockNotification(trx, block, at) {
7995
- if (block.addressee_role !== "worker") return;
7996
- await trx.insertInto("notification").values({
7997
- source_key: `block:${String(block.id)}:worker`,
7998
- kind: "block",
7999
- task_id: block.task_id,
8000
- block_id: block.id,
8001
- comment_id: null,
8002
- revision: null,
8003
- role: "worker",
8004
- author_session: null,
8005
- recipient_session: null,
8006
- next_at: at.toISOString(),
8007
- last_outbox_id: null,
8008
- acked_at: null,
8009
- exhausted_at: null,
8010
- created_at: at.toISOString()
8011
- }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
8012
- }
8013
- /** Register an answer or clarification for the original author and its task role. */
8014
- async function registerAnswerNotification(trx, input) {
8015
- if (input.authorRole !== "worker") return;
8016
- const parsed = parseActorId(input.block.author);
8017
- if (parsed?.actor !== "agent") return;
8018
- await trx.insertInto("notification").values({
8019
- source_key: `comment:${String(input.commentId)}:${String(input.revision)}`,
8020
- kind: "answer",
8021
- task_id: input.block.task_id,
8022
- block_id: input.block.id,
8023
- comment_id: input.commentId,
8024
- revision: input.revision,
8025
- role: "worker",
8026
- author_session: parsed.actorRef.session,
8027
- recipient_session: null,
8028
- next_at: input.at.toISOString(),
8029
- last_outbox_id: null,
8030
- acked_at: null,
8031
- exhausted_at: null,
8032
- created_at: input.at.toISOString()
8033
- }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
8034
- }
8035
- async function liveSession(trx, id) {
8036
- const row = await trx.selectFrom("session_snapshot").selectAll().where("id", "=", id).executeTakeFirst();
8037
- return row?.ended_at === null && row.state !== "killed" && row.state !== "stopped" ? row : void 0;
8038
- }
8039
- /** Select the current live recipient for a semantic notification. */
8040
- async function selectNotificationRecipient(trx, n) {
8041
- if (n.author_session !== null) {
8042
- const author = await liveSession(trx, n.author_session);
8043
- if (author !== void 0) return author;
8044
- }
8045
- 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();
8046
- for (const link of links) {
8047
- if (link.session_id === null) continue;
8048
- const session = await liveSession(trx, link.session_id);
8049
- if (session !== void 0) return session;
8050
- }
8051
- }
8052
- function taskUrl(task, config) {
8053
- if (task.tracker_kind === "github-issues") {
8054
- const match = /^(.+)#(\d+)$/.exec(task.key);
8055
- if (match?.[1] !== void 0 && match[2] !== void 0) return `https://github.com/${match[1]}/issues/${match[2]}`;
8056
- }
8057
- const project = config?.projects.find((p) => p.id === task.project);
8058
- if (project?.tracker.type === "jira") return `${project.tracker.baseUrl.replace(/\/$/, "")}/browse/${task.key}`;
8059
- return `https://github.com/${task.key.replace("#", "/issues/")}`;
8060
- }
8061
- /** The operator item kind raised when a notification's rings are exhausted. */
8062
- function exhaustedItemKind(n) {
8063
- return n.kind === "answer" ? "answer_undelivered" : "worker_not_reading";
8064
- }
8065
- /** The operator item key raised when a notification's rings are exhausted. */
8066
- function exhaustedItemKey(n) {
8067
- return `${exhaustedItemKind(n)}:${n.source_key}`;
8016
+ /** Kinds whose item has a retry action besides `delivery:<id>` (see `items.ts`). */
8017
+ const RETRY_KINDS = /* @__PURE__ */ new Set([
8018
+ "answer_undelivered",
8019
+ "worker_not_reading",
8020
+ "inbound_failure"
8021
+ ]);
8022
+ /** Every item line gets Close, after Retry when its kind has a retry action. */
8023
+ function itemActions(item) {
8024
+ const id = String(item.id);
8025
+ const close = {
8026
+ id: `item:${id}:close`,
8027
+ label: "Close"
8028
+ };
8029
+ if (item.kind === "token_request") return [
8030
+ {
8031
+ id: `token:${id}:approve`,
8032
+ label: "Approve"
8033
+ },
8034
+ {
8035
+ id: `token:${id}:deny`,
8036
+ label: "Deny"
8037
+ },
8038
+ close
8039
+ ];
8040
+ return item.item_key.startsWith("delivery:") || RETRY_KINDS.has(item.kind) ? [{
8041
+ id: `item:${id}:retry`,
8042
+ label: "Retry"
8043
+ }, close] : [close];
8068
8044
  }
8069
8045
  /**
8070
- * Restart an exhausted, unacknowledged ring series at `at`. The recipient and last row stay, so
8071
- * the next reconcile rings the same session under the next series key.
8046
+ * Raise one item generation; `writeLine` enqueues its feed line. A repeated raise of an active
8047
+ * key is idempotent.
8072
8048
  */
8073
- async function restartNotification(trx, sourceKey, at) {
8074
- if (await trx.updateTable("notification").set({
8075
- rings: 0,
8076
- exhausted_at: null,
8077
- next_at: at.toISOString()
8078
- }).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.");
8079
- }
8080
- /** Reconcile due semantic notifications in the sender's claim transaction. */
8081
- async function reconcileDoorbells(trx, at, config) {
8082
- const due = await trx.selectFrom("notification").innerJoin("task", "task.id", "notification.task_id").selectAll("notification").where("task.membership", "!=", "archived").where("notification.acked_at", "is", null).where("notification.exhausted_at", "is", null).where("notification.next_at", "<=", at.toISOString()).orderBy("notification.id").execute();
8083
- for (const n of due) {
8084
- const session = await selectNotificationRecipient(trx, n);
8085
- if (session === void 0) {
8086
- if (n.recipient_session !== null) await trx.updateTable("notification").set({
8087
- recipient_session: null,
8088
- rings: 0,
8089
- last_outbox_id: null
8090
- }).where("id", "=", n.id).execute();
8091
- continue;
8092
- }
8093
- if (session.state === "working") continue;
8094
- let rings = n.rings;
8095
- let lastOutbox = n.last_outbox_id;
8096
- if (session.id !== n.recipient_session) {
8097
- if (lastOutbox !== null) await trx.updateTable("outbox").set({
8098
- state: "dead",
8099
- last_error: "recipient changed"
8100
- }).where("id", "=", lastOutbox).where("state", "=", "pending").execute();
8101
- rings = 0;
8102
- lastOutbox = null;
8103
- await trx.updateTable("notification").set({
8104
- recipient_session: session.id,
8105
- rings: 0,
8106
- last_outbox_id: null
8107
- }).where("id", "=", n.id).execute();
8108
- }
8109
- if (lastOutbox !== null) {
8110
- const row = await trx.selectFrom("outbox").select("state").where("id", "=", lastOutbox).executeTakeFirst();
8111
- if (row?.state === "pending" || row?.state === "in_flight") continue;
8112
- }
8113
- const task = await trx.selectFrom("task").selectAll().where("id", "=", n.task_id).executeTakeFirstOrThrow();
8114
- const itemKey = exhaustedItemKey(n);
8115
- if (rings >= 3) {
8116
- await raiseItem(trx, {
8117
- itemKey,
8118
- kind: exhaustedItemKind(n),
8119
- 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}`,
8120
- url: taskUrl(task, config),
8121
- taskId: task.id,
8122
- blockId: n.block_id,
8123
- at
8124
- });
8125
- await trx.updateTable("notification").set({ exhausted_at: at.toISOString() }).where("id", "=", n.id).execute();
8126
- await journal$3(trx, n, "doorbell_undelivered", {
8127
- doorbell: `N${String(n.id)}`,
8128
- reason: "unanswered"
8129
- }, at);
8130
- continue;
8131
- }
8132
- const raised = await trx.selectFrom("operator_item").select((eb) => eb.fn.max("raise_no").as("series")).where("item_key", "=", itemKey).executeTakeFirst();
8133
- const archived = await trx.selectFrom("event").select((eb) => eb.fn.countAll().as("count")).where("task_id", "=", n.task_id).where("kind", "=", "task_archived").executeTakeFirst();
8134
- const ring = rings + 1;
8135
- const text = `${task.key} block B${String(n.block_id)}: check board inbox (N${String(n.id)}-${String(ring)})`;
8136
- const outboxId = await enqueueDoorbell(trx, {
8137
- notificationId: n.id,
8138
- ring,
8139
- session: session.id,
8140
- text,
8141
- at,
8142
- series: raised?.series ?? 0,
8143
- archives: archived?.count ?? 0
8049
+ async function raiseItemWith(trx, input, writeLine) {
8050
+ const active = await trx.selectFrom("operator_item").selectAll().where("item_key", "=", input.itemKey).where("cleared_at", "is", null).executeTakeFirst();
8051
+ if (active !== void 0) return active;
8052
+ const previous = await trx.selectFrom("operator_item").select("raise_no").where("item_key", "=", input.itemKey).orderBy("raise_no", "desc").executeTakeFirst();
8053
+ let item = await trx.insertInto("operator_item").values({
8054
+ item_key: input.itemKey,
8055
+ raise_no: (previous?.raise_no ?? 0) + 1,
8056
+ kind: input.kind,
8057
+ text: input.text,
8058
+ url: input.url,
8059
+ task_id: input.taskId,
8060
+ block_id: input.blockId,
8061
+ raised_at: input.at.toISOString(),
8062
+ cleared_at: null,
8063
+ line_outbox_id: null,
8064
+ fingerprint: input.fingerprint ?? null,
8065
+ fact_at: input.factAt ?? null,
8066
+ source: input.source ?? null,
8067
+ priority: input.priority ?? null,
8068
+ inbound_event_json: null
8069
+ }).returningAll().executeTakeFirstOrThrow();
8070
+ await journal$3(trx, item, "from_you_raised", input.at, input.rule);
8071
+ if (!NO_FEED.has(item.kind) && !input.suppressFeed) {
8072
+ const key = (item.task_id === null ? null : await trx.selectFrom("task").select("key").where("id", "=", item.task_id).executeTakeFirstOrThrow())?.key ?? "spur-board";
8073
+ const line = await writeLine(trx, {
8074
+ itemId: item.id,
8075
+ itemKey: item.item_key,
8076
+ raise: item.raise_no,
8077
+ key,
8078
+ text: item.text,
8079
+ title: `${key}: ${item.text}`,
8080
+ url: item.url,
8081
+ taskId: item.task_id,
8082
+ actions: itemActions(item),
8083
+ at: input.at
8144
8084
  });
8145
- await trx.updateTable("notification").set({ last_outbox_id: outboxId }).where("id", "=", n.id).execute();
8146
- }
8147
- }
8148
- /** Count one confirmed Spur send, regardless of transport attempts for its outbox row. */
8149
- async function recordRingDelivery(trx, notificationId, ring, session, at, config) {
8150
- const n = await trx.selectFrom("notification").selectAll().where("id", "=", notificationId).executeTakeFirst();
8151
- if (n === void 0 || n.acked_at !== null || n.recipient_session !== session || n.rings >= ring) return;
8152
- const pauses = config ? [
8153
- config.doorbells.firstRetryMs,
8154
- config.doorbells.secondRetryMs,
8155
- config.doorbells.unansweredAfterMs
8156
- ] : DEFAULT_PAUSES;
8157
- await trx.updateTable("notification").set({
8158
- rings: ring,
8159
- next_at: new Date(at.getTime() + (pauses[ring - 1] ?? 0)).toISOString()
8160
- }).where("id", "=", notificationId).execute();
8161
- await journal$3(trx, n, "doorbell_rung", {
8162
- doorbell: `N${String(n.id)}`,
8163
- addressee: n.role,
8164
- attempt: ring
8165
- }, at);
8166
- }
8167
- /** Confirm that a queued ring still belongs to a live, idle, unread recipient. */
8168
- async function ringStillCurrent(trx, notificationId, sessionId) {
8169
- const n = await trx.selectFrom("notification").selectAll().where("id", "=", notificationId).executeTakeFirst();
8170
- if (n === void 0 || n.acked_at !== null || n.exhausted_at !== null || n.recipient_session !== sessionId) return "dead";
8171
- const session = await selectNotificationRecipient(trx, n);
8172
- if (session?.id !== sessionId) return "dead";
8173
- return session.state === "working" ? "defer" : "send";
8174
- }
8175
- /**
8176
- * The task of a ring: through its notification, or for an inbound author ring (no notification)
8177
- * through the comment in its `doorbell:comment:<id>:` key. Archive kills only unclaimed rings;
8178
- * the sender drops a claimed one of an archived task before its send starts.
8179
- */
8180
- async function ringTask(trx, notificationId, dedupeKey) {
8181
- const commentId = /^doorbell:comment:(\d+):/.exec(dedupeKey)?.[1];
8182
- if (notificationId === void 0 && commentId === void 0) return void 0;
8183
- const owner = notificationId !== void 0 ? trx.selectFrom("notification").select("task_id").where("id", "=", notificationId) : trx.selectFrom("comment").select("task_id").where("id", "=", Number(commentId));
8184
- return trx.selectFrom("task").selectAll().where("id", "in", owner).executeTakeFirst();
8185
- }
8186
- /** Stop notifications acknowledged by the addressed session. */
8187
- async function acknowledgeNotification(trx, input) {
8188
- let query = trx.selectFrom("notification").selectAll().where("acked_at", "is", null);
8189
- if (input.blockId !== void 0) query = query.where("block_id", "=", input.blockId).where("kind", "=", "block");
8190
- else if (input.commentId !== void 0) query = query.where("comment_id", "=", input.commentId).where("kind", "=", "answer");
8191
- else return false;
8192
- const notices = await query.orderBy("id", "desc").execute();
8193
- const n = notices[0];
8194
- if (n === void 0) return false;
8195
- if (!await notificationAddressedTo(trx, n, input.actor)) throw new CommandError("forbidden", "Only the addressed task role can acknowledge.");
8196
- for (const notice of notices) {
8197
- await trx.updateTable("notification").set({ acked_at: input.at.toISOString() }).where("id", "=", notice.id).execute();
8198
- await journal$3(trx, notice, "doorbell_read", { doorbell: `N${String(notice.id)}` }, input.at);
8199
- const item = await trx.selectFrom("operator_item").select("id").where("item_key", "=", exhaustedItemKey(notice)).where("cleared_at", "is", null).executeTakeFirst();
8200
- if (item !== void 0) await clearItem(trx, item.id, input.at);
8201
- }
8202
- return true;
8203
- }
8204
- /** Use the same current recipient rule when listing and acknowledging an inbox notice. */
8205
- async function notificationAddressedTo(trx, n, actor) {
8206
- const parsed = parseActorId(actor);
8207
- if (parsed?.actor !== "agent") return false;
8208
- 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();
8209
- const selectedIsLive = n.recipient_session !== null && await liveSession(trx, n.recipient_session) !== void 0;
8210
- 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;
8211
- }
8212
- async function closeBlockNotification(trx, blockId, at) {
8213
- 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();
8214
- for (const row of closed) {
8215
- const item = await trx.selectFrom("operator_item").select("id").where("item_key", "=", exhaustedItemKey(row)).where("cleared_at", "is", null).executeTakeFirst();
8216
- if (item !== void 0) await clearItem(trx, item.id, at);
8085
+ if (line !== null) item = await trx.updateTable("operator_item").set({ line_outbox_id: line }).where("id", "=", item.id).returningAll().executeTakeFirstOrThrow();
8217
8086
  }
8087
+ return item;
8218
8088
  }
8219
8089
  //#endregion
8220
8090
  //#region ../core/src/app/outbox.ts
@@ -8432,17 +8302,17 @@ async function blockPost(trx, row, payload, rule) {
8432
8302
  const taskId = "taskId" in payload && typeof payload.taskId === "number" ? payload.taskId : null;
8433
8303
  const blockId = "blockId" in payload && typeof payload.blockId === "number" ? payload.blockId : null;
8434
8304
  const task = taskId === null ? null : await trx.selectFrom("task").selectAll().where("id", "=", taskId).executeTakeFirstOrThrow();
8435
- await raiseItem(trx, {
8305
+ await raiseItemWith(trx, {
8436
8306
  itemKey: `secret-post:${createHash("sha256").update(row.dedupeKey).digest("hex")}`,
8437
8307
  kind: "post_blocked",
8438
8308
  text: `text on ${safeKey} not sent: looks like a secret (${rule}), read \`board task ${safeKey}\``,
8439
- url: task === null ? "" : taskUrl(task),
8309
+ url: task === null ? "" : taskUrl(task, scanConfig()),
8440
8310
  taskId,
8441
8311
  blockId,
8442
8312
  at: row.at,
8443
8313
  rule,
8444
8314
  source: row.kind
8445
- });
8315
+ }, enqueueFeedLine);
8446
8316
  }
8447
8317
  /**
8448
8318
  * Scans a stored gateway row's payload again before it is resent, with the rules used at
@@ -8618,126 +8488,34 @@ async function enqueueConversationClose(trx, input) {
8618
8488
  });
8619
8489
  }
8620
8490
  if (open !== void 0 && open.state !== "done" && open.state !== "dead") await insertOutbox(trx, {
8621
- kind: "conversation.close",
8622
- dedupeKey: `conversation.close:block:${String(block.id)}:pending:${String(open.id)}`,
8623
- payload,
8624
- parent: tail?.state === "dead" ? open.id : tail?.id ?? open.id,
8625
- at: input.at
8626
- });
8627
- await trx.updateTable("conversation").set({
8628
- state: "closed",
8629
- closed_at: input.at.toISOString()
8630
- }).where("block_id", "=", input.blockId).where("state", "=", "open").execute();
8631
- }
8632
- async function enqueueInboundDoorbell(trx, input) {
8633
- await insertOutbox(trx, {
8634
- kind: "doorbell",
8635
- dedupeKey: input.key,
8636
- payload: {
8637
- session: input.session,
8638
- text: input.text
8639
- },
8640
- parent: null,
8641
- at: input.at
8642
- });
8643
- }
8644
- //#endregion
8645
- //#region ../core/src/app/feed.ts
8646
- const NO_FEED = /* @__PURE__ */ new Set([
8647
- "post_failed",
8648
- "answer_undelivered",
8649
- "transport_health"
8650
- ]);
8651
- /** Display label of a feed line with no task; not part of the line's identity. */
8652
- const TASKLESS_FEED_KEY = "spur-board";
8653
- async function journal$2(trx, item, kind, at, rule, actor = "system") {
8654
- const parsed = parseActorId(actor);
8655
- if (parsed === null) throw new Error("Invalid journal actor");
8656
- const task = item.task_id === null ? void 0 : await trx.selectFrom("task").select(["project"]).where("id", "=", item.task_id).executeTakeFirstOrThrow();
8657
- await trx.insertInto("event").values({
8658
- at: at.toISOString(),
8659
- project: task?.project ?? "_board",
8660
- task_id: item.task_id,
8661
- kind,
8662
- actor: parsed.actor,
8663
- actor_ref: parsed.actor === "agent" ? JSON.stringify(parsed.actorRef) : null,
8664
- payload: toJson(eventPayloadSchemas[kind], {
8665
- item: `I${String(item.id)}`,
8666
- ...kind === "from_you_raised" && rule !== void 0 ? { rule } : {}
8667
- }),
8668
- v: 1,
8669
- request_id: null
8670
- }).execute();
8671
- }
8672
- /** Kinds whose item has a retry action besides `delivery:<id>` (see `items.ts`). */
8673
- const RETRY_KINDS = /* @__PURE__ */ new Set([
8674
- "answer_undelivered",
8675
- "worker_not_reading",
8676
- "inbound_failure"
8677
- ]);
8678
- /** Every item line gets Close, after Retry when its kind has a retry action. */
8679
- function itemActions(item) {
8680
- const id = String(item.id);
8681
- const close = {
8682
- id: `item:${id}:close`,
8683
- label: "Close"
8684
- };
8685
- if (item.kind === "token_request") return [
8686
- {
8687
- id: `token:${id}:approve`,
8688
- label: "Approve"
8689
- },
8690
- {
8691
- id: `token:${id}:deny`,
8692
- label: "Deny"
8693
- },
8694
- close
8695
- ];
8696
- return item.item_key.startsWith("delivery:") || RETRY_KINDS.has(item.kind) ? [{
8697
- id: `item:${id}:retry`,
8698
- label: "Retry"
8699
- }, close] : [close];
8700
- }
8701
- /** Raise one item generation. A repeated raise of an active key is idempotent. */
8702
- async function raiseItem(trx, input) {
8703
- const active = await trx.selectFrom("operator_item").selectAll().where("item_key", "=", input.itemKey).where("cleared_at", "is", null).executeTakeFirst();
8704
- if (active !== void 0) return active;
8705
- const previous = await trx.selectFrom("operator_item").select("raise_no").where("item_key", "=", input.itemKey).orderBy("raise_no", "desc").executeTakeFirst();
8706
- let item = await trx.insertInto("operator_item").values({
8707
- item_key: input.itemKey,
8708
- raise_no: (previous?.raise_no ?? 0) + 1,
8709
- kind: input.kind,
8710
- text: input.text,
8711
- url: input.url,
8712
- task_id: input.taskId,
8713
- block_id: input.blockId,
8714
- raised_at: input.at.toISOString(),
8715
- cleared_at: null,
8716
- line_outbox_id: null,
8717
- fingerprint: input.fingerprint ?? null,
8718
- fact_at: input.factAt ?? null,
8719
- source: input.source ?? null,
8720
- priority: input.priority ?? null,
8721
- inbound_event_json: null
8722
- }).returningAll().executeTakeFirstOrThrow();
8723
- await journal$2(trx, item, "from_you_raised", input.at, input.rule);
8724
- if (!NO_FEED.has(item.kind) && !input.suppressFeed) {
8725
- const key = (item.task_id === null ? null : await trx.selectFrom("task").select("key").where("id", "=", item.task_id).executeTakeFirstOrThrow())?.key ?? TASKLESS_FEED_KEY;
8726
- const line = await enqueueFeedLine(trx, {
8727
- itemId: item.id,
8728
- itemKey: item.item_key,
8729
- raise: item.raise_no,
8730
- key,
8731
- text: item.text,
8732
- title: `${key}: ${item.text}`,
8733
- url: item.url,
8734
- taskId: item.task_id,
8735
- actions: itemActions(item),
8736
- at: input.at
8737
- });
8738
- if (line !== null) item = await trx.updateTable("operator_item").set({ line_outbox_id: line }).where("id", "=", item.id).returningAll().executeTakeFirstOrThrow();
8739
- }
8740
- return item;
8491
+ kind: "conversation.close",
8492
+ dedupeKey: `conversation.close:block:${String(block.id)}:pending:${String(open.id)}`,
8493
+ payload,
8494
+ parent: tail?.state === "dead" ? open.id : tail?.id ?? open.id,
8495
+ at: input.at
8496
+ });
8497
+ await trx.updateTable("conversation").set({
8498
+ state: "closed",
8499
+ closed_at: input.at.toISOString()
8500
+ }).where("block_id", "=", input.blockId).where("state", "=", "open").execute();
8501
+ }
8502
+ async function enqueueInboundDoorbell(trx, input) {
8503
+ await insertOutbox(trx, {
8504
+ kind: "doorbell",
8505
+ dedupeKey: input.key,
8506
+ payload: {
8507
+ session: input.session,
8508
+ text: input.text
8509
+ },
8510
+ parent: null,
8511
+ at: input.at
8512
+ });
8513
+ }
8514
+ //#endregion
8515
+ //#region ../core/src/app/feed.ts
8516
+ /** Raise one item generation. A repeated raise of an active key is idempotent. */
8517
+ async function raiseItem(trx, input) {
8518
+ return raiseItemWith(trx, input, enqueueFeedLine);
8741
8519
  }
8742
8520
  /**
8743
8521
  * Clear an item once; the edit waits for its line and is cancelled with a stale pending line.
@@ -8746,14 +8524,14 @@ async function raiseItem(trx, input) {
8746
8524
  async function clearItem(trx, itemId, at, actor = "system") {
8747
8525
  if ((await trx.selectFrom("operator_item").selectAll().where("id", "=", itemId).executeTakeFirstOrThrow()).cleared_at !== null) return;
8748
8526
  const item = await trx.updateTable("operator_item").set({ cleared_at: at.toISOString() }).where("id", "=", itemId).returningAll().executeTakeFirstOrThrow();
8749
- await journal$2(trx, item, "from_you_cleared", at, void 0, actor);
8527
+ await journal$3(trx, item, "from_you_cleared", at, void 0, actor);
8750
8528
  if (item.line_outbox_id === null) return;
8751
8529
  const task = item.task_id === null ? null : await trx.selectFrom("task").select("key").where("id", "=", item.task_id).executeTakeFirstOrThrow();
8752
8530
  await enqueueFeedEdit(trx, {
8753
8531
  itemKey: item.item_key,
8754
8532
  raise: item.raise_no,
8755
8533
  lineId: item.line_outbox_id,
8756
- key: task?.key ?? TASKLESS_FEED_KEY,
8534
+ key: task?.key ?? "spur-board",
8757
8535
  taskId: item.task_id,
8758
8536
  at
8759
8537
  });
@@ -8788,10 +8566,10 @@ async function expireToken(trx, row, at) {
8788
8566
  await clearItem(trx, row.item_id, at);
8789
8567
  }
8790
8568
  /** Register a hash and its approval item together. The raw file secret never reaches this app. */
8791
- async function requestToken(store, input, at) {
8569
+ async function requestToken(store, config, input, at) {
8792
8570
  if (!/^[0-9a-f]{64}$/.test(input.hash) || input.name.trim() === "" || input.folder.trim() === "") throw new CommandError("usage", "Provide a name, folder and SHA-256 token hash.");
8793
8571
  const expiresAt = new Date(at.getTime() + REQUEST_LIFETIME_MS).toISOString();
8794
- return scanTransaction(store, async (trx) => {
8572
+ return scanTransaction(store, config, async (trx) => {
8795
8573
  const existing = await trx.selectFrom("operator_token").selectAll().where("name", "=", input.name).executeTakeFirst();
8796
8574
  const status = existing === void 0 ? void 0 : effectiveStatus(existing, at);
8797
8575
  if (status === "pending" || status === "approved" || status === "revoked") throw new CommandError("usage", `Token name ${input.name} is taken; choose another name (see \`board token list\`).`);
@@ -8854,10 +8632,10 @@ async function decideTokenInTransaction(trx, itemId, decision, at) {
8854
8632
  };
8855
8633
  }
8856
8634
  /** Clear unreviewed requests even when no approval button is pressed. */
8857
- async function expirePendingTokens(store, at) {
8635
+ async function expirePendingTokens(store, config, at) {
8858
8636
  const expiresAt = at.toISOString();
8859
8637
  if (await store.db.selectFrom("operator_token").select("id").where("status", "=", "pending").where("expires_at", "<=", expiresAt).executeTakeFirst() === void 0) return 0;
8860
- return scanTransaction(store, async (trx) => {
8638
+ return scanTransaction(store, config, async (trx) => {
8861
8639
  const rows = await trx.selectFrom("operator_token").select([
8862
8640
  "id",
8863
8641
  "name",
@@ -9071,7 +8849,7 @@ async function createApiServer(options) {
9071
8849
  if (!options.ready()) throw new CommandError("starting", "Wait until the daemon is ready.");
9072
8850
  const parsed = tokenRequestSchema.safeParse(request.body);
9073
8851
  if (!parsed.success) throw new CommandError("usage", "Provide a name, folder, host and token hash.");
9074
- const result = await requestToken(options.store, parsed.data, new Date(options.clock.now()));
8852
+ const result = await requestToken(options.store, options.config, parsed.data, new Date(options.clock.now()));
9075
8853
  return reply.send(successEnvelopeSchema.parse({
9076
8854
  ok: true,
9077
8855
  requestId: request.id,
@@ -9179,6 +8957,239 @@ function acknowledgeComment(revision, requested) {
9179
8957
  return requested;
9180
8958
  }
9181
8959
  //#endregion
8960
+ //#region ../core/src/app/doorbells.ts
8961
+ async function journal$2(trx, notification, kind, payload, at) {
8962
+ const task = await trx.selectFrom("task").select("project").where("id", "=", notification.task_id).executeTakeFirstOrThrow();
8963
+ await trx.insertInto("event").values({
8964
+ at: at.toISOString(),
8965
+ project: task.project,
8966
+ task_id: notification.task_id,
8967
+ kind,
8968
+ actor: "system",
8969
+ actor_ref: null,
8970
+ payload: toJson(eventPayloadSchemas[kind], payload),
8971
+ v: 1,
8972
+ request_id: null
8973
+ }).execute();
8974
+ }
8975
+ /** Register a worker-addressed block without manufacturing a comment. */
8976
+ async function registerBlockNotification(trx, block, at) {
8977
+ if (block.addressee_role !== "worker") return;
8978
+ await trx.insertInto("notification").values({
8979
+ source_key: `block:${String(block.id)}:worker`,
8980
+ kind: "block",
8981
+ task_id: block.task_id,
8982
+ block_id: block.id,
8983
+ comment_id: null,
8984
+ revision: null,
8985
+ role: "worker",
8986
+ author_session: null,
8987
+ recipient_session: null,
8988
+ next_at: at.toISOString(),
8989
+ last_outbox_id: null,
8990
+ acked_at: null,
8991
+ exhausted_at: null,
8992
+ created_at: at.toISOString()
8993
+ }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
8994
+ }
8995
+ /** Register an answer or clarification for the original author and its task role. */
8996
+ async function registerAnswerNotification(trx, input) {
8997
+ if (input.authorRole !== "worker") return;
8998
+ const parsed = parseActorId(input.block.author);
8999
+ if (parsed?.actor !== "agent") return;
9000
+ await trx.insertInto("notification").values({
9001
+ source_key: `comment:${String(input.commentId)}:${String(input.revision)}`,
9002
+ kind: "answer",
9003
+ task_id: input.block.task_id,
9004
+ block_id: input.block.id,
9005
+ comment_id: input.commentId,
9006
+ revision: input.revision,
9007
+ role: "worker",
9008
+ author_session: parsed.actorRef.session,
9009
+ recipient_session: null,
9010
+ next_at: input.at.toISOString(),
9011
+ last_outbox_id: null,
9012
+ acked_at: null,
9013
+ exhausted_at: null,
9014
+ created_at: input.at.toISOString()
9015
+ }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
9016
+ }
9017
+ async function liveSession(trx, id) {
9018
+ const row = await trx.selectFrom("session_snapshot").selectAll().where("id", "=", id).executeTakeFirst();
9019
+ return row?.ended_at === null && row.state !== "killed" && row.state !== "stopped" ? row : void 0;
9020
+ }
9021
+ /** Select the current live recipient for a semantic notification. */
9022
+ async function selectNotificationRecipient(trx, n) {
9023
+ if (n.author_session !== null) {
9024
+ const author = await liveSession(trx, n.author_session);
9025
+ if (author !== void 0) return author;
9026
+ }
9027
+ 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();
9028
+ for (const link of links) {
9029
+ if (link.session_id === null) continue;
9030
+ const session = await liveSession(trx, link.session_id);
9031
+ if (session !== void 0) return session;
9032
+ }
9033
+ }
9034
+ /** The operator item kind raised when a notification's rings are exhausted. */
9035
+ function exhaustedItemKind(n) {
9036
+ return n.kind === "answer" ? "answer_undelivered" : "worker_not_reading";
9037
+ }
9038
+ /** The operator item key raised when a notification's rings are exhausted. */
9039
+ function exhaustedItemKey(n) {
9040
+ return `${exhaustedItemKind(n)}:${n.source_key}`;
9041
+ }
9042
+ /**
9043
+ * Restart an exhausted, unacknowledged ring series at `at`. The recipient and last row stay, so
9044
+ * the next reconcile rings the same session under the next series key.
9045
+ */
9046
+ async function restartNotification(trx, sourceKey, at) {
9047
+ if (await trx.updateTable("notification").set({
9048
+ rings: 0,
9049
+ exhausted_at: null,
9050
+ next_at: at.toISOString()
9051
+ }).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.");
9052
+ }
9053
+ /** Reconcile due semantic notifications in the sender's claim transaction. */
9054
+ async function reconcileDoorbells(trx, at, config) {
9055
+ const due = await trx.selectFrom("notification").innerJoin("task", "task.id", "notification.task_id").selectAll("notification").where("task.membership", "!=", "archived").where("notification.acked_at", "is", null).where("notification.exhausted_at", "is", null).where("notification.next_at", "<=", at.toISOString()).orderBy("notification.id").execute();
9056
+ for (const n of due) {
9057
+ const session = await selectNotificationRecipient(trx, n);
9058
+ if (session === void 0) {
9059
+ if (n.recipient_session !== null) await trx.updateTable("notification").set({
9060
+ recipient_session: null,
9061
+ rings: 0,
9062
+ last_outbox_id: null
9063
+ }).where("id", "=", n.id).execute();
9064
+ continue;
9065
+ }
9066
+ if (session.state === "working") continue;
9067
+ let rings = n.rings;
9068
+ let lastOutbox = n.last_outbox_id;
9069
+ if (session.id !== n.recipient_session) {
9070
+ if (lastOutbox !== null) await trx.updateTable("outbox").set({
9071
+ state: "dead",
9072
+ last_error: "recipient changed"
9073
+ }).where("id", "=", lastOutbox).where("state", "=", "pending").execute();
9074
+ rings = 0;
9075
+ lastOutbox = null;
9076
+ await trx.updateTable("notification").set({
9077
+ recipient_session: session.id,
9078
+ rings: 0,
9079
+ last_outbox_id: null
9080
+ }).where("id", "=", n.id).execute();
9081
+ }
9082
+ if (lastOutbox !== null) {
9083
+ const row = await trx.selectFrom("outbox").select("state").where("id", "=", lastOutbox).executeTakeFirst();
9084
+ if (row?.state === "pending" || row?.state === "in_flight") continue;
9085
+ }
9086
+ const task = await trx.selectFrom("task").selectAll().where("id", "=", n.task_id).executeTakeFirstOrThrow();
9087
+ const itemKey = exhaustedItemKey(n);
9088
+ if (rings >= 3) {
9089
+ await raiseItem(trx, {
9090
+ itemKey,
9091
+ kind: exhaustedItemKind(n),
9092
+ 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}`,
9093
+ url: taskUrl(task, config),
9094
+ taskId: task.id,
9095
+ blockId: n.block_id,
9096
+ at
9097
+ });
9098
+ await trx.updateTable("notification").set({ exhausted_at: at.toISOString() }).where("id", "=", n.id).execute();
9099
+ await journal$2(trx, n, "doorbell_undelivered", {
9100
+ doorbell: `N${String(n.id)}`,
9101
+ reason: "unanswered"
9102
+ }, at);
9103
+ continue;
9104
+ }
9105
+ const raised = await trx.selectFrom("operator_item").select((eb) => eb.fn.max("raise_no").as("series")).where("item_key", "=", itemKey).executeTakeFirst();
9106
+ const archived = await trx.selectFrom("event").select((eb) => eb.fn.countAll().as("count")).where("task_id", "=", n.task_id).where("kind", "=", "task_archived").executeTakeFirst();
9107
+ const ring = rings + 1;
9108
+ const text = `${task.key} block B${String(n.block_id)}: check board inbox (N${String(n.id)}-${String(ring)})`;
9109
+ const outboxId = await enqueueDoorbell(trx, {
9110
+ notificationId: n.id,
9111
+ ring,
9112
+ session: session.id,
9113
+ text,
9114
+ at,
9115
+ series: raised?.series ?? 0,
9116
+ archives: archived?.count ?? 0
9117
+ });
9118
+ await trx.updateTable("notification").set({ last_outbox_id: outboxId }).where("id", "=", n.id).execute();
9119
+ }
9120
+ }
9121
+ /** Count one confirmed Spur send, regardless of transport attempts for its outbox row. */
9122
+ async function recordRingDelivery(trx, notificationId, ring, session, at, config) {
9123
+ const n = await trx.selectFrom("notification").selectAll().where("id", "=", notificationId).executeTakeFirst();
9124
+ if (n === void 0 || n.acked_at !== null || n.recipient_session !== session || n.rings >= ring) return;
9125
+ const pauses = [
9126
+ config.doorbells.firstRetryMs,
9127
+ config.doorbells.secondRetryMs,
9128
+ config.doorbells.unansweredAfterMs
9129
+ ];
9130
+ await trx.updateTable("notification").set({
9131
+ rings: ring,
9132
+ next_at: new Date(at.getTime() + (pauses[ring - 1] ?? 0)).toISOString()
9133
+ }).where("id", "=", notificationId).execute();
9134
+ await journal$2(trx, n, "doorbell_rung", {
9135
+ doorbell: `N${String(n.id)}`,
9136
+ addressee: n.role,
9137
+ attempt: ring
9138
+ }, at);
9139
+ }
9140
+ /** Confirm that a queued ring still belongs to a live, idle, unread recipient. */
9141
+ async function ringStillCurrent(trx, notificationId, sessionId) {
9142
+ const n = await trx.selectFrom("notification").selectAll().where("id", "=", notificationId).executeTakeFirst();
9143
+ if (n === void 0 || n.acked_at !== null || n.exhausted_at !== null || n.recipient_session !== sessionId) return "dead";
9144
+ const session = await selectNotificationRecipient(trx, n);
9145
+ if (session?.id !== sessionId) return "dead";
9146
+ return session.state === "working" ? "defer" : "send";
9147
+ }
9148
+ /**
9149
+ * The task of a ring: through its notification, or for an inbound author ring (no notification)
9150
+ * through the comment in its `doorbell:comment:<id>:` key. Archive kills only unclaimed rings;
9151
+ * the sender drops a claimed one of an archived task before its send starts.
9152
+ */
9153
+ async function ringTask(trx, notificationId, dedupeKey) {
9154
+ const commentId = /^doorbell:comment:(\d+):/.exec(dedupeKey)?.[1];
9155
+ if (notificationId === void 0 && commentId === void 0) return void 0;
9156
+ const owner = notificationId !== void 0 ? trx.selectFrom("notification").select("task_id").where("id", "=", notificationId) : trx.selectFrom("comment").select("task_id").where("id", "=", Number(commentId));
9157
+ return trx.selectFrom("task").selectAll().where("id", "in", owner).executeTakeFirst();
9158
+ }
9159
+ /** Stop notifications acknowledged by the addressed session. */
9160
+ async function acknowledgeNotification(trx, input) {
9161
+ let query = trx.selectFrom("notification").selectAll().where("acked_at", "is", null);
9162
+ if (input.blockId !== void 0) query = query.where("block_id", "=", input.blockId).where("kind", "=", "block");
9163
+ else if (input.commentId !== void 0) query = query.where("comment_id", "=", input.commentId).where("kind", "=", "answer");
9164
+ else return false;
9165
+ const notices = await query.orderBy("id", "desc").execute();
9166
+ const n = notices[0];
9167
+ if (n === void 0) return false;
9168
+ if (!await notificationAddressedTo(trx, n, input.actor)) throw new CommandError("forbidden", "Only the addressed task role can acknowledge.");
9169
+ for (const notice of notices) {
9170
+ await trx.updateTable("notification").set({ acked_at: input.at.toISOString() }).where("id", "=", notice.id).execute();
9171
+ await journal$2(trx, notice, "doorbell_read", { doorbell: `N${String(notice.id)}` }, input.at);
9172
+ const item = await trx.selectFrom("operator_item").select("id").where("item_key", "=", exhaustedItemKey(notice)).where("cleared_at", "is", null).executeTakeFirst();
9173
+ if (item !== void 0) await clearItem(trx, item.id, input.at);
9174
+ }
9175
+ return true;
9176
+ }
9177
+ /** Use the same current recipient rule when listing and acknowledging an inbox notice. */
9178
+ async function notificationAddressedTo(trx, n, actor) {
9179
+ const parsed = parseActorId(actor);
9180
+ if (parsed?.actor !== "agent") return false;
9181
+ 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();
9182
+ const selectedIsLive = n.recipient_session !== null && await liveSession(trx, n.recipient_session) !== void 0;
9183
+ 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;
9184
+ }
9185
+ async function closeBlockNotification(trx, blockId, at) {
9186
+ 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();
9187
+ for (const row of closed) {
9188
+ const item = await trx.selectFrom("operator_item").select("id").where("item_key", "=", exhaustedItemKey(row)).where("cleared_at", "is", null).executeTakeFirst();
9189
+ if (item !== void 0) await clearItem(trx, item.id, at);
9190
+ }
9191
+ }
9192
+ //#endregion
9182
9193
  //#region ../core/src/app/blocks.ts
9183
9194
  const actorRefSchema$1 = z.strictObject({
9184
9195
  project: z.string().min(1),
@@ -10370,28 +10381,28 @@ function createSender(options) {
10370
10381
  async function runTick(signal) {
10371
10382
  if (signal?.aborted) return;
10372
10383
  const claimedAt = now().getTime();
10373
- const { claims, ranThreshold } = await scanTransaction(store, (trx) => claim(trx, claimedAt));
10384
+ const { claims, ranThreshold } = await scanTransaction(store, options.config, (trx) => claim(trx, claimedAt));
10374
10385
  if (ranThreshold) downRecorded = true;
10375
10386
  for (const [i, c] of claims.entries()) {
10376
10387
  if (signal?.aborted) {
10377
10388
  const ids = claims.slice(i).map((c) => c.id);
10378
- await scanTransaction(store, (trx) => trx.updateTable("outbox").set((eb) => ({
10389
+ await scanTransaction(store, options.config, (trx) => trx.updateTable("outbox").set((eb) => ({
10379
10390
  state: "pending",
10380
10391
  attempts: eb("attempts", "-", 1)
10381
10392
  })).where("id", "in", ids).where("state", "=", "in_flight").execute());
10382
10393
  return;
10383
10394
  }
10384
- const started = await scanTransaction(store, (trx) => start(trx, c));
10395
+ const started = await scanTransaction(store, options.config, (trx) => start(trx, c));
10385
10396
  if (started.skip) continue;
10386
10397
  const { outcome, error } = await attempt(c, started.firstDeliveryAt);
10387
10398
  const at = now().getTime();
10388
- await scanTransaction(store, (trx) => record(trx, c, outcome, error, at, started.at));
10399
+ await scanTransaction(store, options.config, (trx) => record(trx, c, outcome, error, at, started.at));
10389
10400
  }
10390
10401
  }
10391
10402
  return {
10392
10403
  async recover() {
10393
10404
  const nowIso = now().toISOString();
10394
- const failed = await scanTransaction(store, async (trx) => {
10405
+ const failed = await scanTransaction(store, options.config, async (trx) => {
10395
10406
  const rows = await trx.selectFrom("outbox").select([
10396
10407
  "id",
10397
10408
  "kind",
@@ -10415,7 +10426,7 @@ function createSender(options) {
10415
10426
  });
10416
10427
  for (let i = 0; i < failed.length; i += RECOVER_BATCH) {
10417
10428
  const batch = failed.slice(i, i + RECOVER_BATCH);
10418
- await scanTransaction(store, (trx) => requeuePostFailed(trx, batch, nowIso));
10429
+ await scanTransaction(store, options.config, (trx) => requeuePostFailed(trx, batch, nowIso));
10419
10430
  }
10420
10431
  },
10421
10432
  tick(signal) {
@@ -10432,7 +10443,7 @@ function createSender(options) {
10432
10443
  downSince = void 0;
10433
10444
  downRecorded = false;
10434
10445
  if (gateway === void 0) return;
10435
- await scanTransaction(store, async (trx) => {
10446
+ await scanTransaction(store, options.config, async (trx) => {
10436
10447
  if ((await trx.deleteFrom("transport_health").where("gateway", "=", gatewayKind).where("reason", "=", "down").returning("space").execute()).length > 0) await syncTransportItem(trx, gatewayKind, at);
10437
10448
  });
10438
10449
  });
@@ -10587,6 +10598,10 @@ async function snapshot(trx, repo, number) {
10587
10598
  const row = await trx.selectFrom("pr_snapshot").select("detail").where(sql`lower(repo) = ${repo.toLowerCase()}`).where("number", "=", number).executeTakeFirst();
10588
10599
  return row === void 0 ? null : parseJson(prFactsSchema, row.detail);
10589
10600
  }
10601
+ async function sessionSnapshot(trx, id) {
10602
+ const row = await trx.selectFrom("session_snapshot").select("detail").where("id", "=", id).executeTakeFirst();
10603
+ return row === void 0 ? null : parseJson(sessionFactsSchema, row.detail);
10604
+ }
10590
10605
  async function existingLink(trx, taskId, input, ticket) {
10591
10606
  let query = trx.selectFrom("link").selectAll().where("task_id", "=", taskId);
10592
10607
  if (input.mode === "pr") {
@@ -10670,6 +10685,7 @@ async function run(trx, input, ctx, config, remove) {
10670
10685
  target
10671
10686
  };
10672
10687
  const role = input.mode === "session" ? current?.role ?? await sessionRole(trx, task.id) : null;
10688
+ const session = input.mode === "session" ? await sessionSnapshot(trx, input.session) : null;
10673
10689
  if (current === void 0) await trx.insertInto("link").values({
10674
10690
  task_id: task.id,
10675
10691
  entity: input.mode,
@@ -10698,12 +10714,14 @@ async function run(trx, input, ctx, config, remove) {
10698
10714
  pr: pr?.number ?? 0,
10699
10715
  state: "active",
10700
10716
  source: "manual",
10717
+ ...facts === null ? {} : { facts },
10701
10718
  reason: input.reason
10702
10719
  } : input.mode === "session" ? {
10703
10720
  entity: "session",
10704
10721
  session: input.session,
10705
10722
  role: role ?? "other",
10706
10723
  source: "manual",
10724
+ ...session === null ? {} : { facts: session },
10707
10725
  reason: input.reason
10708
10726
  } : {
10709
10727
  entity: "ticket",
@@ -11595,7 +11613,7 @@ async function updateTerminal(trx, config, taskId, at, completeSince, blind) {
11595
11613
  const complete = completeSince.get(source);
11596
11614
  return !blind.has(source) && complete !== void 0 && complete > (task.last_change_at ?? task.created_at);
11597
11615
  });
11598
- const terminal = merged || doneTicket && !hasOpen && githubComplete;
11616
+ const terminal = !hasOpen && (merged || doneTicket && githubComplete);
11599
11617
  await trx.updateTable("task").set({ terminal_at: terminal ? task.terminal_at ?? (merged ? at : task.last_change_at ?? at) : null }).where("id", "=", taskId).execute();
11600
11618
  }
11601
11619
  async function sourceState(trx, source, state, observedAt, cursor) {
@@ -12007,7 +12025,7 @@ function createObservationCore(deps) {
12007
12025
  },
12008
12026
  async observe(source, observation) {
12009
12027
  const { batch } = observation;
12010
- await scanTransaction(store, async (trx) => {
12028
+ await scanTransaction(store, config, async (trx) => {
12011
12029
  await sourceState(trx, source, observation.state, batch.observedAt, batch.cursor);
12012
12030
  for (const outcome of observation.outcomes) {
12013
12031
  const answer = batch.entities.find((entity) => refKey(entity.ref) === refKey(outcome.ref));
@@ -12112,13 +12130,13 @@ function createObservationCore(deps) {
12112
12130
  if (observation.effectiveComplete) completeSince.set(source, batch.observedAt);
12113
12131
  },
12114
12132
  reportSourceState(source, state) {
12115
- return scanTransaction(store, async (trx) => {
12133
+ return scanTransaction(store, config, async (trx) => {
12116
12134
  await sourceState(trx, source, state);
12117
12135
  await reconcileItems(trx, config, clock.now(), completeSince.has("spur"));
12118
12136
  });
12119
12137
  },
12120
12138
  notice(kind, value) {
12121
- return scanTransaction(store, async (trx) => {
12139
+ return scanTransaction(store, config, async (trx) => {
12122
12140
  const key = `spur-notice:${kind}:${value}`;
12123
12141
  if (await trx.selectFrom("meta").select("key").where("key", "=", key).executeTakeFirst() !== void 0) return;
12124
12142
  await trx.insertInto("meta").values({
@@ -12177,7 +12195,7 @@ async function tickBoard(deps) {
12177
12195
  const now = clock.now();
12178
12196
  const at = new Date(now).toISOString();
12179
12197
  const slot = new Date(lastArchiveSlot(now, config)).toISOString();
12180
- await scanTransaction(store, async (trx) => {
12198
+ await scanTransaction(store, config, async (trx) => {
12181
12199
  const sourceStates = await trx.selectFrom("source_state").select(["source", "blind_reason"]).execute();
12182
12200
  const blind = new Set(sourceStates.filter((source) => source.blind_reason !== null).map((source) => source.source));
12183
12201
  const tasks = await trx.selectFrom("task").selectAll().where("membership", "!=", "archived").execute();
@@ -12759,7 +12777,7 @@ function createInbound(input) {
12759
12777
  });
12760
12778
  }
12761
12779
  async function recordFailure(event, error, at) {
12762
- await scanTransaction(store, async (trx) => {
12780
+ await scanTransaction(store, config, async (trx) => {
12763
12781
  const context = await taskContext(trx, event, gateway.kind);
12764
12782
  await journal(trx, {
12765
12783
  kind: "inbound_failed",
@@ -12790,7 +12808,7 @@ function createInbound(input) {
12790
12808
  let response = "not allowed";
12791
12809
  if (event.sourceSpace === "feed") try {
12792
12810
  const at = new Date(clock.now()).toISOString();
12793
- response = (await scanTransaction(store, (trx) => decideToken(trx, event.dedupeKey, token, at)))?.response ?? "not available yet";
12811
+ response = (await scanTransaction(store, config, (trx) => decideToken(trx, event.dedupeKey, token, at)))?.response ?? "not available yet";
12794
12812
  } catch (error) {
12795
12813
  if (!(error instanceof CommandError)) await recordFailure(event, error, new Date(clock.now()).toISOString());
12796
12814
  response = error instanceof CommandError ? error.hint : "not available yet";
@@ -12838,7 +12856,7 @@ function createInbound(input) {
12838
12856
  const at = new Date(clock.now()).toISOString();
12839
12857
  const actor = event.kind === "message_deleted" || event.author === config.operator.slack ? "operator" : "system";
12840
12858
  try {
12841
- const result = await scanTransaction(store, (trx) => replayOperation(trx, {
12859
+ const result = await scanTransaction(store, config, (trx) => replayOperation(trx, {
12842
12860
  actor,
12843
12861
  key: event.dedupeKey,
12844
12862
  operation: operationId(event),
@@ -12856,7 +12874,7 @@ function createInbound(input) {
12856
12874
  }
12857
12875
  async function applyGap(event) {
12858
12876
  const at = new Date(clock.now()).toISOString();
12859
- await scanTransaction(store, async (trx) => {
12877
+ await scanTransaction(store, config, async (trx) => {
12860
12878
  const context = await taskContext(trx, event, gateway.kind);
12861
12879
  const conversation = event.conversation === void 0 ? void 0 : await trx.selectFrom("conversation").select(["root_message_ref"]).where("gateway", "=", gateway.kind).where("ref", "=", event.conversation).executeTakeFirst();
12862
12880
  const opened = conversation === void 0 ? void 0 : await trx.selectFrom("outbox").select("external_ref").where("kind", "=", "conversation.open").where("state", "=", "done").where(sql`json_extract(external_ref, '$.message')`, "=", conversation.root_message_ref).orderBy("id", "desc").executeTakeFirst();
@@ -12909,7 +12927,7 @@ function createInbound(input) {
12909
12927
  retryStored(itemId) {
12910
12928
  return serial(async () => {
12911
12929
  const at = new Date(clock.now()).toISOString();
12912
- await scanTransaction(store, async (trx) => {
12930
+ await scanTransaction(store, config, async (trx) => {
12913
12931
  await reapply(trx, itemId, at);
12914
12932
  await clearItem(trx, itemId, new Date(at));
12915
12933
  });
@@ -16893,7 +16911,7 @@ function createOutboxModule(ctx, gateway, options = {}) {
16893
16911
  const tick = () => {
16894
16912
  if (stopped || signal?.aborted) return active;
16895
16913
  active = active.then(() => ctx.logCall("outbox.tick", async () => {
16896
- await expirePendingTokens(ctx.store, new Date(ctx.clock.now()));
16914
+ await expirePendingTokens(ctx.store, ctx.config, new Date(ctx.clock.now()));
16897
16915
  if (!signal?.aborted) await sender.tick(signal);
16898
16916
  })).catch(() => void 0);
16899
16917
  return active;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spur-board",
3
- "version": "0.16.0",
3
+ "version": "0.16.2",
4
4
  "license": "MIT",
5
5
  "engines": {
6
6
  "node": "^24.12.0 || ^26.0.0"