spur-board 0.50.0 → 0.51.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 { $ as configSchema, A as parseRingMarker, B as parseRef$1, C as userIdSchema, D as SESSION_HEALTH_STATES, E as REVIEW_STATES, F as ticketFactsSchema, H as ERRORS, I as actorIdSchema, K as ok, L as encodeActorId, M as prRefSchema, N as ringMarker, O as SESSION_STATUSES, P as sessionFactsSchema, Q as RESERVED_PROJECT, R as errorCodeOf, S as messageRefSchema, T as eventPayloadSchemas, U as err, V as taskKeySchema, Y as DEFAULT_LINK, Z as DEFAULT_SLACK_COMMAND, a as BOARD_TICK_MS, b as inboundEventSchema, c as batchSchema, d as buildCatalogSnapshot, et as plainHttpAllowed, f as roleCanUseOperation, h as renderHttpProblem, i as tokenRequestSchema, it as SLACK_BOT_SCOPES, j as prFactsSchema, k as isExternalAuthor, l as entityRefSchema, m as turnHandedSchema, n as TOKEN_REQUEST_LIMITS, nt as COLUMN_IDS, p as OPERATIONS, q as successEnvelopeSchema, r as requestHashOf, rt as DISPATCHER_MODES, s as AdapterError, t as assertNever, tt as requiredSecretKeys, u as sourceCursorSchema, v as SPACE_IDS, w as EVENT_KINDS, x as interactionRefSchema, y as conversationRefSchema, z as parseActorId } from "./src-CDr8R3sf.mjs";
1
+ import { $ as configSchema, A as parseRingMarker, B as parseRef$1, C as userIdSchema, D as SESSION_HEALTH_STATES, E as REVIEW_STATES, F as ticketFactsSchema, H as ERRORS, I as actorIdSchema, K as ok, L as encodeActorId, M as prRefSchema, N as ringMarker, O as SESSION_STATUSES, P as sessionFactsSchema, Q as RESERVED_PROJECT, R as errorCodeOf, S as messageRefSchema, T as eventPayloadSchemas, U as err, V as taskKeySchema, Y as DEFAULT_LINK, Z as DEFAULT_SLACK_COMMAND, a as BOARD_TICK_MS, b as inboundEventSchema, c as batchSchema, d as buildCatalogSnapshot, et as plainHttpAllowed, f as roleCanUseOperation, h as renderHttpProblem, i as tokenRequestSchema, it as SLACK_BOT_SCOPES, j as prFactsSchema, k as isExternalAuthor, l as entityRefSchema, m as turnHandedSchema, n as TOKEN_REQUEST_LIMITS, nt as COLUMN_IDS, p as OPERATIONS, q as successEnvelopeSchema, r as requestHashOf, rt as DISPATCHER_MODES, s as AdapterError, t as assertNever, tt as requiredSecretKeys, u as sourceCursorSchema, v as SPACE_IDS, w as EVENT_KINDS, x as interactionRefSchema, y as conversationRefSchema, z as parseActorId } from "./src-B5vMuqoD.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { chmodSync, closeSync, existsSync, fchmodSync, fstatSync, fsyncSync, ftruncateSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeSync } from "node:fs";
@@ -7985,6 +7985,16 @@ async function taskPr(db, taskId) {
7985
7985
  open: link.pr_open === 1
7986
7986
  };
7987
7987
  }
7988
+ /** A PR snapshot's facts, or null when the detail is missing or unreadable. */
7989
+ function parsePr(detail) {
7990
+ if (detail === void 0) return null;
7991
+ try {
7992
+ const parsed = prFactsSchema.safeParse(JSON.parse(detail));
7993
+ return parsed.success ? parsed.data : null;
7994
+ } catch {
7995
+ return null;
7996
+ }
7997
+ }
7988
7998
  /** The project whose tracker or repo source wrote an observation. */
7989
7999
  function projectForSource(config, source) {
7990
8000
  return config.projects.find((project) => source === trackerSource(project) || project.repos.some((repo) => source === `github:${project.id}:${repo.toLowerCase()}`));
@@ -8414,7 +8424,8 @@ const ITEM_KINDS = [
8414
8424
  "worker_ended",
8415
8425
  "turn",
8416
8426
  "anomaly",
8417
- "cycle_limit"
8427
+ "cycle_limit",
8428
+ "course_check"
8418
8429
  ];
8419
8430
  const ITEM_POLICY = {
8420
8431
  token_request: {
@@ -8531,6 +8542,18 @@ const ITEM_POLICY = {
8531
8542
  buttons: "item",
8532
8543
  reconciled: false,
8533
8544
  block: true
8545
+ },
8546
+ /**
8547
+ * A task whose returns from a column reached its course check; the answer to its block, sent to
8548
+ * the curator or the operator, resets it.
8549
+ */
8550
+ course_check: {
8551
+ retry: "none",
8552
+ feed: false,
8553
+ priority: 4,
8554
+ buttons: "item",
8555
+ reconciled: false,
8556
+ block: true
8534
8557
  }
8535
8558
  };
8536
8559
  /** Guards a stored kind: the column is free text and old or hand-written rows may hold others. */
@@ -8724,7 +8747,9 @@ const doorbellPayload = z.strictObject({
8724
8747
  session: z.string().min(1),
8725
8748
  text: z.string(),
8726
8749
  notificationId: id.optional(),
8727
- ring: z.int().min(1).max(3).optional()
8750
+ ring: z.int().min(1).max(3).optional(),
8751
+ /** When a skill reload message was queued; rings never carry it. */
8752
+ queuedAt: z.iso.datetime().optional()
8728
8753
  });
8729
8754
  /** A row's kind with its parsed payload. */
8730
8755
  const outboxBodySchema = z.discriminatedUnion("kind", [
@@ -8800,6 +8825,29 @@ async function enqueueDoorbell(trx, input) {
8800
8825
  if (row.id === null) throw new Error("Doorbell cannot be blocked by gateway scan");
8801
8826
  return row.id;
8802
8827
  }
8828
+ /** The key holds no install time, so a session gets at most one reload message per version. */
8829
+ function skillReloadKey(version, session) {
8830
+ return `doorbell:skill-reload:${version}:${session}`;
8831
+ }
8832
+ /**
8833
+ * Asks one session to re-read the board skill after an install of `version`; `queuedAt` lets a
8834
+ * reader tell a message older than the latest install. Returns whether this call inserted it.
8835
+ */
8836
+ async function enqueueSkillReload(trx, input) {
8837
+ const row = await insertOutbox(trx, {
8838
+ kind: "doorbell",
8839
+ dedupeKey: skillReloadKey(input.version, input.session),
8840
+ payload: {
8841
+ session: input.session,
8842
+ text: input.text,
8843
+ queuedAt: input.at.toISOString()
8844
+ },
8845
+ parent: null,
8846
+ at: input.at
8847
+ });
8848
+ if (row.id === null) throw new Error("Doorbell cannot be blocked by gateway scan");
8849
+ return row.inserted;
8850
+ }
8803
8851
  /** The key includes the item raise, so a restart cannot add a second line. */
8804
8852
  async function enqueueFeedLine(trx, input) {
8805
8853
  return (await insertOutbox(trx, {
@@ -9163,6 +9211,61 @@ async function enqueueConversationClose(trx, input) {
9163
9211
  }).where("block_id", "=", input.blockId).where("state", "=", "open").execute();
9164
9212
  }
9165
9213
  //#endregion
9214
+ //#region ../core/src/app/block-thread.ts
9215
+ function orchestrator(config, task) {
9216
+ const name = config.projects.find((project) => project.id === task.project)?.columns.find((column) => column.id === task.column)?.orchestrator;
9217
+ return name === void 0 || name === "none" ? null : name;
9218
+ }
9219
+ function authorRole(config, task, actor) {
9220
+ if (actor === "operator") return "operator";
9221
+ const parsed = parseActorId(actor);
9222
+ if (parsed?.actor === "agent" && config.projects.some((project) => project.spurProjects.some((spur) => spur.name === parsed.actorRef.project && spur.role === "operator"))) return "operator";
9223
+ if (parsed?.actor !== "agent") return "worker";
9224
+ if (parsed.actorRef.project === orchestrator(config, task)) return `orchestrator:${task.column}`;
9225
+ return parsed.actorRef.project === curatorProject(config, task.project) ? "curator" : "worker";
9226
+ }
9227
+ function personaRole(role) {
9228
+ const addressee = parseAddressee(role);
9229
+ switch (addressee.kind) {
9230
+ case "operator": return "board";
9231
+ case "worker": return "worker";
9232
+ case "curator": return "curator";
9233
+ case "orchestrator": return "orchestrator";
9234
+ default: return assertNever(addressee);
9235
+ }
9236
+ }
9237
+ function personaFor(config, task, actor) {
9238
+ if (actor === "system") return {
9239
+ name: "board",
9240
+ role: "board"
9241
+ };
9242
+ if (actor === "operator") return {
9243
+ name: "operator",
9244
+ role: "board"
9245
+ };
9246
+ const parsed = parseActorId(actor);
9247
+ if (parsed?.actor !== "agent") throw new Error("Invalid actor");
9248
+ return {
9249
+ name: parsed.actorRef.project,
9250
+ role: personaRole(authorRole(config, task, actor))
9251
+ };
9252
+ }
9253
+ async function queueBlockOpen(trx, task, block, ctx, config) {
9254
+ if (authorRole(config, task, block.author) === "operator") return;
9255
+ const comments = await trx.selectFrom("comment").select(["id", "author"]).where("block_id", "=", block.id).orderBy("id").execute();
9256
+ if (await enqueueConversationOpen(trx, {
9257
+ blockId: block.id,
9258
+ commentId: comments[0]?.id ?? null,
9259
+ persona: personaFor(config, task, comments[0]?.author ?? block.author),
9260
+ at: new Date(ctx.at)
9261
+ }) === null) return;
9262
+ for (const comment of comments.slice(1)) await enqueueConversationReply(trx, {
9263
+ commentId: comment.id,
9264
+ persona: personaFor(config, task, comment.author),
9265
+ at: new Date(ctx.at)
9266
+ });
9267
+ }
9268
+ //#endregion
9166
9269
  //#region ../core/src/app/feed.ts
9167
9270
  /** The struck summary is capped so the edit stays one message part. */
9168
9271
  const MAX_SUMMARY = 500;
@@ -9351,682 +9454,151 @@ function tokenCardBody(card, config) {
9351
9454
  }];
9352
9455
  }
9353
9456
  //#endregion
9354
- //#region ../core/src/app/tokens.ts
9355
- const REQUEST_LIFETIME_MS = 900 * 1e3;
9356
- const MAX_PENDING_REQUESTS = 10;
9357
- /** Days an expired or denied request stays after its decision before the daily purge drops it. */
9358
- const TOKEN_REQUEST_RETENTION_DAYS = 7;
9359
- const DAY_MS$1 = 864e5;
9360
- /**
9361
- * Code-point caps that keep a legacy name or folder from overflowing a card, line or button. A
9362
- * messenger may escape a point to five characters; a card of all-escaped points still fits 2900.
9363
- */
9364
- const CARD_NAME = 64;
9365
- const CARD_FOLDER = 400;
9366
- const LIST_NAME = 64;
9367
- const LIST_FOLDER = 120;
9368
- const LABEL_NAME = 40;
9369
- /** Tokens in one token-list feed line that get a row and a Revoke button. */
9370
- const LIST_BUTTONS = 20;
9457
+ //#region ../core/src/app/doorbells.ts
9458
+ const UNANSWERED = "unanswered";
9459
+ async function journal$2(trx, notification, kind, payload, at) {
9460
+ await emit(trx, kind, (await trx.selectFrom("task").select("project").where("id", "=", notification.task_id).executeTakeFirstOrThrow()).project, notification.task_id, at.toISOString(), payload);
9461
+ }
9371
9462
  /**
9372
- * Escaped characters the rows and the `N more` line of a token list may take, each row counted
9373
- * with its newline and quote marks; the feed key fills the rest of one 2900-character part.
9463
+ * The one rule for who a board event rings. A doorbell means someone is waiting for your action,
9464
+ * so a party that caused the event, or that the Slack thread already reaches, gets no row.
9374
9465
  */
9375
- const LIST_TEXT = 2800;
9376
- /** Kept for the `N more` line. */
9377
- const LIST_MORE = 40;
9378
- /** An approved token's last use is written at most once per token per this interval. */
9379
- const TOKEN_USE_INTERVAL_MS = 5 * 6e4;
9380
- /** The longest attention line; the doctor fix limit is the same. */
9381
- const ATTENTION_LINE_MAX = 300;
9382
- /** The Revoke button of the token approved through item `itemId`, on its card or in a list. */
9383
- function revokeAction(itemId, name, label) {
9384
- return {
9385
- id: `token:${String(itemId)}:revoke`,
9386
- label,
9387
- confirm: `Revoke operator token ${capPoints(name, CARD_NAME)}? Calls with it fail at once.`
9388
- };
9389
- }
9390
- /** The card of token `row` approved at `approvedAt`, its name and folder capped. */
9391
- function cardOf(row, approvedAt) {
9392
- return {
9393
- name: capPoints(row.name, CARD_NAME),
9394
- folder: capPoints(row.folder, CARD_FOLDER),
9395
- createdAt: row.requested_at,
9396
- approvedAt
9397
- };
9398
- }
9399
- /** The length of `text` once a messenger escapes it: `&`, `<` and `>` take up to five characters. */
9400
- function escapedLength(text) {
9401
- return text.length + 4 * (text.match(/[&<>]/g)?.length ?? 0);
9466
+ async function applyDoorbellPolicy(trx, event, at) {
9467
+ switch (event.kind) {
9468
+ case "block_opened":
9469
+ if (!(parseActorId(event.block.author)?.actor === "agent" && event.block.addressee_role === event.authorRole)) await registerBlockNotification(trx, event.block, at);
9470
+ return;
9471
+ case "block_escalated":
9472
+ await closeBlockNotification(trx, event.block.id, at, "system");
9473
+ await registerBlockNotification(trx, event.block, at);
9474
+ return;
9475
+ case "answer":
9476
+ await registerAnswerNotification(trx, event, at);
9477
+ return;
9478
+ case "block_removed":
9479
+ await registerRemovedNotification(trx, event.block, at);
9480
+ return;
9481
+ case "block_closed_by_addressee":
9482
+ case "task_comment": return;
9483
+ default: assertNever(event);
9484
+ }
9402
9485
  }
9403
- function effectiveStatus(row, at) {
9404
- return row.status === "pending" && row.expires_at <= at.toISOString() ? "expired" : row.status;
9486
+ /** Register a block for its agent addressee; the Slack thread carries an operator's. */
9487
+ async function registerBlockNotification(trx, block, at) {
9488
+ if (block.addressee_role === "operator") return;
9489
+ await trx.insertInto("notification").values({
9490
+ source_key: `block:${String(block.id)}:${block.addressee_role}`,
9491
+ kind: "block",
9492
+ task_id: block.task_id,
9493
+ block_id: block.id,
9494
+ comment_id: null,
9495
+ revision: null,
9496
+ role: block.addressee_role,
9497
+ author_session: null,
9498
+ recipient_session: null,
9499
+ next_at: at.toISOString(),
9500
+ last_outbox_id: null,
9501
+ acked_at: null,
9502
+ exhausted_at: null,
9503
+ created_at: at.toISOString()
9504
+ }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
9405
9505
  }
9406
- async function journalToken(trx, kind, name, at) {
9407
- await emit(trx, kind, RESERVED_PROJECT, null, at.toISOString(), { name }, kind === "token_approved" || kind === "token_denied" || kind === "token_revoked" ? "operator" : "system");
9506
+ /**
9507
+ * Register an agent executor's turn. Core opens a turn, so no session authored it: the worker
9508
+ * or column orchestrator the board selects is rung.
9509
+ */
9510
+ async function registerTurnNotification(trx, turn, at) {
9511
+ await trx.insertInto("notification").values({
9512
+ source_key: `turn:${String(turn.id)}:${turn.role}`,
9513
+ kind: "turn",
9514
+ task_id: turn.task_id,
9515
+ block_id: null,
9516
+ turn_id: turn.id,
9517
+ comment_id: null,
9518
+ revision: null,
9519
+ role: turn.role,
9520
+ author_session: null,
9521
+ recipient_session: null,
9522
+ next_at: at.toISOString(),
9523
+ last_outbox_id: null,
9524
+ acked_at: null,
9525
+ exhausted_at: null,
9526
+ created_at: at.toISOString()
9527
+ }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
9408
9528
  }
9409
- /** Lapse one pending request: journal it once and clear its approval item. */
9410
- async function expireToken(trx, row, at) {
9411
- await trx.updateTable("operator_token").set({
9412
- status: "expired",
9413
- decided_at: at.toISOString()
9414
- }).where("id", "=", row.id).execute();
9415
- await journalToken(trx, "token_expired", row.name, at);
9416
- await clearItem(trx, row.item_id, at);
9529
+ /**
9530
+ * The key of the reminder to `session` about a turn it took at `takenAt`. The take time names the
9531
+ * ownership episode, so a session that loses the turn and takes it again gets a new reminder.
9532
+ */
9533
+ const turnReminderKey = (turnId, session, takenAt) => `turn:${String(turnId)}:reminder:${session}:${takenAt}`;
9534
+ const isTurnKind = (kind) => kind === "turn" || kind === "turn_reminder";
9535
+ /**
9536
+ * Whether a reminder was cancelled before it was ever sent, as a link removal does: it counts as
9537
+ * no reminder for its take, so a restored link reminds the holder again. A ring of it still
9538
+ * queued or in flight, or one that may have reached Spur (`uncertain`), keeps it: the outcome is
9539
+ * not known yet or the reminder may be out, and one reminder per take wins over a missed one.
9540
+ * Only rings the sender killed unsent leave it re-armable.
9541
+ */
9542
+ async function reminderCancelledUnsent(trx, n) {
9543
+ return await cancelledRingState(trx, n) === "unsent";
9417
9544
  }
9418
9545
  /**
9419
- * Lapses the pending request whose approval item is `itemId` once it has expired at `at`. The
9420
- * sender calls it before posting the approval line, so a late or failing sweep cannot post it.
9546
+ * The rings of a reminder acked before any delivery was counted: `unsent` when the sender killed
9547
+ * them all unsent, `maybe_out` when all are dead and one may have reached Spur, and null while one
9548
+ * is queued or in flight, or for a reminder that was delivered, exhausted or never acked. A
9549
+ * `maybe_out` reminder counts as delivered for the stuck-turn rule, so the one-ring limit does not
9550
+ * hide a stuck turn.
9421
9551
  */
9422
- async function expireTokenOfItem(trx, itemId, at) {
9423
- const row = await trx.selectFrom("operator_token").select([
9424
- "id",
9425
- "name",
9426
- "item_id"
9427
- ]).where("item_id", "=", itemId).where("status", "=", "pending").where("expires_at", "<=", at.toISOString()).executeTakeFirst();
9428
- if (row !== void 0) await expireToken(trx, row, at);
9429
- }
9430
- /** Fixed per-field text: the hint never echoes the value or an unknown key. */
9431
- const REQUEST_FIELD_HINTS = {
9432
- name: `Fix \`name\`: use 1-${String(TOKEN_REQUEST_LIMITS.name)} characters, each a letter, digit, ".", "_" or "-".`,
9433
- folder: `Fix \`folder\`: use 1-${String(TOKEN_REQUEST_LIMITS.folder)} characters, not only spaces, with no control or format characters.`,
9434
- host: `Fix \`host\`: use 1-${String(TOKEN_REQUEST_LIMITS.host)} characters with no control or format characters.`,
9435
- hash: "Fix `hash`: send the 64-character lowercase hex SHA-256 of the token."
9436
- };
9437
- /** Register a hash and its approval item together. The raw file secret never reaches this app. */
9438
- async function requestToken(store, config, body, at) {
9439
- const parsed = tokenRequestSchema.safeParse(body);
9440
- if (!parsed.success) {
9441
- const field = parsed.error.issues[0]?.path[0];
9442
- throw new CommandError("usage", (typeof field === "string" ? REQUEST_FIELD_HINTS[field] : void 0) ?? "Send a JSON object with only name, folder, host and hash.");
9443
- }
9444
- const input = parsed.data;
9445
- const expiresAt = new Date(at.getTime() + REQUEST_LIFETIME_MS).toISOString();
9446
- return scanTransaction(store, config, async (trx) => {
9447
- const existing = await trx.selectFrom("operator_token").selectAll().where("name", "=", input.name).executeTakeFirst();
9448
- const status = existing === void 0 ? void 0 : effectiveStatus(existing, at);
9449
- if (status === "pending" || status === "approved" || status === "revoked") throw new CommandError("usage", `Token name ${input.name} is taken; choose another name (see \`board token list\`).`);
9450
- if ((await trx.selectFrom("operator_token").select("id").where("status", "=", "pending").where("expires_at", ">", at.toISOString()).limit(MAX_PENDING_REQUESTS).execute()).length >= MAX_PENDING_REQUESTS) throw new CommandError("usage", "Too many token requests are awaiting approval.");
9451
- if (existing?.status === "pending") await expireToken(trx, existing, at);
9452
- const item = await raiseItem(trx, {
9453
- itemKey: `token:${input.name}`,
9454
- kind: "token_request",
9455
- text: `Approve operator token ${input.name} (request ${requestHashOf(input.hash)}) for ${input.folder} on ${input.host}, requested ${at.toISOString()}?`,
9456
- url: "",
9457
- taskId: null,
9458
- blockId: null,
9459
- at
9460
- });
9461
- const values = {
9462
- hash: input.hash,
9463
- folder: input.folder,
9464
- host: input.host,
9465
- status: "pending",
9466
- requested_at: at.toISOString(),
9467
- expires_at: expiresAt,
9468
- decided_at: null,
9469
- item_id: item.id
9470
- };
9471
- if (existing === void 0) await trx.insertInto("operator_token").values({
9472
- name: input.name,
9473
- ...values
9474
- }).execute();
9475
- else await trx.updateTable("operator_token").set(values).where("id", "=", existing.id).execute();
9476
- await journalToken(trx, "token_requested", input.name, at);
9477
- return {
9478
- name: input.name,
9479
- status: "pending",
9480
- expiresAt
9481
- };
9482
- });
9483
- }
9484
- /** Called within the inbound event's transaction, after the gateway user and space are checked. */
9485
- async function decideTokenInTransaction(trx, itemId, decision, at) {
9486
- const row = await trx.selectFrom("operator_token").selectAll().where("item_id", "=", itemId).executeTakeFirst();
9487
- if (row === void 0) throw new CommandError("not_found", "Token request was not found.");
9488
- const status = effectiveStatus(row, at);
9489
- if (status !== "pending") {
9490
- if (status === "expired" && row.status === "pending") await expireToken(trx, row, at);
9491
- return {
9492
- name: row.name,
9493
- status
9494
- };
9495
- }
9496
- const next = decision === "approve" ? "approved" : "denied";
9497
- await trx.updateTable("operator_token").set({
9498
- status: next,
9499
- decided_at: at.toISOString(),
9500
- ...next === "approved" ? { approved_at: at.toISOString() } : {}
9501
- }).where("id", "=", row.id).execute();
9502
- await journalToken(trx, decision === "approve" ? "token_approved" : "token_denied", row.name, at);
9503
- await clearItem(trx, row.item_id, at, "operator", decision === "approve" ? (item, lineId) => enqueueTokenCard(trx, {
9504
- itemId: item.id,
9505
- parent: lineId,
9506
- card: cardOf(row, at.toISOString()),
9507
- actions: [revokeAction(item.id, row.name, "Revoke")],
9508
- at
9509
- }) : void 0);
9510
- return {
9511
- name: row.name,
9512
- status: next
9513
- };
9514
- }
9515
- /** Clear unreviewed requests even when no approval button is pressed. */
9516
- async function expirePendingTokens(store, config, at) {
9517
- const expiresAt = at.toISOString();
9518
- if (await store.db.selectFrom("operator_token").select("id").where("status", "=", "pending").where("expires_at", "<=", expiresAt).executeTakeFirst() === void 0) return 0;
9519
- return scanTransaction(store, config, async (trx) => {
9520
- const rows = await trx.selectFrom("operator_token").select([
9521
- "id",
9522
- "name",
9523
- "item_id"
9524
- ]).where("status", "=", "pending").where("expires_at", "<=", expiresAt).execute();
9525
- for (const row of rows) await expireToken(trx, row, at);
9526
- return rows.length;
9527
- });
9528
- }
9529
- /**
9530
- * Deletes expired and denied requests decided more than the retention period before `at`; a row
9531
- * exactly at the cutoff stays. Approved, revoked and pending rows and every approval item stay.
9532
- */
9533
- async function purgeEndedTokenRequests(store, at) {
9534
- const cutoff = (/* @__PURE__ */ new Date(at.getTime() - TOKEN_REQUEST_RETENTION_DAYS * DAY_MS$1)).toISOString();
9535
- return store.transaction(async (trx) => {
9536
- const deleted = await trx.deleteFrom("operator_token").where("status", "in", ["expired", "denied"]).where("decided_at", "<", cutoff).executeTakeFirst();
9537
- return Number(deleted.numDeletedRows);
9538
- });
9539
- }
9540
- /**
9541
- * Hash lookup uses the unique index and checks durable state on every call. An approved token's
9542
- * use at `at` is recorded when its last recorded use is older than `TOKEN_USE_INTERVAL_MS`; a
9543
- * failed write goes to `onUseError` and never changes the result.
9544
- */
9545
- async function verifyOperatorToken(store, token, at, onUseError) {
9546
- const hash = createHash("sha256").update(token).digest("hex");
9547
- const row = await store.db.selectFrom("operator_token").select([
9548
- "name",
9549
- "status",
9550
- "last_used_at"
9551
- ]).where("hash", "=", hash).executeTakeFirst();
9552
- if (row?.status !== "approved") return null;
9553
- const usedAt = at.toISOString();
9554
- const staleBy = (/* @__PURE__ */ new Date(at.getTime() - TOKEN_USE_INTERVAL_MS)).toISOString();
9555
- if (row.last_used_at === null || row.last_used_at <= staleBy) try {
9556
- await store.transaction((trx) => trx.updateTable("operator_token").set({ last_used_at: usedAt }).where("hash", "=", hash).where("status", "=", "approved").where((eb) => eb.or([eb("last_used_at", "is", null), eb("last_used_at", "<=", staleBy)])).execute());
9557
- } catch (err) {
9558
- onUseError(err);
9559
- }
9560
- return { name: row.name };
9561
- }
9562
- /** Read-only: an expired pending row is reported as expired but left for the sweep. */
9563
- async function tokenStatusByHash(store, hash, at) {
9564
- const row = await store.db.selectFrom("operator_token").selectAll().where("hash", "=", hash).executeTakeFirst();
9565
- return row === void 0 ? "unknown" : effectiveStatus(row, at);
9566
- }
9567
- function tokenListQuery(clock) {
9568
- return {
9569
- id: "token.list",
9570
- resolveTargets: () => Promise.resolve([]),
9571
- async run(trx) {
9572
- const rows = await trx.selectFrom("operator_token").selectAll().orderBy("id").execute();
9573
- const at = new Date(clock.now());
9574
- return { tokens: rows.map((row) => ({
9575
- name: row.name,
9576
- folder: row.folder,
9577
- status: effectiveStatus(row, at),
9578
- createdAt: row.requested_at,
9579
- approvedAt: row.approved_at,
9580
- lastUsedAt: row.last_used_at
9581
- })) };
9582
- }
9583
- };
9584
- }
9585
- /**
9586
- * Posts one feed line listing the approved and unexpired pending tokens under `key`, so a replay
9587
- * of the same command posts none. The first ones that fit 20 rows and the escaped text budget
9588
- * get a row and a Revoke button; the rest are counted. Returns how many are active and writes
9589
- * nothing for none.
9590
- */
9591
- async function postTokenList(trx, input) {
9592
- const rows = (await trx.selectFrom("operator_token").selectAll().orderBy("id").execute()).map((row) => ({
9593
- row,
9594
- status: effectiveStatus(row, input.at)
9595
- })).filter(({ status }) => status === "approved" || status === "pending");
9596
- if (rows.length === 0) return 0;
9597
- const lines = [];
9598
- let used = LIST_MORE;
9599
- for (const { row, status } of rows.slice(0, LIST_BUTTONS)) {
9600
- const line = `${capPoints(row.name, LIST_NAME)} (${status}), ${capPoints(row.folder, LIST_FOLDER)}`;
9601
- used += escapedLength(line) + 3;
9602
- if (used > LIST_TEXT) break;
9603
- lines.push(line);
9604
- }
9605
- const shown = rows.slice(0, lines.length);
9606
- const hidden = rows.length - shown.length;
9607
- if (hidden > 0) lines.push(`${String(hidden)} more: \`board token list\``);
9608
- await enqueueBoardFeedLine(trx, {
9609
- dedupeKey: `feed.line:token-list:${input.key}`,
9610
- itemKey: `token-list:${input.key}`,
9611
- text: lines.join("\n"),
9612
- title: "Operator tokens",
9613
- actions: shown.map(({ row }) => revokeAction(row.item_id, row.name, `Revoke ${capPoints(row.name, LABEL_NAME)}`)),
9614
- at: input.at
9615
- });
9616
- return rows.length;
9617
- }
9618
- const tokenRevokeMutation = {
9619
- id: "token.revoke",
9620
- resolveTargets: () => Promise.resolve([]),
9621
- async run(trx, input, ctx) {
9622
- const row = await trx.selectFrom("operator_token").selectAll().where("name", "=", input.name).executeTakeFirst();
9623
- if (row === void 0) throw new CommandError("not_found", "Token name was not found.");
9624
- if (row.status !== "revoked") {
9625
- const at = new Date(ctx.at);
9626
- await trx.updateTable("operator_token").set({
9627
- status: "revoked",
9628
- decided_at: ctx.at
9629
- }).where("id", "=", row.id).execute();
9630
- await journalToken(trx, "token_revoked", row.name, at);
9631
- await clearItem(trx, row.item_id, at, ctx.actor);
9632
- const text = `token ${capPoints(row.name, CARD_NAME)} revoked`;
9633
- await enqueueBoardFeedLine(trx, {
9634
- dedupeKey: `feed.line:token-revoked:${String(row.id)}`,
9635
- itemKey: `token-revoked:${String(row.id)}`,
9636
- text,
9637
- title: text,
9638
- at
9639
- });
9640
- const card = row.status === "approved" ? await trx.selectFrom("outbox").select(["id", "state"]).where("dedupe_key", "=", tokenCardKey(row.item_id)).executeTakeFirst() : void 0;
9641
- if (card !== void 0 && card.state !== "dead" && row.decided_at !== null) await enqueueTokenCard(trx, {
9642
- itemId: row.item_id,
9643
- parent: card.id,
9644
- card: {
9645
- ...cardOf(row, row.decided_at),
9646
- revoked: {
9647
- by: ctx.actor,
9648
- at: ctx.at
9649
- }
9650
- },
9651
- at
9652
- });
9653
- }
9654
- return {
9655
- name: row.name,
9656
- status: "revoked"
9657
- };
9658
- }
9659
- };
9660
- /**
9661
- * Approved tokens unused for `unusedAfterDays` days (last use, else approval, else request time)
9662
- * or whose token file is gone. `probe` answers whether the token file is present, or null when
9663
- * it cannot tell (another host, an unreadable folder); it runs after the read, outside any
9664
- * transaction.
9665
- */
9666
- async function tokenAttention(store, at, unusedAfterDays, probe) {
9667
- const rows = await store.db.selectFrom("operator_token").select([
9668
- "name",
9669
- "folder",
9670
- "host",
9671
- "requested_at",
9672
- "approved_at",
9673
- "last_used_at"
9674
- ]).where("status", "=", "approved").orderBy("id").execute();
9675
- const cutoff = (/* @__PURE__ */ new Date(at.getTime() - unusedAfterDays * DAY_MS$1)).toISOString();
9676
- const attention = {
9677
- fileMissing: [],
9678
- unused: []
9679
- };
9680
- for (const row of rows) if (await probe({
9681
- folder: row.folder,
9682
- host: row.host
9683
- }) === false) attention.fileMissing.push(row.name);
9684
- else if ((row.last_used_at ?? row.approved_at ?? row.requested_at) <= cutoff) attention.unused.push(row.name);
9685
- return attention;
9686
- }
9687
- /**
9688
- * One line naming the tokens in `attention`, at most 300 characters, or null when none needs
9689
- * attention. Shared by `board doctor` and the daily digest. A name enrollment would refuse today
9690
- * is counted, never printed; trailing names that do not fit become "and N more".
9691
- */
9692
- function tokenAttentionLine(attention, unusedAfterDays) {
9693
- const total = attention.fileMissing.length + attention.unused.length;
9694
- if (total === 0) return null;
9695
- const head = `${String(total)} operator ${total === 1 ? "token needs" : "tokens need"} attention (revoke any that nothing uses with \`board token revoke <name>\`)`;
9696
- const printableNames = (names) => names.filter((name) => tokenRequestSchema.shape.name.safeParse(name).success);
9697
- const printable = [{
9698
- label: "no token file",
9699
- names: printableNames(attention.fileMissing)
9700
- }, {
9701
- label: `unused for ${String(unusedAfterDays)}+ days`,
9702
- names: printableNames(attention.unused)
9703
- }];
9704
- const named = printable.reduce((n, group) => n + group.names.length, 0);
9705
- for (let shown = named; shown > 0; shown -= 1) {
9706
- let left = shown;
9707
- const parts = [];
9708
- for (const { label, names } of printable) {
9709
- const listed = names.slice(0, left);
9710
- left -= listed.length;
9711
- if (listed.length > 0) parts.push(`${label}: ${listed.join(", ")}`);
9712
- }
9713
- const more = total - shown;
9714
- const line = `${head}: ${parts.join("; ")}${more > 0 ? ` and ${String(more)} more` : ""}`;
9715
- if (line.length <= ATTENTION_LINE_MAX) return line;
9716
- }
9717
- return `${head}: ${String(total)} not named`;
9718
- }
9719
- //#endregion
9720
- //#region ../core/src/api/identity.ts
9721
- function sessionActor(project, session, config) {
9722
- const actor = actorIdSchema.safeParse(`agent:${project}/${session}`);
9723
- if (!actor.success) throw new CommandError("forbidden", "Invalid session identity.");
9724
- const matches = config.projects.filter((entry) => entry.spurProjects.some((spur) => spur.name === project));
9725
- if (matches.length === 0) throw new CommandError("forbidden", `Spur project "${project}" is not listed in any spurProjects in the Board's config.yaml (not Spur's spur.yaml), and inside a Spur session a token is not used. Ask the operator to add it under projects[].spurProjects there and restart the Board daemon, or run the command outside a Spur session.`);
9726
- if (matches.length > 1) throw new CommandError("forbidden", `Spur project "${project}" is listed under several Board projects: ${matches.map((entry) => entry.id).join(", ")}. Ask the operator to keep it under one of them in the Board's config.yaml (not Spur's spur.yaml) and restart the Board daemon.`);
9727
- return actor.data;
9728
- }
9729
- /** Resolve the caller at the HTTP boundary; a session header always outranks a token. */
9730
- async function identifyCaller(ports, headers) {
9731
- const { session, authorization } = headers;
9732
- if (session !== void 0) {
9733
- if (!actorIdSchema.safeParse(`agent:project/${session}`).success) throw new CommandError("forbidden", "Invalid session identity.");
9734
- const snapshot = await ports.store.db.selectFrom("session_snapshot").select([
9735
- "spur_project",
9736
- "ended_at",
9737
- "raw_state",
9738
- "state"
9739
- ]).where("id", "=", session).executeTakeFirst();
9740
- if (snapshot !== void 0) {
9741
- if (snapshot.ended_at !== null || snapshot.raw_state === "completed" || snapshot.raw_state === "killed" || snapshot.state === "completed" || snapshot.state === "killed") throw new CommandError("forbidden", "The session has ended.");
9742
- return { actor: sessionActor(snapshot.spur_project, session, ports.config) };
9743
- }
9744
- let live;
9745
- try {
9746
- live = await ports.lookupSession(session);
9747
- } catch {
9748
- throw new CommandError("identity_unavailable", "Session identity is unavailable.");
9749
- }
9750
- if (live === null) throw new CommandError("forbidden", "Unknown session.");
9751
- if (typeof live !== "object" || typeof live.project !== "string" || typeof live.status !== "string" || !SESSION_STATUSES.some((status) => status === live.status)) throw new CommandError("identity_unavailable", "Invalid session response.");
9752
- if (live.status === "completed" || live.status === "killed") throw new CommandError("forbidden", "The session has ended.");
9753
- return { actor: sessionActor(live.project, session, ports.config) };
9754
- }
9755
- const bearer = authorization?.match(/^Bearer (\S+)$/i)?.[1];
9756
- if (bearer !== void 0) try {
9757
- const token = await ports.verifyToken(bearer);
9758
- if (token !== null) return {
9759
- actor: "operator",
9760
- tokenName: token.name
9761
- };
9762
- } catch {
9763
- throw new CommandError("identity_unavailable", "Token verification is unavailable.");
9764
- }
9765
- throw new CommandError("forbidden", "A session or accepted token is required.");
9766
- }
9767
- //#endregion
9768
- //#region ../core/src/api/server.ts
9769
- const doctorReportSchema = z.strictObject({
9770
- version: z.string().min(1).max(50),
9771
- checks: z.array(z.strictObject({
9772
- id: z.string().regex(/^[a-z][a-z._]+$/).max(60),
9773
- status: z.enum([
9774
- "pass",
9775
- "fail",
9776
- "warning"
9777
- ]),
9778
- blocking: z.boolean(),
9779
- fix: z.string().max(300).nullable()
9780
- })).max(30)
9781
- });
9782
- const tokenStatusSchema = z.strictObject({ hash: tokenRequestSchema.shape.hash });
9783
- function header(value) {
9784
- return Array.isArray(value) ? void 0 : value;
9785
- }
9786
- function inputBody(body) {
9787
- if (body === null || typeof body !== "object" || Array.isArray(body)) throw new CommandError("usage", "Send a JSON object with input and optional key.");
9788
- const record = body;
9789
- if (!Object.hasOwn(record, "input") || Object.keys(record).some((name) => name !== "input" && name !== "key") || record["key"] !== void 0 && typeof record["key"] !== "string") throw new CommandError("usage", "Send a JSON object with input and optional key.");
9790
- return {
9791
- input: record["input"],
9792
- key: record["key"]
9793
- };
9794
- }
9795
- /** Construct the local HTTP transport; the caller owns listen and close. */
9796
- async function createApiServer(options) {
9797
- const app = Fastify({
9798
- logger: false,
9799
- genReqId: () => randomUUID(),
9800
- trustProxy: false
9801
- });
9802
- const snapshot = await buildCatalogSnapshot(OPERATIONS);
9803
- /** Lets clients notice a daemon restart and check its catalog again. */
9804
- const instance = randomUUID();
9805
- const callers = /* @__PURE__ */ new WeakMap();
9806
- let doctorInFlight = null;
9807
- let doctorCached = null;
9808
- let doctorNextProbeAt = 0;
9809
- const notReady = () => options.stopping?.() === true ? new CommandError("stopping", "Wait until the daemon is running again.") : new CommandError("starting", "Wait until the daemon is ready.");
9810
- app.addHook("onRequest", async (request, reply) => {
9811
- reply.header("x-request-id", request.id);
9812
- reply.header("x-board-instance", instance);
9813
- if (request.headers.origin !== void 0) throw new CommandError("forbidden", "Browser origins are not accepted.");
9814
- const address = app.server.address();
9815
- const port = address !== null && typeof address === "object" ? address.port : options.port;
9816
- if (header(request.headers.host) !== `127.0.0.1:${String(port)}`) throw new CommandError("forbidden", "Use the local API host.");
9817
- const contentType = header(request.headers["content-type"]);
9818
- const mediaType = contentType?.split(";", 1)[0]?.trim().toLowerCase();
9819
- if (contentType !== void 0 && mediaType !== "application/json" || request.method === "POST" && mediaType !== "application/json") throw new CommandError("forbidden", "Use application/json.");
9820
- });
9821
- app.addHook("onResponse", (request, reply, done) => {
9822
- const caller = callers.get(request);
9823
- options.logRequest({
9824
- requestId: request.id,
9825
- method: request.method,
9826
- url: request.url,
9827
- status: reply.statusCode,
9828
- ...caller?.tokenName === void 0 ? {} : { tokenName: caller.tokenName }
9829
- });
9830
- done();
9831
- });
9832
- app.setErrorHandler((error, request, reply) => {
9833
- let code = "unexpected";
9834
- let hint;
9835
- if (error instanceof CommandError) {
9836
- code = error.code;
9837
- hint = error.hint;
9838
- } else if (error instanceof Error && "statusCode" in error) {
9839
- if (error.statusCode === 400 || error.statusCode === 413) code = "usage";
9840
- if (error.statusCode === 413) hint = "Send a smaller JSON body.";
9841
- }
9842
- if (code === "unexpected") options.logError?.({
9843
- requestId: request.id,
9844
- err: error
9845
- });
9846
- const problem = renderHttpProblem({
9847
- code,
9848
- requestId: request.id
9849
- });
9850
- reply.code(problem.status).type("application/problem+json").send(hint === void 0 ? problem.body : {
9851
- ...problem.body,
9852
- hint
9853
- });
9854
- });
9855
- app.setNotFoundHandler(() => {
9856
- throw new CommandError("not_found", "This API route is not available.");
9857
- });
9858
- app.get("/v1/schema", async (_request, reply) => {
9859
- if (!options.ready()) throw notReady();
9860
- return reply.send(snapshot);
9861
- });
9862
- app.get("/v1/doctor", async (_request, reply) => {
9863
- if (!options.ready()) throw notReady();
9864
- if (options.doctor === void 0) throw new CommandError("not_found", "Doctor is unavailable.");
9865
- if (doctorInFlight !== null) return reply.send(await doctorInFlight);
9866
- if (options.clock.now() < doctorNextProbeAt) {
9867
- if (doctorCached !== null) return reply.send(doctorCached);
9868
- throw new CommandError("starting", "Retry board doctor in a few seconds.");
9869
- }
9870
- doctorNextProbeAt = options.clock.now() + 5e3;
9871
- doctorInFlight = options.doctor().then((report) => doctorReportSchema.parse(report));
9872
- try {
9873
- doctorCached = await doctorInFlight;
9874
- return await reply.send(doctorCached);
9875
- } finally {
9876
- doctorInFlight = null;
9877
- }
9878
- });
9879
- app.get("/v1/health", async (_request, reply) => {
9880
- if (!options.ready()) throw notReady();
9881
- if (options.firstPollDone === void 0) throw new CommandError("not_found", "Health is unavailable.");
9882
- return reply.send({ firstPollDone: await options.firstPollDone() });
9883
- });
9884
- app.post("/v1/tokens/requests", async (request, reply) => {
9885
- if (!options.ready()) throw notReady();
9886
- const result = await requestToken(options.store, options.config, request.body, new Date(options.clock.now()));
9887
- return reply.send(successEnvelopeSchema.parse({
9888
- ok: true,
9889
- requestId: request.id,
9890
- value: result
9891
- }));
9892
- });
9893
- /** The hash travels in the body because request logs record the URL. */
9894
- app.post("/v1/tokens/status", async (request, reply) => {
9895
- if (!options.ready()) throw notReady();
9896
- const parsed = tokenStatusSchema.safeParse(request.body);
9897
- if (!parsed.success) throw new CommandError("usage", "Provide a SHA-256 token hash.");
9898
- const status = await tokenStatusByHash(options.store, parsed.data.hash, new Date(options.clock.now()));
9899
- return reply.send(successEnvelopeSchema.parse({
9900
- ok: true,
9901
- requestId: request.id,
9902
- value: { status }
9903
- }));
9904
- });
9905
- app.post("/v1/ops/:id", { onRequest: async (request) => {
9906
- if (!options.ready()) throw notReady();
9907
- const sessionHeader = request.headers["x-board-session"];
9908
- if (Array.isArray(sessionHeader)) throw new CommandError("forbidden", "Use one session identity header.");
9909
- callers.set(request, await identifyCaller(options, {
9910
- session: sessionHeader,
9911
- authorization: header(request.headers.authorization)
9912
- }));
9913
- } }, async (request, reply) => {
9914
- const caller = callers.get(request);
9915
- if (caller === void 0) throw new Error("Operation identity was not resolved.");
9916
- const operation = OPERATIONS.find((entry) => entry.id === request.params.id);
9917
- if (operation === void 0) throw new CommandError("version_mismatch", "This daemon does not know the operation. Run `board service restart` to update the daemon, then retry.");
9918
- const body = inputBody(request.body);
9919
- const parsed = operation.input.safeParse(body.input);
9920
- if (!parsed.success) throw new CommandError(errorCodeOf(parsed.error), "Fix the operation input.");
9921
- const dispatch = () => dispatchOperation(options, operation.id, parsed.data, caller.actor, body.key);
9922
- const result = await (options.runOperation === void 0 ? dispatch() : options.runOperation(operation.id, parsed.data, dispatch));
9923
- await options.afterOperation?.(reply.raw);
9924
- return reply.send(successEnvelopeSchema.parse({
9925
- ok: true,
9926
- requestId: request.id,
9927
- value: result
9928
- }));
9929
- });
9930
- return app;
9931
- }
9932
- /** The only supported listener for the local API. */
9933
- function listenApiServer(app, port) {
9934
- return app.listen({
9935
- host: "127.0.0.1",
9936
- port
9937
- });
9938
- }
9939
- //#endregion
9940
- //#region ../core/src/app/block-thread.ts
9941
- function orchestrator(config, task) {
9942
- const name = config.projects.find((project) => project.id === task.project)?.columns.find((column) => column.id === task.column)?.orchestrator;
9943
- return name === void 0 || name === "none" ? null : name;
9944
- }
9945
- function authorRole(config, task, actor) {
9946
- if (actor === "operator") return "operator";
9947
- const parsed = parseActorId(actor);
9948
- if (parsed?.actor === "agent" && config.projects.some((project) => project.spurProjects.some((spur) => spur.name === parsed.actorRef.project && spur.role === "operator"))) return "operator";
9949
- if (parsed?.actor !== "agent") return "worker";
9950
- if (parsed.actorRef.project === orchestrator(config, task)) return `orchestrator:${task.column}`;
9951
- return parsed.actorRef.project === curatorProject(config, task.project) ? "curator" : "worker";
9952
- }
9953
- function personaRole(role) {
9954
- const addressee = parseAddressee(role);
9955
- switch (addressee.kind) {
9956
- case "operator": return "board";
9957
- case "worker": return "worker";
9958
- case "curator": return "curator";
9959
- case "orchestrator": return "orchestrator";
9960
- default: return assertNever(addressee);
9961
- }
9962
- }
9963
- function personaFor(config, task, actor) {
9964
- if (actor === "system") return {
9965
- name: "board",
9966
- role: "board"
9967
- };
9968
- if (actor === "operator") return {
9969
- name: "operator",
9970
- role: "board"
9971
- };
9972
- const parsed = parseActorId(actor);
9973
- if (parsed?.actor !== "agent") throw new Error("Invalid actor");
9974
- return {
9975
- name: parsed.actorRef.project,
9976
- role: personaRole(authorRole(config, task, actor))
9977
- };
9978
- }
9979
- async function queueBlockOpen(trx, task, block, ctx, config) {
9980
- if (authorRole(config, task, block.author) === "operator") return;
9981
- const comments = await trx.selectFrom("comment").select(["id", "author"]).where("block_id", "=", block.id).orderBy("id").execute();
9982
- if (await enqueueConversationOpen(trx, {
9983
- blockId: block.id,
9984
- commentId: comments[0]?.id ?? null,
9985
- persona: personaFor(config, task, comments[0]?.author ?? block.author),
9986
- at: new Date(ctx.at)
9987
- }) === null) return;
9988
- for (const comment of comments.slice(1)) await enqueueConversationReply(trx, {
9989
- commentId: comment.id,
9990
- persona: personaFor(config, task, comment.author),
9991
- at: new Date(ctx.at)
9992
- });
9993
- }
9994
- //#endregion
9995
- //#region ../core/src/app/doorbells.ts
9996
- const UNANSWERED = "unanswered";
9997
- async function journal$2(trx, notification, kind, payload, at) {
9998
- await emit(trx, kind, (await trx.selectFrom("task").select("project").where("id", "=", notification.task_id).executeTakeFirstOrThrow()).project, notification.task_id, at.toISOString(), payload);
9552
+ async function cancelledRingState(trx, n) {
9553
+ if (n.acked_at === null || n.rings !== 0 || n.exhausted_at !== null) return null;
9554
+ const rows = await trx.selectFrom("outbox").select(["state", "uncertain"]).where("kind", "=", "doorbell").where(sql`json_extract(payload, '$.notificationId')`, "=", n.id).execute();
9555
+ if (rows.some((row) => row.state !== "dead")) return null;
9556
+ return rows.some((row) => row.uncertain === 1) ? "maybe_out" : "unsent";
9999
9557
  }
10000
9558
  /**
10001
- * The one rule for who a board event rings. A doorbell means someone is waiting for your action,
10002
- * so a party that caused the event, or that the Slack thread already reaches, gets no row.
9559
+ * Register the single reminder to the session holding a quiet turn. The key names the holder and
9560
+ * its take, so each ownership episode gets its own reminder and no episode gets a second. A
9561
+ * reminder of the take cancelled unsent is replaced by a fresh one: its row gets a new id, so the
9562
+ * new ring does not reuse the outbox key of a ring the sender already killed.
10003
9563
  */
10004
- async function applyDoorbellPolicy(trx, event, at) {
10005
- switch (event.kind) {
10006
- case "block_opened":
10007
- if (!(parseActorId(event.block.author)?.actor === "agent" && event.block.addressee_role === event.authorRole)) await registerBlockNotification(trx, event.block, at);
10008
- return;
10009
- case "block_escalated":
10010
- await closeBlockNotification(trx, event.block.id, at, "system");
10011
- await registerBlockNotification(trx, event.block, at);
10012
- return;
10013
- case "answer":
10014
- await registerAnswerNotification(trx, event, at);
10015
- return;
10016
- case "block_removed":
10017
- await registerRemovedNotification(trx, event.block, at);
10018
- return;
10019
- case "block_closed_by_addressee":
10020
- case "task_comment": return;
10021
- default: assertNever(event);
10022
- }
9564
+ async function registerTurnReminder(trx, turn, session, at) {
9565
+ if (turn.acked_at === null) throw new Error(`turn ${String(turn.id)} is not taken`);
9566
+ const key = turnReminderKey(turn.id, session, turn.acked_at);
9567
+ const earlier = await trx.selectFrom("notification").selectAll().where("source_key", "=", key).executeTakeFirst();
9568
+ if (earlier !== void 0 && await reminderCancelledUnsent(trx, earlier)) await trx.deleteFrom("notification").where("id", "=", earlier.id).execute();
9569
+ await trx.insertInto("notification").values({
9570
+ source_key: key,
9571
+ kind: "turn_reminder",
9572
+ task_id: turn.task_id,
9573
+ block_id: null,
9574
+ turn_id: turn.id,
9575
+ comment_id: null,
9576
+ revision: null,
9577
+ role: turn.role,
9578
+ author_session: session,
9579
+ recipient_session: null,
9580
+ next_at: at.toISOString(),
9581
+ last_outbox_id: null,
9582
+ acked_at: null,
9583
+ exhausted_at: null,
9584
+ created_at: at.toISOString()
9585
+ }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
10023
9586
  }
10024
- /** Register a block for its agent addressee; the Slack thread carries an operator's. */
10025
- async function registerBlockNotification(trx, block, at) {
9587
+ /** The block of a block-owned notification; the store CHECK gives every non-turn kind one. */
9588
+ function noticeBlockId(n) {
9589
+ if (n.block_id === null) throw new Error(`notification of kind ${n.kind} has no block`);
9590
+ return n.block_id;
9591
+ }
9592
+ /** What a notification is about, as the operator item names it. */
9593
+ function noticeRef(n, task) {
9594
+ return isTurnKind(n.kind) ? `turn T${String(n.turn_id)} on ${task.key}` : `block B${String(noticeBlockId(n))} on ${task.key}`;
9595
+ }
9596
+ /** Register a one-ring notice that a block its addressee held was closed by someone else. */
9597
+ async function registerRemovedNotification(trx, block, at) {
10026
9598
  if (block.addressee_role === "operator") return;
10027
9599
  await trx.insertInto("notification").values({
10028
- source_key: `block:${String(block.id)}:${block.addressee_role}`,
10029
- kind: "block",
9600
+ source_key: `removed:${String(block.id)}`,
9601
+ kind: "removed",
10030
9602
  task_id: block.task_id,
10031
9603
  block_id: block.id,
10032
9604
  comment_id: null,
@@ -10041,588 +9613,1170 @@ async function registerBlockNotification(trx, block, at) {
10041
9613
  created_at: at.toISOString()
10042
9614
  }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
10043
9615
  }
9616
+ /** Register an answer or clarification for the question's author, unless the author wrote it. */
9617
+ async function registerAnswerNotification(trx, input, at) {
9618
+ const parsed = parseActorId(input.block.author);
9619
+ if (parsed?.actor !== "agent" || input.actor === input.block.author) return;
9620
+ const actor = parseActorId(input.actor);
9621
+ if (resolvedByProject(input.authorRole) && actor?.actor === "agent" && actor.actorRef.project === parsed.actorRef.project) return;
9622
+ await trx.insertInto("notification").values({
9623
+ source_key: `comment:${String(input.commentId)}:${String(input.revision)}`,
9624
+ kind: "answer",
9625
+ task_id: input.block.task_id,
9626
+ block_id: input.block.id,
9627
+ comment_id: input.commentId,
9628
+ revision: input.revision,
9629
+ role: input.authorRole,
9630
+ author_session: parsed.actorRef.session,
9631
+ recipient_session: null,
9632
+ next_at: at.toISOString(),
9633
+ last_outbox_id: null,
9634
+ acked_at: null,
9635
+ exhausted_at: null,
9636
+ created_at: at.toISOString()
9637
+ }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
9638
+ }
9639
+ /**
9640
+ * Moves a block to a new addressee, for `block.escalate` and for a ring series that ended: the
9641
+ * journal row, the old notification's end, the new one and the Slack thread, in the caller's
9642
+ * transaction.
9643
+ */
9644
+ async function moveBlockToAddressee(trx, input) {
9645
+ const { task, block, to, reason, ctx, config } = input;
9646
+ const updated = await trx.updateTable("block").set({ addressee_role: to }).where("id", "=", block.id).returningAll().executeTakeFirstOrThrow();
9647
+ await emit(trx, "block_escalated", task.project, task.id, ctx.at, {
9648
+ block: `B${String(block.id)}`,
9649
+ from: block.addressee_role,
9650
+ to,
9651
+ ...reason === void 0 ? {} : { reason }
9652
+ }, ctx.actor);
9653
+ await applyDoorbellPolicy(trx, {
9654
+ kind: "block_escalated",
9655
+ block: updated
9656
+ }, new Date(ctx.at));
9657
+ await queueBlockOpen(trx, task, updated, ctx, config);
9658
+ return updated;
9659
+ }
9660
+ async function sessionById(trx, id) {
9661
+ return trx.selectFrom("session_snapshot").selectAll().where("id", "=", id).executeTakeFirst();
9662
+ }
9663
+ async function liveSession(trx, id) {
9664
+ const row = await sessionById(trx, id);
9665
+ return row?.ended_at === null && row.state !== "killed" && row.state !== "stopped" ? row : void 0;
9666
+ }
9667
+ /** Spur lifecycle states of a session that can no longer read a ring. */
9668
+ const FINISHED_STATES = [
9669
+ "killed",
9670
+ "stopped",
9671
+ "errored",
9672
+ "completed"
9673
+ ];
9674
+ /** Stricter than `liveSession`: a role resolved by Spur project must also be in Spur's list. */
9675
+ function liveInProject(session) {
9676
+ return session.ended_at === null && session.absent_since === null && !FINISHED_STATES.includes(session.state);
9677
+ }
9678
+ /** Roles whose recipient is any session of a configured Spur project, not one linked session. */
9679
+ function resolvedByProject(role) {
9680
+ const { kind } = parseAddressee(role);
9681
+ return kind === "curator" || kind === "orchestrator";
9682
+ }
9683
+ /**
9684
+ * Milliseconds of a stored time, or null for a missing or unreadable one. `Date.parse`, not text
9685
+ * order: ISO values with different fractions do not sort as text.
9686
+ */
9687
+ function instant(value) {
9688
+ if (typeof value !== "string") return null;
9689
+ const ms = Date.parse(value);
9690
+ return Number.isNaN(ms) ? null : ms;
9691
+ }
9692
+ /** Orders later times first and missing times last. Compared, never subtracted. */
9693
+ function laterFirst(left, right) {
9694
+ const a = left ?? -Infinity;
9695
+ const b = right ?? -Infinity;
9696
+ return a > b ? -1 : a < b ? 1 : 0;
9697
+ }
9698
+ /**
9699
+ * The newest live session of a Spur project, then the most recently active, then by id. A row
9700
+ * with an unreadable time or detail stays eligible and sorts last on that time.
9701
+ */
9702
+ async function bestProjectSession(trx, project) {
9703
+ if (project === null) return void 0;
9704
+ return (await trx.selectFrom("session_snapshot").selectAll().select(sql`CASE WHEN json_valid(detail) THEN json_extract(detail, '$.lastActivityAt') END`.as("last_activity")).where("spur_project", "=", project).where("ended_at", "is", null).where("absent_since", "is", null).where("state", "not in", FINISHED_STATES).execute()).sort((left, right) => laterFirst(instant(left.first_seen), instant(right.first_seen)) || laterFirst(instant(left.last_activity), instant(right.last_activity)) || (left.id < right.id ? -1 : 1))[0];
9705
+ }
9706
+ /**
9707
+ * The live session that a curator block on a board project rings, or undefined when the project
9708
+ * has no curator or the curator has no live session. `board doctor` reports the same choice.
9709
+ */
9710
+ async function curatorSession(trx, config, projectId) {
9711
+ return bestProjectSession(trx, curatorProject(config, projectId));
9712
+ }
9713
+ /** The newest live session linked to a task in a role. */
9714
+ async function linkedSession(trx, taskId, role) {
9715
+ 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();
9716
+ for (const link of links) {
9717
+ if (link.session_id === null) continue;
9718
+ const session = await liveSession(trx, link.session_id);
9719
+ if (session !== void 0) return session;
9720
+ }
9721
+ }
9722
+ async function taskProject(trx, taskId) {
9723
+ return (await trx.selectFrom("task").select("project").where("id", "=", taskId).executeTakeFirstOrThrow()).project;
9724
+ }
9725
+ /** The Spur project orchestrating a column; null when no agent project does. */
9726
+ function columnOrchestratorProject(config, projectId, column) {
9727
+ const name = config.projects.find((project) => project.id === projectId)?.columns.find((entry) => entry.id === column)?.orchestrator;
9728
+ return name === void 0 || name === "none" || name === "operator" ? null : name;
9729
+ }
9730
+ /**
9731
+ * Select the current live recipient for a semantic notification. A turn reminder reaches only
9732
+ * the session it names, while that session lives.
9733
+ */
9734
+ async function selectNotificationRecipient(trx, n, config) {
9735
+ if (n.kind === "turn_reminder") return n.author_session === null ? void 0 : liveSession(trx, n.author_session);
9736
+ const addressee = parseAddressee(n.role);
9737
+ switch (addressee.kind) {
9738
+ case "curator": return curatorSession(trx, config, await taskProject(trx, n.task_id));
9739
+ case "orchestrator": {
9740
+ const author = n.author_session === null ? void 0 : await sessionById(trx, n.author_session);
9741
+ if (author !== void 0 && liveInProject(author)) return author;
9742
+ return await linkedSession(trx, n.task_id, "orchestrator") ?? bestProjectSession(trx, columnOrchestratorProject(config, await taskProject(trx, n.task_id), addressee.column));
9743
+ }
9744
+ case "worker":
9745
+ case "operator": {
9746
+ const author = n.author_session === null ? void 0 : await liveSession(trx, n.author_session);
9747
+ if (author !== void 0 || addressee.kind === "operator") return author;
9748
+ return linkedSession(trx, n.task_id, "worker");
9749
+ }
9750
+ default: return assertNever(addressee);
9751
+ }
9752
+ }
9753
+ /** The operator item kind raised when a notification's rings are exhausted. */
9754
+ function exhaustedItemKind(n) {
9755
+ return n.kind === "answer" ? "answer_undelivered" : "worker_not_reading";
9756
+ }
9757
+ /** The operator item key raised when a notification's rings are exhausted. */
9758
+ function exhaustedItemKey(n) {
9759
+ return `${exhaustedItemKind(n)}:${n.source_key}`;
9760
+ }
10044
9761
  /**
10045
- * Register an agent executor's turn. Core opens a turn, so no session authored it: the worker
10046
- * or column orchestrator the board selects is rung.
9762
+ * Restart an exhausted, unacknowledged ring series at `at`. The recipient and last row stay, so
9763
+ * the next reconcile rings the same session under the next series key.
10047
9764
  */
10048
- async function registerTurnNotification(trx, turn, at) {
10049
- await trx.insertInto("notification").values({
10050
- source_key: `turn:${String(turn.id)}:${turn.role}`,
10051
- kind: "turn",
10052
- task_id: turn.task_id,
10053
- block_id: null,
10054
- turn_id: turn.id,
10055
- comment_id: null,
10056
- revision: null,
10057
- role: turn.role,
10058
- author_session: null,
10059
- recipient_session: null,
10060
- next_at: at.toISOString(),
10061
- last_outbox_id: null,
10062
- acked_at: null,
9765
+ async function restartNotification(trx, sourceKey, at) {
9766
+ if (await trx.updateTable("notification").set({
9767
+ rings: 0,
10063
9768
  exhausted_at: null,
10064
- created_at: at.toISOString()
10065
- }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
9769
+ next_at: at.toISOString()
9770
+ }).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.");
10066
9771
  }
10067
9772
  /**
10068
- * The key of the reminder to `session` about a turn it took at `takenAt`. The take time names the
10069
- * ownership episode, so a session that loses the turn and takes it again gets a new reminder.
10070
- */
10071
- const turnReminderKey = (turnId, session, takenAt) => `turn:${String(turnId)}:reminder:${session}:${takenAt}`;
10072
- const isTurnKind = (kind) => kind === "turn" || kind === "turn_reminder";
10073
- /**
10074
- * Whether a reminder was cancelled before it was ever sent, as a link removal does: it counts as
10075
- * no reminder for its take, so a restored link reminds the holder again. A ring of it still
10076
- * queued or in flight, or one that may have reached Spur (`uncertain`), keeps it: the outcome is
10077
- * not known yet or the reminder may be out, and one reminder per take wins over a missed one.
10078
- * Only rings the sender killed unsent leave it re-armable.
9773
+ * Ends a notification's ring series. A curator block moves to the operator; a removal, a turn
9774
+ * reminder or a ring with no session to name ends alone; anything else raises the operator item, whose Retry restarts
9775
+ * the series (`restartNotification`). Every end journals `doorbell_undelivered`.
10079
9776
  */
10080
- async function reminderCancelledUnsent(trx, n) {
10081
- return await cancelledRingState(trx, n) === "unsent";
9777
+ async function endNotification(trx, n, task, end) {
9778
+ const { session, reason, at, config } = end;
9779
+ await trx.updateTable("notification").set({ exhausted_at: at.toISOString() }).where("id", "=", n.id).execute();
9780
+ const addressee = parseAddressee(n.role);
9781
+ if (n.kind === "block" && addressee.kind === "curator") await moveBlockToAddressee(trx, {
9782
+ task,
9783
+ block: await trx.selectFrom("block").selectAll().where("id", "=", noticeBlockId(n)).executeTakeFirstOrThrow(),
9784
+ to: "operator",
9785
+ reason,
9786
+ ctx: {
9787
+ actor: "system",
9788
+ at: at.toISOString()
9789
+ },
9790
+ config
9791
+ });
9792
+ else if (n.kind !== "removed" && n.kind !== "turn_reminder" && session !== null) {
9793
+ const blockRef = noticeRef(n, task);
9794
+ const answer = `Answer to ${blockRef} was not`;
9795
+ const holder = `${addressee.kind} ${session}`;
9796
+ await raiseItem(trx, {
9797
+ itemKey: exhaustedItemKey(n),
9798
+ kind: exhaustedItemKind(n),
9799
+ 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}`,
9800
+ url: taskUrl(task, config),
9801
+ taskId: task.id,
9802
+ blockId: n.block_id,
9803
+ at
9804
+ });
9805
+ }
9806
+ await journal$2(trx, n, "doorbell_undelivered", {
9807
+ doorbell: `N${String(n.id)}`,
9808
+ reason
9809
+ }, at);
10082
9810
  }
10083
9811
  /**
10084
- * The rings of a reminder acked before any delivery was counted: `unsent` when the sender killed
10085
- * them all unsent, `maybe_out` when all are dead and one may have reached Spur, and null while one
10086
- * is queued or in flight, or for a reminder that was delivered, exhausted or never acked. A
10087
- * `maybe_out` reminder counts as delivered for the stuck-turn rule, so the one-ring limit does not
10088
- * hide a stuck turn.
9812
+ * Ends a ring Spur will not take (a permanent rejection, or no answer for the retry window). A
9813
+ * ring that is no longer its notification's last row (the recipient changed while it was in
9814
+ * flight) ends alone. An inbound author ring has no notification: it ends like an author found
9815
+ * unavailable at enqueue.
10089
9816
  */
10090
- async function cancelledRingState(trx, n) {
10091
- if (n.acked_at === null || n.rings !== 0 || n.exhausted_at !== null) return null;
10092
- const rows = await trx.selectFrom("outbox").select(["state", "uncertain"]).where("kind", "=", "doorbell").where(sql`json_extract(payload, '$.notificationId')`, "=", n.id).execute();
10093
- if (rows.some((row) => row.state !== "dead")) return null;
10094
- return rows.some((row) => row.uncertain === 1) ? "maybe_out" : "unsent";
9817
+ async function ringUndelivered(trx, input) {
9818
+ const { at, reason } = input;
9819
+ if (input.notificationId === void 0) {
9820
+ const task = await ringTask(trx, void 0, input.dedupeKey);
9821
+ if (task === void 0) return;
9822
+ await emit(trx, "doorbell_undelivered", task.project, task.id, at.toISOString(), {
9823
+ doorbell: input.dedupeKey,
9824
+ reason
9825
+ });
9826
+ await raiseItem(trx, {
9827
+ itemKey: `doorbell:unavailable:${input.dedupeKey}`,
9828
+ kind: "answer_author_unavailable",
9829
+ text: `Answer author unavailable: ${reason}`,
9830
+ url: taskUrl(task, input.config),
9831
+ taskId: task.id,
9832
+ blockId: null,
9833
+ at
9834
+ });
9835
+ return;
9836
+ }
9837
+ const n = await trx.selectFrom("notification").selectAll().where("id", "=", input.notificationId).executeTakeFirst();
9838
+ if (n === void 0 || n.acked_at !== null || n.exhausted_at !== null || n.last_outbox_id !== input.outboxId) return;
9839
+ await endNotification(trx, n, await trx.selectFrom("task").selectAll().where("id", "=", n.task_id).executeTakeFirstOrThrow(), {
9840
+ session: input.session,
9841
+ reason,
9842
+ at,
9843
+ config: input.config
9844
+ });
9845
+ }
9846
+ /** Why a notification with no recipient ends now, or null when it stays due for a next session. */
9847
+ function noRecipientEnd(n) {
9848
+ if (n.kind === "removed" || n.kind === "turn_reminder" || n.kind === "answer" && n.role === "operator") return "no live addressee";
9849
+ return n.kind === "block" && n.role === "curator" ? "no live curator session" : null;
9850
+ }
9851
+ /** A ring never carries comment or reason text: only where to look. */
9852
+ async function ringText(trx, n, task, ring) {
9853
+ const suffix = ringMarker(n.id, ring);
9854
+ if (n.kind === "turn") return `${task.key} turn T${String(n.turn_id)}: check board inbox ${suffix}`;
9855
+ if (n.kind === "turn_reminder") return `${task.key} turn T${String(n.turn_id)} is still open: check board inbox ${suffix}`;
9856
+ const blockId = noticeBlockId(n);
9857
+ if (n.kind !== "removed") return `${task.key} block B${String(blockId)}: check board inbox ${suffix}`;
9858
+ const block = await trx.selectFrom("block").select("unblocked_by").where("id", "=", blockId).executeTakeFirstOrThrow();
9859
+ return `${task.key} block B${String(blockId)} was removed by ${block.unblocked_by ?? "system"}; see board task ${task.key} ${suffix}`;
9860
+ }
9861
+ /** Notifications reconcile looks at: unacked, not exhausted, due, on a task not archived. */
9862
+ function dueNotifications(db, at) {
9863
+ return db.selectFrom("notification").innerJoin("task", "task.id", "notification.task_id").where("task.membership", "!=", "archived").where("notification.acked_at", "is", null).where("notification.exhausted_at", "is", null).where("notification.next_at", "<=", at.toISOString());
10095
9864
  }
10096
9865
  /**
10097
- * Register the single reminder to the session holding a quiet turn. The key names the holder and
10098
- * its take, so each ownership episode gets its own reminder and no episode gets a second. A
10099
- * reminder of the take cancelled unsent is replaced by a fresh one: its row gets a new id, so the
10100
- * new ring does not reuse the outbox key of a ring the sender already killed.
9866
+ * Reconciles due notifications in their own transaction. With none due it opens no transaction;
9867
+ * a due notification waiting on a working recipient, an unsent ring or a ring still in the
9868
+ * recipient's Spur queue still opens one.
10101
9869
  */
10102
- async function registerTurnReminder(trx, turn, session, at) {
10103
- if (turn.acked_at === null) throw new Error(`turn ${String(turn.id)} is not taken`);
10104
- const key = turnReminderKey(turn.id, session, turn.acked_at);
10105
- const earlier = await trx.selectFrom("notification").selectAll().where("source_key", "=", key).executeTakeFirst();
10106
- if (earlier !== void 0 && await reminderCancelledUnsent(trx, earlier)) await trx.deleteFrom("notification").where("id", "=", earlier.id).execute();
10107
- await trx.insertInto("notification").values({
10108
- source_key: key,
10109
- kind: "turn_reminder",
10110
- task_id: turn.task_id,
10111
- block_id: null,
10112
- turn_id: turn.id,
10113
- comment_id: null,
10114
- revision: null,
10115
- role: turn.role,
10116
- author_session: session,
10117
- recipient_session: null,
10118
- next_at: at.toISOString(),
10119
- last_outbox_id: null,
10120
- acked_at: null,
10121
- exhausted_at: null,
10122
- created_at: at.toISOString()
10123
- }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
10124
- }
10125
- /** The block of a block-owned notification; the store CHECK gives every non-turn kind one. */
10126
- function noticeBlockId(n) {
10127
- if (n.block_id === null) throw new Error(`notification of kind ${n.kind} has no block`);
10128
- return n.block_id;
9870
+ async function reconcileDueDoorbells(store, config, at) {
9871
+ if (await dueNotifications(store.db, at).select("notification.id").executeTakeFirst() === void 0) return;
9872
+ await scanTransaction(store, config, (trx) => reconcileDoorbells(trx, at, config));
10129
9873
  }
10130
- /** What a notification is about, as the operator item names it. */
10131
- function noticeRef(n, task) {
10132
- return isTurnKind(n.kind) ? `turn T${String(n.turn_id)} on ${task.key}` : `block B${String(noticeBlockId(n))} on ${task.key}`;
9874
+ /** Reconcile due semantic notifications in the caller's transaction. */
9875
+ async function reconcileDoorbells(trx, at, config) {
9876
+ const due = await dueNotifications(trx, at).selectAll("notification").orderBy("notification.id").execute();
9877
+ for (const n of due) {
9878
+ const session = await selectNotificationRecipient(trx, n, config);
9879
+ const keepsRings = resolvedByProject(n.role);
9880
+ if (session === void 0) {
9881
+ const reason = noRecipientEnd(n);
9882
+ if (reason !== null) await endNotification(trx, n, await trx.selectFrom("task").selectAll().where("id", "=", n.task_id).executeTakeFirstOrThrow(), {
9883
+ session: null,
9884
+ reason,
9885
+ at,
9886
+ config
9887
+ });
9888
+ else if (n.recipient_session !== null) await trx.updateTable("notification").set({
9889
+ recipient_session: null,
9890
+ rings: keepsRings ? n.rings : 0,
9891
+ last_outbox_id: null
9892
+ }).where("id", "=", n.id).execute();
9893
+ continue;
9894
+ }
9895
+ if (recipientBusy(session) && !await spurBlind$1(trx)) continue;
9896
+ let rings = n.rings;
9897
+ let lastOutbox = n.last_outbox_id;
9898
+ if (session.id !== n.recipient_session) {
9899
+ if (lastOutbox !== null) await trx.updateTable("outbox").set({
9900
+ state: "dead",
9901
+ last_error: "recipient changed"
9902
+ }).where("id", "=", lastOutbox).where("state", "=", "pending").execute();
9903
+ if (!keepsRings) rings = 0;
9904
+ lastOutbox = null;
9905
+ await trx.updateTable("notification").set({
9906
+ recipient_session: session.id,
9907
+ rings,
9908
+ last_outbox_id: null
9909
+ }).where("id", "=", n.id).execute();
9910
+ }
9911
+ if (lastOutbox !== null) {
9912
+ const row = await trx.selectFrom("outbox").select("state").where("id", "=", lastOutbox).executeTakeFirst();
9913
+ if (row?.state === "pending" || row?.state === "in_flight") continue;
9914
+ }
9915
+ const task = await trx.selectFrom("task").selectAll().where("id", "=", n.task_id).executeTakeFirstOrThrow();
9916
+ if (rings >= 3) {
9917
+ await endNotification(trx, n, task, {
9918
+ session: session.id,
9919
+ reason: UNANSWERED,
9920
+ at,
9921
+ config
9922
+ });
9923
+ continue;
9924
+ }
9925
+ if (rings > 0 && earlierRingQueued(session, n.id, rings) && !await spurBlind$1(trx)) {
9926
+ const pauses = ringPauses(config);
9927
+ const deadline = Date.parse(n.next_at) + pauses.slice(rings).reduce((sum, pause) => sum + pause, 0);
9928
+ if (at.getTime() >= deadline) await endNotification(trx, n, task, {
9929
+ session: session.id,
9930
+ reason: UNANSWERED,
9931
+ at,
9932
+ config
9933
+ });
9934
+ continue;
9935
+ }
9936
+ const raised = await trx.selectFrom("operator_item").select((eb) => eb.fn.max("raise_no").as("series")).where("item_key", "=", exhaustedItemKey(n)).executeTakeFirst();
9937
+ const archived = await trx.selectFrom("event").select((eb) => eb.fn.countAll().as("count")).where("task_id", "=", n.task_id).where("kind", "=", "task_archived").executeTakeFirst();
9938
+ 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;
9939
+ const ring = rings + 1;
9940
+ const text = await ringText(trx, n, task, ring);
9941
+ const outboxId = await enqueueDoorbell(trx, {
9942
+ notificationId: n.id,
9943
+ ring,
9944
+ session: session.id,
9945
+ text,
9946
+ at,
9947
+ series: raised?.series ?? 0,
9948
+ archives: archived?.count ?? 0,
9949
+ moves: killed?.count ?? 0
9950
+ });
9951
+ await trx.updateTable("notification").set({ last_outbox_id: outboxId }).where("id", "=", n.id).execute();
9952
+ }
10133
9953
  }
10134
- /** Register a one-ring notice that a block its addressee held was closed by someone else. */
10135
- async function registerRemovedNotification(trx, block, at) {
10136
- if (block.addressee_role === "operator") return;
10137
- await trx.insertInto("notification").values({
10138
- source_key: `removed:${String(block.id)}`,
10139
- kind: "removed",
10140
- task_id: block.task_id,
10141
- block_id: block.id,
10142
- comment_id: null,
10143
- revision: null,
10144
- role: block.addressee_role,
10145
- author_session: null,
10146
- recipient_session: null,
10147
- next_at: at.toISOString(),
10148
- last_outbox_id: null,
10149
- acked_at: null,
10150
- exhausted_at: null,
10151
- created_at: at.toISOString()
10152
- }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
9954
+ /** The pause after each delivered ring of a series: before ring 2, before ring 3, then the end. */
9955
+ function ringPauses(config) {
9956
+ return [
9957
+ config.doorbells.firstRetryMs,
9958
+ config.doorbells.secondRetryMs,
9959
+ config.doorbells.unansweredAfterMs
9960
+ ];
10153
9961
  }
10154
- /** Register an answer or clarification for the question's author, unless the author wrote it. */
10155
- async function registerAnswerNotification(trx, input, at) {
10156
- const parsed = parseActorId(input.block.author);
10157
- if (parsed?.actor !== "agent" || input.actor === input.block.author) return;
10158
- const actor = parseActorId(input.actor);
10159
- if (resolvedByProject(input.authorRole) && actor?.actor === "agent" && actor.actorRef.project === parsed.actorRef.project) return;
10160
- await trx.insertInto("notification").values({
10161
- source_key: `comment:${String(input.commentId)}:${String(input.revision)}`,
10162
- kind: "answer",
10163
- task_id: input.block.task_id,
10164
- block_id: input.block.id,
10165
- comment_id: input.commentId,
10166
- revision: input.revision,
10167
- role: input.authorRole,
10168
- author_session: parsed.actorRef.session,
10169
- recipient_session: null,
10170
- next_at: at.toISOString(),
10171
- last_outbox_id: null,
10172
- acked_at: null,
10173
- exhausted_at: null,
10174
- created_at: at.toISOString()
10175
- }).onConflict((oc) => oc.column("source_key").doNothing()).execute();
9962
+ /** The session's last observed Spur facts, or null when its detail does not parse. */
9963
+ function observedFacts(session) {
9964
+ let detail;
9965
+ try {
9966
+ detail = JSON.parse(session.detail);
9967
+ } catch {
9968
+ return null;
9969
+ }
9970
+ const fact = sessionFactsSchema.safeParse(detail);
9971
+ return fact.success ? fact.data : null;
10176
9972
  }
10177
9973
  /**
10178
- * Moves a block to a new addressee, for `block.escalate` and for a ring series that ended: the
10179
- * journal row, the old notification's end, the new one and the Slack thread, in the caller's
10180
- * transaction.
9974
+ * Whether the session was last observed mid-turn. Only an observed `working` health counts: any
9975
+ * other health, or a detail that does not parse, is rung.
10181
9976
  */
10182
- async function moveBlockToAddressee(trx, input) {
10183
- const { task, block, to, reason, ctx, config } = input;
10184
- const updated = await trx.updateTable("block").set({ addressee_role: to }).where("id", "=", block.id).returningAll().executeTakeFirstOrThrow();
10185
- await emit(trx, "block_escalated", task.project, task.id, ctx.at, {
10186
- block: `B${String(block.id)}`,
10187
- from: block.addressee_role,
10188
- to,
10189
- ...reason === void 0 ? {} : { reason }
10190
- }, ctx.actor);
10191
- await applyDoorbellPolicy(trx, {
10192
- kind: "block_escalated",
10193
- block: updated
10194
- }, new Date(ctx.at));
10195
- await queueBlockOpen(trx, task, updated, ctx, config);
10196
- return updated;
9977
+ function recipientBusy(session) {
9978
+ return observedFacts(session)?.health === "working";
10197
9979
  }
10198
- async function sessionById(trx, id) {
10199
- return trx.selectFrom("session_snapshot").selectAll().where("id", "=", id).executeTakeFirst();
9980
+ /**
9981
+ * Whether the session's facts list a ring of this series, up to `rings`, still in its Spur queue.
9982
+ * A detail that does not parse, or one without a queue, holds nothing.
9983
+ */
9984
+ function earlierRingQueued(session, notificationId, rings) {
9985
+ return (observedFacts(session)?.queuedRings ?? []).some((queued) => queued.notification === notificationId && queued.ring <= rings);
10200
9986
  }
10201
- async function liveSession(trx, id) {
10202
- const row = await sessionById(trx, id);
10203
- return row?.ended_at === null && row.state !== "killed" && row.state !== "stopped" ? row : void 0;
9987
+ /** Count one confirmed Spur send, regardless of transport attempts for its outbox row. */
9988
+ async function recordRingDelivery(trx, notificationId, ring, session, at, config) {
9989
+ const n = await trx.selectFrom("notification").selectAll().where("id", "=", notificationId).executeTakeFirst();
9990
+ if (n === void 0 || n.acked_at !== null && n.kind !== "turn_reminder" || n.recipient_session !== session || n.rings >= ring) return;
9991
+ const pauses = ringPauses(config);
9992
+ await trx.updateTable("notification").set({
9993
+ rings: ring,
9994
+ next_at: new Date(at.getTime() + (pauses[ring - 1] ?? 0)).toISOString(),
9995
+ ...n.kind === "removed" || n.kind === "turn_reminder" ? { acked_at: at.toISOString() } : {}
9996
+ }).where("id", "=", notificationId).execute();
9997
+ await journal$2(trx, n, "doorbell_rung", {
9998
+ doorbell: `N${String(n.id)}`,
9999
+ addressee: n.role,
10000
+ attempt: ring
10001
+ }, at);
10204
10002
  }
10205
- /** Spur lifecycle states of a session that can no longer read a ring. */
10206
- const FINISHED_STATES = [
10207
- "killed",
10208
- "stopped",
10209
- "errored",
10210
- "completed"
10211
- ];
10212
- /** Stricter than `liveSession`: a role resolved by Spur project must also be in Spur's list. */
10213
- function liveInProject(session) {
10214
- return session.ended_at === null && session.absent_since === null && !FINISHED_STATES.includes(session.state);
10003
+ /** True while the Spur source is blind: its stored session facts may no longer hold. */
10004
+ async function spurBlind$1(trx) {
10005
+ const state = await trx.selectFrom("source_state").select("blind_reason").where("source", "=", "spur").executeTakeFirst();
10006
+ return state !== void 0 && state.blind_reason !== null;
10215
10007
  }
10216
- /** Roles whose recipient is any session of a configured Spur project, not one linked session. */
10217
- function resolvedByProject(role) {
10218
- const { kind } = parseAddressee(role);
10219
- return kind === "curator" || kind === "orchestrator";
10008
+ /** Confirm that a queued ring still belongs to a live, idle, unread recipient. */
10009
+ async function ringStillCurrent(trx, notificationId, sessionId, config) {
10010
+ const n = await trx.selectFrom("notification").selectAll().where("id", "=", notificationId).executeTakeFirst();
10011
+ if (n === void 0 || n.acked_at !== null || n.exhausted_at !== null || n.recipient_session !== sessionId) return "dead";
10012
+ const session = await selectNotificationRecipient(trx, n, config);
10013
+ if (session?.id !== sessionId) return "dead";
10014
+ return recipientBusy(session) && !await spurBlind$1(trx) ? "defer" : "send";
10220
10015
  }
10221
10016
  /**
10222
- * Milliseconds of a stored time, or null for a missing or unreadable one. `Date.parse`, not text
10223
- * order: ISO values with different fractions do not sort as text.
10017
+ * The task of a ring: through its notification, or for an inbound author ring (no notification)
10018
+ * through the comment in its `doorbell:comment:<id>:` key. Archive kills only unclaimed rings;
10019
+ * the sender drops a claimed one of an archived task before its send starts.
10224
10020
  */
10225
- function instant(value) {
10226
- if (typeof value !== "string") return null;
10227
- const ms = Date.parse(value);
10228
- return Number.isNaN(ms) ? null : ms;
10021
+ async function ringTask(trx, notificationId, dedupeKey) {
10022
+ const commentId = /^doorbell:comment:(\d+):/.exec(dedupeKey)?.[1];
10023
+ if (notificationId === void 0 && commentId === void 0) return void 0;
10024
+ const owner = notificationId !== void 0 ? trx.selectFrom("notification").select("task_id").where("id", "=", notificationId) : trx.selectFrom("comment").select("task_id").where("id", "=", Number(commentId));
10025
+ return trx.selectFrom("task").selectAll().where("id", "in", owner).executeTakeFirst();
10229
10026
  }
10230
- /** Orders later times first and missing times last. Compared, never subtracted. */
10231
- function laterFirst(left, right) {
10232
- const a = left ?? -Infinity;
10233
- const b = right ?? -Infinity;
10234
- return a > b ? -1 : a < b ? 1 : 0;
10027
+ /** Stop notifications acknowledged by the addressed session. */
10028
+ async function acknowledgeNotification(trx, input) {
10029
+ let query = trx.selectFrom("notification").selectAll().where("acked_at", "is", null);
10030
+ if (input.blockId !== void 0) query = query.where("block_id", "=", input.blockId).where("kind", "=", "block");
10031
+ else if (input.commentId !== void 0) query = query.where("comment_id", "=", input.commentId).where("kind", "=", "answer");
10032
+ else if (input.turnId !== void 0) query = query.where("turn_id", "=", input.turnId).where("kind", "=", "turn");
10033
+ else return false;
10034
+ const notices = await query.orderBy("id", "desc").execute();
10035
+ const n = notices[0];
10036
+ if (n === void 0) return false;
10037
+ if (!await notificationAddressedTo(trx, n, input.actor, input.config)) throw new CommandError("forbidden", "Only the addressed task role can acknowledge.");
10038
+ for (const notice of notices) {
10039
+ await trx.updateTable("notification").set({ acked_at: input.at.toISOString() }).where("id", "=", notice.id).execute();
10040
+ await journal$2(trx, notice, "doorbell_read", { doorbell: `N${String(notice.id)}` }, input.at);
10041
+ const item = await trx.selectFrom("operator_item").select("id").where("item_key", "=", exhaustedItemKey(notice)).where("cleared_at", "is", null).executeTakeFirst();
10042
+ if (item !== void 0) await clearItem(trx, item.id, input.at);
10043
+ }
10044
+ return true;
10235
10045
  }
10236
- /**
10237
- * The newest live session of a Spur project, then the most recently active, then by id. A row
10238
- * with an unreadable time or detail stays eligible and sorts last on that time.
10239
- */
10240
- async function bestProjectSession(trx, project) {
10241
- if (project === null) return void 0;
10242
- return (await trx.selectFrom("session_snapshot").selectAll().select(sql`CASE WHEN json_valid(detail) THEN json_extract(detail, '$.lastActivityAt') END`.as("last_activity")).where("spur_project", "=", project).where("ended_at", "is", null).where("absent_since", "is", null).where("state", "not in", FINISHED_STATES).execute()).sort((left, right) => laterFirst(instant(left.first_seen), instant(right.first_seen)) || laterFirst(instant(left.last_activity), instant(right.last_activity)) || (left.id < right.id ? -1 : 1))[0];
10046
+ /** Decides who may list and acknowledge an inbox notice, by the role it is addressed to. */
10047
+ async function notificationAddressedTo(trx, n, actor, config) {
10048
+ const parsed = parseActorId(actor);
10049
+ if (parsed?.actor !== "agent") return false;
10050
+ const { project, session } = parsed.actorRef;
10051
+ const addressee = parseAddressee(n.role);
10052
+ switch (addressee.kind) {
10053
+ case "curator": return project === curatorProject(config, await taskProject(trx, n.task_id));
10054
+ case "orchestrator": return project === columnOrchestratorProject(config, await taskProject(trx, n.task_id), addressee.column) || await hasLiveLink(trx, n.task_id, "orchestrator", session);
10055
+ case "operator": return session === n.author_session;
10056
+ case "worker": return workerNotificationAddressedTo(trx, n, session, config);
10057
+ default: return assertNever(addressee);
10058
+ }
10243
10059
  }
10244
- /**
10245
- * The live session that a curator block on a board project rings, or undefined when the project
10246
- * has no curator or the curator has no live session. `board doctor` reports the same choice.
10247
- */
10248
- async function curatorSession(trx, config, projectId) {
10249
- return bestProjectSession(trx, curatorProject(config, projectId));
10060
+ async function sessionLink(trx, taskId, role, session) {
10061
+ return trx.selectFrom("link").select("id").where("task_id", "=", taskId).where("entity", "=", "session").where("role", "=", role).where("banned", "=", 0).where("session_id", "=", session).executeTakeFirst();
10250
10062
  }
10251
- /** The newest live session linked to a task in a role. */
10252
- async function linkedSession(trx, taskId, role) {
10253
- 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();
10254
- for (const link of links) {
10255
- if (link.session_id === null) continue;
10256
- const session = await liveSession(trx, link.session_id);
10257
- if (session !== void 0) return session;
10258
- }
10063
+ async function hasLiveLink(trx, taskId, role, session) {
10064
+ return await sessionLink(trx, taskId, role, session) !== void 0 && await liveSession(trx, session) !== void 0;
10259
10065
  }
10260
- async function taskProject(trx, taskId) {
10261
- return (await trx.selectFrom("task").select("project").where("id", "=", taskId).executeTakeFirstOrThrow()).project;
10066
+ /** The selected worker while it lives; before the first ring, the author or a linked worker. */
10067
+ async function workerNotificationAddressedTo(trx, n, session, config) {
10068
+ if (n.recipient_session === null) return session === n.author_session || await sessionLink(trx, n.task_id, "worker", session) !== void 0;
10069
+ return await liveSession(trx, n.recipient_session) !== void 0 ? session === n.recipient_session : (await selectNotificationRecipient(trx, n, config))?.id === session;
10262
10070
  }
10263
- /** The Spur project orchestrating a column; null when no agent project does. */
10264
- function columnOrchestratorProject(config, projectId, column) {
10265
- const name = config.projects.find((project) => project.id === projectId)?.columns.find((entry) => entry.id === column)?.orchestrator;
10266
- return name === void 0 || name === "none" || name === "operator" ? null : name;
10071
+ /** Ends a block's ring series; its exhaustion item is cleared by `actor`, who closed the block. */
10072
+ async function closeBlockNotification(trx, blockId, at, actor) {
10073
+ await closeOwnedNotifications(trx, "block", blockId, at, actor);
10267
10074
  }
10268
10075
  /**
10269
- * Select the current live recipient for a semantic notification. A turn reminder reaches only
10270
- * the session it names, while that session lives.
10076
+ * Ends a turn's ring series and reminders for good: acked, and its exhaustion item cleared by the
10077
+ * system.
10271
10078
  */
10272
- async function selectNotificationRecipient(trx, n, config) {
10273
- if (n.kind === "turn_reminder") return n.author_session === null ? void 0 : liveSession(trx, n.author_session);
10274
- const addressee = parseAddressee(n.role);
10275
- switch (addressee.kind) {
10276
- case "curator": return curatorSession(trx, config, await taskProject(trx, n.task_id));
10277
- case "orchestrator": {
10278
- const author = n.author_session === null ? void 0 : await sessionById(trx, n.author_session);
10279
- if (author !== void 0 && liveInProject(author)) return author;
10280
- return await linkedSession(trx, n.task_id, "orchestrator") ?? bestProjectSession(trx, columnOrchestratorProject(config, await taskProject(trx, n.task_id), addressee.column));
10281
- }
10282
- case "worker":
10283
- case "operator": {
10284
- const author = n.author_session === null ? void 0 : await liveSession(trx, n.author_session);
10285
- if (author !== void 0 || addressee.kind === "operator") return author;
10286
- return linkedSession(trx, n.task_id, "worker");
10287
- }
10288
- default: return assertNever(addressee);
10079
+ async function closeTurnNotification(trx, turnId, at) {
10080
+ await closeOwnedNotifications(trx, "turn", turnId, at, "system");
10081
+ }
10082
+ async function closeOwnedNotifications(trx, kind, ownerId, at, actor) {
10083
+ const closed = await trx.updateTable("notification").set({ acked_at: at.toISOString() }).where(kind === "block" ? "block_id" : "turn_id", "=", ownerId).where("kind", "in", kind === "block" ? ["block"] : ["turn", "turn_reminder"]).where("acked_at", "is", null).returning(["kind", "source_key"]).execute();
10084
+ for (const row of closed) {
10085
+ const item = await trx.selectFrom("operator_item").select("id").where("item_key", "=", exhaustedItemKey(row)).where("cleared_at", "is", null).executeTakeFirst();
10086
+ if (item !== void 0) await clearItem(trx, item.id, at, actor);
10289
10087
  }
10290
10088
  }
10291
- /** The operator item kind raised when a notification's rings are exhausted. */
10292
- function exhaustedItemKind(n) {
10293
- return n.kind === "answer" ? "answer_undelivered" : "worker_not_reading";
10089
+ //#endregion
10090
+ //#region ../core/src/app/skill-reload.ts
10091
+ /** An installed spur-board version: strict semver with an optional prerelease. */
10092
+ const SKILL_VERSION = z.string().max(64).regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/);
10093
+ /** Session ids a caller already holds, checked as the session part of an agent actor ID. */
10094
+ const RELOAD_SESSIONS = z.array(z.string().max(128).refine((id) => actorIdSchema.safeParse(`agent:project/${id}`).success)).min(1).max(200);
10095
+ /** The fixed message a live session gets after an install of `version`. */
10096
+ function skillReloadText(version) {
10097
+ return `spur-board skill updated to ${version}. Before your next board command, read the spur-board skill file again: ~/.claude/skills/spur-board/SKILL.md (Claude Code) or $CODEX_HOME/skills/spur-board/SKILL.md, by default ~/.codex/skills/spur-board/SKILL.md (Codex).`;
10294
10098
  }
10295
- /** The operator item key raised when a notification's rings are exhausted. */
10296
- function exhaustedItemKey(n) {
10297
- return `${exhaustedItemKind(n)}:${n.source_key}`;
10099
+ /**
10100
+ * Queues the reload message for every live session of a configured Spur project, any role.
10101
+ * Returns how many rows this call inserted: a session told about `version` before gets none.
10102
+ */
10103
+ async function requestSkillReload(store, config, version, at) {
10104
+ const projects = [...new Set(config.projects.flatMap((project) => project.spurProjects.map((spur) => spur.name)))];
10105
+ if (projects.length === 0) return { queued: 0 };
10106
+ const text = skillReloadText(version);
10107
+ return store.transaction(async (trx) => {
10108
+ const sessions = await trx.selectFrom("session_snapshot").select("id").where("spur_project", "in", projects).where("ended_at", "is", null).where("absent_since", "is", null).where("state", "not in", FINISHED_STATES).orderBy("id").execute();
10109
+ let queued = 0;
10110
+ for (const session of sessions) if (await enqueueSkillReload(trx, {
10111
+ session: session.id,
10112
+ version,
10113
+ text,
10114
+ at
10115
+ })) queued += 1;
10116
+ return { queued };
10117
+ });
10298
10118
  }
10119
+ const STATES = {
10120
+ done: "delivered",
10121
+ pending: "pending",
10122
+ in_flight: "pending",
10123
+ dead: "failed",
10124
+ post_failed: "failed"
10125
+ };
10126
+ const storedPayload = z.looseObject({
10127
+ session: z.string(),
10128
+ queuedAt: z.string().optional()
10129
+ });
10299
10130
  /**
10300
- * Restart an exhausted, unacknowledged ring series at `at`. The recipient and last row stay, so
10301
- * the next reconcile rings the same session under the next series key.
10131
+ * The reload record of each named session for `version`, sorted by id. A session without a
10132
+ * record is left out, and no session the caller did not name is ever returned.
10302
10133
  */
10303
- async function restartNotification(trx, sourceKey, at) {
10304
- if (await trx.updateTable("notification").set({
10305
- rings: 0,
10306
- exhausted_at: null,
10307
- next_at: at.toISOString()
10308
- }).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.");
10134
+ async function skillReloads(db, version, sessions) {
10135
+ const keys = new Map(sessions.map((session) => [skillReloadKey(version, session), session]));
10136
+ if (keys.size === 0) return [];
10137
+ return (await db.selectFrom("outbox").select([
10138
+ "dedupe_key",
10139
+ "state",
10140
+ "payload"
10141
+ ]).where("kind", "=", "doorbell").where("dedupe_key", "in", [...keys.keys()]).execute()).flatMap((row) => {
10142
+ const id = keys.get(row.dedupe_key);
10143
+ if (id === void 0) return [];
10144
+ let queuedAt = null;
10145
+ try {
10146
+ const payload = storedPayload.safeParse(JSON.parse(row.payload));
10147
+ if (payload.success && payload.data.session === id) queuedAt = payload.data.queuedAt ?? null;
10148
+ } catch {}
10149
+ return [{
10150
+ id,
10151
+ state: STATES[row.state],
10152
+ queuedAt
10153
+ }];
10154
+ }).sort((left, right) => left.id < right.id ? -1 : left.id > right.id ? 1 : 0);
10309
10155
  }
10156
+ //#endregion
10157
+ //#region ../core/src/app/tokens.ts
10158
+ const REQUEST_LIFETIME_MS = 900 * 1e3;
10159
+ const MAX_PENDING_REQUESTS = 10;
10160
+ /** Days an expired or denied request stays after its decision before the daily purge drops it. */
10161
+ const TOKEN_REQUEST_RETENTION_DAYS = 7;
10162
+ const DAY_MS$1 = 864e5;
10310
10163
  /**
10311
- * Ends a notification's ring series. A curator block moves to the operator; a removal, a turn
10312
- * reminder or a ring with no session to name ends alone; anything else raises the operator item, whose Retry restarts
10313
- * the series (`restartNotification`). Every end journals `doorbell_undelivered`.
10164
+ * Code-point caps that keep a legacy name or folder from overflowing a card, line or button. A
10165
+ * messenger may escape a point to five characters; a card of all-escaped points still fits 2900.
10314
10166
  */
10315
- async function endNotification(trx, n, task, end) {
10316
- const { session, reason, at, config } = end;
10317
- await trx.updateTable("notification").set({ exhausted_at: at.toISOString() }).where("id", "=", n.id).execute();
10318
- const addressee = parseAddressee(n.role);
10319
- if (n.kind === "block" && addressee.kind === "curator") await moveBlockToAddressee(trx, {
10320
- task,
10321
- block: await trx.selectFrom("block").selectAll().where("id", "=", noticeBlockId(n)).executeTakeFirstOrThrow(),
10322
- to: "operator",
10323
- reason,
10324
- ctx: {
10325
- actor: "system",
10326
- at: at.toISOString()
10327
- },
10328
- config
10329
- });
10330
- else if (n.kind !== "removed" && n.kind !== "turn_reminder" && session !== null) {
10331
- const blockRef = noticeRef(n, task);
10332
- const answer = `Answer to ${blockRef} was not`;
10333
- const holder = `${addressee.kind} ${session}`;
10334
- await raiseItem(trx, {
10335
- itemKey: exhaustedItemKey(n),
10336
- kind: exhaustedItemKind(n),
10337
- 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}`,
10338
- url: taskUrl(task, config),
10339
- taskId: task.id,
10340
- blockId: n.block_id,
10341
- at
10342
- });
10343
- }
10344
- await journal$2(trx, n, "doorbell_undelivered", {
10345
- doorbell: `N${String(n.id)}`,
10346
- reason
10347
- }, at);
10167
+ const CARD_NAME = 64;
10168
+ const CARD_FOLDER = 400;
10169
+ const LIST_NAME = 64;
10170
+ const LIST_FOLDER = 120;
10171
+ const LABEL_NAME = 40;
10172
+ /** Tokens in one token-list feed line that get a row and a Revoke button. */
10173
+ const LIST_BUTTONS = 20;
10174
+ /**
10175
+ * Escaped characters the rows and the `N more` line of a token list may take, each row counted
10176
+ * with its newline and quote marks; the feed key fills the rest of one 2900-character part.
10177
+ */
10178
+ const LIST_TEXT = 2800;
10179
+ /** Kept for the `N more` line. */
10180
+ const LIST_MORE = 40;
10181
+ /** An approved token's last use is written at most once per token per this interval. */
10182
+ const TOKEN_USE_INTERVAL_MS = 5 * 6e4;
10183
+ /** The longest attention line; the doctor fix limit is the same. */
10184
+ const ATTENTION_LINE_MAX = 300;
10185
+ /** The Revoke button of the token approved through item `itemId`, on its card or in a list. */
10186
+ function revokeAction(itemId, name, label) {
10187
+ return {
10188
+ id: `token:${String(itemId)}:revoke`,
10189
+ label,
10190
+ confirm: `Revoke operator token ${capPoints(name, CARD_NAME)}? Calls with it fail at once.`
10191
+ };
10192
+ }
10193
+ /** The card of token `row` approved at `approvedAt`, its name and folder capped. */
10194
+ function cardOf(row, approvedAt) {
10195
+ return {
10196
+ name: capPoints(row.name, CARD_NAME),
10197
+ folder: capPoints(row.folder, CARD_FOLDER),
10198
+ createdAt: row.requested_at,
10199
+ approvedAt
10200
+ };
10201
+ }
10202
+ /** The length of `text` once a messenger escapes it: `&`, `<` and `>` take up to five characters. */
10203
+ function escapedLength(text) {
10204
+ return text.length + 4 * (text.match(/[&<>]/g)?.length ?? 0);
10205
+ }
10206
+ function effectiveStatus(row, at) {
10207
+ return row.status === "pending" && row.expires_at <= at.toISOString() ? "expired" : row.status;
10208
+ }
10209
+ async function journalToken(trx, kind, name, at) {
10210
+ await emit(trx, kind, RESERVED_PROJECT, null, at.toISOString(), { name }, kind === "token_approved" || kind === "token_denied" || kind === "token_revoked" ? "operator" : "system");
10211
+ }
10212
+ /** Lapse one pending request: journal it once and clear its approval item. */
10213
+ async function expireToken(trx, row, at) {
10214
+ await trx.updateTable("operator_token").set({
10215
+ status: "expired",
10216
+ decided_at: at.toISOString()
10217
+ }).where("id", "=", row.id).execute();
10218
+ await journalToken(trx, "token_expired", row.name, at);
10219
+ await clearItem(trx, row.item_id, at);
10348
10220
  }
10349
10221
  /**
10350
- * Ends a ring Spur will not take (a permanent rejection, or no answer for the retry window). A
10351
- * ring that is no longer its notification's last row (the recipient changed while it was in
10352
- * flight) ends alone. An inbound author ring has no notification: it ends like an author found
10353
- * unavailable at enqueue.
10222
+ * Lapses the pending request whose approval item is `itemId` once it has expired at `at`. The
10223
+ * sender calls it before posting the approval line, so a late or failing sweep cannot post it.
10354
10224
  */
10355
- async function ringUndelivered(trx, input) {
10356
- const { at, reason } = input;
10357
- if (input.notificationId === void 0) {
10358
- const task = await ringTask(trx, void 0, input.dedupeKey);
10359
- if (task === void 0) return;
10360
- await emit(trx, "doorbell_undelivered", task.project, task.id, at.toISOString(), {
10361
- doorbell: input.dedupeKey,
10362
- reason
10363
- });
10364
- await raiseItem(trx, {
10365
- itemKey: `doorbell:unavailable:${input.dedupeKey}`,
10366
- kind: "answer_author_unavailable",
10367
- text: `Answer author unavailable: ${reason}`,
10368
- url: taskUrl(task, input.config),
10369
- taskId: task.id,
10225
+ async function expireTokenOfItem(trx, itemId, at) {
10226
+ const row = await trx.selectFrom("operator_token").select([
10227
+ "id",
10228
+ "name",
10229
+ "item_id"
10230
+ ]).where("item_id", "=", itemId).where("status", "=", "pending").where("expires_at", "<=", at.toISOString()).executeTakeFirst();
10231
+ if (row !== void 0) await expireToken(trx, row, at);
10232
+ }
10233
+ /** Fixed per-field text: the hint never echoes the value or an unknown key. */
10234
+ const REQUEST_FIELD_HINTS = {
10235
+ name: `Fix \`name\`: use 1-${String(TOKEN_REQUEST_LIMITS.name)} characters, each a letter, digit, ".", "_" or "-".`,
10236
+ folder: `Fix \`folder\`: use 1-${String(TOKEN_REQUEST_LIMITS.folder)} characters, not only spaces, with no control or format characters.`,
10237
+ host: `Fix \`host\`: use 1-${String(TOKEN_REQUEST_LIMITS.host)} characters with no control or format characters.`,
10238
+ hash: "Fix `hash`: send the 64-character lowercase hex SHA-256 of the token."
10239
+ };
10240
+ /** Register a hash and its approval item together. The raw file secret never reaches this app. */
10241
+ async function requestToken(store, config, body, at) {
10242
+ const parsed = tokenRequestSchema.safeParse(body);
10243
+ if (!parsed.success) {
10244
+ const field = parsed.error.issues[0]?.path[0];
10245
+ throw new CommandError("usage", (typeof field === "string" ? REQUEST_FIELD_HINTS[field] : void 0) ?? "Send a JSON object with only name, folder, host and hash.");
10246
+ }
10247
+ const input = parsed.data;
10248
+ const expiresAt = new Date(at.getTime() + REQUEST_LIFETIME_MS).toISOString();
10249
+ return scanTransaction(store, config, async (trx) => {
10250
+ const existing = await trx.selectFrom("operator_token").selectAll().where("name", "=", input.name).executeTakeFirst();
10251
+ const status = existing === void 0 ? void 0 : effectiveStatus(existing, at);
10252
+ if (status === "pending" || status === "approved" || status === "revoked") throw new CommandError("usage", `Token name ${input.name} is taken; choose another name (see \`board token list\`).`);
10253
+ if ((await trx.selectFrom("operator_token").select("id").where("status", "=", "pending").where("expires_at", ">", at.toISOString()).limit(MAX_PENDING_REQUESTS).execute()).length >= MAX_PENDING_REQUESTS) throw new CommandError("usage", "Too many token requests are awaiting approval.");
10254
+ if (existing?.status === "pending") await expireToken(trx, existing, at);
10255
+ const item = await raiseItem(trx, {
10256
+ itemKey: `token:${input.name}`,
10257
+ kind: "token_request",
10258
+ text: `Approve operator token ${input.name} (request ${requestHashOf(input.hash)}) for ${input.folder} on ${input.host}, requested ${at.toISOString()}?`,
10259
+ url: "",
10260
+ taskId: null,
10370
10261
  blockId: null,
10371
10262
  at
10372
10263
  });
10373
- return;
10374
- }
10375
- const n = await trx.selectFrom("notification").selectAll().where("id", "=", input.notificationId).executeTakeFirst();
10376
- if (n === void 0 || n.acked_at !== null || n.exhausted_at !== null || n.last_outbox_id !== input.outboxId) return;
10377
- await endNotification(trx, n, await trx.selectFrom("task").selectAll().where("id", "=", n.task_id).executeTakeFirstOrThrow(), {
10378
- session: input.session,
10379
- reason,
10380
- at,
10381
- config: input.config
10264
+ const values = {
10265
+ hash: input.hash,
10266
+ folder: input.folder,
10267
+ host: input.host,
10268
+ status: "pending",
10269
+ requested_at: at.toISOString(),
10270
+ expires_at: expiresAt,
10271
+ decided_at: null,
10272
+ item_id: item.id
10273
+ };
10274
+ if (existing === void 0) await trx.insertInto("operator_token").values({
10275
+ name: input.name,
10276
+ ...values
10277
+ }).execute();
10278
+ else await trx.updateTable("operator_token").set(values).where("id", "=", existing.id).execute();
10279
+ await journalToken(trx, "token_requested", input.name, at);
10280
+ return {
10281
+ name: input.name,
10282
+ status: "pending",
10283
+ expiresAt
10284
+ };
10382
10285
  });
10383
10286
  }
10384
- /** Why a notification with no recipient ends now, or null when it stays due for a next session. */
10385
- function noRecipientEnd(n) {
10386
- if (n.kind === "removed" || n.kind === "turn_reminder" || n.kind === "answer" && n.role === "operator") return "no live addressee";
10387
- return n.kind === "block" && n.role === "curator" ? "no live curator session" : null;
10388
- }
10389
- /** A ring never carries comment or reason text: only where to look. */
10390
- async function ringText(trx, n, task, ring) {
10391
- const suffix = ringMarker(n.id, ring);
10392
- if (n.kind === "turn") return `${task.key} turn T${String(n.turn_id)}: check board inbox ${suffix}`;
10393
- if (n.kind === "turn_reminder") return `${task.key} turn T${String(n.turn_id)} is still open: check board inbox ${suffix}`;
10394
- const blockId = noticeBlockId(n);
10395
- if (n.kind !== "removed") return `${task.key} block B${String(blockId)}: check board inbox ${suffix}`;
10396
- const block = await trx.selectFrom("block").select("unblocked_by").where("id", "=", blockId).executeTakeFirstOrThrow();
10397
- return `${task.key} block B${String(blockId)} was removed by ${block.unblocked_by ?? "system"}; see board task ${task.key} ${suffix}`;
10287
+ /** Called within the inbound event's transaction, after the gateway user and space are checked. */
10288
+ async function decideTokenInTransaction(trx, itemId, decision, at) {
10289
+ const row = await trx.selectFrom("operator_token").selectAll().where("item_id", "=", itemId).executeTakeFirst();
10290
+ if (row === void 0) throw new CommandError("not_found", "Token request was not found.");
10291
+ const status = effectiveStatus(row, at);
10292
+ if (status !== "pending") {
10293
+ if (status === "expired" && row.status === "pending") await expireToken(trx, row, at);
10294
+ return {
10295
+ name: row.name,
10296
+ status
10297
+ };
10298
+ }
10299
+ const next = decision === "approve" ? "approved" : "denied";
10300
+ await trx.updateTable("operator_token").set({
10301
+ status: next,
10302
+ decided_at: at.toISOString(),
10303
+ ...next === "approved" ? { approved_at: at.toISOString() } : {}
10304
+ }).where("id", "=", row.id).execute();
10305
+ await journalToken(trx, decision === "approve" ? "token_approved" : "token_denied", row.name, at);
10306
+ await clearItem(trx, row.item_id, at, "operator", decision === "approve" ? (item, lineId) => enqueueTokenCard(trx, {
10307
+ itemId: item.id,
10308
+ parent: lineId,
10309
+ card: cardOf(row, at.toISOString()),
10310
+ actions: [revokeAction(item.id, row.name, "Revoke")],
10311
+ at
10312
+ }) : void 0);
10313
+ return {
10314
+ name: row.name,
10315
+ status: next
10316
+ };
10398
10317
  }
10399
- /** Notifications reconcile looks at: unacked, not exhausted, due, on a task not archived. */
10400
- function dueNotifications(db, at) {
10401
- return db.selectFrom("notification").innerJoin("task", "task.id", "notification.task_id").where("task.membership", "!=", "archived").where("notification.acked_at", "is", null).where("notification.exhausted_at", "is", null).where("notification.next_at", "<=", at.toISOString());
10318
+ /** Clear unreviewed requests even when no approval button is pressed. */
10319
+ async function expirePendingTokens(store, config, at) {
10320
+ const expiresAt = at.toISOString();
10321
+ if (await store.db.selectFrom("operator_token").select("id").where("status", "=", "pending").where("expires_at", "<=", expiresAt).executeTakeFirst() === void 0) return 0;
10322
+ return scanTransaction(store, config, async (trx) => {
10323
+ const rows = await trx.selectFrom("operator_token").select([
10324
+ "id",
10325
+ "name",
10326
+ "item_id"
10327
+ ]).where("status", "=", "pending").where("expires_at", "<=", expiresAt).execute();
10328
+ for (const row of rows) await expireToken(trx, row, at);
10329
+ return rows.length;
10330
+ });
10402
10331
  }
10403
10332
  /**
10404
- * Reconciles due notifications in their own transaction. With none due it opens no transaction;
10405
- * a due notification waiting on a working recipient, an unsent ring or a ring still in the
10406
- * recipient's Spur queue still opens one.
10333
+ * Deletes expired and denied requests decided more than the retention period before `at`; a row
10334
+ * exactly at the cutoff stays. Approved, revoked and pending rows and every approval item stay.
10407
10335
  */
10408
- async function reconcileDueDoorbells(store, config, at) {
10409
- if (await dueNotifications(store.db, at).select("notification.id").executeTakeFirst() === void 0) return;
10410
- await scanTransaction(store, config, (trx) => reconcileDoorbells(trx, at, config));
10336
+ async function purgeEndedTokenRequests(store, at) {
10337
+ const cutoff = (/* @__PURE__ */ new Date(at.getTime() - TOKEN_REQUEST_RETENTION_DAYS * DAY_MS$1)).toISOString();
10338
+ return store.transaction(async (trx) => {
10339
+ const deleted = await trx.deleteFrom("operator_token").where("status", "in", ["expired", "denied"]).where("decided_at", "<", cutoff).executeTakeFirst();
10340
+ return Number(deleted.numDeletedRows);
10341
+ });
10411
10342
  }
10412
- /** Reconcile due semantic notifications in the caller's transaction. */
10413
- async function reconcileDoorbells(trx, at, config) {
10414
- const due = await dueNotifications(trx, at).selectAll("notification").orderBy("notification.id").execute();
10415
- for (const n of due) {
10416
- const session = await selectNotificationRecipient(trx, n, config);
10417
- const keepsRings = resolvedByProject(n.role);
10418
- if (session === void 0) {
10419
- const reason = noRecipientEnd(n);
10420
- if (reason !== null) await endNotification(trx, n, await trx.selectFrom("task").selectAll().where("id", "=", n.task_id).executeTakeFirstOrThrow(), {
10421
- session: null,
10422
- reason,
10423
- at,
10424
- config
10425
- });
10426
- else if (n.recipient_session !== null) await trx.updateTable("notification").set({
10427
- recipient_session: null,
10428
- rings: keepsRings ? n.rings : 0,
10429
- last_outbox_id: null
10430
- }).where("id", "=", n.id).execute();
10431
- continue;
10432
- }
10433
- if (recipientBusy(session) && !await spurBlind$1(trx)) continue;
10434
- let rings = n.rings;
10435
- let lastOutbox = n.last_outbox_id;
10436
- if (session.id !== n.recipient_session) {
10437
- if (lastOutbox !== null) await trx.updateTable("outbox").set({
10438
- state: "dead",
10439
- last_error: "recipient changed"
10440
- }).where("id", "=", lastOutbox).where("state", "=", "pending").execute();
10441
- if (!keepsRings) rings = 0;
10442
- lastOutbox = null;
10443
- await trx.updateTable("notification").set({
10444
- recipient_session: session.id,
10445
- rings,
10446
- last_outbox_id: null
10447
- }).where("id", "=", n.id).execute();
10448
- }
10449
- if (lastOutbox !== null) {
10450
- const row = await trx.selectFrom("outbox").select("state").where("id", "=", lastOutbox).executeTakeFirst();
10451
- if (row?.state === "pending" || row?.state === "in_flight") continue;
10452
- }
10453
- const task = await trx.selectFrom("task").selectAll().where("id", "=", n.task_id).executeTakeFirstOrThrow();
10454
- if (rings >= 3) {
10455
- await endNotification(trx, n, task, {
10456
- session: session.id,
10457
- reason: UNANSWERED,
10458
- at,
10459
- config
10460
- });
10461
- continue;
10462
- }
10463
- if (rings > 0 && earlierRingQueued(session, n.id, rings) && !await spurBlind$1(trx)) {
10464
- const pauses = ringPauses(config);
10465
- const deadline = Date.parse(n.next_at) + pauses.slice(rings).reduce((sum, pause) => sum + pause, 0);
10466
- if (at.getTime() >= deadline) await endNotification(trx, n, task, {
10467
- session: session.id,
10468
- reason: UNANSWERED,
10469
- at,
10470
- config
10471
- });
10472
- continue;
10473
- }
10474
- const raised = await trx.selectFrom("operator_item").select((eb) => eb.fn.max("raise_no").as("series")).where("item_key", "=", exhaustedItemKey(n)).executeTakeFirst();
10475
- const archived = await trx.selectFrom("event").select((eb) => eb.fn.countAll().as("count")).where("task_id", "=", n.task_id).where("kind", "=", "task_archived").executeTakeFirst();
10476
- 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;
10477
- const ring = rings + 1;
10478
- const text = await ringText(trx, n, task, ring);
10479
- const outboxId = await enqueueDoorbell(trx, {
10480
- notificationId: n.id,
10481
- ring,
10482
- session: session.id,
10483
- text,
10484
- at,
10485
- series: raised?.series ?? 0,
10486
- archives: archived?.count ?? 0,
10487
- moves: killed?.count ?? 0
10488
- });
10489
- await trx.updateTable("notification").set({ last_outbox_id: outboxId }).where("id", "=", n.id).execute();
10343
+ /**
10344
+ * Hash lookup uses the unique index and checks durable state on every call. An approved token's
10345
+ * use at `at` is recorded when its last recorded use is older than `TOKEN_USE_INTERVAL_MS`; a
10346
+ * failed write goes to `onUseError` and never changes the result.
10347
+ */
10348
+ async function verifyOperatorToken(store, token, at, onUseError) {
10349
+ const hash = createHash("sha256").update(token).digest("hex");
10350
+ const row = await store.db.selectFrom("operator_token").select([
10351
+ "name",
10352
+ "status",
10353
+ "last_used_at"
10354
+ ]).where("hash", "=", hash).executeTakeFirst();
10355
+ if (row?.status !== "approved") return null;
10356
+ const usedAt = at.toISOString();
10357
+ const staleBy = (/* @__PURE__ */ new Date(at.getTime() - TOKEN_USE_INTERVAL_MS)).toISOString();
10358
+ if (row.last_used_at === null || row.last_used_at <= staleBy) try {
10359
+ await store.transaction((trx) => trx.updateTable("operator_token").set({ last_used_at: usedAt }).where("hash", "=", hash).where("status", "=", "approved").where((eb) => eb.or([eb("last_used_at", "is", null), eb("last_used_at", "<=", staleBy)])).execute());
10360
+ } catch (err) {
10361
+ onUseError(err);
10490
10362
  }
10363
+ return { name: row.name };
10491
10364
  }
10492
- /** The pause after each delivered ring of a series: before ring 2, before ring 3, then the end. */
10493
- function ringPauses(config) {
10494
- return [
10495
- config.doorbells.firstRetryMs,
10496
- config.doorbells.secondRetryMs,
10497
- config.doorbells.unansweredAfterMs
10498
- ];
10365
+ /** Read-only: an expired pending row is reported as expired but left for the sweep. */
10366
+ async function tokenStatusByHash(store, hash, at) {
10367
+ const row = await store.db.selectFrom("operator_token").selectAll().where("hash", "=", hash).executeTakeFirst();
10368
+ return row === void 0 ? "unknown" : effectiveStatus(row, at);
10499
10369
  }
10500
- /** The session's last observed Spur facts, or null when its detail does not parse. */
10501
- function observedFacts(session) {
10502
- let detail;
10503
- try {
10504
- detail = JSON.parse(session.detail);
10505
- } catch {
10506
- return null;
10507
- }
10508
- const fact = sessionFactsSchema.safeParse(detail);
10509
- return fact.success ? fact.data : null;
10370
+ function tokenListQuery(clock) {
10371
+ return {
10372
+ id: "token.list",
10373
+ resolveTargets: () => Promise.resolve([]),
10374
+ async run(trx) {
10375
+ const rows = await trx.selectFrom("operator_token").selectAll().orderBy("id").execute();
10376
+ const at = new Date(clock.now());
10377
+ return { tokens: rows.map((row) => ({
10378
+ name: row.name,
10379
+ folder: row.folder,
10380
+ status: effectiveStatus(row, at),
10381
+ createdAt: row.requested_at,
10382
+ approvedAt: row.approved_at,
10383
+ lastUsedAt: row.last_used_at
10384
+ })) };
10385
+ }
10386
+ };
10510
10387
  }
10511
10388
  /**
10512
- * Whether the session was last observed mid-turn. Only an observed `working` health counts: any
10513
- * other health, or a detail that does not parse, is rung.
10389
+ * Posts one feed line listing the approved and unexpired pending tokens under `key`, so a replay
10390
+ * of the same command posts none. The first ones that fit 20 rows and the escaped text budget
10391
+ * get a row and a Revoke button; the rest are counted. Returns how many are active and writes
10392
+ * nothing for none.
10514
10393
  */
10515
- function recipientBusy(session) {
10516
- return observedFacts(session)?.health === "working";
10394
+ async function postTokenList(trx, input) {
10395
+ const rows = (await trx.selectFrom("operator_token").selectAll().orderBy("id").execute()).map((row) => ({
10396
+ row,
10397
+ status: effectiveStatus(row, input.at)
10398
+ })).filter(({ status }) => status === "approved" || status === "pending");
10399
+ if (rows.length === 0) return 0;
10400
+ const lines = [];
10401
+ let used = LIST_MORE;
10402
+ for (const { row, status } of rows.slice(0, LIST_BUTTONS)) {
10403
+ const line = `${capPoints(row.name, LIST_NAME)} (${status}), ${capPoints(row.folder, LIST_FOLDER)}`;
10404
+ used += escapedLength(line) + 3;
10405
+ if (used > LIST_TEXT) break;
10406
+ lines.push(line);
10407
+ }
10408
+ const shown = rows.slice(0, lines.length);
10409
+ const hidden = rows.length - shown.length;
10410
+ if (hidden > 0) lines.push(`${String(hidden)} more: \`board token list\``);
10411
+ await enqueueBoardFeedLine(trx, {
10412
+ dedupeKey: `feed.line:token-list:${input.key}`,
10413
+ itemKey: `token-list:${input.key}`,
10414
+ text: lines.join("\n"),
10415
+ title: "Operator tokens",
10416
+ actions: shown.map(({ row }) => revokeAction(row.item_id, row.name, `Revoke ${capPoints(row.name, LABEL_NAME)}`)),
10417
+ at: input.at
10418
+ });
10419
+ return rows.length;
10517
10420
  }
10421
+ const tokenRevokeMutation = {
10422
+ id: "token.revoke",
10423
+ resolveTargets: () => Promise.resolve([]),
10424
+ async run(trx, input, ctx) {
10425
+ const row = await trx.selectFrom("operator_token").selectAll().where("name", "=", input.name).executeTakeFirst();
10426
+ if (row === void 0) throw new CommandError("not_found", "Token name was not found.");
10427
+ if (row.status !== "revoked") {
10428
+ const at = new Date(ctx.at);
10429
+ await trx.updateTable("operator_token").set({
10430
+ status: "revoked",
10431
+ decided_at: ctx.at
10432
+ }).where("id", "=", row.id).execute();
10433
+ await journalToken(trx, "token_revoked", row.name, at);
10434
+ await clearItem(trx, row.item_id, at, ctx.actor);
10435
+ const text = `token ${capPoints(row.name, CARD_NAME)} revoked`;
10436
+ await enqueueBoardFeedLine(trx, {
10437
+ dedupeKey: `feed.line:token-revoked:${String(row.id)}`,
10438
+ itemKey: `token-revoked:${String(row.id)}`,
10439
+ text,
10440
+ title: text,
10441
+ at
10442
+ });
10443
+ const card = row.status === "approved" ? await trx.selectFrom("outbox").select(["id", "state"]).where("dedupe_key", "=", tokenCardKey(row.item_id)).executeTakeFirst() : void 0;
10444
+ if (card !== void 0 && card.state !== "dead" && row.decided_at !== null) await enqueueTokenCard(trx, {
10445
+ itemId: row.item_id,
10446
+ parent: card.id,
10447
+ card: {
10448
+ ...cardOf(row, row.decided_at),
10449
+ revoked: {
10450
+ by: ctx.actor,
10451
+ at: ctx.at
10452
+ }
10453
+ },
10454
+ at
10455
+ });
10456
+ }
10457
+ return {
10458
+ name: row.name,
10459
+ status: "revoked"
10460
+ };
10461
+ }
10462
+ };
10518
10463
  /**
10519
- * Whether the session's facts list a ring of this series, up to `rings`, still in its Spur queue.
10520
- * A detail that does not parse, or one without a queue, holds nothing.
10464
+ * Approved tokens unused for `unusedAfterDays` days (last use, else approval, else request time)
10465
+ * or whose token file is gone. `probe` answers whether the token file is present, or null when
10466
+ * it cannot tell (another host, an unreadable folder); it runs after the read, outside any
10467
+ * transaction.
10521
10468
  */
10522
- function earlierRingQueued(session, notificationId, rings) {
10523
- return (observedFacts(session)?.queuedRings ?? []).some((queued) => queued.notification === notificationId && queued.ring <= rings);
10524
- }
10525
- /** Count one confirmed Spur send, regardless of transport attempts for its outbox row. */
10526
- async function recordRingDelivery(trx, notificationId, ring, session, at, config) {
10527
- const n = await trx.selectFrom("notification").selectAll().where("id", "=", notificationId).executeTakeFirst();
10528
- if (n === void 0 || n.acked_at !== null && n.kind !== "turn_reminder" || n.recipient_session !== session || n.rings >= ring) return;
10529
- const pauses = ringPauses(config);
10530
- await trx.updateTable("notification").set({
10531
- rings: ring,
10532
- next_at: new Date(at.getTime() + (pauses[ring - 1] ?? 0)).toISOString(),
10533
- ...n.kind === "removed" || n.kind === "turn_reminder" ? { acked_at: at.toISOString() } : {}
10534
- }).where("id", "=", notificationId).execute();
10535
- await journal$2(trx, n, "doorbell_rung", {
10536
- doorbell: `N${String(n.id)}`,
10537
- addressee: n.role,
10538
- attempt: ring
10539
- }, at);
10540
- }
10541
- /** True while the Spur source is blind: its stored session facts may no longer hold. */
10542
- async function spurBlind$1(trx) {
10543
- const state = await trx.selectFrom("source_state").select("blind_reason").where("source", "=", "spur").executeTakeFirst();
10544
- return state !== void 0 && state.blind_reason !== null;
10545
- }
10546
- /** Confirm that a queued ring still belongs to a live, idle, unread recipient. */
10547
- async function ringStillCurrent(trx, notificationId, sessionId, config) {
10548
- const n = await trx.selectFrom("notification").selectAll().where("id", "=", notificationId).executeTakeFirst();
10549
- if (n === void 0 || n.acked_at !== null || n.exhausted_at !== null || n.recipient_session !== sessionId) return "dead";
10550
- const session = await selectNotificationRecipient(trx, n, config);
10551
- if (session?.id !== sessionId) return "dead";
10552
- return recipientBusy(session) && !await spurBlind$1(trx) ? "defer" : "send";
10469
+ async function tokenAttention(store, at, unusedAfterDays, probe) {
10470
+ const rows = await store.db.selectFrom("operator_token").select([
10471
+ "name",
10472
+ "folder",
10473
+ "host",
10474
+ "requested_at",
10475
+ "approved_at",
10476
+ "last_used_at"
10477
+ ]).where("status", "=", "approved").orderBy("id").execute();
10478
+ const cutoff = (/* @__PURE__ */ new Date(at.getTime() - unusedAfterDays * DAY_MS$1)).toISOString();
10479
+ const attention = {
10480
+ fileMissing: [],
10481
+ unused: []
10482
+ };
10483
+ for (const row of rows) if (await probe({
10484
+ folder: row.folder,
10485
+ host: row.host
10486
+ }) === false) attention.fileMissing.push(row.name);
10487
+ else if ((row.last_used_at ?? row.approved_at ?? row.requested_at) <= cutoff) attention.unused.push(row.name);
10488
+ return attention;
10553
10489
  }
10554
10490
  /**
10555
- * The task of a ring: through its notification, or for an inbound author ring (no notification)
10556
- * through the comment in its `doorbell:comment:<id>:` key. Archive kills only unclaimed rings;
10557
- * the sender drops a claimed one of an archived task before its send starts.
10491
+ * One line naming the tokens in `attention`, at most 300 characters, or null when none needs
10492
+ * attention. Shared by `board doctor` and the daily digest. A name enrollment would refuse today
10493
+ * is counted, never printed; trailing names that do not fit become "and N more".
10558
10494
  */
10559
- async function ringTask(trx, notificationId, dedupeKey) {
10560
- const commentId = /^doorbell:comment:(\d+):/.exec(dedupeKey)?.[1];
10561
- if (notificationId === void 0 && commentId === void 0) return void 0;
10562
- const owner = notificationId !== void 0 ? trx.selectFrom("notification").select("task_id").where("id", "=", notificationId) : trx.selectFrom("comment").select("task_id").where("id", "=", Number(commentId));
10563
- return trx.selectFrom("task").selectAll().where("id", "in", owner).executeTakeFirst();
10564
- }
10565
- /** Stop notifications acknowledged by the addressed session. */
10566
- async function acknowledgeNotification(trx, input) {
10567
- let query = trx.selectFrom("notification").selectAll().where("acked_at", "is", null);
10568
- if (input.blockId !== void 0) query = query.where("block_id", "=", input.blockId).where("kind", "=", "block");
10569
- else if (input.commentId !== void 0) query = query.where("comment_id", "=", input.commentId).where("kind", "=", "answer");
10570
- else if (input.turnId !== void 0) query = query.where("turn_id", "=", input.turnId).where("kind", "=", "turn");
10571
- else return false;
10572
- const notices = await query.orderBy("id", "desc").execute();
10573
- const n = notices[0];
10574
- if (n === void 0) return false;
10575
- if (!await notificationAddressedTo(trx, n, input.actor, input.config)) throw new CommandError("forbidden", "Only the addressed task role can acknowledge.");
10576
- for (const notice of notices) {
10577
- await trx.updateTable("notification").set({ acked_at: input.at.toISOString() }).where("id", "=", notice.id).execute();
10578
- await journal$2(trx, notice, "doorbell_read", { doorbell: `N${String(notice.id)}` }, input.at);
10579
- const item = await trx.selectFrom("operator_item").select("id").where("item_key", "=", exhaustedItemKey(notice)).where("cleared_at", "is", null).executeTakeFirst();
10580
- if (item !== void 0) await clearItem(trx, item.id, input.at);
10581
- }
10582
- return true;
10583
- }
10584
- /** Decides who may list and acknowledge an inbox notice, by the role it is addressed to. */
10585
- async function notificationAddressedTo(trx, n, actor, config) {
10586
- const parsed = parseActorId(actor);
10587
- if (parsed?.actor !== "agent") return false;
10588
- const { project, session } = parsed.actorRef;
10589
- const addressee = parseAddressee(n.role);
10590
- switch (addressee.kind) {
10591
- case "curator": return project === curatorProject(config, await taskProject(trx, n.task_id));
10592
- case "orchestrator": return project === columnOrchestratorProject(config, await taskProject(trx, n.task_id), addressee.column) || await hasLiveLink(trx, n.task_id, "orchestrator", session);
10593
- case "operator": return session === n.author_session;
10594
- case "worker": return workerNotificationAddressedTo(trx, n, session, config);
10595
- default: return assertNever(addressee);
10495
+ function tokenAttentionLine(attention, unusedAfterDays) {
10496
+ const total = attention.fileMissing.length + attention.unused.length;
10497
+ if (total === 0) return null;
10498
+ const head = `${String(total)} operator ${total === 1 ? "token needs" : "tokens need"} attention (revoke any that nothing uses with \`board token revoke <name>\`)`;
10499
+ const printableNames = (names) => names.filter((name) => tokenRequestSchema.shape.name.safeParse(name).success);
10500
+ const printable = [{
10501
+ label: "no token file",
10502
+ names: printableNames(attention.fileMissing)
10503
+ }, {
10504
+ label: `unused for ${String(unusedAfterDays)}+ days`,
10505
+ names: printableNames(attention.unused)
10506
+ }];
10507
+ const named = printable.reduce((n, group) => n + group.names.length, 0);
10508
+ for (let shown = named; shown > 0; shown -= 1) {
10509
+ let left = shown;
10510
+ const parts = [];
10511
+ for (const { label, names } of printable) {
10512
+ const listed = names.slice(0, left);
10513
+ left -= listed.length;
10514
+ if (listed.length > 0) parts.push(`${label}: ${listed.join(", ")}`);
10515
+ }
10516
+ const more = total - shown;
10517
+ const line = `${head}: ${parts.join("; ")}${more > 0 ? ` and ${String(more)} more` : ""}`;
10518
+ if (line.length <= ATTENTION_LINE_MAX) return line;
10596
10519
  }
10520
+ return `${head}: ${String(total)} not named`;
10597
10521
  }
10598
- async function sessionLink(trx, taskId, role, session) {
10599
- return trx.selectFrom("link").select("id").where("task_id", "=", taskId).where("entity", "=", "session").where("role", "=", role).where("banned", "=", 0).where("session_id", "=", session).executeTakeFirst();
10522
+ //#endregion
10523
+ //#region ../core/src/api/identity.ts
10524
+ function sessionActor(project, session, config) {
10525
+ const actor = actorIdSchema.safeParse(`agent:${project}/${session}`);
10526
+ if (!actor.success) throw new CommandError("forbidden", "Invalid session identity.");
10527
+ const matches = config.projects.filter((entry) => entry.spurProjects.some((spur) => spur.name === project));
10528
+ if (matches.length === 0) throw new CommandError("forbidden", `Spur project "${project}" is not listed in any spurProjects in the Board's config.yaml (not Spur's spur.yaml), and inside a Spur session a token is not used. Ask the operator to add it under projects[].spurProjects there and restart the Board daemon, or run the command outside a Spur session.`);
10529
+ if (matches.length > 1) throw new CommandError("forbidden", `Spur project "${project}" is listed under several Board projects: ${matches.map((entry) => entry.id).join(", ")}. Ask the operator to keep it under one of them in the Board's config.yaml (not Spur's spur.yaml) and restart the Board daemon.`);
10530
+ return actor.data;
10600
10531
  }
10601
- async function hasLiveLink(trx, taskId, role, session) {
10602
- return await sessionLink(trx, taskId, role, session) !== void 0 && await liveSession(trx, session) !== void 0;
10532
+ /** Resolve the caller at the HTTP boundary; a session header always outranks a token. */
10533
+ async function identifyCaller(ports, headers) {
10534
+ const { session, authorization } = headers;
10535
+ if (session !== void 0) {
10536
+ if (!actorIdSchema.safeParse(`agent:project/${session}`).success) throw new CommandError("forbidden", "Invalid session identity.");
10537
+ const snapshot = await ports.store.db.selectFrom("session_snapshot").select([
10538
+ "spur_project",
10539
+ "ended_at",
10540
+ "raw_state",
10541
+ "state"
10542
+ ]).where("id", "=", session).executeTakeFirst();
10543
+ if (snapshot !== void 0) {
10544
+ if (snapshot.ended_at !== null || snapshot.raw_state === "completed" || snapshot.raw_state === "killed" || snapshot.state === "completed" || snapshot.state === "killed") throw new CommandError("forbidden", "The session has ended.");
10545
+ return { actor: sessionActor(snapshot.spur_project, session, ports.config) };
10546
+ }
10547
+ let live;
10548
+ try {
10549
+ live = await ports.lookupSession(session);
10550
+ } catch {
10551
+ throw new CommandError("identity_unavailable", "Session identity is unavailable.");
10552
+ }
10553
+ if (live === null) throw new CommandError("forbidden", "Unknown session.");
10554
+ if (typeof live !== "object" || typeof live.project !== "string" || typeof live.status !== "string" || !SESSION_STATUSES.some((status) => status === live.status)) throw new CommandError("identity_unavailable", "Invalid session response.");
10555
+ if (live.status === "completed" || live.status === "killed") throw new CommandError("forbidden", "The session has ended.");
10556
+ return { actor: sessionActor(live.project, session, ports.config) };
10557
+ }
10558
+ const bearer = authorization?.match(/^Bearer (\S+)$/i)?.[1];
10559
+ if (bearer !== void 0) try {
10560
+ const token = await ports.verifyToken(bearer);
10561
+ if (token !== null) return {
10562
+ actor: "operator",
10563
+ tokenName: token.name
10564
+ };
10565
+ } catch {
10566
+ throw new CommandError("identity_unavailable", "Token verification is unavailable.");
10567
+ }
10568
+ throw new CommandError("forbidden", "A session or accepted token is required.");
10603
10569
  }
10604
- /** The selected worker while it lives; before the first ring, the author or a linked worker. */
10605
- async function workerNotificationAddressedTo(trx, n, session, config) {
10606
- if (n.recipient_session === null) return session === n.author_session || await sessionLink(trx, n.task_id, "worker", session) !== void 0;
10607
- return await liveSession(trx, n.recipient_session) !== void 0 ? session === n.recipient_session : (await selectNotificationRecipient(trx, n, config))?.id === session;
10570
+ //#endregion
10571
+ //#region ../core/src/api/server.ts
10572
+ const doctorReportSchema = z.strictObject({
10573
+ version: z.string().min(1).max(50),
10574
+ checks: z.array(z.strictObject({
10575
+ id: z.string().regex(/^[a-z][a-z._]+$/).max(60),
10576
+ status: z.enum([
10577
+ "pass",
10578
+ "fail",
10579
+ "warning"
10580
+ ]),
10581
+ blocking: z.boolean(),
10582
+ fix: z.string().max(300).nullable()
10583
+ })).max(30)
10584
+ });
10585
+ const tokenStatusSchema = z.strictObject({ hash: tokenRequestSchema.shape.hash });
10586
+ const skillReloadSchema = z.strictObject({ version: SKILL_VERSION });
10587
+ const skillReloadsSchema = z.strictObject({
10588
+ version: SKILL_VERSION,
10589
+ sessions: RELOAD_SESSIONS
10590
+ });
10591
+ function header(value) {
10592
+ return Array.isArray(value) ? void 0 : value;
10608
10593
  }
10609
- /** Ends a block's ring series; its exhaustion item is cleared by `actor`, who closed the block. */
10610
- async function closeBlockNotification(trx, blockId, at, actor) {
10611
- await closeOwnedNotifications(trx, "block", blockId, at, actor);
10594
+ function inputBody(body) {
10595
+ if (body === null || typeof body !== "object" || Array.isArray(body)) throw new CommandError("usage", "Send a JSON object with input and optional key.");
10596
+ const record = body;
10597
+ if (!Object.hasOwn(record, "input") || Object.keys(record).some((name) => name !== "input" && name !== "key") || record["key"] !== void 0 && typeof record["key"] !== "string") throw new CommandError("usage", "Send a JSON object with input and optional key.");
10598
+ return {
10599
+ input: record["input"],
10600
+ key: record["key"]
10601
+ };
10612
10602
  }
10613
- /**
10614
- * Ends a turn's ring series and reminders for good: acked, and its exhaustion item cleared by the
10615
- * system.
10616
- */
10617
- async function closeTurnNotification(trx, turnId, at) {
10618
- await closeOwnedNotifications(trx, "turn", turnId, at, "system");
10603
+ /** Construct the local HTTP transport; the caller owns listen and close. */
10604
+ async function createApiServer(options) {
10605
+ const app = Fastify({
10606
+ logger: false,
10607
+ genReqId: () => randomUUID(),
10608
+ trustProxy: false
10609
+ });
10610
+ const snapshot = await buildCatalogSnapshot(OPERATIONS);
10611
+ /** Lets clients notice a daemon restart and check its catalog again. */
10612
+ const instance = randomUUID();
10613
+ const callers = /* @__PURE__ */ new WeakMap();
10614
+ let doctorInFlight = null;
10615
+ let doctorCached = null;
10616
+ let doctorNextProbeAt = 0;
10617
+ const notReady = () => options.stopping?.() === true ? new CommandError("stopping", "Wait until the daemon is running again.") : new CommandError("starting", "Wait until the daemon is ready.");
10618
+ app.addHook("onRequest", async (request, reply) => {
10619
+ reply.header("x-request-id", request.id);
10620
+ reply.header("x-board-instance", instance);
10621
+ if (request.headers.origin !== void 0) throw new CommandError("forbidden", "Browser origins are not accepted.");
10622
+ const address = app.server.address();
10623
+ const port = address !== null && typeof address === "object" ? address.port : options.port;
10624
+ if (header(request.headers.host) !== `127.0.0.1:${String(port)}`) throw new CommandError("forbidden", "Use the local API host.");
10625
+ const contentType = header(request.headers["content-type"]);
10626
+ const mediaType = contentType?.split(";", 1)[0]?.trim().toLowerCase();
10627
+ if (contentType !== void 0 && mediaType !== "application/json" || request.method === "POST" && mediaType !== "application/json") throw new CommandError("forbidden", "Use application/json.");
10628
+ });
10629
+ app.addHook("onResponse", (request, reply, done) => {
10630
+ const caller = callers.get(request);
10631
+ options.logRequest({
10632
+ requestId: request.id,
10633
+ method: request.method,
10634
+ url: request.url,
10635
+ status: reply.statusCode,
10636
+ ...caller?.tokenName === void 0 ? {} : { tokenName: caller.tokenName }
10637
+ });
10638
+ done();
10639
+ });
10640
+ app.setErrorHandler((error, request, reply) => {
10641
+ let code = "unexpected";
10642
+ let hint;
10643
+ if (error instanceof CommandError) {
10644
+ code = error.code;
10645
+ hint = error.hint;
10646
+ } else if (error instanceof Error && "statusCode" in error) {
10647
+ if (error.statusCode === 400 || error.statusCode === 413) code = "usage";
10648
+ if (error.statusCode === 413) hint = "Send a smaller JSON body.";
10649
+ }
10650
+ if (code === "unexpected") options.logError?.({
10651
+ requestId: request.id,
10652
+ err: error
10653
+ });
10654
+ const problem = renderHttpProblem({
10655
+ code,
10656
+ requestId: request.id
10657
+ });
10658
+ reply.code(problem.status).type("application/problem+json").send(hint === void 0 ? problem.body : {
10659
+ ...problem.body,
10660
+ hint
10661
+ });
10662
+ });
10663
+ app.setNotFoundHandler(() => {
10664
+ throw new CommandError("not_found", "This API route is not available.");
10665
+ });
10666
+ app.get("/v1/schema", async (_request, reply) => {
10667
+ if (!options.ready()) throw notReady();
10668
+ return reply.send(snapshot);
10669
+ });
10670
+ app.get("/v1/doctor", async (_request, reply) => {
10671
+ if (!options.ready()) throw notReady();
10672
+ if (options.doctor === void 0) throw new CommandError("not_found", "Doctor is unavailable.");
10673
+ if (doctorInFlight !== null) return reply.send(await doctorInFlight);
10674
+ if (options.clock.now() < doctorNextProbeAt) {
10675
+ if (doctorCached !== null) return reply.send(doctorCached);
10676
+ throw new CommandError("starting", "Retry board doctor in a few seconds.");
10677
+ }
10678
+ doctorNextProbeAt = options.clock.now() + 5e3;
10679
+ doctorInFlight = options.doctor().then((report) => doctorReportSchema.parse(report));
10680
+ try {
10681
+ doctorCached = await doctorInFlight;
10682
+ return await reply.send(doctorCached);
10683
+ } finally {
10684
+ doctorInFlight = null;
10685
+ }
10686
+ });
10687
+ app.get("/v1/health", async (_request, reply) => {
10688
+ if (!options.ready()) throw notReady();
10689
+ if (options.firstPollDone === void 0) throw new CommandError("not_found", "Health is unavailable.");
10690
+ return reply.send({ firstPollDone: await options.firstPollDone() });
10691
+ });
10692
+ app.post("/v1/tokens/requests", async (request, reply) => {
10693
+ if (!options.ready()) throw notReady();
10694
+ const result = await requestToken(options.store, options.config, request.body, new Date(options.clock.now()));
10695
+ return reply.send(successEnvelopeSchema.parse({
10696
+ ok: true,
10697
+ requestId: request.id,
10698
+ value: result
10699
+ }));
10700
+ });
10701
+ /** The hash travels in the body because request logs record the URL. */
10702
+ app.post("/v1/tokens/status", async (request, reply) => {
10703
+ if (!options.ready()) throw notReady();
10704
+ const parsed = tokenStatusSchema.safeParse(request.body);
10705
+ if (!parsed.success) throw new CommandError("usage", "Provide a SHA-256 token hash.");
10706
+ const status = await tokenStatusByHash(options.store, parsed.data.hash, new Date(options.clock.now()));
10707
+ return reply.send(successEnvelopeSchema.parse({
10708
+ ok: true,
10709
+ requestId: request.id,
10710
+ value: { status }
10711
+ }));
10712
+ });
10713
+ /** Anonymous: the message is fixed and goes at most once per session for the running version. */
10714
+ app.post("/v1/skills/reload", async (request, reply) => {
10715
+ if (!options.ready()) throw notReady();
10716
+ if (options.productVersion === void 0) throw new CommandError("not_found", "Skill reload is unavailable.");
10717
+ const parsed = skillReloadSchema.safeParse(request.body);
10718
+ if (!parsed.success) throw new CommandError("usage", "Send {\"version\": \"<x.y.z>\"} with the installed spur-board version.");
10719
+ if (parsed.data.version !== options.productVersion) throw new CommandError("version_mismatch", `The daemon runs ${options.productVersion}. Run \`board service restart\` to start the installed version.`);
10720
+ const { version } = parsed.data;
10721
+ const { queued } = await requestSkillReload(options.store, options.config, version, new Date(options.clock.now()));
10722
+ return reply.send(successEnvelopeSchema.parse({
10723
+ ok: true,
10724
+ requestId: request.id,
10725
+ value: {
10726
+ version,
10727
+ queued
10728
+ }
10729
+ }));
10730
+ });
10731
+ /** Session ids travel in the body because request logs record the URL; only named ids answer. */
10732
+ app.post("/v1/skills/reloads", async (request, reply) => {
10733
+ if (!options.ready()) throw notReady();
10734
+ const parsed = skillReloadsSchema.safeParse(request.body);
10735
+ if (!parsed.success) throw new CommandError("usage", "Send {\"version\": \"<x.y.z>\", \"sessions\": [\"<session id>\", ...]} with 1 to 200 session ids.");
10736
+ const { version, sessions } = parsed.data;
10737
+ const records = await skillReloads(options.store.db, version, sessions);
10738
+ return reply.send(successEnvelopeSchema.parse({
10739
+ ok: true,
10740
+ requestId: request.id,
10741
+ value: {
10742
+ version,
10743
+ sessions: records
10744
+ }
10745
+ }));
10746
+ });
10747
+ app.post("/v1/ops/:id", { onRequest: async (request) => {
10748
+ if (!options.ready()) throw notReady();
10749
+ const sessionHeader = request.headers["x-board-session"];
10750
+ if (Array.isArray(sessionHeader)) throw new CommandError("forbidden", "Use one session identity header.");
10751
+ callers.set(request, await identifyCaller(options, {
10752
+ session: sessionHeader,
10753
+ authorization: header(request.headers.authorization)
10754
+ }));
10755
+ } }, async (request, reply) => {
10756
+ const caller = callers.get(request);
10757
+ if (caller === void 0) throw new Error("Operation identity was not resolved.");
10758
+ const operation = OPERATIONS.find((entry) => entry.id === request.params.id);
10759
+ if (operation === void 0) throw new CommandError("version_mismatch", "This daemon does not know the operation. Run `board service restart` to update the daemon, then retry.");
10760
+ const body = inputBody(request.body);
10761
+ const parsed = operation.input.safeParse(body.input);
10762
+ if (!parsed.success) throw new CommandError(errorCodeOf(parsed.error), "Fix the operation input.");
10763
+ const dispatch = () => dispatchOperation(options, operation.id, parsed.data, caller.actor, body.key);
10764
+ const result = await (options.runOperation === void 0 ? dispatch() : options.runOperation(operation.id, parsed.data, dispatch));
10765
+ await options.afterOperation?.(reply.raw);
10766
+ return reply.send(successEnvelopeSchema.parse({
10767
+ ok: true,
10768
+ requestId: request.id,
10769
+ value: result
10770
+ }));
10771
+ });
10772
+ return app;
10619
10773
  }
10620
- async function closeOwnedNotifications(trx, kind, ownerId, at, actor) {
10621
- const closed = await trx.updateTable("notification").set({ acked_at: at.toISOString() }).where(kind === "block" ? "block_id" : "turn_id", "=", ownerId).where("kind", "in", kind === "block" ? ["block"] : ["turn", "turn_reminder"]).where("acked_at", "is", null).returning(["kind", "source_key"]).execute();
10622
- for (const row of closed) {
10623
- const item = await trx.selectFrom("operator_item").select("id").where("item_key", "=", exhaustedItemKey(row)).where("cleared_at", "is", null).executeTakeFirst();
10624
- if (item !== void 0) await clearItem(trx, item.id, at, actor);
10625
- }
10774
+ /** The only supported listener for the local API. */
10775
+ function listenApiServer(app, port) {
10776
+ return app.listen({
10777
+ host: "127.0.0.1",
10778
+ port
10779
+ });
10626
10780
  }
10627
10781
  //#endregion
10628
10782
  //#region ../core/src/app/turns.ts
@@ -11057,11 +11211,11 @@ function wroteBlock(config, actor, target) {
11057
11211
  target
11058
11212
  }).status === "allowed";
11059
11213
  }
11060
- async function addComment(trx, task, block, text, ctx, addressee, config, options = {}) {
11061
- const { source, ringsAuthor = true } = options;
11214
+ /** Inserts a comment row and journals `comment_added`; it rings and posts nothing. */
11215
+ async function insertComment(trx, task, blockId, text, ctx, addressee, source, forwardedFrom) {
11062
11216
  const row = await trx.insertInto("comment").values({
11063
11217
  task_id: task.id,
11064
- block_id: block?.id ?? null,
11218
+ block_id: blockId,
11065
11219
  author: ctx.actor,
11066
11220
  text,
11067
11221
  revision: 1,
@@ -11073,8 +11227,14 @@ async function addComment(trx, task, block, text, ctx, addressee, config, option
11073
11227
  }).returningAll().executeTakeFirstOrThrow();
11074
11228
  await journal$1(trx, task, ctx, "comment_added", {
11075
11229
  comment: commentId(row.id),
11076
- addressee
11230
+ addressee,
11231
+ ...forwardedFrom === void 0 ? {} : { forwardedFrom: commentId(forwardedFrom) }
11077
11232
  });
11233
+ return row;
11234
+ }
11235
+ async function addComment(trx, task, block, text, ctx, addressee, config, options = {}) {
11236
+ const { source, ringsAuthor = true } = options;
11237
+ const row = await insertComment(trx, task, block?.id ?? null, text, ctx, addressee, source);
11078
11238
  if (ringsAuthor) await applyDoorbellPolicy(trx, block === void 0 ? { kind: "task_comment" } : {
11079
11239
  kind: "answer",
11080
11240
  block,
@@ -11123,23 +11283,65 @@ async function openBlock(trx, task, type, reason, ctx, config, addressee) {
11123
11283
  return row;
11124
11284
  }
11125
11285
  /**
11126
- * Opens a `system` question to the operator on a condition only the operator can fix, with its
11127
- * thread. The caller raises the ledger item that names the block.
11286
+ * Opens a `system` question to `addressee` (the operator by default) on a condition the board
11287
+ * cannot settle, with its thread once the operator holds it. The caller raises the ledger item
11288
+ * that names the block.
11128
11289
  */
11129
11290
  async function openSystemBlock(trx, input) {
11130
- const { task, reason, at, config } = input;
11291
+ const { task, reason, at, config, addressee = "operator" } = input;
11131
11292
  const ctx = {
11132
11293
  actor: "system",
11133
11294
  at
11134
11295
  };
11135
- const block = await openBlock(trx, task, "needs_input", reason, ctx, config, "operator");
11296
+ const block = await openBlock(trx, task, "needs_input", reason, ctx, config, addressee);
11136
11297
  await queueBlockOpen(trx, task, block, ctx, config);
11137
11298
  return block;
11138
11299
  }
11139
11300
  /**
11301
+ * Copies the answer to a course check to the task as a comment without a block, so the worker
11302
+ * reads it in its inbox: the close reason, else the closing actor's newest comment on the block.
11303
+ * A copied comment is named in the copy's `comment_added`, so its edits reach the copy.
11304
+ */
11305
+ async function forwardCourseNote(trx, task, block, ctx, reason) {
11306
+ if (reason !== null) {
11307
+ await insertComment(trx, task, null, reason, ctx, "worker");
11308
+ return;
11309
+ }
11310
+ const answer = await trx.selectFrom("comment").select(["id", "text"]).where("block_id", "=", block.id).where("author", "=", ctx.actor).orderBy("id", "desc").executeTakeFirst();
11311
+ if (answer === void 0) return;
11312
+ await insertComment(trx, task, null, answer.text, ctx, "worker", void 0, answer.id);
11313
+ }
11314
+ /** The comments `forwardCourseNote` copied from comment `id`. */
11315
+ async function forwardedCopies(trx, id) {
11316
+ const ids = (await trx.selectFrom("event").select("payload").where("kind", "=", "comment_added").where(sql`json_extract(payload, '$.forwardedFrom') = ${commentId(id)}`).execute()).flatMap(({ payload }) => {
11317
+ const parsed = eventPayloadSchemas.comment_added.safeParse(JSON.parse(payload));
11318
+ return parsed.success ? [idNumber(parsed.data.comment)] : [];
11319
+ });
11320
+ if (ids.length === 0) return [];
11321
+ return trx.selectFrom("comment").selectAll().where("id", "in", ids).execute();
11322
+ }
11323
+ /** Writes an edit to one comment by the acknowledgment rule, with its `comment_edited`. */
11324
+ async function reviseComment(trx, task, comment, text, ctx) {
11325
+ const next = editComment(comment.revision, comment.acked_revision);
11326
+ const updated = await trx.updateTable("comment").set({
11327
+ text,
11328
+ revision: next.revision
11329
+ }).where("id", "=", comment.id).returningAll().executeTakeFirstOrThrow();
11330
+ await journal$1(trx, task, ctx, "comment_edited", {
11331
+ comment: commentId(comment.id),
11332
+ revision: next.revision,
11333
+ clarification: next.clarification
11334
+ });
11335
+ return {
11336
+ updated,
11337
+ clarification: next.clarification
11338
+ };
11339
+ }
11340
+ /**
11140
11341
  * Unblocks one block with its journal entry, thread close, doorbell close and item clears. An
11141
11342
  * operator or agent close of a reconciled ledger block dismisses its item, so the condition
11142
- * raises again only once it changes; a `system` or archive close only clears it.
11343
+ * raises again only once it changes; a `system` or archive close only clears it. An answer or a
11344
+ * close with a reason to a course check also goes to the worker as a task comment.
11143
11345
  */
11144
11346
  async function closeOpenBlock(trx, task, block, ctx, outcome, outcomeReason) {
11145
11347
  const updated = await trx.updateTable("block").set({
@@ -11162,6 +11364,7 @@ async function closeOpenBlock(trx, task, block, ctx, outcome, outcomeReason) {
11162
11364
  });
11163
11365
  await closeBlockNotification(trx, block.id, new Date(ctx.at), ctx.actor);
11164
11366
  const items = await trx.selectFrom("operator_item").selectAll().where("kind", "in", ["post_blocked", ...BLOCK_ITEM_KINDS]).where("block_id", "=", block.id).where("cleared_at", "is", null).execute();
11367
+ if (ctx.actor !== "system" && (outcome === "done" || outcome === "reason") && items.some((item) => item.kind === "course_check")) await forwardCourseNote(trx, task, block, ctx, outcome === "reason" ? outcomeReason : null);
11165
11368
  for (const item of items) if (item.kind === "post_blocked") await clearItem(trx, item.id, new Date(ctx.at), ctx.actor);
11166
11369
  else if (ctx.actor !== "system" && outcome !== "archived" && isItemKind(item.kind) && ITEM_POLICY[item.kind].reconciled) await dismissItem(trx, item, ctx.actor, new Date(ctx.at));
11167
11370
  else await clearItem(trx, item.id, new Date(ctx.at), ctx.actor);
@@ -11204,21 +11407,14 @@ async function editInboundComment(trx, input) {
11204
11407
  const task = await taskById$1(trx, input.comment.task_id);
11205
11408
  active(task);
11206
11409
  if (input.comment.author !== input.actor) throw new CommandError("forbidden", "Only the comment author can edit it.");
11207
- const next = editComment(input.comment.revision, input.comment.acked_revision);
11208
- const updated = await trx.updateTable("comment").set({
11209
- text: input.text,
11210
- revision: next.revision
11211
- }).where("id", "=", input.comment.id).returningAll().executeTakeFirstOrThrow();
11212
- await journal$1(trx, task, {
11410
+ const ctx = {
11213
11411
  actor: input.actor,
11214
11412
  at: input.at
11215
- }, "comment_edited", {
11216
- comment: commentId(input.comment.id),
11217
- revision: next.revision,
11218
- clarification: next.clarification
11219
- });
11413
+ };
11414
+ const { updated, clarification } = await reviseComment(trx, task, input.comment, input.text, ctx);
11415
+ for (const copy of await forwardedCopies(trx, input.comment.id)) await reviseComment(trx, task, copy, input.text, ctx);
11220
11416
  const answered = await trx.selectFrom("notification").select("id").where("kind", "=", "answer").where("comment_id", "=", updated.id).executeTakeFirst();
11221
- if (next.clarification && updated.block_id !== null && answered !== void 0) {
11417
+ if (clarification && updated.block_id !== null && answered !== void 0) {
11222
11418
  const block = await trx.selectFrom("block").selectAll().where("id", "=", updated.block_id).executeTakeFirstOrThrow();
11223
11419
  await applyDoorbellPolicy(trx, {
11224
11420
  kind: "answer",
@@ -13105,17 +13301,17 @@ const NO_TURN = {
13105
13301
  open: false,
13106
13302
  operatorUntaken: false
13107
13303
  };
13108
- const indexOf$1 = (column) => COLUMN_IDS.indexOf(column);
13304
+ const indexOf$2 = (column) => COLUMN_IDS.indexOf(column);
13109
13305
  function orchestratorOf(project, column) {
13110
13306
  return project.columns.find((c) => c.id === column)?.orchestrator ?? "none";
13111
13307
  }
13112
13308
  /** The next enabled column of the project right of `column`, if any. */
13113
13309
  function nextColumn(project, column) {
13114
- return project.columns.find((c) => c.enabled && indexOf$1(c.id) > indexOf$1(column))?.id;
13310
+ return project.columns.find((c) => c.enabled && indexOf$2(c.id) > indexOf$2(column))?.id;
13115
13311
  }
13116
13312
  /** A left move to `to` voids the submits of `to` and right of it; marks stay. */
13117
13313
  function dropSubmits(marks, to) {
13118
- return marks.filter((mark) => mark.kind === "mark" || indexOf$1(mark.column) < indexOf$1(to));
13314
+ return marks.filter((mark) => mark.kind === "mark" || indexOf$2(mark.column) < indexOf$2(to));
13119
13315
  }
13120
13316
  /** Whether work on the task started: it has an open PR, or a live worker and no reopen. */
13121
13317
  function workStarted(input) {
@@ -13124,9 +13320,9 @@ function workStarted(input) {
13124
13320
  }
13125
13321
  /**
13126
13322
  * What holds the dispatcher on the task now: a blind GitHub stops it, a blind Spur defers a
13127
- * worker's turn, an active cycle-limit item stops every turn and move right, and To Do and Ready
13128
- * for Dev wait for the work to start. The last is judged at the task's column, while `dispatch`
13129
- * judges it at each column the cascade reaches.
13323
+ * worker's turn, an active cycle-limit or course-check item stops every turn and move right, and
13324
+ * To Do and Ready for Dev wait for the work to start. The last is judged at the task's column,
13325
+ * while `dispatch` judges it at each column the cascade reaches.
13130
13326
  */
13131
13327
  function dispatchHolds(input) {
13132
13328
  const holds = [];
@@ -13158,7 +13354,7 @@ function dispatch(input) {
13158
13354
  reason,
13159
13355
  ...gate === void 0 ? {} : { gate }
13160
13356
  });
13161
- if (indexOf$1(to) < indexOf$1(column)) facts = {
13357
+ if (indexOf$2(to) < indexOf$2(column)) facts = {
13162
13358
  ...facts,
13163
13359
  marks: dropSubmits(facts.marks, to)
13164
13360
  };
@@ -13266,6 +13462,173 @@ function turnReason(turn, rerouted) {
13266
13462
  return `${turn.column}: ${turn.reasons.join(", ")}`;
13267
13463
  }
13268
13464
  //#endregion
13465
+ //#region ../core/src/app/course-check.ts
13466
+ /** The longest text of one open finding in the course check's question. */
13467
+ const MAX_FINDING = 300;
13468
+ const cycleKeyPrefix = (taskId) => `cycle-limit:${String(taskId)}:`;
13469
+ const courseKeyPrefix = (taskId) => `course-check:${String(taskId)}:`;
13470
+ /** A reopened ticket or a mode switch moves a task left without counting a return. */
13471
+ const uncounted = (reason) => reason === "ticket_reopened" || reason === "mode_changed";
13472
+ const indexOf$1 = (column) => COLUMN_IDS.indexOf(column);
13473
+ const isColumn = (text) => COLUMN_IDS.includes(text);
13474
+ /** A left move as a return with its causes, or null when it is no counted return. */
13475
+ function counted$1(move, blocked) {
13476
+ if (indexOf$1(move.to) >= indexOf$1(move.from) || uncounted(move.reason)) return null;
13477
+ const [first, ...rest] = returnCauses(move.gate ?? [], blocked);
13478
+ return first === void 0 ? null : {
13479
+ kind: "return",
13480
+ column: move.from,
13481
+ causes: [first, ...rest]
13482
+ };
13483
+ }
13484
+ /**
13485
+ * The counted returns from `column`: `cycle` since the last close of its cycle-limit item, and
13486
+ * `course` since the last close of its course-check item.
13487
+ */
13488
+ async function returnCounts(trx, taskId, column) {
13489
+ const prefixes = {
13490
+ cycle: cycleKeyPrefix(taskId),
13491
+ course: courseKeyPrefix(taskId)
13492
+ };
13493
+ const items = await trx.selectFrom("operator_item").select(["id", "item_key"]).where((eb) => eb.or([eb("item_key", "like", `${prefixes.cycle}%`), eb("item_key", "like", `${prefixes.course}%`)])).execute();
13494
+ const resetOf = new Map(items.map((item) => {
13495
+ const count = item.item_key.startsWith(prefixes.cycle) ? "cycle" : "course";
13496
+ return [`I${String(item.id)}`, {
13497
+ count,
13498
+ column: item.item_key.slice(prefixes[count].length)
13499
+ }];
13500
+ }));
13501
+ const rows = await trx.selectFrom("event").select(["kind", "payload"]).where("task_id", "=", taskId).where("kind", "in", ["task_moved", "from_you_cleared"]).orderBy("id").execute();
13502
+ const events = {
13503
+ cycle: [],
13504
+ course: []
13505
+ };
13506
+ for (const row of rows) {
13507
+ if (row.kind === "from_you_cleared") {
13508
+ const cleared = eventPayloadSchemas.from_you_cleared.safeParse(JSON.parse(row.payload));
13509
+ const reset = cleared.success ? resetOf.get(cleared.data.item) : void 0;
13510
+ if (reset !== void 0 && isColumn(reset.column)) events[reset.count].push({
13511
+ kind: "limit_reset",
13512
+ column: reset.column
13513
+ });
13514
+ continue;
13515
+ }
13516
+ const moved = eventPayloadSchemas.task_moved.safeParse(JSON.parse(row.payload));
13517
+ const event = moved.success ? counted$1(moved.data, moved.data.block !== void 0) : null;
13518
+ if (event === null) continue;
13519
+ events.cycle.push(event);
13520
+ events.course.push(event);
13521
+ }
13522
+ return {
13523
+ cycle: countCycles(events.cycle, column, Infinity).count,
13524
+ course: countCycles(events.course, column, Infinity).count
13525
+ };
13526
+ }
13527
+ /**
13528
+ * Raises the course check of a task's column, once while it is open: a `system` question to the
13529
+ * curator, or to the operator when the project has no curator, with the open findings in its
13530
+ * reason. The answer to the block resets the course count.
13531
+ */
13532
+ async function raiseCourseCheck(trx, input) {
13533
+ const { task, column, count, at, config } = input;
13534
+ const itemKey = `${courseKeyPrefix(task.id)}${column}`;
13535
+ const active = await trx.selectFrom("operator_item").selectAll().where("item_key", "=", itemKey).where("cleared_at", "is", null).executeTakeFirst();
13536
+ if (active !== void 0) return active;
13537
+ const url = taskUrl(task, config);
13538
+ const block = await openSystemBlock(trx, {
13539
+ task,
13540
+ reason: await courseSummary(trx, task, column, count, url),
13541
+ at: at.toISOString(),
13542
+ config,
13543
+ addressee: curatorProject(config, task.project) === null ? "operator" : "curator"
13544
+ });
13545
+ return raiseItem(trx, {
13546
+ itemKey,
13547
+ kind: "course_check",
13548
+ text: `${task.key}: course check after ${String(count)} returns from ${column}`,
13549
+ url,
13550
+ taskId: task.id,
13551
+ blockId: block.id,
13552
+ at
13553
+ });
13554
+ }
13555
+ /** The question of a course check: the count, the open findings and the links. */
13556
+ async function courseSummary(trx, task, column, count, url) {
13557
+ const pr = await prFacts(trx, task.id);
13558
+ const current = pr?.headSha.toLowerCase();
13559
+ const short = (sha) => sha.toLowerCase() === current ? `${sha.slice(0, 7)} (current head)` : sha.slice(0, 7);
13560
+ const findings = await openFindings(trx, task.id);
13561
+ const lines = [
13562
+ `course check: ${String(count)} returns to Dev from ${column} since the last check`,
13563
+ findings.length === 0 ? "Open findings: none on the board" : "Open findings:",
13564
+ ...findings.map((finding) => `- B${String(finding.id)} by ${finding.author.replace(/^agent:/, "")} on ${finding.head === null ? "unknown head" : short(finding.head)}: ${capPoints(finding.text, MAX_FINDING)}`)
13565
+ ];
13566
+ if (pr !== null) {
13567
+ for (const review of pr.reviews) if (review.state === "changes_requested") lines.push(`- ${review.reviewer} requested changes on ${short(review.commitSha)}`);
13568
+ lines.push(`Unresolved review threads: ${String(pr.reviewThreads.filter((t) => !t.resolved).length)}`);
13569
+ lines.push(`PR: ${pr.url}`);
13570
+ }
13571
+ lines.push(`Issue: ${url}`);
13572
+ return lines.join("\n");
13573
+ }
13574
+ /** The task's active PR facts, or null without a readable snapshot. */
13575
+ async function prFacts(trx, taskId) {
13576
+ const link = await taskPr(trx, taskId);
13577
+ if (link === null) return null;
13578
+ return parsePr((await trx.selectFrom("pr_snapshot").select("detail").where(sql`lower(repo) = ${link.repo.toLowerCase()}`).where("number", "=", link.number).executeTakeFirst())?.detail);
13579
+ }
13580
+ /**
13581
+ * The task's open `code` blocks, oldest first, each with the head of the turn whose return opened
13582
+ * it, or null when no return names it.
13583
+ */
13584
+ async function openFindings(trx, taskId) {
13585
+ const blocks = await trx.selectFrom("block").select([
13586
+ "id",
13587
+ "author",
13588
+ "reason"
13589
+ ]).where("task_id", "=", taskId).where("type", "=", "code").where("state", "=", "open").orderBy("id").execute();
13590
+ if (blocks.length === 0) return [];
13591
+ const turnOf = /* @__PURE__ */ new Map();
13592
+ const moves = await trx.selectFrom("event").select("payload").where("task_id", "=", taskId).where("kind", "=", "task_moved").execute();
13593
+ for (const row of moves) {
13594
+ const moved = eventPayloadSchemas.task_moved.safeParse(JSON.parse(row.payload));
13595
+ const { block, turn } = moved.success ? moved.data : {};
13596
+ if (block !== void 0 && turn !== void 0) turnOf.set(block, turn);
13597
+ }
13598
+ const findings = [];
13599
+ for (const block of blocks) {
13600
+ const turn = turnOf.get(`B${String(block.id)}`);
13601
+ const row = turn === void 0 ? void 0 : await trx.selectFrom("turn").select("head_sha").where("id", "=", Number(turn.slice(1))).where("task_id", "=", taskId).executeTakeFirst();
13602
+ findings.push({
13603
+ id: block.id,
13604
+ author: block.author,
13605
+ text: block.reason,
13606
+ head: row?.head_sha ?? null
13607
+ });
13608
+ }
13609
+ return findings;
13610
+ }
13611
+ /**
13612
+ * Whether a shadow move reaches the course check of its column: a counted return whose count of
13613
+ * counted shadow returns from that column, itself included, is a multiple of `courseCheck`.
13614
+ * Shadow mode has no answer, so the count never resets.
13615
+ */
13616
+ async function shadowCourseCheck(trx, taskId, move, project) {
13617
+ const every = project.columns.find((column) => column.id === move.from)?.courseCheck ?? 0;
13618
+ const current = counted$1(move, false);
13619
+ if (every <= 0 || current === null) return false;
13620
+ const rows = await trx.selectFrom("event").select("payload").where("task_id", "=", taskId).where("kind", "=", "task_shadow_moved").orderBy("id").execute();
13621
+ const past = [];
13622
+ for (const row of rows) {
13623
+ const moved = eventPayloadSchemas.task_shadow_moved.safeParse(JSON.parse(row.payload));
13624
+ const event = moved.success ? counted$1(moved.data, false) : null;
13625
+ if (event !== null) past.push(event);
13626
+ }
13627
+ const before = countCycles(past, move.from, every).count;
13628
+ const after = countCycles([...past, current], move.from, every).count;
13629
+ return after > before && after % every === 0;
13630
+ }
13631
+ //#endregion
13269
13632
  //#region ../core/src/domain/health.ts
13270
13633
  const ENDED_WORKER_KINDS = {
13271
13634
  complete: "worker_completed",
@@ -13785,9 +14148,6 @@ const modeSchema = z.enum(DISPATCHER_MODES);
13785
14148
  /** Columns whose submissions are marks: they last for their head across visits. */
13786
14149
  const MARK_COLUMNS = ["review", "product-review"];
13787
14150
  const indexOf = (column) => COLUMN_IDS.indexOf(column);
13788
- const cycleKeyPrefix = (taskId) => `cycle-limit:${String(taskId)}:`;
13789
- /** A reopened ticket or a mode switch moves a task left without counting a return. */
13790
- const uncounted = (reason) => reason === "ticket_reopened" || reason === "mode_changed";
13791
14151
  /**
13792
14152
  * Sets `voided_at` on the unvoided submits of `columns`. Review and product-review marks are
13793
14153
  * never voided.
@@ -13801,40 +14161,11 @@ async function voidColumns(trx, taskId, columns, at) {
13801
14161
  async function voidSubmits(trx, taskId, to, at) {
13802
14162
  await voidColumns(trx, taskId, COLUMN_IDS.filter((column) => indexOf(column) >= indexOf(to)), at);
13803
14163
  }
13804
- /** Whether the returns from `column` since its last limit reset reach the column's limit. */
13805
- async function cycleLimitReached(trx, taskId, column, limit) {
13806
- const prefix = cycleKeyPrefix(taskId);
13807
- const items = await trx.selectFrom("operator_item").select(["id", "item_key"]).where("item_key", "like", `${prefix}%`).execute();
13808
- const itemColumn = new Map(items.map((item) => [`I${String(item.id)}`, item.item_key.slice(prefix.length)]));
13809
- const rows = await trx.selectFrom("event").select(["kind", "payload"]).where("task_id", "=", taskId).where("kind", "in", ["task_moved", "from_you_cleared"]).orderBy("id").execute();
13810
- const events = [];
13811
- for (const row of rows) {
13812
- if (row.kind === "from_you_cleared") {
13813
- const cleared = eventPayloadSchemas.from_you_cleared.safeParse(JSON.parse(row.payload));
13814
- const of = cleared.success ? itemColumn.get(cleared.data.item) : void 0;
13815
- if (of !== void 0 && COLUMN_IDS.includes(of)) events.push({
13816
- kind: "limit_reset",
13817
- column: of
13818
- });
13819
- continue;
13820
- }
13821
- const moved = eventPayloadSchemas.task_moved.safeParse(JSON.parse(row.payload));
13822
- if (!moved.success) continue;
13823
- const { from, to, reason, gate, block } = moved.data;
13824
- if (indexOf(to) >= indexOf(from) || uncounted(reason)) continue;
13825
- const [first, ...rest] = returnCauses(gate ?? [], block !== void 0);
13826
- if (first !== void 0) events.push({
13827
- kind: "return",
13828
- column: from,
13829
- causes: [first, ...rest]
13830
- });
13831
- }
13832
- return countCycles(events, column, limit).limitReached;
13833
- }
13834
14164
  /**
13835
14165
  * Moves a task left to `to` as a new visit: bumps `column_epoch` and `left_moves`, voids the
13836
14166
  * submits of `to` and right of it, closes its turns and journals `task_moved`. In `on` mode a
13837
- * counted return that reaches the column's cycle limit raises its cycle-limit block, and
14167
+ * counted return that reaches the column's cycle limit raises its cycle-limit block; otherwise
14168
+ * one that reaches its course check raises the course check. Either holds the task, and
13838
14169
  * `limitReached` tells the dispatcher to stop the cascade.
13839
14170
  */
13840
14171
  async function moveLeft(trx, input) {
@@ -13860,20 +14191,40 @@ async function moveLeft(trx, input) {
13860
14191
  ...gate === void 0 ? {} : { gate: [...gate] }
13861
14192
  }, actor);
13862
14193
  const project = config.projects.find((entry) => entry.id === task.project);
13863
- const limit = project?.columns.find((column) => column.id === task.column)?.cycleLimit;
13864
- if (project?.dispatcher.mode !== "on" || limit === void 0 || uncounted(reason) || !await cycleLimitReached(trx, task.id, task.column, limit)) return {
14194
+ const column = project?.columns.find((entry) => entry.id === task.column);
14195
+ if (project?.dispatcher.mode !== "on" || column === void 0 || uncounted(reason)) return {
13865
14196
  task: moved,
13866
14197
  limitReached: false
13867
14198
  };
13868
- await raiseCycleLimit(trx, {
13869
- task: moved,
13870
- column: task.column,
13871
- at,
13872
- config
13873
- });
14199
+ const counts = await returnCounts(trx, task.id, task.column);
14200
+ if (counts.cycle >= column.cycleLimit) {
14201
+ await raiseCycleLimit(trx, {
14202
+ task: moved,
14203
+ column: task.column,
14204
+ at,
14205
+ config
14206
+ });
14207
+ return {
14208
+ task: moved,
14209
+ limitReached: true
14210
+ };
14211
+ }
14212
+ if (column.courseCheck > 0 && counts.course >= column.courseCheck) {
14213
+ await raiseCourseCheck(trx, {
14214
+ task: moved,
14215
+ column: task.column,
14216
+ count: counts.course,
14217
+ at,
14218
+ config
14219
+ });
14220
+ return {
14221
+ task: moved,
14222
+ limitReached: true
14223
+ };
14224
+ }
13874
14225
  return {
13875
14226
  task: moved,
13876
- limitReached: true
14227
+ limitReached: false
13877
14228
  };
13878
14229
  }
13879
14230
  /**
@@ -13976,15 +14327,6 @@ async function blindSources(trx, complete) {
13976
14327
  const blind = new Set(states.filter((state) => state.blind_reason !== null).map((state) => state.source));
13977
14328
  return (source) => blind.has(source) || !complete.has(source);
13978
14329
  }
13979
- function parsePr(detail) {
13980
- if (detail === void 0) return null;
13981
- try {
13982
- const parsed = prFactsSchema.safeParse(JSON.parse(detail));
13983
- return parsed.success ? parsed.data : null;
13984
- } catch {
13985
- return null;
13986
- }
13987
- }
13988
14330
  /** Whether the external reviewers approved: one approval, and no changes requested by one. */
13989
14331
  function externalApproval(pr, agentLogin) {
13990
14332
  const external = (login) => login.toLowerCase() !== agentLogin.toLowerCase() && !(pr.feedback ?? []).some((entry) => entry.author?.type === "bot" && entry.author.login.toLowerCase() === login.toLowerCase());
@@ -14119,7 +14461,7 @@ async function readInput(trx, task, project, mode, blind) {
14119
14461
  const column = mode === "shadow" ? task.shadow_column ?? task.column : task.column;
14120
14462
  const last = mode === "shadow" ? void 0 : await trx.selectFrom("turn").selectAll().where("task_id", "=", task.id).where("column", "=", task.column).where("epoch", "=", task.column_epoch).orderBy("seq", "desc").executeTakeFirst();
14121
14463
  const unclosed = last?.closed_at === null ? last : void 0;
14122
- const held = mode === "on" && await trx.selectFrom("operator_item").select("id").where("item_key", "like", `${cycleKeyPrefix(task.id)}%`).where("cleared_at", "is", null).executeTakeFirst() !== void 0;
14464
+ const held = mode === "on" && await trx.selectFrom("operator_item").select("id").where((eb) => eb.or([eb("item_key", "like", `${cycleKeyPrefix(task.id)}%`), eb("item_key", "like", `${courseKeyPrefix(task.id)}%`)])).where("cleared_at", "is", null).executeTakeFirst() !== void 0;
14123
14465
  return {
14124
14466
  input: {
14125
14467
  column,
@@ -14150,16 +14492,18 @@ async function readInput(trx, task, project, mode, blind) {
14150
14492
  unclosed
14151
14493
  };
14152
14494
  }
14153
- async function applyShadow(trx, task, result, at) {
14495
+ async function applyShadow(trx, task, project, result, at) {
14154
14496
  const last = result.moves.at(-1);
14155
14497
  if (last === void 0) return;
14156
14498
  for (const move of result.moves) {
14157
14499
  if (indexOf(move.to) < indexOf(move.from)) await voidSubmits(trx, task.id, move.to, at);
14500
+ const courseCheck = await shadowCourseCheck(trx, task.id, move, project);
14158
14501
  await emit(trx, "task_shadow_moved", task.project, task.id, at.toISOString(), {
14159
14502
  from: move.from,
14160
14503
  to: move.to,
14161
14504
  reason: move.reason,
14162
- ...move.gate === void 0 ? {} : { gate: [...move.gate] }
14505
+ ...move.gate === void 0 ? {} : { gate: [...move.gate] },
14506
+ ...courseCheck ? { courseCheck } : {}
14163
14507
  });
14164
14508
  }
14165
14509
  await trx.updateTable("task").set({ shadow_column: last.to }).where("id", "=", task.id).execute();
@@ -14233,7 +14577,7 @@ async function dispatchTasks(trx, taskIds, ctx) {
14233
14577
  const read = await readInput(trx, task, project, mode, blind);
14234
14578
  if (read === null) continue;
14235
14579
  const result = dispatch(read.input);
14236
- if (mode === "shadow") await applyShadow(trx, task, result, ctx.at);
14580
+ if (mode === "shadow") await applyShadow(trx, task, project, result, ctx.at);
14237
14581
  else await applyOn(trx, task, read, result, ctx);
14238
14582
  }
14239
14583
  }
@@ -14323,6 +14667,16 @@ function linkSummary(kind, payloadText) {
14323
14667
  return null;
14324
14668
  }
14325
14669
  }
14670
+ /** The summary of a shadow move that reached its column's course check. */
14671
+ function shadowSummary(kind, payloadText) {
14672
+ if (kind !== "task_shadow_moved") return null;
14673
+ try {
14674
+ const payload = eventPayloadSchemas[kind].safeParse(JSON.parse(payloadText));
14675
+ return payload.success && payload.data.courseCheck === true ? "Shadow move with a course check" : null;
14676
+ } catch {
14677
+ return null;
14678
+ }
14679
+ }
14326
14680
  function projectTarget(project) {
14327
14681
  return {
14328
14682
  kind: "found",
@@ -14446,7 +14800,7 @@ function createTaskQueries(deps) {
14446
14800
  at: row.at,
14447
14801
  kind,
14448
14802
  actor: eventActor(row),
14449
- summary: linkSummary(kind, row.payload) ?? EVENT_SUMMARIES[kind]
14803
+ summary: linkSummary(kind, row.payload) ?? shadowSummary(kind, row.payload) ?? EVENT_SUMMARIES[kind]
14450
14804
  }];
14451
14805
  });
14452
14806
  return {
@@ -21619,6 +21973,7 @@ function createHttpModule(ctx, options = {}) {
21619
21973
  ...options.runOperation === void 0 ? {} : { runOperation: options.runOperation },
21620
21974
  doctor: options.doctor ?? (() => runDaemonDoctor(ctx, options.productVersion ?? "unknown", options.fetcher)),
21621
21975
  ...options.firstPollDone === void 0 ? {} : { firstPollDone: options.firstPollDone },
21976
+ ...options.productVersion === void 0 ? {} : { productVersion: options.productVersion },
21622
21977
  logRequest: ({ requestId, method, url, status, tokenName }) => {
21623
21978
  const path = new URL(url, "http://127.0.0.1").pathname;
21624
21979
  ctx.log.info({